@qiaolei81/copilot-session-viewer 0.3.6 → 0.3.8

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,35 +1,40 @@
1
- var b=(p,e)=>()=>(e||p((e={exports:{}}).exports,e),e.exports);var R=b((rn,We)=>{var ie=require("applicationinsights"),Q=require("fs"),ee=require("path"),Bt=require("crypto"),ze=require("os");function Wt(){let p=ee.join(ze.homedir(),".copilot-session-viewer"),e=ee.join(p,"analytics-id");try{return Q.readFileSync(e,"utf8").trim()}catch{let s=Bt.randomUUID();try{Q.mkdirSync(p,{recursive:!0}),Q.writeFileSync(e,s)}catch{}return s}}function Gt(){try{let p=[ee.join(__dirname,"..","package.json"),ee.join(__dirname,"package.json")];for(let e of p)try{return JSON.parse(Q.readFileSync(e,"utf8")).version}catch{}}catch{}return"unknown"}var Ve=process.env.NODE_ENV==="test",Be=process.env.DISABLE_TELEMETRY==="true"||Ve,Jt="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",C=null;if(Be)C=Ue(),console.log(Ve?"\u{1F4CA} Telemetry disabled (test environment)":"\u{1F4CA} Telemetry disabled (DISABLE_TELEMETRY=true)");else try{let p=process.env.APPLICATIONINSIGHTS_CONNECTION_STRING||Jt;ie.setup(p).setAutoDependencyCorrelation(!0).setAutoCollectRequests(!0).setAutoCollectPerformance(!0,!0).setAutoCollectExceptions(!0).setAutoCollectDependencies(!0).setAutoCollectConsole(!1).setUseDiskRetryCaching(!0).setSendLiveMetrics(!1).setDistributedTracingMode(ie.DistributedTracingModes.AI_AND_W3C).start(),C=ie.defaultClient;let e=Gt(),s=Wt();C.context.tags[C.context.keys.cloudRole]="copilot-session-viewer",C.context.tags[C.context.keys.cloudRoleInstance]=ze.hostname(),C.context.tags[C.context.keys.applicationVersion]=e,C.context.tags[C.context.keys.userId]=s,C.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(p){console.error("\u274C Failed to initialize Application Insights:",p.message),C=Ue()}function Ue(){return{trackEvent:()=>{},trackMetric:()=>{},trackException:()=>{},trackTrace:()=>{},trackDependency:()=>{},trackRequest:()=>{},flush:p=>{p&&p()}}}function Ht(p,e={}){C&&C.trackEvent&&C.trackEvent({name:p,properties:e})}function Kt(p,e,s={}){C&&C.trackMetric&&C.trackMetric({name:p,value:e,properties:s})}function Yt(p,e={}){C&&C.trackException&&C.trackException({exception:p,properties:e})}function Zt(){return new Promise(p=>{C&&C.flush?C.flush({callback:()=>p()}):p()})}We.exports={client:C,trackEvent:Ht,trackMetric:Kt,trackException:Yt,flush:Zt,isEnabled:!Be}});var L=b((an,Ge)=>{Ge.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 Ke=b((ln,He)=>{var ae=L(),{trackException:Xt,isEnabled:Je}=R(),Qt=(p,e,s)=>{p.setTimeout(ae.REQUEST_TIMEOUT_MS),s()},es=(p,e,s)=>{e.locals.telemetryEnabled=Je,e.locals.telemetryConnectionString=Je?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()},ts=(p,e,s)=>{if(ae.NODE_ENV==="development"){let t=["http://localhost:3838","http://127.0.0.1:3838"],n=p.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()},ss=(p,e,s,t)=>{console.error("Unhandled error:",p.stack),Xt(p,{url:e.url,method:e.method,statusCode:(p.status||500).toString(),userAgent:e.headers&&e.headers["user-agent"]||"unknown"});let n=p.status||500,o=ae.NODE_ENV==="development",r=o?p.message:"Internal server error";s.status(n).json({error:r,...o&&{stack:p.stack}})},ns=(p,e)=>{e.status(404).json({error:"Not found"})};He.exports={requestTimeout:Qt,developmentCors:ts,errorHandler:ss,notFoundHandler:ns,telemetryLocals:es}});var U=b((cn,Ye)=>{function os(p){let e=p.toJSON?p.toJSON():{};return{type:p.type,source:p.source,sourceName:e.sourceName||p.source,sourceBadgeClass:e.sourceBadgeClass||"source-unknown",summary:p.summary,model:p.selectedModel||p.model,repo:p.workspace?.repository,branch:p.workspace?.branch,cwd:p.workspace?.cwd,created:p.createdAt,updated:p.updatedAt,copilotVersion:p.copilotVersion,sessionStatus:p.sessionStatus}}function rs(p){return typeof p=="string"&&/^[a-zA-Z0-9_-]+$/.test(p)&&p.length<256}Ye.exports={buildMetadata:os,isValidSessionId:rs}});var Xe=b((un,Ze)=>{var is=require("path"),le=class p{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.selectedModel=t.selectedModel||null,this.sessionStatus=t.sessionStatus||"completed"}static fromDirectory(e,s,t,n,o,r,i,a,l,c,d){let u=n?.created_at?new Date(n.created_at):n?.startTime?new Date(n.startTime):t.birthtime,m=n?.updated_at?new Date(n.updated_at):n?.endTime?new Date(n.endTime):t.mtime;return new p(s,"directory",{directory:e,workspace:n,createdAt:u,updatedAt:m,summary:n?.summary||"No summary",hasEvents:o>0,eventCount:o,duration:r,isImported:i,hasInsight:a,copilotVersion:l,selectedModel:c,sessionStatus:d})}static fromFile(e,s,t,n,o,r,i,a,l){return new p(s,"file",{filePath:e,directory:is.dirname(e),createdAt:t.birthtime,updatedAt:t.mtime,summary:o||"Legacy session",hasEvents:!0,eventCount:n,duration:r,isImported:!1,hasInsight:!1,copilotVersion:i,selectedModel:a,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){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"}}};Ze.exports=le});var tt=b((dn,et)=>{var Qe=require("fs").promises,H=require("fs"),K=require("readline");async function as(p){try{return await Qe.access(p),!0}catch{return!1}}async function ls(p){try{let e=H.createReadStream(p,{encoding:"utf-8"}),s=K.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 ${p}:`,e.message),0}}async function cs(p){try{let s=(await Qe.readFile(p,"utf-8")).split(`
2
- `),t={};for(let n of s){let o=n.match(/^(\w+):\s*(.+)$/);o&&(t[o[1]]=o[2].trim())}return t}catch(e){return console.error(`Error parsing YAML ${p}:`,e.message),{}}}async function us(p,e=200){try{let s=H.createReadStream(p,{encoding:"utf-8"}),t=K.createInterface({input:s,crlfDelay:1/0}),n="",o=null,r=null,i=null,a=null,l=!1;for await(let d of t)if(d.trim())try{let u=JSON.parse(d);if(u.timestamp){let m=new Date(u.timestamp).getTime();isNaN(m)||(o||(o=m),r=m)}if(!n&&u.type==="user.message"){let m=u.data?.message||u.data?.content||u.data?.text||"";m&&(n=m.length>e?m.substring(0,e)+"...":m)}u.type==="session.end"&&(l=!0),u.type==="session.start"&&u.data?.copilotVersion&&!i&&(i=u.data.copilotVersion),(u.type==="session.start"||u.type==="session.model_change")&&!a&&(u.data?.selectedModel?a=u.data.selectedModel:u.data?.newModel?a=u.data.newModel:u.data?.model&&(a=u.data.model))}catch{}t.close(),s.destroy();let c=o&&r&&r>o?r-o:null;return{firstUserMessage:n||"",duration:c,copilotVersion:i||null,selectedModel:a||null,hasSessionEnd:l,lastEventTime:r,firstEventTime:o}}catch(s){return console.error(`Error reading session metadata from ${p}:`,s.message),{firstUserMessage:"",duration:null,copilotVersion:null,selectedModel:null,hasSessionEnd:!1,lastEventTime:null}}}async function ds(p,e=200){try{let s=H.createReadStream(p,{encoding:"utf-8"}),t=K.createInterface({input:s,crlfDelay:1/0});for await(let n of t)if(n.trim())try{let o=JSON.parse(n);if(o.type==="user.message"){let r=o.data?.message||o.data?.content||o.data?.text||"";if(r)return t.close(),s.destroy(),r.length>e?r.substring(0,e)+"...":r}}catch{}return""}catch{return""}}async function ps(p){try{let e=H.createReadStream(p,{encoding:"utf-8"}),s=K.createInterface({input:e,crlfDelay:1/0}),t=null,n=null;for await(let o of s)if(o.trim())try{let r=JSON.parse(o);if(r.timestamp){let i=new Date(r.timestamp).getTime();t||(t=i),n=i}}catch{}return t&&n&&n>=t?n-t:null}catch(e){return console.error(`Error calculating session duration for ${p}:`,e.message),null}}async function ms(p){try{let e=H.createReadStream(p,{encoding:"utf-8"}),s=K.createInterface({input:e,crlfDelay:1/0}),t=null,n=null;for await(let o of s)if(o.trim())try{let r=JSON.parse(o);if(r.type==="session.start"&&r.data&&(t=r.data.copilotVersion||null,n=r.data.selectedModel||null,n))return s.close(),e.destroy(),{copilotVersion:t,selectedModel:n};if(!n&&r.type==="session.model_change"&&r.data)return n=r.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 ${p}:`,e.message),{copilotVersion:null,selectedModel:null}}}function fs(p){return p===".DS_Store"||p.startsWith(".")}et.exports={fileExists:as,countLines:ls,parseYAML:cs,getFirstUserMessage:ds,getSessionDuration:ps,getSessionMetadata:ms,getSessionMetadataOptimized:us,shouldSkipEntry:fs}});var z=b((pn,st)=>{var ce=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")}};st.exports=ce});var de=b((mn,nt)=>{var gs=z(),ue=class extends gs{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 o=n.data?.toolCallId,r=t.toolCalls.find(i=>i.toolCallId===o);r||(r={toolCallId:o,events:[]},t.toolCalls.push(r)),r.events.push(n),n.type==="tool.execution_start"?(r.name=n.data?.toolName,r.arguments=n.data?.arguments):n.type==="tool.execution_complete"&&(r.result=n.data?.result,r.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 o=n.data?.toolCallId;t.set(o,{toolCallId:o,name:n.data?.toolName,arguments:n.data?.arguments,startEvent:n,completeEvent:null})}else if(n.type==="tool.execution_complete"){let o=n.data?.toolCallId,r=t.get(o);r&&(r.completeEvent=n,r.result=n.data?.result,r.exitCode=n.data?.exitCode,s.push(r))}return s}};nt.exports=ue});var me=b((fn,ot)=>{var hs=z(),pe=class extends hs{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(o=>o.type==="user");if(!s)return null;let n=e.find(o=>o.type==="assistant"&&o.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(r=>["user","assistant"].includes(r.type)&&r.type!=="file-history-snapshot"&&r.type!=="queue-operation"),n=new Map;for(let r of t)n.set(r.uuid,r);let o=t.filter(r=>r.type==="user"&&(!r.parentUuid||!n.has(r.parentUuid)));for(let r of o){let i={turnId:r.uuid,userMessage:{id:r.uuid,content:this._extractMessageContent(r.message),timestamp:r.timestamp},assistantMessages:[],toolCalls:[]};this._collectAssistantResponses(r.uuid,n,i),s.push(i)}return s}_collectAssistantResponses(e,s,t){for(let[n,o]of s.entries())if(o.parentUuid===e&&o.type==="assistant"){let r={id:o.uuid,messageId:o.message?.id,content:this._extractMessageContent(o.message),model:o.message?.model,timestamp:o.timestamp},i=this._extractToolUse(o.message);i.length>0&&(r.toolRequests=i,t.toolCalls.push(...i.map(a=>({toolCallId:a.id,name:a.name,arguments:a.input,parentUuid:o.uuid})))),t.assistantMessages.push(r),this._collectAssistantResponses(o.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 o of n)s.push({toolCallId:o.id,name:o.name,arguments:o.input,parentUuid:t.uuid,timestamp:t.timestamp,result:null,exitCode:null})}return s}};ot.exports=pe});var ge=b((gn,rt)=>{var ys=z(),fe=class extends ys{constructor(){super("pi-mono")}async parseSessionDir(e){let s=require("fs").promises,t=require("path");try{let o=(await s.readdir(e)).filter(d=>d.endsWith(".jsonl"));if(o.length===0)return null;o.sort().reverse();let r=t.join(e,o[0]),i=await this._readFirstLine(r);if(!i)return null;let a=JSON.parse(i);if(a.type!=="session")return console.warn(`Pi-Mono file ${r} doesn't start with session event`),null;let c=t.basename(e).replace(/^--/,"").replace(/--$/,"");return{id:a.id,type:"pi-mono",source:"pi-mono",cwd:a.cwd||c,createdAt:new Date(a.timestamp),updatedAt:new Date(a.timestamp),summary:`Pi-Mono: ${c}`,fileCount:o.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 o=s.createReadStream(e,{encoding:"utf-8"}),r=t.createInterface({input:o,crlfDelay:1/0});r.on("line",i=>{r.close(),o.destroy(),n(i.trim())}),r.on("close",()=>n(null))})}async parseEvents(e){let s=require("fs"),t=require("readline"),n=[],o=s.createReadStream(e,{encoding:"utf-8"}),r=t.createInterface({input:o,crlfDelay:1/0}),i=0;for await(let a of r){i++;let l=a.trim();if(l)try{let c=JSON.parse(l);n.push(c)}catch(c){console.error(`Error parsing Pi-Mono line ${i}:`,c.message)}}return n}};rt.exports=fe});var at=b((hn,it)=>{var Ss=z(),he=class extends Ss{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:o,v:r,i}=t;switch(n){case 0:s=r;break;case 1:o&&Array.isArray(o)&&this._applySet(s,o,r);break;case 2:o&&Array.isArray(o)&&this._applyPush(s,o,r,i);break;case 3:o&&Array.isArray(o)&&this._applyDelete(s,o);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 r=0;r<s.length-1;r++){let i=s[r];n[i]||(n[i]=typeof s[r+1]=="number"?[]:{}),n=n[i]}let o=s[s.length-1];n[o]=t}_applyPush(e,s,t,n){if(!e||s.length===0)return;let o=e;for(let a=0;a<s.length-1;a++){let l=s[a];o[l]||(o[l]=typeof s[a+1]=="number"?[]:{}),o=o[l]}let r=s[s.length-1];o[r]||(o[r]=[]);let i=o[r];if(!Array.isArray(i)){console.warn(`[VsCodeParser] Push target is not an array: ${s.join(".")}`);return}n!=null&&(i.length=n),t&&Array.isArray(t)&&t.length>0&&i.push(...t)}_applyDelete(e,s){if(!e||s.length===0)return;let t=e;for(let o=0;o<s.length-1;o++){let r=s[o];if(!t[r])return;t=t[r]}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]||{},o=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:o,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 o=n.timestamp?new Date(n.timestamp).toISOString():null,r=n.modelState?.completedAt?new Date(n.modelState.completedAt).toISOString():o,i=Array.isArray(n.response)?n.response:[],a=this._buildSubAgentNameMap(i),l=this._extractUserText(n.message);s.push({type:"user.message",id:n.requestId,timestamp:o,data:{message:l,content:l}}),s.push({type:"assistant.turn_start",id:`${n.requestId}-turn`,timestamp:o,parentId:n.requestId,data:{}});let c="",d=0,u=null,m=()=>{let f=c.trim().replace(/^`{3,}$/gm,"").trim();if(c="",!f)return;let g=u,w=g?a[g]||g.slice(0,8):null;s.push({type:"assistant.message",id:`${n.requestId}-text-${d}`,timestamp:r,parentId:n.requestId,data:{message:f,content:f,tools:[],subAgentId:g||null,subAgentName:w,parentToolCallId:null}})};for(let f of i)switch(d++,f.kind){case"thinking":{let g=f.content?.value||f.content||"";g&&(c+=g+`
4
- `);break}case"markdownContent":{let g=f.content?.value||f.content||"";g&&(c+=g+`
5
- `);break}case void 0:case null:{let g=f.value||"";g&&(c+=g);break}case"inlineReference":{let g=f.name||"";g&&(c+="`"+g+"`");break}case"toolInvocationSerialized":{m();let g=f.toolId==="runSubagent"?f.toolCallId:f.subAgentInvocationId;f.toolId==="runSubagent"&&(u=g),g&&(u=g);let w=this._normalizeTool(f);if(w){let _=g?a[g]||g.slice(0,8):null;s.push({type:"tool.invocation",id:w.id||`${n.requestId}-tool-${d}`,timestamp:r,parentId:n.requestId,data:{tool:w,subAgentId:g||null,subAgentName:_,parentToolCallId:g||null,badgeLabel:w.name,badgeClass:w.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-${d}`,timestamp:r,parentId:n.requestId,data:{tool:{type:"tool_use",id:`${n.requestId}-edit-${d}`,name:"textEdit",startTime:o,endTime:o,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 o=t.toolSpecificData?.agentName;if(o){s[n]=o;continue}let r=t.invocationMessage,i=typeof r=="string"?r:r&&typeof r=="object"&&r.value||"";if(i){s[n]=i;continue}let a=i.match(/agents\/([^/\]]+?)\.agent\.md/);if(a){s[n]=a[1];continue}let l=t.resultDetails,c=Array.isArray(l)?l:l?[l]:[];for(let d of c){if(typeof d!="object")continue;if(a=(d.fsPath||d.path||"").match(/agents\/([^/]+?)\.agent\.md/),a){s[n]=a[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,o=e.isConfirmed===!1;if(!n&&(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);n=l.length>0?l.join(`
6
- `):e.generatedTitle||null}else n=e.generatedTitle||null;if(Object.keys(t).length===0&&e.invocationMessage){let a=e.invocationMessage,l=typeof a=="string"?a:a&&typeof a=="object"&&a.value||"";l&&(t={description:l})}let r=a=>{if(!a||typeof a!="object")return a;let l=a.fsPath||a.path||a.external||"";return l?l.replace(/.*\//,""):JSON.stringify(a)},i=a=>{if(!a||typeof a!="object")return a;let l={};for(let[c,d]of Object.entries(a))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]=r(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=i(t)),{type:"tool_use",id:e.toolCallId,name:e.toolId||"unknown",startTime:null,endTime:null,status:o?"error":e.isComplete?"completed":"pending",input:t,result:typeof n=="string"?n:JSON.stringify(n),error:o?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)}};it.exports=he});var ct=b((yn,lt)=>{var ye=de(),Se=me(),we=ge(),_e=class{constructor(){this.parsers=[new ye,new Se,new we],this.parserMap={copilot:new ye,claude:new Se,"pi-mono":new we}}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 ye?"copilot":s instanceof Se?"claude":s instanceof we?"pi-mono":"unknown":null}};lt.exports=_e});var Ie=b((Sn,ut)=>{var ws=z(),_s=de(),Is=me(),Ts=ge(),Es=at(),Cs=ct();ut.exports={BaseSessionParser:ws,CopilotSessionParser:_s,ClaudeSessionParser:Is,PiMonoParser:Ts,VsCodeParser:Es,ParserFactory:Cs}});var Ee=b((wn,mt)=>{var E=require("fs").promises,S=require("path"),P=require("os"),{fileURLToPath:dt}=require("url"),F=Xe(),{fileExists:Y,countLines:V,parseYAML:bs,getSessionMetadataOptimized:pt,shouldSkipEntry:te}=tt(),{ParserFactory:js}=Ie();function vs(){let p;switch(P.platform()){case"win32":p=S.join(process.env.APPDATA||S.join(P.homedir(),"AppData","Roaming"));break;case"darwin":p=S.join(P.homedir(),"Library","Application Support");break;case"linux":p=S.join(P.homedir(),".config");break;default:p=S.join(P.homedir(),".config")}return[S.join(p,"Code","User","workspaceStorage"),S.join(p,"Code - Insiders","User","workspaceStorage")]}var Te=class{constructor(e){typeof e=="string"?this.sources=[{type:"copilot",dir:e}]:Array.isArray(e)?this.sources=e:this.sources=[{type:"copilot",dir:process.env.COPILOT_SESSION_DIR||process.env.SESSION_DIR||S.join(P.homedir(),".copilot","session-state")},{type:"claude",dir:process.env.CLAUDE_SESSION_DIR||S.join(P.homedir(),".claude","projects")},{type:"pi-mono",dir:process.env.PI_MONO_SESSION_DIR||S.join(P.homedir(),".pi","agent","sessions")},{type:"vscode",...process.env.VSCODE_WORKSPACE_STORAGE_DIR?{dir:process.env.VSCODE_WORKSPACE_STORAGE_DIR}:(()=>{let s=vs();return{dir:s[0],dirCandidates:s}})()}],this.parserFactory=new js,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(o=>(this._cache.set(s,{data:o,timestamp:Date.now()}),this._pendingScans.delete(s),o)).catch(o=>{throw this._pendingScans.delete(s),o});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 o=await this._scanSource(n);s.push(...o)}catch(o){console.error(`Error reading ${n.type} sessions from ${n.dir}:`,o.message)}return this._sortByUpdatedAt(this._deduplicateSessions(s))}_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 _resolveSourceDir(e){if(!e.dirCandidates)return e.dir;for(let s of e.dirCandidates)try{return await E.access(s),e.dir=s,s}catch{}return null}async _scanSource(e){if(e.dirCandidates&&!await this._resolveSourceDir(e))return console.warn(`No ${e.type} directory found (tried: ${e.dirCandidates.join(", ")})`),[];try{await E.access(e.dir)}catch{return console.warn(`Source directory not found: ${e.dir}`),[]}let t=(await E.readdir(e.dir)).filter(o=>!te(o)).map(async o=>{let r=S.join(e.dir,o),i=await E.stat(r);if(e.type==="copilot"){if(i.isDirectory())return this._createDirectorySession(o,r,i,"copilot");if(o.endsWith(".jsonl"))return this._createFileSession(o,r,i,"copilot")}else if(e.type==="claude"){if(i.isDirectory())return this._scanClaudeProjectDir(r,o)}else if(e.type==="pi-mono"){if(i.isDirectory())return this._scanPiMonoDir(r,o)}else if(e.type==="vscode"&&i.isDirectory())return this._scanVsCodeWorkspaceDir(r);return null});return(await Promise.allSettled(t)).filter(o=>o.status==="fulfilled"&&o.value!==null&&o.value!==void 0).map(o=>o.value).flat()}async _scanClaudeProjectDir(e,s){try{let t=await E.readdir(e),n=[];for(let o of t){if(te(o))continue;let r=S.join(e,o),i=await E.stat(r);if(i.isFile()&&o.endsWith(".jsonl")){let a=await this._createClaudeSession(o,r,i,s);a&&n.push(a)}if(i.isDirectory()){let a=S.join(r,"subagents");try{if((await E.stat(a)).isDirectory()){let c=await this._createClaudeSubagentsSession(o,r,i,s);c&&n.push(c)}}catch{}}}return n}catch(t){return console.error(`Error scanning Claude project dir ${e}:`,t.message),[]}}async _createClaudeSession(e,s,t,n){let o=e.replace(".jsonl",""),r=await V(s);console.log(`[DEBUG] _createClaudeSession: ${e}, events: ${r}`);try{let l=(await E.readFile(s,"utf-8")).trim().split(`
7
- `).filter(w=>w.trim()).map(w=>{try{return JSON.parse(w)}catch{return null}}).filter(w=>w!==null);console.log(`[DEBUG] Parsed ${l.length} events from ${e}`);let c=l.some(w=>w.type==="assistant"||w.type==="user"),d=l.some(w=>w.type==="assistant.message"||w.type==="user.message");if(console.log(`[DEBUG] ${e}: hasClaudeCoreEvents=${c}, hasCopilotCoreEvents=${d}`),!c&&d)return console.warn(`File ${s} contains only Copilot core events, skipping as Claude session`),null;if(!c)return console.warn(`File ${s} has no Claude core events (assistant/user), skipping`),null;if(console.log(`[DEBUG] ${e} passed validation, creating session...`),this.parserFactory.getParserType(l)!=="claude")return null;let m=this.parserFactory.parse(l),f=m.metadata||{},g=n.replace(/^-/,"/").replace(/-/g,"/");return new F(o,"file",{source:"claude",filePath:s,directory:S.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:r>0,eventCount:r,duration:null,isImported:!1,hasInsight:!1,copilotVersion:f.version,selectedModel:f.model,sessionStatus:"completed"})}catch(i){return console.error(`Error creating Claude session ${o}:`,i.message),null}}async findById(e){if(te(e))return null;for(let s of this.sources){let t=null;if(s.type==="copilot")t=await this._findCopilotSession(e,s.dir);else if(s.type==="claude")t=await this._findClaudeSession(e,s.dir);else if(s.type==="pi-mono")t=await this._findPiMonoSession(e,s.dir);else if(s.type==="vscode"){let n=s.dirCandidates?await this._resolveSourceDir(s):s.dir;n&&(t=await this._findVsCodeSession(e,n))}if(t)return t}return null}async _findCopilotSession(e,s){try{let t=S.join(s,e),n=await E.stat(t);if(n.isDirectory())return await this._createDirectorySession(e,t,n,"copilot")}catch{}try{let t=S.join(s,`${e}.jsonl`),n=await E.stat(t);if(n.isFile())return await this._createFileSession(`${e}.jsonl`,t,n,"copilot")}catch{}return null}async _findClaudeSession(e,s){try{let t=await E.readdir(s);for(let n of t){let o=S.join(s,n),r=S.join(o,`${e}.jsonl`);try{let a=await E.stat(r);if(a.isFile()){console.log(`[DEBUG] Found file: ${r}`);let l=await this._createClaudeSession(`${e}.jsonl`,r,a,n);if(l)return console.log("[DEBUG] File validated as Claude session, returning"),l;console.log("[DEBUG] File validation failed, checking directory...")}}catch(a){console.log(`[DEBUG] File not found: ${r}, error: ${a.message}`)}let i=S.join(o,e);console.log(`[DEBUG] Checking directory: ${i}`);try{let a=await E.stat(i);if(a.isDirectory()){console.log("[DEBUG] Directory exists, checking for subagents...");let l=S.join(i,"subagents");try{if((await E.stat(l)).isDirectory()){console.log("[DEBUG] Found subagents directory, creating session...");let d=await this._createClaudeSubagentsSession(e,i,a,n);return console.log("[DEBUG] Created subagents session:",d?"SUCCESS":"FAILED"),d}}catch(c){console.log(`[DEBUG] No subagents directory: ${c.message}`)}}}catch(a){console.log(`[DEBUG] Directory not found: ${a.message}`)}}}catch(t){console.error(`[DEBUG] Projects dir error: ${t.message}`)}return console.log(`[DEBUG] Session ${e} not found in any project`),null}async _findPiMonoSession(e,s){try{let t=await E.readdir(s);for(let n of t){let o=S.join(s,n);try{let i=(await E.readdir(o)).find(a=>a.includes(`_${e}.jsonl`));if(i){let a=S.join(o,i),l=await E.stat(a),c=await this._readFirstLine(a);if(c){let d=JSON.parse(c);if(d.type==="session"){let u=n.replace(/^--/,"").replace(/--$/,""),m=await V(a);return new F(e,"directory",{source:"pi-mono",filePath:a,directory:o,workspace:{cwd:d.cwd||u},createdAt:new Date(d.timestamp),updatedAt:new Date(l.mtime),summary:`Pi-Mono: ${S.basename(d.cwd||u)}`,hasEvents:m>0,eventCount:m,duration:null,sessionStatus:"completed"})}}}}catch{}}}catch(t){console.error(`Error searching Pi-Mono sessions: ${t.message}`)}return null}async _findVsCodeSession(e,s){try{let t=await E.readdir(s),n=[];for(let o of t){let r=S.join(s,o,"chatSessions");try{let a=(await E.readdir(r)).find(l=>l===`${e}.json`||l===`${e}.jsonl`||l.replace(/\.jsonl?$/,"")===e);if(a){let l=S.join(r,a),c=await E.stat(l),d=await E.readFile(l,"utf-8"),u;if(a.endsWith(".jsonl")){if(u=this._parseVsCodeJsonl(d),!u)continue}else u=JSON.parse(d);let m=u.requests||[];if(m.length===0)continue;let f=await this._resolveVsCodeWorkspacePath(S.join(s,o)),g={...c,filePath:l};n.push(this._buildVsCodeSession(e,m,u,g,o,f||S.join(s,o)))}}catch{}}if(n.length>0)return n.sort((o,r)=>(r.updatedAt?.getTime?.()??0)-(o.updatedAt?.getTime?.()??0)),n[0]}catch(t){console.error(`[VSCode findById] Error searching VSCode sessions: ${t.message}`,t.stack)}return console.log(`[VSCode findById] Session ${e} not found in vscode sessions`),null}async _createClaudeSubagentsSession(e,s,t,n){try{let o=S.join(s,"subagents"),i=(await E.readdir(o)).filter(g=>g.startsWith("agent-")&&g.endsWith(".jsonl"));if(i.length===0)return null;let a=0;for(let g of i){let w=S.join(o,g);a+=await V(w)}let l=S.join(o,i[0]),d=(await E.readFile(l,"utf-8")).trim().split(`
8
- `).filter(g=>g.trim()),u=d.length>0?JSON.parse(d[0]):null,m={cwd:u?.cwd||n,version:u?.version,model:u?.message?.model,startTime:u?.timestamp},f=n.replace(/^-/,"/").replace(/-/g,"/");return new F(e,"directory",{source:"claude",directory:s,workspace:{summary:`Claude session (${i.length} sub-agents)`,cwd:m.cwd||f},createdAt:m.startTime||t.birthtime,updatedAt:t.mtime,summary:u?.message?.content?.substring(0,100)||"Sub-agent tasks",hasEvents:a>0,eventCount:a,duration:null,isImported:!1,hasInsight:!1,copilotVersion:m.version,selectedModel:m.model,sessionStatus:"completed"})}catch(o){return console.error(`Error creating Claude subagents session ${e}:`,o.message),null}}async _createDirectorySession(e,s,t,n="copilot"){let o=S.join(s,"workspace.yaml"),r=S.join(s,"events.jsonl"),i=S.join(s,".imported"),a=S.join(s,`${e}.agent-review.md`),l=await Y(o)?await bs(o):{summary:e,repo:"unknown"},c=await Y(r)?await V(r):0,d=await Y(i),u=await Y(a),m=null,f=null,g=null,w="completed";if(await Y(r)){let y=await pt(r);if(m=y.duration,f=y.copilotVersion,g=y.selectedModel,w=this._computeSessionStatus(y),!l.summary&&y.firstUserMessage&&(l.summary=y.firstUserMessage),y.lastEventTime){let j=new Date(y.lastEventTime).getTime(),v=new Date(t.mtime).getTime();j>v&&(t={...t,mtime:new Date(j)})}}let _=F.fromDirectory(s,e,t,l,c,m,d,u,f,g,w);return _.source=n,_}async _createFileSession(e,s,t,n="copilot"){let o=e.replace(".jsonl",""),r=await V(s),i=await pt(s),a=this._computeSessionStatus(i),l=F.fromFile(s,o,t,r,i.firstUserMessage,i.duration,i.copilotVersion,i.selectedModel,a);return l.source=n,l}_computeSessionStatus(e){return e.hasSessionEnd?"completed":e.lastEventTime!==null&&e.lastEventTime!==void 0&&Date.now()-e.lastEventTime<3e5?"wip":"completed"}async _scanPiMonoDir(e,s){try{console.log(`[PI-MONO] Scanning directory: ${e}`);let n=(await E.readdir(e)).filter(r=>r.endsWith(".jsonl"));if(console.log(`[PI-MONO] Found ${n.length} .jsonl files in ${s}`),n.length===0)return[];let o=[];n.sort().reverse();for(let r of n){let i=S.join(e,r),a=await E.stat(i),l=r.match(/_([a-f0-9-]+)\.jsonl$/);if(!l){console.log(`[PI-MONO] Skipping ${r}: no UUID match`);continue}let c=l[1],d=await this._readFirstLine(i);if(!d){console.log(`[PI-MONO] Skipping ${r}: no first line`);continue}try{let u=JSON.parse(d);if(u.type!=="session"){console.log(`[PI-MONO] Skipping ${r}: first event type is ${u.type}, not 'session'`);continue}let m=await V(i),f=s.replace(/^--/,"").replace(/--$/,""),g=new F(c,"directory",{source:"pi-mono",directory:e,workspace:{cwd:u.cwd||f},createdAt:new Date(u.timestamp),updatedAt:new Date(a.mtime),summary:`Pi-Mono: ${S.basename(u.cwd||f)}`,hasEvents:m>0,eventCount:m,duration:null,sessionStatus:"completed"});console.log(`[PI-MONO] Created session: ${c} from ${r}`),o.push(g)}catch(u){console.error(`[PI-MONO] Error parsing session ${r}:`,u.message)}}return console.log(`[PI-MONO] Total sessions found in ${s}: ${o.length}`),o}catch(t){return console.error(`[PI-MONO] Error scanning dir ${e}:`,t.message),[]}}_parseVsCodeJsonl(e){let s=e.split(`
9
- `).filter(o=>o.trim());if(s.length===0)return null;let t=JSON.parse(s[0]),n=t.v||t;for(let o=1;o<s.length;o++)try{let r=JSON.parse(s[o]),i=r.k||[],a=r.v;if(r.kind===2&&Array.isArray(a)){let l=n;for(let d=0;d<i.length-1;d++){let u=i[d];typeof u=="number"||l[u]||(l[u]={}),l=l[u]}let c=i[i.length-1];if(c!==void 0){l[c]||(l[c]=[]);let d=l[c],u=r.i;u==null?d.push(...a):d.splice(u,0,...a)}else{let d=r.i;d==null&&n.push?.(...a)}}else if(r.kind===1&&i.length>0){let l=n;for(let d=0;d<i.length-1;d++){let u=i[d];typeof u=="number"||l[u]||(l[u]={}),l=l[u]}let c=i[i.length-1];l[c]=a}}catch{}return n}async _resolveVsCodeWorkspacePath(e){try{let s=S.join(e,"workspace.json"),t=await E.readFile(s,"utf-8"),n=JSON.parse(t);if(n.folder)return dt(n.folder);if(n.workspace){let o=dt(n.workspace);try{let r=await E.readFile(o,"utf-8"),i=JSON.parse(r);if(Array.isArray(i.folders)&&i.folders.length>0){let a=S.dirname(o);return S.resolve(a,i.folders[0].path)}}catch{}}}catch{}return null}async _scanVsCodeWorkspaceDir(e){let s=S.join(e,"chatSessions");try{await E.access(s)}catch{return[]}let t=S.basename(e),n=await this._resolveVsCodeWorkspacePath(e),r=(await E.readdir(s)).filter(a=>(a.endsWith(".json")||a.endsWith(".jsonl"))&&!te(a));if(r.length===0)return[];let i=[];for(let a of r){let l=S.join(s,a);try{let c=await E.stat(l),d=await E.readFile(l,"utf-8"),u;if(a.endsWith(".jsonl")){if(u=this._parseVsCodeJsonl(d),!u)continue}else u=JSON.parse(d);let m=u.sessionId||S.basename(a).replace(/\.jsonl?$/,""),f=u.requests||[];if(f.length===0)continue;let g={...c,filePath:l},w=this._buildVsCodeSession(m,f,u,g,t,n||e);i.push(w)}catch{}}return i}_buildVsCodeSession(e,s,t,n,o,r){let i=s[0],a=s[s.length-1],l=t.creationDate?new Date(t.creationDate):i.timestamp?new Date(i.timestamp):n.birthtime,c=a.timestamp?new Date(a.timestamp):null,d=t.lastMessageDate?new Date(t.lastMessageDate):c||n.mtime,m=this._extractLastTerminalTimestamp(s)||c||d,f=Date.now()-m.getTime()<900*1e3,g=this._extractVsCodeUserText(i.message),w=s.reduce((_,y)=>_+(y.response||[]).filter(j=>j.kind==="toolInvocationSerialized").length,0);return new F(e,"file",{source:"vscode",filePath:n.filePath,workspaceHash:o,createdAt:l,updatedAt:m,summary:g?g.slice(0,120):`VSCode chat (${s.length} requests)`,hasEvents:!0,eventCount:s.reduce((_,y)=>_+(y.response||[]).length,0)+s.length*2+1,duration:m.getTime()-l.getTime(),sessionStatus:f?"wip":"completed",selectedModel:i.modelId||null,agentId:i.agent?.id||"vscode-copilot",toolCount:w,copilotVersion:i.agent?.extensionVersion||null,workspace:{cwd:r}})}_extractLastTerminalTimestamp(e){let s=0;function t(n){if(!(!n||typeof n!="object")){if(Array.isArray(n)){n.forEach(t);return}if(n.terminalCommandState&&typeof n.terminalCommandState.timestamp=="number"){let o=n.terminalCommandState.timestamp;o>1e12&&o<9999999999999&&o>s&&(s=o)}for(let o of Object.values(n))t(o)}}for(let n of e)t(n.response);return s>0?new Date(s):null}_extractVsCodeUserText(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(""):"":""}async _readFirstLine(e){let s=require("fs"),t=require("readline");return new Promise((n,o)=>{let r=s.createReadStream(e,{encoding:"utf-8"}),i=t.createInterface({input:r,crlfDelay:1/0}),a=!1;i.on("line",l=>{a||(a=!0,i.close(),n(l.trim()))}),i.on("close",()=>{a||n(null)}),i.on("error",l=>{a||(a=!0,o(l))}),r.on("error",l=>{a||(a=!0,i.close(),o(l))})})}_sortByUpdatedAt(e){return e.sort((s,t)=>new Date(t.updatedAt)-new Date(s.updatedAt))}};mt.exports=Te});var gt=b((_n,ft)=>{var Ce=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),o=e._startTime||t,r=e._matched?e._endTime||t:null;return{type:"tool_use",id:e.id,name:e.name,startTime:o,endTime:r,status:n,input:e.input||{},result:e.result||null,error:e.error||null,metadata:{source:s,matched:e._matched,duration:this._computeDuration(o,r)}}}if(e.name&&e.status){let n=t,o=e.status==="success"?"completed":e.status,r=o==="completed"||o==="error"?t:null;return{id:e.id||this._generateToolId(),name:e.name,startTime:n,endTime:r,status:o,input:e.input||{},result:e.isError?null:e.result||null,error:e.isError?e.result:null,metadata:{source:s,duration:this._computeDuration(n,r)}}}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 o=n.getTime()-t.getTime();return o>=0?o: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)}};ft.exports=Ce});var je=b((In,wt)=>{var D=require("fs"),x=require("path"),ht=require("readline"),{isValidSessionId:yt,buildMetadata:xs}=U(),St=Ee(),As=gt(),be=class{constructor(e){e?(this.SESSION_DIR=e,this.sessionRepository=new St(e)):this.sessionRepository=new St,this.eventNormalizer=new As}async getAllSessions(e=null){return(await this.sessionRepository.findAll(e)).map(t=>t.toJSON())}async getPaginatedSessions(e=1,s=20,t=null){let o=(await this.sessionRepository.findAll(t)).map(l=>l.toJSON()),r=(e-1)*s,i=r+s;return{sessions:o.slice(r,i),totalSessions:o.length,currentPage:e,totalPages:Math.ceil(o.length/s),hasNextPage:i<o.length,hasPrevPage:e>1}}async getSessionById(e){return yt(e)?(await this.getAllSessions()).find(t=>t.id===e):null}async getSessionEvents(e,s=null){if(!yt(e))return s?{events:[],total:0}:[];let t=await this.sessionRepository.findById(e);if(!t)return s?{events:[],total:0}:[];let n;if(t.source==="copilot")if(this.SESSION_DIR){let r=x.join(this.SESSION_DIR,e);try{(await D.promises.stat(r)).isDirectory()?n=x.join(r,"events.jsonl"):n=x.join(this.SESSION_DIR,`${e}.jsonl`)}catch{n=x.join(this.SESSION_DIR,`${e}.jsonl`)}}else{let r=this.sessionRepository.sources.find(a=>a.type==="copilot");if(!r)return[];let i=x.join(r.dir,e);try{(await D.promises.stat(i)).isDirectory()?n=x.join(i,"events.jsonl"):n=x.join(r.dir,`${e}.jsonl`)}catch{n=x.join(r.dir,`${e}.jsonl`)}}else if(t.source==="claude"){let r=this.sessionRepository.sources.find(i=>i.type==="claude");if(!r)return[];if(t.type!=="directory")try{let i=await D.promises.readdir(r.dir);for(let a of i){let l=x.join(r.dir,a,`${e}.jsonl`);try{await D.promises.access(l),n=l;break}catch{}}}catch(i){return console.error("Error searching Claude projects:",i),[]}}else if(t.source==="pi-mono"){let r=this.sessionRepository.sources.find(i=>i.type==="pi-mono");if(!r)return[];try{let i=await D.promises.readdir(r.dir);for(let a of i){let l=x.join(r.dir,a);try{let d=(await D.promises.readdir(l)).find(u=>u.includes(`_${e}.jsonl`));if(d){n=x.join(l,d);break}}catch{}}}catch(i){return console.error("Error searching Pi-Mono sessions:",i),[]}}else if(t.source==="vscode"){let{VsCodeParser:r}=Ie(),i=new r;try{let a=await D.promises.readFile(t.filePath,"utf-8"),c=a.trim().split(`
10
- `).filter(m=>m.trim()).map(m=>{try{return JSON.parse(m)}catch{return null}}).filter(m=>m!==null);if(c.length===0)return[];let d;if(i.canParse(c))d=i.parseJsonl(c);else{let m=JSON.parse(a);d=i.parseVsCode(m)}let u=this._expandVsCodeEvents(d.allEvents);if(u.length>0)try{let m=await D.promises.stat(t.filePath),f=new Date(m.mtime).toISOString(),g=u[u.length-1];if(g&&g.timestamp){let w=new Date(g.timestamp).getTime(),y=(new Date(f).getTime()-w)/1e3;y>10&&(g.timestamp=f,console.log(`[VSCode] Updated session ${t.id} end time to file mtime (${y.toFixed(0)}s difference)`))}}catch(m){console.error("[VSCode] Error getting file mtime:",m)}return u=this._expandVsCodeToTimelineFormat(u),u}catch(a){return console.error("Error reading VSCode session:",a),[]}}let o=[];if(n)try{await D.promises.access(n);let r=D.createReadStream(n,{encoding:"utf-8"}),i=ht.createInterface({input:r,crlfDelay:1/0}),a=0,l=[];for await(let d of i){let u=d.trim();if(u)try{let m=JSON.parse(u);m._fileIndex=a,l.push(m)}catch(m){console.error(`Error parsing line ${a+1}:`,m.message)}a++}o=l,o.sort((d,u)=>{let m=d.timestamp?new Date(d.timestamp).getTime():0,f=u.timestamp?new Date(u.timestamp).getTime():0;return m!==f?m-f:d._fileIndex-u._fileIndex}),o=o.map(d=>this._normalizeEvent(d,t.source)),t.source==="copilot"?this._matchCopilotToolCalls(o):t.source==="claude"&&this._matchClaudeToolResults(o)}catch(r){console.error("Error reading main events file:",r)}if(await this._mergeSubAgentEvents(o,n,e,t.source),t.source==="copilot"?(this._matchCopilotToolCalls(o),o=this._expandCopilotToTimelineFormat(o)):t.source==="claude"?(this._matchClaudeToolResults(o),o=this._expandClaudeToTimelineFormat(o)):t.source==="pi-mono"&&this._mergePiMonoToolResults(o),o=o.filter(r=>r.timestamp||r.snapshot?.timestamp?!0:(console.warn("[SessionService] Filtered event without timestamp:",r.type,r.id||r._fileIndex),!1)),o.forEach(r=>{r._fileIndex===999999&&r.timestamp&&delete r._fileIndex}),o=this.eventNormalizer.normalizeEvents(o,t.source),s&&typeof s.limit=="number"&&typeof s.offset=="number"){let r=o.length;return{events:o.slice(s.offset,s.offset+s.limit),total:r}}return o}async _mergeSubAgentEvents(e,s,t,n){let o;if(n==="claude"){let r=this.sessionRepository.sources.find(i=>i.type==="claude");if(!r)return;try{let i=await D.promises.readdir(r.dir);for(let a of i){let l=x.join(r.dir,a,t,"subagents");try{if((await D.promises.stat(l)).isDirectory()){o=l;break}}catch{}}}catch(i){console.error("Error searching Claude subagents:",i);return}}else if(n==="copilot"&&s){let r=x.dirname(s);x.basename(s)==="events.jsonl"?o=x.join(r,"subagents"):o=x.join(r,t,"subagents")}if(o){try{if(!(await D.promises.stat(o)).isDirectory())return}catch{return}try{let i=(await D.promises.readdir(o)).filter(a=>a.startsWith("agent-")&&a.endsWith(".jsonl"));if(i.length===0)return;for(let a of i){let l=a.replace(".jsonl",""),c=x.join(o,a);try{let d=D.createReadStream(c,{encoding:"utf-8"}),u=ht.createInterface({input:d,crlfDelay:1/0}),m=[];for await(let A of u){let $=A.trim();$&&m.push($)}if(m.length===0)continue;let f=l.replace("agent-",""),g=f.toUpperCase(),w=`Sub-agent ${l}`;try{let A=JSON.parse(m[0]);if(A.agentId&&(f=A.agentId,g=`agent-${A.agentId}`),A.message?.content){let $=typeof A.message.content=="string"?A.message.content:JSON.stringify(A.message.content);w=$.length>100?$.slice(0,100)+"...":$}}catch{}let _=m.map((A,$)=>{try{let J=JSON.parse(A);return J._fileIndex=1e6+$,J._subagent={id:l,name:f},J}catch(J){return console.error(`Error parsing sub-agent ${l} line ${$+1}:`,J.message),null}}).filter(A=>A!==null);if(_.length===0)continue;let y=_.map(A=>this._normalizeEvent(A,n)),j=y[0],v=y[y.length-1],q=j.timestamp||new Date().toISOString(),oe=v.timestamp||new Date().toISOString(),re={type:"subagent.started",id:`${l}-start`,timestamp:q,_fileIndex:j._fileIndex-1,_subagent:{id:l,name:f},data:{toolCallId:l,agentName:f,agentDisplayName:g,agentDescription:w}},Le={type:"subagent.completed",id:`${l}-end`,timestamp:oe,_fileIndex:v._fileIndex+1,_subagent:{id:l,name:f},data:{toolCallId:l,result:`Sub-agent ${g} completed`}};e.push(re,...y,Le)}catch(d){console.error(`Error reading sub-agent ${l}:`,d)}}e.sort((a,l)=>{let c=a.timestamp?new Date(a.timestamp).getTime():0,d=l.timestamp?new Date(l.timestamp).getTime():0;return c!==d?c-d:a._fileIndex-l._fileIndex})}catch(r){console.error("Error processing sub-agents:",r)}}}_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(o=>o?.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 o=s.get(n.id);return o?{...n,result:o.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(o=>o.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 o=n.data.tools,r=[],i=n.id,a=!0;for(;a&&r.length<o.length;){a=!1;for(let l of e)if(l.type==="message"&&l.data.role==="toolResult"&&l.parentId===i&&!r.includes(l)){r.push(l),i=l.id,a=!0;break}}r.forEach((l,c)=>{if(c<o.length){let d=o[c];d.result=l.data.result,d.resultId=l.id,d.status="completed",s.add(l.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 o=n.data.tools,r=[],i=n.id,a=!0;for(;a&&r.length<o.length;){a=!1;for(let l of e)if(l.type==="tool.result"&&l.parentId===i&&!r.includes(l)){r.push(l),i=l.id,a=!0;break}}r.forEach((l,c)=>{if(c<o.length){let d=o[c];d.status="completed",d._matched=!0,d.result=l.data.result,d.resultId=l.id,s.add(l.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)`)}_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 o=s.get(n);o.complete=t,o.result=t.data?.result,o.status=t.data?.error?"error":"completed",o.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(o=>{let r=o.toolCallId;if(s.has(r)){let i=s.get(r);n.push({type:"tool_use",id:r,name:o.name||i.name,input:o.arguments||i.input,result:i.result,status:i.status||"running",error:i.error,_matched:!!i.complete,_startTime:i.start?.timestamp,_endTime:i.complete?.timestamp})}else n.push({type:"tool_use",id:r,name:o.name,input:o.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 o=(s||"").split(".")[0]||"unknown",i={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"}}[o]||{label:o.toUpperCase(),class:"badge-info"};e.data.badgeLabel=i.label,e.data.badgeClass=i.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||"",o=n.match(/<system_notification>([\s\S]*?)<\/system_notification>/);return t.data.message=o?o[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(o=>o.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(o=>o.type==="text");n.length>0&&(t.message={role:"assistant",content:n.map(o=>o.text).join(`
11
- `)})}return e.type==="assistant.message"&&e.data?.content&&e.data.content.trim()&&(t.data.message=e.data.content),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 o=n.content.filter(r=>r.type==="text");if(o.length>0&&(t.data.message=o.map(r=>r.text).join(`
12
- `)),n.role==="assistant"){let r=n.content.filter(i=>i.type==="toolCall");r.length>0&&(t.data.tools=r.map(i=>({type:"tool_use",id:i.id,name:i.name,input:i.arguments})))}n.role==="toolResult"&&(t.data.result=o.map(r=>r.text).join(`
1
+ var w=(p,e)=>()=>(e||p((e={exports:{}}).exports,e),e.exports);var U=w((br,dt)=>{var ge=require("applicationinsights"),ie=require("fs"),le=require("path"),$s=require("crypto"),ct=require("os");function Os(){let p=le.join(ct.homedir(),".copilot-session-viewer"),e=le.join(p,"analytics-id");try{return ie.readFileSync(e,"utf8").trim()}catch{let s=$s.randomUUID();try{ie.mkdirSync(p,{recursive:!0}),ie.writeFileSync(e,s)}catch{}return s}}function Ps(){try{let p=[le.join(__dirname,"..","package.json"),le.join(__dirname,"package.json")];for(let e of p)try{return JSON.parse(ie.readFileSync(e,"utf8")).version}catch{}}catch{}return"unknown"}var ut=process.env.DISABLE_TELEMETRY==="true",Rs="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(ut)E=lt(),console.log("\u{1F4CA} Telemetry disabled (DISABLE_TELEMETRY=true)");else try{let p=process.env.APPLICATIONINSIGHTS_CONNECTION_STRING||Rs;ge.setup(p).setAutoDependencyCorrelation(!0).setAutoCollectRequests(!0).setAutoCollectPerformance(!0,!0).setAutoCollectExceptions(!0).setAutoCollectDependencies(!0).setAutoCollectConsole(!1).setUseDiskRetryCaching(!0).setSendLiveMetrics(!1).setDistributedTracingMode(ge.DistributedTracingModes.AI_AND_W3C).start(),E=ge.defaultClient;let e=Ps(),s=Os();E.context.tags[E.context.keys.cloudRole]="copilot-session-viewer",E.context.tags[E.context.keys.cloudRoleInstance]=ct.hostname(),E.context.tags[E.context.keys.applicationVersion]=e,E.context.tags[E.context.keys.userId]=s,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(p){console.error("\u274C Failed to initialize Application Insights:",p.message),E=lt()}function lt(){return{trackEvent:()=>{},trackMetric:()=>{},trackException:()=>{},trackTrace:()=>{},trackDependency:()=>{},trackRequest:()=>{},flush:p=>{p&&p()}}}function qs(p,e={}){E&&E.trackEvent&&E.trackEvent({name:p,properties:e})}function Fs(p,e,s={}){E&&E.trackMetric&&E.trackMetric({name:p,value:e,properties:s})}function Us(p,e={}){E&&E.trackException&&E.trackException({exception:p,properties:e})}function Ls(){return new Promise(p=>{E&&E.flush?E.flush({callback:()=>p()}):p()})}dt.exports={client:E,trackEvent:qs,trackMetric:Fs,trackException:Us,flush:Ls,isEnabled:!ut}});var L=w((Cr,pt)=>{pt.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 gt=w((vr,ft)=>{var he=L(),{trackException:zs,isEnabled:mt}=U(),Vs=(p,e,s)=>{p.setTimeout(he.REQUEST_TIMEOUT_MS),s()},Bs=(p,e,s)=>{e.locals.telemetryEnabled=mt,e.locals.telemetryConnectionString=mt?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()},Ws=(p,e,s)=>{if(he.NODE_ENV==="development"){let t=["http://localhost:3838","http://127.0.0.1:3838"],n=p.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()},Hs=(p,e,s,t)=>{console.error("Unhandled error:",p.stack),zs(p,{url:e.url,method:e.method,statusCode:(p.status||500).toString(),userAgent:e.headers&&e.headers["user-agent"]||"unknown"});let n=p.status||500,r=he.NODE_ENV==="development",a=r?p.message:"Internal server error";s.status(n).json({error:a,...r&&{stack:p.stack}})},Js=(p,e)=>{e.status(404).json({error:"Not found"})};ft.exports={requestTimeout:Vs,developmentCors:Ws,errorHandler:Hs,notFoundHandler:Js,telemetryLocals:Bs}});var z=w((xr,ht)=>{function Gs(p){let e=p.toJSON?p.toJSON():{};return{type:p.type,source:p.source,sourceName:e.sourceName||p.source,sourceBadgeClass:e.sourceBadgeClass||"source-unknown",summary:p.summary,model:p.selectedModel||p.model,repo:p.workspace?.repository,branch:p.workspace?.branch,cwd:p.workspace?.cwd,created:p.createdAt,updated:p.updatedAt,copilotVersion:p.copilotVersion,modernizeVersion:p.modernizeVersion,sessionStatus:p.sessionStatus}}function Ks(p){return typeof p=="string"&&/^[a-zA-Z0-9_-]+$/.test(p)&&p.length<256}ht.exports={buildMetadata:Gs,isValidSessionId:Ks}});var V=w((jr,yt)=>{var ye=require("fs").promises,X=require("fs"),Q=require("readline"),Ys=require("js-yaml");async function Zs(p){try{return await ye.access(p),!0}catch{return!1}}async function Xs(p){try{let e=X.createReadStream(p,{encoding:"utf-8"}),s=Q.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 ${p}:`,e.message),0}}async function Qs(p){try{let e=await ye.readFile(p,"utf-8"),s=Ys.load(e);return s&&typeof s=="object"?s:{}}catch{try{let s=await ye.readFile(p,"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 ${p}:`,s.message),{}}}}async function en(p,e=500){try{let s=X.createReadStream(p,{encoding:"utf-8"}),t=Q.createInterface({input:s,crlfDelay:1/0}),n="",r=null,a=null,o=null,i=null,l=!1;for await(let u of t)if(u.trim())try{let d=JSON.parse(u);if(d.timestamp){let f=new Date(d.timestamp).getTime();isNaN(f)||(r||(r=f),a=f)}if(!n&&d.type==="user.message"){let f=d.data?.message||d.data?.content||d.data?.text||"";f&&(n=f.length>e?f.substring(0,e)+"...":f)}d.type==="session.end"&&(l=!0),d.type==="session.start"&&d.data?.copilotVersion&&!o&&(o=d.data.copilotVersion),(d.type==="session.start"||d.type==="session.model_change")&&!i&&(d.data?.selectedModel?i=d.data.selectedModel:d.data?.newModel?i=d.data.newModel:d.data?.model&&(i=d.data.model))}catch{}t.close(),s.destroy();let c=r&&a&&a>r?a-r:null;return{firstUserMessage:n||"",duration:c,copilotVersion:o||null,selectedModel:i||null,hasSessionEnd:l,lastEventTime:a,firstEventTime:r}}catch(s){return console.error(`Error reading session metadata from ${p}:`,s.message),{firstUserMessage:"",duration:null,copilotVersion:null,selectedModel:null,hasSessionEnd:!1,lastEventTime:null}}}async function tn(p,e=200){try{let s=X.createReadStream(p,{encoding:"utf-8"}),t=Q.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 sn(p){try{let e=X.createReadStream(p,{encoding:"utf-8"}),s=Q.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 ${p}:`,e.message),null}}async function nn(p){try{let e=X.createReadStream(p,{encoding:"utf-8"}),s=Q.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 ${p}:`,e.message),{copilotVersion:null,selectedModel:null}}}function rn(p){return p===".DS_Store"||p.startsWith(".")}yt.exports={fileExists:Zs,countLines:Xs,parseYAML:Qs,getFirstUserMessage:tn,getSessionDuration:sn,getSessionMetadata:nn,getSessionMetadataOptimized:en,shouldSkipEntry:rn}});var wt=w((Ar,St)=>{var Se=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}};St.exports=Se});var B=w((Dr,It)=>{var _t=require("fs"),an=require("readline"),we=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 _t.promises.access(e);let s=_t.createReadStream(e,{encoding:"utf-8"}),t=an.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}};It.exports=we});var ee=w((kr,Tt)=>{var on=require("path"),_e=class p{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.sessionStatus=t.sessionStatus||"completed"}static fromDirectory(e,s,t,n,r,a,o,i,l,c,u){let d=n?.created_at?new Date(n.created_at):n?.startTime?new Date(n.startTime):t.birthtime||(t.birthtimeMs?new Date(t.birthtimeMs):void 0),f=n?.updated_at?new Date(n.updated_at):n?.endTime?new Date(n.endTime):t.mtime;return new p(s,"directory",{directory:e,workspace:n,createdAt:d,updatedAt:f,summary:n?.summary||"No summary",hasEvents:r>0,eventCount:r,duration:a,isImported:o,hasInsight:i,copilotVersion:l,selectedModel:c,sessionStatus:u})}static fromFile(e,s,t,n,r,a,o,i,l){return new p(s,"file",{filePath:e,directory:on.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: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,modernizeVersion:this.modernizeVersion,selectedModel:this.selectedModel,sessionStatus:this.sessionStatus}}_getSourceDisplayMetadata(e){try{let{registry:t}=ce(),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"}}};Tt.exports=_e});var Ie=w((Mr,Et)=>{var ln=require("fs"),cn=require("readline");function un(p){return new Promise((e,s)=>{let t=ln.createReadStream(p,{encoding:"utf-8"}),n=cn.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 dn(p){return p.hasSessionEnd?"completed":p.lastEventTime!==null&&p.lastEventTime!==void 0&&Date.now()-p.lastEventTime<3e5?"wip":"completed"}Et.exports={readFirstLine:un,computeSessionStatus:dn}});var Ee=w((Nr,jt)=>{var N=require("path"),pn=require("os"),te=require("fs").promises,mn=B(),bt=ee(),{fileExists:se,countLines:Ct,parseYAML:fn,getSessionMetadataOptimized:vt,shouldSkipEntry:gn}=V(),{computeSessionStatus:xt}=Ie(),Te=class extends mn{get type(){return"copilot"}get displayName(){return"Copilot CLI"}get envVar(){return"COPILOT_SESSION_DIR"}getDefaultDir(){return process.env.SESSION_DIR||N.join(pn.homedir(),".copilot","session-state")}async scanEntries(e){let t=(await te.readdir(e)).filter(r=>!gn(r)).map(async r=>{let a=N.join(e,r),o=await te.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=N.join(s,e),n=await te.stat(t);if(n.isDirectory())return await this._createDirectorySession(e,t,n)}catch{}try{let t=N.join(s,`${e}.jsonl`),n=await te.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=N.join(s,t);try{return(await te.stat(n)).isDirectory()?N.join(n,"events.jsonl"):N.join(s,`${t}.jsonl`)}catch{return N.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=N.join(s,"workspace.yaml"),r=N.join(s,"events.jsonl"),a=N.join(s,".imported"),o=N.join(s,`${e}.agent-review.md`),i=await se(n)?await fn(n):{summary:e,repo:"unknown"},l=await se(r)?await Ct(r):0,c=await se(a),u=await se(o),d=null,f=null,g=null,m="completed";if(await se(r)){let S=await vt(r);if(d=S.duration,f=S.copilotVersion,g=S.selectedModel,m=xt(S),!i.summary&&S.firstUserMessage&&(i.summary=S.firstUserMessage),S.lastEventTime){let T=new Date(S.lastEventTime).getTime(),b=new Date(t.mtime).getTime();T>b&&(t={...t,mtime:new Date(T)})}}let y=bt.fromDirectory(s,e,t,i,l,d,c,u,f,g,m);return y.source="copilot",y}async _createFileSession(e,s,t){let n=e.replace(".jsonl",""),r=await Ct(s),a=await vt(s),o=xt(a),i=bt.fromFile(s,n,t,r,a.firstUserMessage,a.duration,a.copilotVersion,a.selectedModel,o);return i.source="copilot",i}};jt.exports=Te});var W=w(($r,At)=>{var be=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")}};At.exports=be});var ve=w((Or,Dt)=>{var hn=W(),Ce=class extends hn{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}};Dt.exports=Ce});var je=w((Pr,kt)=>{var yn=W(),xe=class extends yn{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}};kt.exports=xe});var De=w((Rr,Mt)=>{var Sn=W(),Ae=class extends Sn{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 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(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 l=i.trim();if(l)try{let c=JSON.parse(l);n.push(c)}catch(c){console.error(`Error parsing Pi-Mono line ${o}:`,c.message)}}return n}};Mt.exports=Ae});var $t=w((qr,Nt)=>{var wn=W(),ke=class extends wn{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 l=s[i];r[l]||(r[l]=typeof s[i+1]=="number"?[]:{}),r=r[l]}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),l=this._extractUserText(n.message);s.push({type:"user.message",id:n.requestId,timestamp:r,data:{message:l,content:l}}),s.push({type:"assistant.turn_start",id:`${n.requestId}-turn`,timestamp:r,parentId:n.requestId,data:{}});let c="",u=0,d=null,f=()=>{let g=c.trim().replace(/^`{3,}$/gm,"").trim();if(c="",!g)return;let m=d,y=m?i[m]||m.slice(0,8):null;s.push({type:"assistant.message",id:`${n.requestId}-text-${u}`,timestamp:a,parentId:n.requestId,data:{message:g,content:g,tools:[],subAgentId:m||null,subAgentName:y,parentToolCallId:null}})};for(let g of o)switch(u++,g.kind){case"thinking":{let m=g.content?.value||g.content||"";m&&(c+=m+`
4
+ `);break}case"markdownContent":{let m=g.content?.value||g.content||"";m&&(c+=m+`
5
+ `);break}case void 0:case null:{let m=g.value||"";m&&(c+=m);break}case"inlineReference":{let m=g.name||"";m&&(c+="`"+m+"`");break}case"toolInvocationSerialized":{f();let m=g.toolId==="runSubagent"?g.toolCallId:g.subAgentInvocationId;g.toolId==="runSubagent"&&(d=m),m&&(d=m);let y=this._normalizeTool(g);if(y){let S=m?i[m]||m.slice(0,8):null;s.push({type:"tool.invocation",id:y.id||`${n.requestId}-tool-${u}`,timestamp:a,parentId:n.requestId,data:{tool:y,subAgentId:m||null,subAgentName:S,parentToolCallId:m||null,badgeLabel:y.name,badgeClass:y.status==="error"?"badge-error":"badge-tool"}})}break}case"textEditGroup":{f();let m=g.edits||g.uri?[g]:[];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:g.uri,edits:m},result:"file edit",error:null},badgeLabel:"textEdit",badgeClass:"badge-tool"}});break}case"prepareToolInvocation":case"undoStop":case"codeblockUri":case"mcpServersStarting":break;default:break}f()}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 l=t.resultDetails,c=Array.isArray(l)?l:l?[l]:[];for(let u of c){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 l=(Array.isArray(e.resultDetails)?e.resultDetails:[e.resultDetails]).map(c=>c.fsPath||c.path||c.external||JSON.stringify(c)).filter(Boolean);n=l.length>0?l.join(`
6
+ `):e.generatedTitle||null}else n=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 a=i=>{if(!i||typeof i!="object")return i;let l=i.fsPath||i.path||i.external||"";return l?l.replace(/.*\//,""):JSON.stringify(i)},o=i=>{if(!i||typeof i!="object")return i;let l={};for(let[c,u]of Object.entries(i))if(!(c==="$mid"||c==="external"||c==="scheme")){if(c==="fsPath"||c==="path"){l.file=u.replace(/.*\//,"");continue}u&&typeof u=="object"&&("fsPath"in u||"$mid"in u)?l[c]=a(u):Array.isArray(u)&&c==="edits"?l.edits=`${u.length} edit(s)`:l[c]=u}return l};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)}};Nt.exports=ke});var Pt=w((Fr,Ot)=>{var Me=ve(),Ne=je(),$e=De(),Oe=class{constructor(){this.parsers=[new Me,new Ne,new $e],this.parserMap={copilot:new Me,claude:new Ne,"pi-mono":new $e}}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 Me?"copilot":s instanceof Ne?"claude":s instanceof $e?"pi-mono":"unknown":null}};Ot.exports=Oe});var Pe=w((Ur,Rt)=>{var _n=W(),In=ve(),Tn=je(),En=De(),bn=$t(),Cn=Pt();Rt.exports={BaseSessionParser:_n,CopilotSessionParser:In,ClaudeSessionParser:Tn,PiMonoParser:En,VsCodeParser:bn,ParserFactory:Cn}});var zt=w((Lr,Lt)=>{var k=require("path"),vn=require("os"),A=require("fs").promises,xn=B(),qt=ee(),{countLines:Ft,shouldSkipEntry:Ut}=V(),{ParserFactory:jn}=Pe(),Re=class extends xn{constructor(){super(),this.parserFactory=new jn}get type(){return"claude"}get displayName(){return"Claude"}get envVar(){return"CLAUDE_SESSION_DIR"}getDefaultDir(){return k.join(vn.homedir(),".claude","projects")}async scanEntries(e){let t=(await A.readdir(e)).filter(r=>!Ut(r)).map(async r=>{let a=k.join(e,r);return(await A.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 A.readdir(s);for(let n of t){let r=k.join(s,n),a=k.join(r,`${e}.jsonl`);try{let i=await A.stat(a);if(i.isFile()){let l=await this._createClaudeSession(`${e}.jsonl`,a,i,n);if(l)return l}}catch{}let o=k.join(r,e);try{let i=await A.stat(o);if(i.isDirectory()){let l=k.join(o,"subagents");try{if((await A.stat(l)).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 A.readdir(s);for(let n of t){let r=k.join(s,n,`${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,s){let t=await this.resolveEventsFile(e,s);return this.readJsonlEvents(t)}async _scanProjectDir(e,s){try{let t=await A.readdir(e),n=[];for(let r of t){if(Ut(r))continue;let a=k.join(e,r),o=await A.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=k.join(a,"subagents");try{if((await A.stat(i)).isDirectory()){let c=await this._createSubagentsSession(r,a,o,s);c&&n.push(c)}}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 Ft(s);try{let l=(await A.readFile(s,"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"),u=l.some(y=>y.type==="assistant.message"||y.type==="user.message");if(!c&&u||!c||this.parserFactory.getParserType(l)!=="claude")return null;let f=this.parserFactory.parse(l),g=f.metadata||{},m=n.replace(/^-/,"/").replace(/-/g,"/");return new qt(r,"file",{source:"claude",filePath:s,directory:k.dirname(s),workspace:{summary:g.model?`Claude Code session (${g.model})`:"Claude Code session",cwd:g.cwd||m},createdAt:g.startTime||t.birthtime,updatedAt:t.mtime,summary:f.turns[0]?.userMessage?.content?.substring(0,100)||"No summary",hasEvents:a>0,eventCount:a,duration:null,isImported:!1,hasInsight:!1,copilotVersion:g.version,selectedModel:g.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=k.join(s,"subagents"),o=(await A.readdir(r)).filter(m=>m.startsWith("agent-")&&m.endsWith(".jsonl"));if(o.length===0)return null;let i=0;for(let m of o){let y=k.join(r,m);i+=await Ft(y)}let l=k.join(r,o[0]),u=(await A.readFile(l,"utf-8")).trim().split(`
8
+ `).filter(m=>m.trim()),d=u.length>0?JSON.parse(u[0]):null,f={cwd:d?.cwd||n,version:d?.version,model:d?.message?.model,startTime:d?.timestamp},g=n.replace(/^-/,"/").replace(/-/g,"/");return new qt(e,"directory",{source:"claude",directory:s,workspace:{summary:`Claude session (${o.length} sub-agents)`,cwd:f.cwd||g},createdAt:f.startTime||t.birthtime,updatedAt:t.mtime,summary:d?.message?.content?.substring(0,100)||"Sub-agent tasks",hasEvents:i>0,eventCount:i,duration:null,isImported:!1,hasInsight:!1,copilotVersion:f.version,selectedModel:f.model,sessionStatus:"completed"})}catch(r){return console.error(`Error creating Claude subagents session ${e}:`,r.message),null}}};Lt.exports=Re});var Jt=w((zr,Ht)=>{var $=require("path"),An=require("os"),P=require("fs").promises,Dn=B(),Vt=ee(),{countLines:Bt,shouldSkipEntry:kn}=V(),{readFirstLine:Wt}=Ie(),qe=class extends Dn{get type(){return"pi-mono"}get displayName(){return"Pi"}get envVar(){return"PI_MONO_SESSION_DIR"}getDefaultDir(){return $.join(An.homedir(),".pi","agent","sessions")}async scanEntries(e){let t=(await P.readdir(e)).filter(r=>!kn(r)).map(async r=>{let a=$.join(e,r);return(await P.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 P.readdir(s);for(let n of t){let r=$.join(s,n);try{let o=(await P.readdir(r)).find(i=>i.includes(`_${e}.jsonl`));if(o){let i=$.join(r,o),l=await P.stat(i);return await this._createSession(o,i,l,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 Wt(s);if(!o)return null;try{let i=JSON.parse(o);if(i.type!=="session")return null;let l=await Bt(s),c=n.replace(/^--/,"").replace(/--$/,"");return new Vt(a,"directory",{source:"pi-mono",directory:$.dirname(s),workspace:{cwd:i.cwd||c},createdAt:new Date(i.timestamp),updatedAt:new Date(t.mtime),summary:`Pi-Mono: ${$.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,s){try{let t=await P.readdir(s);for(let n of t){let r=$.join(s,n);try{let o=(await P.readdir(r)).find(i=>i.includes(`_${e.id}.jsonl`));if(o)return $.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 P.readdir(e)).filter(a=>a.endsWith(".jsonl"));if(n.length===0)return[];let r=[];n.sort().reverse();for(let a of n){let o=$.join(e,a),i=await P.stat(o),l=a.match(/_([a-f0-9-]+)\.jsonl$/);if(!l)continue;let c=l[1],u=await Wt(o);if(u)try{let d=JSON.parse(u);if(d.type!=="session")continue;let f=await Bt(o),g=s.replace(/^--/,"").replace(/--$/,""),m=new Vt(c,"directory",{source:"pi-mono",directory:e,workspace:{cwd:d.cwd||g},createdAt:new Date(d.timestamp),updatedAt:new Date(i.mtime),summary:`Pi-Mono: ${$.basename(d.cwd||g)}`,hasEvents:f>0,eventCount:f,duration:null,sessionStatus:"completed"});r.push(m)}catch(d){console.error(`[PI-MONO] Error parsing session ${a}:`,d.message)}}return r}catch(t){return console.error(`[PI-MONO] Error scanning dir ${e}:`,t.message),[]}}};Ht.exports=qe});var Zt=w((Vr,Yt)=>{var C=require("path"),ne=require("os"),M=require("fs").promises,{fileURLToPath:Gt}=require("url"),Mn=B(),Nn=ee(),{shouldSkipEntry:Kt}=V(),{VsCodeParser:$n}=Pe();function On(){let p;switch(ne.platform()){case"win32":p=C.join(process.env.APPDATA||C.join(ne.homedir(),"AppData","Roaming"));break;case"darwin":p=C.join(ne.homedir(),"Library","Application Support");break;case"linux":p=C.join(ne.homedir(),".config");break;default:p=C.join(ne.homedir(),".config")}return[C.join(p,"Code","User","workspaceStorage"),C.join(p,"Code - Insiders","User","workspaceStorage")]}var Fe=class extends Mn{constructor(){super(),this._candidates=null,this._parser=new $n}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=On()),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=>!Kt(r)).map(async r=>{let a=C.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=C.join(s,r,"chatSessions");try{let i=(await M.readdir(a)).find(l=>l===`${e}.json`||l===`${e}.jsonl`||l.replace(/\.jsonl?$/,"")===e);if(i){let l=C.join(a,i),c=await M.stat(l),u=await this._parseSessionFile(l);if(!u)continue;let{sessionJson:d}=u,f=d.requests||[];if(f.length===0)continue;let g=await this._resolveWorkspacePath(C.join(s,r)),m={...c,filePath:l};n.push(this._buildSession(e,f,d,m,r,g||C.join(s,r)))}}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._parseSessionFile(e.filePath);if(!t)return[];let n=this._expandVsCodeEvents(t.parsed.allEvents);return n=await this._applyFileMtimeFallback(n,e.filePath),this._expandVsCodeToTimelineFormat(n)}catch(t){return console.error(`[VSCode readEvents] Error reading session ${e.id}:`,t),[]}}buildTimeline(e,s){let t=[],n=0,r=new Set;for(let o=0;o<e.length;o++){let i=e[o];if(i.type!=="user.message")continue;n++;let l={id:`turn-${n}`,type:"user-request",message:i.data?.message||"",startTime:i.timestamp,endTime:i.timestamp,assistantTurns:[],subagents:[]},c=new Set,u=0,d=o+1;for(;d<e.length&&e[d].type!=="user.message";){let f=e[d];if(f.type==="assistant.message"){u++,l.endTime=f.timestamp||l.endTime;let g={id:`assistant-${u}`,startTime:f.timestamp,endTime:f.timestamp,tools:[]};if(Array.isArray(f.data?.tools))for(let y of f.data.tools)g.tools.push({name:y.name,startTime:y.startTime||f.timestamp,endTime:y.endTime||f.timestamp,status:y.status||"completed",input:y.input,result:y.result});let m=f.data?.subAgentId;m&&!c.has(m)&&(c.add(m),r.add(m),l.subagents.push({id:m,name:f.data?.subAgentName||m,startTime:f.timestamp,endTime:f.timestamp})),l.assistantTurns.push(g)}d++}t.push(l)}let a=t.reduce((o,i)=>o+i.assistantTurns.reduce((l,c)=>l+c.tools.length,0),0);return{turns:t,summary:{totalTurns:t.length,totalAssistantTurns:t.reduce((o,i)=>o+i.assistantTurns.length,0),totalTools:a,totalSubagents:r.size,startTime:e[0]?.timestamp,endTime:e[e.length-1]?.timestamp}}}async _scanWorkspaceDir(e){let s=C.join(e,"chatSessions");try{await M.access(s)}catch{return[]}let t=C.basename(e),n=await this._resolveWorkspacePath(e),a=(await M.readdir(s)).filter(i=>(i.endsWith(".json")||i.endsWith(".jsonl"))&&!Kt(i));if(a.length===0)return[];let o=[];for(let i of a){let l=C.join(s,i);try{let c=await M.stat(l),u=await this._parseSessionFile(l);if(!u)continue;let{sessionJson:d}=u,f=d.sessionId||C.basename(i).replace(/\.jsonl?$/,""),g=d.requests||[];if(g.length===0)continue;let m={...c,filePath:l},y=this._buildSession(f,g,d,m,t,n||e);o.push(y)}catch(c){console.warn(`[VSCode scan] Skipping malformed session file ${l}: ${c.message}`)}}return o}async _parseSessionFile(e){let s=await M.readFile(e,"utf-8");return this._parseSessionContent(s,e)}_parseSessionContent(e,s="unknown"){let t=e.trim();if(!t)return null;try{let a=JSON.parse(t);if(a&&typeof a=="object"&&!Array.isArray(a))return{sessionJson:a,parsed:this._parser.parseVsCode(a)}}catch{}let n=t.split(`
9
+ `).filter(a=>a.trim()),r=[];for(let a=0;a<n.length;a++)try{r.push(JSON.parse(n[a]))}catch(o){return console.warn(`[VSCode parse] Failed to parse ${s} line ${a+1}: ${o.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 ${s}`),null)}_parseJsonl(e,s="unknown"){return this._parseSessionContent(e,s)?.sessionJson||null}async _applyFileMtimeFallback(e,s){if(!e.length)return e;try{let t=await M.stat(s),n=new Date(t.mtime).toISOString(),r=e[e.length-1];if(!r?.timestamp)return e;let a=new Date(r.timestamp).getTime();(new Date(n).getTime()-a)/1e3>10&&(r.timestamp=n)}catch(t){console.error("[VSCode] Error getting file mtime:",t)}return e}async _resolveWorkspacePath(e){try{let s=C.join(e,"workspace.json"),t=await M.readFile(s,"utf-8"),n=JSON.parse(t);if(n.folder)return Gt(n.folder);if(n.workspace){let r=Gt(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=C.dirname(r);return C.resolve(i,o.folders[0].path)}}catch{}}}catch{}return null}_buildSession(e,s,t,n,r,a){let o=s[0],i=s[s.length-1],l=t.creationDate?new Date(t.creationDate):o.timestamp?new Date(o.timestamp):n.birthtime,c=i.timestamp?new Date(i.timestamp):null,u=t.lastMessageDate?new Date(t.lastMessageDate):c||n.mtime,f=this._extractLastTerminalTimestamp(s)||c||u,g=Date.now()-f.getTime()<900*1e3,m=this._extractUserText(o.message);return new Nn(e,"file",{source:"vscode",filePath:n.filePath,directory:C.dirname(n.filePath),createdAt:l,updatedAt:f,summary:m?m.slice(0,120):`VSCode chat (${s.length} requests)`,hasEvents:!0,eventCount:s.reduce((y,S)=>y+(S.response||[]).length,0)+s.length*2+1,duration:f.getTime()-l.getTime(),sessionStatus:g?"wip":"completed",selectedModel:o.modelId||null,copilotVersion:o.agent?.extensionVersion||null,workspace:{cwd:a,workspaceHash:r}})}_expandVsCodeEvents(e){let s=[],t=[],n=null,r=null,a=0,o=null,i=null,l=()=>{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 c=0;c<e.length;c++){let u=e[c];if(u.type==="tool.invocation"){let d=u.data?.subAgentId||null;t.length>0&&d!==o&&l(),t.length===0&&(n=u.parentId,r=u.timestamp,a=c,o=d,i=u.data?.subAgentName||null),u.data?.tool&&t.push(u.data.tool);continue}l(),s.push(u)}return l(),s}_expandVsCodeToTimelineFormat(e){let s=[];for(let t=0;t<e.length;t++){let n=e[t];s.push(n),!(n.type!=="assistant.message"||!Array.isArray(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}_extractLastTerminalTimestamp(e){let s=0;function t(n){if(!(!n||typeof n!="object")){if(Array.isArray(n)){n.forEach(t);return}if(n.terminalCommandState&&typeof n.terminalCommandState.timestamp=="number"){let r=n.terminalCommandState.timestamp;r>1e12&&r<9999999999999&&r>s&&(s=r)}for(let r of Object.values(n))t(r)}}for(let n of e)t(n.response);return s>0?new Date(s):null}_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(""):"":""}};Yt.exports=Fe});var Qt=w((Br,Xt)=>{var ue=require("path"),Pn=require("os"),Ue=require("fs").promises,Rn=Ee(),Le=class extends Rn{get type(){return"modernize"}get displayName(){return"Modernize CLI"}get envVar(){return"MODERNIZE_SESSION_DIR"}getDefaultDir(){return ue.join(Pn.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 Ue.readdir(e);for(let n of t){if(!n.includes("+"))continue;let r=ue.join(e,n,"session-state");try{(await Ue.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=ue.basename(ue.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 Ue.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}};Xt.exports=Le});var ce=w((Wr,ts)=>{var es=wt(),qn=B(),Fn=Ee(),Un=zt(),Ln=Jt(),zn=Zt(),Vn=Qt(),H=new es;H.register(new Fn);H.register(new Un);H.register(new Ln);H.register(new zn);H.register(new Vn);ts.exports={registry:H,AdapterRegistry:es,BaseSourceAdapter:qn}});var Ve=w((Hr,ns)=>{var ss=require("fs").promises,{shouldSkipEntry:Bn}=V(),{registry:Wn}=ce(),ze=class{constructor(e){if(this.registry=Wn,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 ss.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(Bn(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 ss.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))}};ns.exports=ze});var as=w((Jr,rs)=>{var Be=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)}};rs.exports=Be});var He=w((Gr,ls)=>{var re=require("fs"),J=require("path"),Hn=require("readline"),{isValidSessionId:os,buildMetadata:Jn}=z(),is=Ve(),Gn=as(),We=class{constructor(e){e?(this.SESSION_DIR=e,this.sessionRepository=new is(e)):this.sessionRepository=new is,this.eventNormalizer=new Gn}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(l=>l.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(!os(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(!os(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=[];if(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(c=>c._subagent):i=i.filter(c=>!c._subagent)),i.sort((l,c)=>{let u=l.timestamp?new Date(l.timestamp).getTime():0,d=c.timestamp?new Date(c.timestamp).getTime():0;return u!==d?u-d:(l._fileIndex??0)-(c._fileIndex??0)}),i=i.filter(l=>l.type!=="file-history-snapshot"),i=i.map(l=>this._normalizeEvent(l,t.source)),n&&!n.hasCustomPipeline&&await this._mergeSubAgentEvents(i,o,e,t.source),n&&!n.hasCustomPipeline&&t.source==="copilot"?(this._matchCopilotToolCalls(i),this._mergeHookEvents(i),i=this._expandCopilotToTimelineFormat(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 re.promises.readdir(o.dir);for(let l of i){let c=J.join(o.dir,l,t,"subagents");try{if((await re.promises.stat(c)).isDirectory()){r=c;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 re.promises.stat(r)).isDirectory())return}catch{return}try{let i=(await re.promises.readdir(r)).filter(l=>l.startsWith("agent-")&&l.endsWith(".jsonl"));if(i.length===0)return;for(let l of i){let c=l.replace(".jsonl",""),u=J.join(r,l);try{let d=re.createReadStream(u,{encoding:"utf-8"}),f=Hn.createInterface({input:d,crlfDelay:1/0}),g=[];for await(let v of f){let D=v.trim();D&&g.push(D)}if(g.length===0)continue;let m=c.replace("agent-",""),y=m.toUpperCase(),S=`Sub-agent ${c}`;try{let v=JSON.parse(g[0]);if(v.agentId&&(m=v.agentId,y=`agent-${v.agentId}`),v.message?.content){let D=typeof v.message.content=="string"?v.message.content:JSON.stringify(v.message.content);S=D.length>100?D.slice(0,100)+"...":D}}catch{}let T=g.map((v,D)=>{try{let Z=JSON.parse(v);return Z._fileIndex=1e6+D,Z._subagent={id:c,name:m},Z}catch(Z){return console.error(`Error parsing sub-agent ${c} line ${D+1}:`,Z.message),null}}).filter(v=>v!==null);if(T.length===0)continue;let b=T.map(v=>this._normalizeEvent(v,n));if(a&&(b=b.filter(v=>{let D=this._getClaudeSubagentMergeKey(v);return D?a.has(D)?!1:(a.add(D),!0):!0})),b.length===0)continue;let x=b[0],F=b[b.length-1],me=x.timestamp||new Date().toISOString(),fe=F.timestamp||new Date().toISOString(),it={type:"subagent.started",id:`${c}-start`,timestamp:me,_fileIndex:x._fileIndex-1,_subagent:{id:c,name:m},data:{toolCallId:c,agentName:m,agentDisplayName:y,agentDescription:S}},Ns={type:"subagent.completed",id:`${c}-end`,timestamp:fe,_fileIndex:F._fileIndex+1,_subagent:{id:c,name:m},data:{toolCallId:c,result:`Sub-agent ${y} completed`}};e.push(it,...b,Ns)}catch(d){console.error(`Error reading sub-agent ${c}:`,d)}}e.sort((l,c)=>{let u=l.timestamp?new Date(l.timestamp).getTime():0,d=c.timestamp?new Date(c.timestamp).getTime():0;return u!==d?u-d:l._fileIndex-c._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 l of e)if(l.type==="message"&&l.data.role==="toolResult"&&l.parentId===o&&!a.includes(l)){a.push(l),o=l.id,i=!0;break}}a.forEach((l,c)=>{if(c<r.length){let u=r[c];u.result=l.data.result,u.resultId=l.id,u.status="completed",s.add(l.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 l of e)if(l.type==="tool.result"&&l.parentId===o&&!a.includes(l)){a.push(l),o=l.id,i=!0;break}}a.forEach((l,c)=>{if(c<r.length){let u=r[c];u.status="completed",u._matched=!0,u.result=l.data.result,u.resultId=l.id,s.add(l.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 l=new Date(n.timestamp)-new Date(o.timestamp);o.data.hookDurationMs=l;let c=l<1e3?`${l}ms`:`${(l/1e3).toFixed(2)}s`;o.data.message&&(o.data.message+=`
10
+ **Duration:** ${c}`)}o.data.badgeLabel=i?"\u2713 HOOK":"\u2717 HOOK",o.data.badgeClass=i?"badge-tool":"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
+ `)})}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 n=e.data||{},r=[];if(n.hookType&&r.push(`**Hook:** ${n.hookType}`),n.input?.toolName&&r.push(`**Tool:** ${n.input.toolName}`),n.input?.toolArgs&&Object.keys(n.input.toolArgs).length>0){let a=Object.entries(n.input.toolArgs).map(([o,i])=>`${o}: ${typeof i=="string"?i:JSON.stringify(i)}`).join(", ");r.push(`**Args:** ${a}`)}if(n.input?.toolResult?.textResultForLlm){let a=n.input.toolResult.textResultForLlm.slice(0,200);r.push(`**Result:** ${a}${n.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 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-tool":"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(`
13
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(`
14
- `))}return this._generateBadgeInfo(t),t}switch(e.type){case"user":case"assistant":if(e.message){if(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(o=>o&&typeof o=="object"&&(o.type==="tool_use"||o.type==="tool_result"));n.length>0&&(t.data.tools=n.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}))}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 o=n.map(([r,i])=>`${r} (v${i.version})`).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(`
15
18
  `);t.data.message=`Tracked files:
16
- ${o}`}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(`
17
- `)),e.data.message?.message?.content&&Array.isArray(e.data.message.message.content)){let o=e.data.message.message.content.filter(r=>r&&typeof r=="object"&&(r.type==="tool_use"||r.type==="tool_result"));o.length>0&&(t.data.tools=o.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}))}}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(o=>o.type==="text").map(o=>o.text).join(`
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||{},r=[];if(n.hookType&&r.push(`**Hook:** ${n.hookType}`),n.input?.toolName&&r.push(`**Tool:** ${n.input.toolName}`),n.input?.toolArgs&&Object.keys(n.input.toolArgs).length>0){let a=Object.entries(n.input.toolArgs).map(([o,i])=>`${o}: ${typeof i=="string"?i:JSON.stringify(i)}`).join(", ");r.push(`**Args:** ${a}`)}if(n.input?.toolResult?.textResultForLlm){let a=n.input.toolResult.textResultForLlm.slice(0,200);r.push(`**Result:** ${a}${n.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 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(`
22
+ `),t.data.badgeLabel="HOOK END",t.data.badgeClass=n.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 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(`
18
23
  `);n&&s.push(n)}}return s.join(`
19
- `)}return""}async getSessionWithEvents(e){let s=await this.getSessionById(e);if(!s)return null;let t=await this.getSessionEvents(e),n=xs(s),o=t.find(i=>i.type==="session.start");o?.data?.selectedModel&&(n.model=o.data.selectedModel);let r=t.find(i=>i.type==="session.model_change");if(r?.data&&(n.model=r.data.newModel||r.data.model),t.length){let i=t[t.length-1];i?.timestamp&&(n.updated=i.timestamp)}if(t.length){let i=t[0];i?.timestamp&&(n.created=i.timestamp)}return{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);return s.source==="copilot"?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 i=0;i<e.length;i++){let a=e[i];if(a.type==="user.message"){n++;let l={id:`turn-${n}`,type:"user-request",message:a.data.message||"",startTime:a.timestamp,endTime:a.timestamp,assistantTurns:[],subagents:[]},c=i+1,d=0;for(;c<e.length&&e[c].type!=="user.message";){let u=e[c];if(u.type==="assistant.message"){d++,l.endTime=u.timestamp;let m={id:`assistant-${d}`,startTime:u.timestamp,endTime:u.timestamp,tools:[]};if(u.data.tools&&Array.isArray(u.data.tools))for(let f of u.data.tools)m.tools.push({name:f.name,startTime:u.timestamp,endTime:u.timestamp,status:f.status||"completed",input:f.input,result:f.result});l.assistantTurns.push(m)}c++}t.push(l)}}let o=t.reduce((i,a)=>i+a.assistantTurns.reduce((l,c)=>l+c.tools.length,0),0),r={totalTurns:t.length,totalAssistantTurns:t.reduce((i,a)=>i+a.assistantTurns.length,0),totalTools:o,totalSubagents:0,startTime:e[0]?.timestamp,endTime:e[e.length-1]?.timestamp};return{turns:t,summary:r}}_buildCopilotTimeline(e,s){let t=[],n=null,o=0;for(let i of e)if(i.type==="assistant.turn_start")o++,n={id:`turn-${o}`,type:"assistant-turn",message:i.data.message||"",startTime:i.timestamp,endTime:null,tools:[],subagents:[]};else if(i.type==="assistant.turn_complete"&&n)n.endTime=i.timestamp,t.push(n),n=null;else if(i.type==="tool.execution_start"&&n){let a={name:i.data.tool||i.data.name,startTime:i.timestamp,endTime:null,status:"running",input:i.data.arguments||i.data.input};n.tools.push(a)}else if(i.type==="tool.execution_complete"&&n){let a=n.tools.find(l=>l.name===(i.data.tool||i.data.name)&&!l.endTime);a&&(a.endTime=i.timestamp,a.status=i.data.error||i.data.isError?"error":"completed",a.result=i.data.result||i.data.output)}n&&(n.endTime=e[e.length-1]?.timestamp,t.push(n));let r={totalTurns:t.length,totalTools:t.reduce((i,a)=>i+a.tools.length,0),totalSubagents:0,startTime:e[0]?.timestamp,endTime:e[e.length-1]?.timestamp};return{turns:t,summary:r}}_buildClaudeTimeline(e,s){return this._buildPiMonoTimeline(e,s)}_expandPiMonoToCopilotFormat(e){let s=[],t=0,n=0;for(let o=0;o<e.length;o++){let r=e[o];if(r.type!=="user.message"&&r.type!=="assistant.message"){s.push(r);continue}if(r.type==="user.message"){t++,s.push({...r,_turnNumber:t});continue}if(r.type==="assistant.message"){let i=r.data.tools||[],a=r.timestamp,l=`pi-turn-${o}`;s.push({type:"assistant.turn_start",id:`${l}-start`,timestamp:a,parentId:r.parentId,data:{message:r.data.message||"",model:r.data.model,tools:i.length>0?i:void 0},_synthetic:!0,_turnNumber:t,_fileIndex:r._fileIndex}),s.push({...r,_fileIndex:r._fileIndex+.05}),i.forEach((c,d)=>{let u=`pi-tool-${n++}`,m=a,f=a;s.push({type:"tool.execution_start",id:`${u}-start`,timestamp:m,parentId:l,data:{toolCallId:u,toolName:c.name,tool:c.name,arguments:c.input||{}},_synthetic:!0,_fileIndex:r._fileIndex+.1+d*.01}),s.push({type:"tool.execution_complete",id:`${u}-complete`,timestamp:f,parentId:u,data:{toolCallId:u,toolName:c.name,tool:c.name,result:c.result,error:c.status==="error"?"Tool execution failed":null,isError:c.status==="error"},_synthetic:!0,_fileIndex:r._fileIndex+.15+d*.01})}),s.push({type:"assistant.turn_complete",id:`${l}-complete`,timestamp:r.timestamp,parentId:l,data:{message:r.data.message||""},_synthetic:!0,_turnNumber:t,_fileIndex:r._fileIndex+.9})}}return s}_expandVsCodeEvents(e){let s=[],t=[],n=null,o=null,r=0,i=null,a=null,l=()=>{t.length!==0&&(s.push({type:"assistant.message",id:`vscode-tools-${r}`,timestamp:o,parentId:n,data:{message:"",content:"",tools:t,subAgentId:i,subAgentName:a},_synthetic:!0}),t=[],i=null,a=null)};for(let c=0;c<e.length;c++){let d=e[c];if(d.type==="tool.invocation"){let u=d.data?.subAgentId||null;t.length>0&&u!==i&&l(),t.length===0&&(n=d.parentId,o=d.timestamp,r=c,i=u,a=d.data?.subAgentName||null),d.data?.tool&&t.push(d.data.tool)}else l(),s.push(d)}return l(),s}_expandCopilotToTimelineFormat(e){let s=[],t=0;for(let n=0;n<e.length;n++){let o=e[n];if(o.type==="user"){t++,s.push({...o,type:"user.message",_turnNumber:t,data:{...o.data,message:o.message?.content||o.data?.message||""}});continue}if(o.type==="assistant"){let r=o.uuid||`copilot-assistant-${n}`,i=o.timestamp,a="";o.message?.content?Array.isArray(o.message.content)?a=o.message.content.filter(l=>l&&l.type==="text").map(l=>l.text).join(`
20
- `):typeof o.message.content=="string"&&(a=o.message.content):o.data?.message&&(a=o.data.message),s.push({type:"assistant.turn_start",id:`${r}-start`,timestamp:i,parentId:o.parentId,uuid:o.uuid,data:{message:a,turnId:r},_synthetic:!0,_turnNumber:t,_fileIndex:o._fileIndex}),s.push({type:"assistant.message",id:r,timestamp:i,parentId:o.parentId,uuid:o.uuid,data:{message:a,tools:o.data?.tools||[]},_synthetic:!0,_turnNumber:t,_fileIndex:o._fileIndex+.05}),o.data?.tools&&o.data.tools.length>0&&o.data.tools.forEach((l,c)=>{let d=l.toolId||`tool-${n}-${c}`;l.start&&s.push({...l.start,_fileIndex:o._fileIndex+.1+c*.02}),l.complete&&s.push({...l.complete,_fileIndex:o._fileIndex+.15+c*.02})}),s.push({type:"assistant.turn_complete",id:`${r}-complete`,timestamp:i,parentId:r,uuid:o.uuid,data:{message:a},_synthetic:!0,_turnNumber:t,_fileIndex:o._fileIndex+.9});continue}s.push(o)}return s}_expandClaudeToTimelineFormat(e){let s=[],t=0;for(let n=0;n<e.length;n++){let o=e[n];if(o.type==="user"){t++,s.push({...o,type:"user.message",_turnNumber:t,data:{...o.data,message:o.data?.message||""}});continue}if(o.type==="assistant"){let r=o.id||`claude-assistant-${n}`,i=o.timestamp,a=o.data?.message||"";s.push({type:"assistant.turn_start",id:`${r}-start`,timestamp:i,parentId:o.parentId,data:{message:a,turnId:r},_synthetic:!0,_turnNumber:t,_fileIndex:o._fileIndex}),s.push({type:"assistant.message",id:r,timestamp:i,parentId:o.parentId,data:{message:a,tools:o.data?.tools||[]},_synthetic:!0,_turnNumber:t,_fileIndex:o._fileIndex+.05}),o.data?.tools&&o.data.tools.length>0&&o.data.tools.forEach((l,c)=>{l.type==="tool_use"&&(s.push({type:"tool.execution_start",id:`${l.id}-start`,timestamp:i,data:{toolCallId:l.id,toolName:l.name,arguments:l.input||{}},_synthetic:!0,_fileIndex:o._fileIndex+.1+c*.02}),l.result&&s.push({type:"tool.execution_complete",id:`${l.id}-complete`,timestamp:i,data:{toolCallId:l.id,toolName:l.name,result:l.result,isError:!1},_synthetic:!0,_fileIndex:o._fileIndex+.15+c*.02}))}),s.push({type:"assistant.turn_complete",id:`${r}-complete`,timestamp:i,parentId:r,data:{message:a},_synthetic:!0,_turnNumber:t,_fileIndex:o._fileIndex+.9});continue}s.push(o)}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((o,r)=>{if(!o.id||!o.name)return;let i=o.startTime||n.timestamp,a=o.endTime||n.timestamp;s.push({type:"tool.execution_start",id:`${o.id}-start`,timestamp:i,parentId:n.id,data:{toolCallId:o.id,toolName:o.name,tool:o.name,arguments:o.input||{}},_synthetic:!0,_fileIndex:n._fileIndex?n._fileIndex+.1+r*.02:void 0}),s.push({type:"tool.execution_complete",id:`${o.id}-complete`,timestamp:a,parentId:o.id,data:{toolCallId:o.id,toolName:o.name,tool:o.name,result:o.result||null,error:o.error||(o.status==="error"?"Tool execution failed":null),isError:o.status==="error"},_synthetic:!0,_fileIndex:n._fileIndex?n._fileIndex+.15+r*.02:void 0})})}return s}};wt.exports=be});var xe=b((Tn,_t)=>{var k=require("fs").promises,N=require("path"),Ds=require("os"),ve=class{constructor(){this.knownTagsDir=N.join(Ds.homedir(),".session-viewer"),this.knownTagsFilePath=N.join(this.knownTagsDir,"known-tags.json")}async ensureKnownTagsFile(){try{await k.access(this.knownTagsFilePath)}catch{await k.mkdir(this.knownTagsDir,{recursive:!0}),await k.writeFile(this.knownTagsFilePath,JSON.stringify([]),"utf8")}}async readKnownTagsFile(){await this.ensureKnownTagsFile();try{let e=await k.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 k.writeFile(this.knownTagsFilePath,JSON.stringify(e,null,2),"utf8")}getSessionTagsFilePath(e){if(e.filePath){let s=N.dirname(e.filePath),t=N.basename(e.filePath,N.extname(e.filePath));return N.join(s,`${t}.tags.json`)}return e.directory?N.join(e.directory,"tags.json"):N.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 k.access(s);let t=await k.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(o=>this.normalizeTag(o)).filter(o=>o.length>0).filter((o,r,i)=>i.indexOf(o)===r);if(t.length>10)throw new Error("Maximum 10 tags per session");let n=this.getSessionTagsFilePath(e);if(t.length===0)try{await k.unlink(n)}catch{}else await k.mkdir(N.dirname(n),{recursive:!0}),await k.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(r=>this.normalizeTag(r)),o=t.filter(r=>!n.includes(r));return await this.setSessionTags(e,o)}async getMultipleSessionTags(e){let s={};for(let t of e)s[t.id]=await this.getSessionTags(t);return s}};_t.exports=ve});var Ct=b((En,Et)=>{var Ms=je(),{isValidSessionId:Z,buildMetadata:It}=U(),{trackEvent:B,trackMetric:Tt}=R(),ks=require("adm-zip"),W=require("path"),O=require("fs"),Ae=class{constructor(e=null){this.sessionService=e||new Ms}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 r of this.sessionService.sessionRepository.sources)n[r.type]=r.dir;let o={sessions:t.sessions,hasMore:t.hasNextPage,totalSessions:t.totalSessions,sourceHints:JSON.stringify(n)};B("HomepageViewed",{sessionCount:t.totalSessions.toString(),sourceFilter:"copilot"}),s.render("index",o)}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(!Z(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 o=It(n);B("SessionViewed",{sessionId:t,source:n.source||"unknown",eventCount:(n.eventCount||o.totalEvents||0).toString(),duration:(n.duration||o.duration||0).toString(),model:n.model||o.model||"unknown",sessionStatus:n.status||o.status||"unknown"});let r=n.eventCount||o.totalEvents||0;r>0&&Tt("SessionEventCount",r,{sessionId:t,source:n.source||"unknown"});let i=n.duration||o.duration||0;i>0&&Tt("SessionDuration",i,{sessionId:t,source:n.source||"unknown"}),s.render("session-vue",{sessionId:t,events:[],metadata:o})}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(!Z(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 o=It(n);B("TimeAnalysisViewed",{sessionId:t,turnCount:(o.totalEvents||0).toString()}),s.render("time-analyze",{sessionId:t,events:[],metadata:o})}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,o=e.query.source||null;if(t&&n){if(t<1||n<1||n>100)return s.status(400).json({error:"Invalid pagination parameters"});let r=await this.sessionService.getPaginatedSessions(t,n,o);B("SessionListLoaded",{page:t.toString(),limit:n.toString(),totalSessions:r.totalSessions.toString()}),s.set({"Cache-Control":"public, max-age=60"}),s.json(r)}else if(o&&n){let r=await this.sessionService.getAllSessions(o),i=r.slice(0,n);s.set({"Cache-Control":"public, max-age=60"}),s.json({sessions:i,hasMore:r.length>n,totalSessions:r.length})}else{let r=await this.sessionService.getAllSessions(o);s.set({"Cache-Control":"public, max-age=300"}),s.json(r)}}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,o=e.query.source||null;if(t<0||n<1||n>50)return s.status(400).json({error:"Invalid parameters"});let r=Math.floor(t/n)+1,i=await this.sessionService.getPaginatedSessions(r,n,o);B("SessionListLoaded",{page:r.toString(),limit:n.toString(),totalSessions:i.totalSessions.toString()}),s.json({sessions:i.sessions,hasMore:i.hasNextPage,totalSessions:i.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(!Z(t))return s.status(400).json({error:"Invalid session ID"});let n=e.query.limit!==void 0||e.query.offset!==void 0,o,r,i;if(n){if(o=parseInt(e.query.limit)||100,r=parseInt(e.query.offset)||0,o<1||o>1e3)return s.status(400).json({error:"Limit must be between 1 and 1000"});if(r<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?i=await this.sessionService.getSessionEvents(t,{limit:o,offset:r}):i=await this.sessionService.getSessionEvents(t),s.set({"Cache-Control":"no-store",Vary:"Accept-Encoding"}),n?s.json({events:i.events,pagination:{total:i.total,limit:o,offset:r,hasMore:r+o<i.total}}):s.json(i)}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(!Z(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 o=await this.sessionService.getTimeline(t),r=require("crypto"),i=`${t}-timeline-${n.updatedAt||n.createdAt}`,a=r.createHash("md5").update(i).digest("hex");s.set({ETag:a,"Cache-Control":"private, max-age=300",Vary:"Accept-Encoding"}),s.json(o)}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(!Z(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 o,r=!1;if(n.directory)try{(await O.promises.stat(n.directory)).isDirectory()&&(o=n.directory,r=!0)}catch{}if(!o&&n.filePath)try{await O.promises.access(n.filePath),o=n.filePath}catch{}if(!o){if(n.source==="copilot"){let l=this.sessionService.sessionRepository.sources.find(c=>c.type==="copilot");if(l){let c=W.join(l.dir,t);try{(await O.promises.stat(c)).isDirectory()?(o=c,r=!0):o=`${c}.jsonl`}catch{o=`${c}.jsonl`}}}else if(n.source==="claude"){let l=this.sessionService.sessionRepository.sources.find(c=>c.type==="claude");if(l){let c=await O.promises.readdir(W.join(l.dir,"projects"));for(let d of c){let u=W.join(l.dir,"projects",d,`${t}.jsonl`);try{await O.promises.access(u),o=u;break}catch{}}}}else if(n.source==="pi-mono"){let l=this.sessionService.sessionRepository.sources.find(c=>c.type==="pi-mono");if(l){let d=(await O.promises.readdir(l.dir)).find(u=>u.includes(t)&&u.endsWith(".jsonl"));d&&(o=W.join(l.dir,d))}}}if(!o)return s.status(404).json({error:"Session file not found"});try{await O.promises.access(o)}catch{return s.status(404).json({error:"Session file not accessible"})}let i=new ks;if(r)i.addLocalFolder(o,t);else{let l=W.basename(o);i.addLocalFile(o,"",l);let c=xe(),u=new c().getSessionTagsFilePath(n);try{await O.promises.access(u),i.addLocalFile(u,"",W.basename(u))}catch{}}let a=i.toBuffer();s.setHeader("Content-Type","application/zip"),s.setHeader("Content-Disposition",`attachment; filename="session-${t}.zip"`),B("SessionExported",{sessionId:t}),s.send(a)}catch(n){console.error("Error exporting session:",n),s.status(500).json({error:"Error exporting session"})}}};Et.exports=Ae});var se=b((Cn,bt)=>{var De=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(`
21
- \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)})}};bt.exports=new De});var At=b((bn,xt)=>{var I=require("fs").promises,jt=require("fs"),M=require("path"),$s=require("os"),{spawn:Ns}=require("child_process"),vt=L(),Ps=se(),Me=class{constructor(){}_getToolConfig(e,s){let t={copilot:{name:"Copilot",cli:"copilot",args:(n,o)=>["--config-dir",n,"--yolo","-p",o],cwd:s},vscode:{name:"Copilot",cli:"copilot",args:(n,o)=>["--config-dir",n,"--yolo","-p",o],cwd:s},claude:{name:"Claude Code",cli:"claude",args:(n,o)=>["-p",o,"--dangerously-skip-permissions"],cwd:s},"pi-mono":{name:"Pi",cli:"pi",args:(n,o)=>["-p",o],cwd:s}};return t[e]||t.copilot}async generateInsight(e,s,t="copilot",n=!1){let o=M.join(s,`${e}.agent-review.md`),r=M.join(s,`${e}.agent-review.md.lock`),i=M.join(s,"events.jsonl");try{await I.access(i)}catch{try{i=M.join(s,`${e}.jsonl`),await I.access(i)}catch{let d=(await I.readdir(s)).find(u=>u.endsWith(`_${e}.jsonl`));d&&(i=M.join(s,d))}}let a=this._getToolConfig(t,s),l=a.name;if(!n)try{let c=await I.readFile(o,"utf-8"),d=await I.stat(o);return{status:"completed",report:c,generatedAt:d.mtime}}catch{}try{await I.writeFile(r,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 I.readFile(r,"utf-8")),u=await I.stat(r),m=Date.now()-u.mtime.getTime();if(m<vt.INSIGHT_TIMEOUT_MS)return{status:"generating",report:`# Generating ${l} Insight...
24
+ `)}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: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||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)||{},l=this._getClaudeUsageNumber(i.cache_read_input_tokens),c=this._getClaudeCacheWriteTokens(i),u=this._getClaudeUsageNumber(i.input_tokens),d=this._getClaudeUsageNumber(i.output_tokens),f=this._getClaudeEventTotalTokens(o),g=u+l+c;if(g===0&&d===0&&f>0&&(g=Math.max(f-d,0)),g===0&&d===0)continue;let m=this._resolveClaudeUsageModel(o,t);s[m]||(s[m]={requests:{count:0},usage:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0}}),s[m].requests.count+=1,s[m].usage.inputTokens+=g,s[m].usage.outputTokens+=d,s[m].usage.cacheReadTokens+=l,s[m].usage.cacheWriteTokens+=c,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;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}}return this._extractClaudeUsageData(e)}async getSessionWithEvents(e){let s=await this.getSessionById(e);if(!s)return null;let t=await this.getSessionEvents(e),n=Jn(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"?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 l={id:`turn-${n}`,type:"user-request",message:i.data.message||"",startTime:i.timestamp,endTime:i.timestamp,assistantTurns:[],subagents:[]},c=o+1,u=0;for(;c<e.length&&e[c].type!=="user.message";){let d=e[c];if(d.type==="assistant.message"){u++,l.endTime=d.timestamp;let f={id:`assistant-${u}`,startTime:d.timestamp,endTime:d.timestamp,tools:[]};if(d.data.tools&&Array.isArray(d.data.tools))for(let g of d.data.tools)f.tools.push({name:g.name,startTime:d.timestamp,endTime:d.timestamp,status:g.status||"completed",input:g.input,result:g.result});l.assistantTurns.push(f)}c++}t.push(l)}}let r=t.reduce((o,i)=>o+i.assistantTurns.reduce((l,c)=>l+c.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(l=>l.name===(o.data.tool||o.data.name)&&!l.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,l=`pi-turn-${r}`;s.push({type:"assistant.turn_start",id:`${l}-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((c,u)=>{let d=`pi-tool-${n++}`,f=i,g=i;s.push({type:"tool.execution_start",id:`${d}-start`,timestamp:f,parentId:l,data:{toolCallId:d,toolName:c.name,tool:c.name,arguments:c.input||{}},_synthetic:!0,_fileIndex:a._fileIndex+.1+u*.01}),s.push({type:"tool.execution_complete",id:`${d}-complete`,timestamp:g,parentId:d,data:{toolCallId:d,toolName:c.name,tool:c.name,result:c.result,error:c.status==="error"?"Tool execution failed":null,isError:c.status==="error"},_synthetic:!0,_fileIndex:a._fileIndex+.15+u*.01})}),s.push({type:"assistant.turn_complete",id:`${l}-complete`,timestamp:a.timestamp,parentId:l,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,l=()=>{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 c=0;c<e.length;c++){let u=e[c];if(u.type==="tool.invocation"){let d=u.data?.subAgentId||null;t.length>0&&d!==o&&l(),t.length===0&&(n=u.parentId,r=u.timestamp,a=c,o=d,i=u.data?.subAgentName||null),u.data?.tool&&t.push(u.data.tool)}else l(),s.push(u)}return l(),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(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),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((l,c)=>{l.start&&s.push({...l.start,_fileIndex:r._fileIndex+.1+c*.02}),l.complete&&s.push({...l.complete,_fileIndex:r._fileIndex+.15+c*.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}s.push(r)}return s}_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"){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,l=a.uuid?n.get(a.uuid)||[]:[],c=a.data?.message||"";s.push({type:"assistant.turn_start",id:`${o}-start`,uuid:a.uuid,timestamp:i,parentId:a.parentId,data:{message:c,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:c,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,d)=>{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+d*.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+d*.02}))}),s.push({type:"assistant.turn_complete",id:`${o}-complete`,uuid:a.uuid,timestamp:i,parentId:o,model:a.model,_relatedUsageEvents:l.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:c},_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||ce().registry;return s?.get?s.get(e):null}};ls.exports=We});var Ge=w((Kr,cs)=>{var O=require("fs").promises,R=require("path"),Kn=require("os"),Je=class{constructor(){this.knownTagsDir=R.join(Kn.homedir(),".session-viewer"),this.knownTagsFilePath=R.join(this.knownTagsDir,"known-tags.json")}async ensureKnownTagsFile(){try{await O.access(this.knownTagsFilePath)}catch{await O.mkdir(this.knownTagsDir,{recursive:!0}),await O.writeFile(this.knownTagsFilePath,JSON.stringify([]),"utf8")}}async readKnownTagsFile(){await this.ensureKnownTagsFile();try{let e=await O.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 O.writeFile(this.knownTagsFilePath,JSON.stringify(e,null,2),"utf8")}getSessionTagsFilePath(e){if(e.filePath){let s=R.dirname(e.filePath),t=R.basename(e.filePath,R.extname(e.filePath));return R.join(s,`${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 s=this.getSessionTagsFilePath(e);try{await O.access(s);let t=await O.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 O.unlink(n)}catch{}else await O.mkdir(R.dirname(n),{recursive:!0}),await O.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=Je});var ms=w((Yr,ps)=>{var Yn=He(),{isValidSessionId:ae,buildMetadata:us}=z(),{trackEvent:G,trackMetric:ds}=U(),Zn=require("adm-zip"),K=require("path"),q=require("fs"),Ke=class{constructor(e=null){this.sessionService=e||new Yn}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(!ae(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=us(n);try{let i=await this.sessionService.getSessionEvents(t),l=this.sessionService.extractUsageData(i);l&&(r.usage=l)}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&&ds("SessionEventCount",a,{sessionId:t,source:n.source||"unknown"});let o=n.duration||r.duration||0;o>0&&ds("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(!ae(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=us(n);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(!ae(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(!ae(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(!ae(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 q.promises.stat(n.directory)).isDirectory()&&(r=n.directory,a=!0)}catch{}if(!r&&n.filePath)try{await q.promises.access(n.filePath),r=n.filePath}catch{}if(!r){if(n.source==="copilot"){let l=this.sessionService.sessionRepository.sources.find(c=>c.type==="copilot");if(l){let c=K.join(l.dir,t);try{(await q.promises.stat(c)).isDirectory()?(r=c,a=!0):r=`${c}.jsonl`}catch{r=`${c}.jsonl`}}}else if(n.source==="claude"){let l=this.sessionService.sessionRepository.sources.find(c=>c.type==="claude");if(l){let c=await q.promises.readdir(K.join(l.dir,"projects"));for(let u of c){let d=K.join(l.dir,"projects",u,`${t}.jsonl`);try{await q.promises.access(d),r=d;break}catch{}}}}else if(n.source==="pi-mono"){let l=this.sessionService.sessionRepository.sources.find(c=>c.type==="pi-mono");if(l){let u=(await q.promises.readdir(l.dir)).find(d=>d.includes(t)&&d.endsWith(".jsonl"));u&&(r=K.join(l.dir,u))}}}if(!r)return s.status(404).json({error:"Session file not found"});try{await q.promises.access(r)}catch{return s.status(404).json({error:"Session file not accessible"})}let o=new Zn;if(a)o.addLocalFolder(r,t);else{let l=K.basename(r);o.addLocalFile(r,"",l);let c=Ge(),d=new c().getSessionTagsFilePath(n);try{await q.promises.access(d),o.addLocalFile(d,"",K.basename(d))}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"})}}};ps.exports=Ke});var de=w((Zr,fs)=>{var Ye=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(`
26
+ \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)})}},Ze="__copilotSessionViewerProcessManager";globalThis[Ze]||(globalThis[Ze]=new Ye);fs.exports=globalThis[Ze]});var Ss=w((Xr,ys)=>{var _=require("fs").promises,gs=require("fs"),j=require("path"),Xn=require("os"),{spawn:Qn}=require("child_process"),hs=L(),er=de(),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=j.join(s,`${e}.agent-review.md`),a=j.join(s,`${e}.agent-review.md.lock`),o=j.join(s,"events.jsonl");try{await _.access(o)}catch{try{o=j.join(s,`${e}.jsonl`),await _.access(o)}catch{let u=(await _.readdir(s)).find(d=>d.endsWith(`_${e}.jsonl`));u&&(o=j.join(s,u))}}let i=this._getToolConfig(t,s),l=i.name;if(!n)try{let c=await _.readFile(r,"utf-8"),u=await _.stat(r);return{status:"completed",report:c,generatedAt:u.mtime}}catch{}try{await _.writeFile(a,JSON.stringify({sessionId:e,startTime:new Date().toISOString(),pid:process.pid}),{flag:"wx"})}catch(c){if(c.code==="EEXIST")try{let u=JSON.parse(await _.readFile(a,"utf-8")),d=await _.stat(a),f=Date.now()-d.mtime.getTime();if(f<hs.INSIGHT_TIMEOUT_MS)return{status:"generating",report:`# Generating ${l} Insight...
22
27
 
23
- Another request is currently generating this insight. Please wait.`,startedAt:u.birthtime,lastUpdate:u.mtime,ageMs:Date.now()-u.birthtime.getTime()};console.log(`\u26A0\uFE0F Removing stale lock file (${Math.floor(m/1e3)}s old)`),await I.unlink(r),await I.writeFile(r,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 I.access(i)}catch(c){throw await I.unlink(r),new Error("Events file not found",{cause:c})}if(n)try{await I.unlink(o)}catch{}return await this._spawnAnalysisProcess(s,i,o,r,a),{status:"generating",report:`# Generating ${l} Insight...
28
+ Another request is currently generating this insight. Please wait.`,startedAt:d.birthtime,lastUpdate:d.mtime,ageMs:Date.now()-d.birthtime.getTime()};console.log(`\u26A0\uFE0F Removing stale lock file (${Math.floor(f/1e3)}s old)`),await _.unlink(a),await _.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 c}try{await _.access(o)}catch(c){throw await _.unlink(a),new Error("Events file not found",{cause:c})}if(n)try{await _.unlink(r)}catch{}return await this._spawnAnalysisProcess(s,o,r,a,i),{status:"generating",report:`# Generating ${l} Insight...
24
29
 
25
- Analysis in progress. Please wait.`,startedAt:new Date}}async _spawnAnalysisProcess(e,s,t,n,o){let r=M.basename(e),i=M.join($s.tmpdir(),`agent-review-${r}-${Date.now()}`);await I.mkdir(i,{recursive:!0});let a=this._buildPrompt(t,s),l=M.join(e,`${r}.agent-review.md.tmp`),c=o.cli,d=o.args(i,a);console.log(`\u{1F916} Starting ${o.name} analysis: ${c} ${d.slice(0,2).join(" ")}...`),console.log(`\u{1F4CB} Args count: ${d.length}, prompt length: ${a.length} chars`);let u=Ns(c,d,{env:{...process.env},cwd:e,stdio:["pipe","pipe","pipe"]});if(Ps.register(u,{name:`insight-${r}`}),o.cli==="copilot"){let _=jt.createReadStream(s);u.stdin.on("error",y=>{y.code==="EPIPE"?_.destroy():console.error("\u274C stdin error:",y)}),_.pipe(u.stdin)}else u.stdin.end();let m=jt.createWriteStream(l);u.stdout.pipe(m);let f=[],g=0,w=64*1024;u.stderr.on("data",_=>{g<w&&(f.push(_),g+=_.length)}),u.on("close",async _=>{try{m.end();let y=Buffer.concat(f).toString("utf-8").slice(0,w);if(console.log(`\u{1F4CB} ${o.name} process exited with code ${_}`),y&&console.log(`\u{1F4CB} ${o.name} stderr:`,y.substring(0,500)),_!==0)console.error(`\u274C ${o.name} CLI failed (code ${_}):`,y),await I.writeFile(t,`# \u274C Generation Failed
30
+ Analysis in progress. Please wait.`,startedAt:new Date}}async _spawnAnalysisProcess(e,s,t,n,r){let a=j.basename(e),o=j.join(Xn.tmpdir(),`agent-review-${a}-${Date.now()}`);await _.mkdir(o,{recursive:!0});let i=this._buildPrompt(t,s),l=j.join(e,`${a}.agent-review.md.tmp`),c=r.cli,u=r.args(o,i);console.log(`\u{1F916} Starting ${r.name} analysis: ${c} ${u.slice(0,2).join(" ")}...`),console.log(`\u{1F4CB} Args count: ${u.length}, prompt length: ${i.length} chars`);let d=Qn(c,u,{env:{...process.env},cwd:e,stdio:["pipe","pipe","pipe"]});if(er.register(d,{name:`insight-${a}`}),r.cli==="copilot"){let S=gs.createReadStream(s);d.stdin.on("error",T=>{T.code==="EPIPE"?S.destroy():console.error("\u274C stdin error:",T)}),S.pipe(d.stdin)}else d.stdin.end();let f=gs.createWriteStream(l);d.stdout.pipe(f);let g=[],m=0,y=64*1024;d.stderr.on("data",S=>{m<y&&(g.push(S),m+=S.length)}),d.on("close",async S=>{try{f.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
26
31
 
27
- Exit code: ${_}
32
+ Exit code: ${S}
28
33
 
29
34
  \`\`\`
30
- ${y||"(no error output)"}
35
+ ${T||"(no error output)"}
31
36
  \`\`\`
32
- `,"utf-8");else{let j=!1;try{let v=await I.readFile(t,"utf-8");v&&v.trim().length>50&&(j=!0,console.log(`\u2705 Insight generated for session ${r} (agent wrote directly)`))}catch{}if(!j){let v=await I.readFile(l,"utf-8");v=this._cleanReport(v),await I.writeFile(t,v,"utf-8"),console.log(`\u2705 Insight generated for session ${r} (cleaned from stdout)`)}}await I.unlink(l).catch(()=>{}),await I.unlink(n).catch(()=>{}),await I.rm(i,{recursive:!0,force:!0}).catch(()=>{}),await I.rm(M.join(e,".output"),{recursive:!0,force:!0}).catch(()=>{})}catch(y){console.error("\u274C Error finalizing insight:",y),await I.unlink(n).catch(()=>{}),await I.rm(i,{recursive:!0,force:!0}).catch(()=>{})}}),u.on("error",async _=>{console.error(`\u274C Failed to spawn ${o.name}:`,_),await I.unlink(n).catch(()=>{}),await I.rm(i,{recursive:!0,force:!0}).catch(()=>{})})}_buildPrompt(e,s){let t=M.dirname(e),n=M.basename(s),o=`${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.
37
+ `,"utf-8");else{let b=!1;try{let x=await _.readFile(t,"utf-8");x&&x.trim().length>50&&(b=!0,console.log(`\u2705 Insight generated for session ${a} (agent wrote directly)`))}catch{}if(!b){let x=await _.readFile(l,"utf-8");x=this._cleanReport(x),await _.writeFile(t,x,"utf-8"),console.log(`\u2705 Insight generated for session ${a} (cleaned from stdout)`)}}await _.unlink(l).catch(()=>{}),await _.unlink(n).catch(()=>{}),await _.rm(o,{recursive:!0,force:!0}).catch(()=>{}),await _.rm(j.join(e,".output"),{recursive:!0,force:!0}).catch(()=>{})}catch(T){console.error("\u274C Error finalizing insight:",T),await _.unlink(n).catch(()=>{}),await _.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}),d.on("error",async S=>{console.error(`\u274C Failed to spawn ${r.name}:`,S),await _.unlink(n).catch(()=>{}),await _.rm(o,{recursive:!0,force:!0}).catch(()=>{})})}_buildPrompt(e,s){let t=j.dirname(e),n=j.basename(s),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.
33
38
  ${n.includes("_")?`
34
39
  **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.
35
40
  `:""}
@@ -39,27 +44,27 @@ ${n.includes("_")?`
39
44
  - \`workspace.yaml\` \u2014 workspace configuration (if it exists).
40
45
  - Any other relevant files.
41
46
 
42
- **Step 2 \u2014 Spawn 3 sub-agents for parallel analysis.** First create the working directory: \`mkdir -p ${o}\`. 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:
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:
43
48
  - Read \`${n}\` from \`${t}\` (use Bash: \`cat\`, \`jq\`, or \`python3\` to parse) **\u2014 ONLY this file, ignore others**
44
49
  - Read other session files as needed
45
- - Write its findings to an intermediate file in \`${o}/\`
50
+ - Write its findings to an intermediate file in \`${r}/\`
46
51
  - Return a summary of its findings
47
52
 
48
53
  Sub-agents to spawn:
49
54
 
50
- 1. **Tool Usage Analyst** \u2014 Analyze tool selection quality, redundant/wasted calls, error handling patterns, tool call counts and durations. Write findings to \`${o}/tools.md\`.
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\`.
51
56
 
52
- 2. **Workflow Strategist** \u2014 Evaluate planning quality, sequencing logic, sub-agent decomposition, backtracking/wandering patterns. Write findings to \`${o}/workflow.md\`.
57
+ 2. **Workflow Strategist** \u2014 Evaluate planning quality, sequencing logic, sub-agent decomposition, backtracking/wandering patterns. Write findings to \`${r}/workflow.md\`.
53
58
 
54
- 3. **Performance Profiler** \u2014 Calculate time distribution (LLM thinking vs tool execution vs idle gaps), identify bottlenecks, assess concurrency usage. Write findings to \`${o}/performance.md\`.
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\`.
55
60
 
56
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.
57
62
 
58
63
  **Step 3 \u2014 Synthesize the final report.** Once all sub-agents are done:
59
- 1. Read the intermediate files from \`${o}/\`
64
+ 1. Read the intermediate files from \`${r}/\`
60
65
  2. Synthesize a unified report
61
66
  3. Write the final report to \`${e}\`
62
- 4. Clean up by removing the entire working directory: \`rm -rf ${o}\`
67
+ 4. Clean up by removing the entire working directory: \`rm -rf ${r}\`
63
68
 
64
69
  The final report must be a markdown file with these sections:
65
70
 
@@ -91,9 +96,9 @@ Be brutally honest. Generic advice like "add error handling" is useless \u2014 a
91
96
 
92
97
  IMPORTANT CONSTRAINTS:
93
98
  - Be precise and concise. Every sentence must carry data or actionable insight \u2014 no filler, no fluff.
94
- - 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 s=/^## 🎯\s*Effectiveness Score/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 o=e.split(`
95
- `),r=[],i=!1;for(let a of o){if(/^● /.test(a)){i=!0;continue}if(/^ {2}\$ /.test(a)){i=!0;continue}if(/^ {2}└ /.test(a)){i=!1;continue}if(!/^\(\+\d+ lines?\)/.test(a)&&!/^ {2}└ \d+ lines/.test(a)){if(/^● Asked user:/.test(a)){i=!0;continue}if(/^ {2}└ User responded:/.test(a)){i=!1;continue}i&&/\S/.test(a)&&!/^ {2}/.test(a)&&(i=!1),!i&&r.push(a)}}e=r.join(`
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 s=/^## 🎯\s*Effectiveness Score/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(`
100
+ `),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(`
96
101
  `)}}return e=e.replace(/\n{3,}/g,`
97
102
 
98
- `).trim(),e}async getInsightStatus(e,s,t="copilot"){return await this._getStatusForSource(e,s)}async _getStatusForSource(e,s){let t=M.join(s,`${e}.agent-review.md`),n=M.join(s,`${e}.agent-review.md.lock`),o=M.join(s,`${e}.agent-review.md.tmp`);try{let r=await I.readFile(t,"utf-8"),i=await I.stat(t);return{status:"completed",report:r,generatedAt:i.mtime}}catch{try{await I.access(n);let i=await I.stat(n),a=Date.now()-i.birthtime.getTime(),l=null;try{l=await I.readFile(o,"utf-8")}catch{}return a>=vt.INSIGHT_TIMEOUT_MS?{status:"timeout",log:l,startedAt:i.birthtime,lastUpdate:i.mtime,ageMs:a}:{status:"generating",log:l,startedAt:i.birthtime,lastUpdate:i.mtime,ageMs:a}}catch{return{status:"not_started"}}}}async deleteInsight(e,s,t="copilot"){let n=M.join(s,`${e}.agent-review.md`);try{return await I.unlink(n),{success:!0}}catch(o){if(o.code==="ENOENT")return{success:!0,message:"Insight file not found"};throw o}}};xt.exports=Me});var Mt=b((jn,Dt)=>{var Os=At(),{isValidSessionId:ke}=U(),{trackEvent:$e,trackMetric:Rs,trackException:Fs}=R(),Ne=class{constructor(e=null,s=null){if(e?this.insightService=e:this.insightService=new Os,s)this.sessionService=s;else{let t=je();this.sessionService=new t}}async generateInsight(e,s){try{let t=e.params.id,n=e.body?.force===!0;if(!ke(t))return s.status(400).json({error:"Invalid session ID"});let o=await this.sessionService.getSessionById(t);if(!o)return s.status(404).json({error:"Session not found"});if(!o.directory)return s.status(400).json({error:"Session directory not available"});let r=Date.now(),i=await this.insightService.generateInsight(o.id,o.directory,o.source,n),a=Date.now()-r;$e("InsightGenerated",{sessionId:t,source:o.source||"unknown",durationMs:a.toString()}),Rs("InsightGenerationTime",a,{sessionId:t,source:o.source||"unknown"}),s.json(i)}catch(t){console.error("Error generating insight:",t),Fs(t,{sessionId:e.params.id,operation:"generateInsight"}),s.status(500).json({error:t.message||"Error generating insight"})}}async getInsightStatus(e,s){try{let t=e.params.id;if(!ke(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 o=await this.insightService.getInsightStatus(n.id,n.directory,n.source);o.status==="ready"&&o.report&&$e("InsightViewed",{sessionId:t}),s.json(o)}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(!ke(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 o=await this.insightService.deleteInsight(n.id,n.directory,n.source);$e("InsightDeleted",{sessionId:t}),s.json(o)}catch(t){console.error("Error deleting insight:",t),s.status(500).json({error:"Error deleting insight"})}}};Dt.exports=Ne});var Pt=b((vn,Nt)=>{var h=require("fs"),T=require("path"),X=require("os"),qs=require("multer"),{spawn:Pe}=require("child_process"),{isValidSessionId:G}=U(),{trackEvent:kt,trackException:Oe}=R(),$t=se(),Ls=L(),Re=class{constructor(){this.SESSION_DIR=process.env.SESSION_DIR||T.join(X.homedir(),".copilot","session-state"),this.uploadDir=process.env.UPLOAD_DIR||T.join(X.tmpdir(),"copilot-session-uploads"),this.SESSION_DIRS={copilot:this.SESSION_DIR,claude:T.join(X.homedir(),".claude","projects"),"pi-mono":T.join(X.homedir(),".pi","agent","sessions")},this.upload=this.createMulterInstance()}createMulterInstance(){return qs({dest:this.uploadDir,limits:{fileSize:Ls.MAX_UPLOAD_SIZE},fileFilter:(e,s,t)=>{let n=s.originalname.toLowerCase().endsWith(".zip"),o=s.mimetype==="application/zip"||s.mimetype==="application/x-zip-compressed";if(!n||!o)return t(new Error("Only .zip files are allowed"));t(null,!0)}})}async shareSession(e,s){try{let t=e.params.id;if(!G(t))return s.status(400).json({error:"Invalid session ID"});let n=T.join(this.SESSION_DIR,t);try{await h.promises.access(n)}catch{return s.status(404).json({error:"Session not found"})}let o=T.join(X.tmpdir(),`session-${t}.zip`),r=Pe("zip",["-r","-q",o,t],{cwd:this.SESSION_DIR});$t.register(r,{name:`zip-${t}`}),r.on("close",i=>{if(i!==0)return s.status(500).json({error:"Failed to create zip file"});kt("SessionShared",{sessionId:t}),s.download(o,`session-${t}.zip`,a=>{h.promises.unlink(o).catch(()=>{}),a&&console.error("Error sending zip:",a)})}),r.on("error",i=>{console.error("Error creating zip:",i),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=T.join(this.uploadDir,`extract-${Date.now()}`);await h.promises.mkdir(n,{recursive:!0});let o=50*1024*1024,r=200*1024*1024,i=1e3,a=5;if((await h.promises.stat(t)).size>o)return await h.promises.unlink(t),s.status(400).json({error:"Compressed file too large (max 50MB)"});let c=Pe("unzip",["-l",t]),d="";c.stdout.on("data",_=>{d+=_.toString()}),await new Promise((_,y)=>{c.on("close",j=>{j!==0?y(new Error("Failed to list zip contents")):_()}),c.on("error",y)});let u=d.split(`
99
- `),m=0,f=0,g=0;for(let _ of u){let y=_.trim().match(/^\s*(\d+)\s+\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}\s+(.+)$/);if(y){let j=parseInt(y[1]),v=y[2];m+=j,f++;let q=(v.match(/\//g)||[]).length;g=Math.max(g,q)}}if(m>r)return await h.promises.unlink(t),s.status(400).json({error:`Uncompressed size too large (${Math.round(m/1024/1024)}MB > ${r/1024/1024}MB)`});if(f>i)return await h.promises.unlink(t),s.status(400).json({error:`Too many files in archive (${f} > ${i})`});if(g>a)return await h.promises.unlink(t),s.status(400).json({error:`Directory nesting too deep (${g} > ${a})`});let w=Pe("unzip",["-q",t,"-d",n]);$t.register(w,{name:"unzip-import"}),w.on("close",async _=>{let y;try{if(await h.promises.unlink(t),_!==0)return await h.promises.rm(n,{recursive:!0,force:!0}),s.status(500).json({error:"Failed to extract zip file"});let j=await h.promises.readdir(n);if(j.length===0)return await h.promises.rm(n,{recursive:!0,force:!0}),s.status(400).json({error:"Empty zip file"});if(y=j[0],!G(y))return await h.promises.rm(n,{recursive:!0,force:!0}),s.status(400).json({error:"Invalid session directory name in zip file"});let v=T.join(n,y),q=T.join(this.SESSION_DIR,y),oe=T.join(v,"events.jsonl");try{await h.promises.access(oe)}catch{return await h.promises.rm(n,{recursive:!0,force:!0}),s.status(400).json({error:"Invalid session structure (no events.jsonl)"})}if(h.existsSync(q))return await h.promises.rm(n,{recursive:!0,force:!0}),s.status(409).json({error:"Session already exists"});await h.promises.rename(v,q),await h.promises.rm(n,{recursive:!0,force:!0});let re=await h.promises.stat(t).catch(()=>({size:0}));kt("SessionImported",{format:"copilot",fileSize:re.size.toString()}),s.json({success:!0,sessionId:y})}catch(j){console.error("Error importing session:",j),Oe(j,{operation:"importSession",sessionId:y||"unknown"}),await h.promises.rm(n,{recursive:!0,force:!0}).catch(()=>{}),s.status(500).json({error:"Error importing session"})}}),w.on("error",async _=>{console.error("Error extracting zip:",_),Oe(_,{operation:"importSession_unzip"}),await h.promises.unlink(t).catch(()=>{}),await h.promises.rm(n,{recursive:!0,force:!0}).catch(()=>{}),s.status(500).json({error:"Failed to extract zip file"})})}catch(t){console.error("Error processing upload:",t),Oe(t,{operation:"importSession_upload"}),e.file&&await h.promises.unlink(e.file.path).catch(()=>{}),s.status(500).json({error:"Error processing upload"})}}getUploadMiddleware(){return this.upload.single("zipFile")}async _detectFormat(e){try{let s=await h.promises.readdir(e);if(s.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 o of s){let r=o.match(t);if(r)return{format:"pi-mono",sessionId:r[1],fileName:o,extractDir:e}}for(let o of s){let r=T.join(e,o);if((await h.promises.stat(r)).isDirectory()){let a=T.join(r,"events.jsonl");if(h.existsSync(a))return{format:"copilot",sessionId:o,directoryName:o,extractDir:e}}}let n=/^([a-zA-Z0-9_-]+)\.jsonl$/;for(let o of s){let r=T.join(e,o);if((await h.promises.stat(r)).isFile()){let a=o.match(n);if(a){let l=a[1],c=T.join(e,l),d=h.existsSync(c);return{format:"claude",sessionId:l,fileName:o,hasDirectory:d,directoryName:d?l:void 0,extractDir:e}}}}return null}catch(s){return console.error("Error detecting format:",s),null}}async _importCopilotSession(e,s){try{let{sessionId:t,directoryName:n}=e;if(!G(t))return{success:!1,error:"Invalid session ID",statusCode:400};let o=T.join(s,n),r=T.join(this.SESSION_DIRS.copilot,t),i=T.join(o,"events.jsonl");return h.existsSync(i)?h.existsSync(r)?{success:!1,error:"Session already exists",statusCode:409}:(await h.promises.rename(o,r),await h.promises.writeFile(T.join(r,".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,s,t){try{let{sessionId:n,fileName:o,hasDirectory:r,directoryName:i}=e;if(!G(n))return{success:!1,error:"Invalid session ID",statusCode:400};let a=t.query.project||"imported-sessions",l=T.join(this.SESSION_DIRS.claude,a);await h.promises.mkdir(l,{recursive:!0});let c=T.join(s,o),d=T.join(l,o);if(await h.promises.rename(c,d),r&&i){let u=T.join(s,i),m=T.join(l,i);await h.promises.rename(u,m)}return{success:!0,sessionId:n,format:"claude",project:a}}catch(n){return console.error("Error importing Claude session:",n),{success:!1,error:`Error importing Claude session: ${n.message}`,statusCode:500}}}async _importPiMonoSession(e,s,t){try{let{sessionId:n,fileName:o}=e;if(!G(n))return{success:!1,error:"Invalid session ID",statusCode:400};let r=t.query.project||"imported-sessions",i=T.join(this.SESSION_DIRS["pi-mono"],r);await h.promises.mkdir(i,{recursive:!0});let a=T.join(s,o),l=T.join(i,o);return await h.promises.rename(a,l),{success:!0,sessionId:n,format:"pi-mono",project:r}}catch(n){return console.error("Error importing Pi-Mono session:",n),{success:!1,error:`Error importing Pi-Mono session: ${n.message}`,statusCode:500}}}async _importByFormat(e,s,t){if(!G(e.sessionId))return{success:!1,error:"Invalid session ID",statusCode:400};switch(e.format){case"copilot":return await this._importCopilotSession(e,s);case"claude":return await this._importClaudeSession(e,s,t);case"pi-mono":return await this._importPiMonoSession(e,s,t);default:return{success:!1,error:`Unsupported format: ${e.format}`,statusCode:400}}}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 o=this.SESSION_DIRS[n];if(n==="copilot"){let r=T.join(o,e);if(h.existsSync(r)){let i=T.join(r,"events.jsonl");if(h.existsSync(i))return{source:"copilot",sessionId:e,sessionPath:r,baseDir:o}}}else if(n==="claude"){if(h.existsSync(o)){let r=await h.promises.readdir(o);for(let i of r){let a=T.join(o,i);if((await h.promises.stat(a)).isDirectory()){let c=T.join(a,`${e}.jsonl`);if(h.existsSync(c))return{source:"claude",sessionId:e,sessionFile:c,projectPath:a,project:i,baseDir:o}}}}}else if(n==="pi-mono"&&h.existsSync(o)){let r=await h.promises.readdir(o);for(let i of r){let a=T.join(o,i);if((await h.promises.stat(a)).isDirectory()){let c=await h.promises.readdir(a),d=new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-\\d{3}Z_${e}\\.jsonl$`);for(let u of c)if(d.test(u))return{source:"pi-mono",sessionId:e,fileName:u,sessionFile:T.join(a,u),projectPath:a,project:i,baseDir:o}}}}}return null}catch(t){return console.error("Error finding session location:",t),null}}};Nt.exports=Re});var Ft=b((xn,Rt)=>{var Us=xe(),zs=Ee(),{isValidSessionId:Ot}=U(),{trackEvent:Vs}=R(),Fe=class{constructor(e=null,s=null){this.tagService=e||new Us,this.sessionRepository=s||new zs}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(!Ot(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 o=await this.tagService.getSessionTags(n);s.json({tags:o})}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(!Ot(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 i of n){if(typeof i!="string"||i.trim().length===0)return s.status(400).json({error:"Tags must be non-empty strings"});if(i.length>30)return s.status(400).json({error:"Tag length must not exceed 30 characters"})}let o=await this.sessionRepository.findById(t);if(!o)return s.status(404).json({error:"Session not found"});let r=await this.tagService.setSessionTags(o,n);Vs("TagUpdated",{sessionId:t,tagCount:r.length.toString()}),s.json({tags:r})}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"})}}};Rt.exports=Fe});var zt=b((An,Ut)=>{var ne=require("express"),qt=require("path"),Lt=require("compression"),Bs=require("helmet"),Ws=L(),{requestTimeout:Gs,developmentCors:Js,errorHandler:Hs,notFoundHandler:Ks,telemetryLocals:Ys}=Ke(),Zs=Ct(),Xs=Mt(),Qs=Pt(),en=Ft();function tn(p={}){let e=ne();e.set("etag",!1);let s=new Zs(p.sessionService),t=new Xs(p.insightService,p.sessionService),n=new Qs,o=new en(p.tagService);return e.use((r,i,a)=>{i.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:"),a()}),e.use(Bs({contentSecurityPolicy:!1,hsts:!1,referrerPolicy:!1,crossOriginEmbedderPolicy:!1,crossOriginOpenerPolicy:!1,crossOriginResourcePolicy:!1})),e.use(Lt({level:1,threshold:1024,filter:(r,i)=>r.path.includes("/events")&&i.getHeader("Content-Type")?.includes("application/json")?!1:Lt.filter(r,i)})),e.use(ne.json({limit:"1mb"})),e.use(ne.urlencoded({extended:!0})),e.use(Gs),e.use(Ys),Ws.NODE_ENV==="development"&&e.use(Js),e.use("/public",ne.static(qt.join(__dirname,"../public"))),e.set("view engine","ejs"),e.set("views",qt.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",o.getAllTags.bind(o)),e.get("/api/sessions/:id/tags",o.getSessionTags.bind(o)),e.put("/api/sessions/:id/tags",o.setSessionTags.bind(o)),e.get("/session/:id/share",n.shareSession.bind(n)),e.post("/session/import",(r,i,a)=>n.getUploadMiddleware()(r,i,a),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(Ks),e.use(Hs),e}Ut.exports=tn});R();var sn=zt(),qe=L(),nn=se(),Vt=sn();module.exports=Vt;if(require.main===module){let p=Vt.listen(qe.PORT,()=>{console.log(`\u{1F680} Copilot Session Viewer running at http://localhost:${qe.PORT}`),console.log(`\u{1F527} Environment: ${qe.NODE_ENV}`),console.log(`\u26A1 Active processes: ${nn.getActiveCount()}`)});process.on("SIGTERM",()=>{console.log("\u{1F4DB} SIGTERM received, closing server..."),p.close(()=>{console.log("\u2705 Server closed")})})}
103
+ `).trim(),e}async getInsightStatus(e,s,t="copilot"){return await this._getStatusForSource(e,s)}async _getStatusForSource(e,s){let t=j.join(s,`${e}.agent-review.md`),n=j.join(s,`${e}.agent-review.md.lock`),r=j.join(s,`${e}.agent-review.md.tmp`);try{let a=await _.readFile(t,"utf-8"),o=await _.stat(t);return{status:"completed",report:a,generatedAt:o.mtime}}catch{try{await _.access(n);let o=await _.stat(n),i=Date.now()-o.birthtime.getTime(),l=null;try{l=await _.readFile(r,"utf-8")}catch{}return i>=hs.INSIGHT_TIMEOUT_MS?{status:"timeout",log:l,startedAt:o.birthtime,lastUpdate:o.mtime,ageMs:i}:{status:"generating",log:l,startedAt:o.birthtime,lastUpdate:o.mtime,ageMs:i}}catch{return{status:"not_started"}}}}async deleteInsight(e,s,t="copilot"){let n=j.join(s,`${e}.agent-review.md`);try{return await _.unlink(n),{success:!0}}catch(r){if(r.code==="ENOENT")return{success:!0,message:"Insight file not found"};throw r}}};ys.exports=Xe});var _s=w((Qr,ws)=>{var tr=Ss(),{isValidSessionId:Qe}=z(),{trackEvent:et,trackMetric:sr,trackException:nr}=U(),tt=class{constructor(e=null,s=null){if(e?this.insightService=e:this.insightService=new tr,s)this.sessionService=s;else{let t=He();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(!Qe(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;et("InsightGenerated",{sessionId:t,source:r.source||"unknown",durationMs:i.toString()}),sr("InsightGenerationTime",i,{sessionId:t,source:r.source||"unknown"}),s.json(o)}catch(t){console.error("Error generating insight:",t),nr(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(!Qe(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&&et("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(!Qe(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);et("InsightDeleted",{sessionId:t}),s.json(r)}catch(t){console.error("Error deleting insight:",t),s.status(500).json({error:"Error deleting insight"})}}};ws.exports=tt});var bs=w((ea,Es)=>{var h=require("fs"),I=require("path"),oe=require("os"),rr=require("multer"),{spawn:st}=require("child_process"),{isValidSessionId:Y}=z(),{trackEvent:Is,trackException:nt}=U(),Ts=de(),ar=L(),rt=class{constructor(){this.SESSION_DIR=process.env.SESSION_DIR||I.join(oe.homedir(),".copilot","session-state"),this.uploadDir=process.env.UPLOAD_DIR||I.join(oe.tmpdir(),"copilot-session-uploads"),this.SESSION_DIRS={copilot:this.SESSION_DIR,claude:I.join(oe.homedir(),".claude","projects"),"pi-mono":I.join(oe.homedir(),".pi","agent","sessions")},this.upload=this.createMulterInstance()}createMulterInstance(){return rr({dest:this.uploadDir,limits:{fileSize:ar.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(!Y(t))return s.status(400).json({error:"Invalid session ID"});let n=I.join(this.SESSION_DIR,t);try{await h.promises.access(n)}catch{return s.status(404).json({error:"Session not found"})}let r=I.join(oe.tmpdir(),`session-${t}.zip`),a=st("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=>{h.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=I.join(this.uploadDir,`extract-${Date.now()}`);await h.promises.mkdir(n,{recursive:!0});let r=50*1024*1024,a=200*1024*1024,o=1e3,i=5;if((await h.promises.stat(t)).size>r)return await h.promises.unlink(t),s.status(400).json({error:"Compressed file too large (max 50MB)"});let c=st("unzip",["-l",t]),u="";c.stdout.on("data",S=>{u+=S.toString()}),await new Promise((S,T)=>{c.on("close",b=>{b!==0?T(new Error("Failed to list zip contents")):S()}),c.on("error",T)});let d=u.split(`
104
+ `),f=0,g=0,m=0;for(let S of d){let T=S.trim().match(/^\s*(\d+)\s+\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}\s+(.+)$/);if(T){let b=parseInt(T[1]),x=T[2];f+=b,g++;let F=(x.match(/\//g)||[]).length;m=Math.max(m,F)}}if(f>a)return await h.promises.unlink(t),s.status(400).json({error:`Uncompressed size too large (${Math.round(f/1024/1024)}MB > ${a/1024/1024}MB)`});if(g>o)return await h.promises.unlink(t),s.status(400).json({error:`Too many files in archive (${g} > ${o})`});if(m>i)return await h.promises.unlink(t),s.status(400).json({error:`Directory nesting too deep (${m} > ${i})`});let y=st("unzip",["-q",t,"-d",n]);Ts.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(n,{recursive:!0,force:!0}),s.status(500).json({error:"Failed to extract zip file"});let b=await h.promises.readdir(n);if(b.length===0)return await h.promises.rm(n,{recursive:!0,force:!0}),s.status(400).json({error:"Empty zip file"});if(T=b[0],!Y(T))return await h.promises.rm(n,{recursive:!0,force:!0}),s.status(400).json({error:"Invalid session directory name in zip file"});let x=I.join(n,T),F=I.join(this.SESSION_DIR,T),me=I.join(x,"events.jsonl");try{await h.promises.access(me)}catch{return await h.promises.rm(n,{recursive:!0,force:!0}),s.status(400).json({error:"Invalid session structure (no events.jsonl)"})}if(h.existsSync(F))return await h.promises.rm(n,{recursive:!0,force:!0}),s.status(409).json({error:"Session already exists"});await h.promises.rename(x,F),await h.promises.rm(n,{recursive:!0,force:!0});let fe=await h.promises.stat(t).catch(()=>({size:0}));Is("SessionImported",{format:"copilot",fileSize:fe.size.toString()}),s.json({success:!0,sessionId:T})}catch(b){console.error("Error importing session:",b),nt(b,{operation:"importSession",sessionId:T||"unknown"}),await h.promises.rm(n,{recursive:!0,force:!0}).catch(()=>{}),s.status(500).json({error:"Error importing session"})}}),y.on("error",async S=>{console.error("Error extracting zip:",S),nt(S,{operation:"importSession_unzip"}),await h.promises.unlink(t).catch(()=>{}),await h.promises.rm(n,{recursive:!0,force:!0}).catch(()=>{}),s.status(500).json({error:"Failed to extract zip file"})})}catch(t){console.error("Error processing upload:",t),nt(t,{operation:"importSession_upload"}),e.file&&await h.promises.unlink(e.file.path).catch(()=>{}),s.status(500).json({error:"Error processing upload"})}}getUploadMiddleware(){return this.upload.single("zipFile")}async _detectFormat(e){try{let s=await h.promises.readdir(e);if(s.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 s){let a=r.match(t);if(a)return{format:"pi-mono",sessionId:a[1],fileName:r,extractDir:e}}for(let r of s){let a=I.join(e,r);if((await h.promises.stat(a)).isDirectory()){let i=I.join(a,"events.jsonl");if(h.existsSync(i))return{format:"copilot",sessionId:r,directoryName:r,extractDir:e}}}let n=/^([a-zA-Z0-9_-]+)\.jsonl$/;for(let r of s){let a=I.join(e,r);if((await h.promises.stat(a)).isFile()){let i=r.match(n);if(i){let l=i[1],c=I.join(e,l),u=h.existsSync(c);return{format:"claude",sessionId:l,fileName:r,hasDirectory:u,directoryName:u?l:void 0,extractDir:e}}}}return null}catch(s){return console.error("Error detecting format:",s),null}}async _importCopilotSession(e,s){try{let{sessionId:t,directoryName:n}=e;if(!Y(t))return{success:!1,error:"Invalid session ID",statusCode:400};let r=I.join(s,n),a=I.join(this.SESSION_DIRS.copilot,t),o=I.join(r,"events.jsonl");return h.existsSync(o)?h.existsSync(a)?{success:!1,error:"Session already exists",statusCode:409}:(await h.promises.rename(r,a),await h.promises.writeFile(I.join(a,".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,s,t){try{let{sessionId:n,fileName:r,hasDirectory:a,directoryName:o}=e;if(!Y(n))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(s,r),u=I.join(l,r);if(await h.promises.rename(c,u),a&&o){let d=I.join(s,o),f=I.join(l,o);await h.promises.rename(d,f)}return{success:!0,sessionId:n,format:"claude",project:i}}catch(n){return console.error("Error importing Claude session:",n),{success:!1,error:`Error importing Claude session: ${n.message}`,statusCode:500}}}async _importPiMonoSession(e,s,t){try{let{sessionId:n,fileName:r}=e;if(!Y(n))return{success:!1,error:"Invalid session ID",statusCode:400};let a=t.query.project||"imported-sessions",o=I.join(this.SESSION_DIRS["pi-mono"],a);await h.promises.mkdir(o,{recursive:!0});let i=I.join(s,r),l=I.join(o,r);return await h.promises.rename(i,l),{success:!0,sessionId:n,format:"pi-mono",project:a}}catch(n){return console.error("Error importing Pi-Mono session:",n),{success:!1,error:`Error importing Pi-Mono session: ${n.message}`,statusCode:500}}}async _importByFormat(e,s,t){if(!Y(e.sessionId))return{success:!1,error:"Invalid session ID",statusCode:400};switch(e.format){case"copilot":return await this._importCopilotSession(e,s);case"claude":return await this._importClaudeSession(e,s,t);case"pi-mono":return await this._importPiMonoSession(e,s,t);default:return{success:!1,error:`Unsupported format: ${e.format}`,statusCode:400}}}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=I.join(r,e);if(h.existsSync(a)){let o=I.join(a,"events.jsonl");if(h.existsSync(o))return{source:"copilot",sessionId:e,sessionPath:a,baseDir:r}}}else if(n==="claude"){if(h.existsSync(r)){let a=await h.promises.readdir(r);for(let o of a){let i=I.join(r,o);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:o,baseDir:r}}}}}else if(n==="pi-mono"&&h.existsSync(r)){let a=await h.promises.readdir(r);for(let o of a){let i=I.join(r,o);if((await h.promises.stat(i)).isDirectory()){let c=await h.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 d of c)if(u.test(d))return{source:"pi-mono",sessionId:e,fileName:d,sessionFile:I.join(i,d),projectPath:i,project:o,baseDir:r}}}}}return null}catch(t){return console.error("Error finding session location:",t),null}}};Es.exports=rt});var xs=w((ta,vs)=>{var or=Ge(),ir=Ve(),{isValidSessionId:Cs}=z(),{trackEvent:lr}=U(),at=class{constructor(e=null,s=null){this.tagService=e||new or,this.sessionRepository=s||new ir}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);lr("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=at});var ks=w((sa,Ds)=>{var pe=require("express"),js=require("path"),As=require("compression"),cr=require("helmet"),ur=L(),{requestTimeout:dr,developmentCors:pr,errorHandler:mr,notFoundHandler:fr,telemetryLocals:gr}=gt(),hr=ms(),yr=_s(),Sr=bs(),wr=xs();function _r(p={}){let e=pe();e.set("etag",!1);let s=new hr(p.sessionService),t=new yr(p.insightService,p.sessionService),n=new Sr,r=new wr(p.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(cr({contentSecurityPolicy:!1,hsts:!1,referrerPolicy:!1,crossOriginEmbedderPolicy:!1,crossOriginOpenerPolicy:!1,crossOriginResourcePolicy:!1})),e.use(As({level:1,threshold:1024,filter:(a,o)=>a.path.includes("/events")&&o.getHeader("Content-Type")?.includes("application/json")?!1:As.filter(a,o)})),e.use(pe.json({limit:"1mb"})),e.use(pe.urlencoded({extended:!0})),e.use(dr),e.use(gr),ur.NODE_ENV==="development"&&e.use(pr),e.use("/public",pe.static(js.join(__dirname,"../public"))),e.set("view engine","ejs"),e.set("views",js.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(fr),e.use(mr),e}Ds.exports=_r});U();var Ir=ks(),ot=L(),Tr=de(),Ms=Ir();module.exports=Ms;if(require.main===module){let p=Ms.listen(ot.PORT,()=>{console.log(`\u{1F680} Copilot Session Viewer running at http://localhost:${ot.PORT}`),console.log(`\u{1F527} Environment: ${ot.NODE_ENV}`),console.log(`\u26A1 Active processes: ${Tr.getActiveCount()}`)});process.on("SIGTERM",()=>{console.log("\u{1F4DB} SIGTERM received, closing server..."),p.close(()=>{console.log("\u2705 Server closed")})})}