@pasko70/pibo 2.2.0 → 2.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/apps/chat/agent-store.js +11 -4
- package/dist/apps/chat/chat-request-normalizers.js +6 -0
- package/dist/apps/chat/trace.js +5 -0
- package/dist/apps/chat-ui/assets/{dist-CBPDkWd4.js → dist-CbM7-718.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-CwS16H7k.js → dist-CvCbmtlu.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-CHInEWhr.js → dist-DrthHok7.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-nU3BVpFi.js → dist-I3spUe7o.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-BB8loWTa.js → dist-ogVF1MMz.js} +1 -1
- package/dist/apps/chat-ui/assets/{index-CQuka3bs.js → index-CI_vSx9U.js} +54 -54
- package/dist/apps/chat-ui/assets/index-QkfBrh9Q.css +1 -0
- package/dist/apps/chat-ui/index.html +2 -2
- package/dist/apps/chat-vscode-web/assets/{index-Dp1TzeRL.js → index-C0sMILFt.js} +1 -1
- package/dist/apps/chat-vscode-web/index.html +1 -1
- package/dist/apps/vscode-artifacts/latest.vsix +0 -0
- package/dist/apps/vscode-artifacts/{pibo-vscode-ext-2.2.0.vsix → pibo-vscode-ext-2.2.2.vsix} +0 -0
- package/dist/core/profiles.js +9 -3
- package/dist/core/session-router.js +7 -1
- package/dist/plugins/registry.js +2 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/apps/chat-ui/assets/index-DUXboQnI.css +0 -1
|
@@ -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 gy(e){return typeof e==`object`&&!!e&&`languages`in e}var _y=globalThis,vy=gy(_y.Prism)?_y.Prism:hy.default;_y.Prism=vy,typeof window<`u`&&(window.Prism=vy);var yy;function by(){if(yy!==void 0)return yy;let e=Iy();if(!e)return yy=!1,yy;try{let t=new URL(e.location.href).searchParams.get(`debugStreaming`);yy=t===null?e.localStorage.getItem(`pibo.chat.debugStreaming`)===`1`:t!==`0`&&t!==`false`}catch{yy=!1}return yy}function xy(e,t){My(e,e=>{e.liveOpenCount+=1,e.lastReadyState=t})}function Sy(e,t){My(e,e=>{e.liveErrorCount+=1,e.lastReadyState=t})}function Cy(e,t,n,r){My(e,e=>{let i=Ry();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=jy(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+=Ly(t.delta)):t.type===`REASONING_MESSAGE_CONTENT`&&typeof t.delta==`string`&&(e.firstReasoningDeltaAt??=i,e.reasoningDeltaCount+=1,e.reasoningDeltaBytes+=Ly(t.delta))})}function wy(e,t,n,r){My(e,e=>{if(e.firstEnqueueAt??=Ry(),e.enqueueCount+=1,r&&(e.enqueueFlushImmediateCount+=1),e.pendingEventCount=n,t.streamFrameId){let n=jy(t.streamFrameId);n===`durable`?e.lastDurableCursor=t.streamFrameId:n===`transient`&&(e.lastTransientLiveId=t.streamFrameId)}})}function Ty(e,t,n){My(e,e=>{let r=Ry();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 Ey(e,t){My(e,e=>{let n=zy(t);e.liveTraceComputeCount+=1,e.liveTraceComputeDurationMsLast=n,e.liveTraceComputeDurationMsTotal+=n,e.liveTraceComputeDurationMsMax=Math.max(e.liveTraceComputeDurationMsMax??0,n)})}function Dy(e,t){Ny(n=>{let r=zy(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 Oy(e,t){My(e,e=>{e.traceRefreshScheduledCount+=1,e.lastTraceRefreshScheduledAt=Ry(),e.lastTraceRefreshDelayMs=t})}function ky(e,t){My(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 Ay(e){let t=Iy();if(!t?.__piboStreamingBenchmarkShouldDropOverlayEvent)return!1;try{return!!t.__piboStreamingBenchmarkShouldDropOverlayEvent(e)}catch{return!1}}function jy(e){return e?/^live:\d+$/.test(e)?`transient`:/^\d+:\d+$/.test(e)?`durable`:`other`:`missing`}function My(e,t){Ny(n=>{n.sessionIds.includes(e)||n.sessionIds.push(e),n.selectedPiboSessionId=e,t(n)})}function Ny(e){let t=Py();t&&(e(t),t.updatedAt=Ry())}function Py(){if(!by())return;let e=Iy();if(e)return e.__piboStreamingDebugReset||=()=>(e.__piboStreamingDebug=Fy(),e.__piboStreamingDebug),e.__piboStreamingDebug??=Fy(),e.__piboStreamingDebug}function Fy(){let e=Ry();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 Iy(){return typeof window>`u`?void 0:window}function Ly(e){return typeof TextEncoder<`u`?new TextEncoder().encode(e).byteLength:e.length}function Ry(){return new Date().toISOString()}function zy(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){function t(e){return e=e.replace(/<inner>/g,function(){return`(?:\\\\.|[^\\\\\\n\\r]|(?:\\n|\\r\\n?)(?![\\r\\n]))`}),RegExp(`((?:^|[^\\\\])(?:\\\\{2})*)(?:`+e+`)`)}var n="(?:\\\\.|``(?:[^`\\r\\n]|`(?!`))+``|`[^`\\r\\n]+`|[^\\\\|\\r\\n`])+",r=`\\|?__(?:\\|__)+\\|?(?:(?:\\n|\\r\\n?)|(?![\\s\\S]))`.replace(/__/g,function(){return n}),i=`\\|?[ \\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(`^`+r+i+`(?:`+r+`)*`,`m`),inside:{"table-data-rows":{pattern:RegExp(`^(`+r+i+`)(?:`+r+`)*$`),lookbehind:!0,inside:{"table-data":{pattern:RegExp(n),inside:e.languages.markdown},punctuation:/\|/}},"table-line":{pattern:RegExp(`^(`+r+`)`+i+`$`),lookbehind:!0,inside:{punctuation:/\||:?-{3,}:?/}},"table-header-row":{pattern:RegExp(`^`+r+`$`),inside:{"table-header":{pattern:RegExp(n),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:t(`\\b__(?:(?!_)<inner>|_(?:(?!_)<inner>)+_)+__\\b|\\*\\*(?:(?!\\*)<inner>|\\*(?:(?!\\*)<inner>)+\\*)+\\*\\*`),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^..)[\s\S]+(?=..$)/,lookbehind:!0,inside:{}},punctuation:/\*\*|__/}},italic:{pattern:t(`\\b_(?:(?!_)<inner>|__(?:(?!_)<inner>)+__)+_\\b|\\*(?:(?!\\*)<inner>|\\*\\*(?:(?!\\*)<inner>)+\\*\\*)+\\*`),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^.)[\s\S]+(?=.$)/,lookbehind:!0,inside:{}},punctuation:/[*_]/}},strike:{pattern:t(`(~~?)(?:(?!~)<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:t(`!?\\[(?:(?!\\])<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(c(t.content),s,n);else if(n&&n!==`none`&&e.plugins.autoloader){var l=`md-`+new Date().valueOf()+`-`+Math.floor(Math.random()*0x2386f26fc10000);t.attributes.id=l,e.plugins.autoloader.loadLanguages(n,function(){var t=document.getElementById(l);t&&(t.innerHTML=e.highlight(t.textContent,e.languages[n],n))})}}});var a=RegExp(e.languages.markup.tag.pattern.source,`gi`),o={amp:`&`,lt:`<`,gt:`>`,quot:`"`},s=String.fromCodePoint||String.fromCharCode;function c(e){var t=e.replace(a,``);return t=t.replace(/&(\w{1,8}|#x?[\da-f]{1,8});/gi,function(e,t){return t=t.toLowerCase(),t[0]===`#`?s(t[1]===`x`?parseInt(t.slice(2),16):Number(t.slice(1))):o[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 By=[`p`,`br`,`strong`,`em`,`a`,`ul`,`ol`,`li`,`blockquote`,`code`,`pre`,`h1`,`h2`,`h3`,`h4`,`hr`,`table`,`thead`,`tbody`,`tr`,`th`,`td`,`input`,`del`],Vy=[my],Hy=[],Uy=/[\n\r\\`*_\[\]<>]|~~/,Wy=/^\s*(?:#{1,6}\s|[-+>]|(?:\d+[.)]))\s/,Gy=/^\s*-{3,}\s*$/,Ky=/\b(?:https?:\/\/|www\.)|\S+@\S+\.\S+/i,qy=/^\s*[-+*]\s+\[[ xX]\]\s/m,Jy=/(^|\n)\s*\|?.+\|.+\n\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*(?:\n|$)/;function Yy(e){return e.length>0&&!Uy.test(e)&&!Wy.test(e)&&!Gy.test(e)&&!(Xy(e)&&Ky.test(e))}function Xy(e){return e.includes(`://`)||e.includes(`www.`)||e.includes(`@`)}function Zy(e){let t=Qy(e);return t?t.openerEnd>=e.length?e.slice(0,t.openerStart):`${e}\``:e}function Qy(e){let t=0;for(;t<e.length;){let n=e.indexOf("`",t);if(n===-1)return;if(tb(e,n)){t=n+1;continue}if(eb(e,n)!==1)return;let r=$y(e,n+1);if(r===-1)return{openerStart:n,openerEnd:n+1};t=r+1}}function $y(e,t){for(;t<e.length;){let n=e.indexOf("`",t);if(n===-1)return-1;let r=eb(e,n);if(r===1)return n;t=n+r}return-1}function eb(e,t){let n=t;for(;n<e.length&&e[n]==="`";)n+=1;return n-t}function tb(e,t){let n=0,r=t-1;for(;r>=0&&e[r]===`\\`;)n+=1,--r;return n%2==1}function nb(e){return e.includes(`~~`)||e.includes(`[`)&&qy.test(e)||e.includes(`|`)&&Jy.test(e)||Xy(e)&&Ky.test(e)}var rb=/[\n\r\\`*_\[\]<>]/,ib=/^\s*[-+*]\s+\[([ xX])\]\s+(.+?)\s*$/,ab=/[\n\r\\<>|~]/,ob=/[\n\r\\\[\]<>|~]/,sb=/[\s\[\]()`<>]/;function cb(e){if(!e.includes(`~~`)||rb.test(e)||Wy.test(e)||Gy.test(e)||Xy(e)&&Ky.test(e)||e.includes(`[`)&&qy.test(e)||e.includes(`|`)&&Jy.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,I.jsx)(`del`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`del`,children:s},`del-${r}`)),r+=1,n=a+2}return r>0?(0,I.jsx)(`p`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`p`,children:t}):void 0}function lb(e){if(!e||sb.test(e))return;let t=mg(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 ub(e,t){if(!e||ob.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("`")||Xy(t)&&Ky.test(t))return;t&&n.push(t);break}let p=e.slice(r,f);if(p.includes(`*`)||p.includes(`_`)||p.includes("`")||Xy(p)&&Ky.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,I.jsx)(`strong`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`strong`,children:(0,I.jsx)(`em`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`em`,children:e})},`link-${t}-strong-${i}`))}else n.push((0,I.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,I.jsx)(`em`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`em`,children:(0,I.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,I.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,I.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 db(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(`]`)||Xy(r)&&Ky.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(`]`)||Xy(f)&&Ky.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,I.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,I.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=ub(e.slice(d+1,r),a),s=lb(e.slice(r+2,i));if(!s||!o)return;t.push((0,I.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 fb(e){let t=ib.exec(e);if(!t)return;let n=t[2];if(!n||ab.test(n))return;let r=db(n);if(!r)return;let i=t[1].toLowerCase()===`x`;return(0,I.jsx)(`ul`,{className:`contains-task-list`,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`ul`,children:(0,I.jsxs)(`li`,{className:`task-list-item`,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`li`,children:[(0,I.jsx)(`input`,{type:`checkbox`,checked:i,readOnly:!0,disabled:!0,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`input`}),r]})})}var pb={p({children:e,node:t,...n}){return(0,I.jsx)(`p`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`p`,...n,children:e})},ul({children:e,node:t,...n}){return(0,I.jsx)(`ul`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`ul`,...n,children:e})},ol({children:e,node:t,...n}){return(0,I.jsx)(`ol`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`ol`,...n,children:e})},li({children:e,node:t,...n}){return(0,I.jsx)(`li`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`li`,...n,children:e})},blockquote({children:e,node:t,...n}){return(0,I.jsx)(`blockquote`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`blockquote`,...n,children:e})},pre({children:e,node:t,...n}){return(0,I.jsx)(`pre`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`pre`,...n,children:e})},a({href:e,children:t}){return(0,I.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=mb(e),a=String(t).replace(/\n$/,``);if(!i)return(0,I.jsx)(`code`,{className:e,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`code`,...r,children:t});let o=vy.languages[i];return o?(0,I.jsx)(`code`,{className:`language-${i}`,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`code`,dangerouslySetInnerHTML:{__html:vy.highlight(a,o,i)},...r}):(0,I.jsx)(`code`,{className:e,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`code`,...r,children:t})},th({children:e,node:t,...n}){return(0,I.jsx)(`th`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`th`,...n,children:e})},td({children:e,node:t,...n}){return(0,I.jsx)(`td`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`td`,...n,children:e})},input({checked:e,node:t,...n}){return(0,I.jsx)(`input`,{type:`checkbox`,checked:!!e,readOnly:!0,disabled:!0,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`input`,...n})}};function mb(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 hb(e,t){t!==void 0&&Dy(e,(typeof performance>`u`?Date.now():performance.now())-t)}var gb=(e,t,n)=>{if(n.tagName!==`a`||t!==`href`)return``;let r=mg(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``}},_b=(0,v.memo)(function({children:e,streaming:t=!1}){let n=by()?typeof performance>`u`?Date.now():performance.now():void 0,r=t?Zy(e):e,i=`commonmark`,a;if(Yy(r))i=`plain`,a=(0,I.jsx)(`p`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`p`,children:r});else{let e=nb(r),t=e?cb(r)??fb(r):void 0;t?(i=`gfm-fast`,a=t):(i=e?`gfm`:`commonmark`,a=ug({allowedElements:By,children:r,components:pb,remarkPlugins:e?Vy:Hy,skipHtml:!0,urlTransform:gb}))}return hb(i,n),a}),vb={"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`}},yb=12;function bb(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)(()=>bb(r,i)),[d,f]=(0,v.useState)(()=>t.spanType===`model.reasoning`?o:bb(r,i));(0,v.useEffect)(()=>{let e=bb(r,i);u(e),f(t.spanType===`model.reasoning`?o:e)},[r,i,a,o,t.spanType]),vb[t.spanType]||vb[`agent.run`],t.status,t.status,t.spanType===`user.prompt`||t.spanType;let p=!!t.children?.length;Nb(t.startTime,n),t.durationUs?`${(t.durationUs/1e3).toFixed(1)}`:t.endTime&&`${((t.endTime-t.startTime)/1e3).toFixed(1)}`;let m=(0,v.useCallback)(()=>{f(e=>!e),p&&u(e=>!e)},[p]);return(0,I.jsx)(xb,{span:t,startTime:n,depth:r,contentExpanded:d,childrenExpanded:l,onToggle:m,onFork:s,onOpenSession:c,childrenContent:p?t.children?.map(t=>(0,I.jsx)(e,{span:t,startTime:n,depth:r+1,expansionDepth:i,expansionSignal:a,expandThinking:o,onFork:s,onOpenSession:c},t.id)):void 0})});var xb=(0,v.memo)(function({span:e,startTime:t,depth:n=0,contentExpanded:r,childrenExpanded:i,onToggle:a,onFork:o,onOpenSession:s,signals:c,childrenContent:l}){let u=vb[e.spanType]||vb[`agent.run`],d=e.status===`UNSET`,f=Ab(e.status,d),p=e.spanType===`user.prompt`||e.spanType===`user_input`,m=!!e.children?.length,h=Nb(e.startTime,t),g=e.durationUs?`${(e.durationUs/1e3).toFixed(1)}ms`:e.endTime?`${((e.endTime-e.startTime)/1e3).toFixed(1)}ms`:null;return e.spanType===`agent.delegation`?(0,I.jsx)(`div`,{className:`relative mb-4`,"data-pibo-debug":`trace-span`,"data-trace-node-id":e.id,"data-span-type":e.spanType,"data-span-status":e.status,"data-order-source":e.pibo?.source,"data-stable-key":e.pibo?.stableKey,style:{marginLeft:n>0?yb:0,width:n>0?`calc(100% - ${yb}px)`:`var(--trace-readable-width)`,maxWidth:`100%`},children:(0,I.jsx)(Sl,{title:e.name,summary:typeof e.attributes.content==`string`?e.attributes.content:void 0,input:e.attributes.input??e.attributes.arguments,output:e.attributes.output??e.attributes.result,error:e.statusMessage,traceStatus:e.status===`UNSET`?`running`:e.status===`ERROR`?`error`:`done`,linkedPiboSessionId:e.pibo?.linkedPiboSessionId,startedAt:new Date(e.startTime/1e3).toISOString(),completedAt:e.endTime?new Date(e.endTime/1e3).toISOString():void 0,durationMs:e.durationUs===void 0?void 0:e.durationUs/1e3,signals:c,onOpenSession:s})}):(0,I.jsx)(`div`,{className:`relative mb-4 group`,"data-pibo-debug":`trace-span`,"data-trace-node-id":e.id,"data-span-type":e.spanType,"data-span-status":e.status,"data-order-source":e.pibo?.source,"data-stable-key":e.pibo?.stableKey,style:{marginLeft:n>0?yb:0,width:n>0?`calc(100% - ${yb}px)`:`var(--trace-readable-width)`,maxWidth:`100%`},children:(0,I.jsxs)(`div`,{className:`min-w-0 ${p?`bg-[#11a4d4]/10`:`bg-white dark:bg-[#1a262b]`} border ${f.cardClass} rounded-sm shadow-sm transition-all hover:border-opacity-70 focus:outline-none focus:ring-1 focus:ring-[#11a4d4]/50 ${d?f.glowClass:``}`,onDoubleClick:e=>{Sb(e)||a()},onKeyDown:e=>{Sb(e)||(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),a())},role:`button`,tabIndex:0,"aria-expanded":r,children:[(0,I.jsx)(Cb,{span:e,config:u,statusStyles:f,isActive:d,contentExpanded:r,duration:g,relativeTime:h,onToggle:a,onFork:o,onOpenSession:s}),r?(0,I.jsx)(Eb,{span:e}):null,m&&i&&r?(0,I.jsx)(`div`,{className:`min-w-0 border-t border-slate-700 bg-slate-900/50 py-4`,children:l}):null]})})});function Sb(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 Cb({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,d=`${i?`border-b ${t.borderColor}/20`:``} ${u}`;return(0,I.jsx)(`div`,{className:d,children:(0,I.jsxs)(`div`,{className:`box-border flex w-full min-w-0 items-center`,style:{maxWidth:`100%`},children:[(0,I.jsx)(`div`,{className:`min-w-0 flex-1 px-4 py-2 text-left`,children:(0,I.jsxs)(`span`,{className:`min-w-0 text-xs font-bold ${t.color} uppercase tracking-wider flex items-center gap-2`,children:[i?(0,I.jsx)(Ne,{size:12}):(0,I.jsx)(Pe,{size:12}),(0,I.jsx)(wb,{spanType:e.spanType,config:t,isActive:r}),(0,I.jsx)(`span`,{className:`shrink-0`,children:t.label}),e.name?(0,I.jsxs)(`span`,{className:`min-w-0 truncate font-normal text-slate-500 dark:text-slate-400 normal-case`,children:[`: `,e.name]}):null,r?(0,I.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-[#11a4d4] animate-pulse`}):null]})}),(0,I.jsx)(Db,{forkEntryId:e.pibo?.traceNodeType===`user.message`?e.pibo.entryId:void 0,linkedPiboSessionId:e.pibo?.linkedPiboSessionId,onFork:c,onOpenSession:l}),(0,I.jsx)(Tb,{duration:a,relativeTime:o})]})})}function wb({spanType:e,config:t,isActive:n}){return(0,I.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,I.jsx)(kb,{type:e,className:t.color}),n?(0,I.jsx)(`span`,{className:`absolute -right-0.5 -top-0.5 h-1.5 w-1.5 rounded-full bg-[#11a4d4] animate-pulse`}):null]})}function Tb({duration:e,relativeTime:t}){return(0,I.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,I.jsx)(`span`,{className:`text-[10px] text-slate-500 dark:text-slate-400`,children:e}):null,(0,I.jsx)(`span`,{className:`text-xs text-slate-400 dark:text-slate-500`,children:t})]})}var Eb=(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=Mb(i[`message.pending_delivery`]),f=e.status===`ERROR`?(0,I.jsxs)(`div`,{className:`mx-4 mt-4 p-3 bg-red-500/10 border border-red-500/20 rounded-sm text-xs`,children:[(0,I.jsx)(`div`,{className:`flex items-center gap-2 font-semibold text-red-500 mb-1`,children:`Error`}),e.statusMessage?(0,I.jsx)(`div`,{className:`font-mono text-red-400 mb-2`,children:e.statusMessage}):null]}):null;if(r===`user.prompt`||r===`user_input`)return(0,I.jsxs)(`div`,{className:`flex flex-col`,children:[f,(0,I.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)}),d===`queue`||d===`steer`?(0,I.jsx)(kl,{delivery:d,className:`mx-4 mb-4`}):null]});if(r===`model.response`)return(0,I.jsxs)(`div`,{className:`flex flex-col`,children:[f,(0,I.jsx)(`div`,{className:`model-response-markdown min-w-0 p-4 text-sm text-slate-200 leading-relaxed`,children:typeof o==`string`?(0,I.jsx)(_b,{children:o}):(0,I.jsx)(bl,{value:o})})]});if(r===`tool.result`)return(0,I.jsxs)(`div`,{className:`flex flex-col`,children:[f,(0,I.jsxs)(`div`,{className:`p-4 bg-green-500/5 border-t border-green-500/20`,children:[(0,I.jsxs)(`div`,{className:`text-xs font-medium text-green-400 mb-2`,children:[`Returned from `,c||a,`:`]}),(0,I.jsx)(bl,{value:l??o})]})]});if(r===`tool.call`){let e=Pb(u)?u:{},r=Object.keys(e).length>0;return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(`div`,{className:`p-4 bg-[#0e1116] border-b border-slate-800`,children:(0,I.jsx)(Ob,{name:c??a,args:e})}),l==null?null:(0,I.jsxs)(`div`,{className:`px-4 py-2 bg-[#1a262b] flex items-center gap-2`,children:[(0,I.jsx)(we,{size:14,className:`text-slate-400`}),(0,I.jsx)(`span`,{className:`text-xs font-mono text-slate-500`,children:`Output:`}),(0,I.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,I.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,I.jsx)(Xe,{size:12}):(0,I.jsx)(Ze,{size:12}),t?`Hide Details`:`Show Details`]}),t?(0,I.jsxs)(`div`,{className:`border-t border-slate-700/40 bg-[#0e1116]`,children:[r?(0,I.jsxs)(`div`,{className:`px-4 pt-3 pb-2`,children:[(0,I.jsx)(`div`,{className:`text-[10px] font-semibold text-blue-400 uppercase tracking-wider mb-1.5`,children:`Input`}),(0,I.jsx)(bl,{value:e})]}):null,l==null?null:(0,I.jsxs)(`div`,{className:`px-4 pt-2 pb-3 border-t border-slate-700/30`,children:[(0,I.jsx)(`div`,{className:`text-[10px] font-semibold text-green-400 uppercase tracking-wider mb-1.5`,children:`Output`}),(0,I.jsx)(bl,{value:l})]})]}):null,f]})}if(r===`yielded.run`){let e=Pb(l)?l:Pb(o)?o:{};return(0,I.jsxs)(`div`,{className:`flex flex-col`,children:[f,(0,I.jsxs)(`div`,{className:`p-4 border-b border-[#11a4d4]/20 bg-[#11a4d4]/5`,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,I.jsx)(Ee,{size:14,className:`text-[#11a4d4]`}),(0,I.jsx)(`span`,{className:`text-sm font-medium text-[#11a4d4]`,children:`Run notification`}),(0,I.jsx)(`span`,{className:`text-xs font-mono text-slate-400`,children:typeof i.content==`string`?i.content:a})]}),(0,I.jsx)(jb,{notification:e})]}),(0,I.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,I.jsx)(Xe,{size:12}):(0,I.jsx)(Ze,{size:12}),t?`Hide Details`:`Show Details`]}),t?(0,I.jsx)(`div`,{className:`border-t border-slate-700/40 bg-[#0e1116] px-4 py-3`,children:(0,I.jsx)(bl,{value:e})}):null]})}if(r===`model.reasoning`){let e=i.reasoning||i[`model.reasoning`]||o;return(0,I.jsxs)(`div`,{className:`flex flex-col`,children:[f,(0,I.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,I.jsx)(`span`,{className:`text-amber-500 opacity-60`,children:`// Model reasoning`}),(0,I.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,I.jsxs)(I.Fragment,{children:[f,(0,I.jsxs)(`div`,{className:`p-4 border-b border-orange-500/20 bg-orange-500/5`,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,I.jsx)(et,{size:14,className:`text-orange-500`}),(0,I.jsx)(`span`,{className:`text-sm font-medium text-orange-500`,children:`Delegated to:`}),(0,I.jsxs)(`span`,{className:`text-sm font-semibold text-slate-200`,children:[e||`unknown`,` agent`]}),n?(0,I.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,I.jsxs)(`div`,{className:`text-xs text-slate-400 font-mono italic line-clamp-2`,children:[`"`,Fb(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,I.jsxs)(I.Fragment,{children:[f,(0,I.jsxs)(`div`,{className:`p-4 border-b border-orange-500/20 bg-orange-500/5`,children:[(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 mb-2`,children:[(0,I.jsx)(et,{size:14,className:`text-orange-500`}),(0,I.jsx)(`span`,{className:`text-sm font-medium text-orange-500`,children:`Async agent started:`}),(0,I.jsxs)(`span`,{className:`text-sm font-semibold text-slate-200`,children:[e||`unknown`,` agent`]}),a?(0,I.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,I.jsxs)(`div`,{className:`mb-2 flex flex-wrap gap-x-3 gap-y-1 font-mono text-[11px] text-slate-500`,children:[(0,I.jsxs)(`span`,{children:[`Started by `,n||`pibo_run_start`]}),r?(0,I.jsx)(`span`,{children:r}):null]}),t?(0,I.jsxs)(`div`,{className:`text-xs text-slate-400 font-mono italic line-clamp-2`,children:[`"`,Fb(t),`"`]}):null]})]})}return r===`agent.run`?(0,I.jsx)(`div`,{className:`flex flex-col`,children:f}):(0,I.jsxs)(`div`,{className:`flex flex-col`,children:[f,(0,I.jsx)(`div`,{className:`p-4 font-mono text-sm text-slate-300`,children:(0,I.jsx)(bl,{value:i})})]})});function Db({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,I.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[i?(0,I.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,I.jsx)(et,{size:14})}):null,a?(0,I.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,I.jsx)(Ye,{size:14})}):null]})}function Ob({name:e,args:t}){return(0,I.jsxs)(`code`,{className:`font-mono text-xs text-green-400`,children:[(0,I.jsx)(`span`,{className:`text-purple-400`,children:`def`}),` `,(0,I.jsx)(`span`,{className:`text-yellow-300`,children:e}),(0,I.jsxs)(`span`,{children:[`(`,Object.entries(t).map(([e,t],n)=>(0,I.jsxs)(`span`,{children:[n>0?`, `:null,(0,I.jsx)(`span`,{className:`text-blue-400`,children:e}),`=`,(0,I.jsx)(`span`,{className:`text-green-300`,children:typeof t==`string`?`'${t.slice(0,50)}${t.length>50?`...`:``}'`:Fb(t).slice(0,50)})]},e)),`)`]})]})}function kb({type:e,className:t}){let n={size:14,className:t};switch(e){case`agent.run`:return(0,I.jsx)(Ae,{...n});case`tool.call`:return(0,I.jsx)(De,{...n});case`tool.result`:return(0,I.jsx)(we,{...n});case`model.request`:return(0,I.jsx)(ke,{...n});case`model.response`:return(0,I.jsx)(we,{...n});case`model.reasoning`:return(0,I.jsx)(ot,{...n});case`agent.delegation`:return(0,I.jsx)(et,{...n});case`agent.async`:return(0,I.jsx)(et,{...n});case`yielded.run`:return(0,I.jsx)(Ee,{...n});case`user.prompt`:return(0,I.jsx)(dt,{...n});case`user_input`:return(0,I.jsx)(wt,{...n});case`execution.command`:return(0,I.jsx)(De,{...n});default:return(0,I.jsx)(Me,{...n})}}function Ab(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 jb({notification:e}){let t=[[`completed`,`text-green-500`,e.completed],[`failed`,`text-red-400`,e.failed],[`timed out`,`text-amber-400`,e.timedOut],[`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(Pb):[]})).filter(e=>e.runs.length>0);return t.length===0?(0,I.jsx)(`div`,{className:`text-xs text-slate-400`,children:`No yielded run updates.`}):(0,I.jsx)(`div`,{className:`grid gap-2`,children:t.map(e=>(0,I.jsxs)(`div`,{children:[(0,I.jsx)(`div`,{className:`mb-1 text-[10px] font-bold uppercase tracking-wider ${e.color}`,children:e.name}),(0,I.jsx)(`div`,{className:`grid gap-1`,children:e.runs.map((t,n)=>(0,I.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,I.jsxs)(`div`,{className:`min-w-0`,children:[(0,I.jsx)(`div`,{className:`truncate font-mono text-xs text-slate-200`,children:Mb(t.toolName)||`yielded tool`}),(0,I.jsx)(`div`,{className:`truncate font-mono text-[10px] text-slate-500`,children:Mb(t.runId)})]}),(0,I.jsx)(`div`,{className:`font-mono text-[10px] uppercase text-slate-400`,children:Mb(t.status)||e.name})]},`${e.name}-${n}`))})]},e.name))})}function Mb(e){return typeof e==`string`?e:``}function Nb(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 Pb(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Fb(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}var Ib=5e3,Lb=0,Rb=new Map,zb=0;function Bb(e){let t=Rb.get(e);return t||(t={snapshots:[],pending:null,pendingTimer:null},Rb.set(e,t)),t}function Vb(){if(typeof window<`u`&&window.__piboTraceSnapshotCollectionEnabled===!0)return!0;try{return localStorage.getItem(`pibo.chat.traceDebug`)===`true`}catch{return!1}}function Hb(e){let t=0;for(let n of e)for(let e=0;e<n.length;e++)t=(t<<5)-t+n.charCodeAt(e),t|=0;return t.toString(36)}function Ub(e){return Hb([JSON.stringify(e)])}function Wb(e){return JSON.stringify({trigger:e.trigger,traceVersion:e.traceVersion,baseTraceVersion:e.baseTraceVersion,latestStreamId:e.latestStreamId,lastRawEventId:e.lastRawEventId,selectedSessionStatus:e.selectedSessionStatus,overlayEventCount:e.overlayEventCount,layers:e.layers.map(e=>[e.kind,e.digest])})}function Gb(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||Wb(n)!==Wb(t))&&(e.snapshots.push(t),e.snapshots.length>Ib&&e.snapshots.shift()),e.pending=null}function Kb(e){if(!Vb())return;let t=Bb(e.piboSessionId);t.pendingTimer&&=(clearTimeout(t.pendingTimer),null);let n=e.layer&&t.pending?.layers?.find(t=>t.kind===e.layer.kind),r=t.pending&&nx(t.pending.traceVersion,e.traceVersion)&&nx(t.pending.baseTraceVersion,e.baseTraceVersion)&&nx(t.pending.latestStreamId,e.latestStreamId)&&nx(t.pending.lastRawEventId,e.lastRawEventId)&&nx(t.pending.selectedSessionStatus,e.selectedSessionStatus)&&nx(t.pending.overlayEventCount,e.overlayEventCount);if(t.pending&&t.pending.trigger===e.trigger&&t.pending.piboSessionId===e.piboSessionId&&r&&(!n||n.digest===e.layer?.digest)||Gb(t),t.pending||={sequence:++zb,timestamp:Date.now(),piboSessionId:e.piboSessionId,trigger:e.trigger,layers:[],expansionOverrides:e.expansionOverrides,traceVersion:e.traceVersion,baseTraceVersion:e.baseTraceVersion,latestStreamId:e.latestStreamId,lastRawEventId:e.lastRawEventId,selectedSessionStatus:e.selectedSessionStatus,overlayEventCount:e.overlayEventCount},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),e.traceVersion!==void 0&&(t.pending.traceVersion=e.traceVersion),e.baseTraceVersion!==void 0&&(t.pending.baseTraceVersion=e.baseTraceVersion),e.latestStreamId!==void 0&&(t.pending.latestStreamId=e.latestStreamId),e.lastRawEventId!==void 0&&(t.pending.lastRawEventId=e.lastRawEventId),e.selectedSessionStatus!==void 0&&(t.pending.selectedSessionStatus=e.selectedSessionStatus),e.overlayEventCount!==void 0&&(t.pending.overlayEventCount=e.overlayEventCount),t.pendingTimer=setTimeout(()=>{Gb(t),t.pendingTimer=null},Lb)}function qb(e){let t={traceVersion:e.currentTraceView.version,baseTraceVersion:e.baseTraceView?.version,latestStreamId:e.currentTraceView.latestStreamId,lastRawEventId:e.currentTraceView.rawEvents.at(-1)?.id,selectedSessionStatus:e.selectedSessionStatus,overlayEventCount:e.overlayEvents.length};Jb(e.piboSessionId,e.trigger,`baseNodes`,e.baseTraceView?.nodes??[],t),Yb(e.piboSessionId,e.trigger,e.overlayEvents,t),Jb(e.piboSessionId,e.trigger,`currentNodes`,e.currentTraceView.nodes,t)}function Jb(e,t,n,r,i){let a=rx(r).map(ix);Kb({piboSessionId:e,trigger:t,layer:{kind:n,ids:a.map(e=>e.id),digest:Ub(a),meta:a},...i})}function Yb(e,t,n,r){let i=n.map(e=>({id:e.id,type:e.type,eventId:e.eventId,eventSequence:e.eventSequence,streamId:e.streamId,streamFrameIndex:e.streamFrameIndex}));Kb({piboSessionId:e,trigger:t,layer:{kind:`overlayEvents`,ids:i.map(e=>e.id),digest:Ub(i),meta:i},...r})}function Xb(e,t,n,r){let i=n.map(e=>({id:e.id,kind:e.kind,status:e.status,sourceNodeIds:[...e.sourceNodeIds],eventId:e.eventId,runId:e.runId,orderSource:e.orderSource,orderStreamId:e.orderStreamId,orderStreamFrameIndex:e.orderStreamFrameIndex}));Kb({piboSessionId:e,trigger:t,layer:{kind:`terminalRows`,ids:i.map(e=>e.id),digest:Ub(i),meta:i},...r})}function Zb(e){let t=Rb.get(e);return t?(Gb(t),t.snapshots):[]}function Qb(e){let t=Rb.get(e);return t?.pending?.sequence??t?.snapshots.at(-1)?.sequence}function $b(e){if(e)return JSON.stringify({piboSessionId:e,snapshots:Zb(e)},null,2);let t={};for(let[e,n]of Rb)Gb(n),t[e]=n.snapshots;return JSON.stringify(t,null,2)}function ex(e){if(e){tx(Rb.get(e)),Rb.delete(e);return}for(let e of Rb.values())tx(e);Rb.clear()}function tx(e){e?.pendingTimer&&(clearTimeout(e.pendingTimer),e.pendingTimer=null)}function nx(e,t){return t===void 0||e===void 0||e===t}function rx(e){return e.flatMap(e=>[e,...rx(e.children??[])])}function ix(e){let t=ox(e);return{id:e.id,type:e.type,status:e.status,parentId:e.parentId,childIds:e.children.map(e=>e.id),entryId:e.entryId,eventId:e.eventId,toolCallId:e.toolCallId,runId:e.runId,stableKey:e.stableKey,source:e.source,orderKey:e.orderKey,contentLength:t.length,contentKind:ax(t)}}function ax(e){return e.startsWith(`<pibo_run_notification>`)?`pibo-run-notification`:e.startsWith(`<pibo_goal_continuation>`)?`pibo-goal-continuation`:e.startsWith(`<pibo_`)?`pibo-system`:`message`}function ox(e){return typeof e.output==`string`?e.output:typeof e.summary==`string`?e.summary:e.output&&typeof e.output==`object`&&`text`in e.output&&typeof e.output.text==`string`?e.output.text:``}typeof window<`u`&&(window.__piboTraceSnapshots={exportAsJson:e=>{let t=$b(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:Zb,getLatestSequence:Qb,clearSnapshots:ex,exportSnapshots:$b});function sx(e,t={}){if(!e)return cx(t);let n=e.latestTurn,r=n?.state===`running`,i=e.isTreeActive||r;return{status:e.hasError||e.hasErrorDescendant||e.aggregateStatus===`error`?`error`:i?`running`:`idle`,isTreeActive:i,isTurnActive:r,activeTurnId:r?n.eventId:void 0,activeTurnStartedAt:r?n.startedAt:void 0,latestTurn:n,source:`signals`}}function cx(e){let t=e.status===`running`&&lx(e.turnStartedAt);return{status:e.status??`idle`,isTreeActive:e.status===`running`,isTurnActive:t,activeTurnStartedAt:t?e.turnStartedAt:void 0,source:`fallback`}}function lx(e){return!!(e&&Number.isFinite(Date.parse(e)))}function ux({signal:e,fallbackStatus:t,fallbackTurnStartedAt:n}){return(0,v.useMemo)(()=>sx(e,{status:t,turnStartedAt:n}),[t,n,e])}function dx({goal:e}){let t=px(e),[n,r]=(0,v.useState)(()=>Date.now());return(0,v.useEffect)(()=>{if(r(Date.now()),!t||e?.state.goalEndedAt)return;let n=window.setInterval(()=>r(Date.now()),1e3);return()=>window.clearInterval(n)},[e?.id,e?.state.goalEndedAt,t]),(0,I.jsx)(fx,{goal:e,nowMs:n})}function fx({goal:e,nowMs:t}){let n=px(e);if(!e||!n)return null;let r=n===`active`?`Pursuing Goal`:`Goal Paused`,i=n===`active`?`text-fuchsia-400`:`text-amber-300`,a=mx(e,t);return(0,I.jsxs)(`span`,{className:`inline-flex shrink-0 items-center gap-2 font-sans text-sm font-semibold ${i}`,"data-pibo-debug":`session-goal-indicator`,"data-goal-id":e.id,"data-goal-status":n,title:`${e.name}: ${e.prompt}`,children:[(0,I.jsx)(bt,{size:17,className:n===`active`?`animate-pulse`:``,"aria-hidden":`true`}),(0,I.jsxs)(`span`,{children:[r,`:`]}),(0,I.jsx)(`span`,{className:`tabular-nums`,children:a})]})}function px(e){if(!e||e.mode!==`goal`)return;let t=e.state.goalStatus??(e.enabled?`active`:`paused`);return t===`active`||t===`paused`?t:void 0}function mx(e,t){let n=e.state.goalStartedAt?Date.parse(e.state.goalStartedAt):NaN,r=e.state.goalEndedAt?Date.parse(e.state.goalEndedAt):t,i=Number.isFinite(n)&&Number.isFinite(r)?Math.max(0,Math.floor((r-n)/1e3)):0,a=Math.floor(i/3600),o=Math.floor(i%3600/60),s=i%60;return a>0?`${a}:${String(o).padStart(2,`0`)}:${String(s).padStart(2,`0`)}`:`${o}:${String(s).padStart(2,`0`)}`}function hx(e){if(e==null)return{kind:`empty`};let t=gx(e);return t===void 0?{kind:`json`,value:e}:{kind:`text`,text:t}}function gx(e){if(typeof e==`string`)return e;if(Array.isArray(e)){let t=e.map(gx).filter(e=>e!==void 0);return t.length===e.length&&t.length>0?t.join(``):void 0}if(!vx(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=gx(e.content);if(n!==void 0&&_x(e))return n;let r=vx(e.message)?gx(e.message.content):void 0;if(r!==void 0)return r}function _x(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 vx(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}async function yx(e,t,n){let r=new URLSearchParams({piboSessionId:e}),i=await fetch(`/api/chat/trace/summary?${r.toString()}`,{headers:t?{"if-none-match":Cx(t)}:void 0,signal:n?.signal});if(i.status===304)return{notModified:!0,version:wx(i.headers.get(`etag`))??t};let a=await i.json().catch(()=>void 0);if(!i.ok){let e=a&&typeof a==`object`&&`error`in a?String(a.error):`Request failed`,t=Error(e);throw t.status=i.status,t.data=a,t}return{summary:a,notModified:!1,version:wx(i.headers.get(`etag`))??a.version}}async function bx(e,t={}){let n=new URLSearchParams({piboSessionId:e});t.limit&&n.set(`limit`,String(t.limit)),t.beforeCursor===void 0?t.beforeSequence!==void 0&&n.set(`before`,String(t.beforeSequence)):n.set(`before`,String(t.beforeCursor));let r=await fetch(`/api/chat/trace/timeline?${n.toString()}`,{headers:t.knownVersion?{"if-none-match":Cx(t.knownVersion)}:void 0,signal:t.signal});if(r.status===304)return{notModified:!0,version:wx(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{timeline:i,notModified:!1,version:wx(r.headers.get(`etag`))??i.version}}async function xx(e,t={}){let n=new URLSearchParams({piboSessionId:e});return t.limit&&n.set(`limit`,String(t.limit)),t.beforeSequence!==void 0&&n.set(`before`,String(t.beforeSequence)),A(`/api/chat/trace/raw-events?${n.toString()}`,{signal:t.signal})}async function Sx(e,t={}){let n=new URLSearchParams;t.offset!==void 0&&n.set(`offset`,String(t.offset)),t.limit!==void 0&&n.set(`limit`,String(t.limit));let r=n.toString();return A(`/api/chat/trace/payload/${encodeURIComponent(e)}${r?`?${r}`:``}`)}function Cx(e){return`"${e}"`}function wx(e){if(!e)return;let t=e.trim();return t.startsWith(`W/`)?wx(t.slice(2)):t.startsWith(`"`)&&t.endsWith(`"`)?t.slice(1,-1):t}function Tx({row:e,onOpenSession:t}){return(0,I.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,I.jsx)(`div`,{className:`space-y-3`,children:e.detailItems.map(e=>(0,I.jsxs)(`div`,{className:`space-y-2`,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px]`,children:[(0,I.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:e.label}),e.linkedPiboSessionId?(0,I.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,I.jsx)(Ox,{label:`Input`,value:e.input}),(0,I.jsx)(Ox,{label:`Output`,value:e.output}),(0,I.jsx)(Ex,{refs:e.payloadRefs}),(0,I.jsx)(kx,{value:e.output}),e.error?(0,I.jsx)(Mx,{label:`Error`,value:e.error,tone:`red`}):null]},e.id))}):(0,I.jsxs)(`div`,{className:`space-y-3`,children:[(0,I.jsx)(Ox,{label:`Input`,value:e.input}),(0,I.jsx)(Ox,{label:`Output`,value:e.output}),(0,I.jsx)(Ex,{refs:e.payloadRefs}),(0,I.jsx)(kx,{value:e.output}),e.error?(0,I.jsx)(Mx,{label:`Error`,value:e.error,tone:`red`}):null,e.linkedPiboSessionId?(0,I.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px]`,children:[(0,I.jsx)(`span`,{className:`text-[#737373]`,children:`Child session`}),(0,I.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 Ex({refs:e}){if(!e)return null;let t=Object.entries(e).filter(e=>!!e[1]);return t.length?(0,I.jsx)(`div`,{className:`space-y-2`,children:t.map(([e,t])=>(0,I.jsx)(Dx,{kind:e,refInfo:t},`${e}:${t.ref}`))}):null}function Dx({kind:e,refInfo:t}){let[n,r]=(0,v.useState)({status:`loading`});return(0,v.useEffect)(()=>{let e=!1;return r({status:`loading`}),Sx(t.ref,{offset:0,limit:65536}).then(t=>{e||r({status:`loaded`,data:t.data,hasMore:t.hasMore,nextOffset:t.nextOffset})}).catch(t=>{e||r({status:`error`,message:t instanceof Error?t.message:String(t)})}),()=>{e=!0}},[t.ref]),(0,I.jsxs)(`div`,{className:`space-y-1`,"data-shared-terminal-payload-ref":e,children:[(0,I.jsxs)(`div`,{className:`text-[11px] font-semibold text-[#737373]`,children:[e,` payload (`,Math.ceil(t.byteLength/1024),` KB)`]}),n.status===`loading`?(0,I.jsx)(`div`,{className:`border border-[#2a2a2a] bg-[#0b0b0b] p-2 text-[12px] text-[#737373]`,children:`Loading payload preview...`}):n.status===`error`?(0,I.jsx)(`div`,{className:`border border-[#2a2a2a] bg-[#0b0b0b] p-2 text-[12px] text-[#ef4444]`,children:n.message}):(0,I.jsxs)(`div`,{className:`space-y-1`,children:[(0,I.jsx)(`pre`,{className:`m-0 max-h-[520px] overflow-auto whitespace-pre-wrap break-words border border-[#2a2a2a] bg-[#0b0b0b] p-2 font-mono text-[12px] leading-[1.45] text-[#d4d4d4]`,children:n.data}),n.hasMore?(0,I.jsx)(`div`,{className:`text-[11px] text-[#737373]`,children:`Showing first chunk. More payload data is available on demand.`}):null]})]})}function Ox({label:e,value:t}){let n=hx(t);if(n.kind===`empty`)return null;if(n.kind===`text`){let t=Nx(n.text);return t?.kind===`json`?(0,I.jsx)(jx,{label:e,value:t.value,meta:t.meta}):t?.kind===`text`?(0,I.jsx)(Mx,{label:e,value:t.text}):(0,I.jsx)(Mx,{label:e,value:n.text})}return(0,I.jsx)(jx,{label:e,value:n.value})}function kx({value:e}){let t=Ax(e);return t?(0,I.jsxs)(`details`,{className:`space-y-1 border border-[#2a2a2a] bg-[#0b0b0b] p-2`,children:[(0,I.jsxs)(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-[#38bdf8]`,children:[`Show full output (`,t.originalLines,` lines)`]}),t.fullOutput?(0,I.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,I.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 Ax(e){if(!Ix(e))return;let t=Ix(e.details)?e.details.piboBashOutputCompaction:void 0;if(!Ix(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 jx({label:e,value:t,meta:n}){return(0,I.jsxs)(`div`,{className:`space-y-1`,"data-shared-terminal-detail-json":e,children:[(0,I.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,I.jsx)(`div`,{className:`text-[11px] font-semibold text-[#737373]`,"data-shared-terminal-detail-label":e,children:e}),n?(0,I.jsxs)(`div`,{className:`min-w-0 break-words text-[11px] text-[#737373]`,children:[`Status: `,n]}):null]}),(0,I.jsx)(`div`,{className:`compact-terminal-json border border-[#2a2a2a] bg-[#0b0b0b] p-2`,children:(0,I.jsx)(bl,{value:t,showControls:!1})})]})}function Mx({label:e,value:t,tone:n=`default`}){return(0,I.jsxs)(`div`,{className:`space-y-1`,"data-shared-terminal-detail-text":e,children:[(0,I.jsx)(`div`,{className:`text-[11px] font-semibold text-[#737373]`,"data-shared-terminal-detail-label":e,children:e}),(0,I.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 Nx(e){let t=e.trim();if(!t)return;let n=Fx(t);if(n!==void 0)return Px(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=Fx(t);if(n!==void 0)return Px(n,r.slice(0,e).join(` `).trim()||void 0)}}function Px(e,t){let n=hx(e);if(n.kind===`text`){let e=Nx(n.text);return e?.kind===`json`?{...e,meta:e.meta??t}:{kind:`text`,text:n.text}}return{kind:`json`,value:e,meta:t}}function Fx(e){if(!(!e.startsWith(`{`)&&!e.startsWith(`[`)))try{let t=JSON.parse(e);return typeof t==`object`&&t?t:void 0}catch{return}}function Ix(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Lx({name:e,input:t}){return(0,I.jsxs)(`span`,{className:`compact-terminal-function-call`,children:[(0,I.jsx)(`span`,{className:`text-[#facc15] font-semibold`,children:e}),(0,I.jsx)(`span`,{className:`text-[#d4d4d4]`,children:`(`}),t===void 0?null:(0,I.jsx)(Rx,{value:t}),(0,I.jsx)(`span`,{className:`text-[#d4d4d4]`,children:`)`})]})}function Rx({value:e}){let[t,n]=(0,v.useState)(()=>new Set([`$`])),[r,i]=(0,v.useState)(()=>new Set);return(0,I.jsx)(zx,{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 zx({value:e,path:t,expandedPaths:n,expandedStrings:r,onTogglePath:i,onToggleString:a}){if(Array.isArray(e))return(0,I.jsx)(Bx,{value:e,path:t,open:`[`,close:`]`,expandedPaths:n,expandedStrings:r,onTogglePath:i,onToggleString:a});if(Ux(e))return(0,I.jsx)(Bx,{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,I.jsx)(`span`,{className:`text-[#fb923c]`,children:JSON.stringify(o)});return!i&&e.length<=140?s:(0,I.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`,"aria-label":`String at ${Vx(t)}`,"aria-expanded":n,children:s})}return typeof e==`number`||typeof e==`boolean`||e===null?(0,I.jsx)(`span`,{className:`text-[#60a5fa]`,children:String(e)}):(0,I.jsx)(`span`,{className:`text-[#737373]`,children:JSON.stringify(String(e))})}function Bx({value:e,path:t,open:n,close:r,expandedPaths:i,expandedStrings:a,onTogglePath:o,onToggleString:s}){let c=i.has(t),l=`inline-json-${(0,v.useId)()}`,u=c?Array.isArray(e)?e.map((e,t)=>[String(t),e]):Object.entries(e):[];return(0,I.jsxs)(`span`,{children:[(0,I.jsxs)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),o(t)},className:`compact-terminal-json-toggle align-baseline text-[#737373]`,title:c?`Collapse JSON`:`Expand JSON`,"aria-label":`JSON at ${t}`,"aria-expanded":c,"aria-controls":l,"data-inline-json-path":t,children:[(0,I.jsx)(`span`,{className:`compact-terminal-json-caret`,children:c?`▾`:`▸`}),n,c?null:`...${r}`]}),(0,I.jsxs)(`span`,{id:l,children:[u.map(([n,r],c)=>{let l=`${t}.${Hx(n)}`;return(0,I.jsxs)(`span`,{children:[c>0?(0,I.jsx)(`span`,{className:`text-[#737373]`,children:`, `}):null,Array.isArray(e)?null:(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(`span`,{className:`text-[#d4d4d4]`,children:JSON.stringify(n)}),(0,I.jsx)(`span`,{className:`text-[#737373]`,children:`:`})]}),(0,I.jsx)(zx,{value:r,path:l,expandedPaths:i,expandedStrings:a,onTogglePath:o,onToggleString:s})]},l)}),c?(0,I.jsx)(`span`,{className:`text-[#737373]`,children:r}):null]})]})}function Vx(e){let t=e.replace(/[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}/gi,`[id]`);return t.length<=80?t:`${t.slice(0,39)}…${t.slice(-39)}`}function Hx(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`.`,`\\.`)}function Ux(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}var Wx=120;function Gx({line:e,status:t,clampLines:n}){let r=`min-w-0 whitespace-pre-wrap break-words ${n?`block overflow-hidden`:``}`,i=Yx(e.tokens),a=i.length>Wx;return(0,I.jsxs)(`div`,{className:`grid grid-cols-[1.9rem_minmax(0,1fr)] gap-2 leading-[1.45]`,children:[(0,I.jsx)(`span`,{className:`whitespace-pre ${qx(e.prefix,t)}`,children:Kx(e.prefix)}),(0,I.jsxs)(`span`,{className:r,style:n?{maxHeight:`${n*1.45}em`}:void 0,children:[a?(0,I.jsx)(`span`,{className:`text-[#d4d4d4]`,children:i.map(e=>e.text).join(``)}):i.map((e,t)=>(0,I.jsx)(`span`,{className:Jx(e),children:e.text},`${t}:${e.text}`)),e.functionCall?(0,I.jsx)(Lx,{name:e.functionCall.name,input:e.functionCall.input}):null]})]})}function Kx(e=`none`){switch(e){case`bullet`:return`•`;case`detail`:return`└`;case`continuation`:return` `;case`prompt`:return`›`;default:return` `}}function qx(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 Jx(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()}function Yx(e){let t=[];for(let n of e){if(!n.text)continue;let e=t.at(-1);if(e&&e.tone===n.tone&&e.weight===n.weight&&e.italic===n.italic){e.text+=n.text;continue}t.push({...n})}return t}async function Xx(e,t){return A(`/api/chat/loops/session-goal?${new URLSearchParams({piboSessionId:e}).toString()}`,t)}async function Zx(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),A(`/api/web-annotations?${n.toString()}`)}async function Qx(e,t){return A(`/api/web-annotations/${encodeURIComponent(e)}`,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify(nS(t))})}async function $x(e){let t=new URLSearchParams;return e?.trim()&&t.set(`cdpUrl`,e.trim()),A(`/api/web-annotations/targets${t.size?`?${t.toString()}`:``}`)}async function eS(e){return A(`/api/web-annotations/bindings`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(nS(e))})}async function tS(e,t){return A(`/api/web-annotations/bindings/${encodeURIComponent(e)}/inject`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(nS(t))})}function nS(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0&&e!==``))}async function rS(e,t,n){return A(`/api/chat/projects/${encodeURIComponent(e)}/workflow-sessions/${encodeURIComponent(t)}/human-actions`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n)})}function iS(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 aS(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 oS(e){return sS(e)?e.result:e}function sS(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.type===`execution_result`}var cS={device_code:`Device code`,browser_oauth:`Browser OAuth`,api_key:`API key`};function lS({row:e,piboSessionId:t}){let n=iS(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.useRef)(!1),h=(0,v.useCallback)(()=>{a({type:`select_provider`}),l(``),d(``)},[]),g=(0,v.useCallback)(async e=>{try{await navigator.clipboard.writeText(e),p(e),window.setTimeout(()=>p(t=>t===e?null:t),1600)}catch{}},[]),_=(0,v.useCallback)(async(e,n)=>{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 r=oS(await N(t,`login.start`,{provider:e.id,method:n})),i=r?.url??r?.flow?.verificationUrl;if(!i){a({type:`error`,provider:e,message:`No login URL returned.`});return}a({type:`device_flow`,provider:e,url:i,flowId:r.flowId??r.state??r.flow?.flowId,completion:r.flow?.completion,userCode:r.userCode??r.flow?.userCode,instructions:r.instructions??r.flow?.instructions})}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,n,r)=>{if(!(!t||!n)){s(!0);try{let i=oS(await N(t,`login.complete`,{provider:e.id,flowId:n,...r?{code:r}:{}}));if(i?.state===`pending`)return;if(i?.state===`failed`){a({type:`error`,provider:e,message:`Login failed. Start a new runtime login flow.`});return}a({type:`success`,provider:e,message:`${e.name} login completed for this runtime.`})}catch(t){a({type:`error`,provider:e,message:t instanceof Error?t.message:String(t)})}finally{s(!1)}}},[t]),b=(0,v.useCallback)(async(e,n)=>{if(!t||!n){h();return}s(!0);try{await N(t,`login.cancel`,{provider:e.id,flowId:n}),h()}catch(t){a({type:`error`,provider:e,message:t instanceof Error?t.message:String(t)})}finally{s(!1)}},[t,h]);(0,v.useEffect)(()=>{if(i.type!==`device_flow`||i.completion!==`notification`||!i.flowId||!t)return;let e=async()=>{if(!(m.current||i.type!==`device_flow`)){m.current=!0;try{let e=oS(await N(t,`login.complete`,{provider:i.provider.id,flowId:i.flowId}));e?.state===`connected`||e?.state===`partial`?a({type:`success`,provider:i.provider,message:`${i.provider.name} login completed for this runtime.`}):e?.state===`failed`&&a({type:`error`,provider:i.provider,message:`Login failed. Start a new runtime login flow.`})}catch(e){a({type:`error`,provider:i.provider,message:e instanceof Error?e.message:String(e)})}finally{m.current=!1}}},n=window.setInterval(()=>void e(),1500);return()=>window.clearInterval(n)},[t,i]);let x=(0,v.useCallback)(async e=>{if(!t)return;let n=c.trim();if(n){s(!0);try{await N(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,I.jsx)(uS,{title:i.type===`select_provider`?`Login`:pS(i),tone:i.type===`error`?`red`:i.type===`success`?`green`:`cyan`,action:i.type===`select_provider`?void 0:(0,I.jsx)(dS,{onClick:()=>{i.type===`device_flow`?b(i.provider,i.flowId):h()},disabled:o}),children:i.type===`select_provider`?(0,I.jsxs)(`div`,{className:`grid gap-2`,children:[(0,I.jsxs)(`div`,{className:`text-[11px] text-[#737373]`,children:[`Choose a provider. Use `,(0,I.jsx)(`span`,{className:`text-[#38bdf8]`,children:`/login`}),` anytime.`]}),(0,I.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:r.map(e=>(0,I.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,I.jsx)(`span`,{children:e.name}),e.configured?(0,I.jsx)(`span`,{className:`text-[#22c55e]`,children:`●`}):null]},e.id))})]}):i.type===`select_method`?(0,I.jsxs)(`div`,{className:`grid gap-2`,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px]`,children:[(0,I.jsx)(`span`,{className:`text-[#737373]`,children:`Provider:`}),(0,I.jsx)(`span`,{className:`text-[#d4d4d4]`,children:i.provider.name}),i.provider.configured?(0,I.jsx)(fS,{tone:`green`,children:`Configured`}):(0,I.jsx)(fS,{tone:`neutral`,children:`Not configured`})]}),(0,I.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:i.provider.authMethods.map(e=>(0,I.jsxs)(`button`,{type:`button`,onClick:()=>e===`api_key`?a({type:`api_key`,provider:i.provider}):void _(i.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:[e===`api_key`?(0,I.jsx)(it,{size:11}):(0,I.jsx)(lt,{size:11}),cS[e]]},e))})]}):i.type===`device_starting`?(0,I.jsxs)(`div`,{className:`inline-flex items-center gap-2 text-[11px] text-[#38bdf8]`,children:[(0,I.jsx)(ct,{size:13,className:`animate-spin`}),` Starting device login...`]}):i.type===`device_flow`?(0,I.jsxs)(`div`,{className:`grid gap-2 text-[11px]`,children:[(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,I.jsx)(`span`,{className:`text-[#737373]`,children:`Open:`}),(0,I.jsxs)(`a`,{href:i.url,target:`_blank`,rel:`noreferrer`,className:`inline-flex items-center gap-1 text-[#38bdf8] hover:underline`,children:[mS(i.url),` `,(0,I.jsx)(Ye,{size:11})]}),(0,I.jsxs)(`button`,{type:`button`,onClick:()=>void g(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,I.jsx)(Ve,{size:10}):(0,I.jsx)(Ke,{size:10}),` `,f===i.url?`Copied`:`Copy`]})]}),i.userCode?(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,I.jsx)(`span`,{className:`text-[#737373]`,children:`Code:`}),(0,I.jsx)(`button`,{type:`button`,onClick:()=>void g(i.userCode),className:`border border-[#1f4960] px-2 py-0.5 font-semibold tracking-widest text-[#38bdf8] hover:border-[#38bdf8]`,children:i.userCode}),(0,I.jsx)(`span`,{className:`text-[#737373]`,children:`then`}),i.completion===`notification`?(0,I.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-[#38bdf8]`,children:[(0,I.jsx)(ct,{size:11,className:`animate-spin`}),` Waiting for runtime`]}):(0,I.jsxs)(`button`,{type:`button`,disabled:o||!i.flowId,onClick:()=>void y(i.provider,i.flowId),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,I.jsx)(ct,{size:11,className:`animate-spin`}):(0,I.jsx)(Ve,{size:11}),` Complete`]})]}):(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,I.jsx)(`input`,{value:u,autoComplete:`off`,spellCheck:!1,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,I.jsxs)(`button`,{type:`button`,disabled:o||!u.trim()||!i.flowId,onClick:()=>void y(i.provider,i.flowId,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,I.jsx)(ct,{size:11,className:`animate-spin`}):(0,I.jsx)(Ve,{size:11}),` Complete`]})]}),i.instructions?(0,I.jsx)(`div`,{className:`text-[#737373]`,children:i.instructions}):null]}):i.type===`api_key`?(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 text-[11px]`,children:[(0,I.jsx)(`span`,{className:`text-[#737373]`,children:`API key:`}),(0,I.jsx)(`input`,{type:`password`,value:c,autoComplete:`off`,spellCheck:!1,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&x(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,I.jsxs)(`button`,{type:`button`,disabled:o||!c.trim(),onClick:()=>void x(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,I.jsx)(ct,{size:11,className:`animate-spin`}):(0,I.jsx)(Ve,{size:11}),` Save`]})]}):i.type===`success`?(0,I.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px] text-[#22c55e]`,children:[(0,I.jsx)(Ve,{size:13}),` `,i.message]}):(0,I.jsxs)(`div`,{className:`flex items-start gap-2 text-[11px] text-[#ef4444]`,children:[(0,I.jsx)(ze,{size:13,className:`mt-0.5 shrink-0`}),` `,(0,I.jsx)(`span`,{children:i.message})]})}):(0,I.jsx)(uS,{title:`Login`,tone:`red`,children:`Unparseable login payload.`})}function uS({title:e,tone:t,action:n,children:r}){return(0,I.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,I.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[(0,I.jsx)(lt,{size:14,className:t===`red`?`text-[#ef4444]`:t===`green`?`text-[#22c55e]`:`text-[#38bdf8]`}),(0,I.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:e}),n?(0,I.jsx)(`div`,{className:`ml-auto`,children:n}):null]}),r]})}function dS({onClick:e,disabled:t}){return(0,I.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,I.jsx)(Te,{size:10}),` Back`]})}function fS({tone:e,children:t}){return(0,I.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 pS(e){return`provider`in e&&e.provider?e.provider.name:`Login`}function mS(e){try{let t=new URL(e);return`${t.host}${t.pathname}`}catch{return e.length>42?`${e.slice(0,39)}...`:e}}function hS({row:e,piboSessionId:t,onModelChanged:n}){let r=oS(e.output),i=(aS(r)?r:void 0)?.providers??[],a=(0,v.useMemo)(()=>i.flatMap(e=>e.models.map(t=>({...t,providerLabel:e.label,authConfigured:e.authConfigured}))),[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||e.authConfigured===!1)){d(!0),l(e),p(null);try{await ne(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,I.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,I.jsx)(`div`,{className:`flex items-center justify-between gap-3 border-b border-[#2a2a2a] px-3 py-2`,children:(0,I.jsxs)(`div`,{children:[(0,I.jsx)(`div`,{className:`text-[#d4d4d4]`,children:`Model`}),(0,I.jsx)(`div`,{className:`text-[11px] text-[#737373]`,children:`Choose a model exposed by the active runtime.`})]})}),(0,I.jsxs)(`div`,{className:`space-y-2 p-3`,children:[i.length?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)(`label`,{className:`flex items-center gap-2 border border-[#2a2a2a] bg-[#0b0b0b] px-2 py-1 text-[#737373]`,children:[(0,I.jsx)(_t,{size:13}),(0,I.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,I.jsx)(`div`,{className:`max-h-72 overflow-auto border border-[#2a2a2a]`,children:m.length?m.map(e=>(0,I.jsxs)(`button`,{type:`button`,disabled:u||e.authConfigured===!1,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:cursor-not-allowed disabled:opacity-50`,children:[(0,I.jsx)(`span`,{className:`truncate text-[#737373]`,children:e.providerLabel}),(0,I.jsxs)(`span`,{className:`min-w-0`,children:[(0,I.jsx)(`span`,{className:`block truncate text-[#d4d4d4]`,children:e.label}),(0,I.jsxs)(`span`,{className:`block truncate text-[11px] text-[#737373]`,children:[e.provider,`/`,e.id]})]}),e.authConfigured===!1?(0,I.jsx)(lt,{size:13,className:`text-[#737373]`,"aria-label":`Provider authentication missing`}):c?.provider===e.provider&&c?.id===e.id?(0,I.jsx)(Me,{size:14,className:`text-[#22c55e]`}):null]},`${e.provider}:${e.id}`)):(0,I.jsx)(`div`,{className:`px-3 py-2 text-[#737373]`,children:`No matching models.`})})]}):(0,I.jsx)(`div`,{className:`text-[#737373]`,children:`No models are available for the active runtime.`}),f?(0,I.jsx)(`div`,{className:`text-[11px] text-[#a3a3a3]`,children:f}):null]})]})}function gS(e={}){let t=[],n=[],r=CS(e.warnings),i=CS(e.errors);(e.session?.id||e.session?.title)&&t.push({id:`session`,label:`Session`,value:_S([e.session?.title,e.session?.id].filter(Boolean).join(` | `))}),e.session?.profile&&t.push({id:`profile`,label:`Profile`,value:_S(e.session.profile)}),e.session?.status&&t.push({id:`session-status`,label:`Session status`,value:_S(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:_S(e.model.label??[e.model.provider,e.model.id].filter(Boolean).join(`/`))}),e.runtime?.state&&t.push({id:`runtime`,label:`Runtime`,value:_S(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:_S(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:_S(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`?_S(e.fastMode):e.fastMode?`on`:`off`,tone:e.fastMode?`green`:`neutral`});let o=CS(e.tools?.enabled),s=CS(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:_S(e.providerUsage.planType)}),e.providerUsage?.credits&&t.push({id:`provider-credits`,label:`Credits`,value:e.providerUsage.credits.unlimited?`unlimited`:_S(e.providerUsage.credits.balance??`available`)}),e.message&&t.push({id:`message`,label:`Message`,value:_S(e.message)}),n.push(vS(e.contextUsage));for(let t of yS(e.providerUsage))n.push(t);return{kind:`status`,title:`Status`,fields:t,progress:n,warnings:r,errors:i}}function _S(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 vS(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=bS(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:xS(t)}}function yS(e){return e?.limits?.length?e.limits.map((t,n)=>{let r=bS(t.usedPercent),i=bS(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 ${_S(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:SS(i)}}):[{id:`provider`,label:`Provider quota`,state:`unavailable`,text:`Provider usage unavailable`,tone:`neutral`}]}function bS(e){if(!(typeof e!=`number`||!Number.isFinite(e)))return Math.max(0,Math.min(100,e))}function xS(e){return e===void 0?`neutral`:e>=80?`red`:e>=50?`yellow`:`green`}function SS(e){return e===void 0?`neutral`:e<=20?`red`:e<=50?`yellow`:`green`}function CS(e){return(e??[]).map(e=>_S(e)).filter(e=>e.length>0)}function wS(e){switch(e.kind){case`tool.status`:return TS(e);case`tool.thinking`:return ES(e);case`tool.model`:return DS(e);case`tool.login`:return OS(e);case`tool.call`:case`tool.image`:case`tool.group.exploring`:case`tool.group.images`:return kS(e);case`yielded.run`:return AS(e,`yielded-run`,`Yielded run`,e.status===`error`?`red`:e.status===`running`?`cyan`:`green`);case`execution.compaction`:return AS(e,`compaction`,e.status===`error`?`Compaction failed`:e.status===`running`?`Compacting`:`Compaction`,e.status===`error`?`red`:`magenta`);case`execution.command`:return AS(e,`command`,`Command`,e.status===`error`?`red`:`yellow`);case`error`:return AS(e,`error`,`Error`,`red`);default:return}}function TS(e){let t=MS(e.output),n=NS(t,`activeModel`)??NS(t,`model`),r=gS({session:{id:IS(t,`piboSessionId`)??IS(t,`sessionId`),title:IS(t,`sessionTitle`)??IS(t,`title`),profile:IS(t,`profile`)??IS(t,`activeAgentId`)??IS(t,`agentId`),status:RS(t,`disposed`)?`disposed`:IS(t,`sessionStatus`)},model:n?{provider:IS(n,`provider`),id:IS(n,`id`),label:IS(n,`label`)}:void 0,runtime:{state:RS(t,`disposed`)?`disposed`:RS(t,`processing`)?`processing`:RS(t,`streaming`)?`streaming`:IS(t,`mode`)??`idle`,connected:RS(t,`connected`),queuedMessages:LS(t,`queuedMessages`),processing:RS(t,`processing`),streaming:RS(t,`streaming`),disposed:RS(t,`disposed`)},cwd:IS(t,`cwd`),contextUsage:NS(t,`contextUsage`),providerUsage:NS(t,`providerUsage`),tools:{enabled:FS(t,`enabledTools`),active:FS(t,`activeTools`)},thinking:IS(t,`thinkingLevel`)?{level:IS(t,`thinkingLevel`)}:void 0,fastMode:RS(t,`fastMode`),warnings:FS(t,`warnings`),errors:FS(t,`errors`),message:IS(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 ES(e){let t=MS(e.output),n=IS(t,`level`)??`unknown`,r=t?.supported!==!1,i=FS(t,`availableLevels`);return{id:e.id,kind:`thinking`,title:`Thinking`,status:e.status,tone:r?`yellow`:`red`,rows:[{label:`Current`,value:_S(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 DS(e){let t=PS(MS(e.output),`providers`),n=t.flatMap(e=>{let t=IS(e,`id`)??IS(e,`provider`)??`provider`,n=IS(e,`label`)??IS(e,`name`)??t;return PS(e,`models`).map(e=>{let r=IS(e,`id`)??`model`,i=IS(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 OS(e){let t=PS(MS(e.output),`providers`),n=t.map(e=>{let t=IS(e,`id`)??`provider`;return{id:`login:${t}`,label:IS(e,`name`)??IS(e,`label`)??t,action:`login.selectProvider`,value:t,description:FS(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 kS(e){return AS(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 AS(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?``:` ${jS(e.functionCall.input)}`}`:``}`.trim();return t?[{value:_S(t)}]:[]}),a=e.lines.length===0&&typeof e.output==`string`&&e.output.trim()?[{value:_S(e.output.trim())}]:[],o=[e.error?{label:`Error`,value:_S(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 jS(e){try{return JSON.stringify(e)}catch{return String(e)}}function MS(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 NS(e,t){let n=e?.[t];return n&&typeof n==`object`&&!Array.isArray(n)?n:void 0}function PS(e,t){let n=e?.[t];return Array.isArray(n)?n.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e)):[]}function FS(e,t){let n=e?.[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function IS(e,t){let n=e?.[t];return typeof n==`string`?n:void 0}function LS(e,t){let n=e?.[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function RS(e,t){let n=e?.[t];return typeof n==`boolean`?n:void 0}var zS={transcript:0,"product-history":1,"event-log":1,live:2},BS={"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 VS(e,t){return{sourceRank:zS[`event-log`],turnSeq:e??2**53-1,eventSequence:e,phaseRank:BS[t]}}function HS(e,t,n){let r=e??2**53-1,i=t??2**53-1;return{sourceRank:zS.live,turnSeq:r,streamId:r,streamFrameIndex:i,phaseRank:BS[n]}}function US(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 WS(e,t){if(e)return{...e,contentPartIndex:(e.contentPartIndex??0)+.1,phaseRank:BS[t]}}function GS(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 KS(e){let t=!1,n=e.map(e=>e.children.length?(t=!0,{...e,children:KS(e.children)}):e);return qS(n)?t?n:[...e]:[...n].sort(JS)}function qS(e){for(let t=1;t<e.length;t+=1)if(JS(e[t-1],e[t])>0)return!1;return!0}function JS(e,t){if(e.orderKey&&t.orderKey&&e.orderKey.sourceRank===t.orderKey.sourceRank){let n=GS(e.orderKey,t.orderKey);if(n!==0)return n}else{let n=YS(e,t);if(n!==0)return n}let n=XS(e.startedAt,t.startedAt);if(n!==0)return n;let r=GS(e.orderKey,t.orderKey);return r===0?e.id.localeCompare(t.id):r}function YS(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 XS(e,t){return!e&&!t?0:e?t?e.localeCompare(t):-1:1}function ZS(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 QS(e){let t=new Map;for(let n of e)t.set(n.id,{...n,children:[...n.children]});let n=new Set;for(let e of t.values()){if(!e.parentId)continue;let r=t.get(e.parentId);r&&(r.children.push(e),n.add(e.id))}return KS([...t.values()].filter(e=>!n.has(e.id)))}function $S(e,t,n,r){if(!eC(t))return;let i=r.get(e)?.filter(e=>e.metadata?.subagentToolName===t)??[],a=nC(n);return a?i.find(e=>e.metadata?.threadKey===a)?.id:i.length===1?i[0].id:void 0}function eC(e){return e.startsWith(`pibo_subagent_`)}function tC(e){return e.slice(14)}function nC(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 rC(e,t,n,r){let i=aC(e,t,n,r);if(!i)return;let a=e.children.find(e=>e.id===i.id);if(a){sC(a,i),a.runId=i.runId??a.runId;return}e.children.push(i)}function iC(e){let t=new Map;for(let n of ZS(e)){let e=cC(n.output);if(!e)continue;let r=uC(e.runId);r&&t.set(r,{snapshot:e,completedAt:uC(e.completedAt)??uC(e.updatedAt)??n.completedAt})}for(let n of ZS(e)){if(n.type!==`agent.async`||!n.runId)continue;let e=t.get(n.runId);if(!e)continue;let r=uC(e.snapshot.status);(r===`completed`||r===`cancelled`||r===`failed`||r===`timed_out`)&&(n.status=r===`failed`||r===`timed_out`?`error`:`done`,n.completedAt=e.completedAt??n.completedAt,n.output=e.snapshot,(r===`failed`||r===`timed_out`)&&(n.error=uC(e.snapshot.summary)??n.error))}}function aC(e,t,n,r){if(!oC(e))return;let i=cC(e.output),a=fC(e.input)?e.input:{},o=uC(i?.toolName)??uC(a.toolName)??r?.title;if(!o||!eC(o))return;let s=uC(r?.summary)??tC(o),c=uC(i?.runId),l=uC(i?.status),u=a.arguments,d=uC(i?.completionPolicy)??uC(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:dC(e,l),startedAt:r?.startedAt??n??e.startedAt,completedAt:l===`completed`||l===`cancelled`||l===`failed`||l===`timed_out`?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:fC(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:WS(e.orderKey,`agent.async`),children:[]}}function oC(e){return e.type===`tool.call`&&e.title===`pibo_run_start`}function sC(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 cC(e){if(fC(e)){if(lC(e))return e;if(fC(e.details)&&lC(e.details))return e.details}}function lC(e){return typeof e.runId==`string`&&typeof e.toolName==`string`}function uC(e){return typeof e==`string`?e:void 0}function dC(e,t){return e.status===`error`||t===`failed`?`error`:t===`completed`||t===`cancelled`?`done`:`running`}function fC(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function pC(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 mC(e){let t=hC(e.notification),n=t.length===1?t[0]:void 0,r=_C(e.notification.failed)+_C(e.notification.timedOut),i=_C(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:vC(e.notification),output:e.notification,source:e.source,stableKey:e.stableKey??e.id,orderKey:e.orderKey,children:[]}}function hC(e){return[...gC(e.completed),...gC(e.failed),...gC(e.timedOut),...gC(e.cancelled),...gC(e.running)]}function gC(e){return Array.isArray(e)?e.filter(yC):[]}function _C(e){return Array.isArray(e)?e.length:0}function vC(e){let t=[[_C(e.completed),`completed`],[_C(e.failed),`failed`],[_C(e.timedOut),`timed out`],[_C(e.cancelled),`cancelled`],[_C(e.running),`running`]].filter(([e])=>Number(e)>0).map(([e,t])=>`${e} ${t}`);return t.length?t.join(`, `):`No yielded run updates`}function yC(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function bC(e,t,n,r,i,a,o,s,c){let l=r.payload,u=o.mode===`none`?void 0:DC(e,r);if(u){l.type===`message_steered`&&l.activeEventId&&(u.parentId=ZC(l.activeEventId));return}if((o.mode===`native`&&WC(l)||o.mode===`product`&&UC(l))&&KC(l,o)&&!GC(l,s)||qC(l,o,c))return;if(l.type===`assistant_delta`){IC(e,t,l,c,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex,r.traceSource);return}if(l.type===`thinking_delta`){zC(e,t,l,c,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex,r.traceSource);return}if(l.type===`assistant_message`){let i=xC(n,l,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex,r.traceSource),a=t.get(i.id)??LC(t,i);if(a){RC(a,i);return}e.push(i),t.set(i.id,i);return}let d=FC(n,l,i,a,c,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex,r.traceSource);if(d){if(d.type===`user.message`&&d.status===`running`&&!d.parentId&&l.type===`message_steered`){let e=[...t.values()].reverse().find(e=>e.type===`agent.turn`&&e.status===`running`);e&&(d.parentId=e.id)}if(d.type===`agent.turn`&&d.eventId){let e=[...t.values()].find(e=>e.type===`agent.turn`&&e.eventId===d.eventId);if(e){e.status=d.status,e.completedAt=d.completedAt??e.completedAt;return}}if(d.type===`assistant.message`){let e=t.get(d.id)??LC(t,d);if(e){RC(e,d);return}}if(d.type===`execution.compaction`){let t=lw(e);if(t){uw(t,d);return}}if(d.type===`model.reasoning`){let e=t.get(d.id)??LC(t,d);if(e){BC(e,d);return}}if(d.type===`agent.delegation`&&!d.toolCallId&&d.linkedPiboSessionId){let e=iw([...t.values()],d);if(e){rw(e,d);return}}if(d.toolCallId){let e=[...t.values()].find(e=>e.toolCallId===d.toolCallId&&(e.type===`tool.call`||e.type===`agent.delegation`));if(e){if(oC(e)&&d.type===`agent.delegation`){rC(e,n,r.createdAt,d);return}nw(e,d),rC(e,n,r.createdAt);return}}if(d.eventId){let e=t.get(d.id);if(e){d.type===`user.message`?(e.status=d.status,e.parentId=d.parentId??e.parentId,e.summary=d.summary??e.summary,e.output=d.output??e.output):d.type===`execution.command`&&(e.status=d.status,e.output=d.output??e.output,e.error=d.error??e.error,e.completedAt=d.completedAt??e.completedAt);return}}SC(d,t),rC(d,n,r.createdAt),e.push(d);for(let e of ZS([d]))t.set(e.id,e)}}function xC(e,t,n,r,i,a,o){let s=typeof t.eventId==`string`?t.eventId:void 0,c=$C(t);return{id:c?QC(c):`event:${t.type}:${hw(t)}`,piboSessionId:e,eventId:s,parentId:s?ZC(s):void 0,type:`assistant.message`,title:`Agent Message`,status:`done`,startedAt:n,completedAt:n,summary:t.text,output:t.text,source:`event-log`,stableKey:c?`assistant:${c}`:XC(t),orderKey:JC(r,t.type,i,a,o),children:[]}}function SC(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=CC(n,t);return r===void 0||e.startedAt<=r}).sort(JS).at(-1);n&&(e.parentId=n.id)}function CC(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(JS).at(0)?.startedAt}function wC(e){return e.some(e=>{let t=e.payload.type;return t!==`assistant_delta`&&t!==`thinking_delta`})}function TC(e){if(e.type===`assistant_delta`){if(e.text.length===0)return;let t=$C(e);return t?QC(t):void 0}if(e.type===`thinking_delta`){if(e.text.length===0)return;let t=tw(e);return t?ew(t):void 0}}function EC(e,t){return!!DC(e,t)}function DC(e,t){let n=t.payload;if(n.type!==`message_queued`&&n.type!==`message_steered`||n.source!==`user`)return;let r=typeof n.eventId==`string`?n.eventId:void 0,i=r??t.eventId,a=`event:${n.type}:${r??hw(n)}`,o=XC(n),s=typeof n.text==`string`?n.text:void 0,c=ZS([...e]).filter(e=>e.type===`user.message`&&OC(e.source));return c.find(e=>kC(e,a,o,i))||c.find(e=>!AC(e)&&!!(s&&MC(e)===s))}function OC(e){return e===`transcript`||e===`product-history`}function kC(e,t,n,r){return e.id===t||e.stableKey===n?!0:r?e.entryId===r||e.stableKey===`entry:${r}`||[e.id,e.stableKey].some(e=>jC(e)===r):!1}function AC(e){return[e.id,e.stableKey].some(e=>jC(e)!==void 0)}function jC(e){for(let t of[`event:message_queued:`,`event:message_steered:`])if(e?.startsWith(t))return e.slice(t.length)}function MC(e){if(typeof e.output==`string`)return e.output;if(typeof e.summary==`string`)return e.summary}function NC(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 PC(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 FC(e,t,n,r,i,a,o,s,c,l){let u=`eventId`in t&&typeof t.eventId==`string`?t.eventId:void 0,d=`event:${t.type}:${u??hw(t)}`,f=u?ZC(u):void 0,p={id:d,piboSessionId:e,eventId:u,startedAt:a,source:`event-log`,stableKey:XC(t),orderKey:JC(o,t.type,s,c,l),children:[]};switch(t.type){case`message_queued`:case`message_steered`:{let n=pC(t.text);return t.source===`service`&&n?mC({id:d,piboSessionId:e,eventId:u,startedAt:a,source:`event-log`,stableKey:u?`run-notification:${u}`:d,orderKey:JC(o,t.type,s,c,l),notification:n}):{...p,...t.type===`message_steered`&&t.activeEventId?{parentId:ZC(t.activeEventId)}:{},type:`user.message`,title:`User Message`,status:VC(t)?`running`:`done`,summary:t.text,output:t.text}}case`message_started`:case`message_finished`:return t.source===`service`?void 0:{...p,id:u?ZC(u):d,type:`agent.turn`,startedAt:t.type===`message_started`?a:void 0,title:`Agent Turn`,status:t.type===`message_finished`||i!==`running`?`done`:`running`,completedAt:t.type===`message_finished`?a:void 0,stableKey:u?`turn:${u}`:p.stableKey};case`thinking_finished`:{if(!dw(t.text))return;let e=tw(t);return{...p,id:e?ew(e):d,parentId:f,type:`model.reasoning`,title:`Thinking`,status:`done`,summary:t.text,output:t.text,stableKey:e?`reasoning:${e}`:p.stableKey}}case`assistant_message`:{let e=$C(t);return{...p,id:e?QC(e):d,parentId:f,type:`assistant.message`,title:`Agent Message`,status:`done`,completedAt:a,summary:t.text,output:t.text,stableKey:e?`assistant:${e}`:p.stableKey}}case`tool_call`:case`tool_execution_started`:case`tool_execution_updated`:case`tool_execution_finished`:{let o=eC(t.toolName),s=r.get(t.toolCallId)??(o?$S(e,t.toolName,t,n):void 0);return{...p,id:`tool:${t.toolCallId}`,parentId:f,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?fw(t.result):void 0,linkedPiboSessionId:s,stableKey:`tool:${t.toolCallId}`,children:[]}}case`subagent_session`:{let e=mw(t.childPiboSessionId),n=pw(o,s,t);return{...p,id:t.toolCallId?`tool:${t.toolCallId}`:`event:subagent_session:${n}`,eventId:u,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:e,stableKey:t.toolCallId?`tool:${t.toolCallId}`:e?`subagent:${e}`:`subagent:event:${n}`,children:[]}}case`execution_result`:return HC(t.action)?void 0:{...p,type:`execution.command`,title:t.action,status:`done`,input:{action:t.action},output:t.result};case`compaction_start`:{let e=pw(o,s,t);return{...p,id:`event:compaction:${e}`,type:`execution.compaction`,title:`compact`,status:`running`,summary:`Compacting`,input:{reason:t.reason},stableKey:`compaction:${e}`}}case`compaction_end`:{let e=pw(o,s,t);return{...p,id:`event:compaction:end:${e}`,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:${e}`}}case`session_error`:return{...p,type:`error`,title:`Session Error`,status:`error`,summary:t.errorDetails?.userMessage,input:t.errorDetails,error:t.error,output:t.error};default:return}}function IC(e,t,n,r,i,a,o,s,c){if(typeof n.text!=`string`||n.text.length===0)return;let l=$C(n),u=l?QC(l):`event:assistant_delta:${hw(n)}`,d=t.get(u);if(d){let e=`${typeof d.output==`string`?d.output:``}${n.text}`;d.status=r===`running`?`running`:`done`,d.summary=e,d.output=e;return}let f={id:u,parentId:n.eventId?ZC(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:l?`assistant:${l}`:u,orderKey:JC(a,n.type,o,s,c),children:[]};e.push(f),t.set(f.id,f)}function LC(e,t){if(t.stableKey)return[...e.values()].find(e=>e.type===t.type&&e.stableKey===t.stableKey)}function RC(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 zC(e,t,n,r,i,a,o,s,c){if(typeof n.text!=`string`||n.text.length===0)return;let l=tw(n),u=l?ew(l):`event:thinking_delta:${hw(n)}`,d=l?`reasoning:${l}`:u,f=t.get(u)??[...t.values()].find(e=>e.type===`model.reasoning`&&e.stableKey===d);if(f){let e=`${typeof f.output==`string`?f.output:``}${n.text}`;f.status=r===`running`?`running`:`done`,f.summary=e,f.output=e;return}let p={id:u,parentId:n.eventId?ZC(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:d,orderKey:JC(a,n.type,o,s,c),children:[]};e.push(p),t.set(p.id,p)}function BC(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 VC(e){return(e.type===`message_queued`||e.type===`message_steered`)&&`clientTxnId`in e&&typeof e.clientTxnId==`string`}function HC(e){return e===`session.fork`||e===`session.clone`||e===`session.switch`}function UC(e){return e.type===`assistant_delta`||e.type===`assistant_message`}function WC(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 GC(e,t){let n=`eventId`in e&&typeof e.eventId==`string`?e.eventId:void 0;return!!(n&&t.has(n))}function KC(e,t){let n=`eventId`in e&&typeof e.eventId==`string`?e.eventId:void 0;return n===void 0||t.eventIds.has(n)}function qC(e,t,n){return t.mode!==`native`||n===`running`||e.type!==`tool_call`&&e.type!==`tool_execution_started`&&e.type!==`tool_execution_updated`&&e.type!==`tool_execution_finished`?!1:t.toolCallIds.has(e.toolCallId)||KC(e,t)}function JC(e,t,n,r,i){return i===`live`?HS(n,r,YC(t)):VS(e,YC(t))}function YC(e){switch(e){case`message_queued`:case`message_steered`: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 XC(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=tw(e);if(t)return`reasoning:${t}`}if(e.type===`assistant_delta`||e.type===`assistant_message`){let t=$C(e);if(t)return`assistant:${t}`}return`event:${e.type}:${t??hw(e)}`}function ZC(e){return`event:message:${e}`}function QC(e){return`event:assistant:${e}`}function $C(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 ew(e){return`event:thinking:${e}`}function tw(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 nw(e,t){e.status=t.status,e.summary=t.summary??e.summary,e.input=sw(e,t),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 rw(e,t){e.summary=t.summary??e.summary,e.input=sw(e,t),e.linkedPiboSessionId=t.linkedPiboSessionId??e.linkedPiboSessionId}function iw(e,t){let n=[...e].reverse().filter(e=>e.type===`agent.delegation`),r=aw(t),i=n.filter(e=>!e.linkedPiboSessionId&&aw(e)===r),a=ow(t.input);return(a?i.find(e=>ow(e.input)===a):i.length===1?i[0]:void 0)||n.find(e=>e.linkedPiboSessionId===t.linkedPiboSessionId)}function aw(e){let t=cw(e.input)?e.input:void 0,n=typeof t?.subagentName==`string`?t.subagentName:e.summary??e.title;return typeof n==`string`&&n.replace(/^pibo_subagent_/,``).trim().toLowerCase()||void 0}function ow(e){if(!(!cw(e)||typeof e.threadKey!=`string`))return e.threadKey.trim()||void 0}function sw(e,t){return e.type!==`agent.delegation`||!cw(e.input)||!cw(t.input)?t.input??e.input:Object.fromEntries(Object.entries({...e.input,...t.input}).filter(([,e])=>e!==void 0))}function cw(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function lw(e){return ZS([...e]).reverse().find(e=>e.type===`execution.compaction`&&e.status===`running`)}function uw(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 dw(e){return typeof e==`string`&&e.trim().length>0}function fw(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}function pw(e,t,n){return e===void 0?t===void 0?hw(n):`stream:${t}`:`sequence:${e}`}function mw(e){if(typeof e==`string`)return e.trim()||void 0}function hw(e){return gw(new TextEncoder().encode(JSON.stringify(e))).slice(0,48)}function gw(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 _w(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 KS(n)}function vw(e,t,n){return t.map(t=>yw(e,t,n))}function yw(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)||bw(r,t))?r:e?{...t,children:r.children}:{...t,children:[]}}let i=t.children.map(t=>yw(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)||bw(r,t))?r:a?{...t,children:r?.children??i}:{...t,children:i}}function bw(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&&xw(e.orderKey,t.orderKey)}function xw(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 Sw(e,t,n){if(!t.length)return e;let r=new Set(e.rawEvents.map(e=>NC(e))),i=[];for(let e of t){let t=NC(e);r.has(t)||(r.add(t),i.push(e))}if(!i.length)return e;let a=ZS(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={mode:`none`,eventIds:new Set,toolCallIds:new Set},p=[],m=new Set;for(let t of i){if(EC(o,t))continue;p.push(t);let r=TC(t.payload);m&&r?m.add(r):m=void 0,bC(o,s,e.piboSessionId,t,l,u,f,d,n)}if(!p.length)return e;let h=_w(o);wC(p)&&iC(h);let g=vw(c,h,m);return{...e,rawEvents:e.rawEvents.length?[...e.rawEvents,...p]:p,nodes:g,latestStreamId:PC(p,e.latestStreamId)}}var Cw={browser_use_open_tabs:`browser_use.open_tabs`,browser_use_take_screenshot:`browser_use.take_screenshot`,browser_use_browser_use:`browser_use.browser_use`,node_repl_js:`node_repl.js`,node_repl_js_reset:`node_repl.js_reset`};function ww(e,t){if(!e)return[];let n=Dw(e.nodes),r=oT(Ow(e.nodes).sort((e,t)=>JS(e.node,t.node)).filter(e=>e.node.type!==`agent.turn`&&(t.showThinking||e.node.type!==`model.reasoning`)).map(e=>kw(e.node,e.turnId)));return Nw(r,n),lT(Mw(r)).map(e=>e.row)}function Tw(e){if(!e)return;let t=new Set(Ow(e.nodes).map(({node:e})=>e).filter(e=>e.type===`error`&&e.eventId).map(e=>e.eventId));return[...Dw(e.nodes).values()].filter(e=>e.startedAt&&!e.completedAt&&(!e.eventId||!t.has(e.eventId))).sort(JS).at(-1)?.startedAt}function Ew(e){let t=Math.max(0,Math.floor(e/1e3));return[Math.floor(t/3600),Math.floor(t%3600/60),t%60].map(e=>String(e).padStart(2,`0`)).join(`:`)}function Dw(e){let t=new Map;for(let n of e){n.type===`agent.turn`&&t.set(n.id,n);for(let[e,r]of Dw(n.children))t.set(e,r)}return t}function Ow(e,t){let n=[];for(let r of e)r.type!==`agent.turn`&&n.push({node:r,turnId:t}),n.push(...Ow(r.children,r.type===`agent.turn`?r.id:t));return n}function kw(e,t){let n;switch(e.type){case`user.message`:n={row:Iw(e),turnId:t};break;case`assistant.message`:n={row:Lw(e),turnId:t};break;case`model.reasoning`:n={row:Rw(e),turnId:t};break;case`tool.call`:n=zw(e,t);break;case`tool.result`:n=Hw(e,t);break;case`agent.delegation`:n={row:Ww(e),turnId:t};break;case`agent.async`:n={row:Gw(e),turnId:t};break;case`yielded.run`:n={row:Kw(e),turnId:t};break;case`execution.command`:n={row:Jw(e),turnId:t};break;case`execution.compaction`:n={row:qw(e),turnId:t};break;case`error`:n={row:iT(e),turnId:t};break;case`agent.turn`:n={row:{id:e.id,kind:`error`,status:`neutral`,lines:[],sourceNodeIds:[e.id]},turnId:t}}return{...n,row:{...n.row,id:Aw(e),...Fw(e)}}}function Aw(e){if(e.type===`tool.call`||e.type===`tool.result`||e.type===`agent.delegation`){let t=e.toolCallId??jw(e.stableKey,`tool:`);if(t)return`terminal:tool:${t}`;if(e.type===`agent.delegation`&&e.linkedPiboSessionId)return`terminal:delegation:${e.linkedPiboSessionId}`}if((e.type===`agent.async`||e.type===`yielded.run`)&&e.runId)return`terminal:run:${e.runId}`;if(e.type===`assistant.message`){let t=jw(e.stableKey,`assistant:`);if(t)return`terminal:assistant:${t}`}if(e.type===`model.reasoning`){let t=jw(e.stableKey,`reasoning:`);if(t)return`terminal:reasoning:${t}`}return e.id}function jw(e,t){if(!e?.startsWith(t))return;let n=e.slice(t.length);return n&&n!==`undefined`?n:void 0}function Mw(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.row.id);if(e===void 0){n.set(r.row.id,t.length),t.push(r);continue}let i=t[e];t[e]={...r,turnId:r.turnId??i.turnId,row:{...i.row,...r.row,sourceNodeIds:[...new Set([...i.row.sourceNodeIds,...r.row.sourceNodeIds])],input:r.row.input??i.row.input,output:r.row.output??i.row.output,error:r.row.error??i.row.error,payloadRefs:{...i.row.payloadRefs,...r.row.payloadRefs}}}}return t}function Nw(e,t){for(let n of t.values()){if(!n.completedAt)continue;let t=e.filter(e=>e.turnId===n.id).at(-1);t?.row.kind===`message.assistant`&&t.row.status!==`running`&&(t.row.startedAt=n.startedAt,t.row.completedAt=n.completedAt,t.row.durationMs=n.durationMs??Pw(n.startedAt,n.completedAt))}}function Pw(e,t){if(!e||!t)return;let n=new Date(e).getTime(),r=new Date(t).getTime();return Number.isFinite(n)&&Number.isFinite(r)?Math.max(0,r-n):void 0}function Fw(e){return{eventId:e.eventId,runId:e.runId,orderSource:e.source,orderStreamId:e.orderKey?.streamId,orderStreamFrameIndex:e.orderKey?.streamFrameIndex,payloadRefs:e.payloadRefs}}function Iw(e){let t=GT(e.output)||GT(e.summary)||e.title;return{id:e.id,kind:`message.user`,status:UT(e.status),lines:[{prefix:`prompt`,tokens:[$(t)]}],sourceNodeIds:[e.id],forkEntryId:e.entryId,pendingMessageDelivery:VT(e),startedAt:e.startedAt,output:t,payloadRefs:e.payloadRefs}}function Lw(e){return{id:e.id,kind:`message.assistant`,status:UT(e.status),lines:[],sourceNodeIds:[e.id],startedAt:e.startedAt,completedAt:e.source===`transcript`||e.source===`product-history`?e.completedAt:void 0,durationMs:e.source===`transcript`||e.source===`product-history`?e.durationMs:void 0,output:GT(e.output)||GT(e.summary)||``,error:e.error,payloadRefs:e.payloadRefs}}function Rw(e){let t=AT(e.output??e.summary);return{id:e.id,kind:`reasoning`,status:UT(e.status),lines:[{prefix:`bullet`,tokens:[$(e.status===`running`?`Thinking`:`Thought`,`amber`,`semibold`)]}],sourceNodeIds:[e.id],markdown:t,payloadRefs:e.payloadRefs}}function zw(e,t){let n=LT(e.input);if(n&&MT(e.title))return{row:rT(e,n),turnId:t,exploring:void 0};if(NT(e.title))return{row:Bw(e),turnId:t};let r=mT(e);if(r)return{row:Vw(e,r),turnId:t,image:r.groupable?r.detail:void 0};let i=OT(e.error??e.output,5,e.error?`red`:`dim`);return{row:{id:e.id,kind:`tool.call`,status:UT(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(zT(e.status),WT(e.status),`semibold`),$(` `)],functionCall:{name:CT(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:kT(i,e.error?`error`:`output`)},turnId:t,exploring:ST(e)}}function Bw(e){let t=UT(e.status),n=FT(e),r=IT(e.output),i=[{prefix:`bullet`,tokens:[$(PT(e.status),WT(e.status),e.status===`error`?`bold`:`semibold`)]}];return n&&i.push({prefix:`detail`,tokens:[$(`query: ${JSON.stringify(n)}`,`cyan`)]}),e.status===`done`&&r!==void 0&&i.push({prefix:`detail`,tokens:[$(`sources: ${r}`,`dim`)]}),e.status===`error`&&e.error&&i.push({prefix:`detail`,tokens:[$(e.error,`red`)]}),{id:e.id,kind:`tool.call`,status:t,errorKind:e.status===`error`?`tool`:void 0,lines:i,sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:e.input!==void 0||e.output!==void 0||!!e.error}}function Vw(e,t){let n=UT(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,WT(e.status),`semibold`)]},{prefix:`detail`,tokens:[$(r,e.status===`error`?`red`:`cyan`)]}],sourceNodeIds:[e.id],input:gT(e.input),output:t.summary,error:e.error,expandable:e.input!==void 0||t.summary!==void 0||!!e.error}}function Hw(e,t){let n=mT(e);return n?{row:Vw(e,n),turnId:t,image:n.groupable?n.detail:void 0}:{row:Uw(e),turnId:t}}function Uw(e){let t=OT(e.error??e.output,5,e.error?`red`:`dim`);return{id:e.id,kind:`tool.call`,status:UT(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(e.status===`error`?`Tool failed`:`Returned`,WT(e.status),`semibold`),$(` ${CT(e.title)}`)]},...t.lines],sourceNodeIds:[e.id],output:e.output,error:e.error,expandable:e.output!==void 0||!!e.error,previewOmission:kT(t,e.error?`error`:`output`)}}function Ww(e){let t=GT(KT(e.input)?e.input.subagentName:void 0)||e.summary||e.title,n=jT((KT(e.input)?e.input.arguments:void 0)??e.input),r=n?[{prefix:`detail`,tokens:[$(n,`dim`)]}]:[];return{id:e.id,kind:`agent.delegation`,status:UT(e.status),errorKind:e.status===`error`?`tool`:void 0,title:e.title,summary:e.summary,lines:[{prefix:`bullet`,tokens:[$(BT(e.status),WT(e.status),`semibold`),$(` ${t}`,`cyan`)]},...r],sourceNodeIds:[e.id],linkedPiboSessionId:e.linkedPiboSessionId,startedAt:e.startedAt,completedAt:e.completedAt,durationMs:e.durationMs,input:e.input,output:e.output,error:e.error,expandable:e.input!==void 0||e.output!==void 0||!!e.error}}function Gw(e){let t=OT(e.error??e.output,5,e.error?`red`:`dim`);return{id:e.id,kind:`agent.async`,status:UT(e.status),lines:[{prefix:`bullet`,tokens:[$(HT(e.status),WT(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:kT(t,e.error?`error`:`output`)}}function Kw(e){let t=OT(e.output,5);return{id:e.id,kind:`yielded.run`,status:UT(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(e.status===`running`?`Waiting on runs`:`Run update`,WT(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:kT(t,`output`)}}function qw(e){let t=e.status===`running`?`Compacting`:e.status===`error`?`Compaction failed`:GT(e.summary)||`Compacted`;return{id:e.id,kind:`execution.compaction`,status:UT(e.status),lines:[{prefix:`bullet`,tokens:[$(t,WT(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 Jw(e){if(e.title===`status`)return Yw(e);if(e.title===`thinking`)return cT(e.output)?Zw(e):Xw(e);if(e.title===`fast_mode`)return Qw(e);if(e.title===`login`&&tT(e.output))return $w(e);if(e.title===`model`&&nT(e.output))return eT(e);LT(e.output)??LT(e.input)??e.title;let t=OT(e.error??e.output,5,e.error?`red`:`dim`,180);return{id:e.id,kind:`execution.command`,status:UT(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:kT(t,e.error?`error`:`output`)}}function Yw(e){return{id:e.id,kind:`tool.status`,status:UT(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function Xw(e){return{id:e.id,kind:`tool.thinking`,status:UT(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function Zw(e){let t=KT(e.output)?e.output:void 0,n=GT(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:UT(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 Qw(e){let t=KT(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:UT(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 $w(e){return{id:e.id,kind:`tool.login`,status:UT(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function eT(e){return{id:e.id,kind:`tool.model`,status:UT(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function tT(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 nT(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 rT(e,t){let n=OT(e.error??e.output,5,e.error?`red`:`dim`,180);return{id:e.id,kind:`execution.command`,status:UT(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(e.status===`running`?`Running`:`Ran`,WT(e.status),`semibold`),$(` `),...RT(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:kT(n,e.error?`error`:`output`)}}function iT(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`)]},...aT(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 aT(e){return KT(e)?[[`Class`,GT(e.errorClass)??GT(e.category)],[`Code`,GT(e.code)??GT(e.providerCode)],[`Origin`,GT(e.origin)],[`Provider`,[GT(e.api),GT(e.provider),GT(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 oT(e){let t=e.map(e=>e.row.output).filter(sT).at(-1);return t?e.map(e=>e.row.kind!==`tool.thinking`||!KT(e.row.output)?e:{...e,row:{...e.row,output:{...e.row.output,level:t.level,availableLevels:t.availableLevels,supported:t.supported}}}):[...e]}function sT(e){return KT(e)&&typeof e.level==`string`&&Array.isArray(e.availableLevels)}function cT(e){return KT(e)&&e.action===`set_thinking_level`}function lT(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n],i=uT(r);if(!i){t.push(r);continue}let a=[r],o=n+1;for(;o<e.length&&uT(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`?fT(a):dT(a),turnId:r.turnId}),n=o-1}return t}function uT(e){if(e.image)return`images`;if(e.exploring)return`exploring`}function dT(e){let t=pT(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`,WT(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 fT(e){let t=pT(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`,WT(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 pT(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,payloadRefs:e.row.payloadRefs,linkedPiboSessionId:e.row.linkedPiboSessionId,previewOmission:e.row.previewOmission}})}function mT(e){let t=(e.title??``).trim().toLowerCase(),n=KT(e.input)?e.input:void 0,r=KT(e.output)?e.output:void 0,i=xT(r,`details`),a=t===`codex_image_generation`?vT(i)??yT(n):void 0,o=a?GT(i?.savedPath)??TT(i):TT(n)??TT(i)??TT(r),s=a?GT(i?.artifactId):void 0,c=ET(n),l=hT(e.output),u=wT(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?GT(i?.model):void 0,referencedImageCount:a?DT(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?bT(e.status,a):_T(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:UT(e.status),input:gT(e.input),output:p,error:e.error}}}function hT(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=>hT(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`||KT(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=>hT(e,t+1,n))}function gT(e){if(Array.isArray(e))return e.map(gT);if(!KT(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]=gT(r)}return t}function _T(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 vT(e){let t=GT(e?.operation);return t===`generate`||t===`edit`?t:void 0}function yT(e){if(!e)return;let t=e.referenced_image_paths;return Array.isArray(t)&&t.length>0||DT(e.num_last_images_to_include)!==void 0?`edit`:`generate`}function bT(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 xT(e,t){let n=e?.[t];return KT(n)?n:void 0}function ST(e){let t=(e.title??``).trim().toLowerCase(),n=KT(e.input)?e.input:void 0;if(wT(t,[`read`,`open`]))return{id:e.id,label:`Read ${TT(n)??jT(e.input)}`,status:UT(e.status),input:e.input,output:e.output,error:e.error};if(wT(t,[`list`,`ls`,`glob`]))return{id:e.id,label:`List ${TT(n)??jT(e.input)}`,status:UT(e.status),input:e.input,output:e.output,error:e.error};if(wT(t,[`search`,`find`,`grep`,`rg`])){let t=ET(n),r=TT(n);return{id:e.id,label:`Search ${t??jT(e.input)}${r?` in ${r}`:``}`,status:UT(e.status),input:e.input,output:e.output,error:e.error}}}function CT(e){return Cw[e]??e}function wT(e,t){return t.some(t=>e===t||e.startsWith(`${t}_`)||e.endsWith(`_${t}`)||e.includes(t))}function TT(e){if(e)for(let t of[`path`,`file`,`filePath`,`filepath`,`url`,`uri`,`cwd`,`pattern`,`glob`]){let n=GT(e[t]);if(n)return n}}function ET(e){if(e)for(let t of[`query`,`pattern`,`text`,`name`,`q`,`regex`]){let n=GT(e[t]);if(n)return n}}function DT(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function OT(e,t,n=`dim`,r=160){let i={lines:[],visibleLineCount:0,omittedLineCount:0,totalLineCount:0,maxVisibleLineCount:t},a=AT(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 kT(e,t){if(!(e.omittedLineCount<=0))return{source:t,visibleLineCount:e.visibleLineCount,omittedLineCount:e.omittedLineCount,totalLineCount:e.totalLineCount,maxVisibleLineCount:e.maxVisibleLineCount}}function AT(e){let t=gx(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 jT(e){return(typeof e==`string`?e:AT(e)).replace(/\s+/g,` `).trim()}function MT(e){let t=(e??``).trim().toLowerCase();return t===`shell`||t===`bash`||t===`terminal`}function NT(e){return(e??``).trim().toLowerCase()===`web_search`}function PT(e){return e===`running`?`Searching web`:e===`error`?`Web search failed`:`Searched web`}function FT(e){let t=KT(e.input)?e.input:void 0,n=KT(e.output)?e.output:void 0;return GT(t?.query)??GT(n?.query)??GT(e.summary)}function IT(e){if(!KT(e))return;let t=e.sourceCount??e.sourcesCount;if(typeof t==`number`&&Number.isFinite(t))return t;let n=e.sources??e.citations??e.results;return Array.isArray(n)?n.length:void 0}function LT(e){if(KT(e))for(let t of[`cmd`,`command`,`script`]){let n=GT(e[t]);if(n)return n}}function RT(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 zT(e){return e===`running`?`Calling`:e===`error`?`Call failed`:`Called`}function BT(e){return e===`running`?`Spawning`:e===`error`?`Spawn failed`:`Spawned`}function VT(e){if(e.status===`running`){if(e.id.startsWith(`event:message_steered:`))return`steer`;if(e.id.startsWith(`event:message_queued:`))return`queue`}}function HT(e){return e===`running`?`Waiting for`:`Finished waiting for`}function UT(e){return e===`running`?`running`:e===`error`?`error`:`done`}function WT(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 GT(e){return typeof e==`string`&&e.trim().length?e:void 0}function KT(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function qT(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 JT(e,t,n){return n?{id:e,label:t,value:n}:void 0}function YT({field:e,icon:t}){let n=t===`session`?nt:Qe;return(0,I.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[11px]`,"data-shared-status-field":e.id,children:[(0,I.jsx)(n,{size:11,className:`shrink-0 text-[#737373]`}),(0,I.jsxs)(`span`,{className:`shrink-0 text-[#737373]`,children:[e.label,`:`]}),(0,I.jsx)(`span`,{className:`truncate font-mono ${e.id===`session`?`text-[#38bdf8]`:`text-[#d4d4d4]`}`,children:e.value})]})}function XT({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,I.jsxs)(`div`,{className:`mt-3 space-y-1`,"data-shared-progress":e.id,"data-shared-progress-state":e.state,children:[(0,I.jsxs)(`div`,{className:`flex items-center justify-between text-[11px]`,children:[(0,I.jsx)(`span`,{className:`text-[#737373]`,children:t??e.label}),(0,I.jsx)(`span`,{className:`font-mono text-[#d4d4d4]`,children:e.state===`available`?e.text:`unavailable`})]}),e.state===`available`?(0,I.jsx)(`div`,{className:`h-1.5 w-full overflow-hidden rounded-full bg-[#2a2a2a]`,children:(0,I.jsx)(`div`,{className:`h-full rounded-full ${r} transition-all`,style:{width:`${Math.min(Math.max(n,0),100)}%`}})}):null]})}function ZT(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 QT({row:e,piboSessionId:t}){let[n,r]=(0,v.useState)(null),i=n?.rowId===e.id&&Object.is(n.sourceOutput,e.output)?n.output:e.output,[a,o]=(0,v.useState)(!1),[s,c]=(0,v.useState)(!1),[l,u]=(0,v.useState)(null),d=qT(i),f=wS(e),p=i===e.output?f:wS({...e,output:i}),m=p?.kind===`status`?p.statusView:void 0,h=async()=>{if(!(!t||s)){c(!0),u(null);try{r({rowId:e.id,sourceOutput:e.output,output:await M(t)})}catch(e){u(e instanceof Error?e.message:String(e))}finally{c(!1)}}},g=(0,I.jsx)(`button`,{type:`button`,disabled:!t||s,onClick:()=>void h(),className:`ml-auto inline-flex h-7 w-7 shrink-0 items-center justify-center border border-[#3a3a3a] bg-[#151f24] text-[#737373] transition hover:border-[#38bdf8] hover:text-[#38bdf8] disabled:cursor-not-allowed disabled:opacity-50`,"aria-label":`Refresh status`,"aria-busy":s,title:s?`Refreshing status`:`Refresh status`,"data-pibo-debug":`terminal-status-refresh`,children:(0,I.jsx)(mt,{size:13,className:s?`animate-spin`:void 0})});if(!d||!m)return(0,I.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,I.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,I.jsx)(`div`,{className:`text-[#737373]`,children:`Status (unparseable)`}),g]}),l?(0,I.jsx)(`div`,{className:`mt-2 text-[11px] text-[#ef4444]`,role:`alert`,children:l}):null]});let _=new Map(m.fields.map(e=>[e.id,e])),y=_.get(`session`)??JT(`session`,`Session`,d.piboSessionId),b=_.get(`cwd`)??JT(`cwd`,`CWD`,d.cwd),x=m.progress.find(e=>e.id===`context`),S=m.progress.filter(e=>e.id.startsWith(`provider`)),C=d.providerUsage?.limits.length?d.providerUsage.limits:void 0,w=d.enabledTools??d.activeTools??[],T=m.fields.filter(e=>!new Set([`session`,`cwd`]).has(e.id)),E=d.providerUsage?.provider?`${d.providerUsage.provider} quota`:`Provider quota`;return(0,I.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,I.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[(0,I.jsx)(Ce,{size:14,className:`text-[#22c55e]`}),(0,I.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:m.title}),g]}),l?(0,I.jsx)(`div`,{className:`mb-2 text-[11px] text-[#ef4444]`,role:`alert`,children:l}):null,(0,I.jsxs)(`div`,{className:`grid grid-cols-1 gap-1.5 sm:grid-cols-2`,children:[y?(0,I.jsx)(YT,{field:y,icon:`session`}):null,b?(0,I.jsx)(YT,{field:b,icon:`cwd`}):null,T.slice(0,8).map(e=>(0,I.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[11px]`,"data-shared-status-field":e.id,children:[(0,I.jsxs)(`span`,{className:`shrink-0 text-[#737373]`,children:[e.label,`:`]}),(0,I.jsx)(`span`,{className:`truncate font-mono text-[#d4d4d4]`,children:e.value})]},e.id))]}),(0,I.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-1.5`,children:[d.processing?(0,I.jsxs)(`span`,{className:`inline-flex items-center gap-1 border border-[#1f4960] px-1.5 py-0.5 text-[11px] text-[#38bdf8]`,children:[(0,I.jsx)(qe,{size:10}),` Processing`]}):null,d.streaming?(0,I.jsxs)(`span`,{className:`inline-flex items-center gap-1 border border-[#1f4960] px-1.5 py-0.5 text-[11px] text-[#38bdf8]`,children:[(0,I.jsx)(Ce,{size:10}),` Streaming`]}):null,typeof d.queuedMessages==`number`&&d.queuedMessages>0?(0,I.jsxs)(`span`,{className:`inline-flex items-center gap-1 border border-[#3a3a3a] px-1.5 py-0.5 text-[11px] text-[#d4d4d4]`,children:[(0,I.jsx)(at,{size:10}),` Queued: `,d.queuedMessages]}):null,d.disposed?(0,I.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]}),x?(0,I.jsx)(XT,{progress:x,label:`Context Usage`}):null,S.length?(0,I.jsxs)(`div`,{className:`mt-3 space-y-1.5 border-t border-[#2a2a2a] pt-2`,"data-shared-provider-progress":S.length,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[11px] text-[#737373]`,"data-shared-status-field":`provider-quota`,children:[(0,I.jsx)($e,{size:11}),(0,I.jsxs)(`span`,{children:[E,d.providerUsage?.planType?` (${d.providerUsage.planType})`:``]})]}),C?C.map(e=>{let t=ZT(e.resetsAt);return(0,I.jsxs)(`div`,{className:`space-y-1`,"data-shared-progress":`provider-limit:${e.label}`,"data-shared-progress-state":`available`,children:[(0,I.jsxs)(`div`,{className:`flex items-center justify-between gap-2 text-[11px]`,children:[(0,I.jsx)(`span`,{className:`text-[#a3a3a3]`,children:e.label}),(0,I.jsxs)(`span`,{className:`shrink-0 font-mono text-[#d4d4d4]`,children:[e.remainingPercent.toFixed(0),`% left`,t?` · resets ${t}`:``]})]}),(0,I.jsx)(`div`,{className:`h-1.5 w-full overflow-hidden rounded-full bg-[#2a2a2a]`,children:(0,I.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??``}`)}):S.map(e=>(0,I.jsx)(XT,{progress:e},e.id)),d.providerUsage?.credits?(0,I.jsxs)(`div`,{className:`text-[11px] text-[#a3a3a3]`,"data-shared-status-field":`provider-credits`,children:[`Credits: `,d.providerUsage.credits.unlimited?`unlimited`:d.providerUsage.credits.balance??`available`]}):null]}):null,m.warnings.length||m.errors.length?(0,I.jsxs)(`div`,{className:`mt-3 space-y-1 border-t border-[#2a2a2a] pt-2`,children:[m.warnings.map((e,t)=>(0,I.jsxs)(`div`,{"data-shared-status-warning":!0,className:`text-[11px] text-[#facc15]`,children:[`⚠ `,e]},`warning-${t}`)),m.errors.map((e,t)=>(0,I.jsxs)(`div`,{"data-shared-status-error":!0,className:`text-[11px] text-[#ef4444]`,children:[`✕ `,e]},`error-${t}`))]}):null,w.length>0?(0,I.jsxs)(`div`,{className:`mt-3`,children:[(0,I.jsxs)(`button`,{type:`button`,onClick:()=>o(e=>!e),className:`flex items-center gap-1.5 text-[11px] text-[#737373] hover:text-[#d4d4d4]`,children:[(0,I.jsx)(`span`,{className:`text-[#d4d4d4]`,children:a?`▾`:`▸`}),(0,I.jsxs)(`span`,{children:[`Enabled tools (`,w.length,`)`]})]}),a?(0,I.jsx)(`div`,{className:`mt-1.5 flex flex-wrap gap-1`,children:w.map(e=>(0,I.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 $T=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function eE(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 tE(e){return $T.includes(e)?e:void 0}function nE({row:e,onLevelSelect:t}){let n=eE(e.output);return n?(0,I.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,I.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[(0,I.jsx)(Ae,{size:14,className:`text-[#f59e0b]`}),(0,I.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:`Thinking`}),n.supported===!1?(0,I.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,I.jsx)(Tt,{size:10}),` Unsupported`]}):(0,I.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,I.jsx)(Me,{size:10}),` Supported`]})]}),(0,I.jsxs)(`div`,{className:`grid gap-1.5 text-[11px]`,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,I.jsx)(`span`,{className:`text-[#737373]`,children:`Current:`}),(0,I.jsx)(`span`,{className:`font-mono font-semibold text-[#f59e0b]`,children:n.level??`unknown`})]}),n.availableLevels.length?(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,I.jsx)(`span`,{className:`mr-1 text-[#737373]`,children:`Available:`}),n.availableLevels.map(e=>{let r=tE(e),i=n.supported===!1||!r||!t;return(0,I.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,I.jsxs)(`div`,{className:`text-[#737373]`,children:[`Click a level or use `,(0,I.jsx)(`span`,{className:`text-[#f59e0b]`,children:`/thinking <level>`}),`.`]})]})]}):(0,I.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,I.jsx)(`div`,{className:`text-[#737373]`,children:`Thinking (unparseable)`})})}var rE=`pibo.chat.terminalReadingPosition.`;function iE(e){if(e)try{return oE(sessionStorage.getItem(rE+e))}catch{return}}function aE(e,t){if(e)try{let n=rE+e;t?sessionStorage.setItem(n,JSON.stringify(t)):sessionStorage.removeItem(n)}catch{}}function oE(e){if(e)try{let t=JSON.parse(e);return typeof t.rowId!=`string`||!t.rowId||typeof t.offsetPx!=`number`||!Number.isFinite(t.offsetPx)?void 0:{rowId:t.rowId,offsetPx:t.offsetPx}}catch{return}}var sE=180,cE=4800,lE=20,uE={index:`LAST`,align:`end`},dE={top:2400,bottom:2400},fE=84,pE=700,mE=6;function hE({traceView:e,isLoading:t,terminalFullscreen:n,showThinking:r,expandThinking:i,sessionAgentProfile:a,sessionActiveModel:o,sessionRuntimeBinding:s,selectedSessionStatus:c,selectedSessionSignal:l,signals:u,sessionGoal:d,sessionBreadcrumbs:f,originSession:p,derivedSessions:m,agentProfiles:h,sessionProfileChangeDisabled:g,onSessionAgentProfileChange:_,onFork:y,onOpenSession:b,onLoadOlderTracePage:x,hasOlderTraceEvents:S,isFetchingOlderTracePage:C,onThinkingLevelChange:w,onModelChanged:T}){let E=(0,v.useMemo)(()=>ww(e,{showThinking:r}),[r,e]),D=(0,v.useMemo)(()=>E.map(e=>e.id),[E]),O=e?.piboSessionId??``,[k,A]=(0,v.useState)(),ee=(0,v.useRef)(void 0),[te,ne]=(0,v.useState)(new Set),j=(0,v.useMemo)(()=>[E,te],[te,E]),[re,M]=(0,v.useState)(null),N=(0,v.useRef)({}),ie=(0,v.useRef)(!1),ae=(0,v.useRef)(!1),oe=(0,v.useRef)(void 0),se=(0,v.useRef)(!1),ce=(0,v.useRef)(!1),le=(0,v.useRef)(!1),ue=(0,v.useRef)(()=>void 0),de=E.filter(e=>EE(e,`user`)).length,fe=E.filter(e=>EE(e,`tool`)).length,P=E.filter(e=>EE(e,`system`)).length,pe=ux({signal:l,fallbackStatus:c,fallbackTurnStartedAt:(0,v.useMemo)(()=>Tw(e),[e])}),me=pe.activeTurnStartedAt,he=pe.isTurnActive,ge=!!px(d);(0,v.useLayoutEffect)(()=>{!O||!e||!Vb()||Xb(O,`compact-terminal:render`,E,{traceVersion:e.version,latestStreamId:e.latestStreamId,lastRawEventId:e.rawEvents.at(-1)?.id,selectedSessionStatus:c})},[O,E,c,e]);let _e=(0,v.useCallback)(e=>{if(!S||C||se.current)return;if(ce.current){le.current=!0;return}let t=()=>{oe.current=void 0,!se.current&&(se.current=!0,ae.current=!1,ue.current(),x?.())};if(!e||!ae.current){oe.current!==void 0&&window.clearTimeout(oe.current),t();return}oe.current===void 0&&(oe.current=window.setTimeout(t,pE))},[S,C,x]),ve=(0,v.useCallback)(()=>{ie.current&&ae.current&&_e(!0)},[_e]),ye=(0,v.useCallback)(()=>{ie.current&&(!ae.current&&!ce.current||_e(!1))},[_e]),be=(0,v.useCallback)(e=>{if(ce.current=e,e){oe.current!==void 0&&(window.clearTimeout(oe.current),oe.current=void 0,le.current=!0);return}le.current&&(le.current=!1,_e(!1))},[_e]),xe=(0,v.useCallback)((e,t)=>{VE(e,t)&&(ae.current=!0)},[]),Se=(0,v.useCallback)(e=>{ie.current&&e.startIndex<=lE&&ve()},[ve]),F=(0,v.useCallback)(e=>{O&&aE(O,e?{rowId:e.key,offsetPx:e.offset}:void 0)},[O]),Ce=to({itemCount:E.length,itemKeys:D,isPrepending:C,resetKey:e?.piboSessionId,contentKey:j,atBottomThreshold:sE,nearTopThreshold:cE,onAtTop:ye,onNearTop:ve,onUserScrollIntent:xe,onScrollbarDragChange:be,onVisibleAnchorChange:F});ue.current=Ce.prepareForPrepend,(0,v.useEffect)(()=>{ee.current=void 0,se.current=!1,ce.current=!1,le.current=!1,A(O?iE(O):void 0)},[O]),(0,v.useEffect)(()=>{se.current=!1},[e?.nextBeforeCursor,e?.nextBeforeSequence]),(0,v.useEffect)(()=>()=>{oe.current!==void 0&&window.clearTimeout(oe.current)},[]),(0,v.useEffect)(()=>{if(!O||!k)return;let t=D.indexOf(k.rowId);if(t>=0){let e=requestAnimationFrame(()=>{Ce.restoreAnchor({key:k.rowId,dataIndex:t,offset:k.offsetPx})&&A(void 0)});return()=>cancelAnimationFrame(e)}if(!S){aE(O,void 0),A(void 0);return}if(C)return;let n=String(e?.nextBeforeCursor??e?.nextBeforeSequence??E.length),r=`${O}:${n}`;ee.current!==r&&(ee.current=r,x?.())},[S,C,x,O,k,D,E.length,Ce.restoreAnchor,e?.nextBeforeCursor,e?.nextBeforeSequence]),(0,v.useEffect)(()=>{if(!O)return;let e=()=>{Ce.captureVisibleAnchor()};return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[O,Ce.captureVisibleAnchor]),(0,v.useEffect)(()=>{ne(e=>TE(e,E,i))},[i,E]),(0,v.useEffect)(()=>{ie.current=!1,ae.current=!1;let e=window.setTimeout(()=>{ie.current=!0},250);return()=>window.clearTimeout(e)},[e?.piboSessionId]),(0,v.useEffect)(()=>{let e=new Set(E.map(e=>e.id));M(t=>t&&e.has(t)?t:null);for(let t of[`system`,`tool`,`user`]){let n=N.current[t];n&&!e.has(n)&&delete N.current[t]}},[E]);let we=(0,v.useCallback)(e=>{let t=DE(E,e,N.current[e]);t&&(N.current[e]=t.row.id,M(t.row.id),Ce.scrollToIndex(t.index,`start`,`fast-smooth`,{fromIndex:t.fromIndex,stagingAlign:e===`tool`?`end`:void 0}),OE(t.row.id))},[E,Ce]),Te=e=>{e.expandable&&ne(t=>{let n=new Set(t);return n.has(e.id)?n.delete(e.id):n.add(e.id),n})},Ee=(0,v.useCallback)((t,n)=>(0,I.jsx)(`div`,{className:`px-4`,children:(0,I.jsx)(vE,{row:n,expanded:te.has(n.id),focused:re===n.id,piboSessionId:e?.piboSessionId??``,onToggle:()=>Te(n),onFork:y,onOpenSession:b,onThinkingLevelChange:w,onModelChanged:T,signals:u})}),[te,re,y,T,b,w,u,e?.piboSessionId]),De=(0,v.useMemo)(()=>({Footer:he||ge?()=>(0,I.jsx)(NE,{startedAt:me,isWorking:he,goal:d}):void 0}),[me,he,d,ge]);return(0,I.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,"data-pibo-terminal-fullscreen":n?`true`:`false`,"data-pibo-trace-has-older":e?.hasOlderEvents===!0?`true`:`false`,"data-pibo-trace-next-before":e?.nextBeforeCursor??e?.nextBeforeSequence??``,children:[n?null:(0,I.jsx)(gE,{errorCount:P,toolErrorCount:fe,userMessageCount:de,onNavigate:we,sessionAgentProfile:a,sessionActiveModel:o,sessionRuntimeBinding:s,sessionBreadcrumbs:f,originSession:p,derivedSessions:m,onOpenSession:b}),(0,I.jsx)(`div`,{className:`min-h-0 flex-1 overflow-hidden`,children:e?E.length?(0,I.jsx)(Zi,{ref:Ce.virtuosoRef,data:E,firstItemIndex:Ce.firstItemIndex,initialTopMostItemIndex:uE,increaseViewportBy:dE,defaultItemHeight:fE,className:`min-h-0 h-full overflow-x-hidden font-mono text-[12px] leading-[1.45]`,computeItemKey:(e,t)=>t.id,scrollerRef:Ce.scrollerRef,atBottomStateChange:Ce.atBottomStateChange,atBottomThreshold:Ce.atBottomThreshold,itemsRendered:Ce.itemsRendered,rangeChanged:e=>Se(Ce.normalizeRange(e)),followOutput:Ce.followOutput,totalListHeightChanged:Ce.totalListHeightChanged,alignToBottom:!0,components:De,itemContent:Ee}):(0,I.jsx)(zE,{isLoading:t,agentProfiles:h,disabled:g,onSelectAgentProfile:_,message:`No visible trace rows yet.`}):(0,I.jsx)(zE,{isLoading:t,agentProfiles:h,disabled:g,onSelectAgentProfile:_})}),E.length===0&&ge?(0,I.jsx)(NE,{isWorking:!1,goal:d}):null,Ce.isSticky?null:(0,I.jsx)(`button`,{type:`button`,onClick:()=>{aE(O,void 0),Ce.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,I.jsx)(Ne,{size:18})})]})}function gE({errorCount:e,toolErrorCount:t,userMessageCount:n,onNavigate:r,sessionAgentProfile:i,sessionActiveModel:a,sessionRuntimeBinding:o,sessionBreadcrumbs:s,originSession:c,derivedSessions:l,onOpenSession:u}){return(0,I.jsxs)(`div`,{"data-pibo-debug":`compact-terminal-header`,className:`border-b border-[#2a2a2a] bg-[#111111] px-4 py-2 text-[11px]`,children:[(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i?(0,I.jsx)(LE,{tone:`neutral`,children:i}):null,o?(0,I.jsxs)(LE,{tone:o.state===`missing`||o.state===`error`?`red`:o.state===`unbound`?`amber`:`cyan`,label:`Runtime ${o.runtimeInstanceId} · ${o.state}`,children:[o.runtimeInstanceId,` · `,o.state]}):null,a?(0,I.jsx)(LE,{tone:`purple`,children:a}):null,n>0?(0,I.jsxs)(LE,{tone:`cyan`,label:`${n} user messages · jump to previous user message`,onClick:()=>r(`user`),children:[n,(0,I.jsx)(dt,{size:12})]}):null,e>0?(0,I.jsxs)(LE,{tone:`red`,label:`${e} errors · jump to previous error`,onClick:()=>r(`system`),children:[e,(0,I.jsx)(Ue,{size:12})]}):null,t>0?(0,I.jsxs)(LE,{tone:`amber`,label:`${t} tool call errors · jump to previous tool error`,onClick:()=>r(`tool`),children:[t,(0,I.jsx)(tt,{size:12})]}):null,c?(0,I.jsxs)(_E,{onClick:()=>u(c.piboSessionId),children:[`Origin `,c.label]}):null,l.map(e=>(0,I.jsxs)(_E,{onClick:()=>u(e.piboSessionId),children:[`Derived `,e.label]},e.piboSessionId))]}),s.length?(0,I.jsx)(`div`,{className:`mt-2 flex flex-wrap items-center gap-1 text-[#737373]`,children:s.map((e,t)=>(0,I.jsxs)(`div`,{className:`flex items-center gap-1`,children:[t>0?(0,I.jsx)(Pe,{size:12,className:`text-[#525252]`}):null,(0,I.jsx)(`button`,{type:`button`,onClick:()=>u(e.piboSessionId),className:`hover:text-[#38bdf8]`,children:e.label})]},e.piboSessionId))}):null]})}function _E({children:e,onClick:t}){return(0,I.jsx)(`button`,{type:`button`,onClick:t,className:`border border-[#3a3a3a] px-2 py-0.5 text-[#38bdf8] hover:border-[#38bdf8]`,children:e})}function vE({row:e,expanded:t,focused:n,piboSessionId:r,onToggle:i,onFork:a,onOpenSession:o,onThinkingLevelChange:s,onModelChanged:c,signals:l}){let u=!t&&AE(e),d=u?kE(e):e.lines;return e.kind===`agent.delegation`?(0,I.jsx)(`div`,{className:wE(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,tabIndex:n?0:void 0,"aria-current":n?`true`:void 0,children:(0,I.jsx)(Sl,{title:e.title,summary:e.summary,input:e.input,output:e.output,error:e.error,traceStatus:e.status===`neutral`?`done`:e.status,linkedPiboSessionId:e.linkedPiboSessionId,startedAt:e.startedAt,completedAt:e.completedAt,durationMs:e.durationMs,signals:l,onOpenSession:o})}):(0,I.jsxs)(`div`,{className:wE(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||jE(t)||i()}:void 0,onKeyDown:e.expandable?t=>{!e.expandable||jE(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,I.jsxs)(`div`,{className:`flex gap-3`,children:[(0,I.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,I.jsx)(yE,{row:e,visibleLines:d,collapseToolCallPreview:u,piboSessionId:r,onThinkingLevelChange:s,onModelChanged:c})}),(0,I.jsx)(CE,{row:e,onFork:a,onOpenSession:o})]}),t?(0,I.jsx)(Tx,{row:e,onOpenSession:o}):null]})}function yE({row:e,visibleLines:t,collapseToolCallPreview:n,piboSessionId:r,onThinkingLevelChange:i,onModelChanged:a}){return e.kind===`message.assistant`?(0,I.jsxs)(`div`,{className:`ml-[1.9rem] min-w-0`,"data-pibo-component":`TerminalAssistantMessage`,children:[(0,I.jsx)(`div`,{className:`compact-terminal-markdown`,"data-pibo-component":`MarkdownRendererHost`,"data-pibo-markdown-kind":`assistant-message`,children:(0,I.jsx)(_b,{streaming:e.status===`running`,children:typeof e.output==`string`?e.output:``})}),e.status===`running`?null:(0,I.jsx)(xE,{timestamp:e.completedAt,durationMs:e.durationMs})]}):e.kind===`message.user`?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(bE,{lines:t,status:e.status,clampPreview:n}),e.pendingMessageDelivery?(0,I.jsx)(kl,{delivery:e.pendingMessageDelivery,className:`ml-[1.9rem] mt-2`}):null,(0,I.jsx)(xE,{timestamp:e.startedAt})]}):e.kind===`tool.status`?(0,I.jsx)(QT,{row:e,piboSessionId:r}):e.kind===`tool.thinking`?(0,I.jsx)(nE,{row:e,onLevelSelect:i}):e.kind===`tool.login`?(0,I.jsx)(lS,{row:e,piboSessionId:r}):e.kind===`tool.model`?(0,I.jsx)(hS,{row:e,piboSessionId:r,onModelChanged:a}):e.kind===`execution.compaction`&&e.status===`running`?(0,I.jsx)(FE,{}):e.kind===`reasoning`&&e.markdown?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(bE,{lines:t,status:e.status,clampPreview:n}),(0,I.jsx)(`div`,{className:`ml-[1.9rem] min-w-0`,"data-pibo-component":`TerminalReasoningMarkdown`,children:(0,I.jsx)(`div`,{className:`compact-terminal-markdown compact-terminal-reasoning`,"data-pibo-component":`MarkdownRendererHost`,"data-pibo-markdown-kind":`reasoning`,children:(0,I.jsx)(_b,{streaming:e.status===`running`,children:e.markdown})})})]}):(0,I.jsx)(bE,{lines:t,status:e.status,clampPreview:n})}function bE({lines:e,status:t,clampPreview:n}){return e.map((e,r)=>(0,I.jsx)(Gx,{line:e,status:t,clampLines:n&&r===0?5:void 0},r))}function xE({timestamp:e,durationMs:t}){let n=SE(e);return n?(0,I.jsxs)(`div`,{className:`mt-1 text-right font-mono text-[10px] tabular-nums text-[#737373]`,"data-pibo-component":`TerminalMessageMetadata`,children:[n,t===void 0?null:` · ${Ew(t)}`]}):null}function SE(e){if(!e)return;let t=new Date(e);if(Number.isFinite(t.getTime()))return new Intl.DateTimeFormat(void 0,{hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}).format(t)}function CE({row:e,onFork:t,onOpenSession:n}){return(0,I.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,I.jsx)(RE,{label:`Open linked session`,onClick:()=>n(e.linkedPiboSessionId),children:`Open`}):null,e.forkEntryId?(0,I.jsxs)(RE,{label:`Fork from this user message`,onClick:()=>t(e.forkEntryId),children:[(0,I.jsx)(et,{size:13}),`Fork`]}):null]})}function wE(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===`agent.delegation`?`group border-b border-[#141414] bg-[#f97316]/5 py-2 last:border-b-0`: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 TE(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 BE(e,r)?e:r}function EE(e,t){return t===`user`?e.kind===`message.user`:e.status===`error`?t===`tool`?e.errorKind===`tool`:e.errorKind!==`tool`:!1}function DE(e,t,n){let r=e.map((e,t)=>({row:e,index:t})).filter(({row:e})=>EE(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 OE(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 kE(e){return e.kind===`tool.group.exploring`||e.kind===`tool.group.images`?e.lines.slice(0,mE):e.lines}function AE(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 jE(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 ME=`Working...`;function NE({startedAt:e,isWorking:t,goal:n}){let r=PE(t?e:void 0),i=px(n),a=[t?`Working`:void 0,i===`active`?`Pursuing Goal`:i===`paused`?`Goal Paused`:void 0].filter(Boolean).join(`. `);return(0,I.jsx)(`div`,{className:`border-t border-[#141414] px-4 py-2`,role:`status`,"aria-live":`polite`,"aria-label":a,"data-pibo-component":`TerminalStreamingFooter`,"data-pibo-active-turn-started-at":t?e:void 0,children:(0,I.jsxs)(`div`,{className:`flex min-w-0 items-baseline justify-between gap-4`,"aria-hidden":`true`,children:[t?(0,I.jsxs)(`div`,{className:`grid min-w-0 flex-1 grid-cols-[1.9rem_minmax(0,1fr)] gap-2 whitespace-pre-wrap break-words`,children:[(0,I.jsx)(`span`,{className:`whitespace-pre text-[#737373]`,children:`•`}),(0,I.jsxs)(`span`,{className:`inline-flex min-w-0 items-baseline gap-2`,children:[r?(0,I.jsx)(`span`,{className:`shrink-0 tabular-nums text-[#737373]`,children:r}):null,(0,I.jsx)(`span`,{className:`compact-terminal-working-label`,children:ME})]})]}):(0,I.jsx)(`span`,{className:`min-w-0 flex-1`}),(0,I.jsx)(dx,{goal:n})]})})}function PE(e){let t=e?new Date(e).getTime():NaN,[n,r]=(0,v.useState)(()=>Date.now());return(0,v.useEffect)(()=>{if(r(Date.now()),!Number.isFinite(t))return;let e=window.setInterval(()=>r(Date.now()),1e3);return()=>window.clearInterval(e)},[t]),Number.isFinite(t)?Ew(Math.max(0,n-t)):void 0}function FE(){let e=IE();return(0,I.jsxs)(`div`,{className:`grid grid-cols-[1.9rem_minmax(0,1fr)] gap-2 whitespace-pre-wrap break-words`,children:[(0,I.jsx)(`span`,{className:`whitespace-pre text-[#38bdf8]`,children:`•`}),(0,I.jsxs)(`span`,{className:`min-w-0`,children:[(0,I.jsx)(`span`,{className:`font-semibold text-[#38bdf8]`,children:`Compacting`}),(0,I.jsx)(`span`,{className:`text-[#38bdf8]`,children:e})]})]})}function IE(){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 LE({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,I.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,I.jsx)(`span`,{className:i,title:t,"aria-label":t,children:r})}function RE({label:e,onClick:t,children:n}){return(0,I.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 zE({isLoading:e,agentProfiles:t,disabled:n,onSelectAgentProfile:r,message:i}){return(0,I.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,I.jsx)(`div`,{children:e?`Loading trace…`:i??`No trace selected.`}),t.length?(0,I.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:t.map(e=>(0,I.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 BE(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function VE(e,t){return t?t===`away`:e instanceof WheelEvent?e.deltaY<0:e instanceof KeyboardEvent?[`ArrowUp`,`PageUp`,`Home`].includes(e.key):e?.type===`touchmove`}function HE({traceView:e,isLoading:t,selectedSessionStatus:n,selectedSessionSignal:r,workflowProjectSession:i,workflowLifecycleEvents:a,sessionNodes:o,onOpenSession:s,onRefreshBootstrap:c,onError:l}){let u=i?cD(i,e,n,r,a??[],o):null;return u?(0,I.jsx)(`section`,{className:`min-w-0 flex-1 overflow-auto bg-[#0b0f14] p-4 text-slate-300`,children:(0,I.jsxs)(`div`,{className:`mx-auto flex max-w-6xl flex-col gap-4`,children:[(0,I.jsx)(UE,{model:u}),(0,I.jsx)(WE,{}),(0,I.jsx)(GE,{model:u,onRefreshBootstrap:c,onError:l}),(0,I.jsx)(qE,{model:u}),(0,I.jsx)(JE,{model:u,onOpenSession:s}),(0,I.jsx)(tD,{nodes:u.nodes,edges:u.edges}),(0,I.jsxs)(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_360px]`,children:[(0,I.jsx)(rD,{model:u}),(0,I.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-4`,children:[(0,I.jsx)(iD,{model:u}),(0,I.jsx)(aD,{model:u}),(0,I.jsx)(oD,{model:u})]})]})]})}):(0,I.jsx)(`section`,{className:`min-w-0 flex-1 overflow-auto bg-[#0b0f14] p-4 text-slate-300`,children:(0,I.jsxs)(`div`,{className:`mx-auto flex max-w-4xl flex-col gap-4`,children:[(0,I.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4`,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-semibold text-slate-100`,children:[(0,I.jsx)(at,{size:16,className:`text-[#11a4d4]`}),`Workflow / XState`]}),(0,I.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,I.jsx)(WE,{})]})})}function UE({model:e}){return(0,I.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4`,children:[(0,I.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,I.jsxs)(`div`,{className:`min-w-0`,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-semibold text-slate-100`,children:[(0,I.jsx)(at,{size:16,className:`text-[#11a4d4]`}),`Workflow / XState Projection`]}),(0,I.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2 text-xs`,children:[(0,I.jsx)(WD,{tone:`blue`,children:e.workflowId}),e.workflowRunId?(0,I.jsxs)(WD,{tone:`slate`,children:[`run `,YD(e.workflowRunId)]}):null,(0,I.jsx)(WD,{tone:GD(e.status),children:e.state})]})]}),(0,I.jsxs)(`div`,{className:`min-w-0 text-right font-mono text-[11px] text-slate-500`,children:[(0,I.jsxs)(`div`,{className:`truncate`,children:[`session `,YD(e.piboSessionId)]}),e.latestStreamId===void 0?null:(0,I.jsxs)(`div`,{children:[`stream `,e.latestStreamId]})]})]}),(0,I.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 WE(){return(0,I.jsx)(`div`,{className:`rounded-sm border border-amber-500/30 bg-amber-500/10 p-4 text-sm`,children:(0,I.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,I.jsxs)(`div`,{className:`min-w-0`,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-amber-200`,children:[(0,I.jsx)(St,{size:14}),`Workflow IR source-of-truth boundary`]}),(0,I.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,I.jsxs)(`div`,{className:`flex shrink-0 flex-wrap gap-2`,children:[(0,I.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,I.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 GE({model:e,onRefreshBootstrap:t,onError:n}){let r=e.workflowRunId?eD(e):void 0,i=`${e.workflowId}${e.workflowVersion?`@${e.workflowVersion}`:``}`;return(0,I.jsxs)(`div`,{className:`grid gap-4 lg:grid-cols-3`,"aria-label":`Projects workflow execution shell`,children:[(0,I.jsx)(QE,{title:`Workflow configured-session view`,icon:(0,I.jsx)(st,{size:14}),children:(0,I.jsxs)(`div`,{className:`space-y-3 text-xs text-slate-400`,children:[(0,I.jsx)($E,{label:`selected workflow`,value:i}),(0,I.jsx)($E,{label:`session state`,value:e.workflowRunId?`started`:`configured/not-started`}),(0,I.jsx)($E,{label:`input keys`,value:String(e.configuration.inputKeys.length)}),(0,I.jsx)($E,{label:`prompt overrides`,value:String(e.configuration.promptOverrideNodeIds.length)}),(0,I.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,I.jsx)(QE,{title:`Workflow run view`,icon:(0,I.jsx)(Ce,{size:14}),children:(0,I.jsxs)(`div`,{className:`space-y-3 text-xs text-slate-400`,children:[(0,I.jsx)($E,{label:`run id`,value:e.workflowRunId?YD(e.workflowRunId):`not started`}),(0,I.jsx)($E,{label:`status`,value:e.state}),(0,I.jsx)($E,{label:`current node`,value:r?.label??`none`}),(0,I.jsx)($E,{label:`output`,value:e.finalOutput?`available`:`empty`}),(0,I.jsx)($E,{label:`error`,value:e.runtimeErrors.length?`${e.runtimeErrors.length} runtime errors`:e.validationErrors.length?`${e.validationErrors.length} validation diagnostics`:`none`}),(0,I.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,I.jsx)(QE,{title:`Human action area`,icon:(0,I.jsx)(Ge,{size:14}),children:(0,I.jsx)(KE,{model:e,onRefreshBootstrap:t,onError:n})})]})}function KE({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 rS(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=MD(e);c(e=>({...e,[i.waitTokenId]:t})),n?.(t[0]?.message??ND(e))}finally{o(null)}};return(0,I.jsxs)(`div`,{className:`space-y-3 text-xs text-slate-400`,children:[e.pendingHumanActions.length?(0,I.jsx)(`div`,{className:`space-y-3`,children:e.pendingHumanActions.map(e=>{let t=[...e.diagnostics,...e.waitTokenId?s[e.waitTokenId]??[]:[]];return(0,I.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,I.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,I.jsxs)(`div`,{className:`min-w-0`,children:[(0,I.jsx)(`div`,{className:`font-semibold`,children:e.label}),(0,I.jsx)(`div`,{className:`mt-1 break-words text-[11px] leading-5 text-amber-100/80`,children:e.prompt})]}),(0,I.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?YD(e.waitTokenId):e.source})]}),(0,I.jsxs)(`div`,{className:`mt-2 grid gap-2 text-[11px] text-amber-100/75`,children:[(0,I.jsx)($E,{label:`human node`,value:e.humanNodeId??`unspecified`}),(0,I.jsx)($E,{label:`payload`,value:e.payloadRequirements?.description??`No persisted payload schema.`}),e.expiresAt?(0,I.jsx)($E,{label:`expires`,value:e.expiresAt}):null]}),e.payloadRequirements?.schema?(0,I.jsxs)(`div`,{className:`mt-2 rounded-sm border border-amber-400/25 bg-[#0b0f14]/50 p-2`,children:[(0,I.jsx)(`div`,{className:`mb-1 text-[10px] font-bold uppercase tracking-wider text-amber-100/70`,children:`Resume payload schema`}),(0,I.jsx)(bl,{value:e.payloadRequirements.schema,defaultExpandLevel:1,maxHeight:`10rem`,showControls:!1})]}):null,e.availableActions.some(e=>e.kind===`resume`)?(0,I.jsxs)(`label`,{className:`mt-3 block text-[11px] text-amber-100/80`,children:[(0,I.jsx)(`span`,{className:`mb-1 block font-semibold`,children:`Resume payload JSON`}),(0,I.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,I.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,I.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,I.jsx)(`span`,{className:`text-amber-100/60`,children:`No registered human actions are available for this wait token.`})}),e.waitTokenId&&l[e.waitTokenId]?(0,I.jsx)(`div`,{className:`mt-2 text-[11px] text-emerald-200`,children:l[e.waitTokenId]}):null,t.length?(0,I.jsx)(`div`,{className:`mt-2 space-y-1`,"aria-label":`Human action diagnostics`,children:t.map((e,t)=>(0,I.jsxs)(`div`,{className:`rounded border border-red-400/35 bg-red-500/15 p-2 text-[11px] leading-5 text-red-100`,children:[(0,I.jsx)(`div`,{children:e.message}),(0,I.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,I.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,I.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 qE({model:e}){let t=e.workflowRunId?eD(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,I.jsxs)(`section`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,"aria-label":`Workflow run inspection panel`,children:[(0,I.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,I.jsxs)(`div`,{className:`min-w-0`,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,I.jsx)(Je,{size:14}),`Workflow run inspection`]}),(0,I.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,I.jsxs)(`div`,{className:`flex shrink-0 flex-wrap gap-2 text-[10px] uppercase tracking-wide`,children:[(0,I.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,I.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,I.jsxs)(`div`,{className:`mt-4 grid gap-3 lg:grid-cols-3`,children:[(0,I.jsxs)(YE,{title:`Status`,badge:e.state,icon:(0,I.jsx)(Ce,{size:14}),children:[(0,I.jsx)(XE,{label:`run id`,value:e.workflowRunId?YD(e.workflowRunId):`not started`}),(0,I.jsx)(XE,{label:`status`,value:e.state}),(0,I.jsx)(XE,{label:`record source`,value:e.workflowRunId?`Project workflow run id`:`no run record yet`})]}),(0,I.jsxs)(YE,{title:`Current node`,badge:t?.status??`none`,icon:(0,I.jsx)(ht,{size:14}),children:[(0,I.jsx)(XE,{label:`node`,value:t?.label??`none`}),(0,I.jsx)(XE,{label:`node id`,value:t?.id??`none`}),(0,I.jsx)(XE,{label:`source`,value:`project/session run cursor`})]}),(0,I.jsx)(YE,{title:`Run history`,badge:`${e.runHistory.length}`,icon:(0,I.jsx)(rt,{size:14}),children:e.runHistory.length?(0,I.jsx)(`div`,{className:`space-y-2`,children:e.runHistory.map(e=>(0,I.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:[(0,I.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,I.jsx)(`div`,{className:`min-w-0 truncate font-mono text-xs text-slate-200`,children:YD(e.id)}),(0,I.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide ${JD(e.status)}`,children:e.status})]}),(0,I.jsxs)(`div`,{className:`mt-1 text-[11px] text-slate-500`,children:[e.currentNodeId?`current ${e.currentNodeId}`:`no current node`,` · `,e.source]}),(0,I.jsxs)(`div`,{className:`mt-1 font-mono text-[10px] text-slate-600`,children:[`updated `,e.updatedAt]})]},e.id))}):(0,I.jsx)(ZE,{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,I.jsxs)(`div`,{className:`mt-3 grid gap-3 lg:grid-cols-2`,children:[(0,I.jsx)(YE,{title:`Node attempts`,badge:`${e.nodeAttempts.length}`,icon:(0,I.jsx)(st,{size:14}),children:e.nodeAttempts.length?(0,I.jsx)(`div`,{className:`space-y-2`,children:e.nodeAttempts.map(e=>(0,I.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:[(0,I.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,I.jsxs)(`div`,{className:`min-w-0`,children:[(0,I.jsx)(`div`,{className:`truncate text-xs font-semibold text-slate-200`,children:e.label}),(0,I.jsxs)(`div`,{className:`mt-1 font-mono text-[10px] text-slate-500`,children:[e.nodeId,` · attempt `,e.attempt]})]}),(0,I.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide ${JD(e.status)}`,children:e.status})]}),(0,I.jsxs)(`div`,{className:`mt-1 text-[11px] text-slate-500`,children:[e.kind,` · `,e.source]})]},e.id))}):(0,I.jsx)(ZE,{children:e.workflowRunId?`No node attempts recorded for this workflow run yet.`:`No current node attempts; Start has not created a workflow run.`})}),(0,I.jsx)(YE,{title:`Edge transfers`,badge:`${e.edgeTransfers.length}`,icon:(0,I.jsx)(et,{size:14}),children:e.edgeTransfers.length?(0,I.jsx)(`div`,{className:`space-y-2`,children:e.edgeTransfers.map(e=>(0,I.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:[(0,I.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,I.jsx)(`div`,{className:`min-w-0 truncate font-mono text-xs text-slate-200`,children:e.edgeId}),(0,I.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide ${JD(e.status)}`,children:e.status})]}),(0,I.jsxs)(`div`,{className:`mt-1 text-[11px] text-slate-500`,children:[e.source,e.createdAt?` · ${e.createdAt}`:``]})]},e.id))}):(0,I.jsx)(ZE,{children:`No edge transfers recorded for this workflow run yet.`})}),(0,I.jsx)(YE,{title:`Output`,badge:e.finalOutput?`available`:`empty`,icon:(0,I.jsx)(Be,{size:14}),children:e.finalOutput?(0,I.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:[(0,I.jsx)(`div`,{className:`mb-2 font-mono text-[10px] text-slate-500`,children:e.finalOutput.source}),(0,I.jsx)(bl,{value:e.finalOutput.value,defaultExpandLevel:1,maxHeight:`12rem`,showControls:!1})]}):(0,I.jsx)(ZE,{children:`No workflow output has been recorded for this run yet.`})}),(0,I.jsx)(YE,{title:`Error`,badge:n.length?`${n.length}`:`none`,icon:(0,I.jsx)(St,{size:14}),children:n.length?(0,I.jsx)(`div`,{className:`space-y-2`,children:n.map(e=>(0,I.jsxs)(`div`,{className:`rounded-sm border border-red-500/35 bg-red-500/10 p-2 text-xs text-red-100`,children:[(0,I.jsx)(`div`,{className:`break-words`,children:e.message}),(0,I.jsxs)(`div`,{className:`mt-1 flex flex-wrap gap-1 font-mono text-[10px] text-red-200/70`,children:[e.code?(0,I.jsx)(`span`,{children:e.code}):null,e.source?(0,I.jsx)(`span`,{children:e.source}):null]})]},e.id))}):(0,I.jsx)(ZE,{children:`No workflow run errors are recorded.`})})]})]})}function JE({model:e,onOpenSession:t}){let n=fD(e.definitionLink);return(0,I.jsxs)(`section`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,"aria-label":`Workflow navigation links`,children:[(0,I.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,I.jsxs)(`div`,{className:`min-w-0`,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,I.jsx)(Ye,{size:14}),`Workflow navigation links`]}),(0,I.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,I.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,I.jsx)(Ye,{size:13}),`Open live workflow definition`]}):null]}),(0,I.jsxs)(`div`,{className:`mt-4 grid gap-3 lg:grid-cols-2`,children:[(0,I.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0f171e] p-3`,"aria-label":`Nested workflow child session links`,children:[(0,I.jsxs)(`div`,{className:`mb-3 flex items-center justify-between gap-2`,children:[(0,I.jsx)(`div`,{className:`text-xs font-bold uppercase tracking-wider text-slate-500`,children:`Nested workflow child sessions`}),(0,I.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,I.jsx)(`div`,{className:`space-y-2`,children:e.nestedSessionLinks.map(e=>(0,I.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,I.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,I.jsxs)(`div`,{className:`min-w-0`,children:[(0,I.jsx)(`div`,{className:`truncate text-xs font-semibold text-slate-200`,children:e.title}),(0,I.jsx)(`div`,{className:`mt-1 font-mono text-[10px] text-slate-500`,children:YD(e.piboSessionId)})]}),(0,I.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,I.jsx)(ZE,{children:`No nested workflow child sessions are linked under this selected Project session yet.`})]}),(0,I.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0f171e] p-3`,"aria-label":`Workflow definition link state`,children:[(0,I.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,I.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,I.jsx)(`div`,{className:`font-semibold`,children:`Live workflow definition exists`}),(0,I.jsx)(`div`,{className:`mt-1 font-mono text-[11px] text-emerald-100/80`,children:mD(e.definitionLink)}),e.definitionLink.definitionHash?(0,I.jsxs)(`div`,{className:`mt-1 font-mono text-[10px] text-emerald-100/60`,children:[`snapshot `,YD(e.definitionLink.definitionHash)]}):null]}):(0,I.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,I.jsx)(`div`,{className:`font-semibold`,children:`Definition deleted — snapshot-only definition-deleted state`}),(0,I.jsx)(`div`,{className:`mt-1 font-mono text-[11px] text-amber-100/80`,children:mD(e.definitionLink)}),(0,I.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,I.jsxs)(`div`,{className:`mt-1 font-mono text-[10px] text-amber-100/60`,children:[`snapshot `,YD(e.definitionLink.definitionHash)]}):null]})]})]})]})}function YE({title:e,badge:t,icon:n,children:r}){return(0,I.jsxs)(`section`,{className:`min-w-0 rounded-sm border border-slate-800 bg-[#0f171e] p-3`,"aria-label":e,children:[(0,I.jsxs)(`div`,{className:`mb-3 flex items-center justify-between gap-3`,children:[(0,I.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,I.jsx)(`span`,{className:`text-[#11a4d4]`,children:n}),e]}),(0,I.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 XE({label:e,value:t}){return(0,I.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,I.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-slate-500`,children:e}),(0,I.jsx)(`span`,{className:`min-w-0 max-w-[14rem] truncate text-right font-mono text-xs text-slate-300`,title:t,children:t})]})}function ZE({children:e}){return(0,I.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 QE({title:e,icon:t,children:n}){return(0,I.jsxs)(`section`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4`,"aria-label":e,children:[(0,I.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,I.jsx)(`span`,{className:`text-[#11a4d4]`,children:t}),e]}),n]})}function $E({label:e,value:t}){return(0,I.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,I.jsx)(`span`,{className:`uppercase tracking-wide text-slate-500`,children:e}),(0,I.jsx)(`span`,{className:`min-w-0 max-w-[12rem] truncate text-right font-mono text-slate-300`,title:t,children:t})]})}function eD(e){return e.nodes.find(e=>e.status===`active`||e.status===`waiting`)??e.nodes[0]}function tD({nodes:e,edges:t}){return(0,I.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0f171e] p-4`,children:[(0,I.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,I.jsx)(ht,{size:14}),`Visual State Flow`]}),(0,I.jsx)(`div`,{className:`grid gap-3 md:grid-cols-[1fr_auto_1fr_auto_1fr]`,children:e.map((e,n)=>(0,I.jsx)(nD,{node:e,edge:t[n]},e.id))})]})}function nD({node:e,edge:t}){return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)(`div`,{className:`rounded-sm border p-3 ${KD(e.status)}`,children:[(0,I.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,I.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,I.jsx)(UD,{status:e.status}),(0,I.jsx)(`div`,{className:`min-w-0 truncate text-sm font-semibold text-slate-100`,children:e.label})]}),(0,I.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,I.jsx)(`p`,{className:`mt-2 text-xs text-slate-400`,children:e.description})]}),t?(0,I.jsx)(`div`,{className:`hidden items-center justify-center text-center text-[10px] uppercase tracking-wide text-slate-500 md:flex`,children:(0,I.jsxs)(`div`,{children:[(0,I.jsx)(et,{size:14,className:`mx-auto mb-1 text-[#11a4d4]`}),t.label]})}):null]})}function rD({model:e}){return(0,I.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4`,children:[(0,I.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,I.jsx)(Ce,{size:14}),`Current UI Snapshot`]}),(0,I.jsx)(bl,{value:e.snapshot,showControls:!1})]})}function iD({model:e}){return(0,I.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,children:[(0,I.jsxs)(`div`,{className:`mb-3 flex items-center justify-between gap-3`,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,I.jsx)(st,{size:14}),`Node Statuses`]}),(0,I.jsxs)(`span`,{className:`font-mono text-[11px] text-slate-500`,children:[e.nodes.length,` nodes`]})]}),(0,I.jsx)(`div`,{className:`space-y-2`,children:e.nodes.map(e=>(0,I.jsxs)(`div`,{className:`rounded-sm border px-3 py-2 ${KD(e.status)}`,children:[(0,I.jsxs)(`div`,{className:`flex min-w-0 items-start justify-between gap-3`,children:[(0,I.jsxs)(`div`,{className:`flex min-w-0 items-start gap-2`,children:[(0,I.jsx)(`span`,{className:`mt-0.5 shrink-0`,children:(0,I.jsx)(UD,{status:e.status})}),(0,I.jsxs)(`div`,{className:`min-w-0`,children:[(0,I.jsx)(`div`,{className:`truncate text-sm font-semibold text-slate-100`,children:e.label}),(0,I.jsx)(`div`,{className:`mt-0.5 truncate font-mono text-[11px] text-slate-500`,children:e.id})]})]}),(0,I.jsxs)(`div`,{className:`flex shrink-0 flex-col items-end gap-1`,children:[(0,I.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide ${qD(e.status)}`,children:e.status}),(0,I.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,I.jsx)(`p`,{className:`mt-2 text-xs text-slate-400`,children:e.description})]},e.id))}),(0,I.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 aD({model:e}){return(0,I.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,children:[(0,I.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,I.jsx)(Be,{size:14}),`Final Output & Validation`]}),(0,I.jsxs)(`div`,{className:`space-y-4`,children:[(0,I.jsxs)(`div`,{children:[(0,I.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,I.jsx)(`div`,{className:`text-xs font-semibold uppercase tracking-wide text-slate-400`,children:`Final output`}),e.finalOutput?(0,I.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,I.jsx)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:(0,I.jsx)(bl,{value:e.finalOutput.value,defaultExpandLevel:1,maxHeight:`14rem`,showControls:!1})}):(0,I.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,I.jsxs)(`div`,{children:[(0,I.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,I.jsx)(`div`,{className:`text-xs font-semibold uppercase tracking-wide text-slate-400`,children:`Validation errors`}),(0,I.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,I.jsx)(`div`,{className:`space-y-2`,children:e.validationErrors.map(e=>(0,I.jsx)(`div`,{className:`rounded-sm border border-red-500/35 bg-red-500/10 p-2`,children:(0,I.jsxs)(`div`,{className:`flex min-w-0 items-start gap-2 text-xs text-red-200`,children:[(0,I.jsx)(St,{size:14,className:`mt-0.5 shrink-0 text-red-300`}),(0,I.jsxs)(`div`,{className:`min-w-0`,children:[(0,I.jsx)(`div`,{className:`break-words`,children:e.message}),(0,I.jsxs)(`div`,{className:`mt-1 flex flex-wrap gap-1 font-mono text-[10px] text-red-200/70`,children:[e.code?(0,I.jsx)(`span`,{children:e.code}):null,e.path?(0,I.jsx)(`span`,{children:e.path}):null,e.source?(0,I.jsx)(`span`,{children:e.source}):null]})]})]})},e.id))}):(0,I.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 oD({model:e}){return(0,I.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,children:[(0,I.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,I.jsx)(We,{size:14}),`Projection Facts`]}),(0,I.jsxs)(`dl`,{className:`space-y-3`,children:[(0,I.jsx)(sD,{label:`projection kind`,value:`pibo.workflow.xstateUiModel`}),(0,I.jsx)(sD,{label:`schema`,value:`v1`}),(0,I.jsx)(sD,{label:`durable truth`,value:`kernel`}),(0,I.jsx)(sD,{label:`private payloads`,value:`not exposed`}),(0,I.jsx)(sD,{label:`states`,value:String(e.nodes.length)}),(0,I.jsx)(sD,{label:`transitions`,value:String(e.edges.length)}),(0,I.jsx)(sD,{label:`trace`,value:e.traceVersion??`pending`})]})]})}function sD({label:e,value:t}){return(0,I.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,I.jsx)(`dt`,{className:`text-xs uppercase tracking-wide text-slate-500`,children:e}),(0,I.jsx)(`dd`,{className:`min-w-0 truncate text-right font-mono text-xs text-slate-300`,children:t})]})}function cD(e,t,n,r,i,a){if(!ID(e))return null;let o=LD(e,n),s=RD(e,n),c=zD(s),l=wD(t,s),u=[...ED(t),...TD(e,i)],d=_D(e,o,c),f=vD(t,e.workflowRunId),p=xD(t,e.workflowRunId),m=SD(t,r),h=lD(e),g=uD(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:BD(s),label:VD(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:BD(s),label:HD(s)}],configuration:hD(e),definitionLink:h,nestedSessionLinks:g,pendingHumanActions:gD(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`&&!!fD(h)},nestedWorkflowSessionCount:g.length}}}function lD(e){return e.workflowDefinitionLink?e.workflowDefinitionLink:e.workflowVersion?{status:`live`,workflowId:e.workflowId,workflowVersion:e.workflowVersion,title:e.title??e.workflowId,href:pD(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 uD(e,t){let n=dD(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 dD(e,t){for(let n of e){if(n.piboSessionId===t)return n;let e=dD(n.children,t);if(e)return e}}function fD(e){if(e.status===`live`){if(e.href)return e.href;if(e.workflowVersion)return pD(e.workflowId,e.workflowVersion)}}function pD(e,t){return`/apps/chat/workflows/view/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function mD(e){return`${e.workflowId}${e.workflowVersion?`@${e.workflowVersion}`:``}`}function hD(e){let t=e.configuration;return{inputKeys:Object.keys(t?.inputValues??{}).sort(),promptOverrideNodeIds:Object.keys(t?.promptOverrides??{}).sort()}}function gD(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=LD(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 _D(e,t,n){return e.workflowRunId?[{id:e.workflowRunId,status:t,currentNodeId:n,updatedAt:e.updatedAt,source:`project session run record`}]:[]}function vD(e,t){return!t||!e?[]:DD(e.nodes).filter(yD).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:bD(e.status),attempt:t+1,source:`session trace fact`,...e.startedAt?{startedAt:e.startedAt}:{},...e.completedAt?{completedAt:e.completedAt}:{}}))}function yD(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 bD(e){return e===`done`?`completed`:e===`error`?`failed`:`running`}function xD(e,t){if(!t||!e)return[];let n=[];for(let r of e.rawEvents){if(!FD(r.payload))continue;let e=PD(r.payload.type),i=PD(r.payload.runId);if(e!==`edge.transferred`||i&&i!==t)continue;let a=PD(r.payload.edgeId);a&&n.push({id:PD(r.payload.edgeTransferId)??r.id,edgeId:a,status:`transferred`,source:r.type,createdAt:r.createdAt})}return n.slice(0,8)}function SD(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 DD(e.nodes)){let e=t.error??(t.status===`error`?kD(t.output)??kD(t.summary):void 0);e&&n.push({id:`node:${t.id}`,message:e,source:t.type})}for(let t of e.rawEvents){if(!FD(t.payload))continue;let e=t.payload.error,r=FD(e)?PD(e.message):PD(e),i=FD(e)?PD(e.code):void 0;r&&n.push({id:`event:${t.id}`,message:r,...i?{code:i}:{},source:t.type})}}return CD(n).slice(0,8)}function CD(e){let t=new Set;return e.filter(e=>{let n=`${e.code??``}:${e.message}:${e.source??``}`;return!t.has(n)&&(t.add(n),!0)})}function wD(e,t){if(t!==`completed`||!e)return;let n=DD(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 TD(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 jD(n).slice(0,8)}function ED(e){if(!e)return[];let t=[];for(let n of DD(e.nodes)){let e=n.error??kD(n.output)??kD(n.summary);e&&(!AD([n.title,n.summary,n.error,n.type].filter(e=>typeof e==`string`).join(` `))&&!AD(e)||t.push({id:`node:${n.id}`,message:e,...n.type?{source:n.type}:{}}))}for(let n of e.rawEvents)OD(n.payload,`event:${n.id}`,t);return jD(t).slice(0,8)}function DD(e){let t=[],n=e=>{for(let r of e)t.push(r),n(r.children)};return n(e),t}function OD(e,t,n,r=0){if(r>4||!FD(e))return;let i=Array.isArray(e.diagnostics)?e.diagnostics:void 0;if(i)for(let e of i){if(!FD(e))continue;let r=PD(e.message)??kD(e);r&&n.push({id:`${t}:diagnostic:${n.length}`,message:r,...PD(e.code)?{code:PD(e.code)}:{},...PD(e.path)?{path:PD(e.path)}:{},source:`workflow.diagnostic`})}let a=e.error;if(FD(a)){let e=PD(a.code),r=PD(a.message)??kD(a);r&&AD([e,r].filter(Boolean).join(` `))&&n.push({id:`${t}:error:${n.length}`,message:r,...e?{code:e}:{},source:`workflow.error`})}else typeof a==`string`&&AD(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`)&&OD(a,`${t}:${i}`,n,r+1)}function kD(e){if(typeof e==`string`)return e;if(FD(e))return PD(e.message)??PD(e.error)??PD(e.summary)}function AD(e){let t=e.toLowerCase();return t.includes(`validation`)||t.includes(`validate`)||t.includes(`diagnostic`)||t.includes(`workflowinterfaceerror`)||t.includes(`workflowruntimeerror.validation`)}function jD(e){let t=new Set;return e.filter(e=>{let n=`${e.code??``}:${e.path??``}:${e.message}`;return!t.has(n)&&(t.add(n),!0)})}function MD(e){return FD(e)&&FD(e.data)&&Array.isArray(e.data.diagnostics)?e.data.diagnostics.filter(FD).map(t=>({code:PD(t.code)??`WorkflowRuntimeError.humanActionRejected`,message:PD(t.message)??ND(e),severity:t.severity===`info`||t.severity===`warning`||t.severity===`error`?t.severity:`error`,...PD(t.path)?{path:PD(t.path)}:{},...PD(t.registryRef)?{registryRef:PD(t.registryRef)}:{},...PD(t.hint)?{hint:PD(t.hint)}:{}})):[{code:`WorkflowRuntimeError.humanActionRejected`,message:ND(e),severity:`error`}]}function ND(e){return e instanceof Error?e.message:String(e)}function PD(e){return typeof e==`string`&&e.trim()?e:void 0}function FD(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function ID(e){return!!e.workflowRunId||e.state===`workflow`||e.workflowId!==`simple-chat`}function LD(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 RD(e,t){let n=LD(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 zD(e){return e===`completed`?`workflow.completed`:e===`failed`?`workflow.failed`:e===`cancelled`?`workflow.cancelled`:`node.session`}function BD(e){return e===`failed`?`workflow.failed`:e===`cancelled`?`workflow.cancelled`:`workflow.completed`}function VD(e){return e===`failed`?`failed`:e===`cancelled`?`cancelled`:`completed`}function HD(e){return e===`failed`?`WORKFLOW.FAIL`:e===`cancelled`?`WORKFLOW.CANCEL`:`WORKFLOW.NODE.DONE`}function UD({status:e}){return e===`completed`?(0,I.jsx)(Be,{size:16,className:`text-emerald-300`}):e===`failed`?(0,I.jsx)(Ue,{size:16,className:`text-red-300`}):e===`cancelled`?(0,I.jsx)(St,{size:16,className:`text-slate-400`}):e===`waiting`?(0,I.jsx)(Ge,{size:16,className:`text-amber-300`}):e===`active`?(0,I.jsx)(Ce,{size:16,className:`text-[#11a4d4]`}):(0,I.jsx)(We,{size:16,className:`text-slate-500`})}function WD({tone:e,children:t}){return(0,I.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 GD(e){return e===`completed`?`green`:e===`failed`||e===`cancelled`?`red`:e===`waiting`?`amber`:`blue`}function KD(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 qD(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 JD(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 YD(e){return e.length>18?`${e.slice(0,10)}…${e.slice(-6)}`:e}var XD=[{id:`terminal`,label:`Terminal`,description:`Compact Codex-style terminal transcript.`,render:e=>(0,I.jsx)(hE,{...e})},{id:`workflow`,label:`Workflow`,description:`Workflow/XState visualization for workflow-backed project sessions.`,render:e=>(0,I.jsx)(HE,{...e})}],ZD=new Map(XD.map(e=>[e.id,e]));function QD(){return XD}function $D(e){return ZD.get(e)??ZD.get(`terminal`)}var eO=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(){}},tO=new class extends eO{#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`}},nO={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},rO=new class{#e=nO;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 iO(e){setTimeout(e,0)}var aO=typeof window>`u`||`Deno`in globalThis;function oO(){}function sO(e){return typeof e==`number`&&e>=0&&e!==1/0}function cO(e,t){return Math.max(e+(t||0)-Date.now(),0)}function lO(e,t){return typeof e==`function`?e(t):e}function uO(e,t){return typeof e==`function`?e(t):e}var dO=Object.prototype.hasOwnProperty;function fO(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=mO(e)&&mO(t);if(!r&&!(hO(e)&&hO(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:dO.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=fO(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function pO(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 mO(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function hO(e){if(!gO(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!gO(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function gO(e){return Object.prototype.toString.call(e)===`[object Object]`}function _O(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:fO(e,t)}function vO(e,t){return typeof e==`function`?e(...t):!!e}var yO=(()=>{let e=()=>aO;return{isServer(){return e()},setIsServer(t){e=t}}})();function bO(){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 xO=iO;function SO(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=xO,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 CO=SO(),wO=new class extends eO{#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 TO(e){return(e??`online`)!==`online`||wO.isOnline()}function EO(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:TO(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}var DO=class extends eO{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=bO(),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),kO(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return AO(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return AO(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 uO(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&&!pO(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&jO(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||uO(this.options.enabled,this.#t)!==uO(t.enabled,this.#t)||lO(this.options.staleTime,this.#t)!==lO(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||uO(this.options.enabled,this.#t)!==uO(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 NO(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(oO)),t}#g(){this.#b();let e=lO(this.options.staleTime,this.#t);if(yO.isServer()||this.#r.isStale||!sO(e))return;let t=cO(this.#r.dataUpdatedAt,e)+1;this.#d=rO.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,!(yO.isServer()||uO(this.options.enabled,this.#t)===!1||!sO(this.#p)||this.#p===0)&&(this.#f=rO.setInterval(()=>{(this.options.refetchIntervalInBackground||tO.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(rO.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(rO.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&&kO(e,t),o=i&&jO(e,n,t,r);(a||o)&&(l={...l,...EO(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=_O(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=_O(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:MO(e,t),refetch:this.refetch,promise:this.#o,isEnabled:uO(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=()=>{let e=this.#o=x.promise=bO();i(e)},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()}}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),!pO(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){CO.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function OO(e,t){return uO(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||uO(t.retryOnMount,e)!==!1)}function kO(e,t){return OO(e,t)||e.state.data!==void 0&&AO(e,t,t.refetchOnMount)}function AO(e,t,n){if(uO(t.enabled,e)!==!1&&lO(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&MO(e,t)}return!1}function jO(e,t,n,r){return(e!==t||uO(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&MO(e,n)}function MO(e,t){return uO(t.enabled,e)!==!1&&e.isStaleByTime(lO(t.staleTime,e))}function NO(e,t){return!pO(e.getCurrentResult(),t)}var PO=v.createContext(void 0),FO=e=>{let t=v.useContext(PO);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},IO=v.createContext(!1),LO=()=>v.useContext(IO);IO.Provider;function RO(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var zO=v.createContext(RO()),BO=()=>v.useContext(zO),VO=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?vO(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},HO=e=>{v.useEffect(()=>{e.clearReset()},[e])},UO=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||vO(n,[e.error,r])),WO=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))}},GO=(e,t)=>e.isLoading&&e.isFetching&&!t,KO=(e,t)=>e?.suspense&&t.isPending,qO=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function JO(e,t,n){let r=LO(),i=BO(),a=FO(n),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,WO(o),VO(o,i,s),HO(i);let l=!a.getQueryCache().get(o.queryHash),[u]=v.useState(()=>new t(a,o)),d=u.getOptimisticResult(o),f=!r&&c;if(v.useSyncExternalStore(v.useCallback(e=>{let t=f?u.subscribe(CO.batchCalls(e)):oO;return u.updateResult(),t},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),v.useEffect(()=>{u.setOptions(o)},[o,u]),KO(o,d))throw qO(o,u,i);if(UO({result:d,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw d.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!yO.isServer()&&GO(d,r)&&(l?qO(o,u,i):s?.promise)?.catch(oO).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function YO(e,t){return JO(e,DO,t)}var XO=`pibo.chat.composerHistory`;function ZO(){try{let e=localStorage.getItem(XO);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`&&e.trim().length>0).slice(-100):[]}catch{return[]}}function QO(e){let t=e.trim();if(!t)return;let n=ZO();if(n.at(-1)!==t)try{localStorage.setItem(XO,JSON.stringify([...n,t].slice(-100)))}catch{}}function $O(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 ek(e,t){return e.length>t?`${e.slice(0,Math.max(0,t-1))}…`:e}function tk({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,D]=(0,v.useState)(0),[O,k]=(0,v.useState)(0),[A,ee]=(0,v.useState)([]),[te,ne]=(0,v.useState)(!1),[j,re]=(0,v.useState)(null),[M,N]=(0,v.useState)(null),ie=(0,v.useMemo)(()=>{for(let e=O-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,O).toLowerCase(),startPos:e,endPos:O}}}return null},[i,O]),ae=i.trim().startsWith(`/`)?i.trim().split(/\s+/)[0]:null,oe=ie?nk(ie.startPos,i.slice(ie.startPos,O)):null,se=ae?rk(ae):null,ce=(0,v.useMemo)(()=>ie?r.filter(e=>e.name.toLowerCase().startsWith(ie.query)):[],[ie,r]),le=(0,v.useMemo)(()=>ae?n.filter(e=>e.slash.startsWith(ae)):[],[ae,n]),de=oe&&A.includes(oe)?[]:ce,fe=se&&A.includes(se)?[]:le,P=(0,v.useCallback)(e=>{e&&ee(t=>t.includes(e)?t:[...t,e])},[]),pe=(0,v.useCallback)(()=>{let e=[ce.length?oe:null,le.length?se:null].filter(e=>!!e);e.length&&ee(t=>{let n=new Set(t);for(let t of e)n.add(t);return n.size===t.length?t:[...n]})},[se,le.length,ce.length,oe]);(0,v.useEffect)(()=>{let e=[oe,se].filter(e=>!!e);ee(t=>t.filter(t=>e.includes(t)))},[se,oe]),(0,v.useEffect)(()=>{!fe.length||w<fe.length||T(0)},[w,fe.length]),(0,v.useEffect)(()=>{!de.length||E<de.length||D(0)},[E,de.length]),(0,v.useEffect)(()=>{let e=requestAnimationFrame(()=>x.current?.scrollIntoView({block:`nearest`}));return()=>cancelAnimationFrame(e)},[w,fe.length]),(0,v.useEffect)(()=>{let e=requestAnimationFrame(()=>S.current?.scrollIntoView({block:`nearest`}));return()=>cancelAnimationFrame(e)},[E,de.length]),(0,v.useEffect)(()=>{C.current=null},[e]),(0,v.useEffect)(()=>{if(!M)return;let e=requestAnimationFrame(()=>b.current?.focus());return()=>{cancelAnimationFrame(e),URL.revokeObjectURL(M.previewUrl)}},[M]),(0,v.useEffect)(()=>{if(a<=0)return;let e=_.current;if(!e)return;let t=e.value.length;e.focus(),e.setSelectionRange(t,t),k(t)},[a]),(0,v.useEffect)(()=>{if(!fe.length&&!de.length)return;let e=e=>{let t=e.target;t instanceof Node&&(g.current?.contains(t)||pe())};return document.addEventListener(`pointerdown`,e,!0),()=>document.removeEventListener(`pointerdown`,e,!0)},[pe,fe.length,de.length]),(0,v.useLayoutEffect)(()=>{uk(_.current)},[i]);let me=e=>{if(!ie||!_.current)return;let t=i.slice(0,ie.startPos),n=i.slice(ie.endPos);c(t+`$`+e+n),P(nk(ie.startPos,`$${e}`));let r=ie.startPos+1+e.length;k(r),requestAnimationFrame(()=>{_.current?.setSelectionRange(r,r),k(r)})},he=e=>{c(e),requestAnimationFrame(()=>{let e=_.current;if(!e)return;let t=e.value.length;e.setSelectionRange(t,t),k(t)})},ge=e=>{let t=C.current;if(!t){if(e===`next`||i!==``)return!1;let t=ZO();if(!t.length)return!1;let n=e===`previous`?t.length-1:0;return C.current={entries:t,index:n,draft:i},he(t[n]),!0}if(e===`previous`){let e=Math.max(0,t.index-1);return C.current={...t,index:e},he(t.entries[e]),!0}let n=t.index+1;return n>=t.entries.length?(C.current=null,he(t.draft),!0):(C.current={...t,index:n},he(t.entries[n]),!0)},_e=()=>{t||te||y.current?.click()},ve=()=>{N(null)},ye=e=>{if(t||te)return;let n=ik(e.clipboardData);if(!n.length)return;e.preventDefault(),pe(),re(null);let r=n[0];N(e=>(e&&URL.revokeObjectURL(e.previewUrl),{file:r,previewUrl:URL.createObjectURL(r)}))},be=async()=>{if(!M||te)return;let e=M.file;N(null),await xe([e])},xe=async e=>{if(e.length){ne(!0),re({message:`Uploading ${e.length} file${e.length===1?``:`s`}...`,error:!1});try{f((await ue(e)).files),re(null)}catch(e){re({message:e instanceof Error?e.message:String(e),error:!0})}finally{ne(!1)}}},Se=async()=>{if(t)return;let e=i.trim();if(e){if(de.length){me(de[Math.min(E,de.length-1)].name);return}if(fe.length&&!n.some(t=>t.slash===e.split(/\s+/)[0])){let e=fe[Math.min(w,fe.length-1)].slash;c(e),P(rk(e));return}if(C.current=null,QO(e),c(``),e.split(/\s+/)[0]===`/upload`){_e();return}e.startsWith(`/`)&&await l(e)||await h(e)}};return(0,I.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,I.jsx)(`input`,{ref:y,type:`file`,multiple:!0,className:`hidden`,onChange:e=>{let t=Array.from(e.target.files??[]);e.target.value=``,xe(t)}}),j?(0,I.jsxs)(`div`,{className:`mb-2 flex items-center gap-2 rounded-sm border px-3 py-2 text-xs ${j.error?`border-red-900 bg-red-950/40 text-red-200`:j.copyText?`border-green-900/60 bg-green-950/30 text-green-300`:`border-slate-700 bg-[#0e1116] text-slate-300`}`,children:[(0,I.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:j.message}),j.copyText?(0,I.jsx)(`button`,{type:`button`,onClick:()=>void $O(j.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,I.jsx)(Ke,{size:13})}):null,(0,I.jsx)(`button`,{type:`button`,onClick:()=>re(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,I.jsx)(Tt,{size:13})})]}):null,M?(0,I.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`&&ve()},children:(0,I.jsxs)(`div`,{className:`w-full max-w-md rounded-sm border border-slate-700 bg-[#151f24] shadow-2xl`,children:[(0,I.jsxs)(`div`,{className:`flex items-start justify-between gap-3 border-b border-slate-800 px-4 py-3`,children:[(0,I.jsxs)(`div`,{children:[(0,I.jsx)(`div`,{className:`text-sm font-semibold text-slate-100`,children:`Pasted image detected`}),(0,I.jsx)(`div`,{className:`mt-1 text-xs text-slate-400`,children:`Upload this clipboard image to the configured Pibo uploads directory?`})]}),(0,I.jsx)(`button`,{type:`button`,onClick:ve,className:`rounded-sm p-1 text-slate-500 hover:bg-slate-800 hover:text-slate-200`,"aria-label":`Cancel pasted image upload`,children:(0,I.jsx)(Tt,{size:14})})]}),(0,I.jsxs)(`div`,{className:`space-y-3 px-4 py-4`,children:[(0,I.jsx)(`img`,{src:M.previewUrl,alt:`Pasted clipboard image preview`,className:`max-h-64 w-full rounded-sm border border-slate-800 bg-[#0e1116] object-contain`}),(0,I.jsxs)(`div`,{className:`flex items-center justify-between gap-3 text-xs text-slate-400`,children:[(0,I.jsx)(`span`,{className:`min-w-0 truncate font-mono`,children:M.file.name}),(0,I.jsx)(`span`,{className:`shrink-0 font-mono`,children:lk(M.file.size)})]})]}),(0,I.jsxs)(`div`,{className:`flex justify-end gap-2 border-t border-slate-800 px-4 py-3`,children:[(0,I.jsx)(`button`,{type:`button`,onClick:ve,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,I.jsx)(`button`,{ref:b,type:`button`,onClick:()=>void be(),disabled:te,className:`h-8 rounded-sm bg-[#11a4d4] px-3 text-xs font-medium text-white disabled:opacity-50`,children:`Upload image`})]})]})}):null,de.length?(0,I.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:de.map((e,t)=>(0,I.jsxs)(`button`,{ref:t===E?S:null,type:`button`,onClick:()=>me(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,I.jsxs)(`span`,{className:`font-mono text-emerald-400`,children:[`$`,e.name]}),(0,I.jsx)(`span`,{className:`text-xs text-slate-400`,children:e.description??e.path??``})]},e.name))}):null,s.length?(0,I.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,I.jsxs)(`div`,{className:`mb-1.5 flex items-center justify-between gap-2`,children:[(0,I.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Attached uploads`}),(0,I.jsx)(`button`,{type:`button`,onClick:m,className:`text-[11px] text-slate-500 hover:text-[#11a4d4]`,children:`Clear`})]}),(0,I.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:s.map(e=>(0,I.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,I.jsx)(`span`,{className:`min-w-0 truncate`,children:ek(e.name||e.path,100)}),(0,I.jsx)(`button`,{type:`button`,onClick:()=>void $O(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,I.jsx)(Ke,{size:11})}),(0,I.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,I.jsx)(Tt,{size:11})})]},e.id))})]}):null,o.length?(0,I.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,I.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,I.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Attached web annotations`}),(0,I.jsx)(`button`,{type:`button`,onClick:d,className:`text-[11px] text-slate-500 hover:text-[#11a4d4]`,children:`Clear`})]}),(0,I.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:o.map(e=>(0,I.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,I.jsx)(`span`,{className:`min-w-0 truncate`,children:ek(e.primaryTarget||e.label||e.note||e.id,100)}),(0,I.jsx)(Tt,{size:11,className:`shrink-0 text-[#11a4d4]`})]},e.id))})]}):null,fe.length?(0,I.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:fe.map((e,t)=>(0,I.jsxs)(`button`,{ref:t===w?x:null,type:`button`,onClick:()=>{c(e.slash),P(rk(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,I.jsx)(`span`,{className:`font-mono text-[#11a4d4]`,children:e.slash}),(0,I.jsx)(`span`,{className:`text-xs text-slate-400`,children:e.description})]},e.slash))}):null,(0,I.jsxs)(`div`,{className:`grid grid-cols-[1fr_auto] items-end gap-2`,children:[(0,I.jsx)(`textarea`,{id:`message-composer-input`,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),k(e.target.selectionStart)},onKeyDown:e=>{if(e.key===`Escape`&&(de.length||fe.length)){e.preventDefault(),e.stopPropagation(),pe();return}if(de.length&&(e.key===`ArrowDown`||e.key===`ArrowUp`)){e.preventDefault(),D(t=>e.key===`ArrowDown`?(t+1)%de.length:(t-1+de.length)%de.length);return}if(fe.length&&(e.key===`ArrowDown`||e.key===`ArrowUp`)){e.preventDefault(),T(t=>e.key===`ArrowDown`?(t+1)%fe.length:(t-1+fe.length)%fe.length);return}if((e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&ge(e.key===`ArrowUp`?`previous`:`next`)){e.preventDefault();return}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),Se())},onPaste:ye,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,I.jsx)(`button`,{type:`button`,disabled:t||te,onClick:()=>void Se(),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,I.jsx)(vt,{size:16})})]})]})}function nk(e,t){return`skill:${e}:${t}`}function rk(e){return`command:${e}`}function ik(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(ak)}function ak(e){return e.name&&e.name!==`image.png`?e:new File([e],ok(e.type),{type:e.type||`image/png`,lastModified:Date.now()})}function ok(e){let t=sk(e),n=new Date;return`screenshot-${[n.getFullYear(),ck(n.getMonth()+1),ck(n.getDate()),`-`,ck(n.getHours()),ck(n.getMinutes()),ck(n.getSeconds())].join(``)}${t}`}function sk(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 ck(e){return String(e).padStart(2,`0`)}function lk(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KiB`:`${(e/1048576).toFixed(1)} MiB`}function uk(e){if(!e)return;if(e.value&&!e.value.includes(`
|
|
41
|
-
`)&&e.value.length<80){e.style.height=``,e.style.overflowY=`hidden`;return}let t=window.getComputedStyle(e),n=dk(t.lineHeight,20),r=dk(t.borderTopWidth)+dk(t.borderBottomWidth),i=n*5+dk(t.paddingTop)+dk(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 dk(e,t=0){let n=Number.parseFloat(e);return Number.isFinite(n)?n:t}var fk=`pibo.chat.webAnnotations.cdpUrl`,pk=`pibo.chat.webAnnotations.selected`,mk=`${pk}.`,hk=`pibo.chat.webAnnotations.overlay.`,gk=`pibo.chat.webAnnotations.panelCollapsed`,_k=`pibo.chat.shortcuts.webAnnotationsToggle`,vk=`Alt+Shift+A`;function yk(){try{return localStorage.getItem(fk)??``}catch{return``}}function bk(e){try{e.trim()?localStorage.setItem(fk,e.trim()):localStorage.removeItem(fk)}catch{}}function xk(){try{return localStorage.getItem(_k)||`Alt+Shift+A`}catch{return vk}}function Sk(e){try{return wk(localStorage.getItem(Ck(e)))}catch{return null}}function Ck(e){return hk+e}function wk(e){if(!e)return null;try{return Tk(JSON.parse(e))}catch{return null}}function Tk(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 Ek(e){try{let t=Ok(localStorage.getItem(pk));if(t.length||!e)return t;let n=mk+e,r=Ok(localStorage.getItem(n));return r.length&&(localStorage.setItem(pk,JSON.stringify(r)),localStorage.removeItem(n)),r}catch{return[]}}function Dk(e,t){try{let n=[...new Set(t.filter(e=>e.trim()))].slice(0,5);n.length?localStorage.setItem(pk,JSON.stringify(n)):localStorage.removeItem(pk),e&&localStorage.removeItem(mk+e)}catch{}}function Ok(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`&&!!e.trim()).slice(0,5):[]}catch{return[]}}function kk(){try{return localStorage.getItem(gk)===`true`}catch{return!1}}function Ak(e){try{localStorage.setItem(gk,String(e))}catch{}}var jk=`web-annotations-dialog`,Mk=`web-annotations-session-panel-details`;function Nk({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,I.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,I.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,I.jsx)(`div`,{className:`min-w-0`,children:(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,I.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Web annotations`}),(0,I.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,I.jsxs)(`span`,{className:`rounded-sm border border-[#11a4d4]/50 px-1.5 py-0.5 text-[10px] text-[#11a4d4]`,children:[n.length,` attached`]}):null]})}),(0,I.jsxs)(`div`,{className:`ml-auto flex shrink-0 items-center gap-1`,children:[(0,I.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,I.jsx)(mt,{size:12,className:r?`animate-spin`:void 0})}),(0,I.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,I.jsx)(xt,{size:12})}),(0,I.jsx)(`button`,{type:`button`,onClick:l,title:a?`Expand annotations panel`:`Collapse annotations panel`,"aria-label":`Web annotations details`,"aria-expanded":!a,"aria-controls":Mk,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,I.jsx)(Re,{size:12}):(0,I.jsx)(Ie,{size:12})}),(0,I.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,I.jsx)(Tt,{size:12})})]})]}),(0,I.jsxs)(`div`,{id:Mk,hidden:a,children:[(0,I.jsx)(`div`,{className:`text-[11px] text-slate-500`,children:`Global annotation list. Selected attachments follow you when switching sessions.`}),i?(0,I.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:Wk(i,220)}):r&&!t.length?(0,I.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,I.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,t)=>{let r=n.includes(e.id),i=Wk(e.primaryTarget||e.label||e.selector||e.targetKind||`target`,64),a=`${t+1}: ${i}`;return(0,I.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":r?`true`:`false`,className:`min-w-0 rounded-sm border px-3 py-2 text-xs ${r?`border-[#11a4d4] bg-[#11a4d4]/10`:`border-slate-800 bg-[#0e1116]`}`,children:[(0,I.jsxs)(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[(0,I.jsxs)(`span`,{className:`min-w-0 truncate font-mono text-[11px] text-slate-500`,children:[e.status,` · `,e.targetKind]}),(0,I.jsxs)(`button`,{type:`button`,onClick:()=>s(e.id),"aria-pressed":r,"aria-label":`Include web annotation ${a}`,title:`${r?`Detach`:`Attach`} web annotation ${a}`,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 ${r?`border-[#11a4d4] text-[#11a4d4]`:`border-slate-700 text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:[r?(0,I.jsx)(Tt,{size:11}):(0,I.jsx)(pt,{size:11}),` `,r?`Detach`:`Attach`]})]}),(0,I.jsx)(`div`,{className:`truncate text-slate-200`,title:e.primaryTarget||e.label||e.selector||e.id,children:Wk(e.primaryTarget||e.label||e.selector||e.id,120)}),e.piboContext?(0,I.jsx)(`div`,{className:`truncate font-mono text-[11px] text-[#11a4d4]`,title:e.piboContext,children:Wk(e.piboContext,140)}):null,(0,I.jsx)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:e.url,children:Vk(e.url)}),(0,I.jsxs)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:Uk(e),children:[`Source `,Hk(e)]}),(0,I.jsx)(`div`,{className:`mt-1 line-clamp-2 text-slate-400`,title:e.note,children:Wk(e.note,180)}),(0,I.jsx)(`div`,{className:`mt-1 text-[11px] text-slate-600`,children:Gk(e.createdAt)})]},e.id)})}):(0,I.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 Pk({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)(()=>yk()),[p,m]=(0,v.useState)([]),[h,g]=(0,v.useState)(`idle`),[_,y]=(0,v.useState)(!1),[b,x]=(0,v.useState)(null),S=(0,v.useRef)(null),C=(0,v.useRef)(null),w=()=>{c(!1),S.current?.focus()};(0,v.useEffect)(()=>{n&&c(!1)},[n]),(0,v.useEffect)(()=>{if(!s||n)return;C.current?.focus();let e=e=>{e.key===`Escape`&&(e.preventDefault(),w())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[s,n]),(0,v.useEffect)(()=>{bk(d)},[d]);let T=async()=>{if(e){g(`loading`),x(null);try{let e=await $x(d);m(e.targets.filter(e=>e.type===`page`||e.attachable)),g(`loaded`)}catch(e){let t=zk(e,`CDP unavailable`);m([]),g(`error`),x({kind:`error`,message:t}),o(t)}}},E=async n=>{if(!e)throw Error(`No active session context`);return tS(n.binding.id,Ik({piboSessionId:e,piboRoomId:t,cdpUrl:d,annotationShortcut:xk()}))},D=async()=>{if(!(!e||_)){i(),y(!0),x({kind:`info`,message:`Injecting annotation overlay into this Pibo page…`});try{let n=await eS({piboSessionId:e,piboRoomId:t,url:window.location.href,title:document.title,sameOrigin:!0,annotationShortcut:xk()});if(!n.overlay)throw Error(`Overlay config missing from same-origin binding response`);await Rk(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=zk(e,`Current-page annotation failed`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}}},O=async()=>{if(!e||_)return;i();let n=l.trim();if(!n){x({kind:`error`,message:`URL is required`});return}if(Lk(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 eS(Ik({piboSessionId:e,piboRoomId:t,url:n,cdpUrl:d})),i=await E(r);x({kind:`success`,message:`Annotation overlay injected for ${Bk(i.target??r.target,i.binding.url)}`}),u(``),o(null)}catch(e){let t=zk(e,`Annotation failed`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}},k=async n=>{if(!(!e||_)){i(),y(!0),x({kind:`info`,message:`Binding selected target and injecting overlay…`});try{let r=await eS(Ik({piboSessionId:e,piboRoomId:t,targetId:n.id,cdpUrl:d})),i=await E(r);x({kind:`success`,message:`Annotation overlay injected for ${Bk(i.target??n,i.binding.url)}`}),o(null)}catch(e){let t=zk(e,n.attachable?`Target annotation failed`:`Target not attachable`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}}};return(0,I.jsxs)(`div`,{className:`relative`,"data-pibo-debug":`web-annotations-entry`,"data-pibo-session-id":e??void 0,children:[(0,I.jsx)(Fk,{buttonRef:S,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`,ariaHaspopup:`dialog`,ariaExpanded:s,ariaControls:jk,disabled:n,active:s||r,children:(0,I.jsx)(Oe,{size:14})}),s&&!n?(0,I.jsxs)(`div`,{id:jk,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,I.jsxs)(`div`,{className:`mb-2 flex items-start justify-between gap-3`,children:[(0,I.jsxs)(`div`,{children:[(0,I.jsx)(`div`,{className:`text-xs font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Web Annotations`}),(0,I.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,I.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,I.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,I.jsx)(gt,{size:14})}),(0,I.jsx)(`button`,{type:`button`,onClick:w,className:`rounded-sm p-1 text-slate-500 hover:bg-slate-800 hover:text-slate-200`,"aria-label":`Close Web Annotations panel`,children:(0,I.jsx)(Tt,{size:14})})]})]}),(0,I.jsx)(`button`,{ref:C,type:`button`,onClick:()=>void D(),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,I.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,I.jsxs)(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-[1fr_auto]`,children:[(0,I.jsx)(`input`,{id:`web-annotation-url`,value:l,onChange:e=>u(e.target.value),onKeyDown:e=>{e.key===`Enter`&&O()},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,I.jsx)(`button`,{type:`button`,onClick:()=>void O(),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,I.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,I.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,I.jsxs)(`div`,{className:`mt-3 flex items-center justify-between gap-2`,children:[(0,I.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-slate-500`,children:`Existing targets`}),(0,I.jsxs)(`button`,{type:`button`,onClick:()=>void T(),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,I.jsx)(mt,{size:12,className:h===`loading`?`animate-spin`:void 0}),` Refresh`]})]}),(0,I.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,I.jsx)(`div`,{className:`px-3 py-3 text-xs text-slate-500`,children:`Refresh to list reachable browser targets.`}):null,h===`loading`?(0,I.jsx)(`div`,{className:`px-3 py-3 text-xs text-slate-400`,children:`Loading targets…`}):null,h===`loaded`&&!p.length?(0,I.jsx)(`div`,{className:`px-3 py-3 text-xs text-slate-500`,children:`No attachable browser targets found.`}):null,p.map(e=>(0,I.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,I.jsxs)(`div`,{className:`min-w-0`,children:[(0,I.jsx)(`div`,{className:`truncate text-xs text-slate-200`,title:e.title||e.url,children:Wk(e.title||`Untitled target`,120)}),(0,I.jsx)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:e.url,children:Wk(e.url||e.id,160)})]}),(0,I.jsx)(`button`,{type:`button`,onClick:()=>void k(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,I.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 Fk({buttonRef:e,title:t,ariaLabel:n,ariaHaspopup:r,ariaExpanded:i,ariaControls:a,disabled:o,active:s,onClick:c,children:l}){return(0,I.jsx)(`button`,{ref:e,type:`button`,onClick:c,disabled:o,title:t,"aria-label":n,"aria-haspopup":r,"aria-expanded":i,"aria-controls":a,className:`h-8 w-8 inline-flex items-center justify-center border rounded-sm transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${s?`border-[#11a4d4] bg-[#11a4d4]/10 text-[#11a4d4]`:`border-slate-700 text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:l})}function Ik(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e&&e.trim()))}function Lk(e){try{let t=new URL(e);return t.port===`56663`||t.pathname.startsWith(`/json/`)}catch{return!1}}function Rk(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 zk(e,t){let n=Kk(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 Bk(e,t){let n=e?.url||t||e?.title||`target`;return Vk(e?.title||n)}function Vk(e){try{let t=new URL(e);return`${t.host}${t.pathname===`/`?``:t.pathname}`}catch{return Wk(e,80)}}function Hk(e){return e.piboRoomId?`${Wk(e.piboSessionId,24)} · room ${Wk(e.piboRoomId,18)}`:Wk(e.piboSessionId,44)}function Uk(e){return e.piboRoomId?`Session ${e.piboSessionId} in room ${e.piboRoomId}`:`Session ${e.piboSessionId}`}function Wk(e,t){return e.length>t?`${e.slice(0,Math.max(0,t-1))}…`:e}function Gk(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{dateStyle:`short`,timeStyle:`short`})}function Kk(e){return e instanceof Error?e.message:String(e)}function qk(e){return!!e.workflowRunId||e.state===`workflow`||e.workflowId!==`simple-chat`}function Jk(e,t){return{workflowId:e.workflowId,state:Xk(e,t),...e.workflowRunId?{workflowRunId:e.workflowRunId}:{}}}function Yk({summary:e}){return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(`span`,{className:`text-slate-600`,children:`·`}),(0,I.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,I.jsxs)(`span`,{className:Zk(e.state),children:[`state `,e.state]}),e.workflowRunId?(0,I.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 `,Qk(e.workflowRunId)]}):null]})}function Xk(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 Zk(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 Qk(e){return e.length>18?`${e.slice(0,10)}…${e.slice(-6)}`:e}function $k({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,terminalFullscreenAvailable:m,onEnterTerminalFullscreen:h,onOpenSessionWindow:g,showRawEvents:_,showThinking:y,expandThinking:b,onShowWebAnnotationsPanel:x,onHideWebAnnotationsPanel:S,onSelectSessionView:C,onToggleRawEvents:w,onToggleThinking:T,onToggleExpandThinking:E,onError:D}){let[O,k]=(0,v.useState)(null),A=(0,v.useRef)(void 0),ee=O===n,te=p??c,ne=(0,v.useMemo)(()=>d?new Set(d):null,[d]);(0,v.useEffect)(()=>()=>{A.current&&window.clearTimeout(A.current)},[]);let j=()=>{n&&($O(n).catch(()=>void 0),k(n),A.current&&window.clearTimeout(A.current),A.current=window.setTimeout(()=>k(null),900))};return(0,I.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,I.jsxs)(`div`,{className:`min-w-0`,children:[(0,I.jsx)(`h1`,{className:`text-base font-semibold truncate`,children:e}),(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 font-mono text-[11px] text-slate-500`,children:[(0,I.jsx)(`span`,{className:`truncate`,children:t}),n?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(`span`,{className:`text-slate-600`,children:`·`}),(0,I.jsx)(`button`,{type:`button`,onMouseDown:e=>e.preventDefault(),onClick:()=>void j(),title:ee?`Copied Pibo session ID`:`Copy Pibo session ID`,"aria-label":ee?`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] ${ee?`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,I.jsx)(Yk,{summary:s}):null]})]}),(0,I.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,I.jsx)(Pk,{piboSessionId:r,piboRoomId:i,disabled:a,panelVisible:o,onShowPanel:x,onHidePanel:S,onError:D}),g?(0,I.jsx)(`button`,{type:`button`,onClick:g,title:`Open selected session in new window`,"aria-label":`Open selected session in new window`,"data-pibo-debug":`open-session-window`,className:`h-8 w-8 inline-flex items-center justify-center border border-slate-700 rounded-sm text-slate-400 transition-colors hover:border-[#11a4d4] hover:text-[#11a4d4]`,children:(0,I.jsx)(pt,{size:15})}):null,(0,I.jsxs)(`div`,{role:`group`,"aria-label":`Session views`,className:`flex items-center rounded-sm border border-slate-700 bg-[#0e1116] p-0.5`,children:[l.map(e=>{let t=!!(ne&&!ne.has(e.id));return(0,I.jsx)(`button`,{type:`button`,onClick:()=>{t||C(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`,"aria-pressed":te===e.id,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 ${te===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=>{let t=e.active??te===e.id;return(0,I.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`,"aria-pressed":t,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 ${t?`bg-[#11a4d4]/10 text-[#11a4d4]`:`text-slate-400 hover:text-[#11a4d4] disabled:hover:text-slate-600`}`,children:e.label},e.id)})]}),m&&h?(0,I.jsx)(`button`,{type:`button`,onClick:h,title:`Enter Terminal fullscreen`,"aria-label":`Enter Terminal fullscreen`,"data-pibo-debug":`enter-terminal-fullscreen`,className:`h-8 w-8 inline-flex items-center justify-center border border-slate-700 rounded-sm text-slate-400 transition-colors hover:border-[#11a4d4] hover:text-[#11a4d4]`,children:(0,I.jsx)(ut,{size:14})}):null,(0,I.jsx)(eA,{onClick:w,title:_?`Hide Raw Events`:`Show Raw Events`,ariaLabel:`Raw Events`,active:_,children:(0,I.jsx)(je,{size:14})}),(0,I.jsx)(eA,{onClick:T,title:y?`Hide Thinking`:`Show Thinking`,ariaLabel:`Thinking`,active:y,children:y?(0,I.jsx)(Ae,{size:14}):(0,I.jsx)(Xe,{size:14})}),y?(0,I.jsx)(eA,{onClick:E,title:b?`Collapse Thinking`:`Expand Thinking`,ariaLabel:`Thinking expansion`,active:b,children:b?(0,I.jsx)(Ie,{size:14}):(0,I.jsx)(Re,{size:14})}):null]})]})}function eA({title:e,ariaLabel:t,active:n,onClick:r,children:i}){return(0,I.jsx)(`button`,{type:`button`,onClick:r,title:e,"aria-label":t,"aria-pressed":n,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 tA(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&nA(e,n)){e.count+=1,e.createdAt=n.createdAt,e.payload={...aA(e.payload)?e.payload:{},text:`${rA(e.payload)}${rA(n.payload)}`};continue}t.push({...n,count:1})}return t}function nA(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=aA(e.payload)?e.payload:{},r=aA(t.payload)?t.payload:{};return iA(n)===iA(r)}function rA(e){return aA(e)?typeof e.text==`string`?e.text:typeof e.delta==`string`?e.delta:``:``}function iA(e){return e.eventId??e.messageId}function aA(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function oA({traceView:e,eventLimit:t,isFetching:n,visible:r,onLoadOlder:i}){let a=(0,v.useMemo)(()=>r?tA(e?.rawEvents??[]):[],[e?.rawEvents,r]);return r?(0,I.jsxs)(`aside`,{className:`min-h-0 overflow-auto bg-[#0e1116] border-l border-slate-800 max-[980px]:hidden`,children:[(0,I.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,I.jsxs)(`div`,{className:`p-3 flex flex-col gap-2`,children:[e&&a.length>=t?(0,I.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,I.jsxs)(`div`,{className:`border-l-2 border-[#11a4d4] bg-[#151f24] p-2`,children:[(0,I.jsxs)(`div`,{className:`flex items-center justify-between gap-2 text-[#11a4d4] font-mono text-[11px] mb-1`,children:[(0,I.jsx)(`span`,{children:e.type}),e.count>1?(0,I.jsxs)(`span`,{className:`text-slate-500`,children:[`x`,e.count]}):null]}),(0,I.jsx)(bl,{value:e.payload,showControls:!1})]},e.id))]})]}):null}function sA({title:e,onOpenSessionWindow:t,onExit:n}){return(0,I.jsxs)(`div`,{"data-pibo-debug":`terminal-fullscreen-top-bar`,className:`h-7 min-h-7 flex items-center border-b border-slate-600 bg-[#151f24]`,children:[(0,I.jsx)(`div`,{className:`min-w-0 flex-1 truncate text-base font-semibold leading-none`,children:e}),t?(0,I.jsx)(`button`,{type:`button`,onClick:t,title:`Open selected session in new window`,"aria-label":`Open selected session in new window`,"data-pibo-debug":`open-session-window`,className:`h-full w-7 shrink-0 inline-flex items-center justify-center text-slate-400 hover:bg-[#11a4d4]/10 hover:text-[#11a4d4]`,children:(0,I.jsx)(pt,{size:14})}):null,(0,I.jsx)(`button`,{type:`button`,onClick:n,title:`Show normal top bar`,"aria-label":`Exit Terminal fullscreen`,className:`h-full w-7 shrink-0 inline-flex items-center justify-center text-slate-400 hover:bg-[#11a4d4]/10 hover:text-[#11a4d4]`,children:(0,I.jsx)(ft,{size:14})})]})}function cA({enabled:e,onFilesDropped:t,children:n,className:r,...i}){let a=(0,v.useRef)(0),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(0),u=c>0;(0,v.useEffect)(()=>{e||(a.current=0,s(!1))},[e]);let d=()=>{a.current=0,s(!1)},f=t=>uA(t.dataTransfer)?(t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=e&&!u?`copy`:`none`,!0):!1,p=t=>{!f(t)||!e||u||(a.current+=1,s(!0))},m=e=>{f(e)},h=e=>{!f(e)||a.current===0||(a.current=Math.max(0,a.current-1),a.current===0&&s(!1))},g=async n=>{if(!f(n)||(d(),!e||u))return;let r=dA(n.dataTransfer);if(r.length){l(r.length);try{await t(r)}finally{l(0)}}},_=u?`uploading`:o?`drag-active`:`idle`;return(0,I.jsxs)(`main`,{...i,"data-pibo-file-drop-state":_,className:`relative ${r??``}`,onDragEnter:p,onDragOver:m,onDragLeave:h,onDragEnd:d,onDrop:g,children:[n,o||u?(0,I.jsx)(lA,{uploadingFileCount:c}):null]})}function lA({uploadingFileCount:e}){let t=e>0;return(0,I.jsx)(`div`,{"data-pibo-debug":`terminal-file-drop-overlay`,"data-pibo-state":t?`uploading`:`drag-active`,role:`status`,"aria-live":`polite`,className:`pointer-events-none absolute inset-0 z-40 grid place-items-center bg-[#071015]/90 p-6 backdrop-blur-[2px]`,children:(0,I.jsxs)(`div`,{className:`flex max-w-sm flex-col items-center rounded-sm border border-dashed border-[#11a4d4] bg-[#0e1116]/95 px-8 py-7 text-center shadow-2xl shadow-black/50`,children:[t?(0,I.jsx)(ct,{size:36,className:`mb-3 animate-spin text-[#11a4d4]`,"aria-hidden":`true`}):(0,I.jsx)(Ct,{size:36,className:`mb-3 text-[#11a4d4]`,"aria-hidden":`true`}),(0,I.jsx)(`span`,{className:`text-sm font-semibold text-slate-100`,children:t?`Uploading ${e} file${e===1?``:`s`}…`:`Drop files to upload`}),(0,I.jsx)(`span`,{className:`mt-1 text-xs leading-5 text-slate-400`,children:t?`Saving to the Pibo uploads directory`:`Images and other files will be attached to your next message.`})]})})}function uA(e){return Array.from(e.types).includes(`Files`)||Array.from(e.items).some(e=>e.kind===`file`)}function dA(e){return Array.from(e.files)}function fA({selectedPiboSessionId:e,selectedRoomId:t,fallbackRoomId:n,sessionViewId:r,loadingTrace:i,roomNavigationPending:a=!1,sessionNavigationPending:o=!1,traceError:s,showRawEvents:c,currentTraceView:l,rawEventLimit:u,tracePageFetching:d,onLoadMoreRawEvents:f,terminalFullscreen:p,terminalFileDropEnabled:m,onTerminalFilesDropped:h,onOpenSessionWindow:g,onExitTerminalFullscreen:_,headerProps:v,projectSessionCreatePanel:y,workflowStartPanel:b,projectModulePanel:x,currentSessionView:S,sessionViewProps:C,webAnnotationsPanelRendered:w,webAnnotationsPanelProps:T,runtimeRequestPanel:E,composerProps:D}){let O=a||o&&!l||i;return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)(cA,{enabled:m,onFilesDropped:h,"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":a?`room-loading`:o?`session-loading`:i?`loading`:s?`error`:e?`ready`:`empty`,"data-pibo-terminal-fullscreen":p?`true`:`false`,className:`min-h-0 flex flex-col`,children:[p?(0,I.jsx)(sA,{title:v.title,onOpenSessionWindow:g,onExit:_}):(0,I.jsx)($k,{...v}),!p&&y?(0,I.jsx)(`div`,{className:`border-b border-slate-800 bg-[#101d22] px-4 py-3`,children:y}):null,!p&&b?(0,I.jsx)(`div`,{className:`border-b border-slate-800 bg-[#101d22] px-4 py-3`,children:b}):null,!p&&x?x:O?(0,I.jsx)(pA,{label:a?`Loading room`:`Loading session`}):s&&!l?(0,I.jsx)(`div`,{className:`min-h-0 flex-1 p-4 text-sm text-red-200`,children:s}):S.render({...C,terminalFullscreen:p}),!p&&w?(0,I.jsx)(Nk,{...T}):null,E,(0,I.jsx)(tk,{...D})]}),(0,I.jsx)(oA,{traceView:l,eventLimit:u,isFetching:d,visible:c&&!p,onLoadOlder:f})]})}function pA({label:e}){return(0,I.jsx)(`section`,{"data-pibo-debug":`room-navigation-loading`,className:`relative min-w-0 flex-1 overflow-hidden bg-[#0b0b0b] text-[#d4d4d4]`,"aria-live":`polite`,"aria-label":e,children:(0,I.jsx)(`div`,{className:`min-h-0 h-full overflow-hidden font-mono text-[12px] leading-[1.45]`,children:(0,I.jsxs)(`div`,{className:`px-4`,children:[(0,I.jsx)(`div`,{className:`group border-b border-[#141414] py-2`,children:(0,I.jsxs)(`div`,{className:`grid grid-cols-[1.9rem_minmax(0,1fr)] gap-2 leading-[1.45]`,children:[(0,I.jsx)(`span`,{className:`flex items-center text-[#38bdf8]`,children:(0,I.jsx)(`span`,{className:`h-1.5 w-1.5 rounded-full bg-[#38bdf8] animate-pulse`})}),(0,I.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,I.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:e}),(0,I.jsx)(`span`,{className:`h-2 w-24 rounded-sm bg-[#262626] animate-pulse`})]})]})}),[{kind:`tool`,lines:5},{kind:`markdown`,lines:4},{kind:`command`,lines:4},{kind:`tool`,lines:3},{kind:`markdown`,lines:5}].map((e,t)=>(0,I.jsx)(mA,{kind:e.kind,lineCount:e.lines},t))]})})})}function mA({kind:e,lineCount:t}){let n=e===`command`,r=e===`markdown`;return(0,I.jsx)(`div`,{className:`group border-b border-[#141414] py-2 animate-pulse ${n?`bg-[#f59e0b]/5`:``}`,"aria-hidden":`true`,children:Array.from({length:t}).map((e,i)=>(0,I.jsxs)(`div`,{className:`grid grid-cols-[1.9rem_minmax(0,1fr)] gap-2 leading-[1.45]`,children:[(0,I.jsx)(`span`,{className:`flex items-center text-[#737373]`,children:i===0&&!r?(0,I.jsx)(`span`,{className:`h-1.5 w-1.5 rounded-full ${n?`bg-[#f59e0b]`:`bg-[#22c55e]`}`}):i>0&&!r?(0,I.jsx)(`span`,{className:`text-[10px]`,children:`L`}):null}),(0,I.jsx)(`span`,{className:`min-w-0 py-[3px]`,children:i===0?(0,I.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,I.jsx)(`span`,{className:`h-[13px] rounded-sm ${r?`w-56 bg-[#d4d4d4]/45`:n?`w-28 bg-[#f59e0b]/65`:`w-24 bg-[#22c55e]/65`}`}),r?null:(0,I.jsx)(`span`,{className:`h-[13px] w-64 rounded-sm bg-[#262626]`})]}):(0,I.jsx)(`span`,{className:`block h-[10px] rounded-sm bg-[#262626] ${i===t-1?`w-[42%]`:i%2==0?`w-[72%]`:`w-[58%]`}`})})]},i))})}var hA=[`a[href]`,`button:not([disabled])`,`input:not([disabled])`,`select:not([disabled])`,`textarea:not([disabled])`,`[tabindex]:not([tabindex="-1"])`].join(`,`);function gA({title:e,description:t,onClose:n,initialFocusRef:r,children:i,closeLabel:a=`Close dialog`,closeDisabled:o=!1}){let s=(0,v.useId)(),c=(0,v.useId)(),l=(0,v.useRef)(null);return(0,v.useEffect)(()=>{let e=document.activeElement instanceof HTMLElement?document.activeElement:null,t=window.requestAnimationFrame(()=>{(r?.current??l.current?.querySelector(hA)??l.current)?.focus()});return()=>{window.cancelAnimationFrame(t),e?.isConnected&&e.focus()}},[r]),(0,I.jsx)(`div`,{className:`fixed inset-0 z-50 grid place-items-center bg-black/70 p-4`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":s,"aria-describedby":c,onClick:e=>{!o&&e.target===e.currentTarget&&n()},onKeyDown:e=>{if(e.key===`Escape`){e.preventDefault(),o||n();return}if(e.key!==`Tab`)return;let t=Array.from(l.current?.querySelectorAll(hA)??[]);if(t.length===0){e.preventDefault(),l.current?.focus();return}let r=t[0],i=t[t.length-1],a=document.activeElement;t.includes(a)?e.shiftKey&&a===r?(e.preventDefault(),i.focus()):!e.shiftKey&&a===i&&(e.preventDefault(),r.focus()):(e.preventDefault(),(e.shiftKey?i:r).focus())},children:(0,I.jsxs)(`div`,{ref:l,tabIndex:-1,className:`max-h-[calc(100vh-2rem)] w-full max-w-lg overflow-y-auto rounded-sm border border-slate-700 bg-[#1a262b] text-slate-200 shadow-2xl outline-none`,children:[(0,I.jsxs)(`div`,{className:`flex items-start justify-between gap-3 border-b border-slate-800 px-4 py-3`,children:[(0,I.jsxs)(`div`,{children:[(0,I.jsx)(`h2`,{id:s,className:`text-sm font-bold uppercase tracking-wider text-slate-100`,children:e}),(0,I.jsx)(`p`,{id:c,className:`mt-1 text-xs text-slate-400`,children:t})]}),(0,I.jsx)(`button`,{type:`button`,onClick:n,disabled:o,"aria-label":a,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-sm border border-slate-700 text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:cursor-not-allowed disabled:opacity-50`,children:(0,I.jsx)(Tt,{size:14})})]}),i]})})}function _A(e){let t=new Map;if(SA(e.nodes,t),!t.size)return e;let{nodes:n,changed:r}=CA(e.nodes,t);return r?{...e,nodes:n}:e}function vA(e){return e.some(xA)}function yA(e){let t=new Map;return EA(e,e=>{if(e.type!==`user.message`||!e.entryId)return;let n=DA(e),r=t.get(n);r?r.push(e.entryId):t.set(n,[e.entryId])}),t}function bA(e,t){if(!t.size)return;let n=new Map;EA(e,e=>{if(e.type!==`user.message`||!e.entryId)return;let t=DA(e),r=n.get(t)??new Set;r.add(e.entryId),n.set(t,r)});let r=new Map;EA(e,e=>{if(e.type!==`user.message`||e.entryId)return;let i=DA(e),a=t.get(i);if(!a?.length)return;let o=n.get(i)??new Set,s=r.get(i)??0;for(;s<a.length&&o.has(a[s]);)s+=1;let c=a[s];c&&(e.entryId=c,o.add(c),n.set(i,o),r.set(i,s+1))})}function xA(e){let t=e.payload;return!!(t&&typeof t==`object`&&!Array.isArray(t)&&`type`in t&&(t.type===`message_queued`||t.type===`message_steered`)&&`source`in t&&t.source===`user`&&`text`in t&&typeof t.text==`string`)}function SA(e,t){for(let n of e){if(n.type===`user.message`&&!TA(n)&&!wA(n)){let e=DA(n);e&&t.set(e,(t.get(e)??0)+1)}SA(n.children,t)}}function CA(e,t){let n=!1,r=[];for(let i of e){if(TA(i)){let e=DA(i),r=e?t.get(e)??0:0;if(r>0){t.set(e,r-1),n=!0;continue}}let e=CA(i.children,t);n||=e.changed,r.push(e.changed?{...i,children:e.nodes}:i)}return{nodes:n?r:e,changed:n}}function wA(e){return[e.id,e.stableKey].some(e=>e?.startsWith(`event:message_queued:`)||e?.startsWith(`event:message_steered:`))}function TA(e){return e.type===`user.message`?e.source===`event-log`&&(e.id.startsWith(`event:message_queued:`)||e.id.startsWith(`event:message_steered:`))?!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 EA(e,t){for(let n of e)t(n),EA(n.children,t)}function DA(e){return typeof e.output==`string`?e.output:typeof e.summary==`string`?e.summary:``}function OA(e,t,n){return t&&e.set(t.piboSessionId,t),n?e.get(n)??null:null}function kA(e,t,n){t&&t.piboSessionId!==n.piboSessionId&&e.set(t.piboSessionId,t);let r=AA(t?.piboSessionId===n.piboSessionId?t:e.get(n.piboSessionId)??null,n);return r?e.set(n.piboSessionId,r):e.delete(n.piboSessionId),r}function AA(e,t){if(!e||e.piboSessionId!==t.piboSessionId)return e;let n=NA(t),r=jA(t.nodes),i=e.events.filter(e=>{let i=RA(e);if(i&&n.has(i))return!1;if(xA(e)){let t=r.get(e.payload.text)??0;if(t>0)return t===1?r.delete(e.payload.text):r.set(e.payload.text,t-1),!1}return!IA(t,e)});return i.length?{...e,events:i}:null}function jA(e){let t=new Map;for(let n of e){if(n.type===`user.message`&&FA(n)&&!MA(n)){let e=VA(n);e&&t.set(e,(t.get(e)??0)+1)}for(let[e,r]of jA(n.children))t.set(e,(t.get(e)??0)+r)}return t}function MA(e){return[e.id,e.stableKey].some(e=>e?.startsWith(`event:message_queued:`)||e?.startsWith(`event:message_steered:`))}function NA(e){let t=new Set;for(let n of e.rawEvents){let e=RA(n);e&&t.add(e)}return PA(e.nodes,t),t}function PA(e,t){for(let n of e){if(n.type===`user.message`)for(let e of[`message_queued`,`message_steered`]){let r=`event:${e}:`,i=n.id.startsWith(r)?n.id.slice(r.length):void 0;i&&t.add(`${n.piboSessionId}:${e}:${i}`),FA(n)&&n.entryId&&t.add(`${n.piboSessionId}:${e}:${n.entryId}`)}if(n.type===`assistant.message`){let e=zA(n,`assistant:`);e&&(t.add(`${n.piboSessionId}:assistant_delta:${e}`),(FA(n)||n.completedAt!==void 0)&&t.add(`${n.piboSessionId}:assistant_message:${e}`)),FA(n)&&n.eventId&&(t.add(`${n.piboSessionId}:message_started:${n.eventId}`),t.add(`${n.piboSessionId}:message_finished:${n.eventId}`))}if(n.type===`model.reasoning`){let e=zA(n,`reasoning:`);e&&(t.add(`${n.piboSessionId}:thinking_delta:${e}`),FA(n)&&(t.add(`${n.piboSessionId}:thinking_started:${e}`),t.add(`${n.piboSessionId}:thinking_finished:${e}`)))}if(n.toolCallId&&(n.type===`tool.call`||n.type===`tool.result`||n.type===`agent.delegation`)){let e=`tool:${n.toolCallId}`;t.add(`${n.piboSessionId}:tool_call:${e}`);let r=n.completedAt!==void 0||n.type===`tool.result`||n.status===`error`;(n.status===`running`||n.output!==void 0||r)&&t.add(`${n.piboSessionId}:tool_execution_started:${e}`),(n.output!==void 0&&!r||r)&&t.add(`${n.piboSessionId}:tool_execution_updated:${e}`),r&&t.add(`${n.piboSessionId}:tool_execution_finished:${e}`)}PA(n.children,t)}}function FA(e){return e.source===`transcript`||e.source===`product-history`}function IA(e,t){let n=t.payload;if(!n||typeof n!=`object`||Array.isArray(n))return!1;let r=`source`in n?n.source:void 0,i=`text`in n?n.text:void 0;return r!==`service`||typeof i!=`string`||!pC(i)?!1:LA(e,t)}function LA(e,t){let n=t.eventSequence;if(n===void 0||e.firstEventSequence===void 0)return!1;let r=e.lastEventSequence??e.eventCount;return r!==void 0&&n>=e.firstEventSequence&&n<=r}function RA(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(r){if(e.type===`tool_call`||e.type===`tool_execution_started`||e.type===`tool_execution_updated`||e.type===`tool_execution_finished`){let n=`toolCallId`in t&&typeof t.toolCallId==`string`?t.toolCallId:void 0;return n?`${r}:${e.type}:tool:${n}`:void 0}if(n){if(e.type===`assistant_delta`||e.type===`assistant_message`){let i=BA(t,`assistantIndex`)??BA(t,`contentIndex`),a=i===void 0?n:`${n}:assistant:${i}`;return`${r}:${e.type}:${a}`}if(e.type===`thinking_started`||e.type===`thinking_delta`||e.type===`thinking_finished`){let i=BA(t,`thinkingIndex`)??BA(t,`contentIndex`),a=i===void 0?n:`${n}:thinking:${i}`;return`${r}:${e.type}:${a}`}return`${r}:${e.type}:${n}`}}}function zA(e,t){return e.stableKey?.startsWith(t)?e.stableKey.slice(t.length):e.eventId}function BA(e,t){let n=t in e?e[t]:void 0;return typeof n==`number`&&Number.isFinite(n)?n:void 0}function VA(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 HA({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?AA(n,t):null)?.events??[];if(!o.length)return{traceView:t};let s=a?.(),c=Sw(t,o,r??`idle`),l=vA(o);return l&&bA(c.nodes,i),{traceView:l?_A(c):c,liveTraceComputeDurationMs:s!==void 0&&a?a()-s:void 0}}function UA(e,t){for(let n of e)t(n),UA(n.children,t)}function WA(e){return typeof e.output==`string`?e.output:typeof e.summary==`string`?e.summary:``}function GA(e){if(!e)return;let t=0;return UA(e.nodes,e=>{e.type===`assistant.message`&&(t+=WA(e).length)}),t}function KA({selectedPiboSessionId:e,baseTraceView:t,liveTraceOverlay:n,selectedSessionStatus:r}){let i=(0,v.useMemo)(()=>t?_A(t):null,[t]),a=(0,v.useMemo)(()=>i?yA(i.nodes):new Map,[i]),o=(0,v.useMemo)(()=>HA({selectedPiboSessionId:e,reconciledBaseTraceView:i,liveTraceOverlay:n,selectedSessionStatus:r,persistedUserMessageIndexForBaseTrace:a,now:by()?()=>performance.now():void 0}),[n,e,r,i,a]),s=o.traceView;return(0,v.useEffect)(()=>{!e||!s?.piboSessionId||!by()||(ky(s.piboSessionId,{overlayEventCount:n?.piboSessionId===s.piboSessionId?n.events.length:0,traceBaseOutputLength:GA(t),currentOutputLength:GA(s)}),o.liveTraceComputeDurationMs!==void 0&&Ey(s.piboSessionId,o.liveTraceComputeDurationMs))},[t,o.liveTraceComputeDurationMs,s,n,e]),(0,v.useEffect)(()=>{if(!s?.piboSessionId||!Vb())return;let e=n?.piboSessionId===s.piboSessionId?n.events:[];qb({piboSessionId:s.piboSessionId,trigger:`trace-state:render`,baseTraceView:t,currentTraceView:s,overlayEvents:e,selectedSessionStatus:r})},[t,s,n,r]),(0,v.useEffect)(()=>{let e=()=>{if(!s?.piboSessionId||!Vb())return;let e=n?.piboSessionId===s.piboSessionId?n.events:[];qb({piboSessionId:s.piboSessionId,trigger:`trace-state:tab:${document.visibilityState}`,baseTraceView:t,currentTraceView:s,overlayEvents:e,selectedSessionStatus:r})};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[t,s,n,r]),s}var qA=1e4,JA=3e5;function YA(e){return[`chat`,`trace-summary`,e]}function XA(e,t={}){let n=t.pageSize??t.eventLimit??50,r=t.beforeCursor??t.beforeSequence;return[`chat`,`trace-page`,e,t.includeRawEvents?`raw`:`compact`,t.rawEventsLimit??80,n,r===void 0?`tail`:String(r)]}function ZA(e,t){if(e.piboSessionId!==t.piboSessionId)return e;let n=new Set,r=[...t.rawEvents,...e.rawEvents].filter(e=>{let t=e.id||`${e.eventSequence??``}:${e.type}:${e.createdAt}`;return!n.has(t)&&(n.add(t),!0)});return{...e,version:e.version,nodes:cj(t.nodes,e.nodes),rawEvents:r,beforeCursor:t.beforeCursor??e.beforeCursor,firstEventSequence:t.firstEventSequence??e.firstEventSequence,nextBeforeSequence:t.nextBeforeSequence,nextBeforeCursor:t.nextBeforeCursor,hasOlderEvents:t.hasOlderEvents,eventLimit:(e.eventLimit??0)+(t.eventLimit??t.pageSize??0)}}function QA(e,t){return e.piboSessionId===t.piboSessionId?{...t,nodes:$A(e.nodes,t),rawEvents:oj(e.rawEvents,t.rawEvents),beforeCursor:e.beforeCursor,firstEventSequence:e.firstEventSequence??t.firstEventSequence,nextBeforeSequence:e.nextBeforeSequence,nextBeforeCursor:e.nextBeforeCursor,hasOlderEvents:e.hasOlderEvents,eventLimit:e.eventLimit??t.eventLimit}:t}function $A(e,t){let n=ZS([...e]),r=ZS([...t.nodes]),i=new Set(r.map(e=>e.id)),a=tj([...n,...r]),o=rj(r),s=ij(r),c=n.filter(e=>{if(i.has(e.id))return!0;if(e.type===`agent.turn`&&e.source===`event-log`&&e.eventId&&a.has(e.eventId)||nj(e))return!1;let n=e.orderKey?.eventSequence;if(n!==void 0&&t.firstEventSequence!==void 0)return n<t.firstEventSequence;let r=e.orderKey?o.get(e.orderKey.sourceRank):void 0;if(e.orderKey&&r)return GS(e.orderKey,r)<0;if(e.source===`live`||e.orderKey?.streamId!==void 0)return!1;let c=aj(e.startedAt);return c!==void 0&&s!==void 0&&c<s}),l=new Set([...c,...r].map(e=>e.id)),u=new Set(n.filter(e=>!l.has(e.id)).map(e=>e.id));return cj(ej(c,u),ej(r,u))}function ej(e,t){return e.map(e=>e.parentId&&t.has(e.parentId)?{...e,parentId:void 0}:e)}function tj(e){let t=new Set;for(let n of e)(n.source===`transcript`||n.source===`product-history`)&&n.eventId&&t.add(n.eventId);return t}function nj(e){return e.source===`live`||e.orderKey?.streamId!==void 0}function rj(e){let t=new Map;for(let n of e){if(!n.orderKey)continue;let e=t.get(n.orderKey.sourceRank);(!e||GS(n.orderKey,e)<0)&&t.set(n.orderKey.sourceRank,n.orderKey)}return t}function ij(e){let t;for(let n of e){let e=aj(n.startedAt);e!==void 0&&(t=t===void 0?e:Math.min(t,e))}return t}function aj(e){if(!e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function oj(e,t){if(!t.length)return e;let n=t.reduce((e,t)=>t.eventSequence===void 0?e:e===void 0?t.eventSequence:Math.min(e,t.eventSequence),void 0),r=new Map;for(let t of e)n!==void 0&&t.eventSequence!==void 0&&t.eventSequence>=n||r.set(sj(t),t);for(let e of t)r.set(sj(e),e);return[...r.values()]}function sj(e){return e.id||`${e.eventSequence??``}:${e.type}:${e.createdAt}`}function cj(e,t){let n=new Map;for(let t of ZS([...e]))n.set(t.id,{...t,children:[]});for(let e of ZS([...t])){let t=n.get(e.id);n.set(e.id,{...t,...e,children:[]})}return QS([...n.values()])}function lj(e,t=[]){let n=new Map,r=[],i=e.hasOlderEvents??e.cursor.hasOlder,a=i?e.nextBeforeCursor??e.cursor.before:void 0,o=i?e.nextBeforeSequence??uj(e.cursor.before):void 0;for(let t of e.nodes)n.set(t.nodeId,dj(t));for(let t of e.nodes){let e=n.get(t.nodeId);if(!e)continue;let i=t.parentId?n.get(t.parentId):void 0;i?i.children.push(e):r.push(e)}return{piboSessionId:e.piboSessionId,piSessionId:e.piSessionId,title:e.title,version:e.version,latestStreamId:e.latestStreamId,eventCount:e.eventCount,eventLimit:e.pageSize,pageSize:e.pageSize,beforeCursor:e.cursor.before,firstEventSequence:e.firstEventSequence??uj(e.cursor.before),lastEventSequence:e.lastEventSequence??uj(e.cursor.after),nextBeforeSequence:o,nextBeforeCursor:a,hasOlderEvents:i,nodes:r,rawEvents:t}}function uj(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function dj(e){let t=e.preview?.text,n=e.payloadRefs?.input?.preview,r=e.payloadRefs?.output?.preview??e.payloadRefs?.reasoning?.preview??t,i=e.payloadRefs?.error?.preview,a=e.inlinePayloads?.output??e.inlinePayloads?.reasoning;return{id:e.nodeId,parentId:e.parentId,entryId:e.entryId,piboSessionId:e.piboSessionId,eventId:e.eventId,toolCallId:e.toolCallId,runId:e.runId,type:e.type,title:e.title,status:e.status,startedAt:e.startedAt,completedAt:e.completedAt,durationMs:e.durationMs,summary:t,input:e.inlinePayloads?.input??n,output:a??r,error:typeof e.inlinePayloads?.error==`string`?e.inlinePayloads.error:i,payloadRefs:e.payloadRefs,linkedPiboSessionId:e.linkedPiboSessionId,source:e.source,stableKey:e.stableKey,orderKey:e.orderKey,children:[]}}var fj=128;function pj({selectedPiboSessionId:e,showRawEvents:t,liveTraceOverlay:n,liveTraceOverlayCacheRef:r,setLiveTraceOverlay:i}){let a=FO(),[o,s]=(0,v.useState)(50),[c,l]=(0,v.useState)(80),[u,d]=(0,v.useState)(null),f=(0,v.useRef)(new Map),[p,m]=(0,v.useState)(void 0),[h,g]=(0,v.useState)(!1),_=(0,v.useRef)(null),y=(0,v.useRef)(new Set),b=(0,v.useMemo)(()=>e?YA(e):null,[e]),x=(0,v.useMemo)(()=>e?XA(e,{includeRawEvents:!1,rawEventsLimit:0,pageSize:50}):null,[e]),S=YO({queryKey:b??[`chat`,`trace-summary`,`idle`],queryFn:async({signal:t})=>{if(!e||!b)throw Error(`Session is required`);let n=a.getQueryData(b),r=await yx(e,n?.version,{signal:t});if(r.notModified&&n)return n;if(!r.summary)throw Error(`Trace summary response missing payload.`);return r.summary},enabled:!1,staleTime:qA,gcTime:JA,refetchOnWindowFocus:!1,retry:1}),C=YO({queryKey:x??[`chat`,`trace-page`,`idle`,`compact`,c,50,`tail`],queryFn:async({signal:t})=>{if(!e||!x)throw Error(`Session is required`);let n=a.getQueryData(x),r=await bx(e,{limit:50,knownVersion:n?.version,signal:t});if(r.notModified&&n)return n;if(!r.timeline)throw Error(`Trace timeline response missing payload.`);return lj(r.timeline)},enabled:!!e,staleTime:qA,gcTime:JA,refetchOnWindowFocus:!1,retry:1});(0,v.useLayoutEffect)(()=>{let t=x?a.getQueryData(x):void 0;s(50),l(80),m(void 0),g(!1),d(n=>(n&&f.current.set(n.piboSessionId,n),e?f.current.get(e)??(t?.piboSessionId===e?t:null):null)),i(t=>OA(r.current,t,e)),_.current=null,y.current=new Set},[r,a,e,i,x]);let w=YO({queryKey:e?[`chat`,`trace-raw-events`,e,c,p??`tail`]:[`chat`,`trace-raw-events`,`idle`],queryFn:async({signal:t})=>{if(!e)throw Error(`Session is required`);return xx(e,{limit:c,beforeSequence:p,signal:t})},enabled:!!(e&&t),staleTime:qA,gcTime:JA,refetchOnWindowFocus:!1,retry:1});(0,v.useEffect)(()=>{let t=C.data;!t||t.piboSessionId!==e||(by()&&ky(t.piboSessionId,{overlayEventCount:0,traceBaseOutputLength:GA(t),traceBaseUpdated:!0}),(0,v.startTransition)(()=>{d(e=>{let n=e?.piboSessionId===t.piboSessionId?QA(e,t):t;return f.current.set(t.piboSessionId,n),n}),i(e=>kA(r.current,e,t))}))},[r,e,i,C.data]),(0,v.useEffect)(()=>{let t=u;!t||t.piboSessionId!==e||(0,v.startTransition)(()=>{i(e=>kA(r.current,e,t))})},[u,r,e,i]),(0,v.useEffect)(()=>{let t=w.data;!t||t.piboSessionId!==e||(0,v.startTransition)(()=>{d(e=>{if(!e)return e;if(p===void 0)return{...e,rawEvents:t.events};let n=new Set(t.events.map(e=>e.id));return{...e,rawEvents:[...t.events,...e.rawEvents.filter(e=>!n.has(e.id))]}})})},[p,w.data,e]);let T=(0,v.useCallback)(async n=>{if(!e||!n)return;let r=`${e}:${n}`;if(_.current||y.current.has(r))return;_.current=r,g(!0);let i=XA(e,{includeRawEvents:t,rawEventsLimit:c,pageSize:50,beforeCursor:n});try{let t=await a.fetchQuery({queryKey:i,queryFn:async({signal:t})=>{let r=a.getQueryData(i),o=await bx(e,{limit:50,beforeCursor:n,knownVersion:r?.version,signal:t});if(o.notModified&&r)return r;if(!o.timeline)throw Error(`Trace timeline response missing payload.`);return lj(o.timeline)},staleTime:qA,gcTime:JA});(0,v.startTransition)(()=>{d(e=>e?ZA(e,t):t),s(e=>e+(t.pageSize??50))}),mj(y.current,r)}finally{_.current===r&&(_.current=null),g(!1)}},[a,c,e,t]),E=e?u?.piboSessionId===e?u:f.current.get(e)??(C.data?.piboSessionId===e?C.data:null):null,D=e?n?.piboSessionId===e?n:r.current.get(e)??null:null,O=(0,v.useCallback)(()=>{let e=E?.rawEvents[0]?.eventSequence;m(e),l(e=>e+80)},[E?.rawEvents]);return{baseTraceView:E,liveTraceOverlay:D,traceEventLimit:o,rawEventLimit:c,traceSummaryQuery:S,tracePageQuery:C,rawEventsQuery:w,loadingOlderTracePage:h,tracePageReady:!!x,loadOlderTracePage:T,loadMoreRawEvents:O}}function mj(e,t){if(e.add(t),e.size<=fj)return;let n=e.values().next();n.done||e.delete(n.value)}function hj(e){let t=e.currentEvents,n,r,i=()=>(r??=new Set(t.map(Sj)),r),a=e=>{n??=t.slice(),n.push(e),t=n};for(let o of e.streamEvents){let s=vj(o,e.piboSessionId,e.nextSequence,e.now??(()=>new Date().toISOString()));if(!s)continue;if(gj(s)){t=_j(t,s),n=t,r=void 0;continue}let c=Sj(s),l=i();l.has(c)||(l.add(c),a(s))}return t}function gj(e){return e.type===`assistant_message`||e.type===`thinking_finished`||e.type===`tool_execution_finished`}function _j(e,t){return t.type===`assistant_message`?[...xj(e,t,`assistant_delta`),t]:t.type===`thinking_finished`?[...xj(e,t,`thinking_delta`),t]:t.type===`tool_execution_finished`?[...xj(e,t,`tool_execution_updated`),t]:e}function vj(e,t,n,r){if(e.type===`RAW_EVENT`&&Tj(e.event)&&typeof e.event.type==`string`){let i=e.event;return yj(e,t,e.event.type,i,n,r)}if(e.type===`TEXT_MESSAGE_CONTENT`&&typeof e.delta==`string`)return yj(e,t,`assistant_delta`,{type:`assistant_delta`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,...wj(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 yj(e,t,`thinking_delta`,{type:`thinking_delta`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,...wj(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 yj(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 yj(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 yj(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 yj(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 yj(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,traceSource:`live`,eventId:typeof r.eventId==`string`?r.eventId:void 0,type:n,createdAt:bj(e)??a(),payload:r}}function bj(e){if(!(typeof e.createdAt!=`string`||!Number.isFinite(Date.parse(e.createdAt))))return e.createdAt}function xj(e,t,n){let r=Cj(t);return e.filter(e=>e.type!==n||Cj(e)!==r)}function Sj(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 Cj(e){let t=Tj(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 wj(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 Tj(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Ej(e){try{let t=JSON.parse(e.data);if(typeof t.type!=`string`)return;let n=e.lastEventId?US(e.lastEventId):void 0;return{...t,...e.lastEventId?{streamFrameId:e.lastEventId}:{},...n?{streamId:n.streamId,streamFrameIndex:n.frameIndex}:{}}}catch{return}}function Dj(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:kj(n),exact:!1,...r?.liveReplayId===void 0?{}:{liveReplayId:r.liveReplayId}})}function Oj(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 kj(e){return`${e}:999999`}function Aj(e){if(e.type===`RUN_FINISHED`||e.type===`TEXT_MESSAGE_END`)return 300;if(e.type===`RUN_ERROR`)return 0}function jj(e){return e.type===`RUN_STARTED`||e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`||e.type===`TEXT_MESSAGE_END`||e.type===`RUNTIME_APPROVAL_REQUESTED`||e.type===`RUNTIME_APPROVAL_RESOLVED`||e.type===`RUNTIME_USER_INPUT_REQUESTED`||e.type===`RUNTIME_USER_INPUT_RESOLVED`}function Mj(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 Nj(e,t,n){if(n.type===`RUN_STARTED`||n.type===`RUN_FINISHED`||n.type===`RUN_ERROR`){e.delete(t);return}let r=Ij(n);r&&e.get(t)?.delete(r)}function Pj(e,t,n){let r=Fj(n);if(!r)return!1;let i=e.get(t);return i||(i=new Set,e.set(t,i)),!i.has(r)&&(i.add(r),!0)}function Fj(e){if(e.type===`TEXT_MESSAGE_CONTENT`||e.type===`REASONING_MESSAGE_CONTENT`)return`${e.type}:${e.messageId}`}function Ij(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 Lj=500,Rj=1e4,zj=45e3,Bj=15e3,Vj=100,Hj=2;function Uj(e){let t=Math.max(e.eventCount??0,e.lastEventSequence??0);for(let n of e.rawEvents)t=Math.max(t,n.eventSequence??0);return t+1}function Wj(e){if(e.forceReconnect)return!0;let t=e.liveStream;return!t||t.piboSessionId!==e.selectedPiboSessionId||t.readyState===Hj||(e.nowMs??Date.now())-t.lastActivityAt>zj}function Gj({selectedPiboSessionId:e,tracePageData:t,currentTraceView:n,liveEventSeqRef:r,selectedSessionStatus:i,tracePageReady:a,setLiveTraceOverlay:o,onRefreshTrace:s,onRefreshBootstrap:c,onRuntimeRequestEvent:l,onError:u}){let d=(0,v.useRef)(new Map),f=(0,v.useRef)(void 0),p=(0,v.useRef)(void 0),m=(0,v.useRef)(new Map),h=(0,v.useRef)(new Map),g=(0,v.useRef)(null),_=(0,v.useRef)(void 0),y=(0,v.useRef)(0),b=(0,v.useRef)(!1),x=(0,v.useRef)(!1),[S,C]=(0,v.useState)(0);(0,v.useEffect)(()=>{let n=t;!n||n.piboSessionId!==e||(r.current=Math.max(r.current,Uj(n)),n.latestStreamId!==void 0&&Dj(h.current,n.piboSessionId,n.latestStreamId))},[r,e,t]);let w=(0,v.useCallback)(e=>{let t=d.current.get(e);t?.length&&(o(n=>{let i=hj({currentEvents:n?.piboSessionId===e?n.events:[],streamEvents:t,piboSessionId:e,nextSequence:()=>r.current++});return Ty(e,t.length,i.length),{piboSessionId:e,events:i}}),d.current.delete(e))},[]),T=(0,v.useCallback)(()=>{if(!(f.current!==void 0||p.current!==void 0||!e)){if(document.hidden){p.current=setTimeout(()=>{p.current=void 0,w(e)},Vj);return}f.current=requestAnimationFrame(()=>{f.current=void 0,w(e)})}},[w,e]),E=(0,v.useCallback)((t,n,r=!1)=>{Nj(m.current,t,n);let i=r||Pj(m.current,t,n),a=d.current.get(t)??[];a.push(n),d.current.set(t,a),wy(t,n,a.length,i),i||t!==e?w(t):T()},[w,T,e]);(0,v.useEffect)(()=>()=>{f.current!==void 0&&cancelAnimationFrame(f.current),p.current!==void 0&&clearTimeout(p.current),_.current!==void 0&&clearTimeout(_.current)},[]);let D=(0,v.useCallback)((e,t)=>{Oj(h.current,e,t)},[]),O=(0,v.useCallback)((e=0)=>{if(_.current!==void 0){if(e>0)return;clearTimeout(_.current)}_.current=setTimeout(()=>{_.current=void 0,C(e=>e+1)},e)},[]),k=(0,v.useCallback)((t=!1)=>{if(!e)return;w(e),s().catch(e=>u(Kj(e))),c().catch(e=>u(Kj(e)));let n=g.current;if(Wj({selectedPiboSessionId:e,liveStream:n?{piboSessionId:n.piboSessionId,lastActivityAt:n.lastActivityAt,readyState:n.events.readyState}:null,forceReconnect:t})){if(t){if(b.current)return;b.current=!0}O()}},[w,u,c,s,O,e]);(0,v.useEffect)(()=>{if(!e||!a||!n||n.piboSessionId!==e)return;let t=new URLSearchParams({piboSessionId:e});t.set(`mode`,`live`);let r=h.current.get(e),i=r?.cursor??(n.latestStreamId===void 0?void 0:kj(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()}`),d=Date.now();g.current={piboSessionId:e,events:o,openedAt:d,lastActivityAt:d};let f=!1,p,m,v=!1,x=!1,S=(t,n=!1)=>{if(p){if(!n)return;clearTimeout(p)}Oy(e,t),p=setTimeout(()=>{p=void 0,s().catch(e=>u(Kj(e)))},t)},C=()=>{if(v){x=!0;return}v=!0,c().catch(e=>u(Kj(e))).finally(()=>{v=!1,x&&(x=!1,T(250,!0))})},T=(e,t=!1)=>{if(m){if(!t)return;clearTimeout(m)}m=setTimeout(()=>{m=void 0,C()},e)},k=()=>{T(900,!0)};return o.onopen=()=>{y.current=0,b.current=!1,_.current!==void 0&&(clearTimeout(_.current),_.current=void 0),xy(e,o.readyState);let t=g.current;t?.events===o&&(t.lastActivityAt=Date.now())},o.onerror=()=>{if(f)return;Sy(e,o.readyState);let t=g.current;t?.events===o&&(t.lastErrorAt=Date.now());let n=y.current++,r=Math.min(Rj,Lj*2**n);O(r)},o.addEventListener(`pibo`,t=>{if(f)return;let n=Ej(t);if(!n)return;let r=n.piboSessionId||e,i=g.current;if(i?.events===o&&(i.lastActivityAt=Date.now()),D(r,n),Cy(r,n,t.lastEventId,o.readyState),r===e&&n.type===`ready`&&n.liveReplay?.missed&&S(0,!0),Ay(n))return;(n.type===`RUNTIME_APPROVAL_REQUESTED`||n.type===`RUNTIME_APPROVAL_RESOLVED`||n.type===`RUNTIME_USER_INPUT_REQUESTED`||n.type===`RUNTIME_USER_INPUT_RESOLVED`)&&l?.(n);let a=n.type!==`TEXT_MESSAGE_CONTENT`&&n.type!==`REASONING_MESSAGE_CONTENT`;r===e&&Mj(n)&&E(r,n,a);let s=Aj(n);r===e&&s!==void 0?S(s,!0):r===e&&n.type!==`ready`&&n.type!==`RAW_EVENT`&&S(1500,!0),jj(n)&&(n.type===`RUN_FINISHED`||n.type===`RUN_ERROR`||n.type===`TEXT_MESSAGE_END`?k():T(r===e?0:150))}),()=>{f=!0,p&&clearTimeout(p),m&&clearTimeout(m),w(e),g.current?.events===o&&(g.current=null),o.close()}},[n?.piboSessionId,E,w,u,c,s,l,D,O,S,e,a]),(0,v.useEffect)(()=>{n?.piboSessionId&&w(n.piboSessionId)},[n?.piboSessionId,w]),(0,v.useEffect)(()=>{let e=()=>k(),t=()=>k(!0),n=()=>{x.current=!0},r=()=>{if(document.hidden){n();return}x.current=!1,k(!0)},i=e=>{let t=x.current||e.persisted;x.current=!1,k(t)};return window.addEventListener(`focus`,e),window.addEventListener(`online`,t),window.addEventListener(`pagehide`,n),window.addEventListener(`pageshow`,i),document.addEventListener(`visibilitychange`,r),()=>{window.removeEventListener(`focus`,e),window.removeEventListener(`online`,t),window.removeEventListener(`pagehide`,n),window.removeEventListener(`pageshow`,i),document.removeEventListener(`visibilitychange`,r)}},[k]),(0,v.useEffect)(()=>{if(!e||i!==`running`)return;let t=window.setInterval(()=>{w(e);let t=g.current;Wj({selectedPiboSessionId:e,liveStream:t?{piboSessionId:t.piboSessionId,lastActivityAt:t.lastActivityAt,readyState:t.events.readyState}:null})&&(s().catch(e=>u(Kj(e))),O())},Bj);return()=>window.clearInterval(t)},[w,u,s,O,e,i])}function Kj(e){return e instanceof Error?e.message:String(e)}var qj=10;function Jj(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,qj)}:e}function Yj(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 Xj(e,t){return!t||!e[t]?.length?e:{...e,[t]:[]}}function Zj(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=>Jj(r,e,n,t))},[t,e]),detachUploadAttachment:(0,v.useCallback)(t=>{r(n=>Yj(n,e,t))},[e]),clearSelectedUploadAttachments:(0,v.useCallback)(()=>{r(t=>Xj(t,e))},[e])}}function Qj({selectedPiboSessionId:e,onError:t,formatError:n}){let[r,i]=(0,v.useState)([]),[a,o]=(0,v.useState)(!1),[s,c]=(0,v.useState)(()=>e?Sk(e):null),[l,u]=(0,v.useState)(()=>kk()),[d,f]=(0,v.useState)(!1),p=!!(e&&s?.piboSessionId===e&&s.installed),m=!!e&&(a||p),h=YO({queryKey:[`web-annotations`,`app`,e],queryFn:async()=>{if(!e)throw Error(`Session is required`);return Zx(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?Ek(e):[]),c(e?Sk(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(Tk(e.detail)),r=n=>{n.key===Ck(e)&&t(wk(n.newValue))},i=()=>t(Sk(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&&Dk(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&&Dk(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&&Dk(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 Ak(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=>Qx(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,_])}}var $j=new WeakMap;function eM(e,t,n){let r=n.map(e=>tM(e)),i=cM(r),a=i.length?Math.min(...i.map(e=>e.startTime)):Date.now()*1e3,o=i.flatMap(e=>e.endTime?[e.endTime]:[]),s=o.length?Math.max(...o):void 0,c=i.some(e=>e.status===`UNSET`);return{id:e,name:t,status:i.some(e=>e.status===`ERROR`)?`ERROR`:c?`UNSET`:`OK`,spans:r,startedAt:new Date(a/1e3),completedAt:s?new Date(s/1e3):void 0,totalDurationMs:s?(s-a)/1e3:0}}function tM(e){let t=$j.get(e);if(t)return t;let n=sM(e.startedAt)??Date.now()*1e3,r=sM(e.completedAt),i=oM(e.status),a=nM(e.type),o={id:e.id,parentId:e.parentId,name:rM(e),spanType:a,startTime:n,endTime:r,durationUs:e.durationMs===void 0?void 0:e.durationMs*1e3,attributes:iM(e),status:i,statusMessage:e.error,events:e.error?[{name:`exception`,timestamp:r??n,attributes:{message:e.error}}]:[],children:e.children?.map(tM),pibo:{entryId:e.entryId,linkedPiboSessionId:e.linkedPiboSessionId,traceNodeType:e.type,traceOrder:e.orderKey,stableKey:e.stableKey,source:e.source}};return $j.set(e,o),o}function nM(e){switch(e){case`user.message`:return`user.prompt`;case`assistant.message`:return`model.response`;case`model.reasoning`:return`model.reasoning`;case`tool.call`:return`tool.call`;case`tool.result`:return`tool.result`;case`agent.delegation`:return`agent.delegation`;case`agent.async`:return`agent.async`;case`execution.command`:case`execution.compaction`:return`execution.command`;case`yielded.run`:return`yielded.run`;case`agent.turn`:return`agent.run`;case`error`:return`tool.result`}}function rM(e){return e.type===`assistant.message`?`assistant_message`:e.type===`user.message`?`user_prompt`:e.type===`model.reasoning`?`model_reasoning`:e.title||e.type}function iM(e){let t={};if(e.summary&&(t.content=e.summary),e.input!==void 0&&(t.input=e.input,t.args=e.input,t.arguments=e.input),e.output!==void 0&&(t.output=e.output,t.result=e.output),e.error&&(t.error=e.error),e.toolCallId&&(t.tool_call_id=e.toolCallId),e.runId&&(t.run_id=e.runId),(e.type===`tool.call`||e.type===`agent.delegation`)&&(t.tool_name=e.title),e.type===`assistant.message`&&(t.content=e.output??e.summary??``),e.type===`user.message`){t.content=e.output??e.summary??``;let n=aM(e);n&&(t[`message.pending_delivery`]=n)}return e.type===`model.reasoning`&&(t.reasoning=e.output??e.summary??``),e.type===`agent.delegation`&&(t[`delegation.target_agent`]=e.title.replace(/^pibo_subagent_/,``),t[`delegation.query`]=e.summary??e.input,t[`result.status`]=e.status===`done`?`completed`:e.status,t.linked_pibo_session_id=e.linkedPiboSessionId),e.type===`agent.async`&&(t[`async_agent.target_agent`]=e.title,t[`async_agent.started_by`]=lM(e.input)?e.input.startedBy:`pibo_run_start`,t[`async_agent.query`]=lM(e.input)?e.input.arguments:e.input,t[`result.status`]=e.status===`done`?`started`:e.status,t.linked_pibo_session_id=e.linkedPiboSessionId),e.type===`yielded.run`&&(t[`run.notification`]=!0,t[`run.status`]=e.status),t}function aM(e){if(e.type===`user.message`&&e.status===`running`){if(e.id.startsWith(`event:message_steered:`))return`steer`;if(e.id.startsWith(`event:message_queued:`))return`queue`}}function oM(e){return e===`running`?`UNSET`:e===`error`?`ERROR`:`OK`}function sM(e){if(!e)return;let t=new Date(e).getTime();return Number.isFinite(t)?t*1e3:void 0}function cM(e){return e.flatMap(e=>[e,...e.children?cM(e.children):[]])}function lM(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function uM(e){return(e.selectedPiboSessionId?S(e.sessionNodes,e.selectedPiboSessionId):void 0)?.title||e.traceTitle||e.selectedPiboSessionId||e.fallback}function dM(e,t){return t?{sessionBreadcrumbs:gM(e,t),originSession:mM(e,t),derivedSessions:hM(e,t)}:{sessionBreadcrumbs:[],originSession:void 0,derivedSessions:[]}}function fM(e){let t=e.selectedPiboSessionId?S(e.bootstrap.sessions,e.selectedPiboSessionId):void 0,n=bM(e.currentTraceView);return yM(e.selectedSessionActiveModel,e.bootstrap.runtimeStatus?.thinkingLevel??n.level??_M(e.bootstrap,e.selectedSessionProfile,!!t?.parentId),e.bootstrap.runtimeStatus?.fastMode??n.fast??vM(e.bootstrap,e.selectedSessionProfile,!!t?.parentId)??!1)}function pM(e){return{traceView:e.currentTraceView,selectedTrace:e.currentTraceView?eM(e.currentTraceView.piboSessionId,e.currentTraceView.title,e.currentTraceView.nodes):null,isLoading:e.isLoading,showThinking:e.showThinking,expandThinking:e.expandThinking,sessionAgentProfile:e.selectedSessionProfile,sessionActiveModel:e.sessionActiveModelBadge,sessionRuntimeBinding:e.sessionRuntimeBinding,selectedSessionStatus:e.selectedSessionStatus,selectedSessionSignal:e.selectedSessionSignal,signals:e.signals,sessionGoal:e.sessionGoal,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,onLoadOlderTracePage:e.onLoadOlderTracePage,hasOlderTraceEvents:e.hasOlderTraceEvents,isFetchingOlderTracePage:e.isFetchingOlderTracePage,onThinkingLevelChange:e.onThinkingLevelChange,onModelChanged:async()=>{await e.onRefreshBootstrap(),await e.onRefreshTrace()},onRefreshBootstrap:e.onRefreshBootstrap,onError:e.onError}}function mM(e,t){let n=S(e,t);if(!n?.originId)return;let r=S(e,n.originId);return{piboSessionId:n.originId,label:r?CM(r,0):n.originId}}function hM(e,t){return S(e,t)?.derivedSessions.map(e=>({piboSessionId:e.piboSessionId,label:wM(e),profile:e.profile,status:e.status}))??[]}function gM(e,t){return C(e,t).map((e,t)=>({piboSessionId:e.piboSessionId,label:CM(e,t)}))}function _M(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 vM(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 yM(e,t,n){if(e)return[e,t,n?`fast`:void 0].filter(Boolean).join(` `)}function bM(e){let t={};if(!e)return t;for(let n of xM(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`&&SM(e.level)?e.level:void 0)??t.level,fast:n.title===`fast_mode`?e?.mode===`fast`:t.fast}}return t}function xM(e){return e.flatMap(e=>[e,...xM(e.children)])}function SM(e){return $T.includes(e)}function CM(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 wM(e){return e.subagentName&&e.subagentName!==e.profile?`${e.subagentName} (${e.profile})`:e.title||e.profile||e.subagentName||`Untitled Session`}function TM({piboSessionId:e,text:t,selectedWebAnnotations:n,selectedUploadAttachments:r,eventSequence:i,now:a,clientTxnId:o,delivery:s=`queue`}){let c=n.map(e=>e.id),l=r.map(e=>e.path),u=s===`steer`?`message_steered`:`message_queued`;return{piboSessionId:e,text:t,webAnnotationIds:c,fileAttachmentPaths:l,clientTxnId:o,delivery:s,optimisticEvent:{id:o,piboSessionId:e,eventSequence:i,eventId:o,type:u,createdAt:a,payload:{type:u,piboSessionId:e,eventId:o,clientTxnId:o,delivery:s,...s===`queue`?{queuedMessages:1}:{},text:t,...l.length?{fileAttachmentPaths:l}:{},source:`user`}}}}function EM(e,t){if(e.delivery===t)return e;let n=t===`steer`?`message_steered`:`message_queued`,r={...e.optimisticEvent.payload};return delete r.queuedMessages,{...e,delivery:t,optimisticEvent:{...e.optimisticEvent,type:n,payload:{...r,type:n,delivery:t,...t===`queue`?{queuedMessages:1}:{}}}}}function DM(e,t,n){return{piboSessionId:t,events:[...e?.piboSessionId===t?e.events:[],n]}}var OM=`optimistic-session-`;function kM(e){return e?.startsWith(OM)===!0}function AM(e){return e&&!kM(e)?e:null}function jM(e){return e instanceof Error?e.message:String(e)}var MM=[`(display-mode: standalone)`,`(display-mode: window-controls-overlay)`];function NM(e,t){return MM.some(t=>e(t).matches)?typeof t.userAgentData?.mobile==`boolean`?!t.userAgentData.mobile:!(/Android|iPhone|iPad|iPod|Mobile/i.test(t.userAgent)||/Macintosh/i.test(t.userAgent)&&t.maxTouchPoints>1):!1}function PM(){return typeof window<`u`&&typeof navigator<`u`&&NM(window.matchMedia.bind(window),navigator)}function FM(e,t){return{url:e,name:`pibo-session-${t}`,features:`width=1280,height=900`}}function IM(){let e=FM(window.location.href,crypto.randomUUID());return window.open(e.url,e.name,e.features)}var LM=[{id:`accept`,label:`Approve once`},{id:`acceptForSession`,label:`Approve for session`},{id:`decline`,label:`Decline`},{id:`cancel`,label:`Cancel turn`}];function RM({piboSessionId:e,approvals:t,userInputs:n,onResolved:r,onError:i}){let[a,o]=(0,v.useState)(null);if(t.length===0&&n.length===0)return null;let s=async(t,n)=>{if(!a){o(t),i(null);try{await N(e,`runtime.approval.respond`,{requestId:t,decision:n}),r(t)}catch(e){i(jM(e))}finally{o(null)}}},c=async(t,n)=>{if(!a){o(t),i(null);try{await N(e,`runtime.user_input.respond`,{requestId:t,answers:n}),r(t)}catch(e){i(jM(e))}finally{o(null)}}};return(0,I.jsx)(`section`,{className:`border-t border-slate-800 bg-[#101d22] px-3 py-2 sm:px-4`,"data-pibo-debug":`runtime-request-panel`,"aria-label":`Runtime requests`,children:(0,I.jsxs)(`div`,{className:`mx-auto grid w-full max-w-4xl gap-2`,children:[t.map(e=>(0,I.jsx)(zM,{request:e,busy:a===e.requestId,disabled:a!==null,onDecision:t=>void s(e.requestId,t)},e.requestId)),n.map(e=>(0,I.jsx)(BM,{request:e,busy:a===e.requestId,disabled:a!==null,onSubmit:t=>void c(e.requestId,t)},e.requestId))]})})}function zM({request:e,busy:t,disabled:n,onDecision:r}){let i=e.decisions?.length?e.decisions:LM;return(0,I.jsxs)(`article`,{className:`rounded-sm border border-amber-500/40 bg-amber-500/5`,"data-pibo-debug":`runtime-approval-request`,children:[(0,I.jsxs)(`div`,{className:`flex items-start gap-3 border-b border-amber-500/20 px-3 py-2`,children:[(0,I.jsx)(yt,{size:16,className:`mt-0.5 shrink-0 text-amber-400`,"aria-hidden":`true`}),(0,I.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,I.jsx)(`h3`,{className:`text-xs font-bold uppercase tracking-wider text-amber-300`,children:e.title||`Approval required`}),(0,I.jsx)(`span`,{className:`rounded-sm border border-slate-700 px-1.5 py-0.5 font-mono text-[10px] uppercase text-slate-400`,children:e.requestType})]}),e.detail?(0,I.jsx)(`p`,{className:`mt-1 text-xs leading-5 text-slate-300`,children:e.detail}):null]})]}),e.arguments===void 0?null:(0,I.jsx)(`pre`,{className:`max-h-36 overflow-auto border-b border-slate-800 bg-[#0e1116] px-3 py-2 font-mono text-[11px] leading-5 text-slate-300`,children:UM(e.arguments)}),(0,I.jsx)(`div`,{className:`flex flex-wrap gap-2 px-3 py-2`,children:i.map(e=>(0,I.jsx)(`button`,{type:`button`,onClick:()=>r(e.id),disabled:n,title:e.description,className:HM(e.id),"data-pibo-decision":e.id,children:t?`Responding…`:e.label},e.id))})]})}function BM({request:e,busy:t,disabled:n,onSubmit:r}){let[i,a]=(0,v.useState)({}),o=(0,v.useMemo)(()=>e.questions.every(e=>!!i[e.id]?.trim()),[i,e.questions]);return(0,I.jsxs)(`article`,{className:`rounded-sm border border-cyan-500/40 bg-cyan-500/5`,"data-pibo-debug":`runtime-user-input-request`,children:[(0,I.jsxs)(`div`,{className:`flex items-start gap-3 border-b border-cyan-500/20 px-3 py-2`,children:[(0,I.jsx)(He,{size:16,className:`mt-0.5 shrink-0 text-cyan-400`,"aria-hidden":`true`}),(0,I.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,I.jsx)(`h3`,{className:`text-xs font-bold uppercase tracking-wider text-cyan-300`,children:`Input requested`}),(0,I.jsx)(`span`,{className:`rounded-sm border border-slate-700 px-1.5 py-0.5 font-mono text-[10px] uppercase text-slate-400`,children:e.blocking===!1?`non-blocking`:`blocking`})]}),(0,I.jsx)(`p`,{className:`mt-1 text-xs leading-5 text-slate-400`,children:`Codex is waiting for structured input before continuing this turn.`})]})]}),(0,I.jsx)(`div`,{className:`grid gap-3 px-3 py-3`,children:e.questions.map(t=>(0,I.jsx)(VM,{question:t,groupName:`runtime-question-${e.requestId}-${t.id}`,value:i[t.id]??``,disabled:n,onChange:e=>a(n=>({...n,[t.id]:e}))},t.id))}),(0,I.jsx)(`div`,{className:`flex justify-end border-t border-cyan-500/20 px-3 py-2`,children:(0,I.jsx)(`button`,{type:`button`,onClick:()=>r(i),disabled:n||!o,className:`rounded-sm border border-[#11a4d4] bg-[#11a4d4] px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-[#0d8eb8] disabled:cursor-not-allowed disabled:opacity-50`,children:t?`Submitting…`:`Submit response`})})]})}function VM({question:e,groupName:t,value:n,disabled:r,onChange:i}){let a=e.options??[],o=new Set(a.map(e=>e.label)),s=!!n&&!o.has(n);return(0,I.jsxs)(`fieldset`,{className:`grid gap-2`,disabled:r,children:[(0,I.jsxs)(`legend`,{className:`text-xs font-semibold text-slate-200`,children:[e.header?(0,I.jsx)(`span`,{className:`mr-2 font-mono uppercase text-cyan-400`,children:e.header}):null,e.question]}),a.length?(0,I.jsxs)(`div`,{className:`grid gap-1.5 sm:grid-cols-2`,children:[a.map(e=>(0,I.jsxs)(`label`,{className:`flex cursor-pointer gap-2 rounded-sm border border-slate-700 bg-[#151f24] px-2.5 py-2 text-xs hover:border-cyan-500/60`,children:[(0,I.jsx)(`input`,{type:`radio`,name:t,value:e.label,checked:n===e.label,onChange:()=>i(e.label),className:`mt-0.5 accent-[#11a4d4]`}),(0,I.jsxs)(`span`,{children:[(0,I.jsx)(`span`,{className:`block font-semibold text-slate-200`,children:e.label}),e.description?(0,I.jsx)(`span`,{className:`mt-0.5 block leading-4 text-slate-400`,children:e.description}):null]})]},e.label)),e.allowFreeform?(0,I.jsxs)(`label`,{className:`flex cursor-pointer gap-2 rounded-sm border border-slate-700 bg-[#151f24] px-2.5 py-2 text-xs hover:border-cyan-500/60`,children:[(0,I.jsx)(`input`,{type:`radio`,name:t,checked:s,onChange:()=>i(`Other`),className:`mt-0.5 accent-[#11a4d4]`}),(0,I.jsx)(`span`,{className:`font-semibold text-slate-200`,children:`Other`})]}):null]}):null,a.length===0||e.allowFreeform&&s?(0,I.jsx)(`input`,{type:e.secret?`password`:`text`,value:s&&n===`Other`?``:n,onChange:e=>i(e.target.value),autoComplete:`off`,placeholder:e.secret?`Enter a private response`:`Enter a response`,className:`w-full rounded-sm border border-slate-700 bg-[#0e1116] px-2.5 py-2 font-mono text-xs text-slate-200 outline-none focus:border-[#11a4d4] focus:ring-1 focus:ring-[#11a4d4]/40`}):null]})}function HM(e){let t=`rounded-sm border px-2.5 py-1.5 text-xs font-semibold transition disabled:cursor-not-allowed disabled:opacity-50`;return e===`accept`?`${t} border-emerald-500/60 bg-emerald-500/10 text-emerald-300 hover:bg-emerald-500/20`:e===`acceptForSession`?`${t} border-cyan-500/60 bg-cyan-500/10 text-cyan-300 hover:bg-cyan-500/20`:e===`cancel`?`${t} border-red-500/60 bg-red-500/10 text-red-300 hover:bg-red-500/20`:`${t} border-slate-600 bg-slate-800/60 text-slate-300 hover:border-slate-500`}function UM(e){if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return`[unavailable]`}}function WM({bootstrap:e,selectedPiboSessionId:t,selectedRoomId:n,selectedRoomArchived:r,roomNavigationPending:i,sessionNavigationPending:a,selectedSessionProfile:o,selectedSessionActiveModel:s,selectedSessionStatus:c,selectedSessionSignal:l,signals:u,workflowProjectSession:d,workflowLifecycleEvents:f,projectSessionCreatePanel:p,workflowStartPanel:m,projectModulePanel:h,extraViewTabs:g,activeViewId:_,sessionViewId:y,sessionViews:b,currentSessionView:x,allowedSessionViewIds:S,creatingSession:C,terminalFullscreen:E=!1,onEnterTerminalFullscreen:D,onExitTerminalFullscreen:O,showRawEvents:k,showThinking:A,expandThinking:ee,commands:te,skills:ne,composerText:j,composerFocusSignal:re,onComposerTextChange:M,onToggleRawEvents:N,onToggleThinking:ie,onToggleExpandThinking:ae,onSessionAgentProfileChange:oe,onFork:se,onOpenSession:ce,onSelectSessionView:le,onCommand:de,onThinkingLevelChange:fe,onRefreshTrace:P,onRefreshBootstrap:pe,onSend:me,onError:he}){let ge=(0,v.useRef)(0),_e=(0,v.useRef)(new Map),[ve,ye]=(0,v.useState)(null),be=(0,v.useCallback)(e=>{ye(t=>{let n=typeof e==`function`?e(t):e;return n&&_e.current.set(n.piboSessionId,n),n})},[]),[xe,Se]=(0,v.useState)(null),[F,Ce]=(0,v.useState)([]),[we,Te]=(0,v.useState)([]),Ee=(0,v.useRef)(new Set),De=(0,v.useRef)(null),Oe=AM(t);(0,v.useEffect)(()=>{let t=e.runtimeStatus?.piboSessionId===Oe?e.runtimeStatus:void 0;Ce(t?.pendingApprovals?[...t.pendingApprovals]:[]),Te(t?.pendingUserInputs?[...t.pendingUserInputs]:[])},[e.runtimeStatus,Oe]);let ke=(0,v.useCallback)(e=>{if(e.type===`RUNTIME_APPROVAL_REQUESTED`){Ce(t=>[...t.filter(t=>t.requestId!==e.request.requestId),e.request]);return}if(e.type===`RUNTIME_USER_INPUT_REQUESTED`){Te(t=>[...t.filter(t=>t.requestId!==e.request.requestId),e.request]);return}Ce(t=>t.filter(t=>t.requestId!==e.requestId)),Te(t=>t.filter(t=>t.requestId!==e.requestId))},[]),Ae=(0,v.useCallback)(e=>{Ce(t=>t.filter(t=>t.requestId!==e)),Te(t=>t.filter(t=>t.requestId!==e))},[]),je=YO({queryKey:Oe?[`chat`,`session-goal`,Oe]:[`chat`,`session-goal`,`idle`],queryFn:({signal:e})=>Xx(Oe,{signal:e}),enabled:!!Oe,refetchInterval:Oe?5e3:!1}),Me=!!Oe&&PM(),Ne=(0,v.useCallback)(()=>{IM()||he(`The browser blocked the new Pibo window.`)},[he]),Pe=Me?Ne:void 0,{baseTraceView:Fe,liveTraceOverlay:Ie,rawEventLimit:Le,traceSummaryQuery:Re,tracePageQuery:ze,rawEventsQuery:Be,loadingOlderTracePage:Ve,tracePageReady:He,loadOlderTracePage:Ue,loadMoreRawEvents:We}=pj({selectedPiboSessionId:Oe,showRawEvents:k,liveTraceOverlay:ve,liveTraceOverlayCacheRef:_e,setLiveTraceOverlay:be}),{selectedWebAnnotationIds:Ge,selectedWebAnnotations:Ke,visibleWebAnnotations:qe,webAnnotationsPanelCollapsed:Je,webAnnotationsPanelRendered:Ye,webAnnotationsPanelVisible:Xe,webAnnotationsQuery:Ze,clearingWebAnnotations:Qe,setWebAnnotationsPanelVisible:$e,toggleWebAnnotationAttachment:et,detachWebAnnotationAttachment:tt,clearSelectedWebAnnotationAttachments:nt,toggleWebAnnotationsPanelCollapsed:rt,clearVisibleWebAnnotations:it}=Qj({selectedPiboSessionId:Oe,onError:he,formatError:zk}),{selectedUploadAttachments:at,attachUploadedFiles:ot,detachUploadAttachment:st,clearSelectedUploadAttachments:ct}=Zj(t,(0,v.useCallback)(()=>`upload-${w()}`,[])),lt=KA({selectedPiboSessionId:Oe,baseTraceView:Fe,liveTraceOverlay:Ie,selectedSessionStatus:c});Gj({selectedPiboSessionId:Oe,tracePageData:ze.data,currentTraceView:lt,liveEventSeqRef:ge,selectedSessionStatus:c,tracePageReady:He,setLiveTraceOverlay:be,onRefreshTrace:P,onRefreshBootstrap:pe,onRuntimeRequestEvent:ke,onError:he});let ut=fM({bootstrap:e,selectedPiboSessionId:t,selectedSessionProfile:o,selectedSessionActiveModel:s,currentTraceView:lt}),dt=(0,v.useMemo)(()=>dM(e.sessions,t),[e.sessions,t]),ft=!!t&&ze.isFetching&&!lt,pt=ze.error?jM(ze.error):Re.error?jM(Re.error):null,mt=T(t,r),ht=!mt&&x.id===`terminal`&&(_??y)===`terminal`,gt=(0,v.useCallback)(async e=>{try{let t=await ue(e);ot(t.files)}catch(e){he(jM(e))}},[ot,he]),_t=lt?.piboSessionId??t??``,vt=d&&qk(d)?Jk(d,c):null,yt=e=>{for(let n of[750,2e3,5e3,1e4])window.setTimeout(()=>{t===e&&ze.refetch().catch(e=>he(jM(e)))},n)},bt=async(e,t)=>{let n=EM(e,t);be(e=>DM(e,n.piboSessionId,n.optimisticEvent)),await me(n.text,n.webAnnotationIds,n.fileAttachmentPaths,n.clientTxnId,t),nt(),ct(),await Promise.all([ze.refetch(),Ze.refetch()]),yt(n.piboSessionId)},xt=(e,t)=>{be(t=>{let n=t?.piboSessionId===e.piboSessionId?t:_e.current.get(e.piboSessionId)??null;if(!n)return t;let r=n.events.filter(t=>t.id!==e.clientTxnId),i=r.length?{...n,events:r}:null;return i?_e.current.set(e.piboSessionId,i):_e.current.delete(e.piboSessionId),t?.piboSessionId===e.piboSessionId?i:t}),M(t=>t||e.text),he(jM(t))},St=async e=>{if(mt||!t)return;let n=TM({piboSessionId:t,text:e,selectedWebAnnotations:Ke,selectedUploadAttachments:at,eventSequence:ge.current++,now:new Date().toISOString(),clientTxnId:w()});if(c===`running`){Se(n);return}try{await bt(n,`queue`)}catch(e){xt(n,e)}},Ct=()=>{xe&&(M(e=>e||xe.text),Se(null))},wt=async e=>{let t=xe;if(!(!t||Ee.current.has(t.clientTxnId))){Ee.current.add(t.clientTxnId),Se(e=>e?.clientTxnId===t.clientTxnId?null:e),he(null);try{await bt(t,e)}catch(e){xt(t,e)}finally{Ee.current.delete(t.clientTxnId)}}},Tt=pM({currentTraceView:lt,isLoading:ft,showThinking:A,expandThinking:ee,selectedSessionProfile:o,sessionActiveModelBadge:ut,sessionRuntimeBinding:e.session?.id===Oe?e.session.runtimeBinding:void 0,selectedSessionStatus:c,selectedSessionSignal:l,signals:u,sessionGoal:je.data?.goal,workflowProjectSession:d,workflowLifecycleEvents:f,sessionNodes:e.sessions,sessionLinks:dt,agentProfiles:e.agents,sessionProfileChangeDisabled:C||r,onSessionAgentProfileChange:oe,onFork:se,onOpenSession:ce,onLoadOlderTracePage:()=>void Ue(lt?.nextBeforeCursor??lt?.nextBeforeSequence),hasOlderTraceEvents:lt?.hasOlderEvents===!0||lt?.nextBeforeCursor!==void 0||typeof lt?.nextBeforeSequence==`number`,isFetchingOlderTracePage:Ve,onThinkingLevelChange:fe,onRefreshTrace:P,onRefreshBootstrap:pe,onError:he});return(0,I.jsxs)(I.Fragment,{children:[xe?(0,I.jsx)(gA,{title:`Session is running`,description:`Choose how this message should be delivered.`,onClose:Ct,initialFocusRef:De,children:(0,I.jsxs)(`div`,{className:`grid gap-2 p-4 sm:grid-cols-2`,"data-pibo-debug":`message-delivery-dialog`,children:[(0,I.jsxs)(`button`,{ref:De,type:`button`,onClick:()=>void wt(`queue`),className:`rounded-sm border border-slate-700 bg-[#151f24] p-3 text-left transition hover:border-[#11a4d4] hover:bg-[#11a4d4]/10 disabled:opacity-50`,"data-pibo-debug":`message-delivery-queue`,children:[(0,I.jsx)(`span`,{className:`block text-xs font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Queue`}),(0,I.jsx)(`span`,{className:`mt-1 block text-xs leading-5 text-slate-400`,children:`Run it as the next turn after the active turn finishes.`})]}),(0,I.jsxs)(`button`,{type:`button`,onClick:()=>void wt(`steer`),className:`rounded-sm border border-amber-500/50 bg-amber-500/5 p-3 text-left transition hover:border-amber-400 hover:bg-amber-500/10 disabled:opacity-50`,"data-pibo-debug":`message-delivery-steer`,children:[(0,I.jsx)(`span`,{className:`block text-xs font-bold uppercase tracking-wider text-amber-400`,children:`Steer`}),(0,I.jsx)(`span`,{className:`mt-1 block text-xs leading-5 text-slate-400`,children:`Add it to the active turn after the current tool finishes, before the next model step.`})]})]})}):null,(0,I.jsx)(fA,{selectedPiboSessionId:t,selectedRoomId:n,fallbackRoomId:e.selectedRoomId??void 0,sessionViewId:y,loadingTrace:ft,roomNavigationPending:i,sessionNavigationPending:a,traceError:pt,showRawEvents:k,currentTraceView:lt,rawEventLimit:Le,tracePageFetching:k?Be.isFetching:ze.isFetching,onLoadMoreRawEvents:We,terminalFullscreen:E,terminalFileDropEnabled:ht,onTerminalFilesDropped:gt,onOpenSessionWindow:Pe,onExitTerminalFullscreen:O??(()=>void 0),headerProps:{title:uM({sessionNodes:e.sessions,selectedPiboSessionId:t,traceTitle:lt?.title,fallback:e.room?.name??n??void 0}),roomLabel:e.room?.name??n??`Room`,headerPiboSessionId:_t,piboSessionId:t,piboRoomId:n??e.selectedRoomId??void 0,webAnnotationsDisabled:!t||r,webAnnotationsPanelRendered:Ye,workflowHeader:vt,sessionViewId:y,sessionViews:b,currentSessionView:x,allowedSessionViewIds:S,extraViewTabs:g,activeViewId:_,terminalFullscreenAvailable:x.id===`terminal`&&(_??y)===`terminal`,onEnterTerminalFullscreen:D,onOpenSessionWindow:Pe,showRawEvents:k,showThinking:A,expandThinking:ee,onShowWebAnnotationsPanel:()=>$e(!0),onHideWebAnnotationsPanel:()=>$e(!1),onSelectSessionView:le,onToggleRawEvents:N,onToggleThinking:ie,onToggleExpandThinking:ae,onError:he},projectSessionCreatePanel:p,workflowStartPanel:m,projectModulePanel:h,currentSessionView:x,sessionViewProps:Tt,webAnnotationsPanelRendered:Ye,webAnnotationsPanelProps:{piboSessionId:t,annotations:qe,selectedIds:Ge,loading:Ze.isLoading||Ze.isFetching||Qe,error:Ze.error?jM(Ze.error):null,collapsed:Je,onRefresh:()=>void Ze.refetch(),onToggle:et,onClear:()=>void it(),onCollapse:rt,onClose:()=>$e(!1)},runtimeRequestPanel:Oe?(0,I.jsx)(RM,{piboSessionId:Oe,approvals:F,userInputs:we,onResolved:Ae,onError:he}):void 0,composerProps:{sessionId:t,disabled:mt,commands:te,skills:ne,value:j,focusSignal:re,selectedWebAnnotations:Ke,selectedUploadAttachments:at,onValueChange:M,onCommand:de,onDetachWebAnnotation:tt,onClearWebAnnotations:nt,onAttachUploadedFiles:ot,onDetachUploadAttachment:st,onClearUploadAttachments:ct,onSend:St}})]})}function GM({mode:e,onSelectSession:t,onNewSession:n,onDeleteSession:r,onRenameSession:i,onSelectRoom:a}){return e.kind===`rooms`?(0,I.jsx)(QM,{candidates:e.candidates,workspace:e.workspace,onSelectRoom:a}):(0,I.jsx)(XM,{sessions:e.sessions,selectedPiboSessionId:e.selectedPiboSessionId,onSelectSession:t,onNewSession:n,onDeleteSession:r,onRenameSession:i})}function KM(e){return e===`running`?`running`:e===`error`?`error`:e===`completed`?`completed`:`idle`}var qM={running:`bg-cyan-400`,idle:`bg-slate-500`,error:`bg-rose-500`,completed:`bg-emerald-500`},JM={running:`running`,idle:`idle`,error:`error`,completed:`completed`};function YM({status:e}){let t=KM(e);return(0,I.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-[10px] uppercase tracking-wider text-slate-400`,children:[(0,I.jsx)(`span`,{className:`inline-block w-1.5 h-1.5 rounded-full ${qM[t]}`,"aria-hidden":`true`}),JM[t]]})}function XM({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,I.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,I.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,I.jsxs)(`ul`,{className:`flex gap-1 overflow-x-auto min-w-0`,children:[o.map(e=>{let r=e.piboSessionId===t;return(0,I.jsx)(`li`,{className:`shrink-0`,children:(0,I.jsx)(ZM,{session:e,isActive:r,onSelect:()=>n(e.piboSessionId),onDelete:()=>void i(e.piboSessionId),onRename:t=>void a(e.piboSessionId,t)})},e.piboSessionId)}),o.length===0&&(0,I.jsx)(`li`,{className:`text-xs text-slate-500 px-2 py-1`,children:`No sessions yet — click + to start one.`})]})]})}function ZM({session:e,isActive:t,onSelect:n,onDelete:r,onRename:i}){let[a,o]=(0,v.useState)(!1);return(0,I.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,I.jsxs)(`button`,{type:`button`,onClick:n,className:`inline-flex items-center gap-2 text-left`,children:[(0,I.jsx)(YM,{status:e.status}),(0,I.jsx)(`span`,{className:`text-xs text-slate-200 max-w-[180px] truncate`,children:e.title||`Untitled`})]}),(0,I.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,I.jsxs)(`div`,{className:`absolute z-10 mt-12 -ml-20 bg-[#0a1418] border border-slate-700 rounded shadow-lg text-xs`,children:[(0,I.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,I.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 QM({candidates:e,workspace:t,onSelectRoom:n}){return(0,I.jsxs)(`div`,{className:`border-b border-slate-800 px-3 py-3 bg-[#0c1820]`,"data-testid":`room-picker`,children:[(0,I.jsxs)(`div`,{className:`text-[10px] uppercase tracking-wider text-slate-400 mb-2`,children:[`Multiple rooms found for `,(0,I.jsx)(`span`,{className:`font-mono text-slate-300`,children:t})]}),(0,I.jsx)(`ul`,{className:`flex flex-col gap-1`,children:e.map(e=>(0,I.jsx)(`li`,{children:(0,I.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,I.jsx)(`div`,{className:`font-semibold text-slate-200 text-sm`,children:e.name}),e.topic&&(0,I.jsx)(`div`,{className:`text-xs text-slate-400 mt-0.5`,children:e.topic}),(0,I.jsxs)(`div`,{className:`text-[10px] text-slate-500 mt-1`,children:[`Created `,$M(e.createdAt),` · Updated `,$M(e.updatedAt)]})]})},e.id))})]})}function $M(e){try{return new Date(e).toLocaleString()}catch{return e}}function eN(){return new URLSearchParams(window.location.search).get(`workspace`)}function tN(){return new URLSearchParams(window.location.search).get(`roomId`)}function nN(){let e=(0,v.useMemo)(()=>eN(),[]),[t,n]=(0,v.useState)(()=>tN()),[r,i]=(0,v.useState)(()=>tN()?{kind:`sessions`,roomId:tN(),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 ee(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(jM(t))}})(),()=>{e=!0}},[t]);let y=(0,v.useCallback)(async()=>{if(t)try{let e=await ee(s??void 0,!1,t,!0);o(e)}catch(e){m(jM(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?O(a.capabilities.actions):[],[a]),C=(0,v.useMemo)(()=>k(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)},[]),D=(0,v.useCallback)(async e=>{if(t)try{let n=await te(e,t);await y(),n.session?.id&&c(n.session.id)}catch(e){m(jM(e))}},[t,y]),A=(0,v.useCallback)(async e=>{try{await j(e,`delete`),await y(),s===e&&c(null)}catch(e){m(jM(e))}},[y,s]),M=(0,v.useCallback)(async(e,t)=>{try{await ne(e,{title:t}),await y()}catch(e){m(jM(e))}},[y]),ie=(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()}`)},[]),ae=(0,v.useCallback)(async e=>{if(!(!s||!t))try{await re(s,e,w(),t),u(``),f(e=>e+1),await y()}catch(e){m(jM(e))}},[s,t,y]),oe=(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=se(n.slice(r.length));if(!e)return m(`Usage: /download <path>`),!0;try{await de(e,{piboSessionId:s,roomId:t??void 0})}catch(e){m(jM(e))}return!0}try{let e=ce(i.action,n.slice(r.length).trim());await N(s,i.action,e),await y()}catch(e){m(jM(e))}return!0},[S,s,t,y]),le=(0,v.useMemo)(()=>QD(),[]),ue=(0,v.useMemo)(()=>$D(he),[]);if(!a)return(0,I.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,I.jsx)(GM,{mode:r,onSelectSession:E,onNewSession:D,onDeleteSession:A,onRenameSession:M,onSelectRoom:ie}),(0,I.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`){let e=a.rooms??r.candidates;return(0,I.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,I.jsx)(GM,{mode:{kind:`rooms`,candidates:e,workspace:r.workspace},onSelectSession:E,onNewSession:D,onDeleteSession:A,onRenameSession:M,onSelectRoom:ie}),(0,I.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 fe=a.sessions.find(e=>e.piboSessionId===s);return(0,I.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,I.jsx)(GM,{mode:{kind:`sessions`,roomId:t??``,sessions:T,selectedPiboSessionId:s},onSelectSession:E,onNewSession:D,onDeleteSession:A,onRenameSession:M,onSelectRoom:ie}),p&&(0,I.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,I.jsx)(`button`,{type:`button`,className:`ml-3 underline`,onClick:()=>m(null),children:`dismiss`})]}),(0,I.jsx)(`div`,{className:`flex-1 min-h-0`,children:(0,I.jsx)(WM,{bootstrap:a,selectedPiboSessionId:s,selectedRoomId:t,selectedRoomArchived:!1,selectedSessionProfile:fe?.profile??`default`,selectedSessionActiveModel:fe?x(a,fe)??void 0:void 0,selectedSessionStatus:fe?.status,sessionViewId:he,sessionViews:le,currentSessionView:ue,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:oe,onThinkingLevelChange:e=>void oe(`/thinking ${e}`),onRefreshTrace:b,onRefreshBootstrap:y,onSend:ae,onError:m})})]})}var rN=document.getElementById(`root`);rN&&(0,y.createRoot)(rN).render((0,I.jsx)(v.StrictMode,{children:(0,I.jsx)(nN,{})}));
|
|
41
|
+
`)&&e.value.length<80){e.style.height=``,e.style.overflowY=`hidden`;return}let t=window.getComputedStyle(e),n=dk(t.lineHeight,20),r=dk(t.borderTopWidth)+dk(t.borderBottomWidth),i=n*5+dk(t.paddingTop)+dk(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 dk(e,t=0){let n=Number.parseFloat(e);return Number.isFinite(n)?n:t}var fk=`pibo.chat.webAnnotations.cdpUrl`,pk=`pibo.chat.webAnnotations.selected`,mk=`${pk}.`,hk=`pibo.chat.webAnnotations.overlay.`,gk=`pibo.chat.webAnnotations.panelCollapsed`,_k=`pibo.chat.shortcuts.webAnnotationsToggle`,vk=`Alt+Shift+A`;function yk(){try{return localStorage.getItem(fk)??``}catch{return``}}function bk(e){try{e.trim()?localStorage.setItem(fk,e.trim()):localStorage.removeItem(fk)}catch{}}function xk(){try{return localStorage.getItem(_k)||`Alt+Shift+A`}catch{return vk}}function Sk(e){try{return wk(localStorage.getItem(Ck(e)))}catch{return null}}function Ck(e){return hk+e}function wk(e){if(!e)return null;try{return Tk(JSON.parse(e))}catch{return null}}function Tk(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 Ek(e){try{let t=Ok(localStorage.getItem(pk));if(t.length||!e)return t;let n=mk+e,r=Ok(localStorage.getItem(n));return r.length&&(localStorage.setItem(pk,JSON.stringify(r)),localStorage.removeItem(n)),r}catch{return[]}}function Dk(e,t){try{let n=[...new Set(t.filter(e=>e.trim()))].slice(0,5);n.length?localStorage.setItem(pk,JSON.stringify(n)):localStorage.removeItem(pk),e&&localStorage.removeItem(mk+e)}catch{}}function Ok(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`&&!!e.trim()).slice(0,5):[]}catch{return[]}}function kk(){try{return localStorage.getItem(gk)===`true`}catch{return!1}}function Ak(e){try{localStorage.setItem(gk,String(e))}catch{}}var jk=`web-annotations-dialog`,Mk=`web-annotations-session-panel-details`;function Nk({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,I.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,I.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,I.jsx)(`div`,{className:`min-w-0`,children:(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,I.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Web annotations`}),(0,I.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,I.jsxs)(`span`,{className:`rounded-sm border border-[#11a4d4]/50 px-1.5 py-0.5 text-[10px] text-[#11a4d4]`,children:[n.length,` attached`]}):null]})}),(0,I.jsxs)(`div`,{className:`ml-auto flex shrink-0 items-center gap-1`,children:[(0,I.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,I.jsx)(mt,{size:12,className:r?`animate-spin`:void 0})}),(0,I.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,I.jsx)(xt,{size:12})}),(0,I.jsx)(`button`,{type:`button`,onClick:l,title:a?`Expand annotations panel`:`Collapse annotations panel`,"aria-label":`Web annotations details`,"aria-expanded":!a,"aria-controls":Mk,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,I.jsx)(Re,{size:12}):(0,I.jsx)(Ie,{size:12})}),(0,I.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,I.jsx)(Tt,{size:12})})]})]}),(0,I.jsxs)(`div`,{id:Mk,hidden:a,children:[(0,I.jsx)(`div`,{className:`text-[11px] text-slate-500`,children:`Global annotation list. Selected attachments follow you when switching sessions.`}),i?(0,I.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:Wk(i,220)}):r&&!t.length?(0,I.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,I.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,t)=>{let r=n.includes(e.id),i=Wk(e.primaryTarget||e.label||e.selector||e.targetKind||`target`,64),a=`${t+1}: ${i}`;return(0,I.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":r?`true`:`false`,className:`min-w-0 rounded-sm border px-3 py-2 text-xs ${r?`border-[#11a4d4] bg-[#11a4d4]/10`:`border-slate-800 bg-[#0e1116]`}`,children:[(0,I.jsxs)(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[(0,I.jsxs)(`span`,{className:`min-w-0 truncate font-mono text-[11px] text-slate-500`,children:[e.status,` · `,e.targetKind]}),(0,I.jsxs)(`button`,{type:`button`,onClick:()=>s(e.id),"aria-pressed":r,"aria-label":`Include web annotation ${a}`,title:`${r?`Detach`:`Attach`} web annotation ${a}`,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 ${r?`border-[#11a4d4] text-[#11a4d4]`:`border-slate-700 text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:[r?(0,I.jsx)(Tt,{size:11}):(0,I.jsx)(pt,{size:11}),` `,r?`Detach`:`Attach`]})]}),(0,I.jsx)(`div`,{className:`truncate text-slate-200`,title:e.primaryTarget||e.label||e.selector||e.id,children:Wk(e.primaryTarget||e.label||e.selector||e.id,120)}),e.piboContext?(0,I.jsx)(`div`,{className:`truncate font-mono text-[11px] text-[#11a4d4]`,title:e.piboContext,children:Wk(e.piboContext,140)}):null,(0,I.jsx)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:e.url,children:Vk(e.url)}),(0,I.jsxs)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:Uk(e),children:[`Source `,Hk(e)]}),(0,I.jsx)(`div`,{className:`mt-1 line-clamp-2 text-slate-400`,title:e.note,children:Wk(e.note,180)}),(0,I.jsx)(`div`,{className:`mt-1 text-[11px] text-slate-600`,children:Gk(e.createdAt)})]},e.id)})}):(0,I.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 Pk({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)(()=>yk()),[p,m]=(0,v.useState)([]),[h,g]=(0,v.useState)(`idle`),[_,y]=(0,v.useState)(!1),[b,x]=(0,v.useState)(null),S=(0,v.useRef)(null),C=(0,v.useRef)(null),w=()=>{c(!1),S.current?.focus()};(0,v.useEffect)(()=>{n&&c(!1)},[n]),(0,v.useEffect)(()=>{if(!s||n)return;C.current?.focus();let e=e=>{e.key===`Escape`&&(e.preventDefault(),w())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[s,n]),(0,v.useEffect)(()=>{bk(d)},[d]);let T=async()=>{if(e){g(`loading`),x(null);try{let e=await $x(d);m(e.targets.filter(e=>e.type===`page`||e.attachable)),g(`loaded`)}catch(e){let t=zk(e,`CDP unavailable`);m([]),g(`error`),x({kind:`error`,message:t}),o(t)}}},E=async n=>{if(!e)throw Error(`No active session context`);return tS(n.binding.id,Ik({piboSessionId:e,piboRoomId:t,cdpUrl:d,annotationShortcut:xk()}))},D=async()=>{if(!(!e||_)){i(),y(!0),x({kind:`info`,message:`Injecting annotation overlay into this Pibo page…`});try{let n=await eS({piboSessionId:e,piboRoomId:t,url:window.location.href,title:document.title,sameOrigin:!0,annotationShortcut:xk()});if(!n.overlay)throw Error(`Overlay config missing from same-origin binding response`);await Rk(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=zk(e,`Current-page annotation failed`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}}},O=async()=>{if(!e||_)return;i();let n=l.trim();if(!n){x({kind:`error`,message:`URL is required`});return}if(Lk(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 eS(Ik({piboSessionId:e,piboRoomId:t,url:n,cdpUrl:d})),i=await E(r);x({kind:`success`,message:`Annotation overlay injected for ${Bk(i.target??r.target,i.binding.url)}`}),u(``),o(null)}catch(e){let t=zk(e,`Annotation failed`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}},k=async n=>{if(!(!e||_)){i(),y(!0),x({kind:`info`,message:`Binding selected target and injecting overlay…`});try{let r=await eS(Ik({piboSessionId:e,piboRoomId:t,targetId:n.id,cdpUrl:d})),i=await E(r);x({kind:`success`,message:`Annotation overlay injected for ${Bk(i.target??n,i.binding.url)}`}),o(null)}catch(e){let t=zk(e,n.attachable?`Target annotation failed`:`Target not attachable`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}}};return(0,I.jsxs)(`div`,{className:`relative`,"data-pibo-debug":`web-annotations-entry`,"data-pibo-session-id":e??void 0,children:[(0,I.jsx)(Fk,{buttonRef:S,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`,ariaHaspopup:`dialog`,ariaExpanded:s,ariaControls:jk,disabled:n,active:s||r,children:(0,I.jsx)(Oe,{size:14})}),s&&!n?(0,I.jsxs)(`div`,{id:jk,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,I.jsxs)(`div`,{className:`mb-2 flex items-start justify-between gap-3`,children:[(0,I.jsxs)(`div`,{children:[(0,I.jsx)(`div`,{className:`text-xs font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Web Annotations`}),(0,I.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,I.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,I.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,I.jsx)(gt,{size:14})}),(0,I.jsx)(`button`,{type:`button`,onClick:w,className:`rounded-sm p-1 text-slate-500 hover:bg-slate-800 hover:text-slate-200`,"aria-label":`Close Web Annotations panel`,children:(0,I.jsx)(Tt,{size:14})})]})]}),(0,I.jsx)(`button`,{ref:C,type:`button`,onClick:()=>void D(),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,I.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,I.jsxs)(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-[1fr_auto]`,children:[(0,I.jsx)(`input`,{id:`web-annotation-url`,value:l,onChange:e=>u(e.target.value),onKeyDown:e=>{e.key===`Enter`&&O()},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,I.jsx)(`button`,{type:`button`,onClick:()=>void O(),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,I.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,I.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,I.jsxs)(`div`,{className:`mt-3 flex items-center justify-between gap-2`,children:[(0,I.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-slate-500`,children:`Existing targets`}),(0,I.jsxs)(`button`,{type:`button`,onClick:()=>void T(),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,I.jsx)(mt,{size:12,className:h===`loading`?`animate-spin`:void 0}),` Refresh`]})]}),(0,I.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,I.jsx)(`div`,{className:`px-3 py-3 text-xs text-slate-500`,children:`Refresh to list reachable browser targets.`}):null,h===`loading`?(0,I.jsx)(`div`,{className:`px-3 py-3 text-xs text-slate-400`,children:`Loading targets…`}):null,h===`loaded`&&!p.length?(0,I.jsx)(`div`,{className:`px-3 py-3 text-xs text-slate-500`,children:`No attachable browser targets found.`}):null,p.map(e=>(0,I.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,I.jsxs)(`div`,{className:`min-w-0`,children:[(0,I.jsx)(`div`,{className:`truncate text-xs text-slate-200`,title:e.title||e.url,children:Wk(e.title||`Untitled target`,120)}),(0,I.jsx)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:e.url,children:Wk(e.url||e.id,160)})]}),(0,I.jsx)(`button`,{type:`button`,onClick:()=>void k(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,I.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 Fk({buttonRef:e,title:t,ariaLabel:n,ariaHaspopup:r,ariaExpanded:i,ariaControls:a,disabled:o,active:s,onClick:c,children:l}){return(0,I.jsx)(`button`,{ref:e,type:`button`,onClick:c,disabled:o,title:t,"aria-label":n,"aria-haspopup":r,"aria-expanded":i,"aria-controls":a,className:`h-8 w-8 inline-flex items-center justify-center border rounded-sm transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${s?`border-[#11a4d4] bg-[#11a4d4]/10 text-[#11a4d4]`:`border-slate-700 text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:l})}function Ik(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e&&e.trim()))}function Lk(e){try{let t=new URL(e);return t.port===`56663`||t.pathname.startsWith(`/json/`)}catch{return!1}}function Rk(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 zk(e,t){let n=Kk(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 Bk(e,t){let n=e?.url||t||e?.title||`target`;return Vk(e?.title||n)}function Vk(e){try{let t=new URL(e);return`${t.host}${t.pathname===`/`?``:t.pathname}`}catch{return Wk(e,80)}}function Hk(e){return e.piboRoomId?`${Wk(e.piboSessionId,24)} · room ${Wk(e.piboRoomId,18)}`:Wk(e.piboSessionId,44)}function Uk(e){return e.piboRoomId?`Session ${e.piboSessionId} in room ${e.piboRoomId}`:`Session ${e.piboSessionId}`}function Wk(e,t){return e.length>t?`${e.slice(0,Math.max(0,t-1))}…`:e}function Gk(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{dateStyle:`short`,timeStyle:`short`})}function Kk(e){return e instanceof Error?e.message:String(e)}function qk(e){return!!e.workflowRunId||e.state===`workflow`||e.workflowId!==`simple-chat`}function Jk(e,t){return{workflowId:e.workflowId,state:Xk(e,t),...e.workflowRunId?{workflowRunId:e.workflowRunId}:{}}}function Yk({summary:e}){return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(`span`,{className:`text-slate-600`,children:`·`}),(0,I.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,I.jsxs)(`span`,{className:Zk(e.state),children:[`state `,e.state]}),e.workflowRunId?(0,I.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 `,Qk(e.workflowRunId)]}):null]})}function Xk(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 Zk(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 Qk(e){return e.length>18?`${e.slice(0,10)}…${e.slice(-6)}`:e}function $k({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,terminalFullscreenAvailable:m,onEnterTerminalFullscreen:h,onOpenSessionWindow:g,showRawEvents:_,showThinking:y,expandThinking:b,onShowWebAnnotationsPanel:x,onHideWebAnnotationsPanel:S,onSelectSessionView:C,onToggleRawEvents:w,onToggleThinking:T,onToggleExpandThinking:E,onError:D}){let[O,k]=(0,v.useState)(null),A=(0,v.useRef)(void 0),ee=O===n,te=p??c,ne=(0,v.useMemo)(()=>d?new Set(d):null,[d]);(0,v.useEffect)(()=>()=>{A.current&&window.clearTimeout(A.current)},[]);let j=()=>{n&&($O(n).catch(()=>void 0),k(n),A.current&&window.clearTimeout(A.current),A.current=window.setTimeout(()=>k(null),900))};return(0,I.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,I.jsxs)(`div`,{className:`min-w-0`,children:[(0,I.jsx)(`h1`,{className:`text-base font-semibold truncate`,children:e}),(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 font-mono text-[11px] text-slate-500`,children:[(0,I.jsx)(`span`,{className:`truncate`,children:t}),n?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(`span`,{className:`text-slate-600`,children:`·`}),(0,I.jsx)(`button`,{type:`button`,onMouseDown:e=>e.preventDefault(),onClick:()=>void j(),title:ee?`Copied Pibo session ID`:`Copy Pibo session ID`,"aria-label":ee?`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] ${ee?`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,I.jsx)(Yk,{summary:s}):null]})]}),(0,I.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,I.jsx)(Pk,{piboSessionId:r,piboRoomId:i,disabled:a,panelVisible:o,onShowPanel:x,onHidePanel:S,onError:D}),g?(0,I.jsx)(`button`,{type:`button`,onClick:g,title:`Open selected session in new window`,"aria-label":`Open selected session in new window`,"data-pibo-debug":`open-session-window`,className:`h-8 w-8 inline-flex items-center justify-center border border-slate-700 rounded-sm text-slate-400 transition-colors hover:border-[#11a4d4] hover:text-[#11a4d4]`,children:(0,I.jsx)(pt,{size:15})}):null,(0,I.jsxs)(`div`,{role:`group`,"aria-label":`Session views`,className:`flex items-center rounded-sm border border-slate-700 bg-[#0e1116] p-0.5`,children:[l.map(e=>{let t=!!(ne&&!ne.has(e.id));return(0,I.jsx)(`button`,{type:`button`,onClick:()=>{t||C(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`,"aria-pressed":te===e.id,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 ${te===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=>{let t=e.active??te===e.id;return(0,I.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`,"aria-pressed":t,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 ${t?`bg-[#11a4d4]/10 text-[#11a4d4]`:`text-slate-400 hover:text-[#11a4d4] disabled:hover:text-slate-600`}`,children:e.label},e.id)})]}),m&&h?(0,I.jsx)(`button`,{type:`button`,onClick:h,title:`Enter Terminal fullscreen`,"aria-label":`Enter Terminal fullscreen`,"data-pibo-debug":`enter-terminal-fullscreen`,className:`h-8 w-8 inline-flex items-center justify-center border border-slate-700 rounded-sm text-slate-400 transition-colors hover:border-[#11a4d4] hover:text-[#11a4d4]`,children:(0,I.jsx)(ut,{size:14})}):null,(0,I.jsx)(eA,{onClick:w,title:_?`Hide Raw Events`:`Show Raw Events`,ariaLabel:`Raw Events`,active:_,children:(0,I.jsx)(je,{size:14})}),(0,I.jsx)(eA,{onClick:T,title:y?`Hide Thinking`:`Show Thinking`,ariaLabel:`Thinking`,active:y,children:y?(0,I.jsx)(Ae,{size:14}):(0,I.jsx)(Xe,{size:14})}),y?(0,I.jsx)(eA,{onClick:E,title:b?`Collapse Thinking`:`Expand Thinking`,ariaLabel:`Thinking expansion`,active:b,children:b?(0,I.jsx)(Ie,{size:14}):(0,I.jsx)(Re,{size:14})}):null]})]})}function eA({title:e,ariaLabel:t,active:n,onClick:r,children:i}){return(0,I.jsx)(`button`,{type:`button`,onClick:r,title:e,"aria-label":t,"aria-pressed":n,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 tA(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&nA(e,n)){e.count+=1,e.createdAt=n.createdAt,e.payload={...aA(e.payload)?e.payload:{},text:`${rA(e.payload)}${rA(n.payload)}`};continue}t.push({...n,count:1})}return t}function nA(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=aA(e.payload)?e.payload:{},r=aA(t.payload)?t.payload:{};return iA(n)===iA(r)}function rA(e){return aA(e)?typeof e.text==`string`?e.text:typeof e.delta==`string`?e.delta:``:``}function iA(e){return e.eventId??e.messageId}function aA(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function oA({traceView:e,eventLimit:t,isFetching:n,visible:r,onLoadOlder:i}){let a=(0,v.useMemo)(()=>r?tA(e?.rawEvents??[]):[],[e?.rawEvents,r]);return r?(0,I.jsxs)(`aside`,{className:`min-h-0 overflow-auto bg-[#0e1116] border-l border-slate-800 max-[980px]:hidden`,children:[(0,I.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,I.jsxs)(`div`,{className:`p-3 flex flex-col gap-2`,children:[e&&a.length>=t?(0,I.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,I.jsxs)(`div`,{className:`border-l-2 border-[#11a4d4] bg-[#151f24] p-2`,children:[(0,I.jsxs)(`div`,{className:`flex items-center justify-between gap-2 text-[#11a4d4] font-mono text-[11px] mb-1`,children:[(0,I.jsx)(`span`,{children:e.type}),e.count>1?(0,I.jsxs)(`span`,{className:`text-slate-500`,children:[`x`,e.count]}):null]}),(0,I.jsx)(bl,{value:e.payload,showControls:!1})]},e.id))]})]}):null}function sA({title:e,onOpenSessionWindow:t,onExit:n}){return(0,I.jsxs)(`div`,{"data-pibo-debug":`terminal-fullscreen-top-bar`,className:`h-7 min-h-7 flex items-center border-b border-slate-600 bg-[#151f24]`,children:[(0,I.jsx)(`div`,{className:`min-w-0 flex-1 truncate text-base font-semibold leading-none`,children:e}),t?(0,I.jsx)(`button`,{type:`button`,onClick:t,title:`Open selected session in new window`,"aria-label":`Open selected session in new window`,"data-pibo-debug":`open-session-window`,className:`h-full w-7 shrink-0 inline-flex items-center justify-center text-slate-400 hover:bg-[#11a4d4]/10 hover:text-[#11a4d4]`,children:(0,I.jsx)(pt,{size:14})}):null,(0,I.jsx)(`button`,{type:`button`,onClick:n,title:`Show normal top bar`,"aria-label":`Exit Terminal fullscreen`,className:`h-full w-7 shrink-0 inline-flex items-center justify-center text-slate-400 hover:bg-[#11a4d4]/10 hover:text-[#11a4d4]`,children:(0,I.jsx)(ft,{size:14})})]})}function cA({enabled:e,onFilesDropped:t,children:n,className:r,...i}){let a=(0,v.useRef)(0),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(0),u=c>0;(0,v.useEffect)(()=>{e||(a.current=0,s(!1))},[e]);let d=()=>{a.current=0,s(!1)},f=t=>uA(t.dataTransfer)?(t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=e&&!u?`copy`:`none`,!0):!1,p=t=>{!f(t)||!e||u||(a.current+=1,s(!0))},m=e=>{f(e)},h=e=>{!f(e)||a.current===0||(a.current=Math.max(0,a.current-1),a.current===0&&s(!1))},g=async n=>{if(!f(n)||(d(),!e||u))return;let r=dA(n.dataTransfer);if(r.length){l(r.length);try{await t(r)}finally{l(0)}}},_=u?`uploading`:o?`drag-active`:`idle`;return(0,I.jsxs)(`main`,{...i,"data-pibo-file-drop-state":_,className:`relative ${r??``}`,onDragEnter:p,onDragOver:m,onDragLeave:h,onDragEnd:d,onDrop:g,children:[n,o||u?(0,I.jsx)(lA,{uploadingFileCount:c}):null]})}function lA({uploadingFileCount:e}){let t=e>0;return(0,I.jsx)(`div`,{"data-pibo-debug":`terminal-file-drop-overlay`,"data-pibo-state":t?`uploading`:`drag-active`,role:`status`,"aria-live":`polite`,className:`pointer-events-none absolute inset-0 z-40 grid place-items-center bg-[#071015]/90 p-6 backdrop-blur-[2px]`,children:(0,I.jsxs)(`div`,{className:`flex max-w-sm flex-col items-center rounded-sm border border-dashed border-[#11a4d4] bg-[#0e1116]/95 px-8 py-7 text-center shadow-2xl shadow-black/50`,children:[t?(0,I.jsx)(ct,{size:36,className:`mb-3 animate-spin text-[#11a4d4]`,"aria-hidden":`true`}):(0,I.jsx)(Ct,{size:36,className:`mb-3 text-[#11a4d4]`,"aria-hidden":`true`}),(0,I.jsx)(`span`,{className:`text-sm font-semibold text-slate-100`,children:t?`Uploading ${e} file${e===1?``:`s`}…`:`Drop files to upload`}),(0,I.jsx)(`span`,{className:`mt-1 text-xs leading-5 text-slate-400`,children:t?`Saving to the Pibo uploads directory`:`Images and other files will be attached to your next message.`})]})})}function uA(e){return Array.from(e.types).includes(`Files`)||Array.from(e.items).some(e=>e.kind===`file`)}function dA(e){return Array.from(e.files)}function fA({selectedPiboSessionId:e,selectedRoomId:t,fallbackRoomId:n,sessionViewId:r,loadingTrace:i,roomNavigationPending:a=!1,sessionNavigationPending:o=!1,traceError:s,showRawEvents:c,currentTraceView:l,rawEventLimit:u,tracePageFetching:d,onLoadMoreRawEvents:f,terminalFullscreen:p,terminalFileDropEnabled:m,onTerminalFilesDropped:h,onOpenSessionWindow:g,onExitTerminalFullscreen:_,headerProps:v,projectSessionCreatePanel:y,workflowStartPanel:b,projectModulePanel:x,currentSessionView:S,sessionViewProps:C,webAnnotationsPanelRendered:w,webAnnotationsPanelProps:T,runtimeRequestPanel:E,composerProps:D}){let O=a||o&&!l||i;return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)(cA,{enabled:m,onFilesDropped:h,"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":a?`room-loading`:o?`session-loading`:i?`loading`:s?`error`:e?`ready`:`empty`,"data-pibo-terminal-fullscreen":p?`true`:`false`,className:`min-h-0 flex flex-col`,children:[p?(0,I.jsx)(sA,{title:v.title,onOpenSessionWindow:g,onExit:_}):(0,I.jsx)($k,{...v}),!p&&y?(0,I.jsx)(`div`,{className:`border-b border-slate-800 bg-[#101d22] px-4 py-3`,children:y}):null,!p&&b?(0,I.jsx)(`div`,{className:`border-b border-slate-800 bg-[#101d22] px-4 py-3`,children:b}):null,!p&&x?x:O?(0,I.jsx)(pA,{label:a?`Loading room`:`Loading session`}):s&&!l?(0,I.jsx)(`div`,{className:`min-h-0 flex-1 p-4 text-sm text-red-200`,children:s}):S.render({...C,terminalFullscreen:p}),!p&&w?(0,I.jsx)(Nk,{...T}):null,E,(0,I.jsx)(tk,{...D})]}),(0,I.jsx)(oA,{traceView:l,eventLimit:u,isFetching:d,visible:c&&!p,onLoadOlder:f})]})}function pA({label:e}){return(0,I.jsx)(`section`,{"data-pibo-debug":`room-navigation-loading`,className:`relative min-w-0 flex-1 overflow-hidden bg-[#0b0b0b] text-[#d4d4d4]`,"aria-live":`polite`,"aria-label":e,children:(0,I.jsx)(`div`,{className:`min-h-0 h-full overflow-hidden font-mono text-[12px] leading-[1.45]`,children:(0,I.jsxs)(`div`,{className:`px-4`,children:[(0,I.jsx)(`div`,{className:`group border-b border-[#141414] py-2`,children:(0,I.jsxs)(`div`,{className:`grid grid-cols-[1.9rem_minmax(0,1fr)] gap-2 leading-[1.45]`,children:[(0,I.jsx)(`span`,{className:`flex items-center text-[#38bdf8]`,children:(0,I.jsx)(`span`,{className:`h-1.5 w-1.5 rounded-full bg-[#38bdf8] animate-pulse`})}),(0,I.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,I.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:e}),(0,I.jsx)(`span`,{className:`h-2 w-24 rounded-sm bg-[#262626] animate-pulse`})]})]})}),[{kind:`tool`,lines:5},{kind:`markdown`,lines:4},{kind:`command`,lines:4},{kind:`tool`,lines:3},{kind:`markdown`,lines:5}].map((e,t)=>(0,I.jsx)(mA,{kind:e.kind,lineCount:e.lines},t))]})})})}function mA({kind:e,lineCount:t}){let n=e===`command`,r=e===`markdown`;return(0,I.jsx)(`div`,{className:`group border-b border-[#141414] py-2 animate-pulse ${n?`bg-[#f59e0b]/5`:``}`,"aria-hidden":`true`,children:Array.from({length:t}).map((e,i)=>(0,I.jsxs)(`div`,{className:`grid grid-cols-[1.9rem_minmax(0,1fr)] gap-2 leading-[1.45]`,children:[(0,I.jsx)(`span`,{className:`flex items-center text-[#737373]`,children:i===0&&!r?(0,I.jsx)(`span`,{className:`h-1.5 w-1.5 rounded-full ${n?`bg-[#f59e0b]`:`bg-[#22c55e]`}`}):i>0&&!r?(0,I.jsx)(`span`,{className:`text-[10px]`,children:`L`}):null}),(0,I.jsx)(`span`,{className:`min-w-0 py-[3px]`,children:i===0?(0,I.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,I.jsx)(`span`,{className:`h-[13px] rounded-sm ${r?`w-56 bg-[#d4d4d4]/45`:n?`w-28 bg-[#f59e0b]/65`:`w-24 bg-[#22c55e]/65`}`}),r?null:(0,I.jsx)(`span`,{className:`h-[13px] w-64 rounded-sm bg-[#262626]`})]}):(0,I.jsx)(`span`,{className:`block h-[10px] rounded-sm bg-[#262626] ${i===t-1?`w-[42%]`:i%2==0?`w-[72%]`:`w-[58%]`}`})})]},i))})}var hA=[`a[href]`,`button:not([disabled])`,`input:not([disabled])`,`select:not([disabled])`,`textarea:not([disabled])`,`[tabindex]:not([tabindex="-1"])`].join(`,`);function gA({title:e,description:t,onClose:n,initialFocusRef:r,children:i,closeLabel:a=`Close dialog`,closeDisabled:o=!1}){let s=(0,v.useId)(),c=(0,v.useId)(),l=(0,v.useRef)(null);return(0,v.useEffect)(()=>{let e=document.activeElement instanceof HTMLElement?document.activeElement:null,t=window.requestAnimationFrame(()=>{(r?.current??l.current?.querySelector(hA)??l.current)?.focus()});return()=>{window.cancelAnimationFrame(t),e?.isConnected&&e.focus()}},[r]),(0,I.jsx)(`div`,{className:`fixed inset-0 z-50 grid place-items-center bg-black/70 p-4`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":s,"aria-describedby":c,onClick:e=>{!o&&e.target===e.currentTarget&&n()},onKeyDown:e=>{if(e.key===`Escape`){e.preventDefault(),o||n();return}if(e.key!==`Tab`)return;let t=Array.from(l.current?.querySelectorAll(hA)??[]);if(t.length===0){e.preventDefault(),l.current?.focus();return}let r=t[0],i=t[t.length-1],a=document.activeElement;t.includes(a)?e.shiftKey&&a===r?(e.preventDefault(),i.focus()):!e.shiftKey&&a===i&&(e.preventDefault(),r.focus()):(e.preventDefault(),(e.shiftKey?i:r).focus())},children:(0,I.jsxs)(`div`,{ref:l,tabIndex:-1,className:`max-h-[calc(100vh-2rem)] w-full max-w-lg overflow-y-auto rounded-sm border border-slate-700 bg-[#1a262b] text-slate-200 shadow-2xl outline-none`,children:[(0,I.jsxs)(`div`,{className:`flex items-start justify-between gap-3 border-b border-slate-800 px-4 py-3`,children:[(0,I.jsxs)(`div`,{children:[(0,I.jsx)(`h2`,{id:s,className:`text-sm font-bold uppercase tracking-wider text-slate-100`,children:e}),(0,I.jsx)(`p`,{id:c,className:`mt-1 text-xs text-slate-400`,children:t})]}),(0,I.jsx)(`button`,{type:`button`,onClick:n,disabled:o,"aria-label":a,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-sm border border-slate-700 text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:cursor-not-allowed disabled:opacity-50`,children:(0,I.jsx)(Tt,{size:14})})]}),i]})})}function _A(e){let t=new Map;if(SA(e.nodes,t),!t.size)return e;let{nodes:n,changed:r}=CA(e.nodes,t);return r?{...e,nodes:n}:e}function vA(e){return e.some(xA)}function yA(e){let t=new Map;return EA(e,e=>{if(e.type!==`user.message`||!e.entryId)return;let n=DA(e),r=t.get(n);r?r.push(e.entryId):t.set(n,[e.entryId])}),t}function bA(e,t){if(!t.size)return;let n=new Map;EA(e,e=>{if(e.type!==`user.message`||!e.entryId)return;let t=DA(e),r=n.get(t)??new Set;r.add(e.entryId),n.set(t,r)});let r=new Map;EA(e,e=>{if(e.type!==`user.message`||e.entryId)return;let i=DA(e),a=t.get(i);if(!a?.length)return;let o=n.get(i)??new Set,s=r.get(i)??0;for(;s<a.length&&o.has(a[s]);)s+=1;let c=a[s];c&&(e.entryId=c,o.add(c),n.set(i,o),r.set(i,s+1))})}function xA(e){let t=e.payload;return!!(t&&typeof t==`object`&&!Array.isArray(t)&&`type`in t&&(t.type===`message_queued`||t.type===`message_steered`)&&`source`in t&&t.source===`user`&&`text`in t&&typeof t.text==`string`)}function SA(e,t){for(let n of e){if(n.type===`user.message`&&!TA(n)&&!wA(n)){let e=DA(n);e&&t.set(e,(t.get(e)??0)+1)}SA(n.children,t)}}function CA(e,t){let n=!1,r=[];for(let i of e){if(TA(i)){let e=DA(i),r=e?t.get(e)??0:0;if(r>0){t.set(e,r-1),n=!0;continue}}let e=CA(i.children,t);n||=e.changed,r.push(e.changed?{...i,children:e.nodes}:i)}return{nodes:n?r:e,changed:n}}function wA(e){return[e.id,e.stableKey].some(e=>e?.startsWith(`event:message_queued:`)||e?.startsWith(`event:message_steered:`))}function TA(e){return e.type===`user.message`?e.source===`event-log`&&(e.id.startsWith(`event:message_queued:`)||e.id.startsWith(`event:message_steered:`))?!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 EA(e,t){for(let n of e)t(n),EA(n.children,t)}function DA(e){return typeof e.output==`string`?e.output:typeof e.summary==`string`?e.summary:``}function OA(e,t,n){return t&&e.set(t.piboSessionId,t),n?e.get(n)??null:null}function kA(e,t,n){t&&t.piboSessionId!==n.piboSessionId&&e.set(t.piboSessionId,t);let r=AA(t?.piboSessionId===n.piboSessionId?t:e.get(n.piboSessionId)??null,n);return r?e.set(n.piboSessionId,r):e.delete(n.piboSessionId),r}function AA(e,t){if(!e||e.piboSessionId!==t.piboSessionId)return e;let n=NA(t),r=jA(t.nodes),i=e.events.filter(e=>{let i=RA(e);if(i&&n.has(i))return!1;if(xA(e)){let t=r.get(e.payload.text)??0;if(t>0)return t===1?r.delete(e.payload.text):r.set(e.payload.text,t-1),!1}return!IA(t,e)});return i.length?{...e,events:i}:null}function jA(e){let t=new Map;for(let n of e){if(n.type===`user.message`&&FA(n)&&!MA(n)){let e=VA(n);e&&t.set(e,(t.get(e)??0)+1)}for(let[e,r]of jA(n.children))t.set(e,(t.get(e)??0)+r)}return t}function MA(e){return[e.id,e.stableKey].some(e=>e?.startsWith(`event:message_queued:`)||e?.startsWith(`event:message_steered:`))}function NA(e){let t=new Set;for(let n of e.rawEvents){let e=RA(n);e&&t.add(e)}return PA(e.nodes,t),t}function PA(e,t){for(let n of e){if(n.type===`user.message`)for(let e of[`message_queued`,`message_steered`]){let r=`event:${e}:`,i=n.id.startsWith(r)?n.id.slice(r.length):void 0;i&&t.add(`${n.piboSessionId}:${e}:${i}`),FA(n)&&n.entryId&&t.add(`${n.piboSessionId}:${e}:${n.entryId}`)}if(n.type===`assistant.message`){let e=zA(n,`assistant:`);e&&(t.add(`${n.piboSessionId}:assistant_delta:${e}`),(FA(n)||n.completedAt!==void 0)&&t.add(`${n.piboSessionId}:assistant_message:${e}`)),FA(n)&&n.eventId&&(t.add(`${n.piboSessionId}:message_started:${n.eventId}`),t.add(`${n.piboSessionId}:message_finished:${n.eventId}`))}if(n.type===`model.reasoning`){let e=zA(n,`reasoning:`);e&&(t.add(`${n.piboSessionId}:thinking_delta:${e}`),FA(n)&&(t.add(`${n.piboSessionId}:thinking_started:${e}`),t.add(`${n.piboSessionId}:thinking_finished:${e}`)))}if(n.toolCallId&&(n.type===`tool.call`||n.type===`tool.result`||n.type===`agent.delegation`)){let e=`tool:${n.toolCallId}`;t.add(`${n.piboSessionId}:tool_call:${e}`);let r=n.completedAt!==void 0||n.type===`tool.result`||n.status===`error`;(n.status===`running`||n.output!==void 0||r)&&t.add(`${n.piboSessionId}:tool_execution_started:${e}`),(n.output!==void 0&&!r||r)&&t.add(`${n.piboSessionId}:tool_execution_updated:${e}`),r&&t.add(`${n.piboSessionId}:tool_execution_finished:${e}`)}PA(n.children,t)}}function FA(e){return e.source===`transcript`||e.source===`product-history`}function IA(e,t){let n=t.payload;if(!n||typeof n!=`object`||Array.isArray(n))return!1;let r=`source`in n?n.source:void 0,i=`text`in n?n.text:void 0;return r!==`service`||typeof i!=`string`||!pC(i)?!1:LA(e,t)}function LA(e,t){let n=t.eventSequence;if(n===void 0||e.firstEventSequence===void 0)return!1;let r=e.lastEventSequence??e.eventCount;return r!==void 0&&n>=e.firstEventSequence&&n<=r}function RA(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(r){if(e.type===`tool_call`||e.type===`tool_execution_started`||e.type===`tool_execution_updated`||e.type===`tool_execution_finished`){let n=`toolCallId`in t&&typeof t.toolCallId==`string`?t.toolCallId:void 0;return n?`${r}:${e.type}:tool:${n}`:void 0}if(n){if(e.type===`assistant_delta`||e.type===`assistant_message`){let i=BA(t,`assistantIndex`)??BA(t,`contentIndex`),a=i===void 0?n:`${n}:assistant:${i}`;return`${r}:${e.type}:${a}`}if(e.type===`thinking_started`||e.type===`thinking_delta`||e.type===`thinking_finished`){let i=BA(t,`thinkingIndex`)??BA(t,`contentIndex`),a=i===void 0?n:`${n}:thinking:${i}`;return`${r}:${e.type}:${a}`}return`${r}:${e.type}:${n}`}}}function zA(e,t){return e.stableKey?.startsWith(t)?e.stableKey.slice(t.length):e.eventId}function BA(e,t){let n=t in e?e[t]:void 0;return typeof n==`number`&&Number.isFinite(n)?n:void 0}function VA(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 HA({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?AA(n,t):null)?.events??[];if(!o.length)return{traceView:t};let s=a?.(),c=Sw(t,o,r??`idle`),l=vA(o);return l&&bA(c.nodes,i),{traceView:l?_A(c):c,liveTraceComputeDurationMs:s!==void 0&&a?a()-s:void 0}}function UA(e,t){for(let n of e)t(n),UA(n.children,t)}function WA(e){return typeof e.output==`string`?e.output:typeof e.summary==`string`?e.summary:``}function GA(e){if(!e)return;let t=0;return UA(e.nodes,e=>{e.type===`assistant.message`&&(t+=WA(e).length)}),t}function KA({selectedPiboSessionId:e,baseTraceView:t,liveTraceOverlay:n,selectedSessionStatus:r}){let i=(0,v.useMemo)(()=>t?_A(t):null,[t]),a=(0,v.useMemo)(()=>i?yA(i.nodes):new Map,[i]),o=(0,v.useMemo)(()=>HA({selectedPiboSessionId:e,reconciledBaseTraceView:i,liveTraceOverlay:n,selectedSessionStatus:r,persistedUserMessageIndexForBaseTrace:a,now:by()?()=>performance.now():void 0}),[n,e,r,i,a]),s=o.traceView;return(0,v.useEffect)(()=>{!e||!s?.piboSessionId||!by()||(ky(s.piboSessionId,{overlayEventCount:n?.piboSessionId===s.piboSessionId?n.events.length:0,traceBaseOutputLength:GA(t),currentOutputLength:GA(s)}),o.liveTraceComputeDurationMs!==void 0&&Ey(s.piboSessionId,o.liveTraceComputeDurationMs))},[t,o.liveTraceComputeDurationMs,s,n,e]),(0,v.useEffect)(()=>{if(!s?.piboSessionId||!Vb())return;let e=n?.piboSessionId===s.piboSessionId?n.events:[];qb({piboSessionId:s.piboSessionId,trigger:`trace-state:render`,baseTraceView:t,currentTraceView:s,overlayEvents:e,selectedSessionStatus:r})},[t,s,n,r]),(0,v.useEffect)(()=>{let e=()=>{if(!s?.piboSessionId||!Vb())return;let e=n?.piboSessionId===s.piboSessionId?n.events:[];qb({piboSessionId:s.piboSessionId,trigger:`trace-state:tab:${document.visibilityState}`,baseTraceView:t,currentTraceView:s,overlayEvents:e,selectedSessionStatus:r})};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[t,s,n,r]),s}var qA=1e4,JA=3e5;function YA(e){return[`chat`,`trace-summary`,e]}function XA(e,t={}){let n=t.pageSize??t.eventLimit??50,r=t.beforeCursor??t.beforeSequence;return[`chat`,`trace-page`,e,t.includeRawEvents?`raw`:`compact`,t.rawEventsLimit??80,n,r===void 0?`tail`:String(r)]}function ZA(e,t){if(e.piboSessionId!==t.piboSessionId)return e;let n=new Set,r=[...t.rawEvents,...e.rawEvents].filter(e=>{let t=e.id||`${e.eventSequence??``}:${e.type}:${e.createdAt}`;return!n.has(t)&&(n.add(t),!0)});return{...e,version:e.version,nodes:cj(t.nodes,e.nodes),rawEvents:r,beforeCursor:t.beforeCursor??e.beforeCursor,firstEventSequence:t.firstEventSequence??e.firstEventSequence,nextBeforeSequence:t.nextBeforeSequence,nextBeforeCursor:t.nextBeforeCursor,hasOlderEvents:t.hasOlderEvents,eventLimit:(e.eventLimit??0)+(t.eventLimit??t.pageSize??0)}}function QA(e,t){return e.piboSessionId===t.piboSessionId?{...t,nodes:$A(e.nodes,t),rawEvents:oj(e.rawEvents,t.rawEvents),beforeCursor:e.beforeCursor,firstEventSequence:e.firstEventSequence??t.firstEventSequence,nextBeforeSequence:e.nextBeforeSequence,nextBeforeCursor:e.nextBeforeCursor,hasOlderEvents:e.hasOlderEvents,eventLimit:e.eventLimit??t.eventLimit}:t}function $A(e,t){let n=ZS([...e]),r=ZS([...t.nodes]),i=new Set(r.map(e=>e.id)),a=tj([...n,...r]),o=rj(r),s=ij(r),c=n.filter(e=>{if(i.has(e.id))return!0;if(e.type===`agent.turn`&&e.source===`event-log`&&e.eventId&&a.has(e.eventId)||nj(e))return!1;let n=e.orderKey?.eventSequence;if(n!==void 0&&t.firstEventSequence!==void 0)return n<t.firstEventSequence;let r=e.orderKey?o.get(e.orderKey.sourceRank):void 0;if(e.orderKey&&r)return GS(e.orderKey,r)<0;if(e.source===`live`||e.orderKey?.streamId!==void 0)return!1;let c=aj(e.startedAt);return c!==void 0&&s!==void 0&&c<s}),l=new Set([...c,...r].map(e=>e.id)),u=new Set(n.filter(e=>!l.has(e.id)).map(e=>e.id));return cj(ej(c,u),ej(r,u))}function ej(e,t){return e.map(e=>e.parentId&&t.has(e.parentId)?{...e,parentId:void 0}:e)}function tj(e){let t=new Set;for(let n of e)(n.source===`transcript`||n.source===`product-history`)&&n.eventId&&t.add(n.eventId);return t}function nj(e){return e.source===`live`||e.orderKey?.streamId!==void 0}function rj(e){let t=new Map;for(let n of e){if(!n.orderKey)continue;let e=t.get(n.orderKey.sourceRank);(!e||GS(n.orderKey,e)<0)&&t.set(n.orderKey.sourceRank,n.orderKey)}return t}function ij(e){let t;for(let n of e){let e=aj(n.startedAt);e!==void 0&&(t=t===void 0?e:Math.min(t,e))}return t}function aj(e){if(!e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function oj(e,t){if(!t.length)return e;let n=t.reduce((e,t)=>t.eventSequence===void 0?e:e===void 0?t.eventSequence:Math.min(e,t.eventSequence),void 0),r=new Map;for(let t of e)n!==void 0&&t.eventSequence!==void 0&&t.eventSequence>=n||r.set(sj(t),t);for(let e of t)r.set(sj(e),e);return[...r.values()]}function sj(e){return e.id||`${e.eventSequence??``}:${e.type}:${e.createdAt}`}function cj(e,t){let n=new Map;for(let t of ZS([...e]))n.set(t.id,{...t,children:[]});for(let e of ZS([...t])){let t=n.get(e.id);n.set(e.id,{...t,...e,children:[]})}return QS([...n.values()])}function lj(e,t=[]){let n=new Map,r=[],i=e.hasOlderEvents??e.cursor.hasOlder,a=i?e.nextBeforeCursor??e.cursor.before:void 0,o=i?e.nextBeforeSequence??uj(e.cursor.before):void 0;for(let t of e.nodes)n.set(t.nodeId,dj(t));for(let t of e.nodes){let e=n.get(t.nodeId);if(!e)continue;let i=t.parentId?n.get(t.parentId):void 0;i?i.children.push(e):r.push(e)}return{piboSessionId:e.piboSessionId,piSessionId:e.piSessionId,title:e.title,version:e.version,latestStreamId:e.latestStreamId,eventCount:e.eventCount,eventLimit:e.pageSize,pageSize:e.pageSize,beforeCursor:e.cursor.before,firstEventSequence:e.firstEventSequence??uj(e.cursor.before),lastEventSequence:e.lastEventSequence??uj(e.cursor.after),nextBeforeSequence:o,nextBeforeCursor:a,hasOlderEvents:i,nodes:r,rawEvents:t}}function uj(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function dj(e){let t=e.preview?.text,n=e.payloadRefs?.input?.preview,r=e.payloadRefs?.output?.preview??e.payloadRefs?.reasoning?.preview??t,i=e.payloadRefs?.error?.preview,a=e.inlinePayloads?.output??e.inlinePayloads?.reasoning;return{id:e.nodeId,parentId:e.parentId,entryId:e.entryId,piboSessionId:e.piboSessionId,eventId:e.eventId,toolCallId:e.toolCallId,runId:e.runId,type:e.type,title:e.title,status:e.status,startedAt:e.startedAt,completedAt:e.completedAt,durationMs:e.durationMs,summary:t,input:e.inlinePayloads?.input??n,output:a??r,error:typeof e.inlinePayloads?.error==`string`?e.inlinePayloads.error:i,payloadRefs:e.payloadRefs,linkedPiboSessionId:e.linkedPiboSessionId,source:e.source,stableKey:e.stableKey,orderKey:e.orderKey,children:[]}}var fj=128;function pj({selectedPiboSessionId:e,showRawEvents:t,liveTraceOverlay:n,liveTraceOverlayCacheRef:r,setLiveTraceOverlay:i}){let a=FO(),[o,s]=(0,v.useState)(50),[c,l]=(0,v.useState)(80),[u,d]=(0,v.useState)(null),f=(0,v.useRef)(new Map),[p,m]=(0,v.useState)(void 0),[h,g]=(0,v.useState)(!1),_=(0,v.useRef)(null),y=(0,v.useRef)(new Set),b=(0,v.useMemo)(()=>e?YA(e):null,[e]),x=(0,v.useMemo)(()=>e?XA(e,{includeRawEvents:!1,rawEventsLimit:0,pageSize:50}):null,[e]),S=YO({queryKey:b??[`chat`,`trace-summary`,`idle`],queryFn:async({signal:t})=>{if(!e||!b)throw Error(`Session is required`);let n=a.getQueryData(b),r=await yx(e,n?.version,{signal:t});if(r.notModified&&n)return n;if(!r.summary)throw Error(`Trace summary response missing payload.`);return r.summary},enabled:!1,staleTime:qA,gcTime:JA,refetchOnWindowFocus:!1,retry:1}),C=YO({queryKey:x??[`chat`,`trace-page`,`idle`,`compact`,c,50,`tail`],queryFn:async({signal:t})=>{if(!e||!x)throw Error(`Session is required`);let n=a.getQueryData(x),r=await bx(e,{limit:50,knownVersion:n?.version,signal:t});if(r.notModified&&n)return n;if(!r.timeline)throw Error(`Trace timeline response missing payload.`);return lj(r.timeline)},enabled:!!e,staleTime:qA,gcTime:JA,refetchOnWindowFocus:!1,retry:1});(0,v.useLayoutEffect)(()=>{let t=x?a.getQueryData(x):void 0;s(50),l(80),m(void 0),g(!1),d(n=>(n&&f.current.set(n.piboSessionId,n),e?f.current.get(e)??(t?.piboSessionId===e?t:null):null)),i(t=>OA(r.current,t,e)),_.current=null,y.current=new Set},[r,a,e,i,x]);let w=YO({queryKey:e?[`chat`,`trace-raw-events`,e,c,p??`tail`]:[`chat`,`trace-raw-events`,`idle`],queryFn:async({signal:t})=>{if(!e)throw Error(`Session is required`);return xx(e,{limit:c,beforeSequence:p,signal:t})},enabled:!!(e&&t),staleTime:qA,gcTime:JA,refetchOnWindowFocus:!1,retry:1});(0,v.useEffect)(()=>{let t=C.data;!t||t.piboSessionId!==e||(by()&&ky(t.piboSessionId,{overlayEventCount:0,traceBaseOutputLength:GA(t),traceBaseUpdated:!0}),(0,v.startTransition)(()=>{d(e=>{let n=e?.piboSessionId===t.piboSessionId?QA(e,t):t;return f.current.set(t.piboSessionId,n),n}),i(e=>kA(r.current,e,t))}))},[r,e,i,C.data]),(0,v.useEffect)(()=>{let t=u;!t||t.piboSessionId!==e||(0,v.startTransition)(()=>{i(e=>kA(r.current,e,t))})},[u,r,e,i]),(0,v.useEffect)(()=>{let t=w.data;!t||t.piboSessionId!==e||(0,v.startTransition)(()=>{d(e=>{if(!e)return e;if(p===void 0)return{...e,rawEvents:t.events};let n=new Set(t.events.map(e=>e.id));return{...e,rawEvents:[...t.events,...e.rawEvents.filter(e=>!n.has(e.id))]}})})},[p,w.data,e]);let T=(0,v.useCallback)(async n=>{if(!e||!n)return;let r=`${e}:${n}`;if(_.current||y.current.has(r))return;_.current=r,g(!0);let i=XA(e,{includeRawEvents:t,rawEventsLimit:c,pageSize:50,beforeCursor:n});try{let t=await a.fetchQuery({queryKey:i,queryFn:async({signal:t})=>{let r=a.getQueryData(i),o=await bx(e,{limit:50,beforeCursor:n,knownVersion:r?.version,signal:t});if(o.notModified&&r)return r;if(!o.timeline)throw Error(`Trace timeline response missing payload.`);return lj(o.timeline)},staleTime:qA,gcTime:JA});(0,v.startTransition)(()=>{d(e=>e?ZA(e,t):t),s(e=>e+(t.pageSize??50))}),mj(y.current,r)}finally{_.current===r&&(_.current=null),g(!1)}},[a,c,e,t]),E=e?u?.piboSessionId===e?u:f.current.get(e)??(C.data?.piboSessionId===e?C.data:null):null,D=e?n?.piboSessionId===e?n:r.current.get(e)??null:null,O=(0,v.useCallback)(()=>{let e=E?.rawEvents[0]?.eventSequence;m(e),l(e=>e+80)},[E?.rawEvents]);return{baseTraceView:E,liveTraceOverlay:D,traceEventLimit:o,rawEventLimit:c,traceSummaryQuery:S,tracePageQuery:C,rawEventsQuery:w,loadingOlderTracePage:h,tracePageReady:!!x,loadOlderTracePage:T,loadMoreRawEvents:O}}function mj(e,t){if(e.add(t),e.size<=fj)return;let n=e.values().next();n.done||e.delete(n.value)}function hj(e){let t=e.currentEvents,n,r,i=()=>(r??=new Set(t.map(Sj)),r),a=e=>{n??=t.slice(),n.push(e),t=n};for(let o of e.streamEvents){let s=vj(o,e.piboSessionId,e.nextSequence,e.now??(()=>new Date().toISOString()));if(!s)continue;if(gj(s)){t=_j(t,s),n=t,r=void 0;continue}let c=Sj(s),l=i();l.has(c)||(l.add(c),a(s))}return t}function gj(e){return e.type===`assistant_message`||e.type===`thinking_finished`||e.type===`tool_execution_finished`}function _j(e,t){return t.type===`assistant_message`?[...xj(e,t,`assistant_delta`),t]:t.type===`thinking_finished`?[...xj(e,t,`thinking_delta`),t]:t.type===`tool_execution_finished`?[...xj(e,t,`tool_execution_updated`),t]:e}function vj(e,t,n,r){if(e.type===`RAW_EVENT`&&Tj(e.event)&&typeof e.event.type==`string`){let i=e.event;return yj(e,t,e.event.type,i,n,r)}if(e.type===`TEXT_MESSAGE_CONTENT`&&typeof e.delta==`string`)return yj(e,t,`assistant_delta`,{type:`assistant_delta`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,...wj(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 yj(e,t,`thinking_delta`,{type:`thinking_delta`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,...wj(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 yj(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 yj(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 yj(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 yj(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 yj(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,traceSource:`live`,eventId:typeof r.eventId==`string`?r.eventId:void 0,type:n,createdAt:bj(e)??a(),payload:r}}function bj(e){if(!(typeof e.createdAt!=`string`||!Number.isFinite(Date.parse(e.createdAt))))return e.createdAt}function xj(e,t,n){let r=Cj(t);return e.filter(e=>e.type!==n||Cj(e)!==r)}function Sj(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 Cj(e){let t=Tj(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 wj(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 Tj(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Ej(e){try{let t=JSON.parse(e.data);if(typeof t.type!=`string`)return;let n=e.lastEventId?US(e.lastEventId):void 0;return{...t,...e.lastEventId?{streamFrameId:e.lastEventId}:{},...n?{streamId:n.streamId,streamFrameIndex:n.frameIndex}:{}}}catch{return}}function Dj(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:kj(n),exact:!1,...r?.liveReplayId===void 0?{}:{liveReplayId:r.liveReplayId}})}function Oj(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 kj(e){return`${e}:999999`}function Aj(e){if(e.type===`RUN_FINISHED`||e.type===`TEXT_MESSAGE_END`)return 300;if(e.type===`RUN_ERROR`)return 0}function jj(e){return e.type===`RUN_STARTED`||e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`||e.type===`TEXT_MESSAGE_END`||e.type===`RUNTIME_APPROVAL_REQUESTED`||e.type===`RUNTIME_APPROVAL_RESOLVED`||e.type===`RUNTIME_USER_INPUT_REQUESTED`||e.type===`RUNTIME_USER_INPUT_RESOLVED`}function Mj(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 Nj(e,t,n){if(n.type===`RUN_STARTED`||n.type===`RUN_FINISHED`||n.type===`RUN_ERROR`){e.delete(t);return}let r=Ij(n);r&&e.get(t)?.delete(r)}function Pj(e,t,n){let r=Fj(n);if(!r)return!1;let i=e.get(t);return i||(i=new Set,e.set(t,i)),!i.has(r)&&(i.add(r),!0)}function Fj(e){if(e.type===`TEXT_MESSAGE_CONTENT`||e.type===`REASONING_MESSAGE_CONTENT`)return`${e.type}:${e.messageId}`}function Ij(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 Lj=500,Rj=1e4,zj=45e3,Bj=15e3,Vj=100,Hj=2;function Uj(e){let t=Math.max(e.eventCount??0,e.lastEventSequence??0);for(let n of e.rawEvents)t=Math.max(t,n.eventSequence??0);return t+1}function Wj(e){if(e.forceReconnect)return!0;let t=e.liveStream;return!t||t.piboSessionId!==e.selectedPiboSessionId||t.readyState===Hj||(e.nowMs??Date.now())-t.lastActivityAt>zj}function Gj({selectedPiboSessionId:e,tracePageData:t,currentTraceView:n,liveEventSeqRef:r,selectedSessionStatus:i,tracePageReady:a,setLiveTraceOverlay:o,onRefreshTrace:s,onRefreshBootstrap:c,onRuntimeRequestEvent:l,onError:u}){let d=(0,v.useRef)(new Map),f=(0,v.useRef)(void 0),p=(0,v.useRef)(void 0),m=(0,v.useRef)(new Map),h=(0,v.useRef)(new Map),g=(0,v.useRef)(null),_=(0,v.useRef)(void 0),y=(0,v.useRef)(0),b=(0,v.useRef)(!1),x=(0,v.useRef)(!1),[S,C]=(0,v.useState)(0);(0,v.useEffect)(()=>{let n=t;!n||n.piboSessionId!==e||(r.current=Math.max(r.current,Uj(n)),n.latestStreamId!==void 0&&Dj(h.current,n.piboSessionId,n.latestStreamId))},[r,e,t]);let w=(0,v.useCallback)(e=>{let t=d.current.get(e);t?.length&&(o(n=>{let i=hj({currentEvents:n?.piboSessionId===e?n.events:[],streamEvents:t,piboSessionId:e,nextSequence:()=>r.current++});return Ty(e,t.length,i.length),{piboSessionId:e,events:i}}),d.current.delete(e))},[]),T=(0,v.useCallback)(()=>{if(!(f.current!==void 0||p.current!==void 0||!e)){if(document.hidden){p.current=setTimeout(()=>{p.current=void 0,w(e)},Vj);return}f.current=requestAnimationFrame(()=>{f.current=void 0,w(e)})}},[w,e]),E=(0,v.useCallback)((t,n,r=!1)=>{Nj(m.current,t,n);let i=r||Pj(m.current,t,n),a=d.current.get(t)??[];a.push(n),d.current.set(t,a),wy(t,n,a.length,i),i||t!==e?w(t):T()},[w,T,e]);(0,v.useEffect)(()=>()=>{f.current!==void 0&&cancelAnimationFrame(f.current),p.current!==void 0&&clearTimeout(p.current),_.current!==void 0&&clearTimeout(_.current)},[]);let D=(0,v.useCallback)((e,t)=>{Oj(h.current,e,t)},[]),O=(0,v.useCallback)((e=0)=>{if(_.current!==void 0){if(e>0)return;clearTimeout(_.current)}_.current=setTimeout(()=>{_.current=void 0,C(e=>e+1)},e)},[]),k=(0,v.useCallback)((t=!1)=>{if(!e)return;w(e),s().catch(e=>u(Kj(e))),c().catch(e=>u(Kj(e)));let n=g.current;if(Wj({selectedPiboSessionId:e,liveStream:n?{piboSessionId:n.piboSessionId,lastActivityAt:n.lastActivityAt,readyState:n.events.readyState}:null,forceReconnect:t})){if(t){if(b.current)return;b.current=!0}O()}},[w,u,c,s,O,e]);(0,v.useEffect)(()=>{if(!e||!a||!n||n.piboSessionId!==e)return;let t=new URLSearchParams({piboSessionId:e});t.set(`mode`,`live`);let r=h.current.get(e),i=r?.cursor??(n.latestStreamId===void 0?void 0:kj(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()}`),d=Date.now();g.current={piboSessionId:e,events:o,openedAt:d,lastActivityAt:d};let f=!1,p,m,v=!1,x=!1,S=(t,n=!1)=>{if(p){if(!n)return;clearTimeout(p)}Oy(e,t),p=setTimeout(()=>{p=void 0,s().catch(e=>u(Kj(e)))},t)},C=()=>{if(v){x=!0;return}v=!0,c().catch(e=>u(Kj(e))).finally(()=>{v=!1,x&&(x=!1,T(250,!0))})},T=(e,t=!1)=>{if(m){if(!t)return;clearTimeout(m)}m=setTimeout(()=>{m=void 0,C()},e)},k=()=>{T(900,!0)};return o.onopen=()=>{y.current=0,b.current=!1,_.current!==void 0&&(clearTimeout(_.current),_.current=void 0),xy(e,o.readyState);let t=g.current;t?.events===o&&(t.lastActivityAt=Date.now())},o.onerror=()=>{if(f)return;Sy(e,o.readyState);let t=g.current;t?.events===o&&(t.lastErrorAt=Date.now());let n=y.current++,r=Math.min(Rj,Lj*2**n);O(r)},o.addEventListener(`pibo`,t=>{if(f)return;let n=Ej(t);if(!n)return;let r=n.piboSessionId||e,i=g.current;if(i?.events===o&&(i.lastActivityAt=Date.now()),D(r,n),Cy(r,n,t.lastEventId,o.readyState),r===e&&n.type===`ready`&&n.liveReplay?.missed&&S(0,!0),Ay(n))return;(n.type===`RUNTIME_APPROVAL_REQUESTED`||n.type===`RUNTIME_APPROVAL_RESOLVED`||n.type===`RUNTIME_USER_INPUT_REQUESTED`||n.type===`RUNTIME_USER_INPUT_RESOLVED`)&&l?.(n);let a=n.type!==`TEXT_MESSAGE_CONTENT`&&n.type!==`REASONING_MESSAGE_CONTENT`;r===e&&Mj(n)&&E(r,n,a);let s=Aj(n);r===e&&s!==void 0?S(s,!0):r===e&&n.type!==`ready`&&n.type!==`RAW_EVENT`&&S(1500,!0),jj(n)&&(n.type===`RUN_FINISHED`||n.type===`RUN_ERROR`||n.type===`TEXT_MESSAGE_END`?k():T(r===e?0:150))}),()=>{f=!0,p&&clearTimeout(p),m&&clearTimeout(m),w(e),g.current?.events===o&&(g.current=null),o.close()}},[n?.piboSessionId,E,w,u,c,s,l,D,O,S,e,a]),(0,v.useEffect)(()=>{n?.piboSessionId&&w(n.piboSessionId)},[n?.piboSessionId,w]),(0,v.useEffect)(()=>{let e=()=>k(),t=()=>k(!0),n=()=>{x.current=!0},r=()=>{if(document.hidden){n();return}x.current=!1,k(!0)},i=e=>{let t=x.current||e.persisted;x.current=!1,k(t)};return window.addEventListener(`focus`,e),window.addEventListener(`online`,t),window.addEventListener(`pagehide`,n),window.addEventListener(`pageshow`,i),document.addEventListener(`visibilitychange`,r),()=>{window.removeEventListener(`focus`,e),window.removeEventListener(`online`,t),window.removeEventListener(`pagehide`,n),window.removeEventListener(`pageshow`,i),document.removeEventListener(`visibilitychange`,r)}},[k]),(0,v.useEffect)(()=>{if(!e||i!==`running`)return;let t=window.setInterval(()=>{w(e);let t=g.current;Wj({selectedPiboSessionId:e,liveStream:t?{piboSessionId:t.piboSessionId,lastActivityAt:t.lastActivityAt,readyState:t.events.readyState}:null})&&(s().catch(e=>u(Kj(e))),O())},Bj);return()=>window.clearInterval(t)},[w,u,s,O,e,i])}function Kj(e){return e instanceof Error?e.message:String(e)}var qj=10;function Jj(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,qj)}:e}function Yj(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 Xj(e,t){return!t||!e[t]?.length?e:{...e,[t]:[]}}function Zj(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=>Jj(r,e,n,t))},[t,e]),detachUploadAttachment:(0,v.useCallback)(t=>{r(n=>Yj(n,e,t))},[e]),clearSelectedUploadAttachments:(0,v.useCallback)(()=>{r(t=>Xj(t,e))},[e])}}function Qj({selectedPiboSessionId:e,onError:t,formatError:n}){let[r,i]=(0,v.useState)([]),[a,o]=(0,v.useState)(!1),[s,c]=(0,v.useState)(()=>e?Sk(e):null),[l,u]=(0,v.useState)(()=>kk()),[d,f]=(0,v.useState)(!1),p=!!(e&&s?.piboSessionId===e&&s.installed),m=!!e&&(a||p),h=YO({queryKey:[`web-annotations`,`app`,e],queryFn:async()=>{if(!e)throw Error(`Session is required`);return Zx(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?Ek(e):[]),c(e?Sk(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(Tk(e.detail)),r=n=>{n.key===Ck(e)&&t(wk(n.newValue))},i=()=>t(Sk(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&&Dk(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&&Dk(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&&Dk(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 Ak(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=>Qx(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,_])}}var $j=new WeakMap;function eM(e,t,n){let r=n.map(e=>tM(e)),i=cM(r),a=i.length?Math.min(...i.map(e=>e.startTime)):Date.now()*1e3,o=i.flatMap(e=>e.endTime?[e.endTime]:[]),s=o.length?Math.max(...o):void 0,c=i.some(e=>e.status===`UNSET`);return{id:e,name:t,status:i.some(e=>e.status===`ERROR`)?`ERROR`:c?`UNSET`:`OK`,spans:r,startedAt:new Date(a/1e3),completedAt:s?new Date(s/1e3):void 0,totalDurationMs:s?(s-a)/1e3:0}}function tM(e){let t=$j.get(e);if(t)return t;let n=sM(e.startedAt)??Date.now()*1e3,r=sM(e.completedAt),i=oM(e.status),a=nM(e.type),o={id:e.id,parentId:e.parentId,name:rM(e),spanType:a,startTime:n,endTime:r,durationUs:e.durationMs===void 0?void 0:e.durationMs*1e3,attributes:iM(e),status:i,statusMessage:e.error,events:e.error?[{name:`exception`,timestamp:r??n,attributes:{message:e.error}}]:[],children:e.children?.map(tM),pibo:{entryId:e.entryId,linkedPiboSessionId:e.linkedPiboSessionId,traceNodeType:e.type,traceOrder:e.orderKey,stableKey:e.stableKey,source:e.source}};return $j.set(e,o),o}function nM(e){switch(e){case`user.message`:return`user.prompt`;case`assistant.message`:return`model.response`;case`model.reasoning`:return`model.reasoning`;case`tool.call`:return`tool.call`;case`tool.result`:return`tool.result`;case`agent.delegation`:return`agent.delegation`;case`agent.async`:return`agent.async`;case`execution.command`:case`execution.compaction`:return`execution.command`;case`yielded.run`:return`yielded.run`;case`agent.turn`:return`agent.run`;case`error`:return`tool.result`}}function rM(e){return e.type===`assistant.message`?`assistant_message`:e.type===`user.message`?`user_prompt`:e.type===`model.reasoning`?`model_reasoning`:e.title||e.type}function iM(e){let t={};if(e.summary&&(t.content=e.summary),e.input!==void 0&&(t.input=e.input,t.args=e.input,t.arguments=e.input),e.output!==void 0&&(t.output=e.output,t.result=e.output),e.error&&(t.error=e.error),e.toolCallId&&(t.tool_call_id=e.toolCallId),e.runId&&(t.run_id=e.runId),(e.type===`tool.call`||e.type===`agent.delegation`)&&(t.tool_name=e.title),e.type===`assistant.message`&&(t.content=e.output??e.summary??``),e.type===`user.message`){t.content=e.output??e.summary??``;let n=aM(e);n&&(t[`message.pending_delivery`]=n)}return e.type===`model.reasoning`&&(t.reasoning=e.output??e.summary??``),e.type===`agent.delegation`&&(t[`delegation.target_agent`]=e.title.replace(/^pibo_subagent_/,``),t[`delegation.query`]=e.summary??e.input,t[`result.status`]=e.status===`done`?`completed`:e.status,t.linked_pibo_session_id=e.linkedPiboSessionId),e.type===`agent.async`&&(t[`async_agent.target_agent`]=e.title,t[`async_agent.started_by`]=lM(e.input)?e.input.startedBy:`pibo_run_start`,t[`async_agent.query`]=lM(e.input)?e.input.arguments:e.input,t[`result.status`]=e.status===`done`?`started`:e.status,t.linked_pibo_session_id=e.linkedPiboSessionId),e.type===`yielded.run`&&(t[`run.notification`]=!0,t[`run.status`]=e.status),t}function aM(e){if(e.type===`user.message`&&e.status===`running`){if(e.id.startsWith(`event:message_steered:`))return`steer`;if(e.id.startsWith(`event:message_queued:`))return`queue`}}function oM(e){return e===`running`?`UNSET`:e===`error`?`ERROR`:`OK`}function sM(e){if(!e)return;let t=new Date(e).getTime();return Number.isFinite(t)?t*1e3:void 0}function cM(e){return e.flatMap(e=>[e,...e.children?cM(e.children):[]])}function lM(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function uM(e){return(e.selectedPiboSessionId?S(e.sessionNodes,e.selectedPiboSessionId):void 0)?.title||e.traceTitle||e.selectedPiboSessionId||e.fallback}function dM(e,t){return t?{sessionBreadcrumbs:gM(e,t),originSession:mM(e,t),derivedSessions:hM(e,t)}:{sessionBreadcrumbs:[],originSession:void 0,derivedSessions:[]}}function fM(e){let t=e.selectedPiboSessionId?S(e.bootstrap.sessions,e.selectedPiboSessionId):void 0,n=bM(e.currentTraceView);return yM(e.selectedSessionActiveModel,e.bootstrap.runtimeStatus?.thinkingLevel??n.level??t?.initialThinkingLevel??_M(e.bootstrap,e.selectedSessionProfile,!!t?.parentId),e.bootstrap.runtimeStatus?.fastMode??n.fast??vM(e.bootstrap,e.selectedSessionProfile,!!t?.parentId)??!1)}function pM(e){return{traceView:e.currentTraceView,selectedTrace:e.currentTraceView?eM(e.currentTraceView.piboSessionId,e.currentTraceView.title,e.currentTraceView.nodes):null,isLoading:e.isLoading,showThinking:e.showThinking,expandThinking:e.expandThinking,sessionAgentProfile:e.selectedSessionProfile,sessionActiveModel:e.sessionActiveModelBadge,sessionRuntimeBinding:e.sessionRuntimeBinding,selectedSessionStatus:e.selectedSessionStatus,selectedSessionSignal:e.selectedSessionSignal,signals:e.signals,sessionGoal:e.sessionGoal,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,onLoadOlderTracePage:e.onLoadOlderTracePage,hasOlderTraceEvents:e.hasOlderTraceEvents,isFetchingOlderTracePage:e.isFetchingOlderTracePage,onThinkingLevelChange:e.onThinkingLevelChange,onModelChanged:async()=>{await e.onRefreshBootstrap(),await e.onRefreshTrace()},onRefreshBootstrap:e.onRefreshBootstrap,onError:e.onError}}function mM(e,t){let n=S(e,t);if(!n?.originId)return;let r=S(e,n.originId);return{piboSessionId:n.originId,label:r?CM(r,0):n.originId}}function hM(e,t){return S(e,t)?.derivedSessions.map(e=>({piboSessionId:e.piboSessionId,label:wM(e),profile:e.profile,status:e.status}))??[]}function gM(e,t){return C(e,t).map((e,t)=>({piboSessionId:e.piboSessionId,label:CM(e,t)}))}function _M(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 vM(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 yM(e,t,n){if(e)return[e,t,n?`fast`:void 0].filter(Boolean).join(` `)}function bM(e){let t={};if(!e)return t;for(let n of xM(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`&&SM(e.level)?e.level:void 0)??t.level,fast:n.title===`fast_mode`?e?.mode===`fast`:t.fast}}return t}function xM(e){return e.flatMap(e=>[e,...xM(e.children)])}function SM(e){return $T.includes(e)}function CM(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 wM(e){return e.subagentName&&e.subagentName!==e.profile?`${e.subagentName} (${e.profile})`:e.title||e.profile||e.subagentName||`Untitled Session`}function TM({piboSessionId:e,text:t,selectedWebAnnotations:n,selectedUploadAttachments:r,eventSequence:i,now:a,clientTxnId:o,delivery:s=`queue`}){let c=n.map(e=>e.id),l=r.map(e=>e.path),u=s===`steer`?`message_steered`:`message_queued`;return{piboSessionId:e,text:t,webAnnotationIds:c,fileAttachmentPaths:l,clientTxnId:o,delivery:s,optimisticEvent:{id:o,piboSessionId:e,eventSequence:i,eventId:o,type:u,createdAt:a,payload:{type:u,piboSessionId:e,eventId:o,clientTxnId:o,delivery:s,...s===`queue`?{queuedMessages:1}:{},text:t,...l.length?{fileAttachmentPaths:l}:{},source:`user`}}}}function EM(e,t){if(e.delivery===t)return e;let n=t===`steer`?`message_steered`:`message_queued`,r={...e.optimisticEvent.payload};return delete r.queuedMessages,{...e,delivery:t,optimisticEvent:{...e.optimisticEvent,type:n,payload:{...r,type:n,delivery:t,...t===`queue`?{queuedMessages:1}:{}}}}}function DM(e,t,n){return{piboSessionId:t,events:[...e?.piboSessionId===t?e.events:[],n]}}var OM=`optimistic-session-`;function kM(e){return e?.startsWith(OM)===!0}function AM(e){return e&&!kM(e)?e:null}function jM(e){return e instanceof Error?e.message:String(e)}var MM=[`(display-mode: standalone)`,`(display-mode: window-controls-overlay)`];function NM(e,t){return MM.some(t=>e(t).matches)?typeof t.userAgentData?.mobile==`boolean`?!t.userAgentData.mobile:!(/Android|iPhone|iPad|iPod|Mobile/i.test(t.userAgent)||/Macintosh/i.test(t.userAgent)&&t.maxTouchPoints>1):!1}function PM(){return typeof window<`u`&&typeof navigator<`u`&&NM(window.matchMedia.bind(window),navigator)}function FM(e,t){return{url:e,name:`pibo-session-${t}`,features:`width=1280,height=900`}}function IM(){let e=FM(window.location.href,crypto.randomUUID());return window.open(e.url,e.name,e.features)}var LM=[{id:`accept`,label:`Approve once`},{id:`acceptForSession`,label:`Approve for session`},{id:`decline`,label:`Decline`},{id:`cancel`,label:`Cancel turn`}];function RM({piboSessionId:e,approvals:t,userInputs:n,onResolved:r,onError:i}){let[a,o]=(0,v.useState)(null);if(t.length===0&&n.length===0)return null;let s=async(t,n)=>{if(!a){o(t),i(null);try{await N(e,`runtime.approval.respond`,{requestId:t,decision:n}),r(t)}catch(e){i(jM(e))}finally{o(null)}}},c=async(t,n)=>{if(!a){o(t),i(null);try{await N(e,`runtime.user_input.respond`,{requestId:t,answers:n}),r(t)}catch(e){i(jM(e))}finally{o(null)}}};return(0,I.jsx)(`section`,{className:`border-t border-slate-800 bg-[#101d22] px-3 py-2 sm:px-4`,"data-pibo-debug":`runtime-request-panel`,"aria-label":`Runtime requests`,children:(0,I.jsxs)(`div`,{className:`mx-auto grid w-full max-w-4xl gap-2`,children:[t.map(e=>(0,I.jsx)(zM,{request:e,busy:a===e.requestId,disabled:a!==null,onDecision:t=>void s(e.requestId,t)},e.requestId)),n.map(e=>(0,I.jsx)(BM,{request:e,busy:a===e.requestId,disabled:a!==null,onSubmit:t=>void c(e.requestId,t)},e.requestId))]})})}function zM({request:e,busy:t,disabled:n,onDecision:r}){let i=e.decisions?.length?e.decisions:LM;return(0,I.jsxs)(`article`,{className:`rounded-sm border border-amber-500/40 bg-amber-500/5`,"data-pibo-debug":`runtime-approval-request`,children:[(0,I.jsxs)(`div`,{className:`flex items-start gap-3 border-b border-amber-500/20 px-3 py-2`,children:[(0,I.jsx)(yt,{size:16,className:`mt-0.5 shrink-0 text-amber-400`,"aria-hidden":`true`}),(0,I.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,I.jsx)(`h3`,{className:`text-xs font-bold uppercase tracking-wider text-amber-300`,children:e.title||`Approval required`}),(0,I.jsx)(`span`,{className:`rounded-sm border border-slate-700 px-1.5 py-0.5 font-mono text-[10px] uppercase text-slate-400`,children:e.requestType})]}),e.detail?(0,I.jsx)(`p`,{className:`mt-1 text-xs leading-5 text-slate-300`,children:e.detail}):null]})]}),e.arguments===void 0?null:(0,I.jsx)(`pre`,{className:`max-h-36 overflow-auto border-b border-slate-800 bg-[#0e1116] px-3 py-2 font-mono text-[11px] leading-5 text-slate-300`,children:UM(e.arguments)}),(0,I.jsx)(`div`,{className:`flex flex-wrap gap-2 px-3 py-2`,children:i.map(e=>(0,I.jsx)(`button`,{type:`button`,onClick:()=>r(e.id),disabled:n,title:e.description,className:HM(e.id),"data-pibo-decision":e.id,children:t?`Responding…`:e.label},e.id))})]})}function BM({request:e,busy:t,disabled:n,onSubmit:r}){let[i,a]=(0,v.useState)({}),o=(0,v.useMemo)(()=>e.questions.every(e=>!!i[e.id]?.trim()),[i,e.questions]);return(0,I.jsxs)(`article`,{className:`rounded-sm border border-cyan-500/40 bg-cyan-500/5`,"data-pibo-debug":`runtime-user-input-request`,children:[(0,I.jsxs)(`div`,{className:`flex items-start gap-3 border-b border-cyan-500/20 px-3 py-2`,children:[(0,I.jsx)(He,{size:16,className:`mt-0.5 shrink-0 text-cyan-400`,"aria-hidden":`true`}),(0,I.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,I.jsx)(`h3`,{className:`text-xs font-bold uppercase tracking-wider text-cyan-300`,children:`Input requested`}),(0,I.jsx)(`span`,{className:`rounded-sm border border-slate-700 px-1.5 py-0.5 font-mono text-[10px] uppercase text-slate-400`,children:e.blocking===!1?`non-blocking`:`blocking`})]}),(0,I.jsx)(`p`,{className:`mt-1 text-xs leading-5 text-slate-400`,children:`Codex is waiting for structured input before continuing this turn.`})]})]}),(0,I.jsx)(`div`,{className:`grid gap-3 px-3 py-3`,children:e.questions.map(t=>(0,I.jsx)(VM,{question:t,groupName:`runtime-question-${e.requestId}-${t.id}`,value:i[t.id]??``,disabled:n,onChange:e=>a(n=>({...n,[t.id]:e}))},t.id))}),(0,I.jsx)(`div`,{className:`flex justify-end border-t border-cyan-500/20 px-3 py-2`,children:(0,I.jsx)(`button`,{type:`button`,onClick:()=>r(i),disabled:n||!o,className:`rounded-sm border border-[#11a4d4] bg-[#11a4d4] px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-[#0d8eb8] disabled:cursor-not-allowed disabled:opacity-50`,children:t?`Submitting…`:`Submit response`})})]})}function VM({question:e,groupName:t,value:n,disabled:r,onChange:i}){let a=e.options??[],o=new Set(a.map(e=>e.label)),s=!!n&&!o.has(n);return(0,I.jsxs)(`fieldset`,{className:`grid gap-2`,disabled:r,children:[(0,I.jsxs)(`legend`,{className:`text-xs font-semibold text-slate-200`,children:[e.header?(0,I.jsx)(`span`,{className:`mr-2 font-mono uppercase text-cyan-400`,children:e.header}):null,e.question]}),a.length?(0,I.jsxs)(`div`,{className:`grid gap-1.5 sm:grid-cols-2`,children:[a.map(e=>(0,I.jsxs)(`label`,{className:`flex cursor-pointer gap-2 rounded-sm border border-slate-700 bg-[#151f24] px-2.5 py-2 text-xs hover:border-cyan-500/60`,children:[(0,I.jsx)(`input`,{type:`radio`,name:t,value:e.label,checked:n===e.label,onChange:()=>i(e.label),className:`mt-0.5 accent-[#11a4d4]`}),(0,I.jsxs)(`span`,{children:[(0,I.jsx)(`span`,{className:`block font-semibold text-slate-200`,children:e.label}),e.description?(0,I.jsx)(`span`,{className:`mt-0.5 block leading-4 text-slate-400`,children:e.description}):null]})]},e.label)),e.allowFreeform?(0,I.jsxs)(`label`,{className:`flex cursor-pointer gap-2 rounded-sm border border-slate-700 bg-[#151f24] px-2.5 py-2 text-xs hover:border-cyan-500/60`,children:[(0,I.jsx)(`input`,{type:`radio`,name:t,checked:s,onChange:()=>i(`Other`),className:`mt-0.5 accent-[#11a4d4]`}),(0,I.jsx)(`span`,{className:`font-semibold text-slate-200`,children:`Other`})]}):null]}):null,a.length===0||e.allowFreeform&&s?(0,I.jsx)(`input`,{type:e.secret?`password`:`text`,value:s&&n===`Other`?``:n,onChange:e=>i(e.target.value),autoComplete:`off`,placeholder:e.secret?`Enter a private response`:`Enter a response`,className:`w-full rounded-sm border border-slate-700 bg-[#0e1116] px-2.5 py-2 font-mono text-xs text-slate-200 outline-none focus:border-[#11a4d4] focus:ring-1 focus:ring-[#11a4d4]/40`}):null]})}function HM(e){let t=`rounded-sm border px-2.5 py-1.5 text-xs font-semibold transition disabled:cursor-not-allowed disabled:opacity-50`;return e===`accept`?`${t} border-emerald-500/60 bg-emerald-500/10 text-emerald-300 hover:bg-emerald-500/20`:e===`acceptForSession`?`${t} border-cyan-500/60 bg-cyan-500/10 text-cyan-300 hover:bg-cyan-500/20`:e===`cancel`?`${t} border-red-500/60 bg-red-500/10 text-red-300 hover:bg-red-500/20`:`${t} border-slate-600 bg-slate-800/60 text-slate-300 hover:border-slate-500`}function UM(e){if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return`[unavailable]`}}function WM({bootstrap:e,selectedPiboSessionId:t,selectedRoomId:n,selectedRoomArchived:r,roomNavigationPending:i,sessionNavigationPending:a,selectedSessionProfile:o,selectedSessionActiveModel:s,selectedSessionStatus:c,selectedSessionSignal:l,signals:u,workflowProjectSession:d,workflowLifecycleEvents:f,projectSessionCreatePanel:p,workflowStartPanel:m,projectModulePanel:h,extraViewTabs:g,activeViewId:_,sessionViewId:y,sessionViews:b,currentSessionView:x,allowedSessionViewIds:S,creatingSession:C,terminalFullscreen:E=!1,onEnterTerminalFullscreen:D,onExitTerminalFullscreen:O,showRawEvents:k,showThinking:A,expandThinking:ee,commands:te,skills:ne,composerText:j,composerFocusSignal:re,onComposerTextChange:M,onToggleRawEvents:N,onToggleThinking:ie,onToggleExpandThinking:ae,onSessionAgentProfileChange:oe,onFork:se,onOpenSession:ce,onSelectSessionView:le,onCommand:de,onThinkingLevelChange:fe,onRefreshTrace:P,onRefreshBootstrap:pe,onSend:me,onError:he}){let ge=(0,v.useRef)(0),_e=(0,v.useRef)(new Map),[ve,ye]=(0,v.useState)(null),be=(0,v.useCallback)(e=>{ye(t=>{let n=typeof e==`function`?e(t):e;return n&&_e.current.set(n.piboSessionId,n),n})},[]),[xe,Se]=(0,v.useState)(null),[F,Ce]=(0,v.useState)([]),[we,Te]=(0,v.useState)([]),Ee=(0,v.useRef)(new Set),De=(0,v.useRef)(null),Oe=AM(t);(0,v.useEffect)(()=>{let t=e.runtimeStatus?.piboSessionId===Oe?e.runtimeStatus:void 0;Ce(t?.pendingApprovals?[...t.pendingApprovals]:[]),Te(t?.pendingUserInputs?[...t.pendingUserInputs]:[])},[e.runtimeStatus,Oe]);let ke=(0,v.useCallback)(e=>{if(e.type===`RUNTIME_APPROVAL_REQUESTED`){Ce(t=>[...t.filter(t=>t.requestId!==e.request.requestId),e.request]);return}if(e.type===`RUNTIME_USER_INPUT_REQUESTED`){Te(t=>[...t.filter(t=>t.requestId!==e.request.requestId),e.request]);return}Ce(t=>t.filter(t=>t.requestId!==e.requestId)),Te(t=>t.filter(t=>t.requestId!==e.requestId))},[]),Ae=(0,v.useCallback)(e=>{Ce(t=>t.filter(t=>t.requestId!==e)),Te(t=>t.filter(t=>t.requestId!==e))},[]),je=YO({queryKey:Oe?[`chat`,`session-goal`,Oe]:[`chat`,`session-goal`,`idle`],queryFn:({signal:e})=>Xx(Oe,{signal:e}),enabled:!!Oe,refetchInterval:Oe?5e3:!1}),Me=!!Oe&&PM(),Ne=(0,v.useCallback)(()=>{IM()||he(`The browser blocked the new Pibo window.`)},[he]),Pe=Me?Ne:void 0,{baseTraceView:Fe,liveTraceOverlay:Ie,rawEventLimit:Le,traceSummaryQuery:Re,tracePageQuery:ze,rawEventsQuery:Be,loadingOlderTracePage:Ve,tracePageReady:He,loadOlderTracePage:Ue,loadMoreRawEvents:We}=pj({selectedPiboSessionId:Oe,showRawEvents:k,liveTraceOverlay:ve,liveTraceOverlayCacheRef:_e,setLiveTraceOverlay:be}),{selectedWebAnnotationIds:Ge,selectedWebAnnotations:Ke,visibleWebAnnotations:qe,webAnnotationsPanelCollapsed:Je,webAnnotationsPanelRendered:Ye,webAnnotationsPanelVisible:Xe,webAnnotationsQuery:Ze,clearingWebAnnotations:Qe,setWebAnnotationsPanelVisible:$e,toggleWebAnnotationAttachment:et,detachWebAnnotationAttachment:tt,clearSelectedWebAnnotationAttachments:nt,toggleWebAnnotationsPanelCollapsed:rt,clearVisibleWebAnnotations:it}=Qj({selectedPiboSessionId:Oe,onError:he,formatError:zk}),{selectedUploadAttachments:at,attachUploadedFiles:ot,detachUploadAttachment:st,clearSelectedUploadAttachments:ct}=Zj(t,(0,v.useCallback)(()=>`upload-${w()}`,[])),lt=KA({selectedPiboSessionId:Oe,baseTraceView:Fe,liveTraceOverlay:Ie,selectedSessionStatus:c});Gj({selectedPiboSessionId:Oe,tracePageData:ze.data,currentTraceView:lt,liveEventSeqRef:ge,selectedSessionStatus:c,tracePageReady:He,setLiveTraceOverlay:be,onRefreshTrace:P,onRefreshBootstrap:pe,onRuntimeRequestEvent:ke,onError:he});let ut=fM({bootstrap:e,selectedPiboSessionId:t,selectedSessionProfile:o,selectedSessionActiveModel:s,currentTraceView:lt}),dt=(0,v.useMemo)(()=>dM(e.sessions,t),[e.sessions,t]),ft=!!t&&ze.isFetching&&!lt,pt=ze.error?jM(ze.error):Re.error?jM(Re.error):null,mt=T(t,r),ht=!mt&&x.id===`terminal`&&(_??y)===`terminal`,gt=(0,v.useCallback)(async e=>{try{let t=await ue(e);ot(t.files)}catch(e){he(jM(e))}},[ot,he]),_t=lt?.piboSessionId??t??``,vt=d&&qk(d)?Jk(d,c):null,yt=e=>{for(let n of[750,2e3,5e3,1e4])window.setTimeout(()=>{t===e&&ze.refetch().catch(e=>he(jM(e)))},n)},bt=async(e,t)=>{let n=EM(e,t);be(e=>DM(e,n.piboSessionId,n.optimisticEvent)),await me(n.text,n.webAnnotationIds,n.fileAttachmentPaths,n.clientTxnId,t),nt(),ct(),await Promise.all([ze.refetch(),Ze.refetch()]),yt(n.piboSessionId)},xt=(e,t)=>{be(t=>{let n=t?.piboSessionId===e.piboSessionId?t:_e.current.get(e.piboSessionId)??null;if(!n)return t;let r=n.events.filter(t=>t.id!==e.clientTxnId),i=r.length?{...n,events:r}:null;return i?_e.current.set(e.piboSessionId,i):_e.current.delete(e.piboSessionId),t?.piboSessionId===e.piboSessionId?i:t}),M(t=>t||e.text),he(jM(t))},St=async e=>{if(mt||!t)return;let n=TM({piboSessionId:t,text:e,selectedWebAnnotations:Ke,selectedUploadAttachments:at,eventSequence:ge.current++,now:new Date().toISOString(),clientTxnId:w()});if(c===`running`){Se(n);return}try{await bt(n,`queue`)}catch(e){xt(n,e)}},Ct=()=>{xe&&(M(e=>e||xe.text),Se(null))},wt=async e=>{let t=xe;if(!(!t||Ee.current.has(t.clientTxnId))){Ee.current.add(t.clientTxnId),Se(e=>e?.clientTxnId===t.clientTxnId?null:e),he(null);try{await bt(t,e)}catch(e){xt(t,e)}finally{Ee.current.delete(t.clientTxnId)}}},Tt=pM({currentTraceView:lt,isLoading:ft,showThinking:A,expandThinking:ee,selectedSessionProfile:o,sessionActiveModelBadge:ut,sessionRuntimeBinding:e.session?.id===Oe?e.session.runtimeBinding:void 0,selectedSessionStatus:c,selectedSessionSignal:l,signals:u,sessionGoal:je.data?.goal,workflowProjectSession:d,workflowLifecycleEvents:f,sessionNodes:e.sessions,sessionLinks:dt,agentProfiles:e.agents,sessionProfileChangeDisabled:C||r,onSessionAgentProfileChange:oe,onFork:se,onOpenSession:ce,onLoadOlderTracePage:()=>void Ue(lt?.nextBeforeCursor??lt?.nextBeforeSequence),hasOlderTraceEvents:lt?.hasOlderEvents===!0||lt?.nextBeforeCursor!==void 0||typeof lt?.nextBeforeSequence==`number`,isFetchingOlderTracePage:Ve,onThinkingLevelChange:fe,onRefreshTrace:P,onRefreshBootstrap:pe,onError:he});return(0,I.jsxs)(I.Fragment,{children:[xe?(0,I.jsx)(gA,{title:`Session is running`,description:`Choose how this message should be delivered.`,onClose:Ct,initialFocusRef:De,children:(0,I.jsxs)(`div`,{className:`grid gap-2 p-4 sm:grid-cols-2`,"data-pibo-debug":`message-delivery-dialog`,children:[(0,I.jsxs)(`button`,{ref:De,type:`button`,onClick:()=>void wt(`queue`),className:`rounded-sm border border-slate-700 bg-[#151f24] p-3 text-left transition hover:border-[#11a4d4] hover:bg-[#11a4d4]/10 disabled:opacity-50`,"data-pibo-debug":`message-delivery-queue`,children:[(0,I.jsx)(`span`,{className:`block text-xs font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Queue`}),(0,I.jsx)(`span`,{className:`mt-1 block text-xs leading-5 text-slate-400`,children:`Run it as the next turn after the active turn finishes.`})]}),(0,I.jsxs)(`button`,{type:`button`,onClick:()=>void wt(`steer`),className:`rounded-sm border border-amber-500/50 bg-amber-500/5 p-3 text-left transition hover:border-amber-400 hover:bg-amber-500/10 disabled:opacity-50`,"data-pibo-debug":`message-delivery-steer`,children:[(0,I.jsx)(`span`,{className:`block text-xs font-bold uppercase tracking-wider text-amber-400`,children:`Steer`}),(0,I.jsx)(`span`,{className:`mt-1 block text-xs leading-5 text-slate-400`,children:`Add it to the active turn after the current tool finishes, before the next model step.`})]})]})}):null,(0,I.jsx)(fA,{selectedPiboSessionId:t,selectedRoomId:n,fallbackRoomId:e.selectedRoomId??void 0,sessionViewId:y,loadingTrace:ft,roomNavigationPending:i,sessionNavigationPending:a,traceError:pt,showRawEvents:k,currentTraceView:lt,rawEventLimit:Le,tracePageFetching:k?Be.isFetching:ze.isFetching,onLoadMoreRawEvents:We,terminalFullscreen:E,terminalFileDropEnabled:ht,onTerminalFilesDropped:gt,onOpenSessionWindow:Pe,onExitTerminalFullscreen:O??(()=>void 0),headerProps:{title:uM({sessionNodes:e.sessions,selectedPiboSessionId:t,traceTitle:lt?.title,fallback:e.room?.name??n??void 0}),roomLabel:e.room?.name??n??`Room`,headerPiboSessionId:_t,piboSessionId:t,piboRoomId:n??e.selectedRoomId??void 0,webAnnotationsDisabled:!t||r,webAnnotationsPanelRendered:Ye,workflowHeader:vt,sessionViewId:y,sessionViews:b,currentSessionView:x,allowedSessionViewIds:S,extraViewTabs:g,activeViewId:_,terminalFullscreenAvailable:x.id===`terminal`&&(_??y)===`terminal`,onEnterTerminalFullscreen:D,onOpenSessionWindow:Pe,showRawEvents:k,showThinking:A,expandThinking:ee,onShowWebAnnotationsPanel:()=>$e(!0),onHideWebAnnotationsPanel:()=>$e(!1),onSelectSessionView:le,onToggleRawEvents:N,onToggleThinking:ie,onToggleExpandThinking:ae,onError:he},projectSessionCreatePanel:p,workflowStartPanel:m,projectModulePanel:h,currentSessionView:x,sessionViewProps:Tt,webAnnotationsPanelRendered:Ye,webAnnotationsPanelProps:{piboSessionId:t,annotations:qe,selectedIds:Ge,loading:Ze.isLoading||Ze.isFetching||Qe,error:Ze.error?jM(Ze.error):null,collapsed:Je,onRefresh:()=>void Ze.refetch(),onToggle:et,onClear:()=>void it(),onCollapse:rt,onClose:()=>$e(!1)},runtimeRequestPanel:Oe?(0,I.jsx)(RM,{piboSessionId:Oe,approvals:F,userInputs:we,onResolved:Ae,onError:he}):void 0,composerProps:{sessionId:t,disabled:mt,commands:te,skills:ne,value:j,focusSignal:re,selectedWebAnnotations:Ke,selectedUploadAttachments:at,onValueChange:M,onCommand:de,onDetachWebAnnotation:tt,onClearWebAnnotations:nt,onAttachUploadedFiles:ot,onDetachUploadAttachment:st,onClearUploadAttachments:ct,onSend:St}})]})}function GM({mode:e,onSelectSession:t,onNewSession:n,onDeleteSession:r,onRenameSession:i,onSelectRoom:a}){return e.kind===`rooms`?(0,I.jsx)(QM,{candidates:e.candidates,workspace:e.workspace,onSelectRoom:a}):(0,I.jsx)(XM,{sessions:e.sessions,selectedPiboSessionId:e.selectedPiboSessionId,onSelectSession:t,onNewSession:n,onDeleteSession:r,onRenameSession:i})}function KM(e){return e===`running`?`running`:e===`error`?`error`:e===`completed`?`completed`:`idle`}var qM={running:`bg-cyan-400`,idle:`bg-slate-500`,error:`bg-rose-500`,completed:`bg-emerald-500`},JM={running:`running`,idle:`idle`,error:`error`,completed:`completed`};function YM({status:e}){let t=KM(e);return(0,I.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-[10px] uppercase tracking-wider text-slate-400`,children:[(0,I.jsx)(`span`,{className:`inline-block w-1.5 h-1.5 rounded-full ${qM[t]}`,"aria-hidden":`true`}),JM[t]]})}function XM({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,I.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,I.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,I.jsxs)(`ul`,{className:`flex gap-1 overflow-x-auto min-w-0`,children:[o.map(e=>{let r=e.piboSessionId===t;return(0,I.jsx)(`li`,{className:`shrink-0`,children:(0,I.jsx)(ZM,{session:e,isActive:r,onSelect:()=>n(e.piboSessionId),onDelete:()=>void i(e.piboSessionId),onRename:t=>void a(e.piboSessionId,t)})},e.piboSessionId)}),o.length===0&&(0,I.jsx)(`li`,{className:`text-xs text-slate-500 px-2 py-1`,children:`No sessions yet — click + to start one.`})]})]})}function ZM({session:e,isActive:t,onSelect:n,onDelete:r,onRename:i}){let[a,o]=(0,v.useState)(!1);return(0,I.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,I.jsxs)(`button`,{type:`button`,onClick:n,className:`inline-flex items-center gap-2 text-left`,children:[(0,I.jsx)(YM,{status:e.status}),(0,I.jsx)(`span`,{className:`text-xs text-slate-200 max-w-[180px] truncate`,children:e.title||`Untitled`})]}),(0,I.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,I.jsxs)(`div`,{className:`absolute z-10 mt-12 -ml-20 bg-[#0a1418] border border-slate-700 rounded shadow-lg text-xs`,children:[(0,I.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,I.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 QM({candidates:e,workspace:t,onSelectRoom:n}){return(0,I.jsxs)(`div`,{className:`border-b border-slate-800 px-3 py-3 bg-[#0c1820]`,"data-testid":`room-picker`,children:[(0,I.jsxs)(`div`,{className:`text-[10px] uppercase tracking-wider text-slate-400 mb-2`,children:[`Multiple rooms found for `,(0,I.jsx)(`span`,{className:`font-mono text-slate-300`,children:t})]}),(0,I.jsx)(`ul`,{className:`flex flex-col gap-1`,children:e.map(e=>(0,I.jsx)(`li`,{children:(0,I.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,I.jsx)(`div`,{className:`font-semibold text-slate-200 text-sm`,children:e.name}),e.topic&&(0,I.jsx)(`div`,{className:`text-xs text-slate-400 mt-0.5`,children:e.topic}),(0,I.jsxs)(`div`,{className:`text-[10px] text-slate-500 mt-1`,children:[`Created `,$M(e.createdAt),` · Updated `,$M(e.updatedAt)]})]})},e.id))})]})}function $M(e){try{return new Date(e).toLocaleString()}catch{return e}}function eN(){return new URLSearchParams(window.location.search).get(`workspace`)}function tN(){return new URLSearchParams(window.location.search).get(`roomId`)}function nN(){let e=(0,v.useMemo)(()=>eN(),[]),[t,n]=(0,v.useState)(()=>tN()),[r,i]=(0,v.useState)(()=>tN()?{kind:`sessions`,roomId:tN(),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 ee(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(jM(t))}})(),()=>{e=!0}},[t]);let y=(0,v.useCallback)(async()=>{if(t)try{let e=await ee(s??void 0,!1,t,!0);o(e)}catch(e){m(jM(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?O(a.capabilities.actions):[],[a]),C=(0,v.useMemo)(()=>k(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)},[]),D=(0,v.useCallback)(async e=>{if(t)try{let n=await te(e,t);await y(),n.session?.id&&c(n.session.id)}catch(e){m(jM(e))}},[t,y]),A=(0,v.useCallback)(async e=>{try{await j(e,`delete`),await y(),s===e&&c(null)}catch(e){m(jM(e))}},[y,s]),M=(0,v.useCallback)(async(e,t)=>{try{await ne(e,{title:t}),await y()}catch(e){m(jM(e))}},[y]),ie=(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()}`)},[]),ae=(0,v.useCallback)(async e=>{if(!(!s||!t))try{await re(s,e,w(),t),u(``),f(e=>e+1),await y()}catch(e){m(jM(e))}},[s,t,y]),oe=(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=se(n.slice(r.length));if(!e)return m(`Usage: /download <path>`),!0;try{await de(e,{piboSessionId:s,roomId:t??void 0})}catch(e){m(jM(e))}return!0}try{let e=ce(i.action,n.slice(r.length).trim());await N(s,i.action,e),await y()}catch(e){m(jM(e))}return!0},[S,s,t,y]),le=(0,v.useMemo)(()=>QD(),[]),ue=(0,v.useMemo)(()=>$D(he),[]);if(!a)return(0,I.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,I.jsx)(GM,{mode:r,onSelectSession:E,onNewSession:D,onDeleteSession:A,onRenameSession:M,onSelectRoom:ie}),(0,I.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`){let e=a.rooms??r.candidates;return(0,I.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,I.jsx)(GM,{mode:{kind:`rooms`,candidates:e,workspace:r.workspace},onSelectSession:E,onNewSession:D,onDeleteSession:A,onRenameSession:M,onSelectRoom:ie}),(0,I.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 fe=a.sessions.find(e=>e.piboSessionId===s);return(0,I.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,I.jsx)(GM,{mode:{kind:`sessions`,roomId:t??``,sessions:T,selectedPiboSessionId:s},onSelectSession:E,onNewSession:D,onDeleteSession:A,onRenameSession:M,onSelectRoom:ie}),p&&(0,I.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,I.jsx)(`button`,{type:`button`,className:`ml-3 underline`,onClick:()=>m(null),children:`dismiss`})]}),(0,I.jsx)(`div`,{className:`flex-1 min-h-0`,children:(0,I.jsx)(WM,{bootstrap:a,selectedPiboSessionId:s,selectedRoomId:t,selectedRoomArchived:!1,selectedSessionProfile:fe?.profile??`default`,selectedSessionActiveModel:fe?x(a,fe)??void 0:void 0,selectedSessionStatus:fe?.status,sessionViewId:he,sessionViews:le,currentSessionView:ue,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:oe,onThinkingLevelChange:e=>void oe(`/thinking ${e}`),onRefreshTrace:b,onRefreshBootstrap:y,onSend:ae,onError:m})})]})}var rN=document.getElementById(`root`);rN&&(0,y.createRoot)(rN).render((0,I.jsx)(v.StrictMode,{children:(0,I.jsx)(nN,{})}));
|