cogpit 3.5.4 → 3.6.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.
Files changed (50) hide show
  1. package/README.md +11 -5
  2. package/dist/cli-runtime.js +3084 -2382
  3. package/dist/cli.js +1 -1
  4. package/dist/instance-worker.js +625 -276
  5. package/dist/web/assets/AgentCheckDialog-DeSKJqG3.js +1 -0
  6. package/dist/web/assets/{AutomationsPanel-DTiDsq54.js → AutomationsPanel-BWjD657g.js} +1 -1
  7. package/dist/web/assets/{CogpitBlock-Hk57z10V.js → CogpitBlock-DEl4Kxl9.js} +15 -15
  8. package/dist/web/assets/CogpitView-BYDVcso1.js +85 -0
  9. package/dist/web/assets/CommandPaletteHost-BWee2Tov.js +1 -0
  10. package/dist/web/assets/{ConfigBrowser-C77Ydij0.js → ConfigBrowser-CQOlu4Gg.js} +1 -1
  11. package/dist/web/assets/{CrewPanel-BzEJLKMd.js → CrewPanel-Dzyxoj46.js} +1 -1
  12. package/dist/web/assets/{HighlightedEditor-D1S-wotA.js → HighlightedEditor-B-bjFcyU.js} +1 -1
  13. package/dist/web/assets/KeyboardShortcutsDialog-9k4clgVv.js +1 -0
  14. package/dist/web/assets/MissionHome-CIwnHTXt.js +2 -0
  15. package/dist/web/assets/{MobileFileChanges-DovO__Ap.js → MobileFileChanges-B8RaPAmX.js} +1 -1
  16. package/dist/web/assets/OrbitControls-CcXenNM0.js +1861 -0
  17. package/dist/web/assets/{PluginsDialog-o6ySRFLf.js → PluginsDialog-CYiiMArh.js} +1 -1
  18. package/dist/web/assets/{PreviewPanel-kD79kXYD.js → PreviewPanel-CZazqeGT.js} +1 -1
  19. package/dist/web/assets/{ProjectFilesPanel-CwEqOA2q.js → ProjectFilesPanel-oFw09UPd.js} +3 -3
  20. package/dist/web/assets/{ProjectSwitcherModal-BnWbJWEX.js → ProjectSwitcherModal-Bq7zI10J.js} +1 -1
  21. package/dist/web/assets/{TerminalOutput-DsK-7nR8.js → TerminalOutput-BDmdqvpJ.js} +1 -1
  22. package/dist/web/assets/{ThemeSelectorModal-D5SBWDm5.js → ThemeSelectorModal-Crb0YaTK.js} +1 -1
  23. package/dist/web/assets/{WorkflowsPanel-NU49178V.js → WorkflowsPanel-HqdzMBXP.js} +1 -1
  24. package/dist/web/assets/WorktreePanel-DHW4Agwj.js +1 -0
  25. package/dist/web/assets/auto-render.min-BCDUXXLr.js +1 -0
  26. package/dist/web/assets/d3.min-DhuWnDrq.js +1 -0
  27. package/dist/web/assets/{edition-ui-7WkqSCbs.js → edition-ui-Cm-dw9e0.js} +1 -1
  28. package/dist/web/assets/index-BtF9zrz_.css +1 -0
  29. package/dist/web/assets/index-C3zvtMTl.js +1 -0
  30. package/dist/web/assets/{index-BgZ8qUzM.js → index-DGG5ZuyK.js} +2 -2
  31. package/dist/web/assets/{index-CevokSRq.js → index-DUeulx0e.js} +2 -2
  32. package/dist/web/assets/index-Dn2vHUyS.js +2 -0
  33. package/dist/web/assets/index-Dv2TZ38C.js +521 -0
  34. package/dist/web/assets/katex.min-C_ZjXvJu.js +1 -0
  35. package/dist/web/assets/session-parser.worker-tdry_1oJ.js +43 -0
  36. package/dist/web/assets/{switch-DI9dp0Ya.js → switch-mgfHveYR.js} +1 -1
  37. package/dist/web/assets/three.core.min-D_80lYGt.js +1 -0
  38. package/dist/web/assets/three.module.min-CXftPEfC.js +1 -0
  39. package/dist/web/assets/{vendor-ui-Dc_kJXxz.js → vendor-ui-ClPj6-Gu.js} +230 -200
  40. package/dist/web/index.html +4 -4
  41. package/package.json +1 -1
  42. package/dist/web/assets/CommandPaletteHost-BYfieK7H.js +0 -1
  43. package/dist/web/assets/KeyboardShortcutsDialog-B_DSi5JO.js +0 -1
  44. package/dist/web/assets/MissionHome-B3uYgylE.js +0 -2
  45. package/dist/web/assets/WorktreePanel-DPk5b1Os.js +0 -1
  46. package/dist/web/assets/index-Bg4A-xl7.js +0 -510
  47. package/dist/web/assets/index-C2tUYo8z.js +0 -1
  48. package/dist/web/assets/index-DIuobrPN.js +0 -2
  49. package/dist/web/assets/index-DMO9bL9w.css +0 -1
  50. package/dist/web/assets/session-parser.worker-DCsmYUeX.js +0 -41
@@ -0,0 +1,43 @@
1
+ const Ft=["acp","codex","copilot","claude"];function ne(t,e){if(t==="default")return e;const n=new TextEncoder().encode(e),s=btoa(Array.from(n,o=>String.fromCharCode(o)).join("")).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return`i-${t}__${s}`}function se(t){const e=/^i-([A-Za-z0-9-]+)__([A-Za-z0-9_-]+)$/.exec(t);if(!e)return{instanceId:"default",nativeId:t};try{const n=Uint8Array.from(atob(e[2].replace(/-/g,"+").replace(/_/g,"/")),s=>s.charCodeAt(0));return{instanceId:e[1],nativeId:new TextDecoder("utf-8",{fatal:!0}).decode(n)}}catch{throw new Error("Invalid instance session ID")}}function In(t,e){return e==="default"?t:{...t,instanceId:e,sessionId:ne(e,se(t.sessionId).nativeId),...t.branchedFrom?{branchedFrom:{...t.branchedFrom,sessionId:ne(e,se(t.branchedFrom.sessionId).nativeId)}}:{}}}const Ht="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",Sn=new RegExp(`^${Ht}$`,"i");function oe(t,e){const n=new TextEncoder().encode(e);let s="";for(const i of n)s+=String.fromCharCode(i);const o=btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return`${t}${o}`}function ie(t,e){if(!e.startsWith(t))return null;try{const n=e.slice(t.length).replace(/-/g,"+").replace(/_/g,"/"),s=atob(n),o=Uint8Array.from(s,i=>i.charCodeAt(0));return new TextDecoder().decode(o)}catch{return null}}function Jt(t){return{lossy:!1,owns:e=>typeof e=="string"&&e.startsWith(t),recognizes:e=>{const n=ie(t,e);return n!==null&&n!==""&&oe(t,n)===e},encode:e=>oe(t,e),decode:e=>ie(t,e)}}function ft(t){const e=new RegExp(`(${Ht})\\.jsonl(?:\\.zst)?$`,"i").exec(t);return e?e[1]:null}function Et(t){return t?{rootSessionId:t.toLowerCase(),isRootTranscript:!0}:null}function Vt(t){const e=t.split("/");return e.every(s=>s!==""&&s!=="."&&s!==".."&&!s.includes("\\"))?e:null}const Gt={urlId:t=>t.replace(/\.jsonl$/,""),fileNameFromUrlId:t=>t.endsWith(".jsonl")?t:`${t}.jsonl`};function $e(t){return`'${t.replace(/'/g,"'\\''")}'`}function pt(t,e){return e?[t,e]:[]}function Tt(t,e){var n;return((n=e.exec(t))==null?void 0:n[1])??null}const Ct="[0-9a-f-]{36}",Ue="codex__",Oe="copilot__",wn=new Set(["default","plan","acceptEdits","dontAsk","auto"]),En=new Set(["subagents","workflows"]);function Mn(t){const e=Vt(t);if(!e)return null;const[n,s]=e;if(e.length===1){const o=n.replace(/\.jsonl$/,"");return o!==n&&ae(o)?Et(o):null}return e.length>2&&En.has(s)&&ae(n)?{rootSessionId:n.toLowerCase(),isRootTranscript:!1}:null}const vn={kind:"claude",displayName:"Claude Code",binName:"claude",dirName:{lossy:!0,owns:t=>typeof t=="string"&&!t.startsWith(Ue)&&!t.startsWith(Oe),recognizes:t=>/^(?:(?:-|[A-Za-z]--)[A-Za-z0-9-]*|[A-Za-z]-)$/.test(t),encode:t=>{const e=t.replace(/[\\/]+$/,"");return(e!==t&&/^[A-Za-z]:$/.test(e)?t.slice(0,e.length+1):e||t).replace(/[^a-zA-Z0-9]/g,"-")},decode:t=>{const e=/^([A-Za-z])--(.*)$/.exec(t);return e?`${e[1]}:\\${e[2].replace(/-/g,"\\")}`:"/"+t.replace(/^-/,"").replace(/-/g,"/")}},projectWorktreeDir:".claude/worktrees",sessionFile:{name:t=>`${t}.jsonl`,sessionId:ft,...Gt,transcriptRoot:Mn},metadataFromHead:!0,resume:{command:t=>`claude --resume ${t}`,args:t=>["--resume",t]},launchArgs:{permissions:t=>t!=null&&t.mode?t.mode==="bypassPermissions"?["--dangerously-skip-permissions"]:[...wn.has(t.mode)?["--permission-mode",t.mode]:[],...(t.allowedTools??[]).flatMap(e=>["--allowedTools",e]),...(t.disallowedTools??[]).flatMap(e=>["--disallowedTools",e])]:["--permission-mode","default"],model:t=>pt("--model",t),effort:t=>pt("--effort",t),fastTier:()=>[]},serviceTier:null,cli:{packageName:"@anthropic-ai/claude-code",homebrew:{name:"claude-code",cask:!1},wingetId:null,versionArgs:["--version"],selfUpdate:{args:["update"],matches:t=>t.endsWith("/.local/bin/claude")||t.endsWith("/.local/bin/claude.exe")||t.includes("/.local/share/claude/")},bundledBySdk:!0,homeDirName:".claude",homeEnvVar:null,sdkHomeEnvVar:"CLAUDE_CONFIG_DIR",installMarker:"projects",homeIsDiscoverable:!1,process:{by:"command",sessionIdFromCommand:t=>Tt(t,new RegExp(`--resume(?:=|\\s+)(${Ct})`))??Tt(t,new RegExp(`--session-id(?:=|\\s+)(${Ct})`))},install:{page:"https://code.claude.com/docs/en/setup",command:t=>t==="win32"?"irm https://claude.ai/install.ps1 | iex":"curl -fsSL https://claude.ai/install.sh | bash"},signIn:{args:["auth","login"],envVars:["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN"],statusArgs:["auth","status","--json"],readStatus:({stdout:t})=>{try{const{loggedIn:e}=JSON.parse(t);return typeof e=="boolean"?e:"unknown"}catch{return"unknown"}}}},config:{rootDirName:".claude",instructions:[{in:"scope",path:"CLAUDE.md",scopes:["global","project"]},{in:"root",path:"CLAUDE.md",label:".claude/CLAUDE.md",scopes:["project"]},{in:"scope",path:"AGENTS.md",scopes:["project"],fallback:!0}],settings:[{in:"root",path:"settings.json",scopes:["global"]},{in:"root",path:"settings.local.json",scopes:["project"]}],skillsDir:"skills",agentsDir:"agents",commandsDir:"commands",themesDir:"themes",pluginsDir:"plugins"},contextWindow:{defaultLimit:1e6,limits:[{match:"claude-haiku-4-5",limit:2e5},{match:"claude-haiku-4-1",limit:2e5},{match:"claude-sonnet-4-5",limit:2e5},{match:"claude-opus-4-5",limit:2e5},{match:"claude-opus-4-1",limit:2e5}],compactBuffer:33e3,extendedContext:{marker:"[1m]",limit:1e6}},capabilities:{worktrees:!0,mcp:!0,slashCommands:!0,workflows:!0,agentTeams:!0,subagentTranscripts:!0,nestedSubagents:!1,sharing:!0,goals:"transcript",undo:!0,redo:!0,nativeRewind:!1,fileCheckpoints:!0,reasoningEffort:!0,configurableContextWindow:!1,fastTier:!0,lowPriorityInTerminal:!0,imageInput:!0,midTurnSteering:!0,activeNotifications:!0,stopSession:!0,ultracode:!0,contextWindow:!0,externalProcesses:!1,accountSwitching:!0,modelFallbackNotices:!0,autoPermissionMode:"per-model",toolPermissionRules:!0,settingsApply:"live",turnLiveness:"transcript",tokenStreaming:!0,nativeFork:!1,namedSessions:!0}},re={appServerValue:"priority",cliConfigValue:"fast"},Nn={kind:"codex",displayName:"Codex",binName:"codex",dirName:Jt(Ue),projectWorktreeDir:null,sessionFile:{name:(t,e=new Date)=>{const n=String(e.getFullYear()),s=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),l=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0");return`${n}/${s}/${o}/rollout-${n}-${s}-${o}T${i}-${l}-${a}-${t}.jsonl`},sessionId:ft,...Gt,transcriptRoot:t=>Vt(t)?Et(ft(t)):null},metadataFromHead:!1,resume:{command:(t,e)=>e?`codex -C ${$e(e)} resume ${t}`:`codex resume ${t}`,args:t=>["resume",t]},launchArgs:{permissions:t=>{const e=(t==null?void 0:t.mode)||"default";return e==="bypassPermissions"?["--dangerously-bypass-approvals-and-sandbox"]:e==="auto"?["--approve-for-me"]:["--sandbox",e==="plan"?"read-only":"workspace-write","-c",'approval_policy="never"']},model:t=>pt("-m",t),effort:t=>t?["-c",`model_reasoning_effort=${JSON.stringify(t)}`]:[],fastTier:t=>t?["-c",`service_tier=${JSON.stringify(re.cliConfigValue)}`,"--enable","fast_mode"]:[]},serviceTier:re,cli:{packageName:"@openai/codex",homebrew:{name:"codex",cask:!1},wingetId:null,versionArgs:["--version"],selfUpdate:null,bundledBySdk:!1,homeDirName:".codex",homeEnvVar:"CODEX_HOME",sessionIdEnvVar:"CODEX_THREAD_ID",installMarker:"sessions",homeIsDiscoverable:!0,process:{by:"command",sessionIdFromCommand:t=>Tt(t,new RegExp(`codex(?:\\s+\\S+)*\\s+exec\\s+resume\\s+(${Ct})`))},install:{page:"https://developers.openai.com/codex/cli",command:()=>"npm install -g @openai/codex"},signIn:{args:["login"],envVars:[],statusArgs:["login","status"],readStatus:({code:t,stdout:e,stderr:n})=>t===0?!0:/not logged in/i.test(`${e}
2
+ ${n}`)?!1:"unknown"}},config:{rootDirName:".codex",instructions:[{in:"scope",path:"AGENTS.md",scopes:["global","project"]}],settings:[{in:"root",path:"config.toml",scopes:["global","project"]}],skillsDir:"skills",agentsDir:"agents",commandsDir:"prompts",themesDir:null,pluginsDir:null},contextWindow:{defaultLimit:272e3,limits:[],compactBuffer:0,extendedContext:null},capabilities:{worktrees:!0,mcp:!1,slashCommands:!1,workflows:!1,agentTeams:!1,subagentTranscripts:!0,nestedSubagents:!0,sharing:!0,goals:"thread-api",undo:!0,redo:!0,nativeRewind:!1,fileCheckpoints:!1,reasoningEffort:!0,configurableContextWindow:!0,fastTier:!0,lowPriorityInTerminal:!1,imageInput:!0,midTurnSteering:!0,activeNotifications:!0,stopSession:!1,ultracode:!1,contextWindow:!1,externalProcesses:!1,accountSwitching:!1,modelFallbackNotices:!1,autoPermissionMode:"always",toolPermissionRules:!0,settingsApply:"next-turn",turnLiveness:"runtime",tokenStreaming:!0,nativeFork:!1,namedSessions:!1}};function Rt(t){const e=new RegExp(`^(${Ht})/events\\.jsonl$`,"i").exec(t);return e?e[1]:null}const at={kind:"copilot",displayName:"GitHub Copilot CLI",binName:"copilot",dirName:Jt(Oe),projectWorktreeDir:null,sessionFile:{name:t=>`${t}/events.jsonl`,sessionId:Rt,urlId:t=>Rt(t)??t.replace(/\.jsonl$/,""),fileNameFromUrlId:t=>t.endsWith(".jsonl")?t:`${t}/events.jsonl`,transcriptRoot:t=>Et(Rt(t))},metadataFromHead:!0,resume:{command:(t,e)=>e?`copilot -C ${$e(e)} --resume ${t}`:`copilot --resume ${t}`,args:t=>[`--resume=${t}`]},launchArgs:{permissions:t=>(t==null?void 0:t.mode)==="bypassPermissions"||(t==null?void 0:t.mode)==="auto"?["--allow-all"]:[],model:t=>pt("--model",t),effort:t=>pt("--reasoning-effort",t),fastTier:()=>[]},serviceTier:null,cli:{packageName:"@github/copilot",homebrew:{name:"copilot-cli",cask:!0},wingetId:"GitHub.Copilot",versionArgs:["--version"],selfUpdate:{args:["update"],matches:t=>t.endsWith("/.local/bin/copilot")||t==="/usr/local/bin/copilot"},bundledBySdk:!1,homeDirName:".copilot",homeEnvVar:"COPILOT_HOME",installMarker:"session-state",homeIsDiscoverable:!0,process:{by:"executable",sessionIdFromCommand:t=>Tt(t,new RegExp(`--resume(?:=|\\s+)(${Ct})`))},install:{page:"https://docs.github.com/en/copilot/how-tos/set-up/install-copilot-cli",command:t=>t==="win32"?"winget install GitHub.Copilot":"curl -fsSL https://gh.io/copilot-install | bash"},signIn:{args:["login"],envVars:["COPILOT_GITHUB_TOKEN","GH_TOKEN","GITHUB_TOKEN"],statusArgs:null,readStatus:()=>"unknown"}},config:{rootDirName:".copilot",instructions:[{in:"scope",path:"AGENTS.md",scopes:["global","project"]}],settings:[{in:"root",path:"config.json",scopes:["global"]}],skillsDir:"skills",agentsDir:null,commandsDir:null,themesDir:null,pluginsDir:null},contextWindow:{defaultLimit:2e5,limits:[],compactBuffer:0,extendedContext:null},capabilities:{worktrees:!1,mcp:!1,slashCommands:!1,workflows:!1,agentTeams:!1,subagentTranscripts:!1,nestedSubagents:!1,sharing:!1,goals:!1,undo:!0,redo:!1,nativeRewind:!0,fileCheckpoints:!1,reasoningEffort:!1,configurableContextWindow:!1,fastTier:!1,lowPriorityInTerminal:!1,imageInput:!1,midTurnSteering:!0,activeNotifications:!0,stopSession:!0,ultracode:!1,contextWindow:!1,externalProcesses:!0,accountSwitching:!1,modelFallbackNotices:!1,autoPermissionMode:"always",toolPermissionRules:!0,settingsApply:"next-turn",turnLiveness:"runtime",tokenStreaming:!1,nativeFork:!0,namedSessions:!0}},Rn={...at,kind:"acp",displayName:"ACP agent",binName:"acp",dirName:Jt("acp__"),sessionFile:{name:t=>`${t}.jsonl`,sessionId:ft,...Gt,transcriptRoot:t=>{const e=Vt(t);return(e==null?void 0:e.length)===1?Et(ft(t)):null}},resume:{command:()=>"Resume this session in Cogpit",args:()=>[]},launchArgs:{permissions:()=>[],model:()=>[],effort:()=>[],fastTier:()=>[]},cli:{...at.cli,packageName:"",homebrew:null,wingetId:null,selfUpdate:null,requiresConfiguration:!0,homeDirName:".cogpit-acp",homeEnvVar:"COGPIT_ACP_HOME",homeIsDiscoverable:!0,installMarker:"projects",install:null,signIn:null},config:{...at.config,rootDirName:".cogpit-acp",instructions:[],settings:[],skillsDir:null},capabilities:{...at.capabilities,undo:!1,redo:!1,nativeRewind:!1,nativeFork:!1,midTurnSteering:!1,activeNotifications:!1,externalProcesses:!1,autoPermissionMode:"never",toolPermissionRules:!1,namedSessions:!1}},Pn=Object.freeze({claude:vn,codex:Nn,copilot:at,acp:Rn});function gt(t){return Pn[t]}function ae(t){return Sn.test(t)}const le={0:"\0",b:"\b",f:"\f",n:`
3
+ `,r:"\r",t:" ",v:"\v"};function ce(t,e){const n=t[e];if(n!=='"'&&n!=="'"&&n!=="`")return null;let s="",o=e+1;for(;o<t.length;){const i=t[o];if(i===n)return{endIndex:o+1,value:s};if(i!=="\\"){s+=i,o++;continue}if(o++,o>=t.length)return null;const l=t[o];if(l in le){s+=le[l],o++;continue}if(l===`
4
+ `){o++;continue}if(l==="\r"){o+=t[o+1]===`
5
+ `?2:1;continue}if(l==="x"&&/^[0-9a-fA-F]{2}$/.test(t.slice(o+1,o+3))){s+=String.fromCharCode(Number.parseInt(t.slice(o+1,o+3),16)),o+=3;continue}if(l==="u"){const a=t.slice(o+1).match(/^\{([0-9a-fA-F]+)\}/);if(a){const u=Number.parseInt(a[1],16);if(Number.isFinite(u)&&u<=1114111){s+=String.fromCodePoint(u),o+=a[0].length+1;continue}}const c=t.slice(o+1,o+5);if(/^[0-9a-fA-F]{4}$/.test(c)){s+=String.fromCharCode(Number.parseInt(c,16)),o+=5;continue}}s+=l,o++}return null}const $n=[/isn't installed on this computer/i,/native cli binary for \S+ not found/i,/(?:native binary|executable) not found at/i,/not installed or not found in path/i,/was not found on path/i],Un=[/not logged in/i,/invalid api key/i,/missing bearer or basic authentication/i,/not created with authentication info/i,/no github oauth token/i,/no authentication information found/i,/isn't signed in/i],On=/\b(?:status|http)\s+([1-5]\d\d)\b|\b([45]\d\d) (?:unauthorized|forbidden|not found|too many requests|internal server error|bad gateway|service unavailable)\b/i;function Bn(t){const e=On.exec(t),n=(e==null?void 0:e[1])??(e==null?void 0:e[2]);return n?Number(n):void 0}function xt(t,e){const n=e??Bn(t),s=n===void 0?{}:{httpStatus:n};return $n.some(o=>o.test(t))?{reason:"not_installed",message:t}:n===401||Un.some(o=>o.test(t))?{reason:"not_signed_in",message:t,...s}:{reason:n===void 0?"other":"http_status",message:t,...s}}function Dn(t){return`${gt(t).displayName} isn't signed in.`}function Qt(t,e=0){if(!t.some(a=>a.endedAt===void 0))return null;const n=[...t].sort((a,c)=>a.launchedAt-c.launchedAt);let s=0,o=-1/0;n.forEach((a,c)=>{o<a.launchedAt&&(s=c),o=Math.max(o,a.endedAt??1/0)});const i=n.slice(s).map(({agent:a,endedAt:c})=>({...a,done:c!==void 0})),l=i.filter(a=>!a.done);return{status:"awaiting_agents",pendingQueue:e,pendingAgents:l.length,pendingAgentDescriptions:l.map(a=>a.description).filter(a=>a.length>0),backgroundAgents:i}}function jt(t){return t.type==="user"}function Zt(t){return t.type==="assistant"}function ue(t){return t.type==="progress"}function Pt(t){return t.type==="system"}function Be(t){return t.type==="summary"}function Fn(t){return t.type==="queue-operation"}function De(t){return t.type==="attachment"}function jn(t){return t.type==="user"&&t.isCompactSummary===!0}function Fe(t){return t.type==="system"&&t.subtype==="compact_boundary"}function de(t,e){let n=0;for(const s of t)e[s.name]=(e[s.name]??0)+1,s.isError&&n++;return n}function fe(t,e){t.totalInputTokens+=e.input_tokens,t.totalOutputTokens+=e.output_tokens,t.totalCacheCreationTokens+=e.cache_creation_input_tokens??0,t.totalCacheReadTokens+=e.cache_read_input_tokens??0}function Mt(t){return{totalInputTokens:0,totalOutputTokens:0,totalCacheCreationTokens:0,totalCacheReadTokens:0,toolCallCounts:{},errorCount:0,totalDurationMs:0,turnCount:t}}function vt(t){const e=Mt(t.length);for(const n of t){n.tokenUsage&&fe(e,n.tokenUsage),n.durationMs&&(e.totalDurationMs+=n.durationMs),e.errorCount+=de(n.toolCalls,e.toolCallCounts);for(const s of n.subAgentActivity)e.errorCount+=de(s.toolCalls,e.toolCallCounts),s.tokenUsage&&fe(e,s.tokenUsage)}return e}function nt(t,e){var s,o;if(!t)return{...e};const n=(((s=t.output_tokens_details)==null?void 0:s.thinking_tokens)??0)+(((o=e.output_tokens_details)==null?void 0:o.thinking_tokens)??0);return{input_tokens:t.input_tokens+e.input_tokens,output_tokens:t.output_tokens+e.output_tokens,cache_creation_input_tokens:(t.cache_creation_input_tokens??0)+(e.cache_creation_input_tokens??0),cache_read_input_tokens:(t.cache_read_input_tokens??0)+(e.cache_read_input_tokens??0),speed:e.speed??t.speed,...t.output_tokens_details||e.output_tokens_details?{output_tokens_details:{thinking_tokens:n}}:{}}}const Ln=/<(agent-message|teammate-message)([^>]*)>([\s\S]*?)<\/\1>/g,Wn=[/\bteammate_id=(?:"([^"]*)"|'([^']*)')/,/\bfrom=(?:"([^"]*)"|'([^']*)')/];function qn(t){for(const e of Wn){const n=t.match(e),s=(n==null?void 0:n[1])??(n==null?void 0:n[2]);if(s)return s}return null}function At(t){let e=null,n=!1;const s=t.replace(Ln,(o,i,l,a)=>(n=!0,e===null&&(e=qn(l)),a.trim()));return{sender:e,matched:n,body:n?s.trim():t}}function ht(t){return t&&typeof t=="object"?t:{}}function zn(t,e){const n=ht(e);if(t==="Edit"||t==="Write")return n.staged===!0?{awaitingReview:!0}:{};if(t!=="Bash")return{};const s=ht(n.bashEditDiff);if(!Array.isArray(s.files))return{};const o=[];for(const l of s.files){const a=ht(l);if(typeof a.filePath!="string"||!a.filePath||!Array.isArray(a.hunks))continue;const c=[];for(const u of a.hunks){const h=ht(u),{oldStart:C,oldLines:_,newStart:m,newLines:v,lines:P}=h;[C,_,m,v].every($=>typeof $=="number"&&Number.isInteger($)&&$>=0)&&(!Array.isArray(P)||!P.every($=>typeof $=="string"&&/^[ +\\-]/.test($))||c.push({oldStart:C,oldLines:_,newStart:m,newLines:v,lines:P}))}c.length&&o.push({filePath:a.filePath,hunks:c})}const i=typeof s.moreFiles=="number"&&Number.isInteger(s.moreFiles)&&s.moreFiles>0?s.moreFiles:0;return{fileDiffs:o,...i?{additionalFileDiffs:i}:{}}}function Nt(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join(`
6
+ `)}function pe(t){return t?typeof t=="string"?t:t.map(e=>e.type==="text"?e.text:"").filter(Boolean).join(`
7
+ `):""}function je(t){if(!(t!=null&&t.trim()))return!1;const e=t.trimStart();return e.startsWith("<")?!e.includes("<task-notification>")&&!e.startsWith("<system-reminder>")&&!e.startsWith("<local-command-"):!0}const Kn=/<task-notification>[\s\S]*?<\/task-notification>/g,Hn=/<[^>]*>/g;function Jn(t){var n;if(((n=t.origin)==null?void 0:n.kind)==="task-notification")return!0;const e=Nt(t.message.content);return e.includes("<task-notification>")?e.replace(Kn,"").replace(Hn,"").trim()==="":!1}function me(t){return t==="Task"||t==="Agent"}function ge(t){const e=t.effort;return{name:typeof t.name=="string"?t.name:null,subagentType:typeof t.subagent_type=="string"?t.subagent_type:null,effort:typeof e=="string"||typeof e=="number"?String(e):null}}function Vn(t){if(!De(t))return null;const e=t.attachment;if(!e||e.type!=="queued_command"||e.commandMode!=="prompt")return null;const n=e.prompt;if(n==null)return null;const s=typeof n=="string"?n:Nt(n);if(!je(s))return null;const o=e.origin;if((o==null?void 0:o.kind)==="peer"){const l=o.name??o.from??null;if(l)return{raw:s,sender:l,body:o.body??At(s).body}}if((o==null?void 0:o.kind)==="human")return{raw:s,sender:null,body:s};const i=At(s);return{raw:s,sender:i.sender,body:i.body}}const Gn=[["attributionAgent","agent"],["attributionSkill","skill"],["attributionPlugin","plugin"],["attributionMcpServer","mcpServer"],["attributionMcpTool","mcpTool"]];function Qn(t,e){let n=t;for(const[s,o]of Gn){const i=e[s];typeof i!="string"||!i||(n={...n,[o]:i})}return n}const Zn=/^This session is being continued from a previous conversation[\s\S]*?\n\nSummary:\s*\n/,Xn=/\n+(?:If you need specific details from before compaction|(?:Please c|C)ontinue the conversation from where it left off)[\s\S]*$/;function Yn(t){return Nt(t).trim().replace(Zn,"").replace(Xn,"").trim()}function ts(t){if(t)return{trigger:t.trigger,preTokens:t.preTokens,postTokens:t.postTokens}}function yt(t,e){return{id:t.uuid??crypto.randomUUID(),userMessage:e,contentBlocks:[],thinking:[],assistantText:[],toolCalls:[],subAgentActivity:[],timestamp:t.timestamp??"",durationMs:null,tokenUsage:null,model:null}}function es(t){const e=[];let n=0;for(;n<t.length;){const s=t[n];if(s.kind==="tool_calls"){const o=s.toolCalls.findIndex(i=>i.name==="EnterPlanMode");if(o!==-1){const i=s.toolCalls[o],l=String(i.input.plan??""),a=s.timestamp,c=s.toolCalls.slice(0,o);c.length>0&&e.push({kind:"tool_calls",toolCalls:c,timestamp:s.timestamp});const u=[],h=s.toolCalls.slice(o+1),C=h.findIndex(_=>_.name==="ExitPlanMode");if(C!==-1){u.push(...h.slice(0,C));const _=h[C],m=_.input.path?String(_.input.path):void 0;let v="pending";_.result!==null&&(v=_.isError?"rejected":"approved"),e.push({kind:"plan_mode",plan:l,planFilePath:m,status:v,toolCalls:u,timestamp:a});const P=h.slice(C+1);P.length>0&&e.push({kind:"tool_calls",toolCalls:P,timestamp:s.timestamp}),n++;continue}else{u.push(...h);let _,m,v="pending",P=n+1;const $=[];for(;P<t.length;){const y=t[P];if(y.kind==="tool_calls"){const N=y.toolCalls.findIndex(O=>O.name==="ExitPlanMode");if(N!==-1){u.push(...y.toolCalls.slice(0,N)),_=y.toolCalls[N],m=_.input.path?String(_.input.path):void 0,_.result!==null&&(v=_.isError?"rejected":"approved");const O=y.toolCalls.slice(N+1);e.push({kind:"plan_mode",plan:l,planFilePath:m,status:v,toolCalls:u,timestamp:a}),e.push(...$),O.length>0&&e.push({kind:"tool_calls",toolCalls:O,timestamp:y.timestamp}),n=P+1;break}else u.push(...y.toolCalls),P++}else if(y.kind==="hook_event"||y.kind==="text"||y.kind==="queued_prompt"||y.kind==="agent_message")$.push(y),P++;else break}_||(e.push({kind:"plan_mode",plan:l,planFilePath:void 0,status:"pending",toolCalls:u,timestamp:a}),e.push(...$),n=P);continue}}}e.push(s),n++}return e}function ns(t){return t.contentBlocks.some(e=>e.kind==="agent_message")?{...t,contentBlocks:t.contentBlocks.map(e=>{if(e.kind!=="agent_message")return e;const{reply:n,...s}=e;return s})}:t}function Le(t){var s;const e=t.map(ns),n=new Map;for(const o of e)for(const i of o.contentBlocks){if(i.kind==="agent_message"){const l=n.get(i.sender);l?l.push(i):n.set(i.sender,[i]);continue}if(i.kind==="tool_calls")for(const l of i.toolCalls){if(l.name!=="SendMessage")continue;const a=l.input.to;if(typeof a!="string"||!a)continue;const c=(s=n.get(a))==null?void 0:s.shift();if(!c)continue;const u=l.input.summary;c.reply={summary:typeof u=="string"?u:"",timestamp:l.timestamp||i.timestamp||""}}}return e}function ss(t){const e=[];let n=!1;for(let s=0;s<t.length;s++){const o=t[s];if(Be(o)||Fe(o)){n=!1;continue}if(jt(o)&&!o.isMeta){const i=o.message.content;if(n&&Array.isArray(i)&&i.some(a=>a.type==="tool_result"))continue;e.push(s),n=!0;continue}Zt(o)&&!n&&(e.push(s),n=!0)}return e}function We(t){var q,T;const e=[],n=[];let s=null,o=0,i=null,l=null;function a(r){l&&(r.compactionSummary=l.summary,r.compactionMeta=l.meta,l=null)}let c=null;const u=new Map,h=new Set,C=new Map,_=new Map,m=new Set,v=new Map,P=[],$=new Map;function y(r,d){let k=$.get(r);k||(k=new Map,$.set(r,k)),k.set(d,(k.get(d)??0)+1)}function N(r,d){const k=$.get(r),g=k==null?void 0:k.get(d);return!k||!g?!1:(g===1?k.delete(d):k.set(d,g-1),!0)}function O(){for(const r of P)r.turn.contentBlocks.push(r.sender?{kind:"agent_message",sender:r.sender,body:r.body,timestamp:r.timestamp}:{kind:"queued_prompt",content:r.content,timestamp:r.timestamp});P.length=0}function z(r){if(!i)return;const d=C.get(r);if(!d||d.length===0)return;i.subAgentActivity.push(...d),C.delete(r);const k=m.has(r)?"background_agent":"sub_agent",g=_.get(r);if(g)g.messages.push(...d);else{const w={kind:k,messages:[...d]};i.contentBlocks.push(w),_.set(r,w)}}function L(){if(i){for(const r of i.toolCalls)z(r.id);for(const[r]of C)z(r);for(const r of i.contentBlocks)if(r.kind==="hook_event")for(const d of r.events){if(!(d.eventName==="PostToolUse"||d.eventName.startsWith("PostToolUse:"))||!d.toolUseId)continue;const g=i.toolCalls.find(w=>w.id===d.toolUseId);g&&(d.updatedToolOutput&&(g.outputReplacedByHook=!0),d.durationMs!==void 0&&(g.hookDurationMs=(g.hookDurationMs??0)+d.durationMs))}i.contentBlocks=es(i.contentBlocks),e.push(i),s!==null&&n.push(s),s=null,i=null,_.clear()}}for(o=0;o<t.length;o++){const r=t[o];if(Be(r)){L(),l={summary:r.summary};continue}if(Fe(r)){L(),l={meta:ts(r.compactMetadata)};continue}if(jn(r)){L(),s=o,i=yt(r,null),i.compactionSummary=Yn(r.message.content),i.compactionMeta=l==null?void 0:l.meta,l=null;continue}if(Pt(r)&&r.subtype==="away_summary"&&r.content){c={content:r.content,timestamp:r.timestamp};continue}if(Pt(r)&&r.subtype==="local_command"&&r.content){i==null||i.contentBlocks.push({kind:"local_command",content:r.content,timestamp:r.timestamp,...r.contextUsage?{contextUsage:r.contextUsage}:{},...r.usageReport?{usageReport:r.usageReport}:{}});continue}if(Fn(r)){if(i&&r.operation==="enqueue"&&je(r.content)){const d=At(r.content);P.push({turn:i,content:r.content,timestamp:r.timestamp,sender:d.sender,body:d.body}),y(i,r.content)}continue}if(De(r)){const d=Vn(r);i&&d!==null&&!N(i,d.raw)&&P.push({turn:i,content:d.raw,timestamp:((q=r.attachment)==null?void 0:q.timestamp)??r.timestamp,sender:d.sender,body:d.body});continue}if(P.length>0){const d=jt(r)&&!r.isMeta?r.message.content:null;if(typeof d=="string"){const k=P.findIndex(g=>g.content===d);if(k>=0){const[g]=P.splice(k,1);N(g.turn,g.content)}}O()}if(jt(r)&&!r.isMeta){const d=r.message.content;if(typeof d!="string"&&Array.isArray(d)&&d.some(g=>g.type==="tool_result")&&i){for(const w of d)if(w.type==="tool_result"){const E=u.get(w.tool_use_id);if(E){E.turn.toolCalls[E.index].result=pe(w.content),E.turn.toolCalls[E.index].isError=w.is_error===!0;const I=E.turn.toolCalls[E.index];Object.assign(I,zn(I.name,r.toolUseResult)),u.delete(w.tool_use_id)}}const g=r.toolUseResult;if(g!=null&&g.agentId){const w=((T=d.find(p=>p.type==="tool_result"))==null?void 0:T.tool_use_id)??"",E=v.get(w),I=m.has(w),f=[];if(Array.isArray(g.content))for(const p of g.content)p.type==="text"&&f.push(p.text);const A={agentId:g.agentId,parentToolUseId:w||void 0,agentName:(E==null?void 0:E.name)??null,subagentType:(E==null?void 0:E.subagentType)??null,...E!=null&&E.effort?{effort:E.effort}:{},type:"assistant",content:g.content,toolCalls:[],thinking:[],text:f,timestamp:r.timestamp??"",tokenUsage:g.usage?{input_tokens:g.usage.input_tokens??0,output_tokens:g.usage.output_tokens??0,cache_creation_input_tokens:g.usage.cache_creation_input_tokens??0,cache_read_input_tokens:g.usage.cache_read_input_tokens??0}:null,model:null,isBackground:I,prompt:g.prompt,status:g.status,durationMs:g.totalDurationMs,toolUseCount:g.totalToolUseCount};if(!_.get(w)){i.subAgentActivity.push(A);const b={kind:I?"background_agent":"sub_agent",messages:[A]};i.contentBlocks.push(b),_.set(w,b)}}continue}if(Jn(r)){const k={kind:"task_notification",content:Nt(d),timestamp:r.timestamp};if(i){i.contentBlocks.push(k);continue}s=o,i=yt(r,null),i.contentBlocks.push(k),a(i);continue}L(),s=o,i=yt(r,r.message.content),a(i),c&&(i.contentBlocks.push({kind:"recap",content:c.content,timestamp:c.timestamp}),c=null);continue}if(Zt(r)){let d=function(){I.length>0&&(f.contentBlocks.push({kind:"tool_calls",toolCalls:[...I],timestamp:w}),I.length=0)},k=function(){if(E.length>0){const A=f.contentBlocks[f.contentBlocks.length-1];A&&A.kind==="thinking"?A.blocks.push(...E):f.contentBlocks.push({kind:"thinking",blocks:[...E],timestamp:w}),E.length=0}};i||(s=o,i=yt(r,null),a(i)),i.model=r.message.model,r.effort&&(i.effort=r.effort),i.attribution=Qn(i.attribution,r);const g=r.message.id;h.has(g)||(h.add(g),i.tokenUsage=nt(i.tokenUsage,r.message.usage));const w=r.timestamp??"",E=[],I=[],f=i;for(const A of r.message.content)if(A.type==="thinking"){d();const R=A;if(!R.thinking)continue;i.thinking.push(R),E.push(R)}else if(A.type==="text"){d(),k();const R=/<thinking>([\s\S]*?)<\/thinking>/g;let p=A.text,b;for(;(b=R.exec(A.text))!==null;){const S=b[1].trim();if(S){const U={type:"thinking",thinking:S,signature:""};i.thinking.push(U),i.contentBlocks.push({kind:"thinking",blocks:[U],timestamp:w})}p=p.replace(b[0],"")}if(p=p.trim(),p){i.assistantText.push(p);const S=i.contentBlocks[i.contentBlocks.length-1];S&&S.kind==="text"?S.text.push(p):i.contentBlocks.push({kind:"text",text:[p],timestamp:w})}}else if(A.type==="tool_use"){k();const R={id:A.id,name:A.name,input:A.input,result:null,isError:!1,timestamp:r.timestamp??""},p=i.toolCalls.length;if(i.toolCalls.push(R),I.push(R),u.set(A.id,{turn:i,index:p}),me(A.name)){const b=A.input;b.run_in_background===!0&&m.add(A.id),v.set(A.id,ge(b))}}k(),d();continue}if(ue(r)&&r.data.type==="agent_progress"){const d=r.data,k=r.parentToolUseID??"",g=d.toolUseId??k;let w=null;if(d.message.type==="assistant"){const R=d.message.message,p=R.id,b=R.usage;b&&p&&!h.has(p)&&(h.add(p),w={input_tokens:b.input_tokens??0,output_tokens:b.output_tokens??0,cache_creation_input_tokens:b.cache_creation_input_tokens??0,cache_read_input_tokens:b.cache_read_input_tokens??0})}const E=d.message.type==="assistant"?d.message.message.model??null:null,I=v.get(g),f={agentId:d.agentId,parentToolUseId:g||void 0,...d.parentAgentId?{parentAgentId:d.parentAgentId}:{},...I!=null&&I.effort?{effort:I.effort}:{},agentName:(I==null?void 0:I.name)??null,subagentType:(I==null?void 0:I.subagentType)??d.subagentType??null,type:d.message.type,content:d.message.message.content,toolCalls:[],thinking:[],text:[],timestamp:d.message.timestamp??r.timestamp??"",tokenUsage:w,model:E,isBackground:m.has(k)};if(d.message.type==="assistant"){const R=d.message.message.content;if(Array.isArray(R))for(const p of R)p.type==="thinking"?f.thinking.push(p.thinking):p.type==="text"?f.text.push(p.text):p.type==="tool_use"&&(me(p.name)&&v.set(p.id,ge(p.input)),f.toolCalls.push({id:p.id,name:p.name,input:p.input,result:null,isError:!1,timestamp:d.message.timestamp??r.timestamp??""}))}else if(d.message.type==="user"){const R=d.message.message.content;if(Array.isArray(R)){for(const p of R)if(p.type==="tool_result"){const b=C.get(k);if(b)for(const S of b){const U=S.toolCalls.find(M=>M.id===p.tool_use_id);U&&(U.result=pe(p.content),U.isError=p.is_error===!0)}}}}let A=C.get(k);A||(A=[],C.set(k,A)),A.push(f),i&&z(k);continue}if(ue(r)&&r.data.type==="hook_progress"){const d=r.data,k=String(d.hook_event_name??d.hookEvent??"unknown"),g=d.hookSpecificOutput,w={eventName:k,source:d.source!==void 0?String(d.source):void 0,toolName:d.tool_name!==void 0?String(d.tool_name):void 0,toolUseId:d.tool_use_id!==void 0?String(d.tool_use_id):void 0,command:d.command!==void 0?String(d.command):void 0,output:d.output!==void 0?String(d.output):void 0,stderr:d.stderr!==void 0?String(d.stderr):void 0,exitCode:d.exit_code!==void 0?Number(d.exit_code):void 0,decision:d.decision!==void 0?String(d.decision):void 0,durationMs:d.duration_ms!==void 0?Number(d.duration_ms):void 0,updatedToolOutput:(g==null?void 0:g.updatedToolOutput)!==void 0?String(g.updatedToolOutput):void 0,sessionTitle:(g==null?void 0:g.sessionTitle)!==void 0?String(g.sessionTitle):void 0,worktreePath:(g==null?void 0:g.worktreePath)!==void 0?String(g.worktreePath):void 0,timestamp:r.timestamp??""};if(i){const E=i.contentBlocks[i.contentBlocks.length-1];E&&E.kind==="hook_event"?E.events.push(w):i.contentBlocks.push({kind:"hook_event",events:[w],timestamp:r.timestamp})}continue}if(Pt(r)&&r.subtype==="turn_duration"&&i){r.durationMs!==void 0&&r.durationMs!==null&&(i.durationMs=(i.durationMs??0)+r.durationMs);continue}}return O(),L(),{turns:Le(e),turnStartIndices:n}}function qe(t){return We(t).turns}const $t="⁣cogpit-elided-v1:",he="⁣";function os(t){if(!t||!t.startsWith($t))return null;const e=t.indexOf(he,$t.length);if(e<0)return null;try{const n=JSON.parse(t.slice($t.length,e));return typeof n.ref!="string"||typeof n.bytes!="number"?null:{stub:n,preview:t.slice(e+he.length)}}catch{return null}}function J(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function X(t,e,n,s="text"){const o=t[e];if(typeof o!="string")return!1;const i=n(o,s);return i===o?!1:(t[e]=i,!0)}function Xt(t,e,n,s,o){const i=t.map(e),l=i.findIndex(u=>u!==void 0);if(l<0)return null;const a=i.filter(u=>!!u).join(n),c=o(a,"text");return c===a?null:t.flatMap((u,h)=>h===l?[s(u,c)]:i[h]===void 0?[u]:[])}function _t(t){for(const e of t){const n=os(e.result);n&&(e.result=n.preview,e.resultRef=n.stub)}}function is(t){for(const e of t.turns){_t(e.toolCalls);for(const n of e.subAgentActivity)_t(n.toolCalls);for(const n of e.contentBlocks)if(n.kind==="tool_calls"||n.kind==="plan_mode")_t(n.toolCalls);else if(n.kind==="sub_agent"||n.kind==="background_agent")for(const s of n.messages)_t(s.toolCalls)}return t}function ye(){return!0}const _e='"type":"api-request',rs=256;function ze(t){if(t.startsWith(`{${_e}`))return!0;const e=t.slice(0,rs),n=e.indexOf(_e);return n>0&&e.lastIndexOf("{",n)===0}function Ke(t){const e=[];for(const n of t){const s=n.trim();if(!(!s||ze(s)))try{e.push(JSON.parse(s))}catch{}}return e}function He(t){return Ke(t.split(`
8
+ `))}function Je(t){const e={sessionId:"",version:"",gitBranch:"",cwd:"",slug:"",name:"",model:"",branchedFrom:void 0};for(const n of t)if(n.sessionId&&!e.sessionId&&(e.sessionId=n.sessionId),n.version&&!e.version&&(e.version=n.version),n.gitBranch&&!e.gitBranch&&(e.gitBranch=n.gitBranch),n.cwd&&!e.cwd&&(e.cwd=n.cwd),n.slug&&!e.slug&&(e.slug=n.slug),n.name&&!e.name&&(e.name=n.name),n.branchedFrom&&!e.branchedFrom&&(e.branchedFrom=n.branchedFrom),Zt(n)&&n.message.model&&!Yt(n.message.model)&&!e.model&&(e.model=n.message.model),e.sessionId&&e.version&&e.gitBranch&&e.cwd&&e.model)break;return e}function as(t){return Je(Ke(t))}function Ve(t,e){const n=He(t),s=Je(n),o=qe(n),i=e!=null&&e.skipStats?Mt(o.length):vt(o);return{...s,turns:o,stats:i,rawMessages:e!=null&&e.skipStats?[]:n,agentKind:"claude"}}function Ge(t,e){var v;const n=He(e);if(n.length===0)return t;const s=t.rawMessages,o=[...s,...n],i=ss(s),l=Math.max(0,t.turns.length-i.length);let a=Math.max(0,i.length-1);const c=new Set;for(const P of n)if(P.type==="progress"){const $=P.parentToolUseID;$&&c.add($)}if(c.size>0)for(let P=a-1;P>=0;P--){const $=t.turns[l+P];if($!=null&&$.toolCalls.some(y=>c.has(y.id))){a=P;break}}const u=i[a]??s.length,h=t.turns.slice(0,l+a),C=qe(o.slice(u)),_=Le([...h,...C]),m=vt(_);return{sessionId:t.sessionId,version:t.version,gitBranch:t.gitBranch,cwd:t.cwd,slug:t.slug,name:t.name,model:t.model||((v=[..._].reverse().find(P=>P.model&&!Yt(P.model)))==null?void 0:v.model)||"",turns:_,stats:m,rawMessages:o,branchedFrom:t.branchedFrom,agentKind:t.agentKind}}const Qe="<task-notification>",ls=/<task-id>([^<]+)<\/task-id>/g,cs=/<tool-use-id>([^<]+)<\/tool-use-id>/g;function H(t){return typeof t=="object"&&t!==null}function Yt(t){return typeof t=="string"&&t.startsWith("<")}function us(t){if(t.type!=="assistant"||t.isApiErrorMessage!==!0)return null;const e=H(t.message)?t.message:null,n=Array.isArray(e==null?void 0:e.content)?e.content.filter(i=>H(i)&&typeof i.text=="string").map(i=>i.text).join(`
9
+ `).trim():"",s=typeof t.apiErrorStatus=="number"?t.apiErrorStatus:void 0,o=xt(n||"The request failed",s);return t.error==="authentication_failed"?{...o,reason:"not_signed_in"}:o}function ds(t){if(t.type!=="assistant"||!H(t.message))return!1;const{stop_reason:e,model:n}=t.message;return e==="end_turn"||e==="stop_sequence"||Yt(n)&&e!=="tool_use"}function fs(t){const e=H(t.message)?t.message:null,n=e==null?void 0:e.content;return typeof n=="string"?[n]:Array.isArray(n)?n.filter(s=>H(s)&&typeof s.text=="string").map(s=>s.text):[]}function ps(t){const e=[],n=new Map,s=new Set,o=new Set;function i(a,c){n.has(a)||n.set(a,c)}function l(a,c,u){if(a.includes(Qe)){for(const h of a.matchAll(ls))i(h[1],c),u==null||u.add(h[1]);for(const h of a.matchAll(cs))i(h[1],c),u==null||u.add(h[1])}}for(const[a,c]of t.entries()){if(c.type==="user"){const u=H(c.toolUseResult)?c.toolUseResult:null;if((u==null?void 0:u.status)==="async_launched"){const h=H(c.message)?c.message:null,_=(Array.isArray(h==null?void 0:h.content)?h.content:[]).filter(y=>H(y)&&y.type==="tool_result").map(y=>y.tool_use_id),m=[u.agentId,u.taskId,..._].filter(y=>typeof y=="string"&&y.length>0),v=[u.description,u.workflowName,u.summary].find(y=>typeof y=="string"&&y.length>0)??"",P=_.find(y=>typeof y=="string"&&y.length>0),$=typeof c.timestamp=="string"?c.timestamp:void 0;m.length>0&&e.push({ids:m,launch:{agent:{description:v,startedAt:$,toolUseId:P},launchedAt:a}})}for(const h of fs(c))l(h,a,o);continue}if(c.type==="assistant"){const u=H(c.message)?c.message:null,h=Array.isArray(u==null?void 0:u.content)?u.content:[];for(const C of h){if(!H(C)||C.type!=="tool_use"||C.name!=="TaskStop")continue;const _=H(C.input)?C.input:null,m=(_==null?void 0:_.task_id)??(_==null?void 0:_.shell_id);typeof m=="string"&&i(m,a)}continue}if(c.type==="attachment"){const u=H(c.attachment)?c.attachment:null;typeof(u==null?void 0:u.prompt)=="string"&&l(u.prompt,a,o);continue}if(c.type==="queue-operation"&&typeof c.content=="string"){const u=c.operation;l(c.content,a,u==="enqueue"?s:o)}}return{launches:e.map(({ids:a,launch:c})=>{const u=a.flatMap(h=>n.get(h)??[]);return u.length>0?{...c,endedAt:Math.min(...u)}:c}),undeliveredNotifications:[...s].filter(a=>!o.has(a)).length}}function ms(t){var l,a;let e=0,n=null,s=!1;function o(c,u){const h={status:c,pendingQueue:Math.max(0,e)};return u&&(h.toolName=u),h}function i(){return n??(n=ps(t))}for(let c=t.length-1;c>=0;c--){const u=t[c];if(u.type!=="queue-operation"){if(u.type==="progress"){const h=u.data;if((h==null?void 0:h.type)==="hook_progress"&&(h.decision??((l=h.hookSpecificOutput)==null?void 0:l.permissionDecision))==="defer")return o("deferred");break}break}}for(let c=t.length-1;c>=0;c--){const u=t[c];if(u.type==="queue-operation"){if(typeof u.content=="string"&&u.content.includes(Qe))continue;const h=u.operation;h==="enqueue"?e++:(h==="dequeue"||h==="remove")&&e--;continue}if(u.type==="attachment"){const h=H(u.attachment)?u.attachment:null;(h==null?void 0:h.commandMode)==="task-notification"&&(s=!0);continue}if(u.type==="assistant"){const h=u.message,C=h==null?void 0:h.stop_reason,_=us(u);if(_)return{status:"completed",terminalReason:typeof u.error=="string"&&u.error?u.error:"api_error",failure:_,pendingQueue:Math.max(0,e)};if(ds(u)){const m=i();if(s||m.undeliveredNotifications>0)return o("processing");const v=Qt(m.launches,Math.max(0,e));if(v)return v;let P=!1;for(let $=c-1;$>=0;$--){const y=t[$];if(y.type==="user"&&!y.isMeta){P=!0;break}}return o(P?"completed":"idle")}if(C==="tool_use"){const m=h==null?void 0:h.content,v=(a=m==null?void 0:m.findLast)==null?void 0:a.call(m,P=>P.type==="tool_use");return o("tool_use",v==null?void 0:v.name)}return o("thinking")}if(u.type==="user"){if(u.isMeta)continue;return o("processing")}if(u.type==="system"&&u.subtype==="terminal_reason"){const h=u.reason;if(h)return{status:"completed",terminalReason:h,pendingQueue:Math.max(0,e)};continue}u.type!=="summary"&&u.type==="system"&&u.subtype}return{status:"idle"}}function gs(t,e,n){const s=typeof t.sessionId=="string"?t.sessionId:"";return{record:{...t,sessionId:e,branchedFrom:{sessionId:s,turnIndex:n}},originalId:s}}function hs(t){return We(t).turnStartIndices}const ys=new Set(["bashEditDiff","structuredPatch","prompt","summary","description","status"]);function Ze(t,e,n){let s=!1;for(const o of Object.keys(t)){if(ys.has(o))continue;const i=t[o];typeof i=="string"?s=X(t,o,e)||s:J(i)&&n<3&&(s=Ze(i,e,n+1)||s)}return s}function _s(t,e){if(t.type!=="user")return!1;const n=J(t.message)?t.message:null;let s=!1;if(n&&Array.isArray(n.content)){for(const i of n.content)if(!(!J(i)||i.type!=="tool_result")){if(typeof i.content=="string")s=X(i,"content",e)||s;else if(Array.isArray(i.content)){const l=Xt(i.content,a=>J(a)&&a.type==="text"&&typeof a.text=="string"?a.text:void 0,`
10
+ `,(a,c)=>({...a,text:c}),e);l&&(i.content=l,s=!0);for(const a of i.content)J(a)&&a.type==="image"&&J(a.source)&&(s=X(a.source,"data",e,"image")||s)}}}const o=t.toolUseResult;return typeof o=="string"?s=X(t,"toolUseResult",e)||s:J(o)&&!o.agentId&&(s=Ze(o,e,0)||s),s}function Lt(t,e,n){if(!e)return;t.assistantText.push(e);const s=t.contentBlocks[t.contentBlocks.length-1];if((s==null?void 0:s.kind)==="text"){s.text.push(e);return}t.contentBlocks.push({kind:"text",text:[e],timestamp:n})}const ks=/^Crew chat · ([^\n]+) · message (\d+)(?:\n|$)/,bs=/^Delegated task \S+ (?:running|completed|error|cancelled|needs attention)\. Child session: /;function Ts(t){const e=t.trim();return!e||ks.test(e)||bs.test(e)?!1:At(e).sender===null}function Cs(t){return t===null?"":typeof t=="string"?t:t.flatMap(e=>e.type==="text"?[e.text]:[]).join(`
11
+ `)}function xs(t){const e=new Map;let n=[];const s=a=>{if(!(n.length===0||!Ts(a))){for(const c of n)e.set(c,a.trim());n=[]}};for(const a of t){s(Cs(a.userMessage));for(const c of a.contentBlocks)if(c.kind==="queued_prompt")s(c.content);else if(c.kind==="tool_calls")for(const u of c.toolCalls)u.asyncQuestion&&n.push(u.id)}const o=a=>a.asyncQuestion===!0&&a.asyncAnswer!==e.get(a.id),i=new Map,l=a=>{if(!o(a))return a;let c=i.get(a);if(!c){const{asyncAnswer:u,...h}=a,C=e.get(a.id);c=C===void 0?h:{...h,asyncAnswer:C},i.set(a,c)}return c};return t.map(a=>a.toolCalls.some(o)?{...a,toolCalls:a.toolCalls.map(l),contentBlocks:a.contentBlocks.map(c=>c.kind==="tool_calls"?{...c,toolCalls:c.toolCalls.map(l)}:c)}:a)}const V=Object.freeze({items:12,itemChars:2e4,metadataChars:2e3,totalChars:1e5,noteChars:2e3}),Xe=/^ctx-[a-z0-9]{8,32}$/;function As(t){var e,n;return t.kind==="browser"?t.note.length:t.kind==="file"?(((e=t.text)==null?void 0:e.length)??0)+(((n=t.comment)==null?void 0:n.length)??0):t.text.length}function Is(t){if(!Xe.test(t.id))return"This context has no valid id";if(As(t)>V.itemChars)return`This context is longer than ${V.itemChars.toLocaleString("en-US")} characters`;if(t.kind==="browser"&&t.note.length>V.noteChars)return`An annotation note is limited to ${V.noteChars.toLocaleString("en-US")} characters`;const e=Ye(t).filter(([n])=>n!=="comment");return e.some(([,n])=>n.length>V.metadataChars)?`This context's ${e.find(([,n])=>n.length>V.metadataChars)[0]} is longer than ${V.metadataChars.toLocaleString("en-US")} characters`:null}function Ss(t,e){if(t.some(o=>o.id===e.id))return null;if(t.length>=V.items)return`A message holds at most ${V.items} context items`;const n=Is(e);return n||([...t,e].reduce((o,i)=>o+Ps(i).length,0)>V.totalChars?`The message's context would exceed ${V.totalChars.toLocaleString("en-US")} characters`:null)}function ws(t){const e=[];for(const n of t){if(e.some(o=>o.id===n.id))return"The same context appears twice";const s=Ss(e,n);if(s)return s;e.push(n)}return null}function Es(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/\r/g,"&#13;").replace(/\n/g,"&#10;")}function Ms(t){return t.replace(/&#10;/g,`
12
+ `).replace(/&#13;/g,"\r").replace(/&lt;/g,"<").replace(/&quot;/g,'"').replace(/&amp;/g,"&")}const Wt="</context>";function vs(t){return t.split(`
13
+ `).map(e=>/^ *<\/context>/.test(e)?` ${e}`:e).join(`
14
+ `)}function Ns(t){return t.split(`
15
+ `).map(e=>/^ +<\/context>/.test(e)?e.slice(1):e).join(`
16
+ `)}function Ye(t){switch(t.kind){case"file":return[["path",t.path],...t.startLine!==void 0?[["lines",t.endLine!==void 0&&t.endLine!==t.startLine?`${t.startLine}-${t.endLine}`:String(t.startLine)]]:[],...t.comment?[["comment",t.comment]]:[]];case"terminal":return t.label?[["label",t.label]]:[];case"quote":return[["session",t.source.sessionId],["turn",t.source.turnId],["dir",t.source.dirName],["file",t.source.fileName]];case"browser":return[["url",t.url],["title",t.title],["viewport",`${t.viewport.width}x${t.viewport.height}`],["region",`${t.region.x},${t.region.y},${t.region.width},${t.region.height}`],["captured",t.capturedAt],["browser",t.browser],...t.tab?[["tab",t.tab]]:[],["image",String(t.image)]]}}function Rs(t){return t.kind==="browser"?t.note:t.kind==="file"?t.text??"":t.text}function Ps(t){return`<context ${[["id",t.id],["kind",t.kind],...Ye(t)].map(([n,s])=>`${n}="${Es(s)}"`).join(" ")}>
17
+ ${vs(Rs(t))}
18
+ ${Wt}`}const $s=/^<context ((?:[a-z]+="[^"]*"\s*)+)>\n/;function Us(t){const e=new Map;for(const n of t.matchAll(/([a-z]+)="([^"]*)"/g))e.set(n[1],Ms(n[2]));return e}function Ut(t){if(!(t===void 0||!/^\d+$/.test(t)))return Number(t)}function Os(t,e){const n=t.get("id");if(!n||!Xe.test(n))return null;switch(t.get("kind")){case"file":{const s=t.get("path");if(!s)return null;const[o,i]=(t.get("lines")??"").split("-"),l=Ut(o),a=Ut(i)??l,c=t.get("comment");return{id:n,kind:"file",path:s,...l!==void 0?{startLine:l,endLine:a}:{},...e?{text:e}:{},...c?{comment:c}:{}}}case"terminal":{const s=t.get("label");return{id:n,kind:"terminal",text:e,...s?{label:s}:{}}}case"quote":{const[s,o,i,l]=["session","turn","dir","file"].map(a=>t.get(a));return!s||!o||!i||!l?null:{id:n,kind:"quote",text:e,source:{sessionId:s,turnId:o,dirName:i,fileName:l}}}case"browser":{const s=(t.get("viewport")??"").split("x").map(Number),o=(t.get("region")??"").split(",").map(Number),i=Ut(t.get("image"));if(s.length!==2||o.length!==4||![...s,...o].every(Number.isFinite)||!i)return null;const l=t.get("tab");return{id:n,kind:"browser",note:e,url:t.get("url")??"",title:t.get("title")??"",viewport:{width:s[0],height:s[1]},region:{x:o[0],y:o[1],width:o[2],height:o[3]},capturedAt:t.get("captured")??"",browser:t.get("browser")??"",...l?{tab:l}:{},image:i}}default:return null}}function Bs(t){const e=[];let n=t;for(;;){const s=$s.exec(n);if(!s)break;const o=n.indexOf(`
19
+ ${Wt}`,s[0].length-1);if(o<0)break;const i=Os(Us(s[1]),Ns(n.slice(s[0].length,o)));if(!i)break;e.push(i),n=n.slice(o+Wt.length+1).replace(/^\n{1,2}/,"")}return e.length===0||ws(e)?null:{context:e,text:n.trim()}}function tn(t){var e;return((e=Bs(t))==null?void 0:e.text)??t}function ke(t){return t.includes("*** Begin Patch")&&t.includes("*** End Patch")}function Ds(t){if(!t.includes("apply_patch")||!t.includes("*** Begin Patch"))return[];const e=new Map;for(let l=0;l<t.length;l++){const a=ce(t,l);if(a){if(ke(a.value)){const c=t.slice(0,l).match(/(?:^|[;\n])\s*(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*$/);c&&e.set(c[1],a.value)}l=a.endIndex-1}}const n=[],s=new Set,o=/\btools\s*\.\s*apply_patch\s*\(/g;let i;for(;(i=o.exec(t))!==null;){let l=i.index+i[0].length;for(;/\s/.test(t[l]??"");)l++;const a=ce(t,l),c=a?null:t.slice(l).match(/^([A-Za-z_$][\w$]*)/),u=(a==null?void 0:a.value)??(c?e.get(c[1]):void 0);!u||!ke(u)||s.has(u)||(s.add(u),n.push(u))}return n}function be(t,e){if(!e||t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t))return t;const n=e.replace(/[\\/]+$/,""),s=t.replace(/^\.[\\/]/,"");return/^[A-Za-z]:[\\/]/.test(e)?`${n}\\${s.replace(/\//g,"\\")}`:`${n}/${s}`}function Te(t,e,n,s=""){var c,u;const o=[],i=/^\*\*\*\s+(Update File|Add File|Delete File):\s*(.+)$/gm,l=[];let a;for(;(a=i.exec(t))!==null;)l.push({action:a[1],filePath:a[2].trim(),headerIdx:a.index,startIdx:a.index+a[0].length});for(let h=0;h<l.length;h++){const C=l[h],_=h+1<l.length?l[h+1].headerIdx:t.length,m=t.slice(C.startIdx,_),v=(u=(c=m.match(/^\*\*\*\s+Move to:\s*(.+)$/m))==null?void 0:c[1])==null?void 0:u.trim(),P=be(C.filePath,s),$=be(v||C.filePath,s),y=m.split(/^@@.*$/m).filter(L=>L.trim()),N=[],O=[];for(const L of y)for(const q of L.split(`
20
+ `))q.startsWith("-")?N.push(q.slice(1)):q.startsWith("+")?O.push(q.slice(1)):q.startsWith(" ")&&(N.push(q.slice(1)),O.push(q.slice(1)));const z=l.length>1?`${e}:file-${h}`:e;C.action==="Add File"?o.push({id:z,name:"Write",input:{file_path:$,content:O.join(`
21
+ `)},result:null,isError:!1,timestamp:n}):C.action==="Delete File"?o.push({id:z,name:"Edit",input:{file_path:$,old_string:N.join(`
22
+ `),new_string:""},result:null,isError:!1,timestamp:n}):o.push({id:z,name:"Edit",input:{file_path:$,...v?{old_path:P}:{},old_string:N.join(`
23
+ `),new_string:O.join(`
24
+ `)},result:null,isError:!1,timestamp:n})}return o}function Fs(t,e,n,s,o=""){return t==="apply_patch"?Te(e,n,s,o):Ds(e).flatMap((i,l)=>Te(i,`${n}:patch-${l}`,s,o))}function js(t,e,n){var a;if(!e||!/(?:apply[_ ]patch|invalid patch|invalid context|failed to (?:apply|find)|could not apply)/i.test(t))return new Set;const s=new Map;for(const c of n){const u=(a=c.id.match(/:patch-(\d+)(?::file-\d+)?$/))==null?void 0:a[1];if(u===void 0)continue;const h=Number(u),C=s.get(h)??[];C.push(c),s.set(h,C)}if(s.size===0)return new Set(n.map(c=>c.id));const o=t.toLowerCase().replaceAll("\\","/"),i=new Set;for(const[c,u]of s)u.some(h=>{const C=String(h.input.file_path??"").toLowerCase().replaceAll("\\","/");if(!C)return!1;const m=C.split("/").filter(Boolean).slice(-2).join("/");return o.includes(C)||m.includes("/")&&o.includes(m)})&&i.add(c);for(const c of o.matchAll(/\bpatch\s*(?:#|-)?\s*(\d+)\b/g)){const u=Number(c[1]);s.has(u)&&i.add(u)}i.size===0&&i.add(Math.max(...s.keys()));const l=Math.min(...i);for(const c of s.keys())c>=l&&i.add(c);return new Set([...i].flatMap(c=>{var u;return((u=s.get(c))==null?void 0:u.map(h=>h.id))??[]}))}function Q(t){return typeof t=="object"&&t!==null}const Ls=new Map([["spawn_agent","spawn_agent"],["spawnAgent","spawn_agent"],["wait_agent","wait_agent"],["waitAgent","wait_agent"],["send_message","send_message"],["sendMessage","send_message"],["followup_task","followup_task"],["followupTask","followup_task"],["list_agents","list_agents"],["listAgents","list_agents"],["interrupt_agent","interrupt_agent"],["interruptAgent","interrupt_agent"]]),Ws=new Set(["exec","exec_command","write_stdin","apply_patch","update_plan","view_image","request_user_input","request_user_input_async","tool_search","list_mcp_resources","list_mcp_resource_templates","read_mcp_resource","request_plugin_install","create_goal","get_goal","update_goal","wait"]);function st(t){if(t.startsWith("mcp__"))return t;const e=t.split(/(?:__|[.:/])+/).filter(Boolean).at(-1)??t;return Ls.get(e)??(Ws.has(e)?e:t)}function qs(t){const e=t==null?void 0:t.match(/Process exited with code (\d+)/);return e?e[1]!=="0":!1}function zs(t){return t==="request_user_input"||t==="request_user_input_async"}function Ks(t){const n=(Array.isArray(t.questions)?t.questions:[t]).filter(s=>Q(s)).map(s=>{const o=typeof s.question=="string"?s.question:typeof s.title=="string"?s.title:"",i=Array.isArray(s.options)?s.options:[];return{question:o,...typeof s.header=="string"&&s.header?{header:s.header}:{},options:i.map(l=>typeof l=="string"?{label:l}:!Q(l)||typeof l.label!="string"?null:{label:l.label,...typeof l.description=="string"&&l.description?{description:l.description}:{}}).filter(l=>l!==null)}}).filter(s=>s.question);return n.length>0?{...t,questions:n}:t}function Hs(t){return{todos:(Array.isArray(t.plan)?t.plan:[]).filter(s=>Q(s)).map(s=>({content:typeof s.step=="string"?s.step:"",status:typeof s.status=="string"?s.status:"pending",activeForm:typeof s.step=="string"?s.step:""}))}}function Js(t){if(t.type!=="image"&&t.type!=="input_image"&&t.type!=="image_url")return null;const e=Q(t.source)?t.source:t,n=e.media_type??e.mimeType;if(typeof n=="string"&&n.startsWith("image/")&&typeof e.data=="string"&&e.data)return{type:"image",source:{type:"base64",media_type:n,data:e.data}};const s=Q(t.image_url)?t.image_url.url:t.image_url,o=typeof s=="string"?/^data:(image\/[^;,]+);base64,(.+)$/is.exec(s):null;return o?{type:"image",source:{type:"base64",media_type:o[1].toLowerCase(),data:o[2]}}:null}function Ce(t){if(typeof t=="string")return{parts:[t],text:t,images:[]};if(!Array.isArray(t)){const s=t==null?"":JSON.stringify(t);return{parts:[s],text:s,images:[]}}const e=[],n=[];for(const s of t){if(!Q(s))continue;typeof s.text=="string"&&e.push(s.text);const o=Js(s);o&&n.push(o)}return{parts:e,text:e.join(""),images:n}}const Vs=/^Script (?:completed|failed|running)\b/;function en(t,e){Q(t)&&(t.status==="rejected"?e.push(1):t.status==="fulfilled"?en(t.value,e):typeof t.exit_code=="number"&&e.push(t.exit_code))}function Gs(t){const e=t[0]??"";if(!Vs.test(e))return;if(e.startsWith("Script failed"))return!0;const n=[];for(const s of t.slice(1)){let o;try{o=JSON.parse(s)}catch{continue}for(const i of Array.isArray(o)?o:[o])en(i,n)}return n.length>0?n.some(s=>s!==0):void 0}function It(t){const e=Ce(t);let n=Q(t)&&!Array.isArray(t)?t:null;try{const u=n??JSON.parse(e.text);Q(u)&&!Array.isArray(u)&&(n=u)}catch{}const s=n&&("output"in n||"content"in n)?Ce(n.output??n.content):e,o=s===e?e.images:[...e.images,...s.images],i=Q(n==null?void 0:n.metadata)?n.metadata:null,l=(i==null?void 0:i.exit_code)??(n==null?void 0:n.exit_code),a=typeof(n==null?void 0:n.isError)=="boolean"?n.isError:typeof(n==null?void 0:n.is_error)=="boolean"?n.is_error:void 0,c=a===!0||(typeof l=="number"?l!==0:a??Gs(e.parts)??qs(s.text));return{text:s.text,isError:c,...o.length>0?{images:o}:{}}}const Qs=["# AGENTS.md instructions","<recommended_plugins>","<environment_context>","<permissions instructions>","<collaboration_mode>","<skills_instructions>"];function Zs(t){var e,n;return((n=(e=globalThis.crypto)==null?void 0:e.randomUUID)==null?void 0:n.call(e))??`${t}-${Math.random().toString(36).slice(2,10)}`}function mt(t){try{return JSON.parse(t)}catch{return null}}function B(t){return typeof t=="object"&&t!==null}function Xs(t){const e=B(t.source)?t.source:null,n=e&&B(e.subagent)?e.subagent:null,s=n&&B(n.thread_spawn)?n.thread_spawn:null;for(const o of[t.forked_from_id,t.parent_thread_id,s==null?void 0:s.parent_thread_id])if(typeof o=="string"&&o)return o;return null}function te(t){var o;const e=t.find(i=>(i==null?void 0:i.type)==="session_meta"),n=(o=e==null?void 0:e.payload)==null?void 0:o.subagent_history_start_ordinal;if(typeof n!="number")return null;const s=i=>typeof i=="number"&&i>=n;return!s(e==null?void 0:e.rolloutLastOrdinal)&&!t.some(i=>s(i==null?void 0:i.ordinal))?null:i=>typeof i.ordinal=="number"&&i.ordinal>0&&i.ordinal<n}async function Ys(t,e){var o;if(!t.includes('"subagent_history_start_ordinal"'))return t;const n=mt(t);if((n==null?void 0:n.type)!=="session_meta")return t;const s=await e();for(let i=s.length-1;i>=0;i--){const l=(o=mt(s[i]))==null?void 0:o.ordinal;if(typeof l=="number")return JSON.stringify({...n,rolloutLastOrdinal:l})}return t}function to(t){const e=t.payload;return t.type!=="event_msg"||!B(e)?null:e.type==="sub_agent_activity"?e:e.type==="item_completed"&&B(e.item)&&e.item.type==="SubAgentActivity"?e.item:null}function nn(t){const e=to(t);return!e||typeof e.agent_thread_id!="string"||typeof e.agent_path!="string"?null:{agentId:e.agent_thread_id,agentPath:e.agent_path,kind:typeof e.kind=="string"?e.kind:"started",eventId:dt(e.event_id,e.id)??"",model:dt(e.model)||null,effort:dt(e.reasoning_effort)||null}}function sn(t,e=0){if(t==="unauthorized")return 401;if(!B(t)||e>3)return;const n=t.http_status_code??t.httpStatusCode;if(typeof n=="number")return n;for(const s of Object.values(t)){const o=sn(s,e+1);if(o!==void 0)return o}}function eo(t){if(!B(t)||typeof t.message!="string"||!t.message.trim())return null;const e=[t.additional_details,t.additionalDetails].find(o=>typeof o=="string"&&o.trim()),n=sn(t.codex_error_info??t.codexErrorInfo),s=xt(t.message.trim(),n);return s.reason==="other"&&typeof e=="string"?{...xt(e,n),message:t.message.trim()}:s}function on(t){return t.type==="task_complete"?eo(t.error):null}function ot(t){return!t||typeof t.type!="string"?!1:t.type==="session_meta"||t.type==="turn_context"||t.type==="event_msg"||t.type==="response_item"||t.type==="inter_agent_communication_metadata"||t.type==="compacted"||t.type==="world_state"}function St(t,e){const n=t==null?void 0:t.content;return Array.isArray(n)?n.filter(s=>B(s)&&s.type===e&&typeof s.text=="string").map(s=>s.text).join(`
25
+ `).trim():""}const no=/^data:(image\/(?:png|jpeg|gif|webp));base64,(.+)$/is,so=/^data:(audio\/(?:wav|x-wav|mpeg|mp4|webm|ogg));base64,(.+)$/is;function rn(t){if(typeof t!="string")return null;const e=no.exec(t);return!(e!=null&&e[1])||!e[2]?null:{type:"image",source:{type:"base64",media_type:e[1].toLowerCase(),data:e[2]}}}function an(t){if(typeof t!="string")return null;const e=so.exec(t);return!(e!=null&&e[1])||!e[2]?null:{type:"audio",source:{type:"base64",media_type:e[1].toLowerCase(),data:e[2]}}}function oo(t){return Array.isArray(t.images)?t.images.map(rn).filter(e=>e!==null):[]}function io(t){return Array.isArray(t.audio)?t.audio.map(an).filter(e=>e!==null):[]}function ln(t){return Array.isArray(t.content)?t.content.filter(e=>B(e)&&e.type==="input_image").map(e=>rn(e.image_url)).filter(e=>e!==null):[]}function cn(t){return Array.isArray(t.content)?t.content.filter(e=>B(e)&&e.type==="input_audio").map(e=>an(e.audio_url)).filter(e=>e!==null):[]}function xe(t,e,n=[],s=[],o=[]){const i=[...s.map(a=>`
26
+ ![image](<${a}>)`),...o.map(a=>`
27
+ [audio attachment](<${a}>)`)].join(""),l=t+i;return e.length===0&&n.length===0?l:[...e,...n,...l?[{type:"text",text:l}]:[]]}function ro(t){var l,a;const e=St(t,"input_text");if(!e)return{messageType:null,text:""};const n=e.match(/\r?\nPayload:\s*(?:\r?\n|$)/);if(!e.startsWith("Message Type:")||!n||n.index===void 0)return{messageType:null,text:e.trim()};const o=((a=(l=e.slice(0,n.index).match(/^Message Type:\s*([^\r\n]+)/))==null?void 0:l[1])==null?void 0:a.trim().toUpperCase())??null,i=e.slice(n.index+n[0].length).trim();return{messageType:o,text:i}}function it(t){return t.split(/[\\/]/).filter(Boolean).at(-1)??null}function ao(t){if(typeof t!="string")return"";const e=t.trim();return/^gAAAAA[A-Za-z0-9_-]+$/.test(e)?"":e}function qt(t){const e=t.trim();return!e||Qs.some(n=>e.startsWith(n))?"":e}function lo(t){if(!B(t))return null;const e=typeof t.input_tokens=="number"?t.input_tokens:0,n=typeof t.output_tokens=="number"?t.output_tokens:0,s=typeof t.cache_write_input_tokens=="number"?t.cache_write_input_tokens:typeof t.cache_creation_input_tokens=="number"?t.cache_creation_input_tokens:0,o=typeof t.cached_input_tokens=="number"?Math.max(0,t.cached_input_tokens):null,i=o??(typeof t.cache_read_input_tokens=="number"?t.cache_read_input_tokens:0),l=o===null?e:Math.max(0,e-o);return l===0&&n===0&&s===0&&i===0?null:{input_tokens:l,output_tokens:n,cache_creation_input_tokens:s,cache_read_input_tokens:i}}function co(t,e,n){if(!e)return;const s={type:"thinking",thinking:e,signature:""};t.thinking.push(s);const o=t.contentBlocks[t.contentBlocks.length-1];if(o&&o.kind==="thinking"){o.blocks.push(s);return}t.contentBlocks.push({kind:"thinking",blocks:[s],timestamp:n})}function et(t,e,n){t.toolCalls.push(e);const s=t.contentBlocks[t.contentBlocks.length-1];if(s&&s.kind==="tool_calls"&&s.timestamp===n){s.toolCalls.push(e);return}t.contentBlocks.push({kind:"tool_calls",toolCalls:[e],timestamp:n})}function uo(t,e,n){if(!e||!(e.userMessage!==null||e.assistantText.length>0||e.toolCalls.length>0||e.thinking.length>0||e.subAgentActivity.length>0))return null;if(e.timestamp&&n){const o=new Date(e.timestamp).getTime(),i=new Date(n).getTime();Number.isFinite(o)&&Number.isFinite(i)&&i>=o&&(e.durationMs=i-o)}return t.push(e),null}function Ae(t){if(typeof t!="string"||!t.trim())return{};try{const e=JSON.parse(t);return B(e)?e:{value:e}}catch{return{raw:t}}}function rt(t){if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t??"")}}function dt(...t){return t.find(e=>typeof e=="string")}function fo(t){return t.startsWith("exec-")}function po(t){var o;if(!B(t))return{text:rt(t),isError:!1};if("Err"in t)return{text:rt(t.Err),isError:!0};const e=B(t.Ok)?t.Ok:null;if(!e)return{text:rt(t),isError:!1};const n=It({...e,content:e.content}),s=n.text||((o=n.images)!=null&&o.length?"":e.structuredContent!==void 0?rt(e.structuredContent):rt(e));return{...n,text:s,isError:n.isError}}function mo(t,e,n){return{id:t?`${t}@${e}`:Zs("codex-turn"),userMessage:null,contentBlocks:[],thinking:[],assistantText:[],toolCalls:[],subAgentActivity:[],timestamp:e,durationMs:null,tokenUsage:null,model:n}}function zt(t){const e=B(t.payload)?t.payload:null;return t.type==="event_msg"&&(e==null?void 0:e.type)==="user_message"&&typeof e.message=="string"?qt(e.message):t.type==="response_item"&&(e==null?void 0:e.type)==="message"&&e.role==="user"?qt(St(e,"input_text")):""}function go(){let t=!1;return e=>{const n=B(e.payload)?e.payload:null;if(e.type==="event_msg"&&(n==null?void 0:n.type)==="user_message"){const o=t;return t=!1,o?"":zt(e)}if(e.type!=="response_item")return"";const s=zt(e);return s?t=!0:((n==null?void 0:n.type)!=="message"||n.role!=="user")&&(t=!1),s}}function ho(t,e){if(t.type==="session_meta"||t.type==="event_msg"&&(e==null?void 0:e.type)==="task_started")return!1;if(t.type==="response_item"&&(e==null?void 0:e.type)==="message"){if(e.role==="developer"||e.role==="system")return!1;if(e.role==="user")return zt(t)!==""||ln(e).length>0||cn(e).length>0}return!0}function un(t){let e="",n="",s="",o="",i="",l,a="",c="",u="",h="",C=0,_=!1,m=null,v="/root";const P=go(),$=te(t);for(const y of t){if(!B(y.payload)||$!=null&&$(y))continue;if(y.type==="session_meta"){if(e||(e=typeof y.payload.id=="string"?y.payload.id:""),n||(n=typeof y.payload.cli_version=="string"?y.payload.cli_version:""),o||(o=typeof y.payload.cwd=="string"?y.payload.cwd:""),!l&&B(y.payload.branchedFrom)){const L=typeof y.payload.branchedFrom.sessionId=="string"?y.payload.branchedFrom.sessionId:"";L&&(l={sessionId:L,turnIndex:typeof y.payload.branchedFrom.turnIndex=="number"?y.payload.branchedFrom.turnIndex:null})}const O=B(y.payload.source)?y.payload.source:null;if(O&&B(O.subagent)){_=!0;const L=B(O.subagent.thread_spawn)?O.subagent.thread_spawn:null;L&&typeof L.agent_path=="string"&&(v=L.agent_path)}m=Xs(y.payload)??m;const z=B(y.payload.git)?y.payload.git:null;s||(s=z&&typeof z.branch=="string"?z.branch:"")}y.type==="turn_context"&&(i||(i=typeof y.payload.model=="string"?y.payload.model:""),o||(o=typeof y.payload.cwd=="string"?y.payload.cwd:""));const N=tn(P(y));N&&(a||(a=N),c=N,C++,u||(u=y.timestamp??""),h=y.timestamp??h)}return h===""&&(h=u),{sessionId:e,version:n,gitBranch:s,cwd:o,model:i,slug:"",name:"",branchedFrom:l,firstUserMessage:a,lastUserMessage:c,timestamp:u,lastTimestamp:h,turnCount:C,isSubagent:_,parentSessionId:m,agentPath:v}}function yo(t){for(const e of t.split(`
28
+ `)){const n=e.trim();if(n)return ot(mt(n))}return!1}function _o(t){return ot(t[0]??null)}function ko(t){const e=t.map(mt).filter(ot);return un(e)}function dn(t,e){const n=un(t.filter(ot)),s=[],o=new Map,i=new Map,l=new Map,a=new Map,c=new Map,u=new Map,h=new Map,C=new Map;function _(E,I,f,A={}){const R=c.get(E);let p=C.get(E);if(!p){const S={agentId:E,parentToolUseId:(R==null?void 0:R.parentToolCallId)||void 0,agentName:(R==null?void 0:R.nickname)??(R!=null&&R.agentPath?it(R.agentPath):null),subagentType:(R==null?void 0:R.agentType)??null,type:"assistant",content:null,toolCalls:[],thinking:[],text:[],timestamp:(R==null?void 0:R.timestamp)??f,tokenUsage:null,model:(R==null?void 0:R.model)??null,...R!=null&&R.effort?{effort:R.effort}:{},isBackground:!1,prompt:(R==null?void 0:R.message)||void 0,status:A.status??"running"};I.subAgentActivity.push(S);const U=I.contentBlocks[I.contentBlocks.length-1];(U==null?void 0:U.kind)==="sub_agent"?U.messages.push(S):I.contentBlocks.push({kind:"sub_agent",messages:[S],timestamp:f}),p={message:S,turn:I},C.set(E,p)}const b=p.message;if(R&&(b.parentToolUseId=R.parentToolCallId||b.parentToolUseId,b.agentName=R.nickname??(R.agentPath?it(R.agentPath):b.agentName),b.subagentType=R.agentType,b.model=R.model,R.effort&&(b.effort=R.effort),b.prompt=R.message||b.prompt),A.text&&!b.text.includes(A.text)&&(b.text.push(A.text),b.content=b.text.join(`
29
+
30
+ `)),A.status){const S=new Set(["completed","failed","interrupted"]);if(A.status==="running"&&b.status&&S.has(b.status)||(b.status=A.status),S.has(A.status)&&b.timestamp&&f){const U=new Date(b.timestamp).getTime(),M=new Date(f).getTime();Number.isFinite(U)&&Number.isFinite(M)&&M>=U&&(b.durationMs=M-U)}}return b}let m=null,v=null,P=!1,$=n.model||null,y="",N=null,O=!1;const z=[];let L=0,q=null,T=null;function r(E){const I=s.length,f=uo(s,E,y);return s.length>I&&T!==null&&z.push(T),T=null,f}function d(E,I,f){const A=mo(E,I,f);return T=q??L,q=null,O||(A.isFragment=!0),N&&(A.compactionSummary=N,N=null),A}function k(E,I,f,A,R){const p=i.get(I);if(p){p.input={...p.input,...f},p.result=A,p.isError=A==="failed";return}const b={id:I,name:"WebSearch",input:f,result:A,isError:A==="failed",timestamp:R};i.set(I,b),et(E,b,R)}const g=te(t);for(let E=0;E<t.length;E++){const I=t[E];if(!ot(I)||g!=null&&g(I))continue;L=E;const f=B(I.payload)?I.payload:void 0,A=I.timestamp??"";if(I.type!=="event_msg"&&(P=!1),I.type==="compacted"){m=r(m),N="Conversation compacted",y=A;continue}if(I.type==="world_state")continue;if(I.type==="turn_context"){m=r(m),q=E,v=typeof(f==null?void 0:f.turn_id)=="string"?f.turn_id:null,$=typeof(f==null?void 0:f.model)=="string"?f.model:$,y=A,O=!0;continue}if(I.type==="event_msg"&&(f==null?void 0:f.type)==="user_message"&&typeof f.message=="string"){if(P){P=!1;continue}m&&(m.assistantText.length>0||m.toolCalls.length>0||m.thinking.length>0)&&(m=r(m));const p=!O;O=!0,m??(m=d(v,A,$)),p&&(m.opensOnPrompt=!0);const b=(Array.isArray(f.local_images)?f.local_images:[]).filter(U=>typeof U=="string"&&U.length>0),S=(Array.isArray(f.local_audio)?f.local_audio:[]).filter(U=>typeof U=="string"&&U.length>0);m.userMessage=xe(f.message,oo(f),io(f),b,S),m.isFragment=!1,m.timestamp=m.timestamp||A,y=A;continue}if(!m&&!ho(I,f))continue;if(m??(m=d(v,A,$)),!m.model&&$&&(m.model=$),m.timestamp||(m.timestamp=A),A&&(y=A),I.type==="event_msg"&&(f==null?void 0:f.type)==="token_count"){const p=B(f.info)?f.info:null,b=p?lo(p.last_token_usage):null;b&&(m.tokenUsage=nt(m.tokenUsage,b));continue}if(I.type==="event_msg"&&(f==null?void 0:f.type)==="web_search_end"&&typeof f.call_id=="string"){const p={};typeof f.query=="string"&&f.query&&(p.query=f.query),B(f.action)&&(p.action=f.action),k(m,f.call_id,p,"completed",A);continue}if(I.type==="event_msg"&&(f==null?void 0:f.type)==="mcp_tool_call_end"&&typeof f.call_id=="string"&&B(f.invocation)){const p=f.invocation,b=typeof p.server=="string"?p.server:"mcp",S=typeof p.tool=="string"?p.tool:"tool",U=B(p.arguments)?p.arguments:{},M=po(f.result),D=o.get(f.call_id);D?(D.result=M.text,D.isError=M.isError,M.images&&(D.resultImages=M.images),o.delete(f.call_id)):fo(f.call_id)||et(m,{id:f.call_id,name:`mcp__${b}__${S}`,input:U,result:M.text,isError:M.isError,...M.images?{resultImages:M.images}:{},timestamp:A},A);continue}if(I.type==="event_msg"&&f){const p=on(f);if(p){Lt(m,p.reason==="not_signed_in"?Dn("codex"):p.message,A);continue}}const R=nn(I);if(R){const{agentId:p,agentPath:b,eventId:S,kind:U}=R,M=S?a.get(S):void 0,D=u.get(b),F=c.get(p)??(D?c.get(D):void 0);if(U!=="started"&&!F&&!M)continue;if(D&&D!==p&&!C.has(p)){const G=C.get(D);G&&(G.message.agentId=p,C.delete(D),C.set(p,G)),c.delete(D)}const W={agentId:p,nickname:(F==null?void 0:F.nickname)??it(b)??(M==null?void 0:M.taskName)??null,agentPath:b,message:(F==null?void 0:F.message)??(M==null?void 0:M.message)??"",model:R.model??(F==null?void 0:F.model)??(M==null?void 0:M.model)??null,effort:R.effort??(F==null?void 0:F.effort)??null,agentType:(F==null?void 0:F.agentType)??(M==null?void 0:M.agentType)??null,timestamp:(F==null?void 0:F.timestamp)??(A||(M==null?void 0:M.timestamp)||""),parentToolCallId:(F==null?void 0:F.parentToolCallId)??S};c.set(p,W),u.set(b,p),S&&(U==="started"||M)&&h.set(S,p),_(p,m,A,{status:U==="interrupted"||U==="completed"?U:"running"});continue}if(!(I.type!=="response_item"||!f)){if(f.type==="reasoning"){const p=Array.isArray(f.summary)?f.summary.filter(b=>typeof b=="string").join(`
31
+ `):"";co(m,p.trim(),A);continue}if(f.type==="message"&&f.role==="assistant"){Lt(m,St(f,"output_text"),A);continue}if(f.type==="message"&&f.role==="user"){const p=qt(St(f,"input_text"));if(m.userMessage!==null||m.contentBlocks.length>0){p&&(m.contentBlocks.push({kind:"queued_prompt",content:p,timestamp:A}),P=!0);continue}const b=ln(f),S=cn(f);(p||b.length>0||S.length>0)&&(m.userMessage=xe(p,b,S),m.isFragment=!1,O=!0);continue}if(f.type==="web_search_call"&&typeof f.id=="string"){const p={};B(f.action)&&(p.action=f.action);const b=typeof f.status=="string"?f.status:"completed";k(m,f.id,p,b,A);continue}if(f.type==="tool_search_call"){const p=dt(f.call_id,f.id)??"";if(p){const b={id:p,name:"ToolSearch",input:B(f.arguments)?f.arguments:{},result:null,isError:!1,timestamp:A};o.set(p,b),et(m,b,A)}continue}if(f.type==="tool_search_output"&&typeof f.call_id=="string"){const p=o.get(f.call_id);if(p){const b=Array.isArray(f.tools)?f.tools:[],S=b.filter(B).map(D=>dt(D.name)??"").filter(Boolean),U=S.length>0?S.length:b.length,M=`Found ${U} tool${U===1?"":"s"}`;p.result=S.length>0?`${M}: ${S.join(", ")}`:M,p.isError=f.status==="failed",o.delete(f.call_id)}continue}if(f.type==="agent_message"&&typeof f.author=="string"){const p=f.author,b=typeof f.recipient=="string"?f.recipient:null,S=ro(f);if(S.messageType==="NEW_TASK")continue;const U=u.get(p),M=p.startsWith(`${n.agentPath}/`)&&(b===null||b===n.agentPath);if(!U&&!M)continue;const D=U??p;U||(c.set(D,{agentId:D,nickname:it(p),agentPath:p,message:"",model:null,agentType:null,timestamp:A,parentToolCallId:""}),u.set(p,D));let F;S.messageType==="FINAL_ANSWER"?F="completed":S.messageType==="ERROR"||S.messageType==="FAILED"?F="failed":S.messageType==="INTERRUPTED"?F="interrupted":S.messageType==="MESSAGE"&&(F="running"),_(D,m,A,{status:F,text:S.text||void 0});continue}if(f.type==="function_call"&&typeof f.call_id=="string"){const p=typeof f.name=="string"?f.name:"tool",b=st(p),S=Ae(f.arguments);let U=b,M=S;b==="exec_command"?U="Bash":b==="update_plan"?(U="TodoWrite",M=Hs(S)):zs(b)&&(U="AskUserQuestion",M=Ks(S)),b==="spawn_agent"&&a.set(f.call_id,{callId:f.call_id,message:ao(S.message),taskName:typeof S.task_name=="string"?S.task_name:null,model:typeof S.model=="string"?S.model:null,agentType:typeof S.agent_type=="string"?S.agent_type:null,timestamp:A});const D={id:f.call_id,name:U,input:M,result:null,isError:!1,timestamp:A,...b==="request_user_input_async"?{asyncQuestion:!0}:{}};o.set(D.id,D),et(m,D,A);continue}if(f.type==="function_call_output"&&typeof f.call_id=="string"){const p=o.get(f.call_id);if(!p)continue;const b=It(f.output),S=b.text;if(p.result=S,p.isError=b.isError,b.images&&(p.resultImages=b.images),o.delete(f.call_id),p.name==="spawn_agent"&&S)try{const U=JSON.parse(S),M=typeof U.agent_id=="string"?U.agent_id:h.get(p.id)??"",D=typeof U.task_name=="string"?U.task_name:null,F=typeof U.nickname=="string"?U.nickname:D?it(D):null;if(M){const W=a.get(p.id),j=c.get(M),G={agentId:M,nickname:F??(j==null?void 0:j.nickname)??(W==null?void 0:W.taskName)??null,agentPath:D??(j==null?void 0:j.agentPath)??null,message:(j==null?void 0:j.message)??(W==null?void 0:W.message)??"",model:(j==null?void 0:j.model)??(W==null?void 0:W.model)??null,effort:(j==null?void 0:j.effort)??null,agentType:(j==null?void 0:j.agentType)??(W==null?void 0:W.agentType)??null,timestamp:(j==null?void 0:j.timestamp)??(W==null?void 0:W.timestamp)??A,parentToolCallId:(j==null?void 0:j.parentToolCallId)??p.id};c.set(M,G),h.set(p.id,M),G.agentPath&&u.set(G.agentPath,M),_(M,m,A,{status:"running"})}}catch{}if(p.name==="wait_agent"&&S&&m)try{const U=JSON.parse(S),M=B(U.status)?U.status:{};for(const[D,F]of Object.entries(M)){const W=B(F)?F:{},j=typeof W.completed=="string"?W.completed:"",G=typeof W.failed=="string"?W.failed:typeof W.error=="string"?W.error:"",ee=typeof W.interrupted=="string"?W.interrupted:"",An=j?"completed":G?"failed":ee?"interrupted":typeof W.status=="string"?W.status:"running";c.has(D)||c.set(D,{agentId:D,nickname:null,agentPath:null,message:"",model:null,agentType:null,timestamp:A,parentToolCallId:""}),_(D,m,A,{status:An,text:j||G||ee||void 0})}}catch{}continue}if(f.type==="custom_tool_call"&&typeof f.call_id=="string"){const p=st(typeof f.name=="string"?f.name:"tool"),b=typeof f.input=="string"?f.input:"",S=f.call_id,U=b?Fs(p,b,S,A,n.cwd):[];if(p!=="apply_patch"){const M={id:S,name:p==="exec_command"?"Bash":p,input:Ae(b),result:null,isError:!1,timestamp:A};o.set(M.id,M),et(m,M,A)}for(const M of U)o.set(M.id,M),et(m,M,A);U.length>0&&l.set(S,{calls:U,direct:p==="apply_patch"});continue}if(f.type==="custom_tool_call_output"&&typeof f.call_id=="string"){const p=f.call_id,{text:b,isError:S,images:U}=It(f.output),M=l.get(p);if(M){const F=M.direct&&S?new Set(M.calls.map(W=>W.id)):js(b,S,M.calls);for(const W of M.calls){const j=o.get(W.id);j&&(j.result=b,j.isError=F.has(j.id),o.delete(j.id))}l.delete(p)}const D=o.get(p);D&&(D.result=b,D.isError=S,U&&(D.resultImages=U),o.delete(p));continue}}}r(m);const w=xs(s);return{turnStartIndices:z,sessionId:n.sessionId,version:n.version,gitBranch:n.gitBranch,cwd:n.cwd,slug:n.slug,name:"",model:n.model,turns:w,stats:e!=null&&e.skipStats?Mt(w.length):vt(w),rawMessages:e!=null&&e.skipStats?[]:t,branchedFrom:n.branchedFrom,agentKind:"codex"}}function fn(t,e){const n=t.split(`
32
+ `).map(a=>a.trim()).filter(Boolean).map(mt).filter(ot),s=te(n),o=s?n.filter(a=>!s(a)):n,{turnStartIndices:i,...l}=dn(o,e);return l}function bo(t,e){const n=t.rawMessages.map(s=>JSON.stringify(s)).join(`
33
+ `);return fn(n?`${n}
34
+ ${e}`:e)}const To=new Set(["FINAL_ANSWER","ERROR","FAILED","INTERRUPTED"]);function Co(t){const e=t.content;return Array.isArray(e)?e.filter(n=>B(n)&&n.type==="input_text"&&typeof n.text=="string").map(n=>n.text).join(`
35
+ `):""}function kt(t){if(typeof t!="string")return null;try{const e=JSON.parse(t);return B(e)?e:null}catch{return null}}function xo(t){var h,C;const e=new Map,n=new Set,s=new Map,o=new Map,i=new Map,l=new Set,a=new Map;function c(_,m,v,P){if(s.has(_))return;n.add(_);const $=e.get(_);$?$.description||($.description=m):e.set(_,{launchedAt:v,description:m,startedAt:P})}function u(_,m){s.has(_)||s.set(_,m),n.delete(_)}for(const[_,m]of t.entries()){const v=B(m.payload)?m.payload:null;if(!v)continue;const P=typeof m.timestamp=="string"?m.timestamp:void 0,$=nn(m);if($){const{agentId:y,agentPath:N,kind:O,eventId:z}=$,L=o.get(N),q=n.has(y)||s.has(y)||L!==void 0||i.has(z);if(O!=="started"&&!q)continue;if(L&&L!==y){const T=e.get(L);e.delete(L);const r=e.get(y);T&&!r?e.set(y,T):T&&r&&!r.description&&(r.description=T.description),n.delete(L)&&c(y,"",_,P);const d=s.get(L);d!==void 0&&u(y,d)}o.set(N,y),O==="interrupted"||O==="completed"?u(y,_):c(y,i.get(z)??"",_,P);continue}if(m.type==="response_item"){if(v.type==="function_call"&&typeof v.call_id=="string"){const y=st(typeof v.name=="string"?v.name:"");if(y==="spawn_agent"){const N=kt(v.arguments);i.set(v.call_id,typeof(N==null?void 0:N.task_name)=="string"?N.task_name:"")}else if(y==="wait_agent")l.add(v.call_id);else if(y==="interrupt_agent"){const N=kt(v.arguments),O=[N==null?void 0:N.agent_id,...Array.isArray(N==null?void 0:N.agent_ids)?N.agent_ids:[]].filter(z=>typeof z=="string");a.set(v.call_id,O)}continue}if(v.type==="function_call_output"&&typeof v.call_id=="string"){const y=v.call_id;if(i.has(y)){const N=kt(v.output),O=typeof(N==null?void 0:N.agent_id)=="string"?N.agent_id:"";if(O){c(O,i.get(y)??"",_,P);const z=typeof(N==null?void 0:N.task_name)=="string"?N.task_name:"";z&&!o.has(z)&&o.set(z,O)}}else if(l.has(y)){const N=kt(v.output),O=B(N==null?void 0:N.status)?N.status:{};for(const[z,L]of Object.entries(O)){const q=B(L)?L:{},T=typeof q.status=="string"?q.status:"";(typeof q.completed=="string"||typeof q.failed=="string"||typeof q.error=="string"||typeof q.interrupted=="string"||T==="completed"||T==="failed"||T==="interrupted")&&u(z,_)}}else if(a.has(y))for(const N of a.get(y)??[])u(N,_);continue}if(v.type==="agent_message"&&typeof v.author=="string"){const N=((C=(h=Co(v).match(/^Message Type:\s*([^\r\n]+)/))==null?void 0:h[1])==null?void 0:C.trim().toUpperCase())??"";if(!To.has(N))continue;u(o.get(v.author)??v.author,_)}}}return[...e.entries()].map(([_,{description:m,startedAt:v,launchedAt:P}])=>({agent:{description:m,startedAt:v},launchedAt:P,endedAt:n.has(_)?void 0:s.get(_)??P}))}function Ao(t){for(let e=t.length-1;e>=0;e--){const n=t[e];if(n.type==="event_msg"){const s=n.payload;switch(s==null?void 0:s.type){case"task_complete":{const o=on(s);return o?{status:"completed",terminalReason:o.reason==="not_signed_in"?"authentication_failed":"turn_failed",failure:o}:Qt(xo(t))??{status:"completed"}}case"task_started":return{status:"processing"};case"agent_message":return{status:"thinking"};case"token_count":continue}}if(n.type==="response_item"){const s=n.payload;if(!s)continue;if(s.type==="function_call")return{status:"tool_use",toolName:s.name?st(s.name):s.name};if(s.type==="message"){if(s.role==="assistant")return{status:"thinking"};if(s.role==="user")return{status:"processing"}}}}return{status:"idle"}}function Io(t,e,n,s){const o=B(t.payload)?{...t.payload}:{},i=typeof o.id=="string"?o.id:"";return o.id=e,o.branchedFrom={sessionId:i,turnIndex:n,at:new Date(s).toISOString()},{record:{...t,payload:o},originalId:i}}function So(t){return dn(t,{skipStats:!0}).turnStartIndices}const wo=/^(?:assistant|auto_mode|auto_mode_switch|background_tasks|canvas|command|custom|elicitation|exit_plan_mode|extensions|external_tool|factory|hook|managed_settings|mcp|model|pending_messages|permission|sampling|session|skill|subagent|system|tool|ui|user_input)\./;function K(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function pn(t){return typeof t.agentId!="string"||t.agentId.length===0}function mn(t){return!K(t)||typeof t.type!="string"||!K(t.data)?!1:t.type==="abort"||t.type==="binary_asset"||t.type==="user.message"||wo.test(t.type)}function gn(t){try{const e=JSON.parse(t);return mn(e)?e:null}catch{return null}}function Eo(t){return t.split(`
36
+ `).map(e=>e.trim()).filter(Boolean).map(gn).filter(e=>e!==null)}function x(...t){return t.find(e=>typeof e=="string")??""}function Z(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function lt(t){return typeof t.timestamp=="string"?t.timestamp:""}function Y(t,e){var n,s;return typeof t.id=="string"&&t.id?t.id:((s=(n=globalThis.crypto)==null?void 0:n.randomUUID)==null?void 0:s.call(n))??`${e}-${Math.random().toString(36).slice(2,10)}`}function Ie(t){const e=Y(t,"copilot-turn"),n=x(t.data.turnId);return n?`${n}@${e}`:e}function Ot(t,e){if(!K(t))return;const n=x(t.cwd),s=x(t.branch);n&&(e.cwd=n),s&&(e.gitBranch=s)}function hn(t){const e={sessionId:"",version:"",gitBranch:"",cwd:"",model:"",slug:"",name:"",firstUserMessage:"",lastUserMessage:"",timestamp:"",lastTimestamp:"",turnCount:0,isSubagent:!1,parentSessionId:null};for(const n of t){if(!pn(n))continue;const{data:s}=n,o=lt(n);if(o&&(e.lastTimestamp=o),n.type==="session.start"){e.sessionId||(e.sessionId=x(s.sessionId)),e.version||(e.version=x(s.copilotVersion)||(typeof s.version=="number"?String(s.version):x(s.version))),Ot(s.context,e),e.model=x(s.selectedModel)||e.model;continue}if(n.type==="session.resume"){Ot(s.context,e),e.model=x(s.selectedModel)||e.model;continue}if(n.type==="session.context_changed"){Ot(s,e);continue}if(n.type==="session.auto_mode_resolved"){e.model=x(s.chosenModel)||e.model;continue}if(n.type==="session.model_change"){e.model=x(s.newModel)||e.model;continue}if(n.type==="session.title_changed"){e.name=x(s.title)||e.name;continue}if(n.type==="session.shutdown"){e.model=x(s.currentModel)||e.model;continue}if((n.type==="assistant.turn_start"||n.type==="assistant.turn_end"||n.type==="assistant.message"||n.type==="assistant.usage"||n.type==="tool.execution_start"||n.type==="tool.execution_complete")&&(e.model=x(s.model)||e.model),n.type!=="user.message")continue;e.turnCount++,e.timestamp||(e.timestamp=o);const i=tn(x(s.content)).trim();i&&(e.firstUserMessage||(e.firstUserMessage=i),e.lastUserMessage=i)}return e.lastTimestamp||(e.lastTimestamp=e.timestamp),e}function Mo(t){for(const e of t.split(`
37
+ `)){const n=e.trim();if(n)try{const s=JSON.parse(n);if(mn(s))return!0}catch{}}return!1}function vo(t){var e;return zo((e=t[0])==null?void 0:e.type)}function No(t){const e=t.map(n=>gn(n.trim())).filter(n=>n!==null);return hn(e)}function Bt(t){if(typeof t=="string")return t;if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}function Se(t){return typeof t=="string"?t:Array.isArray(t)?t.flatMap(e=>{const n=typeof e=="string"?e:K(e)?x(e.text,e.content):"";return n?[n]:[]}).join(`
38
+ `):""}function Ro(t){const e=new Map;for(const n of t){if(n.type!=="session.binary_asset"&&n.type!=="binary_asset")continue;const s=x(n.data.assetId),o=x(n.data.data),i=x(n.data.mimeType);s&&o&&i&&e.set(s,{data:o,mimeType:i})}return e}function Po(t,e){if(!K(t))return null;const n=e.get(x(t.assetId)),s=x(t.mimeType,n==null?void 0:n.mimeType).toLowerCase(),o=x(t.data,n==null?void 0:n.data);return!s.startsWith("image/")||!o?null:{type:"image",source:{type:"base64",media_type:s,data:o}}}function yn(t,e){if(!Array.isArray(t))return[];const n=[],s=new Set;for(const o of t){const i=Po(o,e);if(!i)continue;const l=`${i.source.media_type}:${i.source.data}`;s.has(l)||(s.add(l),n.push(i))}return n}function $o(t,e){const n=x(t.content),s=yn(t.attachments,e);return s.length===0?n:[...s,...n?[{type:"text",text:n}]:[]]}function Uo(t,e){return K(t.result)?yn([...Array.isArray(t.result.contents)?t.result.contents:[],...Array.isArray(t.result.binaryResultsForLlm)?t.result.binaryResultsForLlm:[]],e):[]}function Kt(t,e=!1){const n=Z(t.cacheWriteTokens),s=Z(t.cacheReadTokens),o=Z(t.inputTokens),i={input_tokens:e?Math.max(0,o-n-s):o,output_tokens:Z(t.outputTokens),cache_creation_input_tokens:n,cache_read_input_tokens:s},l=Z(t.reasoningTokens);return l&&(i.output_tokens_details={thinking_tokens:l}),i.input_tokens===0&&i.output_tokens===0&&i.cache_creation_input_tokens===0&&i.cache_read_input_tokens===0&&l===0?null:i}function Oo(t){if(!K(t.modelMetrics))return null;let e=null;for(const n of Object.values(t.modelMetrics)){if(!K(n)||!K(n.usage))continue;const s=Kt(n.usage,!0);s&&(e=nt(e,s))}return e}function Bo(t){if(typeof t=="string")return{label:t};if(!K(t))return null;const e=x(t.label,t.title,t.value,t.name);if(!e)return null;const n=x(t.description);return n?{label:e,description:n}:{label:e}}function Do(t){return Array.isArray(t)?t.map(Bo).filter(e=>e!==null):[]}function Fo(t){if(!K(t))return null;const e=x(t.question,t.prompt,t.text,t.message);if(!e)return null;const n=x(t.header,t.title),s=typeof t.multiSelect=="boolean"?t.multiSelect:typeof t.multi_select=="boolean"?t.multi_select:void 0;return{question:e,...n?{header:n}:{},options:Do(t.options??t.choices),...s===void 0?{}:{multiSelect:s}}}function jo(t){const n=(Array.isArray(t.questions)?t.questions:[t]).map(Fo).filter(s=>s!==null);return n.length>0?{...t,questions:n}:t}function ct(t){switch(t.toLowerCase().replace(/-/g,"_")){case"ask_user":return"AskUserQuestion";case"bash":case"powershell":case"shell":return"Bash";case"create":return"Write";case"edit":return"Edit";default:return t}}function wt(t,e){const n=K(e)?e:e===void 0?{}:{value:e};return t==="AskUserQuestion"?jo(n):t==="Edit"?{...n,file_path:x(n.file_path,n.path),old_string:x(n.old_string,n.old_str),new_string:x(n.new_string,n.new_str)}:t==="Write"?{...n,file_path:x(n.file_path,n.path),content:x(n.content,n.file_text)}:t==="Bash"&&typeof n.command!="string"&&typeof n.cmd=="string"?{...n,command:n.cmd}:n}function Lo(t){const e=t.error;if(typeof e=="string")return e;if(K(e)){const s=x(e.message,e.code);if(s)return s}const n=t.result;if(typeof n=="string")return n;if(!K(n))return n===void 0?"":Bt(n);if(typeof n.detailedContent=="string")return n.detailedContent;if(typeof n.content=="string")return n.content;if(Array.isArray(n.contents)){const s=n.contents.flatMap(o=>{const i=typeof o=="string"?o:K(o)?x(o.text,o.content,o.output):"";return i?[i]:[]}).join(`
39
+ `);if(s)return s}return n.structuredContent!==void 0?Bt(n.structuredContent):Bt(n)}function we(t,e,n,s){if(!e||t.thinking.some(l=>l.thinking===e))return;const o={type:"thinking",thinking:e,signature:s};t.thinking.push(o);const i=t.contentBlocks[t.contentBlocks.length-1];if((i==null?void 0:i.kind)==="thinking"){i.blocks.push(o);return}t.contentBlocks.push({kind:"thinking",blocks:[o],timestamp:n})}function bt(t,e,n){t.toolCalls.push(e);const s=t.contentBlocks[t.contentBlocks.length-1];if((s==null?void 0:s.kind)==="tool_calls"){s.toolCalls.push(e);return}t.contentBlocks.push({kind:"tool_calls",toolCalls:[e],timestamp:n})}function ut(t,e,n,s){return{id:t,name:e,input:n,result:null,isError:!1,timestamp:s}}function Ee(t,e,n){if(!Array.isArray(t))return[];const s=[];for(const o of t){if(!K(o))continue;const i=x(o.toolCallId),l=x(o.name);if(!i||!l||n(i))continue;const a=ct(l);s.push(ut(i,a,wt(a,o.arguments),e))}return s}function Me(t,e,n,s){t.name=e,t.input=wt(e,n),t.timestamp=s||t.timestamp}function ve(t,e,n){t.result=Lo(e);const s=Uo(e,n);s.length>0&&(t.resultImages=s),t.isError=e.success===!1||e.error!==void 0&&e.error!==null}function Ne(t,e,n,s,o,i){return{id:t,userMessage:n,contentBlocks:[],thinking:[],assistantText:[],toolCalls:[],subAgentActivity:[],timestamp:e,durationMs:null,tokenUsage:null,model:s,...o?{effort:o}:{},...i?{isFragment:!0}:{}}}function Wo(t){return t.userMessage!==null||t.assistantText.length>0||t.thinking.length>0||t.toolCalls.length>0||t.subAgentActivity.length>0}function _n(t,e){const n=Eo(t),s=hn(n),o=Ro(n),i=[],l=new Map,a=new Map,c=new Map,u=new WeakMap,h=new WeakMap;let C=null,_=null,m,v=!1,P=!1,$=null;function y(T,r){r&&u.set(T,r)}function N(T){return C||(C=Ne(Ie(T),lt(T),null,_,m,!0)),C}function O(){C&&(Wo(C)&&i.push(C),C=null)}function z(T){var f;const r=typeof T.agentId=="string"?T.agentId:"";if(!r)return null;const d=a.get(r);if(d)return d.message;const k=T.data,g=x(k.toolCallId),w=g?((f=l.get(g))==null?void 0:f.turn)??C:C;if(!w)return null;const E=x(k.executionMode),I={agentId:r,...g?{parentToolUseId:g}:{},agentName:x(k.agentDisplayName,k.agentName)||null,subagentType:x(k.agentType,k.agentName)||null,type:"assistant",content:null,toolCalls:[],thinking:[],text:[],timestamp:lt(T),tokenUsage:null,model:x(k.model)||null,isBackground:E==="background",...x(k.description)?{prompt:x(k.description)}:{},status:"running"};return w.subAgentActivity.push(I),w.contentBlocks.push({kind:I.isBackground?"background_agent":"sub_agent",messages:[I],timestamp:I.timestamp}),a.set(r,{message:I,turn:w}),I}function L(T){if(pn(T))return!1;const r=z(T);if(!r)return!0;const{data:d}=T,k=lt(T);if(T.type==="subagent.started"||T.type==="subagent.configured")return r.parentToolUseId||(r.parentToolUseId=x(d.toolCallId)||void 0),r.agentName=x(d.agentDisplayName,d.agentName)||r.agentName,r.subagentType=x(d.agentType,d.agentName)||r.subagentType,r.model=x(d.model)||r.model,r.prompt||(r.prompt=x(d.description)||void 0),r.isBackground||(r.isBackground=x(d.executionMode)==="background"),r.status="running",!0;if(T.type==="subagent.completed"||T.type==="subagent.failed"){r.agentName=x(d.agentDisplayName,d.agentName)||r.agentName,r.subagentType=x(d.agentType,d.agentName)||r.subagentType,r.model=x(d.model)||r.model,r.durationMs=Z(d.durationMs)||r.durationMs,r.toolUseCount=Z(d.totalToolCalls)||r.toolUseCount,r.status=T.type==="subagent.completed"?"completed":"failed";const g=x(d.error,d.message);return g&&!r.text.includes(g)&&r.text.push(g),!0}if(T.type==="user.message")return r.prompt||(r.prompt=x(d.content)||void 0),!0;if(T.type==="assistant.reasoning"){const g=x(d.content);return g&&!r.thinking.includes(g)&&r.thinking.push(g),!0}if(T.type==="assistant.message"){r.model=x(d.model)||r.model;const g=x(d.reasoningText);g&&!r.thinking.includes(g)&&r.thinking.push(g);const w=Se(d.content);w&&!r.text.includes(w)&&r.text.push(w);for(const E of Ee(d.toolRequests,k,I=>c.has(I)))r.toolCalls.push(E),c.set(E.id,{call:E,message:r});return!0}if(T.type==="assistant.usage"){r.model=x(d.model)||r.model;const g=Kt(d);return g&&(r.tokenUsage=nt(r.tokenUsage,g)),!0}if(T.type==="tool.execution_start"){const g=x(d.toolCallId)||Y(T,"copilot-agent-tool"),w=x(d.toolName)||"Tool",E=ct(w),I=c.get(g);if(I)Me(I.call,E,d.arguments,k);else{const f=ut(g,E,wt(E,d.arguments),k);r.toolCalls.push(f),c.set(g,{call:f,message:r})}return!0}if(T.type==="tool.execution_complete"){const g=x(d.toolCallId)||Y(T,"copilot-agent-tool");let w=c.get(g);if(!w){const E=x(d.toolName)||"Tool",I=ct(E),f=ut(g,I,{},k);r.toolCalls.push(f),w={call:f,message:r}}return ve(w.call,d,o),c.delete(g),!0}return!0}for(const T of n){if(L(T))continue;const{data:r}=T,d=lt(T);if(T.type==="session.start"||T.type==="session.resume"){_=x(r.selectedModel)||_,m=x(r.reasoningEffort)||m;continue}if(T.type==="session.auto_mode_resolved"){_=x(r.chosenModel)||_,C&&(C.model=_);continue}if(T.type==="session.model_change"){_=x(r.newModel)||_;const k=r.reasoningEffort;typeof k=="string"&&(m=k),C&&(C.model=_,m&&(C.effort=m));continue}if(T.type==="session.shutdown"){_=x(r.currentModel)||_,C&&!C.model&&(C.model=_),$=Oo(r)??$;const k=Z(r.totalApiDurationMs);C&&!P&&k&&h.set(C,k);continue}if(T.type==="user.message"){O(),C=Ne(Ie(T),d,$o(r,o),_,m,!1),y(C,d);continue}if(T.type==="assistant.turn_start"){_=x(r.model)||_;const k=N(T);k.model=_,m&&(k.effort=m),y(k,d);continue}if(T.type==="assistant.reasoning"){const k=N(T);we(k,x(r.content),d,x(r.reasoningId)||Y(T,"copilot-thinking")),y(k,d);continue}if(T.type==="assistant.message"){_=x(r.model)||_;const k=N(T);k.model=_,m&&(k.effort=m),we(k,x(r.reasoningText),d,Y(T,"copilot-thinking")),Lt(k,Se(r.content),d);for(const g of Ee(r.toolRequests,d,w=>l.has(w)))bt(k,g,d),l.set(g.id,{call:g,turn:k});y(k,d);continue}if(T.type==="assistant.usage"){_=x(r.model)||_,m=x(r.reasoningEffort)||m;const k=Kt(r),g=Z(r.duration);k&&(v=!0),g&&(P=!0);const w=N(T);w.model=_,m&&(w.effort=m),k&&(w.tokenUsage=nt(w.tokenUsage,k)),g&&h.set(w,(h.get(w)??0)+g),y(w,d);continue}if(T.type==="tool.execution_start"){_=x(r.model)||_;const k=N(T);k.model=_;const g=x(r.toolCallId)||Y(T,"copilot-tool"),w=x(r.toolName)||"Tool",E=ct(w),I=l.get(g);if(I)Me(I.call,E,r.arguments,d);else{const f=ut(g,E,wt(E,r.arguments),d);bt(k,f,d),l.set(g,{call:f,turn:k})}y(k,d);continue}if(T.type==="tool.execution_complete"){_=x(r.model)||_;const k=x(r.toolCallId)||Y(T,"copilot-tool");let g=l.get(k);if(!g){const w=N(T),E=x(r.toolName)||"Tool",I=ct(E),f=ut(k,I,{},d);bt(w,f,d),g={call:f,turn:w}}ve(g.call,r,o),l.delete(k),y(g.turn,d);continue}if(T.type==="session.error"){const k=N(T),w={errorType:x(r.errorType)||"unknown"};typeof r.statusCode=="number"&&(w.statusCode=r.statusCode),typeof r.errorCode=="string"&&(w.errorCode=r.errorCode),bt(k,{id:Y(T,"copilot-error"),name:"Error",input:w,result:x(r.message)||"Copilot session error",isError:!0,timestamp:d},d),y(k,d);continue}(T.type==="assistant.turn_end"||T.type==="assistant.idle"||T.type==="session.idle")&&C&&y(C,d)}if(O(),!v&&$&&i.length===1&&(i[0].tokenUsage=nt(i[0].tokenUsage,$)),s.model)for(const T of i)T.model||(T.model=s.model);for(const T of i){const r=u.get(T),d=Date.parse(T.timestamp),k=r?Date.parse(r):Number.NaN;if(Number.isFinite(d)&&Number.isFinite(k)&&k>=d)T.durationMs=k-d;else{const g=h.get(T)??0;g&&(T.durationMs=g)}}const q=e!=null&&e.skipStats?Mt(i.length):vt(i);return!(e!=null&&e.skipStats)&&!v&&$&&i.length>1&&(q.totalInputTokens=$.input_tokens,q.totalOutputTokens=$.output_tokens,q.totalCacheCreationTokens=$.cache_creation_input_tokens??0,q.totalCacheReadTokens=$.cache_read_input_tokens??0),{sessionId:s.sessionId,version:s.version,gitBranch:s.gitBranch,cwd:s.cwd,slug:s.slug,name:s.name,model:s.model,turns:i,stats:q,rawMessages:e!=null&&e.skipStats?[]:n,agentKind:"copilot"}}function qo(t,e){const n=t.rawMessages.map(s=>JSON.stringify(s)).join(`
40
+ `);return _n(n?`${n}
41
+ ${e}`:e)}function zo(t){return typeof t=="string"&&(t==="abort"||t==="binary_asset"||t==="user.message"||t.startsWith("assistant.")||t.startsWith("permission.")||t.startsWith("session.")||t.startsWith("subagent.")||t.startsWith("tool.")||t.startsWith("user_input."))}function Ko(t){const e=new Map;for(const[i,l]of t.entries()){const a=typeof l.agentId=="string"?l.agentId:"";if(!a&&(l.type==="abort"||l.type==="session.shutdown"||l.type==="session.error")){e.clear();continue}if(!a||!l.type.startsWith("subagent."))continue;const c=K(l.data)?l.data:{},u=e.get(a);if(l.type==="subagent.completed"||l.type==="subagent.failed"){u&&(u.endedAt??(u.endedAt=i));continue}if(l.type==="subagent.started"||l.type==="subagent.configured"){const h=[c.agentDisplayName,c.description,c.agentName].find(C=>typeof C=="string")??"";if(!u||u.endedAt!==void 0){const C=typeof l.timestamp=="string"?l.timestamp:void 0;e.set(a,{agent:{description:h,startedAt:C},launchedAt:i})}else h&&(u.agent.description=h)}}const n=Qt([...e.values()]);if(n)return n;let s=!1;const o=new Set;for(let i=t.length-1;i>=0;i--){const l=t[i];if(typeof l.agentId=="string"&&l.agentId)continue;const a=K(l.data)?l.data:{};switch(l.type){case"abort":case"session.shutdown":return{status:"completed"};case"assistant.turn_end":{for(let c=i-1;c>=0;c--){const u=t[c];if(typeof u.agentId=="string"&&u.agentId)continue;if(u.type==="user.message")break;if(u.type==="abort")return{status:"completed"};if(u.type!=="assistant.message")continue;const h=K(u.data)?u.data:{};return Array.isArray(h.toolRequests)&&h.toolRequests.length>0?{status:"processing"}:{status:"completed"}}return{status:"processing"}}case"session.error":{const c=xt(typeof a.message=="string"&&a.message?a.message:"Copilot session error",typeof a.statusCode=="number"?a.statusCode:void 0);return{status:"completed",terminalReason:c.reason==="not_signed_in"?"authentication_failed":c.message,failure:c}}case"assistant.idle":case"session.idle":return{status:s?"completed":"idle"};case"permission.completed":{const c=typeof a.requestId=="string"?a.requestId:"";c&&o.add(c);continue}case"permission.requested":{const c=typeof a.requestId=="string"?a.requestId:"";if(c&&o.has(c))continue;return{status:"deferred"}}case"user_input.requested":return{status:"tool_use",toolName:"AskUserQuestion"};case"tool.execution_start":return o.size>0?{status:"thinking"}:{status:"tool_use",toolName:typeof a.toolName=="string"?st(a.toolName):typeof a.name=="string"?st(a.name):void 0};case"tool.execution_complete":return{status:"thinking"};case"assistant.turn_start":return{status:"processing"};case"assistant.message":case"assistant.message_delta":case"assistant.reasoning":case"assistant.reasoning_delta":return{status:"thinking"};case"user.message":return s=!0,{status:"processing"};case"session.start":case"session.resume":return{status:s?"processing":"idle"}}}return{status:"idle"}}function Ho(){throw new Error("Copilot sessions branch through the CLI's fork API, not by copying the transcript")}function Jo(t){const e=[];for(let n=0;n<t.length;n++){const s=t[n];if(s.type!=="user.message"||typeof s.agentId=="string")continue;const o=s.data;!o||typeof o!="object"||Array.isArray(o)||typeof s.id!="string"||!s.id||e.push(n)}return e}function Vo(t,e){if(t.type!=="tool.execution_complete"||!K(t.data))return!1;const n=t.data;if(typeof n.result=="string")return X(n,"result",e);if(!K(n.result))return!1;const s=n.result;let o=X(s,"detailedContent",e);if(o=X(s,"content",e)||o,Array.isArray(s.contents)){const i=a=>(typeof a=="string"?a:K(a)?x(a.text,a.content,a.output):"")||void 0,l=Xt(s.contents,i,`
42
+ `,(a,c)=>typeof a=="string"?c:{...a,text:c},e);l&&(s.contents=l,o=!0)}return o}const Go=new Set(["function_call_output","custom_tool_call_output"]),Qo=["aggregated_output","formatted_output","stdout","stderr"];function Re(t){var n;const e=It(t);return JSON.stringify([e.isError,((n=e.images)==null?void 0:n.length)??0])}function Zo(t,e){const n=J(t.source)?{...t.source}:null;if(n)return X(n,"data",e,"image")?{...t,source:n}:t;if(typeof t.image_url!="string")return t;const s=/^(data:image\/[^;,]+;base64,)(.+)$/is.exec(t.image_url);if(!s)return t;const o=e(s[2],"image");return o===s[2]?t:{...t,image_url:s[1]+o}}function Xo(t,e){const n=Xt(t,i=>J(i)&&typeof i.text=="string"?i.text:void 0,"",(i,l)=>({...i,text:l}),e)??t;let s=n!==t;const o=n.map(i=>{if(!J(i)||typeof i.text=="string")return i;const l=Zo(i,e);return l!==i&&(s=!0),l});return s?o:t}function kn(t,e){if(Array.isArray(t))return Xo(t,e);if(typeof t!="string")return t;let n=null;try{n=JSON.parse(t)}catch{}if(J(n)&&("output"in n||"content"in n)){const s=n.output!==void 0&&n.output!==null?"output":"content",o=n[s],i=typeof o=="string"?e(o,"text"):Array.isArray(o)?kn(o,e):o;return i===o?t:JSON.stringify({...n,[s]:i})}return e(t,"text")}function Yo(t,e){const n=t.output,s=kn(n,e);return s===n||Re(s)!==Re(n)?!1:(t.output=s,!0)}function ti(t,e){const n=J(t.payload)?t.payload:null;if(!n)return!1;if(t.type==="response_item"&&Go.has(String(n.type)))return Yo(n,e);if(t.type==="event_msg"&&n.type==="exec_command_end"){let s=!1;for(const o of Qo)s=X(n,o,e)||s;return s}return!1}const bn=Ft[Ft.length-1],Tn=()=>!1,ei={kind:"codex",descriptor:gt("codex"),detectsText:yo,detectsRecords:_o,parse:fn,append:bo,metadataFromLines:ko,status:Ao,isNoiseLine:Tn,pageHeaderLine:Ys,brandBranch:Io,turnBoundaries:So,projectResults:ti},ni={kind:"copilot",descriptor:gt("copilot"),detectsText:Mo,detectsRecords:vo,parse:_n,append:qo,metadataFromLines:No,status:Ko,isNoiseLine:Tn,brandBranch:Ho,turnBoundaries:Jo,projectResults:Vo},Pe={kind:"claude",descriptor:gt("claude"),detectsText:ye,detectsRecords:ye,parse:Ve,append:Ge,metadataFromLines:as,status:ms,isNoiseLine:ze,brandBranch:gs,turnBoundaries:hs,projectResults:_s},Dt=Object.freeze({acp:{...Pe,kind:"acp",descriptor:gt("acp"),detectsText:t=>{var e;return((e=t.split(`
43
+ `,1)[0])==null?void 0:e.includes('"type":"acp_session"'))??!1},detectsRecords:t=>{var e;return((e=t[0])==null?void 0:e.type)==="acp_session"},parse:(t,e)=>({...Ve(t,e),agentKind:"acp"}),append:(t,e)=>({...Ge(t,e),agentKind:"acp"})},claude:Pe,codex:ei,copilot:ni});function Cn(t){for(const e of Ft)if(t(Dt[e]))return Dt[e];return Dt[bn]}function xn(t){return Cn(e=>e.detectsText(t))}function si(t){return Cn(e=>e.detectsRecords(t))}function oi(t,e){return xn(t).parse(t,e)}function ii(t,e){const n=si(t.rawMessages),o=(n.kind===bn?xn(e):n).append(t,e);return t.instanceId?In(o,t.instanceId):o}const ri=4,tt=new Map;function ai(t,e){if(t)for(tt.delete(t.handle),tt.set(t.handle,{version:t.version,session:e});tt.size>ri;)tt.delete(tt.keys().next().value)}self.onmessage=t=>{const e=t.data;try{let n;if(e.type==="parse")n=oi(e.text);else{let s;if("base"in e){const o=tt.get(e.base.handle);(o==null?void 0:o.version)===e.base.version&&(s=o.session,tt.delete(e.base.handle))}else s=e.existing;if(!s){self.postMessage({type:"missing",id:e.id});return}n=ii(s,e.newText),ai(e.keep,n)}is(n),self.postMessage({type:"result",id:e.id,session:n})}catch(n){self.postMessage({type:"error",id:e.id,error:n instanceof Error?n.message:String(n)})}};
@@ -1 +1 @@
1
- import{c,j as n}from"./vendor-react-gGw_S5I_.js";import{c as u}from"./index-Bg4A-xl7.js";import{dA as p,dB as f}from"./vendor-ui-Dc_kJXxz.js";function g(l){const e=c.c(11);let a,t,s;e[0]!==l?({className:a,size:s,...t}=l,e[0]=l,e[1]=a,e[2]=t,e[3]=s):(a=e[1],t=e[2],s=e[3]);const o=s===void 0?"default":s;let i;e[4]!==a?(i=u("peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none group-has-[:focus-visible]/field-label:border-transparent group-has-[:focus-visible]/field-label:ring-0 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input data-disabled:cursor-not-allowed data-disabled:opacity-50",a),e[4]=a,e[5]=i):i=e[5];let r;e[6]===Symbol.for("react.memo_cache_sentinel")?(r=n.jsx(f,{"data-slot":"switch-thumb",className:"pointer-events-none block rounded-full bg-foreground ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0"}),e[6]=r):r=e[6];let d;return e[7]!==t||e[8]!==o||e[9]!==i?(d=n.jsx(p,{"data-slot":"switch","data-size":o,className:i,...t,children:r}),e[7]=t,e[8]=o,e[9]=i,e[10]=d):d=e[10],d}export{g as S};
1
+ import{c,j as n}from"./vendor-react-gGw_S5I_.js";import{c as u}from"./index-Dv2TZ38C.js";import{dG as p,dH as f}from"./vendor-ui-ClPj6-Gu.js";function g(l){const e=c.c(11);let a,t,s;e[0]!==l?({className:a,size:s,...t}=l,e[0]=l,e[1]=a,e[2]=t,e[3]=s):(a=e[1],t=e[2],s=e[3]);const o=s===void 0?"default":s;let i;e[4]!==a?(i=u("peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none group-has-[:focus-visible]/field-label:border-transparent group-has-[:focus-visible]/field-label:ring-0 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input data-disabled:cursor-not-allowed data-disabled:opacity-50",a),e[4]=a,e[5]=i):i=e[5];let r;e[6]===Symbol.for("react.memo_cache_sentinel")?(r=n.jsx(f,{"data-slot":"switch-thumb",className:"pointer-events-none block rounded-full bg-foreground ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0"}),e[6]=r):r=e[6];let d;return e[7]!==t||e[8]!==o||e[9]!==i?(d=n.jsx(p,{"data-slot":"switch","data-size":o,className:i,...t,children:r}),e[7]=t,e[8]=o,e[9]=i,e[10]=d):d=e[10],d}export{g as S};