@pasko70/pibo 1.10.1 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/apps/chat-ui/assets/{dist-4NlLjLs7.js → dist-0E9FVJ6k.js} +1 -1
  2. package/dist/apps/chat-ui/assets/{dist-BpfBSMzK.js → dist-BvqC0hRM.js} +1 -1
  3. package/dist/apps/chat-ui/assets/{dist-hU-2oAb6.js → dist-C2BRHNXr.js} +1 -1
  4. package/dist/apps/chat-ui/assets/{dist-DnXWNQRm.js → dist-C57jNmjf.js} +1 -1
  5. package/dist/apps/chat-ui/assets/{dist-BPl-fzRB.js → dist-CBL8UXjd.js} +1 -1
  6. package/dist/apps/chat-ui/assets/{dist-uF6UXzI7.js → dist-CI-LPHjw.js} +1 -1
  7. package/dist/apps/chat-ui/assets/{dist-3Sts0Afa.js → dist-CMRFkfl5.js} +1 -1
  8. package/dist/apps/chat-ui/assets/{dist-Cvx5M97R.js → dist-CpZPhD2y.js} +1 -1
  9. package/dist/apps/chat-ui/assets/{dist-BA6mhAec.js → dist-CuCZ-3_K.js} +1 -1
  10. package/dist/apps/chat-ui/assets/{dist-BPnn9e2B.js → dist-CzC5kPWJ.js} +1 -1
  11. package/dist/apps/chat-ui/assets/{dist-r31x5Fcc.js → dist-D9hLnn1T.js} +1 -1
  12. package/dist/apps/chat-ui/assets/{index-CaTGYBOS.js → index-BEvjPUor.js} +21 -21
  13. package/dist/apps/chat-ui/assets/{index-al8DeEjA.css → index-DNeE4HrG.css} +1 -1
  14. package/dist/apps/chat-ui/index.html +2 -2
  15. package/dist/apps/chat-vscode-web/assets/{index-CK4SMZuu.js → index-BLZRi4Ka.js} +3 -3
  16. package/dist/apps/chat-vscode-web/assets/index-Bf2JvJ9z.css +2 -0
  17. package/dist/apps/chat-vscode-web/index.html +2 -2
  18. package/dist/apps/vscode-artifacts/latest.vsix +0 -0
  19. package/dist/apps/vscode-artifacts/pibo-vscode-ext-1.11.0.vsix +0 -0
  20. package/dist/auth/better-auth.js +49 -1
  21. package/dist/auth/cli.js +220 -0
  22. package/dist/auth/machine-keys.js +258 -0
  23. package/dist/auth/machine-session.js +123 -0
  24. package/dist/bin/pibo.js +0 -0
  25. package/dist/bin/rg.js +0 -0
  26. package/dist/cli.js +6 -0
  27. package/dist/compute/cli.js +7 -0
  28. package/dist/compute/resource-health.js +27 -3
  29. package/dist/config/config.js +5 -0
  30. package/dist/core/session-router.js +17 -0
  31. package/dist/data/schema.js +4 -0
  32. package/dist/debug/trace-status.js +25 -0
  33. package/dist/debug/trace.js +9 -10
  34. package/dist/resources/cli.js +15 -0
  35. package/dist/resources/lifecycle.js +28 -4
  36. package/dist/resources/reaper.js +1 -0
  37. package/dist/signals/projector.js +10 -1
  38. package/package.json +1 -1
  39. package/dist/apps/chat-vscode-web/assets/index-B5QK07zO.css +0 -2
@@ -36,6 +36,6 @@ Error generating stack: `+e.message+`
36
36
  `,inConstruct:`tableCell`},{atBreak:!0,character:`|`,after:`[ :-]`},{character:`|`,inConstruct:`tableCell`},{atBreak:!0,character:`:`,after:`-`},{atBreak:!0,character:`-`,after:`[:|-]`}],handlers:{inlineCode:f,table:o,tableCell:c,tableRow:s}};function o(e,t,n,r){return l(u(e,n,r),e.align)}function s(e,t,n,r){let i=l([d(e,n,r)]);return i.slice(0,i.indexOf(`
37
37
  `))}function c(e,t,n,r){let i=n.enter(`tableCell`),o=n.enter(`phrasing`),s=n.containerPhrasing(e,{...r,before:a,after:a});return o(),i(),s}function l(e,t){return Rg(e,{align:t,alignDelimiters:r,padding:n,stringLength:i})}function u(e,t,n){let r=e.children,i=-1,a=[],o=t.enter(`table`);for(;++i<r.length;)a[i]=d(r[i],t,n);return o(),a}function d(e,t,n){let r=e.children,i=-1,a=[],o=t.enter(`tableRow`);for(;++i<r.length;)a[i]=c(r[i],e,t,n);return o(),a}function f(e,t,n){let r=F_.inlineCode(e,t,n);return n.stack.includes(`tableCell`)&&(r=r.replace(/\|/g,`\\$&`)),r}}function G_(){return{exit:{taskListCheckValueChecked:q_,taskListCheckValueUnchecked:q_,paragraph:J_}}}function K_(){return{unsafe:[{atBreak:!0,character:`-`,after:`[:|-]`}],handlers:{listItem:Y_}}}function q_(e){let t=this.stack[this.stack.length-2];t.type,t.checked=e.type===`taskListCheckValueChecked`}function J_(e){let t=this.stack[this.stack.length-2];if(t&&t.type===`listItem`&&typeof t.checked==`boolean`){let e=this.stack[this.stack.length-1];e.type;let n=e.children[0];if(n&&n.type===`text`){let r=t.children,i=-1,a;for(;++i<r.length;){let e=r[i];if(e.type===`paragraph`){a=e;break}}a===e&&(n.value=n.value.slice(1),n.value.length===0?e.children.shift():e.position&&n.position&&typeof n.position.start.offset==`number`&&(n.position.start.column++,n.position.start.offset++,e.position.start=Object.assign({},n.position.start)))}}this.exit(e)}function Y_(e,t,n,r){let i=e.children[0],a=typeof e.checked==`boolean`&&i&&i.type===`paragraph`,o=`[`+(e.checked?`x`:` `)+`] `,s=n.createTracker(r);a&&s.move(o);let c=F_.listItem(e,t,n,{...r,...s.current()});return a&&(c=c.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,l)),c;function l(e){return e+o}}function X_(){return[ng(),Eg(),jg(),I_(),G_()]}function Z_(e){return{extensions:[rg(),Dg(e),Mg(),W_(e),K_()]}}var Q_={tokenize:fv,partial:!0},$_={tokenize:pv,partial:!0},ev={tokenize:mv,partial:!0},tv={tokenize:hv,partial:!0},nv={tokenize:gv,partial:!0},rv={name:`wwwAutolink`,tokenize:uv,previous:_v},iv={name:`protocolAutolink`,tokenize:dv,previous:vv},av={name:`emailAutolink`,tokenize:lv,previous:yv},ov={};function sv(){return{text:ov}}for(var cv=48;cv<123;)ov[cv]=av,cv++,cv===58?cv=65:cv===91&&(cv=97);ov[43]=av,ov[45]=av,ov[46]=av,ov[95]=av,ov[72]=[av,iv],ov[104]=[av,iv],ov[87]=[av,rv],ov[119]=[av,rv];function lv(e,t,n){let r=this,i,a;return o;function o(t){return!bv(t)||!yv.call(r,r.previous)||xv(r.events)?n(t):(e.enter(`literalAutolink`),e.enter(`literalAutolinkEmail`),s(t))}function s(t){return bv(t)?(e.consume(t),s):t===64?(e.consume(t),c):n(t)}function c(t){return t===46?e.check(nv,u,l)(t):t===45||t===95||nd(t)?(a=!0,e.consume(t),c):u(t)}function l(t){return e.consume(t),i=!0,c}function u(o){return a&&i&&td(r.previous)?(e.exit(`literalAutolinkEmail`),e.exit(`literalAutolink`),t(o)):n(o)}}function uv(e,t,n){let r=this;return i;function i(t){return t!==87&&t!==119||!_v.call(r,r.previous)||xv(r.events)?n(t):(e.enter(`literalAutolink`),e.enter(`literalAutolinkWww`),e.check(Q_,e.attempt($_,e.attempt(ev,a),n),n)(t))}function a(n){return e.exit(`literalAutolinkWww`),e.exit(`literalAutolink`),t(n)}}function dv(e,t,n){let r=this,i=``,a=!1;return o;function o(t){return(t===72||t===104)&&vv.call(r,r.previous)&&!xv(r.events)?(e.enter(`literalAutolink`),e.enter(`literalAutolinkHttp`),i+=String.fromCodePoint(t),e.consume(t),s):n(t)}function s(t){if(td(t)&&i.length<5)return i+=String.fromCodePoint(t),e.consume(t),s;if(t===58){let n=i.toLowerCase();if(n===`http`||n===`https`)return e.consume(t),c}return n(t)}function c(t){return t===47?(e.consume(t),a?l:(a=!0,c)):n(t)}function l(t){return t===null||id(t)||cd(t)||dd(t)||ud(t)?n(t):e.attempt($_,e.attempt(ev,u),n)(t)}function u(n){return e.exit(`literalAutolinkHttp`),e.exit(`literalAutolink`),t(n)}}function fv(e,t,n){let r=0;return i;function i(t){return(t===87||t===119)&&r<3?(r++,e.consume(t),i):t===46&&r===3?(e.consume(t),a):n(t)}function a(e){return e===null?n(e):t(e)}}function pv(e,t,n){let r,i,a;return o;function o(t){return t===46||t===95?e.check(tv,c,s)(t):t===null||cd(t)||dd(t)||t!==45&&ud(t)?c(t):(a=!0,e.consume(t),o)}function s(t){return t===95?r=!0:(i=r,r=void 0),e.consume(t),o}function c(e){return i||r||!a?n(e):t(e)}}function mv(e,t){let n=0,r=0;return i;function i(o){return o===40?(n++,e.consume(o),i):o===41&&r<n?a(o):o===33||o===34||o===38||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===60||o===63||o===93||o===95||o===126?e.check(tv,t,a)(o):o===null||cd(o)||dd(o)?t(o):(e.consume(o),i)}function a(t){return t===41&&r++,e.consume(t),i}}function hv(e,t,n){return r;function r(o){return o===33||o===34||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===63||o===95||o===126?(e.consume(o),r):o===38?(e.consume(o),a):o===93?(e.consume(o),i):o===60||o===null||cd(o)||dd(o)?t(o):n(o)}function i(e){return e===null||e===40||e===91||cd(e)||dd(e)?t(e):r(e)}function a(e){return td(e)?o(e):n(e)}function o(t){return t===59?(e.consume(t),r):td(t)?(e.consume(t),o):n(t)}}function gv(e,t,n){return r;function r(t){return e.consume(t),i}function i(e){return nd(e)?n(e):t(e)}}function _v(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||cd(e)}function vv(e){return!td(e)}function yv(e){return!(e===47||bv(e))}function bv(e){return e===43||e===45||e===46||e===95||nd(e)}function xv(e){let t=e.length,n=!1;for(;t--;){let r=e[t][1];if((r.type===`labelLink`||r.type===`labelImage`)&&!r._balanced){n=!0;break}if(r._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}var Sv={tokenize:Av,partial:!0};function Cv(){return{document:{91:{name:`gfmFootnoteDefinition`,tokenize:Dv,continuation:{tokenize:Ov},exit:kv}},text:{91:{name:`gfmFootnoteCall`,tokenize:Ev},93:{name:`gfmPotentialFootnoteCall`,add:`after`,tokenize:wv,resolveTo:Tv}}}}function wv(e,t,n){let r=this,i=r.events.length,a=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),o;for(;i--;){let e=r.events[i][1];if(e.type===`labelImage`){o=e;break}if(e.type===`gfmFootnoteCall`||e.type===`labelLink`||e.type===`label`||e.type===`image`||e.type===`link`)break}return s;function s(i){if(!o||!o._balanced)return n(i);let s=ed(r.sliceSerialize({start:o.end,end:r.now()}));return s.codePointAt(0)!==94||!a.includes(s.slice(1))?n(i):(e.enter(`gfmFootnoteCallLabelMarker`),e.consume(i),e.exit(`gfmFootnoteCallLabelMarker`),t(i))}}function Tv(e,t){let n=e.length;for(;n--;)if(e[n][1].type===`labelImage`&&e[n][0]===`enter`){e[n][1];break}e[n+1][1].type=`data`,e[n+3][1].type=`gfmFootnoteCallLabelMarker`;let r={type:`gfmFootnoteCall`,start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:`gfmFootnoteCallMarker`,start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;let a={type:`gfmFootnoteCallString`,start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},o={type:`chunkString`,contentType:`string`,start:Object.assign({},a.start),end:Object.assign({},a.end)},s=[e[n+1],e[n+2],[`enter`,r,t],e[n+3],e[n+4],[`enter`,i,t],[`exit`,i,t],[`enter`,a,t],[`enter`,o,t],[`exit`,o,t],[`exit`,a,t],e[e.length-2],e[e.length-1],[`exit`,r,t]];return e.splice(n,e.length-n+1,...s),e}function Ev(e,t,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),a=0,o;return s;function s(t){return e.enter(`gfmFootnoteCall`),e.enter(`gfmFootnoteCallLabelMarker`),e.consume(t),e.exit(`gfmFootnoteCallLabelMarker`),c}function c(t){return t===94?(e.enter(`gfmFootnoteCallMarker`),e.consume(t),e.exit(`gfmFootnoteCallMarker`),e.enter(`gfmFootnoteCallString`),e.enter(`chunkString`).contentType=`string`,l):n(t)}function l(s){if(a>999||s===93&&!o||s===null||s===91||cd(s))return n(s);if(s===93){e.exit(`chunkString`);let a=e.exit(`gfmFootnoteCallString`);return i.includes(ed(r.sliceSerialize(a)))?(e.enter(`gfmFootnoteCallLabelMarker`),e.consume(s),e.exit(`gfmFootnoteCallLabelMarker`),e.exit(`gfmFootnoteCall`),t):n(s)}return cd(s)||(o=!0),a++,e.consume(s),s===92?u:l}function u(t){return t===91||t===92||t===93?(e.consume(t),a++,l):l(t)}}function Dv(e,t,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),a,o=0,s;return c;function c(t){return e.enter(`gfmFootnoteDefinition`)._container=!0,e.enter(`gfmFootnoteDefinitionLabel`),e.enter(`gfmFootnoteDefinitionLabelMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionLabelMarker`),l}function l(t){return t===94?(e.enter(`gfmFootnoteDefinitionMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionMarker`),e.enter(`gfmFootnoteDefinitionLabelString`),e.enter(`chunkString`).contentType=`string`,u):n(t)}function u(t){if(o>999||t===93&&!s||t===null||t===91||cd(t))return n(t);if(t===93){e.exit(`chunkString`);let n=e.exit(`gfmFootnoteDefinitionLabelString`);return a=ed(r.sliceSerialize(n)),e.enter(`gfmFootnoteDefinitionLabelMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionLabelMarker`),e.exit(`gfmFootnoteDefinitionLabel`),f}return cd(t)||(s=!0),o++,e.consume(t),t===92?d:u}function d(t){return t===91||t===92||t===93?(e.consume(t),o++,u):u(t)}function f(t){return t===58?(e.enter(`definitionMarker`),e.consume(t),e.exit(`definitionMarker`),i.includes(a)||i.push(a),md(e,p,`gfmFootnoteDefinitionWhitespace`)):n(t)}function p(e){return t(e)}}function Ov(e,t,n){return e.check(kd,t,e.attempt(Sv,t,n))}function kv(e){e.exit(`gfmFootnoteDefinition`)}function Av(e,t,n){let r=this;return md(e,i,`gfmFootnoteDefinitionIndent`,5);function i(e){let i=r.events[r.events.length-1];return i&&i[1].type===`gfmFootnoteDefinitionIndent`&&i[2].sliceSerialize(i[1],!0).length===4?t(e):n(e)}}function jv(e){let t=(e||{}).singleTilde,n={name:`strikethrough`,tokenize:i,resolveAll:r};return t??=!0,{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function r(e,t){let n=-1;for(;++n<e.length;)if(e[n][0]===`enter`&&e[n][1].type===`strikethroughSequenceTemporary`&&e[n][1]._close){let r=n;for(;r--;)if(e[r][0]===`exit`&&e[r][1].type===`strikethroughSequenceTemporary`&&e[r][1]._open&&e[n][1].end.offset-e[n][1].start.offset===e[r][1].end.offset-e[r][1].start.offset){e[n][1].type=`strikethroughSequence`,e[r][1].type=`strikethroughSequence`;let i={type:`strikethrough`,start:Object.assign({},e[r][1].start),end:Object.assign({},e[n][1].end)},a={type:`strikethroughText`,start:Object.assign({},e[r][1].end),end:Object.assign({},e[n][1].start)},o=[[`enter`,i,t],[`enter`,e[r][1],t],[`exit`,e[r][1],t],[`enter`,a,t]],s=t.parser.constructs.insideSpan.null;s&&qu(o,o.length,0,Sd(s,e.slice(r+1,n),t)),qu(o,o.length,0,[[`exit`,a,t],[`enter`,e[n][1],t],[`exit`,e[n][1],t],[`exit`,i,t]]),qu(e,r-1,n-r+3,o),n=r+o.length-2;break}}for(n=-1;++n<e.length;)e[n][1].type===`strikethroughSequenceTemporary`&&(e[n][1].type=`data`);return e}function i(e,n,r){let i=this.previous,a=this.events,o=0;return s;function s(t){return i===126&&a[a.length-1][1].type!==`characterEscape`?r(t):(e.enter(`strikethroughSequenceTemporary`),c(t))}function c(a){let s=xd(i);if(a===126)return o>1?r(a):(e.consume(a),o++,c);if(o<2&&!t)return r(a);let l=e.exit(`strikethroughSequenceTemporary`),u=xd(a);return l._open=!u||u===2&&!!s,l._close=!s||s===2&&!!u,n(a)}}}var Mv=class{constructor(){this.map=[]}add(e,t,n){Nv(this,e,t,n)}consume(e){if(this.map.sort(function(e,t){return e[0]-t[0]}),this.map.length===0)return;let t=this.map.length,n=[];for(;t>0;)--t,n.push(e.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),e.length=this.map[t][0];n.push(e.slice()),e.length=0;let r=n.pop();for(;r;){for(let t of r)e.push(t);r=n.pop()}this.map.length=0}};function Nv(e,t,n,r){let i=0;if(!(n===0&&r.length===0)){for(;i<e.map.length;){if(e.map[i][0]===t){e.map[i][1]+=n,e.map[i][2].push(...r);return}i+=1}e.map.push([t,n,r])}}function Pv(e,t){let n=!1,r=[];for(;t<e.length;){let i=e[t];if(n){if(i[0]===`enter`)i[1].type===`tableContent`&&r.push(e[t+1][1].type===`tableDelimiterMarker`?`left`:`none`);else if(i[1].type===`tableContent`){if(e[t-1][1].type===`tableDelimiterMarker`){let e=r.length-1;r[e]=r[e]===`left`?`center`:`right`}}else if(i[1].type===`tableDelimiterRow`)break}else i[0]===`enter`&&i[1].type===`tableDelimiterRow`&&(n=!0);t+=1}return r}function Fv(){return{flow:{null:{name:`table`,tokenize:Iv,resolveAll:Lv}}}}function Iv(e,t,n){let r=this,i=0,a=0,o;return s;function s(e){let t=r.events.length-1;for(;t>-1;){let e=r.events[t][1].type;if(e===`lineEnding`||e===`linePrefix`)t--;else break}let i=t>-1?r.events[t][1].type:null,a=i===`tableHead`||i===`tableRow`?S:c;return a===S&&r.parser.lazy[r.now().line]?n(e):a(e)}function c(t){return e.enter(`tableHead`),e.enter(`tableRow`),l(t)}function l(e){return e===124?u(e):(o=!0,a+=1,u(e))}function u(t){return t===null?n(t):Q(t)?a>1?(a=0,r.interrupt=!0,e.exit(`tableRow`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),p):n(t):ld(t)?md(e,u,`whitespace`)(t):(a+=1,o&&(o=!1,i+=1),t===124?(e.enter(`tableCellDivider`),e.consume(t),e.exit(`tableCellDivider`),o=!0,u):(e.enter(`data`),d(t)))}function d(t){return t===null||t===124||cd(t)?(e.exit(`data`),u(t)):(e.consume(t),t===92?f:d)}function f(t){return t===92||t===124?(e.consume(t),d):d(t)}function p(t){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(t):(e.enter(`tableDelimiterRow`),o=!1,ld(t)?md(e,m,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):m(t))}function m(t){return t===45||t===58?g(t):t===124?(o=!0,e.enter(`tableCellDivider`),e.consume(t),e.exit(`tableCellDivider`),h):x(t)}function h(t){return ld(t)?md(e,g,`whitespace`)(t):g(t)}function g(t){return t===58?(a+=1,o=!0,e.enter(`tableDelimiterMarker`),e.consume(t),e.exit(`tableDelimiterMarker`),_):t===45?(a+=1,_(t)):t===null||Q(t)?b(t):x(t)}function _(t){return t===45?(e.enter(`tableDelimiterFiller`),v(t)):x(t)}function v(t){return t===45?(e.consume(t),v):t===58?(o=!0,e.exit(`tableDelimiterFiller`),e.enter(`tableDelimiterMarker`),e.consume(t),e.exit(`tableDelimiterMarker`),y):(e.exit(`tableDelimiterFiller`),y(t))}function y(t){return ld(t)?md(e,b,`whitespace`)(t):b(t)}function b(n){return n===124?m(n):n===null||Q(n)?!o||i!==a?x(n):(e.exit(`tableDelimiterRow`),e.exit(`tableHead`),t(n)):x(n)}function x(e){return n(e)}function S(t){return e.enter(`tableRow`),C(t)}function C(n){return n===124?(e.enter(`tableCellDivider`),e.consume(n),e.exit(`tableCellDivider`),C):n===null||Q(n)?(e.exit(`tableRow`),t(n)):ld(n)?md(e,C,`whitespace`)(n):(e.enter(`data`),w(n))}function w(t){return t===null||t===124||cd(t)?(e.exit(`data`),C(t)):(e.consume(t),t===92?T:w)}function T(t){return t===92||t===124?(e.consume(t),w):w(t)}}function Lv(e,t){let n=-1,r=!0,i=0,a=[0,0,0,0],o=[0,0,0,0],s=!1,c=0,l,u,d,f=new Mv;for(;++n<e.length;){let p=e[n],m=p[1];p[0]===`enter`?m.type===`tableHead`?(s=!1,c!==0&&(zv(f,t,c,l,u),u=void 0,c=0),l={type:`table`,start:Object.assign({},m.start),end:Object.assign({},m.end)},f.add(n,0,[[`enter`,l,t]])):m.type===`tableRow`||m.type===`tableDelimiterRow`?(r=!0,d=void 0,a=[0,0,0,0],o=[0,n+1,0,0],s&&(s=!1,u={type:`tableBody`,start:Object.assign({},m.start),end:Object.assign({},m.end)},f.add(n,0,[[`enter`,u,t]])),i=m.type===`tableDelimiterRow`?2:u?3:1):i&&(m.type===`data`||m.type===`tableDelimiterMarker`||m.type===`tableDelimiterFiller`)?(r=!1,o[2]===0&&(a[1]!==0&&(o[0]=o[1],d=Rv(f,t,a,i,void 0,d),a=[0,0,0,0]),o[2]=n)):m.type===`tableCellDivider`&&(r?r=!1:(a[1]!==0&&(o[0]=o[1],d=Rv(f,t,a,i,void 0,d)),a=o,o=[a[1],n,0,0])):m.type===`tableHead`?(s=!0,c=n):m.type===`tableRow`||m.type===`tableDelimiterRow`?(c=n,a[1]===0?o[1]!==0&&(d=Rv(f,t,o,i,n,d)):(o[0]=o[1],d=Rv(f,t,a,i,n,d)),i=0):i&&(m.type===`data`||m.type===`tableDelimiterMarker`||m.type===`tableDelimiterFiller`)&&(o[3]=n)}for(c!==0&&zv(f,t,c,l,u),f.consume(t.events),n=-1;++n<t.events.length;){let e=t.events[n];e[0]===`enter`&&e[1].type===`table`&&(e[1]._align=Pv(t.events,n))}return e}function Rv(e,t,n,r,i,a){let o=r===1?`tableHeader`:r===2?`tableDelimiter`:`tableData`;n[0]!==0&&(a.end=Object.assign({},Bv(t.events,n[0])),e.add(n[0],0,[[`exit`,a,t]]));let s=Bv(t.events,n[1]);if(a={type:o,start:Object.assign({},s),end:Object.assign({},s)},e.add(n[1],0,[[`enter`,a,t]]),n[2]!==0){let i=Bv(t.events,n[2]),a=Bv(t.events,n[3]),o={type:`tableContent`,start:Object.assign({},i),end:Object.assign({},a)};if(e.add(n[2],0,[[`enter`,o,t]]),r!==2){let r=t.events[n[2]],i=t.events[n[3]];if(r[1].end=Object.assign({},i[1].end),r[1].type=`chunkText`,r[1].contentType=`text`,n[3]>n[2]+1){let t=n[2]+1,r=n[3]-n[2]-1;e.add(t,r,[])}}e.add(n[3]+1,0,[[`exit`,o,t]])}return i!==void 0&&(a.end=Object.assign({},Bv(t.events,i)),e.add(i,0,[[`exit`,a,t]]),a=void 0),a}function zv(e,t,n,r,i){let a=[],o=Bv(t.events,n);i&&(i.end=Object.assign({},o),a.push([`exit`,i,t])),r.end=Object.assign({},o),a.push([`exit`,r,t]),e.add(n+1,0,a)}function Bv(e,t){let n=e[t],r=n[0]===`enter`?`start`:`end`;return n[1][r]}var Vv={name:`tasklistCheck`,tokenize:Uv};function Hv(){return{text:{91:Vv}}}function Uv(e,t,n){let r=this;return i;function i(t){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(t):(e.enter(`taskListCheck`),e.enter(`taskListCheckMarker`),e.consume(t),e.exit(`taskListCheckMarker`),a)}function a(t){return cd(t)?(e.enter(`taskListCheckValueUnchecked`),e.consume(t),e.exit(`taskListCheckValueUnchecked`),o):t===88||t===120?(e.enter(`taskListCheckValueChecked`),e.consume(t),e.exit(`taskListCheckValueChecked`),o):n(t)}function o(t){return t===93?(e.enter(`taskListCheckMarker`),e.consume(t),e.exit(`taskListCheckMarker`),e.exit(`taskListCheck`),s):n(t)}function s(r){return Q(r)?t(r):ld(r)?e.check({tokenize:Wv},t,n)(r):n(r)}}function Wv(e,t,n){return md(e,r,`whitespace`);function r(e){return e===null?n(e):t(e)}}function Gv(e){return Xu([sv(),Cv(),jv(e),Fv(),Hv()])}var Kv={};function qv(e){let t=this,n=e||Kv,r=t.data(),i=r.micromarkExtensions||=[],a=r.fromMarkdownExtensions||=[],o=r.toMarkdownExtensions||=[];i.push(Gv(n)),a.push(X_()),o.push(Z_(n))}var Jv=l(o(((e,t)=>{var n=function(e){var t=/(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i,n=0,r={},i={manual:e.Prism&&e.Prism.manual,disableWorkerMessageHandler:e.Prism&&e.Prism.disableWorkerMessageHandler,util:{encode:function e(t){return t instanceof a?new a(t.type,e(t.content),t.alias):Array.isArray(t)?t.map(e):t.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/\u00a0/g,` `)},type:function(e){return Object.prototype.toString.call(e).slice(8,-1)},objId:function(e){return e.__id||Object.defineProperty(e,`__id`,{value:++n}),e.__id},clone:function e(t,n){n||={};var r,a;switch(i.util.type(t)){case`Object`:if(a=i.util.objId(t),n[a])return n[a];for(var o in r={},n[a]=r,t)t.hasOwnProperty(o)&&(r[o]=e(t[o],n));return r;case`Array`:return a=i.util.objId(t),n[a]?n[a]:(r=[],n[a]=r,t.forEach(function(t,i){r[i]=e(t,n)}),r);default:return t}},getLanguage:function(e){for(;e;){var n=t.exec(e.className);if(n)return n[1].toLowerCase();e=e.parentElement}return`none`},setLanguage:function(e,n){e.className=e.className.replace(RegExp(t,`gi`),``),e.classList.add(`language-`+n)},currentScript:function(){if(typeof document>`u`)return null;if(document.currentScript&&document.currentScript.tagName===`SCRIPT`)return document.currentScript;try{throw Error()}catch(r){var e=(/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(r.stack)||[])[1];if(e){var t=document.getElementsByTagName(`script`);for(var n in t)if(t[n].src==e)return t[n]}return null}},isActive:function(e,t,n){for(var r=`no-`+t;e;){var i=e.classList;if(i.contains(t))return!0;if(i.contains(r))return!1;e=e.parentElement}return!!n}},languages:{plain:r,plaintext:r,text:r,txt:r,extend:function(e,t){var n=i.util.clone(i.languages[e]);for(var r in t)n[r]=t[r];return n},insertBefore:function(e,t,n,r){r||=i.languages;var a=r[e],o={};for(var s in a)if(a.hasOwnProperty(s)){if(s==t)for(var c in n)n.hasOwnProperty(c)&&(o[c]=n[c]);n.hasOwnProperty(s)||(o[s]=a[s])}var l=r[e];return r[e]=o,i.languages.DFS(i.languages,function(t,n){n===l&&t!=e&&(this[t]=o)}),o},DFS:function e(t,n,r,a){a||={};var o=i.util.objId;for(var s in t)if(t.hasOwnProperty(s)){n.call(t,s,t[s],r||s);var c=t[s],l=i.util.type(c);l===`Object`&&!a[o(c)]?(a[o(c)]=!0,e(c,n,null,a)):l===`Array`&&!a[o(c)]&&(a[o(c)]=!0,e(c,n,s,a))}}},plugins:{},highlightAll:function(e,t){i.highlightAllUnder(document,e,t)},highlightAllUnder:function(e,t,n){var r={callback:n,container:e,selector:`code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code`};i.hooks.run(`before-highlightall`,r),r.elements=Array.prototype.slice.apply(r.container.querySelectorAll(r.selector)),i.hooks.run(`before-all-elements-highlight`,r);for(var a=0,o;o=r.elements[a++];)i.highlightElement(o,t===!0,r.callback)},highlightElement:function(t,n,r){var a=i.util.getLanguage(t),o=i.languages[a];i.util.setLanguage(t,a);var s=t.parentElement;s&&s.nodeName.toLowerCase()===`pre`&&i.util.setLanguage(s,a);var c={element:t,language:a,grammar:o,code:t.textContent};function l(e){c.highlightedCode=e,i.hooks.run(`before-insert`,c),c.element.innerHTML=c.highlightedCode,i.hooks.run(`after-highlight`,c),i.hooks.run(`complete`,c),r&&r.call(c.element)}if(i.hooks.run(`before-sanity-check`,c),s=c.element.parentElement,s&&s.nodeName.toLowerCase()===`pre`&&!s.hasAttribute(`tabindex`)&&s.setAttribute(`tabindex`,`0`),!c.code){i.hooks.run(`complete`,c),r&&r.call(c.element);return}if(i.hooks.run(`before-highlight`,c),!c.grammar){l(i.util.encode(c.code));return}if(n&&e.Worker){var u=new Worker(i.filename);u.onmessage=function(e){l(e.data)},u.postMessage(JSON.stringify({language:c.language,code:c.code,immediateClose:!0}))}else l(i.highlight(c.code,c.grammar,c.language))},highlight:function(e,t,n){var r={code:e,grammar:t,language:n};if(i.hooks.run(`before-tokenize`,r),!r.grammar)throw Error(`The language "`+r.language+`" has no grammar.`);return r.tokens=i.tokenize(r.code,r.grammar),i.hooks.run(`after-tokenize`,r),a.stringify(i.util.encode(r.tokens),r.language)},tokenize:function(e,t){var n=t.rest;if(n){for(var r in n)t[r]=n[r];delete t.rest}var i=new c;return l(i,i.head,e),s(e,i,t,i.head,0),d(i)},hooks:{all:{},add:function(e,t){var n=i.hooks.all;n[e]=n[e]||[],n[e].push(t)},run:function(e,t){var n=i.hooks.all[e];if(!(!n||!n.length))for(var r=0,a;a=n[r++];)a(t)}},Token:a};e.Prism=i;function a(e,t,n,r){this.type=e,this.content=t,this.alias=n,this.length=(r||``).length|0}a.stringify=function e(t,n){if(typeof t==`string`)return t;if(Array.isArray(t)){var r=``;return t.forEach(function(t){r+=e(t,n)}),r}var a={type:t.type,content:e(t.content,n),tag:`span`,classes:[`token`,t.type],attributes:{},language:n},o=t.alias;o&&(Array.isArray(o)?Array.prototype.push.apply(a.classes,o):a.classes.push(o)),i.hooks.run(`wrap`,a);var s=``;for(var c in a.attributes)s+=` `+c+`="`+(a.attributes[c]||``).replace(/"/g,`&quot;`)+`"`;return`<`+a.tag+` class="`+a.classes.join(` `)+`"`+s+`>`+a.content+`</`+a.tag+`>`};function o(e,t,n,r){e.lastIndex=t;var i=e.exec(n);if(i&&r&&i[1]){var a=i[1].length;i.index+=a,i[0]=i[0].slice(a)}return i}function s(e,t,n,r,c,d){for(var f in n)if(!(!n.hasOwnProperty(f)||!n[f])){var p=n[f];p=Array.isArray(p)?p:[p];for(var m=0;m<p.length;++m){if(d&&d.cause==f+`,`+m)return;var h=p[m],g=h.inside,_=!!h.lookbehind,v=!!h.greedy,y=h.alias;if(v&&!h.pattern.global){var b=h.pattern.toString().match(/[imsuy]*$/)[0];h.pattern=RegExp(h.pattern.source,b+`g`)}for(var x=h.pattern||h,S=r.next,C=c;S!==t.tail&&!(d&&C>=d.reach);C+=S.value.length,S=S.next){var w=S.value;if(t.length>e.length)return;if(!(w instanceof a)){var T=1,E;if(v){if(E=o(x,C,e,_),!E||E.index>=e.length)break;var D=E.index,O=E.index+E[0].length,k=C;for(k+=S.value.length;D>=k;)S=S.next,k+=S.value.length;if(k-=S.value.length,C=k,S.value instanceof a)continue;for(var ee=S;ee!==t.tail&&(k<O||typeof ee.value==`string`);ee=ee.next)T++,k+=ee.value.length;T--,w=e.slice(C,k),E.index-=C}else if(E=o(x,0,w,_),!E)continue;var D=E.index,A=E[0],te=w.slice(0,D),ne=w.slice(D+A.length),re=C+w.length;d&&re>d.reach&&(d.reach=re);var ie=S.prev;te&&(ie=l(t,ie,te),C+=te.length),u(t,ie,T);var j=new a(f,g?i.tokenize(A,g):A,y,A);if(S=l(t,ie,j),ne&&l(t,S,ne),T>1){var M={cause:f+`,`+m,reach:re};s(e,t,n,S.prev,C,M),d&&M.reach>d.reach&&(d.reach=M.reach)}}}}}}function c(){var e={value:null,prev:null,next:null},t={value:null,prev:e,next:null};e.next=t,this.head=e,this.tail=t,this.length=0}function l(e,t,n){var r=t.next,i={value:n,prev:t,next:r};return t.next=i,r.prev=i,e.length++,i}function u(e,t,n){for(var r=t.next,i=0;i<n&&r!==e.tail;i++)r=r.next;t.next=r,r.prev=t,e.length-=i}function d(e){for(var t=[],n=e.head.next;n!==e.tail;)t.push(n.value),n=n.next;return t}if(!e.document)return e.addEventListener&&(i.disableWorkerMessageHandler||e.addEventListener(`message`,function(t){var n=JSON.parse(t.data),r=n.language,a=n.code,o=n.immediateClose;e.postMessage(i.highlight(a,i.languages[r],r)),o&&e.close()},!1)),i;var f=i.util.currentScript();f&&(i.filename=f.src,f.hasAttribute(`data-manual`)&&(i.manual=!0));function p(){i.manual||i.highlightAll()}if(!i.manual){var m=document.readyState;m===`loading`||m===`interactive`&&f&&f.defer?document.addEventListener(`DOMContentLoaded`,p):window.requestAnimationFrame?window.requestAnimationFrame(p):window.setTimeout(p,16)}return i}(typeof window<`u`?window:typeof WorkerGlobalScope<`u`&&self instanceof WorkerGlobalScope?self:{});t!==void 0&&t.exports&&(t.exports=n),typeof global<`u`&&(global.Prism=n),n.languages.markup={comment:{pattern:/<!--(?:(?!<!--)[\s\S])*?-->/,greedy:!0},prolog:{pattern:/<\?[\s\S]+?\?>/,greedy:!0},doctype:{pattern:/<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,greedy:!0,inside:{"internal-subset":{pattern:/(^[^\[]*\[)[\s\S]+(?=\]>$)/,lookbehind:!0,greedy:!0,inside:null},string:{pattern:/"[^"]*"|'[^']*'/,greedy:!0},punctuation:/^<!|>$|[[\]]/,"doctype-tag":/^DOCTYPE/i,name:/[^\s<>'"]+/}},cdata:{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,greedy:!0},tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"special-attr":[],"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,inside:{punctuation:[{pattern:/^=/,alias:`attr-equals`},{pattern:/^(\s*)["']|["']$/,lookbehind:!0}]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:[{pattern:/&[\da-z]{1,8};/i,alias:`named-entity`},/&#x?[\da-f]{1,8};/i]},n.languages.markup.tag.inside[`attr-value`].inside.entity=n.languages.markup.entity,n.languages.markup.doctype.inside[`internal-subset`].inside=n.languages.markup,n.hooks.add(`wrap`,function(e){e.type===`entity`&&(e.attributes.title=e.content.replace(/&amp;/,`&`))}),Object.defineProperty(n.languages.markup.tag,`addInlined`,{value:function(e,t){var r={};r[`language-`+t]={pattern:/(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,lookbehind:!0,inside:n.languages[t]},r.cdata=/^<!\[CDATA\[|\]\]>$/i;var i={"included-cdata":{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,inside:r}};i[`language-`+t]={pattern:/[\s\S]+/,inside:n.languages[t]};var a={};a[e]={pattern:RegExp(`(<__[^>]*>)(?:<!\\[CDATA\\[(?:[^\\]]|\\](?!\\]>))*\\]\\]>|(?!<!\\[CDATA\\[)[\\s\\S])*?(?=<\\/__>)`.replace(/__/g,function(){return e}),`i`),lookbehind:!0,greedy:!0,inside:i},n.languages.insertBefore(`markup`,`cdata`,a)}}),Object.defineProperty(n.languages.markup.tag,`addAttribute`,{value:function(e,t){n.languages.markup.tag.inside[`special-attr`].push({pattern:RegExp(`(^|["'\\s])(?:`+e+`)\\s*=\\s*(?:"[^"]*"|'[^']*'|[^\\s'">=]+(?=[\\s>]))`,`i`),lookbehind:!0,inside:{"attr-name":/^[^\s=]+/,"attr-value":{pattern:/=[\s\S]+/,inside:{value:{pattern:/(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,lookbehind:!0,alias:[t,`language-`+t],inside:n.languages[t]},punctuation:[{pattern:/^=/,alias:`attr-equals`},/"|'/]}}}})}}),n.languages.html=n.languages.markup,n.languages.mathml=n.languages.markup,n.languages.svg=n.languages.markup,n.languages.xml=n.languages.extend(`markup`,{}),n.languages.ssml=n.languages.xml,n.languages.atom=n.languages.xml,n.languages.rss=n.languages.xml,(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`))})(n),n.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,boolean:/\b(?:false|true)\b/,function:/\b\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/},n.languages.javascript=n.languages.extend(`clike`,{"class-name":[n.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}|\?\?=?|\?\.?|[~:]/}),n.languages.javascript[`class-name`][0].pattern=/(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/,n.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:n.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:n.languages.javascript},{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,lookbehind:!0,inside:n.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,lookbehind:!0,inside:n.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:n.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/}),n.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:n.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`}}),n.languages.insertBefore(`javascript`,`operator`,{"literal-property":{pattern:/((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,lookbehind:!0,alias:`property`}}),n.languages.markup&&(n.languages.markup.tag.addInlined(`script`,`javascript`),n.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`)),n.languages.js=n.languages.javascript,(function(){if(n===void 0||typeof document>`u`)return;Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector);var e=`Loading…`,t=function(e,t){return`✖ Error `+e+` while fetching file: `+t},r=`✖ Error: File does not exist or is empty`,i={js:`javascript`,py:`python`,rb:`ruby`,ps1:`powershell`,psm1:`powershell`,sh:`bash`,bat:`batch`,h:`c`,tex:`latex`},a=`data-src-status`,o=`loading`,s=`loaded`,c=`failed`,l=`pre[data-src]:not([`+a+`="`+s+`"]):not([`+a+`="`+o+`"])`;function u(e,n,i){var a=new XMLHttpRequest;a.open(`GET`,e,!0),a.onreadystatechange=function(){a.readyState==4&&(a.status<400&&a.responseText?n(a.responseText):a.status>=400?i(t(a.status,a.statusText)):i(r))},a.send(null)}function d(e){var t=/^\s*(\d+)\s*(?:(,)\s*(?:(\d+)\s*)?)?$/.exec(e||``);if(t){var n=Number(t[1]),r=t[2],i=t[3];return r?i?[n,Number(i)]:[n,void 0]:[n,n]}}n.hooks.add(`before-highlightall`,function(e){e.selector+=`, `+l}),n.hooks.add(`before-sanity-check`,function(t){var r=t.element;if(r.matches(l)){t.code=``,r.setAttribute(a,o);var f=r.appendChild(document.createElement(`CODE`));f.textContent=e;var p=r.getAttribute(`data-src`),m=t.language;if(m===`none`){var h=(/\.(\w+)$/.exec(p)||[,`none`])[1];m=i[h]||h}n.util.setLanguage(f,m),n.util.setLanguage(r,m);var g=n.plugins.autoloader;g&&g.loadLanguages(m),u(p,function(e){r.setAttribute(a,s);var t=d(r.getAttribute(`data-range`));if(t){var i=e.split(/\r\n?|\n/g),o=t[0],c=t[1]==null?i.length:t[1];o<0&&(o+=i.length),o=Math.max(0,Math.min(o-1,i.length)),c<0&&(c+=i.length),c=Math.max(0,Math.min(c,i.length)),e=i.slice(o,c).join(`
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 Yv(e){return typeof e==`object`&&!!e&&`languages`in e}var Xv=globalThis,Zv=Yv(Xv.Prism)?Xv.Prism:Jv.default;Xv.Prism=Zv,typeof window<`u`&&(window.Prism=Zv);var Qv;function $v(){if(Qv!==void 0)return Qv;let e=hy();if(!e)return Qv=!1,Qv;try{let t=new URL(e.location.href).searchParams.get(`debugStreaming`);Qv=t===null?e.localStorage.getItem(`pibo.chat.debugStreaming`)===`1`:t!==`0`&&t!==`false`}catch{Qv=!1}return Qv}function ey(e,t){dy(e,e=>{e.liveOpenCount+=1,e.lastReadyState=t})}function ty(e,t){dy(e,e=>{e.liveErrorCount+=1,e.lastReadyState=t})}function ny(e,t,n,r){dy(e,e=>{let i=_y();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=uy(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+=gy(t.delta)):t.type===`REASONING_MESSAGE_CONTENT`&&typeof t.delta==`string`&&(e.firstReasoningDeltaAt??=i,e.reasoningDeltaCount+=1,e.reasoningDeltaBytes+=gy(t.delta))})}function ry(e,t,n,r){dy(e,e=>{if(e.firstEnqueueAt??=_y(),e.enqueueCount+=1,r&&(e.enqueueFlushImmediateCount+=1),e.pendingEventCount=n,t.streamFrameId){let n=uy(t.streamFrameId);n===`durable`?e.lastDurableCursor=t.streamFrameId:n===`transient`&&(e.lastTransientLiveId=t.streamFrameId)}})}function iy(e,t,n){dy(e,e=>{let r=_y();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 ay(e,t){dy(e,e=>{let n=vy(t);e.liveTraceComputeCount+=1,e.liveTraceComputeDurationMsLast=n,e.liveTraceComputeDurationMsTotal+=n,e.liveTraceComputeDurationMsMax=Math.max(e.liveTraceComputeDurationMsMax??0,n)})}function oy(e,t){fy(n=>{let r=vy(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 sy(e,t){dy(e,e=>{e.traceRefreshScheduledCount+=1,e.lastTraceRefreshScheduledAt=_y(),e.lastTraceRefreshDelayMs=t})}function cy(e,t){dy(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 ly(e){let t=hy();if(!t?.__piboStreamingBenchmarkShouldDropOverlayEvent)return!1;try{return!!t.__piboStreamingBenchmarkShouldDropOverlayEvent(e)}catch{return!1}}function uy(e){return e?/^live:\d+$/.test(e)?`transient`:/^\d+:\d+$/.test(e)?`durable`:`other`:`missing`}function dy(e,t){fy(n=>{n.sessionIds.includes(e)||n.sessionIds.push(e),n.selectedPiboSessionId=e,t(n)})}function fy(e){let t=py();t&&(e(t),t.updatedAt=_y())}function py(){if(!$v())return;let e=hy();if(e)return e.__piboStreamingDebugReset||=()=>(e.__piboStreamingDebug=my(),e.__piboStreamingDebug),e.__piboStreamingDebug??=my(),e.__piboStreamingDebug}function my(){let e=_y();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 hy(){return typeof window>`u`?void 0:window}function gy(e){return typeof TextEncoder<`u`?new TextEncoder().encode(e).byteLength:e.length}function _y(){return new Date().toISOString()}function vy(e){return Math.max(0,Math.round(e*1e3)/1e3)}(function(e){var t=`\\b(?:BASH|BASHOPTS|BASH_ALIASES|BASH_ARGC|BASH_ARGV|BASH_CMDS|BASH_COMPLETION_COMPAT_DIR|BASH_LINENO|BASH_REMATCH|BASH_SOURCE|BASH_VERSINFO|BASH_VERSION|COLORTERM|COLUMNS|COMP_WORDBREAKS|DBUS_SESSION_BUS_ADDRESS|DEFAULTS_PATH|DESKTOP_SESSION|DIRSTACK|DISPLAY|EUID|GDMSESSION|GDM_LANG|GNOME_KEYRING_CONTROL|GNOME_KEYRING_PID|GPG_AGENT_INFO|GROUPS|HISTCONTROL|HISTFILE|HISTFILESIZE|HISTSIZE|HOME|HOSTNAME|HOSTTYPE|IFS|INSTANCE|JOB|LANG|LANGUAGE|LC_ADDRESS|LC_ALL|LC_IDENTIFICATION|LC_MEASUREMENT|LC_MONETARY|LC_NAME|LC_NUMERIC|LC_PAPER|LC_TELEPHONE|LC_TIME|LESSCLOSE|LESSOPEN|LINES|LOGNAME|LS_COLORS|MACHTYPE|MAILCHECK|MANDATORY_PATH|NO_AT_BRIDGE|OLDPWD|OPTERR|OPTIND|ORBIT_SOCKETDIR|OSTYPE|PAPERSIZE|PATH|PIPESTATUS|PPID|PS1|PS2|PS3|PS4|PWD|RANDOM|REPLY|SECONDS|SELINUX_INIT|SESSION|SESSIONTYPE|SESSION_MANAGER|SHELL|SHELLOPTS|SHLVL|SSH_AUTH_SOCK|TERM|UID|UPSTART_EVENTS|UPSTART_INSTANCE|UPSTART_JOB|UPSTART_SESSION|USER|WINDOWID|XAUTHORITY|XDG_CONFIG_DIRS|XDG_CURRENT_DESKTOP|XDG_DATA_DIRS|XDG_GREETER_DATA_DIR|XDG_MENU_PREFIX|XDG_RUNTIME_DIR|XDG_SEAT|XDG_SEAT_PATH|XDG_SESSION_DESKTOP|XDG_SESSION_ID|XDG_SESSION_PATH|XDG_SESSION_TYPE|XDG_VTNR|XMODIFIERS)\\b`,n={pattern:/(^(["']?)\w+\2)[ \t]+\S.*/,lookbehind:!0,alias:`punctuation`,inside:null},r={bash:n,environment:{pattern:RegExp(`\\$`+t),alias:`constant`},variable:[{pattern:/\$?\(\([\s\S]+?\)\)/,greedy:!0,inside:{variable:[{pattern:/(^\$\(\([\s\S]+)\)\)/,lookbehind:!0},/^\$\(\(/],number:/\b0x[\dA-Fa-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[Ee]-?\d+)?/,operator:/--|\+\+|\*\*=?|<<=?|>>=?|&&|\|\||[=!+\-*/%<>^&|]=?|[?~:]/,punctuation:/\(\(?|\)\)?|,|;/}},{pattern:/\$\((?:\([^)]+\)|[^()])+\)|`[^`]+`/,greedy:!0,inside:{variable:/^\$\(|^`|\)$|`$/}},{pattern:/\$\{[^}]+\}/,greedy:!0,inside:{operator:/:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,punctuation:/[\[\]]/,environment:{pattern:RegExp(`(\\{)`+t),lookbehind:!0,alias:`constant`}}},/\$(?:\w+|[#?*!@$])/],entity:/\\(?:[abceEfnrtv\\"]|O?[0-7]{1,3}|U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{1,2})/};e.languages.bash={shebang:{pattern:/^#!\s*\/.*/,alias:`important`},comment:{pattern:/(^|[^"{\\$])#.*/,lookbehind:!0},"function-name":[{pattern:/(\bfunction\s+)[\w-]+(?=(?:\s*\(?:\s*\))?\s*\{)/,lookbehind:!0,alias:`function`},{pattern:/\b[\w-]+(?=\s*\(\s*\)\s*\{)/,alias:`function`}],"for-or-select":{pattern:/(\b(?:for|select)\s+)\w+(?=\s+in\s)/,alias:`variable`,lookbehind:!0},"assign-left":{pattern:/(^|[\s;|&]|[<>]\()\w+(?:\.\w+)*(?=\+?=)/,inside:{environment:{pattern:RegExp(`(^|[\\s;|&]|[<>]\\()`+t),lookbehind:!0,alias:`constant`}},alias:`variable`,lookbehind:!0},parameter:{pattern:/(^|\s)-{1,2}(?:\w+:[+-]?)?\w+(?:\.\w+)*(?=[=\s]|$)/,alias:`variable`,lookbehind:!0},string:[{pattern:/((?:^|[^<])<<-?\s*)(\w+)\s[\s\S]*?(?:\r?\n|\r)\2/,lookbehind:!0,greedy:!0,inside:r},{pattern:/((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s[\s\S]*?(?:\r?\n|\r)\3/,lookbehind:!0,greedy:!0,inside:{bash:n}},{pattern:/(^|[^\\](?:\\\\)*)"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/,lookbehind:!0,greedy:!0,inside:r},{pattern:/(^|[^$\\])'[^']*'/,lookbehind:!0,greedy:!0},{pattern:/\$'(?:[^'\\]|\\[\s\S])*'/,greedy:!0,inside:{entity:r.entity}}],environment:{pattern:RegExp(`\\$?`+t),alias:`constant`},variable:r.variable,function:{pattern:/(^|[\s;|&]|[<>]\()(?:add|apropos|apt|apt-cache|apt-get|aptitude|aspell|automysqlbackup|awk|basename|bash|bc|bconsole|bg|bzip2|cal|cargo|cat|cfdisk|chgrp|chkconfig|chmod|chown|chroot|cksum|clear|cmp|column|comm|composer|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|debootstrap|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|docker|docker-compose|du|egrep|eject|env|ethtool|expand|expect|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|git|gparted|grep|groupadd|groupdel|groupmod|groups|grub-mkconfig|gzip|halt|head|hg|history|host|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|ip|java|jobs|join|kill|killall|less|link|ln|locate|logname|logrotate|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|lynx|make|man|mc|mdadm|mkconfig|mkdir|mke2fs|mkfifo|mkfs|mkisofs|mknod|mkswap|mmv|more|most|mount|mtools|mtr|mutt|mv|nano|nc|netstat|nice|nl|node|nohup|notify-send|npm|nslookup|op|open|parted|passwd|paste|pathchk|ping|pkill|pnpm|podman|podman-compose|popd|pr|printcap|printenv|ps|pushd|pv|quota|quotacheck|quotactl|ram|rar|rcp|reboot|remsync|rename|renice|rev|rm|rmdir|rpm|rsync|scp|screen|sdiff|sed|sendmail|seq|service|sftp|sh|shellcheck|shuf|shutdown|sleep|slocate|sort|split|ssh|stat|strace|su|sudo|sum|suspend|swapon|sync|sysctl|tac|tail|tar|tee|time|timeout|top|touch|tr|traceroute|tsort|tty|umount|uname|unexpand|uniq|units|unrar|unshar|unzip|update-grub|uptime|useradd|userdel|usermod|users|uudecode|uuencode|v|vcpkg|vdir|vi|vim|virsh|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yarn|yes|zenity|zip|zsh|zypper)(?=$|[)\s;|&])/,lookbehind:!0},keyword:{pattern:/(^|[\s;|&]|[<>]\()(?:case|do|done|elif|else|esac|fi|for|function|if|in|select|then|until|while)(?=$|[)\s;|&])/,lookbehind:!0},builtin:{pattern:/(^|[\s;|&]|[<>]\()(?:\.|:|alias|bind|break|builtin|caller|cd|command|continue|declare|echo|enable|eval|exec|exit|export|getopts|hash|help|let|local|logout|mapfile|printf|pwd|read|readarray|readonly|return|set|shift|shopt|source|test|times|trap|type|typeset|ulimit|umask|unalias|unset)(?=$|[)\s;|&])/,lookbehind:!0,alias:`class-name`},boolean:{pattern:/(^|[\s;|&]|[<>]\()(?:false|true)(?=$|[)\s;|&])/,lookbehind:!0},"file-descriptor":{pattern:/\B&\d\b/,alias:`important`},operator:{pattern:/\d?<>|>\||\+=|=[=~]?|!=?|<<[<-]?|[&\d]?>>|\d[<>]&?|[<>][&=]?|&[>&]?|\|[&|]?/,inside:{"file-descriptor":{pattern:/^\d/,alias:`important`}}},punctuation:/\$?\(\(?|\)\)?|\.\.|[{}[\];\\]/,number:{pattern:/(^|\s)(?:[1-9]\d*|0)(?:[.,]\d+)?\b/,lookbehind:!0}},n.inside=e.languages.bash;for(var i=[`comment`,`function-name`,`for-or-select`,`assign-left`,`parameter`,`string`,`environment`,`function`,`keyword`,`builtin`,`boolean`,`file-descriptor`,`operator`,`punctuation`,`number`],a=r.variable[1].inside,o=0;o<i.length;o++)a[i[o]]=e.languages.bash[i[o]];e.languages.sh=e.languages.bash,e.languages.shell=e.languages.bash})(Prism),(function(e){var t=/(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;e.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:RegExp(`@[\\w-](?:[^;{\\s"']|\\s+(?!\\s)|`+t.source+`)*?(?:;|(?=\\s*\\{))`),inside:{rule:/^@[\w-]+/,"selector-function-argument":{pattern:/(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,lookbehind:!0,alias:`selector`},keyword:{pattern:/(^|[^\w-])(?:and|not|only|or)(?![\w-])/,lookbehind:!0}}},url:{pattern:RegExp(`\\burl\\((?:`+t.source+`|(?:[^\\\\\\r\\n()"']|\\\\[\\s\\S])*)\\)`,`i`),greedy:!0,inside:{function:/^url/i,punctuation:/^\(|\)$/,string:{pattern:RegExp(`^`+t.source+`$`),alias:`url`}}},selector:{pattern:RegExp(`(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|`+t.source+`)*(?=\\s*\\{)`),lookbehind:!0},string:{pattern:t,greedy:!0},property:{pattern:/(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,lookbehind:!0},important:/!important\b/i,function:{pattern:/(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,lookbehind:!0},punctuation:/[(){};:,]/},e.languages.css.atrule.inside.rest=e.languages.css;var n=e.languages.markup;n&&(n.tag.addInlined(`style`,`css`),n.tag.addAttribute(`style`,`css`))})(Prism),Prism.languages.javascript=Prism.languages.extend(`clike`,{"class-name":[Prism.languages.clike[`class-name`],{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,lookbehind:!0}],keyword:[{pattern:/((?:^|\})\s*)catch\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],function:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,number:{pattern:RegExp(`(^|[^\\w$])(?:NaN|Infinity|0[bB][01]+(?:_[01]+)*n?|0[oO][0-7]+(?:_[0-7]+)*n?|0[xX][\\dA-Fa-f]+(?:_[\\dA-Fa-f]+)*n?|\\d+(?:_\\d+)*n|(?:\\d+(?:_\\d+)*(?:\\.(?:\\d+(?:_\\d+)*)?)?|\\.\\d+(?:_\\d+)*)(?:[Ee][+-]?\\d+(?:_\\d+)*)?)(?![\\w$])`),lookbehind:!0},operator:/--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/}),Prism.languages.javascript[`class-name`][0].pattern=/(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/,Prism.languages.insertBefore(`javascript`,`keyword`,{regex:{pattern:RegExp(`((?:^|[^$\\w\\xA0-\\uFFFF."'\\])\\s]|\\b(?:return|yield))\\s*)\\/(?:(?:\\[(?:[^\\]\\\\\\r\\n]|\\\\.)*\\]|\\\\.|[^/\\\\\\[\\r\\n])+\\/[dgimyus]{0,7}|(?:\\[(?:[^[\\]\\\\\\r\\n]|\\\\.|\\[(?:[^[\\]\\\\\\r\\n]|\\\\.|\\[(?:[^[\\]\\\\\\r\\n]|\\\\.)*\\])*\\])*\\]|\\\\.|[^/\\\\\\[\\r\\n])+\\/[dgimyus]{0,7}v[dgimyus]{0,7})(?=(?:\\s|\\/\\*(?:[^*]|\\*(?!\\/))*\\*\\/)*(?:$|[\\r\\n,.;:})\\]]|\\/\\/))`),lookbehind:!0,greedy:!0,inside:{"regex-source":{pattern:/^(\/)[\s\S]+(?=\/[a-z]*$)/,lookbehind:!0,alias:`language-regex`,inside:Prism.languages.regex},"regex-delimiter":/^\/|\/$/,"regex-flags":/^[a-z]+$/}},"function-variable":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,alias:`function`},parameter:[{pattern:/(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,lookbehind:!0,inside:Prism.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/}),Prism.languages.insertBefore(`javascript`,`string`,{hashbang:{pattern:/^#!.*/,greedy:!0,alias:`comment`},"template-string":{pattern:/`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:`string`},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:`punctuation`},rest:Prism.languages.javascript}},string:/[\s\S]+/}},"string-property":{pattern:/((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,lookbehind:!0,greedy:!0,alias:`property`}}),Prism.languages.insertBefore(`javascript`,`operator`,{"literal-property":{pattern:/((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,lookbehind:!0,alias:`property`}}),Prism.languages.markup&&(Prism.languages.markup.tag.addInlined(`script`,`javascript`),Prism.languages.markup.tag.addAttribute(`on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)`,`javascript`)),Prism.languages.js=Prism.languages.javascript,Prism.languages.json={property:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,lookbehind:!0,greedy:!0},string:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,lookbehind:!0,greedy:!0},comment:{pattern:/\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,greedy:!0},number:/-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,punctuation:/[{}[\],]/,operator:/:/,boolean:/\b(?:false|true)\b/,null:{pattern:/\bnull\b/,alias:`keyword`}},Prism.languages.webmanifest=Prism.languages.json,(function(e){var t=`(?:\\\\.|[^\\\\\\n\\r]|(?:\\n|\\r\\n?)(?![\\r\\n]))`;function n(e){return e=e.replace(/<inner>/g,function(){return t}),RegExp(`((?:^|[^\\\\])(?:\\\\{2})*)(?:`+e+`)`)}var r="(?:\\\\.|``(?:[^`\\r\\n]|`(?!`))+``|`[^`\\r\\n]+`|[^\\\\|\\r\\n`])+",i=`\\|?__(?:\\|__)+\\|?(?:(?:\\n|\\r\\n?)|(?![\\s\\S]))`.replace(/__/g,function(){return r}),a=`\\|?[ \\t]*:?-{3,}:?[ \\t]*(?:\\|[ \\t]*:?-{3,}:?[ \\t]*)+\\|?(?:\\n|\\r\\n?)`;e.languages.markdown=e.languages.extend(`markup`,{}),e.languages.insertBefore(`markdown`,`prolog`,{"front-matter-block":{pattern:/(^(?:\s*[\r\n])?)---(?!.)[\s\S]*?[\r\n]---(?!.)/,lookbehind:!0,greedy:!0,inside:{punctuation:/^---|---$/,"front-matter":{pattern:/\S+(?:\s+\S+)*/,alias:[`yaml`,`language-yaml`],inside:e.languages.yaml}}},blockquote:{pattern:/^>(?:[\t ]*>)*/m,alias:`punctuation`},table:{pattern:RegExp(`^`+i+a+`(?:`+i+`)*`,`m`),inside:{"table-data-rows":{pattern:RegExp(`^(`+i+a+`)(?:`+i+`)*$`),lookbehind:!0,inside:{"table-data":{pattern:RegExp(r),inside:e.languages.markdown},punctuation:/\|/}},"table-line":{pattern:RegExp(`^(`+i+`)`+a+`$`),lookbehind:!0,inside:{punctuation:/\||:?-{3,}:?/}},"table-header-row":{pattern:RegExp(`^`+i+`$`),inside:{"table-header":{pattern:RegExp(r),alias:`important`,inside:e.languages.markdown},punctuation:/\|/}}}},code:[{pattern:/((?:^|\n)[ \t]*\n|(?:^|\r\n?)[ \t]*\r\n?)(?: {4}|\t).+(?:(?:\n|\r\n?)(?: {4}|\t).+)*/,lookbehind:!0,alias:`keyword`},{pattern:/^```[\s\S]*?^```$/m,greedy:!0,inside:{"code-block":{pattern:/^(```.*(?:\n|\r\n?))[\s\S]+?(?=(?:\n|\r\n?)^```$)/m,lookbehind:!0},"code-language":{pattern:/^(```).+/,lookbehind:!0},punctuation:/```/}}],title:[{pattern:/\S.*(?:\n|\r\n?)(?:==+|--+)(?=[ \t]*$)/m,alias:`important`,inside:{punctuation:/==+$|--+$/}},{pattern:/(^\s*)#.+/m,lookbehind:!0,alias:`important`,inside:{punctuation:/^#+|#+$/}}],hr:{pattern:/(^\s*)([*-])(?:[\t ]*\2){2,}(?=\s*$)/m,lookbehind:!0,alias:`punctuation`},list:{pattern:/(^\s*)(?:[*+-]|\d+\.)(?=[\t ].)/m,lookbehind:!0,alias:`punctuation`},"url-reference":{pattern:/!?\[[^\]]+\]:[\t ]+(?:\S+|<(?:\\.|[^>\\])+>)(?:[\t ]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\)))?/,inside:{variable:{pattern:/^(!?\[)[^\]]+/,lookbehind:!0},string:/(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\))$/,punctuation:/^[\[\]!:]|[<>]/},alias:`url`},bold:{pattern:n(`\\b__(?:(?!_)<inner>|_(?:(?!_)<inner>)+_)+__\\b|\\*\\*(?:(?!\\*)<inner>|\\*(?:(?!\\*)<inner>)+\\*)+\\*\\*`),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^..)[\s\S]+(?=..$)/,lookbehind:!0,inside:{}},punctuation:/\*\*|__/}},italic:{pattern:n(`\\b_(?:(?!_)<inner>|__(?:(?!_)<inner>)+__)+_\\b|\\*(?:(?!\\*)<inner>|\\*\\*(?:(?!\\*)<inner>)+\\*\\*)+\\*`),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^.)[\s\S]+(?=.$)/,lookbehind:!0,inside:{}},punctuation:/[*_]/}},strike:{pattern:n(`(~~?)(?:(?!~)<inner>)+\\2`),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^~~?)[\s\S]+(?=\1$)/,lookbehind:!0,inside:{}},punctuation:/~~?/}},"code-snippet":{pattern:/(^|[^\\`])(?:``[^`\r\n]+(?:`[^`\r\n]+)*``(?!`)|`[^`\r\n]+`(?!`))/,lookbehind:!0,greedy:!0,alias:[`code`,`keyword`]},url:{pattern:n(`!?\\[(?:(?!\\])<inner>)+\\](?:\\([^\\s)]+(?:[\\t ]+"(?:\\\\.|[^"\\\\])*")?\\)|[ \\t]?\\[(?:(?!\\])<inner>)+\\])`),lookbehind:!0,greedy:!0,inside:{operator:/^!/,content:{pattern:/(^\[)[^\]]+(?=\])/,lookbehind:!0,inside:{}},variable:{pattern:/(^\][ \t]?\[)[^\]]+(?=\]$)/,lookbehind:!0},url:{pattern:/(^\]\()[^\s)]+/,lookbehind:!0},string:{pattern:/(^[ \t]+)"(?:\\.|[^"\\])*"(?=\)$)/,lookbehind:!0}}}}),[`url`,`bold`,`italic`,`strike`].forEach(function(t){[`url`,`bold`,`italic`,`strike`,`code-snippet`].forEach(function(n){t!==n&&(e.languages.markdown[t].inside.content.inside[n]=e.languages.markdown[n])})}),e.hooks.add(`after-tokenize`,function(e){if(e.language!==`markdown`&&e.language!==`md`)return;function t(e){if(!(!e||typeof e==`string`))for(var n=0,r=e.length;n<r;n++){var i=e[n];if(i.type!==`code`){t(i.content);continue}var a=i.content[1],o=i.content[3];if(a&&o&&a.type===`code-language`&&o.type===`code-block`&&typeof a.content==`string`){var s=a.content.replace(/\b#/g,`sharp`).replace(/\b\+\+/g,`pp`);s=(/[a-z][\w-]*/i.exec(s)||[``])[0].toLowerCase();var c=`language-`+s;o.alias?typeof o.alias==`string`?o.alias=[o.alias,c]:o.alias.push(c):o.alias=[c]}}}t(e.tokens)}),e.hooks.add(`wrap`,function(t){if(t.type===`code-block`){for(var n=``,r=0,i=t.classes.length;r<i;r++){var a=t.classes[r],o=/language-(.+)/.exec(a);if(o){n=o[1];break}}var s=e.languages[n];if(s)t.content=e.highlight(l(t.content),s,n);else if(n&&n!==`none`&&e.plugins.autoloader){var c=`md-`+new Date().valueOf()+`-`+Math.floor(Math.random()*0x2386f26fc10000);t.attributes.id=c,e.plugins.autoloader.loadLanguages(n,function(){var t=document.getElementById(c);t&&(t.innerHTML=e.highlight(t.textContent,e.languages[n],n))})}}});var o=RegExp(e.languages.markup.tag.pattern.source,`gi`),s={amp:`&`,lt:`<`,gt:`>`,quot:`"`},c=String.fromCodePoint||String.fromCharCode;function l(e){var t=e.replace(o,``);return t=t.replace(/&(\w{1,8}|#x?[\da-f]{1,8});/gi,function(e,t){return t=t.toLowerCase(),t[0]===`#`?c(t[1]===`x`?parseInt(t.slice(2),16):Number(t.slice(1))):s[t]||e}),t}e.languages.md=e.languages.markdown})(Prism),(function(e){e.languages.typescript=e.languages.extend(`javascript`,{"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|type)\s+)(?!keyof\b)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?:\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>)?/,lookbehind:!0,greedy:!0,inside:null},builtin:/\b(?:Array|Function|Promise|any|boolean|console|never|number|string|symbol|unknown)\b/}),e.languages.typescript.keyword.push(/\b(?:abstract|declare|is|keyof|readonly|require)\b/,/\b(?:asserts|infer|interface|module|namespace|type)\b(?=\s*(?:[{_$a-zA-Z\xA0-\uFFFF]|$))/,/\btype\b(?=\s*(?:[\{*]|$))/),delete e.languages.typescript.parameter,delete e.languages.typescript[`literal-property`];var t=e.languages.extend(`typescript`,{});delete t[`class-name`],e.languages.typescript[`class-name`].inside=t,e.languages.insertBefore(`typescript`,`function`,{decorator:{pattern:/@[$\w\xA0-\uFFFF]+/,inside:{at:{pattern:/^@/,alias:`operator`},function:/^[\s\S]+/}},"generic-function":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>(?=\s*\()/,greedy:!0,inside:{function:/^#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*/,generic:{pattern:/<[\s\S]+/,alias:`class-name`,inside:t}}}}),e.languages.ts=e.languages.typescript})(Prism),(function(e){var t=/[*&][^\s[\]{},]+/,n=/!(?:<[\w\-%#;/?:@&=+$,.!~*'()[\]]+>|(?:[a-zA-Z\d-]*!)?[\w\-%#;/?:@&=+$.~*'()]+)?/,r=`(?:`+n.source+`(?:[ ]+`+t.source+`)?|`+t.source+`(?:[ ]+`+n.source+`)?)`,i=`(?:[^\\s\\x00-\\x08\\x0e-\\x1f!"#%&'*,\\-:>?@[\\]\`{|}\\x7f-\\x84\\x86-\\x9f\\ud800-\\udfff\\ufffe\\uffff]|[?:-]<PLAIN>)(?:[ \\t]*(?:(?![#:])<PLAIN>|:<PLAIN>))*`.replace(/<PLAIN>/g,function(){return`[^\\s\\x00-\\x08\\x0e-\\x1f,[\\]{}\\x7f-\\x84\\x86-\\x9f\\ud800-\\udfff\\ufffe\\uffff]`}),a=`"(?:[^"\\\\\\r\\n]|\\\\.)*"|'(?:[^'\\\\\\r\\n]|\\\\.)*'`;function o(e,t){t=(t||``).replace(/m/g,``)+`m`;var n=`([:\\-,[{]\\s*(?:\\s<<prop>>[ \\t]+)?)(?:<<value>>)(?=[ \\t]*(?:$|,|\\]|\\}|(?:[\\r\\n]\\s*)?#))`.replace(/<<prop>>/g,function(){return r}).replace(/<<value>>/g,function(){return e});return RegExp(n,t)}e.languages.yaml={scalar:{pattern:RegExp(`([\\-:]\\s*(?:\\s<<prop>>[ \\t]+)?[|>])[ \\t]*(?:((?:\\r?\\n|\\r)[ \\t]+)\\S[^\\r\\n]*(?:\\2[^\\r\\n]+)*)`.replace(/<<prop>>/g,function(){return r})),lookbehind:!0,alias:`string`},comment:/#.*/,key:{pattern:RegExp(`((?:^|[:\\-,[{\\r\\n?])[ \\t]*(?:<<prop>>[ \\t]+)?)<<key>>(?=\\s*:\\s)`.replace(/<<prop>>/g,function(){return r}).replace(/<<key>>/g,function(){return`(?:`+i+`|`+a+`)`})),lookbehind:!0,greedy:!0,alias:`atrule`},directive:{pattern:/(^[ \t]*)%.+/m,lookbehind:!0,alias:`important`},datetime:{pattern:o(`\\d{4}-\\d\\d?-\\d\\d?(?:[tT]|[ \\t]+)\\d\\d?:\\d{2}:\\d{2}(?:\\.\\d*)?(?:[ \\t]*(?:Z|[-+]\\d\\d?(?::\\d{2})?))?|\\d{4}-\\d{2}-\\d{2}|\\d\\d?:\\d{2}(?::\\d{2}(?:\\.\\d*)?)?`),lookbehind:!0,alias:`number`},boolean:{pattern:o(`false|true`,`i`),lookbehind:!0,alias:`important`},null:{pattern:o(`null|~`,`i`),lookbehind:!0,alias:`important`},string:{pattern:o(a),lookbehind:!0,greedy:!0},number:{pattern:o(`[+-]?(?:0x[\\da-f]+|0o[0-7]+|(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?|\\.inf|\\.nan)`,`i`),lookbehind:!0},tag:n,important:t,punctuation:/---|[:[\]{}\-,|>?]|\.\.\./},e.languages.yml=e.languages.yaml})(Prism);var yy=[`p`,`br`,`strong`,`em`,`a`,`ul`,`ol`,`li`,`blockquote`,`code`,`pre`,`h1`,`h2`,`h3`,`h4`,`hr`,`table`,`thead`,`tbody`,`tr`,`th`,`td`,`input`,`del`],by=[qv],xy=[],Sy=/[\n\r\\`*_\[\]<>]|~~/,Cy=/^\s*(?:#{1,6}\s|[-+>]|(?:\d+[.)]))\s/,wy=/^\s*-{3,}\s*$/,Ty=/\b(?:https?:\/\/|www\.)|\S+@\S+\.\S+/i,Ey=/^\s*[-+*]\s+\[[ xX]\]\s/m,Dy=/(^|\n)\s*\|?.+\|.+\n\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*(?:\n|$)/;function Oy(e){return e.length>0&&!Sy.test(e)&&!Cy.test(e)&&!wy.test(e)&&!(ky(e)&&Ty.test(e))}function ky(e){return e.includes(`://`)||e.includes(`www.`)||e.includes(`@`)}function Ay(e){let t=jy(e);return t?t.openerEnd>=e.length?e.slice(0,t.openerStart):`${e}\``:e}function jy(e){let t=0;for(;t<e.length;){let n=e.indexOf("`",t);if(n===-1)return;if(Py(e,n)){t=n+1;continue}if(Ny(e,n)!==1)return;let r=My(e,n+1);if(r===-1)return{openerStart:n,openerEnd:n+1};t=r+1}}function My(e,t){for(;t<e.length;){let n=e.indexOf("`",t);if(n===-1)return-1;let r=Ny(e,n);if(r===1)return n;t=n+r}return-1}function Ny(e,t){let n=t;for(;n<e.length&&e[n]==="`";)n+=1;return n-t}function Py(e,t){let n=0,r=t-1;for(;r>=0&&e[r]===`\\`;)n+=1,--r;return n%2==1}function Fy(e){return e.includes(`~~`)||e.includes(`[`)&&Ey.test(e)||e.includes(`|`)&&Dy.test(e)||ky(e)&&Ty.test(e)}var Iy=/[\n\r\\`*_\[\]<>]/,Ly=/^\s*[-+*]\s+\[([ xX])\]\s+(.+?)\s*$/,Ry=/[\n\r\\<>|~]/,zy=/[\n\r\\\[\]<>|~]/,By=/[\s\[\]()`<>]/;function Vy(e){if(!e.includes(`~~`)||Iy.test(e)||Cy.test(e)||wy.test(e)||ky(e)&&Ty.test(e)||e.includes(`[`)&&Ey.test(e)||e.includes(`|`)&&Dy.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 Hy(e){if(!e||By.test(e))return;let t=qh(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 Uy(e,t){if(!e||zy.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("`")||ky(t)&&Ty.test(t))return;t&&n.push(t);break}let p=e.slice(r,f);if(p.includes(`*`)||p.includes(`_`)||p.includes("`")||ky(p)&&Ty.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 Wy(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(`]`)||ky(r)&&Ty.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(`]`)||ky(f)&&Ty.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=Uy(e.slice(d+1,r),a),s=Hy(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 Gy(e){let t=Ly.exec(e);if(!t)return;let n=t[2];if(!n||Ry.test(n))return;let r=Wy(n);if(r)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:t[1].toLowerCase()===`x`,readOnly:!0,disabled:!0,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`input`}),r]})})}var Ky={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=qy(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=Zv.languages[i];return o?(0,I.jsx)(`code`,{className:`language-${i}`,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`code`,dangerouslySetInnerHTML:{__html:Zv.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 qy(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 Jy(e,t){t!==void 0&&oy(e,(typeof performance>`u`?Date.now():performance.now())-t)}var Yy=(e,t,n)=>{if(n.tagName!==`a`||t!==`href`)return``;let r=qh(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``}},Xy=(0,v.memo)(function({children:e,streaming:t=!1}){let n=$v()?typeof performance>`u`?Date.now():performance.now():void 0,r=t?Ay(e):e,i=`commonmark`,a;if(Oy(r))i=`plain`,a=(0,I.jsx)(`p`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`p`,children:r});else{let e=Fy(r),t=e?Vy(r)??Gy(r):void 0;t?(i=`gfm-fast`,a=t):(i=e?`gfm`:`commonmark`,a=Uh({allowedElements:yy,children:r,components:Ky,remarkPlugins:e?by:xy,skipHtml:!0,urlTransform:Yy}))}return Jy(i,n),a}),Zy={"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`}},Qy=12;function $y(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)(()=>$y(r,i)),[d,f]=(0,v.useState)(()=>t.spanType===`model.reasoning`?o:$y(r,i));(0,v.useEffect)(()=>{let e=$y(r,i);u(e),f(t.spanType===`model.reasoning`?o:e)},[r,i,a,o,t.spanType]),Zy[t.spanType]||Zy[`agent.run`],t.status,t.status,t.spanType===`user.prompt`||t.spanType;let p=!!t.children?.length;return fb(t.startTime,n),t.durationUs?`${(t.durationUs/1e3).toFixed(1)}`:t.endTime&&`${((t.endTime-t.startTime)/1e3).toFixed(1)}`,(0,I.jsx)(eb,{span:t,startTime:n,depth:r,contentExpanded:d,childrenExpanded:l,onToggle:(0,v.useCallback)(()=>{f(e=>!e),p&&u(e=>!e)},[p]),onFork:s,onOpenSession:c,childrenContent:p?t.children?.map(t=>(0,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 eb=(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=Zy[e.spanType]||Zy[`agent.run`],d=e.status===`UNSET`,f=lb(e.status,d),p=e.spanType===`user.prompt`||e.spanType===`user_input`,m=!!e.children?.length,h=fb(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`,style:{marginLeft:n>0?Qy:0,width:n>0?`calc(100% - ${Qy}px)`:`var(--trace-readable-width)`,maxWidth:`100%`},children:(0,I.jsx)(nl,{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`,style:{marginLeft:n>0?Qy:0,width:n>0?`calc(100% - ${Qy}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=>{tb(e)||a()},onKeyDown:e=>{tb(e)||(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),a())},role:`button`,tabIndex:0,"aria-expanded":r,children:[(0,I.jsx)(nb,{span:e,config:u,statusStyles:f,isActive:d,contentExpanded:r,duration:g,relativeTime:h,onToggle:a,onFork:o,onOpenSession:s}),r?(0,I.jsx)(ab,{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 tb(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 nb({span:e,config:t,statusStyles:n,isActive:r,contentExpanded:i,duration:a,relativeTime:o,onToggle:s,onFork:c,onOpenSession:l}){let u=e.spanType===`user.prompt`||e.spanType===`user_input`?`bg-[#11a4d4]/10`:n.headerClass;return(0,I.jsx)(`div`,{className:`${i?`border-b ${t.borderColor}/20`:``} ${u}`,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)(je,{size:12}):(0,I.jsx)(Me,{size:12}),(0,I.jsx)(rb,{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)(ob,{forkEntryId:e.pibo?.traceNodeType===`user.message`?e.pibo.entryId:void 0,linkedPiboSessionId:e.pibo?.linkedPiboSessionId,onFork:c,onOpenSession:l}),(0,I.jsx)(ib,{duration:a,relativeTime:o})]})})}function rb({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)(cb,{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 ib({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 ab=(0,v.memo)(function({span:e}){let[t,n]=(0,v.useState)(!1),{spanType:r,attributes:i,name:a}=e,o=i.content||i.input||i.output||i.message,s=i.tool_name||i.tool?.name||i[`tool.name`],c=typeof s==`string`?s:null,l=i.output||i.result||i[`tool.result`],u=i.arguments||i.args||i[`tool.arguments`],d=e.status===`ERROR`?(0,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:[d,(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)})]});if(r===`model.response`)return(0,I.jsxs)(`div`,{className:`flex flex-col`,children:[d,(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)(Xy,{children:o}):(0,I.jsx)(el,{value:o})})]});if(r===`tool.result`)return(0,I.jsxs)(`div`,{className:`flex flex-col`,children:[d,(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)(el,{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)(sb,{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)(Se,{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)(qe,{size:12}):(0,I.jsx)(Je,{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)(el,{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)(el,{value:l})]})]}):null,d]})}if(r===`yielded.run`){let e=pb(l)?l:pb(o)?o:{};return(0,I.jsxs)(`div`,{className:`flex flex-col`,children:[d,(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)(we,{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)(ub,{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)(qe,{size:12}):(0,I.jsx)(Je,{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)(el,{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:[d,(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:[d,(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)(Ze,{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:[`"`,mb(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:[d,(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)(Ze,{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:[`"`,mb(t),`"`]}):null]})]})}return r===`agent.run`?(0,I.jsx)(`div`,{className:`flex flex-col`,children:d}):(0,I.jsxs)(`div`,{className:`flex flex-col`,children:[d,(0,I.jsx)(`div`,{className:`p-4 font-mono text-sm text-slate-300`,children:(0,I.jsx)(el,{value:i})})]})});function ob({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)(Ze,{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)(Ke,{size:14})}):null]})}function sb({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?`...`:``}'`:mb(t).slice(0,50)})]},e)),`)`]})]})}function cb({type:e,className:t}){let n={size:14,className:t};switch(e){case`agent.run`:return(0,I.jsx)(Oe,{...n});case`tool.call`:return(0,I.jsx)(Te,{...n});case`tool.result`:return(0,I.jsx)(Se,{...n});case`model.request`:return(0,I.jsx)(De,{...n});case`model.response`:return(0,I.jsx)(Se,{...n});case`model.reasoning`:return(0,I.jsx)(rt,{...n});case`agent.delegation`:return(0,I.jsx)(Ze,{...n});case`agent.async`:return(0,I.jsx)(Ze,{...n});case`yielded.run`:return(0,I.jsx)(we,{...n});case`user.prompt`:return(0,I.jsx)(st,{...n});case`user_input`:return(0,I.jsx)(gt,{...n});case`execution.command`:return(0,I.jsx)(Te,{...n});default:return(0,I.jsx)(Ae,{...n})}}function lb(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 ub({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:db(t.toolName)||`yielded tool`}),(0,I.jsx)(`div`,{className:`truncate font-mono text-[10px] text-slate-500`,children:db(t.runId)})]}),(0,I.jsx)(`div`,{className:`font-mono text-[10px] uppercase text-slate-400`,children:db(t.status)||e.name})]},`${e.name}-${n}`))})]},e.name))})}function db(e){return typeof e==`string`?e:``}function fb(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 mb(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}var hb=5e3,gb=50,_b=new Map;function vb(e){let t=_b.get(e);return t||(t={snapshots:[],pending:null,pendingTimer:null},_b.set(e,t)),t}function yb(){try{return localStorage.getItem(`pibo.chat.traceDebug`)===`true`}catch{return!1}}function bb(e){let t=0;for(let n of e)for(let e=0;e<n.length;e++){let r=n.charCodeAt(e);t=(t<<5)-t+r,t|=0}return t.toString(36)}function xb(e){if(!e.pending)return;let t=e.pending;if(t.layers.length===0){e.pending=null;return}let n=e.snapshots.at(-1);n&&n.trigger===t.trigger&&n.traceVersion===t.traceVersion&&JSON.stringify(n.layers.map(e=>e.ids))===JSON.stringify(t.layers.map(e=>e.ids))||(e.snapshots.push(t),e.snapshots.length>hb&&e.snapshots.shift()),e.pending=null}function Sb(e){if(!yb())return;let t=vb(e.piboSessionId);if(t.pendingTimer&&=(clearTimeout(t.pendingTimer),null),(!t.pending||t.pending.trigger!==e.trigger||t.pending.piboSessionId!==e.piboSessionId)&&(xb(t),t.pending={timestamp:Date.now(),piboSessionId:e.piboSessionId,trigger:e.trigger,layers:[],expansionOverrides:e.expansionOverrides,traceVersion:e.traceVersion,latestStreamId:e.latestStreamId,lastRawEventId:e.lastRawEventId}),e.layer){let n=t.pending.layers.findIndex(t=>t.kind===e.layer.kind);n>=0?t.pending.layers[n]=e.layer:t.pending.layers.push(e.layer)}e.expansionOverrides!==void 0&&(t.pending.expansionOverrides=e.expansionOverrides),t.pendingTimer=setTimeout(()=>{xb(t),t.pendingTimer=null},gb)}function Cb(e,t,n,r){let i=Db(n);Sb({piboSessionId:e,trigger:t,layer:{kind:`backendNodes`,ids:i.map(e=>e.id),digest:bb(i.map(e=>e.id)),meta:i.map(e=>({id:e.id,type:e.type,orderKey:JSON.stringify(e.orderKey),parentId:e.parentId}))},...r})}function wb(e){let t=_b.get(e);return t?(xb(t),t.snapshots):[]}function Tb(e){if(e){let t=wb(e);return JSON.stringify({piboSessionId:e,snapshots:t},null,2)}let t={};for(let[e,n]of _b)xb(n),t[e]=n.snapshots;return JSON.stringify(t,null,2)}function Eb(e){e?_b.delete(e):_b.clear()}function Db(e){return e.flatMap(e=>[e,...Db(e.children??[])])}typeof window<`u`&&(window.__piboTraceSnapshots={exportAsJson:e=>{let t=Tb(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:wb,clearSnapshots:Eb,exportSnapshots:Tb});function Ob(e,t={}){if(!e)return kb(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 kb(e){let t=e.status===`running`&&Ab(e.turnStartedAt);return{status:e.status??`idle`,isTreeActive:e.status===`running`,isTurnActive:t,activeTurnStartedAt:t?e.turnStartedAt:void 0,source:`fallback`}}function Ab(e){return!!(e&&Number.isFinite(Date.parse(e)))}function jb({signal:e,fallbackStatus:t,fallbackTurnStartedAt:n}){return(0,v.useMemo)(()=>Ob(e,{status:t,turnStartedAt:n}),[t,n,e])}function Mb(e){if(e==null)return{kind:`empty`};let t=Nb(e);return t===void 0?{kind:`json`,value:e}:{kind:`text`,text:t}}function Nb(e){if(typeof e==`string`)return e;if(Array.isArray(e)){let t=e.map(Nb).filter(e=>e!==void 0);return t.length===e.length&&t.length>0?t.join(``):void 0}if(!Fb(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=Nb(e.content);if(n!==void 0&&Pb(e))return n;let r=Fb(e.message)?Nb(e.message.content):void 0;if(r!==void 0)return r}function Pb(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 Fb(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}async function Ib(e,t,n){let r=new URLSearchParams({piboSessionId:e}),i=await fetch(`/api/chat/trace/summary?${r.toString()}`,{headers:t?{"if-none-match":Bb(t)}:void 0,signal:n?.signal});if(i.status===304)return{notModified:!0,version:Vb(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:Vb(i.headers.get(`etag`))??a.version}}async function Lb(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":Bb(t.knownVersion)}:void 0,signal:t.signal});if(r.status===304)return{notModified:!0,version:Vb(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:Vb(r.headers.get(`etag`))??i.version}}async function Rb(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)),k(`/api/chat/trace/raw-events?${n.toString()}`,{signal:t.signal})}async function zb(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 k(`/api/chat/trace/payload/${encodeURIComponent(e)}${r?`?${r}`:``}`)}function Bb(e){return`"${e}"`}function Vb(e){if(!e)return;let t=e.trim();return t.startsWith(`W/`)?Vb(t.slice(2)):t.startsWith(`"`)&&t.endsWith(`"`)?t.slice(1,-1):t}function Hb({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)(Gb,{label:`Input`,value:e.input}),(0,I.jsx)(Gb,{label:`Output`,value:e.output}),(0,I.jsx)(Ub,{refs:e.payloadRefs}),(0,I.jsx)(Kb,{value:e.output}),e.error?(0,I.jsx)(Yb,{label:`Error`,value:e.error,tone:`red`}):null]},e.id))}):(0,I.jsxs)(`div`,{className:`space-y-3`,children:[(0,I.jsx)(Gb,{label:`Input`,value:e.input}),(0,I.jsx)(Gb,{label:`Output`,value:e.output}),(0,I.jsx)(Ub,{refs:e.payloadRefs}),(0,I.jsx)(Kb,{value:e.output}),e.error?(0,I.jsx)(Yb,{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 Ub({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)(Wb,{kind:e,refInfo:t},`${e}:${t.ref}`))}):null}function Wb({kind:e,refInfo:t}){let[n,r]=(0,v.useState)({status:`loading`});return(0,v.useEffect)(()=>{let e=!1;return r({status:`loading`}),zb(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 Gb({label:e,value:t}){let n=Mb(t);if(n.kind===`empty`)return null;if(n.kind===`text`){let t=Xb(n.text);return t?.kind===`json`?(0,I.jsx)(Jb,{label:e,value:t.value,meta:t.meta}):t?.kind===`text`?(0,I.jsx)(Yb,{label:e,value:t.text}):(0,I.jsx)(Yb,{label:e,value:n.text})}return(0,I.jsx)(Jb,{label:e,value:n.value})}function Kb({value:e}){let t=qb(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 qb(e){if(!$b(e))return;let t=$b(e.details)?e.details.piboBashOutputCompaction:void 0;if(!$b(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 Jb({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)(el,{value:t,showControls:!1})})]})}function Yb({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 Xb(e){let t=e.trim();if(!t)return;let n=Qb(t);if(n!==void 0)return Zb(n);let r=t.split(/\r?\n/);for(let e=1;e<r.length;e+=1){let t=r.slice(e).join(`
39
- `).trim();if(!t.startsWith(`{`)&&!t.startsWith(`[`))continue;let n=Qb(t);if(n!==void 0)return Zb(n,r.slice(0,e).join(` `).trim()||void 0)}}function Zb(e,t){let n=Mb(e);if(n.kind===`text`){let e=Xb(n.text);return e?.kind===`json`?{...e,meta:e.meta??t}:{kind:`text`,text:n.text}}return{kind:`json`,value:e,meta:t}}function Qb(e){if(!(!e.startsWith(`{`)&&!e.startsWith(`[`)))try{let t=JSON.parse(e);return typeof t==`object`&&t?t:void 0}catch{return}}function $b(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function ex({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)(tx,{value:t}),(0,I.jsx)(`span`,{className:`text-[#d4d4d4]`,children:`)`})]})}function tx({value:e}){let[t,n]=(0,v.useState)(()=>new Set([`$`])),[r,i]=(0,v.useState)(()=>new Set);return(0,I.jsx)(nx,{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 nx({value:e,path:t,expandedPaths:n,expandedStrings:r,onTogglePath:i,onToggleString:a}){if(Array.isArray(e))return(0,I.jsx)(rx,{value:e,path:t,open:`[`,close:`]`,expandedPaths:n,expandedStrings:r,onTogglePath:i,onToggleString:a});if(ax(e))return(0,I.jsx)(rx,{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`,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 rx({value:e,path:t,open:n,close:r,expandedPaths:i,expandedStrings:a,onTogglePath:o,onToggleString:s}){let c=Array.isArray(e)?e.map((e,t)=>[String(t),e]):Object.entries(e);return i.has(t)?(0,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:`Collapse JSON`,"aria-label":`Collapse JSON at ${t}`,"data-inline-json-path":t,children:[(0,I.jsx)(`span`,{className:`compact-terminal-json-caret`,children:`▾`}),n]}),c.map(([n,r],c)=>{let l=`${t}.${ix(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)(nx,{value:r,path:l,expandedPaths:i,expandedStrings:a,onTogglePath:o,onToggleString:s})]},l)}),(0,I.jsx)(`span`,{className:`text-[#737373]`,children:r})]}):(0,I.jsxs)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),o(t)},className:`compact-terminal-json-toggle align-baseline text-[#737373]`,title:`Expand JSON`,"aria-label":`Expand JSON at ${t}`,"data-inline-json-path":t,children:[(0,I.jsx)(`span`,{className:`compact-terminal-json-caret`,children:`▸`}),n,`...`,r]})}function ix(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`.`,`\\.`)}function ax(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}var ox=120;function sx({line:e,status:t,clampLines:n}){let r=`min-w-0 whitespace-pre-wrap break-words ${n?`block overflow-hidden`:``}`,i=dx(e.tokens),a=i.length>ox;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 ${lx(e.prefix,t)}`,children:cx(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:ux(e),children:e.text},`${t}:${e.text}`)),e.functionCall?(0,I.jsx)(ex,{name:e.functionCall.name,input:e.functionCall.input}):null]})]})}function cx(e=`none`){switch(e){case`bullet`:return`•`;case`detail`:return`└`;case`continuation`:return` `;case`prompt`:return`›`;default:return` `}}function lx(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 ux(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 dx(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 fx(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),k(`/api/web-annotations?${n.toString()}`)}async function px(e,t){return k(`/api/web-annotations/${encodeURIComponent(e)}`,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify(_x(t))})}async function mx(e){let t=new URLSearchParams;return e?.trim()&&t.set(`cdpUrl`,e.trim()),k(`/api/web-annotations/targets${t.size?`?${t.toString()}`:``}`)}async function hx(e){return k(`/api/web-annotations/bindings`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(_x(e))})}async function gx(e,t){return k(`/api/web-annotations/bindings/${encodeURIComponent(e)}/inject`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(_x(t))})}function _x(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0&&e!==``))}async function vx(e,t,n){return k(`/api/chat/projects/${encodeURIComponent(e)}/workflow-sessions/${encodeURIComponent(t)}/human-actions`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n)})}function yx(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 bx(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 xx(e){return Sx(e)?e.result:e}function Sx(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.type===`execution_result`}var Cx={device_code:`Device code`,api_key:`API key`,oauth:`Browser OAuth`};function wx({row:e,piboSessionId:t}){let n=yx(e.output)?e.output:void 0,r=(0,v.useMemo)(()=>n?.providers??[],[n?.providers]),[i,a]=(0,v.useState)({type:`select_provider`}),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(``),[u,d]=(0,v.useState)(``),[f,p]=(0,v.useState)(null),m=(0,v.useCallback)(()=>{a({type:`select_provider`}),l(``),d(``)},[]),h=(0,v.useCallback)(async e=>{try{await navigator.clipboard.writeText(e),p(e),window.setTimeout(()=>p(t=>t===e?null:t),1600)}catch{}},[]),g=(0,v.useCallback)(async e=>{if(!t){a({type:`error`,provider:e,message:`Select a chat session before starting login.`});return}s(!0),a({type:`device_starting`,provider:e});try{let n=xx(await ie(t,`login.start`,{provider:e.id}));if(!n?.url){a({type:`error`,provider:e,message:`No login URL returned.`});return}a({type:`device_flow`,provider:e,url:n.url,state:n.state,userCode:n.userCode,instructions:n.instructions})}catch(t){a({type:`error`,provider:e,message:t instanceof Error?t.message:String(t)})}finally{s(!1)}},[t]),_=(0,v.useCallback)(async(e,n,r)=>{if(t){s(!0);try{await ie(t,`login.complete`,{provider:e.id,state:n??``,...r?{code:r}:{}}),a({type:`success`,provider:e,message:`${e.name} login completed.`})}catch(t){a({type:`error`,provider:e,message:t instanceof Error?t.message:String(t)})}finally{s(!1)}}},[t]),y=(0,v.useCallback)(async e=>{if(!t)return;let n=c.trim();if(n){s(!0);try{await ie(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)(Tx,{title:i.type===`select_provider`?`Login`:Ox(i),tone:i.type===`error`?`red`:i.type===`success`?`green`:`cyan`,action:i.type===`select_provider`?void 0:(0,I.jsx)(Ex,{onClick:m,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)(Dx,{tone:`green`,children:`Configured`}):(0,I.jsx)(Dx,{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 g(i.provider),className:`inline-flex items-center gap-1 border border-[#3a3a3a] bg-transparent px-2 py-1 text-[11px] text-[#d4d4d4] hover:border-[#38bdf8] hover:text-[#38bdf8]`,children:[e===`api_key`?(0,I.jsx)(tt,{size:11}):(0,I.jsx)(ot,{size:11}),Cx[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)(at,{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:[kx(i.url),` `,(0,I.jsx)(Ke,{size:11})]}),(0,I.jsxs)(`button`,{type:`button`,onClick:()=>void h(i.url),className:`inline-flex items-center gap-1 border border-[#3a3a3a] px-1.5 py-0.5 text-[#737373] hover:border-[#38bdf8] hover:text-[#38bdf8]`,children:[f===i.url?(0,I.jsx)(ze,{size:10}):(0,I.jsx)(Ue,{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 h(i.userCode),className:`border border-[#1f4960] px-2 py-0.5 font-semibold tracking-widest text-[#38bdf8] hover:border-[#38bdf8]`,children:i.userCode}),(0,I.jsx)(`span`,{className:`text-[#737373]`,children:`then`}),(0,I.jsxs)(`button`,{type:`button`,disabled:o,onClick:()=>void _(i.provider,i.state),className:`inline-flex items-center gap-1 border border-[#3a3a3a] px-2 py-0.5 text-[#d4d4d4] hover:border-[#38bdf8] hover:text-[#38bdf8] disabled:opacity-50`,children:[o?(0,I.jsx)(at,{size:11,className:`animate-spin`}):(0,I.jsx)(ze,{size:11}),` Complete`]})]}):(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,I.jsx)(`input`,{value:u,onChange:e=>d(e.target.value),placeholder:`authorization code`,className:`min-w-0 flex-1 border border-[#2a2a2a] bg-[#0b0b0b] px-2 py-1 text-[11px] text-[#d4d4d4] outline-none focus:border-[#38bdf8]`}),(0,I.jsxs)(`button`,{type:`button`,disabled:o||!u.trim(),onClick:()=>void _(i.provider,i.state,u.trim()),className:`inline-flex items-center gap-1 border border-[#3a3a3a] px-2 py-1 text-[#d4d4d4] hover:border-[#38bdf8] hover:text-[#38bdf8] disabled:opacity-50`,children:[o?(0,I.jsx)(at,{size:11,className:`animate-spin`}):(0,I.jsx)(ze,{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,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&y(i.provider)},placeholder:`sk-...`,className:`min-w-[12rem] flex-1 border border-[#2a2a2a] bg-[#0b0b0b] px-2 py-1 text-[11px] text-[#d4d4d4] outline-none focus:border-[#38bdf8]`}),(0,I.jsxs)(`button`,{type:`button`,disabled:o||!c.trim(),onClick:()=>void y(i.provider),className:`inline-flex items-center gap-1 border border-[#3a3a3a] px-2 py-1 text-[#d4d4d4] hover:border-[#38bdf8] hover:text-[#38bdf8] disabled:opacity-50`,children:[o?(0,I.jsx)(at,{size:11,className:`animate-spin`}):(0,I.jsx)(ze,{size:11}),` Save`]})]}):i.type===`success`?(0,I.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px] text-[#22c55e]`,children:[(0,I.jsx)(ze,{size:13}),` `,i.message]}):(0,I.jsxs)(`div`,{className:`flex items-start gap-2 text-[11px] text-[#ef4444]`,children:[(0,I.jsx)(Le,{size:13,className:`mt-0.5 shrink-0`}),` `,(0,I.jsx)(`span`,{children:i.message})]})}):(0,I.jsx)(Tx,{title:`Login`,tone:`red`,children:`Unparseable login payload.`})}function Tx({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)(ot,{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 Ex({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)(Ce,{size:10}),` Back`]})}function Dx({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 Ox(e){return`provider`in e&&e.provider?e.provider.name:`Login`}function kx(e){try{let t=new URL(e);return`${t.host}${t.pathname}`}catch{return e.length>42?`${e.slice(0,39)}...`:e}}function Ax({row:e,piboSessionId:t,onModelChanged:n}){let r=xx(e.output),i=(bx(r)?r:void 0)?.providers??[],a=(0,v.useMemo)(()=>i.flatMap(e=>e.models.map(t=>({...t,providerLabel:e.label}))),[i]),[o,s]=(0,v.useState)(``),[c,l]=(0,v.useState)(null),[u,d]=(0,v.useState)(!1),[f,p]=(0,v.useState)(null),m=(0,v.useMemo)(()=>{let e=o.trim().toLowerCase();return e?a.filter(t=>`${t.providerLabel} ${t.provider} ${t.label} ${t.id}`.toLowerCase().includes(e)):a},[a,o]),h=async e=>{if(!(!t||u)){d(!0),l(e),p(null);try{await te(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.jsxs)(`div`,{className:`text-[11px] text-[#737373]`,children:[`Choose a model from authenticated providers. Use `,(0,I.jsx)(`span`,{className:`text-[#38bdf8]`,children:`/login`}),` to add providers.`]})]})}),(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)(ft,{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,onClick:()=>void h(e),className:`grid w-full grid-cols-[150px_1fr_auto] gap-2 border-b border-[#1f1f1f] px-3 py-2 text-left hover:bg-[#38bdf8]/10 disabled:opacity-50`,children:[(0,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]})]}),c?.provider===e.provider&&c?.id===e.id?(0,I.jsx)(Ae,{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.jsxs)(`div`,{className:`text-[#737373]`,children:[`No authenticated model providers found. Run `,(0,I.jsx)(`span`,{className:`text-[#38bdf8]`,children:`/login`}),` first.`]}),f?(0,I.jsx)(`div`,{className:`text-[11px] text-[#a3a3a3]`,children:f}):null]})]})}function jx(e={}){let t=[],n=[],r=Rx(e.warnings),i=Rx(e.errors);(e.session?.id||e.session?.title)&&t.push({id:`session`,label:`Session`,value:Mx([e.session?.title,e.session?.id].filter(Boolean).join(` | `))}),e.session?.profile&&t.push({id:`profile`,label:`Profile`,value:Mx(e.session.profile)}),e.session?.status&&t.push({id:`session-status`,label:`Session status`,value:Mx(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:Mx(e.model.label??[e.model.provider,e.model.id].filter(Boolean).join(`/`))}),e.runtime?.state&&t.push({id:`runtime`,label:`Runtime`,value:Mx(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:Mx(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:Mx(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`?Mx(e.fastMode):e.fastMode?`on`:`off`,tone:e.fastMode?`green`:`neutral`});let o=Rx(e.tools?.enabled),s=Rx(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:Mx(e.providerUsage.planType)}),e.providerUsage?.credits&&t.push({id:`provider-credits`,label:`Credits`,value:e.providerUsage.credits.unlimited?`unlimited`:Mx(e.providerUsage.credits.balance??`available`)}),e.message&&t.push({id:`message`,label:`Message`,value:Mx(e.message)}),n.push(Nx(e.contextUsage));for(let t of Px(e.providerUsage))n.push(t);return{kind:`status`,title:`Status`,fields:t,progress:n,warnings:r,errors:i}}function Mx(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 Nx(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=Fx(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:Ix(t)}}function Px(e){return e?.limits?.length?e.limits.map((t,n)=>{let r=Fx(t.usedPercent),i=Fx(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 ${Mx(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:Lx(i)}}):[{id:`provider`,label:`Provider quota`,state:`unavailable`,text:`Provider usage unavailable`,tone:`neutral`}]}function Fx(e){if(!(typeof e!=`number`||!Number.isFinite(e)))return Math.max(0,Math.min(100,e))}function Ix(e){return e===void 0?`neutral`:e>=80?`red`:e>=50?`yellow`:`green`}function Lx(e){return e===void 0?`neutral`:e<=20?`red`:e<=50?`yellow`:`green`}function Rx(e){return(e??[]).map(e=>Mx(e)).filter(e=>e.length>0)}function zx(e){switch(e.kind){case`tool.status`:return Bx(e);case`tool.thinking`:return Vx(e);case`tool.model`:return Hx(e);case`tool.login`:return Ux(e);case`tool.call`:case`tool.image`:case`tool.group.exploring`:case`tool.group.images`:return Wx(e);case`yielded.run`:return Gx(e,`yielded-run`,`Yielded run`,e.status===`error`?`red`:e.status===`running`?`cyan`:`green`);case`execution.compaction`:return Gx(e,`compaction`,e.status===`error`?`Compaction failed`:e.status===`running`?`Compacting`:`Compaction`,e.status===`error`?`red`:`magenta`);case`execution.command`:return Gx(e,`command`,`Command`,e.status===`error`?`red`:`yellow`);case`error`:return Gx(e,`error`,`Error`,`red`);default:return}}function Bx(e){let t=qx(e.output),n=Jx(t,`activeModel`)??Jx(t,`model`),r=jx({session:{id:Zx(t,`piboSessionId`)??Zx(t,`sessionId`),title:Zx(t,`sessionTitle`)??Zx(t,`title`),profile:Zx(t,`profile`)??Zx(t,`activeAgentId`)??Zx(t,`agentId`),status:$x(t,`disposed`)?`disposed`:Zx(t,`sessionStatus`)},model:n?{provider:Zx(n,`provider`),id:Zx(n,`id`),label:Zx(n,`label`)}:void 0,runtime:{state:$x(t,`disposed`)?`disposed`:$x(t,`processing`)?`processing`:$x(t,`streaming`)?`streaming`:Zx(t,`mode`)??`idle`,connected:$x(t,`connected`),queuedMessages:Qx(t,`queuedMessages`),processing:$x(t,`processing`),streaming:$x(t,`streaming`),disposed:$x(t,`disposed`)},cwd:Zx(t,`cwd`),contextUsage:Jx(t,`contextUsage`),providerUsage:Jx(t,`providerUsage`),tools:{enabled:Xx(t,`enabledTools`),active:Xx(t,`activeTools`)},thinking:Zx(t,`thinkingLevel`)?{level:Zx(t,`thinkingLevel`)}:void 0,fastMode:$x(t,`fastMode`),warnings:Xx(t,`warnings`),errors:Xx(t,`errors`),message:Zx(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 Vx(e){let t=qx(e.output),n=Zx(t,`level`)??`unknown`,r=t?.supported!==!1,i=Xx(t,`availableLevels`);return{id:e.id,kind:`thinking`,title:`Thinking`,status:e.status,tone:r?`yellow`:`red`,rows:[{label:`Current`,value:Mx(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 Hx(e){let t=Yx(qx(e.output),`providers`),n=t.flatMap(e=>{let t=Zx(e,`id`)??Zx(e,`provider`)??`provider`,n=Zx(e,`label`)??Zx(e,`name`)??t;return Yx(e,`models`).map(e=>{let r=Zx(e,`id`)??`model`,i=Zx(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 Ux(e){let t=Yx(qx(e.output),`providers`),n=t.map(e=>{let t=Zx(e,`id`)??`provider`;return{id:`login:${t}`,label:Zx(e,`name`)??Zx(e,`label`)??t,action:`login.selectProvider`,value:t,description:Xx(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 Wx(e){return Gx(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 Gx(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?``:` ${Kx(e.functionCall.input)}`}`:``}`.trim();return t?[{value:Mx(t)}]:[]}),a=e.lines.length===0&&typeof e.output==`string`&&e.output.trim()?[{value:Mx(e.output.trim())}]:[],o=[e.error?{label:`Error`,value:Mx(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 Kx(e){try{return JSON.stringify(e)}catch{return String(e)}}function qx(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 Jx(e,t){let n=e?.[t];return n&&typeof n==`object`&&!Array.isArray(n)?n:void 0}function Yx(e,t){let n=e?.[t];return Array.isArray(n)?n.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e)):[]}function Xx(e,t){let n=e?.[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Zx(e,t){let n=e?.[t];return typeof n==`string`?n:void 0}function Qx(e,t){let n=e?.[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function $x(e,t){let n=e?.[t];return typeof n==`boolean`?n:void 0}var eS={transcript:0,"event-log":1,live:2},tS={"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 nS(e,t){return{sourceRank:eS[`event-log`],turnSeq:e??2**53-1,eventSequence:e,phaseRank:tS[t]}}function rS(e,t,n){let r=e??2**53-1,i=t??2**53-1;return{sourceRank:eS.live,turnSeq:r,streamId:r,streamFrameIndex:i,phaseRank:tS[n]}}function iS(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 aS(e,t){if(e)return{...e,contentPartIndex:(e.contentPartIndex??0)+.1,phaseRank:tS[t]}}function oS(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 sS(e){let t=!1,n=e.map(e=>e.children.length?(t=!0,{...e,children:sS(e.children)}):e);return cS(n)?t?n:[...e]:[...n].sort(lS)}function cS(e){for(let t=1;t<e.length;t+=1)if(lS(e[t-1],e[t])>0)return!1;return!0}function lS(e,t){let n=uS(e,t);if(n!==0)return n;if(e.orderKey?.sourceRank===t.orderKey?.sourceRank){let n=oS(e.orderKey,t.orderKey);if(n!==0)return n}let r=dS(e.startedAt,t.startedAt);if(r!==0)return r;let i=oS(e.orderKey,t.orderKey);return i===0?e.id.localeCompare(t.id):i}function uS(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 dS(e,t){return!e&&!t?0:e?t?e.localeCompare(t):-1:1}function fS(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 pS(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 sS([...t.values()].filter(e=>!n.has(e.id)))}function mS(e,t,n,r){if(!hS(t))return;let i=r.get(e)?.filter(e=>e.metadata?.subagentToolName===t)??[],a=_S(n);return a?i.find(e=>e.metadata?.threadKey===a)?.id:i.length===1?i[0].id:void 0}function hS(e){return e.startsWith(`pibo_subagent_`)}function gS(e){return e.slice(14)}function _S(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 vS(e,t,n,r){let i=bS(e,t,n,r);if(!i)return;let a=e.children.find(e=>e.id===i.id);if(a){SS(a,i),a.runId=i.runId??a.runId;return}e.children.push(i)}function yS(e){let t=new Map;for(let n of fS(e)){let e=CS(n.output);if(!e)continue;let r=TS(e.runId);r&&t.set(r,{snapshot:e,completedAt:TS(e.completedAt)??TS(e.updatedAt)??n.completedAt})}for(let n of fS(e)){if(n.type!==`agent.async`||!n.runId)continue;let e=t.get(n.runId);if(!e)continue;let r=TS(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=TS(e.snapshot.summary)??n.error))}}function bS(e,t,n,r){if(!xS(e))return;let i=CS(e.output),a=DS(e.input)?e.input:{},o=TS(i?.toolName)??TS(a.toolName)??r?.title;if(!o||!hS(o))return;let s=TS(r?.summary)??gS(o),c=TS(i?.runId),l=TS(i?.status),u=a.arguments,d=TS(i?.completionPolicy)??TS(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:ES(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:DS(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:aS(e.orderKey,`agent.async`),children:[]}}function xS(e){return e.type===`tool.call`&&e.title===`pibo_run_start`}function SS(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 CS(e){if(DS(e)){if(wS(e))return e;if(DS(e.details)&&wS(e.details))return e.details}}function wS(e){return typeof e.runId==`string`&&typeof e.toolName==`string`}function TS(e){return typeof e==`string`?e:void 0}function ES(e,t){return e.status===`error`||t===`failed`?`error`:t===`completed`||t===`cancelled`?`done`:`running`}function DS(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function OS(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 kS(e){let t=AS(e.notification),n=t.length===1?t[0]:void 0,r=MS(e.notification.failed)+MS(e.notification.timedOut),i=MS(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:NS(e.notification),output:e.notification,source:e.source,stableKey:e.stableKey??e.id,orderKey:e.orderKey,children:[]}}function AS(e){return[...jS(e.completed),...jS(e.failed),...jS(e.timedOut),...jS(e.cancelled),...jS(e.running)]}function jS(e){return Array.isArray(e)?e.filter(PS):[]}function MS(e){return Array.isArray(e)?e.length:0}function NS(e){let t=[[MS(e.completed),`completed`],[MS(e.failed),`failed`],[MS(e.timedOut),`timed out`],[MS(e.cancelled),`cancelled`],[MS(e.running),`running`]].filter(([e])=>Number(e)>0).map(([e,t])=>`${e} ${t}`);return t.length?t.join(`, `):`No yielded run updates`}function PS(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function FS(e,t,n,r,i,a,o,s,c){let l=r.payload,u=o?HS(e,r):void 0;if(u){l.type===`message_steered`&&l.activeEventId&&(u.parentId=iC(l.activeEventId));return}if(o&&QS(l)&&!$S(l,s)||o&&eC(l,c))return;if(l.type===`assistant_delta`){qS(e,t,l,c,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex);return}if(l.type===`thinking_delta`){YS(e,t,l,c,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex);return}if(l.type===`assistant_message`){let i=IS(n,l,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex),a=t.get(i.id);if(a){JS(a,i);return}e.push(i),t.set(i.id,i);return}let d=KS(n,l,i,a,c,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex);if(d){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);if(e){JS(e,d);return}}if(d.type===`execution.compaction`){let t=gC(e);if(t){_C(t,d);return}}if(d.type===`model.reasoning`){let e=t.get(d.id);if(e){XS(e,d);return}}if(d.type===`agent.delegation`&&!d.toolCallId&&d.linkedPiboSessionId){let e=dC([...t.values()],d);if(e){uC(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(xS(e)&&d.type===`agent.delegation`){vS(e,n,r.createdAt,d);return}lC(e,d),vS(e,n,r.createdAt);return}}if(d.eventId){let e=t.get(d.id);if(e){d.type===`user.message`&&d.parentId&&(e.parentId=d.parentId);return}}LS(d,t),vS(d,n,r.createdAt),e.push(d);for(let e of fS([d]))t.set(e.id,e)}}function IS(e,t,n,r,i,a){let o=typeof t.eventId==`string`?t.eventId:void 0,s=oC(t);return{id:s?aC(s):`event:${t.type}:${SC(t)}`,piboSessionId:e,eventId:o,parentId:o?iC(o):void 0,type:`assistant.message`,title:`Agent Message`,status:`done`,startedAt:n,completedAt:n,summary:t.text,output:t.text,source:`event-log`,stableKey:s?`assistant:${s}`:rC(t),orderKey:tC(r,t.type,i,a),children:[]}}function LS(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=RS(n,t);return r===void 0||e.startedAt<=r}).sort(lS).at(-1);n&&(e.parentId=n.id)}function RS(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(lS).at(0)?.startedAt}function zS(e){return e.some(e=>{let t=e.payload.type;return t!==`assistant_delta`&&t!==`thinking_delta`})}function BS(e){if(e.type===`assistant_delta`){if(e.text.length===0)return;let t=oC(e);return t?aC(t):void 0}if(e.type===`thinking_delta`){if(e.text.length===0)return;let t=cC(e);return t?sC(t):void 0}}function VS(e,t){return!!HS(e,t)}function HS(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:t.eventId,i=typeof n.text==`string`?n.text:void 0;return fS([...e]).find(e=>e.type!==`user.message`||e.source!==`transcript`?!1:r&&(e.entryId===r||e.stableKey===`entry:${r}`)?!0:!!(i&&US(e)===i))}function US(e){if(typeof e.output==`string`)return e.output;if(typeof e.summary==`string`)return e.summary}function WS(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 GS(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 KS(e,t,n,r,i,a,o,s,c){let l=`eventId`in t&&typeof t.eventId==`string`?t.eventId:void 0,u=`event:${t.type}:${l??SC(t)}`,d=l?iC(l):void 0,f={id:u,piboSessionId:e,eventId:l,startedAt:a,source:`event-log`,stableKey:rC(t),orderKey:tC(o,t.type,s,c),children:[]};switch(t.type){case`message_queued`:case`message_steered`:{let n=OS(t.text);return t.source===`service`&&n?kS({id:u,piboSessionId:e,eventId:l,startedAt:a,source:`event-log`,stableKey:l?`run-notification:${l}`:u,orderKey:tC(o,t.type,s,c),notification:n}):{...f,...t.type===`message_steered`&&t.activeEventId?{parentId:iC(t.activeEventId)}:{},type:`user.message`,title:`User Message`,status:`done`,summary:t.text,output:t.text}}case`message_started`:case`message_finished`:return t.source===`service`?void 0:{...f,id:l?iC(l):u,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:l?`turn:${l}`:f.stableKey};case`thinking_finished`:{if(!vC(t.text))return;let e=cC(t);return{...f,id:e?sC(e):u,parentId:d,type:`model.reasoning`,title:`Thinking`,status:`done`,summary:t.text,output:t.text,stableKey:e?`reasoning:${e}`:f.stableKey}}case`assistant_message`:{let e=oC(t);return{...f,id:e?aC(e):u,parentId:d,type:`assistant.message`,title:`Agent Message`,status:`done`,completedAt:a,summary:t.text,output:t.text,stableKey:e?`assistant:${e}`:f.stableKey}}case`tool_call`:case`tool_execution_started`:case`tool_execution_updated`:case`tool_execution_finished`:{let o=hS(t.toolName),s=r.get(t.toolCallId)??(o?mS(e,t.toolName,t,n):void 0);return{...f,id:`tool:${t.toolCallId}`,parentId:d,toolCallId:t.toolCallId,type:o?`agent.delegation`:`tool.call`,title:t.toolName,status:t.type===`tool_execution_finished`?t.isError?`error`:`done`:i===`running`&&(t.type===`tool_execution_started`||t.type===`tool_execution_updated`)?`running`:`done`,completedAt:t.type===`tool_execution_finished`?a:void 0,input:`args`in t?t.args:void 0,output:t.type===`tool_execution_finished`?t.result:t.type===`tool_execution_updated`?t.partialResult:void 0,error:t.type===`tool_execution_finished`&&t.isError?yC(t.result):void 0,linkedPiboSessionId:s,stableKey:`tool:${t.toolCallId}`,children:[]}}case`subagent_session`:{let e=xC(t.childPiboSessionId),n=bC(o,s,t);return{...f,id:t.toolCallId?`tool:${t.toolCallId}`:`event:subagent_session:${n}`,eventId:l,toolCallId:t.toolCallId,type:`agent.delegation`,title:t.toolName,status:i===`running`?`running`:`done`,summary:t.subagentName,input:{subagentName:t.subagentName,threadKey:t.threadKey},linkedPiboSessionId:e,stableKey:t.toolCallId?`tool:${t.toolCallId}`:e?`subagent:${e}`:`subagent:event:${n}`,children:[]}}case`execution_result`:return ZS(t.action)?void 0:{...f,type:`execution.command`,title:t.action,status:`done`,input:{action:t.action},output:t.result};case`compaction_start`:{let e=bC(o,s,t);return{...f,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=bC(o,s,t);return{...f,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{...f,type:`error`,title:`Session Error`,status:`error`,summary:t.errorDetails?.userMessage,input:t.errorDetails,error:t.error,output:t.error};default:return}}function qS(e,t,n,r,i,a,o,s){if(typeof n.text!=`string`||n.text.length===0)return;let c=oC(n),l=c?aC(c):`event:assistant_delta:${SC(n)}`,u=t.get(l);if(u){let e=`${typeof u.output==`string`?u.output:``}${n.text}`;u.status=r===`running`?`running`:`done`,u.summary=e,u.output=e;return}let d={id:l,parentId:n.eventId?iC(n.eventId):void 0,piboSessionId:n.piboSessionId,eventId:n.eventId,type:`assistant.message`,title:`Agent Message`,status:r===`running`?`running`:`done`,startedAt:i,summary:n.text,output:n.text,source:`event-log`,stableKey:c?`assistant:${c}`:l,orderKey:tC(a,n.type,o,s),children:[]};e.push(d),t.set(d.id,d)}function JS(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 YS(e,t,n,r,i,a,o,s){if(typeof n.text!=`string`||n.text.length===0)return;let c=cC(n),l=c?sC(c):`event:thinking_delta:${SC(n)}`,u=t.get(l);if(u){let e=`${typeof u.output==`string`?u.output:``}${n.text}`;u.status=r===`running`?`running`:`done`,u.summary=e,u.output=e;return}let d={id:l,parentId:n.eventId?iC(n.eventId):void 0,piboSessionId:n.piboSessionId,eventId:n.eventId,type:`model.reasoning`,title:`Thinking`,status:r===`running`?`running`:`done`,startedAt:i,summary:n.text,output:n.text,source:`event-log`,stableKey:c?`reasoning:${c}`:l,orderKey:tC(a,n.type,o,s),children:[]};e.push(d),t.set(d.id,d)}function XS(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 ZS(e){return e===`session.fork`||e===`session.clone`||e===`session.switch`}function QS(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 $S(e,t){let n=`eventId`in e&&typeof e.eventId==`string`?e.eventId:void 0;return!!(n&&t.has(n))}function eC(e,t){return t!==`running`&&e.type===`tool_call`}function tC(e,t,n,r){return e===void 0&&(n!==void 0||r!==void 0)?rS(n,r,nC(t)):nS(e,nC(t))}function nC(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 rC(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=cC(e);if(t)return`reasoning:${t}`}if(e.type===`assistant_delta`||e.type===`assistant_message`){let t=oC(e);if(t)return`assistant:${t}`}return`event:${e.type}:${t??SC(e)}`}function iC(e){return`event:message:${e}`}function aC(e){return`event:assistant:${e}`}function oC(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 sC(e){return`event:thinking:${e}`}function cC(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 lC(e,t){e.status=t.status,e.summary=t.summary??e.summary,e.input=mC(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 uC(e,t){e.summary=t.summary??e.summary,e.input=mC(e,t),e.linkedPiboSessionId=t.linkedPiboSessionId??e.linkedPiboSessionId}function dC(e,t){let n=[...e].reverse().filter(e=>e.type===`agent.delegation`),r=fC(t),i=n.filter(e=>!e.linkedPiboSessionId&&fC(e)===r),a=pC(t.input);return(a?i.find(e=>pC(e.input)===a):i.length===1?i[0]:void 0)||n.find(e=>e.linkedPiboSessionId===t.linkedPiboSessionId)}function fC(e){let t=hC(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 pC(e){if(!(!hC(e)||typeof e.threadKey!=`string`))return e.threadKey.trim()||void 0}function mC(e,t){return e.type!==`agent.delegation`||!hC(e.input)||!hC(t.input)?t.input??e.input:Object.fromEntries(Object.entries({...e.input,...t.input}).filter(([,e])=>e!==void 0))}function hC(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function gC(e){return fS([...e]).reverse().find(e=>e.type===`execution.compaction`&&e.status===`running`)}function _C(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 vC(e){return typeof e==`string`&&e.trim().length>0}function yC(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}function bC(e,t,n){return e===void 0?t===void 0?SC(n):`stream:${t}`:`sequence:${e}`}function xC(e){if(typeof e==`string`)return e.trim()||void 0}function SC(e){return CC(new TextEncoder().encode(JSON.stringify(e))).slice(0,48)}function CC(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 wC(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 sS(n)}function TC(e,t,n){return t.map(t=>EC(e,t,n))}function EC(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)||DC(r,t))?r:e?{...t,children:r.children}:{...t,children:[]}}let i=t.children.map(t=>EC(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)||DC(r,t))?r:a?{...t,children:r?.children??i}:{...t,children:i}}function DC(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&&OC(e.orderKey,t.orderKey)}function OC(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 kC(e,t,n){if(!t.length)return e;let r=new Set(e.rawEvents.map(e=>WS(e))),i=[];for(let e of t){let t=WS(e);r.has(t)||(r.add(t),i.push(e))}if(!i.length)return e;let a=fS(e.nodes),o=[],s=new Map,c=new Map;for(let e of a){c.set(e.id,e);let t={...e,children:[]};o.push(t),s.set(t.id,t)}let l=new Map,u=new Map,d=new Set,f=[],p=new Set;for(let t of i){if(VS(o,t))continue;f.push(t);let r=BS(t.payload);p&&r?p.add(r):p=void 0,FS(o,s,e.piboSessionId,t,l,u,!1,d,n)}if(!f.length)return e;let m=wC(o);zS(f)&&yS(m);let h=TC(c,m,p);return{...e,rawEvents:e.rawEvents.length?[...e.rawEvents,...f]:f,nodes:h,latestStreamId:GS(f,e.latestStreamId)}}function AC(e,t){if(!e)return[];let n=NC(e.nodes),r=fw(PC(e.nodes).sort((e,t)=>lS(e.node,t.node)).filter(e=>e.node.type!==`agent.turn`&&(t.showThinking||e.node.type!==`model.reasoning`)).map(e=>FC(e.node,e.turnId)));return zC(r,n),hw(RC(r)).map(e=>e.row)}function jC(e){if(!e)return;let t=new Set(PC(e.nodes).map(({node:e})=>e).filter(e=>e.type===`error`&&e.eventId).map(e=>e.eventId));return[...NC(e.nodes).values()].filter(e=>e.startedAt&&!e.completedAt&&(!e.eventId||!t.has(e.eventId))).sort(lS).at(-1)?.startedAt}function MC(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 NC(e){let t=new Map;for(let n of e){n.type===`agent.turn`&&t.set(n.id,n);for(let[e,r]of NC(n.children))t.set(e,r)}return t}function PC(e,t){let n=[];for(let r of e)r.type!==`agent.turn`&&n.push({node:r,turnId:t}),n.push(...PC(r.children,r.type===`agent.turn`?r.id:t));return n}function FC(e,t){let n;switch(e.type){case`user.message`:n={row:HC(e),turnId:t};break;case`assistant.message`:n={row:UC(e),turnId:t};break;case`model.reasoning`:n={row:WC(e),turnId:t};break;case`tool.call`:n=GC(e,t);break;case`tool.result`:n=JC(e,t);break;case`agent.delegation`:n={row:XC(e),turnId:t};break;case`agent.async`:n={row:ZC(e),turnId:t};break;case`yielded.run`:n={row:QC(e),turnId:t};break;case`execution.command`:n={row:ew(e),turnId:t};break;case`execution.compaction`:n={row:$C(e),turnId:t};break;case`error`:n={row:uw(e),turnId:t};break;case`agent.turn`:n={row:{id:e.id,kind:`error`,status:`neutral`,lines:[],sourceNodeIds:[e.id]},turnId:t};break}return{...n,row:{...n.row,id:IC(e),...VC(e)}}}function IC(e){if(e.type===`tool.call`||e.type===`tool.result`||e.type===`agent.delegation`){let t=e.toolCallId??LC(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=LC(e.stableKey,`assistant:`);if(t)return`terminal:assistant:${t}`}if(e.type===`model.reasoning`){let t=LC(e.stableKey,`reasoning:`);if(t)return`terminal:reasoning:${t}`}return e.id}function LC(e,t){if(!e?.startsWith(t))return;let n=e.slice(t.length);return n&&n!==`undefined`?n:void 0}function RC(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 zC(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??BC(n.startedAt,n.completedAt))}}function BC(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 VC(e){return{eventId:e.eventId,runId:e.runId,orderSource:e.source,orderStreamId:e.orderKey?.streamId,orderStreamFrameIndex:e.orderKey?.streamFrameIndex,payloadRefs:e.payloadRefs}}function HC(e){let t=Yw(e.output)||Yw(e.summary)||e.title;return{id:e.id,kind:`message.user`,status:qw(e.status),lines:[{prefix:`prompt`,tokens:[$(t)]}],sourceNodeIds:[e.id],forkEntryId:e.entryId,startedAt:e.startedAt,output:t,payloadRefs:e.payloadRefs}}function UC(e){return{id:e.id,kind:`message.assistant`,status:qw(e.status),lines:[],sourceNodeIds:[e.id],startedAt:e.startedAt,completedAt:e.source===`transcript`?e.completedAt:void 0,durationMs:e.source===`transcript`?e.durationMs:void 0,output:Yw(e.output)||Yw(e.summary)||``,error:e.error,payloadRefs:e.payloadRefs}}function WC(e){let t=Fw(e.output??e.summary);return{id:e.id,kind:`reasoning`,status:qw(e.status),lines:[{prefix:`bullet`,tokens:[$(e.status===`running`?`Thinking`:`Thought`,`amber`,`semibold`)]}],sourceNodeIds:[e.id],markdown:t,payloadRefs:e.payloadRefs}}function GC(e,t){let n=Hw(e.input);if(n&&Lw(e.title))return{row:lw(e,n),turnId:t,exploring:void 0};if(Rw(e.title))return{row:KC(e),turnId:t};let r=bw(e);if(r)return{row:qC(e,r),turnId:t,image:r.groupable?r.detail:void 0};let i=Nw(e.error??e.output,5,e.error?`red`:`dim`);return{row:{id:e.id,kind:`tool.call`,status:qw(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(Ww(e.status),Jw(e.status),`semibold`),$(` `)],functionCall:{name:e.title,input:e.input}},...i.lines],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:e.input!==void 0||e.output!==void 0||!!e.error,previewOmission:Pw(i,e.error?`error`:`output`)},turnId:t,exploring:Ow(e)}}function KC(e){let t=qw(e.status),n=Bw(e),r=Vw(e.output),i=[{prefix:`bullet`,tokens:[$(zw(e.status),Jw(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 qC(e,t){let n=qw(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,Jw(e.status),`semibold`)]},{prefix:`detail`,tokens:[$(r,e.status===`error`?`red`:`cyan`)]}],sourceNodeIds:[e.id],input:Sw(e.input),output:t.summary,error:e.error,expandable:e.input!==void 0||t.summary!==void 0||!!e.error}}function JC(e,t){let n=bw(e);return n?{row:qC(e,n),turnId:t,image:n.groupable?n.detail:void 0}:{row:YC(e),turnId:t}}function YC(e){let t=Nw(e.error??e.output,5,e.error?`red`:`dim`);return{id:e.id,kind:`tool.call`,status:qw(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(e.status===`error`?`Tool failed`:`Returned`,Jw(e.status),`semibold`),$(` ${e.title}`)]},...t.lines],sourceNodeIds:[e.id],output:e.output,error:e.error,expandable:e.output!==void 0||!!e.error,previewOmission:Pw(t,e.error?`error`:`output`)}}function XC(e){let t=Yw(Xw(e.input)?e.input.subagentName:void 0)||e.summary||e.title,n=Iw((Xw(e.input)?e.input.arguments:void 0)??e.input),r=n?[{prefix:`detail`,tokens:[$(n,`dim`)]}]:[];return{id:e.id,kind:`agent.delegation`,status:qw(e.status),errorKind:e.status===`error`?`tool`:void 0,title:e.title,summary:e.summary,lines:[{prefix:`bullet`,tokens:[$(Gw(e.status),Jw(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 ZC(e){let t=Nw(e.error??e.output,5,e.error?`red`:`dim`);return{id:e.id,kind:`agent.async`,status:qw(e.status),lines:[{prefix:`bullet`,tokens:[$(Kw(e.status),Jw(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:Pw(t,e.error?`error`:`output`)}}function QC(e){let t=Nw(e.output,5);return{id:e.id,kind:`yielded.run`,status:qw(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(e.status===`running`?`Waiting on runs`:`Run update`,Jw(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:Pw(t,`output`)}}function $C(e){let t=e.status===`running`?`Compacting`:e.status===`error`?`Compaction failed`:Yw(e.summary)||`Compacted`;return{id:e.id,kind:`execution.compaction`,status:qw(e.status),lines:[{prefix:`bullet`,tokens:[$(t,Jw(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 ew(e){if(e.title===`status`)return tw(e);if(e.title===`thinking`)return mw(e.output)?rw(e):nw(e);if(e.title===`fast_mode`)return iw(e);if(e.title===`login`&&sw(e.output))return aw(e);if(e.title===`model`&&cw(e.output))return ow(e);Hw(e.output)??Hw(e.input)??e.title;let t=Nw(e.error??e.output,5,e.error?`red`:`dim`,180);return{id:e.id,kind:`execution.command`,status:qw(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:Pw(t,e.error?`error`:`output`)}}function tw(e){return{id:e.id,kind:`tool.status`,status:qw(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function nw(e){return{id:e.id,kind:`tool.thinking`,status:qw(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function rw(e){let t=Xw(e.output)?e.output:void 0,n=Yw(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:qw(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 iw(e){let t=Xw(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:qw(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 aw(e){return{id:e.id,kind:`tool.login`,status:qw(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function ow(e){return{id:e.id,kind:`tool.model`,status:qw(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function sw(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 cw(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 lw(e,t){let n=Nw(e.error??e.output,5,e.error?`red`:`dim`,180);return{id:e.id,kind:`execution.command`,status:qw(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(e.status===`running`?`Running`:`Ran`,Jw(e.status),`semibold`),$(` `),...Uw(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:Pw(n,e.error?`error`:`output`)}}function uw(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`)]},...dw(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 dw(e){return Xw(e)?[[`Class`,Yw(e.errorClass)??Yw(e.category)],[`Code`,Yw(e.code)??Yw(e.providerCode)],[`Origin`,Yw(e.origin)],[`Provider`,[Yw(e.api),Yw(e.provider),Yw(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 fw(e){let t=e.map(e=>e.row.output).filter(pw).at(-1);return t?e.map(e=>e.row.kind!==`tool.thinking`||!Xw(e.row.output)?e:{...e,row:{...e.row,output:{...e.row.output,level:t.level,availableLevels:t.availableLevels,supported:t.supported}}}):[...e]}function pw(e){return Xw(e)&&typeof e.level==`string`&&Array.isArray(e.availableLevels)}function mw(e){return Xw(e)&&e.action===`set_thinking_level`}function hw(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n],i=gw(r);if(!i){t.push(r);continue}let a=[r],o=n+1;for(;o<e.length&&gw(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`?vw(a):_w(a),turnId:r.turnId}),n=o-1}return t}function gw(e){if(e.image)return`images`;if(e.exploring)return`exploring`}function _w(e){let t=yw(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`,Jw(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 vw(e){let t=yw(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`,Jw(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 yw(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 bw(e){let t=(e.title??``).trim().toLowerCase(),n=Xw(e.input)?e.input:void 0,r=Xw(e.output)?e.output:void 0,i=Dw(r,`details`),a=t===`codex_image_generation`?ww(i)??Tw(n):void 0,o=a?Yw(i?.savedPath)??Aw(i):Aw(n)??Aw(i)??Aw(r),s=a?Yw(i?.artifactId):void 0,c=jw(n),l=xw(e.output),u=kw(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?Yw(i?.model):void 0,referencedImageCount:a?Mw(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?Ew(e.status,a):Cw(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:qw(e.status),input:Sw(e.input),output:p,error:e.error}}}function xw(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=>xw(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`||Xw(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=>xw(e,t+1,n))}function Sw(e){if(Array.isArray(e))return e.map(Sw);if(!Xw(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]=Sw(r)}return t}function Cw(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 ww(e){let t=Yw(e?.operation);return t===`generate`||t===`edit`?t:void 0}function Tw(e){if(!e)return;let t=e.referenced_image_paths;return Array.isArray(t)&&t.length>0||Mw(e.num_last_images_to_include)!==void 0?`edit`:`generate`}function Ew(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 Dw(e,t){let n=e?.[t];return Xw(n)?n:void 0}function Ow(e){let t=(e.title??``).trim().toLowerCase(),n=Xw(e.input)?e.input:void 0;if(kw(t,[`read`,`open`]))return{id:e.id,label:`Read ${Aw(n)??Iw(e.input)}`,status:qw(e.status),input:e.input,output:e.output,error:e.error};if(kw(t,[`list`,`ls`,`glob`]))return{id:e.id,label:`List ${Aw(n)??Iw(e.input)}`,status:qw(e.status),input:e.input,output:e.output,error:e.error};if(kw(t,[`search`,`find`,`grep`,`rg`])){let t=jw(n),r=Aw(n);return{id:e.id,label:`Search ${t??Iw(e.input)}${r?` in ${r}`:``}`,status:qw(e.status),input:e.input,output:e.output,error:e.error}}}function kw(e,t){return t.some(t=>e===t||e.startsWith(`${t}_`)||e.endsWith(`_${t}`)||e.includes(t))}function Aw(e){if(e)for(let t of[`path`,`file`,`filePath`,`filepath`,`url`,`uri`,`cwd`,`pattern`,`glob`]){let n=Yw(e[t]);if(n)return n}}function jw(e){if(e)for(let t of[`query`,`pattern`,`text`,`name`,`q`,`regex`]){let n=Yw(e[t]);if(n)return n}}function Mw(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Nw(e,t,n=`dim`,r=160){let i={lines:[],visibleLineCount:0,omittedLineCount:0,totalLineCount:0,maxVisibleLineCount:t},a=Fw(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 Pw(e,t){if(!(e.omittedLineCount<=0))return{source:t,visibleLineCount:e.visibleLineCount,omittedLineCount:e.omittedLineCount,totalLineCount:e.totalLineCount,maxVisibleLineCount:e.maxVisibleLineCount}}function Fw(e){let t=Nb(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 Iw(e){return(typeof e==`string`?e:Fw(e)).replace(/\s+/g,` `).trim()}function Lw(e){let t=(e??``).trim().toLowerCase();return t===`shell`||t===`bash`||t===`terminal`}function Rw(e){return(e??``).trim().toLowerCase()===`web_search`}function zw(e){return e===`running`?`Searching web`:e===`error`?`Web search failed`:`Searched web`}function Bw(e){let t=Xw(e.input)?e.input:void 0,n=Xw(e.output)?e.output:void 0;return Yw(t?.query)??Yw(n?.query)??Yw(e.summary)}function Vw(e){if(!Xw(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 Hw(e){if(Xw(e))for(let t of[`cmd`,`command`,`script`]){let n=Yw(e[t]);if(n)return n}}function Uw(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 Ww(e){return e===`running`?`Calling`:e===`error`?`Call failed`:`Called`}function Gw(e){return e===`running`?`Spawning`:e===`error`?`Spawn failed`:`Spawned`}function Kw(e){return e===`running`?`Waiting for`:`Finished waiting for`}function qw(e){return e===`running`?`running`:e===`error`?`error`:`done`}function Jw(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 Yw(e){return typeof e==`string`&&e.trim().length?e:void 0}function Xw(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Zw(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 Qw(e,t,n){return n?{id:e,label:t,value:n}:void 0}function $w({field:e,icon:t}){let n=t===`session`?$e:Ye;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 eT({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 tT(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 nT({row:e}){let t=Zw(e.output),n=zx(e),r=n?.kind===`status`?n.statusView:void 0,[i,a]=(0,v.useState)(!1);if(!t||!r)return(0,I.jsx)(`div`,{className:`mt-2 border border-[#2a2a2a] bg-[#111111] px-3 py-2 text-[12px] text-[#d4d4d4]`,"data-pibo-component":`TerminalStatusCard`,"data-pibo-debug":`terminal-status-card`,"data-shared-terminal-card":`status`,children:(0,I.jsx)(`div`,{className:`text-[#737373]`,children:`Status (unparseable)`})});let o=new Map(r.fields.map(e=>[e.id,e])),s=o.get(`session`)??Qw(`session`,`Session`,t.piboSessionId),c=o.get(`cwd`)??Qw(`cwd`,`CWD`,t.cwd),l=r.progress.find(e=>e.id===`context`),u=r.progress.filter(e=>e.id.startsWith(`provider`)),d=t.providerUsage?.limits.length?t.providerUsage.limits:void 0,f=t.enabledTools??t.activeTools??[],p=r.fields.filter(e=>!new Set([`session`,`cwd`]).has(e.id)),m=t.providerUsage?.provider?`${t.providerUsage.provider} quota`:`Provider quota`;return(0,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)(xe,{size:14,className:`text-[#22c55e]`}),(0,I.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:r.title})]}),(0,I.jsxs)(`div`,{className:`grid grid-cols-1 gap-1.5 sm:grid-cols-2`,children:[s?(0,I.jsx)($w,{field:s,icon:`session`}):null,c?(0,I.jsx)($w,{field:c,icon:`cwd`}):null,p.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:[t.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)(We,{size:10}),` Processing`]}):null,t.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)(xe,{size:10}),` Streaming`]}):null,typeof t.queuedMessages==`number`&&t.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)(nt,{size:10}),` Queued: `,t.queuedMessages]}):null,t.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]}),l?(0,I.jsx)(eT,{progress:l,label:`Context Usage`}):null,u.length?(0,I.jsxs)(`div`,{className:`mt-3 space-y-1.5 border-t border-[#2a2a2a] pt-2`,"data-shared-provider-progress":u.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)(Xe,{size:11}),(0,I.jsxs)(`span`,{children:[m,t.providerUsage?.planType?` (${t.providerUsage.planType})`:``]})]}),d?d.map(e=>{let t=tT(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??``}`)}):u.map(e=>(0,I.jsx)(eT,{progress:e},e.id)),t.providerUsage?.credits?(0,I.jsxs)(`div`,{className:`text-[11px] text-[#a3a3a3]`,"data-shared-status-field":`provider-credits`,children:[`Credits: `,t.providerUsage.credits.unlimited?`unlimited`:t.providerUsage.credits.balance??`available`]}):null]}):null,r.warnings.length||r.errors.length?(0,I.jsxs)(`div`,{className:`mt-3 space-y-1 border-t border-[#2a2a2a] pt-2`,children:[r.warnings.map((e,t)=>(0,I.jsxs)(`div`,{"data-shared-status-warning":!0,className:`text-[11px] text-[#facc15]`,children:[`⚠ `,e]},`warning-${t}`)),r.errors.map((e,t)=>(0,I.jsxs)(`div`,{"data-shared-status-error":!0,className:`text-[11px] text-[#ef4444]`,children:[`✕ `,e]},`error-${t}`))]}):null,f.length>0?(0,I.jsxs)(`div`,{className:`mt-3`,children:[(0,I.jsxs)(`button`,{type:`button`,onClick:()=>a(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:i?`▾`:`▸`}),(0,I.jsxs)(`span`,{children:[`Enabled tools (`,f.length,`)`]})]}),i?(0,I.jsx)(`div`,{className:`mt-1.5 flex flex-wrap gap-1`,children:f.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 rT=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function iT(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 aT(e){return rT.includes(e)?e:void 0}function oT({row:e,onLevelSelect:t}){let n=iT(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)(Oe,{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)(_t,{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)(Ae,{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=aT(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 sT=`pibo.chat.terminalReadingPosition.`;function cT(e){if(e)try{return uT(sessionStorage.getItem(sT+e))}catch{return}}function lT(e,t){if(e)try{let n=sT+e;t?sessionStorage.setItem(n,JSON.stringify(t)):sessionStorage.removeItem(n)}catch{}}function uT(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 dT=180,fT=4800,pT=20,mT={index:`LAST`,align:`end`},hT={top:2400,bottom:2400},gT=84,_T=700,vT=6;function yT({traceView:e,isLoading:t,showThinking:n,expandThinking:r,sessionAgentProfile:i,sessionActiveModel:a,selectedSessionStatus:o,selectedSessionSignal:s,signals:c,sessionBreadcrumbs:l,originSession:u,derivedSessions:d,agentProfiles:f,sessionProfileChangeDisabled:p,onSessionAgentProfileChange:m,onFork:h,onOpenSession:g,onLoadOlderTracePage:_,hasOlderTraceEvents:y,isFetchingOlderTracePage:b,onThinkingLevelChange:x,onModelChanged:S}){let C=(0,v.useMemo)(()=>AC(e,{showThinking:n}),[n,e]),w=(0,v.useMemo)(()=>C.map(e=>e.id),[C]),T=e?.piboSessionId??``,[E,D]=(0,v.useState)(),O=(0,v.useRef)(void 0),[k,ee]=(0,v.useState)(new Set),A=(0,v.useMemo)(()=>[C,k],[k,C]),[te,ne]=(0,v.useState)(null),re=(0,v.useRef)({}),ie=(0,v.useRef)(!1),j=(0,v.useRef)(!1),M=(0,v.useRef)(void 0),ae=(0,v.useRef)(!1),oe=(0,v.useRef)(()=>void 0),se=C.filter(e=>AT(e,`user`)).length,ce=C.filter(e=>AT(e,`tool`)).length,N=C.filter(e=>AT(e,`system`)).length,le=jb({signal:s,fallbackStatus:o,fallbackTurnStartedAt:(0,v.useMemo)(()=>jC(e),[e])}),ue=le.activeTurnStartedAt,de=le.isTurnActive,P=(0,v.useCallback)(()=>{if(!y||b||ae.current)return;let e=()=>{M.current=void 0,!ae.current&&(ae.current=!0,j.current=!1,oe.current(),_?.())};if(!j.current){e();return}M.current===void 0&&(M.current=window.setTimeout(e,_T))},[y,b,_]),fe=(0,v.useCallback)(()=>{ie.current&&j.current&&P()},[P]),pe=(0,v.useCallback)(()=>{ie.current&&P()},[P]),me=(0,v.useCallback)(e=>{QT(e)&&(j.current=!0)},[]),he=(0,v.useCallback)(e=>{ie.current&&(e.startIndex<=0?pe():e.startIndex<=pT&&fe())},[pe,fe]),ge=(0,v.useCallback)(e=>{T&&lT(T,e?{rowId:e.key,offsetPx:e.offset}:void 0)},[T]),_e=Ra({itemCount:C.length,itemKeys:w,isPrepending:b,resetKey:e?.piboSessionId,contentKey:A,atBottomThreshold:dT,nearTopThreshold:fT,onAtTop:pe,onNearTop:fe,onUserScrollIntent:me,onVisibleAnchorChange:ge});oe.current=_e.prepareForPrepend,(0,v.useEffect)(()=>{O.current=void 0,ae.current=!1,D(T?cT(T):void 0)},[T]),(0,v.useEffect)(()=>{ae.current=!1},[e?.nextBeforeCursor,e?.nextBeforeSequence]),(0,v.useEffect)(()=>()=>{M.current!==void 0&&window.clearTimeout(M.current)},[]),(0,v.useEffect)(()=>{if(!T||!E)return;let t=w.indexOf(E.rowId);if(t>=0){let e=requestAnimationFrame(()=>{_e.restoreAnchor({key:E.rowId,dataIndex:t,offset:E.offsetPx})&&D(void 0)});return()=>cancelAnimationFrame(e)}if(!y){lT(T,void 0),D(void 0);return}if(b)return;let n=`${T}:${String(e?.nextBeforeCursor??e?.nextBeforeSequence??C.length)}`;O.current!==n&&(O.current=n,_?.())},[y,b,_,T,E,w,C.length,_e.restoreAnchor,e?.nextBeforeCursor,e?.nextBeforeSequence]),(0,v.useEffect)(()=>{if(!T)return;let e=()=>{_e.captureVisibleAnchor()};return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[T,_e.captureVisibleAnchor]),(0,v.useEffect)(()=>{ee(e=>kT(e,C,r))},[r,C]),(0,v.useEffect)(()=>{b||_e.isScrolledToTop()&&pe()},[y,b,pe,C.length,_e.isScrolledToTop,e?.nextBeforeCursor,e?.nextBeforeSequence]),(0,v.useEffect)(()=>{ie.current=!1,j.current=!1;let e=window.setTimeout(()=>{ie.current=!0,_e.isScrolledToTop()&&pe()},250);return()=>window.clearTimeout(e)},[pe,_e.isScrolledToTop,e?.piboSessionId]),(0,v.useEffect)(()=>{let e=new Set(C.map(e=>e.id));ne(t=>t&&e.has(t)?t:null);for(let t of[`system`,`tool`,`user`]){let n=re.current[t];n&&!e.has(n)&&delete re.current[t]}},[C]);let ve=(0,v.useCallback)(e=>{let t=jT(C,e,re.current[e]);t&&(re.current[e]=t.row.id,ne(t.row.id),_e.scrollToIndex(t.index,`start`,`fast-smooth`,{fromIndex:t.fromIndex,stagingAlign:e===`tool`?`end`:void 0}),MT(t.row.id))},[C,_e]),ye=e=>{e.expandable&&ee(t=>{let n=new Set(t);return n.has(e.id)?n.delete(e.id):n.add(e.id),n})},be=(0,v.useCallback)((t,n)=>(0,I.jsx)(`div`,{className:`px-4`,children:(0,I.jsx)(ST,{row:n,expanded:k.has(n.id),focused:te===n.id,piboSessionId:e?.piboSessionId??``,onToggle:()=>ye(n),onFork:h,onOpenSession:g,onThinkingLevelChange:x,onModelChanged:S,signals:c})}),[k,te,h,S,g,x,c,e?.piboSessionId]),F=(0,v.useMemo)(()=>({Footer:de?()=>(0,I.jsx)(zT,{startedAt:ue}):void 0}),[ue,de]);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-trace-has-older":e?.hasOlderEvents===!0?`true`:`false`,"data-pibo-trace-next-before":e?.nextBeforeCursor??e?.nextBeforeSequence??``,children:[(0,I.jsx)(bT,{errorCount:N,toolErrorCount:ce,userMessageCount:se,onNavigate:ve,sessionAgentProfile:i,sessionActiveModel:a,sessionBreadcrumbs:l,originSession:u,derivedSessions:d,onOpenSession:g}),(0,I.jsx)(`div`,{className:`min-h-0 flex-1 overflow-hidden`,children:e?C.length?(0,I.jsx)(Ri,{ref:_e.virtuosoRef,data:C,firstItemIndex:_e.firstItemIndex,initialTopMostItemIndex:mT,increaseViewportBy:hT,defaultItemHeight:gT,className:`min-h-0 h-full overflow-x-hidden font-mono text-[12px] leading-[1.45]`,computeItemKey:(e,t)=>t.id,scrollerRef:_e.scrollerRef,atBottomStateChange:_e.atBottomStateChange,atBottomThreshold:_e.atBottomThreshold,atTopStateChange:e=>{e&&pe()},itemsRendered:_e.itemsRendered,rangeChanged:e=>he(_e.normalizeRange(e)),startReached:pe,followOutput:_e.followOutput,totalListHeightChanged:_e.totalListHeightChanged,alignToBottom:!0,components:F,itemContent:be},e.piboSessionId):(0,I.jsx)(XT,{isLoading:t,agentProfiles:f,disabled:p,onSelectAgentProfile:m,message:`No visible trace rows yet.`}):(0,I.jsx)(XT,{isLoading:t,agentProfiles:f,disabled:p,onSelectAgentProfile:m})}),_e.isSticky?null:(0,I.jsx)(`button`,{type:`button`,onClick:()=>{lT(T,void 0),_e.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)(je,{size:18})})]})}function bT({errorCount:e,toolErrorCount:t,userMessageCount:n,onNavigate:r,sessionAgentProfile:i,sessionActiveModel:a,sessionBreadcrumbs:o,originSession:s,derivedSessions:c,onOpenSession:l}){return(0,I.jsxs)(`div`,{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)(JT,{tone:`neutral`,children:i}):null,a?(0,I.jsx)(JT,{tone:`purple`,children:a}):null,n>0?(0,I.jsxs)(JT,{tone:`cyan`,label:`${n} user messages · jump to previous user message`,onClick:()=>r(`user`),children:[n,(0,I.jsx)(st,{size:12})]}):null,e>0?(0,I.jsxs)(JT,{tone:`red`,label:`${e} errors · jump to previous error`,onClick:()=>r(`system`),children:[e,(0,I.jsx)(Be,{size:12})]}):null,t>0?(0,I.jsxs)(JT,{tone:`amber`,label:`${t} tool call errors · jump to previous tool error`,onClick:()=>r(`tool`),children:[t,(0,I.jsx)(Qe,{size:12})]}):null,s?(0,I.jsxs)(xT,{onClick:()=>l(s.piboSessionId),children:[`Origin `,s.label]}):null,c.map(e=>(0,I.jsxs)(xT,{onClick:()=>l(e.piboSessionId),children:[`Derived `,e.label]},e.piboSessionId))]}),o.length?(0,I.jsx)(`div`,{className:`mt-2 flex flex-wrap items-center gap-1 text-[#737373]`,children:o.map((e,t)=>(0,I.jsxs)(`div`,{className:`flex items-center gap-1`,children:[t>0?(0,I.jsx)(Me,{size:12,className:`text-[#525252]`}):null,(0,I.jsx)(`button`,{type:`button`,onClick:()=>l(e.piboSessionId),className:`hover:text-[#38bdf8]`,children:e.label})]},e.piboSessionId))}):null]})}function xT({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 ST({row:e,expanded:t,focused:n,piboSessionId:r,onToggle:i,onFork:a,onOpenSession:o,onThinkingLevelChange:s,onModelChanged:c,signals:l}){let u=!t&&PT(e),d=u?NT(e):e.lines;return e.kind===`agent.delegation`?(0,I.jsx)(`div`,{className:OT(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)(nl,{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:OT(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||FT(t)||i()}:void 0,onKeyDown:e.expandable?t=>{!e.expandable||FT(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)(CT,{row:e,visibleLines:d,collapseToolCallPreview:u,piboSessionId:r,onThinkingLevelChange:s,onModelChanged:c})}),(0,I.jsx)(DT,{row:e,onFork:a,onOpenSession:o})]}),t?(0,I.jsx)(Hb,{row:e,onOpenSession:o}):null]})}function CT({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)(Xy,{streaming:e.status===`running`,children:typeof e.output==`string`?e.output:``})}),e.status===`running`?null:(0,I.jsx)(TT,{timestamp:e.completedAt,durationMs:e.durationMs})]}):e.kind===`message.user`?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(wT,{lines:t,status:e.status,clampPreview:n}),(0,I.jsx)(TT,{timestamp:e.startedAt})]}):e.kind===`tool.status`?(0,I.jsx)(nT,{row:e}):e.kind===`tool.thinking`?(0,I.jsx)(oT,{row:e,onLevelSelect:i}):e.kind===`tool.login`?(0,I.jsx)(wx,{row:e,piboSessionId:r}):e.kind===`tool.model`?(0,I.jsx)(Ax,{row:e,piboSessionId:r,onModelChanged:a}):e.kind===`execution.compaction`&&e.status===`running`?(0,I.jsx)(KT,{}):e.kind===`reasoning`&&e.markdown?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(wT,{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)(Xy,{streaming:e.status===`running`,children:e.markdown})})})]}):(0,I.jsx)(wT,{lines:t,status:e.status,clampPreview:n})}function wT({lines:e,status:t,clampPreview:n}){return e.map((e,r)=>(0,I.jsx)(sx,{line:e,status:t,clampLines:n&&r===0?5:void 0},r))}function TT({timestamp:e,durationMs:t}){let n=ET(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:` · ${MC(t)}`]}):null}function ET(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 DT({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)(YT,{label:`Open linked session`,onClick:()=>n(e.linkedPiboSessionId),children:`Open`}):null,e.forkEntryId?(0,I.jsxs)(YT,{label:`Fork from this user message`,onClick:()=>t(e.forkEntryId),children:[(0,I.jsx)(Ze,{size:13}),`Fork`]}):null]})}function OT(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 kT(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 ZT(e,r)?e:r}function AT(e,t){return t===`user`?e.kind===`message.user`:e.status===`error`?t===`tool`?e.errorKind===`tool`:e.errorKind!==`tool`:!1}function jT(e,t,n){let r=e.map((e,t)=>({row:e,index:t})).filter(({row:e})=>AT(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 MT(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 NT(e){return e.kind===`tool.group.exploring`||e.kind===`tool.group.images`?e.lines.slice(0,vT):e.lines}function PT(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 FT(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 IT=`Working...`,LT=33,RT=126;function zT({startedAt:e}){let{chars:t,activeIndex:n}=VT(IT),r=BT(e);return(0,I.jsx)(`div`,{className:`border-t border-[#141414] px-4 py-2`,role:`status`,"aria-live":`polite`,"aria-label":`Working`,"data-pibo-component":`TerminalStreamingFooter`,"data-pibo-active-turn-started-at":e,children:(0,I.jsxs)(`div`,{className:`grid grid-cols-[1.9rem_minmax(0,1fr)] gap-2 whitespace-pre-wrap break-words`,"aria-hidden":`true`,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-scramble`,children:t.map((e,t)=>(0,I.jsx)(`span`,{className:t===n?`compact-terminal-working-scramble-active`:void 0,children:e},t))})]})]})})}function BT(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)?MC(Math.max(0,n-t)):void 0}function VT(e){let t=(0,v.useMemo)(()=>Array.from(e),[e]),[n,r]=(0,v.useState)(()=>UT(t)),[i,a]=(0,v.useState)(0);return(0,v.useEffect)(()=>{let e=0,n=0,i=GT(),o=0;r(UT(t));let s=window.setInterval(()=>{if(o>0){o--;return}if(e>=t.length){e=0,n=0,i=GT(),r(UT(t)),a(0);return}let s=e,c=t[s]??` `;if(a(s),n++,n<i){r(e=>HT(e,s,WT(c)));return}r(e=>HT(e,s,c)),e++,n=0,i=GT(),e>=t.length&&(r(t),a(-1),o=18)},55);return()=>window.clearInterval(s)},[t]),{chars:n,activeIndex:i}}function HT(e,t,n){let r=[...e];return r[t]=n,r}function UT(e){return e.map(e=>WT(e))}function WT(e){let t=``;do{let e=LT+Math.floor(Math.random()*(RT-LT+1));t=String.fromCharCode(e)}while(t===e);return t}function GT(){return 2+Math.floor(Math.random()*11)}function KT(){let e=qT();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 qT(){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 JT({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 YT({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 XT({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 ZT(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function QT(e){return e instanceof WheelEvent?e.deltaY<0:e instanceof KeyboardEvent?[`ArrowUp`,`PageUp`,`Home`].includes(e.key):e?.type===`touchmove`}function $T({traceView:e,isLoading:t,selectedSessionStatus:n,selectedSessionSignal:r,workflowProjectSession:i,workflowLifecycleEvents:a,sessionNodes:o,onOpenSession:s,onRefreshBootstrap:c,onError:l}){let u=i?yE(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)(eE,{model:u}),(0,I.jsx)(tE,{}),(0,I.jsx)(nE,{model:u,onRefreshBootstrap:c,onError:l}),(0,I.jsx)(iE,{model:u}),(0,I.jsx)(aE,{model:u,onOpenSession:s}),(0,I.jsx)(fE,{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)(mE,{model:u}),(0,I.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-4`,children:[(0,I.jsx)(hE,{model:u}),(0,I.jsx)(gE,{model:u}),(0,I.jsx)(_E,{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)(nt,{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)(tE,{})]})})}function eE({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)(nt,{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)(tD,{tone:`blue`,children:e.workflowId}),e.workflowRunId?(0,I.jsxs)(tD,{tone:`slate`,children:[`run `,oD(e.workflowRunId)]}):null,(0,I.jsx)(tD,{tone:nD(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 `,oD(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 tE(){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)(ht,{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 nE({model:e,onRefreshBootstrap:t,onError:n}){let r=e.workflowRunId?dE(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)(lE,{title:`Workflow configured-session view`,icon:(0,I.jsx)(it,{size:14}),children:(0,I.jsxs)(`div`,{className:`space-y-3 text-xs text-slate-400`,children:[(0,I.jsx)(uE,{label:`selected workflow`,value:i}),(0,I.jsx)(uE,{label:`session state`,value:e.workflowRunId?`started`:`configured/not-started`}),(0,I.jsx)(uE,{label:`input keys`,value:String(e.configuration.inputKeys.length)}),(0,I.jsx)(uE,{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)(lE,{title:`Workflow run view`,icon:(0,I.jsx)(xe,{size:14}),children:(0,I.jsxs)(`div`,{className:`space-y-3 text-xs text-slate-400`,children:[(0,I.jsx)(uE,{label:`run id`,value:e.workflowRunId?oD(e.workflowRunId):`not started`}),(0,I.jsx)(uE,{label:`status`,value:e.state}),(0,I.jsx)(uE,{label:`current node`,value:r?.label??`none`}),(0,I.jsx)(uE,{label:`output`,value:e.finalOutput?`available`:`empty`}),(0,I.jsx)(uE,{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)(lE,{title:`Human action area`,icon:(0,I.jsx)(He,{size:14}),children:(0,I.jsx)(rE,{model:e,onRefreshBootstrap:t,onError:n})})]})}function rE({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 vx(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=UE(e);c(e=>({...e,[i.waitTokenId]:t})),n?.(t[0]?.message??WE(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?oD(e.waitTokenId):e.source})]}),(0,I.jsxs)(`div`,{className:`mt-2 grid gap-2 text-[11px] text-amber-100/75`,children:[(0,I.jsx)(uE,{label:`human node`,value:e.humanNodeId??`unspecified`}),(0,I.jsx)(uE,{label:`payload`,value:e.payloadRequirements?.description??`No persisted payload schema.`}),e.expiresAt?(0,I.jsx)(uE,{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)(el,{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 iE({model:e}){let t=e.workflowRunId?dE(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)(Ge,{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)(oE,{title:`Status`,badge:e.state,icon:(0,I.jsx)(xe,{size:14}),children:[(0,I.jsx)(sE,{label:`run id`,value:e.workflowRunId?oD(e.workflowRunId):`not started`}),(0,I.jsx)(sE,{label:`status`,value:e.state}),(0,I.jsx)(sE,{label:`record source`,value:e.workflowRunId?`Project workflow run id`:`no run record yet`})]}),(0,I.jsxs)(oE,{title:`Current node`,badge:t?.status??`none`,icon:(0,I.jsx)(ut,{size:14}),children:[(0,I.jsx)(sE,{label:`node`,value:t?.label??`none`}),(0,I.jsx)(sE,{label:`node id`,value:t?.id??`none`}),(0,I.jsx)(sE,{label:`source`,value:`project/session run cursor`})]}),(0,I.jsx)(oE,{title:`Run history`,badge:`${e.runHistory.length}`,icon:(0,I.jsx)(et,{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:oD(e.id)}),(0,I.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide ${aD(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)(cE,{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)(oE,{title:`Node attempts`,badge:`${e.nodeAttempts.length}`,icon:(0,I.jsx)(it,{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 ${aD(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)(cE,{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)(oE,{title:`Edge transfers`,badge:`${e.edgeTransfers.length}`,icon:(0,I.jsx)(Ze,{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 ${aD(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)(cE,{children:`No edge transfers recorded for this workflow run yet.`})}),(0,I.jsx)(oE,{title:`Output`,badge:e.finalOutput?`available`:`empty`,icon:(0,I.jsx)(Re,{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)(el,{value:e.finalOutput.value,defaultExpandLevel:1,maxHeight:`12rem`,showControls:!1})]}):(0,I.jsx)(cE,{children:`No workflow output has been recorded for this run yet.`})}),(0,I.jsx)(oE,{title:`Error`,badge:n.length?`${n.length}`:`none`,icon:(0,I.jsx)(ht,{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)(cE,{children:`No workflow run errors are recorded.`})})]})]})}function aE({model:e,onOpenSession:t}){let n=CE(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)(Ke,{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)(Ke,{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:oD(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)(cE,{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:TE(e.definitionLink)}),e.definitionLink.definitionHash?(0,I.jsxs)(`div`,{className:`mt-1 font-mono text-[10px] text-emerald-100/60`,children:[`snapshot `,oD(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:TE(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 `,oD(e.definitionLink.definitionHash)]}):null]})]})]})]})}function oE({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 sE({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 cE({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 lE({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 uE({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 dE(e){return e.nodes.find(e=>e.status===`active`||e.status===`waiting`)??e.nodes[0]}function fE({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)(ut,{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)(pE,{node:e,edge:t[n]},e.id))})]})}function pE({node:e,edge:t}){return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)(`div`,{className:`rounded-sm border p-3 ${rD(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)(eD,{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)(Ze,{size:14,className:`mx-auto mb-1 text-[#11a4d4]`}),t.label]})}):null]})}function mE({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)(xe,{size:14}),`Current UI Snapshot`]}),(0,I.jsx)(el,{value:e.snapshot,showControls:!1})]})}function hE({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)(it,{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 ${rD(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)(eD,{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 ${iD(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 gE({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)(Re,{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)(el,{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)(ht,{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 _E({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)(Ve,{size:14}),`Projection Facts`]}),(0,I.jsxs)(`dl`,{className:`space-y-3`,children:[(0,I.jsx)(vE,{label:`projection kind`,value:`pibo.workflow.xstateUiModel`}),(0,I.jsx)(vE,{label:`schema`,value:`v1`}),(0,I.jsx)(vE,{label:`durable truth`,value:`kernel`}),(0,I.jsx)(vE,{label:`private payloads`,value:`not exposed`}),(0,I.jsx)(vE,{label:`states`,value:String(e.nodes.length)}),(0,I.jsx)(vE,{label:`transitions`,value:String(e.edges.length)}),(0,I.jsx)(vE,{label:`trace`,value:e.traceVersion??`pending`})]})]})}function vE({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 yE(e,t,n,r,i,a){if(!qE(e))return null;let o=JE(e,n),s=YE(e,n),c=XE(s),l=FE(t,s),u=[...LE(t),...IE(e,i)],d=OE(e,o,c),f=kE(t,e.workflowRunId),p=ME(t,e.workflowRunId),m=NE(t,r),h=bE(e),g=xE(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:ZE(s),label:QE(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:ZE(s),label:$E(s)}],configuration:EE(e),definitionLink:h,nestedSessionLinks:g,pendingHumanActions:DE(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`&&!!CE(h)},nestedWorkflowSessionCount:g.length}}}function bE(e){return e.workflowDefinitionLink?e.workflowDefinitionLink:e.workflowVersion?{status:`live`,workflowId:e.workflowId,workflowVersion:e.workflowVersion,title:e.title??e.workflowId,href:wE(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 xE(e,t){let n=SE(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 SE(e,t){for(let n of e){if(n.piboSessionId===t)return n;let e=SE(n.children,t);if(e)return e}}function CE(e){if(e.status===`live`){if(e.href)return e.href;if(e.workflowVersion)return wE(e.workflowId,e.workflowVersion)}}function wE(e,t){return`/apps/chat/workflows/view/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function TE(e){return`${e.workflowId}${e.workflowVersion?`@${e.workflowVersion}`:``}`}function EE(e){let t=e.configuration;return{inputKeys:Object.keys(t?.inputValues??{}).sort(),promptOverrideNodeIds:Object.keys(t?.promptOverrides??{}).sort()}}function DE(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=JE(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 OE(e,t,n){return e.workflowRunId?[{id:e.workflowRunId,status:t,currentNodeId:n,updatedAt:e.updatedAt,source:`project session run record`}]:[]}function kE(e,t){return!t||!e?[]:RE(e.nodes).filter(AE).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:jE(e.status),attempt:t+1,source:`session trace fact`,...e.startedAt?{startedAt:e.startedAt}:{},...e.completedAt?{completedAt:e.completedAt}:{}}))}function AE(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 jE(e){return e===`done`?`completed`:e===`error`?`failed`:`running`}function ME(e,t){if(!t||!e)return[];let n=[];for(let r of e.rawEvents){if(!KE(r.payload))continue;let e=GE(r.payload.type),i=GE(r.payload.runId);if(e!==`edge.transferred`||i&&i!==t)continue;let a=GE(r.payload.edgeId);a&&n.push({id:GE(r.payload.edgeTransferId)??r.id,edgeId:a,status:`transferred`,source:r.type,createdAt:r.createdAt})}return n.slice(0,8)}function NE(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 RE(e.nodes)){let e=t.error??(t.status===`error`?BE(t.output)??BE(t.summary):void 0);e&&n.push({id:`node:${t.id}`,message:e,source:t.type})}for(let t of e.rawEvents){if(!KE(t.payload))continue;let e=t.payload.error,r=KE(e)?GE(e.message):GE(e),i=KE(e)?GE(e.code):void 0;r&&n.push({id:`event:${t.id}`,message:r,...i?{code:i}:{},source:t.type})}}return PE(n).slice(0,8)}function PE(e){let t=new Set;return e.filter(e=>{let n=`${e.code??``}:${e.message}:${e.source??``}`;return t.has(n)?!1:(t.add(n),!0)})}function FE(e,t){if(t!==`completed`||!e)return;let n=RE(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 IE(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 HE(n).slice(0,8)}function LE(e){if(!e)return[];let t=[];for(let n of RE(e.nodes)){let e=n.error??BE(n.output)??BE(n.summary);e&&(!VE([n.title,n.summary,n.error,n.type].filter(e=>typeof e==`string`).join(` `))&&!VE(e)||t.push({id:`node:${n.id}`,message:e,...n.type?{source:n.type}:{}}))}for(let n of e.rawEvents)zE(n.payload,`event:${n.id}`,t);return HE(t).slice(0,8)}function RE(e){let t=[],n=e=>{for(let r of e)t.push(r),n(r.children)};return n(e),t}function zE(e,t,n,r=0){if(r>4||!KE(e))return;let i=Array.isArray(e.diagnostics)?e.diagnostics:void 0;if(i)for(let e of i){if(!KE(e))continue;let r=GE(e.message)??BE(e);r&&n.push({id:`${t}:diagnostic:${n.length}`,message:r,...GE(e.code)?{code:GE(e.code)}:{},...GE(e.path)?{path:GE(e.path)}:{},source:`workflow.diagnostic`})}let a=e.error;if(KE(a)){let e=GE(a.code),r=GE(a.message)??BE(a);r&&VE([e,r].filter(Boolean).join(` `))&&n.push({id:`${t}:error:${n.length}`,message:r,...e?{code:e}:{},source:`workflow.error`})}else typeof a==`string`&&VE(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`||zE(a,`${t}:${i}`,n,r+1)}function BE(e){if(typeof e==`string`)return e;if(KE(e))return GE(e.message)??GE(e.error)??GE(e.summary)}function VE(e){let t=e.toLowerCase();return t.includes(`validation`)||t.includes(`validate`)||t.includes(`diagnostic`)||t.includes(`workflowinterfaceerror`)||t.includes(`workflowruntimeerror.validation`)}function HE(e){let t=new Set;return e.filter(e=>{let n=`${e.code??``}:${e.path??``}:${e.message}`;return t.has(n)?!1:(t.add(n),!0)})}function UE(e){return KE(e)&&KE(e.data)&&Array.isArray(e.data.diagnostics)?e.data.diagnostics.filter(KE).map(t=>({code:GE(t.code)??`WorkflowRuntimeError.humanActionRejected`,message:GE(t.message)??WE(e),severity:t.severity===`info`||t.severity===`warning`||t.severity===`error`?t.severity:`error`,...GE(t.path)?{path:GE(t.path)}:{},...GE(t.registryRef)?{registryRef:GE(t.registryRef)}:{},...GE(t.hint)?{hint:GE(t.hint)}:{}})):[{code:`WorkflowRuntimeError.humanActionRejected`,message:WE(e),severity:`error`}]}function WE(e){return e instanceof Error?e.message:String(e)}function GE(e){return typeof e==`string`&&e.trim()?e:void 0}function KE(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function qE(e){return!!e.workflowRunId||e.state===`workflow`||e.workflowId!==`simple-chat`}function JE(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 YE(e,t){let n=JE(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 XE(e){return e===`completed`?`workflow.completed`:e===`failed`?`workflow.failed`:e===`cancelled`?`workflow.cancelled`:`node.session`}function ZE(e){return e===`failed`?`workflow.failed`:e===`cancelled`?`workflow.cancelled`:`workflow.completed`}function QE(e){return e===`failed`?`failed`:e===`cancelled`?`cancelled`:`completed`}function $E(e){return e===`failed`?`WORKFLOW.FAIL`:e===`cancelled`?`WORKFLOW.CANCEL`:`WORKFLOW.NODE.DONE`}function eD({status:e}){return e===`completed`?(0,I.jsx)(Re,{size:16,className:`text-emerald-300`}):e===`failed`?(0,I.jsx)(Be,{size:16,className:`text-red-300`}):e===`cancelled`?(0,I.jsx)(ht,{size:16,className:`text-slate-400`}):e===`waiting`?(0,I.jsx)(He,{size:16,className:`text-amber-300`}):e===`active`?(0,I.jsx)(xe,{size:16,className:`text-[#11a4d4]`}):(0,I.jsx)(Ve,{size:16,className:`text-slate-500`})}function tD({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 nD(e){return e===`completed`?`green`:e===`failed`||e===`cancelled`?`red`:e===`waiting`?`amber`:`blue`}function rD(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 iD(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 aD(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 oD(e){return e.length>18?`${e.slice(0,10)}…${e.slice(-6)}`:e}var sD=[{id:`terminal`,label:`Terminal`,description:`Compact Codex-style terminal transcript.`,render:e=>(0,I.jsx)(yT,{...e})},{id:`workflow`,label:`Workflow`,description:`Workflow/XState visualization for workflow-backed project sessions.`,render:e=>(0,I.jsx)($T,{...e})}],cD=new Map(sD.map(e=>[e.id,e]));function lD(){return sD}function uD(e){return cD.get(e)??cD.get(`terminal`)}var dD=`pibo.chat.composerHistory`,fD=100;function pD(){try{let e=localStorage.getItem(dD);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`&&e.trim().length>0).slice(-fD):[]}catch{return[]}}function mD(e){let t=e.trim();if(!t)return;let n=pD();if(n.at(-1)!==t)try{localStorage.setItem(dD,JSON.stringify([...n,t].slice(-fD)))}catch{}}function hD(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 gD(e,t){return e.length>t?`${e.slice(0,Math.max(0,t-1))}…`:e}function _D({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),[ee,A]=(0,v.useState)([]),[te,ne]=(0,v.useState)(!1),[re,ie]=(0,v.useState)(null),[j,M]=(0,v.useState)(null),ae=(0,v.useMemo)(()=>{for(let e=O-1;e>=0;e--){let t=i[e];if(t===` `||t===`
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]),oe=i.trim().startsWith(`/`)?i.trim().split(/\s+/)[0]:null,se=ae?vD(ae.startPos,i.slice(ae.startPos,O)):null,ce=oe?yD(oe):null,le=(0,v.useMemo)(()=>ae?r.filter(e=>e.name.toLowerCase().startsWith(ae.query)):[],[ae,r]),ue=(0,v.useMemo)(()=>oe?n.filter(e=>e.slash.startsWith(oe)):[],[oe,n]),de=se&&ee.includes(se)?[]:le,P=ce&&ee.includes(ce)?[]:ue,fe=(0,v.useCallback)(e=>{e&&A(t=>t.includes(e)?t:[...t,e])},[]),pe=(0,v.useCallback)(()=>{let e=[le.length?se:null,ue.length?ce:null].filter(e=>!!e);e.length&&A(t=>{let n=new Set(t);for(let t of e)n.add(t);return n.size===t.length?t:[...n]})},[ce,ue.length,le.length,se]);(0,v.useEffect)(()=>{let e=[se,ce].filter(e=>!!e);A(t=>t.filter(t=>e.includes(t)))},[ce,se]),(0,v.useEffect)(()=>{!P.length||w<P.length||T(0)},[w,P.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,P.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(!j)return;let e=requestAnimationFrame(()=>b.current?.focus());return()=>{cancelAnimationFrame(e),URL.revokeObjectURL(j.previewUrl)}},[j]),(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(!P.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,P.length,de.length]),(0,v.useLayoutEffect)(()=>{ED(_.current)},[i]);let me=e=>{if(!ae||!_.current)return;let t=i.slice(0,ae.startPos),n=i.slice(ae.endPos);c(t+`$`+e+n),fe(vD(ae.startPos,`$${e}`));let r=ae.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=pD();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=()=>{M(null)},ye=e=>{if(t||te)return;let n=bD(e.clipboardData);if(!n.length)return;e.preventDefault(),pe(),ie(null);let r=n[0];M(e=>(e&&URL.revokeObjectURL(e.previewUrl),{file:r,previewUrl:URL.createObjectURL(r)}))},be=async()=>{if(!j||te)return;let e=j.file;M(null),await F([e])},F=async e=>{if(e.length){ne(!0),ie({message:`Uploading ${e.length} file${e.length===1?``:`s`}...`,error:!1});try{f((await N(e)).files),ie(null)}catch(e){ie({message:e instanceof Error?e.message:String(e),error:!0})}finally{ne(!1)}}},xe=async()=>{if(t)return;let e=i.trim();if(e){if(de.length){me(de[Math.min(E,de.length-1)].name);return}if(P.length&&!n.some(t=>t.slash===e.split(/\s+/)[0])){let e=P[Math.min(w,P.length-1)].slash;c(e),fe(yD(e));return}if(C.current=null,mD(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=``,F(t)}}),re?(0,I.jsxs)(`div`,{className:`mb-2 flex items-center gap-2 rounded-sm border px-3 py-2 text-xs ${re.error?`border-red-900 bg-red-950/40 text-red-200`:re.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:re.message}),re.copyText?(0,I.jsx)(`button`,{type:`button`,onClick:()=>void hD(re.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)(Ue,{size:13})}):null,(0,I.jsx)(`button`,{type:`button`,onClick:()=>ie(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)(_t,{size:13})})]}):null,j?(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 ~/.pibo/uploads?`})]}),(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)(_t,{size:14})})]}),(0,I.jsxs)(`div`,{className:`space-y-3 px-4 py-4`,children:[(0,I.jsx)(`img`,{src:j.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:j.file.name}),(0,I.jsx)(`span`,{className:`shrink-0 font-mono`,children:TD(j.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:gD(e.name||e.path,100)}),(0,I.jsx)(`button`,{type:`button`,onClick:()=>void hD(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)(Ue,{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)(_t,{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:gD(e.primaryTarget||e.label||e.note||e.id,100)}),(0,I.jsx)(_t,{size:11,className:`shrink-0 text-[#11a4d4]`})]},e.id))})]}):null,P.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:P.map((e,t)=>(0,I.jsxs)(`button`,{ref:t===w?x:null,type:`button`,onClick:()=>{c(e.slash),fe(yD(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`,{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||P.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(P.length&&(e.key===`ArrowDown`||e.key===`ArrowUp`)){e.preventDefault(),T(t=>e.key===`ArrowDown`?(t+1)%P.length:(t-1+P.length)%P.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(),xe())},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 xe(),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)(pt,{size:16})})]})]})}function vD(e,t){return`skill:${e}:${t}`}function yD(e){return`command:${e}`}function bD(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(xD)}function xD(e){return e.name&&e.name!==`image.png`?e:new File([e],SD(e.type),{type:e.type||`image/png`,lastModified:Date.now()})}function SD(e){let t=CD(e),n=new Date;return`screenshot-${[n.getFullYear(),wD(n.getMonth()+1),wD(n.getDate()),`-`,wD(n.getHours()),wD(n.getMinutes()),wD(n.getSeconds())].join(``)}${t}`}function CD(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 wD(e){return String(e).padStart(2,`0`)}function TD(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KiB`:`${(e/(1024*1024)).toFixed(1)} MiB`}function ED(e){if(!e)return;if(!e.value.includes(`
41
- `)&&e.value.length<80){e.style.height=``,e.style.overflowY=`hidden`;return}let t=window.getComputedStyle(e),n=DD(t.lineHeight,20),r=DD(t.borderTopWidth)+DD(t.borderBottomWidth),i=n*5+DD(t.paddingTop)+DD(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 DD(e,t=0){let n=Number.parseFloat(e);return Number.isFinite(n)?n:t}var OD=`pibo.chat.webAnnotations.cdpUrl`,kD=`pibo.chat.webAnnotations.selected`,AD=`${kD}.`,jD=`pibo.chat.webAnnotations.overlay.`,MD=`pibo.chat.webAnnotations.panelCollapsed`,ND=`pibo.chat.shortcuts.webAnnotationsToggle`,PD=`Alt+Shift+A`;function FD(){try{return localStorage.getItem(OD)??``}catch{return``}}function ID(e){try{e.trim()?localStorage.setItem(OD,e.trim()):localStorage.removeItem(OD)}catch{}}function LD(){try{return localStorage.getItem(ND)||`Alt+Shift+A`}catch{return PD}}function RD(e){try{return BD(localStorage.getItem(zD(e)))}catch{return null}}function zD(e){return jD+e}function BD(e){if(!e)return null;try{return VD(JSON.parse(e))}catch{return null}}function VD(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 HD(e){try{let t=WD(localStorage.getItem(kD));if(t.length||!e)return t;let n=AD+e,r=WD(localStorage.getItem(n));return r.length&&(localStorage.setItem(kD,JSON.stringify(r)),localStorage.removeItem(n)),r}catch{return[]}}function UD(e,t){try{let n=[...new Set(t.filter(e=>e.trim()))].slice(0,5);n.length?localStorage.setItem(kD,JSON.stringify(n)):localStorage.removeItem(kD),e&&localStorage.removeItem(AD+e)}catch{}}function WD(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 GD(){try{return localStorage.getItem(MD)===`true`}catch{return!1}}function KD(e){try{localStorage.setItem(MD,String(e))}catch{}}function qD({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.jsxs)(`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]}),a?null:(0,I.jsx)(`div`,{className:`text-[11px] text-slate-500`,children:`Global annotation list. Selected attachments follow you when switching sessions.`})]}),(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)(lt,{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)(mt,{size:12})}),(0,I.jsx)(`button`,{type:`button`,onClick:l,title:a?`Expand annotations panel`:`Collapse annotations panel`,"aria-label":a?`Expand annotations panel`:`Collapse annotations panel`,className:`inline-flex h-8 w-8 items-center justify-center rounded-sm border border-slate-700 text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] sm:h-7 sm:w-7`,children:a?(0,I.jsx)(Ie,{size:12}):(0,I.jsx)(Pe,{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)(_t,{size:12})})]})]}),a?null: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:iO(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=>{let t=n.includes(e.id);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":t?`true`:`false`,className:`min-w-0 rounded-sm border px-3 py-2 text-xs ${t?`border-[#11a4d4] bg-[#11a4d4]/10`:`border-slate-800 bg-[#0e1116]`}`,children:[(0,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),className:`inline-flex h-8 shrink-0 items-center gap-1 rounded-sm border px-2 text-[11px] sm:h-6 sm:px-1.5 ${t?`border-[#11a4d4] text-[#11a4d4]`:`border-slate-700 text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:[t?(0,I.jsx)(_t,{size:11}):(0,I.jsx)(ct,{size:11}),` `,t?`Detach`:`Attach`]})]}),(0,I.jsx)(`div`,{className:`truncate text-slate-200`,title:e.primaryTarget||e.label||e.selector||e.id,children:iO(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:iO(e.piboContext,140)}):null,(0,I.jsx)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:e.url,children:tO(e.url)}),(0,I.jsxs)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:rO(e),children:[`Source `,nO(e)]}),(0,I.jsx)(`div`,{className:`mt-1 line-clamp-2 text-slate-400`,title:e.note,children:iO(e.note,180)}),(0,I.jsx)(`div`,{className:`mt-1 text-[11px] text-slate-600`,children:aO(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 JD({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)(()=>FD()),[p,m]=(0,v.useState)([]),[h,g]=(0,v.useState)(`idle`),[_,y]=(0,v.useState)(!1),[b,x]=(0,v.useState)(null);(0,v.useEffect)(()=>{n&&c(!1)},[n]),(0,v.useEffect)(()=>{ID(d)},[d]);let S=async()=>{if(e){g(`loading`),x(null);try{m((await mx(d)).targets.filter(e=>e.type===`page`||e.attachable)),g(`loaded`)}catch(e){let t=$D(e,`CDP unavailable`);m([]),g(`error`),x({kind:`error`,message:t}),o(t)}}},C=async n=>{if(!e)throw Error(`No active session context`);return gx(n.binding.id,XD({piboSessionId:e,piboRoomId:t,cdpUrl:d,annotationShortcut:LD()}))},w=async()=>{if(!(!e||_)){i(),y(!0),x({kind:`info`,message:`Injecting annotation overlay into this Pibo page…`});try{let n=await hx({piboSessionId:e,piboRoomId:t,url:window.location.href,title:document.title,sameOrigin:!0,annotationShortcut:LD()});if(!n.overlay)throw Error(`Overlay config missing from same-origin binding response`);await QD(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=$D(e,`Current-page annotation failed`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}}},T=async()=>{if(!e||_)return;i();let n=l.trim();if(!n){x({kind:`error`,message:`URL is required`});return}if(ZD(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 hx(XD({piboSessionId:e,piboRoomId:t,url:n,cdpUrl:d})),i=await C(r);x({kind:`success`,message:`Annotation overlay injected for ${eO(i.target??r.target,i.binding.url)}`}),u(``),o(null)}catch(e){let t=$D(e,`Annotation failed`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}},E=async n=>{if(!(!e||_)){i(),y(!0),x({kind:`info`,message:`Binding selected target and injecting overlay…`});try{let r=await C(await hx(XD({piboSessionId:e,piboRoomId:t,targetId:n.id,cdpUrl:d})));x({kind:`success`,message:`Annotation overlay injected for ${eO(r.target??n,r.binding.url)}`}),o(null)}catch(e){let t=$D(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)(YD,{onClick:()=>{n||(c(e=>!e),r||i())},title:n?`Select an active session to annotate a web page`:r?`Web Annotations`:`Show Web Annotations`,ariaLabel:`Web Annotations`,active:s||r,children:(0,I.jsx)(Ee,{size:14})}),s&&!n?(0,I.jsxs)(`div`,{className:`fixed inset-x-2 bottom-3 z-40 max-h-[calc(100svh-1.5rem)] overflow-y-auto rounded-sm border border-slate-700 bg-[#0e1116] p-3 text-sm shadow-xl sm:absolute sm:inset-auto sm:right-0 sm:top-full sm:bottom-auto sm:mt-2 sm:w-[min(420px,calc(100vw-24px))] sm:max-h-[calc(100svh-5rem)]`,role:`dialog`,"aria-label":`Web Annotations`,children:[(0,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)(dt,{size:14})}),(0,I.jsx)(`button`,{type:`button`,onClick:()=>c(!1),className:`rounded-sm p-1 text-slate-500 hover:bg-slate-800 hover:text-slate-200`,"aria-label":`Close Web Annotations panel`,children:(0,I.jsx)(_t,{size:14})})]})]}),(0,I.jsx)(`button`,{type:`button`,onClick:()=>void w(),disabled:_,className:`mb-3 h-10 w-full rounded-sm bg-emerald-600 px-3 text-xs font-medium text-white hover:bg-emerald-500 disabled:opacity-50 sm:h-9`,"data-pibo-debug":`web-annotations-current-page`,children:`Annotate this Pibo page`}),(0,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`&&T()},placeholder:`http://localhost:5173`,disabled:_,className:`h-10 min-w-0 rounded-sm border border-slate-700 bg-[#151f24] px-2 text-base text-slate-100 outline-none focus:border-[#11a4d4] disabled:opacity-60 sm:h-9 sm:text-xs`}),(0,I.jsx)(`button`,{type:`button`,onClick:()=>void T(),disabled:_||!l.trim(),className:`h-10 rounded-sm bg-[#11a4d4] px-3 text-xs font-medium text-white disabled:opacity-50 sm:h-9`,children:`Annotate`})]}),(0,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 S(),disabled:_||h===`loading`,className:`inline-flex h-7 items-center gap-1 rounded-sm border border-slate-700 px-2 text-[11px] text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:opacity-50`,children:[(0,I.jsx)(lt,{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:iO(e.title||`Untitled target`,120)}),(0,I.jsx)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:e.url,children:iO(e.url||e.id,160)})]}),(0,I.jsx)(`button`,{type:`button`,onClick:()=>void E(e),disabled:_||!e.attachable,title:e.attachable?`Attach selected target`:`Target is not attachable`,className:`h-9 rounded-sm border border-slate-700 px-2 text-[11px] text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:opacity-40 sm:h-8`,children:`Attach`})]},e.id))]}),b?(0,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 YD({title:e,ariaLabel:t,active:n,onClick:r,children:i}){return(0,I.jsx)(`button`,{type:`button`,onClick:r,title:e,"aria-label":t,className:`h-8 w-8 inline-flex items-center justify-center border rounded-sm transition-colors ${n?`border-[#11a4d4] bg-[#11a4d4]/10 text-[#11a4d4]`:`border-slate-700 text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:i})}function XD(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e&&e.trim()))}function ZD(e){try{let t=new URL(e);return t.port===`56663`||t.pathname.startsWith(`/json/`)}catch{return!1}}function QD(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 $D(e,t){let n=oO(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 eO(e,t){let n=e?.url||t||e?.title||`target`;return tO(e?.title||n)}function tO(e){try{let t=new URL(e);return`${t.host}${t.pathname===`/`?``:t.pathname}`}catch{return iO(e,80)}}function nO(e){return e.piboRoomId?`${iO(e.piboSessionId,24)} · room ${iO(e.piboRoomId,18)}`:iO(e.piboSessionId,44)}function rO(e){return e.piboRoomId?`Session ${e.piboSessionId} in room ${e.piboRoomId}`:`Session ${e.piboSessionId}`}function iO(e,t){return e.length>t?`${e.slice(0,Math.max(0,t-1))}…`:e}function aO(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{dateStyle:`short`,timeStyle:`short`})}function oO(e){return e instanceof Error?e.message:String(e)}function sO(e){return!!e.workflowRunId||e.state===`workflow`||e.workflowId!==`simple-chat`}function cO(e,t){return{workflowId:e.workflowId,state:uO(e,t),...e.workflowRunId?{workflowRunId:e.workflowRunId}:{}}}function lO({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:dO(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 `,fO(e.workflowRunId)]}):null]})}function uO(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 dO(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 fO(e){return e.length>18?`${e.slice(0,10)}…${e.slice(-6)}`:e}function pO({title:e,roomLabel:t,headerPiboSessionId:n,piboSessionId:r,piboRoomId:i,webAnnotationsDisabled:a,webAnnotationsPanelRendered:o,workflowHeader:s,sessionViewId:c,sessionViews:l,currentSessionView:u,allowedSessionViewIds:d,extraViewTabs:f,activeViewId:p,showRawEvents:m,showThinking:h,expandThinking:g,onShowWebAnnotationsPanel:_,onHideWebAnnotationsPanel:y,onSelectSessionView:b,onToggleRawEvents:x,onToggleThinking:S,onToggleExpandThinking:C,onError:w}){let[T,E]=(0,v.useState)(null),D=(0,v.useRef)(void 0),O=T===n,k=p??c,ee=(0,v.useMemo)(()=>d?new Set(d):null,[d]);(0,v.useEffect)(()=>()=>{D.current&&window.clearTimeout(D.current)},[]);let A=()=>{n&&(hD(n).catch(()=>void 0),E(n),D.current&&window.clearTimeout(D.current),D.current=window.setTimeout(()=>E(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 A(),title:O?`Copied Pibo session ID`:`Copy Pibo session ID`,"aria-label":O?`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] ${O?`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)(lO,{summary:s}):null]})]}),(0,I.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,I.jsx)(JD,{piboSessionId:r,piboRoomId:i,disabled:a,panelVisible:o,onShowPanel:_,onHidePanel:y,onError:w}),(0,I.jsxs)(`div`,{className:`flex items-center rounded-sm border border-slate-700 bg-[#0e1116] p-0.5`,children:[l.map(e=>{let t=!!(ee&&!ee.has(e.id));return(0,I.jsx)(`button`,{type:`button`,onClick:()=>{t||b(e.id)},disabled:t,title:t?`Project session routing uses the ${u.label} view for this session kind.`:e.description??e.label,"aria-label":t?`${e.label} view unavailable for this Project session kind`:`Switch to ${e.label} view`,className:`min-w-20 px-2.5 py-1 text-[11px] font-bold tracking-wide max-[980px]:min-w-0 max-[980px]:px-1.5 disabled:cursor-not-allowed disabled:text-slate-600 ${k===e.id?`bg-[#11a4d4]/10 text-[#11a4d4]`:`text-slate-400 hover:text-[#11a4d4] disabled:hover:text-slate-600`}`,children:e.label},e.id)}),f?.map(e=>(0,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`,className:`min-w-20 px-2.5 py-1 text-[11px] font-bold tracking-wide max-[980px]:min-w-0 max-[980px]:px-1.5 disabled:cursor-not-allowed disabled:text-slate-600 ${e.active??k===e.id?`bg-[#11a4d4]/10 text-[#11a4d4]`:`text-slate-400 hover:text-[#11a4d4] disabled:hover:text-slate-600`}`,children:e.label},e.id))]}),(0,I.jsx)(mO,{onClick:x,title:m?`Hide Raw Events`:`Show Raw Events`,ariaLabel:m?`Hide Raw Events`:`Show Raw Events`,active:m,children:(0,I.jsx)(ke,{size:14})}),(0,I.jsx)(mO,{onClick:S,title:h?`Hide Thinking`:`Show Thinking`,ariaLabel:h?`Hide Thinking`:`Show Thinking`,active:h,children:h?(0,I.jsx)(Oe,{size:14}):(0,I.jsx)(qe,{size:14})}),h?(0,I.jsx)(mO,{onClick:C,title:g?`Collapse Thinking`:`Expand Thinking`,ariaLabel:g?`Collapse Thinking`:`Expand Thinking`,active:g,children:g?(0,I.jsx)(Pe,{size:14}):(0,I.jsx)(Ie,{size:14})}):null]})]})}function mO({title:e,ariaLabel:t,active:n,onClick:r,children:i}){return(0,I.jsx)(`button`,{type:`button`,onClick:r,title:e,"aria-label":t,className:`h-8 w-8 inline-flex items-center justify-center border rounded-sm transition-colors ${n?`border-[#11a4d4] bg-[#11a4d4]/10 text-[#11a4d4]`:`border-slate-700 text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:i})}function hO(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&gO(e,n)){e.count+=1,e.createdAt=n.createdAt,e.payload={...yO(e.payload)?e.payload:{},text:`${_O(e.payload)}${_O(n.payload)}`};continue}t.push({...n,count:1})}return t}function gO(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=yO(e.payload)?e.payload:{},r=yO(t.payload)?t.payload:{};return vO(n)===vO(r)}function _O(e){return yO(e)?typeof e.text==`string`?e.text:typeof e.delta==`string`?e.delta:``:``}function vO(e){return e.eventId??e.messageId}function yO(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function bO({traceView:e,eventLimit:t,isFetching:n,visible:r,onLoadOlder:i}){let a=(0,v.useMemo)(()=>r?hO(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)(el,{value:e.payload,showControls:!1})]},e.id))]})]}):null}function xO({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,headerProps:p,projectSessionCreatePanel:m,workflowStartPanel:h,projectModulePanel:g,currentSessionView:_,sessionViewProps:v,webAnnotationsPanelRendered:y,webAnnotationsPanelProps:b,composerProps:x}){let S=a||o||i;return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)(`main`,{"data-pibo-debug":`chat-shell`,"data-pibo-session-id":e??void 0,"data-pibo-room-id":t??n??void 0,"data-pibo-view-id":r,"data-pibo-state":a?`room-loading`:o?`session-loading`:i?`loading`:s?`error`:e?`ready`:`empty`,className:`min-h-0 flex flex-col`,children:[(0,I.jsx)(pO,{...p}),m?(0,I.jsx)(`div`,{className:`border-b border-slate-800 bg-[#101d22] px-4 py-3`,children:m}):null,h?(0,I.jsx)(`div`,{className:`border-b border-slate-800 bg-[#101d22] px-4 py-3`,children:h}):null,g||(S?(0,I.jsx)(SO,{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}):_.render(v)),y?(0,I.jsx)(qD,{...b}):null,(0,I.jsx)(_D,{...x})]}),(0,I.jsx)(bO,{traceView:l,eventLimit:u,isFetching:d,visible:c,onLoadOlder:f})]})}function SO({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)(CO,{kind:e.kind,lineCount:e.lines},t))]})})})}function CO({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 wO=[`a[href]`,`button:not([disabled])`,`input:not([disabled])`,`select:not([disabled])`,`textarea:not([disabled])`,`[tabindex]:not([tabindex="-1"])`].join(`,`);function TO({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(wO)??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(wO)??[]);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)(_t,{size:14})})]}),i]})})}function EO(e){let t=new Map;if(jO(e.nodes,t),!t.size)return e;let{nodes:n,changed:r}=MO(e.nodes,t);return r?{...e,nodes:n}:e}function DO(e){return e.some(AO)}function OO(e){let t=new Map;return PO(e,e=>{if(e.type!==`user.message`||!e.entryId)return;let n=FO(e),r=t.get(n);r?r.push(e.entryId):t.set(n,[e.entryId])}),t}function kO(e,t){if(!t.size)return;let n=new Map;PO(e,e=>{if(e.type!==`user.message`||e.entryId)return;let r=FO(e),i=t.get(r);if(!i?.length)return;let a=n.get(r)??0,o=i[a];o&&(e.entryId=o,n.set(r,a+1))})}function AO(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 jO(e,t){for(let n of e){if(n.type===`user.message`&&!NO(n)){let e=FO(n);e&&t.set(e,(t.get(e)??0)+1)}jO(n.children,t)}}function MO(e,t){let n=!1,r=[];for(let i of e){if(NO(i)){let e=FO(i),r=e?t.get(e)??0:0;if(r>0){t.set(e,r-1),n=!0;continue}}let e=MO(i.children,t);n||=e.changed,r.push(e.changed?{...i,children:e.nodes}:i)}return{nodes:n?r:e,changed:n}}function NO(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 PO(e,t){for(let n of e)t(n),PO(n.children,t)}function FO(e){return typeof e.output==`string`?e.output:typeof e.summary==`string`?e.summary:``}function IO({selectedPiboSessionId:e,reconciledBaseTraceView:t,liveTraceOverlay:n,selectedSessionStatus:r,persistedUserMessageIndexForBaseTrace:i,now:a}){if(!e||t?.piboSessionId!==e)return{traceView:null};let o=n?.piboSessionId===e?n.events:[];if(!o.length)return{traceView:t};let s=a?.(),c=kC(t,o,r??`idle`),l=DO(o);return l&&kO(c.nodes,i),{traceView:l?EO(c):c,liveTraceComputeDurationMs:s!==void 0&&a?a()-s:void 0}}function LO(e,t){for(let n of e)t(n),LO(n.children,t)}function RO(e){return typeof e.output==`string`?e.output:typeof e.summary==`string`?e.summary:``}function zO(e){if(!e)return;let t=0;return LO(e.nodes,e=>{e.type===`assistant.message`&&(t+=RO(e).length)}),t}function BO({selectedPiboSessionId:e,baseTraceView:t,liveTraceOverlay:n,selectedSessionStatus:r}){let i=(0,v.useMemo)(()=>t?EO(t):null,[t]),a=(0,v.useMemo)(()=>i?OO(i.nodes):new Map,[i]),o=(0,v.useMemo)(()=>IO({selectedPiboSessionId:e,reconciledBaseTraceView:i,liveTraceOverlay:n,selectedSessionStatus:r,persistedUserMessageIndexForBaseTrace:a,now:$v()?()=>performance.now():void 0}),[n,e,r,i,a]),s=o.traceView;return(0,v.useEffect)(()=>{!e||!s?.piboSessionId||!$v()||(cy(s.piboSessionId,{overlayEventCount:n?.piboSessionId===s.piboSessionId?n.events.length:0,traceBaseOutputLength:zO(t),currentOutputLength:zO(s)}),o.liveTraceComputeDurationMs!==void 0&&ay(s.piboSessionId,o.liveTraceComputeDurationMs))},[t,o.liveTraceComputeDurationMs,s,n,e]),(0,v.useEffect)(()=>{let e=()=>{!s?.piboSessionId||!yb()||Cb(s.piboSessionId,`tab:${document.visibilityState}`,s.nodes,{traceVersion:s.version,latestStreamId:s.latestStreamId,lastRawEventId:s.rawEvents.at(-1)?.id})};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[s]),s}var VO=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(){}},HO=new class extends VO{#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`}},UO={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},WO=new class{#e=UO;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 GO(e){setTimeout(e,0)}var KO=typeof window>`u`||`Deno`in globalThis;function qO(){}function JO(e){return typeof e==`number`&&e>=0&&e!==1/0}function YO(e,t){return Math.max(e+(t||0)-Date.now(),0)}function XO(e,t){return typeof e==`function`?e(t):e}function ZO(e,t){return typeof e==`function`?e(t):e}var QO=Object.prototype.hasOwnProperty;function $O(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=tk(e)&&tk(t);if(!r&&!(nk(e)&&nk(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:QO.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=$O(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function ek(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 tk(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function nk(e){if(!rk(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!rk(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function rk(e){return Object.prototype.toString.call(e)===`[object Object]`}function ik(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:$O(e,t)}function ak(e,t){return typeof e==`function`?e(...t):!!e}var ok=(()=>{let e=()=>KO;return{isServer(){return e()},setIsServer(t){e=t}}})();function sk(){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 ck=GO;function lk(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=ck,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 uk=lk(),dk=new class extends VO{#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 fk(e){return(e??`online`)===`online`?dk.isOnline():!0}function pk(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:fk(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}var mk=class extends VO{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=sk(),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),gk(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return _k(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return _k(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 ZO(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&&!ek(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&vk(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||ZO(this.options.enabled,this.#t)!==ZO(t.enabled,this.#t)||XO(this.options.staleTime,this.#t)!==XO(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||ZO(this.options.enabled,this.#t)!==ZO(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 bk(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(qO)),t}#g(){this.#b();let e=XO(this.options.staleTime,this.#t);if(ok.isServer()||this.#r.isStale||!JO(e))return;let t=YO(this.#r.dataUpdatedAt,e)+1;this.#d=WO.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,!(ok.isServer()||ZO(this.options.enabled,this.#t)===!1||!JO(this.#p)||this.#p===0)&&(this.#f=WO.setInterval(()=>{(this.options.refetchIntervalInBackground||HO.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(WO.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(WO.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&&gk(e,t),o=i&&vk(e,n,t,r);(a||o)&&(l={...l,...pk(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=ik(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=ik(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:yk(e,t),refetch:this.refetch,promise:this.#o,isEnabled:ZO(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let t=x.data!==void 0,r=x.status===`error`&&!t,i=e=>{r?e.reject(x.error):t&&e.resolve(x.data)},a=()=>{i(this.#o=x.promise=sk())},o=this.#o;switch(o.status){case`pending`:e.queryHash===n.queryHash&&i(o);break;case`fulfilled`:(r||x.data!==o.value)&&a();break;case`rejected`:(!r||x.error!==o.reason)&&a();break}}return x}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#u=this.#t),!ek(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){uk.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function hk(e,t){return ZO(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status===`error`&&ZO(t.retryOnMount,e)===!1)}function gk(e,t){return hk(e,t)||e.state.data!==void 0&&_k(e,t,t.refetchOnMount)}function _k(e,t,n){if(ZO(t.enabled,e)!==!1&&XO(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&yk(e,t)}return!1}function vk(e,t,n,r){return(e!==t||ZO(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&yk(e,n)}function yk(e,t){return ZO(t.enabled,e)!==!1&&e.isStaleByTime(XO(t.staleTime,e))}function bk(e,t){return!ek(e.getCurrentResult(),t)}var xk=v.createContext(void 0),Sk=e=>{let t=v.useContext(xk);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},Ck=v.createContext(!1),wk=()=>v.useContext(Ck);Ck.Provider;function Tk(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Ek=v.createContext(Tk()),Dk=()=>v.useContext(Ek),Ok=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?ak(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},kk=e=>{v.useEffect(()=>{e.clearReset()},[e])},Ak=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||ak(n,[e.error,r])),jk=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))}},Mk=(e,t)=>e.isLoading&&e.isFetching&&!t,Nk=(e,t)=>e?.suspense&&t.isPending,Pk=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Fk(e,t,n){let r=wk(),i=Dk(),a=Sk(n),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let s=a.getQueryCache().get(o.queryHash);o._optimisticResults=r?`isRestoring`:`optimistic`,jk(o),Ok(o,i,s),kk(i);let c=!a.getQueryCache().get(o.queryHash),[l]=v.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&e.subscribed!==!1;if(v.useSyncExternalStore(v.useCallback(e=>{let t=d?l.subscribe(uk.batchCalls(e)):qO;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),v.useEffect(()=>{l.setOptions(o)},[o,l]),Nk(o,u))throw Pk(o,l,i);if(Ak({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,u),o.experimental_prefetchInRender&&!ok.isServer()&&Mk(u,r)&&(c?Pk(o,l,i):s?.promise)?.catch(qO).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?u:l.trackResult(u)}function Ik(e,t){return Fk(e,mk,t)}var Lk=1e4,Rk=5*6e4;function zk(e){return[`chat`,`trace-summary`,e]}function Bk(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 Vk(e,t){if(!e||e.piboSessionId!==t.piboSessionId)return e;let n=t.latestStreamId,r=Uk(t),i=Hk(t.nodes),a=e.events.filter(e=>{if(n!==void 0&&e.streamId!==void 0&&e.streamId<=n||AO(e)&&i.has(e.payload.text))return!1;let t=Gk(e);return!t||!r.has(t)});return a.length?{...e,events:a}:null}function Hk(e){let t=new Set;for(let n of e){if(n.type===`user.message`&&n.source===`transcript`){let e=Kk(n);e&&t.add(e)}for(let e of Hk(n.children))t.add(e)}return t}function Uk(e){let t=new Set;for(let n of e.rawEvents){let e=Gk(n);e&&t.add(e)}return Wk(e.nodes,t),t}function Wk(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}`),n.source===`transcript`&&n.entryId&&t.add(`${n.piboSessionId}:${e}:${n.entryId}`)}n.eventId&&n.type===`assistant.message`&&(t.add(`${n.piboSessionId}:assistant_delta:${n.eventId}`),t.add(`${n.piboSessionId}:assistant_message:${n.eventId}`)),n.eventId&&n.type===`model.reasoning`&&(t.add(`${n.piboSessionId}:thinking_delta:${n.eventId}`),t.add(`${n.piboSessionId}:thinking_finished:${n.eventId}`)),Wk(n.children,t)}}function Gk(e){let t=e.payload;if(!t||typeof t!=`object`||Array.isArray(t))return;let n=`eventId`in t&&typeof t.eventId==`string`?t.eventId:e.eventId,r=`piboSessionId`in t&&typeof t.piboSessionId==`string`?t.piboSessionId:e.piboSessionId;if(!(!n||!r))return`${r}:${e.type}:${n}`}function Kk(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 qk(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)?!1:(n.add(t),!0)});return{...e,version:e.version,nodes:Yk(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 Jk(e,t){return e.piboSessionId===t.piboSessionId?{...t,nodes:Yk(e.nodes,t.nodes),rawEvents:e.rawEvents.length?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 Yk(e,t){let n=new Map;for(let t of fS([...e]))n.set(t.id,{...t,children:[]});for(let e of fS([...t])){let t=n.get(e.id);n.set(e.id,{...t,...e,children:[]})}return pS([...n.values()])}function Xk(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??Zk(e.cursor.before):void 0;for(let t of e.nodes)n.set(t.nodeId,Qk(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??Zk(e.cursor.before),lastEventSequence:e.lastEventSequence??Zk(e.cursor.after),nextBeforeSequence:o,nextBeforeCursor:a,hasOlderEvents:i,nodes:r,rawEvents:t}}function Zk(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function Qk(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 $k=128;function eA({selectedPiboSessionId:e,showRawEvents:t,setLiveTraceOverlay:n}){let r=Sk(),[i,a]=(0,v.useState)(50),[o,s]=(0,v.useState)(80),[c,l]=(0,v.useState)(null),[u,d]=(0,v.useState)(void 0),[f,p]=(0,v.useState)(!1),m=(0,v.useRef)(null),h=(0,v.useRef)(new Set),g=(0,v.useMemo)(()=>e?zk(e):null,[e]),_=(0,v.useMemo)(()=>e?Bk(e,{includeRawEvents:!1,rawEventsLimit:0,pageSize:50}):null,[e]),y=Ik({queryKey:g??[`chat`,`trace-summary`,`idle`],queryFn:async({signal:t})=>{if(!e||!g)throw Error(`Session is required`);let n=r.getQueryData(g),i=await Ib(e,n?.version,{signal:t});if(i.notModified&&n)return n;if(!i.summary)throw Error(`Trace summary response missing payload.`);return i.summary},enabled:!1,staleTime:Lk,gcTime:Rk,refetchOnWindowFocus:!1,retry:1}),b=Ik({queryKey:_??[`chat`,`trace-page`,`idle`,`compact`,o,50,`tail`],queryFn:async({signal:t})=>{if(!e||!_)throw Error(`Session is required`);let n=r.getQueryData(_),i=await Lb(e,{limit:50,knownVersion:n?.version,signal:t});if(i.notModified&&n)return n;if(!i.timeline)throw Error(`Trace timeline response missing payload.`);return Xk(i.timeline)},enabled:!!e,staleTime:Lk,gcTime:Rk,refetchOnWindowFocus:!1,retry:1});(0,v.useEffect)(()=>{let t=_?r.getQueryData(_):void 0;a(50),s(80),d(void 0),p(!1),l(t?.piboSessionId===e?t:null),n(null),m.current=null,h.current=new Set},[r,e,n,_]);let x=Ik({queryKey:e?[`chat`,`trace-raw-events`,e,o,u??`tail`]:[`chat`,`trace-raw-events`,`idle`],queryFn:async({signal:t})=>{if(!e)throw Error(`Session is required`);return Rb(e,{limit:o,beforeSequence:u,signal:t})},enabled:!!(e&&t),staleTime:Lk,gcTime:Rk,refetchOnWindowFocus:!1,retry:1});(0,v.useEffect)(()=>{let t=b.data;!t||t.piboSessionId!==e||($v()&&cy(t.piboSessionId,{overlayEventCount:0,traceBaseOutputLength:zO(t),traceBaseUpdated:!0}),(0,v.startTransition)(()=>{l(e=>e?.piboSessionId===t.piboSessionId?Jk(e,t):t),n(e=>Vk(e,t))}))},[e,n,b.data]),(0,v.useEffect)(()=>{let t=x.data;!t||t.piboSessionId!==e||(0,v.startTransition)(()=>{l(e=>{if(!e)return e;if(u===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))]}})})},[u,x.data,e]);let S=(0,v.useCallback)(async n=>{if(!e||!n)return;let i=`${e}:${n}`;if(m.current||h.current.has(i))return;m.current=i,p(!0);let s=Bk(e,{includeRawEvents:t,rawEventsLimit:o,pageSize:50,beforeCursor:n});try{let t=await r.fetchQuery({queryKey:s,queryFn:async({signal:t})=>{let i=r.getQueryData(s),a=await Lb(e,{limit:50,beforeCursor:n,knownVersion:i?.version,signal:t});if(a.notModified&&i)return i;if(!a.timeline)throw Error(`Trace timeline response missing payload.`);return Xk(a.timeline)},staleTime:Lk,gcTime:Rk});(0,v.startTransition)(()=>{l(e=>e?qk(e,t):t),a(e=>e+(t.pageSize??50))}),tA(h.current,i)}finally{m.current===i&&(m.current=null),p(!1)}},[r,o,e,t]),C=(0,v.useCallback)(()=>{let e=c?.rawEvents[0]?.eventSequence;d(e),s(e=>e+80)},[c?.rawEvents]);return{baseTraceView:c,traceEventLimit:i,rawEventLimit:o,traceSummaryQuery:y,tracePageQuery:b,rawEventsQuery:x,loadingOlderTracePage:f,tracePageReady:!!_,loadOlderTracePage:S,loadMoreRawEvents:C}}function tA(e,t){if(e.add(t),e.size<=$k)return;let n=e.values().next();n.done||e.delete(n.value)}function nA(e){let t=e.currentEvents,n,r,i=()=>(r??=new Set(t.map(cA)),r),a=e=>{n??=t.slice(),n.push(e),t=n};for(let o of e.streamEvents){let s=aA(o,e.piboSessionId,e.nextSequence,e.now??(()=>new Date().toISOString()));if(!s)continue;if(rA(s)){t=iA(t,s),n=t,r=void 0;continue}let c=cA(s),l=i();l.has(c)||(l.add(c),a(s))}return t}function rA(e){return e.type===`assistant_message`||e.type===`thinking_finished`||e.type===`tool_execution_finished`}function iA(e,t){return t.type===`assistant_message`?[...sA(e,t,`assistant_delta`),t]:t.type===`thinking_finished`?[...sA(e,t,`thinking_delta`),t]:t.type===`tool_execution_finished`?[...sA(e,t,`tool_execution_updated`),t]:e}function aA(e,t,n,r){if(e.type===`RAW_EVENT`&&dA(e.event)&&typeof e.event.type==`string`){let i=e.event;return oA(e,t,e.event.type,i,n,r)}if(e.type===`TEXT_MESSAGE_CONTENT`&&typeof e.delta==`string`)return oA(e,t,`assistant_delta`,{type:`assistant_delta`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,...uA(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 oA(e,t,`thinking_delta`,{type:`thinking_delta`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,...uA(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 oA(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 oA(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 oA(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 oA(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 oA(e,t,n,r,i,a){let o=typeof e.streamFrameId==`string`?e.streamFrameId:void 0,s=typeof e.streamFrameIndex==`number`?e.streamFrameIndex:void 0,c=typeof e.liveReplayId==`number`&&Number.isFinite(e.liveReplayId)?e.liveReplayId:void 0,l=i();return{id:typeof e.streamId==`number`?`stream:${e.streamId}:${s??`raw`}:${n}`:c===void 0?o?`stream:${o}:${n}`:`live:${l}:${n}`:`live-replay:${c}:${n}`,piboSessionId:t,eventSequence:l,streamId:typeof e.streamId==`number`?e.streamId:void 0,streamFrameIndex:s,eventId:typeof r.eventId==`string`?r.eventId:void 0,type:n,createdAt:a(),payload:r}}function sA(e,t,n){let r=lA(t);return e.filter(e=>e.type!==n||lA(e)!==r)}function cA(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 lA(e){let t=dA(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 uA(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 dA(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function fA(e){try{let t=JSON.parse(e.data);if(typeof t.type!=`string`)return;let n=e.lastEventId?iS(e.lastEventId):void 0;return{...t,...e.lastEventId?{streamFrameId:e.lastEventId}:{},...n?{streamId:n.streamId,streamFrameIndex:n.frameIndex}:{}}}catch{return}}function pA(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:hA(n),exact:!1,...r?.liveReplayId===void 0?{}:{liveReplayId:r.liveReplayId}})}function mA(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 hA(e){return`${e}:999999`}function gA(e){if(e.type===`RUN_FINISHED`||e.type===`TEXT_MESSAGE_END`)return 300;if(e.type===`RUN_ERROR`)return 0}function _A(e){return e.type===`RUN_STARTED`||e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`||e.type===`TEXT_MESSAGE_END`}function vA(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 yA(e,t,n){if(n.type===`RUN_STARTED`||n.type===`RUN_FINISHED`||n.type===`RUN_ERROR`){e.delete(t);return}let r=SA(n);r&&e.get(t)?.delete(r)}function bA(e,t,n){let r=xA(n);if(!r)return!1;let i=e.get(t);return i||(i=new Set,e.set(t,i)),i.has(r)?!1:(i.add(r),!0)}function xA(e){if(e.type===`TEXT_MESSAGE_CONTENT`||e.type===`REASONING_MESSAGE_CONTENT`)return`${e.type}:${e.messageId}`}function SA(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 CA=500,wA=1e4,TA=45e3,EA=15e3,DA=100;function OA({selectedPiboSessionId:e,tracePageData:t,currentTraceView:n,liveEventSeqRef:r,selectedSessionStatus:i,tracePageReady:a,setLiveTraceOverlay:o,onRefreshTrace:s,onRefreshBootstrap:c,onError:l}){let u=(0,v.useRef)(new Map),d=(0,v.useRef)(void 0),f=(0,v.useRef)(void 0),p=(0,v.useRef)(new Map),m=(0,v.useRef)(new Map),h=(0,v.useRef)(null),g=(0,v.useRef)(void 0),_=(0,v.useRef)(0),[y,b]=(0,v.useState)(0);(0,v.useEffect)(()=>{let n=t;if(!n||n.piboSessionId!==e)return;let i=n.rawEvents.map(e=>e.eventSequence??0).reduce((e,t)=>Math.max(e,t),0);r.current=Math.max(r.current,i+1),n.latestStreamId!==void 0&&pA(m.current,n.piboSessionId,n.latestStreamId)},[r,e,t]);let x=(0,v.useCallback)(e=>{let t=u.current.get(e);t?.length&&(o(n=>{let i=nA({currentEvents:n?.piboSessionId===e?n.events:[],streamEvents:t,piboSessionId:e,nextSequence:()=>r.current++});return iy(e,t.length,i.length),{piboSessionId:e,events:i}}),u.current.delete(e))},[]),S=(0,v.useCallback)(()=>{if(!(d.current!==void 0||f.current!==void 0||!e)){if(document.hidden){f.current=setTimeout(()=>{f.current=void 0,x(e)},DA);return}d.current=requestAnimationFrame(()=>{d.current=void 0,x(e)})}},[x,e]),C=(0,v.useCallback)((t,n,r=!1)=>{yA(p.current,t,n);let i=r||bA(p.current,t,n),a=u.current.get(t)??[];a.push(n),u.current.set(t,a),ry(t,n,a.length,i),i||t!==e?x(t):S()},[x,S,e]);(0,v.useEffect)(()=>()=>{d.current!==void 0&&cancelAnimationFrame(d.current),f.current!==void 0&&clearTimeout(f.current),g.current!==void 0&&clearTimeout(g.current)},[]);let w=(0,v.useCallback)((e,t)=>{mA(m.current,e,t)},[]),T=(0,v.useCallback)((e=0)=>{if(g.current!==void 0){if(e>0)return;clearTimeout(g.current)}g.current=setTimeout(()=>{g.current=void 0,b(e=>e+1)},e)},[]),E=(0,v.useCallback)(()=>{if(!e)return;x(e),s().catch(e=>l(kA(e))),c().catch(e=>l(kA(e)));let t=h.current;(!t||t.piboSessionId!==e||t.events.readyState===2||Date.now()-t.lastActivityAt>TA)&&T()},[x,l,c,s,T,e]);(0,v.useEffect)(()=>{if(!e||!a||!n||n.piboSessionId!==e)return;let t=new URLSearchParams({piboSessionId:e});t.set(`mode`,`live`);let r=m.current.get(e),i=r?.cursor??(n.latestStreamId===void 0?void 0:hA(n.latestStreamId));i!==void 0&&t.set(`since`,i),r?.liveReplayId!==void 0&&t.set(`liveSince`,String(r.liveReplayId));let o=new EventSource(`/api/chat/events?${t.toString()}`),u=Date.now();h.current={piboSessionId:e,events:o,openedAt:u,lastActivityAt:u};let d=!1,f,p,v=!1,y=!1,b=(t,n=!1)=>{if(f){if(!n)return;clearTimeout(f)}sy(e,t),f=setTimeout(()=>{f=void 0,s().catch(e=>l(kA(e)))},t)},S=()=>{if(v){y=!0;return}v=!0,c().catch(e=>l(kA(e))).finally(()=>{v=!1,y&&(y=!1,E(250,!0))})},E=(e,t=!1)=>{if(p){if(!t)return;clearTimeout(p)}p=setTimeout(()=>{p=void 0,S()},e)},D=()=>{E(900,!0)};return o.onopen=()=>{_.current=0,g.current!==void 0&&(clearTimeout(g.current),g.current=void 0),ey(e,o.readyState);let t=h.current;t?.events===o&&(t.lastActivityAt=Date.now())},o.onerror=()=>{if(d)return;ty(e,o.readyState);let t=h.current;t?.events===o&&(t.lastErrorAt=Date.now());let n=_.current++;T(Math.min(wA,CA*2**n))},o.addEventListener(`pibo`,t=>{if(d)return;let n=fA(t);if(!n)return;let r=n.piboSessionId||e,i=h.current;if(i?.events===o&&(i.lastActivityAt=Date.now()),w(r,n),ny(r,n,t.lastEventId,o.readyState),r===e&&n.type===`ready`&&n.liveReplay?.missed&&b(0,!0),ly(n))return;let a=n.type!==`TEXT_MESSAGE_CONTENT`&&n.type!==`REASONING_MESSAGE_CONTENT`;r===e&&vA(n)&&C(r,n,a);let s=gA(n);r===e&&s!==void 0?b(s,!0):r===e&&n.type!==`ready`&&n.type!==`RAW_EVENT`&&b(1500,!0),_A(n)&&(n.type===`RUN_FINISHED`||n.type===`RUN_ERROR`||n.type===`TEXT_MESSAGE_END`?D():E(r===e?0:150))}),()=>{d=!0,f&&clearTimeout(f),p&&clearTimeout(p),x(e),h.current?.events===o&&(h.current=null),o.close()}},[n?.piboSessionId,C,x,l,c,s,w,T,y,e,a]),(0,v.useEffect)(()=>{n?.piboSessionId&&x(n.piboSessionId)},[n?.piboSessionId,x]),(0,v.useEffect)(()=>{let e=()=>E(),t=()=>{document.hidden||E()};return window.addEventListener(`focus`,e),window.addEventListener(`online`,e),window.addEventListener(`pageshow`,e),document.addEventListener(`visibilitychange`,t),()=>{window.removeEventListener(`focus`,e),window.removeEventListener(`online`,e),window.removeEventListener(`pageshow`,e),document.removeEventListener(`visibilitychange`,t)}},[E]),(0,v.useEffect)(()=>{if(!e||i!==`running`)return;let t=window.setInterval(()=>{x(e);let t=h.current;(!t||t.piboSessionId!==e||t.events.readyState===2||Date.now()-t.lastActivityAt>TA)&&(s().catch(e=>l(kA(e))),T())},EA);return()=>window.clearInterval(t)},[x,l,s,T,e,i])}function kA(e){return e instanceof Error?e.message:String(e)}var AA=10;function jA(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,AA)}:e}function MA(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 NA(e,t){return!t||!e[t]?.length?e:{...e,[t]:[]}}function PA(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=>jA(r,e,n,t))},[t,e]),detachUploadAttachment:(0,v.useCallback)(t=>{r(n=>MA(n,e,t))},[e]),clearSelectedUploadAttachments:(0,v.useCallback)(()=>{r(t=>NA(t,e))},[e])}}function FA({selectedPiboSessionId:e,onError:t,formatError:n}){let[r,i]=(0,v.useState)([]),[a,o]=(0,v.useState)(!1),[s,c]=(0,v.useState)(()=>e?RD(e):null),[l,u]=(0,v.useState)(()=>GD()),[d,f]=(0,v.useState)(!1),p=!!(e&&s?.piboSessionId===e&&s.installed),m=!!e&&(a||p),h=Ik({queryKey:[`web-annotations`,`app`,e],queryFn:async()=>{if(!e)throw Error(`Session is required`);return fx(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?HD(e):[]),c(e?RD(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(VD(e.detail)),r=n=>{n.key===zD(e)&&t(BD(n.newValue))},i=()=>t(RD(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&&UD(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&&UD(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&&UD(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 KD(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=>px(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 IA=new WeakMap;function LA(e,t,n){let r=n.map(e=>RA(e)),i=WA(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 RA(e){let t=IA.get(e);if(t)return t;let n=UA(e.startedAt)??Date.now()*1e3,r=UA(e.completedAt),i=HA(e.status),a=zA(e.type),o={id:e.id,parentId:e.parentId,name:BA(e),spanType:a,startTime:n,endTime:r,durationUs:e.durationMs===void 0?void 0:e.durationMs*1e3,attributes:VA(e),status:i,statusMessage:e.error,events:e.error?[{name:`exception`,timestamp:r??n,attributes:{message:e.error}}]:[],children:e.children?.map(RA),pibo:{entryId:e.entryId,linkedPiboSessionId:e.linkedPiboSessionId,traceNodeType:e.type,traceOrder:e.orderKey,stableKey:e.stableKey,source:e.source}};return IA.set(e,o),o}function zA(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 BA(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 VA(e){let t={};return 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??``),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`]=GA(e.input)?e.input.startedBy:`pibo_run_start`,t[`async_agent.query`]=GA(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 HA(e){return e===`running`?`UNSET`:e===`error`?`ERROR`:`OK`}function UA(e){if(!e)return;let t=new Date(e).getTime();return Number.isFinite(t)?t*1e3:void 0}function WA(e){return e.flatMap(e=>[e,...e.children?WA(e.children):[]])}function GA(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function KA(e){return(e.selectedPiboSessionId?S(e.sessionNodes,e.selectedPiboSessionId):void 0)?.title||e.traceTitle||e.selectedPiboSessionId||e.fallback}function qA(e,t){return t?{sessionBreadcrumbs:QA(e,t),originSession:XA(e,t),derivedSessions:ZA(e,t)}:{sessionBreadcrumbs:[],originSession:void 0,derivedSessions:[]}}function JA(e){let t=e.selectedPiboSessionId?S(e.bootstrap.sessions,e.selectedPiboSessionId):void 0,n=nj(e.currentTraceView);return tj(e.selectedSessionActiveModel,e.bootstrap.runtimeStatus?.thinkingLevel??n.level??$A(e.bootstrap,e.selectedSessionProfile,!!t?.parentId),e.bootstrap.runtimeStatus?.fastMode??n.fast??ej(e.bootstrap,e.selectedSessionProfile,!!t?.parentId)??!1)}function YA(e){return{traceView:e.currentTraceView,selectedTrace:e.currentTraceView?LA(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,selectedSessionStatus:e.selectedSessionStatus,selectedSessionSignal:e.selectedSessionSignal,signals:e.signals,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 XA(e,t){let n=S(e,t);if(!n?.originId)return;let r=S(e,n.originId);return{piboSessionId:n.originId,label:r?aj(r,0):n.originId}}function ZA(e,t){return S(e,t)?.derivedSessions.map(e=>({piboSessionId:e.piboSessionId,label:oj(e),profile:e.profile,status:e.status}))??[]}function QA(e,t){return C(e,t).map((e,t)=>({piboSessionId:e.piboSessionId,label:aj(e,t)}))}function $A(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 ej(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 tj(e,t,n){if(e)return[e,t,n?`fast`:void 0].filter(Boolean).join(` `)}function nj(e){let t={};if(!e)return t;for(let n of rj(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`&&ij(e.level)?e.level:void 0)??t.level,fast:n.title===`fast_mode`?e?.mode===`fast`:t.fast}}return t}function rj(e){return e.flatMap(e=>[e,...rj(e.children)])}function ij(e){return rT.includes(e)}function aj(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 oj(e){return e.subagentName&&e.subagentName!==e.profile?`${e.subagentName} (${e.profile})`:e.title||e.profile||e.subagentName||`Untitled Session`}function sj({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 cj(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 lj(e,t,n){return{piboSessionId:t,events:[...e?.piboSessionId===t?e.events:[],n]}}function uj(e){return e instanceof Error?e.message:String(e)}function dj({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,showRawEvents:T,showThinking:E,expandThinking:D,commands:O,skills:k,composerText:ee,composerFocusSignal:A,onComposerTextChange:te,onToggleRawEvents:ne,onToggleThinking:re,onToggleExpandThinking:ie,onSessionAgentProfileChange:j,onFork:M,onOpenSession:ae,onSelectSessionView:oe,onCommand:se,onThinkingLevelChange:ce,onRefreshTrace:N,onRefreshBootstrap:le,onSend:ue,onError:de}){let P=(0,v.useRef)(0),[fe,pe]=(0,v.useState)(null),[me,he]=(0,v.useState)(null),[ge,_e]=(0,v.useState)(!1),ve=(0,v.useRef)(null),{baseTraceView:ye,rawEventLimit:be,traceSummaryQuery:F,tracePageQuery:xe,rawEventsQuery:Se,loadingOlderTracePage:Ce,tracePageReady:we,loadOlderTracePage:Te,loadMoreRawEvents:Ee}=eA({selectedPiboSessionId:t,showRawEvents:T,setLiveTraceOverlay:pe}),{selectedWebAnnotationIds:De,selectedWebAnnotations:Oe,visibleWebAnnotations:ke,webAnnotationsPanelCollapsed:Ae,webAnnotationsPanelRendered:je,webAnnotationsPanelVisible:Me,webAnnotationsQuery:Ne,clearingWebAnnotations:Pe,setWebAnnotationsPanelVisible:Fe,toggleWebAnnotationAttachment:Ie,detachWebAnnotationAttachment:Le,clearSelectedWebAnnotationAttachments:Re,toggleWebAnnotationsPanelCollapsed:ze,clearVisibleWebAnnotations:Be}=FA({selectedPiboSessionId:t,onError:de,formatError:$D}),{selectedUploadAttachments:Ve,attachUploadedFiles:He,detachUploadAttachment:Ue,clearSelectedUploadAttachments:We}=PA(t,(0,v.useCallback)(()=>`upload-${w()}`,[])),Ge=BO({selectedPiboSessionId:t,baseTraceView:ye,liveTraceOverlay:fe,selectedSessionStatus:c});OA({selectedPiboSessionId:t,tracePageData:xe.data,currentTraceView:Ge,liveEventSeqRef:P,selectedSessionStatus:c,tracePageReady:we,setLiveTraceOverlay:pe,onRefreshTrace:N,onRefreshBootstrap:le,onError:de});let Ke=JA({bootstrap:e,selectedPiboSessionId:t,selectedSessionProfile:o,selectedSessionActiveModel:s,currentTraceView:Ge}),qe=(0,v.useMemo)(()=>qA(e.sessions,t),[e.sessions,t]),Je=!!t&&xe.isFetching&&!Ge,Ye=xe.error?uj(xe.error):F.error?uj(F.error):null,Xe=Ge?.piboSessionId??t??``,Ze=d&&sO(d)?cO(d,c):null,Qe=e=>{for(let n of[750,2e3,5e3,1e4])window.setTimeout(()=>{t===e&&xe.refetch().catch(e=>de(uj(e)))},n)},$e=async(e,t)=>{let n=cj(e,t);pe(e=>lj(e,n.piboSessionId,n.optimisticEvent)),await ue(n.text,n.webAnnotationIds,n.fileAttachmentPaths,n.clientTxnId,t),Re(),We(),await Promise.all([xe.refetch(),Ne.refetch()]),Qe(n.piboSessionId)},et=(e,t)=>{pe(t=>{if(!t||t.piboSessionId!==e.piboSessionId)return t;let n=t.events.filter(t=>t.id!==e.clientTxnId);return n.length?{...t,events:n}:null}),te(t=>t||e.text),de(uj(t))},tt=async e=>{if(!t)return;let n=sj({piboSessionId:t,text:e,selectedWebAnnotations:Oe,selectedUploadAttachments:Ve,eventSequence:P.current++,now:new Date().toISOString(),clientTxnId:w()});if(c===`running`){he(n);return}try{await $e(n,`queue`)}catch(e){et(n,e)}},nt=()=>{!me||ge||(te(e=>e||me.text),he(null))},rt=async e=>{if(!(!me||ge)){_e(!0);try{await $e(me,e),he(null),de(null)}catch(e){et(me,e),he(null)}finally{_e(!1)}}},it=YA({currentTraceView:Ge,isLoading:Je,showThinking:E,expandThinking:D,selectedSessionProfile:o,sessionActiveModelBadge:Ke,selectedSessionStatus:c,selectedSessionSignal:l,signals:u,workflowProjectSession:d,workflowLifecycleEvents:f,sessionNodes:e.sessions,sessionLinks:qe,agentProfiles:e.agents,sessionProfileChangeDisabled:C||r,onSessionAgentProfileChange:j,onFork:M,onOpenSession:ae,onLoadOlderTracePage:()=>void Te(Ge?.nextBeforeCursor??Ge?.nextBeforeSequence),hasOlderTraceEvents:Ge?.hasOlderEvents===!0||Ge?.nextBeforeCursor!==void 0||typeof Ge?.nextBeforeSequence==`number`,isFetchingOlderTracePage:Ce,onThinkingLevelChange:ce,onRefreshTrace:N,onRefreshBootstrap:le,onError:de});return(0,I.jsxs)(I.Fragment,{children:[me?(0,I.jsx)(TO,{title:`Session is running`,description:`Choose how this message should be delivered.`,onClose:nt,initialFocusRef:ve,closeDisabled:ge,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:ve,type:`button`,disabled:ge,onClick:()=>void rt(`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`,disabled:ge,onClick:()=>void rt(`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)(xO,{selectedPiboSessionId:t,selectedRoomId:n,fallbackRoomId:e.selectedRoomId??void 0,sessionViewId:y,loadingTrace:Je,roomNavigationPending:i,sessionNavigationPending:a,traceError:Ye,showRawEvents:T,currentTraceView:Ge,rawEventLimit:be,tracePageFetching:T?Se.isFetching:xe.isFetching,onLoadMoreRawEvents:Ee,headerProps:{title:KA({sessionNodes:e.sessions,selectedPiboSessionId:t,traceTitle:Ge?.title,fallback:e.room?.name??n??void 0}),roomLabel:e.room?.name??n??`Room`,headerPiboSessionId:Xe,piboSessionId:t,piboRoomId:n??e.selectedRoomId??void 0,webAnnotationsDisabled:!t||r,webAnnotationsPanelRendered:je,workflowHeader:Ze,sessionViewId:y,sessionViews:b,currentSessionView:x,allowedSessionViewIds:S,extraViewTabs:g,activeViewId:_,showRawEvents:T,showThinking:E,expandThinking:D,onShowWebAnnotationsPanel:()=>Fe(!0),onHideWebAnnotationsPanel:()=>Fe(!1),onSelectSessionView:oe,onToggleRawEvents:ne,onToggleThinking:re,onToggleExpandThinking:ie,onError:de},projectSessionCreatePanel:p,workflowStartPanel:m,projectModulePanel:h,currentSessionView:x,sessionViewProps:it,webAnnotationsPanelRendered:je,webAnnotationsPanelProps:{piboSessionId:t,annotations:ke,selectedIds:De,loading:Ne.isLoading||Ne.isFetching||Pe,error:Ne.error?uj(Ne.error):null,collapsed:Ae,onRefresh:()=>void Ne.refetch(),onToggle:Ie,onClear:()=>void Be(),onCollapse:ze,onClose:()=>Fe(!1)},composerProps:{sessionId:t,disabled:!t||r,commands:O,skills:k,value:ee,focusSignal:A,selectedWebAnnotations:Oe,selectedUploadAttachments:Ve,onValueChange:te,onCommand:se,onDetachWebAnnotation:Le,onClearWebAnnotations:Re,onAttachUploadedFiles:He,onDetachUploadAttachment:Ue,onClearUploadAttachments:We,onSend:tt}})]})}function fj({mode:e,onSelectSession:t,onNewSession:n,onDeleteSession:r,onRenameSession:i,onSelectRoom:a}){return e.kind===`rooms`?(0,I.jsx)(yj,{candidates:e.candidates,workspace:e.workspace,onSelectRoom:a}):(0,I.jsx)(_j,{sessions:e.sessions,selectedPiboSessionId:e.selectedPiboSessionId,onSelectSession:t,onNewSession:n,onDeleteSession:r,onRenameSession:i})}function pj(e){return e===`running`?`running`:e===`error`?`error`:e===`completed`?`completed`:`idle`}var mj={running:`bg-cyan-400`,idle:`bg-slate-500`,error:`bg-rose-500`,completed:`bg-emerald-500`},hj={running:`running`,idle:`idle`,error:`error`,completed:`completed`};function gj({status:e}){let t=pj(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 ${mj[t]}`,"aria-hidden":`true`}),hj[t]]})}function _j({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=>(0,I.jsx)(`li`,{className:`shrink-0`,children:(0,I.jsx)(vj,{session:e,isActive:e.piboSessionId===t,onSelect:()=>n(e.piboSessionId),onDelete:()=>void i(e.piboSessionId),onRename:t=>void a(e.piboSessionId,t)})},e.piboSessionId)),o.length===0&&(0,I.jsx)(`li`,{className:`text-xs text-slate-500 px-2 py-1`,children:`No sessions yet — click + to start one.`})]})]})}function vj({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)(gj,{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 yj({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 `,bj(e.createdAt),` · Updated `,bj(e.updatedAt)]})]})},e.id))})]})}function bj(e){try{return new Date(e).toLocaleString()}catch{return e}}function xj(){return new URLSearchParams(window.location.search).get(`workspace`)}function Sj(){return new URLSearchParams(window.location.search).get(`roomId`)}function Cj(){let e=(0,v.useMemo)(()=>xj(),[]),[t,n]=(0,v.useState)(()=>Sj()),[r,i]=(0,v.useState)(()=>Sj()?{kind:`sessions`,roomId:Sj(),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(uj(t))}})(),()=>{e=!0}},[t]);let y=(0,v.useCallback)(async()=>{if(t)try{o(await ee(s??void 0,!1,t,!0))}catch(e){m(uj(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?D(a.capabilities.actions):[],[a]),C=(0,v.useMemo)(()=>O(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)},[]),k=(0,v.useCallback)(async e=>{if(t)try{let n=await A(e,t);await y(),n.session?.id&&c(n.session.id)}catch(e){m(uj(e))}},[t,y]),j=(0,v.useCallback)(async e=>{try{await ne(e,`delete`),await y(),s===e&&c(null)}catch(e){m(uj(e))}},[y,s]),M=(0,v.useCallback)(async(e,t)=>{try{await te(e,{title:t}),await y()}catch(e){m(uj(e))}},[y]),ae=(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()}`)},[]),ce=(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(uj(e))}},[s,t,y]),N=(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=oe(n.slice(r.length));if(!e)return m(`Usage: /download <path>`),!0;try{await le(e,{piboSessionId:s,roomId:t??void 0})}catch(e){m(uj(e))}return!0}try{let e=se(i.action,n.slice(r.length).trim());await ie(s,i.action,e),await y()}catch(e){m(uj(e))}return!0},[S,s,t,y]),ue=(0,v.useMemo)(()=>lD(),[]),de=(0,v.useMemo)(()=>uD(pe),[]);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)(fj,{mode:r,onSelectSession:E,onNewSession:k,onDeleteSession:j,onRenameSession:M,onSelectRoom:ae}),(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`)return(0,I.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,I.jsx)(fj,{mode:{kind:`rooms`,candidates:a.rooms??r.candidates,workspace:r.workspace},onSelectSession:E,onNewSession:k,onDeleteSession:j,onRenameSession:M,onSelectRoom:ae}),(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 P=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)(fj,{mode:{kind:`sessions`,roomId:t??``,sessions:T,selectedPiboSessionId:s},onSelectSession:E,onNewSession:k,onDeleteSession:j,onRenameSession:M,onSelectRoom:ae}),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)(dj,{bootstrap:a,selectedPiboSessionId:s,selectedRoomId:t,selectedRoomArchived:!1,selectedSessionProfile:P?.profile??`default`,selectedSessionActiveModel:P?x(a,P)??void 0:void 0,selectedSessionStatus:P?.status,sessionViewId:pe,sessionViews:ue,currentSessionView:de,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:N,onThinkingLevelChange:e=>void N(`/thinking ${e}`),onRefreshTrace:b,onRefreshBootstrap:y,onSend:ce,onError:m})})]})}var wj=document.getElementById(`root`);wj&&(0,y.createRoot)(wj).render((0,I.jsx)(v.StrictMode,{children:(0,I.jsx)(Cj,{})}));
39
+ `).trim();if(!t.startsWith(`{`)&&!t.startsWith(`[`))continue;let n=Qb(t);if(n!==void 0)return Zb(n,r.slice(0,e).join(` `).trim()||void 0)}}function Zb(e,t){let n=Mb(e);if(n.kind===`text`){let e=Xb(n.text);return e?.kind===`json`?{...e,meta:e.meta??t}:{kind:`text`,text:n.text}}return{kind:`json`,value:e,meta:t}}function Qb(e){if(!(!e.startsWith(`{`)&&!e.startsWith(`[`)))try{let t=JSON.parse(e);return typeof t==`object`&&t?t:void 0}catch{return}}function $b(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function ex({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)(tx,{value:t}),(0,I.jsx)(`span`,{className:`text-[#d4d4d4]`,children:`)`})]})}function tx({value:e}){let[t,n]=(0,v.useState)(()=>new Set([`$`])),[r,i]=(0,v.useState)(()=>new Set);return(0,I.jsx)(nx,{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 nx({value:e,path:t,expandedPaths:n,expandedStrings:r,onTogglePath:i,onToggleString:a}){if(Array.isArray(e))return(0,I.jsx)(rx,{value:e,path:t,open:`[`,close:`]`,expandedPaths:n,expandedStrings:r,onTogglePath:i,onToggleString:a});if(ax(e))return(0,I.jsx)(rx,{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`,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 rx({value:e,path:t,open:n,close:r,expandedPaths:i,expandedStrings:a,onTogglePath:o,onToggleString:s}){let c=Array.isArray(e)?e.map((e,t)=>[String(t),e]):Object.entries(e);return i.has(t)?(0,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:`Collapse JSON`,"aria-label":`Collapse JSON at ${t}`,"data-inline-json-path":t,children:[(0,I.jsx)(`span`,{className:`compact-terminal-json-caret`,children:`▾`}),n]}),c.map(([n,r],c)=>{let l=`${t}.${ix(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)(nx,{value:r,path:l,expandedPaths:i,expandedStrings:a,onTogglePath:o,onToggleString:s})]},l)}),(0,I.jsx)(`span`,{className:`text-[#737373]`,children:r})]}):(0,I.jsxs)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),o(t)},className:`compact-terminal-json-toggle align-baseline text-[#737373]`,title:`Expand JSON`,"aria-label":`Expand JSON at ${t}`,"data-inline-json-path":t,children:[(0,I.jsx)(`span`,{className:`compact-terminal-json-caret`,children:`▸`}),n,`...`,r]})}function ix(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`.`,`\\.`)}function ax(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}var ox=120;function sx({line:e,status:t,clampLines:n}){let r=`min-w-0 whitespace-pre-wrap break-words ${n?`block overflow-hidden`:``}`,i=dx(e.tokens),a=i.length>ox;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 ${lx(e.prefix,t)}`,children:cx(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:ux(e),children:e.text},`${t}:${e.text}`)),e.functionCall?(0,I.jsx)(ex,{name:e.functionCall.name,input:e.functionCall.input}):null]})]})}function cx(e=`none`){switch(e){case`bullet`:return`•`;case`detail`:return`└`;case`continuation`:return` `;case`prompt`:return`›`;default:return` `}}function lx(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 ux(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 dx(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 fx(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),k(`/api/web-annotations?${n.toString()}`)}async function px(e,t){return k(`/api/web-annotations/${encodeURIComponent(e)}`,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify(_x(t))})}async function mx(e){let t=new URLSearchParams;return e?.trim()&&t.set(`cdpUrl`,e.trim()),k(`/api/web-annotations/targets${t.size?`?${t.toString()}`:``}`)}async function hx(e){return k(`/api/web-annotations/bindings`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(_x(e))})}async function gx(e,t){return k(`/api/web-annotations/bindings/${encodeURIComponent(e)}/inject`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(_x(t))})}function _x(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0&&e!==``))}async function vx(e,t,n){return k(`/api/chat/projects/${encodeURIComponent(e)}/workflow-sessions/${encodeURIComponent(t)}/human-actions`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n)})}function yx(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 bx(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 xx(e){return Sx(e)?e.result:e}function Sx(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.type===`execution_result`}var Cx={device_code:`Device code`,api_key:`API key`,oauth:`Browser OAuth`};function wx({row:e,piboSessionId:t}){let n=yx(e.output)?e.output:void 0,r=(0,v.useMemo)(()=>n?.providers??[],[n?.providers]),[i,a]=(0,v.useState)({type:`select_provider`}),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(``),[u,d]=(0,v.useState)(``),[f,p]=(0,v.useState)(null),m=(0,v.useCallback)(()=>{a({type:`select_provider`}),l(``),d(``)},[]),h=(0,v.useCallback)(async e=>{try{await navigator.clipboard.writeText(e),p(e),window.setTimeout(()=>p(t=>t===e?null:t),1600)}catch{}},[]),g=(0,v.useCallback)(async e=>{if(!t){a({type:`error`,provider:e,message:`Select a chat session before starting login.`});return}s(!0),a({type:`device_starting`,provider:e});try{let n=xx(await ie(t,`login.start`,{provider:e.id}));if(!n?.url){a({type:`error`,provider:e,message:`No login URL returned.`});return}a({type:`device_flow`,provider:e,url:n.url,state:n.state,userCode:n.userCode,instructions:n.instructions})}catch(t){a({type:`error`,provider:e,message:t instanceof Error?t.message:String(t)})}finally{s(!1)}},[t]),_=(0,v.useCallback)(async(e,n,r)=>{if(t){s(!0);try{await ie(t,`login.complete`,{provider:e.id,state:n??``,...r?{code:r}:{}}),a({type:`success`,provider:e,message:`${e.name} login completed.`})}catch(t){a({type:`error`,provider:e,message:t instanceof Error?t.message:String(t)})}finally{s(!1)}}},[t]),y=(0,v.useCallback)(async e=>{if(!t)return;let n=c.trim();if(n){s(!0);try{await ie(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)(Tx,{title:i.type===`select_provider`?`Login`:Ox(i),tone:i.type===`error`?`red`:i.type===`success`?`green`:`cyan`,action:i.type===`select_provider`?void 0:(0,I.jsx)(Ex,{onClick:m,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)(Dx,{tone:`green`,children:`Configured`}):(0,I.jsx)(Dx,{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 g(i.provider),className:`inline-flex items-center gap-1 border border-[#3a3a3a] bg-transparent px-2 py-1 text-[11px] text-[#d4d4d4] hover:border-[#38bdf8] hover:text-[#38bdf8]`,children:[e===`api_key`?(0,I.jsx)(tt,{size:11}):(0,I.jsx)(ot,{size:11}),Cx[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)(at,{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:[kx(i.url),` `,(0,I.jsx)(Ke,{size:11})]}),(0,I.jsxs)(`button`,{type:`button`,onClick:()=>void h(i.url),className:`inline-flex items-center gap-1 border border-[#3a3a3a] px-1.5 py-0.5 text-[#737373] hover:border-[#38bdf8] hover:text-[#38bdf8]`,children:[f===i.url?(0,I.jsx)(ze,{size:10}):(0,I.jsx)(Ue,{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 h(i.userCode),className:`border border-[#1f4960] px-2 py-0.5 font-semibold tracking-widest text-[#38bdf8] hover:border-[#38bdf8]`,children:i.userCode}),(0,I.jsx)(`span`,{className:`text-[#737373]`,children:`then`}),(0,I.jsxs)(`button`,{type:`button`,disabled:o,onClick:()=>void _(i.provider,i.state),className:`inline-flex items-center gap-1 border border-[#3a3a3a] px-2 py-0.5 text-[#d4d4d4] hover:border-[#38bdf8] hover:text-[#38bdf8] disabled:opacity-50`,children:[o?(0,I.jsx)(at,{size:11,className:`animate-spin`}):(0,I.jsx)(ze,{size:11}),` Complete`]})]}):(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,I.jsx)(`input`,{value:u,onChange:e=>d(e.target.value),placeholder:`authorization code`,className:`min-w-0 flex-1 border border-[#2a2a2a] bg-[#0b0b0b] px-2 py-1 text-[11px] text-[#d4d4d4] outline-none focus:border-[#38bdf8]`}),(0,I.jsxs)(`button`,{type:`button`,disabled:o||!u.trim(),onClick:()=>void _(i.provider,i.state,u.trim()),className:`inline-flex items-center gap-1 border border-[#3a3a3a] px-2 py-1 text-[#d4d4d4] hover:border-[#38bdf8] hover:text-[#38bdf8] disabled:opacity-50`,children:[o?(0,I.jsx)(at,{size:11,className:`animate-spin`}):(0,I.jsx)(ze,{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,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&y(i.provider)},placeholder:`sk-...`,className:`min-w-[12rem] flex-1 border border-[#2a2a2a] bg-[#0b0b0b] px-2 py-1 text-[11px] text-[#d4d4d4] outline-none focus:border-[#38bdf8]`}),(0,I.jsxs)(`button`,{type:`button`,disabled:o||!c.trim(),onClick:()=>void y(i.provider),className:`inline-flex items-center gap-1 border border-[#3a3a3a] px-2 py-1 text-[#d4d4d4] hover:border-[#38bdf8] hover:text-[#38bdf8] disabled:opacity-50`,children:[o?(0,I.jsx)(at,{size:11,className:`animate-spin`}):(0,I.jsx)(ze,{size:11}),` Save`]})]}):i.type===`success`?(0,I.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px] text-[#22c55e]`,children:[(0,I.jsx)(ze,{size:13}),` `,i.message]}):(0,I.jsxs)(`div`,{className:`flex items-start gap-2 text-[11px] text-[#ef4444]`,children:[(0,I.jsx)(Le,{size:13,className:`mt-0.5 shrink-0`}),` `,(0,I.jsx)(`span`,{children:i.message})]})}):(0,I.jsx)(Tx,{title:`Login`,tone:`red`,children:`Unparseable login payload.`})}function Tx({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)(ot,{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 Ex({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)(Ce,{size:10}),` Back`]})}function Dx({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 Ox(e){return`provider`in e&&e.provider?e.provider.name:`Login`}function kx(e){try{let t=new URL(e);return`${t.host}${t.pathname}`}catch{return e.length>42?`${e.slice(0,39)}...`:e}}function Ax({row:e,piboSessionId:t,onModelChanged:n}){let r=xx(e.output),i=(bx(r)?r:void 0)?.providers??[],a=(0,v.useMemo)(()=>i.flatMap(e=>e.models.map(t=>({...t,providerLabel:e.label}))),[i]),[o,s]=(0,v.useState)(``),[c,l]=(0,v.useState)(null),[u,d]=(0,v.useState)(!1),[f,p]=(0,v.useState)(null),m=(0,v.useMemo)(()=>{let e=o.trim().toLowerCase();return e?a.filter(t=>`${t.providerLabel} ${t.provider} ${t.label} ${t.id}`.toLowerCase().includes(e)):a},[a,o]),h=async e=>{if(!(!t||u)){d(!0),l(e),p(null);try{await te(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.jsxs)(`div`,{className:`text-[11px] text-[#737373]`,children:[`Choose a model from authenticated providers. Use `,(0,I.jsx)(`span`,{className:`text-[#38bdf8]`,children:`/login`}),` to add providers.`]})]})}),(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)(ft,{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,onClick:()=>void h(e),className:`grid w-full grid-cols-[150px_1fr_auto] gap-2 border-b border-[#1f1f1f] px-3 py-2 text-left hover:bg-[#38bdf8]/10 disabled:opacity-50`,children:[(0,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]})]}),c?.provider===e.provider&&c?.id===e.id?(0,I.jsx)(Ae,{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.jsxs)(`div`,{className:`text-[#737373]`,children:[`No authenticated model providers found. Run `,(0,I.jsx)(`span`,{className:`text-[#38bdf8]`,children:`/login`}),` first.`]}),f?(0,I.jsx)(`div`,{className:`text-[11px] text-[#a3a3a3]`,children:f}):null]})]})}function jx(e={}){let t=[],n=[],r=Rx(e.warnings),i=Rx(e.errors);(e.session?.id||e.session?.title)&&t.push({id:`session`,label:`Session`,value:Mx([e.session?.title,e.session?.id].filter(Boolean).join(` | `))}),e.session?.profile&&t.push({id:`profile`,label:`Profile`,value:Mx(e.session.profile)}),e.session?.status&&t.push({id:`session-status`,label:`Session status`,value:Mx(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:Mx(e.model.label??[e.model.provider,e.model.id].filter(Boolean).join(`/`))}),e.runtime?.state&&t.push({id:`runtime`,label:`Runtime`,value:Mx(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:Mx(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:Mx(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`?Mx(e.fastMode):e.fastMode?`on`:`off`,tone:e.fastMode?`green`:`neutral`});let o=Rx(e.tools?.enabled),s=Rx(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:Mx(e.providerUsage.planType)}),e.providerUsage?.credits&&t.push({id:`provider-credits`,label:`Credits`,value:e.providerUsage.credits.unlimited?`unlimited`:Mx(e.providerUsage.credits.balance??`available`)}),e.message&&t.push({id:`message`,label:`Message`,value:Mx(e.message)}),n.push(Nx(e.contextUsage));for(let t of Px(e.providerUsage))n.push(t);return{kind:`status`,title:`Status`,fields:t,progress:n,warnings:r,errors:i}}function Mx(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 Nx(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=Fx(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:Ix(t)}}function Px(e){return e?.limits?.length?e.limits.map((t,n)=>{let r=Fx(t.usedPercent),i=Fx(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 ${Mx(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:Lx(i)}}):[{id:`provider`,label:`Provider quota`,state:`unavailable`,text:`Provider usage unavailable`,tone:`neutral`}]}function Fx(e){if(!(typeof e!=`number`||!Number.isFinite(e)))return Math.max(0,Math.min(100,e))}function Ix(e){return e===void 0?`neutral`:e>=80?`red`:e>=50?`yellow`:`green`}function Lx(e){return e===void 0?`neutral`:e<=20?`red`:e<=50?`yellow`:`green`}function Rx(e){return(e??[]).map(e=>Mx(e)).filter(e=>e.length>0)}function zx(e){switch(e.kind){case`tool.status`:return Bx(e);case`tool.thinking`:return Vx(e);case`tool.model`:return Hx(e);case`tool.login`:return Ux(e);case`tool.call`:case`tool.image`:case`tool.group.exploring`:case`tool.group.images`:return Wx(e);case`yielded.run`:return Gx(e,`yielded-run`,`Yielded run`,e.status===`error`?`red`:e.status===`running`?`cyan`:`green`);case`execution.compaction`:return Gx(e,`compaction`,e.status===`error`?`Compaction failed`:e.status===`running`?`Compacting`:`Compaction`,e.status===`error`?`red`:`magenta`);case`execution.command`:return Gx(e,`command`,`Command`,e.status===`error`?`red`:`yellow`);case`error`:return Gx(e,`error`,`Error`,`red`);default:return}}function Bx(e){let t=qx(e.output),n=Jx(t,`activeModel`)??Jx(t,`model`),r=jx({session:{id:Zx(t,`piboSessionId`)??Zx(t,`sessionId`),title:Zx(t,`sessionTitle`)??Zx(t,`title`),profile:Zx(t,`profile`)??Zx(t,`activeAgentId`)??Zx(t,`agentId`),status:$x(t,`disposed`)?`disposed`:Zx(t,`sessionStatus`)},model:n?{provider:Zx(n,`provider`),id:Zx(n,`id`),label:Zx(n,`label`)}:void 0,runtime:{state:$x(t,`disposed`)?`disposed`:$x(t,`processing`)?`processing`:$x(t,`streaming`)?`streaming`:Zx(t,`mode`)??`idle`,connected:$x(t,`connected`),queuedMessages:Qx(t,`queuedMessages`),processing:$x(t,`processing`),streaming:$x(t,`streaming`),disposed:$x(t,`disposed`)},cwd:Zx(t,`cwd`),contextUsage:Jx(t,`contextUsage`),providerUsage:Jx(t,`providerUsage`),tools:{enabled:Xx(t,`enabledTools`),active:Xx(t,`activeTools`)},thinking:Zx(t,`thinkingLevel`)?{level:Zx(t,`thinkingLevel`)}:void 0,fastMode:$x(t,`fastMode`),warnings:Xx(t,`warnings`),errors:Xx(t,`errors`),message:Zx(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 Vx(e){let t=qx(e.output),n=Zx(t,`level`)??`unknown`,r=t?.supported!==!1,i=Xx(t,`availableLevels`);return{id:e.id,kind:`thinking`,title:`Thinking`,status:e.status,tone:r?`yellow`:`red`,rows:[{label:`Current`,value:Mx(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 Hx(e){let t=Yx(qx(e.output),`providers`),n=t.flatMap(e=>{let t=Zx(e,`id`)??Zx(e,`provider`)??`provider`,n=Zx(e,`label`)??Zx(e,`name`)??t;return Yx(e,`models`).map(e=>{let r=Zx(e,`id`)??`model`,i=Zx(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 Ux(e){let t=Yx(qx(e.output),`providers`),n=t.map(e=>{let t=Zx(e,`id`)??`provider`;return{id:`login:${t}`,label:Zx(e,`name`)??Zx(e,`label`)??t,action:`login.selectProvider`,value:t,description:Xx(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 Wx(e){return Gx(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 Gx(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?``:` ${Kx(e.functionCall.input)}`}`:``}`.trim();return t?[{value:Mx(t)}]:[]}),a=e.lines.length===0&&typeof e.output==`string`&&e.output.trim()?[{value:Mx(e.output.trim())}]:[],o=[e.error?{label:`Error`,value:Mx(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 Kx(e){try{return JSON.stringify(e)}catch{return String(e)}}function qx(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 Jx(e,t){let n=e?.[t];return n&&typeof n==`object`&&!Array.isArray(n)?n:void 0}function Yx(e,t){let n=e?.[t];return Array.isArray(n)?n.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e)):[]}function Xx(e,t){let n=e?.[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Zx(e,t){let n=e?.[t];return typeof n==`string`?n:void 0}function Qx(e,t){let n=e?.[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function $x(e,t){let n=e?.[t];return typeof n==`boolean`?n:void 0}var eS={transcript:0,"event-log":1,live:2},tS={"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 nS(e,t){return{sourceRank:eS[`event-log`],turnSeq:e??2**53-1,eventSequence:e,phaseRank:tS[t]}}function rS(e,t,n){let r=e??2**53-1,i=t??2**53-1;return{sourceRank:eS.live,turnSeq:r,streamId:r,streamFrameIndex:i,phaseRank:tS[n]}}function iS(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 aS(e,t){if(e)return{...e,contentPartIndex:(e.contentPartIndex??0)+.1,phaseRank:tS[t]}}function oS(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 sS(e){let t=!1,n=e.map(e=>e.children.length?(t=!0,{...e,children:sS(e.children)}):e);return cS(n)?t?n:[...e]:[...n].sort(lS)}function cS(e){for(let t=1;t<e.length;t+=1)if(lS(e[t-1],e[t])>0)return!1;return!0}function lS(e,t){let n=uS(e,t);if(n!==0)return n;if(e.orderKey?.sourceRank===t.orderKey?.sourceRank){let n=oS(e.orderKey,t.orderKey);if(n!==0)return n}let r=dS(e.startedAt,t.startedAt);if(r!==0)return r;let i=oS(e.orderKey,t.orderKey);return i===0?e.id.localeCompare(t.id):i}function uS(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 dS(e,t){return!e&&!t?0:e?t?e.localeCompare(t):-1:1}function fS(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 pS(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 sS([...t.values()].filter(e=>!n.has(e.id)))}function mS(e,t,n,r){if(!hS(t))return;let i=r.get(e)?.filter(e=>e.metadata?.subagentToolName===t)??[],a=_S(n);return a?i.find(e=>e.metadata?.threadKey===a)?.id:i.length===1?i[0].id:void 0}function hS(e){return e.startsWith(`pibo_subagent_`)}function gS(e){return e.slice(14)}function _S(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 vS(e,t,n,r){let i=bS(e,t,n,r);if(!i)return;let a=e.children.find(e=>e.id===i.id);if(a){SS(a,i),a.runId=i.runId??a.runId;return}e.children.push(i)}function yS(e){let t=new Map;for(let n of fS(e)){let e=CS(n.output);if(!e)continue;let r=TS(e.runId);r&&t.set(r,{snapshot:e,completedAt:TS(e.completedAt)??TS(e.updatedAt)??n.completedAt})}for(let n of fS(e)){if(n.type!==`agent.async`||!n.runId)continue;let e=t.get(n.runId);if(!e)continue;let r=TS(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=TS(e.snapshot.summary)??n.error))}}function bS(e,t,n,r){if(!xS(e))return;let i=CS(e.output),a=DS(e.input)?e.input:{},o=TS(i?.toolName)??TS(a.toolName)??r?.title;if(!o||!hS(o))return;let s=TS(r?.summary)??gS(o),c=TS(i?.runId),l=TS(i?.status),u=a.arguments,d=TS(i?.completionPolicy)??TS(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:ES(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:DS(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:aS(e.orderKey,`agent.async`),children:[]}}function xS(e){return e.type===`tool.call`&&e.title===`pibo_run_start`}function SS(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 CS(e){if(DS(e)){if(wS(e))return e;if(DS(e.details)&&wS(e.details))return e.details}}function wS(e){return typeof e.runId==`string`&&typeof e.toolName==`string`}function TS(e){return typeof e==`string`?e:void 0}function ES(e,t){return e.status===`error`||t===`failed`?`error`:t===`completed`||t===`cancelled`?`done`:`running`}function DS(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function OS(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 kS(e){let t=AS(e.notification),n=t.length===1?t[0]:void 0,r=MS(e.notification.failed)+MS(e.notification.timedOut),i=MS(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:NS(e.notification),output:e.notification,source:e.source,stableKey:e.stableKey??e.id,orderKey:e.orderKey,children:[]}}function AS(e){return[...jS(e.completed),...jS(e.failed),...jS(e.timedOut),...jS(e.cancelled),...jS(e.running)]}function jS(e){return Array.isArray(e)?e.filter(PS):[]}function MS(e){return Array.isArray(e)?e.length:0}function NS(e){let t=[[MS(e.completed),`completed`],[MS(e.failed),`failed`],[MS(e.timedOut),`timed out`],[MS(e.cancelled),`cancelled`],[MS(e.running),`running`]].filter(([e])=>Number(e)>0).map(([e,t])=>`${e} ${t}`);return t.length?t.join(`, `):`No yielded run updates`}function PS(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function FS(e,t,n,r,i,a,o,s,c){let l=r.payload,u=o?HS(e,r):void 0;if(u){l.type===`message_steered`&&l.activeEventId&&(u.parentId=iC(l.activeEventId));return}if(o&&QS(l)&&!$S(l,s)||o&&eC(l,c))return;if(l.type===`assistant_delta`){qS(e,t,l,c,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex);return}if(l.type===`thinking_delta`){YS(e,t,l,c,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex);return}if(l.type===`assistant_message`){let i=IS(n,l,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex),a=t.get(i.id);if(a){JS(a,i);return}e.push(i),t.set(i.id,i);return}let d=KS(n,l,i,a,c,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex);if(d){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);if(e){JS(e,d);return}}if(d.type===`execution.compaction`){let t=gC(e);if(t){_C(t,d);return}}if(d.type===`model.reasoning`){let e=t.get(d.id);if(e){XS(e,d);return}}if(d.type===`agent.delegation`&&!d.toolCallId&&d.linkedPiboSessionId){let e=dC([...t.values()],d);if(e){uC(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(xS(e)&&d.type===`agent.delegation`){vS(e,n,r.createdAt,d);return}lC(e,d),vS(e,n,r.createdAt);return}}if(d.eventId){let e=t.get(d.id);if(e){d.type===`user.message`&&d.parentId&&(e.parentId=d.parentId);return}}LS(d,t),vS(d,n,r.createdAt),e.push(d);for(let e of fS([d]))t.set(e.id,e)}}function IS(e,t,n,r,i,a){let o=typeof t.eventId==`string`?t.eventId:void 0,s=oC(t);return{id:s?aC(s):`event:${t.type}:${SC(t)}`,piboSessionId:e,eventId:o,parentId:o?iC(o):void 0,type:`assistant.message`,title:`Agent Message`,status:`done`,startedAt:n,completedAt:n,summary:t.text,output:t.text,source:`event-log`,stableKey:s?`assistant:${s}`:rC(t),orderKey:tC(r,t.type,i,a),children:[]}}function LS(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=RS(n,t);return r===void 0||e.startedAt<=r}).sort(lS).at(-1);n&&(e.parentId=n.id)}function RS(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(lS).at(0)?.startedAt}function zS(e){return e.some(e=>{let t=e.payload.type;return t!==`assistant_delta`&&t!==`thinking_delta`})}function BS(e){if(e.type===`assistant_delta`){if(e.text.length===0)return;let t=oC(e);return t?aC(t):void 0}if(e.type===`thinking_delta`){if(e.text.length===0)return;let t=cC(e);return t?sC(t):void 0}}function VS(e,t){return!!HS(e,t)}function HS(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:t.eventId,i=typeof n.text==`string`?n.text:void 0;return fS([...e]).find(e=>e.type!==`user.message`||e.source!==`transcript`?!1:r&&(e.entryId===r||e.stableKey===`entry:${r}`)?!0:!!(i&&US(e)===i))}function US(e){if(typeof e.output==`string`)return e.output;if(typeof e.summary==`string`)return e.summary}function WS(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 GS(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 KS(e,t,n,r,i,a,o,s,c){let l=`eventId`in t&&typeof t.eventId==`string`?t.eventId:void 0,u=`event:${t.type}:${l??SC(t)}`,d=l?iC(l):void 0,f={id:u,piboSessionId:e,eventId:l,startedAt:a,source:`event-log`,stableKey:rC(t),orderKey:tC(o,t.type,s,c),children:[]};switch(t.type){case`message_queued`:case`message_steered`:{let n=OS(t.text);return t.source===`service`&&n?kS({id:u,piboSessionId:e,eventId:l,startedAt:a,source:`event-log`,stableKey:l?`run-notification:${l}`:u,orderKey:tC(o,t.type,s,c),notification:n}):{...f,...t.type===`message_steered`&&t.activeEventId?{parentId:iC(t.activeEventId)}:{},type:`user.message`,title:`User Message`,status:`done`,summary:t.text,output:t.text}}case`message_started`:case`message_finished`:return t.source===`service`?void 0:{...f,id:l?iC(l):u,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:l?`turn:${l}`:f.stableKey};case`thinking_finished`:{if(!vC(t.text))return;let e=cC(t);return{...f,id:e?sC(e):u,parentId:d,type:`model.reasoning`,title:`Thinking`,status:`done`,summary:t.text,output:t.text,stableKey:e?`reasoning:${e}`:f.stableKey}}case`assistant_message`:{let e=oC(t);return{...f,id:e?aC(e):u,parentId:d,type:`assistant.message`,title:`Agent Message`,status:`done`,completedAt:a,summary:t.text,output:t.text,stableKey:e?`assistant:${e}`:f.stableKey}}case`tool_call`:case`tool_execution_started`:case`tool_execution_updated`:case`tool_execution_finished`:{let o=hS(t.toolName),s=r.get(t.toolCallId)??(o?mS(e,t.toolName,t,n):void 0);return{...f,id:`tool:${t.toolCallId}`,parentId:d,toolCallId:t.toolCallId,type:o?`agent.delegation`:`tool.call`,title:t.toolName,status:t.type===`tool_execution_finished`?t.isError?`error`:`done`:i===`running`&&(t.type===`tool_execution_started`||t.type===`tool_execution_updated`)?`running`:`done`,completedAt:t.type===`tool_execution_finished`?a:void 0,input:`args`in t?t.args:void 0,output:t.type===`tool_execution_finished`?t.result:t.type===`tool_execution_updated`?t.partialResult:void 0,error:t.type===`tool_execution_finished`&&t.isError?yC(t.result):void 0,linkedPiboSessionId:s,stableKey:`tool:${t.toolCallId}`,children:[]}}case`subagent_session`:{let e=xC(t.childPiboSessionId),n=bC(o,s,t);return{...f,id:t.toolCallId?`tool:${t.toolCallId}`:`event:subagent_session:${n}`,eventId:l,toolCallId:t.toolCallId,type:`agent.delegation`,title:t.toolName,status:i===`running`?`running`:`done`,summary:t.subagentName,input:{subagentName:t.subagentName,threadKey:t.threadKey},linkedPiboSessionId:e,stableKey:t.toolCallId?`tool:${t.toolCallId}`:e?`subagent:${e}`:`subagent:event:${n}`,children:[]}}case`execution_result`:return ZS(t.action)?void 0:{...f,type:`execution.command`,title:t.action,status:`done`,input:{action:t.action},output:t.result};case`compaction_start`:{let e=bC(o,s,t);return{...f,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=bC(o,s,t);return{...f,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{...f,type:`error`,title:`Session Error`,status:`error`,summary:t.errorDetails?.userMessage,input:t.errorDetails,error:t.error,output:t.error};default:return}}function qS(e,t,n,r,i,a,o,s){if(typeof n.text!=`string`||n.text.length===0)return;let c=oC(n),l=c?aC(c):`event:assistant_delta:${SC(n)}`,u=t.get(l);if(u){let e=`${typeof u.output==`string`?u.output:``}${n.text}`;u.status=r===`running`?`running`:`done`,u.summary=e,u.output=e;return}let d={id:l,parentId:n.eventId?iC(n.eventId):void 0,piboSessionId:n.piboSessionId,eventId:n.eventId,type:`assistant.message`,title:`Agent Message`,status:r===`running`?`running`:`done`,startedAt:i,summary:n.text,output:n.text,source:`event-log`,stableKey:c?`assistant:${c}`:l,orderKey:tC(a,n.type,o,s),children:[]};e.push(d),t.set(d.id,d)}function JS(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 YS(e,t,n,r,i,a,o,s){if(typeof n.text!=`string`||n.text.length===0)return;let c=cC(n),l=c?sC(c):`event:thinking_delta:${SC(n)}`,u=t.get(l);if(u){let e=`${typeof u.output==`string`?u.output:``}${n.text}`;u.status=r===`running`?`running`:`done`,u.summary=e,u.output=e;return}let d={id:l,parentId:n.eventId?iC(n.eventId):void 0,piboSessionId:n.piboSessionId,eventId:n.eventId,type:`model.reasoning`,title:`Thinking`,status:r===`running`?`running`:`done`,startedAt:i,summary:n.text,output:n.text,source:`event-log`,stableKey:c?`reasoning:${c}`:l,orderKey:tC(a,n.type,o,s),children:[]};e.push(d),t.set(d.id,d)}function XS(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 ZS(e){return e===`session.fork`||e===`session.clone`||e===`session.switch`}function QS(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 $S(e,t){let n=`eventId`in e&&typeof e.eventId==`string`?e.eventId:void 0;return!!(n&&t.has(n))}function eC(e,t){return t!==`running`&&e.type===`tool_call`}function tC(e,t,n,r){return e===void 0&&(n!==void 0||r!==void 0)?rS(n,r,nC(t)):nS(e,nC(t))}function nC(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 rC(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=cC(e);if(t)return`reasoning:${t}`}if(e.type===`assistant_delta`||e.type===`assistant_message`){let t=oC(e);if(t)return`assistant:${t}`}return`event:${e.type}:${t??SC(e)}`}function iC(e){return`event:message:${e}`}function aC(e){return`event:assistant:${e}`}function oC(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 sC(e){return`event:thinking:${e}`}function cC(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 lC(e,t){e.status=t.status,e.summary=t.summary??e.summary,e.input=mC(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 uC(e,t){e.summary=t.summary??e.summary,e.input=mC(e,t),e.linkedPiboSessionId=t.linkedPiboSessionId??e.linkedPiboSessionId}function dC(e,t){let n=[...e].reverse().filter(e=>e.type===`agent.delegation`),r=fC(t),i=n.filter(e=>!e.linkedPiboSessionId&&fC(e)===r),a=pC(t.input);return(a?i.find(e=>pC(e.input)===a):i.length===1?i[0]:void 0)||n.find(e=>e.linkedPiboSessionId===t.linkedPiboSessionId)}function fC(e){let t=hC(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 pC(e){if(!(!hC(e)||typeof e.threadKey!=`string`))return e.threadKey.trim()||void 0}function mC(e,t){return e.type!==`agent.delegation`||!hC(e.input)||!hC(t.input)?t.input??e.input:Object.fromEntries(Object.entries({...e.input,...t.input}).filter(([,e])=>e!==void 0))}function hC(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function gC(e){return fS([...e]).reverse().find(e=>e.type===`execution.compaction`&&e.status===`running`)}function _C(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 vC(e){return typeof e==`string`&&e.trim().length>0}function yC(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}function bC(e,t,n){return e===void 0?t===void 0?SC(n):`stream:${t}`:`sequence:${e}`}function xC(e){if(typeof e==`string`)return e.trim()||void 0}function SC(e){return CC(new TextEncoder().encode(JSON.stringify(e))).slice(0,48)}function CC(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 wC(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 sS(n)}function TC(e,t,n){return t.map(t=>EC(e,t,n))}function EC(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)||DC(r,t))?r:e?{...t,children:r.children}:{...t,children:[]}}let i=t.children.map(t=>EC(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)||DC(r,t))?r:a?{...t,children:r?.children??i}:{...t,children:i}}function DC(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&&OC(e.orderKey,t.orderKey)}function OC(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 kC(e,t,n){if(!t.length)return e;let r=new Set(e.rawEvents.map(e=>WS(e))),i=[];for(let e of t){let t=WS(e);r.has(t)||(r.add(t),i.push(e))}if(!i.length)return e;let a=fS(e.nodes),o=[],s=new Map,c=new Map;for(let e of a){c.set(e.id,e);let t={...e,children:[]};o.push(t),s.set(t.id,t)}let l=new Map,u=new Map,d=new Set,f=[],p=new Set;for(let t of i){if(VS(o,t))continue;f.push(t);let r=BS(t.payload);p&&r?p.add(r):p=void 0,FS(o,s,e.piboSessionId,t,l,u,!1,d,n)}if(!f.length)return e;let m=wC(o);zS(f)&&yS(m);let h=TC(c,m,p);return{...e,rawEvents:e.rawEvents.length?[...e.rawEvents,...f]:f,nodes:h,latestStreamId:GS(f,e.latestStreamId)}}function AC(e,t){if(!e)return[];let n=NC(e.nodes),r=fw(PC(e.nodes).sort((e,t)=>lS(e.node,t.node)).filter(e=>e.node.type!==`agent.turn`&&(t.showThinking||e.node.type!==`model.reasoning`)).map(e=>FC(e.node,e.turnId)));return zC(r,n),hw(RC(r)).map(e=>e.row)}function jC(e){if(!e)return;let t=new Set(PC(e.nodes).map(({node:e})=>e).filter(e=>e.type===`error`&&e.eventId).map(e=>e.eventId));return[...NC(e.nodes).values()].filter(e=>e.startedAt&&!e.completedAt&&(!e.eventId||!t.has(e.eventId))).sort(lS).at(-1)?.startedAt}function MC(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 NC(e){let t=new Map;for(let n of e){n.type===`agent.turn`&&t.set(n.id,n);for(let[e,r]of NC(n.children))t.set(e,r)}return t}function PC(e,t){let n=[];for(let r of e)r.type!==`agent.turn`&&n.push({node:r,turnId:t}),n.push(...PC(r.children,r.type===`agent.turn`?r.id:t));return n}function FC(e,t){let n;switch(e.type){case`user.message`:n={row:HC(e),turnId:t};break;case`assistant.message`:n={row:UC(e),turnId:t};break;case`model.reasoning`:n={row:WC(e),turnId:t};break;case`tool.call`:n=GC(e,t);break;case`tool.result`:n=JC(e,t);break;case`agent.delegation`:n={row:XC(e),turnId:t};break;case`agent.async`:n={row:ZC(e),turnId:t};break;case`yielded.run`:n={row:QC(e),turnId:t};break;case`execution.command`:n={row:ew(e),turnId:t};break;case`execution.compaction`:n={row:$C(e),turnId:t};break;case`error`:n={row:uw(e),turnId:t};break;case`agent.turn`:n={row:{id:e.id,kind:`error`,status:`neutral`,lines:[],sourceNodeIds:[e.id]},turnId:t};break}return{...n,row:{...n.row,id:IC(e),...VC(e)}}}function IC(e){if(e.type===`tool.call`||e.type===`tool.result`||e.type===`agent.delegation`){let t=e.toolCallId??LC(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=LC(e.stableKey,`assistant:`);if(t)return`terminal:assistant:${t}`}if(e.type===`model.reasoning`){let t=LC(e.stableKey,`reasoning:`);if(t)return`terminal:reasoning:${t}`}return e.id}function LC(e,t){if(!e?.startsWith(t))return;let n=e.slice(t.length);return n&&n!==`undefined`?n:void 0}function RC(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 zC(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??BC(n.startedAt,n.completedAt))}}function BC(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 VC(e){return{eventId:e.eventId,runId:e.runId,orderSource:e.source,orderStreamId:e.orderKey?.streamId,orderStreamFrameIndex:e.orderKey?.streamFrameIndex,payloadRefs:e.payloadRefs}}function HC(e){let t=Yw(e.output)||Yw(e.summary)||e.title;return{id:e.id,kind:`message.user`,status:qw(e.status),lines:[{prefix:`prompt`,tokens:[$(t)]}],sourceNodeIds:[e.id],forkEntryId:e.entryId,startedAt:e.startedAt,output:t,payloadRefs:e.payloadRefs}}function UC(e){return{id:e.id,kind:`message.assistant`,status:qw(e.status),lines:[],sourceNodeIds:[e.id],startedAt:e.startedAt,completedAt:e.source===`transcript`?e.completedAt:void 0,durationMs:e.source===`transcript`?e.durationMs:void 0,output:Yw(e.output)||Yw(e.summary)||``,error:e.error,payloadRefs:e.payloadRefs}}function WC(e){let t=Fw(e.output??e.summary);return{id:e.id,kind:`reasoning`,status:qw(e.status),lines:[{prefix:`bullet`,tokens:[$(e.status===`running`?`Thinking`:`Thought`,`amber`,`semibold`)]}],sourceNodeIds:[e.id],markdown:t,payloadRefs:e.payloadRefs}}function GC(e,t){let n=Hw(e.input);if(n&&Lw(e.title))return{row:lw(e,n),turnId:t,exploring:void 0};if(Rw(e.title))return{row:KC(e),turnId:t};let r=bw(e);if(r)return{row:qC(e,r),turnId:t,image:r.groupable?r.detail:void 0};let i=Nw(e.error??e.output,5,e.error?`red`:`dim`);return{row:{id:e.id,kind:`tool.call`,status:qw(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(Ww(e.status),Jw(e.status),`semibold`),$(` `)],functionCall:{name:e.title,input:e.input}},...i.lines],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:e.input!==void 0||e.output!==void 0||!!e.error,previewOmission:Pw(i,e.error?`error`:`output`)},turnId:t,exploring:Ow(e)}}function KC(e){let t=qw(e.status),n=Bw(e),r=Vw(e.output),i=[{prefix:`bullet`,tokens:[$(zw(e.status),Jw(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 qC(e,t){let n=qw(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,Jw(e.status),`semibold`)]},{prefix:`detail`,tokens:[$(r,e.status===`error`?`red`:`cyan`)]}],sourceNodeIds:[e.id],input:Sw(e.input),output:t.summary,error:e.error,expandable:e.input!==void 0||t.summary!==void 0||!!e.error}}function JC(e,t){let n=bw(e);return n?{row:qC(e,n),turnId:t,image:n.groupable?n.detail:void 0}:{row:YC(e),turnId:t}}function YC(e){let t=Nw(e.error??e.output,5,e.error?`red`:`dim`);return{id:e.id,kind:`tool.call`,status:qw(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(e.status===`error`?`Tool failed`:`Returned`,Jw(e.status),`semibold`),$(` ${e.title}`)]},...t.lines],sourceNodeIds:[e.id],output:e.output,error:e.error,expandable:e.output!==void 0||!!e.error,previewOmission:Pw(t,e.error?`error`:`output`)}}function XC(e){let t=Yw(Xw(e.input)?e.input.subagentName:void 0)||e.summary||e.title,n=Iw((Xw(e.input)?e.input.arguments:void 0)??e.input),r=n?[{prefix:`detail`,tokens:[$(n,`dim`)]}]:[];return{id:e.id,kind:`agent.delegation`,status:qw(e.status),errorKind:e.status===`error`?`tool`:void 0,title:e.title,summary:e.summary,lines:[{prefix:`bullet`,tokens:[$(Gw(e.status),Jw(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 ZC(e){let t=Nw(e.error??e.output,5,e.error?`red`:`dim`);return{id:e.id,kind:`agent.async`,status:qw(e.status),lines:[{prefix:`bullet`,tokens:[$(Kw(e.status),Jw(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:Pw(t,e.error?`error`:`output`)}}function QC(e){let t=Nw(e.output,5);return{id:e.id,kind:`yielded.run`,status:qw(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(e.status===`running`?`Waiting on runs`:`Run update`,Jw(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:Pw(t,`output`)}}function $C(e){let t=e.status===`running`?`Compacting`:e.status===`error`?`Compaction failed`:Yw(e.summary)||`Compacted`;return{id:e.id,kind:`execution.compaction`,status:qw(e.status),lines:[{prefix:`bullet`,tokens:[$(t,Jw(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 ew(e){if(e.title===`status`)return tw(e);if(e.title===`thinking`)return mw(e.output)?rw(e):nw(e);if(e.title===`fast_mode`)return iw(e);if(e.title===`login`&&sw(e.output))return aw(e);if(e.title===`model`&&cw(e.output))return ow(e);Hw(e.output)??Hw(e.input)??e.title;let t=Nw(e.error??e.output,5,e.error?`red`:`dim`,180);return{id:e.id,kind:`execution.command`,status:qw(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:Pw(t,e.error?`error`:`output`)}}function tw(e){return{id:e.id,kind:`tool.status`,status:qw(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function nw(e){return{id:e.id,kind:`tool.thinking`,status:qw(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function rw(e){let t=Xw(e.output)?e.output:void 0,n=Yw(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:qw(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 iw(e){let t=Xw(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:qw(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 aw(e){return{id:e.id,kind:`tool.login`,status:qw(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function ow(e){return{id:e.id,kind:`tool.model`,status:qw(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function sw(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 cw(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 lw(e,t){let n=Nw(e.error??e.output,5,e.error?`red`:`dim`,180);return{id:e.id,kind:`execution.command`,status:qw(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(e.status===`running`?`Running`:`Ran`,Jw(e.status),`semibold`),$(` `),...Uw(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:Pw(n,e.error?`error`:`output`)}}function uw(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`)]},...dw(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 dw(e){return Xw(e)?[[`Class`,Yw(e.errorClass)??Yw(e.category)],[`Code`,Yw(e.code)??Yw(e.providerCode)],[`Origin`,Yw(e.origin)],[`Provider`,[Yw(e.api),Yw(e.provider),Yw(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 fw(e){let t=e.map(e=>e.row.output).filter(pw).at(-1);return t?e.map(e=>e.row.kind!==`tool.thinking`||!Xw(e.row.output)?e:{...e,row:{...e.row,output:{...e.row.output,level:t.level,availableLevels:t.availableLevels,supported:t.supported}}}):[...e]}function pw(e){return Xw(e)&&typeof e.level==`string`&&Array.isArray(e.availableLevels)}function mw(e){return Xw(e)&&e.action===`set_thinking_level`}function hw(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n],i=gw(r);if(!i){t.push(r);continue}let a=[r],o=n+1;for(;o<e.length&&gw(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`?vw(a):_w(a),turnId:r.turnId}),n=o-1}return t}function gw(e){if(e.image)return`images`;if(e.exploring)return`exploring`}function _w(e){let t=yw(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`,Jw(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 vw(e){let t=yw(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`,Jw(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 yw(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 bw(e){let t=(e.title??``).trim().toLowerCase(),n=Xw(e.input)?e.input:void 0,r=Xw(e.output)?e.output:void 0,i=Dw(r,`details`),a=t===`codex_image_generation`?ww(i)??Tw(n):void 0,o=a?Yw(i?.savedPath)??Aw(i):Aw(n)??Aw(i)??Aw(r),s=a?Yw(i?.artifactId):void 0,c=jw(n),l=xw(e.output),u=kw(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?Yw(i?.model):void 0,referencedImageCount:a?Mw(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?Ew(e.status,a):Cw(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:qw(e.status),input:Sw(e.input),output:p,error:e.error}}}function xw(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=>xw(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`||Xw(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=>xw(e,t+1,n))}function Sw(e){if(Array.isArray(e))return e.map(Sw);if(!Xw(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]=Sw(r)}return t}function Cw(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 ww(e){let t=Yw(e?.operation);return t===`generate`||t===`edit`?t:void 0}function Tw(e){if(!e)return;let t=e.referenced_image_paths;return Array.isArray(t)&&t.length>0||Mw(e.num_last_images_to_include)!==void 0?`edit`:`generate`}function Ew(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 Dw(e,t){let n=e?.[t];return Xw(n)?n:void 0}function Ow(e){let t=(e.title??``).trim().toLowerCase(),n=Xw(e.input)?e.input:void 0;if(kw(t,[`read`,`open`]))return{id:e.id,label:`Read ${Aw(n)??Iw(e.input)}`,status:qw(e.status),input:e.input,output:e.output,error:e.error};if(kw(t,[`list`,`ls`,`glob`]))return{id:e.id,label:`List ${Aw(n)??Iw(e.input)}`,status:qw(e.status),input:e.input,output:e.output,error:e.error};if(kw(t,[`search`,`find`,`grep`,`rg`])){let t=jw(n),r=Aw(n);return{id:e.id,label:`Search ${t??Iw(e.input)}${r?` in ${r}`:``}`,status:qw(e.status),input:e.input,output:e.output,error:e.error}}}function kw(e,t){return t.some(t=>e===t||e.startsWith(`${t}_`)||e.endsWith(`_${t}`)||e.includes(t))}function Aw(e){if(e)for(let t of[`path`,`file`,`filePath`,`filepath`,`url`,`uri`,`cwd`,`pattern`,`glob`]){let n=Yw(e[t]);if(n)return n}}function jw(e){if(e)for(let t of[`query`,`pattern`,`text`,`name`,`q`,`regex`]){let n=Yw(e[t]);if(n)return n}}function Mw(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Nw(e,t,n=`dim`,r=160){let i={lines:[],visibleLineCount:0,omittedLineCount:0,totalLineCount:0,maxVisibleLineCount:t},a=Fw(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 Pw(e,t){if(!(e.omittedLineCount<=0))return{source:t,visibleLineCount:e.visibleLineCount,omittedLineCount:e.omittedLineCount,totalLineCount:e.totalLineCount,maxVisibleLineCount:e.maxVisibleLineCount}}function Fw(e){let t=Nb(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 Iw(e){return(typeof e==`string`?e:Fw(e)).replace(/\s+/g,` `).trim()}function Lw(e){let t=(e??``).trim().toLowerCase();return t===`shell`||t===`bash`||t===`terminal`}function Rw(e){return(e??``).trim().toLowerCase()===`web_search`}function zw(e){return e===`running`?`Searching web`:e===`error`?`Web search failed`:`Searched web`}function Bw(e){let t=Xw(e.input)?e.input:void 0,n=Xw(e.output)?e.output:void 0;return Yw(t?.query)??Yw(n?.query)??Yw(e.summary)}function Vw(e){if(!Xw(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 Hw(e){if(Xw(e))for(let t of[`cmd`,`command`,`script`]){let n=Yw(e[t]);if(n)return n}}function Uw(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 Ww(e){return e===`running`?`Calling`:e===`error`?`Call failed`:`Called`}function Gw(e){return e===`running`?`Spawning`:e===`error`?`Spawn failed`:`Spawned`}function Kw(e){return e===`running`?`Waiting for`:`Finished waiting for`}function qw(e){return e===`running`?`running`:e===`error`?`error`:`done`}function Jw(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 Yw(e){return typeof e==`string`&&e.trim().length?e:void 0}function Xw(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Zw(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 Qw(e,t,n){return n?{id:e,label:t,value:n}:void 0}function $w({field:e,icon:t}){let n=t===`session`?$e:Ye;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 eT({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 tT(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 nT({row:e}){let t=Zw(e.output),n=zx(e),r=n?.kind===`status`?n.statusView:void 0,[i,a]=(0,v.useState)(!1);if(!t||!r)return(0,I.jsx)(`div`,{className:`mt-2 border border-[#2a2a2a] bg-[#111111] px-3 py-2 text-[12px] text-[#d4d4d4]`,"data-pibo-component":`TerminalStatusCard`,"data-pibo-debug":`terminal-status-card`,"data-shared-terminal-card":`status`,children:(0,I.jsx)(`div`,{className:`text-[#737373]`,children:`Status (unparseable)`})});let o=new Map(r.fields.map(e=>[e.id,e])),s=o.get(`session`)??Qw(`session`,`Session`,t.piboSessionId),c=o.get(`cwd`)??Qw(`cwd`,`CWD`,t.cwd),l=r.progress.find(e=>e.id===`context`),u=r.progress.filter(e=>e.id.startsWith(`provider`)),d=t.providerUsage?.limits.length?t.providerUsage.limits:void 0,f=t.enabledTools??t.activeTools??[],p=r.fields.filter(e=>!new Set([`session`,`cwd`]).has(e.id)),m=t.providerUsage?.provider?`${t.providerUsage.provider} quota`:`Provider quota`;return(0,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)(xe,{size:14,className:`text-[#22c55e]`}),(0,I.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:r.title})]}),(0,I.jsxs)(`div`,{className:`grid grid-cols-1 gap-1.5 sm:grid-cols-2`,children:[s?(0,I.jsx)($w,{field:s,icon:`session`}):null,c?(0,I.jsx)($w,{field:c,icon:`cwd`}):null,p.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:[t.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)(We,{size:10}),` Processing`]}):null,t.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)(xe,{size:10}),` Streaming`]}):null,typeof t.queuedMessages==`number`&&t.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)(nt,{size:10}),` Queued: `,t.queuedMessages]}):null,t.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]}),l?(0,I.jsx)(eT,{progress:l,label:`Context Usage`}):null,u.length?(0,I.jsxs)(`div`,{className:`mt-3 space-y-1.5 border-t border-[#2a2a2a] pt-2`,"data-shared-provider-progress":u.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)(Xe,{size:11}),(0,I.jsxs)(`span`,{children:[m,t.providerUsage?.planType?` (${t.providerUsage.planType})`:``]})]}),d?d.map(e=>{let t=tT(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??``}`)}):u.map(e=>(0,I.jsx)(eT,{progress:e},e.id)),t.providerUsage?.credits?(0,I.jsxs)(`div`,{className:`text-[11px] text-[#a3a3a3]`,"data-shared-status-field":`provider-credits`,children:[`Credits: `,t.providerUsage.credits.unlimited?`unlimited`:t.providerUsage.credits.balance??`available`]}):null]}):null,r.warnings.length||r.errors.length?(0,I.jsxs)(`div`,{className:`mt-3 space-y-1 border-t border-[#2a2a2a] pt-2`,children:[r.warnings.map((e,t)=>(0,I.jsxs)(`div`,{"data-shared-status-warning":!0,className:`text-[11px] text-[#facc15]`,children:[`⚠ `,e]},`warning-${t}`)),r.errors.map((e,t)=>(0,I.jsxs)(`div`,{"data-shared-status-error":!0,className:`text-[11px] text-[#ef4444]`,children:[`✕ `,e]},`error-${t}`))]}):null,f.length>0?(0,I.jsxs)(`div`,{className:`mt-3`,children:[(0,I.jsxs)(`button`,{type:`button`,onClick:()=>a(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:i?`▾`:`▸`}),(0,I.jsxs)(`span`,{children:[`Enabled tools (`,f.length,`)`]})]}),i?(0,I.jsx)(`div`,{className:`mt-1.5 flex flex-wrap gap-1`,children:f.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 rT=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function iT(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 aT(e){return rT.includes(e)?e:void 0}function oT({row:e,onLevelSelect:t}){let n=iT(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)(Oe,{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)(_t,{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)(Ae,{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=aT(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 sT=`pibo.chat.terminalReadingPosition.`;function cT(e){if(e)try{return uT(sessionStorage.getItem(sT+e))}catch{return}}function lT(e,t){if(e)try{let n=sT+e;t?sessionStorage.setItem(n,JSON.stringify(t)):sessionStorage.removeItem(n)}catch{}}function uT(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 dT=180,fT=4800,pT=20,mT={index:`LAST`,align:`end`},hT={top:2400,bottom:2400},gT=84,_T=700,vT=6;function yT({traceView:e,isLoading:t,showThinking:n,expandThinking:r,sessionAgentProfile:i,sessionActiveModel:a,selectedSessionStatus:o,selectedSessionSignal:s,signals:c,sessionBreadcrumbs:l,originSession:u,derivedSessions:d,agentProfiles:f,sessionProfileChangeDisabled:p,onSessionAgentProfileChange:m,onFork:h,onOpenSession:g,onLoadOlderTracePage:_,hasOlderTraceEvents:y,isFetchingOlderTracePage:b,onThinkingLevelChange:x,onModelChanged:S}){let C=(0,v.useMemo)(()=>AC(e,{showThinking:n}),[n,e]),w=(0,v.useMemo)(()=>C.map(e=>e.id),[C]),T=e?.piboSessionId??``,[E,D]=(0,v.useState)(),O=(0,v.useRef)(void 0),[k,ee]=(0,v.useState)(new Set),A=(0,v.useMemo)(()=>[C,k],[k,C]),[te,ne]=(0,v.useState)(null),re=(0,v.useRef)({}),ie=(0,v.useRef)(!1),j=(0,v.useRef)(!1),M=(0,v.useRef)(void 0),ae=(0,v.useRef)(!1),oe=(0,v.useRef)(()=>void 0),se=C.filter(e=>AT(e,`user`)).length,ce=C.filter(e=>AT(e,`tool`)).length,N=C.filter(e=>AT(e,`system`)).length,le=jb({signal:s,fallbackStatus:o,fallbackTurnStartedAt:(0,v.useMemo)(()=>jC(e),[e])}),ue=le.activeTurnStartedAt,de=le.isTurnActive,P=(0,v.useCallback)(e=>{if(!y||b||ae.current)return;let t=()=>{M.current=void 0,!ae.current&&(ae.current=!0,j.current=!1,oe.current(),_?.())};if(!e||!j.current){M.current!==void 0&&window.clearTimeout(M.current),t();return}M.current===void 0&&(M.current=window.setTimeout(t,_T))},[y,b,_]),fe=(0,v.useCallback)(()=>{ie.current&&j.current&&P(!0)},[P]),pe=(0,v.useCallback)(()=>{ie.current&&P(!1)},[P]),me=(0,v.useCallback)(e=>{GT(e)&&(j.current=!0)},[]),he=(0,v.useCallback)(e=>{ie.current&&(e.startIndex<=0?pe():e.startIndex<=pT&&fe())},[pe,fe]),ge=(0,v.useCallback)(e=>{T&&lT(T,e?{rowId:e.key,offsetPx:e.offset}:void 0)},[T]),_e=Ra({itemCount:C.length,itemKeys:w,isPrepending:b,resetKey:e?.piboSessionId,contentKey:A,atBottomThreshold:dT,nearTopThreshold:fT,onAtTop:pe,onNearTop:fe,onUserScrollIntent:me,onVisibleAnchorChange:ge});oe.current=_e.prepareForPrepend,(0,v.useEffect)(()=>{O.current=void 0,ae.current=!1,D(T?cT(T):void 0)},[T]),(0,v.useEffect)(()=>{ae.current=!1},[e?.nextBeforeCursor,e?.nextBeforeSequence]),(0,v.useEffect)(()=>()=>{M.current!==void 0&&window.clearTimeout(M.current)},[]),(0,v.useEffect)(()=>{if(!T||!E)return;let t=w.indexOf(E.rowId);if(t>=0){let e=requestAnimationFrame(()=>{_e.restoreAnchor({key:E.rowId,dataIndex:t,offset:E.offsetPx})&&D(void 0)});return()=>cancelAnimationFrame(e)}if(!y){lT(T,void 0),D(void 0);return}if(b)return;let n=`${T}:${String(e?.nextBeforeCursor??e?.nextBeforeSequence??C.length)}`;O.current!==n&&(O.current=n,_?.())},[y,b,_,T,E,w,C.length,_e.restoreAnchor,e?.nextBeforeCursor,e?.nextBeforeSequence]),(0,v.useEffect)(()=>{if(!T)return;let e=()=>{_e.captureVisibleAnchor()};return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[T,_e.captureVisibleAnchor]),(0,v.useEffect)(()=>{ee(e=>kT(e,C,r))},[r,C]),(0,v.useEffect)(()=>{b||_e.isScrolledToTop()&&pe()},[y,b,pe,C.length,_e.isScrolledToTop,e?.nextBeforeCursor,e?.nextBeforeSequence]),(0,v.useEffect)(()=>{ie.current=!1,j.current=!1;let e=window.setTimeout(()=>{ie.current=!0,_e.isScrolledToTop()&&pe()},250);return()=>window.clearTimeout(e)},[pe,_e.isScrolledToTop,e?.piboSessionId]),(0,v.useEffect)(()=>{let e=new Set(C.map(e=>e.id));ne(t=>t&&e.has(t)?t:null);for(let t of[`system`,`tool`,`user`]){let n=re.current[t];n&&!e.has(n)&&delete re.current[t]}},[C]);let ve=(0,v.useCallback)(e=>{let t=jT(C,e,re.current[e]);t&&(re.current[e]=t.row.id,ne(t.row.id),_e.scrollToIndex(t.index,`start`,`fast-smooth`,{fromIndex:t.fromIndex,stagingAlign:e===`tool`?`end`:void 0}),MT(t.row.id))},[C,_e]),ye=e=>{e.expandable&&ee(t=>{let n=new Set(t);return n.has(e.id)?n.delete(e.id):n.add(e.id),n})},be=(0,v.useCallback)((t,n)=>(0,I.jsx)(`div`,{className:`px-4`,children:(0,I.jsx)(ST,{row:n,expanded:k.has(n.id),focused:te===n.id,piboSessionId:e?.piboSessionId??``,onToggle:()=>ye(n),onFork:h,onOpenSession:g,onThinkingLevelChange:x,onModelChanged:S,signals:c})}),[k,te,h,S,g,x,c,e?.piboSessionId]),F=(0,v.useMemo)(()=>({Footer:de?()=>(0,I.jsx)(LT,{startedAt:ue}):void 0}),[ue,de]);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-trace-has-older":e?.hasOlderEvents===!0?`true`:`false`,"data-pibo-trace-next-before":e?.nextBeforeCursor??e?.nextBeforeSequence??``,children:[(0,I.jsx)(bT,{errorCount:N,toolErrorCount:ce,userMessageCount:se,onNavigate:ve,sessionAgentProfile:i,sessionActiveModel:a,sessionBreadcrumbs:l,originSession:u,derivedSessions:d,onOpenSession:g}),(0,I.jsx)(`div`,{className:`min-h-0 flex-1 overflow-hidden`,children:e?C.length?(0,I.jsx)(Ri,{ref:_e.virtuosoRef,data:C,firstItemIndex:_e.firstItemIndex,initialTopMostItemIndex:mT,increaseViewportBy:hT,defaultItemHeight:gT,className:`min-h-0 h-full overflow-x-hidden font-mono text-[12px] leading-[1.45]`,computeItemKey:(e,t)=>t.id,scrollerRef:_e.scrollerRef,atBottomStateChange:_e.atBottomStateChange,atBottomThreshold:_e.atBottomThreshold,atTopStateChange:e=>{e&&pe()},itemsRendered:_e.itemsRendered,rangeChanged:e=>he(_e.normalizeRange(e)),startReached:pe,followOutput:_e.followOutput,totalListHeightChanged:_e.totalListHeightChanged,alignToBottom:!0,components:F,itemContent:be}):(0,I.jsx)(UT,{isLoading:t,agentProfiles:f,disabled:p,onSelectAgentProfile:m,message:`No visible trace rows yet.`}):(0,I.jsx)(UT,{isLoading:t,agentProfiles:f,disabled:p,onSelectAgentProfile:m})}),_e.isSticky?null:(0,I.jsx)(`button`,{type:`button`,onClick:()=>{lT(T,void 0),_e.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)(je,{size:18})})]})}function bT({errorCount:e,toolErrorCount:t,userMessageCount:n,onNavigate:r,sessionAgentProfile:i,sessionActiveModel:a,sessionBreadcrumbs:o,originSession:s,derivedSessions:c,onOpenSession:l}){return(0,I.jsxs)(`div`,{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)(VT,{tone:`neutral`,children:i}):null,a?(0,I.jsx)(VT,{tone:`purple`,children:a}):null,n>0?(0,I.jsxs)(VT,{tone:`cyan`,label:`${n} user messages · jump to previous user message`,onClick:()=>r(`user`),children:[n,(0,I.jsx)(st,{size:12})]}):null,e>0?(0,I.jsxs)(VT,{tone:`red`,label:`${e} errors · jump to previous error`,onClick:()=>r(`system`),children:[e,(0,I.jsx)(Be,{size:12})]}):null,t>0?(0,I.jsxs)(VT,{tone:`amber`,label:`${t} tool call errors · jump to previous tool error`,onClick:()=>r(`tool`),children:[t,(0,I.jsx)(Qe,{size:12})]}):null,s?(0,I.jsxs)(xT,{onClick:()=>l(s.piboSessionId),children:[`Origin `,s.label]}):null,c.map(e=>(0,I.jsxs)(xT,{onClick:()=>l(e.piboSessionId),children:[`Derived `,e.label]},e.piboSessionId))]}),o.length?(0,I.jsx)(`div`,{className:`mt-2 flex flex-wrap items-center gap-1 text-[#737373]`,children:o.map((e,t)=>(0,I.jsxs)(`div`,{className:`flex items-center gap-1`,children:[t>0?(0,I.jsx)(Me,{size:12,className:`text-[#525252]`}):null,(0,I.jsx)(`button`,{type:`button`,onClick:()=>l(e.piboSessionId),className:`hover:text-[#38bdf8]`,children:e.label})]},e.piboSessionId))}):null]})}function xT({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 ST({row:e,expanded:t,focused:n,piboSessionId:r,onToggle:i,onFork:a,onOpenSession:o,onThinkingLevelChange:s,onModelChanged:c,signals:l}){let u=!t&&PT(e),d=u?NT(e):e.lines;return e.kind===`agent.delegation`?(0,I.jsx)(`div`,{className:OT(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)(nl,{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:OT(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||FT(t)||i()}:void 0,onKeyDown:e.expandable?t=>{!e.expandable||FT(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)(CT,{row:e,visibleLines:d,collapseToolCallPreview:u,piboSessionId:r,onThinkingLevelChange:s,onModelChanged:c})}),(0,I.jsx)(DT,{row:e,onFork:a,onOpenSession:o})]}),t?(0,I.jsx)(Hb,{row:e,onOpenSession:o}):null]})}function CT({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)(Xy,{streaming:e.status===`running`,children:typeof e.output==`string`?e.output:``})}),e.status===`running`?null:(0,I.jsx)(TT,{timestamp:e.completedAt,durationMs:e.durationMs})]}):e.kind===`message.user`?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(wT,{lines:t,status:e.status,clampPreview:n}),(0,I.jsx)(TT,{timestamp:e.startedAt})]}):e.kind===`tool.status`?(0,I.jsx)(nT,{row:e}):e.kind===`tool.thinking`?(0,I.jsx)(oT,{row:e,onLevelSelect:i}):e.kind===`tool.login`?(0,I.jsx)(wx,{row:e,piboSessionId:r}):e.kind===`tool.model`?(0,I.jsx)(Ax,{row:e,piboSessionId:r,onModelChanged:a}):e.kind===`execution.compaction`&&e.status===`running`?(0,I.jsx)(zT,{}):e.kind===`reasoning`&&e.markdown?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(wT,{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)(Xy,{streaming:e.status===`running`,children:e.markdown})})})]}):(0,I.jsx)(wT,{lines:t,status:e.status,clampPreview:n})}function wT({lines:e,status:t,clampPreview:n}){return e.map((e,r)=>(0,I.jsx)(sx,{line:e,status:t,clampLines:n&&r===0?5:void 0},r))}function TT({timestamp:e,durationMs:t}){let n=ET(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:` · ${MC(t)}`]}):null}function ET(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 DT({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)(HT,{label:`Open linked session`,onClick:()=>n(e.linkedPiboSessionId),children:`Open`}):null,e.forkEntryId?(0,I.jsxs)(HT,{label:`Fork from this user message`,onClick:()=>t(e.forkEntryId),children:[(0,I.jsx)(Ze,{size:13}),`Fork`]}):null]})}function OT(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 kT(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 WT(e,r)?e:r}function AT(e,t){return t===`user`?e.kind===`message.user`:e.status===`error`?t===`tool`?e.errorKind===`tool`:e.errorKind!==`tool`:!1}function jT(e,t,n){let r=e.map((e,t)=>({row:e,index:t})).filter(({row:e})=>AT(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 MT(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 NT(e){return e.kind===`tool.group.exploring`||e.kind===`tool.group.images`?e.lines.slice(0,vT):e.lines}function PT(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 FT(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 IT=`Working...`;function LT({startedAt:e}){let t=RT(e);return(0,I.jsx)(`div`,{className:`border-t border-[#141414] px-4 py-2`,role:`status`,"aria-live":`polite`,"aria-label":`Working`,"data-pibo-component":`TerminalStreamingFooter`,"data-pibo-active-turn-started-at":e,children:(0,I.jsxs)(`div`,{className:`grid grid-cols-[1.9rem_minmax(0,1fr)] gap-2 whitespace-pre-wrap break-words`,"aria-hidden":`true`,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:[t?(0,I.jsx)(`span`,{className:`shrink-0 tabular-nums text-[#737373]`,children:t}):null,(0,I.jsx)(`span`,{className:`compact-terminal-working-label`,children:IT})]})]})})}function RT(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)?MC(Math.max(0,n-t)):void 0}function zT(){let e=BT();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 BT(){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 VT({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 HT({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 UT({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 WT(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function GT(e){return e instanceof WheelEvent?e.deltaY<0:e instanceof KeyboardEvent?[`ArrowUp`,`PageUp`,`Home`].includes(e.key):e?.type===`touchmove`}function KT({traceView:e,isLoading:t,selectedSessionStatus:n,selectedSessionSignal:r,workflowProjectSession:i,workflowLifecycleEvents:a,sessionNodes:o,onOpenSession:s,onRefreshBootstrap:c,onError:l}){let u=i?fE(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)(qT,{model:u}),(0,I.jsx)(JT,{}),(0,I.jsx)(YT,{model:u,onRefreshBootstrap:c,onError:l}),(0,I.jsx)(ZT,{model:u}),(0,I.jsx)(QT,{model:u,onOpenSession:s}),(0,I.jsx)(aE,{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)(sE,{model:u}),(0,I.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-4`,children:[(0,I.jsx)(cE,{model:u}),(0,I.jsx)(lE,{model:u}),(0,I.jsx)(uE,{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)(nt,{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)(JT,{})]})})}function qT({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)(nt,{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)(JE,{tone:`blue`,children:e.workflowId}),e.workflowRunId?(0,I.jsxs)(JE,{tone:`slate`,children:[`run `,$E(e.workflowRunId)]}):null,(0,I.jsx)(JE,{tone:YE(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 `,$E(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 JT(){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)(ht,{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 YT({model:e,onRefreshBootstrap:t,onError:n}){let r=e.workflowRunId?iE(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)(nE,{title:`Workflow configured-session view`,icon:(0,I.jsx)(it,{size:14}),children:(0,I.jsxs)(`div`,{className:`space-y-3 text-xs text-slate-400`,children:[(0,I.jsx)(rE,{label:`selected workflow`,value:i}),(0,I.jsx)(rE,{label:`session state`,value:e.workflowRunId?`started`:`configured/not-started`}),(0,I.jsx)(rE,{label:`input keys`,value:String(e.configuration.inputKeys.length)}),(0,I.jsx)(rE,{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)(nE,{title:`Workflow run view`,icon:(0,I.jsx)(xe,{size:14}),children:(0,I.jsxs)(`div`,{className:`space-y-3 text-xs text-slate-400`,children:[(0,I.jsx)(rE,{label:`run id`,value:e.workflowRunId?$E(e.workflowRunId):`not started`}),(0,I.jsx)(rE,{label:`status`,value:e.state}),(0,I.jsx)(rE,{label:`current node`,value:r?.label??`none`}),(0,I.jsx)(rE,{label:`output`,value:e.finalOutput?`available`:`empty`}),(0,I.jsx)(rE,{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)(nE,{title:`Human action area`,icon:(0,I.jsx)(He,{size:14}),children:(0,I.jsx)(XT,{model:e,onRefreshBootstrap:t,onError:n})})]})}function XT({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 vx(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=IE(e);c(e=>({...e,[i.waitTokenId]:t})),n?.(t[0]?.message??LE(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?$E(e.waitTokenId):e.source})]}),(0,I.jsxs)(`div`,{className:`mt-2 grid gap-2 text-[11px] text-amber-100/75`,children:[(0,I.jsx)(rE,{label:`human node`,value:e.humanNodeId??`unspecified`}),(0,I.jsx)(rE,{label:`payload`,value:e.payloadRequirements?.description??`No persisted payload schema.`}),e.expiresAt?(0,I.jsx)(rE,{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)(el,{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 ZT({model:e}){let t=e.workflowRunId?iE(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)(Ge,{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)($T,{title:`Status`,badge:e.state,icon:(0,I.jsx)(xe,{size:14}),children:[(0,I.jsx)(eE,{label:`run id`,value:e.workflowRunId?$E(e.workflowRunId):`not started`}),(0,I.jsx)(eE,{label:`status`,value:e.state}),(0,I.jsx)(eE,{label:`record source`,value:e.workflowRunId?`Project workflow run id`:`no run record yet`})]}),(0,I.jsxs)($T,{title:`Current node`,badge:t?.status??`none`,icon:(0,I.jsx)(ut,{size:14}),children:[(0,I.jsx)(eE,{label:`node`,value:t?.label??`none`}),(0,I.jsx)(eE,{label:`node id`,value:t?.id??`none`}),(0,I.jsx)(eE,{label:`source`,value:`project/session run cursor`})]}),(0,I.jsx)($T,{title:`Run history`,badge:`${e.runHistory.length}`,icon:(0,I.jsx)(et,{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:$E(e.id)}),(0,I.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide ${QE(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)(tE,{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)($T,{title:`Node attempts`,badge:`${e.nodeAttempts.length}`,icon:(0,I.jsx)(it,{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 ${QE(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)(tE,{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)($T,{title:`Edge transfers`,badge:`${e.edgeTransfers.length}`,icon:(0,I.jsx)(Ze,{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 ${QE(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)(tE,{children:`No edge transfers recorded for this workflow run yet.`})}),(0,I.jsx)($T,{title:`Output`,badge:e.finalOutput?`available`:`empty`,icon:(0,I.jsx)(Re,{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)(el,{value:e.finalOutput.value,defaultExpandLevel:1,maxHeight:`12rem`,showControls:!1})]}):(0,I.jsx)(tE,{children:`No workflow output has been recorded for this run yet.`})}),(0,I.jsx)($T,{title:`Error`,badge:n.length?`${n.length}`:`none`,icon:(0,I.jsx)(ht,{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)(tE,{children:`No workflow run errors are recorded.`})})]})]})}function QT({model:e,onOpenSession:t}){let n=gE(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)(Ke,{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)(Ke,{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:$E(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)(tE,{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:vE(e.definitionLink)}),e.definitionLink.definitionHash?(0,I.jsxs)(`div`,{className:`mt-1 font-mono text-[10px] text-emerald-100/60`,children:[`snapshot `,$E(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:vE(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 `,$E(e.definitionLink.definitionHash)]}):null]})]})]})]})}function $T({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 eE({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 tE({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 nE({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 rE({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 iE(e){return e.nodes.find(e=>e.status===`active`||e.status===`waiting`)??e.nodes[0]}function aE({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)(ut,{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)(oE,{node:e,edge:t[n]},e.id))})]})}function oE({node:e,edge:t}){return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)(`div`,{className:`rounded-sm border p-3 ${XE(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)(qE,{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)(Ze,{size:14,className:`mx-auto mb-1 text-[#11a4d4]`}),t.label]})}):null]})}function sE({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)(xe,{size:14}),`Current UI Snapshot`]}),(0,I.jsx)(el,{value:e.snapshot,showControls:!1})]})}function cE({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)(it,{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 ${XE(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)(qE,{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 ${ZE(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 lE({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)(Re,{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)(el,{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)(ht,{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 uE({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)(Ve,{size:14}),`Projection Facts`]}),(0,I.jsxs)(`dl`,{className:`space-y-3`,children:[(0,I.jsx)(dE,{label:`projection kind`,value:`pibo.workflow.xstateUiModel`}),(0,I.jsx)(dE,{label:`schema`,value:`v1`}),(0,I.jsx)(dE,{label:`durable truth`,value:`kernel`}),(0,I.jsx)(dE,{label:`private payloads`,value:`not exposed`}),(0,I.jsx)(dE,{label:`states`,value:String(e.nodes.length)}),(0,I.jsx)(dE,{label:`transitions`,value:String(e.edges.length)}),(0,I.jsx)(dE,{label:`trace`,value:e.traceVersion??`pending`})]})]})}function dE({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 fE(e,t,n,r,i,a){if(!BE(e))return null;let o=VE(e,n),s=HE(e,n),c=UE(s),l=OE(t,s),u=[...AE(t),...kE(e,i)],d=xE(e,o,c),f=SE(t,e.workflowRunId),p=TE(t,e.workflowRunId),m=EE(t,r),h=pE(e),g=mE(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:WE(s),label:GE(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:WE(s),label:KE(s)}],configuration:yE(e),definitionLink:h,nestedSessionLinks:g,pendingHumanActions:bE(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`&&!!gE(h)},nestedWorkflowSessionCount:g.length}}}function pE(e){return e.workflowDefinitionLink?e.workflowDefinitionLink:e.workflowVersion?{status:`live`,workflowId:e.workflowId,workflowVersion:e.workflowVersion,title:e.title??e.workflowId,href:_E(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 mE(e,t){let n=hE(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 hE(e,t){for(let n of e){if(n.piboSessionId===t)return n;let e=hE(n.children,t);if(e)return e}}function gE(e){if(e.status===`live`){if(e.href)return e.href;if(e.workflowVersion)return _E(e.workflowId,e.workflowVersion)}}function _E(e,t){return`/apps/chat/workflows/view/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function vE(e){return`${e.workflowId}${e.workflowVersion?`@${e.workflowVersion}`:``}`}function yE(e){let t=e.configuration;return{inputKeys:Object.keys(t?.inputValues??{}).sort(),promptOverrideNodeIds:Object.keys(t?.promptOverrides??{}).sort()}}function bE(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=VE(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 xE(e,t,n){return e.workflowRunId?[{id:e.workflowRunId,status:t,currentNodeId:n,updatedAt:e.updatedAt,source:`project session run record`}]:[]}function SE(e,t){return!t||!e?[]:jE(e.nodes).filter(CE).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:wE(e.status),attempt:t+1,source:`session trace fact`,...e.startedAt?{startedAt:e.startedAt}:{},...e.completedAt?{completedAt:e.completedAt}:{}}))}function CE(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 wE(e){return e===`done`?`completed`:e===`error`?`failed`:`running`}function TE(e,t){if(!t||!e)return[];let n=[];for(let r of e.rawEvents){if(!zE(r.payload))continue;let e=RE(r.payload.type),i=RE(r.payload.runId);if(e!==`edge.transferred`||i&&i!==t)continue;let a=RE(r.payload.edgeId);a&&n.push({id:RE(r.payload.edgeTransferId)??r.id,edgeId:a,status:`transferred`,source:r.type,createdAt:r.createdAt})}return n.slice(0,8)}function EE(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 jE(e.nodes)){let e=t.error??(t.status===`error`?NE(t.output)??NE(t.summary):void 0);e&&n.push({id:`node:${t.id}`,message:e,source:t.type})}for(let t of e.rawEvents){if(!zE(t.payload))continue;let e=t.payload.error,r=zE(e)?RE(e.message):RE(e),i=zE(e)?RE(e.code):void 0;r&&n.push({id:`event:${t.id}`,message:r,...i?{code:i}:{},source:t.type})}}return DE(n).slice(0,8)}function DE(e){let t=new Set;return e.filter(e=>{let n=`${e.code??``}:${e.message}:${e.source??``}`;return t.has(n)?!1:(t.add(n),!0)})}function OE(e,t){if(t!==`completed`||!e)return;let n=jE(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 kE(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 FE(n).slice(0,8)}function AE(e){if(!e)return[];let t=[];for(let n of jE(e.nodes)){let e=n.error??NE(n.output)??NE(n.summary);e&&(!PE([n.title,n.summary,n.error,n.type].filter(e=>typeof e==`string`).join(` `))&&!PE(e)||t.push({id:`node:${n.id}`,message:e,...n.type?{source:n.type}:{}}))}for(let n of e.rawEvents)ME(n.payload,`event:${n.id}`,t);return FE(t).slice(0,8)}function jE(e){let t=[],n=e=>{for(let r of e)t.push(r),n(r.children)};return n(e),t}function ME(e,t,n,r=0){if(r>4||!zE(e))return;let i=Array.isArray(e.diagnostics)?e.diagnostics:void 0;if(i)for(let e of i){if(!zE(e))continue;let r=RE(e.message)??NE(e);r&&n.push({id:`${t}:diagnostic:${n.length}`,message:r,...RE(e.code)?{code:RE(e.code)}:{},...RE(e.path)?{path:RE(e.path)}:{},source:`workflow.diagnostic`})}let a=e.error;if(zE(a)){let e=RE(a.code),r=RE(a.message)??NE(a);r&&PE([e,r].filter(Boolean).join(` `))&&n.push({id:`${t}:error:${n.length}`,message:r,...e?{code:e}:{},source:`workflow.error`})}else typeof a==`string`&&PE(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`||ME(a,`${t}:${i}`,n,r+1)}function NE(e){if(typeof e==`string`)return e;if(zE(e))return RE(e.message)??RE(e.error)??RE(e.summary)}function PE(e){let t=e.toLowerCase();return t.includes(`validation`)||t.includes(`validate`)||t.includes(`diagnostic`)||t.includes(`workflowinterfaceerror`)||t.includes(`workflowruntimeerror.validation`)}function FE(e){let t=new Set;return e.filter(e=>{let n=`${e.code??``}:${e.path??``}:${e.message}`;return t.has(n)?!1:(t.add(n),!0)})}function IE(e){return zE(e)&&zE(e.data)&&Array.isArray(e.data.diagnostics)?e.data.diagnostics.filter(zE).map(t=>({code:RE(t.code)??`WorkflowRuntimeError.humanActionRejected`,message:RE(t.message)??LE(e),severity:t.severity===`info`||t.severity===`warning`||t.severity===`error`?t.severity:`error`,...RE(t.path)?{path:RE(t.path)}:{},...RE(t.registryRef)?{registryRef:RE(t.registryRef)}:{},...RE(t.hint)?{hint:RE(t.hint)}:{}})):[{code:`WorkflowRuntimeError.humanActionRejected`,message:LE(e),severity:`error`}]}function LE(e){return e instanceof Error?e.message:String(e)}function RE(e){return typeof e==`string`&&e.trim()?e:void 0}function zE(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function BE(e){return!!e.workflowRunId||e.state===`workflow`||e.workflowId!==`simple-chat`}function VE(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 HE(e,t){let n=VE(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 UE(e){return e===`completed`?`workflow.completed`:e===`failed`?`workflow.failed`:e===`cancelled`?`workflow.cancelled`:`node.session`}function WE(e){return e===`failed`?`workflow.failed`:e===`cancelled`?`workflow.cancelled`:`workflow.completed`}function GE(e){return e===`failed`?`failed`:e===`cancelled`?`cancelled`:`completed`}function KE(e){return e===`failed`?`WORKFLOW.FAIL`:e===`cancelled`?`WORKFLOW.CANCEL`:`WORKFLOW.NODE.DONE`}function qE({status:e}){return e===`completed`?(0,I.jsx)(Re,{size:16,className:`text-emerald-300`}):e===`failed`?(0,I.jsx)(Be,{size:16,className:`text-red-300`}):e===`cancelled`?(0,I.jsx)(ht,{size:16,className:`text-slate-400`}):e===`waiting`?(0,I.jsx)(He,{size:16,className:`text-amber-300`}):e===`active`?(0,I.jsx)(xe,{size:16,className:`text-[#11a4d4]`}):(0,I.jsx)(Ve,{size:16,className:`text-slate-500`})}function JE({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 YE(e){return e===`completed`?`green`:e===`failed`||e===`cancelled`?`red`:e===`waiting`?`amber`:`blue`}function XE(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 ZE(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 QE(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 $E(e){return e.length>18?`${e.slice(0,10)}…${e.slice(-6)}`:e}var eD=[{id:`terminal`,label:`Terminal`,description:`Compact Codex-style terminal transcript.`,render:e=>(0,I.jsx)(yT,{...e})},{id:`workflow`,label:`Workflow`,description:`Workflow/XState visualization for workflow-backed project sessions.`,render:e=>(0,I.jsx)(KT,{...e})}],tD=new Map(eD.map(e=>[e.id,e]));function nD(){return eD}function rD(e){return tD.get(e)??tD.get(`terminal`)}var iD=`pibo.chat.composerHistory`,aD=100;function oD(){try{let e=localStorage.getItem(iD);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`&&e.trim().length>0).slice(-aD):[]}catch{return[]}}function sD(e){let t=e.trim();if(!t)return;let n=oD();if(n.at(-1)!==t)try{localStorage.setItem(iD,JSON.stringify([...n,t].slice(-aD)))}catch{}}function cD(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 lD(e,t){return e.length>t?`${e.slice(0,Math.max(0,t-1))}…`:e}function uD({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),[ee,A]=(0,v.useState)([]),[te,ne]=(0,v.useState)(!1),[re,ie]=(0,v.useState)(null),[j,M]=(0,v.useState)(null),ae=(0,v.useMemo)(()=>{for(let e=O-1;e>=0;e--){let t=i[e];if(t===` `||t===`
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]),oe=i.trim().startsWith(`/`)?i.trim().split(/\s+/)[0]:null,se=ae?dD(ae.startPos,i.slice(ae.startPos,O)):null,ce=oe?fD(oe):null,le=(0,v.useMemo)(()=>ae?r.filter(e=>e.name.toLowerCase().startsWith(ae.query)):[],[ae,r]),ue=(0,v.useMemo)(()=>oe?n.filter(e=>e.slash.startsWith(oe)):[],[oe,n]),de=se&&ee.includes(se)?[]:le,P=ce&&ee.includes(ce)?[]:ue,fe=(0,v.useCallback)(e=>{e&&A(t=>t.includes(e)?t:[...t,e])},[]),pe=(0,v.useCallback)(()=>{let e=[le.length?se:null,ue.length?ce:null].filter(e=>!!e);e.length&&A(t=>{let n=new Set(t);for(let t of e)n.add(t);return n.size===t.length?t:[...n]})},[ce,ue.length,le.length,se]);(0,v.useEffect)(()=>{let e=[se,ce].filter(e=>!!e);A(t=>t.filter(t=>e.includes(t)))},[ce,se]),(0,v.useEffect)(()=>{!P.length||w<P.length||T(0)},[w,P.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,P.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(!j)return;let e=requestAnimationFrame(()=>b.current?.focus());return()=>{cancelAnimationFrame(e),URL.revokeObjectURL(j.previewUrl)}},[j]),(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(!P.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,P.length,de.length]),(0,v.useLayoutEffect)(()=>{yD(_.current)},[i]);let me=e=>{if(!ae||!_.current)return;let t=i.slice(0,ae.startPos),n=i.slice(ae.endPos);c(t+`$`+e+n),fe(dD(ae.startPos,`$${e}`));let r=ae.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=oD();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=()=>{M(null)},ye=e=>{if(t||te)return;let n=pD(e.clipboardData);if(!n.length)return;e.preventDefault(),pe(),ie(null);let r=n[0];M(e=>(e&&URL.revokeObjectURL(e.previewUrl),{file:r,previewUrl:URL.createObjectURL(r)}))},be=async()=>{if(!j||te)return;let e=j.file;M(null),await F([e])},F=async e=>{if(e.length){ne(!0),ie({message:`Uploading ${e.length} file${e.length===1?``:`s`}...`,error:!1});try{f((await N(e)).files),ie(null)}catch(e){ie({message:e instanceof Error?e.message:String(e),error:!0})}finally{ne(!1)}}},xe=async()=>{if(t)return;let e=i.trim();if(e){if(de.length){me(de[Math.min(E,de.length-1)].name);return}if(P.length&&!n.some(t=>t.slash===e.split(/\s+/)[0])){let e=P[Math.min(w,P.length-1)].slash;c(e),fe(fD(e));return}if(C.current=null,sD(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=``,F(t)}}),re?(0,I.jsxs)(`div`,{className:`mb-2 flex items-center gap-2 rounded-sm border px-3 py-2 text-xs ${re.error?`border-red-900 bg-red-950/40 text-red-200`:re.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:re.message}),re.copyText?(0,I.jsx)(`button`,{type:`button`,onClick:()=>void cD(re.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)(Ue,{size:13})}):null,(0,I.jsx)(`button`,{type:`button`,onClick:()=>ie(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)(_t,{size:13})})]}):null,j?(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 ~/.pibo/uploads?`})]}),(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)(_t,{size:14})})]}),(0,I.jsxs)(`div`,{className:`space-y-3 px-4 py-4`,children:[(0,I.jsx)(`img`,{src:j.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:j.file.name}),(0,I.jsx)(`span`,{className:`shrink-0 font-mono`,children:vD(j.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:lD(e.name||e.path,100)}),(0,I.jsx)(`button`,{type:`button`,onClick:()=>void cD(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)(Ue,{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)(_t,{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:lD(e.primaryTarget||e.label||e.note||e.id,100)}),(0,I.jsx)(_t,{size:11,className:`shrink-0 text-[#11a4d4]`})]},e.id))})]}):null,P.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:P.map((e,t)=>(0,I.jsxs)(`button`,{ref:t===w?x:null,type:`button`,onClick:()=>{c(e.slash),fe(fD(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`,{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||P.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(P.length&&(e.key===`ArrowDown`||e.key===`ArrowUp`)){e.preventDefault(),T(t=>e.key===`ArrowDown`?(t+1)%P.length:(t-1+P.length)%P.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(),xe())},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 xe(),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)(pt,{size:16})})]})]})}function dD(e,t){return`skill:${e}:${t}`}function fD(e){return`command:${e}`}function pD(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(mD)}function mD(e){return e.name&&e.name!==`image.png`?e:new File([e],hD(e.type),{type:e.type||`image/png`,lastModified:Date.now()})}function hD(e){let t=gD(e),n=new Date;return`screenshot-${[n.getFullYear(),_D(n.getMonth()+1),_D(n.getDate()),`-`,_D(n.getHours()),_D(n.getMinutes()),_D(n.getSeconds())].join(``)}${t}`}function gD(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 _D(e){return String(e).padStart(2,`0`)}function vD(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KiB`:`${(e/(1024*1024)).toFixed(1)} MiB`}function yD(e){if(!e)return;if(!e.value.includes(`
41
+ `)&&e.value.length<80){e.style.height=``,e.style.overflowY=`hidden`;return}let t=window.getComputedStyle(e),n=bD(t.lineHeight,20),r=bD(t.borderTopWidth)+bD(t.borderBottomWidth),i=n*5+bD(t.paddingTop)+bD(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 bD(e,t=0){let n=Number.parseFloat(e);return Number.isFinite(n)?n:t}var xD=`pibo.chat.webAnnotations.cdpUrl`,SD=`pibo.chat.webAnnotations.selected`,CD=`${SD}.`,wD=`pibo.chat.webAnnotations.overlay.`,TD=`pibo.chat.webAnnotations.panelCollapsed`,ED=`pibo.chat.shortcuts.webAnnotationsToggle`,DD=`Alt+Shift+A`;function OD(){try{return localStorage.getItem(xD)??``}catch{return``}}function kD(e){try{e.trim()?localStorage.setItem(xD,e.trim()):localStorage.removeItem(xD)}catch{}}function AD(){try{return localStorage.getItem(ED)||`Alt+Shift+A`}catch{return DD}}function jD(e){try{return ND(localStorage.getItem(MD(e)))}catch{return null}}function MD(e){return wD+e}function ND(e){if(!e)return null;try{return PD(JSON.parse(e))}catch{return null}}function PD(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 FD(e){try{let t=LD(localStorage.getItem(SD));if(t.length||!e)return t;let n=CD+e,r=LD(localStorage.getItem(n));return r.length&&(localStorage.setItem(SD,JSON.stringify(r)),localStorage.removeItem(n)),r}catch{return[]}}function ID(e,t){try{let n=[...new Set(t.filter(e=>e.trim()))].slice(0,5);n.length?localStorage.setItem(SD,JSON.stringify(n)):localStorage.removeItem(SD),e&&localStorage.removeItem(CD+e)}catch{}}function LD(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 RD(){try{return localStorage.getItem(TD)===`true`}catch{return!1}}function zD(e){try{localStorage.setItem(TD,String(e))}catch{}}function BD({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.jsxs)(`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]}),a?null:(0,I.jsx)(`div`,{className:`text-[11px] text-slate-500`,children:`Global annotation list. Selected attachments follow you when switching sessions.`})]}),(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)(lt,{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)(mt,{size:12})}),(0,I.jsx)(`button`,{type:`button`,onClick:l,title:a?`Expand annotations panel`:`Collapse annotations panel`,"aria-label":a?`Expand annotations panel`:`Collapse annotations panel`,className:`inline-flex h-8 w-8 items-center justify-center rounded-sm border border-slate-700 text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] sm:h-7 sm:w-7`,children:a?(0,I.jsx)(Ie,{size:12}):(0,I.jsx)(Pe,{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)(_t,{size:12})})]})]}),a?null: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:ZD(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=>{let t=n.includes(e.id);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":t?`true`:`false`,className:`min-w-0 rounded-sm border px-3 py-2 text-xs ${t?`border-[#11a4d4] bg-[#11a4d4]/10`:`border-slate-800 bg-[#0e1116]`}`,children:[(0,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),className:`inline-flex h-8 shrink-0 items-center gap-1 rounded-sm border px-2 text-[11px] sm:h-6 sm:px-1.5 ${t?`border-[#11a4d4] text-[#11a4d4]`:`border-slate-700 text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:[t?(0,I.jsx)(_t,{size:11}):(0,I.jsx)(ct,{size:11}),` `,t?`Detach`:`Attach`]})]}),(0,I.jsx)(`div`,{className:`truncate text-slate-200`,title:e.primaryTarget||e.label||e.selector||e.id,children:ZD(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:ZD(e.piboContext,140)}):null,(0,I.jsx)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:e.url,children:JD(e.url)}),(0,I.jsxs)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:XD(e),children:[`Source `,YD(e)]}),(0,I.jsx)(`div`,{className:`mt-1 line-clamp-2 text-slate-400`,title:e.note,children:ZD(e.note,180)}),(0,I.jsx)(`div`,{className:`mt-1 text-[11px] text-slate-600`,children:QD(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 VD({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)(()=>OD()),[p,m]=(0,v.useState)([]),[h,g]=(0,v.useState)(`idle`),[_,y]=(0,v.useState)(!1),[b,x]=(0,v.useState)(null);(0,v.useEffect)(()=>{n&&c(!1)},[n]),(0,v.useEffect)(()=>{kD(d)},[d]);let S=async()=>{if(e){g(`loading`),x(null);try{m((await mx(d)).targets.filter(e=>e.type===`page`||e.attachable)),g(`loaded`)}catch(e){let t=KD(e,`CDP unavailable`);m([]),g(`error`),x({kind:`error`,message:t}),o(t)}}},C=async n=>{if(!e)throw Error(`No active session context`);return gx(n.binding.id,UD({piboSessionId:e,piboRoomId:t,cdpUrl:d,annotationShortcut:AD()}))},w=async()=>{if(!(!e||_)){i(),y(!0),x({kind:`info`,message:`Injecting annotation overlay into this Pibo page…`});try{let n=await hx({piboSessionId:e,piboRoomId:t,url:window.location.href,title:document.title,sameOrigin:!0,annotationShortcut:AD()});if(!n.overlay)throw Error(`Overlay config missing from same-origin binding response`);await GD(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=KD(e,`Current-page annotation failed`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}}},T=async()=>{if(!e||_)return;i();let n=l.trim();if(!n){x({kind:`error`,message:`URL is required`});return}if(WD(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 hx(UD({piboSessionId:e,piboRoomId:t,url:n,cdpUrl:d})),i=await C(r);x({kind:`success`,message:`Annotation overlay injected for ${qD(i.target??r.target,i.binding.url)}`}),u(``),o(null)}catch(e){let t=KD(e,`Annotation failed`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}},E=async n=>{if(!(!e||_)){i(),y(!0),x({kind:`info`,message:`Binding selected target and injecting overlay…`});try{let r=await C(await hx(UD({piboSessionId:e,piboRoomId:t,targetId:n.id,cdpUrl:d})));x({kind:`success`,message:`Annotation overlay injected for ${qD(r.target??n,r.binding.url)}`}),o(null)}catch(e){let t=KD(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)(HD,{onClick:()=>{n||(c(e=>!e),r||i())},title:n?`Select an active session to annotate a web page`:r?`Web Annotations`:`Show Web Annotations`,ariaLabel:`Web Annotations`,active:s||r,children:(0,I.jsx)(Ee,{size:14})}),s&&!n?(0,I.jsxs)(`div`,{className:`fixed inset-x-2 bottom-3 z-40 max-h-[calc(100svh-1.5rem)] overflow-y-auto rounded-sm border border-slate-700 bg-[#0e1116] p-3 text-sm shadow-xl sm:absolute sm:inset-auto sm:right-0 sm:top-full sm:bottom-auto sm:mt-2 sm:w-[min(420px,calc(100vw-24px))] sm:max-h-[calc(100svh-5rem)]`,role:`dialog`,"aria-label":`Web Annotations`,children:[(0,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)(dt,{size:14})}),(0,I.jsx)(`button`,{type:`button`,onClick:()=>c(!1),className:`rounded-sm p-1 text-slate-500 hover:bg-slate-800 hover:text-slate-200`,"aria-label":`Close Web Annotations panel`,children:(0,I.jsx)(_t,{size:14})})]})]}),(0,I.jsx)(`button`,{type:`button`,onClick:()=>void w(),disabled:_,className:`mb-3 h-10 w-full rounded-sm bg-emerald-600 px-3 text-xs font-medium text-white hover:bg-emerald-500 disabled:opacity-50 sm:h-9`,"data-pibo-debug":`web-annotations-current-page`,children:`Annotate this Pibo page`}),(0,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`&&T()},placeholder:`http://localhost:5173`,disabled:_,className:`h-10 min-w-0 rounded-sm border border-slate-700 bg-[#151f24] px-2 text-base text-slate-100 outline-none focus:border-[#11a4d4] disabled:opacity-60 sm:h-9 sm:text-xs`}),(0,I.jsx)(`button`,{type:`button`,onClick:()=>void T(),disabled:_||!l.trim(),className:`h-10 rounded-sm bg-[#11a4d4] px-3 text-xs font-medium text-white disabled:opacity-50 sm:h-9`,children:`Annotate`})]}),(0,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 S(),disabled:_||h===`loading`,className:`inline-flex h-7 items-center gap-1 rounded-sm border border-slate-700 px-2 text-[11px] text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:opacity-50`,children:[(0,I.jsx)(lt,{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:ZD(e.title||`Untitled target`,120)}),(0,I.jsx)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:e.url,children:ZD(e.url||e.id,160)})]}),(0,I.jsx)(`button`,{type:`button`,onClick:()=>void E(e),disabled:_||!e.attachable,title:e.attachable?`Attach selected target`:`Target is not attachable`,className:`h-9 rounded-sm border border-slate-700 px-2 text-[11px] text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:opacity-40 sm:h-8`,children:`Attach`})]},e.id))]}),b?(0,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 HD({title:e,ariaLabel:t,active:n,onClick:r,children:i}){return(0,I.jsx)(`button`,{type:`button`,onClick:r,title:e,"aria-label":t,className:`h-8 w-8 inline-flex items-center justify-center border rounded-sm transition-colors ${n?`border-[#11a4d4] bg-[#11a4d4]/10 text-[#11a4d4]`:`border-slate-700 text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:i})}function UD(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e&&e.trim()))}function WD(e){try{let t=new URL(e);return t.port===`56663`||t.pathname.startsWith(`/json/`)}catch{return!1}}function GD(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 KD(e,t){let n=$D(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 qD(e,t){let n=e?.url||t||e?.title||`target`;return JD(e?.title||n)}function JD(e){try{let t=new URL(e);return`${t.host}${t.pathname===`/`?``:t.pathname}`}catch{return ZD(e,80)}}function YD(e){return e.piboRoomId?`${ZD(e.piboSessionId,24)} · room ${ZD(e.piboRoomId,18)}`:ZD(e.piboSessionId,44)}function XD(e){return e.piboRoomId?`Session ${e.piboSessionId} in room ${e.piboRoomId}`:`Session ${e.piboSessionId}`}function ZD(e,t){return e.length>t?`${e.slice(0,Math.max(0,t-1))}…`:e}function QD(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{dateStyle:`short`,timeStyle:`short`})}function $D(e){return e instanceof Error?e.message:String(e)}function eO(e){return!!e.workflowRunId||e.state===`workflow`||e.workflowId!==`simple-chat`}function tO(e,t){return{workflowId:e.workflowId,state:rO(e,t),...e.workflowRunId?{workflowRunId:e.workflowRunId}:{}}}function nO({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:iO(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 `,aO(e.workflowRunId)]}):null]})}function rO(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 iO(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 aO(e){return e.length>18?`${e.slice(0,10)}…${e.slice(-6)}`:e}function oO({title:e,roomLabel:t,headerPiboSessionId:n,piboSessionId:r,piboRoomId:i,webAnnotationsDisabled:a,webAnnotationsPanelRendered:o,workflowHeader:s,sessionViewId:c,sessionViews:l,currentSessionView:u,allowedSessionViewIds:d,extraViewTabs:f,activeViewId:p,showRawEvents:m,showThinking:h,expandThinking:g,onShowWebAnnotationsPanel:_,onHideWebAnnotationsPanel:y,onSelectSessionView:b,onToggleRawEvents:x,onToggleThinking:S,onToggleExpandThinking:C,onError:w}){let[T,E]=(0,v.useState)(null),D=(0,v.useRef)(void 0),O=T===n,k=p??c,ee=(0,v.useMemo)(()=>d?new Set(d):null,[d]);(0,v.useEffect)(()=>()=>{D.current&&window.clearTimeout(D.current)},[]);let A=()=>{n&&(cD(n).catch(()=>void 0),E(n),D.current&&window.clearTimeout(D.current),D.current=window.setTimeout(()=>E(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 A(),title:O?`Copied Pibo session ID`:`Copy Pibo session ID`,"aria-label":O?`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] ${O?`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)(nO,{summary:s}):null]})]}),(0,I.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,I.jsx)(VD,{piboSessionId:r,piboRoomId:i,disabled:a,panelVisible:o,onShowPanel:_,onHidePanel:y,onError:w}),(0,I.jsxs)(`div`,{className:`flex items-center rounded-sm border border-slate-700 bg-[#0e1116] p-0.5`,children:[l.map(e=>{let t=!!(ee&&!ee.has(e.id));return(0,I.jsx)(`button`,{type:`button`,onClick:()=>{t||b(e.id)},disabled:t,title:t?`Project session routing uses the ${u.label} view for this session kind.`:e.description??e.label,"aria-label":t?`${e.label} view unavailable for this Project session kind`:`Switch to ${e.label} view`,className:`min-w-20 px-2.5 py-1 text-[11px] font-bold tracking-wide max-[980px]:min-w-0 max-[980px]:px-1.5 disabled:cursor-not-allowed disabled:text-slate-600 ${k===e.id?`bg-[#11a4d4]/10 text-[#11a4d4]`:`text-slate-400 hover:text-[#11a4d4] disabled:hover:text-slate-600`}`,children:e.label},e.id)}),f?.map(e=>(0,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`,className:`min-w-20 px-2.5 py-1 text-[11px] font-bold tracking-wide max-[980px]:min-w-0 max-[980px]:px-1.5 disabled:cursor-not-allowed disabled:text-slate-600 ${e.active??k===e.id?`bg-[#11a4d4]/10 text-[#11a4d4]`:`text-slate-400 hover:text-[#11a4d4] disabled:hover:text-slate-600`}`,children:e.label},e.id))]}),(0,I.jsx)(sO,{onClick:x,title:m?`Hide Raw Events`:`Show Raw Events`,ariaLabel:m?`Hide Raw Events`:`Show Raw Events`,active:m,children:(0,I.jsx)(ke,{size:14})}),(0,I.jsx)(sO,{onClick:S,title:h?`Hide Thinking`:`Show Thinking`,ariaLabel:h?`Hide Thinking`:`Show Thinking`,active:h,children:h?(0,I.jsx)(Oe,{size:14}):(0,I.jsx)(qe,{size:14})}),h?(0,I.jsx)(sO,{onClick:C,title:g?`Collapse Thinking`:`Expand Thinking`,ariaLabel:g?`Collapse Thinking`:`Expand Thinking`,active:g,children:g?(0,I.jsx)(Pe,{size:14}):(0,I.jsx)(Ie,{size:14})}):null]})]})}function sO({title:e,ariaLabel:t,active:n,onClick:r,children:i}){return(0,I.jsx)(`button`,{type:`button`,onClick:r,title:e,"aria-label":t,className:`h-8 w-8 inline-flex items-center justify-center border rounded-sm transition-colors ${n?`border-[#11a4d4] bg-[#11a4d4]/10 text-[#11a4d4]`:`border-slate-700 text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:i})}function cO(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&lO(e,n)){e.count+=1,e.createdAt=n.createdAt,e.payload={...fO(e.payload)?e.payload:{},text:`${uO(e.payload)}${uO(n.payload)}`};continue}t.push({...n,count:1})}return t}function lO(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=fO(e.payload)?e.payload:{},r=fO(t.payload)?t.payload:{};return dO(n)===dO(r)}function uO(e){return fO(e)?typeof e.text==`string`?e.text:typeof e.delta==`string`?e.delta:``:``}function dO(e){return e.eventId??e.messageId}function fO(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function pO({traceView:e,eventLimit:t,isFetching:n,visible:r,onLoadOlder:i}){let a=(0,v.useMemo)(()=>r?cO(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)(el,{value:e.payload,showControls:!1})]},e.id))]})]}):null}function mO({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,headerProps:p,projectSessionCreatePanel:m,workflowStartPanel:h,projectModulePanel:g,currentSessionView:_,sessionViewProps:v,webAnnotationsPanelRendered:y,webAnnotationsPanelProps:b,composerProps:x}){let S=a||o&&!l||i;return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)(`main`,{"data-pibo-debug":`chat-shell`,"data-pibo-session-id":e??void 0,"data-pibo-room-id":t??n??void 0,"data-pibo-view-id":r,"data-pibo-state":a?`room-loading`:o?`session-loading`:i?`loading`:s?`error`:e?`ready`:`empty`,className:`min-h-0 flex flex-col`,children:[(0,I.jsx)(oO,{...p}),m?(0,I.jsx)(`div`,{className:`border-b border-slate-800 bg-[#101d22] px-4 py-3`,children:m}):null,h?(0,I.jsx)(`div`,{className:`border-b border-slate-800 bg-[#101d22] px-4 py-3`,children:h}):null,g||(S?(0,I.jsx)(hO,{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}):_.render(v)),y?(0,I.jsx)(BD,{...b}):null,(0,I.jsx)(uD,{...x})]}),(0,I.jsx)(pO,{traceView:l,eventLimit:u,isFetching:d,visible:c,onLoadOlder:f})]})}function hO({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)(gO,{kind:e.kind,lineCount:e.lines},t))]})})})}function gO({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 _O=[`a[href]`,`button:not([disabled])`,`input:not([disabled])`,`select:not([disabled])`,`textarea:not([disabled])`,`[tabindex]:not([tabindex="-1"])`].join(`,`);function vO({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(_O)??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(_O)??[]);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)(_t,{size:14})})]}),i]})})}function yO(e){let t=new Map;if(wO(e.nodes,t),!t.size)return e;let{nodes:n,changed:r}=TO(e.nodes,t);return r?{...e,nodes:n}:e}function bO(e){return e.some(CO)}function xO(e){let t=new Map;return DO(e,e=>{if(e.type!==`user.message`||!e.entryId)return;let n=OO(e),r=t.get(n);r?r.push(e.entryId):t.set(n,[e.entryId])}),t}function SO(e,t){if(!t.size)return;let n=new Map;DO(e,e=>{if(e.type!==`user.message`||e.entryId)return;let r=OO(e),i=t.get(r);if(!i?.length)return;let a=n.get(r)??0,o=i[a];o&&(e.entryId=o,n.set(r,a+1))})}function CO(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 wO(e,t){for(let n of e){if(n.type===`user.message`&&!EO(n)){let e=OO(n);e&&t.set(e,(t.get(e)??0)+1)}wO(n.children,t)}}function TO(e,t){let n=!1,r=[];for(let i of e){if(EO(i)){let e=OO(i),r=e?t.get(e)??0:0;if(r>0){t.set(e,r-1),n=!0;continue}}let e=TO(i.children,t);n||=e.changed,r.push(e.changed?{...i,children:e.nodes}:i)}return{nodes:n?r:e,changed:n}}function EO(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 DO(e,t){for(let n of e)t(n),DO(n.children,t)}function OO(e){return typeof e.output==`string`?e.output:typeof e.summary==`string`?e.summary:``}function kO({selectedPiboSessionId:e,reconciledBaseTraceView:t,liveTraceOverlay:n,selectedSessionStatus:r,persistedUserMessageIndexForBaseTrace:i,now:a}){if(!e||t?.piboSessionId!==e)return{traceView:null};let o=n?.piboSessionId===e?n.events:[];if(!o.length)return{traceView:t};let s=a?.(),c=kC(t,o,r??`idle`),l=bO(o);return l&&SO(c.nodes,i),{traceView:l?yO(c):c,liveTraceComputeDurationMs:s!==void 0&&a?a()-s:void 0}}function AO(e,t){for(let n of e)t(n),AO(n.children,t)}function jO(e){return typeof e.output==`string`?e.output:typeof e.summary==`string`?e.summary:``}function MO(e){if(!e)return;let t=0;return AO(e.nodes,e=>{e.type===`assistant.message`&&(t+=jO(e).length)}),t}function NO({selectedPiboSessionId:e,baseTraceView:t,liveTraceOverlay:n,selectedSessionStatus:r}){let i=(0,v.useMemo)(()=>t?yO(t):null,[t]),a=(0,v.useMemo)(()=>i?xO(i.nodes):new Map,[i]),o=(0,v.useMemo)(()=>kO({selectedPiboSessionId:e,reconciledBaseTraceView:i,liveTraceOverlay:n,selectedSessionStatus:r,persistedUserMessageIndexForBaseTrace:a,now:$v()?()=>performance.now():void 0}),[n,e,r,i,a]),s=o.traceView;return(0,v.useEffect)(()=>{!e||!s?.piboSessionId||!$v()||(cy(s.piboSessionId,{overlayEventCount:n?.piboSessionId===s.piboSessionId?n.events.length:0,traceBaseOutputLength:MO(t),currentOutputLength:MO(s)}),o.liveTraceComputeDurationMs!==void 0&&ay(s.piboSessionId,o.liveTraceComputeDurationMs))},[t,o.liveTraceComputeDurationMs,s,n,e]),(0,v.useEffect)(()=>{let e=()=>{!s?.piboSessionId||!yb()||Cb(s.piboSessionId,`tab:${document.visibilityState}`,s.nodes,{traceVersion:s.version,latestStreamId:s.latestStreamId,lastRawEventId:s.rawEvents.at(-1)?.id})};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[s]),s}var PO=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(){}},FO=new class extends PO{#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`}},IO={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},LO=new class{#e=IO;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 RO(e){setTimeout(e,0)}var zO=typeof window>`u`||`Deno`in globalThis;function BO(){}function VO(e){return typeof e==`number`&&e>=0&&e!==1/0}function HO(e,t){return Math.max(e+(t||0)-Date.now(),0)}function UO(e,t){return typeof e==`function`?e(t):e}function WO(e,t){return typeof e==`function`?e(t):e}var GO=Object.prototype.hasOwnProperty;function KO(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=JO(e)&&JO(t);if(!r&&!(YO(e)&&YO(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:GO.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=KO(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function qO(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 JO(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function YO(e){if(!XO(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!XO(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function XO(e){return Object.prototype.toString.call(e)===`[object Object]`}function ZO(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:KO(e,t)}function QO(e,t){return typeof e==`function`?e(...t):!!e}var $O=(()=>{let e=()=>zO;return{isServer(){return e()},setIsServer(t){e=t}}})();function ek(){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 tk=RO;function nk(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=tk,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 rk=nk(),ik=new class extends PO{#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 ak(e){return(e??`online`)===`online`?ik.isOnline():!0}function ok(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ak(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}var sk=class extends PO{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=ek(),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),lk(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return uk(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return uk(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 WO(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&&!qO(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&dk(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||WO(this.options.enabled,this.#t)!==WO(t.enabled,this.#t)||UO(this.options.staleTime,this.#t)!==UO(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||WO(this.options.enabled,this.#t)!==WO(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 pk(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(BO)),t}#g(){this.#b();let e=UO(this.options.staleTime,this.#t);if($O.isServer()||this.#r.isStale||!VO(e))return;let t=HO(this.#r.dataUpdatedAt,e)+1;this.#d=LO.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,!($O.isServer()||WO(this.options.enabled,this.#t)===!1||!VO(this.#p)||this.#p===0)&&(this.#f=LO.setInterval(()=>{(this.options.refetchIntervalInBackground||FO.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(LO.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(LO.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&&lk(e,t),o=i&&dk(e,n,t,r);(a||o)&&(l={...l,...ok(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=ZO(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=ZO(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:fk(e,t),refetch:this.refetch,promise:this.#o,isEnabled:WO(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let t=x.data!==void 0,r=x.status===`error`&&!t,i=e=>{r?e.reject(x.error):t&&e.resolve(x.data)},a=()=>{i(this.#o=x.promise=ek())},o=this.#o;switch(o.status){case`pending`:e.queryHash===n.queryHash&&i(o);break;case`fulfilled`:(r||x.data!==o.value)&&a();break;case`rejected`:(!r||x.error!==o.reason)&&a();break}}return x}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#u=this.#t),!qO(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){rk.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function ck(e,t){return WO(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status===`error`&&WO(t.retryOnMount,e)===!1)}function lk(e,t){return ck(e,t)||e.state.data!==void 0&&uk(e,t,t.refetchOnMount)}function uk(e,t,n){if(WO(t.enabled,e)!==!1&&UO(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&fk(e,t)}return!1}function dk(e,t,n,r){return(e!==t||WO(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&fk(e,n)}function fk(e,t){return WO(t.enabled,e)!==!1&&e.isStaleByTime(UO(t.staleTime,e))}function pk(e,t){return!qO(e.getCurrentResult(),t)}var mk=v.createContext(void 0),hk=e=>{let t=v.useContext(mk);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},gk=v.createContext(!1),_k=()=>v.useContext(gk);gk.Provider;function vk(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var yk=v.createContext(vk()),bk=()=>v.useContext(yk),xk=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?QO(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Sk=e=>{v.useEffect(()=>{e.clearReset()},[e])},Ck=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||QO(n,[e.error,r])),wk=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))}},Tk=(e,t)=>e.isLoading&&e.isFetching&&!t,Ek=(e,t)=>e?.suspense&&t.isPending,Dk=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Ok(e,t,n){let r=_k(),i=bk(),a=hk(n),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let s=a.getQueryCache().get(o.queryHash);o._optimisticResults=r?`isRestoring`:`optimistic`,wk(o),xk(o,i,s),Sk(i);let c=!a.getQueryCache().get(o.queryHash),[l]=v.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&e.subscribed!==!1;if(v.useSyncExternalStore(v.useCallback(e=>{let t=d?l.subscribe(rk.batchCalls(e)):BO;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),v.useEffect(()=>{l.setOptions(o)},[o,l]),Ek(o,u))throw Dk(o,l,i);if(Ck({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,u),o.experimental_prefetchInRender&&!$O.isServer()&&Tk(u,r)&&(c?Dk(o,l,i):s?.promise)?.catch(BO).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?u:l.trackResult(u)}function kk(e,t){return Ok(e,sk,t)}var Ak=1e4,jk=5*6e4;function Mk(e){return[`chat`,`trace-summary`,e]}function Nk(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 Pk(e,t,n){return t&&e.set(t.piboSessionId,t),n?e.get(n)??null:null}function Fk(e,t,n){t&&t.piboSessionId!==n.piboSessionId&&e.set(t.piboSessionId,t);let r=Ik(t?.piboSessionId===n.piboSessionId?t:e.get(n.piboSessionId)??null,n);return r?e.set(n.piboSessionId,r):e.delete(n.piboSessionId),r}function Ik(e,t){if(!e||e.piboSessionId!==t.piboSessionId)return e;let n=Rk(t),r=Lk(t.nodes),i=e.events.filter(e=>{if(CO(e)&&r.has(e.payload.text))return!1;let t=Bk(e);return!t||!n.has(t)});return i.length?{...e,events:i}:null}function Lk(e){let t=new Set;for(let n of e){if(n.type===`user.message`&&n.source===`transcript`){let e=Vk(n);e&&t.add(e)}for(let e of Lk(n.children))t.add(e)}return t}function Rk(e){let t=new Set;for(let n of e.rawEvents){let e=Bk(n);e&&t.add(e)}return zk(e.nodes,t),t}function zk(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}`),n.source===`transcript`&&n.entryId&&t.add(`${n.piboSessionId}:${e}:${n.entryId}`)}n.eventId&&n.type===`assistant.message`&&(t.add(`${n.piboSessionId}:assistant_delta:${n.eventId}`),t.add(`${n.piboSessionId}:assistant_message:${n.eventId}`)),n.eventId&&n.type===`model.reasoning`&&(t.add(`${n.piboSessionId}:thinking_delta:${n.eventId}`),t.add(`${n.piboSessionId}:thinking_finished:${n.eventId}`)),zk(n.children,t)}}function Bk(e){let t=e.payload;if(!t||typeof t!=`object`||Array.isArray(t))return;let n=`eventId`in t&&typeof t.eventId==`string`?t.eventId:e.eventId,r=`piboSessionId`in t&&typeof t.piboSessionId==`string`?t.piboSessionId:e.piboSessionId;if(!(!n||!r))return`${r}:${e.type}:${n}`}function Vk(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 Hk(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)?!1:(n.add(t),!0)});return{...e,version:e.version,nodes:Wk(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 Uk(e,t){return e.piboSessionId===t.piboSessionId?{...t,nodes:Wk(e.nodes,t.nodes),rawEvents:e.rawEvents.length?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 Wk(e,t){let n=new Map;for(let t of fS([...e]))n.set(t.id,{...t,children:[]});for(let e of fS([...t])){let t=n.get(e.id);n.set(e.id,{...t,...e,children:[]})}return pS([...n.values()])}function Gk(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??Kk(e.cursor.before):void 0;for(let t of e.nodes)n.set(t.nodeId,qk(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??Kk(e.cursor.before),lastEventSequence:e.lastEventSequence??Kk(e.cursor.after),nextBeforeSequence:o,nextBeforeCursor:a,hasOlderEvents:i,nodes:r,rawEvents:t}}function Kk(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function qk(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 Jk=128;function Yk({selectedPiboSessionId:e,showRawEvents:t,liveTraceOverlay:n,liveTraceOverlayCacheRef:r,setLiveTraceOverlay:i}){let a=hk(),[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?Mk(e):null,[e]),x=(0,v.useMemo)(()=>e?Nk(e,{includeRawEvents:!1,rawEventsLimit:0,pageSize:50}):null,[e]),S=kk({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 Ib(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:Ak,gcTime:jk,refetchOnWindowFocus:!1,retry:1}),C=kk({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 Lb(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 Gk(r.timeline)},enabled:!!e,staleTime:Ak,gcTime:jk,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=>Pk(r.current,t,e)),_.current=null,y.current=new Set},[r,a,e,i,x]);let w=kk({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 Rb(e,{limit:c,beforeSequence:p,signal:t})},enabled:!!(e&&t),staleTime:Ak,gcTime:jk,refetchOnWindowFocus:!1,retry:1});(0,v.useEffect)(()=>{let t=C.data;!t||t.piboSessionId!==e||($v()&&cy(t.piboSessionId,{overlayEventCount:0,traceBaseOutputLength:MO(t),traceBaseUpdated:!0}),(0,v.startTransition)(()=>{d(e=>{let n=e?.piboSessionId===t.piboSessionId?Uk(e,t):t;return f.current.set(t.piboSessionId,n),n}),i(e=>Fk(r.current,e,t))}))},[r,e,i,C.data]),(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=Nk(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 Lb(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 Gk(o.timeline)},staleTime:Ak,gcTime:jk});(0,v.startTransition)(()=>{d(e=>e?Hk(e,t):t),s(e=>e+(t.pageSize??50))}),Xk(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 Xk(e,t){if(e.add(t),e.size<=Jk)return;let n=e.values().next();n.done||e.delete(n.value)}function Zk(e){let t=e.currentEvents,n,r,i=()=>(r??=new Set(t.map(rA)),r),a=e=>{n??=t.slice(),n.push(e),t=n};for(let o of e.streamEvents){let s=eA(o,e.piboSessionId,e.nextSequence,e.now??(()=>new Date().toISOString()));if(!s)continue;if(Qk(s)){t=$k(t,s),n=t,r=void 0;continue}let c=rA(s),l=i();l.has(c)||(l.add(c),a(s))}return t}function Qk(e){return e.type===`assistant_message`||e.type===`thinking_finished`||e.type===`tool_execution_finished`}function $k(e,t){return t.type===`assistant_message`?[...nA(e,t,`assistant_delta`),t]:t.type===`thinking_finished`?[...nA(e,t,`thinking_delta`),t]:t.type===`tool_execution_finished`?[...nA(e,t,`tool_execution_updated`),t]:e}function eA(e,t,n,r){if(e.type===`RAW_EVENT`&&oA(e.event)&&typeof e.event.type==`string`){let i=e.event;return tA(e,t,e.event.type,i,n,r)}if(e.type===`TEXT_MESSAGE_CONTENT`&&typeof e.delta==`string`)return tA(e,t,`assistant_delta`,{type:`assistant_delta`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,...aA(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 tA(e,t,`thinking_delta`,{type:`thinking_delta`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,...aA(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 tA(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 tA(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 tA(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 tA(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 tA(e,t,n,r,i,a){let o=typeof e.streamFrameId==`string`?e.streamFrameId:void 0,s=typeof e.streamFrameIndex==`number`?e.streamFrameIndex:void 0,c=typeof e.liveReplayId==`number`&&Number.isFinite(e.liveReplayId)?e.liveReplayId:void 0,l=i();return{id:typeof e.streamId==`number`?`stream:${e.streamId}:${s??`raw`}:${n}`:c===void 0?o?`stream:${o}:${n}`:`live:${l}:${n}`:`live-replay:${c}:${n}`,piboSessionId:t,eventSequence:l,streamId:typeof e.streamId==`number`?e.streamId:void 0,streamFrameIndex:s,eventId:typeof r.eventId==`string`?r.eventId:void 0,type:n,createdAt:a(),payload:r}}function nA(e,t,n){let r=iA(t);return e.filter(e=>e.type!==n||iA(e)!==r)}function rA(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 iA(e){let t=oA(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 aA(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 oA(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function sA(e){try{let t=JSON.parse(e.data);if(typeof t.type!=`string`)return;let n=e.lastEventId?iS(e.lastEventId):void 0;return{...t,...e.lastEventId?{streamFrameId:e.lastEventId}:{},...n?{streamId:n.streamId,streamFrameIndex:n.frameIndex}:{}}}catch{return}}function cA(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:uA(n),exact:!1,...r?.liveReplayId===void 0?{}:{liveReplayId:r.liveReplayId}})}function lA(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 uA(e){return`${e}:999999`}function dA(e){if(e.type===`RUN_FINISHED`||e.type===`TEXT_MESSAGE_END`)return 300;if(e.type===`RUN_ERROR`)return 0}function fA(e){return e.type===`RUN_STARTED`||e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`||e.type===`TEXT_MESSAGE_END`}function pA(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 mA(e,t,n){if(n.type===`RUN_STARTED`||n.type===`RUN_FINISHED`||n.type===`RUN_ERROR`){e.delete(t);return}let r=_A(n);r&&e.get(t)?.delete(r)}function hA(e,t,n){let r=gA(n);if(!r)return!1;let i=e.get(t);return i||(i=new Set,e.set(t,i)),i.has(r)?!1:(i.add(r),!0)}function gA(e){if(e.type===`TEXT_MESSAGE_CONTENT`||e.type===`REASONING_MESSAGE_CONTENT`)return`${e.type}:${e.messageId}`}function _A(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 vA=500,yA=1e4,bA=45e3,xA=15e3,SA=100;function CA({selectedPiboSessionId:e,tracePageData:t,currentTraceView:n,liveEventSeqRef:r,selectedSessionStatus:i,tracePageReady:a,setLiveTraceOverlay:o,onRefreshTrace:s,onRefreshBootstrap:c,onError:l}){let u=(0,v.useRef)(new Map),d=(0,v.useRef)(void 0),f=(0,v.useRef)(void 0),p=(0,v.useRef)(new Map),m=(0,v.useRef)(new Map),h=(0,v.useRef)(null),g=(0,v.useRef)(void 0),_=(0,v.useRef)(0),[y,b]=(0,v.useState)(0);(0,v.useEffect)(()=>{let n=t;if(!n||n.piboSessionId!==e)return;let i=n.rawEvents.map(e=>e.eventSequence??0).reduce((e,t)=>Math.max(e,t),0);r.current=Math.max(r.current,i+1),n.latestStreamId!==void 0&&cA(m.current,n.piboSessionId,n.latestStreamId)},[r,e,t]);let x=(0,v.useCallback)(e=>{let t=u.current.get(e);t?.length&&(o(n=>{let i=Zk({currentEvents:n?.piboSessionId===e?n.events:[],streamEvents:t,piboSessionId:e,nextSequence:()=>r.current++});return iy(e,t.length,i.length),{piboSessionId:e,events:i}}),u.current.delete(e))},[]),S=(0,v.useCallback)(()=>{if(!(d.current!==void 0||f.current!==void 0||!e)){if(document.hidden){f.current=setTimeout(()=>{f.current=void 0,x(e)},SA);return}d.current=requestAnimationFrame(()=>{d.current=void 0,x(e)})}},[x,e]),C=(0,v.useCallback)((t,n,r=!1)=>{mA(p.current,t,n);let i=r||hA(p.current,t,n),a=u.current.get(t)??[];a.push(n),u.current.set(t,a),ry(t,n,a.length,i),i||t!==e?x(t):S()},[x,S,e]);(0,v.useEffect)(()=>()=>{d.current!==void 0&&cancelAnimationFrame(d.current),f.current!==void 0&&clearTimeout(f.current),g.current!==void 0&&clearTimeout(g.current)},[]);let w=(0,v.useCallback)((e,t)=>{lA(m.current,e,t)},[]),T=(0,v.useCallback)((e=0)=>{if(g.current!==void 0){if(e>0)return;clearTimeout(g.current)}g.current=setTimeout(()=>{g.current=void 0,b(e=>e+1)},e)},[]),E=(0,v.useCallback)(()=>{if(!e)return;x(e),s().catch(e=>l(wA(e))),c().catch(e=>l(wA(e)));let t=h.current;(!t||t.piboSessionId!==e||t.events.readyState===2||Date.now()-t.lastActivityAt>bA)&&T()},[x,l,c,s,T,e]);(0,v.useEffect)(()=>{if(!e||!a||!n||n.piboSessionId!==e)return;let t=new URLSearchParams({piboSessionId:e});t.set(`mode`,`live`);let r=m.current.get(e),i=r?.cursor??(n.latestStreamId===void 0?void 0:uA(n.latestStreamId));i!==void 0&&t.set(`since`,i),r?.liveReplayId!==void 0&&t.set(`liveSince`,String(r.liveReplayId));let o=new EventSource(`/api/chat/events?${t.toString()}`),u=Date.now();h.current={piboSessionId:e,events:o,openedAt:u,lastActivityAt:u};let d=!1,f,p,v=!1,y=!1,b=(t,n=!1)=>{if(f){if(!n)return;clearTimeout(f)}sy(e,t),f=setTimeout(()=>{f=void 0,s().catch(e=>l(wA(e)))},t)},S=()=>{if(v){y=!0;return}v=!0,c().catch(e=>l(wA(e))).finally(()=>{v=!1,y&&(y=!1,E(250,!0))})},E=(e,t=!1)=>{if(p){if(!t)return;clearTimeout(p)}p=setTimeout(()=>{p=void 0,S()},e)},D=()=>{E(900,!0)};return o.onopen=()=>{_.current=0,g.current!==void 0&&(clearTimeout(g.current),g.current=void 0),ey(e,o.readyState);let t=h.current;t?.events===o&&(t.lastActivityAt=Date.now())},o.onerror=()=>{if(d)return;ty(e,o.readyState);let t=h.current;t?.events===o&&(t.lastErrorAt=Date.now());let n=_.current++;T(Math.min(yA,vA*2**n))},o.addEventListener(`pibo`,t=>{if(d)return;let n=sA(t);if(!n)return;let r=n.piboSessionId||e,i=h.current;if(i?.events===o&&(i.lastActivityAt=Date.now()),w(r,n),ny(r,n,t.lastEventId,o.readyState),r===e&&n.type===`ready`&&n.liveReplay?.missed&&b(0,!0),ly(n))return;let a=n.type!==`TEXT_MESSAGE_CONTENT`&&n.type!==`REASONING_MESSAGE_CONTENT`;r===e&&pA(n)&&C(r,n,a);let s=dA(n);r===e&&s!==void 0?b(s,!0):r===e&&n.type!==`ready`&&n.type!==`RAW_EVENT`&&b(1500,!0),fA(n)&&(n.type===`RUN_FINISHED`||n.type===`RUN_ERROR`||n.type===`TEXT_MESSAGE_END`?D():E(r===e?0:150))}),()=>{d=!0,f&&clearTimeout(f),p&&clearTimeout(p),x(e),h.current?.events===o&&(h.current=null),o.close()}},[n?.piboSessionId,C,x,l,c,s,w,T,y,e,a]),(0,v.useEffect)(()=>{n?.piboSessionId&&x(n.piboSessionId)},[n?.piboSessionId,x]),(0,v.useEffect)(()=>{let e=()=>E(),t=()=>{document.hidden||E()};return window.addEventListener(`focus`,e),window.addEventListener(`online`,e),window.addEventListener(`pageshow`,e),document.addEventListener(`visibilitychange`,t),()=>{window.removeEventListener(`focus`,e),window.removeEventListener(`online`,e),window.removeEventListener(`pageshow`,e),document.removeEventListener(`visibilitychange`,t)}},[E]),(0,v.useEffect)(()=>{if(!e||i!==`running`)return;let t=window.setInterval(()=>{x(e);let t=h.current;(!t||t.piboSessionId!==e||t.events.readyState===2||Date.now()-t.lastActivityAt>bA)&&(s().catch(e=>l(wA(e))),T())},xA);return()=>window.clearInterval(t)},[x,l,s,T,e,i])}function wA(e){return e instanceof Error?e.message:String(e)}var TA=10;function EA(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,TA)}:e}function DA(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 OA(e,t){return!t||!e[t]?.length?e:{...e,[t]:[]}}function kA(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=>EA(r,e,n,t))},[t,e]),detachUploadAttachment:(0,v.useCallback)(t=>{r(n=>DA(n,e,t))},[e]),clearSelectedUploadAttachments:(0,v.useCallback)(()=>{r(t=>OA(t,e))},[e])}}function AA({selectedPiboSessionId:e,onError:t,formatError:n}){let[r,i]=(0,v.useState)([]),[a,o]=(0,v.useState)(!1),[s,c]=(0,v.useState)(()=>e?jD(e):null),[l,u]=(0,v.useState)(()=>RD()),[d,f]=(0,v.useState)(!1),p=!!(e&&s?.piboSessionId===e&&s.installed),m=!!e&&(a||p),h=kk({queryKey:[`web-annotations`,`app`,e],queryFn:async()=>{if(!e)throw Error(`Session is required`);return fx(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?FD(e):[]),c(e?jD(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(PD(e.detail)),r=n=>{n.key===MD(e)&&t(ND(n.newValue))},i=()=>t(jD(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&&ID(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&&ID(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&&ID(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 zD(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=>px(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 jA=new WeakMap;function MA(e,t,n){let r=n.map(e=>NA(e)),i=zA(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 NA(e){let t=jA.get(e);if(t)return t;let n=RA(e.startedAt)??Date.now()*1e3,r=RA(e.completedAt),i=LA(e.status),a=PA(e.type),o={id:e.id,parentId:e.parentId,name:FA(e),spanType:a,startTime:n,endTime:r,durationUs:e.durationMs===void 0?void 0:e.durationMs*1e3,attributes:IA(e),status:i,statusMessage:e.error,events:e.error?[{name:`exception`,timestamp:r??n,attributes:{message:e.error}}]:[],children:e.children?.map(NA),pibo:{entryId:e.entryId,linkedPiboSessionId:e.linkedPiboSessionId,traceNodeType:e.type,traceOrder:e.orderKey,stableKey:e.stableKey,source:e.source}};return jA.set(e,o),o}function PA(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 FA(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 IA(e){let t={};return 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??``),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`]=BA(e.input)?e.input.startedBy:`pibo_run_start`,t[`async_agent.query`]=BA(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 LA(e){return e===`running`?`UNSET`:e===`error`?`ERROR`:`OK`}function RA(e){if(!e)return;let t=new Date(e).getTime();return Number.isFinite(t)?t*1e3:void 0}function zA(e){return e.flatMap(e=>[e,...e.children?zA(e.children):[]])}function BA(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function VA(e){return(e.selectedPiboSessionId?S(e.sessionNodes,e.selectedPiboSessionId):void 0)?.title||e.traceTitle||e.selectedPiboSessionId||e.fallback}function HA(e,t){return t?{sessionBreadcrumbs:qA(e,t),originSession:GA(e,t),derivedSessions:KA(e,t)}:{sessionBreadcrumbs:[],originSession:void 0,derivedSessions:[]}}function UA(e){let t=e.selectedPiboSessionId?S(e.bootstrap.sessions,e.selectedPiboSessionId):void 0,n=ZA(e.currentTraceView);return XA(e.selectedSessionActiveModel,e.bootstrap.runtimeStatus?.thinkingLevel??n.level??JA(e.bootstrap,e.selectedSessionProfile,!!t?.parentId),e.bootstrap.runtimeStatus?.fastMode??n.fast??YA(e.bootstrap,e.selectedSessionProfile,!!t?.parentId)??!1)}function WA(e){return{traceView:e.currentTraceView,selectedTrace:e.currentTraceView?MA(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,selectedSessionStatus:e.selectedSessionStatus,selectedSessionSignal:e.selectedSessionSignal,signals:e.signals,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 GA(e,t){let n=S(e,t);if(!n?.originId)return;let r=S(e,n.originId);return{piboSessionId:n.originId,label:r?ej(r,0):n.originId}}function KA(e,t){return S(e,t)?.derivedSessions.map(e=>({piboSessionId:e.piboSessionId,label:tj(e),profile:e.profile,status:e.status}))??[]}function qA(e,t){return C(e,t).map((e,t)=>({piboSessionId:e.piboSessionId,label:ej(e,t)}))}function JA(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 YA(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 XA(e,t,n){if(e)return[e,t,n?`fast`:void 0].filter(Boolean).join(` `)}function ZA(e){let t={};if(!e)return t;for(let n of QA(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`&&$A(e.level)?e.level:void 0)??t.level,fast:n.title===`fast_mode`?e?.mode===`fast`:t.fast}}return t}function QA(e){return e.flatMap(e=>[e,...QA(e.children)])}function $A(e){return rT.includes(e)}function ej(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 tj(e){return e.subagentName&&e.subagentName!==e.profile?`${e.subagentName} (${e.profile})`:e.title||e.profile||e.subagentName||`Untitled Session`}function nj({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 rj(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 ij(e,t,n){return{piboSessionId:t,events:[...e?.piboSessionId===t?e.events:[],n]}}function aj(e){return e instanceof Error?e.message:String(e)}function oj({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,showRawEvents:T,showThinking:E,expandThinking:D,commands:O,skills:k,composerText:ee,composerFocusSignal:A,onComposerTextChange:te,onToggleRawEvents:ne,onToggleThinking:re,onToggleExpandThinking:ie,onSessionAgentProfileChange:j,onFork:M,onOpenSession:ae,onSelectSessionView:oe,onCommand:se,onThinkingLevelChange:ce,onRefreshTrace:N,onRefreshBootstrap:le,onSend:ue,onError:de}){let P=(0,v.useRef)(0),fe=(0,v.useRef)(new Map),[pe,me]=(0,v.useState)(null),he=(0,v.useCallback)(e=>{me(t=>{let n=typeof e==`function`?e(t):e;return n&&fe.current.set(n.piboSessionId,n),n})},[]),[ge,_e]=(0,v.useState)(null),[ve,ye]=(0,v.useState)(!1),be=(0,v.useRef)(null),{baseTraceView:F,liveTraceOverlay:xe,rawEventLimit:Se,traceSummaryQuery:Ce,tracePageQuery:we,rawEventsQuery:Te,loadingOlderTracePage:Ee,tracePageReady:De,loadOlderTracePage:Oe,loadMoreRawEvents:ke}=Yk({selectedPiboSessionId:t,showRawEvents:T,liveTraceOverlay:pe,liveTraceOverlayCacheRef:fe,setLiveTraceOverlay:he}),{selectedWebAnnotationIds:Ae,selectedWebAnnotations:je,visibleWebAnnotations:Me,webAnnotationsPanelCollapsed:Ne,webAnnotationsPanelRendered:Pe,webAnnotationsPanelVisible:Fe,webAnnotationsQuery:Ie,clearingWebAnnotations:Le,setWebAnnotationsPanelVisible:Re,toggleWebAnnotationAttachment:ze,detachWebAnnotationAttachment:Be,clearSelectedWebAnnotationAttachments:Ve,toggleWebAnnotationsPanelCollapsed:He,clearVisibleWebAnnotations:Ue}=AA({selectedPiboSessionId:t,onError:de,formatError:KD}),{selectedUploadAttachments:We,attachUploadedFiles:Ge,detachUploadAttachment:Ke,clearSelectedUploadAttachments:qe}=kA(t,(0,v.useCallback)(()=>`upload-${w()}`,[])),Je=NO({selectedPiboSessionId:t,baseTraceView:F,liveTraceOverlay:xe,selectedSessionStatus:c});CA({selectedPiboSessionId:t,tracePageData:we.data,currentTraceView:Je,liveEventSeqRef:P,selectedSessionStatus:c,tracePageReady:De,setLiveTraceOverlay:he,onRefreshTrace:N,onRefreshBootstrap:le,onError:de});let Ye=UA({bootstrap:e,selectedPiboSessionId:t,selectedSessionProfile:o,selectedSessionActiveModel:s,currentTraceView:Je}),Xe=(0,v.useMemo)(()=>HA(e.sessions,t),[e.sessions,t]),Ze=!!t&&we.isFetching&&!Je,Qe=we.error?aj(we.error):Ce.error?aj(Ce.error):null,$e=Je?.piboSessionId??t??``,et=d&&eO(d)?tO(d,c):null,tt=e=>{for(let n of[750,2e3,5e3,1e4])window.setTimeout(()=>{t===e&&we.refetch().catch(e=>de(aj(e)))},n)},nt=async(e,t)=>{let n=rj(e,t);he(e=>ij(e,n.piboSessionId,n.optimisticEvent)),await ue(n.text,n.webAnnotationIds,n.fileAttachmentPaths,n.clientTxnId,t),Ve(),qe(),await Promise.all([we.refetch(),Ie.refetch()]),tt(n.piboSessionId)},rt=(e,t)=>{he(t=>{let n=t?.piboSessionId===e.piboSessionId?t:fe.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?fe.current.set(e.piboSessionId,i):fe.current.delete(e.piboSessionId),t?.piboSessionId===e.piboSessionId?i:t}),te(t=>t||e.text),de(aj(t))},it=async e=>{if(!t)return;let n=nj({piboSessionId:t,text:e,selectedWebAnnotations:je,selectedUploadAttachments:We,eventSequence:P.current++,now:new Date().toISOString(),clientTxnId:w()});if(c===`running`){_e(n);return}try{await nt(n,`queue`)}catch(e){rt(n,e)}},at=()=>{!ge||ve||(te(e=>e||ge.text),_e(null))},ot=async e=>{if(!ge||ve)return;let t=ge;_e(null),ye(!0);try{await nt(t,e),de(null)}catch(e){rt(t,e)}finally{ye(!1)}},st=WA({currentTraceView:Je,isLoading:Ze,showThinking:E,expandThinking:D,selectedSessionProfile:o,sessionActiveModelBadge:Ye,selectedSessionStatus:c,selectedSessionSignal:l,signals:u,workflowProjectSession:d,workflowLifecycleEvents:f,sessionNodes:e.sessions,sessionLinks:Xe,agentProfiles:e.agents,sessionProfileChangeDisabled:C||r,onSessionAgentProfileChange:j,onFork:M,onOpenSession:ae,onLoadOlderTracePage:()=>void Oe(Je?.nextBeforeCursor??Je?.nextBeforeSequence),hasOlderTraceEvents:Je?.hasOlderEvents===!0||Je?.nextBeforeCursor!==void 0||typeof Je?.nextBeforeSequence==`number`,isFetchingOlderTracePage:Ee,onThinkingLevelChange:ce,onRefreshTrace:N,onRefreshBootstrap:le,onError:de});return(0,I.jsxs)(I.Fragment,{children:[ge?(0,I.jsx)(vO,{title:`Session is running`,description:`Choose how this message should be delivered.`,onClose:at,initialFocusRef:be,closeDisabled:ve,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:be,type:`button`,disabled:ve,onClick:()=>void ot(`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`,disabled:ve,onClick:()=>void ot(`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)(mO,{selectedPiboSessionId:t,selectedRoomId:n,fallbackRoomId:e.selectedRoomId??void 0,sessionViewId:y,loadingTrace:Ze,roomNavigationPending:i,sessionNavigationPending:a,traceError:Qe,showRawEvents:T,currentTraceView:Je,rawEventLimit:Se,tracePageFetching:T?Te.isFetching:we.isFetching,onLoadMoreRawEvents:ke,headerProps:{title:VA({sessionNodes:e.sessions,selectedPiboSessionId:t,traceTitle:Je?.title,fallback:e.room?.name??n??void 0}),roomLabel:e.room?.name??n??`Room`,headerPiboSessionId:$e,piboSessionId:t,piboRoomId:n??e.selectedRoomId??void 0,webAnnotationsDisabled:!t||r,webAnnotationsPanelRendered:Pe,workflowHeader:et,sessionViewId:y,sessionViews:b,currentSessionView:x,allowedSessionViewIds:S,extraViewTabs:g,activeViewId:_,showRawEvents:T,showThinking:E,expandThinking:D,onShowWebAnnotationsPanel:()=>Re(!0),onHideWebAnnotationsPanel:()=>Re(!1),onSelectSessionView:oe,onToggleRawEvents:ne,onToggleThinking:re,onToggleExpandThinking:ie,onError:de},projectSessionCreatePanel:p,workflowStartPanel:m,projectModulePanel:h,currentSessionView:x,sessionViewProps:st,webAnnotationsPanelRendered:Pe,webAnnotationsPanelProps:{piboSessionId:t,annotations:Me,selectedIds:Ae,loading:Ie.isLoading||Ie.isFetching||Le,error:Ie.error?aj(Ie.error):null,collapsed:Ne,onRefresh:()=>void Ie.refetch(),onToggle:ze,onClear:()=>void Ue(),onCollapse:He,onClose:()=>Re(!1)},composerProps:{sessionId:t,disabled:!t||r,commands:O,skills:k,value:ee,focusSignal:A,selectedWebAnnotations:je,selectedUploadAttachments:We,onValueChange:te,onCommand:se,onDetachWebAnnotation:Be,onClearWebAnnotations:Ve,onAttachUploadedFiles:Ge,onDetachUploadAttachment:Ke,onClearUploadAttachments:qe,onSend:it}})]})}function sj({mode:e,onSelectSession:t,onNewSession:n,onDeleteSession:r,onRenameSession:i,onSelectRoom:a}){return e.kind===`rooms`?(0,I.jsx)(mj,{candidates:e.candidates,workspace:e.workspace,onSelectRoom:a}):(0,I.jsx)(fj,{sessions:e.sessions,selectedPiboSessionId:e.selectedPiboSessionId,onSelectSession:t,onNewSession:n,onDeleteSession:r,onRenameSession:i})}function cj(e){return e===`running`?`running`:e===`error`?`error`:e===`completed`?`completed`:`idle`}var lj={running:`bg-cyan-400`,idle:`bg-slate-500`,error:`bg-rose-500`,completed:`bg-emerald-500`},uj={running:`running`,idle:`idle`,error:`error`,completed:`completed`};function dj({status:e}){let t=cj(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 ${lj[t]}`,"aria-hidden":`true`}),uj[t]]})}function fj({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=>(0,I.jsx)(`li`,{className:`shrink-0`,children:(0,I.jsx)(pj,{session:e,isActive:e.piboSessionId===t,onSelect:()=>n(e.piboSessionId),onDelete:()=>void i(e.piboSessionId),onRename:t=>void a(e.piboSessionId,t)})},e.piboSessionId)),o.length===0&&(0,I.jsx)(`li`,{className:`text-xs text-slate-500 px-2 py-1`,children:`No sessions yet — click + to start one.`})]})]})}function pj({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)(dj,{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 mj({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 `,hj(e.createdAt),` · Updated `,hj(e.updatedAt)]})]})},e.id))})]})}function hj(e){try{return new Date(e).toLocaleString()}catch{return e}}function gj(){return new URLSearchParams(window.location.search).get(`workspace`)}function _j(){return new URLSearchParams(window.location.search).get(`roomId`)}function vj(){let e=(0,v.useMemo)(()=>gj(),[]),[t,n]=(0,v.useState)(()=>_j()),[r,i]=(0,v.useState)(()=>_j()?{kind:`sessions`,roomId:_j(),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(aj(t))}})(),()=>{e=!0}},[t]);let y=(0,v.useCallback)(async()=>{if(t)try{o(await ee(s??void 0,!1,t,!0))}catch(e){m(aj(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?D(a.capabilities.actions):[],[a]),C=(0,v.useMemo)(()=>O(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)},[]),k=(0,v.useCallback)(async e=>{if(t)try{let n=await A(e,t);await y(),n.session?.id&&c(n.session.id)}catch(e){m(aj(e))}},[t,y]),j=(0,v.useCallback)(async e=>{try{await ne(e,`delete`),await y(),s===e&&c(null)}catch(e){m(aj(e))}},[y,s]),M=(0,v.useCallback)(async(e,t)=>{try{await te(e,{title:t}),await y()}catch(e){m(aj(e))}},[y]),ae=(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()}`)},[]),ce=(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(aj(e))}},[s,t,y]),N=(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=oe(n.slice(r.length));if(!e)return m(`Usage: /download <path>`),!0;try{await le(e,{piboSessionId:s,roomId:t??void 0})}catch(e){m(aj(e))}return!0}try{let e=se(i.action,n.slice(r.length).trim());await ie(s,i.action,e),await y()}catch(e){m(aj(e))}return!0},[S,s,t,y]),ue=(0,v.useMemo)(()=>nD(),[]),de=(0,v.useMemo)(()=>rD(pe),[]);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)(sj,{mode:r,onSelectSession:E,onNewSession:k,onDeleteSession:j,onRenameSession:M,onSelectRoom:ae}),(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`)return(0,I.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,I.jsx)(sj,{mode:{kind:`rooms`,candidates:a.rooms??r.candidates,workspace:r.workspace},onSelectSession:E,onNewSession:k,onDeleteSession:j,onRenameSession:M,onSelectRoom:ae}),(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 P=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)(sj,{mode:{kind:`sessions`,roomId:t??``,sessions:T,selectedPiboSessionId:s},onSelectSession:E,onNewSession:k,onDeleteSession:j,onRenameSession:M,onSelectRoom:ae}),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)(oj,{bootstrap:a,selectedPiboSessionId:s,selectedRoomId:t,selectedRoomArchived:!1,selectedSessionProfile:P?.profile??`default`,selectedSessionActiveModel:P?x(a,P)??void 0:void 0,selectedSessionStatus:P?.status,sessionViewId:pe,sessionViews:ue,currentSessionView:de,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:N,onThinkingLevelChange:e=>void N(`/thinking ${e}`),onRefreshTrace:b,onRefreshBootstrap:y,onSend:ce,onError:m})})]})}var yj=document.getElementById(`root`);yj&&(0,y.createRoot)(yj).render((0,I.jsx)(v.StrictMode,{children:(0,I.jsx)(vj,{})}));