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