@rajbos/ai-engineering-fluency 0.4.0 → 0.5.0
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/dist/cli.js +105 -93
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,87 +1,102 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Rm=Object.create;var bl=Object.defineProperty;var Im=Object.getOwnPropertyDescriptor;var Um=Object.getOwnPropertyNames;var Om=Object.getPrototypeOf,Fm=Object.prototype.hasOwnProperty;var Te=(o,e)=>()=>{try{return e||o((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var Nm=(o,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Um(e))!Fm.call(o,n)&&n!==t&&bl(o,n,{get:()=>e[n],enumerable:!(s=Im(e,n))||s.enumerable});return o};var w=(o,e,t)=>(t=o!=null?Rm(Om(o)):{},Nm(e||!o||!o.__esModule?bl(t,"default",{value:o,enumerable:!0}):t,o));var is=Te((Uo,os)=>{var Ro=void 0,Io=function(o){return Ro||(Ro=new Promise(function(e,t){var s=typeof o<"u"?o:{},n=s.onAbort;s.onAbort=function(l){t(new Error(l)),n&&n(l)},s.postRun=s.postRun||[],s.postRun.push(function(){e(s)}),os=void 0;var i;i||=typeof s<"u"?s:{};var r=!!globalThis.window,a=!!globalThis.WorkerGlobalScope,c=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";i.onRuntimeInitialized=function(){function l(b,v){switch(typeof v){case"boolean":Dm(b,v?1:0);break;case"number":vm(b,v);break;case"string":Am(b,v,-1,-1);break;case"object":if(v===null)hl(b);else if(v.length!=null){var I=go(v.length);x.set(v,I),xm(b,I,v.length,-1),Xs(I)}else _o(b,"Wrong API use : tried to return a value of an unknown type ("+v+").",-1);break;default:hl(b)}}function u(b,v){for(var I=[],O=0;O<b;O+=1){var H=Xe(v+4*O,"i32"),ie=Sm(H);if(ie===1||ie===2)H=Pm(H);else if(ie===3)H=Tm(H);else if(ie===4){ie=H,H=wm(ie),ie=Mm(ie);for(var Ze=new Uint8Array(H),ze=0;ze<H;ze+=1)Ze[ze]=x[ie+ze];H=Ze}else H=null;I.push(H)}return I}function d(b,v){this.Qa=b,this.db=v,this.Oa=1,this.mb=[]}function g(b,v){if(this.db=v,this.fb=po(b),this.fb===null)throw Error("Unable to allocate memory for the SQL string");this.lb=this.fb,this.$a=this.sb=null}function y(b){if(this.filename="dbfile_"+(4294967295*Math.random()>>>0),b!=null){var v=this.filename,I="/",O=v;if(I&&(I=typeof I=="string"?I:tr(I),O=v?Qt(I+"/"+v):I),v=za(!0,!0),O=Yd(O,v),b){if(typeof b=="string"){I=Array(b.length);for(var H=0,ie=b.length;H<ie;++H)I[H]=b.charCodeAt(H);b=I}lo(O,v|146),I=Ss(O,577),ol(I,b,0,b.length,0),ar(I),lo(O,v)}}this.handleError(j(this.filename,k)),this.db=Xe(k,"i32"),_l(this.db),this.gb={},this.Sa={}}var k=es(4),M=i.cwrap,j=M("sqlite3_open","number",["string","number"]),oe=M("sqlite3_close_v2","number",["number"]),z=M("sqlite3_exec","number",["number","string","number","number","number"]),pe=M("sqlite3_changes","number",["number"]),Pe=M("sqlite3_prepare_v2","number",["number","string","number","number","number"]),dl=M("sqlite3_sql","string",["number"]),im=M("sqlite3_normalized_sql","string",["number"]),ml=M("sqlite3_prepare_v2","number",["number","number","number","number","number"]),rm=M("sqlite3_bind_text","number",["number","number","number","number","number"]),pl=M("sqlite3_bind_blob","number",["number","number","number","number","number"]),am=M("sqlite3_bind_double","number",["number","number","number"]),lm=M("sqlite3_bind_int","number",["number","number","number"]),cm=M("sqlite3_bind_parameter_index","number",["number","string"]),um=M("sqlite3_step","number",["number"]),dm=M("sqlite3_errmsg","string",["number"]),mm=M("sqlite3_column_count","number",["number"]),pm=M("sqlite3_data_count","number",["number"]),gm=M("sqlite3_column_double","number",["number","number"]),gl=M("sqlite3_column_text","string",["number","number"]),fm=M("sqlite3_column_blob","number",["number","number"]),hm=M("sqlite3_column_bytes","number",["number","number"]),ym=M("sqlite3_column_type","number",["number","number"]),_m=M("sqlite3_column_name","string",["number","number"]),Cm=M("sqlite3_reset","number",["number"]),bm=M("sqlite3_clear_bindings","number",["number"]),km=M("sqlite3_finalize","number",["number"]),fl=M("sqlite3_create_function_v2","number","number string number number number number number number number".split(" ")),Sm=M("sqlite3_value_type","number",["number"]),wm=M("sqlite3_value_bytes","number",["number"]),Tm=M("sqlite3_value_text","string",["number"]),Mm=M("sqlite3_value_blob","number",["number"]),Pm=M("sqlite3_value_double","number",["number"]),vm=M("sqlite3_result_double","",["number","number"]),hl=M("sqlite3_result_null","",["number"]),Am=M("sqlite3_result_text","",["number","string","number","number"]),xm=M("sqlite3_result_blob","",["number","number","number","number"]),Dm=M("sqlite3_result_int","",["number","number"]),_o=M("sqlite3_result_error","",["number","string","number"]),yl=M("sqlite3_aggregate_context","number",["number","number"]),_l=M("RegisterExtensionFunctions","number",["number"]),Cl=M("sqlite3_update_hook","number",["number","number","number"]);d.prototype.bind=function(b){if(!this.Qa)throw"Statement closed";return this.reset(),Array.isArray(b)?this.Gb(b):b!=null&&typeof b=="object"?this.Hb(b):!0},d.prototype.step=function(){if(!this.Qa)throw"Statement closed";this.Oa=1;var b=um(this.Qa);switch(b){case 100:return!0;case 101:return!1;default:throw this.db.handleError(b)}},d.prototype.Ab=function(b){return b==null&&(b=this.Oa,this.Oa+=1),gm(this.Qa,b)},d.prototype.Ob=function(b){if(b==null&&(b=this.Oa,this.Oa+=1),b=gl(this.Qa,b),typeof BigInt!="function")throw Error("BigInt is not supported");return BigInt(b)},d.prototype.Tb=function(b){return b==null&&(b=this.Oa,this.Oa+=1),gl(this.Qa,b)},d.prototype.getBlob=function(b){b==null&&(b=this.Oa,this.Oa+=1);var v=hm(this.Qa,b);b=fm(this.Qa,b);for(var I=new Uint8Array(v),O=0;O<v;O+=1)I[O]=x[b+O];return I},d.prototype.get=function(b,v){v=v||{},b!=null&&this.bind(b)&&this.step(),b=[];for(var I=pm(this.Qa),O=0;O<I;O+=1)switch(ym(this.Qa,O)){case 1:var H=v.useBigInt?this.Ob(O):this.Ab(O);b.push(H);break;case 2:b.push(this.Ab(O));break;case 3:b.push(this.Tb(O));break;case 4:b.push(this.getBlob(O));break;default:b.push(null)}return b},d.prototype.qb=function(){for(var b=[],v=mm(this.Qa),I=0;I<v;I+=1)b.push(_m(this.Qa,I));return b},d.prototype.zb=function(b,v){b=this.get(b,v),v=this.qb();for(var I={},O=0;O<v.length;O+=1)I[v[O]]=b[O];return I},d.prototype.Sb=function(){return dl(this.Qa)},d.prototype.Pb=function(){return im(this.Qa)},d.prototype.run=function(b){return b!=null&&this.bind(b),this.step(),this.reset()},d.prototype.wb=function(b,v){v==null&&(v=this.Oa,this.Oa+=1),b=po(b),this.mb.push(b),this.db.handleError(rm(this.Qa,v,b,-1,0))},d.prototype.Fb=function(b,v){v==null&&(v=this.Oa,this.Oa+=1);var I=go(b.length);x.set(b,I),this.mb.push(I),this.db.handleError(pl(this.Qa,v,I,b.length,0))},d.prototype.vb=function(b,v){v==null&&(v=this.Oa,this.Oa+=1),this.db.handleError((b===(b|0)?lm:am)(this.Qa,v,b))},d.prototype.Ib=function(b){b==null&&(b=this.Oa,this.Oa+=1),pl(this.Qa,b,0,0,0)},d.prototype.xb=function(b,v){switch(v==null&&(v=this.Oa,this.Oa+=1),typeof b){case"string":this.wb(b,v);return;case"number":this.vb(b,v);return;case"bigint":this.wb(b.toString(),v);return;case"boolean":this.vb(b+0,v);return;case"object":if(b===null){this.Ib(v);return}if(b.length!=null){this.Fb(b,v);return}}throw"Wrong API use : tried to bind a value of an unknown type ("+b+")."},d.prototype.Hb=function(b){var v=this;return Object.keys(b).forEach(function(I){var O=cm(v.Qa,I);O!==0&&v.xb(b[I],O)}),!0},d.prototype.Gb=function(b){for(var v=0;v<b.length;v+=1)this.xb(b[v],v+1);return!0},d.prototype.reset=function(){return this.freemem(),bm(this.Qa)===0&&Cm(this.Qa)===0},d.prototype.freemem=function(){for(var b;(b=this.mb.pop())!==void 0;)Xs(b)},d.prototype.Ya=function(){this.freemem();var b=km(this.Qa)===0;return delete this.db.gb[this.Qa],this.Qa=0,b},g.prototype.next=function(){if(this.fb===null)return{done:!0};if(this.$a!==null&&(this.$a.Ya(),this.$a=null),!this.db.db)throw this.ob(),Error("Database closed");var b=ho(),v=es(4);V(k),V(v);try{this.db.handleError(ml(this.db.db,this.lb,-1,k,v)),this.lb=Xe(v,"i32");var I=Xe(k,"i32");return I===0?(this.ob(),{done:!0}):(this.$a=new d(I,this.db),this.db.gb[I]=this.$a,{value:this.$a,done:!1})}catch(O){throw this.sb=ae(this.lb),this.ob(),O}finally{fo(b)}},g.prototype.ob=function(){Xs(this.fb),this.fb=null},g.prototype.Qb=function(){return this.sb!==null?this.sb:ae(this.lb)},typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"&&(g.prototype[Symbol.iterator]=function(){return this}),y.prototype.run=function(b,v){if(!this.db)throw"Database closed";if(v){b=this.tb(b,v);try{b.step()}finally{b.Ya()}}else this.handleError(z(this.db,b,0,0,k));return this},y.prototype.exec=function(b,v,I){if(!this.db)throw"Database closed";var O=null,H=null,ie=null;try{ie=H=po(b);var Ze=es(4);for(b=[];Xe(ie,"i8")!==0;){V(k),V(Ze),this.handleError(ml(this.db,ie,-1,k,Ze));var ze=Xe(k,"i32");if(ie=Xe(Ze,"i32"),ze!==0){var Ne=null;for(O=new d(ze,this),v!=null&&O.bind(v);O.step();)Ne===null&&(Ne={columns:O.qb(),values:[]},b.push(Ne)),Ne.values.push(O.get(null,I));O.Ya()}}return b}catch(et){throw O&&O.Ya(),et}finally{H&&Xs(H)}},y.prototype.Mb=function(b,v,I,O,H){typeof v=="function"&&(O=I,I=v,v=void 0),b=this.tb(b,v);try{for(;b.step();)I(b.zb(null,H))}finally{b.Ya()}if(typeof O=="function")return O()},y.prototype.tb=function(b,v){if(V(k),this.handleError(Pe(this.db,b,-1,k,0)),b=Xe(k,"i32"),b===0)throw"Nothing to prepare";var I=new d(b,this);return v!=null&&I.bind(v),this.gb[b]=I},y.prototype.Ub=function(b){return new g(b,this)},y.prototype.Nb=function(){Object.values(this.gb).forEach(function(v){v.Ya()}),Object.values(this.Sa).forEach(Ut),this.Sa={},this.handleError(oe(this.db));var b=Xd(this.filename);return this.handleError(j(this.filename,k)),this.db=Xe(k,"i32"),_l(this.db),b},y.prototype.close=function(){this.db!==null&&(Object.values(this.gb).forEach(function(b){b.Ya()}),Object.values(this.Sa).forEach(Ut),this.Sa={},this.Za&&(Ut(this.Za),this.Za=void 0),this.handleError(oe(this.db)),Za("/"+this.filename),this.db=null)},y.prototype.handleError=function(b){if(b===0)return null;throw b=dm(this.db),Error(b)},y.prototype.Rb=function(){return pe(this.db)},y.prototype.Kb=function(b,v){Object.prototype.hasOwnProperty.call(this.Sa,b)&&(Ut(this.Sa[b]),delete this.Sa[b]);var I=Ys(function(O,H,ie){H=u(H,ie);try{var Ze=v.apply(null,H)}catch(ze){_o(O,ze,-1);return}l(O,Ze)},"viii");return this.Sa[b]=I,this.handleError(fl(this.db,b,v.length,1,0,I,0,0,0)),this},y.prototype.Jb=function(b,v){var I=v.init||function(){return null},O=v.finalize||function(Ne){return Ne},H=v.step;if(!H)throw"An aggregate function must have a step function in "+b;var ie={};Object.hasOwnProperty.call(this.Sa,b)&&(Ut(this.Sa[b]),delete this.Sa[b]),v=b+"__finalize",Object.hasOwnProperty.call(this.Sa,v)&&(Ut(this.Sa[v]),delete this.Sa[v]);var Ze=Ys(function(Ne,et,gr){var ts=yl(Ne,1);Object.hasOwnProperty.call(ie,ts)||(ie[ts]=I()),et=u(et,gr),et=[ie[ts]].concat(et);try{ie[ts]=H.apply(null,et)}catch(Em){delete ie[ts],_o(Ne,Em,-1)}},"viii"),ze=Ys(function(Ne){var et=yl(Ne,1);try{var gr=O(ie[et])}catch(ts){delete ie[et],_o(Ne,ts,-1);return}l(Ne,gr),delete ie[et]},"vi");return this.Sa[b]=Ze,this.Sa[v]=ze,this.handleError(fl(this.db,b,H.length-1,1,0,0,Ze,ze,0)),this},y.prototype.Zb=function(b){return this.Za&&(Cl(this.db,0,0),Ut(this.Za),this.Za=void 0),b?(this.Za=Ys(function(v,I,O,H,ie){switch(I){case 18:v="insert";break;case 23:v="update";break;case 9:v="delete";break;default:throw"unknown operationCode in updateHook callback: "+I}if(O=ae(O),H=ae(H),ie>Number.MAX_SAFE_INTEGER)throw"rowId too big to fit inside a Number";b(v,O,H,Number(ie))},"viiiij"),Cl(this.db,this.Za,0),this):this},d.prototype.bind=d.prototype.bind,d.prototype.step=d.prototype.step,d.prototype.get=d.prototype.get,d.prototype.getColumnNames=d.prototype.qb,d.prototype.getAsObject=d.prototype.zb,d.prototype.getSQL=d.prototype.Sb,d.prototype.getNormalizedSQL=d.prototype.Pb,d.prototype.run=d.prototype.run,d.prototype.reset=d.prototype.reset,d.prototype.freemem=d.prototype.freemem,d.prototype.free=d.prototype.Ya,g.prototype.next=g.prototype.next,g.prototype.getRemainingSQL=g.prototype.Qb,y.prototype.run=y.prototype.run,y.prototype.exec=y.prototype.exec,y.prototype.each=y.prototype.Mb,y.prototype.prepare=y.prototype.tb,y.prototype.iterateStatements=y.prototype.Ub,y.prototype.export=y.prototype.Nb,y.prototype.close=y.prototype.close,y.prototype.handleError=y.prototype.handleError,y.prototype.getRowsModified=y.prototype.Rb,y.prototype.create_function=y.prototype.Kb,y.prototype.create_aggregate=y.prototype.Jb,y.prototype.updateHook=y.prototype.Zb,i.Database=y};var m="./this.program",p=(l,u)=>{throw u},f=globalThis.document?.currentScript?.src;typeof __filename<"u"?f=__filename:a&&(f=self.location.href);var h="",_,C;if(c){var S=require("node:fs");h=__dirname+"/",C=l=>(l=P(l)?new URL(l):l,S.readFileSync(l)),_=async l=>(l=P(l)?new URL(l):l,S.readFileSync(l,void 0)),1<process.argv.length&&(m=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),typeof os<"u"&&(os.exports=i),p=(l,u)=>{throw process.exitCode=l,u}}else if(r||a){try{h=new URL(".",f).href}catch{}a&&(C=l=>{var u=new XMLHttpRequest;return u.open("GET",l,!1),u.responseType="arraybuffer",u.send(null),new Uint8Array(u.response)}),_=async l=>{if(P(l))return new Promise((d,g)=>{var y=new XMLHttpRequest;y.open("GET",l,!0),y.responseType="arraybuffer",y.onload=()=>{y.status==200||y.status==0&&y.response?d(y.response):g(y.status)},y.onerror=g,y.send(null)});var u=await fetch(l,{credentials:"same-origin"});if(u.ok)return u.arrayBuffer();throw Error(u.status+" : "+u.url)}}var E=console.log.bind(console),A=console.error.bind(console),R,q=!1,F,P=l=>l.startsWith("file://"),x,N,re,ne,se,Ws,hs,Oe;function Hs(){var l=yo.buffer;x=new Int8Array(l),re=new Int16Array(l),N=new Uint8Array(l),new Uint16Array(l),ne=new Int32Array(l),se=new Uint32Array(l),Ws=new Float32Array(l),hs=new Float64Array(l),Oe=new BigInt64Array(l),new BigUint64Array(l)}function Et(l){throw i.onAbort?.(l),l="Aborted("+l+")",A(l),q=!0,new WebAssembly.RuntimeError(l+". Build with -sASSERTIONS for more info.")}var Ct;async function to(l){if(!R)try{var u=await _(l);return new Uint8Array(u)}catch{}if(l==Ct&&R)l=new Uint8Array(R);else if(C)l=C(l);else throw"both async and sync fetching of the wasm failed";return l}async function so(l,u){try{var d=await to(l);return await WebAssembly.instantiate(d,u)}catch(g){A(`failed to asynchronously prepare wasm: ${g}`),Et(g)}}async function Yi(l){var u=Ct;if(!R&&!P(u)&&!c)try{var d=fetch(u,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(d,l)}catch(g){A(`wasm streaming compile failed: ${g}`),A("falling back to ArrayBuffer instantiation")}return so(u,l)}class Kt{name="ExitStatus";constructor(u){this.message=`Program terminated with exit(${u})`,this.status=u}}var ys=l=>{for(;0<l.length;)l.shift()(i)},Xi=[],no=[],Js=()=>{var l=i.preRun.shift();no.push(l)},Ye=0,_s=null;function Xe(l,u="i8"){switch(u.endsWith("*")&&(u="*"),u){case"i1":return x[l];case"i8":return x[l];case"i16":return re[l>>1];case"i32":return ne[l>>2];case"i64":return Oe[l>>3];case"float":return Ws[l>>2];case"double":return hs[l>>3];case"*":return se[l>>2];default:Et(`invalid type for getValue: ${u}`)}}var U=!0;function V(l){var u="i32";switch(u.endsWith("*")&&(u="*"),u){case"i1":x[l]=0;break;case"i8":x[l]=0;break;case"i16":re[l>>1]=0;break;case"i32":ne[l>>2]=0;break;case"i64":Oe[l>>3]=BigInt(0);break;case"float":Ws[l>>2]=0;break;case"double":hs[l>>3]=0;break;case"*":se[l>>2]=0;break;default:Et(`invalid type for setValue: ${u}`)}}var _e=new TextDecoder,be=(l,u,d,g)=>{if(d=u+d,g)return d;for(;l[u]&&!(u>=d);)++u;return u},ae=(l,u,d)=>l?_e.decode(N.subarray(l,be(N,l,u,d))):"",ut=(l,u)=>{for(var d=0,g=l.length-1;0<=g;g--){var y=l[g];y==="."?l.splice(g,1):y===".."?(l.splice(g,1),d++):d&&(l.splice(g,1),d--)}if(u)for(;d;d--)l.unshift("..");return l},Qt=l=>{var u=l.charAt(0)==="/",d=l.slice(-1)==="/";return(l=ut(l.split("/").filter(g=>!!g),!u).join("/"))||u||(l="."),l&&d&&(l+="/"),(u?"/":"")+l},dt=l=>{var u=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(l).slice(1);return l=u[0],u=u[1],!l&&!u?".":(u&&=u.slice(0,-1),l+u)},Fe=l=>l&&l.match(/([^\/]+|\/)\/*$/)[1],oo=()=>{if(c){var l=require("node:crypto");return u=>l.randomFillSync(u)}return u=>crypto.getRandomValues(u)},Ga=l=>{(Ga=oo())(l)},Bd=(...l)=>{for(var u="",d=!1,g=l.length-1;-1<=g&&!d;g--){if(d=0<=g?l[g]:"/",typeof d!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!d)return"";u=d+"/"+u,d=d.charAt(0)==="/"}return u=ut(u.split("/").filter(y=>!!y),!d).join("/"),(d?"/":"")+u||"."},Vs=l=>{var u=be(l,0);return _e.decode(l.buffer?l.subarray(0,u):new Uint8Array(l.slice(0,u)))},Zi=[],Cs=l=>{for(var u=0,d=0;d<l.length;++d){var g=l.charCodeAt(d);127>=g?u++:2047>=g?u+=2:55296<=g&&57343>=g?(u+=4,++d):u+=3}return u},mt=(l,u,d,g)=>{if(!(0<g))return 0;var y=d;g=d+g-1;for(var k=0;k<l.length;++k){var M=l.codePointAt(k);if(127>=M){if(d>=g)break;u[d++]=M}else if(2047>=M){if(d+1>=g)break;u[d++]=192|M>>6,u[d++]=128|M&63}else if(65535>=M){if(d+2>=g)break;u[d++]=224|M>>12,u[d++]=128|M>>6&63,u[d++]=128|M&63}else{if(d+3>=g)break;u[d++]=240|M>>18,u[d++]=128|M>>12&63,u[d++]=128|M>>6&63,u[d++]=128|M&63,k++}}return u[d]=0,d-y},qa=[];function Ba(l,u){qa[l]={input:[],output:[],eb:u},ir(l,zd)}var zd={open(l){var u=qa[l.node.rdev];if(!u)throw new D(43);l.tty=u,l.seekable=!1},close(l){l.tty.eb.fsync(l.tty)},fsync(l){l.tty.eb.fsync(l.tty)},read(l,u,d,g){if(!l.tty||!l.tty.eb.Bb)throw new D(60);for(var y=0,k=0;k<g;k++){try{var M=l.tty.eb.Bb(l.tty)}catch{throw new D(29)}if(M===void 0&&y===0)throw new D(6);if(M==null)break;y++,u[d+k]=M}return y&&(l.node.atime=Date.now()),y},write(l,u,d,g){if(!l.tty||!l.tty.eb.ub)throw new D(60);try{for(var y=0;y<g;y++)l.tty.eb.ub(l.tty,u[d+y])}catch{throw new D(29)}return g&&(l.node.mtime=l.node.ctime=Date.now()),y}},$d={Bb(){e:{if(!Zi.length){var l=null;if(c){var u=Buffer.alloc(256),d=0,g=process.stdin.fd;try{d=S.readSync(g,u,0,256)}catch(y){if(y.toString().includes("EOF"))d=0;else throw y}0<d&&(l=u.slice(0,d).toString("utf-8"))}else globalThis.window?.prompt&&(l=window.prompt("Input: "),l!==null&&(l+=`
|
|
3
|
-
`));if(!l){l=null;break e}u=Array(Cs(l)+1),l=mt(l,u,0,u.length),u.length=l,Zi=u}l=Zi.shift()}return l},ub(l,u){u===null||u===10?(E(Vs(l.output)),l.output=[]):u!=0&&l.output.push(u)},fsync(l){0<l.output?.length&&(E(Vs(l.output)),l.output=[])},hc(){return{bc:25856,dc:5,ac:191,cc:35387,$b:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ic(){return 0},jc(){return[24,80]}},Wd={ub(l,u){u===null||u===10?(A(Vs(l.output)),l.output=[]):u!=0&&l.output.push(u)},fsync(l){0<l.output?.length&&(A(Vs(l.output)),l.output=[])}},G={Wa:null,Xa(){return G.createNode(null,"/",16895,0)},createNode(l,u,d,g){if((d&61440)===24576||(d&61440)===4096)throw new D(63);return G.Wa||(G.Wa={dir:{node:{Ta:G.La.Ta,Ua:G.La.Ua,lookup:G.La.lookup,ib:G.La.ib,rename:G.La.rename,unlink:G.La.unlink,rmdir:G.La.rmdir,readdir:G.La.readdir,symlink:G.La.symlink},stream:{Va:G.Ma.Va}},file:{node:{Ta:G.La.Ta,Ua:G.La.Ua},stream:{Va:G.Ma.Va,read:G.Ma.read,write:G.Ma.write,jb:G.Ma.jb,kb:G.Ma.kb}},link:{node:{Ta:G.La.Ta,Ua:G.La.Ua,readlink:G.La.readlink},stream:{}},yb:{node:{Ta:G.La.Ta,Ua:G.La.Ua},stream:Qd}}),d=Ja(l,u,d,g),Re(d.mode)?(d.La=G.Wa.dir.node,d.Ma=G.Wa.dir.stream,d.Na={}):(d.mode&61440)===32768?(d.La=G.Wa.file.node,d.Ma=G.Wa.file.stream,d.Ra=0,d.Na=null):(d.mode&61440)===40960?(d.La=G.Wa.link.node,d.Ma=G.Wa.link.stream):(d.mode&61440)===8192&&(d.La=G.Wa.yb.node,d.Ma=G.Wa.yb.stream),d.atime=d.mtime=d.ctime=Date.now(),l&&(l.Na[u]=d,l.atime=l.mtime=l.ctime=d.atime),d},fc(l){return l.Na?l.Na.subarray?l.Na.subarray(0,l.Ra):new Uint8Array(l.Na):new Uint8Array(0)},La:{Ta(l){var u={};return u.dev=(l.mode&61440)===8192?l.id:1,u.ino=l.id,u.mode=l.mode,u.nlink=1,u.uid=0,u.gid=0,u.rdev=l.rdev,Re(l.mode)?u.size=4096:(l.mode&61440)===32768?u.size=l.Ra:(l.mode&61440)===40960?u.size=l.link.length:u.size=0,u.atime=new Date(l.atime),u.mtime=new Date(l.mtime),u.ctime=new Date(l.ctime),u.blksize=4096,u.blocks=Math.ceil(u.size/u.blksize),u},Ua(l,u){for(var d of["mode","atime","mtime","ctime"])u[d]!=null&&(l[d]=u[d]);u.size!==void 0&&(u=u.size,l.Ra!=u&&(u==0?(l.Na=null,l.Ra=0):(d=l.Na,l.Na=new Uint8Array(u),d&&l.Na.set(d.subarray(0,Math.min(u,l.Ra))),l.Ra=u)))},lookup(){throw G.nb||(G.nb=new D(44),G.nb.stack="<generic error, no stack>"),G.nb},ib(l,u,d,g){return G.createNode(l,u,d,g)},rename(l,u,d){try{var g=Yt(u,d)}catch{}if(g){if(Re(l.mode))for(var y in g.Na)throw new D(55);nr(g)}delete l.parent.Na[l.name],u.Na[d]=l,l.name=d,u.ctime=u.mtime=l.parent.ctime=l.parent.mtime=Date.now()},unlink(l,u){delete l.Na[u],l.ctime=l.mtime=Date.now()},rmdir(l,u){var d=Yt(l,u),g;for(g in d.Na)throw new D(55);delete l.Na[u],l.ctime=l.mtime=Date.now()},readdir(l){return[".","..",...Object.keys(l.Na)]},symlink(l,u,d){return l=G.createNode(l,u,41471,0),l.link=d,l},readlink(l){if((l.mode&61440)!==40960)throw new D(28);return l.link}},Ma:{read(l,u,d,g,y){var k=l.node.Na;if(y>=l.node.Ra)return 0;if(l=Math.min(l.node.Ra-y,g),8<l&&k.subarray)u.set(k.subarray(y,y+l),d);else for(g=0;g<l;g++)u[d+g]=k[y+g];return l},write(l,u,d,g,y,k){if(u.buffer===x.buffer&&(k=!1),!g)return 0;if(l=l.node,l.mtime=l.ctime=Date.now(),u.subarray&&(!l.Na||l.Na.subarray)){if(k)return l.Na=u.subarray(d,d+g),l.Ra=g;if(l.Ra===0&&y===0)return l.Na=u.slice(d,d+g),l.Ra=g;if(y+g<=l.Ra)return l.Na.set(u.subarray(d,d+g),y),g}k=y+g;var M=l.Na?l.Na.length:0;if(M>=k||(k=Math.max(k,M*(1048576>M?2:1.125)>>>0),M!=0&&(k=Math.max(k,256)),M=l.Na,l.Na=new Uint8Array(k),0<l.Ra&&l.Na.set(M.subarray(0,l.Ra),0)),l.Na.subarray&&u.subarray)l.Na.set(u.subarray(d,d+g),y);else for(k=0;k<g;k++)l.Na[y+k]=u[d+k];return l.Ra=Math.max(l.Ra,y+g),g},Va(l,u,d){if(d===1?u+=l.position:d===2&&(l.node.mode&61440)===32768&&(u+=l.node.Ra),0>u)throw new D(28);return u},jb(l,u,d,g,y){if((l.node.mode&61440)!==32768)throw new D(43);if(l=l.node.Na,y&2||!l||l.buffer!==x.buffer){y=!0,g=65536*Math.ceil(u/65536);var k=cl(65536,g);if(k&&N.fill(0,k,k+g),g=k,!g)throw new D(48);l&&((0<d||d+u<l.length)&&(l.subarray?l=l.subarray(d,d+u):l=Array.prototype.slice.call(l,d,d+u)),x.set(l,g))}else y=!1,g=l.byteOffset;return{Xb:g,Eb:y}},kb(l,u,d,g){return G.Ma.write(l,u,0,g,d,!1),0}}},za=(l,u)=>{var d=0;return l&&(d|=365),u&&(d|=146),d},er=null,$a={},bs=[],Hd=1,Rt=null,Wa=!1,Ha=!0,D=class{name="ErrnoError";constructor(l){this.Pa=l}},Jd=class{hb={};node=null;get flags(){return this.hb.flags}set flags(l){this.hb.flags=l}get position(){return this.hb.position}set position(l){this.hb.position=l}},Vd=class{La={};Ma={};bb=null;constructor(l,u,d,g){l||=this,this.parent=l,this.Xa=l.Xa,this.id=Hd++,this.name=u,this.mode=d,this.rdev=g,this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&365)===365}set read(l){l?this.mode|=365:this.mode&=-366}get write(){return(this.mode&146)===146}set write(l){l?this.mode|=146:this.mode&=-147}};function Be(l,u={}){if(!l)throw new D(44);u.pb??(u.pb=!0),l.charAt(0)==="/"||(l="//"+l);var d=0;e:for(;40>d;d++){l=l.split("/").filter(j=>!!j);for(var g=er,y="/",k=0;k<l.length;k++){var M=k===l.length-1;if(M&&u.parent)break;if(l[k]!==".")if(l[k]==="..")if(y=dt(y),g===g.parent){l=y+"/"+l.slice(k+1).join("/"),d--;continue e}else g=g.parent;else{y=Qt(y+"/"+l[k]);try{g=Yt(g,l[k])}catch(j){if(j?.Pa===44&&M&&u.Wb)return{path:y};throw j}if(!g.bb||M&&!u.pb||(g=g.bb.root),(g.mode&61440)===40960&&(!M||u.ab)){if(!g.La.readlink)throw new D(52);g=g.La.readlink(g),g.charAt(0)==="/"||(g=dt(y)+"/"+g),l=g+"/"+l.slice(k+1).join("/");continue e}}}return{path:y,node:g}}throw new D(32)}function tr(l){for(var u;;){if(l===l.parent)return l=l.Xa.Db,u?l[l.length-1]!=="/"?`${l}/${u}`:l+u:l;u=u?`${l.name}/${u}`:l.name,l=l.parent}}function sr(l,u){for(var d=0,g=0;g<u.length;g++)d=(d<<5)-d+u.charCodeAt(g)|0;return(l+d>>>0)%Rt.length}function nr(l){var u=sr(l.parent.id,l.name);if(Rt[u]===l)Rt[u]=l.cb;else for(u=Rt[u];u;){if(u.cb===l){u.cb=l.cb;break}u=u.cb}}function Yt(l,u){var d=Re(l.mode)?(d=ks(l,"x"))?d:l.La.lookup?0:2:54;if(d)throw new D(d);for(d=Rt[sr(l.id,u)];d;d=d.cb){var g=d.name;if(d.parent.id===l.id&&g===u)return d}return l.La.lookup(l,u)}function Ja(l,u,d,g){return l=new Vd(l,u,d,g),u=sr(l.parent.id,l.name),l.cb=Rt[u],Rt[u]=l}function Re(l){return(l&61440)===16384}function ks(l,u){return Ha?0:u.includes("r")&&!(l.mode&292)||u.includes("w")&&!(l.mode&146)||u.includes("x")&&!(l.mode&73)?2:0}function Va(l,u){if(!Re(l.mode))return 54;try{return Yt(l,u),20}catch{}return ks(l,"wx")}function Ka(l,u,d){try{var g=Yt(l,u)}catch(y){return y.Pa}if(l=ks(l,"wx"))return l;if(d){if(!Re(g.mode))return 54;if(g===g.parent||tr(g)==="/")return 10}else if(Re(g.mode))return 31;return 0}function io(l){if(!l)throw new D(63);return l}function xe(l){if(l=bs[l],!l)throw new D(8);return l}function Qa(l,u=-1){if(l=Object.assign(new Jd,l),u==-1)e:{for(u=0;4096>=u;u++)if(!bs[u])break e;throw new D(33)}return l.fd=u,bs[u]=l}function Kd(l,u=-1){return l=Qa(l,u),l.Ma?.ec?.(l),l}function or(l,u,d){var g=l?.Ma.Ua;l=g?l:u,g??=u.La.Ua,io(g),g(l,d)}var Qd={open(l){l.Ma=$a[l.node.rdev].Ma,l.Ma.open?.(l)},Va(){throw new D(70)}};function ir(l,u){$a[l]={Ma:u}}function Ya(l,u){var d=u==="/";if(d&&er)throw new D(10);if(!d&&u){var g=Be(u,{pb:!1});if(u=g.path,g=g.node,g.bb)throw new D(10);if(!Re(g.mode))throw new D(54)}u={type:l,kc:{},Db:u,Vb:[]},l=l.Xa(u),l.Xa=u,u.root=l,d?er=l:g&&(g.bb=u,g.Xa&&g.Xa.Vb.push(u))}function ro(l,u,d){var g=Be(l,{parent:!0}).node;if(l=Fe(l),!l)throw new D(28);if(l==="."||l==="..")throw new D(20);var y=Va(g,l);if(y)throw new D(y);if(!g.La.ib)throw new D(63);return g.La.ib(g,l,u,d)}function Yd(l,u=438){return ro(l,u&4095|32768,0)}function pt(l,u=511){return ro(l,u&1023|16384,0)}function ao(l,u,d){typeof d>"u"&&(d=u,u=438),ro(l,u|8192,d)}function rr(l,u){if(!Bd(l))throw new D(44);var d=Be(u,{parent:!0}).node;if(!d)throw new D(44);u=Fe(u);var g=Va(d,u);if(g)throw new D(g);if(!d.La.symlink)throw new D(63);d.La.symlink(d,u,l)}function Xa(l){var u=Be(l,{parent:!0}).node;l=Fe(l);var d=Yt(u,l),g=Ka(u,l,!0);if(g)throw new D(g);if(!u.La.rmdir)throw new D(63);if(d.bb)throw new D(10);u.La.rmdir(u,l),nr(d)}function Za(l){var u=Be(l,{parent:!0}).node;if(!u)throw new D(44);l=Fe(l);var d=Yt(u,l),g=Ka(u,l,!1);if(g)throw new D(g);if(!u.La.unlink)throw new D(63);if(d.bb)throw new D(10);u.La.unlink(u,l),nr(d)}function Ks(l,u){return l=Be(l,{ab:!u}).node,io(l.La.Ta)(l)}function el(l,u,d,g){or(l,u,{mode:d&4095|u.mode&-4096,ctime:Date.now(),Lb:g})}function lo(l,u){l=typeof l=="string"?Be(l,{ab:!0}).node:l,el(null,l,u)}function tl(l,u,d){if(Re(u.mode))throw new D(31);if((u.mode&61440)!==32768)throw new D(28);var g=ks(u,"w");if(g)throw new D(g);or(l,u,{size:d,timestamp:Date.now()})}function Ss(l,u,d=438){if(l==="")throw new D(44);if(typeof u=="string"){var g={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[u];if(typeof g>"u")throw Error(`Unknown file open mode: ${u}`);u=g}if(d=u&64?d&4095|32768:0,typeof l=="object")g=l;else{var y=l.endsWith("/"),k=Be(l,{ab:!(u&131072),Wb:!0});g=k.node,l=k.path}if(k=!1,u&64)if(g){if(u&128)throw new D(20)}else{if(y)throw new D(31);g=ro(l,d|511,0),k=!0}if(!g)throw new D(44);if((g.mode&61440)===8192&&(u&=-513),u&65536&&!Re(g.mode))throw new D(54);if(!k&&(g?(g.mode&61440)===40960?y=32:(y=["r","w","rw"][u&3],u&512&&(y+="w"),y=Re(g.mode)&&(y!=="r"||u&576)?31:ks(g,y)):y=44,y))throw new D(y);return u&512&&!k&&(y=g,y=typeof y=="string"?Be(y,{ab:!0}).node:y,tl(null,y,0)),u=Qa({node:g,path:tr(g),flags:u&-131713,seekable:!0,position:0,Ma:g.Ma,Yb:[],error:!1}),u.Ma.open&&u.Ma.open(u),k&&lo(g,d&511),u}function ar(l){if(l.fd===null)throw new D(8);l.rb&&(l.rb=null);try{l.Ma.close&&l.Ma.close(l)}catch(u){throw u}finally{bs[l.fd]=null}l.fd=null}function sl(l,u,d){if(l.fd===null)throw new D(8);if(!l.seekable||!l.Ma.Va)throw new D(70);if(d!=0&&d!=1&&d!=2)throw new D(28);l.position=l.Ma.Va(l,u,d),l.Yb=[]}function nl(l,u,d,g,y){if(0>g||0>y)throw new D(28);if(l.fd===null)throw new D(8);if((l.flags&2097155)===1)throw new D(8);if(Re(l.node.mode))throw new D(31);if(!l.Ma.read)throw new D(28);var k=typeof y<"u";if(!k)y=l.position;else if(!l.seekable)throw new D(70);return u=l.Ma.read(l,u,d,g,y),k||(l.position+=u),u}function ol(l,u,d,g,y){if(0>g||0>y)throw new D(28);if(l.fd===null)throw new D(8);if((l.flags&2097155)===0)throw new D(8);if(Re(l.node.mode))throw new D(31);if(!l.Ma.write)throw new D(28);l.seekable&&l.flags&1024&&sl(l,0,2);var k=typeof y<"u";if(!k)y=l.position;else if(!l.seekable)throw new D(70);return u=l.Ma.write(l,u,d,g,y,void 0),k||(l.position+=u),u}function Xd(l){var u=u||0,d="binary";d!=="utf8"&&d!=="binary"&&Et(`Invalid encoding type "${d}"`),u=Ss(l,u),l=Ks(l).size;var g=new Uint8Array(l);return nl(u,g,0,l,0),d==="utf8"&&(g=Vs(g)),ar(u),g}function It(l,u,d){l=Qt("/dev/"+l);var g=za(!!u,!!d);It.Cb??(It.Cb=64);var y=It.Cb++<<8|0;ir(y,{open(k){k.seekable=!1},close(){d?.buffer?.length&&d(10)},read(k,M,j,oe){for(var z=0,pe=0;pe<oe;pe++){try{var Pe=u()}catch{throw new D(29)}if(Pe===void 0&&z===0)throw new D(6);if(Pe==null)break;z++,M[j+pe]=Pe}return z&&(k.node.atime=Date.now()),z},write(k,M,j,oe){for(var z=0;z<oe;z++)try{d(M[j+z])}catch{throw new D(29)}return oe&&(k.node.mtime=k.node.ctime=Date.now()),z}}),ao(l,g,y)}var me={};function Xt(l,u,d){if(u.charAt(0)==="/")return u;if(l=l===-100?"/":xe(l).path,u.length==0){if(!d)throw new D(44);return l}return l+"/"+u}function co(l,u){se[l>>2]=u.dev,se[l+4>>2]=u.mode,se[l+8>>2]=u.nlink,se[l+12>>2]=u.uid,se[l+16>>2]=u.gid,se[l+20>>2]=u.rdev,Oe[l+24>>3]=BigInt(u.size),ne[l+32>>2]=4096,ne[l+36>>2]=u.blocks;var d=u.atime.getTime(),g=u.mtime.getTime(),y=u.ctime.getTime();return Oe[l+40>>3]=BigInt(Math.floor(d/1e3)),se[l+48>>2]=d%1e3*1e6,Oe[l+56>>3]=BigInt(Math.floor(g/1e3)),se[l+64>>2]=g%1e3*1e6,Oe[l+72>>3]=BigInt(Math.floor(y/1e3)),se[l+80>>2]=y%1e3*1e6,Oe[l+88>>3]=BigInt(u.ino),0}var uo=void 0,mo=()=>{var l=ne[+uo>>2];return uo+=4,l},lr=0,Zd=[0,31,60,91,121,152,182,213,244,274,305,335],em=[0,31,59,90,120,151,181,212,243,273,304,334],Qs={},il=l=>{F=l,U||0<lr||(i.onExit?.(l),q=!0),p(l,new Kt(l))},tm=l=>{if(!q)try{l()}catch(u){u instanceof Kt||u=="unwind"||p(1,u)}finally{if(!(U||0<lr))try{F=l=F,il(l)}catch(u){u instanceof Kt||u=="unwind"||p(1,u)}}},cr={},rl=()=>{if(!ur){var l={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:m||"./this.program"},u;for(u in cr)cr[u]===void 0?delete l[u]:l[u]=cr[u];var d=[];for(u in l)d.push(`${u}=${l[u]}`);ur=d}return ur},ur,sm=(l,u,d,g)=>{var y={string:z=>{var pe=0;if(z!=null&&z!==0){pe=Cs(z)+1;var Pe=es(pe);mt(z,N,Pe,pe),pe=Pe}return pe},array:z=>{var pe=es(z.length);return x.set(z,pe),pe}};l=i["_"+l];var k=[],M=0;if(g)for(var j=0;j<g.length;j++){var oe=y[d[j]];oe?(M===0&&(M=ho()),k[j]=oe(g[j])):k[j]=g[j]}return d=l(...k),d=(function(z){return M!==0&&fo(M),u==="string"?ae(z):u==="boolean"?!!z:z})(d)},po=l=>{var u=Cs(l)+1,d=go(u);return d&&mt(l,N,d,u),d},Zt,dr=[],Ut=l=>{Zt.delete(Ot.get(l)),Ot.set(l,null),dr.push(l)},al=l=>{let u=l.length;return[u%128|128,u>>7,...l]},nm={i:127,p:127,j:126,f:125,d:124,e:111},ll=l=>al(Array.from(l,u=>nm[u])),Ys=(l,u)=>{if(!Zt){Zt=new WeakMap;var d=Ot.length;if(Zt)for(var g=0;g<0+d;g++){var y=Ot.get(g);y&&Zt.set(y,g)}}if(d=Zt.get(l)||0)return d;d=dr.length?dr.pop():Ot.grow(1);try{Ot.set(d,l)}catch(k){if(!(k instanceof TypeError))throw k;u=Uint8Array.of(0,97,115,109,1,0,0,0,1,...al([1,96,...ll(u.slice(1)),...ll(u[0]==="v"?"":u[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),u=new WebAssembly.Module(u),u=new WebAssembly.Instance(u,{e:{f:l}}).exports.f,Ot.set(d,u)}return Zt.set(l,d),d};if(Rt=Array(4096),Ya(G,"/"),pt("/tmp"),pt("/home"),pt("/home/web_user"),(function(){pt("/dev"),ir(259,{read:()=>0,write:(g,y,k,M)=>M,Va:()=>0}),ao("/dev/null",259),Ba(1280,$d),Ba(1536,Wd),ao("/dev/tty",1280),ao("/dev/tty1",1536);var l=new Uint8Array(1024),u=0,d=()=>(u===0&&(Ga(l),u=l.byteLength),l[--u]);It("random",d),It("urandom",d),pt("/dev/shm"),pt("/dev/shm/tmp")})(),(function(){pt("/proc");var l=pt("/proc/self");pt("/proc/self/fd"),Ya({Xa(){var u=Ja(l,"fd",16895,73);return u.Ma={Va:G.Ma.Va},u.La={lookup(d,g){d=+g;var y=xe(d);return d={parent:null,Xa:{Db:"fake"},La:{readlink:()=>y.path},id:d+1},d.parent=d},readdir(){return Array.from(bs.entries()).filter(([,d])=>d).map(([d])=>d.toString())}},u}},"/proc/self/fd")})(),i.noExitRuntime&&(U=i.noExitRuntime),i.print&&(E=i.print),i.printErr&&(A=i.printErr),i.wasmBinary&&(R=i.wasmBinary),i.thisProgram&&(m=i.thisProgram),i.preInit)for(typeof i.preInit=="function"&&(i.preInit=[i.preInit]);0<i.preInit.length;)i.preInit.shift()();i.stackSave=()=>ho(),i.stackRestore=l=>fo(l),i.stackAlloc=l=>es(l),i.cwrap=(l,u,d,g)=>{var y=!d||d.every(k=>k==="number"||k==="boolean");return u!=="string"&&y&&!g?i["_"+l]:(...k)=>sm(l,u,d,k)},i.addFunction=Ys,i.removeFunction=Ut,i.UTF8ToString=ae,i.stringToNewUTF8=po,i.writeArrayToMemory=(l,u)=>{x.set(l,u)};var go,Xs,cl,ul,fo,es,ho,yo,Ot,om={a:(l,u,d,g)=>Et(`Assertion failed: ${ae(l)}, at: `+[u?ae(u):"unknown filename",d,g?ae(g):"unknown function"]),i:function(l,u){try{return l=ae(l),lo(l,u),0}catch(d){if(typeof me>"u"||d.name!=="ErrnoError")throw d;return-d.Pa}},L:function(l,u,d){try{if(u=ae(u),u=Xt(l,u),d&-8)return-28;var g=Be(u,{ab:!0}).node;return g?(l="",d&4&&(l+="r"),d&2&&(l+="w"),d&1&&(l+="x"),l&&ks(g,l)?-2:0):-44}catch(y){if(typeof me>"u"||y.name!=="ErrnoError")throw y;return-y.Pa}},j:function(l,u){try{var d=xe(l);return el(d,d.node,u,!1),0}catch(g){if(typeof me>"u"||g.name!=="ErrnoError")throw g;return-g.Pa}},h:function(l){try{var u=xe(l);return or(u,u.node,{timestamp:Date.now(),Lb:!1}),0}catch(d){if(typeof me>"u"||d.name!=="ErrnoError")throw d;return-d.Pa}},b:function(l,u,d){uo=d;try{var g=xe(l);switch(u){case 0:var y=mo();if(0>y)break;for(;bs[y];)y++;return Kd(g,y).fd;case 1:case 2:return 0;case 3:return g.flags;case 4:return y=mo(),g.flags|=y,0;case 12:return y=mo(),re[y+0>>1]=2,0;case 13:case 14:return 0}return-28}catch(k){if(typeof me>"u"||k.name!=="ErrnoError")throw k;return-k.Pa}},g:function(l,u){try{var d=xe(l),g=d.node,y=d.Ma.Ta;l=y?d:g,y??=g.La.Ta,io(y);var k=y(l);return co(u,k)}catch(M){if(typeof me>"u"||M.name!=="ErrnoError")throw M;return-M.Pa}},H:function(l,u){u=-9007199254740992>u||9007199254740992<u?NaN:Number(u);try{if(isNaN(u))return-61;var d=xe(l);if(0>u||(d.flags&2097155)===0)throw new D(28);return tl(d,d.node,u),0}catch(g){if(typeof me>"u"||g.name!=="ErrnoError")throw g;return-g.Pa}},G:function(l,u){try{if(u===0)return-28;var d=Cs("/")+1;return u<d?-68:(mt("/",N,l,u),d)}catch(g){if(typeof me>"u"||g.name!=="ErrnoError")throw g;return-g.Pa}},K:function(l,u){try{return l=ae(l),co(u,Ks(l,!0))}catch(d){if(typeof me>"u"||d.name!=="ErrnoError")throw d;return-d.Pa}},C:function(l,u,d){try{return u=ae(u),u=Xt(l,u),pt(u,d),0}catch(g){if(typeof me>"u"||g.name!=="ErrnoError")throw g;return-g.Pa}},J:function(l,u,d,g){try{u=ae(u);var y=g&256;return u=Xt(l,u,g&4096),co(d,y?Ks(u,!0):Ks(u))}catch(k){if(typeof me>"u"||k.name!=="ErrnoError")throw k;return-k.Pa}},x:function(l,u,d,g){uo=g;try{u=ae(u),u=Xt(l,u);var y=g?mo():0;return Ss(u,d,y).fd}catch(k){if(typeof me>"u"||k.name!=="ErrnoError")throw k;return-k.Pa}},v:function(l,u,d,g){try{if(u=ae(u),u=Xt(l,u),0>=g)return-28;var y=Be(u).node;if(!y)throw new D(44);if(!y.La.readlink)throw new D(28);var k=y.La.readlink(y),M=Math.min(g,Cs(k)),j=x[d+M];return mt(k,N,d,g+1),x[d+M]=j,M}catch(oe){if(typeof me>"u"||oe.name!=="ErrnoError")throw oe;return-oe.Pa}},u:function(l){try{return l=ae(l),Xa(l),0}catch(u){if(typeof me>"u"||u.name!=="ErrnoError")throw u;return-u.Pa}},f:function(l,u){try{return l=ae(l),co(u,Ks(l))}catch(d){if(typeof me>"u"||d.name!=="ErrnoError")throw d;return-d.Pa}},r:function(l,u,d){try{if(u=ae(u),u=Xt(l,u),d)if(d===512)Xa(u);else return-28;else Za(u);return 0}catch(g){if(typeof me>"u"||g.name!=="ErrnoError")throw g;return-g.Pa}},q:function(l,u,d){try{u=ae(u),u=Xt(l,u,!0);var g=Date.now(),y,k;if(d){var M=se[d>>2]+4294967296*ne[d+4>>2],j=ne[d+8>>2];j==1073741823?y=g:j==1073741822?y=null:y=1e3*M+j/1e6,d+=16,M=se[d>>2]+4294967296*ne[d+4>>2],j=ne[d+8>>2],j==1073741823?k=g:j==1073741822?k=null:k=1e3*M+j/1e6}else k=y=g;if((k??y)!==null){l=y;var oe=Be(u,{ab:!0}).node;io(oe.La.Ua)(oe,{atime:l,mtime:k})}return 0}catch(z){if(typeof me>"u"||z.name!=="ErrnoError")throw z;return-z.Pa}},m:()=>Et(""),l:()=>{U=!1,lr=0},A:function(l,u){l=-9007199254740992>l||9007199254740992<l?NaN:Number(l),l=new Date(1e3*l),ne[u>>2]=l.getSeconds(),ne[u+4>>2]=l.getMinutes(),ne[u+8>>2]=l.getHours(),ne[u+12>>2]=l.getDate(),ne[u+16>>2]=l.getMonth(),ne[u+20>>2]=l.getFullYear()-1900,ne[u+24>>2]=l.getDay();var d=l.getFullYear();ne[u+28>>2]=(d%4!==0||d%100===0&&d%400!==0?em:Zd)[l.getMonth()]+l.getDate()-1|0,ne[u+36>>2]=-(60*l.getTimezoneOffset()),d=new Date(l.getFullYear(),6,1).getTimezoneOffset();var g=new Date(l.getFullYear(),0,1).getTimezoneOffset();ne[u+32>>2]=(d!=g&&l.getTimezoneOffset()==Math.min(g,d))|0},y:function(l,u,d,g,y,k,M){y=-9007199254740992>y||9007199254740992<y?NaN:Number(y);try{var j=xe(g);if((u&2)!==0&&(d&2)===0&&(j.flags&2097155)!==2)throw new D(2);if((j.flags&2097155)===1)throw new D(2);if(!j.Ma.jb)throw new D(43);if(!l)throw new D(28);var oe=j.Ma.jb(j,l,y,u,d),z=oe.Xb;return ne[k>>2]=oe.Eb,se[M>>2]=z,0}catch(pe){if(typeof me>"u"||pe.name!=="ErrnoError")throw pe;return-pe.Pa}},z:function(l,u,d,g,y,k){k=-9007199254740992>k||9007199254740992<k?NaN:Number(k);try{var M=xe(y);if(d&2){if(d=k,(M.node.mode&61440)!==32768)throw new D(43);if(!(g&2)){var j=N.slice(l,l+u);M.Ma.kb&&M.Ma.kb(M,j,d,u,g)}}}catch(oe){if(typeof me>"u"||oe.name!=="ErrnoError")throw oe;return-oe.Pa}},n:(l,u)=>{if(Qs[l]&&(clearTimeout(Qs[l].id),delete Qs[l]),!u)return 0;var d=setTimeout(()=>{delete Qs[l],tm(()=>ul(l,performance.now()))},u);return Qs[l]={id:d,lc:u},0},B:(l,u,d,g)=>{var y=new Date().getFullYear(),k=new Date(y,0,1).getTimezoneOffset();y=new Date(y,6,1).getTimezoneOffset(),se[l>>2]=60*Math.max(k,y),ne[u>>2]=+(k!=y),u=M=>{var j=Math.abs(M);return`UTC${0<=M?"-":"+"}${String(Math.floor(j/60)).padStart(2,"0")}${String(j%60).padStart(2,"0")}`},l=u(k),u=u(y),y<k?(mt(l,N,d,17),mt(u,N,g,17)):(mt(l,N,g,17),mt(u,N,d,17))},d:()=>Date.now(),s:()=>2147483648,c:()=>performance.now(),o:l=>{var u=N.length;if(l>>>=0,2147483648<l)return!1;for(var d=1;4>=d;d*=2){var g=u*(1+.2/d);g=Math.min(g,l+100663296);e:{g=(Math.min(2147483648,65536*Math.ceil(Math.max(l,g)/65536))-yo.buffer.byteLength+65535)/65536|0;try{yo.grow(g),Hs();var y=1;break e}catch{}y=void 0}if(y)return!0}return!1},E:(l,u)=>{var d=0,g=0,y;for(y of rl()){var k=u+d;se[l+g>>2]=k,d+=mt(y,N,k,1/0)+1,g+=4}return 0},F:(l,u)=>{var d=rl();se[l>>2]=d.length,l=0;for(var g of d)l+=Cs(g)+1;return se[u>>2]=l,0},e:function(l){try{var u=xe(l);return ar(u),0}catch(d){if(typeof me>"u"||d.name!=="ErrnoError")throw d;return d.Pa}},p:function(l,u){try{var d=xe(l);return x[u]=d.tty?2:Re(d.mode)?3:(d.mode&61440)===40960?7:4,re[u+2>>1]=0,Oe[u+8>>3]=BigInt(0),Oe[u+16>>3]=BigInt(0),0}catch(g){if(typeof me>"u"||g.name!=="ErrnoError")throw g;return g.Pa}},w:function(l,u,d,g){try{e:{var y=xe(l);l=u;for(var k,M=u=0;M<d;M++){var j=se[l>>2],oe=se[l+4>>2];l+=8;var z=nl(y,x,j,oe,k);if(0>z){var pe=-1;break e}if(u+=z,z<oe)break;typeof k<"u"&&(k+=z)}pe=u}return se[g>>2]=pe,0}catch(Pe){if(typeof me>"u"||Pe.name!=="ErrnoError")throw Pe;return Pe.Pa}},D:function(l,u,d,g){u=-9007199254740992>u||9007199254740992<u?NaN:Number(u);try{if(isNaN(u))return 61;var y=xe(l);return sl(y,u,d),Oe[g>>3]=BigInt(y.position),y.rb&&u===0&&d===0&&(y.rb=null),0}catch(k){if(typeof me>"u"||k.name!=="ErrnoError")throw k;return k.Pa}},I:function(l){try{var u=xe(l);return u.Ma?.fsync?.(u)}catch(d){if(typeof me>"u"||d.name!=="ErrnoError")throw d;return d.Pa}},t:function(l,u,d,g){try{e:{var y=xe(l);l=u;for(var k,M=u=0;M<d;M++){var j=se[l>>2],oe=se[l+4>>2];l+=8;var z=ol(y,x,j,oe,k);if(0>z){var pe=-1;break e}if(u+=z,z<oe)break;typeof k<"u"&&(k+=z)}pe=u}return se[g>>2]=pe,0}catch(Pe){if(typeof me>"u"||Pe.name!=="ErrnoError")throw Pe;return Pe.Pa}},k:il};function mr(){function l(){if(i.calledRun=!0,!q){if(!i.noFSInit&&!Wa){var u,d;Wa=!0,u??=i.stdin,d??=i.stdout,g??=i.stderr,u?It("stdin",u):rr("/dev/tty","/dev/stdin"),d?It("stdout",null,d):rr("/dev/tty","/dev/stdout"),g?It("stderr",null,g):rr("/dev/tty1","/dev/stderr"),Ss("/dev/stdin",0),Ss("/dev/stdout",1),Ss("/dev/stderr",1)}if(pr.N(),Ha=!1,i.onRuntimeInitialized?.(),i.postRun)for(typeof i.postRun=="function"&&(i.postRun=[i.postRun]);i.postRun.length;){var g=i.postRun.shift();Xi.push(g)}ys(Xi)}}if(0<Ye)_s=mr;else{if(i.preRun)for(typeof i.preRun=="function"&&(i.preRun=[i.preRun]);i.preRun.length;)Js();ys(no),0<Ye?_s=mr:i.setStatus?(i.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>i.setStatus(""),1),l()},1)):l()}}var pr;return(async function(){function l(d){return d=pr=d.exports,i._sqlite3_free=d.P,i._sqlite3_value_text=d.Q,i._sqlite3_prepare_v2=d.R,i._sqlite3_step=d.S,i._sqlite3_reset=d.T,i._sqlite3_exec=d.U,i._sqlite3_finalize=d.V,i._sqlite3_column_name=d.W,i._sqlite3_column_text=d.X,i._sqlite3_column_type=d.Y,i._sqlite3_errmsg=d.Z,i._sqlite3_clear_bindings=d._,i._sqlite3_value_blob=d.$,i._sqlite3_value_bytes=d.aa,i._sqlite3_value_double=d.ba,i._sqlite3_value_int=d.ca,i._sqlite3_value_type=d.da,i._sqlite3_result_blob=d.ea,i._sqlite3_result_double=d.fa,i._sqlite3_result_error=d.ga,i._sqlite3_result_int=d.ha,i._sqlite3_result_int64=d.ia,i._sqlite3_result_null=d.ja,i._sqlite3_result_text=d.ka,i._sqlite3_aggregate_context=d.la,i._sqlite3_column_count=d.ma,i._sqlite3_data_count=d.na,i._sqlite3_column_blob=d.oa,i._sqlite3_column_bytes=d.pa,i._sqlite3_column_double=d.qa,i._sqlite3_bind_blob=d.ra,i._sqlite3_bind_double=d.sa,i._sqlite3_bind_int=d.ta,i._sqlite3_bind_text=d.ua,i._sqlite3_bind_parameter_index=d.va,i._sqlite3_sql=d.wa,i._sqlite3_normalized_sql=d.xa,i._sqlite3_changes=d.ya,i._sqlite3_close_v2=d.za,i._sqlite3_create_function_v2=d.Aa,i._sqlite3_update_hook=d.Ba,i._sqlite3_open=d.Ca,go=i._malloc=d.Da,Xs=i._free=d.Ea,i._RegisterExtensionFunctions=d.Fa,cl=d.Ga,ul=d.Ha,fo=d.Ia,es=d.Ja,ho=d.Ka,yo=d.M,Ot=d.O,Hs(),Ye--,i.monitorRunDependencies?.(Ye),Ye==0&&_s&&(d=_s,_s=null,d()),pr}Ye++,i.monitorRunDependencies?.(Ye);var u={a:om};return i.instantiateWasm?new Promise(d=>{i.instantiateWasm(u,(g,y)=>{d(l(g,y))})}):(Ct??=i.locateFile?i.locateFile("sql-wasm.wasm",h):h+"sql-wasm.wasm",l((await Yi(u)).instance))})(),mr(),s}),Ro)};typeof Uo=="object"&&typeof os=="object"?(os.exports=Io,os.exports.default=Io):typeof define=="function"&&define.amd?define([],function(){return Io}):typeof Uo=="object"&&(Uo.Module=Io)});var Go=Te(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.utf8Count=Hp;kt.utf8EncodeJs=ec;kt.utf8EncodeTE=tc;kt.utf8Encode=Kp;kt.utf8DecodeJs=sc;kt.utf8DecodeTD=nc;kt.utf8Decode=Zp;function Hp(o){let e=o.length,t=0,s=0;for(;s<e;){let n=o.charCodeAt(s++);if((n&4294967168)===0){t++;continue}else if((n&4294965248)===0)t+=2;else{if(n>=55296&&n<=56319&&s<e){let i=o.charCodeAt(s);(i&64512)===56320&&(++s,n=((n&1023)<<10)+(i&1023)+65536)}(n&4294901760)===0?t+=3:t+=4}}return t}function ec(o,e,t){let s=o.length,n=t,i=0;for(;i<s;){let r=o.charCodeAt(i++);if((r&4294967168)===0){e[n++]=r;continue}else if((r&4294965248)===0)e[n++]=r>>6&31|192;else{if(r>=55296&&r<=56319&&i<s){let a=o.charCodeAt(i);(a&64512)===56320&&(++i,r=((r&1023)<<10)+(a&1023)+65536)}(r&4294901760)===0?(e[n++]=r>>12&15|224,e[n++]=r>>6&63|128):(e[n++]=r>>18&7|240,e[n++]=r>>12&63|128,e[n++]=r>>6&63|128)}e[n++]=r&63|128}}var Jp=new TextEncoder,Vp=50;function tc(o,e,t){Jp.encodeInto(o,e.subarray(t))}function Kp(o,e,t){o.length>Vp?tc(o,e,t):ec(o,e,t)}var Qp=4096;function sc(o,e,t){let s=e,n=s+t,i=[],r="";for(;s<n;){let a=o[s++];if((a&128)===0)i.push(a);else if((a&224)===192){let c=o[s++]&63;i.push((a&31)<<6|c)}else if((a&240)===224){let c=o[s++]&63,m=o[s++]&63;i.push((a&31)<<12|c<<6|m)}else if((a&248)===240){let c=o[s++]&63,m=o[s++]&63,p=o[s++]&63,f=(a&7)<<18|c<<12|m<<6|p;f>65535&&(f-=65536,i.push(f>>>10&1023|55296),f=56320|f&1023),i.push(f)}else i.push(a);i.length>=Qp&&(r+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(r+=String.fromCharCode(...i)),r}var Yp=new TextDecoder,Xp=200;function nc(o,e,t){let s=o.subarray(e,e+t);return Yp.decode(s)}function Zp(o,e,t){return t>Xp?nc(o,e,t):sc(o,e,t)}});var Ar=Te(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.ExtData=void 0;var vr=class{type;data;constructor(e,t){this.type=e,this.data=t}};qo.ExtData=vr});var zo=Te(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});Bo.DecodeError=void 0;var xr=class o extends Error{constructor(e){super(e);let t=Object.create(o.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:o.name})}};Bo.DecodeError=xr});var $o=Te(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.UINT32_MAX=void 0;Lt.setUint64=eg;Lt.setInt64=tg;Lt.getInt64=sg;Lt.getUint64=ng;Lt.UINT32_MAX=4294967295;function eg(o,e,t){let s=t/4294967296,n=t;o.setUint32(e,s),o.setUint32(e+4,n)}function tg(o,e,t){let s=Math.floor(t/4294967296),n=t;o.setUint32(e,s),o.setUint32(e+4,n)}function sg(o,e){let t=o.getInt32(e),s=o.getUint32(e+4);return t*4294967296+s}function ng(o,e){let t=o.getUint32(e),s=o.getUint32(e+4);return t*4294967296+s}});var Dr=Te(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.timestampExtension=He.EXT_TIMESTAMP=void 0;He.encodeTimeSpecToTimestamp=ic;He.encodeDateToTimeSpec=rc;He.encodeTimestampExtension=ac;He.decodeTimestampToTimeSpec=lc;He.decodeTimestampExtension=cc;var og=zo(),oc=$o();He.EXT_TIMESTAMP=-1;var ig=4294967296-1,rg=17179869184-1;function ic({sec:o,nsec:e}){if(o>=0&&e>=0&&o<=rg)if(e===0&&o<=ig){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,o),t}else{let t=o/4294967296,s=o&4294967295,n=new Uint8Array(8),i=new DataView(n.buffer);return i.setUint32(0,e<<2|t&3),i.setUint32(4,s),n}else{let t=new Uint8Array(12),s=new DataView(t.buffer);return s.setUint32(0,e),(0,oc.setInt64)(s,4,o),t}}function rc(o){let e=o.getTime(),t=Math.floor(e/1e3),s=(e-t*1e3)*1e6,n=Math.floor(s/1e9);return{sec:t+n,nsec:s-n*1e9}}function ac(o){if(o instanceof Date){let e=rc(o);return ic(e)}else return null}function lc(o){let e=new DataView(o.buffer,o.byteOffset,o.byteLength);switch(o.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let t=e.getUint32(0),s=e.getUint32(4),n=(t&3)*4294967296+s,i=t>>>2;return{sec:n,nsec:i}}case 12:{let t=(0,oc.getInt64)(e,4),s=e.getUint32(0);return{sec:t,nsec:s}}default:throw new og.DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${o.length}`)}}function cc(o){let e=lc(o);return new Date(e.sec*1e3+e.nsec/1e6)}He.timestampExtension={type:He.EXT_TIMESTAMP,encode:ac,decode:cc}});var Jo=Te(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.ExtensionCodec=void 0;var Wo=Ar(),ag=Dr(),Er=class o{static defaultCodec=new o;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(ag.timestampExtension)}register({type:e,encode:t,decode:s}){if(e>=0)this.encoders[e]=t,this.decoders[e]=s;else{let n=-1-e;this.builtInEncoders[n]=t,this.builtInDecoders[n]=s}}tryToEncode(e,t){for(let s=0;s<this.builtInEncoders.length;s++){let n=this.builtInEncoders[s];if(n!=null){let i=n(e,t);if(i!=null){let r=-1-s;return new Wo.ExtData(r,i)}}}for(let s=0;s<this.encoders.length;s++){let n=this.encoders[s];if(n!=null){let i=n(e,t);if(i!=null){let r=s;return new Wo.ExtData(r,i)}}}return e instanceof Wo.ExtData?e:null}decode(e,t,s){let n=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return n?n(e,t,s):new Wo.ExtData(t,e)}};Ho.ExtensionCodec=Er});var Ir=Te(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.ensureUint8Array=cg;function lg(o){return o instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&o instanceof SharedArrayBuffer}function cg(o){return o instanceof Uint8Array?o:ArrayBuffer.isView(o)?new Uint8Array(o.buffer,o.byteOffset,o.byteLength):lg(o)?new Uint8Array(o):Uint8Array.from(o)}});var Or=Te(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.Encoder=ht.DEFAULT_INITIAL_BUFFER_SIZE=ht.DEFAULT_MAX_DEPTH=void 0;var uc=Go(),ug=Jo(),dc=$o(),dg=Ir();ht.DEFAULT_MAX_DEPTH=100;ht.DEFAULT_INITIAL_BUFFER_SIZE=2048;var Ur=class o{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??ug.ExtensionCodec.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??ht.DEFAULT_MAX_DEPTH,this.initialBufferSize=e?.initialBufferSize??ht.DEFAULT_INITIAL_BUFFER_SIZE,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new o({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){let t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){let t=new ArrayBuffer(e),s=new Uint8Array(t),n=new DataView(t);s.set(this.bytes),this.view=n,this.bytes=s}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let s=(0,uc.utf8Count)(e);this.ensureBufferSizeToWrite(5+s),this.writeStringHeader(s),(0,uc.utf8Encode)(e,this.bytes,this.pos),this.pos+=s}encodeObject(e,t){let s=this.extensionCodec.tryToEncode(e,this.context);if(s!=null)this.encodeExtension(s);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);let s=(0,dg.ensureUint8Array)(e);this.writeU8a(s)}encodeArray(e,t){let s=e.length;if(s<16)this.writeU8(144+s);else if(s<65536)this.writeU8(220),this.writeU16(s);else if(s<4294967296)this.writeU8(221),this.writeU32(s);else throw new Error(`Too large array: ${s}`);for(let n of e)this.doEncode(n,t+1)}countWithoutUndefined(e,t){let s=0;for(let n of t)e[n]!==void 0&&s++;return s}encodeMap(e,t){let s=Object.keys(e);this.sortKeys&&s.sort();let n=this.ignoreUndefined?this.countWithoutUndefined(e,s):s.length;if(n<16)this.writeU8(128+n);else if(n<65536)this.writeU8(222),this.writeU16(n);else if(n<4294967296)this.writeU8(223),this.writeU32(n);else throw new Error(`Too large map object: ${n}`);for(let i of s){let r=e[i];this.ignoreUndefined&&r===void 0||(this.encodeString(i),this.doEncode(r,t+1))}}encodeExtension(e){if(typeof e.data=="function"){let s=e.data(this.pos+6),n=s.length;if(n>=4294967296)throw new Error(`Too large extension object: ${n}`);this.writeU8(201),this.writeU32(n),this.writeI8(e.type),this.writeU8a(s);return}let t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),(0,dc.setUint64)(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),(0,dc.setInt64)(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};ht.Encoder=Ur});var mc=Te(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.encode=pg;var mg=Or();function pg(o,e){return new mg.Encoder(e).encodeSharedRef(o)}});var pc=Te(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.prettyByte=gg;function gg(o){return`${o<0?"-":""}0x${Math.abs(o).toString(16).padStart(2,"0")}`}});var gc=Te(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});Vo.CachedKeyDecoder=void 0;var fg=Go(),hg=16,yg=16,Lr=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=hg,t=yg){this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let s=0;s<this.maxKeyLength;s++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,s){let n=this.caches[s-1];e:for(let i of n){let r=i.bytes;for(let a=0;a<s;a++)if(r[a]!==e[t+a])continue e;return i.str}return null}store(e,t){let s=this.caches[e.length-1],n={bytes:e,str:t};s.length>=this.maxLengthPerKey?s[Math.random()*s.length|0]=n:s.push(n)}decode(e,t,s){let n=this.find(e,t,s);if(n!=null)return this.hit++,n;this.miss++;let i=(0,fg.utf8DecodeJs)(e,t,s),r=Uint8Array.prototype.slice.call(e,t,t+s);return this.store(r,i),i}};Vo.CachedKeyDecoder=Lr});var Qo=Te(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.Decoder=void 0;var jr=pc(),_g=Jo(),cs=$o(),Cg=Go(),fc=Ir(),bg=gc(),St=zo(),Gr="array",mn="map_key",yc="map_value",kg=o=>{if(typeof o=="string"||typeof o=="number")return o;throw new St.DecodeError("The type of key must be string or number but "+typeof o)},qr=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let t=this.getUninitializedStateFromPool();t.type=Gr,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=mn,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===Gr){let s=e;s.size=0,s.array=void 0,s.position=0,s.type=void 0}if(e.type===mn||e.type===yc){let s=e;s.size=0,s.map=void 0,s.readCount=0,s.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},dn=-1,zr=new DataView(new ArrayBuffer(0)),Sg=new Uint8Array(zr.buffer);try{zr.getInt8(0)}catch(o){if(!(o instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var hc=new RangeError("Insufficient data"),wg=new bg.CachedKeyDecoder,Br=class o{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=zr;bytes=Sg;headByte=dn;stack=new qr;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??_g.ExtensionCodec.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??cs.UINT32_MAX,this.maxBinLength=e?.maxBinLength??cs.UINT32_MAX,this.maxArrayLength=e?.maxArrayLength??cs.UINT32_MAX,this.maxMapLength=e?.maxMapLength??cs.UINT32_MAX,this.maxExtLength=e?.maxExtLength??cs.UINT32_MAX,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:wg,this.mapKeyConverter=e?.mapKeyConverter??kg}clone(){return new o({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=dn,this.stack.reset()}setBuffer(e){let t=(0,fc.ensureUint8Array)(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===dn&&!this.hasRemaining(1))this.setBuffer(e);else{let t=this.bytes.subarray(this.pos),s=(0,fc.ensureUint8Array)(e),n=new Uint8Array(t.length+s.length);n.set(t),n.set(s,t.length),this.setBuffer(n)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:s}=this;return new RangeError(`Extra ${t.byteLength-s} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,s;for await(let a of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{s=this.doDecodeSync(),t=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return s}let{headByte:n,pos:i,totalPos:r}=this;throw new RangeError(`Insufficient data in parsing ${(0,jr.prettyByte)(n)} at ${r} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let s=t,n=-1;for await(let i of e){if(t&&n===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),s&&(n=this.readArraySize(),s=!1,this.complete());try{for(;yield this.doDecodeSync(),--n!==0;);}catch(r){if(!(r instanceof RangeError))throw r}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){let n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e<160){let n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else{let n=e-160;t=this.decodeString(n,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){let n=this.lookU8();t=this.decodeString(n,1)}else if(e===218){let n=this.lookU16();t=this.decodeString(n,2)}else if(e===219){let n=this.lookU32();t=this.decodeString(n,4)}else if(e===220){let n=this.readU16();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===221){let n=this.readU32();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===222){let n=this.readU16();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===223){let n=this.readU32();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===196){let n=this.lookU8();t=this.decodeBinary(n,1)}else if(e===197){let n=this.lookU16();t=this.decodeBinary(n,2)}else if(e===198){let n=this.lookU32();t=this.decodeBinary(n,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){let n=this.lookU8();t=this.decodeExtension(n,1)}else if(e===200){let n=this.lookU16();t=this.decodeExtension(n,2)}else if(e===201){let n=this.lookU32();t=this.decodeExtension(n,4)}else throw new St.DecodeError(`Unrecognized type byte: ${(0,jr.prettyByte)(e)}`);this.complete();let s=this.stack;for(;s.length>0;){let n=s.top();if(n.type===Gr)if(n.array[n.position]=t,n.position++,n.position===n.size)t=n.array,s.release(n);else continue e;else if(n.type===mn){if(t==="__proto__")throw new St.DecodeError("The key __proto__ is not allowed");n.key=this.mapKeyConverter(t),n.type=yc;continue e}else if(n.map[n.key]=t,n.readCount++,n.readCount===n.size)t=n.map,s.release(n);else{n.key=null,n.type=mn;continue e}}return t}}readHeadByte(){return this.headByte===dn&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=dn}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new St.DecodeError(`Unrecognized array type byte: ${(0,jr.prettyByte)(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new St.DecodeError(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new St.DecodeError(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new St.DecodeError(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw hc;let s=this.pos+t,n;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?n=this.keyDecoder.decode(this.bytes,s,e):n=(0,Cg.utf8Decode)(this.bytes,s,e),this.pos+=t+e,n}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===mn:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new St.DecodeError(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw hc;let s=this.pos+t,n=this.bytes.subarray(s,s+e);return this.pos+=t+e,n}decodeExtension(e,t){if(e>this.maxExtLength)throw new St.DecodeError(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let s=this.view.getInt8(this.pos+t),n=this.decodeBinary(e,t+1);return this.extensionCodec.decode(n,s,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=(0,cs.getUint64)(this.view,this.pos);return this.pos+=8,e}readI64(){let e=(0,cs.getInt64)(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};Ko.Decoder=Br});var Cc=Te(Yo=>{"use strict";Object.defineProperty(Yo,"__esModule",{value:!0});Yo.decode=Tg;Yo.decodeMulti=Mg;var _c=Qo();function Tg(o,e){return new _c.Decoder(e).decode(o)}function Mg(o,e){return new _c.Decoder(e).decodeMulti(o)}});var Sc=Te(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.isAsyncIterable=bc;pn.asyncIterableFromStream=kc;pn.ensureAsyncIterable=Pg;function bc(o){return o[Symbol.asyncIterator]!=null}async function*kc(o){let e=o.getReader();try{for(;;){let{done:t,value:s}=await e.read();if(t)return;yield s}}finally{e.releaseLock()}}function Pg(o){return bc(o)?o:kc(o)}});var wc=Te(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.decodeAsync=vg;gn.decodeArrayStream=Ag;gn.decodeMultiStream=xg;var $r=Qo(),Wr=Sc();async function vg(o,e){let t=(0,Wr.ensureAsyncIterable)(o);return new $r.Decoder(e).decodeAsync(t)}function Ag(o,e){let t=(0,Wr.ensureAsyncIterable)(o);return new $r.Decoder(e).decodeArrayStream(t)}function xg(o,e){let t=(0,Wr.ensureAsyncIterable)(o);return new $r.Decoder(e).decodeStream(t)}});var Jr=Te(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.decodeTimestampExtension=K.encodeTimestampExtension=K.decodeTimestampToTimeSpec=K.encodeTimeSpecToTimestamp=K.encodeDateToTimeSpec=K.EXT_TIMESTAMP=K.ExtData=K.ExtensionCodec=K.Encoder=K.DecodeError=K.Decoder=K.decodeMultiStream=K.decodeArrayStream=K.decodeAsync=K.decodeMulti=K.decode=K.encode=void 0;var Dg=mc();Object.defineProperty(K,"encode",{enumerable:!0,get:function(){return Dg.encode}});var Tc=Cc();Object.defineProperty(K,"decode",{enumerable:!0,get:function(){return Tc.decode}});Object.defineProperty(K,"decodeMulti",{enumerable:!0,get:function(){return Tc.decodeMulti}});var Hr=wc();Object.defineProperty(K,"decodeAsync",{enumerable:!0,get:function(){return Hr.decodeAsync}});Object.defineProperty(K,"decodeArrayStream",{enumerable:!0,get:function(){return Hr.decodeArrayStream}});Object.defineProperty(K,"decodeMultiStream",{enumerable:!0,get:function(){return Hr.decodeMultiStream}});var Eg=Qo();Object.defineProperty(K,"Decoder",{enumerable:!0,get:function(){return Eg.Decoder}});var Rg=zo();Object.defineProperty(K,"DecodeError",{enumerable:!0,get:function(){return Rg.DecodeError}});var Ig=Or();Object.defineProperty(K,"Encoder",{enumerable:!0,get:function(){return Ig.Encoder}});var Ug=Jo();Object.defineProperty(K,"ExtensionCodec",{enumerable:!0,get:function(){return Ug.ExtensionCodec}});var Og=Ar();Object.defineProperty(K,"ExtData",{enumerable:!0,get:function(){return Og.ExtData}});var Es=Dr();Object.defineProperty(K,"EXT_TIMESTAMP",{enumerable:!0,get:function(){return Es.EXT_TIMESTAMP}});Object.defineProperty(K,"encodeDateToTimeSpec",{enumerable:!0,get:function(){return Es.encodeDateToTimeSpec}});Object.defineProperty(K,"encodeTimeSpecToTimestamp",{enumerable:!0,get:function(){return Es.encodeTimeSpecToTimestamp}});Object.defineProperty(K,"decodeTimestampToTimeSpec",{enumerable:!0,get:function(){return Es.decodeTimestampToTimeSpec}});Object.defineProperty(K,"encodeTimestampExtension",{enumerable:!0,get:function(){return Es.encodeTimestampExtension}});Object.defineProperty(K,"decodeTimestampExtension",{enumerable:!0,get:function(){return Es.decodeTimestampExtension}})});var qd=Te((ZP,cb)=>{cb.exports={name:"@rajbos/ai-engineering-fluency",version:"0.4.0",description:"AI Engineering Fluency - CLI tool to analyze GitHub Copilot token usage from local session files",license:"MIT",author:"RobBos",repository:{type:"git",url:"git+https://github.com/rajbos/ai-engineering-fluency.git",directory:"cli"},keywords:["github-copilot","token-usage","copilot","cli","token-tracker"],bin:{"ai-engineering-fluency":"dist/cli.js"},files:["dist/**/*"],scripts:{build:"node esbuild.js","build:production":"node esbuild.js --production","bundle-exe":"pwsh -NoProfile -File bundle-exe.ps1",lint:"eslint src","check-types":"tsc --noEmit",test:"node dist/cli.js --help && node dist/cli.js --version && npm run test:unit","test:unit":'node esbuild.tests.js && node --test "out/test/*.test.js"'},devDependencies:{"@msgpack/msgpack":"^3.1.3","@types/node":"^26.0.0",chalk:"^5.6.2",commander:"^15.0.0",esbuild:"^0.28.0","sql.js":"^1.12.0",typescript:"^7.0.2"},engines:{node:">=22.14.0"}}});var Ft=class extends Error{constructor(e,t,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},ss=class extends Ft{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var Zs=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,s)=>{if(!this.argChoices.includes(t))throw new ss(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(t,s):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Co(o){let e=o.name()+(o.variadic===!0?"...":"");return o.required?"<"+e+">":"["+e+"]"}var Ml=require("node:events"),ko=w(require("node:child_process"),1),gt=w(require("node:path"),1),tn=w(require("node:fs"),1),te=w(require("node:process"),1),Pl=require("node:util");var kl=require("node:util"),en=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(n=>!n._hidden),s=e._getHelpCommand();return s&&!s._hidden&&t.push(s),this.sortSubcommands&&t.sort((n,i)=>n.name().localeCompare(i.name())),t}compareOptions(e,t){let s=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return s(e).localeCompare(s(t))}visibleOptions(e){let t=e.options.filter(n=>!n.hidden),s=e._getHelpOption();if(s&&!s.hidden){let n=s.short&&e._findOption(s.short),i=s.long&&e._findOption(s.long);!n&&!i?t.push(s):s.long&&!i?t.push(e.createOption(s.long,s.description)):s.short&&!n&&t.push(e.createOption(s.short,s.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let s=e.parent;s;s=s.parent){let n=s.options.filter(i=>!i.hidden);t.push(...n)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(s=>Co(s)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((s,n)=>Math.max(s,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((s,n)=>Math.max(s,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((s,n)=>Math.max(s,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((s,n)=>Math.max(s,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let s="";for(let n=e.parent;n;n=n.parent)s=n.name()+" "+s;return s+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let s=`(${t.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let s=`(${t.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}formatItemList(e,t,s){return t.length===0?[]:[s.styleTitle(e),...t,""]}groupItems(e,t,s){let n=new Map;return e.forEach(i=>{let r=s(i);n.has(r)||n.set(r,[])}),t.forEach(i=>{let r=s(i);n.has(r)||n.set(r,[]),n.get(r).push(i)}),n}formatHelp(e,t){let s=t.padWidth(e,t),n=t.helpWidth??80;function i(f,h){return t.formatItem(f,s,h,t)}let r=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],a=t.commandDescription(e);a.length>0&&(r=r.concat([t.boxWrap(t.styleCommandDescription(a),n),""]));let c=t.visibleArguments(e).map(f=>i(t.styleArgumentTerm(t.argumentTerm(f)),t.styleArgumentDescription(t.argumentDescription(f))));if(r=r.concat(this.formatItemList("Arguments:",c,t)),this.groupItems(e.options,t.visibleOptions(e),f=>f.helpGroupHeading??"Options:").forEach((f,h)=>{let _=f.map(C=>i(t.styleOptionTerm(t.optionTerm(C)),t.styleOptionDescription(t.optionDescription(C))));r=r.concat(this.formatItemList(h,_,t))}),t.showGlobalOptions){let f=t.visibleGlobalOptions(e).map(h=>i(t.styleOptionTerm(t.optionTerm(h)),t.styleOptionDescription(t.optionDescription(h))));r=r.concat(this.formatItemList("Global Options:",f,t))}return this.groupItems(e.commands,t.visibleCommands(e),f=>f.helpGroup()||"Commands:").forEach((f,h)=>{let _=f.map(C=>i(t.styleSubcommandTerm(t.subcommandTerm(C)),t.styleSubcommandDescription(t.subcommandDescription(C))));r=r.concat(this.formatItemList(h,_,t))}),r.join(`
|
|
4
|
-
`)}displayWidth(e){return(0,
|
|
2
|
+
"use strict";var zm=Object.create;var vl=Object.defineProperty;var $m=Object.getOwnPropertyDescriptor;var Hm=Object.getOwnPropertyNames;var Wm=Object.getPrototypeOf,Jm=Object.prototype.hasOwnProperty;var we=(o,e)=>()=>{try{return e||o((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var Vm=(o,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Hm(e))!Jm.call(o,n)&&n!==t&&vl(o,n,{get:()=>e[n],enumerable:!(s=$m(e,n))||s.enumerable});return o};var S=(o,e,t)=>(t=o!=null?zm(Wm(o)):{},Vm(e||!o||!o.__esModule?vl(t,"default",{value:o,enumerable:!0}):t,o));var Nt=we((Lo,is)=>{var Fo=void 0,No=function(o){return Fo||(Fo=new Promise(function(e,t){var s=typeof o<"u"?o:{},n=s.onAbort;s.onAbort=function(l){t(new Error(l)),n&&n(l)},s.postRun=s.postRun||[],s.postRun.push(function(){e(s)}),is=void 0;var i;i||=typeof s<"u"?s:{};var r=!!globalThis.window,a=!!globalThis.WorkerGlobalScope,c=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";i.onRuntimeInitialized=function(){function l(b,v){switch(typeof v){case"boolean":qm(b,v?1:0);break;case"number":Lm(b,v);break;case"string":jm(b,v,-1,-1);break;case"object":if(v===null)Tl(b);else if(v.length!=null){var I=yo(v.length);x.set(v,I),Gm(b,I,v.length,-1),Ys(I)}else ko(b,"Wrong API use : tried to return a value of an unknown type ("+v+").",-1);break;default:Tl(b)}}function u(b,v){for(var I=[],O=0;O<b;O+=1){var J=Ze(v+4*O,"i32"),ie=Im(J);if(ie===1||ie===2)J=Nm(J);else if(ie===3)J=Om(J);else if(ie===4){ie=J,J=Um(ie),ie=Fm(ie);for(var et=new Uint8Array(J),$e=0;$e<J;$e+=1)et[$e]=x[ie+$e];J=et}else J=null;I.push(J)}return I}function m(b,v){this.Qa=b,this.db=v,this.Oa=1,this.mb=[]}function g(b,v){if(this.db=v,this.fb=ho(b),this.fb===null)throw Error("Unable to allocate memory for the SQL string");this.lb=this.fb,this.$a=this.sb=null}function y(b){if(this.filename="dbfile_"+(4294967295*Math.random()>>>0),b!=null){var v=this.filename,I="/",O=v;if(I&&(I=typeof I=="string"?I:ar(I),O=v?Yt(I+"/"+v):I),v=Qa(!0,!0),O=lm(O,v),b){if(typeof b=="string"){I=Array(b.length);for(var J=0,ie=b.length;J<ie;++J)I[J]=b.charCodeAt(J);b=I}mo(O,v|146),I=Ss(O,577),dl(I,b,0,b.length,0),pr(I),mo(O,v)}}this.handleError(j(this.filename,k)),this.db=Ze(k,"i32"),Ml(this.db),this.gb={},this.Sa={}}var k=ts(4),M=i.cwrap,j=M("sqlite3_open","number",["string","number"]),oe=M("sqlite3_close_v2","number",["number"]),$=M("sqlite3_exec","number",["number","string","number","number","number"]),ge=M("sqlite3_changes","number",["number"]),Pe=M("sqlite3_prepare_v2","number",["number","string","number","number","number"]),_l=M("sqlite3_sql","string",["number"]),hm=M("sqlite3_normalized_sql","string",["number"]),Cl=M("sqlite3_prepare_v2","number",["number","number","number","number","number"]),ym=M("sqlite3_bind_text","number",["number","number","number","number","number"]),bl=M("sqlite3_bind_blob","number",["number","number","number","number","number"]),_m=M("sqlite3_bind_double","number",["number","number","number"]),Cm=M("sqlite3_bind_int","number",["number","number","number"]),bm=M("sqlite3_bind_parameter_index","number",["number","string"]),km=M("sqlite3_step","number",["number"]),Sm=M("sqlite3_errmsg","string",["number"]),Tm=M("sqlite3_column_count","number",["number"]),wm=M("sqlite3_data_count","number",["number"]),Mm=M("sqlite3_column_double","number",["number","number"]),kl=M("sqlite3_column_text","string",["number","number"]),Pm=M("sqlite3_column_blob","number",["number","number"]),vm=M("sqlite3_column_bytes","number",["number","number"]),Am=M("sqlite3_column_type","number",["number","number"]),xm=M("sqlite3_column_name","string",["number","number"]),Dm=M("sqlite3_reset","number",["number"]),Em=M("sqlite3_clear_bindings","number",["number"]),Rm=M("sqlite3_finalize","number",["number"]),Sl=M("sqlite3_create_function_v2","number","number string number number number number number number number".split(" ")),Im=M("sqlite3_value_type","number",["number"]),Um=M("sqlite3_value_bytes","number",["number"]),Om=M("sqlite3_value_text","string",["number"]),Fm=M("sqlite3_value_blob","number",["number"]),Nm=M("sqlite3_value_double","number",["number"]),Lm=M("sqlite3_result_double","",["number","number"]),Tl=M("sqlite3_result_null","",["number"]),jm=M("sqlite3_result_text","",["number","string","number","number"]),Gm=M("sqlite3_result_blob","",["number","number","number","number"]),qm=M("sqlite3_result_int","",["number","number"]),ko=M("sqlite3_result_error","",["number","string","number"]),wl=M("sqlite3_aggregate_context","number",["number","number"]),Ml=M("RegisterExtensionFunctions","number",["number"]),Pl=M("sqlite3_update_hook","number",["number","number","number"]);m.prototype.bind=function(b){if(!this.Qa)throw"Statement closed";return this.reset(),Array.isArray(b)?this.Gb(b):b!=null&&typeof b=="object"?this.Hb(b):!0},m.prototype.step=function(){if(!this.Qa)throw"Statement closed";this.Oa=1;var b=km(this.Qa);switch(b){case 100:return!0;case 101:return!1;default:throw this.db.handleError(b)}},m.prototype.Ab=function(b){return b==null&&(b=this.Oa,this.Oa+=1),Mm(this.Qa,b)},m.prototype.Ob=function(b){if(b==null&&(b=this.Oa,this.Oa+=1),b=kl(this.Qa,b),typeof BigInt!="function")throw Error("BigInt is not supported");return BigInt(b)},m.prototype.Tb=function(b){return b==null&&(b=this.Oa,this.Oa+=1),kl(this.Qa,b)},m.prototype.getBlob=function(b){b==null&&(b=this.Oa,this.Oa+=1);var v=vm(this.Qa,b);b=Pm(this.Qa,b);for(var I=new Uint8Array(v),O=0;O<v;O+=1)I[O]=x[b+O];return I},m.prototype.get=function(b,v){v=v||{},b!=null&&this.bind(b)&&this.step(),b=[];for(var I=wm(this.Qa),O=0;O<I;O+=1)switch(Am(this.Qa,O)){case 1:var J=v.useBigInt?this.Ob(O):this.Ab(O);b.push(J);break;case 2:b.push(this.Ab(O));break;case 3:b.push(this.Tb(O));break;case 4:b.push(this.getBlob(O));break;default:b.push(null)}return b},m.prototype.qb=function(){for(var b=[],v=Tm(this.Qa),I=0;I<v;I+=1)b.push(xm(this.Qa,I));return b},m.prototype.zb=function(b,v){b=this.get(b,v),v=this.qb();for(var I={},O=0;O<v.length;O+=1)I[v[O]]=b[O];return I},m.prototype.Sb=function(){return _l(this.Qa)},m.prototype.Pb=function(){return hm(this.Qa)},m.prototype.run=function(b){return b!=null&&this.bind(b),this.step(),this.reset()},m.prototype.wb=function(b,v){v==null&&(v=this.Oa,this.Oa+=1),b=ho(b),this.mb.push(b),this.db.handleError(ym(this.Qa,v,b,-1,0))},m.prototype.Fb=function(b,v){v==null&&(v=this.Oa,this.Oa+=1);var I=yo(b.length);x.set(b,I),this.mb.push(I),this.db.handleError(bl(this.Qa,v,I,b.length,0))},m.prototype.vb=function(b,v){v==null&&(v=this.Oa,this.Oa+=1),this.db.handleError((b===(b|0)?Cm:_m)(this.Qa,v,b))},m.prototype.Ib=function(b){b==null&&(b=this.Oa,this.Oa+=1),bl(this.Qa,b,0,0,0)},m.prototype.xb=function(b,v){switch(v==null&&(v=this.Oa,this.Oa+=1),typeof b){case"string":this.wb(b,v);return;case"number":this.vb(b,v);return;case"bigint":this.wb(b.toString(),v);return;case"boolean":this.vb(b+0,v);return;case"object":if(b===null){this.Ib(v);return}if(b.length!=null){this.Fb(b,v);return}}throw"Wrong API use : tried to bind a value of an unknown type ("+b+")."},m.prototype.Hb=function(b){var v=this;return Object.keys(b).forEach(function(I){var O=bm(v.Qa,I);O!==0&&v.xb(b[I],O)}),!0},m.prototype.Gb=function(b){for(var v=0;v<b.length;v+=1)this.xb(b[v],v+1);return!0},m.prototype.reset=function(){return this.freemem(),Em(this.Qa)===0&&Dm(this.Qa)===0},m.prototype.freemem=function(){for(var b;(b=this.mb.pop())!==void 0;)Ys(b)},m.prototype.Ya=function(){this.freemem();var b=Rm(this.Qa)===0;return delete this.db.gb[this.Qa],this.Qa=0,b},g.prototype.next=function(){if(this.fb===null)return{done:!0};if(this.$a!==null&&(this.$a.Ya(),this.$a=null),!this.db.db)throw this.ob(),Error("Database closed");var b=Co(),v=ts(4);V(k),V(v);try{this.db.handleError(Cl(this.db.db,this.lb,-1,k,v)),this.lb=Ze(v,"i32");var I=Ze(k,"i32");return I===0?(this.ob(),{done:!0}):(this.$a=new m(I,this.db),this.db.gb[I]=this.$a,{value:this.$a,done:!1})}catch(O){throw this.sb=le(this.lb),this.ob(),O}finally{_o(b)}},g.prototype.ob=function(){Ys(this.fb),this.fb=null},g.prototype.Qb=function(){return this.sb!==null?this.sb:le(this.lb)},typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"&&(g.prototype[Symbol.iterator]=function(){return this}),y.prototype.run=function(b,v){if(!this.db)throw"Database closed";if(v){b=this.tb(b,v);try{b.step()}finally{b.Ya()}}else this.handleError($(this.db,b,0,0,k));return this},y.prototype.exec=function(b,v,I){if(!this.db)throw"Database closed";var O=null,J=null,ie=null;try{ie=J=ho(b);var et=ts(4);for(b=[];Ze(ie,"i8")!==0;){V(k),V(et),this.handleError(Cl(this.db,ie,-1,k,et));var $e=Ze(k,"i32");if(ie=Ze(et,"i32"),$e!==0){var Ne=null;for(O=new m($e,this),v!=null&&O.bind(v);O.step();)Ne===null&&(Ne={columns:O.qb(),values:[]},b.push(Ne)),Ne.values.push(O.get(null,I));O.Ya()}}return b}catch(tt){throw O&&O.Ya(),tt}finally{J&&Ys(J)}},y.prototype.Mb=function(b,v,I,O,J){typeof v=="function"&&(O=I,I=v,v=void 0),b=this.tb(b,v);try{for(;b.step();)I(b.zb(null,J))}finally{b.Ya()}if(typeof O=="function")return O()},y.prototype.tb=function(b,v){if(V(k),this.handleError(Pe(this.db,b,-1,k,0)),b=Ze(k,"i32"),b===0)throw"Nothing to prepare";var I=new m(b,this);return v!=null&&I.bind(v),this.gb[b]=I},y.prototype.Ub=function(b){return new g(b,this)},y.prototype.Nb=function(){Object.values(this.gb).forEach(function(v){v.Ya()}),Object.values(this.Sa).forEach(Ut),this.Sa={},this.handleError(oe(this.db));var b=cm(this.filename);return this.handleError(j(this.filename,k)),this.db=Ze(k,"i32"),Ml(this.db),b},y.prototype.close=function(){this.db!==null&&(Object.values(this.gb).forEach(function(b){b.Ya()}),Object.values(this.Sa).forEach(Ut),this.Sa={},this.Za&&(Ut(this.Za),this.Za=void 0),this.handleError(oe(this.db)),rl("/"+this.filename),this.db=null)},y.prototype.handleError=function(b){if(b===0)return null;throw b=Sm(this.db),Error(b)},y.prototype.Rb=function(){return ge(this.db)},y.prototype.Kb=function(b,v){Object.prototype.hasOwnProperty.call(this.Sa,b)&&(Ut(this.Sa[b]),delete this.Sa[b]);var I=Qs(function(O,J,ie){J=u(J,ie);try{var et=v.apply(null,J)}catch($e){ko(O,$e,-1);return}l(O,et)},"viii");return this.Sa[b]=I,this.handleError(Sl(this.db,b,v.length,1,0,I,0,0,0)),this},y.prototype.Jb=function(b,v){var I=v.init||function(){return null},O=v.finalize||function(Ne){return Ne},J=v.step;if(!J)throw"An aggregate function must have a step function in "+b;var ie={};Object.hasOwnProperty.call(this.Sa,b)&&(Ut(this.Sa[b]),delete this.Sa[b]),v=b+"__finalize",Object.hasOwnProperty.call(this.Sa,v)&&(Ut(this.Sa[v]),delete this.Sa[v]);var et=Qs(function(Ne,tt,br){var ss=wl(Ne,1);Object.hasOwnProperty.call(ie,ss)||(ie[ss]=I()),tt=u(tt,br),tt=[ie[ss]].concat(tt);try{ie[ss]=J.apply(null,tt)}catch(Bm){delete ie[ss],ko(Ne,Bm,-1)}},"viii"),$e=Qs(function(Ne){var tt=wl(Ne,1);try{var br=O(ie[tt])}catch(ss){delete ie[tt],ko(Ne,ss,-1);return}l(Ne,br),delete ie[tt]},"vi");return this.Sa[b]=et,this.Sa[v]=$e,this.handleError(Sl(this.db,b,J.length-1,1,0,0,et,$e,0)),this},y.prototype.Zb=function(b){return this.Za&&(Pl(this.db,0,0),Ut(this.Za),this.Za=void 0),b?(this.Za=Qs(function(v,I,O,J,ie){switch(I){case 18:v="insert";break;case 23:v="update";break;case 9:v="delete";break;default:throw"unknown operationCode in updateHook callback: "+I}if(O=le(O),J=le(J),ie>Number.MAX_SAFE_INTEGER)throw"rowId too big to fit inside a Number";b(v,O,J,Number(ie))},"viiiij"),Pl(this.db,this.Za,0),this):this},m.prototype.bind=m.prototype.bind,m.prototype.step=m.prototype.step,m.prototype.get=m.prototype.get,m.prototype.getColumnNames=m.prototype.qb,m.prototype.getAsObject=m.prototype.zb,m.prototype.getSQL=m.prototype.Sb,m.prototype.getNormalizedSQL=m.prototype.Pb,m.prototype.run=m.prototype.run,m.prototype.reset=m.prototype.reset,m.prototype.freemem=m.prototype.freemem,m.prototype.free=m.prototype.Ya,g.prototype.next=g.prototype.next,g.prototype.getRemainingSQL=g.prototype.Qb,y.prototype.run=y.prototype.run,y.prototype.exec=y.prototype.exec,y.prototype.each=y.prototype.Mb,y.prototype.prepare=y.prototype.tb,y.prototype.iterateStatements=y.prototype.Ub,y.prototype.export=y.prototype.Nb,y.prototype.close=y.prototype.close,y.prototype.handleError=y.prototype.handleError,y.prototype.getRowsModified=y.prototype.Rb,y.prototype.create_function=y.prototype.Kb,y.prototype.create_aggregate=y.prototype.Jb,y.prototype.updateHook=y.prototype.Zb,i.Database=y};var d="./this.program",p=(l,u)=>{throw u},f=globalThis.document?.currentScript?.src;typeof __filename<"u"?f=__filename:a&&(f=self.location.href);var h="",_,C;if(c){var T=require("node:fs");h=__dirname+"/",C=l=>(l=P(l)?new URL(l):l,T.readFileSync(l)),_=async l=>(l=P(l)?new URL(l):l,T.readFileSync(l,void 0)),1<process.argv.length&&(d=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),typeof is<"u"&&(is.exports=i),p=(l,u)=>{throw process.exitCode=l,u}}else if(r||a){try{h=new URL(".",f).href}catch{}a&&(C=l=>{var u=new XMLHttpRequest;return u.open("GET",l,!1),u.responseType="arraybuffer",u.send(null),new Uint8Array(u.response)}),_=async l=>{if(P(l))return new Promise((m,g)=>{var y=new XMLHttpRequest;y.open("GET",l,!0),y.responseType="arraybuffer",y.onload=()=>{y.status==200||y.status==0&&y.response?m(y.response):g(y.status)},y.onerror=g,y.send(null)});var u=await fetch(l,{credentials:"same-origin"});if(u.ok)return u.arrayBuffer();throw Error(u.status+" : "+u.url)}}var E=console.log.bind(console),A=console.error.bind(console),R,B=!1,F,P=l=>l.startsWith("file://"),x,N,ae,ne,se,$s,hs,Oe;function Hs(){var l=bo.buffer;x=new Int8Array(l),ae=new Int16Array(l),N=new Uint8Array(l),new Uint16Array(l),ne=new Int32Array(l),se=new Uint32Array(l),$s=new Float32Array(l),hs=new Float64Array(l),Oe=new BigInt64Array(l),new BigUint64Array(l)}function Et(l){throw i.onAbort?.(l),l="Aborted("+l+")",A(l),B=!0,new WebAssembly.RuntimeError(l+". Build with -sASSERTIONS for more info.")}var Ct;async function oo(l){if(!R)try{var u=await _(l);return new Uint8Array(u)}catch{}if(l==Ct&&R)l=new Uint8Array(R);else if(C)l=C(l);else throw"both async and sync fetching of the wasm failed";return l}async function io(l,u){try{var m=await oo(l);return await WebAssembly.instantiate(m,u)}catch(g){A(`failed to asynchronously prepare wasm: ${g}`),Et(g)}}async function nr(l){var u=Ct;if(!R&&!P(u)&&!c)try{var m=fetch(u,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(m,l)}catch(g){A(`wasm streaming compile failed: ${g}`),A("falling back to ArrayBuffer instantiation")}return io(u,l)}class Qt{name="ExitStatus";constructor(u){this.message=`Program terminated with exit(${u})`,this.status=u}}var ys=l=>{for(;0<l.length;)l.shift()(i)},or=[],ro=[],Ws=()=>{var l=i.preRun.shift();ro.push(l)},Xe=0,_s=null;function Ze(l,u="i8"){switch(u.endsWith("*")&&(u="*"),u){case"i1":return x[l];case"i8":return x[l];case"i16":return ae[l>>1];case"i32":return ne[l>>2];case"i64":return Oe[l>>3];case"float":return $s[l>>2];case"double":return hs[l>>3];case"*":return se[l>>2];default:Et(`invalid type for getValue: ${u}`)}}var U=!0;function V(l){var u="i32";switch(u.endsWith("*")&&(u="*"),u){case"i1":x[l]=0;break;case"i8":x[l]=0;break;case"i16":ae[l>>1]=0;break;case"i32":ne[l>>2]=0;break;case"i64":Oe[l>>3]=BigInt(0);break;case"float":$s[l>>2]=0;break;case"double":hs[l>>3]=0;break;case"*":se[l>>2]=0;break;default:Et(`invalid type for setValue: ${u}`)}}var _e=new TextDecoder,be=(l,u,m,g)=>{if(m=u+m,g)return m;for(;l[u]&&!(u>=m);)++u;return u},le=(l,u,m)=>l?_e.decode(N.subarray(l,be(N,l,u,m))):"",ct=(l,u)=>{for(var m=0,g=l.length-1;0<=g;g--){var y=l[g];y==="."?l.splice(g,1):y===".."?(l.splice(g,1),m++):m&&(l.splice(g,1),m--)}if(u)for(;m;m--)l.unshift("..");return l},Yt=l=>{var u=l.charAt(0)==="/",m=l.slice(-1)==="/";return(l=ct(l.split("/").filter(g=>!!g),!u).join("/"))||u||(l="."),l&&m&&(l+="/"),(u?"/":"")+l},ut=l=>{var u=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(l).slice(1);return l=u[0],u=u[1],!l&&!u?".":(u&&=u.slice(0,-1),l+u)},Fe=l=>l&&l.match(/([^\/]+|\/)\/*$/)[1],ao=()=>{if(c){var l=require("node:crypto");return u=>l.randomFillSync(u)}return u=>crypto.getRandomValues(u)},Ja=l=>{(Ja=ao())(l)},Zd=(...l)=>{for(var u="",m=!1,g=l.length-1;-1<=g&&!m;g--){if(m=0<=g?l[g]:"/",typeof m!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!m)return"";u=m+"/"+u,m=m.charAt(0)==="/"}return u=ct(u.split("/").filter(y=>!!y),!m).join("/"),(m?"/":"")+u||"."},Js=l=>{var u=be(l,0);return _e.decode(l.buffer?l.subarray(0,u):new Uint8Array(l.slice(0,u)))},ir=[],Cs=l=>{for(var u=0,m=0;m<l.length;++m){var g=l.charCodeAt(m);127>=g?u++:2047>=g?u+=2:55296<=g&&57343>=g?(u+=4,++m):u+=3}return u},dt=(l,u,m,g)=>{if(!(0<g))return 0;var y=m;g=m+g-1;for(var k=0;k<l.length;++k){var M=l.codePointAt(k);if(127>=M){if(m>=g)break;u[m++]=M}else if(2047>=M){if(m+1>=g)break;u[m++]=192|M>>6,u[m++]=128|M&63}else if(65535>=M){if(m+2>=g)break;u[m++]=224|M>>12,u[m++]=128|M>>6&63,u[m++]=128|M&63}else{if(m+3>=g)break;u[m++]=240|M>>18,u[m++]=128|M>>12&63,u[m++]=128|M>>6&63,u[m++]=128|M&63,k++}}return u[m]=0,m-y},Va=[];function Ka(l,u){Va[l]={input:[],output:[],eb:u},dr(l,em)}var em={open(l){var u=Va[l.node.rdev];if(!u)throw new D(43);l.tty=u,l.seekable=!1},close(l){l.tty.eb.fsync(l.tty)},fsync(l){l.tty.eb.fsync(l.tty)},read(l,u,m,g){if(!l.tty||!l.tty.eb.Bb)throw new D(60);for(var y=0,k=0;k<g;k++){try{var M=l.tty.eb.Bb(l.tty)}catch{throw new D(29)}if(M===void 0&&y===0)throw new D(6);if(M==null)break;y++,u[m+k]=M}return y&&(l.node.atime=Date.now()),y},write(l,u,m,g){if(!l.tty||!l.tty.eb.ub)throw new D(60);try{for(var y=0;y<g;y++)l.tty.eb.ub(l.tty,u[m+y])}catch{throw new D(29)}return g&&(l.node.mtime=l.node.ctime=Date.now()),y}},tm={Bb(){e:{if(!ir.length){var l=null;if(c){var u=Buffer.alloc(256),m=0,g=process.stdin.fd;try{m=T.readSync(g,u,0,256)}catch(y){if(y.toString().includes("EOF"))m=0;else throw y}0<m&&(l=u.slice(0,m).toString("utf-8"))}else globalThis.window?.prompt&&(l=window.prompt("Input: "),l!==null&&(l+=`
|
|
3
|
+
`));if(!l){l=null;break e}u=Array(Cs(l)+1),l=dt(l,u,0,u.length),u.length=l,ir=u}l=ir.shift()}return l},ub(l,u){u===null||u===10?(E(Js(l.output)),l.output=[]):u!=0&&l.output.push(u)},fsync(l){0<l.output?.length&&(E(Js(l.output)),l.output=[])},hc(){return{bc:25856,dc:5,ac:191,cc:35387,$b:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ic(){return 0},jc(){return[24,80]}},sm={ub(l,u){u===null||u===10?(A(Js(l.output)),l.output=[]):u!=0&&l.output.push(u)},fsync(l){0<l.output?.length&&(A(Js(l.output)),l.output=[])}},q={Wa:null,Xa(){return q.createNode(null,"/",16895,0)},createNode(l,u,m,g){if((m&61440)===24576||(m&61440)===4096)throw new D(63);return q.Wa||(q.Wa={dir:{node:{Ta:q.La.Ta,Ua:q.La.Ua,lookup:q.La.lookup,ib:q.La.ib,rename:q.La.rename,unlink:q.La.unlink,rmdir:q.La.rmdir,readdir:q.La.readdir,symlink:q.La.symlink},stream:{Va:q.Ma.Va}},file:{node:{Ta:q.La.Ta,Ua:q.La.Ua},stream:{Va:q.Ma.Va,read:q.Ma.read,write:q.Ma.write,jb:q.Ma.jb,kb:q.Ma.kb}},link:{node:{Ta:q.La.Ta,Ua:q.La.Ua,readlink:q.La.readlink},stream:{}},yb:{node:{Ta:q.La.Ta,Ua:q.La.Ua},stream:am}}),m=el(l,u,m,g),Re(m.mode)?(m.La=q.Wa.dir.node,m.Ma=q.Wa.dir.stream,m.Na={}):(m.mode&61440)===32768?(m.La=q.Wa.file.node,m.Ma=q.Wa.file.stream,m.Ra=0,m.Na=null):(m.mode&61440)===40960?(m.La=q.Wa.link.node,m.Ma=q.Wa.link.stream):(m.mode&61440)===8192&&(m.La=q.Wa.yb.node,m.Ma=q.Wa.yb.stream),m.atime=m.mtime=m.ctime=Date.now(),l&&(l.Na[u]=m,l.atime=l.mtime=l.ctime=m.atime),m},fc(l){return l.Na?l.Na.subarray?l.Na.subarray(0,l.Ra):new Uint8Array(l.Na):new Uint8Array(0)},La:{Ta(l){var u={};return u.dev=(l.mode&61440)===8192?l.id:1,u.ino=l.id,u.mode=l.mode,u.nlink=1,u.uid=0,u.gid=0,u.rdev=l.rdev,Re(l.mode)?u.size=4096:(l.mode&61440)===32768?u.size=l.Ra:(l.mode&61440)===40960?u.size=l.link.length:u.size=0,u.atime=new Date(l.atime),u.mtime=new Date(l.mtime),u.ctime=new Date(l.ctime),u.blksize=4096,u.blocks=Math.ceil(u.size/u.blksize),u},Ua(l,u){for(var m of["mode","atime","mtime","ctime"])u[m]!=null&&(l[m]=u[m]);u.size!==void 0&&(u=u.size,l.Ra!=u&&(u==0?(l.Na=null,l.Ra=0):(m=l.Na,l.Na=new Uint8Array(u),m&&l.Na.set(m.subarray(0,Math.min(u,l.Ra))),l.Ra=u)))},lookup(){throw q.nb||(q.nb=new D(44),q.nb.stack="<generic error, no stack>"),q.nb},ib(l,u,m,g){return q.createNode(l,u,m,g)},rename(l,u,m){try{var g=Xt(u,m)}catch{}if(g){if(Re(l.mode))for(var y in g.Na)throw new D(55);cr(g)}delete l.parent.Na[l.name],u.Na[m]=l,l.name=m,u.ctime=u.mtime=l.parent.ctime=l.parent.mtime=Date.now()},unlink(l,u){delete l.Na[u],l.ctime=l.mtime=Date.now()},rmdir(l,u){var m=Xt(l,u),g;for(g in m.Na)throw new D(55);delete l.Na[u],l.ctime=l.mtime=Date.now()},readdir(l){return[".","..",...Object.keys(l.Na)]},symlink(l,u,m){return l=q.createNode(l,u,41471,0),l.link=m,l},readlink(l){if((l.mode&61440)!==40960)throw new D(28);return l.link}},Ma:{read(l,u,m,g,y){var k=l.node.Na;if(y>=l.node.Ra)return 0;if(l=Math.min(l.node.Ra-y,g),8<l&&k.subarray)u.set(k.subarray(y,y+l),m);else for(g=0;g<l;g++)u[m+g]=k[y+g];return l},write(l,u,m,g,y,k){if(u.buffer===x.buffer&&(k=!1),!g)return 0;if(l=l.node,l.mtime=l.ctime=Date.now(),u.subarray&&(!l.Na||l.Na.subarray)){if(k)return l.Na=u.subarray(m,m+g),l.Ra=g;if(l.Ra===0&&y===0)return l.Na=u.slice(m,m+g),l.Ra=g;if(y+g<=l.Ra)return l.Na.set(u.subarray(m,m+g),y),g}k=y+g;var M=l.Na?l.Na.length:0;if(M>=k||(k=Math.max(k,M*(1048576>M?2:1.125)>>>0),M!=0&&(k=Math.max(k,256)),M=l.Na,l.Na=new Uint8Array(k),0<l.Ra&&l.Na.set(M.subarray(0,l.Ra),0)),l.Na.subarray&&u.subarray)l.Na.set(u.subarray(m,m+g),y);else for(k=0;k<g;k++)l.Na[y+k]=u[m+k];return l.Ra=Math.max(l.Ra,y+g),g},Va(l,u,m){if(m===1?u+=l.position:m===2&&(l.node.mode&61440)===32768&&(u+=l.node.Ra),0>u)throw new D(28);return u},jb(l,u,m,g,y){if((l.node.mode&61440)!==32768)throw new D(43);if(l=l.node.Na,y&2||!l||l.buffer!==x.buffer){y=!0,g=65536*Math.ceil(u/65536);var k=hl(65536,g);if(k&&N.fill(0,k,k+g),g=k,!g)throw new D(48);l&&((0<m||m+u<l.length)&&(l.subarray?l=l.subarray(m,m+u):l=Array.prototype.slice.call(l,m,m+u)),x.set(l,g))}else y=!1,g=l.byteOffset;return{Xb:g,Eb:y}},kb(l,u,m,g){return q.Ma.write(l,u,0,g,m,!1),0}}},Qa=(l,u)=>{var m=0;return l&&(m|=365),u&&(m|=146),m},rr=null,Ya={},bs=[],nm=1,Rt=null,Xa=!1,Za=!0,D=class{name="ErrnoError";constructor(l){this.Pa=l}},om=class{hb={};node=null;get flags(){return this.hb.flags}set flags(l){this.hb.flags=l}get position(){return this.hb.position}set position(l){this.hb.position=l}},im=class{La={};Ma={};bb=null;constructor(l,u,m,g){l||=this,this.parent=l,this.Xa=l.Xa,this.id=nm++,this.name=u,this.mode=m,this.rdev=g,this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&365)===365}set read(l){l?this.mode|=365:this.mode&=-366}get write(){return(this.mode&146)===146}set write(l){l?this.mode|=146:this.mode&=-147}};function ze(l,u={}){if(!l)throw new D(44);u.pb??(u.pb=!0),l.charAt(0)==="/"||(l="//"+l);var m=0;e:for(;40>m;m++){l=l.split("/").filter(j=>!!j);for(var g=rr,y="/",k=0;k<l.length;k++){var M=k===l.length-1;if(M&&u.parent)break;if(l[k]!==".")if(l[k]==="..")if(y=ut(y),g===g.parent){l=y+"/"+l.slice(k+1).join("/"),m--;continue e}else g=g.parent;else{y=Yt(y+"/"+l[k]);try{g=Xt(g,l[k])}catch(j){if(j?.Pa===44&&M&&u.Wb)return{path:y};throw j}if(!g.bb||M&&!u.pb||(g=g.bb.root),(g.mode&61440)===40960&&(!M||u.ab)){if(!g.La.readlink)throw new D(52);g=g.La.readlink(g),g.charAt(0)==="/"||(g=ut(y)+"/"+g),l=g+"/"+l.slice(k+1).join("/");continue e}}}return{path:y,node:g}}throw new D(32)}function ar(l){for(var u;;){if(l===l.parent)return l=l.Xa.Db,u?l[l.length-1]!=="/"?`${l}/${u}`:l+u:l;u=u?`${l.name}/${u}`:l.name,l=l.parent}}function lr(l,u){for(var m=0,g=0;g<u.length;g++)m=(m<<5)-m+u.charCodeAt(g)|0;return(l+m>>>0)%Rt.length}function cr(l){var u=lr(l.parent.id,l.name);if(Rt[u]===l)Rt[u]=l.cb;else for(u=Rt[u];u;){if(u.cb===l){u.cb=l.cb;break}u=u.cb}}function Xt(l,u){var m=Re(l.mode)?(m=ks(l,"x"))?m:l.La.lookup?0:2:54;if(m)throw new D(m);for(m=Rt[lr(l.id,u)];m;m=m.cb){var g=m.name;if(m.parent.id===l.id&&g===u)return m}return l.La.lookup(l,u)}function el(l,u,m,g){return l=new im(l,u,m,g),u=lr(l.parent.id,l.name),l.cb=Rt[u],Rt[u]=l}function Re(l){return(l&61440)===16384}function ks(l,u){return Za?0:u.includes("r")&&!(l.mode&292)||u.includes("w")&&!(l.mode&146)||u.includes("x")&&!(l.mode&73)?2:0}function tl(l,u){if(!Re(l.mode))return 54;try{return Xt(l,u),20}catch{}return ks(l,"wx")}function sl(l,u,m){try{var g=Xt(l,u)}catch(y){return y.Pa}if(l=ks(l,"wx"))return l;if(m){if(!Re(g.mode))return 54;if(g===g.parent||ar(g)==="/")return 10}else if(Re(g.mode))return 31;return 0}function lo(l){if(!l)throw new D(63);return l}function xe(l){if(l=bs[l],!l)throw new D(8);return l}function nl(l,u=-1){if(l=Object.assign(new om,l),u==-1)e:{for(u=0;4096>=u;u++)if(!bs[u])break e;throw new D(33)}return l.fd=u,bs[u]=l}function rm(l,u=-1){return l=nl(l,u),l.Ma?.ec?.(l),l}function ur(l,u,m){var g=l?.Ma.Ua;l=g?l:u,g??=u.La.Ua,lo(g),g(l,m)}var am={open(l){l.Ma=Ya[l.node.rdev].Ma,l.Ma.open?.(l)},Va(){throw new D(70)}};function dr(l,u){Ya[l]={Ma:u}}function ol(l,u){var m=u==="/";if(m&&rr)throw new D(10);if(!m&&u){var g=ze(u,{pb:!1});if(u=g.path,g=g.node,g.bb)throw new D(10);if(!Re(g.mode))throw new D(54)}u={type:l,kc:{},Db:u,Vb:[]},l=l.Xa(u),l.Xa=u,u.root=l,m?rr=l:g&&(g.bb=u,g.Xa&&g.Xa.Vb.push(u))}function co(l,u,m){var g=ze(l,{parent:!0}).node;if(l=Fe(l),!l)throw new D(28);if(l==="."||l==="..")throw new D(20);var y=tl(g,l);if(y)throw new D(y);if(!g.La.ib)throw new D(63);return g.La.ib(g,l,u,m)}function lm(l,u=438){return co(l,u&4095|32768,0)}function mt(l,u=511){return co(l,u&1023|16384,0)}function uo(l,u,m){typeof m>"u"&&(m=u,u=438),co(l,u|8192,m)}function mr(l,u){if(!Zd(l))throw new D(44);var m=ze(u,{parent:!0}).node;if(!m)throw new D(44);u=Fe(u);var g=tl(m,u);if(g)throw new D(g);if(!m.La.symlink)throw new D(63);m.La.symlink(m,u,l)}function il(l){var u=ze(l,{parent:!0}).node;l=Fe(l);var m=Xt(u,l),g=sl(u,l,!0);if(g)throw new D(g);if(!u.La.rmdir)throw new D(63);if(m.bb)throw new D(10);u.La.rmdir(u,l),cr(m)}function rl(l){var u=ze(l,{parent:!0}).node;if(!u)throw new D(44);l=Fe(l);var m=Xt(u,l),g=sl(u,l,!1);if(g)throw new D(g);if(!u.La.unlink)throw new D(63);if(m.bb)throw new D(10);u.La.unlink(u,l),cr(m)}function Vs(l,u){return l=ze(l,{ab:!u}).node,lo(l.La.Ta)(l)}function al(l,u,m,g){ur(l,u,{mode:m&4095|u.mode&-4096,ctime:Date.now(),Lb:g})}function mo(l,u){l=typeof l=="string"?ze(l,{ab:!0}).node:l,al(null,l,u)}function ll(l,u,m){if(Re(u.mode))throw new D(31);if((u.mode&61440)!==32768)throw new D(28);var g=ks(u,"w");if(g)throw new D(g);ur(l,u,{size:m,timestamp:Date.now()})}function Ss(l,u,m=438){if(l==="")throw new D(44);if(typeof u=="string"){var g={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[u];if(typeof g>"u")throw Error(`Unknown file open mode: ${u}`);u=g}if(m=u&64?m&4095|32768:0,typeof l=="object")g=l;else{var y=l.endsWith("/"),k=ze(l,{ab:!(u&131072),Wb:!0});g=k.node,l=k.path}if(k=!1,u&64)if(g){if(u&128)throw new D(20)}else{if(y)throw new D(31);g=co(l,m|511,0),k=!0}if(!g)throw new D(44);if((g.mode&61440)===8192&&(u&=-513),u&65536&&!Re(g.mode))throw new D(54);if(!k&&(g?(g.mode&61440)===40960?y=32:(y=["r","w","rw"][u&3],u&512&&(y+="w"),y=Re(g.mode)&&(y!=="r"||u&576)?31:ks(g,y)):y=44,y))throw new D(y);return u&512&&!k&&(y=g,y=typeof y=="string"?ze(y,{ab:!0}).node:y,ll(null,y,0)),u=nl({node:g,path:ar(g),flags:u&-131713,seekable:!0,position:0,Ma:g.Ma,Yb:[],error:!1}),u.Ma.open&&u.Ma.open(u),k&&mo(g,m&511),u}function pr(l){if(l.fd===null)throw new D(8);l.rb&&(l.rb=null);try{l.Ma.close&&l.Ma.close(l)}catch(u){throw u}finally{bs[l.fd]=null}l.fd=null}function cl(l,u,m){if(l.fd===null)throw new D(8);if(!l.seekable||!l.Ma.Va)throw new D(70);if(m!=0&&m!=1&&m!=2)throw new D(28);l.position=l.Ma.Va(l,u,m),l.Yb=[]}function ul(l,u,m,g,y){if(0>g||0>y)throw new D(28);if(l.fd===null)throw new D(8);if((l.flags&2097155)===1)throw new D(8);if(Re(l.node.mode))throw new D(31);if(!l.Ma.read)throw new D(28);var k=typeof y<"u";if(!k)y=l.position;else if(!l.seekable)throw new D(70);return u=l.Ma.read(l,u,m,g,y),k||(l.position+=u),u}function dl(l,u,m,g,y){if(0>g||0>y)throw new D(28);if(l.fd===null)throw new D(8);if((l.flags&2097155)===0)throw new D(8);if(Re(l.node.mode))throw new D(31);if(!l.Ma.write)throw new D(28);l.seekable&&l.flags&1024&&cl(l,0,2);var k=typeof y<"u";if(!k)y=l.position;else if(!l.seekable)throw new D(70);return u=l.Ma.write(l,u,m,g,y,void 0),k||(l.position+=u),u}function cm(l){var u=u||0,m="binary";m!=="utf8"&&m!=="binary"&&Et(`Invalid encoding type "${m}"`),u=Ss(l,u),l=Vs(l).size;var g=new Uint8Array(l);return ul(u,g,0,l,0),m==="utf8"&&(g=Js(g)),pr(u),g}function It(l,u,m){l=Yt("/dev/"+l);var g=Qa(!!u,!!m);It.Cb??(It.Cb=64);var y=It.Cb++<<8|0;dr(y,{open(k){k.seekable=!1},close(){m?.buffer?.length&&m(10)},read(k,M,j,oe){for(var $=0,ge=0;ge<oe;ge++){try{var Pe=u()}catch{throw new D(29)}if(Pe===void 0&&$===0)throw new D(6);if(Pe==null)break;$++,M[j+ge]=Pe}return $&&(k.node.atime=Date.now()),$},write(k,M,j,oe){for(var $=0;$<oe;$++)try{m(M[j+$])}catch{throw new D(29)}return oe&&(k.node.mtime=k.node.ctime=Date.now()),$}}),uo(l,g,y)}var pe={};function Zt(l,u,m){if(u.charAt(0)==="/")return u;if(l=l===-100?"/":xe(l).path,u.length==0){if(!m)throw new D(44);return l}return l+"/"+u}function po(l,u){se[l>>2]=u.dev,se[l+4>>2]=u.mode,se[l+8>>2]=u.nlink,se[l+12>>2]=u.uid,se[l+16>>2]=u.gid,se[l+20>>2]=u.rdev,Oe[l+24>>3]=BigInt(u.size),ne[l+32>>2]=4096,ne[l+36>>2]=u.blocks;var m=u.atime.getTime(),g=u.mtime.getTime(),y=u.ctime.getTime();return Oe[l+40>>3]=BigInt(Math.floor(m/1e3)),se[l+48>>2]=m%1e3*1e6,Oe[l+56>>3]=BigInt(Math.floor(g/1e3)),se[l+64>>2]=g%1e3*1e6,Oe[l+72>>3]=BigInt(Math.floor(y/1e3)),se[l+80>>2]=y%1e3*1e6,Oe[l+88>>3]=BigInt(u.ino),0}var go=void 0,fo=()=>{var l=ne[+go>>2];return go+=4,l},gr=0,um=[0,31,60,91,121,152,182,213,244,274,305,335],dm=[0,31,59,90,120,151,181,212,243,273,304,334],Ks={},ml=l=>{F=l,U||0<gr||(i.onExit?.(l),B=!0),p(l,new Qt(l))},mm=l=>{if(!B)try{l()}catch(u){u instanceof Qt||u=="unwind"||p(1,u)}finally{if(!(U||0<gr))try{F=l=F,ml(l)}catch(u){u instanceof Qt||u=="unwind"||p(1,u)}}},fr={},pl=()=>{if(!hr){var l={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:d||"./this.program"},u;for(u in fr)fr[u]===void 0?delete l[u]:l[u]=fr[u];var m=[];for(u in l)m.push(`${u}=${l[u]}`);hr=m}return hr},hr,pm=(l,u,m,g)=>{var y={string:$=>{var ge=0;if($!=null&&$!==0){ge=Cs($)+1;var Pe=ts(ge);dt($,N,Pe,ge),ge=Pe}return ge},array:$=>{var ge=ts($.length);return x.set($,ge),ge}};l=i["_"+l];var k=[],M=0;if(g)for(var j=0;j<g.length;j++){var oe=y[m[j]];oe?(M===0&&(M=Co()),k[j]=oe(g[j])):k[j]=g[j]}return m=l(...k),m=(function($){return M!==0&&_o(M),u==="string"?le($):u==="boolean"?!!$:$})(m)},ho=l=>{var u=Cs(l)+1,m=yo(u);return m&&dt(l,N,m,u),m},es,yr=[],Ut=l=>{es.delete(Ot.get(l)),Ot.set(l,null),yr.push(l)},gl=l=>{let u=l.length;return[u%128|128,u>>7,...l]},gm={i:127,p:127,j:126,f:125,d:124,e:111},fl=l=>gl(Array.from(l,u=>gm[u])),Qs=(l,u)=>{if(!es){es=new WeakMap;var m=Ot.length;if(es)for(var g=0;g<0+m;g++){var y=Ot.get(g);y&&es.set(y,g)}}if(m=es.get(l)||0)return m;m=yr.length?yr.pop():Ot.grow(1);try{Ot.set(m,l)}catch(k){if(!(k instanceof TypeError))throw k;u=Uint8Array.of(0,97,115,109,1,0,0,0,1,...gl([1,96,...fl(u.slice(1)),...fl(u[0]==="v"?"":u[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),u=new WebAssembly.Module(u),u=new WebAssembly.Instance(u,{e:{f:l}}).exports.f,Ot.set(m,u)}return es.set(l,m),m};if(Rt=Array(4096),ol(q,"/"),mt("/tmp"),mt("/home"),mt("/home/web_user"),(function(){mt("/dev"),dr(259,{read:()=>0,write:(g,y,k,M)=>M,Va:()=>0}),uo("/dev/null",259),Ka(1280,tm),Ka(1536,sm),uo("/dev/tty",1280),uo("/dev/tty1",1536);var l=new Uint8Array(1024),u=0,m=()=>(u===0&&(Ja(l),u=l.byteLength),l[--u]);It("random",m),It("urandom",m),mt("/dev/shm"),mt("/dev/shm/tmp")})(),(function(){mt("/proc");var l=mt("/proc/self");mt("/proc/self/fd"),ol({Xa(){var u=el(l,"fd",16895,73);return u.Ma={Va:q.Ma.Va},u.La={lookup(m,g){m=+g;var y=xe(m);return m={parent:null,Xa:{Db:"fake"},La:{readlink:()=>y.path},id:m+1},m.parent=m},readdir(){return Array.from(bs.entries()).filter(([,m])=>m).map(([m])=>m.toString())}},u}},"/proc/self/fd")})(),i.noExitRuntime&&(U=i.noExitRuntime),i.print&&(E=i.print),i.printErr&&(A=i.printErr),i.wasmBinary&&(R=i.wasmBinary),i.thisProgram&&(d=i.thisProgram),i.preInit)for(typeof i.preInit=="function"&&(i.preInit=[i.preInit]);0<i.preInit.length;)i.preInit.shift()();i.stackSave=()=>Co(),i.stackRestore=l=>_o(l),i.stackAlloc=l=>ts(l),i.cwrap=(l,u,m,g)=>{var y=!m||m.every(k=>k==="number"||k==="boolean");return u!=="string"&&y&&!g?i["_"+l]:(...k)=>pm(l,u,m,k)},i.addFunction=Qs,i.removeFunction=Ut,i.UTF8ToString=le,i.stringToNewUTF8=ho,i.writeArrayToMemory=(l,u)=>{x.set(l,u)};var yo,Ys,hl,yl,_o,ts,Co,bo,Ot,fm={a:(l,u,m,g)=>Et(`Assertion failed: ${le(l)}, at: `+[u?le(u):"unknown filename",m,g?le(g):"unknown function"]),i:function(l,u){try{return l=le(l),mo(l,u),0}catch(m){if(typeof pe>"u"||m.name!=="ErrnoError")throw m;return-m.Pa}},L:function(l,u,m){try{if(u=le(u),u=Zt(l,u),m&-8)return-28;var g=ze(u,{ab:!0}).node;return g?(l="",m&4&&(l+="r"),m&2&&(l+="w"),m&1&&(l+="x"),l&&ks(g,l)?-2:0):-44}catch(y){if(typeof pe>"u"||y.name!=="ErrnoError")throw y;return-y.Pa}},j:function(l,u){try{var m=xe(l);return al(m,m.node,u,!1),0}catch(g){if(typeof pe>"u"||g.name!=="ErrnoError")throw g;return-g.Pa}},h:function(l){try{var u=xe(l);return ur(u,u.node,{timestamp:Date.now(),Lb:!1}),0}catch(m){if(typeof pe>"u"||m.name!=="ErrnoError")throw m;return-m.Pa}},b:function(l,u,m){go=m;try{var g=xe(l);switch(u){case 0:var y=fo();if(0>y)break;for(;bs[y];)y++;return rm(g,y).fd;case 1:case 2:return 0;case 3:return g.flags;case 4:return y=fo(),g.flags|=y,0;case 12:return y=fo(),ae[y+0>>1]=2,0;case 13:case 14:return 0}return-28}catch(k){if(typeof pe>"u"||k.name!=="ErrnoError")throw k;return-k.Pa}},g:function(l,u){try{var m=xe(l),g=m.node,y=m.Ma.Ta;l=y?m:g,y??=g.La.Ta,lo(y);var k=y(l);return po(u,k)}catch(M){if(typeof pe>"u"||M.name!=="ErrnoError")throw M;return-M.Pa}},H:function(l,u){u=-9007199254740992>u||9007199254740992<u?NaN:Number(u);try{if(isNaN(u))return-61;var m=xe(l);if(0>u||(m.flags&2097155)===0)throw new D(28);return ll(m,m.node,u),0}catch(g){if(typeof pe>"u"||g.name!=="ErrnoError")throw g;return-g.Pa}},G:function(l,u){try{if(u===0)return-28;var m=Cs("/")+1;return u<m?-68:(dt("/",N,l,u),m)}catch(g){if(typeof pe>"u"||g.name!=="ErrnoError")throw g;return-g.Pa}},K:function(l,u){try{return l=le(l),po(u,Vs(l,!0))}catch(m){if(typeof pe>"u"||m.name!=="ErrnoError")throw m;return-m.Pa}},C:function(l,u,m){try{return u=le(u),u=Zt(l,u),mt(u,m),0}catch(g){if(typeof pe>"u"||g.name!=="ErrnoError")throw g;return-g.Pa}},J:function(l,u,m,g){try{u=le(u);var y=g&256;return u=Zt(l,u,g&4096),po(m,y?Vs(u,!0):Vs(u))}catch(k){if(typeof pe>"u"||k.name!=="ErrnoError")throw k;return-k.Pa}},x:function(l,u,m,g){go=g;try{u=le(u),u=Zt(l,u);var y=g?fo():0;return Ss(u,m,y).fd}catch(k){if(typeof pe>"u"||k.name!=="ErrnoError")throw k;return-k.Pa}},v:function(l,u,m,g){try{if(u=le(u),u=Zt(l,u),0>=g)return-28;var y=ze(u).node;if(!y)throw new D(44);if(!y.La.readlink)throw new D(28);var k=y.La.readlink(y),M=Math.min(g,Cs(k)),j=x[m+M];return dt(k,N,m,g+1),x[m+M]=j,M}catch(oe){if(typeof pe>"u"||oe.name!=="ErrnoError")throw oe;return-oe.Pa}},u:function(l){try{return l=le(l),il(l),0}catch(u){if(typeof pe>"u"||u.name!=="ErrnoError")throw u;return-u.Pa}},f:function(l,u){try{return l=le(l),po(u,Vs(l))}catch(m){if(typeof pe>"u"||m.name!=="ErrnoError")throw m;return-m.Pa}},r:function(l,u,m){try{if(u=le(u),u=Zt(l,u),m)if(m===512)il(u);else return-28;else rl(u);return 0}catch(g){if(typeof pe>"u"||g.name!=="ErrnoError")throw g;return-g.Pa}},q:function(l,u,m){try{u=le(u),u=Zt(l,u,!0);var g=Date.now(),y,k;if(m){var M=se[m>>2]+4294967296*ne[m+4>>2],j=ne[m+8>>2];j==1073741823?y=g:j==1073741822?y=null:y=1e3*M+j/1e6,m+=16,M=se[m>>2]+4294967296*ne[m+4>>2],j=ne[m+8>>2],j==1073741823?k=g:j==1073741822?k=null:k=1e3*M+j/1e6}else k=y=g;if((k??y)!==null){l=y;var oe=ze(u,{ab:!0}).node;lo(oe.La.Ua)(oe,{atime:l,mtime:k})}return 0}catch($){if(typeof pe>"u"||$.name!=="ErrnoError")throw $;return-$.Pa}},m:()=>Et(""),l:()=>{U=!1,gr=0},A:function(l,u){l=-9007199254740992>l||9007199254740992<l?NaN:Number(l),l=new Date(1e3*l),ne[u>>2]=l.getSeconds(),ne[u+4>>2]=l.getMinutes(),ne[u+8>>2]=l.getHours(),ne[u+12>>2]=l.getDate(),ne[u+16>>2]=l.getMonth(),ne[u+20>>2]=l.getFullYear()-1900,ne[u+24>>2]=l.getDay();var m=l.getFullYear();ne[u+28>>2]=(m%4!==0||m%100===0&&m%400!==0?dm:um)[l.getMonth()]+l.getDate()-1|0,ne[u+36>>2]=-(60*l.getTimezoneOffset()),m=new Date(l.getFullYear(),6,1).getTimezoneOffset();var g=new Date(l.getFullYear(),0,1).getTimezoneOffset();ne[u+32>>2]=(m!=g&&l.getTimezoneOffset()==Math.min(g,m))|0},y:function(l,u,m,g,y,k,M){y=-9007199254740992>y||9007199254740992<y?NaN:Number(y);try{var j=xe(g);if((u&2)!==0&&(m&2)===0&&(j.flags&2097155)!==2)throw new D(2);if((j.flags&2097155)===1)throw new D(2);if(!j.Ma.jb)throw new D(43);if(!l)throw new D(28);var oe=j.Ma.jb(j,l,y,u,m),$=oe.Xb;return ne[k>>2]=oe.Eb,se[M>>2]=$,0}catch(ge){if(typeof pe>"u"||ge.name!=="ErrnoError")throw ge;return-ge.Pa}},z:function(l,u,m,g,y,k){k=-9007199254740992>k||9007199254740992<k?NaN:Number(k);try{var M=xe(y);if(m&2){if(m=k,(M.node.mode&61440)!==32768)throw new D(43);if(!(g&2)){var j=N.slice(l,l+u);M.Ma.kb&&M.Ma.kb(M,j,m,u,g)}}}catch(oe){if(typeof pe>"u"||oe.name!=="ErrnoError")throw oe;return-oe.Pa}},n:(l,u)=>{if(Ks[l]&&(clearTimeout(Ks[l].id),delete Ks[l]),!u)return 0;var m=setTimeout(()=>{delete Ks[l],mm(()=>yl(l,performance.now()))},u);return Ks[l]={id:m,lc:u},0},B:(l,u,m,g)=>{var y=new Date().getFullYear(),k=new Date(y,0,1).getTimezoneOffset();y=new Date(y,6,1).getTimezoneOffset(),se[l>>2]=60*Math.max(k,y),ne[u>>2]=+(k!=y),u=M=>{var j=Math.abs(M);return`UTC${0<=M?"-":"+"}${String(Math.floor(j/60)).padStart(2,"0")}${String(j%60).padStart(2,"0")}`},l=u(k),u=u(y),y<k?(dt(l,N,m,17),dt(u,N,g,17)):(dt(l,N,g,17),dt(u,N,m,17))},d:()=>Date.now(),s:()=>2147483648,c:()=>performance.now(),o:l=>{var u=N.length;if(l>>>=0,2147483648<l)return!1;for(var m=1;4>=m;m*=2){var g=u*(1+.2/m);g=Math.min(g,l+100663296);e:{g=(Math.min(2147483648,65536*Math.ceil(Math.max(l,g)/65536))-bo.buffer.byteLength+65535)/65536|0;try{bo.grow(g),Hs();var y=1;break e}catch{}y=void 0}if(y)return!0}return!1},E:(l,u)=>{var m=0,g=0,y;for(y of pl()){var k=u+m;se[l+g>>2]=k,m+=dt(y,N,k,1/0)+1,g+=4}return 0},F:(l,u)=>{var m=pl();se[l>>2]=m.length,l=0;for(var g of m)l+=Cs(g)+1;return se[u>>2]=l,0},e:function(l){try{var u=xe(l);return pr(u),0}catch(m){if(typeof pe>"u"||m.name!=="ErrnoError")throw m;return m.Pa}},p:function(l,u){try{var m=xe(l);return x[u]=m.tty?2:Re(m.mode)?3:(m.mode&61440)===40960?7:4,ae[u+2>>1]=0,Oe[u+8>>3]=BigInt(0),Oe[u+16>>3]=BigInt(0),0}catch(g){if(typeof pe>"u"||g.name!=="ErrnoError")throw g;return g.Pa}},w:function(l,u,m,g){try{e:{var y=xe(l);l=u;for(var k,M=u=0;M<m;M++){var j=se[l>>2],oe=se[l+4>>2];l+=8;var $=ul(y,x,j,oe,k);if(0>$){var ge=-1;break e}if(u+=$,$<oe)break;typeof k<"u"&&(k+=$)}ge=u}return se[g>>2]=ge,0}catch(Pe){if(typeof pe>"u"||Pe.name!=="ErrnoError")throw Pe;return Pe.Pa}},D:function(l,u,m,g){u=-9007199254740992>u||9007199254740992<u?NaN:Number(u);try{if(isNaN(u))return 61;var y=xe(l);return cl(y,u,m),Oe[g>>3]=BigInt(y.position),y.rb&&u===0&&m===0&&(y.rb=null),0}catch(k){if(typeof pe>"u"||k.name!=="ErrnoError")throw k;return k.Pa}},I:function(l){try{var u=xe(l);return u.Ma?.fsync?.(u)}catch(m){if(typeof pe>"u"||m.name!=="ErrnoError")throw m;return m.Pa}},t:function(l,u,m,g){try{e:{var y=xe(l);l=u;for(var k,M=u=0;M<m;M++){var j=se[l>>2],oe=se[l+4>>2];l+=8;var $=dl(y,x,j,oe,k);if(0>$){var ge=-1;break e}if(u+=$,$<oe)break;typeof k<"u"&&(k+=$)}ge=u}return se[g>>2]=ge,0}catch(Pe){if(typeof pe>"u"||Pe.name!=="ErrnoError")throw Pe;return Pe.Pa}},k:ml};function _r(){function l(){if(i.calledRun=!0,!B){if(!i.noFSInit&&!Xa){var u,m;Xa=!0,u??=i.stdin,m??=i.stdout,g??=i.stderr,u?It("stdin",u):mr("/dev/tty","/dev/stdin"),m?It("stdout",null,m):mr("/dev/tty","/dev/stdout"),g?It("stderr",null,g):mr("/dev/tty1","/dev/stderr"),Ss("/dev/stdin",0),Ss("/dev/stdout",1),Ss("/dev/stderr",1)}if(Cr.N(),Za=!1,i.onRuntimeInitialized?.(),i.postRun)for(typeof i.postRun=="function"&&(i.postRun=[i.postRun]);i.postRun.length;){var g=i.postRun.shift();or.push(g)}ys(or)}}if(0<Xe)_s=_r;else{if(i.preRun)for(typeof i.preRun=="function"&&(i.preRun=[i.preRun]);i.preRun.length;)Ws();ys(ro),0<Xe?_s=_r:i.setStatus?(i.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>i.setStatus(""),1),l()},1)):l()}}var Cr;return(async function(){function l(m){return m=Cr=m.exports,i._sqlite3_free=m.P,i._sqlite3_value_text=m.Q,i._sqlite3_prepare_v2=m.R,i._sqlite3_step=m.S,i._sqlite3_reset=m.T,i._sqlite3_exec=m.U,i._sqlite3_finalize=m.V,i._sqlite3_column_name=m.W,i._sqlite3_column_text=m.X,i._sqlite3_column_type=m.Y,i._sqlite3_errmsg=m.Z,i._sqlite3_clear_bindings=m._,i._sqlite3_value_blob=m.$,i._sqlite3_value_bytes=m.aa,i._sqlite3_value_double=m.ba,i._sqlite3_value_int=m.ca,i._sqlite3_value_type=m.da,i._sqlite3_result_blob=m.ea,i._sqlite3_result_double=m.fa,i._sqlite3_result_error=m.ga,i._sqlite3_result_int=m.ha,i._sqlite3_result_int64=m.ia,i._sqlite3_result_null=m.ja,i._sqlite3_result_text=m.ka,i._sqlite3_aggregate_context=m.la,i._sqlite3_column_count=m.ma,i._sqlite3_data_count=m.na,i._sqlite3_column_blob=m.oa,i._sqlite3_column_bytes=m.pa,i._sqlite3_column_double=m.qa,i._sqlite3_bind_blob=m.ra,i._sqlite3_bind_double=m.sa,i._sqlite3_bind_int=m.ta,i._sqlite3_bind_text=m.ua,i._sqlite3_bind_parameter_index=m.va,i._sqlite3_sql=m.wa,i._sqlite3_normalized_sql=m.xa,i._sqlite3_changes=m.ya,i._sqlite3_close_v2=m.za,i._sqlite3_create_function_v2=m.Aa,i._sqlite3_update_hook=m.Ba,i._sqlite3_open=m.Ca,yo=i._malloc=m.Da,Ys=i._free=m.Ea,i._RegisterExtensionFunctions=m.Fa,hl=m.Ga,yl=m.Ha,_o=m.Ia,ts=m.Ja,Co=m.Ka,bo=m.M,Ot=m.O,Hs(),Xe--,i.monitorRunDependencies?.(Xe),Xe==0&&_s&&(m=_s,_s=null,m()),Cr}Xe++,i.monitorRunDependencies?.(Xe);var u={a:fm};return i.instantiateWasm?new Promise(m=>{i.instantiateWasm(u,(g,y)=>{m(l(g,y))})}):(Ct??=i.locateFile?i.locateFile("sql-wasm.wasm",h):h+"sql-wasm.wasm",l((await nr(u)).instance))})(),_r(),s}),Fo)};typeof Lo=="object"&&typeof is=="object"?(is.exports=No,is.exports.default=No):typeof define=="function"&&define.amd?define([],function(){return No}):typeof Lo=="object"&&(Lo.Module=No)});var $o=we(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.utf8Count=ig;kt.utf8EncodeJs=ac;kt.utf8EncodeTE=lc;kt.utf8Encode=lg;kt.utf8DecodeJs=cc;kt.utf8DecodeTD=uc;kt.utf8Decode=mg;function ig(o){let e=o.length,t=0,s=0;for(;s<e;){let n=o.charCodeAt(s++);if((n&4294967168)===0){t++;continue}else if((n&4294965248)===0)t+=2;else{if(n>=55296&&n<=56319&&s<e){let i=o.charCodeAt(s);(i&64512)===56320&&(++s,n=((n&1023)<<10)+(i&1023)+65536)}(n&4294901760)===0?t+=3:t+=4}}return t}function ac(o,e,t){let s=o.length,n=t,i=0;for(;i<s;){let r=o.charCodeAt(i++);if((r&4294967168)===0){e[n++]=r;continue}else if((r&4294965248)===0)e[n++]=r>>6&31|192;else{if(r>=55296&&r<=56319&&i<s){let a=o.charCodeAt(i);(a&64512)===56320&&(++i,r=((r&1023)<<10)+(a&1023)+65536)}(r&4294901760)===0?(e[n++]=r>>12&15|224,e[n++]=r>>6&63|128):(e[n++]=r>>18&7|240,e[n++]=r>>12&63|128,e[n++]=r>>6&63|128)}e[n++]=r&63|128}}var rg=new TextEncoder,ag=50;function lc(o,e,t){rg.encodeInto(o,e.subarray(t))}function lg(o,e,t){o.length>ag?lc(o,e,t):ac(o,e,t)}var cg=4096;function cc(o,e,t){let s=e,n=s+t,i=[],r="";for(;s<n;){let a=o[s++];if((a&128)===0)i.push(a);else if((a&224)===192){let c=o[s++]&63;i.push((a&31)<<6|c)}else if((a&240)===224){let c=o[s++]&63,d=o[s++]&63;i.push((a&31)<<12|c<<6|d)}else if((a&248)===240){let c=o[s++]&63,d=o[s++]&63,p=o[s++]&63,f=(a&7)<<18|c<<12|d<<6|p;f>65535&&(f-=65536,i.push(f>>>10&1023|55296),f=56320|f&1023),i.push(f)}else i.push(a);i.length>=cg&&(r+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(r+=String.fromCharCode(...i)),r}var ug=new TextDecoder,dg=200;function uc(o,e,t){let s=o.subarray(e,e+t);return ug.decode(s)}function mg(o,e,t){return t>dg?uc(o,e,t):cc(o,e,t)}});var Or=we(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.ExtData=void 0;var Ur=class{type;data;constructor(e,t){this.type=e,this.data=t}};Ho.ExtData=Ur});var Jo=we(Wo=>{"use strict";Object.defineProperty(Wo,"__esModule",{value:!0});Wo.DecodeError=void 0;var Fr=class o extends Error{constructor(e){super(e);let t=Object.create(o.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:o.name})}};Wo.DecodeError=Fr});var Vo=we(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.UINT32_MAX=void 0;jt.setUint64=pg;jt.setInt64=gg;jt.getInt64=fg;jt.getUint64=hg;jt.UINT32_MAX=4294967295;function pg(o,e,t){let s=t/4294967296,n=t;o.setUint32(e,s),o.setUint32(e+4,n)}function gg(o,e,t){let s=Math.floor(t/4294967296),n=t;o.setUint32(e,s),o.setUint32(e+4,n)}function fg(o,e){let t=o.getInt32(e),s=o.getUint32(e+4);return t*4294967296+s}function hg(o,e){let t=o.getUint32(e),s=o.getUint32(e+4);return t*4294967296+s}});var Nr=we(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.timestampExtension=Je.EXT_TIMESTAMP=void 0;Je.encodeTimeSpecToTimestamp=mc;Je.encodeDateToTimeSpec=pc;Je.encodeTimestampExtension=gc;Je.decodeTimestampToTimeSpec=fc;Je.decodeTimestampExtension=hc;var yg=Jo(),dc=Vo();Je.EXT_TIMESTAMP=-1;var _g=4294967296-1,Cg=17179869184-1;function mc({sec:o,nsec:e}){if(o>=0&&e>=0&&o<=Cg)if(e===0&&o<=_g){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,o),t}else{let t=o/4294967296,s=o&4294967295,n=new Uint8Array(8),i=new DataView(n.buffer);return i.setUint32(0,e<<2|t&3),i.setUint32(4,s),n}else{let t=new Uint8Array(12),s=new DataView(t.buffer);return s.setUint32(0,e),(0,dc.setInt64)(s,4,o),t}}function pc(o){let e=o.getTime(),t=Math.floor(e/1e3),s=(e-t*1e3)*1e6,n=Math.floor(s/1e9);return{sec:t+n,nsec:s-n*1e9}}function gc(o){if(o instanceof Date){let e=pc(o);return mc(e)}else return null}function fc(o){let e=new DataView(o.buffer,o.byteOffset,o.byteLength);switch(o.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let t=e.getUint32(0),s=e.getUint32(4),n=(t&3)*4294967296+s,i=t>>>2;return{sec:n,nsec:i}}case 12:{let t=(0,dc.getInt64)(e,4),s=e.getUint32(0);return{sec:t,nsec:s}}default:throw new yg.DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${o.length}`)}}function hc(o){let e=fc(o);return new Date(e.sec*1e3+e.nsec/1e6)}Je.timestampExtension={type:Je.EXT_TIMESTAMP,encode:gc,decode:hc}});var Yo=we(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.ExtensionCodec=void 0;var Ko=Or(),bg=Nr(),Lr=class o{static defaultCodec=new o;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(bg.timestampExtension)}register({type:e,encode:t,decode:s}){if(e>=0)this.encoders[e]=t,this.decoders[e]=s;else{let n=-1-e;this.builtInEncoders[n]=t,this.builtInDecoders[n]=s}}tryToEncode(e,t){for(let s=0;s<this.builtInEncoders.length;s++){let n=this.builtInEncoders[s];if(n!=null){let i=n(e,t);if(i!=null){let r=-1-s;return new Ko.ExtData(r,i)}}}for(let s=0;s<this.encoders.length;s++){let n=this.encoders[s];if(n!=null){let i=n(e,t);if(i!=null){let r=s;return new Ko.ExtData(r,i)}}}return e instanceof Ko.ExtData?e:null}decode(e,t,s){let n=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return n?n(e,t,s):new Ko.ExtData(t,e)}};Qo.ExtensionCodec=Lr});var Gr=we(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});jr.ensureUint8Array=Sg;function kg(o){return o instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&o instanceof SharedArrayBuffer}function Sg(o){return o instanceof Uint8Array?o:ArrayBuffer.isView(o)?new Uint8Array(o.buffer,o.byteOffset,o.byteLength):kg(o)?new Uint8Array(o):Uint8Array.from(o)}});var Br=we(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.Encoder=ht.DEFAULT_INITIAL_BUFFER_SIZE=ht.DEFAULT_MAX_DEPTH=void 0;var yc=$o(),Tg=Yo(),_c=Vo(),wg=Gr();ht.DEFAULT_MAX_DEPTH=100;ht.DEFAULT_INITIAL_BUFFER_SIZE=2048;var qr=class o{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Tg.ExtensionCodec.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??ht.DEFAULT_MAX_DEPTH,this.initialBufferSize=e?.initialBufferSize??ht.DEFAULT_INITIAL_BUFFER_SIZE,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new o({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){let t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){let t=new ArrayBuffer(e),s=new Uint8Array(t),n=new DataView(t);s.set(this.bytes),this.view=n,this.bytes=s}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let s=(0,yc.utf8Count)(e);this.ensureBufferSizeToWrite(5+s),this.writeStringHeader(s),(0,yc.utf8Encode)(e,this.bytes,this.pos),this.pos+=s}encodeObject(e,t){let s=this.extensionCodec.tryToEncode(e,this.context);if(s!=null)this.encodeExtension(s);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);let s=(0,wg.ensureUint8Array)(e);this.writeU8a(s)}encodeArray(e,t){let s=e.length;if(s<16)this.writeU8(144+s);else if(s<65536)this.writeU8(220),this.writeU16(s);else if(s<4294967296)this.writeU8(221),this.writeU32(s);else throw new Error(`Too large array: ${s}`);for(let n of e)this.doEncode(n,t+1)}countWithoutUndefined(e,t){let s=0;for(let n of t)e[n]!==void 0&&s++;return s}encodeMap(e,t){let s=Object.keys(e);this.sortKeys&&s.sort();let n=this.ignoreUndefined?this.countWithoutUndefined(e,s):s.length;if(n<16)this.writeU8(128+n);else if(n<65536)this.writeU8(222),this.writeU16(n);else if(n<4294967296)this.writeU8(223),this.writeU32(n);else throw new Error(`Too large map object: ${n}`);for(let i of s){let r=e[i];this.ignoreUndefined&&r===void 0||(this.encodeString(i),this.doEncode(r,t+1))}}encodeExtension(e){if(typeof e.data=="function"){let s=e.data(this.pos+6),n=s.length;if(n>=4294967296)throw new Error(`Too large extension object: ${n}`);this.writeU8(201),this.writeU32(n),this.writeI8(e.type),this.writeU8a(s);return}let t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),(0,_c.setUint64)(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),(0,_c.setInt64)(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};ht.Encoder=qr});var Cc=we(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.encode=Pg;var Mg=Br();function Pg(o,e){return new Mg.Encoder(e).encodeSharedRef(o)}});var bc=we($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.prettyByte=vg;function vg(o){return`${o<0?"-":""}0x${Math.abs(o).toString(16).padStart(2,"0")}`}});var kc=we(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.CachedKeyDecoder=void 0;var Ag=$o(),xg=16,Dg=16,Hr=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=xg,t=Dg){this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let s=0;s<this.maxKeyLength;s++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,s){let n=this.caches[s-1];e:for(let i of n){let r=i.bytes;for(let a=0;a<s;a++)if(r[a]!==e[t+a])continue e;return i.str}return null}store(e,t){let s=this.caches[e.length-1],n={bytes:e,str:t};s.length>=this.maxLengthPerKey?s[Math.random()*s.length|0]=n:s.push(n)}decode(e,t,s){let n=this.find(e,t,s);if(n!=null)return this.hit++,n;this.miss++;let i=(0,Ag.utf8DecodeJs)(e,t,s),r=Uint8Array.prototype.slice.call(e,t,t+s);return this.store(r,i),i}};Xo.CachedKeyDecoder=Hr});var ei=we(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.Decoder=void 0;var Wr=bc(),Eg=Yo(),cs=Vo(),Rg=$o(),Sc=Gr(),Ig=kc(),St=Jo(),Jr="array",pn="map_key",wc="map_value",Ug=o=>{if(typeof o=="string"||typeof o=="number")return o;throw new St.DecodeError("The type of key must be string or number but "+typeof o)},Vr=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let t=this.getUninitializedStateFromPool();t.type=Jr,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=pn,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===Jr){let s=e;s.size=0,s.array=void 0,s.position=0,s.type=void 0}if(e.type===pn||e.type===wc){let s=e;s.size=0,s.map=void 0,s.readCount=0,s.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},mn=-1,Qr=new DataView(new ArrayBuffer(0)),Og=new Uint8Array(Qr.buffer);try{Qr.getInt8(0)}catch(o){if(!(o instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var Tc=new RangeError("Insufficient data"),Fg=new Ig.CachedKeyDecoder,Kr=class o{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=Qr;bytes=Og;headByte=mn;stack=new Vr;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Eg.ExtensionCodec.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??cs.UINT32_MAX,this.maxBinLength=e?.maxBinLength??cs.UINT32_MAX,this.maxArrayLength=e?.maxArrayLength??cs.UINT32_MAX,this.maxMapLength=e?.maxMapLength??cs.UINT32_MAX,this.maxExtLength=e?.maxExtLength??cs.UINT32_MAX,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:Fg,this.mapKeyConverter=e?.mapKeyConverter??Ug}clone(){return new o({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=mn,this.stack.reset()}setBuffer(e){let t=(0,Sc.ensureUint8Array)(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===mn&&!this.hasRemaining(1))this.setBuffer(e);else{let t=this.bytes.subarray(this.pos),s=(0,Sc.ensureUint8Array)(e),n=new Uint8Array(t.length+s.length);n.set(t),n.set(s,t.length),this.setBuffer(n)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:s}=this;return new RangeError(`Extra ${t.byteLength-s} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,s;for await(let a of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{s=this.doDecodeSync(),t=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return s}let{headByte:n,pos:i,totalPos:r}=this;throw new RangeError(`Insufficient data in parsing ${(0,Wr.prettyByte)(n)} at ${r} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let s=t,n=-1;for await(let i of e){if(t&&n===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),s&&(n=this.readArraySize(),s=!1,this.complete());try{for(;yield this.doDecodeSync(),--n!==0;);}catch(r){if(!(r instanceof RangeError))throw r}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){let n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e<160){let n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else{let n=e-160;t=this.decodeString(n,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){let n=this.lookU8();t=this.decodeString(n,1)}else if(e===218){let n=this.lookU16();t=this.decodeString(n,2)}else if(e===219){let n=this.lookU32();t=this.decodeString(n,4)}else if(e===220){let n=this.readU16();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===221){let n=this.readU32();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===222){let n=this.readU16();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===223){let n=this.readU32();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===196){let n=this.lookU8();t=this.decodeBinary(n,1)}else if(e===197){let n=this.lookU16();t=this.decodeBinary(n,2)}else if(e===198){let n=this.lookU32();t=this.decodeBinary(n,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){let n=this.lookU8();t=this.decodeExtension(n,1)}else if(e===200){let n=this.lookU16();t=this.decodeExtension(n,2)}else if(e===201){let n=this.lookU32();t=this.decodeExtension(n,4)}else throw new St.DecodeError(`Unrecognized type byte: ${(0,Wr.prettyByte)(e)}`);this.complete();let s=this.stack;for(;s.length>0;){let n=s.top();if(n.type===Jr)if(n.array[n.position]=t,n.position++,n.position===n.size)t=n.array,s.release(n);else continue e;else if(n.type===pn){if(t==="__proto__")throw new St.DecodeError("The key __proto__ is not allowed");n.key=this.mapKeyConverter(t),n.type=wc;continue e}else if(n.map[n.key]=t,n.readCount++,n.readCount===n.size)t=n.map,s.release(n);else{n.key=null,n.type=pn;continue e}}return t}}readHeadByte(){return this.headByte===mn&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=mn}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new St.DecodeError(`Unrecognized array type byte: ${(0,Wr.prettyByte)(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new St.DecodeError(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new St.DecodeError(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new St.DecodeError(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw Tc;let s=this.pos+t,n;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?n=this.keyDecoder.decode(this.bytes,s,e):n=(0,Rg.utf8Decode)(this.bytes,s,e),this.pos+=t+e,n}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===pn:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new St.DecodeError(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw Tc;let s=this.pos+t,n=this.bytes.subarray(s,s+e);return this.pos+=t+e,n}decodeExtension(e,t){if(e>this.maxExtLength)throw new St.DecodeError(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let s=this.view.getInt8(this.pos+t),n=this.decodeBinary(e,t+1);return this.extensionCodec.decode(n,s,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=(0,cs.getUint64)(this.view,this.pos);return this.pos+=8,e}readI64(){let e=(0,cs.getInt64)(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};Zo.Decoder=Kr});var Pc=we(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.decode=Ng;ti.decodeMulti=Lg;var Mc=ei();function Ng(o,e){return new Mc.Decoder(e).decode(o)}function Lg(o,e){return new Mc.Decoder(e).decodeMulti(o)}});var xc=we(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.isAsyncIterable=vc;gn.asyncIterableFromStream=Ac;gn.ensureAsyncIterable=jg;function vc(o){return o[Symbol.asyncIterator]!=null}async function*Ac(o){let e=o.getReader();try{for(;;){let{done:t,value:s}=await e.read();if(t)return;yield s}}finally{e.releaseLock()}}function jg(o){return vc(o)?o:Ac(o)}});var Dc=we(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.decodeAsync=Gg;fn.decodeArrayStream=qg;fn.decodeMultiStream=Bg;var Yr=ei(),Xr=xc();async function Gg(o,e){let t=(0,Xr.ensureAsyncIterable)(o);return new Yr.Decoder(e).decodeAsync(t)}function qg(o,e){let t=(0,Xr.ensureAsyncIterable)(o);return new Yr.Decoder(e).decodeArrayStream(t)}function Bg(o,e){let t=(0,Xr.ensureAsyncIterable)(o);return new Yr.Decoder(e).decodeStream(t)}});var ea=we(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.decodeTimestampExtension=K.encodeTimestampExtension=K.decodeTimestampToTimeSpec=K.encodeTimeSpecToTimestamp=K.encodeDateToTimeSpec=K.EXT_TIMESTAMP=K.ExtData=K.ExtensionCodec=K.Encoder=K.DecodeError=K.Decoder=K.decodeMultiStream=K.decodeArrayStream=K.decodeAsync=K.decodeMulti=K.decode=K.encode=void 0;var zg=Cc();Object.defineProperty(K,"encode",{enumerable:!0,get:function(){return zg.encode}});var Ec=Pc();Object.defineProperty(K,"decode",{enumerable:!0,get:function(){return Ec.decode}});Object.defineProperty(K,"decodeMulti",{enumerable:!0,get:function(){return Ec.decodeMulti}});var Zr=Dc();Object.defineProperty(K,"decodeAsync",{enumerable:!0,get:function(){return Zr.decodeAsync}});Object.defineProperty(K,"decodeArrayStream",{enumerable:!0,get:function(){return Zr.decodeArrayStream}});Object.defineProperty(K,"decodeMultiStream",{enumerable:!0,get:function(){return Zr.decodeMultiStream}});var $g=ei();Object.defineProperty(K,"Decoder",{enumerable:!0,get:function(){return $g.Decoder}});var Hg=Jo();Object.defineProperty(K,"DecodeError",{enumerable:!0,get:function(){return Hg.DecodeError}});var Wg=Br();Object.defineProperty(K,"Encoder",{enumerable:!0,get:function(){return Wg.Encoder}});var Jg=Yo();Object.defineProperty(K,"ExtensionCodec",{enumerable:!0,get:function(){return Jg.ExtensionCodec}});var Vg=Or();Object.defineProperty(K,"ExtData",{enumerable:!0,get:function(){return Vg.ExtData}});var xs=Nr();Object.defineProperty(K,"EXT_TIMESTAMP",{enumerable:!0,get:function(){return xs.EXT_TIMESTAMP}});Object.defineProperty(K,"encodeDateToTimeSpec",{enumerable:!0,get:function(){return xs.encodeDateToTimeSpec}});Object.defineProperty(K,"encodeTimeSpecToTimestamp",{enumerable:!0,get:function(){return xs.encodeTimeSpecToTimestamp}});Object.defineProperty(K,"decodeTimestampToTimeSpec",{enumerable:!0,get:function(){return xs.decodeTimestampToTimeSpec}});Object.defineProperty(K,"encodeTimestampExtension",{enumerable:!0,get:function(){return xs.encodeTimestampExtension}});Object.defineProperty(K,"decodeTimestampExtension",{enumerable:!0,get:function(){return xs.decodeTimestampExtension}})});var Xd=we((xv,vb)=>{vb.exports={name:"@rajbos/ai-engineering-fluency",version:"0.5.0",description:"AI Engineering Fluency - CLI tool to analyze GitHub Copilot token usage from local session files",license:"MIT",author:"RobBos",repository:{type:"git",url:"git+https://github.com/rajbos/ai-engineering-fluency.git",directory:"cli"},keywords:["github-copilot","token-usage","copilot","cli","token-tracker"],bin:{"ai-engineering-fluency":"dist/cli.js"},files:["dist/**/*"],scripts:{build:"node esbuild.js","build:production":"node esbuild.js --production","bundle-exe":"pwsh -NoProfile -File bundle-exe.ps1",lint:"eslint src","check-types":"tsc --noEmit",test:"node dist/cli.js --help && node dist/cli.js --version && npm run test:unit","test:unit":'node esbuild.tests.js && node --test "out/test/*.test.js"'},devDependencies:{"@msgpack/msgpack":"^3.1.3","@types/node":"^26.0.0",chalk:"^6.0.0",commander:"^15.0.0",esbuild:"^0.28.0","sql.js":"^1.12.0",typescript:"^7.0.2"},engines:{node:">=22.14.0"}}});var Ft=class extends Error{constructor(e,t,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},ns=class extends Ft{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var Xs=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,s)=>{if(!this.argChoices.includes(t))throw new ns(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(t,s):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function So(o){let e=o.name()+(o.variadic===!0?"...":"");return o.required?"<"+e+">":"["+e+"]"}var Rl=require("node:events"),wo=S(require("node:child_process"),1),pt=S(require("node:path"),1),en=S(require("node:fs"),1),te=S(require("node:process"),1),Il=require("node:util");var Al=require("node:util"),Zs=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(n=>!n._hidden),s=e._getHelpCommand();return s&&!s._hidden&&t.push(s),this.sortSubcommands&&t.sort((n,i)=>n.name().localeCompare(i.name())),t}compareOptions(e,t){let s=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return s(e).localeCompare(s(t))}visibleOptions(e){let t=e.options.filter(n=>!n.hidden),s=e._getHelpOption();if(s&&!s.hidden){let n=s.short&&e._findOption(s.short),i=s.long&&e._findOption(s.long);!n&&!i?t.push(s):s.long&&!i?t.push(e.createOption(s.long,s.description)):s.short&&!n&&t.push(e.createOption(s.short,s.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let s=e.parent;s;s=s.parent){let n=s.options.filter(i=>!i.hidden);t.push(...n)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(s=>So(s)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((s,n)=>Math.max(s,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((s,n)=>Math.max(s,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((s,n)=>Math.max(s,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((s,n)=>Math.max(s,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let s="";for(let n=e.parent;n;n=n.parent)s=n.name()+" "+s;return s+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let s=`(${t.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let s=`(${t.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}formatItemList(e,t,s){return t.length===0?[]:[s.styleTitle(e),...t,""]}groupItems(e,t,s){let n=new Map;return e.forEach(i=>{let r=s(i);n.has(r)||n.set(r,[])}),t.forEach(i=>{let r=s(i);n.has(r)||n.set(r,[]),n.get(r).push(i)}),n}formatHelp(e,t){let s=t.padWidth(e,t),n=t.helpWidth??80;function i(f,h){return t.formatItem(f,s,h,t)}let r=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],a=t.commandDescription(e);a.length>0&&(r=r.concat([t.boxWrap(t.styleCommandDescription(a),n),""]));let c=t.visibleArguments(e).map(f=>i(t.styleArgumentTerm(t.argumentTerm(f)),t.styleArgumentDescription(t.argumentDescription(f))));if(r=r.concat(this.formatItemList("Arguments:",c,t)),this.groupItems(e.options,t.visibleOptions(e),f=>f.helpGroupHeading??"Options:").forEach((f,h)=>{let _=f.map(C=>i(t.styleOptionTerm(t.optionTerm(C)),t.styleOptionDescription(t.optionDescription(C))));r=r.concat(this.formatItemList(h,_,t))}),t.showGlobalOptions){let f=t.visibleGlobalOptions(e).map(h=>i(t.styleOptionTerm(t.optionTerm(h)),t.styleOptionDescription(t.optionDescription(h))));r=r.concat(this.formatItemList("Global Options:",f,t))}return this.groupItems(e.commands,t.visibleCommands(e),f=>f.helpGroup()||"Commands:").forEach((f,h)=>{let _=f.map(C=>i(t.styleSubcommandTerm(t.subcommandTerm(C)),t.styleSubcommandDescription(t.subcommandDescription(C))));r=r.concat(this.formatItemList(h,_,t))}),r.join(`
|
|
4
|
+
`)}displayWidth(e){return(0,Al.stripVTControlCharacters)(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t==="[command]"?this.styleSubcommandText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleCommandText(t)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleSubcommandText(t)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,s,n){let r=" ".repeat(2);if(!s)return r+e;let a=e.padEnd(t+e.length-n.displayWidth(e)),c=2,p=(this.helpWidth??80)-t-c-2,f;return p<this.minWidthToWrap||n.preformatted(s)?f=s:f=n.boxWrap(s,p).replace(/\n/g,`
|
|
5
5
|
`+" ".repeat(t+c)),r+a+" ".repeat(c)+f.replace(/\n/g,`
|
|
6
|
-
${r}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let s=e.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,i=[];return s.forEach(r=>{let a=r.match(n);if(a===null){i.push("");return}let c=[a.shift()],
|
|
7
|
-
`)}};var
|
|
6
|
+
${r}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let s=e.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,i=[];return s.forEach(r=>{let a=r.match(n);if(a===null){i.push("");return}let c=[a.shift()],d=this.displayWidth(c[0]);a.forEach(p=>{let f=this.displayWidth(p);if(d+f<=t){c.push(p),d+=f;return}i.push(c.join(""));let h=p.trimStart();c=[h],d=this.displayWidth(h)}),i.push(c.join(""))}),i.join(`
|
|
7
|
+
`)}};var Ts=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let s=Km(e);this.short=s.shortFlag,this.long=s.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,s)=>{if(!this.argChoices.includes(t))throw new ns(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(t,s):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?xl(this.name().replace(/^no-/,"")):xl(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},To=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,s)=>{this.positiveOptions.has(s)&&this.dualOptions.add(s)})}valueFromOption(e,t){let s=t.attributeName();if(!this.dualOptions.has(s))return!0;let n=this.negativeOptions.get(s).presetArg,i=n!==void 0?n:!1;return t.negate===(i===e)}};function xl(o){return o.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Km(o){let e,t,s=/^-[^-]$/,n=/^--[^-]/,i=o.split(/[ |,]+/).concat("guard");if(s.test(i[0])&&(e=i.shift()),n.test(i[0])&&(t=i.shift()),!e&&s.test(i[0])&&(e=i.shift()),!e&&n.test(i[0])&&(e=t,t=i.shift()),i[0].startsWith("-")){let r=i[0],a=`option creation failed due to '${r}' in option flags '${o}'`;throw/^-[^-][^-]/.test(r)?new Error(`${a}
|
|
8
8
|
- a short flag is a single dash and a single character
|
|
9
9
|
- either use a single dash and a single character (for a short flag)
|
|
10
10
|
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):s.test(r)?new Error(`${a}
|
|
11
11
|
- too many short flags`):n.test(r)?new Error(`${a}
|
|
12
12
|
- too many long flags`):new Error(`${a}
|
|
13
|
-
- unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${o}'.`);return{shortFlag:e,longFlag:t}}function
|
|
13
|
+
- unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${o}'.`);return{shortFlag:e,longFlag:t}}function Qm(o,e){if(Math.abs(o.length-e.length)>3)return Math.max(o.length,e.length);let t=[];for(let s=0;s<=o.length;s++)t[s]=[s];for(let s=0;s<=e.length;s++)t[0][s]=s;for(let s=1;s<=e.length;s++)for(let n=1;n<=o.length;n++){let i;o[n-1]===e[s-1]?i=0:i=1,t[n][s]=Math.min(t[n-1][s]+1,t[n][s-1]+1,t[n-1][s-1]+i),n>1&&s>1&&o[n-1]===e[s-2]&&o[n-2]===e[s-1]&&(t[n][s]=Math.min(t[n][s],t[n-2][s-2]+1))}return t[o.length][e.length]}function kr(o,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=o.startsWith("--");t&&(o=o.slice(2),e=e.map(r=>r.slice(2)));let s=[],n=3,i=.4;return e.forEach(r=>{if(r.length<=1)return;let a=Qm(o,r),c=Math.max(o.length,r.length);(c-a)/c>i&&(a<n?(n=a,s=[r]):a===n&&s.push(r))}),s.sort((r,a)=>r.localeCompare(a)),t&&(s=s.map(r=>`--${r}`)),s.length>1?`
|
|
14
14
|
(Did you mean one of ${s.join(", ")}?)`:s.length===1?`
|
|
15
|
-
(Did you mean ${s[0]}?)`:""}var
|
|
16
|
-
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new
|
|
17
|
-
Expecting one of '${s.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,s){this._exitCallback&&this._exitCallback(new Ft(e,t,s)),te.default.exit(e)}action(e){let t=s=>{let n=this.registeredArguments.length,i=s.slice(0,n);return this._storeOptionsAsProperties?i[n]=this:i[n]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new
|
|
18
|
-
- already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=n=>[n.name()].concat(n.aliases()),s=t(e).find(n=>this._findCommand(n));if(s){let n=t(this._findCommand(s)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${n}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),s=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(s,e.defaultValue,"default");let n=(i,r,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let c=this.getOptionValue(s);i!==null&&e.parseArg?i=this._callParseArg(e,i,c,r):i!==null&&e.variadic&&(i=e._collectValue(i,c)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(s,i,a)};return this.on("option:"+t,i=>{let r=`error: option '${e.flags}' argument '${i}' is invalid.`;n(i,r,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let r=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;n(i,r,"env")}),this}_optionEx(e,t,s,n,i){if(typeof t=="object"&&t instanceof
|
|
19
|
-
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,s){if(
|
|
15
|
+
(Did you mean ${s[0]}?)`:""}var de=class o extends Rl.EventEmitter{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:t=>te.default.stdout.write(t),writeErr:t=>te.default.stderr.write(t),outputError:(t,s)=>s(t),getOutHelpWidth:()=>te.default.stdout.isTTY?te.default.stdout.columns:void 0,getErrHelpWidth:()=>te.default.stderr.isTTY?te.default.stderr.columns:void 0,getOutHasColors:()=>El()??(te.default.stdout.isTTY&&te.default.stdout.hasColors?.()),getErrHasColors:()=>El()??(te.default.stderr.isTTY&&te.default.stderr.hasColors?.()),stripColor:t=>(0,Il.stripVTControlCharacters)(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,s){let n=t,i=s;typeof n=="object"&&n!==null&&(i=n,n=null),i=i||{};let[,r,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(r);return n&&(c.description(n),c._executableHandler=!0),i.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(i.noHelp||i.hidden),c._executableFile=i.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),n?this:c}createCommand(e){return new o(e)}createHelp(){return Object.assign(new Zs,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
16
|
+
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Xs(e,t)}argument(e,t,s,n){let i=this.createArgument(e,t);return typeof s=="function"?i.default(n).argParser(s):i.default(s),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let s=e??"help [command]",[,n,i]=s.match(/([^ ]+) *(.*)/),r=t??"display help for command",a=this.createCommand(n);return a.helpOption(!1),i&&a.arguments(i),r&&a.description(r),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||t)&&this._initCommandGroup(a),this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let s=["preSubcommand","preAction","postAction"];if(!s.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
17
|
+
Expecting one of '${s.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,s){this._exitCallback&&this._exitCallback(new Ft(e,t,s)),te.default.exit(e)}action(e){let t=s=>{let n=this.registeredArguments.length,i=s.slice(0,n);return this._storeOptionsAsProperties?i[n]=this:i[n]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new Ts(e,t)}_callParseArg(e,t,s,n){try{return e.parseArg(t,s)}catch(i){if(i.code==="commander.invalidArgument"){let r=`${n} ${i.message}`;this.error(r,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let s=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${s}'
|
|
18
|
+
- already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=n=>[n.name()].concat(n.aliases()),s=t(e).find(n=>this._findCommand(n));if(s){let n=t(this._findCommand(s)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${n}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),s=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(s,e.defaultValue,"default");let n=(i,r,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let c=this.getOptionValue(s);i!==null&&e.parseArg?i=this._callParseArg(e,i,c,r):i!==null&&e.variadic&&(i=e._collectValue(i,c)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(s,i,a)};return this.on("option:"+t,i=>{let r=`error: option '${e.flags}' argument '${i}' is invalid.`;n(i,r,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let r=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;n(i,r,"env")}),this}_optionEx(e,t,s,n,i){if(typeof t=="object"&&t instanceof Ts)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let r=this.createOption(t,s);if(r.makeOptionMandatory(!!e.mandatory),typeof n=="function")r.default(i).argParser(n);else if(n instanceof RegExp){let a=n;n=(c,d)=>{let p=a.exec(c);return p?p[0]:d},r.default(i).argParser(n)}else r.default(n);return this.addOption(r)}option(e,t,s,n){return this._optionEx({},e,t,s,n)}requiredOption(e,t,s,n){return this._optionEx({mandatory:!0},e,t,s,n)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,s){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=s,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(s=>{s.getOptionValueSource(e)!==void 0&&(t=s.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){te.default.versions?.electron&&(t.from="electron");let n=te.default.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(t.from="eval")}e===void 0&&(e=te.default.argv),this.rawArgs=e.slice();let s;switch(t.from){case void 0:case"node":this._scriptPath=e[1],s=e.slice(2);break;case"electron":te.default.defaultApp?(this._scriptPath=e[1],s=e.slice(2)):s=e.slice(1);break;case"user":s=e.slice(0);break;case"eval":s=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",s}parse(e,t){this._prepareForParse();let s=this._prepareUserArgs(e,t);return this._parseCommand([],s),this}async parseAsync(e,t){this._prepareForParse();let s=this._prepareUserArgs(e,t);return await this._parseCommand([],s),this}_prepareForParse(){this._savedState===null?(this.options.filter(e=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach(e=>{let t=e.long.replace(/^--no-/,"--");this._findOption(t)||this.setOptionValueWithSource(e.attributeName(),!0,"default")}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
19
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,s){if(en.default.existsSync(e))return;let n=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",i=`'${e}' does not exist
|
|
20
20
|
- if '${s}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
21
21
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
22
|
-
- ${n}`;throw new Error(i)}_executeSubCommand(e,t){t=t.slice();let s=[".js",".ts",".tsx",".mjs",".cjs"];function n(p,f){let h=
|
|
22
|
+
- ${n}`;throw new Error(i)}_executeSubCommand(e,t){t=t.slice();let s=[".js",".ts",".tsx",".mjs",".cjs"];function n(p,f){let h=pt.default.resolve(p,f);if(en.default.existsSync(h))return h;if(s.includes(pt.default.extname(f)))return;let _=s.find(C=>en.default.existsSync(`${h}${C}`));if(_)return`${h}${_}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,r=this._executableDir||"";if(this._scriptPath){let p;try{p=en.default.realpathSync(this._scriptPath)}catch{p=this._scriptPath}r=pt.default.resolve(pt.default.dirname(p),r)}if(r){let p=n(r,i);if(!p&&!e._executableFile&&this._scriptPath){let f=pt.default.basename(this._scriptPath,pt.default.extname(this._scriptPath));f!==this._name&&(p=n(r,`${f}-${e._name}`))}i=p||i}let a=s.includes(pt.default.extname(i)),c;te.default.platform!=="win32"?a?(t.unshift(i),t=Dl(te.default.execArgv).concat(t),c=wo.default.spawn(te.default.argv[0],t,{stdio:"inherit"})):c=wo.default.spawn(i,t,{stdio:"inherit"}):(this._checkForMissingExecutable(i,r,e._name),t.unshift(i),t=Dl(te.default.execArgv).concat(t),c=wo.default.spawn(te.default.execPath,t,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{te.default.on(f,()=>{c.killed===!1&&c.exitCode===null&&c.kill(f)})});let d=this._exitCallback;c.on("close",p=>{p=p??1,d?d(new Ft(p,"commander.executeSubCommandAsync","(close)")):te.default.exit(p)}),c.on("error",p=>{if(p.code==="ENOENT")this._checkForMissingExecutable(i,r,e._name);else if(p.code==="EACCES")throw new Error(`'${i}' not executable`);if(!d)te.default.exit(1);else{let f=new Ft(1,"commander.executeSubCommandAsync","(error)");f.nestedError=p,d(f)}}),this.runningCommand=c}_dispatchSubcommand(e,t,s){let n=this._findCommand(e);n||this.help({error:!0}),n._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,n,"preSubcommand"),i=this._chainOrCall(i,()=>{if(n._executableHandler)this._executeSubCommand(n,t.concat(s));else return n._parseCommand(t,s)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(s,n,i)=>{let r=n;if(n!==null&&s.parseArg){let a=`error: command-argument value '${n}' is invalid for argument '${s.name()}'.`;r=this._callParseArg(s,n,i,a)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((s,n)=>{let i=s.defaultValue;s.variadic?n<this.args.length?(i=this.args.slice(n),s.parseArg&&(i=i.reduce((r,a)=>e(s,a,r),s.defaultValue))):i===void 0&&(i=[]):n<this.args.length&&(i=this.args[n],s.parseArg&&(i=e(s,i,s.defaultValue))),t[n]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let s=e,n=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(r=>{n.push({hookedCommand:i,callback:r})})}),t==="postAction"&&n.reverse(),n.forEach(i=>{s=this._chainOrCall(s,()=>i.callback(i.hookedCommand,this))}),s}_chainOrCallSubCommandHook(e,t,s){let n=e;return this._lifeCycleHooks[s]!==void 0&&this._lifeCycleHooks[s].forEach(i=>{n=this._chainOrCall(n,()=>i(this,t))}),n}_parseCommand(e,t){let s=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(s.operands),t=s.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(s.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{s.unknown.length>0&&this.unknownOption(s.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let r;return r=this._chainOrCallHooks(r,"preAction"),r=this._chainOrCall(r,()=>this._actionHandler(this.processedArgs)),this.parent&&(r=this._chainOrCall(r,()=>{this.parent.emit(i,e,t)})),r=this._chainOrCallHooks(r,"postAction"),r}if(this.parent?.listenerCount(i))n(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(s=>{let n=s.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});e.filter(s=>s.conflictsWith.length>0).forEach(s=>{let n=e.find(i=>s.conflictsWith.includes(i.attributeName()));n&&this._conflictingOption(s,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],s=[],n=t;function i(p){return p.length>1&&p[0]==="-"}let r=p=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(p)?!this._getCommandAndAncestors().some(f=>f.options.map(h=>h.short).some(h=>/^-\d$/.test(h))):!1,a=null,c=null,d=0;for(;d<e.length||c;){let p=c??e[d++];if(c=null,p==="--"){n===s&&n.push(p),n.push(...e.slice(d));break}if(a&&(!i(p)||r(p))){this.emit(`option:${a.name()}`,p);continue}if(a=null,i(p)){let f=this._findOption(p);if(f){if(f.required){let h=e[d++];h===void 0&&this.optionMissingArgument(f),this.emit(`option:${f.name()}`,h)}else if(f.optional){let h=null;d<e.length&&(!i(e[d])||r(e[d]))&&(h=e[d++]),this.emit(`option:${f.name()}`,h)}else this.emit(`option:${f.name()}`);a=f.variadic?f:null;continue}}if(p.length>2&&p[0]==="-"&&p[1]!=="-"){let f=this._findOption(`-${p[1]}`);if(f){f.required||f.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${f.name()}`,p.slice(2)):(this.emit(`option:${f.name()}`),c=`-${p.slice(2)}`);continue}}if(/^--[^=]+=/.test(p)){let f=p.indexOf("="),h=this._findOption(p.slice(0,f));if(h&&(h.required||h.optional)){this.emit(`option:${h.name()}`,p.slice(f+1));continue}}if(n===t&&i(p)&&!(this.commands.length===0&&r(p))&&(n=s),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&s.length===0){if(this._findCommand(p)){t.push(p),s.push(...e.slice(d));break}else if(this._getHelpCommand()&&p===this._getHelpCommand().name()){t.push(p,...e.slice(d));break}else if(this._defaultCommandName){s.push(p,...e.slice(d));break}}if(this._passThroughOptions){n.push(p,...e.slice(d));break}n.push(p)}return{operands:t,unknown:s}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let s=0;s<t;s++){let n=this.options[s].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
23
23
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
24
24
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
25
|
-
`),this.outputHelp({error:!0}));let s=t||{},n=s.exitCode||1,i=s.code||"commander.error";this._exit(n,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in te.default.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,te.default.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new
|
|
26
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let s=this.parent?._findCommand(e);if(s){let n=[s.name()].concat(s.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(s=>
|
|
25
|
+
`),this.outputHelp({error:!0}));let s=t||{},n=s.exitCode||1,i=s.code||"commander.error";this._exit(n,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in te.default.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,te.default.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new To(this.options),t=s=>this.getOptionValue(s)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(s));this.options.filter(s=>s.implied!==void 0&&t(s.attributeName())&&e.valueFromOption(this.getOptionValue(s.attributeName()),s)).forEach(s=>{Object.keys(s.implied).filter(n=>!t(n)).forEach(n=>{this.setOptionValueWithSource(n,s.implied[n],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let s=r=>{let a=r.attributeName(),c=this.getOptionValue(a),d=this.options.find(f=>f.negate&&a===f.attributeName()),p=this.options.find(f=>!f.negate&&a===f.attributeName());return d&&(d.presetArg===void 0&&c===!1||d.presetArg!==void 0&&c===d.presetArg)?d:p||r},n=r=>{let a=s(r),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${n(e)} cannot be used with ${n(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],i=this;do{let r=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);n=n.concat(r),i=i.parent}while(i&&!i._enablePositionalOptions);t=kr(e,n)}let s=`error: unknown option '${e}'${t}`;this.error(s,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,s=t===1?"":"s",n=e.length,i=this.parent?` for '${this.name()}'`:"",r=e.join(", "),a=`error: too many arguments${i}. Expected ${t} argument${s} but got ${n}: ${r}.`;this.error(a,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(i=>{n.push(i.name()),i.alias()&&n.push(i.alias())}),t=kr(e,n)}let s=`error: unknown command '${e}'${t}`;this.error(s,{code:"commander.unknownCommand"})}version(e,t,s){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",s=s||"output the version number";let n=this.createOption(t,s);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
26
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let s=this.parent?._findCommand(e);if(s){let n=[s.name()].concat(s.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(s=>So(s));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=pt.default.basename(e,pt.default.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),s=this._getOutputContext(e);t.prepareContext({error:s.error,helpWidth:s.helpWidth,outputHasColors:s.hasColors});let n=t.formatHelp(this,t);return s.hasColors?n:this._outputConfiguration.stripColor(n)}_getOutputContext(e){e=e||{};let t=!!e.error,s,n,i;return t?(s=a=>this._outputConfiguration.writeErr(a),n=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(s=a=>this._outputConfiguration.writeOut(a),n=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:a=>(n||(a=this._outputConfiguration.stripColor(a)),s(a)),hasColors:n,helpWidth:i}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let s=this._getOutputContext(e),n={error:s.error,write:s.write,command:this};this._getCommandAndAncestors().reverse().forEach(r=>r.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let i=this.helpInformation({error:s.error});if(t&&(i=t(i),typeof i!="string"&&!Buffer.isBuffer(i)))throw new Error("outputHelp callback must return a string or a Buffer");s.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(r=>r.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??"-h, --help",t??"display help for command"),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(te.default.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let s=["beforeAll","before","after","afterAll"];if(!s.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
27
27
|
Expecting one of '${s.join("', '")}'`);let n=`${e}Help`;return this.on(n,i=>{let r;typeof t=="function"?r=t({error:i.error,command:i.command}):r=t,r&&i.write(`${r}
|
|
28
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(n=>t.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function
|
|
28
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(n=>t.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Dl(o){return o.map(e=>{if(!e.startsWith("--inspect"))return e;let t,s="127.0.0.1",n="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?n=i[3]:s=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],s=i[3],n=i[4]),t&&n!=="0"?`${t}=${s}:${parseInt(n)+1}`:e})}function El(){if(te.default.env.NO_COLOR||te.default.env.FORCE_COLOR==="0"||te.default.env.FORCE_COLOR==="false")return!1;if(te.default.env.FORCE_COLOR||te.default.env.CLICOLOR_FORCE!==void 0)return!0}var Kb=new de;function Ul(o,e,t){let s=o.indexOf(e);if(s===-1)return o;let n=e.length,i=0,r="";do r+=o.slice(i,s)+e+t,i=s+n,s=o.indexOf(e,i);while(s!==-1);return r+=o.slice(i),r}function Ol(o,e,t,s){let n=0,i="";do{let r=o[s-1]==="\r";i+=o.slice(n,r?s-1:s)+e+(r?`\r
|
|
29
29
|
`:`
|
|
30
30
|
`)+t,n=s+1,s=o.indexOf(`
|
|
31
|
-
`,n)}while(s!==-1);return i+=o.slice(n),i}var{
|
|
32
|
-
`);return i!==-1&&(e=
|
|
33
|
-
`)){let r=i.trim();if(!r)continue;let a;try{a=JSON.parse(r)}catch{continue}if(a?.entrypoint==="claude-desktop")return"Claude Desktop";if(a?.entrypoint==="cli")return"Claude Code CLI";if(a?.entrypoint)return"Claude Code"}}finally{We.closeSync(e)}}catch{}return"Claude Code"}var Eo=class o{deps;_sessionFilesCache=null;_sessionFilesCacheTime=0;static SESSION_FILES_CACHE_TTL=6e4;_lastDiscoveryHadError=!1;_lastDiscoveryFilesCount=0;constructor(e){this.deps=e}get lastDiscoveryHadError(){return this._lastDiscoveryHadError}get lastDiscoveryFilesCount(){return this._lastDiscoveryFilesCount}clearCache(){this._sessionFilesCache=null,this._sessionFilesCacheTime=0}async pathExists(e){try{return await rn.promises.access(e),!0}catch{return!1}}pathExistsWithLogging(e,t){try{let s=rn.existsSync(e);return s||this.deps.log(`\u{1F50D} Path not found [${t}]: ${e}`),s}catch{return!1}}getDiagnosticCandidatePaths(){let e=[];for(let t of this.deps.ecosystems)if(kr(t))try{let s=t.getCandidatePaths();for(let n of s){let i=this.pathExistsWithLogging(n.path,n.source);e.push({path:n.path,exists:i,source:n.source})}}catch{}if(this.deps.windsurf){let t=this.deps.windsurf.getCascadeDir(),s=this.deps.windsurf.isRunningInDevin()?"Devin Cascade (shared with Windsurf)":"Windsurf Cascade";e.push({path:t,exists:this.pathExistsWithLogging(t,s),source:s})}return e}checkCopilotExtension(){let e=br.getExtension("GitHub.copilot"),t=br.getExtension("GitHub.copilot-chat");if(!e&&!t)this.deps.log("\u26A0\uFE0F GitHub Copilot extensions not found");else{let n=e?e.isActive?"\u2705 Active":"\u23F3 Loading":"\u274C Not found",i=t?t.isActive?"\u2705 Active":"\u23F3 Loading":"\u274C Not found";this.deps.log(`GitHub Copilot: ${n}, Chat: ${i}`)}process.env.CODESPACES==="true"&&(!e?.isActive||!t?.isActive)&&this.deps.warn("\u26A0\uFE0F Running in Codespaces with inactive Copilot extensions")}async getCopilotSessionFiles(){return this.getCopilotSessionFilesStreaming()}async tryGetSampleDataFiles(e){let t=this.deps.sampleDataDirectoryOverride?.()??Ll.getConfiguration("aiEngineeringFluency").get("sampleDataDirectory");if(!t||t.trim().length===0)return;let s=t.trim();try{if(!await this.pathExists(s)){this.deps.warn(`Sample data directory not found: ${s}`);return}let n=(await rn.promises.readdir(s)).filter(i=>i.endsWith(".json")||i.endsWith(".jsonl")).map(i=>Bl.join(s,i));return this.deps.log(`\u{1F4F8} Sample data mode: using ${n.length} file(s) from ${s}`),this._sessionFilesCache=n,this._sessionFilesCacheTime=e,this._lastDiscoveryFilesCount=n.length,n}catch(n){this.deps.warn(`Error reading sample data directory: ${n}`);return}}collectAdapterFiles(e,t,s,n,i){for(let r=0;r<e.length;r++){let a=e[r];if(a.status==="rejected"){this.deps.warn(`Could not discover ${t[r].displayName} sessions: ${a.reason}`),this._lastDiscoveryHadError=!0;continue}let c=[];for(let m of a.value.sessionFiles){let p=Ao(m);s.has(p)||(s.add(p),c.push(m))}c.length>0&&(n.push(...c),i&&i(c))}}async collectWindsurfFiles(e,t,s){if(this.deps.windsurf)try{let i=(await this.deps.windsurf.getWindsurfSessions()).map(r=>r.file).filter(r=>{let a=Ao(r);return e.has(a)?!1:(e.add(a),!0)});i.length>0&&(t.push(...i),s&&s(i))}catch(n){this.deps.warn(`Could not discover Windsurf sessions: ${n}`),this._lastDiscoveryHadError=!0}}async discoverFromAdapters(e){let t=new Set,s=[],n=Date.now(),i=this.deps.ecosystems.filter(kr);this.deps.log(`\u{1F50D} Searching for session files via ${i.length} discoverable ecosystem adapter(s) (parallel)`);let r=await Promise.allSettled(i.map(c=>c.discover(this.deps.log)));this.collectAdapterFiles(r,i,t,s,e),await this.collectWindsurfFiles(t,s,e);let a=r.reduce((c,m)=>c+(m.status==="fulfilled"?m.value.sessionFiles.length:0),0)-s.length;return a>0&&this.deps.log(`\u{1F9F9} Deduplicated ${a} duplicate session path(s)`),this.deps.log(`\u2728 Total: ${s.length} session file(s) discovered in ${((Date.now()-n)/1e3).toFixed(1)}s`),s.length===0&&this.deps.warn("\u26A0\uFE0F No session files found - Have you used GitHub Copilot Chat yet?"),s}async getCopilotSessionFilesStreaming(e){let t=Date.now();if(this._sessionFilesCache&&t-this._sessionFilesCacheTime<o.SESSION_FILES_CACHE_TTL)return this.deps.log(`\u{1F4A8} Using cached session files list (${this._sessionFilesCache.length} files, cached ${Math.round((t-this._sessionFilesCacheTime)/1e3)}s ago)`),e&&e(this._sessionFilesCache),this._sessionFilesCache;this._lastDiscoveryHadError=!1,this._lastDiscoveryFilesCount=0;let s=await this.tryGetSampleDataFiles(t);if(s)return e&&e(s),s;let n=[];try{let i=await this.discoverFromAdapters(e);return n.push(...i),this._sessionFilesCache=n,this._sessionFilesCacheTime=Date.now(),this._lastDiscoveryFilesCount=n.length,n}catch(i){return this.deps.error("Error getting session files:",i),this._lastDiscoveryHadError=!0,this._lastDiscoveryFilesCount=n.length,n}}};var ce=w(require("fs")),Ie=w(require("path")),Ps=w(require("os")),zl=w(is());var Oo=class{_sqlJsModule=null;_sqlJsInitPromise=null;_dbCache=null;_dbCacheInflight=new Map;extensionUri;constructor(e){this.extensionUri=e}getOpenCodeDataDir(){let e=Ps.platform(),t=Ps.homedir();if(e==="win32")return Ie.join(t,".local","share","opencode");let s=process.env.XDG_DATA_HOME||Ie.join(t,".local","share");return Ie.join(s,"opencode")}isOpenCodeSessionFile(e){let t=Y(e);return t.includes("/opencode/storage/session/")||t.includes("/opencode/opencode.db#ses_")}isOpenCodeDbSession(e){return e.includes("opencode.db#ses_")}async initSqlJs(){return this._sqlJsModule?this._sqlJsModule:(this._sqlJsInitPromise||(this._sqlJsInitPromise=(async()=>{let e=Ie.join(__dirname,"sql-wasm.wasm"),t;ce.existsSync(e)&&(t=ce.readFileSync(e));let s=await(0,zl.default)(t?{wasmBinary:t.buffer}:void 0);return this._sqlJsModule=s,s})().catch(e=>{throw this._sqlJsInitPromise=null,e})),this._sqlJsInitPromise)}dispose(){this.closeDbCache(),this._dbCacheInflight.clear(),this._sqlJsInitPromise=null}closeDb(e){try{e.close()}catch{}}closeDbCache(){this._dbCache&&(this.closeDb(this._dbCache.db),this._dbCache=null)}getCachedDbForPath(e){return this._dbCache?.path===e?this._dbCache.db:null}isMissingFileError(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}statOpenCodeDb(e){try{return ce.statSync(e)}catch(t){return this.isMissingFileError(t)&&this._dbCache?.path===e&&this.closeDbCache(),null}}getWalMtimeMs(e){try{return ce.statSync(e+"-wal").mtimeMs}catch{return 0}}isCachedDbCurrent(e,t){return this._dbCache?.path===e&&this._dbCache.mtimeMs===t.mtimeMs&&this._dbCache.size===t.size&&this._dbCache.walMtimeMs===this.getWalMtimeMs(e)}getDbCacheKey(e,t){return`${e}:${t.mtimeMs}:${t.size}:wal${this.getWalMtimeMs(e)}`}sameDbStats(e,t){return e.mtimeMs===t.mtimeMs&&e.size===t.size}async tryReadDbWithWal(e){let t=e+"-wal",s;try{s=ce.statSync(t).size}catch{return null}if(s===0)return null;try{let{DatabaseSync:n}=require("node:sqlite"),i=Ps.tmpdir(),r=Ie.join(i,`opencode-wal-${Date.now()}.db`),a=r+"-wal",c=r+"-shm",m=e+"-shm";ce.copyFileSync(e,r),ce.copyFileSync(t,a),ce.existsSync(m)&&ce.copyFileSync(m,c);let p=new n(r);p.exec("PRAGMA wal_checkpoint(TRUNCATE);"),p.close();let f=ce.readFileSync(r);for(let h of[r,a,c])try{ce.unlinkSync(h)}catch{}return f}catch{return null}}async refreshOpenCodeDb(e,t){let s;try{let i=await this.initSqlJs(),a=await this.tryReadDbWithWal(e)??ce.readFileSync(e);s=new i.Database(a)}catch{return this.getCachedDbForPath(e)}let n=this.statOpenCodeDb(e);return!n||!this.sameDbStats(t,n)?(this.closeDb(s),this.isCachedDbCurrent(e,n??t)?this._dbCache?.db??null:this.getCachedDbForPath(e)):(this.closeDbCache(),this._dbCache={db:s,path:e,mtimeMs:t.mtimeMs,size:t.size,walMtimeMs:this.getWalMtimeMs(e)},s)}async getOpenCodeDb(){let e=Ie.join(this.getOpenCodeDataDir(),"opencode.db"),t=this.statOpenCodeDb(e);if(!t)return this.getCachedDbForPath(e);if(this.isCachedDbCurrent(e,t))return this._dbCache?.db??null;let s=this.getDbCacheKey(e,t),n=this._dbCacheInflight.get(s);if(n)return n;let i=this.refreshOpenCodeDb(e,t);this._dbCacheInflight.set(s,i);try{return await i}finally{this._dbCacheInflight.get(s)===i&&this._dbCacheInflight.delete(s)}}async readOpenCodeDbSession(e){let t=await this.getOpenCodeDb();if(!t)return null;try{let s=t.exec("SELECT id, slug, title, time_created, time_updated, project_id, directory FROM session WHERE id = ?",[e]);if(s.length===0||s[0].values.length===0)return null;let n=s[0].values[0],i=s[0].columns,r={};for(let a=0;a<i.length;a++)r[i[a]]=n[a];return{id:r.id,slug:r.slug,title:r.title,projectID:r.project_id,directory:r.directory,time:{created:r.time_created,updated:r.time_updated}}}catch{return null}}async readOpenCodeDbMessages(e){let t=await this.getOpenCodeDb();if(!t)return[];try{let s=t.exec("SELECT id, data, time_created FROM message WHERE session_id = ? ORDER BY time_created ASC",[e]);return s.length===0?[]:s[0].values.map(n=>{let i=JSON.parse(n[1]);return i.id=n[0],i.time=i.time||{},i.time.created=i.time.created||n[2],i})}catch{return[]}}async readOpenCodeDbParts(e){let t=await this.getOpenCodeDb();if(!t)return[];try{let s=t.exec("SELECT id, data, time_created FROM part WHERE message_id = ? ORDER BY time_created ASC",[e]);return s.length===0?[]:s[0].values.map(n=>{let i=JSON.parse(n[1]);return i.id=n[0],i.time=i.time||{},i.time.created=i.time.created||n[2],i})}catch{return[]}}async discoverOpenCodeDbSessions(){let e=await this.getOpenCodeDb();if(!e)return[];try{let t=e.exec("SELECT id FROM session");return t.length===0?[]:t[0].values.map(s=>s[0])}catch{return[]}}async statSessionFile(e){if(this.isOpenCodeDbSession(e)){let t=Ie.join(this.getOpenCodeDataDir(),"opencode.db");return ce.promises.stat(t)}return ce.promises.stat(e)}readOpenCodeMessages(e){let t=this.getOpenCodeDataDir(),s=Ie.join(t,"storage","message",e),n=[];try{if(!ce.existsSync(s))return n;let i=ce.readdirSync(s,{withFileTypes:!0});for(let r of i)if(!(!r.isFile()||!r.name.endsWith(".json")))try{let a=ce.readFileSync(Ie.join(s,r.name),"utf8"),c=JSON.parse(a);n.push(c)}catch{}}catch{}return n.sort((i,r)=>(i.time?.created||0)-(r.time?.created||0)),n}readOpenCodeParts(e){let t=this.getOpenCodeDataDir(),s=Ie.join(t,"storage","part",e),n=[];try{if(!ce.existsSync(s))return n;let i=ce.readdirSync(s,{withFileTypes:!0});for(let r of i)if(!(!r.isFile()||!r.name.endsWith(".json")))try{let a=ce.readFileSync(Ie.join(s,r.name),"utf8"),c=JSON.parse(a);n.push(c)}catch{}}catch{}return n.sort((i,r)=>(i.time?.start||0)-(r.time?.start||0)),n}getOpenCodeSessionId(e){let t=e.indexOf("opencode.db#");if(t!==-1)return e.substring(t+12);let s=Ie.basename(e,".json");return s.startsWith("ses_")?s:null}async getOpenCodeMessagesForSession(e){let t=this.getOpenCodeSessionId(e);if(!t)return[];if(this.isOpenCodeDbSession(e))return this.readOpenCodeDbMessages(t);let s=await this.readOpenCodeDbMessages(t);return s.length>0?s:this.readOpenCodeMessages(t)}async getOpenCodePartsForMessage(e){let t=await this.readOpenCodeDbParts(e);return t.length>0?t:this.readOpenCodeParts(e)}async getTokensFromOpenCodeSession(e){let t=await this.getOpenCodeMessagesForSession(e);return this.getTokensFromOpenCodeMessages(t)}getTokensFromOpenCodeMessages(e){let t=0,s=0;for(let n of e)n.role==="assistant"&&n.tokens&&(typeof n.tokens.total=="number"&&(s=n.tokens.total),t+=n.tokens.reasoning||0);return{tokens:s,thinkingTokens:t}}async countOpenCodeInteractions(e){let t=await this.getOpenCodeMessagesForSession(e);return this.countOpenCodeInteractionsFromMessages(t)}countOpenCodeInteractionsFromMessages(e){return e.filter(t=>t.role==="user").length}getAssistantMessagesByParent(e){let t=new Map;for(let s of e){if(s.role!=="assistant"||!s.parentID)continue;let n=t.get(s.parentID)??[];n.push(s),t.set(s.parentID,n)}return t}async getOpenCodeModelUsage(e){let t=await this.getOpenCodeMessagesForSession(e);return this.getOpenCodeModelUsageFromMessages(t)}computeTurnCumTotal(e,t){let s=t;for(let n of e)typeof n.tokens?.total=="number"&&(s=Math.max(s,n.tokens.total));return s}getOpenCodeModelUsageFromMessages(e){let t={},s=this.getAssistantMessagesByParent(e),n=0;for(let i=0;i<e.length;i++){let r=e[i];if(r.role!=="user")continue;let a=s.get(r.id)??[];if(a.length===0)continue;let c=this.computeTurnCumTotal(a,n),m=c-n;if(m<=0){n=c;continue}let p=a[0].modelID||a[0].model?.modelID||"unknown";t[p]||(t[p]={inputTokens:0,outputTokens:0});let f=a.reduce((C,S)=>C+(S.tokens?.output||0)+(S.tokens?.reasoning||0),0);t[p].inputTokens+=Math.max(0,m-f),t[p].outputTokens+=f;let h=a.reduce((C,S)=>C+(S.tokens?.cache?.read||0),0),_=a.reduce((C,S)=>C+(S.tokens?.cache?.write||0),0);h>0&&(t[p].cachedReadTokens=(t[p].cachedReadTokens??0)+h),_>0&&(t[p].cacheCreationTokens=(t[p].cacheCreationTokens??0)+_),n=c}return t}async getOpenCodeSessionData(e){let t=await this.getOpenCodeMessagesForSession(e),s=Date.now();t.length>0&&t[0].time?.created&&(s=t[0].time.created);let{tokens:n}=this.getTokensFromOpenCodeMessages(t),i=this.countOpenCodeInteractionsFromMessages(t),r=this.getOpenCodeModelUsageFromMessages(t),a=this.getAssistantMessagesByParent(t),c={};for(let p=0;p<t.length;p++){let f=t[p];if(f.role!=="user")continue;let h=a.get(f.id)??[];if(h.length===0)continue;let _=h[0].modelID||h[0].model?.modelID||"unknown";c[_]=(c[_]||0)+1}let m={};for(let[p,f]of Object.entries(r))m[p]={...f,interactions:c[p]||0};return{tokens:n,interactions:i,modelUsage:m,timestamp:s}}};var nt=w(require("fs")),rs=w(require("path")),an=w(require("os")),$l=w(is());var Fo=class{_sqlJsModule=null;_sqlJsInitPromise=null;_dbCache=new Map;_dbCacheInflight=new Map;extensionUri;constructor(e){this.extensionUri=e}dispose(){for(let e of this._dbCache.values())try{e.db.close()}catch{}this._dbCache.clear(),this._dbCacheInflight.clear(),this._sqlJsInitPromise=null}closeDb(e){try{e.close()}catch{}}isMissingFileError(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}statCrushDb(e){try{return nt.statSync(e)}catch(t){return this.isMissingFileError(t)&&this._dbCache.has(e)&&(this.closeDb(this._dbCache.get(e).db),this._dbCache.delete(e)),null}}isCachedDbCurrent(e,t){let s=this._dbCache.get(e);return!!s&&s.mtimeMs===t.mtimeMs&&s.size===t.size}getDbCacheKey(e,t){return`${e}:${t.mtimeMs}:${t.size}`}sameDbStats(e,t){return e.mtimeMs===t.mtimeMs&&e.size===t.size}async refreshCrushDb(e,t){let s;try{let r=await this.initSqlJs(),a=nt.readFileSync(e);s=new r.Database(a)}catch{return this._dbCache.get(e)?.db??null}let n=this.statCrushDb(e);if(!n||!this.sameDbStats(t,n))return this.closeDb(s),this._dbCache.get(e)?.db??null;let i=this._dbCache.get(e);return i&&this.closeDb(i.db),this._dbCache.set(e,{db:s,mtimeMs:t.mtimeMs,size:t.size}),s}async getCrushDb(e){let t=this.statCrushDb(e);if(!t)return this._dbCache.get(e)?.db??null;if(this.isCachedDbCurrent(e,t))return this._dbCache.get(e).db;let s=this.getDbCacheKey(e,t),n=this._dbCacheInflight.get(s);if(n)return n;let i=this.refreshCrushDb(e,t);this._dbCacheInflight.set(s,i);try{return await i}finally{this._dbCacheInflight.get(s)===i&&this._dbCacheInflight.delete(s)}}getCrushConfigDir(){if(an.platform()==="win32"){let s=process.env.LOCALAPPDATA||rs.join(an.homedir(),"AppData","Local");return rs.join(s,"crush")}let t=process.env.XDG_CONFIG_HOME||rs.join(an.homedir(),".config");return rs.join(t,"crush")}readCrushProjects(){let e=rs.join(this.getCrushConfigDir(),"projects.json");if(!nt.existsSync(e))return[];try{let t=nt.readFileSync(e,"utf8"),s=JSON.parse(t);return Array.isArray(s.projects)?s.projects:[]}catch{return[]}}isCrushSessionFile(e){return de(e).includes("/.crush/crush.db#")}getCrushDbPath(e){let t=e.indexOf("crush.db#");return t===-1?e:e.substring(0,t+8)}getCrushSessionId(e){let t=e.indexOf("crush.db#");return t===-1?null:e.substring(t+9)}async initSqlJs(){return this._sqlJsModule?this._sqlJsModule:(this._sqlJsInitPromise||(this._sqlJsInitPromise=(async()=>{let e=rs.join(__dirname,"sql-wasm.wasm"),t;nt.existsSync(e)&&(t=nt.readFileSync(e));let s=await(0,$l.default)(t?{wasmBinary:t.buffer}:void 0);return this._sqlJsModule=s,s})().catch(e=>{throw this._sqlJsInitPromise=null,e})),this._sqlJsInitPromise)}async statSessionFile(e){let t=this.getCrushDbPath(e);return nt.promises.stat(t)}async discoverSessionsInDb(e){let t=await this.getCrushDb(e);if(!t)return[];try{let s=t.exec("SELECT id FROM sessions");return s.length===0?[]:s[0].values.map(n=>n[0])}catch{return[]}}async readCrushSession(e){let t=this.getCrushDbPath(e),s=this.getCrushSessionId(e);if(!s)return null;let n=await this.getCrushDb(t);if(!n)return null;try{let i=n.exec("SELECT id, title, message_count, prompt_tokens, completion_tokens, created_at, updated_at FROM sessions WHERE id = ?",[s]);if(i.length===0||i[0].values.length===0)return null;let r=i[0].columns,a=i[0].values[0],c={};return r.forEach((m,p)=>{c[m]=a[p]}),c}catch{return null}}async getCrushMessages(e){let t=this.getCrushDbPath(e),s=this.getCrushSessionId(e);if(!s)return[];let n=await this.getCrushDb(t);if(!n)return[];try{let i=n.exec("SELECT id, session_id, role, parts, model, provider, created_at, updated_at, finished_at FROM messages WHERE session_id = ? AND is_summary_message = 0 ORDER BY created_at ASC",[s]);if(i.length===0)return[];let r=i[0].columns;return i[0].values.map(a=>{let c={};if(r.forEach((m,p)=>{c[m]=a[p]}),typeof c.parts=="string")try{c.parts=JSON.parse(c.parts)}catch{c.parts=[]}return c})}catch{return[]}}async getTokensFromCrushSession(e){let t=await this.readCrushSession(e);if(!t)return{tokens:0,thinkingTokens:0};let s=typeof t.prompt_tokens=="number"?t.prompt_tokens:0,n=typeof t.completion_tokens=="number"?t.completion_tokens:0;return{tokens:s+n,thinkingTokens:0}}async countCrushInteractions(e){return(await this.getCrushMessages(e)).filter(s=>s.role==="user").length}async getCrushModelUsage(e){let t={},s=await this.readCrushSession(e);if(!s)return t;let n=typeof s.prompt_tokens=="number"?s.prompt_tokens:0,i=typeof s.completion_tokens=="number"?s.completion_tokens:0;if(n+i===0)return t;let a=(await this.getCrushMessages(e)).filter(p=>p.role==="assistant"&&p.model);if(a.length===0)return t.unknown={inputTokens:n,outputTokens:i},t;let c={};for(let p of a){let f=p.model||"unknown";c[f]=(c[f]||0)+1}let m=a.length;for(let[p,f]of Object.entries(c)){let h=f/m;t[p]={inputTokens:Math.round(n*h),outputTokens:Math.round(i*h)}}return t}async getCrushSessionData(e){let t=await this.readCrushSession(e);if(!t)return{tokens:0,interactions:0,modelUsage:{},timestamp:0};let s=typeof t.prompt_tokens=="number"?t.prompt_tokens:0,n=typeof t.completion_tokens=="number"?t.completion_tokens:0,i=s+n,r=typeof t.created_at=="number"?t.created_at*1e3:Date.now(),a=await this.getCrushModelUsage(e),m=(await this.getCrushMessages(e)).filter(h=>h.role==="user").length,p=s+n,f={};for(let[h,_]of Object.entries(a)){let C=_.inputTokens+_.outputTokens,S=p>0?C/p:0;f[h]={inputTokens:_.inputTokens,outputTokens:_.outputTokens,interactions:Math.round(m*S)}}return{tokens:i,interactions:m,modelUsage:f,timestamp:r}}getToolCallsFromMessages(e){let t=[];for(let s of e)if(!(s.role!=="assistant"||!Array.isArray(s.parts)))for(let n of s.parts)n?.type==="tool_call"&&n?.data?.name&&t.push(n.data.name);return t}};var ln=w(require("fs")),as=w(require("path")),Wl=w(require("os"));var No=class{getContinueDataDir(){return as.join(Wl.homedir(),".continue")}getContinueSessionsDir(){return as.join(this.getContinueDataDir(),"sessions")}isContinueSessionFile(e){let t=Y(e);return t.includes("/.continue/sessions/")&&t.endsWith(".json")}async getContinueSessionFiles(){let e=this.getContinueSessionsDir();try{await ln.promises.access(e)}catch{return[]}try{return(await ln.promises.readdir(e)).filter(s=>s.endsWith(".json")&&s!=="sessions.json").map(s=>as.join(e,s))}catch{return[]}}async readSessionFile(e){try{let t=await ln.promises.readFile(e,"utf8");return JSON.parse(t)}catch{return null}}estimateTokens(e){return e?Math.ceil(e.length/4):0}async getTokensFromContinueSession(e){let t=await this.readSessionFile(e);if(!t||!Array.isArray(t.history))return{tokens:0,thinkingTokens:0};let s=0,n=0;for(let i of t.history)if(Array.isArray(i.promptLogs))for(let r of i.promptLogs)s+=this.estimateTokens(r.prompt||""),n+=this.estimateTokens(r.completion||"");return{tokens:s+n,thinkingTokens:0}}async countContinueInteractions(e){let t=await this.readSessionFile(e);return!t||!Array.isArray(t.history)?0:t.history.filter(s=>s.message?.role==="user").length}async getContinueModelUsage(e){let t=await this.readSessionFile(e);if(!t||!Array.isArray(t.history))return{};let s={};for(let n of t.history)if(Array.isArray(n.promptLogs))for(let i of n.promptLogs){let r=i.modelTitle||t.chatModelTitle||"unknown";s[r]||(s[r]={inputTokens:0,outputTokens:0}),s[r].inputTokens+=this.estimateTokens(i.prompt||""),s[r].outputTokens+=this.estimateTokens(i.completion||"")}return s}async getContinueSessionMeta(e){let t=await this.readSessionFile(e);return t?{title:t.title,model:t.chatModelTitle,workspaceDirectory:t.workspaceDirectory,mode:t.mode}:null}async readSessionsIndex(){let e=as.join(this.getContinueSessionsDir(),"sessions.json"),t=new Map;try{let s=await ln.promises.readFile(e,"utf8"),n=JSON.parse(s);if(!Array.isArray(n))return t;for(let i of n)i.sessionId&&t.set(i.sessionId,{dateCreated:i.dateCreated?Number(i.dateCreated):void 0,title:i.title,workspaceDirectory:i.workspaceDirectory})}catch{}return t}getContinueSessionId(e){return as.basename(e,".json")}extractUserText(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
34
|
-
`):""}async buildContinueTurns(e){let t=await this.readSessionFile(e);if(!t||!Array.isArray(t.history))return[];let s=t.history,n=[],i=0;for(;i<s.length;){if(s[i].message?.role!=="user"){i++;continue}let{turn:a,nextIndex:c}=this.buildTurnFromHistory(s,i,t.chatModelTitle||null);n.push(a),i=c}return n}buildTurnFromHistory(e,t,s){let n=this.extractUserText(e[t].message.content),i={assistantText:"",model:s,inputTokens:0,outputTokens:0,toolCalls:[],pendingToolCalls:new Map},r=t+1;for(;r<e.length&&e[r].message?.role!=="user";){let a=e[r],c=a.message?.role;c==="assistant"?this.processAssistantSubItem(a,i):c==="tool"&&this.processToolSubItem(a,i),r++}for(let[,a]of i.pendingToolCalls)i.toolCalls.push(a);return{turn:{userText:n,assistantText:i.assistantText,model:i.model,toolCalls:i.toolCalls,inputTokens:i.inputTokens,outputTokens:i.outputTokens},nextIndex:r}}processAssistantSubItem(e,t){if(typeof e.message.content=="string"&&e.message.content&&(t.assistantText+=e.message.content),Array.isArray(e.promptLogs)&&e.promptLogs.length>0){let s=e.promptLogs[0];s.modelTitle&&(t.model=s.modelTitle);for(let n of e.promptLogs)t.inputTokens+=this.estimateTokens(n.prompt||""),t.outputTokens+=this.estimateTokens(n.completion||"")}this.collectToolCallsFromAssistant(e,t)}collectToolCallsFromAssistant(e,t){if(Array.isArray(e.message.toolCalls))for(let s of e.message.toolCalls){let n=s.function?.name||s.name||"unknown",i=s.function?.arguments,r=s.id||n;t.pendingToolCalls.set(r,{toolName:n,arguments:i})}}processToolSubItem(e,t){let s=e.message.toolCallId||"",n=this.extractUserText(e.message.content),i=t.pendingToolCalls.get(s);i?(t.toolCalls.push({...i,result:n}),t.pendingToolCalls.delete(s)):t.toolCalls.push({toolName:"unknown",result:n})}};var
|
|
35
|
-
`),n=
|
|
31
|
+
`,n)}while(s!==-1);return i+=o.slice(n),i}var Fl=(o=0)=>e=>`\x1B[${e+o}m`,Sr=(o=0)=>e=>`\x1B[${38+o};5;${e}m`,Tr=(o=0)=>(e,t,s)=>`\x1B[${38+o};2;${e};${t};${s}m`,Ym=o=>`\x1B[58;5;${o<90?o-30:o-90+8}m`,re={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],underlineDouble:["4:2",24],underlineCurly:["4:3",24],underlineDotted:["4:4",24],underlineDashed:["4:5",24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]},underlineColor:{underlineBlack:["58;5;0",59],underlineRed:["58;5;1",59],underlineGreen:["58;5;2",59],underlineYellow:["58;5;3",59],underlineBlue:["58;5;4",59],underlineMagenta:["58;5;5",59],underlineCyan:["58;5;6",59],underlineWhite:["58;5;7",59],underlineBlackBright:["58;5;8",59],underlineGray:["58;5;8",59],underlineGrey:["58;5;8",59],underlineRedBright:["58;5;9",59],underlineGreenBright:["58;5;10",59],underlineYellowBright:["58;5;11",59],underlineBlueBright:["58;5;12",59],underlineMagentaBright:["58;5;13",59],underlineCyanBright:["58;5;14",59],underlineWhiteBright:["58;5;15",59]}},Xb=Object.keys(re.modifier),Xm=Object.keys(re.color),Zm=Object.keys(re.bgColor),Zb=Object.keys(re.underlineColor),ek=[...Xm,...Zm];function ep(){let o=new Map;for(let[e,t]of Object.entries(re)){for(let[s,n]of Object.entries(t))re[s]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},t[s]=re[s],o.set(Number.parseInt(n[0],10),n[1]);Object.defineProperty(re,e,{value:t,enumerable:!1})}return Object.defineProperty(re,"codes",{value:o,enumerable:!1}),re.color.close="\x1B[39m",re.bgColor.close="\x1B[49m",re.underlineColor.close="\x1B[59m",re.color.ansi=Fl(),re.color.ansi256=Sr(),re.color.ansi16m=Tr(),re.bgColor.ansi=Fl(10),re.bgColor.ansi256=Sr(10),re.bgColor.ansi16m=Tr(10),re.underlineColor.ansi=Ym,re.underlineColor.ansi256=Sr(20),re.underlineColor.ansi16m=Tr(20),Object.defineProperties(re,{rgbToAnsi256:{value(e,t,s){return e===t&&t===s?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(s/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[\da-f]{6}|[\da-f]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[s]=t;s.length===3&&(s=[...s].map(i=>i+i).join(""));let n=Number.parseInt(s,16);return[n>>16&255,n>>8&255,n&255]},enumerable:!1},hexToAnsi256:{value:e=>re.rgbToAnsi256(...re.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,s,n;if(e>=232)t=((e-232)*10+8)/255,s=t,n=t;else{e-=16;let a=e%36;t=Math.floor(e/36)/5,s=Math.floor(a/6)/5,n=a%6/5}let i=Math.max(t,s,n)*2;if(i===0)return 30;let r=30+(Math.round(n)<<2|Math.round(s)<<1|Math.round(t));return i===2&&(r+=60),r},enumerable:!1},rgbToAnsi:{value:(e,t,s)=>re.ansi256ToAnsi(re.rgbToAnsi256(e,t,s)),enumerable:!1},hexToAnsi:{value:e=>re.ansi256ToAnsi(re.hexToAnsi256(e)),enumerable:!1}}),re}var tp=ep(),gt=tp;var Po=S(require("node:process"),1),Ll=S(require("node:os"),1),wr=S(require("node:tty"),1);function He(o,e=globalThis.Deno?globalThis.Deno.args:Po.default.argv){let t=o.startsWith("-")?"":o.length===1?"-":"--",s=e.indexOf(t+o),n=e.indexOf("--");return s!==-1&&(n===-1||s<n)}var{env:fe}=Po.default,Mo;He("no-color")||He("no-colors")||He("color=false")||He("color=never")?Mo=0:(He("color")||He("colors")||He("color=true")||He("color=always"))&&(Mo=1);function jl(){return/^\d+$/.test(fe.FORCE_COLOR)}function sp(){if("FORCE_COLOR"in fe){if(fe.FORCE_COLOR==="false")return 0;if(fe.FORCE_COLOR==="true"||fe.FORCE_COLOR.length===0)return 1;if(jl())return Math.min(Number.parseInt(fe.FORCE_COLOR,10),3)}}function np(o){return o===0?!1:{level:o,hasBasic:!0,has256:o>=2,has16m:o>=3}}function op(o,{streamIsTTY:e,sniffFlags:t=!0}={}){let s=sp();s!==void 0&&(Mo=s);let n=t?Mo:s;if(n===0)return 0;if(t){if(He("color=16m")||He("color=full")||He("color=truecolor"))return 3;if(He("color=256"))return 2}if(n!==void 0&&jl())return n;if("TF_BUILD"in fe&&"AGENT_NAME"in fe)return 1;if(o&&!e&&n===void 0)return 0;let i=n||0;if(fe.TERM==="dumb")return i;if(Po.default.platform==="win32"){let r=Ll.default.release().split(".");return Number(r[0])>=10&&Number(r[2])>=10586?Number(r[2])>=14931?3:2:1}if("CI"in fe)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(r=>r in fe)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(r=>r in fe)||fe.CI_NAME==="codeship"?1:i;if("TEAMCITY_VERSION"in fe)return/^(?:9\.0*[1-9]\d*\.|\d{2,}\.)/.test(fe.TEAMCITY_VERSION)?1:0;if(fe.COLORTERM==="truecolor"||fe.TERM==="xterm-kitty"||fe.TERM==="xterm-ghostty"||fe.TERM==="wezterm")return 3;if("TERM_PROGRAM"in fe){let r=Number.parseInt((fe.TERM_PROGRAM_VERSION||"").split(".",1)[0],10);switch(fe.TERM_PROGRAM){case"iTerm.app":return r>=3?3:2;case"Apple_Terminal":return 2}}return/-256(?:color)?$/i.test(fe.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(fe.TERM)||"COLORTERM"in fe?1:i}function Nl(o,e={}){let t=op(o,{streamIsTTY:o&&o.isTTY,...e});return np(t)}var ip={stdout:Nl({isTTY:wr.default.isatty(1)}),stderr:Nl({isTTY:wr.default.isatty(2)})},Gl=ip;var{stdout:ql,stderr:Bl}=Gl,tn=Symbol("GENERATOR"),sn=Symbol("STYLER"),Ao=Symbol("IS_EMPTY"),vo=Symbol("LEVEL"),nn=Object.create(null),zl=o=>{if(!Number.isSafeInteger(o)||o<0||o>3)throw new Error("The `level` should be an integer from 0 to 3")},rp={enumerable:!0,get(){return this[vo]},set(o){zl(o),this[vo]=o}},ap=(o,e={})=>{e.level!==void 0&&zl(e.level);let t=ql?ql.level:0;o[vo]=e.level===void 0?t:e.level};var lp=o=>{let e=(...t)=>t.join(" ");return ap(e,o),Object.setPrototypeOf(e,on.prototype),e};function on(o){return lp(o)}Object.setPrototypeOf(on.prototype,Function.prototype);for(let[o,e]of Object.entries(gt))nn[o]={get(){let t=Pr(this,$l(e.open,e.close,this[sn]),this[Ao]);return Object.defineProperty(this,o,{value:t}),t}};nn.visible={get(){let o=Pr(this,this[sn],!0);return Object.defineProperty(this,"visible",{value:o}),o}};var cp=(o,e)=>{let t=gt[e];if(o==="rgb"){let n=(r,a,c)=>t.ansi(gt.rgbToAnsi(r,a,c));return[n,n,(r,a,c)=>t.ansi256(gt.rgbToAnsi256(r,a,c)),t.ansi16m]}if(o==="hex"){let n=r=>t.ansi(gt.hexToAnsi(r));return[n,n,r=>t.ansi256(gt.hexToAnsi256(r)),r=>t.ansi16m(...gt.hexToRgb(r))]}let s=n=>t.ansi(gt.ansi256ToAnsi(n));return[s,s,t.ansi256,t.ansi256]},up=["rgb","hex","ansi256"];for(let o of up){let e=o[0].toUpperCase()+o.slice(1);for(let[t,s]of[[o,"color"],["bg"+e,"bgColor"],["underline"+e,"underlineColor"]]){let{close:n}=gt[s],i=cp(o,s);nn[t]={get(){let r=function(a,c,d){let p=i[this.level](a,c,d);return Pr(this,$l(p,n,this[sn]),this[Ao])};return Object.defineProperty(this,t,{value:r}),r}}}}var dp=Object.defineProperties(()=>{},{...nn,level:{enumerable:!0,get(){return this[tn].level},set(o){this[tn].level=o}}}),$l=(o,e,t)=>{let s,n;return t===void 0?(s=o,n=e):(s=t.openAll+o,n=e+t.closeAll),{open:o,close:e,openAll:s,closeAll:n,parent:t}},Pr=(o,e,t)=>{let s=(...n)=>n.length===1?Mr(s,""+n[0]):n.length===2?Mr(s,n[0]+" "+n[1]):Mr(s,n.join(" "));return Object.setPrototypeOf(s,dp),s[tn]=o[tn]??o,s[sn]=e,s[Ao]=t,s},Mr=(o,e)=>{if(o[tn][vo]<=0||!e)return o[Ao]?"":e;let t=o[sn];if(t===void 0)return e;let{openAll:s,closeAll:n}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=Ul(e,t.close,t.open),t=t.parent;let i=e.indexOf(`
|
|
32
|
+
`);return i!==-1&&(e=Ol(e,n,s,i)),s+e+n};Object.defineProperties(on.prototype,{...nn,level:rp});var mp=on(),rk=on({level:Bl?Bl.level:0});var w=mp;var Dt=S(require("fs")),ve=S(require("path")),Md=S(require("os"));var Hl={getConfiguration:()=>({get:()=>{}})},vr={getExtension:()=>{}},xo=class o{fsPath;scheme;path;constructor(e){this.fsPath=e,this.scheme="file",this.path=e}static file(e){return new o(e)}static joinPath(e,...t){let s=[e.fsPath,...t].join("/");return new o(s)}toString(){return this.fsPath}};var an=S(require("fs")),Kl=S(require("path"));function Ar(o){return typeof o.discover=="function"}function Jl(o){return typeof o.analyzeUsage=="function"}var We=S(require("fs"));function Do(o){if(!o||!o.startsWith("file://"))return;let e=o.slice(7),t;try{t=decodeURIComponent(e)}catch{return}if(!t.split(/[\\/]/).some(n=>n===".."))return t.startsWith("//")?process.platform==="win32"?t.replace(/\//g,"\\"):t:/^\/[A-Za-z]:/.test(t)?t.slice(1):t}function me(o){return o.replace(/\\/g,"/")}var Eo=me;function X(o){return me(o).toLowerCase()}function Ro(o,e=process.platform){let t=me(o);return e==="linux"?t:t.toLowerCase()}function xr(o,e,t){try{return o()}catch(s){return console.error(`[recovery] ${t??"unknown"}:`,s),e}}async function os(o,e,t){try{return await o()}catch(s){return console.error(`[recovery] ${t??"unknown"}:`,s),e}}var pp=/^mcp__[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}__(.+)$/i;function Vl(o){return pp.test(o)}function gp(o){return!o||o==="agent"?"agent":o.includes("plan-agent/Plan.agent.md")?"plan":o.includes(".agent.md")?"customAgent":"agent"}function Io(o){return o?typeof o=="string"?o==="edit"?"edit":o==="agent"?"agent":"ask":o.kind?o.kind==="edit"?"edit":o.kind==="ask"?"ask":o.kind==="agent"?gp(o.id):"ask":"ask":"ask"}function st(o){return o.startsWith("mcp.")||o.startsWith("mcp_")||o.startsWith("mcp__")}var fp=[["mcp_github_github_","mcp_io_github_git_"],["github-mcp-server-","mcp_io_github_git_"],["mcp_github_mcp_s2_","mcp_io_github_git_"],["mcp_github_mcp_se_","mcp_io_github_git_"],["mcp.github.github.","mcp.io.github.git."],["mcp__plugin_context7_context7__","context7-"],["mcp__context7__","context7-"],["mcp_context7_","context7-"],["mcp_io_github_ups_","context7-"],["mcp__microsoft_playwright-mcp__","microsoft_playwright-mcp-"],["mcp__playwright__","microsoft_playwright-mcp-"],["mcp_playwright_","microsoft_playwright-mcp-"],["mcp_microsoft_pla_","microsoft_playwright-mcp-"],["mcp_tavily-mcp_","io_github_tavily-ai_tavily-mcp-"],["mcp_tavily_","io_github_tavily-ai_tavily-mcp-"],["mcp__claude-in-chrome__","mcp__claude_browser__"],["mcp__Claude_Browser__","mcp__claude_browser__"]];function rn(o){for(let[e,t]of fp)if(o.startsWith(e))return t+o.substring(e.length);return o}function ft(o,e={}){let t=e[o]??e[o.toLowerCase()];if(t&&t.includes(":"))return t.split(":")[0].trim();if(o.startsWith("mcp_io_github_git_")||o.startsWith("mcp.io.github.git."))return"GitHub MCP (Local)";if(o.startsWith("mcp_github_github_")||o.startsWith("mcp.github.github."))return"GitHub MCP (Remote)";if(o.startsWith("mcp__")){if(Vl(o))return"Claude MCP";let i=o.slice(5),r=i.indexOf("__");return(r>=0?i.slice(0,r):i)||"unknown"}return o.replace(/^mcp[._]/,"").split(/[._]/)[0]||"unknown"}function Uo(o){try{let e=We.openSync(o,"r");try{let t=Buffer.alloc(65536),s=We.readSync(e,t,0,t.length,0),n=t.toString("utf8",0,s);for(let i of n.split(`
|
|
33
|
+
`)){let r=i.trim();if(!r)continue;let a;try{a=JSON.parse(r)}catch{continue}if(a?.entrypoint==="claude-desktop")return"Claude Desktop";if(a?.entrypoint==="cli")return"Claude Code CLI";if(a?.entrypoint)return"Claude Code"}}finally{We.closeSync(e)}}catch{}return"Claude Code"}var Oo=class o{deps;_sessionFilesCache=null;_sessionFilesCacheTime=0;static SESSION_FILES_CACHE_TTL=6e4;_lastDiscoveryHadError=!1;_lastDiscoveryFilesCount=0;constructor(e){this.deps=e}get lastDiscoveryHadError(){return this._lastDiscoveryHadError}get lastDiscoveryFilesCount(){return this._lastDiscoveryFilesCount}clearCache(){this._sessionFilesCache=null,this._sessionFilesCacheTime=0}async pathExists(e){try{return await an.promises.access(e),!0}catch{return!1}}pathExistsWithLogging(e,t){try{let s=an.existsSync(e);return s||this.deps.log(`\u{1F50D} Path not found [${t}]: ${e}`),s}catch{return!1}}getDiagnosticCandidatePaths(){let e=[];for(let t of this.deps.ecosystems)if(Ar(t))try{let s=t.getCandidatePaths();for(let n of s){let i=this.pathExistsWithLogging(n.path,n.source);e.push({path:n.path,exists:i,source:n.source})}}catch{}if(this.deps.windsurf){let t=this.deps.windsurf.getCascadeDir(),s=this.deps.windsurf.isRunningInDevin()?"Devin Cascade (shared with Windsurf)":"Windsurf Cascade";e.push({path:t,exists:this.pathExistsWithLogging(t,s),source:s})}return e}checkCopilotExtension(){let e=vr.getExtension("GitHub.copilot"),t=vr.getExtension("GitHub.copilot-chat");if(!e&&!t)this.deps.log("\u26A0\uFE0F GitHub Copilot extensions not found");else{let n=e?e.isActive?"\u2705 Active":"\u23F3 Loading":"\u274C Not found",i=t?t.isActive?"\u2705 Active":"\u23F3 Loading":"\u274C Not found";this.deps.log(`GitHub Copilot: ${n}, Chat: ${i}`)}process.env.CODESPACES==="true"&&(!e?.isActive||!t?.isActive)&&this.deps.warn("\u26A0\uFE0F Running in Codespaces with inactive Copilot extensions")}async getCopilotSessionFiles(){return this.getCopilotSessionFilesStreaming()}async tryGetSampleDataFiles(e){let t=this.deps.sampleDataDirectoryOverride?.()??Hl.getConfiguration("aiEngineeringFluency").get("sampleDataDirectory");if(!t||t.trim().length===0)return;let s=t.trim();try{if(!await this.pathExists(s)){this.deps.warn(`Sample data directory not found: ${s}`);return}let n=(await an.promises.readdir(s)).filter(i=>i.endsWith(".json")||i.endsWith(".jsonl")).map(i=>Kl.join(s,i));return this.deps.log(`\u{1F4F8} Sample data mode: using ${n.length} file(s) from ${s}`),this._sessionFilesCache=n,this._sessionFilesCacheTime=e,this._lastDiscoveryFilesCount=n.length,n}catch(n){this.deps.warn(`Error reading sample data directory: ${n}`);return}}collectAdapterFiles(e,t,s,n,i){for(let r=0;r<e.length;r++){let a=e[r];if(a.status==="rejected"){this.deps.warn(`Could not discover ${t[r].displayName} sessions: ${a.reason}`),this._lastDiscoveryHadError=!0;continue}let c=[];for(let d of a.value.sessionFiles){let p=Ro(d);s.has(p)||(s.add(p),c.push(d))}c.length>0&&(n.push(...c),i&&i(c))}}async collectWindsurfFiles(e,t,s){if(this.deps.windsurf)try{let i=(await this.deps.windsurf.getWindsurfSessions()).map(r=>r.file).filter(r=>{let a=Ro(r);return e.has(a)?!1:(e.add(a),!0)});i.length>0&&(t.push(...i),s&&s(i))}catch(n){this.deps.warn(`Could not discover Windsurf sessions: ${n}`),this._lastDiscoveryHadError=!0}}async discoverFromAdapters(e){let t=new Set,s=[],n=Date.now(),i=this.deps.ecosystems.filter(Ar);this.deps.log(`\u{1F50D} Searching for session files via ${i.length} discoverable ecosystem adapter(s) (parallel)`);let r=await Promise.allSettled(i.map(c=>c.discover(this.deps.log)));this.collectAdapterFiles(r,i,t,s,e),await this.collectWindsurfFiles(t,s,e);let a=r.reduce((c,d)=>c+(d.status==="fulfilled"?d.value.sessionFiles.length:0),0)-s.length;return a>0&&this.deps.log(`\u{1F9F9} Deduplicated ${a} duplicate session path(s)`),this.deps.log(`\u2728 Total: ${s.length} session file(s) discovered in ${((Date.now()-n)/1e3).toFixed(1)}s`),s.length===0&&this.deps.warn("\u26A0\uFE0F No session files found - Have you used GitHub Copilot Chat yet?"),s}async getCopilotSessionFilesStreaming(e){let t=Date.now();if(this._sessionFilesCache&&t-this._sessionFilesCacheTime<o.SESSION_FILES_CACHE_TTL)return this.deps.log(`\u{1F4A8} Using cached session files list (${this._sessionFilesCache.length} files, cached ${Math.round((t-this._sessionFilesCacheTime)/1e3)}s ago)`),e&&e(this._sessionFilesCache),this._sessionFilesCache;this._lastDiscoveryHadError=!1,this._lastDiscoveryFilesCount=0;let s=await this.tryGetSampleDataFiles(t);if(s)return e&&e(s),s;let n=[];try{let i=await this.discoverFromAdapters(e);return n.push(...i),this._sessionFilesCache=n,this._sessionFilesCacheTime=Date.now(),this._lastDiscoveryFilesCount=n.length,n}catch(i){return this.deps.error("Error getting session files:",i),this._lastDiscoveryHadError=!0,this._lastDiscoveryFilesCount=n.length,n}}};var ue=S(require("fs")),Ie=S(require("path")),ws=S(require("os")),Ql=S(Nt());var jo=class{_sqlJsModule=null;_sqlJsInitPromise=null;_dbCache=null;_dbCacheInflight=new Map;extensionUri;constructor(e){this.extensionUri=e}getOpenCodeDataDir(){let e=ws.platform(),t=ws.homedir();if(e==="win32")return Ie.join(t,".local","share","opencode");let s=process.env.XDG_DATA_HOME||Ie.join(t,".local","share");return Ie.join(s,"opencode")}isOpenCodeSessionFile(e){let t=X(e);return t.includes("/opencode/storage/session/")||t.includes("/opencode/opencode.db#ses_")}isOpenCodeDbSession(e){return e.includes("opencode.db#ses_")}async initSqlJs(){return this._sqlJsModule?this._sqlJsModule:(this._sqlJsInitPromise||(this._sqlJsInitPromise=(async()=>{let e=Ie.join(__dirname,"sql-wasm.wasm"),t;ue.existsSync(e)&&(t=ue.readFileSync(e));let s=await(0,Ql.default)(t?{wasmBinary:t.buffer}:void 0);return this._sqlJsModule=s,s})().catch(e=>{throw this._sqlJsInitPromise=null,e})),this._sqlJsInitPromise)}dispose(){this.closeDbCache(),this._dbCacheInflight.clear(),this._sqlJsInitPromise=null}closeDb(e){try{e.close()}catch{}}closeDbCache(){this._dbCache&&(this.closeDb(this._dbCache.db),this._dbCache=null)}getCachedDbForPath(e){return this._dbCache?.path===e?this._dbCache.db:null}isMissingFileError(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}statOpenCodeDb(e){try{return ue.statSync(e)}catch(t){return this.isMissingFileError(t)&&this._dbCache?.path===e&&this.closeDbCache(),null}}getWalMtimeMs(e){try{return ue.statSync(e+"-wal").mtimeMs}catch{return 0}}isCachedDbCurrent(e,t){return this._dbCache?.path===e&&this._dbCache.mtimeMs===t.mtimeMs&&this._dbCache.size===t.size&&this._dbCache.walMtimeMs===this.getWalMtimeMs(e)}getDbCacheKey(e,t){return`${e}:${t.mtimeMs}:${t.size}:wal${this.getWalMtimeMs(e)}`}sameDbStats(e,t){return e.mtimeMs===t.mtimeMs&&e.size===t.size}async tryReadDbWithWal(e){let t=e+"-wal",s;try{s=ue.statSync(t).size}catch{return null}if(s===0)return null;try{let{DatabaseSync:n}=require("node:sqlite"),i=ws.tmpdir(),r=Ie.join(i,`opencode-wal-${Date.now()}.db`),a=r+"-wal",c=r+"-shm",d=e+"-shm";ue.copyFileSync(e,r),ue.copyFileSync(t,a),ue.existsSync(d)&&ue.copyFileSync(d,c);let p=new n(r);p.exec("PRAGMA wal_checkpoint(TRUNCATE);"),p.close();let f=ue.readFileSync(r);for(let h of[r,a,c])try{ue.unlinkSync(h)}catch{}return f}catch{return null}}async refreshOpenCodeDb(e,t){let s;try{let i=await this.initSqlJs(),a=await this.tryReadDbWithWal(e)??ue.readFileSync(e);s=new i.Database(a)}catch{return this.getCachedDbForPath(e)}let n=this.statOpenCodeDb(e);return!n||!this.sameDbStats(t,n)?(this.closeDb(s),this.isCachedDbCurrent(e,n??t)?this._dbCache?.db??null:this.getCachedDbForPath(e)):(this.closeDbCache(),this._dbCache={db:s,path:e,mtimeMs:t.mtimeMs,size:t.size,walMtimeMs:this.getWalMtimeMs(e)},s)}async getOpenCodeDb(){let e=Ie.join(this.getOpenCodeDataDir(),"opencode.db"),t=this.statOpenCodeDb(e);if(!t)return this.getCachedDbForPath(e);if(this.isCachedDbCurrent(e,t))return this._dbCache?.db??null;let s=this.getDbCacheKey(e,t),n=this._dbCacheInflight.get(s);if(n)return n;let i=this.refreshOpenCodeDb(e,t);this._dbCacheInflight.set(s,i);try{return await i}finally{this._dbCacheInflight.get(s)===i&&this._dbCacheInflight.delete(s)}}async readOpenCodeDbSession(e){let t=await this.getOpenCodeDb();if(!t)return null;try{let s=t.exec("SELECT id, slug, title, time_created, time_updated, project_id, directory FROM session WHERE id = ?",[e]);if(s.length===0||s[0].values.length===0)return null;let n=s[0].values[0],i=s[0].columns,r={};for(let a=0;a<i.length;a++)r[i[a]]=n[a];return{id:r.id,slug:r.slug,title:r.title,projectID:r.project_id,directory:r.directory,time:{created:r.time_created,updated:r.time_updated}}}catch{return null}}async readOpenCodeDbMessages(e){let t=await this.getOpenCodeDb();if(!t)return[];try{let s=t.exec("SELECT id, data, time_created FROM message WHERE session_id = ? ORDER BY time_created ASC",[e]);return s.length===0?[]:s[0].values.map(n=>{let i=JSON.parse(n[1]);return i.id=n[0],i.time=i.time||{},i.time.created=i.time.created||n[2],i})}catch{return[]}}async readOpenCodeDbParts(e){let t=await this.getOpenCodeDb();if(!t)return[];try{let s=t.exec("SELECT id, data, time_created FROM part WHERE message_id = ? ORDER BY time_created ASC",[e]);return s.length===0?[]:s[0].values.map(n=>{let i=JSON.parse(n[1]);return i.id=n[0],i.time=i.time||{},i.time.created=i.time.created||n[2],i})}catch{return[]}}async discoverOpenCodeDbSessions(){let e=await this.getOpenCodeDb();if(!e)return[];try{let t=e.exec("SELECT id FROM session");return t.length===0?[]:t[0].values.map(s=>s[0])}catch{return[]}}async statSessionFile(e){if(this.isOpenCodeDbSession(e)){let t=Ie.join(this.getOpenCodeDataDir(),"opencode.db");return ue.promises.stat(t)}return ue.promises.stat(e)}readOpenCodeMessages(e){let t=this.getOpenCodeDataDir(),s=Ie.join(t,"storage","message",e),n=[];try{if(!ue.existsSync(s))return n;let i=ue.readdirSync(s,{withFileTypes:!0});for(let r of i)if(!(!r.isFile()||!r.name.endsWith(".json")))try{let a=ue.readFileSync(Ie.join(s,r.name),"utf8"),c=JSON.parse(a);n.push(c)}catch{}}catch{}return n.sort((i,r)=>(i.time?.created||0)-(r.time?.created||0)),n}readOpenCodeParts(e){let t=this.getOpenCodeDataDir(),s=Ie.join(t,"storage","part",e),n=[];try{if(!ue.existsSync(s))return n;let i=ue.readdirSync(s,{withFileTypes:!0});for(let r of i)if(!(!r.isFile()||!r.name.endsWith(".json")))try{let a=ue.readFileSync(Ie.join(s,r.name),"utf8"),c=JSON.parse(a);n.push(c)}catch{}}catch{}return n.sort((i,r)=>(i.time?.start||0)-(r.time?.start||0)),n}getOpenCodeSessionId(e){let t=e.indexOf("opencode.db#");if(t!==-1)return e.substring(t+12);let s=Ie.basename(e,".json");return s.startsWith("ses_")?s:null}async getOpenCodeMessagesForSession(e){let t=this.getOpenCodeSessionId(e);if(!t)return[];if(this.isOpenCodeDbSession(e))return this.readOpenCodeDbMessages(t);let s=await this.readOpenCodeDbMessages(t);return s.length>0?s:this.readOpenCodeMessages(t)}async getOpenCodePartsForMessage(e){let t=await this.readOpenCodeDbParts(e);return t.length>0?t:this.readOpenCodeParts(e)}async getTokensFromOpenCodeSession(e){let t=await this.getOpenCodeMessagesForSession(e);return this.getTokensFromOpenCodeMessages(t)}getTokensFromOpenCodeMessages(e){let t=0,s=0;for(let n of e)n.role==="assistant"&&n.tokens&&(typeof n.tokens.total=="number"&&(s=n.tokens.total),t+=n.tokens.reasoning||0);return{tokens:s,thinkingTokens:t}}async countOpenCodeInteractions(e){let t=await this.getOpenCodeMessagesForSession(e);return this.countOpenCodeInteractionsFromMessages(t)}countOpenCodeInteractionsFromMessages(e){return e.filter(t=>t.role==="user").length}getAssistantMessagesByParent(e){let t=new Map;for(let s of e){if(s.role!=="assistant"||!s.parentID)continue;let n=t.get(s.parentID)??[];n.push(s),t.set(s.parentID,n)}return t}async getOpenCodeModelUsage(e){let t=await this.getOpenCodeMessagesForSession(e);return this.getOpenCodeModelUsageFromMessages(t)}computeTurnCumTotal(e,t){let s=t;for(let n of e)typeof n.tokens?.total=="number"&&(s=Math.max(s,n.tokens.total));return s}getOpenCodeModelUsageFromMessages(e){let t={},s=this.getAssistantMessagesByParent(e),n=0;for(let i=0;i<e.length;i++){let r=e[i];if(r.role!=="user")continue;let a=s.get(r.id)??[];if(a.length===0)continue;let c=this.computeTurnCumTotal(a,n),d=c-n;if(d<=0){n=c;continue}let p=a[0].modelID||a[0].model?.modelID||"unknown";t[p]||(t[p]={inputTokens:0,outputTokens:0,sessions:0});let f=a.reduce((C,T)=>C+(T.tokens?.output||0)+(T.tokens?.reasoning||0),0);t[p].inputTokens+=Math.max(0,d-f),t[p].outputTokens+=f;let h=a.reduce((C,T)=>C+(T.tokens?.cache?.read||0),0),_=a.reduce((C,T)=>C+(T.tokens?.cache?.write||0),0);h>0&&(t[p].cachedReadTokens=(t[p].cachedReadTokens??0)+h),_>0&&(t[p].cacheCreationTokens=(t[p].cacheCreationTokens??0)+_),n=c}return t}async getOpenCodeSessionData(e){let t=await this.getOpenCodeMessagesForSession(e),s=Date.now();t.length>0&&t[0].time?.created&&(s=t[0].time.created);let{tokens:n}=this.getTokensFromOpenCodeMessages(t),i=this.countOpenCodeInteractionsFromMessages(t),r=this.getOpenCodeModelUsageFromMessages(t),a=this.getAssistantMessagesByParent(t),c={};for(let p=0;p<t.length;p++){let f=t[p];if(f.role!=="user")continue;let h=a.get(f.id)??[];if(h.length===0)continue;let _=h[0].modelID||h[0].model?.modelID||"unknown";c[_]=(c[_]||0)+1}let d={};for(let[p,f]of Object.entries(r))d[p]={...f,interactions:c[p]||0};return{tokens:n,interactions:i,modelUsage:d,timestamp:s}}};var nt=S(require("fs")),rs=S(require("path")),ln=S(require("os")),Yl=S(Nt());var Go=class{_sqlJsModule=null;_sqlJsInitPromise=null;_dbCache=new Map;_dbCacheInflight=new Map;extensionUri;constructor(e){this.extensionUri=e}dispose(){for(let e of this._dbCache.values())try{e.db.close()}catch{}this._dbCache.clear(),this._dbCacheInflight.clear(),this._sqlJsInitPromise=null}closeDb(e){try{e.close()}catch{}}isMissingFileError(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}statCrushDb(e){try{return nt.statSync(e)}catch(t){return this.isMissingFileError(t)&&this._dbCache.has(e)&&(this.closeDb(this._dbCache.get(e).db),this._dbCache.delete(e)),null}}isCachedDbCurrent(e,t){let s=this._dbCache.get(e);return!!s&&s.mtimeMs===t.mtimeMs&&s.size===t.size}getDbCacheKey(e,t){return`${e}:${t.mtimeMs}:${t.size}`}sameDbStats(e,t){return e.mtimeMs===t.mtimeMs&&e.size===t.size}async refreshCrushDb(e,t){let s;try{let r=await this.initSqlJs(),a=nt.readFileSync(e);s=new r.Database(a)}catch{return this._dbCache.get(e)?.db??null}let n=this.statCrushDb(e);if(!n||!this.sameDbStats(t,n))return this.closeDb(s),this._dbCache.get(e)?.db??null;let i=this._dbCache.get(e);return i&&this.closeDb(i.db),this._dbCache.set(e,{db:s,mtimeMs:t.mtimeMs,size:t.size}),s}async getCrushDb(e){let t=this.statCrushDb(e);if(!t)return this._dbCache.get(e)?.db??null;if(this.isCachedDbCurrent(e,t))return this._dbCache.get(e).db;let s=this.getDbCacheKey(e,t),n=this._dbCacheInflight.get(s);if(n)return n;let i=this.refreshCrushDb(e,t);this._dbCacheInflight.set(s,i);try{return await i}finally{this._dbCacheInflight.get(s)===i&&this._dbCacheInflight.delete(s)}}getCrushConfigDir(){if(ln.platform()==="win32"){let s=process.env.LOCALAPPDATA||rs.join(ln.homedir(),"AppData","Local");return rs.join(s,"crush")}let t=process.env.XDG_CONFIG_HOME||rs.join(ln.homedir(),".config");return rs.join(t,"crush")}readCrushProjects(){let e=rs.join(this.getCrushConfigDir(),"projects.json");if(!nt.existsSync(e))return[];try{let t=nt.readFileSync(e,"utf8"),s=JSON.parse(t);return Array.isArray(s.projects)?s.projects:[]}catch{return[]}}isCrushSessionFile(e){return me(e).includes("/.crush/crush.db#")}getCrushDbPath(e){let t=e.indexOf("crush.db#");return t===-1?e:e.substring(0,t+8)}getCrushSessionId(e){let t=e.indexOf("crush.db#");return t===-1?null:e.substring(t+9)}async initSqlJs(){return this._sqlJsModule?this._sqlJsModule:(this._sqlJsInitPromise||(this._sqlJsInitPromise=(async()=>{let e=rs.join(__dirname,"sql-wasm.wasm"),t;nt.existsSync(e)&&(t=nt.readFileSync(e));let s=await(0,Yl.default)(t?{wasmBinary:t.buffer}:void 0);return this._sqlJsModule=s,s})().catch(e=>{throw this._sqlJsInitPromise=null,e})),this._sqlJsInitPromise)}async statSessionFile(e){let t=this.getCrushDbPath(e);return nt.promises.stat(t)}async discoverSessionsInDb(e){let t=await this.getCrushDb(e);if(!t)return[];try{let s=t.exec("SELECT id FROM sessions");return s.length===0?[]:s[0].values.map(n=>n[0])}catch{return[]}}async readCrushSession(e){let t=this.getCrushDbPath(e),s=this.getCrushSessionId(e);if(!s)return null;let n=await this.getCrushDb(t);if(!n)return null;try{let i=n.exec("SELECT id, title, message_count, prompt_tokens, completion_tokens, created_at, updated_at FROM sessions WHERE id = ?",[s]);if(i.length===0||i[0].values.length===0)return null;let r=i[0].columns,a=i[0].values[0],c={};return r.forEach((d,p)=>{c[d]=a[p]}),c}catch{return null}}async getCrushMessages(e){let t=this.getCrushDbPath(e),s=this.getCrushSessionId(e);if(!s)return[];let n=await this.getCrushDb(t);if(!n)return[];try{let i=n.exec("SELECT id, session_id, role, parts, model, provider, created_at, updated_at, finished_at FROM messages WHERE session_id = ? AND is_summary_message = 0 ORDER BY created_at ASC",[s]);if(i.length===0)return[];let r=i[0].columns;return i[0].values.map(a=>{let c={};if(r.forEach((d,p)=>{c[d]=a[p]}),typeof c.parts=="string")try{c.parts=JSON.parse(c.parts)}catch{c.parts=[]}return c})}catch{return[]}}async getTokensFromCrushSession(e){let t=await this.readCrushSession(e);if(!t)return{tokens:0,thinkingTokens:0};let s=typeof t.prompt_tokens=="number"?t.prompt_tokens:0,n=typeof t.completion_tokens=="number"?t.completion_tokens:0;return{tokens:s+n,thinkingTokens:0}}async countCrushInteractions(e){return(await this.getCrushMessages(e)).filter(s=>s.role==="user").length}async getCrushModelUsage(e){let t={},s=await this.readCrushSession(e);if(!s)return t;let n=typeof s.prompt_tokens=="number"?s.prompt_tokens:0,i=typeof s.completion_tokens=="number"?s.completion_tokens:0;if(n+i===0)return t;let a=(await this.getCrushMessages(e)).filter(p=>p.role==="assistant"&&p.model);if(a.length===0)return t.unknown={inputTokens:n,outputTokens:i,sessions:0},t;let c={};for(let p of a){let f=p.model||"unknown";c[f]=(c[f]||0)+1}let d=a.length;for(let[p,f]of Object.entries(c)){let h=f/d;t[p]={inputTokens:Math.round(n*h),outputTokens:Math.round(i*h),sessions:0}}return t}async getCrushSessionData(e){let t=await this.readCrushSession(e);if(!t)return{tokens:0,interactions:0,modelUsage:{},timestamp:0};let s=typeof t.prompt_tokens=="number"?t.prompt_tokens:0,n=typeof t.completion_tokens=="number"?t.completion_tokens:0,i=s+n,r=typeof t.created_at=="number"?t.created_at*1e3:Date.now(),a=await this.getCrushModelUsage(e),d=(await this.getCrushMessages(e)).filter(h=>h.role==="user").length,p=s+n,f={};for(let[h,_]of Object.entries(a)){let C=_.inputTokens+_.outputTokens,T=p>0?C/p:0;f[h]={inputTokens:_.inputTokens,outputTokens:_.outputTokens,sessions:_.sessions,interactions:Math.round(d*T)}}return{tokens:i,interactions:d,modelUsage:f,timestamp:r}}getToolCallsFromMessages(e){let t=[];for(let s of e)if(!(s.role!=="assistant"||!Array.isArray(s.parts)))for(let n of s.parts)n?.type==="tool_call"&&n?.data?.name&&t.push(n.data.name);return t}};var cn=S(require("fs")),as=S(require("path")),Xl=S(require("os"));var qo=class{getContinueDataDir(){return as.join(Xl.homedir(),".continue")}getContinueSessionsDir(){return as.join(this.getContinueDataDir(),"sessions")}isContinueSessionFile(e){let t=X(e);return t.includes("/.continue/sessions/")&&t.endsWith(".json")}async getContinueSessionFiles(){let e=this.getContinueSessionsDir();try{await cn.promises.access(e)}catch{return[]}try{return(await cn.promises.readdir(e)).filter(s=>s.endsWith(".json")&&s!=="sessions.json").map(s=>as.join(e,s))}catch{return[]}}async readSessionFile(e){try{let t=await cn.promises.readFile(e,"utf8");return JSON.parse(t)}catch{return null}}estimateTokens(e){return e?Math.ceil(e.length/4):0}async getTokensFromContinueSession(e){let t=await this.readSessionFile(e);if(!t||!Array.isArray(t.history))return{tokens:0,thinkingTokens:0};let s=0,n=0;for(let i of t.history)if(Array.isArray(i.promptLogs))for(let r of i.promptLogs)s+=this.estimateTokens(r.prompt||""),n+=this.estimateTokens(r.completion||"");return{tokens:s+n,thinkingTokens:0}}async countContinueInteractions(e){let t=await this.readSessionFile(e);return!t||!Array.isArray(t.history)?0:t.history.filter(s=>s.message?.role==="user").length}async getContinueModelUsage(e){let t=await this.readSessionFile(e);if(!t||!Array.isArray(t.history))return{};let s={};for(let n of t.history)if(Array.isArray(n.promptLogs))for(let i of n.promptLogs){let r=i.modelTitle||t.chatModelTitle||"unknown";s[r]||(s[r]={inputTokens:0,outputTokens:0,sessions:0}),s[r].inputTokens+=this.estimateTokens(i.prompt||""),s[r].outputTokens+=this.estimateTokens(i.completion||"")}return s}async getContinueSessionMeta(e){let t=await this.readSessionFile(e);return t?{title:t.title,model:t.chatModelTitle,workspaceDirectory:t.workspaceDirectory,mode:t.mode}:null}async readSessionsIndex(){let e=as.join(this.getContinueSessionsDir(),"sessions.json"),t=new Map;try{let s=await cn.promises.readFile(e,"utf8"),n=JSON.parse(s);if(!Array.isArray(n))return t;for(let i of n)i.sessionId&&t.set(i.sessionId,{dateCreated:i.dateCreated?Number(i.dateCreated):void 0,title:i.title,workspaceDirectory:i.workspaceDirectory})}catch{}return t}getContinueSessionId(e){return as.basename(e,".json")}extractUserText(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
34
|
+
`):""}async buildContinueTurns(e){let t=await this.readSessionFile(e);if(!t||!Array.isArray(t.history))return[];let s=t.history,n=[],i=0;for(;i<s.length;){if(s[i].message?.role!=="user"){i++;continue}let{turn:a,nextIndex:c}=this.buildTurnFromHistory(s,i,t.chatModelTitle||null);n.push(a),i=c}return n}buildTurnFromHistory(e,t,s){let n=this.extractUserText(e[t].message.content),i={assistantText:"",model:s,inputTokens:0,outputTokens:0,toolCalls:[],pendingToolCalls:new Map},r=t+1;for(;r<e.length&&e[r].message?.role!=="user";){let a=e[r],c=a.message?.role;c==="assistant"?this.processAssistantSubItem(a,i):c==="tool"&&this.processToolSubItem(a,i),r++}for(let[,a]of i.pendingToolCalls)i.toolCalls.push(a);return{turn:{userText:n,assistantText:i.assistantText,model:i.model,toolCalls:i.toolCalls,inputTokens:i.inputTokens,outputTokens:i.outputTokens},nextIndex:r}}processAssistantSubItem(e,t){if(typeof e.message.content=="string"&&e.message.content&&(t.assistantText+=e.message.content),Array.isArray(e.promptLogs)&&e.promptLogs.length>0){let s=e.promptLogs[0];s.modelTitle&&(t.model=s.modelTitle);for(let n of e.promptLogs)t.inputTokens+=this.estimateTokens(n.prompt||""),t.outputTokens+=this.estimateTokens(n.completion||"")}this.collectToolCallsFromAssistant(e,t)}collectToolCallsFromAssistant(e,t){if(Array.isArray(e.message.toolCalls))for(let s of e.message.toolCalls){let n=s.function?.name||s.name||"unknown",i=s.function?.arguments,r=s.id||n;t.pendingToolCalls.set(r,{toolName:n,arguments:i})}}processToolSubItem(e,t){let s=e.message.toolCallId||"",n=this.extractUserText(e.message.content),i=t.pendingToolCalls.get(s);i?(t.toolCalls.push({...i,result:n}),t.pendingToolCalls.delete(s)):t.toolCalls.push({toolName:"unknown",result:n})}};var As=S(require("fs")),it=S(require("path")),Ir=S(require("os"));function L(o){let e=o.getFullYear(),t=String(o.getMonth()+1).padStart(2,"0"),s=String(o.getDate()).padStart(2,"0");return`${e}-${t}-${s}`}function hp(o){if(typeof o!="object"||o===null)return;let t=o.result;if(!(typeof t!="object"||t===null))return t}function yp(o){if(typeof o!="object"||o===null)return;let t=o.response;if(Array.isArray(t))return t}function _p(o){return typeof o!="object"||o===null?!1:o.kind==="toolInvocationSerialized"}function Cp(o){return typeof o!="object"||o===null?!1:o.kind==="subagent"}var bp=20,kp=5,Sp=130,Tp=50,wp=10,Mp=.25,Pp=10,Zl=new WeakMap;function vp(o){let e=Zl.get(o);return e||(e=Object.entries(o).map(([t,s])=>[t,t.replace("-",""),s]),Zl.set(o,e)),e}function Z(o,e="gpt-4",t={}){let s=Mp;for(let[n,i,r]of vp(t))if(e.includes(n)||e.includes(i)){s=r;break}return Math.ceil(o.length*s)}function Ap(o){return o.trim().toLowerCase().replace(/\s+/g,"-")}function Ms(o){if(!_p(o))return null;let e=o.toolSpecificData;if(!Cp(e))return null;let t=typeof e.prompt=="string"?e.prompt:"",s="";if(typeof e.result=="string")s=e.result;else if(e.result!==null&&typeof e.result=="object"){let r=Object.entries(e.result);r.sort(([a],[c])=>Number(a)-Number(c)),s=r.map(([,a])=>typeof a=="string"?a:"").join("")}let n=typeof e.modelName=="string"?e.modelName:"",i=n?Ap(n):"";return t||s?{prompt:t,result:s,modelName:i}:null}function Ps(o){if(typeof o!="object"||o===null)return{text:"",isThinking:!1};let e=o;if(e.kind==="thinking"){let n=e.value;return{text:typeof n=="string"?n:"",isThinking:!0}}let t=e.content;if(typeof t=="object"&&t!==null){let n=t.value;if(typeof n=="string"&&n)return{text:n,isThinking:!1}}let s=e.value;return typeof s=="string"&&s?{text:s,isThinking:!1}:{text:"",isThinking:!1}}var Xk=1/1e11;function xp(o){return typeof o.promptTokens=="number"?o.promptTokens:o.metadata&&typeof o.metadata.promptTokens=="number"?o.metadata.promptTokens:o.usage&&typeof o.usage.promptTokens=="number"?o.usage.promptTokens:0}function Dp(o){if(typeof o.promptTokens=="number"&&typeof o.outputTokens=="number")return o.promptTokens+o.outputTokens;if(o.metadata&&typeof o.metadata.promptTokens=="number"&&typeof o.metadata.outputTokens=="number")return o.metadata.promptTokens+o.metadata.outputTokens;if(o.usage){let e=typeof o.usage.promptTokens=="number"?o.usage.promptTokens:0,t=typeof o.usage.completionTokens=="number"?o.usage.completionTokens:0;return e+t}return 0}function Ep(o,e){let t=o.length;for(let i of e.keys())i+1>t&&(t=i+1);let s=0,n=0;for(let i=0;i<t;i++){let r=hp(o[i]),a=r?Dp(r):0;if(a>0)s+=a,n=Math.max(n,xp(r));else{let c=e.get(i);c&&(s+=c.promptTokens+c.outputTokens,n=Math.max(n,c.promptTokens))}}return{total:s,maxPromptTokens:n}}function Rp(o){let e=Ms(o);if(!e)return 0;let t=0;return e.prompt&&(t+=Z(e.prompt)),e.result&&(t+=Z(e.result)),t}function Ip(o){let e=0;for(let t of o){let s=yp(t);if(s)for(let n of s)e+=Rp(n)}return e}function Up(o){let e=o.k;if(o.kind!==2||e?.[0]!=="requests"||!Array.isArray(o.v))return 0;let t=0;for(let s of o.v){let i=s.message;i?.text&&(t+=Z(String(i.text)))}return t}function Op(o,e){if(Ms(o))return;let{text:t,isThinking:s}=Ps(o);t&&(s?e.totalThinkingTokens+=Z(t):e.totalTokens+=Z(t))}function Fp(o,e){let t=o.k;if(!(o.kind!==2||!t?.includes("response")||!Array.isArray(o.v)))for(let s of o.v)Op(s,e)}var Dr=class{estimate(e){let t={totalTokens:0,totalThinkingTokens:0,parseFailedLines:0},s={};for(let d of e)if(d.trim())try{let p=JSON.parse(d);s=un(s,p),t.totalTokens+=Up(p),Fp(p,t)}catch{t.parseFailedLines++}let n=t.parseFailedLines>0?Rr(e):new Map,i=s.requests,r=Array.isArray(i)?i:[],{total:a,maxPromptTokens:c}=Ep(r,n);return t.totalTokens+=Ip(r),{tokens:t.totalTokens+t.totalThinkingTokens,thinkingTokens:t.totalThinkingTokens,actualTokens:a,cacheReadTokens:0,modelUsage:{},dailyActualTokens:{},copilotNanoAiu:0,...c>0?{maxRequestInputTokens:c}:{}}}};function Np(o,e,t){let s=e?.usage;if(!s)return 0;let n=typeof s.inputTokens=="number"?s.inputTokens:0,i=typeof s.outputTokens=="number"?s.outputTokens:0,r=typeof s.cacheReadTokens=="number"?s.cacheReadTokens:0,a=typeof s.cacheWriteTokens=="number"?s.cacheWriteTokens:0;return t.cliActualTokens+=n+i,t.cliCacheReadTokens+=r,t.cliShutdownModelUsage[o]||(t.cliShutdownModelUsage[o]={inputTokens:0,outputTokens:0,sessions:0}),t.cliShutdownModelUsage[o].inputTokens+=n,t.cliShutdownModelUsage[o].outputTokens+=i,r>0&&(t.cliShutdownModelUsage[o].cachedReadTokens=(t.cliShutdownModelUsage[o].cachedReadTokens??0)+r),a>0&&(t.cliShutdownModelUsage[o].cacheCreationTokens=(t.cliShutdownModelUsage[o].cacheCreationTokens??0)+a),n+i}function Lp(o,e){let t=o.data;if(!t?.modelMetrics)return;e.cliShutdownModelUsage||(e.cliShutdownModelUsage={});let s=0;for(let[i,r]of Object.entries(t.modelMetrics))s+=Np(i,r,e);let n=typeof t.totalNanoAiu=="number"?t.totalNanoAiu:0;if(n>0&&(e.cliTotalNanoAiu+=n),s>0&&o.timestamp){let i=L(new Date(String(o.timestamp)));i&&i!=="Inval"&&(e.dailyActualTokens[i]=(e.dailyActualTokens[i]||0)+s)}}function jp(o,e){let s=o.data?.contextTier;typeof s=="string"&&s&&(e.contextTier=s)}function Gp(o,e){let t=o.data,s=typeof t?.messagesRemovedDuringTruncation=="number"?t.messagesRemovedDuringTruncation:0;s>0&&(e.truncationCount++,e.messagesRemovedByTruncation+=s)}function qp(o,e){let t=o?.reasoningText;typeof t=="string"&&t&&(e.totalThinkingTokens+=Z(t));let s=o?.thinking?.text;typeof s=="string"&&s&&(e.totalThinkingTokens+=Z(s))}function Bp(o,e,t){t.cliRealOutputByModel||(t.cliRealOutputByModel={});let s=String(o?.model??"unknown");t.cliRealOutputByModel[s]=(t.cliRealOutputByModel[s]??0)+e}function zp(o,e){let t=o.data,s=typeof t?.outputTokens=="number"?t.outputTokens:0;s>0?Bp(t,s,e):t?.content&&(e.totalTokens+=Z(String(t.content))),qp(t,e)}function $p(o,e){if(!o?.result)return;let t=o.result,s=typeof t.detailedContent=="string"?t.detailedContent:typeof t.content=="string"?t.content:"";s&&(e.totalTokens+=Z(s))}function Hp(o,e){let t=o.data;o.type==="user.message"&&t?.content?e.totalTokens+=Z(String(t.content)):o.type==="user.message_rendered"&&t?.renderedMessage?e.totalTokens+=Z(String(t.renderedMessage)):o.type==="assistant.message"?zp(o,e):o.type==="tool.execution_start"?e.totalEstToolCalls++:o.type==="tool.execution_complete"?$p(t,e):o.content&&(e.totalTokens+=Z(String(o.content)))}function Wp(o){if(!o.cliRealOutputByModel)return;let e=o.totalEstToolCalls>bp?Sp:o.totalEstToolCalls>kp?Tp:wp;for(let t of Object.values(o.cliRealOutputByModel)){let s=Math.round(t*e);o.cliActualTokens+=s+t,o.cliCacheReadTokens+=s}}var Er=class{estimate(e){let t={totalTokens:0,totalThinkingTokens:0,cliActualTokens:0,cliCacheReadTokens:0,cliShutdownModelUsage:null,cliRealOutputByModel:null,totalEstToolCalls:0,dailyActualTokens:{},cliTotalNanoAiu:0,truncationCount:0,messagesRemovedByTruncation:0,contextTier:null};for(let s of e)if(s.trim())try{let n=JSON.parse(s);n.type==="session.shutdown"?Lp(n,t):n.type==="session.truncation"?Gp(n,t):(n.type==="session.start"||n.type==="session.resume"||n.type==="session.model_change")&&jp(n,t),Hp(n,t)}catch{}return t.cliActualTokens||Wp(t),{tokens:t.totalTokens+t.totalThinkingTokens,thinkingTokens:t.totalThinkingTokens,actualTokens:t.cliActualTokens,cacheReadTokens:t.cliCacheReadTokens,modelUsage:t.cliShutdownModelUsage??{},dailyActualTokens:t.dailyActualTokens,copilotNanoAiu:t.cliTotalNanoAiu,...t.truncationCount>0?{truncationCount:t.truncationCount,messagesRemovedByTruncation:t.messagesRemovedByTruncation}:{},...t.contextTier?{contextTier:t.contextTier}:{}}}};function Jp(o){let e=0;for(let t of o)if(t.trim()){if(++e>Pp)break;try{if(typeof JSON.parse(t).kind=="number")return new Dr}catch{}}return new Er}function Bo(o,e){let t=o.trim().split(`
|
|
35
|
+
`),n=Jp(t).estimate(t);return e?{...n,actualTokens:e.actualTokens,cacheReadTokens:e.cacheReadTokens,copilotNanoAiu:e.nanoAiu||n.copilotNanoAiu}:n}function Vp(o,e){e.modelTurns++;let t=o.attrs,s=typeof t?.inputTokens=="number"?t.inputTokens:0,n=typeof t?.outputTokens=="number"?t.outputTokens:0,i=typeof t?.cachedTokens=="number"?t.cachedTokens:0,r=typeof t?.copilotUsageNanoAiu=="number"?t.copilotUsageNanoAiu:0;e.inputTokens+=s,e.outputTokens+=n,e.cachedTokens+=i,e.copilotNanoAiu+=r,e.maxRequestInputTokens=Math.max(e.maxRequestInputTokens,s);let a=typeof t?.model=="string"&&t.model?t.model:"";if(!a)return;let c=e.modelBreakdown[a]??{inputTokens:0,outputTokens:0,cachedTokens:0};c.inputTokens+=s,c.outputTokens+=n,c.cachedTokens+=i,e.modelBreakdown[a]=c}function sc(o){let e={inputTokens:0,outputTokens:0,cachedTokens:0,modelTurns:0,modelBreakdown:{},copilotNanoAiu:0,maxRequestInputTokens:0};for(let t of o.split(/\r?\n/))if(t.trim())try{let s=JSON.parse(t);s.type==="llm_request"&&Vp(s,e)}catch{}return e.modelTurns>0?e:null}function nc(o){if(!o||typeof o!="object")return null;let t=o.metadata;if(!t||typeof t!="object")return null;let n=t.configurationSchema;if(!n||typeof n!="object")return null;let r=n.properties;if(!r||typeof r!="object")return null;let c=r.reasoningEffort;if(!c||typeof c!="object")return null;let d=c;return typeof d.default=="string"?d.default:null}function Kp(o,e){let s=o.v?.inputState,n=nc(s?.selectedModel);n!==null&&(e.currentEffort=n,e.defaultEffort=n)}function Qp(o,e){let t=o.k;if(!Array.isArray(t)||t[0]!=="inputState"||t[1]!=="selectedModel")return;let s=nc(o.v);s!==null&&s!==e.currentEffort&&(e.currentEffort!==null&&e.switchCount++,e.currentEffort=s)}function Yp(o,e){let t=o.k;if(!Array.isArray(t)||t[0]!=="requests"||typeof t[1]!="number"||e.currentEffort===null)return;let s=o.v;if(!s||typeof s!="object")return;let n=typeof s.requestId=="string"?s.requestId:null;n&&e.effortByRequestId.set(n,e.currentEffort)}function oc(o){let e={effortByRequestId:new Map,currentEffort:null,defaultEffort:null,switchCount:0};for(let t of o){if(!t.trim())continue;let s;try{s=JSON.parse(t)}catch{continue}typeof s.kind=="number"&&(s.kind===0?Kp(s,e):s.kind===1?Qp(s,e):s.kind===2&&Yp(s,e))}return{effortByRequestId:e.effortByRequestId,defaultEffort:e.defaultEffort,switchCount:e.switchCount}}function Rr(o){let e=new Map;for(let t of o){if(!t.includes('"result"'))continue;let s=t.match(/"k":\s*\["requests",\s*(\d+),\s*"result"\]/);if(!s)continue;let n=parseInt(s[1],10),i=t.match(/"promptTokens":(\d+)/),r=t.match(/"outputTokens":(\d+)/),a=t.match(/"completionTokens":(\d+)/);i&&(r||a)&&e.set(n,{promptTokens:parseInt(i[1],10),outputTokens:parseInt(r?.[1]||a[1],10)})}return e}var ec=new WeakMap;function ic(o){let e=ec.get(o);if(!e){let t={};for(let[n,i]of Object.entries(o))if(i.displayNames)for(let r of i.displayNames)t[r]=n;let s=Object.keys(t).sort((n,i)=>i.length-n.length);e={map:t,sortedNames:s},ec.set(o,e)}return e}function Xp(o,e){let{map:t,sortedNames:s}=ic(e);for(let n of s)if(o.includes(n))return t[n];return null}function Zp(o,e){let{map:t,sortedNames:s}=ic(e);for(let n of s)if(o.includes(n))return t[n];return null}function Lt(o,e={}){if(o.modelId)return o.modelId.replace(/^copilot\//,"");if(o.result?.metadata?.modelId)return o.result.metadata.modelId.replace(/^copilot\//,"");if(o.result?.details){let t=Zp(o.result.details,e);if(t)return t}if(o.result?.metadata?.modelId)return o.result.metadata.modelId.replace(/^copilot\//,"");if(o.result?.details){let t=Xp(o.result.details,e);if(t)return t}return"gpt-4"}function bt(o){let e=o.trim();if(!e.includes(`
|
|
36
36
|
`))return!1;let t=e.split(`
|
|
37
|
-
`).filter(i=>i.trim());if(t.length<2)return!1;let s=t[0].trim(),n=t[1].trim();return s.startsWith("{")&&s.endsWith("}")&&n.startsWith("{")&&n.endsWith("}")}function
|
|
37
|
+
`).filter(i=>i.trim());if(t.length<2)return!1;let s=t[0].trim(),n=t[1].trim();return s.startsWith("{")&&s.endsWith("}")&&n.startsWith("{")&&n.endsWith("}")}function vs(o){let e=o.trim();return/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(e)}function eg(o,e,t){if(Array.isArray(o)){let s=Number(e);return(!o[s]||typeof o[s]!="object")&&(o[s]=t?[]:{}),o[s]}else return(!o[e]||typeof o[e]!="object")&&(o[e]=t?[]:{}),o[e]}function tg(o,e,t){Array.isArray(o)?o[Number(e)]=t:o[e]=t}function sg(o,e){Array.isArray(e)?o.push(...e):o.push(e)}function ng(o,e,t){let s;if(Array.isArray(o)){let n=Number(e);Array.isArray(o[n])||(o[n]=[]),s=o[n]}else Array.isArray(o[e])||(o[e]=[]),s=o[e];sg(s,t)}function un(o,e){if(typeof e!="object"||e===null)return o;let t=e,{kind:s,k:n,v:i}=t;if(s===0)return i;if(!Array.isArray(n)||n.length===0)return o;let r=n.map(String),a=typeof o=="object"&&o!==null?o:{},c=a;for(let p=0;p<r.length-1;p++)c=eg(c,r[p],/^\d+$/.test(r[p+1]));let d=r[r.length-1];return s===1?(tg(c,d,i),a):(s===2&&ng(c,d,i),a)}function ls(o,e={}){let t=e[o];if(t?.tier)return t.tier;for(let[s,n]of Object.entries(e))if((o.includes(s)||s.includes(o))&&n.tier)return n.tier;return"unknown"}function tc(o){let e=o.copilotPricing?.inputCostPerMillion??o.inputCostPerMillion??null;return e!==null?e<2?"low":e<5?"medium":"high":"unknown"}function dn(o,e={}){let t=e[o];if(t)return tc(t);for(let[s,n]of Object.entries(e))if(o.includes(s)||s.includes(o))return tc(n);return"unknown"}function ot(o,e={},t="provider"){let s=0;for(let[n,i]of Object.entries(o)){let r=e[n];if(!r)continue;let a=t==="copilot"&&r.copilotPricing?r.copilotPricing:r,c=i.cachedReadTokens??0,d=i.cacheCreationTokens??0,p=Math.min(i.cacheCreation1hTokens??0,d),f=d-p,_=Math.max(0,i.inputTokens-c-d)/1e6*a.inputCostPerMillion,C=c/1e6*(a.cachedInputCostPerMillion??a.inputCostPerMillion),T=f/1e6*(a.cacheCreationCostPerMillion??a.inputCostPerMillion),E=p/1e6*(a.cacheCreation1hCostPerMillion??a.cacheCreationCostPerMillion??a.inputCostPerMillion),A=i.outputTokens/1e6*a.outputCostPerMillion;s+=_+C+T+E+A}return s}function G(){return{file:0,selection:0,implicitSelection:0,symbol:0,codebase:0,workspace:0,terminal:0,vscode:0,terminalLastCommand:0,terminalSelection:0,clipboard:0,changes:0,outputPanel:0,problemsPanel:0,pullRequest:0,codeContextLines:0,byKind:{},copilotInstructions:0,agentsMd:0,byPath:{}}}var og="com.microsoft.copilot.eclipse",rc=it.join(".metadata",".plugins","com.microsoft.copilot.eclipse.core","conversations"),zo=class{getDefaultWorkspaceRoot(){return it.join(Ir.homedir(),"eclipse-workspace")}getEclipseInstallsRoot(){return it.join(Ir.homedir(),"eclipse")}isEclipseSessionFile(e){let t=X(e);return t.includes(og)&&t.endsWith(".json")}async getWorkspaceRoots(){let e=new Set;e.add(this.getDefaultWorkspaceRoot());for(let t of await this.readRecentWorkspaces())e.add(t);return[...e]}async readRecentWorkspaces(){let e=this.getEclipseInstallsRoot(),t;try{t=await As.promises.readdir(e)}catch{return[]}let s=[];for(let n of t){let i=it.join(e,n,"eclipse","configuration",".settings","org.eclipse.ui.ide.prefs");s.push(...await this.parseRecentWorkspacesFromPrefs(i))}return s}async parseRecentWorkspacesFromPrefs(e){let t;try{t=await As.promises.readFile(e,"utf8")}catch{return[]}let s=/^RECENT_WORKSPACES=(.*)$/m.exec(t);return s?s[1].split("\\n").map(n=>this.unescapeJavaPropertyValue(n)).filter(Boolean):[]}unescapeJavaPropertyValue(e){return e.replace(/\\:/g,":").replace(/\\=/g,"=").replace(/\\\\/g,"\\").trim()}async discoverEclipseSessions(){let e=[];for(let t of await this.getWorkspaceRoots()){let s=it.join(t,rc);e.push(...await this.discoverSessionsInDir(s))}return e}async discoverSessionsInDir(e){let t;try{t=await As.promises.readdir(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let n of t){if(!n.isDirectory())continue;let i=it.join(e,n.name),r;try{r=await As.promises.readdir(i)}catch{continue}for(let a of r)a.endsWith(".json")&&s.push(it.join(i,a))}return s}async getDiagnosticCandidatePaths(){return(await this.getWorkspaceRoots()).map(t=>it.join(t,rc))}async readSession(e){try{let t=await As.promises.readFile(e,"utf8");return JSON.parse(t)}catch{return null}}getEclipseSessionId(e){return it.basename(e,".json")}estimate(e){return e?Z(e):0}userText(e){let t=e?.message?.text;return typeof t=="string"?t:""}assistantText(e){let t=e?.reply?.editAgentRounds;return Array.isArray(t)?t.map(s=>typeof s?.reply=="string"?s.reply:"").filter(Boolean).join(`
|
|
38
38
|
`):""}thinkingText(e){let t=e?.reply?.editAgentRounds;return Array.isArray(t)?t.map(s=>typeof s?.thinkingBlock?.content=="string"?s.thinkingBlock.content:"").filter(Boolean).join(`
|
|
39
39
|
`):""}toolCallsFromTurn(e){let t=e?.reply?.editAgentRounds;if(!Array.isArray(t))return[];let s=[];for(let n of t)if(Array.isArray(n?.toolCalls))for(let i of n.toolCalls)s.push(this.normalizeToolCall(i));return s}normalizeToolCall(e){let t=e?.function??{};return{toolName:e?.name||e?.toolName||t.name||"unknown",arguments:this.stringifyArgs(e?.arguments??t.arguments)??this.strOrNull(e?.progressMessage)??void 0,result:this.resultToString(e?.result)}}stringifyArgs(e){if(typeof e=="string")return e;if(e)return JSON.stringify(e)}strOrNull(e){return typeof e=="string"?e:null}resultToString(e){if(typeof e=="string")return e||void 0;if(!Array.isArray(e)||e.length===0)return;let t=e.map(s=>typeof s=="string"?s:typeof s?.value=="string"?s.value:"").filter(Boolean);return t.length>0?t.join(`
|
|
40
|
-
`):void 0}async getTokensFromEclipseSession(e){let t=await this.readSession(e);if(!t||!Array.isArray(t.turns))return{tokens:0,thinkingTokens:0};let s=0,n=0;for(let i of t.turns)i?.role==="user"?s+=this.estimate(this.userText(i)):i?.role==="copilot"&&(s+=this.estimate(this.assistantText(i)),n+=this.estimate(this.thinkingText(i)));return{tokens:s+n,thinkingTokens:n}}async countEclipseInteractions(e){let t=await this.readSession(e);return!t||!Array.isArray(t.turns)?0:t.turns.filter(s=>s?.role==="user").length}async getEclipseModelUsage(e){let t=await this.readSession(e);if(!t||!Array.isArray(t.turns))return{};let s={},n=t.turns;for(let i=0;i<n.length;i++){let r=n[i];if(r?.role!=="user")continue;let a=this.findCopilotReply(n,i,r?.turnId),c=r?.model||a?.reply?.modelName||"unknown";s[c]||(s[c]={inputTokens:0,outputTokens:0}),s[c].inputTokens+=this.estimate(this.userText(r)),s[c].outputTokens+=this.estimate(this.assistantText(a))}return s}findCopilotReply(e,t,s){for(let n=t+1;n<e.length;n++){let i=e[n];if(i?.role==="user")break;if(i?.role==="copilot"&&(!s||i?.turnId===s||!i?.turnId))return i}return null}async getEclipseSessionMeta(e){let t=await this.readSession(e);if(!t)return null;let s=Array.isArray(t.turns)?t.turns.find(n=>n?.role==="user"):void 0;return{title:t.title,conversationId:t.conversationId,requester:t.requesterUsername,creationDate:t.creationDate,lastMessageDate:t.lastMessageDate,model:s?.model,mode:s?.chatMode}}async buildEclipseTurns(e){let t=await this.readSession(e);if(!t||!Array.isArray(t.turns))return[];let s=t.turns,n=[];for(let i=0;i<s.length;i++){if(s[i]?.role!=="user")continue;let r=this.findCopilotReply(s,i,s[i]?.turnId);n.push(this.buildTurn(s[i],r))}return n}buildTurn(e,t){let s=this.userText(e),n=this.assistantText(t),i=this.thinkingText(t);return{userText:s,assistantText:n,model:e?.model||t?.reply?.modelName||null,mode:this.strOrNull(e?.chatMode),reasoningEffort:this.strOrNull(t?.reply?.reasoningEffort),timestamp:this.strOrNull(e?.timestamp),currentDocumentUri:this.strOrNull(e?.currentDocument?.uri),toolCalls:this.toolCallsFromTurn(t),inputTokens:this.estimate(s),outputTokens:this.estimate(n),thinkingTokens:this.estimate(i)}}};var Ue=
|
|
41
|
-
`)){let r=t.exec(i);if(!r)continue;let a=r[1];if(!s.has(a)){s.add(a);try{await Ue.promises.access(a),n.push(a)}catch{}}}}async _discoverFromFilesystem(e,t){if(us.platform()!=="win32")return;let s=us.homedir(),n=["C","D"],i=[],r=["code","repos","src","projects","dev","workspace","work","source"];for(let a of r){let c=Le.join(s,a);try{await Ue.promises.access(c),i.push(c)}catch{}}for(let a of r){let c=Le.join(s,"Documents",a);try{await Ue.promises.access(c),i.push(c)}catch{}}for(let a of n)for(let c of r){let
|
|
42
|
-
`)}_decodeVcRaw(e,t){let s=Object.keys(e);if(s.length!==0)if(isNaN(Number(s[0])))e.Content&&typeof e.Content=="string"&&t.push(e.Content);else try{let n=s.map(Number).sort((c,
|
|
43
|
-
`)}getModelId(e,t){if(!e)return null;if(t)return e.Model?.ModelId||null;let s=e.Model;return Array.isArray(s)&&s.length>=2&&s[1]?.Id?s[1].Id:null}async getTokenEstimates(e,t){let s=await this.decodeSessionFile(e),n=0;for(let i=1;i<s.length;i++){let r=s[i]?.[1];if(!r?.Content)continue;let a=this.extractTextFromContent(r.Content),c=i%2===1,
|
|
44
|
-
`),n=[];for(let i of s)if(i.trim())try{n.push(JSON.parse(i))}catch{}return n},[],`claudecode readSessionEvents(${e})`)}deduplicateAssistantEvents(e){let t=new Map,s=[];for(let n of e){if(n.type!=="assistant"||!n.message?.usage)continue;let i=n.message?.id;i?t.set(i,n):s.push(n)}return[...t.values(),...s]}resolveSessionFamilyRoot(e){let t=e.split(Se.sep),s=t.lastIndexOf("subagents");return s>0?{sessionId:t[s-1],projectDir:t.slice(0,s-1).join(Se.sep)}:{sessionId:Se.basename(e,".jsonl"),projectDir:Se.dirname(e)}}async getSessionFamilyFiles(e){let{projectDir:t,sessionId:s}=this.resolveSessionFamilyRoot(e),n=Se.join(t,`${s}.jsonl`),i=Se.join(t,s,"subagents"),r=[];try{await ds.promises.access(i),r=(await this.collectJsonlFilesFromProject(i)).sort()}catch{}return[n,...r]}async getPriorFamilyMessageIds(e){if(e.split(Se.sep).lastIndexOf("subagents")<=0)return new Set;let s=await this.getSessionFamilyFiles(e),n=Se.normalize(e),i=new Set;for(let r of s){if(Se.normalize(r)===n)break;let a=await this.readSessionEvents(r);for(let c of this.deduplicateAssistantEvents(a)){let
|
|
45
|
-
`),n=[];for(let i of s)if(i.trim())try{n.push(JSON.parse(i))}catch{}return n}catch{return[]}}async getTokensFromCoworkSession(e){let t=await this.readCoworkEvents(e),s=0,n=0,i=new Set;for(let r of t){let a=this.extractCoworkEventTokens(r,i);a&&(s+=a.inputTokens,n+=a.outputTokens)}return{tokens:s+n,thinkingTokens:0}}computeCoworkTokenCounts(e){let t=typeof e.cache_creation_input_tokens=="number"?e.cache_creation_input_tokens:0,s=typeof e.cache_creation?.ephemeral_1h_input_tokens=="number"?e.cache_creation.ephemeral_1h_input_tokens:0,n=typeof e.cache_read_input_tokens=="number"?e.cache_read_input_tokens:0,i=(typeof e.input_tokens=="number"?e.input_tokens:0)+t+n,r=typeof e.output_tokens=="number"?e.output_tokens:0;return{inputTokens:i,outputTokens:r,cacheCreation:t,cachedRead:n,cacheCreation1h:s}}extractCoworkEventTokens(e,t){if(e.type!=="assistant")return null;let s=e.message?.usage;if(!s)return null;let n=e.requestId;if(n){if(!e.message?.stop_reason||t.has(n))return null;t.add(n)}let{inputTokens:i,outputTokens:r}=this.computeCoworkTokenCounts(s);return{inputTokens:i,outputTokens:r}}async countCoworkInteractions(e){let t=await this.readCoworkEvents(e),s=0;for(let n of t)if(n.type==="user"&&!n.isSidechain&&n.message?.role==="user"){let i=n.message?.content;(typeof i=="string"||Array.isArray(i)&&i.some(a=>a.type==="text")&&!i.some(a=>a.type==="tool_result"))&&s++}return s}async getCoworkModelUsage(e){let t=await this.readCoworkEvents(e),s={},n=new Set;for(let i of t)this.processCoworkEventModelUsage(i,n,s);return s}processCoworkEventModelUsage(e,t,s){if(e.type!=="assistant")return;let n=e.message?.usage;if(!n||!this.shouldCountCoworkRequest(e,t))return;let i=
|
|
46
|
-
`),i=[];for(let r of n)if(r.trim())try{i.push(JSON.parse(r))}catch{}return i}catch{return[]}}async getTokensFromSession(e){let t=await this.readSessionMeta(e);if(!t?.stats)return{tokens:0,thinkingTokens:0};let s=typeof t.stats.session_prompt_tokens=="number"?t.stats.session_prompt_tokens:0,n=typeof t.stats.session_completion_tokens=="number"?t.stats.session_completion_tokens:0;return{tokens:s+n,thinkingTokens:0}}async countInteractions(e){return(await this.readSessionMessages(e)).filter(s=>s.role==="user"&&s.injected!==!0).length}async getModelUsage(e){let t=await this.readSessionMeta(e);if(!t)return{};let s=typeof t.stats?.session_prompt_tokens=="number"?t.stats.session_prompt_tokens:0,n=typeof t.stats?.session_completion_tokens=="number"?t.stats.session_completion_tokens:0;return s+n===0?{}:{[t.config?.active_model||"devstral"]:{inputTokens:s,outputTokens:n}}}async getSessionMeta(e){let t=await this.readSessionMeta(e);return t?{title:t.title||void 0,firstInteraction:t.start_time||null,lastInteraction:t.end_time||null,model:t.config?.active_model||void 0}:{title:void 0,firstInteraction:null,lastInteraction:null,model:void 0}}async getSessionData(e){let t=await this.readSessionMeta(e);if(!t)return{tokens:0,interactions:0,modelUsage:{},timestamp:0};let{tokens:s}=await this.getTokensFromSession(e),n=await this.countInteractions(e),i=await this.getModelUsage(e),r={};for(let[c,
|
|
40
|
+
`):void 0}async getTokensFromEclipseSession(e){let t=await this.readSession(e);if(!t||!Array.isArray(t.turns))return{tokens:0,thinkingTokens:0};let s=0,n=0;for(let i of t.turns)i?.role==="user"?s+=this.estimate(this.userText(i)):i?.role==="copilot"&&(s+=this.estimate(this.assistantText(i)),n+=this.estimate(this.thinkingText(i)));return{tokens:s+n,thinkingTokens:n}}async countEclipseInteractions(e){let t=await this.readSession(e);return!t||!Array.isArray(t.turns)?0:t.turns.filter(s=>s?.role==="user").length}async getEclipseModelUsage(e){let t=await this.readSession(e);if(!t||!Array.isArray(t.turns))return{};let s={},n=t.turns;for(let i=0;i<n.length;i++){let r=n[i];if(r?.role!=="user")continue;let a=this.findCopilotReply(n,i,r?.turnId),c=r?.model||a?.reply?.modelName||"unknown";s[c]||(s[c]={inputTokens:0,outputTokens:0,sessions:0}),s[c].inputTokens+=this.estimate(this.userText(r)),s[c].outputTokens+=this.estimate(this.assistantText(a))}return s}findCopilotReply(e,t,s){for(let n=t+1;n<e.length;n++){let i=e[n];if(i?.role==="user")break;if(i?.role==="copilot"&&(!s||i?.turnId===s||!i?.turnId))return i}return null}async getEclipseSessionMeta(e){let t=await this.readSession(e);if(!t)return null;let s=Array.isArray(t.turns)?t.turns.find(n=>n?.role==="user"):void 0;return{title:t.title,conversationId:t.conversationId,requester:t.requesterUsername,creationDate:t.creationDate,lastMessageDate:t.lastMessageDate,model:s?.model,mode:s?.chatMode}}async buildEclipseTurns(e){let t=await this.readSession(e);if(!t||!Array.isArray(t.turns))return[];let s=t.turns,n=[];for(let i=0;i<s.length;i++){if(s[i]?.role!=="user")continue;let r=this.findCopilotReply(s,i,s[i]?.turnId);n.push(this.buildTurn(s[i],r))}return n}buildTurn(e,t){let s=this.userText(e),n=this.assistantText(t),i=this.thinkingText(t);return{userText:s,assistantText:n,model:e?.model||t?.reply?.modelName||null,mode:this.strOrNull(e?.chatMode),reasoningEffort:this.strOrNull(t?.reply?.reasoningEffort),timestamp:this.strOrNull(e?.timestamp),currentDocumentUri:this.strOrNull(e?.currentDocument?.uri),toolCalls:this.toolCallsFromTurn(t),inputTokens:this.estimate(s),outputTokens:this.estimate(n),thinkingTokens:this.estimate(i)}}};var Ue=S(require("fs")),Le=S(require("path")),us=S(require("os")),ni=S(ea());var Kg=new Set(["node_modules",".git",".github","bin","obj","out","dist","build","target","packages","vendor","__pycache__",".tox",".venv","venv","env","Windows","Program Files","Program Files (x86)","ProgramData","$Recycle.Bin","System Volume Information","Recovery"]),si=class{isVSSessionFile(e){let t=X(e),s=t.includes("/.vs/")&&t.includes("/copilot-chat/")&&t.includes("/sessions/"),n=t.includes("/ssmsgithubcopilot/")&&t.includes("/copilot-chat/")&&t.includes("/sessions/");return s||n}async statSessionFile(e){return Ue.promises.stat(e)}getLogDir(){let e=process.env.LOCALAPPDATA||Le.join(us.homedir(),"AppData","Local");return Le.join(e,"Temp","VSGitHubCopilotLogs")}getSsmsSessionsDir(){let e=process.env.LOCALAPPDATA||Le.join(us.homedir(),"AppData","Local");return Le.join(e,"Microsoft","SSMS")}async discoverSessions(){let e=new Set,t=[];return await this._discoverFromLogs(e,t),await this._discoverFromFilesystem(e,t),await this._discoverFromSsmsAppData(e,t),t}async _discoverFromLogs(e,t){let s=this.getLogDir(),n;try{n=(await Ue.promises.readdir(s)).filter(a=>a.endsWith(".chat.log")).map(a=>Le.join(s,a))}catch{return}let i=/Updating session file '([^']+)'/;for(let r of n)try{let a=await Ue.promises.readFile(r,"utf8");await this._processLogFileLines(a,i,e,t)}catch{}}async _processLogFileLines(e,t,s,n){for(let i of e.split(`
|
|
41
|
+
`)){let r=t.exec(i);if(!r)continue;let a=r[1];if(!s.has(a)){s.add(a);try{await Ue.promises.access(a),n.push(a)}catch{}}}}async _discoverFromFilesystem(e,t){if(us.platform()!=="win32")return;let s=us.homedir(),n=["C","D"],i=[],r=["code","repos","src","projects","dev","workspace","work","source"];for(let a of r){let c=Le.join(s,a);try{await Ue.promises.access(c),i.push(c)}catch{}}for(let a of r){let c=Le.join(s,"Documents",a);try{await Ue.promises.access(c),i.push(c)}catch{}}for(let a of n)for(let c of r){let d=a+":\\"+c;try{await Ue.promises.access(d),i.push(d)}catch{}}for(let a of i)await this._scanForVsDirs(a,0,5,e,t)}async _scanForVsDirs(e,t,s,n,i){if(t>s)return;let r;try{r=await Ue.promises.readdir(e,{withFileTypes:!0})}catch{return}let a=r.filter(d=>{if(!d.isDirectory())return!1;let p=d.name;return!(Kg.has(p)||p.startsWith(".")&&p!==".vs")}),c=8;for(let d=0;d<a.length;d+=c)await Promise.all(a.slice(d,d+c).map(async p=>{let f=Le.join(e,p.name);p.name===".vs"?await this._findSessionsInVsDir(f,n,i):await this._scanForVsDirs(f,t+1,s,n,i)}))}async _collectFromSessionsDir(e,t,s){let n;try{n=await Ue.promises.readdir(e,{withFileTypes:!0})}catch{return}for(let i of n){if(!i.isFile())continue;let r=Le.join(e,i.name);t.has(r)||(t.add(r),s.push(r))}}async _collectFromHashDirs(e,t,s){let n;try{n=await Ue.promises.readdir(e,{withFileTypes:!0})}catch{return}for(let i of n)i.isDirectory()&&await this._collectFromSessionsDir(Le.join(e,i.name,"sessions"),t,s)}async _findSessionsInVsDir(e,t,s){let n;try{n=await Ue.promises.readdir(e,{withFileTypes:!0})}catch{return}for(let i of n)i.isDirectory()&&await this._collectFromHashDirs(Le.join(e,i.name,"copilot-chat"),t,s)}async _discoverFromSsmsAppData(e,t){if(us.platform()!=="win32")return;let s=this.getSsmsSessionsDir(),n;try{n=await Ue.promises.readdir(s,{withFileTypes:!0})}catch{return}for(let i of n)i.isDirectory()&&await this._collectFromHashDirs(Le.join(s,i.name,"SSMSGitHubCopilot","copilot-chat"),e,t)}async decodeSessionFile(e){try{let t=await Ue.promises.readFile(e);return t.length<2?[]:Array.from((0,ni.decodeMulti)(t.slice(1)))}catch{return[]}}getSessionTitle(e){let s=e.find((i,r)=>r>0&&r%2===1)?.[1];if(!s?.Content)return;let n=this.extractTextFromContent(s.Content).trim();if(n)return n.length>80?n.substring(0,80)+"\u2026":n}getSessionTimestamps(e){let t=e[0];return t?{timeCreated:t.TimeCreated?new Date(t.TimeCreated).toISOString():null,timeUpdated:t.TimeUpdated?new Date(t.TimeUpdated).toISOString():null}:{timeCreated:null,timeUpdated:null}}countInteractions(e){return e.filter((t,s)=>s>0&&s%2===1).length}extractTextFromContent(e){if(!Array.isArray(e))return"";let t=[];for(let s of e){let n=s?.[1];n&&typeof n.Content=="string"&&n.Content&&t.push(n.Content)}return t.join(`
|
|
42
|
+
`)}_decodeVcRaw(e,t){let s=Object.keys(e);if(s.length!==0)if(isNaN(Number(s[0])))e.Content&&typeof e.Content=="string"&&t.push(e.Content);else try{let n=s.map(Number).sort((c,d)=>c-d),i=Buffer.from(n.map(c=>e[c])),r=(0,ni.decode)(i),a=Array.isArray(r)?r[1]:r;a?.Content&&typeof a.Content=="string"&&t.push(a.Content)}catch{}}extractContextText(e){if(!Array.isArray(e))return"";let t=[];for(let s of e){let n=s?.ValueContainer;if(!Array.isArray(n)||n.length<2)continue;let i=n[1];!i||typeof i!="object"||this._decodeVcRaw(i,t)}return t.join(`
|
|
43
|
+
`)}getModelId(e,t){if(!e)return null;if(t)return e.Model?.ModelId||null;let s=e.Model;return Array.isArray(s)&&s.length>=2&&s[1]?.Id?s[1].Id:null}async getTokenEstimates(e,t){let s=await this.decodeSessionFile(e),n=0;for(let i=1;i<s.length;i++){let r=s[i]?.[1];if(!r?.Content)continue;let a=this.extractTextFromContent(r.Content),c=i%2===1,d=c?this.extractContextText(r.Context):"";if(!a&&!d)continue;let p=this.getModelId(r,c)||void 0;n+=t(a+d,p)}return{tokens:n,thinkingTokens:0}}async getModelUsage(e,t){let s={},n=await this.decodeSessionFile(e),i={};for(let r=1;r<n.length;r++){let a=n[r]?.[1];if(!a?.Content)continue;let c=this.extractTextFromContent(a.Content),d=r%2===1,p=d?this.extractContextText(a.Context):"";if(!c&&!p)continue;let f=this.getModelId(a,d)||"unknown";i[f]||(i[f]={input:"",output:""}),d?i[f].input+=c+p:i[f].output+=c}for(let[r,a]of Object.entries(i))s[r]={inputTokens:t(a.input,r),outputTokens:t(a.output,r),sessions:0};return s}};var ds=S(require("fs")),Se=S(require("path")),ii=S(require("os"));function Gt(o){if(!o||/claude-.+-\d+\.\d+/.test(o))return o;let e=o.match(/^(claude-.+)-(\d)-(\d)(-\d{8})?$/);return e?`${e[1]}-${e[2]}.${e[3]}`:o}var oi=class{getClaudeCodeDataDir(){return Se.join(ii.homedir(),".claude")}getClaudeCodeProjectsDir(){return Se.join(this.getClaudeCodeDataDir(),"projects")}isClaudeCodeSessionFile(e){let t=X(e),s=X(this.getClaudeCodeProjectsDir());return t.startsWith(s)&&t.endsWith(".jsonl")}async getClaudeCodeSessionFiles(){let e=this.getClaudeCodeProjectsDir();try{await ds.promises.access(e)}catch{return[]}try{let t=await ds.promises.readdir(e,{withFileTypes:!0});return(await Promise.all(t.filter(n=>n.isDirectory()).map(n=>this.collectJsonlFilesFromProject(Se.join(e,n.name))))).flat()}catch(t){return console.error("[claudecode] Failed to read projects dir:",t),[]}}async collectJsonlFilesFromProject(e,t=0,s=6){if(t>s)return[];try{let n=await ds.promises.readdir(e,{withFileTypes:!0});return(await Promise.all(n.map(async r=>{let a=Se.join(e,r.name);if(r.isDirectory())return this.collectJsonlFilesFromProject(a,t+1,s);if(!r.name.endsWith(".jsonl"))return[];try{return(await ds.promises.stat(a)).size>0?[a]:[]}catch(c){return console.error(`[claudecode] Failed to stat ${a}:`,c),[]}}))).flat()}catch(n){return console.error(`[claudecode] Failed to read project dir ${e}:`,n),[]}}async readSessionEvents(e){return os(async()=>{let s=(await ds.promises.readFile(e,"utf8")).trim().split(`
|
|
44
|
+
`),n=[];for(let i of s)if(i.trim())try{n.push(JSON.parse(i))}catch{}return n},[],`claudecode readSessionEvents(${e})`)}deduplicateAssistantEvents(e){let t=new Map,s=[];for(let n of e){if(n.type!=="assistant"||!n.message?.usage)continue;let i=n.message?.id;i?t.set(i,n):s.push(n)}return[...t.values(),...s]}resolveSessionFamilyRoot(e){let t=e.split(Se.sep),s=t.lastIndexOf("subagents");return s>0?{sessionId:t[s-1],projectDir:t.slice(0,s-1).join(Se.sep)}:{sessionId:Se.basename(e,".jsonl"),projectDir:Se.dirname(e)}}async getSessionFamilyFiles(e){let{projectDir:t,sessionId:s}=this.resolveSessionFamilyRoot(e),n=Se.join(t,`${s}.jsonl`),i=Se.join(t,s,"subagents"),r=[];try{await ds.promises.access(i),r=(await this.collectJsonlFilesFromProject(i)).sort()}catch{}return[n,...r]}async getPriorFamilyMessageIds(e){if(e.split(Se.sep).lastIndexOf("subagents")<=0)return new Set;let s=await this.getSessionFamilyFiles(e),n=Se.normalize(e),i=new Set;for(let r of s){if(Se.normalize(r)===n)break;let a=await this.readSessionEvents(r);for(let c of this.deduplicateAssistantEvents(a)){let d=c.message?.id;d&&i.add(d)}}return i}getEventTotalTokens(e){let t=(typeof e.input_tokens=="number"?e.input_tokens:0)+(typeof e.cache_creation_input_tokens=="number"?e.cache_creation_input_tokens:0)+(typeof e.cache_read_input_tokens=="number"?e.cache_read_input_tokens:0),s=typeof e.output_tokens=="number"?e.output_tokens:0;return t+s}async getTokensFromClaudeCodeSession(e){let t=await this.readSessionEvents(e),s=await this.getPriorFamilyMessageIds(e),n=0;for(let i of this.deduplicateAssistantEvents(t)){let r=i.message?.id;r&&s.has(r)||(n+=this.getEventTotalTokens(i.message.usage))}return{tokens:n,thinkingTokens:0}}bucketEventIntoDay(e,t,s){let n=e.message?.id;if(n&&t.has(n))return 0;let i=this.getEventTotalTokens(e.message.usage);if(i<=0)return 0;let r=e.timestamp?new Date(e.timestamp).getTime():NaN;if(isNaN(r))return 0;let a=L(new Date(r));return s.set(a,(s.get(a)??0)+i),i}async getClaudeCodeDailyFractions(e){let t=await this.readSessionEvents(e),s=await this.getPriorFamilyMessageIds(e),n=new Map,i=0;for(let a of this.deduplicateAssistantEvents(t))i+=this.bucketEventIntoDay(a,s,n);if(i===0){let a=await this.getClaudeCodeSessionMeta(e),c=a?.firstInteraction?Date.parse(a.firstInteraction):NaN;return{[isNaN(c)?L(new Date):L(new Date(c))]:1}}let r={};for(let[a,c]of n.entries())r[a]=c/i;return r}async countClaudeCodeInteractions(e){let t=await this.readSessionEvents(e),s=0;for(let n of t)if(n.type==="user"&&!n.isSidechain&&n.message?.role==="user"){let i=n.message?.content;(typeof i=="string"||Array.isArray(i)&&i.some(a=>a.type==="text")&&!i.some(a=>a.type==="tool_result"))&&s++}return s}extractCacheTokenBreakdown(e){let t=typeof e.cache_creation_input_tokens=="number"?e.cache_creation_input_tokens:0,s=typeof e.cache_creation?.ephemeral_1h_input_tokens=="number"?e.cache_creation.ephemeral_1h_input_tokens:0,n=typeof e.cache_read_input_tokens=="number"?e.cache_read_input_tokens:0;return{cacheCreation:t,cacheCreation1h:s,cachedRead:n}}addModelUsageEntry(e,t,s){e[t]||(e[t]={inputTokens:0,outputTokens:0,sessions:0});let{cacheCreation:n,cacheCreation1h:i,cachedRead:r}=this.extractCacheTokenBreakdown(s),a=(typeof s.input_tokens=="number"?s.input_tokens:0)+n+r,c=typeof s.output_tokens=="number"?s.output_tokens:0;e[t].inputTokens+=a,e[t].outputTokens+=c,n>0&&(e[t].cacheCreationTokens=(e[t].cacheCreationTokens??0)+n),i>0&&(e[t].cacheCreation1hTokens=(e[t].cacheCreation1hTokens??0)+i),r>0&&(e[t].cachedReadTokens=(e[t].cachedReadTokens??0)+r)}async getClaudeCodeModelUsage(e){let t=await this.readSessionEvents(e),s=await this.getPriorFamilyMessageIds(e),n={};for(let i of this.deduplicateAssistantEvents(t)){let r=i.message?.id;if(r&&s.has(r))continue;let a=i.message.usage,c=Gt(i.message?.model||"unknown");this.addModelUsageEntry(n,c,a)}return n}async getClaudeCodeSessionMeta(e){let t=await this.readSessionEvents(e);if(t.length===0)return null;let{title:s,entrypoint:n,cwd:i,timestamps:r}=this.extractMetaFieldsFromEvents(t),a,c;return r.length>0&&(r.sort((d,p)=>d-p),a=new Date(r[0]).toISOString(),c=new Date(r[r.length-1]).toISOString()),{title:s,entrypoint:n,firstInteraction:a,lastInteraction:c,cwd:i}}extractMetaFieldsFromEvents(e){let t,s,n,i=[];for(let r of e)if(r.type==="ai-title"&&r.aiTitle&&(t=r.aiTitle),!s&&r.entrypoint&&(s=r.entrypoint),!n&&r.cwd&&(n=r.cwd),r.timestamp){let a=new Date(r.timestamp).getTime();isNaN(a)||i.push(a)}return{title:t,entrypoint:s,cwd:n,timestamps:i}}getClaudeCodeSessionId(e){return Se.basename(e,".jsonl")}getProjectPathFromHash(e){if(ii.platform()==="win32"){let s=e.split("-");if(s.length>=2&&s[0].length===1&&s[1]===""){let n=s[0].toUpperCase(),i=s.slice(2).join("\\");return`${n}:\\${i}`}}return"/"+e.replace(/-/g,"/")}};var Ds=S(require("fs")),hn=S(require("path")),yn=S(require("os"));var Qg="Claude_pzs8sxrjxfjjc",ri=class{getCoworkBaseDir(){let e=yn.platform();if(e==="win32"){let t=process.env.LOCALAPPDATA||hn.join(yn.homedir(),"AppData","Local");return hn.join(t,"Packages",Qg,"LocalCache","Roaming","Claude","local-agent-mode-sessions")}return e==="darwin"?hn.join(yn.homedir(),"Library","Application Support","Claude","local-agent-mode-sessions"):""}isCoworkSessionFile(e){let t=X(e);return t.includes("/local-agent-mode-sessions/")&&t.endsWith(".jsonl")}async getCoworkSessionFiles(){let e=this.getCoworkBaseDir();if(!e)return[];try{await Ds.promises.access(e)}catch{return[]}let t=[];try{await this.walkForJsonlFiles(e,t,0,8)}catch{}return t}async walkForJsonlFiles(e,t,s,n){if(s>n)return;let i;try{i=await Ds.promises.readdir(e,{withFileTypes:!0})}catch{return}for(let r of i)await this.processWalkEntry(r,e,t,s,n)}async processWalkEntry(e,t,s,n,i){let r=hn.join(t,e.name);if(e.isDirectory()){if(e.name==="agent")return;await this.walkForJsonlFiles(r,s,n+1,i)}else if(e.name.endsWith(".jsonl")&&e.name!=="audit.jsonl")try{(await Ds.promises.stat(r)).size>0&&s.push(r)}catch{}}async readCoworkEvents(e){try{let s=(await Ds.promises.readFile(e,"utf8")).trim().split(`
|
|
45
|
+
`),n=[];for(let i of s)if(i.trim())try{n.push(JSON.parse(i))}catch{}return n}catch{return[]}}async getTokensFromCoworkSession(e){let t=await this.readCoworkEvents(e),s=0,n=0,i=new Set;for(let r of t){let a=this.extractCoworkEventTokens(r,i);a&&(s+=a.inputTokens,n+=a.outputTokens)}return{tokens:s+n,thinkingTokens:0}}computeCoworkTokenCounts(e){let t=typeof e.cache_creation_input_tokens=="number"?e.cache_creation_input_tokens:0,s=typeof e.cache_creation?.ephemeral_1h_input_tokens=="number"?e.cache_creation.ephemeral_1h_input_tokens:0,n=typeof e.cache_read_input_tokens=="number"?e.cache_read_input_tokens:0,i=(typeof e.input_tokens=="number"?e.input_tokens:0)+t+n,r=typeof e.output_tokens=="number"?e.output_tokens:0;return{inputTokens:i,outputTokens:r,cacheCreation:t,cachedRead:n,cacheCreation1h:s}}extractCoworkEventTokens(e,t){if(e.type!=="assistant")return null;let s=e.message?.usage;if(!s)return null;let n=e.requestId;if(n){if(!e.message?.stop_reason||t.has(n))return null;t.add(n)}let{inputTokens:i,outputTokens:r}=this.computeCoworkTokenCounts(s);return{inputTokens:i,outputTokens:r}}async countCoworkInteractions(e){let t=await this.readCoworkEvents(e),s=0;for(let n of t)if(n.type==="user"&&!n.isSidechain&&n.message?.role==="user"){let i=n.message?.content;(typeof i=="string"||Array.isArray(i)&&i.some(a=>a.type==="text")&&!i.some(a=>a.type==="tool_result"))&&s++}return s}async getCoworkModelUsage(e){let t=await this.readCoworkEvents(e),s={},n=new Set;for(let i of t)this.processCoworkEventModelUsage(i,n,s);return s}processCoworkEventModelUsage(e,t,s){if(e.type!=="assistant")return;let n=e.message?.usage;if(!n||!this.shouldCountCoworkRequest(e,t))return;let i=Gt(e.message?.model||"unknown");s[i]||(s[i]={inputTokens:0,outputTokens:0,sessions:0}),this.applyCoworkTokenCounts(s[i],n)}shouldCountCoworkRequest(e,t){let s=e.requestId;return s?!e.message?.stop_reason||t.has(s)?!1:(t.add(s),!0):!0}applyCoworkTokenCounts(e,t){let{inputTokens:s,outputTokens:n,cacheCreation:i,cachedRead:r,cacheCreation1h:a}=this.computeCoworkTokenCounts(t);e.inputTokens+=s,e.outputTokens+=n,i>0&&(e.cacheCreationTokens=(e.cacheCreationTokens??0)+i),a>0&&(e.cacheCreation1hTokens=(e.cacheCreation1hTokens??0)+a),r>0&&(e.cachedReadTokens=(e.cachedReadTokens??0)+r)}getMetadataPathFromJsonl(e){let s=me(e).split("/"),n=s.lastIndexOf(".claude");if(n<1)return null;let i=s[n-1];return i.startsWith("local_")?`${s.slice(0,n-1).join("/")}/${i}.json`:null}async getCoworkSessionMeta(e){let t=this.getMetadataPathFromJsonl(e);if(!t)return null;try{let s=await Ds.promises.readFile(t,"utf8"),n=JSON.parse(s),i=n.createdAt?new Date(n.createdAt).toISOString():void 0,r=n.lastActivityAt?new Date(n.lastActivityAt).toISOString():void 0,a=Array.isArray(n.userSelectedFolders)&&n.userSelectedFolders.length>0?n.userSelectedFolders[0]:n.cwd;return{title:n.title||void 0,firstInteraction:i,lastInteraction:r,cwd:typeof a=="string"?a:void 0}}catch{return null}}};var _n=S(require("fs")),Tt=S(require("path")),ta=S(require("os"));var ai=class{getVibeHomeDir(){let e=process.env.VIBE_HOME;return e?Tt.resolve(e.replace(/^~/,ta.homedir())):Tt.join(ta.homedir(),".vibe")}getSessionLogDir(){return Tt.join(this.getVibeHomeDir(),"logs","session")}isVibeSessionFile(e){let t=me(e);return t.includes("/.vibe/logs/session/")&&t.endsWith("/meta.json")}getSessionDir(e){return Tt.dirname(e)}async discoverSessions(){let e=this.getSessionLogDir();try{let t=await _n.promises.readdir(e,{withFileTypes:!0}),s=[];for(let n of t){if(!n.isDirectory())continue;let i=Tt.join(e,n.name,"meta.json");try{await _n.promises.access(i),s.push(i)}catch{}}return s}catch{return[]}}async readSessionMeta(e){try{let t=await _n.promises.readFile(e,"utf8");return JSON.parse(t)}catch{return null}}async readSessionMessages(e){let t=Tt.join(this.getSessionDir(e),"messages.jsonl");try{let n=(await _n.promises.readFile(t,"utf8")).trim().split(`
|
|
46
|
+
`),i=[];for(let r of n)if(r.trim())try{i.push(JSON.parse(r))}catch{}return i}catch{return[]}}async getTokensFromSession(e){let t=await this.readSessionMeta(e);if(!t?.stats)return{tokens:0,thinkingTokens:0};let s=typeof t.stats.session_prompt_tokens=="number"?t.stats.session_prompt_tokens:0,n=typeof t.stats.session_completion_tokens=="number"?t.stats.session_completion_tokens:0;return{tokens:s+n,thinkingTokens:0}}async countInteractions(e){return(await this.readSessionMessages(e)).filter(s=>s.role==="user"&&s.injected!==!0).length}async getModelUsage(e){let t=await this.readSessionMeta(e);if(!t)return{};let s=typeof t.stats?.session_prompt_tokens=="number"?t.stats.session_prompt_tokens:0,n=typeof t.stats?.session_completion_tokens=="number"?t.stats.session_completion_tokens:0;return s+n===0?{}:{[t.config?.active_model||"devstral"]:{inputTokens:s,outputTokens:n,sessions:0}}}async getSessionMeta(e){let t=await this.readSessionMeta(e);return t?{title:t.title||void 0,firstInteraction:t.start_time||null,lastInteraction:t.end_time||null,model:t.config?.active_model||void 0}:{title:void 0,firstInteraction:null,lastInteraction:null,model:void 0}}async getSessionData(e){let t=await this.readSessionMeta(e);if(!t)return{tokens:0,interactions:0,modelUsage:{},timestamp:0};let{tokens:s}=await this.getTokensFromSession(e),n=await this.countInteractions(e),i=await this.getModelUsage(e),r={};for(let[c,d]of Object.entries(i))r[c]={...d,interactions:n};let a=t.start_time?new Date(t.start_time).getTime():0;return{tokens:s,interactions:n,modelUsage:r,timestamp:a}}};var Ve=S(require("fs")),na=S(require("os")),yt=S(require("path"));function W(o){return typeof o=="string"&&o.trim().length>0}function Es(o){return typeof o=="number"&&Number.isFinite(o)?o:0}function Rs(o){if(!W(o))return null;let e=Date.parse(o);return Number.isFinite(e)?e:null}function sa(o,e){let t=Rs(o.timestamp),s=Rs(e.timestamp);return t!==null&&s!==null&&t!==s?t-s:t!==null&&s===null?-1:t===null&&s!==null?1:o.lineNumber-e.lineNumber}function Cn(o){if(!o)return o;let e=o.trim();return e==="gemini-3-flash-preview"?"gemini-3-flash":e}async function Yg(o){let e=[];try{let t=await Ve.promises.readdir(o,{withFileTypes:!0});for(let s of t){if(s.isDirectory()||!s.name.startsWith("session-")||!s.name.endsWith(".jsonl"))continue;let n=yt.join(o,s.name);try{(await Ve.promises.stat(n)).size>0&&e.push(n)}catch{}}}catch{}return e}async function Xg(o,e){if(!e.isDirectory())return[];let t=yt.join(o,e.name,"chats");try{await Ve.promises.access(t)}catch{return[]}return Yg(t)}function Zg(o){return{sessionId:o.sessionId,projectHash:W(o.projectHash)?o.projectHash:void 0,startTime:W(o.startTime)?o.startTime:void 0,lastUpdated:W(o.lastUpdated)?o.lastUpdated:void 0,kind:W(o.kind)?o.kind:void 0}}var li=class{_projectsIndexCache=null;_projectsIndexInflight=new Map;getGeminiDataDir(){return yt.join(na.homedir(),".gemini")}getGeminiTmpDir(){return yt.join(this.getGeminiDataDir(),"tmp")}getGeminiProjectsPath(){return yt.join(this.getGeminiDataDir(),"projects.json")}getGeminiLogsPath(){return yt.join(this.getGeminiDataDir(),"logs.json")}isGeminiCliSessionFile(e){let t=X(e),s=X(this.getGeminiTmpDir());return t.startsWith(s)&&t.includes("/chats/session-")&&t.endsWith(".jsonl")}async collectSessionFilesFromChatDir(e){let t=[];try{let s=await Ve.promises.readdir(e,{withFileTypes:!0});for(let n of s){if(n.isDirectory()||!n.name.startsWith("session-")||!n.name.endsWith(".jsonl"))continue;let i=yt.join(e,n.name);try{(await Ve.promises.stat(i)).size>0&&t.push(i)}catch{}}}catch{}return t}async getGeminiCliSessionFiles(){let e=this.getGeminiTmpDir();try{await Ve.promises.access(e)}catch{return[]}try{let t=await Ve.promises.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(n=>Xg(e,n)))).flat()}catch{return[]}}parseGeminiSessionHeader(e){return{sessionId:e.sessionId,projectHash:W(e.projectHash)?e.projectHash:void 0,startTime:W(e.startTime)?e.startTime:void 0,lastUpdated:W(e.lastUpdated)?e.lastUpdated:void 0,kind:W(e.kind)?e.kind:void 0}}parseGeminiUserRecord(e,t,s){let n=W(e.id)?e.id:`__user_${t}`;return s.has(n)?null:(s.add(n),{id:W(e.id)?e.id:void 0,timestamp:W(e.timestamp)?e.timestamp:void 0,type:"user",content:e.content,lineNumber:t})}parseGeminiAssistantRecord(e,t,s){return{id:W(e.id)?e.id:`__assistant_${s.value++}_${t}`,record:{id:W(e.id)?e.id:void 0,timestamp:W(e.timestamp)?e.timestamp:void 0,type:"gemini",content:e.content,thoughts:Array.isArray(e.thoughts)?e.thoughts:[],tokens:e.tokens,model:W(e.model)?e.model:void 0,toolCalls:Array.isArray(e.toolCalls)?e.toolCalls:[],lineNumber:t}}}processOneParsedLine(e,t,s){let n;try{n=JSON.parse(e)}catch{return}if(!s.header&&W(n?.sessionId)){s.header=this.parseGeminiSessionHeader(n);return}if(W(n?.$set?.lastUpdated)){s.latestHeaderUpdate=n.$set.lastUpdated;return}if(n?.type==="user"){let i=this.parseGeminiUserRecord(n,t,s.seenUserIds);i&&s.userRecords.push(i);return}if(n?.type==="gemini"){let{id:i,record:r}=this.parseGeminiAssistantRecord(n,t,s.counter);s.assistantRecords.set(i,r)}}async readGeminiCliSession(e){let t={header:null,latestHeaderUpdate:void 0,anonymousAssistantCounter:0,seenUserIds:new Set,userRecords:[],assistantRecords:new Map};for(let[r,a]of(await this.readJsonlLines(e)).entries()){let c;try{c=JSON.parse(a)}catch{continue}this._rgsDispatchLine(c,r,t)}t.header&&t.latestHeaderUpdate&&(t.header.lastUpdated=t.latestHeaderUpdate),t.userRecords.sort(sa);let s=Array.from(t.assistantRecords.values()).sort(sa),n=this.getProjectBucketFromPath(e)||t.header?.projectHash,i=await this.resolveWorkspacePath(n,t.header?.projectHash);return{header:t.header,projectBucket:n,workspacePath:i??n,userRecords:t.userRecords,assistantRecords:s}}_rgsDispatchLine(e,t,s){if(!s.header&&W(e?.sessionId)){s.header=Zg(e);return}if(W(e?.$set?.lastUpdated)){s.latestHeaderUpdate=e.$set.lastUpdated;return}if(e?.type==="user"){this._rgsHandleUserRecord(e,t,s.seenUserIds,s.userRecords);return}e?.type==="gemini"&&(s.anonymousAssistantCounter=this._rgsHandleGeminiRecord(e,t,s.anonymousAssistantCounter,s.assistantRecords))}_rgsHandleUserRecord(e,t,s,n){let i=W(e.id)?e.id:`__user_${t}`;s.has(i)||(s.add(i),n.push({id:W(e.id)?e.id:void 0,timestamp:W(e.timestamp)?e.timestamp:void 0,type:"user",content:e.content,lineNumber:t}))}_rgsHandleGeminiRecord(e,t,s,n){let i=W(e.id)?e.id:`__assistant_${s}_${t}`;return n.set(i,{id:W(e.id)?e.id:void 0,timestamp:W(e.timestamp)?e.timestamp:void 0,type:"gemini",content:e.content,thoughts:Array.isArray(e.thoughts)?e.thoughts:[],tokens:e.tokens,model:W(e.model)?e.model:void 0,toolCalls:Array.isArray(e.toolCalls)?e.toolCalls:[],lineNumber:t}),W(e.id)?s:s+1}async getTokensFromGeminiCliSession(e){let t=await this.readGeminiCliSession(e),s=0,n=0;for(let i of t.assistantRecords){let r=this.getTokenBreakdown(i.tokens);s+=r.total,n+=r.thinking}return{tokens:s,thinkingTokens:n}}async countGeminiCliInteractions(e){return(await this.readGeminiCliSession(e)).userRecords.length}async getGeminiCliModelUsage(e){let t=await this.readGeminiCliSession(e),s={};for(let n of t.assistantRecords){let i=Cn(n.model||"unknown"),r=this.getTokenBreakdown(n.tokens);s[i]||(s[i]={inputTokens:0,outputTokens:0,sessions:0}),s[i].inputTokens+=r.input,s[i].outputTokens+=r.output+r.thinking+r.tool,r.cached>0&&(s[i].cachedReadTokens=(s[i].cachedReadTokens??0)+r.cached),r.thinking>0&&(s[i].thinkingTokens=(s[i].thinkingTokens??0)+r.thinking)}return s}async getGeminiCliSessionMeta(e){let t=await this.readGeminiCliSession(e),s=[],n=i=>{let r=Rs(i);r!==null&&s.push(r)};n(t.header?.startTime),n(t.header?.lastUpdated);for(let i of t.userRecords)n(i.timestamp);for(let i of t.assistantRecords)n(i.timestamp);return s.sort((i,r)=>i-r),{title:this.deriveSessionTitle(t),firstInteraction:s.length>0?new Date(s[0]).toISOString():null,lastInteraction:s.length>0?new Date(s[s.length-1]).toISOString():null,workspacePath:t.workspacePath}}processAssistantGroup(e){let t=[],s=[],n=null,i=0,r=0,a=0,c=0,d=0,p=0;for(let f of e.assistants){let h=this.getTokenBreakdown(f.tokens);p+=h.total,i+=h.input,r+=h.output,a+=h.thinking,c+=h.tool,d+=h.cached;let _=W(f.content)?f.content.trim():"";_.length>0&&t.push(_);for(let C of this.toDisplayToolCalls(f.toolCalls))s.push(C);W(f.model)&&(n=Cn(f.model))}return{assistantContents:t,toolCalls:s,model:n,inputTokens:i,outputTokens:r,thinkingTokens:a,toolTokens:c,cachedTokens:d,totalTokens:p}}async buildGeminiCliTurns(e){let t=await this.readGeminiCliSession(e),s=this.groupConversationTurns(t),n=[],i=0;for(let r of s){let a={assistantContents:[],toolCalls:[],model:null,inputTokens:0,outputTokens:0,thinkingTokens:0,toolTokens:0,cachedTokens:0};for(let A of r.assistants)i+=this._bgtAggregateAssistant(A,a);let{assistantContents:c,toolCalls:d,model:p,inputTokens:f,outputTokens:h,thinkingTokens:_,toolTokens:C,cachedTokens:T}=a,E=f>0||h>0||_>0||C>0?{promptTokens:f,completionTokens:h+_+C,promptTokenDetails:this.buildPromptTokenDetails(f,T)}:void 0;n.push({turnNumber:n.length+1,timestamp:this.pickTurnTimestamp(r.user?.timestamp,r.assistants),mode:"cli",userMessage:this.extractUserText(r.user?.content),assistantResponse:c.join(`
|
|
47
47
|
|
|
48
|
-
`),model:p,toolCalls:
|
|
48
|
+
`),model:p,toolCalls:d,contextReferences:G(),mcpTools:[],inputTokensEstimate:f,outputTokensEstimate:h+C,thinkingTokensEstimate:_,actualUsage:E})}return{turns:n,actualTokens:i}}_bgtAggregateAssistant(e,t){let s=this.getTokenBreakdown(e.tokens);t.inputTokens+=s.input,t.outputTokens+=s.output,t.thinkingTokens+=s.thinking,t.toolTokens+=s.tool,t.cachedTokens+=s.cached;let n=W(e.content)?e.content.trim():"";n.length>0&&t.assistantContents.push(n);for(let i of this.toDisplayToolCalls(e.toolCalls))t.toolCalls.push(i);return W(e.model)&&(t.model=Cn(e.model)),s.total}async getGeminiCliDailyFractions(e){let t=await this.readGeminiCliSession(e),s=t.userRecords.map(a=>this.toLocalDayKey(a.timestamp)).filter(a=>!!a);if(s.length===0)for(let a of t.assistantRecords){let c=this.toLocalDayKey(a.timestamp);c&&s.push(c)}if(s.length===0)return{[this.toLocalDayKey(t.header?.startTime)??this.toLocalDayKey(t.header?.lastUpdated)??L(new Date)]:1};let n=new Map;for(let a of s)n.set(a,(n.get(a)??0)+1);let i=s.length,r={};for(let[a,c]of n.entries())r[a]=c/i;return r}async readJsonlLines(e){try{return(await Ve.promises.readFile(e,"utf8")).split(/\r?\n/).map(t=>t.trim()).filter(t=>t.length>0)}catch{return[]}}getProjectBucketFromPath(e){let s=me(e).split("/").filter(r=>r.length>0),n=s.lastIndexOf("chats");if(n>0)return s[n-1];let i=s.lastIndexOf("tmp");if(i>=0&&i+1<s.length)return s[i+1]}async resolveWorkspacePath(e,t){let s=await this.readGeminiProjectsIndex();if(e&&s.has(e))return s.get(e);if(t&&s.has(t))return s.get(t)}async readGeminiProjectsIndex(){let e=this.getGeminiProjectsPath(),t;try{t=await Ve.promises.stat(e)}catch{return new Map}let s=this._projectsIndexCache;if(s&&s.mtimeMs===t.mtimeMs&&s.size===t.size)return s.map;let n=`${t.mtimeMs}:${t.size}`,i=this._projectsIndexInflight.get(n);if(i)return i;let r=(async()=>{let a=new Map;try{let d=JSON.parse(await Ve.promises.readFile(e,"utf8"));if(Array.isArray(d))for(let p of d)this.addProjectMapping(a,void 0,p);else if(d&&typeof d=="object")for(let[p,f]of Object.entries(d))this.addProjectMapping(a,p,f)}catch{}let c=await Ve.promises.stat(e).catch(()=>null);return c&&c.mtimeMs===t.mtimeMs&&c.size===t.size&&(this._projectsIndexCache={map:a,mtimeMs:t.mtimeMs,size:t.size}),a})();this._projectsIndexInflight.set(n,r);try{return await r}finally{this._projectsIndexInflight.get(n)===r&&this._projectsIndexInflight.delete(n)}}applyStringValueMapping(e,t,s){t&&this.looksLikePath(t)&&!this.looksLikePath(s)?e.set(s,this.normalizeWorkspacePath(t)):t&&!this.looksLikePath(t)&&this.looksLikePath(s)&&e.set(t,this.normalizeWorkspacePath(s))}applyObjectValueMapping(e,t,s){let n=this.pickString(s,["projectHash","projectBucket","bucket","slug","name","id"]),i=this.pickString(s,["workspacePath","path","directory","cwd","rootPath","repoPath","workspace","root"]);n&&i&&this.looksLikePath(i)&&e.set(n,this.normalizeWorkspacePath(i)),t&&this.looksLikePath(t)&&n&&e.set(n,this.normalizeWorkspacePath(t)),t&&!this.looksLikePath(t)&&i&&this.looksLikePath(i)&&e.set(t,this.normalizeWorkspacePath(i))}addProjectMapping(e,t,s){if(typeof s=="string"){this.applyStringValueMapping(e,t,s);return}!s||typeof s!="object"||Array.isArray(s)||this.applyObjectValueMapping(e,t,s)}pickString(e,t){for(let s of t)if(W(e[s]))return e[s].trim()}looksLikePath(e){let t=me(e);return/^[a-zA-Z]:/.test(e)||t.startsWith("/")||t.startsWith("~")||t.startsWith("file://")}normalizeWorkspacePath(e){let t=e.trim().replace(/^~(?=[/\\]|$)/,na.homedir());if(/^file:\/\//i.test(t))try{t=decodeURIComponent(t.replace(/^file:\/\/\/?/,"")),process.platform==="win32"&&/^\/[a-zA-Z]:/.test(t)&&(t=t.slice(1))}catch{}return yt.normalize(t)}getTokenBreakdown(e){let t=Es(e?.input),s=Es(e?.output),n=Es(e?.cached),i=Es(e?.thoughts),r=Es(e?.tool),a=Es(e?.total)||t+s+i+r;return{input:t,output:s,cached:n,thinking:i,tool:r,total:a}}deriveSessionTitle(e){for(let t of e.userRecords){let s=this.extractUserText(t.content).split(/\r?\n/).map(n=>n.trim()).find(n=>n.length>0);if(s)return s.length>80?`${s.slice(0,77)}...`:s}return e.projectBucket}extractUserText(e){if(W(e))return e.trim();if(!Array.isArray(e))return"";let t=[];for(let s of e)s&&typeof s=="object"&&W(s.text)&&t.push(s.text.trim());return t.join(`
|
|
49
49
|
|
|
50
|
-
`).trim()}toDisplayToolCalls(e){if(!Array.isArray(e))return[];let t=[];for(let s of e){let n=W(s?.name)?s.name.trim():"",r=(W(s?.displayName)?s.displayName.trim():"")||n;r&&t.push({toolName:r,arguments:s.args!==void 0?this.safeStringify(s.args):void 0,result:W(s.resultDisplay)?s.resultDisplay:s.result!==void 0?this.safeStringify(s.result):void 0})}return t}safeStringify(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}buildPromptTokenDetails(e,t){if(e<=0)return;let s=[],n=Math.min(t,e);n>0&&s.push({category:"cached",label:"Cache reads",percentageOfPrompt:n/e*100});let i=e-n;return i>0&&s.push({category:"prompt",label:"Prompt tokens",percentageOfPrompt:i/e*100}),s.length>0?s:void 0}groupConversationTurns(e){let t=[...e.userRecords.map(r=>({kind:"user",record:r})),...e.assistantRecords.map(r=>({kind:"assistant",record:r}))].sort((r,a)=>
|
|
50
|
+
`).trim()}toDisplayToolCalls(e){if(!Array.isArray(e))return[];let t=[];for(let s of e){let n=W(s?.name)?s.name.trim():"",r=(W(s?.displayName)?s.displayName.trim():"")||n;r&&t.push({toolName:r,arguments:s.args!==void 0?this.safeStringify(s.args):void 0,result:W(s.resultDisplay)?s.resultDisplay:s.result!==void 0?this.safeStringify(s.result):void 0})}return t}safeStringify(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}buildPromptTokenDetails(e,t){if(e<=0)return;let s=[],n=Math.min(t,e);n>0&&s.push({category:"cached",label:"Cache reads",percentageOfPrompt:n/e*100});let i=e-n;return i>0&&s.push({category:"prompt",label:"Prompt tokens",percentageOfPrompt:i/e*100}),s.length>0?s:void 0}groupConversationTurns(e){let t=[...e.userRecords.map(r=>({kind:"user",record:r})),...e.assistantRecords.map(r=>({kind:"assistant",record:r}))].sort((r,a)=>sa(r.record,a.record)),s=[],n=null,i=[];for(let r of t)r.kind==="user"?((n||i.length>0)&&(s.push({user:n,assistants:i}),i=[]),n=r.record):i.push(r.record);return(n||i.length>0)&&s.push({user:n,assistants:i}),s}pickTurnTimestamp(e,t){let s=Rs(e);if(s!==null)return new Date(s).toISOString();for(let n of t){let i=Rs(n.timestamp);if(i!==null)return new Date(i).toISOString()}return null}toLocalDayKey(e){let t=Rs(e);return t!==null?L(new Date(t)):null}};var ci=S(require("fs")),Rc=S(require("os")),_t=S(require("path"));function oa(o){let e=o.match(/<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/);if(e)return e[1].trim();let t=o.indexOf("<ADDITIONAL_METADATA>");return t!==-1?o.substring(0,t).trim():o.trim()}function ef(o,e){o.content&&o.content.trim()&&(e.assistantResponse+=(e.assistantResponse?`
|
|
51
51
|
|
|
52
52
|
`:"")+o.content.trim()),o.thinking&&o.thinking.trim()&&(e.thinkingContent+=(e.thinkingContent?`
|
|
53
53
|
|
|
54
|
-
`:"")+o.thinking.trim());for(let t of o.tool_calls??[])t.name&&e.toolCalls.push({toolName:t.name,arguments:t.args?JSON.stringify(t.args):void 0})}function
|
|
55
|
-
`).filter(
|
|
56
|
-
`)){let n=s.trim();if(n)try{t.push(JSON.parse(n))}catch{}}return t}async readSession(e){return(await this.readLines(e)).find(s=>s.type==="session")??null}async getParentSessionPath(e){let s=(await this.readSession(e))?.parentSession;return typeof s=="string"&&s.length>0?s:null}getParentSessionPathFromFilePath(e){if(Ve.basename(e)!=="session.jsonl")return null;let t=Ve.dirname(Ve.dirname(Ve.dirname(e)))+".jsonl";return this.isPiSessionFile(t)?t:null}async getMessages(e){return(await this.readLines(e)).filter(s=>s.type==="message")}async getTokens(e){let t=await this.getMessages(e),s=0;for(let n of t){if(n.message?.role!=="assistant")continue;let i=n.message?.usage;i&&typeof i.totalTokens=="number"&&(s+=i.totalTokens)}return{tokens:s,thinkingTokens:0}}async countInteractions(e){return(await this.getMessages(e)).filter(s=>s.message?.role==="user").length}async getModelUsage(e){let t=await this.getMessages(e),s={};for(let n of t)this.accumulateModelUsage(n,s);return s}accumulateModelUsage(e,t){let s=e.message;if(!s||s.role!=="assistant")return;let n=s.usage;if(!n)return;let i=typeof n.input=="number"?n.input:0,r=typeof n.output=="number"?n.output:0;if(i+r===0)return;let a=s.model||"unknown";t[a]||(t[a]={inputTokens:0,outputTokens:0}),t[a].inputTokens+=i,t[a].outputTokens+=r,this.accumulateCacheTokens(n,t[a])}accumulateCacheTokens(e,t){let s=typeof e.cacheRead=="number"?e.cacheRead:0,n=typeof e.cacheWrite=="number"?e.cacheWrite:0;s>0&&(t.cachedReadTokens=(t.cachedReadTokens??0)+s),n>0&&(t.cacheCreationTokens=(t.cacheCreationTokens??0)+n)}async getSessionMeta(e){let t=await this.readLines(e);if(t.length===0)return{title:void 0,firstInteraction:null,lastInteraction:null};let s=t.find(c=>c.type==="session"),n=s?.cwd,i=n?Ve.basename(n):void 0,r=s?.timestamp??null,a=this.findLastTimestamp(t);return{title:i,firstInteraction:r,lastInteraction:a,workspacePath:n}}findLastTimestamp(e){for(let t=e.length-1;t>=0;t--)if(e[t].timestamp)return e[t].timestamp;return null}async getSessionData(e){let[{tokens:t},s,n,i]=await Promise.all([this.getTokens(e),this.countInteractions(e),this.getModelUsage(e),this.getSessionMeta(e)]),r=i.firstInteraction?new Date(i.firstInteraction).getTime():0,a=this.buildModelUsageWithInteractions(n,s);return{tokens:t,interactions:s,modelUsage:a,timestamp:r}}buildModelUsageWithInteractions(e,t){let s=Object.values(e).reduce((i,r)=>i+r.inputTokens+r.outputTokens,0),n={};for(let[i,r]of Object.entries(e)){let a=r.inputTokens+r.outputTokens,c=s>0?a/s:0;n[i]={inputTokens:r.inputTokens,outputTokens:r.outputTokens,interactions:Math.round(t*c)}}return n}};var we=w(require("fs")),rt=w(require("path")),Gt=w(require("os")),vc=w(is());var ci=class{_sqlJsModule=null;_sqlJsInitPromise=null;_dbCache=new Map;_dbCacheInflight=new Map;extensionUri;constructor(e){this.extensionUri=e}dispose(){for(let e of this._dbCache.values())try{e.db.close()}catch{}this._dbCache.clear(),this._dbCacheInflight.clear(),this._sqlJsInitPromise=null}getCursorGlobalStorageDir(){let e=Gt.platform();if(e==="win32"){let s=process.env.APPDATA||rt.join(Gt.homedir(),"AppData","Roaming");return rt.join(s,"Cursor","User","globalStorage")}if(e==="darwin")return rt.join(Gt.homedir(),"Library","Application Support","Cursor","User","globalStorage");let t=process.env.XDG_CONFIG_HOME||rt.join(Gt.homedir(),".config");return rt.join(t,"Cursor","User","globalStorage")}getCursorDbPath(){return rt.join(this.getCursorGlobalStorageDir(),"state.vscdb")}isCursorSessionFile(e){return Y(e).includes("/cursor/user/globalstorage/state.vscdb#")}getDbPathFromVirtual(e){let t=e.indexOf("state.vscdb#");return t===-1?e:e.substring(0,t+11)}getComposerIdFromVirtual(e){let t=e.indexOf("state.vscdb#");return t===-1?null:e.substring(t+12)}async initSqlJs(){return this._sqlJsModule?this._sqlJsModule:(this._sqlJsInitPromise||(this._sqlJsInitPromise=(async()=>{let e=rt.join(__dirname,"sql-wasm.wasm"),t;we.existsSync(e)&&(t=we.readFileSync(e));let s=await(0,vc.default)(t?{wasmBinary:t.buffer}:void 0);return this._sqlJsModule=s,s})().catch(e=>{throw this._sqlJsInitPromise=null,e})),this._sqlJsInitPromise)}getWalMtimeMs(e){try{return we.statSync(e+"-wal").mtimeMs}catch{return 0}}statDb(e){try{return we.statSync(e)}catch(t){let s=t?.code;if((s==="ENOENT"||s==="ENOTDIR")&&this._dbCache.has(e)){try{this._dbCache.get(e).db.close()}catch{}this._dbCache.delete(e)}return null}}isCachedDbCurrent(e,t){let s=this._dbCache.get(e);return!!s&&s.mtimeMs===t.mtimeMs&&s.size===t.size&&s.walMtimeMs===this.getWalMtimeMs(e)}async tryReadDbWithWal(e){let t=e+"-wal",s;try{s=we.statSync(t).size}catch{return null}if(s===0)return null;try{let{DatabaseSync:n}=require("node:sqlite"),i=Gt.tmpdir(),r=rt.join(i,`cursor-wal-${Date.now()}.db`),a=r+"-wal",c=r+"-shm",m=e+"-shm";we.copyFileSync(e,r),we.copyFileSync(t,a),we.existsSync(m)&&we.copyFileSync(m,c);let p=new n(r);p.exec("PRAGMA wal_checkpoint(TRUNCATE);"),p.close();let f=we.readFileSync(r);for(let h of[r,a,c])try{we.unlinkSync(h)}catch{}return f}catch{return null}}async refreshDb(e,t){let s=this.getWalMtimeMs(e),n;try{let a=await this.initSqlJs(),m=await this.tryReadDbWithWal(e)??we.readFileSync(e);n=new a.Database(m)}catch{return this._dbCache.get(e)?.db??null}let i=this.statDb(e);if(!i||i.mtimeMs!==t.mtimeMs||i.size!==t.size){try{n.close()}catch{}return this._dbCache.get(e)?.db??null}let r=this._dbCache.get(e);if(r)try{r.db.close()}catch{}return this._dbCache.set(e,{db:n,mtimeMs:t.mtimeMs,size:t.size,walMtimeMs:s}),n}async getDb(e){let t=this.statDb(e);if(!t)return this._dbCache.get(e)?.db??null;if(this.isCachedDbCurrent(e,t))return this._dbCache.get(e).db;let s=`${e}:${t.mtimeMs}:${t.size}:wal${this.getWalMtimeMs(e)}`,n=this._dbCacheInflight.get(s);if(n)return n;let i=this.refreshDb(e,t);this._dbCacheInflight.set(s,i);try{return await i}finally{this._dbCacheInflight.get(s)===i&&this._dbCacheInflight.delete(s)}}async readComposerData(e){let t=this.getDbPathFromVirtual(e),s=this.getComposerIdFromVirtual(e);if(!s)return null;let n=await this.getDb(t);if(!n)return null;try{let i=n.exec("SELECT value FROM cursorDiskKV WHERE key = ?",[`composerData:${s}`]);if(i.length===0||i[0].values.length===0)return null;let r=i[0].values[0][0];return JSON.parse(r)}catch{return null}}async readBubbles(e,t){if(t.length===0)return new Map;let s=this.getDbPathFromVirtual(e),n=this.getComposerIdFromVirtual(e);if(!n)return new Map;let i=await this.getDb(s);if(!i)return new Map;let r=new Map;try{let a=t.map(()=>"?").join(","),c=t.map(p=>`bubbleId:${n}:${p}`),m=i.exec(`SELECT key, value FROM cursorDiskKV WHERE key IN (${a})`,c);if(m.length===0)return r;for(let p of m[0].values){let f=p[0],h=p[1],_=f.replace(`bubbleId:${n}:`,"");try{let C=JSON.parse(h);r.set(_,C)}catch{}}}catch{}return r}async discoverSessions(){let e=this.getCursorDbPath(),t=await this.getDb(e);if(!t)return[];try{let s=t.exec("SELECT key FROM cursorDiskKV WHERE key LIKE 'composerData:%' AND (length(key) - length(replace(key, ':', ''))) = 1");return s.length===0?[]:s[0].values.map(n=>{let i=n[0].replace("composerData:","");return`${e}#${i}`})}catch{return[]}}async statSessionFile(e){let t=this.getDbPathFromVirtual(e);return we.promises.stat(t)}async getTokens(e){let t=await this.readComposerData(e);return t?{tokens:typeof t.contextTokensUsed=="number"?t.contextTokensUsed:0,thinkingTokens:0}:{tokens:0,thinkingTokens:0}}async countInteractions(e){let t=await this.readComposerData(e);return t?.fullConversationHeadersOnly?t.fullConversationHeadersOnly.filter(s=>s.type===1).length:0}async getModelUsage(e){let t=await this.readComposerData(e);if(!t)return{};let s=typeof t.contextTokensUsed=="number"?t.contextTokensUsed:0;return s===0?{}:{[t.modelConfig?.modelName||"unknown"]:{inputTokens:s,outputTokens:0}}}async getSessionMeta(e){let t=await this.readComposerData(e);if(!t)return{title:void 0,firstInteraction:null,lastInteraction:null,workspacePath:void 0};let s=t.name&&t.name.trim()?t.name.trim():void 0,n=typeof t.createdAt=="number"?t.createdAt:null,i=typeof t.lastUpdatedAt=="number"?t.lastUpdatedAt:null,r=n?new Date(n).toISOString():null,a=i?new Date(i):n?new Date(n):null,c=this.extractWorkspacePath(t);return{title:s,firstInteraction:r,lastInteraction:a?a.toISOString():null,workspacePath:c}}extractWorkspacePath(e){return e.trackedGitRepos&&e.trackedGitRepos.length>0?e.trackedGitRepos[0].repoPath:this.extractWorkspaceFromFileStates(e.originalFileStates)}extractWorkspaceFromFileStates(e){if(!e)return;let t=Object.keys(e);if(t.length!==0)try{return decodeURIComponent(t[0].replace("file:///","").replace("file://","")).replace(/^\/([A-Za-z]):/,"$1:").split(/[/\\]/).slice(0,-1).join(rt.sep)}catch{return}}async getSessionData(e){let[{tokens:t},s,n,i]=await Promise.all([this.getTokens(e),this.countInteractions(e),this.getModelUsage(e),this.getSessionMeta(e)]),r=i.firstInteraction?new Date(i.firstInteraction).getTime():Date.now();return{tokens:t,interactions:s,modelUsage:n,timestamp:r}}};var Tt=w(require("fs")),Ce=w(require("path")),Os=w(require("os")),Ac=w(require("crypto"));var Wg=new Set(["intentClassification","model","say"]),ui=class{getKiroAppDataDir(){let e=Os.platform();if(e==="win32"){let t=process.env.APPDATA||Ce.join(Os.homedir(),"AppData","Roaming");return Ce.join(t,"Kiro")}return e==="darwin"?Ce.join(Os.homedir(),"Library","Application Support","Kiro"):Ce.join(Os.homedir(),".config","Kiro")}getKiroAgentDir(){return Ce.join(this.getKiroAppDataDir(),"User","globalStorage","kiro.kiroagent")}getKiroWorkspaceSessionsDir(){return Ce.join(this.getKiroAgentDir(),"workspace-sessions")}isKiroSessionFile(e){let t=Y(e);return t.includes("/kiro.kiroagent/workspace-sessions/")&&t.endsWith(".json")&&!t.endsWith("/sessions.json")}async getKiroSessionFiles(){let e=this.getKiroWorkspaceSessionsDir(),t;try{t=await Tt.promises.readdir(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let n of t){if(!n.isDirectory())continue;let i=Ce.join(e,n.name);try{let r=await Tt.promises.readdir(i);for(let a of r)a.endsWith(".json")&&a!=="sessions.json"&&s.push(Ce.join(i,a))}catch{}}return s}async readSessionFile(e){try{let t=await Tt.promises.readFile(e,"utf8");return JSON.parse(t)}catch{return null}}_executionRecordCache=new Map;getWorkspaceExecutionDir(e){let t=Ac.createHash("sha256").update(e).digest("hex").slice(0,32);return Ce.join(this.getKiroAgentDir(),t)}async readExecutionRecordsForSession(e){let t=Ce.basename(e,".json"),s=this.decodeWorkspaceDirName(Ce.basename(Ce.dirname(e)));if(!s)return[];let n=this.getWorkspaceExecutionDir(s),i=await this.collectExecutionFiles(n,0),r=[];for(let a of i){let c=await this.readExecutionFile(a);c?.executionId&&c?.chatSessionId===t&&r.push(this.toExecutionRecord(c))}return r.sort((a,c)=>(a.startTimeMs??0)-(c.startTimeMs??0)),r}async collectExecutionFiles(e,t){if(t>3)return[];let s;try{s=await Tt.promises.readdir(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let i of s){if(!/^[0-9a-f]{32}$/.test(i.name))continue;let r=Ce.join(e,i.name);i.isDirectory()?n.push(...await this.collectExecutionFiles(r,t+1)):n.push(r)}return n}async readExecutionFile(e){let t;try{t=await Tt.promises.stat(e)}catch{return null}let s=this._executionRecordCache.get(e);if(s&&s.mtimeMs===t.mtimeMs)return s.parsed;let n=null;try{n=JSON.parse(await Tt.promises.readFile(e,"utf8"))}catch{n=null}return this._executionRecordCache.set(e,{mtimeMs:t.mtimeMs,parsed:n}),n}toExecutionRecord(e){let t=Array.isArray(e?.context?.messages)?e.context.messages:[],s=t[t.length-1],n=s?.role==="bot",i=0;for(let c of n?t.slice(0,-1):t)i+=this.estimateTokens(this.extractContextMessageText(c));let r=n?this.extractContextMessageText(s,!0):"",a=this.estimateTokens(n?this.extractContextMessageText(s):"");return{executionId:String(e.executionId),startTimeMs:typeof e.startTime=="number"?e.startTime:null,responseText:r,toolCalls:this.extractActionToolCalls(e),inputTokens:i,outputTokens:a,credits:this.sumUsageCredits(e)}}extractContextMessageText(e,t=!1){let s=[];for(let n of Array.isArray(e?.entries)?e.entries:[]){if(typeof n?.text=="string"){s.push(n.text);continue}t||(n?.args!==void 0?s.push(this.safeStringify(n.args)):n?.document!==void 0&&s.push(this.safeStringify(n.document)))}return s.join(`
|
|
57
|
-
`)}extractActionToolCalls(e){let t=[];for(let s of Array.isArray(e?.actions)?e.actions:[]){let n=typeof s?.actionType=="string"?s.actionType:"";!n||
|
|
54
|
+
`:"")+o.thinking.trim());for(let t of o.tool_calls??[])t.name&&e.toolCalls.push({toolName:t.name,arguments:t.args?JSON.stringify(t.args):void 0})}function tf(o,e){e.toolCalls.length>0&&!e.toolCalls[e.toolCalls.length-1].result&&o.content&&(e.toolCalls[e.toolCalls.length-1].result=o.content.trim())}function sf(o,e){o.type==="PLANNER_RESPONSE"?ef(o,e):o.type==="SEARCH_WEB"&&o.content&&tf(o,e)}function nf(o,e){let t={assistantResponse:"",thinkingContent:"",toolCalls:[]};for(let s=e;s<o.length;s++){let n=o[s];if(n.type==="USER_INPUT"&&n.source==="USER_EXPLICIT")break;n.source==="MODEL"&&sf(n,t)}return t}var ui=class{getAntigravityDataDir(){return _t.join(Rc.homedir(),".gemini","antigravity")}getAntigravityBrainDir(){return _t.join(this.getAntigravityDataDir(),"brain")}isAntigravitySessionFile(e){let t=X(e);return t.includes("/.gemini/antigravity/brain/")&&t.endsWith("/transcript.jsonl")}getSessionIdFromPath(e){let t=e.replace(/\\/g,"/"),s=t.toLowerCase().indexOf("/.gemini/antigravity/brain/");if(s===-1)return _t.basename(_t.dirname(_t.dirname(_t.dirname(e))));let n=t.substring(s+27),i=n.indexOf("/");return i!==-1?n.substring(0,i):n}async getAntigravitySessionFiles(){let e=this.getAntigravityBrainDir(),t=[],s;try{s=await ci.promises.readdir(e,{withFileTypes:!0})}catch{return[]}for(let n of s){if(!n.isDirectory())continue;let i=_t.join(e,n.name,".system_generated","logs","transcript.jsonl");try{(await ci.promises.stat(i)).size>0&&t.push(i)}catch{}}return t}async readAntigravitySession(e){let t=this.getSessionIdFromPath(e),s=[],n=[],i=[],r;try{r=await ci.promises.readFile(e,"utf8")}catch{return{sessionId:t,userEntries:s,modelEntries:n,allEntries:i}}let a=r.split(`
|
|
55
|
+
`).filter(d=>d.trim().length>0);for(let d of a){let p;try{p=JSON.parse(d)}catch{continue}!p||typeof p.type!="string"||(i.push(p),p.type==="USER_INPUT"&&p.source==="USER_EXPLICIT"?s.push(p):p.source==="MODEL"&&n.push(p))}let c=(d,p)=>d.step_index-p.step_index;return i.sort(c),s.sort(c),n.sort(c),{sessionId:t,userEntries:s,modelEntries:n,allEntries:i}}async estimateTokensFromAntigravitySession(e,t){let s=await this.readAntigravitySession(e),n=0,i=0,r=0;for(let a of s.userEntries)n+=t(oa(a.content??""));for(let a of s.modelEntries)a.type==="PLANNER_RESPONSE"&&(a.content&&(i+=t(a.content)),a.thinking&&(r+=t(a.thinking)));return{tokens:n+i+r,thinkingTokens:r}}async countAntigravityInteractions(e){return(await this.readAntigravitySession(e)).userEntries.length}getAntigravityModelUsage(e){return{}}async getAntigravitySessionMeta(e){let t=await this.readAntigravitySession(e),s=t.allEntries,n;if(t.userEntries.length>0){let c=t.userEntries[0].content??"",d=oa(c);n=d.length>120?d.substring(0,117)+"...":d||void 0}let i=s.length>0?s[0].created_at??null:null,r=s.length>0?s[s.length-1].created_at??null:null;return{title:n,firstInteraction:i,lastInteraction:r}}_batCreateChatTurn(e,t,s,n){return{turnNumber:e,timestamp:t.created_at??null,mode:"cli",userMessage:oa(t.content??""),assistantResponse:s,model:null,toolCalls:n,contextReferences:G(),mcpTools:[],inputTokensEstimate:0,outputTokensEstimate:0,thinkingTokensEstimate:0}}_batIsUserInputEntry(e){return e.type==="USER_INPUT"&&e.source==="USER_EXPLICIT"}async buildAntigravityTurns(e){let s=(await this.readAntigravitySession(e)).allEntries,n=[],i=0;for(let r=0;r<s.length;r++){let a=s[r];if(!this._batIsUserInputEntry(a))continue;i++;let{assistantResponse:c,toolCalls:d}=nf(s,r+1);n.push(this._batCreateChatTurn(i,a,c,d))}return{turns:n}}async countToolCalls(e){let t=await this.readAntigravitySession(e),s=0;for(let n of t.allEntries)Array.isArray(n.tool_calls)&&(s+=n.tool_calls.length);return s}};var di=S(require("fs")),Ke=S(require("path")),Ic=S(require("os"));var mi=class{getConfigDir(){return Ke.join(Ic.homedir(),".pi","agent","sessions")}isPiSessionFile(e){let t=me(e);return t.includes("/.pi/agent/sessions/")&&t.endsWith(".jsonl")}async discoverSessions(){let e=this.getConfigDir(),t=[];try{let s=await di.promises.readdir(e,{withFileTypes:!0});for(let n of s)n.isDirectory()&&await this.collectSessionFilesInDir(Ke.join(e,n.name),t,4)}catch{}return t}async collectSessionFilesInDir(e,t,s){if(!(s<=0))try{let n=await di.promises.readdir(e,{withFileTypes:!0});for(let i of n)i.isFile()&&i.name.endsWith(".jsonl")?t.push(Ke.join(e,i.name)):i.isDirectory()&&await this.collectSessionFilesInDir(Ke.join(e,i.name),t,s-1)}catch{}}async readLines(e){try{let t=await di.promises.readFile(e,"utf8");return this.parseJsonlContent(t)}catch{return[]}}parseJsonlContent(e){let t=[];for(let s of e.split(`
|
|
56
|
+
`)){let n=s.trim();if(n)try{t.push(JSON.parse(n))}catch{}}return t}async readSession(e){return(await this.readLines(e)).find(s=>s.type==="session")??null}async getParentSessionPath(e){let s=(await this.readSession(e))?.parentSession;return typeof s=="string"&&s.length>0?s:null}getParentSessionPathFromFilePath(e){if(Ke.basename(e)!=="session.jsonl")return null;let t=Ke.dirname(Ke.dirname(Ke.dirname(e)))+".jsonl";return this.isPiSessionFile(t)?t:null}async getMessages(e){return(await this.readLines(e)).filter(s=>s.type==="message")}async getTokens(e){let t=await this.getMessages(e),s=0;for(let n of t){if(n.message?.role!=="assistant")continue;let i=n.message?.usage;i&&typeof i.totalTokens=="number"&&(s+=i.totalTokens)}return{tokens:s,thinkingTokens:0}}async countInteractions(e){return(await this.getMessages(e)).filter(s=>s.message?.role==="user").length}async getModelUsage(e){let t=await this.getMessages(e),s={};for(let n of t)this.accumulateModelUsage(n,s);return s}accumulateModelUsage(e,t){let s=e.message;if(!s||s.role!=="assistant")return;let n=s.usage;if(!n)return;let i=typeof n.input=="number"?n.input:0,r=typeof n.output=="number"?n.output:0;if(i+r===0)return;let a=s.model||"unknown";t[a]||(t[a]={inputTokens:0,outputTokens:0,sessions:0}),t[a].inputTokens+=i,t[a].outputTokens+=r,this.accumulateCacheTokens(n,t[a])}accumulateCacheTokens(e,t){let s=typeof e.cacheRead=="number"?e.cacheRead:0,n=typeof e.cacheWrite=="number"?e.cacheWrite:0;s>0&&(t.cachedReadTokens=(t.cachedReadTokens??0)+s),n>0&&(t.cacheCreationTokens=(t.cacheCreationTokens??0)+n)}async getSessionMeta(e){let t=await this.readLines(e);if(t.length===0)return{title:void 0,firstInteraction:null,lastInteraction:null};let s=t.find(c=>c.type==="session"),n=s?.cwd,i=n?Ke.basename(n):void 0,r=s?.timestamp??null,a=this.findLastTimestamp(t);return{title:i,firstInteraction:r,lastInteraction:a,workspacePath:n}}findLastTimestamp(e){for(let t=e.length-1;t>=0;t--)if(e[t].timestamp)return e[t].timestamp;return null}async getSessionData(e){let[{tokens:t},s,n,i]=await Promise.all([this.getTokens(e),this.countInteractions(e),this.getModelUsage(e),this.getSessionMeta(e)]),r=i.firstInteraction?new Date(i.firstInteraction).getTime():0,a=this.buildModelUsageWithInteractions(n,s);return{tokens:t,interactions:s,modelUsage:a,timestamp:r}}buildModelUsageWithInteractions(e,t){let s=Object.values(e).reduce((i,r)=>i+r.inputTokens+r.outputTokens,0),n={};for(let[i,r]of Object.entries(e)){let a=r.inputTokens+r.outputTokens,c=s>0?a/s:0;n[i]={inputTokens:r.inputTokens,outputTokens:r.outputTokens,sessions:r.sessions,interactions:Math.round(t*c)}}return n}};var Te=S(require("fs")),rt=S(require("path")),qt=S(require("os")),Uc=S(Nt());var pi=class{_sqlJsModule=null;_sqlJsInitPromise=null;_dbCache=new Map;_dbCacheInflight=new Map;extensionUri;constructor(e){this.extensionUri=e}dispose(){for(let e of this._dbCache.values())try{e.db.close()}catch{}this._dbCache.clear(),this._dbCacheInflight.clear(),this._sqlJsInitPromise=null}getCursorGlobalStorageDir(){let e=qt.platform();if(e==="win32"){let s=process.env.APPDATA||rt.join(qt.homedir(),"AppData","Roaming");return rt.join(s,"Cursor","User","globalStorage")}if(e==="darwin")return rt.join(qt.homedir(),"Library","Application Support","Cursor","User","globalStorage");let t=process.env.XDG_CONFIG_HOME||rt.join(qt.homedir(),".config");return rt.join(t,"Cursor","User","globalStorage")}getCursorDbPath(){return rt.join(this.getCursorGlobalStorageDir(),"state.vscdb")}isCursorSessionFile(e){return X(e).includes("/cursor/user/globalstorage/state.vscdb#")}getDbPathFromVirtual(e){let t=e.indexOf("state.vscdb#");return t===-1?e:e.substring(0,t+11)}getComposerIdFromVirtual(e){let t=e.indexOf("state.vscdb#");return t===-1?null:e.substring(t+12)}async initSqlJs(){return this._sqlJsModule?this._sqlJsModule:(this._sqlJsInitPromise||(this._sqlJsInitPromise=(async()=>{let e=rt.join(__dirname,"sql-wasm.wasm"),t;Te.existsSync(e)&&(t=Te.readFileSync(e));let s=await(0,Uc.default)(t?{wasmBinary:t.buffer}:void 0);return this._sqlJsModule=s,s})().catch(e=>{throw this._sqlJsInitPromise=null,e})),this._sqlJsInitPromise)}getWalMtimeMs(e){try{return Te.statSync(e+"-wal").mtimeMs}catch{return 0}}statDb(e){try{return Te.statSync(e)}catch(t){let s=t?.code;if((s==="ENOENT"||s==="ENOTDIR")&&this._dbCache.has(e)){try{this._dbCache.get(e).db.close()}catch{}this._dbCache.delete(e)}return null}}isCachedDbCurrent(e,t){let s=this._dbCache.get(e);return!!s&&s.mtimeMs===t.mtimeMs&&s.size===t.size&&s.walMtimeMs===this.getWalMtimeMs(e)}async tryReadDbWithWal(e){let t=e+"-wal",s;try{s=Te.statSync(t).size}catch{return null}if(s===0)return null;try{let{DatabaseSync:n}=require("node:sqlite"),i=qt.tmpdir(),r=rt.join(i,`cursor-wal-${Date.now()}.db`),a=r+"-wal",c=r+"-shm",d=e+"-shm";Te.copyFileSync(e,r),Te.copyFileSync(t,a),Te.existsSync(d)&&Te.copyFileSync(d,c);let p=new n(r);p.exec("PRAGMA wal_checkpoint(TRUNCATE);"),p.close();let f=Te.readFileSync(r);for(let h of[r,a,c])try{Te.unlinkSync(h)}catch{}return f}catch{return null}}async refreshDb(e,t){let s=this.getWalMtimeMs(e),n;try{let a=await this.initSqlJs(),d=await this.tryReadDbWithWal(e)??Te.readFileSync(e);n=new a.Database(d)}catch{return this._dbCache.get(e)?.db??null}let i=this.statDb(e);if(!i||i.mtimeMs!==t.mtimeMs||i.size!==t.size){try{n.close()}catch{}return this._dbCache.get(e)?.db??null}let r=this._dbCache.get(e);if(r)try{r.db.close()}catch{}return this._dbCache.set(e,{db:n,mtimeMs:t.mtimeMs,size:t.size,walMtimeMs:s}),n}async getDb(e){let t=this.statDb(e);if(!t)return this._dbCache.get(e)?.db??null;if(this.isCachedDbCurrent(e,t))return this._dbCache.get(e).db;let s=`${e}:${t.mtimeMs}:${t.size}:wal${this.getWalMtimeMs(e)}`,n=this._dbCacheInflight.get(s);if(n)return n;let i=this.refreshDb(e,t);this._dbCacheInflight.set(s,i);try{return await i}finally{this._dbCacheInflight.get(s)===i&&this._dbCacheInflight.delete(s)}}async readComposerData(e){let t=this.getDbPathFromVirtual(e),s=this.getComposerIdFromVirtual(e);if(!s)return null;let n=await this.getDb(t);if(!n)return null;try{let i=n.exec("SELECT value FROM cursorDiskKV WHERE key = ?",[`composerData:${s}`]);if(i.length===0||i[0].values.length===0)return null;let r=i[0].values[0][0];return JSON.parse(r)}catch{return null}}async readBubbles(e,t){if(t.length===0)return new Map;let s=this.getDbPathFromVirtual(e),n=this.getComposerIdFromVirtual(e);if(!n)return new Map;let i=await this.getDb(s);if(!i)return new Map;let r=new Map;try{let a=t.map(()=>"?").join(","),c=t.map(p=>`bubbleId:${n}:${p}`),d=i.exec(`SELECT key, value FROM cursorDiskKV WHERE key IN (${a})`,c);if(d.length===0)return r;for(let p of d[0].values){let f=p[0],h=p[1],_=f.replace(`bubbleId:${n}:`,"");try{let C=JSON.parse(h);r.set(_,C)}catch{}}}catch{}return r}async discoverSessions(){let e=this.getCursorDbPath(),t=await this.getDb(e);if(!t)return[];try{let s=t.exec("SELECT key FROM cursorDiskKV WHERE key LIKE 'composerData:%' AND (length(key) - length(replace(key, ':', ''))) = 1");return s.length===0?[]:s[0].values.map(n=>{let i=n[0].replace("composerData:","");return`${e}#${i}`})}catch{return[]}}async statSessionFile(e){let t=this.getDbPathFromVirtual(e);return Te.promises.stat(t)}async getTokens(e){let t=await this.readComposerData(e);return t?{tokens:typeof t.contextTokensUsed=="number"?t.contextTokensUsed:0,thinkingTokens:0}:{tokens:0,thinkingTokens:0}}async countInteractions(e){let t=await this.readComposerData(e);return t?.fullConversationHeadersOnly?t.fullConversationHeadersOnly.filter(s=>s.type===1).length:0}async getModelUsage(e){let t=await this.readComposerData(e);if(!t)return{};let s=typeof t.contextTokensUsed=="number"?t.contextTokensUsed:0;return s===0?{}:{[t.modelConfig?.modelName||"unknown"]:{inputTokens:s,outputTokens:0,sessions:0}}}async getSessionMeta(e){let t=await this.readComposerData(e);if(!t)return{title:void 0,firstInteraction:null,lastInteraction:null,workspacePath:void 0};let s=t.name&&t.name.trim()?t.name.trim():void 0,n=typeof t.createdAt=="number"?t.createdAt:null,i=typeof t.lastUpdatedAt=="number"?t.lastUpdatedAt:null,r=n?new Date(n).toISOString():null,a=i?new Date(i):n?new Date(n):null,c=this.extractWorkspacePath(t);return{title:s,firstInteraction:r,lastInteraction:a?a.toISOString():null,workspacePath:c}}extractWorkspacePath(e){return e.trackedGitRepos&&e.trackedGitRepos.length>0?e.trackedGitRepos[0].repoPath:this.extractWorkspaceFromFileStates(e.originalFileStates)}extractWorkspaceFromFileStates(e){if(!e)return;let t=Object.keys(e);if(t.length!==0)try{return decodeURIComponent(t[0].replace("file:///","").replace("file://","")).replace(/^\/([A-Za-z]):/,"$1:").split(/[/\\]/).slice(0,-1).join(rt.sep)}catch{return}}async getSessionData(e){let[{tokens:t},s,n,i]=await Promise.all([this.getTokens(e),this.countInteractions(e),this.getModelUsage(e),this.getSessionMeta(e)]),r=i.firstInteraction?new Date(i.firstInteraction).getTime():Date.now();return{tokens:t,interactions:s,modelUsage:n,timestamp:r}}};var wt=S(require("fs")),Ce=S(require("path")),Is=S(require("os")),Oc=S(require("crypto"));var of=new Set(["intentClassification","model","say"]),gi=class{getKiroAppDataDir(){let e=Is.platform();if(e==="win32"){let t=process.env.APPDATA||Ce.join(Is.homedir(),"AppData","Roaming");return Ce.join(t,"Kiro")}return e==="darwin"?Ce.join(Is.homedir(),"Library","Application Support","Kiro"):Ce.join(Is.homedir(),".config","Kiro")}getKiroAgentDir(){return Ce.join(this.getKiroAppDataDir(),"User","globalStorage","kiro.kiroagent")}getKiroWorkspaceSessionsDir(){return Ce.join(this.getKiroAgentDir(),"workspace-sessions")}isKiroSessionFile(e){let t=X(e);return t.includes("/kiro.kiroagent/workspace-sessions/")&&t.endsWith(".json")&&!t.endsWith("/sessions.json")}async getKiroSessionFiles(){let e=this.getKiroWorkspaceSessionsDir(),t;try{t=await wt.promises.readdir(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let n of t){if(!n.isDirectory())continue;let i=Ce.join(e,n.name);try{let r=await wt.promises.readdir(i);for(let a of r)a.endsWith(".json")&&a!=="sessions.json"&&s.push(Ce.join(i,a))}catch{}}return s}async readSessionFile(e){try{let t=await wt.promises.readFile(e,"utf8");return JSON.parse(t)}catch{return null}}_executionRecordCache=new Map;getWorkspaceExecutionDir(e){let t=Oc.createHash("sha256").update(e).digest("hex").slice(0,32);return Ce.join(this.getKiroAgentDir(),t)}async readExecutionRecordsForSession(e){let t=Ce.basename(e,".json"),s=this.decodeWorkspaceDirName(Ce.basename(Ce.dirname(e)));if(!s)return[];let n=this.getWorkspaceExecutionDir(s),i=await this.collectExecutionFiles(n,0),r=[];for(let a of i){let c=await this.readExecutionFile(a);c?.executionId&&c?.chatSessionId===t&&r.push(this.toExecutionRecord(c))}return r.sort((a,c)=>(a.startTimeMs??0)-(c.startTimeMs??0)),r}async collectExecutionFiles(e,t){if(t>3)return[];let s;try{s=await wt.promises.readdir(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let i of s){if(!/^[0-9a-f]{32}$/.test(i.name))continue;let r=Ce.join(e,i.name);i.isDirectory()?n.push(...await this.collectExecutionFiles(r,t+1)):n.push(r)}return n}async readExecutionFile(e){let t;try{t=await wt.promises.stat(e)}catch{return null}let s=this._executionRecordCache.get(e);if(s&&s.mtimeMs===t.mtimeMs)return s.parsed;let n=null;try{n=JSON.parse(await wt.promises.readFile(e,"utf8"))}catch{n=null}return this._executionRecordCache.set(e,{mtimeMs:t.mtimeMs,parsed:n}),n}toExecutionRecord(e){let t=Array.isArray(e?.context?.messages)?e.context.messages:[],s=t[t.length-1],n=s?.role==="bot",i=0;for(let c of n?t.slice(0,-1):t)i+=this.estimateTokens(this.extractContextMessageText(c));let r=n?this.extractContextMessageText(s,!0):"",a=this.estimateTokens(n?this.extractContextMessageText(s):"");return{executionId:String(e.executionId),startTimeMs:typeof e.startTime=="number"?e.startTime:null,responseText:r,toolCalls:this.extractActionToolCalls(e),inputTokens:i,outputTokens:a,credits:this.sumUsageCredits(e)}}extractContextMessageText(e,t=!1){let s=[];for(let n of Array.isArray(e?.entries)?e.entries:[]){if(typeof n?.text=="string"){s.push(n.text);continue}t||(n?.args!==void 0?s.push(this.safeStringify(n.args)):n?.document!==void 0&&s.push(this.safeStringify(n.document)))}return s.join(`
|
|
57
|
+
`)}extractActionToolCalls(e){let t=[];for(let s of Array.isArray(e?.actions)?e.actions:[]){let n=typeof s?.actionType=="string"?s.actionType:"";!n||of.has(n)||t.push({toolName:n,arguments:s.input!==void 0?this.safeStringify(s.input):void 0})}return t}sumUsageCredits(e){let t=0;for(let s of Array.isArray(e?.usageSummary)?e.usageSummary:[])typeof s?.usage=="number"&&Number.isFinite(s.usage)&&(t+=s.usage);return t}safeStringify(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}estimateTokens(e){return e?Math.ceil(e.length/4):0}async getTokensFromKiroSession(e){let t=await this.readExecutionRecordsForSession(e);if(t.length>0){let s=0;for(let n of t)s+=n.inputTokens+n.outputTokens;return{tokens:s,thinkingTokens:0}}return this.getTokensFromSessionFileText(e)}async getTokensFromSessionFileText(e){let t=await this.readSessionFile(e);if(!t||!Array.isArray(t.history))return{tokens:0,thinkingTokens:0};let s=0;for(let n of t.history){if(Array.isArray(n.promptLogs))for(let i of n.promptLogs)s+=this.estimateTokens(i.prompt||""),s+=this.estimateTokens(i.completion||"");n.message?.role==="assistant"&&typeof n.message.content=="string"&&(s+=this.estimateTokens(n.message.content))}return{tokens:s,thinkingTokens:0}}async countKiroInteractions(e){let t=await this.readSessionFile(e);return!t||!Array.isArray(t.history)?0:t.history.filter(s=>s.message?.role==="user").length}async getKiroModelUsage(e){let t=await this.readExecutionRecordsForSession(e);if(t.length>0){let s=await this.getSessionModelTitle(e),n={[s]:{inputTokens:0,outputTokens:0,sessions:0}};for(let i of t)n[s].inputTokens+=i.inputTokens,n[s].outputTokens+=i.outputTokens;return n}return this.getModelUsageFromSessionFileText(e)}async getSessionModelTitle(e){let t=await this.readSessionFile(e);for(let s of Array.isArray(t?.history)?t.history:[])if(Array.isArray(s.promptLogs))for(let n of s.promptLogs){let i=n.modelTitle||n.completionOptions?.model;if(i)return i}return"agent"}async getModelUsageFromSessionFileText(e){let t=await this.readSessionFile(e);if(!t||!Array.isArray(t.history))return{};let s={};for(let n of t.history)if(Array.isArray(n.promptLogs))for(let i of n.promptLogs){let r=i.modelTitle||i.completionOptions?.model||"unknown";s[r]||(s[r]={inputTokens:0,outputTokens:0,sessions:0}),s[r].inputTokens+=this.estimateTokens(i.prompt||""),s[r].outputTokens+=this.estimateTokens(i.completion||"")}return s}async readSessionIndexEntry(e){let t=Ce.join(Ce.dirname(e),"sessions.json"),s=Ce.basename(e,".json");try{let n=JSON.parse(await wt.promises.readFile(t,"utf8"));if(!Array.isArray(n))return;let i=n.find(r=>r?.sessionId===s);return i?{dateCreated:i.dateCreated?Number(i.dateCreated):void 0,title:i.title,workspaceDirectory:i.workspaceDirectory}:void 0}catch{return}}decodeWorkspaceDirName(e){try{let t=Buffer.from(e.replace(/_/g,"="),"base64").toString("utf8");return/^([a-zA-Z]:[\\/]|\/)/.test(t)?t:void 0}catch{return}}async getKiroSessionMeta(e){let t=await this.readSessionFile(e),s=await this.readSessionIndexEntry(e),n=null,i=null;s?.dateCreated&&Number.isFinite(s.dateCreated)&&(n=new Date(s.dateCreated).toISOString());try{let a=await wt.promises.stat(e);i=a.mtime.toISOString(),n||(n=a.birthtime.toISOString())}catch{}let r=s?.workspaceDirectory??this.decodeWorkspaceDirName(Ce.basename(Ce.dirname(e)));return{title:s?.title??t?.title,firstInteraction:n,lastInteraction:i,workspacePath:r}}async getKiroDailyFractions(e){let t=await this.readExecutionRecordsForSession(e),s=t.reduce((r,a)=>r+a.inputTokens+a.outputTokens,0);if(t.length===0||s===0){let r=await this.getKiroSessionMeta(e),a=r.firstInteraction?Date.parse(r.firstInteraction):NaN;return{[Number.isFinite(a)?L(new Date(a)):L(new Date)]:1}}let n=new Map;for(let r of t){let a=r.startTimeMs!==null?L(new Date(r.startTimeMs)):L(new Date);n.set(a,(n.get(a)??0)+r.inputTokens+r.outputTokens)}let i={};for(let[r,a]of n.entries())i[r]=a/s;return i}extractUserText(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
58
58
|
`):""}async buildKiroTurns(e){let t=await this.readSessionFile(e);if(!t||!Array.isArray(t.history))return[];let s=t.history,n=[],i=0;for(;i<s.length;){if(s[i].message?.role!=="user"){i++;continue}let{turn:a,nextIndex:c}=this.buildTurnFromHistory(s,i);n.push(a),i=c}let r=await this.readExecutionRecordsForSession(e);if(r.length>0){let a=new Map(r.map(c=>[c.executionId,c]));for(let c of n)this.enrichTurnWithExecutionRecords(c,a)}return n}enrichTurnWithExecutionRecords(e,t){let s=e.executionIds.map(i=>t.get(i)).filter(i=>i!==void 0);if(s.length===0)return;let n=s.map(i=>i.responseText).filter(i=>i.length>0);n.length>0&&(e.assistantText=n.join(`
|
|
59
59
|
|
|
60
60
|
`)),e.toolCalls=s.flatMap(i=>i.toolCalls),e.inputTokens=s.reduce((i,r)=>i+r.inputTokens,0),e.outputTokens=s.reduce((i,r)=>i+r.outputTokens,0),e.timestampMs=s[0].startTimeMs}buildTurnFromHistory(e,t){let s={userText:this.extractUserText(e[t].message.content),assistantText:"",model:null,toolCalls:[],inputTokens:0,outputTokens:0,timestampMs:null,executionIds:[]};this.applyPromptLogs(e[t],s);let n=t+1;for(;n<e.length&&e[n].message?.role!=="user";){let i=e[n];i.message?.role==="assistant"&&(typeof i.executionId=="string"&&s.executionIds.push(i.executionId),typeof i.message.content=="string"&&i.message.content&&(s.assistantText+=(s.assistantText?`
|
|
61
61
|
|
|
62
|
-
`:"")+i.message.content),this.applyPromptLogs(i,s),this.collectToolCalls(i,s)),n++}return{turn:s,nextIndex:n}}applyPromptLogs(e,t){if(Array.isArray(e.promptLogs))for(let s of e.promptLogs)s.modelTitle&&!t.model&&(t.model=s.modelTitle),t.inputTokens+=this.estimateTokens(s.prompt||""),t.outputTokens+=this.estimateTokens(s.completion||"")}collectToolCalls(e,t){if(Array.isArray(e.message?.toolCalls))for(let s of e.message.toolCalls)t.toolCalls.push({toolName:s.function?.name||s.name||"unknown",arguments:s.function?.arguments})}};var
|
|
62
|
+
`:"")+i.message.content),this.applyPromptLogs(i,s),this.collectToolCalls(i,s)),n++}return{turn:s,nextIndex:n}}applyPromptLogs(e,t){if(Array.isArray(e.promptLogs))for(let s of e.promptLogs)s.modelTitle&&!t.model&&(t.model=s.modelTitle),t.inputTokens+=this.estimateTokens(s.prompt||""),t.outputTokens+=this.estimateTokens(s.completion||"")}collectToolCalls(e,t){if(Array.isArray(e.message?.toolCalls))for(let s of e.message.toolCalls)t.toolCalls.push({toolName:s.function?.name||s.name||"unknown",arguments:s.function?.arguments})}};var bn=S(require("fs")),fi=S(require("path")),Fc=S(require("os"));var hi=class{getKiroCliDataDir(){return fi.join(Fc.homedir(),".kiro")}getKiroCliSessionsDir(){return fi.join(this.getKiroCliDataDir(),"sessions","cli")}isKiroCliSessionFile(e){let t=X(e);return t.includes("/.kiro/sessions/cli/")&&t.endsWith(".json")}async getKiroCliSessionFiles(){let e=this.getKiroCliSessionsDir();try{await bn.promises.access(e)}catch{return[]}try{return(await bn.promises.readdir(e)).filter(s=>s.endsWith(".json")).map(s=>fi.join(e,s))}catch{return[]}}getMessageLogPath(e){return e.replace(/\.json$/,".jsonl")}async readSessionMetadata(e){let t;try{t=JSON.parse(await bn.promises.readFile(e,"utf8"))}catch{return null}let s=Array.isArray(t?.session_state?.conversation_metadata?.user_turn_metadatas)?t.session_state.conversation_metadata.user_turn_metadatas:[];return{sessionId:this.asString(t?.session_id),cwd:this.asString(t?.cwd),title:this.asString(t?.title),createdAt:this.asString(t?.created_at),updatedAt:this.asString(t?.updated_at),modelId:this.asString(t?.session_state?.rts_model_state?.model_info?.model_id),turnCount:s.length,totalCredits:this.sumMeteredCredits(s)}}asString(e){return typeof e=="string"?e:void 0}sumMeteredCredits(e){let t=0;for(let s of e)if(Array.isArray(s?.metering_usage))for(let n of s.metering_usage)typeof n?.value=="number"&&Number.isFinite(n.value)&&(t+=n.value);return t}async readSessionMessages(e){let t=this.getMessageLogPath(e),s;try{s=await bn.promises.readFile(t,"utf8")}catch{return[]}let n=[],i=s.split(/\r?\n/);for(let r=0;r<i.length;r++){let a=i[r].trim();if(!a)continue;let c;try{c=JSON.parse(a)}catch{continue}let d=this.parseMessageRecord(c,r+1);d&&n.push(d)}return n}parseMessageRecord(e,t){let s=e?.kind;if(s!=="Prompt"&&s!=="AssistantMessage"&&s!=="ToolResults")return null;let n=e.data??{},i={kind:s,text:"",toolUses:[],toolResults:[],timestampMs:this.toEpochMs(n?.meta?.timestamp),lineNumber:t};for(let r of Array.isArray(n.content)?n.content:[])this.applyContentPart(r,i);return i}applyContentPart(e,t){if(e?.kind==="text"&&typeof e.data=="string"){t.text+=(t.text?`
|
|
63
63
|
`:"")+e.data;return}if(e?.kind==="toolUse"&&e.data){t.toolUses.push({toolName:typeof e.data.name=="string"?e.data.name:"unknown",arguments:e.data.input!==void 0?this.safeStringify(e.data.input):void 0});return}e?.kind==="toolResult"&&e.data&&t.toolResults.push({toolUseId:typeof e.data.toolUseId=="string"?e.data.toolUseId:"",text:this.extractToolResultText(e.data)})}extractToolResultText(e){let t=[];for(let s of Array.isArray(e.content)?e.content:[])s?.kind==="text"&&typeof s.data=="string"&&t.push(s.data);return t.join(`
|
|
64
|
-
`)}toEpochMs(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:e*1e3}safeStringify(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}estimateTokens(e){return e?Math.ceil(e.length/4):0}async getTokensFromKiroCliSession(e){let{inputTokens:t,outputTokens:s}=await this.estimateSessionTokens(e);return{tokens:t+s,thinkingTokens:0}}async estimateSessionTokens(e){let t=await this.readSessionMessages(e),s=0,n=0;for(let i of t)if(i.kind==="AssistantMessage"){n+=this.estimateTokens(i.text);for(let r of i.toolUses)n+=this.estimateTokens(r.arguments??"")}else{s+=this.estimateTokens(i.text);for(let r of i.toolResults)s+=this.estimateTokens(r.text)}return{inputTokens:s,outputTokens:n}}async countKiroCliInteractions(e){let s=(await this.readSessionMessages(e)).filter(i=>i.kind==="Prompt").length;return s>0?s:(await this.readSessionMetadata(e))?.turnCount??0}async getKiroCliModelUsage(e){let t=await this.readSessionMetadata(e),{inputTokens:s,outputTokens:n}=await this.estimateSessionTokens(e);return s===0&&n===0?{}:{[t?.modelId||"unknown"]:{inputTokens:s,outputTokens:n}}}async getKiroCliSessionMeta(e){let t=await this.readSessionMetadata(e);return{title:t?.title,firstInteraction:this.toIsoString(t?.createdAt),lastInteraction:this.toIsoString(t?.updatedAt),workspacePath:t?.cwd}}toIsoString(e){if(!e)return null;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():null}async getKiroCliDailyFractions(e){let s=(await this.readSessionMessages(e)).filter(r=>r.kind==="Prompt"&&r.timestampMs!==null).map(r=>L(new Date(r.timestampMs)));if(s.length===0){let r=await this.readSessionMetadata(e),a=r?.createdAt?Date.parse(r.createdAt):NaN;return{[Number.isFinite(a)?L(new Date(a)):L(new Date)]:1}}let n=new Map;for(let r of s)n.set(r,(n.get(r)??0)+1);let i={};for(let[r,a]of n.entries())i[r]=a/s.length;return i}async buildKiroCliTurns(e){let t=await this.readSessionMessages(e),s=[],n=null;for(let i of t){if(i.kind==="Prompt"){n={userText:i.text,assistantText:"",toolCalls:[],timestampMs:i.timestampMs,inputTokens:this.estimateTokens(i.text),outputTokens:0},s.push(n);continue}n&&(i.kind==="AssistantMessage"?this.applyAssistantRecordToTurn(i,n):this.applyToolResultsToTurn(i,n))}return s}applyAssistantRecordToTurn(e,t){e.text&&(t.assistantText+=(t.assistantText?`
|
|
64
|
+
`)}toEpochMs(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:e*1e3}safeStringify(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}estimateTokens(e){return e?Math.ceil(e.length/4):0}async getTokensFromKiroCliSession(e){let{inputTokens:t,outputTokens:s}=await this.estimateSessionTokens(e);return{tokens:t+s,thinkingTokens:0}}async estimateSessionTokens(e){let t=await this.readSessionMessages(e),s=0,n=0;for(let i of t)if(i.kind==="AssistantMessage"){n+=this.estimateTokens(i.text);for(let r of i.toolUses)n+=this.estimateTokens(r.arguments??"")}else{s+=this.estimateTokens(i.text);for(let r of i.toolResults)s+=this.estimateTokens(r.text)}return{inputTokens:s,outputTokens:n}}async countKiroCliInteractions(e){let s=(await this.readSessionMessages(e)).filter(i=>i.kind==="Prompt").length;return s>0?s:(await this.readSessionMetadata(e))?.turnCount??0}async getKiroCliModelUsage(e){let t=await this.readSessionMetadata(e),{inputTokens:s,outputTokens:n}=await this.estimateSessionTokens(e);return s===0&&n===0?{}:{[t?.modelId||"unknown"]:{inputTokens:s,outputTokens:n,sessions:0}}}async getKiroCliSessionMeta(e){let t=await this.readSessionMetadata(e);return{title:t?.title,firstInteraction:this.toIsoString(t?.createdAt),lastInteraction:this.toIsoString(t?.updatedAt),workspacePath:t?.cwd}}toIsoString(e){if(!e)return null;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():null}async getKiroCliDailyFractions(e){let s=(await this.readSessionMessages(e)).filter(r=>r.kind==="Prompt"&&r.timestampMs!==null).map(r=>L(new Date(r.timestampMs)));if(s.length===0){let r=await this.readSessionMetadata(e),a=r?.createdAt?Date.parse(r.createdAt):NaN;return{[Number.isFinite(a)?L(new Date(a)):L(new Date)]:1}}let n=new Map;for(let r of s)n.set(r,(n.get(r)??0)+1);let i={};for(let[r,a]of n.entries())i[r]=a/s.length;return i}async buildKiroCliTurns(e){let t=await this.readSessionMessages(e),s=[],n=null;for(let i of t){if(i.kind==="Prompt"){n={userText:i.text,assistantText:"",toolCalls:[],timestampMs:i.timestampMs,inputTokens:this.estimateTokens(i.text),outputTokens:0},s.push(n);continue}n&&(i.kind==="AssistantMessage"?this.applyAssistantRecordToTurn(i,n):this.applyToolResultsToTurn(i,n))}return s}applyAssistantRecordToTurn(e,t){e.text&&(t.assistantText+=(t.assistantText?`
|
|
65
65
|
|
|
66
|
-
`:"")+e.text,t.outputTokens+=this.estimateTokens(e.text));for(let s of e.toolUses)t.toolCalls.push({toolName:s.toolName,arguments:s.arguments}),t.outputTokens+=this.estimateTokens(s.arguments??"")}applyToolResultsToTurn(e,t){for(let s of e.toolResults){t.inputTokens+=this.estimateTokens(s.text);let n=[...t.toolCalls].reverse().find(i=>i.result===void 0);n&&(n.result=s.text)}}};var
|
|
66
|
+
`:"")+e.text,t.outputTokens+=this.estimateTokens(e.text));for(let s of e.toolUses)t.toolCalls.push({toolName:s.toolName,arguments:s.arguments}),t.outputTokens+=this.estimateTokens(s.arguments??"")}applyToolResultsToTurn(e,t){for(let s of e.toolResults){t.inputTokens+=this.estimateTokens(s.text);let n=[...t.toolCalls].reverse().find(i=>i.result===void 0);n&&(n.result=s.text)}}};var kn=S(require("fs")),Bt=S(require("path")),_i=S(require("os")),Nc=S(Nt());var rf="devin/cli/sessions.db#";function yi(o,e){for(let t of e){let s=o[t];if(typeof s=="number"&&Number.isFinite(s)&&s!==0)return s}return 0}var Ci=class{_sqlJsModule=null;_sqlJsInitPromise=null;_dbCache=new Map;_dbCacheInflight=new Map;_dbPathOverride=null;dispose(){for(let e of this._dbCache.values())try{e.db.close()}catch{}this._dbCache.clear(),this._dbCacheInflight.clear(),this._sqlJsInitPromise=null}getConfigDir(){if(process.platform==="win32"){let s=process.env.APPDATA||Bt.join(_i.homedir(),"AppData","Roaming");return Bt.join(s,"devin","cli")}if(process.platform==="darwin")return Bt.join(_i.homedir(),"Library","Application Support","devin","cli");let e=process.env.XDG_DATA_HOME,t=e&&e.trim()?e:Bt.join(_i.homedir(),".local","share");return Bt.join(t,"devin","cli")}getDbPath(){return this._dbPathOverride??Bt.join(this.getConfigDir(),"sessions.db")}setDbPathOverrideForTests(e){this._dbPathOverride=e}virtualPath(e){return`${this.getDbPath()}#${e}`}isDevinCliSessionFile(e){return e.replace(/\\/g,"/").toLowerCase().includes(rf)}getDbPathFromVirtual(e){let t=e.lastIndexOf("sessions.db#");return t===-1?e:e.substring(0,t+11)}getSessionId(e){let t=e.lastIndexOf("sessions.db#");return t===-1?null:e.substring(t+12)||null}async statSessionFile(e){return kn.promises.stat(this.getDbPathFromVirtual(e))}closeDb(e){try{e.close()}catch{}}isMissingFileError(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async statDb(e){try{return await kn.promises.stat(e)}catch(t){return this.isMissingFileError(t)&&this._dbCache.has(e)&&(this.closeDb(this._dbCache.get(e).db),this._dbCache.delete(e)),null}}isCachedDbCurrent(e,t){let s=this._dbCache.get(e);return!!s&&s.mtimeMs===t.mtimeMs&&s.size===t.size}sameDbStats(e,t){return e.mtimeMs===t.mtimeMs&&e.size===t.size}async refreshDb(e,t){let s;try{let r=await this.initSqlJs(),a=await kn.promises.readFile(e);s=new r.Database(a)}catch{return this._dbCache.get(e)?.db??null}let n=await this.statDb(e);if(!n||!this.sameDbStats(t,n))return this.closeDb(s),this._dbCache.get(e)?.db??null;let i=this._dbCache.get(e);return i&&this.closeDb(i.db),this._dbCache.set(e,{db:s,mtimeMs:t.mtimeMs,size:t.size}),s}async getDb(e){let t=await this.statDb(e);if(!t)return this._dbCache.get(e)?.db??null;if(this.isCachedDbCurrent(e,t))return this._dbCache.get(e).db;let s=`${e}:${t.mtimeMs}:${t.size}`,n=this._dbCacheInflight.get(s);if(n)return n;let i=this.refreshDb(e,t);this._dbCacheInflight.set(s,i);try{return await i}finally{this._dbCacheInflight.get(s)===i&&this._dbCacheInflight.delete(s)}}async initSqlJs(){return this._sqlJsModule?this._sqlJsModule:(this._sqlJsInitPromise||(this._sqlJsInitPromise=(async()=>{let e=Bt.join(__dirname,"sql-wasm.wasm"),t;try{t=await kn.promises.readFile(e)}catch{}let s=await(0,Nc.default)(t?{wasmBinary:t.buffer}:void 0);return this._sqlJsModule=s,s})().catch(e=>{throw this._sqlJsInitPromise=null,e})),this._sqlJsInitPromise)}rowsToObjects(e){if(e.length===0)return[];let{columns:t,values:s}=e[0];return s.map(n=>{let i={};return t.forEach((r,a)=>{i[r]=n[a]}),i})}async discoverSessionIds(){let e=this.getDbPath(),t=await this.getDb(e);if(!t)return[];try{let s=t.exec("SELECT id FROM sessions WHERE hidden = 0 OR hidden IS NULL ORDER BY last_activity_at DESC");return this.rowsToObjects(s).map(n=>n.id)}catch{try{let s=t.exec("SELECT id FROM sessions ORDER BY last_activity_at DESC");return this.rowsToObjects(s).map(n=>n.id)}catch{return[]}}}async readSession(e){let t=this.getDbPathFromVirtual(e),s=this.getSessionId(e);if(!s)return null;let n=await this.getDb(t);if(!n)return null;try{let i=n.exec(`SELECT id, working_directory, backend_type, model, agent_mode, created_at,
|
|
67
67
|
last_activity_at, title, main_chain_id, cogs_json, hidden
|
|
68
68
|
FROM sessions WHERE id = ?`,[s]),r=this.rowsToObjects(i);return r.length===0?null:r[0]}catch{return null}}async getMessageNodes(e){let t=this.getDbPathFromVirtual(e),s=this.getSessionId(e);if(!s)return[];let n=await this.getDb(t);if(!n)return[];try{let i=n.exec(`SELECT row_id, session_id, node_id, parent_node_id, chat_message, created_at, metadata
|
|
69
69
|
FROM message_nodes WHERE session_id = ? ORDER BY created_at ASC`,[s]);return this.rowsToObjects(i)}catch{return[]}}async getToolCalls(e){let t=this.getDbPathFromVirtual(e),s=this.getSessionId(e);if(!s)return[];let n=await this.getDb(t);if(!n)return[];try{let i=n.exec(`SELECT session_id, tool_call_id, tool_call_json, tool_call_update_json
|
|
70
70
|
FROM tool_call_state WHERE session_id = ?`,[s]);return this.rowsToObjects(i)}catch{return[]}}buildMainChain(e,t){if(e.length===0)return[];if(t==null)return[...e].sort((a,c)=>(a.created_at??0)-(c.created_at??0));let s=new Map;for(let a of e)s.set(a.node_id,a);let n=[],i=s.get(t),r=new Set;for(;i&&!r.has(i.node_id);)r.add(i.node_id),n.push(i),i=i.parent_node_id!==null?s.get(i.parent_node_id):void 0;return n.length===0?[...e].sort((a,c)=>(a.created_at??0)-(c.created_at??0)):n.reverse()}parseChatMessage(e){if(!e)return{role:"unknown",text:""};let t;try{t=JSON.parse(e)}catch{return{role:"unknown",text:e}}if(typeof t!="object"||t===null)return{role:"unknown",text:""};let s=t;return{role:this.extractRole(s),text:this.extractText(s)}}extractRole(e){let t=e.role;if(t==="user"||t==="assistant"||t==="tool")return t;let s=e.sessionUpdate??e.session_update;if(typeof s=="string"){if(s.startsWith("user_message"))return"user";if(s.startsWith("agent_message"))return"assistant";if(s.includes("tool_call"))return"tool"}return"unknown"}extractText(e){let t=e.content;return typeof t=="string"?t:Array.isArray(t)?t.filter(s=>typeof s=="object"&&s!==null).filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join(`
|
|
71
|
-
`):typeof e.text=="string"?e.text:""}estimateTokens(e){return e?Math.ceil(e.length/4):0}extractCogsTokens(e){let t=this.parseJsonObject(e);if(!t)return null;let s=pi(t,["input_tokens","prompt_tokens","inputTokens"]),n=pi(t,["output_tokens","completion_tokens","outputTokens"]),i=pi(t,["reasoning_tokens","thinking_tokens","reasoningTokens"]);if(s===0&&n===0&&i===0){let r=pi(t,["used","total_tokens","tokens_used"]);return r>0?{input:r,output:0,thinking:0}:null}return{input:s,output:n,thinking:i}}parseJsonObject(e){if(!e)return null;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null?t:null}catch{return null}}async getTokens(e){let t=await this.readSession(e),s=this.extractCogsTokens(t?.cogs_json??null);if(s)return{tokens:s.input+s.output+s.thinking,thinkingTokens:s.thinking};let n=await this.getMessageNodes(e),i=0;for(let r of n){let a=this.parseChatMessage(r.chat_message);i+=this.estimateTokens(a.text)}return{tokens:i,thinkingTokens:0}}async countInteractions(e){let t=await this.getMessageNodes(e),s=0;for(let n of t)this.parseChatMessage(n.chat_message).role==="user"&&s++;return s>0?s:this.countPromptHistory(e)}async countPromptHistory(e){let t=this.getDbPathFromVirtual(e),s=this.getSessionId(e);if(!s)return 0;let n=await this.getDb(t);if(!n)return 0;try{let i=n.exec("SELECT COUNT(*) as c FROM prompt_history WHERE session_id = ?",[s]),r=this.rowsToObjects(i);return r.length>0&&r[0].c||0}catch{return 0}}async getModelUsage(e){let s=(await this.readSession(e))?.model||"unknown",n=await this.getMessageNodes(e),i={[s]:{inputTokens:0,outputTokens:0}};for(let r of n){let a=this.parseChatMessage(r.chat_message),c=this.estimateTokens(a.text);a.role==="user"?i[s].inputTokens+=c:a.role==="assistant"&&(i[s].outputTokens+=c)}return i}async getDailyFractions(e){let t=await this.getMessageNodes(e),s={},n=0;for(let r of t){if(!r.created_at)continue;let a=L(new Date(r.created_at*1e3));s[a]=(s[a]||0)+1,n++}if(n===0){let r=await this.readSession(e);return{[r?.last_activity_at?L(new Date(r.last_activity_at*1e3)):L(new Date)]:1}}let i={};for(let[r,a]of Object.entries(s))i[r]=a/n;return i}};var Fs=w(require("fs")),at=w(require("path"));var je=w(require("fs")),le=w(require("path")),wn=w(require("os"));var Jg=/\/partition-\d+\.jsonl$/,Vg=["embeddings","index","cache","preferences","settings","config","workspacesessions","globalsessions","api.json"];function Ec(o){let e=o.toLowerCase();return Vg.some(t=>e.includes(t))}function hi(o){let e=de(o);return e.includes("/.copilot/jb/")&&Jg.test(e)}var Rc=w(require("fs"));async function Mt(o){try{return await Rc.promises.access(o),!0}catch{return!1}}var kn=["Code","Code - Insiders","Code - Exploration","VSCodium","Cursor"],Uc=new Set(["Public","Default","Default User","All Users"]);function Xr(){return wn.platform()==="linux"&&(typeof process.env.WSL_DISTRO_NAME=="string"||typeof process.env.WSL_INTEROP=="string")}function yi(){let o=wn.platform(),e=wn.homedir(),t=[];if(o==="win32"){let s=process.env.APPDATA||le.join(e,"AppData","Roaming");for(let n of kn)t.push(le.join(s,n,"User"))}else if(o==="darwin")for(let s of kn)t.push(le.join(e,"Library","Application Support",s,"User"));else{let s=process.env.XDG_CONFIG_HOME||le.join(e,".config");for(let n of kn)t.push(le.join(s,n,"User"))}return t.push(le.join(e,".vscode-server","data","User"),le.join(e,".vscode-server-insiders","data","User"),le.join(e,".vscode-remote","data","User"),le.join("/tmp",".vscode-server","data","User"),le.join("/workspace",".vscode-server","data","User")),t}async function Kg(){if(!Xr())return[];let o=[],e=[],t=process.env.USERPROFILE;if(t){let n=t.match(/^\/mnt\/[a-z]\/Users\/([^/]+)/);n&&e.push(n[1])}let s="/mnt/c/Users";try{let n=await je.promises.readdir(s,{withFileTypes:!0});for(let i of n){if(!i.isDirectory())continue;let r=i.name;Uc.has(r)||r.startsWith(".")||e.includes(r)||e.push(r)}}catch{return[]}for(let n of e){let i=le.join(s,n,"AppData","Roaming");for(let r of kn)o.push(le.join(i,r,"User"))}return o}function Qg(){if(!Xr())return[];let o=[],e="/mnt/c/Users";try{let t=je.readdirSync(e,{withFileTypes:!0});for(let s of t)if(!(!s.isDirectory()||s.name.startsWith(".")||Uc.has(s.name)))for(let n of kn)o.push(le.join(e,s.name,"AppData","Roaming",n,"User"))}catch{}return o}async function Ic(o,e,t,s){if(o.length===0)return;let n=0,i=Array.from({length:Math.min(t,o.length)},async()=>{for(;n<o.length;){let r=n++;try{await e(o[r],r)}catch(a){s?.(o[r],r,a)}}});await Promise.all(i)}async function Oc(o,e,t){let s;try{s=await je.promises.readdir(o,{withFileTypes:!0})}catch(n){t(`Could not scan directory ${o}: ${n}`);return}for(let n of s){let i=le.join(o,n.name);if(n.isDirectory()){await Oc(i,e,t);continue}if(!(!n.name.endsWith(".json")&&!n.name.endsWith(".jsonl"))&&!Ec(n.name))try{(await je.promises.stat(i)).size>0&&e.push(i)}catch{}}}var Sn=class{id="copilotchat";displayName="GitHub Copilot Chat";handles(e){return!1}getBackingPath(e){return e}async stat(e){return je.promises.stat(e)}async getTokens(e){try{let t=await je.promises.readFile(e,"utf8");return xs(t)?{tokens:0,thinkingTokens:0,actualTokens:0}:e.endsWith(".jsonl")||bt(t)?Lo(t):{tokens:0,thinkingTokens:0,actualTokens:0}}catch{return{tokens:0,thinkingTokens:0,actualTokens:0}}}async countInteractions(e){return 0}async getModelUsage(e){return{}}async getMeta(e){return{title:void 0,firstInteraction:null,lastInteraction:null}}getEditorRoot(e){let t=de(e),s=t.lastIndexOf("/User/");return s>=0?t.substring(0,s+5):le.dirname(e)}getCandidatePaths(){let e=[];for(let t of yi())e.push({path:t,source:"VS Code"});for(let t of Qg())e.push({path:t,source:"VS Code (Windows via WSL)"});return e}async discover(e){let t=this.getCandidatePaths(),s=[],n=await this.resolveAllVSCodePaths(e);e(`\u{1F4C2} Considering ${n.length} candidate VS Code paths`);let i=await Promise.all(n.map(a=>Mt(a).catch(()=>!1))),r=n.filter((a,c)=>i[c]);return e(`\u2705 Found ${r.length} of ${n.length} VS Code paths exist on disk`),await Ic(r,async a=>{let c=le.basename(le.dirname(a));await this.scanWorkspaceStorage(a,c,s,e),await this.scanGlobalStorage(a,c,s,e)},4,(a,c,m)=>{e(`Failed to scan VS Code user path ${a}: ${m instanceof Error?m.message:String(m)}`)}),{sessionFiles:s,candidatePaths:t}}async resolveAllVSCodePaths(e){let t=yi();if(Xr()){e("\u{1FA9F} WSL environment detected \u2014 probing Windows-side VS Code paths");let s=await Kg();s.length>0?(e(`\u{1FA9F} Adding ${s.length} Windows-side candidate paths from WSL`),t.push(...s)):e("\u{1FA9F} No Windows-side paths found (Windows drive may not be mounted)")}return t}async scanWorkspaceStorage(e,t,s,n){let i=le.join(e,"workspaceStorage"),r;try{r=await je.promises.readdir(i)}catch{return}let a=["GitHub.copilot-chat","github.copilot-chat","GitHub.copilot","github.copilot"],c=["chatSessions","debug-logs","transcripts"],m=async f=>{try{let h=(await je.promises.readdir(f)).filter(_=>_.endsWith(".json")||_.endsWith(".jsonl")).map(_=>le.join(f,_));h.length>0&&s.push(...h)}catch{}},p=0;await Ic(r,async f=>{let h=le.join(i,f),_;try{_=await je.promises.readdir(h)}catch{return}let C=new Set(_),S=s.length;C.has("chatSessions")&&await m(le.join(h,"chatSessions"));for(let E of a)if(C.has(E))for(let A of c)await m(le.join(h,E,A));s.length>S&&p++},8),p>0&&n(`\u{1F4C2} ${t}: found sessions in ${p}/${r.length} workspace dir(s)`)}async scanGlobalStorage(e,t,s,n){try{let i=le.join(e,"globalStorage","emptyWindowChatSessions"),r=(await je.promises.readdir(i)).filter(a=>a.endsWith(".json")||a.endsWith(".jsonl")).map(a=>le.join(i,a));r.length>0&&s.push(...r)}catch{}for(let i of["GitHub.copilot-chat","github.copilot-chat","GitHub.copilot","github.copilot"]){let r=le.join(e,"globalStorage",i);try{await je.promises.access(r),await Oc(r,s,n)}catch{}}}};var _i="saoudrizwan.claude-dev",Fc=new Set(["task","user_feedback"]),Ci=class{_uiMessagesCache=new Map;getClineStorageDirs(){return yi().map(e=>at.join(e,"globalStorage",_i))}getClineTasksDirs(){return this.getClineStorageDirs().map(e=>at.join(e,"tasks"))}isClineSessionFile(e){let t=Y(e);return t.includes(`/${_i}/tasks/`)&&t.endsWith("/ui_messages.json")}getClineRootFromSessionFile(e){let s=e.replace(/\\/g,"/").toLowerCase().indexOf(`/${_i}/`.toLowerCase());return s!==-1?e.slice(0,s+1+_i.length):this.getClineStorageDirs()[0]}async getClineSessionFiles(){let e=[];for(let t of this.getClineTasksDirs()){let s;try{s=await Fs.promises.readdir(t,{withFileTypes:!0})}catch{continue}for(let n of s){if(!n.isDirectory())continue;let i=at.join(t,n.name,"ui_messages.json");try{await Fs.promises.access(i),e.push(i)}catch{}}}return e}async readUiMessages(e){let t;try{t=await Fs.promises.stat(e)}catch{return[]}let s=this._uiMessagesCache.get(e);if(s&&s.mtimeMs===t.mtimeMs)return s.parsed;let n=[];try{let i=JSON.parse(await Fs.promises.readFile(e,"utf8"));Array.isArray(i)&&(n=i)}catch{}return this._uiMessagesCache.set(e,{mtimeMs:t.mtimeMs,parsed:n}),n}async getApiRequests(e){let t=await this.readUiMessages(e),s=[];for(let n of t){if(n.say!=="api_req_started"||typeof n.text!="string")continue;let i;try{i=JSON.parse(n.text)}catch{continue}typeof i?.tokensIn!="number"&&typeof i?.tokensOut!="number"||s.push({ts:typeof n.ts=="number"?n.ts:null,tokensIn:this.asNumber(i.tokensIn),tokensOut:this.asNumber(i.tokensOut),cacheWrites:this.asNumber(i.cacheWrites),cacheReads:this.asNumber(i.cacheReads),cost:this.asNumber(i.cost),model:n.modelInfo?.modelId??null,mode:n.modelInfo?.mode??null})}return s}async readTaskHistoryEntry(e){let t=at.basename(at.dirname(e)),s=at.join(this.getClineRootFromSessionFile(e),"state","taskHistory.json");try{let n=JSON.parse(await Fs.promises.readFile(s,"utf8"));return Array.isArray(n)?n.find(i=>i?.id===t):void 0}catch{return}}requestInputTokens(e){return e.tokensIn+e.cacheWrites+e.cacheReads}async getTokensFromClineSession(e){let t=await this.getApiRequests(e);if(t.length>0){let n=0;for(let i of t)n+=this.requestInputTokens(i)+i.tokensOut;return{tokens:n,thinkingTokens:0}}let s=await this.readTaskHistoryEntry(e);return s?{tokens:this.asNumber(s.tokensIn)+this.asNumber(s.tokensOut)+this.asNumber(s.cacheWrites)+this.asNumber(s.cacheReads),thinkingTokens:0}:{tokens:0,thinkingTokens:0}}async countClineInteractions(e){return(await this.readUiMessages(e)).filter(s=>s.type==="say"&&Fc.has(s.say??"")).length}async getClineModelUsage(e){let t=await this.getApiRequests(e),s={};if(t.length>0){for(let i of t)this.addRequestToModelUsage(s,i.model??"unknown",this.requestInputTokens(i),i.tokensOut,i.cacheReads,i.cacheWrites);return s}let n=await this.readTaskHistoryEntry(e);if(n){let i=this.asNumber(n.cacheReads),r=this.asNumber(n.cacheWrites),a=this.asNumber(n.tokensIn)+i+r;this.addRequestToModelUsage(s,n.modelId??"unknown",a,this.asNumber(n.tokensOut),i,r)}return s}addRequestToModelUsage(e,t,s,n,i,r){e[t]||(e[t]={inputTokens:0,outputTokens:0}),e[t].inputTokens+=s,e[t].outputTokens+=n,i>0&&(e[t].cachedReadTokens=(e[t].cachedReadTokens??0)+i),r>0&&(e[t].cacheCreationTokens=(e[t].cacheCreationTokens??0)+r)}async getClineSessionMeta(e){let t=await this.readUiMessages(e),s=await this.readTaskHistoryEntry(e),n=t.find(a=>typeof a.ts=="number")?.ts??this.taskIdToEpochMs(e),i;for(let a of t)typeof a.ts=="number"&&(i=a.ts);let r=t.find(a=>a.say==="task");return{title:s?.task??r?.text??void 0,firstInteraction:n!==void 0?new Date(n).toISOString():null,lastInteraction:i!==void 0?new Date(i).toISOString():n!==void 0?new Date(n).toISOString():null,workspacePath:s?.cwdOnTaskInitialization}}taskIdToEpochMs(e){let t=at.basename(at.dirname(e)),s=Number(t);if(Number.isFinite(s)&&s>9466848e5&&s<41024448e5)return s}async getClineDailyFractions(e){let t=await this.getApiRequests(e),s=t.reduce((r,a)=>r+this.requestInputTokens(a)+a.tokensOut,0);if(t.length===0||s===0){let r=await this.getClineSessionMeta(e),a=r.firstInteraction?Date.parse(r.firstInteraction):NaN;return{[Number.isFinite(a)?L(new Date(a)):L(new Date)]:1}}let n=new Map;for(let r of t){let a=r.ts!==null?L(new Date(r.ts)):L(new Date);n.set(a,(n.get(a)??0)+this.requestInputTokens(r)+r.tokensOut)}let i={};for(let[r,a]of n.entries())i[r]=a/s;return i}async buildClineTurns(e){let t=await this.readUiMessages(e),s=[],n=null;for(let i of t){let r=i.say??i.ask??"";if(i.type==="say"&&Fc.has(r)){n=this.newTurn(i),s.push(n);continue}n||(n=this.newTurn(void 0),s.push(n)),this.applyMessageToTurn(n,i,r)}return s}newTurn(e){return{userText:e?.text??"",assistantText:"",model:e?.modelInfo?.modelId??null,mode:e?.modelInfo?.mode??null,toolCalls:[],mcpTools:[],inputTokens:0,outputTokens:0,timestampMs:typeof e?.ts=="number"?e.ts:null}}applyMessageToTurn(e,t,s){switch(s){case"api_req_started":this.applyApiRequestToTurn(e,t);break;case"text":case"completion_result":this.appendAssistantText(e,t.text);break;case"tool":this.applyToolMessageToTurn(e,t);break;case"command":e.toolCalls.push({toolName:"executeCommand",arguments:t.text});break;case"command_output":{let n=e.toolCalls[e.toolCalls.length-1];n&&n.toolName==="executeCommand"&&(n.result=t.text);break}case"use_mcp_server":this.applyMcpMessageToTurn(e,t);break;case"browser_action_launch":case"browser_action":e.toolCalls.push({toolName:"browserAction",arguments:t.text});break;default:break}}applyApiRequestToTurn(e,t){if(t.modelInfo?.modelId&&(e.model=t.modelInfo.modelId),t.modelInfo?.mode&&(e.mode=t.modelInfo.mode),typeof t.text=="string")try{let s=JSON.parse(t.text);e.inputTokens+=this.asNumber(s?.tokensIn)+this.asNumber(s?.cacheWrites)+this.asNumber(s?.cacheReads),e.outputTokens+=this.asNumber(s?.tokensOut)}catch{}}appendAssistantText(e,t){if(!t)return;let s=t.indexOf("<tool_call>"),n=(s!==-1?t.slice(0,s):t).trim();n&&(e.assistantText+=(e.assistantText?`
|
|
71
|
+
`):typeof e.text=="string"?e.text:""}estimateTokens(e){return e?Math.ceil(e.length/4):0}extractCogsTokens(e){let t=this.parseJsonObject(e);if(!t)return null;let s=yi(t,["input_tokens","prompt_tokens","inputTokens"]),n=yi(t,["output_tokens","completion_tokens","outputTokens"]),i=yi(t,["reasoning_tokens","thinking_tokens","reasoningTokens"]);if(s===0&&n===0&&i===0){let r=yi(t,["used","total_tokens","tokens_used"]);return r>0?{input:r,output:0,thinking:0}:null}return{input:s,output:n,thinking:i}}parseJsonObject(e){if(!e)return null;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null?t:null}catch{return null}}async getTokens(e){let t=await this.readSession(e),s=this.extractCogsTokens(t?.cogs_json??null);if(s)return{tokens:s.input+s.output+s.thinking,thinkingTokens:s.thinking};let n=await this.getMessageNodes(e),i=0;for(let r of n){let a=this.parseChatMessage(r.chat_message);i+=this.estimateTokens(a.text)}return{tokens:i,thinkingTokens:0}}async countInteractions(e){let t=await this.getMessageNodes(e),s=0;for(let n of t)this.parseChatMessage(n.chat_message).role==="user"&&s++;return s>0?s:this.countPromptHistory(e)}async countPromptHistory(e){let t=this.getDbPathFromVirtual(e),s=this.getSessionId(e);if(!s)return 0;let n=await this.getDb(t);if(!n)return 0;try{let i=n.exec("SELECT COUNT(*) as c FROM prompt_history WHERE session_id = ?",[s]),r=this.rowsToObjects(i);return r.length>0&&r[0].c||0}catch{return 0}}async getModelUsage(e){let s=(await this.readSession(e))?.model||"unknown",n=await this.getMessageNodes(e),i={[s]:{inputTokens:0,outputTokens:0,sessions:0}};for(let r of n){let a=this.parseChatMessage(r.chat_message),c=this.estimateTokens(a.text);a.role==="user"?i[s].inputTokens+=c:a.role==="assistant"&&(i[s].outputTokens+=c)}return i}async getDailyFractions(e){let t=await this.getMessageNodes(e),s={},n=0;for(let r of t){if(!r.created_at)continue;let a=L(new Date(r.created_at*1e3));s[a]=(s[a]||0)+1,n++}if(n===0){let r=await this.readSession(e);return{[r?.last_activity_at?L(new Date(r.last_activity_at*1e3)):L(new Date)]:1}}let i={};for(let[r,a]of Object.entries(s))i[r]=a/n;return i}};var Us=S(require("fs")),at=S(require("path"));var je=S(require("fs")),ce=S(require("path")),wn=S(require("os"));var af=/\/partition-\d+\.jsonl$/,lf=["embeddings","index","cache","preferences","settings","config","workspacesessions","globalsessions","api.json"];function Lc(o){let e=o.toLowerCase();return lf.some(t=>e.includes(t))}function bi(o){let e=me(o);return e.includes("/.copilot/jb/")&&af.test(e)}var jc=S(require("fs"));async function Mt(o){try{return await jc.promises.access(o),!0}catch{return!1}}var Sn=["Code","Code - Insiders","Code - Exploration","VSCodium","Cursor"],qc=new Set(["Public","Default","Default User","All Users"]);function ia(){return wn.platform()==="linux"&&(typeof process.env.WSL_DISTRO_NAME=="string"||typeof process.env.WSL_INTEROP=="string")}function ki(){let o=wn.platform(),e=wn.homedir(),t=[];if(o==="win32"){let s=process.env.APPDATA||ce.join(e,"AppData","Roaming");for(let n of Sn)t.push(ce.join(s,n,"User"))}else if(o==="darwin")for(let s of Sn)t.push(ce.join(e,"Library","Application Support",s,"User"));else{let s=process.env.XDG_CONFIG_HOME||ce.join(e,".config");for(let n of Sn)t.push(ce.join(s,n,"User"))}return t.push(ce.join(e,".vscode-server","data","User"),ce.join(e,".vscode-server-insiders","data","User"),ce.join(e,".vscode-remote","data","User"),ce.join("/tmp",".vscode-server","data","User"),ce.join("/workspace",".vscode-server","data","User")),t}async function cf(){if(!ia())return[];let o=[],e=[],t=process.env.USERPROFILE;if(t){let n=t.match(/^\/mnt\/[a-z]\/Users\/([^/]+)/);n&&e.push(n[1])}let s="/mnt/c/Users";try{let n=await je.promises.readdir(s,{withFileTypes:!0});for(let i of n){if(!i.isDirectory())continue;let r=i.name;qc.has(r)||r.startsWith(".")||e.includes(r)||e.push(r)}}catch{return[]}for(let n of e){let i=ce.join(s,n,"AppData","Roaming");for(let r of Sn)o.push(ce.join(i,r,"User"))}return o}function uf(){if(!ia())return[];let o=[],e="/mnt/c/Users";try{let t=je.readdirSync(e,{withFileTypes:!0});for(let s of t)if(!(!s.isDirectory()||s.name.startsWith(".")||qc.has(s.name)))for(let n of Sn)o.push(ce.join(e,s.name,"AppData","Roaming",n,"User"))}catch{}return o}async function Gc(o,e,t,s){if(o.length===0)return;let n=0,i=Array.from({length:Math.min(t,o.length)},async()=>{for(;n<o.length;){let r=n++;try{await e(o[r],r)}catch(a){s?.(o[r],r,a)}}});await Promise.all(i)}async function Bc(o,e,t){let s;try{s=await je.promises.readdir(o,{withFileTypes:!0})}catch(n){t(`Could not scan directory ${o}: ${n}`);return}for(let n of s){let i=ce.join(o,n.name);if(n.isDirectory()){await Bc(i,e,t);continue}if(!(!n.name.endsWith(".json")&&!n.name.endsWith(".jsonl"))&&!Lc(n.name))try{(await je.promises.stat(i)).size>0&&e.push(i)}catch{}}}var Tn=class{id="copilotchat";displayName="GitHub Copilot Chat";handles(e){return!1}getBackingPath(e){return e}async stat(e){return je.promises.stat(e)}async getTokens(e){try{let t=await je.promises.readFile(e,"utf8");return vs(t)?{tokens:0,thinkingTokens:0,actualTokens:0}:e.endsWith(".jsonl")||bt(t)?Bo(t):{tokens:0,thinkingTokens:0,actualTokens:0}}catch{return{tokens:0,thinkingTokens:0,actualTokens:0}}}async countInteractions(e){return 0}async getModelUsage(e){return{}}async getMeta(e){return{title:void 0,firstInteraction:null,lastInteraction:null}}getEditorRoot(e){let t=me(e),s=t.lastIndexOf("/User/");return s>=0?t.substring(0,s+5):ce.dirname(e)}getCandidatePaths(){let e=[];for(let t of ki())e.push({path:t,source:"VS Code"});for(let t of uf())e.push({path:t,source:"VS Code (Windows via WSL)"});return e}async discover(e){let t=this.getCandidatePaths(),s=[],n=await this.resolveAllVSCodePaths(e);e(`\u{1F4C2} Considering ${n.length} candidate VS Code paths`);let i=await Promise.all(n.map(a=>Mt(a).catch(()=>!1))),r=n.filter((a,c)=>i[c]);return e(`\u2705 Found ${r.length} of ${n.length} VS Code paths exist on disk`),await Gc(r,async a=>{let c=ce.basename(ce.dirname(a));await this.scanWorkspaceStorage(a,c,s,e),await this.scanGlobalStorage(a,c,s,e)},4,(a,c,d)=>{e(`Failed to scan VS Code user path ${a}: ${d instanceof Error?d.message:String(d)}`)}),{sessionFiles:s,candidatePaths:t}}async resolveAllVSCodePaths(e){let t=ki();if(ia()){e("\u{1FA9F} WSL environment detected \u2014 probing Windows-side VS Code paths");let s=await cf();s.length>0?(e(`\u{1FA9F} Adding ${s.length} Windows-side candidate paths from WSL`),t.push(...s)):e("\u{1FA9F} No Windows-side paths found (Windows drive may not be mounted)")}return t}async scanWorkspaceStorage(e,t,s,n){let i=ce.join(e,"workspaceStorage"),r;try{r=await je.promises.readdir(i)}catch{return}let a=["GitHub.copilot-chat","github.copilot-chat","GitHub.copilot","github.copilot"],c=["chatSessions","debug-logs","transcripts"],d=async f=>{try{let h=(await je.promises.readdir(f)).filter(_=>_.endsWith(".json")||_.endsWith(".jsonl")).map(_=>ce.join(f,_));h.length>0&&s.push(...h)}catch{}},p=0;await Gc(r,async f=>{let h=ce.join(i,f),_;try{_=await je.promises.readdir(h)}catch{return}let C=new Set(_),T=s.length;C.has("chatSessions")&&await d(ce.join(h,"chatSessions"));for(let E of a)if(C.has(E))for(let A of c)await d(ce.join(h,E,A));s.length>T&&p++},8),p>0&&n(`\u{1F4C2} ${t}: found sessions in ${p}/${r.length} workspace dir(s)`)}async scanGlobalStorage(e,t,s,n){try{let i=ce.join(e,"globalStorage","emptyWindowChatSessions"),r=(await je.promises.readdir(i)).filter(a=>a.endsWith(".json")||a.endsWith(".jsonl")).map(a=>ce.join(i,a));r.length>0&&s.push(...r)}catch{}for(let i of["GitHub.copilot-chat","github.copilot-chat","GitHub.copilot","github.copilot"]){let r=ce.join(e,"globalStorage",i);try{await je.promises.access(r),await Bc(r,s,n)}catch{}}}};var Si="saoudrizwan.claude-dev",zc=new Set(["task","user_feedback"]),Ti=class{_uiMessagesCache=new Map;getClineStorageDirs(){return ki().map(e=>at.join(e,"globalStorage",Si))}getClineTasksDirs(){return this.getClineStorageDirs().map(e=>at.join(e,"tasks"))}isClineSessionFile(e){let t=X(e);return t.includes(`/${Si}/tasks/`)&&t.endsWith("/ui_messages.json")}getClineRootFromSessionFile(e){let s=e.replace(/\\/g,"/").toLowerCase().indexOf(`/${Si}/`.toLowerCase());return s!==-1?e.slice(0,s+1+Si.length):this.getClineStorageDirs()[0]}async getClineSessionFiles(){let e=[];for(let t of this.getClineTasksDirs()){let s;try{s=await Us.promises.readdir(t,{withFileTypes:!0})}catch{continue}for(let n of s){if(!n.isDirectory())continue;let i=at.join(t,n.name,"ui_messages.json");try{await Us.promises.access(i),e.push(i)}catch{}}}return e}async readUiMessages(e){let t;try{t=await Us.promises.stat(e)}catch{return[]}let s=this._uiMessagesCache.get(e);if(s&&s.mtimeMs===t.mtimeMs)return s.parsed;let n=[];try{let i=JSON.parse(await Us.promises.readFile(e,"utf8"));Array.isArray(i)&&(n=i)}catch{}return this._uiMessagesCache.set(e,{mtimeMs:t.mtimeMs,parsed:n}),n}async getApiRequests(e){let t=await this.readUiMessages(e),s=[];for(let n of t){if(n.say!=="api_req_started"||typeof n.text!="string")continue;let i;try{i=JSON.parse(n.text)}catch{continue}typeof i?.tokensIn!="number"&&typeof i?.tokensOut!="number"||s.push({ts:typeof n.ts=="number"?n.ts:null,tokensIn:this.asNumber(i.tokensIn),tokensOut:this.asNumber(i.tokensOut),cacheWrites:this.asNumber(i.cacheWrites),cacheReads:this.asNumber(i.cacheReads),cost:this.asNumber(i.cost),model:n.modelInfo?.modelId??null,mode:n.modelInfo?.mode??null})}return s}async readTaskHistoryEntry(e){let t=at.basename(at.dirname(e)),s=at.join(this.getClineRootFromSessionFile(e),"state","taskHistory.json");try{let n=JSON.parse(await Us.promises.readFile(s,"utf8"));return Array.isArray(n)?n.find(i=>i?.id===t):void 0}catch{return}}requestInputTokens(e){return e.tokensIn+e.cacheWrites+e.cacheReads}async getTokensFromClineSession(e){let t=await this.getApiRequests(e);if(t.length>0){let n=0;for(let i of t)n+=this.requestInputTokens(i)+i.tokensOut;return{tokens:n,thinkingTokens:0}}let s=await this.readTaskHistoryEntry(e);return s?{tokens:this.asNumber(s.tokensIn)+this.asNumber(s.tokensOut)+this.asNumber(s.cacheWrites)+this.asNumber(s.cacheReads),thinkingTokens:0}:{tokens:0,thinkingTokens:0}}async countClineInteractions(e){return(await this.readUiMessages(e)).filter(s=>s.type==="say"&&zc.has(s.say??"")).length}async getClineModelUsage(e){let t=await this.getApiRequests(e),s={};if(t.length>0){for(let i of t)this.addRequestToModelUsage(s,i.model??"unknown",this.requestInputTokens(i),i.tokensOut,i.cacheReads,i.cacheWrites);return s}let n=await this.readTaskHistoryEntry(e);if(n){let i=this.asNumber(n.cacheReads),r=this.asNumber(n.cacheWrites),a=this.asNumber(n.tokensIn)+i+r;this.addRequestToModelUsage(s,n.modelId??"unknown",a,this.asNumber(n.tokensOut),i,r)}return s}addRequestToModelUsage(e,t,s,n,i,r){e[t]||(e[t]={inputTokens:0,outputTokens:0,sessions:0}),e[t].inputTokens+=s,e[t].outputTokens+=n,i>0&&(e[t].cachedReadTokens=(e[t].cachedReadTokens??0)+i),r>0&&(e[t].cacheCreationTokens=(e[t].cacheCreationTokens??0)+r)}async getClineSessionMeta(e){let t=await this.readUiMessages(e),s=await this.readTaskHistoryEntry(e),n=t.find(a=>typeof a.ts=="number")?.ts??this.taskIdToEpochMs(e),i;for(let a of t)typeof a.ts=="number"&&(i=a.ts);let r=t.find(a=>a.say==="task");return{title:s?.task??r?.text??void 0,firstInteraction:n!==void 0?new Date(n).toISOString():null,lastInteraction:i!==void 0?new Date(i).toISOString():n!==void 0?new Date(n).toISOString():null,workspacePath:s?.cwdOnTaskInitialization}}taskIdToEpochMs(e){let t=at.basename(at.dirname(e)),s=Number(t);if(Number.isFinite(s)&&s>9466848e5&&s<41024448e5)return s}async getClineDailyFractions(e){let t=await this.getApiRequests(e),s=t.reduce((r,a)=>r+this.requestInputTokens(a)+a.tokensOut,0);if(t.length===0||s===0){let r=await this.getClineSessionMeta(e),a=r.firstInteraction?Date.parse(r.firstInteraction):NaN;return{[Number.isFinite(a)?L(new Date(a)):L(new Date)]:1}}let n=new Map;for(let r of t){let a=r.ts!==null?L(new Date(r.ts)):L(new Date);n.set(a,(n.get(a)??0)+this.requestInputTokens(r)+r.tokensOut)}let i={};for(let[r,a]of n.entries())i[r]=a/s;return i}async buildClineTurns(e){let t=await this.readUiMessages(e),s=[],n=null;for(let i of t){let r=i.say??i.ask??"";if(i.type==="say"&&zc.has(r)){n=this.newTurn(i),s.push(n);continue}n||(n=this.newTurn(void 0),s.push(n)),this.applyMessageToTurn(n,i,r)}return s}newTurn(e){return{userText:e?.text??"",assistantText:"",model:e?.modelInfo?.modelId??null,mode:e?.modelInfo?.mode??null,toolCalls:[],mcpTools:[],inputTokens:0,outputTokens:0,timestampMs:typeof e?.ts=="number"?e.ts:null}}applyMessageToTurn(e,t,s){switch(s){case"api_req_started":this.applyApiRequestToTurn(e,t);break;case"text":case"completion_result":this.appendAssistantText(e,t.text);break;case"tool":this.applyToolMessageToTurn(e,t);break;case"command":e.toolCalls.push({toolName:"executeCommand",arguments:t.text});break;case"command_output":{let n=e.toolCalls[e.toolCalls.length-1];n&&n.toolName==="executeCommand"&&(n.result=t.text);break}case"use_mcp_server":this.applyMcpMessageToTurn(e,t);break;case"browser_action_launch":case"browser_action":e.toolCalls.push({toolName:"browserAction",arguments:t.text});break;default:break}}applyApiRequestToTurn(e,t){if(t.modelInfo?.modelId&&(e.model=t.modelInfo.modelId),t.modelInfo?.mode&&(e.mode=t.modelInfo.mode),typeof t.text=="string")try{let s=JSON.parse(t.text);e.inputTokens+=this.asNumber(s?.tokensIn)+this.asNumber(s?.cacheWrites)+this.asNumber(s?.cacheReads),e.outputTokens+=this.asNumber(s?.tokensOut)}catch{}}appendAssistantText(e,t){if(!t)return;let s=t.indexOf("<tool_call>"),n=(s!==-1?t.slice(0,s):t).trim();n&&(e.assistantText+=(e.assistantText?`
|
|
72
72
|
|
|
73
|
-
`:"")+n)}applyToolMessageToTurn(e,t){if(typeof t.text=="string")try{let s=JSON.parse(t.text);e.toolCalls.push({toolName:typeof s?.tool=="string"?s.tool:"tool",arguments:typeof s?.path=="string"?s.path:void 0,result:typeof s?.content=="string"?s.content:void 0})}catch{e.toolCalls.push({toolName:"tool",arguments:t.text})}}applyMcpMessageToTurn(e,t){let s="unknown",n="unknown";if(typeof t.text=="string")try{let i=JSON.parse(t.text);typeof i?.serverName=="string"&&(s=i.serverName),typeof i?.toolName=="string"&&(n=i.toolName)}catch{}e.mcpTools.push({server:s,tool:n}),e.toolCalls.push({toolName:`${s}.${n}`})}asNumber(e){return typeof e=="number"&&Number.isFinite(e)?e:0}};var
|
|
73
|
+
`:"")+n)}applyToolMessageToTurn(e,t){if(typeof t.text=="string")try{let s=JSON.parse(t.text);e.toolCalls.push({toolName:typeof s?.tool=="string"?s.tool:"tool",arguments:typeof s?.path=="string"?s.path:void 0,result:typeof s?.content=="string"?s.content:void 0})}catch{e.toolCalls.push({toolName:"tool",arguments:t.text})}}applyMcpMessageToTurn(e,t){let s="unknown",n="unknown";if(typeof t.text=="string")try{let i=JSON.parse(t.text);typeof i?.serverName=="string"&&(s=i.serverName),typeof i?.toolName=="string"&&(n=i.toolName)}catch{}e.mcpTools.push({server:s,tool:n}),e.toolCalls.push({toolName:`${s}.${n}`})}asNumber(e){return typeof e=="number"&&Number.isFinite(e)?e:0}};var Qe=S(require("fs")),Pt=S(require("path")),Jc=S(require("os")),Vc=S(Nt());var $c=/^rollout-.*\.jsonl$/i,df=/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i,Hc=/\/state_\d+\.sqlite#/i,mf="state_5.sqlite",Wc=/^\s*<(user_instructions|environment_context|turn_context|permissions|ide_context|system_instructions)\b/i,wi=class o{_sqlJsModule=null;_sqlJsInitPromise=null;_dbCache=new Map;_dbCacheInflight=new Map;_rolloutCache=new Map;static ROLLOUT_CACHE_MAX=64;_codexHomeOverride=null;dispose(){for(let e of this._dbCache.values())try{e.db.close()}catch{}this._dbCache.clear(),this._dbCacheInflight.clear(),this._rolloutCache.clear(),this._sqlJsInitPromise=null}getCodexHome(){if(this._codexHomeOverride)return this._codexHomeOverride;let e=process.env.CODEX_HOME;return e&&e.trim()?e:Pt.join(Jc.homedir(),".codex")}setCodexHomeOverrideForTests(e){this._codexHomeOverride=e,this._rolloutCache.clear()}getSessionsDir(){return Pt.join(this.getCodexHome(),"sessions")}getArchivedSessionsDir(){return Pt.join(this.getCodexHome(),"archived_sessions")}getStateDbPath(){let e=this.getCodexHome(),t=null;try{for(let s of Qe.readdirSync(e)){let n=/^state_(\d+)\.sqlite$/i.exec(s);if(n){let i=parseInt(n[1],10);(!t||i>t.n)&&(t={n:i,name:s})}}}catch{}return Pt.join(e,t?t.name:mf)}isCodexCliSessionFile(e){let t=me(e).toLowerCase(),s=me(this.getCodexHome()).toLowerCase();return t.includes("/.codex/")||t.startsWith(s+"/")?Hc.test(t)?!0:$c.test(Pt.basename(t)):!1}isVirtualThreadPath(e){return Hc.test(me(e))}getDbPathFromVirtual(e){let t=e.lastIndexOf(".sqlite#");return t===-1?e:e.substring(0,t+7)}getThreadId(e){let t=e.lastIndexOf(".sqlite#");return t===-1?null:e.substring(t+8)||null}virtualPath(e){return`${this.getStateDbPath()}#${e}`}getBackingPath(e){return this.isVirtualThreadPath(e)?this.getDbPathFromVirtual(e):e}async statSessionFile(e){return Qe.promises.stat(this.getBackingPath(e))}async initSqlJs(){return this._sqlJsModule?this._sqlJsModule:(this._sqlJsInitPromise||(this._sqlJsInitPromise=(async()=>{let e=Pt.join(__dirname,"sql-wasm.wasm"),t;try{t=await Qe.promises.readFile(e)}catch{}let s=await(0,Vc.default)(t?{wasmBinary:t.buffer}:void 0);return this._sqlJsModule=s,s})().catch(e=>{throw this._sqlJsInitPromise=null,e})),this._sqlJsInitPromise)}closeDb(e){try{e.close()}catch{}}isMissingFileError(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async statDb(e){try{return await Qe.promises.stat(e)}catch(t){return this.isMissingFileError(t)&&this._dbCache.has(e)&&(this.closeDb(this._dbCache.get(e).db),this._dbCache.delete(e)),null}}sameDbStats(e,t){return e.mtimeMs===t.mtimeMs&&e.size===t.size}async refreshDb(e,t){let s;try{let r=await this.initSqlJs(),a=await Qe.promises.readFile(e);s=new r.Database(a)}catch{return this._dbCache.get(e)?.db??null}let n=await this.statDb(e);if(!n||!this.sameDbStats(t,n))return this.closeDb(s),this._dbCache.get(e)?.db??null;let i=this._dbCache.get(e);return i&&this.closeDb(i.db),this._dbCache.set(e,{db:s,mtimeMs:t.mtimeMs,size:t.size}),s}async getDb(e){let t=await this.statDb(e);if(!t)return this._dbCache.get(e)?.db??null;let s=this._dbCache.get(e);if(s&&s.mtimeMs===t.mtimeMs&&s.size===t.size)return s.db;let n=`${e}:${t.mtimeMs}:${t.size}`,i=this._dbCacheInflight.get(n);if(i)return i;let r=this.refreshDb(e,t);this._dbCacheInflight.set(n,r);try{return await r}finally{this._dbCacheInflight.get(n)===r&&this._dbCacheInflight.delete(n)}}rowsToObjects(e){if(e.length===0)return[];let{columns:t,values:s}=e[0];return s.map(n=>{let i={};return t.forEach((r,a)=>{i[r]=n[a]}),i})}async readAllThreads(){let e=await this.getDb(this.getStateDbPath());if(!e)return[];try{let t=e.exec(`SELECT id, rollout_path, created_at, updated_at, cwd, title, tokens_used,
|
|
74
74
|
has_user_event, archived, first_user_message, model
|
|
75
75
|
FROM threads ORDER BY updated_at DESC`);return this.rowsToObjects(t)}catch{return[]}}async readThread(e){let t=this.getThreadId(e);if(!t)return null;let s=await this.getDb(this.getDbPathFromVirtual(e));if(!s)return null;try{let n=s.exec(`SELECT id, rollout_path, created_at, updated_at, cwd, title, tokens_used,
|
|
76
76
|
has_user_event, archived, first_user_message, model
|
|
77
|
-
FROM threads WHERE id = ?`,[t]),i=this.rowsToObjects(n);return i.length>0?i[0]:null}catch{return null}}toMillis(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:e>1e12?e:e*1e3}async collectRolloutFiles(e,t=0,s=[]){if(t>5)return s;let n;try{n=await
|
|
78
|
-
`):""}extractTokenSnapshot(e,t){let s=e.info,n=typeof s=="object"&&s!==null?s.total_token_usage??s:e;if(typeof n!="object"||n===null)return null;let i=n,r=
|
|
79
|
-
`)){let i=n.trim();if(i)try{let r=JSON.parse(i);if(typeof r!="object"||r===null)continue;let a=this.normalizeRolloutLine(r);a&&s.push(a)}catch{}}return s}async getRolloutSummary(e){let t=null;try{t=await
|
|
80
|
-
`)[0].slice(0,100)||void 0,firstInteraction:t.firstTimestamp,lastInteraction:t.lastTimestamp,workspacePath:t.cwd||void 0}}async getThreadMeta(e){let t=await this.readThread(e),s=this.toMillis(t?.created_at),n=this.toMillis(t?.updated_at);return{title:t?.title||t?.first_user_message?.slice(0,100)||void 0,firstInteraction:s?new Date(s).toISOString():null,lastInteraction:n?new Date(n).toISOString():null,workspacePath:t?.cwd||void 0}}async getDailyFractions(e){if(this.isVirtualThreadPath(e)){let r=await this.readThread(e),a=this.toMillis(r?.updated_at)??this.toMillis(r?.created_at);return{[L(a?new Date(a):new Date)]:1}}let t=await this.getRolloutSummary(e),s={},n=0;for(let r of[...t.userMessages,...t.assistantMessages]){if(!r.timestamp)continue;let a=new Date(r.timestamp);if(isNaN(a.getTime()))continue;let c=L(a);s[c]=(s[c]||0)+1,n++}if(n===0){let r=t.lastTimestamp?new Date(t.lastTimestamp):new Date;return{[L(isNaN(r.getTime())?new Date:r)]:1}}let i={};for(let[r,a]of Object.entries(s))i[r]=a/n;return i}};var Pi=w(require("fs")),vt=w(require("path"));var js=w(require("fs"));var Zg=new Set(["edit","create","write","patch","multiedit","notebookedit","editfiles","edit_files","edit_file","apply_patch","applypatch","create_file","createfile","write_file","writefile","insert_edit_into_file","insertedit","replace_string_in_file","replacestring","edit_notebook_file","editnotebook","str_replace_editor","str_replace","copilot_editfiles","copilot_editfile","copilot_writefile","copilot_applypatch","copilot_createfile","copilot_insertedit","copilot_replacestring","copilot_editnotebook","write_to_file","replace_in_file","apply_diff","replace","fswrite","fsappend","strreplace","windsurf_file_edit","windsurf_file_create"]);function ef(o){return Zg.has(o.toLowerCase())}var tf=["file_path","filePath","path","absolute_path","absolutePath","target_file","targetFile","file","filename","fileName","notebook_path"];function sf(o){if(!o)return null;let e;try{e=JSON.parse(o)}catch{return null}if(!e||typeof e!="object")return null;let t=e;for(let n of tf){let i=t[n];if(typeof i=="string"&&i)return i}let s=t.uri;if(s&&typeof s=="object"){let n=s;if(typeof n.fsPath=="string"&&n.fsPath)return n.fsPath;if(typeof n.path=="string"&&n.path)return n.path}return null}function nf(){return{calls:0,editTurns:0,oneShotEditTurns:0,retries:0,selfCorrections:0,editToolCalls:0,inputTokens:0,outputTokens:0,cachedReadTokens:0,cost:0}}function Bc(o,e){return o[e]||(o[e]=nf()),o[e]}function of(o,e){let t=0,s=0,n=0,i=new Set,r=null,a=0;for(let c of o){if(!ef(c.toolName)){r=null;continue}t++;let m=sf(c.arguments)??`\0unknown-${a++}`;i.has(m)&&(r===m?s++:n++),i.add(m),r=m}e.editToolCalls+=t,t>0&&(e.editTurns++,e.retries+=s,e.selfCorrections+=n,s===0&&n===0&&e.oneShotEditTurns++)}function ki(o){let e={};for(let t of o){let s=t.model||"unknown",n=Bc(e,s);n.calls++,of(t.toolCalls??[],n)}return e}function zc(o){let e=[];if(!o.response||!Array.isArray(o.response))return e;for(let t of o.response)if(!(!t||typeof t!="object"))if(t.kind==="textEditGroup"){let s=t.uri?.fsPath||t.uri?.path;e.push({toolName:"edit",arguments:s?JSON.stringify({path:s}):void 0})}else(t.kind==="toolInvocationSerialized"||t.kind==="prepareToolInvocation")&&e.push({toolName:"toolInvocation"});return e}function $c(o,e){if(e)for(let[t,s]of Object.entries(e)){let n=Bc(o,t);n.calls+=s.calls,n.editTurns+=s.editTurns,n.oneShotEditTurns+=s.oneShotEditTurns,n.retries+=s.retries,n.selfCorrections+=s.selfCorrections,n.editToolCalls+=s.editToolCalls,n.inputTokens+=s.inputTokens,n.outputTokens+=s.outputTokens,n.cachedReadTokens+=s.cachedReadTokens,n.cost+=s.cost}}var Si=w(require("fs")),Bt=w(require("path")),Yc=w(require("os")),Xc=require("worker_threads");var Tn=w(require("fs")),Zr=w(require("path")),Wc=w(require("os")),Hc=w(is());function ea(o){return o?o.replace(/\\/g,"/").toLowerCase().includes("/microsoft scout"):!1}function Jc(o){return o==="github/autopilot"}function rf(o){if(typeof o!="object"||o===null)return!1;let e=o;return typeof e.id=="string"&&(e.cwd===null||typeof e.cwd=="string")&&(e.repository===null||typeof e.repository=="string")&&(e.branch===null||typeof e.branch=="string")&&(e.summary===null||typeof e.summary=="string")&&(e.created_at===null||typeof e.created_at=="string")&&(e.updated_at===null||typeof e.updated_at=="string")}function af(o){if(typeof o!="object"||o===null)return!1;let e=o;return typeof e.session_id=="string"&&typeof e.turn_index=="number"&&(e.user_message===null||typeof e.user_message=="string")&&(e.assistant_response===null||typeof e.assistant_response=="string")&&(e.timestamp===null||typeof e.timestamp=="string")}var Ns=class{_sqlJsModule=null;_sqlJsInitPromise=null;_initSqlJsFn;_dbCache=new Map;_dbCacheInflight=new Map;_sessionsCache=new Map;_sessionsCacheInflight=new Map;_turnCountsCache=new Map;_turnCountsCacheInflight=new Map;constructor(e){this._initSqlJsFn=e??Hc.default}dispose(){for(let e of this._dbCache.values())try{e.db.close()}catch{}this._dbCache.clear(),this._dbCacheInflight.clear(),this._sessionsCache.clear(),this._sessionsCacheInflight.clear(),this._turnCountsCache.clear(),this._turnCountsCacheInflight.clear(),this._sqlJsInitPromise=null}closeDb(e){try{e.close()}catch{}}isMissingFileError(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async statDb(e){try{return await Tn.promises.stat(e)}catch(t){return this.isMissingFileError(t)&&this._dbCache.has(e)&&(this.closeDb(this._dbCache.get(e).db),this._dbCache.delete(e)),null}}isCachedDbCurrent(e,t){let s=this._dbCache.get(e);return!!s&&s.mtimeMs===t.mtimeMs&&s.size===t.size}getDbCacheKey(e,t){return`${e}:${t.mtimeMs}:${t.size}`}sameDbStats(e,t){return e.mtimeMs===t.mtimeMs&&e.size===t.size}async refreshDb(e,t){let s;try{let r=await this.initSqlJs(),a=await Tn.promises.readFile(e);s=new r.Database(a)}catch{return this._dbCache.get(e)?.db??null}let n=await this.statDb(e);if(!n||!this.sameDbStats(t,n))return this.closeDb(s),this._dbCache.get(e)?.db??null;let i=this._dbCache.get(e);return i&&this.closeDb(i.db),this._dbCache.set(e,{db:s,mtimeMs:t.mtimeMs,size:t.size}),s}async getDb(e){let t=await this.statDb(e);if(!t)return this._dbCache.get(e)?.db??null;if(this.isCachedDbCurrent(e,t))return this._dbCache.get(e).db;let s=this.getDbCacheKey(e,t),n=this._dbCacheInflight.get(s);if(n)return n;let i=this.refreshDb(e,t);this._dbCacheInflight.set(s,i);try{return await i}finally{this._dbCacheInflight.get(s)===i&&this._dbCacheInflight.delete(s)}}getDbPath(){return Zr.join(Wc.homedir(),".copilot","session-store.db")}virtualPath(e){return`${this.getDbPath()}#${e}`}isCliStoreSession(e){return e.includes("session-store.db#")}getDbPathFromVirtual(e){let t=e.indexOf("session-store.db#");return t===-1?e:e.substring(0,t+16)}getSessionId(e){let t=e.indexOf("session-store.db#");return t===-1?null:e.substring(t+17)||null}async getSessionsMap(e){let t=await this.statDb(e);if(!t)return this._sessionsCache.get(e)?.byId??new Map;let s=this._sessionsCache.get(e);if(s&&s.mtimeMs===t.mtimeMs&&s.size===t.size)return s.byId;let n=`${e}:${t.mtimeMs}:${t.size}`,i=this._sessionsCacheInflight.get(n);if(i)return i;let r=(async()=>{let a=await this.getDb(e),c=new Map;if(a)try{let m=a.exec("SELECT id, cwd, repository, branch, summary, created_at, updated_at FROM sessions");if(m.length>0){let p=m[0].columns;for(let f of m[0].values){let h={};p.forEach((_,C)=>{h[_]=f[C]}),rf(h)&&c.set(h.id,h)}}}catch{}return this._sessionsCache.set(e,{mtimeMs:t.mtimeMs,size:t.size,byId:c}),c})();this._sessionsCacheInflight.set(n,r);try{return await r}finally{this._sessionsCacheInflight.get(n)===r&&this._sessionsCacheInflight.delete(n)}}async getTurnCountsMap(e){let t=await this.statDb(e);if(!t)return this._turnCountsCache.get(e)?.byId??new Map;let s=this._turnCountsCache.get(e);if(s&&s.mtimeMs===t.mtimeMs&&s.size===t.size)return s.byId;let n=`${e}:${t.mtimeMs}:${t.size}`,i=this._turnCountsCacheInflight.get(n);if(i)return i;let r=(async()=>{let a=await this.getDb(e),c=new Map;if(a)try{let m=a.exec("SELECT session_id, COUNT(*) FROM turns GROUP BY session_id");if(m.length>0)for(let p of m[0].values)c.set(p[0],p[1]||0)}catch{}return this._turnCountsCache.set(e,{mtimeMs:t.mtimeMs,size:t.size,byId:c}),c})();this._turnCountsCacheInflight.set(n,r);try{return await r}finally{this._turnCountsCacheInflight.get(n)===r&&this._turnCountsCacheInflight.delete(n)}}async stat(e){let t=this.getDbPathFromVirtual(e),s=this.getSessionId(e),n=await Tn.promises.stat(t),i=s?(await this.getSessionsMap(t)).get(s):void 0,r=i?.updated_at?new Date(i.updated_at):null;return!r||Number.isNaN(r.getTime())||Object.defineProperty(n,"mtime",{value:r,writable:!1}),n}async initSqlJs(){return this._sqlJsModule?this._sqlJsModule:(this._sqlJsInitPromise||(this._sqlJsInitPromise=(async()=>{let e=Zr.join(__dirname,"sql-wasm.wasm"),t;try{t=await Tn.promises.readFile(e)}catch{}let s=await this._initSqlJsFn(t?{wasmBinary:t.buffer}:void 0);return this._sqlJsModule=s,s})().catch(e=>{throw this._sqlJsInitPromise=null,e})),this._sqlJsInitPromise)}async discoverNewSessions(e){let t=this.getDbPath(),s=await this.getDb(t);if(!s)return[];try{let n=s.exec("SELECT id FROM sessions ORDER BY updated_at DESC");return n.length===0?[]:n[0].values.map(i=>i[0]).filter(i=>!e.has(i))}catch{return[]}}async discoverNewSessionsWithCwd(e){let t=this.getDbPath(),s=await this.getDb(t);if(!s)return[];try{let n=s.exec("SELECT id, cwd FROM sessions ORDER BY updated_at DESC");return n.length===0?[]:n[0].values.filter(i=>!e.has(i[0])).map(i=>({id:i[0],cwd:i[1]??null}))}catch{return[]}}async readSession(e){let t=this.getDbPathFromVirtual(e),s=this.getSessionId(e);return s?(await this.getSessionsMap(t)).get(s)??null:null}async getTurns(e){let t=this.getDbPathFromVirtual(e),s=this.getSessionId(e);if(!s)return[];let n=await this.getDb(t);if(!n)return[];try{let i=n.exec("SELECT session_id, turn_index, user_message, assistant_response, timestamp FROM turns WHERE session_id = ? ORDER BY turn_index ASC",[s]);if(i.length===0)return[];let r=i[0].columns,a=[];for(let c of i[0].values){let m={};r.forEach((p,f)=>{m[p]=c[f]}),af(m)&&a.push(m)}return a}catch{return[]}}async countTurns(e){let t=this.getDbPathFromVirtual(e),s=this.getSessionId(e);return s?(await this.getTurnCountsMap(t)).get(s)??0:0}async getSessionUsage(e){let t=this.getDbPath(),s=await this.getDb(t);if(!s)return null;try{let n=s.exec("SELECT model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, total_nano_aiu FROM assistant_usage_events WHERE session_id = ?",[e]);return n.length?this.aggregateUsageEvents(n[0].columns,n[0].values):null}catch{return null}}parseUsageEventRow(e,t){let s={};return e.forEach((n,i)=>{s[n]=t[i]}),{model:typeof s.model=="string"?s.model:"unknown",inputTokens:typeof s.input_tokens=="number"?s.input_tokens:0,outputTokens:typeof s.output_tokens=="number"?s.output_tokens:0,cacheReadTokens:typeof s.cache_read_tokens=="number"?s.cache_read_tokens:0,cacheWriteTokens:typeof s.cache_write_tokens=="number"?s.cache_write_tokens:0,nanoAiu:typeof s.total_nano_aiu=="number"?s.total_nano_aiu:0}}addUsageEventToModelUsage(e,t){e[t.model]||(e[t.model]={inputTokens:0,outputTokens:0});let s=e[t.model];s.inputTokens+=t.inputTokens,s.outputTokens+=t.outputTokens,t.cacheReadTokens>0&&(s.cachedReadTokens=(s.cachedReadTokens??0)+t.cacheReadTokens),t.cacheWriteTokens>0&&(s.cacheCreationTokens=(s.cacheCreationTokens??0)+t.cacheWriteTokens)}aggregateUsageEvents(e,t){let s={},n=0,i=0,r=0;for(let a of t){let c=this.parseUsageEventRow(e,a);this.addUsageEventToModelUsage(s,c),n+=c.inputTokens+c.outputTokens,i+=c.cacheReadTokens,r+=c.nanoAiu}return n===0&&i===0&&r===0?null:{modelUsage:s,actualTokens:n,cacheReadTokens:i,nanoAiu:r}}async getDailyFractions(e){let t=await this.getTurns(e),s={},n=0;for(let r of t)if(r.timestamp)try{let a=L(new Date(r.timestamp));s[a]=(s[a]||0)+1,n++}catch{}if(n===0){let r=await this.readSession(e);return{[r?.updated_at?L(new Date(r.updated_at)):L(new Date)]:1}}let i={};for(let[r,a]of Object.entries(s))i[r]=a/n;return i}};var Vc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function lf(){return Bt.join(Yc.homedir(),".copilot","otel")}function Ls(o){let e=o.lastIndexOf("#");if(e!==-1&&o.slice(0,e).endsWith(".db")){let t=o.slice(e+1);return Vc.test(t)?t:null}if(o.includes("session-state")){let t=Bt.basename(Bt.dirname(o));return Vc.test(t)?t:null}return null}function cf(o){let e=t=>typeof t=="number"?t:0;return{model:o?.["gen_ai.response.model"]||o?.["gen_ai.request.model"]||"unknown",input:e(o?.["gen_ai.usage.input_tokens"]),output:e(o?.["gen_ai.usage.output_tokens"]),cacheCreation:e(o?.["gen_ai.usage.cache_creation.input_tokens"]),cacheRead:e(o?.["gen_ai.usage.cache_read.input_tokens"]),nanoAiu:e(o?.["github.copilot.nano_aiu"])}}function uf(o,e,t){o.has(e)||o.set(e,{modelUsage:{},actualTokens:0,cacheReadTokens:0,nanoAiu:0});let s=o.get(e);s.modelUsage[t.model]||(s.modelUsage[t.model]={inputTokens:0,outputTokens:0});let n=s.modelUsage[t.model];n.inputTokens+=t.input,n.outputTokens+=t.output,t.cacheCreation>0&&(n.cacheCreationTokens=(n.cacheCreationTokens??0)+t.cacheCreation),t.cacheRead>0&&(n.cachedReadTokens=(n.cachedReadTokens??0)+t.cacheRead),s.actualTokens+=t.input+t.output,s.cacheReadTokens+=t.cacheRead,s.nanoAiu+=t.nanoAiu}var Zc='"name":"chat ',df=10;function mf(o,e){if(o.type!=="span"||!o.name?.startsWith("chat "))return;let t=o.attributes?.["gen_ai.conversation.id"];t&&uf(e,t,cf(o.attributes))}function pf(o){if(!o.includes(Zc))return null;try{return JSON.parse(o)}catch{return null}}function gf(o){let e=o;return{records:Array.isArray(e?.records)?e.records:[],consumed:e?.consumed&&typeof e.consumed=="object"?e.consumed:{}}}var ff=`
|
|
77
|
+
FROM threads WHERE id = ?`,[t]),i=this.rowsToObjects(n);return i.length>0?i[0]:null}catch{return null}}toMillis(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:e>1e12?e:e*1e3}async collectRolloutFiles(e,t=0,s=[]){if(t>5)return s;let n;try{n=await Qe.promises.readdir(e,{withFileTypes:!0})}catch{return s}for(let i of n){let r=Pt.join(e,i.name);i.isDirectory()?await this.collectRolloutFiles(r,t+1,s):$c.test(i.name)&&s.push(r)}return s}async discoverSessions(){let e=[],t=new Set,s=new Set,n=[...await this.collectRolloutFiles(this.getSessionsDir()),...await this.collectRolloutFiles(this.getArchivedSessionsDir())];for(let a of n){let c=me(a).toLowerCase();if(t.has(c))continue;t.add(c),e.push(a);let d=df.exec(a);d&&s.add(d[1].toLowerCase())}let i=e.length,r=0;for(let a of await this.readAllThreads()){if(!a.id||s.has(a.id.toLowerCase()))continue;s.add(a.id.toLowerCase());let c=this.resolveThreadPath(a,t);c&&(e.push(c.path),c.dbOnly&&r++)}return{files:e,rolloutCount:i,dbOnlyCount:r}}resolveThreadPath(e,t){if(e.rollout_path&&Qe.existsSync(e.rollout_path)){let s=me(e.rollout_path).toLowerCase();return t.has(s)?null:(t.add(s),{path:e.rollout_path,dbOnly:!1})}return{path:this.virtualPath(e.id),dbOnly:!0}}normalizeRolloutLine(e){let t=typeof e.timestamp=="string"?e.timestamp:null,s=typeof e.type=="string"?e.type:null,n=e.payload;return s&&typeof n=="object"&&n!==null?{timestamp:t,kind:s,payload:n}:s?{timestamp:t,kind:"response_item",payload:e}:typeof e.id=="string"&&("instructions"in e||"cwd"in e||"git"in e)?{timestamp:t,kind:"session_meta",payload:e}:null}extractMessageText(e){let t=e.content;return typeof t=="string"?t:Array.isArray(t)?t.filter(s=>typeof s=="object"&&s!==null).filter(s=>typeof s.text=="string"&&(s.type==="input_text"||s.type==="output_text"||s.type==="text"||s.type===void 0)).map(s=>s.text).join(`
|
|
78
|
+
`):""}extractTokenSnapshot(e,t){let s=e.info,n=typeof s=="object"&&s!==null?s.total_token_usage??s:e;if(typeof n!="object"||n===null)return null;let i=n,r=d=>typeof i[d]=="number"&&Number.isFinite(i[d])?i[d]:0,a=r("input_tokens"),c=r("output_tokens");return a===0&&c===0&&r("total_tokens")===0?null:{input:a,cachedInput:r("cached_input_tokens"),output:c,reasoning:r("reasoning_output_tokens"),model:t}}toolNameForResponseItem(e,t){return e==="function_call"||e==="custom_tool_call"?typeof t.name=="string"&&t.name?t.name:"unknown":e==="local_shell_call"?"shell":e==="web_search_call"?"web_search":null}applyMessageItem(e,t,s){let n=e.payload.role,i=this.extractMessageText(e.payload);i&&(n==="user"&&!Wc.test(i)?t.userMessages.push({text:i,timestamp:e.timestamp}):n==="assistant"&&t.assistantMessages.push({text:i,timestamp:e.timestamp,model:s}))}applyReasoningItem(e,t){let s=Array.isArray(e.summary)?e.summary:[];for(let n of s)typeof n=="object"&&n!==null&&typeof n.text=="string"&&(t.reasoningChars+=n.text.length)}applyResponseItem(e,t,s){let n=e.payload,i=typeof n.type=="string"?n.type:"";if(i==="message"){this.applyMessageItem(e,t,s);return}if(i==="reasoning"){this.applyReasoningItem(n,t);return}let r=this.toolNameForResponseItem(i,n);r&&t.toolCalls.push({name:r,timestamp:e.timestamp})}applyEventMsg(e,t,s){let n=e.payload;if(n.type==="token_count"){let r=this.extractTokenSnapshot(n,s);r&&t.tokenSnapshots.push(r)}}countEventMsgUserMessages(e){let t=[];for(let s of e){if(s.kind!=="event_msg"||s.payload.type!=="user_message")continue;let n=s.payload.message;typeof n=="string"&&n&&!Wc.test(n)&&t.push({text:n,timestamp:s.timestamp})}return t}async readRolloutLines(e){let t;try{t=await Qe.promises.readFile(e,"utf8")}catch{return[]}let s=[];for(let n of t.split(`
|
|
79
|
+
`)){let i=n.trim();if(i)try{let r=JSON.parse(i);if(typeof r!="object"||r===null)continue;let a=this.normalizeRolloutLine(r);a&&s.push(a)}catch{}}return s}async getRolloutSummary(e){let t=null;try{t=await Qe.promises.stat(e)}catch{}if(t){let n=this._rolloutCache.get(e);if(n&&n.mtimeMs===t.mtimeMs&&n.size===t.size)return n.summary}let s=this.buildRolloutSummary(await this.readRolloutLines(e));if(t){if(this._rolloutCache.size>=o.ROLLOUT_CACHE_MAX){let n=this._rolloutCache.keys().next().value;n!==void 0&&this._rolloutCache.delete(n)}this._rolloutCache.set(e,{mtimeMs:t.mtimeMs,size:t.size,summary:s})}return s}buildRolloutSummary(e){let t={sessionId:null,cwd:null,firstTimestamp:null,lastTimestamp:null,userMessages:[],assistantMessages:[],toolCalls:[],tokenSnapshots:[],reasoningChars:0,models:[]},s="unknown";for(let n of e)n.timestamp&&(t.firstTimestamp||(t.firstTimestamp=n.timestamp),t.lastTimestamp=n.timestamp),s=this.applyRolloutLine(n,t,s);return t.userMessages.length===0&&(t.userMessages=this.countEventMsgUserMessages(e)),t}applyRolloutLine(e,t,s){if(e.kind==="session_meta"){let n=e.payload;return typeof n.id=="string"&&(t.sessionId=n.id),typeof n.cwd=="string"&&(t.cwd=n.cwd),s}if(e.kind==="turn_context"){let n=e.payload.model;return typeof n=="string"&&n?(t.models.includes(n)||t.models.push(n),n):s}return e.kind==="response_item"?this.applyResponseItem(e,t,s):e.kind==="event_msg"&&this.applyEventMsg(e,t,s),s}computeTokenTotals(e){let t={},s=0,n=null;for(let r of e.tokenSnapshots){let a=n?Math.max(0,r.input-n.input):r.input,c=n?Math.max(0,r.output-n.output):r.output,d=n?Math.max(0,r.reasoning-n.reasoning):r.reasoning;if(a>0||c>0){let p=t[r.model]??(t[r.model]={inputTokens:0,outputTokens:0,sessions:0});p.inputTokens+=a,p.outputTokens+=c}s+=d,n=r}let i=Object.values(t).reduce((r,a)=>r+a.inputTokens+a.outputTokens,0);return{perModel:t,totalTokens:i,thinkingTokens:s}}estimateTextTokens(e){return e?Math.ceil(e.length/4):0}estimateRolloutTokens(e){let t=0,s=0;for(let i of e.userMessages)t+=this.estimateTextTokens(i.text);for(let i of e.assistantMessages)s+=this.estimateTextTokens(i.text);let n=Math.ceil(e.reasoningChars/4);return{input:t,output:s,thinking:n}}async getTokens(e){if(this.isVirtualThreadPath(e)){let i=await this.readThread(e);return{tokens:typeof i?.tokens_used=="number"?i.tokens_used:0,thinkingTokens:0}}let t=await this.getRolloutSummary(e),s=this.computeTokenTotals(t);if(s.totalTokens>0)return{tokens:s.totalTokens,thinkingTokens:s.thinkingTokens};let n=this.estimateRolloutTokens(t);return{tokens:n.input+n.output+n.thinking,thinkingTokens:n.thinking}}async countInteractions(e){if(this.isVirtualThreadPath(e)){let s=await this.readThread(e);return s&&(s.has_user_event===1||typeof s.first_user_message=="string"&&s.first_user_message.trim().length>0)?1:0}return(await this.getRolloutSummary(e)).userMessages.length}async getModelUsage(e){if(this.isVirtualThreadPath(e)){let r=await this.readThread(e),a=typeof r?.tokens_used=="number"?r.tokens_used:0;return a===0?{}:{[r?.model||"unknown"]:{inputTokens:a,outputTokens:0,sessions:0}}}let t=await this.getRolloutSummary(e),s=this.computeTokenTotals(t);if(s.totalTokens>0)return s.perModel;let n=this.estimateRolloutTokens(t);return n.input+n.output+n.thinking===0?{}:{[t.models[t.models.length-1]||"unknown"]:{inputTokens:n.input,outputTokens:n.output+n.thinking,sessions:0}}}async getMeta(e){if(this.isVirtualThreadPath(e))return this.getThreadMeta(e);let t=await this.getRolloutSummary(e);return{title:t.userMessages[0]?.text.split(`
|
|
80
|
+
`)[0].slice(0,100)||void 0,firstInteraction:t.firstTimestamp,lastInteraction:t.lastTimestamp,workspacePath:t.cwd||void 0}}async getThreadMeta(e){let t=await this.readThread(e),s=this.toMillis(t?.created_at),n=this.toMillis(t?.updated_at);return{title:t?.title||t?.first_user_message?.slice(0,100)||void 0,firstInteraction:s?new Date(s).toISOString():null,lastInteraction:n?new Date(n).toISOString():null,workspacePath:t?.cwd||void 0}}async getDailyFractions(e){if(this.isVirtualThreadPath(e)){let r=await this.readThread(e),a=this.toMillis(r?.updated_at)??this.toMillis(r?.created_at);return{[L(a?new Date(a):new Date)]:1}}let t=await this.getRolloutSummary(e),s={},n=0;for(let r of[...t.userMessages,...t.assistantMessages]){if(!r.timestamp)continue;let a=new Date(r.timestamp);if(isNaN(a.getTime()))continue;let c=L(a);s[c]=(s[c]||0)+1,n++}if(n===0){let r=t.lastTimestamp?new Date(t.lastTimestamp):new Date;return{[L(isNaN(r.getTime())?new Date:r)]:1}}let i={};for(let[r,a]of Object.entries(s))i[r]=a/n;return i}};var Mn=S(require("fs")),Os=S(require("path")),Pn=S(require("os")),Zc=S(Nt());var Kc=["read_file","copilot_readFile","read","view","view_image","copilot_viewImage","list_dir","list_directory","ls","copilot_listDirectory","find_files","file_search","file_glob_search","copilot_findFiles","opilot_findFiles","copilot_findTextInFiles","copilot_findTestFiles","test_search","grep_search","grep","glob","rg","semantic_search","copilot_searchCodebase","code_search","copilot_getSearchResults","copilot_githubTextSearch","get_search_view_results","search_workspace_symbols","copilot_searchWorkspaceSymbols","vscode_listCodeUsages","get_symbols_by_name","get_errors","copilot_getErrors","get_changed_files","copilot_getChangedFiles","read_project_structure","copilot_readProjectStructure","get_doc_info","copilot_getDocInfo","get_vscode_api","copilot_getVSCodeAPI","get_project_setup_info","copilot_getProjectSetupInfo","get_files_in_project","get_projects_in_solution","get_python_executable_details","get_currentfile","get_file","vscode_get_confirmation","vscode_get_confirmation_with_options","vscode_get_terminal_confirmation","vscode_get_modified_files_confirmation","memory","copilot_memory","copilot_resolveMemoryFileUri","detect_memories","todo","tool_replay","copilot_toolReplay","tool_search","tool_search_tool","get_task_output","get_output_window_logs","job_output","get_terminal_output","await_terminal","terminal_selection","terminal_last_command","read_notebook_cell_output","copilot_readNotebookCellOutput","copilot_getNotebookSummary","test_failure","copilot_testFailure","ask_questions","AskUserQuestion","ask_user_question","copilot_askQuestions","switch_agent","copilot_switchAgent","bash","chmod","vscode_editFile_internal","vscode_fetchWebPage_internal","vscode_searchExtensions_internal","fetch_copilot_cli_documentation","generate_findings","generate_topics","list_bash","read_bash","write_bash","stop_bash","list_powershell","read_powershell","clarify_requirements","get_tests","ide-get_diagnostics","mcp__ide__getDiagnostics","plan","signal_plan_ready","update_plan_progress","EnterPlanMode","ExitPlanMode","stop_agent","mcp_reload","mcp_validate","add_loaded_assembly","analyze_symbol","search_decompiled_symbols","search_web"];var gf=/subagent|sub[-_]?agent|agent[-_]?spawn|delegate/i;function Qc(o){let e=0;for(let[t,s]of Object.entries(o))gf.test(t)&&(e+=s);return e}var ff=new Set(Kc.map(o=>o.toLowerCase()));function z(o){return o.toLocaleString("en-US")}function he(o,e){return Math.max(o,e)}var hf={1:"Stage 1: AI Skeptic",2:"Stage 2: AI Explorer",3:"Stage 3: AI Collaborator",4:"Stage 4: AI Strategist"},Ge={promptEngineering:{stage2MinInteractions:5,stage2MinAvgTurns:3,stage3MinAvgTurns:5,stage3MinInteractions:30,stage3MinSlashCommands:2,stage4MinInteractions:100,stage4MinSlashCommands:3},contextEngineering:{stage2MinTotalRefs:1,stage3MinRefTypes:3,stage3MinTotalRefs:10,stage4MinRefTypes:5,stage4MinTotalRefs:30},agentic:{stage3MinAvgFilesPerSession:3,stage3MinAgentInteractions:10,stage3MinNonAutoTools:3,stage4MinAgentInteractions:50,stage4MinNonAutoTools:5,stage4MinMultiFileEdits:20,stage3MinMultiAgentParents:1,stage4MinMultiAgentParents:3,multiAgentMinChildren:2,stage3MinDelegationSessions:2,stage4MinDelegationSessions:5},toolUsage:{stage3MinAdvancedTools:2,stage4MinMcpServers:2},customization:{stage3MinCustomizationRate:.3,stage3MinCustomizedRepos:2,stage4MinCustomizationRate:.7,stage4MinCustomizedRepos:3,stage3MinUniqueModels:3,stage4MinUniqueModels:5},workflowIntegration:{stage2MinSessions:3,stage2MinApplyRatePct:50,stage3MinModesUsed:2,hasExplicitContextMinRefs:10,stage3MinContextRefs:20,stage4MinSessions:15}};function yf(o){let e=[...o].sort((n,i)=>n-i),t=Math.floor(e.length/2);return e.length%2===0?Math.round((e[t-1]+e[t])/2):e[t]}var _f=["explain","fix","tests","doc","generate","optimize","new","newNotebook","search","fixTestFailure","setupTests"],Cf=["review","bug","think","compact","pr_comments"];function bf(o){return[..._f.filter(e=>(o[e]??0)>0),...Cf.filter(e=>(o[`__slash__${e}`]??0)>0)]}function Xc(o){return Object.keys(o).filter(e=>!ff.has(e.toLowerCase())&&!e.startsWith("__slash__")).length}function kf(o,e,t){return o>0||e>0||t>0}function Sf(o,e){return o>0||e>0}function Tf(o,e,t){let s=Ge.promptEngineering;return o>=s.stage3MinInteractions&&(e.length>=s.stage3MinSlashCommands||t)}function wf(o,e,t,s){let n=Ge.promptEngineering;return o>=n.stage4MinInteractions&&e&&(t||s.length>=n.stage4MinSlashCommands)}function Mf(o,e,t){let s=[];return o||s.push("Try [agent mode](https://code.visualstudio.com/docs/copilot/agents/overview) for multi-file changes \u2014 [\u25B6 Agent Mode video](https://tech.hub.ms/github-copilot/videos/agent-mode)"),e.length<t.stage3MinSlashCommands&&s.push("Use [slash commands](https://code.visualstudio.com/docs/copilot/chat/copilot-chat#_add-context-to-your-prompts) like /explain, /fix, or /tests to give structured prompts"),s}function Pf(o,e,t,s,n){let i=[];return o||i.push("Try [agent mode](https://code.visualstudio.com/docs/copilot/agents/overview) for autonomous, multi-step coding tasks"),e||i.push("Experiment with [different models](https://code.visualstudio.com/docs/copilot/chat/copilot-chat#_choose-a-language-model) for different tasks - use fast models for simple queries and reasoning models for complex problems \u2014 [\u25B6 Model selection video](https://tech.hub.ms/github-copilot/videos/model-selection)"),s===0?i.push("Try the Auto model for cost-sensitive tasks so Copilot can pick the most efficient model for you"):s<.5&&i.push("Use the Auto model more often when you want Copilot to balance quality and cost for you"),t.length<n.stage4MinSlashCommands&&o&&e&&i.push("Explore more [slash commands](https://code.visualstudio.com/docs/copilot/chat/copilot-chat#_add-context-to-your-prompts) like /explain, /tests, or /doc to diversify your prompting"),i}function vf(o,e,t,s,n){let i=Ge.promptEngineering,r=[];return o<2&&r.push("Try asking Copilot a question using the Chat panel \u2014 [\u25B6 Chat in IDE video](https://tech.hub.ms/github-copilot/videos/chat-in-ide)"),o<3&&r.push(...Mf(e,s,i)),o<4&&r.push(...Pf(e,t,s,n,i)),r}function Af(o,e,t){if(!o.conversationPatterns)return t;let s=Ge.promptEngineering,n=Math.round(o.conversationPatterns.multiTurnSessions/Math.max(1,o.sessions)*100);return o.conversationPatterns.multiTurnSessions>0&&e.push(`${z(o.conversationPatterns.multiTurnSessions)} multi-turn sessions (${n}%)`),o.conversationPatterns.avgTurnsPerSession>=s.stage2MinAvgTurns&&(e.push(`Avg ${o.conversationPatterns.avgTurnsPerSession.toFixed(1)} exchanges per session`),t=he(t,2)),o.conversationPatterns.avgTurnsPerSession>=s.stage3MinAvgTurns&&(t=he(t,3)),t}function xf(o){let{stage:e,evidence:t,usedSlashCommands:s,hasModelSwitching:n,hasAgentMode:i,autoUsageRatio:r}=Uf(o);return{stage:e,evidence:t,tips:vf(e,i,n,s,r)}}function Df(o,e){let t=e.modeUsage.ask+e.modeUsage.edit+e.modeUsage.agent+e.modeUsage.cli;t>0&&o.push(`${z(t)} total interactions`),e.modeUsage.ask>0&&o.push(`${z(e.modeUsage.ask)} ask-mode conversations`),e.modeUsage.agent>0&&o.push(`${z(e.modeUsage.agent)} agent-mode interactions`),e.modeUsage.cli>0&&o.push(`${z(e.modeUsage.cli)} CLI interactions`)}function Ef(o,e,t){e.modelSwitching.autoSessions>0&&o.push(`Auto model used in ${z(e.modelSwitching.autoSessions)} session${e.modelSwitching.autoSessions===1?"":"s"} (${Math.round(t*100)}%)`)}function Rf(o,e,t){let s=o;return e>0&&(s=he(s,2)),e>=.5&&(s=he(s,3)),e>=.8&&t>=5&&(s=4),s}function If(o,e,t,s){return e?(s.push(`Switched models in ${Math.round(t.modelSwitching.switchingFrequency)}% of sessions`),o<4&&(t.modelSwitching.mixedTierSessions>0||t.modelSwitching.mixedCostSessions>0)?he(o,3):o):o}function Uf(o){let e=[],t=Ge.promptEngineering;Df(e,o);let s=o.modeUsage.ask+o.modeUsage.edit+o.modeUsage.agent+o.modeUsage.cli,n=Af(o,e,1);s>=t.stage2MinInteractions&&(n=2);let i=bf(o.toolCalls.byTool);i.length>0&&e.push(`Used slash commands: /${i.join(", /")}`);let r=kf(o.modelSwitching.mixedTierSessions,o.modelSwitching.mixedCostSessions,o.modelSwitching.switchingFrequency),a=Sf(o.modeUsage.agent,o.modeUsage.cli),c=o.modelSwitching.totalSessions>0?o.modelSwitching.autoSessions/o.modelSwitching.totalSessions:0;return Ef(e,o,c),Tf(s,i,a)&&(n=3),wf(s,a,r,i)&&(n=4),n=Rf(n,c,o.sessions),n=If(n,r,o,e),{stage:n,evidence:e,usedSlashCommands:i,hasModelSwitching:r,hasAgentMode:a,autoUsageRatio:c}}function Of(o,e){if(o.length===0)return;let t=e.length>0?` \u2014 try ${e.slice(0,3).join(", ")}`:"";return`Stage 4 needs ${o.join(" and ")}${t}`}function Ff(o,e){let t=o.filter(n=>!n.used).map(n=>n.name);if(t.length===0)return;let s=t.length>3?` and ${t.length-3} more`:"";return`Try ${t.slice(0,3).join(", ")}${s} \u2014 see ${e} to reach Stage 4`}function Nf(o,e,t){let s=Ge.contextEngineering,n=Math.max(0,s.stage4MinRefTypes-e),i=Math.max(0,s.stage4MinTotalRefs-t),r=[{name:"image attachments",used:(o.byKind?.["copilot.image"]??0)>0},{name:"prompt files",used:(o.byKind?.promptFile??0)>0},{name:"custom prompt commands",used:(o.byKind?.prompt??0)>0},{name:"#changes",used:o.changes>0},{name:"#problemsPanel",used:o.problemsPanel>0},{name:"#outputPanel",used:o.outputPanel>0},{name:"#terminalLastCommand",used:o.terminalLastCommand>0},{name:"#terminalSelection",used:o.terminalSelection>0},{name:"#clipboard",used:o.clipboard>0},{name:"@vscode",used:o.vscode>0}];if(r.filter(c=>c.used).length>=2){let c=[{name:"#symbol",used:o.symbol>0},{name:"@workspace",used:o.workspace>0},{name:"#codebase",used:o.codebase>0},{name:"@terminal",used:o.terminal>0},...r].filter(p=>!p.used).map(p=>p.name),d=[];return n>0&&d.push(`${z(e)} of ${s.stage4MinRefTypes} different reference types used`),i>0&&d.push(`${z(t)} of ${s.stage4MinTotalRefs} total references`),Of(d,c)}return Ff(r,"[specialized context variables](https://code.visualstudio.com/docs/copilot/chat/copilot-chat#_add-context-to-your-prompts)")}function Lf(o,e,t){e>0&&o.push(`${z(e)} ${t}`)}function jf(o){let e=[],t=[[o.file,"#file references"],[o.selection,"#selection references"],[o.codebase,"#codebase references"],[o.workspace,"@workspace references"],[o.terminal,"@terminal references"],[o.vscode,"@vscode references"],[o.clipboard,"#clipboard references"],[o.changes,"#changes references"],[o.problemsPanel,"#problemsPanel references"],[o.outputPanel,"#outputPanel references"],[o.terminalLastCommand,"#terminalLastCommand references"],[o.terminalSelection,"#terminalSelection references"],[o.byKind?.promptFile??0,"prompt file uses"],[o.byKind?.prompt??0,"custom prompt commands"],[o.codeContextLines??0,"lines of code context"]];for(let[s,n]of t)Lf(e,s,n);return e}function Gf(o){return[o.file,o.selection,o.symbol,o.codebase,o.workspace,o.terminal,o.vscode,o.clipboard,o.changes,o.problemsPanel,o.outputPanel,o.terminalLastCommand,o.terminalSelection,o.byKind?.["copilot.image"]??0,o.byKind?.promptFile??0,o.byKind?.prompt??0].filter(Boolean).length}function qf(o,e,t){let s=o.byKind["copilot.image"]||0;return s>0&&(e.push(`${z(s)} image references (vision)`),t=he(t,3)),(o.byKind.promptFile||0)>0&&(t=he(t,3)),t}function Bf(o){let e=1,t=Ge.contextEngineering,s=o.contextReferences,n=s.file+s.selection+s.symbol+s.codebase+s.workspace,i=Gf(s),r=jf(s);n>=t.stage2MinTotalRefs&&(e=2),i>=t.stage3MinRefTypes&&n>=t.stage3MinTotalRefs&&(e=3),i>=t.stage4MinRefTypes&&n>=t.stage4MinTotalRefs&&(e=4),e=qf(s,r,e);let a=[];if(e<2&&a.push("Try adding [#file or #selection](https://code.visualstudio.com/docs/copilot/chat/copilot-chat#_add-context-to-your-prompts) references to give Copilot more context"),e<3&&a.push("Explore [@workspace, #codebase, and @terminal](https://code.visualstudio.com/docs/copilot/chat/copilot-chat#_add-context-to-your-prompts) for broader context"),e<4){let c=Nf(s,i,n);c&&a.push(c)}return{stage:e,evidence:r,tips:a}}function zf(o,e,t){return o>=t.stage3MinAgentInteractions&&e>=t.stage3MinNonAutoTools}function $f(o,e,t){return o>=t.stage4MinAgentInteractions&&e>=t.stage4MinNonAutoTools}function Hf(o,e){return!!o&&o.multiFileEdits>=e.stage4MinMultiFileEdits&&o.avgFilesPerSession>=e.stage3MinAvgFilesPerSession}function Wf(o,e,t,s){if(o<e.stage3MinMultiAgentParents)return t;let n=o===1?"1 session":`${z(o)} sessions`;return s.push(`${n} with child workspaces (multi-agent orchestration)`),t=he(t,3),o>=e.stage4MinMultiAgentParents&&(t=he(t,4)),t}function Jf(o,e,t,s){if(o<e.stage3MinDelegationSessions)return t;let n=o===1?"1 session":`${z(o)} sessions`;return s.push(`${n} delegated work to sub-agents (Task/delegate tool calls)`),t=he(t,3),o>=e.stage4MinDelegationSessions&&(t=he(t,4)),t}function Vf(o){let e=[];return o<2&&e.push("Try [agent mode](https://code.visualstudio.com/docs/copilot/agents/overview) \u2014 it can run terminal commands, edit files, and explore your codebase autonomously \u2014 [\u25B6 Agent Mode video](https://tech.hub.ms/github-copilot/videos/agent-mode)"),o<3&&e.push("Use [agent mode](https://code.visualstudio.com/docs/copilot/agents/overview) for multi-step tasks; let it chain tools like file search, terminal, and code edits \u2014 [\u25B6 Agent Mode video](https://tech.hub.ms/github-copilot/videos/agent-mode)"),o<4&&e.push("Try [multi-agent orchestration](https://code.visualstudio.com/docs/copilot/agents/overview): start child sessions from a parent session to run multiple agents in parallel on independent sub-tasks"),e}function Kf(o,e,t){let s=t;return e.modeUsage.agent>0&&(o.push(`${z(e.modeUsage.agent)} agent-mode interactions`),s=2),e.modeUsage.cli>0&&(o.push(`${z(e.modeUsage.cli)} CLI interactions`),s=he(s,2)),e.toolCalls.total>0&&o.push(`${z(e.toolCalls.total)} tool calls executed`),e.modeUsage.edit>0&&o.push(`${z(e.modeUsage.edit)} edit-mode interactions`),s}function Qf(o,e,t,s){if(!e.editScope)return t;let n=t,i=e.editScope.singleFileEdits+e.editScope.multiFileEdits,r=i>0?Math.round(e.editScope.multiFileEdits/i*100):0;return e.editScope.multiFileEdits>0&&(o.push(`${z(e.editScope.multiFileEdits)} multi-file edit sessions (${r}%)`),n=he(n,2)),e.editScope.avgFilesPerSession>=s.stage3MinAvgFilesPerSession&&(o.push(`Avg ${e.editScope.avgFilesPerSession.toFixed(1)} files per edit session`),n=he(n,3)),n}function Yf(o,e,t,s){let n=o;e.agentTypes?.editsAgent&&(s.push(`${z(e.agentTypes.editsAgent)} edits agent sessions`),n=he(n,2));let i=Xc(e.toolCalls.byTool),r=e.modeUsage.agent+e.modeUsage.cli;return zf(r,i,t)&&(n=3),$f(r,i,t)&&(n=4),Hf(e.editScope,t)&&(n=he(n,4)),n=Wf(e.multiAgentParentSessions??0,t,n,s),n=Jf(e.delegationSessions??0,t,n,s),n}function Xf(o,e){let t=Qc(e.toolCalls.byTool);if(t===0)return;let s=e.delegationSessions??0,n=s>0?` (avg ${(t/s).toFixed(1)} per delegating session)`:"";o.push(`${z(t)} sub-agent/delegate tool calls executed${n}`)}function Zf(o){let e=[],t=1,s=Ge.agentic;return t=Kf(e,o,t),t=Qf(e,o,t,s),t=Yf(t,o,s,e),Xf(e,o),{stage:t,evidence:e,tips:Vf(t)}}function Yc(o,e,t){let s=[];return o<2&&s.push("Try [agent mode](https://code.visualstudio.com/docs/copilot/agents/overview) to let Copilot use built-in tools for file operations and terminal commands \u2014 [\u25B6 Agent Mode video](https://tech.hub.ms/github-copilot/videos/agent-mode)"),o<3&&(e.length===0&&!t?s.push("Set up [MCP servers](https://code.visualstudio.com/docs/copilot/customization/mcp-servers) to connect Copilot to external tools (databases, APIs, cloud services) \u2014 [\u25B6 MCP with Azure and GitHub](https://tech.hub.ms/github-copilot/videos/mcp-with-azure-and-github)"):e.length>0&&s.push("Explore [GitHub integrations](https://code.visualstudio.com/docs/copilot/agents/agent-tools) and advanced tools like editFiles and run_in_terminal")),o<4&&(e.length===1?s.push("Add more [MCP servers](https://code.visualstudio.com/docs/copilot/customization/mcp-servers) to expand Copilot's capabilities - check the VS Code MCP registry \u2014 [\u25B6 MCP with Azure and GitHub](https://tech.hub.ms/github-copilot/videos/mcp-with-azure-and-github)"):e.length===0&&!t?s.push("Explore the [VS Code MCP registry](https://code.visualstudio.com/docs/copilot/customization/mcp-servers) for tools that integrate with your workflow"):e.length>0&&s.push("You're using multiple MCP servers - keep exploring advanced tool combinations")),s}function eh(o,e,t){let s=Object.keys(e.toolCalls.byTool).length,n=Xc(e.toolCalls.byTool),i=t;if(n>0){let r=s-n,a=r>0?` (+ ${z(r)} automatic)`:"";o.push(`${z(n)} intentional tools used${a}`),i=2}else s>0&&o.push(`${z(s)} tools used (all automatic \u2014 agent reads/searches)`);return i}function th(o,e,t){return e.agentTypes?.workspaceAgent>0?(o.push(`${z(e.agentTypes.workspaceAgent)} @workspace agent sessions`),he(t,3)):t}function sh(o,e,t,s){let n={github_pull_request:"GitHub Pull Request",github_repo:"GitHub Repository",run_in_terminal:"Run In Terminal",editFiles:"Edit Files",listFiles:"List Files"},i=Object.keys(n).filter(a=>(e.toolCalls.byTool[a]||0)>0),r=t;return i.length>0&&(o.push(`Advanced tools: ${i.map(a=>n[a]).join(", ")}`),i.length>=s.stage3MinAdvancedTools&&(r=he(r,3))),r}function nh(o,e,t,s){let n=Object.keys(e.mcpTools.byServer),i=t;return e.mcpTools.total>0&&(o.push(`${z(e.mcpTools.total)} MCP tool calls across ${n.length} server(s)`),i=he(i,3),n.length>=s.stage4MinMcpServers&&(i=4)),{stage:i,mcpServers:n}}function oh(o,e){let t=[],s=1,n=Ge.toolUsage;s=eh(t,o,s),s=th(t,o,s),s=sh(t,o,s,n);let i=e===!1;if(!i){let{stage:r,mcpServers:a}=nh(t,o,s,n);return s=r,{stage:s,evidence:t,tips:Yc(s,a)}}return{stage:s,evidence:t,tips:Yc(s,[],i)}}function ih(o,e,t){let s=e-t;if(s===0)return"All repos customized! Keep instructions up to date and add [skill files](https://code.visualstudio.com/docs/copilot/customization/agent-skills) or [MCP server configs](https://code.visualstudio.com/docs/copilot/customization/mcp-servers) for deeper integration";let n=`${z(s)} repo${s===1?"":"s"} still missing customization \u2014 add [instructions](https://code.visualstudio.com/docs/copilot/customization/custom-instructions), [agents.md](https://code.visualstudio.com/docs/copilot/customization/custom-instructions), or [MCP configs](https://code.visualstudio.com/docs/copilot/customization/mcp-servers) for full coverage.`,i=(o?.workspaces||[]).filter(a=>Object.values(a.typeStatuses).every(c=>c==="\u274C")).filter(a=>!a.workspacePath.startsWith("<unresolved:")).sort((a,c)=>c.interactionCount!==a.interactionCount?c.interactionCount-a.interactionCount:c.sessionCount-a.sessionCount).slice(0,3);if(i.length===0)return n;let r=i.map(a=>`${a.workspaceName} (${z(a.interactionCount)} interaction${a.interactionCount===1?"":"s"})`).join(`
|
|
81
|
+
`);return`${n}
|
|
82
|
+
|
|
83
|
+
Top repos to customize first:
|
|
84
|
+
${r}`}function rh(o,e,t,s){let n=1;return e>0&&(n=2),o>=s.stage3MinCustomizationRate&&e>=s.stage3MinCustomizedRepos&&(n=3),o>=s.stage4MinCustomizationRate&&e>=s.stage4MinCustomizedRepos&&(n=4),t>=s.stage3MinUniqueModels&&(n=he(n,3)),t>=s.stage4MinUniqueModels&&e>=s.stage4MinCustomizedRepos&&(n=4),n}function ah(o,e,t){let s=[],n=e-t;return o<2&&s.push("Create a [.github/copilot-instructions.md](https://code.visualstudio.com/docs/copilot/customization/custom-instructions) or [CLAUDE.md](https://docs.anthropic.com/en/docs/claude-code/memory) file with project-specific guidelines \u2014 [\u25B6 User Instructions video](https://tech.hub.ms/github-copilot/videos/user-instructions)"),o<3&&s.push("Add [custom instructions](https://code.visualstudio.com/docs/copilot/customization/custom-instructions) to more repositories to standardize your Copilot experience \u2014 [\u25B6 User Instructions video](https://tech.hub.ms/github-copilot/videos/user-instructions)"),o<4&&n>0?s.push(`${z(t)} of ${z(e)} repos have customization \u2014 add [instructions and agents.md](https://code.visualstudio.com/docs/copilot/customization/custom-instructions) to the remaining ${z(n)} repo${n===1?"":"s"} for Stage 4`):o<4&&s.push("Aim for consistent customization across all projects with [instructions and agents.md](https://code.visualstudio.com/docs/copilot/customization/custom-instructions)"),s}function lh(o){return[...new Set([...o.modelSwitching.standardModels,...o.modelSwitching.premiumModels,...o.modelSwitching.lowCostModels,...o.modelSwitching.mediumCostModels,...o.modelSwitching.highCostModels])]}function ch(o,e,t,s){e>0&&o.push(`Worked in ${e} repositor${e===1?"y":"ies"}`),t.length>=s.stage3MinUniqueModels&&o.push(`Used ${t.length} different models`)}function uh(o,e,t){let s=o;return e.modelSwitching.foundryWindowsSessions>0&&(s=he(s,2),t.push(`Used Microsoft Foundry / local models in ${z(e.modelSwitching.foundryWindowsSessions)} session${e.modelSwitching.foundryWindowsSessions===1?"":"s"}`)),e.modelSwitching.unknownProviderSessions>0&&(s=he(s,2),t.push(`Used models from unknown providers in ${z(e.modelSwitching.unknownProviderSessions)} session${e.modelSwitching.unknownProviderSessions===1?"":"s"}`)),s}function dh(o,e,t,s,n){e>=4?o.push(`${z(t)} of ${z(s)} repos customized (${n.stage4MinCustomizationRate*100}%+ with ${n.stage4MinCustomizedRepos}+ repos \u2192 Stage 4)`):e>=3?o.push(`${z(t)} of ${z(s)} repos customized (${n.stage3MinCustomizationRate*100}%+ with ${n.stage3MinCustomizedRepos}+ repos \u2192 Stage 3)`):t>0&&o.push(`${z(t)} of ${z(s)} repos with custom instructions or agents.md`)}function mh(o,e,t,s,n,i,r){let a=[...o];return t.modelSwitching.foundryWindowsSessions===0&&a.unshift("Try the Microsoft Foundry on Windows extension if you want to experiment with local models and offline-friendly workflows"),t.modelSwitching.unknownProviderSessions===0&&s.length<=1&&a.unshift("Try different model providers from the marketplace when you want more specialized or cost-effective options"),e>=4&&a.push(ih(n,i,r)),a}function ph(o,e){let t=[],s=Ge.customization,n=e,i=n?.totalWorkspaces??0,r=i-(n?.workspacesWithIssues??0),a=i>0?r/i:0,c=lh(o),d=rh(a,r,c.length,s);ch(t,i,c,s),d=uh(d,o,t),dh(t,d,r,i,s);let p=ah(d,i,r);return p=mh(p,d,o,c,n,i,r),{stage:d,evidence:t,tips:p}}function gh(o,e,t,s){return o>=s.stage4MinSessions&&e>=s.stage3MinModesUsed&&t>=s.stage3MinContextRefs}function fh(o,e,t,s){let n=[];return o<2&&n.push("Use AI more regularly - even for quick questions \u2014 [\u25B6 Chat in IDE video](https://tech.hub.ms/github-copilot/videos/chat-in-ide)"),o<3&&(e<s.stage3MinModesUsed&&n.push("Combine [ask mode with agent mode](https://code.visualstudio.com/docs/copilot/agents/overview) in your daily workflow \u2014 [\u25B6 Agent Mode video](https://tech.hub.ms/github-copilot/videos/agent-mode)"),t<s.hasExplicitContextMinRefs&&n.push("Use explicit [context references](https://code.visualstudio.com/docs/copilot/chat/copilot-chat#_add-context-to-your-prompts) like #file, @workspace, and #selection")),o<4&&(t<s.stage3MinContextRefs&&n.push("Make explicit context a habit - use [#file, @workspace, and other references](https://code.visualstudio.com/docs/copilot/chat/copilot-chat#_add-context-to-your-prompts) consistently"),n.push("Make AI part of every coding task: planning, coding, testing, and reviewing")),n}function hh(o){return o.contextReferences.file+o.contextReferences.selection+o.contextReferences.symbol+o.contextReferences.codebase+o.contextReferences.workspace}function yh(o){return[o.modeUsage.ask>0,o.modeUsage.agent>0,o.modeUsage.cli>0].filter(Boolean).length}function _h(o,e,t,s){return e.sessions>=s.stage2MinSessions?(o.push(`${z(e.sessions)} sessions in the last 30 days`),2):t}function Ch(o,e,t,s){if(!e.applyUsage||e.applyUsage.totalCodeBlocks<=0)return t;let n=Math.round(e.applyUsage.applyRate);return o.push(`${n}% code block apply rate (${z(e.applyUsage.totalApplies)}/${z(e.applyUsage.totalCodeBlocks)})`),n>=s.stage2MinApplyRatePct?he(t,2):t}function bh(o,e){if(e.sessionDuration&&e.sessionDuration.avgDurationMs>0&&o.push(`Avg ${Math.round(e.sessionDuration.avgDurationMs/6e4)}min session duration`),e.sessionDuration&&e.sessionDuration.activeDurationMs>0&&e.sessions>0){let t=Math.round(e.sessionDuration.activeDurationMs/e.sessions/6e4);o.push(`Avg ${t}min active time (interacting + waiting on the agent)`)}}function kh(o,e,t,s,n){let i=e;return t>=n.stage3MinModesUsed&&(o.push(`Uses ${t} modes (ask/agent/cli)`),i=he(i,3)),s>=n.hasExplicitContextMinRefs&&(o.push(`${z(s)} explicit context references`),s>=n.stage3MinContextRefs&&(i=he(i,3))),i}function Sh(o,e,t,s,n,i){return gh(e.sessions,t,s,n)?(i.push("Deep integration: regular usage with multi-mode and explicit context"),4):o}function Th(o){let e=[],t=1,s=Ge.workflowIntegration;t=_h(e,o,t,s),t=Ch(e,o,t,s),bh(e,o);let n=hh(o),i=yh(o);return t=kh(e,t,i,n,s),t=Sh(t,o,i,n,s,e),{stage:t,evidence:e,tips:fh(t,i,n,s)}}async function Mi(o,e,t=!0,s){let n=await e(t),i=n.last30Days,r=xf(i),a=Bf(i),c=Zf(i),d=oh(i,s),p=ph(i,o),f=Th(i),h=yf([r.stage,a.stage,c.stage,d.stage,p.stage,f.stage]);return{overallStage:h,overallLabel:hf[h]??`Stage ${h}`,categories:[{category:"Prompt Engineering",icon:"\u{1F4AC}",stage:r.stage,evidence:r.evidence,tips:r.tips},{category:"Context Engineering",icon:"\u{1F4CE}",stage:a.stage,evidence:a.evidence,tips:a.tips},{category:"Agentic",icon:"\u{1F916}",stage:c.stage,evidence:c.evidence,tips:c.tips},{category:"Tool Usage",icon:"\u{1F527}",stage:d.stage,evidence:d.evidence,tips:d.tips},{category:"Customization",icon:"\u2699\uFE0F",stage:p.stage,evidence:p.evidence,tips:p.tips},{category:"Workflow Integration",icon:"\u{1F504}",stage:f.stage,evidence:f.evidence,tips:f.tips}],period:i,lastUpdated:n.lastUpdated.toISOString(),agenticTrend:n.agenticDailyTrend}}var wh="hermes/state.db#",Mh="title_generation",Pi=class{_sqlJsModule=null;_sqlJsInitPromise=null;_dbCache=new Map;_dbCacheInflight=new Map;_dbPathOverride=null;dispose(){for(let e of this._dbCache.values())try{e.db.close()}catch{}this._dbCache.clear(),this._dbCacheInflight.clear(),this._sqlJsInitPromise=null}getConfigDir(){let e=process.env.HERMES_HOME;if(e&&e.trim())return e;if(Pn.platform()==="win32"){let t=process.env.LOCALAPPDATA||Os.join(Pn.homedir(),"AppData","Local");return Os.join(t,"hermes")}return Os.join(Pn.homedir(),".hermes")}getDbPath(){return this._dbPathOverride??Os.join(this.getConfigDir(),"state.db")}setDbPathOverrideForTests(e){this._dbPathOverride=e}virtualPath(e){return`${this.getDbPath()}#${e}`}isHermesSessionFile(e){return e.replace(/\\/g,"/").toLowerCase().includes(wh)}getDbPathFromVirtual(e){let t=e.lastIndexOf("state.db#");return t===-1?e:e.substring(0,t+8)}getSessionId(e){let t=e.lastIndexOf("state.db#");return t===-1?null:e.substring(t+9)||null}async statSessionFile(e){return Mn.promises.stat(this.getDbPathFromVirtual(e))}closeDb(e){try{e.close()}catch{}}isMissingFileError(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async statDb(e){try{return await Mn.promises.stat(e)}catch(t){return this.isMissingFileError(t)&&this._dbCache.has(e)&&(this.closeDb(this._dbCache.get(e).db),this._dbCache.delete(e)),null}}isCachedDbCurrent(e,t){let s=this._dbCache.get(e);return!!s&&s.mtimeMs===t.mtimeMs&&s.size===t.size}sameDbStats(e,t){return e.mtimeMs===t.mtimeMs&&e.size===t.size}async refreshDb(e,t){let s;try{let r=await this.initSqlJs(),a=await Mn.promises.readFile(e);s=new r.Database(a)}catch{return this._dbCache.get(e)?.db??null}let n=await this.statDb(e);if(!n||!this.sameDbStats(t,n))return this.closeDb(s),this._dbCache.get(e)?.db??null;let i=this._dbCache.get(e);return i&&this.closeDb(i.db),this._dbCache.set(e,{db:s,mtimeMs:t.mtimeMs,size:t.size}),s}async getDb(e){let t=await this.statDb(e);if(!t)return this._dbCache.get(e)?.db??null;if(this.isCachedDbCurrent(e,t))return this._dbCache.get(e).db;let s=`${e}:${t.mtimeMs}:${t.size}`,n=this._dbCacheInflight.get(s);if(n)return n;let i=this.refreshDb(e,t);this._dbCacheInflight.set(s,i);try{return await i}finally{this._dbCacheInflight.get(s)===i&&this._dbCacheInflight.delete(s)}}async initSqlJs(){return this._sqlJsModule?this._sqlJsModule:(this._sqlJsInitPromise||(this._sqlJsInitPromise=(async()=>{let e=Os.join(__dirname,"sql-wasm.wasm"),t;try{t=await Mn.promises.readFile(e)}catch{}let s=await(0,Zc.default)(t?{wasmBinary:t.buffer}:void 0);return this._sqlJsModule=s,s})().catch(e=>{throw this._sqlJsInitPromise=null,e})),this._sqlJsInitPromise)}rowsToObjects(e){if(e.length===0)return[];let{columns:t,values:s}=e[0];return s.map(n=>{let i={};return t.forEach((r,a)=>{i[r]=n[a]}),i})}async discoverSessionIds(){let e=await this.getDb(this.getDbPath());if(!e)return[];try{let t=e.exec("SELECT id FROM sessions ORDER BY started_at DESC");return this.rowsToObjects(t).map(s=>s.id)}catch{return[]}}async getChildCounts(e){let t=new Map;if(e.length===0)return t;let s=await this.getDb(this.getDbPath());if(!s)return t;try{let n=s.exec(`SELECT parent_session_id, COUNT(*) as child_count FROM sessions
|
|
85
|
+
WHERE parent_session_id IS NOT NULL
|
|
86
|
+
GROUP BY parent_session_id`),i=this.rowsToObjects(n),r=new Set(e);for(let a of i){let c=a.parent_session_id,d=a.child_count??0;c&&r.has(c)&&t.set(c,d)}}catch{}return t}async getMultiAgentParentCount(e,t=Ge.agentic.multiAgentMinChildren){let s=await this.getChildCounts(e),n=0;for(let i of s.values())i>=t&&n++;return n}async readSession(e){let t=this.getSessionId(e);if(!t)return null;let s=await this.getDb(this.getDbPathFromVirtual(e));if(!s)return null;try{let n=s.exec(`SELECT id, source, display_name, model, started_at, ended_at, message_count,
|
|
87
|
+
tool_call_count, input_tokens, output_tokens, cache_read_tokens,
|
|
88
|
+
cache_write_tokens, reasoning_tokens, cwd, git_branch, git_repo_root,
|
|
89
|
+
title, api_call_count, parent_session_id, archived, pinned
|
|
90
|
+
FROM sessions WHERE id = ?`,[t]),i=this.rowsToObjects(n);return i.length===0?null:i[0]}catch{return null}}async getMessages(e){let t=this.getSessionId(e);if(!t)return[];let s=await this.getDb(this.getDbPathFromVirtual(e));if(!s)return[];try{let n=s.exec(`SELECT id, session_id, role, content, tool_call_id, tool_calls, tool_name,
|
|
91
|
+
timestamp, token_count, reasoning, reasoning_content, finish_reason,
|
|
92
|
+
active, compacted
|
|
93
|
+
FROM messages WHERE session_id = ? ORDER BY timestamp ASC, id ASC`,[t]);return this.rowsToObjects(n)}catch{return[]}}async getModelUsageRows(e,t=!1){let s=this.getSessionId(e);if(!s)return[];let n=await this.getDb(this.getDbPathFromVirtual(e));if(!n)return[];try{let i=n.exec(`SELECT session_id, model, task, api_call_count, input_tokens, output_tokens,
|
|
94
|
+
cache_read_tokens, cache_write_tokens, reasoning_tokens
|
|
95
|
+
FROM session_model_usage WHERE session_id = ?`,[s]),r=this.rowsToObjects(i);return t?r:r.filter(a=>(a.task??"")!==Mh)}catch{return[]}}sumUsageRowTokens(e){let t=0,s=0;for(let n of e)t+=(n.input_tokens||0)+(n.output_tokens||0)+(n.cache_read_tokens||0)+(n.cache_write_tokens||0)+(n.reasoning_tokens||0),s+=n.reasoning_tokens||0;return{tokens:t,thinkingTokens:s}}tokensFromSessionRow(e){return e?{tokens:(e.input_tokens||0)+(e.output_tokens||0)+(e.cache_read_tokens||0)+(e.cache_write_tokens||0)+(e.reasoning_tokens||0),thinkingTokens:e.reasoning_tokens||0}:{tokens:0,thinkingTokens:0}}async getTokens(e){let t=await this.getModelUsageRows(e);if(t.length>0)return this.sumUsageRowTokens(t);let s=await this.readSession(e);return this.tokensFromSessionRow(s)}async countInteractions(e){return(await this.getMessages(e)).filter(s=>s.role==="user").length}mergeUsageRowIntoModelUsage(e,t){let s=t.model||"unknown",n=e[s]??{inputTokens:0,outputTokens:0,cachedReadTokens:0,cacheCreationTokens:0};n.inputTokens+=t.input_tokens||0,n.outputTokens+=t.output_tokens||0,n.cachedReadTokens=(n.cachedReadTokens||0)+(t.cache_read_tokens||0),n.cacheCreationTokens=(n.cacheCreationTokens||0)+(t.cache_write_tokens||0),e[s]=n}modelUsageFromSessionRow(e){let t={};if(!e||(e.input_tokens||0)+(e.output_tokens||0)===0)return t;let s=e.model||"unknown";return t[s]={inputTokens:e.input_tokens||0,outputTokens:e.output_tokens||0,cachedReadTokens:e.cache_read_tokens||0,cacheCreationTokens:e.cache_write_tokens||0,sessions:1},t}async getModelUsage(e){let t=await this.getModelUsageRows(e),s={};for(let i of t)this.mergeUsageRowIntoModelUsage(s,i);if(Object.keys(s).length>0)return s;let n=await this.readSession(e);return this.modelUsageFromSessionRow(n)}async resolveTitle(e,t){if(t?.title&&t.title.trim())return t.title.trim();let n=(await this.getMessages(e)).find(r=>r.role==="user"&&r.content&&r.content.trim());if(!n?.content)return;let i=n.content.trim();return i.length>100?i.slice(0,100)+"...":i}parseToolCalls(e){if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}if(!Array.isArray(t))return[];let s=[];for(let n of t){if(typeof n!="object"||n===null)continue;let i=n,r=i.function,a=r?.name||i.name||void 0;if(!a)continue;let c=i.id||i.call_id||null,d=r?.arguments;s.push({id:c,name:a,arguments:typeof d=="string"?d:void 0})}return s}parseToolResultText(e){if(e)try{let t=JSON.parse(e);if(typeof t=="string")return t;if(t&&typeof t=="object"){let s=t;if(typeof s.content=="string")return s.content;if(typeof s.output=="string")return s.output;if(typeof s.result=="string")return s.result}return e}catch{return e}}async getDailyFractions(e){let t=await this.getMessages(e),s={},n=0;for(let r of t){if(!r.timestamp)continue;let a=r.token_count&&r.token_count>0?r.token_count:1,c=L(new Date(r.timestamp*1e3));s[c]=(s[c]||0)+a,n+=a}if(n===0){let r=await this.readSession(e);return{[r?.started_at?L(new Date(r.started_at*1e3)):L(new Date)]:1}}let i={};for(let[r,a]of Object.entries(s))i[r]=a/n;return i}};var Ri=S(require("fs")),vt=S(require("path"));var Ls=S(require("fs"));var Ph=new Set(["edit","create","write","patch","multiedit","notebookedit","editfiles","edit_files","edit_file","apply_patch","applypatch","create_file","createfile","write_file","writefile","insert_edit_into_file","insertedit","replace_string_in_file","replacestring","edit_notebook_file","editnotebook","str_replace_editor","str_replace","copilot_editfiles","copilot_editfile","copilot_writefile","copilot_applypatch","copilot_createfile","copilot_insertedit","copilot_replacestring","copilot_editnotebook","write_to_file","replace_in_file","apply_diff","replace","fswrite","fsappend","strreplace","windsurf_file_edit","windsurf_file_create"]);function vh(o){return Ph.has(o.toLowerCase())}var Ah=["file_path","filePath","path","absolute_path","absolutePath","target_file","targetFile","file","filename","fileName","notebook_path"];function xh(o){if(!o)return null;let e;try{e=JSON.parse(o)}catch{return null}if(!e||typeof e!="object")return null;let t=e;for(let n of Ah){let i=t[n];if(typeof i=="string"&&i)return i}let s=t.uri;if(s&&typeof s=="object"){let n=s;if(typeof n.fsPath=="string"&&n.fsPath)return n.fsPath;if(typeof n.path=="string"&&n.path)return n.path}return null}function Dh(){return{calls:0,editTurns:0,oneShotEditTurns:0,retries:0,selfCorrections:0,editToolCalls:0,inputTokens:0,outputTokens:0,cachedReadTokens:0,cost:0}}function eu(o,e){return o[e]||(o[e]=Dh()),o[e]}function Eh(o,e){let t=0,s=0,n=0,i=new Set,r=null,a=0;for(let c of o){if(!vh(c.toolName)){r=null;continue}t++;let d=xh(c.arguments)??`\0unknown-${a++}`;i.has(d)&&(r===d?s++:n++),i.add(d),r=d}e.editToolCalls+=t,t>0&&(e.editTurns++,e.retries+=s,e.selfCorrections+=n,s===0&&n===0&&e.oneShotEditTurns++)}function vi(o){let e={};for(let t of o){let s=t.model||"unknown",n=eu(e,s);n.calls++,Eh(t.toolCalls??[],n)}return e}function tu(o){let e=[];if(!o.response||!Array.isArray(o.response))return e;for(let t of o.response)if(!(!t||typeof t!="object"))if(t.kind==="textEditGroup"){let s=t.uri?.fsPath||t.uri?.path;e.push({toolName:"edit",arguments:s?JSON.stringify({path:s}):void 0})}else(t.kind==="toolInvocationSerialized"||t.kind==="prepareToolInvocation")&&e.push({toolName:"toolInvocation"});return e}function su(o,e){if(e)for(let[t,s]of Object.entries(e)){let n=eu(o,t);n.calls+=s.calls,n.editTurns+=s.editTurns,n.oneShotEditTurns+=s.oneShotEditTurns,n.retries+=s.retries,n.selfCorrections+=s.selfCorrections,n.editToolCalls+=s.editToolCalls,n.inputTokens+=s.inputTokens,n.outputTokens+=s.outputTokens,n.cachedReadTokens+=s.cachedReadTokens,n.cost+=s.cost}}var Ai=S(require("fs")),zt=S(require("path")),cu=S(require("os")),uu=require("worker_threads");var vn=S(require("fs")),ra=S(require("path")),nu=S(require("os")),ou=S(Nt());function aa(o){return o?o.replace(/\\/g,"/").toLowerCase().includes("/microsoft scout"):!1}function iu(o){return o==="github/autopilot"}function Rh(o){if(typeof o!="object"||o===null)return!1;let e=o;return typeof e.id=="string"&&(e.cwd===null||typeof e.cwd=="string")&&(e.repository===null||typeof e.repository=="string")&&(e.branch===null||typeof e.branch=="string")&&(e.summary===null||typeof e.summary=="string")&&(e.created_at===null||typeof e.created_at=="string")&&(e.updated_at===null||typeof e.updated_at=="string")}function Ih(o){if(typeof o!="object"||o===null)return!1;let e=o;return typeof e.session_id=="string"&&typeof e.turn_index=="number"&&(e.user_message===null||typeof e.user_message=="string")&&(e.assistant_response===null||typeof e.assistant_response=="string")&&(e.timestamp===null||typeof e.timestamp=="string")}var Fs=class{_sqlJsModule=null;_sqlJsInitPromise=null;_initSqlJsFn;_dbCache=new Map;_dbCacheInflight=new Map;_sessionsCache=new Map;_sessionsCacheInflight=new Map;_turnCountsCache=new Map;_turnCountsCacheInflight=new Map;constructor(e){this._initSqlJsFn=e??ou.default}dispose(){for(let e of this._dbCache.values())try{e.db.close()}catch{}this._dbCache.clear(),this._dbCacheInflight.clear(),this._sessionsCache.clear(),this._sessionsCacheInflight.clear(),this._turnCountsCache.clear(),this._turnCountsCacheInflight.clear(),this._sqlJsInitPromise=null}closeDb(e){try{e.close()}catch{}}isMissingFileError(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async statDb(e){try{return await vn.promises.stat(e)}catch(t){return this.isMissingFileError(t)&&this._dbCache.has(e)&&(this.closeDb(this._dbCache.get(e).db),this._dbCache.delete(e)),null}}isCachedDbCurrent(e,t){let s=this._dbCache.get(e);return!!s&&s.mtimeMs===t.mtimeMs&&s.size===t.size}getDbCacheKey(e,t){return`${e}:${t.mtimeMs}:${t.size}`}sameDbStats(e,t){return e.mtimeMs===t.mtimeMs&&e.size===t.size}async refreshDb(e,t){let s;try{let r=await this.initSqlJs(),a=await vn.promises.readFile(e);s=new r.Database(a)}catch{return this._dbCache.get(e)?.db??null}let n=await this.statDb(e);if(!n||!this.sameDbStats(t,n))return this.closeDb(s),this._dbCache.get(e)?.db??null;let i=this._dbCache.get(e);return i&&this.closeDb(i.db),this._dbCache.set(e,{db:s,mtimeMs:t.mtimeMs,size:t.size}),s}async getDb(e){let t=await this.statDb(e);if(!t)return this._dbCache.get(e)?.db??null;if(this.isCachedDbCurrent(e,t))return this._dbCache.get(e).db;let s=this.getDbCacheKey(e,t),n=this._dbCacheInflight.get(s);if(n)return n;let i=this.refreshDb(e,t);this._dbCacheInflight.set(s,i);try{return await i}finally{this._dbCacheInflight.get(s)===i&&this._dbCacheInflight.delete(s)}}getDbPath(){return ra.join(nu.homedir(),".copilot","session-store.db")}virtualPath(e){return`${this.getDbPath()}#${e}`}isCliStoreSession(e){return e.includes("session-store.db#")}getDbPathFromVirtual(e){let t=e.indexOf("session-store.db#");return t===-1?e:e.substring(0,t+16)}getSessionId(e){let t=e.indexOf("session-store.db#");return t===-1?null:e.substring(t+17)||null}async getSessionsMap(e){let t=await this.statDb(e);if(!t)return this._sessionsCache.get(e)?.byId??new Map;let s=this._sessionsCache.get(e);if(s&&s.mtimeMs===t.mtimeMs&&s.size===t.size)return s.byId;let n=`${e}:${t.mtimeMs}:${t.size}`,i=this._sessionsCacheInflight.get(n);if(i)return i;let r=(async()=>{let a=await this.getDb(e),c=new Map;if(a)try{let d=a.exec("SELECT id, cwd, repository, branch, summary, created_at, updated_at FROM sessions");if(d.length>0){let p=d[0].columns;for(let f of d[0].values){let h={};p.forEach((_,C)=>{h[_]=f[C]}),Rh(h)&&c.set(h.id,h)}}}catch{}return this._sessionsCache.set(e,{mtimeMs:t.mtimeMs,size:t.size,byId:c}),c})();this._sessionsCacheInflight.set(n,r);try{return await r}finally{this._sessionsCacheInflight.get(n)===r&&this._sessionsCacheInflight.delete(n)}}async getTurnCountsMap(e){let t=await this.statDb(e);if(!t)return this._turnCountsCache.get(e)?.byId??new Map;let s=this._turnCountsCache.get(e);if(s&&s.mtimeMs===t.mtimeMs&&s.size===t.size)return s.byId;let n=`${e}:${t.mtimeMs}:${t.size}`,i=this._turnCountsCacheInflight.get(n);if(i)return i;let r=(async()=>{let a=await this.getDb(e),c=new Map;if(a)try{let d=a.exec("SELECT session_id, COUNT(*) FROM turns GROUP BY session_id");if(d.length>0)for(let p of d[0].values)c.set(p[0],p[1]||0)}catch{}return this._turnCountsCache.set(e,{mtimeMs:t.mtimeMs,size:t.size,byId:c}),c})();this._turnCountsCacheInflight.set(n,r);try{return await r}finally{this._turnCountsCacheInflight.get(n)===r&&this._turnCountsCacheInflight.delete(n)}}async stat(e){let t=this.getDbPathFromVirtual(e),s=this.getSessionId(e),n=await vn.promises.stat(t),i=s?(await this.getSessionsMap(t)).get(s):void 0,r=i?.updated_at?new Date(i.updated_at):null;return!r||Number.isNaN(r.getTime())||Object.defineProperty(n,"mtime",{value:r,writable:!1}),n}async initSqlJs(){return this._sqlJsModule?this._sqlJsModule:(this._sqlJsInitPromise||(this._sqlJsInitPromise=(async()=>{let e=ra.join(__dirname,"sql-wasm.wasm"),t;try{t=await vn.promises.readFile(e)}catch{}let s=await this._initSqlJsFn(t?{wasmBinary:t.buffer}:void 0);return this._sqlJsModule=s,s})().catch(e=>{throw this._sqlJsInitPromise=null,e})),this._sqlJsInitPromise)}async discoverNewSessions(e){let t=this.getDbPath(),s=await this.getDb(t);if(!s)return[];try{let n=s.exec("SELECT id FROM sessions ORDER BY updated_at DESC");return n.length===0?[]:n[0].values.map(i=>i[0]).filter(i=>!e.has(i))}catch{return[]}}async discoverNewSessionsWithCwd(e){let t=this.getDbPath(),s=await this.getDb(t);if(!s)return[];try{let n=s.exec("SELECT id, cwd FROM sessions ORDER BY updated_at DESC");return n.length===0?[]:n[0].values.filter(i=>!e.has(i[0])).map(i=>({id:i[0],cwd:i[1]??null}))}catch{return[]}}async readSession(e){let t=this.getDbPathFromVirtual(e),s=this.getSessionId(e);return s?(await this.getSessionsMap(t)).get(s)??null:null}async getTurns(e){let t=this.getDbPathFromVirtual(e),s=this.getSessionId(e);if(!s)return[];let n=await this.getDb(t);if(!n)return[];try{let i=n.exec("SELECT session_id, turn_index, user_message, assistant_response, timestamp FROM turns WHERE session_id = ? ORDER BY turn_index ASC",[s]);if(i.length===0)return[];let r=i[0].columns,a=[];for(let c of i[0].values){let d={};r.forEach((p,f)=>{d[p]=c[f]}),Ih(d)&&a.push(d)}return a}catch{return[]}}async countTurns(e){let t=this.getDbPathFromVirtual(e),s=this.getSessionId(e);return s?(await this.getTurnCountsMap(t)).get(s)??0:0}async getSessionUsage(e){let t=this.getDbPath(),s=await this.getDb(t);if(!s)return null;try{let n=s.exec("SELECT model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, total_nano_aiu FROM assistant_usage_events WHERE session_id = ?",[e]);return n.length?this.aggregateUsageEvents(n[0].columns,n[0].values):null}catch{return null}}parseUsageEventRow(e,t){let s={};return e.forEach((n,i)=>{s[n]=t[i]}),{model:typeof s.model=="string"?s.model:"unknown",inputTokens:typeof s.input_tokens=="number"?s.input_tokens:0,outputTokens:typeof s.output_tokens=="number"?s.output_tokens:0,cacheReadTokens:typeof s.cache_read_tokens=="number"?s.cache_read_tokens:0,cacheWriteTokens:typeof s.cache_write_tokens=="number"?s.cache_write_tokens:0,nanoAiu:typeof s.total_nano_aiu=="number"?s.total_nano_aiu:0}}addUsageEventToModelUsage(e,t){e[t.model]||(e[t.model]={inputTokens:0,outputTokens:0,sessions:0});let s=e[t.model];s.inputTokens+=t.inputTokens,s.outputTokens+=t.outputTokens,t.cacheReadTokens>0&&(s.cachedReadTokens=(s.cachedReadTokens??0)+t.cacheReadTokens),t.cacheWriteTokens>0&&(s.cacheCreationTokens=(s.cacheCreationTokens??0)+t.cacheWriteTokens)}aggregateUsageEvents(e,t){let s={},n=0,i=0,r=0;for(let a of t){let c=this.parseUsageEventRow(e,a);this.addUsageEventToModelUsage(s,c),n+=c.inputTokens+c.outputTokens,i+=c.cacheReadTokens,r+=c.nanoAiu}return n===0&&i===0&&r===0?null:{modelUsage:s,actualTokens:n,cacheReadTokens:i,nanoAiu:r}}async getDailyFractions(e){let t=await this.getTurns(e),s={},n=0;for(let r of t)if(r.timestamp)try{let a=L(new Date(r.timestamp));s[a]=(s[a]||0)+1,n++}catch{}if(n===0){let r=await this.readSession(e);return{[r?.updated_at?L(new Date(r.updated_at)):L(new Date)]:1}}let i={};for(let[r,a]of Object.entries(s))i[r]=a/n;return i}};var ru=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Uh(){return zt.join(cu.homedir(),".copilot","otel")}function Ns(o){let e=o.lastIndexOf("#");if(e!==-1&&o.slice(0,e).endsWith(".db")){let t=o.slice(e+1);return ru.test(t)?t:null}if(o.includes("session-state")){let t=zt.basename(zt.dirname(o));return ru.test(t)?t:null}return null}function Oh(o){let e=t=>typeof t=="number"?t:0;return{model:o?.["gen_ai.response.model"]||o?.["gen_ai.request.model"]||"unknown",input:e(o?.["gen_ai.usage.input_tokens"]),output:e(o?.["gen_ai.usage.output_tokens"]),cacheCreation:e(o?.["gen_ai.usage.cache_creation.input_tokens"]),cacheRead:e(o?.["gen_ai.usage.cache_read.input_tokens"]),nanoAiu:e(o?.["github.copilot.nano_aiu"])}}function Fh(o,e,t){o.has(e)||o.set(e,{modelUsage:{},actualTokens:0,cacheReadTokens:0,nanoAiu:0});let s=o.get(e);s.modelUsage[t.model]||(s.modelUsage[t.model]={inputTokens:0,outputTokens:0,sessions:0});let n=s.modelUsage[t.model];n.inputTokens+=t.input,n.outputTokens+=t.output,t.cacheCreation>0&&(n.cacheCreationTokens=(n.cacheCreationTokens??0)+t.cacheCreation),t.cacheRead>0&&(n.cachedReadTokens=(n.cachedReadTokens??0)+t.cacheRead),s.actualTokens+=t.input+t.output,s.cacheReadTokens+=t.cacheRead,s.nanoAiu+=t.nanoAiu}var du='"name":"chat ',Nh=10;function Lh(o,e){if(o.type!=="span"||!o.name?.startsWith("chat "))return;let t=o.attributes?.["gen_ai.conversation.id"];t&&Fh(e,t,Oh(o.attributes))}function jh(o){if(!o.includes(du))return null;try{return JSON.parse(o)}catch{return null}}function Gh(o){let e=o;return{records:Array.isArray(e?.records)?e.records:[],consumed:e?.consumed&&typeof e.consumed=="object"?e.consumed:{}}}var qh=`
|
|
81
96
|
const { parentPort, workerData } = require('worker_threads');
|
|
82
97
|
const fs = require('fs');
|
|
83
98
|
const path = require('path');
|
|
84
|
-
const HINT = Buffer.from(${JSON.stringify(
|
|
99
|
+
const HINT = Buffer.from(${JSON.stringify(du)});
|
|
85
100
|
const NL = 0x0a;
|
|
86
101
|
function readRange(full, start, end) {
|
|
87
102
|
return new Promise((resolve) => {
|
|
@@ -120,54 +135,51 @@ async function run() {
|
|
|
120
135
|
parentPort.postMessage({ records, consumed });
|
|
121
136
|
}
|
|
122
137
|
run().catch(() => { try { parentPort.postMessage({ records: [], consumed: {} }); } catch { /* worker tearing down */ } });
|
|
123
|
-
`;function
|
|
124
|
-
`)){let c=
|
|
125
|
-
`:"")+n.value)}return t}function
|
|
126
|
-
`)?0:1);t.linesAdded+=n,t.languageUsage[e]||(t.languageUsage[e]={linesAdded:0,linesRemoved:0}),t.languageUsage[e].linesAdded+=n}if(s.range&&typeof s.range.startLineNumber=="number"&&typeof s.range.endLineNumber=="number"){let n=Math.max(0,s.range.endLineNumber-s.range.startLineNumber);t.linesRemoved+=n,t.languageUsage[e]||(t.languageUsage[e]={linesAdded:0,linesRemoved:0}),t.languageUsage[e].linesRemoved+=n}}function sh(o,e,t){for(let s of o)if(Array.isArray(s))for(let n of s)th(n,e,t)}function nh(o,e){if(!o.uri)return;let t=o.uri.path||JSON.stringify(o.uri);e.editedFilePaths.push(t);let s=ra(t),n=o;Array.isArray(n.edits)&&sh(n.edits,s,e)}function oh(o){let e={editedFilePaths:[],codeBlocks:0,applies:0,linesAdded:0,linesRemoved:0,languageUsage:{}};if(!o.response||!Array.isArray(o.response))return e;for(let t of o.response)t&&(t.kind==="textEditGroup"&&nh(t,e),t.kind==="codeblockUri"&&(e.codeBlocks++,t.isEdit===!0&&e.applies++));return e}function ih(o,e){for(let[t,s]of Object.entries(e))o[t]||(o[t]={linesAdded:0,linesRemoved:0}),o[t].linesAdded+=s.linesAdded,o[t].linesRemoved+=s.linesRemoved}function rh(o,e,t,s,n){o.timestamp!==void 0&&e.push(o.timestamp),o.timings&&t.push(o.timings),o.waitTime!==void 0&&s.push(o.waitTime),o.timestamp!==void 0&&o.timings?.totalElapsed!==void 0&&n.push({start:o.timestamp,end:o.timestamp+o.timings.totalElapsed})}function uu(o,e,t,s,n,i,r){let a=0,c=0,m=0,p=0,f={};for(let h of o){if(!h)continue;rh(Zf(h),s,n,i,r);let _=eh(h);_.agentType!==null&&e[_.agentType]++;let C=oh(h);for(let S of C.editedFilePaths)t.add(S);c+=C.codeBlocks,a+=C.applies,m+=C.linesAdded,p+=C.linesRemoved,ih(f,C.languageUsage)}return{totalApplies:a,totalCodeBlocks:c,totalLinesAdded:m,totalLinesRemoved:p,languageUsage:f}}function ah(o,e,t){if(!(!o.response||!Array.isArray(o.response))){for(let s of o.response)if(s&&(s.kind==="toolInvocationSerialized"||s.kind==="prepareToolInvocation")){let n=s.toolId||s.toolName||s.invocationMessage?.toolName||s.toolSpecificData?.kind||"unknown";ia(n,e,t)}}}function lh(o,e,t,s){e.requestId&&(cu(t,s.modeUsage),e.agent?.id&&(s.toolCalls.total++,s.toolCalls.byTool[e.agent.id]=(s.toolCalls.byTool[e.agent.id]||0)+1),ca(e,s.contextReferences),ah(e,s,o.toolNameMap))}function du(o,e,t){return o.modelId?o.modelId.replace(/^copilot\//,""):o.result?.metadata?.modelId?o.result.metadata.modelId.replace(/^copilot\//,""):o.result?.details?Nt(o,t):e}function ch(o){let e=0;for(let t=1;t<o.length;t++)o[t]!==o[t-1]&&e++;return e}function mu(o){let e=o.selectedModel,t=o.inputState?.selectedModel;return(e?.identifier||e?.metadata?.id||t?.identifier||t?.metadata?.id||"gpt-4o").replace(/^copilot\//,"")}function uh(o,e,t,s){let n=mu(e),i=e.selectedModel,r=e.inputState?.selectedModel;(i?.identifier||r?.identifier||"").replace(/^copilot\//,"")==="auto"&&(s.modelSwitching.autoSessions=1);let c=[];for(let p of t){if(!p||!p.requestId)continue;let f=du(p,n,o.modelPricing);c.push(f);let h=f.toLowerCase();h.includes("foundry")&&(h.includes("microsoft")||h.includes("aitk"))&&(s.modelSwitching.foundryWindowsSessions=1)}let m=[...new Set(c)];s.modelSwitching.uniqueModels=m,s.modelSwitching.modelCount=m.length,s.modelSwitching.totalRequests=c.length,s.modelSwitching.switchCount=ch(c),ee(o.modelPricing,m,c,s)}function dh(o,e,t){let{effortByRequestId:s,defaultEffort:n,switchCount:i}=Yl(o);if(n===null&&s.size===0)return;let r={};for(let[,a]of s)r[a]=(r[a]||0)+1;s.size===0&&n!==null&&(r[n]=e.length),t.thinkingEffort={byEffort:r,switchCount:i,defaultEffort:n}}function mh(o,e,t,s){let n=e.inputState?.mode?xo(e.inputState.mode):"ask";if(e.inputState?.selections&&Array.isArray(e.inputState.selections)){for(let r of e.inputState.selections)if(r&&(r.startLineNumber!==r.endLineNumber||r.startColumn!==r.endColumn)){s.contextReferences.implicitSelection++;break}}let i=e.requests??[];for(let r of i)lh(o,r,n,s);uh(o,e,i,s),dh(t,i,s),pu(i,mu(e),o.modelPricing,s),la(s)}function ph(o){return(o.selectedModel?.identifier||o.selectedModel?.metadata?.id||"unknown").replace(/^copilot\//,"")}function pu(o,e,t,s){let n=[];for(let i of o)i&&n.push({model:du(i,e,t),toolCalls:zc(i)});n.length!==0&&(s.modelEfficiency=ki(n))}function gh(o,e){if(o.agent?.id){let t=o.agent.id.toLowerCase();if(t.includes("edit"))return"edit";if(t.includes("agent"))return"agent"}if(e.mode?.id){let t=e.mode.id.toLowerCase();if(t.includes("agent"))return"agent";if(t.includes("edit"))return"edit"}return"ask"}function fh(o,e,t){if(o.kind==="toolInvocationSerialized"||o.kind==="prepareToolInvocation"){let s=o.toolId||o.toolName||o.invocationMessage?.toolName||"unknown";ia(s,e,t.toolNameMap)}if(o.kind==="mcpServersStarting"&&o.didStartServerIds)for(let s of o.didStartServerIds)e.mcpTools.total++,e.mcpTools.byServer[s]=(e.mcpTools.byServer[s]||0)+1;o.kind==="inlineReference"&&o.inlineReference&&aa([o],e.contextReferences)}function hh(o,e,t,s){let n=gh(e,t);if(n==="agent"?s.modeUsage.agent++:n==="edit"?s.modeUsage.edit++:s.modeUsage.ask++,ca(e,s.contextReferences),e.response&&Array.isArray(e.response))for(let i of e.response)i&&fh(i,s,o)}function yh(o,e,t){if(!(!e.requests||!Array.isArray(e.requests)))for(let s of e.requests)hh(o,s,e,t)}function _h(o,e){for(let t of e.tiers.standard)o.modelSwitching.standardModels.includes(t)||o.modelSwitching.standardModels.push(t);for(let t of e.tiers.premium)o.modelSwitching.premiumModels.includes(t)||o.modelSwitching.premiumModels.push(t);for(let t of e.tiers.unknown)o.modelSwitching.unknownModels.includes(t)||o.modelSwitching.unknownModels.push(t)}function ru(o,e){for(let t of e??[])o.includes(t)||o.push(t)}function Ch(o,e){for(let t of e.costBuckets?.low??[])o.modelSwitching.lowCostModels.includes(t)||o.modelSwitching.lowCostModels.push(t);for(let t of e.costBuckets?.medium??[])o.modelSwitching.mediumCostModels.includes(t)||o.modelSwitching.mediumCostModels.push(t);for(let t of e.costBuckets?.high??[])o.modelSwitching.highCostModels.includes(t)||o.modelSwitching.highCostModels.push(t)}function bh(o){let e=o.modelSwitching.modelsPerSession;e.length!==0&&(o.modelSwitching.averageModelsPerSession=e.reduce((t,s)=>t+s,0)/e.length,o.modelSwitching.maxModelsPerSession=Math.max(...e),o.modelSwitching.minModelsPerSession=Math.min(...e),o.modelSwitching.switchingFrequency=e.filter(t=>t>1).length/e.length*100)}function kh(o,e){if(e.modelSwitching||(e.modelSwitching={uniqueModels:[],modelCount:0,switchCount:0,autoSessions:0,foundryWindowsSessions:0,unknownProviderSessions:0,selectedModelExtensions:[],unknownProviderModels:[],tiers:{standard:[],premium:[],unknown:[]},hasMixedTiers:!1,standardRequests:0,premiumRequests:0,unknownRequests:0,totalRequests:0,costBuckets:{low:[],medium:[],high:[],unknown:[]},hasMixedCosts:!1,lowCostRequests:0,mediumCostRequests:0,highCostRequests:0}),e.modelSwitching.modelCount<=0)return;let t=e.modelSwitching;o.modelSwitching.totalSessions++,o.modelSwitching.modelsPerSession.push(t.modelCount),_h(o,t),Ch(o,t),o.modelSwitching.autoSessions+=t.autoSessions||0,o.modelSwitching.foundryWindowsSessions+=t.foundryWindowsSessions||0,o.modelSwitching.unknownProviderSessions+=t.unknownProviderSessions||0,ru(o.modelSwitching.selectedModelExtensions,t.selectedModelExtensions),ru(o.modelSwitching.unknownProviderModels,t.unknownProviderModels),t.hasMixedTiers&&o.modelSwitching.mixedTierSessions++,t.hasMixedCosts&&o.modelSwitching.mixedCostSessions++,o.modelSwitching.standardRequests+=t.standardRequests||0,o.modelSwitching.premiumRequests+=t.premiumRequests||0,o.modelSwitching.unknownRequests+=t.unknownRequests||0,o.modelSwitching.lowCostRequests+=t.lowCostRequests||0,o.modelSwitching.mediumCostRequests+=t.mediumCostRequests||0,o.modelSwitching.highCostRequests+=t.highCostRequests||0,o.modelSwitching.totalRequests+=t.totalRequests||0,bh(o)}function Sh(o,e){if(e.thinkingEffort){o.thinkingEffortUsage||(o.thinkingEffortUsage={byEffort:{},sessionCount:0,switchCount:0}),o.thinkingEffortUsage.sessionCount++,o.thinkingEffortUsage.switchCount+=e.thinkingEffort.switchCount;for(let[t,s]of Object.entries(e.thinkingEffort.byEffort))o.thinkingEffortUsage.byEffort[t]=(o.thinkingEffortUsage.byEffort[t]||0)+s}}var wh=["file","selection","implicitSelection","symbol","codebase","workspace","terminal","vscode","terminalLastCommand","terminalSelection","clipboard","changes","outputPanel","problemsPanel","pullRequest","copilotInstructions","agentsMd"];function au(o,e){for(let[t,s]of Object.entries(e))o[t]=(o[t]||0)+s}function Th(o,e){let t=o.contextReferences,s=e.contextReferences;for(let n of wh)t[n]+=s[n]||0;t.codeContextLines=(t.codeContextLines||0)+(s.codeContextLines||0),au(t.byKind,s.byKind),au(t.byPath,s.byPath)}function Mh(o,e){if(e.editScope){o.editScope.singleFileEdits+=e.editScope.singleFileEdits,o.editScope.multiFileEdits+=e.editScope.multiFileEdits,o.editScope.totalEditedFiles+=e.editScope.totalEditedFiles;let t=o.editScope.singleFileEdits+o.editScope.multiFileEdits;o.editScope.avgFilesPerSession=t>0?o.editScope.totalEditedFiles/t:0}if(e.applyUsage&&(o.applyUsage.totalApplies+=e.applyUsage.totalApplies,o.applyUsage.totalCodeBlocks+=e.applyUsage.totalCodeBlocks,o.applyUsage.applyRate=o.applyUsage.totalCodeBlocks>0?o.applyUsage.totalApplies/o.applyUsage.totalCodeBlocks*100:0),e.sessionDuration){o.sessionDuration.totalDurationMs+=e.sessionDuration.totalDurationMs,o.sessionDuration.activeDurationMs+=e.sessionDuration.activeDurationMs;let t=o.sessions;if(t>0){o.sessionDuration.avgDurationMs=o.sessionDuration.totalDurationMs/t;let s=o.sessionDuration.avgFirstProgressMs*(t-1);o.sessionDuration.avgFirstProgressMs=(s+e.sessionDuration.avgFirstProgressMs)/t;let n=o.sessionDuration.avgTotalElapsedMs*(t-1);o.sessionDuration.avgTotalElapsedMs=(n+e.sessionDuration.avgTotalElapsedMs)/t;let i=o.sessionDuration.avgWaitTimeMs*(t-1);o.sessionDuration.avgWaitTimeMs=(i+e.sessionDuration.avgWaitTimeMs)/t}}if(e.conversationPatterns){o.conversationPatterns.multiTurnSessions+=e.conversationPatterns.multiTurnSessions,o.conversationPatterns.singleTurnSessions+=e.conversationPatterns.singleTurnSessions,o.conversationPatterns.maxTurnsInSession=Math.max(o.conversationPatterns.maxTurnsInSession,e.conversationPatterns.maxTurnsInSession);let t=o.conversationPatterns.multiTurnSessions+o.conversationPatterns.singleTurnSessions;if(t>0){let n=o.conversationPatterns.avgTurnsPerSession*(t-1)+e.conversationPatterns.avgTurnsPerSession;o.conversationPatterns.avgTurnsPerSession=n/t}}e.agentTypes&&(o.agentTypes.editsAgent+=e.agentTypes.editsAgent,o.agentTypes.defaultAgent+=e.agentTypes.defaultAgent,o.agentTypes.workspaceAgent+=e.agentTypes.workspaceAgent,o.agentTypes.other+=e.agentTypes.other),Sh(o,e),Ph(o,e)}function Ph(o,e){e.modelEfficiency&&(o.modelEfficiency||(o.modelEfficiency={}),$c(o.modelEfficiency,e.modelEfficiency))}function En(o,e){o.toolCalls.total+=e.toolCalls.total;for(let[t,s]of Object.entries(e.toolCalls.byTool))o.toolCalls.byTool[t]=(o.toolCalls.byTool[t]||0)+s;if(e.toolCalls.outputTokensByTool){o.toolCalls.outputTokensByTool||(o.toolCalls.outputTokensByTool={});for(let[t,s]of Object.entries(e.toolCalls.outputTokensByTool))o.toolCalls.outputTokensByTool[t]=(o.toolCalls.outputTokensByTool[t]||0)+s}o.modeUsage.ask+=e.modeUsage.ask,o.modeUsage.edit+=e.modeUsage.edit,o.modeUsage.agent+=e.modeUsage.agent,o.modeUsage.plan+=e.modeUsage.plan,o.modeUsage.customAgent+=e.modeUsage.customAgent,o.modeUsage.cli+=e.modeUsage.cli,Th(o,e),o.mcpTools.total+=e.mcpTools.total;for(let[t,s]of Object.entries(e.mcpTools.byServer))o.mcpTools.byServer[t]=(o.mcpTools.byServer[t]||0)+s;for(let[t,s]of Object.entries(e.mcpTools.byTool))o.mcpTools.byTool[t]=(o.mcpTools.byTool[t]||0)+s;kh(o,e),Mh(o,e)}var vh=[[/#file/gi,"file"],[/#selection/gi,"selection"],[/#symbol/gi,"symbol"],[/#sym(?![:\w])/gi,"symbol"],[/#codebase/gi,"codebase"],[/#terminalLastCommand/gi,"terminalLastCommand"],[/#terminalSelection/gi,"terminalSelection"],[/#clipboard/gi,"clipboard"],[/#changes/gi,"changes"],[/#outputPanel/gi,"outputPanel"],[/#problemsPanel\b/gi,"problemsPanel"],[/#pr\b/gi,"pullRequest"],[/#pullRequest\b/gi,"pullRequest"],[/@workspace/gi,"workspace"],[/@terminal/gi,"terminal"],[/@vscode/gi,"vscode"]];function gu(o,e){for(let[t,s]of vh){let n=o.match(t);n&&(e[s]+=n.length)}}function Ah(o){let e=o.kind;return e==="reference"&&o.reference?o.reference:e==="inlineReference"&&o.inlineReference?o.inlineReference:null}function xh(o,e,t){e.endsWith("/.github/copilot-instructions.md")||e.includes(".github/copilot-instructions.md")?t.copilotInstructions++:e.endsWith("/agents.md")||e.match(/\/agents\.md$/i)?t.agentsMd++:e.endsWith(".instructions.md")||e.includes(".instructions.md")?t.copilotInstructions++:t.file++;let s=o.length>100?"..."+o.substring(o.length-97):o;t.byPath[s]=(t.byPath[s]||0)+1}function Dh(o,e,t){let s=o.fsPath||o.path;typeof s=="string"&&xh(s,Y(s),t);let n=o.name;if(typeof n=="string"&&e==="reference"){t.symbol++;let i=`#sym:${n}`;t.byPath[i]=(t.byPath[i]||0)+1}}function aa(o,e){if(Array.isArray(o))for(let t of o){if(!t||typeof t!="object")continue;let s=t,n=s.kind;if(typeof n=="string"&&(e.byKind[n]=(e.byKind[n]||0)+1),n==="pullRequest"){e.pullRequest++;continue}let i=Ah(s);i&&Dh(i,n,e)}}function Eh(o,e){let t=o.kind;if(typeof t=="string"&&(e.byKind[t]=(e.byKind[t]||0)+1),t==="image"&&(e.byKind["copilot.image"]=(e.byKind["copilot.image"]||0)+1),t==="file"&&e.file++,t==="generic"&&typeof o.name=="string"&&o.name.startsWith("sym:")){e.symbol++;let s=`#${o.name}`;e.byPath[s]=(e.byPath[s]||0)+1}}function fu(o,e){if(!o||typeof o!="object")return;let t=o;if(Array.isArray(t.variables))for(let s of t.variables)!s||typeof s!="object"||Eh(s,e)}function la(o){let e=o.modeUsage.ask+o.modeUsage.edit+o.modeUsage.agent+o.modeUsage.cli;o.conversationPatterns={multiTurnSessions:e>1?1:0,singleTurnSessions:e===1?1:0,avgTurnsPerSession:e,maxTurnsInSession:e}}function Rh(o,e){if(o.kind!=="dynamic")return;let t=o.data?.range,s=typeof t?.startLineNumber=="number"?t.startLineNumber:0,n=typeof t?.endLineNumber=="number"?t.endLineNumber:0;n>=s&&n>0&&(e.codeContextLines=(e.codeContextLines||0)+(n-s+1))}function Ih(o,e){if(o.kind!=="prompt")return;typeof o.slashPromptCommand?.command=="string"&&(e.byKind.prompt=(e.byKind.prompt||0)+1)}function Uh(o,e){if(!o||typeof o!="object")return;let t=o;typeof t.text=="string"&&gu(t.text,e),Rh(t,e),Ih(t,e)}function Oh(o,e){typeof o.text=="string"&&gu(o.text,e);let t=o.parts;if(Array.isArray(t))for(let s of t)Uh(s,e)}function ca(o,e){if(!o||typeof o!="object")return;let t=o,s=t.message;s&&typeof s=="object"&&Oh(s,e);let n=t.contentReferences;Array.isArray(n)&&aa(n,e);let i=t.variableData;i!==void 0&&fu(i,e)}async function Rn(o){try{let t=(await js.promises.readFile(o,"utf8")).trim().split(`
|
|
127
|
-
`),s=[];for(let n of t)if(n.trim())try{s.push(JSON.parse(n))}catch{}return s}catch{return[]}}function
|
|
128
|
-
`),t,o.modelPricing);else{let _=n!==void 0?n:JSON.parse(f);if(!
|
|
129
|
-
`)?0:1):0}function
|
|
130
|
-
`).filter(
|
|
131
|
-
`);return e[e.length-1]===""&&e.pop(),e.length}function
|
|
132
|
-
`).filter(
|
|
133
|
-
`);return
|
|
134
|
-
`),f=await this.processOpenCodeAssistantMessages(c,n),h=Math.max(0,f.turnCumulativeTotal-n-f.turnOutputAndThinking);t.push({turnNumber:i,timestamp:a.time?.created?new Date(a.time.created).toISOString():null,mode:"cli",userMessage:p,assistantResponse:f.assistantText,model:f.model,toolCalls:f.toolCalls,contextReferences:
|
|
135
|
-
`),{assistantText:c,toolCalls:m,model:p}=this.processAssistantMessagesForTurn(t),f=s?.prompt_tokens&&n>0?Math.round(s.prompt_tokens/n):0,h=s?.completion_tokens&&n>0?Math.round(s.completion_tokens/n):0;return{turnNumber:i,timestamp:e.created_at?new Date(e.created_at*1e3).toISOString():null,mode:"cli",userMessage:a,assistantResponse:c,model:p,toolCalls:m,contextReferences:B(),mcpTools:[],inputTokensEstimate:f,outputTokensEstimate:h,thinkingTokensEstimate:0}}processAssistantMessagesForTurn(e){let t="",s=[],n=null;for(let i of e){n||(n=i.model||null);for(let r of Array.isArray(i.parts)?i.parts:[])t+=this.processCrushMessagePart(r,s)}return{assistantText:t,toolCalls:s,model:n}}processCrushMessagePart(e,t){return e?.type==="text"&&e?.text?e.text:(e?.type==="tool_call"&&e?.data?.name&&t.push({toolName:e.data.name,arguments:e.data.arguments?JSON.stringify(e.data.arguments):void 0}),"")}async getSyncData(e){return this.crush.getCrushSessionData(e)}async analyzeUsage(e,t){let s=J(),n=await this.crush.getCrushMessages(e),i=[];for(let r of n)r.role==="user"&&s.modeUsage.cli++,r.role==="assistant"&&this.processCrushAssistantMessage(r,s,i);return this.applyCrushModelSwitchingStats(i,s),ee(t.modelPricing,s.modelSwitching.uniqueModels,i,s),s}processCrushAssistantMessage(e,t,s){s.push(e.model||"unknown");for(let n of Array.isArray(e.parts)?e.parts:[]){if(n?.type!=="tool_call"||!n?.data?.name)continue;t.toolCalls.total++;let i=n.data.name;t.toolCalls.byTool[i]=(t.toolCalls.byTool[i]||0)+1}}applyCrushModelSwitchingStats(e,t){let s=[...new Set(e)];t.modelSwitching.uniqueModels=s,t.modelSwitching.modelCount=s.length,t.modelSwitching.totalRequests=e.length;let n=0;for(let i=1;i<e.length;i++)e[i]!==e[i-1]&&n++;t.modelSwitching.switchCount=n}};var Eu=w(require("fs")),Ru=w(require("path")),Iu=w(Jr());var On=class{constructor(e,t){this.visualStudio=e;this.estimateTokens=t}visualStudio;estimateTokens;id="visualstudio";displayName="Visual Studio";handles(e){return this.visualStudio.isVSSessionFile(e)}getDisplayName(e){return Y(e).includes("/ssmsgithubcopilot/")?"SSMS":"Visual Studio"}getBackingPath(e){return e}async stat(e){return this.visualStudio.statSessionFile(e)}async getTokens(e){let t=await this.visualStudio.getTokenEstimates(e,this.estimateTokens);return{...t,actualTokens:t.tokens}}async countInteractions(e){let t=await this.visualStudio.decodeSessionFile(e);return this.visualStudio.countInteractions(t)}async getModelUsage(e){return this.visualStudio.getModelUsage(e,this.estimateTokens)}async getMeta(e){let t=await this.visualStudio.decodeSessionFile(e),s=this.visualStudio.getSessionTitle(t),n=this.visualStudio.getSessionTimestamps(t),i=[];return n.timeCreated&&i.push(new Date(n.timeCreated).getTime()),n.timeUpdated&&i.push(new Date(n.timeUpdated).getTime()),i.sort((r,a)=>r-a),{title:s,firstInteraction:i.length>0?new Date(i[0]).toISOString():null,lastInteraction:i.length>0?new Date(i[i.length-1]).toISOString():null}}getEditorRoot(e){return Ru.dirname(e)}skipBackendSync=!0;async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=await this.visualStudio.discoverSessions();n.length>0&&(e(`\u{1F4C4} Found ${n.length} session file(s) in Visual Studio Copilot`),s.push(...n))}catch(n){e(`Could not read Visual Studio session files: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.visualStudio.getLogDir(),source:"Visual Studio (log dir)"},{path:this.visualStudio.getSsmsSessionsDir(),source:"SSMS (sessions dir)"}]}getRawFileContent(e){try{let t=Eu.readFileSync(e),n=(t.length>=2?Array.from((0,Iu.decodeMulti)(t.slice(1))):[]).map((i,r)=>r===0?i:i?.[1]??i);return JSON.stringify(n,null,2)}catch{return"[]"}}async buildTurns(e){let t=[],s=await this.visualStudio.decodeSessionFile(e),n=0;for(let i=1;i<s.length;i+=2){let r=s[i],a=s[i+1];r&&(n++,t.push(this.buildVSTurn(r,a,n)))}return{turns:t}}buildVSTurn(e,t,s){let n=e[1],i=t?.[1],r=this.visualStudio.extractTextFromContent(n?.Content||[]),a=t?this.visualStudio.extractTextFromContent(i?.Content||[]):"",c=this.visualStudio.getModelId(i??n,!i),m=this.visualStudio.extractContextText(n?.Context),p=this.estimateTokens(r+m,c??"gpt-4"),f=t?this.estimateTokens(a,c??"gpt-4"):0;return{turnNumber:s,timestamp:n?.Timestamp?new Date(n.Timestamp).toISOString():null,mode:"ask",userMessage:r,assistantResponse:a,model:c,toolCalls:this.extractVSToolCalls(i),contextReferences:B(),mcpTools:[],inputTokensEstimate:p,outputTokensEstimate:f,thinkingTokensEstimate:0}}extractVSToolCalls(e){let t=[];for(let s of e?.Content||[]){let n=Array.isArray(s)?s[1]:null;n?.Function&&t.push({toolName:String(n.Function.Description||"tool"),result:typeof n.Function.Result=="string"?n.Function.Result:void 0})}return t}async analyzeUsage(e,t){let s=J(),n=await this.visualStudio.decodeSessionFile(e),i=[];for(let c=1;c<n.length;c++)c%2===1?s.modeUsage.ask++:this.processVSResponseObject(n[c]?.[1],s,i,t);let r=[...new Set(i)];s.modelSwitching.uniqueModels=r,s.modelSwitching.modelCount=r.length,s.modelSwitching.totalRequests=i.length;let a=0;for(let c=1;c<i.length;c++)i[c]!==i[c-1]&&a++;return s.modelSwitching.switchCount=a,ee(t.modelPricing,r,i,s),s}processVSResponseObject(e,t,s,n){let i=this.visualStudio.getModelId(e,!1);i&&s.push(i);for(let r of e?.Content??[]){let a=Array.isArray(r)?r[1]:null;if(!a?.Function)continue;t.toolCalls.total++;let c=String(a.Function.Name||a.Function.Description||"tool");if(st(c)){t.mcpTools.total++;let m=ft(c,n.toolNameMap);t.mcpTools.byServer[m]=(t.mcpTools.byServer[m]||0)+1;let p=on(c);t.mcpTools.byTool[p]=(t.mcpTools.byTool[p]||0)+1,t.toolCalls.total--}else t.toolCalls.byTool[c]=(t.toolCalls.byTool[c]||0)+1}}};var da=w(require("fs"));var Fn=class{constructor(e){this.continue_=e}continue_;id="continue";displayName="Continue";handles(e){return this.continue_.isContinueSessionFile(e)}getBackingPath(e){return e}async stat(e){return da.promises.stat(e)}async getTokens(e){let t=await this.continue_.getTokensFromContinueSession(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return await this.continue_.countContinueInteractions(e)}async getModelUsage(e){return await this.continue_.getContinueModelUsage(e)}async getMeta(e){let t=await this.continue_.getContinueSessionMeta(e),s=this.continue_.getContinueSessionId(e),n=(await this.continue_.readSessionsIndex()).get(s),i=null,r=null;if(n?.dateCreated){i=new Date(n.dateCreated).toISOString();try{r=(await da.promises.stat(e)).mtime.toISOString()}catch{}}let a;if(t?.workspaceDirectory)try{a=decodeURIComponent(t.workspaceDirectory.replace(/^file:\/\/\//,"").replace(/^file:\/\//,""))}catch{}return{title:t?.title,firstInteraction:i,lastInteraction:r,workspacePath:a}}getEditorRoot(e){return this.continue_.getContinueDataDir()}async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=await this.continue_.getContinueSessionFiles();n.length>0&&(e(`\u{1F4C4} Found ${n.length} session file(s) in Continue (~/.continue/sessions)`),s.push(...n))}catch(n){e(`Could not read Continue session files: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.continue_.getContinueSessionsDir(),source:"Continue"}]}async buildTurns(e){let t=[],s=await this.continue_.buildContinueTurns(e),n=B();for(let i of s)t.push({turnNumber:t.length+1,timestamp:null,mode:"ask",userMessage:i.userText,assistantResponse:i.assistantText,model:i.model,toolCalls:i.toolCalls,contextReferences:n,mcpTools:[],inputTokensEstimate:i.inputTokens,outputTokensEstimate:i.outputTokens,thinkingTokensEstimate:0});return{turns:t}}async analyzeUsage(e,t){let s=J(),n=await this.continue_.buildContinueTurns(e),i=await this.continue_.getContinueSessionMeta(e),r=[];for(let m of n){s.modeUsage.ask++,m.model&&r.push(m.model);for(let p of m.toolCalls)s.toolCalls.total++,s.toolCalls.byTool[p.toolName]=(s.toolCalls.byTool[p.toolName]||0)+1}if(i?.mode==="agent")for(let m=0;m<n.length;m++)s.modeUsage.ask--,s.modeUsage.agent++;let a=[...new Set(r)];s.modelSwitching.uniqueModels=a,s.modelSwitching.modelCount=a.length,s.modelSwitching.totalRequests=r.length;let c=0;for(let m=1;m<r.length;m++)r[m]!==r[m-1]&&c++;return s.modelSwitching.switchCount=c,ee(t.modelPricing,a,r,s),s}};var Fu=w(require("fs")),Ai=w(require("path"));function Uu(o){switch((o||"").toLowerCase()){case"agent":return"agent";case"edit":return"edit";case"plan":return"plan";case"ask":return"ask";default:return"ask"}}function Ou(o){if(!o)return null;let e=Date.parse(o);return Number.isNaN(e)?null:new Date(e).toISOString()}var vi=class{constructor(e){this.eclipse=e}eclipse;id="eclipse";displayName="Eclipse";handles(e){return this.eclipse.isEclipseSessionFile(e)}getBackingPath(e){return e}async stat(e){return Fu.promises.stat(e)}async getTokens(e){let t=await this.eclipse.getTokensFromEclipseSession(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return this.eclipse.countEclipseInteractions(e)}async getModelUsage(e){return this.eclipse.getEclipseModelUsage(e)}async getMeta(e){let t=await this.eclipse.getEclipseSessionMeta(e);return{title:t?.title,firstInteraction:Ou(t?.creationDate),lastInteraction:Ou(t?.lastMessageDate)}}getEditorRoot(e){return Ai.dirname(e)}async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=await this.eclipse.discoverEclipseSessions();n.length>0&&(e(`\u{1F4C4} Found ${n.length} session file(s) in Eclipse (Copilot conversations)`),s.push(...n))}catch(n){e(`Could not read Eclipse session files: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:Ai.join(this.eclipse.getDefaultWorkspaceRoot(),".metadata",".plugins","com.microsoft.copilot.eclipse.core","conversations"),source:"Eclipse"}]}async buildTurns(e){let t=[],s=await this.eclipse.buildEclipseTurns(e),n=B();for(let i of s)t.push({turnNumber:t.length+1,timestamp:i.timestamp,mode:Uu(i.mode),userMessage:i.userText,assistantResponse:i.assistantText,model:i.model,toolCalls:i.toolCalls,contextReferences:n,mcpTools:[],inputTokensEstimate:i.inputTokens,outputTokensEstimate:i.outputTokens,thinkingTokensEstimate:i.thinkingTokens,thinkingEffort:i.reasoningEffort??void 0});return{turns:t}}async analyzeUsage(e,t){let s=J(),n=await this.eclipse.buildEclipseTurns(e),i=[];for(let c of n){this.tallyMode(s,c.mode),c.model&&i.push(c.model);for(let m of c.toolCalls)s.toolCalls.total++,s.toolCalls.byTool[m.toolName]=(s.toolCalls.byTool[m.toolName]||0)+1}let r=[...new Set(i)];s.modelSwitching.uniqueModels=r,s.modelSwitching.modelCount=r.length,s.modelSwitching.totalRequests=i.length;let a=0;for(let c=1;c<i.length;c++)i[c]!==i[c-1]&&a++;return s.modelSwitching.switchCount=a,ee(t.modelPricing,r,i,s),s}tallyMode(e,t){let s=Uu(t);s==="agent"?e.modeUsage.agent++:s==="edit"?e.modeUsage.edit++:e.modeUsage.ask++}};var Lu=w(require("fs"));var Nu=w(require("fs"));var zy=new Set(["review","bug","think","compact","pr_comments"]);function ma(o){let e="";if(typeof o=="string")e=o;else if(Array.isArray(o)){for(let i of o)if(i?.type==="text"&&typeof i.text=="string"){e=i.text;break}}let s=e.trimStart().split(`
|
|
136
|
-
`)[0].trim().match(/^\/([a-z_]+)(?:\s|$)/i);if(!s)return null;let n=s[1].toLowerCase();return
|
|
137
|
-
`):"",{assistantText:r,model:a,actualInputTokens:c,actualOutputTokens:
|
|
138
|
-
`):"",{assistantText:r,model:a,actualInputTokens:c,actualOutputTokens:m,toolCalls:p,mcpTools:f}=this.processAssistantEventsForTurn(t),h=a||"claude-sonnet-4-6",_=c>0||m>0?{promptTokens:c,completionTokens:m}:void 0;return{turnNumber:s,timestamp:e.timestamp?new Date(e.timestamp).toISOString():null,mode:"agent",userMessage:i,assistantResponse:r,model:h,toolCalls:p,contextReferences:B(),mcpTools:f,inputTokensEstimate:c||this.estimateTokensFn(i,h),outputTokensEstimate:m||this.estimateTokensFn(r,h),thinkingTokensEstimate:0,actualUsage:_}}processAssistantEventsForTurn(e){let t="",s=0,n=0,i=null,r=[],a=[],c=new Set;for(let m of e){let p=m.message;!i&&p?.model&&(i=p.model);let f=m.requestId,h=!f||!c.has(f);f&&c.add(f);let _=p?.usage;if(_&&h){let C=this.extractUsageTokens(_);s+=C.input,n+=C.output}for(let C of Array.isArray(p?.content)?p.content:[])t+=this.processEventContentBlock(C,r,a)}return{assistantText:t,model:i,actualInputTokens:s,actualOutputTokens:n,toolCalls:r,mcpTools:a}}extractUsageTokens(e){return{input:(e.input_tokens||0)+(e.cache_creation_input_tokens||0)+(e.cache_read_input_tokens||0),output:e.output_tokens||0}}processEventContentBlock(e,t,s){if(e.type==="text")return e.text||"";if(e.type==="tool_use"){let n=e.name||"unknown";this.isMcpToolFn(n)?s.push({server:this.extractMcpServerNameFn(n),tool:n}):t.push({toolName:n,arguments:e.input?JSON.stringify(e.input):void 0})}return""}async analyzeUsage(e,t){let s=J(),n=await Rn(e),i=[];for(let r of n)r.type==="user"&&r.message?.role==="user"&&!r.isSidechain?this.processDesktopUserEvent(r,s):r.type==="assistant"&&this.processDesktopAssistantEvent(r,s,i);return this.applyDesktopModelSwitchingStats(i,s),ee(t.modelPricing,s.modelSwitching.uniqueModels,i,s),s}processDesktopUserEvent(e,t){t.modeUsage.ask++;let s=ma(e.message?.content);if(s){let n=`__slash__${s}`;t.toolCalls.byTool[n]=(t.toolCalls.byTool[n]||0)+1}}processDesktopAssistantEvent(e,t,s){let n=jt(e.message?.model||"unknown");s.push(n);let i=Array.isArray(e.message?.content)?e.message.content:[];for(let r of i){if(r?.type!=="tool_use")continue;t.toolCalls.total++;let a=String(r.name||"tool");t.toolCalls.byTool[a]=(t.toolCalls.byTool[a]||0)+1}}applyDesktopModelSwitchingStats(e,t){let s=[...new Set(e)];t.modelSwitching.uniqueModels=s,t.modelSwitching.modelCount=s.length,t.modelSwitching.totalRequests=e.length;let n=0;for(let i=1;i<e.length;i++)e[i]!==e[i-1]&&n++;t.modelSwitching.switchCount=n}};var ju=w(require("fs"));var jn=class{constructor(e){this.mistralVibe=e}mistralVibe;id="mistralvibe";displayName="Mistral Vibe";handles(e){return this.mistralVibe.isVibeSessionFile(e)}getBackingPath(e){return e}async stat(e){return ju.promises.stat(e)}async getTokens(e){let t=await this.mistralVibe.getTokensFromSession(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return this.mistralVibe.countInteractions(e)}async getModelUsage(e){return this.mistralVibe.getModelUsage(e)}async getMeta(e){let t=await this.mistralVibe.getSessionMeta(e);return{title:t.title,firstInteraction:t.firstInteraction,lastInteraction:t.lastInteraction}}getEditorRoot(e){return this.mistralVibe.getSessionLogDir()}async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=await this.mistralVibe.discoverSessions();n.length>0&&(e(`\u{1F4C4} Found ${n.length} session file(s) in Mistral Vibe (~/.vibe/logs/session)`),s.push(...n))}catch(n){e(`Could not read Mistral Vibe session files: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.mistralVibe.getSessionLogDir(),source:"Mistral Vibe"}]}async buildTurns(e){let t=[],s=await this.mistralVibe.readSessionMessages(e),n=await this.mistralVibe.getSessionMeta(e),i=await this.mistralVibe.getTokensFromSession(e),r=n.model||"devstral",a=this.findUserMessageIndices(s);for(let c=0;c<a.length;c++){let m=a[c],p=c+1<a.length?a[c+1]:s.length;t.push(this.buildMistralTurn(s,m,p,n,r,c+1))}return{turns:t,actualTokens:i.tokens}}findUserMessageIndices(e){let t=[];for(let s=0;s<e.length;s++)e[s].role==="user"&&e[s].injected!==!0&&t.push(s);return t}buildMistralTurn(e,t,s,n,i,r){let a=e[t],c=typeof a.content=="string"?a.content:"",{assistantText:m,toolCalls:p}=this.collectMistralTurnContent(e,t,s);return{turnNumber:r,timestamp:n.firstInteraction,mode:"cli",userMessage:c,assistantResponse:m,model:i,toolCalls:p,contextReferences:B(),mcpTools:[],inputTokensEstimate:0,outputTokensEstimate:0,thinkingTokensEstimate:0}}collectMistralTurnContent(e,t,s){let n="",i=[];for(let r=t+1;r<s;r++){let a=e[r];if(a.role==="assistant")n+=this.processMistralAssistantMsg(a,i);else if(a.role==="tool"){let c=i[i.length-1];c&&(c.result=typeof a.content=="string"?a.content:void 0)}}return{assistantText:n,toolCalls:i}}processMistralAssistantMsg(e,t){let s="";typeof e.content=="string"&&(s=e.content);for(let n of Array.isArray(e.tool_calls)?e.tool_calls:[])t.push({toolName:n.function?.name||n.name||"unknown",arguments:n.function?.arguments?JSON.stringify(n.function.arguments):void 0});return s}async analyzeUsage(e,t){let s=J(),n=await this.mistralVibe.readSessionMessages(e),r=(await this.mistralVibe.getSessionMeta(e)).model||"devstral",a=[];for(let m of n)if(m.role==="user"&&m.injected!==!0)s.modeUsage.cli++;else if(m.role==="assistant"&&(a.push(r),Array.isArray(m.tool_calls)))for(let p of m.tool_calls){s.toolCalls.total++;let f=String(p.function?.name||p.name||"tool");s.toolCalls.byTool[f]=(s.toolCalls.byTool[f]||0)+1}let c=[...new Set(a)];return s.modelSwitching.uniqueModels=c,s.modelSwitching.modelCount=c.length,s.modelSwitching.totalRequests=a.length,s.modelSwitching.switchCount=0,ee(t.modelPricing,c,a,s),s}};var Gu=w(require("fs"));var Gn=class{constructor(e){this.geminiCli=e}geminiCli;id="geminicli";displayName="Gemini CLI";handles(e){return this.geminiCli.isGeminiCliSessionFile(e)}getBackingPath(e){return e}async stat(e){return Gu.promises.stat(e)}async getTokens(e){let t=await this.geminiCli.getTokensFromGeminiCliSession(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return await this.geminiCli.countGeminiCliInteractions(e)}async getModelUsage(e){return await this.geminiCli.getGeminiCliModelUsage(e)}async getMeta(e){return await this.geminiCli.getGeminiCliSessionMeta(e)}getEditorRoot(e){return this.geminiCli.getGeminiDataDir()}async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=await this.geminiCli.getGeminiCliSessionFiles();n.length>0&&(e(`\u{1F4C4} Found ${n.length} session file(s) in Gemini CLI (~/.gemini/tmp/*/chats)`),s.push(...n))}catch(n){e(`Could not read Gemini CLI session files: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.geminiCli.getGeminiTmpDir(),source:"Gemini CLI (sessions)"},{path:this.geminiCli.getGeminiProjectsPath(),source:"Gemini CLI (projects.json)"},{path:this.geminiCli.getGeminiLogsPath(),source:"Gemini CLI (logs.json)"}]}async buildTurns(e){return await this.geminiCli.buildGeminiCliTurns(e)}async getDailyFractions(e){return await this.geminiCli.getGeminiCliDailyFractions(e)}async analyzeUsage(e,t){let s=J(),n=await this.geminiCli.readGeminiCliSession(e),i=[];s.modeUsage.cli+=n.userRecords.length;for(let r of n.assistantRecords)this.processGeminiAssistantRecord(r,s,i);return this.applyGeminiModelSwitchingStats(i,s),ee(t.modelPricing,s.modelSwitching.uniqueModels,i,s),s}processGeminiAssistantRecord(e,t,s){let n=_n(e.model||"unknown");s.push(n);for(let i of Array.isArray(e.toolCalls)?e.toolCalls:[]){let r=this.resolveGeminiToolName(i);r&&(t.toolCalls.total++,t.toolCalls.byTool[r]=(t.toolCalls.byTool[r]||0)+1)}}resolveGeminiToolName(e){return typeof e?.name=="string"&&e.name.trim().length>0?e.name.trim():typeof e?.displayName=="string"&&e.displayName.trim().length>0?e.displayName.trim():""}applyGeminiModelSwitchingStats(e,t){let s=[...new Set(e)];t.modelSwitching.uniqueModels=s,t.modelSwitching.modelCount=s.length,t.modelSwitching.totalRequests=e.length;let n=0;for(let i=1;i<e.length;i++)e[i]!==e[i-1]&&n++;t.modelSwitching.switchCount=n}};var qu=w(require("fs")),pa=w(require("inspector"));var qn=class{constructor(e,t=()=>0){this.antigravity=e;this.estimateTokens=t}antigravity;estimateTokens;id="antigravity";displayName="Antigravity";handles(e){return this.antigravity.isAntigravitySessionFile(e)}getBackingPath(e){return e}async stat(e){return qu.promises.stat(e)}async getTokens(e){return{...await this.antigravity.estimateTokensFromAntigravitySession(e,this.estimateTokens),actualTokens:0}}async countInteractions(e){return this.antigravity.countAntigravityInteractions(e)}async getModelUsage(e){return{}}async getMeta(e){return this.antigravity.getAntigravitySessionMeta(e)}getEditorRoot(e){return this.antigravity.getAntigravityBrainDir()}async buildTurns(e){return this.antigravity.buildAntigravityTurns(e)}async discover(e){let t=this.getCandidatePaths(),s=[],n=this.antigravity.getAntigravityBrainDir();pa.url()&&e(`\u{1F50D} [Antigravity] Checking brain dir: ${n}`);try{let i=await this.antigravity.getAntigravitySessionFiles();pa.url()&&e(`\u{1F50D} [Antigravity] Found ${i.length} transcript(s)`),i.length>0&&(e(`\u{1F4C4} Found ${i.length} session file(s) in Antigravity (~/.gemini/antigravity/brain/*/)`),s.push(...i))}catch(i){e(`Could not read Antigravity session files: ${i}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.antigravity.getAntigravityBrainDir(),source:"Antigravity (brain/)"}]}async analyzeUsage(e,t){let s=J(),n=await this.antigravity.readAntigravitySession(e);s.modeUsage.cli+=n.userEntries.length;for(let i of n.modelEntries)if(Array.isArray(i.tool_calls))for(let r of i.tool_calls)r.name&&(s.toolCalls.total++,s.toolCalls.byTool[r.name]=(s.toolCalls.byTool[r.name]||0)+1);return s.modelSwitching.uniqueModels=[],s.modelSwitching.modelCount=0,s.modelSwitching.totalRequests=0,s.modelSwitching.switchCount=0,s}};var Bu=w(require("fs"));var Bn=class{constructor(e){this.pi=e}pi;id="pi";displayName="Pi";handles(e){return this.pi.isPiSessionFile(e)}getBackingPath(e){return e}async stat(e){return Bu.promises.stat(e)}async getTokens(e){let t=await this.pi.getTokens(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return this.pi.countInteractions(e)}async getModelUsage(e){return this.pi.getModelUsage(e)}async getMeta(e){return this.pi.getSessionMeta(e)}getEditorRoot(e){return this.pi.getConfigDir()}async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=await this.pi.discoverSessions();n.length>0&&(e(`\u{1F4C4} Found ${n.length} session file(s) in Pi (~/.pi/agent/sessions)`),s.push(...n))}catch(n){e(`Could not read Pi session files: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.pi.getConfigDir(),source:"Pi"}]}async buildTurns(e){let t=await this.pi.getMessages(e),{tokens:s}=await this.pi.getTokens(e),n=await this.pi.getModelUsage(e),i=t.filter(c=>c.message?.role==="user").length,{perTurnInput:r,perTurnOutput:a}=this.computePerTurnDefaults(n,i);return{turns:this.buildAllTurns(t,r,a),actualTokens:s}}computePerTurnDefaults(e,t){if(t===0)return{perTurnInput:0,perTurnOutput:0};let s=Object.values(e).reduce((i,r)=>i+r.inputTokens,0),n=Object.values(e).reduce((i,r)=>i+r.outputTokens,0);return{perTurnInput:Math.round(s/t),perTurnOutput:Math.round(n/t)}}buildAllTurns(e,t,s){let n=[],i=0;for(let r=0;r<e.length;r++){if(e[r].message?.role!=="user")continue;i++;let a=this.collectAssistantEvents(e,r);n.push(this.buildTurn(e[r],a,i,t,s))}return n}collectAssistantEvents(e,t){let s=[];for(let n=t+1;n<e.length&&e[n].message?.role!=="user";n++)e[n].message?.role==="assistant"&&s.push(e[n]);return s}buildTurn(e,t,s,n,i){let r=this.extractUserText(e.message?.content),{assistantText:a,toolCalls:c,model:m}=this.processAssistantEvents(t),p=t.reduce((h,_)=>h+(_.message?.usage?.input??0),0),f=t.reduce((h,_)=>h+(_.message?.usage?.output??0),0);return{turnNumber:s,timestamp:e.timestamp??null,mode:"cli",userMessage:r,assistantResponse:a,model:m,toolCalls:c,contextReferences:B(),mcpTools:[],inputTokensEstimate:p>0?p:n,outputTokensEstimate:f>0?f:i,thinkingTokensEstimate:0}}extractUserText(e){return Array.isArray(e)?e.filter(t=>t.type==="text").map(t=>t.text||"").join(`
|
|
139
|
-
`):typeof e=="string"?e:""}processAssistantEvents(e){let t="",s=[],n=null;for(let i of e){let r=i.message;n||(n=r?.model??null),Array.isArray(r?.content)&&(t+=this.processContentParts(r.content,s))}return{assistantText:t,toolCalls:s,model:n}}processContentParts(e,t){let s="";for(let n of e)n.type==="text"&&n.text?s+=n.text:n.type==="toolCall"&&n.name&&t.push({toolName:n.name,arguments:n.arguments?JSON.stringify(n.arguments):void 0});return s}async getSyncData(e){return this.pi.getSessionData(e)}async analyzeUsage(e,t){let s=
|
|
138
|
+
`;function Bh(o,e){return new Promise((t,s)=>{let n;try{n=new uu.Worker(qh,{eval:!0,workerData:{dir:o,plan:e}})}catch(a){s(a);return}let i=!1,r=a=>{i||(i=!0,n.terminate(),a())};n.once("message",a=>r(()=>t(Gh(a)))),n.once("error",a=>r(()=>s(a))),n.once("exit",a=>r(()=>s(new Error(`OTel worker exited before posting results (code ${a})`))))})}async function zh(o,e,t){if(t<=e)return Buffer.alloc(0);let s=await Ai.promises.open(o,"r");try{let n=t-e,i=Buffer.allocUnsafe(n),{bytesRead:r}=await s.read(i,0,n,e);return r===n?i:i.subarray(0,r)}finally{await s.close()}}async function au(o,e){let t=[],s={};for(let n of e)try{let i=await zh(zt.join(o,n.name),n.start,n.end),r=i.lastIndexOf(Nh);if(r===-1){s[n.name]=n.start;continue}for(let a of i.subarray(0,r+1).toString("utf8").split(`
|
|
139
|
+
`)){let c=jh(a);c&&t.push(c)}s[n.name]=n.start+r+1}catch{}return{records:t,consumed:s}}var Dn=null,lu=0,xn=new Map,$h=3e4,Hh=1e6,An=null;async function Wh(o,e){let t=new Map;for(let s of e)try{t.set(s,(await Ai.promises.stat(zt.join(o,s))).size)}catch{}return t}function Jh(o){if(Dn===null)return!0;for(let[e,t]of xn){let s=o.get(e);if(s===void 0||s<t)return!0}return!1}function Vh(o,e){let t=[],s=0;for(let[n,i]of o){let r=e.get(n)??0;i>r&&(t.push({name:n,start:r,end:i}),s+=i-r)}return{plan:t,totalBytes:s}}async function Kh(o,e,t){try{return t>Hh?await Bh(o,e):await au(o,e)}catch{return au(o,e)}}async function Qh(){let o=Uh(),e;try{e=(await Ai.promises.readdir(o)).filter(p=>p.endsWith(".jsonl"))}catch{return xn=new Map,new Map}let t=await Wh(o,e),s=Jh(t),n=s?new Map:Dn,i=s?new Map:xn,{plan:r,totalBytes:a}=Vh(t,i);if(r.length===0)return xn=i,n;let c=await Kh(o,r,a);for(let p of c.records)Lh(p,n);let d=new Map(i);for(let[p,f]of Object.entries(c.consumed))d.set(p,f);return xn=d,n}async function Yh(){let o=Date.now();return Dn&&o-lu<$h?Dn:An||(An=Qh().then(e=>(Dn=e,lu=Date.now(),e)).finally(()=>{An=null}),An)}async function Xh(o){let e=Ns(o);return e?(await Yh()).get(e)??null:null}var mu=new Fs;async function Zh(o,e=mu){let t=Ns(o);if(!t)return null;let s=await e.getSessionUsage(t);return s||null}async function ms(o,e=mu){let t=await Zh(o,e);return t||Xh(o)}function pu(o,e,t){if(e+t<=0)return o;let s=Object.values(o).reduce((h,_)=>h+_.inputTokens,0),n=Object.values(o).reduce((h,_)=>h+_.outputTokens,0),i=s>0?e/s:0,r=n>0?t/n:0,a={},c=0,d=0;for(let[h,_]of Object.entries(o)){let C=Math.round(_.inputTokens*i),T=Math.round(_.outputTokens*r);c+=C,d+=T,a[h]={inputTokens:C,outputTokens:T,..._.cachedReadTokens!==void 0?{cachedReadTokens:Math.round(_.cachedReadTokens*i)}:{},..._.cacheCreationTokens!==void 0?{cacheCreationTokens:Math.round(_.cacheCreationTokens*i)}:{},..._.sessions!==void 0?{sessions:_.sessions}:{sessions:0}}}let p=e-c,f=t-d;if(p!==0||f!==0){let h=a.unknown??{inputTokens:0,outputTokens:0,sessions:0};a.unknown={...h,inputTokens:h.inputTokens+p,outputTokens:h.outputTokens+f}}return a}function gu(o,e){if(e<=0)return o;let t=Object.values(o).reduce((a,c)=>a+c.inputTokens,0),s=Object.values(o).reduce((a,c)=>a+c.outputTokens,0),n=t+s;if(n===0)return Object.keys(o).length===0?{unknown:{inputTokens:e,outputTokens:0,sessions:0}}:o;if(n===e)return o;if(s>0&&s<=e)return pu(o,e-s,s);let i=Math.round(e*(t/n)),r=e-i;return pu(o,i,r)}function fu(o){let e=globalThis.window;return e?e[o]:void 0}var ey=fu("__MODEL_PRICING__"),ty={};for(let[o,e]of Object.entries(ey?.pricing??{}))e.displayNames&&e.displayNames.length>0&&(ty[o]=e.displayNames[0]);var ny=[["anthropic","Anthropic"],["claude","Anthropic"],["codestral","Mistral AI"],["devstral","Mistral AI"],["gemini","Google"],["goldeneye","xAI"],["google","Google"],["gpt","OpenAI"],["grok","xAI"],["magistral","Mistral AI"],["mai-","Microsoft"],["ministral","Mistral AI"],["mistral","Mistral AI"],["o1","OpenAI"],["o3","OpenAI"],["o4","OpenAI"],["pixtral","Mistral AI"],["qwen","Alibaba"],["raptor","xAI"]];function hu(o){let e=o.toLowerCase(),t=ny.find(([s])=>e.startsWith(s));return t?t[1]:"Other"}function oy(o){return!o||typeof o!="string"?null:o.startsWith("toolu_")?"claude":o.startsWith("call_")?"gpt":null}function iy(o){let e=[],t=new Set;for(let s of o)if(s)try{let n=JSON.parse(s);if(!n||typeof n!="object")continue;e.push(n),n.type==="user.message_rendered"&&typeof n.data?.turnId=="string"&&t.add(n.data.turnId)}catch{}return{parsed:e,renderedTurnIds:t}}function ry(o,e){o.data?.conversationId&&(e.conversationId=String(o.data.conversationId)),o.data?.source&&(e.source=String(o.data.source)),e.turns=[],e.messageIds=[],e.turnStatusCounts={success:0,cancelled:0,failed:0,unknown:0},e.hasThinking=!1}function ay(o,e){e.result.interactions++,typeof o.timestamp=="string"&&e.firstUserTs===null&&(e.firstUserTs=o.timestamp);let t=o.data?.turnId,s=typeof t=="string"?t:null;s&&s!==e.currentTurnId&&(e.currentTurnId=s,e.currentMessageId=null,e.currentIterationNumber=null),typeof o.data?.content=="string"&&(typeof t!="string"||!e.renderedTurnIds.has(t))&&(e.inputTokens+=Z(o.data.content))}function En(o,e){if(!o.currentTurnId)return;let t=o.turnById.get(o.currentTurnId);t&&e(t)}function ly(o){return typeof o?.text=="string"&&o.text?o.text:typeof o?.content=="string"&&o.content?o.content:null}function cy(o,e){let t=ly(o.data);t&&(e.outputTokens+=Z(t));let s=o.data?.thinking?.text;typeof s=="string"&&s&&(e.result.thinkingTokens+=Z(s),e.hasThinking=!0,En(e,n=>{n.hasThinking=!0})),typeof o.data?.messageId=="string"&&(e.currentMessageId=o.data.messageId,e.messageIds.push(o.data.messageId),En(e,n=>{n.messageId=o.data.messageId})),typeof o.data?.iterationNumber=="number"&&(e.currentIterationNumber=o.data.iterationNumber,En(e,n=>{n.iterationNumber=o.data.iterationNumber})),typeof o.timestamp=="string"&&(e.lastTurnTs=o.timestamp,En(e,n=>{n.endTimestamp||(n.endTimestamp=o.timestamp)}))}function uy(o,e,t){e.currentTurnId&&(t.turnId=e.currentTurnId,e.toolCallByTurnId.has(e.currentTurnId)||e.toolCallByTurnId.set(e.currentTurnId,[]),e.toolCallByTurnId.get(e.currentTurnId).push(o||""),En(e,s=>{s.toolCallCount++}))}function dy(o,e){e.sawToolCall=!0;let t=o.data,s=t?.toolCallId;if(!e.modelFromToolCallId){let r=oy(s);r&&(e.modelFromToolCallId=r)}let n=typeof t?.toolName=="string"?t.toolName:"unknown",i={toolName:n};if(uy(s,e,i),s&&(i.toolCallId=s),t?.arguments!==void 0)try{i.arguments=JSON.stringify(t.arguments)}catch{}e.result.toolCalls.push(i),e.result.toolCounts[n]=(e.result.toolCounts[n]||0)+1,typeof s=="string"&&e.toolCallById.set(s,i)}function my(o,e){let t="";for(let s of o){let n=s;n&&typeof n.value=="string"&&(e.outputTokens+=Z(n.value),t+=(t?`
|
|
140
|
+
`:"")+n.value)}return t}function py(o,e){let t=o.data?.result?.result,s=Array.isArray(t)?my(t,e):"",n=o.data?.toolCallId;if(typeof n!="string")return;let i=e.toolCallById.get(n);i&&(typeof o.data?.success=="boolean"&&(i.success=o.data.success),s&&(i.result=s),typeof o.data?.progressMessage=="string"&&(i.progressMessage=o.data.progressMessage))}function gy(o,e){typeof o.data?.model=="string"&&!e.modelFromTurnStart&&(e.modelFromTurnStart=o.data.model),typeof o.data?.turnId=="string"&&(e.currentTurnId=o.data.turnId,e.currentMessageId=null,e.currentIterationNumber=null,e.turnById.has(o.data.turnId)||e.turnById.set(o.data.turnId,{turnId:o.data.turnId,startTimestamp:typeof o.timestamp=="string"?o.timestamp:null,endTimestamp:null,status:null,turnStatus:null,messageId:null,iterationNumber:null,hasThinking:!1,toolCallCount:0}))}function fy(o,e){if(typeof o.timestamp=="string"&&(e.lastTurnTs=o.timestamp),typeof o.data?.turnId!="string")return;let t=e.turnById.get(o.data.turnId);if(!t)return;typeof o.timestamp=="string"&&(t.endTimestamp=o.timestamp);let s=typeof o.data?.status=="string"?o.data.status:null;if(t.turnStatus=typeof o.data?.turnStatus=="string"?o.data.turnStatus:null,!!s)switch(t.status=s,s.toLowerCase()){case"success":e.turnStatusCounts.success++;break;case"cancelled":e.turnStatusCounts.cancelled++;break;case"failed":e.turnStatusCounts.failed++;break;default:e.turnStatusCounts.unknown++;break}}function hy(o,e){switch(o.type){case"partition.created":ry(o,e.result);break;case"user.message":ay(o,e);break;case"user.message_rendered":typeof o.data?.renderedMessage=="string"&&(e.inputTokens+=Z(o.data.renderedMessage));break;case"assistant.turn_start":gy(o,e);break;case"assistant.message":cy(o,e);break;case"tool.execution_start":dy(o,e);break;case"tool.execution_complete":py(o,e);break;case"assistant.turn_end":fy(o,e);break}}function yy(){return{tokens:0,thinkingTokens:0,actualTokens:0,interactions:0,modelUsage:{},mode:"ask",modelHint:"unknown",firstInteraction:null,lastInteraction:null,source:null,conversationId:null,toolCalls:[],toolCounts:{},turns:[],messageIds:[],turnStatusCounts:{success:0,cancelled:0,failed:0,unknown:0},hasThinking:!1}}function _y(o,e){return{inputTokens:0,outputTokens:0,firstUserTs:null,lastTurnTs:null,modelFromTurnStart:null,modelFromToolCallId:null,sawToolCall:!1,toolCallById:new Map,renderedTurnIds:e,result:o,currentTurnId:null,currentMessageId:null,currentIterationNumber:null,turnById:new Map,messageIds:[],turnStatusCounts:{success:0,cancelled:0,failed:0,unknown:0},hasThinking:!1,toolCallByTurnId:new Map}}function Cy(o,e){o.mode=e.sawToolCall?"agent":"ask",o.modelHint=e.modelFromTurnStart||e.modelFromToolCallId||"unknown",o.tokens=e.inputTokens+e.outputTokens,o.firstInteraction=e.firstUserTs,o.lastInteraction=e.lastTurnTs,o.hasThinking=e.hasThinking,o.turnStatusCounts={...e.turnStatusCounts},o.turns=Array.from(e.turnById.values()),o.messageIds=[...e.messageIds],o.tokens>0&&o.modelHint!=="unknown"&&(o.modelUsage[o.modelHint]={inputTokens:e.inputTokens,outputTokens:e.outputTokens,sessions:0})}function xi(o){let e=yy(),{parsed:t,renderedTurnIds:s}=iy(o.split(/\r?\n/)),n=_y(e,s);for(let i of t)hy(i,n);return Cy(e,n),e}function yu(o){let e=o.split(/\r?\n/);for(let t of e)if(t&&t.indexOf("tool.execution_start")!==-1)try{let s=JSON.parse(t);if(s&&s.type==="tool.execution_start")return"agent"}catch{}return"ask"}function In(o){return o==null}function by(o){if(typeof o!="object"||o===null||Array.isArray(o))return!1;let e=o;return In(e.id)||typeof e.id=="string"}function Ei(o){if(o===null||typeof o!="object"||Array.isArray(o))return!1;let e=o;return!(!In(e.requests)&&!Array.isArray(e.requests)||!In(e.mode)&&!by(e.mode)||!In(e.creationDate)&&typeof e.creationDate!="number"||!In(e.lastMessageDate)&&typeof e.lastMessageDate!="number")}function Di(o){return typeof o=="string"?o.trim().toLowerCase():""}function Rn(o){let e=o.v;return e?.selectedModel??e?.inputState?.selectedModel}function ky(o,e){return o==="auto"||e==="auto"||e.includes("auto")||o.includes("/auto")}function Sy(o,e,t,s,n){let i=t.includes("foundry")||t.includes("local")||s.includes("foundry")||s.includes("windows")||n.includes("foundry")||n.includes("windows")||o.includes("foundry");return o.includes("foundry")&&(o.includes("microsoft")||o.includes("aitk"))||e.includes("microsoft")&&i}function Ty(o){let e=o?.metadata,t=e?.extension;return{family:Di(e?.family),vendor:Di(e?.vendor),extension:Di(t?.value),category:Di(e?.modelPickerCategory?.label),rawExtension:t?.value}}function ps(o,e,t){let s=(o??"").replace(/^copilot\//,"");if(!s)return;let{family:n,vendor:i,extension:r,category:a,rawExtension:c}=Ty(e);ky(s,n)&&(t.modelSwitching.autoSessions=1),Sy(s,i,n,r,a)&&(t.modelSwitching.foundryWindowsSessions=1),hu(s)==="Other"&&(t.modelSwitching.unknownProviderSessions=1,t.modelSwitching.unknownProviderModels.includes(s)||t.modelSwitching.unknownProviderModels.push(s)),c&&!t.modelSwitching.selectedModelExtensions.includes(c)&&t.modelSwitching.selectedModelExtensions.push(c)}function wy(o,e){if(o.type==="session.start"&&typeof o.data?.selectedModel=="string"){ps(o.data.selectedModel,Rn(o),e);return}if(o.type==="session.model_change"&&typeof o.data?.newModel=="string"){ps(o.data.newModel,Rn(o),e);return}let t=Eu(o);if(t){ps(t,Rn(o),e);return}let s=Ru(o);if(s){ps(s,Rn(o),e);return}typeof o.model=="string"&&(ps(o.model,Rn(o),e),Du(o,e))}function ku(o,e){o==="agent"?e.agent++:o==="edit"?e.edit++:o==="plan"?e.plan++:o==="customAgent"?e.customAgent++:e.ask++}function ma(o,e,t){if(st(o)){e.mcpTools.total++;let s=ft(o,t);e.mcpTools.byServer[s]=(e.mcpTools.byServer[s]||0)+1;let n=rn(o);e.mcpTools.byTool[n]=(e.mcpTools.byTool[n]||0)+1}else e.toolCalls.total++,e.toolCalls.byTool[o]=(e.toolCalls.byTool[o]||0)+1}function pa(o){let e=o.split("/").pop()?.split("\\").pop()??"",t=e.lastIndexOf(".");return t<=0?e.toLowerCase()||"unknown":e.slice(t+1).toLowerCase()}function My(o){return{timestamp:o.timestamp,timings:o.result?.timings,waitTime:o.timeSpentWaiting}}function Py(o){if(!o.agent?.id)return{agentType:null};let e=o.agent.id;return e.includes("edit")?{agentType:"editsAgent"}:e.includes("default")?{agentType:"defaultAgent"}:e.includes("workspace")?{agentType:"workspaceAgent"}:{agentType:"other"}}function vy(o,e,t){if(!o||typeof o!="object")return;let s=o;if(typeof s.text=="string"&&s.text){let n=(s.text.match(/\n/g)??[]).length+(s.text.endsWith(`
|
|
141
|
+
`)?0:1);t.linesAdded+=n,t.languageUsage[e]||(t.languageUsage[e]={linesAdded:0,linesRemoved:0}),t.languageUsage[e].linesAdded+=n}if(s.range&&typeof s.range.startLineNumber=="number"&&typeof s.range.endLineNumber=="number"){let n=Math.max(0,s.range.endLineNumber-s.range.startLineNumber);t.linesRemoved+=n,t.languageUsage[e]||(t.languageUsage[e]={linesAdded:0,linesRemoved:0}),t.languageUsage[e].linesRemoved+=n}}function Ay(o,e,t){for(let s of o)if(Array.isArray(s))for(let n of s)vy(n,e,t)}function xy(o,e){if(!o.uri)return;let t=o.uri.path||JSON.stringify(o.uri);e.editedFilePaths.push(t);let s=pa(t),n=o;Array.isArray(n.edits)&&Ay(n.edits,s,e)}function Dy(o){let e={editedFilePaths:[],codeBlocks:0,applies:0,linesAdded:0,linesRemoved:0,languageUsage:{}};if(!o.response||!Array.isArray(o.response))return e;for(let t of o.response)t&&(t.kind==="textEditGroup"&&xy(t,e),t.kind==="codeblockUri"&&(e.codeBlocks++,t.isEdit===!0&&e.applies++));return e}function Ey(o,e){for(let[t,s]of Object.entries(e))o[t]||(o[t]={linesAdded:0,linesRemoved:0}),o[t].linesAdded+=s.linesAdded,o[t].linesRemoved+=s.linesRemoved}function Ry(o,e,t,s,n){o.timestamp!==void 0&&e.push(o.timestamp),o.timings&&t.push(o.timings),o.waitTime!==void 0&&s.push(o.waitTime),o.timestamp!==void 0&&o.timings?.totalElapsed!==void 0&&n.push({start:o.timestamp,end:o.timestamp+o.timings.totalElapsed})}function Su(o,e,t,s,n,i,r){let a=0,c=0,d=0,p=0,f={};for(let h of o){if(!h)continue;Ry(My(h),s,n,i,r);let _=Py(h);_.agentType!==null&&e[_.agentType]++;let C=Dy(h);for(let T of C.editedFilePaths)t.add(T);c+=C.codeBlocks,a+=C.applies,d+=C.linesAdded,p+=C.linesRemoved,Ey(f,C.languageUsage)}return{totalApplies:a,totalCodeBlocks:c,totalLinesAdded:d,totalLinesRemoved:p,languageUsage:f}}function Iy(o,e,t){if(!(!o.response||!Array.isArray(o.response))){for(let s of o.response)if(s&&(s.kind==="toolInvocationSerialized"||s.kind==="prepareToolInvocation")){let n=s.toolId||s.toolName||s.invocationMessage?.toolName||s.toolSpecificData?.kind||"unknown";ma(n,e,t)}}}function Uy(o,e,t,s){e.requestId&&(ku(t,s.modeUsage),e.agent?.id&&(s.toolCalls.total++,s.toolCalls.byTool[e.agent.id]=(s.toolCalls.byTool[e.agent.id]||0)+1),ha(e,s.contextReferences),Iy(e,s,o.toolNameMap))}function Tu(o,e,t){return o.modelId?o.modelId.replace(/^copilot\//,""):o.result?.metadata?.modelId?o.result.metadata.modelId.replace(/^copilot\//,""):o.result?.details?Lt(o,t):e}function Oy(o){let e=0;for(let t=1;t<o.length;t++)o[t]!==o[t-1]&&e++;return e}function wu(o){let e=o.selectedModel,t=o.inputState?.selectedModel;return(e?.identifier||e?.metadata?.id||t?.identifier||t?.metadata?.id||"gpt-4o").replace(/^copilot\//,"")}function Fy(o,e,t,s){let n=wu(e),i=e.selectedModel,r=e.inputState?.selectedModel;(i?.identifier||r?.identifier||"").replace(/^copilot\//,"")==="auto"&&(s.modelSwitching.autoSessions=1);let c=[];for(let p of t){if(!p||!p.requestId)continue;let f=Tu(p,n,o.modelPricing);c.push(f);let h=f.toLowerCase();h.includes("foundry")&&(h.includes("microsoft")||h.includes("aitk"))&&(s.modelSwitching.foundryWindowsSessions=1)}let d=[...new Set(c)];s.modelSwitching.uniqueModels=d,s.modelSwitching.modelCount=d.length,s.modelSwitching.totalRequests=c.length,s.modelSwitching.switchCount=Oy(c),Q(o.modelPricing,d,c,s)}function Ny(o,e,t){let{effortByRequestId:s,defaultEffort:n,switchCount:i}=oc(o);if(n===null&&s.size===0)return;let r={};for(let[,a]of s)r[a]=(r[a]||0)+1;s.size===0&&n!==null&&(r[n]=e.length),t.thinkingEffort={byEffort:r,switchCount:i,defaultEffort:n}}function Ly(o,e,t,s){let n=e.inputState?.mode?Io(e.inputState.mode):"ask";if(e.inputState?.selections&&Array.isArray(e.inputState.selections)){for(let r of e.inputState.selections)if(r&&(r.startLineNumber!==r.endLineNumber||r.startColumn!==r.endColumn)){s.contextReferences.implicitSelection++;break}}let i=e.requests??[];for(let r of i)Uy(o,r,n,s);Fy(o,e,i,s),Ny(t,i,s),Mu(i,wu(e),o.modelPricing,s),fa(s)}function jy(o){return(o.selectedModel?.identifier||o.selectedModel?.metadata?.id||"unknown").replace(/^copilot\//,"")}function Mu(o,e,t,s){let n=[];for(let i of o)i&&n.push({model:Tu(i,e,t),toolCalls:tu(i)});n.length!==0&&(s.modelEfficiency=vi(n))}function Gy(o,e){if(o.agent?.id){let t=o.agent.id.toLowerCase();if(t.includes("edit"))return"edit";if(t.includes("agent"))return"agent"}if(e.mode?.id){let t=e.mode.id.toLowerCase();if(t.includes("agent"))return"agent";if(t.includes("edit"))return"edit"}return"ask"}function qy(o,e,t){if(o.kind==="toolInvocationSerialized"||o.kind==="prepareToolInvocation"){let s=o.toolId||o.toolName||o.invocationMessage?.toolName||"unknown";ma(s,e,t.toolNameMap)}if(o.kind==="mcpServersStarting"&&o.didStartServerIds)for(let s of o.didStartServerIds)e.mcpTools.total++,e.mcpTools.byServer[s]=(e.mcpTools.byServer[s]||0)+1;o.kind==="inlineReference"&&o.inlineReference&&ga([o],e.contextReferences)}function By(o,e,t,s){let n=Gy(e,t);if(n==="agent"?s.modeUsage.agent++:n==="edit"?s.modeUsage.edit++:s.modeUsage.ask++,ha(e,s.contextReferences),e.response&&Array.isArray(e.response))for(let i of e.response)i&&qy(i,s,o)}function zy(o,e,t){if(!(!e.requests||!Array.isArray(e.requests)))for(let s of e.requests)By(o,s,e,t)}function $y(o,e){for(let t of e.tiers.standard)o.modelSwitching.standardModels.includes(t)||o.modelSwitching.standardModels.push(t);for(let t of e.tiers.premium)o.modelSwitching.premiumModels.includes(t)||o.modelSwitching.premiumModels.push(t);for(let t of e.tiers.unknown)o.modelSwitching.unknownModels.includes(t)||o.modelSwitching.unknownModels.push(t)}function _u(o,e){for(let t of e??[])o.includes(t)||o.push(t)}function Hy(o,e){for(let t of e.costBuckets?.low??[])o.modelSwitching.lowCostModels.includes(t)||o.modelSwitching.lowCostModels.push(t);for(let t of e.costBuckets?.medium??[])o.modelSwitching.mediumCostModels.includes(t)||o.modelSwitching.mediumCostModels.push(t);for(let t of e.costBuckets?.high??[])o.modelSwitching.highCostModels.includes(t)||o.modelSwitching.highCostModels.push(t)}function Wy(o){let e=o.modelSwitching.modelsPerSession;e.length!==0&&(o.modelSwitching.averageModelsPerSession=e.reduce((t,s)=>t+s,0)/e.length,o.modelSwitching.maxModelsPerSession=Math.max(...e),o.modelSwitching.minModelsPerSession=Math.min(...e),o.modelSwitching.switchingFrequency=e.filter(t=>t>1).length/e.length*100)}function Jy(o,e){if(e.modelSwitching||(e.modelSwitching={uniqueModels:[],modelCount:0,switchCount:0,autoSessions:0,foundryWindowsSessions:0,unknownProviderSessions:0,selectedModelExtensions:[],unknownProviderModels:[],tiers:{standard:[],premium:[],unknown:[]},hasMixedTiers:!1,standardRequests:0,premiumRequests:0,unknownRequests:0,totalRequests:0,costBuckets:{low:[],medium:[],high:[],unknown:[]},hasMixedCosts:!1,lowCostRequests:0,mediumCostRequests:0,highCostRequests:0}),e.modelSwitching.modelCount<=0)return;let t=e.modelSwitching;o.modelSwitching.totalSessions++,o.modelSwitching.modelsPerSession.push(t.modelCount),$y(o,t),Hy(o,t),o.modelSwitching.autoSessions+=t.autoSessions||0,o.modelSwitching.foundryWindowsSessions+=t.foundryWindowsSessions||0,o.modelSwitching.unknownProviderSessions+=t.unknownProviderSessions||0,_u(o.modelSwitching.selectedModelExtensions,t.selectedModelExtensions),_u(o.modelSwitching.unknownProviderModels,t.unknownProviderModels),t.hasMixedTiers&&o.modelSwitching.mixedTierSessions++,t.hasMixedCosts&&o.modelSwitching.mixedCostSessions++,o.modelSwitching.standardRequests+=t.standardRequests||0,o.modelSwitching.premiumRequests+=t.premiumRequests||0,o.modelSwitching.unknownRequests+=t.unknownRequests||0,o.modelSwitching.lowCostRequests+=t.lowCostRequests||0,o.modelSwitching.mediumCostRequests+=t.mediumCostRequests||0,o.modelSwitching.highCostRequests+=t.highCostRequests||0,o.modelSwitching.totalRequests+=t.totalRequests||0,Wy(o)}function Vy(o,e){if(e.thinkingEffort){o.thinkingEffortUsage||(o.thinkingEffortUsage={byEffort:{},sessionCount:0,switchCount:0}),o.thinkingEffortUsage.sessionCount++,o.thinkingEffortUsage.switchCount+=e.thinkingEffort.switchCount;for(let[t,s]of Object.entries(e.thinkingEffort.byEffort))o.thinkingEffortUsage.byEffort[t]=(o.thinkingEffortUsage.byEffort[t]||0)+s}}var Ky=["file","selection","implicitSelection","symbol","codebase","workspace","terminal","vscode","terminalLastCommand","terminalSelection","clipboard","changes","outputPanel","problemsPanel","pullRequest","copilotInstructions","agentsMd"];function Cu(o,e){for(let[t,s]of Object.entries(e))o[t]=(o[t]||0)+s}function Qy(o,e){let t=o.contextReferences,s=e.contextReferences;for(let n of Ky)t[n]+=s[n]||0;t.codeContextLines=(t.codeContextLines||0)+(s.codeContextLines||0),Cu(t.byKind,s.byKind),Cu(t.byPath,s.byPath)}function Yy(o,e){if(e.editScope){o.editScope.singleFileEdits+=e.editScope.singleFileEdits,o.editScope.multiFileEdits+=e.editScope.multiFileEdits,o.editScope.totalEditedFiles+=e.editScope.totalEditedFiles;let t=o.editScope.singleFileEdits+o.editScope.multiFileEdits;o.editScope.avgFilesPerSession=t>0?o.editScope.totalEditedFiles/t:0}if(e.applyUsage&&(o.applyUsage.totalApplies+=e.applyUsage.totalApplies,o.applyUsage.totalCodeBlocks+=e.applyUsage.totalCodeBlocks,o.applyUsage.applyRate=o.applyUsage.totalCodeBlocks>0?o.applyUsage.totalApplies/o.applyUsage.totalCodeBlocks*100:0),e.sessionDuration){o.sessionDuration.totalDurationMs+=e.sessionDuration.totalDurationMs,o.sessionDuration.activeDurationMs+=e.sessionDuration.activeDurationMs;let t=o.sessions;if(t>0){o.sessionDuration.avgDurationMs=o.sessionDuration.totalDurationMs/t;let s=o.sessionDuration.avgFirstProgressMs*(t-1);o.sessionDuration.avgFirstProgressMs=(s+e.sessionDuration.avgFirstProgressMs)/t;let n=o.sessionDuration.avgTotalElapsedMs*(t-1);o.sessionDuration.avgTotalElapsedMs=(n+e.sessionDuration.avgTotalElapsedMs)/t;let i=o.sessionDuration.avgWaitTimeMs*(t-1);o.sessionDuration.avgWaitTimeMs=(i+e.sessionDuration.avgWaitTimeMs)/t}}if(e.conversationPatterns){o.conversationPatterns.multiTurnSessions+=e.conversationPatterns.multiTurnSessions,o.conversationPatterns.singleTurnSessions+=e.conversationPatterns.singleTurnSessions,o.conversationPatterns.maxTurnsInSession=Math.max(o.conversationPatterns.maxTurnsInSession,e.conversationPatterns.maxTurnsInSession);let t=o.conversationPatterns.multiTurnSessions+o.conversationPatterns.singleTurnSessions;if(t>0){let n=o.conversationPatterns.avgTurnsPerSession*(t-1)+e.conversationPatterns.avgTurnsPerSession;o.conversationPatterns.avgTurnsPerSession=n/t}}e.agentTypes&&(o.agentTypes.editsAgent+=e.agentTypes.editsAgent,o.agentTypes.defaultAgent+=e.agentTypes.defaultAgent,o.agentTypes.workspaceAgent+=e.agentTypes.workspaceAgent,o.agentTypes.other+=e.agentTypes.other),Vy(o,e),Xy(o,e)}function Xy(o,e){e.modelEfficiency&&(o.modelEfficiency||(o.modelEfficiency={}),su(o.modelEfficiency,e.modelEfficiency))}function Un(o,e){o.toolCalls.total+=e.toolCalls.total;for(let[t,s]of Object.entries(e.toolCalls.byTool))o.toolCalls.byTool[t]=(o.toolCalls.byTool[t]||0)+s;if(e.toolCalls.outputTokensByTool){o.toolCalls.outputTokensByTool||(o.toolCalls.outputTokensByTool={});for(let[t,s]of Object.entries(e.toolCalls.outputTokensByTool))o.toolCalls.outputTokensByTool[t]=(o.toolCalls.outputTokensByTool[t]||0)+s}o.modeUsage.ask+=e.modeUsage.ask,o.modeUsage.edit+=e.modeUsage.edit,o.modeUsage.agent+=e.modeUsage.agent,o.modeUsage.plan+=e.modeUsage.plan,o.modeUsage.customAgent+=e.modeUsage.customAgent,o.modeUsage.cli+=e.modeUsage.cli,Qy(o,e),o.mcpTools.total+=e.mcpTools.total;for(let[t,s]of Object.entries(e.mcpTools.byServer))o.mcpTools.byServer[t]=(o.mcpTools.byServer[t]||0)+s;for(let[t,s]of Object.entries(e.mcpTools.byTool))o.mcpTools.byTool[t]=(o.mcpTools.byTool[t]||0)+s;Jy(o,e),Yy(o,e)}var Zy=[[/#file/gi,"file"],[/#selection/gi,"selection"],[/#symbol/gi,"symbol"],[/#sym(?![:\w])/gi,"symbol"],[/#codebase/gi,"codebase"],[/#terminalLastCommand/gi,"terminalLastCommand"],[/#terminalSelection/gi,"terminalSelection"],[/#clipboard/gi,"clipboard"],[/#changes/gi,"changes"],[/#outputPanel/gi,"outputPanel"],[/#problemsPanel\b/gi,"problemsPanel"],[/#pr\b/gi,"pullRequest"],[/#pullRequest\b/gi,"pullRequest"],[/@workspace/gi,"workspace"],[/@terminal/gi,"terminal"],[/@vscode/gi,"vscode"]];function Pu(o,e){for(let[t,s]of Zy){let n=o.match(t);n&&(e[s]+=n.length)}}function e_(o){let e=o.kind;return e==="reference"&&o.reference?o.reference:e==="inlineReference"&&o.inlineReference?o.inlineReference:null}function t_(o,e,t){e.endsWith("/.github/copilot-instructions.md")||e.includes(".github/copilot-instructions.md")?t.copilotInstructions++:e.endsWith("/agents.md")||e.match(/\/agents\.md$/i)?t.agentsMd++:e.endsWith(".instructions.md")||e.includes(".instructions.md")?t.copilotInstructions++:t.file++;let s=o.length>100?"..."+o.substring(o.length-97):o;t.byPath[s]=(t.byPath[s]||0)+1}function s_(o,e,t){let s=o.fsPath||o.path;typeof s=="string"&&t_(s,X(s),t);let n=o.name;if(typeof n=="string"&&e==="reference"){t.symbol++;let i=`#sym:${n}`;t.byPath[i]=(t.byPath[i]||0)+1}}function ga(o,e){if(Array.isArray(o))for(let t of o){if(!t||typeof t!="object")continue;let s=t,n=s.kind;if(typeof n=="string"&&(e.byKind[n]=(e.byKind[n]||0)+1),n==="pullRequest"){e.pullRequest++;continue}let i=e_(s);i&&s_(i,n,e)}}function n_(o,e){let t=o.kind;if(typeof t=="string"&&(e.byKind[t]=(e.byKind[t]||0)+1),t==="image"&&(e.byKind["copilot.image"]=(e.byKind["copilot.image"]||0)+1),t==="file"&&e.file++,t==="generic"&&typeof o.name=="string"&&o.name.startsWith("sym:")){e.symbol++;let s=`#${o.name}`;e.byPath[s]=(e.byPath[s]||0)+1}}function vu(o,e){if(!o||typeof o!="object")return;let t=o;if(Array.isArray(t.variables))for(let s of t.variables)!s||typeof s!="object"||n_(s,e)}function fa(o){let e=o.modeUsage.ask+o.modeUsage.edit+o.modeUsage.agent+o.modeUsage.cli;o.conversationPatterns={multiTurnSessions:e>1?1:0,singleTurnSessions:e===1?1:0,avgTurnsPerSession:e,maxTurnsInSession:e}}function o_(o,e){if(o.kind!=="dynamic")return;let t=o.data?.range,s=typeof t?.startLineNumber=="number"?t.startLineNumber:0,n=typeof t?.endLineNumber=="number"?t.endLineNumber:0;n>=s&&n>0&&(e.codeContextLines=(e.codeContextLines||0)+(n-s+1))}function i_(o,e){if(o.kind!=="prompt")return;typeof o.slashPromptCommand?.command=="string"&&(e.byKind.prompt=(e.byKind.prompt||0)+1)}function r_(o,e){if(!o||typeof o!="object")return;let t=o;typeof t.text=="string"&&Pu(t.text,e),o_(t,e),i_(t,e)}function a_(o,e){typeof o.text=="string"&&Pu(o.text,e);let t=o.parts;if(Array.isArray(t))for(let s of t)r_(s,e)}function ha(o,e){if(!o||typeof o!="object")return;let t=o,s=t.message;s&&typeof s=="object"&&a_(s,e);let n=t.contentReferences;Array.isArray(n)&&ga(n,e);let i=t.variableData;i!==void 0&&vu(i,e)}async function On(o){try{let t=(await Ls.promises.readFile(o,"utf8")).trim().split(`
|
|
142
|
+
`),s=[];for(let n of t)if(n.trim())try{s.push(JSON.parse(n))}catch{}return s}catch{return[]}}function Q(o,e,t,s){let n=[],i=[],r=[];for(let T of e){let E=ls(T,o);E==="standard"?n.push(T):E==="premium"?i.push(T):r.push(T)}s.modelSwitching.tiers={standard:n,premium:i,unknown:r},s.modelSwitching.hasMixedTiers=n.length>0&&i.length>0;let a={low:[],medium:[],high:[],unknown:[]};for(let T of e){let E=dn(T,o);E==="low"?a.low.push(T):E==="medium"?a.medium.push(T):E==="high"?a.high.push(T):a.unknown.push(T)}s.modelSwitching.costBuckets=a;let c=[a.low,a.medium,a.high].filter(T=>T.length>0).length;s.modelSwitching.hasMixedCosts=c>=2;let d=0,p=0,f=0,h=0,_=0,C=0;for(let T of t){let E=ls(T,o);E==="standard"?d++:E==="premium"?p++:f++;let A=dn(T,o);A==="low"?h++:A==="medium"?_++:A==="high"&&C++}s.modelSwitching.standardRequests=d,s.modelSwitching.premiumRequests=p,s.modelSwitching.unknownRequests=f,s.modelSwitching.lowCostRequests=h,s.modelSwitching.mediumCostRequests=_,s.modelSwitching.highCostRequests=C}function ca(o,e,t){let s=ls(o,t);s==="standard"?e.standard++:s==="premium"?e.premium++:e.unknown++}function ua(o,e,t){let s=dn(o,t);s==="low"?e.low++:s==="medium"?e.medium++:s==="high"?e.high++:e.unknown++}function Au(o,e){e.modelSwitching.standardRequests=o.standard,e.modelSwitching.premiumRequests=o.premium,e.modelSwitching.unknownRequests=o.unknown,e.modelSwitching.totalRequests=o.standard+o.premium+o.unknown}function xu(o,e){e.modelSwitching.lowCostRequests=o.low,e.modelSwitching.mediumCostRequests=o.medium,e.modelSwitching.highCostRequests=o.high,e.modelSwitching.totalRequests=o.low+o.medium+o.high+o.unknown}function l_(o,e){let t=[],s=[],n=[];for(let i of o){let r=ls(i,e);r==="standard"?t.push(i):r==="premium"?s.push(i):n.push(i)}return{standard:t,premium:s,unknown:n}}function c_(o,e){if(o.model==="auto"){e.modelSwitching.autoSessions=1;return}if(o.model&&o.resolvedModel&&o.model!==o.resolvedModel){e.modelSwitching.autoSessions=1;return}if(o.result?.metadata){if(o.result.metadata.model==="auto"){e.modelSwitching.autoSessions=1;return}if(o.result.metadata.model&&o.result.metadata.resolvedModel&&o.result.metadata.model!==o.result.metadata.resolvedModel){e.modelSwitching.autoSessions=1;return}}}function Du(o,e){if(!o.model)return;let t=String(o.model).toLowerCase();t.includes("foundry")&&(t.includes("microsoft")||t.includes("aitk"))&&(e.modelSwitching.foundryWindowsSessions=1)}function u_(o,e,t){if(!o.requests||!Array.isArray(o.requests))return;let s=null,n=0,i={standard:0,premium:0,unknown:0},r={low:0,medium:0,high:0,unknown:0};for(let a of o.requests){let c=Lt(a,t);s&&c!==s&&n++,s=c,ca(c,i,t),ua(c,r,t),c_(a,e),Du(a,e)}e.modelSwitching.switchCount=n,Au(i,e),xu(r,e)}function d_(o,e){ps(o.selectedModel?.identifier||o.selectedModel?.metadata?.id,o.selectedModel,e),ps(o.inputState?.selectedModel?.identifier||o.inputState?.selectedModel?.metadata?.id,o.inputState?.selectedModel,e)}function Eu(o){if(o.kind!==0)return null;let e=o.v;if(!e)return null;let t=e.selectedModel,s=e.inputState?.selectedModel,n=t?.identifier||t?.metadata?.id||s?.identifier||s?.metadata?.id;return n?n.replace(/^copilot\//,""):null}function Ru(o){if(o.kind!==2||o.k?.[0]!=="selectedModel")return null;let e=o.v,t=e?.identifier||e?.metadata?.id;return t?t.replace(/^copilot\//,""):null}function m_(o,e){let t=Eu(o);if(t)return t;let s=Ru(o);return s||(o.type==="session.start"&&typeof o.data?.selectedModel=="string"?o.data.selectedModel:o.type==="session.model_change"&&typeof o.data?.newModel=="string"?o.data.newModel:e)}function p_(o,e,t){let s=o;return s.modelId?s.modelId.replace(/^copilot\//,""):s.result?.metadata?.modelId?s.result.metadata.modelId.replace(/^copilot\//,""):s.result?.details?Lt(o,t):e}function g_(o,e,t,s,n){if(o.type==="user.message"){let i=o.model||s;ca(i,e,n),ua(i,t,n);return}if(!(o.kind!==2||o.k?.[0]!=="requests"||!Array.isArray(o.v)))for(let i of o.v){let r=p_(i,s,n);ca(r,e,n),ua(r,t,n)}}function f_(o,e,t){let s={standard:0,premium:0,unknown:0},n={low:0,medium:0,high:0,unknown:0},i="unknown";for(let r of o)if(r.trim())try{let a=JSON.parse(r);i=m_(a,i),wy(a,e),g_(a,s,n,i,t)}catch{}Au(s,e),xu(n,e)}async function Iu(o,e,t,s,n){try{let i=await ya(o,e,s,n),r=i?Object.keys(i).length:0;if(!i||r===0)return;let a=Object.keys(i);t.modelSwitching.uniqueModels=a,t.modelSwitching.modelCount=a.length;let c=l_(a,o.modelPricing);t.modelSwitching.tiers=c,t.modelSwitching.hasMixedTiers=c.standard.length>0&&c.premium.length>0;let d={low:[],medium:[],high:[],unknown:[]};for(let _ of a){let C=dn(_,o.modelPricing);C==="low"?d.low.push(_):C==="medium"?d.medium.push(_):C==="high"?d.high.push(_):d.unknown.push(_)}t.modelSwitching.costBuckets=d;let p=[d.low,d.medium,d.high].filter(_=>_.length>0).length;t.modelSwitching.hasMixedCosts=p>=2;let f=s??await Ls.promises.readFile(e,"utf8");if(vs(f))return;if(e.endsWith(".jsonl")||bt(f))f_(f.trim().split(`
|
|
143
|
+
`),t,o.modelPricing);else{let _=n!==void 0?n:JSON.parse(f);if(!Ei(_)){o.warn(`Unexpected session format in ${e}`);return}d_(_,t),u_(_,t,o.modelPricing)}}catch(i){o.warn(`Error calculating model switching for ${e}: ${i}`)}}function h_(o){if(o.length===0)return 0;let e=[...o].sort((i,r)=>i.start-r.start),t=0,s=e[0].start,n=e[0].end;for(let i=1;i<e.length;i++){let{start:r,end:a}=e[i];r<=n?n=Math.max(n,a):(t+=n-s,s=r,n=a)}return t+=n-s,t}function Uu(o,e){for(let[t,s]of Object.entries(e))o[t]||(o[t]={linesAdded:0,linesRemoved:0}),o[t].linesAdded+=s.linesAdded,o[t].linesRemoved+=s.linesRemoved}function y_(o,e){let t=!1;if(o.length>0)try{let i=JSON.parse(o[0]);i&&typeof i.kind=="number"&&(t=!0)}catch{}if(!t)return;let s={};for(let i of o)try{s=un(s,JSON.parse(i))}catch{}s.creationDate!==void 0&&e.timestamps.push(s.creationDate),s.lastMessageDate!==void 0&&e.timestamps.push(s.lastMessageDate);let n=Su(s.requests||[],e.agentCounts,e.editedFiles,e.timestamps,e.timingsData,e.waitTimes,e.activeIntervals);e.totalApplies=n.totalApplies,e.totalCodeBlocks=n.totalCodeBlocks,e.totalLinesAdded=n.totalLinesAdded,e.totalLinesRemoved=n.totalLinesRemoved,Uu(e.allLanguageUsage,n.languageUsage)}function __(o,e,t,s){if(!Ei(t))return o.warn(`Unexpected session format in ${e}`),!1;t.creationDate&&s.timestamps.push(t.creationDate),t.lastMessageDate&&s.timestamps.push(t.lastMessageDate);let n=Su(t.requests??[],s.agentCounts,s.editedFiles,s.timestamps,s.timingsData,s.waitTimes,s.activeIntervals);return s.totalApplies=n.totalApplies,s.totalCodeBlocks=n.totalCodeBlocks,s.totalLinesAdded=n.totalLinesAdded,s.totalLinesRemoved=n.totalLinesRemoved,Uu(s.allLanguageUsage,n.languageUsage),!0}function C_(o,e){let t=e.editedFiles.size>0?1:0;o.editScope={singleFileEdits:e.editedFiles.size===1?1:0,multiFileEdits:e.editedFiles.size>1?1:0,totalEditedFiles:e.editedFiles.size,avgFilesPerSession:t>0?e.editedFiles.size/t:0,linesAdded:e.totalLinesAdded,linesRemoved:e.totalLinesRemoved,...Object.keys(e.allLanguageUsage).length>0?{languageUsage:e.allLanguageUsage}:{}},o.applyUsage={totalApplies:e.totalApplies,totalCodeBlocks:e.totalCodeBlocks,applyRate:e.totalCodeBlocks>0?e.totalApplies/e.totalCodeBlocks*100:0};let s=e.timestamps.length>=2?Math.max(...e.timestamps)-Math.min(...e.timestamps):0,n=e.timingsData.length>0?e.timingsData.reduce((c,d)=>c+(d.firstProgress||0),0)/e.timingsData.length:0,i=e.timingsData.length>0?e.timingsData.reduce((c,d)=>c+(d.totalElapsed||0),0)/e.timingsData.length:0,r=e.waitTimes.length>0?e.waitTimes.reduce((c,d)=>c+d,0)/e.waitTimes.length:0,a=h_(e.activeIntervals);o.sessionDuration={totalDurationMs:s,avgDurationMs:s,avgFirstProgressMs:n,avgTotalElapsedMs:i,avgWaitTimeMs:r,activeDurationMs:a},fa(o),o.agentTypes=e.agentCounts}function bu(o){return o.length>0?(o.match(/\n/g)??[]).length+(o.endsWith(`
|
|
144
|
+
`)?0:1):0}function b_(o,e){let t=o.data?.toolName,s=o.data?.arguments??{},n=o.data?.toolCallId,i=s.path;if(typeof i!="string"||!i||typeof n!="string"||t!=="edit"&&t!=="create")return;let r=t==="edit"?s.new_str:s.file_text,a=t==="edit"?s.old_str:void 0,c=typeof r=="string"?r:"",d=typeof a=="string"?a:"";e.set(n,{filePath:i,added:bu(c),removed:bu(d)})}function k_(o,e,t){if(o.data?.success!==!0)return;let s=o.data?.toolCallId;if(typeof s!="string")return;let n=e.get(s);if(!n)return;e.delete(s),t.totalLinesAdded+=n.added,t.totalLinesRemoved+=n.removed,t.editedFiles.add(n.filePath);let i=pa(n.filePath);t.allLanguageUsage[i]||(t.allLanguageUsage[i]={linesAdded:0,linesRemoved:0}),t.allLanguageUsage[i].linesAdded+=n.added,t.allLanguageUsage[i].linesRemoved+=n.removed}function S_(o,e){let t=new Map;for(let s of o)try{let n=JSON.parse(s);n.type==="tool.execution_start"?b_(n,t):n.type==="tool.execution_complete"&&k_(n,t,e)}catch{}}async function da(o,e,t,s,n){try{let i=s??await Ls.promises.readFile(e,"utf8");if(vs(i))return;let r=e.endsWith(".jsonl")||bt(i),a={totalApplies:0,totalCodeBlocks:0,totalLinesAdded:0,totalLinesRemoved:0,allLanguageUsage:{},editedFiles:new Set,timestamps:[],timingsData:[],waitTimes:[],activeIntervals:[],agentCounts:{editsAgent:0,defaultAgent:0,workspaceAgent:0,other:0}};if(r){let c=i.trim().split(`
|
|
145
|
+
`).filter(d=>d.trim());y_(c,a),Ou(c)||S_(c,a)}else{let c=n!==void 0?n:JSON.parse(i);if(!__(o,e,c,a))return}C_(t,a)}catch(i){o.warn(`Error tracking enhanced metrics from ${e}: ${i}`)}}function H(){return{toolCalls:{total:0,byTool:{}},modeUsage:{ask:0,edit:0,agent:0,plan:0,customAgent:0,cli:0},contextReferences:G(),mcpTools:{total:0,byServer:{},byTool:{}},modelSwitching:{uniqueModels:[],modelCount:0,switchCount:0,autoSessions:0,foundryWindowsSessions:0,unknownProviderSessions:0,selectedModelExtensions:[],unknownProviderModels:[],tiers:{standard:[],premium:[],unknown:[]},hasMixedTiers:!1,standardRequests:0,premiumRequests:0,unknownRequests:0,totalRequests:0,costBuckets:{low:[],medium:[],high:[],unknown:[]},hasMixedCosts:!1,lowCostRequests:0,mediumCostRequests:0,highCostRequests:0}}}function T_(o,e,t){let s=o.efficiencyTurns[o.efficiencyTurns.length-1];s||(s={model:o.defaultModel,toolCalls:[]},o.efficiencyTurns.push(s)),s.toolCalls.push({toolName:e,arguments:t?JSON.stringify(t):void 0})}function Ou(o){if(o.length===0)return!1;try{let e=JSON.parse(o[0]);return e&&typeof e.kind=="number"}catch{return!1}}function w_(o,e,t){let s={};for(let n of e)try{let i=JSON.parse(n);s=un(s,i)}catch{}Ly(o,s,e,t)}function Fu(o,e){for(let t of o){let s=t;if(s&&(s.startLineNumber!==s.endLineNumber||s.startColumn!==s.endColumn)){e.implicitSelection++;break}}}function M_(o,e,t){o.kind!==0||!o.v?.inputState?.mode||(t.sessionMode=Io(o.v.inputState.mode),Array.isArray(o.v?.inputState?.selections)&&Fu(o.v.inputState.selections,e.contextReferences))}function P_(o,e,t){o.kind===1&&(o.k?.includes("mode")&&o.v&&(t.sessionMode=Io(o.v)),o.k?.includes("selections")&&Array.isArray(o.v)&&Fu(o.v,e.contextReferences),o.k?.includes("contentReferences")&&Array.isArray(o.v)&&ga(o.v,e.contextReferences),o.k?.includes("variableData")&&o.v&&vu(o.v,e.contextReferences))}function Nu(o){return o.toolId||o.toolName||o.invocationMessage?.toolName||o.toolSpecificData?.kind||"unknown"}function v_(o,e){for(let t of o)if(t&&(t.kind==="toolInvocationSerialized"||t.kind==="prepareToolInvocation")){e.toolCalls.total++;let s=Nu(t);e.toolCalls.byTool[s]=(e.toolCalls.byTool[s]||0)+1}}function A_(o,e){for(let t of o){let s=t;if(s&&s.kind==="toolInvocationSerialized"){e.toolCalls.total++;let n=Nu(s);e.toolCalls.byTool[n]=(e.toolCalls.byTool[n]||0)+1}}}function x_(o,e,t){o.requestId&&ku(t,e.modeUsage),o.agent?.id&&(e.toolCalls.total++,e.toolCalls.byTool[o.agent.id]=(e.toolCalls.byTool[o.agent.id]||0)+1),ha(o,e.contextReferences),o.response&&Array.isArray(o.response)&&v_(o.response,e)}function D_(o,e,t,s){if(o.kind===2){if(o.k?.[0]==="requests"&&Array.isArray(o.v))for(let n of o.v)x_(n,e,t.sessionMode);o.k?.includes("response")&&Array.isArray(o.v)&&A_(o.v,e)}}function E_(o,e){typeof o.selectedModel=="string"&&(e.defaultModel=o.selectedModel),typeof o.reasoningEffort=="string"&&(e.defaultEffort=o.reasoningEffort)}function R_(o,e){o==="agent"?e.modeUsage.agent++:o==="ask"?e.modeUsage.ask++:e.modeUsage.cli++}function I_(o,e){if(Array.isArray(o))for(let t of o){if(!t||typeof t!="object")continue;let s=t.displayName;typeof s=="string"&&(/clipboard\.png$/i.test(s)?e.byKind["copilot.image"]=(e.byKind["copilot.image"]||0)+1:(/^\d+ lines$/.test(s)||/\.[a-z0-9]+$/i.test(s))&&e.file++)}}function U_(o,e,t,s){if(o.type==="session.start"&&o.data&&E_(o.data,e),o.type==="session.model_change"&&typeof o.data?.newModel=="string"&&(e.defaultModel=o.data.newModel),o.type==="user.message"){e.requestCount++;let n=typeof o.data?.reasoningEffort=="string"?o.data.reasoningEffort:e.defaultEffort;n&&(e.effortByRequest[n]=(e.effortByRequest[n]||0)+1),e.efficiencyTurns.push({model:o.model||e.defaultModel,toolCalls:[]}),I_(o.data?.attachments,t.contextReferences),R_(s,t)}}function O_(o,e,t){if(o.type!=="tool.call"&&o.type!=="tool.result"&&o.type!=="tool.execution_start")return;let s=o.data?.toolName||o.toolName||"unknown";ma(s,e,t)}function F_(o,e){if(o.type!=="mcp.tool.call"&&!o.data?.mcpServer)return;e.mcpTools.total++;let t=o.data?.mcpServer||"unknown",s=o.data?.toolName||o.toolName||"unknown";e.mcpTools.byServer[t]=(e.mcpTools.byServer[t]||0)+1;let n=rn(s);e.mcpTools.byTool[n]=(e.mcpTools.byTool[n]||0)+1}function N_(o,e,t){O_(o,e,t),F_(o,e)}function la(o){if(!o)return 0;let e=o.split(`
|
|
146
|
+
`);return e[e.length-1]===""&&e.pop(),e.length}function Lu(o){o.editScope||(o.editScope={singleFileEdits:0,multiFileEdits:0,totalEditedFiles:0,avgFilesPerSession:0,linesAdded:0,linesRemoved:0})}function L_(o,e){let{toolCallId:t,toolName:s,arguments:n}=o.data??{};t&&s&&(e.pendingToolCalls.set(t,{toolName:s,args:n??{}}),T_(e,s,n))}function j_(o,e,t){let s=o.toolName==="edit"?la(o.args.new_str??""):la(o.args.file_text??""),n=o.toolName==="edit"?la(o.args.old_str??""):0;Lu(t),t.editScope.linesAdded=(t.editScope.linesAdded??0)+s,t.editScope.linesRemoved=(t.editScope.linesRemoved??0)+n;let i=o.args.path??"";e.editedFilePaths.add(i);let r=pa(i);t.editScope.languageUsage||(t.editScope.languageUsage={}),t.editScope.languageUsage[r]||(t.editScope.languageUsage[r]={linesAdded:0,linesRemoved:0}),t.editScope.languageUsage[r].linesAdded+=s,t.editScope.languageUsage[r].linesRemoved+=n}function G_(o){return typeof o=="string"?o:Array.isArray(o)?o.filter(e=>e?.type==="text"&&typeof e.text=="string").map(e=>e.text).join(""):""}function q_(o,e,t){let{toolCallId:s,success:n,result:i}=o.data??{},r=s?e.pendingToolCalls.get(s):void 0;if(s&&e.pendingToolCalls.delete(s),!r||(n&&(r.toolName==="edit"||r.toolName==="create")&&j_(r,e,t),!i?.content||st(r.toolName)))return;let a=G_(i.content);if(!a)return;let c=Z(a);t.toolCalls.outputTokensByTool||(t.toolCalls.outputTokensByTool={}),t.toolCalls.outputTokensByTool[r.toolName]=(t.toolCalls.outputTokensByTool[r.toolName]||0)+c}function B_(o,e,t){o.type==="tool.execution_start"?L_(o,e):o.type==="tool.execution_complete"&&q_(o,e,t)}function z_(o,e){if(o.editedFilePaths.size===0)return;Lu(e);let t=o.editedFilePaths.size;e.editScope.totalEditedFiles=t,e.editScope.singleFileEdits=t===1?1:0,e.editScope.multiFileEdits=t>1?1:0,e.editScope.avgFilesPerSession=t}function $_(o,e,t,s,n,i){M_(o,e,t),P_(o,e,t),D_(o,e,t,i),U_(o,s,e,n),N_(o,e,i),B_(o,s,e)}function H_(o,e){if(o.defaultEffort===null&&Object.keys(o.effortByRequest).length===0)return;let t=Object.keys(o.effortByRequest).length>0?o.effortByRequest:o.defaultEffort!==null?{[o.defaultEffort]:o.requestCount}:{};e.thinkingEffort={byEffort:t,switchCount:0,defaultEffort:o.defaultEffort}}async function W_(o,e,t,s,n){let i={sessionMode:"ask"},r={defaultModel:"unknown",defaultEffort:null,requestCount:0,effortByRequest:{},pendingToolCalls:new Map,editedFilePaths:new Set,efficiencyTurns:[]},c=bi(e)?yu(s):null;for(let d of t)if(d.trim())try{let p=JSON.parse(d);$_(p,n,i,r,c,o.toolNameMap)}catch{}z_(r,n),H_(r,n),r.efficiencyTurns.length>0&&(n.modelEfficiency=vi(r.efficiencyTurns)),await Iu(o,e,n,s),await da(o,e,n,s),fa(n)}async function J_(o,e,t){if(!(t.modelEfficiency||!o.buildTurns))try{let{turns:s}=await o.buildTurns(e),n=vi(s);Object.keys(n).length>0&&(t.modelEfficiency=n)}catch{}}async function ju(o,e,t,s){let n=H();try{let i=o.ecosystems.find(c=>c.handles(e));if(i&&Jl(i)){let c=await i.analyzeUsage(e,{modelPricing:o.modelPricing,toolNameMap:o.toolNameMap});return await J_(i,e,c),c}if(e.startsWith("windsurf://")||e.startsWith("devin://"))return n;let r=t??await Ls.promises.readFile(e,"utf8");if(e.endsWith(".jsonl")||bt(r)){let c=r.trim().split(`
|
|
147
|
+
`).filter(d=>d.trim());if(Ou(c))return w_(o,c,n),await da(o,e,n,r),n;await W_(o,e,c,r,n)}else{let c=s!==void 0?s:JSON.parse(r);if(!Ei(c))return o.warn(`Unexpected session format in ${e}`),n;zy(o,c,n),Mu(c.requests??[],jy(c),o.modelPricing,n),await Iu(o,e,n,r,s),await da(o,e,n,r,s)}}catch(i){o.warn(`Error analyzing session usage from ${e}: ${i}`)}return n}function Gu(o,e,t){if(o.result?.usage){let s=o.result.usage;return t[e].inputTokens+=typeof s.promptTokens=="number"?s.promptTokens:0,t[e].outputTokens+=typeof s.completionTokens=="number"?s.completionTokens:0,!0}return typeof o.result?.promptTokens=="number"&&typeof o.result?.outputTokens=="number"?(t[e].inputTokens+=o.result.promptTokens,t[e].outputTokens+=o.result.outputTokens,!0):o.result?.metadata&&typeof o.result.metadata.promptTokens=="number"&&typeof o.result.metadata.outputTokens=="number"?(t[e].inputTokens+=o.result.metadata.promptTokens,t[e].outputTokens+=o.result.metadata.outputTokens,!0):!1}function qu(o,e,t,s){for(let n of o){let i=Ms(n);if(i){let r=i.modelName||e;t[r]||(t[r]={inputTokens:0,outputTokens:0,sessions:0}),i.prompt&&(t[r].inputTokens+=Z(i.prompt,r,s)),i.result&&(t[r].outputTokens+=Z(i.result,r,s))}}}function V_(o,e,t){t[o]||(t[o]={inputTokens:0,outputTokens:0,sessions:0}),t[o].inputTokens+=typeof e.inputTokens=="number"?e.inputTokens:0,t[o].outputTokens+=typeof e.outputTokens=="number"?e.outputTokens:0;let s=typeof e.cacheReadTokens=="number"?e.cacheReadTokens:0,n=typeof e.cacheWriteTokens=="number"?e.cacheWriteTokens:0;s>0&&(t[o].cachedReadTokens=(t[o].cachedReadTokens??0)+s),n>0&&(t[o].cacheCreationTokens=(t[o].cacheCreationTokens??0)+n)}function K_(o,e){for(let[t,s]of Object.entries(o))s?.usage&&V_(t,s.usage,e)}function Q_(o,e,t,s,n){let i=typeof o.data?.outputTokens=="number"?o.data.outputTokens:0;i>0?(t.cliRealOutputByModel||(t.cliRealOutputByModel={}),t.cliRealOutputByModel[e]=(t.cliRealOutputByModel[e]??0)+i):o.data?.content&&(s[e].outputTokens+=Z(o.data.content,e,n.tokenEstimators))}function Y_(o,e){o.data?.modelMetrics&&(e.cliShutdownModelUsage||(e.cliShutdownModelUsage={}),K_(o.data.modelMetrics,e.cliShutdownModelUsage))}function X_(o,e,t,s,n){if(o.type==="session.shutdown")Y_(o,t);else if(o.type==="user.message"&&o.data?.content)s[e].inputTokens+=Z(o.data.content,e,n.tokenEstimators);else if(o.type==="assistant.message")Q_(o,e,t,s,n);else if(o.type==="tool.execution_start")t.totalCliToolCalls++;else if(o.type==="tool.execution_complete"){let i=o.data?.result?.content||o.data?.result?.detailedContent;i&&(s[e].inputTokens+=Z(String(i),e,n.tokenEstimators))}}function Z_(o){return o.kind!==0?null:o.v?.selectedModel?.identifier||o.v?.selectedModel?.metadata?.id||o.v?.inputState?.selectedModel?.metadata?.id||null}function eC(o){return o.kind!==2||o.k?.[0]!=="selectedModel"?null:o.v?.identifier||o.v?.metadata?.id||null}function tC(o,e){if(o.type==="session.start"&&typeof o.data?.selectedModel=="string"){e.defaultModel=o.data.selectedModel;return}if(o.type==="session.model_change"&&typeof o.data?.newModel=="string"){e.defaultModel=o.data.newModel;return}let t=Z_(o);t&&(e.defaultModel=t.replace(/^copilot\//,""));let s=eC(o);s&&(e.defaultModel=s.replace(/^copilot\//,""))}function sC(o,e,t,s){typeof o.kind=="number"&&(e.isDeltaBased=!0,e.sessionState=un(e.sessionState,o)),tC(o,e);let n=o.data?.model||o.model||e.defaultModel;t[n]||(t[n]={inputTokens:0,outputTokens:0,sessions:0}),e.isDeltaBased||X_(o,n,e,t,s)}function nC(o,e,t){let s={defaultModel:"unknown",isDeltaBased:!1,sessionState:{},cliShutdownModelUsage:null,cliRealOutputByModel:null,totalCliToolCalls:0};for(let n of o)if(n.trim())try{let i=JSON.parse(n);sC(i,s,e,t)}catch{}return s}function oC(o,e,t,s){if(o.message?.text&&(t[e].inputTokens+=Z(o.message.text,e,s.tokenEstimators)),o.response&&Array.isArray(o.response))for(let n of o.response){let{text:i}=Ps(n);i&&(t[e].outputTokens+=Z(i,e,s.tokenEstimators))}}function iC(o,e,t,s){if(!o.requestId)return;let n=e;o.modelId?n=o.modelId.replace(/^copilot\//,""):o.result?.metadata?.modelId?n=o.result.metadata.modelId.replace(/^copilot\//,""):o.result?.details&&(n=Lt(o,s.modelPricing)),t[n]||(t[n]={inputTokens:0,outputTokens:0,sessions:0}),Gu(o,n,t)||oC(o,n,t,s),o.response&&Array.isArray(o.response)&&qu(o.response,n,t,s.tokenEstimators)}function rC(o,e,t){if(!(!o.isDeltaBased||!o.sessionState.requests||!Array.isArray(o.sessionState.requests)))for(let s of o.sessionState.requests)s&&iC(s,o.defaultModel,e,t)}function aC(o,e,t){let s=Rr(o);for(let[n,i]of s){let r=e.sessionState.requests?.[n];if(!r||r.result?.usage||typeof r.result?.promptTokens=="number"||r.result?.metadata&&typeof r.result.metadata.promptTokens=="number")continue;let a=e.defaultModel;r.modelId&&(a=r.modelId.replace(/^copilot\//,"")),t[a]||(t[a]={inputTokens:0,outputTokens:0,sessions:0}),t[a].inputTokens+=i.promptTokens,t[a].outputTokens+=i.outputTokens}}function lC(o,e){let t=Math.max(1,Math.round(o.totalCliToolCalls/2)),s=Math.max(1,(t+1)/2),n={};for(let[i,r]of Object.entries(o.cliRealOutputByModel)){let a=e[i]?.inputTokens??0;n[i]={inputTokens:Math.round(a*s),outputTokens:r,sessions:0}}return n}function cC(o,e,t){let s=nC(o,e,t);return!s.isDeltaBased&&s.cliShutdownModelUsage?s.cliShutdownModelUsage:!s.isDeltaBased&&s.cliRealOutputByModel?lC(s,e):(rC(s,e,t),aC(o,s,e),null)}function uC(o,e,t,s){if(o.message?.parts)for(let n of o.message.parts)n.text&&(t[e].inputTokens+=Z(n.text,e,s.tokenEstimators));if(o.response&&Array.isArray(o.response))for(let n of o.response){let{text:i}=Ps(n);i&&(t[e].outputTokens+=Z(i,e,s.tokenEstimators))}}function dC(o,e,t){let s=Lt(o,t.modelPricing);e[s]||(e[s]={inputTokens:0,outputTokens:0,sessions:0}),Gu(o,s,e)||uC(o,s,e,t),o.response&&Array.isArray(o.response)&&qu(o.response,s,e,t.tokenEstimators)}function mC(o,e,t){if(!(!o.requests||!Array.isArray(o.requests)))for(let s of o.requests)dC(s,e,t)}async function pC(o,e,t,s){if(Ns(o)){let r=await ms(o);if(r&&Object.keys(r.modelUsage).length>0)return r.modelUsage}let n=e.trim().split(`
|
|
148
|
+
`);return cC(n,t,s)??t}async function gC(o,e,t,s,n){if(vs(e))return t;if(o.endsWith(".jsonl")||bt(e))return pC(o,e,t,s);let r=n!==void 0?n:JSON.parse(e);return Ei(r)?(mC(r,t,s),t):(s.warn(`Unexpected session format in ${o}`),t)}async function ya(o,e,t,s){let n={};if(o.ecosystems){let i=o.ecosystems.find(r=>r.handles(e));if(i)return i.getModelUsage(e)}if(e.startsWith("windsurf://")||e.startsWith("devin://"))return n;try{let i=t??await Ls.promises.readFile(e,"utf8");return await gC(e,i,n,o,s)}catch(i){o.warn(`Error getting model usage from ${e}: ${i}`)}return n}var Fn=class{constructor(e){this.openCode=e}openCode;id="opencode";displayName="OpenCode";handles(e){return this.openCode.isOpenCodeSessionFile(e)}getBackingPath(e){return this.openCode.isOpenCodeDbSession(e)?vt.join(this.openCode.getOpenCodeDataDir(),"opencode.db"):e}async stat(e){return this.openCode.statSessionFile(e)}async getTokens(e){let t=await this.openCode.getTokensFromOpenCodeSession(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return this.openCode.countOpenCodeInteractions(e)}async getModelUsage(e){return this.openCode.getOpenCodeModelUsage(e)}async getMeta(e){let t=[],s,n,i=await this.readOpenCodeSessionData(e);i&&(s=i.title||i.slug,n=i.directory||void 0,i.time?.created&&t.push(i.time.created),i.time?.updated&&t.push(i.time.updated));let r=await this.openCode.getOpenCodeMessagesForSession(e);for(let a of r)a.time?.created&&t.push(a.time.created),a.time?.completed&&t.push(a.time.completed);return t.sort((a,c)=>a-c),{title:s,firstInteraction:t.length>0?new Date(t[0]).toISOString():null,lastInteraction:t.length>0?new Date(t[t.length-1]).toISOString():null,workspacePath:n}}async readOpenCodeSessionData(e){let t=this.openCode.getOpenCodeSessionId(e);return this.openCode.isOpenCodeDbSession(e)&&t?this.openCode.readOpenCodeDbSession(t):os(async()=>JSON.parse(await Ri.promises.readFile(e,"utf8")),null,`openCodeAdapter getMeta readFile(${e})`)}getEditorRoot(e){return this.openCode.getOpenCodeDataDir()}async discover(e){let t=this.getCandidatePaths(),s=[],n=this.openCode.getOpenCodeDataDir(),i=vt.join(n,"storage","session"),r=vt.join(n,"opencode.db");if(e(`\u{1F4C1} Checking OpenCode JSON path: ${i}`),e(`\u{1F4C1} Checking OpenCode DB path: ${r}`),await Mt(i)){let d=async f=>{let h=[];try{h=await Ri.promises.readdir(f,{withFileTypes:!0})}catch(_){console.error(`[openCodeAdapter] Failed to read dir ${f}:`,_)}for(let _ of h)if(_.isDirectory())await d(vt.join(f,_.name));else if(_.name.startsWith("ses_")&&_.name.endsWith(".json")){let C=vt.join(f,_.name);try{(await Ri.promises.stat(C)).size>0&&s.push(C)}catch(T){console.error(`[openCodeAdapter] Failed to stat ${C}:`,T)}}};await d(i);let p=s.length;p>0&&e(`\u{1F4C4} Found ${p} session files in OpenCode storage`)}if(await Mt(r))try{let d=new Set(s.filter(h=>this.openCode.isOpenCodeSessionFile(h)).map(h=>this.openCode.getOpenCodeSessionId(h)).filter(Boolean)),p=await this.openCode.discoverOpenCodeDbSessions(),f=0;for(let h of p)d.has(h)||(s.push(vt.join(n,`opencode.db#${h}`)),f++);f>0&&e(`\u{1F4C4} Found ${f} additional session(s) in OpenCode database`)}catch(d){e(`OpenCode DB exists but could not be read: ${d}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){let e=this.openCode.getOpenCodeDataDir();return[{path:vt.join(e,"storage","session"),source:"OpenCode (JSON)"},{path:vt.join(e,"opencode.db"),source:"OpenCode (DB)"}]}async buildTurns(e){let t=[],s=await this.openCode.getOpenCodeMessagesForSession(e),n=0,i=0;for(let r=0;r<s.length;r++){let a=s[r];if(a.role!=="user")continue;i++;let c=s.filter((_,C)=>C>r&&_.role==="assistant"&&_.parentID===a.id),p=(await this.openCode.getOpenCodePartsForMessage(a.id)).filter(_=>_.type==="text").map(_=>_.text||"").join(`
|
|
149
|
+
`),f=await this.processOpenCodeAssistantMessages(c,n),h=Math.max(0,f.turnCumulativeTotal-n-f.turnOutputAndThinking);t.push({turnNumber:i,timestamp:a.time?.created?new Date(a.time.created).toISOString():null,mode:"cli",userMessage:p,assistantResponse:f.assistantText,model:f.model,toolCalls:f.toolCalls,contextReferences:G(),mcpTools:[],inputTokensEstimate:h,outputTokensEstimate:f.turnOutputAndThinking-f.thinkingTokens,thinkingTokensEstimate:f.thinkingTokens}),n=f.turnCumulativeTotal}return{turns:t}}async processOpenCodeAssistantMessages(e,t){let s="",n=[],i=null,r=0,a=t;for(let d of e){i||(i=d.modelID||d.model?.modelID||null),r+=d.tokens?.reasoning||0,typeof d.tokens?.total=="number"&&(a=Math.max(a,d.tokens.total));let p=await this.openCode.getOpenCodePartsForMessage(d.id);for(let f of p)s+=this.processOpenCodePart(f,n)}let c=e.reduce((d,p)=>d+(p.tokens?.output||0)+(p.tokens?.reasoning||0),0);return{assistantText:s,toolCalls:n,model:i,thinkingTokens:r,turnCumulativeTotal:a,turnOutputAndThinking:c}}processOpenCodePart(e,t){return e.type==="text"&&e.text?e.text:(e.type==="tool"&&e.tool&&t.push({toolName:e.tool,arguments:e.state?.input?JSON.stringify(e.state.input):void 0,result:e.state?.output||void 0}),"")}async getSyncData(e){return this.openCode.getOpenCodeSessionData(e)}async analyzeUsage(e,t){let s=H(),n=await this.openCode.getOpenCodeMessagesForSession(e),i=[];for(let r of n)r.role==="user"&&s.modeUsage.cli++,r.role==="assistant"&&await this.processOpenCodeAssistantMessage(r,s,i);if(i.length>0){let r=[...new Set(i)];s.modelSwitching.uniqueModels=r,s.modelSwitching.modelCount=r.length,s.modelSwitching.totalRequests=i.length;let a=0;for(let c=1;c<i.length;c++)i[c]!==i[c-1]&&a++;s.modelSwitching.switchCount=a,Q(t.modelPricing,r,i,s)}return s}async processOpenCodeAssistantMessage(e,t,s){s.push(e.modelID||"unknown");let n=await this.openCode.getOpenCodePartsForMessage(e.id);for(let i of n)i.type!=="tool"||!i.tool||(t.toolCalls.total++,t.toolCalls.byTool[i.tool]=(t.toolCalls.byTool[i.tool]||0)+1)}};var Bu=S(require("fs")),At=S(require("path"));var Nn=class{constructor(e){this.crush=e}crush;id="crush";displayName="Crush";handles(e){return this.crush.isCrushSessionFile(e)}getBackingPath(e){return this.crush.getCrushDbPath(e)}async stat(e){return this.crush.statSessionFile(e)}async getTokens(e){let t=await this.crush.getTokensFromCrushSession(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return this.crush.countCrushInteractions(e)}async getModelUsage(e){return this.crush.getCrushModelUsage(e)}async getMeta(e){let t=[],s=await this.crush.readCrushSession(e),n;s&&(n=s.title||void 0,s.created_at&&t.push(s.created_at*1e3),s.updated_at&&t.push(s.updated_at*1e3));let i=await this.crush.getCrushMessages(e);for(let r of i)r.created_at&&t.push(r.created_at*1e3),r.finished_at&&t.push(r.finished_at*1e3);return t.sort((r,a)=>r-a),{title:n,firstInteraction:t.length>0?new Date(t[0]).toISOString():null,lastInteraction:t.length>0?new Date(t[t.length-1]).toISOString():null}}getEditorRoot(e){return At.dirname(this.crush.getCrushDbPath(e))}async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=this.crush.readCrushProjects();e(`\u{1F4C1} Crush: found ${n.length} project(s) in projects.json`);let i=await Promise.all(n.map(async a=>{let c=At.join(a.data_dir,"crush.db");e(`\u{1F4C1} Checking Crush DB path: ${c}`);try{return await Bu.promises.access(c),(await this.crush.discoverSessionsInDb(c)).map(p=>At.join(a.data_dir,`crush.db#${p}`))}catch(d){e(`Could not read Crush database for ${a.path}: ${d}`)}return[]})),r=i.reduce((a,c)=>a+c.length,0);r>0&&e(`\u{1F4C4} Found ${r} session(s) in Crush database(s)`),s.push(...i.flat())}catch(n){e(`Could not read Crush projects: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){let e=this.crush.getCrushConfigDir(),t=[{path:At.join(e,"projects.json"),source:"Crush (projects.json)"}],s=xr(()=>this.crush.readCrushProjects().map(n=>({path:At.join(n.data_dir,"crush.db"),source:`Crush (${At.basename(n.path)})`})),[],"crushAdapter getCandidatePaths");return t.push(...s),t}async buildTurns(e){let t=[],s=await this.crush.getCrushMessages(e),n=await this.crush.readCrushSession(e),i=s.filter(a=>a.role==="user").length,r=0;for(let a=0;a<s.length;a++){let c=s[a];if(c.role!=="user")continue;r++;let d=[];for(let p=a+1;p<s.length&&s[p].role!=="user";p++)s[p].role==="assistant"&&d.push(s[p]);t.push(this.buildCrushTurn(c,d,n,i,r))}return{turns:t}}buildCrushTurn(e,t,s,n,i){let a=(Array.isArray(e.parts)?e.parts:[]).filter(_=>_?.type==="text"&&_?.text).map(_=>_.text).join(`
|
|
150
|
+
`),{assistantText:c,toolCalls:d,model:p}=this.processAssistantMessagesForTurn(t),f=s?.prompt_tokens&&n>0?Math.round(s.prompt_tokens/n):0,h=s?.completion_tokens&&n>0?Math.round(s.completion_tokens/n):0;return{turnNumber:i,timestamp:e.created_at?new Date(e.created_at*1e3).toISOString():null,mode:"cli",userMessage:a,assistantResponse:c,model:p,toolCalls:d,contextReferences:G(),mcpTools:[],inputTokensEstimate:f,outputTokensEstimate:h,thinkingTokensEstimate:0}}processAssistantMessagesForTurn(e){let t="",s=[],n=null;for(let i of e){n||(n=i.model||null);for(let r of Array.isArray(i.parts)?i.parts:[])t+=this.processCrushMessagePart(r,s)}return{assistantText:t,toolCalls:s,model:n}}processCrushMessagePart(e,t){return e?.type==="text"&&e?.text?e.text:(e?.type==="tool_call"&&e?.data?.name&&t.push({toolName:e.data.name,arguments:e.data.arguments?JSON.stringify(e.data.arguments):void 0}),"")}async getSyncData(e){return this.crush.getCrushSessionData(e)}async analyzeUsage(e,t){let s=H(),n=await this.crush.getCrushMessages(e),i=[];for(let r of n)r.role==="user"&&s.modeUsage.cli++,r.role==="assistant"&&this.processCrushAssistantMessage(r,s,i);return this.applyCrushModelSwitchingStats(i,s),Q(t.modelPricing,s.modelSwitching.uniqueModels,i,s),s}processCrushAssistantMessage(e,t,s){s.push(e.model||"unknown");for(let n of Array.isArray(e.parts)?e.parts:[]){if(n?.type!=="tool_call"||!n?.data?.name)continue;t.toolCalls.total++;let i=n.data.name;t.toolCalls.byTool[i]=(t.toolCalls.byTool[i]||0)+1}}applyCrushModelSwitchingStats(e,t){let s=[...new Set(e)];t.modelSwitching.uniqueModels=s,t.modelSwitching.modelCount=s.length,t.modelSwitching.totalRequests=e.length;let n=0;for(let i=1;i<e.length;i++)e[i]!==e[i-1]&&n++;t.modelSwitching.switchCount=n}};var zu=S(require("fs")),$u=S(require("path")),Hu=S(ea());var Ln=class{constructor(e,t){this.visualStudio=e;this.estimateTokens=t}visualStudio;estimateTokens;id="visualstudio";displayName="Visual Studio";handles(e){return this.visualStudio.isVSSessionFile(e)}getDisplayName(e){return X(e).includes("/ssmsgithubcopilot/")?"SSMS":"Visual Studio"}getBackingPath(e){return e}async stat(e){return this.visualStudio.statSessionFile(e)}async getTokens(e){let t=await this.visualStudio.getTokenEstimates(e,this.estimateTokens);return{...t,actualTokens:t.tokens}}async countInteractions(e){let t=await this.visualStudio.decodeSessionFile(e);return this.visualStudio.countInteractions(t)}async getModelUsage(e){return this.visualStudio.getModelUsage(e,this.estimateTokens)}async getMeta(e){let t=await this.visualStudio.decodeSessionFile(e),s=this.visualStudio.getSessionTitle(t),n=this.visualStudio.getSessionTimestamps(t),i=[];return n.timeCreated&&i.push(new Date(n.timeCreated).getTime()),n.timeUpdated&&i.push(new Date(n.timeUpdated).getTime()),i.sort((r,a)=>r-a),{title:s,firstInteraction:i.length>0?new Date(i[0]).toISOString():null,lastInteraction:i.length>0?new Date(i[i.length-1]).toISOString():null}}getEditorRoot(e){return $u.dirname(e)}skipBackendSync=!0;async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=await this.visualStudio.discoverSessions();n.length>0&&(e(`\u{1F4C4} Found ${n.length} session file(s) in Visual Studio Copilot`),s.push(...n))}catch(n){e(`Could not read Visual Studio session files: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.visualStudio.getLogDir(),source:"Visual Studio (log dir)"},{path:this.visualStudio.getSsmsSessionsDir(),source:"SSMS (sessions dir)"}]}getRawFileContent(e){try{let t=zu.readFileSync(e),n=(t.length>=2?Array.from((0,Hu.decodeMulti)(t.slice(1))):[]).map((i,r)=>r===0?i:i?.[1]??i);return JSON.stringify(n,null,2)}catch{return"[]"}}async buildTurns(e){let t=[],s=await this.visualStudio.decodeSessionFile(e),n=0;for(let i=1;i<s.length;i+=2){let r=s[i],a=s[i+1];r&&(n++,t.push(this.buildVSTurn(r,a,n)))}return{turns:t}}buildVSTurn(e,t,s){let n=e[1],i=t?.[1],r=this.visualStudio.extractTextFromContent(n?.Content||[]),a=t?this.visualStudio.extractTextFromContent(i?.Content||[]):"",c=this.visualStudio.getModelId(i??n,!i),d=this.visualStudio.extractContextText(n?.Context),p=this.estimateTokens(r+d,c??"gpt-4"),f=t?this.estimateTokens(a,c??"gpt-4"):0;return{turnNumber:s,timestamp:n?.Timestamp?new Date(n.Timestamp).toISOString():null,mode:"ask",userMessage:r,assistantResponse:a,model:c,toolCalls:this.extractVSToolCalls(i),contextReferences:G(),mcpTools:[],inputTokensEstimate:p,outputTokensEstimate:f,thinkingTokensEstimate:0}}extractVSToolCalls(e){let t=[];for(let s of e?.Content||[]){let n=Array.isArray(s)?s[1]:null;n?.Function&&t.push({toolName:String(n.Function.Description||"tool"),result:typeof n.Function.Result=="string"?n.Function.Result:void 0})}return t}async analyzeUsage(e,t){let s=H(),n=await this.visualStudio.decodeSessionFile(e),i=[];for(let c=1;c<n.length;c++)c%2===1?s.modeUsage.ask++:this.processVSResponseObject(n[c]?.[1],s,i,t);let r=[...new Set(i)];s.modelSwitching.uniqueModels=r,s.modelSwitching.modelCount=r.length,s.modelSwitching.totalRequests=i.length;let a=0;for(let c=1;c<i.length;c++)i[c]!==i[c-1]&&a++;return s.modelSwitching.switchCount=a,Q(t.modelPricing,r,i,s),s}processVSResponseObject(e,t,s,n){let i=this.visualStudio.getModelId(e,!1);i&&s.push(i);for(let r of e?.Content??[]){let a=Array.isArray(r)?r[1]:null;if(!a?.Function)continue;t.toolCalls.total++;let c=String(a.Function.Name||a.Function.Description||"tool");if(st(c)){t.mcpTools.total++;let d=ft(c,n.toolNameMap);t.mcpTools.byServer[d]=(t.mcpTools.byServer[d]||0)+1;let p=rn(c);t.mcpTools.byTool[p]=(t.mcpTools.byTool[p]||0)+1,t.toolCalls.total--}else t.toolCalls.byTool[c]=(t.toolCalls.byTool[c]||0)+1}}};var _a=S(require("fs"));var jn=class{constructor(e){this.continue_=e}continue_;id="continue";displayName="Continue";handles(e){return this.continue_.isContinueSessionFile(e)}getBackingPath(e){return e}async stat(e){return _a.promises.stat(e)}async getTokens(e){let t=await this.continue_.getTokensFromContinueSession(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return await this.continue_.countContinueInteractions(e)}async getModelUsage(e){return await this.continue_.getContinueModelUsage(e)}async getMeta(e){let t=await this.continue_.getContinueSessionMeta(e),s=this.continue_.getContinueSessionId(e),n=(await this.continue_.readSessionsIndex()).get(s),i=null,r=null;if(n?.dateCreated){i=new Date(n.dateCreated).toISOString();try{r=(await _a.promises.stat(e)).mtime.toISOString()}catch{}}let a;if(t?.workspaceDirectory)try{a=decodeURIComponent(t.workspaceDirectory.replace(/^file:\/\/\//,"").replace(/^file:\/\//,""))}catch{}return{title:t?.title,firstInteraction:i,lastInteraction:r,workspacePath:a}}getEditorRoot(e){return this.continue_.getContinueDataDir()}async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=await this.continue_.getContinueSessionFiles();n.length>0&&(e(`\u{1F4C4} Found ${n.length} session file(s) in Continue (~/.continue/sessions)`),s.push(...n))}catch(n){e(`Could not read Continue session files: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.continue_.getContinueSessionsDir(),source:"Continue"}]}async buildTurns(e){let t=[],s=await this.continue_.buildContinueTurns(e),n=G();for(let i of s)t.push({turnNumber:t.length+1,timestamp:null,mode:"ask",userMessage:i.userText,assistantResponse:i.assistantText,model:i.model,toolCalls:i.toolCalls,contextReferences:n,mcpTools:[],inputTokensEstimate:i.inputTokens,outputTokensEstimate:i.outputTokens,thinkingTokensEstimate:0});return{turns:t}}async analyzeUsage(e,t){let s=H(),n=await this.continue_.buildContinueTurns(e),i=await this.continue_.getContinueSessionMeta(e),r=[];for(let d of n){s.modeUsage.ask++,d.model&&r.push(d.model);for(let p of d.toolCalls)s.toolCalls.total++,s.toolCalls.byTool[p.toolName]=(s.toolCalls.byTool[p.toolName]||0)+1}if(i?.mode==="agent")for(let d=0;d<n.length;d++)s.modeUsage.ask--,s.modeUsage.agent++;let a=[...new Set(r)];s.modelSwitching.uniqueModels=a,s.modelSwitching.modelCount=a.length,s.modelSwitching.totalRequests=r.length;let c=0;for(let d=1;d<r.length;d++)r[d]!==r[d-1]&&c++;return s.modelSwitching.switchCount=c,Q(t.modelPricing,a,r,s),s}};var Vu=S(require("fs")),Ui=S(require("path"));function Wu(o){switch((o||"").toLowerCase()){case"agent":return"agent";case"edit":return"edit";case"plan":return"plan";case"ask":return"ask";default:return"ask"}}function Ju(o){if(!o)return null;let e=Date.parse(o);return Number.isNaN(e)?null:new Date(e).toISOString()}var Ii=class{constructor(e){this.eclipse=e}eclipse;id="eclipse";displayName="Eclipse";handles(e){return this.eclipse.isEclipseSessionFile(e)}getBackingPath(e){return e}async stat(e){return Vu.promises.stat(e)}async getTokens(e){let t=await this.eclipse.getTokensFromEclipseSession(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return this.eclipse.countEclipseInteractions(e)}async getModelUsage(e){return this.eclipse.getEclipseModelUsage(e)}async getMeta(e){let t=await this.eclipse.getEclipseSessionMeta(e);return{title:t?.title,firstInteraction:Ju(t?.creationDate),lastInteraction:Ju(t?.lastMessageDate)}}getEditorRoot(e){return Ui.dirname(e)}async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=await this.eclipse.discoverEclipseSessions();n.length>0&&(e(`\u{1F4C4} Found ${n.length} session file(s) in Eclipse (Copilot conversations)`),s.push(...n))}catch(n){e(`Could not read Eclipse session files: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:Ui.join(this.eclipse.getDefaultWorkspaceRoot(),".metadata",".plugins","com.microsoft.copilot.eclipse.core","conversations"),source:"Eclipse"}]}async buildTurns(e){let t=[],s=await this.eclipse.buildEclipseTurns(e),n=G();for(let i of s)t.push({turnNumber:t.length+1,timestamp:i.timestamp,mode:Wu(i.mode),userMessage:i.userText,assistantResponse:i.assistantText,model:i.model,toolCalls:i.toolCalls,contextReferences:n,mcpTools:[],inputTokensEstimate:i.inputTokens,outputTokensEstimate:i.outputTokens,thinkingTokensEstimate:i.thinkingTokens,thinkingEffort:i.reasoningEffort??void 0});return{turns:t}}async analyzeUsage(e,t){let s=H(),n=await this.eclipse.buildEclipseTurns(e),i=[];for(let c of n){this.tallyMode(s,c.mode),c.model&&i.push(c.model);for(let d of c.toolCalls)s.toolCalls.total++,s.toolCalls.byTool[d.toolName]=(s.toolCalls.byTool[d.toolName]||0)+1}let r=[...new Set(i)];s.modelSwitching.uniqueModels=r,s.modelSwitching.modelCount=r.length,s.modelSwitching.totalRequests=i.length;let a=0;for(let c=1;c<i.length;c++)i[c]!==i[c-1]&&a++;return s.modelSwitching.switchCount=a,Q(t.modelPricing,r,i,s),s}tallyMode(e,t){let s=Wu(t);s==="agent"?e.modeUsage.agent++:s==="edit"?e.modeUsage.edit++:e.modeUsage.ask++}};var Qu=S(require("fs"));var Ku=S(require("fs"));var fC=new Set(["review","bug","think","compact","pr_comments"]);function Ca(o){let e="";if(typeof o=="string")e=o;else if(Array.isArray(o)){for(let i of o)if(i?.type==="text"&&typeof i.text=="string"){e=i.text;break}}let s=e.trimStart().split(`
|
|
151
|
+
`)[0].trim().match(/^\/([a-z_]+)(?:\s|$)/i);if(!s)return null;let n=s[1].toLowerCase();return fC.has(n)?n:null}var Gn=class{constructor(e,t=st,s=ft,n=()=>0){this.claudeCode=e;this.isMcpToolFn=t;this.extractMcpServerNameFn=s;this.estimateTokensFn=n}claudeCode;isMcpToolFn;extractMcpServerNameFn;estimateTokensFn;id="claudecode";displayName="Claude Code";handles(e){return this.claudeCode.isClaudeCodeSessionFile(e)}getDisplayName(e){return Uo(e)}getBackingPath(e){return e}async stat(e){return Ku.promises.stat(e)}async getTokens(e){let t=await this.claudeCode.getTokensFromClaudeCodeSession(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return await this.claudeCode.countClaudeCodeInteractions(e)}async getModelUsage(e){return await this.claudeCode.getClaudeCodeModelUsage(e)}async getMeta(e){let t=await this.claudeCode.getClaudeCodeSessionMeta(e);return{title:t?.title,firstInteraction:t?.firstInteraction||null,lastInteraction:t?.lastInteraction||null,workspacePath:t?.cwd}}async getDailyFractions(e){return await this.claudeCode.getClaudeCodeDailyFractions(e)}getEditorRoot(e){return this.claudeCode.getClaudeCodeProjectsDir()}async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=await this.claudeCode.getClaudeCodeSessionFiles();n.length>0&&(e(`\u{1F4C4} Found ${n.length} session file(s) in Claude Code (~/.claude/projects)`),s.push(...n))}catch(n){e(`Could not read Claude Code session files: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.claudeCode.getClaudeCodeProjectsDir(),source:"Claude Code"}]}async buildTurns(e){let t=[],s=await On(e),n=null,i=[];for(let a of s)if(a.type==="user"&&!a.isSidechain&&a.message?.role==="user"&&this.isRealUserMessage(a)){let c=this.buildTurnFromEvents(n,i,t.length+1);c&&t.push(c),n=a,i.length=0}else a.type==="assistant"&&a.message?.stop_reason&&a.message?.role==="assistant"&&i.push(a);let r=this.buildTurnFromEvents(n,i,t.length+1);return r&&t.push(r),{turns:t}}isRealUserMessage(e){let t=e.message?.content;if(typeof t=="string")return!!t.trim();if(!Array.isArray(t))return!1;let s=t.some(i=>i.type==="text"),n=t.some(i=>i.type==="tool_result");return s&&!n}buildTurnFromEvents(e,t,s){if(!e)return null;let n=e.message?.content,i=typeof n=="string"?n:Array.isArray(n)?n.filter(C=>C.type==="text").map(C=>C.text||"").join(`
|
|
152
|
+
`):"",{assistantText:r,model:a,actualInputTokens:c,actualOutputTokens:d,toolCalls:p,mcpTools:f}=this.processAssistantEventsForTurn(t),h=a||"claude-sonnet-4-6",_=c>0||d>0?{promptTokens:c,completionTokens:d}:void 0;return{turnNumber:s,timestamp:e.timestamp?new Date(e.timestamp).toISOString():null,mode:"agent",userMessage:i,assistantResponse:r,model:h,toolCalls:p,contextReferences:G(),mcpTools:f,inputTokensEstimate:c||this.estimateTokensFn(i,h),outputTokensEstimate:d||this.estimateTokensFn(r,h),thinkingTokensEstimate:0,actualUsage:_}}processAssistantEventsForTurn(e){let t="",s=0,n=0,i=null,r=[],a=[],c=new Set;for(let d of e){let p=d.message;!i&&p?.model&&(i=Gt(p.model));let f=p?.id,h=!f||!c.has(f);f&&c.add(f),p?.usage&&h&&(s+=this.extractInputTokens(p.usage),n+=p.usage.output_tokens||0);for(let _ of Array.isArray(p?.content)?p.content:[])t+=this.processContentBlock(_,r,a)}return{assistantText:t,model:i,actualInputTokens:s,actualOutputTokens:n,toolCalls:r,mcpTools:a}}extractInputTokens(e){return(e.input_tokens||0)+(e.cache_creation_input_tokens||0)+(e.cache_read_input_tokens||0)}processContentBlock(e,t,s){if(e.type==="text")return e.text||"";if(e.type==="tool_use"){let n=e.name||"unknown";this.isMcpToolFn(n)?s.push({server:this.extractMcpServerNameFn(n),tool:n}):t.push({toolName:n,arguments:e.input?JSON.stringify(e.input):void 0})}return""}async analyzeUsage(e,t){let s=H(),n=await On(e),i=[];for(let r of n)r.type==="user"&&r.message?.role==="user"&&!r.isSidechain?this.processUserEvent(r,s):r.type==="assistant"?this.processAssistantEvent(r,s,t,i):r.type==="system"&&r.subtype==="compact_boundary"&&this.processCompactBoundaryEvent(r,s);return this.applyModelSwitchingStats(i,s),Q(t.modelPricing,s.modelSwitching.uniqueModels,i,s),s}processCompactBoundaryEvent(e,t){e.compactMetadata?.trigger==="auto"&&(t.toolCalls.byTool.__auto_compact__=(t.toolCalls.byTool.__auto_compact__||0)+1)}processUserEvent(e,t){t.modeUsage.cli++;let s=Ca(e.message?.content);if(s){let n=`__slash__${s}`;t.toolCalls.byTool[n]=(t.toolCalls.byTool[n]||0)+1}}processAssistantEvent(e,t,s,n){let i=Gt(e.message?.model||"unknown");n.push(i);let r=Array.isArray(e.message?.content)?e.message.content:[];for(let a of r){if(a?.type!=="tool_use")continue;let c=String(a.name||"tool");if(st(c)){let d=ft(c,s.toolNameMap);t.mcpTools.total++,t.mcpTools.byServer[d]=(t.mcpTools.byServer[d]||0)+1,t.mcpTools.byTool[c]=(t.mcpTools.byTool[c]||0)+1}else t.toolCalls.total++,t.toolCalls.byTool[c]=(t.toolCalls.byTool[c]||0)+1}}applyModelSwitchingStats(e,t){let s=[...new Set(e)];t.modelSwitching.uniqueModels=s,t.modelSwitching.modelCount=s.length,t.modelSwitching.totalRequests=e.length;let n=0;for(let i=1;i<e.length;i++)e[i]!==e[i-1]&&n++;t.modelSwitching.switchCount=n}};var qn=class{constructor(e,t,s,n){this.claudeDesktopCowork=e;this.isMcpToolFn=t;this.extractMcpServerNameFn=s;this.estimateTokensFn=n}claudeDesktopCowork;isMcpToolFn;extractMcpServerNameFn;estimateTokensFn;id="claudedesktop";displayName="Claude Desktop Cowork";handles(e){return this.claudeDesktopCowork.isCoworkSessionFile(e)}getBackingPath(e){return e}async stat(e){return Qu.promises.stat(e)}async getTokens(e){let t=await this.claudeDesktopCowork.getTokensFromCoworkSession(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return await this.claudeDesktopCowork.countCoworkInteractions(e)}async getModelUsage(e){return await this.claudeDesktopCowork.getCoworkModelUsage(e)}async getMeta(e){let t=await this.claudeDesktopCowork.getCoworkSessionMeta(e);return{title:t?.title,firstInteraction:t?.firstInteraction||null,lastInteraction:t?.lastInteraction||null,workspacePath:t?.cwd}}getEditorRoot(e){return this.claudeDesktopCowork.getCoworkBaseDir()}async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=await this.claudeDesktopCowork.getCoworkSessionFiles();n.length>0&&(e(`\u{1F4C4} Found ${n.length} session file(s) in Claude Desktop Cowork`),s.push(...n))}catch(n){e(`Could not read Claude Desktop Cowork session files: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){let e=this.claudeDesktopCowork.getCoworkBaseDir();return e?[{path:e,source:"Claude Desktop (Cowork)"}]:[]}async buildTurns(e){let t=[],s=await this.claudeDesktopCowork.readCoworkEvents(e),n=null,i=[];for(let a of s)if(a.type==="user"&&!a.isSidechain&&a.message?.role==="user"&&this.isRealUserMessage(a)){let c=this.buildTurnFromEvents(n,i,t.length+1);c&&t.push(c),n=a,i.length=0}else a.type==="assistant"&&a.message?.stop_reason&&a.message?.role==="assistant"&&i.push(a);let r=this.buildTurnFromEvents(n,i,t.length+1);return r&&t.push(r),{turns:t}}isRealUserMessage(e){let t=e.message?.content;if(typeof t=="string")return!!t.trim();if(!Array.isArray(t))return!1;let s=t.some(i=>i.type==="text"),n=t.some(i=>i.type==="tool_result");return s&&!n}buildTurnFromEvents(e,t,s){if(!e)return null;let n=e.message?.content,i=typeof n=="string"?n:Array.isArray(n)?n.filter(C=>C.type==="text").map(C=>C.text||"").join(`
|
|
153
|
+
`):"",{assistantText:r,model:a,actualInputTokens:c,actualOutputTokens:d,toolCalls:p,mcpTools:f}=this.processAssistantEventsForTurn(t),h=a||"claude-sonnet-4-6",_=c>0||d>0?{promptTokens:c,completionTokens:d}:void 0;return{turnNumber:s,timestamp:e.timestamp?new Date(e.timestamp).toISOString():null,mode:"agent",userMessage:i,assistantResponse:r,model:h,toolCalls:p,contextReferences:G(),mcpTools:f,inputTokensEstimate:c||this.estimateTokensFn(i,h),outputTokensEstimate:d||this.estimateTokensFn(r,h),thinkingTokensEstimate:0,actualUsage:_}}processAssistantEventsForTurn(e){let t="",s=0,n=0,i=null,r=[],a=[],c=new Set;for(let d of e){let p=d.message;!i&&p?.model&&(i=p.model);let f=d.requestId,h=!f||!c.has(f);f&&c.add(f);let _=p?.usage;if(_&&h){let C=this.extractUsageTokens(_);s+=C.input,n+=C.output}for(let C of Array.isArray(p?.content)?p.content:[])t+=this.processEventContentBlock(C,r,a)}return{assistantText:t,model:i,actualInputTokens:s,actualOutputTokens:n,toolCalls:r,mcpTools:a}}extractUsageTokens(e){return{input:(e.input_tokens||0)+(e.cache_creation_input_tokens||0)+(e.cache_read_input_tokens||0),output:e.output_tokens||0}}processEventContentBlock(e,t,s){if(e.type==="text")return e.text||"";if(e.type==="tool_use"){let n=e.name||"unknown";this.isMcpToolFn(n)?s.push({server:this.extractMcpServerNameFn(n),tool:n}):t.push({toolName:n,arguments:e.input?JSON.stringify(e.input):void 0})}return""}async analyzeUsage(e,t){let s=H(),n=await On(e),i=[];for(let r of n)r.type==="user"&&r.message?.role==="user"&&!r.isSidechain?this.processDesktopUserEvent(r,s):r.type==="assistant"&&this.processDesktopAssistantEvent(r,s,i);return this.applyDesktopModelSwitchingStats(i,s),Q(t.modelPricing,s.modelSwitching.uniqueModels,i,s),s}processDesktopUserEvent(e,t){t.modeUsage.ask++;let s=Ca(e.message?.content);if(s){let n=`__slash__${s}`;t.toolCalls.byTool[n]=(t.toolCalls.byTool[n]||0)+1}}processDesktopAssistantEvent(e,t,s){let n=Gt(e.message?.model||"unknown");s.push(n);let i=Array.isArray(e.message?.content)?e.message.content:[];for(let r of i){if(r?.type!=="tool_use")continue;t.toolCalls.total++;let a=String(r.name||"tool");t.toolCalls.byTool[a]=(t.toolCalls.byTool[a]||0)+1}}applyDesktopModelSwitchingStats(e,t){let s=[...new Set(e)];t.modelSwitching.uniqueModels=s,t.modelSwitching.modelCount=s.length,t.modelSwitching.totalRequests=e.length;let n=0;for(let i=1;i<e.length;i++)e[i]!==e[i-1]&&n++;t.modelSwitching.switchCount=n}};var Yu=S(require("fs"));var Bn=class{constructor(e){this.mistralVibe=e}mistralVibe;id="mistralvibe";displayName="Mistral Vibe";handles(e){return this.mistralVibe.isVibeSessionFile(e)}getBackingPath(e){return e}async stat(e){return Yu.promises.stat(e)}async getTokens(e){let t=await this.mistralVibe.getTokensFromSession(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return this.mistralVibe.countInteractions(e)}async getModelUsage(e){return this.mistralVibe.getModelUsage(e)}async getMeta(e){let t=await this.mistralVibe.getSessionMeta(e);return{title:t.title,firstInteraction:t.firstInteraction,lastInteraction:t.lastInteraction}}getEditorRoot(e){return this.mistralVibe.getSessionLogDir()}async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=await this.mistralVibe.discoverSessions();n.length>0&&(e(`\u{1F4C4} Found ${n.length} session file(s) in Mistral Vibe (~/.vibe/logs/session)`),s.push(...n))}catch(n){e(`Could not read Mistral Vibe session files: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.mistralVibe.getSessionLogDir(),source:"Mistral Vibe"}]}async buildTurns(e){let t=[],s=await this.mistralVibe.readSessionMessages(e),n=await this.mistralVibe.getSessionMeta(e),i=await this.mistralVibe.getTokensFromSession(e),r=n.model||"devstral",a=this.findUserMessageIndices(s);for(let c=0;c<a.length;c++){let d=a[c],p=c+1<a.length?a[c+1]:s.length;t.push(this.buildMistralTurn(s,d,p,n,r,c+1))}return{turns:t,actualTokens:i.tokens}}findUserMessageIndices(e){let t=[];for(let s=0;s<e.length;s++)e[s].role==="user"&&e[s].injected!==!0&&t.push(s);return t}buildMistralTurn(e,t,s,n,i,r){let a=e[t],c=typeof a.content=="string"?a.content:"",{assistantText:d,toolCalls:p}=this.collectMistralTurnContent(e,t,s);return{turnNumber:r,timestamp:n.firstInteraction,mode:"cli",userMessage:c,assistantResponse:d,model:i,toolCalls:p,contextReferences:G(),mcpTools:[],inputTokensEstimate:0,outputTokensEstimate:0,thinkingTokensEstimate:0}}collectMistralTurnContent(e,t,s){let n="",i=[];for(let r=t+1;r<s;r++){let a=e[r];if(a.role==="assistant")n+=this.processMistralAssistantMsg(a,i);else if(a.role==="tool"){let c=i[i.length-1];c&&(c.result=typeof a.content=="string"?a.content:void 0)}}return{assistantText:n,toolCalls:i}}processMistralAssistantMsg(e,t){let s="";typeof e.content=="string"&&(s=e.content);for(let n of Array.isArray(e.tool_calls)?e.tool_calls:[])t.push({toolName:n.function?.name||n.name||"unknown",arguments:n.function?.arguments?JSON.stringify(n.function.arguments):void 0});return s}async analyzeUsage(e,t){let s=H(),n=await this.mistralVibe.readSessionMessages(e),r=(await this.mistralVibe.getSessionMeta(e)).model||"devstral",a=[];for(let d of n)if(d.role==="user"&&d.injected!==!0)s.modeUsage.cli++;else if(d.role==="assistant"&&(a.push(r),Array.isArray(d.tool_calls)))for(let p of d.tool_calls){s.toolCalls.total++;let f=String(p.function?.name||p.name||"tool");s.toolCalls.byTool[f]=(s.toolCalls.byTool[f]||0)+1}let c=[...new Set(a)];return s.modelSwitching.uniqueModels=c,s.modelSwitching.modelCount=c.length,s.modelSwitching.totalRequests=a.length,s.modelSwitching.switchCount=0,Q(t.modelPricing,c,a,s),s}};var Xu=S(require("fs"));var zn=class{constructor(e){this.geminiCli=e}geminiCli;id="geminicli";displayName="Gemini CLI";handles(e){return this.geminiCli.isGeminiCliSessionFile(e)}getBackingPath(e){return e}async stat(e){return Xu.promises.stat(e)}async getTokens(e){let t=await this.geminiCli.getTokensFromGeminiCliSession(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return await this.geminiCli.countGeminiCliInteractions(e)}async getModelUsage(e){return await this.geminiCli.getGeminiCliModelUsage(e)}async getMeta(e){return await this.geminiCli.getGeminiCliSessionMeta(e)}getEditorRoot(e){return this.geminiCli.getGeminiDataDir()}async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=await this.geminiCli.getGeminiCliSessionFiles();n.length>0&&(e(`\u{1F4C4} Found ${n.length} session file(s) in Gemini CLI (~/.gemini/tmp/*/chats)`),s.push(...n))}catch(n){e(`Could not read Gemini CLI session files: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.geminiCli.getGeminiTmpDir(),source:"Gemini CLI (sessions)"},{path:this.geminiCli.getGeminiProjectsPath(),source:"Gemini CLI (projects.json)"},{path:this.geminiCli.getGeminiLogsPath(),source:"Gemini CLI (logs.json)"}]}async buildTurns(e){return await this.geminiCli.buildGeminiCliTurns(e)}async getDailyFractions(e){return await this.geminiCli.getGeminiCliDailyFractions(e)}async analyzeUsage(e,t){let s=H(),n=await this.geminiCli.readGeminiCliSession(e),i=[];s.modeUsage.cli+=n.userRecords.length;for(let r of n.assistantRecords)this.processGeminiAssistantRecord(r,s,i);return this.applyGeminiModelSwitchingStats(i,s),Q(t.modelPricing,s.modelSwitching.uniqueModels,i,s),s}processGeminiAssistantRecord(e,t,s){let n=Cn(e.model||"unknown");s.push(n);for(let i of Array.isArray(e.toolCalls)?e.toolCalls:[]){let r=this.resolveGeminiToolName(i);r&&(t.toolCalls.total++,t.toolCalls.byTool[r]=(t.toolCalls.byTool[r]||0)+1)}}resolveGeminiToolName(e){return typeof e?.name=="string"&&e.name.trim().length>0?e.name.trim():typeof e?.displayName=="string"&&e.displayName.trim().length>0?e.displayName.trim():""}applyGeminiModelSwitchingStats(e,t){let s=[...new Set(e)];t.modelSwitching.uniqueModels=s,t.modelSwitching.modelCount=s.length,t.modelSwitching.totalRequests=e.length;let n=0;for(let i=1;i<e.length;i++)e[i]!==e[i-1]&&n++;t.modelSwitching.switchCount=n}};var Zu=S(require("fs")),ba=S(require("inspector"));var $n=class{constructor(e,t=()=>0){this.antigravity=e;this.estimateTokens=t}antigravity;estimateTokens;id="antigravity";displayName="Antigravity";handles(e){return this.antigravity.isAntigravitySessionFile(e)}getBackingPath(e){return e}async stat(e){return Zu.promises.stat(e)}async getTokens(e){return{...await this.antigravity.estimateTokensFromAntigravitySession(e,this.estimateTokens),actualTokens:0}}async countInteractions(e){return this.antigravity.countAntigravityInteractions(e)}async getModelUsage(e){return{}}async getMeta(e){return this.antigravity.getAntigravitySessionMeta(e)}getEditorRoot(e){return this.antigravity.getAntigravityBrainDir()}async buildTurns(e){return this.antigravity.buildAntigravityTurns(e)}async discover(e){let t=this.getCandidatePaths(),s=[],n=this.antigravity.getAntigravityBrainDir();ba.url()&&e(`\u{1F50D} [Antigravity] Checking brain dir: ${n}`);try{let i=await this.antigravity.getAntigravitySessionFiles();ba.url()&&e(`\u{1F50D} [Antigravity] Found ${i.length} transcript(s)`),i.length>0&&(e(`\u{1F4C4} Found ${i.length} session file(s) in Antigravity (~/.gemini/antigravity/brain/*/)`),s.push(...i))}catch(i){e(`Could not read Antigravity session files: ${i}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.antigravity.getAntigravityBrainDir(),source:"Antigravity (brain/)"}]}async analyzeUsage(e,t){let s=H(),n=await this.antigravity.readAntigravitySession(e);s.modeUsage.cli+=n.userEntries.length;for(let i of n.modelEntries)if(Array.isArray(i.tool_calls))for(let r of i.tool_calls)r.name&&(s.toolCalls.total++,s.toolCalls.byTool[r.name]=(s.toolCalls.byTool[r.name]||0)+1);return s.modelSwitching.uniqueModels=[],s.modelSwitching.modelCount=0,s.modelSwitching.totalRequests=0,s.modelSwitching.switchCount=0,s}};var ed=S(require("fs"));var Hn=class{constructor(e){this.pi=e}pi;id="pi";displayName="Pi";handles(e){return this.pi.isPiSessionFile(e)}getBackingPath(e){return e}async stat(e){return ed.promises.stat(e)}async getTokens(e){let t=await this.pi.getTokens(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return this.pi.countInteractions(e)}async getModelUsage(e){return this.pi.getModelUsage(e)}async getMeta(e){return this.pi.getSessionMeta(e)}getEditorRoot(e){return this.pi.getConfigDir()}async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=await this.pi.discoverSessions();n.length>0&&(e(`\u{1F4C4} Found ${n.length} session file(s) in Pi (~/.pi/agent/sessions)`),s.push(...n))}catch(n){e(`Could not read Pi session files: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.pi.getConfigDir(),source:"Pi"}]}async buildTurns(e){let t=await this.pi.getMessages(e),{tokens:s}=await this.pi.getTokens(e),n=await this.pi.getModelUsage(e),i=t.filter(c=>c.message?.role==="user").length,{perTurnInput:r,perTurnOutput:a}=this.computePerTurnDefaults(n,i);return{turns:this.buildAllTurns(t,r,a),actualTokens:s}}computePerTurnDefaults(e,t){if(t===0)return{perTurnInput:0,perTurnOutput:0};let s=Object.values(e).reduce((i,r)=>i+r.inputTokens,0),n=Object.values(e).reduce((i,r)=>i+r.outputTokens,0);return{perTurnInput:Math.round(s/t),perTurnOutput:Math.round(n/t)}}buildAllTurns(e,t,s){let n=[],i=0;for(let r=0;r<e.length;r++){if(e[r].message?.role!=="user")continue;i++;let a=this.collectAssistantEvents(e,r);n.push(this.buildTurn(e[r],a,i,t,s))}return n}collectAssistantEvents(e,t){let s=[];for(let n=t+1;n<e.length&&e[n].message?.role!=="user";n++)e[n].message?.role==="assistant"&&s.push(e[n]);return s}buildTurn(e,t,s,n,i){let r=this.extractUserText(e.message?.content),{assistantText:a,toolCalls:c,model:d}=this.processAssistantEvents(t),p=t.reduce((h,_)=>h+(_.message?.usage?.input??0),0),f=t.reduce((h,_)=>h+(_.message?.usage?.output??0),0);return{turnNumber:s,timestamp:e.timestamp??null,mode:"cli",userMessage:r,assistantResponse:a,model:d,toolCalls:c,contextReferences:G(),mcpTools:[],inputTokensEstimate:p>0?p:n,outputTokensEstimate:f>0?f:i,thinkingTokensEstimate:0}}extractUserText(e){return Array.isArray(e)?e.filter(t=>t.type==="text").map(t=>t.text||"").join(`
|
|
154
|
+
`):typeof e=="string"?e:""}processAssistantEvents(e){let t="",s=[],n=null;for(let i of e){let r=i.message;n||(n=r?.model??null),Array.isArray(r?.content)&&(t+=this.processContentParts(r.content,s))}return{assistantText:t,toolCalls:s,model:n}}processContentParts(e,t){let s="";for(let n of e)n.type==="text"&&n.text?s+=n.text:n.type==="toolCall"&&n.name&&t.push({toolName:n.name,arguments:n.arguments?JSON.stringify(n.arguments):void 0});return s}async getSyncData(e){return this.pi.getSessionData(e)}async analyzeUsage(e,t){let s=H(),n=await this.pi.getMessages(e),i=this.collectModelsAndCounts(n,s);return this.applyModelSwitchingStats(i,t,s),s}collectModelsAndCounts(e,t){let s=[];for(let n of e){let i=n.message;i&&(i.role==="user"?t.modeUsage.cli++:i.role==="assistant"&&this.processAssistantForAnalysis(i,s,t))}return s}processAssistantForAnalysis(e,t,s){if(t.push(e.model||"unknown"),!!Array.isArray(e.content)){for(let n of e.content)if(n.type==="toolCall"&&n.name){s.toolCalls.total++;let i=n.name;s.toolCalls.byTool[i]=(s.toolCalls.byTool[i]||0)+1}}}applyModelSwitchingStats(e,t,s){let n=[...new Set(e)];s.modelSwitching.uniqueModels=n,s.modelSwitching.modelCount=n.length,s.modelSwitching.totalRequests=e.length;let i=0;for(let r=1;r<e.length;r++)e[r]!==e[r-1]&&i++;s.modelSwitching.switchCount=i,Q(t.modelPricing,n,e,s)}};var td=S(require("fs")),sd=S(require("path"));var Oi=class{constructor(e){this.cursor=e}cursor;id="cursor";displayName="Cursor";handles(e){return this.cursor.isCursorSessionFile(e)}getBackingPath(e){return this.cursor.getDbPathFromVirtual(e)}async stat(e){return this.cursor.statSessionFile(e)}async getTokens(e){let t=await this.cursor.getTokens(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return this.cursor.countInteractions(e)}async getModelUsage(e){return this.cursor.getModelUsage(e)}async getMeta(e){return this.cursor.getSessionMeta(e)}getEditorRoot(e){return sd.dirname(this.cursor.getDbPathFromVirtual(e))}async discover(e){let t=this.getCandidatePaths(),s=this.cursor.getCursorDbPath();e(`\u{1F4C1} Checking Cursor DB path: ${s}`);let n=[];try{await td.promises.access(s),n=await this.cursor.discoverSessions(),n.length>0&&e(`\u{1F4C4} Found ${n.length} Cursor session(s)`)}catch{e(`\u{1F4C1} Cursor DB not found: ${s}`)}return{sessionFiles:n,candidatePaths:t}}getCandidatePaths(){return[{path:this.cursor.getCursorDbPath(),source:"Cursor (state.vscdb)"}]}collectAssistantText(e,t,s){let n=[],i=t;for(;i<e.length&&e[i].type!==1;){let r=e[i].bubbleId,a=r?s.get(r):void 0;a?.text&&n.push(a.text),i++}return n.join(`
|
|
140
155
|
|
|
141
|
-
`)}async buildTurns(e){let t=await this.cursor.readComposerData(e);if(!t?.fullConversationHeadersOnly)return{turns:[]};let s=t.fullConversationHeadersOnly,n=typeof t.contextTokensUsed=="number"?t.contextTokensUsed:0,i=t.modelConfig?.modelName||null,r=s.map(p=>p.bubbleId).filter(p=>!!p),a=await this.cursor.readBubbles(e,r),c=[],m=0;for(let p=0;p<s.length;p++){let f=s[p];if(f.type!==1)continue;m++;let h=f.bubbleId?a.get(f.bubbleId):void 0;c.push({turnNumber:m,timestamp:h?.createdAt??null,mode:"agent",userMessage:h?.text??"",assistantResponse:this.collectAssistantText(s,p+1,a),model:i,toolCalls:[],contextReferences:B(),mcpTools:[],inputTokensEstimate:0,outputTokensEstimate:0,thinkingTokensEstimate:0})}return{turns:c,actualTokens:n}}async getSyncData(e){return this.cursor.getSessionData(e)}async analyzeUsage(e,t){let s=J(),n=await this.cursor.readComposerData(e);if(!n?.fullConversationHeadersOnly)return s;let i=n.modelConfig?.modelName||"unknown",r=n.fullConversationHeadersOnly,a=r.filter(p=>p.type===1).length,c=r.filter(p=>p.type===2).length;s.modeUsage.agent+=a,c>0&&(s.modelSwitching.uniqueModels=[i],s.modelSwitching.modelCount=1,s.modelSwitching.totalRequests=c,s.modelSwitching.switchCount=0);let m=Array(c).fill(i);return ee(t.modelPricing,[i],m,s),s}};var Gs=w(require("fs")),Ae=w(require("path")),fa=w(require("os"));function ga(){return Ae.join(fa.homedir(),".copilot","session-state")}var zn=class{id="copilotcli";displayName="Copilot CLI";store=new Ns;_scoutSessionIds=new Set;_appSessionIds=new Set;getDisplayName(e){let t=this.store.getSessionId(e),s=Ae.basename(Ae.dirname(e));return t&&this._scoutSessionIds.has(t)||s&&this._scoutSessionIds.has(s)?"MS Scout (Copilot CLI)":t&&this._appSessionIds.has(t)||s&&this._appSessionIds.has(s)?"Copilot CLI (App)":"Copilot CLI"}getDisplayNameForDiscoveredPath(e){let t=Ae.basename(Ae.dirname(e));if(t&&this._scoutSessionIds.has(t))return"MS Scout (Copilot CLI)";if(t&&this._appSessionIds.has(t))return"Copilot CLI (App)"}async getWorkspacePathForDiscoveredPath(e){let t=Ae.join(Ae.dirname(e),"workspace.yaml");try{return(await Gs.promises.readFile(t,"utf8")).match(/^cwd:\s*(.+)$/m)?.[1]?.trim()||void 0}catch{return}}handles(e){return this.store.isCliStoreSession(e)}getBackingPath(e){return this.store.isCliStoreSession(e)?this.store.getDbPathFromVirtual(e):e}async stat(e){return this.store.isCliStoreSession(e)?this.store.stat(e):Gs.promises.stat(e)}async getTokens(e){let t=await ms(e);return t?{tokens:t.actualTokens,thinkingTokens:0,actualTokens:t.actualTokens,cacheReadTokens:t.cacheReadTokens}:{tokens:0,thinkingTokens:0,actualTokens:0}}async countInteractions(e){return this.store.isCliStoreSession(e)?this.store.countTurns(e):0}async getModelUsage(e){return(await ms(e))?.modelUsage??{}}async getMeta(e){if(this.store.isCliStoreSession(e)){let t=await this.store.readSession(e);return t?{title:t.summary??void 0,firstInteraction:t.created_at,lastInteraction:t.updated_at,workspacePath:t.cwd??void 0}:{title:void 0,firstInteraction:null,lastInteraction:null}}return{title:void 0,firstInteraction:null,lastInteraction:null}}getEditorRoot(e){return this.store.isCliStoreSession(e)?Ae.join(fa.homedir(),".copilot"):ga()}async buildTurns(e){return this.store.isCliStoreSession(e)?{turns:(await this.store.getTurns(e)).map(n=>({turnNumber:n.turn_index+1,timestamp:n.timestamp,mode:"cli",userMessage:n.user_message??"",assistantResponse:n.assistant_response??"",model:null,toolCalls:[],contextReferences:B(),mcpTools:[],inputTokensEstimate:0,outputTokensEstimate:0,thinkingTokensEstimate:0}))}:{turns:[]}}async analyzeUsage(e,t){let s=J();if(!this.store.isCliStoreSession(e))return s;let n=await this.store.getTurns(e);return s.modeUsage.cli=n.filter(i=>i.user_message!==null).length,s}async getDailyFractions(e){return this.store.isCliStoreSession(e)?this.store.getDailyFractions(e):{}}async _tryMarkScoutFromWorkspaceYaml(e,t){let s=Ae.join(e,"workspace.yaml");try{let n=await Gs.promises.readFile(s,"utf8"),i=n.match(/^cwd:\s*(.+)$/m);i&&ea(i[1].trim())&&this._scoutSessionIds.add(t);let r=n.match(/^client_name:\s*(.+)$/m);r&&Jc(r[1].trim())&&this._appSessionIds.add(t)}catch{}}getCandidatePaths(){let e=[{path:ga(),source:"Copilot CLI"}],t=this.store.getDbPath();return e.push({path:t,source:"Copilot CLI (session-store.db)"}),e}async discover(e){let t=this.getCandidatePaths(),s=[],n=ga(),i=new Set;try{if(await Mt(n)){let r;try{r=await Gs.promises.readdir(n,{withFileTypes:!0})}catch(p){e(`Could not read Copilot CLI session path in ${n}: ${p}`),r=[]}let a=r.filter(p=>!p.isDirectory()&&(p.name.endsWith(".json")||p.name.endsWith(".jsonl"))).map(p=>Ae.join(n,p.name));a.length>0&&(e(`\u{1F4C4} Found ${a.length} session files in Copilot CLI directory`),s.push(...a));let c=r.filter(p=>p.isDirectory()),m=(await Promise.all(c.map(async p=>{let f=Ae.join(n,p.name),h=Ae.join(f,"events.jsonl");try{if((await Gs.promises.stat(h)).size>0)return i.add(p.name),await this._tryMarkScoutFromWorkspaceYaml(f,p.name),h}catch{}return null}))).filter(p=>p!==null);m.length>0&&(e(`\u{1F4C4} Found ${m.length} session files in Copilot CLI subdirectories`),s.push(...m))}}catch(r){e(`Could not check Copilot CLI session path ${n}: ${r}`)}try{let r=await this.store.discoverNewSessionsWithCwd(i);if(r.length>0){e(`\u{1F4C4} Found ${r.length} chat-only session(s) in Copilot CLI session-store.db`),await Promise.all(r.map(async({id:a,cwd:c})=>{ea(c)&&this._scoutSessionIds.add(a),await this._tryMarkScoutFromWorkspaceYaml(Ae.join(n,a),a)}));for(let{id:a}of r)s.push(this.store.virtualPath(a))}}catch(r){e(`Could not read Copilot CLI session-store.db: ${r}`)}return{sessionFiles:s,candidatePaths:t}}};var qs=w(require("fs")),Di=w(require("path")),Wu=w(require("os"));function ha(){return Di.join(Wu.homedir(),".copilot","jb")}var $n=class{id="jetbrains";displayName="JetBrains IDE";handles(e){return!1}getBackingPath(e){return e}async stat(e){return qs.promises.stat(e)}async parsePartition(e){try{let t=await qs.promises.readFile(e,"utf8");return wi(t)}catch{return null}}async getTokens(e){let t=await this.parsePartition(e);return t?{tokens:t.tokens,thinkingTokens:t.thinkingTokens,actualTokens:t.actualTokens}:{tokens:0,thinkingTokens:0,actualTokens:0}}async countInteractions(e){return(await this.parsePartition(e))?.interactions??0}async getModelUsage(e){return(await this.parsePartition(e))?.modelUsage??{}}async getMeta(e){let t=await this.parsePartition(e);return{title:void 0,firstInteraction:t?.firstInteraction??null,lastInteraction:t?.lastInteraction??null}}async getToolCounts(e){return(await this.parsePartition(e))?.toolCounts??{}}async getToolCalls(e){return(await this.parsePartition(e))?.toolCalls??[]}async getTurns(e){return(await this.parsePartition(e))?.turns??[]}async getMessageIds(e){return(await this.parsePartition(e))?.messageIds??[]}async getTurnStatusCounts(e){return(await this.parsePartition(e))?.turnStatusCounts??{success:0,cancelled:0,failed:0,unknown:0}}async hasThinking(e){return(await this.parsePartition(e))?.hasThinking??!1}getEditorRoot(e){return ha()}getCandidatePaths(){return[{path:ha(),source:"JetBrains IDE"}]}async discover(e){let t=this.getCandidatePaths(),s=[],n=ha();try{if(!await Mt(n))return{sessionFiles:s,candidatePaths:t};let i;try{i=await qs.promises.readdir(n,{withFileTypes:!0})}catch(c){return e(`Could not read JetBrains session path in ${n}: ${c}`),{sessionFiles:s,candidatePaths:t}}let r=i.filter(c=>c.isDirectory()),a=(await Promise.all(r.map(async c=>{let m=Di.join(n,c.name),p;try{p=await qs.promises.readdir(m,{withFileTypes:!0})}catch{return[]}let f=[];for(let h of p){if(!h.isFile()||!/^partition-\d+\.jsonl$/.test(h.name))continue;let _=Di.join(m,h.name);try{(await qs.promises.stat(_)).size>0&&f.push(_)}catch{}}return f}))).flat();a.length>0&&(e(`\u{1F4C4} Found ${a.length} session file(s) in JetBrains IDE Copilot`),s.push(...a))}catch(i){e(`Could not check JetBrains session path ${n}: ${i}`)}return{sessionFiles:s,candidatePaths:t}}};var Hu=w(require("fs"));var Wn=class{constructor(e){this.kiro=e}kiro;id="kiro";displayName="Kiro";handles(e){return this.kiro.isKiroSessionFile(e)}getBackingPath(e){return e}async stat(e){return Hu.promises.stat(e)}async getTokens(e){let t=await this.kiro.getTokensFromKiroSession(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return await this.kiro.countKiroInteractions(e)}async getModelUsage(e){return await this.kiro.getKiroModelUsage(e)}async getMeta(e){return await this.kiro.getKiroSessionMeta(e)}getEditorRoot(e){return this.kiro.getKiroAppDataDir()}async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=await this.kiro.getKiroSessionFiles();n.length>0&&(e(`\u{1F4C4} Found ${n.length} session file(s) in Kiro (kiro.kiroagent/workspace-sessions)`),s.push(...n))}catch(n){e(`Could not read Kiro session files: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.kiro.getKiroWorkspaceSessionsDir(),source:"Kiro"}]}async buildTurns(e){let t=await this.kiro.buildKiroTurns(e),s=B();return{turns:t.map((i,r)=>({turnNumber:r+1,timestamp:i.timestampMs!==null?new Date(i.timestampMs).toISOString():null,mode:"agent",userMessage:i.userText,assistantResponse:i.assistantText,model:i.model,toolCalls:i.toolCalls,contextReferences:s,mcpTools:[],inputTokensEstimate:i.inputTokens,outputTokensEstimate:i.outputTokens,thinkingTokensEstimate:0}))}}async getDailyFractions(e){return await this.kiro.getKiroDailyFractions(e)}async analyzeUsage(e,t){let s=J(),n=await this.kiro.buildKiroTurns(e),i=[];for(let c of n){s.modeUsage.agent++,c.model&&i.push(c.model);for(let m of c.toolCalls)s.toolCalls.total++,s.toolCalls.byTool[m.toolName]=(s.toolCalls.byTool[m.toolName]||0)+1}let r=[...new Set(i)];s.modelSwitching.uniqueModels=r,s.modelSwitching.modelCount=r.length,s.modelSwitching.totalRequests=i.length;let a=0;for(let c=1;c<i.length;c++)i[c]!==i[c-1]&&a++;return s.modelSwitching.switchCount=a,ee(t.modelPricing,r,i,s),s}};var Ju=w(require("fs"));var Hn=class{constructor(e){this.kiroCli=e}kiroCli;id="kirocli";displayName="Kiro CLI";handles(e){return this.kiroCli.isKiroCliSessionFile(e)}getBackingPath(e){return e}async stat(e){return Ju.promises.stat(e)}async getTokens(e){let t=await this.kiroCli.getTokensFromKiroCliSession(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return await this.kiroCli.countKiroCliInteractions(e)}async getModelUsage(e){return await this.kiroCli.getKiroCliModelUsage(e)}async getMeta(e){return await this.kiroCli.getKiroCliSessionMeta(e)}getEditorRoot(e){return this.kiroCli.getKiroCliDataDir()}async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=await this.kiroCli.getKiroCliSessionFiles();n.length>0&&(e(`\u{1F4C4} Found ${n.length} session file(s) in Kiro CLI (~/.kiro/sessions/cli)`),s.push(...n))}catch(n){e(`Could not read Kiro CLI session files: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.kiroCli.getKiroCliSessionsDir(),source:"Kiro CLI"}]}async buildTurns(e){let t=await this.kiroCli.buildKiroCliTurns(e),s=B(),i=(await this.kiroCli.readSessionMetadata(e))?.modelId||null;return{turns:t.map((a,c)=>({turnNumber:c+1,timestamp:a.timestampMs!==null?new Date(a.timestampMs).toISOString():null,mode:"cli",userMessage:a.userText,assistantResponse:a.assistantText,model:i,toolCalls:a.toolCalls,contextReferences:s,mcpTools:[],inputTokensEstimate:a.inputTokens,outputTokensEstimate:a.outputTokens,thinkingTokensEstimate:0}))}}async getDailyFractions(e){return await this.kiroCli.getKiroCliDailyFractions(e)}async analyzeUsage(e,t){let s=J(),n=await this.kiroCli.buildKiroCliTurns(e),r=(await this.kiroCli.readSessionMetadata(e))?.modelId||"unknown",a=[];for(let m of n){s.modeUsage.cli++,a.push(r);for(let p of m.toolCalls)s.toolCalls.total++,s.toolCalls.byTool[p.toolName]=(s.toolCalls.byTool[p.toolName]||0)+1}let c=[...new Set(a)];return s.modelSwitching.uniqueModels=c,s.modelSwitching.modelCount=c.length,s.modelSwitching.totalRequests=a.length,s.modelSwitching.switchCount=0,ee(t.modelPricing,c,a,s),s}};var Vu=w(require("fs")),Ku=w(require("path"));var Ei=class{constructor(e){this.devinCli=e}devinCli;id="devincli";displayName="Devin CLI";handles(e){return this.devinCli.isDevinCliSessionFile(e)}getBackingPath(e){return this.devinCli.getDbPathFromVirtual(e)}async stat(e){return this.devinCli.statSessionFile(e)}async getTokens(e){let t=await this.devinCli.getTokens(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return this.devinCli.countInteractions(e)}async getModelUsage(e){return this.devinCli.getModelUsage(e)}async getMeta(e){let t=await this.devinCli.readSession(e),s=await this.devinCli.getMessageNodes(e),n=[];t?.created_at&&n.push(t.created_at*1e3),t?.last_activity_at&&n.push(t.last_activity_at*1e3);for(let i of s)i.created_at&&n.push(i.created_at*1e3);return n.sort((i,r)=>i-r),{title:t?.title||void 0,firstInteraction:n.length>0?new Date(n[0]).toISOString():null,lastInteraction:n.length>0?new Date(n[n.length-1]).toISOString():null,workspacePath:t?.working_directory||void 0}}getEditorRoot(e){return Ku.dirname(this.devinCli.getDbPathFromVirtual(e))}async discover(e){let t=this.getCandidatePaths(),s=[],n=this.devinCli.getDbPath();e(`\u{1F4C1} Checking Devin CLI DB path: ${n}`);try{await Vu.promises.access(n);let i=await this.devinCli.discoverSessionIds();i.length>0&&e(`\u{1F4C4} Found ${i.length} session(s) in Devin CLI database`),s.push(...i.map(r=>this.devinCli.virtualPath(r)))}catch(i){e(`Could not read Devin CLI database: ${i}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.devinCli.getDbPath(),source:"Devin CLI (sessions.db)"}]}async buildTurns(e){let t=[],s=await this.devinCli.readSession(e),n=await this.devinCli.getMessageNodes(e),i=this.devinCli.buildMainChain(n,s?.main_chain_id??null),r=0;for(let a=0;a<i.length;a++){let c=this.devinCli.parseChatMessage(i[a].chat_message);c.role==="user"&&(r++,t.push(this.buildDevinCliTurn(i,a,c.text,s,r)))}return{turns:t}}buildDevinCliTurn(e,t,s,n,i){let r="";for(let c=t+1;c<e.length;c++){let m=this.devinCli.parseChatMessage(e[c].chat_message);if(m.role==="user")break;m.role==="assistant"&&(r+=(r?`
|
|
142
|
-
`:"")+
|
|
143
|
-
`),c=r.length>0?r[r.length-1].model:e.models[e.models.length-1]??null;return{turnNumber:t+1,timestamp:s.timestamp,mode:"cli",userMessage:s.text,assistantResponse:a,model:c==="unknown"?null:c,toolCalls:e.toolCalls.filter(
|
|
144
|
-
`);for(let i of n)if(i.trim())try{let r=JSON.parse(i);if(r.type==="user.message"){zs(r.timestamp??r.ts??r.data?.timestamp,t);continue}this.processVsCodeDeltaEvent(r,s,t)}catch{}return t}processVsCodeDeltaEvent(e,t,s){let n=e.kind,i=e.k,r=e.v;n===0&&r?.requests&&Array.isArray(r.requests)?this.processKind0Event(r,s):n===2&&Array.isArray(i)&&i[0]==="requests"?this.processKind2Event(i,r,t,s):this.isKind1TimestampUpdate(n,i)&&this.processKind1Event(i,r,t,s)}isKind1TimestampUpdate(e,t){return e===1&&Array.isArray(t)&&t.length===3&&t[0]==="requests"&&(t[2]==="timestamp"||t[2]==="ts")&&typeof t[1]=="number"}processKind0Event(e,t){for(let s of e.requests)zs(s.timestamp??s.ts,t)}processKind2Event(e,t,s,n){if(Array.isArray(t))for(let i of t)zs(i.timestamp??i.ts,n);else if(t&&typeof t=="object"){let i=t.timestamp??t.ts;i!==void 0&&zs(i,n),typeof e[1]=="number"&&(s[e[1]]=i)}}processKind1Event(e,t,s,n){let i=e[1];s[i]===void 0&&zs(t,n),s[i]=t}},Sa=class{extractCounts(e){let t={};try{let s=JSON.parse(e);if(s.requests&&Array.isArray(s.requests))for(let n of s.requests){let i=n.timestamp??n.ts??n.result?.timestamp;zs(i,t)}}catch{}return t}};function i_(o){if(o==null)return null;let e=new Date(o);return isNaN(e.getTime())?null:e}function zs(o,e){let t=i_(o);if(t!==null){let s=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0"),r=`${s}-${n}-${i}`;e[r]=(e[r]||0)+1}}function ed(o,e,t){let s=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0"),r=`${s}-${n}-${i}`,c=(e?new ka:new Sa).extractCounts(o),m=Object.values(c).reduce((f,h)=>f+h,0);if(m===0)return{[r]:1};let p={};for(let[f,h]of Object.entries(c))p[f]=h/m;return p}var zt=w(require("fs")),Ta=w(require("path")),td=w(require("os"));var Ii=class{maxEntries;constructor(e=2e3){this.maxEntries=e}isValid(e,t,s){return e.mtime===t&&e.size===s}evict(e){if(e.size<=this.maxEntries)return;let t=[...e.entries()].sort((s,n)=>n[1].mtime-s[1].mtime);e.clear();for(let[s,n]of t.slice(0,this.maxEntries))e.set(s,n)}};var sd=5,r_=2e3,nd=Ta.join(td.homedir(),".copilot-token-tracker"),wa=Ta.join(nd,"cli-cache.json"),xt=new Map,$s=!0,od=!1,id=new Ii(r_);function Ma(){$s=!1,xt.clear()}function Pa(){if($s)try{if(!zt.existsSync(wa))return;let o=zt.readFileSync(wa,"utf-8"),e=JSON.parse(o);if(e.version!==sd){xt.clear();return}xt=new Map(Object.entries(e.entries))}catch{xt.clear()}}function va(){if(!(!$s||!od))try{id.evict(xt),zt.mkdirSync(nd,{recursive:!0});let o={version:sd,entries:Object.fromEntries(xt)};zt.writeFileSync(wa,JSON.stringify(o),"utf-8")}catch{}}function rd(o,e,t){if(!$s)return null;let s=xt.get(o);return!s||!id.isValid(s,e,t)?null:{...s.data,lastModified:new Date(s.data.lastModified)}}function Aa(o,e,t,s){$s&&(od=!0,xt.set(o,{mtime:e,size:t,data:{...s,lastModified:s.lastModified.toISOString()}}))}function xa(){return{entries:xt.size,enabled:$s}}var Ge={CO2_PER_1K_TOKENS:.2,CO2_ABSORPTION_PER_TREE_PER_YEAR:21e3,WATER_USAGE_PER_1K_TOKENS:.3,CO2_PER_KM_DRIVING:120,CO2_PER_PHONE_CHARGE:8.22,WATER_PER_COFFEE_CUP:140,CO2_PER_LED_HOUR:20};var ad={$schema:"http://json-schema.org/draft-07/schema#",description:"Character-to-token ratio estimators for different AI models. Used to estimate token counts from text length.",estimators:{"gpt-4":.25,"gpt-4.1":.25,"gpt-4.1-mini":.25,"gpt-4o":.25,"gpt-4o-mini":.25,"gpt-4-turbo":.25,"gpt-3.5-turbo":.25,"gpt-5":.25,"gpt-5-codex":.25,"gpt-5-mini":.25,"gpt-5.1":.25,"gpt-5.1-codex":.25,"gpt-5.1-codex-max":.25,"gpt-5.1-codex-mini":.25,"gpt-5.2":.25,"gpt-5.2-codex":.25,"gpt-5.2-pro":.25,"gpt-5.3-codex":.25,"gpt-5.4":.25,"gpt-5.4-mini":.25,"gpt-5.4-nano":.25,"gpt-4.1-nano":.25,"gemini-2.0-flash":.25,"gemini-2.0-flash-lite":.25,"gemini-2.5-flash":.25,"gemini-2.5-flash-lite":.25,"claude-sonnet-3.5":.24,"claude-sonnet-3.7":.24,"claude-sonnet-4":.24,"claude-sonnet-4.5":.24,"claude-sonnet-4.6":.24,"claude-haiku":.24,"claude-haiku-4.5":.24,"claude-opus-4.1":.24,"claude-opus-4.5":.24,"claude-opus-4.6":.24,"claude-opus-4.6-(fast-mode)-(preview)":.24,"claude-opus-4.6-fast":.24,"claude-opus-4.7":.24,"gemini-2.5-pro":.25,"gemini-3-flash":.25,"gemini-3-pro":.25,"gemini-3-pro-preview":.25,"gemini-3.1-pro":.25,"gemini-3.1-flash-lite":.25,"grok-code-fast-1":.25,"raptor-mini":.25,goldeneye:.25,"o1-preview":.25,"o1-mini":.25,"o3-mini":.25,"o4-mini":.25,"gpt-5.5":.25,"mistral-large-latest":.25,"mistral-large-2512":.25,"mistral-large-2411":.25,"magistral-medium-latest":.25,"mistral-medium-latest":.25,"mistral-medium-3-5":.25,"mistral-medium-2505":.25,"mistral-small-latest":.25,"mistral-small-2503":.25,"mistral-small-2603":.25,"codestral-latest":.25,"codestral-2501":.25,"open-mistral-nemo":.25,"ministral-3b-2410":.25,"ministral-8b-2410":.25,"magistral-small-latest":.25,"devstral-medium-2507":.25,"pixtral-large-2411":.25,"gemini-3.5-flash":.25,"claude-opus-4.8":.24,"qwen2.5":.25,"mai-code-1-flash[^mai-code-1-flash]":.25,"mai-code-1-flash":.25,"claude-fable-5":.24,"claude-sonnet-5":.24,"claude-opus-4.8-(fast-mode)-(preview)":.24,"kimi-k2.7-code":.25,"gpt-5.6-luna":.25,"gpt-5.6-sol":.25,"gpt-5.6-terra":.25}};var Ui={$schema:"http://json-schema.org/draft-07/schema#",description:"Model pricing data - costs per million tokens. Each model has direct provider/API pricing at the top level (used as a reference); models billed through GitHub Copilot AI Credits also include a `copilotPricing` block reflecting GitHub's published per-token rates (1 AI credit = $0.01).",metadata:{lastUpdated:"2026-07-11",sources:[{name:"OpenAI API Pricing",url:"https://developers.openai.com/api/docs/pricing",retrievedDate:"2026-04-24"},{name:"Mistral AI API Pricing",url:"https://pricepertoken.com/pricing-page/provider/mistral-ai",retrievedDate:"2026-05-06",note:"Cross-referenced with https://openrouter.ai/mistralai and https://ai-pricing.info/mistral"},{name:"Anthropic Claude Pricing",url:"https://www.anthropic.com/pricing",note:"Standard rates; also see https://platform.claude.com/docs/en/about-claude/pricing",retrievedDate:"2026-03-30"},{name:"Google AI Gemini API Pricing",url:"https://ai.google.dev/gemini-api/docs/pricing",retrievedDate:"2026-03-30"},{name:"xAI Grok API Pricing",url:"https://x.ai/api",retrievedDate:"2026-03-30"},{name:"GitHub Copilot Supported Models",url:"https://docs.github.com/en/copilot/reference/ai-models/supported-models",retrievedDate:"2026-03-30",note:"Source for tier/multiplier data"},{name:"GitHub Copilot Premium Requests",url:"https://docs.github.com/en/copilot/managing-copilot/monitoring-usage-and-entitlements/about-premium-requests",retrievedDate:"2026-03-30",note:"Source for premium request multiplier values"},{name:"OpenRouter Model Pricing",url:"https://openrouter.ai",retrievedDate:"2026-03-30",note:"Cross-provider pricing aggregator used for verification"},{name:"DeepSeek API Pricing",url:"https://platform.deepseek.com/api-docs/pricing",retrievedDate:"2026-06-21",note:"deepseek-v4-flash: $0.14/M input (miss), $0.0028/M input (cache hit), $0.28/M output; free tier (deepseek-v4-flash-free via OpenRouter) is $0"},{name:"GitHub Copilot Models and Pricing",url:"https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",retrievedDate:"2026-04-27",note:"Source for the `copilotPricing` per-model block (GitHub AI Credit per-token rates)"}],disclaimer:"GitHub Copilot uses these models but pricing may differ from direct API usage. These are reference prices for cost estimation purposes only."},pricing:{"gpt-5":{inputCostPerMillion:1.25,outputCostPerMillion:10,category:"GPT-5 models",tier:"premium",multiplier:1,displayNames:["GPT-5"]},"gpt-5-codex":{inputCostPerMillion:1.25,outputCostPerMillion:10,category:"GPT-5 models",tier:"premium",multiplier:1,displayNames:["GPT-5 Codex (Preview)"]},"gpt-5-mini":{inputCostPerMillion:.25,outputCostPerMillion:2,category:"GPT-5 models",tier:"standard",multiplier:0,displayNames:["GPT-5 Mini"],copilotPricing:{inputCostPerMillion:.25,cachedInputCostPerMillion:.025,outputCostPerMillion:2,releaseStatus:"GA",category:"Lightweight"},cachedInputCostPerMillion:.025},"gpt-5.1":{inputCostPerMillion:1.25,outputCostPerMillion:10,category:"GPT-5 models",tier:"premium",multiplier:1,displayNames:["GPT-5.1"]},"gpt-5.1-codex":{inputCostPerMillion:1.25,outputCostPerMillion:10,category:"GPT-5 models",tier:"premium",multiplier:1,displayNames:["GPT-5.1 Codex"]},"gpt-5.1-codex-max":{inputCostPerMillion:1.75,outputCostPerMillion:14,category:"GPT-5 models",tier:"premium",multiplier:1,displayNames:["GPT-5.1 Codex Max"]},"gpt-5.1-codex-mini":{inputCostPerMillion:.25,outputCostPerMillion:2,category:"GPT-5 models",tier:"premium",multiplier:.33,displayNames:["GPT-5.1 Codex Mini (Preview)"]},"gpt-5.2":{inputCostPerMillion:1.75,outputCostPerMillion:14,category:"GPT-5 models",tier:"standard",multiplier:1,displayNames:["GPT-5.2"],copilotPricing:{inputCostPerMillion:1.75,cachedInputCostPerMillion:.175,outputCostPerMillion:14,releaseStatus:"Closing down 2026-06-01",category:"Versatile"}},"gpt-5.2-codex":{inputCostPerMillion:1.75,outputCostPerMillion:14,category:"GPT-5 models",tier:"standard",multiplier:1,displayNames:["GPT-5.2 Codex"],copilotPricing:{inputCostPerMillion:1.75,cachedInputCostPerMillion:.175,outputCostPerMillion:14,releaseStatus:"Closing down 2026-06-01",category:"Powerful"}},"gpt-5.2-pro":{inputCostPerMillion:21,outputCostPerMillion:168,category:"GPT-5 models",tier:"premium",multiplier:1,displayNames:["GPT-5.2 Pro"]},"gpt-5.3-codex":{inputCostPerMillion:1.75,outputCostPerMillion:14,category:"GPT-5 models",tier:"standard",multiplier:1,displayNames:["GPT-5.3 Codex"],copilotPricing:{inputCostPerMillion:1.75,cachedInputCostPerMillion:.175,outputCostPerMillion:14,releaseStatus:"GA",category:"Powerful"},cachedInputCostPerMillion:.175},"gpt-5.4":{inputCostPerMillion:2.5,cachedInputCostPerMillion:.25,outputCostPerMillion:15,category:"GPT-5 models",tier:"standard",multiplier:1,displayNames:["GPT-5.4"],copilotPricing:{inputCostPerMillion:2.5,cachedInputCostPerMillion:.25,outputCostPerMillion:15,releaseStatus:"GA",category:"Versatile"}},"gpt-5.4-mini":{inputCostPerMillion:.75,cachedInputCostPerMillion:.075,outputCostPerMillion:4.5,category:"GPT-5 models",tier:"standard",multiplier:.33,displayNames:["GPT-5.4 mini"],copilotPricing:{inputCostPerMillion:.75,cachedInputCostPerMillion:.075,outputCostPerMillion:4.5,releaseStatus:"GA",category:"Lightweight"}},"gpt-5.4-nano":{inputCostPerMillion:.2,cachedInputCostPerMillion:.02,outputCostPerMillion:1.25,category:"GPT-5 models",tier:"standard",multiplier:.25,displayNames:["GPT-5.4 nano"],copilotPricing:{inputCostPerMillion:.2,cachedInputCostPerMillion:.02,outputCostPerMillion:1.25,releaseStatus:"GA",category:"Lightweight"}},"gpt-4":{inputCostPerMillion:3,outputCostPerMillion:12,category:"GPT-4 models",tier:"unknown",multiplier:1,displayNames:["GPT-4"]},"gpt-4.1":{inputCostPerMillion:2,cachedInputCostPerMillion:.5,outputCostPerMillion:8,category:"GPT-4 models",tier:"standard",multiplier:0,displayNames:["GPT-4.1"],copilotPricing:{inputCostPerMillion:2,cachedInputCostPerMillion:.5,outputCostPerMillion:8,releaseStatus:"Closing down 2026-06-01",category:"Versatile"}},"gpt-4.1-mini":{inputCostPerMillion:.4,cachedInputCostPerMillion:.1,outputCostPerMillion:1.6,category:"GPT-4 models",tier:"standard",multiplier:0,displayNames:["GPT-4.1 Mini"]},"gpt-4.1-nano":{inputCostPerMillion:.1,cachedInputCostPerMillion:.025,outputCostPerMillion:.4,category:"GPT-4 models",tier:"standard",multiplier:0,displayNames:["GPT-4.1 Nano"]},"gpt-4o":{inputCostPerMillion:2.5,outputCostPerMillion:10,cachedInputCostPerMillion:1.25,category:"GPT-4 models",tier:"standard",multiplier:0,displayNames:["GPT-4o"]},"gpt-4o-mini":{inputCostPerMillion:.15,outputCostPerMillion:.6,cachedInputCostPerMillion:.075,category:"GPT-4 models",tier:"standard",multiplier:0,displayNames:["GPT-4o-mini","GPT-4o Mini"]},"gpt-4o-mini-2024-07-18":{inputCostPerMillion:.15,outputCostPerMillion:.6,cachedInputCostPerMillion:.075,category:"GPT-4 models",tier:"standard",multiplier:0,displayNames:["GPT-4o-mini (2024-07-18)"]},"gpt-4-turbo":{inputCostPerMillion:10,outputCostPerMillion:30,category:"GPT-4 models",tier:"standard",multiplier:0,displayNames:["GPT-4 Turbo"]},"claude-sonnet-3.5":{inputCostPerMillion:3,outputCostPerMillion:15,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,cacheCreation1hCostPerMillion:6,category:"Claude models (Anthropic)",tier:"unknown",multiplier:1,displayNames:["Claude Sonnet 3.5"]},"claude-sonnet-3.7":{inputCostPerMillion:3,outputCostPerMillion:15,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,cacheCreation1hCostPerMillion:6,category:"Claude models (Anthropic)",tier:"unknown",multiplier:1,displayNames:["Claude Sonnet 3.7"]},"claude-sonnet-4":{inputCostPerMillion:3,outputCostPerMillion:15,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,cacheCreation1hCostPerMillion:6,category:"Claude models (Anthropic)",tier:"premium",multiplier:1,displayNames:["Claude Sonnet 4"],copilotPricing:{inputCostPerMillion:3,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,outputCostPerMillion:15,releaseStatus:"GA",category:"Versatile"}},"claude-sonnet-4.5":{inputCostPerMillion:3,outputCostPerMillion:15,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,cacheCreation1hCostPerMillion:6,category:"Claude models (Anthropic)",tier:"standard",multiplier:1,displayNames:["Claude Sonnet 4.5"],copilotPricing:{inputCostPerMillion:3,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,outputCostPerMillion:15,releaseStatus:"GA",category:"Versatile"}},"claude-sonnet-4.6":{inputCostPerMillion:3,outputCostPerMillion:15,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,cacheCreation1hCostPerMillion:6,category:"Claude models (Anthropic)",tier:"standard",multiplier:1,displayNames:["Claude Sonnet 4.6"],copilotPricing:{inputCostPerMillion:3,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,outputCostPerMillion:15,releaseStatus:"GA",category:"Versatile"}},"claude-sonnet-4-6":{inputCostPerMillion:3,outputCostPerMillion:15,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,cacheCreation1hCostPerMillion:6,category:"Claude models (Anthropic)",tier:"standard",multiplier:1,displayNames:["Claude Sonnet 4.6 (alternate format)"],copilotPricing:{inputCostPerMillion:3,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,outputCostPerMillion:15,releaseStatus:"GA",category:"Versatile"}},"claude-haiku":{inputCostPerMillion:.25,outputCostPerMillion:1.25,cachedInputCostPerMillion:.025,cacheCreationCostPerMillion:.3125,cacheCreation1hCostPerMillion:.5,category:"Claude models (Anthropic)",tier:"standard",multiplier:0,displayNames:["Claude Haiku"]},"claude-haiku-4.5":{inputCostPerMillion:1,outputCostPerMillion:5,cachedInputCostPerMillion:.1,cacheCreationCostPerMillion:1.25,cacheCreation1hCostPerMillion:2,category:"Claude models (Anthropic)",tier:"standard",multiplier:.33,displayNames:["Claude Haiku 4.5"],copilotPricing:{inputCostPerMillion:1,cachedInputCostPerMillion:.1,cacheCreationCostPerMillion:1.25,outputCostPerMillion:5,releaseStatus:"GA",category:"Versatile"}},"claude-haiku-4-5-20251001":{inputCostPerMillion:1,outputCostPerMillion:5,cachedInputCostPerMillion:.1,cacheCreationCostPerMillion:1.25,cacheCreation1hCostPerMillion:2,category:"Claude models (Anthropic)",tier:"standard",multiplier:.33,displayNames:["Claude Haiku 4.5 (2025-10-01)"],copilotPricing:{inputCostPerMillion:1,cachedInputCostPerMillion:.1,cacheCreationCostPerMillion:1.25,outputCostPerMillion:5,releaseStatus:"GA",category:"Versatile"}},"claude-opus-4.1":{inputCostPerMillion:15,outputCostPerMillion:75,cachedInputCostPerMillion:1.5,cacheCreationCostPerMillion:18.75,cacheCreation1hCostPerMillion:30,category:"Claude models (Anthropic)",tier:"premium",multiplier:10,displayNames:["Claude Opus 4.1"]},"claude-opus-4.5":{inputCostPerMillion:5,outputCostPerMillion:25,cachedInputCostPerMillion:.5,cacheCreationCostPerMillion:6.25,cacheCreation1hCostPerMillion:10,category:"Claude models (Anthropic)",tier:"standard",multiplier:3,displayNames:["Claude Opus 4.5"],copilotPricing:{inputCostPerMillion:5,cachedInputCostPerMillion:.5,cacheCreationCostPerMillion:6.25,outputCostPerMillion:25,releaseStatus:"GA",category:"Powerful"}},"claude-opus-4.6":{inputCostPerMillion:5,outputCostPerMillion:25,cachedInputCostPerMillion:.5,cacheCreationCostPerMillion:6.25,cacheCreation1hCostPerMillion:10,category:"Claude models (Anthropic)",tier:"standard",multiplier:3,displayNames:["Claude Opus 4.6"],copilotPricing:{inputCostPerMillion:5,cachedInputCostPerMillion:.5,cacheCreationCostPerMillion:6.25,outputCostPerMillion:25,releaseStatus:"GA",category:"Powerful"}},"claude-opus-4.7":{inputCostPerMillion:5,outputCostPerMillion:25,cachedInputCostPerMillion:.5,cacheCreationCostPerMillion:6.25,cacheCreation1hCostPerMillion:10,category:"Claude models (Anthropic)",tier:"standard",multiplier:15,displayNames:["Claude Opus 4.7"],copilotPricing:{inputCostPerMillion:5,cachedInputCostPerMillion:.5,cacheCreationCostPerMillion:6.25,outputCostPerMillion:25,releaseStatus:"GA",category:"Powerful"}},"claude-opus-4.6-(fast-mode)-(preview)":{inputCostPerMillion:5,outputCostPerMillion:25,cachedInputCostPerMillion:.5,cacheCreationCostPerMillion:6.25,cacheCreation1hCostPerMillion:10,category:"Claude models (Anthropic)",tier:"standard",multiplier:30,displayNames:["Claude Opus 4.6 (Fast Mode Preview)"],copilotPricing:{inputCostPerMillion:30,cachedInputCostPerMillion:3,cacheCreationCostPerMillion:37.5,outputCostPerMillion:150,releaseStatus:"Public preview",category:"Powerful"}},"claude-opus-4.6-fast":{inputCostPerMillion:5,outputCostPerMillion:25,cachedInputCostPerMillion:.5,cacheCreationCostPerMillion:6.25,cacheCreation1hCostPerMillion:10,category:"Claude models (Anthropic)",tier:"premium",multiplier:30,displayNames:["Claude Opus 4.6 (Fast)"],copilotPricing:{inputCostPerMillion:30,cachedInputCostPerMillion:3,cacheCreationCostPerMillion:37.5,outputCostPerMillion:150,releaseStatus:"Public preview",category:"Powerful"}},"o3-mini":{inputCostPerMillion:1.1,outputCostPerMillion:4.4,category:"OpenAI reasoning models",tier:"premium",multiplier:1,displayNames:["o3-mini"]},"o4-mini":{inputCostPerMillion:1.1,outputCostPerMillion:4.4,category:"OpenAI reasoning models",tier:"premium",multiplier:1,displayNames:["o4-mini"]},"o1-preview":{inputCostPerMillion:15,outputCostPerMillion:60,category:"OpenAI reasoning models",tier:"premium",multiplier:1,displayNames:["o1-preview"]},"o1-mini":{inputCostPerMillion:3,outputCostPerMillion:12,category:"OpenAI reasoning models",tier:"premium",multiplier:1,displayNames:["o1-mini"]},"gpt-3.5-turbo":{inputCostPerMillion:.5,outputCostPerMillion:1.5,category:"Legacy models",tier:"standard",multiplier:0,displayNames:["GPT-3.5-Turbo","GPT-3.5 Turbo"]},"gemini-2.5-pro":{inputCostPerMillion:1.25,outputCostPerMillion:10,category:"Google Gemini models",tier:"standard",multiplier:1,displayNames:["Gemini 2.5 Pro"],copilotPricing:{inputCostPerMillion:1.25,cachedInputCostPerMillion:.125,outputCostPerMillion:10,releaseStatus:"GA",category:"Powerful"},cachedInputCostPerMillion:.125},"gemini-2.5-flash":{inputCostPerMillion:.3,outputCostPerMillion:2.5,category:"Google Gemini models",tier:"unknown",multiplier:1,displayNames:["Gemini 2.5 Flash"]},"gemini-2.5-flash-lite":{inputCostPerMillion:.1,outputCostPerMillion:.4,category:"Google Gemini models",tier:"unknown",multiplier:1,displayNames:["Gemini 2.5 Flash Lite"]},"gemini-2.0-flash":{inputCostPerMillion:.1,outputCostPerMillion:.4,category:"Google Gemini models",tier:"standard",multiplier:0,displayNames:["Gemini 2.0 Flash"]},"gemini-2.0-flash-lite":{inputCostPerMillion:.075,outputCostPerMillion:.3,category:"Google Gemini models",tier:"standard",multiplier:0,displayNames:["Gemini 2.0 Flash Lite"]},"gemini-3-flash":{inputCostPerMillion:.5,outputCostPerMillion:3,category:"Google Gemini models",tier:"standard",multiplier:.33,displayNames:["Gemini 3 Flash"],copilotPricing:{inputCostPerMillion:.5,cachedInputCostPerMillion:.05,outputCostPerMillion:3,releaseStatus:"Public preview",category:"Lightweight"},cachedInputCostPerMillion:.05},"gemini-3-pro":{inputCostPerMillion:2,outputCostPerMillion:12,category:"Google Gemini models",tier:"premium",multiplier:1,displayNames:["Gemini 3 Pro"]},"gemini-3-pro-preview":{inputCostPerMillion:2,outputCostPerMillion:12,category:"Google Gemini models",tier:"premium",multiplier:1,displayNames:["Gemini 3 Pro (Preview)"]},"gemini-3.1-pro":{inputCostPerMillion:2,outputCostPerMillion:12,category:"Google Gemini models",tier:"standard",multiplier:1,displayNames:["Gemini 3.1 Pro","Gemini 3.1 Pro (Preview)"],copilotPricing:{inputCostPerMillion:2,cachedInputCostPerMillion:.2,outputCostPerMillion:12,releaseStatus:"Public preview",category:"Powerful"},cachedInputCostPerMillion:.2},"gemini-3.1-flash-lite":{inputCostPerMillion:.25,outputCostPerMillion:1.5,category:"Google Gemini models",tier:"unknown",multiplier:.33,displayNames:["Gemini 3.1 Flash Lite"]},"grok-code-fast-1":{inputCostPerMillion:.2,outputCostPerMillion:1.5,category:"xAI Grok models",tier:"premium",multiplier:.25,displayNames:["Grok Code Fast 1"],copilotPricing:{inputCostPerMillion:.2,cachedInputCostPerMillion:.02,outputCostPerMillion:1.5,releaseStatus:"GA",category:"Lightweight"}},"raptor-mini":{inputCostPerMillion:.25,outputCostPerMillion:2,category:"GitHub Copilot fine-tuned models",tier:"standard",multiplier:0,displayNames:["Raptor Mini"],copilotPricing:{inputCostPerMillion:.25,cachedInputCostPerMillion:.025,outputCostPerMillion:2,releaseStatus:"GA",category:"Versatile"},cachedInputCostPerMillion:.025},goldeneye:{inputCostPerMillion:0,outputCostPerMillion:0,category:"GitHub Copilot fine-tuned models",tier:"standard",multiplier:0,copilotPricing:{inputCostPerMillion:1.25,cachedInputCostPerMillion:.125,outputCostPerMillion:10,releaseStatus:"Public preview",category:"Powerful"}},"gpt-5.5":{inputCostPerMillion:5,outputCostPerMillion:30,category:"GPT-5 models",tier:"standard",multiplier:7.5,displayNames:["GPT-5.5"],cachedInputCostPerMillion:.5},"mistral-large-latest":{inputCostPerMillion:.5,outputCostPerMillion:1.5,category:"Mistral models",tier:"unknown",multiplier:1,displayNames:["Mistral Large 3"]},"mistral-large-2512":{inputCostPerMillion:.5,outputCostPerMillion:1.5,category:"Mistral models",tier:"unknown",multiplier:1,displayNames:["Mistral Large 3 (2512)"]},"mistral-large-2411":{inputCostPerMillion:2,outputCostPerMillion:6,category:"Mistral models",tier:"unknown",multiplier:1,displayNames:["Mistral Large 2.1"]},"magistral-medium-latest":{inputCostPerMillion:2,outputCostPerMillion:5,category:"Mistral models",tier:"unknown",multiplier:1,displayNames:["Magistral Medium"]},"mistral-medium-latest":{inputCostPerMillion:1.5,outputCostPerMillion:7.5,category:"Mistral models",tier:"unknown",multiplier:1,displayNames:["Mistral Medium 3.5"]},"mistral-medium-3-5":{inputCostPerMillion:1.5,outputCostPerMillion:7.5,category:"Mistral models",tier:"unknown",multiplier:1,displayNames:["Mistral Medium 3.5"]},"mistral-medium-3.5":{inputCostPerMillion:1.5,outputCostPerMillion:7.5,category:"Mistral models",tier:"unknown",multiplier:1,displayNames:["Mistral Medium 3.5"]},"mistral-medium-2505":{inputCostPerMillion:.4,outputCostPerMillion:2,category:"Mistral models",tier:"unknown",multiplier:1,displayNames:["Mistral Medium 3.1"]},"mistral-small-latest":{inputCostPerMillion:.1,outputCostPerMillion:.3,category:"Mistral models",tier:"unknown",multiplier:1,displayNames:["Mistral Small 3.1"]},"mistral-small-2503":{inputCostPerMillion:.075,outputCostPerMillion:.2,category:"Mistral models",tier:"unknown",multiplier:1,displayNames:["Mistral Small 3.2"]},"mistral-small-2603":{inputCostPerMillion:.15,outputCostPerMillion:.6,category:"Mistral models",tier:"unknown",multiplier:1,displayNames:["Mistral Small 4"]},"codestral-latest":{inputCostPerMillion:.3,outputCostPerMillion:.9,category:"Mistral models",tier:"unknown",multiplier:1,displayNames:["Codestral"]},"codestral-2501":{inputCostPerMillion:.3,outputCostPerMillion:.9,category:"Mistral models",tier:"unknown",multiplier:1,displayNames:["Codestral (2501)"]},"open-mistral-nemo":{inputCostPerMillion:.02,outputCostPerMillion:.03,category:"Mistral models",tier:"unknown",multiplier:1,displayNames:["Mistral Nemo"]},"ministral-3b-2410":{inputCostPerMillion:.04,outputCostPerMillion:.04,category:"Mistral models",tier:"unknown",multiplier:1,displayNames:["Ministral 3B"]},"ministral-8b-2410":{inputCostPerMillion:.1,outputCostPerMillion:.1,category:"Mistral models",tier:"unknown",multiplier:1,displayNames:["Ministral 8B"]},"magistral-small-latest":{inputCostPerMillion:.5,outputCostPerMillion:1.5,category:"Mistral models",tier:"unknown",multiplier:1,displayNames:["Magistral Small"]},"devstral-medium-2507":{inputCostPerMillion:.4,outputCostPerMillion:2,category:"Mistral models",tier:"unknown",multiplier:1,displayNames:["Devstral Medium"]},"pixtral-large-2411":{inputCostPerMillion:2,outputCostPerMillion:6,category:"Mistral models",tier:"unknown",multiplier:1,displayNames:["Pixtral Large"]},"gemini-3.5-flash":{inputCostPerMillion:1.5,outputCostPerMillion:9,category:"Google Gemini models",tier:"standard",multiplier:14,displayNames:["Gemini 3.5 Flash"],cachedInputCostPerMillion:.15},"claude-opus-4.8":{inputCostPerMillion:5,outputCostPerMillion:25,category:"Claude models (Anthropic)",tier:"standard",multiplier:15,displayNames:["Claude Opus 4.8"],cachedInputCostPerMillion:.5,cacheCreationCostPerMillion:6.25,cacheCreation1hCostPerMillion:10},"qwen2.5":{inputCostPerMillion:0,outputCostPerMillion:0,category:" models",tier:"standard",multiplier:0,displayNames:["Qwen2.5"]},"mai-code-1-flash[^mai-code-1-flash]":{inputCostPerMillion:0,outputCostPerMillion:0,category:" models",tier:"standard",multiplier:0,displayNames:["MAI-Code-1-Flash[^mai-code-1-flash]"]},"mai-code-1-flash":{inputCostPerMillion:.75,outputCostPerMillion:4.5,category:" models",tier:"standard",multiplier:0,displayNames:["MAI-Code-1-Flash"],cachedInputCostPerMillion:.075},"claude-fable-5":{inputCostPerMillion:10,outputCostPerMillion:50,category:"Claude models (Anthropic)",tier:"standard",multiplier:0,displayNames:["Claude Fable 5"],cachedInputCostPerMillion:1,cacheCreationCostPerMillion:12.5,cacheCreation1hCostPerMillion:20},"deepseek-v4-flash":{inputCostPerMillion:.14,outputCostPerMillion:.28,cachedInputCostPerMillion:.0028,category:"DeepSeek models",tier:"standard",multiplier:0,displayNames:["DeepSeek V4 Flash"]},"deepseek-v4-flash-free":{inputCostPerMillion:0,outputCostPerMillion:0,category:"DeepSeek models",tier:"standard",multiplier:0,displayNames:["DeepSeek V4 Flash (free)"]},"claude-sonnet-5":{inputCostPerMillion:2,outputCostPerMillion:10,category:"Claude models (Anthropic)",tier:"standard",multiplier:0,displayNames:["Claude Sonnet 5"],cachedInputCostPerMillion:.2,cacheCreationCostPerMillion:2.5,cacheCreation1hCostPerMillion:4},"claude-opus-4.8-(fast-mode)-(preview)":{inputCostPerMillion:10,outputCostPerMillion:50,category:"Claude models (Anthropic)",tier:"standard",multiplier:0,displayNames:["Claude Opus 4.8 (fast mode) (preview)"],cachedInputCostPerMillion:1,cacheCreationCostPerMillion:12.5,cacheCreation1hCostPerMillion:20},"kimi-k2.7-code":{inputCostPerMillion:.95,outputCostPerMillion:4,category:"Moonshot AI models",tier:"standard",multiplier:0,displayNames:["Kimi-K2.7-Code"],cachedInputCostPerMillion:.19},"gpt-5.6-luna":{inputCostPerMillion:1,outputCostPerMillion:6,category:"GPT-5 models",tier:"standard",multiplier:0,displayNames:["GPT-5.6 Luna"],cachedInputCostPerMillion:.1,copilotPricing:{inputCostPerMillion:1,cachedInputCostPerMillion:.1,outputCostPerMillion:6,releaseStatus:"GA",category:"Lightweight",longContext:{inputCostPerMillion:2,cachedInputCostPerMillion:.2,outputCostPerMillion:9,threshold:"> 200K"}}},"gpt-5.6-sol":{inputCostPerMillion:5,outputCostPerMillion:30,category:"GPT-5 models",tier:"standard",multiplier:0,displayNames:["GPT-5.6 Sol"],cachedInputCostPerMillion:.5,copilotPricing:{inputCostPerMillion:5,cachedInputCostPerMillion:.5,outputCostPerMillion:30,releaseStatus:"GA",category:"Powerful",longContext:{inputCostPerMillion:10,cachedInputCostPerMillion:1,outputCostPerMillion:45,threshold:"> 272K"}}},"gpt-5.6-terra":{inputCostPerMillion:2.5,outputCostPerMillion:15,category:"GPT-5 models",tier:"standard",multiplier:0,displayNames:["GPT-5.6 Terra"],cachedInputCostPerMillion:.25,copilotPricing:{inputCostPerMillion:2.5,cachedInputCostPerMillion:.25,outputCostPerMillion:15,releaseStatus:"GA",category:"Versatile",longContext:{inputCostPerMillion:5,cachedInputCostPerMillion:.5,outputCostPerMillion:22.5,threshold:"> 272K"}}}}};var ld={unknown:"Unknown",windsurf_cascade:"Windsurf Cascade",windsurf_file_edit:"Windsurf: File Edit",windsurf_file_create:"Windsurf: File Create",windsurf_file_read:"Windsurf: File Read",windsurf_terminal:"Windsurf: Terminal",windsurf_search:"Windsurf: Search",windsurf_browser:"Windsurf: Browser",run_in_terminal:"Run In Terminal",run_shell_command:"Run Shell Command",send_to_terminal:"Send To Terminal",run_build:"Run Build",run_command_in_terminal:"Run Command In Terminal","mcp.io.github.git.assign_copilot_to_issue":"GitHub MCP (Local): Assign Copilot to Issue","mcp.io.github.git.create_or_update_file":"GitHub MCP (Local): Create/Update File",mcp_io_github_git_create_or_update_file:"GitHub MCP (Local): Create/Update File",mcp_io_github_git_assign_copilot_to_issue:"GitHub MCP (Local): Assign Copilot to Issue",mcp_io_github_git_pull_request_read:"GitHub MCP (Local): Pull Request Read",mcp_io_github_git_issue_read:"GitHub MCP (Local): Issue Read",mcp_io_github_git_issue_write:"GitHub MCP (Local): Issue Write",mcp_io_github_git_list_issues:"GitHub MCP (Local): List Issues",mcp_io_github_git_create_pull_request:"GitHub MCP (Local): Create Pull Request",mcp_io_github_git_get_file_contents:"GitHub MCP (Local): Get File Contents",mcp_io_github_git_search_code:"GitHub MCP (Local): Search Code",mcp_io_github_git_search_pull_requests:"GitHub MCP (Local): Search Pull Requests",mcp_io_github_git_get_release_by_tag:"GitHub MCP (Local): Get Release By Tag",mcp_io_github_git_search_issues:"GitHub MCP (Local): Search Issues",mcp_io_github_git_add_issue_comment:"GitHub MCP (Local): Add Issue Comment",mcp_io_github_git_list_pull_requests:"GitHub MCP (Local): List Pull Requests",mcp_io_github_git_get_commit:"GitHub MCP (Local): Get Commit",mcp_io_github_git_list_commits:"GitHub MCP (Local): List Commits",mcp_io_github_git_list_code_scanning_alerts:"GitHub MCP (Local): List Code Scanning Alerts",mcp_io_github_git_get_repository_tree:"GitHub MCP (Local): Get Repository Tree",mcp_io_github_git_get_job_logs:"GitHub MCP (Local): Get Job Logs",mcp_io_github_git_list_tags:"GitHub MCP (Local): List Tags",mcp_io_github_git_search_repositories:"GitHub MCP (Local): Search Repositories",mcp_io_github_git_create_repository:"GitHub MCP (Local): Create Repository",mcp_io_github_git_search_users:"GitHub MCP (Local): Search Users",mcp_io_github_git_get_latest_release:"GitHub MCP (Local): Get Latest Release",mcp_io_github_git_get_tag:"GitHub MCP (Local): Get Tag",mcp_github_github_assign_copilot_to_issue:"GitHub MCP (Remote): Assign Copilot to Issue",mcp_github_github_issue_read:"GitHub MCP (Remote): Issue Read",mcp_github_github_issue_write:"GitHub MCP (Remote): Issue Write",mcp_github_github_list_issues:"GitHub MCP (Remote): List Issues",mcp_github_get_file_contents:"GitHub MCP (Remote): Get File Contents",mcp_github_get_latest_release:"GitHub MCP (Remote): Get Latest Release",mcp_github_get_release_by_tag:"GitHub MCP (Remote): Get Release By Tag",mcp_github_list_releases:"GitHub MCP (Remote): List Releases",mcp_github_list_tags:"GitHub MCP (Remote): List Tags",mcp_github_search_code:"GitHub MCP (Remote): Search Code",mcp_github_search_issues:"GitHub MCP (Remote): Search Issues",mcp_github_issue_write:"GitHub MCP (Remote): Issue Write",mcp_github_list_issues:"GitHub MCP (Remote): List Issues",mcp_github_create_pull_request:"GitHub MCP (Remote): Create Pull Request",mcp_github_pull_request_read:"GitHub MCP (Remote): Pull Request Read",mcp_github_list_branches:"MCP GitHub List Branches",mcp_github_update_pull_request:"MCP GitHub Update Pull Request","github-mcp-server-get_file_contents":"GitHub MCP: Get File Contents","github-mcp-server-get_job_logs":"GitHub MCP: Get Job Logs","github-mcp-server-list_commits":"GitHub MCP: List Commits","github-mcp-server-search_code":"GitHub MCP: Search Code","github-mcp-server-actions_list":"GitHub MCP: Actions List","github-mcp-server-list_issues":"GitHub MCP: List Issues","github-mcp-server-search_repositories":"GitHub MCP: Search Repositories","github-mcp-server-list_branches":"GitHub MCP: List Branches","github-mcp-server-issue_read":"GitHub MCP: Issue Read","github-mcp-server-issue_write":"GitHub MCP: Issue Write","github-mcp-server-pull_request_read":"GitHub MCP: Pull Request Read","github-mcp-server-search_issues":"GitHub MCP: Search Issues","github-mcp-server-search_users":"GitHub MCP: Search Users","github-mcp-server-sub_issue_write":"GitHub MCP: Sub Issue Write","github-mcp-server-list_pull_requests":"GitHub MCP Server List Pull Requests","github-mcp-server-search_pull_requests":"GitHub MCP (Remote): Search Pull Requests","github-actions_get":"GitHub Actions: Get","github-actions_list":"GitHub Actions: List","github-create_pull_request":"GitHub: Create Pull Request","github-get_commit":"GitHub: Get Commit","github-get_file_contents":"GitHub: Get File Contents","github-get_job_logs":"GitHub: Get Job Logs","github-get_latest_release":"GitHub: Get Latest Release","github-get_me":"GitHub: Get Me","github-get_release_by_tag":"GitHub: Get Release By Tag","github-get_repository_tree":"GitHub: Get Repository Tree","github-get_teams":"GitHub: Get Teams","github-github_support_docs_search":"GitHub: GitHub Support Docs Search","github-issue_read":"GitHub: Issue Read","github-list_code_scanning_alerts":"GitHub: List Code Scanning Alerts","github-list_dependabot_alerts":"GitHub: List Dependabot Alerts","github-list_tags":"GitHub: List Tags","github-pull_request_read":"GitHub: Pull Request Read","github-pull_request_review_write":"GitHub: Pull Request Review Write","github-search_code":"GitHub: Search Code","github-search_pull_requests":"GitHub: Search Pull Requests","github-search_repositories":"GitHub: Search Repositories","github-update_pull_request":"GitHub: Update Pull Request","mcp_github-code-s_get_code_scanning_alert":"GitHub MCP (Code Scanning): Get Alert","mcp_github-code-s_list_code_scanning_alerts":"GitHub MCP (Code Scanning): List Alerts",mcp_com_microsoft_get_bestpractices:"GitHub MCP: Get Best Practices",mcp_microsoft_doc_microsoft_code_sample_search:"Microsoft Docs MCP: Code Sample Search",mcp_microsoft_doc_microsoft_docs_search:"Microsoft Docs MCP: Docs Search",mcp_microsoftdocs_microsoft_code_sample_search:"Microsoft Docs MCP: Code Sample Search",mcp_microsoftdocs_microsoft_docs_fetch:"Microsoft Docs MCP: Docs Fetch",mcp_microsoftdocs_microsoft_docs_search:"Microsoft Docs MCP: Docs Search",Microsoft_Learn_microsoft_docs_search:"Microsoft Learn: Docs Search","microsoft-learn-microsoft_docs_search":"Microsoft Learn: Docs Search",mcp_gitkraken_git_add_or_commit:"GitKraken MCP: Git Add or Commit",mcp_gitkraken_git_status:"GitKraken MCP: Git Status",mcp_gitkraken_git_branch:"GitKraken MCP: Git Branch",mcp_gitkraken_git_checkout:"GitKraken MCP: Git Checkout",mcp_gitkraken_git_log_or_diff:"GitKraken MCP: Git Log or Diff",mcp_gitkraken_gitkraken_workspace_list:"GitKraken MCP: List Workspaces",mcp_gitkraken_git_push:"GitKraken MCP: Git Push",mcp_gitkraken_gitlens_commit_composer:"GitKraken MCP: GitLens Commit Composer",mcp_git_git_log:"Git MCP: Git Log",mcp_git_git_show:"Git MCP: Git Show",mcp_git_git_diff_staged:"Git MCP: Git Diff Staged",mcp_pencil_batch_design:"Pencil MCP: Batch Design",mcp_pencil_get_editor_state:"Pencil MCP: Get Editor State",mcp_pencil_get_guidelines:"Pencil MCP: Get Guidelines",mcp_pencil_get_screenshot:"Pencil MCP: Get Screenshot",mcp_pencil_snapshot_layout:"Pencil MCP: Snapshot Layout",mcp_figma_get_design_context:"Figma MCP: Get Design Context",mcp_figma_get_screenshot:"Figma MCP: Get Screenshot",mcp_figma_get_variable_defs:"Figma MCP: Get Variable Defs",mcp_azure_aks:"Azure MCP: AKS",mcp_azure_mcp_azureterraformbestpractices:"Azure MCP: Azure Terraform Best Practices",mcp_azure_mcp_documentation:"Azure MCP: Documentation",mcp_azure_mcp_get_bestpractices:"Azure MCP: Get Best Practices",mcp_azure_mcp_group_list:"Azure MCP: Group List",mcp_azure_mcp_storage:"Azure MCP: Storage",mcp_azure_mcp_subscription_list:"Azure MCP: Subscription List",mcp_azure_mcp_pricing:"Azure MCP: Pricing",mcp_azure_mcp_get_azure_bestpractices:"Azure MCP: Get Azure Best Practices","azure-mcp-azureterraformbestpractices":"Azure MCP: Azure Terraform Best Practices","azure-mcp-documentation":"Azure MCP: Documentation","azure-mcp-extension_cli_generate":"Azure MCP: Extension CLI Generate","azure-mcp-get_azure_bestpractices":"Azure MCP: Get Azure Best Practices","azure-mcp-group_list":"Azure MCP: Group List","azure-mcp-subscription_list":"Azure MCP: Subscription List",mcp_bicep_format_bicep_file:"Bicep MCP: Format Bicep File",mcp_bicep_get_az_resource_type_schema:"Bicep MCP: Get Az Resource Type Schema",mcp_bicep_get_bicep_best_practices:"Bicep MCP: Get Bicep Best Practices",mcp_bicep_get_bicep_file_diagnostics:"Bicep MCP: Get Bicep File Diagnostics",mcp_bicep_list_az_resource_types_for_provider:"Bicep MCP: List Az Resource Types For Provider","azure_bicep-get_azure_verified_module":"Azure Bicep: Get Azure Verified Module","azure_development-recommend_custom_modes":"Azure Development: Recommend Custom Modes","azure_resources-query_azure_resource_graph":"Azure Resources: Query Azure Resource Graph",azureResources_getAzureActivityLog:"Azure Resources: Get Azure Activity Log","azure_auth-get_auth_context":"Azure Auth: Get Auth Context","azure_auth-set_auth_context":"Azure Auth: Set Auth Context","ms-azuretools.azure-agent":"Azure Agent",manage_todo_list:"Manage TODO List",copilot_readFile:"Read File",copilot_viewImage:"Copilot View Image",opilot_findFiles:"Find Files",copilot_writeFile:"Write File",copilot_applyPatch:"Apply Patch",copilot_findTextInFiles:"Find Text In Files",copilot_findFiles:"Find Files",copilot_replaceString:"Replace String",copilot_createFile:"Create File",copilot_listDirectory:"List Directory",copilot_fetchWebPage:"Fetch Web Page",copilot_getErrors:"Get Errors",copilot_multiReplaceString:"Multi Replace String",copilot_searchCodebase:"Search Codebase",get_terminal_output:"Get Terminal Output",run_task:"Run Task: Investigate",await_terminal:"Await Terminal command","github.copilot.editsAgent":"GitHub Copilot Edits Agent",todoList:"TODO List",terminal:"Terminal",terminal_last_command:"Terminal Last Command",github_pull_request:"GitHub Pull Request",github_repo:"GitHub Repository",editFiles:"Edit Files",listFiles:"List Files",list_issues:"List Issues",search_subagent:"Search Subagent",execution_subagent:"Execution Subagent",apply_patch:"Apply Patch",ask_questions:"Ask Questions",AskUserQuestion:"Ask User Question",ask_user_question:"Ask User Question",copilot_askQuestions:"Ask Questions",copilot_createAndRunTask:"Create And Run Task",copilot_createDirectory:"Create Directory",copilot_createNewJupyterNotebook:"Create New Jupyter Notebook",copilot_createNewWorkspace:"Create New Workspace",copilot_editFiles:"Edit Files",copilot_editNotebook:"Edit Notebook",copilot_findTestFiles:"Find Test Files",copilot_getChangedFiles:"Get Changed Files",copilot_getDocInfo:"Get Doc Info",copilot_getNotebookSummary:"Get Notebook Summary",copilot_getProjectSetupInfo:"Get Project Setup Info",copilot_getSearchResults:"Get Search Results",copilot_getVSCodeAPI:"Get VSCode API",copilot_githubRepo:"GitHub Repository",copilot_githubTextSearch:"GitHub Text Search",copilot_resolveMemoryFileUri:"Resolve Memory File URI",copilot_insertEdit:"Insert Edit",copilot_installExtension:"Install Extension",copilot_memory:"Memory",copilot_openIntegratedBrowser:"Open Integrated Browser",copilot_openSimpleBrowser:"Open Simple Browser",copilot_readNotebookCellOutput:"Read Notebook Cell Output",copilot_readProjectStructure:"Read Project Structure",copilot_runNotebookCell:"Run Notebook Cell",copilot_runInTerminal:"Run In Terminal",copilot_runTests1:"Run Tests",copilot_runVscodeCommand:"Run VSCode Command",copilot_searchWorkspaceSymbols:"Search Workspace Symbols",copilot_switchAgent:"Switch Agent",copilot_testFailure:"Test Failure",copilot_toolReplay:"Tool Replay",create_and_run_task:"Create And Run Task",create_directory:"Create Directory",create_file:"Create File",remove_file:"Remove File",create_new_jupyter_notebook:"Create New Jupyter Notebook",create_new_workspace:"Create New Workspace",create_virtual_environment:"Create Virtual Environment",edit_files:"Edit Files",edit_file:"Edit File",edit_notebook_file:"Edit Notebook File",fetch_webpage:"Fetch Webpage",file_search:"File Search",get_changed_files:"Get Changed Files",get_doc_info:"Get Doc Info",get_errors:"Get Errors",get_project_setup_info:"Get Project Setup Info",get_files_in_project:"Get Files In Project",get_projects_in_solution:"Get Projects In Solution",configure_python_environment:"Configure Python Environment",get_python_executable_details:"Get Python Executable Details",get_search_view_results:"Get Search View Results",get_task_output:"Get Task Output",get_output_window_logs:"Get Output Window Logs",job_output:"Job Output",get_vscode_api:"Get VSCode API",grep_search:"Grep Search",insert_edit_into_file:"Insert Edit Into File",install_extension:"Install Extension",install_python_packages:"Install Python Packages",list_dir:"List Dir",list_directory:"List Directory",ls:"Ls",memory:"Memory",multi_replace_string_in_file:"Multi Replace String In File",open_integrated_browser:"Open Integrated Browser",open_simple_browser:"Open Simple Browser",read_file:"Read File",view_image:"View Image",read_notebook_cell_output:"Read Notebook Cell Output",read_project_structure:"Read Project Structure",replace_string_in_file:"Replace String In File","setup.agent":"Setup Agent",selectEnvironment:"Select Environment",run_notebook_cell:"Run Notebook Cell",run_vscode_command:"Run VSCode Command",runSubagent:"Run Subagent",renderMermaidDiagram:"Render Mermaid Diagram",runTests:"Run Tests",search_workspace_symbols:"Search Workspace Symbols",semantic_search:"Semantic Search",switch_agent:"Switch Agent",terminal_selection:"Terminal Selection",test_failure:"Test Failure",test_search:"Test Search",tool_replay:"Tool Replay",tool_search:"Tool Search",vscode_askQuestions:"VSCode Ask Questions",vscode_get_confirmation:"VSCode Get Confirmation",vscode_get_confirmation_with_options:"VSCode Get Confirmation With Options",vscode_get_terminal_confirmation:"VSCode Get Terminal Confirmation",vscode_get_modified_files_confirmation:"VSCode Get Modified Files Confirmation",vscode_listCodeUsages:"VSCode List Code Usages",vscode_renameSymbol:"VSCode Rename Symbol","mcp_io_github_ups_get-library-docs":"Context7 MCP: Get Library Docs","mcp_io_github_ups_query-docs":"Context7 MCP: Query Docs","mcp_io_github_ups_resolve-library-id":"Context7 MCP: Resolve Library ID","mcp_context7_get-library-docs":"Context7 MCP: Get Library Docs","mcp_context7_query-docs":"Context7 MCP: Query Docs","mcp_context7_resolve-library-id":"Context7 MCP: Resolve Library ID",mcp_microsoft_pla_browser_evaluate:"Playwright MCP: Browser Evaluate",mcp_microsoft_pla_browser_install:"Playwright MCP: Browser Install",mcp_microsoft_pla_browser_navigate:"Playwright MCP: Browser Navigate",mcp_microsoft_pla_browser_run_code:"Playwright MCP: Browser Run Code",mcp_microsoft_pla_browser_click:"Playwright MCP: Browser Click",mcp_microsoft_pla_browser_fill_form:"Playwright MCP: Browser Fill Form",mcp_microsoft_pla_browser_press_key:"Playwright MCP: Browser Press Key",mcp_microsoft_pla_browser_resize:"Playwright MCP: Browser Resize",mcp_microsoft_pla_browser_snapshot:"Playwright MCP: Browser Snapshot",mcp_microsoft_pla_browser_tabs:"Playwright MCP: Browser Tabs",mcp_microsoft_pla_browser_take_screenshot:"Playwright MCP: Browser Take Screenshot",mcp_microsoft_pla_browser_type:"Playwright MCP: Browser Type",mcp_microsoft_pla_browser_console_messages:"MCP Microsoft Playwright Browser Console Messages",mcp_microsoft_pla_browser_wait_for:"Mcp Microsoft Pla Browser Wait For",mcp_playwright_browser_click:"Playwright MCP: Browser Click",mcp_playwright_browser_navigate:"Playwright MCP: Browser Navigate",mcp_playwright_browser_snapshot:"Playwright MCP: Browser Snapshot",mcp_playwright_browser_take_screenshot:"Playwright MCP: Browser Take Screenshot","microsoft-playwright-mcp-browser_evaluate":"Playwright MCP: Browser Evaluate","microsoft-playwright-mcp-browser_navigate":"Playwright MCP: Browser Navigate","microsoft-playwright-mcp-browser_snapshot":"Playwright MCP: Browser Snapshot",mcp_pylance_mcp_s_pylanceDocString:"Pylance MCP: Pylance Doc String",mcp_pylance_mcp_s_pylanceRunCodeSnippet:"Pylance MCP: Run Code Snippet",mcp_pylance_mcp_s_pylanceWorkspaceRoots:"Pylance MCP: Workspace Roots",mcp_pylance_mcp_s_pylanceFileSyntaxErrors:"Pylance MCP: File Syntax Errors",mcp_pylance_mcp_s_pylanceSyntaxErrors:"Pylance MCP: Syntax Errors","mcp_chrome-devtoo_click":"Chrome DevTools MCP: Click","mcp_chrome-devtoo_evaluate_script":"Chrome DevTools MCP: Evaluate Script","mcp_chrome-devtoo_fill":"Chrome DevTools MCP: Fill","mcp_chrome-devtoo_get_network_request":"Chrome DevTools MCP: Get Network Request","mcp_chrome-devtoo_list_console_messages":"Chrome DevTools MCP: List Console Messages","mcp_chrome-devtoo_list_pages":"Chrome DevTools MCP: List Pages","mcp_chrome-devtoo_navigate_page":"Chrome DevTools MCP: Navigate Page","mcp_chrome-devtoo_new_page":"Chrome DevTools MCP: New Page","mcp_chrome-devtoo_select_page":"Chrome DevTools MCP: Select Page","mcp_chrome-devtoo_take_screenshot":"Chrome DevTools MCP: Take Screenshot","mcp_chrome-devtoo_fill_form":"Chrome DevTools MCP: Fill Form","mcp_chrome-devtoo_hover":"Chrome DevTools MCP: Hover","mcp_chrome-devtoo_list_network_requests":"Chrome DevTools MCP: List Network Requests","mcp_chrome-devtoo_press_key":"Chrome DevTools MCP: Press Key","mcp_chrome-devtoo_take_snapshot":"Chrome DevTools MCP: Take Snapshot","mcp_chrome-devtoo_wait_for":"Chrome DevTools MCP: Wait For","mcp_chrome-devtoo_close_page":"Chrome DevTools MCP: Close Page","mcp_chrome-devtoo_lighthouse_audit":"Chrome DevTools MCP: Lighthouse Audit","mcp_chrome-devtoo_performance_analyze_insight":"Chrome DevTools MCP: Performance Analyze Insight","mcp_chrome-devtoo_performance_start_trace":"Chrome DevTools MCP: Performance Start Trace","mcp_chrome-devtoo_resize_page":"Chrome DevTools MCP: Resize Page","mcp_chrome-devtoo_type_text":"Chrome DevTools MCP: Type Text",mcp_chrome_devtoo_click:"Chrome DevTools MCP: Click",mcp_chrome_devtoo_evaluate_script:"Chrome DevTools MCP: Evaluate Script",mcp_chrome_devtoo_fill:"Chrome DevTools MCP: Fill",mcp_chrome_devtoo_get_console_message:"Chrome DevTools MCP: Get Console Message",mcp_chrome_devtoo_get_network_request:"Chrome DevTools MCP: Get Network Request",mcp_chrome_devtoo_list_console_messages:"Chrome DevTools MCP: List Console Messages",mcp_chrome_devtoo_list_network_requests:"Chrome DevTools MCP: List Network Requests",mcp_chrome_devtoo_list_pages:"Chrome DevTools MCP: List Pages",mcp_chrome_devtoo_navigate_page:"Chrome DevTools MCP: Navigate Page",mcp_chrome_devtoo_new_page:"Chrome DevTools MCP: New Page",mcp_chrome_devtoo_take_snapshot:"Chrome DevTools MCP: Take Snapshot",mcp_chrome_devtoo_wait_for:"Chrome DevTools MCP: Wait For",mcp_io_github_chr_click:"Chrome DevTools MCP: Click",mcp_io_github_chr_emulate:"Chrome DevTools MCP: Emulate",mcp_io_github_chr_evaluate_script:"Chrome DevTools MCP: Evaluate Script",mcp_io_github_chr_list_network_requests:"Chrome DevTools MCP: List Network Requests",mcp_io_github_chr_list_pages:"Chrome DevTools MCP: List Pages",mcp_io_github_chr_navigate_page:"Chrome DevTools MCP: Navigate Page",mcp_io_github_chr_new_page:"Chrome DevTools MCP: New Page",mcp_io_github_chr_resize_page:"Chrome DevTools MCP: Resize Page",mcp_io_github_chr_select_page:"Chrome DevTools MCP: Select Page",mcp_io_github_chr_take_snapshot:"Chrome DevTools MCP: Take Snapshot",mcp_oraios_serena_activate_project:"Serena: Activate Project",mcp_oraios_serena_check_onboarding_performed:"Serena: Check Onboarding Performed",mcp_oraios_serena_create_text_file:"Serena: Create Text File",mcp_oraios_serena_delete_lines:"Serena: Delete Lines",mcp_oraios_serena_delete_memory:"Serena: Delete Memory",mcp_oraios_serena_edit_memory:"Serena: Edit Memory",mcp_oraios_serena_execute_shell_command:"Serena: Execute Shell Command",mcp_oraios_serena_find_file:"Serena: Find File",mcp_oraios_serena_find_referencing_symbols:"Serena: Find Referencing Symbols",mcp_oraios_serena_find_symbol:"Serena: Find Symbol",mcp_oraios_serena_get_current_config:"Serena: Get Current Config",mcp_oraios_serena_get_symbols_overview:"Serena: Get Symbols Overview",mcp_oraios_serena_initial_instructions:"Serena: Initial Instructions",mcp_oraios_serena_insert_after_symbol:"Serena: Insert After Symbol",mcp_oraios_serena_insert_at_line:"Serena: Insert At Line",mcp_oraios_serena_insert_before_symbol:"Serena: Insert Before Symbol",mcp_oraios_serena_jet_brains_find_referencing_symbols:"Serena: JetBrains Find Referencing Symbols",mcp_oraios_serena_jet_brains_find_symbol:"Serena: JetBrains Find Symbol",mcp_oraios_serena_jet_brains_get_symbols_overview:"Serena: JetBrains Get Symbols Overview",mcp_oraios_serena_jet_brains_type_hierarchy:"Serena: JetBrains Type Hierarchy",mcp_oraios_serena_list_dir:"Serena: List Dir",mcp_oraios_serena_list_memories:"Serena: List Memories",mcp_oraios_serena_onboarding:"Serena: Onboarding",mcp_oraios_serena_open_dashboard:"Serena: Open Dashboard",mcp_oraios_serena_prepare_for_new_conversation:"Serena: Prepare For New Conversation",mcp_oraios_serena_read_file:"Serena: Read File",mcp_oraios_serena_read_memory:"Serena: Read Memory",mcp_oraios_serena_remove_project:"Serena: Remove Project",mcp_oraios_serena_rename_symbol:"Serena: Rename Symbol",mcp_oraios_serena_replace_content:"Serena: Replace Content",mcp_oraios_serena_replace_lines:"Serena: Replace Lines",mcp_oraios_serena_replace_symbol_body:"Serena: Replace Symbol Body",mcp_oraios_serena_restart_language_server:"Serena: Restart Language Server",mcp_oraios_serena_search_for_pattern:"Serena: Search For Pattern",mcp_oraios_serena_summarize_changes:"Serena: Summarize Changes",mcp_oraios_serena_switch_modes:"Serena: Switch Modes",mcp_oraios_serena_think_about_collected_information:"Serena: Think About Collected Information",mcp_oraios_serena_think_about_task_adherence:"Serena: Think About Task Adherence",mcp_oraios_serena_think_about_whether_you_are_done:"Serena: Think About Whether You Are Done",mcp_oraios_serena_write_memory:"Serena: Write Memory","mcp_visuals-mcp_display_image":"Visuals MCP: Display Image","mcp_laravel-boost_tinker":"Laravel Boost MCP: Tinker",bash:"Bash",Bash:"Bash",code_search:"Code Search",detect_memories:"Detect Memories",dismiss_deployment_notifications:"Dismiss Deployment Notifications",get_currentfile:"Get Current File",get_file:"Get File",get_symbols_by_name:"Get Symbols By Name","claude-code":"Claude Code","copilot-cloud-agent":"Copilot Cloud Agent",agent:"Agent",copilotcli:"Copilot CLI","github.copilot.default":"GitHub Copilot Default","github.copilot.workspace":"GitHub Copilot Workspace","github.copilot.vscode":"GitHub Copilot VSCode","github.copilot-dynamic.platform":"GitHub Copilot Dynamic: Platform",glob:"Glob",file_glob_search:"File Glob Search",grep:"Grep",kill_terminal:"Kill Terminal",read:"Read",view:"View",vscode_editFile_internal:"VSCode Edit File (Internal)",vscode_fetchWebPage_internal:"VSCode Fetch Web Page (Internal)",vscode_searchExtensions_internal:"VSCode Search Extensions (Internal)","vscode-websearchforcopilot_webSearch":"VSCode WebSearch for Copilot: Web Search",Build_CMakeTools:"CMake Tools: Build",ListBuildTargets_CMakeTools:"CMake Tools: List Build Targets",ListTests_CMakeTools:"CMake Tools: List Tests",RunCtest_CMakeTools:"CMake Tools: Run CTest","nuget_get-nuget-solver":"NuGet: Get NuGet Solver",webfetch:"Web Fetch",web_fetch:"Web Fetch",write:"Write",edit:"Edit",search_replace:"Search Replace",write_file:"Write File",multiedit:"Multi Edit",question:"Question",skill:"Skill",read_skill:"Read Skill",task:"Task",todowrite:"Todo Write",TodoWrite:"Todo Write",todos:"Todos",todo:"Todo",websearch:"Web Search",WebSearch:"Web Search",click_element:"Click Element",navigate_page:"Navigate Page",open_browser_page:"Open Browser Page",read_page:"Read Page",run_playwright_code:"Run Playwright Code",screenshot_page:"Screenshot Page",type_in_page:"Type in Page",task_complete:"Task Complete","pdf-utilities.pdf":"PDF Utilities: PDF","container-tools_get-config":"Container Tools: Get Config","github-pull-request_activePullRequest":"GitHub Pull Request: Active Pull Request","github-pull-request_currentActivePullRequest":"GitHub Pull Request: Current Active Pull Request","github-pull-request_issue_fetch":"GitHub Pull Request: Issue Fetch","github-pull-request_pullRequestStatusChecks":"GitHub Pull Request: Pull Request Status Checks","github-pull-request_pullRequestInViewport":"GitHub MCP (Remote): Pull Request In Viewport","mcp_powerbi-model_connection_operations":"Power BI MCP: Connection Operations",MiniMax_web_search:"MiniMax: Web Search",dingDocuments_get_document_content:"Ding Documents: Get Document Content",dingDocuments_list_nodes:"Ding Documents: List Nodes",dingDocuments_search_documents:"Ding Documents: Search Documents",fetch_fetch:"Fetch: Fetch",mcp__Claude_in_Chrome__computer:"Claude in Chrome MCP: Computer",mcp__Claude_in_Chrome__navigate:"Claude in Chrome MCP: Navigate",mcp__Claude_in_Chrome__browser_batch:"Claude in Chrome MCP: Browser Batch",mcp__Claude_in_Chrome__get_page_text:"Claude in Chrome MCP: Get Page Text",mcp__Claude_in_Chrome__tabs_context_mcp:"Claude in Chrome MCP: Tabs Context",mcp__Claude_in_Chrome__tabs_create_mcp:"Claude in Chrome MCP: Tabs Create",mcp__Claude_in_Chrome__javascript_tool:"Claude in Chrome MCP: Javascript Tool",mcp__Claude_in_Chrome__read_console_messages:"Claude in Chrome MCP: Read Console Messages",mcp__Claude_in_Chrome__read_network_requests:"Claude in Chrome MCP: Read Network Requests",mcp__Claude_in_Chrome:"Claude in Chrome MCP",mcp__Claude_in_Chrome__find:"Claude in Chrome MCP: Find",mcp__Claude_in_Chrome__form_input:"Claude in Chrome MCP: Form Input",mcp__Claude_in_Chrome__list_connected_browsers:"Claude in Chrome MCP: List Connected Browsers",mcp__Claude_in_Chrome__read_page:"Claude in Chrome MCP: Read Page",mcp__Claude_in_Chrome__select_browser:"Claude in Chrome MCP: Select Browser",mcp__cowork__allow_cowork_file_delete:"Cowork MCP: Allow Cowork File Delete",mcp__cowork__present_files:"Cowork MCP: Present Files",mcp__cowork__request_cowork_directory:"Cowork MCP: Request Cowork Directory","mcp__cowork-onboarding__show_onboarding_role_picker":"Cowork Onboarding MCP: Show Onboarding Role Picker",TaskOutput:"Task Output",TaskStop:"Task Stop",mcp__plugins__search_plugins:"Plugins MCP: Search Plugins",mcp__plugins__suggest_plugin_install:"Plugins MCP: Suggest Plugin Install",mcp__workspace__bash:"Workspace MCP: Bash",mcp__workspace__web_fetch:"Workspace MCP: Web Fetch","mcp__mcp-registry__search_mcp_registry":"MCP Registry: Search MCP Registry",Agent:"Agent",Edit:"Edit",Glob:"Glob",Grep:"Grep",NotebookEdit:"Notebook Edit",Read:"Read",Skill:"Skill",TaskCreate:"Task Create",TaskUpdate:"Task Update",ToolSearch:"Tool Search",Write:"Write","mcp__claude_ai_Context7__resolve-library-id":"Context7 MCP (Claude): Resolve Library ID",mcp__claude_ai_Excalidraw__create_view:"Excalidraw MCP (Claude): Create View",mcp__claude_ai_Excalidraw__read_me:"Excalidraw MCP (Claude): Read Me","mcp__claude_ai_Notion__notion-create-pages":"Notion MCP (Claude): Create Pages","mcp__claude_ai_Notion__notion-fetch":"Notion MCP (Claude): Fetch","mcp__claude_ai_Notion__notion-search":"Notion MCP (Claude): Search","mcp__claude_ai_Notion__notion-update-page":"Notion MCP (Claude): Update Page","mcp__context7__query-docs":"Context7 MCP: Query Docs","mcp__context7__resolve-library-id":"Context7 MCP: Resolve Library ID","mcp__databricks-sql-allscopes__authenticate":"Databricks SQL MCP: Authenticate","mcp__databricks-sql-allscopes__complete_authentication":"Databricks SQL MCP: Complete Authentication","mcp__databricks-sql__authenticate":"Databricks SQL MCP: Authenticate",mcp__playwright__browser_evaluate:"Playwright MCP: Browser Evaluate",mcp__playwright__browser_navigate:"Playwright MCP: Browser Navigate","mcp__plugin_context7_context7__query-docs":"Context7 MCP: Query Docs","mcp__plugin_context7_context7__resolve-library-id":"Context7 MCP: Resolve Library ID","mcp__shopify-dev-mcp__learn_shopify_api":"Shopify Dev MCP: Learn Shopify API","mcp__shopify-dev-mcp__search_docs_chunks":"Shopify Dev MCP: Search Docs Chunks","mcp__shopify-dev-mcp__validate_graphql_codeblocks":"Shopify Dev MCP: Validate GraphQL Codeblocks",invalid:"Invalid",rename_session:"Rename Session",update_topic:"Update Topic",rename_branch:"Rename Branch",report_intent:"Report Intent",create_pull_request:"Create Pull Request",update_pull_request:"Update Pull Request",powershell:"PowerShell",ask_user:"Ask User",sql:"SQL",show_file:"Show File",exit_plan_mode:"Exit Plan Mode",get_changes_overview:"Get Changes Overview",annotate_diff_line:"Annotate Diff",add_pr_review_comment:"Add PR Review Comment",remove_pr_review_comment:"Remove PR Review Comment",reply_to_comment:"Reply to Comment",open_pr_session:"Open PR Session",open_issue_session:"Open Issue Session",create_session:"Create Session",list_sessions_and_chats:"List Sessions & Chats",list_projects:"List Projects",get_session:"Get Session",navigate_to:"Navigate To",delete_item:"Delete Item",send_session_message:"Send Session Message",send_chat_message:"Send Chat Message",read_agent:"Read Agent",write_agent:"Write Agent",list_agents:"List Agents",discover_widgets:"Discover Widgets",render_widget:"Render Widget",clear_widget:"Clear Widget",extensions_manage:"Extensions Manage",extensions_reload:"Extensions Reload",create:"Create",fetch_copilot_cli_documentation:"Fetch Copilot CLI Documentation",generate_findings:"Generate Findings",generate_topics:"Generate Topics",list_bash:"List Bash",read_bash:"Read Bash",write_bash:"Write Bash",stop_bash:"Stop Bash",list_powershell:"List PowerShell",read_powershell:"Read PowerShell",render_widget_inbox:"Render Widget Inbox",rg:"Ripgrep",stop_powershell:"Stop PowerShell",store_memory:"Store Memory",web_search:"Web Search",write_powershell:"Write PowerShell",slidev_chooseEntry:"Slidev: Choose Entry",slidev_getPreviewPort:"Slidev: Get Preview Port",clarify_requirements:"Clarify Requirements",get_tests:"Get Tests","ide-get_diagnostics":"IDE: Get Diagnostics","ide-get_selection":"IDE: Get Selection",plan:"Plan",signal_plan_ready:"Signal Plan Ready",update_plan_progress:"Update Plan Progress",EnterPlanMode:"Enter Plan Mode",ExitPlanMode:"Exit Plan Mode",mcp_reload:"MCP: Reload",mcp_validate:"MCP: Validate",stop_agent:"Stop Agent","workiq-accept_eula":"WorkIQ: Accept EULA","workiq-ask_work_iq":"WorkIQ: Ask Work IQ","mcp_ado-remote-mc_core_list_projects":"Azure DevOps MCP: Core List Projects","mcp_ado-remote-mc_repo_branch":"Azure DevOps MCP: Repo Branch","mcp_ado-remote-mc_repo_pull_request":"Azure DevOps MCP: Repo Pull Request","mcp_ado-remote-mc_repo_pull_request_thread":"Azure DevOps MCP: Repo Pull Request Thread","mcp_ado-remote-mc_repo_pull_request_write":"Azure DevOps MCP: Repo Pull Request Write","mcp_ado-remote-mc_repo_repository":"Azure DevOps MCP: Repo Repository","mcp_ado-remote-mc_search_workitem":"Azure DevOps MCP: Search Work Item","mcp_ado-remote-mc_wit_get_work_item":"Azure DevOps MCP: Get Work Item","mcp_ado-remote-mc_wit_work_item":"Azure DevOps MCP: Work Item","mcp_ado-remote-mc_wit_work_item_comment_write":"Azure DevOps MCP: Work Item Comment Write","mcp_ado-remote-mc_wit_work_item_link_write":"Azure DevOps MCP: Work Item Link Write","mcp_ado-remote-mc_wit_work_item_write":"Azure DevOps MCP: Work Item Write",mssql_list_servers:"MSSQL: List Servers",add_loaded_assembly:"Add Loaded Assembly",analyze_symbol:"Analyze Symbol",search_decompiled_symbols:"Search Decompiled Symbols",get_classification_rubric:"Get Classification Rubric",get_weather:"Get Weather",mcp_azure_mcp_search:"Azure MCP: Search",mcp_gitnexus_context:"GitNexus MCP: Context",mcp_gitnexus_cypher:"GitNexus MCP: Cypher",mcp_gitnexus_detect_changes:"GitNexus MCP: Detect Changes",mcp_gitnexus_impact:"GitNexus MCP: Impact",mcp_gitnexus_list_repos:"GitNexus MCP: List Repos",mcp_gitnexus_query:"GitNexus MCP: Query",slidev_getSlideContent:"Slidev: Get Slide Content",mcp__GitLab__get_mcp_server_version:"GitLab MCP: Get MCP Server Version",mcp__plugin_figma_figma__get_design_context:"Figma MCP: Get Design Context",mcp__plugin_figma_figma__get_metadata:"Figma MCP: Get Metadata",mcp__plugin_figma_figma__get_screenshot:"Figma MCP: Get Screenshot",mcp_io_github_tav_tavily_extract:"MCP Io GitHub Tavily Extract",mcp_io_github_tav_tavily_search:"MCP Io GitHub Tavily Search",browser_wait_for:"Browser Wait For",copilot_sessionStoreSql:"Copilot Session Store Sql",explore_subagent:"Explore Subagent","github.copilot.terminalPanel":"Github Copilot Terminal Panel",handle_dialog:"Handle Dialog",run_subagent:"Run Subagent",testFailure:"Test Failure","mcp_angular-cli_get_best_practices":"Angular MCP: Get Best Practices","mcp_angular-cli_list_projects":"Angular MCP: Get Project List",mcp_azure_mcp_extension_cli_generate:"Azure MCP (Local): Generate",mcp_playwright_browser_console_messages:"Playwright MCP: Browser Console Messages",mcp_com_figma_mcp_get_design_context:"Figma MCP (Local): Get Design Context",mcp_com_figma_mcp_get_screenshot:"Figma MCP (Local): Get Screenshot",mcp__Bicep__get_bicep_best_practices:"Bicep MCP: Get Bicep Best Practices","mcp__microsoft-docs-learn__microsoft_docs_fetch":"Microsoft Learn MCP: Microsoft Docs Fetch","mcp__microsoft-docs-learn__microsoft_docs_search":"Microsoft Learn MCP: Microsoft Docs Search",mcp__azure__subscription_list:"Azure MCP: Subscription List",mcp__bicep__get_bicep_file_diagnostics:"Bicep MCP: File Diagnostics",mcp__linear__authenticate:"Linear MCP: Authenticate",mcp__linear__get_issue:"Linear MCP: Get Issue",mcp__linear__list_issues:"Linear MCP: List Issues",mcp__linear__list_teams:"Linear MCP: List Teams",mcp__linear__save_issue:"Linear MCP: Save Issue",mcp_workiq_accept_eula:"WorkIQ Accept EULA",mcp_workiq_ask_work_iq:"WorkIQ Ask Work IQ","mcp_microsoft-lea_microsoft_code_sample_search":"Microsoft Docs MCP (Local): Search Code Sample","mcp_microsoft-lea_microsoft_docs_search":"Microsoft Docs MCP (Remote): Search Docs","mcp_upstash_conte_query-docs":"MCP Upstash: Query Docs","mcp_upstash_conte_resolve-library-id":"MCP Upstash: Resolve Library ID",mcp__Bicep__list_avm_metadata:"MCP Bicep: List Azure Verified Module Metadata",google_research:"Google Research",task_execution:"Task Execution",tool_search_tool_regex:"Tool Search",FindDatabaseObjectsThat:"Find Database Objects That",GetTableColumnNames:"Get Table Column Names",SchemaStore_getSchema:"Schema Store Get Schema",SchemaStore_searchSchemas:"Schema Store Search Schemas",SearchSchemasForOnePartName:"Search Schemas For One Part Name",ValidateGeneratedTSQL:"Validate Generated T-SQL",aspire_execute_resource_command:"Aspire Execute Resource Command",aspire_get_doc:"Aspire Get Doc",aspire_list_console_logs:"Aspire List Console Logs",aspire_list_resources:"Aspire List Resources",aspire_list_structured_logs:"Aspire List Structured Logs",aspire_search_docs:"Aspire Search Docs",codesearch:"CodeSearch","context-engine_context_search":"Context Engine Context Search","context7_query-docs":"Context7 Query Docs","context7_resolve-library-id":"Context7 Resolve Library ID",playwright_browser_navigate:"Playwright Browser Navigate",run_tests:"Run Tests","azure-subscription_list":"Azure Subscription List",debugger_evaluate_expressions:"Debugger Evaluate Expressions",debugger_get_output_window_text:"Debugger Get Output Window Text",get_symbols:"Get Symbols",lookup_vs:"Lookup VS",search_web:"Search Web","aspire-get_doc":"Get Doc","aspire-search_docs":"Search Docs",vote_memory:"Vote Memory",create_issue:"Issue Create",save_workflow:"Workflow Save","context-mode_ctx_execute":"Context Mode: Execute","mcp_context-mode_ctx_batch_execute":"Context Mode: Batch Execute","mcp_context-mode_ctx_execute":"Context Mode: Execute","mcp_context-mode_ctx_search":"Context Mode: Search",mcp_github_issue_read:"GitHub MCP (Remote): Issue Read",mcp_github_search_repositories:"GitHub MCP (Remote): Search Repositories",mcp_io_github_tav_tavily_map:"Tavily MCP: Map","mcp_lean-ctx_ctx_call":"Lean Context: Call","mcp_lean-ctx_ctx_discover_tools":"Lean Context: Discover Tools","mcp_lean-ctx_ctx_edit":"Lean Context: Edit","mcp_lean-ctx_ctx_graph":"Lean Context: Graph","mcp_lean-ctx_ctx_knowledge":"Lean Context: Knowledge","mcp_lean-ctx_ctx_multi_read":"Lean Context: Multi Read","mcp_lean-ctx_ctx_overview":"Lean Context: Overview","mcp_lean-ctx_ctx_read":"Lean Context: Read","mcp_lean-ctx_ctx_search":"Lean Context: Search","mcp_lean-ctx_ctx_session":"Lean Context: Session","mcp_lean-ctx_ctx_shell":"Lean Context: Shell","mcp_lean-ctx_ctx_tree":"Lean Context: Tree","mcp_mcp-server-ti_get_current_time":"Time MCP: Get Current Time",mcp_playwright_browser_close:"Playwright MCP: Browser Close",mcp_playwright_browser_evaluate:"Playwright MCP: Browser Evaluate",mcp_playwright_browser_fill_form:"Playwright MCP: Browser Fill Form",mcp_playwright_browser_network_request:"Playwright MCP: Browser Network Request",mcp_playwright_browser_network_requests:"Playwright MCP: Browser Network Requests",mcp_playwright_browser_press_key:"Playwright MCP: Browser Press Key",mcp_playwright_browser_resize:"Playwright MCP: Browser Resize",mcp_playwright_browser_run_code_unsafe:"Playwright MCP: Browser Run Code Unsafe",mcp_playwright_browser_type:"Playwright MCP: Browser Type",mcp_playwright_browser_wait_for:"Playwright MCP: Browser Wait For",mcp_pylance_mcp_s_pylancePythonEnvironments:"Pylance MCP: Python Environments","mcp_spec-gen_get_architecture_overview":"Spec Gen MCP: Get Architecture Overview","mcp_spec-gen_get_call_graph":"Spec Gen MCP: Get Call Graph",mcp_specgen_analyze_codebase:"Spec Gen MCP: Analyze Codebase",mcp_specgen_get_function_body:"Spec Gen MCP: Get Function Body",mcp_specgen_get_spec:"Spec Gen MCP: Get Spec",mcp_specgen_list_spec_domains:"Spec Gen MCP: List Spec Domains",mcp_specgen_orient:"Spec Gen MCP: Orient",mcp_specgen_search_code:"Spec Gen MCP: Search Code",mcp_specgen_search_specs:"Spec Gen MCP: Search Specs",mcp_stitch_apply_design_system:"Stitch: Apply Design System",mcp_stitch_create_design_system:"Stitch: Create Design System",mcp_stitch_create_project:"Stitch: Create Project",mcp_stitch_edit_screens:"Stitch: Edit Screens",mcp_stitch_generate_screen_from_text:"Stitch: Generate Screen From Text",mcp_stitch_get_project:"Stitch: Get Project",mcp_stitch_get_screen:"Stitch: Get Screen",mcp_stitch_list_design_systems:"Stitch: List Design Systems",mcp_stitch_list_projects:"Stitch: List Projects",mcp_stitch_list_screens:"Stitch: List Screens",mcp_symdex_build_context_pack:"Symdex: Build Context Pack",mcp_symdex_get_callees:"Symdex: Get Callees",mcp_symdex_get_callers:"Symdex: Get Callers",mcp_symdex_get_file_outline:"Symdex: Get File Outline",mcp_symdex_get_file_tree:"Symdex: Get File Tree",mcp_symdex_get_graph_diagram:"Symdex: Get Graph Diagram",mcp_symdex_get_index_status:"Symdex: Get Index Status",mcp_symdex_get_repo_outline:"Symdex: Get Repo Outline",mcp_symdex_get_repo_stats:"Symdex: Get Repo Stats",mcp_symdex_index_folder:"Symdex: Index Folder",mcp_symdex_list_repos:"Symdex: List Repos",mcp_symdex_search_routes:"Symdex: Search Routes",mcp_symdex_search_symbols:"Symdex: Search Symbols",mcp_symdex_search_text:"Symdex: Search Text",mcp_tavily_tavily_crawl:"Tavily: Crawl",mcp_tavily_tavily_extract:"Tavily: Extract",mcp_tavily_tavily_search:"Tavily: Search",mcp_time_get_current_time:"Time: Get Current Time",mcp_trueline_trueline_outline:"Trueline: Outline",mcp_trueline_trueline_read:"Trueline: Read",mcp_trueline_trueline_search:"Trueline: Search",mcp_zettelkasten_zk_create_link:"Zettelkasten: Create Link",mcp_zettelkasten_zk_create_note:"Zettelkasten: Create Note",mcp_zettelkasten_zk_get_note:"Zettelkasten: Get Note",mcp_zettelkasten_zk_remove_link:"Zettelkasten: Remove Link",mcp_zettelkasten_zk_search_notes:"Zettelkasten: Search Notes",mcp_zettelkasten_zk_update_note:"Zettelkasten: Update Note",copilot_listCodeUsages:"Copilot: List Code Usages",create_new_file:"Windsurf: File Create",edit_existing_file:"Windsurf: File Edit","github.copilot.editingSession":"GitHub MCP (Local): Assign Copilot to Issue",mssql_connect:"SQL Server Connection",mssql_disconnect:"SQL Server Disconnection",mssql_list_tables:"SQL Server Tables List",mssql_run_query:"SQL Server Query Execution",run_terminal_command:"Terminal Command Run",single_find_and_replace:"Find and Replace",mcp_io_github_git_add_comment_to_pending_review:"GitHub MCP (Local): Add Comment To Pending Review",mcp_io_github_git_add_reply_to_pull_request_comment:"GitHub MCP (Local): Add Reply To Pull Request Comment",mcp_io_github_git_pull_request_review_write:"GitHub MCP (Local): Pull Request Review Write",mcp_aikido_aikido_full_scan:"Aikido MCP: Full Scan",mcp_aikido_aikido_issues_list:"Aikido MCP: Issues List",mcp_com_atlassian_addCommentToJiraIssue:"Atlassian MCP: Add Comment To Jira Issue",mcp_com_atlassian_atlassianUserInfo:"Atlassian MCP: User Info",mcp_com_atlassian_createConfluencePage:"Atlassian MCP: Create Confluence Page",mcp_com_atlassian_getAccessibleAtlassianResources:"Atlassian MCP: Get Accessible Atlassian Resources",mcp_com_atlassian_getConfluencePage:"Atlassian MCP: Get Confluence Page",mcp_com_atlassian_getConfluencePageFooterComments:"Atlassian MCP: Get Confluence Page Footer Comments",mcp_com_atlassian_getConfluenceSpaces:"Atlassian MCP: Get Confluence Spaces",mcp_com_atlassian_getJiraIssue:"Atlassian MCP: Get Jira Issue",mcp_com_atlassian_search:"Atlassian MCP: Search",mcp_com_atlassian_searchJiraIssuesUsingJql:"Atlassian MCP: Search Jira Issues Using JQL",mcp_com_atlassian_updateConfluencePage:"Atlassian MCP: Update Confluence Page",mcp_sonarqube_analyze_code_snippet:"SonarQube MCP: Analyze Code Snippet",mcp_sonarqube_get_project_quality_gate_status:"SonarQube MCP: Get Project Quality Gate Status",mcp_sonarqube_search_my_sonarqube_projects:"SonarQube MCP: Search My SonarQube Projects",mcp_sonarqube_search_security_hotspots:"SonarQube MCP: Search Security Hotspots",mcp_sonarqube_search_sonar_issues_in_projects:"SonarQube MCP: Search Sonar Issues In Projects",sonarqube_analyze_file:"SonarQube: Analyze File","azure-bicepschema":"Azure Bicep Schema","azure-documentation":"Azure Documentation","azure-extension_cli_generate":"Azure Extension CLI Generate","azure-get_azure_bestpractices":"Get Azure Best Practices",__auto_compact__:"Auto Compact",mcp_github_get_teams:"GitHub MCP (Remote): Get Teams",mcp_github_list_issue_types:"GitHub MCP (Remote): List Issue Types",mcp_github_mcp_se_issue_write:"GitHub MCP (Remote): Write Issue",mcp_github_mcp_se_list_issues:"GitHub MCP (Remote): List Issues",mcp_github_mcp_se_list_label:"GitHub MCP (Remote): List Labels",mcp_github_mcp_se_search_issues:"GitHub MCP (Remote): Search Issues",mcp_github_mcp_se_add_issue_comment:"GitHub MCP (Remote): Add Comment to Issue",mcp_github_mcp_se_create_pull_request:"GitHub MCP (Remote): Create Pull Request",mcp_github_mcp_se_get_file_contents:"GitHub MCP (Remote): Get File Contents",mcp_github_mcp_se_pull_request_read:"GitHub MCP (Remote): Read Pull Request",mcp_github_mcp_se_issue_read:" GitHub MCP (Remote): Issue Read on GitHub",mcp_github_search_users:"GitHub MCP (Remote): Search Users",mcp_github_semantic_issue_similarity_search:"GitHub MCP (Remote): Semantic Issue Similarity Search",codebase:"Codebase",invoke_subagent:"Invoke Subagent",list_permissions:"List Permissions",manage_task:"Manage Task",mcp__ccd_session__mark_chapter:"CCD Session: Mark Chapter",multi_replace_file_content:"Multi-Replace File Content",read_currently_open_file:"Read Currently Open File",replace_file_content:"Replace File Content",run_command:"Run Command",schedule:"Schedule",send_message:"Send Message",view_file:"View File",write_to_file:"Write To File",glob_search:"Glob Search","azure-devops_core_list_projects":"Azure DevOps Core List Projects","azure-devops_repo_get_file_content":"Azure DevOps Repo Get File Content","azure-devops_repo_list_repos_by_project":"Azure DevOps Repo List Repos By Project","azure-devops_search_code":"Azure DevOps Search Code","azure-devops_wit_get_work_item":"Azure DevOps Wit Get Work Item","azure-devops_wit_query_by_wiql":"Azure DevOps Wit Query By WIQL",mcp_microsoft_azu_wit_get_work_items_batch_by_ids:"Microsoft Azure DevOps MCP (Local): Get Work Items Batch by IDs",mcp_microsoft_azu_wit_get_work_items_for_iteration:"Microsoft Azure DevOps MCP (Local): Get Work Items for Iteration",mcp_microsoft_azu_wit_update_work_items_batch:"Microsoft Azure DevOps MCP (Local): Update Work Items Batch",mcp_microsoft_azu_wit_work_items_link:"Microsoft Azure DevOps MCP (Local): Link Work Items",mcp_microsoft_azu_work_list_iterations:"Microsoft Azure DevOps MCP (Local): List Iterations","microsoft_azure-devops-mcp_core_list_projects":"Azure DevOps Core List Projects","microsoft_azure-devops-mcp_search_workitem":"Azure DevOps Search Work Item","microsoft_azure-devops-mcp_wit_get_work_item":"Microsoft Azure DevOps MCP (Local): Get Work Item",mcp_com_microsoft_get_azure_bestpractices:"Microsoft Docs MCP: Get Azure Best Practices",mcp_github_enterp_create_branch:"GitHub MCP (Remote): Create Branch",mcp_github_enterp_get_latest_release:"GitHub MCP (Remote): Get Latest Release",mcp_github_enterp_pull_request_read:"GitHub MCP (Remote): Pull Request Read",handoff:"Handoff",mcp_ado_search_workitem:"ADO Search Workitem",mcp_ado_wit_add_artifact_link:"ADO Wit Add Artifact Link",mcp_ado_wit_add_child_work_items:"ADO Wit Add Child Work Items",mcp_ado_wit_add_work_item_comment:"ADO Wit Add Work Item Comment",mcp_ado_wit_create_work_item:"ADO Wit Create Work Item",mcp_ado_wit_get_work_item:"ADO Wit Get Work Item",mcp_ado_wit_get_work_item_type:"MCP Ado Wit Get Work Item Type",mcp_ado_wit_get_work_items_batch_by_ids:"MCP Ado Wit Get Work Items Batch By Ids",mcp_ado_wit_list_work_item_comments:"ADO Wit List Work Item Comments",mcp_ado_wit_my_work_items:"ADO Wit My Work Items",mcp_ado_wit_update_work_item:"ADO Wit Update Work Item",mcp_ado_wit_update_work_items_batch:"ADO Wit Update Work Items Batch",mcp_ado_wit_work_item_unlink:"ADO Wit Work Item Unlink",mcp_ado_wit_work_items_link:"ADO Wit Work Items Link",mcp_azure_devops__search_workitem:"Azure DevOps Search Workitem",mcp_github_add_issue_comment:"GitHub Add Issue Comment",mcp_github_create_branch:"GitHub Create Branch",mcp_github_list_commits:"GitHub List Commits",mcp_github_list_pull_requests:"GitHub List Pull Requests",mcp_github_push_files:"GitHub Push Files","mcp_hashline-edit_grep":"Hashline Edit Grep",mcp_raindrop_create_bookmarks:"RainDrop Create Bookmarks","mcp_symdex-mcp_semantic_search":"Symdex MCP Semantic Search","mcp_tavily-global_tavily-search":"Tavily Global Tavily-Search","mcp_tavily_tavily-extract":"Tavily Tavily-Extract","mcp_tavily_tavily-search":"Tavily Tavily-Search",mcp_tavily_tavily_research:"Tavily Tavily-Research",session_store_sql:"SQL Session Store","azure-advisor":"Azure Advisor","azure-devops-core_list_projects":"Azure DevOps Core List Projects","azure-devops-wit_work_item":"Azure DevOps Work Item","azure-devops-wit_work_item_write":"Azure DevOps Work Item Write","azure-group_resource_list":"Azure Group Resource List","azure-sql":"Azure SQL",ScheduleWakeup:"Scheduled Wakeup",mcp__ccd_session__spawn_task:"Spawn Task",mcp_figma_mcp_ser_get_design_context:"Figma MCP (Local): Get Design Context",mcp_figma_mcp_ser_get_libraries:"Figma MCP (Local): Get Libraries",mcp_figma_mcp_ser_get_metadata:"Figma MCP (Local): Get Metadata",mcp_figma_mcp_ser_search_design_system:"Figma MCP (Local): Search Design System","azure-devops-repo_file":"Azure DevOps: File","azure-devops-repo_pull_request":"Azure DevOps: Pull Request","azure-devops-repo_repository":"Azure DevOps: Repository","azure-devops-search_code":"Azure DevOps: Search Code","azure-devops-search_workitem":"Azure DevOps: Work Item","azure-devops-wiki":"Azure DevOps: Wiki","azure-devops-wiki_upsert_page":"Azure DevOps: Wiki Upsert Page","azure-devops-wit_work_item_comment_write":"Azure DevOps: Work Item Comment Write",invoke_canvas_action:"Canvas Action",list_canvas_capabilities:"List Canvas Capabilities",open_canvas:"Open Canvas",subagent:"Subagent",workiq_search_files:"WorkIQ Search Files",workiq_get_email:"Workiq Get Email",workiq_list_emails:"Workiq List Emails",github_text_search:"GitHub MCP (Local): Text Search",mcp_azure_mcp_ser_search:"Azure MCP (Remote): Search","azure_mcp-documentation":"Azure MCP Documentation",mcp_azure_mcp_ser_get_azure_bestpractices:"Serena MCP: Get Azure Best Practices",find:"Find","get-syntax-docs-mermaid":"Mermaid Syntax Docs","mermaid-chart":"Mermaid Chart","mermaid-diagram-preview":"Mermaid Diagram Preview","mermaid-diagram-validator":"Mermaid Diagram Validator",sonarqube_list_potential_security_issues:"SonarQube List Potential Security Issues",m_filesystem_tree:"File System Tree",m_get_settings:"Get Settings",m_get_skill:"Get Skill",m_list_skills:"List Skills",find_symbol:"Find Symbol",finish_plan:"Finish Plan",jcodemunch_file_outline:"JCodeMunch File Outline",jcodemunch_find_references:"JCodeMunch Find References",jcodemunch_get_file_content:"JCodeMunch Get File Content",jcodemunch_get_session_stats:"JCodeMunch Get Session Stats",jcodemunch_get_symbol_source:"JCodeMunch Get Symbol Source",jcodemunch_list_repos:"JCodeMunch List Repos",jcodemunch_search_symbols:"JCodeMunch Search Symbols",jcodemunch_search_text:"JCodeMunch Search Text","mcp_jcodemunch-mc_check_references":"JCodeMunch MCP (Local): Check References","mcp_jcodemunch-mc_find_references":"JCodeMunch MCP (Local): Find References","mcp_jcodemunch-mc_get_file_outline":"JCodeMunch MCP (Local): Get File Outline","mcp_jcodemunch-mc_index_folder":"JCodeMunch MCP (Local): Index Folder","mcp_jcodemunch-mc_list_repos":"JCodeMunch MCP (Local): List Repos","mcp_jcodemunch-mc_plan_turn":"JCodeMunch MCP (Local): Plan Turn","mcp_jcodemunch-mc_search_symbols":"JCodeMunch MCP (Local): Search Symbols","mcp_jcodemunch-mc_winnow_symbols":"JCodeMunch MCP (Local): Winnow Symbols",search_text:"Search Text",ask_question:"Ask Question",create_cpp_performance_test:"Create C++ Performance Test",debugger_continue:"Debug Continue",debugger_get_call_stack:"Debug Get Call Stack",debugger_get_frame_source:"Debug Get Frame Source",debugger_get_threads:"Debug Get Threads",debugger_launch_unit_test:"Debug Launch Unit Test","foundrytk-get_ai_model_guidance":"Foundry: AI Model Guidance","foundrytk-usage_guidance":"Foundry: Usage Guidance","mcp_atlassian-mcp_addCommentToJiraIssue":"Atlassian MCP (Local): Add Comment to Jira Issue","mcp_atlassian-mcp_atlassianUserInfo":"Atlassian MCP (Local): Get User Info","mcp_atlassian-mcp_createJiraIssue":"Atlassian MCP (Local): Create/Update Jira Issue","mcp_atlassian-mcp_editJiraIssue":"Atlassian MCP (Local): Edit Jira Issue","mcp_atlassian-mcp_getAccessibleAtlassianResources":"Atlassian MCP (Local): Get Accessible Resources","mcp_atlassian-mcp_getJiraIssue":"Atlassian MCP (Local): Get Jira Issue","mcp_atlassian-mcp_getJiraIssueTypeMetaWithFields":"Atlassian MCP (Local): Get Jira Issue Type Meta with Fields","mcp_atlassian-mcp_getJiraProjectIssueTypesMetadata":"Atlassian MCP (Local): Get Jira Project Issue Types Metadata","mcp_atlassian-mcp_getTransitionsForJiraIssue":"Atlassian MCP (Local): Get Transitions for Jira Issue","mcp_atlassian-mcp_getVisibleJiraProjects":"Atlassian MCP (Local): Get Visible Jira Projects","mcp_atlassian-mcp_searchJiraIssuesUsingJql":"Atlassian MCP (Local): Search Jira Issues Using JQL","mcp_atlassian-mcp_transitionJiraIssue":"Atlassian MCP (Local): Transition Jira Issue",mcp_figma_mcp_ser_get_screenshot:"Figma MCP: Get Screenshot",mcp_figma_mcp_ser_get_variable_defs:"Figma MCP: Get Variable Defs",mcp_gitkraken_cli_git_log_or_diff:"GitKraken MCP: Log/Compare",mcp_gitkraken_cli_git_push:"GitKraken MCP: Push",mcp_gitkraken_cli_git_status:"GitKraken MCP: Status",mcp_gitkraken_cli_gitlens_commit_composer:"GitKraken MCP: Commit Composer",profile_unit_test:"Profile Unit Test",profiler_agent:"Profiler Agent",run_profiler:"Run Profiler",define_subagent:"Define Subagent",find_by_name:"Find by Name",manage_subagents:"Manage Subagents","mcp__computer-use__request_access":"MCP: Computer Use Request Access","mcp__computer-use__screenshot":"MCP: Computer Use Screenshot",CronList:"Cron List","mcp__scheduled-tasks__list_scheduled_tasks":"MCP: Scheduled Tasks - List Scheduled Tasks",m_accept_workiq_eula:"WorkIQ EULA Acceptance",mcp_azure_bicep_m_get_bicep_best_practices:"Azure Bicep MCP (Local): Get Best Practices",mcp_azure_bicep_m_list_avm_metadata:"Azure Bicep MCP (Remote): List AVM Metadata",mcp_azure_mcp_policy:"Azure MCP Policy",workiq_search_emails:"WorkIQ Search Emails",resolve_memory_file_uri:"Serena: Resolve Memory File URI",generate_image:"Generate Image",mcp__plugins__list_plugins:"MCP Plugins List",mcp__skills__list_skills:"MCP Skills List",mcp__visualize__read_me:"MCP Visualize: Read Me",mcp__visualize__show_widget:"MCP Visualize: Show Widget",read_url_content:"Read URL Content",mcp_jira_editJiraIssue:"JIRA MCP (Remote): Edit Jira Issue",mcp_jira_getAccessibleAtlassianResources:"JIRA MCP (Remote): Get Accessible Atlassian Resources",mcp_jira_getConfluencePage:"JIRA MCP (Remote): Get Confluence Page",mcp_jira_getJiraIssue:"JIRA MCP (Remote): Get Jira Issue","mcp__scheduled-tasks__create_scheduled_task":"Scheduled Tasks MCP: Create Scheduled Task",dart_format:"Dart Format",Monitor:"Monitor",SendMessage:"Send Message","atlassian-getConfluencePage":"Confluence MCP: Page Read/Write","atlassian-getVisibleJiraProjects":"Jira MCP: Projects View/Edit","atlassian-lookupJiraAccountId":"Jira MCP: Account Lookup","github-pull-request_create_pull_request":"GitHub Pull Request Create/Update",mcp_github_check_dependency_vulnerabilities:"GitHub MCP (Local) Check Dependency Vulnerabilities",mcp_provides_tool_pylanceInvokeRefactoring:"MCP Provides Tool Pylance Invoke Refactoring","mcp__codebase-memory-mcp__get_graph_schema":"MCP Codebase Memory Get Graph Schema","mcp__codebase-memory-mcp__index_repository":"MCP Codebase Memory: Index Repository","mcp__codebase-memory-mcp__index_status":"MCP Codebase Memory: Index Status","mcp__codebase-memory-mcp__list_projects":"MCP Codebase Memory: List Projects","mcp__codebase-memory-mcp__query_graph":"MCP Codebase Memory: Query Graph","mcp__codebase-memory-mcp__search_code":"MCP Codebase Memory: Search Code","mcp__codebase-memory-mcp__search_graph":"MCP Codebase Memory: Search Graph",create_project:"Create Project","mcp__scheduled-tasks__update_scheduled_task":"MCP Scheduled Tasks: Update Scheduled Task",mcp_github_mcp_s2_create_pull_request:"MCP GitHub: Create Pull Request",respond_to_session_plan:"Respond To Session Plan",str_replace:"Str Replace","workiq-ask":"Workiq Ask",Artifact:"Figma: Get Design Context",LSP:"Visual Studio Code: LSP",TaskList:"Serena: Task List",mcp__figma__get_design_context:"Figma: Get Design Context",mcp__figma__get_metadata:"Figma: Get Metadata","mcp_atlassian-mcp_getIssueLinkTypes":"Atlassian MCP (Remote): Get Issue Link Types","mcp_atlassian-mcp_search":"Atlassian MCP (Remote): Search",cache_docs:"Cache Docs",call_agent:"Call Agent",delegate_task:"Delegate Task",diff:"Diff",get_task_result:"Get Task Result",git_diff:"Git Diff",git_status:"Git Status",http:"HTTP",jq:"JQ",lsp_diagnostics:"LSP Diagnostics",sed_replace:"SED Replace",update_todo:"Update TODO",workiq_delete_event:"WorkIQ Delete Event",workiq_list_events:"WorkIQ List Events",get_python_environment_details:"Python Environment Details","io_github_tavily-ai_tavily-mcp-tavily_search":"Tavily MCP (Remote): Search","mcp_tavily-mcp_tavily_extract":"Extract from Tavily","mcp_tavily-mcp_tavily_search":"Search in Tavily","microsoft_playwright-mcp-browser_click":"Playwright: Click","microsoft_playwright-mcp-browser_console_messages":"Playwright: Console Messages","microsoft_playwright-mcp-browser_evaluate":"Playwright: Evaluate","microsoft_playwright-mcp-browser_navigate":"Playwright: Navigate","microsoft_playwright-mcp-browser_network_request":"Playwright: Network Request","microsoft_playwright-mcp-browser_network_requests":"Microsoft Playwright MCP Browser Network Requests","microsoft_playwright-mcp-browser_snapshot":"Microsoft Playwright MCP Browser Snapshot","microsoft_playwright-mcp-browser_tabs":"Microsoft Playwright MCP Browser Tabs","microsoft_playwright-mcp-browser_wait_for":"Microsoft Playwright MCP Browser Wait For","rtf-markdown-editor.pdfChat":"PDF Chat",Azure_MCP_Server_get_azure_bestpractices:"Azure MCP: Get Azure Bestpractices",mcp_azure_mcp_ser_subscription_list:"Azure MCP: Search Subscription List","microsoft-learn-microsoft_docs_fetch":"Microsoft Learn: Microsoft Docs Fetch",record_observation:"Record Observation",readFiles:"Read Files",search:"Search",shell:"Shell",steering:"Steering","azure-devops-repo_branch":"Azure DevOps Repository Branch","canvas-authoring-compile_canvas":"Canvas Authoring: Compile Canvas","canvas-authoring-connect":"Canvas Authoring: Connect","canvas-authoring-describe_control":"Canvas Authoring: Describe Control","canvas-authoring-get_data_source_schema":"Canvas Authoring: Get Data Source Schema","canvas-authoring-list_apis":"Canvas Authoring: List APIs","canvas-authoring-list_controls":"Canvas Authoring: List Controls","canvas-authoring-list_data_sources":"Canvas Authoring: List Data Sources","canvas-authoring-sync_canvas":"Canvas Authoring: Sync Canvas","mcp__claude-in-chrome__navigate":"Claude In Chrome MCP: Navigate","mcp__claude-in-chrome__tabs_context_mcp":"Claude In Chrome MCP: Tabs Context ",mcp__Claude_Browser__preview_start:"MCP Claude Browser: Preview Start",mcp__ccd_session__dismiss_task:"MCP: Ccd Session Dismiss Task",mcp__plugin_Notion_notion__authenticate:"MCP Notion: Notion Authenticate",Workflow:"Workflow","atlassian-createJiraIssue":"Atlassian MCP: Create Jira Issue","atlassian-getAccessibleAtlassianResources":"Atlassian MCP: Get Accessible Atlassian Resources",chmod:"Chmod","context7-query-docs":"Context7 MCP: Query Docs","context7-resolve-library-id":"Context7 MCP: Resolve Library ID","github-mcp-server-add_issue_comment":"GitHub MCP: Add Issue Comment","github-mcp-server-add_reply_to_pull_request_comment":"GitHub MCP: Add Reply to Pull Request Comment","github-mcp-server-create_pull_request":"GitHub MCP: Create Pull Request","github-mcp-server-get_me":"GitHub MCP: Get Me","github-mcp-server-label_write":"GitHub MCP: Label Write","github-mcp-server-list_issue_types":"GitHub MCP: List Issue Types","github-mcp-server-list_label":"GitHub MCP: List Label","github-mcp-server-projects_list":"GitHub MCP: Projects List","github-mcp-server-pull_request_review_write":"GitHub MCP: Pull Request Review Write","github-mcp-server-semantic_issue_similarity_search":"GitHub MCP: Semantic Issue Similarity Search","github-mcp-server-semantic_issues_search":"GitHub MCP: Semantic Issues Search",mcp__ide__getDiagnostics:"IDE Get Diagnostics","mcp__microsoft_playwright-mcp__browser_click":"Playwright MCP: Browser Click","mcp__microsoft_playwright-mcp__browser_close":"Playwright MCP: Browser Close","mcp__microsoft_playwright-mcp__browser_console_messages":"Playwright MCP: Browser Console Messages","mcp__microsoft_playwright-mcp__browser_evaluate":"Playwright MCP: Browser Evaluate","mcp__microsoft_playwright-mcp__browser_navigate":"Playwright MCP: Browser Navigate","mcp__microsoft_playwright-mcp__browser_resize":"Playwright MCP: Browser Resize","mcp__microsoft_playwright-mcp__browser_snapshot":"Playwright MCP: Browser Snapshot","mcp__microsoft_playwright-mcp__browser_take_screenshot":"Playwright MCP: Browser Take Screenshot","mcp__microsoft_playwright-mcp__browser_wait_for":"Playwright MCP: Browser Wait For",tool_search_tool:"Tool Search",configure_notebook:"Notebook Configure",restart_notebook_kernel:"Kernel Restart",mcp__Claude_Browser__computer:"MCP Claude Browser: Computer",mcp__Claude_Browser__find:"MCP Claude Browser: Find",mcp__Claude_Browser__get_page_text:"MCP Claude Browser: Get Page Text",mcp__Claude_Browser__navigate:"MCP Claude Browser: Navigate",mcp__Claude_Browser__preview_list:"MCP Claude Browser: Preview List",mcp__Claude_Browser__preview_logs:"MCP Claude Browser: Preview Logs",mcp__Claude_Browser__preview_stop:"MCP Claude Browser: Preview Stop",mcp__Claude_Browser__read_console_messages:"MCP Claude Browser: Read Console Messages",mcp__Claude_Browser__read_page:"MCP Claude Browser: Read Page",mcp__Claude_Browser__tabs_context:"MCP Claude Browser: Tabs Context",mcp__Claude_Browser__tabs_create:"MCP Claude Browser: Tabs Create",mcp__Claude_Browser__tabs_select:"MCP Claude Browser: Tabs Select",mcp_github_github_create_pull_request:"GitHub MCP (Remote): Create Pull Request",mcp_github_github_get_file_contents:"GitHub MCP (Remote): Get File Contents",mcp_github_github_get_job_logs:"GitHub MCP (Remote): Get Job Logs",mcp_github_github_get_latest_release:"GitHub MCP (Remote): Get Latest Release",mcp_github_github_get_release_by_tag:"GitHub MCP (Remote): Get Release By Tag",mcp_github_github_get_repository_tree:"GitHub MCP (Remote): Get Repository Tree",mcp_github_github_get_tag:"GitHub MCP (Remote): Get Tag",mcp_github_github_list_code_scanning_alerts:"GitHub MCP (Remote): List Code Scanning Alerts",mcp_github_github_list_pull_requests:"GitHub MCP (Remote): List Pull Requests",mcp_github_github_list_tags:"GitHub MCP (Remote): List Tags",mcp_github_github_pull_request_read:"GitHub MCP (Remote): Pull Request Read",mcp_github_github_search_issues:"GitHub MCP (Remote): Search Issues",mcp_github_github_search_repositories:"GitHub MCP (Remote): Search Repositories","mcp_actions-marke_lookup-action-versions":"Actions Marketplace MCP: Lookup Action Versions",mcp__dart__analyze_files:"Dart MCP: Analyze Files",mcp__dart__connect_dart_tooling_daemon:"Dart MCP: Connect Dart Tooling Daemon",mcp__dart__flutter_driver:"Dart MCP: Flutter Driver",mcp__dart__get_app_logs:"Dart MCP: Get App Logs",mcp__dart__get_runtime_errors:"Dart MCP: Get Runtime Errors",mcp__dart__get_widget_tree:"Dart MCP: Get Widget Tree",mcp__dart__hot_reload:"Dart MCP: Hot Reload",mcp__dart__launch_app:"Dart MCP: Launch App",mcp__dart__list_devices:"Dart MCP: List Devices",mcp__dart__list_running_apps:"Dart MCP: List Running Apps",mcp__dart__pub_dev_search:"Dart MCP: Pub Dev Search",mcp__dart__resolve_workspace_symbol:"Dart MCP: Resolve Workspace Symbol",mcp__dart__stop_app:"Dart MCP: Stop App",mcp_github_mcp_s2_add_issue_comment:"GitHub MCP (Remote): Add Issue Comment",mcp_github_mcp_s2_issue_read:"GitHub MCP (Remote): Issue Read",mcp_github_mcp_s2_issue_write:"GitHub MCP (Remote): Issue Write"};var Kn=Ui.pricing,ud=new Set(["VS Code","VS Code Insiders","VS Code Exploration","VS Code Server","VS Code Server (Insiders)","VSCodium","Visual Studio","JetBrains","Copilot CLI","Copilot CLI (App)","MS Scout (Copilot CLI)"]),u_=[["claude","Anthropic"],["anthropic","Anthropic"],["gemini","Google"],["google","Google"],["mistral","Mistral AI"],["codestral","Mistral AI"],["magistral","Mistral AI"],["ministral","Mistral AI"],["devstral","Mistral AI"],["pixtral","Mistral AI"],["gpt","OpenAI"],["o1","OpenAI"],["o3","OpenAI"],["o4","OpenAI"],["grok","xAI"],["raptor","xAI"],["goldeneye","xAI"],["qwen","Alibaba"],["mai-","Microsoft"]];function cd(o){return ud.has(o)?"copilot":"provider"}function d_(o){let e=o.toLowerCase(),t=u_.find(([s])=>e.startsWith(s));return t?t[1]:"Other"}function Da(o,e){return ud.has(o)?"GitHub Copilot":d_(e)}function lt(o){return o?o.actualTokens>0?o.actualTokens:o.tokens:0}function Ea(o){let e=Y(o);return e.includes("/.copilot/jb/")?"JetBrains":e.includes("/.copilot/session-store.db#")||e.includes("/.copilot/session-state/")?"Copilot CLI":e.includes("/.crush/crush.db#")?"Crush":e.includes("/saoudrizwan.claude-dev/tasks/")?"Cline":e.includes("/opencode/")?"OpenCode":e.includes("/.codex/")?"Codex CLI":e.includes("/.kiro/sessions/cli/")?"Kiro CLI":e.includes("/kiro.kiroagent/workspace-sessions/")?"Kiro":e.includes("/.continue/sessions/")?"Continue":e.includes("/local-agent-mode-sessions/")?"Claude Desktop Cowork":e.includes("/.claude/projects/")?Do(o):e.includes("/.vibe/logs/session/")?"Mistral Vibe":e.includes("/.gemini/antigravity/brain/")?"Antigravity":e.includes("/.gemini/tmp/")&&e.includes("/chats/session-")&&e.endsWith(".jsonl")?"Gemini CLI":e.includes("/cursor/")?"Cursor":e.includes("/code - insiders/")?"VS Code Insiders":e.includes("/code - exploration/")?"VS Code Exploration":e.includes("/vscodium/")?"VSCodium":e.includes(".vscode-server-insiders/")?"VS Code Server (Insiders)":e.includes(".vscode-server")?"VS Code Server":e.includes("/.vs/")&&e.includes("/copilot-chat/")?"Visual Studio":"VS Code"}async function Ra(o,e,t=20){if(o.length===0)return[];let s=new Array(o.length),n=0,i=Array.from({length:Math.min(t,o.length)},async()=>{for(;n<o.length;){let r=n++;try{s[r]=await e(o[r],r)}catch{s[r]=void 0}}});return await Promise.all(i),s}function Qn(){return{tokens:0,thinkingTokens:0,estimatedTokens:0,actualTokens:0,sessions:0,avgInteractionsPerSession:0,avgTokensPerSession:0,modelUsage:{},editorUsage:{},co2:0,treesEquivalent:0,waterUsage:0,estimatedCost:0}}function Yn(o,e,t){let s=Math.round(lt(e)*t),n=Math.round(e.thinkingTokens*t),i=Math.round(e.actualTokens*t);o.tokens+=s,o.thinkingTokens+=n,o.estimatedTokens+=Math.round(e.tokens*t),o.actualTokens+=i,o.sessions++;for(let[c,m]of Object.entries(e.modelUsage))o.modelUsage[c]||(o.modelUsage[c]={inputTokens:0,outputTokens:0}),o.modelUsage[c].inputTokens+=Math.round(m.inputTokens*t),o.modelUsage[c].outputTokens+=Math.round(m.outputTokens*t),m.cachedReadTokens!==void 0&&(o.modelUsage[c].cachedReadTokens=(o.modelUsage[c].cachedReadTokens??0)+Math.round(m.cachedReadTokens*t)),m.cacheCreationTokens!==void 0&&(o.modelUsage[c].cacheCreationTokens=(o.modelUsage[c].cacheCreationTokens??0)+Math.round(m.cacheCreationTokens*t));let r=Math.round(e.interactions*t),a=o.avgInteractionsPerSession*(o.sessions-1)+r;o.avgInteractionsPerSession=o.sessions>0?a/o.sessions:0,o.editorUsage[e.editorSource]||(o.editorUsage[e.editorSource]={tokens:0,sessions:0}),o.editorUsage[e.editorSource].tokens+=s,o.editorUsage[e.editorSource].sessions++}function gs(){return{sessions:0,toolCalls:{total:0,byTool:{}},modeUsage:{ask:0,edit:0,agent:0,plan:0,customAgent:0,cli:0},contextReferences:B(),mcpTools:{total:0,byServer:{},byTool:{}},modelSwitching:{modelsPerSession:[],totalSessions:0,averageModelsPerSession:0,maxModelsPerSession:0,minModelsPerSession:0,switchingFrequency:0,autoSessions:0,foundryWindowsSessions:0,unknownProviderSessions:0,selectedModelExtensions:[],unknownProviderModels:[],standardModels:[],premiumModels:[],lowCostModels:[],mediumCostModels:[],highCostModels:[],unknownModels:[],mixedTierSessions:0,mixedCostSessions:0,standardRequests:0,premiumRequests:0,unknownRequests:0,totalRequests:0,lowCostRequests:0,mediumCostRequests:0,highCostRequests:0},repositories:[],repositoriesWithCustomization:[],editScope:{singleFileEdits:0,multiFileEdits:0,totalEditedFiles:0,avgFilesPerSession:0},applyUsage:{totalApplies:0,totalCodeBlocks:0,applyRate:0},sessionDuration:{totalDurationMs:0,avgDurationMs:0,avgFirstProgressMs:0,avgTotalElapsedMs:0,avgWaitTimeMs:0,activeDurationMs:0},conversationPatterns:{multiTurnSessions:0,singleTurnSessions:0,avgTurnsPerSession:0,maxTurnsInSession:0},agentTypes:{editsAgent:0,defaultAgent:0,workspaceAgent:0,other:0}}}var $t=[{bg:"rgba(54, 162, 235, 0.6)",border:"rgba(54, 162, 235, 1)"},{bg:"rgba(255, 99, 132, 0.6)",border:"rgba(255, 99, 132, 1)"},{bg:"rgba(75, 192, 192, 0.6)",border:"rgba(75, 192, 192, 1)"},{bg:"rgba(153, 102, 255, 0.6)",border:"rgba(153, 102, 255, 1)"},{bg:"rgba(255, 159, 64, 0.6)",border:"rgba(255, 159, 64, 1)"},{bg:"rgba(255, 205, 86, 0.6)",border:"rgba(255, 205, 86, 1)"},{bg:"rgba(201, 203, 207, 0.6)",border:"rgba(201, 203, 207, 1)"},{bg:"rgba(100, 181, 246, 0.6)",border:"rgba(100, 181, 246, 1)"}];function Xn(o,e,t){if(!o||!e)throw new Error("buildChartPayload: labels and days are required");if(o.length!==e.length)throw new Error(`buildChartPayload: labels.length (${o.length}) !== days.length (${e.length})`);let s=P=>`${P.getFullYear()}-${String(P.getMonth()+1).padStart(2,"0")}-${String(P.getDate()).padStart(2,"0")}`,n=P=>{let x=P.map(U=>U.entry),N=P.map(U=>U.label),re=x.map(U=>U.tokens),ne=x.map(U=>U.sessions),se=new Set;x.forEach(U=>Object.keys(U.modelUsage).forEach(V=>se.add(V)));let Ws=Array.from(se).map((U,V)=>{let _e=$t[V%$t.length];return{label:U,data:x.map(be=>{let ae=be.modelUsage[U];return ae?ae.inputTokens+ae.outputTokens:0}),backgroundColor:_e.bg,borderColor:_e.border,borderWidth:1}}),hs=new Set;x.forEach(U=>Object.keys(U.editorUsage).forEach(V=>hs.add(V)));let Oe=Array.from(hs).map((U,V)=>{let _e=$t[V%$t.length];return{label:U,data:x.map(be=>be.editorUsage[U]?.tokens||0),backgroundColor:_e.bg,borderColor:_e.border,borderWidth:1}}),Hs=re.reduce((U,V)=>U+V,0),Et=ne.reduce((U,V)=>U+V,0),Ct=P.length,to=x.map(U=>ot(U.modelUsage,Kn,"copilot")),so=to.reduce((U,V)=>U+V,0),Yi=Ct>0?so/Ct:0,Kt=new Set;x.forEach(U=>{U.editorModelUsage&&Object.keys(U.editorModelUsage).forEach(V=>Kt.add(V))});let ys=new Map;for(let U of Kt){let V=x.reduce((_e,be)=>_e+ot(be.editorModelUsage?.[U]??{},Kn,cd(U)),0);ys.set(U,V)}let no=Array.from(Kt).sort((U,V)=>(ys.get(V)||0)-(ys.get(U)||0)).map((U,V)=>{let _e=$t[V%$t.length];return{label:U,data:x.map(be=>ot(be.editorModelUsage?.[U]??{},Kn,cd(U))),backgroundColor:_e.bg,borderColor:_e.border,borderWidth:1}}),Js=new Set;x.forEach(U=>{if(U.editorModelUsage)for(let[V,_e]of Object.entries(U.editorModelUsage))for(let be of Object.keys(_e))Js.add(Da(V,be))});let Ye=new Map;for(let U of Js)Ye.set(U,x.reduce((V,_e)=>{if(!_e.editorModelUsage)return V;let be={};for(let[ut,Qt]of Object.entries(_e.editorModelUsage))for(let[dt,Fe]of Object.entries(Qt))Da(ut,dt)===U&&(be[dt]||(be[dt]={inputTokens:0,outputTokens:0}),be[dt].inputTokens+=Fe.inputTokens,be[dt].outputTokens+=Fe.outputTokens);return V+ot(be,Kn,U==="GitHub Copilot"?"copilot":"provider")},0));let Xe=Array.from(Js).sort((U,V)=>(Ye.get(V)||0)-(Ye.get(U)||0)).map((U,V)=>{let _e=$t[V%$t.length],be=U==="GitHub Copilot"?"copilot":"provider";return{label:U,data:x.map(ae=>{if(!ae.editorModelUsage)return 0;let ut={};for(let[Qt,dt]of Object.entries(ae.editorModelUsage))for(let[Fe,oo]of Object.entries(dt))Da(Qt,Fe)===U&&(ut[Fe]||(ut[Fe]={inputTokens:0,outputTokens:0}),ut[Fe].inputTokens+=oo.inputTokens,ut[Fe].outputTokens+=oo.outputTokens);return ot(ut,Kn,be)}),backgroundColor:_e.bg,borderColor:_e.border,borderWidth:1}});return{labels:N,tokensData:re,sessionsData:ne,modelDatasets:Ws,editorDatasets:Oe,repositoryDatasets:[],periodCount:Ct,totalTokens:Hs,totalSessions:Et,avgPerPeriod:Ct>0?Math.round(Hs/Ct):0,costData:to,totalCost:so,avgCostPerPeriod:Yi,editorCostDatasets:no,billingGroupCostDatasets:Xe}},i=(P,x)=>{P.tokens+=x.tokens,P.sessions+=x.sessions;for(let[N,re]of Object.entries(x.modelUsage))P.modelUsage[N]||(P.modelUsage[N]={inputTokens:0,outputTokens:0}),P.modelUsage[N].inputTokens+=re.inputTokens,P.modelUsage[N].outputTokens+=re.outputTokens,re.cachedReadTokens!==void 0&&(P.modelUsage[N].cachedReadTokens=(P.modelUsage[N].cachedReadTokens??0)+re.cachedReadTokens),re.cacheCreationTokens!==void 0&&(P.modelUsage[N].cacheCreationTokens=(P.modelUsage[N].cacheCreationTokens??0)+re.cacheCreationTokens);for(let[N,re]of Object.entries(x.editorUsage))P.editorUsage[N]||(P.editorUsage[N]={tokens:0,sessions:0}),P.editorUsage[N].tokens+=re.tokens,P.editorUsage[N].sessions+=re.sessions;if(x.editorModelUsage){P.editorModelUsage||(P.editorModelUsage={});for(let[N,re]of Object.entries(x.editorModelUsage)){P.editorModelUsage[N]||(P.editorModelUsage[N]={});for(let[ne,se]of Object.entries(re))P.editorModelUsage[N][ne]||(P.editorModelUsage[N][ne]={inputTokens:0,outputTokens:0}),P.editorModelUsage[N][ne].inputTokens+=se.inputTokens,P.editorModelUsage[N][ne].outputTokens+=se.outputTokens}}},r=()=>({tokens:0,sessions:0,modelUsage:{},editorUsage:{}}),a=new Date,c=o.map((P,x)=>({label:P,entry:e[x]})),m=n(c),p=P=>{let x=new Date(P);x.setHours(0,0,0,0);let N=x.getDay();return x.setDate(x.getDate()-(N===0?6:N-1)),x},f=P=>{let x=new Date(P);return x.setDate(P.getDate()+6),P.getMonth()===x.getMonth()?`${P.toLocaleDateString("en-US",{month:"short"})} ${P.getDate()}\u2013${x.getDate()}`:`${P.toLocaleDateString("en-US",{month:"short",day:"numeric"})}\u2013${x.toLocaleDateString("en-US",{month:"short",day:"numeric"})}`},h=p(a),_=new Map;for(let P=5;P>=0;P--){let x=new Date(h);x.setDate(h.getDate()-P*7);let N=s(x);_.set(N,{label:f(x),entry:r()})}let C=t||new Map(o.map((P,x)=>[P,e[x]]));for(let[P,x]of C.entries()){let N=p(new Date(P+"T00:00:00")),re=_.get(s(N));re&&i(re.entry,x)}let S=Array.from(_.values()),E=n(S),A=new Map;for(let P=11;P>=0;P--){let x=new Date(a.getFullYear(),a.getMonth()-P,1),N=`${x.getFullYear()}-${String(x.getMonth()+1).padStart(2,"0")}`,re=x.toLocaleDateString("en-US",{month:"short",year:"numeric"});A.set(N,{label:re,entry:r()})}for(let[P,x]of C.entries()){let N=P.slice(0,7),re=A.get(N);re&&i(re.entry,x)}let R=Array.from(A.values()),q=n(R),F={};return e.forEach(P=>{Object.entries(P.editorUsage).forEach(([x,N])=>{F[x]=(F[x]||0)+N.tokens})}),{labels:m.labels,tokensData:m.tokensData,sessionsData:m.sessionsData,modelDatasets:m.modelDatasets,editorDatasets:m.editorDatasets,editorTotalsMap:F,repositoryDatasets:[],repositoryTotalsMap:{},dailyCount:m.periodCount,totalTokens:m.totalTokens,avgTokensPerDay:m.periodCount>0?Math.round(m.totalTokens/m.periodCount):0,totalSessions:m.totalSessions,lastUpdated:new Date().toISOString(),backendConfigured:!1,periodsReady:!0,periods:{day:m,week:E,month:q}}}function Z(o){return o==null||!Number.isFinite(o)?"0":Math.round(o).toLocaleString("en-US")}function he(o){return o==null||!Number.isFinite(o)||o<0?"0":o>=1e9?`${(o/1e9).toFixed(1)}B`:o>=1e6?`${(o/1e6).toFixed(1)}M`:o>=1e3?`${(o/1e3).toFixed(1)}K`:o.toString()}var Fi=ad.estimators,Wt=Ui.pricing,m_=ld,p_=o=>{},Ia=o=>{},md=(o,e)=>{let t=e instanceof Error?e.message:e!==void 0?String(e):"";console.error(T.red(o),t)};async function g_(o){try{let e=await Dt.promises.readFile(o,"utf-8");return JSON.parse(e)}catch(e){return e?.code!=="ENOENT"&&md(`[readJsonFile] Failed to read or parse JSON at ${o}:`,e),null}}var Oi=null;function Zn(){if(Oi)return Oi;let o=Mo.file(__dirname);return Oi=_a({...ya(o),estimateTokens:(e,t)=>X(e,t??"gpt-4",Fi),isMcpTool:st,extractMcpServerName:ft}),Oi}function pd(){return new Eo({log:p_,warn:Ia,error:md,ecosystems:Zn()})}async function ke(){return pd().getCopilotSessionFiles()}async function Ni(o){let e=new Set,t=ve.join(dd.homedir(),".claude","projects");for(let n of o){if(n.startsWith(t+ve.sep)||n.startsWith(t+"/")){let f=await ns(()=>Dt.promises.readFile(n,"utf-8"),null,`buildCustomizationMatrix readFile(${n})`);if(f!==null){let h=f.split(`
|
|
145
|
-
`).slice(0,30);for(let _ of h)if(_.trim())try{let C=JSON.parse(_);if(C.cwd&&typeof C.cwd=="string"){e.add(C.cwd);break}}catch{}}continue}let i=ve.dirname(n);if(ve.basename(i)!=="chatSessions")continue;let r=ve.dirname(i),a=ve.join(r,"workspace.json"),c=await g_(a);if(!c)continue;let m=c.folder;if(!m||!m.startsWith("file://"))continue;let p=Po(m);p&&e.add(p)}if(e.size===0)return;let s=0;for(let n of e)await ns(async()=>{let[r,a,c]=await Promise.all([Dt.promises.access(ve.join(n,".github","copilot-instructions.md")).then(()=>!0).catch(()=>!1),Dt.promises.access(ve.join(n,"agents.md")).then(()=>!0).catch(()=>!1),Dt.promises.access(ve.join(n,"CLAUDE.md")).then(()=>!0).catch(()=>!1)]);return!r&&!a&&!c},!0,`buildCustomizationMatrix workspace check(${n})`)&&s++;return{customizationTypes:[],workspaces:[],totalWorkspaces:e.size,workspacesWithIssues:s}}function Li(){return pd().getDiagnosticCandidatePaths()}function f_(o,e){return X(o,e||"gpt-4",Fi)}function h_(o){return Nt(o,Wt)}async function gd(o){let e=Zn().find(t=>t.handles(o));return e?e.stat(o):Dt.promises.stat(o)}async function y_(o,e=!1){let t=ve.basename(o,ve.extname(o));if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return null;let n=o.replace(/\\/g,"/").match(/^(.*\/workspaceStorage\/[^/]+)\//);if(!n)return null;let r=n[1].replace(/\//g,"\\"),a=["GitHub.copilot-chat","github.copilot-chat","GitHub.copilot","github.copilot"];for(let c of a){let m=ve.join(r,c,"debug-logs",t,"main.jsonl");try{let p=await Dt.promises.readFile(m,"utf8"),f=Kl(p);if(f)return e&&console.error(` \u2713 Found debug log: ${t} (tokens: ${f.inputTokens+f.outputTokens})`),f}catch{}}return e&&console.error(` \u2717 No debug log found: ${t}`),null}async function fs(o,e=!1){try{let t=await gd(o),s=rd(o,t.mtimeMs,t.size);if(s)return s;let n=Zn().find(S=>S.handles(o));if(n){let[S,E,A]=await Promise.all([n.getTokens(o),n.countInteractions(o),n.getModelUsage(o)]),R=L(t.mtime),q={file:o,tokens:S.actualTokens>0?S.actualTokens:S.tokens,thinkingTokens:S.thinkingTokens,actualTokens:S.actualTokens,interactions:E,modelUsage:A,lastModified:t.mtime,editorSource:Ea(o),dailyFractions:await n.getDailyFractions?.(o)??{[R]:1}};return Aa(o,t.mtimeMs,t.size,q),q}let i=await Dt.promises.readFile(o,"utf-8");if(!i.trim())return null;let r=o.endsWith(".jsonl")||bt(i),a=0,c=0,m=0,p=0,f={};if(r){let S=Ls(o)?await ms(o):null,E=Lo(i,S);if(a=E.actualTokens>0?E.actualTokens:E.tokens,c=E.thinkingTokens,m=E.actualTokens,f=await ua({warn:Ia,tokenEstimators:Fi,modelPricing:Wt,ecosystems:Zn()},o,i),Object.keys(f).length===0&&hi(o)){let R=wi(i);Object.keys(R.modelUsage).length>0?f=R.modelUsage:R.tokens>0&&(f={[R.modelHint&&R.modelHint!=="unknown"?R.modelHint:"unknown"]:{inputTokens:R.tokens,outputTokens:0}})}f=su(f,m||a);let A=i.trim().split(`
|
|
146
|
-
`);for(let
|
|
156
|
+
`)}async buildTurns(e){let t=await this.cursor.readComposerData(e);if(!t?.fullConversationHeadersOnly)return{turns:[]};let s=t.fullConversationHeadersOnly,n=typeof t.contextTokensUsed=="number"?t.contextTokensUsed:0,i=t.modelConfig?.modelName||null,r=s.map(p=>p.bubbleId).filter(p=>!!p),a=await this.cursor.readBubbles(e,r),c=[],d=0;for(let p=0;p<s.length;p++){let f=s[p];if(f.type!==1)continue;d++;let h=f.bubbleId?a.get(f.bubbleId):void 0;c.push({turnNumber:d,timestamp:h?.createdAt??null,mode:"agent",userMessage:h?.text??"",assistantResponse:this.collectAssistantText(s,p+1,a),model:i,toolCalls:[],contextReferences:G(),mcpTools:[],inputTokensEstimate:0,outputTokensEstimate:0,thinkingTokensEstimate:0})}return{turns:c,actualTokens:n}}async getSyncData(e){return this.cursor.getSessionData(e)}async analyzeUsage(e,t){let s=H(),n=await this.cursor.readComposerData(e);if(!n?.fullConversationHeadersOnly)return s;let i=n.modelConfig?.modelName||"unknown",r=n.fullConversationHeadersOnly,a=r.filter(p=>p.type===1).length,c=r.filter(p=>p.type===2).length;s.modeUsage.agent+=a,c>0&&(s.modelSwitching.uniqueModels=[i],s.modelSwitching.modelCount=1,s.modelSwitching.totalRequests=c,s.modelSwitching.switchCount=0);let d=Array(c).fill(i);return Q(t.modelPricing,[i],d,s),s}};var js=S(require("fs")),Ae=S(require("path")),Sa=S(require("os"));function ka(){return Ae.join(Sa.homedir(),".copilot","session-state")}var Wn=class{id="copilotcli";displayName="Copilot CLI";store=new Fs;_scoutSessionIds=new Set;_appSessionIds=new Set;getDisplayName(e){let t=this.store.getSessionId(e),s=Ae.basename(Ae.dirname(e));return t&&this._scoutSessionIds.has(t)||s&&this._scoutSessionIds.has(s)?"MS Scout (Copilot CLI)":t&&this._appSessionIds.has(t)||s&&this._appSessionIds.has(s)?"Copilot CLI (App)":"Copilot CLI"}getDisplayNameForDiscoveredPath(e){let t=Ae.basename(Ae.dirname(e));if(t&&this._scoutSessionIds.has(t))return"MS Scout (Copilot CLI)";if(t&&this._appSessionIds.has(t))return"Copilot CLI (App)"}async getWorkspacePathForDiscoveredPath(e){let t=Ae.join(Ae.dirname(e),"workspace.yaml");try{return(await js.promises.readFile(t,"utf8")).match(/^cwd:\s*(.+)$/m)?.[1]?.trim()||void 0}catch{return}}handles(e){return this.store.isCliStoreSession(e)}getBackingPath(e){return this.store.isCliStoreSession(e)?this.store.getDbPathFromVirtual(e):e}async stat(e){return this.store.isCliStoreSession(e)?this.store.stat(e):js.promises.stat(e)}async getTokens(e){let t=await ms(e);return t?{tokens:t.actualTokens,thinkingTokens:0,actualTokens:t.actualTokens,cacheReadTokens:t.cacheReadTokens}:{tokens:0,thinkingTokens:0,actualTokens:0}}async countInteractions(e){return this.store.isCliStoreSession(e)?this.store.countTurns(e):0}async getModelUsage(e){return(await ms(e))?.modelUsage??{}}async getMeta(e){if(this.store.isCliStoreSession(e)){let t=await this.store.readSession(e);return t?{title:t.summary??void 0,firstInteraction:t.created_at,lastInteraction:t.updated_at,workspacePath:t.cwd??void 0,repository:t.repository??void 0}:{title:void 0,firstInteraction:null,lastInteraction:null}}return{title:void 0,firstInteraction:null,lastInteraction:null}}getEditorRoot(e){return this.store.isCliStoreSession(e)?Ae.join(Sa.homedir(),".copilot"):ka()}async buildTurns(e){return this.store.isCliStoreSession(e)?{turns:(await this.store.getTurns(e)).map(n=>({turnNumber:n.turn_index+1,timestamp:n.timestamp,mode:"cli",userMessage:n.user_message??"",assistantResponse:n.assistant_response??"",model:null,toolCalls:[],contextReferences:G(),mcpTools:[],inputTokensEstimate:0,outputTokensEstimate:0,thinkingTokensEstimate:0}))}:{turns:[]}}async analyzeUsage(e,t){let s=H();if(!this.store.isCliStoreSession(e))return s;let n=await this.store.getTurns(e);return s.modeUsage.cli=n.filter(i=>i.user_message!==null).length,s}async getDailyFractions(e){return this.store.isCliStoreSession(e)?this.store.getDailyFractions(e):{}}async _tryMarkScoutFromWorkspaceYaml(e,t){let s=Ae.join(e,"workspace.yaml");try{let n=await js.promises.readFile(s,"utf8"),i=n.match(/^cwd:\s*(.+)$/m);i&&aa(i[1].trim())&&this._scoutSessionIds.add(t);let r=n.match(/^client_name:\s*(.+)$/m);r&&iu(r[1].trim())&&this._appSessionIds.add(t)}catch{}}getCandidatePaths(){let e=[{path:ka(),source:"Copilot CLI"}],t=this.store.getDbPath();return e.push({path:t,source:"Copilot CLI (session-store.db)"}),e}async discover(e){let t=this.getCandidatePaths(),s=[],n=ka(),i=new Set;try{if(await Mt(n)){let r;try{r=await js.promises.readdir(n,{withFileTypes:!0})}catch(p){e(`Could not read Copilot CLI session path in ${n}: ${p}`),r=[]}let a=r.filter(p=>!p.isDirectory()&&(p.name.endsWith(".json")||p.name.endsWith(".jsonl"))).map(p=>Ae.join(n,p.name));a.length>0&&(e(`\u{1F4C4} Found ${a.length} session files in Copilot CLI directory`),s.push(...a));let c=r.filter(p=>p.isDirectory()),d=(await Promise.all(c.map(async p=>{let f=Ae.join(n,p.name),h=Ae.join(f,"events.jsonl");try{if((await js.promises.stat(h)).size>0)return i.add(p.name),await this._tryMarkScoutFromWorkspaceYaml(f,p.name),h}catch{}return null}))).filter(p=>p!==null);d.length>0&&(e(`\u{1F4C4} Found ${d.length} session files in Copilot CLI subdirectories`),s.push(...d))}}catch(r){e(`Could not check Copilot CLI session path ${n}: ${r}`)}try{let r=await this.store.discoverNewSessionsWithCwd(i);if(r.length>0){e(`\u{1F4C4} Found ${r.length} chat-only session(s) in Copilot CLI session-store.db`),await Promise.all(r.map(async({id:a,cwd:c})=>{aa(c)&&this._scoutSessionIds.add(a),await this._tryMarkScoutFromWorkspaceYaml(Ae.join(n,a),a)}));for(let{id:a}of r)s.push(this.store.virtualPath(a))}}catch(r){e(`Could not read Copilot CLI session-store.db: ${r}`)}return{sessionFiles:s,candidatePaths:t}}};var Gs=S(require("fs")),Fi=S(require("path")),nd=S(require("os"));function Ta(){return Fi.join(nd.homedir(),".copilot","jb")}var Jn=class{id="jetbrains";displayName="JetBrains IDE";handles(e){return!1}getBackingPath(e){return e}async stat(e){return Gs.promises.stat(e)}async parsePartition(e){try{let t=await Gs.promises.readFile(e,"utf8");return xi(t)}catch{return null}}async getTokens(e){let t=await this.parsePartition(e);return t?{tokens:t.tokens,thinkingTokens:t.thinkingTokens,actualTokens:t.actualTokens}:{tokens:0,thinkingTokens:0,actualTokens:0}}async countInteractions(e){return(await this.parsePartition(e))?.interactions??0}async getModelUsage(e){return(await this.parsePartition(e))?.modelUsage??{}}async getMeta(e){let t=await this.parsePartition(e);return{title:void 0,firstInteraction:t?.firstInteraction??null,lastInteraction:t?.lastInteraction??null}}async getToolCounts(e){return(await this.parsePartition(e))?.toolCounts??{}}async getToolCalls(e){return(await this.parsePartition(e))?.toolCalls??[]}async getTurns(e){return(await this.parsePartition(e))?.turns??[]}async getMessageIds(e){return(await this.parsePartition(e))?.messageIds??[]}async getTurnStatusCounts(e){return(await this.parsePartition(e))?.turnStatusCounts??{success:0,cancelled:0,failed:0,unknown:0}}async hasThinking(e){return(await this.parsePartition(e))?.hasThinking??!1}getEditorRoot(e){return Ta()}getCandidatePaths(){return[{path:Ta(),source:"JetBrains IDE"}]}async discover(e){let t=this.getCandidatePaths(),s=[],n=Ta();try{if(!await Mt(n))return{sessionFiles:s,candidatePaths:t};let i;try{i=await Gs.promises.readdir(n,{withFileTypes:!0})}catch(c){return e(`Could not read JetBrains session path in ${n}: ${c}`),{sessionFiles:s,candidatePaths:t}}let r=i.filter(c=>c.isDirectory()),a=(await Promise.all(r.map(async c=>{let d=Fi.join(n,c.name),p;try{p=await Gs.promises.readdir(d,{withFileTypes:!0})}catch{return[]}let f=[];for(let h of p){if(!h.isFile()||!/^partition-\d+\.jsonl$/.test(h.name))continue;let _=Fi.join(d,h.name);try{(await Gs.promises.stat(_)).size>0&&f.push(_)}catch{}}return f}))).flat();a.length>0&&(e(`\u{1F4C4} Found ${a.length} session file(s) in JetBrains IDE Copilot`),s.push(...a))}catch(i){e(`Could not check JetBrains session path ${n}: ${i}`)}return{sessionFiles:s,candidatePaths:t}}};var od=S(require("fs"));var Vn=class{constructor(e){this.kiro=e}kiro;id="kiro";displayName="Kiro";handles(e){return this.kiro.isKiroSessionFile(e)}getBackingPath(e){return e}async stat(e){return od.promises.stat(e)}async getTokens(e){let t=await this.kiro.getTokensFromKiroSession(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return await this.kiro.countKiroInteractions(e)}async getModelUsage(e){return await this.kiro.getKiroModelUsage(e)}async getMeta(e){return await this.kiro.getKiroSessionMeta(e)}getEditorRoot(e){return this.kiro.getKiroAppDataDir()}async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=await this.kiro.getKiroSessionFiles();n.length>0&&(e(`\u{1F4C4} Found ${n.length} session file(s) in Kiro (kiro.kiroagent/workspace-sessions)`),s.push(...n))}catch(n){e(`Could not read Kiro session files: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.kiro.getKiroWorkspaceSessionsDir(),source:"Kiro"}]}async buildTurns(e){let t=await this.kiro.buildKiroTurns(e),s=G();return{turns:t.map((i,r)=>({turnNumber:r+1,timestamp:i.timestampMs!==null?new Date(i.timestampMs).toISOString():null,mode:"agent",userMessage:i.userText,assistantResponse:i.assistantText,model:i.model,toolCalls:i.toolCalls,contextReferences:s,mcpTools:[],inputTokensEstimate:i.inputTokens,outputTokensEstimate:i.outputTokens,thinkingTokensEstimate:0}))}}async getDailyFractions(e){return await this.kiro.getKiroDailyFractions(e)}async analyzeUsage(e,t){let s=H(),n=await this.kiro.buildKiroTurns(e),i=[];for(let c of n){s.modeUsage.agent++,c.model&&i.push(c.model);for(let d of c.toolCalls)s.toolCalls.total++,s.toolCalls.byTool[d.toolName]=(s.toolCalls.byTool[d.toolName]||0)+1}let r=[...new Set(i)];s.modelSwitching.uniqueModels=r,s.modelSwitching.modelCount=r.length,s.modelSwitching.totalRequests=i.length;let a=0;for(let c=1;c<i.length;c++)i[c]!==i[c-1]&&a++;return s.modelSwitching.switchCount=a,Q(t.modelPricing,r,i,s),s}};var id=S(require("fs"));var Kn=class{constructor(e){this.kiroCli=e}kiroCli;id="kirocli";displayName="Kiro CLI";handles(e){return this.kiroCli.isKiroCliSessionFile(e)}getBackingPath(e){return e}async stat(e){return id.promises.stat(e)}async getTokens(e){let t=await this.kiroCli.getTokensFromKiroCliSession(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return await this.kiroCli.countKiroCliInteractions(e)}async getModelUsage(e){return await this.kiroCli.getKiroCliModelUsage(e)}async getMeta(e){return await this.kiroCli.getKiroCliSessionMeta(e)}getEditorRoot(e){return this.kiroCli.getKiroCliDataDir()}async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=await this.kiroCli.getKiroCliSessionFiles();n.length>0&&(e(`\u{1F4C4} Found ${n.length} session file(s) in Kiro CLI (~/.kiro/sessions/cli)`),s.push(...n))}catch(n){e(`Could not read Kiro CLI session files: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.kiroCli.getKiroCliSessionsDir(),source:"Kiro CLI"}]}async buildTurns(e){let t=await this.kiroCli.buildKiroCliTurns(e),s=G(),i=(await this.kiroCli.readSessionMetadata(e))?.modelId||null;return{turns:t.map((a,c)=>({turnNumber:c+1,timestamp:a.timestampMs!==null?new Date(a.timestampMs).toISOString():null,mode:"cli",userMessage:a.userText,assistantResponse:a.assistantText,model:i,toolCalls:a.toolCalls,contextReferences:s,mcpTools:[],inputTokensEstimate:a.inputTokens,outputTokensEstimate:a.outputTokens,thinkingTokensEstimate:0}))}}async getDailyFractions(e){return await this.kiroCli.getKiroCliDailyFractions(e)}async analyzeUsage(e,t){let s=H(),n=await this.kiroCli.buildKiroCliTurns(e),r=(await this.kiroCli.readSessionMetadata(e))?.modelId||"unknown",a=[];for(let d of n){s.modeUsage.cli++,a.push(r);for(let p of d.toolCalls)s.toolCalls.total++,s.toolCalls.byTool[p.toolName]=(s.toolCalls.byTool[p.toolName]||0)+1}let c=[...new Set(a)];return s.modelSwitching.uniqueModels=c,s.modelSwitching.modelCount=c.length,s.modelSwitching.totalRequests=a.length,s.modelSwitching.switchCount=0,Q(t.modelPricing,c,a,s),s}};var rd=S(require("fs")),ad=S(require("path"));var Ni=class{constructor(e){this.devinCli=e}devinCli;id="devincli";displayName="Devin CLI";handles(e){return this.devinCli.isDevinCliSessionFile(e)}getBackingPath(e){return this.devinCli.getDbPathFromVirtual(e)}async stat(e){return this.devinCli.statSessionFile(e)}async getTokens(e){let t=await this.devinCli.getTokens(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return this.devinCli.countInteractions(e)}async getModelUsage(e){return this.devinCli.getModelUsage(e)}async getMeta(e){let t=await this.devinCli.readSession(e),s=await this.devinCli.getMessageNodes(e),n=[];t?.created_at&&n.push(t.created_at*1e3),t?.last_activity_at&&n.push(t.last_activity_at*1e3);for(let i of s)i.created_at&&n.push(i.created_at*1e3);return n.sort((i,r)=>i-r),{title:t?.title||void 0,firstInteraction:n.length>0?new Date(n[0]).toISOString():null,lastInteraction:n.length>0?new Date(n[n.length-1]).toISOString():null,workspacePath:t?.working_directory||void 0}}getEditorRoot(e){return ad.dirname(this.devinCli.getDbPathFromVirtual(e))}async discover(e){let t=this.getCandidatePaths(),s=[],n=this.devinCli.getDbPath();e(`\u{1F4C1} Checking Devin CLI DB path: ${n}`);try{await rd.promises.access(n);let i=await this.devinCli.discoverSessionIds();i.length>0&&e(`\u{1F4C4} Found ${i.length} session(s) in Devin CLI database`),s.push(...i.map(r=>this.devinCli.virtualPath(r)))}catch(i){e(`Could not read Devin CLI database: ${i}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.devinCli.getDbPath(),source:"Devin CLI (sessions.db)"}]}async buildTurns(e){let t=[],s=await this.devinCli.readSession(e),n=await this.devinCli.getMessageNodes(e),i=this.devinCli.buildMainChain(n,s?.main_chain_id??null),r=0;for(let a=0;a<i.length;a++){let c=this.devinCli.parseChatMessage(i[a].chat_message);c.role==="user"&&(r++,t.push(this.buildDevinCliTurn(i,a,c.text,s,r)))}return{turns:t}}buildDevinCliTurn(e,t,s,n,i){let r="";for(let c=t+1;c<e.length;c++){let d=this.devinCli.parseChatMessage(e[c].chat_message);if(d.role==="user")break;d.role==="assistant"&&(r+=(r?`
|
|
157
|
+
`:"")+d.text)}let a=e[t];return{turnNumber:i,timestamp:a.created_at?new Date(a.created_at*1e3).toISOString():null,mode:"cli",userMessage:s,assistantResponse:r,model:n?.model||null,toolCalls:[],contextReferences:G(),mcpTools:[],inputTokensEstimate:Math.ceil(s.length/4),outputTokensEstimate:Math.ceil(r.length/4),thinkingTokensEstimate:0}}async getDailyFractions(e){return this.devinCli.getDailyFractions(e)}async analyzeUsage(e,t){let s=H(),n=await this.devinCli.readSession(e),i=await this.devinCli.getMessageNodes(e),r=this.devinCli.buildMainChain(i,n?.main_chain_id??null),a=await this.devinCli.getToolCalls(e),c=n?.model||"unknown",d=[];for(let f of r)this.devinCli.parseChatMessage(f.chat_message).role==="user"&&(s.modeUsage.cli++,d.push(c));s.toolCalls.total=a.length;for(let f of a){let h=this.extractToolName(f.tool_call_json);s.toolCalls.byTool[h]=(s.toolCalls.byTool[h]||0)+1}let p=[...new Set(d)];return s.modelSwitching.uniqueModels=p,s.modelSwitching.modelCount=p.length,s.modelSwitching.totalRequests=d.length,Q(t.modelPricing,p,d,s),s}extractToolName(e){if(!e)return"unknown";try{let t=JSON.parse(e),s=t.title??t.name??t.kind;return typeof s=="string"&&s?s:"unknown"}catch{return"unknown"}}};var ld=S(require("fs"));var Li=class{constructor(e){this.cline=e}cline;id="cline";displayName="Cline";handles(e){return this.cline.isClineSessionFile(e)}getBackingPath(e){return e}async stat(e){return ld.promises.stat(e)}async getTokens(e){let t=await this.cline.getTokensFromClineSession(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return await this.cline.countClineInteractions(e)}async getModelUsage(e){return await this.cline.getClineModelUsage(e)}async getMeta(e){return await this.cline.getClineSessionMeta(e)}getEditorRoot(e){return this.cline.getClineRootFromSessionFile(e)}async discover(e){let t=this.getCandidatePaths(),s=[];try{let n=await this.cline.getClineSessionFiles();n.length>0&&(e(`\u{1F4C4} Found ${n.length} session file(s) in Cline (saoudrizwan.claude-dev/tasks)`),s.push(...n))}catch(n){e(`Could not read Cline session files: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return this.cline.getClineTasksDirs().map(e=>({path:e,source:"Cline"}))}async buildTurns(e){let t=await this.cline.buildClineTurns(e),s=await this.cline.getTokensFromClineSession(e),n=G();return{turns:t.map((r,a)=>({turnNumber:a+1,timestamp:r.timestampMs!==null?new Date(r.timestampMs).toISOString():null,mode:this.toChatMode(r),userMessage:r.userText,assistantResponse:r.assistantText,model:r.model,toolCalls:r.toolCalls,contextReferences:n,mcpTools:r.mcpTools,inputTokensEstimate:r.inputTokens,outputTokensEstimate:r.outputTokens,thinkingTokensEstimate:0,actualUsage:r.inputTokens>0||r.outputTokens>0?{promptTokens:r.inputTokens,completionTokens:r.outputTokens}:void 0})),actualTokens:s.tokens}}toChatMode(e){return e.mode==="plan"?"plan":"agent"}async getDailyFractions(e){return await this.cline.getClineDailyFractions(e)}async analyzeUsage(e,t){let s=H(),n=await this.cline.buildClineTurns(e);for(let d of n){d.mode==="plan"?s.modeUsage.plan++:s.modeUsage.agent++;for(let p of d.toolCalls)s.toolCalls.total++,s.toolCalls.byTool[p.toolName]=(s.toolCalls.byTool[p.toolName]||0)+1;for(let p of d.mcpTools)s.mcpTools.total++,s.mcpTools.byServer[p.server]=(s.mcpTools.byServer[p.server]||0)+1,s.mcpTools.byTool[p.tool]=(s.mcpTools.byTool[p.tool]||0)+1}let r=(await this.cline.getApiRequests(e)).map(d=>d.model).filter(d=>!!d),a=[...new Set(r)];s.modelSwitching.uniqueModels=a,s.modelSwitching.modelCount=a.length,s.modelSwitching.totalRequests=r.length;let c=0;for(let d=1;d<r.length;d++)r[d]!==r[d-1]&&c++;return s.modelSwitching.switchCount=c,Q(t.modelPricing,a,r,s),s}};var Qn=class{constructor(e){this.codexCli=e}codexCli;id="codexcli";displayName="Codex CLI";handles(e){return this.codexCli.isCodexCliSessionFile(e)}getBackingPath(e){return this.codexCli.getBackingPath(e)}async stat(e){return this.codexCli.statSessionFile(e)}async getTokens(e){let t=await this.codexCli.getTokens(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return this.codexCli.countInteractions(e)}async getModelUsage(e){return this.codexCli.getModelUsage(e)}async getMeta(e){return this.codexCli.getMeta(e)}getEditorRoot(e){return this.codexCli.getCodexHome()}async discover(e){let t=this.getCandidatePaths(),s=[];try{let{files:n,rolloutCount:i,dbOnlyCount:r}=await this.codexCli.discoverSessions();n.length>0&&e(`\u{1F4C4} Found ${n.length} Codex CLI session(s) (${i} rollout file(s), ${r} DB-only thread(s))`),s.push(...n)}catch(n){e(`Could not read Codex CLI sessions: ${n}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.codexCli.getSessionsDir(),source:"Codex CLI (sessions)"},{path:this.codexCli.getArchivedSessionsDir(),source:"Codex CLI (archived sessions)"},{path:this.codexCli.getStateDbPath(),source:"Codex CLI (state db)"}]}async getDailyFractions(e){return this.codexCli.getDailyFractions(e)}async buildTurns(e){if(this.codexCli.isVirtualThreadPath(e))return this.buildDbThreadTurns(e);let t=await this.codexCli.getRolloutSummary(e),s=this.codexCli.computeTokenTotals(t);return{turns:t.userMessages.map((i,r)=>this.buildRolloutTurn(t,r,i)),actualTokens:s.totalTokens>0?s.totalTokens:void 0}}async buildDbThreadTurns(e){let t=await this.codexCli.readThread(e);if(!t)return{turns:[]};let s=t.first_user_message?.trim()||"";if(!s)return{turns:[],actualTokens:t.tokens_used||void 0};let n=this.codexCli.toMillis(t.created_at);return{turns:[{turnNumber:1,timestamp:n?new Date(n).toISOString():null,mode:"cli",userMessage:s,assistantResponse:"",model:t.model||null,toolCalls:[],contextReferences:G(),mcpTools:[],inputTokensEstimate:Math.ceil(s.length/4),outputTokensEstimate:0,thinkingTokensEstimate:0}],actualTokens:t.tokens_used||void 0}}buildRolloutTurn(e,t,s){let n=e.userMessages[t+1]?.timestamp??null,i=d=>s.timestamp?d?d>=s.timestamp&&(n===null||d<n):!1:t===e.userMessages.length-1,r=e.assistantMessages.filter(d=>i(d.timestamp)),a=r.map(d=>d.text).join(`
|
|
158
|
+
`),c=r.length>0?r[r.length-1].model:e.models[e.models.length-1]??null;return{turnNumber:t+1,timestamp:s.timestamp,mode:"cli",userMessage:s.text,assistantResponse:a,model:c==="unknown"?null:c,toolCalls:e.toolCalls.filter(d=>i(d.timestamp)).map(d=>({toolName:d.name})),contextReferences:G(),mcpTools:[],inputTokensEstimate:Math.ceil(s.text.length/4),outputTokensEstimate:Math.ceil(a.length/4),thinkingTokensEstimate:0}}async analyzeUsage(e,t){let s=H();if(this.codexCli.isVirtualThreadPath(e))return this.analyzeDbThread(e,t,s);let n=await this.codexCli.getRolloutSummary(e);s.modeUsage.cli+=n.userMessages.length,s.toolCalls.total=n.toolCalls.length;for(let r of n.toolCalls){let a=t.toolNameMap[r.name]||r.name;s.toolCalls.byTool[a]=(s.toolCalls.byTool[a]||0)+1}let i=n.assistantMessages.map(r=>r.model).filter(r=>r!=="unknown");return this.applyModelStats(i.length>0?i:n.models,s,t),s}async analyzeDbThread(e,t,s){let n=await this.codexCli.readThread(e);if(!n)return s;let i=await this.codexCli.countInteractions(e);return s.modeUsage.cli+=i,n.model&&this.applyModelStats([n.model],s,t),s}applyModelStats(e,t,s){let n=[...new Set(e)];t.modelSwitching.uniqueModels=n,t.modelSwitching.modelCount=n.length,t.modelSwitching.totalRequests=e.length;let i=0;for(let r=1;r<e.length;r++)e[r]!==e[r-1]&&i++;t.modelSwitching.switchCount=i,Q(s.modelPricing,n,e,t)}};var cd=S(require("fs")),ud=S(require("path"));var ji=class{constructor(e){this.hermes=e}hermes;id="hermes";displayName="Hermes";handles(e){return this.hermes.isHermesSessionFile(e)}getBackingPath(e){return this.hermes.getDbPathFromVirtual(e)}async stat(e){return this.hermes.statSessionFile(e)}async getTokens(e){let t=await this.hermes.getTokens(e);return{...t,actualTokens:t.tokens}}async countInteractions(e){return this.hermes.countInteractions(e)}async getModelUsage(e){return this.hermes.getModelUsage(e)}async getMeta(e){let t=await this.hermes.readSession(e),s=await this.hermes.getMessages(e),n=await this.hermes.resolveTitle(e,t),i=[];t?.started_at&&i.push(t.started_at*1e3),t?.ended_at&&i.push(t.ended_at*1e3);for(let r of s)r.timestamp&&i.push(r.timestamp*1e3);return i.sort((r,a)=>r-a),{title:n,firstInteraction:i.length>0?new Date(i[0]).toISOString():null,lastInteraction:i.length>0?new Date(i[i.length-1]).toISOString():null,workspacePath:t?.cwd||void 0}}getEditorRoot(e){return ud.dirname(this.hermes.getDbPathFromVirtual(e))}async discover(e){let t=this.getCandidatePaths(),s=[],n=this.hermes.getDbPath();e(`\u{1F4C1} Checking Hermes DB path: ${n}`);try{await cd.promises.access(n);let i=await this.hermes.discoverSessionIds();i.length>0&&e(`\u{1F4C4} Found ${i.length} session(s) in Hermes database`),s.push(...i.map(r=>this.hermes.virtualPath(r)))}catch(i){e(`Could not read Hermes database: ${i}`)}return{sessionFiles:s,candidatePaths:t}}getCandidatePaths(){return[{path:this.hermes.getDbPath(),source:"Hermes (state.db)"}]}async getDailyFractions(e){return this.hermes.getDailyFractions(e)}async buildTurns(e){let t=[],s=await this.hermes.getMessages(e),n=await this.hermes.readSession(e),i=0;for(let r=0;r<s.length;r++){let a=s[r];if(a.role!=="user")continue;i++;let c=[];for(let d=r+1;d<s.length&&s[d].role!=="user";d++)c.push(s[d]);t.push(this.buildHermesTurn(a,c,n,i))}return{turns:t}}buildHermesTurn(e,t,s,n){let{assistantText:i,toolCalls:r,outputTokens:a}=this.processTurnMessages(t);return{turnNumber:n,timestamp:e.timestamp?new Date(e.timestamp*1e3).toISOString():null,mode:"cli",userMessage:e.content||"",assistantResponse:i,model:s?.model||null,toolCalls:r,contextReferences:G(),mcpTools:[],inputTokensEstimate:e.token_count||Math.ceil((e.content||"").length/4),outputTokensEstimate:a,thinkingTokensEstimate:t.reduce((c,d)=>c+(d.reasoning||d.reasoning_content?Math.ceil(((d.reasoning||"")+(d.reasoning_content||"")).length/4):0),0)}}processTurnMessages(e){let t="",s=0,n=new Map,i=[];for(let r of e)r.role==="assistant"?(t=this.appendAssistantText(t,r),s+=r.token_count||0,this.collectToolCallsFromAssistantMessage(r,n,i)):r.role==="tool"&&this.attachToolResult(r,n,i);return{assistantText:t,toolCalls:i,outputTokens:s}}appendAssistantText(e,t){return!t.content||!t.content.trim()?e:e+(e?`
|
|
159
|
+
`:"")+t.content}collectToolCallsFromAssistantMessage(e,t,s){for(let n of this.hermes.parseToolCalls(e.tool_calls)){let i={toolName:n.name,arguments:n.arguments};s.push(i),n.id&&t.set(n.id,i)}}attachToolResult(e,t,s){let n=this.hermes.parseToolResultText(e.content),i=e.tool_call_id?t.get(e.tool_call_id):void 0;if(i){i.result=n;return}e.tool_name&&s.push({toolName:e.tool_name,result:n})}async analyzeUsage(e,t){let s=H(),n=await this.hermes.readSession(e),i=await this.hermes.getMessages(e),r=n?.model||"unknown",a=[];for(let d of i)d.role==="user"&&(s.modeUsage.cli++,a.push(r)),d.role==="tool"&&d.tool_name&&(s.toolCalls.total++,s.toolCalls.byTool[d.tool_name]=(s.toolCalls.byTool[d.tool_name]||0)+1);let c=[...new Set(a)];return s.modelSwitching.uniqueModels=c,s.modelSwitching.modelCount=c.length,s.modelSwitching.totalRequests=a.length,Q(t.modelPricing,c,a,s),s}};function wa(o){return{openCode:new jo(o),crush:new Go(o),continue_:new qo,eclipse:new zo,visualStudio:new si,claudeCode:new oi,claudeDesktopCowork:new ri,mistralVibe:new ai,geminiCli:new li,antigravity:new ui,pi:new mi,cursor:new pi(o),kiro:new gi,kiroCli:new hi,devinCli:new Ci,cline:new Ti,codexCli:new wi,hermes:new Pi}}function Ma(o){return[new Fn(o.openCode),new Nn(o.crush),new Ln(o.visualStudio,o.estimateTokens),new jn(o.continue_),new Ii(o.eclipse),new qn(o.claudeDesktopCowork,o.isMcpTool,o.extractMcpServerName,o.estimateTokens),new Gn(o.claudeCode,o.isMcpTool,o.extractMcpServerName,o.estimateTokens),new Bn(o.mistralVibe),new $n(o.antigravity,o.estimateTokens),new zn(o.geminiCli),new Hn(o.pi),new Oi(o.cursor),new Vn(o.kiro),new Kn(o.kiroCli),new Ni(o.devinCli),new Li(o.cline),new Qn(o.codexCli),new ji(o.hermes),new Tn,new Wn,new Jn]}function Yn(o,e){try{return JSON.parse(o)}catch(t){console.error(`[${e}] JSON parse error:`,t);return}}function Ye(o){return typeof o=="object"&&o!==null}function dd(o){return typeof o!="string"?!1:!["__proto__","prototype","constructor","hasOwnProperty"].includes(o)&&!o.startsWith("__")}function qs(o){return/^\d+$/.test(o)}function Pa(o,e){if(typeof o!="string")return e;let t=o.trim();return t?t.startsWith("copilot/")?t.substring(8):t:e}function hC(o,e,t){let s=o;for(let n=0;n<e.length-1;n++){let i=e[n],r=e[n+1];if(Array.isArray(s)&&qs(i)){let a=Number(i),c=s[a],d;Ye(c)?d=c:(d=qs(r)?[]:Object.create(null),s[a]=d),s=d;continue}if(!Ye(s))return null;s=t(s,i,r)}return{root:o,current:s}}function yC(o,e,t,s){return Array.isArray(e)&&qs(t)?(e[Number(t)]=s,o):(Ye(e)&&Object.defineProperty(e,t,{value:s,writable:!0,enumerable:!0,configurable:!0}),o)}function _C(o,e,t,s){let n;if(Array.isArray(e)&&qs(t)){let i=Number(t);Array.isArray(e[i])||(e[i]=[]),n=e[i]}else Ye(e)&&(Array.isArray(e[t])||Object.defineProperty(e,t,{value:[],writable:!0,enumerable:!0,configurable:!0}),n=e[t]);return Array.isArray(n)&&(Array.isArray(s)?n.push(...s):n.push(s)),o}function CC(o,e){if(!Ye(e))return o;let t=e.kind,s=e.k,n=e.v;if(t===0)return n;if(!Array.isArray(s)||s.length===0)return o;let i=s.map(String);for(let h of i)if(!dd(h))return o;let r=Ye(o)?o:Object.create(null),c=hC(r,i,(h,_,C)=>{let T=h[_];if(!Ye(T)){let E=qs(C)?[]:Object.create(null);return h[_]=E,E}return T});if(!c)return r;let{root:d,current:p}=c,f=i[i.length-1];return t===1?yC(d,p,f,n):t===2?_C(d,p,f,n):d}function bC(o){if(!Array.isArray(o))return{responseText:"",thinkingText:""};let e="",t="";for(let s of o){let{text:n,isThinking:i}=Ps(s);n&&(i?t+=n:e+=n)}return{responseText:e,thinkingText:t}}var va=class{constructor(e,t){this.defaultModel=e;this.estimateTokens=t}defaultModel;estimateTokens;modelUsage={};totalInputTokens=0;totalOutputTokens=0;ensureModel(e){return typeof e=="string"&&e?e:this.defaultModel}addInput(e,t){let s=this.ensureModel(e);this.modelUsage[s]||(this.modelUsage[s]={inputTokens:0,outputTokens:0,sessions:0});let n=this.estimateTokens(t,s);this.modelUsage[s].inputTokens+=n,this.totalInputTokens+=n}addOutput(e,t){let s=this.ensureModel(e);this.modelUsage[s]||(this.modelUsage[s]={inputTokens:0,outputTokens:0,sessions:0});let n=this.estimateTokens(t,s);this.modelUsage[s].outputTokens+=n,this.totalOutputTokens+=n}};function kC(o,e,t){let s=o.modelId??o.selectedModel?.identifier??o.model,n=Pa(s,t);if(typeof s=="string"&&s.trim())return n;let i=e?e(o):void 0;return Pa(i,"")||n}function SC(o,e,t){if(o.message?.parts)for(let s of o.message.parts)typeof s?.text=="string"&&s.text&&t(e,s.text);else typeof o.message?.text=="string"&&t(e,o.message.text)}function TC(o,e,t,s){let n=o.modelName||e;o.prompt&&t(n,o.prompt),o.result&&s(n,o.result)}function wC(o,e,t,s){let n=Ms(o);if(n){TC(n,e,t,s);return}if(o&&(o.kind==="thinking"||typeof o.value=="string"))return;let i=o?.message?.parts;if(i)for(let r of i)typeof r?.text=="string"&&r.text&&s(e,r.text)}function MC(o,e,t,s){for(let n of o)wC(n,e,t,s)}function PC(o){if(!o)return 0;if(o.usage){let e=typeof o.usage.promptTokens=="number"?o.usage.promptTokens:0,t=typeof o.usage.completionTokens=="number"?o.usage.completionTokens:0;return e+t}return typeof o.promptTokens=="number"&&typeof o.outputTokens=="number"?o.promptTokens+o.outputTokens:o.metadata&&typeof o.metadata.promptTokens=="number"&&typeof o.metadata.outputTokens=="number"?o.metadata.promptTokens+o.metadata.outputTokens:0}function vC(o){return Array.isArray(o.requests)?o.requests:Array.isArray(o.history)?o.history:[]}function AC(o){return o.trim().length>0}function md(o,e,t,s,n,i,r){if(o==null||typeof o!="object")return;let a=o,c=kC(a,n,i);SC(a,c,t);let{responseText:d,thinkingText:p}=bC(a.response);d&&s(c,d),p&&(e.thinkingTokens+=r(p,c));let f=Array.isArray(a.response)?a.response:Array.isArray(a.responses)?a.responses:[];MC(f,c,t,s),e.actualTokens+=PC(a.result)}function xC(o){if(!Ye(o))return!1;let e=o.message;return Ye(e)&&typeof e.text=="string"&&!!e.text.trim()}function DC(o){if(o.length===0)return null;let e=Yn(o[0],"sessionParser");if(!e||typeof e.kind!="number")return null;let t=Object.create(null);for(let n of o){let i=Yn(n,"sessionParser");i!==void 0&&(t=CC(t,i))}let s=Ye(t)?t:null;return s&&Array.isArray(s.requests)?s.requests:[]}function pd(o,e,t,s){let n,i="unknown",r=new va(i,t),{modelUsage:a}=r,c=r.addInput.bind(r),d=r.addOutput.bind(r),p={thinkingTokens:0,actualTokens:0};if(o.endsWith(".jsonl")){let _=e.split(/\r?\n/).filter(AC),C=DC(_);if(C!==null){let T=C.filter(xC).length;for(let E of C)md(E,p,c,d,s,i,t);return{tokens:r.totalInputTokens+r.totalOutputTokens+p.thinkingTokens,interactions:T,modelUsage:a,thinkingTokens:p.thinkingTokens,actualTokens:0}}if(n=Yn(e.trim(),"sessionParser"),n===void 0)return{tokens:0,interactions:0,modelUsage:{},thinkingTokens:0,actualTokens:0}}if(!n&&(n=Yn(e,"sessionParser"),n===void 0))return{tokens:0,interactions:0,modelUsage:{},thinkingTokens:0,actualTokens:0};if(!Ye(n)||Array.isArray(n))return{tokens:0,interactions:0,modelUsage:{},thinkingTokens:0,actualTokens:0};let f=vC(n),h=f.length;for(let _ of f)md(_,p,c,d,s,i,t);return{tokens:r.totalInputTokens+r.totalOutputTokens+p.thinkingTokens,interactions:h,modelUsage:a,thinkingTokens:p.thinkingTokens,actualTokens:p.actualTokens}}var Aa=class{extractCounts(e){let t={},s={},n=e.trim().split(`
|
|
160
|
+
`);for(let i of n)if(i.trim())try{let r=JSON.parse(i);if(r.type==="user.message"){Bs(r.timestamp??r.ts??r.data?.timestamp,t);continue}this.processVsCodeDeltaEvent(r,s,t)}catch{}return t}processVsCodeDeltaEvent(e,t,s){let n=e.kind,i=e.k,r=e.v;n===0&&r?.requests&&Array.isArray(r.requests)?this.processKind0Event(r,s):n===2&&Array.isArray(i)&&i[0]==="requests"?this.processKind2Event(i,r,t,s):this.isKind1TimestampUpdate(n,i)&&this.processKind1Event(i,r,t,s)}isKind1TimestampUpdate(e,t){return e===1&&Array.isArray(t)&&t.length===3&&t[0]==="requests"&&(t[2]==="timestamp"||t[2]==="ts")&&typeof t[1]=="number"}processKind0Event(e,t){for(let s of e.requests)Bs(s.timestamp??s.ts,t)}processKind2Event(e,t,s,n){if(Array.isArray(t))for(let i of t)Bs(i.timestamp??i.ts,n);else if(t&&typeof t=="object"){let i=t.timestamp??t.ts;i!==void 0&&Bs(i,n),typeof e[1]=="number"&&(s[e[1]]=i)}}processKind1Event(e,t,s,n){let i=e[1];s[i]===void 0&&Bs(t,n),s[i]=t}},xa=class{extractCounts(e){let t={};try{let s=JSON.parse(e);if(s.requests&&Array.isArray(s.requests))for(let n of s.requests){let i=n.timestamp??n.ts??n.result?.timestamp;Bs(i,t)}}catch{}return t}};function EC(o){if(o==null)return null;let e=new Date(o);return isNaN(e.getTime())?null:e}function Bs(o,e){let t=EC(o);if(t!==null){let s=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0"),r=`${s}-${n}-${i}`;e[r]=(e[r]||0)+1}}function gd(o,e,t){let s=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0"),r=`${s}-${n}-${i}`,c=(e?new Aa:new xa).extractCounts(o),d=Object.values(c).reduce((f,h)=>f+h,0);if(d===0)return{[r]:1};let p={};for(let[f,h]of Object.entries(c))p[f]=h/d;return p}var $t=S(require("fs")),Ea=S(require("path")),fd=S(require("os"));var Gi=class{maxEntries;constructor(e=2e3){this.maxEntries=e}isValid(e,t,s){return e.mtime===t&&e.size===s}evict(e){if(e.size<=this.maxEntries)return;let t=[...e.entries()].sort((s,n)=>n[1].mtime-s[1].mtime);e.clear();for(let[s,n]of t.slice(0,this.maxEntries))e.set(s,n)}};var hd=5,RC=2e3,yd=Ea.join(fd.homedir(),".copilot-token-tracker"),Da=Ea.join(yd,"cli-cache.json"),xt=new Map,zs=!0,_d=!1,Cd=new Gi(RC);function Ra(){zs=!1,xt.clear()}function Ia(){if(zs)try{if(!$t.existsSync(Da))return;let o=$t.readFileSync(Da,"utf-8"),e=JSON.parse(o);if(e.version!==hd){xt.clear();return}xt=new Map(Object.entries(e.entries))}catch{xt.clear()}}function Ua(){if(!(!zs||!_d))try{Cd.evict(xt),$t.mkdirSync(yd,{recursive:!0});let o={version:hd,entries:Object.fromEntries(xt)};$t.writeFileSync(Da,JSON.stringify(o),"utf-8")}catch{}}function bd(o,e,t){if(!zs)return null;let s=xt.get(o);return!s||!Cd.isValid(s,e,t)?null:{...s.data,lastModified:new Date(s.data.lastModified)}}function Oa(o,e,t,s){zs&&(_d=!0,xt.set(o,{mtime:e,size:t,data:{...s,lastModified:s.lastModified.toISOString()}}))}function Fa(){return{entries:xt.size,enabled:zs}}var qe={CO2_PER_1K_TOKENS:.2,CO2_ABSORPTION_PER_TREE_PER_YEAR:21e3,WATER_USAGE_PER_1K_TOKENS:.3,CO2_PER_KM_DRIVING:120,CO2_PER_PHONE_CHARGE:8.22,WATER_PER_COFFEE_CUP:140,CO2_PER_LED_HOUR:20};var kd={$schema:"http://json-schema.org/draft-07/schema#",description:"Character-to-token ratio estimators for different AI models. Used to estimate token counts from text length.",estimators:{"gpt-4":.25,"gpt-4.1":.25,"gpt-4.1-mini":.25,"gpt-4o":.25,"gpt-4o-mini":.25,"gpt-4-turbo":.25,"gpt-3.5-turbo":.25,"gpt-5":.25,"gpt-5-codex":.25,"gpt-5-mini":.25,"gpt-5.1":.25,"gpt-5.1-codex":.25,"gpt-5.1-codex-max":.25,"gpt-5.1-codex-mini":.25,"gpt-5.2":.25,"gpt-5.2-codex":.25,"gpt-5.2-pro":.25,"gpt-5.3-codex":.25,"gpt-5.4":.25,"gpt-5.4-mini":.25,"gpt-5.4-nano":.25,"gpt-4.1-nano":.25,"gemini-2.0-flash":.25,"gemini-2.0-flash-lite":.25,"gemini-2.5-flash":.25,"gemini-2.5-flash-lite":.25,"claude-sonnet-3.5":.24,"claude-sonnet-3.7":.24,"claude-sonnet-4":.24,"claude-sonnet-4.5":.24,"claude-sonnet-4.6":.24,"claude-haiku":.24,"claude-haiku-4.5":.24,"claude-opus-4.1":.24,"claude-opus-4.5":.24,"claude-opus-4.6":.24,"claude-opus-4.6-(fast-mode)-(preview)":.24,"claude-opus-4.6-fast":.24,"claude-opus-4.7":.24,"gemini-2.5-pro":.25,"gemini-3-flash":.25,"gemini-3-pro":.25,"gemini-3-pro-preview":.25,"gemini-3.1-pro":.25,"gemini-3.1-flash-lite":.25,"grok-code-fast-1":.25,"raptor-mini":.25,goldeneye:.25,"o1-preview":.25,"o1-mini":.25,"o3-mini":.25,"o4-mini":.25,"gpt-5.5":.25,"mistral-large-latest":.25,"mistral-large-2512":.25,"mistral-large-2411":.25,"magistral-medium-latest":.25,"mistral-medium-latest":.25,"mistral-medium-3-5":.25,"mistral-medium-2505":.25,"mistral-small-latest":.25,"mistral-small-2503":.25,"mistral-small-2603":.25,"codestral-latest":.25,"codestral-2501":.25,"open-mistral-nemo":.25,"ministral-3b-2410":.25,"ministral-8b-2410":.25,"magistral-small-latest":.25,"devstral-medium-2507":.25,"pixtral-large-2411":.25,"gemini-3.5-flash":.25,"claude-opus-4.8":.24,"qwen2.5":.25,"mai-code-1-flash[^mai-code-1-flash]":.25,"mai-code-1-flash":.25,"claude-fable-5":.24,"claude-sonnet-5":.24,"claude-opus-4.8-(fast-mode)-(preview)":.24,"kimi-k2.7-code":.25,"gpt-5.6-luna":.25,"gpt-5.6-sol":.25,"gpt-5.6-terra":.25,"gemini-3.6-flash":.25,"claude-opus-5":.24}};var qi={$schema:"http://json-schema.org/draft-07/schema#",description:"Model pricing data - costs per million tokens. Each model has direct provider/API pricing at the top level (used as a reference); models billed through GitHub Copilot AI Credits also include a `copilotPricing` block reflecting GitHub's published per-token rates (1 AI credit = $0.01).",metadata:{lastUpdated:"2026-07-26",sources:[{name:"OpenAI API Pricing",url:"https://developers.openai.com/api/docs/pricing",retrievedDate:"2026-04-24"},{name:"Mistral AI API Pricing",url:"https://pricepertoken.com/pricing-page/provider/mistral-ai",retrievedDate:"2026-05-06",note:"Cross-referenced with https://openrouter.ai/mistralai and https://ai-pricing.info/mistral"},{name:"Anthropic Claude Pricing",url:"https://www.anthropic.com/pricing",note:"Standard rates; also see https://platform.claude.com/docs/en/about-claude/pricing",retrievedDate:"2026-03-30"},{name:"Google AI Gemini API Pricing",url:"https://ai.google.dev/gemini-api/docs/pricing",retrievedDate:"2026-03-30"},{name:"xAI Grok API Pricing",url:"https://x.ai/api",retrievedDate:"2026-03-30"},{name:"GitHub Copilot Supported Models",url:"https://docs.github.com/en/copilot/reference/ai-models/supported-models",retrievedDate:"2026-03-30",note:"Source for tier/multiplier data"},{name:"GitHub Copilot Premium Requests",url:"https://docs.github.com/en/copilot/managing-copilot/monitoring-usage-and-entitlements/about-premium-requests",retrievedDate:"2026-03-30",note:"Source for premium request multiplier values"},{name:"OpenRouter Model Pricing",url:"https://openrouter.ai",retrievedDate:"2026-03-30",note:"Cross-provider pricing aggregator used for verification"},{name:"DeepSeek API Pricing",url:"https://platform.deepseek.com/api-docs/pricing",retrievedDate:"2026-06-21",note:"deepseek-v4-flash: $0.14/M input (miss), $0.0028/M input (cache hit), $0.28/M output; free tier (deepseek-v4-flash-free via OpenRouter) is $0"},{name:"GitHub Copilot Models and Pricing",url:"https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",retrievedDate:"2026-04-27",note:"Source for the `copilotPricing` per-model block (GitHub AI Credit per-token rates)"}],disclaimer:"GitHub Copilot uses these models but pricing may differ from direct API usage. These are reference prices for cost estimation purposes only."},pricing:{"gpt-5":{inputCostPerMillion:1.25,outputCostPerMillion:10,category:"GPT-5 models",tier:"premium",displayNames:["GPT-5"]},"gpt-5-codex":{inputCostPerMillion:1.25,outputCostPerMillion:10,category:"GPT-5 models",tier:"premium",displayNames:["GPT-5 Codex (Preview)"]},"gpt-5-mini":{inputCostPerMillion:.25,outputCostPerMillion:2,category:"GPT-5 models",tier:"standard",displayNames:["GPT-5 Mini"],copilotPricing:{inputCostPerMillion:.25,cachedInputCostPerMillion:.025,outputCostPerMillion:2,releaseStatus:"GA",category:"Lightweight"},cachedInputCostPerMillion:.025},"gpt-5.1":{inputCostPerMillion:1.25,outputCostPerMillion:10,category:"GPT-5 models",tier:"premium",displayNames:["GPT-5.1"]},"gpt-5.1-codex":{inputCostPerMillion:1.25,outputCostPerMillion:10,category:"GPT-5 models",tier:"premium",displayNames:["GPT-5.1 Codex"]},"gpt-5.1-codex-max":{inputCostPerMillion:1.75,outputCostPerMillion:14,category:"GPT-5 models",tier:"premium",displayNames:["GPT-5.1 Codex Max"]},"gpt-5.1-codex-mini":{inputCostPerMillion:.25,outputCostPerMillion:2,category:"GPT-5 models",tier:"premium",displayNames:["GPT-5.1 Codex Mini (Preview)"]},"gpt-5.2":{inputCostPerMillion:1.75,outputCostPerMillion:14,category:"GPT-5 models",tier:"standard",displayNames:["GPT-5.2"],copilotPricing:{inputCostPerMillion:1.75,cachedInputCostPerMillion:.175,outputCostPerMillion:14,releaseStatus:"Closing down 2026-06-01",category:"Versatile"}},"gpt-5.2-codex":{inputCostPerMillion:1.75,outputCostPerMillion:14,category:"GPT-5 models",tier:"standard",displayNames:["GPT-5.2 Codex"],copilotPricing:{inputCostPerMillion:1.75,cachedInputCostPerMillion:.175,outputCostPerMillion:14,releaseStatus:"Closing down 2026-06-01",category:"Powerful"}},"gpt-5.2-pro":{inputCostPerMillion:21,outputCostPerMillion:168,category:"GPT-5 models",tier:"premium",displayNames:["GPT-5.2 Pro"]},"gpt-5.3-codex":{inputCostPerMillion:1.75,outputCostPerMillion:14,category:"GPT-5 models",tier:"standard",displayNames:["GPT-5.3 Codex"],copilotPricing:{inputCostPerMillion:1.75,cachedInputCostPerMillion:.175,outputCostPerMillion:14,releaseStatus:"GA",category:"Powerful"},cachedInputCostPerMillion:.175},"gpt-5.4":{inputCostPerMillion:2.5,cachedInputCostPerMillion:.25,outputCostPerMillion:15,category:"GPT-5 models",tier:"standard",displayNames:["GPT-5.4"],copilotPricing:{inputCostPerMillion:2.5,cachedInputCostPerMillion:.25,outputCostPerMillion:15,releaseStatus:"GA",category:"Versatile"}},"gpt-5.4-mini":{inputCostPerMillion:.75,cachedInputCostPerMillion:.075,outputCostPerMillion:4.5,category:"GPT-5 models",tier:"standard",displayNames:["GPT-5.4 mini"],copilotPricing:{inputCostPerMillion:.75,cachedInputCostPerMillion:.075,outputCostPerMillion:4.5,releaseStatus:"GA",category:"Lightweight"}},"gpt-5.4-nano":{inputCostPerMillion:.2,cachedInputCostPerMillion:.02,outputCostPerMillion:1.25,category:"GPT-5 models",tier:"standard",displayNames:["GPT-5.4 nano"],copilotPricing:{inputCostPerMillion:.2,cachedInputCostPerMillion:.02,outputCostPerMillion:1.25,releaseStatus:"GA",category:"Lightweight"}},"gpt-4":{inputCostPerMillion:3,outputCostPerMillion:12,category:"GPT-4 models",tier:"unknown",displayNames:["GPT-4"]},"gpt-4.1":{inputCostPerMillion:2,cachedInputCostPerMillion:.5,outputCostPerMillion:8,category:"GPT-4 models",tier:"standard",displayNames:["GPT-4.1"],copilotPricing:{inputCostPerMillion:2,cachedInputCostPerMillion:.5,outputCostPerMillion:8,releaseStatus:"Closing down 2026-06-01",category:"Versatile"}},"gpt-4.1-mini":{inputCostPerMillion:.4,cachedInputCostPerMillion:.1,outputCostPerMillion:1.6,category:"GPT-4 models",tier:"standard",displayNames:["GPT-4.1 Mini"]},"gpt-4.1-nano":{inputCostPerMillion:.1,cachedInputCostPerMillion:.025,outputCostPerMillion:.4,category:"GPT-4 models",tier:"standard",displayNames:["GPT-4.1 Nano"]},"gpt-4o":{inputCostPerMillion:2.5,outputCostPerMillion:10,cachedInputCostPerMillion:1.25,category:"GPT-4 models",tier:"standard",displayNames:["GPT-4o"]},"gpt-4o-mini":{inputCostPerMillion:.15,outputCostPerMillion:.6,cachedInputCostPerMillion:.075,category:"GPT-4 models",tier:"standard",displayNames:["GPT-4o-mini","GPT-4o Mini"]},"gpt-4o-mini-2024-07-18":{inputCostPerMillion:.15,outputCostPerMillion:.6,cachedInputCostPerMillion:.075,category:"GPT-4 models",tier:"standard",displayNames:["GPT-4o-mini (2024-07-18)"]},"gpt-4-turbo":{inputCostPerMillion:10,outputCostPerMillion:30,category:"GPT-4 models",tier:"standard",displayNames:["GPT-4 Turbo"]},"claude-sonnet-3.5":{inputCostPerMillion:3,outputCostPerMillion:15,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,cacheCreation1hCostPerMillion:6,category:"Claude models (Anthropic)",tier:"unknown",displayNames:["Claude Sonnet 3.5"]},"claude-sonnet-3.7":{inputCostPerMillion:3,outputCostPerMillion:15,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,cacheCreation1hCostPerMillion:6,category:"Claude models (Anthropic)",tier:"unknown",displayNames:["Claude Sonnet 3.7"]},"claude-sonnet-4":{inputCostPerMillion:3,outputCostPerMillion:15,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,cacheCreation1hCostPerMillion:6,category:"Claude models (Anthropic)",tier:"premium",displayNames:["Claude Sonnet 4"],copilotPricing:{inputCostPerMillion:3,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,outputCostPerMillion:15,releaseStatus:"GA",category:"Versatile"}},"claude-sonnet-4.5":{inputCostPerMillion:3,outputCostPerMillion:15,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,cacheCreation1hCostPerMillion:6,category:"Claude models (Anthropic)",tier:"standard",displayNames:["Claude Sonnet 4.5"],copilotPricing:{inputCostPerMillion:3,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,outputCostPerMillion:15,releaseStatus:"GA",category:"Versatile"}},"claude-sonnet-4.6":{inputCostPerMillion:3,outputCostPerMillion:15,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,cacheCreation1hCostPerMillion:6,category:"Claude models (Anthropic)",tier:"standard",displayNames:["Claude Sonnet 4.6"],copilotPricing:{inputCostPerMillion:3,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,outputCostPerMillion:15,releaseStatus:"GA",category:"Versatile"}},"claude-sonnet-4-6":{inputCostPerMillion:3,outputCostPerMillion:15,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,cacheCreation1hCostPerMillion:6,category:"Claude models (Anthropic)",tier:"standard",displayNames:["Claude Sonnet 4.6 (alternate format)"],copilotPricing:{inputCostPerMillion:3,cachedInputCostPerMillion:.3,cacheCreationCostPerMillion:3.75,outputCostPerMillion:15,releaseStatus:"GA",category:"Versatile"}},"claude-haiku":{inputCostPerMillion:.25,outputCostPerMillion:1.25,cachedInputCostPerMillion:.025,cacheCreationCostPerMillion:.3125,cacheCreation1hCostPerMillion:.5,category:"Claude models (Anthropic)",tier:"standard",displayNames:["Claude Haiku"]},"claude-haiku-4.5":{inputCostPerMillion:1,outputCostPerMillion:5,cachedInputCostPerMillion:.1,cacheCreationCostPerMillion:1.25,cacheCreation1hCostPerMillion:2,category:"Claude models (Anthropic)",tier:"standard",displayNames:["Claude Haiku 4.5"],copilotPricing:{inputCostPerMillion:1,cachedInputCostPerMillion:.1,cacheCreationCostPerMillion:1.25,outputCostPerMillion:5,releaseStatus:"GA",category:"Versatile"}},"claude-haiku-4-5-20251001":{inputCostPerMillion:1,outputCostPerMillion:5,cachedInputCostPerMillion:.1,cacheCreationCostPerMillion:1.25,cacheCreation1hCostPerMillion:2,category:"Claude models (Anthropic)",tier:"standard",displayNames:["Claude Haiku 4.5 (2025-10-01)"],copilotPricing:{inputCostPerMillion:1,cachedInputCostPerMillion:.1,cacheCreationCostPerMillion:1.25,outputCostPerMillion:5,releaseStatus:"GA",category:"Versatile"}},"claude-opus-4.1":{inputCostPerMillion:15,outputCostPerMillion:75,cachedInputCostPerMillion:1.5,cacheCreationCostPerMillion:18.75,cacheCreation1hCostPerMillion:30,category:"Claude models (Anthropic)",tier:"premium",displayNames:["Claude Opus 4.1"]},"claude-opus-4.5":{inputCostPerMillion:5,outputCostPerMillion:25,cachedInputCostPerMillion:.5,cacheCreationCostPerMillion:6.25,cacheCreation1hCostPerMillion:10,category:"Claude models (Anthropic)",tier:"standard",displayNames:["Claude Opus 4.5"],copilotPricing:{inputCostPerMillion:5,cachedInputCostPerMillion:.5,cacheCreationCostPerMillion:6.25,outputCostPerMillion:25,releaseStatus:"GA",category:"Powerful"}},"claude-opus-4.6":{inputCostPerMillion:5,outputCostPerMillion:25,cachedInputCostPerMillion:.5,cacheCreationCostPerMillion:6.25,cacheCreation1hCostPerMillion:10,category:"Claude models (Anthropic)",tier:"standard",displayNames:["Claude Opus 4.6"],copilotPricing:{inputCostPerMillion:5,cachedInputCostPerMillion:.5,cacheCreationCostPerMillion:6.25,outputCostPerMillion:25,releaseStatus:"GA",category:"Powerful"}},"claude-opus-4.7":{inputCostPerMillion:5,outputCostPerMillion:25,cachedInputCostPerMillion:.5,cacheCreationCostPerMillion:6.25,cacheCreation1hCostPerMillion:10,category:"Claude models (Anthropic)",tier:"standard",displayNames:["Claude Opus 4.7"],copilotPricing:{inputCostPerMillion:5,cachedInputCostPerMillion:.5,cacheCreationCostPerMillion:6.25,outputCostPerMillion:25,releaseStatus:"GA",category:"Powerful"}},"claude-opus-4.6-(fast-mode)-(preview)":{inputCostPerMillion:5,outputCostPerMillion:25,cachedInputCostPerMillion:.5,cacheCreationCostPerMillion:6.25,cacheCreation1hCostPerMillion:10,category:"Claude models (Anthropic)",tier:"standard",displayNames:["Claude Opus 4.6 (Fast Mode Preview)"],copilotPricing:{inputCostPerMillion:30,cachedInputCostPerMillion:3,cacheCreationCostPerMillion:37.5,outputCostPerMillion:150,releaseStatus:"Public preview",category:"Powerful"}},"claude-opus-4.6-fast":{inputCostPerMillion:5,outputCostPerMillion:25,cachedInputCostPerMillion:.5,cacheCreationCostPerMillion:6.25,cacheCreation1hCostPerMillion:10,category:"Claude models (Anthropic)",tier:"premium",displayNames:["Claude Opus 4.6 (Fast)"],copilotPricing:{inputCostPerMillion:30,cachedInputCostPerMillion:3,cacheCreationCostPerMillion:37.5,outputCostPerMillion:150,releaseStatus:"Public preview",category:"Powerful"}},"o3-mini":{inputCostPerMillion:1.1,outputCostPerMillion:4.4,category:"OpenAI reasoning models",tier:"premium",displayNames:["o3-mini"]},"o4-mini":{inputCostPerMillion:1.1,outputCostPerMillion:4.4,category:"OpenAI reasoning models",tier:"premium",displayNames:["o4-mini"]},"o1-preview":{inputCostPerMillion:15,outputCostPerMillion:60,category:"OpenAI reasoning models",tier:"premium",displayNames:["o1-preview"]},"o1-mini":{inputCostPerMillion:3,outputCostPerMillion:12,category:"OpenAI reasoning models",tier:"premium",displayNames:["o1-mini"]},"gpt-3.5-turbo":{inputCostPerMillion:.5,outputCostPerMillion:1.5,category:"Legacy models",tier:"standard",displayNames:["GPT-3.5-Turbo","GPT-3.5 Turbo"]},"gemini-2.5-pro":{inputCostPerMillion:1.25,outputCostPerMillion:10,category:"Google Gemini models",tier:"standard",displayNames:["Gemini 2.5 Pro"],copilotPricing:{inputCostPerMillion:1.25,cachedInputCostPerMillion:.125,outputCostPerMillion:10,releaseStatus:"GA",category:"Powerful"},cachedInputCostPerMillion:.125},"gemini-2.5-flash":{inputCostPerMillion:.3,outputCostPerMillion:2.5,category:"Google Gemini models",tier:"unknown",displayNames:["Gemini 2.5 Flash"]},"gemini-2.5-flash-lite":{inputCostPerMillion:.1,outputCostPerMillion:.4,category:"Google Gemini models",tier:"unknown",displayNames:["Gemini 2.5 Flash Lite"]},"gemini-2.0-flash":{inputCostPerMillion:.1,outputCostPerMillion:.4,category:"Google Gemini models",tier:"standard",displayNames:["Gemini 2.0 Flash"]},"gemini-2.0-flash-lite":{inputCostPerMillion:.075,outputCostPerMillion:.3,category:"Google Gemini models",tier:"standard",displayNames:["Gemini 2.0 Flash Lite"]},"gemini-3-flash":{inputCostPerMillion:.5,outputCostPerMillion:3,category:"Google Gemini models",tier:"standard",displayNames:["Gemini 3 Flash"],copilotPricing:{inputCostPerMillion:.5,cachedInputCostPerMillion:.05,outputCostPerMillion:3,releaseStatus:"Public preview",category:"Lightweight"},cachedInputCostPerMillion:.05},"gemini-3-pro":{inputCostPerMillion:2,outputCostPerMillion:12,category:"Google Gemini models",tier:"premium",displayNames:["Gemini 3 Pro"]},"gemini-3-pro-preview":{inputCostPerMillion:2,outputCostPerMillion:12,category:"Google Gemini models",tier:"premium",displayNames:["Gemini 3 Pro (Preview)"]},"gemini-3.1-pro":{inputCostPerMillion:2,outputCostPerMillion:12,category:"Google Gemini models",tier:"standard",displayNames:["Gemini 3.1 Pro","Gemini 3.1 Pro (Preview)"],copilotPricing:{inputCostPerMillion:2,cachedInputCostPerMillion:.2,outputCostPerMillion:12,releaseStatus:"Public preview",category:"Powerful"},cachedInputCostPerMillion:.2},"gemini-3.1-flash-lite":{inputCostPerMillion:.25,outputCostPerMillion:1.5,category:"Google Gemini models",tier:"unknown",displayNames:["Gemini 3.1 Flash Lite"]},"grok-code-fast-1":{inputCostPerMillion:.2,outputCostPerMillion:1.5,category:"xAI Grok models",tier:"premium",displayNames:["Grok Code Fast 1"],copilotPricing:{inputCostPerMillion:.2,cachedInputCostPerMillion:.02,outputCostPerMillion:1.5,releaseStatus:"GA",category:"Lightweight"}},"raptor-mini":{inputCostPerMillion:.25,outputCostPerMillion:2,category:"GitHub Copilot fine-tuned models",tier:"standard",displayNames:["Raptor Mini"],copilotPricing:{inputCostPerMillion:.25,cachedInputCostPerMillion:.025,outputCostPerMillion:2,releaseStatus:"GA",category:"Versatile"},cachedInputCostPerMillion:.025},goldeneye:{inputCostPerMillion:0,outputCostPerMillion:0,category:"GitHub Copilot fine-tuned models",tier:"standard",copilotPricing:{inputCostPerMillion:1.25,cachedInputCostPerMillion:.125,outputCostPerMillion:10,releaseStatus:"Public preview",category:"Powerful"}},"gpt-5.5":{inputCostPerMillion:5,outputCostPerMillion:30,category:"GPT-5 models",tier:"standard",displayNames:["GPT-5.5"],cachedInputCostPerMillion:.5},"mistral-large-latest":{inputCostPerMillion:.5,outputCostPerMillion:1.5,category:"Mistral models",tier:"unknown",displayNames:["Mistral Large 3"]},"mistral-large-2512":{inputCostPerMillion:.5,outputCostPerMillion:1.5,category:"Mistral models",tier:"unknown",displayNames:["Mistral Large 3 (2512)"]},"mistral-large-2411":{inputCostPerMillion:2,outputCostPerMillion:6,category:"Mistral models",tier:"unknown",displayNames:["Mistral Large 2.1"]},"magistral-medium-latest":{inputCostPerMillion:2,outputCostPerMillion:5,category:"Mistral models",tier:"unknown",displayNames:["Magistral Medium"]},"mistral-medium-latest":{inputCostPerMillion:1.5,outputCostPerMillion:7.5,category:"Mistral models",tier:"unknown",displayNames:["Mistral Medium 3.5"]},"mistral-medium-3-5":{inputCostPerMillion:1.5,outputCostPerMillion:7.5,category:"Mistral models",tier:"unknown",displayNames:["Mistral Medium 3.5"]},"mistral-medium-3.5":{inputCostPerMillion:1.5,outputCostPerMillion:7.5,category:"Mistral models",tier:"unknown",displayNames:["Mistral Medium 3.5"]},"mistral-medium-2505":{inputCostPerMillion:.4,outputCostPerMillion:2,category:"Mistral models",tier:"unknown",displayNames:["Mistral Medium 3.1"]},"mistral-small-latest":{inputCostPerMillion:.1,outputCostPerMillion:.3,category:"Mistral models",tier:"unknown",displayNames:["Mistral Small 3.1"]},"mistral-small-2503":{inputCostPerMillion:.075,outputCostPerMillion:.2,category:"Mistral models",tier:"unknown",displayNames:["Mistral Small 3.2"]},"mistral-small-2603":{inputCostPerMillion:.15,outputCostPerMillion:.6,category:"Mistral models",tier:"unknown",displayNames:["Mistral Small 4"]},"codestral-latest":{inputCostPerMillion:.3,outputCostPerMillion:.9,category:"Mistral models",tier:"unknown",displayNames:["Codestral"]},"codestral-2501":{inputCostPerMillion:.3,outputCostPerMillion:.9,category:"Mistral models",tier:"unknown",displayNames:["Codestral (2501)"]},"open-mistral-nemo":{inputCostPerMillion:.02,outputCostPerMillion:.03,category:"Mistral models",tier:"unknown",displayNames:["Mistral Nemo"]},"ministral-3b-2410":{inputCostPerMillion:.04,outputCostPerMillion:.04,category:"Mistral models",tier:"unknown",displayNames:["Ministral 3B"]},"ministral-8b-2410":{inputCostPerMillion:.1,outputCostPerMillion:.1,category:"Mistral models",tier:"unknown",displayNames:["Ministral 8B"]},"magistral-small-latest":{inputCostPerMillion:.5,outputCostPerMillion:1.5,category:"Mistral models",tier:"unknown",displayNames:["Magistral Small"]},"devstral-medium-2507":{inputCostPerMillion:.4,outputCostPerMillion:2,category:"Mistral models",tier:"unknown",displayNames:["Devstral Medium"]},"pixtral-large-2411":{inputCostPerMillion:2,outputCostPerMillion:6,category:"Mistral models",tier:"unknown",displayNames:["Pixtral Large"]},"gemini-3.5-flash":{inputCostPerMillion:1.5,outputCostPerMillion:9,category:"Google Gemini models",tier:"standard",displayNames:["Gemini 3.5 Flash"],cachedInputCostPerMillion:.15},"claude-opus-4.8":{inputCostPerMillion:5,outputCostPerMillion:25,category:"Claude models (Anthropic)",tier:"standard",displayNames:["Claude Opus 4.8"],cachedInputCostPerMillion:.5,cacheCreationCostPerMillion:6.25,cacheCreation1hCostPerMillion:10},"qwen2.5":{inputCostPerMillion:0,outputCostPerMillion:0,category:" models",tier:"standard",displayNames:["Qwen2.5"]},"mai-code-1-flash[^mai-code-1-flash]":{inputCostPerMillion:0,outputCostPerMillion:0,category:" models",tier:"standard",displayNames:["MAI-Code-1-Flash[^mai-code-1-flash]"]},"mai-code-1-flash":{inputCostPerMillion:.75,outputCostPerMillion:4.5,category:" models",tier:"standard",displayNames:["MAI-Code-1-Flash"],cachedInputCostPerMillion:.075},"claude-fable-5":{inputCostPerMillion:10,outputCostPerMillion:50,category:"Claude models (Anthropic)",tier:"standard",displayNames:["Claude Fable 5"],cachedInputCostPerMillion:1,cacheCreationCostPerMillion:12.5,cacheCreation1hCostPerMillion:20},"deepseek-v4-flash":{inputCostPerMillion:.14,outputCostPerMillion:.28,cachedInputCostPerMillion:.0028,category:"DeepSeek models",tier:"standard",displayNames:["DeepSeek V4 Flash"]},"deepseek-v4-flash-free":{inputCostPerMillion:0,outputCostPerMillion:0,category:"DeepSeek models",tier:"standard",displayNames:["DeepSeek V4 Flash (free)"]},"claude-sonnet-5":{inputCostPerMillion:2,outputCostPerMillion:10,category:"Claude models (Anthropic)",tier:"standard",displayNames:["Claude Sonnet 5"],cachedInputCostPerMillion:.2,cacheCreationCostPerMillion:2.5,cacheCreation1hCostPerMillion:4},"claude-opus-4.8-(fast-mode)-(preview)":{inputCostPerMillion:10,outputCostPerMillion:50,category:"Claude models (Anthropic)",tier:"standard",displayNames:["Claude Opus 4.8 (fast mode) (preview)"],cachedInputCostPerMillion:1,cacheCreationCostPerMillion:12.5,cacheCreation1hCostPerMillion:20},"kimi-k2.7-code":{inputCostPerMillion:.95,outputCostPerMillion:4,category:"Moonshot AI models",tier:"standard",displayNames:["Kimi-K2.7-Code"],cachedInputCostPerMillion:.19},"gpt-5.6-luna":{inputCostPerMillion:1,outputCostPerMillion:6,category:"GPT-5 models",tier:"standard",displayNames:["GPT-5.6 Luna"],cachedInputCostPerMillion:.1,copilotPricing:{inputCostPerMillion:1,cachedInputCostPerMillion:.1,outputCostPerMillion:6,releaseStatus:"GA",category:"Lightweight",longContext:{inputCostPerMillion:2,cachedInputCostPerMillion:.2,outputCostPerMillion:9,threshold:"> 200K"}}},"gpt-5.6-sol":{inputCostPerMillion:5,outputCostPerMillion:30,category:"GPT-5 models",tier:"standard",displayNames:["GPT-5.6 Sol"],cachedInputCostPerMillion:.5,copilotPricing:{inputCostPerMillion:5,cachedInputCostPerMillion:.5,outputCostPerMillion:30,releaseStatus:"GA",category:"Powerful",longContext:{inputCostPerMillion:10,cachedInputCostPerMillion:1,outputCostPerMillion:45,threshold:"> 272K"}}},"gpt-5.6-terra":{inputCostPerMillion:2.5,outputCostPerMillion:15,category:"GPT-5 models",tier:"standard",displayNames:["GPT-5.6 Terra"],cachedInputCostPerMillion:.25,copilotPricing:{inputCostPerMillion:2.5,cachedInputCostPerMillion:.25,outputCostPerMillion:15,releaseStatus:"GA",category:"Versatile",longContext:{inputCostPerMillion:5,cachedInputCostPerMillion:.5,outputCostPerMillion:22.5,threshold:"> 272K"}}},"gemini-3.6-flash":{inputCostPerMillion:1.5,outputCostPerMillion:7.5,category:"Google Gemini models",tier:"standard",displayNames:["Gemini 3.6 Flash"],cachedInputCostPerMillion:.15},"claude-opus-5":{inputCostPerMillion:5,outputCostPerMillion:25,category:"Claude models (Anthropic)",tier:"standard",displayNames:["Claude Opus 5"],cachedInputCostPerMillion:.5,cacheCreationCostPerMillion:6.25}}};var Sd={unknown:"Unknown",windsurf_cascade:"Windsurf Cascade",windsurf_file_edit:"Windsurf: File Edit",windsurf_file_create:"Windsurf: File Create",windsurf_file_read:"Windsurf: File Read",windsurf_terminal:"Windsurf: Terminal",windsurf_search:"Windsurf: Search",windsurf_browser:"Windsurf: Browser",run_in_terminal:"Run In Terminal",run_shell_command:"Run Shell Command",send_to_terminal:"Send To Terminal",run_build:"Run Build",run_command_in_terminal:"Run Command In Terminal","mcp.io.github.git.assign_copilot_to_issue":"GitHub MCP (Local): Assign Copilot to Issue","mcp.io.github.git.create_or_update_file":"GitHub MCP (Local): Create/Update File",mcp_io_github_git_create_or_update_file:"GitHub MCP (Local): Create/Update File",mcp_io_github_git_assign_copilot_to_issue:"GitHub MCP (Local): Assign Copilot to Issue",mcp_io_github_git_pull_request_read:"GitHub MCP (Local): Pull Request Read",mcp_io_github_git_issue_read:"GitHub MCP (Local): Issue Read",mcp_io_github_git_issue_write:"GitHub MCP (Local): Issue Write",mcp_io_github_git_list_issues:"GitHub MCP (Local): List Issues",mcp_io_github_git_create_pull_request:"GitHub MCP (Local): Create Pull Request",mcp_io_github_git_get_file_contents:"GitHub MCP (Local): Get File Contents",mcp_io_github_git_search_code:"GitHub MCP (Local): Search Code",mcp_io_github_git_search_pull_requests:"GitHub MCP (Local): Search Pull Requests",mcp_io_github_git_get_release_by_tag:"GitHub MCP (Local): Get Release By Tag",mcp_io_github_git_search_issues:"GitHub MCP (Local): Search Issues",mcp_io_github_git_add_issue_comment:"GitHub MCP (Local): Add Issue Comment",mcp_io_github_git_list_pull_requests:"GitHub MCP (Local): List Pull Requests",mcp_io_github_git_get_commit:"GitHub MCP (Local): Get Commit",mcp_io_github_git_list_commits:"GitHub MCP (Local): List Commits",mcp_io_github_git_list_code_scanning_alerts:"GitHub MCP (Local): List Code Scanning Alerts",mcp_io_github_git_get_repository_tree:"GitHub MCP (Local): Get Repository Tree",mcp_io_github_git_get_job_logs:"GitHub MCP (Local): Get Job Logs",mcp_io_github_git_list_tags:"GitHub MCP (Local): List Tags",mcp_io_github_git_search_repositories:"GitHub MCP (Local): Search Repositories",mcp_io_github_git_create_repository:"GitHub MCP (Local): Create Repository",mcp_io_github_git_search_users:"GitHub MCP (Local): Search Users",mcp_io_github_git_get_latest_release:"GitHub MCP (Local): Get Latest Release",mcp_io_github_git_get_tag:"GitHub MCP (Local): Get Tag",mcp_github_github_assign_copilot_to_issue:"GitHub MCP (Remote): Assign Copilot to Issue",mcp_github_github_issue_read:"GitHub MCP (Remote): Issue Read",mcp_github_github_issue_write:"GitHub MCP (Remote): Issue Write",mcp_github_github_list_issues:"GitHub MCP (Remote): List Issues",mcp_github_get_file_contents:"GitHub MCP (Remote): Get File Contents",mcp_github_get_latest_release:"GitHub MCP (Remote): Get Latest Release",mcp_github_get_release_by_tag:"GitHub MCP (Remote): Get Release By Tag",mcp_github_list_releases:"GitHub MCP (Remote): List Releases",mcp_github_list_tags:"GitHub MCP (Remote): List Tags",mcp_github_search_code:"GitHub MCP (Remote): Search Code",mcp_github_search_issues:"GitHub MCP (Remote): Search Issues",mcp_github_issue_write:"GitHub MCP (Remote): Issue Write",mcp_github_list_issues:"GitHub MCP (Remote): List Issues",mcp_github_create_pull_request:"GitHub MCP (Remote): Create Pull Request",mcp_github_pull_request_read:"GitHub MCP (Remote): Pull Request Read",mcp_github_list_branches:"MCP GitHub List Branches",mcp_github_update_pull_request:"MCP GitHub Update Pull Request","github-mcp-server-get_file_contents":"GitHub MCP: Get File Contents","github-mcp-server-get_job_logs":"GitHub MCP: Get Job Logs","github-mcp-server-list_commits":"GitHub MCP: List Commits","github-mcp-server-search_code":"GitHub MCP: Search Code","github-mcp-server-actions_list":"GitHub MCP: Actions List","github-mcp-server-list_issues":"GitHub MCP: List Issues","github-mcp-server-search_repositories":"GitHub MCP: Search Repositories","github-mcp-server-list_branches":"GitHub MCP: List Branches","github-mcp-server-issue_read":"GitHub MCP: Issue Read","github-mcp-server-issue_write":"GitHub MCP: Issue Write","github-mcp-server-pull_request_read":"GitHub MCP: Pull Request Read","github-mcp-server-search_issues":"GitHub MCP: Search Issues","github-mcp-server-search_users":"GitHub MCP: Search Users","github-mcp-server-sub_issue_write":"GitHub MCP: Sub Issue Write","github-mcp-server-list_pull_requests":"GitHub MCP Server List Pull Requests","github-mcp-server-search_pull_requests":"GitHub MCP (Remote): Search Pull Requests","github-actions_get":"GitHub Actions: Get","github-actions_list":"GitHub Actions: List","github-create_pull_request":"GitHub: Create Pull Request","github-get_commit":"GitHub: Get Commit","github-get_file_contents":"GitHub: Get File Contents","github-get_job_logs":"GitHub: Get Job Logs","github-get_latest_release":"GitHub: Get Latest Release","github-get_me":"GitHub: Get Me","github-get_release_by_tag":"GitHub: Get Release By Tag","github-get_repository_tree":"GitHub: Get Repository Tree","github-get_teams":"GitHub: Get Teams","github-github_support_docs_search":"GitHub: GitHub Support Docs Search","github-issue_read":"GitHub: Issue Read","github-list_code_scanning_alerts":"GitHub: List Code Scanning Alerts","github-list_dependabot_alerts":"GitHub: List Dependabot Alerts","github-list_tags":"GitHub: List Tags","github-pull_request_read":"GitHub: Pull Request Read","github-pull_request_review_write":"GitHub: Pull Request Review Write","github-search_code":"GitHub: Search Code","github-search_pull_requests":"GitHub: Search Pull Requests","github-search_repositories":"GitHub: Search Repositories","github-update_pull_request":"GitHub: Update Pull Request","mcp_github-code-s_get_code_scanning_alert":"GitHub MCP (Code Scanning): Get Alert","mcp_github-code-s_list_code_scanning_alerts":"GitHub MCP (Code Scanning): List Alerts",mcp_com_microsoft_get_bestpractices:"GitHub MCP: Get Best Practices",mcp_microsoft_doc_microsoft_code_sample_search:"Microsoft Docs MCP: Code Sample Search",mcp_microsoft_doc_microsoft_docs_search:"Microsoft Docs MCP: Docs Search",mcp_microsoftdocs_microsoft_code_sample_search:"Microsoft Docs MCP: Code Sample Search",mcp_microsoftdocs_microsoft_docs_fetch:"Microsoft Docs MCP: Docs Fetch",mcp_microsoftdocs_microsoft_docs_search:"Microsoft Docs MCP: Docs Search",Microsoft_Learn_microsoft_docs_search:"Microsoft Learn: Docs Search","microsoft-learn-microsoft_docs_search":"Microsoft Learn: Docs Search",mcp_gitkraken_git_add_or_commit:"GitKraken MCP: Git Add or Commit",mcp_gitkraken_git_status:"GitKraken MCP: Git Status",mcp_gitkraken_git_branch:"GitKraken MCP: Git Branch",mcp_gitkraken_git_checkout:"GitKraken MCP: Git Checkout",mcp_gitkraken_git_log_or_diff:"GitKraken MCP: Git Log or Diff",mcp_gitkraken_gitkraken_workspace_list:"GitKraken MCP: List Workspaces",mcp_gitkraken_git_push:"GitKraken MCP: Git Push",mcp_gitkraken_gitlens_commit_composer:"GitKraken MCP: GitLens Commit Composer",mcp_git_git_log:"Git MCP: Git Log",mcp_git_git_show:"Git MCP: Git Show",mcp_git_git_diff_staged:"Git MCP: Git Diff Staged",mcp_pencil_batch_design:"Pencil MCP: Batch Design",mcp_pencil_get_editor_state:"Pencil MCP: Get Editor State",mcp_pencil_get_guidelines:"Pencil MCP: Get Guidelines",mcp_pencil_get_screenshot:"Pencil MCP: Get Screenshot",mcp_pencil_snapshot_layout:"Pencil MCP: Snapshot Layout",mcp_figma_get_design_context:"Figma MCP: Get Design Context",mcp_figma_get_screenshot:"Figma MCP: Get Screenshot",mcp_figma_get_variable_defs:"Figma MCP: Get Variable Defs",mcp_azure_aks:"Azure MCP: AKS",mcp_azure_mcp_azureterraformbestpractices:"Azure MCP: Azure Terraform Best Practices",mcp_azure_mcp_documentation:"Azure MCP: Documentation",mcp_azure_mcp_get_bestpractices:"Azure MCP: Get Best Practices",mcp_azure_mcp_group_list:"Azure MCP: Group List",mcp_azure_mcp_storage:"Azure MCP: Storage",mcp_azure_mcp_subscription_list:"Azure MCP: Subscription List",mcp_azure_mcp_pricing:"Azure MCP: Pricing",mcp_azure_mcp_get_azure_bestpractices:"Azure MCP: Get Azure Best Practices","azure-mcp-azureterraformbestpractices":"Azure MCP: Azure Terraform Best Practices","azure-mcp-documentation":"Azure MCP: Documentation","azure-mcp-extension_cli_generate":"Azure MCP: Extension CLI Generate","azure-mcp-get_azure_bestpractices":"Azure MCP: Get Azure Best Practices","azure-mcp-group_list":"Azure MCP: Group List","azure-mcp-subscription_list":"Azure MCP: Subscription List",mcp_bicep_format_bicep_file:"Bicep MCP: Format Bicep File",mcp_bicep_get_az_resource_type_schema:"Bicep MCP: Get Az Resource Type Schema",mcp_bicep_get_bicep_best_practices:"Bicep MCP: Get Bicep Best Practices",mcp_bicep_get_bicep_file_diagnostics:"Bicep MCP: Get Bicep File Diagnostics",mcp_bicep_list_az_resource_types_for_provider:"Bicep MCP: List Az Resource Types For Provider","azure_bicep-get_azure_verified_module":"Azure Bicep: Get Azure Verified Module","azure_development-recommend_custom_modes":"Azure Development: Recommend Custom Modes","azure_resources-query_azure_resource_graph":"Azure Resources: Query Azure Resource Graph",azureResources_getAzureActivityLog:"Azure Resources: Get Azure Activity Log","azure_auth-get_auth_context":"Azure Auth: Get Auth Context","azure_auth-set_auth_context":"Azure Auth: Set Auth Context","ms-azuretools.azure-agent":"Azure Agent",manage_todo_list:"Manage TODO List",copilot_readFile:"Read File",copilot_viewImage:"Copilot View Image",opilot_findFiles:"Find Files",copilot_writeFile:"Write File",copilot_applyPatch:"Apply Patch",copilot_findTextInFiles:"Find Text In Files",copilot_findFiles:"Find Files",copilot_replaceString:"Replace String",copilot_createFile:"Create File",copilot_listDirectory:"List Directory",copilot_fetchWebPage:"Fetch Web Page",copilot_getErrors:"Get Errors",copilot_multiReplaceString:"Multi Replace String",copilot_searchCodebase:"Search Codebase",get_terminal_output:"Get Terminal Output",run_task:"Run Task: Investigate",await_terminal:"Await Terminal command","github.copilot.editsAgent":"GitHub Copilot Edits Agent",todoList:"TODO List",terminal:"Terminal",terminal_last_command:"Terminal Last Command",github_pull_request:"GitHub Pull Request",github_repo:"GitHub Repository",editFiles:"Edit Files",listFiles:"List Files",list_issues:"List Issues",search_subagent:"Search Subagent",execution_subagent:"Execution Subagent",apply_patch:"Apply Patch",ask_questions:"Ask Questions",AskUserQuestion:"Ask User Question",ask_user_question:"Ask User Question",copilot_askQuestions:"Ask Questions",copilot_createAndRunTask:"Create And Run Task",copilot_createDirectory:"Create Directory",copilot_createNewJupyterNotebook:"Create New Jupyter Notebook",copilot_createNewWorkspace:"Create New Workspace",copilot_editFiles:"Edit Files",copilot_editNotebook:"Edit Notebook",copilot_findTestFiles:"Find Test Files",copilot_getChangedFiles:"Get Changed Files",copilot_getDocInfo:"Get Doc Info",copilot_getNotebookSummary:"Get Notebook Summary",copilot_getProjectSetupInfo:"Get Project Setup Info",copilot_getSearchResults:"Get Search Results",copilot_getVSCodeAPI:"Get VSCode API",copilot_githubRepo:"GitHub Repository",copilot_githubTextSearch:"GitHub Text Search",copilot_resolveMemoryFileUri:"Resolve Memory File URI",copilot_insertEdit:"Insert Edit",copilot_installExtension:"Install Extension",copilot_memory:"Memory",copilot_openIntegratedBrowser:"Open Integrated Browser",copilot_openSimpleBrowser:"Open Simple Browser",copilot_readNotebookCellOutput:"Read Notebook Cell Output",copilot_readProjectStructure:"Read Project Structure",copilot_runNotebookCell:"Run Notebook Cell",copilot_runInTerminal:"Run In Terminal",copilot_runTests1:"Run Tests",copilot_runVscodeCommand:"Run VSCode Command",copilot_searchWorkspaceSymbols:"Search Workspace Symbols",copilot_switchAgent:"Switch Agent",copilot_testFailure:"Test Failure",copilot_toolReplay:"Tool Replay",create_and_run_task:"Create And Run Task",create_directory:"Create Directory",create_file:"Create File",remove_file:"Remove File",create_new_jupyter_notebook:"Create New Jupyter Notebook",create_new_workspace:"Create New Workspace",create_virtual_environment:"Create Virtual Environment",edit_files:"Edit Files",edit_file:"Edit File",edit_notebook_file:"Edit Notebook File",fetch_webpage:"Fetch Webpage",file_search:"File Search",get_changed_files:"Get Changed Files",get_doc_info:"Get Doc Info",get_errors:"Get Errors",get_project_setup_info:"Get Project Setup Info",get_files_in_project:"Get Files In Project",get_projects_in_solution:"Get Projects In Solution",configure_python_environment:"Configure Python Environment",get_python_executable_details:"Get Python Executable Details",get_search_view_results:"Get Search View Results",get_task_output:"Get Task Output",get_output_window_logs:"Get Output Window Logs",job_output:"Job Output",get_vscode_api:"Get VSCode API",grep_search:"Grep Search",insert_edit_into_file:"Insert Edit Into File",install_extension:"Install Extension",install_python_packages:"Install Python Packages",list_dir:"List Dir",list_directory:"List Directory",ls:"Ls",memory:"Memory",multi_replace_string_in_file:"Multi Replace String In File",open_integrated_browser:"Open Integrated Browser",open_simple_browser:"Open Simple Browser",read_file:"Read File",view_image:"View Image",read_notebook_cell_output:"Read Notebook Cell Output",read_project_structure:"Read Project Structure",replace_string_in_file:"Replace String In File","setup.agent":"Setup Agent",selectEnvironment:"Select Environment",run_notebook_cell:"Run Notebook Cell",run_vscode_command:"Run VSCode Command",runSubagent:"Run Subagent",renderMermaidDiagram:"Render Mermaid Diagram",runTests:"Run Tests",search_workspace_symbols:"Search Workspace Symbols",semantic_search:"Semantic Search",switch_agent:"Switch Agent",terminal_selection:"Terminal Selection",test_failure:"Test Failure",test_search:"Test Search",tool_replay:"Tool Replay",tool_search:"Tool Search",vscode_askQuestions:"VSCode Ask Questions",vscode_get_confirmation:"VSCode Get Confirmation",vscode_get_confirmation_with_options:"VSCode Get Confirmation With Options",vscode_get_terminal_confirmation:"VSCode Get Terminal Confirmation",vscode_get_modified_files_confirmation:"VSCode Get Modified Files Confirmation",vscode_listCodeUsages:"VSCode List Code Usages",vscode_renameSymbol:"VSCode Rename Symbol","mcp_io_github_ups_get-library-docs":"Context7 MCP: Get Library Docs","mcp_io_github_ups_query-docs":"Context7 MCP: Query Docs","mcp_io_github_ups_resolve-library-id":"Context7 MCP: Resolve Library ID","mcp_context7_get-library-docs":"Context7 MCP: Get Library Docs","mcp_context7_query-docs":"Context7 MCP: Query Docs","mcp_context7_resolve-library-id":"Context7 MCP: Resolve Library ID",mcp_microsoft_pla_browser_evaluate:"Playwright MCP: Browser Evaluate",mcp_microsoft_pla_browser_install:"Playwright MCP: Browser Install",mcp_microsoft_pla_browser_navigate:"Playwright MCP: Browser Navigate",mcp_microsoft_pla_browser_run_code:"Playwright MCP: Browser Run Code",mcp_microsoft_pla_browser_click:"Playwright MCP: Browser Click",mcp_microsoft_pla_browser_fill_form:"Playwright MCP: Browser Fill Form",mcp_microsoft_pla_browser_press_key:"Playwright MCP: Browser Press Key",mcp_microsoft_pla_browser_resize:"Playwright MCP: Browser Resize",mcp_microsoft_pla_browser_snapshot:"Playwright MCP: Browser Snapshot",mcp_microsoft_pla_browser_tabs:"Playwright MCP: Browser Tabs",mcp_microsoft_pla_browser_take_screenshot:"Playwright MCP: Browser Take Screenshot",mcp_microsoft_pla_browser_type:"Playwright MCP: Browser Type",mcp_microsoft_pla_browser_console_messages:"MCP Microsoft Playwright Browser Console Messages",mcp_microsoft_pla_browser_wait_for:"Mcp Microsoft Pla Browser Wait For",mcp_playwright_browser_click:"Playwright MCP: Browser Click",mcp_playwright_browser_navigate:"Playwright MCP: Browser Navigate",mcp_playwright_browser_snapshot:"Playwright MCP: Browser Snapshot",mcp_playwright_browser_take_screenshot:"Playwright MCP: Browser Take Screenshot","microsoft-playwright-mcp-browser_evaluate":"Playwright MCP: Browser Evaluate","microsoft-playwright-mcp-browser_navigate":"Playwright MCP: Browser Navigate","microsoft-playwright-mcp-browser_snapshot":"Playwright MCP: Browser Snapshot",mcp_pylance_mcp_s_pylanceDocString:"Pylance MCP: Pylance Doc String",mcp_pylance_mcp_s_pylanceRunCodeSnippet:"Pylance MCP: Run Code Snippet",mcp_pylance_mcp_s_pylanceWorkspaceRoots:"Pylance MCP: Workspace Roots",mcp_pylance_mcp_s_pylanceFileSyntaxErrors:"Pylance MCP: File Syntax Errors",mcp_pylance_mcp_s_pylanceSyntaxErrors:"Pylance MCP: Syntax Errors","mcp_chrome-devtoo_click":"Chrome DevTools MCP: Click","mcp_chrome-devtoo_evaluate_script":"Chrome DevTools MCP: Evaluate Script","mcp_chrome-devtoo_fill":"Chrome DevTools MCP: Fill","mcp_chrome-devtoo_get_network_request":"Chrome DevTools MCP: Get Network Request","mcp_chrome-devtoo_list_console_messages":"Chrome DevTools MCP: List Console Messages","mcp_chrome-devtoo_list_pages":"Chrome DevTools MCP: List Pages","mcp_chrome-devtoo_navigate_page":"Chrome DevTools MCP: Navigate Page","mcp_chrome-devtoo_new_page":"Chrome DevTools MCP: New Page","mcp_chrome-devtoo_select_page":"Chrome DevTools MCP: Select Page","mcp_chrome-devtoo_take_screenshot":"Chrome DevTools MCP: Take Screenshot","mcp_chrome-devtoo_fill_form":"Chrome DevTools MCP: Fill Form","mcp_chrome-devtoo_hover":"Chrome DevTools MCP: Hover","mcp_chrome-devtoo_list_network_requests":"Chrome DevTools MCP: List Network Requests","mcp_chrome-devtoo_press_key":"Chrome DevTools MCP: Press Key","mcp_chrome-devtoo_take_snapshot":"Chrome DevTools MCP: Take Snapshot","mcp_chrome-devtoo_wait_for":"Chrome DevTools MCP: Wait For","mcp_chrome-devtoo_close_page":"Chrome DevTools MCP: Close Page","mcp_chrome-devtoo_lighthouse_audit":"Chrome DevTools MCP: Lighthouse Audit","mcp_chrome-devtoo_performance_analyze_insight":"Chrome DevTools MCP: Performance Analyze Insight","mcp_chrome-devtoo_performance_start_trace":"Chrome DevTools MCP: Performance Start Trace","mcp_chrome-devtoo_resize_page":"Chrome DevTools MCP: Resize Page","mcp_chrome-devtoo_type_text":"Chrome DevTools MCP: Type Text",mcp_chrome_devtoo_click:"Chrome DevTools MCP: Click",mcp_chrome_devtoo_evaluate_script:"Chrome DevTools MCP: Evaluate Script",mcp_chrome_devtoo_fill:"Chrome DevTools MCP: Fill",mcp_chrome_devtoo_get_console_message:"Chrome DevTools MCP: Get Console Message",mcp_chrome_devtoo_get_network_request:"Chrome DevTools MCP: Get Network Request",mcp_chrome_devtoo_list_console_messages:"Chrome DevTools MCP: List Console Messages",mcp_chrome_devtoo_list_network_requests:"Chrome DevTools MCP: List Network Requests",mcp_chrome_devtoo_list_pages:"Chrome DevTools MCP: List Pages",mcp_chrome_devtoo_navigate_page:"Chrome DevTools MCP: Navigate Page",mcp_chrome_devtoo_new_page:"Chrome DevTools MCP: New Page",mcp_chrome_devtoo_take_snapshot:"Chrome DevTools MCP: Take Snapshot",mcp_chrome_devtoo_wait_for:"Chrome DevTools MCP: Wait For",mcp_io_github_chr_click:"Chrome DevTools MCP: Click",mcp_io_github_chr_emulate:"Chrome DevTools MCP: Emulate",mcp_io_github_chr_evaluate_script:"Chrome DevTools MCP: Evaluate Script",mcp_io_github_chr_list_network_requests:"Chrome DevTools MCP: List Network Requests",mcp_io_github_chr_list_pages:"Chrome DevTools MCP: List Pages",mcp_io_github_chr_navigate_page:"Chrome DevTools MCP: Navigate Page",mcp_io_github_chr_new_page:"Chrome DevTools MCP: New Page",mcp_io_github_chr_resize_page:"Chrome DevTools MCP: Resize Page",mcp_io_github_chr_select_page:"Chrome DevTools MCP: Select Page",mcp_io_github_chr_take_snapshot:"Chrome DevTools MCP: Take Snapshot",mcp_oraios_serena_activate_project:"Serena: Activate Project",mcp_oraios_serena_check_onboarding_performed:"Serena: Check Onboarding Performed",mcp_oraios_serena_create_text_file:"Serena: Create Text File",mcp_oraios_serena_delete_lines:"Serena: Delete Lines",mcp_oraios_serena_delete_memory:"Serena: Delete Memory",mcp_oraios_serena_edit_memory:"Serena: Edit Memory",mcp_oraios_serena_execute_shell_command:"Serena: Execute Shell Command",mcp_oraios_serena_find_file:"Serena: Find File",mcp_oraios_serena_find_referencing_symbols:"Serena: Find Referencing Symbols",mcp_oraios_serena_find_symbol:"Serena: Find Symbol",mcp_oraios_serena_get_current_config:"Serena: Get Current Config",mcp_oraios_serena_get_symbols_overview:"Serena: Get Symbols Overview",mcp_oraios_serena_initial_instructions:"Serena: Initial Instructions",mcp_oraios_serena_insert_after_symbol:"Serena: Insert After Symbol",mcp_oraios_serena_insert_at_line:"Serena: Insert At Line",mcp_oraios_serena_insert_before_symbol:"Serena: Insert Before Symbol",mcp_oraios_serena_jet_brains_find_referencing_symbols:"Serena: JetBrains Find Referencing Symbols",mcp_oraios_serena_jet_brains_find_symbol:"Serena: JetBrains Find Symbol",mcp_oraios_serena_jet_brains_get_symbols_overview:"Serena: JetBrains Get Symbols Overview",mcp_oraios_serena_jet_brains_type_hierarchy:"Serena: JetBrains Type Hierarchy",mcp_oraios_serena_list_dir:"Serena: List Dir",mcp_oraios_serena_list_memories:"Serena: List Memories",mcp_oraios_serena_onboarding:"Serena: Onboarding",mcp_oraios_serena_open_dashboard:"Serena: Open Dashboard",mcp_oraios_serena_prepare_for_new_conversation:"Serena: Prepare For New Conversation",mcp_oraios_serena_read_file:"Serena: Read File",mcp_oraios_serena_read_memory:"Serena: Read Memory",mcp_oraios_serena_remove_project:"Serena: Remove Project",mcp_oraios_serena_rename_symbol:"Serena: Rename Symbol",mcp_oraios_serena_replace_content:"Serena: Replace Content",mcp_oraios_serena_replace_lines:"Serena: Replace Lines",mcp_oraios_serena_replace_symbol_body:"Serena: Replace Symbol Body",mcp_oraios_serena_restart_language_server:"Serena: Restart Language Server",mcp_oraios_serena_search_for_pattern:"Serena: Search For Pattern",mcp_oraios_serena_summarize_changes:"Serena: Summarize Changes",mcp_oraios_serena_switch_modes:"Serena: Switch Modes",mcp_oraios_serena_think_about_collected_information:"Serena: Think About Collected Information",mcp_oraios_serena_think_about_task_adherence:"Serena: Think About Task Adherence",mcp_oraios_serena_think_about_whether_you_are_done:"Serena: Think About Whether You Are Done",mcp_oraios_serena_write_memory:"Serena: Write Memory","mcp_visuals-mcp_display_image":"Visuals MCP: Display Image","mcp_laravel-boost_tinker":"Laravel Boost MCP: Tinker",bash:"Bash",Bash:"Bash",code_search:"Code Search",detect_memories:"Detect Memories",dismiss_deployment_notifications:"Dismiss Deployment Notifications",get_currentfile:"Get Current File",get_file:"Get File",get_symbols_by_name:"Get Symbols By Name","claude-code":"Claude Code","copilot-cloud-agent":"Copilot Cloud Agent",agent:"Agent",copilotcli:"Copilot CLI","github.copilot.default":"GitHub Copilot Default","github.copilot.workspace":"GitHub Copilot Workspace","github.copilot.vscode":"GitHub Copilot VSCode","github.copilot-dynamic.platform":"GitHub Copilot Dynamic: Platform",glob:"Glob",file_glob_search:"File Glob Search",grep:"Grep",kill_terminal:"Kill Terminal",read:"Read",view:"View",vscode_editFile_internal:"VSCode Edit File (Internal)",vscode_fetchWebPage_internal:"VSCode Fetch Web Page (Internal)",vscode_searchExtensions_internal:"VSCode Search Extensions (Internal)","vscode-websearchforcopilot_webSearch":"VSCode WebSearch for Copilot: Web Search",Build_CMakeTools:"CMake Tools: Build",ListBuildTargets_CMakeTools:"CMake Tools: List Build Targets",ListTests_CMakeTools:"CMake Tools: List Tests",RunCtest_CMakeTools:"CMake Tools: Run CTest","nuget_get-nuget-solver":"NuGet: Get NuGet Solver",webfetch:"Web Fetch",web_fetch:"Web Fetch",write:"Write",edit:"Edit",search_replace:"Search Replace",write_file:"Write File",multiedit:"Multi Edit",question:"Question",skill:"Skill",read_skill:"Read Skill",task:"Task",todowrite:"Todo Write",TodoWrite:"Todo Write",todos:"Todos",todo:"Todo",websearch:"Web Search",WebSearch:"Web Search",click_element:"Click Element",navigate_page:"Navigate Page",open_browser_page:"Open Browser Page",read_page:"Read Page",run_playwright_code:"Run Playwright Code",screenshot_page:"Screenshot Page",type_in_page:"Type in Page",task_complete:"Task Complete","pdf-utilities.pdf":"PDF Utilities: PDF","container-tools_get-config":"Container Tools: Get Config","github-pull-request_activePullRequest":"GitHub Pull Request: Active Pull Request","github-pull-request_currentActivePullRequest":"GitHub Pull Request: Current Active Pull Request","github-pull-request_issue_fetch":"GitHub Pull Request: Issue Fetch","github-pull-request_pullRequestStatusChecks":"GitHub Pull Request: Pull Request Status Checks","github-pull-request_pullRequestInViewport":"GitHub MCP (Remote): Pull Request In Viewport","mcp_powerbi-model_connection_operations":"Power BI MCP: Connection Operations",MiniMax_web_search:"MiniMax: Web Search",dingDocuments_get_document_content:"Ding Documents: Get Document Content",dingDocuments_list_nodes:"Ding Documents: List Nodes",dingDocuments_search_documents:"Ding Documents: Search Documents",fetch_fetch:"Fetch: Fetch",mcp__Claude_in_Chrome__computer:"Claude in Chrome MCP: Computer",mcp__Claude_in_Chrome__navigate:"Claude in Chrome MCP: Navigate",mcp__Claude_in_Chrome__browser_batch:"Claude in Chrome MCP: Browser Batch",mcp__Claude_in_Chrome__get_page_text:"Claude in Chrome MCP: Get Page Text",mcp__Claude_in_Chrome__tabs_context_mcp:"Claude in Chrome MCP: Tabs Context",mcp__Claude_in_Chrome__tabs_create_mcp:"Claude in Chrome MCP: Tabs Create",mcp__Claude_in_Chrome__javascript_tool:"Claude in Chrome MCP: Javascript Tool",mcp__Claude_in_Chrome__read_console_messages:"Claude in Chrome MCP: Read Console Messages",mcp__Claude_in_Chrome__read_network_requests:"Claude in Chrome MCP: Read Network Requests",mcp__Claude_in_Chrome:"Claude in Chrome MCP",mcp__Claude_in_Chrome__find:"Claude in Chrome MCP: Find",mcp__Claude_in_Chrome__form_input:"Claude in Chrome MCP: Form Input",mcp__Claude_in_Chrome__list_connected_browsers:"Claude in Chrome MCP: List Connected Browsers",mcp__Claude_in_Chrome__read_page:"Claude in Chrome MCP: Read Page",mcp__Claude_in_Chrome__select_browser:"Claude in Chrome MCP: Select Browser",mcp__cowork__allow_cowork_file_delete:"Cowork MCP: Allow Cowork File Delete",mcp__cowork__present_files:"Cowork MCP: Present Files",mcp__cowork__request_cowork_directory:"Cowork MCP: Request Cowork Directory","mcp__cowork-onboarding__show_onboarding_role_picker":"Cowork Onboarding MCP: Show Onboarding Role Picker",TaskOutput:"Task Output",TaskStop:"Task Stop",mcp__plugins__search_plugins:"Plugins MCP: Search Plugins",mcp__plugins__suggest_plugin_install:"Plugins MCP: Suggest Plugin Install",mcp__workspace__bash:"Workspace MCP: Bash",mcp__workspace__web_fetch:"Workspace MCP: Web Fetch","mcp__mcp-registry__search_mcp_registry":"MCP Registry: Search MCP Registry",Agent:"Agent",Edit:"Edit",Glob:"Glob",Grep:"Grep",NotebookEdit:"Notebook Edit",Read:"Read",Skill:"Skill",TaskCreate:"Task Create",TaskUpdate:"Task Update",ToolSearch:"Tool Search",Write:"Write","mcp__claude_ai_Context7__resolve-library-id":"Context7 MCP (Claude): Resolve Library ID",mcp__claude_ai_Excalidraw__create_view:"Excalidraw MCP (Claude): Create View",mcp__claude_ai_Excalidraw__read_me:"Excalidraw MCP (Claude): Read Me","mcp__claude_ai_Notion__notion-create-pages":"Notion MCP (Claude): Create Pages","mcp__claude_ai_Notion__notion-fetch":"Notion MCP (Claude): Fetch","mcp__claude_ai_Notion__notion-search":"Notion MCP (Claude): Search","mcp__claude_ai_Notion__notion-update-page":"Notion MCP (Claude): Update Page","mcp__context7__query-docs":"Context7 MCP: Query Docs","mcp__context7__resolve-library-id":"Context7 MCP: Resolve Library ID","mcp__databricks-sql-allscopes__authenticate":"Databricks SQL MCP: Authenticate","mcp__databricks-sql-allscopes__complete_authentication":"Databricks SQL MCP: Complete Authentication","mcp__databricks-sql__authenticate":"Databricks SQL MCP: Authenticate",mcp__playwright__browser_evaluate:"Playwright MCP: Browser Evaluate",mcp__playwright__browser_navigate:"Playwright MCP: Browser Navigate","mcp__plugin_context7_context7__query-docs":"Context7 MCP: Query Docs","mcp__plugin_context7_context7__resolve-library-id":"Context7 MCP: Resolve Library ID","mcp__shopify-dev-mcp__learn_shopify_api":"Shopify Dev MCP: Learn Shopify API","mcp__shopify-dev-mcp__search_docs_chunks":"Shopify Dev MCP: Search Docs Chunks","mcp__shopify-dev-mcp__validate_graphql_codeblocks":"Shopify Dev MCP: Validate GraphQL Codeblocks",invalid:"Invalid",rename_session:"Rename Session",update_topic:"Update Topic",rename_branch:"Rename Branch",report_intent:"Report Intent",create_pull_request:"Create Pull Request",update_pull_request:"Update Pull Request",powershell:"PowerShell",ask_user:"Ask User",sql:"SQL",show_file:"Show File",exit_plan_mode:"Exit Plan Mode",get_changes_overview:"Get Changes Overview",annotate_diff_line:"Annotate Diff",add_pr_review_comment:"Add PR Review Comment",remove_pr_review_comment:"Remove PR Review Comment",reply_to_comment:"Reply to Comment",open_pr_session:"Open PR Session",open_issue_session:"Open Issue Session",create_session:"Create Session",list_sessions_and_chats:"List Sessions & Chats",list_projects:"List Projects",get_session:"Get Session",navigate_to:"Navigate To",delete_item:"Delete Item",send_session_message:"Send Session Message",send_chat_message:"Send Chat Message",read_agent:"Read Agent",write_agent:"Write Agent",list_agents:"List Agents",discover_widgets:"Discover Widgets",render_widget:"Render Widget",clear_widget:"Clear Widget",extensions_manage:"Extensions Manage",extensions_reload:"Extensions Reload",create:"Create",fetch_copilot_cli_documentation:"Fetch Copilot CLI Documentation",generate_findings:"Generate Findings",generate_topics:"Generate Topics",list_bash:"List Bash",read_bash:"Read Bash",write_bash:"Write Bash",stop_bash:"Stop Bash",list_powershell:"List PowerShell",read_powershell:"Read PowerShell",render_widget_inbox:"Render Widget Inbox",rg:"Ripgrep",stop_powershell:"Stop PowerShell",store_memory:"Store Memory",web_search:"Web Search",write_powershell:"Write PowerShell",slidev_chooseEntry:"Slidev: Choose Entry",slidev_getPreviewPort:"Slidev: Get Preview Port",clarify_requirements:"Clarify Requirements",get_tests:"Get Tests","ide-get_diagnostics":"IDE: Get Diagnostics","ide-get_selection":"IDE: Get Selection",plan:"Plan",signal_plan_ready:"Signal Plan Ready",update_plan_progress:"Update Plan Progress",EnterPlanMode:"Enter Plan Mode",ExitPlanMode:"Exit Plan Mode",mcp_reload:"MCP: Reload",mcp_validate:"MCP: Validate",stop_agent:"Stop Agent","workiq-accept_eula":"WorkIQ: Accept EULA","workiq-ask_work_iq":"WorkIQ: Ask Work IQ","mcp_ado-remote-mc_core_list_projects":"Azure DevOps MCP: Core List Projects","mcp_ado-remote-mc_repo_branch":"Azure DevOps MCP: Repo Branch","mcp_ado-remote-mc_repo_pull_request":"Azure DevOps MCP: Repo Pull Request","mcp_ado-remote-mc_repo_pull_request_thread":"Azure DevOps MCP: Repo Pull Request Thread","mcp_ado-remote-mc_repo_pull_request_write":"Azure DevOps MCP: Repo Pull Request Write","mcp_ado-remote-mc_repo_repository":"Azure DevOps MCP: Repo Repository","mcp_ado-remote-mc_search_workitem":"Azure DevOps MCP: Search Work Item","mcp_ado-remote-mc_wit_get_work_item":"Azure DevOps MCP: Get Work Item","mcp_ado-remote-mc_wit_work_item":"Azure DevOps MCP: Work Item","mcp_ado-remote-mc_wit_work_item_comment_write":"Azure DevOps MCP: Work Item Comment Write","mcp_ado-remote-mc_wit_work_item_link_write":"Azure DevOps MCP: Work Item Link Write","mcp_ado-remote-mc_wit_work_item_write":"Azure DevOps MCP: Work Item Write",mssql_list_servers:"MSSQL: List Servers",add_loaded_assembly:"Add Loaded Assembly",analyze_symbol:"Analyze Symbol",search_decompiled_symbols:"Search Decompiled Symbols",get_classification_rubric:"Get Classification Rubric",get_weather:"Get Weather",mcp_azure_mcp_search:"Azure MCP: Search",mcp_gitnexus_context:"GitNexus MCP: Context",mcp_gitnexus_cypher:"GitNexus MCP: Cypher",mcp_gitnexus_detect_changes:"GitNexus MCP: Detect Changes",mcp_gitnexus_impact:"GitNexus MCP: Impact",mcp_gitnexus_list_repos:"GitNexus MCP: List Repos",mcp_gitnexus_query:"GitNexus MCP: Query",slidev_getSlideContent:"Slidev: Get Slide Content",mcp__GitLab__get_mcp_server_version:"GitLab MCP: Get MCP Server Version",mcp__plugin_figma_figma__get_design_context:"Figma MCP: Get Design Context",mcp__plugin_figma_figma__get_metadata:"Figma MCP: Get Metadata",mcp__plugin_figma_figma__get_screenshot:"Figma MCP: Get Screenshot",mcp_io_github_tav_tavily_extract:"MCP Io GitHub Tavily Extract",mcp_io_github_tav_tavily_search:"MCP Io GitHub Tavily Search",browser_wait_for:"Browser Wait For",copilot_sessionStoreSql:"Copilot Session Store Sql",explore_subagent:"Explore Subagent","github.copilot.terminalPanel":"Github Copilot Terminal Panel",handle_dialog:"Handle Dialog",run_subagent:"Run Subagent",testFailure:"Test Failure","mcp_angular-cli_get_best_practices":"Angular MCP: Get Best Practices","mcp_angular-cli_list_projects":"Angular MCP: Get Project List",mcp_azure_mcp_extension_cli_generate:"Azure MCP (Local): Generate",mcp_playwright_browser_console_messages:"Playwright MCP: Browser Console Messages",mcp_com_figma_mcp_get_design_context:"Figma MCP (Local): Get Design Context",mcp_com_figma_mcp_get_screenshot:"Figma MCP (Local): Get Screenshot",mcp__Bicep__get_bicep_best_practices:"Bicep MCP: Get Bicep Best Practices","mcp__microsoft-docs-learn__microsoft_docs_fetch":"Microsoft Learn MCP: Microsoft Docs Fetch","mcp__microsoft-docs-learn__microsoft_docs_search":"Microsoft Learn MCP: Microsoft Docs Search",mcp__azure__subscription_list:"Azure MCP: Subscription List",mcp__bicep__get_bicep_file_diagnostics:"Bicep MCP: File Diagnostics",mcp__linear__authenticate:"Linear MCP: Authenticate",mcp__linear__get_issue:"Linear MCP: Get Issue",mcp__linear__list_issues:"Linear MCP: List Issues",mcp__linear__list_teams:"Linear MCP: List Teams",mcp__linear__save_issue:"Linear MCP: Save Issue",mcp_workiq_accept_eula:"WorkIQ Accept EULA",mcp_workiq_ask_work_iq:"WorkIQ Ask Work IQ","mcp_microsoft-lea_microsoft_code_sample_search":"Microsoft Docs MCP (Local): Search Code Sample","mcp_microsoft-lea_microsoft_docs_search":"Microsoft Docs MCP (Remote): Search Docs","mcp_upstash_conte_query-docs":"MCP Upstash: Query Docs","mcp_upstash_conte_resolve-library-id":"MCP Upstash: Resolve Library ID",mcp__Bicep__list_avm_metadata:"MCP Bicep: List Azure Verified Module Metadata",google_research:"Google Research",task_execution:"Task Execution",tool_search_tool_regex:"Tool Search",FindDatabaseObjectsThat:"Find Database Objects That",GetTableColumnNames:"Get Table Column Names",SchemaStore_getSchema:"Schema Store Get Schema",SchemaStore_searchSchemas:"Schema Store Search Schemas",SearchSchemasForOnePartName:"Search Schemas For One Part Name",ValidateGeneratedTSQL:"Validate Generated T-SQL",aspire_execute_resource_command:"Aspire Execute Resource Command",aspire_get_doc:"Aspire Get Doc",aspire_list_console_logs:"Aspire List Console Logs",aspire_list_resources:"Aspire List Resources",aspire_list_structured_logs:"Aspire List Structured Logs",aspire_search_docs:"Aspire Search Docs",codesearch:"CodeSearch","context-engine_context_search":"Context Engine Context Search","context7_query-docs":"Context7 Query Docs","context7_resolve-library-id":"Context7 Resolve Library ID",playwright_browser_navigate:"Playwright Browser Navigate",run_tests:"Run Tests","azure-subscription_list":"Azure Subscription List",debugger_evaluate_expressions:"Debugger Evaluate Expressions",debugger_get_output_window_text:"Debugger Get Output Window Text",get_symbols:"Get Symbols",lookup_vs:"Lookup VS",search_web:"Search Web","aspire-get_doc":"Get Doc","aspire-search_docs":"Search Docs",vote_memory:"Vote Memory",create_issue:"Issue Create",save_workflow:"Workflow Save","context-mode_ctx_execute":"Context Mode: Execute","mcp_context-mode_ctx_batch_execute":"Context Mode: Batch Execute","mcp_context-mode_ctx_execute":"Context Mode: Execute","mcp_context-mode_ctx_search":"Context Mode: Search",mcp_github_issue_read:"GitHub MCP (Remote): Issue Read",mcp_github_search_repositories:"GitHub MCP (Remote): Search Repositories",mcp_io_github_tav_tavily_map:"Tavily MCP: Map","mcp_lean-ctx_ctx_call":"Lean Context: Call","mcp_lean-ctx_ctx_discover_tools":"Lean Context: Discover Tools","mcp_lean-ctx_ctx_edit":"Lean Context: Edit","mcp_lean-ctx_ctx_graph":"Lean Context: Graph","mcp_lean-ctx_ctx_knowledge":"Lean Context: Knowledge","mcp_lean-ctx_ctx_multi_read":"Lean Context: Multi Read","mcp_lean-ctx_ctx_overview":"Lean Context: Overview","mcp_lean-ctx_ctx_read":"Lean Context: Read","mcp_lean-ctx_ctx_search":"Lean Context: Search","mcp_lean-ctx_ctx_session":"Lean Context: Session","mcp_lean-ctx_ctx_shell":"Lean Context: Shell","mcp_lean-ctx_ctx_tree":"Lean Context: Tree","mcp_mcp-server-ti_get_current_time":"Time MCP: Get Current Time",mcp_playwright_browser_close:"Playwright MCP: Browser Close",mcp_playwright_browser_evaluate:"Playwright MCP: Browser Evaluate",mcp_playwright_browser_fill_form:"Playwright MCP: Browser Fill Form",mcp_playwright_browser_network_request:"Playwright MCP: Browser Network Request",mcp_playwright_browser_network_requests:"Playwright MCP: Browser Network Requests",mcp_playwright_browser_press_key:"Playwright MCP: Browser Press Key",mcp_playwright_browser_resize:"Playwright MCP: Browser Resize",mcp_playwright_browser_run_code_unsafe:"Playwright MCP: Browser Run Code Unsafe",mcp_playwright_browser_type:"Playwright MCP: Browser Type",mcp_playwright_browser_wait_for:"Playwright MCP: Browser Wait For",mcp_pylance_mcp_s_pylancePythonEnvironments:"Pylance MCP: Python Environments","mcp_spec-gen_get_architecture_overview":"Spec Gen MCP: Get Architecture Overview","mcp_spec-gen_get_call_graph":"Spec Gen MCP: Get Call Graph",mcp_specgen_analyze_codebase:"Spec Gen MCP: Analyze Codebase",mcp_specgen_get_function_body:"Spec Gen MCP: Get Function Body",mcp_specgen_get_spec:"Spec Gen MCP: Get Spec",mcp_specgen_list_spec_domains:"Spec Gen MCP: List Spec Domains",mcp_specgen_orient:"Spec Gen MCP: Orient",mcp_specgen_search_code:"Spec Gen MCP: Search Code",mcp_specgen_search_specs:"Spec Gen MCP: Search Specs",mcp_stitch_apply_design_system:"Stitch: Apply Design System",mcp_stitch_create_design_system:"Stitch: Create Design System",mcp_stitch_create_project:"Stitch: Create Project",mcp_stitch_edit_screens:"Stitch: Edit Screens",mcp_stitch_generate_screen_from_text:"Stitch: Generate Screen From Text",mcp_stitch_get_project:"Stitch: Get Project",mcp_stitch_get_screen:"Stitch: Get Screen",mcp_stitch_list_design_systems:"Stitch: List Design Systems",mcp_stitch_list_projects:"Stitch: List Projects",mcp_stitch_list_screens:"Stitch: List Screens",mcp_symdex_build_context_pack:"Symdex: Build Context Pack",mcp_symdex_get_callees:"Symdex: Get Callees",mcp_symdex_get_callers:"Symdex: Get Callers",mcp_symdex_get_file_outline:"Symdex: Get File Outline",mcp_symdex_get_file_tree:"Symdex: Get File Tree",mcp_symdex_get_graph_diagram:"Symdex: Get Graph Diagram",mcp_symdex_get_index_status:"Symdex: Get Index Status",mcp_symdex_get_repo_outline:"Symdex: Get Repo Outline",mcp_symdex_get_repo_stats:"Symdex: Get Repo Stats",mcp_symdex_index_folder:"Symdex: Index Folder",mcp_symdex_list_repos:"Symdex: List Repos",mcp_symdex_search_routes:"Symdex: Search Routes",mcp_symdex_search_symbols:"Symdex: Search Symbols",mcp_symdex_search_text:"Symdex: Search Text",mcp_tavily_tavily_crawl:"Tavily: Crawl",mcp_tavily_tavily_extract:"Tavily: Extract",mcp_tavily_tavily_search:"Tavily: Search",mcp_time_get_current_time:"Time: Get Current Time",mcp_trueline_trueline_outline:"Trueline: Outline",mcp_trueline_trueline_read:"Trueline: Read",mcp_trueline_trueline_search:"Trueline: Search",mcp_zettelkasten_zk_create_link:"Zettelkasten: Create Link",mcp_zettelkasten_zk_create_note:"Zettelkasten: Create Note",mcp_zettelkasten_zk_get_note:"Zettelkasten: Get Note",mcp_zettelkasten_zk_remove_link:"Zettelkasten: Remove Link",mcp_zettelkasten_zk_search_notes:"Zettelkasten: Search Notes",mcp_zettelkasten_zk_update_note:"Zettelkasten: Update Note",copilot_listCodeUsages:"Copilot: List Code Usages",create_new_file:"Windsurf: File Create",edit_existing_file:"Windsurf: File Edit","github.copilot.editingSession":"GitHub MCP (Local): Assign Copilot to Issue",mssql_connect:"SQL Server Connection",mssql_disconnect:"SQL Server Disconnection",mssql_list_tables:"SQL Server Tables List",mssql_run_query:"SQL Server Query Execution",run_terminal_command:"Terminal Command Run",single_find_and_replace:"Find and Replace",mcp_io_github_git_add_comment_to_pending_review:"GitHub MCP (Local): Add Comment To Pending Review",mcp_io_github_git_add_reply_to_pull_request_comment:"GitHub MCP (Local): Add Reply To Pull Request Comment",mcp_io_github_git_pull_request_review_write:"GitHub MCP (Local): Pull Request Review Write",mcp_aikido_aikido_full_scan:"Aikido MCP: Full Scan",mcp_aikido_aikido_issues_list:"Aikido MCP: Issues List",mcp_com_atlassian_addCommentToJiraIssue:"Atlassian MCP: Add Comment To Jira Issue",mcp_com_atlassian_atlassianUserInfo:"Atlassian MCP: User Info",mcp_com_atlassian_createConfluencePage:"Atlassian MCP: Create Confluence Page",mcp_com_atlassian_getAccessibleAtlassianResources:"Atlassian MCP: Get Accessible Atlassian Resources",mcp_com_atlassian_getConfluencePage:"Atlassian MCP: Get Confluence Page",mcp_com_atlassian_getConfluencePageFooterComments:"Atlassian MCP: Get Confluence Page Footer Comments",mcp_com_atlassian_getConfluenceSpaces:"Atlassian MCP: Get Confluence Spaces",mcp_com_atlassian_getJiraIssue:"Atlassian MCP: Get Jira Issue",mcp_com_atlassian_search:"Atlassian MCP: Search",mcp_com_atlassian_searchJiraIssuesUsingJql:"Atlassian MCP: Search Jira Issues Using JQL",mcp_com_atlassian_updateConfluencePage:"Atlassian MCP: Update Confluence Page",mcp_sonarqube_analyze_code_snippet:"SonarQube MCP: Analyze Code Snippet",mcp_sonarqube_get_project_quality_gate_status:"SonarQube MCP: Get Project Quality Gate Status",mcp_sonarqube_search_my_sonarqube_projects:"SonarQube MCP: Search My SonarQube Projects",mcp_sonarqube_search_security_hotspots:"SonarQube MCP: Search Security Hotspots",mcp_sonarqube_search_sonar_issues_in_projects:"SonarQube MCP: Search Sonar Issues In Projects",sonarqube_analyze_file:"SonarQube: Analyze File","azure-bicepschema":"Azure Bicep Schema","azure-documentation":"Azure Documentation","azure-extension_cli_generate":"Azure Extension CLI Generate","azure-get_azure_bestpractices":"Get Azure Best Practices",__auto_compact__:"Auto Compact",mcp_github_get_teams:"GitHub MCP (Remote): Get Teams",mcp_github_list_issue_types:"GitHub MCP (Remote): List Issue Types",mcp_github_mcp_se_issue_write:"GitHub MCP (Remote): Write Issue",mcp_github_mcp_se_list_issues:"GitHub MCP (Remote): List Issues",mcp_github_mcp_se_list_label:"GitHub MCP (Remote): List Labels",mcp_github_mcp_se_search_issues:"GitHub MCP (Remote): Search Issues",mcp_github_mcp_se_add_issue_comment:"GitHub MCP (Remote): Add Comment to Issue",mcp_github_mcp_se_create_pull_request:"GitHub MCP (Remote): Create Pull Request",mcp_github_mcp_se_get_file_contents:"GitHub MCP (Remote): Get File Contents",mcp_github_mcp_se_pull_request_read:"GitHub MCP (Remote): Read Pull Request",mcp_github_mcp_se_issue_read:" GitHub MCP (Remote): Issue Read on GitHub",mcp_github_search_users:"GitHub MCP (Remote): Search Users",mcp_github_semantic_issue_similarity_search:"GitHub MCP (Remote): Semantic Issue Similarity Search",codebase:"Codebase",invoke_subagent:"Invoke Subagent",list_permissions:"List Permissions",manage_task:"Manage Task",mcp__ccd_session__mark_chapter:"CCD Session: Mark Chapter",multi_replace_file_content:"Multi-Replace File Content",read_currently_open_file:"Read Currently Open File",replace_file_content:"Replace File Content",run_command:"Run Command",schedule:"Schedule",send_message:"Send Message",view_file:"View File",write_to_file:"Write To File",glob_search:"Glob Search","azure-devops_core_list_projects":"Azure DevOps Core List Projects","azure-devops_repo_get_file_content":"Azure DevOps Repo Get File Content","azure-devops_repo_list_repos_by_project":"Azure DevOps Repo List Repos By Project","azure-devops_search_code":"Azure DevOps Search Code","azure-devops_wit_get_work_item":"Azure DevOps Wit Get Work Item","azure-devops_wit_query_by_wiql":"Azure DevOps Wit Query By WIQL",mcp_microsoft_azu_wit_get_work_items_batch_by_ids:"Microsoft Azure DevOps MCP (Local): Get Work Items Batch by IDs",mcp_microsoft_azu_wit_get_work_items_for_iteration:"Microsoft Azure DevOps MCP (Local): Get Work Items for Iteration",mcp_microsoft_azu_wit_update_work_items_batch:"Microsoft Azure DevOps MCP (Local): Update Work Items Batch",mcp_microsoft_azu_wit_work_items_link:"Microsoft Azure DevOps MCP (Local): Link Work Items",mcp_microsoft_azu_work_list_iterations:"Microsoft Azure DevOps MCP (Local): List Iterations","microsoft_azure-devops-mcp_core_list_projects":"Azure DevOps Core List Projects","microsoft_azure-devops-mcp_search_workitem":"Azure DevOps Search Work Item","microsoft_azure-devops-mcp_wit_get_work_item":"Microsoft Azure DevOps MCP (Local): Get Work Item",mcp_com_microsoft_get_azure_bestpractices:"Microsoft Docs MCP: Get Azure Best Practices",mcp_github_enterp_create_branch:"GitHub MCP (Remote): Create Branch",mcp_github_enterp_get_latest_release:"GitHub MCP (Remote): Get Latest Release",mcp_github_enterp_pull_request_read:"GitHub MCP (Remote): Pull Request Read",handoff:"Handoff",mcp_ado_search_workitem:"ADO Search Workitem",mcp_ado_wit_add_artifact_link:"ADO Wit Add Artifact Link",mcp_ado_wit_add_child_work_items:"ADO Wit Add Child Work Items",mcp_ado_wit_add_work_item_comment:"ADO Wit Add Work Item Comment",mcp_ado_wit_create_work_item:"ADO Wit Create Work Item",mcp_ado_wit_get_work_item:"ADO Wit Get Work Item",mcp_ado_wit_get_work_item_type:"MCP Ado Wit Get Work Item Type",mcp_ado_wit_get_work_items_batch_by_ids:"MCP Ado Wit Get Work Items Batch By Ids",mcp_ado_wit_list_work_item_comments:"ADO Wit List Work Item Comments",mcp_ado_wit_my_work_items:"ADO Wit My Work Items",mcp_ado_wit_update_work_item:"ADO Wit Update Work Item",mcp_ado_wit_update_work_items_batch:"ADO Wit Update Work Items Batch",mcp_ado_wit_work_item_unlink:"ADO Wit Work Item Unlink",mcp_ado_wit_work_items_link:"ADO Wit Work Items Link",mcp_azure_devops__search_workitem:"Azure DevOps Search Workitem",mcp_github_add_issue_comment:"GitHub Add Issue Comment",mcp_github_create_branch:"GitHub Create Branch",mcp_github_list_commits:"GitHub List Commits",mcp_github_list_pull_requests:"GitHub List Pull Requests",mcp_github_push_files:"GitHub Push Files","mcp_hashline-edit_grep":"Hashline Edit Grep",mcp_raindrop_create_bookmarks:"RainDrop Create Bookmarks","mcp_symdex-mcp_semantic_search":"Symdex MCP Semantic Search","mcp_tavily-global_tavily-search":"Tavily Global Tavily-Search","mcp_tavily_tavily-extract":"Tavily Tavily-Extract","mcp_tavily_tavily-search":"Tavily Tavily-Search",mcp_tavily_tavily_research:"Tavily Tavily-Research",session_store_sql:"SQL Session Store","azure-advisor":"Azure Advisor","azure-devops-core_list_projects":"Azure DevOps Core List Projects","azure-devops-wit_work_item":"Azure DevOps Work Item","azure-devops-wit_work_item_write":"Azure DevOps Work Item Write","azure-group_resource_list":"Azure Group Resource List","azure-sql":"Azure SQL",ScheduleWakeup:"Scheduled Wakeup",mcp__ccd_session__spawn_task:"Spawn Task",mcp_figma_mcp_ser_get_design_context:"Figma MCP (Local): Get Design Context",mcp_figma_mcp_ser_get_libraries:"Figma MCP (Local): Get Libraries",mcp_figma_mcp_ser_get_metadata:"Figma MCP (Local): Get Metadata",mcp_figma_mcp_ser_search_design_system:"Figma MCP (Local): Search Design System","azure-devops-repo_file":"Azure DevOps: File","azure-devops-repo_pull_request":"Azure DevOps: Pull Request","azure-devops-repo_repository":"Azure DevOps: Repository","azure-devops-search_code":"Azure DevOps: Search Code","azure-devops-search_workitem":"Azure DevOps: Work Item","azure-devops-wiki":"Azure DevOps: Wiki","azure-devops-wiki_upsert_page":"Azure DevOps: Wiki Upsert Page","azure-devops-wit_work_item_comment_write":"Azure DevOps: Work Item Comment Write",invoke_canvas_action:"Canvas Action",list_canvas_capabilities:"List Canvas Capabilities",open_canvas:"Open Canvas",subagent:"Subagent",workiq_search_files:"WorkIQ Search Files",workiq_get_email:"Workiq Get Email",workiq_list_emails:"Workiq List Emails",github_text_search:"GitHub MCP (Local): Text Search",mcp_azure_mcp_ser_search:"Azure MCP (Remote): Search","azure_mcp-documentation":"Azure MCP Documentation",mcp_azure_mcp_ser_get_azure_bestpractices:"Serena MCP: Get Azure Best Practices",find:"Find","get-syntax-docs-mermaid":"Mermaid Syntax Docs","mermaid-chart":"Mermaid Chart","mermaid-diagram-preview":"Mermaid Diagram Preview","mermaid-diagram-validator":"Mermaid Diagram Validator",sonarqube_list_potential_security_issues:"SonarQube List Potential Security Issues",m_filesystem_tree:"File System Tree",m_get_settings:"Get Settings",m_get_skill:"Get Skill",m_list_skills:"List Skills",find_symbol:"Find Symbol",finish_plan:"Finish Plan",jcodemunch_file_outline:"JCodeMunch File Outline",jcodemunch_find_references:"JCodeMunch Find References",jcodemunch_get_file_content:"JCodeMunch Get File Content",jcodemunch_get_session_stats:"JCodeMunch Get Session Stats",jcodemunch_get_symbol_source:"JCodeMunch Get Symbol Source",jcodemunch_list_repos:"JCodeMunch List Repos",jcodemunch_search_symbols:"JCodeMunch Search Symbols",jcodemunch_search_text:"JCodeMunch Search Text","mcp_jcodemunch-mc_check_references":"JCodeMunch MCP (Local): Check References","mcp_jcodemunch-mc_find_references":"JCodeMunch MCP (Local): Find References","mcp_jcodemunch-mc_get_file_outline":"JCodeMunch MCP (Local): Get File Outline","mcp_jcodemunch-mc_index_folder":"JCodeMunch MCP (Local): Index Folder","mcp_jcodemunch-mc_list_repos":"JCodeMunch MCP (Local): List Repos","mcp_jcodemunch-mc_plan_turn":"JCodeMunch MCP (Local): Plan Turn","mcp_jcodemunch-mc_search_symbols":"JCodeMunch MCP (Local): Search Symbols","mcp_jcodemunch-mc_winnow_symbols":"JCodeMunch MCP (Local): Winnow Symbols",search_text:"Search Text",ask_question:"Ask Question",create_cpp_performance_test:"Create C++ Performance Test",debugger_continue:"Debug Continue",debugger_get_call_stack:"Debug Get Call Stack",debugger_get_frame_source:"Debug Get Frame Source",debugger_get_threads:"Debug Get Threads",debugger_launch_unit_test:"Debug Launch Unit Test","foundrytk-get_ai_model_guidance":"Foundry: AI Model Guidance","foundrytk-usage_guidance":"Foundry: Usage Guidance","mcp_atlassian-mcp_addCommentToJiraIssue":"Atlassian MCP (Local): Add Comment to Jira Issue","mcp_atlassian-mcp_atlassianUserInfo":"Atlassian MCP (Local): Get User Info","mcp_atlassian-mcp_createJiraIssue":"Atlassian MCP (Local): Create/Update Jira Issue","mcp_atlassian-mcp_editJiraIssue":"Atlassian MCP (Local): Edit Jira Issue","mcp_atlassian-mcp_getAccessibleAtlassianResources":"Atlassian MCP (Local): Get Accessible Resources","mcp_atlassian-mcp_getJiraIssue":"Atlassian MCP (Local): Get Jira Issue","mcp_atlassian-mcp_getJiraIssueTypeMetaWithFields":"Atlassian MCP (Local): Get Jira Issue Type Meta with Fields","mcp_atlassian-mcp_getJiraProjectIssueTypesMetadata":"Atlassian MCP (Local): Get Jira Project Issue Types Metadata","mcp_atlassian-mcp_getTransitionsForJiraIssue":"Atlassian MCP (Local): Get Transitions for Jira Issue","mcp_atlassian-mcp_getVisibleJiraProjects":"Atlassian MCP (Local): Get Visible Jira Projects","mcp_atlassian-mcp_searchJiraIssuesUsingJql":"Atlassian MCP (Local): Search Jira Issues Using JQL","mcp_atlassian-mcp_transitionJiraIssue":"Atlassian MCP (Local): Transition Jira Issue",mcp_figma_mcp_ser_get_screenshot:"Figma MCP: Get Screenshot",mcp_figma_mcp_ser_get_variable_defs:"Figma MCP: Get Variable Defs",mcp_gitkraken_cli_git_log_or_diff:"GitKraken MCP: Log/Compare",mcp_gitkraken_cli_git_push:"GitKraken MCP: Push",mcp_gitkraken_cli_git_status:"GitKraken MCP: Status",mcp_gitkraken_cli_gitlens_commit_composer:"GitKraken MCP: Commit Composer",profile_unit_test:"Profile Unit Test",profiler_agent:"Profiler Agent",run_profiler:"Run Profiler",define_subagent:"Define Subagent",find_by_name:"Find by Name",manage_subagents:"Manage Subagents","mcp__computer-use__request_access":"MCP: Computer Use Request Access","mcp__computer-use__screenshot":"MCP: Computer Use Screenshot",CronList:"Cron List","mcp__scheduled-tasks__list_scheduled_tasks":"MCP: Scheduled Tasks - List Scheduled Tasks",m_accept_workiq_eula:"WorkIQ EULA Acceptance",mcp_azure_bicep_m_get_bicep_best_practices:"Azure Bicep MCP (Local): Get Best Practices",mcp_azure_bicep_m_list_avm_metadata:"Azure Bicep MCP (Remote): List AVM Metadata",mcp_azure_mcp_policy:"Azure MCP Policy",workiq_search_emails:"WorkIQ Search Emails",resolve_memory_file_uri:"Serena: Resolve Memory File URI",generate_image:"Generate Image",mcp__plugins__list_plugins:"MCP Plugins List",mcp__skills__list_skills:"MCP Skills List",mcp__visualize__read_me:"MCP Visualize: Read Me",mcp__visualize__show_widget:"MCP Visualize: Show Widget",read_url_content:"Read URL Content",mcp_jira_editJiraIssue:"JIRA MCP (Remote): Edit Jira Issue",mcp_jira_getAccessibleAtlassianResources:"JIRA MCP (Remote): Get Accessible Atlassian Resources",mcp_jira_getConfluencePage:"JIRA MCP (Remote): Get Confluence Page",mcp_jira_getJiraIssue:"JIRA MCP (Remote): Get Jira Issue","mcp__scheduled-tasks__create_scheduled_task":"Scheduled Tasks MCP: Create Scheduled Task",dart_format:"Dart Format",Monitor:"Monitor",SendMessage:"Send Message","atlassian-getConfluencePage":"Confluence MCP: Page Read/Write","atlassian-getVisibleJiraProjects":"Jira MCP: Projects View/Edit","atlassian-lookupJiraAccountId":"Jira MCP: Account Lookup","github-pull-request_create_pull_request":"GitHub Pull Request Create/Update",mcp_github_check_dependency_vulnerabilities:"GitHub MCP (Local) Check Dependency Vulnerabilities",mcp_provides_tool_pylanceInvokeRefactoring:"MCP Provides Tool Pylance Invoke Refactoring","mcp__codebase-memory-mcp__get_graph_schema":"MCP Codebase Memory Get Graph Schema","mcp__codebase-memory-mcp__index_repository":"MCP Codebase Memory: Index Repository","mcp__codebase-memory-mcp__index_status":"MCP Codebase Memory: Index Status","mcp__codebase-memory-mcp__list_projects":"MCP Codebase Memory: List Projects","mcp__codebase-memory-mcp__query_graph":"MCP Codebase Memory: Query Graph","mcp__codebase-memory-mcp__search_code":"MCP Codebase Memory: Search Code","mcp__codebase-memory-mcp__search_graph":"MCP Codebase Memory: Search Graph",create_project:"Create Project","mcp__scheduled-tasks__update_scheduled_task":"MCP Scheduled Tasks: Update Scheduled Task",mcp_github_mcp_s2_create_pull_request:"MCP GitHub: Create Pull Request",respond_to_session_plan:"Respond To Session Plan",str_replace:"Str Replace","workiq-ask":"Workiq Ask",Artifact:"Figma: Get Design Context",LSP:"Visual Studio Code: LSP",TaskList:"Serena: Task List",mcp__figma__get_design_context:"Figma: Get Design Context",mcp__figma__get_metadata:"Figma: Get Metadata","mcp_atlassian-mcp_getIssueLinkTypes":"Atlassian MCP (Remote): Get Issue Link Types","mcp_atlassian-mcp_search":"Atlassian MCP (Remote): Search",cache_docs:"Cache Docs",call_agent:"Call Agent",delegate_task:"Delegate Task",diff:"Diff",get_task_result:"Get Task Result",git_diff:"Git Diff",git_status:"Git Status",http:"HTTP",jq:"JQ",lsp_diagnostics:"LSP Diagnostics",sed_replace:"SED Replace",update_todo:"Update TODO",workiq_delete_event:"WorkIQ Delete Event",workiq_list_events:"WorkIQ List Events",get_python_environment_details:"Python Environment Details","io_github_tavily-ai_tavily-mcp-tavily_search":"Tavily MCP (Remote): Search","mcp_tavily-mcp_tavily_extract":"Extract from Tavily","mcp_tavily-mcp_tavily_search":"Search in Tavily","microsoft_playwright-mcp-browser_click":"Playwright: Click","microsoft_playwright-mcp-browser_console_messages":"Playwright: Console Messages","microsoft_playwright-mcp-browser_evaluate":"Playwright: Evaluate","microsoft_playwright-mcp-browser_navigate":"Playwright: Navigate","microsoft_playwright-mcp-browser_network_request":"Playwright: Network Request","microsoft_playwright-mcp-browser_network_requests":"Microsoft Playwright MCP Browser Network Requests","microsoft_playwright-mcp-browser_snapshot":"Microsoft Playwright MCP Browser Snapshot","microsoft_playwright-mcp-browser_tabs":"Microsoft Playwright MCP Browser Tabs","microsoft_playwright-mcp-browser_wait_for":"Microsoft Playwright MCP Browser Wait For","rtf-markdown-editor.pdfChat":"PDF Chat",Azure_MCP_Server_get_azure_bestpractices:"Azure MCP: Get Azure Bestpractices",mcp_azure_mcp_ser_subscription_list:"Azure MCP: Search Subscription List","microsoft-learn-microsoft_docs_fetch":"Microsoft Learn: Microsoft Docs Fetch",record_observation:"Record Observation",readFiles:"Read Files",search:"Search",shell:"Shell",steering:"Steering","azure-devops-repo_branch":"Azure DevOps Repository Branch","canvas-authoring-compile_canvas":"Canvas Authoring: Compile Canvas","canvas-authoring-connect":"Canvas Authoring: Connect","canvas-authoring-describe_control":"Canvas Authoring: Describe Control","canvas-authoring-get_data_source_schema":"Canvas Authoring: Get Data Source Schema","canvas-authoring-list_apis":"Canvas Authoring: List APIs","canvas-authoring-list_controls":"Canvas Authoring: List Controls","canvas-authoring-list_data_sources":"Canvas Authoring: List Data Sources","canvas-authoring-sync_canvas":"Canvas Authoring: Sync Canvas","mcp__claude-in-chrome__navigate":"Claude In Chrome MCP: Navigate","mcp__claude-in-chrome__tabs_context_mcp":"Claude In Chrome MCP: Tabs Context ",mcp__Claude_Browser__preview_start:"MCP Claude Browser: Preview Start",mcp__ccd_session__dismiss_task:"MCP: Ccd Session Dismiss Task",mcp__plugin_Notion_notion__authenticate:"MCP Notion: Notion Authenticate",Workflow:"Workflow","atlassian-createJiraIssue":"Atlassian MCP: Create Jira Issue","atlassian-getAccessibleAtlassianResources":"Atlassian MCP: Get Accessible Atlassian Resources",chmod:"Chmod","context7-query-docs":"Context7 MCP: Query Docs","context7-resolve-library-id":"Context7 MCP: Resolve Library ID","github-mcp-server-add_issue_comment":"GitHub MCP: Add Issue Comment","github-mcp-server-add_reply_to_pull_request_comment":"GitHub MCP: Add Reply to Pull Request Comment","github-mcp-server-create_pull_request":"GitHub MCP: Create Pull Request","github-mcp-server-get_me":"GitHub MCP: Get Me","github-mcp-server-label_write":"GitHub MCP: Label Write","github-mcp-server-list_issue_types":"GitHub MCP: List Issue Types","github-mcp-server-list_label":"GitHub MCP: List Label","github-mcp-server-projects_list":"GitHub MCP: Projects List","github-mcp-server-pull_request_review_write":"GitHub MCP: Pull Request Review Write","github-mcp-server-semantic_issue_similarity_search":"GitHub MCP: Semantic Issue Similarity Search","github-mcp-server-semantic_issues_search":"GitHub MCP: Semantic Issues Search",mcp__ide__getDiagnostics:"IDE Get Diagnostics","mcp__microsoft_playwright-mcp__browser_click":"Playwright MCP: Browser Click","mcp__microsoft_playwright-mcp__browser_close":"Playwright MCP: Browser Close","mcp__microsoft_playwright-mcp__browser_console_messages":"Playwright MCP: Browser Console Messages","mcp__microsoft_playwright-mcp__browser_evaluate":"Playwright MCP: Browser Evaluate","mcp__microsoft_playwright-mcp__browser_navigate":"Playwright MCP: Browser Navigate","mcp__microsoft_playwright-mcp__browser_resize":"Playwright MCP: Browser Resize","mcp__microsoft_playwright-mcp__browser_snapshot":"Playwright MCP: Browser Snapshot","mcp__microsoft_playwright-mcp__browser_take_screenshot":"Playwright MCP: Browser Take Screenshot","mcp__microsoft_playwright-mcp__browser_wait_for":"Playwright MCP: Browser Wait For",tool_search_tool:"Tool Search",configure_notebook:"Notebook Configure",restart_notebook_kernel:"Kernel Restart",mcp__Claude_Browser__computer:"MCP Claude Browser: Computer",mcp__Claude_Browser__find:"MCP Claude Browser: Find",mcp__Claude_Browser__get_page_text:"MCP Claude Browser: Get Page Text",mcp__Claude_Browser__navigate:"MCP Claude Browser: Navigate",mcp__Claude_Browser__preview_list:"MCP Claude Browser: Preview List",mcp__Claude_Browser__preview_logs:"MCP Claude Browser: Preview Logs",mcp__Claude_Browser__preview_stop:"MCP Claude Browser: Preview Stop",mcp__Claude_Browser__read_console_messages:"MCP Claude Browser: Read Console Messages",mcp__Claude_Browser__read_page:"MCP Claude Browser: Read Page",mcp__Claude_Browser__tabs_context:"MCP Claude Browser: Tabs Context",mcp__Claude_Browser__tabs_create:"MCP Claude Browser: Tabs Create",mcp__Claude_Browser__tabs_select:"MCP Claude Browser: Tabs Select",mcp_github_github_create_pull_request:"GitHub MCP (Remote): Create Pull Request",mcp_github_github_get_file_contents:"GitHub MCP (Remote): Get File Contents",mcp_github_github_get_job_logs:"GitHub MCP (Remote): Get Job Logs",mcp_github_github_get_latest_release:"GitHub MCP (Remote): Get Latest Release",mcp_github_github_get_release_by_tag:"GitHub MCP (Remote): Get Release By Tag",mcp_github_github_get_repository_tree:"GitHub MCP (Remote): Get Repository Tree",mcp_github_github_get_tag:"GitHub MCP (Remote): Get Tag",mcp_github_github_list_code_scanning_alerts:"GitHub MCP (Remote): List Code Scanning Alerts",mcp_github_github_list_pull_requests:"GitHub MCP (Remote): List Pull Requests",mcp_github_github_list_tags:"GitHub MCP (Remote): List Tags",mcp_github_github_pull_request_read:"GitHub MCP (Remote): Pull Request Read",mcp_github_github_search_issues:"GitHub MCP (Remote): Search Issues",mcp_github_github_search_repositories:"GitHub MCP (Remote): Search Repositories","mcp_actions-marke_lookup-action-versions":"Actions Marketplace MCP: Lookup Action Versions",mcp__dart__analyze_files:"Dart MCP: Analyze Files",mcp__dart__connect_dart_tooling_daemon:"Dart MCP: Connect Dart Tooling Daemon",mcp__dart__flutter_driver:"Dart MCP: Flutter Driver",mcp__dart__get_app_logs:"Dart MCP: Get App Logs",mcp__dart__get_runtime_errors:"Dart MCP: Get Runtime Errors",mcp__dart__get_widget_tree:"Dart MCP: Get Widget Tree",mcp__dart__hot_reload:"Dart MCP: Hot Reload",mcp__dart__launch_app:"Dart MCP: Launch App",mcp__dart__list_devices:"Dart MCP: List Devices",mcp__dart__list_running_apps:"Dart MCP: List Running Apps",mcp__dart__pub_dev_search:"Dart MCP: Pub Dev Search",mcp__dart__resolve_workspace_symbol:"Dart MCP: Resolve Workspace Symbol",mcp__dart__stop_app:"Dart MCP: Stop App",mcp_github_mcp_s2_add_issue_comment:"GitHub MCP (Remote): Add Issue Comment",mcp_github_mcp_s2_issue_read:"GitHub MCP (Remote): Issue Read",mcp_github_mcp_s2_issue_write:"GitHub MCP (Remote): Issue Write",str_replace_editor:"Editor Replace",TaskGet:"Task Get",mcp__claude_ai_Figma__get_design_context:"Figma MCP: Get Design Context",mcp__claude_ai_Figma__get_metadata:"Figma MCP: Get Metadata",mcp__claude_ai_Figma__get_screenshot:"Figma MCP: Get Screenshot",mcp__claude_ai_Figma__get_variable_defs:"Figma MCP: Get Variable Defs",mcp_figma_mcp_ser_use_figma:"Figma MCP: Use Figma","mcp_home-assistan_GetLiveContext":"Home Assistant MCP: Get Live Context",mcp_io_github_git_list_issue_fields:"GitHub MCP (Local): List Issue Fields",mcp_io_github_git_request_copilot_review:"GitHub MCP (Local): Request Copilot Review",mcp_mcpsamples_aw_search_instructions:"MCPSamples: Search Instructions","actions-marketplace_resolveActionVersions":"Actions Marketplace MCP: Resolve Action Versions",execute_code:"Execute Code",mcp__Claude_Browser__javascript_tool:"Claude Browser: JavaScript Tool",mcp__Claude_Browser__resize_window:"Claude Browser: Resize Window",patch:"Patch",searchFiles:"Search Files",search_files:"Search Files",skill_view:"Skill View",EnterWorktree:"Git Entry Worktree",Grace:"Grace",ReportFindings:"Report Findings",__slash__compact:"Compact",mcp__ccd_session_mgmt__get_session:"Session Management MCP: Get Session",mcp__ccd_session_mgmt__list_events:"Session Management MCP: List Events"};var Xn=qi.pricing,wd=new Set(["VS Code","VS Code Insiders","VS Code Exploration","VS Code Server","VS Code Server (Insiders)","VSCodium","Visual Studio","JetBrains","Copilot CLI","Copilot CLI (App)","MS Scout (Copilot CLI)"]),FC=[["claude","Anthropic"],["anthropic","Anthropic"],["gemini","Google"],["google","Google"],["mistral","Mistral AI"],["codestral","Mistral AI"],["magistral","Mistral AI"],["ministral","Mistral AI"],["devstral","Mistral AI"],["pixtral","Mistral AI"],["gpt","OpenAI"],["o1","OpenAI"],["o3","OpenAI"],["o4","OpenAI"],["grok","xAI"],["raptor","xAI"],["goldeneye","xAI"],["qwen","Alibaba"],["mai-","Microsoft"]];function Td(o){return wd.has(o)?"copilot":"provider"}function NC(o){let e=o.toLowerCase(),t=FC.find(([s])=>e.startsWith(s));return t?t[1]:"Other"}function Na(o,e){return wd.has(o)?"GitHub Copilot":NC(e)}function lt(o){return o?o.actualTokens>0?o.actualTokens:o.tokens:0}function La(o){let e=X(o);return e.includes("/.copilot/jb/")?"JetBrains":e.includes("/.copilot/session-store.db#")||e.includes("/.copilot/session-state/")?"Copilot CLI":e.includes("/.crush/crush.db#")?"Crush":e.includes("/saoudrizwan.claude-dev/tasks/")?"Cline":e.includes("/opencode/")?"OpenCode":e.includes("/.codex/")?"Codex CLI":e.includes("/.kiro/sessions/cli/")?"Kiro CLI":e.includes("/kiro.kiroagent/workspace-sessions/")?"Kiro":e.includes("/.continue/sessions/")?"Continue":e.includes("/local-agent-mode-sessions/")?"Claude Desktop Cowork":e.includes("/.claude/projects/")?Uo(o):e.includes("/.vibe/logs/session/")?"Mistral Vibe":e.includes("/.gemini/antigravity/brain/")?"Antigravity":e.includes("/.gemini/tmp/")&&e.includes("/chats/session-")&&e.endsWith(".jsonl")?"Gemini CLI":e.includes("/cursor/")?"Cursor":e.includes("/code - insiders/")?"VS Code Insiders":e.includes("/code - exploration/")?"VS Code Exploration":e.includes("/vscodium/")?"VSCodium":e.includes(".vscode-server-insiders/")?"VS Code Server (Insiders)":e.includes(".vscode-server")?"VS Code Server":e.includes("/.vs/")&&e.includes("/copilot-chat/")?"Visual Studio":"VS Code"}async function ja(o,e,t=20){if(o.length===0)return[];let s=new Array(o.length),n=0,i=Array.from({length:Math.min(t,o.length)},async()=>{for(;n<o.length;){let r=n++;try{s[r]=await e(o[r],r)}catch{s[r]=void 0}}});return await Promise.all(i),s}function Zn(){return{tokens:0,thinkingTokens:0,estimatedTokens:0,actualTokens:0,sessions:0,avgInteractionsPerSession:0,avgTokensPerSession:0,modelUsage:{},editorUsage:{},co2:0,treesEquivalent:0,waterUsage:0,estimatedCost:0}}function eo(o,e,t){let s=Math.round(lt(e)*t),n=Math.round(e.thinkingTokens*t),i=Math.round(e.actualTokens*t);o.tokens+=s,o.thinkingTokens+=n,o.estimatedTokens+=Math.round(e.tokens*t),o.actualTokens+=i,o.sessions++;for(let[c,d]of Object.entries(e.modelUsage))o.modelUsage[c]||(o.modelUsage[c]={inputTokens:0,outputTokens:0,sessions:0}),o.modelUsage[c].inputTokens+=Math.round(d.inputTokens*t),o.modelUsage[c].outputTokens+=Math.round(d.outputTokens*t),d.cachedReadTokens!==void 0&&(o.modelUsage[c].cachedReadTokens=(o.modelUsage[c].cachedReadTokens??0)+Math.round(d.cachedReadTokens*t)),d.cacheCreationTokens!==void 0&&(o.modelUsage[c].cacheCreationTokens=(o.modelUsage[c].cacheCreationTokens??0)+Math.round(d.cacheCreationTokens*t));let r=Math.round(e.interactions*t),a=o.avgInteractionsPerSession*(o.sessions-1)+r;o.avgInteractionsPerSession=o.sessions>0?a/o.sessions:0,o.editorUsage[e.editorSource]||(o.editorUsage[e.editorSource]={tokens:0,sessions:0}),o.editorUsage[e.editorSource].tokens+=s,o.editorUsage[e.editorSource].sessions++}function gs(){return{sessions:0,toolCalls:{total:0,byTool:{}},modeUsage:{ask:0,edit:0,agent:0,plan:0,customAgent:0,cli:0},contextReferences:G(),mcpTools:{total:0,byServer:{},byTool:{}},modelSwitching:{modelsPerSession:[],totalSessions:0,averageModelsPerSession:0,maxModelsPerSession:0,minModelsPerSession:0,switchingFrequency:0,autoSessions:0,foundryWindowsSessions:0,unknownProviderSessions:0,selectedModelExtensions:[],unknownProviderModels:[],standardModels:[],premiumModels:[],lowCostModels:[],mediumCostModels:[],highCostModels:[],unknownModels:[],mixedTierSessions:0,mixedCostSessions:0,standardRequests:0,premiumRequests:0,unknownRequests:0,totalRequests:0,lowCostRequests:0,mediumCostRequests:0,highCostRequests:0},repositories:[],repositoriesWithCustomization:[],editScope:{singleFileEdits:0,multiFileEdits:0,totalEditedFiles:0,avgFilesPerSession:0},applyUsage:{totalApplies:0,totalCodeBlocks:0,applyRate:0},sessionDuration:{totalDurationMs:0,avgDurationMs:0,avgFirstProgressMs:0,avgTotalElapsedMs:0,avgWaitTimeMs:0,activeDurationMs:0},conversationPatterns:{multiTurnSessions:0,singleTurnSessions:0,avgTurnsPerSession:0,maxTurnsInSession:0},agentTypes:{editsAgent:0,defaultAgent:0,workspaceAgent:0,other:0}}}var Ht=[{bg:"rgba(54, 162, 235, 0.6)",border:"rgba(54, 162, 235, 1)"},{bg:"rgba(255, 99, 132, 0.6)",border:"rgba(255, 99, 132, 1)"},{bg:"rgba(75, 192, 192, 0.6)",border:"rgba(75, 192, 192, 1)"},{bg:"rgba(153, 102, 255, 0.6)",border:"rgba(153, 102, 255, 1)"},{bg:"rgba(255, 159, 64, 0.6)",border:"rgba(255, 159, 64, 1)"},{bg:"rgba(255, 205, 86, 0.6)",border:"rgba(255, 205, 86, 1)"},{bg:"rgba(201, 203, 207, 0.6)",border:"rgba(201, 203, 207, 1)"},{bg:"rgba(100, 181, 246, 0.6)",border:"rgba(100, 181, 246, 1)"}];function to(o,e,t){if(!o||!e)throw new Error("buildChartPayload: labels and days are required");if(o.length!==e.length)throw new Error(`buildChartPayload: labels.length (${o.length}) !== days.length (${e.length})`);let s=P=>`${P.getFullYear()}-${String(P.getMonth()+1).padStart(2,"0")}-${String(P.getDate()).padStart(2,"0")}`,n=P=>{let x=P.map(U=>U.entry),N=P.map(U=>U.label),ae=x.map(U=>U.tokens),ne=x.map(U=>U.sessions),se=new Set;x.forEach(U=>Object.keys(U.modelUsage).forEach(V=>se.add(V)));let $s=Array.from(se).map((U,V)=>{let _e=Ht[V%Ht.length];return{label:U,data:x.map(be=>{let le=be.modelUsage[U];return le?le.inputTokens+le.outputTokens:0}),backgroundColor:_e.bg,borderColor:_e.border,borderWidth:1}}),hs=new Set;x.forEach(U=>Object.keys(U.editorUsage).forEach(V=>hs.add(V)));let Oe=Array.from(hs).map((U,V)=>{let _e=Ht[V%Ht.length];return{label:U,data:x.map(be=>be.editorUsage[U]?.tokens||0),backgroundColor:_e.bg,borderColor:_e.border,borderWidth:1}}),Hs=ae.reduce((U,V)=>U+V,0),Et=ne.reduce((U,V)=>U+V,0),Ct=P.length,oo=x.map(U=>ot(U.modelUsage,Xn,"copilot")),io=oo.reduce((U,V)=>U+V,0),nr=Ct>0?io/Ct:0,Qt=new Set;x.forEach(U=>{U.editorModelUsage&&Object.keys(U.editorModelUsage).forEach(V=>Qt.add(V))});let ys=new Map;for(let U of Qt){let V=x.reduce((_e,be)=>_e+ot(be.editorModelUsage?.[U]??{},Xn,Td(U)),0);ys.set(U,V)}let ro=Array.from(Qt).sort((U,V)=>(ys.get(V)||0)-(ys.get(U)||0)).map((U,V)=>{let _e=Ht[V%Ht.length];return{label:U,data:x.map(be=>ot(be.editorModelUsage?.[U]??{},Xn,Td(U))),backgroundColor:_e.bg,borderColor:_e.border,borderWidth:1}}),Ws=new Set;x.forEach(U=>{if(U.editorModelUsage)for(let[V,_e]of Object.entries(U.editorModelUsage))for(let be of Object.keys(_e))Ws.add(Na(V,be))});let Xe=new Map;for(let U of Ws)Xe.set(U,x.reduce((V,_e)=>{if(!_e.editorModelUsage)return V;let be={};for(let[ct,Yt]of Object.entries(_e.editorModelUsage))for(let[ut,Fe]of Object.entries(Yt))Na(ct,ut)===U&&(be[ut]||(be[ut]={inputTokens:0,outputTokens:0,sessions:0}),be[ut].inputTokens+=Fe.inputTokens,be[ut].outputTokens+=Fe.outputTokens);return V+ot(be,Xn,U==="GitHub Copilot"?"copilot":"provider")},0));let Ze=Array.from(Ws).sort((U,V)=>(Xe.get(V)||0)-(Xe.get(U)||0)).map((U,V)=>{let _e=Ht[V%Ht.length],be=U==="GitHub Copilot"?"copilot":"provider";return{label:U,data:x.map(le=>{if(!le.editorModelUsage)return 0;let ct={};for(let[Yt,ut]of Object.entries(le.editorModelUsage))for(let[Fe,ao]of Object.entries(ut))Na(Yt,Fe)===U&&(ct[Fe]||(ct[Fe]={inputTokens:0,outputTokens:0,sessions:0}),ct[Fe].inputTokens+=ao.inputTokens,ct[Fe].outputTokens+=ao.outputTokens);return ot(ct,Xn,be)}),backgroundColor:_e.bg,borderColor:_e.border,borderWidth:1}});return{labels:N,tokensData:ae,sessionsData:ne,modelDatasets:$s,editorDatasets:Oe,repositoryDatasets:[],periodCount:Ct,totalTokens:Hs,totalSessions:Et,avgPerPeriod:Ct>0?Math.round(Hs/Ct):0,costData:oo,totalCost:io,avgCostPerPeriod:nr,editorCostDatasets:ro,billingGroupCostDatasets:Ze}},i=(P,x)=>{P.tokens+=x.tokens,P.sessions+=x.sessions;for(let[N,ae]of Object.entries(x.modelUsage))P.modelUsage[N]||(P.modelUsage[N]={inputTokens:0,outputTokens:0,sessions:0}),P.modelUsage[N].inputTokens+=ae.inputTokens,P.modelUsage[N].outputTokens+=ae.outputTokens,ae.cachedReadTokens!==void 0&&(P.modelUsage[N].cachedReadTokens=(P.modelUsage[N].cachedReadTokens??0)+ae.cachedReadTokens),ae.cacheCreationTokens!==void 0&&(P.modelUsage[N].cacheCreationTokens=(P.modelUsage[N].cacheCreationTokens??0)+ae.cacheCreationTokens);for(let[N,ae]of Object.entries(x.editorUsage))P.editorUsage[N]||(P.editorUsage[N]={tokens:0,sessions:0}),P.editorUsage[N].tokens+=ae.tokens,P.editorUsage[N].sessions+=ae.sessions;if(x.editorModelUsage){P.editorModelUsage||(P.editorModelUsage={});for(let[N,ae]of Object.entries(x.editorModelUsage)){P.editorModelUsage[N]||(P.editorModelUsage[N]={});for(let[ne,se]of Object.entries(ae))P.editorModelUsage[N][ne]||(P.editorModelUsage[N][ne]={inputTokens:0,outputTokens:0,sessions:0}),P.editorModelUsage[N][ne].inputTokens+=se.inputTokens,P.editorModelUsage[N][ne].outputTokens+=se.outputTokens}}},r=()=>({tokens:0,sessions:0,modelUsage:{},editorUsage:{}}),a=new Date,c=o.map((P,x)=>({label:P,entry:e[x]})),d=n(c),p=P=>{let x=new Date(P);x.setHours(0,0,0,0);let N=x.getDay();return x.setDate(x.getDate()-(N===0?6:N-1)),x},f=P=>{let x=new Date(P);return x.setDate(P.getDate()+6),P.getMonth()===x.getMonth()?`${P.toLocaleDateString("en-US",{month:"short"})} ${P.getDate()}\u2013${x.getDate()}`:`${P.toLocaleDateString("en-US",{month:"short",day:"numeric"})}\u2013${x.toLocaleDateString("en-US",{month:"short",day:"numeric"})}`},h=p(a),_=new Map;for(let P=5;P>=0;P--){let x=new Date(h);x.setDate(h.getDate()-P*7);let N=s(x);_.set(N,{label:f(x),entry:r()})}let C=t||new Map(o.map((P,x)=>[P,e[x]]));for(let[P,x]of C.entries()){let N=p(new Date(P+"T00:00:00")),ae=_.get(s(N));ae&&i(ae.entry,x)}let T=Array.from(_.values()),E=n(T),A=new Map;for(let P=11;P>=0;P--){let x=new Date(a.getFullYear(),a.getMonth()-P,1),N=`${x.getFullYear()}-${String(x.getMonth()+1).padStart(2,"0")}`,ae=x.toLocaleDateString("en-US",{month:"short",year:"numeric"});A.set(N,{label:ae,entry:r()})}for(let[P,x]of C.entries()){let N=P.slice(0,7),ae=A.get(N);ae&&i(ae.entry,x)}let R=Array.from(A.values()),B=n(R),F={};return e.forEach(P=>{Object.entries(P.editorUsage).forEach(([x,N])=>{F[x]=(F[x]||0)+N.tokens})}),{labels:d.labels,tokensData:d.tokensData,sessionsData:d.sessionsData,modelDatasets:d.modelDatasets,editorDatasets:d.editorDatasets,editorTotalsMap:F,repositoryDatasets:[],repositoryTotalsMap:{},dailyCount:d.periodCount,totalTokens:d.totalTokens,avgTokensPerDay:d.periodCount>0?Math.round(d.totalTokens/d.periodCount):0,totalSessions:d.totalSessions,lastUpdated:new Date().toISOString(),backendConfigured:!1,periodsReady:!0,periods:{day:d,week:E,month:B}}}function ee(o){return o==null||!Number.isFinite(o)?"0":Math.round(o).toLocaleString("en-US")}function ye(o){return o==null||!Number.isFinite(o)||o<0?"0":o>=1e9?`${(o/1e9).toFixed(1)}B`:o>=1e6?`${(o/1e6).toFixed(1)}M`:o>=1e3?`${(o/1e3).toFixed(1)}K`:o.toString()}var zi=kd.estimators,Wt=qi.pricing,LC=Sd,jC=o=>{},Ga=o=>{},Pd=(o,e)=>{let t=e instanceof Error?e.message:e!==void 0?String(e):"";console.error(w.red(o),t)};async function GC(o){try{let e=await Dt.promises.readFile(o,"utf-8");return JSON.parse(e)}catch(e){return e?.code!=="ENOENT"&&Pd(`[readJsonFile] Failed to read or parse JSON at ${o}:`,e),null}}var Bi=null;function so(){if(Bi)return Bi;let o=xo.file(__dirname);return Bi=Ma({...wa(o),estimateTokens:(e,t)=>Z(e,t??"gpt-4",zi),isMcpTool:st,extractMcpServerName:ft}),Bi}function vd(){return new Oo({log:jC,warn:Ga,error:Pd,ecosystems:so()})}async function ke(){return vd().getCopilotSessionFiles()}async function $i(o){let e=new Set,t=ve.join(Md.homedir(),".claude","projects");for(let n of o){if(n.startsWith(t+ve.sep)||n.startsWith(t+"/")){let f=await os(()=>Dt.promises.readFile(n,"utf-8"),null,`buildCustomizationMatrix readFile(${n})`);if(f!==null){let h=f.split(`
|
|
161
|
+
`).slice(0,30);for(let _ of h)if(_.trim())try{let C=JSON.parse(_);if(C.cwd&&typeof C.cwd=="string"){e.add(C.cwd);break}}catch{}}continue}let i=ve.dirname(n);if(ve.basename(i)!=="chatSessions")continue;let r=ve.dirname(i),a=ve.join(r,"workspace.json"),c=await GC(a);if(!c)continue;let d=c.folder;if(!d||!d.startsWith("file://"))continue;let p=Do(d);p&&e.add(p)}if(e.size===0)return;let s=0;for(let n of e)await os(async()=>{let[r,a,c]=await Promise.all([Dt.promises.access(ve.join(n,".github","copilot-instructions.md")).then(()=>!0).catch(()=>!1),Dt.promises.access(ve.join(n,"agents.md")).then(()=>!0).catch(()=>!1),Dt.promises.access(ve.join(n,"CLAUDE.md")).then(()=>!0).catch(()=>!1)]);return!r&&!a&&!c},!0,`buildCustomizationMatrix workspace check(${n})`)&&s++;return{customizationTypes:[],workspaces:[],totalWorkspaces:e.size,workspacesWithIssues:s}}function Hi(){return vd().getDiagnosticCandidatePaths()}function qC(o,e){return Z(o,e||"gpt-4",zi)}function BC(o){return Lt(o,Wt)}async function Ad(o){let e=so().find(t=>t.handles(o));return e?e.stat(o):Dt.promises.stat(o)}async function zC(o,e=!1){let t=ve.basename(o,ve.extname(o));if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return null;let n=o.replace(/\\/g,"/").match(/^(.*\/workspaceStorage\/[^/]+)\//);if(!n)return null;let r=n[1].replace(/\//g,"\\"),a=["GitHub.copilot-chat","github.copilot-chat","GitHub.copilot","github.copilot"];for(let c of a){let d=ve.join(r,c,"debug-logs",t,"main.jsonl");try{let p=await Dt.promises.readFile(d,"utf8"),f=sc(p);if(f)return e&&console.error(` \u2713 Found debug log: ${t} (tokens: ${f.inputTokens+f.outputTokens})`),f}catch{}}return e&&console.error(` \u2717 No debug log found: ${t}`),null}async function fs(o,e=!1){try{let t=await Ad(o),s=bd(o,t.mtimeMs,t.size);if(s)return s;let n=so().find(T=>T.handles(o));if(n){let[T,E,A]=await Promise.all([n.getTokens(o),n.countInteractions(o),n.getModelUsage(o)]),R=L(t.mtime),B={file:o,tokens:T.actualTokens>0?T.actualTokens:T.tokens,thinkingTokens:T.thinkingTokens,actualTokens:T.actualTokens,interactions:E,modelUsage:A,lastModified:t.mtime,editorSource:La(o),dailyFractions:await n.getDailyFractions?.(o)??{[R]:1}};return Oa(o,t.mtimeMs,t.size,B),B}let i=await Dt.promises.readFile(o,"utf-8");if(!i.trim())return null;let r=o.endsWith(".jsonl")||bt(i),a=0,c=0,d=0,p=0,f={};if(r){let T=Ns(o)?await ms(o):null,E=Bo(i,T);if(a=E.actualTokens>0?E.actualTokens:E.tokens,c=E.thinkingTokens,d=E.actualTokens,f=await ya({warn:Ga,tokenEstimators:zi,modelPricing:Wt,ecosystems:so()},o,i),Object.keys(f).length===0&&bi(o)){let R=xi(i);Object.keys(R.modelUsage).length>0?f=R.modelUsage:R.tokens>0&&(f={[R.modelHint&&R.modelHint!=="unknown"?R.modelHint:"unknown"]:{inputTokens:R.tokens,outputTokens:0}})}f=gu(f,d||a);let A=i.trim().split(`
|
|
162
|
+
`);for(let R of A)try{let B=JSON.parse(R);(B.type==="user.message"||B.kind===2&&B.k?.[0]==="requests")&&p++}catch{}}else{let T=pd(o,i,qC,BC);a=T.tokens,c=T.thinkingTokens,d=T.actualTokens,p=T.interactions,f=T.modelUsage}let h=gd(i,r,t.mtime),_=await zC(o,e);if(_&&_.inputTokens+_.outputTokens>0&&(a=_.inputTokens+_.outputTokens,d=a,Object.keys(_.modelBreakdown).length>0)){f={};for(let[T,E]of Object.entries(_.modelBreakdown))f[T]={inputTokens:E.inputTokens,outputTokens:E.outputTokens,sessions:0,...E.cachedTokens>0?{cachedReadTokens:E.cachedTokens}:{}}}let C={file:o,tokens:a,thinkingTokens:c,actualTokens:d,interactions:p,modelUsage:f,lastModified:t.mtime,editorSource:La(o),dailyFractions:h};return Oa(o,t.mtimeMs,t.size,C),C}catch{return null}}async function Jt(o,e){let t=new Date,s=L(t),n=t.getFullYear(),i=t.getMonth(),r=L(new Date(n,i,1)),a=new Date(n,i,0),c=L(new Date(a.getFullYear(),a.getMonth(),1)),d=new Date(n,i,t.getDate()-30),p=L(d),f={today:Zn(),month:Zn(),lastMonth:Zn(),last30Days:Zn()},h=0,_=await ja(o,async C=>{let T=await fs(C);return e&&e(++h,o.length),T});for(let C of _){if(!C||C.tokens===0||!Object.keys(C.dailyFractions).some(F=>F>=c))continue;let E=0,A=0,R=0,B=0;for(let[F,P]of Object.entries(C.dailyFractions))F===s&&(E+=P),F>=r&&(A+=P),F>=c&&F<r&&(R+=P),F>=p&&(B+=P);E>0&&eo(f.today,C,E),A>0&&eo(f.month,C,A),R>0&&eo(f.lastMonth,C,R),B>0&&eo(f.last30Days,C,B)}for(let C of Object.values(f))C.sessions>0&&(C.avgTokensPerSession=Math.round(C.tokens/C.sessions)),C.co2=C.tokens/1e3*qe.CO2_PER_1K_TOKENS,C.treesEquivalent=C.co2/qe.CO2_ABSORPTION_PER_TREE_PER_YEAR,C.waterUsage=C.tokens/1e3*qe.WATER_USAGE_PER_1K_TOKENS,C.estimatedCost=ot(C.modelUsage,Wt),C.estimatedCostCopilot=ot(C.modelUsage,Wt,"copilot");return{...f,lastUpdated:t}}async function Vt(o){let e={warn:Ga,tokenEstimators:zi,modelPricing:Wt,toolNameMap:LC,ecosystems:so()},t=new Date,s=new Date(t.getFullYear(),t.getMonth(),t.getDate()),n=new Date(t.getFullYear(),t.getMonth(),t.getDate()-30),i=new Date(t.getFullYear(),t.getMonth(),1),r=new Date(t.getFullYear(),t.getMonth()-1,1),a=r<n?r:n,c=gs(),d=gs(),p=gs(),f=gs(),h=[];for(let _ of o)try{let T=(await Ad(_)).mtime;if(T<a)continue;let E=await ju(e,_);if(T>=n&&(Un(d,E),d.sessions++),T>=i&&(Un(p,E),p.sessions++),T>=s){Un(c,E),c.sessions++;let A=await fs(_);if(A&&A.interactions>0){let R=0,B=0,F=0;for(let P of Object.values(A.modelUsage))R+=P.inputTokens,B+=P.outputTokens,F+=P.cachedReadTokens??0;h.push({title:null,filePath:_,interactions:A.interactions,toolCalls:E.toolCalls.total,inputTokens:R,outputTokens:B,thinkingTokens:A.thinkingTokens??0,cachedTokens:F,totalTokens:A.tokens,estimatedCost:ot(A.modelUsage,Wt),editor:A.editorSource,models:Object.keys(A.modelUsage),lastActivity:A.lastModified.toISOString(),...E.sessionDuration?.totalDurationMs!==void 0?{durationMs:E.sessionDuration.totalDurationMs}:{},...E.sessionDuration?.activeDurationMs!==void 0?{activeDurationMs:E.sessionDuration.activeDurationMs}:{}})}}T>=r&&T<i&&(Un(f,E),f.sessions++)}catch{}return{today:c,last30Days:d,month:p,lastMonth:f,lastUpdated:t,todaySessions:h.sort((_,C)=>C.interactions-_.interactions)}}async function Wi(o,e=!1){let t=new Date,s=new Date(t.getFullYear(),t.getMonth(),t.getDate()-30),n=L(s),i=L(t),r=new Map,a=new Date(s);for(;L(a)<=i;){let h=L(a);r.set(h,{tokens:0,sessions:0,modelUsage:{},editorUsage:{}}),a.setDate(a.getDate()+1)}let c=new Map,d=await ja(o,async h=>fs(h,e));for(let h of d){if(!h||h.tokens===0||h.interactions===0)continue;let _=lt(h);for(let[C,T]of Object.entries(h.dailyFractions)){let E=Math.round(_*T),A=r.get(C);if(A){A.tokens+=E,A.sessions++;for(let[P,x]of Object.entries(h.modelUsage))A.modelUsage[P]||(A.modelUsage[P]={inputTokens:0,outputTokens:0,sessions:0}),A.modelUsage[P].inputTokens+=Math.round(x.inputTokens*T),A.modelUsage[P].outputTokens+=Math.round(x.outputTokens*T),x.cachedReadTokens!==void 0&&(A.modelUsage[P].cachedReadTokens=(A.modelUsage[P].cachedReadTokens??0)+Math.round(x.cachedReadTokens*T)),x.cacheCreationTokens!==void 0&&(A.modelUsage[P].cacheCreationTokens=(A.modelUsage[P].cacheCreationTokens??0)+Math.round(x.cacheCreationTokens*T));let F=h.editorSource;A.editorUsage[F]||(A.editorUsage[F]={tokens:0,sessions:0}),A.editorUsage[F].tokens+=E,A.editorUsage[F].sessions++,A.editorModelUsage||(A.editorModelUsage={}),A.editorModelUsage[F]||(A.editorModelUsage[F]={});for(let[P,x]of Object.entries(h.modelUsage))A.editorModelUsage[F][P]||(A.editorModelUsage[F][P]={inputTokens:0,outputTokens:0,sessions:0}),A.editorModelUsage[F][P].inputTokens+=Math.round(x.inputTokens*T),A.editorModelUsage[F][P].outputTokens+=Math.round(x.outputTokens*T)}c.has(C)||c.set(C,{tokens:0,sessions:0,modelUsage:{},editorUsage:{}});let R=c.get(C);R.tokens+=E,R.sessions++;for(let[F,P]of Object.entries(h.modelUsage))R.modelUsage[F]||(R.modelUsage[F]={inputTokens:0,outputTokens:0,sessions:0}),R.modelUsage[F].inputTokens+=Math.round(P.inputTokens*T),R.modelUsage[F].outputTokens+=Math.round(P.outputTokens*T),P.cachedReadTokens!==void 0&&(R.modelUsage[F].cachedReadTokens=(R.modelUsage[F].cachedReadTokens??0)+Math.round(P.cachedReadTokens*T)),P.cacheCreationTokens!==void 0&&(R.modelUsage[F].cacheCreationTokens=(R.modelUsage[F].cacheCreationTokens??0)+Math.round(P.cacheCreationTokens*T));let B=h.editorSource;R.editorUsage[B]||(R.editorUsage[B]={tokens:0,sessions:0}),R.editorUsage[B].tokens+=E,R.editorUsage[B].sessions++,R.editorModelUsage||(R.editorModelUsage={}),R.editorModelUsage[B]||(R.editorModelUsage[B]={});for(let[F,P]of Object.entries(h.modelUsage))R.editorModelUsage[B][F]||(R.editorModelUsage[B][F]={inputTokens:0,outputTokens:0,sessions:0}),R.editorModelUsage[B][F].inputTokens+=Math.round(P.inputTokens*T),R.editorModelUsage[B][F].outputTokens+=Math.round(P.outputTokens*T)}}let p=Array.from(r.keys()).sort(),f=p.map(h=>r.get(h));return{labels:p,days:f,allDaysMap:c}}var $C=50;function xd(o=$C){process.stdout.write("\r"+" ".repeat(Math.max(0,o))+"\r")}function qa(o){process.stdout.write(w.dim(o))}var HC=80,Be=class{silent;constructor(e=!1){this.silent=e}show(e){this.silent||qa(e)}update(e){this.silent||(process.stdout.write("\r"),qa(e))}done(){this.silent||xd(HC)}};function Me(o){return o.json===!0}var Dd=new de("stats").description("Show overview of discovered session files, sessions, chat turns, and tokens").option("-v, --verbose","Show detailed per-folder breakdown").option("--json","Output raw JSON (for machine consumption)").action(async o=>{let e=Me(o);if(e||console.log(w.bold.cyan(`
|
|
147
163
|
\u{1F50D} Copilot Token Tracker - Session Statistics
|
|
148
|
-
`)),o.verbose&&!e){let _=
|
|
149
|
-
`));let n=0,i=0,r=0,a=0,c=0,
|
|
164
|
+
`)),o.verbose&&!e){let _=Hi();console.log(w.dim("Search paths:"));for(let C of _){let T=C.exists?w.green("\u2705"):w.dim("\u274C");console.log(` ${T} ${w.dim(C.source)}: ${C.path}`)}console.log()}let t=new Be(e);t.show("Scanning for session files...");let s=await ke();if(t.done(),s.length===0){e?process.stdout.write("{}"):(console.log(w.yellow("\u26A0\uFE0F No session files found.")),console.log(w.dim("Have you used GitHub Copilot Chat in VS Code yet?")));return}e||console.log(w.green(`\u{1F4C2} Found ${w.bold(ee(s.length))} session file(s)
|
|
165
|
+
`));let n=0,i=0,r=0,a=0,c=0,d={},p={};for(let _=0;_<s.length;_++){let C=await fs(s[_]);if(!C||C.tokens===0){c++;continue}if(a++,n+=lt(C),i+=C.thinkingTokens,r+=C.interactions,d[C.editorSource]||(d[C.editorSource]={files:0,tokens:0,interactions:0}),d[C.editorSource].files++,d[C.editorSource].tokens+=lt(C),d[C.editorSource].interactions+=C.interactions,o.verbose){let T=JC(s[_]);p[T]||(p[T]={files:0,tokens:0}),p[T].files++,p[T].tokens+=lt(C)}((_+1)%50===0||_===s.length-1)&&t.update(`Processing: ${_+1}/${s.length}`)}if(t.done(),e){let _={totalFiles:s.length,processedFiles:a,emptyFiles:c,totalTokens:n,totalThinkingTokens:i,totalInteractions:r,byEditor:d,lastUpdated:new Date().toISOString()};process.stdout.write(JSON.stringify(_));return}console.log(w.bold("\u{1F4CA} Summary")),console.log(w.dim("\u2500".repeat(50))),console.log(` Session files (with data): ${w.bold(ee(a))}`),c>0&&console.log(` Empty/skipped files: ${w.dim(ee(c))}`),console.log(` Total chat turns: ${w.bold(ee(r))}`),console.log(` Total tokens: ${w.bold.yellow(ye(n))}`),i>0&&console.log(` Thinking tokens (included): ${w.dim(ye(i))}`);let f=Fa();f.enabled&&f.entries>0&&console.log(w.dim(` Cache: ${ee(f.entries)} entries loaded`)),console.log();let h=Object.entries(d).sort((_,C)=>C[1].tokens-_[1].tokens);if(h.length>0){console.log(w.bold("\u{1F5A5}\uFE0F By Editor")),console.log(w.dim("\u2500".repeat(50)));for(let[_,C]of h){let T=WC(_);console.log(` ${T.padEnd(25)} ${ee(C.files).padStart(5)} files ${ye(C.tokens).padStart(8)} tokens ${ee(C.interactions).padStart(6)} turns`)}console.log()}if(o.verbose&&Object.keys(p).length>0){let _=Object.entries(p).sort((C,T)=>T[1].tokens-C[1].tokens);console.log(w.bold("\u{1F4C1} By Folder")),console.log(w.dim("\u2500".repeat(70)));for(let[C,T]of _.slice(0,20))console.log(` ${C.substring(0,50).padEnd(50)} ${ee(T.files).padStart(5)} files ${ye(T.tokens).padStart(8)} tokens`);_.length>20&&console.log(w.dim(` ... and ${_.length-20} more folders`)),console.log()}});function WC(o){return o?{vscode:"VS Code","vscode-insiders":"VS Code Insiders","vscode-exploration":"VS Code Exploration","vscode-remote":"VS Code Remote",vscodium:"VSCodium",cursor:"Cursor","copilot-cli":"Copilot CLI",opencode:"OpenCode","claude-code":"Claude Code","claude-desktop-cowork":"Claude Desktop (Cowork)","mistral-vibe":"Mistral Vibe","gemini-cli":"Gemini CLI"}[o]||o:"Unknown"}function JC(o){let e=o.split(/[/\\]/),t=e.indexOf("chatSessions");return t>=2?e.slice(t-1,t+1).join("/"):e.slice(-3,-1).join("/")}function Ed(o=new Date){return{today:{},month:{},lastMonth:{},last30Days:{},lastUpdated:o.toISOString(),backendConfigured:!1}}function Ji(o=new Date){return{labels:[],tokensData:[],sessionsData:[],modelDatasets:[],editorDatasets:[],editorTotalsMap:{},repositoryDatasets:[],repositoryTotalsMap:{},dailyCount:0,totalTokens:0,avgTokensPerDay:0,totalSessions:0,lastUpdated:o.toISOString(),backendConfigured:!1}}function Vi(o=new Date){return{today:{},last30Days:{},month:{},lastMonth:{},locale:Intl.DateTimeFormat().resolvedOptions().locale,lastUpdated:o.toISOString(),backendConfigured:!1}}function Rd(){return{}}function Ki(o){return{today:o.today,month:o.month,lastMonth:o.lastMonth,last30Days:o.last30Days,lastUpdated:o.lastUpdated.toISOString(),backendConfigured:!1}}function Qi(o,e=new Date){return{...o,locale:Intl.DateTimeFormat().resolvedOptions().locale,lastUpdated:e.toISOString(),backendConfigured:!1}}function Yi(o){return{overallStage:o.overallStage,overallLabel:o.overallLabel,categories:o.categories,period:o.period,lastUpdated:o.lastUpdated,backendConfigured:!1}}var Id=new de("usage").description("Show token usage for today, current month, last month, and last 30 days").option("-m, --models","Show per-model token breakdown").option("-c, --cost","Show estimated cost breakdown").option("--json","Output raw JSON (for machine consumption)").action(async o=>{let e=await VC(o);if(!e)return;let t=await KC(e,o);if(Me(o)){process.stdout.write(JSON.stringify(Ki(t)));return}console.log(w.bold.cyan(`
|
|
150
166
|
\u{1F4CA} Copilot Token Tracker - Usage Report
|
|
151
|
-
`));let s=[{label:"Today",emoji:"\u{1F4C5}",stats:t.today},{label:"This Month",emoji:"\u{1F4C6}",stats:t.month},{label:"Last Month",emoji:"\u{1F5D3}\uFE0F",stats:t.lastMonth},{label:"Last 30 Days",emoji:"\u{1F4C8}",stats:t.last30Days}];for(let n of s)
|
|
152
|
-
`))});async function
|
|
167
|
+
`));let s=[{label:"Today",emoji:"\u{1F4C5}",stats:t.today},{label:"This Month",emoji:"\u{1F4C6}",stats:t.month},{label:"Last Month",emoji:"\u{1F5D3}\uFE0F",stats:t.lastMonth},{label:"Last 30 Days",emoji:"\u{1F4C8}",stats:t.last30Days}];for(let n of s)QC(n.label,n.emoji,n.stats,o);console.log(w.dim(`Last updated: ${t.lastUpdated.toLocaleString()}
|
|
168
|
+
`))});async function VC(o){let e=Me(o),t=new Be(e);t.show("Scanning for session files...");let s=await ke();return t.done(),s.length===0?(e?process.stdout.write("{}"):console.log(w.yellow("\u26A0\uFE0F No session files found.")),null):s}async function KC(o,e){let t=Me(e),s=new Be(t);s.show("Calculating token usage...");let n=await Jt(o,(i,r)=>{s.update(`Processing: ${i}/${r} files`)});return s.done(),n}function QC(o,e,t,s){if(console.log(w.bold(`${e} ${o}`)),console.log(w.dim("\u2500".repeat(55))),!t||t.sessions===0){console.log(w.dim(" No activity in this period")),console.log();return}if(console.log(` Sessions: ${w.bold(ee(t.sessions))}`),console.log(` Avg interactions/sess: ${w.bold(t.avgInteractionsPerSession.toFixed(1))}`),console.log(` Total tokens: ${w.bold.yellow(ye(t.tokens))}`),t.thinkingTokens>0&&console.log(` Thinking tokens: ${w.dim(ye(t.thinkingTokens))} (included in total)`),console.log(` Avg tokens/session: ${w.bold(ye(t.avgTokensPerSession))}`),s.cost&&(t.estimatedCostCopilot??0)>0&&console.log(` Estimated cost (UBB): ${w.green("$"+(t.estimatedCostCopilot??0).toFixed(4))} ${w.dim("(Copilot AI Credits)")}`),s.models&&Object.keys(t.modelUsage).length>0){console.log(),console.log(w.dim(" Model Breakdown:"));let n=Object.entries(t.modelUsage).sort((i,r)=>r[1].inputTokens+r[1].outputTokens-(i[1].inputTokens+i[1].outputTokens));for(let[i,r]of n){let a=r.inputTokens+r.outputTokens,c=ls(i,Wt),d=c==="premium"?w.yellow(" \u2B50"):c==="standard"?w.dim(" \u25CB"):"";console.log(` ${(i+d).padEnd(35)} ${ye(r.inputTokens).padStart(8)} in ${ye(r.outputTokens).padStart(8)} out ${ye(a).padStart(8)} total`)}}if(Object.keys(t.editorUsage).length>1){console.log(),console.log(w.dim(" Editor Breakdown:"));let n=Object.entries(t.editorUsage).sort((i,r)=>r[1].tokens-i[1].tokens);for(let[i,r]of n)console.log(` ${i.padEnd(25)} ${ee(r.sessions).padStart(5)} sessions ${ye(r.tokens).padStart(8)} tokens`)}console.log()}var Ud=new de("environmental").alias("env").description("Show environmental impact of your Copilot usage (CO2, water, trees)").action(async()=>{console.log(w.bold.cyan(`
|
|
153
169
|
\u{1F30D} Copilot Token Tracker - Environmental Impact
|
|
154
|
-
`));let o=new
|
|
155
|
-
`));for(let i of s)
|
|
156
|
-
`))});function kd(o){return o==null||!Number.isFinite(o)||o<0?"0.000 gCO\u2082e":o>=1e3?`${(o/1e3).toFixed(2)} kgCO\u2082e`:`${o.toFixed(3)} gCO\u2082e`}function M_(o,e,t){if(console.log(T.bold(`${e} ${o}`)),console.log(T.dim("\u2500".repeat(55))),!t||t.sessions===0){console.log(T.dim(" No activity in this period")),console.log();return}if(console.log(` Tokens used: ${T.bold.yellow(he(t.tokens))}`),console.log(` CO\u2082 emissions: ${T.bold(kd(t.co2))}`),console.log(` Water usage: ${T.bold(t.waterUsage.toFixed(3))} liters`),t.treesEquivalent>0){let s=t.treesEquivalent<.001?t.treesEquivalent.toExponential(2):t.treesEquivalent.toFixed(6);console.log(` Trees to offset: ${T.green(s)} trees/year`)}console.log()}var Sd=["read_file","copilot_readFile","read","view","view_image","copilot_viewImage","list_dir","list_directory","ls","copilot_listDirectory","find_files","file_search","file_glob_search","copilot_findFiles","opilot_findFiles","copilot_findTextInFiles","copilot_findTestFiles","test_search","grep_search","grep","glob","rg","semantic_search","copilot_searchCodebase","code_search","copilot_getSearchResults","copilot_githubTextSearch","get_search_view_results","search_workspace_symbols","copilot_searchWorkspaceSymbols","vscode_listCodeUsages","get_symbols_by_name","get_errors","copilot_getErrors","get_changed_files","copilot_getChangedFiles","read_project_structure","copilot_readProjectStructure","get_doc_info","copilot_getDocInfo","get_vscode_api","copilot_getVSCodeAPI","get_project_setup_info","copilot_getProjectSetupInfo","get_files_in_project","get_projects_in_solution","get_python_executable_details","get_currentfile","get_file","vscode_get_confirmation","vscode_get_confirmation_with_options","vscode_get_terminal_confirmation","vscode_get_modified_files_confirmation","memory","copilot_memory","copilot_resolveMemoryFileUri","detect_memories","todo","tool_replay","copilot_toolReplay","tool_search","tool_search_tool","get_task_output","get_output_window_logs","job_output","get_terminal_output","await_terminal","terminal_selection","terminal_last_command","read_notebook_cell_output","copilot_readNotebookCellOutput","copilot_getNotebookSummary","test_failure","copilot_testFailure","ask_questions","AskUserQuestion","ask_user_question","copilot_askQuestions","switch_agent","copilot_switchAgent","bash","chmod","vscode_editFile_internal","vscode_fetchWebPage_internal","vscode_searchExtensions_internal","fetch_copilot_cli_documentation","generate_findings","generate_topics","list_bash","read_bash","write_bash","stop_bash","list_powershell","read_powershell","clarify_requirements","get_tests","ide-get_diagnostics","mcp__ide__getDiagnostics","plan","signal_plan_ready","update_plan_progress","EnterPlanMode","ExitPlanMode","stop_agent","mcp_reload","mcp_validate","add_loaded_assembly","analyze_symbol","search_decompiled_symbols","search_web"];var v_=new Set(Sd.map(o=>o.toLowerCase()));function $(o){return o.toLocaleString("en-US")}function ye(o,e){return Math.max(o,e)}var A_={1:"Stage 1: AI Skeptic",2:"Stage 2: AI Explorer",3:"Stage 3: AI Collaborator",4:"Stage 4: AI Strategist"},ct={promptEngineering:{stage2MinInteractions:5,stage2MinAvgTurns:3,stage3MinAvgTurns:5,stage3MinInteractions:30,stage3MinSlashCommands:2,stage4MinInteractions:100,stage4MinSlashCommands:3},contextEngineering:{stage2MinTotalRefs:1,stage3MinRefTypes:3,stage3MinTotalRefs:10,stage4MinRefTypes:5,stage4MinTotalRefs:30},agentic:{stage3MinAvgFilesPerSession:3,stage3MinAgentInteractions:10,stage3MinNonAutoTools:3,stage4MinAgentInteractions:50,stage4MinNonAutoTools:5,stage4MinMultiFileEdits:20,stage3MinMultiAgentParents:1,stage4MinMultiAgentParents:3,multiAgentMinChildren:2},toolUsage:{stage3MinAdvancedTools:2,stage4MinMcpServers:2},customization:{stage3MinCustomizationRate:.3,stage3MinCustomizedRepos:2,stage4MinCustomizationRate:.7,stage4MinCustomizedRepos:3,stage3MinUniqueModels:3,stage4MinUniqueModels:5},workflowIntegration:{stage2MinSessions:3,stage2MinApplyRatePct:50,stage3MinModesUsed:2,hasExplicitContextMinRefs:10,stage3MinContextRefs:20,stage4MinSessions:15}};function x_(o){let e=[...o].sort((n,i)=>n-i),t=Math.floor(e.length/2);return e.length%2===0?Math.round((e[t-1]+e[t])/2):e[t]}var D_=["explain","fix","tests","doc","generate","optimize","new","newNotebook","search","fixTestFailure","setupTests"],E_=["review","bug","think","compact","pr_comments"];function R_(o){return[...D_.filter(e=>(o[e]??0)>0),...E_.filter(e=>(o[`__slash__${e}`]??0)>0)]}function Td(o){return Object.keys(o).filter(e=>!v_.has(e.toLowerCase())&&!e.startsWith("__slash__")).length}function I_(o,e,t){return o>0||e>0||t>0}function U_(o,e){return o>0||e>0}function O_(o,e,t){let s=ct.promptEngineering;return o>=s.stage3MinInteractions&&(e.length>=s.stage3MinSlashCommands||t)}function F_(o,e,t,s){let n=ct.promptEngineering;return o>=n.stage4MinInteractions&&e&&(t||s.length>=n.stage4MinSlashCommands)}function N_(o,e,t){let s=[];return o||s.push("Try [agent mode](https://code.visualstudio.com/docs/copilot/agents/overview) for multi-file changes \u2014 [\u25B6 Agent Mode video](https://tech.hub.ms/github-copilot/videos/agent-mode)"),e.length<t.stage3MinSlashCommands&&s.push("Use [slash commands](https://code.visualstudio.com/docs/copilot/chat/copilot-chat#_add-context-to-your-prompts) like /explain, /fix, or /tests to give structured prompts"),s}function L_(o,e,t,s,n){let i=[];return o||i.push("Try [agent mode](https://code.visualstudio.com/docs/copilot/agents/overview) for autonomous, multi-step coding tasks"),e||i.push("Experiment with [different models](https://code.visualstudio.com/docs/copilot/chat/copilot-chat#_choose-a-language-model) for different tasks - use fast models for simple queries and reasoning models for complex problems \u2014 [\u25B6 Model selection video](https://tech.hub.ms/github-copilot/videos/model-selection)"),s===0?i.push("Try the Auto model for cost-sensitive tasks so Copilot can pick the most efficient model for you"):s<.5&&i.push("Use the Auto model more often when you want Copilot to balance quality and cost for you"),t.length<n.stage4MinSlashCommands&&o&&e&&i.push("Explore more [slash commands](https://code.visualstudio.com/docs/copilot/chat/copilot-chat#_add-context-to-your-prompts) like /explain, /tests, or /doc to diversify your prompting"),i}function j_(o,e,t,s,n){let i=ct.promptEngineering,r=[];return o<2&&r.push("Try asking Copilot a question using the Chat panel \u2014 [\u25B6 Chat in IDE video](https://tech.hub.ms/github-copilot/videos/chat-in-ide)"),o<3&&r.push(...N_(e,s,i)),o<4&&r.push(...L_(e,t,s,n,i)),r}function G_(o,e,t){if(!o.conversationPatterns)return t;let s=ct.promptEngineering,n=Math.round(o.conversationPatterns.multiTurnSessions/Math.max(1,o.sessions)*100);return o.conversationPatterns.multiTurnSessions>0&&e.push(`${$(o.conversationPatterns.multiTurnSessions)} multi-turn sessions (${n}%)`),o.conversationPatterns.avgTurnsPerSession>=s.stage2MinAvgTurns&&(e.push(`Avg ${o.conversationPatterns.avgTurnsPerSession.toFixed(1)} exchanges per session`),t=ye(t,2)),o.conversationPatterns.avgTurnsPerSession>=s.stage3MinAvgTurns&&(t=ye(t,3)),t}function q_(o){let{stage:e,evidence:t,usedSlashCommands:s,hasModelSwitching:n,hasAgentMode:i,autoUsageRatio:r}=H_(o);return{stage:e,evidence:t,tips:j_(e,i,n,s,r)}}function B_(o,e){let t=e.modeUsage.ask+e.modeUsage.edit+e.modeUsage.agent+e.modeUsage.cli;t>0&&o.push(`${$(t)} total interactions`),e.modeUsage.ask>0&&o.push(`${$(e.modeUsage.ask)} ask-mode conversations`),e.modeUsage.agent>0&&o.push(`${$(e.modeUsage.agent)} agent-mode interactions`),e.modeUsage.cli>0&&o.push(`${$(e.modeUsage.cli)} CLI interactions`)}function z_(o,e,t){e.modelSwitching.autoSessions>0&&o.push(`Auto model used in ${$(e.modelSwitching.autoSessions)} session${e.modelSwitching.autoSessions===1?"":"s"} (${Math.round(t*100)}%)`)}function $_(o,e,t){let s=o;return e>0&&(s=ye(s,2)),e>=.5&&(s=ye(s,3)),e>=.8&&t>=5&&(s=4),s}function W_(o,e,t,s){return e?(s.push(`Switched models in ${Math.round(t.modelSwitching.switchingFrequency)}% of sessions`),o<4&&(t.modelSwitching.mixedTierSessions>0||t.modelSwitching.mixedCostSessions>0)?ye(o,3):o):o}function H_(o){let e=[],t=ct.promptEngineering;B_(e,o);let s=o.modeUsage.ask+o.modeUsage.edit+o.modeUsage.agent+o.modeUsage.cli,n=G_(o,e,1);s>=t.stage2MinInteractions&&(n=2);let i=R_(o.toolCalls.byTool);i.length>0&&e.push(`Used slash commands: /${i.join(", /")}`);let r=I_(o.modelSwitching.mixedTierSessions,o.modelSwitching.mixedCostSessions,o.modelSwitching.switchingFrequency),a=U_(o.modeUsage.agent,o.modeUsage.cli),c=o.modelSwitching.totalSessions>0?o.modelSwitching.autoSessions/o.modelSwitching.totalSessions:0;return z_(e,o,c),O_(s,i,a)&&(n=3),F_(s,a,r,i)&&(n=4),n=$_(n,c,o.sessions),n=W_(n,r,o,e),{stage:n,evidence:e,usedSlashCommands:i,hasModelSwitching:r,hasAgentMode:a,autoUsageRatio:c}}function J_(o,e){if(o.length===0)return;let t=e.length>0?` \u2014 try ${e.slice(0,3).join(", ")}`:"";return`Stage 4 needs ${o.join(" and ")}${t}`}function V_(o,e){let t=o.filter(n=>!n.used).map(n=>n.name);if(t.length===0)return;let s=t.length>3?` and ${t.length-3} more`:"";return`Try ${t.slice(0,3).join(", ")}${s} \u2014 see ${e} to reach Stage 4`}function K_(o,e,t){let s=ct.contextEngineering,n=Math.max(0,s.stage4MinRefTypes-e),i=Math.max(0,s.stage4MinTotalRefs-t),r=[{name:"image attachments",used:(o.byKind?.["copilot.image"]??0)>0},{name:"prompt files",used:(o.byKind?.promptFile??0)>0},{name:"custom prompt commands",used:(o.byKind?.prompt??0)>0},{name:"#changes",used:o.changes>0},{name:"#problemsPanel",used:o.problemsPanel>0},{name:"#outputPanel",used:o.outputPanel>0},{name:"#terminalLastCommand",used:o.terminalLastCommand>0},{name:"#terminalSelection",used:o.terminalSelection>0},{name:"#clipboard",used:o.clipboard>0},{name:"@vscode",used:o.vscode>0}];if(r.filter(c=>c.used).length>=2){let c=[{name:"#symbol",used:o.symbol>0},{name:"@workspace",used:o.workspace>0},{name:"#codebase",used:o.codebase>0},{name:"@terminal",used:o.terminal>0},...r].filter(p=>!p.used).map(p=>p.name),m=[];return n>0&&m.push(`${$(e)} of ${s.stage4MinRefTypes} different reference types used`),i>0&&m.push(`${$(t)} of ${s.stage4MinTotalRefs} total references`),J_(m,c)}return V_(r,"[specialized context variables](https://code.visualstudio.com/docs/copilot/chat/copilot-chat#_add-context-to-your-prompts)")}function Q_(o,e,t){e>0&&o.push(`${$(e)} ${t}`)}function Y_(o){let e=[],t=[[o.file,"#file references"],[o.selection,"#selection references"],[o.codebase,"#codebase references"],[o.workspace,"@workspace references"],[o.terminal,"@terminal references"],[o.vscode,"@vscode references"],[o.clipboard,"#clipboard references"],[o.changes,"#changes references"],[o.problemsPanel,"#problemsPanel references"],[o.outputPanel,"#outputPanel references"],[o.terminalLastCommand,"#terminalLastCommand references"],[o.terminalSelection,"#terminalSelection references"],[o.byKind?.promptFile??0,"prompt file uses"],[o.byKind?.prompt??0,"custom prompt commands"],[o.codeContextLines??0,"lines of code context"]];for(let[s,n]of t)Q_(e,s,n);return e}function X_(o){return[o.file,o.selection,o.symbol,o.codebase,o.workspace,o.terminal,o.vscode,o.clipboard,o.changes,o.problemsPanel,o.outputPanel,o.terminalLastCommand,o.terminalSelection,o.byKind?.["copilot.image"]??0,o.byKind?.promptFile??0,o.byKind?.prompt??0].filter(Boolean).length}function Z_(o,e,t){let s=o.byKind["copilot.image"]||0;return s>0&&(e.push(`${$(s)} image references (vision)`),t=ye(t,3)),(o.byKind.promptFile||0)>0&&(t=ye(t,3)),t}function eC(o){let e=1,t=ct.contextEngineering,s=o.contextReferences,n=s.file+s.selection+s.symbol+s.codebase+s.workspace,i=X_(s),r=Y_(s);n>=t.stage2MinTotalRefs&&(e=2),i>=t.stage3MinRefTypes&&n>=t.stage3MinTotalRefs&&(e=3),i>=t.stage4MinRefTypes&&n>=t.stage4MinTotalRefs&&(e=4),e=Z_(s,r,e);let a=[];if(e<2&&a.push("Try adding [#file or #selection](https://code.visualstudio.com/docs/copilot/chat/copilot-chat#_add-context-to-your-prompts) references to give Copilot more context"),e<3&&a.push("Explore [@workspace, #codebase, and @terminal](https://code.visualstudio.com/docs/copilot/chat/copilot-chat#_add-context-to-your-prompts) for broader context"),e<4){let c=K_(s,i,n);c&&a.push(c)}return{stage:e,evidence:r,tips:a}}function tC(o,e,t){return o>=t.stage3MinAgentInteractions&&e>=t.stage3MinNonAutoTools}function sC(o,e,t){return o>=t.stage4MinAgentInteractions&&e>=t.stage4MinNonAutoTools}function nC(o,e){return!!o&&o.multiFileEdits>=e.stage4MinMultiFileEdits&&o.avgFilesPerSession>=e.stage3MinAvgFilesPerSession}function oC(o,e,t,s){if(o<e.stage3MinMultiAgentParents)return t;let n=o===1?"1 session":`${$(o)} sessions`;return s.push(`${n} with child workspaces (multi-agent orchestration)`),t=ye(t,3),o>=e.stage4MinMultiAgentParents&&(t=ye(t,4)),t}function iC(o){let e=[];return o<2&&e.push("Try [agent mode](https://code.visualstudio.com/docs/copilot/agents/overview) \u2014 it can run terminal commands, edit files, and explore your codebase autonomously \u2014 [\u25B6 Agent Mode video](https://tech.hub.ms/github-copilot/videos/agent-mode)"),o<3&&e.push("Use [agent mode](https://code.visualstudio.com/docs/copilot/agents/overview) for multi-step tasks; let it chain tools like file search, terminal, and code edits \u2014 [\u25B6 Agent Mode video](https://tech.hub.ms/github-copilot/videos/agent-mode)"),o<4&&e.push("Try [multi-agent orchestration](https://code.visualstudio.com/docs/copilot/agents/overview): start child sessions from a parent session to run multiple agents in parallel on independent sub-tasks"),e}function rC(o,e,t){let s=t;return e.modeUsage.agent>0&&(o.push(`${$(e.modeUsage.agent)} agent-mode interactions`),s=2),e.modeUsage.cli>0&&(o.push(`${$(e.modeUsage.cli)} CLI interactions`),s=ye(s,2)),e.toolCalls.total>0&&o.push(`${$(e.toolCalls.total)} tool calls executed`),e.modeUsage.edit>0&&o.push(`${$(e.modeUsage.edit)} edit-mode interactions`),s}function aC(o,e,t,s){if(!e.editScope)return t;let n=t,i=e.editScope.singleFileEdits+e.editScope.multiFileEdits,r=i>0?Math.round(e.editScope.multiFileEdits/i*100):0;return e.editScope.multiFileEdits>0&&(o.push(`${$(e.editScope.multiFileEdits)} multi-file edit sessions (${r}%)`),n=ye(n,2)),e.editScope.avgFilesPerSession>=s.stage3MinAvgFilesPerSession&&(o.push(`Avg ${e.editScope.avgFilesPerSession.toFixed(1)} files per edit session`),n=ye(n,3)),n}function lC(o,e,t,s){let n=o;e.agentTypes?.editsAgent&&(s.push(`${$(e.agentTypes.editsAgent)} edits agent sessions`),n=ye(n,2));let i=Td(e.toolCalls.byTool),r=e.modeUsage.agent+e.modeUsage.cli;return tC(r,i,t)&&(n=3),sC(r,i,t)&&(n=4),nC(e.editScope,t)&&(n=ye(n,4)),n=oC(e.multiAgentParentSessions??0,t,n,s),n}function cC(o){let e=[],t=1,s=ct.agentic;return t=rC(e,o,t),t=aC(e,o,t,s),t=lC(t,o,s,e),{stage:t,evidence:e,tips:iC(t)}}function wd(o,e,t){let s=[];return o<2&&s.push("Try [agent mode](https://code.visualstudio.com/docs/copilot/agents/overview) to let Copilot use built-in tools for file operations and terminal commands \u2014 [\u25B6 Agent Mode video](https://tech.hub.ms/github-copilot/videos/agent-mode)"),o<3&&(e.length===0&&!t?s.push("Set up [MCP servers](https://code.visualstudio.com/docs/copilot/customization/mcp-servers) to connect Copilot to external tools (databases, APIs, cloud services) \u2014 [\u25B6 MCP with Azure and GitHub](https://tech.hub.ms/github-copilot/videos/mcp-with-azure-and-github)"):e.length>0&&s.push("Explore [GitHub integrations](https://code.visualstudio.com/docs/copilot/agents/agent-tools) and advanced tools like editFiles and run_in_terminal")),o<4&&(e.length===1?s.push("Add more [MCP servers](https://code.visualstudio.com/docs/copilot/customization/mcp-servers) to expand Copilot's capabilities - check the VS Code MCP registry \u2014 [\u25B6 MCP with Azure and GitHub](https://tech.hub.ms/github-copilot/videos/mcp-with-azure-and-github)"):e.length===0&&!t?s.push("Explore the [VS Code MCP registry](https://code.visualstudio.com/docs/copilot/customization/mcp-servers) for tools that integrate with your workflow"):e.length>0&&s.push("You're using multiple MCP servers - keep exploring advanced tool combinations")),s}function uC(o,e,t){let s=Object.keys(e.toolCalls.byTool).length,n=Td(e.toolCalls.byTool),i=t;if(n>0){let r=s-n,a=r>0?` (+ ${$(r)} automatic)`:"";o.push(`${$(n)} intentional tools used${a}`),i=2}else s>0&&o.push(`${$(s)} tools used (all automatic \u2014 agent reads/searches)`);return i}function dC(o,e,t){return e.agentTypes?.workspaceAgent>0?(o.push(`${$(e.agentTypes.workspaceAgent)} @workspace agent sessions`),ye(t,3)):t}function mC(o,e,t,s){let n={github_pull_request:"GitHub Pull Request",github_repo:"GitHub Repository",run_in_terminal:"Run In Terminal",editFiles:"Edit Files",listFiles:"List Files"},i=Object.keys(n).filter(a=>(e.toolCalls.byTool[a]||0)>0),r=t;return i.length>0&&(o.push(`Advanced tools: ${i.map(a=>n[a]).join(", ")}`),i.length>=s.stage3MinAdvancedTools&&(r=ye(r,3))),r}function pC(o,e,t,s){let n=Object.keys(e.mcpTools.byServer),i=t;return e.mcpTools.total>0&&(o.push(`${$(e.mcpTools.total)} MCP tool calls across ${n.length} server(s)`),i=ye(i,3),n.length>=s.stage4MinMcpServers&&(i=4)),{stage:i,mcpServers:n}}function gC(o,e){let t=[],s=1,n=ct.toolUsage;s=uC(t,o,s),s=dC(t,o,s),s=mC(t,o,s,n);let i=e===!1;if(!i){let{stage:r,mcpServers:a}=pC(t,o,s,n);return s=r,{stage:s,evidence:t,tips:wd(s,a)}}return{stage:s,evidence:t,tips:wd(s,[],i)}}function fC(o,e,t){let s=e-t;if(s===0)return"All repos customized! Keep instructions up to date and add [skill files](https://code.visualstudio.com/docs/copilot/customization/agent-skills) or [MCP server configs](https://code.visualstudio.com/docs/copilot/customization/mcp-servers) for deeper integration";let n=`${$(s)} repo${s===1?"":"s"} still missing customization \u2014 add [instructions](https://code.visualstudio.com/docs/copilot/customization/custom-instructions), [agents.md](https://code.visualstudio.com/docs/copilot/customization/custom-instructions), or [MCP configs](https://code.visualstudio.com/docs/copilot/customization/mcp-servers) for full coverage.`,i=(o?.workspaces||[]).filter(a=>Object.values(a.typeStatuses).every(c=>c==="\u274C")).filter(a=>!a.workspacePath.startsWith("<unresolved:")).sort((a,c)=>c.interactionCount!==a.interactionCount?c.interactionCount-a.interactionCount:c.sessionCount-a.sessionCount).slice(0,3);if(i.length===0)return n;let r=i.map(a=>`${a.workspaceName} (${$(a.interactionCount)} interaction${a.interactionCount===1?"":"s"})`).join(`
|
|
157
|
-
`);return`${n}
|
|
158
|
-
|
|
159
|
-
Top repos to customize first:
|
|
160
|
-
${r}`}function hC(o,e,t,s){let n=1;return e>0&&(n=2),o>=s.stage3MinCustomizationRate&&e>=s.stage3MinCustomizedRepos&&(n=3),o>=s.stage4MinCustomizationRate&&e>=s.stage4MinCustomizedRepos&&(n=4),t>=s.stage3MinUniqueModels&&(n=ye(n,3)),t>=s.stage4MinUniqueModels&&e>=s.stage4MinCustomizedRepos&&(n=4),n}function yC(o,e,t){let s=[],n=e-t;return o<2&&s.push("Create a [.github/copilot-instructions.md](https://code.visualstudio.com/docs/copilot/customization/custom-instructions) or [CLAUDE.md](https://docs.anthropic.com/en/docs/claude-code/memory) file with project-specific guidelines \u2014 [\u25B6 User Instructions video](https://tech.hub.ms/github-copilot/videos/user-instructions)"),o<3&&s.push("Add [custom instructions](https://code.visualstudio.com/docs/copilot/customization/custom-instructions) to more repositories to standardize your Copilot experience \u2014 [\u25B6 User Instructions video](https://tech.hub.ms/github-copilot/videos/user-instructions)"),o<4&&n>0?s.push(`${$(t)} of ${$(e)} repos have customization \u2014 add [instructions and agents.md](https://code.visualstudio.com/docs/copilot/customization/custom-instructions) to the remaining ${$(n)} repo${n===1?"":"s"} for Stage 4`):o<4&&s.push("Aim for consistent customization across all projects with [instructions and agents.md](https://code.visualstudio.com/docs/copilot/customization/custom-instructions)"),s}function _C(o){return[...new Set([...o.modelSwitching.standardModels,...o.modelSwitching.premiumModels,...o.modelSwitching.lowCostModels,...o.modelSwitching.mediumCostModels,...o.modelSwitching.highCostModels])]}function CC(o,e,t,s){e>0&&o.push(`Worked in ${e} repositor${e===1?"y":"ies"}`),t.length>=s.stage3MinUniqueModels&&o.push(`Used ${t.length} different models`)}function bC(o,e,t){let s=o;return e.modelSwitching.foundryWindowsSessions>0&&(s=ye(s,2),t.push(`Used Microsoft Foundry / local models in ${$(e.modelSwitching.foundryWindowsSessions)} session${e.modelSwitching.foundryWindowsSessions===1?"":"s"}`)),e.modelSwitching.unknownProviderSessions>0&&(s=ye(s,2),t.push(`Used models from unknown providers in ${$(e.modelSwitching.unknownProviderSessions)} session${e.modelSwitching.unknownProviderSessions===1?"":"s"}`)),s}function kC(o,e,t,s,n){e>=4?o.push(`${$(t)} of ${$(s)} repos customized (${n.stage4MinCustomizationRate*100}%+ with ${n.stage4MinCustomizedRepos}+ repos \u2192 Stage 4)`):e>=3?o.push(`${$(t)} of ${$(s)} repos customized (${n.stage3MinCustomizationRate*100}%+ with ${n.stage3MinCustomizedRepos}+ repos \u2192 Stage 3)`):t>0&&o.push(`${$(t)} of ${$(s)} repos with custom instructions or agents.md`)}function SC(o,e,t,s,n,i,r){let a=[...o];return t.modelSwitching.foundryWindowsSessions===0&&a.unshift("Try the Microsoft Foundry on Windows extension if you want to experiment with local models and offline-friendly workflows"),t.modelSwitching.unknownProviderSessions===0&&s.length<=1&&a.unshift("Try different model providers from the marketplace when you want more specialized or cost-effective options"),e>=4&&a.push(fC(n,i,r)),a}function wC(o,e){let t=[],s=ct.customization,n=e,i=n?.totalWorkspaces??0,r=i-(n?.workspacesWithIssues??0),a=i>0?r/i:0,c=_C(o),m=hC(a,r,c.length,s);CC(t,i,c,s),m=bC(m,o,t),kC(t,m,r,i,s);let p=yC(m,i,r);return p=SC(p,m,o,c,n,i,r),{stage:m,evidence:t,tips:p}}function TC(o,e,t,s){return o>=s.stage4MinSessions&&e>=s.stage3MinModesUsed&&t>=s.stage3MinContextRefs}function MC(o,e,t,s){let n=[];return o<2&&n.push("Use AI more regularly - even for quick questions \u2014 [\u25B6 Chat in IDE video](https://tech.hub.ms/github-copilot/videos/chat-in-ide)"),o<3&&(e<s.stage3MinModesUsed&&n.push("Combine [ask mode with agent mode](https://code.visualstudio.com/docs/copilot/agents/overview) in your daily workflow \u2014 [\u25B6 Agent Mode video](https://tech.hub.ms/github-copilot/videos/agent-mode)"),t<s.hasExplicitContextMinRefs&&n.push("Use explicit [context references](https://code.visualstudio.com/docs/copilot/chat/copilot-chat#_add-context-to-your-prompts) like #file, @workspace, and #selection")),o<4&&(t<s.stage3MinContextRefs&&n.push("Make explicit context a habit - use [#file, @workspace, and other references](https://code.visualstudio.com/docs/copilot/chat/copilot-chat#_add-context-to-your-prompts) consistently"),n.push("Make AI part of every coding task: planning, coding, testing, and reviewing")),n}function PC(o){return o.contextReferences.file+o.contextReferences.selection+o.contextReferences.symbol+o.contextReferences.codebase+o.contextReferences.workspace}function vC(o){return[o.modeUsage.ask>0,o.modeUsage.agent>0,o.modeUsage.cli>0].filter(Boolean).length}function AC(o,e,t,s){return e.sessions>=s.stage2MinSessions?(o.push(`${$(e.sessions)} sessions in the last 30 days`),2):t}function xC(o,e,t,s){if(!e.applyUsage||e.applyUsage.totalCodeBlocks<=0)return t;let n=Math.round(e.applyUsage.applyRate);return o.push(`${n}% code block apply rate (${$(e.applyUsage.totalApplies)}/${$(e.applyUsage.totalCodeBlocks)})`),n>=s.stage2MinApplyRatePct?ye(t,2):t}function DC(o,e){if(e.sessionDuration&&e.sessionDuration.avgDurationMs>0&&o.push(`Avg ${Math.round(e.sessionDuration.avgDurationMs/6e4)}min session duration`),e.sessionDuration&&e.sessionDuration.activeDurationMs>0&&e.sessions>0){let t=Math.round(e.sessionDuration.activeDurationMs/e.sessions/6e4);o.push(`Avg ${t}min active time (interacting + waiting on the agent)`)}}function EC(o,e,t,s,n){let i=e;return t>=n.stage3MinModesUsed&&(o.push(`Uses ${t} modes (ask/agent/cli)`),i=ye(i,3)),s>=n.hasExplicitContextMinRefs&&(o.push(`${$(s)} explicit context references`),s>=n.stage3MinContextRefs&&(i=ye(i,3))),i}function RC(o,e,t,s,n,i){return TC(e.sessions,t,s,n)?(i.push("Deep integration: regular usage with multi-mode and explicit context"),4):o}function IC(o){let e=[],t=1,s=ct.workflowIntegration;t=AC(e,o,t,s),t=xC(e,o,t,s),DC(e,o);let n=PC(o),i=vC(o);return t=EC(e,t,i,n,s),t=RC(t,o,i,n,s,e),{stage:t,evidence:e,tips:MC(t,i,n,s)}}async function Wi(o,e,t=!0,s){let n=await e(t),i=n.last30Days,r=q_(i),a=eC(i),c=cC(i),m=gC(i,s),p=wC(i,o),f=IC(i),h=x_([r.stage,a.stage,c.stage,m.stage,p.stage,f.stage]);return{overallStage:h,overallLabel:A_[h]??`Stage ${h}`,categories:[{category:"Prompt Engineering",icon:"\u{1F4AC}",stage:r.stage,evidence:r.evidence,tips:r.tips},{category:"Context Engineering",icon:"\u{1F4CE}",stage:a.stage,evidence:a.evidence,tips:a.tips},{category:"Agentic",icon:"\u{1F916}",stage:c.stage,evidence:c.evidence,tips:c.tips},{category:"Tool Usage",icon:"\u{1F527}",stage:m.stage,evidence:m.evidence,tips:m.tips},{category:"Customization",icon:"\u2699\uFE0F",stage:p.stage,evidence:p.evidence,tips:p.tips},{category:"Workflow Integration",icon:"\u{1F504}",stage:f.stage,evidence:f.evidence,tips:f.tips}],period:i,lastUpdated:n.lastUpdated.toISOString()}}var Md=new ue("fluency").description("Show your Copilot Fluency Score and improvement tips").option("-t, --tips","Show improvement tips for each category").option("--json","Output raw JSON (for machine consumption)").action(async o=>{let e=Me(o);e||console.log(T.bold.cyan(`
|
|
170
|
+
`));let o=new Be;o.show("Scanning for session files...");let e=await ke();if(o.done(),e.length===0){console.log(w.yellow("\u26A0\uFE0F No session files found."));return}o.show("Calculating usage...");let t=await Jt(e,(i,r)=>{o.update(`Processing: ${i}/${r} files`)});o.done();let s=[{label:"Today",emoji:"\u{1F4C5}",stats:t.today},{label:"This Month",emoji:"\u{1F4C6}",stats:t.month},{label:"Last Month",emoji:"\u{1F5D3}\uFE0F",stats:t.lastMonth},{label:"Last 30 Days",emoji:"\u{1F4C8}",stats:t.last30Days}];console.log(w.dim("Methodology: Estimates based on industry averages for AI inference")),console.log(w.dim(` CO\u2082: ${qe.CO2_PER_1K_TOKENS} gCO\u2082e per 1K tokens`)),console.log(w.dim(` Water: ${qe.WATER_USAGE_PER_1K_TOKENS} L per 1K tokens`)),console.log(w.dim(` Tree absorption: ${Od(qe.CO2_ABSORPTION_PER_TREE_PER_YEAR)} CO\u2082/year
|
|
171
|
+
`));for(let i of s)YC(i.label,i.emoji,i.stats);let n=t.last30Days;if(n.tokens>0){console.log(w.bold("\u{1F504} Context Comparisons (Last 30 Days)")),console.log(w.dim("\u2500".repeat(55)));let i=n.co2,r=n.waterUsage,a=i/qe.CO2_PER_KM_DRIVING;console.log(` \u{1F697} Equivalent to driving: ${a.toFixed(3)} km`);let c=i/qe.CO2_PER_PHONE_CHARGE;console.log(` \u{1F4F1} Smartphone charges: ${c.toFixed(1)}`);let d=r/qe.WATER_PER_COFFEE_CUP;console.log(` \u2615 Cups of coffee (water): ${d.toFixed(4)}`);let p=i/qe.CO2_PER_LED_HOUR;console.log(` \u{1F4A1} LED bulb hours: ${p.toFixed(2)}`),console.log()}console.log(w.dim(`Last updated: ${t.lastUpdated.toLocaleString()}
|
|
172
|
+
`))});function Od(o){return o==null||!Number.isFinite(o)||o<0?"0.000 gCO\u2082e":o>=1e3?`${(o/1e3).toFixed(2)} kgCO\u2082e`:`${o.toFixed(3)} gCO\u2082e`}function YC(o,e,t){if(console.log(w.bold(`${e} ${o}`)),console.log(w.dim("\u2500".repeat(55))),!t||t.sessions===0){console.log(w.dim(" No activity in this period")),console.log();return}if(console.log(` Tokens used: ${w.bold.yellow(ye(t.tokens))}`),console.log(` CO\u2082 emissions: ${w.bold(Od(t.co2))}`),console.log(` Water usage: ${w.bold(t.waterUsage.toFixed(3))} liters`),t.treesEquivalent>0){let s=t.treesEquivalent<.001?t.treesEquivalent.toExponential(2):t.treesEquivalent.toFixed(6);console.log(` Trees to offset: ${w.green(s)} trees/year`)}console.log()}var Fd=new de("fluency").description("Show your Copilot Fluency Score and improvement tips").option("-t, --tips","Show improvement tips for each category").option("--json","Output raw JSON (for machine consumption)").action(async o=>{let e=Me(o);e||console.log(w.bold.cyan(`
|
|
161
173
|
\u{1F3AF} Copilot Token Tracker - Fluency Score
|
|
162
|
-
`));let t=new
|
|
163
|
-
`))});function
|
|
174
|
+
`));let t=new Be(e);t.show("Scanning for session files...");let s=await ke();if(t.done(),s.length===0){e?process.stdout.write("{}"):console.log(w.yellow("\u26A0\uFE0F No session files found."));return}t.show("Analyzing usage patterns...");let n=await Vt(s);t.done();let i=await $i(s),r=await Mi(i,async()=>n,!1);if(e){process.stdout.write(JSON.stringify(Yi(r)));return}let a={1:w.red,2:w.yellow,3:w.blue,4:w.green},c=_=>{let C=Number.isFinite(_)&&_>=1&&_<=4?Math.floor(_):0,T="\u2588".repeat(C),E="\u2591".repeat(4-C);return T+E};console.log(w.bold("Overall Fluency Score")),console.log(w.dim("\u2500".repeat(55)));let d=a[r.overallStage]||w.white;console.log(` ${d(c(r.overallStage))} ${w.bold(r.overallLabel)}`),console.log(),console.log(w.bold("Category Breakdown")),console.log(w.dim("\u2500".repeat(55)));for(let _ of r.categories){let C=a[_.stage]||w.white;if(console.log(` ${_.icon} ${w.bold(_.category)}`),console.log(` ${C(c(_.stage))} Stage ${_.stage}/4`),_.evidence.length>0){let T=_.evidence.slice(0,3);for(let E of T)console.log(w.dim(` \u2713 ${E}`));_.evidence.length>3&&console.log(w.dim(` ... and ${_.evidence.length-3} more`))}if(_.tips.length>0&&_.stage<4){console.log(w.yellow(" \u{1F4A1} Tips:"));for(let T of _.tips.slice(0,2)){let E=T.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\[▶ [^\]]+\]\([^)]+\)/g,"").trim();console.log(w.yellow(` \u2192 ${E}`))}}console.log()}let p=r.period;console.log(w.bold("\u{1F4CA} Analysis Period (Last 30 Days)")),console.log(w.dim("\u2500".repeat(55))),console.log(` Sessions analyzed: ${w.bold(ee(p.sessions))}`);let f=p.modeUsage.ask+p.modeUsage.edit+p.modeUsage.agent+p.modeUsage.cli;console.log(` Total interactions: ${w.bold(ee(f))}`),p.modeUsage.ask>0&&console.log(` Ask mode: ${ee(p.modeUsage.ask)}`),p.modeUsage.edit>0&&console.log(` Edit mode: ${ee(p.modeUsage.edit)}`),p.modeUsage.agent>0&&console.log(` Agent mode: ${ee(p.modeUsage.agent)}`),p.modeUsage.cli>0&&console.log(` CLI: ${ee(p.modeUsage.cli)}`),p.toolCalls.total>0&&console.log(` Tool calls: ${ee(p.toolCalls.total)}`),p.mcpTools.total>0&&console.log(` MCP tool calls: ${ee(p.mcpTools.total)}`);let h=p.contextReferences.file+p.contextReferences.selection+p.contextReferences.codebase+p.contextReferences.workspace+p.contextReferences.terminal+p.contextReferences.vscode;h>0&&console.log(` Context references: ${ee(h)}`),console.log(),console.log(w.dim(`Last updated: ${r.lastUpdated}
|
|
175
|
+
`))});function XC(o,e){let t=Eo(o),s=t.includes("opencode.db#")?t.split("#")[0]:t,n=null,i=0;for(let r of e){let a=Eo(r.path);s.startsWith(a)&&a.length>i&&(n={path:r.path,source:r.source},i=a.length)}return n}function Ba(o,e=55){if(!o)return"";if(o.length<=e)return o;let t=o.replace(/\\/g,"/").split("/"),s=o;for(let n=t.length-1;n>1&&(s="\u2026/"+t.slice(-n).join("/"),!(s.length<=e));n--);return s}function Nd(o,e,t){if(!o||!e||!t)return;if(o.length!==t.length)throw new Error(`printTable: headers.length (${o.length}) !== colWidths.length (${t.length})`);let s=w.dim("\u2500".repeat(t.reduce((i,r)=>i+r+3,-1))),n=o.map((i,r)=>w.bold(i.padEnd(t[r]))).join(" \u2502 ");console.log(" "+n),console.log(" "+s);for(let i of e){let r=i.map((a,c)=>{let d=a.padEnd(t[c]);return c===0?w.dim(d):d}).join(w.dim(" \u2502 "));console.log(" "+r)}console.log(" "+s)}var Ld=new de("diagnostics").description("Show session file search locations and per-location usage stats").action(async()=>{console.log(w.bold.cyan(`
|
|
164
176
|
\u{1F52C} Copilot Token Tracker - Diagnostics
|
|
165
|
-
`));let o=
|
|
177
|
+
`));let o=Hi(),e=o.filter(A=>A.exists),t=o.filter(A=>!A.exists);console.log(w.bold(`\u{1F4C2} Search Locations (${e.length} found / ${o.length} total)`)),console.log(w.dim("\u2500".repeat(65)));let s=["Source","Exists","Path"],n=[18,6,55],i=o.map(A=>[A.source,A.exists?w.green("yes"):w.dim("no"),Ba(A.path,55)]);if(Nd(s,i,n),console.log(),e.length===0){console.log(w.yellow("\u26A0\uFE0F No search paths exist on this machine.")),console.log(w.dim("Have you used GitHub Copilot Chat in VS Code yet?"));return}let r=new Be;r.show("Scanning for session files...");let a=await ke();if(r.done(),a.length===0){console.log(w.yellow("\u26A0\uFE0F No session files found in any search path."));return}let c=new Map;for(let A of e)c.set(A.path,{label:Ba(A.path,45),source:A.source,files:0,sessions:0,interactions:0,tokens:0});let d=0,p=0,f=0,h=0;for(let A=0;A<a.length;A++){((A+1)%25===0||A===a.length-1)&&r.update(`Processing: ${A+1}/${a.length} files...`);let R=XC(a[A],o),B=R?R.path:"__unknown__";c.has(B)||c.set(B,{label:R?Ba(R.path,45):"(unknown)",source:R?R.source:"unknown",files:0,sessions:0,interactions:0,tokens:0});let F=c.get(B);F.files++,d++;let P=await fs(a[A]);P&&P.tokens>0&&(F.sessions++,F.interactions+=P.interactions,F.tokens+=lt(P),p++,f+=P.interactions,h+=lt(P))}r.done(),console.log(w.bold("\u{1F4CA} Stats per Search Location")),console.log(w.dim("\u2500".repeat(65)));let _=["Source","Files","Sessions","Turns","Tokens"],C=[18,6,9,8,14],T=[],E=[...c.values()].filter(A=>A.files>0).sort((A,R)=>R.tokens-A.tokens||A.source.localeCompare(R.source));for(let A of E)T.push([A.source,ee(A.files),ee(A.sessions),ee(A.interactions),ye(A.tokens)]);T.length===0?console.log(w.dim(" No session data found in any location.")):Nd(_,T,C),console.log(),console.log(w.bold("\u{1F4C8} Totals (all time)")),console.log(w.dim("\u2500".repeat(65))),console.log(` Total files found: ${w.bold(ee(d))}`),console.log(` Files with data: ${w.bold(ee(p))}`),console.log(` Total chat turns: ${w.bold(ee(f))}`),console.log(` Total tokens: ${w.bold.yellow(ye(h))}`),t.length>0&&(console.log(),console.log(w.dim(`\u2139\uFE0F ${t.length} search path(s) not present on this machine \u2014 this is normal if you don't use all VS Code variants.`))),console.log()});var jd=new de("chart").description("Output daily token usage data for the chart webview").option("--json","Output raw JSON (for machine consumption)").option("-v, --verbose","Show debug log discovery details").action(async o=>{let e=await ke();if(e.length===0){Me(o)?process.stdout.write(JSON.stringify(Ji())):console.log(w.yellow("\u26A0\uFE0F No session files found."));return}let t=o.verbose===!0,{labels:s,days:n,allDaysMap:i}=await Wi(e,t),r=to(s,n,i);if(Me(o)){process.stdout.write(JSON.stringify(r));return}console.log(w.bold.cyan(`
|
|
166
178
|
\u{1F4CA} Token Usage Summary
|
|
167
|
-
`));let a=r.periods||{},c=[{key:"day",label:"Daily (last 30 days)"},{key:"week",label:"Weekly (last 6 weeks)"},{key:"month",label:"Monthly (last 12 months)"}];for(let{key:
|
|
168
|
-
`);return}let e=await ke(),t=new Date;if(e.length===0){process.stdout.write(JSON.stringify(
|
|
169
|
-
`)}return i?i.replace(/^["']|["']$/g,""):void 0}}function
|
|
170
|
-
`);return}let p=
|
|
179
|
+
`));let a=r.periods||{},c=[{key:"day",label:"Daily (last 30 days)"},{key:"week",label:"Weekly (last 6 weeks)"},{key:"month",label:"Monthly (last 12 months)"}];for(let{key:d,label:p}of c){let f=a[d];if(!f)continue;console.log(w.bold(p)),console.log(w.dim("\u2500".repeat(60)));let h=(f.labels||[]).map((R,B)=>{let F=f.tokensData?.[B]??0,P=f.costData?.[B]??0;return{Period:R,Tokens:ee(F),Cost:`$${P.toFixed(2)}`}});h.length>0&&console.table(h);let _=f.totalTokens??0,C=f.totalCost??0,T=f.periodCount??0,E=T>0?Math.round(_/T):0,A=T>0?C/T:0;console.log(w.bold("Totals:")),console.log(` Total Tokens: ${ee(_)}`),console.log(` Total Cost: $${C.toFixed(2)}`),console.log(` Avg per Period: ${ee(E)} tokens, $${A.toFixed(2)} cost`),console.log()}});var Gd=new de("usage-analysis").description("Output usage analysis stats for the usage analysis webview").option("--json","Output raw JSON (for machine consumption)").action(async o=>{if(!Me(o)){process.stderr.write(`Use --json flag for usage analysis data output
|
|
180
|
+
`);return}let e=await ke(),t=new Date;if(e.length===0){process.stdout.write(JSON.stringify(Vi(t)));return}let s=await Vt(e),n=Qi(s,t);process.stdout.write(JSON.stringify(n))});var De=S(require("fs")),Y=S(require("path")),Bd=require("url");var ZC=4,zd=1;function eb(o){try{if(!De.existsSync(o))return[];let e=De.readFileSync(o,"utf-8"),s=JSON.parse(e)?.servers;return!s||typeof s!="object"?[]:Object.keys(s)}catch{return[]}}function tb(o){return[Y.join(o,".vscode","mcp.json"),Y.join(o,".mcp.json"),Y.join(o,".vs","mcp.json"),Y.join(o,".cursor","mcp.json")]}function sb(){let o=process.env.USERPROFILE??process.env.HOME??"";return o?[Y.join(o,".mcp.json")]:[]}function Zi(o){let e=[],t=new Map,s=new Set,n=[...o.flatMap(tb),...sb()];for(let i of n)for(let r of eb(i)){t.has(r)||t.set(r,[]);let a=t.get(r);a.includes(i)||a.push(i),s.has(r)||(s.add(r),e.push({name:`mcp__${r}`,description:`MCP server: ${r}`,source:"mcp",server:r,configFiles:a}))}return e}function nb(o,e){try{let t=De.readFileSync(o,"utf-8"),s=ob(t);if(s)return s}catch{}return e}function ob(o){let e=ib(o);if(e!==void 0){let n=ab(e);if(n)return n}let t=/^description:\s+(?!>|[|])(.+)/im.exec(o);if(t)return t[1].trim().replace(/^["']|["']$/g,"");let s=/^#\s+(.+)/m.exec(o);if(s)return s[1].trim()}function ib(o){let e=o.replace(/^\uFEFF/,"").trimStart();if(!/^---(?:\r?\n|$)/.test(e))return;let t=e.slice(3),s=t.search(/\n---(?:\r?\n|$)/m);if(s!==-1)return t.slice(0,s)}function rb(o,e,t){let s=[];for(let n=e;n<o.length;n++){let i=o[n];if(i.trim()===""){s.push("");continue}if((i.match(/^(\s*)/)?.[1].length??0)<=t)break;s.push(i.trim())}for(;s.length>0&&s[s.length-1]==="";)s.pop();return s}function ab(o){let e=o.split(/\r?\n/);for(let t=0;t<e.length;t++){let s=/^(\s*)description:\s*(.*)/i.exec(e[t]);if(!s)continue;let n=s[1].length,i=s[2].trim(),r=/^([|>])[-+>]?\s*$/.exec(i);if(r){let a=rb(e,t+1,n);return a.length===0?void 0:r[1]===">"?a.join(" "):a.join(`
|
|
181
|
+
`)}return i?i.replace(/^["']|["']$/g,""):void 0}}function za(o){try{if(!De.existsSync(o))return;let e=De.readFileSync(o,"utf-8");return JSON.parse(e)}catch{return}}function Xi(o,e,t,s){let n;try{n=De.readdirSync(e,{withFileTypes:!0})}catch{return[]}let i=[];for(let r of n){if(!r.isDirectory())continue;let a=Y.join(e,r.name,"SKILL.md");if(!De.existsSync(a)||t.has(a))continue;t.add(a);let c=nb(a,`Skill: ${r.name}`),d=Y.relative(o,a).replace(/\\/g,"/"),p={name:r.name,description:c,source:"skill",skillPath:d,configFiles:[a]};s&&(p.pluginName=s),i.push(p)}return i}var lb=new Set([".git","node_modules","dist","out","build",".next",".venv","venv","target",".idea",".vscode"]),cb=4,ub=400;function db(o,e=cb){let t=[],s=new Set,n=0,i=(r,a)=>{if(a>e||s.has(r)||n>=ub)return;s.add(r),n++;let c;try{c=De.readdirSync(r,{withFileTypes:!0})}catch{return}for(let d of c){if(!d.isDirectory()||lb.has(d.name))continue;let p=Y.join(r,d.name);if(d.name==="skills"){t.push(p);continue}i(p,a+1)}};return i(o,0),t}function qd(o,e,t){if(!De.existsSync(e))return[];let s=[];s.push(...Xi(o,e,t));for(let n of db(e))s.push(...Xi(o,n,t));return s}function $d(o,e){let t=o.trim();return t?(t.startsWith("~")&&(t==="~"?t=e:(t.startsWith("~/")||t.startsWith("~\\"))&&(t=Y.join(e,t.slice(2)))),t=t.replace(/\$\{env:([^}]+)\}/gi,(s,n)=>process.env[n]??""),t=t.replace(/%([^%]+)%/g,(s,n)=>process.env[n]??""),Y.isAbsolute(t)||(t=Y.resolve(e,t)),t):""}function mb(o){let e=process.env.APPDATA??Y.join(o,"AppData","Roaming");return process.platform==="win32"?[Y.join(e,"Code","User","settings.json"),Y.join(e,"Code - Insiders","User","settings.json")]:process.platform==="darwin"?[Y.join(o,"Library","Application Support","Code","User","settings.json"),Y.join(o,"Library","Application Support","Code - Insiders","User","settings.json")]:[Y.join(o,".config","Code","User","settings.json"),Y.join(o,".config","Code - Insiders","User","settings.json")]}function pb(o){let e=new Set;for(let t of mb(o)){let n=za(t)?.["chat.agentSkillsLocations"];if(Array.isArray(n))for(let i of n){if(typeof i!="string")continue;let r=$d(i,o);r&&e.add(r)}}return[...e]}var gb=[".github/skills",".claude/skills",".agents/skills"];function fb(){let o=process.env.USERPROFILE??process.env.HOME??"";return o?[Y.join(o,".copilot","skills"),Y.join(o,".claude","skills"),Y.join(o,".agents","skills")]:[]}function hb(o){try{let e=new URL(o);return e.protocol!=="file:"?void 0:Y.normalize((0,Bd.fileURLToPath)(e))}catch{return}}function yb(o){let e=za(Y.join(o,"plugin.json")),t;return Array.isArray(e?.skills)?t=e.skills.filter(s=>typeof s=="string"):typeof e?.skills=="string"?t=[e.skills]:t=["./skills/"],t.map(s=>Y.resolve(o,s)).filter(s=>De.existsSync(s))}function _b(o){let e=za(Y.join(o,"installed.json"));if(!Array.isArray(e?.installed))return[];let t=[];for(let s of e.installed){if(typeof s!="object"||s===null)continue;let n=s,i=n.pluginUri;if(typeof i!="string")continue;let r=hb(i);if(!r||!De.existsSync(r))continue;let a=typeof n.name=="string"&&n.name?n.name:Y.basename(r);for(let c of yb(r))t.push({dir:c,pluginName:a})}return t}function Cb(){let o=process.env.USERPROFILE??process.env.HOME??"";if(!o)return[];let e=[Y.join(o,".vscode","agent-plugins"),Y.join(o,".vscode-insiders","agent-plugins")],t=[];for(let s of e)t.push(..._b(s));return t}function er(o,e){let t=[],s=new Set;for(let a of o)for(let c of gb){let d=Y.join(a,...c.split("/"));De.existsSync(d)&&t.push(...Xi(a,d,s))}let n=process.env.USERPROFILE??process.env.HOME??"";for(let a of fb())t.push(...qd(n,a,s));for(let{dir:a,pluginName:c}of Cb())t.push(...Xi(n,a,s,c));let i=Array.isArray(e?.additionalSkillDirs)?e.additionalSkillDirs:[],r=[...pb(n),...i.filter(a=>typeof a=="string").map(a=>$d(a,n)).filter(Boolean)];for(let a of r)t.push(...qd(n,a,s));return t}function Hd(o){return Math.round(o.reduce((e,t)=>e+(t.name.length+t.description.length+10),0)/ZC)}function bb(o){let e={};for(let[t,s]of Object.entries(o.toolCalls.byTool))e[t]=(e[t]??0)+s;for(let[t,s]of Object.entries(o.mcpTools.byTool))e[t]=(e[t]??0)+s;return e}function kb(o,e,t){let s=new Set;for(let n of o)n.source==="mcp"&&n.server&&s.add(n.server);return Array.from(s).map(n=>{let i=o.filter(h=>h.source==="mcp"&&h.server===n),r=i.filter(h=>h.name===`mcp__${n}`?(t.mcpTools.byServer[n]??0)>=zd:e.has(h.name)),a=[...new Set(i.flatMap(h=>h.configFiles??[]))],c=i.find(h=>h.extensionId),d=c?.extensionId,p=c?.enabled,f=c?.extensionActive;return{server:n,availableToolCount:i.length,usedToolCount:r.length,configFiles:a.length>0?a:void 0,extensionId:d,enabled:p,extensionActive:f}}).filter(n=>n.enabled!==!1)}function Sb(o){let e={};for(let s of o){let n=s.server??s.source;e[n]||(e[n]=[]),e[n].push(s)}let t={};for(let[s,n]of Object.entries(e))t[s]=Hd(n);return{totalTokens:Object.values(t).reduce((s,n)=>s+n,0),byServer:t}}function Tb(o,e,t){let s=[];for(let n of o)if(n.usedToolCount===0){let i=e.filter(r=>r.source==="mcp"&&r.server===n.server);s.push({type:"disable-mcp-server",target:n.server,reason:`No tools from the "${n.server}" MCP server were used in the last ${t} days.`,estimatedTokenSavings:Hd(i)})}for(let n of e.filter(i=>i.source==="skill"))s.push({type:"refine-skill",target:n.name,reason:`The "${n.name}" skill was not invoked in the last ${t} days. Consider updating its description or removing it to reduce instruction-file bloat.`});return s}function wb(o,e){let t=new Map;for(let n of o){if(n.source!=="skill"||!n.pluginName)continue;let i=t.get(n.name)??new Set;i.add(n.pluginName),t.set(n.name,i)}let s=new Map;for(let n of o){if(n.source!=="skill"||!n.pluginName)continue;let i=s.get(n.pluginName)??{available:0,used:0};i.available++,e.has(n.name)&&(t.get(n.name)?.size??0)===1&&i.used++,s.set(n.pluginName,i)}return Array.from(s.entries()).map(([n,{available:i,used:r}])=>({pluginName:n,availableSkillCount:i,usedSkillCount:r})).sort((n,i)=>n.usedSkillCount-i.usedSkillCount)}function tr(o,e,t){let s=bb(e),n=Object.entries(s).map(([f,h])=>({name:f,count:h})).sort((f,h)=>h.count-f.count),i=new Set(Object.keys(s)),r=o.filter(f=>f.source==="skill"?!i.has(f.name):f.source==="mcp"&&f.server?f.enabled===!1?!1:f.name===`mcp__${f.server}`?(e.mcpTools.byServer[f.server]??0)<zd:!i.has(f.name):!i.has(f.name)),a=kb(o,i,e),c=wb(o,i),d=Sb(r),p=Tb(a,r,t);return{windowDays:t,availableTools:o,usedTools:n,unusedTools:r,underusedMcpServers:a,underusedAgentPlugins:c,estimatedPromptBloat:d,recommendations:p}}var no=30,Wd=new de("curation").description("Analyse tool curation: compare available MCP servers and skills against actual usage").option("--json","Output raw JSON (for machine consumption)").option("--window <days>",`Look-back window in days (default: ${no})`,String(no)).action(async o=>{let e=Math.max(1,parseInt(o.window??String(no),10)||no),t=process.cwd(),s=await ke(),i=(s.length>0?await Vt(s):null)?.last30Days,r=[t],a=Zi(r),c=er(r),d=[...a,...c];if(d.length===0&&!i){Me(o)?process.stdout.write(JSON.stringify(sr(e))):process.stderr.write(`No MCP servers or skills found in the current directory, and no session data available.
|
|
182
|
+
`);return}let p=tr(d,i??gs(),e);Me(o)?process.stdout.write(JSON.stringify(p)):Mb(p)});function sr(o=no){return{windowDays:o,availableTools:[],usedTools:[],unusedTools:[],underusedMcpServers:[],underusedAgentPlugins:[],estimatedPromptBloat:{totalTokens:0,byServer:{}},recommendations:[]}}function Mb(o){let{availableTools:e,usedTools:t,unusedTools:s,underusedMcpServers:n,estimatedPromptBloat:i,recommendations:r,windowDays:a}=o;if(process.stdout.write(`
|
|
171
183
|
Tool Curation Report (last ${a} days)
|
|
172
184
|
`),process.stdout.write("=".repeat(50)+`
|
|
173
185
|
|
|
@@ -176,17 +188,17 @@ Tool Curation Report (last ${a} days)
|
|
|
176
188
|
`),process.stdout.write(`Unused tools: ${s.length}
|
|
177
189
|
`),i.totalTokens>0&&process.stdout.write(`Est. overhead: ~${i.totalTokens.toLocaleString()} tokens/interaction
|
|
178
190
|
`),process.stdout.write(`
|
|
179
|
-
`),n.length>0){let
|
|
180
|
-
`);for(let p of
|
|
191
|
+
`),n.length>0){let d=n.filter(p=>p.usedToolCount===0);if(d.length>0){process.stdout.write(`Unused MCP Servers:
|
|
192
|
+
`);for(let p of d){let f=i.byServer[p.server],h=f?` (~${f.toLocaleString()} tokens overhead)`:"";process.stdout.write(` \u2022 ${p.server}${h}
|
|
181
193
|
`)}process.stdout.write(`
|
|
182
|
-
`)}}let c=s.filter(
|
|
183
|
-
`);for(let
|
|
194
|
+
`)}}let c=s.filter(d=>d.source==="skill");if(c.length>0){process.stdout.write(`Unused Skills:
|
|
195
|
+
`);for(let d of c)process.stdout.write(` \u2022 ${d.name}
|
|
184
196
|
`);process.stdout.write(`
|
|
185
197
|
`)}if(r.length>0){process.stdout.write(`Recommendations:
|
|
186
|
-
`);for(let
|
|
198
|
+
`);for(let d of r){let p=d.estimatedTokenSavings?` (saves ~${d.estimatedTokenSavings.toLocaleString()} tokens/interaction)`:"";process.stdout.write(` \u2192 ${d.reason}${p}
|
|
187
199
|
`)}process.stdout.write(`
|
|
188
200
|
`)}if(t.length>0){process.stdout.write(`Top Used Tools (last ${a}d):
|
|
189
|
-
`);for(let
|
|
201
|
+
`);for(let d of t.slice(0,10))process.stdout.write(` ${String(d.count).padStart(5)}x ${d.name}
|
|
190
202
|
`);process.stdout.write(`
|
|
191
|
-
`)}}var
|
|
192
|
-
`);return}let e=new Date,t=await ke();if(t.length===0){let F={details:
|
|
203
|
+
`)}}var Jd=new de("all").description("Output all view data in a single JSON response (for Visual Studio extension)").option("--json","Output raw JSON (required)").action(async o=>{if(!Me(o)){process.stderr.write(`Use --json flag for all data output
|
|
204
|
+
`);return}let e=new Date,t=await ke();if(t.length===0){let F={details:Ed(e),chart:Ji(e),usage:Vi(e),fluency:Rd(),curation:sr()};process.stdout.write(JSON.stringify(F));return}let[s,{labels:n,days:i,allDaysMap:r},a]=await Promise.all([Jt(t),Wi(t),Vt(t)]),c=to(n,i,r),d=Ki(s),p=Qi(a,e),f=await $i(t),h=await Mi(f,async()=>a,!1),_=Yi(h),C=process.cwd(),T=Zi([C]),E=er([C]),A=[...T,...E],R=A.length>0?tr(A,a.last30Days,30):sr(),B={details:d,chart:c,usage:p,fluency:_,curation:R};process.stdout.write(JSON.stringify(B))});var Kt=S(require("fs")),Wa=S(require("path")),Kd=S(require("os"));var Qd=Wa.join(Kd.homedir(),".copilot-token-tracker"),Ha=Wa.join(Qd,"omp-segment-cache.json"),$a=5;function Pb(o){try{if(!Kt.existsSync(Ha))return null;let e=JSON.parse(Kt.readFileSync(Ha,"utf-8"));if(typeof e.formatted!="string"||typeof e.updatedAt!="string"||typeof e.todayTokens!="number"||typeof e.thisMonthTokens!="number"||typeof e.last30DaysTokens!="number")return null;let t=Date.parse(e.updatedAt);if(!Number.isFinite(t))return null;let s=Date.now()-t;return s<0||s>o*6e4?null:e}catch{return null}}function Vd(o){try{Kt.mkdirSync(Qd,{recursive:!0}),Kt.writeFileSync(Ha,JSON.stringify(o),"utf-8")}catch{}}var Yd=new de("segment").description("Output a compact token usage string for use in oh-my-posh prompt segments").option("--ttl <minutes>",`Segment cache TTL in minutes (default: ${$a})`,`${$a}`).option("--refresh","Force refresh \u2014 bypass the segment output cache").option("--hide-zero","Output nothing when both today and 30-day token counts are zero").action(async o=>{let e=Number(o.ttl),t=Number.isFinite(e)&&e>=0?e:$a;if(!o.refresh){let c=Pb(t);if(c){if(o.hideZero&&c.todayTokens===0&&c.last30DaysTokens===0)return;process.stdout.write(c.formatted);return}}let s=await ke(),n=0,i=0,r=0;if(s.length>0){let c=await Jt(s);n=c.today.tokens,i=c.month.tokens,r=c.last30Days.tokens}if(o.hideZero&&n===0&&r===0){Vd({updatedAt:new Date().toISOString(),formatted:"",todayTokens:n,thisMonthTokens:i,last30DaysTokens:r});return}let a=`${ye(n)} today \xB7 ${ye(i)} month \xB7 ${ye(r)} 30d`;Vd({updatedAt:new Date().toISOString(),formatted:a,todayTokens:n,thisMonthTokens:i,last30DaysTokens:r}),process.stdout.write(a)});var Ab=Xd(),Ee=new de;Ee.name("copilot-token-tracker").description("Analyze GitHub Copilot token usage from local session files").version(Ab.version).option("--no-cache","Bypass the session file cache and re-parse everything");Ee.hook("preAction",()=>{Ee.opts().cache===!1?Ra():Ia()});Ee.hook("postAction",()=>{Ua()});Ee.addCommand(Dd);Ee.addCommand(Id);Ee.addCommand(Ud);Ee.addCommand(Fd);Ee.addCommand(Ld);Ee.addCommand(jd);Ee.addCommand(Gd);Ee.addCommand(Jd);Ee.addCommand(Yd);Ee.addCommand(Wd);Ee.parse();
|