@qiaolei81/copilot-session-viewer 0.3.7 → 0.3.9

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.
@@ -1,104 +1,129 @@
1
- var w=(u,e)=>()=>(e||u((e={exports:{}}).exports,e),e.exports);var F=w((mr,ot)=>{var fe=require("applicationinsights"),ie=require("fs"),le=require("path"),xs=require("crypto"),nt=require("os");function js(){let u=le.join(nt.homedir(),".copilot-session-viewer"),e=le.join(u,"analytics-id");try{return ie.readFileSync(e,"utf8").trim()}catch{let n=xs.randomUUID();try{ie.mkdirSync(u,{recursive:!0}),ie.writeFileSync(e,n)}catch{}return n}}function Cs(){try{let u=[le.join(__dirname,"..","package.json"),le.join(__dirname,"package.json")];for(let e of u)try{return JSON.parse(ie.readFileSync(e,"utf8")).version}catch{}}catch{}return"unknown"}var rt=process.env.DISABLE_TELEMETRY==="true",As="InstrumentationKey=39f4fbf1-d82f-42c3-b4ef-ea92a1fd82cb;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/;ApplicationId=7d4bb432-f2f5-4526-a5e6-31901e5a2db2",E=null;if(rt)E=st(),console.log("\u{1F4CA} Telemetry disabled (DISABLE_TELEMETRY=true)");else try{let u=process.env.APPLICATIONINSIGHTS_CONNECTION_STRING||As;fe.setup(u).setAutoDependencyCorrelation(!0).setAutoCollectRequests(!0).setAutoCollectPerformance(!0,!0).setAutoCollectExceptions(!0).setAutoCollectDependencies(!0).setAutoCollectConsole(!1).setUseDiskRetryCaching(!0).setSendLiveMetrics(!1).setDistributedTracingMode(fe.DistributedTracingModes.AI_AND_W3C).start(),E=fe.defaultClient;let e=Cs(),n=js();E.context.tags[E.context.keys.cloudRole]="copilot-session-viewer",E.context.tags[E.context.keys.cloudRoleInstance]=nt.hostname(),E.context.tags[E.context.keys.applicationVersion]=e,E.context.tags[E.context.keys.userId]=n,E.addTelemetryProcessor(t=>(t.data.baseData.properties=t.data.baseData.properties||{},t.data.baseData.properties.appVersion=e,!0)),console.log("\u2705 Application Insights telemetry initialized")}catch(u){console.error("\u274C Failed to initialize Application Insights:",u.message),E=st()}function st(){return{trackEvent:()=>{},trackMetric:()=>{},trackException:()=>{},trackTrace:()=>{},trackDependency:()=>{},trackRequest:()=>{},flush:u=>{u&&u()}}}function Ds(u,e={}){E&&E.trackEvent&&E.trackEvent({name:u,properties:e})}function ks(u,e,n={}){E&&E.trackMetric&&E.trackMetric({name:u,value:e,properties:n})}function Ms(u,e={}){E&&E.trackException&&E.trackException({exception:u,properties:e})}function Ns(){return new Promise(u=>{E&&E.flush?E.flush({callback:()=>u()}):u()})}ot.exports={client:E,trackEvent:Ds,trackMetric:ks,trackException:Ms,flush:Ns,isEnabled:!rt}});var z=w((fr,at)=>{at.exports={PORT:process.env.PORT||3838,NODE_ENV:process.env.NODE_ENV||"production",LOG_LEVEL:process.env.LOG_LEVEL||(process.env.NODE_ENV==="development"?"DEBUG":"INFO"),INSIGHT_TIMEOUT_MS:300*1e3,INSIGHT_CACHE_TTL_MS:1440*60*1e3,MAX_UPLOAD_SIZE:10*1024*1024,SESSION_CACHE_TTL_MS:30*1e3,RATE_LIMIT_WINDOW_MS:900*1e3,RATE_LIMIT_MAX_REQUESTS:15,REQUEST_TIMEOUT_MS:30*1e3}});var ct=w((gr,lt)=>{var ge=z(),{trackException:$s,isEnabled:it}=F(),Ps=(u,e,n)=>{u.setTimeout(ge.REQUEST_TIMEOUT_MS),n()},Os=(u,e,n)=>{e.locals.telemetryEnabled=it,e.locals.telemetryConnectionString=it?process.env.APPLICATIONINSIGHTS_CONNECTION_STRING||"InstrumentationKey=39f4fbf1-d82f-42c3-b4ef-ea92a1fd82cb;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/;ApplicationId=7d4bb432-f2f5-4526-a5e6-31901e5a2db2":null,n()},Rs=(u,e,n)=>{if(ge.NODE_ENV==="development"){let t=["http://localhost:3838","http://127.0.0.1:3838"],s=u.headers.origin;t.includes(s)&&(e.header("Access-Control-Allow-Origin",s),e.header("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),e.header("Access-Control-Allow-Headers","Content-Type"))}n()},qs=(u,e,n,t)=>{console.error("Unhandled error:",u.stack),$s(u,{url:e.url,method:e.method,statusCode:(u.status||500).toString(),userAgent:e.headers&&e.headers["user-agent"]||"unknown"});let s=u.status||500,r=ge.NODE_ENV==="development",o=r?u.message:"Internal server error";n.status(s).json({error:o,...r&&{stack:u.stack}})},Fs=(u,e)=>{e.status(404).json({error:"Not found"})};lt.exports={requestTimeout:Ps,developmentCors:Rs,errorHandler:qs,notFoundHandler:Fs,telemetryLocals:Os}});var V=w((hr,ut)=>{function Ls(u){let e=u.toJSON?u.toJSON():{};return{type:u.type,source:u.source,sourceName:e.sourceName||u.source,sourceBadgeClass:e.sourceBadgeClass||"source-unknown",summary:u.summary,model:u.selectedModel||u.model,repo:u.workspace?.repository,branch:u.workspace?.branch,cwd:u.workspace?.cwd,created:u.createdAt,updated:u.updatedAt,copilotVersion:u.copilotVersion,sessionStatus:u.sessionStatus}}function zs(u){return typeof u=="string"&&/^[a-zA-Z0-9_-]+$/.test(u)&&u.length<256}ut.exports={buildMetadata:Ls,isValidSessionId:zs}});var B=w((yr,pt)=>{var dt=require("fs").promises,Z=require("fs"),X=require("readline");async function Vs(u){try{return await dt.access(u),!0}catch{return!1}}async function Bs(u){try{let e=Z.createReadStream(u,{encoding:"utf-8"}),n=X.createInterface({input:e,crlfDelay:1/0}),t=0;for await(let s of n)s.trim()&&t++;return t}catch(e){return console.error(`Error counting lines in ${u}:`,e.message),0}}async function Us(u){try{let e=await dt.readFile(u,"utf-8"),n={};for(let t of e.split(`
2
- `)){let s=t.trim();if(!s||s.startsWith("#"))continue;let r=s.indexOf(":");if(r<=0)continue;let o=s.slice(0,r).trim(),a=s.slice(r+1).trim();o&&(n[o]=a)}return n}catch(e){return console.error(`Error parsing YAML ${u}:`,e.message),{}}}async function Ws(u,e=500){try{let n=Z.createReadStream(u,{encoding:"utf-8"}),t=X.createInterface({input:n,crlfDelay:1/0}),s="",r=null,o=null,a=null,i=null,l=!1;for await(let d of t)if(d.trim())try{let p=JSON.parse(d);if(p.timestamp){let m=new Date(p.timestamp).getTime();isNaN(m)||(r||(r=m),o=m)}if(!s&&p.type==="user.message"){let m=p.data?.message||p.data?.content||p.data?.text||"";m&&(s=m.length>e?m.substring(0,e)+"...":m)}p.type==="session.end"&&(l=!0),p.type==="session.start"&&p.data?.copilotVersion&&!a&&(a=p.data.copilotVersion),(p.type==="session.start"||p.type==="session.model_change")&&!i&&(p.data?.selectedModel?i=p.data.selectedModel:p.data?.newModel?i=p.data.newModel:p.data?.model&&(i=p.data.model))}catch{}t.close(),n.destroy();let c=r&&o&&o>r?o-r:null;return{firstUserMessage:s||"",duration:c,copilotVersion:a||null,selectedModel:i||null,hasSessionEnd:l,lastEventTime:o,firstEventTime:r}}catch(n){return console.error(`Error reading session metadata from ${u}:`,n.message),{firstUserMessage:"",duration:null,copilotVersion:null,selectedModel:null,hasSessionEnd:!1,lastEventTime:null}}}async function Hs(u,e=200){try{let n=Z.createReadStream(u,{encoding:"utf-8"}),t=X.createInterface({input:n,crlfDelay:1/0});for await(let s of t)if(s.trim())try{let r=JSON.parse(s);if(r.type==="user.message"){let o=r.data?.message||r.data?.content||r.data?.text||"";if(o)return t.close(),n.destroy(),o.length>e?o.substring(0,e)+"...":o}}catch{}return""}catch{return""}}async function Js(u){try{let e=Z.createReadStream(u,{encoding:"utf-8"}),n=X.createInterface({input:e,crlfDelay:1/0}),t=null,s=null;for await(let r of n)if(r.trim())try{let o=JSON.parse(r);if(o.timestamp){let a=new Date(o.timestamp).getTime();t||(t=a),s=a}}catch{}return t&&s&&s>=t?s-t:null}catch(e){return console.error(`Error calculating session duration for ${u}:`,e.message),null}}async function Gs(u){try{let e=Z.createReadStream(u,{encoding:"utf-8"}),n=X.createInterface({input:e,crlfDelay:1/0}),t=null,s=null;for await(let r of n)if(r.trim())try{let o=JSON.parse(r);if(o.type==="session.start"&&o.data&&(t=o.data.copilotVersion||null,s=o.data.selectedModel||null,s))return n.close(),e.destroy(),{copilotVersion:t,selectedModel:s};if(!s&&o.type==="session.model_change"&&o.data)return s=o.data.newModel||null,n.close(),e.destroy(),{copilotVersion:t,selectedModel:s}}catch{}return{copilotVersion:t,selectedModel:s}}catch(e){return console.error(`Error reading session metadata from ${u}:`,e.message),{copilotVersion:null,selectedModel:null}}}function Ks(u){return u===".DS_Store"||u.startsWith(".")}pt.exports={fileExists:Vs,countLines:Bs,parseYAML:Us,getFirstUserMessage:Hs,getSessionDuration:Js,getSessionMetadata:Gs,getSessionMetadataOptimized:Ws,shouldSkipEntry:Ks}});var ft=w((Sr,mt)=>{var he=class{constructor(){this._adapters=new Map}register(e){if(this._adapters.has(e.type))throw new Error(`Adapter already registered for type: ${e.type}`);this._adapters.set(e.type,e)}get(e){return this._adapters.get(e)||null}all(){return Array.from(this._adapters.values())}types(){return Array.from(this._adapters.keys())}get size(){return this._adapters.size}};mt.exports=he});var U=w((wr,ht)=>{var gt=require("fs"),Ys=require("readline"),ye=class{get type(){throw new Error("BaseSourceAdapter: type getter must be implemented")}get displayName(){throw new Error("BaseSourceAdapter: displayName getter must be implemented")}get badgeClass(){return`source-${this.type}`}get envVar(){}get displayMetadata(){return{name:this.displayName,badgeClass:this.badgeClass}}getDefaultDir(){throw new Error("BaseSourceAdapter: getDefaultDir() must be implemented")}async resolveDir(){return this.envVar&&process.env[this.envVar]?process.env[this.envVar]:this.getDefaultDir()}async scanEntries(e){throw new Error("BaseSourceAdapter: scanEntries() must be implemented")}async findById(e,n){throw new Error("BaseSourceAdapter: findById() must be implemented")}async resolveEventsFile(e,n){throw new Error("BaseSourceAdapter: resolveEventsFile() must be implemented")}async readJsonlEvents(e){if(!e)return[];try{await gt.promises.access(e);let n=gt.createReadStream(e,{encoding:"utf-8"}),t=Ys.createInterface({input:n,crlfDelay:1/0}),s=0,r=[];for await(let o of t){let a=o.trim();if(a)try{let i=JSON.parse(a);i._fileIndex=s,r.push(i)}catch(i){console.error(`Error parsing line ${s+1} in ${e}:`,i.message)}s++}return r}catch(n){return console.error("Error reading main events file:",n),[]}}async readEvents(e,n){return null}get hasCustomPipeline(){return!1}normalizeEvent(e){return e}matchToolCalls(e){}expandToTimelineFormat(e){return e}async mergeSubAgentEvents(e,n,t,s){}buildTimeline(e,n){return{turns:[],summary:{}}}async findSessionLocation(e,n){return null}async resolveExportPath(e,n){return null}};ht.exports=ye});var Q=w((_r,yt)=>{var Zs=require("path"),Se=class u{constructor(e,n,t={}){this.id=e,this.type=n,this.source=t.source||"copilot",this.directory=t.directory||null,this.filePath=t.filePath||null,this.workspace=t.workspace||{},this.createdAt=t.createdAt,this.updatedAt=t.updatedAt,this.summary=t.summary||(n==="file"?"Legacy session":"No summary"),this.hasEvents=t.hasEvents||!1,this.eventCount=t.eventCount||0,this.duration=t.duration||null,this.isImported=t.isImported||!1,this.hasInsight=t.hasInsight||!1,this.copilotVersion=t.copilotVersion||null,this.selectedModel=t.selectedModel||null,this.sessionStatus=t.sessionStatus||"completed"}static fromDirectory(e,n,t,s,r,o,a,i,l,c,d){let p=s?.created_at?new Date(s.created_at):s?.startTime?new Date(s.startTime):t.birthtime,m=s?.updated_at?new Date(s.updated_at):s?.endTime?new Date(s.endTime):t.mtime;return new u(n,"directory",{directory:e,workspace:s,createdAt:p,updatedAt:m,summary:s?.summary||"No summary",hasEvents:r>0,eventCount:r,duration:o,isImported:a,hasInsight:i,copilotVersion:l,selectedModel:c,sessionStatus:d})}static fromFile(e,n,t,s,r,o,a,i,l){return new u(n,"file",{filePath:e,directory:Zs.dirname(e),createdAt:t.birthtime,updatedAt:t.mtime,summary:r||"Legacy session",hasEvents:!0,eventCount:s,duration:o,isImported:!1,hasInsight:!1,copilotVersion:a,selectedModel:i,sessionStatus:l})}toJSON(){let e=this._getSourceDisplayMetadata(this.source);return{id:this.id,type:this.type,source:this.source,sourceName:e.name,sourceBadgeClass:e.badgeClass,directory:this.directory,workspace:this.workspace,createdAt:this.createdAt,updatedAt:this.updatedAt,summary:this.summary,hasEvents:this.hasEvents,eventCount:this.eventCount,duration:this.duration,isImported:this.isImported,hasInsight:this.hasInsight,copilotVersion:this.copilotVersion,selectedModel:this.selectedModel,sessionStatus:this.sessionStatus}}_getSourceDisplayMetadata(e){try{let{registry:t}=ce(),s=t.get(e);if(s)return s.displayMetadata}catch{}return{copilot:{name:"Copilot CLI",badgeClass:"source-copilot"},claude:{name:"Claude",badgeClass:"source-claude"},"pi-mono":{name:"Pi",badgeClass:"source-pi-mono"},vscode:{name:"Copilot Chat",badgeClass:"source-vscode"}}[e]||{name:e,badgeClass:"source-unknown"}}};yt.exports=Se});var we=w((Ir,St)=>{var Xs=require("fs"),Qs=require("readline");function en(u){return new Promise((e,n)=>{let t=Xs.createReadStream(u,{encoding:"utf-8"}),s=Qs.createInterface({input:t,crlfDelay:1/0}),r=!1;s.on("line",o=>{r||(r=!0,s.close(),e(o.trim()))}),s.on("close",()=>{r||e(null)}),s.on("error",o=>{r||(r=!0,n(o))}),t.on("error",o=>{r||(r=!0,s.close(),n(o))})})}function tn(u){return u.hasSessionEnd?"completed":u.lastEventTime!==null&&u.lastEventTime!==void 0&&Date.now()-u.lastEventTime<3e5?"wip":"completed"}St.exports={readFirstLine:en,computeSessionStatus:tn}});var bt=w((Tr,Et)=>{var M=require("path"),sn=require("os"),ee=require("fs").promises,nn=U(),wt=Q(),{fileExists:te,countLines:_t,parseYAML:rn,getSessionMetadataOptimized:It,shouldSkipEntry:on}=B(),{computeSessionStatus:Tt}=we(),_e=class extends nn{get type(){return"copilot"}get displayName(){return"Copilot CLI"}get envVar(){return"COPILOT_SESSION_DIR"}getDefaultDir(){return process.env.SESSION_DIR||M.join(sn.homedir(),".copilot","session-state")}async scanEntries(e){let t=(await ee.readdir(e)).filter(r=>!on(r)).map(async r=>{let o=M.join(e,r),a=await ee.stat(o);return a.isDirectory()?this._createDirectorySession(r,o,a):r.endsWith(".jsonl")?this._createFileSession(r,o,a):null});return(await Promise.allSettled(t)).filter(r=>r.status==="fulfilled"&&r.value!==null&&r.value!==void 0).map(r=>r.value)}async findById(e,n){try{let t=M.join(n,e),s=await ee.stat(t);if(s.isDirectory())return await this._createDirectorySession(e,t,s)}catch{}try{let t=M.join(n,`${e}.jsonl`),s=await ee.stat(t);if(s.isFile())return await this._createFileSession(`${e}.jsonl`,t,s)}catch{}return null}async resolveEventsFile(e,n){let t=e.id,s=M.join(n,t);try{return(await ee.stat(s)).isDirectory()?M.join(s,"events.jsonl"):M.join(n,`${t}.jsonl`)}catch{return M.join(n,`${t}.jsonl`)}}async readEvents(e,n){let t=await this.resolveEventsFile(e,n);return this.readJsonlEvents(t)}async _createDirectorySession(e,n,t){let s=M.join(n,"workspace.yaml"),r=M.join(n,"events.jsonl"),o=M.join(n,".imported"),a=M.join(n,`${e}.agent-review.md`),i=await te(s)?await rn(s):{summary:e,repo:"unknown"},l=await te(r)?await _t(r):0,c=await te(o),d=await te(a),p=null,m=null,g=null,f="completed";if(await te(r)){let S=await It(r);if(p=S.duration,m=S.copilotVersion,g=S.selectedModel,f=Tt(S),!i.summary&&S.firstUserMessage&&(i.summary=S.firstUserMessage),S.lastEventTime){let T=new Date(S.lastEventTime).getTime(),v=new Date(t.mtime).getTime();T>v&&(t={...t,mtime:new Date(T)})}}let y=wt.fromDirectory(n,e,t,i,l,p,c,d,m,g,f);return y.source="copilot",y}async _createFileSession(e,n,t){let s=e.replace(".jsonl",""),r=await _t(n),o=await It(n),a=Tt(o),i=wt.fromFile(n,s,t,r,o.firstUserMessage,o.duration,o.copilotVersion,o.selectedModel,a);return i.source="copilot",i}};Et.exports=_e});var W=w((Er,vt)=>{var Ie=class{canParse(e){throw new Error("canParse() must be implemented")}parse(e){throw new Error("parse() must be implemented")}getMetadata(e){throw new Error("getMetadata() must be implemented")}extractTurns(e){throw new Error("extractTurns() must be implemented")}extractToolCalls(e){throw new Error("extractToolCalls() must be implemented")}};vt.exports=Ie});var Ee=w((br,xt)=>{var an=W(),Te=class extends an{canParse(e){if(!e||e.length===0)return!1;let n=["session.start","user.message","assistant.turn_start","assistant.message","tool.execution_start"];return e.some(t=>t.type&&n.some(s=>t.type.startsWith(s)))}parse(e){return{metadata:this.getMetadata(e),turns:this.extractTurns(e),toolCalls:this.extractToolCalls(e),allEvents:e}}getMetadata(e){let n=e.find(s=>s.type==="session.start");if(!n)return null;let t=n.data||{};return{sessionId:t.sessionId,startTime:t.startTime,model:t.selectedModel,version:t.copilotVersion,producer:t.producer,cwd:t.context?.cwd,gitRoot:t.context?.gitRoot,branch:t.context?.branch,repository:t.context?.repository}}extractTurns(e){let n=[],t=null;for(let s of e)if(s.type==="user.message")t&&n.push(t),t={turnId:s.id,userMessage:{id:s.id,content:s.data?.content||"",transformedContent:s.data?.transformedContent,timestamp:s.timestamp},assistantMessages:[],toolCalls:[]};else if(s.type==="assistant.message"&&t)t.assistantMessages.push({id:s.id,messageId:s.data?.messageId,content:s.data?.content||"",toolRequests:s.data?.toolRequests||[],reasoningText:s.data?.reasoningText,timestamp:s.timestamp});else if(s.type.startsWith("tool.execution_")&&t){let r=s.data?.toolCallId,o=t.toolCalls.find(a=>a.toolCallId===r);o||(o={toolCallId:r,events:[]},t.toolCalls.push(o)),o.events.push(s),s.type==="tool.execution_start"?(o.name=s.data?.toolName,o.arguments=s.data?.arguments):s.type==="tool.execution_complete"&&(o.result=s.data?.result,o.exitCode=s.data?.exitCode)}return t&&n.push(t),n}extractToolCalls(e){let n=[],t=new Map;for(let s of e)if(s.type==="tool.execution_start"){let r=s.data?.toolCallId;t.set(r,{toolCallId:r,name:s.data?.toolName,arguments:s.data?.arguments,startEvent:s,completeEvent:null})}else if(s.type==="tool.execution_complete"){let r=s.data?.toolCallId,o=t.get(r);o&&(o.completeEvent=s,o.result=s.data?.result,o.exitCode=s.data?.exitCode,n.push(o))}return n}};xt.exports=Te});var ve=w((vr,jt)=>{var ln=W(),be=class extends ln{canParse(e){return!e||e.length===0?!1:e.some(n=>n.type&&["user","assistant"].includes(n.type)&&n.uuid&&Object.prototype.hasOwnProperty.call(n,"parentUuid")&&n.sessionId)}parse(e){return{metadata:this.getMetadata(e),turns:this.extractTurns(e),toolCalls:this.extractToolCalls(e),allEvents:e}}getMetadata(e){let n=e.find(r=>r.type==="user");if(!n)return null;let s=e.find(r=>r.type==="assistant"&&r.message?.model)?.message?.model||"unknown";return{sessionId:n.sessionId,startTime:n.timestamp,model:s,version:n.version,producer:"claude-code",cwd:n.cwd,gitRoot:null,branch:n.gitBranch,repository:null}}extractTurns(e){let n=[],t=e.filter(o=>["user","assistant"].includes(o.type)&&o.type!=="file-history-snapshot"&&o.type!=="queue-operation"),s=new Map;for(let o of t)s.set(o.uuid,o);let r=t.filter(o=>o.type==="user"&&(!o.parentUuid||!s.has(o.parentUuid)));for(let o of r){let a={turnId:o.uuid,userMessage:{id:o.uuid,content:this._extractMessageContent(o.message),timestamp:o.timestamp},assistantMessages:[],toolCalls:[]};this._collectAssistantResponses(o.uuid,s,a),n.push(a)}return n}_collectAssistantResponses(e,n,t){for(let[s,r]of n.entries())if(r.parentUuid===e&&r.type==="assistant"){let o={id:r.uuid,messageId:r.message?.id,content:this._extractMessageContent(r.message),model:r.message?.model,timestamp:r.timestamp},a=this._extractToolUse(r.message);a.length>0&&(o.toolRequests=a,t.toolCalls.push(...a.map(i=>({toolCallId:i.id,name:i.name,arguments:i.input,parentUuid:r.uuid})))),t.assistantMessages.push(o),this._collectAssistantResponses(r.uuid,n,t)}}_extractMessageContent(e){return!e||!e.content?"":typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.filter(n=>n.type==="text").map(n=>n.text).join(`
3
- `):""}_extractToolUse(e){return!e||!e.content||!Array.isArray(e.content)?[]:e.content.filter(n=>n.type==="tool_use").map(n=>({id:n.id,name:n.name,input:n.input}))}extractToolCalls(e){let n=[];for(let t of e)if(t.type==="assistant"&&t.message?.content){let s=this._extractToolUse(t.message);for(let r of s)n.push({toolCallId:r.id,name:r.name,arguments:r.input,parentUuid:t.uuid,timestamp:t.timestamp,result:null,exitCode:null})}return n}};jt.exports=be});var je=w((xr,Ct)=>{var cn=W(),xe=class extends cn{constructor(){super("pi-mono")}async parseSessionDir(e){let n=require("fs").promises,t=require("path");try{let r=(await n.readdir(e)).filter(d=>d.endsWith(".jsonl"));if(r.length===0)return null;r.sort().reverse();let o=t.join(e,r[0]),a=await this._readFirstLine(o);if(!a)return null;let i=JSON.parse(a);if(i.type!=="session")return console.warn(`Pi-Mono file ${o} doesn't start with session event`),null;let c=t.basename(e).replace(/^--/,"").replace(/--$/,"");return{id:i.id,type:"pi-mono",source:"pi-mono",cwd:i.cwd||c,createdAt:new Date(i.timestamp),updatedAt:new Date(i.timestamp),summary:`Pi-Mono: ${c}`,fileCount:r.length}}catch(s){return console.error(`Error parsing Pi-Mono session dir ${e}:`,s.message),null}}async _readFirstLine(e){let n=require("fs"),t=require("readline");return new Promise(s=>{let r=n.createReadStream(e,{encoding:"utf-8"}),o=t.createInterface({input:r,crlfDelay:1/0});o.on("line",a=>{o.close(),r.destroy(),s(a.trim())}),o.on("close",()=>s(null))})}async parseEvents(e){let n=require("fs"),t=require("readline"),s=[],r=n.createReadStream(e,{encoding:"utf-8"}),o=t.createInterface({input:r,crlfDelay:1/0}),a=0;for await(let i of o){a++;let l=i.trim();if(l)try{let c=JSON.parse(l);s.push(c)}catch(c){console.error(`Error parsing Pi-Mono line ${a}:`,c.message)}}return s}};Ct.exports=xe});var Dt=w((jr,At)=>{var un=W(),Ce=class extends un{canParse(e){if(!Array.isArray(e)||e.length===0)return!1;let n=e[0];return!!(n&&typeof n=="object"&&n.kind===0&&n.v&&n.v.sessionId)}parseVsCode(e){let n=this._getMetadata(e),t=this._toEvents(e);return{metadata:n,turns:this._extractTurns(t),toolCalls:this._extractToolCalls(t),allEvents:t}}parseJsonl(e){let n=this.replayMutations(e),t=this._getMetadata(n),s=this._toEvents(n);return{metadata:t,turns:this._extractTurns(s),toolCalls:this._extractToolCalls(s),allEvents:s}}replayMutations(e){let n=null;for(let t of e){if(!t||typeof t!="object")continue;let{kind:s,k:r,v:o,i:a}=t;switch(s){case 0:n=o;break;case 1:r&&Array.isArray(r)&&this._applySet(n,r,o);break;case 2:r&&Array.isArray(r)&&this._applyPush(n,r,o,a);break;case 3:r&&Array.isArray(r)&&this._applyDelete(n,r);break;default:console.warn(`[VsCodeParser] Unknown mutation kind: ${s}`)}}return n}_applySet(e,n,t){if(!e||n.length===0)return;let s=e;for(let o=0;o<n.length-1;o++){let a=n[o];s[a]||(s[a]=typeof n[o+1]=="number"?[]:{}),s=s[a]}let r=n[n.length-1];s[r]=t}_applyPush(e,n,t,s){if(!e||n.length===0)return;let r=e;for(let i=0;i<n.length-1;i++){let l=n[i];r[l]||(r[l]=typeof n[i+1]=="number"?[]:{}),r=r[l]}let o=n[n.length-1];r[o]||(r[o]=[]);let a=r[o];if(!Array.isArray(a)){console.warn(`[VsCodeParser] Push target is not an array: ${n.join(".")}`);return}s!=null&&(a.length=s),t&&Array.isArray(t)&&t.length>0&&a.push(...t)}_applyDelete(e,n){if(!e||n.length===0)return;let t=e;for(let r=0;r<n.length-1;r++){let o=n[r];if(!t[o])return;t=t[o]}let s=n[n.length-1];delete t[s]}parse(e){return Array.isArray(e)&&e.length>0&&this.canParse(e)?this.parseJsonl(e):null}getMetadata(e){let n=this.parse(e);return n?n.metadata:null}extractTurns(e){let n=this.parse(e);return n?n.turns:[]}extractToolCalls(e){let n=this.parse(e);return n?n.toolCalls:[]}_getMetadata(e){let n=e.requests||[],t=n[0]||{},s=n[n.length-1]||{},r=t.agent?.name||t.agent?.id||"vscode-copilot";return{sessionId:e.sessionId,startTime:e.creationDate?new Date(e.creationDate).toISOString():t.timestamp?new Date(t.timestamp).toISOString():null,endTime:e.lastMessageDate?new Date(e.lastMessageDate).toISOString():s.timestamp?new Date(s.timestamp).toISOString():null,model:t.modelId||null,producer:"vscode-copilot-chat",version:t.agent?.extensionVersion||null,agentName:r,requestCount:n.length}}_toEvents(e){let n=[],t=e.requests||[];n.push({type:"session.start",id:`${e.sessionId}-start`,timestamp:e.creationDate?new Date(e.creationDate).toISOString():null,data:{sessionId:e.sessionId,producer:"vscode-copilot-chat",selectedModel:t[0]?.modelId||null}});for(let s of t){let r=s.timestamp?new Date(s.timestamp).toISOString():null,o=s.modelState?.completedAt?new Date(s.modelState.completedAt).toISOString():r,a=Array.isArray(s.response)?s.response:[],i=this._buildSubAgentNameMap(a),l=this._extractUserText(s.message);n.push({type:"user.message",id:s.requestId,timestamp:r,data:{message:l,content:l}}),n.push({type:"assistant.turn_start",id:`${s.requestId}-turn`,timestamp:r,parentId:s.requestId,data:{}});let c="",d=0,p=null,m=()=>{let g=c.trim().replace(/^`{3,}$/gm,"").trim();if(c="",!g)return;let f=p,y=f?i[f]||f.slice(0,8):null;n.push({type:"assistant.message",id:`${s.requestId}-text-${d}`,timestamp:o,parentId:s.requestId,data:{message:g,content:g,tools:[],subAgentId:f||null,subAgentName:y,parentToolCallId:null}})};for(let g of a)switch(d++,g.kind){case"thinking":{let f=g.content?.value||g.content||"";f&&(c+=f+`
4
- `);break}case"markdownContent":{let f=g.content?.value||g.content||"";f&&(c+=f+`
5
- `);break}case void 0:case null:{let f=g.value||"";f&&(c+=f);break}case"inlineReference":{let f=g.name||"";f&&(c+="`"+f+"`");break}case"toolInvocationSerialized":{m();let f=g.toolId==="runSubagent"?g.toolCallId:g.subAgentInvocationId;g.toolId==="runSubagent"&&(p=f),f&&(p=f);let y=this._normalizeTool(g);if(y){let S=f?i[f]||f.slice(0,8):null;n.push({type:"tool.invocation",id:y.id||`${s.requestId}-tool-${d}`,timestamp:o,parentId:s.requestId,data:{tool:y,subAgentId:f||null,subAgentName:S,parentToolCallId:f||null,badgeLabel:y.name,badgeClass:y.status==="error"?"badge-error":"badge-tool"}})}break}case"textEditGroup":{m();let f=g.edits||g.uri?[g]:[];n.push({type:"tool.invocation",id:`${s.requestId}-edit-${d}`,timestamp:o,parentId:s.requestId,data:{tool:{type:"tool_use",id:`${s.requestId}-edit-${d}`,name:"textEdit",startTime:r,endTime:r,status:"completed",input:{uri:g.uri,edits:f},result:"file edit",error:null},badgeLabel:"textEdit",badgeClass:"badge-tool"}});break}case"prepareToolInvocation":case"undoStop":case"codeblockUri":case"mcpServersStarting":break;default:break}m()}return n}_buildSubAgentNameMap(e){let n={};for(let t of e){if(!t||typeof t!="object"||t.kind!=="toolInvocationSerialized"||t.toolId!=="runSubagent")continue;let s=t.toolCallId;if(!s||n[s])continue;let r=t.toolSpecificData?.agentName;if(r){n[s]=r;continue}let o=t.invocationMessage,a=typeof o=="string"?o:o&&typeof o=="object"&&o.value||"";if(a){n[s]=a;continue}let i=a.match(/agents\/([^/\]]+?)\.agent\.md/);if(i){n[s]=i[1];continue}let l=t.resultDetails,c=Array.isArray(l)?l:l?[l]:[];for(let d of c){if(typeof d!="object")continue;if(i=(d.fsPath||d.path||"").match(/agents\/([^/]+?)\.agent\.md/),i){n[s]=i[1];break}}}return n}_extractUserText(e){return e?typeof e.text=="string"?e.text:Array.isArray(e.parts)?e.parts.filter(n=>n.kind==="text").map(n=>n.text||"").join(""):"":""}_normalizeTool(e){if(!e.toolCallId)return null;let n=e.toolSpecificData||{},t=n.input||n.parameters||n.request||{},s=n.output||n.result||null,r=e.isConfirmed===!1;if(!s&&(e.generatedTitle||e.resultDetails))if(e.resultDetails){let l=(Array.isArray(e.resultDetails)?e.resultDetails:[e.resultDetails]).map(c=>c.fsPath||c.path||c.external||JSON.stringify(c)).filter(Boolean);s=l.length>0?l.join(`
6
- `):e.generatedTitle||null}else s=e.generatedTitle||null;if(Object.keys(t).length===0&&e.invocationMessage){let i=e.invocationMessage,l=typeof i=="string"?i:i&&typeof i=="object"&&i.value||"";l&&(t={description:l})}let o=i=>{if(!i||typeof i!="object")return i;let l=i.fsPath||i.path||i.external||"";return l?l.replace(/.*\//,""):JSON.stringify(i)},a=i=>{if(!i||typeof i!="object")return i;let l={};for(let[c,d]of Object.entries(i))if(!(c==="$mid"||c==="external"||c==="scheme")){if(c==="fsPath"||c==="path"){l.file=d.replace(/.*\//,"");continue}d&&typeof d=="object"&&("fsPath"in d||"$mid"in d)?l[c]=o(d):Array.isArray(d)&&c==="edits"?l.edits=`${d.length} edit(s)`:l[c]=d}return l};return t&&typeof t=="object"&&!t.description&&(t=a(t)),{type:"tool_use",id:e.toolCallId,name:e.toolId||"unknown",startTime:null,endTime:null,status:r?"error":e.isComplete?"completed":"pending",input:t,result:typeof s=="string"?s:JSON.stringify(s),error:r?e.resultDetails||"Tool invocation not confirmed":null}}_extractTurns(e){let n=[],t=null;for(let s of e)s.type==="user.message"?(t&&n.push(t),t={userMessage:s,assistantMessages:[],toolCalls:[]}):t&&(s.type==="assistant.message"?t.assistantMessages.push(s):s.type==="tool.invocation"&&t.toolCalls.push(s.data?.tool));return t&&n.push(t),n}_extractToolCalls(e){return e.filter(n=>n.type==="tool.invocation"&&n.data?.tool).map(n=>n.data.tool)}};At.exports=Ce});var Mt=w((Cr,kt)=>{var Ae=Ee(),De=ve(),ke=je(),Me=class{constructor(){this.parsers=[new Ae,new De,new ke],this.parserMap={copilot:new Ae,claude:new De,"pi-mono":new ke}}getParser(e){if(typeof e=="string")return this.parserMap[e]||null;let n=e;for(let t of this.parsers)if(t.canParse(n))return t;return null}parse(e){let n=this.getParser(e);return n?n.parse(e):null}getParserType(e){let n=this.getParser(e);return n?n instanceof Ae?"copilot":n instanceof De?"claude":n instanceof ke?"pi-mono":"unknown":null}};kt.exports=Me});var Ne=w((Ar,Nt)=>{var dn=W(),pn=Ee(),mn=ve(),fn=je(),gn=Dt(),hn=Mt();Nt.exports={BaseSessionParser:dn,CopilotSessionParser:pn,ClaudeSessionParser:mn,PiMonoParser:fn,VsCodeParser:gn,ParserFactory:hn}});var qt=w((Dr,Rt)=>{var D=require("path"),yn=require("os"),A=require("fs").promises,Sn=U(),$t=Q(),{countLines:Pt,shouldSkipEntry:Ot}=B(),{ParserFactory:wn}=Ne(),$e=class extends Sn{constructor(){super(),this.parserFactory=new wn}get type(){return"claude"}get displayName(){return"Claude"}get envVar(){return"CLAUDE_SESSION_DIR"}getDefaultDir(){return D.join(yn.homedir(),".claude","projects")}async scanEntries(e){let t=(await A.readdir(e)).filter(r=>!Ot(r)).map(async r=>{let o=D.join(e,r);return(await A.stat(o)).isDirectory()?this._scanProjectDir(o,r):null});return(await Promise.allSettled(t)).filter(r=>r.status==="fulfilled"&&r.value!==null&&r.value!==void 0).map(r=>r.value).flat()}async findById(e,n){try{let t=await A.readdir(n);for(let s of t){let r=D.join(n,s),o=D.join(r,`${e}.jsonl`);try{let i=await A.stat(o);if(i.isFile()){let l=await this._createClaudeSession(`${e}.jsonl`,o,i,s);if(l)return l}}catch{}let a=D.join(r,e);try{let i=await A.stat(a);if(i.isDirectory()){let l=D.join(a,"subagents");try{if((await A.stat(l)).isDirectory())return await this._createSubagentsSession(e,a,i,s)}catch{}}}catch{}}}catch{}return null}async resolveEventsFile(e,n){if(e.type==="directory")return null;try{let t=await A.readdir(n);for(let s of t){let r=D.join(n,s,`${e.id}.jsonl`);try{return await A.access(r),r}catch{}}}catch(t){console.error("Error searching Claude projects:",t)}return null}async readEvents(e,n){let t=await this.resolveEventsFile(e,n);return this.readJsonlEvents(t)}async _scanProjectDir(e,n){try{let t=await A.readdir(e),s=[];for(let r of t){if(Ot(r))continue;let o=D.join(e,r),a=await A.stat(o);if(a.isFile()&&r.endsWith(".jsonl")){let i=await this._createClaudeSession(r,o,a,n);i&&s.push(i)}if(a.isDirectory()){let i=D.join(o,"subagents");try{if((await A.stat(i)).isDirectory()){let c=await this._createSubagentsSession(r,o,a,n);c&&s.push(c)}}catch{}}}return s}catch(t){return console.error(`Error scanning Claude project dir ${e}:`,t.message),[]}}async _createClaudeSession(e,n,t,s){let r=e.replace(".jsonl",""),o=await Pt(n);try{let l=(await A.readFile(n,"utf-8")).trim().split(`
7
- `).filter(y=>y.trim()).map(y=>{try{return JSON.parse(y)}catch{return null}}).filter(y=>y!==null),c=l.some(y=>y.type==="assistant"||y.type==="user"),d=l.some(y=>y.type==="assistant.message"||y.type==="user.message");if(!c&&d||!c||this.parserFactory.getParserType(l)!=="claude")return null;let m=this.parserFactory.parse(l),g=m.metadata||{},f=s.replace(/^-/,"/").replace(/-/g,"/");return new $t(r,"file",{source:"claude",filePath:n,directory:D.dirname(n),workspace:{summary:g.model?`Claude Code session (${g.model})`:"Claude Code session",cwd:g.cwd||f},createdAt:g.startTime||t.birthtime,updatedAt:t.mtime,summary:m.turns[0]?.userMessage?.content?.substring(0,100)||"No summary",hasEvents:o>0,eventCount:o,duration:null,isImported:!1,hasInsight:!1,copilotVersion:g.version,selectedModel:g.model,sessionStatus:"completed"})}catch(a){return console.error(`Error creating Claude session ${r}:`,a.message),null}}async _createSubagentsSession(e,n,t,s){try{let r=D.join(n,"subagents"),a=(await A.readdir(r)).filter(f=>f.startsWith("agent-")&&f.endsWith(".jsonl"));if(a.length===0)return null;let i=0;for(let f of a){let y=D.join(r,f);i+=await Pt(y)}let l=D.join(r,a[0]),d=(await A.readFile(l,"utf-8")).trim().split(`
8
- `).filter(f=>f.trim()),p=d.length>0?JSON.parse(d[0]):null,m={cwd:p?.cwd||s,version:p?.version,model:p?.message?.model,startTime:p?.timestamp},g=s.replace(/^-/,"/").replace(/-/g,"/");return new $t(e,"directory",{source:"claude",directory:n,workspace:{summary:`Claude session (${a.length} sub-agents)`,cwd:m.cwd||g},createdAt:m.startTime||t.birthtime,updatedAt:t.mtime,summary:p?.message?.content?.substring(0,100)||"Sub-agent tasks",hasEvents:i>0,eventCount:i,duration:null,isImported:!1,hasInsight:!1,copilotVersion:m.version,selectedModel:m.model,sessionStatus:"completed"})}catch(r){return console.error(`Error creating Claude subagents session ${e}:`,r.message),null}}};Rt.exports=$e});var Bt=w((kr,Vt)=>{var N=require("path"),_n=require("os"),O=require("fs").promises,In=U(),Ft=Q(),{countLines:Lt,shouldSkipEntry:Tn}=B(),{readFirstLine:zt}=we(),Pe=class extends In{get type(){return"pi-mono"}get displayName(){return"Pi"}get envVar(){return"PI_MONO_SESSION_DIR"}getDefaultDir(){return N.join(_n.homedir(),".pi","agent","sessions")}async scanEntries(e){let t=(await O.readdir(e)).filter(r=>!Tn(r)).map(async r=>{let o=N.join(e,r);return(await O.stat(o)).isDirectory()?this._scanProjectDir(o,r):null});return(await Promise.allSettled(t)).filter(r=>r.status==="fulfilled"&&r.value!==null&&r.value!==void 0).map(r=>r.value).flat()}async findById(e,n){try{let t=await O.readdir(n);for(let s of t){let r=N.join(n,s);try{let a=(await O.readdir(r)).find(i=>i.includes(`_${e}.jsonl`));if(a){let i=N.join(r,a),l=await O.stat(i);return await this._createSession(a,i,l,s)}}catch{}}}catch(t){console.error("Error searching Pi-Mono sessions:",t)}return null}async _createSession(e,n,t,s){let r=e.match(/_([a-f0-9-]+)\.jsonl$/);if(!r)return null;let o=r[1],a=await zt(n);if(!a)return null;try{let i=JSON.parse(a);if(i.type!=="session")return null;let l=await Lt(n),c=s.replace(/^--/,"").replace(/--$/,"");return new Ft(o,"directory",{source:"pi-mono",directory:N.dirname(n),workspace:{cwd:i.cwd||c},createdAt:new Date(i.timestamp),updatedAt:new Date(t.mtime),summary:`Pi-Mono: ${N.basename(i.cwd||c)}`,hasEvents:l>0,eventCount:l,duration:null,sessionStatus:"completed"})}catch(i){return console.error(`[PI-MONO] Error parsing session ${e}:`,i.message),null}}async resolveEventsFile(e,n){try{let t=await O.readdir(n);for(let s of t){let r=N.join(n,s);try{let a=(await O.readdir(r)).find(i=>i.includes(`_${e.id}.jsonl`));if(a)return N.join(r,a)}catch{}}}catch(t){console.error("Error searching Pi-Mono sessions:",t)}return null}async readEvents(e,n){let t=await this.resolveEventsFile(e,n);return this.readJsonlEvents(t)}async _scanProjectDir(e,n){try{let s=(await O.readdir(e)).filter(o=>o.endsWith(".jsonl"));if(s.length===0)return[];let r=[];s.sort().reverse();for(let o of s){let a=N.join(e,o),i=await O.stat(a),l=o.match(/_([a-f0-9-]+)\.jsonl$/);if(!l)continue;let c=l[1],d=await zt(a);if(d)try{let p=JSON.parse(d);if(p.type!=="session")continue;let m=await Lt(a),g=n.replace(/^--/,"").replace(/--$/,""),f=new Ft(c,"directory",{source:"pi-mono",directory:e,workspace:{cwd:p.cwd||g},createdAt:new Date(p.timestamp),updatedAt:new Date(i.mtime),summary:`Pi-Mono: ${N.basename(p.cwd||g)}`,hasEvents:m>0,eventCount:m,duration:null,sessionStatus:"completed"});r.push(f)}catch(p){console.error(`[PI-MONO] Error parsing session ${o}:`,p.message)}}return r}catch(t){return console.error(`[PI-MONO] Error scanning dir ${e}:`,t.message),[]}}};Vt.exports=Pe});var Jt=w((Mr,Ht)=>{var b=require("path"),se=require("os"),k=require("fs").promises,{fileURLToPath:Ut}=require("url"),En=U(),bn=Q(),{shouldSkipEntry:Wt}=B(),{VsCodeParser:vn}=Ne();function xn(){let u;switch(se.platform()){case"win32":u=b.join(process.env.APPDATA||b.join(se.homedir(),"AppData","Roaming"));break;case"darwin":u=b.join(se.homedir(),"Library","Application Support");break;case"linux":u=b.join(se.homedir(),".config");break;default:u=b.join(se.homedir(),".config")}return[b.join(u,"Code","User","workspaceStorage"),b.join(u,"Code - Insiders","User","workspaceStorage")]}var Oe=class extends En{constructor(){super(),this._candidates=null,this._parser=new vn}get type(){return"vscode"}get displayName(){return"Copilot Chat"}get envVar(){return"VSCODE_WORKSPACE_STORAGE_DIR"}get hasCustomPipeline(){return!0}getDefaultDir(){return this._getCandidates()[0]}_getCandidates(){return this._candidates||(this._candidates=xn()),this._candidates}async resolveDir(){if(this.envVar&&process.env[this.envVar])return process.env[this.envVar];let e=this._getCandidates();for(let n of e)try{return await k.access(n),n}catch{}return null}async scanEntries(e){let t=(await k.readdir(e)).filter(r=>!Wt(r)).map(async r=>{let o=b.join(e,r);return(await k.stat(o)).isDirectory()?this._scanWorkspaceDir(o):null});return(await Promise.allSettled(t)).filter(r=>r.status==="fulfilled"&&r.value!==null&&r.value!==void 0).map(r=>r.value).flat()}async findById(e,n){try{let t=await k.readdir(n),s=[];for(let r of t){let o=b.join(n,r,"chatSessions");try{let i=(await k.readdir(o)).find(l=>l===`${e}.json`||l===`${e}.jsonl`||l.replace(/\.jsonl?$/,"")===e);if(i){let l=b.join(o,i),c=await k.stat(l),d=await this._parseSessionFile(l);if(!d)continue;let{sessionJson:p}=d,m=p.requests||[];if(m.length===0)continue;let g=await this._resolveWorkspacePath(b.join(n,r)),f={...c,filePath:l};s.push(this._buildSession(e,m,p,f,r,g||b.join(n,r)))}}catch{}}if(s.length>0)return s.sort((r,o)=>(o.updatedAt?.getTime?.()??0)-(r.updatedAt?.getTime?.()??0)),s[0]}catch(t){console.error(`[VSCode findById] Error searching VSCode sessions: ${t.message}`)}return null}async readEvents(e,n){if(!e?.filePath)return[];try{let t=await this._parseSessionFile(e.filePath);if(!t)return[];let s=this._expandVsCodeEvents(t.parsed.allEvents);return s=await this._applyFileMtimeFallback(s,e.filePath),this._expandVsCodeToTimelineFormat(s)}catch(t){return console.error(`[VSCode readEvents] Error reading session ${e.id}:`,t),[]}}buildTimeline(e,n){let t=[],s=0,r=new Set;for(let a=0;a<e.length;a++){let i=e[a];if(i.type!=="user.message")continue;s++;let l={id:`turn-${s}`,type:"user-request",message:i.data?.message||"",startTime:i.timestamp,endTime:i.timestamp,assistantTurns:[],subagents:[]},c=new Set,d=0,p=a+1;for(;p<e.length&&e[p].type!=="user.message";){let m=e[p];if(m.type==="assistant.message"){d++,l.endTime=m.timestamp||l.endTime;let g={id:`assistant-${d}`,startTime:m.timestamp,endTime:m.timestamp,tools:[]};if(Array.isArray(m.data?.tools))for(let y of m.data.tools)g.tools.push({name:y.name,startTime:y.startTime||m.timestamp,endTime:y.endTime||m.timestamp,status:y.status||"completed",input:y.input,result:y.result});let f=m.data?.subAgentId;f&&!c.has(f)&&(c.add(f),r.add(f),l.subagents.push({id:f,name:m.data?.subAgentName||f,startTime:m.timestamp,endTime:m.timestamp})),l.assistantTurns.push(g)}p++}t.push(l)}let o=t.reduce((a,i)=>a+i.assistantTurns.reduce((l,c)=>l+c.tools.length,0),0);return{turns:t,summary:{totalTurns:t.length,totalAssistantTurns:t.reduce((a,i)=>a+i.assistantTurns.length,0),totalTools:o,totalSubagents:r.size,startTime:e[0]?.timestamp,endTime:e[e.length-1]?.timestamp}}}async _scanWorkspaceDir(e){let n=b.join(e,"chatSessions");try{await k.access(n)}catch{return[]}let t=b.basename(e),s=await this._resolveWorkspacePath(e),o=(await k.readdir(n)).filter(i=>(i.endsWith(".json")||i.endsWith(".jsonl"))&&!Wt(i));if(o.length===0)return[];let a=[];for(let i of o){let l=b.join(n,i);try{let c=await k.stat(l),d=await this._parseSessionFile(l);if(!d)continue;let{sessionJson:p}=d,m=p.sessionId||b.basename(i).replace(/\.jsonl?$/,""),g=p.requests||[];if(g.length===0)continue;let f={...c,filePath:l},y=this._buildSession(m,g,p,f,t,s||e);a.push(y)}catch(c){console.warn(`[VSCode scan] Skipping malformed session file ${l}: ${c.message}`)}}return a}async _parseSessionFile(e){let n=await k.readFile(e,"utf-8");return this._parseSessionContent(n,e)}_parseSessionContent(e,n="unknown"){let t=e.trim();if(!t)return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&!Array.isArray(o))return{sessionJson:o,parsed:this._parser.parseVsCode(o)}}catch{}let s=t.split(`
9
- `).filter(o=>o.trim()),r=[];for(let o=0;o<s.length;o++)try{r.push(JSON.parse(s[o]))}catch(a){return console.warn(`[VSCode parse] Failed to parse ${n} line ${o+1}: ${a.message}`),null}return r.length===0?null:this._parser.canParse(r)?{sessionJson:this._parser.replayMutations(r),parsed:this._parser.parseJsonl(r)}:r.length===1&&r[0]&&typeof r[0]=="object"?{sessionJson:r[0],parsed:this._parser.parseVsCode(r[0])}:(console.warn(`[VSCode parse] Unsupported session format in ${n}`),null)}_parseJsonl(e,n="unknown"){return this._parseSessionContent(e,n)?.sessionJson||null}async _applyFileMtimeFallback(e,n){if(!e.length)return e;try{let t=await k.stat(n),s=new Date(t.mtime).toISOString(),r=e[e.length-1];if(!r?.timestamp)return e;let o=new Date(r.timestamp).getTime();(new Date(s).getTime()-o)/1e3>10&&(r.timestamp=s)}catch(t){console.error("[VSCode] Error getting file mtime:",t)}return e}async _resolveWorkspacePath(e){try{let n=b.join(e,"workspace.json"),t=await k.readFile(n,"utf-8"),s=JSON.parse(t);if(s.folder)return Ut(s.folder);if(s.workspace){let r=Ut(s.workspace);try{let o=await k.readFile(r,"utf-8"),a=JSON.parse(o);if(Array.isArray(a.folders)&&a.folders.length>0){let i=b.dirname(r);return b.resolve(i,a.folders[0].path)}}catch{}}}catch{}return null}_buildSession(e,n,t,s,r,o){let a=n[0],i=n[n.length-1],l=t.creationDate?new Date(t.creationDate):a.timestamp?new Date(a.timestamp):s.birthtime,c=i.timestamp?new Date(i.timestamp):null,d=t.lastMessageDate?new Date(t.lastMessageDate):c||s.mtime,m=this._extractLastTerminalTimestamp(n)||c||d,g=Date.now()-m.getTime()<900*1e3,f=this._extractUserText(a.message);return new bn(e,"file",{source:"vscode",filePath:s.filePath,directory:b.dirname(s.filePath),createdAt:l,updatedAt:m,summary:f?f.slice(0,120):`VSCode chat (${n.length} requests)`,hasEvents:!0,eventCount:n.reduce((y,S)=>y+(S.response||[]).length,0)+n.length*2+1,duration:m.getTime()-l.getTime(),sessionStatus:g?"wip":"completed",selectedModel:a.modelId||null,copilotVersion:a.agent?.extensionVersion||null,workspace:{cwd:o,workspaceHash:r}})}_expandVsCodeEvents(e){let n=[],t=[],s=null,r=null,o=0,a=null,i=null,l=()=>{t.length!==0&&(n.push({type:"assistant.message",id:`vscode-tools-${o}`,timestamp:r,parentId:s,data:{message:"",content:"",tools:t,subAgentId:a,subAgentName:i},_synthetic:!0}),t=[],a=null,i=null)};for(let c=0;c<e.length;c++){let d=e[c];if(d.type==="tool.invocation"){let p=d.data?.subAgentId||null;t.length>0&&p!==a&&l(),t.length===0&&(s=d.parentId,r=d.timestamp,o=c,a=p,i=d.data?.subAgentName||null),d.data?.tool&&t.push(d.data.tool);continue}l(),n.push(d)}return l(),n}_expandVsCodeToTimelineFormat(e){let n=[];for(let t=0;t<e.length;t++){let s=e[t];n.push(s),!(s.type!=="assistant.message"||!Array.isArray(s.data?.tools)||s.data.tools.length===0)&&s.data.tools.forEach((r,o)=>{if(!r.id||!r.name)return;let a=r.startTime||s.timestamp,i=r.endTime||s.timestamp;n.push({type:"tool.execution_start",id:`${r.id}-start`,timestamp:a,parentId:s.id,data:{toolCallId:r.id,toolName:r.name,tool:r.name,arguments:r.input||{}},_synthetic:!0,_fileIndex:s._fileIndex?s._fileIndex+.1+o*.02:void 0}),n.push({type:"tool.execution_complete",id:`${r.id}-complete`,timestamp:i,parentId:r.id,data:{toolCallId:r.id,toolName:r.name,tool:r.name,result:r.result||null,error:r.error||(r.status==="error"?"Tool execution failed":null),isError:r.status==="error"},_synthetic:!0,_fileIndex:s._fileIndex?s._fileIndex+.15+o*.02:void 0})})}return n}_extractLastTerminalTimestamp(e){let n=0;function t(s){if(!(!s||typeof s!="object")){if(Array.isArray(s)){s.forEach(t);return}if(s.terminalCommandState&&typeof s.terminalCommandState.timestamp=="number"){let r=s.terminalCommandState.timestamp;r>1e12&&r<9999999999999&&r>n&&(n=r)}for(let r of Object.values(s))t(r)}}for(let s of e)t(s.response);return n>0?new Date(n):null}_extractUserText(e){return e?typeof e.text=="string"?e.text:Array.isArray(e.parts)?e.parts.filter(n=>n.kind==="text").map(n=>n.text||"").join(""):"":""}};Ht.exports=Oe});var ce=w((Nr,Kt)=>{var Gt=ft(),jn=U(),Cn=bt(),An=qt(),Dn=Bt(),kn=Jt(),ne=new Gt;ne.register(new Cn);ne.register(new An);ne.register(new Dn);ne.register(new kn);Kt.exports={registry:ne,AdapterRegistry:Gt,BaseSourceAdapter:jn}});var qe=w(($r,Yt)=>{var Mn=require("fs").promises,{shouldSkipEntry:Nn}=B(),{registry:$n}=ce(),Re=class{constructor(e){if(this.registry=$n,typeof e=="string")this.sources=[{type:"copilot",dir:e}];else if(Array.isArray(e))this.sources=e;else{this.sources=this.registry.all().map(n=>({type:n.type,dir:n.getDefaultDir()}));for(let n of this.sources){let t=this.registry.get(n.type);t&&t.envVar&&process.env[t.envVar]&&(n.dir=process.env[t.envVar]),n.type==="copilot"&&process.env.SESSION_DIR&&!process.env.COPILOT_SESSION_DIR&&(n.dir=process.env.SESSION_DIR)}}this._cache=new Map,this._cacheTTL=60*1e3,this._pendingScans=new Map}invalidateCache(e=null){e?(this._cache.delete(e),this._cache.delete(null)):this._cache.clear()}async findAll(e=null){let n=e||"__all__",t=this._cache.get(n);if(t&&Date.now()-t.timestamp<this._cacheTTL)return t.data;if(this._pendingScans.has(n))return this._pendingScans.get(n);let s=this._doFindAll(e).then(r=>(this._cache.set(n,{data:r,timestamp:Date.now()}),this._pendingScans.delete(n),r)).catch(r=>{throw this._pendingScans.delete(n),r});return this._pendingScans.set(n,s),s}async _doFindAll(e=null){let n=[],t=e?this.sources.filter(s=>s.type===e):this.sources;for(let s of t)try{let r=await this._scanSource(s);n.push(...r)}catch(r){console.error(`Error reading ${s.type} sessions from ${s.dir}:`,r.message)}return this._sortByUpdatedAt(this._deduplicateSessions(n))}async _scanSource(e){let n=this.registry.get(e.type);if(!n)return console.warn(`No adapter registered for source type: ${e.type}`),[];let t;if(e.dir?t=e.dir:t=await n.resolveDir(),!t)return console.warn(`No directory resolved for ${e.type}`),[];try{await Mn.access(t)}catch{return console.warn(`Source directory not found: ${t}`),[]}return n.scanEntries(t)}_deduplicateSessions(e){let n=new Map;for(let t of e){let s=n.get(t.id);(!s||t.updatedAt&&s.updatedAt&&new Date(t.updatedAt)>new Date(s.updatedAt))&&n.set(t.id,t)}return Array.from(n.values())}async findById(e){if(Nn(e))return null;for(let n of this.sources){let t=this.registry.get(n.type);if(!t)continue;let s;if(n.dir?s=n.dir:s=await t.resolveDir(),!s)continue;let r=await t.findById(e,s);if(r)return r}return null}_sortByUpdatedAt(e){return e.sort((n,t)=>new Date(t.createdAt)-new Date(n.createdAt))}};Yt.exports=Re});var Xt=w((Pr,Zt)=>{var Fe=class{normalizeEvents(e,n){return Array.isArray(e)?e.filter(t=>!t._isToolResultWrapper).map(t=>this.normalizeEvent(t,n)):(console.warn("[EventNormalizer] normalizeEvents: events is not an array",typeof e),[])}normalizeEvent(e,n){return!e||typeof e!="object"?(console.warn("[EventNormalizer] normalizeEvent: invalid event",e),e):this._isAssistantMessage(e)?this._normalizeAssistantMessage(e,n):this._isTimelineEvent(e)?this._normalizeTimelineEvent(e,n):e}_isAssistantMessage(e){return e.data?.tools&&Array.isArray(e.data.tools)&&e.data.tools.length>0?!0:e.type==="assistant.message"||e.type==="assistant"||e.type==="user.message"||e.type==="user"}_isTimelineEvent(e){return e.type?.startsWith("tool.")||e.type?.startsWith("subagent.")}_normalizeAssistantMessage(e,n){let t={...e};return e.data?.tools&&Array.isArray(e.data.tools)&&(t.data={...e.data,tools:e.data.tools.filter(s=>s.type!=="tool_result").map(s=>this._normalizeToolCall(s,n,e.timestamp))}),t}_normalizeToolCall(e,n,t){if(e.type==="tool_use"){let s=this._computeStatus(e),r=e._startTime||t,o=e._matched?e._endTime||t:null;return{type:"tool_use",id:e.id,name:e.name,startTime:r,endTime:o,status:s,input:e.input||{},result:e.result||null,error:e.error||null,metadata:{source:n,matched:e._matched,duration:this._computeDuration(r,o)}}}if(e.name&&e.status){let s=t,r=e.status==="success"?"completed":e.status,o=r==="completed"||r==="error"?t:null;return{id:e.id||this._generateToolId(),name:e.name,startTime:s,endTime:o,status:r,input:e.input||{},result:e.isError?null:e.result||null,error:e.isError?e.result:null,metadata:{source:n,duration:this._computeDuration(s,o)}}}return console.warn("[EventNormalizer] Unknown tool format, applying fallback normalization",e),{id:e.id||this._generateToolId(),name:e.name||"unknown",startTime:t,endTime:null,status:"running",input:e.input||{},result:null,error:null,metadata:{source:n,fallback:!0}}}_computeStatus(e){return e.error?"error":e.result!==void 0&&e.result!==null&&e.result!==""?"completed":e._matched===!1?"running":e._matched?"completed":"running"}_computeDuration(e,n){if(!(!e||!n))try{let t=new Date(e),s=new Date(n);if(isNaN(t.getTime())||isNaN(s.getTime()))return;let r=s.getTime()-t.getTime();return r>=0?r:void 0}catch{return}}_generateToolId(){return`tool-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}_normalizeTimelineEvent(e){return e.type==="tool.execution_start"||e.type==="tool.execution_complete"?{...e,data:{...e.data,toolCallId:e.data?.toolCallId||e.data?.id,toolName:e.data?.toolName||e.data?.tool||e.data?.name,...e.data}}:(e.type?.startsWith("subagent."),e)}};Zt.exports=Fe});var ze=w((Or,ts)=>{var re=require("fs"),H=require("path"),Pn=require("readline"),{isValidSessionId:Qt,buildMetadata:On}=V(),es=qe(),Rn=Xt(),Le=class{constructor(e){e?(this.SESSION_DIR=e,this.sessionRepository=new es(e)):this.sessionRepository=new es,this.eventNormalizer=new Rn}async getAllSessions(e=null){return(await this.sessionRepository.findAll(e)).map(t=>t.toJSON())}async getPaginatedSessions(e=1,n=20,t=null){let r=(await this.sessionRepository.findAll(t)).map(l=>l.toJSON()),o=(e-1)*n,a=o+n;return{sessions:r.slice(o,a),totalSessions:r.length,currentPage:e,totalPages:Math.ceil(r.length/n),hasNextPage:a<r.length,hasPrevPage:e>1}}async getSessionById(e){return Qt(e)?(await this.getAllSessions()).find(t=>t.id===e):null}async getSessionEvents(e,n=null){if(!Qt(e))return n?{events:[],total:0}:[];let t=await this.sessionRepository.findById(e);if(!t)return n?{events:[],total:0}:[];let s=this._getSourceAdapter(t.source),o=this.sessionRepository.sources.find(l=>l.type===t.source)?.dir||null;!o&&s&&(o=await s.resolveDir()),this.SESSION_DIR&&t.source==="copilot"&&(o=this.SESSION_DIR);let a=s&&!s.hasCustomPipeline?await s.resolveEventsFile(t,o):null,i=[];if(s?i=await s.readEvents(t,o)||[]:console.warn(`SessionService.getSessionEvents: No adapter found for source '${t.source}'. Returning no events.`),i.length>0&&(t.source==="claude"&&t.type==="directory"?i=i.filter(c=>c._subagent):i=i.filter(c=>!c._subagent)),i.sort((l,c)=>{let d=l.timestamp?new Date(l.timestamp).getTime():0,p=c.timestamp?new Date(c.timestamp).getTime():0;return d!==p?d-p:(l._fileIndex??0)-(c._fileIndex??0)}),i=i.map(l=>this._normalizeEvent(l,t.source)),s&&!s.hasCustomPipeline&&await this._mergeSubAgentEvents(i,a,e,t.source),s&&!s.hasCustomPipeline&&t.source==="copilot"?(this._matchCopilotToolCalls(i),this._mergeHookEvents(i),i=this._expandCopilotToTimelineFormat(i)):s&&!s.hasCustomPipeline&&t.source==="claude"?(this._matchClaudeToolResults(i),i=this._expandClaudeToTimelineFormat(i)):s&&!s.hasCustomPipeline&&t.source==="pi-mono"&&this._mergePiMonoToolResults(i),i=i.filter(l=>l.timestamp||l.snapshot?.timestamp?!0:(console.warn("[SessionService] Filtered event without timestamp:",l.type,l.id||l._fileIndex),!1)),i.forEach(l=>{l._fileIndex===999999&&l.timestamp&&delete l._fileIndex}),i=this.eventNormalizer.normalizeEvents(i,t.source),n&&typeof n.limit=="number"&&typeof n.offset=="number"){let l=i.length;return{events:i.slice(n.offset,n.offset+n.limit),total:l}}return i}async _mergeSubAgentEvents(e,n,t,s){let r;if(s==="claude"){let o=this.sessionRepository.sources.find(a=>a.type==="claude");if(!o)return;try{let a=await re.promises.readdir(o.dir);for(let i of a){let l=H.join(o.dir,i,t,"subagents");try{if((await re.promises.stat(l)).isDirectory()){r=l;break}}catch{}}}catch(a){console.error("Error searching Claude subagents:",a);return}}else if(s==="copilot"&&n){let o=H.dirname(n);H.basename(n)==="events.jsonl"?r=H.join(o,"subagents"):r=H.join(o,t,"subagents")}if(r){try{if(!(await re.promises.stat(r)).isDirectory())return}catch{return}try{let a=(await re.promises.readdir(r)).filter(i=>i.startsWith("agent-")&&i.endsWith(".jsonl"));if(a.length===0)return;for(let i of a){let l=i.replace(".jsonl",""),c=H.join(r,i);try{let d=re.createReadStream(c,{encoding:"utf-8"}),p=Pn.createInterface({input:d,crlfDelay:1/0}),m=[];for await(let x of p){let P=x.trim();P&&m.push(P)}if(m.length===0)continue;let g=l.replace("agent-",""),f=g.toUpperCase(),y=`Sub-agent ${l}`;try{let x=JSON.parse(m[0]);if(x.agentId&&(g=x.agentId,f=`agent-${x.agentId}`),x.message?.content){let P=typeof x.message.content=="string"?x.message.content:JSON.stringify(x.message.content);y=P.length>100?P.slice(0,100)+"...":P}}catch{}let S=m.map((x,P)=>{try{let Y=JSON.parse(x);return Y._fileIndex=1e6+P,Y._subagent={id:l,name:g},Y}catch(Y){return console.error(`Error parsing sub-agent ${l} line ${P+1}:`,Y.message),null}}).filter(x=>x!==null);if(S.length===0)continue;let T=S.map(x=>this._normalizeEvent(x,s)),v=T[0],j=T[T.length-1],L=v.timestamp||new Date().toISOString(),pe=j.timestamp||new Date().toISOString(),me={type:"subagent.started",id:`${l}-start`,timestamp:L,_fileIndex:v._fileIndex-1,_subagent:{id:l,name:g},data:{toolCallId:l,agentName:g,agentDisplayName:f,agentDescription:y}},tt={type:"subagent.completed",id:`${l}-end`,timestamp:pe,_fileIndex:j._fileIndex+1,_subagent:{id:l,name:g},data:{toolCallId:l,result:`Sub-agent ${f} completed`}};e.push(me,...T,tt)}catch(d){console.error(`Error reading sub-agent ${l}:`,d)}}e.sort((i,l)=>{let c=i.timestamp?new Date(i.timestamp).getTime():0,d=l.timestamp?new Date(l.timestamp).getTime():0;return c!==d?c-d:i._fileIndex-l._fileIndex})}catch(o){console.error("Error processing sub-agents:",o)}}}_matchClaudeToolResults(e){let n=new Map;e.forEach(t=>{t.data?.tools&&t.data.tools.forEach(s=>{s.type==="tool_result"&&(s.tool_use_id?n.set(s.tool_use_id,s):console.warn("[sessionService] tool_result missing tool_use_id:",s))})}),e.forEach(t=>{t.type==="user"&&Array.isArray(t.message?.content)&&t.message.content.length>0&&t.message.content.every(r=>r?.type==="tool_result")&&(t._isToolResultWrapper=!0)}),e.forEach(t=>{t.data?.tools&&(t.data.tools=t.data.tools.map(s=>{if(s.type==="tool_use"){let r=n.get(s.id);return r?{...s,result:r.content,_matched:!0}:{...s,_matched:!1}}return s}),t.type==="assistant"||t.type==="assistant.message"?t.data.tools=t.data.tools.filter(s=>s.type!=="tool_result"):(t.type==="user"||t.type==="user.message")&&t.data.tools.length>0&&t.data.tools.every(r=>r.type==="tool_result")&&(t._isToolResultWrapper=!0))})}_mergePiMonoToolResults(e){let n=new Set;e.forEach(s=>{if(s.type==="assistant.message"&&s.data.tools&&s.data.tools.length>0){let r=s.data.tools,o=[],a=s.id,i=!0;for(;i&&o.length<r.length;){i=!1;for(let l of e)if(l.type==="message"&&l.data.role==="toolResult"&&l.parentId===a&&!o.includes(l)){o.push(l),a=l.id,i=!0;break}}o.forEach((l,c)=>{if(c<r.length){let d=r[c];d.result=l.data.result,d.resultId=l.id,d.status="completed",n.add(l.id)}})}});let t=e.length;for(let s=e.length-1;s>=0;s--)e[s].type==="message"&&e[s].data.role==="toolResult"&&n.has(e[s].id)&&e.splice(s,1);n.size>0&&console.log(`[PI-MONO] Merged ${n.size} toolResult events into assistant messages (${t} \u2192 ${e.length} events)`)}_matchPiMonoToolResults_OLD(e){let n=new Set;e.forEach(s=>{if(s.type==="assistant.message"&&s.data.tools&&s.data.tools.length>0){let r=s.data.tools,o=[],a=s.id,i=!0;for(;i&&o.length<r.length;){i=!1;for(let l of e)if(l.type==="tool.result"&&l.parentId===a&&!o.includes(l)){o.push(l),a=l.id,i=!0;break}}o.forEach((l,c)=>{if(c<r.length){let d=r[c];d.status="completed",d._matched=!0,d.result=l.data.result,d.resultId=l.id,n.add(l.id)}})}});let t=e.length;for(let s=e.length-1;s>=0;s--)e[s].type==="tool.result"&&n.has(e[s].id)&&e.splice(s,1);n.size>0&&console.log(`[PI-MONO] Removed ${n.size} matched tool.result events (${t} \u2192 ${e.length} events)`)}_mergeHookEvents(e){let n=new Map;for(let t=0;t<e.length;t++){let s=e[t],r=s.data?.hookInvocationId;if(r){if(s.type==="hook.start")n.set(r,t);else if(s.type==="hook.end"){let o=n.get(r);if(o!==void 0){let a=e[o],i=s.data?.success!==!1;if(a.data.hookSuccess=i,a.data.hookError=s.data?.error||null,a.timestamp&&s.timestamp){let l=new Date(s.timestamp)-new Date(a.timestamp);a.data.hookDurationMs=l;let c=l<1e3?`${l}ms`:`${(l/1e3).toFixed(2)}s`;a.data.message&&(a.data.message+=`
10
- **Duration:** ${c}`)}a.data.badgeLabel=i?"\u2713 HOOK":"\u2717 HOOK",a.data.badgeClass=i?"badge-tool":"badge-error",n.delete(r)}s._remove=!0}}}for(let t=e.length-1;t>=0;t--)e[t]._remove&&e.splice(t,1)}_matchCopilotToolCalls(e){let n=new Map;e.forEach(t=>{if(t.type==="tool.execution_start"){let s=t.data?.toolCallId;s&&n.set(s,{name:t.data.toolName,input:t.data.arguments||{},start:t})}else if(t.type==="tool.execution_complete"){let s=t.data?.toolCallId;if(s)if(n.has(s)){let r=n.get(s);r.complete=t,r.result=t.data?.result,r.status=t.data?.error?"error":"completed",r.error=t.data?.error}else console.warn(`[sessionService] Orphaned tool.execution_complete for toolCallId=${s}`),n.set(s,{name:t.data.toolName||"unknown",input:{},start:null,complete:t,result:t.data?.result,status:t.data?.error?"error":"completed",error:t.data?.error})}}),e.forEach(t=>{if(t.type==="assistant.message"&&t.data?.toolRequests){let s=[];t.data.toolRequests.forEach(r=>{let o=r.toolCallId;if(n.has(o)){let a=n.get(o);s.push({type:"tool_use",id:o,name:r.name||a.name,input:r.arguments||a.input,result:a.result,status:a.status||"running",error:a.error,_matched:!!a.complete,_startTime:a.start?.timestamp,_endTime:a.complete?.timestamp})}else s.push({type:"tool_use",id:o,name:r.name,input:r.arguments||{},status:"running",_matched:!1})}),s.length>0&&(t.data.tools=s)}})}_generateBadgeInfo(e){let n=e.type,t=e.data||{};if(n==="message"&&t.role==="toolResult"){e.data.badgeLabel="TOOL RESULT",e.data.badgeClass="badge-tool";return}if(n==="session.model_change"||n==="model.change"){e.data.badgeLabel="MODEL CHANGE",e.data.badgeClass="badge-session";return}if(n==="session.truncation"){e.data.badgeLabel="TRUNCATION",e.data.badgeClass="badge-truncation";return}if(n==="session.compaction_start"||n==="session.compaction_complete"||n==="compaction"){e.data.badgeLabel="COMPACTION",e.data.badgeClass="badge-compaction";return}if(n==="thinking.change"){e.data.badgeLabel="THINKING",e.data.badgeClass="badge-session";return}if(n==="system.notification"){e.data.badgeLabel="SYSTEM",e.data.badgeClass="badge-system";return}let r=(n||"").split(".")[0]||"unknown",a={user:{label:"USER",class:"badge-user"},assistant:{label:"ASSISTANT",class:"badge-assistant"},reasoning:{label:"REASONING",class:"badge-reasoning"},turn:{label:"TURN",class:"badge-turn"},tool:{label:"TOOL",class:"badge-tool"},subagent:{label:"SUBAGENT",class:"badge-subagent"},skill:{label:"SKILL",class:"badge-skill"},session:{label:"SESSION",class:"badge-session"},error:{label:"ERROR",class:"badge-error"},abort:{label:"ABORT",class:"badge-error"}}[r]||{label:r.toUpperCase(),class:"badge-info"};e.data.badgeLabel=a.label,e.data.badgeClass=a.class}_normalizeEvent(e,n){let t={...e};if(t.data=t.data||{},n==="copilot"){if(e.type==="user.message"&&e.data?.source==="system"){t.type="system.notification";let s=e.data.content||e.data.message||"",r=s.match(/<system_notification>([\s\S]*?)<\/system_notification>/);return t.data.message=r?r[1].trim():s.trim(),this._generateBadgeInfo(t),t}if(e.type==="request"){if(t.type="user",e.payload?.messages&&Array.isArray(e.payload.messages)){let s=e.payload.messages.find(r=>r.role==="user");s&&(t.message={role:"user",content:s.content||""})}}else if(e.type==="response"&&(t.type="assistant",e.payload?.content&&Array.isArray(e.payload.content))){let s=e.payload.content.filter(r=>r.type==="text");s.length>0&&(t.message={role:"assistant",content:s.map(r=>r.text).join(`
1
+ var y=(d,e)=>()=>(e||d((e={exports:{}}).exports,e),e.exports);var L=y((jr,lt)=>{var fe=require("applicationinsights"),ie=require("fs"),ce=require("path"),Rs=require("crypto"),it=require("os");function qs(){let d=ce.join(it.homedir(),".copilot-session-viewer"),e=ce.join(d,"analytics-id");try{return ie.readFileSync(e,"utf8").trim()}catch{let s=Rs.randomUUID();try{ie.mkdirSync(d,{recursive:!0}),ie.writeFileSync(e,s)}catch{}return s}}function Fs(){try{let d=[ce.join(__dirname,"..","package.json"),ce.join(__dirname,"package.json")];for(let e of d)try{return JSON.parse(ie.readFileSync(e,"utf8")).version}catch{}}catch{}return"unknown"}var ct=process.env.DISABLE_TELEMETRY==="true",Us="InstrumentationKey=39f4fbf1-d82f-42c3-b4ef-ea92a1fd82cb;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/;ApplicationId=7d4bb432-f2f5-4526-a5e6-31901e5a2db2",_=null;if(ct)_=ot(),console.log("\u{1F4CA} Telemetry disabled (DISABLE_TELEMETRY=true)");else try{let d=process.env.APPLICATIONINSIGHTS_CONNECTION_STRING||Us;fe.setup(d).setAutoDependencyCorrelation(!0).setAutoCollectRequests(!0).setAutoCollectPerformance(!0,!0).setAutoCollectExceptions(!0).setAutoCollectDependencies(!0).setAutoCollectConsole(!1).setUseDiskRetryCaching(!0).setSendLiveMetrics(!1).setDistributedTracingMode(fe.DistributedTracingModes.AI_AND_W3C).start(),_=fe.defaultClient;let e=Fs(),s=qs();_.context.tags[_.context.keys.cloudRole]="copilot-session-viewer",_.context.tags[_.context.keys.cloudRoleInstance]=it.hostname(),_.context.tags[_.context.keys.applicationVersion]=e,_.context.tags[_.context.keys.userId]=s,_.addTelemetryProcessor(t=>(t.data.baseData.properties=t.data.baseData.properties||{},t.data.baseData.properties.appVersion=e,!0)),console.log("\u2705 Application Insights telemetry initialized")}catch(d){console.error("\u274C Failed to initialize Application Insights:",d.message),_=ot()}function ot(){return{trackEvent:()=>{},trackMetric:()=>{},trackException:()=>{},trackTrace:()=>{},trackDependency:()=>{},trackRequest:()=>{},flush:d=>{d&&d()}}}function Ls(d,e={}){_&&_.trackEvent&&_.trackEvent({name:d,properties:e})}function zs(d,e,s={}){_&&_.trackMetric&&_.trackMetric({name:d,value:e,properties:s})}function Vs(d,e={}){_&&_.trackException&&_.trackException({exception:d,properties:e})}function Bs(){return new Promise(d=>{_&&_.flush?_.flush({callback:()=>d()}):d()})}lt.exports={client:_,trackEvent:Ls,trackMetric:zs,trackException:Vs,flush:Bs,isEnabled:!ct}});var z=y((Ar,ut)=>{ut.exports={PORT:process.env.PORT||3838,NODE_ENV:process.env.NODE_ENV||"production",LOG_LEVEL:process.env.LOG_LEVEL||(process.env.NODE_ENV==="development"?"DEBUG":"INFO"),INSIGHT_TIMEOUT_MS:300*1e3,INSIGHT_CACHE_TTL_MS:1440*60*1e3,MAX_UPLOAD_SIZE:10*1024*1024,SESSION_CACHE_TTL_MS:30*1e3,RATE_LIMIT_WINDOW_MS:900*1e3,RATE_LIMIT_MAX_REQUESTS:15,REQUEST_TIMEOUT_MS:30*1e3}});var mt=y((kr,pt)=>{var ge=z(),{trackException:Ws,isEnabled:dt}=L(),Hs=(d,e,s)=>{d.setTimeout(ge.REQUEST_TIMEOUT_MS),s()},Js=(d,e,s)=>{e.locals.telemetryEnabled=dt,e.locals.telemetryConnectionString=dt?process.env.APPLICATIONINSIGHTS_CONNECTION_STRING||"InstrumentationKey=39f4fbf1-d82f-42c3-b4ef-ea92a1fd82cb;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/;ApplicationId=7d4bb432-f2f5-4526-a5e6-31901e5a2db2":null,s()},Gs=(d,e,s)=>{if(ge.NODE_ENV==="development"){let t=["http://localhost:3838","http://127.0.0.1:3838"],n=d.headers.origin;t.includes(n)&&(e.header("Access-Control-Allow-Origin",n),e.header("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),e.header("Access-Control-Allow-Headers","Content-Type"))}s()},Ks=(d,e,s,t)=>{console.error("Unhandled error:",d.stack),Ws(d,{url:e.url,method:e.method,statusCode:(d.status||500).toString(),userAgent:e.headers&&e.headers["user-agent"]||"unknown"});let n=d.status||500,r=ge.NODE_ENV==="development",a=r?d.message:"Internal server error";s.status(n).json({error:a,...r&&{stack:d.stack}})},Xs=(d,e)=>{e.status(404).json({error:"Not found"})};pt.exports={requestTimeout:Hs,developmentCors:Gs,errorHandler:Ks,notFoundHandler:Xs,telemetryLocals:Js}});var q=y((Mr,ft)=>{function Ys(d){let e=d.toJSON?d.toJSON():{};return{type:d.type,source:d.source,sourceName:e.sourceName||d.source,sourceBadgeClass:e.sourceBadgeClass||"source-unknown",summary:d.summary,model:d.selectedModel||d.model,repo:d.workspace?.repository,branch:d.workspace?.branch,cwd:d.workspace?.cwd,created:d.createdAt,updated:d.updatedAt,copilotVersion:d.copilotVersion,modernizeVersion:d.modernizeVersion,agentName:d.agentName,sessionStatus:d.sessionStatus}}function Zs(d){return typeof d=="string"&&/^[a-zA-Z0-9_-]+$/.test(d)&&d.length<256}ft.exports={buildMetadata:Ys,isValidSessionId:Zs}});var V=y((Nr,gt)=>{var he=require("fs").promises,Y=require("fs"),Z=require("readline"),Qs=require("js-yaml");async function en(d){try{return await he.access(d),!0}catch{return!1}}async function tn(d){try{let e=Y.createReadStream(d,{encoding:"utf-8"}),s=Z.createInterface({input:e,crlfDelay:1/0}),t=0;for await(let n of s)n.trim()&&t++;return t}catch(e){return console.error(`Error counting lines in ${d}:`,e.message),0}}async function sn(d){try{let e=await he.readFile(d,"utf-8"),s=Qs.load(e);return s&&typeof s=="object"?s:{}}catch{try{let s=await he.readFile(d,"utf-8"),t={};for(let n of s.split(`
2
+ `)){let r=n.trim();if(!r||r.startsWith("#"))continue;let a=r.indexOf(":");if(a<=0)continue;let o=r.slice(0,a).trim(),i=r.slice(a+1).trim();o&&(t[o]=i)}return t}catch(s){return console.error(`Error parsing YAML ${d}:`,s.message),{}}}}async function nn(d,e=500){try{let s=Y.createReadStream(d,{encoding:"utf-8"}),t=Z.createInterface({input:s,crlfDelay:1/0}),n="",r=null,a=null,o=null,i=null,c=!1,l=0;for await(let p of t)if(p.trim())try{let m=JSON.parse(p);if(l++,m.timestamp){let f=new Date(m.timestamp).getTime();isNaN(f)||(r||(r=f),a=f)}if(!n&&(m.type==="user.message"||m.type==="request")){let f=m.data?.message||m.data?.content||m.data?.text||"";if(!f&&m.type==="request"&&Array.isArray(m.payload?.messages)){let g=m.payload.messages.find(h=>h.role==="user");g&&(f=typeof g.content=="string"?g.content:"")}f&&(n=f.length>e?f.substring(0,e)+"...":f)}m.type==="session.end"&&(c=!0),m.type==="session.start"&&m.data?.copilotVersion&&!o&&(o=m.data.copilotVersion),(m.type==="session.start"||m.type==="session.model_change")&&!i&&(m.data?.selectedModel?i=m.data.selectedModel:m.data?.newModel?i=m.data.newModel:m.data?.model&&(i=m.data.model))}catch{}t.close(),s.destroy();let u=r&&a&&a>r?a-r:null;return{firstUserMessage:n||"",duration:u,eventCount:l,copilotVersion:o||null,selectedModel:i||null,hasSessionEnd:c,lastEventTime:a,firstEventTime:r}}catch(s){return console.error(`Error reading session metadata from ${d}:`,s.message),{firstUserMessage:"",duration:null,eventCount:0,copilotVersion:null,selectedModel:null,hasSessionEnd:!1,lastEventTime:null}}}async function rn(d,e=200){try{let s=Y.createReadStream(d,{encoding:"utf-8"}),t=Z.createInterface({input:s,crlfDelay:1/0});for await(let n of t)if(n.trim())try{let r=JSON.parse(n);if(r.type==="user.message"){let a=r.data?.message||r.data?.content||r.data?.text||"";if(a)return t.close(),s.destroy(),a.length>e?a.substring(0,e)+"...":a}}catch{}return""}catch{return""}}async function an(d){try{let e=Y.createReadStream(d,{encoding:"utf-8"}),s=Z.createInterface({input:e,crlfDelay:1/0}),t=null,n=null;for await(let r of s)if(r.trim())try{let a=JSON.parse(r);if(a.timestamp){let o=new Date(a.timestamp).getTime();t||(t=o),n=o}}catch{}return t&&n&&n>=t?n-t:null}catch(e){return console.error(`Error calculating session duration for ${d}:`,e.message),null}}async function on(d){try{let e=Y.createReadStream(d,{encoding:"utf-8"}),s=Z.createInterface({input:e,crlfDelay:1/0}),t=null,n=null;for await(let r of s)if(r.trim())try{let a=JSON.parse(r);if(a.type==="session.start"&&a.data&&(t=a.data.copilotVersion||null,n=a.data.selectedModel||null,n))return s.close(),e.destroy(),{copilotVersion:t,selectedModel:n};if(!n&&a.type==="session.model_change"&&a.data)return n=a.data.newModel||null,s.close(),e.destroy(),{copilotVersion:t,selectedModel:n}}catch{}return{copilotVersion:t,selectedModel:n}}catch(e){return console.error(`Error reading session metadata from ${d}:`,e.message),{copilotVersion:null,selectedModel:null}}}function cn(d){return d===".DS_Store"||d.startsWith(".")}gt.exports={fileExists:en,countLines:tn,parseYAML:sn,getFirstUserMessage:rn,getSessionDuration:an,getSessionMetadata:on,getSessionMetadataOptimized:nn,shouldSkipEntry:cn}});var yt=y(($r,ht)=>{var ye=class{constructor(){this._adapters=new Map}register(e){if(this._adapters.has(e.type))throw new Error(`Adapter already registered for type: ${e.type}`);this._adapters.set(e.type,e)}get(e){return this._adapters.get(e)||null}all(){return Array.from(this._adapters.values())}types(){return Array.from(this._adapters.keys())}get size(){return this._adapters.size}async detectImportCandidates(e){return(await Promise.all(this.all().map(async t=>{try{let n=await t.detectImportCandidate(e);return{source:t.type,matched:!1,score:0,...n}}catch(n){return{source:t.type,matched:!1,score:0,reason:`Detection error: ${n.message}`}}}))).sort((t,n)=>(n.score||0)-(t.score||0))}};ht.exports=ye});var B=y((Or,wt)=>{var St=require("fs"),ln=require("readline"),Se=class{get type(){throw new Error("BaseSourceAdapter: type getter must be implemented")}get displayName(){throw new Error("BaseSourceAdapter: displayName getter must be implemented")}get badgeClass(){return`source-${this.type}`}get envVar(){}get displayMetadata(){return{name:this.displayName,badgeClass:this.badgeClass}}getDefaultDir(){throw new Error("BaseSourceAdapter: getDefaultDir() must be implemented")}async resolveDir(){return this.envVar&&process.env[this.envVar]?process.env[this.envVar]:this.getDefaultDir()}async scanEntries(e){throw new Error("BaseSourceAdapter: scanEntries() must be implemented")}async findById(e,s){throw new Error("BaseSourceAdapter: findById() must be implemented")}async resolveEventsFile(e,s){throw new Error("BaseSourceAdapter: resolveEventsFile() must be implemented")}async readJsonlEvents(e){if(!e)return[];try{await St.promises.access(e);let s=St.createReadStream(e,{encoding:"utf-8"}),t=ln.createInterface({input:s,crlfDelay:1/0}),n=0,r=[];for await(let a of t){let o=a.trim();if(o)try{let i=JSON.parse(o);i._fileIndex=n,r.push(i)}catch(i){console.error(`Error parsing line ${n+1} in ${e}:`,i.message)}n++}return r}catch(s){return console.error("Error reading main events file:",s),[]}}async readEvents(e,s){return null}get hasCustomPipeline(){return!1}normalizeEvent(e){return e}matchToolCalls(e){}expandToTimelineFormat(e){return e}async mergeSubAgentEvents(e,s,t,n){}buildTimeline(e,s){return{turns:[],summary:{}}}async findSessionLocation(e,s){return null}async resolveExportPath(e,s){return null}async detectImportCandidate(e){return{matched:!1,score:0,reason:`${this.type} import detection not implemented`}}async importDetectedSession(e,s){return{success:!1,error:`Import not implemented for ${this.type}`,statusCode:400}}};wt.exports=Se});var Q=y((Pr,_t)=>{var un=require("path"),we=class d{constructor(e,s,t={}){this.id=e,this.type=s,this.source=t.source||"copilot",this.directory=t.directory||null,this.filePath=t.filePath||null,this.workspace=t.workspace||{},this.createdAt=t.createdAt,this.updatedAt=t.updatedAt,this.summary=t.summary||(s==="file"?"Legacy session":"No summary"),this.hasEvents=t.hasEvents||!1,this.eventCount=t.eventCount||0,this.duration=t.duration||null,this.isImported=t.isImported||!1,this.hasInsight=t.hasInsight||!1,this.copilotVersion=t.copilotVersion||null,this.modernizeVersion=t.modernizeVersion||null,this.selectedModel=t.selectedModel||null,this.agentName=t.agentName||null,this.sessionStatus=t.sessionStatus||"completed"}static fromDirectory(e,s,t,n,r,a,o,i,c,l,u){let p=n?.created_at?new Date(n.created_at):n?.startTime?new Date(n.startTime):t.birthtime||(t.birthtimeMs?new Date(t.birthtimeMs):void 0),m=n?.updated_at?new Date(n.updated_at):n?.endTime?new Date(n.endTime):t.mtime;return new d(s,"directory",{directory:e,workspace:n,createdAt:p,updatedAt:m,summary:n?.summary||"No summary",hasEvents:r>0,eventCount:r,duration:a,isImported:o,hasInsight:i,copilotVersion:c,selectedModel:l,sessionStatus:u})}static fromFile(e,s,t,n,r,a,o,i,c){return new d(s,"file",{filePath:e,directory:un.dirname(e),createdAt:t.birthtime||(t.birthtimeMs?new Date(t.birthtimeMs):void 0),updatedAt:t.mtime,summary:r||"Legacy session",hasEvents:!0,eventCount:n,duration:a,isImported:!1,hasInsight:!1,copilotVersion:o,selectedModel:i,sessionStatus:c})}toJSON(){let e=this._getSourceDisplayMetadata(this.source);return{id:this.id,type:this.type,source:this.source,sourceName:e.name,sourceBadgeClass:e.badgeClass,directory:this.directory,workspace:this.workspace,createdAt:this.createdAt,updatedAt:this.updatedAt,summary:this.summary,hasEvents:this.hasEvents,eventCount:this.eventCount,duration:this.duration,isImported:this.isImported,hasInsight:this.hasInsight,copilotVersion:this.copilotVersion,modernizeVersion:this.modernizeVersion,selectedModel:this.selectedModel,agentName:this.agentName,sessionStatus:this.sessionStatus}}_getSourceDisplayMetadata(e){try{let{registry:t}=ee(),n=t.get(e);if(n)return n.displayMetadata}catch{}return{copilot:{name:"Copilot CLI",badgeClass:"source-copilot"},claude:{name:"Claude",badgeClass:"source-claude"},"pi-mono":{name:"Pi",badgeClass:"source-pi-mono"},vscode:{name:"Copilot Chat",badgeClass:"source-vscode"}}[e]||{name:e,badgeClass:"source-unknown"}}};_t.exports=we});var le=y((Rr,It)=>{var dn=require("fs"),pn=require("readline");function mn(d){return new Promise((e,s)=>{let t=dn.createReadStream(d,{encoding:"utf-8"}),n=pn.createInterface({input:t,crlfDelay:1/0}),r=!1;n.on("line",a=>{r||(r=!0,n.close(),e(a.trim()))}),n.on("close",()=>{r||e(null)}),n.on("error",a=>{r||(r=!0,s(a))}),t.on("error",a=>{r||(r=!0,n.close(),s(a))})})}function fn(d){return d.hasSessionEnd?"completed":d.lastEventTime!==null&&d.lastEventTime!==void 0&&Date.now()-d.lastEventTime<3e5?"wip":"completed"}It.exports={readFirstLine:mn,computeSessionStatus:fn}});var Ie=y((qr,vt)=>{var v=require("path"),gn=require("os"),ue=require("fs"),P=ue.promises,hn=B(),Tt=Q(),{fileExists:te,countLines:Et,parseYAML:yn,getSessionMetadataOptimized:bt,shouldSkipEntry:Sn}=V(),{computeSessionStatus:Ct}=le(),_e=class extends hn{get type(){return"copilot"}get displayName(){return"Copilot CLI"}get envVar(){return"COPILOT_SESSION_DIR"}getDefaultDir(){return process.env.SESSION_DIR||v.join(gn.homedir(),".copilot","session-state")}async scanEntries(e){let t=(await P.readdir(e)).filter(r=>!Sn(r)).map(async r=>{let a=v.join(e,r),o=await P.stat(a);return o.isDirectory()?this._createDirectorySession(r,a,o):r.endsWith(".jsonl")?this._createFileSession(r,a,o):null});return(await Promise.allSettled(t)).filter(r=>r.status==="fulfilled"&&r.value!==null&&r.value!==void 0).map(r=>r.value)}async findById(e,s){try{let t=v.join(s,e),n=await P.stat(t);if(n.isDirectory())return await this._createDirectorySession(e,t,n)}catch{}try{let t=v.join(s,`${e}.jsonl`),n=await P.stat(t);if(n.isFile())return await this._createFileSession(`${e}.jsonl`,t,n)}catch{}return null}async resolveEventsFile(e,s){let t=e.id,n=v.join(s,t);try{return(await P.stat(n)).isDirectory()?v.join(n,"events.jsonl"):v.join(s,`${t}.jsonl`)}catch{return v.join(s,`${t}.jsonl`)}}async readEvents(e,s){let t=await this.resolveEventsFile(e,s);return this.readJsonlEvents(t)}async _createDirectorySession(e,s,t){let n=v.join(s,"workspace.yaml"),r=v.join(s,"events.jsonl"),a=v.join(s,".imported"),o=v.join(s,`${e}.agent-review.md`),i=await te(n)?await yn(n):{summary:e,repo:"unknown"},c=await te(r)?await Et(r):0,l=await te(a),u=await te(o),p=null,m=null,f=null,g="completed";if(await te(r)){let w=await bt(r);if(p=w.duration,m=w.copilotVersion,f=w.selectedModel,g=Ct(w),!i.summary&&w.firstUserMessage&&(i.summary=w.firstUserMessage),w.lastEventTime){let D=new Date(w.lastEventTime).getTime(),N=new Date(t.mtime).getTime();D>N&&(t={...t,mtime:new Date(D)})}}let h=Tt.fromDirectory(s,e,t,i,c,p,l,u,m,f,g);return h.source="copilot",h}async _createFileSession(e,s,t){let n=e.replace(".jsonl",""),r=await Et(s),a=await bt(s),o=Ct(a),i=Tt.fromFile(s,n,t,r,a.firstUserMessage,a.duration,a.copilotVersion,a.selectedModel,o);return i.source="copilot",i}async detectImportCandidate(e){let s=await P.readdir(e);for(let t of s){let n=v.join(e,t);if((await P.stat(n)).isDirectory()&&ue.existsSync(v.join(n,"events.jsonl")))return{matched:!0,score:100,reason:"Directory with events.jsonl",sessionId:t,directoryName:t}}return{matched:!1,score:0,reason:"No directory containing events.jsonl found"}}async importDetectedSession(e,s){let{isValidSessionId:t}=q(),{sessionId:n,directoryName:r}=e;if(!t(n))return{success:!1,error:"Invalid session ID",statusCode:400};let a=v.join(s.extractDir,r);if(!ue.existsSync(v.join(a,"events.jsonl")))return{success:!1,error:"Invalid session structure (no events.jsonl)",statusCode:400};let o=s.targetDir||await this.resolveDir(),i=v.join(o,n);return ue.existsSync(i)?{success:!1,error:"Session already exists",statusCode:409}:(await P.mkdir(o,{recursive:!0}),await P.rename(a,i),await P.writeFile(v.join(i,".imported"),""),{success:!0,sessionId:n,format:this.type})}};vt.exports=_e});var W=y((Fr,Dt)=>{var Te=class{canParse(e){throw new Error("canParse() must be implemented")}parse(e){throw new Error("parse() must be implemented")}getMetadata(e){throw new Error("getMetadata() must be implemented")}extractTurns(e){throw new Error("extractTurns() must be implemented")}extractToolCalls(e){throw new Error("extractToolCalls() must be implemented")}};Dt.exports=Te});var be=y((Ur,xt)=>{var wn=W(),Ee=class extends wn{canParse(e){if(!e||e.length===0)return!1;let s=["session.start","user.message","assistant.turn_start","assistant.message","tool.execution_start"];return e.some(t=>t.type&&s.some(n=>t.type.startsWith(n)))}parse(e){return{metadata:this.getMetadata(e),turns:this.extractTurns(e),toolCalls:this.extractToolCalls(e),allEvents:e}}getMetadata(e){let s=e.find(n=>n.type==="session.start");if(!s)return null;let t=s.data||{};return{sessionId:t.sessionId,startTime:t.startTime,model:t.selectedModel,version:t.copilotVersion,producer:t.producer,cwd:t.context?.cwd,gitRoot:t.context?.gitRoot,branch:t.context?.branch,repository:t.context?.repository}}extractTurns(e){let s=[],t=null;for(let n of e)if(n.type==="user.message")t&&s.push(t),t={turnId:n.id,userMessage:{id:n.id,content:n.data?.content||"",transformedContent:n.data?.transformedContent,timestamp:n.timestamp},assistantMessages:[],toolCalls:[]};else if(n.type==="assistant.message"&&t)t.assistantMessages.push({id:n.id,messageId:n.data?.messageId,content:n.data?.content||"",toolRequests:n.data?.toolRequests||[],reasoningText:n.data?.reasoningText,timestamp:n.timestamp});else if(n.type.startsWith("tool.execution_")&&t){let r=n.data?.toolCallId,a=t.toolCalls.find(o=>o.toolCallId===r);a||(a={toolCallId:r,events:[]},t.toolCalls.push(a)),a.events.push(n),n.type==="tool.execution_start"?(a.name=n.data?.toolName,a.arguments=n.data?.arguments):n.type==="tool.execution_complete"&&(a.result=n.data?.result,a.exitCode=n.data?.exitCode)}return t&&s.push(t),s}extractToolCalls(e){let s=[],t=new Map;for(let n of e)if(n.type==="tool.execution_start"){let r=n.data?.toolCallId;t.set(r,{toolCallId:r,name:n.data?.toolName,arguments:n.data?.arguments,startEvent:n,completeEvent:null})}else if(n.type==="tool.execution_complete"){let r=n.data?.toolCallId,a=t.get(r);a&&(a.completeEvent=n,a.result=n.data?.result,a.exitCode=n.data?.exitCode,s.push(a))}return s}};xt.exports=Ee});var ve=y((Lr,jt)=>{var _n=W(),Ce=class extends _n{canParse(e){return!e||e.length===0?!1:e.some(s=>s.type&&["user","assistant"].includes(s.type)&&s.uuid&&Object.prototype.hasOwnProperty.call(s,"parentUuid")&&s.sessionId)}parse(e){return{metadata:this.getMetadata(e),turns:this.extractTurns(e),toolCalls:this.extractToolCalls(e),allEvents:e}}getMetadata(e){let s=e.find(r=>r.type==="user");if(!s)return null;let n=e.find(r=>r.type==="assistant"&&r.message?.model)?.message?.model||"unknown";return{sessionId:s.sessionId,startTime:s.timestamp,model:n,version:s.version,producer:"claude-code",cwd:s.cwd,gitRoot:null,branch:s.gitBranch,repository:null}}extractTurns(e){let s=[],t=e.filter(a=>["user","assistant"].includes(a.type)&&a.type!=="file-history-snapshot"&&a.type!=="queue-operation"),n=new Map;for(let a of t)n.set(a.uuid,a);let r=t.filter(a=>a.type==="user"&&(!a.parentUuid||!n.has(a.parentUuid)));for(let a of r){let o={turnId:a.uuid,userMessage:{id:a.uuid,content:this._extractMessageContent(a.message),timestamp:a.timestamp},assistantMessages:[],toolCalls:[]};this._collectAssistantResponses(a.uuid,n,o),s.push(o)}return s}_collectAssistantResponses(e,s,t){for(let[n,r]of s.entries())if(r.parentUuid===e&&r.type==="assistant"){let a={id:r.uuid,messageId:r.message?.id,content:this._extractMessageContent(r.message),model:r.message?.model,timestamp:r.timestamp},o=this._extractToolUse(r.message);o.length>0&&(a.toolRequests=o,t.toolCalls.push(...o.map(i=>({toolCallId:i.id,name:i.name,arguments:i.input,parentUuid:r.uuid})))),t.assistantMessages.push(a),this._collectAssistantResponses(r.uuid,s,t)}}_extractMessageContent(e){return!e||!e.content?"":typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.filter(s=>s.type==="text").map(s=>s.text).join(`
3
+ `):""}_extractToolUse(e){return!e||!e.content||!Array.isArray(e.content)?[]:e.content.filter(s=>s.type==="tool_use").map(s=>({id:s.id,name:s.name,input:s.input}))}extractToolCalls(e){let s=[];for(let t of e)if(t.type==="assistant"&&t.message?.content){let n=this._extractToolUse(t.message);for(let r of n)s.push({toolCallId:r.id,name:r.name,arguments:r.input,parentUuid:t.uuid,timestamp:t.timestamp,result:null,exitCode:null})}return s}};jt.exports=Ce});var xe=y((zr,At)=>{var In=W(),De=class extends In{constructor(){super("pi-mono")}async parseSessionDir(e){let s=require("fs").promises,t=require("path");try{let r=(await s.readdir(e)).filter(u=>u.endsWith(".jsonl"));if(r.length===0)return null;r.sort().reverse();let a=t.join(e,r[0]),o=await this._readFirstLine(a);if(!o)return null;let i=JSON.parse(o);if(i.type!=="session")return console.warn(`Pi-Mono file ${a} doesn't start with session event`),null;let l=t.basename(e).replace(/^--/,"").replace(/--$/,"");return{id:i.id,type:"pi-mono",source:"pi-mono",cwd:i.cwd||l,createdAt:new Date(i.timestamp),updatedAt:new Date(i.timestamp),summary:`Pi-Mono: ${l}`,fileCount:r.length}}catch(n){return console.error(`Error parsing Pi-Mono session dir ${e}:`,n.message),null}}async _readFirstLine(e){let s=require("fs"),t=require("readline");return new Promise(n=>{let r=s.createReadStream(e,{encoding:"utf-8"}),a=t.createInterface({input:r,crlfDelay:1/0});a.on("line",o=>{a.close(),r.destroy(),n(o.trim())}),a.on("close",()=>n(null))})}async parseEvents(e){let s=require("fs"),t=require("readline"),n=[],r=s.createReadStream(e,{encoding:"utf-8"}),a=t.createInterface({input:r,crlfDelay:1/0}),o=0;for await(let i of a){o++;let c=i.trim();if(c)try{let l=JSON.parse(c);n.push(l)}catch(l){console.error(`Error parsing Pi-Mono line ${o}:`,l.message)}}return n}};At.exports=De});var Mt=y((Vr,kt)=>{var Tn=W(),je=class extends Tn{canParse(e){if(!Array.isArray(e)||e.length===0)return!1;let s=e[0];return!!(s&&typeof s=="object"&&s.kind===0&&s.v&&s.v.sessionId)}parseVsCode(e){let s=this._getMetadata(e),t=this._toEvents(e);return{metadata:s,turns:this._extractTurns(t),toolCalls:this._extractToolCalls(t),allEvents:t}}parseJsonl(e){let s=this.replayMutations(e),t=this._getMetadata(s),n=this._toEvents(s);return{metadata:t,turns:this._extractTurns(n),toolCalls:this._extractToolCalls(n),allEvents:n}}replayMutations(e){let s=null;for(let t of e){if(!t||typeof t!="object")continue;let{kind:n,k:r,v:a,i:o}=t;switch(n){case 0:s=a;break;case 1:r&&Array.isArray(r)&&this._applySet(s,r,a);break;case 2:r&&Array.isArray(r)&&this._applyPush(s,r,a,o);break;case 3:r&&Array.isArray(r)&&this._applyDelete(s,r);break;default:console.warn(`[VsCodeParser] Unknown mutation kind: ${n}`)}}return s}_applySet(e,s,t){if(!e||s.length===0)return;let n=e;for(let a=0;a<s.length-1;a++){let o=s[a];n[o]||(n[o]=typeof s[a+1]=="number"?[]:{}),n=n[o]}let r=s[s.length-1];n[r]=t}_applyPush(e,s,t,n){if(!e||s.length===0)return;let r=e;for(let i=0;i<s.length-1;i++){let c=s[i];r[c]||(r[c]=typeof s[i+1]=="number"?[]:{}),r=r[c]}let a=s[s.length-1];r[a]||(r[a]=[]);let o=r[a];if(!Array.isArray(o)){console.warn(`[VsCodeParser] Push target is not an array: ${s.join(".")}`);return}n!=null&&(o.length=n),t&&Array.isArray(t)&&t.length>0&&o.push(...t)}_applyDelete(e,s){if(!e||s.length===0)return;let t=e;for(let r=0;r<s.length-1;r++){let a=s[r];if(!t[a])return;t=t[a]}let n=s[s.length-1];delete t[n]}parse(e){return Array.isArray(e)&&e.length>0&&this.canParse(e)?this.parseJsonl(e):null}getMetadata(e){let s=this.parse(e);return s?s.metadata:null}extractTurns(e){let s=this.parse(e);return s?s.turns:[]}extractToolCalls(e){let s=this.parse(e);return s?s.toolCalls:[]}_getMetadata(e){let s=e.requests||[],t=s[0]||{},n=s[s.length-1]||{},r=t.agent?.name||t.agent?.id||"vscode-copilot";return{sessionId:e.sessionId,startTime:e.creationDate?new Date(e.creationDate).toISOString():t.timestamp?new Date(t.timestamp).toISOString():null,endTime:e.lastMessageDate?new Date(e.lastMessageDate).toISOString():n.timestamp?new Date(n.timestamp).toISOString():null,model:t.modelId||null,producer:"vscode-copilot-chat",version:t.agent?.extensionVersion||null,agentName:r,requestCount:s.length}}_toEvents(e){let s=[],t=e.requests||[];s.push({type:"session.start",id:`${e.sessionId}-start`,timestamp:e.creationDate?new Date(e.creationDate).toISOString():null,data:{sessionId:e.sessionId,producer:"vscode-copilot-chat",selectedModel:t[0]?.modelId||null}});for(let n of t){let r=n.timestamp?new Date(n.timestamp).toISOString():null,a=n.modelState?.completedAt?new Date(n.modelState.completedAt).toISOString():r,o=Array.isArray(n.response)?n.response:[],i=this._buildSubAgentNameMap(o),c=this._extractUserText(n.message);s.push({type:"user.message",id:n.requestId,timestamp:r,data:{message:c,content:c}}),s.push({type:"assistant.turn_start",id:`${n.requestId}-turn`,timestamp:r,parentId:n.requestId,data:{}});let l="",u=0,p=null,m=()=>{let f=l.trim().replace(/^`{3,}$/gm,"").trim();if(l="",!f)return;let g=p,h=g?i[g]||g.slice(0,8):null;s.push({type:"assistant.message",id:`${n.requestId}-text-${u}`,timestamp:a,parentId:n.requestId,data:{message:f,content:f,tools:[],subAgentId:g||null,subAgentName:h,parentToolCallId:null}})};for(let f of o)switch(u++,f.kind){case"thinking":{let g=f.content?.value||f.content||"";g&&(l+=g+`
4
+ `);break}case"markdownContent":{let g=f.content?.value||f.content||"";g&&(l+=g+`
5
+ `);break}case void 0:case null:{let g=f.value||"";g&&(l+=g);break}case"inlineReference":{let g=f.name||"";g&&(l+="`"+g+"`");break}case"toolInvocationSerialized":{m();let g=f.toolId==="runSubagent"?f.toolCallId:f.subAgentInvocationId;f.toolId==="runSubagent"&&(p=g),g&&(p=g);let h=this._normalizeTool(f);if(h){let w=g?i[g]||g.slice(0,8):null;s.push({type:"tool.invocation",id:h.id||`${n.requestId}-tool-${u}`,timestamp:a,parentId:n.requestId,data:{tool:h,subAgentId:g||null,subAgentName:w,parentToolCallId:g||null,badgeLabel:h.name,badgeClass:h.status==="error"?"badge-error":"badge-tool"}})}break}case"textEditGroup":{m();let g=f.edits||f.uri?[f]:[];s.push({type:"tool.invocation",id:`${n.requestId}-edit-${u}`,timestamp:a,parentId:n.requestId,data:{tool:{type:"tool_use",id:`${n.requestId}-edit-${u}`,name:"textEdit",startTime:r,endTime:r,status:"completed",input:{uri:f.uri,edits:g},result:"file edit",error:null},badgeLabel:"textEdit",badgeClass:"badge-tool"}});break}case"prepareToolInvocation":case"undoStop":case"codeblockUri":case"mcpServersStarting":break;default:break}m()}return s}_buildSubAgentNameMap(e){let s={};for(let t of e){if(!t||typeof t!="object"||t.kind!=="toolInvocationSerialized"||t.toolId!=="runSubagent")continue;let n=t.toolCallId;if(!n||s[n])continue;let r=t.toolSpecificData?.agentName;if(r){s[n]=r;continue}let a=t.invocationMessage,o=typeof a=="string"?a:a&&typeof a=="object"&&a.value||"";if(o){s[n]=o;continue}let i=o.match(/agents\/([^/\]]+?)\.agent\.md/);if(i){s[n]=i[1];continue}let c=t.resultDetails,l=Array.isArray(c)?c:c?[c]:[];for(let u of l){if(typeof u!="object")continue;if(i=(u.fsPath||u.path||"").match(/agents\/([^/]+?)\.agent\.md/),i){s[n]=i[1];break}}}return s}_extractUserText(e){return e?typeof e.text=="string"?e.text:Array.isArray(e.parts)?e.parts.filter(s=>s.kind==="text").map(s=>s.text||"").join(""):"":""}_normalizeTool(e){if(!e.toolCallId)return null;let s=e.toolSpecificData||{},t=s.input||s.parameters||s.request||{},n=s.output||s.result||null,r=e.isConfirmed===!1;if(!n&&(e.generatedTitle||e.resultDetails))if(e.resultDetails){let c=(Array.isArray(e.resultDetails)?e.resultDetails:[e.resultDetails]).map(l=>l.fsPath||l.path||l.external||JSON.stringify(l)).filter(Boolean);n=c.length>0?c.join(`
6
+ `):e.generatedTitle||null}else n=e.generatedTitle||null;if(Object.keys(t).length===0&&e.invocationMessage){let i=e.invocationMessage,c=typeof i=="string"?i:i&&typeof i=="object"&&i.value||"";c&&(t={description:c})}let a=i=>{if(!i||typeof i!="object")return i;let c=i.fsPath||i.path||i.external||"";return c?c.replace(/.*\//,""):JSON.stringify(i)},o=i=>{if(!i||typeof i!="object")return i;let c={};for(let[l,u]of Object.entries(i))if(!(l==="$mid"||l==="external"||l==="scheme")){if(l==="fsPath"||l==="path"){c.file=u.replace(/.*\//,"");continue}u&&typeof u=="object"&&("fsPath"in u||"$mid"in u)?c[l]=a(u):Array.isArray(u)&&l==="edits"?c.edits=`${u.length} edit(s)`:c[l]=u}return c};return t&&typeof t=="object"&&!t.description&&(t=o(t)),{type:"tool_use",id:e.toolCallId,name:e.toolId||"unknown",startTime:null,endTime:null,status:r?"error":e.isComplete?"completed":"pending",input:t,result:typeof n=="string"?n:JSON.stringify(n),error:r?e.resultDetails||"Tool invocation not confirmed":null}}_extractTurns(e){let s=[],t=null;for(let n of e)n.type==="user.message"?(t&&s.push(t),t={userMessage:n,assistantMessages:[],toolCalls:[]}):t&&(n.type==="assistant.message"?t.assistantMessages.push(n):n.type==="tool.invocation"&&t.toolCalls.push(n.data?.tool));return t&&s.push(t),s}_extractToolCalls(e){return e.filter(s=>s.type==="tool.invocation"&&s.data?.tool).map(s=>s.data.tool)}};kt.exports=je});var $t=y((Br,Nt)=>{var Ae=be(),ke=ve(),Me=xe(),Ne=class{constructor(){this.parsers=[new Ae,new ke,new Me],this.parserMap={copilot:new Ae,claude:new ke,"pi-mono":new Me}}getParser(e){if(typeof e=="string")return this.parserMap[e]||null;let s=e;for(let t of this.parsers)if(t.canParse(s))return t;return null}parse(e){let s=this.getParser(e);return s?s.parse(e):null}getParserType(e){let s=this.getParser(e);return s?s instanceof Ae?"copilot":s instanceof ke?"claude":s instanceof Me?"pi-mono":"unknown":null}};Nt.exports=Ne});var Pt=y((Wr,Ot)=>{var En=W(),bn=be(),Cn=ve(),vn=xe(),Dn=Mt(),xn=$t();Ot.exports={BaseSessionParser:En,CopilotSessionParser:bn,ClaudeSessionParser:Cn,PiMonoParser:vn,VsCodeParser:Dn,ParserFactory:xn}});var zt=y((Hr,Lt)=>{var E=require("path"),jn=require("os"),Ut=require("fs"),b=Ut.promises,An=B(),Rt=Q(),{countLines:qt,shouldSkipEntry:Ft}=V(),{ParserFactory:kn}=Pt(),$e=class extends An{constructor(){super(),this.parserFactory=new kn}get type(){return"claude"}get displayName(){return"Claude"}get envVar(){return"CLAUDE_SESSION_DIR"}getDefaultDir(){return E.join(jn.homedir(),".claude","projects")}async scanEntries(e){let t=(await b.readdir(e)).filter(r=>!Ft(r)).map(async r=>{let a=E.join(e,r);return(await b.stat(a)).isDirectory()?this._scanProjectDir(a,r):null});return(await Promise.allSettled(t)).filter(r=>r.status==="fulfilled"&&r.value!==null&&r.value!==void 0).map(r=>r.value).flat()}async findById(e,s){try{let t=await b.readdir(s);for(let n of t){let r=E.join(s,n),a=E.join(r,`${e}.jsonl`);try{let i=await b.stat(a);if(i.isFile()){let c=await this._createClaudeSession(`${e}.jsonl`,a,i,n);if(c)return c}}catch{}let o=E.join(r,e);try{let i=await b.stat(o);if(i.isDirectory()){let c=E.join(o,"subagents");try{if((await b.stat(c)).isDirectory())return await this._createSubagentsSession(e,o,i,n)}catch{}}}catch{}}}catch{}return null}async resolveEventsFile(e,s){if(e.type==="directory")return null;try{let t=await b.readdir(s);for(let n of t){let r=E.join(s,n,`${e.id}.jsonl`);try{return await b.access(r),r}catch{}}}catch(t){console.error("Error searching Claude projects:",t)}return null}async readEvents(e,s){let t=await this.resolveEventsFile(e,s);return this.readJsonlEvents(t)}async _scanProjectDir(e,s){try{let t=await b.readdir(e),n=[];for(let r of t){if(Ft(r))continue;let a=E.join(e,r),o=await b.stat(a);if(o.isFile()&&r.endsWith(".jsonl")){let i=await this._createClaudeSession(r,a,o,s);i&&n.push(i)}if(o.isDirectory()){let i=E.join(a,"subagents");try{if((await b.stat(i)).isDirectory()){let l=await this._createSubagentsSession(r,a,o,s);l&&n.push(l)}}catch{}}}return n}catch(t){return console.error(`Error scanning Claude project dir ${e}:`,t.message),[]}}async _createClaudeSession(e,s,t,n){let r=e.replace(".jsonl",""),a=await qt(s);try{let c=(await b.readFile(s,"utf-8")).trim().split(`
7
+ `).filter(h=>h.trim()).map(h=>{try{return JSON.parse(h)}catch{return null}}).filter(h=>h!==null),l=c.some(h=>h.type==="assistant"||h.type==="user"),u=c.some(h=>h.type==="assistant.message"||h.type==="user.message");if(!l&&u||!l||this.parserFactory.getParserType(c)!=="claude")return null;let m=this.parserFactory.parse(c),f=m.metadata||{},g=n.replace(/^-/,"/").replace(/-/g,"/");return new Rt(r,"file",{source:"claude",filePath:s,directory:E.dirname(s),workspace:{summary:f.model?`Claude Code session (${f.model})`:"Claude Code session",cwd:f.cwd||g},createdAt:f.startTime||t.birthtime,updatedAt:t.mtime,summary:m.turns[0]?.userMessage?.content?.substring(0,100)||"No summary",hasEvents:a>0,eventCount:a,duration:null,isImported:!1,hasInsight:!1,copilotVersion:f.version,selectedModel:f.model,sessionStatus:"completed"})}catch(o){return console.error(`Error creating Claude session ${r}:`,o.message),null}}async _createSubagentsSession(e,s,t,n){try{let r=E.join(s,"subagents"),o=(await b.readdir(r)).filter(g=>g.startsWith("agent-")&&g.endsWith(".jsonl"));if(o.length===0)return null;let i=0;for(let g of o){let h=E.join(r,g);i+=await qt(h)}let c=E.join(r,o[0]),u=(await b.readFile(c,"utf-8")).trim().split(`
8
+ `).filter(g=>g.trim()),p=u.length>0?JSON.parse(u[0]):null,m={cwd:p?.cwd||n,version:p?.version,model:p?.message?.model,startTime:p?.timestamp},f=n.replace(/^-/,"/").replace(/-/g,"/");return new Rt(e,"directory",{source:"claude",directory:s,workspace:{summary:`Claude session (${o.length} sub-agents)`,cwd:m.cwd||f},createdAt:m.startTime||t.birthtime,updatedAt:t.mtime,summary:p?.message?.content?.substring(0,100)||"Sub-agent tasks",hasEvents:i>0,eventCount:i,duration:null,isImported:!1,hasInsight:!1,copilotVersion:m.version,selectedModel:m.model,sessionStatus:"completed"})}catch(r){return console.error(`Error creating Claude subagents session ${e}:`,r.message),null}}async detectImportCandidate(e){let s=await b.readdir(e);for(let t of s){if(!t.endsWith(".jsonl"))continue;let n=E.join(e,t);if(!(await b.stat(n)).isFile())continue;let a=t.replace(/\.jsonl$/,""),o=(await b.readFile(n,"utf-8")).split(`
9
+ `).find(c=>c.trim()),i;try{i=o?JSON.parse(o):null}catch{i=null}if(i&&(i.type==="user"||i.type==="assistant"||i.parentUuid||i.uuid)){let c=Ut.existsSync(E.join(e,a));return{matched:!0,score:c?95:90,reason:c?"Claude JSONL + companion dir":"Claude JSONL file",sessionId:a,fileName:t,hasDirectory:c,directoryName:c?a:void 0}}}return{matched:!1,score:0,reason:"No Claude session JSONL signature found"}}async importDetectedSession(e,s){let{isValidSessionId:t}=q(),{sessionId:n,fileName:r,hasDirectory:a,directoryName:o}=e;if(!t(n))return{success:!1,error:"Invalid session ID",statusCode:400};let i=s.req.query.project||"imported-sessions",c=s.targetDir||await this.resolveDir(),l=E.join(c,i);return await b.mkdir(l,{recursive:!0}),await b.rename(E.join(s.extractDir,r),E.join(l,r)),a&&o&&await b.rename(E.join(s.extractDir,o),E.join(l,o)),{success:!0,sessionId:n,format:this.type,project:i}}};Lt.exports=$e});var Ht=y((Jr,Wt)=>{var j=require("path"),Mn=require("os"),Nn=require("fs"),$=Nn.promises,$n=B(),Vt=Q(),{countLines:Bt,shouldSkipEntry:On}=V(),{readFirstLine:Oe}=le(),Pe=class extends $n{get type(){return"pi-mono"}get displayName(){return"Pi"}get envVar(){return"PI_MONO_SESSION_DIR"}getDefaultDir(){return j.join(Mn.homedir(),".pi","agent","sessions")}async scanEntries(e){let t=(await $.readdir(e)).filter(r=>!On(r)).map(async r=>{let a=j.join(e,r);return(await $.stat(a)).isDirectory()?this._scanProjectDir(a,r):null});return(await Promise.allSettled(t)).filter(r=>r.status==="fulfilled"&&r.value!==null&&r.value!==void 0).map(r=>r.value).flat()}async findById(e,s){try{let t=await $.readdir(s);for(let n of t){let r=j.join(s,n);try{let o=(await $.readdir(r)).find(i=>i.includes(`_${e}.jsonl`));if(o){let i=j.join(r,o),c=await $.stat(i);return await this._createSession(o,i,c,n)}}catch{}}}catch(t){console.error("Error searching Pi-Mono sessions:",t)}return null}async _createSession(e,s,t,n){let r=e.match(/_([a-f0-9-]+)\.jsonl$/);if(!r)return null;let a=r[1],o=await Oe(s);if(!o)return null;try{let i=JSON.parse(o);if(i.type!=="session")return null;let c=await Bt(s),l=n.replace(/^--/,"").replace(/--$/,"");return new Vt(a,"directory",{source:"pi-mono",directory:j.dirname(s),workspace:{cwd:i.cwd||l},createdAt:new Date(i.timestamp),updatedAt:new Date(t.mtime),summary:`Pi-Mono: ${j.basename(i.cwd||l)}`,hasEvents:c>0,eventCount:c,duration:null,sessionStatus:"completed"})}catch(i){return console.error(`[PI-MONO] Error parsing session ${e}:`,i.message),null}}async resolveEventsFile(e,s){try{let t=await $.readdir(s);for(let n of t){let r=j.join(s,n);try{let o=(await $.readdir(r)).find(i=>i.includes(`_${e.id}.jsonl`));if(o)return j.join(r,o)}catch{}}}catch(t){console.error("Error searching Pi-Mono sessions:",t)}return null}async readEvents(e,s){let t=await this.resolveEventsFile(e,s);return this.readJsonlEvents(t)}async _scanProjectDir(e,s){try{let n=(await $.readdir(e)).filter(a=>a.endsWith(".jsonl"));if(n.length===0)return[];let r=[];n.sort().reverse();for(let a of n){let o=j.join(e,a),i=await $.stat(o),c=a.match(/_([a-f0-9-]+)\.jsonl$/);if(!c)continue;let l=c[1],u=await Oe(o);if(u)try{let p=JSON.parse(u);if(p.type!=="session")continue;let m=await Bt(o),f=s.replace(/^--/,"").replace(/--$/,""),g=new Vt(l,"directory",{source:"pi-mono",directory:e,workspace:{cwd:p.cwd||f},createdAt:new Date(p.timestamp),updatedAt:new Date(i.mtime),summary:`Pi-Mono: ${j.basename(p.cwd||f)}`,hasEvents:m>0,eventCount:m,duration:null,sessionStatus:"completed"});r.push(g)}catch(p){console.error(`[PI-MONO] Error parsing session ${a}:`,p.message)}}return r}catch(t){return console.error(`[PI-MONO] Error scanning dir ${e}:`,t.message),[]}}async detectImportCandidate(e){let s=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z_([a-zA-Z0-9_-]+)\.jsonl$/,t=await $.readdir(e);for(let n of t){let r=n.match(s);if(!r)continue;let a=await Oe(j.join(e,n)),o;try{o=a?JSON.parse(a):null}catch{o=null}if(o?.type==="session")return{matched:!0,score:100,reason:"Pi-Mono timestamped JSONL",sessionId:r[1],fileName:n}}return{matched:!1,score:0,reason:"No Pi-Mono timestamped session JSONL found"}}async importDetectedSession(e,s){let{isValidSessionId:t}=q(),{sessionId:n,fileName:r}=e;if(!t(n))return{success:!1,error:"Invalid session ID",statusCode:400};let a=s.req.query.project||"imported-sessions",o=s.targetDir||await this.resolveDir(),i=j.join(o,a);return await $.mkdir(i,{recursive:!0}),await $.rename(j.join(s.extractDir,r),j.join(i,r)),{success:!0,sessionId:n,format:this.type,project:a}}};Wt.exports=Pe});var Xt=y((Gr,Kt)=>{var T=require("path"),se=require("os"),M=require("fs").promises,{fileURLToPath:Jt}=require("url"),Pn=B(),Rn=Q(),{shouldSkipEntry:Gt,getSessionMetadataOptimized:qn}=V(),{computeSessionStatus:Fn}=le();function Un(){let d;switch(se.platform()){case"win32":d=T.join(process.env.APPDATA||T.join(se.homedir(),"AppData","Roaming"));break;case"darwin":d=T.join(se.homedir(),"Library","Application Support");break;case"linux":d=T.join(se.homedir(),".config");break;default:d=T.join(se.homedir(),".config")}return[T.join(d,"Code","User","workspaceStorage"),T.join(d,"Code - Insiders","User","workspaceStorage")]}var Re=class extends Pn{constructor(){super(),this._candidates=null}get type(){return"vscode"}get displayName(){return"Copilot Chat"}get envVar(){return"VSCODE_WORKSPACE_STORAGE_DIR"}get hasCustomPipeline(){return!0}getDefaultDir(){return this._getCandidates()[0]}_getCandidates(){return this._candidates||(this._candidates=Un()),this._candidates}async resolveDir(){if(this.envVar&&process.env[this.envVar])return process.env[this.envVar];let e=this._getCandidates();for(let s of e)try{return await M.access(s),s}catch{}return null}async scanEntries(e){let t=(await M.readdir(e)).filter(r=>!Gt(r)).map(async r=>{let a=T.join(e,r);return(await M.stat(a)).isDirectory()?this._scanWorkspaceDir(a):null});return(await Promise.allSettled(t)).filter(r=>r.status==="fulfilled"&&r.value!==null&&r.value!==void 0).map(r=>r.value).flat()}async findById(e,s){try{let t=await M.readdir(s),n=[];for(let r of t){let a=T.join(s,r,"GitHub.copilot-chat","transcripts");try{let i=(await M.readdir(a)).find(c=>c===`${e}.jsonl`||c.replace(/\.jsonl$/,"")===e);if(i){let c=T.join(a,i),l=await M.stat(c),u=await this._resolveWorkspacePath(T.join(s,r)),p=await this._buildTranscriptSession(i,c,l,r,u);p&&n.push(p)}}catch{}}if(n.length>0)return n.sort((r,a)=>(a.updatedAt?.getTime?.()??0)-(r.updatedAt?.getTime?.()??0)),n[0]}catch(t){console.error(`[VSCode findById] Error searching VSCode sessions: ${t.message}`)}return null}async readEvents(e,s){if(!e?.filePath)return[];try{let t=await this.readJsonlEvents(e.filePath);if(e._chatSessionInfo?.userMessage&&t.length>0&&!t.some((r,a)=>a<3&&(r.type==="user.message"||r.type==="user"||r.type==="request"))){let r=t.find(o=>o.type==="session.start"),a=r?.timestamp||t[0]?.timestamp;t.splice(r?1:0,0,{type:"user.message",id:"synthetic-user-msg-0",timestamp:a,data:{content:e._chatSessionInfo.userMessage,message:e._chatSessionInfo.userMessage,_synthetic:!0},_synthetic:!0})}return t}catch(t){return console.error(`[VSCode readEvents] Error reading session ${e.id}:`,t),[]}}buildTimeline(e,s){return null}async _scanWorkspaceDir(e){let s=T.basename(e),t=await this._resolveWorkspacePath(e),n=[],r=T.join(e,"GitHub.copilot-chat","transcripts");try{await M.access(r);let o=(await M.readdir(r)).filter(i=>i.endsWith(".jsonl")&&!Gt(i));for(let i of o){let c=T.join(r,i);try{let l=await M.stat(c),u=await this._buildTranscriptSession(i,c,l,s,t);u&&n.push(u)}catch(l){console.warn(`[VSCode scan] Skipping transcript ${c}: ${l.message}`)}}}catch{}return n}async _resolveWorkspacePath(e){try{let s=T.join(e,"workspace.json"),t=await M.readFile(s,"utf-8"),n=JSON.parse(t);if(n.folder)return Jt(n.folder);if(n.workspace){let r=Jt(n.workspace);try{let a=await M.readFile(r,"utf-8"),o=JSON.parse(a);if(Array.isArray(o.folders)&&o.folders.length>0){let i=T.dirname(r);return T.resolve(i,o.folders[0].path)}}catch{}}}catch{}return null}async _buildTranscriptSession(e,s,t,n,r){let a=e.replace(".jsonl",""),o=await qn(s),i=Fn(o),c=await this._extractChatSessionInfo(s,a),l=o.startTime?new Date(o.startTime):t.birthtime,u=o.lastEventTime?new Date(o.lastEventTime):t.mtime,p=c.userMessage||o.firstUserMessage,m=new Rn(a,"file",{source:"vscode",filePath:s,directory:T.dirname(s),createdAt:l,updatedAt:u,summary:p?p.slice(0,120):"Copilot agent session",hasEvents:!0,eventCount:o.eventCount||0,duration:o.duration,sessionStatus:i,selectedModel:c.modelId||o.selectedModel||null,copilotVersion:o.copilotVersion||null,workspace:r?{cwd:r,workspaceHash:n}:{workspaceHash:n},agentName:c.agentName||null});return m._isTranscript=!0,m._chatSessionInfo=c,m}async _extractChatSessionInfo(e,s){let t={agentName:null,modelId:null,userMessage:null};try{let n=T.resolve(T.dirname(e),"..",".."),r=T.join(n,"chatSessions",`${s}.jsonl`);await M.access(r);let o=(await M.readFile(r,"utf-8")).trim().split(`
10
+ `);for(let i of o){let c=JSON.parse(i);if(c.kind===0&&c.v?.requests?.[0]){let l=c.v.requests[0];l.message?.text&&(t.userMessage=l.message.text),l.modelId&&(t.modelId=l.modelId),l.agent?.id&&l.agent.id!=="github.copilot.editsAgent"&&(t.agentName=l.agent.id)}if(c.kind===1){let l=c.k||[],u=c.v;if(l.includes("mode")&&u?.kind==="agent"&&u?.id){let m=u.id.match(/agents\/([^/]+)\.agent\.md$/);m&&(t.agentName=m[1])}}}}catch{}return t}};Kt.exports=Re});var Zt=y((Kr,Yt)=>{var de=require("path"),Ln=require("os"),qe=require("fs").promises,zn=Ie(),Fe=class extends zn{get type(){return"modernize"}get displayName(){return"Modernize CLI"}get envVar(){return"MODERNIZE_SESSION_DIR"}getDefaultDir(){return de.join(Ln.homedir(),".modernize","configuration")}async resolveDir(){return this.envVar&&process.env[this.envVar]?process.env[this.envVar]:this.getDefaultDir()}async _findSessionStateDirs(e){let s=[];try{let t=await qe.readdir(e);for(let n of t){if(!n.includes("+"))continue;let r=de.join(e,n,"session-state");try{(await qe.stat(r)).isDirectory()&&s.push(r)}catch{}}}catch{}return s}_isEnvVarOverride(){return!!(this.envVar&&process.env[this.envVar])}async scanEntries(e){if(this._isEnvVarOverride())return this._scanAndTag(e);let s=await this._findSessionStateDirs(e),t=[];for(let n of s){let r=await this._scanAndTag(n);t.push(...r)}return t}_extractModernizeVersion(e){let s=de.basename(de.dirname(e)),t=s.indexOf("+");return t>0?s.substring(0,t):null}async _scanAndTag(e){try{let s=this._extractModernizeVersion(e),t=await super.scanEntries(e);for(let n of t)n.source="modernize",n.modernizeVersion=s;return t}catch{return[]}}async findById(e,s){if(this._isEnvVarOverride())return this._findByIdInDir(e,s);let t=await this._findSessionStateDirs(s);for(let n of t){let r=await this._findByIdInDir(e,n);if(r)return r}return null}async _findByIdInDir(e,s){let t=await super.findById(e,s);return t&&(t.source="modernize",t.modernizeVersion=this._extractModernizeVersion(s)),t}async resolveEventsFile(e,s){if(this._isEnvVarOverride())return super.resolveEventsFile(e,s);let t=await this._findSessionStateDirs(s);for(let n of t)try{let r=await super.resolveEventsFile(e,n);return await qe.access(r),r}catch{}return null}async readEvents(e,s){let t=await this.resolveEventsFile(e,s);return this.readJsonlEvents(t)}async _createDirectorySession(e,s,t){let n=await super._createDirectorySession(e,s,t);return n&&(n.source="modernize"),n}async _createFileSession(e,s,t){let n=await super._createFileSession(e,s,t);return n&&(n.source="modernize"),n}async detectImportCandidate(e){return{matched:!1,score:0,reason:"Modernize does not support zip import (use Copilot)"}}};Yt.exports=Fe});var ee=y((Xr,es)=>{var Qt=yt(),Vn=B(),Bn=Ie(),Wn=zt(),Hn=Ht(),Jn=Xt(),Gn=Zt(),H=new Qt;H.register(new Bn);H.register(new Wn);H.register(new Hn);H.register(new Jn);H.register(new Gn);es.exports={registry:H,AdapterRegistry:Qt,BaseSourceAdapter:Vn}});var Le=y((Yr,ss)=>{var ts=require("fs").promises,{shouldSkipEntry:Kn}=V(),{registry:Xn}=ee(),Ue=class{constructor(e){if(this.registry=Xn,typeof e=="string")this.sources=[{type:"copilot",dir:e}];else if(Array.isArray(e))this.sources=e;else{this.sources=this.registry.all().map(s=>({type:s.type,dir:s.getDefaultDir()}));for(let s of this.sources){let t=this.registry.get(s.type);t&&t.envVar&&process.env[t.envVar]&&(s.dir=process.env[t.envVar]),s.type==="copilot"&&process.env.SESSION_DIR&&!process.env.COPILOT_SESSION_DIR&&(s.dir=process.env.SESSION_DIR)}}this._cache=new Map,this._cacheTTL=60*1e3,this._pendingScans=new Map}invalidateCache(e=null){e?(this._cache.delete(e),this._cache.delete(null)):this._cache.clear()}async findAll(e=null){let s=e||"__all__",t=this._cache.get(s);if(t&&Date.now()-t.timestamp<this._cacheTTL)return t.data;if(this._pendingScans.has(s))return this._pendingScans.get(s);let n=this._doFindAll(e).then(r=>(this._cache.set(s,{data:r,timestamp:Date.now()}),this._pendingScans.delete(s),r)).catch(r=>{throw this._pendingScans.delete(s),r});return this._pendingScans.set(s,n),n}async _doFindAll(e=null){let s=[],t=e?this.sources.filter(n=>n.type===e):this.sources;for(let n of t)try{let r=await this._scanSource(n);s.push(...r)}catch(r){console.error(`Error reading ${n.type} sessions from ${n.dir}:`,r.message)}return this._sortByUpdatedAt(this._deduplicateSessions(s))}async _scanSource(e){let s=this.registry.get(e.type);if(!s)return console.warn(`No adapter registered for source type: ${e.type}`),[];let t;if(e.dir?t=e.dir:t=await s.resolveDir(),!t)return console.warn(`No directory resolved for ${e.type}`),[];try{await ts.access(t)}catch{return console.warn(`Source directory not found: ${t}`),[]}return s.scanEntries(t)}_deduplicateSessions(e){let s=new Map;for(let t of e){let n=s.get(t.id);(!n||t.updatedAt&&n.updatedAt&&new Date(t.updatedAt)>new Date(n.updatedAt))&&s.set(t.id,t)}return Array.from(s.values())}async findById(e){if(Kn(e))return null;for(let s of this.sources){let t=this.registry.get(s.type);if(!t)continue;let n;if(s.dir?n=s.dir:n=await t.resolveDir(),!n)continue;try{await ts.access(n)}catch{console.warn(`Source directory not found: ${n}`);continue}let r=await t.findById(e,n);if(r)return r}return null}_sortByUpdatedAt(e){return e.sort((s,t)=>new Date(t.createdAt)-new Date(s.createdAt))}};ss.exports=Ue});var rs=y((Zr,ns)=>{var ze=class{normalizeEvents(e,s){return Array.isArray(e)?e.filter(t=>!t._isToolResultWrapper).map(t=>this.normalizeEvent(t,s)):(console.warn("[EventNormalizer] normalizeEvents: events is not an array",typeof e),[])}normalizeEvent(e,s){return!e||typeof e!="object"?(console.warn("[EventNormalizer] normalizeEvent: invalid event",e),e):this._isAssistantMessage(e)?this._normalizeAssistantMessage(e,s):this._isTimelineEvent(e)?this._normalizeTimelineEvent(e,s):e}_isAssistantMessage(e){return e.data?.tools&&Array.isArray(e.data.tools)&&e.data.tools.length>0?!0:e.type==="assistant.message"||e.type==="assistant"||e.type==="user.message"||e.type==="user"}_isTimelineEvent(e){return e.type?.startsWith("tool.")||e.type?.startsWith("subagent.")}_normalizeAssistantMessage(e,s){let t={...e};return e.data?.tools&&Array.isArray(e.data.tools)&&(t.data={...e.data,tools:e.data.tools.filter(n=>n.type!=="tool_result").map(n=>this._normalizeToolCall(n,s,e.timestamp))}),t}_normalizeToolCall(e,s,t){if(e.type==="tool_use"){let n=this._computeStatus(e),r=e._startTime||t,a=e._matched?e._endTime||t:null;return{type:"tool_use",id:e.id,name:e.name,startTime:r,endTime:a,status:n,input:e.input||{},result:e.result||null,error:e.error||null,metadata:{source:s,matched:e._matched,duration:this._computeDuration(r,a)}}}if(e.name&&e.status){let n=t,r=e.status==="success"?"completed":e.status,a=r==="completed"||r==="error"?t:null;return{id:e.id||this._generateToolId(),name:e.name,startTime:n,endTime:a,status:r,input:e.input||{},result:e.isError?null:e.result||null,error:e.isError?e.result:null,metadata:{source:s,duration:this._computeDuration(n,a)}}}return console.warn("[EventNormalizer] Unknown tool format, applying fallback normalization",e),{id:e.id||this._generateToolId(),name:e.name||"unknown",startTime:t,endTime:null,status:"running",input:e.input||{},result:null,error:null,metadata:{source:s,fallback:!0}}}_computeStatus(e){return e.error?"error":e.result!==void 0&&e.result!==null&&e.result!==""?"completed":e._matched===!1?"running":e._matched?"completed":"running"}_computeDuration(e,s){if(!(!e||!s))try{let t=new Date(e),n=new Date(s);if(isNaN(t.getTime())||isNaN(n.getTime()))return;let r=n.getTime()-t.getTime();return r>=0?r:void 0}catch{return}}_generateToolId(){return`tool-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}_normalizeTimelineEvent(e){return e.type==="tool.execution_start"||e.type==="tool.execution_complete"?{...e,data:{...e.data,toolCallId:e.data?.toolCallId||e.data?.id,toolName:e.data?.toolName||e.data?.tool||e.data?.name,...e.data}}:(e.type?.startsWith("subagent."),e)}};ns.exports=ze});var Be=y((Qr,is)=>{var ne=require("fs"),J=require("path"),Yn=require("readline"),{isValidSessionId:as,buildMetadata:Zn}=q(),os=Le(),Qn=rs(),Ve=class{constructor(e){e?(this.SESSION_DIR=e,this.sessionRepository=new os(e)):this.sessionRepository=new os,this.eventNormalizer=new Qn}async getAllSessions(e=null){return(await this.sessionRepository.findAll(e)).map(t=>t.toJSON())}async getPaginatedSessions(e=1,s=20,t=null){let r=(await this.sessionRepository.findAll(t)).map(c=>c.toJSON()),a=(e-1)*s,o=a+s;return{sessions:r.slice(a,o),totalSessions:r.length,currentPage:e,totalPages:Math.ceil(r.length/s),hasNextPage:o<r.length,hasPrevPage:e>1}}async getSessionById(e){if(!as(e))return null;let s=await this.sessionRepository.findById(e);if(s)return typeof s.toJSON=="function"?s.toJSON():s}async getSessionEvents(e,s=null){if(!as(e))return s?{events:[],total:0}:[];let t=await this.sessionRepository.findById(e);if(!t)return s?{events:[],total:0}:[];let n=this._getSourceAdapter(t.source),a=this.sessionRepository.sources.find(l=>l.type===t.source)?.dir||null;!a&&n&&(a=await n.resolveDir()),this.SESSION_DIR&&t.source==="copilot"&&(a=this.SESSION_DIR);let o=n&&!n.hasCustomPipeline?await n.resolveEventsFile(t,a):null,i=[];n?i=await n.readEvents(t,a)||[]:console.warn(`SessionService.getSessionEvents: No adapter found for source '${t.source}'. Returning no events.`),i.length>0&&(t.source==="claude"&&t.type==="directory"?i=i.filter(u=>u._subagent):i=i.filter(u=>!u._subagent)),i.sort((l,u)=>{let p=l.timestamp?new Date(l.timestamp).getTime():0,m=u.timestamp?new Date(u.timestamp).getTime():0;return p!==m?p-m:(l._fileIndex??0)-(u._fileIndex??0)}),i=i.filter(l=>l.type!=="file-history-snapshot");let c=t.source==="vscode"?"copilot":t.source;if(i=i.map(l=>this._normalizeEvent(l,c)),n&&!n.hasCustomPipeline&&await this._mergeSubAgentEvents(i,o,e,t.source),n&&!n.hasCustomPipeline&&t.source==="copilot"||t.source==="vscode"?(this._matchCopilotToolCalls(i),this._mergeHookEvents(i),i=this._expandCopilotToTimelineFormat(i),i=this._synthesizeSubagentBoundaryEvents(i)):n&&!n.hasCustomPipeline&&t.source==="claude"?(this._matchClaudeToolResults(i),i=this._expandClaudeToTimelineFormat(i)):n&&!n.hasCustomPipeline&&t.source==="pi-mono"&&this._mergePiMonoToolResults(i),i=i.filter(l=>l.timestamp||l.snapshot?.timestamp?!0:(console.warn("[SessionService] Filtered event without timestamp:",l.type,l.id||l._fileIndex),!1)),i.forEach(l=>{l._fileIndex===999999&&l.timestamp&&delete l._fileIndex}),i=this.eventNormalizer.normalizeEvents(i,t.source),s&&typeof s.limit=="number"&&typeof s.offset=="number"){let l=i.length;return{events:i.slice(s.offset,s.offset+s.limit),total:l}}return i}async _mergeSubAgentEvents(e,s,t,n){let r,a=n==="claude"?new Set(e.map(o=>this._getClaudeSubagentMergeKey(o)).filter(Boolean)):null;if(n==="claude"){let o=this.sessionRepository.sources.find(i=>i.type==="claude");if(!o)return;try{let i=await ne.promises.readdir(o.dir);for(let c of i){let l=J.join(o.dir,c,t,"subagents");try{if((await ne.promises.stat(l)).isDirectory()){r=l;break}}catch{}}}catch(i){console.error("Error searching Claude subagents:",i);return}}else if(n==="copilot"&&s){let o=J.dirname(s);J.basename(s)==="events.jsonl"?r=J.join(o,"subagents"):r=J.join(o,t,"subagents")}if(r){try{if(!(await ne.promises.stat(r)).isDirectory())return}catch{return}try{let i=(await ne.promises.readdir(r)).filter(c=>c.startsWith("agent-")&&c.endsWith(".jsonl"));if(i.length===0)return;for(let c of i){let l=c.replace(".jsonl",""),u=J.join(r,c);try{let p=ne.createReadStream(u,{encoding:"utf-8"}),m=Yn.createInterface({input:p,crlfDelay:1/0}),f=[];for await(let C of m){let k=C.trim();k&&f.push(k)}if(f.length===0)continue;let g=l.replace("agent-",""),h=g.toUpperCase(),w=`Sub-agent ${l}`;try{let C=JSON.parse(f[0]);if(C.agentId&&(g=C.agentId,h=`agent-${C.agentId}`),C.message?.content){let k=typeof C.message.content=="string"?C.message.content:JSON.stringify(C.message.content);w=k.length>100?k.slice(0,100)+"...":k}}catch{}let D=f.map((C,k)=>{try{let X=JSON.parse(C);return X._fileIndex=1e6+k,X._subagent={id:l,name:g},X}catch(X){return console.error(`Error parsing sub-agent ${l} line ${k+1}:`,X.message),null}}).filter(C=>C!==null);if(D.length===0)continue;let N=D.map(C=>this._normalizeEvent(C,n));if(a&&(N=N.filter(C=>{let k=this._getClaudeSubagentMergeKey(C);return k?a.has(k)?!1:(a.add(k),!0):!0})),N.length===0)continue;let O=N[0],at=N[N.length-1],Ns=O.timestamp||new Date().toISOString(),$s=at.timestamp||new Date().toISOString(),Os={type:"subagent.started",id:`${l}-start`,timestamp:Ns,_fileIndex:O._fileIndex-1,_subagent:{id:l,name:g},data:{toolCallId:l,agentName:g,agentDisplayName:h,agentDescription:w}},Ps={type:"subagent.completed",id:`${l}-end`,timestamp:$s,_fileIndex:at._fileIndex+1,_subagent:{id:l,name:g},data:{toolCallId:l,result:`Sub-agent ${h} completed`}};e.push(Os,...N,Ps)}catch(p){console.error(`Error reading sub-agent ${l}:`,p)}}e.sort((c,l)=>{let u=c.timestamp?new Date(c.timestamp).getTime():0,p=l.timestamp?new Date(l.timestamp).getTime():0;return u!==p?u-p:c._fileIndex-l._fileIndex})}catch(o){console.error("Error processing sub-agents:",o)}}}_getClaudeSubagentMergeKey(e){if(!e||e.type?.startsWith("subagent."))return null;let s=e.timestamp||e.snapshot?.timestamp;if(!s)return null;let t=e.uuid||e.id||"",n=e.parentUuid||e.parentId||"",r=e.data?.message||"",a=Array.isArray(e.data?.tools)?e.data.tools.map(o=>!o||typeof o!="object"?"":o.type==="tool_use"?`${o.type}:${o.id||""}:${o.name||""}`:o.type==="tool_result"?`${o.type}:${o.tool_use_id||""}`:`${o.type||"tool"}:${o.id||""}:${o.name||""}`).join("|"):"";return!t&&!n&&!r&&!a?null:JSON.stringify([e.type,s,t,n,r,a])}_matchClaudeToolResults(e){let s=new Map;e.forEach(t=>{t.data?.tools&&t.data.tools.forEach(n=>{n.type==="tool_result"&&(n.tool_use_id?s.set(n.tool_use_id,n):console.warn("[sessionService] tool_result missing tool_use_id:",n))})}),e.forEach(t=>{t.type==="user"&&Array.isArray(t.message?.content)&&t.message.content.length>0&&t.message.content.every(r=>r?.type==="tool_result")&&(t._isToolResultWrapper=!0)}),e.forEach(t=>{t.data?.tools&&(t.data.tools=t.data.tools.map(n=>{if(n.type==="tool_use"){let r=s.get(n.id);return r?{...n,result:r.content,_matched:!0}:{...n,_matched:!1}}return n}),t.type==="assistant"||t.type==="assistant.message"?t.data.tools=t.data.tools.filter(n=>n.type!=="tool_result"):(t.type==="user"||t.type==="user.message")&&t.data.tools.length>0&&t.data.tools.every(r=>r.type==="tool_result")&&(t._isToolResultWrapper=!0))})}_mergePiMonoToolResults(e){let s=new Set;e.forEach(n=>{if(n.type==="assistant.message"&&n.data.tools&&n.data.tools.length>0){let r=n.data.tools,a=[],o=n.id,i=!0;for(;i&&a.length<r.length;){i=!1;for(let c of e)if(c.type==="message"&&c.data.role==="toolResult"&&c.parentId===o&&!a.includes(c)){a.push(c),o=c.id,i=!0;break}}a.forEach((c,l)=>{if(l<r.length){let u=r[l];u.result=c.data.result,u.resultId=c.id,u.status="completed",s.add(c.id)}})}});let t=e.length;for(let n=e.length-1;n>=0;n--)e[n].type==="message"&&e[n].data.role==="toolResult"&&s.has(e[n].id)&&e.splice(n,1);s.size>0&&console.log(`[PI-MONO] Merged ${s.size} toolResult events into assistant messages (${t} \u2192 ${e.length} events)`)}_matchPiMonoToolResults_OLD(e){let s=new Set;e.forEach(n=>{if(n.type==="assistant.message"&&n.data.tools&&n.data.tools.length>0){let r=n.data.tools,a=[],o=n.id,i=!0;for(;i&&a.length<r.length;){i=!1;for(let c of e)if(c.type==="tool.result"&&c.parentId===o&&!a.includes(c)){a.push(c),o=c.id,i=!0;break}}a.forEach((c,l)=>{if(l<r.length){let u=r[l];u.status="completed",u._matched=!0,u.result=c.data.result,u.resultId=c.id,s.add(c.id)}})}});let t=e.length;for(let n=e.length-1;n>=0;n--)e[n].type==="tool.result"&&s.has(e[n].id)&&e.splice(n,1);s.size>0&&console.log(`[PI-MONO] Removed ${s.size} matched tool.result events (${t} \u2192 ${e.length} events)`)}_mergeHookEvents(e){let s=new Map;for(let t=0;t<e.length;t++){let n=e[t],r=n.data?.hookInvocationId;if(r){if(n.type==="hook.start")s.set(r,t);else if(n.type==="hook.end"){let a=s.get(r);if(a!==void 0){let o=e[a],i=n.data?.success!==!1;if(o.data.hookSuccess=i,o.data.hookError=n.data?.error||null,o.timestamp&&n.timestamp){let c=new Date(n.timestamp)-new Date(o.timestamp);o.data.hookDurationMs=c;let l=c<1e3?`${c}ms`:`${(c/1e3).toFixed(2)}s`;o.data.message&&(o.data.message+=`
11
+ **Duration:** ${l}`)}o.data.badgeLabel=i?"\u2713 HOOK":"\u2717 HOOK",o.data.badgeClass=i?"badge-hook":"badge-error",s.delete(r)}n._remove=!0}}}for(let t=e.length-1;t>=0;t--)e[t]._remove&&e.splice(t,1)}_matchCopilotToolCalls(e){let s=new Map;e.forEach(t=>{if(t.type==="tool.execution_start"){let n=t.data?.toolCallId;n&&s.set(n,{name:t.data.toolName,input:t.data.arguments||{},start:t})}else if(t.type==="tool.execution_complete"){let n=t.data?.toolCallId;if(n)if(s.has(n)){let r=s.get(n);r.complete=t,r.result=t.data?.result,r.status=t.data?.error?"error":"completed",r.error=t.data?.error}else console.warn(`[sessionService] Orphaned tool.execution_complete for toolCallId=${n}`),s.set(n,{name:t.data.toolName||"unknown",input:{},start:null,complete:t,result:t.data?.result,status:t.data?.error?"error":"completed",error:t.data?.error})}}),e.forEach(t=>{if(t.type==="assistant.message"&&t.data?.toolRequests){let n=[];t.data.toolRequests.forEach(r=>{let a=r.toolCallId;if(s.has(a)){let o=s.get(a);n.push({type:"tool_use",id:a,name:r.name||o.name,input:r.arguments||o.input,result:o.result,status:o.status||"running",error:o.error,_matched:!!o.complete,_startTime:o.start?.timestamp,_endTime:o.complete?.timestamp})}else n.push({type:"tool_use",id:a,name:r.name,input:r.arguments||{},status:"running",_matched:!1})}),n.length>0&&(t.data.tools=n)}})}_generateBadgeInfo(e){let s=e.type,t=e.data||{};if(s==="message"&&t.role==="toolResult"){e.data.badgeLabel="TOOL RESULT",e.data.badgeClass="badge-tool";return}if(s==="session.model_change"||s==="model.change"){e.data.badgeLabel="MODEL CHANGE",e.data.badgeClass="badge-session";return}if(s==="session.truncation"){e.data.badgeLabel="TRUNCATION",e.data.badgeClass="badge-truncation";return}if(s==="session.compaction_start"||s==="session.compaction_complete"||s==="compaction"){e.data.badgeLabel="COMPACTION",e.data.badgeClass="badge-compaction";return}if(s==="thinking.change"){e.data.badgeLabel="THINKING",e.data.badgeClass="badge-session";return}if(s==="system.notification"){e.data.badgeLabel="SYSTEM",e.data.badgeClass="badge-system";return}let r=(s||"").split(".")[0]||"unknown",o={user:{label:"USER",class:"badge-user"},assistant:{label:"ASSISTANT",class:"badge-assistant"},reasoning:{label:"REASONING",class:"badge-reasoning"},turn:{label:"TURN",class:"badge-turn"},tool:{label:"TOOL",class:"badge-tool"},subagent:{label:"SUBAGENT",class:"badge-subagent"},skill:{label:"SKILL",class:"badge-skill"},session:{label:"SESSION",class:"badge-session"},error:{label:"ERROR",class:"badge-error"},abort:{label:"ABORT",class:"badge-error"}}[r]||{label:r.toUpperCase(),class:"badge-info"};e.data.badgeLabel=o.label,e.data.badgeClass=o.class}_normalizeEvent(e,s){let t={...e};if(t.data=t.data||{},s==="copilot"){if(e.type==="user.message"&&e.data?.source==="system"){t.type="system.notification";let n=e.data.content||e.data.message||"",r=n.match(/<system_notification>([\s\S]*?)<\/system_notification>/);return t.data.message=r?r[1].trim():n.trim(),this._generateBadgeInfo(t),t}if(e.type==="request"){if(t.type="user",e.payload?.messages&&Array.isArray(e.payload.messages)){let n=e.payload.messages.find(r=>r.role==="user");n&&(t.message={role:"user",content:n.content||""})}}else if(e.type==="response"&&(t.type="assistant",e.payload?.content&&Array.isArray(e.payload.content))){let n=e.payload.content.filter(r=>r.type==="text");n.length>0&&(t.message={role:"assistant",content:n.map(r=>r.text).join(`
11
12
  `)})}if(e.type==="assistant.message"&&e.data?.content&&e.data.content.trim()&&(t.data.message=e.data.content),e.type==="subagent.selected"&&Array.isArray(e.data?.tools)&&(t.data.allowedTools=e.data.tools,delete t.data.tools,(e.data.agentDisplayName||e.data.agentName)&&(t.data.message=`Agent: ${e.data.agentDisplayName||e.data.agentName}`,t.data.allowedTools.length>0&&t.data.allowedTools[0]!=="*"&&(t.data.message+=`
12
- Tools: ${t.data.allowedTools.join(", ")}`))),e.type==="hook.start"){let s=e.data||{},r=[];if(s.hookType&&r.push(`**Hook:** ${s.hookType}`),s.input?.toolName&&r.push(`**Tool:** ${s.input.toolName}`),s.input?.toolArgs&&Object.keys(s.input.toolArgs).length>0){let o=Object.entries(s.input.toolArgs).map(([a,i])=>`${a}: ${typeof i=="string"?i:JSON.stringify(i)}`).join(", ");r.push(`**Args:** ${o}`)}if(s.input?.toolResult?.textResultForLlm){let o=s.input.toolResult.textResultForLlm.slice(0,200);r.push(`**Result:** ${o}${s.input.toolResult.textResultForLlm.length>200?"\u2026":""}`)}return r.length>0&&(t.data.message=r.join(`
13
- `)),t.data.badgeLabel="HOOK",t.data.badgeClass="badge-tool",this._generateBadgeInfo(t),t}if(e.type==="hook.end"){let s=e.data||{},r=[];return s.hookType&&r.push(`**Hook:** ${s.hookType}`),r.push(s.success?"**Status:** \u2713 success":"**Status:** \u2717 failed"),s.error&&r.push(`**Error:** ${s.error}`),t.data.message=r.join(`
14
- `),t.data.badgeLabel="HOOK END",t.data.badgeClass=s.success?"badge-tool":"badge-error",this._generateBadgeInfo(t),t}return this._generateBadgeInfo(t),t}if(n==="pi-mono"){if(e.type==="message"){let{message:s}=e;if(s.role==="user"?t.type="user.message":s.role==="assistant"?t.type="assistant.message":s.role==="toolResult"&&(t.type="message"),t.data.role=s.role,Array.isArray(s.content)){let r=s.content.filter(o=>o.type==="text");if(r.length>0&&(t.data.message=r.map(o=>o.text).join(`
15
- `)),s.role==="assistant"){let o=s.content.filter(a=>a.type==="toolCall");o.length>0&&(t.data.tools=o.map(a=>({type:"tool_use",id:a.id,name:a.name,input:a.arguments})))}s.role==="toolResult"&&(t.data.result=r.map(o=>o.text).join(`
16
- `))}s.usage&&(t.usage=s.usage)}else if(e.type==="model_change")t.type="model.change",t.data={provider:e.provider,model:e.modelId},e.provider&&e.modelId?t.data.message=`Model changed to ${e.provider}/${e.modelId}`:e.modelId&&(t.data.message=`Model changed to ${e.modelId}`);else if(e.type==="thinking_level_change")t.type="thinking.change",t.data={level:e.thinkingLevel},e.thinkingLevel&&(t.data.message=`Thinking level: ${e.thinkingLevel}`);else if(e.type==="session"){t.data={cwd:e.cwd,version:e.version};let s=[];e.cwd&&s.push(`Working directory: ${e.cwd}`),e.version&&s.push(`Session version: ${e.version}`),s.length>0&&(t.data.message=s.join(`
17
- `))}return this._generateBadgeInfo(t),t}switch(e.type){case"user":case"assistant":if(e.message){if(e.message.content){let s=this._extractClaudeTextContent(e.message.content);s&&(t.data.message=s)}if(Array.isArray(e.message.content)){let s=e.message.content.filter(r=>r&&typeof r=="object"&&(r.type==="tool_use"||r.type==="tool_result"));s.length>0&&(t.data.tools=s.map(r=>r.type==="tool_use"?{type:"tool_use",id:r.id,name:r.name,input:r.input}:{type:"tool_result",tool_use_id:r.tool_use_id,content:r.content}))}t._originalMessage=e.message}break;case"file-history-snapshot":if(e.snapshot?.trackedFileBackups){let s=Object.entries(e.snapshot.trackedFileBackups);if(s.length>0){let r=s.map(([o,a])=>`${o} (v${a.version})`).join(`
13
+ Tools: ${t.data.allowedTools.join(", ")}`))),e.type==="hook.start"){let n=e.data||{};t.data.hookType=n.hookType||null,t.data.hookToolName=n.input?.toolName||null,t.data.hookArgs=n.input?.toolArgs||null,t.data.hookResult=n.input?.toolResult?.textResultForLlm||null;let r=[];return n.hookType&&r.push(n.hookType),n.input?.toolName&&r.push(`\u2192 ${n.input.toolName}`),t.data.message=r.join(" ")||"hook",t.data.badgeLabel="HOOK",t.data.badgeClass="badge-hook",this._generateBadgeInfo(t),t}if(e.type==="hook.end"){let n=e.data||{},r=[];return n.hookType&&r.push(`**Hook:** ${n.hookType}`),r.push(n.success?"**Status:** \u2713 success":"**Status:** \u2717 failed"),n.error&&r.push(`**Error:** ${n.error}`),t.data.message=r.join(`
14
+ `),t.data.badgeLabel="HOOK END",t.data.badgeClass=n.success?"badge-hook":"badge-error",this._generateBadgeInfo(t),t}return this._generateBadgeInfo(t),t}if(s==="pi-mono"){if(e.type==="message"){let{message:n}=e;if(n.role==="user"?t.type="user.message":n.role==="assistant"?t.type="assistant.message":n.role==="toolResult"&&(t.type="message"),t.data.role=n.role,Array.isArray(n.content)){let r=n.content.filter(a=>a.type==="text");if(r.length>0&&(t.data.message=r.map(a=>a.text).join(`
15
+ `)),n.role==="assistant"){let a=n.content.filter(o=>o.type==="toolCall");a.length>0&&(t.data.tools=a.map(o=>({type:"tool_use",id:o.id,name:o.name,input:o.arguments})))}n.role==="toolResult"&&(t.data.result=r.map(a=>a.text).join(`
16
+ `))}n.usage&&(t.usage=n.usage)}else if(e.type==="model_change")t.type="model.change",t.data={provider:e.provider,model:e.modelId},e.provider&&e.modelId?t.data.message=`Model changed to ${e.provider}/${e.modelId}`:e.modelId&&(t.data.message=`Model changed to ${e.modelId}`);else if(e.type==="thinking_level_change")t.type="thinking.change",t.data={level:e.thinkingLevel},e.thinkingLevel&&(t.data.message=`Thinking level: ${e.thinkingLevel}`);else if(e.type==="session"){t.data={cwd:e.cwd,version:e.version};let n=[];e.cwd&&n.push(`Working directory: ${e.cwd}`),e.version&&n.push(`Session version: ${e.version}`),n.length>0&&(t.data.message=n.join(`
17
+ `))}return this._generateBadgeInfo(t),t}switch(e.type){case"user":case"assistant":if(e.message){if(e.message.model&&(t.model=e.message.model),e.message.usage&&(t.usage=e.message.usage),e.message.content){let n=this._extractClaudeTextContent(e.message.content);n&&(t.data.message=n)}if(Array.isArray(e.message.content)){let n=e.message.content.filter(r=>r&&typeof r=="object"&&(r.type==="tool_use"||r.type==="tool_result"));n.length>0&&(t.data.tools=n.map(r=>r.type==="tool_use"?{type:"tool_use",id:r.id,name:r.name,input:r.input}:{type:"tool_result",tool_use_id:r.tool_use_id,content:r.content}))}t._originalMessage=e.message}break;case"file-history-snapshot":if(e.snapshot?.trackedFileBackups){let n=Object.entries(e.snapshot.trackedFileBackups);if(n.length>0){let r=n.map(([a,o])=>`${a} (v${o.version})`).join(`
18
18
  `);t.data.message=`Tracked files:
19
- ${r}`}else t.data.message="No files tracked"}break;case"progress":if(e.data){let s=[];if(e.data.hookName&&s.push(`Hook: ${e.data.hookName}`),e.data.hookEvent&&s.push(`Event: ${e.data.hookEvent}`),e.data.command&&s.push(`Command: ${e.data.command}`),s.length>0&&(t.data.message=s.join(`
20
- `)),e.data.message?.message?.content&&Array.isArray(e.data.message.message.content)){let r=e.data.message.message.content.filter(o=>o&&typeof o=="object"&&(o.type==="tool_use"||o.type==="tool_result"));r.length>0&&(t.data.tools=r.map(o=>o.type==="tool_use"?{type:"tool_use",id:o.id,name:o.name,input:o.input}:{type:"tool_result",tool_use_id:o.tool_use_id,content:o.content}))}}break;case"hook.start":{let s=e.data||{},r=[];if(s.hookType&&r.push(`**Hook:** ${s.hookType}`),s.input?.toolName&&r.push(`**Tool:** ${s.input.toolName}`),s.input?.toolArgs&&Object.keys(s.input.toolArgs).length>0){let o=Object.entries(s.input.toolArgs).map(([a,i])=>`${a}: ${typeof i=="string"?i:JSON.stringify(i)}`).join(", ");r.push(`**Args:** ${o}`)}if(s.input?.toolResult?.textResultForLlm){let o=s.input.toolResult.textResultForLlm.slice(0,200);r.push(`**Result:** ${o}${s.input.toolResult.textResultForLlm.length>200?"\u2026":""}`)}r.length>0&&(t.data.message=r.join(`
21
- `)),t.data.badgeLabel="HOOK",t.data.badgeClass="badge-tool";break}case"hook.end":{let s=e.data||{},r=[];s.hookType&&r.push(`**Hook:** ${s.hookType}`),r.push(s.success?"**Status:** \u2713 success":"**Status:** \u2717 failed"),s.error&&r.push(`**Error:** ${s.error}`),t.data.message=r.join(`
22
- `),t.data.badgeLabel="HOOK END",t.data.badgeClass=s.success?"badge-tool":"badge-error";break}default:e.data?.message&&!t.data.message&&(t.data.message=e.data.message)}return this._generateBadgeInfo(t),t}_extractClaudeTextContent(e){if(typeof e=="string")return e;if(Array.isArray(e)){let n=[];for(let t of e)if(t.type==="text")n.push(t.text);else if(t.type==="tool_result"){if(typeof t.content=="string")n.push(t.content);else if(Array.isArray(t.content)){let s=t.content.filter(r=>r.type==="text").map(r=>r.text).join(`
23
- `);s&&n.push(s)}}return n.join(`
24
- `)}return""}_extractUsageData(e){let n=e.find(s=>s.type==="session.shutdown");if(!n||!n.data)return null;let t=n.data;return{modelMetrics:t.modelMetrics||{},totalPremiumRequests:t.totalPremiumRequests||0,totalApiDurationMs:t.totalApiDurationMs||0,codeChanges:t.codeChanges||{linesAdded:0,linesRemoved:0,filesModified:[]},currentTokens:t.currentTokens||0,systemTokens:t.systemTokens||0,conversationTokens:t.conversationTokens||0,toolDefinitionsTokens:t.toolDefinitionsTokens||0}}async getSessionWithEvents(e){let n=await this.getSessionById(e);if(!n)return null;let t=await this.getSessionEvents(e),s=On(n),r=t.find(a=>a.type==="session.start");r?.data?.selectedModel&&(s.model=r.data.selectedModel);let o=t.find(a=>a.type==="session.model_change");if(o?.data&&(s.model=o.data.newModel||o.data.model),t.length){let a=t[t.length-1];a?.timestamp&&(s.updated=a.timestamp)}if(t.length){let a=t[0];a?.timestamp&&(s.created=a.timestamp)}return s.usage=this._extractUsageData(t),{session:n,events:t,metadata:s}}async getTimeline(e){let n=await this.getSessionById(e);if(!n)return null;let t=await this.getSessionEvents(e),s=this._getSourceAdapter(n.source);if(s){let r=s.buildTimeline(t,n);if(r&&(r.turns?.length>0||Object.keys(r.summary||{}).length>0))return r}return n.source==="copilot"?this._buildCopilotTimeline(t,n):n.source==="claude"?this._buildClaudeTimeline(t,n):n.source==="pi-mono"?this._buildPiMonoTimeline(t,n):{turns:[],summary:{}}}_buildPiMonoTimeline(e,n){let t=[],s=0;for(let a=0;a<e.length;a++){let i=e[a];if(i.type==="user.message"){s++;let l={id:`turn-${s}`,type:"user-request",message:i.data.message||"",startTime:i.timestamp,endTime:i.timestamp,assistantTurns:[],subagents:[]},c=a+1,d=0;for(;c<e.length&&e[c].type!=="user.message";){let p=e[c];if(p.type==="assistant.message"){d++,l.endTime=p.timestamp;let m={id:`assistant-${d}`,startTime:p.timestamp,endTime:p.timestamp,tools:[]};if(p.data.tools&&Array.isArray(p.data.tools))for(let g of p.data.tools)m.tools.push({name:g.name,startTime:p.timestamp,endTime:p.timestamp,status:g.status||"completed",input:g.input,result:g.result});l.assistantTurns.push(m)}c++}t.push(l)}}let r=t.reduce((a,i)=>a+i.assistantTurns.reduce((l,c)=>l+c.tools.length,0),0),o={totalTurns:t.length,totalAssistantTurns:t.reduce((a,i)=>a+i.assistantTurns.length,0),totalTools:r,totalSubagents:0,startTime:e[0]?.timestamp,endTime:e[e.length-1]?.timestamp};return{turns:t,summary:o}}_buildCopilotTimeline(e,n){let t=[],s=null,r=0;for(let a of e)if(a.type==="assistant.turn_start")r++,s={id:`turn-${r}`,type:"assistant-turn",message:a.data.message||"",startTime:a.timestamp,endTime:null,tools:[],subagents:[]};else if(a.type==="assistant.turn_complete"&&s)s.endTime=a.timestamp,t.push(s),s=null;else if(a.type==="tool.execution_start"&&s){let i={name:a.data.tool||a.data.name,startTime:a.timestamp,endTime:null,status:"running",input:a.data.arguments||a.data.input};s.tools.push(i)}else if(a.type==="tool.execution_complete"&&s){let i=s.tools.find(l=>l.name===(a.data.tool||a.data.name)&&!l.endTime);i&&(i.endTime=a.timestamp,i.status=a.data?.error||a.data?.isError?"error":"completed",i.result=a.data?.result)}s&&(s.endTime=e[e.length-1]?.timestamp,t.push(s));let o={totalTurns:t.length,totalTools:t.reduce((a,i)=>a+i.tools.length,0),totalSubagents:0,startTime:e[0]?.timestamp,endTime:e[e.length-1]?.timestamp};return{turns:t,summary:o}}_buildClaudeTimeline(e,n){return this._buildPiMonoTimeline(e,n)}_expandPiMonoToCopilotFormat(e){let n=[],t=0,s=0;for(let r=0;r<e.length;r++){let o=e[r];if(o.type!=="user.message"&&o.type!=="assistant.message"){n.push(o);continue}if(o.type==="user.message"){t++,n.push({...o,_turnNumber:t});continue}if(o.type==="assistant.message"){let a=o.data.tools||[],i=o.timestamp,l=`pi-turn-${r}`;n.push({type:"assistant.turn_start",id:`${l}-start`,timestamp:i,parentId:o.parentId,data:{message:o.data.message||"",model:o.data.model,tools:a.length>0?a:void 0},_synthetic:!0,_turnNumber:t,_fileIndex:o._fileIndex}),n.push({...o,_fileIndex:o._fileIndex+.05}),a.forEach((c,d)=>{let p=`pi-tool-${s++}`,m=i,g=i;n.push({type:"tool.execution_start",id:`${p}-start`,timestamp:m,parentId:l,data:{toolCallId:p,toolName:c.name,tool:c.name,arguments:c.input||{}},_synthetic:!0,_fileIndex:o._fileIndex+.1+d*.01}),n.push({type:"tool.execution_complete",id:`${p}-complete`,timestamp:g,parentId:p,data:{toolCallId:p,toolName:c.name,tool:c.name,result:c.result,error:c.status==="error"?"Tool execution failed":null,isError:c.status==="error"},_synthetic:!0,_fileIndex:o._fileIndex+.15+d*.01})}),n.push({type:"assistant.turn_complete",id:`${l}-complete`,timestamp:o.timestamp,parentId:l,data:{message:o.data.message||""},_synthetic:!0,_turnNumber:t,_fileIndex:o._fileIndex+.9})}}return n}_expandVsCodeEvents(e){let n=[],t=[],s=null,r=null,o=0,a=null,i=null,l=()=>{t.length!==0&&(n.push({type:"assistant.message",id:`vscode-tools-${o}`,timestamp:r,parentId:s,data:{message:"",content:"",tools:t,subAgentId:a,subAgentName:i},_synthetic:!0}),t=[],a=null,i=null)};for(let c=0;c<e.length;c++){let d=e[c];if(d.type==="tool.invocation"){let p=d.data?.subAgentId||null;t.length>0&&p!==a&&l(),t.length===0&&(s=d.parentId,r=d.timestamp,o=c,a=p,i=d.data?.subAgentName||null),d.data?.tool&&t.push(d.data.tool)}else l(),n.push(d)}return l(),n}_expandCopilotToTimelineFormat(e){let n=[],t=0;for(let s=0;s<e.length;s++){let r=e[s];if(r.type==="user"){t++,n.push({...r,type:"user.message",_turnNumber:t,data:{...r.data,message:r.message?.content||r.data?.message||""}});continue}if(r.type==="assistant"){let o=r.uuid||`copilot-assistant-${s}`,a=r.timestamp,i="";r.message?.content?Array.isArray(r.message.content)?i=r.message.content.filter(l=>l&&l.type==="text").map(l=>l.text).join(`
25
- `):typeof r.message.content=="string"&&(i=r.message.content):r.data?.message&&(i=r.data.message),n.push({type:"assistant.turn_start",id:`${o}-start`,timestamp:a,parentId:r.parentId,uuid:r.uuid,data:{message:i,turnId:o},_synthetic:!0,_turnNumber:t,_fileIndex:r._fileIndex}),n.push({type:"assistant.message",id:o,timestamp:a,parentId:r.parentId,uuid:r.uuid,data:{message:i,tools:r.data?.tools||[]},_synthetic:!0,_turnNumber:t,_fileIndex:r._fileIndex+.05}),r.data?.tools&&r.data.tools.length>0&&r.data.tools.forEach((l,c)=>{l.start&&n.push({...l.start,_fileIndex:r._fileIndex+.1+c*.02}),l.complete&&n.push({...l.complete,_fileIndex:r._fileIndex+.15+c*.02})}),n.push({type:"assistant.turn_complete",id:`${o}-complete`,timestamp:a,parentId:o,uuid:r.uuid,data:{message:i},_synthetic:!0,_turnNumber:t,_fileIndex:r._fileIndex+.9});continue}n.push(r)}return n}_expandClaudeToTimelineFormat(e){let n=[],t=0;for(let s=0;s<e.length;s++){let r=e[s];if(r.type==="user"){t++,n.push({...r,type:"user.message",_turnNumber:t,data:{...r.data,message:r.data?.message||""}});continue}if(r.type==="assistant"){let o=r.id||`claude-assistant-${s}`,a=r.timestamp,i=r.data?.message||"";n.push({type:"assistant.turn_start",id:`${o}-start`,timestamp:a,parentId:r.parentId,data:{message:i,turnId:o},_synthetic:!0,_turnNumber:t,_fileIndex:r._fileIndex}),n.push({type:"assistant.message",id:o,timestamp:a,parentId:r.parentId,data:{message:i,tools:r.data?.tools||[]},_synthetic:!0,_turnNumber:t,_fileIndex:r._fileIndex+.05}),r.data?.tools&&r.data.tools.length>0&&r.data.tools.forEach((l,c)=>{l.type==="tool_use"&&(n.push({type:"tool.execution_start",id:`${l.id}-start`,timestamp:a,data:{toolCallId:l.id,toolName:l.name,arguments:l.input||{}},_synthetic:!0,_fileIndex:r._fileIndex+.1+c*.02}),l.result&&n.push({type:"tool.execution_complete",id:`${l.id}-complete`,timestamp:a,data:{toolCallId:l.id,toolName:l.name,result:l.result,isError:!1},_synthetic:!0,_fileIndex:r._fileIndex+.15+c*.02}))}),n.push({type:"assistant.turn_complete",id:`${o}-complete`,timestamp:a,parentId:o,data:{message:i},_synthetic:!0,_turnNumber:t,_fileIndex:r._fileIndex+.9});continue}n.push(r)}return n}_expandVsCodeToTimelineFormat(e){let n=[];for(let t=0;t<e.length;t++){let s=e[t];n.push(s),s.type==="assistant.message"&&s.data?.tools&&s.data.tools.length>0&&s.data.tools.forEach((r,o)=>{if(!r.id||!r.name)return;let a=r.startTime||s.timestamp,i=r.endTime||s.timestamp;n.push({type:"tool.execution_start",id:`${r.id}-start`,timestamp:a,parentId:s.id,data:{toolCallId:r.id,toolName:r.name,tool:r.name,arguments:r.input||{}},_synthetic:!0,_fileIndex:s._fileIndex?s._fileIndex+.1+o*.02:void 0}),n.push({type:"tool.execution_complete",id:`${r.id}-complete`,timestamp:i,parentId:r.id,data:{toolCallId:r.id,toolName:r.name,tool:r.name,result:r.result||null,error:r.error||(r.status==="error"?"Tool execution failed":null),isError:r.status==="error"},_synthetic:!0,_fileIndex:s._fileIndex?s._fileIndex+.15+o*.02:void 0})})}return n}_getSourceAdapter(e){let n=this.sessionRepository.registry||ce().registry;return n?.get?n.get(e):null}};ts.exports=Le});var Be=w((Rr,ss)=>{var $=require("fs").promises,R=require("path"),qn=require("os"),Ve=class{constructor(){this.knownTagsDir=R.join(qn.homedir(),".session-viewer"),this.knownTagsFilePath=R.join(this.knownTagsDir,"known-tags.json")}async ensureKnownTagsFile(){try{await $.access(this.knownTagsFilePath)}catch{await $.mkdir(this.knownTagsDir,{recursive:!0}),await $.writeFile(this.knownTagsFilePath,JSON.stringify([]),"utf8")}}async readKnownTagsFile(){await this.ensureKnownTagsFile();try{let e=await $.readFile(this.knownTagsFilePath,"utf8");return JSON.parse(e)}catch(e){return console.error("Error reading known tags file:",e),[]}}async writeKnownTagsFile(e){await this.ensureKnownTagsFile(),await $.writeFile(this.knownTagsFilePath,JSON.stringify(e,null,2),"utf8")}getSessionTagsFilePath(e){if(e.filePath){let n=R.dirname(e.filePath),t=R.basename(e.filePath,R.extname(e.filePath));return R.join(n,`${t}.tags.json`)}return e.directory?R.join(e.directory,"tags.json"):R.join(this.knownTagsDir,"session-tags",`${e.id}.tags.json`)}normalizeTag(e){return e.trim().toLowerCase().substring(0,30)}async getAllKnownTags(){return(await this.readKnownTagsFile()).sort()}async getSessionTags(e){let n=this.getSessionTagsFilePath(e);try{await $.access(n);let t=await $.readFile(n,"utf8");return JSON.parse(t)}catch{return[]}}async setSessionTags(e,n){if(!Array.isArray(n))throw new Error("Tags must be an array");let t=n.map(r=>this.normalizeTag(r)).filter(r=>r.length>0).filter((r,o,a)=>a.indexOf(r)===o);if(t.length>10)throw new Error("Maximum 10 tags per session");let s=this.getSessionTagsFilePath(e);if(t.length===0)try{await $.unlink(s)}catch{}else await $.mkdir(R.dirname(s),{recursive:!0}),await $.writeFile(s,JSON.stringify(t,null,2),"utf8"),await this.updateKnownTags(t);return t}async updateKnownTags(e){let t=[...await this.readKnownTagsFile(),...e],s=[...new Set(t)];await this.writeKnownTagsFile(s)}async addSessionTags(e,n){let s=[...await this.getSessionTags(e),...n];return await this.setSessionTags(e,s)}async removeSessionTags(e,n){let t=await this.getSessionTags(e),s=n.map(o=>this.normalizeTag(o)),r=t.filter(o=>!s.includes(o));return await this.setSessionTags(e,r)}async getMultipleSessionTags(e){let n={};for(let t of e)n[t.id]=await this.getSessionTags(t);return n}};ss.exports=Ve});var as=w((qr,os)=>{var Fn=ze(),{isValidSessionId:oe,buildMetadata:ns}=V(),{trackEvent:J,trackMetric:rs}=F(),Ln=require("adm-zip"),G=require("path"),q=require("fs"),Ue=class{constructor(e=null){this.sessionService=e||new Fn}async getHomepage(e,n){try{let t=await this.sessionService.getPaginatedSessions(1,20,"copilot"),s={};if(this.sessionService.sessionRepository&&this.sessionService.sessionRepository.sources)for(let o of this.sessionService.sessionRepository.sources)s[o.type]=o.dir;let r={sessions:t.sessions,hasMore:t.hasNextPage,totalSessions:t.totalSessions,sourceHints:JSON.stringify(s)};J("HomepageViewed",{sessionCount:t.totalSessions.toString(),sourceFilter:"copilot"}),n.render("index",r)}catch(t){console.error("Error loading sessions:",t),n.status(500).send("Error loading sessions")}}async getSessionDetail(e,n){try{let t=e.params.id;if(!oe(t))return n.status(400).json({error:"Invalid session ID"});let s=await this.sessionService.sessionRepository.findById(t);if(!s)return n.status(404).json({error:"Session not found"});let r=ns(s);try{let l=(await this.sessionService.getSessionEvents(t)).find(c=>c.type==="session.shutdown");if(l&&l.data){let c=l.data;r.usage={modelMetrics:c.modelMetrics||{},totalPremiumRequests:c.totalPremiumRequests||0,totalApiDurationMs:c.totalApiDurationMs||0,codeChanges:c.codeChanges||{linesAdded:0,linesRemoved:0,filesModified:[]},currentTokens:c.currentTokens||0,systemTokens:c.systemTokens||0,conversationTokens:c.conversationTokens||0,toolDefinitionsTokens:c.toolDefinitionsTokens||0}}}catch(i){console.error("Error extracting usage data:",i)}J("SessionViewed",{sessionId:t,source:s.source||"unknown",eventCount:(s.eventCount||r.totalEvents||0).toString(),duration:(s.duration||r.duration||0).toString(),model:s.model||r.model||"unknown",sessionStatus:s.status||r.status||"unknown"});let o=s.eventCount||r.totalEvents||0;o>0&&rs("SessionEventCount",o,{sessionId:t,source:s.source||"unknown"});let a=s.duration||r.duration||0;a>0&&rs("SessionDuration",a,{sessionId:t,source:s.source||"unknown"}),n.render("session-vue",{sessionId:t,events:[],metadata:r})}catch(t){console.error("Error loading session:",t),n.status(500).json({error:"Error loading session"})}}async getTimeAnalysis(e,n){try{let t=e.params.id;if(!oe(t))return n.status(400).json({error:"Invalid session ID"});let s=await this.sessionService.sessionRepository.findById(t);if(!s)return n.status(404).json({error:"Session not found"});let r=ns(s);J("TimeAnalysisViewed",{sessionId:t,turnCount:(r.totalEvents||0).toString()}),n.render("time-analyze",{sessionId:t,events:[],metadata:r})}catch(t){console.error("Error loading time analysis:",t),n.status(500).json({error:"Error loading analysis"})}}async getSessions(e,n){try{let t=e.query.page?parseInt(e.query.page):null,s=e.query.limit?parseInt(e.query.limit):null,r=e.query.source||null;if(t&&s){if(t<1||s<1||s>100)return n.status(400).json({error:"Invalid pagination parameters"});let o=await this.sessionService.getPaginatedSessions(t,s,r);J("SessionListLoaded",{page:t.toString(),limit:s.toString(),totalSessions:o.totalSessions.toString()}),n.set({"Cache-Control":"public, max-age=60"}),n.json(o)}else if(r&&s){let o=await this.sessionService.getAllSessions(r),a=o.slice(0,s);n.set({"Cache-Control":"public, max-age=60"}),n.json({sessions:a,hasMore:o.length>s,totalSessions:o.length})}else{let o=await this.sessionService.getAllSessions(r);n.set({"Cache-Control":"public, max-age=300"}),n.json(o)}}catch(t){console.error("Error loading sessions:",t),n.status(500).json({error:"Error loading sessions"})}}async loadMoreSessions(e,n){try{let t=parseInt(e.query.offset)||0,s=parseInt(e.query.limit)||20,r=e.query.source||null;if(t<0||s<1||s>50)return n.status(400).json({error:"Invalid parameters"});let o=Math.floor(t/s)+1,a=await this.sessionService.getPaginatedSessions(o,s,r);J("SessionListLoaded",{page:o.toString(),limit:s.toString(),totalSessions:a.totalSessions.toString()}),n.json({sessions:a.sessions,hasMore:a.hasNextPage,totalSessions:a.totalSessions})}catch(t){console.error("Error loading more sessions:",t),n.status(500).json({error:"Error loading more sessions"})}}async getSessionEvents(e,n){try{let t=e.params.id;if(!oe(t))return n.status(400).json({error:"Invalid session ID"});let s=e.query.limit!==void 0||e.query.offset!==void 0,r,o,a;if(s){if(r=parseInt(e.query.limit)||100,o=parseInt(e.query.offset)||0,r<1||r>1e3)return n.status(400).json({error:"Limit must be between 1 and 1000"});if(o<0)return n.status(400).json({error:"Offset must be non-negative"})}if(!await this.sessionService.sessionRepository.findById(t))return n.status(404).json({error:"Session not found"});s?a=await this.sessionService.getSessionEvents(t,{limit:r,offset:o}):a=await this.sessionService.getSessionEvents(t),n.set({"Cache-Control":"no-store",Vary:"Accept-Encoding"}),s?n.json({events:a.events,pagination:{total:a.total,limit:r,offset:o,hasMore:o+r<a.total}}):n.json(a)}catch(t){console.error("Error loading events:",t),n.status(500).json({error:"Error loading events"})}}async getTimeline(e,n){try{let t=e.params.id;if(!oe(t))return n.status(400).json({error:"Invalid session ID"});let s=await this.sessionService.getSessionById(t);if(!s)return n.status(404).json({error:"Session not found"});let r=await this.sessionService.getTimeline(t),o=require("crypto"),a=`${t}-timeline-${s.updatedAt||s.createdAt}`,i=o.createHash("md5").update(a).digest("hex");n.set({ETag:i,"Cache-Control":"private, max-age=300",Vary:"Accept-Encoding"}),n.json(r)}catch(t){console.error("Error loading timeline:",t),n.status(500).json({error:"Error loading timeline"})}}async exportSession(e,n){let t=e.params.id;if(!oe(t))return n.status(400).json({error:"Invalid session ID"});try{let s=await this.sessionService.sessionRepository.findById(t);if(!s)return n.status(404).json({error:"Session not found"});let r,o=!1;if(s.directory)try{(await q.promises.stat(s.directory)).isDirectory()&&(r=s.directory,o=!0)}catch{}if(!r&&s.filePath)try{await q.promises.access(s.filePath),r=s.filePath}catch{}if(!r){if(s.source==="copilot"){let l=this.sessionService.sessionRepository.sources.find(c=>c.type==="copilot");if(l){let c=G.join(l.dir,t);try{(await q.promises.stat(c)).isDirectory()?(r=c,o=!0):r=`${c}.jsonl`}catch{r=`${c}.jsonl`}}}else if(s.source==="claude"){let l=this.sessionService.sessionRepository.sources.find(c=>c.type==="claude");if(l){let c=await q.promises.readdir(G.join(l.dir,"projects"));for(let d of c){let p=G.join(l.dir,"projects",d,`${t}.jsonl`);try{await q.promises.access(p),r=p;break}catch{}}}}else if(s.source==="pi-mono"){let l=this.sessionService.sessionRepository.sources.find(c=>c.type==="pi-mono");if(l){let d=(await q.promises.readdir(l.dir)).find(p=>p.includes(t)&&p.endsWith(".jsonl"));d&&(r=G.join(l.dir,d))}}}if(!r)return n.status(404).json({error:"Session file not found"});try{await q.promises.access(r)}catch{return n.status(404).json({error:"Session file not accessible"})}let a=new Ln;if(o)a.addLocalFolder(r,t);else{let l=G.basename(r);a.addLocalFile(r,"",l);let c=Be(),p=new c().getSessionTagsFilePath(s);try{await q.promises.access(p),a.addLocalFile(p,"",G.basename(p))}catch{}}let i=a.toBuffer();n.setHeader("Content-Type","application/zip"),n.setHeader("Content-Disposition",`attachment; filename="session-${t}.zip"`),J("SessionExported",{sessionId:t}),n.send(i)}catch(s){console.error("Error exporting session:",s),n.status(500).json({error:"Error exporting session"})}}};os.exports=Ue});var ue=w((Fr,is)=>{var We=class{constructor(){this.activeProcesses=new Set,this.isShuttingDown=!1,this._setupCleanupHandlers()}register(e,n={}){let t={process:e,metadata:n,startTime:Date.now()};return this.activeProcesses.add(t),e.on("exit",()=>{this.activeProcesses.delete(t);let s=Date.now()-t.startTime;console.log(`\u{1F504} Process exited (${n.name||"unknown"}): ${s}ms`)}),t}killAll(){console.log(`\u{1F6D1} Killing ${this.activeProcesses.size} active processes...`);for(let{process:e,metadata:n}of this.activeProcesses)try{e.killed||(e.kill("SIGTERM"),console.log(` \u2713 Killed ${n.name||e.pid}`))}catch(t){console.error(` \u2717 Failed to kill ${n.name||e.pid}:`,t.message)}this.activeProcesses.clear()}getActiveCount(){return this.activeProcesses.size}_setupCleanupHandlers(){let e=(n,t=0)=>{this.isShuttingDown||(this.isShuttingDown=!0,console.log(`
26
- \u{1F4DB} Received ${n}, shutting down gracefully...`),this.killAll(),setTimeout(()=>{process.exit(t)},1e3))};process.on("SIGTERM",()=>e("SIGTERM",0)),process.on("SIGINT",()=>e("SIGINT",0)),process.on("uncaughtException",n=>{console.error("\u{1F4A5} Uncaught exception:",n),e("uncaughtException",1)})}};is.exports=new We});var ds=w((Lr,us)=>{var _=require("fs").promises,ls=require("fs"),C=require("path"),zn=require("os"),{spawn:Vn}=require("child_process"),cs=z(),Bn=ue(),He=class{constructor(){}_getToolConfig(e,n){let t={copilot:{name:"Copilot",cli:"copilot",args:(s,r)=>["--config-dir",s,"--yolo","-p",r],cwd:n},vscode:{name:"Copilot",cli:"copilot",args:(s,r)=>["--config-dir",s,"--yolo","-p",r],cwd:n},claude:{name:"Claude Code",cli:"claude",args:(s,r)=>["-p",r,"--dangerously-skip-permissions"],cwd:n},"pi-mono":{name:"Pi",cli:"pi",args:(s,r)=>["-p",r],cwd:n}};return t[e]||t.copilot}async generateInsight(e,n,t="copilot",s=!1){let r=C.join(n,`${e}.agent-review.md`),o=C.join(n,`${e}.agent-review.md.lock`),a=C.join(n,"events.jsonl");try{await _.access(a)}catch{try{a=C.join(n,`${e}.jsonl`),await _.access(a)}catch{let d=(await _.readdir(n)).find(p=>p.endsWith(`_${e}.jsonl`));d&&(a=C.join(n,d))}}let i=this._getToolConfig(t,n),l=i.name;if(!s)try{let c=await _.readFile(r,"utf-8"),d=await _.stat(r);return{status:"completed",report:c,generatedAt:d.mtime}}catch{}try{await _.writeFile(o,JSON.stringify({sessionId:e,startTime:new Date().toISOString(),pid:process.pid}),{flag:"wx"})}catch(c){if(c.code==="EEXIST")try{let d=JSON.parse(await _.readFile(o,"utf-8")),p=await _.stat(o),m=Date.now()-p.mtime.getTime();if(m<cs.INSIGHT_TIMEOUT_MS)return{status:"generating",report:`# Generating ${l} Insight...
19
+ ${r}`}else t.data.message="No files tracked"}break;case"progress":if(e.data){let n=[];if(e.data.hookName&&n.push(`Hook: ${e.data.hookName}`),e.data.hookEvent&&n.push(`Event: ${e.data.hookEvent}`),e.data.command&&n.push(`Command: ${e.data.command}`),n.length>0&&(t.data.message=n.join(`
20
+ `)),e.data.message?.message?.content&&Array.isArray(e.data.message.message.content)){let r=e.data.message.message.content.filter(a=>a&&typeof a=="object"&&(a.type==="tool_use"||a.type==="tool_result"));r.length>0&&(t.data.tools=r.map(a=>a.type==="tool_use"?{type:"tool_use",id:a.id,name:a.name,input:a.input}:{type:"tool_result",tool_use_id:a.tool_use_id,content:a.content}))}}break;case"hook.start":{let n=e.data||{};t.data.hookType=n.hookType||null,t.data.hookToolName=n.input?.toolName||null,t.data.hookArgs=n.input?.toolArgs||null,t.data.hookResult=n.input?.toolResult?.textResultForLlm||null;let r=[];n.hookType&&r.push(n.hookType),n.input?.toolName&&r.push(`\u2192 ${n.input.toolName}`),t.data.message=r.join(" ")||"hook",t.data.badgeLabel="HOOK",t.data.badgeClass="badge-hook";break}case"hook.end":{let n=e.data||{},r=[];n.hookType&&r.push(`**Hook:** ${n.hookType}`),r.push(n.success?"**Status:** \u2713 success":"**Status:** \u2717 failed"),n.error&&r.push(`**Error:** ${n.error}`),t.data.message=r.join(`
21
+ `),t.data.badgeLabel="HOOK END",t.data.badgeClass=n.success?"badge-hook":"badge-error";break}default:e.data?.message&&!t.data.message&&(t.data.message=e.data.message)}return this._generateBadgeInfo(t),t}_extractClaudeTextContent(e){if(typeof e=="string")return e;if(Array.isArray(e)){let s=[];for(let t of e)if(t.type==="text")s.push(t.text);else if(t.type==="tool_result"){if(typeof t.content=="string")s.push(t.content);else if(Array.isArray(t.content)){let n=t.content.filter(r=>r.type==="text").map(r=>r.text).join(`
22
+ `);n&&s.push(n)}}return s.join(`
23
+ `)}return""}_getClaudeUsageNumber(e){return typeof e=="number"&&Number.isFinite(e)?e:0}_getClaudeCacheWriteTokens(e){let s=this._getClaudeUsageNumber(e?.cache_creation_input_tokens);return s>0?s:!e?.cache_creation||typeof e.cache_creation!="object"?0:Object.values(e.cache_creation).reduce((t,n)=>t+this._getClaudeUsageNumber(n),0)}_getClaudeUsagePayload(e){return e?.usage&&typeof e.usage=="object"?e.usage:e?.toolUseResult?.usage&&typeof e.toolUseResult.usage=="object"?e.toolUseResult.usage:e?.message?.usage&&typeof e.message.usage=="object"?e.message.usage:e?.payload?.usage&&typeof e.payload.usage=="object"?e.payload.usage:null}_getClaudeEventTotalTokens(e){return this._getClaudeUsageNumber(e?.totalTokens)||this._getClaudeUsageNumber(e?.toolUseResult?.totalTokens)}_getClaudeEventDurationMs(e){return this._getClaudeUsageNumber(e?.totalDurationMs)||this._getClaudeUsageNumber(e?.toolUseResult?.totalDurationMs)}_getClaudeEventModel(e){return e?.model||e?.message?.model||e?._originalMessage?.model||e?.payload?.model||null}_resolveClaudeUsageModel(e,s){return this._getClaudeEventModel(e)||s.get(e?.sourceToolAssistantUUID)||s.get(e?.parentUuid)||s.get(e?.uuid)||"unknown"}_indexClaudeRelatedUsageEvents(e){let s=new Map;for(let t of e){if(!t?._isToolResultWrapper||!this._getClaudeUsagePayload(t)&&this._getClaudeEventTotalTokens(t)===0)continue;let n=new Set([t.sourceToolAssistantUUID,t.parentUuid].filter(r=>typeof r=="string"&&r.length>0));for(let r of n)s.has(r)||s.set(r,[]),s.get(r).push(t)}return s}_extractClaudeUsageData(e){let s={},t=new Map;for(let r of e){let a=this._getClaudeEventModel(r);a&&r?.uuid&&t.set(r.uuid,a)}let n=0;for(let r of e){let a=[r,...Array.isArray(r._relatedUsageEvents)?r._relatedUsageEvents:[]];for(let o of a){let i=this._getClaudeUsagePayload(o)||{},c=this._getClaudeUsageNumber(i.cache_read_input_tokens),l=this._getClaudeCacheWriteTokens(i),u=this._getClaudeUsageNumber(i.input_tokens),p=this._getClaudeUsageNumber(i.output_tokens),m=this._getClaudeEventTotalTokens(o),f=u;if(f===0&&p===0&&c===0&&l===0)if(m>0)f=Math.max(m-p,0);else continue;let g=this._resolveClaudeUsageModel(o,t);s[g]||(s[g]={requests:{count:0},usage:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0}}),s[g].requests.count+=1,s[g].usage.inputTokens+=f,s[g].usage.outputTokens+=p,s[g].usage.cacheReadTokens+=c,s[g].usage.cacheWriteTokens+=l,n+=this._getClaudeEventDurationMs(o)}}return Object.keys(s).length===0?null:{modelMetrics:s,totalPremiumRequests:0,totalApiDurationMs:n,codeChanges:{linesAdded:0,linesRemoved:0,filesModified:[]},currentTokens:0,systemTokens:0,conversationTokens:0,toolDefinitionsTokens:0}}extractUsageData(e){if(!Array.isArray(e)||e.length===0)return null;let s=e.find(t=>t.type==="session.shutdown");if(s&&s.data){let t=s.data,n=t.modelMetrics||{};for(let r of Object.keys(n)){let a=n[r]?.usage;if(a){let o=a.cacheReadTokens||0,i=a.cacheWriteTokens||0;(o>0||i>0)&&(a.inputTokens=Math.max((a.inputTokens||0)-o-i,0))}}return{modelMetrics:n,totalPremiumRequests:t.totalPremiumRequests||0,totalApiDurationMs:t.totalApiDurationMs||0,codeChanges:t.codeChanges||{linesAdded:0,linesRemoved:0,filesModified:[]},currentTokens:t.currentTokens||0,systemTokens:t.systemTokens||0,conversationTokens:t.conversationTokens||0,toolDefinitionsTokens:t.toolDefinitionsTokens||0}}return this._extractClaudeUsageData(e)}async getSessionWithEvents(e){let s=await this.getSessionById(e);if(!s)return null;let t=await this.getSessionEvents(e),n=Zn(s),r=t.find(o=>o.type==="session.start");r?.data?.selectedModel&&(n.model=r.data.selectedModel);let a=t.find(o=>o.type==="session.model_change");if(a?.data&&(n.model=a.data.newModel||a.data.model),t.length){let o=t[t.length-1];o?.timestamp&&(n.updated=o.timestamp)}if(t.length){let o=t[0];o?.timestamp&&(n.created=o.timestamp)}return n.usage=this.extractUsageData(t),{session:s,events:t,metadata:n}}async getTimeline(e){let s=await this.getSessionById(e);if(!s)return null;let t=await this.getSessionEvents(e),n=this._getSourceAdapter(s.source);if(n){let r=n.buildTimeline(t,s);if(r&&(r.turns?.length>0||Object.keys(r.summary||{}).length>0))return r}return s.source==="copilot"||s.source==="vscode"?this._buildCopilotTimeline(t,s):s.source==="claude"?this._buildClaudeTimeline(t,s):s.source==="pi-mono"?this._buildPiMonoTimeline(t,s):{turns:[],summary:{}}}_buildPiMonoTimeline(e,s){let t=[],n=0;for(let o=0;o<e.length;o++){let i=e[o];if(i.type==="user.message"){n++;let c={id:`turn-${n}`,type:"user-request",message:i.data.message||"",startTime:i.timestamp,endTime:i.timestamp,assistantTurns:[],subagents:[]},l=o+1,u=0;for(;l<e.length&&e[l].type!=="user.message";){let p=e[l];if(p.type==="assistant.message"){u++,c.endTime=p.timestamp;let m={id:`assistant-${u}`,startTime:p.timestamp,endTime:p.timestamp,tools:[]};if(p.data.tools&&Array.isArray(p.data.tools))for(let f of p.data.tools)m.tools.push({name:f.name,startTime:p.timestamp,endTime:p.timestamp,status:f.status||"completed",input:f.input,result:f.result});c.assistantTurns.push(m)}l++}t.push(c)}}let r=t.reduce((o,i)=>o+i.assistantTurns.reduce((c,l)=>c+l.tools.length,0),0),a={totalTurns:t.length,totalAssistantTurns:t.reduce((o,i)=>o+i.assistantTurns.length,0),totalTools:r,totalSubagents:0,startTime:e[0]?.timestamp,endTime:e[e.length-1]?.timestamp};return{turns:t,summary:a}}_buildCopilotTimeline(e,s){let t=[],n=null,r=0;for(let o of e)if(o.type==="assistant.turn_start")r++,n={id:`turn-${r}`,type:"assistant-turn",message:o.data.message||"",startTime:o.timestamp,endTime:null,tools:[],subagents:[]};else if(o.type==="assistant.turn_complete"&&n)n.endTime=o.timestamp,t.push(n),n=null;else if(o.type==="tool.execution_start"&&n){let i={name:o.data.tool||o.data.name,startTime:o.timestamp,endTime:null,status:"running",input:o.data.arguments||o.data.input};n.tools.push(i)}else if(o.type==="tool.execution_complete"&&n){let i=n.tools.find(c=>c.name===(o.data.tool||o.data.name)&&!c.endTime);i&&(i.endTime=o.timestamp,i.status=o.data?.error||o.data?.isError?"error":"completed",i.result=o.data?.result)}n&&(n.endTime=e[e.length-1]?.timestamp,t.push(n));let a={totalTurns:t.length,totalTools:t.reduce((o,i)=>o+i.tools.length,0),totalSubagents:0,startTime:e[0]?.timestamp,endTime:e[e.length-1]?.timestamp};return{turns:t,summary:a}}_buildClaudeTimeline(e,s){return this._buildPiMonoTimeline(e,s)}_expandPiMonoToCopilotFormat(e){let s=[],t=0,n=0;for(let r=0;r<e.length;r++){let a=e[r];if(a.type!=="user.message"&&a.type!=="assistant.message"){s.push(a);continue}if(a.type==="user.message"){t++,s.push({...a,_turnNumber:t});continue}if(a.type==="assistant.message"){let o=a.data.tools||[],i=a.timestamp,c=`pi-turn-${r}`;s.push({type:"assistant.turn_start",id:`${c}-start`,timestamp:i,parentId:a.parentId,data:{message:a.data.message||"",model:a.data.model,tools:o.length>0?o:void 0},_synthetic:!0,_turnNumber:t,_fileIndex:a._fileIndex}),s.push({...a,_fileIndex:a._fileIndex+.05}),o.forEach((l,u)=>{let p=`pi-tool-${n++}`,m=i,f=i;s.push({type:"tool.execution_start",id:`${p}-start`,timestamp:m,parentId:c,data:{toolCallId:p,toolName:l.name,tool:l.name,arguments:l.input||{}},_synthetic:!0,_fileIndex:a._fileIndex+.1+u*.01}),s.push({type:"tool.execution_complete",id:`${p}-complete`,timestamp:f,parentId:p,data:{toolCallId:p,toolName:l.name,tool:l.name,result:l.result,error:l.status==="error"?"Tool execution failed":null,isError:l.status==="error"},_synthetic:!0,_fileIndex:a._fileIndex+.15+u*.01})}),s.push({type:"assistant.turn_complete",id:`${c}-complete`,timestamp:a.timestamp,parentId:c,data:{message:a.data.message||""},_synthetic:!0,_turnNumber:t,_fileIndex:a._fileIndex+.9})}}return s}_expandVsCodeEvents(e){let s=[],t=[],n=null,r=null,a=0,o=null,i=null,c=()=>{t.length!==0&&(s.push({type:"assistant.message",id:`vscode-tools-${a}`,timestamp:r,parentId:n,data:{message:"",content:"",tools:t,subAgentId:o,subAgentName:i},_synthetic:!0}),t=[],o=null,i=null)};for(let l=0;l<e.length;l++){let u=e[l];if(u.type==="tool.invocation"){let p=u.data?.subAgentId||null;t.length>0&&p!==o&&c(),t.length===0&&(n=u.parentId,r=u.timestamp,a=l,o=p,i=u.data?.subAgentName||null),u.data?.tool&&t.push(u.data.tool)}else c(),s.push(u)}return c(),s}_expandCopilotToTimelineFormat(e){let s=[],t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r.type==="user"){t++,s.push({...r,type:"user.message",_turnNumber:t,data:{...r.data,message:r.message?.content||r.data?.message||""}});continue}if(r.type==="assistant"){let a=r.uuid||`copilot-assistant-${n}`,o=r.timestamp,i="";r.message?.content?Array.isArray(r.message.content)?i=r.message.content.filter(c=>c&&c.type==="text").map(c=>c.text).join(`
24
+ `):typeof r.message.content=="string"&&(i=r.message.content):r.data?.message&&(i=r.data.message),s.push({type:"assistant.turn_start",id:`${a}-start`,uuid:r.uuid,timestamp:o,parentId:r.parentId,data:{message:i,turnId:a},_synthetic:!0,_turnNumber:t,_fileIndex:r._fileIndex}),s.push({type:"assistant.message",id:a,uuid:r.uuid,timestamp:o,parentId:r.parentId,data:{message:i,tools:r.data?.tools||[]},_synthetic:!0,_turnNumber:t,_fileIndex:r._fileIndex+.05}),r.data?.tools&&r.data.tools.length>0&&r.data.tools.forEach((c,l)=>{c.start&&s.push({...c.start,_fileIndex:r._fileIndex+.1+l*.02}),c.complete&&s.push({...c.complete,_fileIndex:r._fileIndex+.15+l*.02})}),s.push({type:"assistant.turn_complete",id:`${a}-complete`,uuid:r.uuid,timestamp:o,parentId:a,data:{message:i},_synthetic:!0,_turnNumber:t,_fileIndex:r._fileIndex+.9});continue}if(r.type==="user.message"){t++,s.push({...r,_turnNumber:t,data:{...r.data,message:r.data?.content||r.data?.message||""}});continue}s.push({...r,_turnNumber:t})}return s}_synthesizeSubagentBoundaryEvents(e){if(e.some(r=>r.type==="subagent.started"))return e;let s=new Map;for(let r of e)r.type==="tool.execution_start"&&r.data?.toolName==="runSubagent"&&s.set(r.data.toolCallId,r);if(s.size===0)return e;let t=[];for(let r of e)if(r.type==="tool.execution_start"&&s.has(r.data?.toolCallId)){let a=r.data.toolCallId,o=r.data.arguments;if(typeof o=="string")try{o=JSON.parse(o)}catch{o={}}o=o||{};let i=o.description||o.agentName||o.name||"SubAgent";t.push({type:"subagent.started",id:`${a}-synth-start`,timestamp:r.timestamp,data:{toolCallId:a,agentName:i,agentDisplayName:i,agentDescription:o.description||""},_synthetic:!0,_fileIndex:(r._fileIndex||0)-.001})}else if(r.type==="tool.execution_complete"&&s.has(r.data?.toolCallId)){let a=r.data.toolCallId;t.push({type:"subagent.completed",id:`${a}-synth-end`,timestamp:r.timestamp,data:{toolCallId:a,result:"Sub-agent completed"},_synthetic:!0,_fileIndex:(r._fileIndex||0)+.001})}if(t.length===0)return e;let n=e.concat(t);return n.sort((r,a)=>{let o=new Date(r.timestamp||0).getTime(),i=new Date(a.timestamp||0).getTime();return o!==i?o-i:(r._fileIndex||0)-(a._fileIndex||0)}),n}_expandClaudeToTimelineFormat(e){let s=[],t=0,n=this._indexClaudeRelatedUsageEvents(e);for(let r=0;r<e.length;r++){let a=e[r];if(a.type==="user"){if(a._isToolResultWrapper)continue;t++,s.push({...a,type:"user.message",_turnNumber:t,data:{...a.data,message:a.data?.message||""}});continue}if(a.type==="assistant"){let o=a.id||`claude-assistant-${r}`,i=a.timestamp,c=a.uuid?n.get(a.uuid)||[]:[],l=a.data?.message||"";s.push({type:"assistant.turn_start",id:`${o}-start`,uuid:a.uuid,timestamp:i,parentId:a.parentId,data:{message:l,turnId:o},_synthetic:!0,_turnNumber:t,_fileIndex:a._fileIndex}),s.push({type:"assistant.message",id:o,uuid:a.uuid,timestamp:i,parentId:a.parentId,model:a.model,usage:a.usage,data:{message:l,tools:a.data?.tools||[]},_synthetic:!0,_turnNumber:t,_fileIndex:a._fileIndex+.05}),a.data?.tools&&a.data.tools.length>0&&a.data.tools.forEach((u,p)=>{u.type==="tool_use"&&(s.push({type:"tool.execution_start",id:`${u.id}-start`,timestamp:i,data:{toolCallId:u.id,toolName:u.name,arguments:u.input||{}},_synthetic:!0,_fileIndex:a._fileIndex+.1+p*.02}),u.result&&s.push({type:"tool.execution_complete",id:`${u.id}-complete`,timestamp:i,data:{toolCallId:u.id,toolName:u.name,result:u.result,isError:!1},_synthetic:!0,_fileIndex:a._fileIndex+.15+p*.02}))}),s.push({type:"assistant.turn_complete",id:`${o}-complete`,uuid:a.uuid,timestamp:i,parentId:o,model:a.model,_relatedUsageEvents:c.map(u=>({uuid:u.uuid,parentUuid:u.parentUuid,sourceToolAssistantUUID:u.sourceToolAssistantUUID,usage:this._getClaudeUsagePayload(u),totalTokens:this._getClaudeEventTotalTokens(u),totalDurationMs:this._getClaudeEventDurationMs(u)})),data:{message:l},_synthetic:!0,_turnNumber:t,_fileIndex:a._fileIndex+.9});continue}s.push(a)}return s}_expandVsCodeToTimelineFormat(e){let s=[];for(let t=0;t<e.length;t++){let n=e[t];s.push(n),n.type==="assistant.message"&&n.data?.tools&&n.data.tools.length>0&&n.data.tools.forEach((r,a)=>{if(!r.id||!r.name)return;let o=r.startTime||n.timestamp,i=r.endTime||n.timestamp;s.push({type:"tool.execution_start",id:`${r.id}-start`,timestamp:o,parentId:n.id,data:{toolCallId:r.id,toolName:r.name,tool:r.name,arguments:r.input||{}},_synthetic:!0,_fileIndex:n._fileIndex?n._fileIndex+.1+a*.02:void 0}),s.push({type:"tool.execution_complete",id:`${r.id}-complete`,timestamp:i,parentId:r.id,data:{toolCallId:r.id,toolName:r.name,tool:r.name,result:r.result||null,error:r.error||(r.status==="error"?"Tool execution failed":null),isError:r.status==="error"},_synthetic:!0,_fileIndex:n._fileIndex?n._fileIndex+.15+a*.02:void 0})})}return s}_getSourceAdapter(e){let s=this.sessionRepository.registry||ee().registry;return s?.get?s.get(e):null}};is.exports=Ve});var He=y((ea,cs)=>{var R=require("fs").promises,F=require("path"),er=require("os"),We=class{constructor(){this.knownTagsDir=F.join(er.homedir(),".session-viewer"),this.knownTagsFilePath=F.join(this.knownTagsDir,"known-tags.json")}async ensureKnownTagsFile(){try{await R.access(this.knownTagsFilePath)}catch{await R.mkdir(this.knownTagsDir,{recursive:!0}),await R.writeFile(this.knownTagsFilePath,JSON.stringify([]),"utf8")}}async readKnownTagsFile(){await this.ensureKnownTagsFile();try{let e=await R.readFile(this.knownTagsFilePath,"utf8");return JSON.parse(e)}catch(e){return console.error("Error reading known tags file:",e),[]}}async writeKnownTagsFile(e){await this.ensureKnownTagsFile(),await R.writeFile(this.knownTagsFilePath,JSON.stringify(e,null,2),"utf8")}getSessionTagsFilePath(e){if(e.filePath){let s=F.dirname(e.filePath),t=F.basename(e.filePath,F.extname(e.filePath));return F.join(s,`${t}.tags.json`)}return e.directory?F.join(e.directory,"tags.json"):F.join(this.knownTagsDir,"session-tags",`${e.id}.tags.json`)}normalizeTag(e){return e.trim().toLowerCase().substring(0,30)}async getAllKnownTags(){return(await this.readKnownTagsFile()).sort()}async getSessionTags(e){let s=this.getSessionTagsFilePath(e);try{await R.access(s);let t=await R.readFile(s,"utf8");return JSON.parse(t)}catch{return[]}}async setSessionTags(e,s){if(!Array.isArray(s))throw new Error("Tags must be an array");let t=s.map(r=>this.normalizeTag(r)).filter(r=>r.length>0).filter((r,a,o)=>o.indexOf(r)===a);if(t.length>10)throw new Error("Maximum 10 tags per session");let n=this.getSessionTagsFilePath(e);if(t.length===0)try{await R.unlink(n)}catch{}else await R.mkdir(F.dirname(n),{recursive:!0}),await R.writeFile(n,JSON.stringify(t,null,2),"utf8"),await this.updateKnownTags(t);return t}async updateKnownTags(e){let t=[...await this.readKnownTagsFile(),...e],n=[...new Set(t)];await this.writeKnownTagsFile(n)}async addSessionTags(e,s){let n=[...await this.getSessionTags(e),...s];return await this.setSessionTags(e,n)}async removeSessionTags(e,s){let t=await this.getSessionTags(e),n=s.map(a=>this.normalizeTag(a)),r=t.filter(a=>!n.includes(a));return await this.setSessionTags(e,r)}async getMultipleSessionTags(e){let s={};for(let t of e)s[t.id]=await this.getSessionTags(t);return s}};cs.exports=We});var ps=y((ta,ds)=>{var tr=Be(),{isValidSessionId:re,buildMetadata:ls}=q(),{trackEvent:G,trackMetric:us}=L(),sr=require("adm-zip"),K=require("path"),U=require("fs"),Je=class{constructor(e=null){this.sessionService=e||new tr}async getHomepage(e,s){try{let t=await this.sessionService.getPaginatedSessions(1,20,"copilot"),n={};if(this.sessionService.sessionRepository&&this.sessionService.sessionRepository.sources)for(let a of this.sessionService.sessionRepository.sources)n[a.type]=a.dir;let r={sessions:t.sessions,hasMore:t.hasNextPage,totalSessions:t.totalSessions,sourceHints:JSON.stringify(n)};G("HomepageViewed",{sessionCount:t.totalSessions.toString(),sourceFilter:"copilot"}),s.render("index",r)}catch(t){console.error("Error loading sessions:",t),s.status(500).send("Error loading sessions")}}async getSessionDetail(e,s){try{let t=e.params.id;if(!re(t))return s.status(400).json({error:"Invalid session ID"});let n=await this.sessionService.sessionRepository.findById(t);if(!n)return s.status(404).json({error:"Session not found"});let r=ls(n);try{let i=await this.sessionService.getSessionEvents(t),c=this.sessionService.extractUsageData(i);c&&(r.usage=c)}catch(i){console.error("Error extracting usage data:",i)}G("SessionViewed",{sessionId:t,source:n.source||"unknown",eventCount:(n.eventCount||r.totalEvents||0).toString(),duration:(n.duration||r.duration||0).toString(),model:n.model||r.model||"unknown",sessionStatus:n.status||r.status||"unknown"});let a=n.eventCount||r.totalEvents||0;a>0&&us("SessionEventCount",a,{sessionId:t,source:n.source||"unknown"});let o=n.duration||r.duration||0;o>0&&us("SessionDuration",o,{sessionId:t,source:n.source||"unknown"}),s.render("session-vue",{sessionId:t,events:[],metadata:r})}catch(t){console.error("Error loading session:",t),s.status(500).json({error:"Error loading session"})}}async getTimeAnalysis(e,s){try{let t=e.params.id;if(!re(t))return s.status(400).json({error:"Invalid session ID"});let n=await this.sessionService.sessionRepository.findById(t);if(!n)return s.status(404).json({error:"Session not found"});let r=ls(n);try{let a=await this.sessionService.getSessionEvents(t),o=this.sessionService.extractUsageData(a);o&&(r.usage=o)}catch(a){console.error("Error extracting usage data for time analysis:",a)}G("TimeAnalysisViewed",{sessionId:t,turnCount:(r.totalEvents||0).toString()}),s.render("time-analyze",{sessionId:t,events:[],metadata:r})}catch(t){console.error("Error loading time analysis:",t),s.status(500).json({error:"Error loading analysis"})}}async getSessions(e,s){try{let t=e.query.page?parseInt(e.query.page):null,n=e.query.limit?parseInt(e.query.limit):null,r=e.query.source||null;if(t&&n){if(t<1||n<1||n>100)return s.status(400).json({error:"Invalid pagination parameters"});let a=await this.sessionService.getPaginatedSessions(t,n,r);G("SessionListLoaded",{page:t.toString(),limit:n.toString(),totalSessions:a.totalSessions.toString()}),s.set({"Cache-Control":"public, max-age=60"}),s.json(a)}else if(r&&n){let a=await this.sessionService.getAllSessions(r),o=a.slice(0,n);s.set({"Cache-Control":"public, max-age=60"}),s.json({sessions:o,hasMore:a.length>n,totalSessions:a.length})}else{let a=await this.sessionService.getAllSessions(r);s.set({"Cache-Control":"public, max-age=300"}),s.json(a)}}catch(t){console.error("Error loading sessions:",t),s.status(500).json({error:"Error loading sessions"})}}async loadMoreSessions(e,s){try{let t=parseInt(e.query.offset)||0,n=parseInt(e.query.limit)||20,r=e.query.source||null;if(t<0||n<1||n>50)return s.status(400).json({error:"Invalid parameters"});let a=Math.floor(t/n)+1,o=await this.sessionService.getPaginatedSessions(a,n,r);G("SessionListLoaded",{page:a.toString(),limit:n.toString(),totalSessions:o.totalSessions.toString()}),s.json({sessions:o.sessions,hasMore:o.hasNextPage,totalSessions:o.totalSessions})}catch(t){console.error("Error loading more sessions:",t),s.status(500).json({error:"Error loading more sessions"})}}async getSessionEvents(e,s){try{let t=e.params.id;if(!re(t))return s.status(400).json({error:"Invalid session ID"});let n=e.query.limit!==void 0||e.query.offset!==void 0,r,a,o;if(n){if(r=parseInt(e.query.limit)||100,a=parseInt(e.query.offset)||0,r<1||r>1e3)return s.status(400).json({error:"Limit must be between 1 and 1000"});if(a<0)return s.status(400).json({error:"Offset must be non-negative"})}if(!await this.sessionService.sessionRepository.findById(t))return s.status(404).json({error:"Session not found"});n?o=await this.sessionService.getSessionEvents(t,{limit:r,offset:a}):o=await this.sessionService.getSessionEvents(t),s.set({"Cache-Control":"no-store",Vary:"Accept-Encoding"}),n?s.json({events:o.events,pagination:{total:o.total,limit:r,offset:a,hasMore:a+r<o.total}}):s.json(o)}catch(t){console.error("Error loading events:",t),s.status(500).json({error:"Error loading events"})}}async getTimeline(e,s){try{let t=e.params.id;if(!re(t))return s.status(400).json({error:"Invalid session ID"});let n=await this.sessionService.getSessionById(t);if(!n)return s.status(404).json({error:"Session not found"});let r=await this.sessionService.getTimeline(t),a=require("crypto"),o=`${t}-timeline-${n.updatedAt||n.createdAt}`,i=a.createHash("md5").update(o).digest("hex");s.set({ETag:i,"Cache-Control":"private, max-age=300",Vary:"Accept-Encoding"}),s.json(r)}catch(t){console.error("Error loading timeline:",t),s.status(500).json({error:"Error loading timeline"})}}async exportSession(e,s){let t=e.params.id;if(!re(t))return s.status(400).json({error:"Invalid session ID"});try{let n=await this.sessionService.sessionRepository.findById(t);if(!n)return s.status(404).json({error:"Session not found"});let r,a=!1;if(n.directory)try{(await U.promises.stat(n.directory)).isDirectory()&&(r=n.directory,a=!0)}catch{}if(!r&&n.filePath)try{await U.promises.access(n.filePath),r=n.filePath}catch{}if(!r){if(n.source==="copilot"){let c=this.sessionService.sessionRepository.sources.find(l=>l.type==="copilot");if(c){let l=K.join(c.dir,t);try{(await U.promises.stat(l)).isDirectory()?(r=l,a=!0):r=`${l}.jsonl`}catch{r=`${l}.jsonl`}}}else if(n.source==="claude"){let c=this.sessionService.sessionRepository.sources.find(l=>l.type==="claude");if(c){let l=await U.promises.readdir(K.join(c.dir,"projects"));for(let u of l){let p=K.join(c.dir,"projects",u,`${t}.jsonl`);try{await U.promises.access(p),r=p;break}catch{}}}}else if(n.source==="pi-mono"){let c=this.sessionService.sessionRepository.sources.find(l=>l.type==="pi-mono");if(c){let u=(await U.promises.readdir(c.dir)).find(p=>p.includes(t)&&p.endsWith(".jsonl"));u&&(r=K.join(c.dir,u))}}}if(!r)return s.status(404).json({error:"Session file not found"});try{await U.promises.access(r)}catch{return s.status(404).json({error:"Session file not accessible"})}let o=new sr;if(a)o.addLocalFolder(r,t);else{let c=K.basename(r);o.addLocalFile(r,"",c);let l=He(),p=new l().getSessionTagsFilePath(n);try{await U.promises.access(p),o.addLocalFile(p,"",K.basename(p))}catch{}}let i=o.toBuffer();s.setHeader("Content-Type","application/zip"),s.setHeader("Content-Disposition",`attachment; filename="session-${t}.zip"`),G("SessionExported",{sessionId:t}),s.send(i)}catch(n){console.error("Error exporting session:",n),s.status(500).json({error:"Error exporting session"})}}};ds.exports=Je});var pe=y((sa,ms)=>{var Ge=class{constructor(){this.activeProcesses=new Set,this.isShuttingDown=!1,this._setupCleanupHandlers()}register(e,s={}){let t={process:e,metadata:s,startTime:Date.now()};return this.activeProcesses.add(t),e.on("exit",()=>{this.activeProcesses.delete(t);let n=Date.now()-t.startTime;console.log(`\u{1F504} Process exited (${s.name||"unknown"}): ${n}ms`)}),t}killAll(){console.log(`\u{1F6D1} Killing ${this.activeProcesses.size} active processes...`);for(let{process:e,metadata:s}of this.activeProcesses)try{e.killed||(e.kill("SIGTERM"),console.log(` \u2713 Killed ${s.name||e.pid}`))}catch(t){console.error(` \u2717 Failed to kill ${s.name||e.pid}:`,t.message)}this.activeProcesses.clear()}getActiveCount(){return this.activeProcesses.size}_setupCleanupHandlers(){let e=(s,t=0)=>{this.isShuttingDown||(this.isShuttingDown=!0,console.log(`
25
+ \u{1F4DB} Received ${s}, shutting down gracefully...`),this.killAll(),setTimeout(()=>{process.exit(t)},1e3))};process.on("SIGTERM",()=>e("SIGTERM",0)),process.on("SIGINT",()=>e("SIGINT",0)),process.on("uncaughtException",s=>{console.error("\u{1F4A5} Uncaught exception:",s),e("uncaughtException",1)})}},Ke="__copilotSessionViewerProcessManager";globalThis[Ke]||(globalThis[Ke]=new Ge);ms.exports=globalThis[Ke]});var ys=y((na,hs)=>{var S=require("fs").promises,fs=require("fs"),x=require("path"),nr=require("os"),{spawn:rr}=require("child_process"),gs=z(),ar=pe(),Xe=class{constructor(){}_getToolConfig(e,s){let t={copilot:{name:"Copilot",cli:"copilot",args:(n,r)=>["--config-dir",n,"--yolo","-p",r],cwd:s},vscode:{name:"Copilot",cli:"copilot",args:(n,r)=>["--config-dir",n,"--yolo","-p",r],cwd:s},claude:{name:"Claude Code",cli:"claude",args:(n,r)=>["-p",r,"--dangerously-skip-permissions"],cwd:s},"pi-mono":{name:"Pi",cli:"pi",args:(n,r)=>["-p",r],cwd:s}};return t[e]||t.copilot}async generateInsight(e,s,t="copilot",n=!1){let r=x.join(s,`${e}.agent-review.md`),a=x.join(s,`${e}.agent-review.md.lock`),o=x.join(s,"events.jsonl");try{await S.access(o)}catch{try{o=x.join(s,`${e}.jsonl`),await S.access(o)}catch{let u=(await S.readdir(s)).find(p=>p.endsWith(`_${e}.jsonl`));u&&(o=x.join(s,u))}}let i=this._getToolConfig(t,s),c=i.name;if(!n)try{let l=await S.readFile(r,"utf-8"),u=await S.stat(r);return{status:"completed",report:l,generatedAt:u.mtime}}catch{}try{await S.writeFile(a,JSON.stringify({sessionId:e,startTime:new Date().toISOString(),pid:process.pid}),{flag:"wx"})}catch(l){if(l.code==="EEXIST")try{let u=JSON.parse(await S.readFile(a,"utf-8")),p=await S.stat(a),m=Date.now()-p.mtime.getTime();if(m<gs.INSIGHT_TIMEOUT_MS)return{status:"generating",report:`# Generating ${c} Insight...
27
26
 
28
- Another request is currently generating this insight. Please wait.`,startedAt:p.birthtime,lastUpdate:p.mtime,ageMs:Date.now()-p.birthtime.getTime()};console.log(`\u26A0\uFE0F Removing stale lock file (${Math.floor(m/1e3)}s old)`),await _.unlink(o),await _.writeFile(o,JSON.stringify({sessionId:e,startTime:new Date().toISOString(),pid:process.pid}),{flag:"wx"})}catch(d){throw new Error("Failed to acquire lock for insight generation",{cause:d})}else throw c}try{await _.access(a)}catch(c){throw await _.unlink(o),new Error("Events file not found",{cause:c})}if(s)try{await _.unlink(r)}catch{}return await this._spawnAnalysisProcess(n,a,r,o,i),{status:"generating",report:`# Generating ${l} Insight...
27
+ Another request is currently generating this insight. Please wait.`,startedAt:p.birthtime,lastUpdate:p.mtime,ageMs:Date.now()-p.birthtime.getTime()};console.log(`\u26A0\uFE0F Removing stale lock file (${Math.floor(m/1e3)}s old)`),await S.unlink(a),await S.writeFile(a,JSON.stringify({sessionId:e,startTime:new Date().toISOString(),pid:process.pid}),{flag:"wx"})}catch(u){throw new Error("Failed to acquire lock for insight generation",{cause:u})}else throw l}try{await S.access(o)}catch(l){throw await S.unlink(a),new Error("Events file not found",{cause:l})}if(n)try{await S.unlink(r)}catch{}return await this._spawnAnalysisProcess(s,o,r,a,i),{status:"generating",report:`# Generating ${c} Insight...
29
28
 
30
- Analysis in progress. Please wait.`,startedAt:new Date}}async _spawnAnalysisProcess(e,n,t,s,r){let o=C.basename(e),a=C.join(zn.tmpdir(),`agent-review-${o}-${Date.now()}`);await _.mkdir(a,{recursive:!0});let i=this._buildPrompt(t,n),l=C.join(e,`${o}.agent-review.md.tmp`),c=r.cli,d=r.args(a,i);console.log(`\u{1F916} Starting ${r.name} analysis: ${c} ${d.slice(0,2).join(" ")}...`),console.log(`\u{1F4CB} Args count: ${d.length}, prompt length: ${i.length} chars`);let p=Vn(c,d,{env:{...process.env},cwd:e,stdio:["pipe","pipe","pipe"]});if(Bn.register(p,{name:`insight-${o}`}),r.cli==="copilot"){let S=ls.createReadStream(n);p.stdin.on("error",T=>{T.code==="EPIPE"?S.destroy():console.error("\u274C stdin error:",T)}),S.pipe(p.stdin)}else p.stdin.end();let m=ls.createWriteStream(l);p.stdout.pipe(m);let g=[],f=0,y=64*1024;p.stderr.on("data",S=>{f<y&&(g.push(S),f+=S.length)}),p.on("close",async S=>{try{m.end();let T=Buffer.concat(g).toString("utf-8").slice(0,y);if(console.log(`\u{1F4CB} ${r.name} process exited with code ${S}`),T&&console.log(`\u{1F4CB} ${r.name} stderr:`,T.substring(0,500)),S!==0)console.error(`\u274C ${r.name} CLI failed (code ${S}):`,T),await _.writeFile(t,`# \u274C Generation Failed
29
+ Analysis in progress. Please wait.`,startedAt:new Date}}async _spawnAnalysisProcess(e,s,t,n,r){let a=x.basename(e),o=x.join(nr.tmpdir(),`agent-review-${a}-${Date.now()}`);await S.mkdir(o,{recursive:!0});let i=this._buildPrompt(t,s),c=x.join(e,`${a}.agent-review.md.tmp`),l=r.cli,u=r.args(o,i);console.log(`\u{1F916} Starting ${r.name} analysis: ${l} ${u.slice(0,2).join(" ")}...`),console.log(`\u{1F4CB} Args count: ${u.length}, prompt length: ${i.length} chars`);let p=rr(l,u,{env:{...process.env},cwd:e,stdio:["pipe","pipe","pipe"]});if(ar.register(p,{name:`insight-${a}`}),r.cli==="copilot"){let w=fs.createReadStream(s);p.stdin.on("error",D=>{D.code==="EPIPE"?w.destroy():console.error("\u274C stdin error:",D)}),w.pipe(p.stdin)}else p.stdin.end();let m=fs.createWriteStream(c);p.stdout.pipe(m);let f=[],g=0,h=64*1024;p.stderr.on("data",w=>{g<h&&(f.push(w),g+=w.length)}),p.on("close",async w=>{try{m.end();let D=Buffer.concat(f).toString("utf-8").slice(0,h);if(console.log(`\u{1F4CB} ${r.name} process exited with code ${w}`),D&&console.log(`\u{1F4CB} ${r.name} stderr:`,D.substring(0,500)),w!==0)console.error(`\u274C ${r.name} CLI failed (code ${w}):`,D),await S.writeFile(t,`# \u274C Generation Failed
31
30
 
32
- Exit code: ${S}
31
+ Exit code: ${w}
33
32
 
34
33
  \`\`\`
35
- ${T||"(no error output)"}
34
+ ${D||"(no error output)"}
36
35
  \`\`\`
37
- `,"utf-8");else{let v=!1;try{let j=await _.readFile(t,"utf-8");j&&j.trim().length>50&&(v=!0,console.log(`\u2705 Insight generated for session ${o} (agent wrote directly)`))}catch{}if(!v){let j=await _.readFile(l,"utf-8");j=this._cleanReport(j),await _.writeFile(t,j,"utf-8"),console.log(`\u2705 Insight generated for session ${o} (cleaned from stdout)`)}}await _.unlink(l).catch(()=>{}),await _.unlink(s).catch(()=>{}),await _.rm(a,{recursive:!0,force:!0}).catch(()=>{}),await _.rm(C.join(e,".output"),{recursive:!0,force:!0}).catch(()=>{})}catch(T){console.error("\u274C Error finalizing insight:",T),await _.unlink(s).catch(()=>{}),await _.rm(a,{recursive:!0,force:!0}).catch(()=>{})}}),p.on("error",async S=>{console.error(`\u274C Failed to spawn ${r.name}:`,S),await _.unlink(s).catch(()=>{}),await _.rm(a,{recursive:!0,force:!0}).catch(()=>{})})}_buildPrompt(e,n){let t=C.dirname(e),s=C.basename(n),r=`${t}/.output`;return`You are an expert AI agent evaluator. The current working directory is an AI coding agent session folder. It contains the raw session data from an agent run.
38
- ${s.includes("_")?`
39
- **IMPORTANT**: This directory may contain multiple .jsonl files. You MUST analyze ONLY the file named \`${s}\`. Do NOT read or analyze any other .jsonl files in this directory.
36
+ `,"utf-8");else{let N=!1;try{let O=await S.readFile(t,"utf-8");O&&O.trim().length>50&&(N=!0,console.log(`\u2705 Insight generated for session ${a} (agent wrote directly)`))}catch{}if(!N){let O=await S.readFile(c,"utf-8");O=this._cleanReport(O),await S.writeFile(t,O,"utf-8"),console.log(`\u2705 Insight generated for session ${a} (cleaned from stdout)`)}}await S.unlink(c).catch(()=>{}),await S.unlink(n).catch(()=>{}),await S.rm(o,{recursive:!0,force:!0}).catch(()=>{}),await S.rm(x.join(e,".output"),{recursive:!0,force:!0}).catch(()=>{})}catch(D){console.error("\u274C Error finalizing insight:",D),await S.unlink(n).catch(()=>{}),await S.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}),p.on("error",async w=>{console.error(`\u274C Failed to spawn ${r.name}:`,w),await S.unlink(n).catch(()=>{}),await S.rm(o,{recursive:!0,force:!0}).catch(()=>{})})}_buildPrompt(e,s){let t=x.dirname(e),n=x.basename(s),r=`${t}/.output`;return`You are an expert AI agent prompt-compliance auditor. The current working directory is an AI coding agent session folder containing raw session data from an agent run.
37
+ ${n.includes("_")?`
38
+ **IMPORTANT**: This directory may contain multiple .jsonl files. You MUST analyze ONLY the file named \`${n}\`. Do NOT read or analyze any other .jsonl files in this directory.
40
39
  `:""}
41
- **Step 1 \u2014 Discover session files.** Run \`ls -la\` to see what's available, then note which files exist:
42
- - \`${s}\` \u2014 the main session event log (JSONL, one JSON event per line). Primary data source. May be large. **This is the ONLY events file you should analyze.**
40
+ **Step 1 \u2014 Discover session files.** Run \`ls -la\` to see what's available:
41
+ - \`${n}\` \u2014 the main session event log (JSONL, one JSON event per line). **This is the ONLY events file you should analyze.**
43
42
  - \`plan.md\` \u2014 the agent's plan (if it exists).
44
43
  - \`workspace.yaml\` \u2014 workspace configuration (if it exists).
45
- - Any other relevant files.
46
44
 
47
- **Step 2 \u2014 Spawn 3 sub-agents for parallel analysis.** First create the working directory: \`mkdir -p ${r}\`. Then use the Task tool to launch ALL of the following sub-agents simultaneously (in a single message with multiple Task tool calls). Each sub-agent should:
48
- - Read \`${s}\` from \`${t}\` (use Bash: \`cat\`, \`jq\`, or \`python3\` to parse) **\u2014 ONLY this file, ignore others**
49
- - Read other session files as needed
50
- - Write its findings to an intermediate file in \`${r}/\`
51
- - Return a summary of its findings
45
+ **Step 2 \u2014 Extract prompts and execution trace.** Parse \`${n}\` to extract:
46
+ - The **system prompt** (the agent's instructions/rules/constraints)
47
+ - The **user prompt** (what the user actually asked for)
48
+ - The **execution trace** \u2014 what the agent actually did (tool calls, decisions, outputs)
49
+ - All **build/test/compile** operations and their exit codes, stdout/stderr
50
+
51
+ **Step 3 \u2014 Spawn 3 sub-agents for parallel analysis.** First create the working directory: \`mkdir -p ${r}\`. Then use the Task tool to launch ALL of the following sub-agents simultaneously. Each sub-agent should read \`${n}\` from \`${t}\` (use Bash: \`cat\`, \`jq\`, or \`python3\` to parse) **\u2014 ONLY this file, ignore others**.
52
52
 
53
53
  Sub-agents to spawn:
54
54
 
55
- 1. **Tool Usage Analyst** \u2014 Analyze tool selection quality, redundant/wasted calls, error handling patterns, tool call counts and durations. Write findings to \`${r}/tools.md\`.
55
+ 1. **Prompt Compliance Analyst** \u2014 Extract the system prompt rules/constraints and check each against the execution trace. For each rule: was it followed, partially followed, or violated? Identify instructions the agent ignored and actions the agent took that weren't requested. Write findings to \`${r}/compliance.md\`.
56
56
 
57
- 2. **Workflow Strategist** \u2014 Evaluate planning quality, sequencing logic, sub-agent decomposition, backtracking/wandering patterns. Write findings to \`${r}/workflow.md\`.
57
+ 2. **Task Completion Analyst** \u2014 Compare the user's ask against the agent's final output/artifacts. Did the agent deliver what was asked? Did it go off-track, do extra unrequested work, or miss requirements? Evaluate the logical coherence of the agent's plan-to-execution flow. Write findings to \`${r}/task.md\`.
58
58
 
59
- 3. **Performance Profiler** \u2014 Calculate time distribution (LLM thinking vs tool execution vs idle gaps), identify bottlenecks, assess concurrency usage. Write findings to \`${r}/performance.md\`.
59
+ 3. **Build & Test Analyst** \u2014 Find ALL build, compile, test, lint operations in the trace. For each: extract the command, exit code, and key output lines. For failures: diagnose root cause (missing dependency? syntax error? test assertion? wrong config?). Track if the agent fixed failures or left them broken. Write findings to \`${r}/buildtest.md\`.
60
60
 
61
- **CRITICAL: You MUST wait for ALL 3 sub-agents to complete before proceeding to Step 3.** Do NOT move on until every sub-agent has returned its results. After launching them, poll or wait for their completion.
61
+ **CRITICAL: You MUST wait for ALL 3 sub-agents to complete before proceeding to Step 4.** Do NOT move on until every sub-agent has returned its results.
62
62
 
63
- **Step 3 \u2014 Synthesize the final report.** Once all sub-agents are done:
63
+ **Step 4 \u2014 Synthesize the final report.** Once all sub-agents are done:
64
64
  1. Read the intermediate files from \`${r}/\`
65
65
  2. Synthesize a unified report
66
66
  3. Write the final report to \`${e}\`
67
- 4. Clean up by removing the entire working directory: \`rm -rf ${r}\`
67
+ 4. Clean up: \`rm -rf ${r}\`
68
+
69
+ The final report MUST follow this exact structure:
70
+
71
+ ---
72
+
73
+ ## \u{1F4CA} Scorecard
74
+
75
+ | Dimension | Score | Notes |
76
+ |-----------|-------|-------|
77
+ | System Prompt Compliance | X/10 | one-line summary |
78
+ | User Ask Alignment | X/10 | one-line summary |
79
+ | Execution Consistency | X/10 | one-line summary |
80
+ | Error Recovery | X/10 | one-line summary |
81
+
82
+ **Overall: X/10**
83
+
84
+ ## \u{1F528} Build & Test Results
85
+
86
+ For each build/test operation found in the session, list:
87
+ - Command, exit code, pass/fail
88
+ - For failures: root cause in one sentence
89
+ - Final state: all green, or what's still broken
90
+
91
+ If no build/test operations exist, state "No build/test operations found in this session."
92
+
93
+ ## \u{1F4CB} System Prompt Compliance
94
+
95
+ List the key rules/constraints from the system prompt. For each:
96
+ - \u2705 Followed \u2014 with brief evidence
97
+ - \u26A0\uFE0F Partially followed \u2014 what was missed
98
+ - \u274C Violated \u2014 what happened instead
99
+
100
+ Focus on rules that were violated or partially followed. Don't exhaustively list every rule that was trivially followed.
68
101
 
69
- The final report must be a markdown file with these sections:
102
+ ## \u{1F3AF} User Ask Alignment
70
103
 
71
- ## \u{1F3AF} Effectiveness Score: X/100
72
- One-line verdict on how well the agent fulfilled the user's intent.
104
+ - What the user asked for (summarize the ask)
105
+ - What the agent actually delivered
106
+ - Gap analysis: missing deliverables, extra unrequested work, misinterpretations
73
107
 
74
- ## \u{1F527} Tool Usage Analysis
75
- - **Tool selection quality**: Did the agent pick the right tools? Any unnecessary or redundant tool calls? (e.g. repeated Read calls on the same file, Grep when Glob would suffice, excessive Bash calls)
76
- - **Error handling**: How did the agent recover from tool errors? Did it retry blindly or adapt?
77
- - **Efficiency**: Tool call count vs. actual value delivered. Identify wasted calls.
108
+ ## \u{1F504} Execution Consistency
78
109
 
79
- ## \u{1F504} Workflow & Strategy
80
- - **Planning quality**: Did the agent have a coherent strategy, or did it wander? Look for signs of backtracking, repeated attempts, or lack of direction.
81
- - **Sub-agent usage** (if any): Were sub-agents spawned effectively? Was the decomposition logical? Any sub-agents that were unnecessary or too narrow/broad?
82
- - **Sequencing**: Were operations done in a logical order, or was there unnecessary back-and-forth?
110
+ - Did the agent's execution match its own stated plan?
111
+ - Any backtracking, contradictions, or abandoned approaches?
112
+ - Were decisions internally consistent throughout the session?
83
113
 
84
- ## \u26A1 Performance
85
- - **Time distribution**: Where did the wall-clock time actually go? (LLM thinking vs. tool execution vs. idle gaps)
86
- - **Bottlenecks**: Identify the biggest time sinks and whether they were avoidable.
87
- - **Concurrency**: Did the agent parallelize where it could? Missed opportunities?
114
+ ## \u{1F4A1} Key Findings
88
115
 
89
- ## \u{1F4A1} Top 3 Improvements
90
- Specific, actionable recommendations to make this agent workflow better. Examples:
91
- - "Batch the 12 sequential Read calls into a single Glob + targeted Reads"
92
- - "The agent re-read file X 4 times \u2014 cache the content across turns"
93
- - "Sub-agent 'code-explorer' ran for 45s but its output was barely used \u2014 consider inlining"
116
+ Top 3-5 specific, evidence-backed observations. Every finding must reference concrete events from the session trace (tool call IDs, timestamps, or quoted output). No generic advice.
94
117
 
95
- Be brutally honest. Generic advice like "add error handling" is useless \u2014 always tie recommendations to specific evidence from the session data.
118
+ ---
96
119
 
97
120
  IMPORTANT CONSTRAINTS:
98
- - Be precise and concise. Every sentence must carry data or actionable insight \u2014 no filler, no fluff.
99
- - The entire report MUST be under 3000 characters (including markdown formatting). Cut ruthlessly if needed.`}_cleanReport(e){e=e.replace(/<thinking>[\s\S]*?<\/thinking>/g,""),e=e.replace(/^(Let me analyze|I'll analyze|Analyzing|Here's my analysis of|I need the session data).*$/gm,"");let n=/^## 🎯\s*Effectiveness Score/m,t=[...e.matchAll(new RegExp(n.source,"gm"))];if(t.length>0){let s=t[t.length-1];e=e.slice(s.index)}else{let s=e.match(/^(## [🎯🔧🔄⚡💡#])/mu);if(s)e=e.slice(s.index);else{let r=e.split(`
100
- `),o=[],a=!1;for(let i of r){if(/^● /.test(i)){a=!0;continue}if(/^ {2}\$ /.test(i)){a=!0;continue}if(/^ {2}└ /.test(i)){a=!1;continue}if(!/^\(\+\d+ lines?\)/.test(i)&&!/^ {2}└ \d+ lines/.test(i)){if(/^● Asked user:/.test(i)){a=!0;continue}if(/^ {2}└ User responded:/.test(i)){a=!1;continue}a&&/\S/.test(i)&&!/^ {2}/.test(i)&&(a=!1),!a&&o.push(i)}}e=o.join(`
121
+ - Be precise and concise. Every sentence must carry data or actionable insight.
122
+ - The scorecard dimensions are the backbone \u2014 all analysis must map back to them.
123
+ - Always cite evidence from the session trace. "The agent violated rule X" is useless without showing where.
124
+ - The entire report should be under 4000 characters.`}_cleanReport(e){e=e.replace(/<thinking>[\s\S]*?<\/thinking>/g,""),e=e.replace(/^(Let me analyze|I'll analyze|Analyzing|Here's my analysis of|I need the session data).*$/gm,"");let s=/^## 📊\s*Scorecard/m,t=[...e.matchAll(new RegExp(s.source,"gm"))];if(t.length>0){let n=t[t.length-1];e=e.slice(n.index)}else{let n=e.match(/^(## [🎯🔧🔄⚡💡#])/mu);if(n)e=e.slice(n.index);else{let r=e.split(`
125
+ `),a=[],o=!1;for(let i of r){if(/^● /.test(i)){o=!0;continue}if(/^ {2}\$ /.test(i)){o=!0;continue}if(/^ {2}└ /.test(i)){o=!1;continue}if(!/^\(\+\d+ lines?\)/.test(i)&&!/^ {2}└ \d+ lines/.test(i)){if(/^● Asked user:/.test(i)){o=!0;continue}if(/^ {2}└ User responded:/.test(i)){o=!1;continue}o&&/\S/.test(i)&&!/^ {2}/.test(i)&&(o=!1),!o&&a.push(i)}}e=a.join(`
101
126
  `)}}return e=e.replace(/\n{3,}/g,`
102
127
 
103
- `).trim(),e}async getInsightStatus(e,n,t="copilot"){return await this._getStatusForSource(e,n)}async _getStatusForSource(e,n){let t=C.join(n,`${e}.agent-review.md`),s=C.join(n,`${e}.agent-review.md.lock`),r=C.join(n,`${e}.agent-review.md.tmp`);try{let o=await _.readFile(t,"utf-8"),a=await _.stat(t);return{status:"completed",report:o,generatedAt:a.mtime}}catch{try{await _.access(s);let a=await _.stat(s),i=Date.now()-a.birthtime.getTime(),l=null;try{l=await _.readFile(r,"utf-8")}catch{}return i>=cs.INSIGHT_TIMEOUT_MS?{status:"timeout",log:l,startedAt:a.birthtime,lastUpdate:a.mtime,ageMs:i}:{status:"generating",log:l,startedAt:a.birthtime,lastUpdate:a.mtime,ageMs:i}}catch{return{status:"not_started"}}}}async deleteInsight(e,n,t="copilot"){let s=C.join(n,`${e}.agent-review.md`);try{return await _.unlink(s),{success:!0}}catch(r){if(r.code==="ENOENT")return{success:!0,message:"Insight file not found"};throw r}}};us.exports=He});var ms=w((zr,ps)=>{var Un=ds(),{isValidSessionId:Je}=V(),{trackEvent:Ge,trackMetric:Wn,trackException:Hn}=F(),Ke=class{constructor(e=null,n=null){if(e?this.insightService=e:this.insightService=new Un,n)this.sessionService=n;else{let t=ze();this.sessionService=new t}}async generateInsight(e,n){try{let t=e.params.id,s=e.body?.force===!0;if(!Je(t))return n.status(400).json({error:"Invalid session ID"});let r=await this.sessionService.getSessionById(t);if(!r)return n.status(404).json({error:"Session not found"});if(!r.directory)return n.status(400).json({error:"Session directory not available"});let o=Date.now(),a=await this.insightService.generateInsight(r.id,r.directory,r.source,s),i=Date.now()-o;Ge("InsightGenerated",{sessionId:t,source:r.source||"unknown",durationMs:i.toString()}),Wn("InsightGenerationTime",i,{sessionId:t,source:r.source||"unknown"}),n.json(a)}catch(t){console.error("Error generating insight:",t),Hn(t,{sessionId:e.params.id,operation:"generateInsight"}),n.status(500).json({error:t.message||"Error generating insight"})}}async getInsightStatus(e,n){try{let t=e.params.id;if(!Je(t))return n.status(400).json({error:"Invalid session ID"});let s=await this.sessionService.getSessionById(t);if(!s)return n.status(404).json({error:"Session not found"});if(!s.directory)return n.status(400).json({error:"Session directory not available"});let r=await this.insightService.getInsightStatus(s.id,s.directory,s.source);r.status==="ready"&&r.report&&Ge("InsightViewed",{sessionId:t}),n.json(r)}catch(t){console.error("Error getting insight status:",t),n.status(500).json({error:"Error getting insight status"})}}async deleteInsight(e,n){try{let t=e.params.id;if(!Je(t))return n.status(400).json({error:"Invalid session ID"});let s=await this.sessionService.getSessionById(t);if(!s)return n.status(404).json({error:"Session not found"});if(!s.directory)return n.status(400).json({error:"Session directory not available"});let r=await this.insightService.deleteInsight(s.id,s.directory,s.source);Ge("InsightDeleted",{sessionId:t}),n.json(r)}catch(t){console.error("Error deleting insight:",t),n.status(500).json({error:"Error deleting insight"})}}};ps.exports=Ke});var ys=w((Vr,hs)=>{var h=require("fs"),I=require("path"),ae=require("os"),Jn=require("multer"),{spawn:Ye}=require("child_process"),{isValidSessionId:K}=V(),{trackEvent:fs,trackException:Ze}=F(),gs=ue(),Gn=z(),Xe=class{constructor(){this.SESSION_DIR=process.env.SESSION_DIR||I.join(ae.homedir(),".copilot","session-state"),this.uploadDir=process.env.UPLOAD_DIR||I.join(ae.tmpdir(),"copilot-session-uploads"),this.SESSION_DIRS={copilot:this.SESSION_DIR,claude:I.join(ae.homedir(),".claude","projects"),"pi-mono":I.join(ae.homedir(),".pi","agent","sessions")},this.upload=this.createMulterInstance()}createMulterInstance(){return Jn({dest:this.uploadDir,limits:{fileSize:Gn.MAX_UPLOAD_SIZE},fileFilter:(e,n,t)=>{let s=n.originalname.toLowerCase().endsWith(".zip"),r=n.mimetype==="application/zip"||n.mimetype==="application/x-zip-compressed";if(!s||!r)return t(new Error("Only .zip files are allowed"));t(null,!0)}})}async shareSession(e,n){try{let t=e.params.id;if(!K(t))return n.status(400).json({error:"Invalid session ID"});let s=I.join(this.SESSION_DIR,t);try{await h.promises.access(s)}catch{return n.status(404).json({error:"Session not found"})}let r=I.join(ae.tmpdir(),`session-${t}.zip`),o=Ye("zip",["-r","-q",r,t],{cwd:this.SESSION_DIR});gs.register(o,{name:`zip-${t}`}),o.on("close",a=>{if(a!==0)return n.status(500).json({error:"Failed to create zip file"});fs("SessionShared",{sessionId:t}),n.download(r,`session-${t}.zip`,i=>{h.promises.unlink(r).catch(()=>{}),i&&console.error("Error sending zip:",i)})}),o.on("error",a=>{console.error("Error creating zip:",a),n.status(500).json({error:"Failed to create zip file"})})}catch(t){console.error("Error sharing session:",t),n.status(500).json({error:"Error sharing session"})}}async importSession(e,n){try{if(!e.file)return n.status(400).json({error:"No file uploaded"});let t=e.file.path,s=I.join(this.uploadDir,`extract-${Date.now()}`);await h.promises.mkdir(s,{recursive:!0});let r=50*1024*1024,o=200*1024*1024,a=1e3,i=5;if((await h.promises.stat(t)).size>r)return await h.promises.unlink(t),n.status(400).json({error:"Compressed file too large (max 50MB)"});let c=Ye("unzip",["-l",t]),d="";c.stdout.on("data",S=>{d+=S.toString()}),await new Promise((S,T)=>{c.on("close",v=>{v!==0?T(new Error("Failed to list zip contents")):S()}),c.on("error",T)});let p=d.split(`
104
- `),m=0,g=0,f=0;for(let S of p){let T=S.trim().match(/^\s*(\d+)\s+\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}\s+(.+)$/);if(T){let v=parseInt(T[1]),j=T[2];m+=v,g++;let L=(j.match(/\//g)||[]).length;f=Math.max(f,L)}}if(m>o)return await h.promises.unlink(t),n.status(400).json({error:`Uncompressed size too large (${Math.round(m/1024/1024)}MB > ${o/1024/1024}MB)`});if(g>a)return await h.promises.unlink(t),n.status(400).json({error:`Too many files in archive (${g} > ${a})`});if(f>i)return await h.promises.unlink(t),n.status(400).json({error:`Directory nesting too deep (${f} > ${i})`});let y=Ye("unzip",["-q",t,"-d",s]);gs.register(y,{name:"unzip-import"}),y.on("close",async S=>{let T;try{if(await h.promises.unlink(t),S!==0)return await h.promises.rm(s,{recursive:!0,force:!0}),n.status(500).json({error:"Failed to extract zip file"});let v=await h.promises.readdir(s);if(v.length===0)return await h.promises.rm(s,{recursive:!0,force:!0}),n.status(400).json({error:"Empty zip file"});if(T=v[0],!K(T))return await h.promises.rm(s,{recursive:!0,force:!0}),n.status(400).json({error:"Invalid session directory name in zip file"});let j=I.join(s,T),L=I.join(this.SESSION_DIR,T),pe=I.join(j,"events.jsonl");try{await h.promises.access(pe)}catch{return await h.promises.rm(s,{recursive:!0,force:!0}),n.status(400).json({error:"Invalid session structure (no events.jsonl)"})}if(h.existsSync(L))return await h.promises.rm(s,{recursive:!0,force:!0}),n.status(409).json({error:"Session already exists"});await h.promises.rename(j,L),await h.promises.rm(s,{recursive:!0,force:!0});let me=await h.promises.stat(t).catch(()=>({size:0}));fs("SessionImported",{format:"copilot",fileSize:me.size.toString()}),n.json({success:!0,sessionId:T})}catch(v){console.error("Error importing session:",v),Ze(v,{operation:"importSession",sessionId:T||"unknown"}),await h.promises.rm(s,{recursive:!0,force:!0}).catch(()=>{}),n.status(500).json({error:"Error importing session"})}}),y.on("error",async S=>{console.error("Error extracting zip:",S),Ze(S,{operation:"importSession_unzip"}),await h.promises.unlink(t).catch(()=>{}),await h.promises.rm(s,{recursive:!0,force:!0}).catch(()=>{}),n.status(500).json({error:"Failed to extract zip file"})})}catch(t){console.error("Error processing upload:",t),Ze(t,{operation:"importSession_upload"}),e.file&&await h.promises.unlink(e.file.path).catch(()=>{}),n.status(500).json({error:"Error processing upload"})}}getUploadMiddleware(){return this.upload.single("zipFile")}async _detectFormat(e){try{let n=await h.promises.readdir(e);if(n.length===0)return null;let t=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z_([a-zA-Z0-9_-]+)\.jsonl$/;for(let r of n){let o=r.match(t);if(o)return{format:"pi-mono",sessionId:o[1],fileName:r,extractDir:e}}for(let r of n){let o=I.join(e,r);if((await h.promises.stat(o)).isDirectory()){let i=I.join(o,"events.jsonl");if(h.existsSync(i))return{format:"copilot",sessionId:r,directoryName:r,extractDir:e}}}let s=/^([a-zA-Z0-9_-]+)\.jsonl$/;for(let r of n){let o=I.join(e,r);if((await h.promises.stat(o)).isFile()){let i=r.match(s);if(i){let l=i[1],c=I.join(e,l),d=h.existsSync(c);return{format:"claude",sessionId:l,fileName:r,hasDirectory:d,directoryName:d?l:void 0,extractDir:e}}}}return null}catch(n){return console.error("Error detecting format:",n),null}}async _importCopilotSession(e,n){try{let{sessionId:t,directoryName:s}=e;if(!K(t))return{success:!1,error:"Invalid session ID",statusCode:400};let r=I.join(n,s),o=I.join(this.SESSION_DIRS.copilot,t),a=I.join(r,"events.jsonl");return h.existsSync(a)?h.existsSync(o)?{success:!1,error:"Session already exists",statusCode:409}:(await h.promises.rename(r,o),await h.promises.writeFile(I.join(o,".imported"),""),{success:!0,sessionId:t,format:"copilot"}):{success:!1,error:"Invalid session structure (no events.jsonl)",statusCode:400}}catch(t){return console.error("Error importing Copilot session:",t),{success:!1,error:`Error importing Copilot session: ${t.message}`,statusCode:500}}}async _importClaudeSession(e,n,t){try{let{sessionId:s,fileName:r,hasDirectory:o,directoryName:a}=e;if(!K(s))return{success:!1,error:"Invalid session ID",statusCode:400};let i=t.query.project||"imported-sessions",l=I.join(this.SESSION_DIRS.claude,i);await h.promises.mkdir(l,{recursive:!0});let c=I.join(n,r),d=I.join(l,r);if(await h.promises.rename(c,d),o&&a){let p=I.join(n,a),m=I.join(l,a);await h.promises.rename(p,m)}return{success:!0,sessionId:s,format:"claude",project:i}}catch(s){return console.error("Error importing Claude session:",s),{success:!1,error:`Error importing Claude session: ${s.message}`,statusCode:500}}}async _importPiMonoSession(e,n,t){try{let{sessionId:s,fileName:r}=e;if(!K(s))return{success:!1,error:"Invalid session ID",statusCode:400};let o=t.query.project||"imported-sessions",a=I.join(this.SESSION_DIRS["pi-mono"],o);await h.promises.mkdir(a,{recursive:!0});let i=I.join(n,r),l=I.join(a,r);return await h.promises.rename(i,l),{success:!0,sessionId:s,format:"pi-mono",project:o}}catch(s){return console.error("Error importing Pi-Mono session:",s),{success:!1,error:`Error importing Pi-Mono session: ${s.message}`,statusCode:500}}}async _importByFormat(e,n,t){if(!K(e.sessionId))return{success:!1,error:"Invalid session ID",statusCode:400};switch(e.format){case"copilot":return await this._importCopilotSession(e,n);case"claude":return await this._importClaudeSession(e,n,t);case"pi-mono":return await this._importPiMonoSession(e,n,t);default:return{success:!1,error:`Unsupported format: ${e.format}`,statusCode:400}}}async _findSessionLocation(e,n=null){try{let t=n?[n,...Object.keys(this.SESSION_DIRS).filter(s=>s!==n)]:Object.keys(this.SESSION_DIRS);for(let s of t){let r=this.SESSION_DIRS[s];if(s==="copilot"){let o=I.join(r,e);if(h.existsSync(o)){let a=I.join(o,"events.jsonl");if(h.existsSync(a))return{source:"copilot",sessionId:e,sessionPath:o,baseDir:r}}}else if(s==="claude"){if(h.existsSync(r)){let o=await h.promises.readdir(r);for(let a of o){let i=I.join(r,a);if((await h.promises.stat(i)).isDirectory()){let c=I.join(i,`${e}.jsonl`);if(h.existsSync(c))return{source:"claude",sessionId:e,sessionFile:c,projectPath:i,project:a,baseDir:r}}}}}else if(s==="pi-mono"&&h.existsSync(r)){let o=await h.promises.readdir(r);for(let a of o){let i=I.join(r,a);if((await h.promises.stat(i)).isDirectory()){let c=await h.promises.readdir(i),d=new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-\\d{3}Z_${e}\\.jsonl$`);for(let p of c)if(d.test(p))return{source:"pi-mono",sessionId:e,fileName:p,sessionFile:I.join(i,p),projectPath:i,project:a,baseDir:r}}}}}return null}catch(t){return console.error("Error finding session location:",t),null}}};hs.exports=Xe});var _s=w((Br,ws)=>{var Kn=Be(),Yn=qe(),{isValidSessionId:Ss}=V(),{trackEvent:Zn}=F(),Qe=class{constructor(e=null,n=null){this.tagService=e||new Kn,this.sessionRepository=n||new Yn}async getAllTags(e,n){try{let t=await this.tagService.getAllKnownTags();n.json({tags:t})}catch(t){console.error("Error getting all tags:",t),n.status(500).json({error:"Error loading tags"})}}async getSessionTags(e,n){try{let t=e.params.id;if(!Ss(t))return n.status(400).json({error:"Invalid session ID"});let s=await this.sessionRepository.findById(t);if(!s)return n.status(404).json({error:"Session not found"});let r=await this.tagService.getSessionTags(s);n.json({tags:r})}catch(t){console.error("Error getting session tags:",t),n.status(500).json({error:"Error loading session tags"})}}async setSessionTags(e,n){try{let t=e.params.id,{tags:s}=e.body;if(!Ss(t))return n.status(400).json({error:"Invalid session ID"});if(!Array.isArray(s))return n.status(400).json({error:"Tags must be an array"});if(s.length>10)return n.status(400).json({error:"Maximum 10 tags per session"});for(let a of s){if(typeof a!="string"||a.trim().length===0)return n.status(400).json({error:"Tags must be non-empty strings"});if(a.length>30)return n.status(400).json({error:"Tag length must not exceed 30 characters"})}let r=await this.sessionRepository.findById(t);if(!r)return n.status(404).json({error:"Session not found"});let o=await this.tagService.setSessionTags(r,s);Zn("TagUpdated",{sessionId:t,tagCount:o.length.toString()}),n.json({tags:o})}catch(t){if(console.error("Error setting session tags:",t),t.message==="Maximum 10 tags per session")return n.status(400).json({error:t.message});if(t.message==="Session must have a directory field")return n.status(400).json({error:"Session does not support tagging"});n.status(500).json({error:"Error saving session tags"})}}};ws.exports=Qe});var bs=w((Ur,Es)=>{var de=require("express"),Is=require("path"),Ts=require("compression"),Xn=require("helmet"),Qn=z(),{requestTimeout:er,developmentCors:tr,errorHandler:sr,notFoundHandler:nr,telemetryLocals:rr}=ct(),or=as(),ar=ms(),ir=ys(),lr=_s();function cr(u={}){let e=de();e.set("etag",!1);let n=new or(u.sessionService),t=new ar(u.insightService,u.sessionService),s=new ir,r=new lr(u.tagService);return e.use((o,a,i)=>{a.setHeader("Content-Security-Policy","default-src 'self'; style-src 'self' 'unsafe-inline' https: http:; font-src 'self' https: http:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https: http:; img-src 'self' data: https: http:; connect-src 'self' https: http:"),i()}),e.use(Xn({contentSecurityPolicy:!1,hsts:!1,referrerPolicy:!1,crossOriginEmbedderPolicy:!1,crossOriginOpenerPolicy:!1,crossOriginResourcePolicy:!1})),e.use(Ts({level:1,threshold:1024,filter:(o,a)=>o.path.includes("/events")&&a.getHeader("Content-Type")?.includes("application/json")?!1:Ts.filter(o,a)})),e.use(de.json({limit:"1mb"})),e.use(de.urlencoded({extended:!0})),e.use(er),e.use(rr),Qn.NODE_ENV==="development"&&e.use(tr),e.use("/public",de.static(Is.join(__dirname,"../public"))),e.set("view engine","ejs"),e.set("views",Is.join(__dirname,"../views")),e.get("/",n.getHomepage.bind(n)),e.get("/session/:id",n.getSessionDetail.bind(n)),e.get("/session/:id/time-analyze",n.getTimeAnalysis.bind(n)),e.get("/session/:id/export",n.exportSession.bind(n)),e.get("/api/sessions/load-more",n.loadMoreSessions.bind(n)),e.get("/api/sessions",n.getSessions.bind(n)),e.get("/api/sessions/:id/events",n.getSessionEvents.bind(n)),e.get("/api/sessions/:id/timeline",n.getTimeline.bind(n)),e.get("/api/tags",r.getAllTags.bind(r)),e.get("/api/sessions/:id/tags",r.getSessionTags.bind(r)),e.put("/api/sessions/:id/tags",r.setSessionTags.bind(r)),e.get("/session/:id/share",s.shareSession.bind(s)),e.post("/session/import",(o,a,i)=>s.getUploadMiddleware()(o,a,i),s.importSession.bind(s)),e.post("/session/:id/insight",t.generateInsight.bind(t)),e.get("/session/:id/insight",t.getInsightStatus.bind(t)),e.delete("/session/:id/insight",t.deleteInsight.bind(t)),e.use(nr),e.use(sr),e}Es.exports=cr});F();var ur=bs(),et=z(),dr=ue(),vs=ur();module.exports=vs;if(require.main===module){let u=vs.listen(et.PORT,()=>{console.log(`\u{1F680} Copilot Session Viewer running at http://localhost:${et.PORT}`),console.log(`\u{1F527} Environment: ${et.NODE_ENV}`),console.log(`\u26A1 Active processes: ${dr.getActiveCount()}`)});process.on("SIGTERM",()=>{console.log("\u{1F4DB} SIGTERM received, closing server..."),u.close(()=>{console.log("\u2705 Server closed")})})}
128
+ `).trim(),e}async getInsightStatus(e,s,t="copilot"){return await this._getStatusForSource(e,s)}async _getStatusForSource(e,s){let t=x.join(s,`${e}.agent-review.md`),n=x.join(s,`${e}.agent-review.md.lock`),r=x.join(s,`${e}.agent-review.md.tmp`);try{let a=await S.readFile(t,"utf-8"),o=await S.stat(t);return{status:"completed",report:a,generatedAt:o.mtime}}catch{try{await S.access(n);let o=await S.stat(n),i=Date.now()-o.birthtime.getTime(),c=null;try{c=await S.readFile(r,"utf-8")}catch{}return i>=gs.INSIGHT_TIMEOUT_MS?{status:"timeout",log:c,startedAt:o.birthtime,lastUpdate:o.mtime,ageMs:i}:{status:"generating",log:c,startedAt:o.birthtime,lastUpdate:o.mtime,ageMs:i}}catch{return{status:"not_started"}}}}async deleteInsight(e,s,t="copilot"){let n=x.join(s,`${e}.agent-review.md`);try{return await S.unlink(n),{success:!0}}catch(r){if(r.code==="ENOENT")return{success:!0,message:"Insight file not found"};throw r}}};hs.exports=Xe});var ws=y((ra,Ss)=>{var or=ys(),{isValidSessionId:Ye}=q(),{trackEvent:Ze,trackMetric:ir,trackException:cr}=L(),Qe=class{constructor(e=null,s=null){if(e?this.insightService=e:this.insightService=new or,s)this.sessionService=s;else{let t=Be();this.sessionService=new t}}_getGenerateInsightErrorResponse(e){if(e instanceof Error){if(e.message==="Events file not found")return{status:400,body:{error:e.message}};if(e.message==="Failed to acquire lock for insight generation")return{status:503,body:{error:e.message}};if(e.message)return{status:500,body:{error:e.message}}}return{status:500,body:{error:"Error generating insight"}}}async generateInsight(e,s){try{let t=e.params.id,n=e.body?.force===!0;if(!Ye(t))return s.status(400).json({error:"Invalid session ID"});let r=await this.sessionService.getSessionById(t);if(!r)return s.status(404).json({error:"Session not found"});if(!r.directory)return s.status(400).json({error:"Session directory not available"});let a=Date.now(),o=await this.insightService.generateInsight(r.id,r.directory,r.source,n),i=Date.now()-a;Ze("InsightGenerated",{sessionId:t,source:r.source||"unknown",durationMs:i.toString()}),ir("InsightGenerationTime",i,{sessionId:t,source:r.source||"unknown"}),s.json(o)}catch(t){console.error("Error generating insight:",t),cr(t,{sessionId:e.params.id,operation:"generateInsight"});let n=this._getGenerateInsightErrorResponse(t);s.status(n.status).json(n.body)}}async getInsightStatus(e,s){try{let t=e.params.id;if(!Ye(t))return s.status(400).json({error:"Invalid session ID"});let n=await this.sessionService.getSessionById(t);if(!n)return s.status(404).json({error:"Session not found"});if(!n.directory)return s.status(400).json({error:"Session directory not available"});let r=await this.insightService.getInsightStatus(n.id,n.directory,n.source);r.status==="ready"&&r.report&&Ze("InsightViewed",{sessionId:t}),s.json(r)}catch(t){console.error("Error getting insight status:",t),s.status(500).json({error:"Error getting insight status"})}}async deleteInsight(e,s){try{let t=e.params.id;if(!Ye(t))return s.status(400).json({error:"Invalid session ID"});let n=await this.sessionService.getSessionById(t);if(!n)return s.status(404).json({error:"Session not found"});if(!n.directory)return s.status(400).json({error:"Session directory not available"});let r=await this.insightService.deleteInsight(n.id,n.directory,n.source);Ze("InsightDeleted",{sessionId:t}),s.json(r)}catch(t){console.error("Error deleting insight:",t),s.status(500).json({error:"Error deleting insight"})}}};Ss.exports=Qe});var bs=y((aa,Es)=>{var I=require("fs"),A=require("path"),ae=require("os"),lr=require("multer"),{spawn:et}=require("child_process"),{isValidSessionId:_s}=q(),{trackEvent:Is,trackException:tt}=L(),Ts=pe(),ur=z(),{registry:oe}=ee(),st=class{constructor(){this.SESSION_DIR=process.env.SESSION_DIR||A.join(ae.homedir(),".copilot","session-state"),this.uploadDir=process.env.UPLOAD_DIR||A.join(ae.tmpdir(),"copilot-session-uploads"),this.SESSION_DIRS={copilot:this.SESSION_DIR,claude:A.join(ae.homedir(),".claude","projects"),"pi-mono":A.join(ae.homedir(),".pi","agent","sessions")},this.upload=this.createMulterInstance()}createMulterInstance(){return lr({dest:this.uploadDir,limits:{fileSize:ur.MAX_UPLOAD_SIZE},fileFilter:(e,s,t)=>{let n=s.originalname.toLowerCase().endsWith(".zip"),r=s.mimetype==="application/zip"||s.mimetype==="application/x-zip-compressed";if(!n||!r)return t(new Error("Only .zip files are allowed"));t(null,!0)}})}async shareSession(e,s){try{let t=e.params.id;if(!_s(t))return s.status(400).json({error:"Invalid session ID"});let n=A.join(this.SESSION_DIR,t);try{await I.promises.access(n)}catch{return s.status(404).json({error:"Session not found"})}let r=A.join(ae.tmpdir(),`session-${t}.zip`),a=et("zip",["-r","-q",r,t],{cwd:this.SESSION_DIR});Ts.register(a,{name:`zip-${t}`}),a.on("close",o=>{if(o!==0)return s.status(500).json({error:"Failed to create zip file"});Is("SessionShared",{sessionId:t}),s.download(r,`session-${t}.zip`,i=>{I.promises.unlink(r).catch(()=>{}),i&&console.error("Error sending zip:",i)})}),a.on("error",o=>{console.error("Error creating zip:",o),s.status(500).json({error:"Failed to create zip file"})})}catch(t){console.error("Error sharing session:",t),s.status(500).json({error:"Error sharing session"})}}async importSession(e,s){try{if(!e.file)return s.status(400).json({error:"No file uploaded"});let t=e.file.path,n=A.join(this.uploadDir,`extract-${Date.now()}`),r=(await I.promises.stat(t)).size;await I.promises.mkdir(n,{recursive:!0}),await this._validateZipArchive(t);let a=et("unzip",["-q",t,"-d",n]);Ts.register(a,{name:"unzip-import"}),a.on("close",async o=>{try{if(await I.promises.unlink(t).catch(()=>{}),o!==0)return await I.promises.rm(n,{recursive:!0,force:!0}),s.status(500).json({error:"Failed to extract zip file"});let i=await this._importExtractedSession(n,e);if(await I.promises.rm(n,{recursive:!0,force:!0}).catch(()=>{}),!i.success){let l={error:i.error};return i.code&&(l.code=i.code),i.candidates&&(l.candidates=i.candidates),s.status(i.statusCode||500).json(l)}Is("SessionImported",{format:i.format,fileSize:r.toString()});let c={success:!0,sessionId:i.sessionId,format:i.format};return i.project&&(c.project=i.project),s.json(c)}catch(i){return console.error("Error importing session:",i),tt(i,{operation:"importSession"}),await I.promises.rm(n,{recursive:!0,force:!0}).catch(()=>{}),s.status(500).json({error:"Error importing session"})}}),a.on("error",async o=>(console.error("Error extracting zip:",o),tt(o,{operation:"importSession_unzip"}),await I.promises.unlink(t).catch(()=>{}),await I.promises.rm(n,{recursive:!0,force:!0}).catch(()=>{}),s.status(500).json({error:"Failed to extract zip file"})))}catch(t){return console.error("Error processing upload:",t),tt(t,{operation:"importSession_upload"}),e.file&&await I.promises.unlink(e.file.path).catch(()=>{}),t.message?.match(/Compressed file too large|Uncompressed size too large|Too many files|Directory nesting too deep|Failed to list zip/)?s.status(400).json({error:t.message}):s.status(500).json({error:"Error processing upload"})}}getUploadMiddleware(){let e=["zipFile","sessionZip"],s=this.upload.fields(e.map(t=>({name:t,maxCount:1})));return(t,n,r)=>{s(t,n,a=>a?r(a):(t.file=e.map(o=>t.files?.[o]?.[0]).find(Boolean)||null,r()))}}async _detectFormat(e){let s=await this._detectImportCandidates(e);return s.status!=="matched"?null:{format:s.match.source,extractDir:e,...s.match}}async _detectImportCandidates(e){try{let s=await I.promises.readdir(e);if(s.length===0)return{status:"unsupported-format",matches:[],candidates:[],error:"Empty zip file"};if(s.some(r=>r.includes("..")||A.isAbsolute(r)))return{status:"invalid-structure",matches:[],candidates:[],error:"Invalid session directory name in zip file"};let t=await oe.detectImportCandidates(e),n=t.filter(r=>r.matched);return n.length===0?{status:"unsupported-format",matches:[],candidates:t,error:"Unsupported session zip format"}:n.length>1?{status:"ambiguous",matches:n,candidates:t,error:"Ambiguous session zip format"}:{status:"matched",match:n[0],matches:n,candidates:t}}catch(s){return console.error("Error detecting format:",s),{status:"error",matches:[],candidates:[],error:"Error detecting format"}}}async _importCopilotSession(e,s){return oe.get("copilot").importDetectedSession(e,{extractDir:s,req:{query:{}},targetDir:this.SESSION_DIRS.copilot})}async _importClaudeSession(e,s,t){return oe.get("claude").importDetectedSession(e,{extractDir:s,req:t,targetDir:this.SESSION_DIRS.claude})}async _importPiMonoSession(e,s,t){return oe.get("pi-mono").importDetectedSession(e,{extractDir:s,req:t,targetDir:this.SESSION_DIRS["pi-mono"]})}async _importByFormat(e,s,t){if(!_s(e.sessionId))return{success:!1,error:"Invalid session ID",statusCode:400};let n=oe.get(e.format||e.source);return n?n.importDetectedSession(e,{extractDir:s,req:t,targetDir:this.SESSION_DIRS[e.format||e.source]}):{success:!1,error:`Unsupported format: ${e.format||e.source}`,statusCode:400,code:"unsupported-format"}}async _validateZipArchive(e){if((await I.promises.stat(e)).size>52428800)throw new Error("Compressed file too large (max 50MB)");let o=et("unzip",["-l",e]),i="";o.stdout.on("data",p=>{i+=p.toString()}),await new Promise((p,m)=>{o.on("close",f=>f!==0?m(new Error("Failed to list zip contents")):p()),o.on("error",m)});let c=0,l=0,u=0;for(let p of i.split(`
129
+ `)){let m=p.trim().match(/^\s*(\d+)\s+\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}\s+(.+)$/);m&&(c+=parseInt(m[1],10),l++,u=Math.max(u,(m[2].match(/\//g)||[]).length))}if(c>209715200)throw new Error(`Uncompressed size too large (${Math.round(c/1024/1024)}MB > ${209715200/1024/1024}MB)`);if(l>1e3)throw new Error(`Too many files in archive (${l} > 1000)`);if(u>5)throw new Error(`Directory nesting too deep (${u} > 5)`)}async _importExtractedSession(e,s){let t=await this._detectImportCandidates(e);return t.status==="error"?{success:!1,statusCode:500,error:"Error importing session"}:t.status==="invalid-structure"?{success:!1,statusCode:400,error:t.error}:t.status==="unsupported-format"?{success:!1,statusCode:t.error==="Empty zip file"?400:415,error:t.error,code:"unsupported-format",candidates:t.candidates}:t.status==="ambiguous"?{success:!1,statusCode:400,error:t.error,code:"ambiguous-format",candidates:t.matches}:this._importByFormat(t.match,e,s)}async _findSessionLocation(e,s=null){try{let t=s?[s,...Object.keys(this.SESSION_DIRS).filter(n=>n!==s)]:Object.keys(this.SESSION_DIRS);for(let n of t){let r=this.SESSION_DIRS[n];if(n==="copilot"){let a=A.join(r,e);if(I.existsSync(a)){let o=A.join(a,"events.jsonl");if(I.existsSync(o))return{source:"copilot",sessionId:e,sessionPath:a,baseDir:r}}}else if(n==="claude"){if(I.existsSync(r)){let a=await I.promises.readdir(r);for(let o of a){let i=A.join(r,o);if((await I.promises.stat(i)).isDirectory()){let l=A.join(i,`${e}.jsonl`);if(I.existsSync(l))return{source:"claude",sessionId:e,sessionFile:l,projectPath:i,project:o,baseDir:r}}}}}else if(n==="pi-mono"&&I.existsSync(r)){let a=await I.promises.readdir(r);for(let o of a){let i=A.join(r,o);if((await I.promises.stat(i)).isDirectory()){let l=await I.promises.readdir(i),u=new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-\\d{3}Z_${e}\\.jsonl$`);for(let p of l)if(u.test(p))return{source:"pi-mono",sessionId:e,fileName:p,sessionFile:A.join(i,p),projectPath:i,project:o,baseDir:r}}}}}return null}catch(t){return console.error("Error finding session location:",t),null}}};Es.exports=st});var Ds=y((oa,vs)=>{var dr=He(),pr=Le(),{isValidSessionId:Cs}=q(),{trackEvent:mr}=L(),nt=class{constructor(e=null,s=null){this.tagService=e||new dr,this.sessionRepository=s||new pr}async getAllTags(e,s){try{let t=await this.tagService.getAllKnownTags();s.json({tags:t})}catch(t){console.error("Error getting all tags:",t),s.status(500).json({error:"Error loading tags"})}}async getSessionTags(e,s){try{let t=e.params.id;if(!Cs(t))return s.status(400).json({error:"Invalid session ID"});let n=await this.sessionRepository.findById(t);if(!n)return s.status(404).json({error:"Session not found"});let r=await this.tagService.getSessionTags(n);s.json({tags:r})}catch(t){console.error("Error getting session tags:",t),s.status(500).json({error:"Error loading session tags"})}}async setSessionTags(e,s){try{let t=e.params.id,{tags:n}=e.body;if(!Cs(t))return s.status(400).json({error:"Invalid session ID"});if(!Array.isArray(n))return s.status(400).json({error:"Tags must be an array"});if(n.length>10)return s.status(400).json({error:"Maximum 10 tags per session"});for(let o of n){if(typeof o!="string"||o.trim().length===0)return s.status(400).json({error:"Tags must be non-empty strings"});if(o.length>30)return s.status(400).json({error:"Tag length must not exceed 30 characters"})}let r=await this.sessionRepository.findById(t);if(!r)return s.status(404).json({error:"Session not found"});let a=await this.tagService.setSessionTags(r,n);mr("TagUpdated",{sessionId:t,tagCount:a.length.toString()}),s.json({tags:a})}catch(t){if(console.error("Error setting session tags:",t),t.message==="Maximum 10 tags per session")return s.status(400).json({error:t.message});if(t.message==="Session must have a directory field")return s.status(400).json({error:"Session does not support tagging"});s.status(500).json({error:"Error saving session tags"})}}};vs.exports=nt});var ks=y((ia,As)=>{var me=require("express"),xs=require("path"),js=require("compression"),fr=require("helmet"),gr=z(),{requestTimeout:hr,developmentCors:yr,errorHandler:Sr,notFoundHandler:wr,telemetryLocals:_r}=mt(),Ir=ps(),Tr=ws(),Er=bs(),br=Ds();function Cr(d={}){let e=me();e.set("etag",!1);let s=new Ir(d.sessionService),t=new Tr(d.insightService,d.sessionService),n=new Er,r=new br(d.tagService);return e.use((a,o,i)=>{o.setHeader("Content-Security-Policy","default-src 'self'; style-src 'self' 'unsafe-inline' https: http:; font-src 'self' https: http:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https: http:; img-src 'self' data: https: http:; connect-src 'self' https: http:"),i()}),e.use(fr({contentSecurityPolicy:!1,hsts:!1,referrerPolicy:!1,crossOriginEmbedderPolicy:!1,crossOriginOpenerPolicy:!1,crossOriginResourcePolicy:!1})),e.use(js({level:1,threshold:1024,filter:(a,o)=>a.path.includes("/events")&&o.getHeader("Content-Type")?.includes("application/json")?!1:js.filter(a,o)})),e.use(me.json({limit:"1mb"})),e.use(me.urlencoded({extended:!0})),e.use(hr),e.use(_r),gr.NODE_ENV==="development"&&e.use(yr),e.use("/public",me.static(xs.join(__dirname,"../public"))),e.set("view engine","ejs"),e.set("views",xs.join(__dirname,"../views")),e.get("/",s.getHomepage.bind(s)),e.get("/session/:id",s.getSessionDetail.bind(s)),e.get("/session/:id/time-analyze",s.getTimeAnalysis.bind(s)),e.get("/session/:id/export",s.exportSession.bind(s)),e.get("/api/sessions/load-more",s.loadMoreSessions.bind(s)),e.get("/api/sessions",s.getSessions.bind(s)),e.get("/api/sessions/:id/events",s.getSessionEvents.bind(s)),e.get("/api/sessions/:id/timeline",s.getTimeline.bind(s)),e.get("/api/tags",r.getAllTags.bind(r)),e.get("/api/sessions/:id/tags",r.getSessionTags.bind(r)),e.put("/api/sessions/:id/tags",r.setSessionTags.bind(r)),e.get("/session/:id/share",n.shareSession.bind(n)),e.post("/session/import",(a,o,i)=>n.getUploadMiddleware()(a,o,i),n.importSession.bind(n)),e.post("/session/:id/insight",t.generateInsight.bind(t)),e.get("/session/:id/insight",t.getInsightStatus.bind(t)),e.delete("/session/:id/insight",t.deleteInsight.bind(t)),e.use(wr),e.use(Sr),e}As.exports=Cr});L();var vr=ks(),rt=z(),Dr=pe(),Ms=vr();module.exports=Ms;if(require.main===module){let d=Ms.listen(rt.PORT,()=>{console.log(`\u{1F680} Copilot Session Viewer running at http://localhost:${rt.PORT}`),console.log(`\u{1F527} Environment: ${rt.NODE_ENV}`),console.log(`\u26A1 Active processes: ${Dr.getActiveCount()}`)});process.on("SIGTERM",()=>{console.log("\u{1F4DB} SIGTERM received, closing server..."),d.close(()=>{console.log("\u2705 Server closed")})})}