@pasko70/pibo 1.4.6 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/apps/chat/chat-settings-routes.js +24 -1
  2. package/dist/apps/chat/data/project-service.js +13 -3
  3. package/dist/apps/chat/telemetry-retention-service.js +69 -0
  4. package/dist/apps/chat/web-app.js +18 -8
  5. package/dist/apps/chat-ui/assets/{dist-DWA7BIr3.js → dist-B9sopUkn.js} +1 -1
  6. package/dist/apps/chat-ui/assets/{dist-Bns-O5iY.js → dist-BDQhMN_4.js} +1 -1
  7. package/dist/apps/chat-ui/assets/{dist-CVcI9eYD.js → dist-BEStK5um.js} +1 -1
  8. package/dist/apps/chat-ui/assets/{dist-B6kzRv2_.js → dist-BiBY_4CK.js} +1 -1
  9. package/dist/apps/chat-ui/assets/{dist-DvPgMX-r.js → dist-C2OyzisT.js} +1 -1
  10. package/dist/apps/chat-ui/assets/{dist-D9K0kHT0.js → dist-C9stINOY.js} +1 -1
  11. package/dist/apps/chat-ui/assets/{dist-DqaKPP5Y.js → dist-CQKLsKIo.js} +1 -1
  12. package/dist/apps/chat-ui/assets/{dist-D4CEl91a.js → dist-CtSZyFkJ.js} +1 -1
  13. package/dist/apps/chat-ui/assets/{dist-Dj3uUYqF.js → dist-DPLEwPsG.js} +1 -1
  14. package/dist/apps/chat-ui/assets/{dist-CqkKCn6l.js → dist-DRTq4wrN.js} +1 -1
  15. package/dist/apps/chat-ui/assets/{dist-DuM9PL5k.js → dist-F2W_jRom.js} +1 -1
  16. package/dist/apps/chat-ui/assets/index-D_60RTKn.css +1 -0
  17. package/dist/apps/chat-ui/assets/index-iaNLOwJ-.js +157 -0
  18. package/dist/apps/chat-ui/index.html +2 -2
  19. package/dist/apps/chat-vscode-web/assets/{index-CjOC7zYy.js → index-lA76A7Pc.js} +1 -1
  20. package/dist/apps/chat-vscode-web/index.html +1 -1
  21. package/dist/apps/vscode-artifacts/latest.vsix +0 -0
  22. package/dist/apps/vscode-artifacts/{pibo-vscode-ext-1.4.6.vsix → pibo-vscode-ext-1.5.0.vsix} +0 -0
  23. package/dist/core/runtime-telemetry.js +11 -3
  24. package/dist/core/session-router.js +7 -1
  25. package/dist/core/telemetry-retention-settings.js +34 -0
  26. package/dist/core/user-settings.js +11 -0
  27. package/dist/data/telemetry.js +11 -0
  28. package/package.json +1 -1
  29. package/dist/apps/chat-ui/assets/index-B-qaya1G.css +0 -1
  30. package/dist/apps/chat-ui/assets/index-Baxj7Erc.js +0 -166
@@ -38,4 +38,4 @@ Error generating stack: `+e.message+`
38
38
  `),r.hasAttribute(`data-start`)||r.setAttribute(`data-start`,String(o+1))}f.textContent=e,n.highlightElement(f)},function(e){r.setAttribute(a,c),f.textContent=e})}}),n.plugins.fileHighlight={highlight:function(e){for(var t=(e||document).querySelectorAll(l),r=0,i;i=t[r++];)n.highlightElement(i)}};var f=!1;n.fileHighlight=function(){f||=(console.warn("Prism.fileHighlight is deprecated. Use `Prism.plugins.fileHighlight.highlight` instead."),!0),n.plugins.fileHighlight.highlight.apply(this,arguments)}})()}))(),1);function lv(e){return typeof e==`object`&&!!e&&`languages`in e}var uv=globalThis,dv=lv(uv.Prism)?uv.Prism:cv.default;uv.Prism=dv,typeof window<`u`&&(window.Prism=dv);var fv;function pv(){if(fv!==void 0)return fv;let e=kv();if(!e)return fv=!1,fv;try{let t=new URL(e.location.href).searchParams.get(`debugStreaming`);fv=t===null?e.localStorage.getItem(`pibo.chat.debugStreaming`)===`1`:t!==`0`&&t!==`false`}catch{fv=!1}return fv}function mv(e,t){Tv(e,e=>{e.liveOpenCount+=1,e.lastReadyState=t})}function hv(e,t){Tv(e,e=>{e.liveErrorCount+=1,e.lastReadyState=t})}function gv(e,t,n,r){Tv(e,e=>{let i=jv();e.eventCount+=1,e.eventTypeCounts[t.type]=(e.eventTypeCounts[t.type]??0)+1,e.lastEventAt=i,e.firstEventAt??=i,e.lastReadyState=r;let a=n||t.streamFrameId;if(a){e.lastEventId=a;let t=wv(a);t===`durable`?e.lastDurableCursor=a:t===`transient`&&(e.lastTransientLiveId=a)}t.type===`TEXT_MESSAGE_CONTENT`&&typeof t.delta==`string`?(e.firstTextDeltaAt??=i,e.textDeltaCount+=1,e.textDeltaBytes+=Av(t.delta)):t.type===`REASONING_MESSAGE_CONTENT`&&typeof t.delta==`string`&&(e.firstReasoningDeltaAt??=i,e.reasoningDeltaCount+=1,e.reasoningDeltaBytes+=Av(t.delta))})}function _v(e,t,n,r){Tv(e,e=>{if(e.firstEnqueueAt??=jv(),e.enqueueCount+=1,r&&(e.enqueueFlushImmediateCount+=1),e.pendingEventCount=n,t.streamFrameId){let n=wv(t.streamFrameId);n===`durable`?e.lastDurableCursor=t.streamFrameId:n===`transient`&&(e.lastTransientLiveId=t.streamFrameId)}})}function vv(e,t,n){Tv(e,e=>{let r=jv();e.firstFlushAt??=r,e.firstOverlayUpdateAt??=r,e.flushCount+=1,e.flushedEventCount+=t,e.pendingEventCount=0,e.overlayUpdateCount+=1,e.overlayEventCount=n,e.lastFlushAt=r})}function yv(e,t){Tv(e,e=>{let n=Mv(t);e.liveTraceComputeCount+=1,e.liveTraceComputeDurationMsLast=n,e.liveTraceComputeDurationMsTotal+=n,e.liveTraceComputeDurationMsMax=Math.max(e.liveTraceComputeDurationMsMax??0,n)})}function bv(e,t){Ev(n=>{let r=Mv(t);n.markdownRenderCount+=1,n.markdownRenderDurationMsLast=r,n.markdownRenderDurationMsTotal+=r,n.markdownRenderDurationMsMax=Math.max(n.markdownRenderDurationMsMax??0,r),e===`plain`?(n.markdownRenderPlainCount+=1,n.markdownRenderPlainDurationMsTotal+=r,n.markdownRenderPlainDurationMsMax=Math.max(n.markdownRenderPlainDurationMsMax??0,r)):e===`gfm-fast`?(n.markdownRenderGfmFastCount+=1,n.markdownRenderGfmFastDurationMsTotal+=r,n.markdownRenderGfmFastDurationMsMax=Math.max(n.markdownRenderGfmFastDurationMsMax??0,r)):(n.markdownRenderFullCount+=1,n.markdownRenderFullDurationMsTotal+=r,n.markdownRenderFullDurationMsMax=Math.max(n.markdownRenderFullDurationMsMax??0,r),e===`gfm`?(n.markdownRenderGfmCount+=1,n.markdownRenderGfmDurationMsTotal+=r,n.markdownRenderGfmDurationMsMax=Math.max(n.markdownRenderGfmDurationMsMax??0,r)):(n.markdownRenderCommonMarkCount+=1,n.markdownRenderCommonMarkDurationMsTotal+=r,n.markdownRenderCommonMarkDurationMsMax=Math.max(n.markdownRenderCommonMarkDurationMsMax??0,r)))})}function xv(e,t){Tv(e,e=>{e.traceRefreshScheduledCount+=1,e.lastTraceRefreshScheduledAt=jv(),e.lastTraceRefreshDelayMs=t})}function Sv(e,t){Tv(e,e=>{t.traceBaseUpdated&&(e.traceBaseUpdateCount+=1),e.overlayEventCount=t.overlayEventCount,t.traceBaseOutputLength!==void 0&&(e.traceBaseOutputLength=t.traceBaseOutputLength),t.currentOutputLength!==void 0&&(e.currentOutputLength=t.currentOutputLength)})}function Cv(e){let t=kv();if(!t?.__piboStreamingBenchmarkShouldDropOverlayEvent)return!1;try{return!!t.__piboStreamingBenchmarkShouldDropOverlayEvent(e)}catch{return!1}}function wv(e){return e?/^live:\d+$/.test(e)?`transient`:/^\d+:\d+$/.test(e)?`durable`:`other`:`missing`}function Tv(e,t){Ev(n=>{n.sessionIds.includes(e)||n.sessionIds.push(e),n.selectedPiboSessionId=e,t(n)})}function Ev(e){let t=Dv();t&&(e(t),t.updatedAt=jv())}function Dv(){if(!pv())return;let e=kv();if(e)return e.__piboStreamingDebugReset||=()=>(e.__piboStreamingDebug=Ov(),e.__piboStreamingDebug),e.__piboStreamingDebug??=Ov(),e.__piboStreamingDebug}function Ov(){let e=jv();return{enabled:!0,startedAt:e,updatedAt:e,sessionIds:[],liveOpenCount:0,liveErrorCount:0,eventCount:0,eventTypeCounts:{},textDeltaCount:0,textDeltaBytes:0,reasoningDeltaCount:0,reasoningDeltaBytes:0,enqueueCount:0,enqueueFlushImmediateCount:0,pendingEventCount:0,flushCount:0,flushedEventCount:0,overlayUpdateCount:0,overlayEventCount:0,liveTraceComputeCount:0,liveTraceComputeDurationMsTotal:0,markdownRenderCount:0,markdownRenderPlainCount:0,markdownRenderFullCount:0,markdownRenderCommonMarkCount:0,markdownRenderGfmCount:0,markdownRenderGfmFastCount:0,markdownRenderDurationMsTotal:0,markdownRenderPlainDurationMsTotal:0,markdownRenderFullDurationMsTotal:0,markdownRenderCommonMarkDurationMsTotal:0,markdownRenderGfmDurationMsTotal:0,markdownRenderGfmFastDurationMsTotal:0,traceRefreshScheduledCount:0,traceRefreshStartedCount:0,traceRefreshCompletedCount:0,traceRefreshFailedCount:0,traceRefreshDurationMsTotal:0,traceBaseUpdateCount:0}}function kv(){return typeof window>`u`?void 0:window}function Av(e){return typeof TextEncoder<`u`?new TextEncoder().encode(e).byteLength:e.length}function jv(){return new Date().toISOString()}function Mv(e){return Math.max(0,Math.round(e*1e3)/1e3)}(function(e){var t=`\\b(?:BASH|BASHOPTS|BASH_ALIASES|BASH_ARGC|BASH_ARGV|BASH_CMDS|BASH_COMPLETION_COMPAT_DIR|BASH_LINENO|BASH_REMATCH|BASH_SOURCE|BASH_VERSINFO|BASH_VERSION|COLORTERM|COLUMNS|COMP_WORDBREAKS|DBUS_SESSION_BUS_ADDRESS|DEFAULTS_PATH|DESKTOP_SESSION|DIRSTACK|DISPLAY|EUID|GDMSESSION|GDM_LANG|GNOME_KEYRING_CONTROL|GNOME_KEYRING_PID|GPG_AGENT_INFO|GROUPS|HISTCONTROL|HISTFILE|HISTFILESIZE|HISTSIZE|HOME|HOSTNAME|HOSTTYPE|IFS|INSTANCE|JOB|LANG|LANGUAGE|LC_ADDRESS|LC_ALL|LC_IDENTIFICATION|LC_MEASUREMENT|LC_MONETARY|LC_NAME|LC_NUMERIC|LC_PAPER|LC_TELEPHONE|LC_TIME|LESSCLOSE|LESSOPEN|LINES|LOGNAME|LS_COLORS|MACHTYPE|MAILCHECK|MANDATORY_PATH|NO_AT_BRIDGE|OLDPWD|OPTERR|OPTIND|ORBIT_SOCKETDIR|OSTYPE|PAPERSIZE|PATH|PIPESTATUS|PPID|PS1|PS2|PS3|PS4|PWD|RANDOM|REPLY|SECONDS|SELINUX_INIT|SESSION|SESSIONTYPE|SESSION_MANAGER|SHELL|SHELLOPTS|SHLVL|SSH_AUTH_SOCK|TERM|UID|UPSTART_EVENTS|UPSTART_INSTANCE|UPSTART_JOB|UPSTART_SESSION|USER|WINDOWID|XAUTHORITY|XDG_CONFIG_DIRS|XDG_CURRENT_DESKTOP|XDG_DATA_DIRS|XDG_GREETER_DATA_DIR|XDG_MENU_PREFIX|XDG_RUNTIME_DIR|XDG_SEAT|XDG_SEAT_PATH|XDG_SESSION_DESKTOP|XDG_SESSION_ID|XDG_SESSION_PATH|XDG_SESSION_TYPE|XDG_VTNR|XMODIFIERS)\\b`,n={pattern:/(^(["']?)\w+\2)[ \t]+\S.*/,lookbehind:!0,alias:`punctuation`,inside:null},r={bash:n,environment:{pattern:RegExp(`\\$`+t),alias:`constant`},variable:[{pattern:/\$?\(\([\s\S]+?\)\)/,greedy:!0,inside:{variable:[{pattern:/(^\$\(\([\s\S]+)\)\)/,lookbehind:!0},/^\$\(\(/],number:/\b0x[\dA-Fa-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[Ee]-?\d+)?/,operator:/--|\+\+|\*\*=?|<<=?|>>=?|&&|\|\||[=!+\-*/%<>^&|]=?|[?~:]/,punctuation:/\(\(?|\)\)?|,|;/}},{pattern:/\$\((?:\([^)]+\)|[^()])+\)|`[^`]+`/,greedy:!0,inside:{variable:/^\$\(|^`|\)$|`$/}},{pattern:/\$\{[^}]+\}/,greedy:!0,inside:{operator:/:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,punctuation:/[\[\]]/,environment:{pattern:RegExp(`(\\{)`+t),lookbehind:!0,alias:`constant`}}},/\$(?:\w+|[#?*!@$])/],entity:/\\(?:[abceEfnrtv\\"]|O?[0-7]{1,3}|U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{1,2})/};e.languages.bash={shebang:{pattern:/^#!\s*\/.*/,alias:`important`},comment:{pattern:/(^|[^"{\\$])#.*/,lookbehind:!0},"function-name":[{pattern:/(\bfunction\s+)[\w-]+(?=(?:\s*\(?:\s*\))?\s*\{)/,lookbehind:!0,alias:`function`},{pattern:/\b[\w-]+(?=\s*\(\s*\)\s*\{)/,alias:`function`}],"for-or-select":{pattern:/(\b(?:for|select)\s+)\w+(?=\s+in\s)/,alias:`variable`,lookbehind:!0},"assign-left":{pattern:/(^|[\s;|&]|[<>]\()\w+(?:\.\w+)*(?=\+?=)/,inside:{environment:{pattern:RegExp(`(^|[\\s;|&]|[<>]\\()`+t),lookbehind:!0,alias:`constant`}},alias:`variable`,lookbehind:!0},parameter:{pattern:/(^|\s)-{1,2}(?:\w+:[+-]?)?\w+(?:\.\w+)*(?=[=\s]|$)/,alias:`variable`,lookbehind:!0},string:[{pattern:/((?:^|[^<])<<-?\s*)(\w+)\s[\s\S]*?(?:\r?\n|\r)\2/,lookbehind:!0,greedy:!0,inside:r},{pattern:/((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s[\s\S]*?(?:\r?\n|\r)\3/,lookbehind:!0,greedy:!0,inside:{bash:n}},{pattern:/(^|[^\\](?:\\\\)*)"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/,lookbehind:!0,greedy:!0,inside:r},{pattern:/(^|[^$\\])'[^']*'/,lookbehind:!0,greedy:!0},{pattern:/\$'(?:[^'\\]|\\[\s\S])*'/,greedy:!0,inside:{entity:r.entity}}],environment:{pattern:RegExp(`\\$?`+t),alias:`constant`},variable:r.variable,function:{pattern:/(^|[\s;|&]|[<>]\()(?:add|apropos|apt|apt-cache|apt-get|aptitude|aspell|automysqlbackup|awk|basename|bash|bc|bconsole|bg|bzip2|cal|cargo|cat|cfdisk|chgrp|chkconfig|chmod|chown|chroot|cksum|clear|cmp|column|comm|composer|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|debootstrap|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|docker|docker-compose|du|egrep|eject|env|ethtool|expand|expect|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|git|gparted|grep|groupadd|groupdel|groupmod|groups|grub-mkconfig|gzip|halt|head|hg|history|host|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|ip|java|jobs|join|kill|killall|less|link|ln|locate|logname|logrotate|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|lynx|make|man|mc|mdadm|mkconfig|mkdir|mke2fs|mkfifo|mkfs|mkisofs|mknod|mkswap|mmv|more|most|mount|mtools|mtr|mutt|mv|nano|nc|netstat|nice|nl|node|nohup|notify-send|npm|nslookup|op|open|parted|passwd|paste|pathchk|ping|pkill|pnpm|podman|podman-compose|popd|pr|printcap|printenv|ps|pushd|pv|quota|quotacheck|quotactl|ram|rar|rcp|reboot|remsync|rename|renice|rev|rm|rmdir|rpm|rsync|scp|screen|sdiff|sed|sendmail|seq|service|sftp|sh|shellcheck|shuf|shutdown|sleep|slocate|sort|split|ssh|stat|strace|su|sudo|sum|suspend|swapon|sync|sysctl|tac|tail|tar|tee|time|timeout|top|touch|tr|traceroute|tsort|tty|umount|uname|unexpand|uniq|units|unrar|unshar|unzip|update-grub|uptime|useradd|userdel|usermod|users|uudecode|uuencode|v|vcpkg|vdir|vi|vim|virsh|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yarn|yes|zenity|zip|zsh|zypper)(?=$|[)\s;|&])/,lookbehind:!0},keyword:{pattern:/(^|[\s;|&]|[<>]\()(?:case|do|done|elif|else|esac|fi|for|function|if|in|select|then|until|while)(?=$|[)\s;|&])/,lookbehind:!0},builtin:{pattern:/(^|[\s;|&]|[<>]\()(?:\.|:|alias|bind|break|builtin|caller|cd|command|continue|declare|echo|enable|eval|exec|exit|export|getopts|hash|help|let|local|logout|mapfile|printf|pwd|read|readarray|readonly|return|set|shift|shopt|source|test|times|trap|type|typeset|ulimit|umask|unalias|unset)(?=$|[)\s;|&])/,lookbehind:!0,alias:`class-name`},boolean:{pattern:/(^|[\s;|&]|[<>]\()(?:false|true)(?=$|[)\s;|&])/,lookbehind:!0},"file-descriptor":{pattern:/\B&\d\b/,alias:`important`},operator:{pattern:/\d?<>|>\||\+=|=[=~]?|!=?|<<[<-]?|[&\d]?>>|\d[<>]&?|[<>][&=]?|&[>&]?|\|[&|]?/,inside:{"file-descriptor":{pattern:/^\d/,alias:`important`}}},punctuation:/\$?\(\(?|\)\)?|\.\.|[{}[\];\\]/,number:{pattern:/(^|\s)(?:[1-9]\d*|0)(?:[.,]\d+)?\b/,lookbehind:!0}},n.inside=e.languages.bash;for(var i=[`comment`,`function-name`,`for-or-select`,`assign-left`,`parameter`,`string`,`environment`,`function`,`keyword`,`builtin`,`boolean`,`file-descriptor`,`operator`,`punctuation`,`number`],a=r.variable[1].inside,o=0;o<i.length;o++)a[i[o]]=e.languages.bash[i[o]];e.languages.sh=e.languages.bash,e.languages.shell=e.languages.bash})(Prism),(function(e){var t=/(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;e.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:RegExp(`@[\\w-](?:[^;{\\s"']|\\s+(?!\\s)|`+t.source+`)*?(?:;|(?=\\s*\\{))`),inside:{rule:/^@[\w-]+/,"selector-function-argument":{pattern:/(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,lookbehind:!0,alias:`selector`},keyword:{pattern:/(^|[^\w-])(?:and|not|only|or)(?![\w-])/,lookbehind:!0}}},url:{pattern:RegExp(`\\burl\\((?:`+t.source+`|(?:[^\\\\\\r\\n()"']|\\\\[\\s\\S])*)\\)`,`i`),greedy:!0,inside:{function:/^url/i,punctuation:/^\(|\)$/,string:{pattern:RegExp(`^`+t.source+`$`),alias:`url`}}},selector:{pattern:RegExp(`(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|`+t.source+`)*(?=\\s*\\{)`),lookbehind:!0},string:{pattern:t,greedy:!0},property:{pattern:/(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,lookbehind:!0},important:/!important\b/i,function:{pattern:/(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,lookbehind:!0},punctuation:/[(){};:,]/},e.languages.css.atrule.inside.rest=e.languages.css;var n=e.languages.markup;n&&(n.tag.addInlined(`style`,`css`),n.tag.addAttribute(`style`,`css`))})(Prism),Prism.languages.javascript=Prism.languages.extend(`clike`,{"class-name":[Prism.languages.clike[`class-name`],{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,lookbehind:!0}],keyword:[{pattern:/((?:^|\})\s*)catch\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],function:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,number:{pattern:RegExp(`(^|[^\\w$])(?:NaN|Infinity|0[bB][01]+(?:_[01]+)*n?|0[oO][0-7]+(?:_[0-7]+)*n?|0[xX][\\dA-Fa-f]+(?:_[\\dA-Fa-f]+)*n?|\\d+(?:_\\d+)*n|(?:\\d+(?:_\\d+)*(?:\\.(?:\\d+(?:_\\d+)*)?)?|\\.\\d+(?:_\\d+)*)(?:[Ee][+-]?\\d+(?:_\\d+)*)?)(?![\\w$])`),lookbehind:!0},operator:/--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/}),Prism.languages.javascript[`class-name`][0].pattern=/(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/,Prism.languages.insertBefore(`javascript`,`keyword`,{regex:{pattern:RegExp(`((?:^|[^$\\w\\xA0-\\uFFFF."'\\])\\s]|\\b(?:return|yield))\\s*)\\/(?:(?:\\[(?:[^\\]\\\\\\r\\n]|\\\\.)*\\]|\\\\.|[^/\\\\\\[\\r\\n])+\\/[dgimyus]{0,7}|(?:\\[(?:[^[\\]\\\\\\r\\n]|\\\\.|\\[(?:[^[\\]\\\\\\r\\n]|\\\\.|\\[(?:[^[\\]\\\\\\r\\n]|\\\\.)*\\])*\\])*\\]|\\\\.|[^/\\\\\\[\\r\\n])+\\/[dgimyus]{0,7}v[dgimyus]{0,7})(?=(?:\\s|\\/\\*(?:[^*]|\\*(?!\\/))*\\*\\/)*(?:$|[\\r\\n,.;:})\\]]|\\/\\/))`),lookbehind:!0,greedy:!0,inside:{"regex-source":{pattern:/^(\/)[\s\S]+(?=\/[a-z]*$)/,lookbehind:!0,alias:`language-regex`,inside:Prism.languages.regex},"regex-delimiter":/^\/|\/$/,"regex-flags":/^[a-z]+$/}},"function-variable":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,alias:`function`},parameter:[{pattern:/(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,lookbehind:!0,inside:Prism.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/}),Prism.languages.insertBefore(`javascript`,`string`,{hashbang:{pattern:/^#!.*/,greedy:!0,alias:`comment`},"template-string":{pattern:/`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:`string`},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:`punctuation`},rest:Prism.languages.javascript}},string:/[\s\S]+/}},"string-property":{pattern:/((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,lookbehind:!0,greedy:!0,alias:`property`}}),Prism.languages.insertBefore(`javascript`,`operator`,{"literal-property":{pattern:/((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,lookbehind:!0,alias:`property`}}),Prism.languages.markup&&(Prism.languages.markup.tag.addInlined(`script`,`javascript`),Prism.languages.markup.tag.addAttribute(`on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)`,`javascript`)),Prism.languages.js=Prism.languages.javascript,Prism.languages.json={property:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,lookbehind:!0,greedy:!0},string:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,lookbehind:!0,greedy:!0},comment:{pattern:/\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,greedy:!0},number:/-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,punctuation:/[{}[\],]/,operator:/:/,boolean:/\b(?:false|true)\b/,null:{pattern:/\bnull\b/,alias:`keyword`}},Prism.languages.webmanifest=Prism.languages.json,(function(e){var t=`(?:\\\\.|[^\\\\\\n\\r]|(?:\\n|\\r\\n?)(?![\\r\\n]))`;function n(e){return e=e.replace(/<inner>/g,function(){return t}),RegExp(`((?:^|[^\\\\])(?:\\\\{2})*)(?:`+e+`)`)}var r="(?:\\\\.|``(?:[^`\\r\\n]|`(?!`))+``|`[^`\\r\\n]+`|[^\\\\|\\r\\n`])+",i=`\\|?__(?:\\|__)+\\|?(?:(?:\\n|\\r\\n?)|(?![\\s\\S]))`.replace(/__/g,function(){return r}),a=`\\|?[ \\t]*:?-{3,}:?[ \\t]*(?:\\|[ \\t]*:?-{3,}:?[ \\t]*)+\\|?(?:\\n|\\r\\n?)`;e.languages.markdown=e.languages.extend(`markup`,{}),e.languages.insertBefore(`markdown`,`prolog`,{"front-matter-block":{pattern:/(^(?:\s*[\r\n])?)---(?!.)[\s\S]*?[\r\n]---(?!.)/,lookbehind:!0,greedy:!0,inside:{punctuation:/^---|---$/,"front-matter":{pattern:/\S+(?:\s+\S+)*/,alias:[`yaml`,`language-yaml`],inside:e.languages.yaml}}},blockquote:{pattern:/^>(?:[\t ]*>)*/m,alias:`punctuation`},table:{pattern:RegExp(`^`+i+a+`(?:`+i+`)*`,`m`),inside:{"table-data-rows":{pattern:RegExp(`^(`+i+a+`)(?:`+i+`)*$`),lookbehind:!0,inside:{"table-data":{pattern:RegExp(r),inside:e.languages.markdown},punctuation:/\|/}},"table-line":{pattern:RegExp(`^(`+i+`)`+a+`$`),lookbehind:!0,inside:{punctuation:/\||:?-{3,}:?/}},"table-header-row":{pattern:RegExp(`^`+i+`$`),inside:{"table-header":{pattern:RegExp(r),alias:`important`,inside:e.languages.markdown},punctuation:/\|/}}}},code:[{pattern:/((?:^|\n)[ \t]*\n|(?:^|\r\n?)[ \t]*\r\n?)(?: {4}|\t).+(?:(?:\n|\r\n?)(?: {4}|\t).+)*/,lookbehind:!0,alias:`keyword`},{pattern:/^```[\s\S]*?^```$/m,greedy:!0,inside:{"code-block":{pattern:/^(```.*(?:\n|\r\n?))[\s\S]+?(?=(?:\n|\r\n?)^```$)/m,lookbehind:!0},"code-language":{pattern:/^(```).+/,lookbehind:!0},punctuation:/```/}}],title:[{pattern:/\S.*(?:\n|\r\n?)(?:==+|--+)(?=[ \t]*$)/m,alias:`important`,inside:{punctuation:/==+$|--+$/}},{pattern:/(^\s*)#.+/m,lookbehind:!0,alias:`important`,inside:{punctuation:/^#+|#+$/}}],hr:{pattern:/(^\s*)([*-])(?:[\t ]*\2){2,}(?=\s*$)/m,lookbehind:!0,alias:`punctuation`},list:{pattern:/(^\s*)(?:[*+-]|\d+\.)(?=[\t ].)/m,lookbehind:!0,alias:`punctuation`},"url-reference":{pattern:/!?\[[^\]]+\]:[\t ]+(?:\S+|<(?:\\.|[^>\\])+>)(?:[\t ]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\)))?/,inside:{variable:{pattern:/^(!?\[)[^\]]+/,lookbehind:!0},string:/(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\))$/,punctuation:/^[\[\]!:]|[<>]/},alias:`url`},bold:{pattern:n(`\\b__(?:(?!_)<inner>|_(?:(?!_)<inner>)+_)+__\\b|\\*\\*(?:(?!\\*)<inner>|\\*(?:(?!\\*)<inner>)+\\*)+\\*\\*`),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^..)[\s\S]+(?=..$)/,lookbehind:!0,inside:{}},punctuation:/\*\*|__/}},italic:{pattern:n(`\\b_(?:(?!_)<inner>|__(?:(?!_)<inner>)+__)+_\\b|\\*(?:(?!\\*)<inner>|\\*\\*(?:(?!\\*)<inner>)+\\*\\*)+\\*`),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^.)[\s\S]+(?=.$)/,lookbehind:!0,inside:{}},punctuation:/[*_]/}},strike:{pattern:n(`(~~?)(?:(?!~)<inner>)+\\2`),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^~~?)[\s\S]+(?=\1$)/,lookbehind:!0,inside:{}},punctuation:/~~?/}},"code-snippet":{pattern:/(^|[^\\`])(?:``[^`\r\n]+(?:`[^`\r\n]+)*``(?!`)|`[^`\r\n]+`(?!`))/,lookbehind:!0,greedy:!0,alias:[`code`,`keyword`]},url:{pattern:n(`!?\\[(?:(?!\\])<inner>)+\\](?:\\([^\\s)]+(?:[\\t ]+"(?:\\\\.|[^"\\\\])*")?\\)|[ \\t]?\\[(?:(?!\\])<inner>)+\\])`),lookbehind:!0,greedy:!0,inside:{operator:/^!/,content:{pattern:/(^\[)[^\]]+(?=\])/,lookbehind:!0,inside:{}},variable:{pattern:/(^\][ \t]?\[)[^\]]+(?=\]$)/,lookbehind:!0},url:{pattern:/(^\]\()[^\s)]+/,lookbehind:!0},string:{pattern:/(^[ \t]+)"(?:\\.|[^"\\])*"(?=\)$)/,lookbehind:!0}}}}),[`url`,`bold`,`italic`,`strike`].forEach(function(t){[`url`,`bold`,`italic`,`strike`,`code-snippet`].forEach(function(n){t!==n&&(e.languages.markdown[t].inside.content.inside[n]=e.languages.markdown[n])})}),e.hooks.add(`after-tokenize`,function(e){if(e.language!==`markdown`&&e.language!==`md`)return;function t(e){if(!(!e||typeof e==`string`))for(var n=0,r=e.length;n<r;n++){var i=e[n];if(i.type!==`code`){t(i.content);continue}var a=i.content[1],o=i.content[3];if(a&&o&&a.type===`code-language`&&o.type===`code-block`&&typeof a.content==`string`){var s=a.content.replace(/\b#/g,`sharp`).replace(/\b\+\+/g,`pp`);s=(/[a-z][\w-]*/i.exec(s)||[``])[0].toLowerCase();var c=`language-`+s;o.alias?typeof o.alias==`string`?o.alias=[o.alias,c]:o.alias.push(c):o.alias=[c]}}}t(e.tokens)}),e.hooks.add(`wrap`,function(t){if(t.type===`code-block`){for(var n=``,r=0,i=t.classes.length;r<i;r++){var a=t.classes[r],o=/language-(.+)/.exec(a);if(o){n=o[1];break}}var s=e.languages[n];if(s)t.content=e.highlight(l(t.content),s,n);else if(n&&n!==`none`&&e.plugins.autoloader){var c=`md-`+new Date().valueOf()+`-`+Math.floor(Math.random()*0x2386f26fc10000);t.attributes.id=c,e.plugins.autoloader.loadLanguages(n,function(){var t=document.getElementById(c);t&&(t.innerHTML=e.highlight(t.textContent,e.languages[n],n))})}}});var o=RegExp(e.languages.markup.tag.pattern.source,`gi`),s={amp:`&`,lt:`<`,gt:`>`,quot:`"`},c=String.fromCodePoint||String.fromCharCode;function l(e){var t=e.replace(o,``);return t=t.replace(/&(\w{1,8}|#x?[\da-f]{1,8});/gi,function(e,t){return t=t.toLowerCase(),t[0]===`#`?c(t[1]===`x`?parseInt(t.slice(2),16):Number(t.slice(1))):s[t]||e}),t}e.languages.md=e.languages.markdown})(Prism),(function(e){e.languages.typescript=e.languages.extend(`javascript`,{"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|type)\s+)(?!keyof\b)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?:\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>)?/,lookbehind:!0,greedy:!0,inside:null},builtin:/\b(?:Array|Function|Promise|any|boolean|console|never|number|string|symbol|unknown)\b/}),e.languages.typescript.keyword.push(/\b(?:abstract|declare|is|keyof|readonly|require)\b/,/\b(?:asserts|infer|interface|module|namespace|type)\b(?=\s*(?:[{_$a-zA-Z\xA0-\uFFFF]|$))/,/\btype\b(?=\s*(?:[\{*]|$))/),delete e.languages.typescript.parameter,delete e.languages.typescript[`literal-property`];var t=e.languages.extend(`typescript`,{});delete t[`class-name`],e.languages.typescript[`class-name`].inside=t,e.languages.insertBefore(`typescript`,`function`,{decorator:{pattern:/@[$\w\xA0-\uFFFF]+/,inside:{at:{pattern:/^@/,alias:`operator`},function:/^[\s\S]+/}},"generic-function":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>(?=\s*\()/,greedy:!0,inside:{function:/^#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*/,generic:{pattern:/<[\s\S]+/,alias:`class-name`,inside:t}}}}),e.languages.ts=e.languages.typescript})(Prism),(function(e){var t=/[*&][^\s[\]{},]+/,n=/!(?:<[\w\-%#;/?:@&=+$,.!~*'()[\]]+>|(?:[a-zA-Z\d-]*!)?[\w\-%#;/?:@&=+$.~*'()]+)?/,r=`(?:`+n.source+`(?:[ ]+`+t.source+`)?|`+t.source+`(?:[ ]+`+n.source+`)?)`,i=`(?:[^\\s\\x00-\\x08\\x0e-\\x1f!"#%&'*,\\-:>?@[\\]\`{|}\\x7f-\\x84\\x86-\\x9f\\ud800-\\udfff\\ufffe\\uffff]|[?:-]<PLAIN>)(?:[ \\t]*(?:(?![#:])<PLAIN>|:<PLAIN>))*`.replace(/<PLAIN>/g,function(){return`[^\\s\\x00-\\x08\\x0e-\\x1f,[\\]{}\\x7f-\\x84\\x86-\\x9f\\ud800-\\udfff\\ufffe\\uffff]`}),a=`"(?:[^"\\\\\\r\\n]|\\\\.)*"|'(?:[^'\\\\\\r\\n]|\\\\.)*'`;function o(e,t){t=(t||``).replace(/m/g,``)+`m`;var n=`([:\\-,[{]\\s*(?:\\s<<prop>>[ \\t]+)?)(?:<<value>>)(?=[ \\t]*(?:$|,|\\]|\\}|(?:[\\r\\n]\\s*)?#))`.replace(/<<prop>>/g,function(){return r}).replace(/<<value>>/g,function(){return e});return RegExp(n,t)}e.languages.yaml={scalar:{pattern:RegExp(`([\\-:]\\s*(?:\\s<<prop>>[ \\t]+)?[|>])[ \\t]*(?:((?:\\r?\\n|\\r)[ \\t]+)\\S[^\\r\\n]*(?:\\2[^\\r\\n]+)*)`.replace(/<<prop>>/g,function(){return r})),lookbehind:!0,alias:`string`},comment:/#.*/,key:{pattern:RegExp(`((?:^|[:\\-,[{\\r\\n?])[ \\t]*(?:<<prop>>[ \\t]+)?)<<key>>(?=\\s*:\\s)`.replace(/<<prop>>/g,function(){return r}).replace(/<<key>>/g,function(){return`(?:`+i+`|`+a+`)`})),lookbehind:!0,greedy:!0,alias:`atrule`},directive:{pattern:/(^[ \t]*)%.+/m,lookbehind:!0,alias:`important`},datetime:{pattern:o(`\\d{4}-\\d\\d?-\\d\\d?(?:[tT]|[ \\t]+)\\d\\d?:\\d{2}:\\d{2}(?:\\.\\d*)?(?:[ \\t]*(?:Z|[-+]\\d\\d?(?::\\d{2})?))?|\\d{4}-\\d{2}-\\d{2}|\\d\\d?:\\d{2}(?::\\d{2}(?:\\.\\d*)?)?`),lookbehind:!0,alias:`number`},boolean:{pattern:o(`false|true`,`i`),lookbehind:!0,alias:`important`},null:{pattern:o(`null|~`,`i`),lookbehind:!0,alias:`important`},string:{pattern:o(a),lookbehind:!0,greedy:!0},number:{pattern:o(`[+-]?(?:0x[\\da-f]+|0o[0-7]+|(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?|\\.inf|\\.nan)`,`i`),lookbehind:!0},tag:n,important:t,punctuation:/---|[:[\]{}\-,|>?]|\.\.\./},e.languages.yml=e.languages.yaml})(Prism);var Nv=[`p`,`br`,`strong`,`em`,`a`,`ul`,`ol`,`li`,`blockquote`,`code`,`pre`,`h1`,`h2`,`h3`,`h4`,`hr`,`table`,`thead`,`tbody`,`tr`,`th`,`td`,`input`,`del`],Pv=[sv],Fv=[],Iv=/[\n\r\\`*_\[\]<>]|~~/,Lv=/^\s*(?:#{1,6}\s|[-+>]|(?:\d+[.)]))\s/,Rv=/^\s*-{3,}\s*$/,zv=/\b(?:https?:\/\/|www\.)|\S+@\S+\.\S+/i,Bv=/^\s*[-+*]\s+\[[ xX]\]\s/m,Vv=/(^|\n)\s*\|?.+\|.+\n\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*(?:\n|$)/;function Hv(e){return e.length>0&&!Iv.test(e)&&!Lv.test(e)&&!Rv.test(e)&&!(Uv(e)&&zv.test(e))}function Uv(e){return e.includes(`://`)||e.includes(`www.`)||e.includes(`@`)}function Wv(e){let t=Gv(e);return t?t.openerEnd>=e.length?e.slice(0,t.openerStart):`${e}\``:e}function Gv(e){let t=0;for(;t<e.length;){let n=e.indexOf("`",t);if(n===-1)return;if(Jv(e,n)){t=n+1;continue}if(qv(e,n)!==1)return;let r=Kv(e,n+1);if(r===-1)return{openerStart:n,openerEnd:n+1};t=r+1}}function Kv(e,t){for(;t<e.length;){let n=e.indexOf("`",t);if(n===-1)return-1;let r=qv(e,n);if(r===1)return n;t=n+r}return-1}function qv(e,t){let n=t;for(;n<e.length&&e[n]==="`";)n+=1;return n-t}function Jv(e,t){let n=0,r=t-1;for(;r>=0&&e[r]===`\\`;)n+=1,--r;return n%2==1}function Yv(e){return e.includes(`~~`)||e.includes(`[`)&&Bv.test(e)||e.includes(`|`)&&Vv.test(e)||Uv(e)&&zv.test(e)}var Xv=/[\n\r\\`*_\[\]<>]/,Zv=/^\s*[-+*]\s+\[([ xX])\]\s+(.+?)\s*$/,Qv=/[\n\r\\<>|~]/,$v=/[\n\r\\\[\]<>|~]/,ey=/[\s\[\]()`<>]/;function ty(e){if(!e.includes(`~~`)||Xv.test(e)||Lv.test(e)||Rv.test(e)||Uv(e)&&zv.test(e)||e.includes(`[`)&&Bv.test(e)||e.includes(`|`)&&Vv.test(e))return;let t=[],n=0,r=0;for(;n<e.length;){let i=e.indexOf(`~~`,n);if(i===-1){t.push(e.slice(n));break}let a=e.indexOf(`~~`,i+2);if(a===-1||a===i+2)return;let o=e.slice(n,i);o&&t.push(o);let s=e.slice(i+2,a);if(s.includes(`~`))return;t.push((0,M.jsx)(`del`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`del`,children:s},`del-${r}`)),r+=1,n=a+2}return r>0?(0,M.jsx)(`p`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`p`,children:t}):void 0}function ny(e){if(!e||ey.test(e))return;let t=sh(e);if(t){if(t.startsWith(`/`)||t.startsWith(`#`))return t;try{let e=new URL(t);return e.protocol===`http:`||e.protocol===`https:`||e.protocol===`mailto:`?t:void 0}catch{return}}}function ry(e,t){if(!e||$v.test(e))return;let n=[],r=0,i=0,a=0,o=0;for(;r<e.length;){let s=e.indexOf(`**`,r),c=e.indexOf(`_`,r),l=e.indexOf("`",r),u=s===-1?1/0:s,d=c===-1?1/0:c,f=Math.min(u,d,l===-1?1/0:l);if(f===1/0){let t=e.slice(r);if(t.includes(`*`)||t.includes(`_`)||t.includes("`")||Uv(t)&&zv.test(t))return;t&&n.push(t);break}let p=e.slice(r,f);if(p.includes(`*`)||p.includes(`_`)||p.includes("`")||Uv(p)&&zv.test(p))return;if(p&&n.push(p),f===u){let a=e.indexOf(`**`,f+2);if(a===-1||a===f+2)return;let o=e.slice(f+2,a);if(o.includes(`*`)||o.includes("`")||o.includes(`[`)||o.includes(`]`))return;if(o.includes(`_`)){if(!o.startsWith(`_`)||!o.endsWith(`_`)||o.length<=2)return;let e=o.slice(1,-1);if(e.includes(`*`)||e.includes(`_`)||e.includes("`")||e.includes(`[`)||e.includes(`]`))return;n.push((0,M.jsx)(`strong`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`strong`,children:(0,M.jsx)(`em`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`em`,children:e})},`link-${t}-strong-${i}`))}else n.push((0,M.jsx)(`strong`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`strong`,children:o},`link-${t}-strong-${i}`));i+=1,r=a+2}else if(f===d){if(e[f+1]===`_`)return;let i=e.indexOf(`_`,f+1);if(i===-1||i===f+1)return;let o=e.slice(f+1,i);if(o.includes(`**`)){if(!o.startsWith(`**`)||!o.endsWith(`**`)||o.length<=4)return;let e=o.slice(2,-2);if(e.includes(`*`)||e.includes(`_`)||e.includes("`")||e.includes(`[`)||e.includes(`]`))return;n.push((0,M.jsx)(`em`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`em`,children:(0,M.jsx)(`strong`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`strong`,children:e})},`link-${t}-em-${a}`))}else{if(o.includes(`*`)||o.includes(`_`)||o.includes("`")||o.includes(`[`)||o.includes(`]`))return;n.push((0,M.jsx)(`em`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`em`,children:o},`link-${t}-em-${a}`))}a+=1,r=i+1}else{if(e[f+1]==="`")return;let i=e.indexOf("`",f+1);if(i===-1||i===f+1)return;let a=e.slice(f+1,i);if(a.includes("`")||a.includes(`[`)||a.includes(`]`)||a.startsWith(` `)||a.endsWith(` `))return;n.push((0,M.jsx)(`code`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`code`,children:a},`link-${t}-code-${o}`)),o+=1,r=i+1}}return n.length>0?n:void 0}function iy(e){let t=[],n=0,r=0,i=0,a=0;for(;n<e.length;){let o=e.indexOf(`**`,n),s=e.indexOf("`",n),c=e.indexOf(`[`,n),l=o===-1?1/0:o,u=s===-1?1/0:s,d=Math.min(l,u,c===-1?1/0:c);if(d===1/0){let r=e.slice(n);if(r.includes(`*`)||r.includes(`_`)||r.includes("`")||r.includes(`[`)||r.includes(`]`)||Uv(r)&&zv.test(r))return;r&&t.push(r);break}let f=e.slice(n,d);if(f.includes(`*`)||f.includes(`_`)||f.includes("`")||f.includes(`[`)||f.includes(`]`)||Uv(f)&&zv.test(f))return;if(f&&t.push(f),d===l){let i=e.indexOf(`**`,d+2);if(i===-1||i===d+2)return;let a=e.slice(d+2,i);if(a.includes(`*`)||a.includes(`_`)||a.includes("`")||a.includes(`[`)||a.includes(`]`))return;t.push((0,M.jsx)(`strong`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`strong`,children:a},`strong-${r}`)),r+=1,n=i+2}else if(d===u){if(e[d+1]==="`")return;let r=e.indexOf("`",d+1);if(r===-1||r===d+1)return;let a=e.slice(d+1,r);if(a.includes(`_`)||a.includes("`")||a.includes(`[`)||a.includes(`]`)||a.startsWith(` `)||a.endsWith(` `))return;t.push((0,M.jsx)(`code`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`code`,children:a},`code-${i}`)),i+=1,n=r+1}else{let r=e.indexOf(`](`,d+1);if(r===-1||r===d+1)return;let i=e.indexOf(`)`,r+2);if(i===-1||i===r+2)return;let o=ry(e.slice(d+1,r),a),s=ny(e.slice(r+2,i));if(!s||!o)return;t.push((0,M.jsx)(`a`,{href:s,target:`_blank`,rel:`noreferrer`,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`a`,children:o},`link-${a}`)),a+=1,n=i+1}}return t.length>0?t:void 0}function ay(e){let t=Zv.exec(e);if(!t)return;let n=t[2];if(!n||Qv.test(n))return;let r=iy(n);if(r)return(0,M.jsx)(`ul`,{className:`contains-task-list`,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`ul`,children:(0,M.jsxs)(`li`,{className:`task-list-item`,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`li`,children:[(0,M.jsx)(`input`,{type:`checkbox`,checked:t[1].toLowerCase()===`x`,readOnly:!0,disabled:!0,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`input`}),r]})})}var oy={p({children:e,node:t,...n}){return(0,M.jsx)(`p`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`p`,...n,children:e})},ul({children:e,node:t,...n}){return(0,M.jsx)(`ul`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`ul`,...n,children:e})},ol({children:e,node:t,...n}){return(0,M.jsx)(`ol`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`ol`,...n,children:e})},li({children:e,node:t,...n}){return(0,M.jsx)(`li`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`li`,...n,children:e})},blockquote({children:e,node:t,...n}){return(0,M.jsx)(`blockquote`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`blockquote`,...n,children:e})},pre({children:e,node:t,...n}){return(0,M.jsx)(`pre`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`pre`,...n,children:e})},a({href:e,children:t}){return(0,M.jsx)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`a`,children:t})},code({className:e,children:t,node:n,...r}){let i=sy(e),a=String(t).replace(/\n$/,``);if(!i)return(0,M.jsx)(`code`,{className:e,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`code`,...r,children:t});let o=dv.languages[i];return o?(0,M.jsx)(`code`,{className:`language-${i}`,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`code`,dangerouslySetInnerHTML:{__html:dv.highlight(a,o,i)},...r}):(0,M.jsx)(`code`,{className:e,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`code`,...r,children:t})},th({children:e,node:t,...n}){return(0,M.jsx)(`th`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`th`,...n,children:e})},td({children:e,node:t,...n}){return(0,M.jsx)(`td`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`td`,...n,children:e})},input({checked:e,node:t,...n}){return(0,M.jsx)(`input`,{type:`checkbox`,checked:!!e,readOnly:!0,disabled:!0,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`input`,...n})}};function sy(e){let t=/language-(\S+)/.exec(e??``);if(!t)return;let n=t[1].toLowerCase();return n===`sh`||n===`shell`?`bash`:n===`js`?`javascript`:n===`ts`?`typescript`:n===`md`?`markdown`:n===`yml`?`yaml`:n}function cy(e,t){t!==void 0&&bv(e,(typeof performance>`u`?Date.now():performance.now())-t)}var ly=(e,t,n)=>{if(n.tagName!==`a`||t!==`href`)return``;let r=sh(e);if(!r)return``;if(r.startsWith(`/`)||r.startsWith(`#`))return r;try{let e=new URL(r);return e.protocol===`http:`||e.protocol===`https:`||e.protocol===`mailto:`?r:``}catch{return``}},uy=(0,v.memo)(function({children:e,streaming:t=!1}){let n=pv()?typeof performance>`u`?Date.now():performance.now():void 0,r=t?Wv(e):e,i=`commonmark`,a;if(Hv(r))i=`plain`,a=(0,M.jsx)(`p`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`p`,children:r});else{let e=Yv(r),t=e?ty(r)??ay(r):void 0;t?(i=`gfm-fast`,a=t):(i=e?`gfm`:`commonmark`,a=rh({allowedElements:Nv,children:r,components:oy,remarkPlugins:e?Pv:Fv,skipHtml:!0,urlTransform:ly}))}return cy(i,n),a}),dy={"agent.run":{color:`text-[#11a4d4]`,bgColor:`bg-[#11a4d4]/20`,borderColor:`border-[#11a4d4]`,label:`Agent Run`},"tool.call":{color:`text-purple-500`,bgColor:`bg-purple-500/20`,borderColor:`border-purple-500`,label:`Tool Call`},"tool.result":{color:`text-green-500`,bgColor:`bg-green-500/20`,borderColor:`border-green-500`,label:`Tool Result`},"model.request":{color:`text-blue-500`,bgColor:`bg-blue-500/20`,borderColor:`border-blue-500`,label:`Model Request`},"model.response":{color:`text-[#0bda57]`,bgColor:`bg-[#0bda57]/20`,borderColor:`border-[#0bda57]`,label:`Model Response`},"model.reasoning":{color:`text-amber-500`,bgColor:`bg-amber-500/20`,borderColor:`border-amber-500`,label:`Reasoning`},"agent.delegation":{color:`text-orange-500`,bgColor:`bg-orange-500/20`,borderColor:`border-orange-500`,label:`Agent Delegation`},"agent.async":{color:`text-orange-500`,bgColor:`bg-orange-500/20`,borderColor:`border-orange-500`,label:`Async Agent`},"yielded.run":{color:`text-[#11a4d4]`,bgColor:`bg-[#11a4d4]/20`,borderColor:`border-[#11a4d4]`,label:`Yielded Run`},"user.prompt":{color:`text-cyan-500`,bgColor:`bg-cyan-500/20`,borderColor:`border-cyan-500`,label:`User Prompt`},user_input:{color:`text-slate-500`,bgColor:`bg-slate-800`,borderColor:`border-slate-600`,label:`User Input`},"execution.command":{color:`text-yellow-500`,bgColor:`bg-yellow-500/20`,borderColor:`border-yellow-500`,label:`Command`}},fy=12;function py(e,t){return t===`all`||e<t}(0,v.memo)(function e({span:t,startTime:n,depth:r=0,expansionDepth:i,expansionSignal:a,expandThinking:o,onFork:s,onOpenSession:c}){let[l,u]=(0,v.useState)(()=>py(r,i)),[d,f]=(0,v.useState)(()=>t.spanType===`model.reasoning`?o:py(r,i));(0,v.useEffect)(()=>{let e=py(r,i);u(e),f(t.spanType===`model.reasoning`?o:e)},[r,i,a,o,t.spanType]),dy[t.spanType]||dy[`agent.run`],t.status,t.status,t.spanType===`user.prompt`||t.spanType;let p=!!t.children?.length;return Ey(t.startTime,n),t.durationUs?`${(t.durationUs/1e3).toFixed(1)}`:t.endTime&&`${((t.endTime-t.startTime)/1e3).toFixed(1)}`,(0,M.jsx)(my,{span:t,startTime:n,depth:r,contentExpanded:d,childrenExpanded:l,onToggle:(0,v.useCallback)(()=>{f(e=>!e),p&&u(e=>!e)},[p]),onFork:s,onOpenSession:c,childrenContent:p?t.children?.map(t=>(0,M.jsx)(e,{span:t,startTime:n,depth:r+1,expansionDepth:i,expansionSignal:a,expandThinking:o,onFork:s,onOpenSession:c},t.id)):void 0})});var my=(0,v.memo)(function({span:e,startTime:t,depth:n=0,contentExpanded:r,childrenExpanded:i,onToggle:a,onFork:o,onOpenSession:s,childrenContent:c}){let l=dy[e.spanType]||dy[`agent.run`],u=e.status===`UNSET`,d=Cy(e.status,u),f=e.spanType===`user.prompt`||e.spanType===`user_input`,p=!!e.children?.length,m=Ey(e.startTime,t),h=e.durationUs?`${(e.durationUs/1e3).toFixed(1)}ms`:e.endTime?`${((e.endTime-e.startTime)/1e3).toFixed(1)}ms`:null;return(0,M.jsx)(`div`,{className:`relative mb-4 group`,style:{marginLeft:n>0?fy:0,width:n>0?`calc(100% - ${fy}px)`:`var(--trace-readable-width)`,maxWidth:`100%`},children:(0,M.jsxs)(`div`,{className:`min-w-0 ${f?`bg-[#11a4d4]/10`:`bg-white dark:bg-[#1a262b]`} border ${d.cardClass} rounded-sm shadow-sm transition-all hover:border-opacity-70 focus:outline-none focus:ring-1 focus:ring-[#11a4d4]/50 ${u?d.glowClass:``}`,onDoubleClick:e=>{hy(e)||a()},onKeyDown:e=>{hy(e)||(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),a())},role:`button`,tabIndex:0,"aria-expanded":r,children:[(0,M.jsx)(gy,{span:e,config:l,statusStyles:d,isActive:u,contentExpanded:r,duration:h,relativeTime:m,onToggle:a,onFork:o,onOpenSession:s}),r?(0,M.jsx)(yy,{span:e}):null,p&&i&&r?(0,M.jsx)(`div`,{className:`min-w-0 border-t border-slate-700 bg-slate-900/50 py-4`,children:c}):null]})})});function hy(e){let t=e.target;if(!(t instanceof Element)||t===e.currentTarget)return!1;let n=t.closest(`button, a, input, textarea, select, summary, [role='button'], [tabindex]:not([tabindex='-1'])`);return!!(n&&n!==e.currentTarget)}function gy({span:e,config:t,statusStyles:n,isActive:r,contentExpanded:i,duration:a,relativeTime:o,onToggle:s,onFork:c,onOpenSession:l}){let u=e.spanType===`user.prompt`||e.spanType===`user_input`?`bg-[#11a4d4]/10`:n.headerClass;return(0,M.jsx)(`div`,{className:`${i?`border-b ${t.borderColor}/20`:``} ${u}`,children:(0,M.jsxs)(`div`,{className:`box-border flex w-full min-w-0 items-center`,style:{maxWidth:`100%`},children:[(0,M.jsx)(`div`,{className:`min-w-0 flex-1 px-4 py-2 text-left`,children:(0,M.jsxs)(`span`,{className:`min-w-0 text-xs font-bold ${t.color} uppercase tracking-wider flex items-center gap-2`,children:[i?(0,M.jsx)(Me,{size:12}):(0,M.jsx)(Ne,{size:12}),(0,M.jsx)(_y,{spanType:e.spanType,config:t,isActive:r}),(0,M.jsx)(`span`,{className:`shrink-0`,children:t.label}),e.name?(0,M.jsxs)(`span`,{className:`min-w-0 truncate font-normal text-slate-500 dark:text-slate-400 normal-case`,children:[`: `,e.name]}):null,r?(0,M.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-[#11a4d4] animate-pulse`}):null]})}),(0,M.jsx)(by,{forkEntryId:e.pibo?.traceNodeType===`user.message`?e.pibo.entryId:void 0,linkedPiboSessionId:e.pibo?.linkedPiboSessionId,onFork:c,onOpenSession:l}),(0,M.jsx)(vy,{duration:a,relativeTime:o})]})})}function _y({spanType:e,config:t,isActive:n}){return(0,M.jsxs)(`span`,{className:`relative inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full ${t.bgColor} border-2 ${t.borderColor} ${n?`shadow-[0_0_10px_rgba(17,164,212,0.4)]`:``}`,children:[(0,M.jsx)(Sy,{type:e,className:t.color}),n?(0,M.jsx)(`span`,{className:`absolute -right-0.5 -top-0.5 h-1.5 w-1.5 rounded-full bg-[#11a4d4] animate-pulse`}):null]})}function vy({duration:e,relativeTime:t}){return(0,M.jsxs)(`div`,{className:`ml-2 mr-4 flex w-36 shrink-0 items-center justify-end gap-2 font-mono tabular-nums`,children:[e?(0,M.jsx)(`span`,{className:`text-[10px] text-slate-500 dark:text-slate-400`,children:e}):null,(0,M.jsx)(`span`,{className:`text-xs text-slate-400 dark:text-slate-500`,children:t})]})}var yy=(0,v.memo)(function({span:e}){let[t,n]=(0,v.useState)(!1),{spanType:r,attributes:i,name:a}=e,o=i.content||i.input||i.output||i.message,s=i.tool_name||i.tool?.name||i[`tool.name`],c=typeof s==`string`?s:null,l=i.output||i.result||i[`tool.result`],u=i.arguments||i.args||i[`tool.arguments`],d=e.status===`ERROR`?(0,M.jsxs)(`div`,{className:`mx-4 mt-4 p-3 bg-red-500/10 border border-red-500/20 rounded-sm text-xs`,children:[(0,M.jsx)(`div`,{className:`flex items-center gap-2 font-semibold text-red-500 mb-1`,children:`Error`}),e.statusMessage?(0,M.jsx)(`div`,{className:`font-mono text-red-400 mb-2`,children:e.statusMessage}):null]}):null;if(r===`user.prompt`||r===`user_input`)return(0,M.jsxs)(`div`,{className:`flex flex-col`,children:[d,(0,M.jsx)(`div`,{className:`min-w-0 break-words p-4 font-mono text-sm text-slate-300 whitespace-pre-wrap`,children:typeof o==`string`?o:JSON.stringify(o)})]});if(r===`model.response`)return(0,M.jsxs)(`div`,{className:`flex flex-col`,children:[d,(0,M.jsx)(`div`,{className:`model-response-markdown min-w-0 p-4 text-sm text-slate-200 leading-relaxed`,children:typeof o==`string`?(0,M.jsx)(uy,{children:o}):(0,M.jsx)(Sc,{value:o})})]});if(r===`tool.result`)return(0,M.jsxs)(`div`,{className:`flex flex-col`,children:[d,(0,M.jsxs)(`div`,{className:`p-4 bg-green-500/5 border-t border-green-500/20`,children:[(0,M.jsxs)(`div`,{className:`text-xs font-medium text-green-400 mb-2`,children:[`Returned from `,c||a,`:`]}),(0,M.jsx)(Sc,{value:l??o})]})]});if(r===`tool.call`){let e=Dy(u)?u:{},r=Object.keys(e).length>0;return(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(`div`,{className:`p-4 bg-[#0e1116] border-b border-slate-800`,children:(0,M.jsx)(xy,{name:c??a,args:e})}),l==null?null:(0,M.jsxs)(`div`,{className:`px-4 py-2 bg-[#1a262b] flex items-center gap-2`,children:[(0,M.jsx)(Ce,{size:14,className:`text-slate-400`}),(0,M.jsx)(`span`,{className:`text-xs font-mono text-slate-500`,children:`Output:`}),(0,M.jsx)(`code`,{className:`min-w-0 max-w-md truncate text-xs font-mono text-slate-300`,children:typeof l==`string`?l.slice(0,100):JSON.stringify(l).slice(0,100)})]}),(0,M.jsxs)(`button`,{type:`button`,onClick:()=>n(e=>!e),className:`w-full px-4 py-1.5 flex items-center gap-1.5 text-[11px] font-medium text-slate-400 hover:text-slate-200 bg-slate-900/40 hover:bg-slate-800/60 border-t border-slate-700/40 transition-colors`,children:[t?(0,M.jsx)(Je,{size:12}):(0,M.jsx)(Ye,{size:12}),t?`Hide Details`:`Show Details`]}),t?(0,M.jsxs)(`div`,{className:`border-t border-slate-700/40 bg-[#0e1116]`,children:[r?(0,M.jsxs)(`div`,{className:`px-4 pt-3 pb-2`,children:[(0,M.jsx)(`div`,{className:`text-[10px] font-semibold text-blue-400 uppercase tracking-wider mb-1.5`,children:`Input`}),(0,M.jsx)(Sc,{value:e})]}):null,l==null?null:(0,M.jsxs)(`div`,{className:`px-4 pt-2 pb-3 border-t border-slate-700/30`,children:[(0,M.jsx)(`div`,{className:`text-[10px] font-semibold text-green-400 uppercase tracking-wider mb-1.5`,children:`Output`}),(0,M.jsx)(Sc,{value:l})]})]}):null,d]})}if(r===`yielded.run`){let e=Dy(l)?l:Dy(o)?o:{};return(0,M.jsxs)(`div`,{className:`flex flex-col`,children:[d,(0,M.jsxs)(`div`,{className:`p-4 border-b border-[#11a4d4]/20 bg-[#11a4d4]/5`,children:[(0,M.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,M.jsx)(Te,{size:14,className:`text-[#11a4d4]`}),(0,M.jsx)(`span`,{className:`text-sm font-medium text-[#11a4d4]`,children:`Run notification`}),(0,M.jsx)(`span`,{className:`text-xs font-mono text-slate-400`,children:typeof i.content==`string`?i.content:a})]}),(0,M.jsx)(wy,{notification:e})]}),(0,M.jsxs)(`button`,{type:`button`,onClick:()=>n(e=>!e),className:`w-full px-4 py-1.5 flex items-center gap-1.5 text-[11px] font-medium text-slate-400 hover:text-slate-200 bg-slate-900/40 hover:bg-slate-800/60 border-t border-slate-700/40 transition-colors`,children:[t?(0,M.jsx)(Je,{size:12}):(0,M.jsx)(Ye,{size:12}),t?`Hide Details`:`Show Details`]}),t?(0,M.jsx)(`div`,{className:`border-t border-slate-700/40 bg-[#0e1116] px-4 py-3`,children:(0,M.jsx)(Sc,{value:e})}):null]})}if(r===`model.reasoning`){let e=i.reasoning||i[`model.reasoning`]||o;return(0,M.jsxs)(`div`,{className:`flex flex-col`,children:[d,(0,M.jsxs)(`div`,{className:`min-w-0 break-words p-4 font-mono text-sm text-slate-300 bg-amber-500/5 leading-relaxed whitespace-pre-wrap`,children:[(0,M.jsx)(`span`,{className:`text-amber-500 opacity-60`,children:`// Model reasoning`}),(0,M.jsx)(`br`,{}),typeof e==`string`?e:JSON.stringify(e,null,2)]})]})}if(r===`agent.delegation`){let e=i[`delegation.target_agent`],t=i[`delegation.query`],n=i[`result.status`];return(0,M.jsxs)(M.Fragment,{children:[d,(0,M.jsxs)(`div`,{className:`p-4 border-b border-orange-500/20 bg-orange-500/5`,children:[(0,M.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,M.jsx)(Qe,{size:14,className:`text-orange-500`}),(0,M.jsx)(`span`,{className:`text-sm font-medium text-orange-500`,children:`Delegated to:`}),(0,M.jsxs)(`span`,{className:`text-sm font-semibold text-slate-200`,children:[e||`unknown`,` agent`]}),n?(0,M.jsx)(`span`,{className:`ml-2 px-2 py-0.5 text-[10px] font-bold rounded-sm bg-green-500/20 text-green-500`,children:n.toUpperCase()}):null]}),t?(0,M.jsxs)(`div`,{className:`text-xs text-slate-400 font-mono italic line-clamp-2`,children:[`"`,Oy(t),`"`]}):null]})]})}if(r===`agent.async`){let e=i[`async_agent.target_agent`],t=i[`async_agent.query`],n=i[`async_agent.started_by`],r=i.run_id,a=i[`result.status`];return(0,M.jsxs)(M.Fragment,{children:[d,(0,M.jsxs)(`div`,{className:`p-4 border-b border-orange-500/20 bg-orange-500/5`,children:[(0,M.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 mb-2`,children:[(0,M.jsx)(Qe,{size:14,className:`text-orange-500`}),(0,M.jsx)(`span`,{className:`text-sm font-medium text-orange-500`,children:`Async agent started:`}),(0,M.jsxs)(`span`,{className:`text-sm font-semibold text-slate-200`,children:[e||`unknown`,` agent`]}),a?(0,M.jsx)(`span`,{className:`px-2 py-0.5 text-[10px] font-bold rounded-sm bg-orange-500/15 text-orange-400`,children:a.toUpperCase()}):null]}),(0,M.jsxs)(`div`,{className:`mb-2 flex flex-wrap gap-x-3 gap-y-1 font-mono text-[11px] text-slate-500`,children:[(0,M.jsxs)(`span`,{children:[`Started by `,n||`pibo_run_start`]}),r?(0,M.jsx)(`span`,{children:r}):null]}),t?(0,M.jsxs)(`div`,{className:`text-xs text-slate-400 font-mono italic line-clamp-2`,children:[`"`,Oy(t),`"`]}):null]})]})}return r===`agent.run`?(0,M.jsx)(`div`,{className:`flex flex-col`,children:d}):(0,M.jsxs)(`div`,{className:`flex flex-col`,children:[d,(0,M.jsx)(`div`,{className:`p-4 font-mono text-sm text-slate-300`,children:(0,M.jsx)(Sc,{value:i})})]})});function by({forkEntryId:e,linkedPiboSessionId:t,onFork:n,onOpenSession:r}){let i=e&&n?e:void 0,a=t&&r?t:void 0;return!i&&!a?null:(0,M.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[i?(0,M.jsx)(`button`,{type:`button`,onClick:()=>n?.(i),className:`inline-flex h-8 w-8 items-center justify-center rounded-sm border border-slate-700 bg-[#151f24]/80 text-slate-400 transition-colors hover:border-[#11a4d4] hover:text-[#11a4d4]`,title:`Fork user message`,"aria-label":`Fork user message`,children:(0,M.jsx)(Qe,{size:14})}):null,a?(0,M.jsx)(`button`,{type:`button`,onClick:()=>r?.(a),className:`inline-flex h-8 w-8 items-center justify-center rounded-sm border border-slate-700 bg-[#151f24]/80 text-slate-400 transition-colors hover:border-[#11a4d4] hover:text-[#11a4d4]`,title:`Open child session`,"aria-label":`Open child session`,children:(0,M.jsx)(qe,{size:14})}):null]})}function xy({name:e,args:t}){return(0,M.jsxs)(`code`,{className:`font-mono text-xs text-green-400`,children:[(0,M.jsx)(`span`,{className:`text-purple-400`,children:`def`}),` `,(0,M.jsx)(`span`,{className:`text-yellow-300`,children:e}),(0,M.jsxs)(`span`,{children:[`(`,Object.entries(t).map(([e,t],n)=>(0,M.jsxs)(`span`,{children:[n>0?`, `:null,(0,M.jsx)(`span`,{className:`text-blue-400`,children:e}),`=`,(0,M.jsx)(`span`,{className:`text-green-300`,children:typeof t==`string`?`'${t.slice(0,50)}${t.length>50?`...`:``}'`:Oy(t).slice(0,50)})]},e)),`)`]})]})}function Sy({type:e,className:t}){let n={size:14,className:t};switch(e){case`agent.run`:return(0,M.jsx)(ke,{...n});case`tool.call`:return(0,M.jsx)(Ee,{...n});case`tool.result`:return(0,M.jsx)(Ce,{...n});case`model.request`:return(0,M.jsx)(Oe,{...n});case`model.response`:return(0,M.jsx)(Ce,{...n});case`model.reasoning`:return(0,M.jsx)(it,{...n});case`agent.delegation`:return(0,M.jsx)(Qe,{...n});case`agent.async`:return(0,M.jsx)(Qe,{...n});case`yielded.run`:return(0,M.jsx)(Te,{...n});case`user.prompt`:return(0,M.jsx)(ct,{...n});case`user_input`:return(0,M.jsx)(_t,{...n});case`execution.command`:return(0,M.jsx)(Ee,{...n});default:return(0,M.jsx)(je,{...n})}}function Cy(e,t){return e===`ERROR`?{cardClass:`border-[#ff6b00]/50`,headerClass:`bg-[#ff6b00]/5`,glowClass:``}:e===`OK`?{cardClass:`border-[#0bda57]/30`,headerClass:`bg-[#0bda57]/5`,glowClass:``}:t?{cardClass:`border-[#11a4d4]/50`,headerClass:`bg-[#11a4d4]/5`,glowClass:`shadow-[0_0_10px_rgba(17,164,212,0.1)]`}:{cardClass:`border-slate-700`,headerClass:`bg-[#151f24]`,glowClass:``}}function wy({notification:e}){let t=[[`completed`,`text-green-500`,e.completed],[`failed`,`text-red-400`,e.failed],[`cancelled`,`text-slate-400`,e.cancelled],[`running`,`text-[#11a4d4]`,e.running]].map(([e,t,n])=>({name:e,color:t,runs:Array.isArray(n)?n.filter(Dy):[]})).filter(e=>e.runs.length>0);return t.length===0?(0,M.jsx)(`div`,{className:`text-xs text-slate-400`,children:`No yielded run updates.`}):(0,M.jsx)(`div`,{className:`grid gap-2`,children:t.map(e=>(0,M.jsxs)(`div`,{children:[(0,M.jsx)(`div`,{className:`mb-1 text-[10px] font-bold uppercase tracking-wider ${e.color}`,children:e.name}),(0,M.jsx)(`div`,{className:`grid gap-1`,children:e.runs.map((t,n)=>(0,M.jsxs)(`div`,{className:`grid grid-cols-[minmax(0,1fr)_auto] gap-2 rounded-sm border border-slate-700/60 bg-[#0e1116]/60 px-2 py-1.5`,children:[(0,M.jsxs)(`div`,{className:`min-w-0`,children:[(0,M.jsx)(`div`,{className:`truncate font-mono text-xs text-slate-200`,children:Ty(t.toolName)||`yielded tool`}),(0,M.jsx)(`div`,{className:`truncate font-mono text-[10px] text-slate-500`,children:Ty(t.runId)})]}),(0,M.jsx)(`div`,{className:`font-mono text-[10px] uppercase text-slate-400`,children:Ty(t.status)||e.name})]},`${e.name}-${n}`))})]},e.name))})}function Ty(e){return typeof e==`string`?e:``}function Ey(e,t){let n=(e-t)/1e3,r=Math.floor(n/6e4),i=Math.floor(n%6e4/1e3),a=Math.floor(n%1e3);return`${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}.${String(a).padStart(3,`0`)}`}function Dy(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Oy(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}var ky=5e3,Ay=50,jy=new Map;function My(e){let t=jy.get(e);return t||(t={snapshots:[],pending:null,pendingTimer:null},jy.set(e,t)),t}function Ny(){try{return localStorage.getItem(`pibo.chat.traceDebug`)===`true`}catch{return!1}}function Py(e){let t=0;for(let n of e)for(let e=0;e<n.length;e++){let r=n.charCodeAt(e);t=(t<<5)-t+r,t|=0}return t.toString(36)}function Fy(e){if(!e.pending)return;let t=e.pending;if(t.layers.length===0){e.pending=null;return}let n=e.snapshots.at(-1);n&&n.trigger===t.trigger&&n.traceVersion===t.traceVersion&&JSON.stringify(n.layers.map(e=>e.ids))===JSON.stringify(t.layers.map(e=>e.ids))||(e.snapshots.push(t),e.snapshots.length>ky&&e.snapshots.shift()),e.pending=null}function Iy(e){if(!Ny())return;let t=My(e.piboSessionId);if(t.pendingTimer&&=(clearTimeout(t.pendingTimer),null),(!t.pending||t.pending.trigger!==e.trigger||t.pending.piboSessionId!==e.piboSessionId)&&(Fy(t),t.pending={timestamp:Date.now(),piboSessionId:e.piboSessionId,trigger:e.trigger,layers:[],expansionOverrides:e.expansionOverrides,traceVersion:e.traceVersion,latestStreamId:e.latestStreamId,lastRawEventId:e.lastRawEventId}),e.layer){let n=t.pending.layers.findIndex(t=>t.kind===e.layer.kind);n>=0?t.pending.layers[n]=e.layer:t.pending.layers.push(e.layer)}e.expansionOverrides!==void 0&&(t.pending.expansionOverrides=e.expansionOverrides),t.pendingTimer=setTimeout(()=>{Fy(t),t.pendingTimer=null},Ay)}function Ly(e,t,n,r){let i=Vy(n);Iy({piboSessionId:e,trigger:t,layer:{kind:`backendNodes`,ids:i.map(e=>e.id),digest:Py(i.map(e=>e.id)),meta:i.map(e=>({id:e.id,type:e.type,orderKey:JSON.stringify(e.orderKey),parentId:e.parentId}))},...r})}function Ry(e){let t=jy.get(e);return t?(Fy(t),t.snapshots):[]}function zy(e){if(e){let t=Ry(e);return JSON.stringify({piboSessionId:e,snapshots:t},null,2)}let t={};for(let[e,n]of jy)Fy(n),t[e]=n.snapshots;return JSON.stringify(t,null,2)}function By(e){e?jy.delete(e):jy.clear()}function Vy(e){return e.flatMap(e=>[e,...Vy(e.children??[])])}typeof window<`u`&&(window.__piboTraceSnapshots={exportAsJson:e=>{let t=zy(e),n=new Blob([t],{type:`application/json`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=`trace-snapshots-${e??`all`}-${Date.now()}.json`,i.click(),URL.revokeObjectURL(r)},getSnapshots:Ry,clearSnapshots:By,exportSnapshots:zy});function Hy(e){if(e==null)return{kind:`empty`};let t=Uy(e);return t===void 0?{kind:`json`,value:e}:{kind:`text`,text:t}}function Uy(e){if(typeof e==`string`)return e;if(Array.isArray(e)){let t=e.map(Uy).filter(e=>e!==void 0);return t.length===e.length&&t.length>0?t.join(``):void 0}if(!Gy(e))return;let t=typeof e.type==`string`?e.type:void 0;if(t===`text`&&typeof e.text==`string`)return e.text;if(t===`text`&&typeof e.content==`string`)return e.content;if(t===`output_text`&&typeof e.text==`string`)return e.text;let n=Uy(e.content);if(n!==void 0&&Wy(e))return n;let r=Gy(e.message)?Uy(e.message.content):void 0;if(r!==void 0)return r}function Wy(e){let t=Object.keys(e).filter(t=>e[t]!==void 0);return t.length===1&&t[0]===`content`||t.every(e=>e===`content`||e===`type`)||t.every(e=>e===`content`||e===`details`||e===`type`)?!0:typeof e.type==`string`&&e.type.includes(`text`)}function Gy(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Ky({row:e,onOpenSession:t}){return(0,M.jsx)(`div`,{className:`mt-2 border border-[#2a2a2a] bg-[#111111] px-3 py-2 text-[12px] text-[#d4d4d4]`,"data-shared-terminal-details":e.kind,children:e.detailItems?.length?(0,M.jsx)(`div`,{className:`space-y-3`,children:e.detailItems.map(e=>(0,M.jsxs)(`div`,{className:`space-y-2`,children:[(0,M.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px]`,children:[(0,M.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:e.label}),e.linkedPiboSessionId?(0,M.jsx)(`button`,{type:`button`,onClick:()=>t(e.linkedPiboSessionId),className:`border border-[#3a3a3a] px-2 py-0.5 text-[#38bdf8] hover:border-[#38bdf8]`,children:`Open Session`}):null]}),(0,M.jsx)(qy,{label:`Input`,value:e.input}),(0,M.jsx)(qy,{label:`Output`,value:e.output}),(0,M.jsx)(Jy,{value:e.output}),e.error?(0,M.jsx)(Zy,{label:`Error`,value:e.error,tone:`red`}):null]},e.id))}):(0,M.jsxs)(`div`,{className:`space-y-3`,children:[(0,M.jsx)(qy,{label:`Input`,value:e.input}),(0,M.jsx)(qy,{label:`Output`,value:e.output}),(0,M.jsx)(Jy,{value:e.output}),e.error?(0,M.jsx)(Zy,{label:`Error`,value:e.error,tone:`red`}):null,e.linkedPiboSessionId?(0,M.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px]`,children:[(0,M.jsx)(`span`,{className:`text-[#737373]`,children:`Child session`}),(0,M.jsx)(`button`,{type:`button`,onClick:()=>t(e.linkedPiboSessionId),className:`border border-[#3a3a3a] px-2 py-0.5 text-[#38bdf8] hover:border-[#38bdf8]`,children:e.linkedPiboSessionId})]}):null]})})}function qy({label:e,value:t}){let n=Hy(t);if(n.kind===`empty`)return null;if(n.kind===`text`){let t=Qy(n.text);return t?.kind===`json`?(0,M.jsx)(Xy,{label:e,value:t.value,meta:t.meta}):t?.kind===`text`?(0,M.jsx)(Zy,{label:e,value:t.text}):(0,M.jsx)(Zy,{label:e,value:n.text})}return(0,M.jsx)(Xy,{label:e,value:n.value})}function Jy({value:e}){let t=Yy(e);return t?(0,M.jsxs)(`details`,{className:`space-y-1 border border-[#2a2a2a] bg-[#0b0b0b] p-2`,children:[(0,M.jsxs)(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-[#38bdf8]`,children:[`Show full output (`,t.originalLines,` lines)`]}),t.fullOutput?(0,M.jsx)(`pre`,{className:`mt-2 max-h-[520px] overflow-auto whitespace-pre-wrap break-words font-mono text-[12px] leading-[1.45] text-[#d4d4d4]`,children:t.fullOutput}):t.fullOutputPath?(0,M.jsxs)(`div`,{className:`mt-2 min-w-0 break-words font-mono text-[12px] text-[#d4d4d4]`,children:[`Full output file: `,t.fullOutputPath]}):null]}):null}function Yy(e){if(!tb(e))return;let t=tb(e.details)?e.details.piboBashOutputCompaction:void 0;if(!tb(t)||t.kind!==`validation-output`)return;let n=typeof t.originalLines==`number`?t.originalLines:void 0;if(n!==void 0)return{originalLines:n,fullOutput:typeof t.fullOutput==`string`?t.fullOutput:void 0,fullOutputPath:typeof t.fullOutputPath==`string`?t.fullOutputPath:void 0}}function Xy({label:e,value:t,meta:n}){return(0,M.jsxs)(`div`,{className:`space-y-1`,"data-shared-terminal-detail-json":e,children:[(0,M.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,M.jsx)(`div`,{className:`text-[11px] font-semibold text-[#737373]`,"data-shared-terminal-detail-label":e,children:e}),n?(0,M.jsxs)(`div`,{className:`min-w-0 break-words text-[11px] text-[#737373]`,children:[`Status: `,n]}):null]}),(0,M.jsx)(`div`,{className:`compact-terminal-json border border-[#2a2a2a] bg-[#0b0b0b] p-2`,children:(0,M.jsx)(Sc,{value:t,showControls:!1})})]})}function Zy({label:e,value:t,tone:n=`default`}){return(0,M.jsxs)(`div`,{className:`space-y-1`,"data-shared-terminal-detail-text":e,children:[(0,M.jsx)(`div`,{className:`text-[11px] font-semibold text-[#737373]`,"data-shared-terminal-detail-label":e,children:e}),(0,M.jsx)(`pre`,{className:`m-0 whitespace-pre-wrap break-words border border-[#2a2a2a] bg-[#0b0b0b] p-2 font-mono text-[12px] leading-[1.45] ${n===`red`?`text-[#ef4444]`:`text-[#d4d4d4]`}`,children:t})]})}function Qy(e){let t=e.trim();if(!t)return;let n=eb(t);if(n!==void 0)return $y(n);let r=t.split(/\r?\n/);for(let e=1;e<r.length;e+=1){let t=r.slice(e).join(`
39
39
  `).trim();if(!t.startsWith(`{`)&&!t.startsWith(`[`))continue;let n=eb(t);if(n!==void 0)return $y(n,r.slice(0,e).join(` `).trim()||void 0)}}function $y(e,t){let n=Hy(e);if(n.kind===`text`){let e=Qy(n.text);return e?.kind===`json`?{...e,meta:e.meta??t}:{kind:`text`,text:n.text}}return{kind:`json`,value:e,meta:t}}function eb(e){if(!(!e.startsWith(`{`)&&!e.startsWith(`[`)))try{let t=JSON.parse(e);return typeof t==`object`&&t?t:void 0}catch{return}}function tb(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function nb({name:e,input:t}){return(0,M.jsxs)(`span`,{className:`compact-terminal-function-call`,children:[(0,M.jsx)(`span`,{className:`text-[#facc15] font-semibold`,children:e}),(0,M.jsx)(`span`,{className:`text-[#d4d4d4]`,children:`(`}),t===void 0?null:(0,M.jsx)(rb,{value:t}),(0,M.jsx)(`span`,{className:`text-[#d4d4d4]`,children:`)`})]})}function rb({value:e}){let[t,n]=(0,v.useState)(()=>new Set([`$`])),[r,i]=(0,v.useState)(()=>new Set);return(0,M.jsx)(ib,{value:e,path:`$`,expandedPaths:t,expandedStrings:r,onTogglePath:e=>{n(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},onToggleString:e=>{i(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}})}function ib({value:e,path:t,expandedPaths:n,expandedStrings:r,onTogglePath:i,onToggleString:a}){if(Array.isArray(e))return(0,M.jsx)(ab,{value:e,path:t,open:`[`,close:`]`,expandedPaths:n,expandedStrings:r,onTogglePath:i,onToggleString:a});if(sb(e))return(0,M.jsx)(ab,{value:e,path:t,open:`{`,close:`}`,expandedPaths:n,expandedStrings:r,onTogglePath:i,onToggleString:a});if(typeof e==`string`){let n=r.has(t),i=e.length>140&&!n,o=i?`${e.slice(0,140)}...`:e,s=(0,M.jsx)(`span`,{className:`text-[#fb923c]`,children:JSON.stringify(o)});return!i&&e.length<=140?s:(0,M.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),a(t)},className:`compact-terminal-json-toggle text-left align-baseline`,title:n?`Collapse string`:`Expand string`,children:s})}return typeof e==`number`||typeof e==`boolean`||e===null?(0,M.jsx)(`span`,{className:`text-[#60a5fa]`,children:String(e)}):(0,M.jsx)(`span`,{className:`text-[#737373]`,children:JSON.stringify(String(e))})}function ab({value:e,path:t,open:n,close:r,expandedPaths:i,expandedStrings:a,onTogglePath:o,onToggleString:s}){let c=Array.isArray(e)?e.map((e,t)=>[String(t),e]):Object.entries(e);return i.has(t)?(0,M.jsxs)(`span`,{children:[(0,M.jsxs)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),o(t)},className:`compact-terminal-json-toggle align-baseline text-[#737373]`,title:`Collapse JSON`,"aria-label":`Collapse JSON at ${t}`,"data-inline-json-path":t,children:[(0,M.jsx)(`span`,{className:`compact-terminal-json-caret`,children:`▾`}),n]}),c.map(([n,r],c)=>{let l=`${t}.${ob(n)}`;return(0,M.jsxs)(`span`,{children:[c>0?(0,M.jsx)(`span`,{className:`text-[#737373]`,children:`, `}):null,Array.isArray(e)?null:(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(`span`,{className:`text-[#d4d4d4]`,children:JSON.stringify(n)}),(0,M.jsx)(`span`,{className:`text-[#737373]`,children:`:`})]}),(0,M.jsx)(ib,{value:r,path:l,expandedPaths:i,expandedStrings:a,onTogglePath:o,onToggleString:s})]},l)}),(0,M.jsx)(`span`,{className:`text-[#737373]`,children:r})]}):(0,M.jsxs)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),o(t)},className:`compact-terminal-json-toggle align-baseline text-[#737373]`,title:`Expand JSON`,"aria-label":`Expand JSON at ${t}`,"data-inline-json-path":t,children:[(0,M.jsx)(`span`,{className:`compact-terminal-json-caret`,children:`▸`}),n,`...`,r]})}function ob(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`.`,`\\.`)}function sb(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function cb({line:e,status:t,clampLines:n}){let r=`min-w-0 whitespace-pre-wrap break-words ${n?`block overflow-hidden`:``}`;return(0,M.jsxs)(`div`,{className:`grid grid-cols-[1.9rem_minmax(0,1fr)] gap-2 leading-[1.45]`,children:[(0,M.jsx)(`span`,{className:`whitespace-pre ${ub(e.prefix,t)}`,children:lb(e.prefix)}),(0,M.jsxs)(`span`,{className:r,style:n?{maxHeight:`${n*1.45}em`}:void 0,children:[e.tokens.map((e,t)=>(0,M.jsx)(`span`,{className:db(e),children:e.text},`${t}:${e.text}`)),e.functionCall?(0,M.jsx)(nb,{name:e.functionCall.name,input:e.functionCall.input}):null]})]})}function lb(e=`none`){switch(e){case`bullet`:return`•`;case`detail`:return`└`;case`continuation`:return` `;case`prompt`:return`›`;default:return` `}}function ub(e=`none`,t){if(e===`bullet`){if(t===`running`)return`text-[#38bdf8]`;if(t===`error`)return`text-[#ef4444]`;if(t===`done`)return`text-[#22c55e]`}return`text-[#737373]`}function db(e){return`${e.tone===`dim`?`text-[#737373]`:e.tone===`cyan`?`text-[#38bdf8]`:e.tone===`green`?`text-[#22c55e]`:e.tone===`red`?`text-[#ef4444]`:e.tone===`magenta`?`text-[#d946ef]`:e.tone===`yellow`?`text-[#facc15]`:e.tone===`blue`?`text-[#60a5fa]`:e.tone===`amber`?`text-[#f59e0b]`:`text-[#d4d4d4]`} ${e.weight===`bold`?`font-bold`:e.weight===`semibold`?`font-semibold`:`font-normal`} ${e.italic?`italic`:``}`.trim()}async function fb(e,t){let n=new URLSearchParams({piboSessionId:e}),r=await fetch(`/api/chat/trace/summary?${n.toString()}`,{headers:t?{"if-none-match":mb(t)}:void 0});if(r.status===304)return{notModified:!0,version:hb(r.headers.get(`etag`))??t};let i=await r.json().catch(()=>void 0);if(!r.ok){let e=i&&typeof i==`object`&&`error`in i?String(i.error):`Request failed`,t=Error(e);throw t.status=r.status,t.data=i,t}return{summary:i,notModified:!1,version:hb(r.headers.get(`etag`))??i.version}}async function pb(e,t={}){let n=new URLSearchParams({piboSessionId:e});t.includeRawEvents&&n.set(`includeRawEvents`,`true`),t.rawEventsLimit&&n.set(`rawEventsLimit`,String(t.rawEventsLimit)),t.pageSize&&n.set(`pageSize`,String(t.pageSize)),t.beforeSequence===void 0?t.eventLimit&&n.set(`eventLimit`,String(t.eventLimit)):n.set(`beforeSequence`,String(t.beforeSequence));let r=await fetch(`/api/chat/trace?${n.toString()}`,{headers:t.knownVersion?{"if-none-match":mb(t.knownVersion)}:void 0});if(r.status===304)return{notModified:!0,version:hb(r.headers.get(`etag`))??t.knownVersion};let i=await r.json().catch(()=>void 0);if(!r.ok){let e=i&&typeof i==`object`&&`error`in i?String(i.error):`Request failed`,t=Error(e);throw t.status=r.status,t.data=i,t}return{trace:i,notModified:!1,version:hb(r.headers.get(`etag`))??i.version}}function mb(e){return`"${e}"`}function hb(e){if(!e)return;let t=e.trim();return t.startsWith(`W/`)?hb(t.slice(2)):t.startsWith(`"`)&&t.endsWith(`"`)?t.slice(1,-1):t}async function gb(e,t={}){let n=new URLSearchParams({piboSessionId:e});return t.status&&n.set(`status`,t.status),t.limit&&n.set(`limit`,String(t.limit)),t.scope&&n.set(`scope`,t.scope),O(`/api/web-annotations?${n.toString()}`)}async function _b(e,t){return O(`/api/web-annotations/${encodeURIComponent(e)}`,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify(xb(t))})}async function vb(e){let t=new URLSearchParams;return e?.trim()&&t.set(`cdpUrl`,e.trim()),O(`/api/web-annotations/targets${t.size?`?${t.toString()}`:``}`)}async function yb(e){return O(`/api/web-annotations/bindings`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(xb(e))})}async function bb(e,t){return O(`/api/web-annotations/bindings/${encodeURIComponent(e)}/inject`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(xb(t))})}function xb(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0&&e!==``))}async function Sb(e,t,n){return O(`/api/chat/projects/${encodeURIComponent(e)}/workflow-sessions/${encodeURIComponent(t)}/human-actions`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n)})}function Cb(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return t.action===`show_login_menu`&&Array.isArray(t.providers)}function wb(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return t.action===`show_model_menu`&&Array.isArray(t.providers)}function Tb(e){return Eb(e)?e.result:e}function Eb(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.type===`execution_result`}var Db={device_code:`Device code`,api_key:`API key`,oauth:`Browser OAuth`};function Ob({row:e,piboSessionId:t}){let n=Cb(e.output)?e.output:void 0,r=(0,v.useMemo)(()=>n?.providers??[],[n?.providers]),[i,a]=(0,v.useState)({type:`select_provider`}),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(``),[u,d]=(0,v.useState)(``),[f,p]=(0,v.useState)(null),m=(0,v.useCallback)(()=>{a({type:`select_provider`}),l(``),d(``)},[]),h=(0,v.useCallback)(async e=>{try{await navigator.clipboard.writeText(e),p(e),window.setTimeout(()=>p(t=>t===e?null:t),1600)}catch{}},[]),g=(0,v.useCallback)(async e=>{if(!t){a({type:`error`,provider:e,message:`Select a chat session before starting login.`});return}s(!0),a({type:`device_starting`,provider:e});try{let n=Tb(await oe(t,`login.start`,{provider:e.id}));if(!n?.url){a({type:`error`,provider:e,message:`No login URL returned.`});return}a({type:`device_flow`,provider:e,url:n.url,state:n.state,userCode:n.userCode,instructions:n.instructions})}catch(t){a({type:`error`,provider:e,message:t instanceof Error?t.message:String(t)})}finally{s(!1)}},[t]),_=(0,v.useCallback)(async(e,n,r)=>{if(t){s(!0);try{await oe(t,`login.complete`,{provider:e.id,state:n??``,...r?{code:r}:{}}),a({type:`success`,provider:e,message:`${e.name} login completed.`})}catch(t){a({type:`error`,provider:e,message:t instanceof Error?t.message:String(t)})}finally{s(!1)}}},[t]),y=(0,v.useCallback)(async e=>{if(!t)return;let n=c.trim();if(n){s(!0);try{await oe(t,`login.apikey`,{provider:e.id,apiKey:n}),l(``),a({type:`success`,provider:e,message:`${e.name} API key saved.`})}catch(t){a({type:`error`,provider:e,message:t instanceof Error?t.message:String(t)})}finally{s(!1)}}},[c,t]);return n?(0,M.jsx)(kb,{title:i.type===`select_provider`?`Login`:Mb(i),tone:i.type===`error`?`red`:i.type===`success`?`green`:`cyan`,action:i.type===`select_provider`?void 0:(0,M.jsx)(Ab,{onClick:m,disabled:o}),children:i.type===`select_provider`?(0,M.jsxs)(`div`,{className:`grid gap-2`,children:[(0,M.jsxs)(`div`,{className:`text-[11px] text-[#737373]`,children:[`Choose a provider. Use `,(0,M.jsx)(`span`,{className:`text-[#38bdf8]`,children:`/login`}),` anytime.`]}),(0,M.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:r.map(e=>(0,M.jsxs)(`button`,{type:`button`,onClick:()=>a({type:`select_method`,provider:e}),className:`inline-flex items-center gap-1 border border-[#3a3a3a] bg-transparent px-2 py-1 text-[11px] text-[#d4d4d4] hover:border-[#38bdf8] hover:text-[#38bdf8]`,children:[(0,M.jsx)(`span`,{children:e.name}),e.configured?(0,M.jsx)(`span`,{className:`text-[#22c55e]`,children:`●`}):null]},e.id))})]}):i.type===`select_method`?(0,M.jsxs)(`div`,{className:`grid gap-2`,children:[(0,M.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px]`,children:[(0,M.jsx)(`span`,{className:`text-[#737373]`,children:`Provider:`}),(0,M.jsx)(`span`,{className:`text-[#d4d4d4]`,children:i.provider.name}),i.provider.configured?(0,M.jsx)(jb,{tone:`green`,children:`Configured`}):(0,M.jsx)(jb,{tone:`neutral`,children:`Not configured`})]}),(0,M.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:i.provider.authMethods.map(e=>(0,M.jsxs)(`button`,{type:`button`,onClick:()=>e===`api_key`?a({type:`api_key`,provider:i.provider}):void g(i.provider),className:`inline-flex items-center gap-1 border border-[#3a3a3a] bg-transparent px-2 py-1 text-[11px] text-[#d4d4d4] hover:border-[#38bdf8] hover:text-[#38bdf8]`,children:[e===`api_key`?(0,M.jsx)(nt,{size:11}):(0,M.jsx)(st,{size:11}),Db[e]]},e))})]}):i.type===`device_starting`?(0,M.jsxs)(`div`,{className:`inline-flex items-center gap-2 text-[11px] text-[#38bdf8]`,children:[(0,M.jsx)(ot,{size:13,className:`animate-spin`}),` Starting device login...`]}):i.type===`device_flow`?(0,M.jsxs)(`div`,{className:`grid gap-2 text-[11px]`,children:[(0,M.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,M.jsx)(`span`,{className:`text-[#737373]`,children:`Open:`}),(0,M.jsxs)(`a`,{href:i.url,target:`_blank`,rel:`noreferrer`,className:`inline-flex items-center gap-1 text-[#38bdf8] hover:underline`,children:[Nb(i.url),` `,(0,M.jsx)(qe,{size:11})]}),(0,M.jsxs)(`button`,{type:`button`,onClick:()=>void h(i.url),className:`inline-flex items-center gap-1 border border-[#3a3a3a] px-1.5 py-0.5 text-[#737373] hover:border-[#38bdf8] hover:text-[#38bdf8]`,children:[f===i.url?(0,M.jsx)(Be,{size:10}):(0,M.jsx)(We,{size:10}),` `,f===i.url?`Copied`:`Copy`]})]}),i.userCode?(0,M.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,M.jsx)(`span`,{className:`text-[#737373]`,children:`Code:`}),(0,M.jsx)(`button`,{type:`button`,onClick:()=>void h(i.userCode),className:`border border-[#1f4960] px-2 py-0.5 font-semibold tracking-widest text-[#38bdf8] hover:border-[#38bdf8]`,children:i.userCode}),(0,M.jsx)(`span`,{className:`text-[#737373]`,children:`then`}),(0,M.jsxs)(`button`,{type:`button`,disabled:o,onClick:()=>void _(i.provider,i.state),className:`inline-flex items-center gap-1 border border-[#3a3a3a] px-2 py-0.5 text-[#d4d4d4] hover:border-[#38bdf8] hover:text-[#38bdf8] disabled:opacity-50`,children:[o?(0,M.jsx)(ot,{size:11,className:`animate-spin`}):(0,M.jsx)(Be,{size:11}),` Complete`]})]}):(0,M.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,M.jsx)(`input`,{value:u,onChange:e=>d(e.target.value),placeholder:`authorization code`,className:`min-w-0 flex-1 border border-[#2a2a2a] bg-[#0b0b0b] px-2 py-1 text-[11px] text-[#d4d4d4] outline-none focus:border-[#38bdf8]`}),(0,M.jsxs)(`button`,{type:`button`,disabled:o||!u.trim(),onClick:()=>void _(i.provider,i.state,u.trim()),className:`inline-flex items-center gap-1 border border-[#3a3a3a] px-2 py-1 text-[#d4d4d4] hover:border-[#38bdf8] hover:text-[#38bdf8] disabled:opacity-50`,children:[o?(0,M.jsx)(ot,{size:11,className:`animate-spin`}):(0,M.jsx)(Be,{size:11}),` Complete`]})]}),i.instructions?(0,M.jsx)(`div`,{className:`text-[#737373]`,children:i.instructions}):null]}):i.type===`api_key`?(0,M.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 text-[11px]`,children:[(0,M.jsx)(`span`,{className:`text-[#737373]`,children:`API key:`}),(0,M.jsx)(`input`,{type:`password`,value:c,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&y(i.provider)},placeholder:`sk-...`,className:`min-w-[12rem] flex-1 border border-[#2a2a2a] bg-[#0b0b0b] px-2 py-1 text-[11px] text-[#d4d4d4] outline-none focus:border-[#38bdf8]`}),(0,M.jsxs)(`button`,{type:`button`,disabled:o||!c.trim(),onClick:()=>void y(i.provider),className:`inline-flex items-center gap-1 border border-[#3a3a3a] px-2 py-1 text-[#d4d4d4] hover:border-[#38bdf8] hover:text-[#38bdf8] disabled:opacity-50`,children:[o?(0,M.jsx)(ot,{size:11,className:`animate-spin`}):(0,M.jsx)(Be,{size:11}),` Save`]})]}):i.type===`success`?(0,M.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px] text-[#22c55e]`,children:[(0,M.jsx)(Be,{size:13}),` `,i.message]}):(0,M.jsxs)(`div`,{className:`flex items-start gap-2 text-[11px] text-[#ef4444]`,children:[(0,M.jsx)(Re,{size:13,className:`mt-0.5 shrink-0`}),` `,(0,M.jsx)(`span`,{children:i.message})]})}):(0,M.jsx)(kb,{title:`Login`,tone:`red`,children:`Unparseable login payload.`})}function kb({title:e,tone:t,action:n,children:r}){return(0,M.jsxs)(`div`,{className:`mt-2 border border-[#2a2a2a] bg-[#111111] px-3 py-2 text-[12px] text-[#d4d4d4]`,"data-shared-terminal-card":`login`,children:[(0,M.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[(0,M.jsx)(st,{size:14,className:t===`red`?`text-[#ef4444]`:t===`green`?`text-[#22c55e]`:`text-[#38bdf8]`}),(0,M.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:e}),n?(0,M.jsx)(`div`,{className:`ml-auto`,children:n}):null]}),r]})}function Ab({onClick:e,disabled:t}){return(0,M.jsxs)(`button`,{type:`button`,disabled:t,onClick:e,className:`inline-flex items-center gap-1 border border-[#3a3a3a] bg-transparent px-1.5 py-0.5 text-[11px] text-[#737373] hover:border-[#38bdf8] hover:text-[#38bdf8] disabled:opacity-50`,children:[(0,M.jsx)(we,{size:10}),` Back`]})}function jb({tone:e,children:t}){return(0,M.jsx)(`span`,{className:`border px-1.5 py-0.5 text-[10px] ${e===`green`?`border-[#14532d] text-[#22c55e]`:`border-[#3a3a3a] text-[#737373]`}`,children:t})}function Mb(e){return`provider`in e&&e.provider?e.provider.name:`Login`}function Nb(e){try{let t=new URL(e);return`${t.host}${t.pathname}`}catch{return e.length>42?`${e.slice(0,39)}...`:e}}function Pb({row:e,piboSessionId:t,onModelChanged:n}){let r=Tb(e.output),i=(wb(r)?r:void 0)?.providers??[],a=(0,v.useMemo)(()=>i.flatMap(e=>e.models.map(t=>({...t,providerLabel:e.label}))),[i]),[o,s]=(0,v.useState)(``),[c,l]=(0,v.useState)(null),[u,d]=(0,v.useState)(!1),[f,p]=(0,v.useState)(null),m=(0,v.useMemo)(()=>{let e=o.trim().toLowerCase();return e?a.filter(t=>`${t.providerLabel} ${t.provider} ${t.label} ${t.id}`.toLowerCase().includes(e)):a},[a,o]),h=async e=>{if(!(!t||u)){d(!0),l(e),p(null);try{await re(t,{activeModel:{provider:e.provider,id:e.id}}),p(`Selected ${e.provider}/${e.id}.`),await n?.()}catch(e){p(e instanceof Error?e.message:String(e))}finally{d(!1)}}};return(0,M.jsxs)(`div`,{className:`ml-[1.9rem] max-w-3xl border border-[#3a3a3a] bg-[#111111] text-[12px] shadow-lg`,"data-shared-terminal-card":`model`,children:[(0,M.jsx)(`div`,{className:`flex items-center justify-between gap-3 border-b border-[#2a2a2a] px-3 py-2`,children:(0,M.jsxs)(`div`,{children:[(0,M.jsx)(`div`,{className:`text-[#d4d4d4]`,children:`Model`}),(0,M.jsxs)(`div`,{className:`text-[11px] text-[#737373]`,children:[`Choose a model from authenticated providers. Use `,(0,M.jsx)(`span`,{className:`text-[#38bdf8]`,children:`/login`}),` to add providers.`]})]})}),(0,M.jsxs)(`div`,{className:`space-y-2 p-3`,children:[i.length?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsxs)(`label`,{className:`flex items-center gap-2 border border-[#2a2a2a] bg-[#0b0b0b] px-2 py-1 text-[#737373]`,children:[(0,M.jsx)(pt,{size:13}),(0,M.jsx)(`input`,{value:o,onChange:e=>s(e.target.value),placeholder:`Search models`,className:`min-w-0 flex-1 bg-transparent text-[#d4d4d4] outline-none placeholder:text-[#525252]`})]}),(0,M.jsx)(`div`,{className:`max-h-72 overflow-auto border border-[#2a2a2a]`,children:m.length?m.map(e=>(0,M.jsxs)(`button`,{type:`button`,disabled:u,onClick:()=>void h(e),className:`grid w-full grid-cols-[150px_1fr_auto] gap-2 border-b border-[#1f1f1f] px-3 py-2 text-left hover:bg-[#38bdf8]/10 disabled:opacity-50`,children:[(0,M.jsx)(`span`,{className:`truncate text-[#737373]`,children:e.providerLabel}),(0,M.jsxs)(`span`,{className:`min-w-0`,children:[(0,M.jsx)(`span`,{className:`block truncate text-[#d4d4d4]`,children:e.label}),(0,M.jsxs)(`span`,{className:`block truncate text-[11px] text-[#737373]`,children:[e.provider,`/`,e.id]})]}),c?.provider===e.provider&&c?.id===e.id?(0,M.jsx)(je,{size:14,className:`text-[#22c55e]`}):null]},`${e.provider}:${e.id}`)):(0,M.jsx)(`div`,{className:`px-3 py-2 text-[#737373]`,children:`No matching models.`})})]}):(0,M.jsxs)(`div`,{className:`text-[#737373]`,children:[`No authenticated model providers found. Run `,(0,M.jsx)(`span`,{className:`text-[#38bdf8]`,children:`/login`}),` first.`]}),f?(0,M.jsx)(`div`,{className:`text-[11px] text-[#a3a3a3]`,children:f}):null]})]})}function Fb(e={}){let t=[],n=[],r=Hb(e.warnings),i=Hb(e.errors);(e.session?.id||e.session?.title)&&t.push({id:`session`,label:`Session`,value:Ib([e.session?.title,e.session?.id].filter(Boolean).join(` | `))}),e.session?.profile&&t.push({id:`profile`,label:`Profile`,value:Ib(e.session.profile)}),e.session?.status&&t.push({id:`session-status`,label:`Session status`,value:Ib(e.session.status),tone:e.session.status===`error`||e.session.status===`disposed`?`red`:`neutral`}),(e.model?.provider||e.model?.id||e.model?.label)&&t.push({id:`model`,label:`Model`,value:Ib(e.model.label??[e.model.provider,e.model.id].filter(Boolean).join(`/`))}),e.runtime?.state&&t.push({id:`runtime`,label:`Runtime`,value:Ib(e.runtime.state),tone:e.runtime.connected===!1||e.runtime.disposed?`red`:`green`}),e.runtime?.disposed!==void 0&&t.push({id:`disposed`,label:`Disposed`,value:e.runtime.disposed?`yes`:`no`,tone:e.runtime.disposed?`red`:`neutral`}),typeof e.runtime?.queuedMessages==`number`&&t.push({id:`queue`,label:`Queue`,value:String(e.runtime.queuedMessages)}),e.runtime?.processing!==void 0&&t.push({id:`processing`,label:`Processing`,value:e.runtime.processing?`yes`:`no`,tone:e.runtime.processing?`cyan`:`neutral`}),e.runtime?.streaming!==void 0&&t.push({id:`streaming`,label:`Streaming`,value:e.runtime.streaming?`yes`:`no`,tone:e.runtime.streaming?`cyan`:`neutral`}),e.cwd&&t.push({id:`cwd`,label:`CWD`,value:Ib(e.cwd)});let a=typeof e.thinking==`string`?{level:e.thinking}:e.thinking;(a?.level||a?.supported!==void 0)&&t.push({id:`thinking`,label:`Thinking`,value:Ib(a.level??(a.supported===!1?`unsupported`:`available`)),tone:a.supported===!1?`red`:`yellow`}),e.fastMode!==void 0&&t.push({id:`fast-mode`,label:`Fast mode`,value:typeof e.fastMode==`string`?Ib(e.fastMode):e.fastMode?`on`:`off`,tone:e.fastMode?`green`:`neutral`});let o=Hb(e.tools?.enabled),s=Hb(e.tools?.active);o.length&&t.push({id:`enabled-tools`,label:`Enabled tools`,value:`${o.length}${o.length<=4?` (${o.join(`, `)})`:``}`}),s.length&&t.push({id:`active-tools`,label:`Active tools`,value:`${s.length}${s.length<=4?` (${s.join(`, `)})`:``}`,tone:`cyan`}),e.providerUsage?.planType&&t.push({id:`provider-plan`,label:`Provider plan`,value:Ib(e.providerUsage.planType)}),e.providerUsage?.credits&&t.push({id:`provider-credits`,label:`Credits`,value:e.providerUsage.credits.unlimited?`unlimited`:Ib(e.providerUsage.credits.balance??`available`)}),e.message&&t.push({id:`message`,label:`Message`,value:Ib(e.message)}),n.push(Lb(e.contextUsage));for(let t of Rb(e.providerUsage))n.push(t);return{kind:`status`,title:`Status`,fields:t,progress:n,warnings:r,errors:i}}function Ib(e){return e.replace(/\b([A-Z0-9_]*(?:API[_-]?KEY|TOKEN|SECRET|PASSWORD)[A-Z0-9_]*)\s*=\s*([^\s]+)/gi,`$1=[redacted]`).replace(/\b(api[_-]?key|token|secret|password)\s*[:=]\s*([^\s]+)/gi,`$1=[redacted]`).replace(/\b(?:sk|pk|pibo|ghp|github_pat)_[A-Za-z0-9_\-]{8,}\b/g,`[redacted]`)}function Lb(e){if(!e||e.tokens===void 0&&e.contextWindow===void 0&&e.percent===void 0)return{id:`context`,label:`Context`,state:`unavailable`,text:`Context usage unavailable`,tone:`neutral`};let t=zb(e.percent??(e.tokens!==void 0&&e.contextWindow?e.tokens/e.contextWindow*100:void 0));return{id:`context`,label:`Context`,state:t===void 0?`unavailable`:`available`,value:e.tokens,max:e.contextWindow,percent:t,text:t===void 0?`Context usage unavailable`:`${e.tokens??`?`}/${e.contextWindow??`?`} tokens (${t.toFixed(1)}%)`,tone:Bb(t)}}function Rb(e){return e?.limits?.length?e.limits.map((t,n)=>{let r=zb(t.usedPercent),i=zb(t.remainingPercent??(r===void 0?void 0:100-r)),a=e.provider?`${e.provider} `:``,o=[i===void 0?void 0:`${i.toFixed(1)}% remaining`,t.resetsAt?`resets ${Ib(t.resetsAt)}`:void 0].filter(Boolean).join(`, `);return{id:`provider-${n}`,label:`${a}${t.label??`quota`}`.trim(),state:i===void 0?`unavailable`:`available`,percent:i,text:i===void 0?`Provider usage unavailable`:o,tone:Vb(i)}}):[{id:`provider`,label:`Provider quota`,state:`unavailable`,text:`Provider usage unavailable`,tone:`neutral`}]}function zb(e){if(!(typeof e!=`number`||!Number.isFinite(e)))return Math.max(0,Math.min(100,e))}function Bb(e){return e===void 0?`neutral`:e>=80?`red`:e>=50?`yellow`:`green`}function Vb(e){return e===void 0?`neutral`:e<=20?`red`:e<=50?`yellow`:`green`}function Hb(e){return(e??[]).map(e=>Ib(e)).filter(e=>e.length>0)}function Ub(e){switch(e.kind){case`tool.status`:return Wb(e);case`tool.thinking`:return Gb(e);case`tool.model`:return Kb(e);case`tool.login`:return qb(e);case`tool.call`:case`tool.image`:case`tool.group.exploring`:case`tool.group.images`:return Jb(e);case`yielded.run`:return Yb(e,`yielded-run`,`Yielded run`,e.status===`error`?`red`:e.status===`running`?`cyan`:`green`);case`execution.compaction`:return Yb(e,`compaction`,e.status===`error`?`Compaction failed`:e.status===`running`?`Compacting`:`Compaction`,e.status===`error`?`red`:`magenta`);case`execution.command`:return Yb(e,`command`,`Command`,e.status===`error`?`red`:`yellow`);case`error`:return Yb(e,`error`,`Error`,`red`);default:return}}function Wb(e){let t=Zb(e.output),n=Qb(t,`activeModel`)??Qb(t,`model`),r=Fb({session:{id:tx(t,`piboSessionId`)??tx(t,`sessionId`),title:tx(t,`sessionTitle`)??tx(t,`title`),profile:tx(t,`profile`)??tx(t,`activeAgentId`)??tx(t,`agentId`),status:rx(t,`disposed`)?`disposed`:tx(t,`sessionStatus`)},model:n?{provider:tx(n,`provider`),id:tx(n,`id`),label:tx(n,`label`)}:void 0,runtime:{state:rx(t,`disposed`)?`disposed`:rx(t,`processing`)?`processing`:rx(t,`streaming`)?`streaming`:tx(t,`mode`)??`idle`,connected:rx(t,`connected`),queuedMessages:nx(t,`queuedMessages`),processing:rx(t,`processing`),streaming:rx(t,`streaming`),disposed:rx(t,`disposed`)},cwd:tx(t,`cwd`),contextUsage:Qb(t,`contextUsage`),providerUsage:Qb(t,`providerUsage`),tools:{enabled:ex(t,`enabledTools`),active:ex(t,`activeTools`)},thinking:tx(t,`thinkingLevel`)?{level:tx(t,`thinkingLevel`)}:void 0,fastMode:rx(t,`fastMode`),warnings:ex(t,`warnings`),errors:ex(t,`errors`),message:tx(t,`message`)});return{id:e.id,kind:`status`,title:`Status`,status:e.status,tone:e.status===`error`?`red`:`green`,rows:r.fields.map(e=>({label:e.label,value:e.value,tone:e.tone})),statusView:r,sourceRowKind:e.kind}}function Gb(e){let t=Zb(e.output),n=tx(t,`level`)??`unknown`,r=t?.supported!==!1,i=ex(t,`availableLevels`);return{id:e.id,kind:`thinking`,title:`Thinking`,status:e.status,tone:r?`yellow`:`red`,rows:[{label:`Current`,value:Ib(n)},{label:`Supported`,value:r?`yes`:`no`,tone:r?`green`:`red`}],actions:i.map(e=>({id:`thinking:${e}`,label:e,action:`thinking.set`,value:e,disabled:!r})),sourceRowKind:e.kind}}function Kb(e){let t=$b(Zb(e.output),`providers`),n=t.flatMap(e=>{let t=tx(e,`id`)??tx(e,`provider`)??`provider`,n=tx(e,`label`)??tx(e,`name`)??t;return $b(e,`models`).map(e=>{let r=tx(e,`id`)??`model`,i=tx(e,`label`)??r;return{id:`model:${t}:${r}`,label:`${n} / ${i}`,action:`model.select`,value:`${t}/${r}`}})});return{id:e.id,kind:`model`,title:`Model`,status:e.status,tone:n.length?`cyan`:`neutral`,rows:[{label:`Providers`,value:String(t.length)},{label:`Models`,value:String(n.length)}],actions:n,sourceRowKind:e.kind}}function qb(e){let t=$b(Zb(e.output),`providers`),n=t.map(e=>{let t=tx(e,`id`)??`provider`;return{id:`login:${t}`,label:tx(e,`name`)??tx(e,`label`)??t,action:`login.selectProvider`,value:t,description:ex(e,`authMethods`).join(`, `)}});return{id:e.id,kind:`login`,title:`Login`,status:e.status,tone:n.length?`cyan`:`neutral`,rows:[{label:`Providers`,value:String(t.length)}],actions:n,sourceRowKind:e.kind}}function Jb(e){return Yb(e,`tool`,e.kind===`tool.group.exploring`?`Exploring`:e.kind===`tool.image`||e.kind===`tool.group.images`?`Image`:`Tool`,e.status===`error`?`red`:e.status===`running`?`cyan`:`green`)}function Yb(e,t,n,r){let i=e.lines.flatMap(e=>{let t=`${e.tokens.map(e=>e.text).join(``)}${e.functionCall?`${e.functionCall.name}${e.functionCall.input===void 0?``:` ${Xb(e.functionCall.input)}`}`:``}`.trim();return t?[{value:Ib(t)}]:[]}),a=e.lines.length===0&&typeof e.output==`string`&&e.output.trim()?[{value:Ib(e.output.trim())}]:[],o=[e.error?{label:`Error`,value:Ib(e.error),tone:`red`}:void 0].filter(e=>!!e);return{id:e.id,kind:t,title:n,status:e.status,tone:r,rows:[...i,...a,...o],sourceRowKind:e.kind}}function Xb(e){try{return JSON.stringify(e)}catch{return String(e)}}function Zb(e){if(e){if(typeof e==`string`)try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}return typeof e==`object`&&!Array.isArray(e)?e:void 0}}function Qb(e,t){let n=e?.[t];return n&&typeof n==`object`&&!Array.isArray(n)?n:void 0}function $b(e,t){let n=e?.[t];return Array.isArray(n)?n.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e)):[]}function ex(e,t){let n=e?.[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function tx(e,t){let n=e?.[t];return typeof n==`string`?n:void 0}function nx(e,t){let n=e?.[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function rx(e,t){let n=e?.[t];return typeof n==`boolean`?n:void 0}var ix={transcript:0,"event-log":1,live:2},ax={"user.message":0,"execution.command":1,"execution.compaction":1,"agent.turn":2,"model.reasoning":3,"tool.call":4,"agent.delegation":4,"agent.async":5,"tool.result":6,"yielded.run":7,"assistant.message":8,error:9};function ox(e,t){return{sourceRank:ix[`event-log`],turnSeq:e??2**53-1,eventSequence:e,phaseRank:ax[t]}}function sx(e,t,n){let r=e??2**53-1,i=t??2**53-1;return{sourceRank:ix.live,turnSeq:r,streamId:r,streamFrameIndex:i,phaseRank:ax[n]}}function cx(e){let[t,n]=e.split(`:`);if(t===void 0||n===void 0)return;let r=Number(t),i=Number(n);if(!(!Number.isInteger(r)||r<0)&&!(!Number.isInteger(i)||i<0))return{streamId:r,frameIndex:i}}function lx(e,t){if(e)return{...e,contentPartIndex:(e.contentPartIndex??0)+.1,phaseRank:ax[t]}}function ux(e,t){return!e&&!t?0:e?t?e.sourceRank-t.sourceRank||e.turnSeq-t.turnSeq||(e.transcriptIndex??2**53-1)-(t.transcriptIndex??2**53-1)||(e.eventSequence??2**53-1)-(t.eventSequence??2**53-1)||(e.streamId??2**53-1)-(t.streamId??2**53-1)||(e.streamFrameIndex??2**53-1)-(t.streamFrameIndex??2**53-1)||(e.contentPartIndex??0)-(t.contentPartIndex??0)||e.phaseRank-t.phaseRank:-1:1}function dx(e){let t=!1,n=e.map(e=>e.children.length?(t=!0,{...e,children:dx(e.children)}):e);return fx(n)?t?n:[...e]:[...n].sort(px)}function fx(e){for(let t=1;t<e.length;t+=1)if(px(e[t-1],e[t])>0)return!1;return!0}function px(e,t){let n=mx(e,t);if(n!==0)return n;let r=hx(e.startedAt,t.startedAt);if(r!==0)return r;let i=ux(e.orderKey,t.orderKey);return i===0?e.id.localeCompare(t.id):i}function mx(e,t){if(!e.eventId||e.eventId!==t.eventId)return 0;let n=e.orderKey?.phaseRank,r=t.orderKey?.phaseRank;return n===void 0||r===void 0?0:n-r}function hx(e,t){return!e&&!t?0:e?t?e.localeCompare(t):-1:1}function gx(e){let t=[],n=[...e].reverse();for(;n.length;){let e=n.pop();if(e){t.push(e);for(let t=e.children.length-1;t>=0;--t)n.push(e.children[t])}}return t}function _x(e,t,n,r){if(!vx(t))return;let i=r.get(e)?.filter(e=>e.metadata?.subagentToolName===t)??[],a=bx(n);return a?i.find(e=>e.metadata?.threadKey===a)?.id:i.length===1?i[0].id:void 0}function vx(e){return e.startsWith(`pibo_subagent_`)}function yx(e){return e.slice(14)}function bx(e){let t=`args`in e&&e.args&&typeof e.args==`object`&&!Array.isArray(e.args)?e.args:void 0,n=t&&`threadKey`in t?t.threadKey:void 0;return typeof n==`string`&&n.trim()?n.trim():void 0}function xx(e,t,n,r){let i=Cx(e,t,n,r);if(!i)return;let a=e.children.find(e=>e.id===i.id);if(a){Tx(a,i),a.runId=i.runId??a.runId;return}e.children.push(i)}function Sx(e){let t=new Map;for(let n of gx(e)){let e=Ex(n.output);if(!e)continue;let r=Ox(e.runId);r&&t.set(r,{snapshot:e,completedAt:Ox(e.completedAt)??Ox(e.updatedAt)??n.completedAt})}for(let n of gx(e)){if(n.type!==`agent.async`||!n.runId)continue;let e=t.get(n.runId);if(!e)continue;let r=Ox(e.snapshot.status);r!==`completed`&&r!==`cancelled`&&r!==`failed`||(n.status=r===`failed`?`error`:`done`,n.completedAt=e.completedAt??n.completedAt,n.output=e.snapshot,r===`failed`&&(n.error=Ox(e.snapshot.summary)??n.error))}}function Cx(e,t,n,r){if(!wx(e))return;let i=Ex(e.output),a=Ax(e.input)?e.input:{},o=Ox(i?.toolName)??Ox(a.toolName)??r?.title;if(!o||!vx(o))return;let s=Ox(r?.summary)??yx(o),c=Ox(i?.runId),l=Ox(i?.status),u=a.arguments,d=Ox(i?.completionPolicy)??Ox(a.completionPolicy);return{id:`${e.id}:async-agent`,parentId:e.id,piboSessionId:t,eventId:e.eventId,toolCallId:e.toolCallId,runId:c,type:`agent.async`,title:s,status:kx(e,l),startedAt:r?.startedAt??n??e.startedAt,completedAt:l===`completed`||l===`cancelled`?e.completedAt:void 0,summary:`Started by ${e.title}`,input:{startedBy:e.title,startToolCallId:e.toolCallId,toolName:o,subagentName:s,runId:c,completionPolicy:d,arguments:u,threadKey:Ax(r?.input)?r.input.threadKey:void 0},output:i,error:e.error,linkedPiboSessionId:r?.linkedPiboSessionId??e.linkedPiboSessionId,source:e.source,stableKey:c?`async-agent:${c}`:`${e.stableKey??e.id}:async-agent`,orderKey:lx(e.orderKey,`agent.async`),children:[]}}function wx(e){return e.type===`tool.call`&&e.title===`pibo_run_start`}function Tx(e,t){e.status=t.status,e.summary=t.summary??e.summary,e.input=t.input??e.input,e.output=t.output??e.output,e.error=t.error??e.error,e.completedAt=t.completedAt??e.completedAt,e.linkedPiboSessionId=t.linkedPiboSessionId??e.linkedPiboSessionId}function Ex(e){if(Ax(e)){if(Dx(e))return e;if(Ax(e.details)&&Dx(e.details))return e.details}}function Dx(e){return typeof e.runId==`string`&&typeof e.toolName==`string`}function Ox(e){return typeof e==`string`?e:void 0}function kx(e,t){return e.status===`error`||t===`failed`?`error`:t===`completed`||t===`cancelled`?`done`:`running`}function Ax(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function jx(e){let t=(e??``).trim();if(!t.startsWith(`<pibo_run_notification>`)||!t.endsWith(`</pibo_run_notification>`))return;let n=t.slice(23,t.length-24).trim();try{let e=JSON.parse(n);return!e||typeof e!=`object`||Array.isArray(e)?void 0:e}catch{return}}function Mx(e){let t=Nx(e.notification),n=t.length===1?t[0]:void 0,r=Fx(e.notification.failed),i=Fx(e.notification.running);return{id:e.id,entryId:e.entryId,piboSessionId:e.piboSessionId,eventId:e.eventId,runId:typeof n?.runId==`string`?n.runId:void 0,type:`yielded.run`,title:`Run Notification`,status:r>0?`error`:i>0?`running`:`done`,startedAt:e.startedAt,summary:Ix(e.notification),output:e.notification,source:e.source,stableKey:e.stableKey??e.id,orderKey:e.orderKey,children:[]}}function Nx(e){return[...Px(e.completed),...Px(e.failed),...Px(e.cancelled),...Px(e.running)]}function Px(e){return Array.isArray(e)?e.filter(Lx):[]}function Fx(e){return Array.isArray(e)?e.length:0}function Ix(e){let t=[[Fx(e.completed),`completed`],[Fx(e.failed),`failed`],[Fx(e.cancelled),`cancelled`],[Fx(e.running),`running`]].filter(([e])=>Number(e)>0).map(([e,t])=>`${e} ${t}`);return t.length?t.join(`, `):`No yielded run updates`}function Lx(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Rx(e,t,n,r,i,a,o,s,c){let l=r.payload;if(o&&tS(l)&&!nS(l,s)||o&&rS(l,c))return;if(l.type===`assistant_delta`){Yx(e,t,l,c,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex);return}if(l.type===`thinking_delta`){Zx(e,t,l,c,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex);return}if(l.type===`assistant_message`){let i=zx(n,l,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex),a=t.get(i.id);if(a){Xx(a,i),$x(t,a);return}$x(t,i),e.push(i),t.set(i.id,i);return}let u=Jx(n,l,i,a,c,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex);if(u){if(u.type===`agent.turn`&&u.eventId){let e=[...t.values()].find(e=>e.type===`agent.turn`&&e.eventId===u.eventId);if(e){e.status=u.status,e.completedAt=u.completedAt??e.completedAt;return}}if(u.type===`assistant.message`){let e=t.get(u.id);if(e){Xx(e,u),$x(t,e);return}$x(t,u)}if(u.type===`execution.compaction`){let t=pS(e);if(t){mS(t,u);return}}if(u.type===`model.reasoning`){let e=t.get(u.id);if(e){Qx(e,u);return}}if(u.toolCallId){let e=[...t.values()].find(e=>e.toolCallId===u.toolCallId&&(e.type===`tool.call`||e.type===`agent.delegation`));if(e){if(wx(e)&&u.type===`agent.delegation`){xx(e,n,r.createdAt,u);return}fS(e,u),xx(e,n,r.createdAt);return}}if(!(u.eventId&&t.has(u.id))){Bx(u,t),xx(u,n,r.createdAt),e.push(u);for(let e of gx([u]))t.set(e.id,e)}}}function zx(e,t,n,r,i,a){let o=typeof t.eventId==`string`?t.eventId:void 0,s=lS(t);return{id:s?cS(s):`event:${t.type}:${_S(t)}`,piboSessionId:e,eventId:o,parentId:o?sS(o):void 0,type:`assistant.message`,title:`Agent Message`,status:`done`,startedAt:n,summary:t.text,output:t.text,source:`event-log`,stableKey:s?`assistant:${s}`:oS(t),orderKey:iS(r,t.type,i,a),children:[]}}function Bx(e,t){if(e.type!==`execution.command`||e.parentId&&t.has(e.parentId))return;let n=[...t.values()].filter(n=>{if(n.type!==`agent.turn`||!n.startedAt||!e.startedAt||n.startedAt>e.startedAt)return!1;let r=Vx(n,t);return r===void 0||e.startedAt<=r}).sort(px).at(-1);n&&(e.parentId=n.id)}function Vx(e,t){return e.completedAt?e.completedAt:[...t.values()].filter(t=>t.type===`error`&&t.eventId!==void 0&&t.eventId===e.eventId&&t.startedAt!==void 0).sort(px).at(0)?.startedAt}function Hx(e){return e.some(e=>{let t=e.payload.type;return t!==`assistant_delta`&&t!==`thinking_delta`})}function Ux(e){if(e.type===`assistant_delta`){if(e.text.length===0)return;let t=lS(e);return t?cS(t):void 0}if(e.type===`thinking_delta`){if(e.text.length===0)return;let t=dS(e);return t?uS(t):void 0}}function Wx(e,t){let n=t.payload;if(n.type!==`message_queued`||n.source!==`user`)return!1;let r=typeof n.eventId==`string`?n.eventId:t.eventId,i=typeof n.text==`string`?n.text:void 0;return e.some(e=>e.type!==`user.message`||e.source!==`transcript`?!1:r&&(e.entryId===r||e.stableKey===`entry:${r}`)?!0:!!(i&&Gx(e)===i))}function Gx(e){if(typeof e.output==`string`)return e.output;if(typeof e.summary==`string`)return e.summary}function Kx(e){if(e.streamId!==void 0){let t=e.payload;return e.streamFrameIndex===void 0?`stream:${e.streamId}:${t.type}`:`stream:${e.streamId}:${e.streamFrameIndex}:${t.type}`}return e.eventSequence===void 0?`id:${e.id}`:`sequence:${e.piboSessionId??``}:${e.eventSequence}`}function qx(e,t){let n=t;for(let t of e)t.streamId!==void 0&&(n=n===void 0?t.streamId:Math.max(n,t.streamId));return n}function Jx(e,t,n,r,i,a,o,s,c){let l=`eventId`in t&&typeof t.eventId==`string`?t.eventId:void 0,u=`event:${t.type}:${l??_S(t)}`,d=l?sS(l):void 0,f={id:u,piboSessionId:e,eventId:l,startedAt:a,source:`event-log`,stableKey:oS(t),orderKey:iS(o,t.type,s,c),children:[]};switch(t.type){case`message_queued`:{let n=jx(t.text);return t.source===`service`&&n?Mx({id:u,piboSessionId:e,eventId:l,startedAt:a,source:`event-log`,stableKey:l?`run-notification:${l}`:u,orderKey:iS(o,t.type,s,c),notification:n}):{...f,type:`user.message`,title:`User Message`,status:`done`,summary:t.text,output:t.text}}case`message_started`:case`message_finished`:return t.source===`service`?void 0:{...f,id:l?sS(l):u,type:`agent.turn`,title:`Agent Turn`,status:t.type===`message_finished`||i!==`running`?`done`:`running`,completedAt:t.type===`message_finished`?a:void 0,stableKey:l?`turn:${l}`:f.stableKey};case`thinking_finished`:{if(!hS(t.text))return;let e=dS(t);return{...f,id:e?uS(e):u,parentId:d,type:`model.reasoning`,title:`Thinking`,status:`done`,summary:t.text,output:t.text,stableKey:e?`reasoning:${e}`:f.stableKey}}case`assistant_message`:{let e=lS(t);return{...f,id:e?cS(e):u,parentId:d,type:`assistant.message`,title:`Agent Message`,status:`done`,summary:t.text,output:t.text,stableKey:e?`assistant:${e}`:f.stableKey}}case`tool_call`:case`tool_execution_started`:case`tool_execution_updated`:case`tool_execution_finished`:{let o=vx(t.toolName),s=r.get(t.toolCallId)??(o?_x(e,t.toolName,t,n):void 0);return{...f,id:`tool:${t.toolCallId}`,parentId:d,toolCallId:t.toolCallId,type:o?`agent.delegation`:`tool.call`,title:t.toolName,status:t.type===`tool_execution_finished`?t.isError?`error`:`done`:i===`running`&&(t.type===`tool_execution_started`||t.type===`tool_execution_updated`)?`running`:`done`,completedAt:t.type===`tool_execution_finished`?a:void 0,input:`args`in t?t.args:void 0,output:t.type===`tool_execution_finished`?t.result:t.type===`tool_execution_updated`?t.partialResult:void 0,error:t.type===`tool_execution_finished`&&t.isError?gS(t.result):void 0,linkedPiboSessionId:s,stableKey:`tool:${t.toolCallId}`,children:[]}}case`subagent_session`:return{...f,id:t.toolCallId?`tool:${t.toolCallId}`:u,eventId:l,toolCallId:t.toolCallId,type:`agent.delegation`,title:t.toolName,status:i===`running`?`running`:`done`,summary:t.subagentName,input:{subagentName:t.subagentName,threadKey:t.threadKey},linkedPiboSessionId:t.childPiboSessionId,stableKey:t.toolCallId?`tool:${t.toolCallId}`:`subagent:${t.childPiboSessionId}`,children:[]};case`execution_result`:return eS(t.action)?void 0:{...f,type:`execution.command`,title:t.action,status:`done`,input:{action:t.action},output:t.result};case`compaction_start`:return{...f,id:`event:compaction:${o??s??_S(t)}`,type:`execution.compaction`,title:`compact`,status:`running`,summary:`Compacting`,input:{reason:t.reason},stableKey:`compaction:active`};case`compaction_end`:return{...f,id:`event:compaction:end:${o??s??_S(t)}`,type:`execution.compaction`,title:`compact`,status:t.errorMessage?`error`:`done`,completedAt:a,summary:t.aborted?`Compaction skipped`:t.errorMessage?`Compaction failed`:`Compacted`,input:{reason:t.reason},output:t.result,error:t.errorMessage,stableKey:`compaction:active`};case`session_error`:return{...f,type:`error`,title:`Session Error`,status:`error`,summary:t.errorDetails?.userMessage,input:t.errorDetails,error:t.error,output:t.error};default:return}}function Yx(e,t,n,r,i,a,o,s){if(n.text.length===0)return;let c=lS(n),l=c?cS(c):`event:assistant_delta:${_S(n)}`,u=t.get(l);if(u){let e=`${typeof u.output==`string`?u.output:``}${n.text}`;u.status=r===`running`?`running`:`done`,u.summary=e,u.output=e;return}let d={id:l,parentId:n.eventId?sS(n.eventId):void 0,piboSessionId:n.piboSessionId,eventId:n.eventId,type:`assistant.message`,title:`Agent Message`,status:r===`running`?`running`:`done`,startedAt:i,summary:n.text,output:n.text,source:`event-log`,stableKey:c?`assistant:${c}`:l,orderKey:iS(a,n.type,o,s),children:[]};e.push(d),t.set(d.id,d)}function Xx(e,t){e.status=t.status,e.summary=t.summary??e.summary,e.output=t.output??e.output,e.error=t.error??e.error,e.completedAt=t.completedAt??e.completedAt}function Zx(e,t,n,r,i,a,o,s){if(n.text.length===0)return;let c=dS(n),l=c?uS(c):`event:thinking_delta:${_S(n)}`,u=t.get(l);if(u){let e=`${typeof u.output==`string`?u.output:``}${n.text}`;u.status=r===`running`?`running`:`done`,u.summary=e,u.output=e;return}let d={id:l,parentId:n.eventId?sS(n.eventId):void 0,piboSessionId:n.piboSessionId,eventId:n.eventId,type:`model.reasoning`,title:`Thinking`,status:r===`running`?`running`:`done`,startedAt:i,summary:n.text,output:n.text,source:`event-log`,stableKey:c?`reasoning:${c}`:l,orderKey:iS(a,n.type,o,s),children:[]};e.push(d),t.set(d.id,d)}function Qx(e,t){e.status=t.status,e.summary=t.summary??e.summary,e.output=t.output??e.output,e.completedAt=t.completedAt??e.completedAt}function $x(e,t){if(!t.parentId||t.status!==`done`)return;let n=e.get(t.parentId);!n||n.type!==`agent.turn`||(n.status=`done`,n.completedAt=t.completedAt??t.startedAt??n.completedAt)}function eS(e){return e===`session.fork`||e===`session.clone`||e===`session.switch`}function tS(e){return e.type===`message_queued`||e.type===`message_started`||e.type===`message_finished`||e.type===`assistant_delta`||e.type===`assistant_message`||e.type===`thinking_started`||e.type===`thinking_delta`||e.type===`thinking_finished`}function nS(e,t){let n=`eventId`in e&&typeof e.eventId==`string`?e.eventId:void 0;return!!(n&&t.has(n))}function rS(e,t){return t!==`running`&&e.type===`tool_call`}function iS(e,t,n,r){return e===void 0&&(n!==void 0||r!==void 0)?sx(n,r,aS(t)):ox(e,aS(t))}function aS(e){switch(e){case`message_queued`:return`user.message`;case`message_started`:case`message_finished`:return`agent.turn`;case`thinking_started`:case`thinking_delta`:case`thinking_finished`:return`model.reasoning`;case`tool_call`:case`tool_execution_started`:case`tool_execution_updated`:case`tool_execution_finished`:case`subagent_session`:return`tool.call`;case`assistant_delta`:case`assistant_message`:return`assistant.message`;case`execution_result`:return`execution.command`;case`compaction_start`:case`compaction_end`:return`execution.compaction`;case`session_error`:return`error`;default:return`execution.command`}}function oS(e){let t=`eventId`in e&&typeof e.eventId==`string`?e.eventId:void 0;if(e.type===`tool_call`||e.type===`tool_execution_started`||e.type===`tool_execution_updated`||e.type===`tool_execution_finished`||e.type===`subagent_session`&&e.toolCallId)return`tool:${e.toolCallId}`;if(t&&(e.type===`message_started`||e.type===`message_finished`))return`turn:${t}`;if(e.type===`thinking_started`||e.type===`thinking_delta`||e.type===`thinking_finished`){let t=dS(e);if(t)return`reasoning:${t}`}if(e.type===`assistant_delta`||e.type===`assistant_message`){let t=lS(e);if(t)return`assistant:${t}`}return`event:${e.type}:${t??_S(e)}`}function sS(e){return`event:message:${e}`}function cS(e){return`event:assistant:${e}`}function lS(e){if(!e.eventId)return;let t=typeof e.assistantIndex==`number`?e.assistantIndex:e.contentIndex;return typeof t==`number`?`${e.eventId}:assistant:${t}`:e.eventId}function uS(e){return`event:thinking:${e}`}function dS(e){if(!e.eventId)return;let t=typeof e.thinkingIndex==`number`?e.thinkingIndex:e.contentIndex;return typeof t==`number`?`${e.eventId}:thinking:${t}`:e.eventId}function fS(e,t){e.status=t.status,e.summary=t.summary??e.summary,e.input=t.input??e.input,e.output=t.output??e.output,e.error=t.error??e.error,e.completedAt=t.completedAt??e.completedAt,e.linkedPiboSessionId=t.linkedPiboSessionId??e.linkedPiboSessionId}function pS(e){return gx([...e]).reverse().find(e=>e.type===`execution.compaction`&&e.status===`running`)}function mS(e,t){e.status=t.status,e.summary=t.summary??e.summary,e.input=t.input??e.input,e.output=t.output??e.output,e.error=t.error??e.error,e.completedAt=t.completedAt??e.completedAt}function hS(e){return typeof e==`string`&&e.trim().length>0}function gS(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}function _S(e){return vS(new TextEncoder().encode(JSON.stringify(e))).slice(0,48)}function vS(e){let t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`,n=``,r=0;for(;r+2<e.length;r+=3){let i=e[r]<<16|e[r+1]<<8|e[r+2];n+=t[i>>18&63]+t[i>>12&63]+t[i>>6&63]+t[i&63]}if(r<e.length){let i=e[r],a=r+1<e.length?e[r+1]:0,o=i<<16|a<<8;n+=t[o>>18&63]+t[o>>12&63],r+1<e.length&&(n+=t[o>>6&63])}return n}function yS(e){let t=new Map;for(let n of e)t.set(n.id,n);let n=[];for(let r of e){if(!r.parentId){n.push(r);continue}let e=t.get(r.parentId);e?e.children.push(r):n.push(r)}return dx(n)}function bS(e,t,n){return t.map(t=>xS(e,t,n))}function xS(e,t,n){let r=e.get(t.id);if(t.children.length===0){let e=r!==void 0&&r.children.length===0;return r&&e&&(n&&!n.has(t.id)||SS(r,t))?r:e?{...t,children:r.children}:{...t,children:[]}}let i=t.children.map(t=>xS(e,t,n)),a=r!==void 0&&r.children.length===i.length&&r.children.every((e,t)=>e===i[t]);return r&&a&&(n&&!n.has(t.id)||SS(r,t))?r:a?{...t,children:r?.children??i}:{...t,children:i}}function SS(e,t){return e.id===t.id&&e.parentId===t.parentId&&e.entryId===t.entryId&&e.piboSessionId===t.piboSessionId&&e.eventId===t.eventId&&e.toolCallId===t.toolCallId&&e.runId===t.runId&&e.type===t.type&&e.title===t.title&&e.status===t.status&&e.startedAt===t.startedAt&&e.completedAt===t.completedAt&&e.durationMs===t.durationMs&&e.summary===t.summary&&e.input===t.input&&e.output===t.output&&e.error===t.error&&e.linkedPiboSessionId===t.linkedPiboSessionId&&e.source===t.source&&e.stableKey===t.stableKey&&CS(e.orderKey,t.orderKey)}function CS(e,t){return e===t?!0:!e||!t?!1:e.sourceRank===t.sourceRank&&e.turnSeq===t.turnSeq&&e.transcriptIndex===t.transcriptIndex&&e.contentPartIndex===t.contentPartIndex&&e.eventSequence===t.eventSequence&&e.streamId===t.streamId&&e.streamFrameIndex===t.streamFrameIndex&&e.phaseRank===t.phaseRank}function wS(e,t,n){if(!t.length)return e;let r=new Set(e.rawEvents.map(e=>Kx(e))),i=[];for(let e of t){let t=Kx(e);r.has(t)||(r.add(t),i.push(e))}if(!i.length)return e;let a=gx(e.nodes),o=[],s=new Map,c=new Map;for(let e of a){c.set(e.id,e);let t={...e,children:[]};o.push(t),s.set(t.id,t)}let l=new Map,u=new Map,d=new Set,f=[],p=new Set;for(let t of i){if(Wx(o,t))continue;f.push(t);let r=Ux(t.payload);p&&r?p.add(r):p=void 0,Rx(o,s,e.piboSessionId,t,l,u,!1,d,n)}if(!f.length)return e;let m=yS(o);Hx(f)&&Sx(m);let h=bS(c,m,p);return{...e,rawEvents:e.rawEvents.length?[...e.rawEvents,...f]:f,nodes:h,latestStreamId:qx(f,e.latestStreamId)}}function TS(e,t){return e?tC(QS(ES(e.nodes).sort((e,t)=>px(e.node,t.node)).filter(e=>e.node.type!==`agent.turn`&&(t.showThinking||e.node.type!==`model.reasoning`)).map(e=>DS(e.node,e.turnId)))).map(e=>e.row):[]}function ES(e,t){let n=[];for(let r of e)r.type!==`agent.turn`&&n.push({node:r,turnId:t}),n.push(...ES(r.children,r.type===`agent.turn`?r.id:t));return n}function DS(e,t){let n;switch(e.type){case`user.message`:n={row:kS(e),turnId:t};break;case`assistant.message`:n={row:AS(e),turnId:t};break;case`model.reasoning`:n={row:jS(e),turnId:t};break;case`tool.call`:n=MS(e,t);break;case`tool.result`:n=PS(e,t);break;case`agent.delegation`:n={row:IS(e),turnId:t};break;case`agent.async`:n={row:LS(e),turnId:t};break;case`yielded.run`:n={row:RS(e),turnId:t};break;case`execution.command`:n={row:BS(e),turnId:t};break;case`execution.compaction`:n={row:zS(e),turnId:t};break;case`error`:n={row:XS(e),turnId:t};break;case`agent.turn`:n={row:{id:e.id,kind:`error`,status:`neutral`,lines:[],sourceNodeIds:[e.id]},turnId:t};break}return{...n,row:{...n.row,...OS(e)}}}function OS(e){return{eventId:e.eventId,runId:e.runId,orderSource:e.source,orderStreamId:e.orderKey?.streamId,orderStreamFrameIndex:e.orderKey?.streamFrameIndex}}function kS(e){let t=jC(e.output)||jC(e.summary)||e.title;return{id:e.id,kind:`message.user`,status:kC(e.status),lines:[{prefix:`prompt`,tokens:[$(t)]}],sourceNodeIds:[e.id],forkEntryId:e.entryId,output:t}}function AS(e){return{id:e.id,kind:`message.assistant`,status:kC(e.status),lines:[],sourceNodeIds:[e.id],output:jC(e.output)||jC(e.summary)||``,error:e.error}}function jS(e){let t=xC(e.output??e.summary);return{id:e.id,kind:`reasoning`,status:kC(e.status),lines:[{prefix:`bullet`,tokens:[$(e.status===`running`?`Thinking`:`Thought`,`amber`,`semibold`)]}],sourceNodeIds:[e.id],markdown:t}}function MS(e,t){let n=wC(e.input);if(n&&CC(e.title))return{row:YS(e,n),turnId:t,exploring:void 0};let r=oC(e);if(r)return{row:NS(e,r),turnId:t,image:r.groupable?r.detail:void 0};let i=yC(e.error??e.output,5,e.error?`red`:`dim`);return{row:{id:e.id,kind:`tool.call`,status:kC(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(EC(e.status),AC(e.status),`semibold`),$(` `)],functionCall:{name:e.title,input:e.input}},...i.lines],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:e.input!==void 0||e.output!==void 0||!!e.error,previewOmission:bC(i,e.error?`error`:`output`)},turnId:t,exploring:mC(e)}}function NS(e,t){let n=kC(e.status),r=t.path?`Path: ${t.path}`:t.artifactId?`Artifact: ${t.artifactId}`:t.query?`Query: ${t.query}`:t.mimeType?`Type: ${t.mimeType}`:`Image content returned`;return{id:e.id,kind:`tool.image`,status:n,errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(t.verb,AC(e.status),`semibold`)]},{prefix:`detail`,tokens:[$(r,e.status===`error`?`red`:`cyan`)]}],sourceNodeIds:[e.id],input:cC(e.input),output:t.summary,error:e.error,expandable:e.input!==void 0||t.summary!==void 0||!!e.error}}function PS(e,t){let n=oC(e);return n?{row:NS(e,n),turnId:t,image:n.groupable?n.detail:void 0}:{row:FS(e),turnId:t}}function FS(e){let t=yC(e.error??e.output,5,e.error?`red`:`dim`);return{id:e.id,kind:`tool.call`,status:kC(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(e.status===`error`?`Tool failed`:`Returned`,AC(e.status),`semibold`),$(` ${e.title}`)]},...t.lines],sourceNodeIds:[e.id],output:e.output,error:e.error,expandable:e.output!==void 0||!!e.error,previewOmission:bC(t,e.error?`error`:`output`)}}function IS(e){let t=jC(MC(e.input)?e.input.subagentName:void 0)||e.summary||e.title,n=SC((MC(e.input)?e.input.arguments:void 0)??e.input),r=n?[{prefix:`detail`,tokens:[$(n,`dim`)]}]:[];return{id:e.id,kind:`agent.delegation`,status:kC(e.status),lines:[{prefix:`bullet`,tokens:[$(DC(e.status),AC(e.status),`semibold`),$(` ${t}`,`cyan`)]},...r],sourceNodeIds:[e.id],linkedPiboSessionId:e.linkedPiboSessionId,input:e.input,output:e.output,error:e.error,expandable:e.input!==void 0||e.output!==void 0||!!e.error}}function LS(e){let t=yC(e.error??e.output,5,e.error?`red`:`dim`);return{id:e.id,kind:`agent.async`,status:kC(e.status),lines:[{prefix:`bullet`,tokens:[$(OC(e.status),AC(e.status),`semibold`),$(` ${e.title}`,`cyan`)]},...t.lines],sourceNodeIds:[e.id],linkedPiboSessionId:e.linkedPiboSessionId,input:e.input,output:e.output,error:e.error,expandable:e.input!==void 0||e.output!==void 0||!!e.error,previewOmission:bC(t,e.error?`error`:`output`)}}function RS(e){let t=yC(e.output,5);return{id:e.id,kind:`yielded.run`,status:kC(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(e.status===`running`?`Waiting on runs`:`Run update`,AC(e.status),`semibold`),$(e.summary?` ${e.summary}`:``)]},...t.lines],sourceNodeIds:[e.id],output:e.output,error:e.error,expandable:e.output!==void 0||!!e.error,previewOmission:bC(t,`output`)}}function zS(e){let t=e.status===`running`?`Compacting`:e.status===`error`?`Compaction failed`:jC(e.summary)||`Compacted`;return{id:e.id,kind:`execution.compaction`,status:kC(e.status),lines:[{prefix:`bullet`,tokens:[$(t,AC(e.status),e.status===`error`?`bold`:`semibold`)]}],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:e.input!==void 0||e.output!==void 0||!!e.error}}function BS(e){if(e.title===`status`)return VS(e);if(e.title===`thinking`)return eC(e.output)?US(e):HS(e);if(e.title===`fast_mode`)return WS(e);if(e.title===`login`&&qS(e.output))return GS(e);if(e.title===`model`&&JS(e.output))return KS(e);wC(e.output)??wC(e.input)??e.title;let t=yC(e.error??e.output,5,e.error?`red`:`dim`,180);return{id:e.id,kind:`execution.command`,status:kC(e.status),lines:[{prefix:`bullet`,tokens:[$(`Command`,`yellow`,`semibold`),$(` /${e.title}`,`yellow`)]},...t.lines],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:e.input!==void 0||e.output!==void 0||!!e.error,previewOmission:bC(t,e.error?`error`:`output`)}}function VS(e){return{id:e.id,kind:`tool.status`,status:kC(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function HS(e){return{id:e.id,kind:`tool.thinking`,status:kC(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function US(e){let t=MC(e.output)?e.output:void 0,n=jC(t?.level),r=t?.changed!==!1,i=t?.supported!==!1,a=i?n?r?`Thinking level set to ${n}.`:`Thinking level is already ${n}.`:`Thinking level updated.`:`Thinking level is not supported by this model.`;return{id:e.id,kind:`execution.command`,status:kC(e.status),lines:[{prefix:`bullet`,tokens:[$(a,i?`green`:`dim`,`semibold`)]}],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function WS(e){let t=MC(e.output)?e.output:void 0,n=t?.mode===`fast`?`fast`:t?.mode===`normal`?`normal`:void 0,r=t?.changed!==!1,i=t?.supported!==!1,a=i?n===`fast`?r?`Switched to Fast mode.`:`Fast mode is already on.`:n===`normal`?r?`Switched to Normal mode.`:`Normal mode is already on.`:`Fast mode updated.`:`Fast mode is not supported by this model.`;return{id:e.id,kind:`execution.command`,status:kC(e.status),lines:[{prefix:`bullet`,tokens:[$(a,i?`green`:`dim`,`semibold`)]}],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function GS(e){return{id:e.id,kind:`tool.login`,status:kC(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function KS(e){return{id:e.id,kind:`tool.model`,status:kC(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function qS(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return t.action===`show_login_menu`&&Array.isArray(t.providers)}function JS(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return t.action===`show_model_menu`&&Array.isArray(t.providers)}function YS(e,t){let n=yC(e.error??e.output,5,e.error?`red`:`dim`,180);return{id:e.id,kind:`execution.command`,status:kC(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(e.status===`running`?`Running`:`Ran`,AC(e.status),`semibold`),$(` `),...TC(t)]},...n.lines],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:e.input!==void 0||e.output!==void 0||!!e.error,previewOmission:bC(n,e.error?`error`:`output`)}}function XS(e){return{id:e.id,kind:`error`,status:`error`,errorKind:`system`,lines:[{prefix:`bullet`,tokens:[$(e.title||`Error`,`red`,`bold`),$(e.error?` ${e.error}`:``,`red`)]},...ZS(e.input)],sourceNodeIds:[e.id],input:e.input,error:e.error,output:e.output,expandable:e.input!==void 0||e.output!==void 0||!!e.error}}function ZS(e){return MC(e)?[[`Class`,jC(e.errorClass)??jC(e.category)],[`Code`,jC(e.code)??jC(e.providerCode)],[`Origin`,jC(e.origin)],[`Provider`,[jC(e.api),jC(e.provider),jC(e.model)].filter(Boolean).join(` / `)||void 0],[`Retryable`,typeof e.retryable==`boolean`?e.retryable?`yes`:`no`:void 0]].filter(e=>typeof e[1]==`string`&&e[1].length>0).map(([e,t],n)=>({prefix:n===0?`detail`:`continuation`,tokens:[$(`${e}: `,`dim`),$(t,`red`)]})):[]}function QS(e){let t=e.map(e=>e.row.output).filter($S).at(-1);return t?e.map(e=>e.row.kind!==`tool.thinking`||!MC(e.row.output)?e:{...e,row:{...e.row,output:{...e.row.output,level:t.level,availableLevels:t.availableLevels,supported:t.supported}}}):[...e]}function $S(e){return MC(e)&&typeof e.level==`string`&&Array.isArray(e.availableLevels)}function eC(e){return MC(e)&&e.action===`set_thinking_level`}function tC(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n],i=nC(r);if(!i){t.push(r);continue}let a=[r],o=n+1;for(;o<e.length&&nC(e[o])===i&&e[o].turnId===r.turnId;)a.push(e[o]),o+=1;if(a.length===1){t.push(r);continue}t.push({row:i===`images`?iC(a):rC(a),turnId:r.turnId}),n=o-1}return t}function nC(e){if(e.image)return`images`;if(e.exploring)return`exploring`}function rC(e){let t=aC(e,`exploring`),n=t.slice(0,6),r=Math.max(0,t.length-n.length),i=e[0]?.row,a=i?.id??`exploring`,o=e[e.length-1]?.row.id??a,s=e.some(e=>e.row.status===`running`)?`running`:e.some(e=>e.row.status===`error`)?`error`:`done`;return{id:`group:exploring:${a}:${o}`,kind:`tool.group.exploring`,status:s,errorKind:s===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(s===`running`?`Exploring`:s===`error`?`Exploring failed`:`Explored`,AC(s),`semibold`)]},...n.map((e,t)=>({prefix:t===0?`detail`:`continuation`,tokens:[$(e.label,e.status===`error`?`red`:`dim`)]})),...r>0?[{prefix:`continuation`,tokens:[$(`+${r} more explorations`,`dim`,`normal`,!0)]}]:[]],sourceNodeIds:e.flatMap(e=>e.row.sourceNodeIds),eventId:i?.eventId,runId:i?.runId,orderSource:i?.orderSource,orderStreamId:i?.orderStreamId,orderStreamFrameIndex:i?.orderStreamFrameIndex,detailItems:t,expandable:t.some(e=>e.input!==void 0||e.output!==void 0||!!e.error),previewOmission:r>0?{source:`details`,visibleLineCount:n.length,omittedLineCount:r,totalLineCount:t.length,maxVisibleLineCount:6}:void 0}}function iC(e){let t=aC(e,`images`),n=t.slice(0,6),r=Math.max(0,t.length-n.length),i=e[0]?.row,a=i?.id??`images`,o=e[e.length-1]?.row.id??a,s=e.some(e=>e.row.status===`running`)?`running`:e.some(e=>e.row.status===`error`)?`error`:`done`;return{id:`group:images:${a}:${o}`,kind:`tool.group.images`,status:s,errorKind:s===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(s===`running`?`Viewing images`:s===`error`?`Image reads failed`:`Viewed images`,AC(s),`semibold`)]},...n.map((e,t)=>({prefix:t===0?`detail`:`continuation`,tokens:[$(e.label,e.status===`error`?`red`:`cyan`)]})),...r>0?[{prefix:`continuation`,tokens:[$(`+${r} more image reads`,`dim`,`normal`,!0)]}]:[]],sourceNodeIds:e.flatMap(e=>e.row.sourceNodeIds),eventId:i?.eventId,runId:i?.runId,orderSource:i?.orderSource,orderStreamId:i?.orderStreamId,orderStreamFrameIndex:i?.orderStreamFrameIndex,detailItems:t,expandable:t.some(e=>e.input!==void 0||e.output!==void 0||!!e.error),previewOmission:r>0?{source:`details`,visibleLineCount:n.length,omittedLineCount:r,totalLineCount:t.length,maxVisibleLineCount:6}:void 0}}function aC(e,t){return e.map(e=>{let n=t===`images`?e.image:e.exploring;return{id:e.row.id,label:n?.label??e.row.lines[0]?.tokens.map(e=>e.text).join(``)??e.row.id,status:e.row.status,input:e.row.input,output:e.row.output,error:e.row.error,linkedPiboSessionId:e.row.linkedPiboSessionId,previewOmission:e.row.previewOmission}})}function oC(e){let t=(e.title??``).trim().toLowerCase(),n=MC(e.input)?e.input:void 0,r=MC(e.output)?e.output:void 0,i=pC(r,`details`),a=t===`codex_image_generation`?uC(i)??dC(n):void 0,o=a?jC(i?.savedPath)??gC(i):gC(n)??gC(i)??gC(r),s=a?jC(i?.artifactId):void 0,c=_C(n),l=sC(e.output),u=hC(t,[`view_image`,`image`,`screenshot`]);if(!l.length&&!u&&!a)return;let d=l.map(e=>e.mimeType).find(e=>!!e),f=Math.max(1,l.length),p={type:l.length>1?`images`:l.length===1?`image`:`image_reference`,toolName:a?e.title:void 0,operation:a,path:o,savedPath:a?o:void 0,artifactId:s,model:a?jC(i?.model):void 0,referencedImageCount:a?vC(i?.referencedImageCount):void 0,query:c,mimeType:d,count:f>1?f:void 0,detail:l.length?`Image data hidden in terminal view.`:`Image path only; binary data is hidden in terminal view.`},m=o??s??c??d??`image`,h=a?fC(e.status,a):lC(e.status,f);return{count:f,path:o,artifactId:s,query:c,mimeType:d,verb:h,groupable:!a,summary:p,detail:{id:e.id,label:`${h} ${m}`,status:kC(e.status),input:cC(e.input),output:p,error:e.error}}}function sC(e,t=0,n=new Set){if(t>5||typeof e!=`object`||!e||n.has(e))return[];if(n.add(e),Array.isArray(e))return e.flatMap(e=>sC(e,t+1,n));let r=e,i=typeof r.type==`string`?r.type.toLowerCase():void 0,a=typeof r.mimeType==`string`?r.mimeType:typeof r.mime_type==`string`?r.mime_type:void 0,o=typeof r.data==`string`||typeof r.image_url==`string`||MC(r.image_url);if((i===`image`||i===`input_image`||i===`output_image`||i===`image_url`)&&(o||a?.startsWith(`image/`))||a?.startsWith(`image/`)&&o)return[{mimeType:a}];let s=[];return`content`in r&&s.push(r.content),`message`in r&&s.push(r.message),`result`in r&&s.push(r.result),`output`in r&&s.push(r.output),s.flatMap(e=>sC(e,t+1,n))}function cC(e){if(Array.isArray(e))return e.map(cC);if(!MC(e))return e;let t={};for(let[n,r]of Object.entries(e)){if((n===`data`||n===`image_url`)&&typeof r==`string`&&r.length>120){t[n]=`[hidden ${n}]`;continue}t[n]=cC(r)}return t}function lC(e,t){return e===`running`?t>1?`Viewing images`:`Viewing image`:e===`error`?t>1?`Image reads failed`:`Image read failed`:t>1?`Viewed images`:`Viewed image`}function uC(e){let t=jC(e?.operation);return t===`generate`||t===`edit`?t:void 0}function dC(e){if(!e)return;let t=e.referenced_image_paths;return Array.isArray(t)&&t.length>0||vC(e.num_last_images_to_include)!==void 0?`edit`:`generate`}function fC(e,t){return t===`edit`?e===`running`?`Editing image`:e===`error`?`Image edit failed`:`Edited image`:e===`running`?`Generating image`:e===`error`?`Image generation failed`:`Generated image`}function pC(e,t){let n=e?.[t];return MC(n)?n:void 0}function mC(e){let t=(e.title??``).trim().toLowerCase(),n=MC(e.input)?e.input:void 0;if(hC(t,[`read`,`open`]))return{id:e.id,label:`Read ${gC(n)??SC(e.input)}`,status:kC(e.status),input:e.input,output:e.output,error:e.error};if(hC(t,[`list`,`ls`,`glob`]))return{id:e.id,label:`List ${gC(n)??SC(e.input)}`,status:kC(e.status),input:e.input,output:e.output,error:e.error};if(hC(t,[`search`,`find`,`grep`,`rg`])){let t=_C(n),r=gC(n);return{id:e.id,label:`Search ${t??SC(e.input)}${r?` in ${r}`:``}`,status:kC(e.status),input:e.input,output:e.output,error:e.error}}}function hC(e,t){return t.some(t=>e===t||e.startsWith(`${t}_`)||e.endsWith(`_${t}`)||e.includes(t))}function gC(e){if(e)for(let t of[`path`,`file`,`filePath`,`filepath`,`url`,`uri`,`cwd`,`pattern`,`glob`]){let n=jC(e[t]);if(n)return n}}function _C(e){if(e)for(let t of[`query`,`pattern`,`text`,`name`,`q`,`regex`]){let n=jC(e[t]);if(n)return n}}function vC(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function yC(e,t,n=`dim`,r=160){let i={lines:[],visibleLineCount:0,omittedLineCount:0,totalLineCount:0,maxVisibleLineCount:t},a=xC(e);if(!a)return i;let o=a.split(/\r?\n/).map(e=>e.trimEnd()).filter((e,t,n)=>e.length>0||n.length===1);if(!o.length)return i;let s=o.slice(0,t),c=Math.max(0,o.length-s.length),l=s.map((e,t)=>({prefix:t===0?`detail`:`continuation`,tokens:[$(e,n)]}));return c>0&&l.push({prefix:`continuation`,tokens:[$(`+${c} more lines`,`dim`,`normal`,!0)]}),{lines:l,visibleLineCount:s.length,omittedLineCount:c,totalLineCount:o.length,maxVisibleLineCount:t}}function bC(e,t){if(!(e.omittedLineCount<=0))return{source:t,visibleLineCount:e.visibleLineCount,omittedLineCount:e.omittedLineCount,totalLineCount:e.totalLineCount,maxVisibleLineCount:e.maxVisibleLineCount}}function xC(e){let t=Uy(e);if(t!==void 0)return t.trim();if(typeof e==`string`)return e.trim();if(e==null)return``;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function SC(e){return(typeof e==`string`?e:xC(e)).replace(/\s+/g,` `).trim()}function CC(e){let t=(e??``).trim().toLowerCase();return t===`shell`||t===`bash`||t===`terminal`}function wC(e){if(MC(e))for(let t of[`cmd`,`command`,`script`]){let n=jC(e[t]);if(n)return n}}function TC(e){let t=e.match(/\s+|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s]+/g)??[e],n=!1;return t.map(e=>/^\s+$/.test(e)?$(e):/^(?:&&|\|\||[|;<>]|2>&1)$/.test(e)?$(e,`red`,`semibold`):e.startsWith(`-`)?$(e,`magenta`):e.startsWith(`$`)||e.includes(`=`)?$(e,`yellow`):/^['"]/.test(e)?$(e,`green`):n?e.includes(`/`)||e.startsWith(`.`)?$(e,`cyan`):$(e,`default`):(n=!0,$(e,`green`,`semibold`)))}function EC(e){return e===`running`?`Calling`:e===`error`?`Call failed`:`Called`}function DC(e){return e===`running`?`Spawning`:e===`error`?`Spawn failed`:`Spawned`}function OC(e){return e===`running`?`Waiting for`:`Finished waiting for`}function kC(e){return e===`running`?`running`:e===`error`?`error`:`done`}function AC(e){return e===`running`?`cyan`:e===`error`?`red`:e===`done`?`green`:`default`}function $(e,t=`default`,n=`normal`,r=!1){return{text:e,tone:t,weight:n,italic:r}}function jC(e){return typeof e==`string`&&e.trim().length?e:void 0}function MC(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function NC(e){if(!e)return;let t;if(typeof e==`string`)try{t=JSON.parse(e)}catch{return}else typeof e==`object`&&!Array.isArray(e)&&(t=e);if(!t)return;let n=typeof t.contextUsage==`object`&&t.contextUsage!==null?t.contextUsage:void 0,r=typeof t.providerUsage==`object`&&t.providerUsage!==null?t.providerUsage:void 0,i=Array.isArray(r?.limits)?r.limits.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e)).map(e=>{let t=typeof e.usedPercent==`number`?e.usedPercent:void 0,n=typeof e.remainingPercent==`number`?e.remainingPercent:t===void 0?0:Math.max(0,Math.min(100,100-t));return{label:typeof e.label==`string`?e.label:`limit`,usedPercent:t??0,remainingPercent:n,resetsAt:typeof e.resetsAt==`string`?e.resetsAt:void 0}}):[],a=typeof r?.credits==`object`&&r.credits!==null?r.credits:void 0;return{piboSessionId:typeof t.piboSessionId==`string`?t.piboSessionId:void 0,queuedMessages:typeof t.queuedMessages==`number`?t.queuedMessages:void 0,processing:typeof t.processing==`boolean`?t.processing:void 0,streaming:typeof t.streaming==`boolean`?t.streaming:void 0,enabledTools:Array.isArray(t.enabledTools)?t.enabledTools.filter(e=>typeof e==`string`):Array.isArray(t.activeTools)?t.activeTools.filter(e=>typeof e==`string`):void 0,activeTools:Array.isArray(t.activeTools)?t.activeTools.filter(e=>typeof e==`string`):void 0,cwd:typeof t.cwd==`string`?t.cwd:void 0,disposed:typeof t.disposed==`boolean`?t.disposed:void 0,contextUsage:n?{tokens:typeof n.tokens==`number`?n.tokens:void 0,contextWindow:typeof n.contextWindow==`number`?n.contextWindow:void 0,percent:typeof n.percent==`number`?n.percent:void 0}:void 0,providerUsage:r&&(i.length>0||a)?{provider:typeof r.provider==`string`?r.provider:void 0,planType:typeof r.planType==`string`?r.planType:void 0,fetchedAt:typeof r.fetchedAt==`string`?r.fetchedAt:void 0,limits:i,credits:a?{unlimited:a.unlimited===!0,balance:typeof a.balance==`string`?a.balance:void 0}:void 0}:void 0}}function PC(e,t,n){return n?{id:e,label:t,value:n}:void 0}function FC({field:e,icon:t}){let n=t===`session`?et:Xe;return(0,M.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[11px]`,"data-shared-status-field":e.id,children:[(0,M.jsx)(n,{size:11,className:`shrink-0 text-[#737373]`}),(0,M.jsxs)(`span`,{className:`shrink-0 text-[#737373]`,children:[e.label,`:`]}),(0,M.jsx)(`span`,{className:`truncate font-mono ${e.id===`session`?`text-[#38bdf8]`:`text-[#d4d4d4]`}`,children:e.value})]})}function IC({progress:e,label:t}){let n=e.percent??0,r=e.tone===`red`?`bg-[#ef4444]`:e.tone===`yellow`?`bg-[#facc15]`:e.tone===`cyan`?`bg-[#38bdf8]`:`bg-[#22c55e]`;return(0,M.jsxs)(`div`,{className:`mt-3 space-y-1`,"data-shared-progress":e.id,"data-shared-progress-state":e.state,children:[(0,M.jsxs)(`div`,{className:`flex items-center justify-between text-[11px]`,children:[(0,M.jsx)(`span`,{className:`text-[#737373]`,children:t??e.label}),(0,M.jsx)(`span`,{className:`font-mono text-[#d4d4d4]`,children:e.state===`available`?e.text:`unavailable`})]}),e.state===`available`?(0,M.jsx)(`div`,{className:`h-1.5 w-full overflow-hidden rounded-full bg-[#2a2a2a]`,children:(0,M.jsx)(`div`,{className:`h-full rounded-full ${r} transition-all`,style:{width:`${Math.min(Math.max(n,0),100)}%`}})}):null]})}function LC(e){if(!e)return;let t=new Date(e);if(!Number.isNaN(t.getTime()))return t.toLocaleString(void 0,{weekday:`short`,hour:`2-digit`,minute:`2-digit`})}function RC({row:e}){let t=NC(e.output),n=Ub(e),r=n?.kind===`status`?n.statusView:void 0,[i,a]=(0,v.useState)(!1);if(!t||!r)return(0,M.jsx)(`div`,{className:`mt-2 border border-[#2a2a2a] bg-[#111111] px-3 py-2 text-[12px] text-[#d4d4d4]`,"data-pibo-component":`TerminalStatusCard`,"data-pibo-debug":`terminal-status-card`,"data-shared-terminal-card":`status`,children:(0,M.jsx)(`div`,{className:`text-[#737373]`,children:`Status (unparseable)`})});let o=new Map(r.fields.map(e=>[e.id,e])),s=o.get(`session`)??PC(`session`,`Session`,t.piboSessionId),c=o.get(`cwd`)??PC(`cwd`,`CWD`,t.cwd),l=r.progress.find(e=>e.id===`context`),u=r.progress.filter(e=>e.id.startsWith(`provider`)),d=t.providerUsage?.limits.length?t.providerUsage.limits:void 0,f=t.enabledTools??t.activeTools??[],p=r.fields.filter(e=>!new Set([`session`,`cwd`]).has(e.id)),m=t.providerUsage?.provider?`${t.providerUsage.provider} quota`:`Provider quota`;return(0,M.jsxs)(`div`,{className:`mt-2 border border-[#2a2a2a] bg-[#111111] px-3 py-2 text-[12px] text-[#d4d4d4]`,"data-pibo-component":`TerminalStatusCard`,"data-pibo-debug":`terminal-status-card`,"data-shared-terminal-card":`status`,children:[(0,M.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[(0,M.jsx)(Se,{size:14,className:`text-[#22c55e]`}),(0,M.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:r.title})]}),(0,M.jsxs)(`div`,{className:`grid grid-cols-1 gap-1.5 sm:grid-cols-2`,children:[s?(0,M.jsx)(FC,{field:s,icon:`session`}):null,c?(0,M.jsx)(FC,{field:c,icon:`cwd`}):null,p.slice(0,8).map(e=>(0,M.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[11px]`,"data-shared-status-field":e.id,children:[(0,M.jsxs)(`span`,{className:`shrink-0 text-[#737373]`,children:[e.label,`:`]}),(0,M.jsx)(`span`,{className:`truncate font-mono text-[#d4d4d4]`,children:e.value})]},e.id))]}),(0,M.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-1.5`,children:[t.processing?(0,M.jsxs)(`span`,{className:`inline-flex items-center gap-1 border border-[#1f4960] px-1.5 py-0.5 text-[11px] text-[#38bdf8]`,children:[(0,M.jsx)(Ge,{size:10}),` Processing`]}):null,t.streaming?(0,M.jsxs)(`span`,{className:`inline-flex items-center gap-1 border border-[#1f4960] px-1.5 py-0.5 text-[11px] text-[#38bdf8]`,children:[(0,M.jsx)(Se,{size:10}),` Streaming`]}):null,typeof t.queuedMessages==`number`&&t.queuedMessages>0?(0,M.jsxs)(`span`,{className:`inline-flex items-center gap-1 border border-[#3a3a3a] px-1.5 py-0.5 text-[11px] text-[#d4d4d4]`,children:[(0,M.jsx)(rt,{size:10}),` Queued: `,t.queuedMessages]}):null,t.disposed?(0,M.jsx)(`span`,{className:`inline-flex items-center gap-1 border border-[#5f2222] px-1.5 py-0.5 text-[11px] text-[#ef4444]`,children:`Disposed`}):null]}),l?(0,M.jsx)(IC,{progress:l,label:`Context Usage`}):null,u.length?(0,M.jsxs)(`div`,{className:`mt-3 space-y-1.5 border-t border-[#2a2a2a] pt-2`,"data-shared-provider-progress":u.length,children:[(0,M.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[11px] text-[#737373]`,"data-shared-status-field":`provider-quota`,children:[(0,M.jsx)(Ze,{size:11}),(0,M.jsxs)(`span`,{children:[m,t.providerUsage?.planType?` (${t.providerUsage.planType})`:``]})]}),d?d.map(e=>{let t=LC(e.resetsAt);return(0,M.jsxs)(`div`,{className:`space-y-1`,"data-shared-progress":`provider-limit:${e.label}`,"data-shared-progress-state":`available`,children:[(0,M.jsxs)(`div`,{className:`flex items-center justify-between gap-2 text-[11px]`,children:[(0,M.jsx)(`span`,{className:`text-[#a3a3a3]`,children:e.label}),(0,M.jsxs)(`span`,{className:`shrink-0 font-mono text-[#d4d4d4]`,children:[e.remainingPercent.toFixed(0),`% left`,t?` · resets ${t}`:``]})]}),(0,M.jsx)(`div`,{className:`h-1.5 w-full overflow-hidden rounded-full bg-[#2a2a2a]`,children:(0,M.jsx)(`div`,{className:`h-full rounded-full bg-[#38bdf8] transition-all`,style:{width:`${Math.min(Math.max(e.remainingPercent,0),100)}%`}})})]},`${e.label}-${e.resetsAt??``}`)}):u.map(e=>(0,M.jsx)(IC,{progress:e},e.id)),t.providerUsage?.credits?(0,M.jsxs)(`div`,{className:`text-[11px] text-[#a3a3a3]`,"data-shared-status-field":`provider-credits`,children:[`Credits: `,t.providerUsage.credits.unlimited?`unlimited`:t.providerUsage.credits.balance??`available`]}):null]}):null,r.warnings.length||r.errors.length?(0,M.jsxs)(`div`,{className:`mt-3 space-y-1 border-t border-[#2a2a2a] pt-2`,children:[r.warnings.map((e,t)=>(0,M.jsxs)(`div`,{"data-shared-status-warning":!0,className:`text-[11px] text-[#facc15]`,children:[`⚠ `,e]},`warning-${t}`)),r.errors.map((e,t)=>(0,M.jsxs)(`div`,{"data-shared-status-error":!0,className:`text-[11px] text-[#ef4444]`,children:[`✕ `,e]},`error-${t}`))]}):null,f.length>0?(0,M.jsxs)(`div`,{className:`mt-3`,children:[(0,M.jsxs)(`button`,{type:`button`,onClick:()=>a(e=>!e),className:`flex items-center gap-1.5 text-[11px] text-[#737373] hover:text-[#d4d4d4]`,children:[(0,M.jsx)(`span`,{className:`text-[#d4d4d4]`,children:i?`▾`:`▸`}),(0,M.jsxs)(`span`,{children:[`Enabled tools (`,f.length,`)`]})]}),i?(0,M.jsx)(`div`,{className:`mt-1.5 flex flex-wrap gap-1`,children:f.map(e=>(0,M.jsx)(`span`,{className:`inline-block rounded-sm border border-[#2a2a2a] bg-[#0b0b0b] px-1.5 py-0.5 font-mono text-[11px] text-[#a3a3a3]`,children:e},e))}):null]}):null]})}var zC=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`];function BC(e){let t;if(typeof e==`string`)try{t=JSON.parse(e)}catch{return}else e&&typeof e==`object`&&!Array.isArray(e)&&(t=e);if(t)return{level:typeof t.level==`string`?t.level:void 0,availableLevels:Array.isArray(t.availableLevels)?t.availableLevels.filter(e=>typeof e==`string`):[],supported:typeof t.supported==`boolean`?t.supported:void 0}}function VC(e){return zC.includes(e)?e:void 0}function HC({row:e,onLevelSelect:t}){let n=BC(e.output);return n?(0,M.jsxs)(`div`,{className:`mt-2 border border-[#2a2a2a] bg-[#111111] px-3 py-2 text-[12px] text-[#d4d4d4]`,"data-shared-terminal-card":`thinking`,children:[(0,M.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[(0,M.jsx)(ke,{size:14,className:`text-[#f59e0b]`}),(0,M.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:`Thinking`}),n.supported===!1?(0,M.jsxs)(`span`,{className:`ml-auto inline-flex items-center gap-1 border border-[#5f2222] px-1.5 py-0.5 text-[11px] text-[#ef4444]`,children:[(0,M.jsx)(vt,{size:10}),` Unsupported`]}):(0,M.jsxs)(`span`,{className:`ml-auto inline-flex items-center gap-1 border border-[#1f4960] px-1.5 py-0.5 text-[11px] text-[#38bdf8]`,children:[(0,M.jsx)(je,{size:10}),` Supported`]})]}),(0,M.jsxs)(`div`,{className:`grid gap-1.5 text-[11px]`,children:[(0,M.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,M.jsx)(`span`,{className:`text-[#737373]`,children:`Current:`}),(0,M.jsx)(`span`,{className:`font-mono font-semibold text-[#f59e0b]`,children:n.level??`unknown`})]}),n.availableLevels.length?(0,M.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,M.jsx)(`span`,{className:`mr-1 text-[#737373]`,children:`Available:`}),n.availableLevels.map(e=>{let r=VC(e),i=n.supported===!1||!r||!t;return(0,M.jsx)(`button`,{type:`button`,disabled:i,onClick:()=>{r&&t?.(r)},className:`border bg-transparent px-1.5 py-0.5 ${e===n.level?`border-[#f59e0b] text-[#f59e0b]`:`border-[#3a3a3a] text-[#d4d4d4]`} ${i?`cursor-default`:`cursor-pointer`}`,children:e},e)})]}):null,(0,M.jsxs)(`div`,{className:`text-[#737373]`,children:[`Click a level or use `,(0,M.jsx)(`span`,{className:`text-[#f59e0b]`,children:`/thinking <level>`}),`.`]})]})]}):(0,M.jsx)(`div`,{className:`mt-2 border border-[#2a2a2a] bg-[#111111] px-3 py-2 text-[12px] text-[#d4d4d4]`,"data-shared-terminal-card":`thinking`,children:(0,M.jsx)(`div`,{className:`text-[#737373]`,children:`Thinking (unparseable)`})})}var UC=180,WC={index:`LAST`,align:`end`},GC={top:2400,bottom:2400},KC=84,qC=6;function JC({traceView:e,selectedTrace:t,isLoading:n,showThinking:r,expandThinking:i,sessionAgentProfile:a,sessionActiveModel:o,selectedSessionStatus:s,selectedSessionSignal:c,sessionBreadcrumbs:l,originSession:u,derivedSessions:d,agentProfiles:f,sessionProfileChangeDisabled:p,onSessionAgentProfileChange:m,onFork:h,onOpenSession:g,onThinkingLevelChange:_,onModelChanged:y}){let b=(0,v.useMemo)(()=>TS(e,{showThinking:r}),[r,e]),[x,S]=(0,v.useState)(new Set),[C,w]=(0,v.useState)(null),T=(0,v.useRef)({}),E=b.filter(e=>e.status===`running`).length,ee=b.filter(e=>rw(e,`user`)).length,D=b.filter(e=>rw(e,`tool`)).length,O=b.filter(e=>rw(e,`system`)).length,te=c?c.isTreeActive:s===`running`||E>0||t?.status===`UNSET`,ne=ka({itemCount:b.length,resetKey:e?.piboSessionId,contentKey:b,atBottomThreshold:UC});(0,v.useEffect)(()=>{S(e=>nw(e,b,i))},[i,b]),(0,v.useEffect)(()=>{let e=new Set(b.map(e=>e.id));w(t=>t&&e.has(t)?t:null);for(let t of[`system`,`tool`,`user`]){let n=T.current[t];n&&!e.has(n)&&delete T.current[t]}},[b]);let re=(0,v.useCallback)(e=>{let t=iw(b,e,T.current[e]);t&&(T.current[e]=t.row.id,w(t.row.id),ne.scrollToIndex(t.index,`start`,`fast-smooth`,{fromIndex:t.fromIndex,stagingAlign:e===`tool`?`end`:void 0}),aw(t.row.id))},[b,ne]),ie=e=>{e.expandable&&S(t=>{let n=new Set(t);return n.has(e.id)?n.delete(e.id):n.add(e.id),n})},ae=(0,v.useCallback)((t,n)=>(0,M.jsx)(`div`,{className:`px-4`,children:(0,M.jsx)(ZC,{row:n,expanded:x.has(n.id),focused:C===n.id,piboSessionId:e?.piboSessionId??``,onToggle:()=>ie(n),onFork:h,onOpenSession:g,onThinkingLevelChange:_,onModelChanged:y})}),[x,C,h,y,g,_,e?.piboSessionId]),oe=(0,v.useMemo)(()=>({Footer:te?fw:void 0}),[te]);return(0,M.jsxs)(`section`,{className:`relative min-w-0 flex-1 flex flex-col overflow-hidden bg-[#0b0b0b] text-[#d4d4d4]`,"data-pibo-component":`CompactTerminalSessionView`,"data-pibo-debug":`compact-terminal-session-view`,"data-pibo-session-id":e?.piboSessionId??void 0,children:[(0,M.jsx)(YC,{errorCount:O,toolErrorCount:D,userMessageCount:ee,onNavigate:re,sessionAgentProfile:a,sessionActiveModel:o,sessionBreadcrumbs:l,originSession:u,derivedSessions:d,onOpenSession:g}),(0,M.jsx)(`div`,{className:`min-h-0 flex-1 overflow-hidden`,children:e?b.length?(0,M.jsx)(Li,{ref:ne.virtuosoRef,data:b,initialTopMostItemIndex:WC,increaseViewportBy:GC,defaultItemHeight:KC,className:`min-h-0 h-full overflow-x-hidden font-mono text-[12px] leading-[1.45]`,computeItemKey:(e,t)=>t.id,scrollerRef:ne.scrollerRef,atBottomStateChange:ne.atBottomStateChange,atBottomThreshold:ne.atBottomThreshold,followOutput:ne.followOutput,totalListHeightChanged:ne.totalListHeightChanged,alignToBottom:!0,components:oe,itemContent:ae},e.piboSessionId):(0,M.jsx)(Sw,{isLoading:n,agentProfiles:f,disabled:p,onSelectAgentProfile:m,message:`No visible trace rows yet.`}):(0,M.jsx)(Sw,{isLoading:n,agentProfiles:f,disabled:p,onSelectAgentProfile:m})}),ne.isSticky?null:(0,M.jsx)(`button`,{type:`button`,onClick:()=>ne.stickToBottom(`auto`),title:`Scroll to latest`,"aria-label":`Scroll to latest`,className:`absolute right-4 bottom-4 z-30 inline-flex h-9 w-9 items-center justify-center rounded-sm border border-[#38bdf8] bg-[#111111]/95 text-[#38bdf8] shadow-lg shadow-black/30 hover:bg-[#161616]`,children:(0,M.jsx)(Me,{size:18})})]})}function YC({errorCount:e,toolErrorCount:t,userMessageCount:n,onNavigate:r,sessionAgentProfile:i,sessionActiveModel:a,sessionBreadcrumbs:o,originSession:s,derivedSessions:c,onOpenSession:l}){return(0,M.jsxs)(`div`,{className:`border-b border-[#2a2a2a] bg-[#111111] px-4 py-2 text-[11px]`,children:[(0,M.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i?(0,M.jsx)(bw,{tone:`neutral`,children:i}):null,a?(0,M.jsx)(bw,{tone:`purple`,children:a}):null,n>0?(0,M.jsxs)(bw,{tone:`cyan`,label:`${n} user messages · jump to previous user message`,onClick:()=>r(`user`),children:[n,(0,M.jsx)(ct,{size:12})]}):null,e>0?(0,M.jsxs)(bw,{tone:`red`,label:`${e} errors · jump to previous error`,onClick:()=>r(`system`),children:[e,(0,M.jsx)(Ve,{size:12})]}):null,t>0?(0,M.jsxs)(bw,{tone:`amber`,label:`${t} tool call errors · jump to previous tool error`,onClick:()=>r(`tool`),children:[t,(0,M.jsx)($e,{size:12})]}):null,s?(0,M.jsxs)(XC,{onClick:()=>l(s.piboSessionId),children:[`Origin `,s.label]}):null,c.map(e=>(0,M.jsxs)(XC,{onClick:()=>l(e.piboSessionId),children:[`Derived `,e.label]},e.piboSessionId))]}),o.length?(0,M.jsx)(`div`,{className:`mt-2 flex flex-wrap items-center gap-1 text-[#737373]`,children:o.map((e,t)=>(0,M.jsxs)(`div`,{className:`flex items-center gap-1`,children:[t>0?(0,M.jsx)(Ne,{size:12,className:`text-[#525252]`}):null,(0,M.jsx)(`button`,{type:`button`,onClick:()=>l(e.piboSessionId),className:`hover:text-[#38bdf8]`,children:e.label})]},e.piboSessionId))}):null]})}function XC({children:e,onClick:t}){return(0,M.jsx)(`button`,{type:`button`,onClick:t,className:`border border-[#3a3a3a] px-2 py-0.5 text-[#38bdf8] hover:border-[#38bdf8]`,children:e})}function ZC({row:e,expanded:t,focused:n,piboSessionId:r,onToggle:i,onFork:a,onOpenSession:o,onThinkingLevelChange:s,onModelChanged:c}){let l=!t&&sw(e),u=l?ow(e):e.lines;return(0,M.jsxs)(`div`,{className:tw(e,n),"data-pibo-component":`TerminalRow`,"data-pibo-debug":`terminal-row`,"data-pibo-terminal-row":`true`,"data-row-id":e.id,"data-row-kind":e.kind,"data-row-status":e.status,"data-trace-node-id":e.sourceNodeIds.join(` `),"data-event-id":e.eventId,"data-run-id":e.runId,"data-order-source":e.orderSource,"data-order-stream-id":e.orderStreamId,"data-order-frame-index":e.orderStreamFrameIndex,onDoubleClick:e.expandable?t=>{!e.expandable||cw(t)||i()}:void 0,onKeyDown:e.expandable?t=>{!e.expandable||cw(t)||(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),i())}:void 0,role:e.expandable?`button`:void 0,tabIndex:e.expandable||n?0:void 0,"aria-expanded":e.expandable?t:void 0,"aria-current":n?`true`:void 0,children:[(0,M.jsxs)(`div`,{className:`flex gap-3`,children:[(0,M.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,M.jsx)(QC,{row:e,visibleLines:u,collapseToolCallPreview:l,piboSessionId:r,onThinkingLevelChange:s,onModelChanged:c})}),(0,M.jsx)(ew,{row:e,onFork:a,onOpenSession:o})]}),t?(0,M.jsx)(Ky,{row:e,onOpenSession:o}):null]})}function QC({row:e,visibleLines:t,collapseToolCallPreview:n,piboSessionId:r,onThinkingLevelChange:i,onModelChanged:a}){return e.kind===`message.assistant`?(0,M.jsx)(`div`,{className:`ml-[1.9rem] min-w-0`,"data-pibo-component":`TerminalAssistantMessage`,children:(0,M.jsx)(`div`,{className:`compact-terminal-markdown`,"data-pibo-component":`MarkdownRendererHost`,"data-pibo-markdown-kind":`assistant-message`,children:(0,M.jsx)(uy,{streaming:e.status===`running`,children:typeof e.output==`string`?e.output:``})})}):e.kind===`tool.status`?(0,M.jsx)(RC,{row:e}):e.kind===`tool.thinking`?(0,M.jsx)(HC,{row:e,onLevelSelect:i}):e.kind===`tool.login`?(0,M.jsx)(Ob,{row:e,piboSessionId:r}):e.kind===`tool.model`?(0,M.jsx)(Pb,{row:e,piboSessionId:r,onModelChanged:a}):e.kind===`execution.compaction`&&e.status===`running`?(0,M.jsx)(vw,{}):e.kind===`reasoning`&&e.markdown?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)($C,{lines:t,status:e.status,clampPreview:n}),(0,M.jsx)(`div`,{className:`ml-[1.9rem] min-w-0`,"data-pibo-component":`TerminalReasoningMarkdown`,children:(0,M.jsx)(`div`,{className:`compact-terminal-markdown compact-terminal-reasoning`,"data-pibo-component":`MarkdownRendererHost`,"data-pibo-markdown-kind":`reasoning`,children:(0,M.jsx)(uy,{streaming:e.status===`running`,children:e.markdown})})})]}):(0,M.jsx)($C,{lines:t,status:e.status,clampPreview:n})}function $C({lines:e,status:t,clampPreview:n}){return e.map((e,r)=>(0,M.jsx)(cb,{line:e,status:t,clampLines:n&&r===0?5:void 0},r))}function ew({row:e,onFork:t,onOpenSession:n}){return(0,M.jsxs)(`div`,{className:`flex shrink-0 items-start gap-1 transition-opacity ${e.forkEntryId?`opacity-100`:`opacity-0 group-hover:opacity-100 group-focus-within:opacity-100`}`,children:[e.linkedPiboSessionId?(0,M.jsx)(xw,{label:`Open linked session`,onClick:()=>n(e.linkedPiboSessionId),children:`Open`}):null,e.forkEntryId?(0,M.jsxs)(xw,{label:`Fork from this user message`,onClick:()=>t(e.forkEntryId),children:[(0,M.jsx)(Qe,{size:13}),`Fork`]}):null]})}function tw(e,t=!1){let n=e.kind===`message.user`?`group border-b border-[#141414] bg-[#11a4d4]/10 py-2 last:border-b-0 hover:bg-[#11a4d4]/15`:e.kind===`execution.command`?`group border-b border-[#141414] bg-[#f59e0b]/5 py-2 last:border-b-0 hover:bg-[#f59e0b]/10`:`group border-b border-[#141414] py-2 last:border-b-0 hover:bg-[#161616]`,r=e.expandable||t?` focus:outline-none focus:ring-1 focus:ring-[#38bdf8]/50`:``;return t?`${n}${r} ring-1 ring-[#38bdf8] bg-[#123040]`:`${n}${r}`}function nw(e,t,n){let r=new Set;for(let i of t)e.has(i.id)&&r.add(i.id),n&&i.kind===`reasoning`&&i.expandable&&r.add(i.id);return Cw(e,r)?e:r}function rw(e,t){return t===`user`?e.kind===`message.user`:e.status===`error`?t===`tool`?e.errorKind===`tool`:e.errorKind!==`tool`:!1}function iw(e,t,n){let r=e.map((e,t)=>({row:e,index:t})).filter(({row:e})=>rw(e,t));if(!r.length)return;let i=n?e.findIndex(e=>e.id===n):-1,a=i>=0?i:e.length;return{...r.filter(e=>e.index<a).at(-1)??r[r.length-1],fromIndex:a}}function aw(e){let t=0,n=()=>{let r=Array.from(document.querySelectorAll(`[data-pibo-component="TerminalRow"]`)).find(t=>t.dataset.rowId===e);if(r){r.scrollIntoView({block:`start`,inline:`nearest`,behavior:`smooth`}),r.focus({preventScroll:!0});return}t+=1,t<8&&requestAnimationFrame(n)};requestAnimationFrame(()=>requestAnimationFrame(n))}function ow(e){return e.kind===`tool.group.exploring`||e.kind===`tool.group.images`?e.lines.slice(0,qC):e.lines}function sw(e){return!!e.expandable&&(e.kind===`tool.call`||e.kind===`tool.image`||e.kind===`tool.group.exploring`||e.kind===`tool.group.images`||e.kind===`agent.delegation`||e.kind===`agent.async`||e.kind===`yielded.run`||e.kind===`execution.command`||e.kind===`execution.compaction`)}function cw(e){let t=e.target;if(!(t instanceof Element)||t===e.currentTarget)return!1;let n=t.closest(`button, a, input, textarea, select, summary, [role='button'], [tabindex]:not([tabindex='-1'])`);return!!(n&&n!==e.currentTarget)}var lw=`Working...`,uw=33,dw=126;function fw(){let{chars:e,activeIndex:t}=pw(lw);return(0,M.jsx)(`div`,{className:`border-t border-[#141414] px-4 py-2`,role:`status`,"aria-live":`polite`,"aria-label":`Working`,children:(0,M.jsxs)(`div`,{className:`grid grid-cols-[1.9rem_minmax(0,1fr)] gap-2 whitespace-pre-wrap break-words`,children:[(0,M.jsx)(`span`,{className:`whitespace-pre text-[#737373]`,children:`•`}),(0,M.jsx)(`span`,{className:`compact-terminal-working-scramble`,"aria-hidden":`true`,children:e.map((e,n)=>(0,M.jsx)(`span`,{className:n===t?`compact-terminal-working-scramble-active`:void 0,children:e},n))})]})})}function pw(e){let t=(0,v.useMemo)(()=>Array.from(e),[e]),[n,r]=(0,v.useState)(()=>hw(t)),[i,a]=(0,v.useState)(0);return(0,v.useEffect)(()=>{let e=0,n=0,i=_w(),o=0;r(hw(t));let s=window.setInterval(()=>{if(o>0){o--;return}if(e>=t.length){e=0,n=0,i=_w(),r(hw(t)),a(0);return}let s=e,c=t[s]??` `;if(a(s),n++,n<i){r(e=>mw(e,s,gw(c)));return}r(e=>mw(e,s,c)),e++,n=0,i=_w(),e>=t.length&&(r(t),a(-1),o=18)},55);return()=>window.clearInterval(s)},[t]),{chars:n,activeIndex:i}}function mw(e,t,n){let r=[...e];return r[t]=n,r}function hw(e){return e.map(e=>gw(e))}function gw(e){let t=``;do{let e=uw+Math.floor(Math.random()*(dw-uw+1));t=String.fromCharCode(e)}while(t===e);return t}function _w(){return 2+Math.floor(Math.random()*11)}function vw(){let e=yw();return(0,M.jsxs)(`div`,{className:`grid grid-cols-[1.9rem_minmax(0,1fr)] gap-2 whitespace-pre-wrap break-words`,children:[(0,M.jsx)(`span`,{className:`whitespace-pre text-[#38bdf8]`,children:`•`}),(0,M.jsxs)(`span`,{className:`min-w-0`,children:[(0,M.jsx)(`span`,{className:`font-semibold text-[#38bdf8]`,children:`Compacting`}),(0,M.jsx)(`span`,{className:`text-[#38bdf8]`,children:e})]})]})}function yw(){let[e,t]=(0,v.useState)(0);return(0,v.useEffect)(()=>{let e=window.setInterval(()=>t(e=>(e+1)%4),400);return()=>window.clearInterval(e)},[]),`.`.repeat(e)}function bw({tone:e,label:t,onClick:n,children:r}){let i=`inline-flex items-center gap-1 border px-2 py-0.5 ${e===`cyan`?`border-[#1f4960] text-[#38bdf8]`:e===`red`?`border-[#5f2222] text-[#ef4444]`:e===`amber`?`border-[#6b4e16] text-[#f59e0b]`:e===`purple`?`border-purple-500/40 text-purple-300`:`border-[#3a3a3a] text-[#d4d4d4]`}`;return n?(0,M.jsx)(`button`,{type:`button`,onClick:n,className:`${i} hover:bg-white/5 focus:outline-none focus:ring-1 focus:ring-[#38bdf8]`,title:t,"aria-label":t,children:r}):(0,M.jsx)(`span`,{className:i,title:t,"aria-label":t,children:r})}function xw({label:e,onClick:t,children:n}){return(0,M.jsx)(`button`,{type:`button`,onClick:t,"aria-label":e,title:e,className:`inline-flex min-h-7 min-w-7 items-center gap-1 border border-[#3a3a3a] px-2 text-[11px] text-[#737373] hover:border-[#38bdf8] hover:text-[#38bdf8]`,children:n})}function Sw({isLoading:e,agentProfiles:t,disabled:n,onSelectAgentProfile:r,message:i}){return(0,M.jsxs)(`div`,{className:`flex min-h-full flex-col items-center justify-center gap-4 px-6 py-10 text-center text-[12px] text-[#737373]`,children:[(0,M.jsx)(`div`,{children:e?`Loading trace…`:i??`No trace selected.`}),t.length?(0,M.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:t.map(e=>(0,M.jsx)(`button`,{type:`button`,disabled:n,onClick:()=>r(e.name),className:`border border-[#3a3a3a] px-2 py-1 text-[#d4d4d4] hover:border-[#38bdf8] hover:text-[#38bdf8] disabled:opacity-50`,children:e.name},e.name))}):null]})}function Cw(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function ww({traceView:e,isLoading:t,selectedSessionStatus:n,selectedSessionSignal:r,workflowProjectSession:i,workflowLifecycleEvents:a,sessionNodes:o,onOpenSession:s,onRefreshBootstrap:c,onError:l}){let u=i?Ww(i,e,n,r,a??[],o):null;return u?(0,M.jsx)(`section`,{className:`min-w-0 flex-1 overflow-auto bg-[#0b0f14] p-4 text-slate-300`,children:(0,M.jsxs)(`div`,{className:`mx-auto flex max-w-6xl flex-col gap-4`,children:[(0,M.jsx)(Tw,{model:u}),(0,M.jsx)(Ew,{}),(0,M.jsx)(Dw,{model:u,onRefreshBootstrap:c,onError:l}),(0,M.jsx)(kw,{model:u}),(0,M.jsx)(Aw,{model:u,onOpenSession:s}),(0,M.jsx)(Lw,{nodes:u.nodes,edges:u.edges}),(0,M.jsxs)(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_360px]`,children:[(0,M.jsx)(zw,{model:u}),(0,M.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-4`,children:[(0,M.jsx)(Bw,{model:u}),(0,M.jsx)(Vw,{model:u}),(0,M.jsx)(Hw,{model:u})]})]})]})}):(0,M.jsx)(`section`,{className:`min-w-0 flex-1 overflow-auto bg-[#0b0f14] p-4 text-slate-300`,children:(0,M.jsxs)(`div`,{className:`mx-auto flex max-w-4xl flex-col gap-4`,children:[(0,M.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4`,children:[(0,M.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-semibold text-slate-100`,children:[(0,M.jsx)(rt,{size:16,className:`text-[#11a4d4]`}),`Workflow / XState`]}),(0,M.jsx)(`p`,{className:`mt-2 text-sm text-slate-400`,children:t?`Loading session trace…`:`This session is not linked to a workflow run, so no Workflow/XState projection is available.`})]}),(0,M.jsx)(Ew,{})]})})}function Tw({model:e}){return(0,M.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4`,children:[(0,M.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,M.jsxs)(`div`,{className:`min-w-0`,children:[(0,M.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-semibold text-slate-100`,children:[(0,M.jsx)(rt,{size:16,className:`text-[#11a4d4]`}),`Workflow / XState Projection`]}),(0,M.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2 text-xs`,children:[(0,M.jsx)(ET,{tone:`blue`,children:e.workflowId}),e.workflowRunId?(0,M.jsxs)(ET,{tone:`slate`,children:[`run `,jT(e.workflowRunId)]}):null,(0,M.jsx)(ET,{tone:DT(e.status),children:e.state})]})]}),(0,M.jsxs)(`div`,{className:`min-w-0 text-right font-mono text-[11px] text-slate-500`,children:[(0,M.jsxs)(`div`,{className:`truncate`,children:[`session `,jT(e.piboSessionId)]}),e.latestStreamId===void 0?null:(0,M.jsxs)(`div`,{children:[`stream `,e.latestStreamId]})]})]}),(0,M.jsx)(`p`,{className:`mt-3 text-sm text-slate-400`,children:`Dedicated Project workflow execution surface. This view derives the current XState-style UI snapshot from project-session workflow linkage and live session state while keeping kernel records as durable truth.`})]})}function Ew(){return(0,M.jsx)(`div`,{className:`rounded-sm border border-amber-500/30 bg-amber-500/10 p-4 text-sm`,children:(0,M.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,M.jsxs)(`div`,{className:`min-w-0`,children:[(0,M.jsxs)(`div`,{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-amber-200`,children:[(0,M.jsx)(gt,{size:14}),`Workflow IR source-of-truth boundary`]}),(0,M.jsx)(`p`,{className:`mt-2 max-w-3xl text-xs leading-5 text-amber-100/80`,children:`Projects inspect configured sessions, workflow runs, and the XState-style projection derived from Pibo Workflow IR. Authoring stays in the Workflows tab; raw XState editing and inline executable code are not exposed here.`})]}),(0,M.jsxs)(`div`,{className:`flex shrink-0 flex-wrap gap-2`,children:[(0,M.jsx)(`span`,{className:`rounded border border-amber-500/40 bg-[#0b0f14]/50 px-2 py-1 text-[10px] uppercase tracking-wide text-amber-100/80`,children:`IR: source of truth`}),(0,M.jsx)(`span`,{className:`rounded border border-amber-500/40 bg-[#0b0f14]/50 px-2 py-1 text-[10px] uppercase tracking-wide text-amber-100/80`,children:`XState: projection only`})]})]})})}function Dw({model:e,onRefreshBootstrap:t,onError:n}){let r=e.workflowRunId?Iw(e):void 0,i=`${e.workflowId}${e.workflowVersion?`@${e.workflowVersion}`:``}`;return(0,M.jsxs)(`div`,{className:`grid gap-4 lg:grid-cols-3`,"aria-label":`Projects workflow execution shell`,children:[(0,M.jsx)(Pw,{title:`Workflow configured-session view`,icon:(0,M.jsx)(at,{size:14}),children:(0,M.jsxs)(`div`,{className:`space-y-3 text-xs text-slate-400`,children:[(0,M.jsx)(Fw,{label:`selected workflow`,value:i}),(0,M.jsx)(Fw,{label:`session state`,value:e.workflowRunId?`started`:`configured/not-started`}),(0,M.jsx)(Fw,{label:`input keys`,value:String(e.configuration.inputKeys.length)}),(0,M.jsx)(Fw,{label:`prompt overrides`,value:String(e.configuration.promptOverrideNodeIds.length)}),(0,M.jsx)(`p`,{className:`leading-5 text-slate-500`,children:`Saved configuration is reviewed here before Start. Workflow selection and session overrides remain immutable for this configured Project session.`})]})}),(0,M.jsx)(Pw,{title:`Workflow run view`,icon:(0,M.jsx)(Se,{size:14}),children:(0,M.jsxs)(`div`,{className:`space-y-3 text-xs text-slate-400`,children:[(0,M.jsx)(Fw,{label:`run id`,value:e.workflowRunId?jT(e.workflowRunId):`not started`}),(0,M.jsx)(Fw,{label:`status`,value:e.state}),(0,M.jsx)(Fw,{label:`current node`,value:r?.label??`none`}),(0,M.jsx)(Fw,{label:`output`,value:e.finalOutput?`available`:`empty`}),(0,M.jsx)(Fw,{label:`error`,value:e.runtimeErrors.length?`${e.runtimeErrors.length} runtime errors`:e.validationErrors.length?`${e.validationErrors.length} validation diagnostics`:`none`}),(0,M.jsx)(`p`,{className:`leading-5 text-slate-500`,children:`This workflow run view container is the stable Project home for status, current node, output, and error sections.`})]})}),(0,M.jsx)(Pw,{title:`Human action area`,icon:(0,M.jsx)(Ue,{size:14}),children:(0,M.jsx)(Ow,{model:e,onRefreshBootstrap:t,onError:n})})]})}function Ow({model:e,onRefreshBootstrap:t,onError:n}){let[r,i]=(0,v.useState)({}),[a,o]=(0,v.useState)(null),[s,c]=(0,v.useState)({}),[l,u]=(0,v.useState)({}),d=(e,t)=>{i(n=>({...n,[e]:t}))},f=async(i,a)=>{if(!i.waitTokenId||!a.registered)return;let s=`${i.waitTokenId}:${a.id}`,l=a.kind??`resume`,d;if(l===`resume`){let e=r[i.waitTokenId]??(i.payloadRequirements?.required?`{}`:``);if(e.trim())try{d=JSON.parse(e)}catch{let e=[{code:`WorkflowRuntimeError.invalidHumanActionPayload`,message:`Resume payload must be valid JSON before it can be submitted.`,severity:`error`,path:`$.payload`,hint:`Enter JSON such as {"comment":"Approved"}.`}];c(t=>({...t,[i.waitTokenId]:e})),n?.(`Resume payload must be valid JSON.`);return}}o(s),c(e=>({...e,[i.waitTokenId]:[]}));try{await Sb(e.projectId,e.piboSessionId,{waitTokenId:i.waitTokenId,actionId:a.id,...a.kind?{kind:a.kind}:{},...d===void 0?{}:{payload:d}}),u(e=>({...e,[i.waitTokenId]:`${a.displayName} submitted.`})),n?.(null),await t?.()}catch(e){let t=mT(e);c(e=>({...e,[i.waitTokenId]:t})),n?.(t[0]?.message??hT(e))}finally{o(null)}};return(0,M.jsxs)(`div`,{className:`space-y-3 text-xs text-slate-400`,children:[e.pendingHumanActions.length?(0,M.jsx)(`div`,{className:`space-y-3`,children:e.pendingHumanActions.map(e=>{let t=[...e.diagnostics,...e.waitTokenId?s[e.waitTokenId]??[]:[]];return(0,M.jsxs)(`div`,{className:`rounded-sm border border-amber-500/40 bg-amber-500/10 p-3 text-amber-100`,"aria-label":`Pending workflow human action wait token`,children:[(0,M.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,M.jsxs)(`div`,{className:`min-w-0`,children:[(0,M.jsx)(`div`,{className:`font-semibold`,children:e.label}),(0,M.jsx)(`div`,{className:`mt-1 break-words text-[11px] leading-5 text-amber-100/80`,children:e.prompt})]}),(0,M.jsx)(`span`,{className:`shrink-0 rounded border border-amber-400/40 bg-[#0b0f14]/40 px-1.5 py-0.5 font-mono text-[10px] text-amber-100/70`,children:e.waitTokenId?jT(e.waitTokenId):e.source})]}),(0,M.jsxs)(`div`,{className:`mt-2 grid gap-2 text-[11px] text-amber-100/75`,children:[(0,M.jsx)(Fw,{label:`human node`,value:e.humanNodeId??`unspecified`}),(0,M.jsx)(Fw,{label:`payload`,value:e.payloadRequirements?.description??`No persisted payload schema.`}),e.expiresAt?(0,M.jsx)(Fw,{label:`expires`,value:e.expiresAt}):null]}),e.payloadRequirements?.schema?(0,M.jsxs)(`div`,{className:`mt-2 rounded-sm border border-amber-400/25 bg-[#0b0f14]/50 p-2`,children:[(0,M.jsx)(`div`,{className:`mb-1 text-[10px] font-bold uppercase tracking-wider text-amber-100/70`,children:`Resume payload schema`}),(0,M.jsx)(Sc,{value:e.payloadRequirements.schema,defaultExpandLevel:1,maxHeight:`10rem`,showControls:!1})]}):null,e.availableActions.some(e=>e.kind===`resume`)?(0,M.jsxs)(`label`,{className:`mt-3 block text-[11px] text-amber-100/80`,children:[(0,M.jsx)(`span`,{className:`mb-1 block font-semibold`,children:`Resume payload JSON`}),(0,M.jsx)(`textarea`,{className:`min-h-20 w-full rounded-sm border border-amber-500/30 bg-[#0b0f14] px-2 py-1.5 font-mono text-[11px] text-amber-50 outline-none focus:border-[#11a4d4]`,value:r[e.waitTokenId??e.id]??(e.payloadRequirements?.required?`{}`:``),onChange:t=>d(e.waitTokenId??e.id,t.target.value),placeholder:`{"comment":"Approved"}`})]}):null,(0,M.jsx)(`div`,{className:`mt-3 flex flex-wrap gap-2`,"aria-label":`Workflow wait token actions`,children:e.availableActions.length?e.availableActions.map(t=>{let n=`${e.waitTokenId}:${t.id}`;return(0,M.jsx)(`button`,{type:`button`,disabled:!e.waitTokenId||!t.registered||a!==null,onClick:()=>void f(e,t),className:`rounded-sm border border-amber-400/40 bg-[#0b0f14]/70 px-2.5 py-1 text-[11px] font-semibold text-amber-100 transition hover:border-[#11a4d4] hover:text-[#8bdcf4] disabled:cursor-not-allowed disabled:opacity-50`,title:t.description??t.id,children:a===n?`Submitting…`:t.displayName},t.id)}):(0,M.jsx)(`span`,{className:`text-amber-100/60`,children:`No registered human actions are available for this wait token.`})}),e.waitTokenId&&l[e.waitTokenId]?(0,M.jsx)(`div`,{className:`mt-2 text-[11px] text-emerald-200`,children:l[e.waitTokenId]}):null,t.length?(0,M.jsx)(`div`,{className:`mt-2 space-y-1`,"aria-label":`Human action diagnostics`,children:t.map((e,t)=>(0,M.jsxs)(`div`,{className:`rounded border border-red-400/35 bg-red-500/15 p-2 text-[11px] leading-5 text-red-100`,children:[(0,M.jsx)(`div`,{children:e.message}),(0,M.jsxs)(`div`,{className:`mt-1 font-mono text-[10px] text-red-100/70`,children:[e.code,e.path?` · ${e.path}`:``]})]},`${e.code}:${t}`))}):null]},e.id)})}):(0,M.jsx)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-3 text-slate-500`,children:`No pending human action. Approval, rejection, resume, and cancel controls render here when a persisted workflow wait token exists.`}),(0,M.jsx)(`p`,{className:`leading-5 text-slate-500`,children:`This human action area lives inside the workflow run context, validates wait-token state and resume payloads, and stays separate from normal Terminal chat controls.`})]})}function kw({model:e}){let t=e.workflowRunId?Iw(e):void 0,n=[...e.runtimeErrors.map(e=>({...e,source:e.source??`runtime`})),...e.validationErrors.map(e=>({...e,source:e.source??`validation`}))].slice(0,8);return(0,M.jsxs)(`section`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,"aria-label":`Workflow run inspection panel`,children:[(0,M.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,M.jsxs)(`div`,{className:`min-w-0`,children:[(0,M.jsxs)(`div`,{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,M.jsx)(Ke,{size:14}),`Workflow run inspection`]}),(0,M.jsx)(`p`,{className:`mt-2 max-w-3xl text-xs leading-5 text-slate-500`,children:`Status, current node, history, attempts, transfers, output, and errors are rendered from Project session and workflow run facts when a run is linked. The XState graph remains a visualization projection only.`})]}),(0,M.jsxs)(`div`,{className:`flex shrink-0 flex-wrap gap-2 text-[10px] uppercase tracking-wide`,children:[(0,M.jsx)(`span`,{className:`rounded border border-emerald-500/40 bg-emerald-500/10 px-2 py-1 text-emerald-200`,children:`kernel/run records: truth`}),(0,M.jsx)(`span`,{className:`rounded border border-amber-500/40 bg-amber-500/10 px-2 py-1 text-amber-100`,children:`XState projection only`})]})]}),(0,M.jsxs)(`div`,{className:`mt-4 grid gap-3 lg:grid-cols-3`,children:[(0,M.jsxs)(jw,{title:`Status`,badge:e.state,icon:(0,M.jsx)(Se,{size:14}),children:[(0,M.jsx)(Mw,{label:`run id`,value:e.workflowRunId?jT(e.workflowRunId):`not started`}),(0,M.jsx)(Mw,{label:`status`,value:e.state}),(0,M.jsx)(Mw,{label:`record source`,value:e.workflowRunId?`Project workflow run id`:`no run record yet`})]}),(0,M.jsxs)(jw,{title:`Current node`,badge:t?.status??`none`,icon:(0,M.jsx)(dt,{size:14}),children:[(0,M.jsx)(Mw,{label:`node`,value:t?.label??`none`}),(0,M.jsx)(Mw,{label:`node id`,value:t?.id??`none`}),(0,M.jsx)(Mw,{label:`source`,value:`project/session run cursor`})]}),(0,M.jsx)(jw,{title:`Run history`,badge:`${e.runHistory.length}`,icon:(0,M.jsx)(tt,{size:14}),children:e.runHistory.length?(0,M.jsx)(`div`,{className:`space-y-2`,children:e.runHistory.map(e=>(0,M.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:[(0,M.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,M.jsx)(`div`,{className:`min-w-0 truncate font-mono text-xs text-slate-200`,children:jT(e.id)}),(0,M.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide ${AT(e.status)}`,children:e.status})]}),(0,M.jsxs)(`div`,{className:`mt-1 text-[11px] text-slate-500`,children:[e.currentNodeId?`current ${e.currentNodeId}`:`no current node`,` · `,e.source]}),(0,M.jsxs)(`div`,{className:`mt-1 font-mono text-[10px] text-slate-600`,children:[`updated `,e.updatedAt]})]},e.id))}):(0,M.jsx)(Nw,{children:e.workflowRunId?`No workflow run history for this selected Project session yet.`:`No current run attempts; this configured Project session has not been started.`})})]}),(0,M.jsxs)(`div`,{className:`mt-3 grid gap-3 lg:grid-cols-2`,children:[(0,M.jsx)(jw,{title:`Node attempts`,badge:`${e.nodeAttempts.length}`,icon:(0,M.jsx)(at,{size:14}),children:e.nodeAttempts.length?(0,M.jsx)(`div`,{className:`space-y-2`,children:e.nodeAttempts.map(e=>(0,M.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:[(0,M.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,M.jsxs)(`div`,{className:`min-w-0`,children:[(0,M.jsx)(`div`,{className:`truncate text-xs font-semibold text-slate-200`,children:e.label}),(0,M.jsxs)(`div`,{className:`mt-1 font-mono text-[10px] text-slate-500`,children:[e.nodeId,` · attempt `,e.attempt]})]}),(0,M.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide ${AT(e.status)}`,children:e.status})]}),(0,M.jsxs)(`div`,{className:`mt-1 text-[11px] text-slate-500`,children:[e.kind,` · `,e.source]})]},e.id))}):(0,M.jsx)(Nw,{children:e.workflowRunId?`No node attempts recorded for this workflow run yet.`:`No current node attempts; Start has not created a workflow run.`})}),(0,M.jsx)(jw,{title:`Edge transfers`,badge:`${e.edgeTransfers.length}`,icon:(0,M.jsx)(Qe,{size:14}),children:e.edgeTransfers.length?(0,M.jsx)(`div`,{className:`space-y-2`,children:e.edgeTransfers.map(e=>(0,M.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:[(0,M.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,M.jsx)(`div`,{className:`min-w-0 truncate font-mono text-xs text-slate-200`,children:e.edgeId}),(0,M.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide ${AT(e.status)}`,children:e.status})]}),(0,M.jsxs)(`div`,{className:`mt-1 text-[11px] text-slate-500`,children:[e.source,e.createdAt?` · ${e.createdAt}`:``]})]},e.id))}):(0,M.jsx)(Nw,{children:`No edge transfers recorded for this workflow run yet.`})}),(0,M.jsx)(jw,{title:`Output`,badge:e.finalOutput?`available`:`empty`,icon:(0,M.jsx)(ze,{size:14}),children:e.finalOutput?(0,M.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:[(0,M.jsx)(`div`,{className:`mb-2 font-mono text-[10px] text-slate-500`,children:e.finalOutput.source}),(0,M.jsx)(Sc,{value:e.finalOutput.value,defaultExpandLevel:1,maxHeight:`12rem`,showControls:!1})]}):(0,M.jsx)(Nw,{children:`No workflow output has been recorded for this run yet.`})}),(0,M.jsx)(jw,{title:`Error`,badge:n.length?`${n.length}`:`none`,icon:(0,M.jsx)(gt,{size:14}),children:n.length?(0,M.jsx)(`div`,{className:`space-y-2`,children:n.map(e=>(0,M.jsxs)(`div`,{className:`rounded-sm border border-red-500/35 bg-red-500/10 p-2 text-xs text-red-100`,children:[(0,M.jsx)(`div`,{className:`break-words`,children:e.message}),(0,M.jsxs)(`div`,{className:`mt-1 flex flex-wrap gap-1 font-mono text-[10px] text-red-200/70`,children:[e.code?(0,M.jsx)(`span`,{children:e.code}):null,e.source?(0,M.jsx)(`span`,{children:e.source}):null]})]},e.id))}):(0,M.jsx)(Nw,{children:`No workflow run errors are recorded.`})})]})]})}function Aw({model:e,onOpenSession:t}){let n=Jw(e.definitionLink);return(0,M.jsxs)(`section`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,"aria-label":`Workflow navigation links`,children:[(0,M.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,M.jsxs)(`div`,{className:`min-w-0`,children:[(0,M.jsxs)(`div`,{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,M.jsx)(qe,{size:14}),`Workflow navigation links`]}),(0,M.jsx)(`p`,{className:`mt-2 max-w-3xl text-xs leading-5 text-slate-500`,children:`Use these run-view links to move between real nested workflow sessions and the Workflows tab definition. Snapshot-only history is shown when the live definition is deleted or unavailable.`})]}),e.definitionLink.status===`live`&&n?(0,M.jsxs)(`a`,{className:`inline-flex shrink-0 items-center justify-center gap-1 rounded-sm border border-[#11a4d4]/50 px-3 py-1.5 text-xs font-semibold text-[#8bdcf4] transition hover:border-[#11a4d4] hover:text-slate-100`,href:n,children:[(0,M.jsx)(qe,{size:13}),`Open live workflow definition`]}):null]}),(0,M.jsxs)(`div`,{className:`mt-4 grid gap-3 lg:grid-cols-2`,children:[(0,M.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0f171e] p-3`,"aria-label":`Nested workflow child session links`,children:[(0,M.jsxs)(`div`,{className:`mb-3 flex items-center justify-between gap-2`,children:[(0,M.jsx)(`div`,{className:`text-xs font-bold uppercase tracking-wider text-slate-500`,children:`Nested workflow child sessions`}),(0,M.jsx)(`span`,{className:`rounded border border-slate-700 bg-[#0b0f14] px-1.5 py-0.5 font-mono text-[10px] text-slate-400`,children:e.nestedSessionLinks.length})]}),e.nestedSessionLinks.length?(0,M.jsx)(`div`,{className:`space-y-2`,children:e.nestedSessionLinks.map(e=>(0,M.jsx)(`button`,{type:`button`,onClick:()=>t(e.piboSessionId),className:`w-full rounded-sm border border-slate-800 bg-[#0b0f14] p-2 text-left transition hover:border-[#11a4d4]/60 hover:bg-[#102331]`,children:(0,M.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,M.jsxs)(`div`,{className:`min-w-0`,children:[(0,M.jsx)(`div`,{className:`truncate text-xs font-semibold text-slate-200`,children:e.title}),(0,M.jsx)(`div`,{className:`mt-1 font-mono text-[10px] text-slate-500`,children:jT(e.piboSessionId)})]}),(0,M.jsx)(`span`,{className:`rounded border border-[#11a4d4]/40 bg-[#11a4d4]/10 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-[#8bdcf4]`,children:`open session`})]})},e.piboSessionId))}):(0,M.jsx)(Nw,{children:`No nested workflow child sessions are linked under this selected Project session yet.`})]}),(0,M.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0f171e] p-3`,"aria-label":`Workflow definition link state`,children:[(0,M.jsx)(`div`,{className:`mb-3 text-xs font-bold uppercase tracking-wider text-slate-500`,children:`Workflow definition link`}),e.definitionLink.status===`live`&&n?(0,M.jsxs)(`div`,{className:`rounded-sm border border-emerald-500/35 bg-emerald-500/10 p-3 text-xs leading-5 text-emerald-100`,children:[(0,M.jsx)(`div`,{className:`font-semibold`,children:`Live workflow definition exists`}),(0,M.jsx)(`div`,{className:`mt-1 font-mono text-[11px] text-emerald-100/80`,children:Xw(e.definitionLink)}),e.definitionLink.definitionHash?(0,M.jsxs)(`div`,{className:`mt-1 font-mono text-[10px] text-emerald-100/60`,children:[`snapshot `,jT(e.definitionLink.definitionHash)]}):null]}):(0,M.jsxs)(`div`,{className:`rounded-sm border border-amber-500/40 bg-amber-500/10 p-3 text-xs leading-5 text-amber-100`,children:[(0,M.jsx)(`div`,{className:`font-semibold`,children:`Definition deleted — snapshot-only definition-deleted state`}),(0,M.jsx)(`div`,{className:`mt-1 font-mono text-[11px] text-amber-100/80`,children:Xw(e.definitionLink)}),(0,M.jsx)(`div`,{className:`mt-1 text-amber-100/80`,children:e.definitionLink.tombstoneLabel??`Historical run inspection uses the immutable Project session snapshot instead of a broken live definition link.`}),e.definitionLink.definitionHash?(0,M.jsxs)(`div`,{className:`mt-1 font-mono text-[10px] text-amber-100/60`,children:[`snapshot `,jT(e.definitionLink.definitionHash)]}):null]})]})]})]})}function jw({title:e,badge:t,icon:n,children:r}){return(0,M.jsxs)(`section`,{className:`min-w-0 rounded-sm border border-slate-800 bg-[#0f171e] p-3`,"aria-label":e,children:[(0,M.jsxs)(`div`,{className:`mb-3 flex items-center justify-between gap-3`,children:[(0,M.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,M.jsx)(`span`,{className:`text-[#11a4d4]`,children:n}),e]}),(0,M.jsx)(`span`,{className:`shrink-0 rounded border border-slate-700 bg-[#0b0f14] px-1.5 py-0.5 font-mono text-[10px] text-slate-400`,children:t})]}),r]})}function Mw({label:e,value:t}){return(0,M.jsxs)(`div`,{className:`flex items-start justify-between gap-3 border-b border-slate-800/70 py-2 first:pt-0 last:border-b-0 last:pb-0`,children:[(0,M.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-slate-500`,children:e}),(0,M.jsx)(`span`,{className:`min-w-0 max-w-[14rem] truncate text-right font-mono text-xs text-slate-300`,title:t,children:t})]})}function Nw({children:e}){return(0,M.jsx)(`div`,{className:`rounded-sm border border-dashed border-slate-800 bg-[#0b0f14] p-3 text-xs leading-5 text-slate-500`,children:e})}function Pw({title:e,icon:t,children:n}){return(0,M.jsxs)(`section`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4`,"aria-label":e,children:[(0,M.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,M.jsx)(`span`,{className:`text-[#11a4d4]`,children:t}),e]}),n]})}function Fw({label:e,value:t}){return(0,M.jsxs)(`div`,{className:`flex items-start justify-between gap-3 border-b border-slate-800/70 pb-2 last:border-b-0 last:pb-0`,children:[(0,M.jsx)(`span`,{className:`uppercase tracking-wide text-slate-500`,children:e}),(0,M.jsx)(`span`,{className:`min-w-0 max-w-[12rem] truncate text-right font-mono text-slate-300`,title:t,children:t})]})}function Iw(e){return e.nodes.find(e=>e.status===`active`||e.status===`waiting`)??e.nodes[0]}function Lw({nodes:e,edges:t}){return(0,M.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0f171e] p-4`,children:[(0,M.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,M.jsx)(dt,{size:14}),`Visual State Flow`]}),(0,M.jsx)(`div`,{className:`grid gap-3 md:grid-cols-[1fr_auto_1fr_auto_1fr]`,children:e.map((e,n)=>(0,M.jsx)(Rw,{node:e,edge:t[n]},e.id))})]})}function Rw({node:e,edge:t}){return(0,M.jsxs)(M.Fragment,{children:[(0,M.jsxs)(`div`,{className:`rounded-sm border p-3 ${OT(e.status)}`,children:[(0,M.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,M.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,M.jsx)(TT,{status:e.status}),(0,M.jsx)(`div`,{className:`min-w-0 truncate text-sm font-semibold text-slate-100`,children:e.label})]}),(0,M.jsx)(`span`,{className:`rounded border border-slate-700 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-slate-400`,children:e.kind})]}),(0,M.jsx)(`p`,{className:`mt-2 text-xs text-slate-400`,children:e.description})]}),t?(0,M.jsx)(`div`,{className:`hidden items-center justify-center text-center text-[10px] uppercase tracking-wide text-slate-500 md:flex`,children:(0,M.jsxs)(`div`,{children:[(0,M.jsx)(Qe,{size:14,className:`mx-auto mb-1 text-[#11a4d4]`}),t.label]})}):null]})}function zw({model:e}){return(0,M.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4`,children:[(0,M.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,M.jsx)(Se,{size:14}),`Current UI Snapshot`]}),(0,M.jsx)(Sc,{value:e.snapshot,showControls:!1})]})}function Bw({model:e}){return(0,M.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,children:[(0,M.jsxs)(`div`,{className:`mb-3 flex items-center justify-between gap-3`,children:[(0,M.jsxs)(`div`,{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,M.jsx)(at,{size:14}),`Node Statuses`]}),(0,M.jsxs)(`span`,{className:`font-mono text-[11px] text-slate-500`,children:[e.nodes.length,` nodes`]})]}),(0,M.jsx)(`div`,{className:`space-y-2`,children:e.nodes.map(e=>(0,M.jsxs)(`div`,{className:`rounded-sm border px-3 py-2 ${OT(e.status)}`,children:[(0,M.jsxs)(`div`,{className:`flex min-w-0 items-start justify-between gap-3`,children:[(0,M.jsxs)(`div`,{className:`flex min-w-0 items-start gap-2`,children:[(0,M.jsx)(`span`,{className:`mt-0.5 shrink-0`,children:(0,M.jsx)(TT,{status:e.status})}),(0,M.jsxs)(`div`,{className:`min-w-0`,children:[(0,M.jsx)(`div`,{className:`truncate text-sm font-semibold text-slate-100`,children:e.label}),(0,M.jsx)(`div`,{className:`mt-0.5 truncate font-mono text-[11px] text-slate-500`,children:e.id})]})]}),(0,M.jsxs)(`div`,{className:`flex shrink-0 flex-col items-end gap-1`,children:[(0,M.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide ${kT(e.status)}`,children:e.status}),(0,M.jsx)(`span`,{className:`rounded border border-slate-700 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-slate-400`,children:e.kind})]})]}),(0,M.jsx)(`p`,{className:`mt-2 text-xs text-slate-400`,children:e.description})]},e.id))}),(0,M.jsx)(`p`,{className:`mt-3 text-xs text-slate-500`,children:`Node status is reconstructed from the workflow run linkage and live session state; persisted kernel records remain the durable source of truth.`})]})}function Vw({model:e}){return(0,M.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,children:[(0,M.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,M.jsx)(ze,{size:14}),`Final Output & Validation`]}),(0,M.jsxs)(`div`,{className:`space-y-4`,children:[(0,M.jsxs)(`div`,{children:[(0,M.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,M.jsx)(`div`,{className:`text-xs font-semibold uppercase tracking-wide text-slate-400`,children:`Final output`}),e.finalOutput?(0,M.jsx)(`span`,{className:`rounded border border-slate-700 px-1.5 py-0.5 font-mono text-[10px] text-slate-500`,children:e.finalOutput.source}):null]}),e.finalOutput?(0,M.jsx)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:(0,M.jsx)(Sc,{value:e.finalOutput.value,defaultExpandLevel:1,maxHeight:`14rem`,showControls:!1})}):(0,M.jsx)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-3 text-xs text-slate-500`,children:`No final workflow output is available yet. Completed workflow-backed sessions show the final assistant output here.`})]}),(0,M.jsxs)(`div`,{children:[(0,M.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,M.jsx)(`div`,{className:`text-xs font-semibold uppercase tracking-wide text-slate-400`,children:`Validation errors`}),(0,M.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 font-mono text-[10px] ${e.validationErrors.length?`border-red-500/40 bg-red-500/10 text-red-300`:`border-emerald-500/40 bg-emerald-500/10 text-emerald-300`}`,children:e.validationErrors.length?`${e.validationErrors.length} found`:`none`})]}),e.validationErrors.length?(0,M.jsx)(`div`,{className:`space-y-2`,children:e.validationErrors.map(e=>(0,M.jsx)(`div`,{className:`rounded-sm border border-red-500/35 bg-red-500/10 p-2`,children:(0,M.jsxs)(`div`,{className:`flex min-w-0 items-start gap-2 text-xs text-red-200`,children:[(0,M.jsx)(gt,{size:14,className:`mt-0.5 shrink-0 text-red-300`}),(0,M.jsxs)(`div`,{className:`min-w-0`,children:[(0,M.jsx)(`div`,{className:`break-words`,children:e.message}),(0,M.jsxs)(`div`,{className:`mt-1 flex flex-wrap gap-1 font-mono text-[10px] text-red-200/70`,children:[e.code?(0,M.jsx)(`span`,{children:e.code}):null,e.path?(0,M.jsx)(`span`,{children:e.path}):null,e.source?(0,M.jsx)(`span`,{children:e.source}):null]})]})]})},e.id))}):(0,M.jsx)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-3 text-xs text-slate-500`,children:`No workflow validation diagnostics were found in the current session trace.`})]})]})]})}function Hw({model:e}){return(0,M.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,children:[(0,M.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,M.jsx)(He,{size:14}),`Projection Facts`]}),(0,M.jsxs)(`dl`,{className:`space-y-3`,children:[(0,M.jsx)(Uw,{label:`projection kind`,value:`pibo.workflow.xstateUiModel`}),(0,M.jsx)(Uw,{label:`schema`,value:`v1`}),(0,M.jsx)(Uw,{label:`durable truth`,value:`kernel`}),(0,M.jsx)(Uw,{label:`private payloads`,value:`not exposed`}),(0,M.jsx)(Uw,{label:`states`,value:String(e.nodes.length)}),(0,M.jsx)(Uw,{label:`transitions`,value:String(e.edges.length)}),(0,M.jsx)(Uw,{label:`trace`,value:e.traceVersion??`pending`})]})]})}function Uw({label:e,value:t}){return(0,M.jsxs)(`div`,{className:`flex items-center justify-between gap-3 border-b border-slate-800/70 pb-2 last:border-b-0 last:pb-0`,children:[(0,M.jsx)(`dt`,{className:`text-xs uppercase tracking-wide text-slate-500`,children:e}),(0,M.jsx)(`dd`,{className:`min-w-0 truncate text-right font-mono text-xs text-slate-300`,children:t})]})}function Ww(e,t,n,r,i,a){if(!vT(e))return null;let o=yT(e,n),s=bT(e,n),c=xT(s),l=oT(t,s),u=[...cT(t),...sT(e,i)],d=$w(e,o,c),f=eT(t,e.workflowRunId),p=rT(t,e.workflowRunId),m=iT(t,r),h=Gw(e),g=Kw(a,e.piboSessionId),_=[{id:`workflow.entry`,label:`workflow entry`,kind:`initial`,status:s===`idle`?`active`:`completed`,description:`Project session is linked to a workflow-capable route.`},{id:`node.session`,label:t?.title??`pibo session actor`,kind:`agent`,status:c===`node.session`?s:s===`completed`?`completed`:`idle`,description:`Normal Pibo routed session used as the visible workflow actor.`},{id:ST(s),label:CT(s),kind:`terminal`,status:c.startsWith(`workflow.`)?s:`idle`,description:`Terminal state projected from the current workflow/session state.`}];return{projectId:e.projectId,workflowId:e.workflowId,...e.workflowVersion?{workflowVersion:e.workflowVersion}:{},...e.workflowRunId?{workflowRunId:e.workflowRunId}:{},piboSessionId:e.piboSessionId,state:o,status:s,traceTitle:t?.title,traceVersion:t?.version,latestStreamId:t?.latestStreamId,nodes:_,edges:[{id:`workflow.transition.entry.session`,source:`workflow.entry`,target:`node.session`,label:`WORKFLOW.START`},{id:`workflow.transition.session.terminal`,source:`node.session`,target:ST(s),label:wT(s)}],configuration:Zw(e),definitionLink:h,nestedSessionLinks:g,pendingHumanActions:Qw(e,r),runHistory:d,nodeAttempts:f,edgeTransfers:p,runtimeErrors:m,...l?{finalOutput:l}:{},validationErrors:u,snapshot:{kind:`pibo.workflow.xstateUiModel`,schemaVersion:1,projection:{workflowId:e.workflowId,initialStateId:`workflow.entry`,durableTruth:`kernel`,exposesPrivatePayloads:!1},authoring:{location:`workflows_tab`,rawXStateEditingUi:`not_exposed`,inlineExecutableCodeUi:`not_exposed`},current:{snapshotKind:`ui`,...e.workflowRunId?{runId:e.workflowRunId}:{},status:o,stateIds:[c],nodeId:c===`node.session`?`session`:void 0},nodeStatuses:_.map(e=>({id:e.id,kind:e.kind,status:e.status})),runInspection:{durableTruth:`kernel_run_records`,xstateProjectionOnly:!0,runHistoryCount:d.length,nodeAttemptCount:f.length,edgeTransferCount:p.length,runtimeErrorCount:m.length},result:{hasFinalOutput:!!l,validationErrorCount:u.length},actors:[{id:`workflow.actor.session`,kind:`agent`,piboSessionId:e.piboSessionId}],definitionLink:{status:h.status,workflowId:h.workflowId,workflowVersion:h.workflowVersion,hasLiveLink:h.status===`live`&&!!Jw(h)},nestedWorkflowSessionCount:g.length}}}function Gw(e){return e.workflowDefinitionLink?e.workflowDefinitionLink:e.workflowVersion?{status:`live`,workflowId:e.workflowId,workflowVersion:e.workflowVersion,title:e.title??e.workflowId,href:Yw(e.workflowId,e.workflowVersion)}:{status:`snapshot_only_definition_deleted`,workflowId:e.workflowId,title:e.title??e.workflowId,tombstoneLabel:`Historical run inspection uses the immutable Project session snapshot instead of a broken live definition link.`}}function Kw(e,t){let n=qw(e,t);if(!n)return[];let r=[],i=e=>{for(let t of e)t.workflowSessionKind===`nested_workflow`&&r.push({piboSessionId:t.piboSessionId,title:t.title,kind:t.workflowSessionKind??t.profile??`workflow`,...t.workflowSessionKind?{workflowSessionKind:t.workflowSessionKind}:{}}),i(t.children)};return i(n.children),r}function qw(e,t){for(let n of e){if(n.piboSessionId===t)return n;let e=qw(n.children,t);if(e)return e}}function Jw(e){if(e.status===`live`){if(e.href)return e.href;if(e.workflowVersion)return Yw(e.workflowId,e.workflowVersion)}}function Yw(e,t){return`/apps/chat/workflows/view/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function Xw(e){return`${e.workflowId}${e.workflowVersion?`@${e.workflowVersion}`:``}`}function Zw(e){let t=e.configuration;return{inputKeys:Object.keys(t?.inputValues??{}).sort(),promptOverrideNodeIds:Object.keys(t?.promptOverrides??{}).sort()}}function Qw(e,t){if(e.pendingHumanActions?.length)return e.pendingHumanActions.map(e=>({id:`wait-token:${e.waitTokenId}`,waitTokenId:e.waitTokenId,workflowRunId:e.workflowRunId,...e.nodeAttemptId?{nodeAttemptId:e.nodeAttemptId}:{},...e.humanNodeId?{humanNodeId:e.humanNodeId}:{},prompt:e.prompt,label:`Pending registered human action`,source:`persisted wait token`,...e.schema?{schema:e.schema}:{},payloadRequirements:e.payloadRequirements,availableActions:e.availableActions,diagnostics:e.diagnostics,createdAt:e.createdAt,...e.expiresAt?{expiresAt:e.expiresAt}:{}}));let n=yT(e,void 0).toLowerCase(),r=[t?.aggregateStatus,t?.localStatus].filter(e=>typeof e==`string`).join(` `).toLowerCase();return n.includes(`waiting`)||n.includes(`blocked`)||r.includes(`waiting`)||r.includes(`blocked`)||t?.hasBlockedDescendant?[{id:`human-action:${e.piboSessionId}`,prompt:`Session signal indicates a wait, but no persisted workflow wait token is available in the Project run store.`,label:`Awaiting human action`,source:t?`session signal`:`project session state`,availableActions:[],diagnostics:[]}]:[]}function $w(e,t,n){return e.workflowRunId?[{id:e.workflowRunId,status:t,currentNodeId:n,updatedAt:e.updatedAt,source:`project session run record`}]:[]}function eT(e,t){return!t||!e?[]:lT(e.nodes).filter(tT).slice(0,8).map((e,t)=>({id:e.id,nodeId:e.stableKey??e.entryId??e.type,label:e.title||e.type,kind:e.type,status:nT(e.status),attempt:t+1,source:`session trace fact`,...e.startedAt?{startedAt:e.startedAt}:{},...e.completedAt?{completedAt:e.completedAt}:{}}))}function tT(e){return e.type===`agent.turn`||e.type===`tool.call`||e.type===`execution.command`||e.type===`agent.delegation`||e.type===`agent.async`||e.type===`yielded.run`||e.type===`error`}function nT(e){return e===`done`?`completed`:e===`error`?`failed`:`running`}function rT(e,t){if(!t||!e)return[];let n=[];for(let r of e.rawEvents){if(!_T(r.payload))continue;let e=gT(r.payload.type),i=gT(r.payload.runId);if(e!==`edge.transferred`||i&&i!==t)continue;let a=gT(r.payload.edgeId);a&&n.push({id:gT(r.payload.edgeTransferId)??r.id,edgeId:a,status:`transferred`,source:r.type,createdAt:r.createdAt})}return n.slice(0,8)}function iT(e,t){let n=[];for(let e of t?.errors??[])n.push({id:`signal:${n.length}`,message:e.message,...e.code?{code:e.code}:{},source:e.source??`session signal`});if(e){for(let t of lT(e.nodes)){let e=t.error??(t.status===`error`?dT(t.output)??dT(t.summary):void 0);e&&n.push({id:`node:${t.id}`,message:e,source:t.type})}for(let t of e.rawEvents){if(!_T(t.payload))continue;let e=t.payload.error,r=_T(e)?gT(e.message):gT(e),i=_T(e)?gT(e.code):void 0;r&&n.push({id:`event:${t.id}`,message:r,...i?{code:i}:{},source:t.type})}}return aT(n).slice(0,8)}function aT(e){let t=new Set;return e.filter(e=>{let n=`${e.code??``}:${e.message}:${e.source??``}`;return t.has(n)?!1:(t.add(n),!0)})}function oT(e,t){if(t!==`completed`||!e)return;let n=lT(e.nodes),r=[...n].reverse().find(e=>e.type===`assistant.message`&&e.status===`done`&&(e.output!==void 0||e.summary));if(r)return{value:r.output??r.summary??``,source:`assistant.message`};let i=[...n].reverse().find(e=>e.status===`done`&&e.type!==`user.message`&&e.type!==`model.reasoning`&&e.output!==void 0);return i?{value:i.output,source:i.type}:void 0}function sT(e,t){let n=[];for(let r of t)if(r.piboSessionId===e.piboSessionId&&!(r.type!==`project.workflow_start.blocked`&&r.validation?.trigger!==`before_workflow_start`))for(let e of r.diagnostics)e.severity===`error`&&n.push({id:`lifecycle:${r.id}:${n.length}`,message:e.message,code:e.code,path:e.path,source:`start lifecycle event`});return pT(n).slice(0,8)}function cT(e){if(!e)return[];let t=[];for(let n of lT(e.nodes)){let e=n.error??dT(n.output)??dT(n.summary);e&&(!fT([n.title,n.summary,n.error,n.type].filter(e=>typeof e==`string`).join(` `))&&!fT(e)||t.push({id:`node:${n.id}`,message:e,...n.type?{source:n.type}:{}}))}for(let n of e.rawEvents)uT(n.payload,`event:${n.id}`,t);return pT(t).slice(0,8)}function lT(e){let t=[],n=e=>{for(let r of e)t.push(r),n(r.children)};return n(e),t}function uT(e,t,n,r=0){if(r>4||!_T(e))return;let i=Array.isArray(e.diagnostics)?e.diagnostics:void 0;if(i)for(let e of i){if(!_T(e))continue;let r=gT(e.message)??dT(e);r&&n.push({id:`${t}:diagnostic:${n.length}`,message:r,...gT(e.code)?{code:gT(e.code)}:{},...gT(e.path)?{path:gT(e.path)}:{},source:`workflow.diagnostic`})}let a=e.error;if(_T(a)){let e=gT(a.code),r=gT(a.message)??dT(a);r&&fT([e,r].filter(Boolean).join(` `))&&n.push({id:`${t}:error:${n.length}`,message:r,...e?{code:e}:{},source:`workflow.error`})}else typeof a==`string`&&fT(a)&&n.push({id:`${t}:error:${n.length}`,message:a,source:`workflow.error`});for(let[i,a]of Object.entries(e))i===`diagnostics`||i===`error`||i!==`payload`&&i!==`output`&&i!==`result`&&i!==`data`||uT(a,`${t}:${i}`,n,r+1)}function dT(e){if(typeof e==`string`)return e;if(_T(e))return gT(e.message)??gT(e.error)??gT(e.summary)}function fT(e){let t=e.toLowerCase();return t.includes(`validation`)||t.includes(`validate`)||t.includes(`diagnostic`)||t.includes(`workflowinterfaceerror`)||t.includes(`workflowruntimeerror.validation`)}function pT(e){let t=new Set;return e.filter(e=>{let n=`${e.code??``}:${e.path??``}:${e.message}`;return t.has(n)?!1:(t.add(n),!0)})}function mT(e){return _T(e)&&_T(e.data)&&Array.isArray(e.data.diagnostics)?e.data.diagnostics.filter(_T).map(t=>({code:gT(t.code)??`WorkflowRuntimeError.humanActionRejected`,message:gT(t.message)??hT(e),severity:t.severity===`info`||t.severity===`warning`||t.severity===`error`?t.severity:`error`,...gT(t.path)?{path:gT(t.path)}:{},...gT(t.registryRef)?{registryRef:gT(t.registryRef)}:{},...gT(t.hint)?{hint:gT(t.hint)}:{}})):[{code:`WorkflowRuntimeError.humanActionRejected`,message:hT(e),severity:`error`}]}function hT(e){return e instanceof Error?e.message:String(e)}function gT(e){return typeof e==`string`&&e.trim()?e:void 0}function _T(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function vT(e){return!!e.workflowRunId||e.state===`workflow`||e.workflowId!==`simple-chat`}function yT(e,t){return e.archived?`archived`:e.state&&e.state!==`workflow`?e.state.replace(/_/g,` `):t===`running`?`running`:t===`error`?`failed`:e.workflowRunId?`workflow`:e.kind}function bT(e,t){let n=yT(e,t).toLowerCase();return e.archived?`cancelled`:n.includes(`complete`)||n.includes(`done`)?`completed`:n.includes(`fail`)||n.includes(`error`)?`failed`:n.includes(`cancel`)?`cancelled`:n.includes(`wait`)||n.includes(`blocked`)?`waiting`:!e.workflowRunId&&n.includes(`configured`)?`idle`:`active`}function xT(e){return e===`completed`?`workflow.completed`:e===`failed`?`workflow.failed`:e===`cancelled`?`workflow.cancelled`:`node.session`}function ST(e){return e===`failed`?`workflow.failed`:e===`cancelled`?`workflow.cancelled`:`workflow.completed`}function CT(e){return e===`failed`?`failed`:e===`cancelled`?`cancelled`:`completed`}function wT(e){return e===`failed`?`WORKFLOW.FAIL`:e===`cancelled`?`WORKFLOW.CANCEL`:`WORKFLOW.NODE.DONE`}function TT({status:e}){return e===`completed`?(0,M.jsx)(ze,{size:16,className:`text-emerald-300`}):e===`failed`?(0,M.jsx)(Ve,{size:16,className:`text-red-300`}):e===`cancelled`?(0,M.jsx)(gt,{size:16,className:`text-slate-400`}):e===`waiting`?(0,M.jsx)(Ue,{size:16,className:`text-amber-300`}):e===`active`?(0,M.jsx)(Se,{size:16,className:`text-[#11a4d4]`}):(0,M.jsx)(He,{size:16,className:`text-slate-500`})}function ET({tone:e,children:t}){return(0,M.jsx)(`span`,{className:`rounded border px-2 py-1 font-mono ${{blue:`border-[#11a4d4]/40 bg-[#11a4d4]/10 text-[#11a4d4]`,slate:`border-slate-700 bg-slate-900/50 text-slate-300`,green:`border-emerald-500/40 bg-emerald-500/10 text-emerald-300`,amber:`border-amber-500/40 bg-amber-500/10 text-amber-300`,red:`border-red-500/40 bg-red-500/10 text-red-300`}[e]}`,children:t})}function DT(e){return e===`completed`?`green`:e===`failed`||e===`cancelled`?`red`:e===`waiting`?`amber`:`blue`}function OT(e){return e===`completed`?`border-emerald-500/40 bg-emerald-500/10`:e===`failed`?`border-red-500/40 bg-red-500/10`:e===`cancelled`?`border-slate-600 bg-slate-800/40`:e===`waiting`?`border-amber-500/40 bg-amber-500/10`:e===`active`?`border-[#11a4d4]/50 bg-[#11a4d4]/10 shadow-[0_0_0_1px_rgba(17,164,212,0.18)]`:`border-slate-800 bg-[#111820]`}function kT(e){return e===`completed`?`border-emerald-500/40 bg-emerald-500/10 text-emerald-300`:e===`failed`||e===`cancelled`?`border-red-500/40 bg-red-500/10 text-red-300`:e===`waiting`?`border-amber-500/40 bg-amber-500/10 text-amber-300`:e===`active`?`border-[#11a4d4]/40 bg-[#11a4d4]/10 text-[#11a4d4]`:`border-slate-700 bg-slate-900/50 text-slate-400`}function AT(e){let t=e.toLowerCase();return t.includes(`complete`)||t.includes(`done`)||t.includes(`transferred`)?`border-emerald-500/40 bg-emerald-500/10 text-emerald-300`:t.includes(`fail`)||t.includes(`error`)||t.includes(`cancel`)?`border-red-500/40 bg-red-500/10 text-red-300`:t.includes(`wait`)||t.includes(`blocked`)?`border-amber-500/40 bg-amber-500/10 text-amber-300`:t.includes(`run`)||t.includes(`active`)||t.includes(`workflow`)?`border-[#11a4d4]/40 bg-[#11a4d4]/10 text-[#11a4d4]`:`border-slate-700 bg-slate-900/50 text-slate-400`}function jT(e){return e.length>18?`${e.slice(0,10)}…${e.slice(-6)}`:e}var MT=[{id:`terminal`,label:`Terminal`,description:`Compact Codex-style terminal transcript.`,render:e=>(0,M.jsx)(JC,{...e})},{id:`workflow`,label:`Workflow`,description:`Workflow/XState visualization for workflow-backed project sessions.`,render:e=>(0,M.jsx)(ww,{...e})}],NT=new Map(MT.map(e=>[e.id,e]));function PT(){return MT}function FT(e){return NT.get(e)??NT.get(`terminal`)}var IT=`pibo.chat.composerHistory`,LT=100;function RT(){try{let e=localStorage.getItem(IT);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`&&e.trim().length>0).slice(-LT):[]}catch{return[]}}function zT(e){let t=e.trim();if(!t)return;let n=RT();if(n.at(-1)!==t)try{localStorage.setItem(IT,JSON.stringify([...n,t].slice(-LT)))}catch{}}function BT(e){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);let t=document.createElement(`textarea`);t.value=e,t.style.position=`fixed`,t.style.opacity=`0`,document.body.appendChild(t),t.select();try{return document.execCommand(`copy`),Promise.resolve()}finally{document.body.removeChild(t)}}function VT(e,t){return e.length>t?`${e.slice(0,Math.max(0,t-1))}…`:e}function HT({sessionId:e,disabled:t=!1,commands:n,skills:r,value:i,focusSignal:a,selectedWebAnnotations:o,selectedUploadAttachments:s,onValueChange:c,onCommand:l,onDetachWebAnnotation:u,onClearWebAnnotations:d,onAttachUploadedFiles:f,onDetachUploadAttachment:p,onClearUploadAttachments:m,onSend:h}){let g=(0,v.useRef)(null),_=(0,v.useRef)(null),y=(0,v.useRef)(null),b=(0,v.useRef)(null),x=(0,v.useRef)(null),S=(0,v.useRef)(null),C=(0,v.useRef)(null),[w,T]=(0,v.useState)(0),[E,ee]=(0,v.useState)(0),[D,O]=(0,v.useState)(0),[te,ne]=(0,v.useState)([]),[re,ie]=(0,v.useState)(!1),[ae,oe]=(0,v.useState)(null),[k,A]=(0,v.useState)(null),se=(0,v.useMemo)(()=>{for(let e=D-1;e>=0;e--){let t=i[e];if(t===` `||t===`
40
40
  `||t===` `)break;if(t===`$`){if(e>0&&i[e-1]===`\\`)continue;return{query:i.slice(e+1,D).toLowerCase(),startPos:e,endPos:D}}}return null},[i,D]),ce=i.trim().startsWith(`/`)?i.trim().split(/\s+/)[0]:null,le=se?UT(se.startPos,i.slice(se.startPos,D)):null,ue=ce?WT(ce):null,fe=(0,v.useMemo)(()=>se?r.filter(e=>e.name.toLowerCase().startsWith(se.query)):[],[se,r]),pe=(0,v.useMemo)(()=>ce?n.filter(e=>e.slash.startsWith(ce)):[],[ce,n]),me=le&&te.includes(le)?[]:fe,he=ue&&te.includes(ue)?[]:pe,ge=(0,v.useCallback)(e=>{e&&ne(t=>t.includes(e)?t:[...t,e])},[]),_e=(0,v.useCallback)(()=>{let e=[fe.length?le:null,pe.length?ue:null].filter(e=>!!e);e.length&&ne(t=>{let n=new Set(t);for(let t of e)n.add(t);return n.size===t.length?t:[...n]})},[ue,pe.length,fe.length,le]);(0,v.useEffect)(()=>{let e=[le,ue].filter(e=>!!e);ne(t=>t.filter(t=>e.includes(t)))},[ue,le]),(0,v.useEffect)(()=>{!he.length||w<he.length||T(0)},[w,he.length]),(0,v.useEffect)(()=>{!me.length||E<me.length||ee(0)},[E,me.length]),(0,v.useEffect)(()=>{let e=requestAnimationFrame(()=>x.current?.scrollIntoView({block:`nearest`}));return()=>cancelAnimationFrame(e)},[w,he.length]),(0,v.useEffect)(()=>{let e=requestAnimationFrame(()=>S.current?.scrollIntoView({block:`nearest`}));return()=>cancelAnimationFrame(e)},[E,me.length]),(0,v.useEffect)(()=>{C.current=null},[e]),(0,v.useEffect)(()=>{if(!k)return;let e=requestAnimationFrame(()=>b.current?.focus());return()=>{cancelAnimationFrame(e),URL.revokeObjectURL(k.previewUrl)}},[k]),(0,v.useEffect)(()=>{if(a<=0)return;let e=_.current;if(!e)return;let t=e.value.length;e.focus(),e.setSelectionRange(t,t),O(t)},[a]),(0,v.useEffect)(()=>{if(!he.length&&!me.length)return;let e=e=>{let t=e.target;t instanceof Node&&(g.current?.contains(t)||_e())};return document.addEventListener(`pointerdown`,e,!0),()=>document.removeEventListener(`pointerdown`,e,!0)},[_e,he.length,me.length]),(0,v.useLayoutEffect)(()=>{ZT(_.current)},[i]);let ve=e=>{if(!se||!_.current)return;let t=i.slice(0,se.startPos),n=i.slice(se.endPos);c(t+`$`+e+n),ge(UT(se.startPos,`$${e}`));let r=se.startPos+1+e.length;O(r),requestAnimationFrame(()=>{_.current?.setSelectionRange(r,r),O(r)})},ye=e=>{c(e),requestAnimationFrame(()=>{let e=_.current;if(!e)return;let t=e.value.length;e.setSelectionRange(t,t),O(t)})},be=e=>{let t=C.current;if(!t){if(e===`next`||i!==``)return!1;let t=RT();if(!t.length)return!1;let n=e===`previous`?t.length-1:0;return C.current={entries:t,index:n,draft:i},ye(t[n]),!0}if(e===`previous`){let e=Math.max(0,t.index-1);return C.current={...t,index:e},ye(t.entries[e]),!0}let n=t.index+1;return n>=t.entries.length?(C.current=null,ye(t.draft),!0):(C.current={...t,index:n},ye(t.entries[n]),!0)},xe=()=>{t||re||y.current?.click()},j=()=>{A(null)},Se=e=>{if(t||re)return;let n=GT(e.clipboardData);if(!n.length)return;e.preventDefault(),_e(),oe(null);let r=n[0];A(e=>(e&&URL.revokeObjectURL(e.previewUrl),{file:r,previewUrl:URL.createObjectURL(r)}))},Ce=async()=>{if(!k||re)return;let e=k.file;A(null),await we([e])},we=async e=>{if(e.length){ie(!0),oe({message:`Uploading ${e.length} file${e.length===1?``:`s`}...`,error:!1});try{f((await de(e)).files),oe(null)}catch(e){oe({message:e instanceof Error?e.message:String(e),error:!0})}finally{ie(!1)}}},Te=async()=>{if(t)return;let e=i.trim();if(e){if(me.length){ve(me[Math.min(E,me.length-1)].name);return}if(he.length&&!n.some(t=>t.slash===e.split(/\s+/)[0])){let e=he[Math.min(w,he.length-1)].slash;c(e),ge(WT(e));return}if(C.current=null,zT(e),c(``),e.split(/\s+/)[0]===`/upload`){xe();return}e.startsWith(`/`)&&await l(e)||await h(e)}};return(0,M.jsxs)(`div`,{ref:g,"data-pibo-debug":`composer`,"data-pibo-session-id":e??void 0,"data-pibo-state":t?`disabled`:i?`non-empty`:`empty`,className:`relative p-3 bg-[#151f24] border-t border-slate-800 max-[980px]:p-2`,children:[(0,M.jsx)(`input`,{ref:y,type:`file`,multiple:!0,className:`hidden`,onChange:e=>{let t=Array.from(e.target.files??[]);e.target.value=``,we(t)}}),ae?(0,M.jsxs)(`div`,{className:`mb-2 flex items-center gap-2 rounded-sm border px-3 py-2 text-xs ${ae.error?`border-red-900 bg-red-950/40 text-red-200`:ae.copyText?`border-green-900/60 bg-green-950/30 text-green-300`:`border-slate-700 bg-[#0e1116] text-slate-300`}`,children:[(0,M.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:ae.message}),ae.copyText?(0,M.jsx)(`button`,{type:`button`,onClick:()=>void BT(ae.copyText),title:`Copy uploaded file path`,"aria-label":`Copy uploaded file path`,className:`shrink-0 rounded-sm p-0.5 text-slate-400 hover:bg-slate-800 hover:text-[#11a4d4]`,children:(0,M.jsx)(We,{size:13})}):null,(0,M.jsx)(`button`,{type:`button`,onClick:()=>oe(null),title:`Hide upload status`,"aria-label":`Hide upload status`,className:`shrink-0 rounded-sm p-0.5 text-slate-500 hover:bg-slate-800 hover:text-slate-200`,children:(0,M.jsx)(vt,{size:13})})]}):null,k?(0,M.jsx)(`div`,{className:`fixed inset-0 z-50 grid place-items-center bg-black/60 px-4`,role:`dialog`,"aria-modal":`true`,"aria-label":`Upload pasted image`,onKeyDown:e=>{e.key===`Escape`&&j()},children:(0,M.jsxs)(`div`,{className:`w-full max-w-md rounded-sm border border-slate-700 bg-[#151f24] shadow-2xl`,children:[(0,M.jsxs)(`div`,{className:`flex items-start justify-between gap-3 border-b border-slate-800 px-4 py-3`,children:[(0,M.jsxs)(`div`,{children:[(0,M.jsx)(`div`,{className:`text-sm font-semibold text-slate-100`,children:`Pasted image detected`}),(0,M.jsx)(`div`,{className:`mt-1 text-xs text-slate-400`,children:`Upload this clipboard image to ~/.pibo/uploads?`})]}),(0,M.jsx)(`button`,{type:`button`,onClick:j,className:`rounded-sm p-1 text-slate-500 hover:bg-slate-800 hover:text-slate-200`,"aria-label":`Cancel pasted image upload`,children:(0,M.jsx)(vt,{size:14})})]}),(0,M.jsxs)(`div`,{className:`space-y-3 px-4 py-4`,children:[(0,M.jsx)(`img`,{src:k.previewUrl,alt:`Pasted clipboard image preview`,className:`max-h-64 w-full rounded-sm border border-slate-800 bg-[#0e1116] object-contain`}),(0,M.jsxs)(`div`,{className:`flex items-center justify-between gap-3 text-xs text-slate-400`,children:[(0,M.jsx)(`span`,{className:`min-w-0 truncate font-mono`,children:k.file.name}),(0,M.jsx)(`span`,{className:`shrink-0 font-mono`,children:XT(k.file.size)})]})]}),(0,M.jsxs)(`div`,{className:`flex justify-end gap-2 border-t border-slate-800 px-4 py-3`,children:[(0,M.jsx)(`button`,{type:`button`,onClick:j,className:`h-8 rounded-sm border border-slate-700 px-3 text-xs text-slate-300 hover:border-slate-500 hover:text-slate-100`,children:`Cancel`}),(0,M.jsx)(`button`,{ref:b,type:`button`,onClick:()=>void Ce(),disabled:re,className:`h-8 rounded-sm bg-[#11a4d4] px-3 text-xs font-medium text-white disabled:opacity-50`,children:`Upload image`})]})]})}):null,me.length?(0,M.jsx)(`div`,{className:`absolute left-3 bottom-full mb-2 w-[min(520px,calc(100%-24px))] max-h-72 overflow-auto bg-[#0e1116] border border-emerald-500 rounded-sm shadow-xl`,children:me.map((e,t)=>(0,M.jsxs)(`button`,{ref:t===E?S:null,type:`button`,onClick:()=>ve(e.name),className:`w-full grid grid-cols-[120px_1fr] gap-2 px-3 py-2 text-left border-b border-slate-800 ${t===E?`bg-emerald-500/15`:``}`,children:[(0,M.jsxs)(`span`,{className:`font-mono text-emerald-400`,children:[`$`,e.name]}),(0,M.jsx)(`span`,{className:`text-xs text-slate-400`,children:e.description??e.path??``})]},e.name))}):null,s.length?(0,M.jsxs)(`div`,{className:`mb-2 rounded-sm border border-slate-800 bg-[#0e1116] px-2.5 py-1.5`,"data-pibo-debug":`composer-upload-attachments`,"data-upload-attachment-count":s.length,children:[(0,M.jsxs)(`div`,{className:`mb-1.5 flex items-center justify-between gap-2`,children:[(0,M.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Attached uploads`}),(0,M.jsx)(`button`,{type:`button`,onClick:m,className:`text-[11px] text-slate-500 hover:text-[#11a4d4]`,children:`Clear`})]}),(0,M.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:s.map(e=>(0,M.jsxs)(`div`,{title:e.path,className:`inline-flex max-w-80 items-center gap-1 rounded-sm border border-emerald-500/45 bg-emerald-500/10 px-2 py-1 text-left text-[11px] text-slate-200`,"data-pibo-debug":`composer-upload-attachment-chip`,"data-upload-path":e.path,children:[(0,M.jsx)(`span`,{className:`min-w-0 truncate`,children:VT(e.name||e.path,100)}),(0,M.jsx)(`button`,{type:`button`,onClick:()=>void BT(e.path),title:`Copy uploaded file path`,"aria-label":`Copy uploaded file path`,className:`shrink-0 rounded-sm p-0.5 text-emerald-300 hover:bg-slate-800 hover:text-[#11a4d4]`,children:(0,M.jsx)(We,{size:11})}),(0,M.jsx)(`button`,{type:`button`,onClick:()=>p(e.id),title:`Detach ${e.name||e.path}`,"aria-label":`Detach ${e.name||e.path}`,className:`shrink-0 rounded-sm p-0.5 text-emerald-300 hover:bg-slate-800 hover:text-slate-100`,children:(0,M.jsx)(vt,{size:11})})]},e.id))})]}):null,o.length?(0,M.jsxs)(`div`,{className:`mb-2 rounded-sm border border-slate-800 bg-[#0e1116] px-3 py-2`,"data-pibo-debug":`composer-web-annotations`,"data-web-annotation-count":o.length,children:[(0,M.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,M.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Attached web annotations`}),(0,M.jsx)(`button`,{type:`button`,onClick:d,className:`text-[11px] text-slate-500 hover:text-[#11a4d4]`,children:`Clear`})]}),(0,M.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:o.map(e=>(0,M.jsxs)(`button`,{type:`button`,onClick:()=>u(e.id),title:`Detach ${e.id}`,className:`inline-flex max-w-72 items-center gap-1 rounded-sm border border-[#11a4d4]/50 bg-[#11a4d4]/10 px-2 py-1 text-left text-[11px] text-slate-200`,"data-pibo-debug":`composer-web-annotation-chip`,"data-web-annotation-id":e.id,children:[(0,M.jsx)(`span`,{className:`min-w-0 truncate`,children:VT(e.primaryTarget||e.label||e.note||e.id,100)}),(0,M.jsx)(vt,{size:11,className:`shrink-0 text-[#11a4d4]`})]},e.id))})]}):null,he.length?(0,M.jsx)(`div`,{className:`absolute left-3 bottom-full mb-2 w-[min(520px,calc(100%-24px))] max-h-72 overflow-auto bg-[#0e1116] border border-[#11a4d4] rounded-sm shadow-xl`,children:he.map((e,t)=>(0,M.jsxs)(`button`,{ref:t===w?x:null,type:`button`,onClick:()=>{c(e.slash),ge(WT(e.slash)),T(t)},className:`w-full grid grid-cols-[120px_1fr] gap-2 px-3 py-2 text-left border-b border-slate-800 ${t===w?`bg-[#11a4d4]/15`:``}`,children:[(0,M.jsx)(`span`,{className:`font-mono text-[#11a4d4]`,children:e.slash}),(0,M.jsx)(`span`,{className:`text-xs text-slate-400`,children:e.description})]},e.slash))}):null,(0,M.jsxs)(`div`,{className:`grid grid-cols-[1fr_auto] items-end gap-2`,children:[(0,M.jsx)(`textarea`,{ref:_,"data-pibo-debug":`composer-input`,"data-pibo-session-id":e??void 0,"data-pibo-state":t?`disabled`:i?`non-empty`:`empty`,rows:1,value:i,disabled:t,onChange:e=>{C.current=null,c(e.target.value),O(e.target.selectionStart)},onKeyDown:e=>{if(e.key===`Escape`&&(me.length||he.length)){e.preventDefault(),e.stopPropagation(),_e();return}if(me.length&&(e.key===`ArrowDown`||e.key===`ArrowUp`)){e.preventDefault(),ee(t=>e.key===`ArrowDown`?(t+1)%me.length:(t-1+me.length)%me.length);return}if(he.length&&(e.key===`ArrowDown`||e.key===`ArrowUp`)){e.preventDefault(),T(t=>e.key===`ArrowDown`?(t+1)%he.length:(t-1+he.length)%he.length);return}if((e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&be(e.key===`ArrowUp`?`previous`:`next`)){e.preventDefault();return}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),Te())},onPaste:Se,placeholder:t?`Select a session to message`:`Send Message (/ for commands or $ for skills)`,className:`h-10 min-h-10 resize-none overflow-hidden bg-[#0e1116] border border-slate-700 rounded-sm px-3 py-2 text-sm leading-5 outline-none focus:border-[#11a4d4] disabled:opacity-50 [scrollbar-gutter:stable]`}),(0,M.jsx)(`button`,{type:`button`,disabled:t||re,onClick:()=>void Te(),title:`Send message`,"aria-label":`Send message`,className:`h-10 w-10 self-end inline-flex items-center justify-center bg-[#11a4d4] rounded-sm text-white disabled:opacity-50`,children:(0,M.jsx)(mt,{size:16})})]})]})}function UT(e,t){return`skill:${e}:${t}`}function WT(e){return`command:${e}`}function GT(e){let t=Array.from(e.items).filter(e=>e.kind===`file`&&e.type.startsWith(`image/`)).map(e=>e.getAsFile()).filter(e=>!!e);return(t.length?t:Array.from(e.files).filter(e=>e.type.startsWith(`image/`))).map(KT)}function KT(e){return e.name&&e.name!==`image.png`?e:new File([e],qT(e.type),{type:e.type||`image/png`,lastModified:Date.now()})}function qT(e){let t=JT(e),n=new Date;return`screenshot-${[n.getFullYear(),YT(n.getMonth()+1),YT(n.getDate()),`-`,YT(n.getHours()),YT(n.getMinutes()),YT(n.getSeconds())].join(``)}${t}`}function JT(e){switch(e){case`image/jpeg`:return`.jpg`;case`image/gif`:return`.gif`;case`image/webp`:return`.webp`;case`image/svg+xml`:return`.svg`;default:return`.png`}}function YT(e){return String(e).padStart(2,`0`)}function XT(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KiB`:`${(e/(1024*1024)).toFixed(1)} MiB`}function ZT(e){if(!e)return;if(!e.value.includes(`
41
- `)&&e.value.length<80){e.style.height=``,e.style.overflowY=`hidden`;return}let t=window.getComputedStyle(e),n=QT(t.lineHeight,20),r=QT(t.borderTopWidth)+QT(t.borderBottomWidth),i=n*5+QT(t.paddingTop)+QT(t.paddingBottom);e.style.height=`auto`;let a=e.scrollHeight,o=a>i;e.style.height=`${Math.min(a,i)+r}px`,e.style.overflowY=o?`auto`:`hidden`,o&&e.selectionStart===e.value.length&&e.selectionEnd===e.value.length&&(e.scrollTop=a)}function QT(e,t=0){let n=Number.parseFloat(e);return Number.isFinite(n)?n:t}var $T=`pibo.chat.webAnnotations.cdpUrl`,eE=`pibo.chat.webAnnotations.selected.`,tE=`pibo.chat.webAnnotations.overlay.`,nE=`pibo.chat.webAnnotations.panelCollapsed`,rE=`pibo.chat.shortcuts.webAnnotationsToggle`,iE=`Alt+Shift+A`;function aE(){try{return localStorage.getItem($T)??``}catch{return``}}function oE(e){try{e.trim()?localStorage.setItem($T,e.trim()):localStorage.removeItem($T)}catch{}}function sE(){try{return localStorage.getItem(rE)||`Alt+Shift+A`}catch{return iE}}function cE(e){try{return uE(localStorage.getItem(lE(e)))}catch{return null}}function lE(e){return tE+e}function uE(e){if(!e)return null;try{return dE(JSON.parse(e))}catch{return null}}function dE(e){if(!e||typeof e!=`object`)return null;let t=e,n=typeof t.piboSessionId==`string`?t.piboSessionId.trim():``;return n?{bindingId:typeof t.bindingId==`string`?t.bindingId:void 0,piboSessionId:n,installed:t.installed!==!1,active:t.active===!0,toolbarExpanded:t.toolbarExpanded===!0,mode:typeof t.mode==`string`?t.mode:void 0,reason:typeof t.reason==`string`?t.reason:void 0,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:void 0}:null}function fE(e){try{let t=localStorage.getItem(eE+e);if(!t)return[];let n=JSON.parse(t);return Array.isArray(n)?n.filter(e=>typeof e==`string`&&!!e.trim()).slice(0,5):[]}catch{return[]}}function pE(e,t){try{let n=eE+e,r=[...new Set(t.filter(e=>e.trim()))].slice(0,5);r.length?localStorage.setItem(n,JSON.stringify(r)):localStorage.removeItem(n)}catch{}}function mE(){try{return localStorage.getItem(nE)===`true`}catch{return!1}}function hE(e){try{localStorage.setItem(nE,String(e))}catch{}}function gE({piboSessionId:e,annotations:t,selectedIds:n,loading:r,error:i,collapsed:a,onRefresh:o,onToggle:s,onClear:c,onCollapse:l,onClose:u}){return e?(0,M.jsxs)(`section`,{className:`border-t border-slate-800 bg-[#101d22] px-3 py-2 sm:px-4`,"data-pibo-debug":`web-annotations-session-panel`,"data-pibo-session-id":e,children:[(0,M.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,M.jsxs)(`div`,{className:`min-w-0`,children:[(0,M.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,M.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Web annotations`}),(0,M.jsx)(`span`,{className:`rounded-sm border border-slate-700 px-1.5 py-0.5 text-[10px] text-slate-400`,children:t.length}),n.length?(0,M.jsxs)(`span`,{className:`rounded-sm border border-[#11a4d4]/50 px-1.5 py-0.5 text-[10px] text-[#11a4d4]`,children:[n.length,` attached`]}):null]}),a?null:(0,M.jsx)(`div`,{className:`text-[11px] text-slate-500`,children:`Global annotation list. Selected attachments are remembered per session.`})]}),(0,M.jsxs)(`div`,{className:`ml-auto flex shrink-0 items-center gap-1`,children:[(0,M.jsx)(`button`,{type:`button`,onClick:o,disabled:r,title:`Refresh annotations`,"aria-label":`Refresh annotations`,className:`inline-flex h-8 w-8 items-center justify-center rounded-sm border border-slate-700 text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:opacity-50 sm:h-7 sm:w-7`,"data-pibo-debug":`web-annotations-refresh`,children:(0,M.jsx)(ut,{size:12,className:r?`animate-spin`:void 0})}),(0,M.jsx)(`button`,{type:`button`,onClick:c,disabled:r||!t.length,title:`Clear visible annotations`,"aria-label":`Clear visible annotations`,className:`inline-flex h-8 w-8 items-center justify-center rounded-sm border border-slate-700 text-slate-300 hover:border-red-500 hover:text-red-300 disabled:opacity-50 sm:h-7 sm:w-7`,children:(0,M.jsx)(ht,{size:12})}),(0,M.jsx)(`button`,{type:`button`,onClick:l,title:a?`Expand annotations panel`:`Collapse annotations panel`,"aria-label":a?`Expand annotations panel`:`Collapse annotations panel`,className:`inline-flex h-8 w-8 items-center justify-center rounded-sm border border-slate-700 text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] sm:h-7 sm:w-7`,children:a?(0,M.jsx)(Le,{size:12}):(0,M.jsx)(Fe,{size:12})}),(0,M.jsx)(`button`,{type:`button`,onClick:u,title:`Hide annotations panel`,"aria-label":`Hide annotations panel`,className:`inline-flex h-8 w-8 items-center justify-center rounded-sm border border-slate-700 text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] sm:h-7 sm:w-7`,children:(0,M.jsx)(vt,{size:12})})]})]}),a?null:i?(0,M.jsx)(`div`,{className:`rounded-sm border border-red-900 bg-red-950/40 px-3 py-2 text-xs text-red-200`,"data-pibo-debug":`web-annotations-error`,children:TE(i,220)}):r&&!t.length?(0,M.jsx)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0e1116] px-3 py-2 text-xs text-slate-400`,"data-pibo-debug":`web-annotations-loading`,children:`Loading annotations…`}):t.length?(0,M.jsx)(`div`,{className:`mt-2 grid max-h-[min(40svh,18rem)] grid-cols-1 gap-2 overflow-y-auto pr-1 sm:max-h-56 sm:grid-cols-[repeat(auto-fill,minmax(16rem,1fr))]`,"data-pibo-debug":`web-annotations-list`,children:t.map(e=>{let t=n.includes(e.id);return(0,M.jsxs)(`div`,{"data-pibo-debug":`web-annotation-chip`,"data-web-annotation-id":e.id,"data-web-annotation-session-id":e.piboSessionId,"data-web-annotation-selected":t?`true`:`false`,className:`min-w-0 rounded-sm border px-3 py-2 text-xs ${t?`border-[#11a4d4] bg-[#11a4d4]/10`:`border-slate-800 bg-[#0e1116]`}`,children:[(0,M.jsxs)(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[(0,M.jsxs)(`span`,{className:`min-w-0 truncate font-mono text-[11px] text-slate-500`,children:[e.status,` · `,e.targetKind]}),(0,M.jsxs)(`button`,{type:`button`,onClick:()=>s(e.id),className:`inline-flex h-8 shrink-0 items-center gap-1 rounded-sm border px-2 text-[11px] sm:h-6 sm:px-1.5 ${t?`border-[#11a4d4] text-[#11a4d4]`:`border-slate-700 text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:[t?(0,M.jsx)(vt,{size:11}):(0,M.jsx)(lt,{size:11}),` `,t?`Detach`:`Attach`]})]}),(0,M.jsx)(`div`,{className:`truncate text-slate-200`,title:e.primaryTarget||e.label||e.selector||e.id,children:TE(e.primaryTarget||e.label||e.selector||e.id,120)}),e.piboContext?(0,M.jsx)(`div`,{className:`truncate font-mono text-[11px] text-[#11a4d4]`,title:e.piboContext,children:TE(e.piboContext,140)}):null,(0,M.jsx)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:e.url,children:wE(e.url)}),(0,M.jsx)(`div`,{className:`mt-1 line-clamp-2 text-slate-400`,title:e.note,children:TE(e.note,180)}),(0,M.jsx)(`div`,{className:`mt-1 text-[11px] text-slate-600`,children:EE(e.createdAt)})]},e.id)})}):(0,M.jsx)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0e1116] px-3 py-2 text-xs text-slate-500`,"data-pibo-debug":`web-annotations-empty`,children:`No open annotations for this session.`})]}):null}function _E({piboSessionId:e,piboRoomId:t,disabled:n,panelVisible:r,onShowPanel:i,onHidePanel:a,onError:o}){let[s,c]=(0,v.useState)(!1),[l,u]=(0,v.useState)(``),[d,f]=(0,v.useState)(()=>aE()),[p,m]=(0,v.useState)([]),[h,g]=(0,v.useState)(`idle`),[_,y]=(0,v.useState)(!1),[b,x]=(0,v.useState)(null);(0,v.useEffect)(()=>{n&&c(!1)},[n]),(0,v.useEffect)(()=>{oE(d)},[d]);let S=async()=>{if(e){g(`loading`),x(null);try{m((await vb(d)).targets.filter(e=>e.type===`page`||e.attachable)),g(`loaded`)}catch(e){let t=SE(e,`CDP unavailable`);m([]),g(`error`),x({kind:`error`,message:t}),o(t)}}},C=async n=>{if(!e)throw Error(`No active session context`);return bb(n.binding.id,yE({piboSessionId:e,piboRoomId:t,cdpUrl:d,annotationShortcut:sE()}))},w=async()=>{if(!(!e||_)){i(),y(!0),x({kind:`info`,message:`Injecting annotation overlay into this Pibo page…`});try{let n=await yb({piboSessionId:e,piboRoomId:t,url:window.location.href,title:document.title,sameOrigin:!0,annotationShortcut:sE()});if(!n.overlay)throw Error(`Overlay config missing from same-origin binding response`);await xE(n.overlay),x({kind:`success`,message:`Annotation overlay is ready on this Pibo page. Open the overlay controls or use the shortcut to start annotating.`}),o(null)}catch(e){let t=SE(e,`Current-page annotation failed`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}}},T=async()=>{if(!e||_)return;i();let n=l.trim();if(!n){x({kind:`error`,message:`URL is required`});return}if(bE(n)){let e=`That looks like a CDP endpoint. Put it in CDP URL, and put the page you want to annotate in Annotate URL.`;x({kind:`error`,message:e}),o(e);return}y(!0),x({kind:`info`,message:`Opening target and injecting overlay…`});try{let r=await yb(yE({piboSessionId:e,piboRoomId:t,url:n,cdpUrl:d})),i=await C(r);x({kind:`success`,message:`Annotation overlay injected for ${CE(i.target??r.target,i.binding.url)}`}),u(``),o(null)}catch(e){let t=SE(e,`Annotation failed`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}},E=async n=>{if(!(!e||_)){i(),y(!0),x({kind:`info`,message:`Binding selected target and injecting overlay…`});try{let r=await C(await yb(yE({piboSessionId:e,piboRoomId:t,targetId:n.id,cdpUrl:d})));x({kind:`success`,message:`Annotation overlay injected for ${CE(r.target??n,r.binding.url)}`}),o(null)}catch(e){let t=SE(e,n.attachable?`Target annotation failed`:`Target not attachable`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}}};return(0,M.jsxs)(`div`,{className:`relative`,"data-pibo-debug":`web-annotations-entry`,"data-pibo-session-id":e??void 0,children:[(0,M.jsx)(vE,{onClick:()=>{n||(c(e=>!e),r||i())},title:n?`Select an active session to annotate a web page`:r?`Web Annotations`:`Show Web Annotations`,ariaLabel:`Web Annotations`,active:s||r,children:(0,M.jsx)(De,{size:14})}),s&&!n?(0,M.jsxs)(`div`,{className:`fixed inset-x-2 bottom-3 z-40 max-h-[calc(100svh-1.5rem)] overflow-y-auto rounded-sm border border-slate-700 bg-[#0e1116] p-3 text-sm shadow-xl sm:absolute sm:inset-auto sm:right-0 sm:top-full sm:bottom-auto sm:mt-2 sm:w-[min(420px,calc(100vw-24px))] sm:max-h-[calc(100svh-5rem)]`,role:`dialog`,"aria-label":`Web Annotations`,children:[(0,M.jsxs)(`div`,{className:`mb-2 flex items-start justify-between gap-3`,children:[(0,M.jsxs)(`div`,{children:[(0,M.jsx)(`div`,{className:`text-xs font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Web Annotations`}),(0,M.jsx)(`div`,{className:`mt-1 text-xs text-slate-500`,children:`Start an inactive overlay for this Pibo page, or bind a CDP target for external pages.`})]}),(0,M.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,M.jsx)(`button`,{type:`button`,onClick:r?a:i,className:`rounded-sm p-1 text-slate-500 hover:bg-slate-800 hover:text-slate-200`,"aria-label":r?`Hide annotation list`:`Show annotation list`,title:r?`Hide annotation list`:`Show annotation list`,children:(0,M.jsx)(ft,{size:14})}),(0,M.jsx)(`button`,{type:`button`,onClick:()=>c(!1),className:`rounded-sm p-1 text-slate-500 hover:bg-slate-800 hover:text-slate-200`,"aria-label":`Close Web Annotations panel`,children:(0,M.jsx)(vt,{size:14})})]})]}),(0,M.jsx)(`button`,{type:`button`,onClick:()=>void w(),disabled:_,className:`mb-3 h-10 w-full rounded-sm bg-emerald-600 px-3 text-xs font-medium text-white hover:bg-emerald-500 disabled:opacity-50 sm:h-9`,"data-pibo-debug":`web-annotations-current-page`,children:`Annotate this Pibo page`}),(0,M.jsx)(`label`,{className:`mb-2 block text-[11px] font-bold uppercase tracking-wider text-slate-500`,htmlFor:`web-annotation-url`,children:`Annotate URL via CDP`}),(0,M.jsxs)(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-[1fr_auto]`,children:[(0,M.jsx)(`input`,{id:`web-annotation-url`,value:l,onChange:e=>u(e.target.value),onKeyDown:e=>{e.key===`Enter`&&T()},placeholder:`http://localhost:5173`,disabled:_,className:`h-10 min-w-0 rounded-sm border border-slate-700 bg-[#151f24] px-2 text-base text-slate-100 outline-none focus:border-[#11a4d4] disabled:opacity-60 sm:h-9 sm:text-xs`}),(0,M.jsx)(`button`,{type:`button`,onClick:()=>void T(),disabled:_||!l.trim(),className:`h-10 rounded-sm bg-[#11a4d4] px-3 text-xs font-medium text-white disabled:opacity-50 sm:h-9`,children:`Annotate`})]}),(0,M.jsx)(`label`,{className:`mt-3 mb-1 block text-[11px] font-bold uppercase tracking-wider text-slate-500`,htmlFor:`web-annotation-cdp-url`,children:`CDP URL (optional)`}),(0,M.jsx)(`input`,{id:`web-annotation-cdp-url`,value:d,onChange:e=>f(e.target.value),placeholder:`Use gateway default`,disabled:_,className:`h-10 w-full rounded-sm border border-slate-800 bg-[#151f24] px-2 font-mono text-base text-slate-300 outline-none focus:border-[#11a4d4] disabled:opacity-60 sm:h-8 sm:text-[11px]`}),(0,M.jsxs)(`div`,{className:`mt-3 flex items-center justify-between gap-2`,children:[(0,M.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-slate-500`,children:`Existing targets`}),(0,M.jsxs)(`button`,{type:`button`,onClick:()=>void S(),disabled:_||h===`loading`,className:`inline-flex h-7 items-center gap-1 rounded-sm border border-slate-700 px-2 text-[11px] text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:opacity-50`,children:[(0,M.jsx)(ut,{size:12,className:h===`loading`?`animate-spin`:void 0}),` Refresh`]})]}),(0,M.jsxs)(`div`,{className:`mt-2 max-h-[min(34svh,14rem)] overflow-auto rounded-sm border border-slate-800 sm:max-h-56`,children:[h===`idle`?(0,M.jsx)(`div`,{className:`px-3 py-3 text-xs text-slate-500`,children:`Refresh to list reachable browser targets.`}):null,h===`loading`?(0,M.jsx)(`div`,{className:`px-3 py-3 text-xs text-slate-400`,children:`Loading targets…`}):null,h===`loaded`&&!p.length?(0,M.jsx)(`div`,{className:`px-3 py-3 text-xs text-slate-500`,children:`No attachable browser targets found.`}):null,p.map(e=>(0,M.jsxs)(`div`,{className:`grid grid-cols-1 gap-2 border-b border-slate-800 px-3 py-2 last:border-b-0 sm:grid-cols-[1fr_auto]`,children:[(0,M.jsxs)(`div`,{className:`min-w-0`,children:[(0,M.jsx)(`div`,{className:`truncate text-xs text-slate-200`,title:e.title||e.url,children:TE(e.title||`Untitled target`,120)}),(0,M.jsx)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:e.url,children:TE(e.url||e.id,160)})]}),(0,M.jsx)(`button`,{type:`button`,onClick:()=>void E(e),disabled:_||!e.attachable,title:e.attachable?`Attach selected target`:`Target is not attachable`,className:`h-9 rounded-sm border border-slate-700 px-2 text-[11px] text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:opacity-40 sm:h-8`,children:`Attach`})]},e.id))]}),b?(0,M.jsx)(`div`,{className:`mt-2 rounded-sm border px-2 py-2 text-xs ${b.kind===`error`?`border-red-900 bg-red-950/40 text-red-200`:b.kind===`success`?`border-emerald-900/60 bg-emerald-950/30 text-emerald-300`:`border-slate-700 bg-[#151f24] text-slate-300`}`,children:b.message}):null]}):null]})}function vE({title:e,ariaLabel:t,active:n,onClick:r,children:i}){return(0,M.jsx)(`button`,{type:`button`,onClick:r,title:e,"aria-label":t,className:`h-8 w-8 inline-flex items-center justify-center border rounded-sm transition-colors ${n?`border-[#11a4d4] bg-[#11a4d4]/10 text-[#11a4d4]`:`border-slate-700 text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:i})}function yE(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e&&e.trim()))}function bE(e){try{let t=new URL(e);return t.port===`56663`||t.pathname.startsWith(`/json/`)}catch{return!1}}function xE(e){return new Promise((t,n)=>{let r=window;try{r.__piboWebAnnotations?.remove?.(),r.__piboWebAnnotationConfig=e;let i=document.createElement(`script`);i.src=`/apps/web-annotations/overlay.js?ts=${Date.now()}`,i.async=!0,i.onload=()=>t(),i.onerror=()=>n(Error(`Could not load Web Annotation overlay script`)),document.head.appendChild(i)}catch(e){n(e)}})}function SE(e,t){let n=DE(e);return!n||n===`undefined`?t:/target.*not found|selected cdp target/i.test(n)?`Target not found: ${n}`:/inject|overlay|evaluation/i.test(n)?`Injection failed: ${n}`:/cdp endpoint.*is unreachable|failed to fetch|fetch failed|chrome target discovery|cdp unavailable|econnrefused|connect/i.test(n)?`CDP unavailable: ${n}`:`${t}: ${n}`}function CE(e,t){let n=e?.url||t||e?.title||`target`;return wE(e?.title||n)}function wE(e){try{let t=new URL(e);return`${t.host}${t.pathname===`/`?``:t.pathname}`}catch{return TE(e,80)}}function TE(e,t){return e.length>t?`${e.slice(0,Math.max(0,t-1))}…`:e}function EE(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{dateStyle:`short`,timeStyle:`short`})}function DE(e){return e instanceof Error?e.message:String(e)}function OE(e){return!!e.workflowRunId||e.state===`workflow`||e.workflowId!==`simple-chat`}function kE(e,t){return{workflowId:e.workflowId,state:jE(e,t),...e.workflowRunId?{workflowRunId:e.workflowRunId}:{}}}function AE({summary:e}){return(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(`span`,{className:`text-slate-600`,children:`·`}),(0,M.jsxs)(`span`,{className:`min-w-0 max-w-52 truncate rounded border border-[#11a4d4]/35 bg-[#11a4d4]/10 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-[#11a4d4]`,title:e.workflowId,children:[`workflow `,e.workflowId]}),(0,M.jsxs)(`span`,{className:ME(e.state),children:[`state `,e.state]}),e.workflowRunId?(0,M.jsxs)(`span`,{className:`min-w-0 max-w-40 truncate rounded border border-slate-700 bg-slate-900/40 px-1.5 py-0.5 text-[10px] text-slate-400`,title:e.workflowRunId,children:[`run `,NE(e.workflowRunId)]}):null]})}function jE(e,t){return e.archived?`archived`:e.state&&e.state!==`workflow`?e.state.replace(/_/g,` `):t===`running`?`running`:t===`error`?`failed`:e.state?e.state.replace(/_/g,` `):e.workflowRunId?`workflow`:e.kind}function ME(e,t=!1){let n=e.toLowerCase(),r=`shrink-0 rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide`;return t?`${r} border-slate-700 text-slate-500`:n.includes(`failed`)||n.includes(`error`)?`${r} border-red-500/40 text-red-300 bg-red-500/10`:n.includes(`waiting`)?`${r} border-amber-500/40 text-amber-300 bg-amber-500/10`:n.includes(`complete`)||n.includes(`done`)?`${r} border-emerald-500/40 text-emerald-300 bg-emerald-500/10`:`${r} border-[#11a4d4]/40 text-[#11a4d4] bg-[#11a4d4]/10`}function NE(e){return e.length>18?`${e.slice(0,10)}…${e.slice(-6)}`:e}function PE({title:e,roomLabel:t,headerPiboSessionId:n,piboSessionId:r,piboRoomId:i,webAnnotationsDisabled:a,webAnnotationsPanelRendered:o,workflowHeader:s,sessionViewId:c,sessionViews:l,currentSessionView:u,allowedSessionViewIds:d,showRawEvents:f,showThinking:p,expandThinking:m,onShowWebAnnotationsPanel:h,onHideWebAnnotationsPanel:g,onSelectSessionView:_,onToggleRawEvents:y,onToggleThinking:b,onToggleExpandThinking:x,onError:S}){let[C,w]=(0,v.useState)(null),T=(0,v.useRef)(void 0),E=C===n,ee=(0,v.useMemo)(()=>d?new Set(d):null,[d]);(0,v.useEffect)(()=>()=>{T.current&&window.clearTimeout(T.current)},[]);let D=()=>{n&&(BT(n).catch(()=>void 0),w(n),T.current&&window.clearTimeout(T.current),T.current=window.setTimeout(()=>w(null),900))};return(0,M.jsxs)(`div`,{className:`h-14 px-4 bg-[#151f24] border-b border-slate-800 flex items-center justify-between max-[980px]:h-auto max-[980px]:flex-wrap max-[980px]:py-2 max-[980px]:gap-2`,children:[(0,M.jsxs)(`div`,{className:`min-w-0`,children:[(0,M.jsx)(`h1`,{className:`text-base font-semibold truncate`,children:e}),(0,M.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 font-mono text-[11px] text-slate-500`,children:[(0,M.jsx)(`span`,{className:`truncate`,children:t}),n?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(`span`,{className:`text-slate-600`,children:`·`}),(0,M.jsx)(`button`,{type:`button`,onMouseDown:e=>e.preventDefault(),onClick:()=>void D(),title:E?`Copied Pibo session ID`:`Copy Pibo session ID`,"aria-label":E?`Copied Pibo session ID`:`Copy Pibo session ID`,className:`min-w-0 max-w-48 truncate rounded-sm px-1 font-mono underline-offset-2 transition-colors duration-150 focus:outline-none focus:ring-1 focus:ring-[#11a4d4] ${E?`bg-emerald-500/15 text-emerald-300 ring-1 ring-emerald-400/50`:`text-slate-400 hover:text-[#11a4d4] hover:underline`}`,children:n})]}):null,s?(0,M.jsx)(AE,{summary:s}):null]})]}),(0,M.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,M.jsx)(_E,{piboSessionId:r,piboRoomId:i,disabled:a,panelVisible:o,onShowPanel:h,onHidePanel:g,onError:S}),(0,M.jsx)(`div`,{className:`flex items-center rounded-sm border border-slate-700 bg-[#0e1116] p-0.5`,children:l.map(e=>{let t=!!(ee&&!ee.has(e.id));return(0,M.jsx)(`button`,{type:`button`,onClick:()=>{t||_(e.id)},disabled:t,title:t?`Project session routing uses the ${u.label} view for this session kind.`:e.description??e.label,"aria-label":t?`${e.label} view unavailable for this Project session kind`:`Switch to ${e.label} view`,className:`min-w-20 px-2.5 py-1 text-[11px] font-bold tracking-wide max-[980px]:min-w-0 max-[980px]:px-1.5 disabled:cursor-not-allowed disabled:text-slate-600 ${c===e.id?`bg-[#11a4d4]/10 text-[#11a4d4]`:`text-slate-400 hover:text-[#11a4d4] disabled:hover:text-slate-600`}`,children:e.label},e.id)})}),(0,M.jsx)(FE,{onClick:y,title:f?`Hide Raw Events`:`Show Raw Events`,ariaLabel:f?`Hide Raw Events`:`Show Raw Events`,active:f,children:(0,M.jsx)(Ae,{size:14})}),(0,M.jsx)(FE,{onClick:b,title:p?`Hide Thinking`:`Show Thinking`,ariaLabel:p?`Hide Thinking`:`Show Thinking`,active:p,children:p?(0,M.jsx)(ke,{size:14}):(0,M.jsx)(Je,{size:14})}),p?(0,M.jsx)(FE,{onClick:x,title:m?`Collapse Thinking`:`Expand Thinking`,ariaLabel:m?`Collapse Thinking`:`Expand Thinking`,active:m,children:m?(0,M.jsx)(Fe,{size:14}):(0,M.jsx)(Le,{size:14})}):null]})]})}function FE({title:e,ariaLabel:t,active:n,onClick:r,children:i}){return(0,M.jsx)(`button`,{type:`button`,onClick:r,title:e,"aria-label":t,className:`h-8 w-8 inline-flex items-center justify-center border rounded-sm transition-colors ${n?`border-[#11a4d4] bg-[#11a4d4]/10 text-[#11a4d4]`:`border-slate-700 text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:i})}function IE(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&LE(e,n)){e.count+=1,e.createdAt=n.createdAt,e.payload={...BE(e.payload)?e.payload:{},text:`${RE(e.payload)}${RE(n.payload)}`};continue}t.push({...n,count:1})}return t}function LE(e,t){if(e.type!==t.type||e.type!==`assistant_delta`&&e.type!==`thinking_delta`&&e.type!==`TEXT_MESSAGE_CONTENT`&&e.type!==`REASONING_MESSAGE_CONTENT`)return!1;let n=BE(e.payload)?e.payload:{},r=BE(t.payload)?t.payload:{};return zE(n)===zE(r)}function RE(e){return BE(e)?typeof e.text==`string`?e.text:typeof e.delta==`string`?e.delta:``:``}function zE(e){return e.eventId??e.messageId}function BE(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function VE({traceView:e,eventLimit:t,isFetching:n,visible:r,onLoadOlder:i}){let a=(0,v.useMemo)(()=>r?IE(e?.rawEvents??[]):[],[e?.rawEvents,r]);return r?(0,M.jsxs)(`aside`,{className:`min-h-0 overflow-auto bg-[#0e1116] border-l border-slate-800 max-[980px]:hidden`,children:[(0,M.jsx)(`div`,{className:`h-11 px-3 border-b border-slate-800 flex items-center text-xs font-bold uppercase tracking-wider`,children:`Raw Events`}),(0,M.jsxs)(`div`,{className:`p-3 flex flex-col gap-2`,children:[e&&a.length>=t?(0,M.jsx)(`button`,{type:`button`,onClick:i,disabled:n,className:`mb-1 rounded-sm border border-slate-700 px-2 py-1 text-xs text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:opacity-60`,children:n?`Loading raw events…`:`Load older raw events (${a.length})`}):null,a.slice(-t).reverse().map(e=>(0,M.jsxs)(`div`,{className:`border-l-2 border-[#11a4d4] bg-[#151f24] p-2`,children:[(0,M.jsxs)(`div`,{className:`flex items-center justify-between gap-2 text-[#11a4d4] font-mono text-[11px] mb-1`,children:[(0,M.jsx)(`span`,{children:e.type}),e.count>1?(0,M.jsxs)(`span`,{className:`text-slate-500`,children:[`x`,e.count]}):null]}),(0,M.jsx)(Sc,{value:e.payload,showControls:!1})]},e.id))]})]}):null}function HE({traceView:e,eventLimit:t,isFetching:n,onLoadOlder:r}){if(!e?.hasOlderEvents)return null;let i=Math.min(e.eventLimit??t,e.eventCount??t),a=e.eventCount??`many`;return(0,M.jsx)(`div`,{className:`border-b border-slate-800 bg-[#101d22] px-4 py-2 text-center`,children:(0,M.jsx)(`button`,{type:`button`,onClick:r,disabled:n,className:`rounded-sm border border-slate-700 px-3 py-1 text-xs text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:opacity-60`,children:n?`Loading history…`:`Load older trace history (${i} of ${a} events)`})})}function UE({selectedPiboSessionId:e,selectedRoomId:t,fallbackRoomId:n,sessionViewId:r,loadingTrace:i,traceError:a,showRawEvents:o,currentTraceView:s,traceEventLimit:c,rawEventLimit:l,tracePageFetching:u,onLoadOlderTracePage:d,onLoadMoreRawEvents:f,headerProps:p,projectSessionCreatePanel:m,workflowStartPanel:h,currentSessionView:g,sessionViewProps:_,webAnnotationsPanelRendered:v,webAnnotationsPanelProps:y,composerProps:b}){return(0,M.jsxs)(M.Fragment,{children:[(0,M.jsxs)(`main`,{"data-pibo-debug":`chat-shell`,"data-pibo-session-id":e??void 0,"data-pibo-room-id":t??n??void 0,"data-pibo-view-id":r,"data-pibo-state":i?`loading`:a?`error`:e?`ready`:`empty`,className:`min-h-0 flex flex-col`,children:[(0,M.jsx)(PE,{...p}),m?(0,M.jsx)(`div`,{className:`border-b border-slate-800 bg-[#101d22] px-4 py-3`,children:m}):null,h?(0,M.jsx)(`div`,{className:`border-b border-slate-800 bg-[#101d22] px-4 py-3`,children:h}):null,(0,M.jsx)(HE,{traceView:s,eventLimit:c,isFetching:u,onLoadOlder:()=>d(s?.nextBeforeSequence)}),a&&!s?(0,M.jsx)(`div`,{className:`min-h-0 flex-1 p-4 text-sm text-red-200`,children:a}):g.render(_),v?(0,M.jsx)(gE,{...y}):null,(0,M.jsx)(HT,{...b})]}),(0,M.jsx)(VE,{traceView:s,eventLimit:l,isFetching:u,visible:o,onLoadOlder:f})]})}function WE(e){let t=new Map;if(YE(e.nodes,t),!t.size)return e;let{nodes:n,changed:r}=XE(e.nodes,t);return r?{...e,nodes:n}:e}function GE(e){return e.some(JE)}function KE(e){let t=new Map;return QE(e,e=>{if(e.type!==`user.message`||!e.entryId)return;let n=$E(e),r=t.get(n);r?r.push(e.entryId):t.set(n,[e.entryId])}),t}function qE(e,t){if(!t.size)return;let n=new Map;QE(e,e=>{if(e.type!==`user.message`||e.entryId)return;let r=$E(e),i=t.get(r);if(!i?.length)return;let a=n.get(r)??0,o=i[a];o&&(e.entryId=o,n.set(r,a+1))})}function JE(e){let t=e.payload;return!!(t&&typeof t==`object`&&!Array.isArray(t)&&`type`in t&&t.type===`message_queued`&&`source`in t&&t.source===`user`&&`text`in t&&typeof t.text==`string`)}function YE(e,t){for(let n of e){if(n.type===`user.message`&&!ZE(n)){let e=$E(n);e&&t.set(e,(t.get(e)??0)+1)}YE(n.children,t)}}function XE(e,t){let n=!1,r=[];for(let i of e){if(ZE(i)){let e=$E(i),r=e?t.get(e)??0:0;if(r>0){t.set(e,r-1),n=!0;continue}}let e=XE(i.children,t);n||=e.changed,r.push(e.changed?{...i,children:e.nodes}:i)}return{nodes:n?r:e,changed:n}}function ZE(e){return e.type===`user.message`?e.source===`event-log`&&e.id.startsWith(`event:message_queued:`)?!0:[e.id,e.stableKey,e.eventId].filter(e=>typeof e==`string`).some(e=>e.startsWith(`optimistic:user-message:`)||e.includes(`:optimistic:user-message:`)):!1}function QE(e,t){for(let n of e)t(n),QE(n.children,t)}function $E(e){return typeof e.output==`string`?e.output:typeof e.summary==`string`?e.summary:``}function eD({selectedPiboSessionId:e,reconciledBaseTraceView:t,liveTraceOverlay:n,selectedSessionStatus:r,persistedUserMessageIndexForBaseTrace:i,now:a}){if(!e||t?.piboSessionId!==e)return{traceView:null};let o=n?.piboSessionId===e?n.events:[];if(!o.length)return{traceView:t};let s=a?.(),c=wS(t,o,r??`idle`),l=GE(o);return l&&qE(c.nodes,i),{traceView:l?WE(c):c,liveTraceComputeDurationMs:s!==void 0&&a?a()-s:void 0}}function tD(e,t){for(let n of e)t(n),tD(n.children,t)}function nD(e){return typeof e.output==`string`?e.output:typeof e.summary==`string`?e.summary:``}function rD(e){if(!e)return;let t=0;return tD(e.nodes,e=>{e.type===`assistant.message`&&(t+=nD(e).length)}),t}function iD({selectedPiboSessionId:e,baseTraceView:t,liveTraceOverlay:n,selectedSessionStatus:r}){let i=(0,v.useMemo)(()=>t?WE(t):null,[t]),a=(0,v.useMemo)(()=>i?KE(i.nodes):new Map,[i]),o=(0,v.useMemo)(()=>eD({selectedPiboSessionId:e,reconciledBaseTraceView:i,liveTraceOverlay:n,selectedSessionStatus:r,persistedUserMessageIndexForBaseTrace:a,now:pv()?()=>performance.now():void 0}),[n,e,r,i,a]),s=o.traceView;return(0,v.useEffect)(()=>{!e||!s?.piboSessionId||!pv()||(Sv(s.piboSessionId,{overlayEventCount:n?.piboSessionId===s.piboSessionId?n.events.length:0,traceBaseOutputLength:rD(t),currentOutputLength:rD(s)}),o.liveTraceComputeDurationMs!==void 0&&yv(s.piboSessionId,o.liveTraceComputeDurationMs))},[t,o.liveTraceComputeDurationMs,s,n,e]),(0,v.useEffect)(()=>{let e=()=>{!s?.piboSessionId||!Ny()||Ly(s.piboSessionId,`tab:${document.visibilityState}`,s.nodes,{traceVersion:s.version,latestStreamId:s.latestStreamId,lastRawEventId:s.rawEvents.at(-1)?.id})};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[s]),s}var aD=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},oD=new class extends aD{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},sD={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},cD=new class{#e=sD;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function lD(e){setTimeout(e,0)}var uD=typeof window>`u`||`Deno`in globalThis;function dD(){}function fD(e){return typeof e==`number`&&e>=0&&e!==1/0}function pD(e,t){return Math.max(e+(t||0)-Date.now(),0)}function mD(e,t){return typeof e==`function`?e(t):e}function hD(e,t){return typeof e==`function`?e(t):e}var gD=Object.prototype.hasOwnProperty;function _D(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=yD(e)&&yD(t);if(!r&&!(bD(e)&&bD(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:gD.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=_D(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function vD(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function yD(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function bD(e){if(!xD(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!xD(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function xD(e){return Object.prototype.toString.call(e)===`[object Object]`}function SD(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:_D(e,t)}function CD(e,t){return typeof e==`function`?e(...t):!!e}var wD=(()=>{let e=()=>uD;return{isServer(){return e()},setIsServer(t){e=t}}})();function TD(){let e,t,n=new Promise((n,r)=>{e=n,t=r});n.status=`pending`,n.catch(()=>{});function r(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.resolve=t=>{r({status:`fulfilled`,value:t}),e(t)},n.reject=e=>{r({status:`rejected`,reason:e}),t(e)},n}var ED=lD;function DD(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=ED,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var OD=DD(),kD=new class extends aD{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function AD(e){return(e??`online`)===`online`?kD.isOnline():!0}function jD(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:AD(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}var MD=class extends aD{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=TD(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),PD(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return FD(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return FD(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof hD(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!vD(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&ID(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||hD(this.options.enabled,this.#t)!==hD(t.enabled,this.#t)||mD(this.options.staleTime,this.#t)!==mD(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||hD(this.options.enabled,this.#t)!==hD(t.enabled,this.#t)||i!==this.#p)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return RD(this,n)&&(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),n===`promise`&&(this.trackProp(`data`),!this.options.experimental_prefetchInRender&&this.#o.status===`pending`&&this.#o.reject(Error(`experimental_prefetchInRender feature flag is not enabled`))),Reflect.get(e,n))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(dD)),t}#g(){this.#b();let e=mD(this.options.staleTime,this.#t);if(wD.isServer()||this.#r.isStale||!fD(e))return;let t=pD(this.#r.dataUpdatedAt,e)+1;this.#d=cD.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return(typeof this.options.refetchInterval==`function`?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#x(),this.#p=e,!(wD.isServer()||hD(this.options.enabled,this.#t)===!1||!fD(this.#p)||this.#p===0)&&(this.#f=cD.setInterval(()=>{(this.options.refetchIntervalInBackground||oD.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(cD.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(cD.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&PD(e,t),o=i&&ID(e,n,t,r);(a||o)&&(l={...l,...jD(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#u?.state.data,this.#u):t.placeholderData,e!==void 0&&(m=`success`,d=SD(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h)if(i&&d===a?.data&&t.select===this.#c)d=this.#l;else try{this.#c=t.select,d=t.select(d),d=SD(i?.data,d,t),this.#l=d,this.#s=null}catch(e){this.#s=e}this.#s&&(f=this.#s,d=this.#l,p=Date.now(),m=`error`);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0,x={status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:LD(e,t),refetch:this.refetch,promise:this.#o,isEnabled:hD(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let t=x.data!==void 0,r=x.status===`error`&&!t,i=e=>{r?e.reject(x.error):t&&e.resolve(x.data)},a=()=>{i(this.#o=x.promise=TD())},o=this.#o;switch(o.status){case`pending`:e.queryHash===n.queryHash&&i(o);break;case`fulfilled`:(r||x.data!==o.value)&&a();break;case`rejected`:(!r||x.error!==o.reason)&&a();break}}return x}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#u=this.#t),!vD(t,e)&&(this.#r=t,this.#C({listeners:(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#m.size)return!0;let r=new Set(n??this.#m);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})()}))}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#C(e){OD.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function ND(e,t){return hD(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status===`error`&&hD(t.retryOnMount,e)===!1)}function PD(e,t){return ND(e,t)||e.state.data!==void 0&&FD(e,t,t.refetchOnMount)}function FD(e,t,n){if(hD(t.enabled,e)!==!1&&mD(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&LD(e,t)}return!1}function ID(e,t,n,r){return(e!==t||hD(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&LD(e,n)}function LD(e,t){return hD(t.enabled,e)!==!1&&e.isStaleByTime(mD(t.staleTime,e))}function RD(e,t){return!vD(e.getCurrentResult(),t)}var zD=v.createContext(void 0),BD=e=>{let t=v.useContext(zD);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},VD=v.createContext(!1),HD=()=>v.useContext(VD);VD.Provider;function UD(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var WD=v.createContext(UD()),GD=()=>v.useContext(WD),KD=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?CD(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},qD=e=>{v.useEffect(()=>{e.clearReset()},[e])},JD=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||CD(n,[e.error,r])),YD=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},XD=(e,t)=>e.isLoading&&e.isFetching&&!t,ZD=(e,t)=>e?.suspense&&t.isPending,QD=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function $D(e,t,n){let r=HD(),i=GD(),a=BD(n),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let s=a.getQueryCache().get(o.queryHash);o._optimisticResults=r?`isRestoring`:`optimistic`,YD(o),KD(o,i,s),qD(i);let c=!a.getQueryCache().get(o.queryHash),[l]=v.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&e.subscribed!==!1;if(v.useSyncExternalStore(v.useCallback(e=>{let t=d?l.subscribe(OD.batchCalls(e)):dD;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),v.useEffect(()=>{l.setOptions(o)},[o,l]),ZD(o,u))throw QD(o,l,i);if(JD({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,u),o.experimental_prefetchInRender&&!wD.isServer()&&XD(u,r)&&(c?QD(o,l,i):s?.promise)?.catch(dD).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?u:l.trackResult(u)}function eO(e,t){return $D(e,MD,t)}var tO=1e4,nO=30*6e4,rO=2e3;function iO(e){return[`chat`,`trace-summary`,e]}function aO(e,t={}){let n=t.pageSize??t.eventLimit??2e3;return[`chat`,`trace-page`,e,t.includeRawEvents?`raw`:`compact`,t.rawEventsLimit??80,n,t.beforeSequence===void 0?`tail`:String(t.beforeSequence)]}function oO(e,t){if(!e||e.piboSessionId!==t.piboSessionId)return e;let n=t.latestStreamId,r=cO(t),i=sO(t.nodes),a=e.events.filter(e=>{if(n!==void 0&&e.streamId!==void 0&&e.streamId<=n||JE(e)&&i.has(e.payload.text))return!1;let t=uO(e);return!t||!r.has(t)});return a.length?{...e,events:a}:null}function sO(e){let t=new Set;for(let n of e){if(n.type===`user.message`&&n.source===`transcript`){let e=dO(n);e&&t.add(e)}for(let e of sO(n.children))t.add(e)}return t}function cO(e){let t=new Set;for(let n of e.rawEvents){let e=uO(n);e&&t.add(e)}return lO(e.nodes,t),t}function lO(e,t){for(let n of e){if(n.type===`user.message`){let e=n.id.startsWith(`event:message_queued:`)?n.id.slice(21):void 0;e&&t.add(`${n.piboSessionId}:message_queued:${e}`),n.source===`transcript`&&n.entryId&&t.add(`${n.piboSessionId}:message_queued:${n.entryId}`)}n.eventId&&n.type===`assistant.message`&&(t.add(`${n.piboSessionId}:assistant_delta:${n.eventId}`),t.add(`${n.piboSessionId}:assistant_message:${n.eventId}`)),n.eventId&&n.type===`model.reasoning`&&(t.add(`${n.piboSessionId}:thinking_delta:${n.eventId}`),t.add(`${n.piboSessionId}:thinking_finished:${n.eventId}`)),lO(n.children,t)}}function uO(e){let t=e.payload;if(!t||typeof t!=`object`||Array.isArray(t))return;let n=`eventId`in t&&typeof t.eventId==`string`?t.eventId:e.eventId,r=`piboSessionId`in t&&typeof t.piboSessionId==`string`?t.piboSessionId:e.piboSessionId;if(!(!n||!r))return`${r}:${e.type}:${n}`}function dO(e){return typeof e.output==`string`?e.output:e.output&&typeof e.output==`object`&&`text`in e.output&&typeof e.output.text==`string`?e.output.text:``}function fO(e,t){if(e.piboSessionId!==t.piboSessionId)return e;let n=new Set,r=[...t.nodes,...e.nodes].filter(e=>n.has(e.id)?!1:(n.add(e.id),!0)),i=new Set,a=[...t.rawEvents,...e.rawEvents].filter(e=>{let t=e.id||`${e.eventSequence??``}:${e.type}:${e.createdAt}`;return i.has(t)?!1:(i.add(t),!0)});return{...e,version:e.version,nodes:r,rawEvents:a,firstEventSequence:t.firstEventSequence??e.firstEventSequence,nextBeforeSequence:t.nextBeforeSequence,hasOlderEvents:t.hasOlderEvents,eventLimit:(e.eventLimit??0)+(t.eventLimit??t.pageSize??0)}}function pO({selectedPiboSessionId:e,showRawEvents:t,setLiveTraceOverlay:n}){let r=BD(),[i,a]=(0,v.useState)(rO),[o,s]=(0,v.useState)(80),[c,l]=(0,v.useState)(null),u=(0,v.useMemo)(()=>e?iO(e):null,[e]),d=(0,v.useMemo)(()=>e?aO(e,{includeRawEvents:t,rawEventsLimit:o,pageSize:rO}):null,[o,e,t]),f=eO({queryKey:u??[`chat`,`trace-summary`,`idle`],queryFn:async()=>{if(!e||!u)throw Error(`Session is required`);let t=r.getQueryData(u),n=await fb(e,t?.version);if(n.notModified&&t)return t;if(!n.summary)throw Error(`Trace summary response missing payload.`);return n.summary},enabled:!!e,staleTime:tO,gcTime:nO,refetchOnWindowFocus:!1,retry:1}),p=eO({queryKey:d??[`chat`,`trace-page`,`idle`,`compact`,o,2e3,`tail`],queryFn:async()=>{if(!e||!d)throw Error(`Session is required`);let n=r.getQueryData(d),i=await pb(e,{includeRawEvents:t,rawEventsLimit:o,pageSize:rO,knownVersion:n?.version});if(i.notModified&&n)return n;if(!i.trace)throw Error(`Trace page response missing payload.`);return i.trace},enabled:!!e,staleTime:tO,gcTime:nO,refetchOnWindowFocus:!1,retry:1});(0,v.useEffect)(()=>{a(rO),s(80),l(null),n(null)},[e,n]),(0,v.useEffect)(()=>{let t=p.data;!t||t.piboSessionId!==e||(pv()&&Sv(t.piboSessionId,{overlayEventCount:0,traceBaseOutputLength:rD(t),traceBaseUpdated:!0}),(0,v.startTransition)(()=>{l(t),n(e=>oO(e,t))}))},[e,n,p.data]);let m=(0,v.useCallback)(async n=>{if(!e||!n)return;let i=aO(e,{includeRawEvents:t,rawEventsLimit:o,pageSize:rO,beforeSequence:n}),s=await r.fetchQuery({queryKey:i,queryFn:async()=>{let a=r.getQueryData(i),s=await pb(e,{includeRawEvents:t,rawEventsLimit:o,pageSize:rO,beforeSequence:n,knownVersion:a?.version});if(s.notModified&&a)return a;if(!s.trace)throw Error(`Trace page response missing payload.`);return s.trace},staleTime:tO,gcTime:nO});(0,v.startTransition)(()=>{l(e=>e?fO(e,s):s),a(e=>e+(s.pageSize??2e3))})},[r,o,e,t]),h=(0,v.useCallback)(()=>{s(e=>e+80)},[]);return{baseTraceView:c,traceEventLimit:i,rawEventLimit:o,traceSummaryQuery:f,tracePageQuery:p,tracePageReady:!!d,loadOlderTracePage:m,loadMoreRawEvents:h}}function mO(e){let t=e.currentEvents,n,r,i=()=>(r??=new Set(t.map(bO)),r),a=e=>{n??=t.slice(),n.push(e),t=n};for(let o of e.streamEvents){let s=_O(o,e.piboSessionId,e.nextSequence,e.now??(()=>new Date().toISOString()));if(!s)continue;if(hO(s)){t=gO(t,s),n=t,r=void 0;continue}let c=bO(s),l=i();l.has(c)||(l.add(c),a(s))}return t}function hO(e){return e.type===`assistant_message`||e.type===`thinking_finished`||e.type===`tool_execution_finished`}function gO(e,t){return t.type===`assistant_message`?[...yO(e,t,`assistant_delta`),t]:t.type===`thinking_finished`?[...yO(e,t,`thinking_delta`),t]:t.type===`tool_execution_finished`?[...yO(e,t,`tool_execution_updated`),t]:e}function _O(e,t,n,r){if(e.type===`RAW_EVENT`&&CO(e.event)&&typeof e.event.type==`string`){let i=e.event;return vO(e,t,e.event.type,i,n,r)}if(e.type===`TEXT_MESSAGE_CONTENT`&&typeof e.delta==`string`)return vO(e,t,`assistant_delta`,{type:`assistant_delta`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,...SO(typeof e.messageId==`string`?e.messageId:void 0,`assistant`),text:e.delta},n,r);if(e.type===`REASONING_MESSAGE_CONTENT`&&typeof e.delta==`string`)return vO(e,t,`thinking_delta`,{type:`thinking_delta`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,...SO(typeof e.messageId==`string`?e.messageId:void 0,`thinking`),text:e.delta},n,r);if(e.type===`TOOL_CALL_START`&&typeof e.toolCallId==`string`&&typeof e.toolName==`string`)return vO(e,t,`tool_execution_started`,{type:`tool_execution_started`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,toolCallId:e.toolCallId,toolName:e.toolName,args:e.args},n,r);if(e.type===`TOOL_CALL_ARGS`&&typeof e.toolCallId==`string`&&typeof e.toolName==`string`){let i=typeof e.runId==`string`?e.runId:void 0,a=e.sourceEventType===`tool_execution_updated`?`tool_execution_updated`:`tool_call`;return vO(e,t,a,a===`tool_execution_updated`?{type:`tool_execution_updated`,piboSessionId:t,eventId:i,toolCallId:e.toolCallId,toolName:e.toolName,args:e.args,partialResult:e.partialResult}:{type:`tool_call`,piboSessionId:t,eventId:i,toolCallId:e.toolCallId,toolName:e.toolName,args:e.args,argsComplete:!!e.argsComplete},n,r)}if(e.type===`TOOL_CALL_RESULT`&&typeof e.toolCallId==`string`&&typeof e.toolName==`string`)return vO(e,t,`tool_execution_finished`,{type:`tool_execution_finished`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,toolCallId:e.toolCallId,toolName:e.toolName,result:e.result,isError:!!e.isError},n,r);if(e.type===`RUN_ERROR`&&typeof e.message==`string`)return vO(e,t,`session_error`,{type:`session_error`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,error:e.message,errorDetails:e.errorDetails},n,r)}function vO(e,t,n,r,i,a){let o=typeof e.streamFrameId==`string`?e.streamFrameId:void 0,s=typeof e.streamFrameIndex==`number`?e.streamFrameIndex:void 0,c=typeof e.liveReplayId==`number`&&Number.isFinite(e.liveReplayId)?e.liveReplayId:void 0,l=i();return{id:typeof e.streamId==`number`?`stream:${e.streamId}:${s??`raw`}:${n}`:c===void 0?o?`stream:${o}:${n}`:`live:${l}:${n}`:`live-replay:${c}:${n}`,piboSessionId:t,eventSequence:l,streamId:typeof e.streamId==`number`?e.streamId:void 0,streamFrameIndex:s,eventId:typeof r.eventId==`string`?r.eventId:void 0,type:n,createdAt:a(),payload:r}}function yO(e,t,n){let r=xO(t);return e.filter(e=>e.type!==n||xO(e)!==r)}function bO(e){return e.streamId===void 0?`${e.id}:${e.type}`:e.streamFrameIndex===void 0?`stream:${e.streamId}:${e.id}:${e.type}`:`stream:${e.streamId}:${e.streamFrameIndex}:${e.type}`}function xO(e){let t=CO(e.payload)?e.payload:{},n=typeof t.piboSessionId==`string`?t.piboSessionId:e.piboSessionId??``,r=typeof t.eventId==`string`?t.eventId:e.eventId??``;if(typeof t.toolCallId==`string`)return`${n}:${r}:tool:${t.toolCallId}`;let i=typeof t.assistantIndex==`number`?t.assistantIndex:void 0,a=typeof t.thinkingIndex==`number`?t.thinkingIndex:void 0,o=typeof t.contentIndex==`number`?t.contentIndex:0;return`${n}:${r}:${i??a??o}`}function SO(e,t){let n=e?.match(RegExp(`:${t}:(\\d+)$`));if(!n)return{};let r=Number(n[1]);return Number.isInteger(r)?t===`assistant`?{assistantIndex:r}:{thinkingIndex:r}:{}}function CO(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function wO(e){try{let t=JSON.parse(e.data);if(typeof t.type!=`string`)return;let n=e.lastEventId?cx(e.lastEventId):void 0;return{...t,...e.lastEventId?{streamFrameId:e.lastEventId}:{},...n?{streamId:n.streamId,streamFrameIndex:n.frameIndex}:{}}}catch{return}}function TO(e,t,n){let r=e.get(t);r?.streamId!==void 0&&r.streamId>=n||e.set(t,{streamId:n,frameIndex:2**53-1,cursor:DO(n),exact:!1,...r?.liveReplayId===void 0?{}:{liveReplayId:r.liveReplayId}})}function EO(e,t,n){let r=e.get(t),i=typeof n.liveReplayId==`number`&&Number.isFinite(n.liveReplayId)?Math.max(r?.liveReplayId??0,n.liveReplayId):r?.liveReplayId;if(n.streamId===void 0||n.streamFrameIndex===void 0){i!==void 0&&i!==r?.liveReplayId&&e.set(t,{...r??{exact:!1},liveReplayId:i});return}if(r&&(r.streamId!==void 0&&r.streamId>n.streamId||r.streamId===n.streamId&&r.exact&&r.frameIndex!==void 0&&r.frameIndex>=n.streamFrameIndex)){i!==void 0&&i!==r.liveReplayId&&e.set(t,{...r,liveReplayId:i});return}e.set(t,{streamId:n.streamId,frameIndex:n.streamFrameIndex,cursor:n.streamFrameId??`${n.streamId}:${n.streamFrameIndex}`,exact:!0,...i===void 0?{}:{liveReplayId:i}})}function DO(e){return`${e}:999999`}function OO(e){if(e.type===`RUN_FINISHED`||e.type===`TEXT_MESSAGE_END`)return 300;if(e.type===`RUN_ERROR`)return 0}function kO(e){return e.type===`RUN_STARTED`||e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`||e.type===`TEXT_MESSAGE_END`}function AO(e){return e.type===`TEXT_MESSAGE_CONTENT`||e.type===`REASONING_MESSAGE_CONTENT`||e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_RESULT`||e.type===`RUN_ERROR`||e.type===`RAW_EVENT`}function jO(e,t,n){if(n.type===`RUN_STARTED`||n.type===`RUN_FINISHED`||n.type===`RUN_ERROR`){e.delete(t);return}let r=PO(n);r&&e.get(t)?.delete(r)}function MO(e,t,n){let r=NO(n);if(!r)return!1;let i=e.get(t);return i||(i=new Set,e.set(t,i)),i.has(r)?!1:(i.add(r),!0)}function NO(e){if(e.type===`TEXT_MESSAGE_CONTENT`||e.type===`REASONING_MESSAGE_CONTENT`)return`${e.type}:${e.messageId}`}function PO(e){if(e.type===`TEXT_MESSAGE_START`)return`TEXT_MESSAGE_CONTENT:${e.messageId}`;if(e.type===`REASONING_MESSAGE_START`)return`REASONING_MESSAGE_CONTENT:${e.messageId}`}var FO=500,IO=1e4,LO=45e3,RO=100;function zO({selectedPiboSessionId:e,tracePageData:t,currentTraceView:n,liveEventSeqRef:r,selectedSessionStatus:i,tracePageReady:a,setLiveTraceOverlay:o,onRefreshTrace:s,onRefreshBootstrap:c,onError:l}){let u=(0,v.useRef)(new Map),d=(0,v.useRef)(void 0),f=(0,v.useRef)(void 0),p=(0,v.useRef)(new Map),m=(0,v.useRef)(new Map),h=(0,v.useRef)(null),g=(0,v.useRef)(void 0),_=(0,v.useRef)(0),[y,b]=(0,v.useState)(0);(0,v.useEffect)(()=>{let n=t;if(!n||n.piboSessionId!==e)return;let i=n.rawEvents.map(e=>e.eventSequence??0).reduce((e,t)=>Math.max(e,t),0);r.current=Math.max(r.current,i+1),n.latestStreamId!==void 0&&TO(m.current,n.piboSessionId,n.latestStreamId)},[r,e,t]);let x=(0,v.useCallback)(e=>{let t=u.current.get(e);t?.length&&(o(n=>{let i=mO({currentEvents:n?.piboSessionId===e?n.events:[],streamEvents:t,piboSessionId:e,nextSequence:()=>r.current++});return vv(e,t.length,i.length),{piboSessionId:e,events:i}}),u.current.delete(e))},[]),S=(0,v.useCallback)(()=>{if(!(d.current!==void 0||f.current!==void 0||!e)){if(document.hidden){f.current=setTimeout(()=>{f.current=void 0,x(e)},RO);return}d.current=requestAnimationFrame(()=>{d.current=void 0,x(e)})}},[x,e]),C=(0,v.useCallback)((t,n,r=!1)=>{jO(p.current,t,n);let i=r||MO(p.current,t,n),a=u.current.get(t)??[];a.push(n),u.current.set(t,a),_v(t,n,a.length,i),i||t!==e?x(t):S()},[x,S,e]);(0,v.useEffect)(()=>()=>{d.current!==void 0&&cancelAnimationFrame(d.current),f.current!==void 0&&clearTimeout(f.current),g.current!==void 0&&clearTimeout(g.current)},[]);let w=(0,v.useCallback)((e,t)=>{EO(m.current,e,t)},[]),T=(0,v.useCallback)((e=0)=>{if(g.current!==void 0){if(e>0)return;clearTimeout(g.current)}g.current=setTimeout(()=>{g.current=void 0,b(e=>e+1)},e)},[]),E=(0,v.useCallback)(()=>{if(!e)return;x(e),s().catch(e=>l(BO(e))),c().catch(e=>l(BO(e)));let t=h.current;(!t||t.piboSessionId!==e||t.events.readyState===2||Date.now()-t.lastActivityAt>LO)&&T()},[x,l,c,s,T,e]);(0,v.useEffect)(()=>{if(!e||!a||!n||n.piboSessionId!==e)return;let t=new URLSearchParams({piboSessionId:e});t.set(`mode`,`live`);let r=m.current.get(e),i=r?.cursor??(n.latestStreamId===void 0?void 0:DO(n.latestStreamId));i!==void 0&&t.set(`since`,i),r?.liveReplayId!==void 0&&t.set(`liveSince`,String(r.liveReplayId));let o=new EventSource(`/api/chat/events?${t.toString()}`),u=Date.now();h.current={piboSessionId:e,events:o,openedAt:u,lastActivityAt:u};let d=!1,f,p,v=!1,y=!1,b=(t,n=!1)=>{if(f){if(!n)return;clearTimeout(f)}xv(e,t),f=setTimeout(()=>{f=void 0,s().catch(e=>l(BO(e)))},t)},S=()=>{if(v){y=!0;return}v=!0,c().catch(e=>l(BO(e))).finally(()=>{v=!1,y&&(y=!1,E(250,!0))})},E=(e,t=!1)=>{if(p){if(!t)return;clearTimeout(p)}p=setTimeout(()=>{p=void 0,S()},e)},ee=()=>{E(900,!0)};return o.onopen=()=>{_.current=0,g.current!==void 0&&(clearTimeout(g.current),g.current=void 0),mv(e,o.readyState);let t=h.current;t?.events===o&&(t.lastActivityAt=Date.now())},o.onerror=()=>{if(d)return;hv(e,o.readyState);let t=h.current;t?.events===o&&(t.lastErrorAt=Date.now());let n=_.current++;T(Math.min(IO,FO*2**n))},o.addEventListener(`pibo`,t=>{if(d)return;let n=wO(t);if(!n)return;let r=n.piboSessionId||e,i=h.current;if(i?.events===o&&(i.lastActivityAt=Date.now()),w(r,n),gv(r,n,t.lastEventId,o.readyState),r===e&&n.type===`ready`&&n.liveReplay?.missed&&b(0,!0),Cv(n))return;let a=n.type!==`TEXT_MESSAGE_CONTENT`&&n.type!==`REASONING_MESSAGE_CONTENT`;r===e&&AO(n)&&C(r,n,a);let s=OO(n);r===e&&s!==void 0?b(s,!0):r===e&&n.type!==`ready`&&n.type!==`RAW_EVENT`&&b(1500,!0),kO(n)&&(n.type===`RUN_FINISHED`||n.type===`RUN_ERROR`||n.type===`TEXT_MESSAGE_END`?ee():E(r===e?0:150))}),()=>{d=!0,f&&clearTimeout(f),p&&clearTimeout(p),x(e),h.current?.events===o&&(h.current=null),o.close()}},[n?.piboSessionId,C,x,l,c,s,w,T,y,e,a]),(0,v.useEffect)(()=>{n?.piboSessionId&&x(n.piboSessionId)},[n?.piboSessionId,x]),(0,v.useEffect)(()=>{let e=()=>E(),t=()=>{document.hidden||E()};return window.addEventListener(`focus`,e),window.addEventListener(`online`,e),window.addEventListener(`pageshow`,e),document.addEventListener(`visibilitychange`,t),()=>{window.removeEventListener(`focus`,e),window.removeEventListener(`online`,e),window.removeEventListener(`pageshow`,e),document.removeEventListener(`visibilitychange`,t)}},[E]),(0,v.useEffect)(()=>{if(!e||i!==`running`)return;let t=window.setInterval(()=>{x(e),s().catch(e=>l(BO(e)))},1e3);return()=>window.clearInterval(t)},[x,l,s,e,i])}function BO(e){return e instanceof Error?e.message:String(e)}var VO=10;function HO(e,t,n,r){if(!t||!n.length)return e;let i=e[t]??[],a=new Set(i.map(e=>e.path)),o=n.filter(e=>e.path&&!a.has(e.path)).map(e=>({...e,id:r()}));return o.length?{...e,[t]:[...i,...o].slice(0,VO)}:e}function UO(e,t,n){if(!t)return e;let r=e[t]??[],i=r.filter(e=>e.id!==n);return i.length===r.length?e:{...e,[t]:i}}function WO(e,t){return!t||!e[t]?.length?e:{...e,[t]:[]}}function GO(e,t){let[n,r]=(0,v.useState)({});return{selectedUploadAttachments:(0,v.useMemo)(()=>e?n[e]??[]:[],[e,n]),attachUploadedFiles:(0,v.useCallback)(n=>{r(r=>HO(r,e,n,t))},[t,e]),detachUploadAttachment:(0,v.useCallback)(t=>{r(n=>UO(n,e,t))},[e]),clearSelectedUploadAttachments:(0,v.useCallback)(()=>{r(t=>WO(t,e))},[e])}}function KO({selectedPiboSessionId:e,onError:t,formatError:n}){let[r,i]=(0,v.useState)([]),[a,o]=(0,v.useState)(!1),[s,c]=(0,v.useState)(()=>e?cE(e):null),[l,u]=(0,v.useState)(()=>mE()),[d,f]=(0,v.useState)(!1),p=!!(e&&s?.piboSessionId===e&&s.installed),m=!!e&&(a||p),h=eO({queryKey:[`web-annotations`,`app`,e],queryFn:async()=>{if(!e)throw Error(`Session is required`);return gb(e,{limit:100,scope:`app`})},enabled:!!e&&(m||r.length>0),staleTime:1e3,refetchOnWindowFocus:m,refetchInterval:m?5e3:!1,retry:1}),g=h.refetch,_=(0,v.useMemo)(()=>(h.data?.annotations??[]).filter(e=>e.status!==`resolved`&&e.status!==`dismissed`),[h.data?.annotations]),y=(0,v.useMemo)(()=>r.map(e=>_.find(t=>t.id===e)).filter(e=>!!e),[r,_]);(0,v.useEffect)(()=>{i(e?fE(e):[]),c(e?cE(e):null)},[e]),(0,v.useEffect)(()=>{if(!e)return;let t=t=>{!t||t.piboSessionId!==e||(c(e=>t.installed?t:e?.installed&&e.bindingId&&t.bindingId&&e.bindingId!==t.bindingId?e:t),t.installed?g():o(!1))},n=e=>t(dE(e.detail)),r=n=>{n.key===lE(e)&&t(uE(n.newValue))},i=()=>t(cE(e));return window.addEventListener(`pibo:web-annotation-overlay-state`,n),window.addEventListener(`storage`,r),window.addEventListener(`focus`,i),document.addEventListener(`visibilitychange`,i),i(),()=>{window.removeEventListener(`pibo:web-annotation-overlay-state`,n),window.removeEventListener(`storage`,r),window.removeEventListener(`focus`,i),document.removeEventListener(`visibilitychange`,i)}},[g,e]),(0,v.useEffect)(()=>{if(!h.data)return;if(!_.length){i(t=>(t.length&&e&&pE(e,[]),t.length?[]:t));return}let t=new Set(_.map(e=>e.id));i(n=>{let r=n.filter(e=>t.has(e));return r.length!==n.length&&e&&pE(e,r),r.length===n.length?n:r})},[e,_,h.data]),(0,v.useEffect)(()=>{let e=()=>{o(!0),g()};return window.addEventListener(`pibo:web-annotation-saved`,e),()=>window.removeEventListener(`pibo:web-annotation-saved`,e)},[g]);let b=(0,v.useCallback)(t=>{i(n=>{let r=t(n);return e&&pE(e,r),r})},[e]),x=(0,v.useCallback)(e=>{b(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e].slice(0,5))},[b]),S=(0,v.useCallback)(()=>b(()=>[]),[b]);return{selectedWebAnnotationIds:r,selectedWebAnnotations:y,visibleWebAnnotations:_,webAnnotationsPanelCollapsed:l,webAnnotationsPanelRendered:m,webAnnotationsPanelVisible:a,webAnnotationsQuery:h,clearingWebAnnotations:d,setWebAnnotationsPanelVisible:o,toggleWebAnnotationAttachment:x,detachWebAnnotationAttachment:(0,v.useCallback)(e=>{b(t=>t.filter(t=>t!==e))},[b]),clearSelectedWebAnnotationAttachments:S,toggleWebAnnotationsPanelCollapsed:(0,v.useCallback)(()=>{u(e=>{let t=!e;return hE(t),t})},[]),clearVisibleWebAnnotations:(0,v.useCallback)(async()=>{if(!(!_.length||d)&&window.confirm(`Dismiss ${_.length} visible web annotations? This keeps sent messages but clears the annotation list.`)){f(!0);try{await Promise.all(_.map(e=>_b(e.id,{piboSessionId:e.piboSessionId,status:`dismissed`,summary:`Cleared from Chat Web UI`}))),S(),await g()}catch(e){t(n(e,`Could not clear web annotations`))}finally{f(!1)}}},[d,S,n,t,g,_])}}function qO(e,t){return t?{sessionBreadcrumbs:QO(e,t),originSession:XO(e,t),derivedSessions:ZO(e,t)}:{sessionBreadcrumbs:[],originSession:void 0,derivedSessions:[]}}function JO(e){let t=e.selectedPiboSessionId?S(e.bootstrap.sessions,e.selectedPiboSessionId):void 0,n=nk(e.currentTraceView);return tk(e.selectedSessionActiveModel,e.bootstrap.runtimeStatus?.thinkingLevel??n.level??$O(e.bootstrap,e.selectedSessionProfile,!!t?.parentId),e.bootstrap.runtimeStatus?.fastMode??n.fast??ek(e.bootstrap,e.selectedSessionProfile,!!t?.parentId)??!1)}function YO(e){return{traceView:e.currentTraceView,selectedTrace:null,isLoading:e.isLoading,showThinking:e.showThinking,expandThinking:e.expandThinking,sessionAgentProfile:e.selectedSessionProfile,sessionActiveModel:e.sessionActiveModelBadge,selectedSessionStatus:e.selectedSessionStatus,selectedSessionSignal:e.selectedSessionSignal,workflowProjectSession:e.workflowProjectSession,workflowLifecycleEvents:e.workflowLifecycleEvents,sessionNodes:e.sessionNodes,sessionBreadcrumbs:e.sessionLinks.sessionBreadcrumbs,originSession:e.sessionLinks.originSession,derivedSessions:e.sessionLinks.derivedSessions,agentProfiles:e.agentProfiles,sessionProfileChangeDisabled:e.sessionProfileChangeDisabled,onSessionAgentProfileChange:e.onSessionAgentProfileChange,onFork:e.onFork,onOpenSession:e.onOpenSession,onThinkingLevelChange:e.onThinkingLevelChange,onModelChanged:async()=>{await e.onRefreshBootstrap(),await e.onRefreshTrace()},onRefreshBootstrap:e.onRefreshBootstrap,onError:e.onError}}function XO(e,t){let n=S(e,t);if(!n?.originId)return;let r=S(e,n.originId);return{piboSessionId:n.originId,label:r?ak(r,0):n.originId}}function ZO(e,t){return S(e,t)?.derivedSessions.map(e=>({piboSessionId:e.piboSessionId,label:ok(e),profile:e.profile,status:e.status}))??[]}function QO(e,t){return C(e,t).map((e,t)=>({piboSessionId:e.piboSessionId,label:ak(e,t)}))}function $O(e,t,n=!1){let r=e.agents.find(e=>e.name===t),i=e.customAgents.find(e=>e.profileName===t),a=r??i;return n?a?.subagentThinkingLevel??a?.thinkingLevel??e.modelDefaults?.subagentThinking??e.modelDefaults?.thinking:a?.mainThinkingLevel??a?.thinkingLevel??e.modelDefaults?.mainThinking??e.modelDefaults?.thinking}function ek(e,t,n=!1){let r=e.agents.find(e=>e.name===t),i=e.customAgents.find(e=>e.profileName===t),a=r??i;return n?a?.subagentFast??a?.fast??e.modelDefaults?.subagentFast??e.modelDefaults?.fast:a?.mainFast??a?.fast??e.modelDefaults?.mainFast??e.modelDefaults?.fast}function tk(e,t,n){if(e)return[e,t,n?`fast`:void 0].filter(Boolean).join(` `)}function nk(e){let t={};if(!e)return t;for(let n of rk(e.nodes)){if(n.type!==`execution.command`||n.title!==`thinking`&&n.title!==`fast_mode`)continue;let e=n.output&&typeof n.output==`object`?n.output:void 0;t={level:(typeof e?.level==`string`&&ik(e.level)?e.level:void 0)??t.level,fast:n.title===`fast_mode`?e?.mode===`fast`:t.fast}}return t}function rk(e){return e.flatMap(e=>[e,...rk(e.children)])}function ik(e){return zC.includes(e)}function ak(e,t){return t?e.subagentName&&e.subagentName!==e.profile?`${e.subagentName} (${e.profile})`:e.profile||e.subagentName||e.title:e.profile||e.title}function ok(e){return e.subagentName&&e.subagentName!==e.profile?`${e.subagentName} (${e.profile})`:e.title||e.profile||e.subagentName||`Untitled Session`}function sk({piboSessionId:e,text:t,selectedWebAnnotations:n,selectedUploadAttachments:r,eventSequence:i,now:a,clientTxnId:o}){let s=n.map(e=>e.id),c=r.map(e=>e.path);return{text:t,webAnnotationIds:s,fileAttachmentPaths:c,clientTxnId:o,optimisticEvent:{id:o,piboSessionId:e,eventSequence:i,eventId:o,type:`message_queued`,createdAt:a,payload:{type:`message_queued`,piboSessionId:e,eventId:o,clientTxnId:o,queuedMessages:1,text:t,...c.length?{fileAttachmentPaths:c}:{},source:`user`}}}}function ck(e,t,n){return{piboSessionId:t,events:[...e?.piboSessionId===t?e.events:[],n]}}function lk(e){return e instanceof Error?e.message:String(e)}function uk({bootstrap:e,selectedPiboSessionId:t,selectedRoomId:n,selectedRoomArchived:r,selectedSessionProfile:i,selectedSessionActiveModel:a,selectedSessionStatus:o,selectedSessionSignal:s,workflowProjectSession:c,workflowLifecycleEvents:l,projectSessionCreatePanel:u,workflowStartPanel:d,sessionViewId:f,sessionViews:p,currentSessionView:m,allowedSessionViewIds:h,creatingSession:g,showRawEvents:_,showThinking:y,expandThinking:b,commands:x,skills:S,composerText:C,composerFocusSignal:T,onComposerTextChange:E,onToggleRawEvents:ee,onToggleThinking:D,onToggleExpandThinking:O,onSessionAgentProfileChange:te,onFork:ne,onOpenSession:re,onSelectSessionView:ie,onCommand:ae,onThinkingLevelChange:oe,onRefreshTrace:k,onRefreshBootstrap:A,onSend:se,onError:ce}){let le=(0,v.useRef)(0),[ue,de]=(0,v.useState)(null),{baseTraceView:fe,traceEventLimit:pe,rawEventLimit:me,traceSummaryQuery:he,tracePageQuery:ge,tracePageReady:_e,loadOlderTracePage:ve,loadMoreRawEvents:ye}=pO({selectedPiboSessionId:t,showRawEvents:_,setLiveTraceOverlay:de}),{selectedWebAnnotationIds:be,selectedWebAnnotations:xe,visibleWebAnnotations:j,webAnnotationsPanelCollapsed:Se,webAnnotationsPanelRendered:Ce,webAnnotationsPanelVisible:we,webAnnotationsQuery:Te,clearingWebAnnotations:Ee,setWebAnnotationsPanelVisible:De,toggleWebAnnotationAttachment:Oe,detachWebAnnotationAttachment:ke,clearSelectedWebAnnotationAttachments:Ae,toggleWebAnnotationsPanelCollapsed:je,clearVisibleWebAnnotations:Me}=KO({selectedPiboSessionId:t,onError:ce,formatError:SE}),{selectedUploadAttachments:Ne,attachUploadedFiles:Pe,detachUploadAttachment:Fe,clearSelectedUploadAttachments:Ie}=GO(t,(0,v.useCallback)(()=>`upload-${w()}`,[])),Le=iD({selectedPiboSessionId:t,baseTraceView:fe,liveTraceOverlay:ue,selectedSessionStatus:o});zO({selectedPiboSessionId:t,tracePageData:ge.data,currentTraceView:Le,liveEventSeqRef:le,selectedSessionStatus:o,tracePageReady:_e,setLiveTraceOverlay:de,onRefreshTrace:k,onRefreshBootstrap:A,onError:ce});let Re=JO({bootstrap:e,selectedPiboSessionId:t,selectedSessionProfile:i,selectedSessionActiveModel:a,currentTraceView:Le}),ze=(0,v.useMemo)(()=>qO(e.sessions,t),[e.sessions,t]),Be=!!t&&ge.isFetching&&!Le,Ve=ge.error?lk(ge.error):he.error?lk(he.error):null,He=Le?.piboSessionId??t??``,Ue=c&&OE(c)?kE(c,o):null,We=async e=>{if(!t)return;let n=sk({piboSessionId:t,text:e,selectedWebAnnotations:xe,selectedUploadAttachments:Ne,eventSequence:le.current++,now:new Date().toISOString(),clientTxnId:w()});de(e=>ck(e,t,n.optimisticEvent)),await se(n.text,n.webAnnotationIds,n.fileAttachmentPaths,n.clientTxnId),Ae(),Ie(),await Promise.all([ge.refetch(),Te.refetch()])},Ge=YO({currentTraceView:Le,isLoading:Be,showThinking:y,expandThinking:b,selectedSessionProfile:i,sessionActiveModelBadge:Re,selectedSessionStatus:o,selectedSessionSignal:s,workflowProjectSession:c,workflowLifecycleEvents:l,sessionNodes:e.sessions,sessionLinks:ze,agentProfiles:e.agents,sessionProfileChangeDisabled:g||r,onSessionAgentProfileChange:te,onFork:ne,onOpenSession:re,onThinkingLevelChange:oe,onRefreshTrace:k,onRefreshBootstrap:A,onError:ce});return(0,M.jsx)(UE,{selectedPiboSessionId:t,selectedRoomId:n,fallbackRoomId:e.selectedRoomId??void 0,sessionViewId:f,loadingTrace:Be,traceError:Ve,showRawEvents:_,currentTraceView:Le,traceEventLimit:pe,rawEventLimit:me,tracePageFetching:ge.isFetching,onLoadOlderTracePage:e=>void ve(e),onLoadMoreRawEvents:ye,headerProps:{title:Le?.title??t??e.room?.name??n,roomLabel:e.room?.name??n??`Room`,headerPiboSessionId:He,piboSessionId:t,piboRoomId:n??e.selectedRoomId??void 0,webAnnotationsDisabled:!t||r,webAnnotationsPanelRendered:Ce,workflowHeader:Ue,sessionViewId:f,sessionViews:p,currentSessionView:m,allowedSessionViewIds:h,showRawEvents:_,showThinking:y,expandThinking:b,onShowWebAnnotationsPanel:()=>De(!0),onHideWebAnnotationsPanel:()=>De(!1),onSelectSessionView:ie,onToggleRawEvents:ee,onToggleThinking:D,onToggleExpandThinking:O,onError:ce},projectSessionCreatePanel:u,workflowStartPanel:d,currentSessionView:m,sessionViewProps:Ge,webAnnotationsPanelRendered:Ce,webAnnotationsPanelProps:{piboSessionId:t,annotations:j,selectedIds:be,loading:Te.isLoading||Te.isFetching||Ee,error:Te.error?lk(Te.error):null,collapsed:Se,onRefresh:()=>void Te.refetch(),onToggle:Oe,onClear:()=>void Me(),onCollapse:je,onClose:()=>De(!1)},composerProps:{sessionId:t,disabled:!t||r,commands:x,skills:S,value:C,focusSignal:T,selectedWebAnnotations:xe,selectedUploadAttachments:Ne,onValueChange:E,onCommand:ae,onDetachWebAnnotation:ke,onClearWebAnnotations:Ae,onAttachUploadedFiles:Pe,onDetachUploadAttachment:Fe,onClearUploadAttachments:Ie,onSend:We}})}function dk({mode:e,onSelectSession:t,onNewSession:n,onDeleteSession:r,onRenameSession:i,onSelectRoom:a}){return e.kind===`rooms`?(0,M.jsx)(vk,{candidates:e.candidates,workspace:e.workspace,onSelectRoom:a}):(0,M.jsx)(gk,{sessions:e.sessions,selectedPiboSessionId:e.selectedPiboSessionId,onSelectSession:t,onNewSession:n,onDeleteSession:r,onRenameSession:i})}function fk(e){return e===`running`?`running`:e===`error`?`error`:e===`completed`?`completed`:`idle`}var pk={running:`bg-cyan-400`,idle:`bg-slate-500`,error:`bg-rose-500`,completed:`bg-emerald-500`},mk={running:`running`,idle:`idle`,error:`error`,completed:`completed`};function hk({status:e}){let t=fk(e);return(0,M.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-[10px] uppercase tracking-wider text-slate-400`,children:[(0,M.jsx)(`span`,{className:`inline-block w-1.5 h-1.5 rounded-full ${pk[t]}`,"aria-hidden":`true`}),mk[t]]})}function gk({sessions:e,selectedPiboSessionId:t,onSelectSession:n,onNewSession:r,onDeleteSession:i,onRenameSession:a}){let o=[...e].sort((e,t)=>{let n=e.lastActivityAt??``;return(t.lastActivityAt??``).localeCompare(n)});return(0,M.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-slate-800 px-3 py-2 bg-[#0c1820]`,"data-testid":`session-list`,children:[(0,M.jsx)(`button`,{type:`button`,className:`shrink-0 w-7 h-7 inline-flex items-center justify-center rounded border border-slate-700 text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4]`,title:`New session`,onClick:()=>void r(`default`),children:`+`}),(0,M.jsxs)(`ul`,{className:`flex gap-1 overflow-x-auto min-w-0`,children:[o.map(e=>(0,M.jsx)(`li`,{className:`shrink-0`,children:(0,M.jsx)(_k,{session:e,isActive:e.piboSessionId===t,onSelect:()=>n(e.piboSessionId),onDelete:()=>void i(e.piboSessionId),onRename:t=>void a(e.piboSessionId,t)})},e.piboSessionId)),o.length===0&&(0,M.jsx)(`li`,{className:`text-xs text-slate-500 px-2 py-1`,children:`No sessions yet — click + to start one.`})]})]})}function _k({session:e,isActive:t,onSelect:n,onDelete:r,onRename:i}){let[a,o]=(0,v.useState)(!1);return(0,M.jsxs)(`div`,{className:`group inline-flex items-center gap-2 rounded px-2 py-1 border ${t?`border-[#11a4d4] bg-[#102834]`:`border-slate-700 bg-[#0a1418] hover:border-slate-500`}`,children:[(0,M.jsxs)(`button`,{type:`button`,onClick:n,className:`inline-flex items-center gap-2 text-left`,children:[(0,M.jsx)(hk,{status:e.status}),(0,M.jsx)(`span`,{className:`text-xs text-slate-200 max-w-[180px] truncate`,children:e.title||`Untitled`})]}),(0,M.jsx)(`button`,{type:`button`,className:`text-slate-500 hover:text-slate-200 text-xs px-1`,title:`Session actions`,"aria-label":`Session actions`,onClick:e=>{e.stopPropagation(),o(e=>!e)},children:`…`}),a&&(0,M.jsxs)(`div`,{className:`absolute z-10 mt-12 -ml-20 bg-[#0a1418] border border-slate-700 rounded shadow-lg text-xs`,children:[(0,M.jsx)(`button`,{type:`button`,className:`block w-full text-left px-3 py-1.5 hover:bg-[#102834]`,onClick:t=>{t.stopPropagation(),o(!1);let n=window.prompt(`Rename session`,e.title??``);n&&n!==e.title&&i(n)},children:`Rename`}),(0,M.jsx)(`button`,{type:`button`,className:`block w-full text-left px-3 py-1.5 hover:bg-rose-900/30 text-rose-300`,onClick:t=>{t.stopPropagation(),o(!1),window.confirm(`Delete session "${e.title??`Untitled`}"?`)&&r()},children:`Delete`})]})]})}function vk({candidates:e,workspace:t,onSelectRoom:n}){return(0,M.jsxs)(`div`,{className:`border-b border-slate-800 px-3 py-3 bg-[#0c1820]`,"data-testid":`room-picker`,children:[(0,M.jsxs)(`div`,{className:`text-[10px] uppercase tracking-wider text-slate-400 mb-2`,children:[`Multiple rooms found for `,(0,M.jsx)(`span`,{className:`font-mono text-slate-300`,children:t})]}),(0,M.jsx)(`ul`,{className:`flex flex-col gap-1`,children:e.map(e=>(0,M.jsx)(`li`,{children:(0,M.jsxs)(`button`,{type:`button`,className:`w-full text-left px-3 py-2 border border-slate-700 rounded hover:border-[#11a4d4] bg-[#0a1418]`,onClick:()=>n(e.id),children:[(0,M.jsx)(`div`,{className:`font-semibold text-slate-200 text-sm`,children:e.name}),e.topic&&(0,M.jsx)(`div`,{className:`text-xs text-slate-400 mt-0.5`,children:e.topic}),(0,M.jsxs)(`div`,{className:`text-[10px] text-slate-500 mt-1`,children:[`Created `,yk(e.createdAt),` · Updated `,yk(e.updatedAt)]})]})},e.id))})]})}function yk(e){try{return new Date(e).toLocaleString()}catch{return e}}function bk(){return new URLSearchParams(window.location.search).get(`workspace`)}function xk(){return new URLSearchParams(window.location.search).get(`roomId`)}function Sk(){let e=(0,v.useMemo)(()=>bk(),[]),[t,n]=(0,v.useState)(()=>xk()),[r,i]=(0,v.useState)(()=>xk()?{kind:`sessions`,roomId:xk(),sessions:[],selectedPiboSessionId:null}:{kind:`rooms`,candidates:[],workspace:e??``}),[a,o]=(0,v.useState)(null),[s,c]=(0,v.useState)(null),[l,u]=(0,v.useState)(``),[d,f]=(0,v.useState)(0),[p,m]=(0,v.useState)(null),[h,g]=(0,v.useState)(!1),_=(0,v.useMemo)(()=>{let e=a?.sessionNodes;return Array.isArray(e)?e:[]},[a]);(0,v.useEffect)(()=>{if(!t)return;let e=!1;return(async()=>{try{let n=await te(void 0,!1,t);if(e)return;o(n);let r=n.sessions.find(e=>!e.archived)??n.sessions[0];r&&!s&&c(r.piboSessionId),i({kind:`sessions`,roomId:t,sessions:n.sessions,selectedPiboSessionId:r?.piboSessionId??null})}catch(t){e||m(lk(t))}})(),()=>{e=!0}},[t]);let y=(0,v.useCallback)(async()=>{if(t)try{o(await te(s??void 0,!1,t,!0))}catch(e){m(lk(e))}},[t,s]),b=(0,v.useCallback)(async()=>{await y()},[y]);(0,v.useEffect)(()=>{if(!t)return;let e=`/api/chat/events?${new URLSearchParams({roomId:t,mode:`summary`,since:`0:999999`}).toString()}`,n=new EventSource(e),r,i=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=void 0,y()},200)};return n.addEventListener(`change`,i),n.addEventListener(`trace`,i),n.addEventListener(`message`,i),n.onerror=()=>{},()=>{r&&clearTimeout(r),n.close()}},[t,y]),(0,v.useEffect)(()=>{let e=e=>{let t=e.data;!t||typeof t!=`object`||(t.type===`pibo/set-selector-mode`?(i(t.mode),t.mode.kind===`sessions`&&n(t.mode.roomId)):t.type===`pibo/refresh-bootstrap`&&y())};return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[y]);let S=(0,v.useMemo)(()=>a?ee(a.capabilities.actions):[],[a]),C=(0,v.useMemo)(()=>D(a,s),[a,s]),T=(0,v.useMemo)(()=>r.kind===`sessions`?r.sessions:_,[r,_]),E=(0,v.useCallback)(e=>{c(e),f(e=>e+1)},[]),O=(0,v.useCallback)(async e=>{if(t)try{let n=await ne(e,t);await y(),n.session?.id&&c(n.session.id)}catch(e){m(lk(e))}},[t,y]),k=(0,v.useCallback)(async e=>{try{await ie(e,`delete`),await y(),s===e&&c(null)}catch(e){m(lk(e))}},[y,s]),A=(0,v.useCallback)(async(e,t)=>{try{await re(e,{title:t}),await y()}catch(e){m(lk(e))}},[y]),se=(0,v.useCallback)(e=>{n(e),c(null),o(null),i({kind:`sessions`,roomId:e,sessions:[],selectedPiboSessionId:null});let t=new URLSearchParams(window.location.search);t.set(`roomId`,e),window.history.replaceState(null,``,`${window.location.pathname}?${t.toString()}`)},[]),ue=(0,v.useCallback)(async e=>{if(!(!s||!t))try{await ae(s,e,w(),t),u(``),f(e=>e+1),await y()}catch(e){m(lk(e))}},[s,t,y]),de=(0,v.useCallback)(async e=>{if(!s)return!1;let n=e.trim();if(!n)return!1;let r=n.split(/\s+/)[0],i=S.find(e=>e.slash===r);if(!i)return m(`Unknown command: ${r}`),!1;if(i.action===`thinking-show`)return g(e=>!e),!0;if(i.action===`download`){let e=ce(n.slice(r.length));if(!e)return m(`Usage: /download <path>`),!0;try{await fe(e,{piboSessionId:s,roomId:t??void 0})}catch(e){m(lk(e))}return!0}try{let e=le(i.action,n.slice(r.length).trim());await oe(s,i.action,e),await y()}catch(e){m(lk(e))}return!0},[S,s,t,y]),pe=(0,v.useMemo)(()=>PT(),[]),he=(0,v.useMemo)(()=>FT(me),[]);if(!a)return(0,M.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,M.jsx)(dk,{mode:r,onSelectSession:E,onNewSession:O,onDeleteSession:k,onRenameSession:A,onSelectRoom:se}),(0,M.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-slate-400 text-sm`,children:p?`Error: ${p}`:t?`Loading Pibo…`:`Waiting for room…`})]});if(r.kind===`rooms`)return(0,M.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,M.jsx)(dk,{mode:{kind:`rooms`,candidates:a.rooms??r.candidates,workspace:r.workspace},onSelectSession:E,onNewSession:O,onDeleteSession:k,onRenameSession:A,onSelectRoom:se}),(0,M.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-slate-400 text-sm`,children:`Multiple rooms found — pick one above to continue.`})]});let ge=a.sessions.find(e=>e.piboSessionId===s);return(0,M.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,M.jsx)(dk,{mode:{kind:`sessions`,roomId:t??``,sessions:T,selectedPiboSessionId:s},onSelectSession:E,onNewSession:O,onDeleteSession:k,onRenameSession:A,onSelectRoom:se}),p&&(0,M.jsxs)(`div`,{className:`bg-rose-900/40 border-b border-rose-700 text-rose-200 text-xs px-3 py-1.5`,role:`alert`,children:[p,(0,M.jsx)(`button`,{type:`button`,className:`ml-3 underline`,onClick:()=>m(null),children:`dismiss`})]}),(0,M.jsx)(`div`,{className:`flex-1 min-h-0`,children:(0,M.jsx)(uk,{bootstrap:a,selectedPiboSessionId:s,selectedRoomId:t,selectedRoomArchived:!1,selectedSessionProfile:ge?.profile??`default`,selectedSessionActiveModel:ge?x(a,ge)??void 0:void 0,selectedSessionStatus:ge?.status,sessionViewId:me,sessionViews:pe,currentSessionView:he,allowedSessionViewIds:[`terminal`],creatingSession:!1,showRawEvents:!1,showThinking:h,expandThinking:!1,commands:S,skills:C,composerText:l,composerFocusSignal:d,onComposerTextChange:u,onToggleRawEvents:()=>void 0,onToggleThinking:()=>g(e=>!e),onToggleExpandThinking:()=>void 0,onSessionAgentProfileChange:()=>void 0,onFork:()=>void 0,onOpenSession:e=>c(e),onSelectSessionView:()=>void 0,onCommand:de,onThinkingLevelChange:e=>void de(`/thinking ${e}`),onRefreshTrace:b,onRefreshBootstrap:y,onSend:ue,onError:m})})]})}var Ck=document.getElementById(`root`);Ck&&(0,y.createRoot)(Ck).render((0,M.jsx)(v.StrictMode,{children:(0,M.jsx)(Sk,{})}));
41
+ `)&&e.value.length<80){e.style.height=``,e.style.overflowY=`hidden`;return}let t=window.getComputedStyle(e),n=QT(t.lineHeight,20),r=QT(t.borderTopWidth)+QT(t.borderBottomWidth),i=n*5+QT(t.paddingTop)+QT(t.paddingBottom);e.style.height=`auto`;let a=e.scrollHeight,o=a>i;e.style.height=`${Math.min(a,i)+r}px`,e.style.overflowY=o?`auto`:`hidden`,o&&e.selectionStart===e.value.length&&e.selectionEnd===e.value.length&&(e.scrollTop=a)}function QT(e,t=0){let n=Number.parseFloat(e);return Number.isFinite(n)?n:t}var $T=`pibo.chat.webAnnotations.cdpUrl`,eE=`pibo.chat.webAnnotations.selected.`,tE=`pibo.chat.webAnnotations.overlay.`,nE=`pibo.chat.webAnnotations.panelCollapsed`,rE=`pibo.chat.shortcuts.webAnnotationsToggle`,iE=`Alt+Shift+A`;function aE(){try{return localStorage.getItem($T)??``}catch{return``}}function oE(e){try{e.trim()?localStorage.setItem($T,e.trim()):localStorage.removeItem($T)}catch{}}function sE(){try{return localStorage.getItem(rE)||`Alt+Shift+A`}catch{return iE}}function cE(e){try{return uE(localStorage.getItem(lE(e)))}catch{return null}}function lE(e){return tE+e}function uE(e){if(!e)return null;try{return dE(JSON.parse(e))}catch{return null}}function dE(e){if(!e||typeof e!=`object`)return null;let t=e,n=typeof t.piboSessionId==`string`?t.piboSessionId.trim():``;return n?{bindingId:typeof t.bindingId==`string`?t.bindingId:void 0,piboSessionId:n,installed:t.installed!==!1,active:t.active===!0,toolbarExpanded:t.toolbarExpanded===!0,mode:typeof t.mode==`string`?t.mode:void 0,reason:typeof t.reason==`string`?t.reason:void 0,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:void 0}:null}function fE(e){try{let t=localStorage.getItem(eE+e);if(!t)return[];let n=JSON.parse(t);return Array.isArray(n)?n.filter(e=>typeof e==`string`&&!!e.trim()).slice(0,5):[]}catch{return[]}}function pE(e,t){try{let n=eE+e,r=[...new Set(t.filter(e=>e.trim()))].slice(0,5);r.length?localStorage.setItem(n,JSON.stringify(r)):localStorage.removeItem(n)}catch{}}function mE(){try{return localStorage.getItem(nE)===`true`}catch{return!1}}function hE(e){try{localStorage.setItem(nE,String(e))}catch{}}function gE({piboSessionId:e,annotations:t,selectedIds:n,loading:r,error:i,collapsed:a,onRefresh:o,onToggle:s,onClear:c,onCollapse:l,onClose:u}){return e?(0,M.jsxs)(`section`,{className:`border-t border-slate-800 bg-[#101d22] px-3 py-2 sm:px-4`,"data-pibo-debug":`web-annotations-session-panel`,"data-pibo-session-id":e,children:[(0,M.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,M.jsxs)(`div`,{className:`min-w-0`,children:[(0,M.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,M.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Web annotations`}),(0,M.jsx)(`span`,{className:`rounded-sm border border-slate-700 px-1.5 py-0.5 text-[10px] text-slate-400`,children:t.length}),n.length?(0,M.jsxs)(`span`,{className:`rounded-sm border border-[#11a4d4]/50 px-1.5 py-0.5 text-[10px] text-[#11a4d4]`,children:[n.length,` attached`]}):null]}),a?null:(0,M.jsx)(`div`,{className:`text-[11px] text-slate-500`,children:`Global annotation list. Selected attachments are remembered per session.`})]}),(0,M.jsxs)(`div`,{className:`ml-auto flex shrink-0 items-center gap-1`,children:[(0,M.jsx)(`button`,{type:`button`,onClick:o,disabled:r,title:`Refresh annotations`,"aria-label":`Refresh annotations`,className:`inline-flex h-8 w-8 items-center justify-center rounded-sm border border-slate-700 text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:opacity-50 sm:h-7 sm:w-7`,"data-pibo-debug":`web-annotations-refresh`,children:(0,M.jsx)(ut,{size:12,className:r?`animate-spin`:void 0})}),(0,M.jsx)(`button`,{type:`button`,onClick:c,disabled:r||!t.length,title:`Clear visible annotations`,"aria-label":`Clear visible annotations`,className:`inline-flex h-8 w-8 items-center justify-center rounded-sm border border-slate-700 text-slate-300 hover:border-red-500 hover:text-red-300 disabled:opacity-50 sm:h-7 sm:w-7`,children:(0,M.jsx)(ht,{size:12})}),(0,M.jsx)(`button`,{type:`button`,onClick:l,title:a?`Expand annotations panel`:`Collapse annotations panel`,"aria-label":a?`Expand annotations panel`:`Collapse annotations panel`,className:`inline-flex h-8 w-8 items-center justify-center rounded-sm border border-slate-700 text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] sm:h-7 sm:w-7`,children:a?(0,M.jsx)(Le,{size:12}):(0,M.jsx)(Fe,{size:12})}),(0,M.jsx)(`button`,{type:`button`,onClick:u,title:`Hide annotations panel`,"aria-label":`Hide annotations panel`,className:`inline-flex h-8 w-8 items-center justify-center rounded-sm border border-slate-700 text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] sm:h-7 sm:w-7`,children:(0,M.jsx)(vt,{size:12})})]})]}),a?null:i?(0,M.jsx)(`div`,{className:`rounded-sm border border-red-900 bg-red-950/40 px-3 py-2 text-xs text-red-200`,"data-pibo-debug":`web-annotations-error`,children:TE(i,220)}):r&&!t.length?(0,M.jsx)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0e1116] px-3 py-2 text-xs text-slate-400`,"data-pibo-debug":`web-annotations-loading`,children:`Loading annotations…`}):t.length?(0,M.jsx)(`div`,{className:`mt-2 grid max-h-[min(40svh,18rem)] grid-cols-1 gap-2 overflow-y-auto pr-1 sm:max-h-56 sm:grid-cols-[repeat(auto-fill,minmax(16rem,1fr))]`,"data-pibo-debug":`web-annotations-list`,children:t.map(e=>{let t=n.includes(e.id);return(0,M.jsxs)(`div`,{"data-pibo-debug":`web-annotation-chip`,"data-web-annotation-id":e.id,"data-web-annotation-session-id":e.piboSessionId,"data-web-annotation-selected":t?`true`:`false`,className:`min-w-0 rounded-sm border px-3 py-2 text-xs ${t?`border-[#11a4d4] bg-[#11a4d4]/10`:`border-slate-800 bg-[#0e1116]`}`,children:[(0,M.jsxs)(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[(0,M.jsxs)(`span`,{className:`min-w-0 truncate font-mono text-[11px] text-slate-500`,children:[e.status,` · `,e.targetKind]}),(0,M.jsxs)(`button`,{type:`button`,onClick:()=>s(e.id),className:`inline-flex h-8 shrink-0 items-center gap-1 rounded-sm border px-2 text-[11px] sm:h-6 sm:px-1.5 ${t?`border-[#11a4d4] text-[#11a4d4]`:`border-slate-700 text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:[t?(0,M.jsx)(vt,{size:11}):(0,M.jsx)(lt,{size:11}),` `,t?`Detach`:`Attach`]})]}),(0,M.jsx)(`div`,{className:`truncate text-slate-200`,title:e.primaryTarget||e.label||e.selector||e.id,children:TE(e.primaryTarget||e.label||e.selector||e.id,120)}),e.piboContext?(0,M.jsx)(`div`,{className:`truncate font-mono text-[11px] text-[#11a4d4]`,title:e.piboContext,children:TE(e.piboContext,140)}):null,(0,M.jsx)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:e.url,children:wE(e.url)}),(0,M.jsx)(`div`,{className:`mt-1 line-clamp-2 text-slate-400`,title:e.note,children:TE(e.note,180)}),(0,M.jsx)(`div`,{className:`mt-1 text-[11px] text-slate-600`,children:EE(e.createdAt)})]},e.id)})}):(0,M.jsx)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0e1116] px-3 py-2 text-xs text-slate-500`,"data-pibo-debug":`web-annotations-empty`,children:`No open annotations for this session.`})]}):null}function _E({piboSessionId:e,piboRoomId:t,disabled:n,panelVisible:r,onShowPanel:i,onHidePanel:a,onError:o}){let[s,c]=(0,v.useState)(!1),[l,u]=(0,v.useState)(``),[d,f]=(0,v.useState)(()=>aE()),[p,m]=(0,v.useState)([]),[h,g]=(0,v.useState)(`idle`),[_,y]=(0,v.useState)(!1),[b,x]=(0,v.useState)(null);(0,v.useEffect)(()=>{n&&c(!1)},[n]),(0,v.useEffect)(()=>{oE(d)},[d]);let S=async()=>{if(e){g(`loading`),x(null);try{m((await vb(d)).targets.filter(e=>e.type===`page`||e.attachable)),g(`loaded`)}catch(e){let t=SE(e,`CDP unavailable`);m([]),g(`error`),x({kind:`error`,message:t}),o(t)}}},C=async n=>{if(!e)throw Error(`No active session context`);return bb(n.binding.id,yE({piboSessionId:e,piboRoomId:t,cdpUrl:d,annotationShortcut:sE()}))},w=async()=>{if(!(!e||_)){i(),y(!0),x({kind:`info`,message:`Injecting annotation overlay into this Pibo page…`});try{let n=await yb({piboSessionId:e,piboRoomId:t,url:window.location.href,title:document.title,sameOrigin:!0,annotationShortcut:sE()});if(!n.overlay)throw Error(`Overlay config missing from same-origin binding response`);await xE(n.overlay),x({kind:`success`,message:`Annotation overlay is ready on this Pibo page. Open the overlay controls or use the shortcut to start annotating.`}),o(null)}catch(e){let t=SE(e,`Current-page annotation failed`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}}},T=async()=>{if(!e||_)return;i();let n=l.trim();if(!n){x({kind:`error`,message:`URL is required`});return}if(bE(n)){let e=`That looks like a CDP endpoint. Put it in CDP URL, and put the page you want to annotate in Annotate URL.`;x({kind:`error`,message:e}),o(e);return}y(!0),x({kind:`info`,message:`Opening target and injecting overlay…`});try{let r=await yb(yE({piboSessionId:e,piboRoomId:t,url:n,cdpUrl:d})),i=await C(r);x({kind:`success`,message:`Annotation overlay injected for ${CE(i.target??r.target,i.binding.url)}`}),u(``),o(null)}catch(e){let t=SE(e,`Annotation failed`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}},E=async n=>{if(!(!e||_)){i(),y(!0),x({kind:`info`,message:`Binding selected target and injecting overlay…`});try{let r=await C(await yb(yE({piboSessionId:e,piboRoomId:t,targetId:n.id,cdpUrl:d})));x({kind:`success`,message:`Annotation overlay injected for ${CE(r.target??n,r.binding.url)}`}),o(null)}catch(e){let t=SE(e,n.attachable?`Target annotation failed`:`Target not attachable`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}}};return(0,M.jsxs)(`div`,{className:`relative`,"data-pibo-debug":`web-annotations-entry`,"data-pibo-session-id":e??void 0,children:[(0,M.jsx)(vE,{onClick:()=>{n||(c(e=>!e),r||i())},title:n?`Select an active session to annotate a web page`:r?`Web Annotations`:`Show Web Annotations`,ariaLabel:`Web Annotations`,active:s||r,children:(0,M.jsx)(De,{size:14})}),s&&!n?(0,M.jsxs)(`div`,{className:`fixed inset-x-2 bottom-3 z-40 max-h-[calc(100svh-1.5rem)] overflow-y-auto rounded-sm border border-slate-700 bg-[#0e1116] p-3 text-sm shadow-xl sm:absolute sm:inset-auto sm:right-0 sm:top-full sm:bottom-auto sm:mt-2 sm:w-[min(420px,calc(100vw-24px))] sm:max-h-[calc(100svh-5rem)]`,role:`dialog`,"aria-label":`Web Annotations`,children:[(0,M.jsxs)(`div`,{className:`mb-2 flex items-start justify-between gap-3`,children:[(0,M.jsxs)(`div`,{children:[(0,M.jsx)(`div`,{className:`text-xs font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Web Annotations`}),(0,M.jsx)(`div`,{className:`mt-1 text-xs text-slate-500`,children:`Start an inactive overlay for this Pibo page, or bind a CDP target for external pages.`})]}),(0,M.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,M.jsx)(`button`,{type:`button`,onClick:r?a:i,className:`rounded-sm p-1 text-slate-500 hover:bg-slate-800 hover:text-slate-200`,"aria-label":r?`Hide annotation list`:`Show annotation list`,title:r?`Hide annotation list`:`Show annotation list`,children:(0,M.jsx)(ft,{size:14})}),(0,M.jsx)(`button`,{type:`button`,onClick:()=>c(!1),className:`rounded-sm p-1 text-slate-500 hover:bg-slate-800 hover:text-slate-200`,"aria-label":`Close Web Annotations panel`,children:(0,M.jsx)(vt,{size:14})})]})]}),(0,M.jsx)(`button`,{type:`button`,onClick:()=>void w(),disabled:_,className:`mb-3 h-10 w-full rounded-sm bg-emerald-600 px-3 text-xs font-medium text-white hover:bg-emerald-500 disabled:opacity-50 sm:h-9`,"data-pibo-debug":`web-annotations-current-page`,children:`Annotate this Pibo page`}),(0,M.jsx)(`label`,{className:`mb-2 block text-[11px] font-bold uppercase tracking-wider text-slate-500`,htmlFor:`web-annotation-url`,children:`Annotate URL via CDP`}),(0,M.jsxs)(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-[1fr_auto]`,children:[(0,M.jsx)(`input`,{id:`web-annotation-url`,value:l,onChange:e=>u(e.target.value),onKeyDown:e=>{e.key===`Enter`&&T()},placeholder:`http://localhost:5173`,disabled:_,className:`h-10 min-w-0 rounded-sm border border-slate-700 bg-[#151f24] px-2 text-base text-slate-100 outline-none focus:border-[#11a4d4] disabled:opacity-60 sm:h-9 sm:text-xs`}),(0,M.jsx)(`button`,{type:`button`,onClick:()=>void T(),disabled:_||!l.trim(),className:`h-10 rounded-sm bg-[#11a4d4] px-3 text-xs font-medium text-white disabled:opacity-50 sm:h-9`,children:`Annotate`})]}),(0,M.jsx)(`label`,{className:`mt-3 mb-1 block text-[11px] font-bold uppercase tracking-wider text-slate-500`,htmlFor:`web-annotation-cdp-url`,children:`CDP URL (optional)`}),(0,M.jsx)(`input`,{id:`web-annotation-cdp-url`,value:d,onChange:e=>f(e.target.value),placeholder:`Use gateway default`,disabled:_,className:`h-10 w-full rounded-sm border border-slate-800 bg-[#151f24] px-2 font-mono text-base text-slate-300 outline-none focus:border-[#11a4d4] disabled:opacity-60 sm:h-8 sm:text-[11px]`}),(0,M.jsxs)(`div`,{className:`mt-3 flex items-center justify-between gap-2`,children:[(0,M.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-slate-500`,children:`Existing targets`}),(0,M.jsxs)(`button`,{type:`button`,onClick:()=>void S(),disabled:_||h===`loading`,className:`inline-flex h-7 items-center gap-1 rounded-sm border border-slate-700 px-2 text-[11px] text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:opacity-50`,children:[(0,M.jsx)(ut,{size:12,className:h===`loading`?`animate-spin`:void 0}),` Refresh`]})]}),(0,M.jsxs)(`div`,{className:`mt-2 max-h-[min(34svh,14rem)] overflow-auto rounded-sm border border-slate-800 sm:max-h-56`,children:[h===`idle`?(0,M.jsx)(`div`,{className:`px-3 py-3 text-xs text-slate-500`,children:`Refresh to list reachable browser targets.`}):null,h===`loading`?(0,M.jsx)(`div`,{className:`px-3 py-3 text-xs text-slate-400`,children:`Loading targets…`}):null,h===`loaded`&&!p.length?(0,M.jsx)(`div`,{className:`px-3 py-3 text-xs text-slate-500`,children:`No attachable browser targets found.`}):null,p.map(e=>(0,M.jsxs)(`div`,{className:`grid grid-cols-1 gap-2 border-b border-slate-800 px-3 py-2 last:border-b-0 sm:grid-cols-[1fr_auto]`,children:[(0,M.jsxs)(`div`,{className:`min-w-0`,children:[(0,M.jsx)(`div`,{className:`truncate text-xs text-slate-200`,title:e.title||e.url,children:TE(e.title||`Untitled target`,120)}),(0,M.jsx)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:e.url,children:TE(e.url||e.id,160)})]}),(0,M.jsx)(`button`,{type:`button`,onClick:()=>void E(e),disabled:_||!e.attachable,title:e.attachable?`Attach selected target`:`Target is not attachable`,className:`h-9 rounded-sm border border-slate-700 px-2 text-[11px] text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:opacity-40 sm:h-8`,children:`Attach`})]},e.id))]}),b?(0,M.jsx)(`div`,{className:`mt-2 rounded-sm border px-2 py-2 text-xs ${b.kind===`error`?`border-red-900 bg-red-950/40 text-red-200`:b.kind===`success`?`border-emerald-900/60 bg-emerald-950/30 text-emerald-300`:`border-slate-700 bg-[#151f24] text-slate-300`}`,children:b.message}):null]}):null]})}function vE({title:e,ariaLabel:t,active:n,onClick:r,children:i}){return(0,M.jsx)(`button`,{type:`button`,onClick:r,title:e,"aria-label":t,className:`h-8 w-8 inline-flex items-center justify-center border rounded-sm transition-colors ${n?`border-[#11a4d4] bg-[#11a4d4]/10 text-[#11a4d4]`:`border-slate-700 text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:i})}function yE(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e&&e.trim()))}function bE(e){try{let t=new URL(e);return t.port===`56663`||t.pathname.startsWith(`/json/`)}catch{return!1}}function xE(e){return new Promise((t,n)=>{let r=window;try{r.__piboWebAnnotations?.remove?.(),r.__piboWebAnnotationConfig=e;let i=document.createElement(`script`);i.src=`/apps/web-annotations/overlay.js?ts=${Date.now()}`,i.async=!0,i.onload=()=>t(),i.onerror=()=>n(Error(`Could not load Web Annotation overlay script`)),document.head.appendChild(i)}catch(e){n(e)}})}function SE(e,t){let n=DE(e);return!n||n===`undefined`?t:/target.*not found|selected cdp target/i.test(n)?`Target not found: ${n}`:/inject|overlay|evaluation/i.test(n)?`Injection failed: ${n}`:/cdp endpoint.*is unreachable|failed to fetch|fetch failed|chrome target discovery|cdp unavailable|econnrefused|connect/i.test(n)?`CDP unavailable: ${n}`:`${t}: ${n}`}function CE(e,t){let n=e?.url||t||e?.title||`target`;return wE(e?.title||n)}function wE(e){try{let t=new URL(e);return`${t.host}${t.pathname===`/`?``:t.pathname}`}catch{return TE(e,80)}}function TE(e,t){return e.length>t?`${e.slice(0,Math.max(0,t-1))}…`:e}function EE(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{dateStyle:`short`,timeStyle:`short`})}function DE(e){return e instanceof Error?e.message:String(e)}function OE(e){return!!e.workflowRunId||e.state===`workflow`||e.workflowId!==`simple-chat`}function kE(e,t){return{workflowId:e.workflowId,state:jE(e,t),...e.workflowRunId?{workflowRunId:e.workflowRunId}:{}}}function AE({summary:e}){return(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(`span`,{className:`text-slate-600`,children:`·`}),(0,M.jsxs)(`span`,{className:`min-w-0 max-w-52 truncate rounded border border-[#11a4d4]/35 bg-[#11a4d4]/10 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-[#11a4d4]`,title:e.workflowId,children:[`workflow `,e.workflowId]}),(0,M.jsxs)(`span`,{className:ME(e.state),children:[`state `,e.state]}),e.workflowRunId?(0,M.jsxs)(`span`,{className:`min-w-0 max-w-40 truncate rounded border border-slate-700 bg-slate-900/40 px-1.5 py-0.5 text-[10px] text-slate-400`,title:e.workflowRunId,children:[`run `,NE(e.workflowRunId)]}):null]})}function jE(e,t){return e.archived?`archived`:e.state&&e.state!==`workflow`?e.state.replace(/_/g,` `):t===`running`?`running`:t===`error`?`failed`:e.state?e.state.replace(/_/g,` `):e.workflowRunId?`workflow`:e.kind}function ME(e,t=!1){let n=e.toLowerCase(),r=`shrink-0 rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide`;return t?`${r} border-slate-700 text-slate-500`:n.includes(`failed`)||n.includes(`error`)?`${r} border-red-500/40 text-red-300 bg-red-500/10`:n.includes(`waiting`)?`${r} border-amber-500/40 text-amber-300 bg-amber-500/10`:n.includes(`complete`)||n.includes(`done`)?`${r} border-emerald-500/40 text-emerald-300 bg-emerald-500/10`:`${r} border-[#11a4d4]/40 text-[#11a4d4] bg-[#11a4d4]/10`}function NE(e){return e.length>18?`${e.slice(0,10)}…${e.slice(-6)}`:e}function PE({title:e,roomLabel:t,headerPiboSessionId:n,piboSessionId:r,piboRoomId:i,webAnnotationsDisabled:a,webAnnotationsPanelRendered:o,workflowHeader:s,sessionViewId:c,sessionViews:l,currentSessionView:u,allowedSessionViewIds:d,extraViewTabs:f,activeViewId:p,showRawEvents:m,showThinking:h,expandThinking:g,onShowWebAnnotationsPanel:_,onHideWebAnnotationsPanel:y,onSelectSessionView:b,onToggleRawEvents:x,onToggleThinking:S,onToggleExpandThinking:C,onError:w}){let[T,E]=(0,v.useState)(null),ee=(0,v.useRef)(void 0),D=T===n,O=p??c,te=(0,v.useMemo)(()=>d?new Set(d):null,[d]);(0,v.useEffect)(()=>()=>{ee.current&&window.clearTimeout(ee.current)},[]);let ne=()=>{n&&(BT(n).catch(()=>void 0),E(n),ee.current&&window.clearTimeout(ee.current),ee.current=window.setTimeout(()=>E(null),900))};return(0,M.jsxs)(`div`,{className:`h-14 px-4 bg-[#151f24] border-b border-slate-800 flex items-center justify-between max-[980px]:h-auto max-[980px]:flex-wrap max-[980px]:py-2 max-[980px]:gap-2`,children:[(0,M.jsxs)(`div`,{className:`min-w-0`,children:[(0,M.jsx)(`h1`,{className:`text-base font-semibold truncate`,children:e}),(0,M.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 font-mono text-[11px] text-slate-500`,children:[(0,M.jsx)(`span`,{className:`truncate`,children:t}),n?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(`span`,{className:`text-slate-600`,children:`·`}),(0,M.jsx)(`button`,{type:`button`,onMouseDown:e=>e.preventDefault(),onClick:()=>void ne(),title:D?`Copied Pibo session ID`:`Copy Pibo session ID`,"aria-label":D?`Copied Pibo session ID`:`Copy Pibo session ID`,className:`min-w-0 max-w-48 truncate rounded-sm px-1 font-mono underline-offset-2 transition-colors duration-150 focus:outline-none focus:ring-1 focus:ring-[#11a4d4] ${D?`bg-emerald-500/15 text-emerald-300 ring-1 ring-emerald-400/50`:`text-slate-400 hover:text-[#11a4d4] hover:underline`}`,children:n})]}):null,s?(0,M.jsx)(AE,{summary:s}):null]})]}),(0,M.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,M.jsx)(_E,{piboSessionId:r,piboRoomId:i,disabled:a,panelVisible:o,onShowPanel:_,onHidePanel:y,onError:w}),(0,M.jsxs)(`div`,{className:`flex items-center rounded-sm border border-slate-700 bg-[#0e1116] p-0.5`,children:[l.map(e=>{let t=!!(te&&!te.has(e.id));return(0,M.jsx)(`button`,{type:`button`,onClick:()=>{t||b(e.id)},disabled:t,title:t?`Project session routing uses the ${u.label} view for this session kind.`:e.description??e.label,"aria-label":t?`${e.label} view unavailable for this Project session kind`:`Switch to ${e.label} view`,className:`min-w-20 px-2.5 py-1 text-[11px] font-bold tracking-wide max-[980px]:min-w-0 max-[980px]:px-1.5 disabled:cursor-not-allowed disabled:text-slate-600 ${O===e.id?`bg-[#11a4d4]/10 text-[#11a4d4]`:`text-slate-400 hover:text-[#11a4d4] disabled:hover:text-slate-600`}`,children:e.label},e.id)}),f?.map(e=>(0,M.jsx)(`button`,{type:`button`,onClick:()=>{e.disabled||e.onSelect()},disabled:e.disabled,title:e.description??e.label,"aria-label":e.disabled?`${e.label} view unavailable`:`Switch to ${e.label} view`,className:`min-w-20 px-2.5 py-1 text-[11px] font-bold tracking-wide max-[980px]:min-w-0 max-[980px]:px-1.5 disabled:cursor-not-allowed disabled:text-slate-600 ${e.active??O===e.id?`bg-[#11a4d4]/10 text-[#11a4d4]`:`text-slate-400 hover:text-[#11a4d4] disabled:hover:text-slate-600`}`,children:e.label},e.id))]}),(0,M.jsx)(FE,{onClick:x,title:m?`Hide Raw Events`:`Show Raw Events`,ariaLabel:m?`Hide Raw Events`:`Show Raw Events`,active:m,children:(0,M.jsx)(Ae,{size:14})}),(0,M.jsx)(FE,{onClick:S,title:h?`Hide Thinking`:`Show Thinking`,ariaLabel:h?`Hide Thinking`:`Show Thinking`,active:h,children:h?(0,M.jsx)(ke,{size:14}):(0,M.jsx)(Je,{size:14})}),h?(0,M.jsx)(FE,{onClick:C,title:g?`Collapse Thinking`:`Expand Thinking`,ariaLabel:g?`Collapse Thinking`:`Expand Thinking`,active:g,children:g?(0,M.jsx)(Fe,{size:14}):(0,M.jsx)(Le,{size:14})}):null]})]})}function FE({title:e,ariaLabel:t,active:n,onClick:r,children:i}){return(0,M.jsx)(`button`,{type:`button`,onClick:r,title:e,"aria-label":t,className:`h-8 w-8 inline-flex items-center justify-center border rounded-sm transition-colors ${n?`border-[#11a4d4] bg-[#11a4d4]/10 text-[#11a4d4]`:`border-slate-700 text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:i})}function IE(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&LE(e,n)){e.count+=1,e.createdAt=n.createdAt,e.payload={...BE(e.payload)?e.payload:{},text:`${RE(e.payload)}${RE(n.payload)}`};continue}t.push({...n,count:1})}return t}function LE(e,t){if(e.type!==t.type||e.type!==`assistant_delta`&&e.type!==`thinking_delta`&&e.type!==`TEXT_MESSAGE_CONTENT`&&e.type!==`REASONING_MESSAGE_CONTENT`)return!1;let n=BE(e.payload)?e.payload:{},r=BE(t.payload)?t.payload:{};return zE(n)===zE(r)}function RE(e){return BE(e)?typeof e.text==`string`?e.text:typeof e.delta==`string`?e.delta:``:``}function zE(e){return e.eventId??e.messageId}function BE(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function VE({traceView:e,eventLimit:t,isFetching:n,visible:r,onLoadOlder:i}){let a=(0,v.useMemo)(()=>r?IE(e?.rawEvents??[]):[],[e?.rawEvents,r]);return r?(0,M.jsxs)(`aside`,{className:`min-h-0 overflow-auto bg-[#0e1116] border-l border-slate-800 max-[980px]:hidden`,children:[(0,M.jsx)(`div`,{className:`h-11 px-3 border-b border-slate-800 flex items-center text-xs font-bold uppercase tracking-wider`,children:`Raw Events`}),(0,M.jsxs)(`div`,{className:`p-3 flex flex-col gap-2`,children:[e&&a.length>=t?(0,M.jsx)(`button`,{type:`button`,onClick:i,disabled:n,className:`mb-1 rounded-sm border border-slate-700 px-2 py-1 text-xs text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:opacity-60`,children:n?`Loading raw events…`:`Load older raw events (${a.length})`}):null,a.slice(-t).reverse().map(e=>(0,M.jsxs)(`div`,{className:`border-l-2 border-[#11a4d4] bg-[#151f24] p-2`,children:[(0,M.jsxs)(`div`,{className:`flex items-center justify-between gap-2 text-[#11a4d4] font-mono text-[11px] mb-1`,children:[(0,M.jsx)(`span`,{children:e.type}),e.count>1?(0,M.jsxs)(`span`,{className:`text-slate-500`,children:[`x`,e.count]}):null]}),(0,M.jsx)(Sc,{value:e.payload,showControls:!1})]},e.id))]})]}):null}function HE({traceView:e,eventLimit:t,isFetching:n,onLoadOlder:r}){if(!e?.hasOlderEvents)return null;let i=Math.min(e.eventLimit??t,e.eventCount??t),a=e.eventCount??`many`;return(0,M.jsx)(`div`,{className:`border-b border-slate-800 bg-[#101d22] px-4 py-2 text-center`,children:(0,M.jsx)(`button`,{type:`button`,onClick:r,disabled:n,className:`rounded-sm border border-slate-700 px-3 py-1 text-xs text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:opacity-60`,children:n?`Loading history…`:`Load older trace history (${i} of ${a} events)`})})}function UE({selectedPiboSessionId:e,selectedRoomId:t,fallbackRoomId:n,sessionViewId:r,loadingTrace:i,traceError:a,showRawEvents:o,currentTraceView:s,traceEventLimit:c,rawEventLimit:l,tracePageFetching:u,onLoadOlderTracePage:d,onLoadMoreRawEvents:f,headerProps:p,projectSessionCreatePanel:m,workflowStartPanel:h,projectModulePanel:g,currentSessionView:_,sessionViewProps:v,webAnnotationsPanelRendered:y,webAnnotationsPanelProps:b,composerProps:x}){return(0,M.jsxs)(M.Fragment,{children:[(0,M.jsxs)(`main`,{"data-pibo-debug":`chat-shell`,"data-pibo-session-id":e??void 0,"data-pibo-room-id":t??n??void 0,"data-pibo-view-id":r,"data-pibo-state":i?`loading`:a?`error`:e?`ready`:`empty`,className:`min-h-0 flex flex-col`,children:[(0,M.jsx)(PE,{...p}),m?(0,M.jsx)(`div`,{className:`border-b border-slate-800 bg-[#101d22] px-4 py-3`,children:m}):null,h?(0,M.jsx)(`div`,{className:`border-b border-slate-800 bg-[#101d22] px-4 py-3`,children:h}):null,(0,M.jsx)(HE,{traceView:s,eventLimit:c,isFetching:u,onLoadOlder:()=>d(s?.nextBeforeSequence)}),g||(a&&!s?(0,M.jsx)(`div`,{className:`min-h-0 flex-1 p-4 text-sm text-red-200`,children:a}):_.render(v)),y?(0,M.jsx)(gE,{...b}):null,(0,M.jsx)(HT,{...x})]}),(0,M.jsx)(VE,{traceView:s,eventLimit:l,isFetching:u,visible:o,onLoadOlder:f})]})}function WE(e){let t=new Map;if(YE(e.nodes,t),!t.size)return e;let{nodes:n,changed:r}=XE(e.nodes,t);return r?{...e,nodes:n}:e}function GE(e){return e.some(JE)}function KE(e){let t=new Map;return QE(e,e=>{if(e.type!==`user.message`||!e.entryId)return;let n=$E(e),r=t.get(n);r?r.push(e.entryId):t.set(n,[e.entryId])}),t}function qE(e,t){if(!t.size)return;let n=new Map;QE(e,e=>{if(e.type!==`user.message`||e.entryId)return;let r=$E(e),i=t.get(r);if(!i?.length)return;let a=n.get(r)??0,o=i[a];o&&(e.entryId=o,n.set(r,a+1))})}function JE(e){let t=e.payload;return!!(t&&typeof t==`object`&&!Array.isArray(t)&&`type`in t&&t.type===`message_queued`&&`source`in t&&t.source===`user`&&`text`in t&&typeof t.text==`string`)}function YE(e,t){for(let n of e){if(n.type===`user.message`&&!ZE(n)){let e=$E(n);e&&t.set(e,(t.get(e)??0)+1)}YE(n.children,t)}}function XE(e,t){let n=!1,r=[];for(let i of e){if(ZE(i)){let e=$E(i),r=e?t.get(e)??0:0;if(r>0){t.set(e,r-1),n=!0;continue}}let e=XE(i.children,t);n||=e.changed,r.push(e.changed?{...i,children:e.nodes}:i)}return{nodes:n?r:e,changed:n}}function ZE(e){return e.type===`user.message`?e.source===`event-log`&&e.id.startsWith(`event:message_queued:`)?!0:[e.id,e.stableKey,e.eventId].filter(e=>typeof e==`string`).some(e=>e.startsWith(`optimistic:user-message:`)||e.includes(`:optimistic:user-message:`)):!1}function QE(e,t){for(let n of e)t(n),QE(n.children,t)}function $E(e){return typeof e.output==`string`?e.output:typeof e.summary==`string`?e.summary:``}function eD({selectedPiboSessionId:e,reconciledBaseTraceView:t,liveTraceOverlay:n,selectedSessionStatus:r,persistedUserMessageIndexForBaseTrace:i,now:a}){if(!e||t?.piboSessionId!==e)return{traceView:null};let o=n?.piboSessionId===e?n.events:[];if(!o.length)return{traceView:t};let s=a?.(),c=wS(t,o,r??`idle`),l=GE(o);return l&&qE(c.nodes,i),{traceView:l?WE(c):c,liveTraceComputeDurationMs:s!==void 0&&a?a()-s:void 0}}function tD(e,t){for(let n of e)t(n),tD(n.children,t)}function nD(e){return typeof e.output==`string`?e.output:typeof e.summary==`string`?e.summary:``}function rD(e){if(!e)return;let t=0;return tD(e.nodes,e=>{e.type===`assistant.message`&&(t+=nD(e).length)}),t}function iD({selectedPiboSessionId:e,baseTraceView:t,liveTraceOverlay:n,selectedSessionStatus:r}){let i=(0,v.useMemo)(()=>t?WE(t):null,[t]),a=(0,v.useMemo)(()=>i?KE(i.nodes):new Map,[i]),o=(0,v.useMemo)(()=>eD({selectedPiboSessionId:e,reconciledBaseTraceView:i,liveTraceOverlay:n,selectedSessionStatus:r,persistedUserMessageIndexForBaseTrace:a,now:pv()?()=>performance.now():void 0}),[n,e,r,i,a]),s=o.traceView;return(0,v.useEffect)(()=>{!e||!s?.piboSessionId||!pv()||(Sv(s.piboSessionId,{overlayEventCount:n?.piboSessionId===s.piboSessionId?n.events.length:0,traceBaseOutputLength:rD(t),currentOutputLength:rD(s)}),o.liveTraceComputeDurationMs!==void 0&&yv(s.piboSessionId,o.liveTraceComputeDurationMs))},[t,o.liveTraceComputeDurationMs,s,n,e]),(0,v.useEffect)(()=>{let e=()=>{!s?.piboSessionId||!Ny()||Ly(s.piboSessionId,`tab:${document.visibilityState}`,s.nodes,{traceVersion:s.version,latestStreamId:s.latestStreamId,lastRawEventId:s.rawEvents.at(-1)?.id})};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[s]),s}var aD=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},oD=new class extends aD{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},sD={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},cD=new class{#e=sD;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function lD(e){setTimeout(e,0)}var uD=typeof window>`u`||`Deno`in globalThis;function dD(){}function fD(e){return typeof e==`number`&&e>=0&&e!==1/0}function pD(e,t){return Math.max(e+(t||0)-Date.now(),0)}function mD(e,t){return typeof e==`function`?e(t):e}function hD(e,t){return typeof e==`function`?e(t):e}var gD=Object.prototype.hasOwnProperty;function _D(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=yD(e)&&yD(t);if(!r&&!(bD(e)&&bD(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:gD.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=_D(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function vD(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function yD(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function bD(e){if(!xD(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!xD(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function xD(e){return Object.prototype.toString.call(e)===`[object Object]`}function SD(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:_D(e,t)}function CD(e,t){return typeof e==`function`?e(...t):!!e}var wD=(()=>{let e=()=>uD;return{isServer(){return e()},setIsServer(t){e=t}}})();function TD(){let e,t,n=new Promise((n,r)=>{e=n,t=r});n.status=`pending`,n.catch(()=>{});function r(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.resolve=t=>{r({status:`fulfilled`,value:t}),e(t)},n.reject=e=>{r({status:`rejected`,reason:e}),t(e)},n}var ED=lD;function DD(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=ED,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var OD=DD(),kD=new class extends aD{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function AD(e){return(e??`online`)===`online`?kD.isOnline():!0}function jD(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:AD(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}var MD=class extends aD{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=TD(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),PD(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return FD(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return FD(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof hD(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!vD(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&ID(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||hD(this.options.enabled,this.#t)!==hD(t.enabled,this.#t)||mD(this.options.staleTime,this.#t)!==mD(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||hD(this.options.enabled,this.#t)!==hD(t.enabled,this.#t)||i!==this.#p)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return RD(this,n)&&(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),n===`promise`&&(this.trackProp(`data`),!this.options.experimental_prefetchInRender&&this.#o.status===`pending`&&this.#o.reject(Error(`experimental_prefetchInRender feature flag is not enabled`))),Reflect.get(e,n))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(dD)),t}#g(){this.#b();let e=mD(this.options.staleTime,this.#t);if(wD.isServer()||this.#r.isStale||!fD(e))return;let t=pD(this.#r.dataUpdatedAt,e)+1;this.#d=cD.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return(typeof this.options.refetchInterval==`function`?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#x(),this.#p=e,!(wD.isServer()||hD(this.options.enabled,this.#t)===!1||!fD(this.#p)||this.#p===0)&&(this.#f=cD.setInterval(()=>{(this.options.refetchIntervalInBackground||oD.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(cD.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(cD.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&PD(e,t),o=i&&ID(e,n,t,r);(a||o)&&(l={...l,...jD(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#u?.state.data,this.#u):t.placeholderData,e!==void 0&&(m=`success`,d=SD(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h)if(i&&d===a?.data&&t.select===this.#c)d=this.#l;else try{this.#c=t.select,d=t.select(d),d=SD(i?.data,d,t),this.#l=d,this.#s=null}catch(e){this.#s=e}this.#s&&(f=this.#s,d=this.#l,p=Date.now(),m=`error`);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0,x={status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:LD(e,t),refetch:this.refetch,promise:this.#o,isEnabled:hD(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let t=x.data!==void 0,r=x.status===`error`&&!t,i=e=>{r?e.reject(x.error):t&&e.resolve(x.data)},a=()=>{i(this.#o=x.promise=TD())},o=this.#o;switch(o.status){case`pending`:e.queryHash===n.queryHash&&i(o);break;case`fulfilled`:(r||x.data!==o.value)&&a();break;case`rejected`:(!r||x.error!==o.reason)&&a();break}}return x}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#u=this.#t),!vD(t,e)&&(this.#r=t,this.#C({listeners:(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#m.size)return!0;let r=new Set(n??this.#m);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})()}))}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#C(e){OD.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function ND(e,t){return hD(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status===`error`&&hD(t.retryOnMount,e)===!1)}function PD(e,t){return ND(e,t)||e.state.data!==void 0&&FD(e,t,t.refetchOnMount)}function FD(e,t,n){if(hD(t.enabled,e)!==!1&&mD(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&LD(e,t)}return!1}function ID(e,t,n,r){return(e!==t||hD(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&LD(e,n)}function LD(e,t){return hD(t.enabled,e)!==!1&&e.isStaleByTime(mD(t.staleTime,e))}function RD(e,t){return!vD(e.getCurrentResult(),t)}var zD=v.createContext(void 0),BD=e=>{let t=v.useContext(zD);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},VD=v.createContext(!1),HD=()=>v.useContext(VD);VD.Provider;function UD(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var WD=v.createContext(UD()),GD=()=>v.useContext(WD),KD=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?CD(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},qD=e=>{v.useEffect(()=>{e.clearReset()},[e])},JD=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||CD(n,[e.error,r])),YD=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},XD=(e,t)=>e.isLoading&&e.isFetching&&!t,ZD=(e,t)=>e?.suspense&&t.isPending,QD=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function $D(e,t,n){let r=HD(),i=GD(),a=BD(n),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let s=a.getQueryCache().get(o.queryHash);o._optimisticResults=r?`isRestoring`:`optimistic`,YD(o),KD(o,i,s),qD(i);let c=!a.getQueryCache().get(o.queryHash),[l]=v.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&e.subscribed!==!1;if(v.useSyncExternalStore(v.useCallback(e=>{let t=d?l.subscribe(OD.batchCalls(e)):dD;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),v.useEffect(()=>{l.setOptions(o)},[o,l]),ZD(o,u))throw QD(o,l,i);if(JD({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,u),o.experimental_prefetchInRender&&!wD.isServer()&&XD(u,r)&&(c?QD(o,l,i):s?.promise)?.catch(dD).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?u:l.trackResult(u)}function eO(e,t){return $D(e,MD,t)}var tO=1e4,nO=30*6e4,rO=2e3;function iO(e){return[`chat`,`trace-summary`,e]}function aO(e,t={}){let n=t.pageSize??t.eventLimit??2e3;return[`chat`,`trace-page`,e,t.includeRawEvents?`raw`:`compact`,t.rawEventsLimit??80,n,t.beforeSequence===void 0?`tail`:String(t.beforeSequence)]}function oO(e,t){if(!e||e.piboSessionId!==t.piboSessionId)return e;let n=t.latestStreamId,r=cO(t),i=sO(t.nodes),a=e.events.filter(e=>{if(n!==void 0&&e.streamId!==void 0&&e.streamId<=n||JE(e)&&i.has(e.payload.text))return!1;let t=uO(e);return!t||!r.has(t)});return a.length?{...e,events:a}:null}function sO(e){let t=new Set;for(let n of e){if(n.type===`user.message`&&n.source===`transcript`){let e=dO(n);e&&t.add(e)}for(let e of sO(n.children))t.add(e)}return t}function cO(e){let t=new Set;for(let n of e.rawEvents){let e=uO(n);e&&t.add(e)}return lO(e.nodes,t),t}function lO(e,t){for(let n of e){if(n.type===`user.message`){let e=n.id.startsWith(`event:message_queued:`)?n.id.slice(21):void 0;e&&t.add(`${n.piboSessionId}:message_queued:${e}`),n.source===`transcript`&&n.entryId&&t.add(`${n.piboSessionId}:message_queued:${n.entryId}`)}n.eventId&&n.type===`assistant.message`&&(t.add(`${n.piboSessionId}:assistant_delta:${n.eventId}`),t.add(`${n.piboSessionId}:assistant_message:${n.eventId}`)),n.eventId&&n.type===`model.reasoning`&&(t.add(`${n.piboSessionId}:thinking_delta:${n.eventId}`),t.add(`${n.piboSessionId}:thinking_finished:${n.eventId}`)),lO(n.children,t)}}function uO(e){let t=e.payload;if(!t||typeof t!=`object`||Array.isArray(t))return;let n=`eventId`in t&&typeof t.eventId==`string`?t.eventId:e.eventId,r=`piboSessionId`in t&&typeof t.piboSessionId==`string`?t.piboSessionId:e.piboSessionId;if(!(!n||!r))return`${r}:${e.type}:${n}`}function dO(e){return typeof e.output==`string`?e.output:e.output&&typeof e.output==`object`&&`text`in e.output&&typeof e.output.text==`string`?e.output.text:``}function fO(e,t){if(e.piboSessionId!==t.piboSessionId)return e;let n=new Set,r=[...t.nodes,...e.nodes].filter(e=>n.has(e.id)?!1:(n.add(e.id),!0)),i=new Set,a=[...t.rawEvents,...e.rawEvents].filter(e=>{let t=e.id||`${e.eventSequence??``}:${e.type}:${e.createdAt}`;return i.has(t)?!1:(i.add(t),!0)});return{...e,version:e.version,nodes:r,rawEvents:a,firstEventSequence:t.firstEventSequence??e.firstEventSequence,nextBeforeSequence:t.nextBeforeSequence,hasOlderEvents:t.hasOlderEvents,eventLimit:(e.eventLimit??0)+(t.eventLimit??t.pageSize??0)}}function pO({selectedPiboSessionId:e,showRawEvents:t,setLiveTraceOverlay:n}){let r=BD(),[i,a]=(0,v.useState)(rO),[o,s]=(0,v.useState)(80),[c,l]=(0,v.useState)(null),u=(0,v.useMemo)(()=>e?iO(e):null,[e]),d=(0,v.useMemo)(()=>e?aO(e,{includeRawEvents:t,rawEventsLimit:o,pageSize:rO}):null,[o,e,t]),f=eO({queryKey:u??[`chat`,`trace-summary`,`idle`],queryFn:async()=>{if(!e||!u)throw Error(`Session is required`);let t=r.getQueryData(u),n=await fb(e,t?.version);if(n.notModified&&t)return t;if(!n.summary)throw Error(`Trace summary response missing payload.`);return n.summary},enabled:!!e,staleTime:tO,gcTime:nO,refetchOnWindowFocus:!1,retry:1}),p=eO({queryKey:d??[`chat`,`trace-page`,`idle`,`compact`,o,2e3,`tail`],queryFn:async()=>{if(!e||!d)throw Error(`Session is required`);let n=r.getQueryData(d),i=await pb(e,{includeRawEvents:t,rawEventsLimit:o,pageSize:rO,knownVersion:n?.version});if(i.notModified&&n)return n;if(!i.trace)throw Error(`Trace page response missing payload.`);return i.trace},enabled:!!e,staleTime:tO,gcTime:nO,refetchOnWindowFocus:!1,retry:1});(0,v.useEffect)(()=>{a(rO),s(80),l(null),n(null)},[e,n]),(0,v.useEffect)(()=>{let t=p.data;!t||t.piboSessionId!==e||(pv()&&Sv(t.piboSessionId,{overlayEventCount:0,traceBaseOutputLength:rD(t),traceBaseUpdated:!0}),(0,v.startTransition)(()=>{l(t),n(e=>oO(e,t))}))},[e,n,p.data]);let m=(0,v.useCallback)(async n=>{if(!e||!n)return;let i=aO(e,{includeRawEvents:t,rawEventsLimit:o,pageSize:rO,beforeSequence:n}),s=await r.fetchQuery({queryKey:i,queryFn:async()=>{let a=r.getQueryData(i),s=await pb(e,{includeRawEvents:t,rawEventsLimit:o,pageSize:rO,beforeSequence:n,knownVersion:a?.version});if(s.notModified&&a)return a;if(!s.trace)throw Error(`Trace page response missing payload.`);return s.trace},staleTime:tO,gcTime:nO});(0,v.startTransition)(()=>{l(e=>e?fO(e,s):s),a(e=>e+(s.pageSize??2e3))})},[r,o,e,t]),h=(0,v.useCallback)(()=>{s(e=>e+80)},[]);return{baseTraceView:c,traceEventLimit:i,rawEventLimit:o,traceSummaryQuery:f,tracePageQuery:p,tracePageReady:!!d,loadOlderTracePage:m,loadMoreRawEvents:h}}function mO(e){let t=e.currentEvents,n,r,i=()=>(r??=new Set(t.map(bO)),r),a=e=>{n??=t.slice(),n.push(e),t=n};for(let o of e.streamEvents){let s=_O(o,e.piboSessionId,e.nextSequence,e.now??(()=>new Date().toISOString()));if(!s)continue;if(hO(s)){t=gO(t,s),n=t,r=void 0;continue}let c=bO(s),l=i();l.has(c)||(l.add(c),a(s))}return t}function hO(e){return e.type===`assistant_message`||e.type===`thinking_finished`||e.type===`tool_execution_finished`}function gO(e,t){return t.type===`assistant_message`?[...yO(e,t,`assistant_delta`),t]:t.type===`thinking_finished`?[...yO(e,t,`thinking_delta`),t]:t.type===`tool_execution_finished`?[...yO(e,t,`tool_execution_updated`),t]:e}function _O(e,t,n,r){if(e.type===`RAW_EVENT`&&CO(e.event)&&typeof e.event.type==`string`){let i=e.event;return vO(e,t,e.event.type,i,n,r)}if(e.type===`TEXT_MESSAGE_CONTENT`&&typeof e.delta==`string`)return vO(e,t,`assistant_delta`,{type:`assistant_delta`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,...SO(typeof e.messageId==`string`?e.messageId:void 0,`assistant`),text:e.delta},n,r);if(e.type===`REASONING_MESSAGE_CONTENT`&&typeof e.delta==`string`)return vO(e,t,`thinking_delta`,{type:`thinking_delta`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,...SO(typeof e.messageId==`string`?e.messageId:void 0,`thinking`),text:e.delta},n,r);if(e.type===`TOOL_CALL_START`&&typeof e.toolCallId==`string`&&typeof e.toolName==`string`)return vO(e,t,`tool_execution_started`,{type:`tool_execution_started`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,toolCallId:e.toolCallId,toolName:e.toolName,args:e.args},n,r);if(e.type===`TOOL_CALL_ARGS`&&typeof e.toolCallId==`string`&&typeof e.toolName==`string`){let i=typeof e.runId==`string`?e.runId:void 0,a=e.sourceEventType===`tool_execution_updated`?`tool_execution_updated`:`tool_call`;return vO(e,t,a,a===`tool_execution_updated`?{type:`tool_execution_updated`,piboSessionId:t,eventId:i,toolCallId:e.toolCallId,toolName:e.toolName,args:e.args,partialResult:e.partialResult}:{type:`tool_call`,piboSessionId:t,eventId:i,toolCallId:e.toolCallId,toolName:e.toolName,args:e.args,argsComplete:!!e.argsComplete},n,r)}if(e.type===`TOOL_CALL_RESULT`&&typeof e.toolCallId==`string`&&typeof e.toolName==`string`)return vO(e,t,`tool_execution_finished`,{type:`tool_execution_finished`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,toolCallId:e.toolCallId,toolName:e.toolName,result:e.result,isError:!!e.isError},n,r);if(e.type===`RUN_ERROR`&&typeof e.message==`string`)return vO(e,t,`session_error`,{type:`session_error`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,error:e.message,errorDetails:e.errorDetails},n,r)}function vO(e,t,n,r,i,a){let o=typeof e.streamFrameId==`string`?e.streamFrameId:void 0,s=typeof e.streamFrameIndex==`number`?e.streamFrameIndex:void 0,c=typeof e.liveReplayId==`number`&&Number.isFinite(e.liveReplayId)?e.liveReplayId:void 0,l=i();return{id:typeof e.streamId==`number`?`stream:${e.streamId}:${s??`raw`}:${n}`:c===void 0?o?`stream:${o}:${n}`:`live:${l}:${n}`:`live-replay:${c}:${n}`,piboSessionId:t,eventSequence:l,streamId:typeof e.streamId==`number`?e.streamId:void 0,streamFrameIndex:s,eventId:typeof r.eventId==`string`?r.eventId:void 0,type:n,createdAt:a(),payload:r}}function yO(e,t,n){let r=xO(t);return e.filter(e=>e.type!==n||xO(e)!==r)}function bO(e){return e.streamId===void 0?`${e.id}:${e.type}`:e.streamFrameIndex===void 0?`stream:${e.streamId}:${e.id}:${e.type}`:`stream:${e.streamId}:${e.streamFrameIndex}:${e.type}`}function xO(e){let t=CO(e.payload)?e.payload:{},n=typeof t.piboSessionId==`string`?t.piboSessionId:e.piboSessionId??``,r=typeof t.eventId==`string`?t.eventId:e.eventId??``;if(typeof t.toolCallId==`string`)return`${n}:${r}:tool:${t.toolCallId}`;let i=typeof t.assistantIndex==`number`?t.assistantIndex:void 0,a=typeof t.thinkingIndex==`number`?t.thinkingIndex:void 0,o=typeof t.contentIndex==`number`?t.contentIndex:0;return`${n}:${r}:${i??a??o}`}function SO(e,t){let n=e?.match(RegExp(`:${t}:(\\d+)$`));if(!n)return{};let r=Number(n[1]);return Number.isInteger(r)?t===`assistant`?{assistantIndex:r}:{thinkingIndex:r}:{}}function CO(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function wO(e){try{let t=JSON.parse(e.data);if(typeof t.type!=`string`)return;let n=e.lastEventId?cx(e.lastEventId):void 0;return{...t,...e.lastEventId?{streamFrameId:e.lastEventId}:{},...n?{streamId:n.streamId,streamFrameIndex:n.frameIndex}:{}}}catch{return}}function TO(e,t,n){let r=e.get(t);r?.streamId!==void 0&&r.streamId>=n||e.set(t,{streamId:n,frameIndex:2**53-1,cursor:DO(n),exact:!1,...r?.liveReplayId===void 0?{}:{liveReplayId:r.liveReplayId}})}function EO(e,t,n){let r=e.get(t),i=typeof n.liveReplayId==`number`&&Number.isFinite(n.liveReplayId)?Math.max(r?.liveReplayId??0,n.liveReplayId):r?.liveReplayId;if(n.streamId===void 0||n.streamFrameIndex===void 0){i!==void 0&&i!==r?.liveReplayId&&e.set(t,{...r??{exact:!1},liveReplayId:i});return}if(r&&(r.streamId!==void 0&&r.streamId>n.streamId||r.streamId===n.streamId&&r.exact&&r.frameIndex!==void 0&&r.frameIndex>=n.streamFrameIndex)){i!==void 0&&i!==r.liveReplayId&&e.set(t,{...r,liveReplayId:i});return}e.set(t,{streamId:n.streamId,frameIndex:n.streamFrameIndex,cursor:n.streamFrameId??`${n.streamId}:${n.streamFrameIndex}`,exact:!0,...i===void 0?{}:{liveReplayId:i}})}function DO(e){return`${e}:999999`}function OO(e){if(e.type===`RUN_FINISHED`||e.type===`TEXT_MESSAGE_END`)return 300;if(e.type===`RUN_ERROR`)return 0}function kO(e){return e.type===`RUN_STARTED`||e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`||e.type===`TEXT_MESSAGE_END`}function AO(e){return e.type===`TEXT_MESSAGE_CONTENT`||e.type===`REASONING_MESSAGE_CONTENT`||e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_RESULT`||e.type===`RUN_ERROR`||e.type===`RAW_EVENT`}function jO(e,t,n){if(n.type===`RUN_STARTED`||n.type===`RUN_FINISHED`||n.type===`RUN_ERROR`){e.delete(t);return}let r=PO(n);r&&e.get(t)?.delete(r)}function MO(e,t,n){let r=NO(n);if(!r)return!1;let i=e.get(t);return i||(i=new Set,e.set(t,i)),i.has(r)?!1:(i.add(r),!0)}function NO(e){if(e.type===`TEXT_MESSAGE_CONTENT`||e.type===`REASONING_MESSAGE_CONTENT`)return`${e.type}:${e.messageId}`}function PO(e){if(e.type===`TEXT_MESSAGE_START`)return`TEXT_MESSAGE_CONTENT:${e.messageId}`;if(e.type===`REASONING_MESSAGE_START`)return`REASONING_MESSAGE_CONTENT:${e.messageId}`}var FO=500,IO=1e4,LO=45e3,RO=100;function zO({selectedPiboSessionId:e,tracePageData:t,currentTraceView:n,liveEventSeqRef:r,selectedSessionStatus:i,tracePageReady:a,setLiveTraceOverlay:o,onRefreshTrace:s,onRefreshBootstrap:c,onError:l}){let u=(0,v.useRef)(new Map),d=(0,v.useRef)(void 0),f=(0,v.useRef)(void 0),p=(0,v.useRef)(new Map),m=(0,v.useRef)(new Map),h=(0,v.useRef)(null),g=(0,v.useRef)(void 0),_=(0,v.useRef)(0),[y,b]=(0,v.useState)(0);(0,v.useEffect)(()=>{let n=t;if(!n||n.piboSessionId!==e)return;let i=n.rawEvents.map(e=>e.eventSequence??0).reduce((e,t)=>Math.max(e,t),0);r.current=Math.max(r.current,i+1),n.latestStreamId!==void 0&&TO(m.current,n.piboSessionId,n.latestStreamId)},[r,e,t]);let x=(0,v.useCallback)(e=>{let t=u.current.get(e);t?.length&&(o(n=>{let i=mO({currentEvents:n?.piboSessionId===e?n.events:[],streamEvents:t,piboSessionId:e,nextSequence:()=>r.current++});return vv(e,t.length,i.length),{piboSessionId:e,events:i}}),u.current.delete(e))},[]),S=(0,v.useCallback)(()=>{if(!(d.current!==void 0||f.current!==void 0||!e)){if(document.hidden){f.current=setTimeout(()=>{f.current=void 0,x(e)},RO);return}d.current=requestAnimationFrame(()=>{d.current=void 0,x(e)})}},[x,e]),C=(0,v.useCallback)((t,n,r=!1)=>{jO(p.current,t,n);let i=r||MO(p.current,t,n),a=u.current.get(t)??[];a.push(n),u.current.set(t,a),_v(t,n,a.length,i),i||t!==e?x(t):S()},[x,S,e]);(0,v.useEffect)(()=>()=>{d.current!==void 0&&cancelAnimationFrame(d.current),f.current!==void 0&&clearTimeout(f.current),g.current!==void 0&&clearTimeout(g.current)},[]);let w=(0,v.useCallback)((e,t)=>{EO(m.current,e,t)},[]),T=(0,v.useCallback)((e=0)=>{if(g.current!==void 0){if(e>0)return;clearTimeout(g.current)}g.current=setTimeout(()=>{g.current=void 0,b(e=>e+1)},e)},[]),E=(0,v.useCallback)(()=>{if(!e)return;x(e),s().catch(e=>l(BO(e))),c().catch(e=>l(BO(e)));let t=h.current;(!t||t.piboSessionId!==e||t.events.readyState===2||Date.now()-t.lastActivityAt>LO)&&T()},[x,l,c,s,T,e]);(0,v.useEffect)(()=>{if(!e||!a||!n||n.piboSessionId!==e)return;let t=new URLSearchParams({piboSessionId:e});t.set(`mode`,`live`);let r=m.current.get(e),i=r?.cursor??(n.latestStreamId===void 0?void 0:DO(n.latestStreamId));i!==void 0&&t.set(`since`,i),r?.liveReplayId!==void 0&&t.set(`liveSince`,String(r.liveReplayId));let o=new EventSource(`/api/chat/events?${t.toString()}`),u=Date.now();h.current={piboSessionId:e,events:o,openedAt:u,lastActivityAt:u};let d=!1,f,p,v=!1,y=!1,b=(t,n=!1)=>{if(f){if(!n)return;clearTimeout(f)}xv(e,t),f=setTimeout(()=>{f=void 0,s().catch(e=>l(BO(e)))},t)},S=()=>{if(v){y=!0;return}v=!0,c().catch(e=>l(BO(e))).finally(()=>{v=!1,y&&(y=!1,E(250,!0))})},E=(e,t=!1)=>{if(p){if(!t)return;clearTimeout(p)}p=setTimeout(()=>{p=void 0,S()},e)},ee=()=>{E(900,!0)};return o.onopen=()=>{_.current=0,g.current!==void 0&&(clearTimeout(g.current),g.current=void 0),mv(e,o.readyState);let t=h.current;t?.events===o&&(t.lastActivityAt=Date.now())},o.onerror=()=>{if(d)return;hv(e,o.readyState);let t=h.current;t?.events===o&&(t.lastErrorAt=Date.now());let n=_.current++;T(Math.min(IO,FO*2**n))},o.addEventListener(`pibo`,t=>{if(d)return;let n=wO(t);if(!n)return;let r=n.piboSessionId||e,i=h.current;if(i?.events===o&&(i.lastActivityAt=Date.now()),w(r,n),gv(r,n,t.lastEventId,o.readyState),r===e&&n.type===`ready`&&n.liveReplay?.missed&&b(0,!0),Cv(n))return;let a=n.type!==`TEXT_MESSAGE_CONTENT`&&n.type!==`REASONING_MESSAGE_CONTENT`;r===e&&AO(n)&&C(r,n,a);let s=OO(n);r===e&&s!==void 0?b(s,!0):r===e&&n.type!==`ready`&&n.type!==`RAW_EVENT`&&b(1500,!0),kO(n)&&(n.type===`RUN_FINISHED`||n.type===`RUN_ERROR`||n.type===`TEXT_MESSAGE_END`?ee():E(r===e?0:150))}),()=>{d=!0,f&&clearTimeout(f),p&&clearTimeout(p),x(e),h.current?.events===o&&(h.current=null),o.close()}},[n?.piboSessionId,C,x,l,c,s,w,T,y,e,a]),(0,v.useEffect)(()=>{n?.piboSessionId&&x(n.piboSessionId)},[n?.piboSessionId,x]),(0,v.useEffect)(()=>{let e=()=>E(),t=()=>{document.hidden||E()};return window.addEventListener(`focus`,e),window.addEventListener(`online`,e),window.addEventListener(`pageshow`,e),document.addEventListener(`visibilitychange`,t),()=>{window.removeEventListener(`focus`,e),window.removeEventListener(`online`,e),window.removeEventListener(`pageshow`,e),document.removeEventListener(`visibilitychange`,t)}},[E]),(0,v.useEffect)(()=>{if(!e||i!==`running`)return;let t=window.setInterval(()=>{x(e),s().catch(e=>l(BO(e)))},1e3);return()=>window.clearInterval(t)},[x,l,s,e,i])}function BO(e){return e instanceof Error?e.message:String(e)}var VO=10;function HO(e,t,n,r){if(!t||!n.length)return e;let i=e[t]??[],a=new Set(i.map(e=>e.path)),o=n.filter(e=>e.path&&!a.has(e.path)).map(e=>({...e,id:r()}));return o.length?{...e,[t]:[...i,...o].slice(0,VO)}:e}function UO(e,t,n){if(!t)return e;let r=e[t]??[],i=r.filter(e=>e.id!==n);return i.length===r.length?e:{...e,[t]:i}}function WO(e,t){return!t||!e[t]?.length?e:{...e,[t]:[]}}function GO(e,t){let[n,r]=(0,v.useState)({});return{selectedUploadAttachments:(0,v.useMemo)(()=>e?n[e]??[]:[],[e,n]),attachUploadedFiles:(0,v.useCallback)(n=>{r(r=>HO(r,e,n,t))},[t,e]),detachUploadAttachment:(0,v.useCallback)(t=>{r(n=>UO(n,e,t))},[e]),clearSelectedUploadAttachments:(0,v.useCallback)(()=>{r(t=>WO(t,e))},[e])}}function KO({selectedPiboSessionId:e,onError:t,formatError:n}){let[r,i]=(0,v.useState)([]),[a,o]=(0,v.useState)(!1),[s,c]=(0,v.useState)(()=>e?cE(e):null),[l,u]=(0,v.useState)(()=>mE()),[d,f]=(0,v.useState)(!1),p=!!(e&&s?.piboSessionId===e&&s.installed),m=!!e&&(a||p),h=eO({queryKey:[`web-annotations`,`app`,e],queryFn:async()=>{if(!e)throw Error(`Session is required`);return gb(e,{limit:100,scope:`app`})},enabled:!!e&&(m||r.length>0),staleTime:1e3,refetchOnWindowFocus:m,refetchInterval:m?5e3:!1,retry:1}),g=h.refetch,_=(0,v.useMemo)(()=>(h.data?.annotations??[]).filter(e=>e.status!==`resolved`&&e.status!==`dismissed`),[h.data?.annotations]),y=(0,v.useMemo)(()=>r.map(e=>_.find(t=>t.id===e)).filter(e=>!!e),[r,_]);(0,v.useEffect)(()=>{i(e?fE(e):[]),c(e?cE(e):null)},[e]),(0,v.useEffect)(()=>{if(!e)return;let t=t=>{!t||t.piboSessionId!==e||(c(e=>t.installed?t:e?.installed&&e.bindingId&&t.bindingId&&e.bindingId!==t.bindingId?e:t),t.installed?g():o(!1))},n=e=>t(dE(e.detail)),r=n=>{n.key===lE(e)&&t(uE(n.newValue))},i=()=>t(cE(e));return window.addEventListener(`pibo:web-annotation-overlay-state`,n),window.addEventListener(`storage`,r),window.addEventListener(`focus`,i),document.addEventListener(`visibilitychange`,i),i(),()=>{window.removeEventListener(`pibo:web-annotation-overlay-state`,n),window.removeEventListener(`storage`,r),window.removeEventListener(`focus`,i),document.removeEventListener(`visibilitychange`,i)}},[g,e]),(0,v.useEffect)(()=>{if(!h.data)return;if(!_.length){i(t=>(t.length&&e&&pE(e,[]),t.length?[]:t));return}let t=new Set(_.map(e=>e.id));i(n=>{let r=n.filter(e=>t.has(e));return r.length!==n.length&&e&&pE(e,r),r.length===n.length?n:r})},[e,_,h.data]),(0,v.useEffect)(()=>{let e=()=>{o(!0),g()};return window.addEventListener(`pibo:web-annotation-saved`,e),()=>window.removeEventListener(`pibo:web-annotation-saved`,e)},[g]);let b=(0,v.useCallback)(t=>{i(n=>{let r=t(n);return e&&pE(e,r),r})},[e]),x=(0,v.useCallback)(e=>{b(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e].slice(0,5))},[b]),S=(0,v.useCallback)(()=>b(()=>[]),[b]);return{selectedWebAnnotationIds:r,selectedWebAnnotations:y,visibleWebAnnotations:_,webAnnotationsPanelCollapsed:l,webAnnotationsPanelRendered:m,webAnnotationsPanelVisible:a,webAnnotationsQuery:h,clearingWebAnnotations:d,setWebAnnotationsPanelVisible:o,toggleWebAnnotationAttachment:x,detachWebAnnotationAttachment:(0,v.useCallback)(e=>{b(t=>t.filter(t=>t!==e))},[b]),clearSelectedWebAnnotationAttachments:S,toggleWebAnnotationsPanelCollapsed:(0,v.useCallback)(()=>{u(e=>{let t=!e;return hE(t),t})},[]),clearVisibleWebAnnotations:(0,v.useCallback)(async()=>{if(!(!_.length||d)&&window.confirm(`Dismiss ${_.length} visible web annotations? This keeps sent messages but clears the annotation list.`)){f(!0);try{await Promise.all(_.map(e=>_b(e.id,{piboSessionId:e.piboSessionId,status:`dismissed`,summary:`Cleared from Chat Web UI`}))),S(),await g()}catch(e){t(n(e,`Could not clear web annotations`))}finally{f(!1)}}},[d,S,n,t,g,_])}}function qO(e,t){return t?{sessionBreadcrumbs:QO(e,t),originSession:XO(e,t),derivedSessions:ZO(e,t)}:{sessionBreadcrumbs:[],originSession:void 0,derivedSessions:[]}}function JO(e){let t=e.selectedPiboSessionId?S(e.bootstrap.sessions,e.selectedPiboSessionId):void 0,n=nk(e.currentTraceView);return tk(e.selectedSessionActiveModel,e.bootstrap.runtimeStatus?.thinkingLevel??n.level??$O(e.bootstrap,e.selectedSessionProfile,!!t?.parentId),e.bootstrap.runtimeStatus?.fastMode??n.fast??ek(e.bootstrap,e.selectedSessionProfile,!!t?.parentId)??!1)}function YO(e){return{traceView:e.currentTraceView,selectedTrace:null,isLoading:e.isLoading,showThinking:e.showThinking,expandThinking:e.expandThinking,sessionAgentProfile:e.selectedSessionProfile,sessionActiveModel:e.sessionActiveModelBadge,selectedSessionStatus:e.selectedSessionStatus,selectedSessionSignal:e.selectedSessionSignal,workflowProjectSession:e.workflowProjectSession,workflowLifecycleEvents:e.workflowLifecycleEvents,sessionNodes:e.sessionNodes,sessionBreadcrumbs:e.sessionLinks.sessionBreadcrumbs,originSession:e.sessionLinks.originSession,derivedSessions:e.sessionLinks.derivedSessions,agentProfiles:e.agentProfiles,sessionProfileChangeDisabled:e.sessionProfileChangeDisabled,onSessionAgentProfileChange:e.onSessionAgentProfileChange,onFork:e.onFork,onOpenSession:e.onOpenSession,onThinkingLevelChange:e.onThinkingLevelChange,onModelChanged:async()=>{await e.onRefreshBootstrap(),await e.onRefreshTrace()},onRefreshBootstrap:e.onRefreshBootstrap,onError:e.onError}}function XO(e,t){let n=S(e,t);if(!n?.originId)return;let r=S(e,n.originId);return{piboSessionId:n.originId,label:r?ak(r,0):n.originId}}function ZO(e,t){return S(e,t)?.derivedSessions.map(e=>({piboSessionId:e.piboSessionId,label:ok(e),profile:e.profile,status:e.status}))??[]}function QO(e,t){return C(e,t).map((e,t)=>({piboSessionId:e.piboSessionId,label:ak(e,t)}))}function $O(e,t,n=!1){let r=e.agents.find(e=>e.name===t),i=e.customAgents.find(e=>e.profileName===t),a=r??i;return n?a?.subagentThinkingLevel??a?.thinkingLevel??e.modelDefaults?.subagentThinking??e.modelDefaults?.thinking:a?.mainThinkingLevel??a?.thinkingLevel??e.modelDefaults?.mainThinking??e.modelDefaults?.thinking}function ek(e,t,n=!1){let r=e.agents.find(e=>e.name===t),i=e.customAgents.find(e=>e.profileName===t),a=r??i;return n?a?.subagentFast??a?.fast??e.modelDefaults?.subagentFast??e.modelDefaults?.fast:a?.mainFast??a?.fast??e.modelDefaults?.mainFast??e.modelDefaults?.fast}function tk(e,t,n){if(e)return[e,t,n?`fast`:void 0].filter(Boolean).join(` `)}function nk(e){let t={};if(!e)return t;for(let n of rk(e.nodes)){if(n.type!==`execution.command`||n.title!==`thinking`&&n.title!==`fast_mode`)continue;let e=n.output&&typeof n.output==`object`?n.output:void 0;t={level:(typeof e?.level==`string`&&ik(e.level)?e.level:void 0)??t.level,fast:n.title===`fast_mode`?e?.mode===`fast`:t.fast}}return t}function rk(e){return e.flatMap(e=>[e,...rk(e.children)])}function ik(e){return zC.includes(e)}function ak(e,t){return t?e.subagentName&&e.subagentName!==e.profile?`${e.subagentName} (${e.profile})`:e.profile||e.subagentName||e.title:e.profile||e.title}function ok(e){return e.subagentName&&e.subagentName!==e.profile?`${e.subagentName} (${e.profile})`:e.title||e.profile||e.subagentName||`Untitled Session`}function sk({piboSessionId:e,text:t,selectedWebAnnotations:n,selectedUploadAttachments:r,eventSequence:i,now:a,clientTxnId:o}){let s=n.map(e=>e.id),c=r.map(e=>e.path);return{text:t,webAnnotationIds:s,fileAttachmentPaths:c,clientTxnId:o,optimisticEvent:{id:o,piboSessionId:e,eventSequence:i,eventId:o,type:`message_queued`,createdAt:a,payload:{type:`message_queued`,piboSessionId:e,eventId:o,clientTxnId:o,queuedMessages:1,text:t,...c.length?{fileAttachmentPaths:c}:{},source:`user`}}}}function ck(e,t,n){return{piboSessionId:t,events:[...e?.piboSessionId===t?e.events:[],n]}}function lk(e){return e instanceof Error?e.message:String(e)}function uk({bootstrap:e,selectedPiboSessionId:t,selectedRoomId:n,selectedRoomArchived:r,selectedSessionProfile:i,selectedSessionActiveModel:a,selectedSessionStatus:o,selectedSessionSignal:s,workflowProjectSession:c,workflowLifecycleEvents:l,projectSessionCreatePanel:u,workflowStartPanel:d,projectModulePanel:f,extraViewTabs:p,activeViewId:m,sessionViewId:h,sessionViews:g,currentSessionView:_,allowedSessionViewIds:y,creatingSession:b,showRawEvents:x,showThinking:S,expandThinking:C,commands:T,skills:E,composerText:ee,composerFocusSignal:D,onComposerTextChange:O,onToggleRawEvents:te,onToggleThinking:ne,onToggleExpandThinking:re,onSessionAgentProfileChange:ie,onFork:ae,onOpenSession:oe,onSelectSessionView:k,onCommand:A,onThinkingLevelChange:se,onRefreshTrace:ce,onRefreshBootstrap:le,onSend:ue,onError:de}){let fe=(0,v.useRef)(0),[pe,me]=(0,v.useState)(null),{baseTraceView:he,traceEventLimit:ge,rawEventLimit:_e,traceSummaryQuery:ve,tracePageQuery:ye,tracePageReady:be,loadOlderTracePage:xe,loadMoreRawEvents:j}=pO({selectedPiboSessionId:t,showRawEvents:x,setLiveTraceOverlay:me}),{selectedWebAnnotationIds:Se,selectedWebAnnotations:Ce,visibleWebAnnotations:we,webAnnotationsPanelCollapsed:Te,webAnnotationsPanelRendered:Ee,webAnnotationsPanelVisible:De,webAnnotationsQuery:Oe,clearingWebAnnotations:ke,setWebAnnotationsPanelVisible:Ae,toggleWebAnnotationAttachment:je,detachWebAnnotationAttachment:Me,clearSelectedWebAnnotationAttachments:Ne,toggleWebAnnotationsPanelCollapsed:Pe,clearVisibleWebAnnotations:Fe}=KO({selectedPiboSessionId:t,onError:de,formatError:SE}),{selectedUploadAttachments:Ie,attachUploadedFiles:Le,detachUploadAttachment:Re,clearSelectedUploadAttachments:ze}=GO(t,(0,v.useCallback)(()=>`upload-${w()}`,[])),Be=iD({selectedPiboSessionId:t,baseTraceView:he,liveTraceOverlay:pe,selectedSessionStatus:o});zO({selectedPiboSessionId:t,tracePageData:ye.data,currentTraceView:Be,liveEventSeqRef:fe,selectedSessionStatus:o,tracePageReady:be,setLiveTraceOverlay:me,onRefreshTrace:ce,onRefreshBootstrap:le,onError:de});let Ve=JO({bootstrap:e,selectedPiboSessionId:t,selectedSessionProfile:i,selectedSessionActiveModel:a,currentTraceView:Be}),He=(0,v.useMemo)(()=>qO(e.sessions,t),[e.sessions,t]),Ue=!!t&&ye.isFetching&&!Be,We=ye.error?lk(ye.error):ve.error?lk(ve.error):null,Ge=Be?.piboSessionId??t??``,Ke=c&&OE(c)?kE(c,o):null,qe=e=>{for(let n of[750,2e3,5e3,1e4])window.setTimeout(()=>{t===e&&ye.refetch().catch(e=>de(lk(e)))},n)},Je=async e=>{if(!t)return;let n=sk({piboSessionId:t,text:e,selectedWebAnnotations:Ce,selectedUploadAttachments:Ie,eventSequence:fe.current++,now:new Date().toISOString(),clientTxnId:w()});me(e=>ck(e,t,n.optimisticEvent)),await ue(n.text,n.webAnnotationIds,n.fileAttachmentPaths,n.clientTxnId),Ne(),ze(),await Promise.all([ye.refetch(),Oe.refetch()]),qe(t)},Ye=YO({currentTraceView:Be,isLoading:Ue,showThinking:S,expandThinking:C,selectedSessionProfile:i,sessionActiveModelBadge:Ve,selectedSessionStatus:o,selectedSessionSignal:s,workflowProjectSession:c,workflowLifecycleEvents:l,sessionNodes:e.sessions,sessionLinks:He,agentProfiles:e.agents,sessionProfileChangeDisabled:b||r,onSessionAgentProfileChange:ie,onFork:ae,onOpenSession:oe,onThinkingLevelChange:se,onRefreshTrace:ce,onRefreshBootstrap:le,onError:de});return(0,M.jsx)(UE,{selectedPiboSessionId:t,selectedRoomId:n,fallbackRoomId:e.selectedRoomId??void 0,sessionViewId:h,loadingTrace:Ue,traceError:We,showRawEvents:x,currentTraceView:Be,traceEventLimit:ge,rawEventLimit:_e,tracePageFetching:ye.isFetching,onLoadOlderTracePage:e=>void xe(e),onLoadMoreRawEvents:j,headerProps:{title:Be?.title??t??e.room?.name??n,roomLabel:e.room?.name??n??`Room`,headerPiboSessionId:Ge,piboSessionId:t,piboRoomId:n??e.selectedRoomId??void 0,webAnnotationsDisabled:!t||r,webAnnotationsPanelRendered:Ee,workflowHeader:Ke,sessionViewId:h,sessionViews:g,currentSessionView:_,allowedSessionViewIds:y,extraViewTabs:p,activeViewId:m,showRawEvents:x,showThinking:S,expandThinking:C,onShowWebAnnotationsPanel:()=>Ae(!0),onHideWebAnnotationsPanel:()=>Ae(!1),onSelectSessionView:k,onToggleRawEvents:te,onToggleThinking:ne,onToggleExpandThinking:re,onError:de},projectSessionCreatePanel:u,workflowStartPanel:d,projectModulePanel:f,currentSessionView:_,sessionViewProps:Ye,webAnnotationsPanelRendered:Ee,webAnnotationsPanelProps:{piboSessionId:t,annotations:we,selectedIds:Se,loading:Oe.isLoading||Oe.isFetching||ke,error:Oe.error?lk(Oe.error):null,collapsed:Te,onRefresh:()=>void Oe.refetch(),onToggle:je,onClear:()=>void Fe(),onCollapse:Pe,onClose:()=>Ae(!1)},composerProps:{sessionId:t,disabled:!t||r,commands:T,skills:E,value:ee,focusSignal:D,selectedWebAnnotations:Ce,selectedUploadAttachments:Ie,onValueChange:O,onCommand:A,onDetachWebAnnotation:Me,onClearWebAnnotations:Ne,onAttachUploadedFiles:Le,onDetachUploadAttachment:Re,onClearUploadAttachments:ze,onSend:Je}})}function dk({mode:e,onSelectSession:t,onNewSession:n,onDeleteSession:r,onRenameSession:i,onSelectRoom:a}){return e.kind===`rooms`?(0,M.jsx)(vk,{candidates:e.candidates,workspace:e.workspace,onSelectRoom:a}):(0,M.jsx)(gk,{sessions:e.sessions,selectedPiboSessionId:e.selectedPiboSessionId,onSelectSession:t,onNewSession:n,onDeleteSession:r,onRenameSession:i})}function fk(e){return e===`running`?`running`:e===`error`?`error`:e===`completed`?`completed`:`idle`}var pk={running:`bg-cyan-400`,idle:`bg-slate-500`,error:`bg-rose-500`,completed:`bg-emerald-500`},mk={running:`running`,idle:`idle`,error:`error`,completed:`completed`};function hk({status:e}){let t=fk(e);return(0,M.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-[10px] uppercase tracking-wider text-slate-400`,children:[(0,M.jsx)(`span`,{className:`inline-block w-1.5 h-1.5 rounded-full ${pk[t]}`,"aria-hidden":`true`}),mk[t]]})}function gk({sessions:e,selectedPiboSessionId:t,onSelectSession:n,onNewSession:r,onDeleteSession:i,onRenameSession:a}){let o=[...e].sort((e,t)=>{let n=e.lastActivityAt??``;return(t.lastActivityAt??``).localeCompare(n)});return(0,M.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-slate-800 px-3 py-2 bg-[#0c1820]`,"data-testid":`session-list`,children:[(0,M.jsx)(`button`,{type:`button`,className:`shrink-0 w-7 h-7 inline-flex items-center justify-center rounded border border-slate-700 text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4]`,title:`New session`,onClick:()=>void r(`default`),children:`+`}),(0,M.jsxs)(`ul`,{className:`flex gap-1 overflow-x-auto min-w-0`,children:[o.map(e=>(0,M.jsx)(`li`,{className:`shrink-0`,children:(0,M.jsx)(_k,{session:e,isActive:e.piboSessionId===t,onSelect:()=>n(e.piboSessionId),onDelete:()=>void i(e.piboSessionId),onRename:t=>void a(e.piboSessionId,t)})},e.piboSessionId)),o.length===0&&(0,M.jsx)(`li`,{className:`text-xs text-slate-500 px-2 py-1`,children:`No sessions yet — click + to start one.`})]})]})}function _k({session:e,isActive:t,onSelect:n,onDelete:r,onRename:i}){let[a,o]=(0,v.useState)(!1);return(0,M.jsxs)(`div`,{className:`group inline-flex items-center gap-2 rounded px-2 py-1 border ${t?`border-[#11a4d4] bg-[#102834]`:`border-slate-700 bg-[#0a1418] hover:border-slate-500`}`,children:[(0,M.jsxs)(`button`,{type:`button`,onClick:n,className:`inline-flex items-center gap-2 text-left`,children:[(0,M.jsx)(hk,{status:e.status}),(0,M.jsx)(`span`,{className:`text-xs text-slate-200 max-w-[180px] truncate`,children:e.title||`Untitled`})]}),(0,M.jsx)(`button`,{type:`button`,className:`text-slate-500 hover:text-slate-200 text-xs px-1`,title:`Session actions`,"aria-label":`Session actions`,onClick:e=>{e.stopPropagation(),o(e=>!e)},children:`…`}),a&&(0,M.jsxs)(`div`,{className:`absolute z-10 mt-12 -ml-20 bg-[#0a1418] border border-slate-700 rounded shadow-lg text-xs`,children:[(0,M.jsx)(`button`,{type:`button`,className:`block w-full text-left px-3 py-1.5 hover:bg-[#102834]`,onClick:t=>{t.stopPropagation(),o(!1);let n=window.prompt(`Rename session`,e.title??``);n&&n!==e.title&&i(n)},children:`Rename`}),(0,M.jsx)(`button`,{type:`button`,className:`block w-full text-left px-3 py-1.5 hover:bg-rose-900/30 text-rose-300`,onClick:t=>{t.stopPropagation(),o(!1),window.confirm(`Delete session "${e.title??`Untitled`}"?`)&&r()},children:`Delete`})]})]})}function vk({candidates:e,workspace:t,onSelectRoom:n}){return(0,M.jsxs)(`div`,{className:`border-b border-slate-800 px-3 py-3 bg-[#0c1820]`,"data-testid":`room-picker`,children:[(0,M.jsxs)(`div`,{className:`text-[10px] uppercase tracking-wider text-slate-400 mb-2`,children:[`Multiple rooms found for `,(0,M.jsx)(`span`,{className:`font-mono text-slate-300`,children:t})]}),(0,M.jsx)(`ul`,{className:`flex flex-col gap-1`,children:e.map(e=>(0,M.jsx)(`li`,{children:(0,M.jsxs)(`button`,{type:`button`,className:`w-full text-left px-3 py-2 border border-slate-700 rounded hover:border-[#11a4d4] bg-[#0a1418]`,onClick:()=>n(e.id),children:[(0,M.jsx)(`div`,{className:`font-semibold text-slate-200 text-sm`,children:e.name}),e.topic&&(0,M.jsx)(`div`,{className:`text-xs text-slate-400 mt-0.5`,children:e.topic}),(0,M.jsxs)(`div`,{className:`text-[10px] text-slate-500 mt-1`,children:[`Created `,yk(e.createdAt),` · Updated `,yk(e.updatedAt)]})]})},e.id))})]})}function yk(e){try{return new Date(e).toLocaleString()}catch{return e}}function bk(){return new URLSearchParams(window.location.search).get(`workspace`)}function xk(){return new URLSearchParams(window.location.search).get(`roomId`)}function Sk(){let e=(0,v.useMemo)(()=>bk(),[]),[t,n]=(0,v.useState)(()=>xk()),[r,i]=(0,v.useState)(()=>xk()?{kind:`sessions`,roomId:xk(),sessions:[],selectedPiboSessionId:null}:{kind:`rooms`,candidates:[],workspace:e??``}),[a,o]=(0,v.useState)(null),[s,c]=(0,v.useState)(null),[l,u]=(0,v.useState)(``),[d,f]=(0,v.useState)(0),[p,m]=(0,v.useState)(null),[h,g]=(0,v.useState)(!1),_=(0,v.useMemo)(()=>{let e=a?.sessionNodes;return Array.isArray(e)?e:[]},[a]);(0,v.useEffect)(()=>{if(!t)return;let e=!1;return(async()=>{try{let n=await te(void 0,!1,t);if(e)return;o(n);let r=n.sessions.find(e=>!e.archived)??n.sessions[0];r&&!s&&c(r.piboSessionId),i({kind:`sessions`,roomId:t,sessions:n.sessions,selectedPiboSessionId:r?.piboSessionId??null})}catch(t){e||m(lk(t))}})(),()=>{e=!0}},[t]);let y=(0,v.useCallback)(async()=>{if(t)try{o(await te(s??void 0,!1,t,!0))}catch(e){m(lk(e))}},[t,s]),b=(0,v.useCallback)(async()=>{await y()},[y]);(0,v.useEffect)(()=>{if(!t)return;let e=`/api/chat/events?${new URLSearchParams({roomId:t,mode:`summary`,since:`0:999999`}).toString()}`,n=new EventSource(e),r,i=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=void 0,y()},200)};return n.addEventListener(`change`,i),n.addEventListener(`trace`,i),n.addEventListener(`message`,i),n.onerror=()=>{},()=>{r&&clearTimeout(r),n.close()}},[t,y]),(0,v.useEffect)(()=>{let e=e=>{let t=e.data;!t||typeof t!=`object`||(t.type===`pibo/set-selector-mode`?(i(t.mode),t.mode.kind===`sessions`&&n(t.mode.roomId)):t.type===`pibo/refresh-bootstrap`&&y())};return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[y]);let S=(0,v.useMemo)(()=>a?ee(a.capabilities.actions):[],[a]),C=(0,v.useMemo)(()=>D(a,s),[a,s]),T=(0,v.useMemo)(()=>r.kind===`sessions`?r.sessions:_,[r,_]),E=(0,v.useCallback)(e=>{c(e),f(e=>e+1)},[]),O=(0,v.useCallback)(async e=>{if(t)try{let n=await ne(e,t);await y(),n.session?.id&&c(n.session.id)}catch(e){m(lk(e))}},[t,y]),k=(0,v.useCallback)(async e=>{try{await ie(e,`delete`),await y(),s===e&&c(null)}catch(e){m(lk(e))}},[y,s]),A=(0,v.useCallback)(async(e,t)=>{try{await re(e,{title:t}),await y()}catch(e){m(lk(e))}},[y]),se=(0,v.useCallback)(e=>{n(e),c(null),o(null),i({kind:`sessions`,roomId:e,sessions:[],selectedPiboSessionId:null});let t=new URLSearchParams(window.location.search);t.set(`roomId`,e),window.history.replaceState(null,``,`${window.location.pathname}?${t.toString()}`)},[]),ue=(0,v.useCallback)(async e=>{if(!(!s||!t))try{await ae(s,e,w(),t),u(``),f(e=>e+1),await y()}catch(e){m(lk(e))}},[s,t,y]),de=(0,v.useCallback)(async e=>{if(!s)return!1;let n=e.trim();if(!n)return!1;let r=n.split(/\s+/)[0],i=S.find(e=>e.slash===r);if(!i)return m(`Unknown command: ${r}`),!1;if(i.action===`thinking-show`)return g(e=>!e),!0;if(i.action===`download`){let e=ce(n.slice(r.length));if(!e)return m(`Usage: /download <path>`),!0;try{await fe(e,{piboSessionId:s,roomId:t??void 0})}catch(e){m(lk(e))}return!0}try{let e=le(i.action,n.slice(r.length).trim());await oe(s,i.action,e),await y()}catch(e){m(lk(e))}return!0},[S,s,t,y]),pe=(0,v.useMemo)(()=>PT(),[]),he=(0,v.useMemo)(()=>FT(me),[]);if(!a)return(0,M.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,M.jsx)(dk,{mode:r,onSelectSession:E,onNewSession:O,onDeleteSession:k,onRenameSession:A,onSelectRoom:se}),(0,M.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-slate-400 text-sm`,children:p?`Error: ${p}`:t?`Loading Pibo…`:`Waiting for room…`})]});if(r.kind===`rooms`)return(0,M.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,M.jsx)(dk,{mode:{kind:`rooms`,candidates:a.rooms??r.candidates,workspace:r.workspace},onSelectSession:E,onNewSession:O,onDeleteSession:k,onRenameSession:A,onSelectRoom:se}),(0,M.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-slate-400 text-sm`,children:`Multiple rooms found — pick one above to continue.`})]});let ge=a.sessions.find(e=>e.piboSessionId===s);return(0,M.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,M.jsx)(dk,{mode:{kind:`sessions`,roomId:t??``,sessions:T,selectedPiboSessionId:s},onSelectSession:E,onNewSession:O,onDeleteSession:k,onRenameSession:A,onSelectRoom:se}),p&&(0,M.jsxs)(`div`,{className:`bg-rose-900/40 border-b border-rose-700 text-rose-200 text-xs px-3 py-1.5`,role:`alert`,children:[p,(0,M.jsx)(`button`,{type:`button`,className:`ml-3 underline`,onClick:()=>m(null),children:`dismiss`})]}),(0,M.jsx)(`div`,{className:`flex-1 min-h-0`,children:(0,M.jsx)(uk,{bootstrap:a,selectedPiboSessionId:s,selectedRoomId:t,selectedRoomArchived:!1,selectedSessionProfile:ge?.profile??`default`,selectedSessionActiveModel:ge?x(a,ge)??void 0:void 0,selectedSessionStatus:ge?.status,sessionViewId:me,sessionViews:pe,currentSessionView:he,allowedSessionViewIds:[`terminal`],creatingSession:!1,showRawEvents:!1,showThinking:h,expandThinking:!1,commands:S,skills:C,composerText:l,composerFocusSignal:d,onComposerTextChange:u,onToggleRawEvents:()=>void 0,onToggleThinking:()=>g(e=>!e),onToggleExpandThinking:()=>void 0,onSessionAgentProfileChange:()=>void 0,onFork:()=>void 0,onOpenSession:e=>c(e),onSelectSessionView:()=>void 0,onCommand:de,onThinkingLevelChange:e=>void de(`/thinking ${e}`),onRefreshTrace:b,onRefreshBootstrap:y,onSend:ue,onError:m})})]})}var Ck=document.getElementById(`root`);Ck&&(0,y.createRoot)(Ck).render((0,M.jsx)(v.StrictMode,{children:(0,M.jsx)(Sk,{})}));