@pasko70/pibo 1.14.0 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/apps/chat-ui/assets/{dist-DmqwP_tM.js → dist-BFwSuVfD.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-ur4yXrlj.js → dist-BYTi90un.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-hoDORUlL.js → dist-Bi74WdBU.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-BIwXuAMQ.js → dist-CYMM1_bS.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-BG1J2hGI.js → dist-CuIwfDgF.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-LWXXqiGT.js → dist-DS1ScAMf.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-1eQpSfYj.js → dist-DUgrMhHX.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-CtsdsIpj.js → dist-Dq3i1LVZ.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-DfdQQObC.js → dist-Dy5L1xOD.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-BeCHnL7P.js → dist-Zy3KnDp7.js} +1 -1
- package/dist/apps/chat-ui/assets/index-BZO4zpMi.js +237 -0
- package/dist/apps/chat-ui/index.html +1 -1
- package/dist/apps/chat-vscode-web/assets/{index-R_7kgvvD.js → index-V_pKPVAm.js} +3 -3
- package/dist/apps/chat-vscode-web/index.html +1 -1
- package/dist/apps/vscode-artifacts/latest.vsix +0 -0
- package/dist/apps/vscode-artifacts/{pibo-vscode-ext-1.14.0.vsix → pibo-vscode-ext-1.15.0.vsix} +0 -0
- package/dist/core/runtime.js +27 -5
- package/dist/plugins/builtin.js +7 -0
- package/dist/session-ui/terminalRows.js +12 -2
- package/dist/tools/browser-use-leases.js +16 -0
- package/dist/tools/codex-browser-node-repl.js +224 -0
- package/dist/tools/codex-browser-node-worker-source.js +403 -0
- package/dist/tools/codex-browser.js +461 -0
- package/package.json +3 -1
- package/dist/apps/chat-ui/assets/index-DLNTzhdh.js +0 -237
|
@@ -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 Yg(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=K_.inlineCode(e,t,n);return n.stack.includes(`tableCell`)&&(r=r.replace(/\|/g,`\\$&`)),r}}function nv(){return{exit:{taskListCheckValueChecked:iv,taskListCheckValueUnchecked:iv,paragraph:av}}}function rv(){return{unsafe:[{atBreak:!0,character:`-`,after:`[:|-]`}],handlers:{listItem:ov}}}function iv(e){let t=this.stack[this.stack.length-2];t.type,t.checked=e.type===`taskListCheckValueChecked`}function av(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 ov(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=K_.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 sv(){return[pg(),Lg(),Hg(),q_(),nv()]}function cv(e){return{extensions:[mg(),Rg(e),Ug(),tv(e),rv()]}}var lv={tokenize:Cv,partial:!0},uv={tokenize:wv,partial:!0},dv={tokenize:Tv,partial:!0},fv={tokenize:Ev,partial:!0},pv={tokenize:Dv,partial:!0},mv={name:`wwwAutolink`,tokenize:xv,previous:Ov},hv={name:`protocolAutolink`,tokenize:Sv,previous:kv},gv={name:`emailAutolink`,tokenize:bv,previous:Av},_v={};function vv(){return{text:_v}}for(var yv=48;yv<123;)_v[yv]=gv,yv++,yv===58?yv=65:yv===91&&(yv=97);_v[43]=gv,_v[45]=gv,_v[46]=gv,_v[95]=gv,_v[72]=[gv,hv],_v[104]=[gv,hv],_v[87]=[gv,mv],_v[119]=[gv,mv];function bv(e,t,n){let r=this,i,a;return o;function o(t){return!jv(t)||!Av.call(r,r.previous)||Mv(r.events)?n(t):(e.enter(`literalAutolink`),e.enter(`literalAutolinkEmail`),s(t))}function s(t){return jv(t)?(e.consume(t),s):t===64?(e.consume(t),c):n(t)}function c(t){return t===46?e.check(pv,u,l)(t):t===45||t===95||md(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&&pd(r.previous)?(e.exit(`literalAutolinkEmail`),e.exit(`literalAutolink`),t(o)):n(o)}}function xv(e,t,n){let r=this;return i;function i(t){return t!==87&&t!==119||!Ov.call(r,r.previous)||Mv(r.events)?n(t):(e.enter(`literalAutolink`),e.enter(`literalAutolinkWww`),e.check(lv,e.attempt(uv,e.attempt(dv,a),n),n)(t))}function a(n){return e.exit(`literalAutolinkWww`),e.exit(`literalAutolink`),t(n)}}function Sv(e,t,n){let r=this,i=``,a=!1;return o;function o(t){return(t===72||t===104)&&kv.call(r,r.previous)&&!Mv(r.events)?(e.enter(`literalAutolink`),e.enter(`literalAutolinkHttp`),i+=String.fromCodePoint(t),e.consume(t),s):n(t)}function s(t){if(pd(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||gd(t)||Q(t)||Sd(t)||xd(t)?n(t):e.attempt(uv,e.attempt(dv,u),n)(t)}function u(n){return e.exit(`literalAutolinkHttp`),e.exit(`literalAutolink`),t(n)}}function Cv(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 wv(e,t,n){let r,i,a;return o;function o(t){return t===46||t===95?e.check(fv,c,s)(t):t===null||Q(t)||Sd(t)||t!==45&&xd(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 Tv(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(fv,t,a)(o):o===null||Q(o)||Sd(o)?t(o):(e.consume(o),i)}function a(t){return t===41&&r++,e.consume(t),i}}function Ev(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||Q(o)||Sd(o)?t(o):n(o)}function i(e){return e===null||e===40||e===91||Q(e)||Sd(e)?t(e):r(e)}function a(e){return pd(e)?o(e):n(e)}function o(t){return t===59?(e.consume(t),r):pd(t)?(e.consume(t),o):n(t)}}function Dv(e,t,n){return r;function r(t){return e.consume(t),i}function i(e){return md(e)?n(e):t(e)}}function Ov(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Q(e)}function kv(e){return!pd(e)}function Av(e){return!(e===47||jv(e))}function jv(e){return e===43||e===45||e===46||e===95||md(e)}function Mv(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 Nv={tokenize:Vv,partial:!0};function Pv(){return{document:{91:{name:`gfmFootnoteDefinition`,tokenize:Rv,continuation:{tokenize:zv},exit:Bv}},text:{91:{name:`gfmFootnoteCall`,tokenize:Lv},93:{name:`gfmPotentialFootnoteCall`,add:`after`,tokenize:Fv,resolveTo:Iv}}}}function Fv(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=fd(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 Iv(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 Lv(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||Q(s))return n(s);if(s===93){e.exit(`chunkString`);let a=e.exit(`gfmFootnoteCallString`);return i.includes(fd(r.sliceSerialize(a)))?(e.enter(`gfmFootnoteCallLabelMarker`),e.consume(s),e.exit(`gfmFootnoteCallLabelMarker`),e.exit(`gfmFootnoteCall`),t):n(s)}return Q(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 Rv(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||Q(t))return n(t);if(t===93){e.exit(`chunkString`);let n=e.exit(`gfmFootnoteDefinitionLabelString`);return a=fd(r.sliceSerialize(n)),e.enter(`gfmFootnoteDefinitionLabelMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionLabelMarker`),e.exit(`gfmFootnoteDefinitionLabel`),f}return Q(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),Td(e,p,`gfmFootnoteDefinitionWhitespace`)):n(t)}function p(e){return t(e)}}function zv(e,t,n){return e.check(Bd,t,e.attempt(Nv,t,n))}function Bv(e){e.exit(`gfmFootnoteDefinition`)}function Vv(e,t,n){let r=this;return Td(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 Hv(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&&ad(o,o.length,0,Nd(s,e.slice(r+1,n),t)),ad(o,o.length,0,[[`exit`,a,t],[`enter`,e[n][1],t],[`exit`,e[n][1],t],[`exit`,i,t]]),ad(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=Md(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=Md(a);return l._open=!u||u===2&&!!s,l._close=!s||s===2&&!!u,n(a)}}}var Uv=class{constructor(){this.map=[]}add(e,t,n){Wv(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 Wv(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 Gv(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 Kv(){return{flow:{null:{name:`table`,tokenize:qv,resolveAll:Jv}}}}function qv(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):Z(t)?a>1?(a=0,r.interrupt=!0,e.exit(`tableRow`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),p):n(t):bd(t)?Td(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||Q(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,bd(t)?Td(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 bd(t)?Td(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||Z(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 bd(t)?Td(e,b,`whitespace`)(t):b(t)}function b(n){return n===124?m(n):n===null||Z(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||Z(n)?(e.exit(`tableRow`),t(n)):bd(n)?Td(e,C,`whitespace`)(n):(e.enter(`data`),w(n))}function w(t){return t===null||t===124||Q(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 Jv(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 Uv;for(;++n<e.length;){let p=e[n],m=p[1];p[0]===`enter`?m.type===`tableHead`?(s=!1,c!==0&&(Xv(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=Yv(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=Yv(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=Yv(f,t,o,i,n,d)):(o[0]=o[1],d=Yv(f,t,a,i,n,d)),i=0):i&&(m.type===`data`||m.type===`tableDelimiterMarker`||m.type===`tableDelimiterFiller`)&&(o[3]=n)}for(c!==0&&Xv(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=Gv(t.events,n))}return e}function Yv(e,t,n,r,i,a){let o=r===1?`tableHeader`:r===2?`tableDelimiter`:`tableData`;n[0]!==0&&(a.end=Object.assign({},Zv(t.events,n[0])),e.add(n[0],0,[[`exit`,a,t]]));let s=Zv(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=Zv(t.events,n[2]),a=Zv(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({},Zv(t.events,i)),e.add(i,0,[[`exit`,a,t]]),a=void 0),a}function Xv(e,t,n,r,i){let a=[],o=Zv(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 Zv(e,t){let n=e[t],r=n[0]===`enter`?`start`:`end`;return n[1][r]}var Qv={name:`tasklistCheck`,tokenize:ey};function $v(){return{text:{91:Qv}}}function ey(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 Q(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 Z(r)?t(r):bd(r)?e.check({tokenize:ty},t,n)(r):n(r)}}function ty(e,t,n){return Td(e,r,`whitespace`);function r(e){return e===null?n(e):t(e)}}function ny(e){return cd([vv(),Pv(),Hv(e),Kv(),$v()])}var ry={};function iy(e){let t=this,n=e||ry,r=t.data(),i=r.micromarkExtensions||=[],a=r.fromMarkdownExtensions||=[],o=r.toMarkdownExtensions||=[];i.push(ny(n)),a.push(sv()),o.push(cv(n))}var ay=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,`&`).replace(/</g,`<`).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,`"`)+`"`;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 A=S;A!==t.tail&&(k<O||typeof A.value==`string`);A=A.next)T++,k+=A.value.length;T--,w=e.slice(C,k),E.index-=C}else if(E=o(x,0,w,_),!E)continue;var D=E.index,ee=E[0],te=w.slice(0,D),j=w.slice(D+ee.length),M=C+w.length;d&&M>d.reach&&(d.reach=M);var ne=S.prev;te&&(ne=l(t,ne,te),C+=te.length),u(t,ne,T);var N=new a(f,g?i.tokenize(ee,g):ee,y,ee);if(S=l(t,ne,N),j&&l(t,S,j),T>1){var P={cause:f+`,`+m,reach:M};s(e,t,n,S.prev,C,P),d&&P.reach>d.reach&&(d.reach=P.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(/&/,`&`))}),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 oy(e){return typeof e==`object`&&!!e&&`languages`in e}var sy=globalThis,cy=oy(sy.Prism)?sy.Prism:ay.default;sy.Prism=cy,typeof window<`u`&&(window.Prism=cy);var ly;function uy(){if(ly!==void 0)return ly;let e=Ey();if(!e)return ly=!1,ly;try{let t=new URL(e.location.href).searchParams.get(`debugStreaming`);ly=t===null?e.localStorage.getItem(`pibo.chat.debugStreaming`)===`1`:t!==`0`&&t!==`false`}catch{ly=!1}return ly}function dy(e,t){Sy(e,e=>{e.liveOpenCount+=1,e.lastReadyState=t})}function fy(e,t){Sy(e,e=>{e.liveErrorCount+=1,e.lastReadyState=t})}function py(e,t,n,r){Sy(e,e=>{let i=Oy();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=xy(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+=Dy(t.delta)):t.type===`REASONING_MESSAGE_CONTENT`&&typeof t.delta==`string`&&(e.firstReasoningDeltaAt??=i,e.reasoningDeltaCount+=1,e.reasoningDeltaBytes+=Dy(t.delta))})}function my(e,t,n,r){Sy(e,e=>{if(e.firstEnqueueAt??=Oy(),e.enqueueCount+=1,r&&(e.enqueueFlushImmediateCount+=1),e.pendingEventCount=n,t.streamFrameId){let n=xy(t.streamFrameId);n===`durable`?e.lastDurableCursor=t.streamFrameId:n===`transient`&&(e.lastTransientLiveId=t.streamFrameId)}})}function hy(e,t,n){Sy(e,e=>{let r=Oy();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 gy(e,t){Sy(e,e=>{let n=ky(t);e.liveTraceComputeCount+=1,e.liveTraceComputeDurationMsLast=n,e.liveTraceComputeDurationMsTotal+=n,e.liveTraceComputeDurationMsMax=Math.max(e.liveTraceComputeDurationMsMax??0,n)})}function _y(e,t){Cy(n=>{let r=ky(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 vy(e,t){Sy(e,e=>{e.traceRefreshScheduledCount+=1,e.lastTraceRefreshScheduledAt=Oy(),e.lastTraceRefreshDelayMs=t})}function yy(e,t){Sy(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 by(e){let t=Ey();if(!t?.__piboStreamingBenchmarkShouldDropOverlayEvent)return!1;try{return!!t.__piboStreamingBenchmarkShouldDropOverlayEvent(e)}catch{return!1}}function xy(e){return e?/^live:\d+$/.test(e)?`transient`:/^\d+:\d+$/.test(e)?`durable`:`other`:`missing`}function Sy(e,t){Cy(n=>{n.sessionIds.includes(e)||n.sessionIds.push(e),n.selectedPiboSessionId=e,t(n)})}function Cy(e){let t=wy();t&&(e(t),t.updatedAt=Oy())}function wy(){if(!uy())return;let e=Ey();if(e)return e.__piboStreamingDebugReset||=()=>(e.__piboStreamingDebug=Ty(),e.__piboStreamingDebug),e.__piboStreamingDebug??=Ty(),e.__piboStreamingDebug}function Ty(){let e=Oy();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 Ey(){return typeof window>`u`?void 0:window}function Dy(e){return typeof TextEncoder<`u`?new TextEncoder().encode(e).byteLength:e.length}function Oy(){return new Date().toISOString()}function ky(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 Ay=[`p`,`br`,`strong`,`em`,`a`,`ul`,`ol`,`li`,`blockquote`,`code`,`pre`,`h1`,`h2`,`h3`,`h4`,`hr`,`table`,`thead`,`tbody`,`tr`,`th`,`td`,`input`,`del`],jy=[iy],My=[],Ny=/[\n\r\\`*_\[\]<>]|~~/,Py=/^\s*(?:#{1,6}\s|[-+>]|(?:\d+[.)]))\s/,Fy=/^\s*-{3,}\s*$/,Iy=/\b(?:https?:\/\/|www\.)|\S+@\S+\.\S+/i,Ly=/^\s*[-+*]\s+\[[ xX]\]\s/m,Ry=/(^|\n)\s*\|?.+\|.+\n\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*(?:\n|$)/;function zy(e){return e.length>0&&!Ny.test(e)&&!Py.test(e)&&!Fy.test(e)&&!(By(e)&&Iy.test(e))}function By(e){return e.includes(`://`)||e.includes(`www.`)||e.includes(`@`)}function Vy(e){let t=Hy(e);return t?t.openerEnd>=e.length?e.slice(0,t.openerStart):`${e}\``:e}function Hy(e){let t=0;for(;t<e.length;){let n=e.indexOf("`",t);if(n===-1)return;if(Gy(e,n)){t=n+1;continue}if(Wy(e,n)!==1)return;let r=Uy(e,n+1);if(r===-1)return{openerStart:n,openerEnd:n+1};t=r+1}}function Uy(e,t){for(;t<e.length;){let n=e.indexOf("`",t);if(n===-1)return-1;let r=Wy(e,n);if(r===1)return n;t=n+r}return-1}function Wy(e,t){let n=t;for(;n<e.length&&e[n]==="`";)n+=1;return n-t}function Gy(e,t){let n=0,r=t-1;for(;r>=0&&e[r]===`\\`;)n+=1,--r;return n%2==1}function Ky(e){return e.includes(`~~`)||e.includes(`[`)&&Ly.test(e)||e.includes(`|`)&&Ry.test(e)||By(e)&&Iy.test(e)}var qy=/[\n\r\\`*_\[\]<>]/,Jy=/^\s*[-+*]\s+\[([ xX])\]\s+(.+?)\s*$/,Yy=/[\n\r\\<>|~]/,Xy=/[\n\r\\\[\]<>|~]/,Zy=/[\s\[\]()`<>]/;function Qy(e){if(!e.includes(`~~`)||qy.test(e)||Py.test(e)||Fy.test(e)||By(e)&&Iy.test(e)||e.includes(`[`)&&Ly.test(e)||e.includes(`|`)&&Ry.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,L.jsx)(`del`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`del`,children:s},`del-${r}`)),r+=1,n=a+2}return r>0?(0,L.jsx)(`p`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`p`,children:t}):void 0}function $y(e){if(!e||Zy.test(e))return;let t=ig(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 eb(e,t){if(!e||Xy.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("`")||By(t)&&Iy.test(t))return;t&&n.push(t);break}let p=e.slice(r,f);if(p.includes(`*`)||p.includes(`_`)||p.includes("`")||By(p)&&Iy.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,L.jsx)(`strong`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`strong`,children:(0,L.jsx)(`em`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`em`,children:e})},`link-${t}-strong-${i}`))}else n.push((0,L.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,L.jsx)(`em`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`em`,children:(0,L.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,L.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,L.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 tb(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(`]`)||By(r)&&Iy.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(`]`)||By(f)&&Iy.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,L.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,L.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=eb(e.slice(d+1,r),a),s=$y(e.slice(r+2,i));if(!s||!o)return;t.push((0,L.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 nb(e){let t=Jy.exec(e);if(!t)return;let n=t[2];if(!n||Yy.test(n))return;let r=tb(n);if(r)return(0,L.jsx)(`ul`,{className:`contains-task-list`,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`ul`,children:(0,L.jsxs)(`li`,{className:`task-list-item`,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`li`,children:[(0,L.jsx)(`input`,{type:`checkbox`,checked:t[1].toLowerCase()===`x`,readOnly:!0,disabled:!0,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`input`}),r]})})}var rb={p({children:e,node:t,...n}){return(0,L.jsx)(`p`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`p`,...n,children:e})},ul({children:e,node:t,...n}){return(0,L.jsx)(`ul`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`ul`,...n,children:e})},ol({children:e,node:t,...n}){return(0,L.jsx)(`ol`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`ol`,...n,children:e})},li({children:e,node:t,...n}){return(0,L.jsx)(`li`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`li`,...n,children:e})},blockquote({children:e,node:t,...n}){return(0,L.jsx)(`blockquote`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`blockquote`,...n,children:e})},pre({children:e,node:t,...n}){return(0,L.jsx)(`pre`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`pre`,...n,children:e})},a({href:e,children:t}){return(0,L.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=ib(e),a=String(t).replace(/\n$/,``);if(!i)return(0,L.jsx)(`code`,{className:e,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`code`,...r,children:t});let o=cy.languages[i];return o?(0,L.jsx)(`code`,{className:`language-${i}`,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`code`,dangerouslySetInnerHTML:{__html:cy.highlight(a,o,i)},...r}):(0,L.jsx)(`code`,{className:e,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`code`,...r,children:t})},th({children:e,node:t,...n}){return(0,L.jsx)(`th`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`th`,...n,children:e})},td({children:e,node:t,...n}){return(0,L.jsx)(`td`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`td`,...n,children:e})},input({checked:e,node:t,...n}){return(0,L.jsx)(`input`,{type:`checkbox`,checked:!!e,readOnly:!0,disabled:!0,"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`input`,...n})}};function ib(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 ab(e,t){t!==void 0&&_y(e,(typeof performance>`u`?Date.now():performance.now())-t)}var ob=(e,t,n)=>{if(n.tagName!==`a`||t!==`href`)return``;let r=ig(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``}},sb=(0,v.memo)(function({children:e,streaming:t=!1}){let n=uy()?typeof performance>`u`?Date.now():performance.now():void 0,r=t?Vy(e):e,i=`commonmark`,a;if(zy(r))i=`plain`,a=(0,L.jsx)(`p`,{"data-pibo-component":`MarkdownRenderer`,"data-pibo-markdown-node":`p`,children:r});else{let e=Ky(r),t=e?Qy(r)??nb(r):void 0;t?(i=`gfm-fast`,a=t):(i=e?`gfm`:`commonmark`,a=eg({allowedElements:Ay,children:r,components:rb,remarkPlugins:e?jy:My,skipHtml:!0,urlTransform:ob}))}return ab(i,n),a}),cb={"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`}},lb=12;function ub(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)(()=>ub(r,i)),[d,f]=(0,v.useState)(()=>t.spanType===`model.reasoning`?o:ub(r,i));(0,v.useEffect)(()=>{let e=ub(r,i);u(e),f(t.spanType===`model.reasoning`?o:e)},[r,i,a,o,t.spanType]),cb[t.spanType]||cb[`agent.run`],t.status,t.status,t.spanType===`user.prompt`||t.spanType;let p=!!t.children?.length;return Cb(t.startTime,n),t.durationUs?`${(t.durationUs/1e3).toFixed(1)}`:t.endTime&&`${((t.endTime-t.startTime)/1e3).toFixed(1)}`,(0,L.jsx)(db,{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,L.jsx)(e,{span:t,startTime:n,depth:r+1,expansionDepth:i,expansionSignal:a,expandThinking:o,onFork:s,onOpenSession:c},t.id)):void 0})});var db=(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=cb[e.spanType]||cb[`agent.run`],d=e.status===`UNSET`,f=bb(e.status,d),p=e.spanType===`user.prompt`||e.spanType===`user_input`,m=!!e.children?.length,h=Cb(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,L.jsx)(`div`,{className:`relative mb-4`,"data-pibo-debug":`trace-span`,"data-trace-node-id":e.id,"data-span-type":e.spanType,"data-span-status":e.status,"data-order-source":e.pibo?.source,"data-stable-key":e.pibo?.stableKey,style:{marginLeft:n>0?lb:0,width:n>0?`calc(100% - ${lb}px)`:`var(--trace-readable-width)`,maxWidth:`100%`},children:(0,L.jsx)(ml,{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,L.jsx)(`div`,{className:`relative mb-4 group`,"data-pibo-debug":`trace-span`,"data-trace-node-id":e.id,"data-span-type":e.spanType,"data-span-status":e.status,"data-order-source":e.pibo?.source,"data-stable-key":e.pibo?.stableKey,style:{marginLeft:n>0?lb:0,width:n>0?`calc(100% - ${lb}px)`:`var(--trace-readable-width)`,maxWidth:`100%`},children:(0,L.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=>{fb(e)||a()},onKeyDown:e=>{fb(e)||(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),a())},role:`button`,tabIndex:0,"aria-expanded":r,children:[(0,L.jsx)(pb,{span:e,config:u,statusStyles:f,isActive:d,contentExpanded:r,duration:g,relativeTime:h,onToggle:a,onFork:o,onOpenSession:s}),r?(0,L.jsx)(gb,{span:e}):null,m&&i&&r?(0,L.jsx)(`div`,{className:`min-w-0 border-t border-slate-700 bg-slate-900/50 py-4`,children:l}):null]})})});function fb(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 pb({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,L.jsx)(`div`,{className:`${i?`border-b ${t.borderColor}/20`:``} ${u}`,children:(0,L.jsxs)(`div`,{className:`box-border flex w-full min-w-0 items-center`,style:{maxWidth:`100%`},children:[(0,L.jsx)(`div`,{className:`min-w-0 flex-1 px-4 py-2 text-left`,children:(0,L.jsxs)(`span`,{className:`min-w-0 text-xs font-bold ${t.color} uppercase tracking-wider flex items-center gap-2`,children:[i?(0,L.jsx)(je,{size:12}):(0,L.jsx)(Me,{size:12}),(0,L.jsx)(mb,{spanType:e.spanType,config:t,isActive:r}),(0,L.jsx)(`span`,{className:`shrink-0`,children:t.label}),e.name?(0,L.jsxs)(`span`,{className:`min-w-0 truncate font-normal text-slate-500 dark:text-slate-400 normal-case`,children:[`: `,e.name]}):null,r?(0,L.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-[#11a4d4] animate-pulse`}):null]})}),(0,L.jsx)(_b,{forkEntryId:e.pibo?.traceNodeType===`user.message`?e.pibo.entryId:void 0,linkedPiboSessionId:e.pibo?.linkedPiboSessionId,onFork:c,onOpenSession:l}),(0,L.jsx)(hb,{duration:a,relativeTime:o})]})})}function mb({spanType:e,config:t,isActive:n}){return(0,L.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,L.jsx)(yb,{type:e,className:t.color}),n?(0,L.jsx)(`span`,{className:`absolute -right-0.5 -top-0.5 h-1.5 w-1.5 rounded-full bg-[#11a4d4] animate-pulse`}):null]})}function hb({duration:e,relativeTime:t}){return(0,L.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,L.jsx)(`span`,{className:`text-[10px] text-slate-500 dark:text-slate-400`,children:e}):null,(0,L.jsx)(`span`,{className:`text-xs text-slate-400 dark:text-slate-500`,children:t})]})}var gb=(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=Sb(i[`message.pending_delivery`]),f=e.status===`ERROR`?(0,L.jsxs)(`div`,{className:`mx-4 mt-4 p-3 bg-red-500/10 border border-red-500/20 rounded-sm text-xs`,children:[(0,L.jsx)(`div`,{className:`flex items-center gap-2 font-semibold text-red-500 mb-1`,children:`Error`}),e.statusMessage?(0,L.jsx)(`div`,{className:`font-mono text-red-400 mb-2`,children:e.statusMessage}):null]}):null;if(r===`user.prompt`||r===`user_input`)return(0,L.jsxs)(`div`,{className:`flex flex-col`,children:[f,(0,L.jsx)(`div`,{className:`min-w-0 break-words p-4 font-mono text-sm text-slate-300 whitespace-pre-wrap`,children:typeof o==`string`?o:JSON.stringify(o)}),d===`queue`||d===`steer`?(0,L.jsx)(xl,{delivery:d,className:`mx-4 mb-4`}):null]});if(r===`model.response`)return(0,L.jsxs)(`div`,{className:`flex flex-col`,children:[f,(0,L.jsx)(`div`,{className:`model-response-markdown min-w-0 p-4 text-sm text-slate-200 leading-relaxed`,children:typeof o==`string`?(0,L.jsx)(sb,{children:o}):(0,L.jsx)(fl,{value:o})})]});if(r===`tool.result`)return(0,L.jsxs)(`div`,{className:`flex flex-col`,children:[f,(0,L.jsxs)(`div`,{className:`p-4 bg-green-500/5 border-t border-green-500/20`,children:[(0,L.jsxs)(`div`,{className:`text-xs font-medium text-green-400 mb-2`,children:[`Returned from `,c||a,`:`]}),(0,L.jsx)(fl,{value:l??o})]})]});if(r===`tool.call`){let e=wb(u)?u:{},r=Object.keys(e).length>0;return(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(`div`,{className:`p-4 bg-[#0e1116] border-b border-slate-800`,children:(0,L.jsx)(vb,{name:c??a,args:e})}),l==null?null:(0,L.jsxs)(`div`,{className:`px-4 py-2 bg-[#1a262b] flex items-center gap-2`,children:[(0,L.jsx)(Se,{size:14,className:`text-slate-400`}),(0,L.jsx)(`span`,{className:`text-xs font-mono text-slate-500`,children:`Output:`}),(0,L.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,L.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,L.jsx)(qe,{size:12}):(0,L.jsx)(Je,{size:12}),t?`Hide Details`:`Show Details`]}),t?(0,L.jsxs)(`div`,{className:`border-t border-slate-700/40 bg-[#0e1116]`,children:[r?(0,L.jsxs)(`div`,{className:`px-4 pt-3 pb-2`,children:[(0,L.jsx)(`div`,{className:`text-[10px] font-semibold text-blue-400 uppercase tracking-wider mb-1.5`,children:`Input`}),(0,L.jsx)(fl,{value:e})]}):null,l==null?null:(0,L.jsxs)(`div`,{className:`px-4 pt-2 pb-3 border-t border-slate-700/30`,children:[(0,L.jsx)(`div`,{className:`text-[10px] font-semibold text-green-400 uppercase tracking-wider mb-1.5`,children:`Output`}),(0,L.jsx)(fl,{value:l})]})]}):null,f]})}if(r===`yielded.run`){let e=wb(l)?l:wb(o)?o:{};return(0,L.jsxs)(`div`,{className:`flex flex-col`,children:[f,(0,L.jsxs)(`div`,{className:`p-4 border-b border-[#11a4d4]/20 bg-[#11a4d4]/5`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,L.jsx)(we,{size:14,className:`text-[#11a4d4]`}),(0,L.jsx)(`span`,{className:`text-sm font-medium text-[#11a4d4]`,children:`Run notification`}),(0,L.jsx)(`span`,{className:`text-xs font-mono text-slate-400`,children:typeof i.content==`string`?i.content:a})]}),(0,L.jsx)(xb,{notification:e})]}),(0,L.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,L.jsx)(qe,{size:12}):(0,L.jsx)(Je,{size:12}),t?`Hide Details`:`Show Details`]}),t?(0,L.jsx)(`div`,{className:`border-t border-slate-700/40 bg-[#0e1116] px-4 py-3`,children:(0,L.jsx)(fl,{value:e})}):null]})}if(r===`model.reasoning`){let e=i.reasoning||i[`model.reasoning`]||o;return(0,L.jsxs)(`div`,{className:`flex flex-col`,children:[f,(0,L.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,L.jsx)(`span`,{className:`text-amber-500 opacity-60`,children:`// Model reasoning`}),(0,L.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,L.jsxs)(L.Fragment,{children:[f,(0,L.jsxs)(`div`,{className:`p-4 border-b border-orange-500/20 bg-orange-500/5`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,L.jsx)(Ze,{size:14,className:`text-orange-500`}),(0,L.jsx)(`span`,{className:`text-sm font-medium text-orange-500`,children:`Delegated to:`}),(0,L.jsxs)(`span`,{className:`text-sm font-semibold text-slate-200`,children:[e||`unknown`,` agent`]}),n?(0,L.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,L.jsxs)(`div`,{className:`text-xs text-slate-400 font-mono italic line-clamp-2`,children:[`"`,Tb(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,L.jsxs)(L.Fragment,{children:[f,(0,L.jsxs)(`div`,{className:`p-4 border-b border-orange-500/20 bg-orange-500/5`,children:[(0,L.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 mb-2`,children:[(0,L.jsx)(Ze,{size:14,className:`text-orange-500`}),(0,L.jsx)(`span`,{className:`text-sm font-medium text-orange-500`,children:`Async agent started:`}),(0,L.jsxs)(`span`,{className:`text-sm font-semibold text-slate-200`,children:[e||`unknown`,` agent`]}),a?(0,L.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,L.jsxs)(`div`,{className:`mb-2 flex flex-wrap gap-x-3 gap-y-1 font-mono text-[11px] text-slate-500`,children:[(0,L.jsxs)(`span`,{children:[`Started by `,n||`pibo_run_start`]}),r?(0,L.jsx)(`span`,{children:r}):null]}),t?(0,L.jsxs)(`div`,{className:`text-xs text-slate-400 font-mono italic line-clamp-2`,children:[`"`,Tb(t),`"`]}):null]})]})}return r===`agent.run`?(0,L.jsx)(`div`,{className:`flex flex-col`,children:f}):(0,L.jsxs)(`div`,{className:`flex flex-col`,children:[f,(0,L.jsx)(`div`,{className:`p-4 font-mono text-sm text-slate-300`,children:(0,L.jsx)(fl,{value:i})})]})});function _b({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,L.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[i?(0,L.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,L.jsx)(Ze,{size:14})}):null,a?(0,L.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,L.jsx)(Ke,{size:14})}):null]})}function vb({name:e,args:t}){return(0,L.jsxs)(`code`,{className:`font-mono text-xs text-green-400`,children:[(0,L.jsx)(`span`,{className:`text-purple-400`,children:`def`}),` `,(0,L.jsx)(`span`,{className:`text-yellow-300`,children:e}),(0,L.jsxs)(`span`,{children:[`(`,Object.entries(t).map(([e,t],n)=>(0,L.jsxs)(`span`,{children:[n>0?`, `:null,(0,L.jsx)(`span`,{className:`text-blue-400`,children:e}),`=`,(0,L.jsx)(`span`,{className:`text-green-300`,children:typeof t==`string`?`'${t.slice(0,50)}${t.length>50?`...`:``}'`:Tb(t).slice(0,50)})]},e)),`)`]})]})}function yb({type:e,className:t}){let n={size:14,className:t};switch(e){case`agent.run`:return(0,L.jsx)(Oe,{...n});case`tool.call`:return(0,L.jsx)(Te,{...n});case`tool.result`:return(0,L.jsx)(Se,{...n});case`model.request`:return(0,L.jsx)(De,{...n});case`model.response`:return(0,L.jsx)(Se,{...n});case`model.reasoning`:return(0,L.jsx)(rt,{...n});case`agent.delegation`:return(0,L.jsx)(Ze,{...n});case`agent.async`:return(0,L.jsx)(Ze,{...n});case`yielded.run`:return(0,L.jsx)(we,{...n});case`user.prompt`:return(0,L.jsx)(ct,{...n});case`user_input`:return(0,L.jsx)(bt,{...n});case`execution.command`:return(0,L.jsx)(Te,{...n});default:return(0,L.jsx)(Ae,{...n})}}function bb(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 xb({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(wb):[]})).filter(e=>e.runs.length>0);return t.length===0?(0,L.jsx)(`div`,{className:`text-xs text-slate-400`,children:`No yielded run updates.`}):(0,L.jsx)(`div`,{className:`grid gap-2`,children:t.map(e=>(0,L.jsxs)(`div`,{children:[(0,L.jsx)(`div`,{className:`mb-1 text-[10px] font-bold uppercase tracking-wider ${e.color}`,children:e.name}),(0,L.jsx)(`div`,{className:`grid gap-1`,children:e.runs.map((t,n)=>(0,L.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,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsx)(`div`,{className:`truncate font-mono text-xs text-slate-200`,children:Sb(t.toolName)||`yielded tool`}),(0,L.jsx)(`div`,{className:`truncate font-mono text-[10px] text-slate-500`,children:Sb(t.runId)})]}),(0,L.jsx)(`div`,{className:`font-mono text-[10px] uppercase text-slate-400`,children:Sb(t.status)||e.name})]},`${e.name}-${n}`))})]},e.name))})}function Sb(e){return typeof e==`string`?e:``}function Cb(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 wb(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Tb(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}var Eb=5e3,Db=0,Ob=new Map,kb=0;function Ab(e){let t=Ob.get(e);return t||(t={snapshots:[],pending:null,pendingTimer:null},Ob.set(e,t)),t}function jb(){if(typeof window<`u`&&window.__piboTraceSnapshotCollectionEnabled===!0)return!0;try{return localStorage.getItem(`pibo.chat.traceDebug`)===`true`}catch{return!1}}function Mb(e){let t=0;for(let n of e)for(let e=0;e<n.length;e++)t=(t<<5)-t+n.charCodeAt(e),t|=0;return t.toString(36)}function Nb(e){return Mb([JSON.stringify(e)])}function Pb(e){return JSON.stringify({trigger:e.trigger,traceVersion:e.traceVersion,baseTraceVersion:e.baseTraceVersion,latestStreamId:e.latestStreamId,lastRawEventId:e.lastRawEventId,selectedSessionStatus:e.selectedSessionStatus,overlayEventCount:e.overlayEventCount,layers:e.layers.map(e=>[e.kind,e.digest])})}function Fb(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||Pb(n)!==Pb(t))&&(e.snapshots.push(t),e.snapshots.length>Eb&&e.snapshots.shift()),e.pending=null}function Ib(e){if(!jb())return;let t=Ab(e.piboSessionId);t.pendingTimer&&=(clearTimeout(t.pendingTimer),null);let n=e.layer&&t.pending?.layers?.find(t=>t.kind===e.layer.kind),r=t.pending&&Kb(t.pending.traceVersion,e.traceVersion)&&Kb(t.pending.baseTraceVersion,e.baseTraceVersion)&&Kb(t.pending.latestStreamId,e.latestStreamId)&&Kb(t.pending.lastRawEventId,e.lastRawEventId)&&Kb(t.pending.selectedSessionStatus,e.selectedSessionStatus)&&Kb(t.pending.overlayEventCount,e.overlayEventCount);if(t.pending&&t.pending.trigger===e.trigger&&t.pending.piboSessionId===e.piboSessionId&&r&&(!n||n.digest===e.layer?.digest)||Fb(t),t.pending||={sequence:++kb,timestamp:Date.now(),piboSessionId:e.piboSessionId,trigger:e.trigger,layers:[],expansionOverrides:e.expansionOverrides,traceVersion:e.traceVersion,baseTraceVersion:e.baseTraceVersion,latestStreamId:e.latestStreamId,lastRawEventId:e.lastRawEventId,selectedSessionStatus:e.selectedSessionStatus,overlayEventCount:e.overlayEventCount},e.layer){let n=t.pending.layers.findIndex(t=>t.kind===e.layer.kind);n>=0?t.pending.layers[n]=e.layer:t.pending.layers.push(e.layer)}e.expansionOverrides!==void 0&&(t.pending.expansionOverrides=e.expansionOverrides),e.traceVersion!==void 0&&(t.pending.traceVersion=e.traceVersion),e.baseTraceVersion!==void 0&&(t.pending.baseTraceVersion=e.baseTraceVersion),e.latestStreamId!==void 0&&(t.pending.latestStreamId=e.latestStreamId),e.lastRawEventId!==void 0&&(t.pending.lastRawEventId=e.lastRawEventId),e.selectedSessionStatus!==void 0&&(t.pending.selectedSessionStatus=e.selectedSessionStatus),e.overlayEventCount!==void 0&&(t.pending.overlayEventCount=e.overlayEventCount),t.pendingTimer=setTimeout(()=>{Fb(t),t.pendingTimer=null},Db)}function Lb(e){let t={traceVersion:e.currentTraceView.version,baseTraceVersion:e.baseTraceView?.version,latestStreamId:e.currentTraceView.latestStreamId,lastRawEventId:e.currentTraceView.rawEvents.at(-1)?.id,selectedSessionStatus:e.selectedSessionStatus,overlayEventCount:e.overlayEvents.length};Rb(e.piboSessionId,e.trigger,`baseNodes`,e.baseTraceView?.nodes??[],t),zb(e.piboSessionId,e.trigger,e.overlayEvents,t),Rb(e.piboSessionId,e.trigger,`currentNodes`,e.currentTraceView.nodes,t)}function Rb(e,t,n,r,i){let a=qb(r).map(Jb);Ib({piboSessionId:e,trigger:t,layer:{kind:n,ids:a.map(e=>e.id),digest:Nb(a),meta:a},...i})}function zb(e,t,n,r){let i=n.map(e=>({id:e.id,type:e.type,eventId:e.eventId,eventSequence:e.eventSequence,streamId:e.streamId,streamFrameIndex:e.streamFrameIndex}));Ib({piboSessionId:e,trigger:t,layer:{kind:`overlayEvents`,ids:i.map(e=>e.id),digest:Nb(i),meta:i},...r})}function Bb(e,t,n,r){let i=n.map(e=>({id:e.id,kind:e.kind,status:e.status,sourceNodeIds:[...e.sourceNodeIds],eventId:e.eventId,runId:e.runId,orderSource:e.orderSource,orderStreamId:e.orderStreamId,orderStreamFrameIndex:e.orderStreamFrameIndex}));Ib({piboSessionId:e,trigger:t,layer:{kind:`terminalRows`,ids:i.map(e=>e.id),digest:Nb(i),meta:i},...r})}function Vb(e){let t=Ob.get(e);return t?(Fb(t),t.snapshots):[]}function Hb(e){let t=Ob.get(e);return t?.pending?.sequence??t?.snapshots.at(-1)?.sequence}function Ub(e){if(e)return JSON.stringify({piboSessionId:e,snapshots:Vb(e)},null,2);let t={};for(let[e,n]of Ob)Fb(n),t[e]=n.snapshots;return JSON.stringify(t,null,2)}function Wb(e){if(e){Gb(Ob.get(e)),Ob.delete(e);return}for(let e of Ob.values())Gb(e);Ob.clear()}function Gb(e){e?.pendingTimer&&(clearTimeout(e.pendingTimer),e.pendingTimer=null)}function Kb(e,t){return t===void 0||e===void 0||e===t}function qb(e){return e.flatMap(e=>[e,...qb(e.children??[])])}function Jb(e){let t=Xb(e);return{id:e.id,type:e.type,status:e.status,parentId:e.parentId,childIds:e.children.map(e=>e.id),entryId:e.entryId,eventId:e.eventId,toolCallId:e.toolCallId,runId:e.runId,stableKey:e.stableKey,source:e.source,orderKey:e.orderKey,contentLength:t.length,contentKind:Yb(t)}}function Yb(e){return e.startsWith(`<pibo_run_notification>`)?`pibo-run-notification`:e.startsWith(`<pibo_goal_continuation>`)?`pibo-goal-continuation`:e.startsWith(`<pibo_`)?`pibo-system`:`message`}function Xb(e){return typeof e.output==`string`?e.output:typeof e.summary==`string`?e.summary:e.output&&typeof e.output==`object`&&`text`in e.output&&typeof e.output.text==`string`?e.output.text:``}typeof window<`u`&&(window.__piboTraceSnapshots={exportAsJson:e=>{let t=Ub(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:Vb,getLatestSequence:Hb,clearSnapshots:Wb,exportSnapshots:Ub});function Zb(e,t={}){if(!e)return Qb(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 Qb(e){let t=e.status===`running`&&$b(e.turnStartedAt);return{status:e.status??`idle`,isTreeActive:e.status===`running`,isTurnActive:t,activeTurnStartedAt:t?e.turnStartedAt:void 0,source:`fallback`}}function $b(e){return!!(e&&Number.isFinite(Date.parse(e)))}function ex({signal:e,fallbackStatus:t,fallbackTurnStartedAt:n}){return(0,v.useMemo)(()=>Zb(e,{status:t,turnStartedAt:n}),[t,n,e])}function tx({goal:e}){let t=rx(e),[n,r]=(0,v.useState)(()=>Date.now());return(0,v.useEffect)(()=>{if(r(Date.now()),!t||e?.state.goalEndedAt)return;let n=window.setInterval(()=>r(Date.now()),1e3);return()=>window.clearInterval(n)},[e?.id,e?.state.goalEndedAt,t]),(0,L.jsx)(nx,{goal:e,nowMs:n})}function nx({goal:e,nowMs:t}){let n=rx(e);if(!e||!n)return null;let r=n===`active`?`Pursuing Goal`:`Goal Paused`,i=n===`active`?`text-fuchsia-400`:`text-amber-300`,a=ix(e,t);return(0,L.jsxs)(`span`,{className:`inline-flex shrink-0 items-center gap-2 font-sans text-sm font-semibold ${i}`,"data-pibo-debug":`session-goal-indicator`,"data-goal-id":e.id,"data-goal-status":n,title:`${e.name}: ${e.prompt}`,children:[(0,L.jsx)(gt,{size:17,className:n===`active`?`animate-pulse`:``,"aria-hidden":`true`}),(0,L.jsxs)(`span`,{children:[r,`:`]}),(0,L.jsx)(`span`,{className:`tabular-nums`,children:a})]})}function rx(e){if(!e||e.mode!==`goal`)return;let t=e.state.goalStatus??(e.enabled?`active`:`paused`);return t===`active`||t===`paused`?t:void 0}function ix(e,t){let n=e.state.goalStartedAt?Date.parse(e.state.goalStartedAt):NaN,r=e.state.goalEndedAt?Date.parse(e.state.goalEndedAt):t,i=Number.isFinite(n)&&Number.isFinite(r)?Math.max(0,Math.floor((r-n)/1e3)):0,a=Math.floor(i/3600),o=Math.floor(i%3600/60),s=i%60;return a>0?`${a}:${String(o).padStart(2,`0`)}:${String(s).padStart(2,`0`)}`:`${o}:${String(s).padStart(2,`0`)}`}function ax(e){if(e==null)return{kind:`empty`};let t=ox(e);return t===void 0?{kind:`json`,value:e}:{kind:`text`,text:t}}function ox(e){if(typeof e==`string`)return e;if(Array.isArray(e)){let t=e.map(ox).filter(e=>e!==void 0);return t.length===e.length&&t.length>0?t.join(``):void 0}if(!cx(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=ox(e.content);if(n!==void 0&&sx(e))return n;let r=cx(e.message)?ox(e.message.content):void 0;if(r!==void 0)return r}function sx(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 cx(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}async function lx(e,t,n){let r=new URLSearchParams({piboSessionId:e}),i=await fetch(`/api/chat/trace/summary?${r.toString()}`,{headers:t?{"if-none-match":px(t)}:void 0,signal:n?.signal});if(i.status===304)return{notModified:!0,version:mx(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:mx(i.headers.get(`etag`))??a.version}}async function ux(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":px(t.knownVersion)}:void 0,signal:t.signal});if(r.status===304)return{notModified:!0,version:mx(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:mx(r.headers.get(`etag`))??i.version}}async function dx(e,t={}){let n=new URLSearchParams({piboSessionId:e});return t.limit&&n.set(`limit`,String(t.limit)),t.beforeSequence!==void 0&&n.set(`before`,String(t.beforeSequence)),A(`/api/chat/trace/raw-events?${n.toString()}`,{signal:t.signal})}async function fx(e,t={}){let n=new URLSearchParams;t.offset!==void 0&&n.set(`offset`,String(t.offset)),t.limit!==void 0&&n.set(`limit`,String(t.limit));let r=n.toString();return A(`/api/chat/trace/payload/${encodeURIComponent(e)}${r?`?${r}`:``}`)}function px(e){return`"${e}"`}function mx(e){if(!e)return;let t=e.trim();return t.startsWith(`W/`)?mx(t.slice(2)):t.startsWith(`"`)&&t.endsWith(`"`)?t.slice(1,-1):t}function hx({row:e,onOpenSession:t}){return(0,L.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,L.jsx)(`div`,{className:`space-y-3`,children:e.detailItems.map(e=>(0,L.jsxs)(`div`,{className:`space-y-2`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px]`,children:[(0,L.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:e.label}),e.linkedPiboSessionId?(0,L.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,L.jsx)(vx,{label:`Input`,value:e.input}),(0,L.jsx)(vx,{label:`Output`,value:e.output}),(0,L.jsx)(gx,{refs:e.payloadRefs}),(0,L.jsx)(yx,{value:e.output}),e.error?(0,L.jsx)(Sx,{label:`Error`,value:e.error,tone:`red`}):null]},e.id))}):(0,L.jsxs)(`div`,{className:`space-y-3`,children:[(0,L.jsx)(vx,{label:`Input`,value:e.input}),(0,L.jsx)(vx,{label:`Output`,value:e.output}),(0,L.jsx)(gx,{refs:e.payloadRefs}),(0,L.jsx)(yx,{value:e.output}),e.error?(0,L.jsx)(Sx,{label:`Error`,value:e.error,tone:`red`}):null,e.linkedPiboSessionId?(0,L.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px]`,children:[(0,L.jsx)(`span`,{className:`text-[#737373]`,children:`Child session`}),(0,L.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 gx({refs:e}){if(!e)return null;let t=Object.entries(e).filter(e=>!!e[1]);return t.length?(0,L.jsx)(`div`,{className:`space-y-2`,children:t.map(([e,t])=>(0,L.jsx)(_x,{kind:e,refInfo:t},`${e}:${t.ref}`))}):null}function _x({kind:e,refInfo:t}){let[n,r]=(0,v.useState)({status:`loading`});return(0,v.useEffect)(()=>{let e=!1;return r({status:`loading`}),fx(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,L.jsxs)(`div`,{className:`space-y-1`,"data-shared-terminal-payload-ref":e,children:[(0,L.jsxs)(`div`,{className:`text-[11px] font-semibold text-[#737373]`,children:[e,` payload (`,Math.ceil(t.byteLength/1024),` KB)`]}),n.status===`loading`?(0,L.jsx)(`div`,{className:`border border-[#2a2a2a] bg-[#0b0b0b] p-2 text-[12px] text-[#737373]`,children:`Loading payload preview...`}):n.status===`error`?(0,L.jsx)(`div`,{className:`border border-[#2a2a2a] bg-[#0b0b0b] p-2 text-[12px] text-[#ef4444]`,children:n.message}):(0,L.jsxs)(`div`,{className:`space-y-1`,children:[(0,L.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,L.jsx)(`div`,{className:`text-[11px] text-[#737373]`,children:`Showing first chunk. More payload data is available on demand.`}):null]})]})}function vx({label:e,value:t}){let n=ax(t);if(n.kind===`empty`)return null;if(n.kind===`text`){let t=Cx(n.text);return t?.kind===`json`?(0,L.jsx)(xx,{label:e,value:t.value,meta:t.meta}):t?.kind===`text`?(0,L.jsx)(Sx,{label:e,value:t.text}):(0,L.jsx)(Sx,{label:e,value:n.text})}return(0,L.jsx)(xx,{label:e,value:n.value})}function yx({value:e}){let t=bx(e);return t?(0,L.jsxs)(`details`,{className:`space-y-1 border border-[#2a2a2a] bg-[#0b0b0b] p-2`,children:[(0,L.jsxs)(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-[#38bdf8]`,children:[`Show full output (`,t.originalLines,` lines)`]}),t.fullOutput?(0,L.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,L.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 bx(e){if(!Ex(e))return;let t=Ex(e.details)?e.details.piboBashOutputCompaction:void 0;if(!Ex(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 xx({label:e,value:t,meta:n}){return(0,L.jsxs)(`div`,{className:`space-y-1`,"data-shared-terminal-detail-json":e,children:[(0,L.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,L.jsx)(`div`,{className:`text-[11px] font-semibold text-[#737373]`,"data-shared-terminal-detail-label":e,children:e}),n?(0,L.jsxs)(`div`,{className:`min-w-0 break-words text-[11px] text-[#737373]`,children:[`Status: `,n]}):null]}),(0,L.jsx)(`div`,{className:`compact-terminal-json border border-[#2a2a2a] bg-[#0b0b0b] p-2`,children:(0,L.jsx)(fl,{value:t,showControls:!1})})]})}function Sx({label:e,value:t,tone:n=`default`}){return(0,L.jsxs)(`div`,{className:`space-y-1`,"data-shared-terminal-detail-text":e,children:[(0,L.jsx)(`div`,{className:`text-[11px] font-semibold text-[#737373]`,"data-shared-terminal-detail-label":e,children:e}),(0,L.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 Cx(e){let t=e.trim();if(!t)return;let n=Tx(t);if(n!==void 0)return wx(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=Tx(t);if(n!==void 0)return wx(n,r.slice(0,e).join(` `).trim()||void 0)}}function wx(e,t){let n=ax(e);if(n.kind===`text`){let e=Cx(n.text);return e?.kind===`json`?{...e,meta:e.meta??t}:{kind:`text`,text:n.text}}return{kind:`json`,value:e,meta:t}}function Tx(e){if(!(!e.startsWith(`{`)&&!e.startsWith(`[`)))try{let t=JSON.parse(e);return typeof t==`object`&&t?t:void 0}catch{return}}function Ex(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Dx({name:e,input:t}){return(0,L.jsxs)(`span`,{className:`compact-terminal-function-call`,children:[(0,L.jsx)(`span`,{className:`text-[#facc15] font-semibold`,children:e}),(0,L.jsx)(`span`,{className:`text-[#d4d4d4]`,children:`(`}),t===void 0?null:(0,L.jsx)(Ox,{value:t}),(0,L.jsx)(`span`,{className:`text-[#d4d4d4]`,children:`)`})]})}function Ox({value:e}){let[t,n]=(0,v.useState)(()=>new Set([`$`])),[r,i]=(0,v.useState)(()=>new Set);return(0,L.jsx)(kx,{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 kx({value:e,path:t,expandedPaths:n,expandedStrings:r,onTogglePath:i,onToggleString:a}){if(Array.isArray(e))return(0,L.jsx)(Ax,{value:e,path:t,open:`[`,close:`]`,expandedPaths:n,expandedStrings:r,onTogglePath:i,onToggleString:a});if(Nx(e))return(0,L.jsx)(Ax,{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,L.jsx)(`span`,{className:`text-[#fb923c]`,children:JSON.stringify(o)});return!i&&e.length<=140?s:(0,L.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),a(t)},className:`compact-terminal-json-toggle text-left align-baseline`,title:n?`Collapse string`:`Expand string`,"aria-label":`String at ${jx(t)}`,"aria-expanded":n,children:s})}return typeof e==`number`||typeof e==`boolean`||e===null?(0,L.jsx)(`span`,{className:`text-[#60a5fa]`,children:String(e)}):(0,L.jsx)(`span`,{className:`text-[#737373]`,children:JSON.stringify(String(e))})}function Ax({value:e,path:t,open:n,close:r,expandedPaths:i,expandedStrings:a,onTogglePath:o,onToggleString:s}){let c=i.has(t),l=`inline-json-${(0,v.useId)()}`,u=c?Array.isArray(e)?e.map((e,t)=>[String(t),e]):Object.entries(e):[];return(0,L.jsxs)(`span`,{children:[(0,L.jsxs)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),o(t)},className:`compact-terminal-json-toggle align-baseline text-[#737373]`,title:c?`Collapse JSON`:`Expand JSON`,"aria-label":`JSON at ${t}`,"aria-expanded":c,"aria-controls":l,"data-inline-json-path":t,children:[(0,L.jsx)(`span`,{className:`compact-terminal-json-caret`,children:c?`▾`:`▸`}),n,c?null:`...${r}`]}),(0,L.jsxs)(`span`,{id:l,children:[u.map(([n,r],c)=>{let l=`${t}.${Mx(n)}`;return(0,L.jsxs)(`span`,{children:[c>0?(0,L.jsx)(`span`,{className:`text-[#737373]`,children:`, `}):null,Array.isArray(e)?null:(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(`span`,{className:`text-[#d4d4d4]`,children:JSON.stringify(n)}),(0,L.jsx)(`span`,{className:`text-[#737373]`,children:`:`})]}),(0,L.jsx)(kx,{value:r,path:l,expandedPaths:i,expandedStrings:a,onTogglePath:o,onToggleString:s})]},l)}),c?(0,L.jsx)(`span`,{className:`text-[#737373]`,children:r}):null]})]})}function jx(e){let t=e.replace(/[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}/gi,`[id]`);return t.length<=80?t:`${t.slice(0,39)}…${t.slice(-39)}`}function Mx(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`.`,`\\.`)}function Nx(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}var Px=120;function Fx({line:e,status:t,clampLines:n}){let r=`min-w-0 whitespace-pre-wrap break-words ${n?`block overflow-hidden`:``}`,i=zx(e.tokens),a=i.length>Px;return(0,L.jsxs)(`div`,{className:`grid grid-cols-[1.9rem_minmax(0,1fr)] gap-2 leading-[1.45]`,children:[(0,L.jsx)(`span`,{className:`whitespace-pre ${Lx(e.prefix,t)}`,children:Ix(e.prefix)}),(0,L.jsxs)(`span`,{className:r,style:n?{maxHeight:`${n*1.45}em`}:void 0,children:[a?(0,L.jsx)(`span`,{className:`text-[#d4d4d4]`,children:i.map(e=>e.text).join(``)}):i.map((e,t)=>(0,L.jsx)(`span`,{className:Rx(e),children:e.text},`${t}:${e.text}`)),e.functionCall?(0,L.jsx)(Dx,{name:e.functionCall.name,input:e.functionCall.input}):null]})]})}function Ix(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 Rx(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 zx(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 Bx(e,t){return A(`/api/chat/loops/session-goal?${new URLSearchParams({piboSessionId:e}).toString()}`,t)}async function Vx(e,t={}){let n=new URLSearchParams({piboSessionId:e});return t.status&&n.set(`status`,t.status),t.limit&&n.set(`limit`,String(t.limit)),t.scope&&n.set(`scope`,t.scope),A(`/api/web-annotations?${n.toString()}`)}async function Hx(e,t){return A(`/api/web-annotations/${encodeURIComponent(e)}`,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify(Kx(t))})}async function Ux(e){let t=new URLSearchParams;return e?.trim()&&t.set(`cdpUrl`,e.trim()),A(`/api/web-annotations/targets${t.size?`?${t.toString()}`:``}`)}async function Wx(e){return A(`/api/web-annotations/bindings`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(Kx(e))})}async function Gx(e,t){return A(`/api/web-annotations/bindings/${encodeURIComponent(e)}/inject`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(Kx(t))})}function Kx(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0&&e!==``))}async function qx(e,t,n){return A(`/api/chat/projects/${encodeURIComponent(e)}/workflow-sessions/${encodeURIComponent(t)}/human-actions`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n)})}function Jx(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 Yx(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 Zx(e)?e.result:e}function Zx(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.type===`execution_result`}var Qx={device_code:`Device code`,api_key:`API key`,oauth:`Browser OAuth`};function $x({row:e,piboSessionId:t}){let n=Jx(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 N(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 N(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 N(t,`login.apikey`,{provider:e.id,apiKey:n}),l(``),a({type:`success`,provider:e,message:`${e.name} API key saved.`})}catch(t){a({type:`error`,provider:e,message:t instanceof Error?t.message:String(t)})}finally{s(!1)}}},[c,t]);return n?(0,L.jsx)(eS,{title:i.type===`select_provider`?`Login`:rS(i),tone:i.type===`error`?`red`:i.type===`success`?`green`:`cyan`,action:i.type===`select_provider`?void 0:(0,L.jsx)(tS,{onClick:m,disabled:o}),children:i.type===`select_provider`?(0,L.jsxs)(`div`,{className:`grid gap-2`,children:[(0,L.jsxs)(`div`,{className:`text-[11px] text-[#737373]`,children:[`Choose a provider. Use `,(0,L.jsx)(`span`,{className:`text-[#38bdf8]`,children:`/login`}),` anytime.`]}),(0,L.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:r.map(e=>(0,L.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,L.jsx)(`span`,{children:e.name}),e.configured?(0,L.jsx)(`span`,{className:`text-[#22c55e]`,children:`●`}):null]},e.id))})]}):i.type===`select_method`?(0,L.jsxs)(`div`,{className:`grid gap-2`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px]`,children:[(0,L.jsx)(`span`,{className:`text-[#737373]`,children:`Provider:`}),(0,L.jsx)(`span`,{className:`text-[#d4d4d4]`,children:i.provider.name}),i.provider.configured?(0,L.jsx)(nS,{tone:`green`,children:`Configured`}):(0,L.jsx)(nS,{tone:`neutral`,children:`Not configured`})]}),(0,L.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:i.provider.authMethods.map(e=>(0,L.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,L.jsx)(tt,{size:11}):(0,L.jsx)(ot,{size:11}),Qx[e]]},e))})]}):i.type===`device_starting`?(0,L.jsxs)(`div`,{className:`inline-flex items-center gap-2 text-[11px] text-[#38bdf8]`,children:[(0,L.jsx)(at,{size:13,className:`animate-spin`}),` Starting device login...`]}):i.type===`device_flow`?(0,L.jsxs)(`div`,{className:`grid gap-2 text-[11px]`,children:[(0,L.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,L.jsx)(`span`,{className:`text-[#737373]`,children:`Open:`}),(0,L.jsxs)(`a`,{href:i.url,target:`_blank`,rel:`noreferrer`,className:`inline-flex items-center gap-1 text-[#38bdf8] hover:underline`,children:[iS(i.url),` `,(0,L.jsx)(Ke,{size:11})]}),(0,L.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,L.jsx)(ze,{size:10}):(0,L.jsx)(Ue,{size:10}),` `,f===i.url?`Copied`:`Copy`]})]}),i.userCode?(0,L.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,L.jsx)(`span`,{className:`text-[#737373]`,children:`Code:`}),(0,L.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,L.jsx)(`span`,{className:`text-[#737373]`,children:`then`}),(0,L.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,L.jsx)(at,{size:11,className:`animate-spin`}):(0,L.jsx)(ze,{size:11}),` Complete`]})]}):(0,L.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,L.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,L.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,L.jsx)(at,{size:11,className:`animate-spin`}):(0,L.jsx)(ze,{size:11}),` Complete`]})]}),i.instructions?(0,L.jsx)(`div`,{className:`text-[#737373]`,children:i.instructions}):null]}):i.type===`api_key`?(0,L.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 text-[11px]`,children:[(0,L.jsx)(`span`,{className:`text-[#737373]`,children:`API key:`}),(0,L.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,L.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,L.jsx)(at,{size:11,className:`animate-spin`}):(0,L.jsx)(ze,{size:11}),` Save`]})]}):i.type===`success`?(0,L.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px] text-[#22c55e]`,children:[(0,L.jsx)(ze,{size:13}),` `,i.message]}):(0,L.jsxs)(`div`,{className:`flex items-start gap-2 text-[11px] text-[#ef4444]`,children:[(0,L.jsx)(Le,{size:13,className:`mt-0.5 shrink-0`}),` `,(0,L.jsx)(`span`,{children:i.message})]})}):(0,L.jsx)(eS,{title:`Login`,tone:`red`,children:`Unparseable login payload.`})}function eS({title:e,tone:t,action:n,children:r}){return(0,L.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,L.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[(0,L.jsx)(ot,{size:14,className:t===`red`?`text-[#ef4444]`:t===`green`?`text-[#22c55e]`:`text-[#38bdf8]`}),(0,L.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:e}),n?(0,L.jsx)(`div`,{className:`ml-auto`,children:n}):null]}),r]})}function tS({onClick:e,disabled:t}){return(0,L.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,L.jsx)(Ce,{size:10}),` Back`]})}function nS({tone:e,children:t}){return(0,L.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 rS(e){return`provider`in e&&e.provider?e.provider.name:`Login`}function iS(e){try{let t=new URL(e);return`${t.host}${t.pathname}`}catch{return e.length>42?`${e.slice(0,39)}...`:e}}function aS({row:e,piboSessionId:t,onModelChanged:n}){let r=Xx(e.output),i=(Yx(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 j(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,L.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,L.jsx)(`div`,{className:`flex items-center justify-between gap-3 border-b border-[#2a2a2a] px-3 py-2`,children:(0,L.jsxs)(`div`,{children:[(0,L.jsx)(`div`,{className:`text-[#d4d4d4]`,children:`Model`}),(0,L.jsxs)(`div`,{className:`text-[11px] text-[#737373]`,children:[`Choose a model from authenticated providers. Use `,(0,L.jsx)(`span`,{className:`text-[#38bdf8]`,children:`/login`}),` to add providers.`]})]})}),(0,L.jsxs)(`div`,{className:`space-y-2 p-3`,children:[i.length?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(`label`,{className:`flex items-center gap-2 border border-[#2a2a2a] bg-[#0b0b0b] px-2 py-1 text-[#737373]`,children:[(0,L.jsx)(mt,{size:13}),(0,L.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,L.jsx)(`div`,{className:`max-h-72 overflow-auto border border-[#2a2a2a]`,children:m.length?m.map(e=>(0,L.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,L.jsx)(`span`,{className:`truncate text-[#737373]`,children:e.providerLabel}),(0,L.jsxs)(`span`,{className:`min-w-0`,children:[(0,L.jsx)(`span`,{className:`block truncate text-[#d4d4d4]`,children:e.label}),(0,L.jsxs)(`span`,{className:`block truncate text-[11px] text-[#737373]`,children:[e.provider,`/`,e.id]})]}),c?.provider===e.provider&&c?.id===e.id?(0,L.jsx)(Ae,{size:14,className:`text-[#22c55e]`}):null]},`${e.provider}:${e.id}`)):(0,L.jsx)(`div`,{className:`px-3 py-2 text-[#737373]`,children:`No matching models.`})})]}):(0,L.jsxs)(`div`,{className:`text-[#737373]`,children:[`No authenticated model providers found. Run `,(0,L.jsx)(`span`,{className:`text-[#38bdf8]`,children:`/login`}),` first.`]}),f?(0,L.jsx)(`div`,{className:`text-[11px] text-[#a3a3a3]`,children:f}):null]})]})}function oS(e={}){let t=[],n=[],r=pS(e.warnings),i=pS(e.errors);(e.session?.id||e.session?.title)&&t.push({id:`session`,label:`Session`,value:sS([e.session?.title,e.session?.id].filter(Boolean).join(` | `))}),e.session?.profile&&t.push({id:`profile`,label:`Profile`,value:sS(e.session.profile)}),e.session?.status&&t.push({id:`session-status`,label:`Session status`,value:sS(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:sS(e.model.label??[e.model.provider,e.model.id].filter(Boolean).join(`/`))}),e.runtime?.state&&t.push({id:`runtime`,label:`Runtime`,value:sS(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:sS(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:sS(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`?sS(e.fastMode):e.fastMode?`on`:`off`,tone:e.fastMode?`green`:`neutral`});let o=pS(e.tools?.enabled),s=pS(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:sS(e.providerUsage.planType)}),e.providerUsage?.credits&&t.push({id:`provider-credits`,label:`Credits`,value:e.providerUsage.credits.unlimited?`unlimited`:sS(e.providerUsage.credits.balance??`available`)}),e.message&&t.push({id:`message`,label:`Message`,value:sS(e.message)}),n.push(cS(e.contextUsage));for(let t of lS(e.providerUsage))n.push(t);return{kind:`status`,title:`Status`,fields:t,progress:n,warnings:r,errors:i}}function sS(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 cS(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=uS(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:dS(t)}}function lS(e){return e?.limits?.length?e.limits.map((t,n)=>{let r=uS(t.usedPercent),i=uS(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 ${sS(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:fS(i)}}):[{id:`provider`,label:`Provider quota`,state:`unavailable`,text:`Provider usage unavailable`,tone:`neutral`}]}function uS(e){if(!(typeof e!=`number`||!Number.isFinite(e)))return Math.max(0,Math.min(100,e))}function dS(e){return e===void 0?`neutral`:e>=80?`red`:e>=50?`yellow`:`green`}function fS(e){return e===void 0?`neutral`:e<=20?`red`:e<=50?`yellow`:`green`}function pS(e){return(e??[]).map(e=>sS(e)).filter(e=>e.length>0)}function mS(e){switch(e.kind){case`tool.status`:return hS(e);case`tool.thinking`:return gS(e);case`tool.model`:return _S(e);case`tool.login`:return vS(e);case`tool.call`:case`tool.image`:case`tool.group.exploring`:case`tool.group.images`:return yS(e);case`yielded.run`:return bS(e,`yielded-run`,`Yielded run`,e.status===`error`?`red`:e.status===`running`?`cyan`:`green`);case`execution.compaction`:return bS(e,`compaction`,e.status===`error`?`Compaction failed`:e.status===`running`?`Compacting`:`Compaction`,e.status===`error`?`red`:`magenta`);case`execution.command`:return bS(e,`command`,`Command`,e.status===`error`?`red`:`yellow`);case`error`:return bS(e,`error`,`Error`,`red`);default:return}}function hS(e){let t=SS(e.output),n=CS(t,`activeModel`)??CS(t,`model`),r=oS({session:{id:ES(t,`piboSessionId`)??ES(t,`sessionId`),title:ES(t,`sessionTitle`)??ES(t,`title`),profile:ES(t,`profile`)??ES(t,`activeAgentId`)??ES(t,`agentId`),status:OS(t,`disposed`)?`disposed`:ES(t,`sessionStatus`)},model:n?{provider:ES(n,`provider`),id:ES(n,`id`),label:ES(n,`label`)}:void 0,runtime:{state:OS(t,`disposed`)?`disposed`:OS(t,`processing`)?`processing`:OS(t,`streaming`)?`streaming`:ES(t,`mode`)??`idle`,connected:OS(t,`connected`),queuedMessages:DS(t,`queuedMessages`),processing:OS(t,`processing`),streaming:OS(t,`streaming`),disposed:OS(t,`disposed`)},cwd:ES(t,`cwd`),contextUsage:CS(t,`contextUsage`),providerUsage:CS(t,`providerUsage`),tools:{enabled:TS(t,`enabledTools`),active:TS(t,`activeTools`)},thinking:ES(t,`thinkingLevel`)?{level:ES(t,`thinkingLevel`)}:void 0,fastMode:OS(t,`fastMode`),warnings:TS(t,`warnings`),errors:TS(t,`errors`),message:ES(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 gS(e){let t=SS(e.output),n=ES(t,`level`)??`unknown`,r=t?.supported!==!1,i=TS(t,`availableLevels`);return{id:e.id,kind:`thinking`,title:`Thinking`,status:e.status,tone:r?`yellow`:`red`,rows:[{label:`Current`,value:sS(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 _S(e){let t=wS(SS(e.output),`providers`),n=t.flatMap(e=>{let t=ES(e,`id`)??ES(e,`provider`)??`provider`,n=ES(e,`label`)??ES(e,`name`)??t;return wS(e,`models`).map(e=>{let r=ES(e,`id`)??`model`,i=ES(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 vS(e){let t=wS(SS(e.output),`providers`),n=t.map(e=>{let t=ES(e,`id`)??`provider`;return{id:`login:${t}`,label:ES(e,`name`)??ES(e,`label`)??t,action:`login.selectProvider`,value:t,description:TS(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 yS(e){return bS(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 bS(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?``:` ${xS(e.functionCall.input)}`}`:``}`.trim();return t?[{value:sS(t)}]:[]}),a=e.lines.length===0&&typeof e.output==`string`&&e.output.trim()?[{value:sS(e.output.trim())}]:[],o=[e.error?{label:`Error`,value:sS(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 xS(e){try{return JSON.stringify(e)}catch{return String(e)}}function SS(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 CS(e,t){let n=e?.[t];return n&&typeof n==`object`&&!Array.isArray(n)?n:void 0}function wS(e,t){let n=e?.[t];return Array.isArray(n)?n.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e)):[]}function TS(e,t){let n=e?.[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function ES(e,t){let n=e?.[t];return typeof n==`string`?n:void 0}function DS(e,t){let n=e?.[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function OS(e,t){let n=e?.[t];return typeof n==`boolean`?n:void 0}var kS={transcript:0,"event-log":1,live:2},AS={"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 jS(e,t){return{sourceRank:kS[`event-log`],turnSeq:e??2**53-1,eventSequence:e,phaseRank:AS[t]}}function MS(e,t,n){let r=e??2**53-1,i=t??2**53-1;return{sourceRank:kS.live,turnSeq:r,streamId:r,streamFrameIndex:i,phaseRank:AS[n]}}function NS(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 PS(e,t){if(e)return{...e,contentPartIndex:(e.contentPartIndex??0)+.1,phaseRank:AS[t]}}function FS(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 IS(e){let t=!1,n=e.map(e=>e.children.length?(t=!0,{...e,children:IS(e.children)}):e);return LS(n)?t?n:[...e]:[...n].sort(RS)}function LS(e){for(let t=1;t<e.length;t+=1)if(RS(e[t-1],e[t])>0)return!1;return!0}function RS(e,t){if(e.orderKey&&t.orderKey&&e.orderKey.sourceRank===t.orderKey.sourceRank){let n=FS(e.orderKey,t.orderKey);if(n!==0)return n}else{let n=zS(e,t);if(n!==0)return n}let n=BS(e.startedAt,t.startedAt);if(n!==0)return n;let r=FS(e.orderKey,t.orderKey);return r===0?e.id.localeCompare(t.id):r}function zS(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 BS(e,t){return!e&&!t?0:e?t?e.localeCompare(t):-1:1}function VS(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 HS(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 IS([...t.values()].filter(e=>!n.has(e.id)))}function US(e,t,n,r){if(!WS(t))return;let i=r.get(e)?.filter(e=>e.metadata?.subagentToolName===t)??[],a=KS(n);return a?i.find(e=>e.metadata?.threadKey===a)?.id:i.length===1?i[0].id:void 0}function WS(e){return e.startsWith(`pibo_subagent_`)}function GS(e){return e.slice(14)}function KS(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 qS(e,t,n,r){let i=YS(e,t,n,r);if(!i)return;let a=e.children.find(e=>e.id===i.id);if(a){ZS(a,i),a.runId=i.runId??a.runId;return}e.children.push(i)}function JS(e){let t=new Map;for(let n of VS(e)){let e=QS(n.output);if(!e)continue;let r=eC(e.runId);r&&t.set(r,{snapshot:e,completedAt:eC(e.completedAt)??eC(e.updatedAt)??n.completedAt})}for(let n of VS(e)){if(n.type!==`agent.async`||!n.runId)continue;let e=t.get(n.runId);if(!e)continue;let r=eC(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=eC(e.snapshot.summary)??n.error))}}function YS(e,t,n,r){if(!XS(e))return;let i=QS(e.output),a=nC(e.input)?e.input:{},o=eC(i?.toolName)??eC(a.toolName)??r?.title;if(!o||!WS(o))return;let s=eC(r?.summary)??GS(o),c=eC(i?.runId),l=eC(i?.status),u=a.arguments,d=eC(i?.completionPolicy)??eC(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:tC(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:nC(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:PS(e.orderKey,`agent.async`),children:[]}}function XS(e){return e.type===`tool.call`&&e.title===`pibo_run_start`}function ZS(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 QS(e){if(nC(e)){if($S(e))return e;if(nC(e.details)&&$S(e.details))return e.details}}function $S(e){return typeof e.runId==`string`&&typeof e.toolName==`string`}function eC(e){return typeof e==`string`?e:void 0}function tC(e,t){return e.status===`error`||t===`failed`?`error`:t===`completed`||t===`cancelled`?`done`:`running`}function nC(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function rC(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 iC(e){let t=aC(e.notification),n=t.length===1?t[0]:void 0,r=sC(e.notification.failed)+sC(e.notification.timedOut),i=sC(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:cC(e.notification),output:e.notification,source:e.source,stableKey:e.stableKey??e.id,orderKey:e.orderKey,children:[]}}function aC(e){return[...oC(e.completed),...oC(e.failed),...oC(e.timedOut),...oC(e.cancelled),...oC(e.running)]}function oC(e){return Array.isArray(e)?e.filter(lC):[]}function sC(e){return Array.isArray(e)?e.length:0}function cC(e){let t=[[sC(e.completed),`completed`],[sC(e.failed),`failed`],[sC(e.timedOut),`timed out`],[sC(e.cancelled),`cancelled`],[sC(e.running),`running`]].filter(([e])=>Number(e)>0).map(([e,t])=>`${e} ${t}`);return t.length?t.join(`, `):`No yielded run updates`}function lC(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function uC(e,t,n,r,i,a,o,s,c){let l=r.payload,u=o?_C(e,r):void 0;if(u){l.type===`message_steered`&&l.activeEventId&&(u.parentId=RC(l.activeEventId));return}if(o&&MC(l)&&!NC(l,s)||o&&PC(l,c))return;if(l.type===`assistant_delta`){TC(e,t,l,c,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex);return}if(l.type===`thinking_delta`){OC(e,t,l,c,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex);return}if(l.type===`assistant_message`){let i=dC(n,l,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex),a=t.get(i.id)??EC(t,i);if(a){DC(a,i);return}e.push(i),t.set(i.id,i);return}let d=wC(n,l,i,a,c,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex);if(d){if(d.type===`user.message`&&d.status===`running`&&!d.parentId&&l.type===`message_steered`){let e=[...t.values()].reverse().find(e=>e.type===`agent.turn`&&e.status===`running`);e&&(d.parentId=e.id)}if(d.type===`agent.turn`&&d.eventId){let e=[...t.values()].find(e=>e.type===`agent.turn`&&e.eventId===d.eventId);if(e){e.status=d.status,e.completedAt=d.completedAt??e.completedAt;return}}if(d.type===`assistant.message`){let e=t.get(d.id)??EC(t,d);if(e){DC(e,d);return}}if(d.type===`execution.compaction`){let t=XC(e);if(t){ZC(t,d);return}}if(d.type===`model.reasoning`){let e=t.get(d.id)??EC(t,d);if(e){kC(e,d);return}}if(d.type===`agent.delegation`&&!d.toolCallId&&d.linkedPiboSessionId){let e=GC([...t.values()],d);if(e){WC(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`){qS(e,n,r.createdAt,d);return}UC(e,d),qS(e,n,r.createdAt);return}}if(d.eventId){let e=t.get(d.id);if(e){d.type===`user.message`&&(e.status=d.status,e.parentId=d.parentId??e.parentId,e.summary=d.summary??e.summary,e.output=d.output??e.output);return}}fC(d,t),qS(d,n,r.createdAt),e.push(d);for(let e of VS([d]))t.set(e.id,e)}}function dC(e,t,n,r,i,a){let o=typeof t.eventId==`string`?t.eventId:void 0,s=BC(t);return{id:s?zC(s):`event:${t.type}:${nw(t)}`,piboSessionId:e,eventId:o,parentId:o?RC(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}`:LC(t),orderKey:FC(r,t.type,i,a),children:[]}}function fC(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=pC(n,t);return r===void 0||e.startedAt<=r}).sort(RS).at(-1);n&&(e.parentId=n.id)}function pC(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(RS).at(0)?.startedAt}function mC(e){return e.some(e=>{let t=e.payload.type;return t!==`assistant_delta`&&t!==`thinking_delta`})}function hC(e){if(e.type===`assistant_delta`){if(e.text.length===0)return;let t=BC(e);return t?zC(t):void 0}if(e.type===`thinking_delta`){if(e.text.length===0)return;let t=HC(e);return t?VC(t):void 0}}function gC(e,t){return!!_C(e,t)}function _C(e,t){let n=t.payload;if(n.type!==`message_queued`&&n.type!==`message_steered`||n.source!==`user`)return;let r=typeof n.eventId==`string`?n.eventId:void 0,i=r??t.eventId,a=`event:${n.type}:${r??nw(n)}`,o=LC(n),s=typeof n.text==`string`?n.text:void 0,c=VS([...e]).filter(e=>e.type===`user.message`&&e.source===`transcript`);return c.find(e=>vC(e,a,o,i))||c.find(e=>!yC(e)&&!!(s&&xC(e)===s))}function vC(e,t,n,r){return e.id===t||e.stableKey===n?!0:r?e.entryId===r||e.stableKey===`entry:${r}`?!0:[e.id,e.stableKey].some(e=>bC(e)===r):!1}function yC(e){return[e.id,e.stableKey].some(e=>bC(e)!==void 0)}function bC(e){for(let t of[`event:message_queued:`,`event:message_steered:`])if(e?.startsWith(t))return e.slice(t.length)}function xC(e){if(typeof e.output==`string`)return e.output;if(typeof e.summary==`string`)return e.summary}function SC(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 CC(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 wC(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??nw(t)}`,d=l?RC(l):void 0,f={id:u,piboSessionId:e,eventId:l,startedAt:a,source:`event-log`,stableKey:LC(t),orderKey:FC(o,t.type,s,c),children:[]};switch(t.type){case`message_queued`:case`message_steered`:{let n=rC(t.text);return t.source===`service`&&n?iC({id:u,piboSessionId:e,eventId:l,startedAt:a,source:`event-log`,stableKey:l?`run-notification:${l}`:u,orderKey:FC(o,t.type,s,c),notification:n}):{...f,...t.type===`message_steered`&&t.activeEventId?{parentId:RC(t.activeEventId)}:{},type:`user.message`,title:`User Message`,status:AC(t)?`running`:`done`,summary:t.text,output:t.text}}case`message_started`:case`message_finished`:return t.source===`service`?void 0:{...f,id:l?RC(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(!QC(t.text))return;let e=HC(t);return{...f,id:e?VC(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=BC(t);return{...f,id:e?zC(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=WS(t.toolName),s=r.get(t.toolCallId)??(o?US(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?$C(t.result):void 0,linkedPiboSessionId:s,stableKey:`tool:${t.toolCallId}`,children:[]}}case`subagent_session`:{let e=tw(t.childPiboSessionId),n=ew(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 jC(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=ew(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=ew(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 TC(e,t,n,r,i,a,o,s){if(typeof n.text!=`string`||n.text.length===0)return;let c=BC(n),l=c?zC(c):`event:assistant_delta:${nw(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?RC(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:FC(a,n.type,o,s),children:[]};e.push(d),t.set(d.id,d)}function EC(e,t){if(t.stableKey)return[...e.values()].find(e=>e.type===t.type&&e.stableKey===t.stableKey)}function DC(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 OC(e,t,n,r,i,a,o,s){if(typeof n.text!=`string`||n.text.length===0)return;let c=HC(n),l=c?VC(c):`event:thinking_delta:${nw(n)}`,u=c?`reasoning:${c}`:l,d=t.get(l)??[...t.values()].find(e=>e.type===`model.reasoning`&&e.stableKey===u);if(d){let e=`${typeof d.output==`string`?d.output:``}${n.text}`;d.status=r===`running`?`running`:`done`,d.summary=e,d.output=e;return}let f={id:l,parentId:n.eventId?RC(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:u,orderKey:FC(a,n.type,o,s),children:[]};e.push(f),t.set(f.id,f)}function kC(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 AC(e){return(e.type===`message_queued`||e.type===`message_steered`)&&`clientTxnId`in e&&typeof e.clientTxnId==`string`}function jC(e){return e===`session.fork`||e===`session.clone`||e===`session.switch`}function MC(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 NC(e,t){let n=`eventId`in e&&typeof e.eventId==`string`?e.eventId:void 0;return!!(n&&t.has(n))}function PC(e,t){return t!==`running`&&e.type===`tool_call`}function FC(e,t,n,r){return e===void 0&&(n!==void 0||r!==void 0)?MS(n,r,IC(t)):jS(e,IC(t))}function IC(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 LC(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=HC(e);if(t)return`reasoning:${t}`}if(e.type===`assistant_delta`||e.type===`assistant_message`){let t=BC(e);if(t)return`assistant:${t}`}return`event:${e.type}:${t??nw(e)}`}function RC(e){return`event:message:${e}`}function zC(e){return`event:assistant:${e}`}function BC(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 VC(e){return`event:thinking:${e}`}function HC(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 UC(e,t){e.status=t.status,e.summary=t.summary??e.summary,e.input=JC(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 WC(e,t){e.summary=t.summary??e.summary,e.input=JC(e,t),e.linkedPiboSessionId=t.linkedPiboSessionId??e.linkedPiboSessionId}function GC(e,t){let n=[...e].reverse().filter(e=>e.type===`agent.delegation`),r=KC(t),i=n.filter(e=>!e.linkedPiboSessionId&&KC(e)===r),a=qC(t.input);return(a?i.find(e=>qC(e.input)===a):i.length===1?i[0]:void 0)||n.find(e=>e.linkedPiboSessionId===t.linkedPiboSessionId)}function KC(e){let t=YC(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 qC(e){if(!(!YC(e)||typeof e.threadKey!=`string`))return e.threadKey.trim()||void 0}function JC(e,t){return e.type!==`agent.delegation`||!YC(e.input)||!YC(t.input)?t.input??e.input:Object.fromEntries(Object.entries({...e.input,...t.input}).filter(([,e])=>e!==void 0))}function YC(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function XC(e){return VS([...e]).reverse().find(e=>e.type===`execution.compaction`&&e.status===`running`)}function ZC(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 QC(e){return typeof e==`string`&&e.trim().length>0}function $C(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}function ew(e,t,n){return e===void 0?t===void 0?nw(n):`stream:${t}`:`sequence:${e}`}function tw(e){if(typeof e==`string`)return e.trim()||void 0}function nw(e){return rw(new TextEncoder().encode(JSON.stringify(e))).slice(0,48)}function rw(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 iw(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 IS(n)}function aw(e,t,n){return t.map(t=>ow(e,t,n))}function ow(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)||sw(r,t))?r:e?{...t,children:r.children}:{...t,children:[]}}let i=t.children.map(t=>ow(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)||sw(r,t))?r:a?{...t,children:r?.children??i}:{...t,children:i}}function sw(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&&cw(e.orderKey,t.orderKey)}function cw(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 lw(e,t,n){if(!t.length)return e;let r=new Set(e.rawEvents.map(e=>SC(e))),i=[];for(let e of t){let t=SC(e);r.has(t)||(r.add(t),i.push(e))}if(!i.length)return e;let a=VS(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(gC(o,t))continue;f.push(t);let r=hC(t.payload);p&&r?p.add(r):p=void 0,uC(o,s,e.piboSessionId,t,l,u,!1,d,n)}if(!f.length)return e;let m=iw(o);mC(f)&&JS(m);let h=aw(c,m,p);return{...e,rawEvents:e.rawEvents.length?[...e.rawEvents,...f]:f,nodes:h,latestStreamId:CC(f,e.latestStreamId)}}function uw(e,t){if(!e)return[];let n=pw(e.nodes),r=Kw(mw(e.nodes).sort((e,t)=>RS(e.node,t.node)).filter(e=>e.node.type!==`agent.turn`&&(t.showThinking||e.node.type!==`model.reasoning`)).map(e=>hw(e.node,e.turnId)));return yw(r,n),Yw(vw(r)).map(e=>e.row)}function dw(e){if(!e)return;let t=new Set(mw(e.nodes).map(({node:e})=>e).filter(e=>e.type===`error`&&e.eventId).map(e=>e.eventId));return[...pw(e.nodes).values()].filter(e=>e.startedAt&&!e.completedAt&&(!e.eventId||!t.has(e.eventId))).sort(RS).at(-1)?.startedAt}function fw(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 pw(e){let t=new Map;for(let n of e){n.type===`agent.turn`&&t.set(n.id,n);for(let[e,r]of pw(n.children))t.set(e,r)}return t}function mw(e,t){let n=[];for(let r of e)r.type!==`agent.turn`&&n.push({node:r,turnId:t}),n.push(...mw(r.children,r.type===`agent.turn`?r.id:t));return n}function hw(e,t){let n;switch(e.type){case`user.message`:n={row:Sw(e),turnId:t};break;case`assistant.message`:n={row:Cw(e),turnId:t};break;case`model.reasoning`:n={row:ww(e),turnId:t};break;case`tool.call`:n=Tw(e,t);break;case`tool.result`:n=Ow(e,t);break;case`agent.delegation`:n={row:Aw(e),turnId:t};break;case`agent.async`:n={row:jw(e),turnId:t};break;case`yielded.run`:n={row:Mw(e),turnId:t};break;case`execution.command`:n={row:Pw(e),turnId:t};break;case`execution.compaction`:n={row:Nw(e),turnId:t};break;case`error`:n={row:Ww(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:gw(e),...xw(e)}}}function gw(e){if(e.type===`tool.call`||e.type===`tool.result`||e.type===`agent.delegation`){let t=e.toolCallId??_w(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=_w(e.stableKey,`assistant:`);if(t)return`terminal:assistant:${t}`}if(e.type===`model.reasoning`){let t=_w(e.stableKey,`reasoning:`);if(t)return`terminal:reasoning:${t}`}return e.id}function _w(e,t){if(!e?.startsWith(t))return;let n=e.slice(t.length);return n&&n!==`undefined`?n:void 0}function vw(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 yw(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??bw(n.startedAt,n.completedAt))}}function bw(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 xw(e){return{eventId:e.eventId,runId:e.runId,orderSource:e.source,orderStreamId:e.orderKey?.streamId,orderStreamFrameIndex:e.orderKey?.streamFrameIndex,payloadRefs:e.payloadRefs}}function Sw(e){let t=AT(e.output)||AT(e.summary)||e.title;return{id:e.id,kind:`message.user`,status:OT(e.status),lines:[{prefix:`prompt`,tokens:[$(t)]}],sourceNodeIds:[e.id],forkEntryId:e.entryId,pendingMessageDelivery:ET(e),startedAt:e.startedAt,output:t,payloadRefs:e.payloadRefs}}function Cw(e){return{id:e.id,kind:`message.assistant`,status:OT(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:AT(e.output)||AT(e.summary)||``,error:e.error,payloadRefs:e.payloadRefs}}function ww(e){let t=hT(e.output??e.summary);return{id:e.id,kind:`reasoning`,status:OT(e.status),lines:[{prefix:`bullet`,tokens:[$(e.status===`running`?`Thinking`:`Thought`,`amber`,`semibold`)]}],sourceNodeIds:[e.id],markdown:t,payloadRefs:e.payloadRefs}}function Tw(e,t){let n=ST(e.input);if(n&&_T(e.title))return{row:Uw(e,n),turnId:t,exploring:void 0};if(vT(e.title))return{row:Ew(e),turnId:t};let r=eT(e);if(r)return{row:Dw(e,r),turnId:t,image:r.groupable?r.detail:void 0};let i=pT(e.error??e.output,5,e.error?`red`:`dim`);return{row:{id:e.id,kind:`tool.call`,status:OT(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(wT(e.status),kT(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:mT(i,e.error?`error`:`output`)},turnId:t,exploring:cT(e)}}function Ew(e){let t=OT(e.status),n=bT(e),r=xT(e.output),i=[{prefix:`bullet`,tokens:[$(yT(e.status),kT(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 Dw(e,t){let n=OT(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,kT(e.status),`semibold`)]},{prefix:`detail`,tokens:[$(r,e.status===`error`?`red`:`cyan`)]}],sourceNodeIds:[e.id],input:nT(e.input),output:t.summary,error:e.error,expandable:e.input!==void 0||t.summary!==void 0||!!e.error}}function Ow(e,t){let n=eT(e);return n?{row:Dw(e,n),turnId:t,image:n.groupable?n.detail:void 0}:{row:kw(e),turnId:t}}function kw(e){let t=pT(e.error??e.output,5,e.error?`red`:`dim`);return{id:e.id,kind:`tool.call`,status:OT(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(e.status===`error`?`Tool failed`:`Returned`,kT(e.status),`semibold`),$(` ${e.title}`)]},...t.lines],sourceNodeIds:[e.id],output:e.output,error:e.error,expandable:e.output!==void 0||!!e.error,previewOmission:mT(t,e.error?`error`:`output`)}}function Aw(e){let t=AT(jT(e.input)?e.input.subagentName:void 0)||e.summary||e.title,n=gT((jT(e.input)?e.input.arguments:void 0)??e.input),r=n?[{prefix:`detail`,tokens:[$(n,`dim`)]}]:[];return{id:e.id,kind:`agent.delegation`,status:OT(e.status),errorKind:e.status===`error`?`tool`:void 0,title:e.title,summary:e.summary,lines:[{prefix:`bullet`,tokens:[$(TT(e.status),kT(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 jw(e){let t=pT(e.error??e.output,5,e.error?`red`:`dim`);return{id:e.id,kind:`agent.async`,status:OT(e.status),lines:[{prefix:`bullet`,tokens:[$(DT(e.status),kT(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:mT(t,e.error?`error`:`output`)}}function Mw(e){let t=pT(e.output,5);return{id:e.id,kind:`yielded.run`,status:OT(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(e.status===`running`?`Waiting on runs`:`Run update`,kT(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:mT(t,`output`)}}function Nw(e){let t=e.status===`running`?`Compacting`:e.status===`error`?`Compaction failed`:AT(e.summary)||`Compacted`;return{id:e.id,kind:`execution.compaction`,status:OT(e.status),lines:[{prefix:`bullet`,tokens:[$(t,kT(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 Pw(e){if(e.title===`status`)return Fw(e);if(e.title===`thinking`)return Jw(e.output)?Lw(e):Iw(e);if(e.title===`fast_mode`)return Rw(e);if(e.title===`login`&&Vw(e.output))return zw(e);if(e.title===`model`&&Hw(e.output))return Bw(e);ST(e.output)??ST(e.input)??e.title;let t=pT(e.error??e.output,5,e.error?`red`:`dim`,180);return{id:e.id,kind:`execution.command`,status:OT(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:mT(t,e.error?`error`:`output`)}}function Fw(e){return{id:e.id,kind:`tool.status`,status:OT(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function Iw(e){return{id:e.id,kind:`tool.thinking`,status:OT(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function Lw(e){let t=jT(e.output)?e.output:void 0,n=AT(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:OT(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 Rw(e){let t=jT(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:OT(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 zw(e){return{id:e.id,kind:`tool.login`,status:OT(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function Bw(e){return{id:e.id,kind:`tool.model`,status:OT(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function Vw(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 Hw(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 Uw(e,t){let n=pT(e.error??e.output,5,e.error?`red`:`dim`,180);return{id:e.id,kind:`execution.command`,status:OT(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(e.status===`running`?`Running`:`Ran`,kT(e.status),`semibold`),$(` `),...CT(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:mT(n,e.error?`error`:`output`)}}function Ww(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`)]},...Gw(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 Gw(e){return jT(e)?[[`Class`,AT(e.errorClass)??AT(e.category)],[`Code`,AT(e.code)??AT(e.providerCode)],[`Origin`,AT(e.origin)],[`Provider`,[AT(e.api),AT(e.provider),AT(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 Kw(e){let t=e.map(e=>e.row.output).filter(qw).at(-1);return t?e.map(e=>e.row.kind!==`tool.thinking`||!jT(e.row.output)?e:{...e,row:{...e.row,output:{...e.row.output,level:t.level,availableLevels:t.availableLevels,supported:t.supported}}}):[...e]}function qw(e){return jT(e)&&typeof e.level==`string`&&Array.isArray(e.availableLevels)}function Jw(e){return jT(e)&&e.action===`set_thinking_level`}function Yw(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n],i=Xw(r);if(!i){t.push(r);continue}let a=[r],o=n+1;for(;o<e.length&&Xw(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`?Qw(a):Zw(a),turnId:r.turnId}),n=o-1}return t}function Xw(e){if(e.image)return`images`;if(e.exploring)return`exploring`}function Zw(e){let t=$w(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`,kT(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 Qw(e){let t=$w(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`,kT(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 $w(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 eT(e){let t=(e.title??``).trim().toLowerCase(),n=jT(e.input)?e.input:void 0,r=jT(e.output)?e.output:void 0,i=sT(r,`details`),a=t===`codex_image_generation`?iT(i)??aT(n):void 0,o=a?AT(i?.savedPath)??uT(i):uT(n)??uT(i)??uT(r),s=a?AT(i?.artifactId):void 0,c=dT(n),l=tT(e.output),u=lT(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?AT(i?.model):void 0,referencedImageCount:a?fT(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?oT(e.status,a):rT(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:OT(e.status),input:nT(e.input),output:p,error:e.error}}}function tT(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=>tT(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`||jT(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=>tT(e,t+1,n))}function nT(e){if(Array.isArray(e))return e.map(nT);if(!jT(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]=nT(r)}return t}function rT(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 iT(e){let t=AT(e?.operation);return t===`generate`||t===`edit`?t:void 0}function aT(e){if(!e)return;let t=e.referenced_image_paths;return Array.isArray(t)&&t.length>0||fT(e.num_last_images_to_include)!==void 0?`edit`:`generate`}function oT(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 sT(e,t){let n=e?.[t];return jT(n)?n:void 0}function cT(e){let t=(e.title??``).trim().toLowerCase(),n=jT(e.input)?e.input:void 0;if(lT(t,[`read`,`open`]))return{id:e.id,label:`Read ${uT(n)??gT(e.input)}`,status:OT(e.status),input:e.input,output:e.output,error:e.error};if(lT(t,[`list`,`ls`,`glob`]))return{id:e.id,label:`List ${uT(n)??gT(e.input)}`,status:OT(e.status),input:e.input,output:e.output,error:e.error};if(lT(t,[`search`,`find`,`grep`,`rg`])){let t=dT(n),r=uT(n);return{id:e.id,label:`Search ${t??gT(e.input)}${r?` in ${r}`:``}`,status:OT(e.status),input:e.input,output:e.output,error:e.error}}}function lT(e,t){return t.some(t=>e===t||e.startsWith(`${t}_`)||e.endsWith(`_${t}`)||e.includes(t))}function uT(e){if(e)for(let t of[`path`,`file`,`filePath`,`filepath`,`url`,`uri`,`cwd`,`pattern`,`glob`]){let n=AT(e[t]);if(n)return n}}function dT(e){if(e)for(let t of[`query`,`pattern`,`text`,`name`,`q`,`regex`]){let n=AT(e[t]);if(n)return n}}function fT(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function pT(e,t,n=`dim`,r=160){let i={lines:[],visibleLineCount:0,omittedLineCount:0,totalLineCount:0,maxVisibleLineCount:t},a=hT(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 mT(e,t){if(!(e.omittedLineCount<=0))return{source:t,visibleLineCount:e.visibleLineCount,omittedLineCount:e.omittedLineCount,totalLineCount:e.totalLineCount,maxVisibleLineCount:e.maxVisibleLineCount}}function hT(e){let t=ox(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 gT(e){return(typeof e==`string`?e:hT(e)).replace(/\s+/g,` `).trim()}function _T(e){let t=(e??``).trim().toLowerCase();return t===`shell`||t===`bash`||t===`terminal`}function vT(e){return(e??``).trim().toLowerCase()===`web_search`}function yT(e){return e===`running`?`Searching web`:e===`error`?`Web search failed`:`Searched web`}function bT(e){let t=jT(e.input)?e.input:void 0,n=jT(e.output)?e.output:void 0;return AT(t?.query)??AT(n?.query)??AT(e.summary)}function xT(e){if(!jT(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 ST(e){if(jT(e))for(let t of[`cmd`,`command`,`script`]){let n=AT(e[t]);if(n)return n}}function CT(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 wT(e){return e===`running`?`Calling`:e===`error`?`Call failed`:`Called`}function TT(e){return e===`running`?`Spawning`:e===`error`?`Spawn failed`:`Spawned`}function ET(e){if(e.status===`running`){if(e.id.startsWith(`event:message_steered:`))return`steer`;if(e.id.startsWith(`event:message_queued:`))return`queue`}}function DT(e){return e===`running`?`Waiting for`:`Finished waiting for`}function OT(e){return e===`running`?`running`:e===`error`?`error`:`done`}function kT(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 AT(e){return typeof e==`string`&&e.trim().length?e:void 0}function jT(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function MT(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 NT(e,t,n){return n?{id:e,label:t,value:n}:void 0}function PT({field:e,icon:t}){let n=t===`session`?$e:Ye;return(0,L.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[11px]`,"data-shared-status-field":e.id,children:[(0,L.jsx)(n,{size:11,className:`shrink-0 text-[#737373]`}),(0,L.jsxs)(`span`,{className:`shrink-0 text-[#737373]`,children:[e.label,`:`]}),(0,L.jsx)(`span`,{className:`truncate font-mono ${e.id===`session`?`text-[#38bdf8]`:`text-[#d4d4d4]`}`,children:e.value})]})}function FT({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,L.jsxs)(`div`,{className:`mt-3 space-y-1`,"data-shared-progress":e.id,"data-shared-progress-state":e.state,children:[(0,L.jsxs)(`div`,{className:`flex items-center justify-between text-[11px]`,children:[(0,L.jsx)(`span`,{className:`text-[#737373]`,children:t??e.label}),(0,L.jsx)(`span`,{className:`font-mono text-[#d4d4d4]`,children:e.state===`available`?e.text:`unavailable`})]}),e.state===`available`?(0,L.jsx)(`div`,{className:`h-1.5 w-full overflow-hidden rounded-full bg-[#2a2a2a]`,children:(0,L.jsx)(`div`,{className:`h-full rounded-full ${r} transition-all`,style:{width:`${Math.min(Math.max(n,0),100)}%`}})}):null]})}function IT(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 LT({row:e}){let t=MT(e.output),n=mS(e),r=n?.kind===`status`?n.statusView:void 0,[i,a]=(0,v.useState)(!1);if(!t||!r)return(0,L.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,L.jsx)(`div`,{className:`text-[#737373]`,children:`Status (unparseable)`})});let o=new Map(r.fields.map(e=>[e.id,e])),s=o.get(`session`)??NT(`session`,`Session`,t.piboSessionId),c=o.get(`cwd`)??NT(`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,L.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,L.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[(0,L.jsx)(xe,{size:14,className:`text-[#22c55e]`}),(0,L.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:r.title})]}),(0,L.jsxs)(`div`,{className:`grid grid-cols-1 gap-1.5 sm:grid-cols-2`,children:[s?(0,L.jsx)(PT,{field:s,icon:`session`}):null,c?(0,L.jsx)(PT,{field:c,icon:`cwd`}):null,p.slice(0,8).map(e=>(0,L.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[11px]`,"data-shared-status-field":e.id,children:[(0,L.jsxs)(`span`,{className:`shrink-0 text-[#737373]`,children:[e.label,`:`]}),(0,L.jsx)(`span`,{className:`truncate font-mono text-[#d4d4d4]`,children:e.value})]},e.id))]}),(0,L.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-1.5`,children:[t.processing?(0,L.jsxs)(`span`,{className:`inline-flex items-center gap-1 border border-[#1f4960] px-1.5 py-0.5 text-[11px] text-[#38bdf8]`,children:[(0,L.jsx)(We,{size:10}),` Processing`]}):null,t.streaming?(0,L.jsxs)(`span`,{className:`inline-flex items-center gap-1 border border-[#1f4960] px-1.5 py-0.5 text-[11px] text-[#38bdf8]`,children:[(0,L.jsx)(xe,{size:10}),` Streaming`]}):null,typeof t.queuedMessages==`number`&&t.queuedMessages>0?(0,L.jsxs)(`span`,{className:`inline-flex items-center gap-1 border border-[#3a3a3a] px-1.5 py-0.5 text-[11px] text-[#d4d4d4]`,children:[(0,L.jsx)(nt,{size:10}),` Queued: `,t.queuedMessages]}):null,t.disposed?(0,L.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,L.jsx)(FT,{progress:l,label:`Context Usage`}):null,u.length?(0,L.jsxs)(`div`,{className:`mt-3 space-y-1.5 border-t border-[#2a2a2a] pt-2`,"data-shared-provider-progress":u.length,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[11px] text-[#737373]`,"data-shared-status-field":`provider-quota`,children:[(0,L.jsx)(Xe,{size:11}),(0,L.jsxs)(`span`,{children:[m,t.providerUsage?.planType?` (${t.providerUsage.planType})`:``]})]}),d?d.map(e=>{let t=IT(e.resetsAt);return(0,L.jsxs)(`div`,{className:`space-y-1`,"data-shared-progress":`provider-limit:${e.label}`,"data-shared-progress-state":`available`,children:[(0,L.jsxs)(`div`,{className:`flex items-center justify-between gap-2 text-[11px]`,children:[(0,L.jsx)(`span`,{className:`text-[#a3a3a3]`,children:e.label}),(0,L.jsxs)(`span`,{className:`shrink-0 font-mono text-[#d4d4d4]`,children:[e.remainingPercent.toFixed(0),`% left`,t?` · resets ${t}`:``]})]}),(0,L.jsx)(`div`,{className:`h-1.5 w-full overflow-hidden rounded-full bg-[#2a2a2a]`,children:(0,L.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,L.jsx)(FT,{progress:e},e.id)),t.providerUsage?.credits?(0,L.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,L.jsxs)(`div`,{className:`mt-3 space-y-1 border-t border-[#2a2a2a] pt-2`,children:[r.warnings.map((e,t)=>(0,L.jsxs)(`div`,{"data-shared-status-warning":!0,className:`text-[11px] text-[#facc15]`,children:[`⚠ `,e]},`warning-${t}`)),r.errors.map((e,t)=>(0,L.jsxs)(`div`,{"data-shared-status-error":!0,className:`text-[11px] text-[#ef4444]`,children:[`✕ `,e]},`error-${t}`))]}):null,f.length>0?(0,L.jsxs)(`div`,{className:`mt-3`,children:[(0,L.jsxs)(`button`,{type:`button`,onClick:()=>a(e=>!e),className:`flex items-center gap-1.5 text-[11px] text-[#737373] hover:text-[#d4d4d4]`,children:[(0,L.jsx)(`span`,{className:`text-[#d4d4d4]`,children:i?`▾`:`▸`}),(0,L.jsxs)(`span`,{children:[`Enabled tools (`,f.length,`)`]})]}),i?(0,L.jsx)(`div`,{className:`mt-1.5 flex flex-wrap gap-1`,children:f.map(e=>(0,L.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 zT(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 BT(e){return RT.includes(e)?e:void 0}function VT({row:e,onLevelSelect:t}){let n=zT(e.output);return n?(0,L.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,L.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[(0,L.jsx)(Oe,{size:14,className:`text-[#f59e0b]`}),(0,L.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:`Thinking`}),n.supported===!1?(0,L.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,L.jsx)(xt,{size:10}),` Unsupported`]}):(0,L.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,L.jsx)(Ae,{size:10}),` Supported`]})]}),(0,L.jsxs)(`div`,{className:`grid gap-1.5 text-[11px]`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,L.jsx)(`span`,{className:`text-[#737373]`,children:`Current:`}),(0,L.jsx)(`span`,{className:`font-mono font-semibold text-[#f59e0b]`,children:n.level??`unknown`})]}),n.availableLevels.length?(0,L.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,L.jsx)(`span`,{className:`mr-1 text-[#737373]`,children:`Available:`}),n.availableLevels.map(e=>{let r=BT(e),i=n.supported===!1||!r||!t;return(0,L.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,L.jsxs)(`div`,{className:`text-[#737373]`,children:[`Click a level or use `,(0,L.jsx)(`span`,{className:`text-[#f59e0b]`,children:`/thinking <level>`}),`.`]})]})]}):(0,L.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,L.jsx)(`div`,{className:`text-[#737373]`,children:`Thinking (unparseable)`})})}var HT=`pibo.chat.terminalReadingPosition.`;function UT(e){if(e)try{return GT(sessionStorage.getItem(HT+e))}catch{return}}function WT(e,t){if(e)try{let n=HT+e;t?sessionStorage.setItem(n,JSON.stringify(t)):sessionStorage.removeItem(n)}catch{}}function GT(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 KT=180,qT=4800,JT=20,YT={index:`LAST`,align:`end`},XT={top:2400,bottom:2400},ZT=84,QT=700,$T=6;function eE({traceView:e,isLoading:t,terminalFullscreen:n,showThinking:r,expandThinking:i,sessionAgentProfile:a,sessionActiveModel:o,selectedSessionStatus:s,selectedSessionSignal:c,signals:l,sessionGoal:u,sessionBreadcrumbs:d,originSession:f,derivedSessions:p,agentProfiles:m,sessionProfileChangeDisabled:h,onSessionAgentProfileChange:g,onFork:_,onOpenSession:y,onLoadOlderTracePage:b,hasOlderTraceEvents:x,isFetchingOlderTracePage:S,onThinkingLevelChange:C,onModelChanged:w}){let T=(0,v.useMemo)(()=>uw(e,{showThinking:r}),[r,e]),E=(0,v.useMemo)(()=>T.map(e=>e.id),[T]),D=e?.piboSessionId??``,[O,k]=(0,v.useState)(),A=(0,v.useRef)(void 0),[ee,te]=(0,v.useState)(new Set),j=(0,v.useMemo)(()=>[T,ee],[ee,T]),[M,ne]=(0,v.useState)(null),N=(0,v.useRef)({}),P=(0,v.useRef)(!1),re=(0,v.useRef)(!1),ie=(0,v.useRef)(void 0),ae=(0,v.useRef)(!1),oe=(0,v.useRef)(!1),se=(0,v.useRef)(!1),ce=(0,v.useRef)(()=>void 0),le=T.filter(e=>dE(e,`user`)).length,F=T.filter(e=>dE(e,`tool`)).length,ue=T.filter(e=>dE(e,`system`)).length,de=ex({signal:c,fallbackStatus:s,fallbackTurnStartedAt:(0,v.useMemo)(()=>dw(e),[e])}),fe=de.activeTurnStartedAt,pe=de.isTurnActive,me=!!rx(u);(0,v.useLayoutEffect)(()=>{!D||!e||!jb()||Bb(D,`compact-terminal:render`,T,{traceVersion:e.version,latestStreamId:e.latestStreamId,lastRawEventId:e.rawEvents.at(-1)?.id,selectedSessionStatus:s})},[D,T,s,e]);let he=(0,v.useCallback)(e=>{if(!x||S||ae.current)return;if(oe.current){se.current=!0;return}let t=()=>{ie.current=void 0,!ae.current&&(ae.current=!0,re.current=!1,ce.current(),b?.())};if(!e||!re.current){ie.current!==void 0&&window.clearTimeout(ie.current),t();return}ie.current===void 0&&(ie.current=window.setTimeout(t,QT))},[x,S,b]),ge=(0,v.useCallback)(()=>{P.current&&re.current&&he(!0)},[he]),_e=(0,v.useCallback)(()=>{P.current&&he(!1)},[he]),ve=(0,v.useCallback)(e=>{if(oe.current=e,e){ie.current!==void 0&&(window.clearTimeout(ie.current),ie.current=void 0,se.current=!0);return}se.current&&(se.current=!1,he(!1))},[he]),ye=(0,v.useCallback)((e,t)=>{EE(e,t)&&(re.current=!0)},[]),be=(0,v.useCallback)(e=>{P.current&&(e.startIndex<=0?_e():e.startIndex<=JT&&ge())},[_e,ge]),I=(0,v.useCallback)(e=>{D&&WT(D,e?{rowId:e.key,offsetPx:e.offset}:void 0)},[D]),xe=qa({itemCount:T.length,itemKeys:E,isPrepending:S,resetKey:e?.piboSessionId,contentKey:j,atBottomThreshold:KT,nearTopThreshold:qT,onAtTop:_e,onNearTop:ge,onUserScrollIntent:ye,onScrollbarDragChange:ve,onVisibleAnchorChange:I});ce.current=xe.prepareForPrepend,(0,v.useEffect)(()=>{A.current=void 0,ae.current=!1,oe.current=!1,se.current=!1,k(D?UT(D):void 0)},[D]),(0,v.useEffect)(()=>{ae.current=!1},[e?.nextBeforeCursor,e?.nextBeforeSequence]),(0,v.useEffect)(()=>()=>{ie.current!==void 0&&window.clearTimeout(ie.current)},[]),(0,v.useEffect)(()=>{if(!D||!O)return;let t=E.indexOf(O.rowId);if(t>=0){let e=requestAnimationFrame(()=>{xe.restoreAnchor({key:O.rowId,dataIndex:t,offset:O.offsetPx})&&k(void 0)});return()=>cancelAnimationFrame(e)}if(!x){WT(D,void 0),k(void 0);return}if(S)return;let n=`${D}:${String(e?.nextBeforeCursor??e?.nextBeforeSequence??T.length)}`;A.current!==n&&(A.current=n,b?.())},[x,S,b,D,O,E,T.length,xe.restoreAnchor,e?.nextBeforeCursor,e?.nextBeforeSequence]),(0,v.useEffect)(()=>{if(!D)return;let e=()=>{xe.captureVisibleAnchor()};return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[D,xe.captureVisibleAnchor]),(0,v.useEffect)(()=>{te(e=>uE(e,T,i))},[i,T]),(0,v.useEffect)(()=>{S||xe.isScrolledToTop()&&_e()},[x,S,_e,T.length,xe.isScrolledToTop,e?.nextBeforeCursor,e?.nextBeforeSequence]),(0,v.useEffect)(()=>{P.current=!1,re.current=!1;let e=window.setTimeout(()=>{P.current=!0,xe.isScrolledToTop()&&_e()},250);return()=>window.clearTimeout(e)},[_e,xe.isScrolledToTop,e?.piboSessionId]),(0,v.useEffect)(()=>{let e=new Set(T.map(e=>e.id));ne(t=>t&&e.has(t)?t:null);for(let t of[`system`,`tool`,`user`]){let n=N.current[t];n&&!e.has(n)&&delete N.current[t]}},[T]);let Se=(0,v.useCallback)(e=>{let t=fE(T,e,N.current[e]);t&&(N.current[e]=t.row.id,ne(t.row.id),xe.scrollToIndex(t.index,`start`,`fast-smooth`,{fromIndex:t.fromIndex,stagingAlign:e===`tool`?`end`:void 0}),pE(t.row.id))},[T,xe]),Ce=e=>{e.expandable&&te(t=>{let n=new Set(t);return n.has(e.id)?n.delete(e.id):n.add(e.id),n})},we=(0,v.useCallback)((t,n)=>(0,L.jsx)(`div`,{className:`px-4`,children:(0,L.jsx)(rE,{row:n,expanded:ee.has(n.id),focused:M===n.id,piboSessionId:e?.piboSessionId??``,onToggle:()=>Ce(n),onFork:_,onOpenSession:y,onThinkingLevelChange:C,onModelChanged:w,signals:l})}),[ee,M,_,w,y,C,l,e?.piboSessionId]),Te=(0,v.useMemo)(()=>({Footer:pe||me?()=>(0,L.jsx)(vE,{startedAt:fe,isWorking:pe,goal:u}):void 0}),[fe,pe,u,me]);return(0,L.jsxs)(`section`,{className:`relative min-w-0 flex-1 flex flex-col overflow-hidden bg-[#0b0b0b] text-[#d4d4d4]`,"data-pibo-component":`CompactTerminalSessionView`,"data-pibo-debug":`compact-terminal-session-view`,"data-pibo-session-id":e?.piboSessionId??void 0,"data-pibo-terminal-fullscreen":n?`true`:`false`,"data-pibo-trace-has-older":e?.hasOlderEvents===!0?`true`:`false`,"data-pibo-trace-next-before":e?.nextBeforeCursor??e?.nextBeforeSequence??``,children:[n?null:(0,L.jsx)(tE,{errorCount:ue,toolErrorCount:F,userMessageCount:le,onNavigate:Se,sessionAgentProfile:a,sessionActiveModel:o,sessionBreadcrumbs:d,originSession:f,derivedSessions:p,onOpenSession:y}),(0,L.jsx)(`div`,{className:`min-h-0 flex-1 overflow-hidden`,children:e?T.length?(0,L.jsx)(Ui,{ref:xe.virtuosoRef,data:T,firstItemIndex:xe.firstItemIndex,initialTopMostItemIndex:YT,increaseViewportBy:XT,defaultItemHeight:ZT,className:`min-h-0 h-full overflow-x-hidden font-mono text-[12px] leading-[1.45]`,computeItemKey:(e,t)=>t.id,scrollerRef:xe.scrollerRef,atBottomStateChange:xe.atBottomStateChange,atBottomThreshold:xe.atBottomThreshold,atTopStateChange:e=>{e&&_e()},itemsRendered:xe.itemsRendered,rangeChanged:e=>be(xe.normalizeRange(e)),startReached:_e,followOutput:xe.followOutput,totalListHeightChanged:xe.totalListHeightChanged,alignToBottom:!0,components:Te,itemContent:we}):(0,L.jsx)(wE,{isLoading:t,agentProfiles:m,disabled:h,onSelectAgentProfile:g,message:`No visible trace rows yet.`}):(0,L.jsx)(wE,{isLoading:t,agentProfiles:m,disabled:h,onSelectAgentProfile:g})}),T.length===0&&me?(0,L.jsx)(vE,{isWorking:!1,goal:u}):null,xe.isSticky?null:(0,L.jsx)(`button`,{type:`button`,onClick:()=>{WT(D,void 0),xe.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,L.jsx)(je,{size:18})})]})}function tE({errorCount:e,toolErrorCount:t,userMessageCount:n,onNavigate:r,sessionAgentProfile:i,sessionActiveModel:a,sessionBreadcrumbs:o,originSession:s,derivedSessions:c,onOpenSession:l}){return(0,L.jsxs)(`div`,{"data-pibo-debug":`compact-terminal-header`,className:`border-b border-[#2a2a2a] bg-[#111111] px-4 py-2 text-[11px]`,children:[(0,L.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i?(0,L.jsx)(SE,{tone:`neutral`,children:i}):null,a?(0,L.jsx)(SE,{tone:`purple`,children:a}):null,n>0?(0,L.jsxs)(SE,{tone:`cyan`,label:`${n} user messages · jump to previous user message`,onClick:()=>r(`user`),children:[n,(0,L.jsx)(ct,{size:12})]}):null,e>0?(0,L.jsxs)(SE,{tone:`red`,label:`${e} errors · jump to previous error`,onClick:()=>r(`system`),children:[e,(0,L.jsx)(Be,{size:12})]}):null,t>0?(0,L.jsxs)(SE,{tone:`amber`,label:`${t} tool call errors · jump to previous tool error`,onClick:()=>r(`tool`),children:[t,(0,L.jsx)(Qe,{size:12})]}):null,s?(0,L.jsxs)(nE,{onClick:()=>l(s.piboSessionId),children:[`Origin `,s.label]}):null,c.map(e=>(0,L.jsxs)(nE,{onClick:()=>l(e.piboSessionId),children:[`Derived `,e.label]},e.piboSessionId))]}),o.length?(0,L.jsx)(`div`,{className:`mt-2 flex flex-wrap items-center gap-1 text-[#737373]`,children:o.map((e,t)=>(0,L.jsxs)(`div`,{className:`flex items-center gap-1`,children:[t>0?(0,L.jsx)(Me,{size:12,className:`text-[#525252]`}):null,(0,L.jsx)(`button`,{type:`button`,onClick:()=>l(e.piboSessionId),className:`hover:text-[#38bdf8]`,children:e.label})]},e.piboSessionId))}):null]})}function nE({children:e,onClick:t}){return(0,L.jsx)(`button`,{type:`button`,onClick:t,className:`border border-[#3a3a3a] px-2 py-0.5 text-[#38bdf8] hover:border-[#38bdf8]`,children:e})}function rE({row:e,expanded:t,focused:n,piboSessionId:r,onToggle:i,onFork:a,onOpenSession:o,onThinkingLevelChange:s,onModelChanged:c,signals:l}){let u=!t&&hE(e),d=u?mE(e):e.lines;return e.kind===`agent.delegation`?(0,L.jsx)(`div`,{className:lE(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,L.jsx)(ml,{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,L.jsxs)(`div`,{className:lE(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||gE(t)||i()}:void 0,onKeyDown:e.expandable?t=>{!e.expandable||gE(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,L.jsxs)(`div`,{className:`flex gap-3`,children:[(0,L.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,L.jsx)(iE,{row:e,visibleLines:d,collapseToolCallPreview:u,piboSessionId:r,onThinkingLevelChange:s,onModelChanged:c})}),(0,L.jsx)(cE,{row:e,onFork:a,onOpenSession:o})]}),t?(0,L.jsx)(hx,{row:e,onOpenSession:o}):null]})}function iE({row:e,visibleLines:t,collapseToolCallPreview:n,piboSessionId:r,onThinkingLevelChange:i,onModelChanged:a}){return e.kind===`message.assistant`?(0,L.jsxs)(`div`,{className:`ml-[1.9rem] min-w-0`,"data-pibo-component":`TerminalAssistantMessage`,children:[(0,L.jsx)(`div`,{className:`compact-terminal-markdown`,"data-pibo-component":`MarkdownRendererHost`,"data-pibo-markdown-kind":`assistant-message`,children:(0,L.jsx)(sb,{streaming:e.status===`running`,children:typeof e.output==`string`?e.output:``})}),e.status===`running`?null:(0,L.jsx)(oE,{timestamp:e.completedAt,durationMs:e.durationMs})]}):e.kind===`message.user`?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(aE,{lines:t,status:e.status,clampPreview:n}),e.pendingMessageDelivery?(0,L.jsx)(xl,{delivery:e.pendingMessageDelivery,className:`ml-[1.9rem] mt-2`}):null,(0,L.jsx)(oE,{timestamp:e.startedAt})]}):e.kind===`tool.status`?(0,L.jsx)(LT,{row:e}):e.kind===`tool.thinking`?(0,L.jsx)(VT,{row:e,onLevelSelect:i}):e.kind===`tool.login`?(0,L.jsx)($x,{row:e,piboSessionId:r}):e.kind===`tool.model`?(0,L.jsx)(aS,{row:e,piboSessionId:r,onModelChanged:a}):e.kind===`execution.compaction`&&e.status===`running`?(0,L.jsx)(bE,{}):e.kind===`reasoning`&&e.markdown?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(aE,{lines:t,status:e.status,clampPreview:n}),(0,L.jsx)(`div`,{className:`ml-[1.9rem] min-w-0`,"data-pibo-component":`TerminalReasoningMarkdown`,children:(0,L.jsx)(`div`,{className:`compact-terminal-markdown compact-terminal-reasoning`,"data-pibo-component":`MarkdownRendererHost`,"data-pibo-markdown-kind":`reasoning`,children:(0,L.jsx)(sb,{streaming:e.status===`running`,children:e.markdown})})})]}):(0,L.jsx)(aE,{lines:t,status:e.status,clampPreview:n})}function aE({lines:e,status:t,clampPreview:n}){return e.map((e,r)=>(0,L.jsx)(Fx,{line:e,status:t,clampLines:n&&r===0?5:void 0},r))}function oE({timestamp:e,durationMs:t}){let n=sE(e);return n?(0,L.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:` · ${fw(t)}`]}):null}function sE(e){if(!e)return;let t=new Date(e);if(Number.isFinite(t.getTime()))return new Intl.DateTimeFormat(void 0,{hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}).format(t)}function cE({row:e,onFork:t,onOpenSession:n}){return(0,L.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,L.jsx)(CE,{label:`Open linked session`,onClick:()=>n(e.linkedPiboSessionId),children:`Open`}):null,e.forkEntryId?(0,L.jsxs)(CE,{label:`Fork from this user message`,onClick:()=>t(e.forkEntryId),children:[(0,L.jsx)(Ze,{size:13}),`Fork`]}):null]})}function lE(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 uE(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 TE(e,r)?e:r}function dE(e,t){return t===`user`?e.kind===`message.user`:e.status===`error`?t===`tool`?e.errorKind===`tool`:e.errorKind!==`tool`:!1}function fE(e,t,n){let r=e.map((e,t)=>({row:e,index:t})).filter(({row:e})=>dE(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 pE(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 mE(e){return e.kind===`tool.group.exploring`||e.kind===`tool.group.images`?e.lines.slice(0,$T):e.lines}function hE(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 gE(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 _E=`Working...`;function vE({startedAt:e,isWorking:t,goal:n}){let r=yE(t?e:void 0),i=rx(n);return(0,L.jsx)(`div`,{className:`border-t border-[#141414] px-4 py-2`,role:`status`,"aria-live":`polite`,"aria-label":[t?`Working`:void 0,i===`active`?`Pursuing Goal`:i===`paused`?`Goal Paused`:void 0].filter(Boolean).join(`. `),"data-pibo-component":`TerminalStreamingFooter`,"data-pibo-active-turn-started-at":t?e:void 0,children:(0,L.jsxs)(`div`,{className:`flex min-w-0 items-baseline justify-between gap-4`,"aria-hidden":`true`,children:[t?(0,L.jsxs)(`div`,{className:`grid min-w-0 flex-1 grid-cols-[1.9rem_minmax(0,1fr)] gap-2 whitespace-pre-wrap break-words`,children:[(0,L.jsx)(`span`,{className:`whitespace-pre text-[#737373]`,children:`•`}),(0,L.jsxs)(`span`,{className:`inline-flex min-w-0 items-baseline gap-2`,children:[r?(0,L.jsx)(`span`,{className:`shrink-0 tabular-nums text-[#737373]`,children:r}):null,(0,L.jsx)(`span`,{className:`compact-terminal-working-label`,children:_E})]})]}):(0,L.jsx)(`span`,{className:`min-w-0 flex-1`}),(0,L.jsx)(tx,{goal:n})]})})}function yE(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)?fw(Math.max(0,n-t)):void 0}function bE(){let e=xE();return(0,L.jsxs)(`div`,{className:`grid grid-cols-[1.9rem_minmax(0,1fr)] gap-2 whitespace-pre-wrap break-words`,children:[(0,L.jsx)(`span`,{className:`whitespace-pre text-[#38bdf8]`,children:`•`}),(0,L.jsxs)(`span`,{className:`min-w-0`,children:[(0,L.jsx)(`span`,{className:`font-semibold text-[#38bdf8]`,children:`Compacting`}),(0,L.jsx)(`span`,{className:`text-[#38bdf8]`,children:e})]})]})}function xE(){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 SE({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,L.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,L.jsx)(`span`,{className:i,title:t,"aria-label":t,children:r})}function CE({label:e,onClick:t,children:n}){return(0,L.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 wE({isLoading:e,agentProfiles:t,disabled:n,onSelectAgentProfile:r,message:i}){return(0,L.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,L.jsx)(`div`,{children:e?`Loading trace…`:i??`No trace selected.`}),t.length?(0,L.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:t.map(e=>(0,L.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 TE(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function EE(e,t){return t?t===`away`:e instanceof WheelEvent?e.deltaY<0:e instanceof KeyboardEvent?[`ArrowUp`,`PageUp`,`Home`].includes(e.key):e?.type===`touchmove`}function DE({traceView:e,isLoading:t,selectedSessionStatus:n,selectedSessionSignal:r,workflowProjectSession:i,workflowLifecycleEvents:a,sessionNodes:o,onOpenSession:s,onRefreshBootstrap:c,onError:l}){let u=i?qE(i,e,n,r,a??[],o):null;return u?(0,L.jsx)(`section`,{className:`min-w-0 flex-1 overflow-auto bg-[#0b0f14] p-4 text-slate-300`,children:(0,L.jsxs)(`div`,{className:`mx-auto flex max-w-6xl flex-col gap-4`,children:[(0,L.jsx)(OE,{model:u}),(0,L.jsx)(kE,{}),(0,L.jsx)(AE,{model:u,onRefreshBootstrap:c,onError:l}),(0,L.jsx)(ME,{model:u}),(0,L.jsx)(NE,{model:u,onOpenSession:s}),(0,L.jsx)(BE,{nodes:u.nodes,edges:u.edges}),(0,L.jsxs)(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_360px]`,children:[(0,L.jsx)(HE,{model:u}),(0,L.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-4`,children:[(0,L.jsx)(UE,{model:u}),(0,L.jsx)(WE,{model:u}),(0,L.jsx)(GE,{model:u})]})]})]})}):(0,L.jsx)(`section`,{className:`min-w-0 flex-1 overflow-auto bg-[#0b0f14] p-4 text-slate-300`,children:(0,L.jsxs)(`div`,{className:`mx-auto flex max-w-4xl flex-col gap-4`,children:[(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-semibold text-slate-100`,children:[(0,L.jsx)(nt,{size:16,className:`text-[#11a4d4]`}),`Workflow / XState`]}),(0,L.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,L.jsx)(kE,{})]})})}function OE({model:e}){return(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4`,children:[(0,L.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-semibold text-slate-100`,children:[(0,L.jsx)(nt,{size:16,className:`text-[#11a4d4]`}),`Workflow / XState Projection`]}),(0,L.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2 text-xs`,children:[(0,L.jsx)(kD,{tone:`blue`,children:e.workflowId}),e.workflowRunId?(0,L.jsxs)(kD,{tone:`slate`,children:[`run `,PD(e.workflowRunId)]}):null,(0,L.jsx)(kD,{tone:AD(e.status),children:e.state})]})]}),(0,L.jsxs)(`div`,{className:`min-w-0 text-right font-mono text-[11px] text-slate-500`,children:[(0,L.jsxs)(`div`,{className:`truncate`,children:[`session `,PD(e.piboSessionId)]}),e.latestStreamId===void 0?null:(0,L.jsxs)(`div`,{children:[`stream `,e.latestStreamId]})]})]}),(0,L.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 kE(){return(0,L.jsx)(`div`,{className:`rounded-sm border border-amber-500/30 bg-amber-500/10 p-4 text-sm`,children:(0,L.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-amber-200`,children:[(0,L.jsx)(vt,{size:14}),`Workflow IR source-of-truth boundary`]}),(0,L.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,L.jsxs)(`div`,{className:`flex shrink-0 flex-wrap gap-2`,children:[(0,L.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,L.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 AE({model:e,onRefreshBootstrap:t,onError:n}){let r=e.workflowRunId?zE(e):void 0,i=`${e.workflowId}${e.workflowVersion?`@${e.workflowVersion}`:``}`;return(0,L.jsxs)(`div`,{className:`grid gap-4 lg:grid-cols-3`,"aria-label":`Projects workflow execution shell`,children:[(0,L.jsx)(LE,{title:`Workflow configured-session view`,icon:(0,L.jsx)(it,{size:14}),children:(0,L.jsxs)(`div`,{className:`space-y-3 text-xs text-slate-400`,children:[(0,L.jsx)(RE,{label:`selected workflow`,value:i}),(0,L.jsx)(RE,{label:`session state`,value:e.workflowRunId?`started`:`configured/not-started`}),(0,L.jsx)(RE,{label:`input keys`,value:String(e.configuration.inputKeys.length)}),(0,L.jsx)(RE,{label:`prompt overrides`,value:String(e.configuration.promptOverrideNodeIds.length)}),(0,L.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,L.jsx)(LE,{title:`Workflow run view`,icon:(0,L.jsx)(xe,{size:14}),children:(0,L.jsxs)(`div`,{className:`space-y-3 text-xs text-slate-400`,children:[(0,L.jsx)(RE,{label:`run id`,value:e.workflowRunId?PD(e.workflowRunId):`not started`}),(0,L.jsx)(RE,{label:`status`,value:e.state}),(0,L.jsx)(RE,{label:`current node`,value:r?.label??`none`}),(0,L.jsx)(RE,{label:`output`,value:e.finalOutput?`available`:`empty`}),(0,L.jsx)(RE,{label:`error`,value:e.runtimeErrors.length?`${e.runtimeErrors.length} runtime errors`:e.validationErrors.length?`${e.validationErrors.length} validation diagnostics`:`none`}),(0,L.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,L.jsx)(LE,{title:`Human action area`,icon:(0,L.jsx)(He,{size:14}),children:(0,L.jsx)(jE,{model:e,onRefreshBootstrap:t,onError:n})})]})}function jE({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 qx(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=_D(e);c(e=>({...e,[i.waitTokenId]:t})),n?.(t[0]?.message??vD(e))}finally{o(null)}};return(0,L.jsxs)(`div`,{className:`space-y-3 text-xs text-slate-400`,children:[e.pendingHumanActions.length?(0,L.jsx)(`div`,{className:`space-y-3`,children:e.pendingHumanActions.map(e=>{let t=[...e.diagnostics,...e.waitTokenId?s[e.waitTokenId]??[]:[]];return(0,L.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,L.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsx)(`div`,{className:`font-semibold`,children:e.label}),(0,L.jsx)(`div`,{className:`mt-1 break-words text-[11px] leading-5 text-amber-100/80`,children:e.prompt})]}),(0,L.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?PD(e.waitTokenId):e.source})]}),(0,L.jsxs)(`div`,{className:`mt-2 grid gap-2 text-[11px] text-amber-100/75`,children:[(0,L.jsx)(RE,{label:`human node`,value:e.humanNodeId??`unspecified`}),(0,L.jsx)(RE,{label:`payload`,value:e.payloadRequirements?.description??`No persisted payload schema.`}),e.expiresAt?(0,L.jsx)(RE,{label:`expires`,value:e.expiresAt}):null]}),e.payloadRequirements?.schema?(0,L.jsxs)(`div`,{className:`mt-2 rounded-sm border border-amber-400/25 bg-[#0b0f14]/50 p-2`,children:[(0,L.jsx)(`div`,{className:`mb-1 text-[10px] font-bold uppercase tracking-wider text-amber-100/70`,children:`Resume payload schema`}),(0,L.jsx)(fl,{value:e.payloadRequirements.schema,defaultExpandLevel:1,maxHeight:`10rem`,showControls:!1})]}):null,e.availableActions.some(e=>e.kind===`resume`)?(0,L.jsxs)(`label`,{className:`mt-3 block text-[11px] text-amber-100/80`,children:[(0,L.jsx)(`span`,{className:`mb-1 block font-semibold`,children:`Resume payload JSON`}),(0,L.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,L.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,L.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,L.jsx)(`span`,{className:`text-amber-100/60`,children:`No registered human actions are available for this wait token.`})}),e.waitTokenId&&l[e.waitTokenId]?(0,L.jsx)(`div`,{className:`mt-2 text-[11px] text-emerald-200`,children:l[e.waitTokenId]}):null,t.length?(0,L.jsx)(`div`,{className:`mt-2 space-y-1`,"aria-label":`Human action diagnostics`,children:t.map((e,t)=>(0,L.jsxs)(`div`,{className:`rounded border border-red-400/35 bg-red-500/15 p-2 text-[11px] leading-5 text-red-100`,children:[(0,L.jsx)(`div`,{children:e.message}),(0,L.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,L.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,L.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 ME({model:e}){let t=e.workflowRunId?zE(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,L.jsxs)(`section`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,"aria-label":`Workflow run inspection panel`,children:[(0,L.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,L.jsx)(Ge,{size:14}),`Workflow run inspection`]}),(0,L.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,L.jsxs)(`div`,{className:`flex shrink-0 flex-wrap gap-2 text-[10px] uppercase tracking-wide`,children:[(0,L.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,L.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,L.jsxs)(`div`,{className:`mt-4 grid gap-3 lg:grid-cols-3`,children:[(0,L.jsxs)(PE,{title:`Status`,badge:e.state,icon:(0,L.jsx)(xe,{size:14}),children:[(0,L.jsx)(FE,{label:`run id`,value:e.workflowRunId?PD(e.workflowRunId):`not started`}),(0,L.jsx)(FE,{label:`status`,value:e.state}),(0,L.jsx)(FE,{label:`record source`,value:e.workflowRunId?`Project workflow run id`:`no run record yet`})]}),(0,L.jsxs)(PE,{title:`Current node`,badge:t?.status??`none`,icon:(0,L.jsx)(ft,{size:14}),children:[(0,L.jsx)(FE,{label:`node`,value:t?.label??`none`}),(0,L.jsx)(FE,{label:`node id`,value:t?.id??`none`}),(0,L.jsx)(FE,{label:`source`,value:`project/session run cursor`})]}),(0,L.jsx)(PE,{title:`Run history`,badge:`${e.runHistory.length}`,icon:(0,L.jsx)(et,{size:14}),children:e.runHistory.length?(0,L.jsx)(`div`,{className:`space-y-2`,children:e.runHistory.map(e=>(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:[(0,L.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,L.jsx)(`div`,{className:`min-w-0 truncate font-mono text-xs text-slate-200`,children:PD(e.id)}),(0,L.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide ${ND(e.status)}`,children:e.status})]}),(0,L.jsxs)(`div`,{className:`mt-1 text-[11px] text-slate-500`,children:[e.currentNodeId?`current ${e.currentNodeId}`:`no current node`,` · `,e.source]}),(0,L.jsxs)(`div`,{className:`mt-1 font-mono text-[10px] text-slate-600`,children:[`updated `,e.updatedAt]})]},e.id))}):(0,L.jsx)(IE,{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,L.jsxs)(`div`,{className:`mt-3 grid gap-3 lg:grid-cols-2`,children:[(0,L.jsx)(PE,{title:`Node attempts`,badge:`${e.nodeAttempts.length}`,icon:(0,L.jsx)(it,{size:14}),children:e.nodeAttempts.length?(0,L.jsx)(`div`,{className:`space-y-2`,children:e.nodeAttempts.map(e=>(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:[(0,L.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsx)(`div`,{className:`truncate text-xs font-semibold text-slate-200`,children:e.label}),(0,L.jsxs)(`div`,{className:`mt-1 font-mono text-[10px] text-slate-500`,children:[e.nodeId,` · attempt `,e.attempt]})]}),(0,L.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide ${ND(e.status)}`,children:e.status})]}),(0,L.jsxs)(`div`,{className:`mt-1 text-[11px] text-slate-500`,children:[e.kind,` · `,e.source]})]},e.id))}):(0,L.jsx)(IE,{children:e.workflowRunId?`No node attempts recorded for this workflow run yet.`:`No current node attempts; Start has not created a workflow run.`})}),(0,L.jsx)(PE,{title:`Edge transfers`,badge:`${e.edgeTransfers.length}`,icon:(0,L.jsx)(Ze,{size:14}),children:e.edgeTransfers.length?(0,L.jsx)(`div`,{className:`space-y-2`,children:e.edgeTransfers.map(e=>(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:[(0,L.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,L.jsx)(`div`,{className:`min-w-0 truncate font-mono text-xs text-slate-200`,children:e.edgeId}),(0,L.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide ${ND(e.status)}`,children:e.status})]}),(0,L.jsxs)(`div`,{className:`mt-1 text-[11px] text-slate-500`,children:[e.source,e.createdAt?` · ${e.createdAt}`:``]})]},e.id))}):(0,L.jsx)(IE,{children:`No edge transfers recorded for this workflow run yet.`})}),(0,L.jsx)(PE,{title:`Output`,badge:e.finalOutput?`available`:`empty`,icon:(0,L.jsx)(Re,{size:14}),children:e.finalOutput?(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:[(0,L.jsx)(`div`,{className:`mb-2 font-mono text-[10px] text-slate-500`,children:e.finalOutput.source}),(0,L.jsx)(fl,{value:e.finalOutput.value,defaultExpandLevel:1,maxHeight:`12rem`,showControls:!1})]}):(0,L.jsx)(IE,{children:`No workflow output has been recorded for this run yet.`})}),(0,L.jsx)(PE,{title:`Error`,badge:n.length?`${n.length}`:`none`,icon:(0,L.jsx)(vt,{size:14}),children:n.length?(0,L.jsx)(`div`,{className:`space-y-2`,children:n.map(e=>(0,L.jsxs)(`div`,{className:`rounded-sm border border-red-500/35 bg-red-500/10 p-2 text-xs text-red-100`,children:[(0,L.jsx)(`div`,{className:`break-words`,children:e.message}),(0,L.jsxs)(`div`,{className:`mt-1 flex flex-wrap gap-1 font-mono text-[10px] text-red-200/70`,children:[e.code?(0,L.jsx)(`span`,{children:e.code}):null,e.source?(0,L.jsx)(`span`,{children:e.source}):null]})]},e.id))}):(0,L.jsx)(IE,{children:`No workflow run errors are recorded.`})})]})]})}function NE({model:e,onOpenSession:t}){let n=ZE(e.definitionLink);return(0,L.jsxs)(`section`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,"aria-label":`Workflow navigation links`,children:[(0,L.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,L.jsx)(Ke,{size:14}),`Workflow navigation links`]}),(0,L.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,L.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,L.jsx)(Ke,{size:13}),`Open live workflow definition`]}):null]}),(0,L.jsxs)(`div`,{className:`mt-4 grid gap-3 lg:grid-cols-2`,children:[(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0f171e] p-3`,"aria-label":`Nested workflow child session links`,children:[(0,L.jsxs)(`div`,{className:`mb-3 flex items-center justify-between gap-2`,children:[(0,L.jsx)(`div`,{className:`text-xs font-bold uppercase tracking-wider text-slate-500`,children:`Nested workflow child sessions`}),(0,L.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,L.jsx)(`div`,{className:`space-y-2`,children:e.nestedSessionLinks.map(e=>(0,L.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,L.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsx)(`div`,{className:`truncate text-xs font-semibold text-slate-200`,children:e.title}),(0,L.jsx)(`div`,{className:`mt-1 font-mono text-[10px] text-slate-500`,children:PD(e.piboSessionId)})]}),(0,L.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,L.jsx)(IE,{children:`No nested workflow child sessions are linked under this selected Project session yet.`})]}),(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0f171e] p-3`,"aria-label":`Workflow definition link state`,children:[(0,L.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,L.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,L.jsx)(`div`,{className:`font-semibold`,children:`Live workflow definition exists`}),(0,L.jsx)(`div`,{className:`mt-1 font-mono text-[11px] text-emerald-100/80`,children:$E(e.definitionLink)}),e.definitionLink.definitionHash?(0,L.jsxs)(`div`,{className:`mt-1 font-mono text-[10px] text-emerald-100/60`,children:[`snapshot `,PD(e.definitionLink.definitionHash)]}):null]}):(0,L.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,L.jsx)(`div`,{className:`font-semibold`,children:`Definition deleted — snapshot-only definition-deleted state`}),(0,L.jsx)(`div`,{className:`mt-1 font-mono text-[11px] text-amber-100/80`,children:$E(e.definitionLink)}),(0,L.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,L.jsxs)(`div`,{className:`mt-1 font-mono text-[10px] text-amber-100/60`,children:[`snapshot `,PD(e.definitionLink.definitionHash)]}):null]})]})]})]})}function PE({title:e,badge:t,icon:n,children:r}){return(0,L.jsxs)(`section`,{className:`min-w-0 rounded-sm border border-slate-800 bg-[#0f171e] p-3`,"aria-label":e,children:[(0,L.jsxs)(`div`,{className:`mb-3 flex items-center justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,L.jsx)(`span`,{className:`text-[#11a4d4]`,children:n}),e]}),(0,L.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 FE({label:e,value:t}){return(0,L.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,L.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-slate-500`,children:e}),(0,L.jsx)(`span`,{className:`min-w-0 max-w-[14rem] truncate text-right font-mono text-xs text-slate-300`,title:t,children:t})]})}function IE({children:e}){return(0,L.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,L.jsxs)(`section`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4`,"aria-label":e,children:[(0,L.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,L.jsx)(`span`,{className:`text-[#11a4d4]`,children:t}),e]}),n]})}function RE({label:e,value:t}){return(0,L.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,L.jsx)(`span`,{className:`uppercase tracking-wide text-slate-500`,children:e}),(0,L.jsx)(`span`,{className:`min-w-0 max-w-[12rem] truncate text-right font-mono text-slate-300`,title:t,children:t})]})}function zE(e){return e.nodes.find(e=>e.status===`active`||e.status===`waiting`)??e.nodes[0]}function BE({nodes:e,edges:t}){return(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0f171e] p-4`,children:[(0,L.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,L.jsx)(ft,{size:14}),`Visual State Flow`]}),(0,L.jsx)(`div`,{className:`grid gap-3 md:grid-cols-[1fr_auto_1fr_auto_1fr]`,children:e.map((e,n)=>(0,L.jsx)(VE,{node:e,edge:t[n]},e.id))})]})}function VE({node:e,edge:t}){return(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(`div`,{className:`rounded-sm border p-3 ${jD(e.status)}`,children:[(0,L.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,L.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,L.jsx)(OD,{status:e.status}),(0,L.jsx)(`div`,{className:`min-w-0 truncate text-sm font-semibold text-slate-100`,children:e.label})]}),(0,L.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,L.jsx)(`p`,{className:`mt-2 text-xs text-slate-400`,children:e.description})]}),t?(0,L.jsx)(`div`,{className:`hidden items-center justify-center text-center text-[10px] uppercase tracking-wide text-slate-500 md:flex`,children:(0,L.jsxs)(`div`,{children:[(0,L.jsx)(Ze,{size:14,className:`mx-auto mb-1 text-[#11a4d4]`}),t.label]})}):null]})}function HE({model:e}){return(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4`,children:[(0,L.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,L.jsx)(xe,{size:14}),`Current UI Snapshot`]}),(0,L.jsx)(fl,{value:e.snapshot,showControls:!1})]})}function UE({model:e}){return(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,children:[(0,L.jsxs)(`div`,{className:`mb-3 flex items-center justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,L.jsx)(it,{size:14}),`Node Statuses`]}),(0,L.jsxs)(`span`,{className:`font-mono text-[11px] text-slate-500`,children:[e.nodes.length,` nodes`]})]}),(0,L.jsx)(`div`,{className:`space-y-2`,children:e.nodes.map(e=>(0,L.jsxs)(`div`,{className:`rounded-sm border px-3 py-2 ${jD(e.status)}`,children:[(0,L.jsxs)(`div`,{className:`flex min-w-0 items-start justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`flex min-w-0 items-start gap-2`,children:[(0,L.jsx)(`span`,{className:`mt-0.5 shrink-0`,children:(0,L.jsx)(OD,{status:e.status})}),(0,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsx)(`div`,{className:`truncate text-sm font-semibold text-slate-100`,children:e.label}),(0,L.jsx)(`div`,{className:`mt-0.5 truncate font-mono text-[11px] text-slate-500`,children:e.id})]})]}),(0,L.jsxs)(`div`,{className:`flex shrink-0 flex-col items-end gap-1`,children:[(0,L.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide ${MD(e.status)}`,children:e.status}),(0,L.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,L.jsx)(`p`,{className:`mt-2 text-xs text-slate-400`,children:e.description})]},e.id))}),(0,L.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 WE({model:e}){return(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,children:[(0,L.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,L.jsx)(Re,{size:14}),`Final Output & Validation`]}),(0,L.jsxs)(`div`,{className:`space-y-4`,children:[(0,L.jsxs)(`div`,{children:[(0,L.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,L.jsx)(`div`,{className:`text-xs font-semibold uppercase tracking-wide text-slate-400`,children:`Final output`}),e.finalOutput?(0,L.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,L.jsx)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:(0,L.jsx)(fl,{value:e.finalOutput.value,defaultExpandLevel:1,maxHeight:`14rem`,showControls:!1})}):(0,L.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,L.jsxs)(`div`,{children:[(0,L.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,L.jsx)(`div`,{className:`text-xs font-semibold uppercase tracking-wide text-slate-400`,children:`Validation errors`}),(0,L.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,L.jsx)(`div`,{className:`space-y-2`,children:e.validationErrors.map(e=>(0,L.jsx)(`div`,{className:`rounded-sm border border-red-500/35 bg-red-500/10 p-2`,children:(0,L.jsxs)(`div`,{className:`flex min-w-0 items-start gap-2 text-xs text-red-200`,children:[(0,L.jsx)(vt,{size:14,className:`mt-0.5 shrink-0 text-red-300`}),(0,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsx)(`div`,{className:`break-words`,children:e.message}),(0,L.jsxs)(`div`,{className:`mt-1 flex flex-wrap gap-1 font-mono text-[10px] text-red-200/70`,children:[e.code?(0,L.jsx)(`span`,{children:e.code}):null,e.path?(0,L.jsx)(`span`,{children:e.path}):null,e.source?(0,L.jsx)(`span`,{children:e.source}):null]})]})]})},e.id))}):(0,L.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 GE({model:e}){return(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,children:[(0,L.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,L.jsx)(Ve,{size:14}),`Projection Facts`]}),(0,L.jsxs)(`dl`,{className:`space-y-3`,children:[(0,L.jsx)(KE,{label:`projection kind`,value:`pibo.workflow.xstateUiModel`}),(0,L.jsx)(KE,{label:`schema`,value:`v1`}),(0,L.jsx)(KE,{label:`durable truth`,value:`kernel`}),(0,L.jsx)(KE,{label:`private payloads`,value:`not exposed`}),(0,L.jsx)(KE,{label:`states`,value:String(e.nodes.length)}),(0,L.jsx)(KE,{label:`transitions`,value:String(e.edges.length)}),(0,L.jsx)(KE,{label:`trace`,value:e.traceVersion??`pending`})]})]})}function KE({label:e,value:t}){return(0,L.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,L.jsx)(`dt`,{className:`text-xs uppercase tracking-wide text-slate-500`,children:e}),(0,L.jsx)(`dd`,{className:`min-w-0 truncate text-right font-mono text-xs text-slate-300`,children:t})]})}function qE(e,t,n,r,i,a){if(!xD(e))return null;let o=SD(e,n),s=CD(e,n),c=wD(s),l=lD(t,s),u=[...dD(t),...uD(e,i)],d=nD(e,o,c),f=rD(t,e.workflowRunId),p=oD(t,e.workflowRunId),m=sD(t,r),h=JE(e),g=YE(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:TD(s),label:ED(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:TD(s),label:DD(s)}],configuration:eD(e),definitionLink:h,nestedSessionLinks:g,pendingHumanActions:tD(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`&&!!ZE(h)},nestedWorkflowSessionCount:g.length}}}function JE(e){return e.workflowDefinitionLink?e.workflowDefinitionLink:e.workflowVersion?{status:`live`,workflowId:e.workflowId,workflowVersion:e.workflowVersion,title:e.title??e.workflowId,href:QE(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 YE(e,t){let n=XE(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 XE(e,t){for(let n of e){if(n.piboSessionId===t)return n;let e=XE(n.children,t);if(e)return e}}function ZE(e){if(e.status===`live`){if(e.href)return e.href;if(e.workflowVersion)return QE(e.workflowId,e.workflowVersion)}}function QE(e,t){return`/apps/chat/workflows/view/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function $E(e){return`${e.workflowId}${e.workflowVersion?`@${e.workflowVersion}`:``}`}function eD(e){let t=e.configuration;return{inputKeys:Object.keys(t?.inputValues??{}).sort(),promptOverrideNodeIds:Object.keys(t?.promptOverrides??{}).sort()}}function tD(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=SD(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 nD(e,t,n){return e.workflowRunId?[{id:e.workflowRunId,status:t,currentNodeId:n,updatedAt:e.updatedAt,source:`project session run record`}]:[]}function rD(e,t){return!t||!e?[]:fD(e.nodes).filter(iD).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:aD(e.status),attempt:t+1,source:`session trace fact`,...e.startedAt?{startedAt:e.startedAt}:{},...e.completedAt?{completedAt:e.completedAt}:{}}))}function iD(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 aD(e){return e===`done`?`completed`:e===`error`?`failed`:`running`}function oD(e,t){if(!t||!e)return[];let n=[];for(let r of e.rawEvents){if(!bD(r.payload))continue;let e=yD(r.payload.type),i=yD(r.payload.runId);if(e!==`edge.transferred`||i&&i!==t)continue;let a=yD(r.payload.edgeId);a&&n.push({id:yD(r.payload.edgeTransferId)??r.id,edgeId:a,status:`transferred`,source:r.type,createdAt:r.createdAt})}return n.slice(0,8)}function sD(e,t){let n=[];for(let e of t?.errors??[])n.push({id:`signal:${n.length}`,message:e.message,...e.code?{code:e.code}:{},source:e.source??`session signal`});if(e){for(let t of fD(e.nodes)){let e=t.error??(t.status===`error`?mD(t.output)??mD(t.summary):void 0);e&&n.push({id:`node:${t.id}`,message:e,source:t.type})}for(let t of e.rawEvents){if(!bD(t.payload))continue;let e=t.payload.error,r=bD(e)?yD(e.message):yD(e),i=bD(e)?yD(e.code):void 0;r&&n.push({id:`event:${t.id}`,message:r,...i?{code:i}:{},source:t.type})}}return cD(n).slice(0,8)}function cD(e){let t=new Set;return e.filter(e=>{let n=`${e.code??``}:${e.message}:${e.source??``}`;return t.has(n)?!1:(t.add(n),!0)})}function lD(e,t){if(t!==`completed`||!e)return;let n=fD(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 uD(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 gD(n).slice(0,8)}function dD(e){if(!e)return[];let t=[];for(let n of fD(e.nodes)){let e=n.error??mD(n.output)??mD(n.summary);e&&(!hD([n.title,n.summary,n.error,n.type].filter(e=>typeof e==`string`).join(` `))&&!hD(e)||t.push({id:`node:${n.id}`,message:e,...n.type?{source:n.type}:{}}))}for(let n of e.rawEvents)pD(n.payload,`event:${n.id}`,t);return gD(t).slice(0,8)}function fD(e){let t=[],n=e=>{for(let r of e)t.push(r),n(r.children)};return n(e),t}function pD(e,t,n,r=0){if(r>4||!bD(e))return;let i=Array.isArray(e.diagnostics)?e.diagnostics:void 0;if(i)for(let e of i){if(!bD(e))continue;let r=yD(e.message)??mD(e);r&&n.push({id:`${t}:diagnostic:${n.length}`,message:r,...yD(e.code)?{code:yD(e.code)}:{},...yD(e.path)?{path:yD(e.path)}:{},source:`workflow.diagnostic`})}let a=e.error;if(bD(a)){let e=yD(a.code),r=yD(a.message)??mD(a);r&&hD([e,r].filter(Boolean).join(` `))&&n.push({id:`${t}:error:${n.length}`,message:r,...e?{code:e}:{},source:`workflow.error`})}else typeof a==`string`&&hD(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`||pD(a,`${t}:${i}`,n,r+1)}function mD(e){if(typeof e==`string`)return e;if(bD(e))return yD(e.message)??yD(e.error)??yD(e.summary)}function hD(e){let t=e.toLowerCase();return t.includes(`validation`)||t.includes(`validate`)||t.includes(`diagnostic`)||t.includes(`workflowinterfaceerror`)||t.includes(`workflowruntimeerror.validation`)}function gD(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 _D(e){return bD(e)&&bD(e.data)&&Array.isArray(e.data.diagnostics)?e.data.diagnostics.filter(bD).map(t=>({code:yD(t.code)??`WorkflowRuntimeError.humanActionRejected`,message:yD(t.message)??vD(e),severity:t.severity===`info`||t.severity===`warning`||t.severity===`error`?t.severity:`error`,...yD(t.path)?{path:yD(t.path)}:{},...yD(t.registryRef)?{registryRef:yD(t.registryRef)}:{},...yD(t.hint)?{hint:yD(t.hint)}:{}})):[{code:`WorkflowRuntimeError.humanActionRejected`,message:vD(e),severity:`error`}]}function vD(e){return e instanceof Error?e.message:String(e)}function yD(e){return typeof e==`string`&&e.trim()?e:void 0}function bD(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function xD(e){return!!e.workflowRunId||e.state===`workflow`||e.workflowId!==`simple-chat`}function SD(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 CD(e,t){let n=SD(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 wD(e){return e===`completed`?`workflow.completed`:e===`failed`?`workflow.failed`:e===`cancelled`?`workflow.cancelled`:`node.session`}function TD(e){return e===`failed`?`workflow.failed`:e===`cancelled`?`workflow.cancelled`:`workflow.completed`}function ED(e){return e===`failed`?`failed`:e===`cancelled`?`cancelled`:`completed`}function DD(e){return e===`failed`?`WORKFLOW.FAIL`:e===`cancelled`?`WORKFLOW.CANCEL`:`WORKFLOW.NODE.DONE`}function OD({status:e}){return e===`completed`?(0,L.jsx)(Re,{size:16,className:`text-emerald-300`}):e===`failed`?(0,L.jsx)(Be,{size:16,className:`text-red-300`}):e===`cancelled`?(0,L.jsx)(vt,{size:16,className:`text-slate-400`}):e===`waiting`?(0,L.jsx)(He,{size:16,className:`text-amber-300`}):e===`active`?(0,L.jsx)(xe,{size:16,className:`text-[#11a4d4]`}):(0,L.jsx)(Ve,{size:16,className:`text-slate-500`})}function kD({tone:e,children:t}){return(0,L.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 AD(e){return e===`completed`?`green`:e===`failed`||e===`cancelled`?`red`:e===`waiting`?`amber`:`blue`}function jD(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 MD(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 ND(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 PD(e){return e.length>18?`${e.slice(0,10)}…${e.slice(-6)}`:e}var FD=[{id:`terminal`,label:`Terminal`,description:`Compact Codex-style terminal transcript.`,render:e=>(0,L.jsx)(eE,{...e})},{id:`workflow`,label:`Workflow`,description:`Workflow/XState visualization for workflow-backed project sessions.`,render:e=>(0,L.jsx)(DE,{...e})}],ID=new Map(FD.map(e=>[e.id,e]));function LD(){return FD}function RD(e){return ID.get(e)??ID.get(`terminal`)}var zD=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(){}},BD=new class extends zD{#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`}},VD={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},HD=new class{#e=VD;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 UD(e){setTimeout(e,0)}var WD=typeof window>`u`||`Deno`in globalThis;function GD(){}function KD(e){return typeof e==`number`&&e>=0&&e!==1/0}function qD(e,t){return Math.max(e+(t||0)-Date.now(),0)}function JD(e,t){return typeof e==`function`?e(t):e}function YD(e,t){return typeof e==`function`?e(t):e}var XD=Object.prototype.hasOwnProperty;function ZD(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=$D(e)&&$D(t);if(!r&&!(eO(e)&&eO(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:XD.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=ZD(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function QD(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 $D(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function eO(e){if(!tO(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!tO(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function tO(e){return Object.prototype.toString.call(e)===`[object Object]`}function nO(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:ZD(e,t)}function rO(e,t){return typeof e==`function`?e(...t):!!e}var iO=(()=>{let e=()=>WD;return{isServer(){return e()},setIsServer(t){e=t}}})();function aO(){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 oO=UD;function sO(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=oO,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var cO=sO(),lO=new class extends zD{#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 uO(e){return(e??`online`)===`online`?lO.isOnline():!0}function dO(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:uO(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}var fO=class extends zD{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=aO(),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),mO(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return hO(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return hO(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 YD(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&&!QD(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&gO(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||YD(this.options.enabled,this.#t)!==YD(t.enabled,this.#t)||JD(this.options.staleTime,this.#t)!==JD(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||YD(this.options.enabled,this.#t)!==YD(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 vO(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(GD)),t}#g(){this.#b();let e=JD(this.options.staleTime,this.#t);if(iO.isServer()||this.#r.isStale||!KD(e))return;let t=qD(this.#r.dataUpdatedAt,e)+1;this.#d=HD.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,!(iO.isServer()||YD(this.options.enabled,this.#t)===!1||!KD(this.#p)||this.#p===0)&&(this.#f=HD.setInterval(()=>{(this.options.refetchIntervalInBackground||BD.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(HD.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(HD.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&&mO(e,t),o=i&&gO(e,n,t,r);(a||o)&&(l={...l,...dO(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=nO(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=nO(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:_O(e,t),refetch:this.refetch,promise:this.#o,isEnabled:YD(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=aO())},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),!QD(t,e)&&(this.#r=t,this.#C({listeners:(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#m.size)return!0;let r=new Set(n??this.#m);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})()}))}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#C(e){cO.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function pO(e,t){return YD(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status===`error`&&YD(t.retryOnMount,e)===!1)}function mO(e,t){return pO(e,t)||e.state.data!==void 0&&hO(e,t,t.refetchOnMount)}function hO(e,t,n){if(YD(t.enabled,e)!==!1&&JD(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&_O(e,t)}return!1}function gO(e,t,n,r){return(e!==t||YD(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&_O(e,n)}function _O(e,t){return YD(t.enabled,e)!==!1&&e.isStaleByTime(JD(t.staleTime,e))}function vO(e,t){return!QD(e.getCurrentResult(),t)}var yO=v.createContext(void 0),bO=e=>{let t=v.useContext(yO);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},xO=v.createContext(!1),SO=()=>v.useContext(xO);xO.Provider;function CO(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var wO=v.createContext(CO()),TO=()=>v.useContext(wO),EO=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?rO(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},DO=e=>{v.useEffect(()=>{e.clearReset()},[e])},OO=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||rO(n,[e.error,r])),kO=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))}},AO=(e,t)=>e.isLoading&&e.isFetching&&!t,jO=(e,t)=>e?.suspense&&t.isPending,MO=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function NO(e,t,n){let r=SO(),i=TO(),a=bO(n),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let s=a.getQueryCache().get(o.queryHash);o._optimisticResults=r?`isRestoring`:`optimistic`,kO(o),EO(o,i,s),DO(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(cO.batchCalls(e)):GD;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),v.useEffect(()=>{l.setOptions(o)},[o,l]),jO(o,u))throw MO(o,l,i);if(OO({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&&!iO.isServer()&&AO(u,r)&&(c?MO(o,l,i):s?.promise)?.catch(GD).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?u:l.trackResult(u)}function PO(e,t){return NO(e,fO,t)}var FO=`pibo.chat.composerHistory`,IO=100;function LO(){try{let e=localStorage.getItem(FO);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`&&e.trim().length>0).slice(-IO):[]}catch{return[]}}function RO(e){let t=e.trim();if(!t)return;let n=LO();if(n.at(-1)!==t)try{localStorage.setItem(FO,JSON.stringify([...n,t].slice(-IO)))}catch{}}function zO(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 BO(e,t){return e.length>t?`${e.slice(0,Math.max(0,t-1))}…`:e}function VO({sessionId:e,disabled:t=!1,commands:n,skills:r,value:i,focusSignal:a,selectedWebAnnotations:o,selectedUploadAttachments:s,onValueChange:c,onCommand:l,onDetachWebAnnotation:u,onClearWebAnnotations:d,onAttachUploadedFiles:f,onDetachUploadAttachment:p,onClearUploadAttachments:m,onSend:h}){let g=(0,v.useRef)(null),_=(0,v.useRef)(null),y=(0,v.useRef)(null),b=(0,v.useRef)(null),x=(0,v.useRef)(null),S=(0,v.useRef)(null),C=(0,v.useRef)(null),[w,T]=(0,v.useState)(0),[E,D]=(0,v.useState)(0),[O,k]=(0,v.useState)(0),[A,ee]=(0,v.useState)([]),[te,j]=(0,v.useState)(!1),[M,ne]=(0,v.useState)(null),[N,P]=(0,v.useState)(null),re=(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]),ie=i.trim().startsWith(`/`)?i.trim().split(/\s+/)[0]:null,ae=re?HO(re.startPos,i.slice(re.startPos,O)):null,oe=ie?UO(ie):null,se=(0,v.useMemo)(()=>re?r.filter(e=>e.name.toLowerCase().startsWith(re.query)):[],[re,r]),le=(0,v.useMemo)(()=>ie?n.filter(e=>e.slash.startsWith(ie)):[],[ie,n]),F=ae&&A.includes(ae)?[]:se,ue=oe&&A.includes(oe)?[]:le,de=(0,v.useCallback)(e=>{e&&ee(t=>t.includes(e)?t:[...t,e])},[]),fe=(0,v.useCallback)(()=>{let e=[se.length?ae:null,le.length?oe:null].filter(e=>!!e);e.length&&ee(t=>{let n=new Set(t);for(let t of e)n.add(t);return n.size===t.length?t:[...n]})},[oe,le.length,se.length,ae]);(0,v.useEffect)(()=>{let e=[ae,oe].filter(e=>!!e);ee(t=>t.filter(t=>e.includes(t)))},[oe,ae]),(0,v.useEffect)(()=>{!ue.length||w<ue.length||T(0)},[w,ue.length]),(0,v.useEffect)(()=>{!F.length||E<F.length||D(0)},[E,F.length]),(0,v.useEffect)(()=>{let e=requestAnimationFrame(()=>x.current?.scrollIntoView({block:`nearest`}));return()=>cancelAnimationFrame(e)},[w,ue.length]),(0,v.useEffect)(()=>{let e=requestAnimationFrame(()=>S.current?.scrollIntoView({block:`nearest`}));return()=>cancelAnimationFrame(e)},[E,F.length]),(0,v.useEffect)(()=>{C.current=null},[e]),(0,v.useEffect)(()=>{if(!N)return;let e=requestAnimationFrame(()=>b.current?.focus());return()=>{cancelAnimationFrame(e),URL.revokeObjectURL(N.previewUrl)}},[N]),(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(!ue.length&&!F.length)return;let e=e=>{let t=e.target;t instanceof Node&&(g.current?.contains(t)||fe())};return document.addEventListener(`pointerdown`,e,!0),()=>document.removeEventListener(`pointerdown`,e,!0)},[fe,ue.length,F.length]),(0,v.useLayoutEffect)(()=>{XO(_.current)},[i]);let pe=e=>{if(!re||!_.current)return;let t=i.slice(0,re.startPos),n=i.slice(re.endPos);c(t+`$`+e+n),de(HO(re.startPos,`$${e}`));let r=re.startPos+1+e.length;k(r),requestAnimationFrame(()=>{_.current?.setSelectionRange(r,r),k(r)})},me=e=>{c(e),requestAnimationFrame(()=>{let e=_.current;if(!e)return;let t=e.value.length;e.setSelectionRange(t,t),k(t)})},he=e=>{let t=C.current;if(!t){if(e===`next`||i!==``)return!1;let t=LO();if(!t.length)return!1;let n=e===`previous`?t.length-1:0;return C.current={entries:t,index:n,draft:i},me(t[n]),!0}if(e===`previous`){let e=Math.max(0,t.index-1);return C.current={...t,index:e},me(t.entries[e]),!0}let n=t.index+1;return n>=t.entries.length?(C.current=null,me(t.draft),!0):(C.current={...t,index:n},me(t.entries[n]),!0)},ge=()=>{t||te||y.current?.click()},_e=()=>{P(null)},ve=e=>{if(t||te)return;let n=WO(e.clipboardData);if(!n.length)return;e.preventDefault(),fe(),ne(null);let r=n[0];P(e=>(e&&URL.revokeObjectURL(e.previewUrl),{file:r,previewUrl:URL.createObjectURL(r)}))},ye=async()=>{if(!N||te)return;let e=N.file;P(null),await be([e])},be=async e=>{if(e.length){j(!0),ne({message:`Uploading ${e.length} file${e.length===1?``:`s`}...`,error:!1});try{f((await ce(e)).files),ne(null)}catch(e){ne({message:e instanceof Error?e.message:String(e),error:!0})}finally{j(!1)}}},I=async()=>{if(t)return;let e=i.trim();if(e){if(F.length){pe(F[Math.min(E,F.length-1)].name);return}if(ue.length&&!n.some(t=>t.slash===e.split(/\s+/)[0])){let e=ue[Math.min(w,ue.length-1)].slash;c(e),de(UO(e));return}if(C.current=null,RO(e),c(``),e.split(/\s+/)[0]===`/upload`){ge();return}e.startsWith(`/`)&&await l(e)||await h(e)}};return(0,L.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,L.jsx)(`input`,{ref:y,type:`file`,multiple:!0,className:`hidden`,onChange:e=>{let t=Array.from(e.target.files??[]);e.target.value=``,be(t)}}),M?(0,L.jsxs)(`div`,{className:`mb-2 flex items-center gap-2 rounded-sm border px-3 py-2 text-xs ${M.error?`border-red-900 bg-red-950/40 text-red-200`:M.copyText?`border-green-900/60 bg-green-950/30 text-green-300`:`border-slate-700 bg-[#0e1116] text-slate-300`}`,children:[(0,L.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:M.message}),M.copyText?(0,L.jsx)(`button`,{type:`button`,onClick:()=>void zO(M.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,L.jsx)(Ue,{size:13})}):null,(0,L.jsx)(`button`,{type:`button`,onClick:()=>ne(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,L.jsx)(xt,{size:13})})]}):null,N?(0,L.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`&&_e()},children:(0,L.jsxs)(`div`,{className:`w-full max-w-md rounded-sm border border-slate-700 bg-[#151f24] shadow-2xl`,children:[(0,L.jsxs)(`div`,{className:`flex items-start justify-between gap-3 border-b border-slate-800 px-4 py-3`,children:[(0,L.jsxs)(`div`,{children:[(0,L.jsx)(`div`,{className:`text-sm font-semibold text-slate-100`,children:`Pasted image detected`}),(0,L.jsx)(`div`,{className:`mt-1 text-xs text-slate-400`,children:`Upload this clipboard image to ~/.pibo/uploads?`})]}),(0,L.jsx)(`button`,{type:`button`,onClick:_e,className:`rounded-sm p-1 text-slate-500 hover:bg-slate-800 hover:text-slate-200`,"aria-label":`Cancel pasted image upload`,children:(0,L.jsx)(xt,{size:14})})]}),(0,L.jsxs)(`div`,{className:`space-y-3 px-4 py-4`,children:[(0,L.jsx)(`img`,{src:N.previewUrl,alt:`Pasted clipboard image preview`,className:`max-h-64 w-full rounded-sm border border-slate-800 bg-[#0e1116] object-contain`}),(0,L.jsxs)(`div`,{className:`flex items-center justify-between gap-3 text-xs text-slate-400`,children:[(0,L.jsx)(`span`,{className:`min-w-0 truncate font-mono`,children:N.file.name}),(0,L.jsx)(`span`,{className:`shrink-0 font-mono`,children:YO(N.file.size)})]})]}),(0,L.jsxs)(`div`,{className:`flex justify-end gap-2 border-t border-slate-800 px-4 py-3`,children:[(0,L.jsx)(`button`,{type:`button`,onClick:_e,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,L.jsx)(`button`,{ref:b,type:`button`,onClick:()=>void ye(),disabled:te,className:`h-8 rounded-sm bg-[#11a4d4] px-3 text-xs font-medium text-white disabled:opacity-50`,children:`Upload image`})]})]})}):null,F.length?(0,L.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:F.map((e,t)=>(0,L.jsxs)(`button`,{ref:t===E?S:null,type:`button`,onClick:()=>pe(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,L.jsxs)(`span`,{className:`font-mono text-emerald-400`,children:[`$`,e.name]}),(0,L.jsx)(`span`,{className:`text-xs text-slate-400`,children:e.description??e.path??``})]},e.name))}):null,s.length?(0,L.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,L.jsxs)(`div`,{className:`mb-1.5 flex items-center justify-between gap-2`,children:[(0,L.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Attached uploads`}),(0,L.jsx)(`button`,{type:`button`,onClick:m,className:`text-[11px] text-slate-500 hover:text-[#11a4d4]`,children:`Clear`})]}),(0,L.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:s.map(e=>(0,L.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,L.jsx)(`span`,{className:`min-w-0 truncate`,children:BO(e.name||e.path,100)}),(0,L.jsx)(`button`,{type:`button`,onClick:()=>void zO(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,L.jsx)(Ue,{size:11})}),(0,L.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,L.jsx)(xt,{size:11})})]},e.id))})]}):null,o.length?(0,L.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,L.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,L.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Attached web annotations`}),(0,L.jsx)(`button`,{type:`button`,onClick:d,className:`text-[11px] text-slate-500 hover:text-[#11a4d4]`,children:`Clear`})]}),(0,L.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:o.map(e=>(0,L.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,L.jsx)(`span`,{className:`min-w-0 truncate`,children:BO(e.primaryTarget||e.label||e.note||e.id,100)}),(0,L.jsx)(xt,{size:11,className:`shrink-0 text-[#11a4d4]`})]},e.id))})]}):null,ue.length?(0,L.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:ue.map((e,t)=>(0,L.jsxs)(`button`,{ref:t===w?x:null,type:`button`,onClick:()=>{c(e.slash),de(UO(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,L.jsx)(`span`,{className:`font-mono text-[#11a4d4]`,children:e.slash}),(0,L.jsx)(`span`,{className:`text-xs text-slate-400`,children:e.description})]},e.slash))}):null,(0,L.jsxs)(`div`,{className:`grid grid-cols-[1fr_auto] items-end gap-2`,children:[(0,L.jsx)(`textarea`,{id:`message-composer-input`,ref:_,"data-pibo-debug":`composer-input`,"data-pibo-session-id":e??void 0,"data-pibo-state":t?`disabled`:i?`non-empty`:`empty`,rows:1,value:i,disabled:t,onChange:e=>{C.current=null,c(e.target.value),k(e.target.selectionStart)},onKeyDown:e=>{if(e.key===`Escape`&&(F.length||ue.length)){e.preventDefault(),e.stopPropagation(),fe();return}if(F.length&&(e.key===`ArrowDown`||e.key===`ArrowUp`)){e.preventDefault(),D(t=>e.key===`ArrowDown`?(t+1)%F.length:(t-1+F.length)%F.length);return}if(ue.length&&(e.key===`ArrowDown`||e.key===`ArrowUp`)){e.preventDefault(),T(t=>e.key===`ArrowDown`?(t+1)%ue.length:(t-1+ue.length)%ue.length);return}if((e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&he(e.key===`ArrowUp`?`previous`:`next`)){e.preventDefault();return}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),I())},onPaste:ve,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,L.jsx)(`button`,{type:`button`,disabled:t||te,onClick:()=>void I(),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,L.jsx)(ht,{size:16})})]})]})}function HO(e,t){return`skill:${e}:${t}`}function UO(e){return`command:${e}`}function WO(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(GO)}function GO(e){return e.name&&e.name!==`image.png`?e:new File([e],KO(e.type),{type:e.type||`image/png`,lastModified:Date.now()})}function KO(e){let t=qO(e),n=new Date;return`screenshot-${[n.getFullYear(),JO(n.getMonth()+1),JO(n.getDate()),`-`,JO(n.getHours()),JO(n.getMinutes()),JO(n.getSeconds())].join(``)}${t}`}function qO(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 JO(e){return String(e).padStart(2,`0`)}function YO(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KiB`:`${(e/(1024*1024)).toFixed(1)} MiB`}function XO(e){if(!e)return;if(e.value&&!e.value.includes(`
|
|
41
|
-
`)&&e.value.length<80){e.style.height=``,e.style.overflowY=`hidden`;return}let t=window.getComputedStyle(e),n=ZO(t.lineHeight,20),r=ZO(t.borderTopWidth)+ZO(t.borderBottomWidth),i=n*5+ZO(t.paddingTop)+ZO(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 ZO(e,t=0){let n=Number.parseFloat(e);return Number.isFinite(n)?n:t}var QO=`pibo.chat.webAnnotations.cdpUrl`,$O=`pibo.chat.webAnnotations.selected`,ek=`${$O}.`,tk=`pibo.chat.webAnnotations.overlay.`,nk=`pibo.chat.webAnnotations.panelCollapsed`,rk=`pibo.chat.shortcuts.webAnnotationsToggle`,ik=`Alt+Shift+A`;function ak(){try{return localStorage.getItem(QO)??``}catch{return``}}function ok(e){try{e.trim()?localStorage.setItem(QO,e.trim()):localStorage.removeItem(QO)}catch{}}function sk(){try{return localStorage.getItem(rk)||`Alt+Shift+A`}catch{return ik}}function ck(e){try{return uk(localStorage.getItem(lk(e)))}catch{return null}}function lk(e){return tk+e}function uk(e){if(!e)return null;try{return dk(JSON.parse(e))}catch{return null}}function dk(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 fk(e){try{let t=mk(localStorage.getItem($O));if(t.length||!e)return t;let n=ek+e,r=mk(localStorage.getItem(n));return r.length&&(localStorage.setItem($O,JSON.stringify(r)),localStorage.removeItem(n)),r}catch{return[]}}function pk(e,t){try{let n=[...new Set(t.filter(e=>e.trim()))].slice(0,5);n.length?localStorage.setItem($O,JSON.stringify(n)):localStorage.removeItem($O),e&&localStorage.removeItem(ek+e)}catch{}}function mk(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 hk(){try{return localStorage.getItem(nk)===`true`}catch{return!1}}function gk(e){try{localStorage.setItem(nk,String(e))}catch{}}var _k=`web-annotations-dialog`,vk=`web-annotations-session-panel-details`;function yk({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,L.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,L.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,L.jsx)(`div`,{className:`min-w-0`,children:(0,L.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,L.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Web annotations`}),(0,L.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,L.jsxs)(`span`,{className:`rounded-sm border border-[#11a4d4]/50 px-1.5 py-0.5 text-[10px] text-[#11a4d4]`,children:[n.length,` attached`]}):null]})}),(0,L.jsxs)(`div`,{className:`ml-auto flex shrink-0 items-center gap-1`,children:[(0,L.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,L.jsx)(dt,{size:12,className:r?`animate-spin`:void 0})}),(0,L.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,L.jsx)(_t,{size:12})}),(0,L.jsx)(`button`,{type:`button`,onClick:l,title:a?`Expand annotations panel`:`Collapse annotations panel`,"aria-label":`Web annotations details`,"aria-expanded":!a,"aria-controls":vk,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,L.jsx)(Ie,{size:12}):(0,L.jsx)(Pe,{size:12})}),(0,L.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,L.jsx)(xt,{size:12})})]})]}),(0,L.jsxs)(`div`,{id:vk,hidden:a,children:[(0,L.jsx)(`div`,{className:`text-[11px] text-slate-500`,children:`Global annotation list. Selected attachments follow you when switching sessions.`}),i?(0,L.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:Ak(i,220)}):r&&!t.length?(0,L.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,L.jsx)(`div`,{className:`mt-2 grid max-h-[min(40svh,18rem)] grid-cols-1 gap-2 overflow-y-auto pr-1 sm:max-h-56 sm:grid-cols-[repeat(auto-fill,minmax(16rem,1fr))]`,"data-pibo-debug":`web-annotations-list`,children:t.map((e,t)=>{let r=n.includes(e.id),i=Ak(e.primaryTarget||e.label||e.selector||e.targetKind||`target`,64),a=`${t+1}: ${i}`;return(0,L.jsxs)(`div`,{"data-pibo-debug":`web-annotation-chip`,"data-web-annotation-id":e.id,"data-web-annotation-session-id":e.piboSessionId,"data-web-annotation-selected":r?`true`:`false`,className:`min-w-0 rounded-sm border px-3 py-2 text-xs ${r?`border-[#11a4d4] bg-[#11a4d4]/10`:`border-slate-800 bg-[#0e1116]`}`,children:[(0,L.jsxs)(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[(0,L.jsxs)(`span`,{className:`min-w-0 truncate font-mono text-[11px] text-slate-500`,children:[e.status,` · `,e.targetKind]}),(0,L.jsxs)(`button`,{type:`button`,onClick:()=>s(e.id),"aria-pressed":r,"aria-label":`Include web annotation ${a}`,title:`${r?`Detach`:`Attach`} web annotation ${a}`,className:`inline-flex h-8 shrink-0 items-center gap-1 rounded-sm border px-2 text-[11px] sm:h-6 sm:px-1.5 ${r?`border-[#11a4d4] text-[#11a4d4]`:`border-slate-700 text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:[r?(0,L.jsx)(xt,{size:11}):(0,L.jsx)(ut,{size:11}),` `,r?`Detach`:`Attach`]})]}),(0,L.jsx)(`div`,{className:`truncate text-slate-200`,title:e.primaryTarget||e.label||e.selector||e.id,children:Ak(e.primaryTarget||e.label||e.selector||e.id,120)}),e.piboContext?(0,L.jsx)(`div`,{className:`truncate font-mono text-[11px] text-[#11a4d4]`,title:e.piboContext,children:Ak(e.piboContext,140)}):null,(0,L.jsx)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:e.url,children:Dk(e.url)}),(0,L.jsxs)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:kk(e),children:[`Source `,Ok(e)]}),(0,L.jsx)(`div`,{className:`mt-1 line-clamp-2 text-slate-400`,title:e.note,children:Ak(e.note,180)}),(0,L.jsx)(`div`,{className:`mt-1 text-[11px] text-slate-600`,children:jk(e.createdAt)})]},e.id)})}):(0,L.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 bk({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)(()=>ak()),[p,m]=(0,v.useState)([]),[h,g]=(0,v.useState)(`idle`),[_,y]=(0,v.useState)(!1),[b,x]=(0,v.useState)(null),S=(0,v.useRef)(null),C=(0,v.useRef)(null),w=()=>{c(!1),S.current?.focus()};(0,v.useEffect)(()=>{n&&c(!1)},[n]),(0,v.useEffect)(()=>{if(!s||n)return;C.current?.focus();let e=e=>{e.key===`Escape`&&(e.preventDefault(),w())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[s,n]),(0,v.useEffect)(()=>{ok(d)},[d]);let T=async()=>{if(e){g(`loading`),x(null);try{m((await Ux(d)).targets.filter(e=>e.type===`page`||e.attachable)),g(`loaded`)}catch(e){let t=Tk(e,`CDP unavailable`);m([]),g(`error`),x({kind:`error`,message:t}),o(t)}}},E=async n=>{if(!e)throw Error(`No active session context`);return Gx(n.binding.id,Sk({piboSessionId:e,piboRoomId:t,cdpUrl:d,annotationShortcut:sk()}))},D=async()=>{if(!(!e||_)){i(),y(!0),x({kind:`info`,message:`Injecting annotation overlay into this Pibo page…`});try{let n=await Wx({piboSessionId:e,piboRoomId:t,url:window.location.href,title:document.title,sameOrigin:!0,annotationShortcut:sk()});if(!n.overlay)throw Error(`Overlay config missing from same-origin binding response`);await wk(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=Tk(e,`Current-page annotation failed`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}}},O=async()=>{if(!e||_)return;i();let n=l.trim();if(!n){x({kind:`error`,message:`URL is required`});return}if(Ck(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 Wx(Sk({piboSessionId:e,piboRoomId:t,url:n,cdpUrl:d})),i=await E(r);x({kind:`success`,message:`Annotation overlay injected for ${Ek(i.target??r.target,i.binding.url)}`}),u(``),o(null)}catch(e){let t=Tk(e,`Annotation failed`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}},k=async n=>{if(!(!e||_)){i(),y(!0),x({kind:`info`,message:`Binding selected target and injecting overlay…`});try{let r=await E(await Wx(Sk({piboSessionId:e,piboRoomId:t,targetId:n.id,cdpUrl:d})));x({kind:`success`,message:`Annotation overlay injected for ${Ek(r.target??n,r.binding.url)}`}),o(null)}catch(e){let t=Tk(e,n.attachable?`Target annotation failed`:`Target not attachable`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}}};return(0,L.jsxs)(`div`,{className:`relative`,"data-pibo-debug":`web-annotations-entry`,"data-pibo-session-id":e??void 0,children:[(0,L.jsx)(xk,{buttonRef:S,onClick:()=>{n||(c(e=>!e),r||i())},title:n?`Select an active session to annotate a web page`:r?`Web Annotations`:`Show Web Annotations`,ariaLabel:`Web Annotations`,ariaHaspopup:`dialog`,ariaExpanded:s,ariaControls:_k,disabled:n,active:s||r,children:(0,L.jsx)(Ee,{size:14})}),s&&!n?(0,L.jsxs)(`div`,{id:_k,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,L.jsxs)(`div`,{className:`mb-2 flex items-start justify-between gap-3`,children:[(0,L.jsxs)(`div`,{children:[(0,L.jsx)(`div`,{className:`text-xs font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Web Annotations`}),(0,L.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,L.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,L.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,L.jsx)(pt,{size:14})}),(0,L.jsx)(`button`,{type:`button`,onClick:w,className:`rounded-sm p-1 text-slate-500 hover:bg-slate-800 hover:text-slate-200`,"aria-label":`Close Web Annotations panel`,children:(0,L.jsx)(xt,{size:14})})]})]}),(0,L.jsx)(`button`,{ref:C,type:`button`,onClick:()=>void D(),disabled:_,className:`mb-3 h-10 w-full rounded-sm bg-emerald-600 px-3 text-xs font-medium text-white hover:bg-emerald-500 disabled:opacity-50 sm:h-9`,"data-pibo-debug":`web-annotations-current-page`,children:`Annotate this Pibo page`}),(0,L.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,L.jsxs)(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-[1fr_auto]`,children:[(0,L.jsx)(`input`,{id:`web-annotation-url`,value:l,onChange:e=>u(e.target.value),onKeyDown:e=>{e.key===`Enter`&&O()},placeholder:`http://localhost:5173`,disabled:_,className:`h-10 min-w-0 rounded-sm border border-slate-700 bg-[#151f24] px-2 text-base text-slate-100 outline-none focus:border-[#11a4d4] disabled:opacity-60 sm:h-9 sm:text-xs`}),(0,L.jsx)(`button`,{type:`button`,onClick:()=>void O(),disabled:_||!l.trim(),className:`h-10 rounded-sm bg-[#11a4d4] px-3 text-xs font-medium text-white disabled:opacity-50 sm:h-9`,children:`Annotate`})]}),(0,L.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,L.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,L.jsxs)(`div`,{className:`mt-3 flex items-center justify-between gap-2`,children:[(0,L.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-slate-500`,children:`Existing targets`}),(0,L.jsxs)(`button`,{type:`button`,onClick:()=>void T(),disabled:_||h===`loading`,className:`inline-flex h-7 items-center gap-1 rounded-sm border border-slate-700 px-2 text-[11px] text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:opacity-50`,children:[(0,L.jsx)(dt,{size:12,className:h===`loading`?`animate-spin`:void 0}),` Refresh`]})]}),(0,L.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,L.jsx)(`div`,{className:`px-3 py-3 text-xs text-slate-500`,children:`Refresh to list reachable browser targets.`}):null,h===`loading`?(0,L.jsx)(`div`,{className:`px-3 py-3 text-xs text-slate-400`,children:`Loading targets…`}):null,h===`loaded`&&!p.length?(0,L.jsx)(`div`,{className:`px-3 py-3 text-xs text-slate-500`,children:`No attachable browser targets found.`}):null,p.map(e=>(0,L.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,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsx)(`div`,{className:`truncate text-xs text-slate-200`,title:e.title||e.url,children:Ak(e.title||`Untitled target`,120)}),(0,L.jsx)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:e.url,children:Ak(e.url||e.id,160)})]}),(0,L.jsx)(`button`,{type:`button`,onClick:()=>void k(e),disabled:_||!e.attachable,title:e.attachable?`Attach selected target`:`Target is not attachable`,className:`h-9 rounded-sm border border-slate-700 px-2 text-[11px] text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:opacity-40 sm:h-8`,children:`Attach`})]},e.id))]}),b?(0,L.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 xk({buttonRef:e,title:t,ariaLabel:n,ariaHaspopup:r,ariaExpanded:i,ariaControls:a,disabled:o,active:s,onClick:c,children:l}){return(0,L.jsx)(`button`,{ref:e,type:`button`,onClick:c,disabled:o,title:t,"aria-label":n,"aria-haspopup":r,"aria-expanded":i,"aria-controls":a,className:`h-8 w-8 inline-flex items-center justify-center border rounded-sm transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${s?`border-[#11a4d4] bg-[#11a4d4]/10 text-[#11a4d4]`:`border-slate-700 text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:l})}function Sk(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e&&e.trim()))}function Ck(e){try{let t=new URL(e);return t.port===`56663`||t.pathname.startsWith(`/json/`)}catch{return!1}}function wk(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 Tk(e,t){let n=Mk(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 Ek(e,t){let n=e?.url||t||e?.title||`target`;return Dk(e?.title||n)}function Dk(e){try{let t=new URL(e);return`${t.host}${t.pathname===`/`?``:t.pathname}`}catch{return Ak(e,80)}}function Ok(e){return e.piboRoomId?`${Ak(e.piboSessionId,24)} · room ${Ak(e.piboRoomId,18)}`:Ak(e.piboSessionId,44)}function kk(e){return e.piboRoomId?`Session ${e.piboSessionId} in room ${e.piboRoomId}`:`Session ${e.piboSessionId}`}function Ak(e,t){return e.length>t?`${e.slice(0,Math.max(0,t-1))}…`:e}function jk(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{dateStyle:`short`,timeStyle:`short`})}function Mk(e){return e instanceof Error?e.message:String(e)}function Nk(e){return!!e.workflowRunId||e.state===`workflow`||e.workflowId!==`simple-chat`}function Pk(e,t){return{workflowId:e.workflowId,state:Ik(e,t),...e.workflowRunId?{workflowRunId:e.workflowRunId}:{}}}function Fk({summary:e}){return(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(`span`,{className:`text-slate-600`,children:`·`}),(0,L.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,L.jsxs)(`span`,{className:Lk(e.state),children:[`state `,e.state]}),e.workflowRunId?(0,L.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 `,Rk(e.workflowRunId)]}):null]})}function Ik(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 Lk(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 Rk(e){return e.length>18?`${e.slice(0,10)}…${e.slice(-6)}`:e}function zk({title:e,roomLabel:t,headerPiboSessionId:n,piboSessionId:r,piboRoomId:i,webAnnotationsDisabled:a,webAnnotationsPanelRendered:o,workflowHeader:s,sessionViewId:c,sessionViews:l,currentSessionView:u,allowedSessionViewIds:d,extraViewTabs:f,activeViewId:p,terminalFullscreenAvailable:m,onEnterTerminalFullscreen:h,onOpenSessionWindow:g,showRawEvents:_,showThinking:y,expandThinking:b,onShowWebAnnotationsPanel:x,onHideWebAnnotationsPanel:S,onSelectSessionView:C,onToggleRawEvents:w,onToggleThinking:T,onToggleExpandThinking:E,onError:D}){let[O,k]=(0,v.useState)(null),A=(0,v.useRef)(void 0),ee=O===n,te=p??c,j=(0,v.useMemo)(()=>d?new Set(d):null,[d]);(0,v.useEffect)(()=>()=>{A.current&&window.clearTimeout(A.current)},[]);let M=()=>{n&&(zO(n).catch(()=>void 0),k(n),A.current&&window.clearTimeout(A.current),A.current=window.setTimeout(()=>k(null),900))};return(0,L.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,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsx)(`h1`,{className:`text-base font-semibold truncate`,children:e}),(0,L.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 font-mono text-[11px] text-slate-500`,children:[(0,L.jsx)(`span`,{className:`truncate`,children:t}),n?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(`span`,{className:`text-slate-600`,children:`·`}),(0,L.jsx)(`button`,{type:`button`,onMouseDown:e=>e.preventDefault(),onClick:()=>void M(),title:ee?`Copied Pibo session ID`:`Copy Pibo session ID`,"aria-label":ee?`Copied Pibo session ID`:`Copy Pibo session ID`,className:`min-w-0 max-w-48 truncate rounded-sm px-1 font-mono underline-offset-2 transition-colors duration-150 focus:outline-none focus:ring-1 focus:ring-[#11a4d4] ${ee?`bg-emerald-500/15 text-emerald-300 ring-1 ring-emerald-400/50`:`text-slate-400 hover:text-[#11a4d4] hover:underline`}`,children:n})]}):null,s?(0,L.jsx)(Fk,{summary:s}):null]})]}),(0,L.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,L.jsx)(bk,{piboSessionId:r,piboRoomId:i,disabled:a,panelVisible:o,onShowPanel:x,onHidePanel:S,onError:D}),g?(0,L.jsx)(`button`,{type:`button`,onClick:g,title:`Open selected session in new window`,"aria-label":`Open selected session in new window`,"data-pibo-debug":`open-session-window`,className:`h-8 w-8 inline-flex items-center justify-center border border-slate-700 rounded-sm text-slate-400 transition-colors hover:border-[#11a4d4] hover:text-[#11a4d4]`,children:(0,L.jsx)(ut,{size:15})}):null,(0,L.jsxs)(`div`,{role:`group`,"aria-label":`Session views`,className:`flex items-center rounded-sm border border-slate-700 bg-[#0e1116] p-0.5`,children:[l.map(e=>{let t=!!(j&&!j.has(e.id));return(0,L.jsx)(`button`,{type:`button`,onClick:()=>{t||C(e.id)},disabled:t,title:t?`Project session routing uses the ${u.label} view for this session kind.`:e.description??e.label,"aria-label":t?`${e.label} view unavailable for this Project session kind`:`Switch to ${e.label} view`,"aria-pressed":te===e.id,className:`min-w-20 px-2.5 py-1 text-[11px] font-bold tracking-wide max-[980px]:min-w-0 max-[980px]:px-1.5 disabled:cursor-not-allowed disabled:text-slate-600 ${te===e.id?`bg-[#11a4d4]/10 text-[#11a4d4]`:`text-slate-400 hover:text-[#11a4d4] disabled:hover:text-slate-600`}`,children:e.label},e.id)}),f?.map(e=>{let t=e.active??te===e.id;return(0,L.jsx)(`button`,{type:`button`,onClick:()=>{e.disabled||e.onSelect()},disabled:e.disabled,title:e.description??e.label,"aria-label":e.disabled?`${e.label} view unavailable`:`Switch to ${e.label} view`,"aria-pressed":t,className:`min-w-20 px-2.5 py-1 text-[11px] font-bold tracking-wide max-[980px]:min-w-0 max-[980px]:px-1.5 disabled:cursor-not-allowed disabled:text-slate-600 ${t?`bg-[#11a4d4]/10 text-[#11a4d4]`:`text-slate-400 hover:text-[#11a4d4] disabled:hover:text-slate-600`}`,children:e.label},e.id)})]}),m&&h?(0,L.jsx)(`button`,{type:`button`,onClick:h,title:`Enter Terminal fullscreen`,"aria-label":`Enter Terminal fullscreen`,"data-pibo-debug":`enter-terminal-fullscreen`,className:`h-8 w-8 inline-flex items-center justify-center border border-slate-700 rounded-sm text-slate-400 transition-colors hover:border-[#11a4d4] hover:text-[#11a4d4]`,children:(0,L.jsx)(st,{size:14})}):null,(0,L.jsx)(Bk,{onClick:w,title:_?`Hide Raw Events`:`Show Raw Events`,ariaLabel:`Raw Events`,active:_,children:(0,L.jsx)(ke,{size:14})}),(0,L.jsx)(Bk,{onClick:T,title:y?`Hide Thinking`:`Show Thinking`,ariaLabel:`Thinking`,active:y,children:y?(0,L.jsx)(Oe,{size:14}):(0,L.jsx)(qe,{size:14})}),y?(0,L.jsx)(Bk,{onClick:E,title:b?`Collapse Thinking`:`Expand Thinking`,ariaLabel:`Thinking expansion`,active:b,children:b?(0,L.jsx)(Pe,{size:14}):(0,L.jsx)(Ie,{size:14})}):null]})]})}function Bk({title:e,ariaLabel:t,active:n,onClick:r,children:i}){return(0,L.jsx)(`button`,{type:`button`,onClick:r,title:e,"aria-label":t,"aria-pressed":n,className:`h-8 w-8 inline-flex items-center justify-center border rounded-sm transition-colors ${n?`border-[#11a4d4] bg-[#11a4d4]/10 text-[#11a4d4]`:`border-slate-700 text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:i})}function Vk(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&Hk(e,n)){e.count+=1,e.createdAt=n.createdAt,e.payload={...Gk(e.payload)?e.payload:{},text:`${Uk(e.payload)}${Uk(n.payload)}`};continue}t.push({...n,count:1})}return t}function Hk(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=Gk(e.payload)?e.payload:{},r=Gk(t.payload)?t.payload:{};return Wk(n)===Wk(r)}function Uk(e){return Gk(e)?typeof e.text==`string`?e.text:typeof e.delta==`string`?e.delta:``:``}function Wk(e){return e.eventId??e.messageId}function Gk(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Kk({traceView:e,eventLimit:t,isFetching:n,visible:r,onLoadOlder:i}){let a=(0,v.useMemo)(()=>r?Vk(e?.rawEvents??[]):[],[e?.rawEvents,r]);return r?(0,L.jsxs)(`aside`,{className:`min-h-0 overflow-auto bg-[#0e1116] border-l border-slate-800 max-[980px]:hidden`,children:[(0,L.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,L.jsxs)(`div`,{className:`p-3 flex flex-col gap-2`,children:[e&&a.length>=t?(0,L.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,L.jsxs)(`div`,{className:`border-l-2 border-[#11a4d4] bg-[#151f24] p-2`,children:[(0,L.jsxs)(`div`,{className:`flex items-center justify-between gap-2 text-[#11a4d4] font-mono text-[11px] mb-1`,children:[(0,L.jsx)(`span`,{children:e.type}),e.count>1?(0,L.jsxs)(`span`,{className:`text-slate-500`,children:[`x`,e.count]}):null]}),(0,L.jsx)(fl,{value:e.payload,showControls:!1})]},e.id))]})]}):null}function qk({title:e,onOpenSessionWindow:t,onExit:n}){return(0,L.jsxs)(`div`,{"data-pibo-debug":`terminal-fullscreen-top-bar`,className:`h-7 min-h-7 flex items-center border-b border-slate-600 bg-[#151f24]`,children:[(0,L.jsx)(`div`,{className:`min-w-0 flex-1 truncate text-base font-semibold leading-none`,children:e}),t?(0,L.jsx)(`button`,{type:`button`,onClick:t,title:`Open selected session in new window`,"aria-label":`Open selected session in new window`,"data-pibo-debug":`open-session-window`,className:`h-full w-7 shrink-0 inline-flex items-center justify-center text-slate-400 hover:bg-[#11a4d4]/10 hover:text-[#11a4d4]`,children:(0,L.jsx)(ut,{size:14})}):null,(0,L.jsx)(`button`,{type:`button`,onClick:n,title:`Show normal top bar`,"aria-label":`Exit Terminal fullscreen`,className:`h-full w-7 shrink-0 inline-flex items-center justify-center text-slate-400 hover:bg-[#11a4d4]/10 hover:text-[#11a4d4]`,children:(0,L.jsx)(lt,{size:14})})]})}function Jk({enabled:e,onFilesDropped:t,children:n,className:r,...i}){let a=(0,v.useRef)(0),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(0),u=c>0;(0,v.useEffect)(()=>{e||(a.current=0,s(!1))},[e]);let d=()=>{a.current=0,s(!1)},f=t=>Xk(t.dataTransfer)?(t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=e&&!u?`copy`:`none`,!0):!1,p=t=>{!f(t)||!e||u||(a.current+=1,s(!0))},m=e=>{f(e)},h=e=>{!f(e)||a.current===0||(a.current=Math.max(0,a.current-1),a.current===0&&s(!1))},g=async n=>{if(!f(n)||(d(),!e||u))return;let r=Zk(n.dataTransfer);if(r.length){l(r.length);try{await t(r)}finally{l(0)}}},_=u?`uploading`:o?`drag-active`:`idle`;return(0,L.jsxs)(`main`,{...i,"data-pibo-file-drop-state":_,className:`relative ${r??``}`,onDragEnter:p,onDragOver:m,onDragLeave:h,onDragEnd:d,onDrop:g,children:[n,o||u?(0,L.jsx)(Yk,{uploadingFileCount:c}):null]})}function Yk({uploadingFileCount:e}){let t=e>0;return(0,L.jsx)(`div`,{"data-pibo-debug":`terminal-file-drop-overlay`,"data-pibo-state":t?`uploading`:`drag-active`,role:`status`,"aria-live":`polite`,className:`pointer-events-none absolute inset-0 z-40 grid place-items-center bg-[#071015]/90 p-6 backdrop-blur-[2px]`,children:(0,L.jsxs)(`div`,{className:`flex max-w-sm flex-col items-center rounded-sm border border-dashed border-[#11a4d4] bg-[#0e1116]/95 px-8 py-7 text-center shadow-2xl shadow-black/50`,children:[t?(0,L.jsx)(at,{size:36,className:`mb-3 animate-spin text-[#11a4d4]`,"aria-hidden":`true`}):(0,L.jsx)(yt,{size:36,className:`mb-3 text-[#11a4d4]`,"aria-hidden":`true`}),(0,L.jsx)(`span`,{className:`text-sm font-semibold text-slate-100`,children:t?`Uploading ${e} file${e===1?``:`s`}…`:`Drop files to upload`}),(0,L.jsx)(`span`,{className:`mt-1 text-xs leading-5 text-slate-400`,children:t?`Saving to ~/.pibo/uploads`:`Images and other files will be attached to your next message.`})]})})}function Xk(e){return Array.from(e.types).includes(`Files`)||Array.from(e.items).some(e=>e.kind===`file`)}function Zk(e){return Array.from(e.files)}function Qk({selectedPiboSessionId:e,selectedRoomId:t,fallbackRoomId:n,sessionViewId:r,loadingTrace:i,roomNavigationPending:a=!1,sessionNavigationPending:o=!1,traceError:s,showRawEvents:c,currentTraceView:l,rawEventLimit:u,tracePageFetching:d,onLoadMoreRawEvents:f,terminalFullscreen:p,terminalFileDropEnabled:m,onTerminalFilesDropped:h,onOpenSessionWindow:g,onExitTerminalFullscreen:_,headerProps:v,projectSessionCreatePanel:y,workflowStartPanel:b,projectModulePanel:x,currentSessionView:S,sessionViewProps:C,webAnnotationsPanelRendered:w,webAnnotationsPanelProps:T,composerProps:E}){let D=a||o&&!l||i;return(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(Jk,{enabled:m,onFilesDropped:h,"data-pibo-debug":`chat-shell`,"data-pibo-session-id":e??void 0,"data-pibo-room-id":t??n??void 0,"data-pibo-view-id":r,"data-pibo-state":a?`room-loading`:o?`session-loading`:i?`loading`:s?`error`:e?`ready`:`empty`,"data-pibo-terminal-fullscreen":p?`true`:`false`,className:`min-h-0 flex flex-col`,children:[p?(0,L.jsx)(qk,{title:v.title,onOpenSessionWindow:g,onExit:_}):(0,L.jsx)(zk,{...v}),!p&&y?(0,L.jsx)(`div`,{className:`border-b border-slate-800 bg-[#101d22] px-4 py-3`,children:y}):null,!p&&b?(0,L.jsx)(`div`,{className:`border-b border-slate-800 bg-[#101d22] px-4 py-3`,children:b}):null,!p&&x?x:D?(0,L.jsx)($k,{label:a?`Loading room`:`Loading session`}):s&&!l?(0,L.jsx)(`div`,{className:`min-h-0 flex-1 p-4 text-sm text-red-200`,children:s}):S.render({...C,terminalFullscreen:p}),!p&&w?(0,L.jsx)(yk,{...T}):null,(0,L.jsx)(VO,{...E})]}),(0,L.jsx)(Kk,{traceView:l,eventLimit:u,isFetching:d,visible:c&&!p,onLoadOlder:f})]})}function $k({label:e}){return(0,L.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,L.jsx)(`div`,{className:`min-h-0 h-full overflow-hidden font-mono text-[12px] leading-[1.45]`,children:(0,L.jsxs)(`div`,{className:`px-4`,children:[(0,L.jsx)(`div`,{className:`group border-b border-[#141414] py-2`,children:(0,L.jsxs)(`div`,{className:`grid grid-cols-[1.9rem_minmax(0,1fr)] gap-2 leading-[1.45]`,children:[(0,L.jsx)(`span`,{className:`flex items-center text-[#38bdf8]`,children:(0,L.jsx)(`span`,{className:`h-1.5 w-1.5 rounded-full bg-[#38bdf8] animate-pulse`})}),(0,L.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,L.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:e}),(0,L.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,L.jsx)(eA,{kind:e.kind,lineCount:e.lines},t))]})})})}function eA({kind:e,lineCount:t}){let n=e===`command`,r=e===`markdown`;return(0,L.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,L.jsxs)(`div`,{className:`grid grid-cols-[1.9rem_minmax(0,1fr)] gap-2 leading-[1.45]`,children:[(0,L.jsx)(`span`,{className:`flex items-center text-[#737373]`,children:i===0&&!r?(0,L.jsx)(`span`,{className:`h-1.5 w-1.5 rounded-full ${n?`bg-[#f59e0b]`:`bg-[#22c55e]`}`}):i>0&&!r?(0,L.jsx)(`span`,{className:`text-[10px]`,children:`L`}):null}),(0,L.jsx)(`span`,{className:`min-w-0 py-[3px]`,children:i===0?(0,L.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,L.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,L.jsx)(`span`,{className:`h-[13px] w-64 rounded-sm bg-[#262626]`})]}):(0,L.jsx)(`span`,{className:`block h-[10px] rounded-sm bg-[#262626] ${i===t-1?`w-[42%]`:i%2==0?`w-[72%]`:`w-[58%]`}`})})]},i))})}var tA=[`a[href]`,`button:not([disabled])`,`input:not([disabled])`,`select:not([disabled])`,`textarea:not([disabled])`,`[tabindex]:not([tabindex="-1"])`].join(`,`);function nA({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(tA)??l.current)?.focus()});return()=>{window.cancelAnimationFrame(t),e?.isConnected&&e.focus()}},[r]),(0,L.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(tA)??[]);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,L.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,L.jsxs)(`div`,{className:`flex items-start justify-between gap-3 border-b border-slate-800 px-4 py-3`,children:[(0,L.jsxs)(`div`,{children:[(0,L.jsx)(`h2`,{id:s,className:`text-sm font-bold uppercase tracking-wider text-slate-100`,children:e}),(0,L.jsx)(`p`,{id:c,className:`mt-1 text-xs text-slate-400`,children:t})]}),(0,L.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,L.jsx)(xt,{size:14})})]}),i]})})}function rA(e){let t=new Map;if(cA(e.nodes,t),!t.size)return e;let{nodes:n,changed:r}=lA(e.nodes,t);return r?{...e,nodes:n}:e}function iA(e){return e.some(sA)}function aA(e){let t=new Map;return fA(e,e=>{if(e.type!==`user.message`||!e.entryId)return;let n=pA(e),r=t.get(n);r?r.push(e.entryId):t.set(n,[e.entryId])}),t}function oA(e,t){if(!t.size)return;let n=new Map;fA(e,e=>{if(e.type!==`user.message`||!e.entryId)return;let t=pA(e),r=n.get(t)??new Set;r.add(e.entryId),n.set(t,r)});let r=new Map;fA(e,e=>{if(e.type!==`user.message`||e.entryId)return;let i=pA(e),a=t.get(i);if(!a?.length)return;let o=n.get(i)??new Set,s=r.get(i)??0;for(;s<a.length&&o.has(a[s]);)s+=1;let c=a[s];c&&(e.entryId=c,o.add(c),n.set(i,o),r.set(i,s+1))})}function sA(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 cA(e,t){for(let n of e){if(n.type===`user.message`&&!dA(n)&&!uA(n)){let e=pA(n);e&&t.set(e,(t.get(e)??0)+1)}cA(n.children,t)}}function lA(e,t){let n=!1,r=[];for(let i of e){if(dA(i)){let e=pA(i),r=e?t.get(e)??0:0;if(r>0){t.set(e,r-1),n=!0;continue}}let e=lA(i.children,t);n||=e.changed,r.push(e.changed?{...i,children:e.nodes}:i)}return{nodes:n?r:e,changed:n}}function uA(e){return[e.id,e.stableKey].some(e=>e?.startsWith(`event:message_queued:`)||e?.startsWith(`event:message_steered:`))}function dA(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 fA(e,t){for(let n of e)t(n),fA(n.children,t)}function pA(e){return typeof e.output==`string`?e.output:typeof e.summary==`string`?e.summary:``}function mA(e,t,n){return t&&e.set(t.piboSessionId,t),n?e.get(n)??null:null}function hA(e,t,n){t&&t.piboSessionId!==n.piboSessionId&&e.set(t.piboSessionId,t);let r=gA(t?.piboSessionId===n.piboSessionId?t:e.get(n.piboSessionId)??null,n);return r?e.set(n.piboSessionId,r):e.delete(n.piboSessionId),r}function gA(e,t){if(!e||e.piboSessionId!==t.piboSessionId)return e;let n=yA(t),r=_A(t.nodes),i=e.events.filter(e=>{let i=CA(e);if(i&&n.has(i))return!1;if(sA(e)){let t=r.get(e.payload.text)??0;if(t>0)return t===1?r.delete(e.payload.text):r.set(e.payload.text,t-1),!1}return!xA(t,e)});return i.length?{...e,events:i}:null}function _A(e){let t=new Map;for(let n of e){if(n.type===`user.message`&&n.source===`transcript`&&!vA(n)){let e=EA(n);e&&t.set(e,(t.get(e)??0)+1)}for(let[e,r]of _A(n.children))t.set(e,(t.get(e)??0)+r)}return t}function vA(e){return[e.id,e.stableKey].some(e=>e?.startsWith(`event:message_queued:`)||e?.startsWith(`event:message_steered:`))}function yA(e){let t=new Set;for(let n of e.rawEvents){let e=CA(n);e&&t.add(e)}return bA(e.nodes,t),t}function bA(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}`)}if(n.type===`assistant.message`){let e=wA(n,`assistant:`);e&&(t.add(`${n.piboSessionId}:assistant_delta:${e}`),(n.source===`transcript`||n.completedAt!==void 0)&&t.add(`${n.piboSessionId}:assistant_message:${e}`)),n.source===`transcript`&&n.eventId&&(t.add(`${n.piboSessionId}:message_started:${n.eventId}`),t.add(`${n.piboSessionId}:message_finished:${n.eventId}`))}if(n.type===`model.reasoning`){let e=wA(n,`reasoning:`);e&&(t.add(`${n.piboSessionId}:thinking_delta:${e}`),n.source===`transcript`&&(t.add(`${n.piboSessionId}:thinking_started:${e}`),t.add(`${n.piboSessionId}:thinking_finished:${e}`)))}if(n.toolCallId&&(n.type===`tool.call`||n.type===`tool.result`||n.type===`agent.delegation`)){let e=`tool:${n.toolCallId}`;t.add(`${n.piboSessionId}:tool_call:${e}`);let r=n.completedAt!==void 0||n.type===`tool.result`||n.status===`error`;(n.status===`running`||n.output!==void 0||r)&&t.add(`${n.piboSessionId}:tool_execution_started:${e}`),(n.output!==void 0&&!r||r)&&t.add(`${n.piboSessionId}:tool_execution_updated:${e}`),r&&t.add(`${n.piboSessionId}:tool_execution_finished:${e}`)}bA(n.children,t)}}function xA(e,t){let n=t.payload;if(!n||typeof n!=`object`||Array.isArray(n))return!1;let r=`source`in n?n.source:void 0,i=`text`in n?n.text:void 0;return r!==`service`||typeof i!=`string`||!rC(i)?!1:SA(e,t)}function SA(e,t){let n=t.eventSequence;if(n===void 0||e.firstEventSequence===void 0)return!1;let r=e.lastEventSequence??e.eventCount;return r!==void 0&&n>=e.firstEventSequence&&n<=r}function CA(e){let t=e.payload;if(!t||typeof t!=`object`||Array.isArray(t))return;let n=`eventId`in t&&typeof t.eventId==`string`?t.eventId:e.eventId,r=`piboSessionId`in t&&typeof t.piboSessionId==`string`?t.piboSessionId:e.piboSessionId;if(r){if(e.type===`tool_call`||e.type===`tool_execution_started`||e.type===`tool_execution_updated`||e.type===`tool_execution_finished`){let n=`toolCallId`in t&&typeof t.toolCallId==`string`?t.toolCallId:void 0;return n?`${r}:${e.type}:tool:${n}`:void 0}if(n){if(e.type===`assistant_delta`||e.type===`assistant_message`){let i=TA(t,`assistantIndex`)??TA(t,`contentIndex`),a=i===void 0?n:`${n}:assistant:${i}`;return`${r}:${e.type}:${a}`}if(e.type===`thinking_started`||e.type===`thinking_delta`||e.type===`thinking_finished`){let i=TA(t,`thinkingIndex`)??TA(t,`contentIndex`),a=i===void 0?n:`${n}:thinking:${i}`;return`${r}:${e.type}:${a}`}return`${r}:${e.type}:${n}`}}}function wA(e,t){return e.stableKey?.startsWith(t)?e.stableKey.slice(t.length):e.eventId}function TA(e,t){let n=t in e?e[t]:void 0;return typeof n==`number`&&Number.isFinite(n)?n:void 0}function EA(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 DA({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?gA(n,t):null)?.events??[];if(!o.length)return{traceView:t};let s=a?.(),c=lw(t,o,r??`idle`),l=iA(o);return l&&oA(c.nodes,i),{traceView:l?rA(c):c,liveTraceComputeDurationMs:s!==void 0&&a?a()-s:void 0}}function OA(e,t){for(let n of e)t(n),OA(n.children,t)}function kA(e){return typeof e.output==`string`?e.output:typeof e.summary==`string`?e.summary:``}function AA(e){if(!e)return;let t=0;return OA(e.nodes,e=>{e.type===`assistant.message`&&(t+=kA(e).length)}),t}function jA({selectedPiboSessionId:e,baseTraceView:t,liveTraceOverlay:n,selectedSessionStatus:r}){let i=(0,v.useMemo)(()=>t?rA(t):null,[t]),a=(0,v.useMemo)(()=>i?aA(i.nodes):new Map,[i]),o=(0,v.useMemo)(()=>DA({selectedPiboSessionId:e,reconciledBaseTraceView:i,liveTraceOverlay:n,selectedSessionStatus:r,persistedUserMessageIndexForBaseTrace:a,now:uy()?()=>performance.now():void 0}),[n,e,r,i,a]),s=o.traceView;return(0,v.useEffect)(()=>{!e||!s?.piboSessionId||!uy()||(yy(s.piboSessionId,{overlayEventCount:n?.piboSessionId===s.piboSessionId?n.events.length:0,traceBaseOutputLength:AA(t),currentOutputLength:AA(s)}),o.liveTraceComputeDurationMs!==void 0&&gy(s.piboSessionId,o.liveTraceComputeDurationMs))},[t,o.liveTraceComputeDurationMs,s,n,e]),(0,v.useEffect)(()=>{if(!s?.piboSessionId||!jb())return;let e=n?.piboSessionId===s.piboSessionId?n.events:[];Lb({piboSessionId:s.piboSessionId,trigger:`trace-state:render`,baseTraceView:t,currentTraceView:s,overlayEvents:e,selectedSessionStatus:r})},[t,s,n,r]),(0,v.useEffect)(()=>{let e=()=>{if(!s?.piboSessionId||!jb())return;let e=n?.piboSessionId===s.piboSessionId?n.events:[];Lb({piboSessionId:s.piboSessionId,trigger:`trace-state:tab:${document.visibilityState}`,baseTraceView:t,currentTraceView:s,overlayEvents:e,selectedSessionStatus:r})};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[t,s,n,r]),s}var MA=1e4,NA=5*6e4;function PA(e){return[`chat`,`trace-summary`,e]}function FA(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 IA(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:qA(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 LA(e,t){return e.piboSessionId===t.piboSessionId?{...t,nodes:RA(e.nodes,t),rawEvents:GA(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 RA(e,t){let n=VS([...e]),r=VS([...t.nodes]),i=new Set(r.map(e=>e.id)),a=BA([...n,...r]),o=HA(r),s=UA(r),c=n.filter(e=>{if(i.has(e.id))return!0;if(e.type===`agent.turn`&&e.source===`event-log`&&e.eventId&&a.has(e.eventId)||VA(e))return!1;let n=e.orderKey?.eventSequence;if(n!==void 0&&t.firstEventSequence!==void 0)return n<t.firstEventSequence;let r=e.orderKey?o.get(e.orderKey.sourceRank):void 0;if(e.orderKey&&r)return FS(e.orderKey,r)<0;if(e.source===`live`||e.orderKey?.streamId!==void 0)return!1;let c=WA(e.startedAt);return c!==void 0&&s!==void 0&&c<s}),l=new Set([...c,...r].map(e=>e.id)),u=new Set(n.filter(e=>!l.has(e.id)).map(e=>e.id));return qA(zA(c,u),zA(r,u))}function zA(e,t){return e.map(e=>e.parentId&&t.has(e.parentId)?{...e,parentId:void 0}:e)}function BA(e){let t=new Set;for(let n of e)n.source===`transcript`&&n.eventId&&t.add(n.eventId);return t}function VA(e){return e.source===`live`||e.orderKey?.streamId!==void 0}function HA(e){let t=new Map;for(let n of e){if(!n.orderKey)continue;let e=t.get(n.orderKey.sourceRank);(!e||FS(n.orderKey,e)<0)&&t.set(n.orderKey.sourceRank,n.orderKey)}return t}function UA(e){let t;for(let n of e){let e=WA(n.startedAt);e!==void 0&&(t=t===void 0?e:Math.min(t,e))}return t}function WA(e){if(!e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function GA(e,t){if(!t.length)return e;let n=t.reduce((e,t)=>t.eventSequence===void 0?e:e===void 0?t.eventSequence:Math.min(e,t.eventSequence),void 0),r=new Map;for(let t of e)n!==void 0&&t.eventSequence!==void 0&&t.eventSequence>=n||r.set(KA(t),t);for(let e of t)r.set(KA(e),e);return[...r.values()]}function KA(e){return e.id||`${e.eventSequence??``}:${e.type}:${e.createdAt}`}function qA(e,t){let n=new Map;for(let t of VS([...e]))n.set(t.id,{...t,children:[]});for(let e of VS([...t])){let t=n.get(e.id);n.set(e.id,{...t,...e,children:[]})}return HS([...n.values()])}function JA(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??YA(e.cursor.before):void 0;for(let t of e.nodes)n.set(t.nodeId,XA(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??YA(e.cursor.before),lastEventSequence:e.lastEventSequence??YA(e.cursor.after),nextBeforeSequence:o,nextBeforeCursor:a,hasOlderEvents:i,nodes:r,rawEvents:t}}function YA(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function XA(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 ZA=128;function QA({selectedPiboSessionId:e,showRawEvents:t,liveTraceOverlay:n,liveTraceOverlayCacheRef:r,setLiveTraceOverlay:i}){let a=bO(),[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?PA(e):null,[e]),x=(0,v.useMemo)(()=>e?FA(e,{includeRawEvents:!1,rawEventsLimit:0,pageSize:50}):null,[e]),S=PO({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 lx(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:MA,gcTime:NA,refetchOnWindowFocus:!1,retry:1}),C=PO({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 ux(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 JA(r.timeline)},enabled:!!e,staleTime:MA,gcTime:NA,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=>mA(r.current,t,e)),_.current=null,y.current=new Set},[r,a,e,i,x]);let w=PO({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 dx(e,{limit:c,beforeSequence:p,signal:t})},enabled:!!(e&&t),staleTime:MA,gcTime:NA,refetchOnWindowFocus:!1,retry:1});(0,v.useEffect)(()=>{let t=C.data;!t||t.piboSessionId!==e||(uy()&&yy(t.piboSessionId,{overlayEventCount:0,traceBaseOutputLength:AA(t),traceBaseUpdated:!0}),(0,v.startTransition)(()=>{d(e=>{let n=e?.piboSessionId===t.piboSessionId?LA(e,t):t;return f.current.set(t.piboSessionId,n),n}),i(e=>hA(r.current,e,t))}))},[r,e,i,C.data]),(0,v.useEffect)(()=>{let t=u;!t||t.piboSessionId!==e||(0,v.startTransition)(()=>{i(e=>hA(r.current,e,t))})},[u,r,e,i]),(0,v.useEffect)(()=>{let t=w.data;!t||t.piboSessionId!==e||(0,v.startTransition)(()=>{d(e=>{if(!e)return e;if(p===void 0)return{...e,rawEvents:t.events};let n=new Set(t.events.map(e=>e.id));return{...e,rawEvents:[...t.events,...e.rawEvents.filter(e=>!n.has(e.id))]}})})},[p,w.data,e]);let T=(0,v.useCallback)(async n=>{if(!e||!n)return;let r=`${e}:${n}`;if(_.current||y.current.has(r))return;_.current=r,g(!0);let i=FA(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 ux(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 JA(o.timeline)},staleTime:MA,gcTime:NA});(0,v.startTransition)(()=>{d(e=>e?IA(e,t):t),s(e=>e+(t.pageSize??50))}),$A(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 $A(e,t){if(e.add(t),e.size<=ZA)return;let n=e.values().next();n.done||e.delete(n.value)}function ej(e){let t=e.currentEvents,n,r,i=()=>(r??=new Set(t.map(sj)),r),a=e=>{n??=t.slice(),n.push(e),t=n};for(let o of e.streamEvents){let s=rj(o,e.piboSessionId,e.nextSequence,e.now??(()=>new Date().toISOString()));if(!s)continue;if(tj(s)){t=nj(t,s),n=t,r=void 0;continue}let c=sj(s),l=i();l.has(c)||(l.add(c),a(s))}return t}function tj(e){return e.type===`assistant_message`||e.type===`thinking_finished`||e.type===`tool_execution_finished`}function nj(e,t){return t.type===`assistant_message`?[...oj(e,t,`assistant_delta`),t]:t.type===`thinking_finished`?[...oj(e,t,`thinking_delta`),t]:t.type===`tool_execution_finished`?[...oj(e,t,`tool_execution_updated`),t]:e}function rj(e,t,n,r){if(e.type===`RAW_EVENT`&&uj(e.event)&&typeof e.event.type==`string`){let i=e.event;return ij(e,t,e.event.type,i,n,r)}if(e.type===`TEXT_MESSAGE_CONTENT`&&typeof e.delta==`string`)return ij(e,t,`assistant_delta`,{type:`assistant_delta`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,...lj(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 ij(e,t,`thinking_delta`,{type:`thinking_delta`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,...lj(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 ij(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 ij(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 ij(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 ij(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 ij(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:aj(e)??a(),payload:r}}function aj(e){if(!(typeof e.createdAt!=`string`||!Number.isFinite(Date.parse(e.createdAt))))return e.createdAt}function oj(e,t,n){let r=cj(t);return e.filter(e=>e.type!==n||cj(e)!==r)}function sj(e){return e.streamId===void 0?`${e.id}:${e.type}`:e.streamFrameIndex===void 0?`stream:${e.streamId}:${e.id}:${e.type}`:`stream:${e.streamId}:${e.streamFrameIndex}:${e.type}`}function cj(e){let t=uj(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 lj(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 uj(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function dj(e){try{let t=JSON.parse(e.data);if(typeof t.type!=`string`)return;let n=e.lastEventId?NS(e.lastEventId):void 0;return{...t,...e.lastEventId?{streamFrameId:e.lastEventId}:{},...n?{streamId:n.streamId,streamFrameIndex:n.frameIndex}:{}}}catch{return}}function fj(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:mj(n),exact:!1,...r?.liveReplayId===void 0?{}:{liveReplayId:r.liveReplayId}})}function pj(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 mj(e){return`${e}:999999`}function hj(e){if(e.type===`RUN_FINISHED`||e.type===`TEXT_MESSAGE_END`)return 300;if(e.type===`RUN_ERROR`)return 0}function gj(e){return e.type===`RUN_STARTED`||e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`||e.type===`TEXT_MESSAGE_END`}function _j(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 vj(e,t,n){if(n.type===`RUN_STARTED`||n.type===`RUN_FINISHED`||n.type===`RUN_ERROR`){e.delete(t);return}let r=xj(n);r&&e.get(t)?.delete(r)}function yj(e,t,n){let r=bj(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 bj(e){if(e.type===`TEXT_MESSAGE_CONTENT`||e.type===`REASONING_MESSAGE_CONTENT`)return`${e.type}:${e.messageId}`}function xj(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 Sj=500,Cj=1e4,wj=45e3,Tj=15e3,Ej=100,Dj=2;function Oj(e){let t=Math.max(e.eventCount??0,e.lastEventSequence??0);for(let n of e.rawEvents)t=Math.max(t,n.eventSequence??0);return t+1}function kj(e){if(e.forceReconnect)return!0;let t=e.liveStream;return!t||t.piboSessionId!==e.selectedPiboSessionId||t.readyState===Dj||(e.nowMs??Date.now())-t.lastActivityAt>wj}function Aj({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=(0,v.useRef)(!1),b=(0,v.useRef)(!1),[x,S]=(0,v.useState)(0);(0,v.useEffect)(()=>{let n=t;!n||n.piboSessionId!==e||(r.current=Math.max(r.current,Oj(n)),n.latestStreamId!==void 0&&fj(m.current,n.piboSessionId,n.latestStreamId))},[r,e,t]);let C=(0,v.useCallback)(e=>{let t=u.current.get(e);t?.length&&(o(n=>{let i=ej({currentEvents:n?.piboSessionId===e?n.events:[],streamEvents:t,piboSessionId:e,nextSequence:()=>r.current++});return hy(e,t.length,i.length),{piboSessionId:e,events:i}}),u.current.delete(e))},[]),w=(0,v.useCallback)(()=>{if(!(d.current!==void 0||f.current!==void 0||!e)){if(document.hidden){f.current=setTimeout(()=>{f.current=void 0,C(e)},Ej);return}d.current=requestAnimationFrame(()=>{d.current=void 0,C(e)})}},[C,e]),T=(0,v.useCallback)((t,n,r=!1)=>{vj(p.current,t,n);let i=r||yj(p.current,t,n),a=u.current.get(t)??[];a.push(n),u.current.set(t,a),my(t,n,a.length,i),i||t!==e?C(t):w()},[C,w,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 E=(0,v.useCallback)((e,t)=>{pj(m.current,e,t)},[]),D=(0,v.useCallback)((e=0)=>{if(g.current!==void 0){if(e>0)return;clearTimeout(g.current)}g.current=setTimeout(()=>{g.current=void 0,S(e=>e+1)},e)},[]),O=(0,v.useCallback)((t=!1)=>{if(!e)return;C(e),s().catch(e=>l(jj(e))),c().catch(e=>l(jj(e)));let n=h.current;if(kj({selectedPiboSessionId:e,liveStream:n?{piboSessionId:n.piboSessionId,lastActivityAt:n.lastActivityAt,readyState:n.events.readyState}:null,forceReconnect:t})){if(t){if(y.current)return;y.current=!0}D()}},[C,l,c,s,D,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:mj(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,b=!1,x=(t,n=!1)=>{if(f){if(!n)return;clearTimeout(f)}vy(e,t),f=setTimeout(()=>{f=void 0,s().catch(e=>l(jj(e)))},t)},S=()=>{if(v){b=!0;return}v=!0,c().catch(e=>l(jj(e))).finally(()=>{v=!1,b&&(b=!1,w(250,!0))})},w=(e,t=!1)=>{if(p){if(!t)return;clearTimeout(p)}p=setTimeout(()=>{p=void 0,S()},e)},O=()=>{w(900,!0)};return o.onopen=()=>{_.current=0,y.current=!1,g.current!==void 0&&(clearTimeout(g.current),g.current=void 0),dy(e,o.readyState);let t=h.current;t?.events===o&&(t.lastActivityAt=Date.now())},o.onerror=()=>{if(d)return;fy(e,o.readyState);let t=h.current;t?.events===o&&(t.lastErrorAt=Date.now());let n=_.current++;D(Math.min(Cj,Sj*2**n))},o.addEventListener(`pibo`,t=>{if(d)return;let n=dj(t);if(!n)return;let r=n.piboSessionId||e,i=h.current;if(i?.events===o&&(i.lastActivityAt=Date.now()),E(r,n),py(r,n,t.lastEventId,o.readyState),r===e&&n.type===`ready`&&n.liveReplay?.missed&&x(0,!0),by(n))return;let a=n.type!==`TEXT_MESSAGE_CONTENT`&&n.type!==`REASONING_MESSAGE_CONTENT`;r===e&&_j(n)&&T(r,n,a);let s=hj(n);r===e&&s!==void 0?x(s,!0):r===e&&n.type!==`ready`&&n.type!==`RAW_EVENT`&&x(1500,!0),gj(n)&&(n.type===`RUN_FINISHED`||n.type===`RUN_ERROR`||n.type===`TEXT_MESSAGE_END`?O():w(r===e?0:150))}),()=>{d=!0,f&&clearTimeout(f),p&&clearTimeout(p),C(e),h.current?.events===o&&(h.current=null),o.close()}},[n?.piboSessionId,T,C,l,c,s,E,D,x,e,a]),(0,v.useEffect)(()=>{n?.piboSessionId&&C(n.piboSessionId)},[n?.piboSessionId,C]),(0,v.useEffect)(()=>{let e=()=>O(),t=()=>O(!0),n=()=>{b.current=!0},r=()=>{if(document.hidden){n();return}b.current=!1,O(!0)},i=e=>{let t=b.current||e.persisted;b.current=!1,O(t)};return window.addEventListener(`focus`,e),window.addEventListener(`online`,t),window.addEventListener(`pagehide`,n),window.addEventListener(`pageshow`,i),document.addEventListener(`visibilitychange`,r),()=>{window.removeEventListener(`focus`,e),window.removeEventListener(`online`,t),window.removeEventListener(`pagehide`,n),window.removeEventListener(`pageshow`,i),document.removeEventListener(`visibilitychange`,r)}},[O]),(0,v.useEffect)(()=>{if(!e||i!==`running`)return;let t=window.setInterval(()=>{C(e);let t=h.current;kj({selectedPiboSessionId:e,liveStream:t?{piboSessionId:t.piboSessionId,lastActivityAt:t.lastActivityAt,readyState:t.events.readyState}:null})&&(s().catch(e=>l(jj(e))),D())},Tj);return()=>window.clearInterval(t)},[C,l,s,D,e,i])}function jj(e){return e instanceof Error?e.message:String(e)}var Mj=10;function Nj(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,Mj)}:e}function Pj(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 Fj(e,t){return!t||!e[t]?.length?e:{...e,[t]:[]}}function Ij(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=>Nj(r,e,n,t))},[t,e]),detachUploadAttachment:(0,v.useCallback)(t=>{r(n=>Pj(n,e,t))},[e]),clearSelectedUploadAttachments:(0,v.useCallback)(()=>{r(t=>Fj(t,e))},[e])}}function Lj({selectedPiboSessionId:e,onError:t,formatError:n}){let[r,i]=(0,v.useState)([]),[a,o]=(0,v.useState)(!1),[s,c]=(0,v.useState)(()=>e?ck(e):null),[l,u]=(0,v.useState)(()=>hk()),[d,f]=(0,v.useState)(!1),p=!!(e&&s?.piboSessionId===e&&s.installed),m=!!e&&(a||p),h=PO({queryKey:[`web-annotations`,`app`,e],queryFn:async()=>{if(!e)throw Error(`Session is required`);return Vx(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?fk(e):[]),c(e?ck(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(dk(e.detail)),r=n=>{n.key===lk(e)&&t(uk(n.newValue))},i=()=>t(ck(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&&pk(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&&pk(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&&pk(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 gk(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=>Hx(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 Rj=new WeakMap;function zj(e,t,n){let r=n.map(e=>Bj(e)),i=qj(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 Bj(e){let t=Rj.get(e);if(t)return t;let n=Kj(e.startedAt)??Date.now()*1e3,r=Kj(e.completedAt),i=Gj(e.status),a=Vj(e.type),o={id:e.id,parentId:e.parentId,name:Hj(e),spanType:a,startTime:n,endTime:r,durationUs:e.durationMs===void 0?void 0:e.durationMs*1e3,attributes:Uj(e),status:i,statusMessage:e.error,events:e.error?[{name:`exception`,timestamp:r??n,attributes:{message:e.error}}]:[],children:e.children?.map(Bj),pibo:{entryId:e.entryId,linkedPiboSessionId:e.linkedPiboSessionId,traceNodeType:e.type,traceOrder:e.orderKey,stableKey:e.stableKey,source:e.source}};return Rj.set(e,o),o}function Vj(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 Hj(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 Uj(e){let t={};if(e.summary&&(t.content=e.summary),e.input!==void 0&&(t.input=e.input,t.args=e.input,t.arguments=e.input),e.output!==void 0&&(t.output=e.output,t.result=e.output),e.error&&(t.error=e.error),e.toolCallId&&(t.tool_call_id=e.toolCallId),e.runId&&(t.run_id=e.runId),(e.type===`tool.call`||e.type===`agent.delegation`)&&(t.tool_name=e.title),e.type===`assistant.message`&&(t.content=e.output??e.summary??``),e.type===`user.message`){t.content=e.output??e.summary??``;let n=Wj(e);n&&(t[`message.pending_delivery`]=n)}return e.type===`model.reasoning`&&(t.reasoning=e.output??e.summary??``),e.type===`agent.delegation`&&(t[`delegation.target_agent`]=e.title.replace(/^pibo_subagent_/,``),t[`delegation.query`]=e.summary??e.input,t[`result.status`]=e.status===`done`?`completed`:e.status,t.linked_pibo_session_id=e.linkedPiboSessionId),e.type===`agent.async`&&(t[`async_agent.target_agent`]=e.title,t[`async_agent.started_by`]=Jj(e.input)?e.input.startedBy:`pibo_run_start`,t[`async_agent.query`]=Jj(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 Wj(e){if(!(e.type!==`user.message`||e.status!==`running`)){if(e.id.startsWith(`event:message_steered:`))return`steer`;if(e.id.startsWith(`event:message_queued:`))return`queue`}}function Gj(e){return e===`running`?`UNSET`:e===`error`?`ERROR`:`OK`}function Kj(e){if(!e)return;let t=new Date(e).getTime();return Number.isFinite(t)?t*1e3:void 0}function qj(e){return e.flatMap(e=>[e,...e.children?qj(e.children):[]])}function Jj(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Yj(e){return(e.selectedPiboSessionId?S(e.sessionNodes,e.selectedPiboSessionId):void 0)?.title||e.traceTitle||e.selectedPiboSessionId||e.fallback}function Xj(e,t){return t?{sessionBreadcrumbs:tM(e,t),originSession:$j(e,t),derivedSessions:eM(e,t)}:{sessionBreadcrumbs:[],originSession:void 0,derivedSessions:[]}}function Zj(e){let t=e.selectedPiboSessionId?S(e.bootstrap.sessions,e.selectedPiboSessionId):void 0,n=aM(e.currentTraceView);return iM(e.selectedSessionActiveModel,e.bootstrap.runtimeStatus?.thinkingLevel??n.level??nM(e.bootstrap,e.selectedSessionProfile,!!t?.parentId),e.bootstrap.runtimeStatus?.fastMode??n.fast??rM(e.bootstrap,e.selectedSessionProfile,!!t?.parentId)??!1)}function Qj(e){return{traceView:e.currentTraceView,selectedTrace:e.currentTraceView?zj(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,sessionGoal:e.sessionGoal,workflowProjectSession:e.workflowProjectSession,workflowLifecycleEvents:e.workflowLifecycleEvents,sessionNodes:e.sessionNodes,sessionBreadcrumbs:e.sessionLinks.sessionBreadcrumbs,originSession:e.sessionLinks.originSession,derivedSessions:e.sessionLinks.derivedSessions,agentProfiles:e.agentProfiles,sessionProfileChangeDisabled:e.sessionProfileChangeDisabled,onSessionAgentProfileChange:e.onSessionAgentProfileChange,onFork:e.onFork,onOpenSession:e.onOpenSession,onLoadOlderTracePage:e.onLoadOlderTracePage,hasOlderTraceEvents:e.hasOlderTraceEvents,isFetchingOlderTracePage:e.isFetchingOlderTracePage,onThinkingLevelChange:e.onThinkingLevelChange,onModelChanged:async()=>{await e.onRefreshBootstrap(),await e.onRefreshTrace()},onRefreshBootstrap:e.onRefreshBootstrap,onError:e.onError}}function $j(e,t){let n=S(e,t);if(!n?.originId)return;let r=S(e,n.originId);return{piboSessionId:n.originId,label:r?cM(r,0):n.originId}}function eM(e,t){return S(e,t)?.derivedSessions.map(e=>({piboSessionId:e.piboSessionId,label:lM(e),profile:e.profile,status:e.status}))??[]}function tM(e,t){return C(e,t).map((e,t)=>({piboSessionId:e.piboSessionId,label:cM(e,t)}))}function nM(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 rM(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 iM(e,t,n){if(e)return[e,t,n?`fast`:void 0].filter(Boolean).join(` `)}function aM(e){let t={};if(!e)return t;for(let n of oM(e.nodes)){if(n.type!==`execution.command`||n.title!==`thinking`&&n.title!==`fast_mode`)continue;let e=n.output&&typeof n.output==`object`?n.output:void 0;t={level:(typeof e?.level==`string`&&sM(e.level)?e.level:void 0)??t.level,fast:n.title===`fast_mode`?e?.mode===`fast`:t.fast}}return t}function oM(e){return e.flatMap(e=>[e,...oM(e.children)])}function sM(e){return RT.includes(e)}function cM(e,t){return t?e.subagentName&&e.subagentName!==e.profile?`${e.subagentName} (${e.profile})`:e.profile||e.subagentName||e.title:e.profile||e.title}function lM(e){return e.subagentName&&e.subagentName!==e.profile?`${e.subagentName} (${e.profile})`:e.title||e.profile||e.subagentName||`Untitled Session`}function uM({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 dM(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 fM(e,t,n){return{piboSessionId:t,events:[...e?.piboSessionId===t?e.events:[],n]}}var pM=`optimistic-session-`;function mM(e){return e?.startsWith(pM)===!0}function hM(e){return e&&!mM(e)?e:null}function gM(e){return e instanceof Error?e.message:String(e)}var _M=[`(display-mode: standalone)`,`(display-mode: window-controls-overlay)`];function vM(e,t){return _M.some(t=>e(t).matches)?typeof t.userAgentData?.mobile==`boolean`?!t.userAgentData.mobile:!(/Android|iPhone|iPad|iPod|Mobile/i.test(t.userAgent)||/Macintosh/i.test(t.userAgent)&&t.maxTouchPoints>1):!1}function yM(){return typeof window<`u`&&typeof navigator<`u`&&vM(window.matchMedia.bind(window),navigator)}function bM(e,t){return{url:e,name:`pibo-session-${t}`,features:`width=1280,height=900`}}function xM(){let e=bM(window.location.href,crypto.randomUUID());return window.open(e.url,e.name,e.features)}function SM({bootstrap:e,selectedPiboSessionId:t,selectedRoomId:n,selectedRoomArchived:r,roomNavigationPending:i,sessionNavigationPending:a,selectedSessionProfile:o,selectedSessionActiveModel:s,selectedSessionStatus:c,selectedSessionSignal:l,signals:u,workflowProjectSession:d,workflowLifecycleEvents:f,projectSessionCreatePanel:p,workflowStartPanel:m,projectModulePanel:h,extraViewTabs:g,activeViewId:_,sessionViewId:y,sessionViews:b,currentSessionView:x,allowedSessionViewIds:S,creatingSession:C,terminalFullscreen:E=!1,onEnterTerminalFullscreen:D,onExitTerminalFullscreen:O,showRawEvents:k,showThinking:A,expandThinking:ee,commands:te,skills:j,composerText:M,composerFocusSignal:ne,onComposerTextChange:N,onToggleRawEvents:P,onToggleThinking:re,onToggleExpandThinking:ie,onSessionAgentProfileChange:ae,onFork:oe,onOpenSession:se,onSelectSessionView:le,onCommand:F,onThinkingLevelChange:ue,onRefreshTrace:de,onRefreshBootstrap:fe,onSend:pe,onError:me}){let he=(0,v.useRef)(0),ge=(0,v.useRef)(new Map),[_e,ve]=(0,v.useState)(null),ye=(0,v.useCallback)(e=>{ve(t=>{let n=typeof e==`function`?e(t):e;return n&&ge.current.set(n.piboSessionId,n),n})},[]),[be,I]=(0,v.useState)(null),xe=(0,v.useRef)(new Set),Se=(0,v.useRef)(null),Ce=hM(t),we=PO({queryKey:Ce?[`chat`,`session-goal`,Ce]:[`chat`,`session-goal`,`idle`],queryFn:({signal:e})=>Bx(Ce,{signal:e}),enabled:!!Ce,refetchInterval:Ce?5e3:!1}),Te=!!Ce&&yM(),Ee=(0,v.useCallback)(()=>{xM()||me(`The browser blocked the new Pibo window.`)},[me]),De=Te?Ee:void 0,{baseTraceView:Oe,liveTraceOverlay:ke,rawEventLimit:Ae,traceSummaryQuery:je,tracePageQuery:Me,rawEventsQuery:Ne,loadingOlderTracePage:Pe,tracePageReady:Fe,loadOlderTracePage:Ie,loadMoreRawEvents:Le}=QA({selectedPiboSessionId:Ce,showRawEvents:k,liveTraceOverlay:_e,liveTraceOverlayCacheRef:ge,setLiveTraceOverlay:ye}),{selectedWebAnnotationIds:Re,selectedWebAnnotations:ze,visibleWebAnnotations:Be,webAnnotationsPanelCollapsed:Ve,webAnnotationsPanelRendered:He,webAnnotationsPanelVisible:Ue,webAnnotationsQuery:We,clearingWebAnnotations:Ge,setWebAnnotationsPanelVisible:Ke,toggleWebAnnotationAttachment:qe,detachWebAnnotationAttachment:Je,clearSelectedWebAnnotationAttachments:Ye,toggleWebAnnotationsPanelCollapsed:Xe,clearVisibleWebAnnotations:Ze}=Lj({selectedPiboSessionId:Ce,onError:me,formatError:Tk}),{selectedUploadAttachments:Qe,attachUploadedFiles:$e,detachUploadAttachment:et,clearSelectedUploadAttachments:tt}=Ij(t,(0,v.useCallback)(()=>`upload-${w()}`,[])),nt=jA({selectedPiboSessionId:Ce,baseTraceView:Oe,liveTraceOverlay:ke,selectedSessionStatus:c});Aj({selectedPiboSessionId:Ce,tracePageData:Me.data,currentTraceView:nt,liveEventSeqRef:he,selectedSessionStatus:c,tracePageReady:Fe,setLiveTraceOverlay:ye,onRefreshTrace:de,onRefreshBootstrap:fe,onError:me});let rt=Zj({bootstrap:e,selectedPiboSessionId:t,selectedSessionProfile:o,selectedSessionActiveModel:s,currentTraceView:nt}),it=(0,v.useMemo)(()=>Xj(e.sessions,t),[e.sessions,t]),at=!!t&&Me.isFetching&&!nt,ot=Me.error?gM(Me.error):je.error?gM(je.error):null,st=T(t,r),ct=!st&&x.id===`terminal`&&(_??y)===`terminal`,lt=(0,v.useCallback)(async e=>{try{$e((await ce(e)).files)}catch(e){me(gM(e))}},[$e,me]),ut=nt?.piboSessionId??t??``,dt=d&&Nk(d)?Pk(d,c):null,ft=e=>{for(let n of[750,2e3,5e3,1e4])window.setTimeout(()=>{t===e&&Me.refetch().catch(e=>me(gM(e)))},n)},pt=async(e,t)=>{let n=dM(e,t);ye(e=>fM(e,n.piboSessionId,n.optimisticEvent)),await pe(n.text,n.webAnnotationIds,n.fileAttachmentPaths,n.clientTxnId,t),Ye(),tt(),await Promise.all([Me.refetch(),We.refetch()]),ft(n.piboSessionId)},mt=(e,t)=>{ye(t=>{let n=t?.piboSessionId===e.piboSessionId?t:ge.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?ge.current.set(e.piboSessionId,i):ge.current.delete(e.piboSessionId),t?.piboSessionId===e.piboSessionId?i:t}),N(t=>t||e.text),me(gM(t))},ht=async e=>{if(st||!t)return;let n=uM({piboSessionId:t,text:e,selectedWebAnnotations:ze,selectedUploadAttachments:Qe,eventSequence:he.current++,now:new Date().toISOString(),clientTxnId:w()});if(c===`running`){I(n);return}try{await pt(n,`queue`)}catch(e){mt(n,e)}},gt=()=>{be&&(N(e=>e||be.text),I(null))},_t=async e=>{let t=be;if(!(!t||xe.current.has(t.clientTxnId))){xe.current.add(t.clientTxnId),I(e=>e?.clientTxnId===t.clientTxnId?null:e),me(null);try{await pt(t,e)}catch(e){mt(t,e)}finally{xe.current.delete(t.clientTxnId)}}},vt=Qj({currentTraceView:nt,isLoading:at,showThinking:A,expandThinking:ee,selectedSessionProfile:o,sessionActiveModelBadge:rt,selectedSessionStatus:c,selectedSessionSignal:l,signals:u,sessionGoal:we.data?.goal,workflowProjectSession:d,workflowLifecycleEvents:f,sessionNodes:e.sessions,sessionLinks:it,agentProfiles:e.agents,sessionProfileChangeDisabled:C||r,onSessionAgentProfileChange:ae,onFork:oe,onOpenSession:se,onLoadOlderTracePage:()=>void Ie(nt?.nextBeforeCursor??nt?.nextBeforeSequence),hasOlderTraceEvents:nt?.hasOlderEvents===!0||nt?.nextBeforeCursor!==void 0||typeof nt?.nextBeforeSequence==`number`,isFetchingOlderTracePage:Pe,onThinkingLevelChange:ue,onRefreshTrace:de,onRefreshBootstrap:fe,onError:me});return(0,L.jsxs)(L.Fragment,{children:[be?(0,L.jsx)(nA,{title:`Session is running`,description:`Choose how this message should be delivered.`,onClose:gt,initialFocusRef:Se,children:(0,L.jsxs)(`div`,{className:`grid gap-2 p-4 sm:grid-cols-2`,"data-pibo-debug":`message-delivery-dialog`,children:[(0,L.jsxs)(`button`,{ref:Se,type:`button`,onClick:()=>void _t(`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,L.jsx)(`span`,{className:`block text-xs font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Queue`}),(0,L.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,L.jsxs)(`button`,{type:`button`,onClick:()=>void _t(`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,L.jsx)(`span`,{className:`block text-xs font-bold uppercase tracking-wider text-amber-400`,children:`Steer`}),(0,L.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,L.jsx)(Qk,{selectedPiboSessionId:t,selectedRoomId:n,fallbackRoomId:e.selectedRoomId??void 0,sessionViewId:y,loadingTrace:at,roomNavigationPending:i,sessionNavigationPending:a,traceError:ot,showRawEvents:k,currentTraceView:nt,rawEventLimit:Ae,tracePageFetching:k?Ne.isFetching:Me.isFetching,onLoadMoreRawEvents:Le,terminalFullscreen:E,terminalFileDropEnabled:ct,onTerminalFilesDropped:lt,onOpenSessionWindow:De,onExitTerminalFullscreen:O??(()=>void 0),headerProps:{title:Yj({sessionNodes:e.sessions,selectedPiboSessionId:t,traceTitle:nt?.title,fallback:e.room?.name??n??void 0}),roomLabel:e.room?.name??n??`Room`,headerPiboSessionId:ut,piboSessionId:t,piboRoomId:n??e.selectedRoomId??void 0,webAnnotationsDisabled:!t||r,webAnnotationsPanelRendered:He,workflowHeader:dt,sessionViewId:y,sessionViews:b,currentSessionView:x,allowedSessionViewIds:S,extraViewTabs:g,activeViewId:_,terminalFullscreenAvailable:x.id===`terminal`&&(_??y)===`terminal`,onEnterTerminalFullscreen:D,onOpenSessionWindow:De,showRawEvents:k,showThinking:A,expandThinking:ee,onShowWebAnnotationsPanel:()=>Ke(!0),onHideWebAnnotationsPanel:()=>Ke(!1),onSelectSessionView:le,onToggleRawEvents:P,onToggleThinking:re,onToggleExpandThinking:ie,onError:me},projectSessionCreatePanel:p,workflowStartPanel:m,projectModulePanel:h,currentSessionView:x,sessionViewProps:vt,webAnnotationsPanelRendered:He,webAnnotationsPanelProps:{piboSessionId:t,annotations:Be,selectedIds:Re,loading:We.isLoading||We.isFetching||Ge,error:We.error?gM(We.error):null,collapsed:Ve,onRefresh:()=>void We.refetch(),onToggle:qe,onClear:()=>void Ze(),onCollapse:Xe,onClose:()=>Ke(!1)},composerProps:{sessionId:t,disabled:st,commands:te,skills:j,value:M,focusSignal:ne,selectedWebAnnotations:ze,selectedUploadAttachments:Qe,onValueChange:N,onCommand:F,onDetachWebAnnotation:Je,onClearWebAnnotations:Ye,onAttachUploadedFiles:$e,onDetachUploadAttachment:et,onClearUploadAttachments:tt,onSend:ht}})]})}function CM({mode:e,onSelectSession:t,onNewSession:n,onDeleteSession:r,onRenameSession:i,onSelectRoom:a}){return e.kind===`rooms`?(0,L.jsx)(AM,{candidates:e.candidates,workspace:e.workspace,onSelectRoom:a}):(0,L.jsx)(OM,{sessions:e.sessions,selectedPiboSessionId:e.selectedPiboSessionId,onSelectSession:t,onNewSession:n,onDeleteSession:r,onRenameSession:i})}function wM(e){return e===`running`?`running`:e===`error`?`error`:e===`completed`?`completed`:`idle`}var TM={running:`bg-cyan-400`,idle:`bg-slate-500`,error:`bg-rose-500`,completed:`bg-emerald-500`},EM={running:`running`,idle:`idle`,error:`error`,completed:`completed`};function DM({status:e}){let t=wM(e);return(0,L.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-[10px] uppercase tracking-wider text-slate-400`,children:[(0,L.jsx)(`span`,{className:`inline-block w-1.5 h-1.5 rounded-full ${TM[t]}`,"aria-hidden":`true`}),EM[t]]})}function OM({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,L.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,L.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,L.jsxs)(`ul`,{className:`flex gap-1 overflow-x-auto min-w-0`,children:[o.map(e=>(0,L.jsx)(`li`,{className:`shrink-0`,children:(0,L.jsx)(kM,{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,L.jsx)(`li`,{className:`text-xs text-slate-500 px-2 py-1`,children:`No sessions yet — click + to start one.`})]})]})}function kM({session:e,isActive:t,onSelect:n,onDelete:r,onRename:i}){let[a,o]=(0,v.useState)(!1);return(0,L.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,L.jsxs)(`button`,{type:`button`,onClick:n,className:`inline-flex items-center gap-2 text-left`,children:[(0,L.jsx)(DM,{status:e.status}),(0,L.jsx)(`span`,{className:`text-xs text-slate-200 max-w-[180px] truncate`,children:e.title||`Untitled`})]}),(0,L.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,L.jsxs)(`div`,{className:`absolute z-10 mt-12 -ml-20 bg-[#0a1418] border border-slate-700 rounded shadow-lg text-xs`,children:[(0,L.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,L.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 AM({candidates:e,workspace:t,onSelectRoom:n}){return(0,L.jsxs)(`div`,{className:`border-b border-slate-800 px-3 py-3 bg-[#0c1820]`,"data-testid":`room-picker`,children:[(0,L.jsxs)(`div`,{className:`text-[10px] uppercase tracking-wider text-slate-400 mb-2`,children:[`Multiple rooms found for `,(0,L.jsx)(`span`,{className:`font-mono text-slate-300`,children:t})]}),(0,L.jsx)(`ul`,{className:`flex flex-col gap-1`,children:e.map(e=>(0,L.jsx)(`li`,{children:(0,L.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,L.jsx)(`div`,{className:`font-semibold text-slate-200 text-sm`,children:e.name}),e.topic&&(0,L.jsx)(`div`,{className:`text-xs text-slate-400 mt-0.5`,children:e.topic}),(0,L.jsxs)(`div`,{className:`text-[10px] text-slate-500 mt-1`,children:[`Created `,jM(e.createdAt),` · Updated `,jM(e.updatedAt)]})]})},e.id))})]})}function jM(e){try{return new Date(e).toLocaleString()}catch{return e}}function MM(){return new URLSearchParams(window.location.search).get(`workspace`)}function NM(){return new URLSearchParams(window.location.search).get(`roomId`)}function PM(){let e=(0,v.useMemo)(()=>MM(),[]),[t,n]=(0,v.useState)(()=>NM()),[r,i]=(0,v.useState)(()=>NM()?{kind:`sessions`,roomId:NM(),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(gM(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(gM(e))}},[t,s]),b=(0,v.useCallback)(async()=>{await y()},[y]);(0,v.useEffect)(()=>{if(!t)return;let e=`/api/chat/events?${new URLSearchParams({roomId:t,mode:`summary`,since:`0:999999`}).toString()}`,n=new EventSource(e),r,i=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=void 0,y()},200)};return n.addEventListener(`change`,i),n.addEventListener(`trace`,i),n.addEventListener(`message`,i),n.onerror=()=>{},()=>{r&&clearTimeout(r),n.close()}},[t,y]),(0,v.useEffect)(()=>{let e=e=>{let t=e.data;!t||typeof t!=`object`||(t.type===`pibo/set-selector-mode`?(i(t.mode),t.mode.kind===`sessions`&&n(t.mode.roomId)):t.type===`pibo/refresh-bootstrap`&&y())};return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[y]);let S=(0,v.useMemo)(()=>a?O(a.capabilities.actions):[],[a]),C=(0,v.useMemo)(()=>k(a,s),[a,s]),T=(0,v.useMemo)(()=>r.kind===`sessions`?r.sessions:_,[r,_]),E=(0,v.useCallback)(e=>{c(e),f(e=>e+1)},[]),D=(0,v.useCallback)(async e=>{if(t)try{let n=await te(e,t);await y(),n.session?.id&&c(n.session.id)}catch(e){m(gM(e))}},[t,y]),A=(0,v.useCallback)(async e=>{try{await M(e,`delete`),await y(),s===e&&c(null)}catch(e){m(gM(e))}},[y,s]),P=(0,v.useCallback)(async(e,t)=>{try{await j(e,{title:t}),await y()}catch(e){m(gM(e))}},[y]),re=(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()}`)},[]),ie=(0,v.useCallback)(async e=>{if(!(!s||!t))try{await ne(s,e,w(),t),u(``),f(e=>e+1),await y()}catch(e){m(gM(e))}},[s,t,y]),se=(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=ae(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(gM(e))}return!0}try{let e=oe(i.action,n.slice(r.length).trim());await N(s,i.action,e),await y()}catch(e){m(gM(e))}return!0},[S,s,t,y]),ce=(0,v.useMemo)(()=>LD(),[]),F=(0,v.useMemo)(()=>RD(pe),[]);if(!a)return(0,L.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,L.jsx)(CM,{mode:r,onSelectSession:E,onNewSession:D,onDeleteSession:A,onRenameSession:P,onSelectRoom:re}),(0,L.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,L.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,L.jsx)(CM,{mode:{kind:`rooms`,candidates:a.rooms??r.candidates,workspace:r.workspace},onSelectSession:E,onNewSession:D,onDeleteSession:A,onRenameSession:P,onSelectRoom:re}),(0,L.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 ue=a.sessions.find(e=>e.piboSessionId===s);return(0,L.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,L.jsx)(CM,{mode:{kind:`sessions`,roomId:t??``,sessions:T,selectedPiboSessionId:s},onSelectSession:E,onNewSession:D,onDeleteSession:A,onRenameSession:P,onSelectRoom:re}),p&&(0,L.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,L.jsx)(`button`,{type:`button`,className:`ml-3 underline`,onClick:()=>m(null),children:`dismiss`})]}),(0,L.jsx)(`div`,{className:`flex-1 min-h-0`,children:(0,L.jsx)(SM,{bootstrap:a,selectedPiboSessionId:s,selectedRoomId:t,selectedRoomArchived:!1,selectedSessionProfile:ue?.profile??`default`,selectedSessionActiveModel:ue?x(a,ue)??void 0:void 0,selectedSessionStatus:ue?.status,sessionViewId:pe,sessionViews:ce,currentSessionView:F,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:se,onThinkingLevelChange:e=>void se(`/thinking ${e}`),onRefreshTrace:b,onRefreshBootstrap:y,onSend:ie,onError:m})})]})}var FM=document.getElementById(`root`);FM&&(0,y.createRoot)(FM).render((0,L.jsx)(v.StrictMode,{children:(0,L.jsx)(PM,{})}));
|
|
39
|
+
`).trim();if(!t.startsWith(`{`)&&!t.startsWith(`[`))continue;let n=Tx(t);if(n!==void 0)return wx(n,r.slice(0,e).join(` `).trim()||void 0)}}function wx(e,t){let n=ax(e);if(n.kind===`text`){let e=Cx(n.text);return e?.kind===`json`?{...e,meta:e.meta??t}:{kind:`text`,text:n.text}}return{kind:`json`,value:e,meta:t}}function Tx(e){if(!(!e.startsWith(`{`)&&!e.startsWith(`[`)))try{let t=JSON.parse(e);return typeof t==`object`&&t?t:void 0}catch{return}}function Ex(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Dx({name:e,input:t}){return(0,L.jsxs)(`span`,{className:`compact-terminal-function-call`,children:[(0,L.jsx)(`span`,{className:`text-[#facc15] font-semibold`,children:e}),(0,L.jsx)(`span`,{className:`text-[#d4d4d4]`,children:`(`}),t===void 0?null:(0,L.jsx)(Ox,{value:t}),(0,L.jsx)(`span`,{className:`text-[#d4d4d4]`,children:`)`})]})}function Ox({value:e}){let[t,n]=(0,v.useState)(()=>new Set([`$`])),[r,i]=(0,v.useState)(()=>new Set);return(0,L.jsx)(kx,{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 kx({value:e,path:t,expandedPaths:n,expandedStrings:r,onTogglePath:i,onToggleString:a}){if(Array.isArray(e))return(0,L.jsx)(Ax,{value:e,path:t,open:`[`,close:`]`,expandedPaths:n,expandedStrings:r,onTogglePath:i,onToggleString:a});if(Nx(e))return(0,L.jsx)(Ax,{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,L.jsx)(`span`,{className:`text-[#fb923c]`,children:JSON.stringify(o)});return!i&&e.length<=140?s:(0,L.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),a(t)},className:`compact-terminal-json-toggle text-left align-baseline`,title:n?`Collapse string`:`Expand string`,"aria-label":`String at ${jx(t)}`,"aria-expanded":n,children:s})}return typeof e==`number`||typeof e==`boolean`||e===null?(0,L.jsx)(`span`,{className:`text-[#60a5fa]`,children:String(e)}):(0,L.jsx)(`span`,{className:`text-[#737373]`,children:JSON.stringify(String(e))})}function Ax({value:e,path:t,open:n,close:r,expandedPaths:i,expandedStrings:a,onTogglePath:o,onToggleString:s}){let c=i.has(t),l=`inline-json-${(0,v.useId)()}`,u=c?Array.isArray(e)?e.map((e,t)=>[String(t),e]):Object.entries(e):[];return(0,L.jsxs)(`span`,{children:[(0,L.jsxs)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),o(t)},className:`compact-terminal-json-toggle align-baseline text-[#737373]`,title:c?`Collapse JSON`:`Expand JSON`,"aria-label":`JSON at ${t}`,"aria-expanded":c,"aria-controls":l,"data-inline-json-path":t,children:[(0,L.jsx)(`span`,{className:`compact-terminal-json-caret`,children:c?`▾`:`▸`}),n,c?null:`...${r}`]}),(0,L.jsxs)(`span`,{id:l,children:[u.map(([n,r],c)=>{let l=`${t}.${Mx(n)}`;return(0,L.jsxs)(`span`,{children:[c>0?(0,L.jsx)(`span`,{className:`text-[#737373]`,children:`, `}):null,Array.isArray(e)?null:(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(`span`,{className:`text-[#d4d4d4]`,children:JSON.stringify(n)}),(0,L.jsx)(`span`,{className:`text-[#737373]`,children:`:`})]}),(0,L.jsx)(kx,{value:r,path:l,expandedPaths:i,expandedStrings:a,onTogglePath:o,onToggleString:s})]},l)}),c?(0,L.jsx)(`span`,{className:`text-[#737373]`,children:r}):null]})]})}function jx(e){let t=e.replace(/[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}/gi,`[id]`);return t.length<=80?t:`${t.slice(0,39)}…${t.slice(-39)}`}function Mx(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`.`,`\\.`)}function Nx(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}var Px=120;function Fx({line:e,status:t,clampLines:n}){let r=`min-w-0 whitespace-pre-wrap break-words ${n?`block overflow-hidden`:``}`,i=zx(e.tokens),a=i.length>Px;return(0,L.jsxs)(`div`,{className:`grid grid-cols-[1.9rem_minmax(0,1fr)] gap-2 leading-[1.45]`,children:[(0,L.jsx)(`span`,{className:`whitespace-pre ${Lx(e.prefix,t)}`,children:Ix(e.prefix)}),(0,L.jsxs)(`span`,{className:r,style:n?{maxHeight:`${n*1.45}em`}:void 0,children:[a?(0,L.jsx)(`span`,{className:`text-[#d4d4d4]`,children:i.map(e=>e.text).join(``)}):i.map((e,t)=>(0,L.jsx)(`span`,{className:Rx(e),children:e.text},`${t}:${e.text}`)),e.functionCall?(0,L.jsx)(Dx,{name:e.functionCall.name,input:e.functionCall.input}):null]})]})}function Ix(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 Rx(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 zx(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 Bx(e,t){return A(`/api/chat/loops/session-goal?${new URLSearchParams({piboSessionId:e}).toString()}`,t)}async function Vx(e,t={}){let n=new URLSearchParams({piboSessionId:e});return t.status&&n.set(`status`,t.status),t.limit&&n.set(`limit`,String(t.limit)),t.scope&&n.set(`scope`,t.scope),A(`/api/web-annotations?${n.toString()}`)}async function Hx(e,t){return A(`/api/web-annotations/${encodeURIComponent(e)}`,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify(Kx(t))})}async function Ux(e){let t=new URLSearchParams;return e?.trim()&&t.set(`cdpUrl`,e.trim()),A(`/api/web-annotations/targets${t.size?`?${t.toString()}`:``}`)}async function Wx(e){return A(`/api/web-annotations/bindings`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(Kx(e))})}async function Gx(e,t){return A(`/api/web-annotations/bindings/${encodeURIComponent(e)}/inject`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(Kx(t))})}function Kx(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0&&e!==``))}async function qx(e,t,n){return A(`/api/chat/projects/${encodeURIComponent(e)}/workflow-sessions/${encodeURIComponent(t)}/human-actions`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n)})}function Jx(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 Yx(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 Zx(e)?e.result:e}function Zx(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.type===`execution_result`}var Qx={device_code:`Device code`,api_key:`API key`,oauth:`Browser OAuth`};function $x({row:e,piboSessionId:t}){let n=Jx(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 N(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 N(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 N(t,`login.apikey`,{provider:e.id,apiKey:n}),l(``),a({type:`success`,provider:e,message:`${e.name} API key saved.`})}catch(t){a({type:`error`,provider:e,message:t instanceof Error?t.message:String(t)})}finally{s(!1)}}},[c,t]);return n?(0,L.jsx)(eS,{title:i.type===`select_provider`?`Login`:rS(i),tone:i.type===`error`?`red`:i.type===`success`?`green`:`cyan`,action:i.type===`select_provider`?void 0:(0,L.jsx)(tS,{onClick:m,disabled:o}),children:i.type===`select_provider`?(0,L.jsxs)(`div`,{className:`grid gap-2`,children:[(0,L.jsxs)(`div`,{className:`text-[11px] text-[#737373]`,children:[`Choose a provider. Use `,(0,L.jsx)(`span`,{className:`text-[#38bdf8]`,children:`/login`}),` anytime.`]}),(0,L.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:r.map(e=>(0,L.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,L.jsx)(`span`,{children:e.name}),e.configured?(0,L.jsx)(`span`,{className:`text-[#22c55e]`,children:`●`}):null]},e.id))})]}):i.type===`select_method`?(0,L.jsxs)(`div`,{className:`grid gap-2`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px]`,children:[(0,L.jsx)(`span`,{className:`text-[#737373]`,children:`Provider:`}),(0,L.jsx)(`span`,{className:`text-[#d4d4d4]`,children:i.provider.name}),i.provider.configured?(0,L.jsx)(nS,{tone:`green`,children:`Configured`}):(0,L.jsx)(nS,{tone:`neutral`,children:`Not configured`})]}),(0,L.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:i.provider.authMethods.map(e=>(0,L.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,L.jsx)(tt,{size:11}):(0,L.jsx)(ot,{size:11}),Qx[e]]},e))})]}):i.type===`device_starting`?(0,L.jsxs)(`div`,{className:`inline-flex items-center gap-2 text-[11px] text-[#38bdf8]`,children:[(0,L.jsx)(at,{size:13,className:`animate-spin`}),` Starting device login...`]}):i.type===`device_flow`?(0,L.jsxs)(`div`,{className:`grid gap-2 text-[11px]`,children:[(0,L.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,L.jsx)(`span`,{className:`text-[#737373]`,children:`Open:`}),(0,L.jsxs)(`a`,{href:i.url,target:`_blank`,rel:`noreferrer`,className:`inline-flex items-center gap-1 text-[#38bdf8] hover:underline`,children:[iS(i.url),` `,(0,L.jsx)(Ke,{size:11})]}),(0,L.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,L.jsx)(ze,{size:10}):(0,L.jsx)(Ue,{size:10}),` `,f===i.url?`Copied`:`Copy`]})]}),i.userCode?(0,L.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,L.jsx)(`span`,{className:`text-[#737373]`,children:`Code:`}),(0,L.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,L.jsx)(`span`,{className:`text-[#737373]`,children:`then`}),(0,L.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,L.jsx)(at,{size:11,className:`animate-spin`}):(0,L.jsx)(ze,{size:11}),` Complete`]})]}):(0,L.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,L.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,L.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,L.jsx)(at,{size:11,className:`animate-spin`}):(0,L.jsx)(ze,{size:11}),` Complete`]})]}),i.instructions?(0,L.jsx)(`div`,{className:`text-[#737373]`,children:i.instructions}):null]}):i.type===`api_key`?(0,L.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 text-[11px]`,children:[(0,L.jsx)(`span`,{className:`text-[#737373]`,children:`API key:`}),(0,L.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,L.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,L.jsx)(at,{size:11,className:`animate-spin`}):(0,L.jsx)(ze,{size:11}),` Save`]})]}):i.type===`success`?(0,L.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px] text-[#22c55e]`,children:[(0,L.jsx)(ze,{size:13}),` `,i.message]}):(0,L.jsxs)(`div`,{className:`flex items-start gap-2 text-[11px] text-[#ef4444]`,children:[(0,L.jsx)(Le,{size:13,className:`mt-0.5 shrink-0`}),` `,(0,L.jsx)(`span`,{children:i.message})]})}):(0,L.jsx)(eS,{title:`Login`,tone:`red`,children:`Unparseable login payload.`})}function eS({title:e,tone:t,action:n,children:r}){return(0,L.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,L.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[(0,L.jsx)(ot,{size:14,className:t===`red`?`text-[#ef4444]`:t===`green`?`text-[#22c55e]`:`text-[#38bdf8]`}),(0,L.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:e}),n?(0,L.jsx)(`div`,{className:`ml-auto`,children:n}):null]}),r]})}function tS({onClick:e,disabled:t}){return(0,L.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,L.jsx)(Ce,{size:10}),` Back`]})}function nS({tone:e,children:t}){return(0,L.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 rS(e){return`provider`in e&&e.provider?e.provider.name:`Login`}function iS(e){try{let t=new URL(e);return`${t.host}${t.pathname}`}catch{return e.length>42?`${e.slice(0,39)}...`:e}}function aS({row:e,piboSessionId:t,onModelChanged:n}){let r=Xx(e.output),i=(Yx(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 j(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,L.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,L.jsx)(`div`,{className:`flex items-center justify-between gap-3 border-b border-[#2a2a2a] px-3 py-2`,children:(0,L.jsxs)(`div`,{children:[(0,L.jsx)(`div`,{className:`text-[#d4d4d4]`,children:`Model`}),(0,L.jsxs)(`div`,{className:`text-[11px] text-[#737373]`,children:[`Choose a model from authenticated providers. Use `,(0,L.jsx)(`span`,{className:`text-[#38bdf8]`,children:`/login`}),` to add providers.`]})]})}),(0,L.jsxs)(`div`,{className:`space-y-2 p-3`,children:[i.length?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(`label`,{className:`flex items-center gap-2 border border-[#2a2a2a] bg-[#0b0b0b] px-2 py-1 text-[#737373]`,children:[(0,L.jsx)(mt,{size:13}),(0,L.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,L.jsx)(`div`,{className:`max-h-72 overflow-auto border border-[#2a2a2a]`,children:m.length?m.map(e=>(0,L.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,L.jsx)(`span`,{className:`truncate text-[#737373]`,children:e.providerLabel}),(0,L.jsxs)(`span`,{className:`min-w-0`,children:[(0,L.jsx)(`span`,{className:`block truncate text-[#d4d4d4]`,children:e.label}),(0,L.jsxs)(`span`,{className:`block truncate text-[11px] text-[#737373]`,children:[e.provider,`/`,e.id]})]}),c?.provider===e.provider&&c?.id===e.id?(0,L.jsx)(Ae,{size:14,className:`text-[#22c55e]`}):null]},`${e.provider}:${e.id}`)):(0,L.jsx)(`div`,{className:`px-3 py-2 text-[#737373]`,children:`No matching models.`})})]}):(0,L.jsxs)(`div`,{className:`text-[#737373]`,children:[`No authenticated model providers found. Run `,(0,L.jsx)(`span`,{className:`text-[#38bdf8]`,children:`/login`}),` first.`]}),f?(0,L.jsx)(`div`,{className:`text-[11px] text-[#a3a3a3]`,children:f}):null]})]})}function oS(e={}){let t=[],n=[],r=pS(e.warnings),i=pS(e.errors);(e.session?.id||e.session?.title)&&t.push({id:`session`,label:`Session`,value:sS([e.session?.title,e.session?.id].filter(Boolean).join(` | `))}),e.session?.profile&&t.push({id:`profile`,label:`Profile`,value:sS(e.session.profile)}),e.session?.status&&t.push({id:`session-status`,label:`Session status`,value:sS(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:sS(e.model.label??[e.model.provider,e.model.id].filter(Boolean).join(`/`))}),e.runtime?.state&&t.push({id:`runtime`,label:`Runtime`,value:sS(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:sS(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:sS(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`?sS(e.fastMode):e.fastMode?`on`:`off`,tone:e.fastMode?`green`:`neutral`});let o=pS(e.tools?.enabled),s=pS(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:sS(e.providerUsage.planType)}),e.providerUsage?.credits&&t.push({id:`provider-credits`,label:`Credits`,value:e.providerUsage.credits.unlimited?`unlimited`:sS(e.providerUsage.credits.balance??`available`)}),e.message&&t.push({id:`message`,label:`Message`,value:sS(e.message)}),n.push(cS(e.contextUsage));for(let t of lS(e.providerUsage))n.push(t);return{kind:`status`,title:`Status`,fields:t,progress:n,warnings:r,errors:i}}function sS(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 cS(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=uS(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:dS(t)}}function lS(e){return e?.limits?.length?e.limits.map((t,n)=>{let r=uS(t.usedPercent),i=uS(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 ${sS(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:fS(i)}}):[{id:`provider`,label:`Provider quota`,state:`unavailable`,text:`Provider usage unavailable`,tone:`neutral`}]}function uS(e){if(!(typeof e!=`number`||!Number.isFinite(e)))return Math.max(0,Math.min(100,e))}function dS(e){return e===void 0?`neutral`:e>=80?`red`:e>=50?`yellow`:`green`}function fS(e){return e===void 0?`neutral`:e<=20?`red`:e<=50?`yellow`:`green`}function pS(e){return(e??[]).map(e=>sS(e)).filter(e=>e.length>0)}function mS(e){switch(e.kind){case`tool.status`:return hS(e);case`tool.thinking`:return gS(e);case`tool.model`:return _S(e);case`tool.login`:return vS(e);case`tool.call`:case`tool.image`:case`tool.group.exploring`:case`tool.group.images`:return yS(e);case`yielded.run`:return bS(e,`yielded-run`,`Yielded run`,e.status===`error`?`red`:e.status===`running`?`cyan`:`green`);case`execution.compaction`:return bS(e,`compaction`,e.status===`error`?`Compaction failed`:e.status===`running`?`Compacting`:`Compaction`,e.status===`error`?`red`:`magenta`);case`execution.command`:return bS(e,`command`,`Command`,e.status===`error`?`red`:`yellow`);case`error`:return bS(e,`error`,`Error`,`red`);default:return}}function hS(e){let t=SS(e.output),n=CS(t,`activeModel`)??CS(t,`model`),r=oS({session:{id:ES(t,`piboSessionId`)??ES(t,`sessionId`),title:ES(t,`sessionTitle`)??ES(t,`title`),profile:ES(t,`profile`)??ES(t,`activeAgentId`)??ES(t,`agentId`),status:OS(t,`disposed`)?`disposed`:ES(t,`sessionStatus`)},model:n?{provider:ES(n,`provider`),id:ES(n,`id`),label:ES(n,`label`)}:void 0,runtime:{state:OS(t,`disposed`)?`disposed`:OS(t,`processing`)?`processing`:OS(t,`streaming`)?`streaming`:ES(t,`mode`)??`idle`,connected:OS(t,`connected`),queuedMessages:DS(t,`queuedMessages`),processing:OS(t,`processing`),streaming:OS(t,`streaming`),disposed:OS(t,`disposed`)},cwd:ES(t,`cwd`),contextUsage:CS(t,`contextUsage`),providerUsage:CS(t,`providerUsage`),tools:{enabled:TS(t,`enabledTools`),active:TS(t,`activeTools`)},thinking:ES(t,`thinkingLevel`)?{level:ES(t,`thinkingLevel`)}:void 0,fastMode:OS(t,`fastMode`),warnings:TS(t,`warnings`),errors:TS(t,`errors`),message:ES(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 gS(e){let t=SS(e.output),n=ES(t,`level`)??`unknown`,r=t?.supported!==!1,i=TS(t,`availableLevels`);return{id:e.id,kind:`thinking`,title:`Thinking`,status:e.status,tone:r?`yellow`:`red`,rows:[{label:`Current`,value:sS(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 _S(e){let t=wS(SS(e.output),`providers`),n=t.flatMap(e=>{let t=ES(e,`id`)??ES(e,`provider`)??`provider`,n=ES(e,`label`)??ES(e,`name`)??t;return wS(e,`models`).map(e=>{let r=ES(e,`id`)??`model`,i=ES(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 vS(e){let t=wS(SS(e.output),`providers`),n=t.map(e=>{let t=ES(e,`id`)??`provider`;return{id:`login:${t}`,label:ES(e,`name`)??ES(e,`label`)??t,action:`login.selectProvider`,value:t,description:TS(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 yS(e){return bS(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 bS(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?``:` ${xS(e.functionCall.input)}`}`:``}`.trim();return t?[{value:sS(t)}]:[]}),a=e.lines.length===0&&typeof e.output==`string`&&e.output.trim()?[{value:sS(e.output.trim())}]:[],o=[e.error?{label:`Error`,value:sS(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 xS(e){try{return JSON.stringify(e)}catch{return String(e)}}function SS(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 CS(e,t){let n=e?.[t];return n&&typeof n==`object`&&!Array.isArray(n)?n:void 0}function wS(e,t){let n=e?.[t];return Array.isArray(n)?n.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e)):[]}function TS(e,t){let n=e?.[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function ES(e,t){let n=e?.[t];return typeof n==`string`?n:void 0}function DS(e,t){let n=e?.[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function OS(e,t){let n=e?.[t];return typeof n==`boolean`?n:void 0}var kS={transcript:0,"event-log":1,live:2},AS={"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 jS(e,t){return{sourceRank:kS[`event-log`],turnSeq:e??2**53-1,eventSequence:e,phaseRank:AS[t]}}function MS(e,t,n){let r=e??2**53-1,i=t??2**53-1;return{sourceRank:kS.live,turnSeq:r,streamId:r,streamFrameIndex:i,phaseRank:AS[n]}}function NS(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 PS(e,t){if(e)return{...e,contentPartIndex:(e.contentPartIndex??0)+.1,phaseRank:AS[t]}}function FS(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 IS(e){let t=!1,n=e.map(e=>e.children.length?(t=!0,{...e,children:IS(e.children)}):e);return LS(n)?t?n:[...e]:[...n].sort(RS)}function LS(e){for(let t=1;t<e.length;t+=1)if(RS(e[t-1],e[t])>0)return!1;return!0}function RS(e,t){if(e.orderKey&&t.orderKey&&e.orderKey.sourceRank===t.orderKey.sourceRank){let n=FS(e.orderKey,t.orderKey);if(n!==0)return n}else{let n=zS(e,t);if(n!==0)return n}let n=BS(e.startedAt,t.startedAt);if(n!==0)return n;let r=FS(e.orderKey,t.orderKey);return r===0?e.id.localeCompare(t.id):r}function zS(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 BS(e,t){return!e&&!t?0:e?t?e.localeCompare(t):-1:1}function VS(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 HS(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 IS([...t.values()].filter(e=>!n.has(e.id)))}function US(e,t,n,r){if(!WS(t))return;let i=r.get(e)?.filter(e=>e.metadata?.subagentToolName===t)??[],a=KS(n);return a?i.find(e=>e.metadata?.threadKey===a)?.id:i.length===1?i[0].id:void 0}function WS(e){return e.startsWith(`pibo_subagent_`)}function GS(e){return e.slice(14)}function KS(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 qS(e,t,n,r){let i=YS(e,t,n,r);if(!i)return;let a=e.children.find(e=>e.id===i.id);if(a){ZS(a,i),a.runId=i.runId??a.runId;return}e.children.push(i)}function JS(e){let t=new Map;for(let n of VS(e)){let e=QS(n.output);if(!e)continue;let r=eC(e.runId);r&&t.set(r,{snapshot:e,completedAt:eC(e.completedAt)??eC(e.updatedAt)??n.completedAt})}for(let n of VS(e)){if(n.type!==`agent.async`||!n.runId)continue;let e=t.get(n.runId);if(!e)continue;let r=eC(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=eC(e.snapshot.summary)??n.error))}}function YS(e,t,n,r){if(!XS(e))return;let i=QS(e.output),a=nC(e.input)?e.input:{},o=eC(i?.toolName)??eC(a.toolName)??r?.title;if(!o||!WS(o))return;let s=eC(r?.summary)??GS(o),c=eC(i?.runId),l=eC(i?.status),u=a.arguments,d=eC(i?.completionPolicy)??eC(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:tC(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:nC(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:PS(e.orderKey,`agent.async`),children:[]}}function XS(e){return e.type===`tool.call`&&e.title===`pibo_run_start`}function ZS(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 QS(e){if(nC(e)){if($S(e))return e;if(nC(e.details)&&$S(e.details))return e.details}}function $S(e){return typeof e.runId==`string`&&typeof e.toolName==`string`}function eC(e){return typeof e==`string`?e:void 0}function tC(e,t){return e.status===`error`||t===`failed`?`error`:t===`completed`||t===`cancelled`?`done`:`running`}function nC(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function rC(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 iC(e){let t=aC(e.notification),n=t.length===1?t[0]:void 0,r=sC(e.notification.failed)+sC(e.notification.timedOut),i=sC(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:cC(e.notification),output:e.notification,source:e.source,stableKey:e.stableKey??e.id,orderKey:e.orderKey,children:[]}}function aC(e){return[...oC(e.completed),...oC(e.failed),...oC(e.timedOut),...oC(e.cancelled),...oC(e.running)]}function oC(e){return Array.isArray(e)?e.filter(lC):[]}function sC(e){return Array.isArray(e)?e.length:0}function cC(e){let t=[[sC(e.completed),`completed`],[sC(e.failed),`failed`],[sC(e.timedOut),`timed out`],[sC(e.cancelled),`cancelled`],[sC(e.running),`running`]].filter(([e])=>Number(e)>0).map(([e,t])=>`${e} ${t}`);return t.length?t.join(`, `):`No yielded run updates`}function lC(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function uC(e,t,n,r,i,a,o,s,c){let l=r.payload,u=o?_C(e,r):void 0;if(u){l.type===`message_steered`&&l.activeEventId&&(u.parentId=RC(l.activeEventId));return}if(o&&MC(l)&&!NC(l,s)||o&&PC(l,c))return;if(l.type===`assistant_delta`){TC(e,t,l,c,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex);return}if(l.type===`thinking_delta`){OC(e,t,l,c,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex);return}if(l.type===`assistant_message`){let i=dC(n,l,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex),a=t.get(i.id)??EC(t,i);if(a){DC(a,i);return}e.push(i),t.set(i.id,i);return}let d=wC(n,l,i,a,c,r.createdAt,r.eventSequence,r.streamId,r.streamFrameIndex);if(d){if(d.type===`user.message`&&d.status===`running`&&!d.parentId&&l.type===`message_steered`){let e=[...t.values()].reverse().find(e=>e.type===`agent.turn`&&e.status===`running`);e&&(d.parentId=e.id)}if(d.type===`agent.turn`&&d.eventId){let e=[...t.values()].find(e=>e.type===`agent.turn`&&e.eventId===d.eventId);if(e){e.status=d.status,e.completedAt=d.completedAt??e.completedAt;return}}if(d.type===`assistant.message`){let e=t.get(d.id)??EC(t,d);if(e){DC(e,d);return}}if(d.type===`execution.compaction`){let t=XC(e);if(t){ZC(t,d);return}}if(d.type===`model.reasoning`){let e=t.get(d.id)??EC(t,d);if(e){kC(e,d);return}}if(d.type===`agent.delegation`&&!d.toolCallId&&d.linkedPiboSessionId){let e=GC([...t.values()],d);if(e){WC(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`){qS(e,n,r.createdAt,d);return}UC(e,d),qS(e,n,r.createdAt);return}}if(d.eventId){let e=t.get(d.id);if(e){d.type===`user.message`&&(e.status=d.status,e.parentId=d.parentId??e.parentId,e.summary=d.summary??e.summary,e.output=d.output??e.output);return}}fC(d,t),qS(d,n,r.createdAt),e.push(d);for(let e of VS([d]))t.set(e.id,e)}}function dC(e,t,n,r,i,a){let o=typeof t.eventId==`string`?t.eventId:void 0,s=BC(t);return{id:s?zC(s):`event:${t.type}:${nw(t)}`,piboSessionId:e,eventId:o,parentId:o?RC(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}`:LC(t),orderKey:FC(r,t.type,i,a),children:[]}}function fC(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=pC(n,t);return r===void 0||e.startedAt<=r}).sort(RS).at(-1);n&&(e.parentId=n.id)}function pC(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(RS).at(0)?.startedAt}function mC(e){return e.some(e=>{let t=e.payload.type;return t!==`assistant_delta`&&t!==`thinking_delta`})}function hC(e){if(e.type===`assistant_delta`){if(e.text.length===0)return;let t=BC(e);return t?zC(t):void 0}if(e.type===`thinking_delta`){if(e.text.length===0)return;let t=HC(e);return t?VC(t):void 0}}function gC(e,t){return!!_C(e,t)}function _C(e,t){let n=t.payload;if(n.type!==`message_queued`&&n.type!==`message_steered`||n.source!==`user`)return;let r=typeof n.eventId==`string`?n.eventId:void 0,i=r??t.eventId,a=`event:${n.type}:${r??nw(n)}`,o=LC(n),s=typeof n.text==`string`?n.text:void 0,c=VS([...e]).filter(e=>e.type===`user.message`&&e.source===`transcript`);return c.find(e=>vC(e,a,o,i))||c.find(e=>!yC(e)&&!!(s&&xC(e)===s))}function vC(e,t,n,r){return e.id===t||e.stableKey===n?!0:r?e.entryId===r||e.stableKey===`entry:${r}`?!0:[e.id,e.stableKey].some(e=>bC(e)===r):!1}function yC(e){return[e.id,e.stableKey].some(e=>bC(e)!==void 0)}function bC(e){for(let t of[`event:message_queued:`,`event:message_steered:`])if(e?.startsWith(t))return e.slice(t.length)}function xC(e){if(typeof e.output==`string`)return e.output;if(typeof e.summary==`string`)return e.summary}function SC(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 CC(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 wC(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??nw(t)}`,d=l?RC(l):void 0,f={id:u,piboSessionId:e,eventId:l,startedAt:a,source:`event-log`,stableKey:LC(t),orderKey:FC(o,t.type,s,c),children:[]};switch(t.type){case`message_queued`:case`message_steered`:{let n=rC(t.text);return t.source===`service`&&n?iC({id:u,piboSessionId:e,eventId:l,startedAt:a,source:`event-log`,stableKey:l?`run-notification:${l}`:u,orderKey:FC(o,t.type,s,c),notification:n}):{...f,...t.type===`message_steered`&&t.activeEventId?{parentId:RC(t.activeEventId)}:{},type:`user.message`,title:`User Message`,status:AC(t)?`running`:`done`,summary:t.text,output:t.text}}case`message_started`:case`message_finished`:return t.source===`service`?void 0:{...f,id:l?RC(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(!QC(t.text))return;let e=HC(t);return{...f,id:e?VC(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=BC(t);return{...f,id:e?zC(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=WS(t.toolName),s=r.get(t.toolCallId)??(o?US(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?$C(t.result):void 0,linkedPiboSessionId:s,stableKey:`tool:${t.toolCallId}`,children:[]}}case`subagent_session`:{let e=tw(t.childPiboSessionId),n=ew(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 jC(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=ew(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=ew(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 TC(e,t,n,r,i,a,o,s){if(typeof n.text!=`string`||n.text.length===0)return;let c=BC(n),l=c?zC(c):`event:assistant_delta:${nw(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?RC(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:FC(a,n.type,o,s),children:[]};e.push(d),t.set(d.id,d)}function EC(e,t){if(t.stableKey)return[...e.values()].find(e=>e.type===t.type&&e.stableKey===t.stableKey)}function DC(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 OC(e,t,n,r,i,a,o,s){if(typeof n.text!=`string`||n.text.length===0)return;let c=HC(n),l=c?VC(c):`event:thinking_delta:${nw(n)}`,u=c?`reasoning:${c}`:l,d=t.get(l)??[...t.values()].find(e=>e.type===`model.reasoning`&&e.stableKey===u);if(d){let e=`${typeof d.output==`string`?d.output:``}${n.text}`;d.status=r===`running`?`running`:`done`,d.summary=e,d.output=e;return}let f={id:l,parentId:n.eventId?RC(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:u,orderKey:FC(a,n.type,o,s),children:[]};e.push(f),t.set(f.id,f)}function kC(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 AC(e){return(e.type===`message_queued`||e.type===`message_steered`)&&`clientTxnId`in e&&typeof e.clientTxnId==`string`}function jC(e){return e===`session.fork`||e===`session.clone`||e===`session.switch`}function MC(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 NC(e,t){let n=`eventId`in e&&typeof e.eventId==`string`?e.eventId:void 0;return!!(n&&t.has(n))}function PC(e,t){return t!==`running`&&e.type===`tool_call`}function FC(e,t,n,r){return e===void 0&&(n!==void 0||r!==void 0)?MS(n,r,IC(t)):jS(e,IC(t))}function IC(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 LC(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=HC(e);if(t)return`reasoning:${t}`}if(e.type===`assistant_delta`||e.type===`assistant_message`){let t=BC(e);if(t)return`assistant:${t}`}return`event:${e.type}:${t??nw(e)}`}function RC(e){return`event:message:${e}`}function zC(e){return`event:assistant:${e}`}function BC(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 VC(e){return`event:thinking:${e}`}function HC(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 UC(e,t){e.status=t.status,e.summary=t.summary??e.summary,e.input=JC(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 WC(e,t){e.summary=t.summary??e.summary,e.input=JC(e,t),e.linkedPiboSessionId=t.linkedPiboSessionId??e.linkedPiboSessionId}function GC(e,t){let n=[...e].reverse().filter(e=>e.type===`agent.delegation`),r=KC(t),i=n.filter(e=>!e.linkedPiboSessionId&&KC(e)===r),a=qC(t.input);return(a?i.find(e=>qC(e.input)===a):i.length===1?i[0]:void 0)||n.find(e=>e.linkedPiboSessionId===t.linkedPiboSessionId)}function KC(e){let t=YC(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 qC(e){if(!(!YC(e)||typeof e.threadKey!=`string`))return e.threadKey.trim()||void 0}function JC(e,t){return e.type!==`agent.delegation`||!YC(e.input)||!YC(t.input)?t.input??e.input:Object.fromEntries(Object.entries({...e.input,...t.input}).filter(([,e])=>e!==void 0))}function YC(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function XC(e){return VS([...e]).reverse().find(e=>e.type===`execution.compaction`&&e.status===`running`)}function ZC(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 QC(e){return typeof e==`string`&&e.trim().length>0}function $C(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}function ew(e,t,n){return e===void 0?t===void 0?nw(n):`stream:${t}`:`sequence:${e}`}function tw(e){if(typeof e==`string`)return e.trim()||void 0}function nw(e){return rw(new TextEncoder().encode(JSON.stringify(e))).slice(0,48)}function rw(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 iw(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 IS(n)}function aw(e,t,n){return t.map(t=>ow(e,t,n))}function ow(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)||sw(r,t))?r:e?{...t,children:r.children}:{...t,children:[]}}let i=t.children.map(t=>ow(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)||sw(r,t))?r:a?{...t,children:r?.children??i}:{...t,children:i}}function sw(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&&cw(e.orderKey,t.orderKey)}function cw(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 lw(e,t,n){if(!t.length)return e;let r=new Set(e.rawEvents.map(e=>SC(e))),i=[];for(let e of t){let t=SC(e);r.has(t)||(r.add(t),i.push(e))}if(!i.length)return e;let a=VS(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(gC(o,t))continue;f.push(t);let r=hC(t.payload);p&&r?p.add(r):p=void 0,uC(o,s,e.piboSessionId,t,l,u,!1,d,n)}if(!f.length)return e;let m=iw(o);mC(f)&&JS(m);let h=aw(c,m,p);return{...e,rawEvents:e.rawEvents.length?[...e.rawEvents,...f]:f,nodes:h,latestStreamId:CC(f,e.latestStreamId)}}var uw={browser_use_open_tabs:`browser_use.open_tabs`,browser_use_take_screenshot:`browser_use.take_screenshot`,browser_use_browser_use:`browser_use.browser_use`,node_repl_js:`node_repl.js`,node_repl_js_reset:`node_repl.js_reset`};function dw(e,t){if(!e)return[];let n=mw(e.nodes),r=qw(hw(e.nodes).sort((e,t)=>RS(e.node,t.node)).filter(e=>e.node.type!==`agent.turn`&&(t.showThinking||e.node.type!==`model.reasoning`)).map(e=>gw(e.node,e.turnId)));return bw(r,n),Xw(yw(r)).map(e=>e.row)}function fw(e){if(!e)return;let t=new Set(hw(e.nodes).map(({node:e})=>e).filter(e=>e.type===`error`&&e.eventId).map(e=>e.eventId));return[...mw(e.nodes).values()].filter(e=>e.startedAt&&!e.completedAt&&(!e.eventId||!t.has(e.eventId))).sort(RS).at(-1)?.startedAt}function pw(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 mw(e){let t=new Map;for(let n of e){n.type===`agent.turn`&&t.set(n.id,n);for(let[e,r]of mw(n.children))t.set(e,r)}return t}function hw(e,t){let n=[];for(let r of e)r.type!==`agent.turn`&&n.push({node:r,turnId:t}),n.push(...hw(r.children,r.type===`agent.turn`?r.id:t));return n}function gw(e,t){let n;switch(e.type){case`user.message`:n={row:Cw(e),turnId:t};break;case`assistant.message`:n={row:ww(e),turnId:t};break;case`model.reasoning`:n={row:Tw(e),turnId:t};break;case`tool.call`:n=Ew(e,t);break;case`tool.result`:n=kw(e,t);break;case`agent.delegation`:n={row:jw(e),turnId:t};break;case`agent.async`:n={row:Mw(e),turnId:t};break;case`yielded.run`:n={row:Nw(e),turnId:t};break;case`execution.command`:n={row:Fw(e),turnId:t};break;case`execution.compaction`:n={row:Pw(e),turnId:t};break;case`error`:n={row:Gw(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:_w(e),...Sw(e)}}}function _w(e){if(e.type===`tool.call`||e.type===`tool.result`||e.type===`agent.delegation`){let t=e.toolCallId??vw(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=vw(e.stableKey,`assistant:`);if(t)return`terminal:assistant:${t}`}if(e.type===`model.reasoning`){let t=vw(e.stableKey,`reasoning:`);if(t)return`terminal:reasoning:${t}`}return e.id}function vw(e,t){if(!e?.startsWith(t))return;let n=e.slice(t.length);return n&&n!==`undefined`?n:void 0}function yw(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 bw(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??xw(n.startedAt,n.completedAt))}}function xw(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 Sw(e){return{eventId:e.eventId,runId:e.runId,orderSource:e.source,orderStreamId:e.orderKey?.streamId,orderStreamFrameIndex:e.orderKey?.streamFrameIndex,payloadRefs:e.payloadRefs}}function Cw(e){let t=MT(e.output)||MT(e.summary)||e.title;return{id:e.id,kind:`message.user`,status:AT(e.status),lines:[{prefix:`prompt`,tokens:[$(t)]}],sourceNodeIds:[e.id],forkEntryId:e.entryId,pendingMessageDelivery:OT(e),startedAt:e.startedAt,output:t,payloadRefs:e.payloadRefs}}function ww(e){return{id:e.id,kind:`message.assistant`,status:AT(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:MT(e.output)||MT(e.summary)||``,error:e.error,payloadRefs:e.payloadRefs}}function Tw(e){let t=_T(e.output??e.summary);return{id:e.id,kind:`reasoning`,status:AT(e.status),lines:[{prefix:`bullet`,tokens:[$(e.status===`running`?`Thinking`:`Thought`,`amber`,`semibold`)]}],sourceNodeIds:[e.id],markdown:t,payloadRefs:e.payloadRefs}}function Ew(e,t){let n=wT(e.input);if(n&&yT(e.title))return{row:Ww(e,n),turnId:t,exploring:void 0};if(bT(e.title))return{row:Dw(e),turnId:t};let r=tT(e);if(r)return{row:Ow(e,r),turnId:t,image:r.groupable?r.detail:void 0};let i=hT(e.error??e.output,5,e.error?`red`:`dim`);return{row:{id:e.id,kind:`tool.call`,status:AT(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(ET(e.status),jT(e.status),`semibold`),$(` `)],functionCall:{name:uT(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:gT(i,e.error?`error`:`output`)},turnId:t,exploring:lT(e)}}function Dw(e){let t=AT(e.status),n=ST(e),r=CT(e.output),i=[{prefix:`bullet`,tokens:[$(xT(e.status),jT(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 Ow(e,t){let n=AT(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,jT(e.status),`semibold`)]},{prefix:`detail`,tokens:[$(r,e.status===`error`?`red`:`cyan`)]}],sourceNodeIds:[e.id],input:rT(e.input),output:t.summary,error:e.error,expandable:e.input!==void 0||t.summary!==void 0||!!e.error}}function kw(e,t){let n=tT(e);return n?{row:Ow(e,n),turnId:t,image:n.groupable?n.detail:void 0}:{row:Aw(e),turnId:t}}function Aw(e){let t=hT(e.error??e.output,5,e.error?`red`:`dim`);return{id:e.id,kind:`tool.call`,status:AT(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(e.status===`error`?`Tool failed`:`Returned`,jT(e.status),`semibold`),$(` ${uT(e.title)}`)]},...t.lines],sourceNodeIds:[e.id],output:e.output,error:e.error,expandable:e.output!==void 0||!!e.error,previewOmission:gT(t,e.error?`error`:`output`)}}function jw(e){let t=MT(NT(e.input)?e.input.subagentName:void 0)||e.summary||e.title,n=vT((NT(e.input)?e.input.arguments:void 0)??e.input),r=n?[{prefix:`detail`,tokens:[$(n,`dim`)]}]:[];return{id:e.id,kind:`agent.delegation`,status:AT(e.status),errorKind:e.status===`error`?`tool`:void 0,title:e.title,summary:e.summary,lines:[{prefix:`bullet`,tokens:[$(DT(e.status),jT(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 Mw(e){let t=hT(e.error??e.output,5,e.error?`red`:`dim`);return{id:e.id,kind:`agent.async`,status:AT(e.status),lines:[{prefix:`bullet`,tokens:[$(kT(e.status),jT(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:gT(t,e.error?`error`:`output`)}}function Nw(e){let t=hT(e.output,5);return{id:e.id,kind:`yielded.run`,status:AT(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(e.status===`running`?`Waiting on runs`:`Run update`,jT(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:gT(t,`output`)}}function Pw(e){let t=e.status===`running`?`Compacting`:e.status===`error`?`Compaction failed`:MT(e.summary)||`Compacted`;return{id:e.id,kind:`execution.compaction`,status:AT(e.status),lines:[{prefix:`bullet`,tokens:[$(t,jT(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 Fw(e){if(e.title===`status`)return Iw(e);if(e.title===`thinking`)return Yw(e.output)?Rw(e):Lw(e);if(e.title===`fast_mode`)return zw(e);if(e.title===`login`&&Hw(e.output))return Bw(e);if(e.title===`model`&&Uw(e.output))return Vw(e);wT(e.output)??wT(e.input)??e.title;let t=hT(e.error??e.output,5,e.error?`red`:`dim`,180);return{id:e.id,kind:`execution.command`,status:AT(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:gT(t,e.error?`error`:`output`)}}function Iw(e){return{id:e.id,kind:`tool.status`,status:AT(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function Lw(e){return{id:e.id,kind:`tool.thinking`,status:AT(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function Rw(e){let t=NT(e.output)?e.output:void 0,n=MT(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:AT(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 zw(e){let t=NT(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:AT(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 Bw(e){return{id:e.id,kind:`tool.login`,status:AT(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function Vw(e){return{id:e.id,kind:`tool.model`,status:AT(e.status),lines:[],sourceNodeIds:[e.id],input:e.input,output:e.output,error:e.error,expandable:!1}}function Hw(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 Uw(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 Ww(e,t){let n=hT(e.error??e.output,5,e.error?`red`:`dim`,180);return{id:e.id,kind:`execution.command`,status:AT(e.status),errorKind:e.status===`error`?`tool`:void 0,lines:[{prefix:`bullet`,tokens:[$(e.status===`running`?`Running`:`Ran`,jT(e.status),`semibold`),$(` `),...TT(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:gT(n,e.error?`error`:`output`)}}function Gw(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`)]},...Kw(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 Kw(e){return NT(e)?[[`Class`,MT(e.errorClass)??MT(e.category)],[`Code`,MT(e.code)??MT(e.providerCode)],[`Origin`,MT(e.origin)],[`Provider`,[MT(e.api),MT(e.provider),MT(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 qw(e){let t=e.map(e=>e.row.output).filter(Jw).at(-1);return t?e.map(e=>e.row.kind!==`tool.thinking`||!NT(e.row.output)?e:{...e,row:{...e.row,output:{...e.row.output,level:t.level,availableLevels:t.availableLevels,supported:t.supported}}}):[...e]}function Jw(e){return NT(e)&&typeof e.level==`string`&&Array.isArray(e.availableLevels)}function Yw(e){return NT(e)&&e.action===`set_thinking_level`}function Xw(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n],i=Zw(r);if(!i){t.push(r);continue}let a=[r],o=n+1;for(;o<e.length&&Zw(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`?$w(a):Qw(a),turnId:r.turnId}),n=o-1}return t}function Zw(e){if(e.image)return`images`;if(e.exploring)return`exploring`}function Qw(e){let t=eT(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`,jT(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 $w(e){let t=eT(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`,jT(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 eT(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 tT(e){let t=(e.title??``).trim().toLowerCase(),n=NT(e.input)?e.input:void 0,r=NT(e.output)?e.output:void 0,i=cT(r,`details`),a=t===`codex_image_generation`?aT(i)??oT(n):void 0,o=a?MT(i?.savedPath)??fT(i):fT(n)??fT(i)??fT(r),s=a?MT(i?.artifactId):void 0,c=pT(n),l=nT(e.output),u=dT(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?MT(i?.model):void 0,referencedImageCount:a?mT(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?sT(e.status,a):iT(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:AT(e.status),input:rT(e.input),output:p,error:e.error}}}function nT(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=>nT(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`||NT(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=>nT(e,t+1,n))}function rT(e){if(Array.isArray(e))return e.map(rT);if(!NT(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]=rT(r)}return t}function iT(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 aT(e){let t=MT(e?.operation);return t===`generate`||t===`edit`?t:void 0}function oT(e){if(!e)return;let t=e.referenced_image_paths;return Array.isArray(t)&&t.length>0||mT(e.num_last_images_to_include)!==void 0?`edit`:`generate`}function sT(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 cT(e,t){let n=e?.[t];return NT(n)?n:void 0}function lT(e){let t=(e.title??``).trim().toLowerCase(),n=NT(e.input)?e.input:void 0;if(dT(t,[`read`,`open`]))return{id:e.id,label:`Read ${fT(n)??vT(e.input)}`,status:AT(e.status),input:e.input,output:e.output,error:e.error};if(dT(t,[`list`,`ls`,`glob`]))return{id:e.id,label:`List ${fT(n)??vT(e.input)}`,status:AT(e.status),input:e.input,output:e.output,error:e.error};if(dT(t,[`search`,`find`,`grep`,`rg`])){let t=pT(n),r=fT(n);return{id:e.id,label:`Search ${t??vT(e.input)}${r?` in ${r}`:``}`,status:AT(e.status),input:e.input,output:e.output,error:e.error}}}function uT(e){return uw[e]??e}function dT(e,t){return t.some(t=>e===t||e.startsWith(`${t}_`)||e.endsWith(`_${t}`)||e.includes(t))}function fT(e){if(e)for(let t of[`path`,`file`,`filePath`,`filepath`,`url`,`uri`,`cwd`,`pattern`,`glob`]){let n=MT(e[t]);if(n)return n}}function pT(e){if(e)for(let t of[`query`,`pattern`,`text`,`name`,`q`,`regex`]){let n=MT(e[t]);if(n)return n}}function mT(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function hT(e,t,n=`dim`,r=160){let i={lines:[],visibleLineCount:0,omittedLineCount:0,totalLineCount:0,maxVisibleLineCount:t},a=_T(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 gT(e,t){if(!(e.omittedLineCount<=0))return{source:t,visibleLineCount:e.visibleLineCount,omittedLineCount:e.omittedLineCount,totalLineCount:e.totalLineCount,maxVisibleLineCount:e.maxVisibleLineCount}}function _T(e){let t=ox(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 vT(e){return(typeof e==`string`?e:_T(e)).replace(/\s+/g,` `).trim()}function yT(e){let t=(e??``).trim().toLowerCase();return t===`shell`||t===`bash`||t===`terminal`}function bT(e){return(e??``).trim().toLowerCase()===`web_search`}function xT(e){return e===`running`?`Searching web`:e===`error`?`Web search failed`:`Searched web`}function ST(e){let t=NT(e.input)?e.input:void 0,n=NT(e.output)?e.output:void 0;return MT(t?.query)??MT(n?.query)??MT(e.summary)}function CT(e){if(!NT(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 wT(e){if(NT(e))for(let t of[`cmd`,`command`,`script`]){let n=MT(e[t]);if(n)return n}}function TT(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 ET(e){return e===`running`?`Calling`:e===`error`?`Call failed`:`Called`}function DT(e){return e===`running`?`Spawning`:e===`error`?`Spawn failed`:`Spawned`}function OT(e){if(e.status===`running`){if(e.id.startsWith(`event:message_steered:`))return`steer`;if(e.id.startsWith(`event:message_queued:`))return`queue`}}function kT(e){return e===`running`?`Waiting for`:`Finished waiting for`}function AT(e){return e===`running`?`running`:e===`error`?`error`:`done`}function jT(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 MT(e){return typeof e==`string`&&e.trim().length?e:void 0}function NT(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function PT(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 FT(e,t,n){return n?{id:e,label:t,value:n}:void 0}function IT({field:e,icon:t}){let n=t===`session`?$e:Ye;return(0,L.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[11px]`,"data-shared-status-field":e.id,children:[(0,L.jsx)(n,{size:11,className:`shrink-0 text-[#737373]`}),(0,L.jsxs)(`span`,{className:`shrink-0 text-[#737373]`,children:[e.label,`:`]}),(0,L.jsx)(`span`,{className:`truncate font-mono ${e.id===`session`?`text-[#38bdf8]`:`text-[#d4d4d4]`}`,children:e.value})]})}function LT({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,L.jsxs)(`div`,{className:`mt-3 space-y-1`,"data-shared-progress":e.id,"data-shared-progress-state":e.state,children:[(0,L.jsxs)(`div`,{className:`flex items-center justify-between text-[11px]`,children:[(0,L.jsx)(`span`,{className:`text-[#737373]`,children:t??e.label}),(0,L.jsx)(`span`,{className:`font-mono text-[#d4d4d4]`,children:e.state===`available`?e.text:`unavailable`})]}),e.state===`available`?(0,L.jsx)(`div`,{className:`h-1.5 w-full overflow-hidden rounded-full bg-[#2a2a2a]`,children:(0,L.jsx)(`div`,{className:`h-full rounded-full ${r} transition-all`,style:{width:`${Math.min(Math.max(n,0),100)}%`}})}):null]})}function RT(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 zT({row:e}){let t=PT(e.output),n=mS(e),r=n?.kind===`status`?n.statusView:void 0,[i,a]=(0,v.useState)(!1);if(!t||!r)return(0,L.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,L.jsx)(`div`,{className:`text-[#737373]`,children:`Status (unparseable)`})});let o=new Map(r.fields.map(e=>[e.id,e])),s=o.get(`session`)??FT(`session`,`Session`,t.piboSessionId),c=o.get(`cwd`)??FT(`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,L.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,L.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[(0,L.jsx)(xe,{size:14,className:`text-[#22c55e]`}),(0,L.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:r.title})]}),(0,L.jsxs)(`div`,{className:`grid grid-cols-1 gap-1.5 sm:grid-cols-2`,children:[s?(0,L.jsx)(IT,{field:s,icon:`session`}):null,c?(0,L.jsx)(IT,{field:c,icon:`cwd`}):null,p.slice(0,8).map(e=>(0,L.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[11px]`,"data-shared-status-field":e.id,children:[(0,L.jsxs)(`span`,{className:`shrink-0 text-[#737373]`,children:[e.label,`:`]}),(0,L.jsx)(`span`,{className:`truncate font-mono text-[#d4d4d4]`,children:e.value})]},e.id))]}),(0,L.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-1.5`,children:[t.processing?(0,L.jsxs)(`span`,{className:`inline-flex items-center gap-1 border border-[#1f4960] px-1.5 py-0.5 text-[11px] text-[#38bdf8]`,children:[(0,L.jsx)(We,{size:10}),` Processing`]}):null,t.streaming?(0,L.jsxs)(`span`,{className:`inline-flex items-center gap-1 border border-[#1f4960] px-1.5 py-0.5 text-[11px] text-[#38bdf8]`,children:[(0,L.jsx)(xe,{size:10}),` Streaming`]}):null,typeof t.queuedMessages==`number`&&t.queuedMessages>0?(0,L.jsxs)(`span`,{className:`inline-flex items-center gap-1 border border-[#3a3a3a] px-1.5 py-0.5 text-[11px] text-[#d4d4d4]`,children:[(0,L.jsx)(nt,{size:10}),` Queued: `,t.queuedMessages]}):null,t.disposed?(0,L.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,L.jsx)(LT,{progress:l,label:`Context Usage`}):null,u.length?(0,L.jsxs)(`div`,{className:`mt-3 space-y-1.5 border-t border-[#2a2a2a] pt-2`,"data-shared-provider-progress":u.length,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[11px] text-[#737373]`,"data-shared-status-field":`provider-quota`,children:[(0,L.jsx)(Xe,{size:11}),(0,L.jsxs)(`span`,{children:[m,t.providerUsage?.planType?` (${t.providerUsage.planType})`:``]})]}),d?d.map(e=>{let t=RT(e.resetsAt);return(0,L.jsxs)(`div`,{className:`space-y-1`,"data-shared-progress":`provider-limit:${e.label}`,"data-shared-progress-state":`available`,children:[(0,L.jsxs)(`div`,{className:`flex items-center justify-between gap-2 text-[11px]`,children:[(0,L.jsx)(`span`,{className:`text-[#a3a3a3]`,children:e.label}),(0,L.jsxs)(`span`,{className:`shrink-0 font-mono text-[#d4d4d4]`,children:[e.remainingPercent.toFixed(0),`% left`,t?` · resets ${t}`:``]})]}),(0,L.jsx)(`div`,{className:`h-1.5 w-full overflow-hidden rounded-full bg-[#2a2a2a]`,children:(0,L.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,L.jsx)(LT,{progress:e},e.id)),t.providerUsage?.credits?(0,L.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,L.jsxs)(`div`,{className:`mt-3 space-y-1 border-t border-[#2a2a2a] pt-2`,children:[r.warnings.map((e,t)=>(0,L.jsxs)(`div`,{"data-shared-status-warning":!0,className:`text-[11px] text-[#facc15]`,children:[`⚠ `,e]},`warning-${t}`)),r.errors.map((e,t)=>(0,L.jsxs)(`div`,{"data-shared-status-error":!0,className:`text-[11px] text-[#ef4444]`,children:[`✕ `,e]},`error-${t}`))]}):null,f.length>0?(0,L.jsxs)(`div`,{className:`mt-3`,children:[(0,L.jsxs)(`button`,{type:`button`,onClick:()=>a(e=>!e),className:`flex items-center gap-1.5 text-[11px] text-[#737373] hover:text-[#d4d4d4]`,children:[(0,L.jsx)(`span`,{className:`text-[#d4d4d4]`,children:i?`▾`:`▸`}),(0,L.jsxs)(`span`,{children:[`Enabled tools (`,f.length,`)`]})]}),i?(0,L.jsx)(`div`,{className:`mt-1.5 flex flex-wrap gap-1`,children:f.map(e=>(0,L.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 BT=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function VT(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 HT(e){return BT.includes(e)?e:void 0}function UT({row:e,onLevelSelect:t}){let n=VT(e.output);return n?(0,L.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,L.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[(0,L.jsx)(Oe,{size:14,className:`text-[#f59e0b]`}),(0,L.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:`Thinking`}),n.supported===!1?(0,L.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,L.jsx)(xt,{size:10}),` Unsupported`]}):(0,L.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,L.jsx)(Ae,{size:10}),` Supported`]})]}),(0,L.jsxs)(`div`,{className:`grid gap-1.5 text-[11px]`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,L.jsx)(`span`,{className:`text-[#737373]`,children:`Current:`}),(0,L.jsx)(`span`,{className:`font-mono font-semibold text-[#f59e0b]`,children:n.level??`unknown`})]}),n.availableLevels.length?(0,L.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,L.jsx)(`span`,{className:`mr-1 text-[#737373]`,children:`Available:`}),n.availableLevels.map(e=>{let r=HT(e),i=n.supported===!1||!r||!t;return(0,L.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,L.jsxs)(`div`,{className:`text-[#737373]`,children:[`Click a level or use `,(0,L.jsx)(`span`,{className:`text-[#f59e0b]`,children:`/thinking <level>`}),`.`]})]})]}):(0,L.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,L.jsx)(`div`,{className:`text-[#737373]`,children:`Thinking (unparseable)`})})}var WT=`pibo.chat.terminalReadingPosition.`;function GT(e){if(e)try{return qT(sessionStorage.getItem(WT+e))}catch{return}}function KT(e,t){if(e)try{let n=WT+e;t?sessionStorage.setItem(n,JSON.stringify(t)):sessionStorage.removeItem(n)}catch{}}function qT(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 JT=180,YT=4800,XT=20,ZT={index:`LAST`,align:`end`},QT={top:2400,bottom:2400},$T=84,eE=700,tE=6;function nE({traceView:e,isLoading:t,terminalFullscreen:n,showThinking:r,expandThinking:i,sessionAgentProfile:a,sessionActiveModel:o,selectedSessionStatus:s,selectedSessionSignal:c,signals:l,sessionGoal:u,sessionBreadcrumbs:d,originSession:f,derivedSessions:p,agentProfiles:m,sessionProfileChangeDisabled:h,onSessionAgentProfileChange:g,onFork:_,onOpenSession:y,onLoadOlderTracePage:b,hasOlderTraceEvents:x,isFetchingOlderTracePage:S,onThinkingLevelChange:C,onModelChanged:w}){let T=(0,v.useMemo)(()=>dw(e,{showThinking:r}),[r,e]),E=(0,v.useMemo)(()=>T.map(e=>e.id),[T]),D=e?.piboSessionId??``,[O,k]=(0,v.useState)(),A=(0,v.useRef)(void 0),[ee,te]=(0,v.useState)(new Set),j=(0,v.useMemo)(()=>[T,ee],[ee,T]),[M,ne]=(0,v.useState)(null),N=(0,v.useRef)({}),P=(0,v.useRef)(!1),re=(0,v.useRef)(!1),ie=(0,v.useRef)(void 0),ae=(0,v.useRef)(!1),oe=(0,v.useRef)(!1),se=(0,v.useRef)(!1),ce=(0,v.useRef)(()=>void 0),le=T.filter(e=>pE(e,`user`)).length,F=T.filter(e=>pE(e,`tool`)).length,ue=T.filter(e=>pE(e,`system`)).length,de=ex({signal:c,fallbackStatus:s,fallbackTurnStartedAt:(0,v.useMemo)(()=>fw(e),[e])}),fe=de.activeTurnStartedAt,pe=de.isTurnActive,me=!!rx(u);(0,v.useLayoutEffect)(()=>{!D||!e||!jb()||Bb(D,`compact-terminal:render`,T,{traceVersion:e.version,latestStreamId:e.latestStreamId,lastRawEventId:e.rawEvents.at(-1)?.id,selectedSessionStatus:s})},[D,T,s,e]);let he=(0,v.useCallback)(e=>{if(!x||S||ae.current)return;if(oe.current){se.current=!0;return}let t=()=>{ie.current=void 0,!ae.current&&(ae.current=!0,re.current=!1,ce.current(),b?.())};if(!e||!re.current){ie.current!==void 0&&window.clearTimeout(ie.current),t();return}ie.current===void 0&&(ie.current=window.setTimeout(t,eE))},[x,S,b]),ge=(0,v.useCallback)(()=>{P.current&&re.current&&he(!0)},[he]),_e=(0,v.useCallback)(()=>{P.current&&he(!1)},[he]),ve=(0,v.useCallback)(e=>{if(oe.current=e,e){ie.current!==void 0&&(window.clearTimeout(ie.current),ie.current=void 0,se.current=!0);return}se.current&&(se.current=!1,he(!1))},[he]),ye=(0,v.useCallback)((e,t)=>{OE(e,t)&&(re.current=!0)},[]),be=(0,v.useCallback)(e=>{P.current&&(e.startIndex<=0?_e():e.startIndex<=XT&&ge())},[_e,ge]),I=(0,v.useCallback)(e=>{D&&KT(D,e?{rowId:e.key,offsetPx:e.offset}:void 0)},[D]),xe=qa({itemCount:T.length,itemKeys:E,isPrepending:S,resetKey:e?.piboSessionId,contentKey:j,atBottomThreshold:JT,nearTopThreshold:YT,onAtTop:_e,onNearTop:ge,onUserScrollIntent:ye,onScrollbarDragChange:ve,onVisibleAnchorChange:I});ce.current=xe.prepareForPrepend,(0,v.useEffect)(()=>{A.current=void 0,ae.current=!1,oe.current=!1,se.current=!1,k(D?GT(D):void 0)},[D]),(0,v.useEffect)(()=>{ae.current=!1},[e?.nextBeforeCursor,e?.nextBeforeSequence]),(0,v.useEffect)(()=>()=>{ie.current!==void 0&&window.clearTimeout(ie.current)},[]),(0,v.useEffect)(()=>{if(!D||!O)return;let t=E.indexOf(O.rowId);if(t>=0){let e=requestAnimationFrame(()=>{xe.restoreAnchor({key:O.rowId,dataIndex:t,offset:O.offsetPx})&&k(void 0)});return()=>cancelAnimationFrame(e)}if(!x){KT(D,void 0),k(void 0);return}if(S)return;let n=`${D}:${String(e?.nextBeforeCursor??e?.nextBeforeSequence??T.length)}`;A.current!==n&&(A.current=n,b?.())},[x,S,b,D,O,E,T.length,xe.restoreAnchor,e?.nextBeforeCursor,e?.nextBeforeSequence]),(0,v.useEffect)(()=>{if(!D)return;let e=()=>{xe.captureVisibleAnchor()};return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[D,xe.captureVisibleAnchor]),(0,v.useEffect)(()=>{te(e=>fE(e,T,i))},[i,T]),(0,v.useEffect)(()=>{S||xe.isScrolledToTop()&&_e()},[x,S,_e,T.length,xe.isScrolledToTop,e?.nextBeforeCursor,e?.nextBeforeSequence]),(0,v.useEffect)(()=>{P.current=!1,re.current=!1;let e=window.setTimeout(()=>{P.current=!0,xe.isScrolledToTop()&&_e()},250);return()=>window.clearTimeout(e)},[_e,xe.isScrolledToTop,e?.piboSessionId]),(0,v.useEffect)(()=>{let e=new Set(T.map(e=>e.id));ne(t=>t&&e.has(t)?t:null);for(let t of[`system`,`tool`,`user`]){let n=N.current[t];n&&!e.has(n)&&delete N.current[t]}},[T]);let Se=(0,v.useCallback)(e=>{let t=mE(T,e,N.current[e]);t&&(N.current[e]=t.row.id,ne(t.row.id),xe.scrollToIndex(t.index,`start`,`fast-smooth`,{fromIndex:t.fromIndex,stagingAlign:e===`tool`?`end`:void 0}),hE(t.row.id))},[T,xe]),Ce=e=>{e.expandable&&te(t=>{let n=new Set(t);return n.has(e.id)?n.delete(e.id):n.add(e.id),n})},we=(0,v.useCallback)((t,n)=>(0,L.jsx)(`div`,{className:`px-4`,children:(0,L.jsx)(aE,{row:n,expanded:ee.has(n.id),focused:M===n.id,piboSessionId:e?.piboSessionId??``,onToggle:()=>Ce(n),onFork:_,onOpenSession:y,onThinkingLevelChange:C,onModelChanged:w,signals:l})}),[ee,M,_,w,y,C,l,e?.piboSessionId]),Te=(0,v.useMemo)(()=>({Footer:pe||me?()=>(0,L.jsx)(bE,{startedAt:fe,isWorking:pe,goal:u}):void 0}),[fe,pe,u,me]);return(0,L.jsxs)(`section`,{className:`relative min-w-0 flex-1 flex flex-col overflow-hidden bg-[#0b0b0b] text-[#d4d4d4]`,"data-pibo-component":`CompactTerminalSessionView`,"data-pibo-debug":`compact-terminal-session-view`,"data-pibo-session-id":e?.piboSessionId??void 0,"data-pibo-terminal-fullscreen":n?`true`:`false`,"data-pibo-trace-has-older":e?.hasOlderEvents===!0?`true`:`false`,"data-pibo-trace-next-before":e?.nextBeforeCursor??e?.nextBeforeSequence??``,children:[n?null:(0,L.jsx)(rE,{errorCount:ue,toolErrorCount:F,userMessageCount:le,onNavigate:Se,sessionAgentProfile:a,sessionActiveModel:o,sessionBreadcrumbs:d,originSession:f,derivedSessions:p,onOpenSession:y}),(0,L.jsx)(`div`,{className:`min-h-0 flex-1 overflow-hidden`,children:e?T.length?(0,L.jsx)(Ui,{ref:xe.virtuosoRef,data:T,firstItemIndex:xe.firstItemIndex,initialTopMostItemIndex:ZT,increaseViewportBy:QT,defaultItemHeight:$T,className:`min-h-0 h-full overflow-x-hidden font-mono text-[12px] leading-[1.45]`,computeItemKey:(e,t)=>t.id,scrollerRef:xe.scrollerRef,atBottomStateChange:xe.atBottomStateChange,atBottomThreshold:xe.atBottomThreshold,atTopStateChange:e=>{e&&_e()},itemsRendered:xe.itemsRendered,rangeChanged:e=>be(xe.normalizeRange(e)),startReached:_e,followOutput:xe.followOutput,totalListHeightChanged:xe.totalListHeightChanged,alignToBottom:!0,components:Te,itemContent:we}):(0,L.jsx)(EE,{isLoading:t,agentProfiles:m,disabled:h,onSelectAgentProfile:g,message:`No visible trace rows yet.`}):(0,L.jsx)(EE,{isLoading:t,agentProfiles:m,disabled:h,onSelectAgentProfile:g})}),T.length===0&&me?(0,L.jsx)(bE,{isWorking:!1,goal:u}):null,xe.isSticky?null:(0,L.jsx)(`button`,{type:`button`,onClick:()=>{KT(D,void 0),xe.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,L.jsx)(je,{size:18})})]})}function rE({errorCount:e,toolErrorCount:t,userMessageCount:n,onNavigate:r,sessionAgentProfile:i,sessionActiveModel:a,sessionBreadcrumbs:o,originSession:s,derivedSessions:c,onOpenSession:l}){return(0,L.jsxs)(`div`,{"data-pibo-debug":`compact-terminal-header`,className:`border-b border-[#2a2a2a] bg-[#111111] px-4 py-2 text-[11px]`,children:[(0,L.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i?(0,L.jsx)(wE,{tone:`neutral`,children:i}):null,a?(0,L.jsx)(wE,{tone:`purple`,children:a}):null,n>0?(0,L.jsxs)(wE,{tone:`cyan`,label:`${n} user messages · jump to previous user message`,onClick:()=>r(`user`),children:[n,(0,L.jsx)(ct,{size:12})]}):null,e>0?(0,L.jsxs)(wE,{tone:`red`,label:`${e} errors · jump to previous error`,onClick:()=>r(`system`),children:[e,(0,L.jsx)(Be,{size:12})]}):null,t>0?(0,L.jsxs)(wE,{tone:`amber`,label:`${t} tool call errors · jump to previous tool error`,onClick:()=>r(`tool`),children:[t,(0,L.jsx)(Qe,{size:12})]}):null,s?(0,L.jsxs)(iE,{onClick:()=>l(s.piboSessionId),children:[`Origin `,s.label]}):null,c.map(e=>(0,L.jsxs)(iE,{onClick:()=>l(e.piboSessionId),children:[`Derived `,e.label]},e.piboSessionId))]}),o.length?(0,L.jsx)(`div`,{className:`mt-2 flex flex-wrap items-center gap-1 text-[#737373]`,children:o.map((e,t)=>(0,L.jsxs)(`div`,{className:`flex items-center gap-1`,children:[t>0?(0,L.jsx)(Me,{size:12,className:`text-[#525252]`}):null,(0,L.jsx)(`button`,{type:`button`,onClick:()=>l(e.piboSessionId),className:`hover:text-[#38bdf8]`,children:e.label})]},e.piboSessionId))}):null]})}function iE({children:e,onClick:t}){return(0,L.jsx)(`button`,{type:`button`,onClick:t,className:`border border-[#3a3a3a] px-2 py-0.5 text-[#38bdf8] hover:border-[#38bdf8]`,children:e})}function aE({row:e,expanded:t,focused:n,piboSessionId:r,onToggle:i,onFork:a,onOpenSession:o,onThinkingLevelChange:s,onModelChanged:c,signals:l}){let u=!t&&_E(e),d=u?gE(e):e.lines;return e.kind===`agent.delegation`?(0,L.jsx)(`div`,{className:dE(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,L.jsx)(ml,{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,L.jsxs)(`div`,{className:dE(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||vE(t)||i()}:void 0,onKeyDown:e.expandable?t=>{!e.expandable||vE(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,L.jsxs)(`div`,{className:`flex gap-3`,children:[(0,L.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,L.jsx)(oE,{row:e,visibleLines:d,collapseToolCallPreview:u,piboSessionId:r,onThinkingLevelChange:s,onModelChanged:c})}),(0,L.jsx)(uE,{row:e,onFork:a,onOpenSession:o})]}),t?(0,L.jsx)(hx,{row:e,onOpenSession:o}):null]})}function oE({row:e,visibleLines:t,collapseToolCallPreview:n,piboSessionId:r,onThinkingLevelChange:i,onModelChanged:a}){return e.kind===`message.assistant`?(0,L.jsxs)(`div`,{className:`ml-[1.9rem] min-w-0`,"data-pibo-component":`TerminalAssistantMessage`,children:[(0,L.jsx)(`div`,{className:`compact-terminal-markdown`,"data-pibo-component":`MarkdownRendererHost`,"data-pibo-markdown-kind":`assistant-message`,children:(0,L.jsx)(sb,{streaming:e.status===`running`,children:typeof e.output==`string`?e.output:``})}),e.status===`running`?null:(0,L.jsx)(cE,{timestamp:e.completedAt,durationMs:e.durationMs})]}):e.kind===`message.user`?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(sE,{lines:t,status:e.status,clampPreview:n}),e.pendingMessageDelivery?(0,L.jsx)(xl,{delivery:e.pendingMessageDelivery,className:`ml-[1.9rem] mt-2`}):null,(0,L.jsx)(cE,{timestamp:e.startedAt})]}):e.kind===`tool.status`?(0,L.jsx)(zT,{row:e}):e.kind===`tool.thinking`?(0,L.jsx)(UT,{row:e,onLevelSelect:i}):e.kind===`tool.login`?(0,L.jsx)($x,{row:e,piboSessionId:r}):e.kind===`tool.model`?(0,L.jsx)(aS,{row:e,piboSessionId:r,onModelChanged:a}):e.kind===`execution.compaction`&&e.status===`running`?(0,L.jsx)(SE,{}):e.kind===`reasoning`&&e.markdown?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(sE,{lines:t,status:e.status,clampPreview:n}),(0,L.jsx)(`div`,{className:`ml-[1.9rem] min-w-0`,"data-pibo-component":`TerminalReasoningMarkdown`,children:(0,L.jsx)(`div`,{className:`compact-terminal-markdown compact-terminal-reasoning`,"data-pibo-component":`MarkdownRendererHost`,"data-pibo-markdown-kind":`reasoning`,children:(0,L.jsx)(sb,{streaming:e.status===`running`,children:e.markdown})})})]}):(0,L.jsx)(sE,{lines:t,status:e.status,clampPreview:n})}function sE({lines:e,status:t,clampPreview:n}){return e.map((e,r)=>(0,L.jsx)(Fx,{line:e,status:t,clampLines:n&&r===0?5:void 0},r))}function cE({timestamp:e,durationMs:t}){let n=lE(e);return n?(0,L.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:` · ${pw(t)}`]}):null}function lE(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 uE({row:e,onFork:t,onOpenSession:n}){return(0,L.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,L.jsx)(TE,{label:`Open linked session`,onClick:()=>n(e.linkedPiboSessionId),children:`Open`}):null,e.forkEntryId?(0,L.jsxs)(TE,{label:`Fork from this user message`,onClick:()=>t(e.forkEntryId),children:[(0,L.jsx)(Ze,{size:13}),`Fork`]}):null]})}function dE(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 fE(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 DE(e,r)?e:r}function pE(e,t){return t===`user`?e.kind===`message.user`:e.status===`error`?t===`tool`?e.errorKind===`tool`:e.errorKind!==`tool`:!1}function mE(e,t,n){let r=e.map((e,t)=>({row:e,index:t})).filter(({row:e})=>pE(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 hE(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 gE(e){return e.kind===`tool.group.exploring`||e.kind===`tool.group.images`?e.lines.slice(0,tE):e.lines}function _E(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 vE(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 yE=`Working...`;function bE({startedAt:e,isWorking:t,goal:n}){let r=xE(t?e:void 0),i=rx(n);return(0,L.jsx)(`div`,{className:`border-t border-[#141414] px-4 py-2`,role:`status`,"aria-live":`polite`,"aria-label":[t?`Working`:void 0,i===`active`?`Pursuing Goal`:i===`paused`?`Goal Paused`:void 0].filter(Boolean).join(`. `),"data-pibo-component":`TerminalStreamingFooter`,"data-pibo-active-turn-started-at":t?e:void 0,children:(0,L.jsxs)(`div`,{className:`flex min-w-0 items-baseline justify-between gap-4`,"aria-hidden":`true`,children:[t?(0,L.jsxs)(`div`,{className:`grid min-w-0 flex-1 grid-cols-[1.9rem_minmax(0,1fr)] gap-2 whitespace-pre-wrap break-words`,children:[(0,L.jsx)(`span`,{className:`whitespace-pre text-[#737373]`,children:`•`}),(0,L.jsxs)(`span`,{className:`inline-flex min-w-0 items-baseline gap-2`,children:[r?(0,L.jsx)(`span`,{className:`shrink-0 tabular-nums text-[#737373]`,children:r}):null,(0,L.jsx)(`span`,{className:`compact-terminal-working-label`,children:yE})]})]}):(0,L.jsx)(`span`,{className:`min-w-0 flex-1`}),(0,L.jsx)(tx,{goal:n})]})})}function xE(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)?pw(Math.max(0,n-t)):void 0}function SE(){let e=CE();return(0,L.jsxs)(`div`,{className:`grid grid-cols-[1.9rem_minmax(0,1fr)] gap-2 whitespace-pre-wrap break-words`,children:[(0,L.jsx)(`span`,{className:`whitespace-pre text-[#38bdf8]`,children:`•`}),(0,L.jsxs)(`span`,{className:`min-w-0`,children:[(0,L.jsx)(`span`,{className:`font-semibold text-[#38bdf8]`,children:`Compacting`}),(0,L.jsx)(`span`,{className:`text-[#38bdf8]`,children:e})]})]})}function CE(){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 wE({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,L.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,L.jsx)(`span`,{className:i,title:t,"aria-label":t,children:r})}function TE({label:e,onClick:t,children:n}){return(0,L.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 EE({isLoading:e,agentProfiles:t,disabled:n,onSelectAgentProfile:r,message:i}){return(0,L.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,L.jsx)(`div`,{children:e?`Loading trace…`:i??`No trace selected.`}),t.length?(0,L.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:t.map(e=>(0,L.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 DE(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function OE(e,t){return t?t===`away`:e instanceof WheelEvent?e.deltaY<0:e instanceof KeyboardEvent?[`ArrowUp`,`PageUp`,`Home`].includes(e.key):e?.type===`touchmove`}function kE({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,L.jsx)(`section`,{className:`min-w-0 flex-1 overflow-auto bg-[#0b0f14] p-4 text-slate-300`,children:(0,L.jsxs)(`div`,{className:`mx-auto flex max-w-6xl flex-col gap-4`,children:[(0,L.jsx)(AE,{model:u}),(0,L.jsx)(jE,{}),(0,L.jsx)(ME,{model:u,onRefreshBootstrap:c,onError:l}),(0,L.jsx)(PE,{model:u}),(0,L.jsx)(FE,{model:u,onOpenSession:s}),(0,L.jsx)(HE,{nodes:u.nodes,edges:u.edges}),(0,L.jsxs)(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_360px]`,children:[(0,L.jsx)(WE,{model:u}),(0,L.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-4`,children:[(0,L.jsx)(GE,{model:u}),(0,L.jsx)(KE,{model:u}),(0,L.jsx)(qE,{model:u})]})]})]})}):(0,L.jsx)(`section`,{className:`min-w-0 flex-1 overflow-auto bg-[#0b0f14] p-4 text-slate-300`,children:(0,L.jsxs)(`div`,{className:`mx-auto flex max-w-4xl flex-col gap-4`,children:[(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-semibold text-slate-100`,children:[(0,L.jsx)(nt,{size:16,className:`text-[#11a4d4]`}),`Workflow / XState`]}),(0,L.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,L.jsx)(jE,{})]})})}function AE({model:e}){return(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4`,children:[(0,L.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-semibold text-slate-100`,children:[(0,L.jsx)(nt,{size:16,className:`text-[#11a4d4]`}),`Workflow / XState Projection`]}),(0,L.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2 text-xs`,children:[(0,L.jsx)(jD,{tone:`blue`,children:e.workflowId}),e.workflowRunId?(0,L.jsxs)(jD,{tone:`slate`,children:[`run `,ID(e.workflowRunId)]}):null,(0,L.jsx)(jD,{tone:MD(e.status),children:e.state})]})]}),(0,L.jsxs)(`div`,{className:`min-w-0 text-right font-mono text-[11px] text-slate-500`,children:[(0,L.jsxs)(`div`,{className:`truncate`,children:[`session `,ID(e.piboSessionId)]}),e.latestStreamId===void 0?null:(0,L.jsxs)(`div`,{children:[`stream `,e.latestStreamId]})]})]}),(0,L.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 jE(){return(0,L.jsx)(`div`,{className:`rounded-sm border border-amber-500/30 bg-amber-500/10 p-4 text-sm`,children:(0,L.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-amber-200`,children:[(0,L.jsx)(vt,{size:14}),`Workflow IR source-of-truth boundary`]}),(0,L.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,L.jsxs)(`div`,{className:`flex shrink-0 flex-wrap gap-2`,children:[(0,L.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,L.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 ME({model:e,onRefreshBootstrap:t,onError:n}){let r=e.workflowRunId?VE(e):void 0,i=`${e.workflowId}${e.workflowVersion?`@${e.workflowVersion}`:``}`;return(0,L.jsxs)(`div`,{className:`grid gap-4 lg:grid-cols-3`,"aria-label":`Projects workflow execution shell`,children:[(0,L.jsx)(zE,{title:`Workflow configured-session view`,icon:(0,L.jsx)(it,{size:14}),children:(0,L.jsxs)(`div`,{className:`space-y-3 text-xs text-slate-400`,children:[(0,L.jsx)(BE,{label:`selected workflow`,value:i}),(0,L.jsx)(BE,{label:`session state`,value:e.workflowRunId?`started`:`configured/not-started`}),(0,L.jsx)(BE,{label:`input keys`,value:String(e.configuration.inputKeys.length)}),(0,L.jsx)(BE,{label:`prompt overrides`,value:String(e.configuration.promptOverrideNodeIds.length)}),(0,L.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,L.jsx)(zE,{title:`Workflow run view`,icon:(0,L.jsx)(xe,{size:14}),children:(0,L.jsxs)(`div`,{className:`space-y-3 text-xs text-slate-400`,children:[(0,L.jsx)(BE,{label:`run id`,value:e.workflowRunId?ID(e.workflowRunId):`not started`}),(0,L.jsx)(BE,{label:`status`,value:e.state}),(0,L.jsx)(BE,{label:`current node`,value:r?.label??`none`}),(0,L.jsx)(BE,{label:`output`,value:e.finalOutput?`available`:`empty`}),(0,L.jsx)(BE,{label:`error`,value:e.runtimeErrors.length?`${e.runtimeErrors.length} runtime errors`:e.validationErrors.length?`${e.validationErrors.length} validation diagnostics`:`none`}),(0,L.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,L.jsx)(zE,{title:`Human action area`,icon:(0,L.jsx)(He,{size:14}),children:(0,L.jsx)(NE,{model:e,onRefreshBootstrap:t,onError:n})})]})}function NE({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 qx(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=yD(e);c(e=>({...e,[i.waitTokenId]:t})),n?.(t[0]?.message??bD(e))}finally{o(null)}};return(0,L.jsxs)(`div`,{className:`space-y-3 text-xs text-slate-400`,children:[e.pendingHumanActions.length?(0,L.jsx)(`div`,{className:`space-y-3`,children:e.pendingHumanActions.map(e=>{let t=[...e.diagnostics,...e.waitTokenId?s[e.waitTokenId]??[]:[]];return(0,L.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,L.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsx)(`div`,{className:`font-semibold`,children:e.label}),(0,L.jsx)(`div`,{className:`mt-1 break-words text-[11px] leading-5 text-amber-100/80`,children:e.prompt})]}),(0,L.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?ID(e.waitTokenId):e.source})]}),(0,L.jsxs)(`div`,{className:`mt-2 grid gap-2 text-[11px] text-amber-100/75`,children:[(0,L.jsx)(BE,{label:`human node`,value:e.humanNodeId??`unspecified`}),(0,L.jsx)(BE,{label:`payload`,value:e.payloadRequirements?.description??`No persisted payload schema.`}),e.expiresAt?(0,L.jsx)(BE,{label:`expires`,value:e.expiresAt}):null]}),e.payloadRequirements?.schema?(0,L.jsxs)(`div`,{className:`mt-2 rounded-sm border border-amber-400/25 bg-[#0b0f14]/50 p-2`,children:[(0,L.jsx)(`div`,{className:`mb-1 text-[10px] font-bold uppercase tracking-wider text-amber-100/70`,children:`Resume payload schema`}),(0,L.jsx)(fl,{value:e.payloadRequirements.schema,defaultExpandLevel:1,maxHeight:`10rem`,showControls:!1})]}):null,e.availableActions.some(e=>e.kind===`resume`)?(0,L.jsxs)(`label`,{className:`mt-3 block text-[11px] text-amber-100/80`,children:[(0,L.jsx)(`span`,{className:`mb-1 block font-semibold`,children:`Resume payload JSON`}),(0,L.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,L.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,L.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,L.jsx)(`span`,{className:`text-amber-100/60`,children:`No registered human actions are available for this wait token.`})}),e.waitTokenId&&l[e.waitTokenId]?(0,L.jsx)(`div`,{className:`mt-2 text-[11px] text-emerald-200`,children:l[e.waitTokenId]}):null,t.length?(0,L.jsx)(`div`,{className:`mt-2 space-y-1`,"aria-label":`Human action diagnostics`,children:t.map((e,t)=>(0,L.jsxs)(`div`,{className:`rounded border border-red-400/35 bg-red-500/15 p-2 text-[11px] leading-5 text-red-100`,children:[(0,L.jsx)(`div`,{children:e.message}),(0,L.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,L.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,L.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 PE({model:e}){let t=e.workflowRunId?VE(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,L.jsxs)(`section`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,"aria-label":`Workflow run inspection panel`,children:[(0,L.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,L.jsx)(Ge,{size:14}),`Workflow run inspection`]}),(0,L.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,L.jsxs)(`div`,{className:`flex shrink-0 flex-wrap gap-2 text-[10px] uppercase tracking-wide`,children:[(0,L.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,L.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,L.jsxs)(`div`,{className:`mt-4 grid gap-3 lg:grid-cols-3`,children:[(0,L.jsxs)(IE,{title:`Status`,badge:e.state,icon:(0,L.jsx)(xe,{size:14}),children:[(0,L.jsx)(LE,{label:`run id`,value:e.workflowRunId?ID(e.workflowRunId):`not started`}),(0,L.jsx)(LE,{label:`status`,value:e.state}),(0,L.jsx)(LE,{label:`record source`,value:e.workflowRunId?`Project workflow run id`:`no run record yet`})]}),(0,L.jsxs)(IE,{title:`Current node`,badge:t?.status??`none`,icon:(0,L.jsx)(ft,{size:14}),children:[(0,L.jsx)(LE,{label:`node`,value:t?.label??`none`}),(0,L.jsx)(LE,{label:`node id`,value:t?.id??`none`}),(0,L.jsx)(LE,{label:`source`,value:`project/session run cursor`})]}),(0,L.jsx)(IE,{title:`Run history`,badge:`${e.runHistory.length}`,icon:(0,L.jsx)(et,{size:14}),children:e.runHistory.length?(0,L.jsx)(`div`,{className:`space-y-2`,children:e.runHistory.map(e=>(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:[(0,L.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,L.jsx)(`div`,{className:`min-w-0 truncate font-mono text-xs text-slate-200`,children:ID(e.id)}),(0,L.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide ${FD(e.status)}`,children:e.status})]}),(0,L.jsxs)(`div`,{className:`mt-1 text-[11px] text-slate-500`,children:[e.currentNodeId?`current ${e.currentNodeId}`:`no current node`,` · `,e.source]}),(0,L.jsxs)(`div`,{className:`mt-1 font-mono text-[10px] text-slate-600`,children:[`updated `,e.updatedAt]})]},e.id))}):(0,L.jsx)(RE,{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,L.jsxs)(`div`,{className:`mt-3 grid gap-3 lg:grid-cols-2`,children:[(0,L.jsx)(IE,{title:`Node attempts`,badge:`${e.nodeAttempts.length}`,icon:(0,L.jsx)(it,{size:14}),children:e.nodeAttempts.length?(0,L.jsx)(`div`,{className:`space-y-2`,children:e.nodeAttempts.map(e=>(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:[(0,L.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsx)(`div`,{className:`truncate text-xs font-semibold text-slate-200`,children:e.label}),(0,L.jsxs)(`div`,{className:`mt-1 font-mono text-[10px] text-slate-500`,children:[e.nodeId,` · attempt `,e.attempt]})]}),(0,L.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide ${FD(e.status)}`,children:e.status})]}),(0,L.jsxs)(`div`,{className:`mt-1 text-[11px] text-slate-500`,children:[e.kind,` · `,e.source]})]},e.id))}):(0,L.jsx)(RE,{children:e.workflowRunId?`No node attempts recorded for this workflow run yet.`:`No current node attempts; Start has not created a workflow run.`})}),(0,L.jsx)(IE,{title:`Edge transfers`,badge:`${e.edgeTransfers.length}`,icon:(0,L.jsx)(Ze,{size:14}),children:e.edgeTransfers.length?(0,L.jsx)(`div`,{className:`space-y-2`,children:e.edgeTransfers.map(e=>(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:[(0,L.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,L.jsx)(`div`,{className:`min-w-0 truncate font-mono text-xs text-slate-200`,children:e.edgeId}),(0,L.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide ${FD(e.status)}`,children:e.status})]}),(0,L.jsxs)(`div`,{className:`mt-1 text-[11px] text-slate-500`,children:[e.source,e.createdAt?` · ${e.createdAt}`:``]})]},e.id))}):(0,L.jsx)(RE,{children:`No edge transfers recorded for this workflow run yet.`})}),(0,L.jsx)(IE,{title:`Output`,badge:e.finalOutput?`available`:`empty`,icon:(0,L.jsx)(Re,{size:14}),children:e.finalOutput?(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:[(0,L.jsx)(`div`,{className:`mb-2 font-mono text-[10px] text-slate-500`,children:e.finalOutput.source}),(0,L.jsx)(fl,{value:e.finalOutput.value,defaultExpandLevel:1,maxHeight:`12rem`,showControls:!1})]}):(0,L.jsx)(RE,{children:`No workflow output has been recorded for this run yet.`})}),(0,L.jsx)(IE,{title:`Error`,badge:n.length?`${n.length}`:`none`,icon:(0,L.jsx)(vt,{size:14}),children:n.length?(0,L.jsx)(`div`,{className:`space-y-2`,children:n.map(e=>(0,L.jsxs)(`div`,{className:`rounded-sm border border-red-500/35 bg-red-500/10 p-2 text-xs text-red-100`,children:[(0,L.jsx)(`div`,{className:`break-words`,children:e.message}),(0,L.jsxs)(`div`,{className:`mt-1 flex flex-wrap gap-1 font-mono text-[10px] text-red-200/70`,children:[e.code?(0,L.jsx)(`span`,{children:e.code}):null,e.source?(0,L.jsx)(`span`,{children:e.source}):null]})]},e.id))}):(0,L.jsx)(RE,{children:`No workflow run errors are recorded.`})})]})]})}function FE({model:e,onOpenSession:t}){let n=$E(e.definitionLink);return(0,L.jsxs)(`section`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,"aria-label":`Workflow navigation links`,children:[(0,L.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,L.jsx)(Ke,{size:14}),`Workflow navigation links`]}),(0,L.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,L.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,L.jsx)(Ke,{size:13}),`Open live workflow definition`]}):null]}),(0,L.jsxs)(`div`,{className:`mt-4 grid gap-3 lg:grid-cols-2`,children:[(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0f171e] p-3`,"aria-label":`Nested workflow child session links`,children:[(0,L.jsxs)(`div`,{className:`mb-3 flex items-center justify-between gap-2`,children:[(0,L.jsx)(`div`,{className:`text-xs font-bold uppercase tracking-wider text-slate-500`,children:`Nested workflow child sessions`}),(0,L.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,L.jsx)(`div`,{className:`space-y-2`,children:e.nestedSessionLinks.map(e=>(0,L.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,L.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsx)(`div`,{className:`truncate text-xs font-semibold text-slate-200`,children:e.title}),(0,L.jsx)(`div`,{className:`mt-1 font-mono text-[10px] text-slate-500`,children:ID(e.piboSessionId)})]}),(0,L.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,L.jsx)(RE,{children:`No nested workflow child sessions are linked under this selected Project session yet.`})]}),(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0f171e] p-3`,"aria-label":`Workflow definition link state`,children:[(0,L.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,L.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,L.jsx)(`div`,{className:`font-semibold`,children:`Live workflow definition exists`}),(0,L.jsx)(`div`,{className:`mt-1 font-mono text-[11px] text-emerald-100/80`,children:tD(e.definitionLink)}),e.definitionLink.definitionHash?(0,L.jsxs)(`div`,{className:`mt-1 font-mono text-[10px] text-emerald-100/60`,children:[`snapshot `,ID(e.definitionLink.definitionHash)]}):null]}):(0,L.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,L.jsx)(`div`,{className:`font-semibold`,children:`Definition deleted — snapshot-only definition-deleted state`}),(0,L.jsx)(`div`,{className:`mt-1 font-mono text-[11px] text-amber-100/80`,children:tD(e.definitionLink)}),(0,L.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,L.jsxs)(`div`,{className:`mt-1 font-mono text-[10px] text-amber-100/60`,children:[`snapshot `,ID(e.definitionLink.definitionHash)]}):null]})]})]})]})}function IE({title:e,badge:t,icon:n,children:r}){return(0,L.jsxs)(`section`,{className:`min-w-0 rounded-sm border border-slate-800 bg-[#0f171e] p-3`,"aria-label":e,children:[(0,L.jsxs)(`div`,{className:`mb-3 flex items-center justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,L.jsx)(`span`,{className:`text-[#11a4d4]`,children:n}),e]}),(0,L.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 LE({label:e,value:t}){return(0,L.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,L.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-slate-500`,children:e}),(0,L.jsx)(`span`,{className:`min-w-0 max-w-[14rem] truncate text-right font-mono text-xs text-slate-300`,title:t,children:t})]})}function RE({children:e}){return(0,L.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 zE({title:e,icon:t,children:n}){return(0,L.jsxs)(`section`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4`,"aria-label":e,children:[(0,L.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,L.jsx)(`span`,{className:`text-[#11a4d4]`,children:t}),e]}),n]})}function BE({label:e,value:t}){return(0,L.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,L.jsx)(`span`,{className:`uppercase tracking-wide text-slate-500`,children:e}),(0,L.jsx)(`span`,{className:`min-w-0 max-w-[12rem] truncate text-right font-mono text-slate-300`,title:t,children:t})]})}function VE(e){return e.nodes.find(e=>e.status===`active`||e.status===`waiting`)??e.nodes[0]}function HE({nodes:e,edges:t}){return(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0f171e] p-4`,children:[(0,L.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,L.jsx)(ft,{size:14}),`Visual State Flow`]}),(0,L.jsx)(`div`,{className:`grid gap-3 md:grid-cols-[1fr_auto_1fr_auto_1fr]`,children:e.map((e,n)=>(0,L.jsx)(UE,{node:e,edge:t[n]},e.id))})]})}function UE({node:e,edge:t}){return(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(`div`,{className:`rounded-sm border p-3 ${ND(e.status)}`,children:[(0,L.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,L.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,L.jsx)(AD,{status:e.status}),(0,L.jsx)(`div`,{className:`min-w-0 truncate text-sm font-semibold text-slate-100`,children:e.label})]}),(0,L.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,L.jsx)(`p`,{className:`mt-2 text-xs text-slate-400`,children:e.description})]}),t?(0,L.jsx)(`div`,{className:`hidden items-center justify-center text-center text-[10px] uppercase tracking-wide text-slate-500 md:flex`,children:(0,L.jsxs)(`div`,{children:[(0,L.jsx)(Ze,{size:14,className:`mx-auto mb-1 text-[#11a4d4]`}),t.label]})}):null]})}function WE({model:e}){return(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4`,children:[(0,L.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,L.jsx)(xe,{size:14}),`Current UI Snapshot`]}),(0,L.jsx)(fl,{value:e.snapshot,showControls:!1})]})}function GE({model:e}){return(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,children:[(0,L.jsxs)(`div`,{className:`mb-3 flex items-center justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,L.jsx)(it,{size:14}),`Node Statuses`]}),(0,L.jsxs)(`span`,{className:`font-mono text-[11px] text-slate-500`,children:[e.nodes.length,` nodes`]})]}),(0,L.jsx)(`div`,{className:`space-y-2`,children:e.nodes.map(e=>(0,L.jsxs)(`div`,{className:`rounded-sm border px-3 py-2 ${ND(e.status)}`,children:[(0,L.jsxs)(`div`,{className:`flex min-w-0 items-start justify-between gap-3`,children:[(0,L.jsxs)(`div`,{className:`flex min-w-0 items-start gap-2`,children:[(0,L.jsx)(`span`,{className:`mt-0.5 shrink-0`,children:(0,L.jsx)(AD,{status:e.status})}),(0,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsx)(`div`,{className:`truncate text-sm font-semibold text-slate-100`,children:e.label}),(0,L.jsx)(`div`,{className:`mt-0.5 truncate font-mono text-[11px] text-slate-500`,children:e.id})]})]}),(0,L.jsxs)(`div`,{className:`flex shrink-0 flex-col items-end gap-1`,children:[(0,L.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide ${PD(e.status)}`,children:e.status}),(0,L.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,L.jsx)(`p`,{className:`mt-2 text-xs text-slate-400`,children:e.description})]},e.id))}),(0,L.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 KE({model:e}){return(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,children:[(0,L.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,L.jsx)(Re,{size:14}),`Final Output & Validation`]}),(0,L.jsxs)(`div`,{className:`space-y-4`,children:[(0,L.jsxs)(`div`,{children:[(0,L.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,L.jsx)(`div`,{className:`text-xs font-semibold uppercase tracking-wide text-slate-400`,children:`Final output`}),e.finalOutput?(0,L.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,L.jsx)(`div`,{className:`rounded-sm border border-slate-800 bg-[#0b0f14] p-2`,children:(0,L.jsx)(fl,{value:e.finalOutput.value,defaultExpandLevel:1,maxHeight:`14rem`,showControls:!1})}):(0,L.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,L.jsxs)(`div`,{children:[(0,L.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,L.jsx)(`div`,{className:`text-xs font-semibold uppercase tracking-wide text-slate-400`,children:`Validation errors`}),(0,L.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,L.jsx)(`div`,{className:`space-y-2`,children:e.validationErrors.map(e=>(0,L.jsx)(`div`,{className:`rounded-sm border border-red-500/35 bg-red-500/10 p-2`,children:(0,L.jsxs)(`div`,{className:`flex min-w-0 items-start gap-2 text-xs text-red-200`,children:[(0,L.jsx)(vt,{size:14,className:`mt-0.5 shrink-0 text-red-300`}),(0,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsx)(`div`,{className:`break-words`,children:e.message}),(0,L.jsxs)(`div`,{className:`mt-1 flex flex-wrap gap-1 font-mono text-[10px] text-red-200/70`,children:[e.code?(0,L.jsx)(`span`,{children:e.code}):null,e.path?(0,L.jsx)(`span`,{children:e.path}):null,e.source?(0,L.jsx)(`span`,{children:e.source}):null]})]})]})},e.id))}):(0,L.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 qE({model:e}){return(0,L.jsxs)(`div`,{className:`rounded-sm border border-slate-800 bg-[#111820] p-4 text-sm`,children:[(0,L.jsxs)(`div`,{className:`mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-500`,children:[(0,L.jsx)(Ve,{size:14}),`Projection Facts`]}),(0,L.jsxs)(`dl`,{className:`space-y-3`,children:[(0,L.jsx)(JE,{label:`projection kind`,value:`pibo.workflow.xstateUiModel`}),(0,L.jsx)(JE,{label:`schema`,value:`v1`}),(0,L.jsx)(JE,{label:`durable truth`,value:`kernel`}),(0,L.jsx)(JE,{label:`private payloads`,value:`not exposed`}),(0,L.jsx)(JE,{label:`states`,value:String(e.nodes.length)}),(0,L.jsx)(JE,{label:`transitions`,value:String(e.edges.length)}),(0,L.jsx)(JE,{label:`trace`,value:e.traceVersion??`pending`})]})]})}function JE({label:e,value:t}){return(0,L.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,L.jsx)(`dt`,{className:`text-xs uppercase tracking-wide text-slate-500`,children:e}),(0,L.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(!CD(e))return null;let o=wD(e,n),s=TD(e,n),c=ED(s),l=dD(t,s),u=[...pD(t),...fD(e,i)],d=iD(e,o,c),f=aD(t,e.workflowRunId),p=cD(t,e.workflowRunId),m=lD(t,r),h=XE(e),g=ZE(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:DD(s),label:OD(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:DD(s),label:kD(s)}],configuration:nD(e),definitionLink:h,nestedSessionLinks:g,pendingHumanActions:rD(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`&&!!$E(h)},nestedWorkflowSessionCount:g.length}}}function XE(e){return e.workflowDefinitionLink?e.workflowDefinitionLink:e.workflowVersion?{status:`live`,workflowId:e.workflowId,workflowVersion:e.workflowVersion,title:e.title??e.workflowId,href:eD(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 ZE(e,t){let n=QE(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 QE(e,t){for(let n of e){if(n.piboSessionId===t)return n;let e=QE(n.children,t);if(e)return e}}function $E(e){if(e.status===`live`){if(e.href)return e.href;if(e.workflowVersion)return eD(e.workflowId,e.workflowVersion)}}function eD(e,t){return`/apps/chat/workflows/view/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function tD(e){return`${e.workflowId}${e.workflowVersion?`@${e.workflowVersion}`:``}`}function nD(e){let t=e.configuration;return{inputKeys:Object.keys(t?.inputValues??{}).sort(),promptOverrideNodeIds:Object.keys(t?.promptOverrides??{}).sort()}}function rD(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=wD(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 iD(e,t,n){return e.workflowRunId?[{id:e.workflowRunId,status:t,currentNodeId:n,updatedAt:e.updatedAt,source:`project session run record`}]:[]}function aD(e,t){return!t||!e?[]:mD(e.nodes).filter(oD).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:sD(e.status),attempt:t+1,source:`session trace fact`,...e.startedAt?{startedAt:e.startedAt}:{},...e.completedAt?{completedAt:e.completedAt}:{}}))}function oD(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 sD(e){return e===`done`?`completed`:e===`error`?`failed`:`running`}function cD(e,t){if(!t||!e)return[];let n=[];for(let r of e.rawEvents){if(!SD(r.payload))continue;let e=xD(r.payload.type),i=xD(r.payload.runId);if(e!==`edge.transferred`||i&&i!==t)continue;let a=xD(r.payload.edgeId);a&&n.push({id:xD(r.payload.edgeTransferId)??r.id,edgeId:a,status:`transferred`,source:r.type,createdAt:r.createdAt})}return n.slice(0,8)}function lD(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 mD(e.nodes)){let e=t.error??(t.status===`error`?gD(t.output)??gD(t.summary):void 0);e&&n.push({id:`node:${t.id}`,message:e,source:t.type})}for(let t of e.rawEvents){if(!SD(t.payload))continue;let e=t.payload.error,r=SD(e)?xD(e.message):xD(e),i=SD(e)?xD(e.code):void 0;r&&n.push({id:`event:${t.id}`,message:r,...i?{code:i}:{},source:t.type})}}return uD(n).slice(0,8)}function uD(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 dD(e,t){if(t!==`completed`||!e)return;let n=mD(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 fD(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 vD(n).slice(0,8)}function pD(e){if(!e)return[];let t=[];for(let n of mD(e.nodes)){let e=n.error??gD(n.output)??gD(n.summary);e&&(!_D([n.title,n.summary,n.error,n.type].filter(e=>typeof e==`string`).join(` `))&&!_D(e)||t.push({id:`node:${n.id}`,message:e,...n.type?{source:n.type}:{}}))}for(let n of e.rawEvents)hD(n.payload,`event:${n.id}`,t);return vD(t).slice(0,8)}function mD(e){let t=[],n=e=>{for(let r of e)t.push(r),n(r.children)};return n(e),t}function hD(e,t,n,r=0){if(r>4||!SD(e))return;let i=Array.isArray(e.diagnostics)?e.diagnostics:void 0;if(i)for(let e of i){if(!SD(e))continue;let r=xD(e.message)??gD(e);r&&n.push({id:`${t}:diagnostic:${n.length}`,message:r,...xD(e.code)?{code:xD(e.code)}:{},...xD(e.path)?{path:xD(e.path)}:{},source:`workflow.diagnostic`})}let a=e.error;if(SD(a)){let e=xD(a.code),r=xD(a.message)??gD(a);r&&_D([e,r].filter(Boolean).join(` `))&&n.push({id:`${t}:error:${n.length}`,message:r,...e?{code:e}:{},source:`workflow.error`})}else typeof a==`string`&&_D(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`||hD(a,`${t}:${i}`,n,r+1)}function gD(e){if(typeof e==`string`)return e;if(SD(e))return xD(e.message)??xD(e.error)??xD(e.summary)}function _D(e){let t=e.toLowerCase();return t.includes(`validation`)||t.includes(`validate`)||t.includes(`diagnostic`)||t.includes(`workflowinterfaceerror`)||t.includes(`workflowruntimeerror.validation`)}function vD(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 yD(e){return SD(e)&&SD(e.data)&&Array.isArray(e.data.diagnostics)?e.data.diagnostics.filter(SD).map(t=>({code:xD(t.code)??`WorkflowRuntimeError.humanActionRejected`,message:xD(t.message)??bD(e),severity:t.severity===`info`||t.severity===`warning`||t.severity===`error`?t.severity:`error`,...xD(t.path)?{path:xD(t.path)}:{},...xD(t.registryRef)?{registryRef:xD(t.registryRef)}:{},...xD(t.hint)?{hint:xD(t.hint)}:{}})):[{code:`WorkflowRuntimeError.humanActionRejected`,message:bD(e),severity:`error`}]}function bD(e){return e instanceof Error?e.message:String(e)}function xD(e){return typeof e==`string`&&e.trim()?e:void 0}function SD(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function CD(e){return!!e.workflowRunId||e.state===`workflow`||e.workflowId!==`simple-chat`}function wD(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 TD(e,t){let n=wD(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 ED(e){return e===`completed`?`workflow.completed`:e===`failed`?`workflow.failed`:e===`cancelled`?`workflow.cancelled`:`node.session`}function DD(e){return e===`failed`?`workflow.failed`:e===`cancelled`?`workflow.cancelled`:`workflow.completed`}function OD(e){return e===`failed`?`failed`:e===`cancelled`?`cancelled`:`completed`}function kD(e){return e===`failed`?`WORKFLOW.FAIL`:e===`cancelled`?`WORKFLOW.CANCEL`:`WORKFLOW.NODE.DONE`}function AD({status:e}){return e===`completed`?(0,L.jsx)(Re,{size:16,className:`text-emerald-300`}):e===`failed`?(0,L.jsx)(Be,{size:16,className:`text-red-300`}):e===`cancelled`?(0,L.jsx)(vt,{size:16,className:`text-slate-400`}):e===`waiting`?(0,L.jsx)(He,{size:16,className:`text-amber-300`}):e===`active`?(0,L.jsx)(xe,{size:16,className:`text-[#11a4d4]`}):(0,L.jsx)(Ve,{size:16,className:`text-slate-500`})}function jD({tone:e,children:t}){return(0,L.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 MD(e){return e===`completed`?`green`:e===`failed`||e===`cancelled`?`red`:e===`waiting`?`amber`:`blue`}function ND(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 PD(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 FD(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 ID(e){return e.length>18?`${e.slice(0,10)}…${e.slice(-6)}`:e}var LD=[{id:`terminal`,label:`Terminal`,description:`Compact Codex-style terminal transcript.`,render:e=>(0,L.jsx)(nE,{...e})},{id:`workflow`,label:`Workflow`,description:`Workflow/XState visualization for workflow-backed project sessions.`,render:e=>(0,L.jsx)(kE,{...e})}],RD=new Map(LD.map(e=>[e.id,e]));function zD(){return LD}function BD(e){return RD.get(e)??RD.get(`terminal`)}var VD=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(){}},HD=new class extends VD{#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`}},UD={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},WD=new class{#e=UD;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 GD(e){setTimeout(e,0)}var KD=typeof window>`u`||`Deno`in globalThis;function qD(){}function JD(e){return typeof e==`number`&&e>=0&&e!==1/0}function YD(e,t){return Math.max(e+(t||0)-Date.now(),0)}function XD(e,t){return typeof e==`function`?e(t):e}function ZD(e,t){return typeof e==`function`?e(t):e}var QD=Object.prototype.hasOwnProperty;function $D(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=tO(e)&&tO(t);if(!r&&!(nO(e)&&nO(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:QD.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=$D(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function eO(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 tO(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function nO(e){if(!rO(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!rO(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function rO(e){return Object.prototype.toString.call(e)===`[object Object]`}function iO(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:$D(e,t)}function aO(e,t){return typeof e==`function`?e(...t):!!e}var oO=(()=>{let e=()=>KD;return{isServer(){return e()},setIsServer(t){e=t}}})();function sO(){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 cO=GD;function lO(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=cO,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 uO=lO(),dO=new class extends VD{#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 fO(e){return(e??`online`)===`online`?dO.isOnline():!0}function pO(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:fO(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}var mO=class extends VD{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=sO(),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),gO(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return _O(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return _O(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 ZD(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&&!eO(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&vO(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||ZD(this.options.enabled,this.#t)!==ZD(t.enabled,this.#t)||XD(this.options.staleTime,this.#t)!==XD(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||ZD(this.options.enabled,this.#t)!==ZD(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 bO(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(qD)),t}#g(){this.#b();let e=XD(this.options.staleTime,this.#t);if(oO.isServer()||this.#r.isStale||!JD(e))return;let t=YD(this.#r.dataUpdatedAt,e)+1;this.#d=WD.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,!(oO.isServer()||ZD(this.options.enabled,this.#t)===!1||!JD(this.#p)||this.#p===0)&&(this.#f=WD.setInterval(()=>{(this.options.refetchIntervalInBackground||HD.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(WD.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(WD.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&&gO(e,t),o=i&&vO(e,n,t,r);(a||o)&&(l={...l,...pO(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=iO(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=iO(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:yO(e,t),refetch:this.refetch,promise:this.#o,isEnabled:ZD(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=sO())},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),!eO(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){uO.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function hO(e,t){return ZD(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status===`error`&&ZD(t.retryOnMount,e)===!1)}function gO(e,t){return hO(e,t)||e.state.data!==void 0&&_O(e,t,t.refetchOnMount)}function _O(e,t,n){if(ZD(t.enabled,e)!==!1&&XD(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&yO(e,t)}return!1}function vO(e,t,n,r){return(e!==t||ZD(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&yO(e,n)}function yO(e,t){return ZD(t.enabled,e)!==!1&&e.isStaleByTime(XD(t.staleTime,e))}function bO(e,t){return!eO(e.getCurrentResult(),t)}var xO=v.createContext(void 0),SO=e=>{let t=v.useContext(xO);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},CO=v.createContext(!1),wO=()=>v.useContext(CO);CO.Provider;function TO(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var EO=v.createContext(TO()),DO=()=>v.useContext(EO),OO=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?aO(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},kO=e=>{v.useEffect(()=>{e.clearReset()},[e])},AO=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||aO(n,[e.error,r])),jO=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))}},MO=(e,t)=>e.isLoading&&e.isFetching&&!t,NO=(e,t)=>e?.suspense&&t.isPending,PO=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function FO(e,t,n){let r=wO(),i=DO(),a=SO(n),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let s=a.getQueryCache().get(o.queryHash);o._optimisticResults=r?`isRestoring`:`optimistic`,jO(o),OO(o,i,s),kO(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(uO.batchCalls(e)):qD;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),v.useEffect(()=>{l.setOptions(o)},[o,l]),NO(o,u))throw PO(o,l,i);if(AO({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&&!oO.isServer()&&MO(u,r)&&(c?PO(o,l,i):s?.promise)?.catch(qD).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?u:l.trackResult(u)}function IO(e,t){return FO(e,mO,t)}var LO=`pibo.chat.composerHistory`,RO=100;function zO(){try{let e=localStorage.getItem(LO);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`&&e.trim().length>0).slice(-RO):[]}catch{return[]}}function BO(e){let t=e.trim();if(!t)return;let n=zO();if(n.at(-1)!==t)try{localStorage.setItem(LO,JSON.stringify([...n,t].slice(-RO)))}catch{}}function VO(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 HO(e,t){return e.length>t?`${e.slice(0,Math.max(0,t-1))}…`:e}function UO({sessionId:e,disabled:t=!1,commands:n,skills:r,value:i,focusSignal:a,selectedWebAnnotations:o,selectedUploadAttachments:s,onValueChange:c,onCommand:l,onDetachWebAnnotation:u,onClearWebAnnotations:d,onAttachUploadedFiles:f,onDetachUploadAttachment:p,onClearUploadAttachments:m,onSend:h}){let g=(0,v.useRef)(null),_=(0,v.useRef)(null),y=(0,v.useRef)(null),b=(0,v.useRef)(null),x=(0,v.useRef)(null),S=(0,v.useRef)(null),C=(0,v.useRef)(null),[w,T]=(0,v.useState)(0),[E,D]=(0,v.useState)(0),[O,k]=(0,v.useState)(0),[A,ee]=(0,v.useState)([]),[te,j]=(0,v.useState)(!1),[M,ne]=(0,v.useState)(null),[N,P]=(0,v.useState)(null),re=(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]),ie=i.trim().startsWith(`/`)?i.trim().split(/\s+/)[0]:null,ae=re?WO(re.startPos,i.slice(re.startPos,O)):null,oe=ie?GO(ie):null,se=(0,v.useMemo)(()=>re?r.filter(e=>e.name.toLowerCase().startsWith(re.query)):[],[re,r]),le=(0,v.useMemo)(()=>ie?n.filter(e=>e.slash.startsWith(ie)):[],[ie,n]),F=ae&&A.includes(ae)?[]:se,ue=oe&&A.includes(oe)?[]:le,de=(0,v.useCallback)(e=>{e&&ee(t=>t.includes(e)?t:[...t,e])},[]),fe=(0,v.useCallback)(()=>{let e=[se.length?ae:null,le.length?oe:null].filter(e=>!!e);e.length&&ee(t=>{let n=new Set(t);for(let t of e)n.add(t);return n.size===t.length?t:[...n]})},[oe,le.length,se.length,ae]);(0,v.useEffect)(()=>{let e=[ae,oe].filter(e=>!!e);ee(t=>t.filter(t=>e.includes(t)))},[oe,ae]),(0,v.useEffect)(()=>{!ue.length||w<ue.length||T(0)},[w,ue.length]),(0,v.useEffect)(()=>{!F.length||E<F.length||D(0)},[E,F.length]),(0,v.useEffect)(()=>{let e=requestAnimationFrame(()=>x.current?.scrollIntoView({block:`nearest`}));return()=>cancelAnimationFrame(e)},[w,ue.length]),(0,v.useEffect)(()=>{let e=requestAnimationFrame(()=>S.current?.scrollIntoView({block:`nearest`}));return()=>cancelAnimationFrame(e)},[E,F.length]),(0,v.useEffect)(()=>{C.current=null},[e]),(0,v.useEffect)(()=>{if(!N)return;let e=requestAnimationFrame(()=>b.current?.focus());return()=>{cancelAnimationFrame(e),URL.revokeObjectURL(N.previewUrl)}},[N]),(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(!ue.length&&!F.length)return;let e=e=>{let t=e.target;t instanceof Node&&(g.current?.contains(t)||fe())};return document.addEventListener(`pointerdown`,e,!0),()=>document.removeEventListener(`pointerdown`,e,!0)},[fe,ue.length,F.length]),(0,v.useLayoutEffect)(()=>{QO(_.current)},[i]);let pe=e=>{if(!re||!_.current)return;let t=i.slice(0,re.startPos),n=i.slice(re.endPos);c(t+`$`+e+n),de(WO(re.startPos,`$${e}`));let r=re.startPos+1+e.length;k(r),requestAnimationFrame(()=>{_.current?.setSelectionRange(r,r),k(r)})},me=e=>{c(e),requestAnimationFrame(()=>{let e=_.current;if(!e)return;let t=e.value.length;e.setSelectionRange(t,t),k(t)})},he=e=>{let t=C.current;if(!t){if(e===`next`||i!==``)return!1;let t=zO();if(!t.length)return!1;let n=e===`previous`?t.length-1:0;return C.current={entries:t,index:n,draft:i},me(t[n]),!0}if(e===`previous`){let e=Math.max(0,t.index-1);return C.current={...t,index:e},me(t.entries[e]),!0}let n=t.index+1;return n>=t.entries.length?(C.current=null,me(t.draft),!0):(C.current={...t,index:n},me(t.entries[n]),!0)},ge=()=>{t||te||y.current?.click()},_e=()=>{P(null)},ve=e=>{if(t||te)return;let n=KO(e.clipboardData);if(!n.length)return;e.preventDefault(),fe(),ne(null);let r=n[0];P(e=>(e&&URL.revokeObjectURL(e.previewUrl),{file:r,previewUrl:URL.createObjectURL(r)}))},ye=async()=>{if(!N||te)return;let e=N.file;P(null),await be([e])},be=async e=>{if(e.length){j(!0),ne({message:`Uploading ${e.length} file${e.length===1?``:`s`}...`,error:!1});try{f((await ce(e)).files),ne(null)}catch(e){ne({message:e instanceof Error?e.message:String(e),error:!0})}finally{j(!1)}}},I=async()=>{if(t)return;let e=i.trim();if(e){if(F.length){pe(F[Math.min(E,F.length-1)].name);return}if(ue.length&&!n.some(t=>t.slash===e.split(/\s+/)[0])){let e=ue[Math.min(w,ue.length-1)].slash;c(e),de(GO(e));return}if(C.current=null,BO(e),c(``),e.split(/\s+/)[0]===`/upload`){ge();return}e.startsWith(`/`)&&await l(e)||await h(e)}};return(0,L.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,L.jsx)(`input`,{ref:y,type:`file`,multiple:!0,className:`hidden`,onChange:e=>{let t=Array.from(e.target.files??[]);e.target.value=``,be(t)}}),M?(0,L.jsxs)(`div`,{className:`mb-2 flex items-center gap-2 rounded-sm border px-3 py-2 text-xs ${M.error?`border-red-900 bg-red-950/40 text-red-200`:M.copyText?`border-green-900/60 bg-green-950/30 text-green-300`:`border-slate-700 bg-[#0e1116] text-slate-300`}`,children:[(0,L.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:M.message}),M.copyText?(0,L.jsx)(`button`,{type:`button`,onClick:()=>void VO(M.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,L.jsx)(Ue,{size:13})}):null,(0,L.jsx)(`button`,{type:`button`,onClick:()=>ne(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,L.jsx)(xt,{size:13})})]}):null,N?(0,L.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`&&_e()},children:(0,L.jsxs)(`div`,{className:`w-full max-w-md rounded-sm border border-slate-700 bg-[#151f24] shadow-2xl`,children:[(0,L.jsxs)(`div`,{className:`flex items-start justify-between gap-3 border-b border-slate-800 px-4 py-3`,children:[(0,L.jsxs)(`div`,{children:[(0,L.jsx)(`div`,{className:`text-sm font-semibold text-slate-100`,children:`Pasted image detected`}),(0,L.jsx)(`div`,{className:`mt-1 text-xs text-slate-400`,children:`Upload this clipboard image to ~/.pibo/uploads?`})]}),(0,L.jsx)(`button`,{type:`button`,onClick:_e,className:`rounded-sm p-1 text-slate-500 hover:bg-slate-800 hover:text-slate-200`,"aria-label":`Cancel pasted image upload`,children:(0,L.jsx)(xt,{size:14})})]}),(0,L.jsxs)(`div`,{className:`space-y-3 px-4 py-4`,children:[(0,L.jsx)(`img`,{src:N.previewUrl,alt:`Pasted clipboard image preview`,className:`max-h-64 w-full rounded-sm border border-slate-800 bg-[#0e1116] object-contain`}),(0,L.jsxs)(`div`,{className:`flex items-center justify-between gap-3 text-xs text-slate-400`,children:[(0,L.jsx)(`span`,{className:`min-w-0 truncate font-mono`,children:N.file.name}),(0,L.jsx)(`span`,{className:`shrink-0 font-mono`,children:ZO(N.file.size)})]})]}),(0,L.jsxs)(`div`,{className:`flex justify-end gap-2 border-t border-slate-800 px-4 py-3`,children:[(0,L.jsx)(`button`,{type:`button`,onClick:_e,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,L.jsx)(`button`,{ref:b,type:`button`,onClick:()=>void ye(),disabled:te,className:`h-8 rounded-sm bg-[#11a4d4] px-3 text-xs font-medium text-white disabled:opacity-50`,children:`Upload image`})]})]})}):null,F.length?(0,L.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:F.map((e,t)=>(0,L.jsxs)(`button`,{ref:t===E?S:null,type:`button`,onClick:()=>pe(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,L.jsxs)(`span`,{className:`font-mono text-emerald-400`,children:[`$`,e.name]}),(0,L.jsx)(`span`,{className:`text-xs text-slate-400`,children:e.description??e.path??``})]},e.name))}):null,s.length?(0,L.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,L.jsxs)(`div`,{className:`mb-1.5 flex items-center justify-between gap-2`,children:[(0,L.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Attached uploads`}),(0,L.jsx)(`button`,{type:`button`,onClick:m,className:`text-[11px] text-slate-500 hover:text-[#11a4d4]`,children:`Clear`})]}),(0,L.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:s.map(e=>(0,L.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,L.jsx)(`span`,{className:`min-w-0 truncate`,children:HO(e.name||e.path,100)}),(0,L.jsx)(`button`,{type:`button`,onClick:()=>void VO(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,L.jsx)(Ue,{size:11})}),(0,L.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,L.jsx)(xt,{size:11})})]},e.id))})]}):null,o.length?(0,L.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,L.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,L.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Attached web annotations`}),(0,L.jsx)(`button`,{type:`button`,onClick:d,className:`text-[11px] text-slate-500 hover:text-[#11a4d4]`,children:`Clear`})]}),(0,L.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:o.map(e=>(0,L.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,L.jsx)(`span`,{className:`min-w-0 truncate`,children:HO(e.primaryTarget||e.label||e.note||e.id,100)}),(0,L.jsx)(xt,{size:11,className:`shrink-0 text-[#11a4d4]`})]},e.id))})]}):null,ue.length?(0,L.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:ue.map((e,t)=>(0,L.jsxs)(`button`,{ref:t===w?x:null,type:`button`,onClick:()=>{c(e.slash),de(GO(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,L.jsx)(`span`,{className:`font-mono text-[#11a4d4]`,children:e.slash}),(0,L.jsx)(`span`,{className:`text-xs text-slate-400`,children:e.description})]},e.slash))}):null,(0,L.jsxs)(`div`,{className:`grid grid-cols-[1fr_auto] items-end gap-2`,children:[(0,L.jsx)(`textarea`,{id:`message-composer-input`,ref:_,"data-pibo-debug":`composer-input`,"data-pibo-session-id":e??void 0,"data-pibo-state":t?`disabled`:i?`non-empty`:`empty`,rows:1,value:i,disabled:t,onChange:e=>{C.current=null,c(e.target.value),k(e.target.selectionStart)},onKeyDown:e=>{if(e.key===`Escape`&&(F.length||ue.length)){e.preventDefault(),e.stopPropagation(),fe();return}if(F.length&&(e.key===`ArrowDown`||e.key===`ArrowUp`)){e.preventDefault(),D(t=>e.key===`ArrowDown`?(t+1)%F.length:(t-1+F.length)%F.length);return}if(ue.length&&(e.key===`ArrowDown`||e.key===`ArrowUp`)){e.preventDefault(),T(t=>e.key===`ArrowDown`?(t+1)%ue.length:(t-1+ue.length)%ue.length);return}if((e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&he(e.key===`ArrowUp`?`previous`:`next`)){e.preventDefault();return}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),I())},onPaste:ve,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,L.jsx)(`button`,{type:`button`,disabled:t||te,onClick:()=>void I(),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,L.jsx)(ht,{size:16})})]})]})}function WO(e,t){return`skill:${e}:${t}`}function GO(e){return`command:${e}`}function KO(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(qO)}function qO(e){return e.name&&e.name!==`image.png`?e:new File([e],JO(e.type),{type:e.type||`image/png`,lastModified:Date.now()})}function JO(e){let t=YO(e),n=new Date;return`screenshot-${[n.getFullYear(),XO(n.getMonth()+1),XO(n.getDate()),`-`,XO(n.getHours()),XO(n.getMinutes()),XO(n.getSeconds())].join(``)}${t}`}function YO(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 XO(e){return String(e).padStart(2,`0`)}function ZO(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KiB`:`${(e/(1024*1024)).toFixed(1)} MiB`}function QO(e){if(!e)return;if(e.value&&!e.value.includes(`
|
|
41
|
+
`)&&e.value.length<80){e.style.height=``,e.style.overflowY=`hidden`;return}let t=window.getComputedStyle(e),n=$O(t.lineHeight,20),r=$O(t.borderTopWidth)+$O(t.borderBottomWidth),i=n*5+$O(t.paddingTop)+$O(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 $O(e,t=0){let n=Number.parseFloat(e);return Number.isFinite(n)?n:t}var ek=`pibo.chat.webAnnotations.cdpUrl`,tk=`pibo.chat.webAnnotations.selected`,nk=`${tk}.`,rk=`pibo.chat.webAnnotations.overlay.`,ik=`pibo.chat.webAnnotations.panelCollapsed`,ak=`pibo.chat.shortcuts.webAnnotationsToggle`,ok=`Alt+Shift+A`;function sk(){try{return localStorage.getItem(ek)??``}catch{return``}}function ck(e){try{e.trim()?localStorage.setItem(ek,e.trim()):localStorage.removeItem(ek)}catch{}}function lk(){try{return localStorage.getItem(ak)||`Alt+Shift+A`}catch{return ok}}function uk(e){try{return fk(localStorage.getItem(dk(e)))}catch{return null}}function dk(e){return rk+e}function fk(e){if(!e)return null;try{return pk(JSON.parse(e))}catch{return null}}function pk(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 mk(e){try{let t=gk(localStorage.getItem(tk));if(t.length||!e)return t;let n=nk+e,r=gk(localStorage.getItem(n));return r.length&&(localStorage.setItem(tk,JSON.stringify(r)),localStorage.removeItem(n)),r}catch{return[]}}function hk(e,t){try{let n=[...new Set(t.filter(e=>e.trim()))].slice(0,5);n.length?localStorage.setItem(tk,JSON.stringify(n)):localStorage.removeItem(tk),e&&localStorage.removeItem(nk+e)}catch{}}function gk(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 _k(){try{return localStorage.getItem(ik)===`true`}catch{return!1}}function vk(e){try{localStorage.setItem(ik,String(e))}catch{}}var yk=`web-annotations-dialog`,bk=`web-annotations-session-panel-details`;function xk({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,L.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,L.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,L.jsx)(`div`,{className:`min-w-0`,children:(0,L.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,L.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Web annotations`}),(0,L.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,L.jsxs)(`span`,{className:`rounded-sm border border-[#11a4d4]/50 px-1.5 py-0.5 text-[10px] text-[#11a4d4]`,children:[n.length,` attached`]}):null]})}),(0,L.jsxs)(`div`,{className:`ml-auto flex shrink-0 items-center gap-1`,children:[(0,L.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,L.jsx)(dt,{size:12,className:r?`animate-spin`:void 0})}),(0,L.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,L.jsx)(_t,{size:12})}),(0,L.jsx)(`button`,{type:`button`,onClick:l,title:a?`Expand annotations panel`:`Collapse annotations panel`,"aria-label":`Web annotations details`,"aria-expanded":!a,"aria-controls":bk,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,L.jsx)(Ie,{size:12}):(0,L.jsx)(Pe,{size:12})}),(0,L.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,L.jsx)(xt,{size:12})})]})]}),(0,L.jsxs)(`div`,{id:bk,hidden:a,children:[(0,L.jsx)(`div`,{className:`text-[11px] text-slate-500`,children:`Global annotation list. Selected attachments follow you when switching sessions.`}),i?(0,L.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:Mk(i,220)}):r&&!t.length?(0,L.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,L.jsx)(`div`,{className:`mt-2 grid max-h-[min(40svh,18rem)] grid-cols-1 gap-2 overflow-y-auto pr-1 sm:max-h-56 sm:grid-cols-[repeat(auto-fill,minmax(16rem,1fr))]`,"data-pibo-debug":`web-annotations-list`,children:t.map((e,t)=>{let r=n.includes(e.id),i=Mk(e.primaryTarget||e.label||e.selector||e.targetKind||`target`,64),a=`${t+1}: ${i}`;return(0,L.jsxs)(`div`,{"data-pibo-debug":`web-annotation-chip`,"data-web-annotation-id":e.id,"data-web-annotation-session-id":e.piboSessionId,"data-web-annotation-selected":r?`true`:`false`,className:`min-w-0 rounded-sm border px-3 py-2 text-xs ${r?`border-[#11a4d4] bg-[#11a4d4]/10`:`border-slate-800 bg-[#0e1116]`}`,children:[(0,L.jsxs)(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[(0,L.jsxs)(`span`,{className:`min-w-0 truncate font-mono text-[11px] text-slate-500`,children:[e.status,` · `,e.targetKind]}),(0,L.jsxs)(`button`,{type:`button`,onClick:()=>s(e.id),"aria-pressed":r,"aria-label":`Include web annotation ${a}`,title:`${r?`Detach`:`Attach`} web annotation ${a}`,className:`inline-flex h-8 shrink-0 items-center gap-1 rounded-sm border px-2 text-[11px] sm:h-6 sm:px-1.5 ${r?`border-[#11a4d4] text-[#11a4d4]`:`border-slate-700 text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:[r?(0,L.jsx)(xt,{size:11}):(0,L.jsx)(ut,{size:11}),` `,r?`Detach`:`Attach`]})]}),(0,L.jsx)(`div`,{className:`truncate text-slate-200`,title:e.primaryTarget||e.label||e.selector||e.id,children:Mk(e.primaryTarget||e.label||e.selector||e.id,120)}),e.piboContext?(0,L.jsx)(`div`,{className:`truncate font-mono text-[11px] text-[#11a4d4]`,title:e.piboContext,children:Mk(e.piboContext,140)}):null,(0,L.jsx)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:e.url,children:kk(e.url)}),(0,L.jsxs)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:jk(e),children:[`Source `,Ak(e)]}),(0,L.jsx)(`div`,{className:`mt-1 line-clamp-2 text-slate-400`,title:e.note,children:Mk(e.note,180)}),(0,L.jsx)(`div`,{className:`mt-1 text-[11px] text-slate-600`,children:Nk(e.createdAt)})]},e.id)})}):(0,L.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 Sk({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)(()=>sk()),[p,m]=(0,v.useState)([]),[h,g]=(0,v.useState)(`idle`),[_,y]=(0,v.useState)(!1),[b,x]=(0,v.useState)(null),S=(0,v.useRef)(null),C=(0,v.useRef)(null),w=()=>{c(!1),S.current?.focus()};(0,v.useEffect)(()=>{n&&c(!1)},[n]),(0,v.useEffect)(()=>{if(!s||n)return;C.current?.focus();let e=e=>{e.key===`Escape`&&(e.preventDefault(),w())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[s,n]),(0,v.useEffect)(()=>{ck(d)},[d]);let T=async()=>{if(e){g(`loading`),x(null);try{m((await Ux(d)).targets.filter(e=>e.type===`page`||e.attachable)),g(`loaded`)}catch(e){let t=Dk(e,`CDP unavailable`);m([]),g(`error`),x({kind:`error`,message:t}),o(t)}}},E=async n=>{if(!e)throw Error(`No active session context`);return Gx(n.binding.id,wk({piboSessionId:e,piboRoomId:t,cdpUrl:d,annotationShortcut:lk()}))},D=async()=>{if(!(!e||_)){i(),y(!0),x({kind:`info`,message:`Injecting annotation overlay into this Pibo page…`});try{let n=await Wx({piboSessionId:e,piboRoomId:t,url:window.location.href,title:document.title,sameOrigin:!0,annotationShortcut:lk()});if(!n.overlay)throw Error(`Overlay config missing from same-origin binding response`);await Ek(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=Dk(e,`Current-page annotation failed`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}}},O=async()=>{if(!e||_)return;i();let n=l.trim();if(!n){x({kind:`error`,message:`URL is required`});return}if(Tk(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 Wx(wk({piboSessionId:e,piboRoomId:t,url:n,cdpUrl:d})),i=await E(r);x({kind:`success`,message:`Annotation overlay injected for ${Ok(i.target??r.target,i.binding.url)}`}),u(``),o(null)}catch(e){let t=Dk(e,`Annotation failed`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}},k=async n=>{if(!(!e||_)){i(),y(!0),x({kind:`info`,message:`Binding selected target and injecting overlay…`});try{let r=await E(await Wx(wk({piboSessionId:e,piboRoomId:t,targetId:n.id,cdpUrl:d})));x({kind:`success`,message:`Annotation overlay injected for ${Ok(r.target??n,r.binding.url)}`}),o(null)}catch(e){let t=Dk(e,n.attachable?`Target annotation failed`:`Target not attachable`);x({kind:`error`,message:t}),o(t)}finally{y(!1)}}};return(0,L.jsxs)(`div`,{className:`relative`,"data-pibo-debug":`web-annotations-entry`,"data-pibo-session-id":e??void 0,children:[(0,L.jsx)(Ck,{buttonRef:S,onClick:()=>{n||(c(e=>!e),r||i())},title:n?`Select an active session to annotate a web page`:r?`Web Annotations`:`Show Web Annotations`,ariaLabel:`Web Annotations`,ariaHaspopup:`dialog`,ariaExpanded:s,ariaControls:yk,disabled:n,active:s||r,children:(0,L.jsx)(Ee,{size:14})}),s&&!n?(0,L.jsxs)(`div`,{id:yk,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,L.jsxs)(`div`,{className:`mb-2 flex items-start justify-between gap-3`,children:[(0,L.jsxs)(`div`,{children:[(0,L.jsx)(`div`,{className:`text-xs font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Web Annotations`}),(0,L.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,L.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,L.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,L.jsx)(pt,{size:14})}),(0,L.jsx)(`button`,{type:`button`,onClick:w,className:`rounded-sm p-1 text-slate-500 hover:bg-slate-800 hover:text-slate-200`,"aria-label":`Close Web Annotations panel`,children:(0,L.jsx)(xt,{size:14})})]})]}),(0,L.jsx)(`button`,{ref:C,type:`button`,onClick:()=>void D(),disabled:_,className:`mb-3 h-10 w-full rounded-sm bg-emerald-600 px-3 text-xs font-medium text-white hover:bg-emerald-500 disabled:opacity-50 sm:h-9`,"data-pibo-debug":`web-annotations-current-page`,children:`Annotate this Pibo page`}),(0,L.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,L.jsxs)(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-[1fr_auto]`,children:[(0,L.jsx)(`input`,{id:`web-annotation-url`,value:l,onChange:e=>u(e.target.value),onKeyDown:e=>{e.key===`Enter`&&O()},placeholder:`http://localhost:5173`,disabled:_,className:`h-10 min-w-0 rounded-sm border border-slate-700 bg-[#151f24] px-2 text-base text-slate-100 outline-none focus:border-[#11a4d4] disabled:opacity-60 sm:h-9 sm:text-xs`}),(0,L.jsx)(`button`,{type:`button`,onClick:()=>void O(),disabled:_||!l.trim(),className:`h-10 rounded-sm bg-[#11a4d4] px-3 text-xs font-medium text-white disabled:opacity-50 sm:h-9`,children:`Annotate`})]}),(0,L.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,L.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,L.jsxs)(`div`,{className:`mt-3 flex items-center justify-between gap-2`,children:[(0,L.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-slate-500`,children:`Existing targets`}),(0,L.jsxs)(`button`,{type:`button`,onClick:()=>void T(),disabled:_||h===`loading`,className:`inline-flex h-7 items-center gap-1 rounded-sm border border-slate-700 px-2 text-[11px] text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:opacity-50`,children:[(0,L.jsx)(dt,{size:12,className:h===`loading`?`animate-spin`:void 0}),` Refresh`]})]}),(0,L.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,L.jsx)(`div`,{className:`px-3 py-3 text-xs text-slate-500`,children:`Refresh to list reachable browser targets.`}):null,h===`loading`?(0,L.jsx)(`div`,{className:`px-3 py-3 text-xs text-slate-400`,children:`Loading targets…`}):null,h===`loaded`&&!p.length?(0,L.jsx)(`div`,{className:`px-3 py-3 text-xs text-slate-500`,children:`No attachable browser targets found.`}):null,p.map(e=>(0,L.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,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsx)(`div`,{className:`truncate text-xs text-slate-200`,title:e.title||e.url,children:Mk(e.title||`Untitled target`,120)}),(0,L.jsx)(`div`,{className:`truncate font-mono text-[11px] text-slate-500`,title:e.url,children:Mk(e.url||e.id,160)})]}),(0,L.jsx)(`button`,{type:`button`,onClick:()=>void k(e),disabled:_||!e.attachable,title:e.attachable?`Attach selected target`:`Target is not attachable`,className:`h-9 rounded-sm border border-slate-700 px-2 text-[11px] text-slate-300 hover:border-[#11a4d4] hover:text-[#11a4d4] disabled:opacity-40 sm:h-8`,children:`Attach`})]},e.id))]}),b?(0,L.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 Ck({buttonRef:e,title:t,ariaLabel:n,ariaHaspopup:r,ariaExpanded:i,ariaControls:a,disabled:o,active:s,onClick:c,children:l}){return(0,L.jsx)(`button`,{ref:e,type:`button`,onClick:c,disabled:o,title:t,"aria-label":n,"aria-haspopup":r,"aria-expanded":i,"aria-controls":a,className:`h-8 w-8 inline-flex items-center justify-center border rounded-sm transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${s?`border-[#11a4d4] bg-[#11a4d4]/10 text-[#11a4d4]`:`border-slate-700 text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:l})}function wk(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e&&e.trim()))}function Tk(e){try{let t=new URL(e);return t.port===`56663`||t.pathname.startsWith(`/json/`)}catch{return!1}}function Ek(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 Dk(e,t){let n=Pk(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 Ok(e,t){let n=e?.url||t||e?.title||`target`;return kk(e?.title||n)}function kk(e){try{let t=new URL(e);return`${t.host}${t.pathname===`/`?``:t.pathname}`}catch{return Mk(e,80)}}function Ak(e){return e.piboRoomId?`${Mk(e.piboSessionId,24)} · room ${Mk(e.piboRoomId,18)}`:Mk(e.piboSessionId,44)}function jk(e){return e.piboRoomId?`Session ${e.piboSessionId} in room ${e.piboRoomId}`:`Session ${e.piboSessionId}`}function Mk(e,t){return e.length>t?`${e.slice(0,Math.max(0,t-1))}…`:e}function Nk(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{dateStyle:`short`,timeStyle:`short`})}function Pk(e){return e instanceof Error?e.message:String(e)}function Fk(e){return!!e.workflowRunId||e.state===`workflow`||e.workflowId!==`simple-chat`}function Ik(e,t){return{workflowId:e.workflowId,state:Rk(e,t),...e.workflowRunId?{workflowRunId:e.workflowRunId}:{}}}function Lk({summary:e}){return(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(`span`,{className:`text-slate-600`,children:`·`}),(0,L.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,L.jsxs)(`span`,{className:zk(e.state),children:[`state `,e.state]}),e.workflowRunId?(0,L.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 `,Bk(e.workflowRunId)]}):null]})}function Rk(e,t){return e.archived?`archived`:e.state&&e.state!==`workflow`?e.state.replace(/_/g,` `):t===`running`?`running`:t===`error`?`failed`:e.state?e.state.replace(/_/g,` `):e.workflowRunId?`workflow`:e.kind}function zk(e,t=!1){let n=e.toLowerCase(),r=`shrink-0 rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide`;return t?`${r} border-slate-700 text-slate-500`:n.includes(`failed`)||n.includes(`error`)?`${r} border-red-500/40 text-red-300 bg-red-500/10`:n.includes(`waiting`)?`${r} border-amber-500/40 text-amber-300 bg-amber-500/10`:n.includes(`complete`)||n.includes(`done`)?`${r} border-emerald-500/40 text-emerald-300 bg-emerald-500/10`:`${r} border-[#11a4d4]/40 text-[#11a4d4] bg-[#11a4d4]/10`}function Bk(e){return e.length>18?`${e.slice(0,10)}…${e.slice(-6)}`:e}function Vk({title:e,roomLabel:t,headerPiboSessionId:n,piboSessionId:r,piboRoomId:i,webAnnotationsDisabled:a,webAnnotationsPanelRendered:o,workflowHeader:s,sessionViewId:c,sessionViews:l,currentSessionView:u,allowedSessionViewIds:d,extraViewTabs:f,activeViewId:p,terminalFullscreenAvailable:m,onEnterTerminalFullscreen:h,onOpenSessionWindow:g,showRawEvents:_,showThinking:y,expandThinking:b,onShowWebAnnotationsPanel:x,onHideWebAnnotationsPanel:S,onSelectSessionView:C,onToggleRawEvents:w,onToggleThinking:T,onToggleExpandThinking:E,onError:D}){let[O,k]=(0,v.useState)(null),A=(0,v.useRef)(void 0),ee=O===n,te=p??c,j=(0,v.useMemo)(()=>d?new Set(d):null,[d]);(0,v.useEffect)(()=>()=>{A.current&&window.clearTimeout(A.current)},[]);let M=()=>{n&&(VO(n).catch(()=>void 0),k(n),A.current&&window.clearTimeout(A.current),A.current=window.setTimeout(()=>k(null),900))};return(0,L.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,L.jsxs)(`div`,{className:`min-w-0`,children:[(0,L.jsx)(`h1`,{className:`text-base font-semibold truncate`,children:e}),(0,L.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 font-mono text-[11px] text-slate-500`,children:[(0,L.jsx)(`span`,{className:`truncate`,children:t}),n?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(`span`,{className:`text-slate-600`,children:`·`}),(0,L.jsx)(`button`,{type:`button`,onMouseDown:e=>e.preventDefault(),onClick:()=>void M(),title:ee?`Copied Pibo session ID`:`Copy Pibo session ID`,"aria-label":ee?`Copied Pibo session ID`:`Copy Pibo session ID`,className:`min-w-0 max-w-48 truncate rounded-sm px-1 font-mono underline-offset-2 transition-colors duration-150 focus:outline-none focus:ring-1 focus:ring-[#11a4d4] ${ee?`bg-emerald-500/15 text-emerald-300 ring-1 ring-emerald-400/50`:`text-slate-400 hover:text-[#11a4d4] hover:underline`}`,children:n})]}):null,s?(0,L.jsx)(Lk,{summary:s}):null]})]}),(0,L.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,L.jsx)(Sk,{piboSessionId:r,piboRoomId:i,disabled:a,panelVisible:o,onShowPanel:x,onHidePanel:S,onError:D}),g?(0,L.jsx)(`button`,{type:`button`,onClick:g,title:`Open selected session in new window`,"aria-label":`Open selected session in new window`,"data-pibo-debug":`open-session-window`,className:`h-8 w-8 inline-flex items-center justify-center border border-slate-700 rounded-sm text-slate-400 transition-colors hover:border-[#11a4d4] hover:text-[#11a4d4]`,children:(0,L.jsx)(ut,{size:15})}):null,(0,L.jsxs)(`div`,{role:`group`,"aria-label":`Session views`,className:`flex items-center rounded-sm border border-slate-700 bg-[#0e1116] p-0.5`,children:[l.map(e=>{let t=!!(j&&!j.has(e.id));return(0,L.jsx)(`button`,{type:`button`,onClick:()=>{t||C(e.id)},disabled:t,title:t?`Project session routing uses the ${u.label} view for this session kind.`:e.description??e.label,"aria-label":t?`${e.label} view unavailable for this Project session kind`:`Switch to ${e.label} view`,"aria-pressed":te===e.id,className:`min-w-20 px-2.5 py-1 text-[11px] font-bold tracking-wide max-[980px]:min-w-0 max-[980px]:px-1.5 disabled:cursor-not-allowed disabled:text-slate-600 ${te===e.id?`bg-[#11a4d4]/10 text-[#11a4d4]`:`text-slate-400 hover:text-[#11a4d4] disabled:hover:text-slate-600`}`,children:e.label},e.id)}),f?.map(e=>{let t=e.active??te===e.id;return(0,L.jsx)(`button`,{type:`button`,onClick:()=>{e.disabled||e.onSelect()},disabled:e.disabled,title:e.description??e.label,"aria-label":e.disabled?`${e.label} view unavailable`:`Switch to ${e.label} view`,"aria-pressed":t,className:`min-w-20 px-2.5 py-1 text-[11px] font-bold tracking-wide max-[980px]:min-w-0 max-[980px]:px-1.5 disabled:cursor-not-allowed disabled:text-slate-600 ${t?`bg-[#11a4d4]/10 text-[#11a4d4]`:`text-slate-400 hover:text-[#11a4d4] disabled:hover:text-slate-600`}`,children:e.label},e.id)})]}),m&&h?(0,L.jsx)(`button`,{type:`button`,onClick:h,title:`Enter Terminal fullscreen`,"aria-label":`Enter Terminal fullscreen`,"data-pibo-debug":`enter-terminal-fullscreen`,className:`h-8 w-8 inline-flex items-center justify-center border border-slate-700 rounded-sm text-slate-400 transition-colors hover:border-[#11a4d4] hover:text-[#11a4d4]`,children:(0,L.jsx)(st,{size:14})}):null,(0,L.jsx)(Hk,{onClick:w,title:_?`Hide Raw Events`:`Show Raw Events`,ariaLabel:`Raw Events`,active:_,children:(0,L.jsx)(ke,{size:14})}),(0,L.jsx)(Hk,{onClick:T,title:y?`Hide Thinking`:`Show Thinking`,ariaLabel:`Thinking`,active:y,children:y?(0,L.jsx)(Oe,{size:14}):(0,L.jsx)(qe,{size:14})}),y?(0,L.jsx)(Hk,{onClick:E,title:b?`Collapse Thinking`:`Expand Thinking`,ariaLabel:`Thinking expansion`,active:b,children:b?(0,L.jsx)(Pe,{size:14}):(0,L.jsx)(Ie,{size:14})}):null]})]})}function Hk({title:e,ariaLabel:t,active:n,onClick:r,children:i}){return(0,L.jsx)(`button`,{type:`button`,onClick:r,title:e,"aria-label":t,"aria-pressed":n,className:`h-8 w-8 inline-flex items-center justify-center border rounded-sm transition-colors ${n?`border-[#11a4d4] bg-[#11a4d4]/10 text-[#11a4d4]`:`border-slate-700 text-slate-400 hover:border-[#11a4d4] hover:text-[#11a4d4]`}`,children:i})}function Uk(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&Wk(e,n)){e.count+=1,e.createdAt=n.createdAt,e.payload={...qk(e.payload)?e.payload:{},text:`${Gk(e.payload)}${Gk(n.payload)}`};continue}t.push({...n,count:1})}return t}function Wk(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=qk(e.payload)?e.payload:{},r=qk(t.payload)?t.payload:{};return Kk(n)===Kk(r)}function Gk(e){return qk(e)?typeof e.text==`string`?e.text:typeof e.delta==`string`?e.delta:``:``}function Kk(e){return e.eventId??e.messageId}function qk(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Jk({traceView:e,eventLimit:t,isFetching:n,visible:r,onLoadOlder:i}){let a=(0,v.useMemo)(()=>r?Uk(e?.rawEvents??[]):[],[e?.rawEvents,r]);return r?(0,L.jsxs)(`aside`,{className:`min-h-0 overflow-auto bg-[#0e1116] border-l border-slate-800 max-[980px]:hidden`,children:[(0,L.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,L.jsxs)(`div`,{className:`p-3 flex flex-col gap-2`,children:[e&&a.length>=t?(0,L.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,L.jsxs)(`div`,{className:`border-l-2 border-[#11a4d4] bg-[#151f24] p-2`,children:[(0,L.jsxs)(`div`,{className:`flex items-center justify-between gap-2 text-[#11a4d4] font-mono text-[11px] mb-1`,children:[(0,L.jsx)(`span`,{children:e.type}),e.count>1?(0,L.jsxs)(`span`,{className:`text-slate-500`,children:[`x`,e.count]}):null]}),(0,L.jsx)(fl,{value:e.payload,showControls:!1})]},e.id))]})]}):null}function Yk({title:e,onOpenSessionWindow:t,onExit:n}){return(0,L.jsxs)(`div`,{"data-pibo-debug":`terminal-fullscreen-top-bar`,className:`h-7 min-h-7 flex items-center border-b border-slate-600 bg-[#151f24]`,children:[(0,L.jsx)(`div`,{className:`min-w-0 flex-1 truncate text-base font-semibold leading-none`,children:e}),t?(0,L.jsx)(`button`,{type:`button`,onClick:t,title:`Open selected session in new window`,"aria-label":`Open selected session in new window`,"data-pibo-debug":`open-session-window`,className:`h-full w-7 shrink-0 inline-flex items-center justify-center text-slate-400 hover:bg-[#11a4d4]/10 hover:text-[#11a4d4]`,children:(0,L.jsx)(ut,{size:14})}):null,(0,L.jsx)(`button`,{type:`button`,onClick:n,title:`Show normal top bar`,"aria-label":`Exit Terminal fullscreen`,className:`h-full w-7 shrink-0 inline-flex items-center justify-center text-slate-400 hover:bg-[#11a4d4]/10 hover:text-[#11a4d4]`,children:(0,L.jsx)(lt,{size:14})})]})}function Xk({enabled:e,onFilesDropped:t,children:n,className:r,...i}){let a=(0,v.useRef)(0),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(0),u=c>0;(0,v.useEffect)(()=>{e||(a.current=0,s(!1))},[e]);let d=()=>{a.current=0,s(!1)},f=t=>Qk(t.dataTransfer)?(t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=e&&!u?`copy`:`none`,!0):!1,p=t=>{!f(t)||!e||u||(a.current+=1,s(!0))},m=e=>{f(e)},h=e=>{!f(e)||a.current===0||(a.current=Math.max(0,a.current-1),a.current===0&&s(!1))},g=async n=>{if(!f(n)||(d(),!e||u))return;let r=$k(n.dataTransfer);if(r.length){l(r.length);try{await t(r)}finally{l(0)}}},_=u?`uploading`:o?`drag-active`:`idle`;return(0,L.jsxs)(`main`,{...i,"data-pibo-file-drop-state":_,className:`relative ${r??``}`,onDragEnter:p,onDragOver:m,onDragLeave:h,onDragEnd:d,onDrop:g,children:[n,o||u?(0,L.jsx)(Zk,{uploadingFileCount:c}):null]})}function Zk({uploadingFileCount:e}){let t=e>0;return(0,L.jsx)(`div`,{"data-pibo-debug":`terminal-file-drop-overlay`,"data-pibo-state":t?`uploading`:`drag-active`,role:`status`,"aria-live":`polite`,className:`pointer-events-none absolute inset-0 z-40 grid place-items-center bg-[#071015]/90 p-6 backdrop-blur-[2px]`,children:(0,L.jsxs)(`div`,{className:`flex max-w-sm flex-col items-center rounded-sm border border-dashed border-[#11a4d4] bg-[#0e1116]/95 px-8 py-7 text-center shadow-2xl shadow-black/50`,children:[t?(0,L.jsx)(at,{size:36,className:`mb-3 animate-spin text-[#11a4d4]`,"aria-hidden":`true`}):(0,L.jsx)(yt,{size:36,className:`mb-3 text-[#11a4d4]`,"aria-hidden":`true`}),(0,L.jsx)(`span`,{className:`text-sm font-semibold text-slate-100`,children:t?`Uploading ${e} file${e===1?``:`s`}…`:`Drop files to upload`}),(0,L.jsx)(`span`,{className:`mt-1 text-xs leading-5 text-slate-400`,children:t?`Saving to ~/.pibo/uploads`:`Images and other files will be attached to your next message.`})]})})}function Qk(e){return Array.from(e.types).includes(`Files`)||Array.from(e.items).some(e=>e.kind===`file`)}function $k(e){return Array.from(e.files)}function eA({selectedPiboSessionId:e,selectedRoomId:t,fallbackRoomId:n,sessionViewId:r,loadingTrace:i,roomNavigationPending:a=!1,sessionNavigationPending:o=!1,traceError:s,showRawEvents:c,currentTraceView:l,rawEventLimit:u,tracePageFetching:d,onLoadMoreRawEvents:f,terminalFullscreen:p,terminalFileDropEnabled:m,onTerminalFilesDropped:h,onOpenSessionWindow:g,onExitTerminalFullscreen:_,headerProps:v,projectSessionCreatePanel:y,workflowStartPanel:b,projectModulePanel:x,currentSessionView:S,sessionViewProps:C,webAnnotationsPanelRendered:w,webAnnotationsPanelProps:T,composerProps:E}){let D=a||o&&!l||i;return(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(Xk,{enabled:m,onFilesDropped:h,"data-pibo-debug":`chat-shell`,"data-pibo-session-id":e??void 0,"data-pibo-room-id":t??n??void 0,"data-pibo-view-id":r,"data-pibo-state":a?`room-loading`:o?`session-loading`:i?`loading`:s?`error`:e?`ready`:`empty`,"data-pibo-terminal-fullscreen":p?`true`:`false`,className:`min-h-0 flex flex-col`,children:[p?(0,L.jsx)(Yk,{title:v.title,onOpenSessionWindow:g,onExit:_}):(0,L.jsx)(Vk,{...v}),!p&&y?(0,L.jsx)(`div`,{className:`border-b border-slate-800 bg-[#101d22] px-4 py-3`,children:y}):null,!p&&b?(0,L.jsx)(`div`,{className:`border-b border-slate-800 bg-[#101d22] px-4 py-3`,children:b}):null,!p&&x?x:D?(0,L.jsx)(tA,{label:a?`Loading room`:`Loading session`}):s&&!l?(0,L.jsx)(`div`,{className:`min-h-0 flex-1 p-4 text-sm text-red-200`,children:s}):S.render({...C,terminalFullscreen:p}),!p&&w?(0,L.jsx)(xk,{...T}):null,(0,L.jsx)(UO,{...E})]}),(0,L.jsx)(Jk,{traceView:l,eventLimit:u,isFetching:d,visible:c&&!p,onLoadOlder:f})]})}function tA({label:e}){return(0,L.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,L.jsx)(`div`,{className:`min-h-0 h-full overflow-hidden font-mono text-[12px] leading-[1.45]`,children:(0,L.jsxs)(`div`,{className:`px-4`,children:[(0,L.jsx)(`div`,{className:`group border-b border-[#141414] py-2`,children:(0,L.jsxs)(`div`,{className:`grid grid-cols-[1.9rem_minmax(0,1fr)] gap-2 leading-[1.45]`,children:[(0,L.jsx)(`span`,{className:`flex items-center text-[#38bdf8]`,children:(0,L.jsx)(`span`,{className:`h-1.5 w-1.5 rounded-full bg-[#38bdf8] animate-pulse`})}),(0,L.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,L.jsx)(`span`,{className:`font-semibold text-[#d4d4d4]`,children:e}),(0,L.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,L.jsx)(nA,{kind:e.kind,lineCount:e.lines},t))]})})})}function nA({kind:e,lineCount:t}){let n=e===`command`,r=e===`markdown`;return(0,L.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,L.jsxs)(`div`,{className:`grid grid-cols-[1.9rem_minmax(0,1fr)] gap-2 leading-[1.45]`,children:[(0,L.jsx)(`span`,{className:`flex items-center text-[#737373]`,children:i===0&&!r?(0,L.jsx)(`span`,{className:`h-1.5 w-1.5 rounded-full ${n?`bg-[#f59e0b]`:`bg-[#22c55e]`}`}):i>0&&!r?(0,L.jsx)(`span`,{className:`text-[10px]`,children:`L`}):null}),(0,L.jsx)(`span`,{className:`min-w-0 py-[3px]`,children:i===0?(0,L.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,L.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,L.jsx)(`span`,{className:`h-[13px] w-64 rounded-sm bg-[#262626]`})]}):(0,L.jsx)(`span`,{className:`block h-[10px] rounded-sm bg-[#262626] ${i===t-1?`w-[42%]`:i%2==0?`w-[72%]`:`w-[58%]`}`})})]},i))})}var rA=[`a[href]`,`button:not([disabled])`,`input:not([disabled])`,`select:not([disabled])`,`textarea:not([disabled])`,`[tabindex]:not([tabindex="-1"])`].join(`,`);function iA({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(rA)??l.current)?.focus()});return()=>{window.cancelAnimationFrame(t),e?.isConnected&&e.focus()}},[r]),(0,L.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(rA)??[]);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,L.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,L.jsxs)(`div`,{className:`flex items-start justify-between gap-3 border-b border-slate-800 px-4 py-3`,children:[(0,L.jsxs)(`div`,{children:[(0,L.jsx)(`h2`,{id:s,className:`text-sm font-bold uppercase tracking-wider text-slate-100`,children:e}),(0,L.jsx)(`p`,{id:c,className:`mt-1 text-xs text-slate-400`,children:t})]}),(0,L.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,L.jsx)(xt,{size:14})})]}),i]})})}function aA(e){let t=new Map;if(uA(e.nodes,t),!t.size)return e;let{nodes:n,changed:r}=dA(e.nodes,t);return r?{...e,nodes:n}:e}function oA(e){return e.some(lA)}function sA(e){let t=new Map;return mA(e,e=>{if(e.type!==`user.message`||!e.entryId)return;let n=hA(e),r=t.get(n);r?r.push(e.entryId):t.set(n,[e.entryId])}),t}function cA(e,t){if(!t.size)return;let n=new Map;mA(e,e=>{if(e.type!==`user.message`||!e.entryId)return;let t=hA(e),r=n.get(t)??new Set;r.add(e.entryId),n.set(t,r)});let r=new Map;mA(e,e=>{if(e.type!==`user.message`||e.entryId)return;let i=hA(e),a=t.get(i);if(!a?.length)return;let o=n.get(i)??new Set,s=r.get(i)??0;for(;s<a.length&&o.has(a[s]);)s+=1;let c=a[s];c&&(e.entryId=c,o.add(c),n.set(i,o),r.set(i,s+1))})}function lA(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 uA(e,t){for(let n of e){if(n.type===`user.message`&&!pA(n)&&!fA(n)){let e=hA(n);e&&t.set(e,(t.get(e)??0)+1)}uA(n.children,t)}}function dA(e,t){let n=!1,r=[];for(let i of e){if(pA(i)){let e=hA(i),r=e?t.get(e)??0:0;if(r>0){t.set(e,r-1),n=!0;continue}}let e=dA(i.children,t);n||=e.changed,r.push(e.changed?{...i,children:e.nodes}:i)}return{nodes:n?r:e,changed:n}}function fA(e){return[e.id,e.stableKey].some(e=>e?.startsWith(`event:message_queued:`)||e?.startsWith(`event:message_steered:`))}function pA(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 mA(e,t){for(let n of e)t(n),mA(n.children,t)}function hA(e){return typeof e.output==`string`?e.output:typeof e.summary==`string`?e.summary:``}function gA(e,t,n){return t&&e.set(t.piboSessionId,t),n?e.get(n)??null:null}function _A(e,t,n){t&&t.piboSessionId!==n.piboSessionId&&e.set(t.piboSessionId,t);let r=vA(t?.piboSessionId===n.piboSessionId?t:e.get(n.piboSessionId)??null,n);return r?e.set(n.piboSessionId,r):e.delete(n.piboSessionId),r}function vA(e,t){if(!e||e.piboSessionId!==t.piboSessionId)return e;let n=xA(t),r=yA(t.nodes),i=e.events.filter(e=>{let i=TA(e);if(i&&n.has(i))return!1;if(lA(e)){let t=r.get(e.payload.text)??0;if(t>0)return t===1?r.delete(e.payload.text):r.set(e.payload.text,t-1),!1}return!CA(t,e)});return i.length?{...e,events:i}:null}function yA(e){let t=new Map;for(let n of e){if(n.type===`user.message`&&n.source===`transcript`&&!bA(n)){let e=OA(n);e&&t.set(e,(t.get(e)??0)+1)}for(let[e,r]of yA(n.children))t.set(e,(t.get(e)??0)+r)}return t}function bA(e){return[e.id,e.stableKey].some(e=>e?.startsWith(`event:message_queued:`)||e?.startsWith(`event:message_steered:`))}function xA(e){let t=new Set;for(let n of e.rawEvents){let e=TA(n);e&&t.add(e)}return SA(e.nodes,t),t}function SA(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}`)}if(n.type===`assistant.message`){let e=EA(n,`assistant:`);e&&(t.add(`${n.piboSessionId}:assistant_delta:${e}`),(n.source===`transcript`||n.completedAt!==void 0)&&t.add(`${n.piboSessionId}:assistant_message:${e}`)),n.source===`transcript`&&n.eventId&&(t.add(`${n.piboSessionId}:message_started:${n.eventId}`),t.add(`${n.piboSessionId}:message_finished:${n.eventId}`))}if(n.type===`model.reasoning`){let e=EA(n,`reasoning:`);e&&(t.add(`${n.piboSessionId}:thinking_delta:${e}`),n.source===`transcript`&&(t.add(`${n.piboSessionId}:thinking_started:${e}`),t.add(`${n.piboSessionId}:thinking_finished:${e}`)))}if(n.toolCallId&&(n.type===`tool.call`||n.type===`tool.result`||n.type===`agent.delegation`)){let e=`tool:${n.toolCallId}`;t.add(`${n.piboSessionId}:tool_call:${e}`);let r=n.completedAt!==void 0||n.type===`tool.result`||n.status===`error`;(n.status===`running`||n.output!==void 0||r)&&t.add(`${n.piboSessionId}:tool_execution_started:${e}`),(n.output!==void 0&&!r||r)&&t.add(`${n.piboSessionId}:tool_execution_updated:${e}`),r&&t.add(`${n.piboSessionId}:tool_execution_finished:${e}`)}SA(n.children,t)}}function CA(e,t){let n=t.payload;if(!n||typeof n!=`object`||Array.isArray(n))return!1;let r=`source`in n?n.source:void 0,i=`text`in n?n.text:void 0;return r!==`service`||typeof i!=`string`||!rC(i)?!1:wA(e,t)}function wA(e,t){let n=t.eventSequence;if(n===void 0||e.firstEventSequence===void 0)return!1;let r=e.lastEventSequence??e.eventCount;return r!==void 0&&n>=e.firstEventSequence&&n<=r}function TA(e){let t=e.payload;if(!t||typeof t!=`object`||Array.isArray(t))return;let n=`eventId`in t&&typeof t.eventId==`string`?t.eventId:e.eventId,r=`piboSessionId`in t&&typeof t.piboSessionId==`string`?t.piboSessionId:e.piboSessionId;if(r){if(e.type===`tool_call`||e.type===`tool_execution_started`||e.type===`tool_execution_updated`||e.type===`tool_execution_finished`){let n=`toolCallId`in t&&typeof t.toolCallId==`string`?t.toolCallId:void 0;return n?`${r}:${e.type}:tool:${n}`:void 0}if(n){if(e.type===`assistant_delta`||e.type===`assistant_message`){let i=DA(t,`assistantIndex`)??DA(t,`contentIndex`),a=i===void 0?n:`${n}:assistant:${i}`;return`${r}:${e.type}:${a}`}if(e.type===`thinking_started`||e.type===`thinking_delta`||e.type===`thinking_finished`){let i=DA(t,`thinkingIndex`)??DA(t,`contentIndex`),a=i===void 0?n:`${n}:thinking:${i}`;return`${r}:${e.type}:${a}`}return`${r}:${e.type}:${n}`}}}function EA(e,t){return e.stableKey?.startsWith(t)?e.stableKey.slice(t.length):e.eventId}function DA(e,t){let n=t in e?e[t]:void 0;return typeof n==`number`&&Number.isFinite(n)?n:void 0}function OA(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 kA({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?vA(n,t):null)?.events??[];if(!o.length)return{traceView:t};let s=a?.(),c=lw(t,o,r??`idle`),l=oA(o);return l&&cA(c.nodes,i),{traceView:l?aA(c):c,liveTraceComputeDurationMs:s!==void 0&&a?a()-s:void 0}}function AA(e,t){for(let n of e)t(n),AA(n.children,t)}function jA(e){return typeof e.output==`string`?e.output:typeof e.summary==`string`?e.summary:``}function MA(e){if(!e)return;let t=0;return AA(e.nodes,e=>{e.type===`assistant.message`&&(t+=jA(e).length)}),t}function NA({selectedPiboSessionId:e,baseTraceView:t,liveTraceOverlay:n,selectedSessionStatus:r}){let i=(0,v.useMemo)(()=>t?aA(t):null,[t]),a=(0,v.useMemo)(()=>i?sA(i.nodes):new Map,[i]),o=(0,v.useMemo)(()=>kA({selectedPiboSessionId:e,reconciledBaseTraceView:i,liveTraceOverlay:n,selectedSessionStatus:r,persistedUserMessageIndexForBaseTrace:a,now:uy()?()=>performance.now():void 0}),[n,e,r,i,a]),s=o.traceView;return(0,v.useEffect)(()=>{!e||!s?.piboSessionId||!uy()||(yy(s.piboSessionId,{overlayEventCount:n?.piboSessionId===s.piboSessionId?n.events.length:0,traceBaseOutputLength:MA(t),currentOutputLength:MA(s)}),o.liveTraceComputeDurationMs!==void 0&&gy(s.piboSessionId,o.liveTraceComputeDurationMs))},[t,o.liveTraceComputeDurationMs,s,n,e]),(0,v.useEffect)(()=>{if(!s?.piboSessionId||!jb())return;let e=n?.piboSessionId===s.piboSessionId?n.events:[];Lb({piboSessionId:s.piboSessionId,trigger:`trace-state:render`,baseTraceView:t,currentTraceView:s,overlayEvents:e,selectedSessionStatus:r})},[t,s,n,r]),(0,v.useEffect)(()=>{let e=()=>{if(!s?.piboSessionId||!jb())return;let e=n?.piboSessionId===s.piboSessionId?n.events:[];Lb({piboSessionId:s.piboSessionId,trigger:`trace-state:tab:${document.visibilityState}`,baseTraceView:t,currentTraceView:s,overlayEvents:e,selectedSessionStatus:r})};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[t,s,n,r]),s}var PA=1e4,FA=5*6e4;function IA(e){return[`chat`,`trace-summary`,e]}function LA(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 RA(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:YA(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 zA(e,t){return e.piboSessionId===t.piboSessionId?{...t,nodes:BA(e.nodes,t),rawEvents:qA(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 BA(e,t){let n=VS([...e]),r=VS([...t.nodes]),i=new Set(r.map(e=>e.id)),a=HA([...n,...r]),o=WA(r),s=GA(r),c=n.filter(e=>{if(i.has(e.id))return!0;if(e.type===`agent.turn`&&e.source===`event-log`&&e.eventId&&a.has(e.eventId)||UA(e))return!1;let n=e.orderKey?.eventSequence;if(n!==void 0&&t.firstEventSequence!==void 0)return n<t.firstEventSequence;let r=e.orderKey?o.get(e.orderKey.sourceRank):void 0;if(e.orderKey&&r)return FS(e.orderKey,r)<0;if(e.source===`live`||e.orderKey?.streamId!==void 0)return!1;let c=KA(e.startedAt);return c!==void 0&&s!==void 0&&c<s}),l=new Set([...c,...r].map(e=>e.id)),u=new Set(n.filter(e=>!l.has(e.id)).map(e=>e.id));return YA(VA(c,u),VA(r,u))}function VA(e,t){return e.map(e=>e.parentId&&t.has(e.parentId)?{...e,parentId:void 0}:e)}function HA(e){let t=new Set;for(let n of e)n.source===`transcript`&&n.eventId&&t.add(n.eventId);return t}function UA(e){return e.source===`live`||e.orderKey?.streamId!==void 0}function WA(e){let t=new Map;for(let n of e){if(!n.orderKey)continue;let e=t.get(n.orderKey.sourceRank);(!e||FS(n.orderKey,e)<0)&&t.set(n.orderKey.sourceRank,n.orderKey)}return t}function GA(e){let t;for(let n of e){let e=KA(n.startedAt);e!==void 0&&(t=t===void 0?e:Math.min(t,e))}return t}function KA(e){if(!e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function qA(e,t){if(!t.length)return e;let n=t.reduce((e,t)=>t.eventSequence===void 0?e:e===void 0?t.eventSequence:Math.min(e,t.eventSequence),void 0),r=new Map;for(let t of e)n!==void 0&&t.eventSequence!==void 0&&t.eventSequence>=n||r.set(JA(t),t);for(let e of t)r.set(JA(e),e);return[...r.values()]}function JA(e){return e.id||`${e.eventSequence??``}:${e.type}:${e.createdAt}`}function YA(e,t){let n=new Map;for(let t of VS([...e]))n.set(t.id,{...t,children:[]});for(let e of VS([...t])){let t=n.get(e.id);n.set(e.id,{...t,...e,children:[]})}return HS([...n.values()])}function XA(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??ZA(e.cursor.before):void 0;for(let t of e.nodes)n.set(t.nodeId,QA(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??ZA(e.cursor.before),lastEventSequence:e.lastEventSequence??ZA(e.cursor.after),nextBeforeSequence:o,nextBeforeCursor:a,hasOlderEvents:i,nodes:r,rawEvents:t}}function ZA(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function QA(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 $A=128;function ej({selectedPiboSessionId:e,showRawEvents:t,liveTraceOverlay:n,liveTraceOverlayCacheRef:r,setLiveTraceOverlay:i}){let a=SO(),[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?IA(e):null,[e]),x=(0,v.useMemo)(()=>e?LA(e,{includeRawEvents:!1,rawEventsLimit:0,pageSize:50}):null,[e]),S=IO({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 lx(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:PA,gcTime:FA,refetchOnWindowFocus:!1,retry:1}),C=IO({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 ux(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 XA(r.timeline)},enabled:!!e,staleTime:PA,gcTime:FA,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=>gA(r.current,t,e)),_.current=null,y.current=new Set},[r,a,e,i,x]);let w=IO({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 dx(e,{limit:c,beforeSequence:p,signal:t})},enabled:!!(e&&t),staleTime:PA,gcTime:FA,refetchOnWindowFocus:!1,retry:1});(0,v.useEffect)(()=>{let t=C.data;!t||t.piboSessionId!==e||(uy()&&yy(t.piboSessionId,{overlayEventCount:0,traceBaseOutputLength:MA(t),traceBaseUpdated:!0}),(0,v.startTransition)(()=>{d(e=>{let n=e?.piboSessionId===t.piboSessionId?zA(e,t):t;return f.current.set(t.piboSessionId,n),n}),i(e=>_A(r.current,e,t))}))},[r,e,i,C.data]),(0,v.useEffect)(()=>{let t=u;!t||t.piboSessionId!==e||(0,v.startTransition)(()=>{i(e=>_A(r.current,e,t))})},[u,r,e,i]),(0,v.useEffect)(()=>{let t=w.data;!t||t.piboSessionId!==e||(0,v.startTransition)(()=>{d(e=>{if(!e)return e;if(p===void 0)return{...e,rawEvents:t.events};let n=new Set(t.events.map(e=>e.id));return{...e,rawEvents:[...t.events,...e.rawEvents.filter(e=>!n.has(e.id))]}})})},[p,w.data,e]);let T=(0,v.useCallback)(async n=>{if(!e||!n)return;let r=`${e}:${n}`;if(_.current||y.current.has(r))return;_.current=r,g(!0);let i=LA(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 ux(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 XA(o.timeline)},staleTime:PA,gcTime:FA});(0,v.startTransition)(()=>{d(e=>e?RA(e,t):t),s(e=>e+(t.pageSize??50))}),tj(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 tj(e,t){if(e.add(t),e.size<=$A)return;let n=e.values().next();n.done||e.delete(n.value)}function nj(e){let t=e.currentEvents,n,r,i=()=>(r??=new Set(t.map(lj)),r),a=e=>{n??=t.slice(),n.push(e),t=n};for(let o of e.streamEvents){let s=aj(o,e.piboSessionId,e.nextSequence,e.now??(()=>new Date().toISOString()));if(!s)continue;if(rj(s)){t=ij(t,s),n=t,r=void 0;continue}let c=lj(s),l=i();l.has(c)||(l.add(c),a(s))}return t}function rj(e){return e.type===`assistant_message`||e.type===`thinking_finished`||e.type===`tool_execution_finished`}function ij(e,t){return t.type===`assistant_message`?[...cj(e,t,`assistant_delta`),t]:t.type===`thinking_finished`?[...cj(e,t,`thinking_delta`),t]:t.type===`tool_execution_finished`?[...cj(e,t,`tool_execution_updated`),t]:e}function aj(e,t,n,r){if(e.type===`RAW_EVENT`&&fj(e.event)&&typeof e.event.type==`string`){let i=e.event;return oj(e,t,e.event.type,i,n,r)}if(e.type===`TEXT_MESSAGE_CONTENT`&&typeof e.delta==`string`)return oj(e,t,`assistant_delta`,{type:`assistant_delta`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,...dj(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 oj(e,t,`thinking_delta`,{type:`thinking_delta`,piboSessionId:t,eventId:typeof e.runId==`string`?e.runId:void 0,...dj(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 oj(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 oj(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 oj(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 oj(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 oj(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:sj(e)??a(),payload:r}}function sj(e){if(!(typeof e.createdAt!=`string`||!Number.isFinite(Date.parse(e.createdAt))))return e.createdAt}function cj(e,t,n){let r=uj(t);return e.filter(e=>e.type!==n||uj(e)!==r)}function lj(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 uj(e){let t=fj(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 dj(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 fj(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function pj(e){try{let t=JSON.parse(e.data);if(typeof t.type!=`string`)return;let n=e.lastEventId?NS(e.lastEventId):void 0;return{...t,...e.lastEventId?{streamFrameId:e.lastEventId}:{},...n?{streamId:n.streamId,streamFrameIndex:n.frameIndex}:{}}}catch{return}}function mj(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:gj(n),exact:!1,...r?.liveReplayId===void 0?{}:{liveReplayId:r.liveReplayId}})}function hj(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 gj(e){return`${e}:999999`}function _j(e){if(e.type===`RUN_FINISHED`||e.type===`TEXT_MESSAGE_END`)return 300;if(e.type===`RUN_ERROR`)return 0}function vj(e){return e.type===`RUN_STARTED`||e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`||e.type===`TEXT_MESSAGE_END`}function yj(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 bj(e,t,n){if(n.type===`RUN_STARTED`||n.type===`RUN_FINISHED`||n.type===`RUN_ERROR`){e.delete(t);return}let r=Cj(n);r&&e.get(t)?.delete(r)}function xj(e,t,n){let r=Sj(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 Sj(e){if(e.type===`TEXT_MESSAGE_CONTENT`||e.type===`REASONING_MESSAGE_CONTENT`)return`${e.type}:${e.messageId}`}function Cj(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 wj=500,Tj=1e4,Ej=45e3,Dj=15e3,Oj=100,kj=2;function Aj(e){let t=Math.max(e.eventCount??0,e.lastEventSequence??0);for(let n of e.rawEvents)t=Math.max(t,n.eventSequence??0);return t+1}function jj(e){if(e.forceReconnect)return!0;let t=e.liveStream;return!t||t.piboSessionId!==e.selectedPiboSessionId||t.readyState===kj||(e.nowMs??Date.now())-t.lastActivityAt>Ej}function Mj({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=(0,v.useRef)(!1),b=(0,v.useRef)(!1),[x,S]=(0,v.useState)(0);(0,v.useEffect)(()=>{let n=t;!n||n.piboSessionId!==e||(r.current=Math.max(r.current,Aj(n)),n.latestStreamId!==void 0&&mj(m.current,n.piboSessionId,n.latestStreamId))},[r,e,t]);let C=(0,v.useCallback)(e=>{let t=u.current.get(e);t?.length&&(o(n=>{let i=nj({currentEvents:n?.piboSessionId===e?n.events:[],streamEvents:t,piboSessionId:e,nextSequence:()=>r.current++});return hy(e,t.length,i.length),{piboSessionId:e,events:i}}),u.current.delete(e))},[]),w=(0,v.useCallback)(()=>{if(!(d.current!==void 0||f.current!==void 0||!e)){if(document.hidden){f.current=setTimeout(()=>{f.current=void 0,C(e)},Oj);return}d.current=requestAnimationFrame(()=>{d.current=void 0,C(e)})}},[C,e]),T=(0,v.useCallback)((t,n,r=!1)=>{bj(p.current,t,n);let i=r||xj(p.current,t,n),a=u.current.get(t)??[];a.push(n),u.current.set(t,a),my(t,n,a.length,i),i||t!==e?C(t):w()},[C,w,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 E=(0,v.useCallback)((e,t)=>{hj(m.current,e,t)},[]),D=(0,v.useCallback)((e=0)=>{if(g.current!==void 0){if(e>0)return;clearTimeout(g.current)}g.current=setTimeout(()=>{g.current=void 0,S(e=>e+1)},e)},[]),O=(0,v.useCallback)((t=!1)=>{if(!e)return;C(e),s().catch(e=>l(Nj(e))),c().catch(e=>l(Nj(e)));let n=h.current;if(jj({selectedPiboSessionId:e,liveStream:n?{piboSessionId:n.piboSessionId,lastActivityAt:n.lastActivityAt,readyState:n.events.readyState}:null,forceReconnect:t})){if(t){if(y.current)return;y.current=!0}D()}},[C,l,c,s,D,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:gj(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,b=!1,x=(t,n=!1)=>{if(f){if(!n)return;clearTimeout(f)}vy(e,t),f=setTimeout(()=>{f=void 0,s().catch(e=>l(Nj(e)))},t)},S=()=>{if(v){b=!0;return}v=!0,c().catch(e=>l(Nj(e))).finally(()=>{v=!1,b&&(b=!1,w(250,!0))})},w=(e,t=!1)=>{if(p){if(!t)return;clearTimeout(p)}p=setTimeout(()=>{p=void 0,S()},e)},O=()=>{w(900,!0)};return o.onopen=()=>{_.current=0,y.current=!1,g.current!==void 0&&(clearTimeout(g.current),g.current=void 0),dy(e,o.readyState);let t=h.current;t?.events===o&&(t.lastActivityAt=Date.now())},o.onerror=()=>{if(d)return;fy(e,o.readyState);let t=h.current;t?.events===o&&(t.lastErrorAt=Date.now());let n=_.current++;D(Math.min(Tj,wj*2**n))},o.addEventListener(`pibo`,t=>{if(d)return;let n=pj(t);if(!n)return;let r=n.piboSessionId||e,i=h.current;if(i?.events===o&&(i.lastActivityAt=Date.now()),E(r,n),py(r,n,t.lastEventId,o.readyState),r===e&&n.type===`ready`&&n.liveReplay?.missed&&x(0,!0),by(n))return;let a=n.type!==`TEXT_MESSAGE_CONTENT`&&n.type!==`REASONING_MESSAGE_CONTENT`;r===e&&yj(n)&&T(r,n,a);let s=_j(n);r===e&&s!==void 0?x(s,!0):r===e&&n.type!==`ready`&&n.type!==`RAW_EVENT`&&x(1500,!0),vj(n)&&(n.type===`RUN_FINISHED`||n.type===`RUN_ERROR`||n.type===`TEXT_MESSAGE_END`?O():w(r===e?0:150))}),()=>{d=!0,f&&clearTimeout(f),p&&clearTimeout(p),C(e),h.current?.events===o&&(h.current=null),o.close()}},[n?.piboSessionId,T,C,l,c,s,E,D,x,e,a]),(0,v.useEffect)(()=>{n?.piboSessionId&&C(n.piboSessionId)},[n?.piboSessionId,C]),(0,v.useEffect)(()=>{let e=()=>O(),t=()=>O(!0),n=()=>{b.current=!0},r=()=>{if(document.hidden){n();return}b.current=!1,O(!0)},i=e=>{let t=b.current||e.persisted;b.current=!1,O(t)};return window.addEventListener(`focus`,e),window.addEventListener(`online`,t),window.addEventListener(`pagehide`,n),window.addEventListener(`pageshow`,i),document.addEventListener(`visibilitychange`,r),()=>{window.removeEventListener(`focus`,e),window.removeEventListener(`online`,t),window.removeEventListener(`pagehide`,n),window.removeEventListener(`pageshow`,i),document.removeEventListener(`visibilitychange`,r)}},[O]),(0,v.useEffect)(()=>{if(!e||i!==`running`)return;let t=window.setInterval(()=>{C(e);let t=h.current;jj({selectedPiboSessionId:e,liveStream:t?{piboSessionId:t.piboSessionId,lastActivityAt:t.lastActivityAt,readyState:t.events.readyState}:null})&&(s().catch(e=>l(Nj(e))),D())},Dj);return()=>window.clearInterval(t)},[C,l,s,D,e,i])}function Nj(e){return e instanceof Error?e.message:String(e)}var Pj=10;function Fj(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,Pj)}:e}function Ij(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 Lj(e,t){return!t||!e[t]?.length?e:{...e,[t]:[]}}function Rj(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=>Fj(r,e,n,t))},[t,e]),detachUploadAttachment:(0,v.useCallback)(t=>{r(n=>Ij(n,e,t))},[e]),clearSelectedUploadAttachments:(0,v.useCallback)(()=>{r(t=>Lj(t,e))},[e])}}function zj({selectedPiboSessionId:e,onError:t,formatError:n}){let[r,i]=(0,v.useState)([]),[a,o]=(0,v.useState)(!1),[s,c]=(0,v.useState)(()=>e?uk(e):null),[l,u]=(0,v.useState)(()=>_k()),[d,f]=(0,v.useState)(!1),p=!!(e&&s?.piboSessionId===e&&s.installed),m=!!e&&(a||p),h=IO({queryKey:[`web-annotations`,`app`,e],queryFn:async()=>{if(!e)throw Error(`Session is required`);return Vx(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?mk(e):[]),c(e?uk(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(pk(e.detail)),r=n=>{n.key===dk(e)&&t(fk(n.newValue))},i=()=>t(uk(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&&hk(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&&hk(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&&hk(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 vk(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=>Hx(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 Bj=new WeakMap;function Vj(e,t,n){let r=n.map(e=>Hj(e)),i=Yj(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 Hj(e){let t=Bj.get(e);if(t)return t;let n=Jj(e.startedAt)??Date.now()*1e3,r=Jj(e.completedAt),i=qj(e.status),a=Uj(e.type),o={id:e.id,parentId:e.parentId,name:Wj(e),spanType:a,startTime:n,endTime:r,durationUs:e.durationMs===void 0?void 0:e.durationMs*1e3,attributes:Gj(e),status:i,statusMessage:e.error,events:e.error?[{name:`exception`,timestamp:r??n,attributes:{message:e.error}}]:[],children:e.children?.map(Hj),pibo:{entryId:e.entryId,linkedPiboSessionId:e.linkedPiboSessionId,traceNodeType:e.type,traceOrder:e.orderKey,stableKey:e.stableKey,source:e.source}};return Bj.set(e,o),o}function Uj(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 Wj(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 Gj(e){let t={};if(e.summary&&(t.content=e.summary),e.input!==void 0&&(t.input=e.input,t.args=e.input,t.arguments=e.input),e.output!==void 0&&(t.output=e.output,t.result=e.output),e.error&&(t.error=e.error),e.toolCallId&&(t.tool_call_id=e.toolCallId),e.runId&&(t.run_id=e.runId),(e.type===`tool.call`||e.type===`agent.delegation`)&&(t.tool_name=e.title),e.type===`assistant.message`&&(t.content=e.output??e.summary??``),e.type===`user.message`){t.content=e.output??e.summary??``;let n=Kj(e);n&&(t[`message.pending_delivery`]=n)}return e.type===`model.reasoning`&&(t.reasoning=e.output??e.summary??``),e.type===`agent.delegation`&&(t[`delegation.target_agent`]=e.title.replace(/^pibo_subagent_/,``),t[`delegation.query`]=e.summary??e.input,t[`result.status`]=e.status===`done`?`completed`:e.status,t.linked_pibo_session_id=e.linkedPiboSessionId),e.type===`agent.async`&&(t[`async_agent.target_agent`]=e.title,t[`async_agent.started_by`]=Xj(e.input)?e.input.startedBy:`pibo_run_start`,t[`async_agent.query`]=Xj(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 Kj(e){if(!(e.type!==`user.message`||e.status!==`running`)){if(e.id.startsWith(`event:message_steered:`))return`steer`;if(e.id.startsWith(`event:message_queued:`))return`queue`}}function qj(e){return e===`running`?`UNSET`:e===`error`?`ERROR`:`OK`}function Jj(e){if(!e)return;let t=new Date(e).getTime();return Number.isFinite(t)?t*1e3:void 0}function Yj(e){return e.flatMap(e=>[e,...e.children?Yj(e.children):[]])}function Xj(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Zj(e){return(e.selectedPiboSessionId?S(e.sessionNodes,e.selectedPiboSessionId):void 0)?.title||e.traceTitle||e.selectedPiboSessionId||e.fallback}function Qj(e,t){return t?{sessionBreadcrumbs:rM(e,t),originSession:tM(e,t),derivedSessions:nM(e,t)}:{sessionBreadcrumbs:[],originSession:void 0,derivedSessions:[]}}function $j(e){let t=e.selectedPiboSessionId?S(e.bootstrap.sessions,e.selectedPiboSessionId):void 0,n=sM(e.currentTraceView);return oM(e.selectedSessionActiveModel,e.bootstrap.runtimeStatus?.thinkingLevel??n.level??iM(e.bootstrap,e.selectedSessionProfile,!!t?.parentId),e.bootstrap.runtimeStatus?.fastMode??n.fast??aM(e.bootstrap,e.selectedSessionProfile,!!t?.parentId)??!1)}function eM(e){return{traceView:e.currentTraceView,selectedTrace:e.currentTraceView?Vj(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,sessionGoal:e.sessionGoal,workflowProjectSession:e.workflowProjectSession,workflowLifecycleEvents:e.workflowLifecycleEvents,sessionNodes:e.sessionNodes,sessionBreadcrumbs:e.sessionLinks.sessionBreadcrumbs,originSession:e.sessionLinks.originSession,derivedSessions:e.sessionLinks.derivedSessions,agentProfiles:e.agentProfiles,sessionProfileChangeDisabled:e.sessionProfileChangeDisabled,onSessionAgentProfileChange:e.onSessionAgentProfileChange,onFork:e.onFork,onOpenSession:e.onOpenSession,onLoadOlderTracePage:e.onLoadOlderTracePage,hasOlderTraceEvents:e.hasOlderTraceEvents,isFetchingOlderTracePage:e.isFetchingOlderTracePage,onThinkingLevelChange:e.onThinkingLevelChange,onModelChanged:async()=>{await e.onRefreshBootstrap(),await e.onRefreshTrace()},onRefreshBootstrap:e.onRefreshBootstrap,onError:e.onError}}function tM(e,t){let n=S(e,t);if(!n?.originId)return;let r=S(e,n.originId);return{piboSessionId:n.originId,label:r?uM(r,0):n.originId}}function nM(e,t){return S(e,t)?.derivedSessions.map(e=>({piboSessionId:e.piboSessionId,label:dM(e),profile:e.profile,status:e.status}))??[]}function rM(e,t){return C(e,t).map((e,t)=>({piboSessionId:e.piboSessionId,label:uM(e,t)}))}function iM(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 aM(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 oM(e,t,n){if(e)return[e,t,n?`fast`:void 0].filter(Boolean).join(` `)}function sM(e){let t={};if(!e)return t;for(let n of cM(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`&&lM(e.level)?e.level:void 0)??t.level,fast:n.title===`fast_mode`?e?.mode===`fast`:t.fast}}return t}function cM(e){return e.flatMap(e=>[e,...cM(e.children)])}function lM(e){return BT.includes(e)}function uM(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 dM(e){return e.subagentName&&e.subagentName!==e.profile?`${e.subagentName} (${e.profile})`:e.title||e.profile||e.subagentName||`Untitled Session`}function fM({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 pM(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 mM(e,t,n){return{piboSessionId:t,events:[...e?.piboSessionId===t?e.events:[],n]}}var hM=`optimistic-session-`;function gM(e){return e?.startsWith(hM)===!0}function _M(e){return e&&!gM(e)?e:null}function vM(e){return e instanceof Error?e.message:String(e)}var yM=[`(display-mode: standalone)`,`(display-mode: window-controls-overlay)`];function bM(e,t){return yM.some(t=>e(t).matches)?typeof t.userAgentData?.mobile==`boolean`?!t.userAgentData.mobile:!(/Android|iPhone|iPad|iPod|Mobile/i.test(t.userAgent)||/Macintosh/i.test(t.userAgent)&&t.maxTouchPoints>1):!1}function xM(){return typeof window<`u`&&typeof navigator<`u`&&bM(window.matchMedia.bind(window),navigator)}function SM(e,t){return{url:e,name:`pibo-session-${t}`,features:`width=1280,height=900`}}function CM(){let e=SM(window.location.href,crypto.randomUUID());return window.open(e.url,e.name,e.features)}function wM({bootstrap:e,selectedPiboSessionId:t,selectedRoomId:n,selectedRoomArchived:r,roomNavigationPending:i,sessionNavigationPending:a,selectedSessionProfile:o,selectedSessionActiveModel:s,selectedSessionStatus:c,selectedSessionSignal:l,signals:u,workflowProjectSession:d,workflowLifecycleEvents:f,projectSessionCreatePanel:p,workflowStartPanel:m,projectModulePanel:h,extraViewTabs:g,activeViewId:_,sessionViewId:y,sessionViews:b,currentSessionView:x,allowedSessionViewIds:S,creatingSession:C,terminalFullscreen:E=!1,onEnterTerminalFullscreen:D,onExitTerminalFullscreen:O,showRawEvents:k,showThinking:A,expandThinking:ee,commands:te,skills:j,composerText:M,composerFocusSignal:ne,onComposerTextChange:N,onToggleRawEvents:P,onToggleThinking:re,onToggleExpandThinking:ie,onSessionAgentProfileChange:ae,onFork:oe,onOpenSession:se,onSelectSessionView:le,onCommand:F,onThinkingLevelChange:ue,onRefreshTrace:de,onRefreshBootstrap:fe,onSend:pe,onError:me}){let he=(0,v.useRef)(0),ge=(0,v.useRef)(new Map),[_e,ve]=(0,v.useState)(null),ye=(0,v.useCallback)(e=>{ve(t=>{let n=typeof e==`function`?e(t):e;return n&&ge.current.set(n.piboSessionId,n),n})},[]),[be,I]=(0,v.useState)(null),xe=(0,v.useRef)(new Set),Se=(0,v.useRef)(null),Ce=_M(t),we=IO({queryKey:Ce?[`chat`,`session-goal`,Ce]:[`chat`,`session-goal`,`idle`],queryFn:({signal:e})=>Bx(Ce,{signal:e}),enabled:!!Ce,refetchInterval:Ce?5e3:!1}),Te=!!Ce&&xM(),Ee=(0,v.useCallback)(()=>{CM()||me(`The browser blocked the new Pibo window.`)},[me]),De=Te?Ee:void 0,{baseTraceView:Oe,liveTraceOverlay:ke,rawEventLimit:Ae,traceSummaryQuery:je,tracePageQuery:Me,rawEventsQuery:Ne,loadingOlderTracePage:Pe,tracePageReady:Fe,loadOlderTracePage:Ie,loadMoreRawEvents:Le}=ej({selectedPiboSessionId:Ce,showRawEvents:k,liveTraceOverlay:_e,liveTraceOverlayCacheRef:ge,setLiveTraceOverlay:ye}),{selectedWebAnnotationIds:Re,selectedWebAnnotations:ze,visibleWebAnnotations:Be,webAnnotationsPanelCollapsed:Ve,webAnnotationsPanelRendered:He,webAnnotationsPanelVisible:Ue,webAnnotationsQuery:We,clearingWebAnnotations:Ge,setWebAnnotationsPanelVisible:Ke,toggleWebAnnotationAttachment:qe,detachWebAnnotationAttachment:Je,clearSelectedWebAnnotationAttachments:Ye,toggleWebAnnotationsPanelCollapsed:Xe,clearVisibleWebAnnotations:Ze}=zj({selectedPiboSessionId:Ce,onError:me,formatError:Dk}),{selectedUploadAttachments:Qe,attachUploadedFiles:$e,detachUploadAttachment:et,clearSelectedUploadAttachments:tt}=Rj(t,(0,v.useCallback)(()=>`upload-${w()}`,[])),nt=NA({selectedPiboSessionId:Ce,baseTraceView:Oe,liveTraceOverlay:ke,selectedSessionStatus:c});Mj({selectedPiboSessionId:Ce,tracePageData:Me.data,currentTraceView:nt,liveEventSeqRef:he,selectedSessionStatus:c,tracePageReady:Fe,setLiveTraceOverlay:ye,onRefreshTrace:de,onRefreshBootstrap:fe,onError:me});let rt=$j({bootstrap:e,selectedPiboSessionId:t,selectedSessionProfile:o,selectedSessionActiveModel:s,currentTraceView:nt}),it=(0,v.useMemo)(()=>Qj(e.sessions,t),[e.sessions,t]),at=!!t&&Me.isFetching&&!nt,ot=Me.error?vM(Me.error):je.error?vM(je.error):null,st=T(t,r),ct=!st&&x.id===`terminal`&&(_??y)===`terminal`,lt=(0,v.useCallback)(async e=>{try{$e((await ce(e)).files)}catch(e){me(vM(e))}},[$e,me]),ut=nt?.piboSessionId??t??``,dt=d&&Fk(d)?Ik(d,c):null,ft=e=>{for(let n of[750,2e3,5e3,1e4])window.setTimeout(()=>{t===e&&Me.refetch().catch(e=>me(vM(e)))},n)},pt=async(e,t)=>{let n=pM(e,t);ye(e=>mM(e,n.piboSessionId,n.optimisticEvent)),await pe(n.text,n.webAnnotationIds,n.fileAttachmentPaths,n.clientTxnId,t),Ye(),tt(),await Promise.all([Me.refetch(),We.refetch()]),ft(n.piboSessionId)},mt=(e,t)=>{ye(t=>{let n=t?.piboSessionId===e.piboSessionId?t:ge.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?ge.current.set(e.piboSessionId,i):ge.current.delete(e.piboSessionId),t?.piboSessionId===e.piboSessionId?i:t}),N(t=>t||e.text),me(vM(t))},ht=async e=>{if(st||!t)return;let n=fM({piboSessionId:t,text:e,selectedWebAnnotations:ze,selectedUploadAttachments:Qe,eventSequence:he.current++,now:new Date().toISOString(),clientTxnId:w()});if(c===`running`){I(n);return}try{await pt(n,`queue`)}catch(e){mt(n,e)}},gt=()=>{be&&(N(e=>e||be.text),I(null))},_t=async e=>{let t=be;if(!(!t||xe.current.has(t.clientTxnId))){xe.current.add(t.clientTxnId),I(e=>e?.clientTxnId===t.clientTxnId?null:e),me(null);try{await pt(t,e)}catch(e){mt(t,e)}finally{xe.current.delete(t.clientTxnId)}}},vt=eM({currentTraceView:nt,isLoading:at,showThinking:A,expandThinking:ee,selectedSessionProfile:o,sessionActiveModelBadge:rt,selectedSessionStatus:c,selectedSessionSignal:l,signals:u,sessionGoal:we.data?.goal,workflowProjectSession:d,workflowLifecycleEvents:f,sessionNodes:e.sessions,sessionLinks:it,agentProfiles:e.agents,sessionProfileChangeDisabled:C||r,onSessionAgentProfileChange:ae,onFork:oe,onOpenSession:se,onLoadOlderTracePage:()=>void Ie(nt?.nextBeforeCursor??nt?.nextBeforeSequence),hasOlderTraceEvents:nt?.hasOlderEvents===!0||nt?.nextBeforeCursor!==void 0||typeof nt?.nextBeforeSequence==`number`,isFetchingOlderTracePage:Pe,onThinkingLevelChange:ue,onRefreshTrace:de,onRefreshBootstrap:fe,onError:me});return(0,L.jsxs)(L.Fragment,{children:[be?(0,L.jsx)(iA,{title:`Session is running`,description:`Choose how this message should be delivered.`,onClose:gt,initialFocusRef:Se,children:(0,L.jsxs)(`div`,{className:`grid gap-2 p-4 sm:grid-cols-2`,"data-pibo-debug":`message-delivery-dialog`,children:[(0,L.jsxs)(`button`,{ref:Se,type:`button`,onClick:()=>void _t(`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,L.jsx)(`span`,{className:`block text-xs font-bold uppercase tracking-wider text-[#11a4d4]`,children:`Queue`}),(0,L.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,L.jsxs)(`button`,{type:`button`,onClick:()=>void _t(`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,L.jsx)(`span`,{className:`block text-xs font-bold uppercase tracking-wider text-amber-400`,children:`Steer`}),(0,L.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,L.jsx)(eA,{selectedPiboSessionId:t,selectedRoomId:n,fallbackRoomId:e.selectedRoomId??void 0,sessionViewId:y,loadingTrace:at,roomNavigationPending:i,sessionNavigationPending:a,traceError:ot,showRawEvents:k,currentTraceView:nt,rawEventLimit:Ae,tracePageFetching:k?Ne.isFetching:Me.isFetching,onLoadMoreRawEvents:Le,terminalFullscreen:E,terminalFileDropEnabled:ct,onTerminalFilesDropped:lt,onOpenSessionWindow:De,onExitTerminalFullscreen:O??(()=>void 0),headerProps:{title:Zj({sessionNodes:e.sessions,selectedPiboSessionId:t,traceTitle:nt?.title,fallback:e.room?.name??n??void 0}),roomLabel:e.room?.name??n??`Room`,headerPiboSessionId:ut,piboSessionId:t,piboRoomId:n??e.selectedRoomId??void 0,webAnnotationsDisabled:!t||r,webAnnotationsPanelRendered:He,workflowHeader:dt,sessionViewId:y,sessionViews:b,currentSessionView:x,allowedSessionViewIds:S,extraViewTabs:g,activeViewId:_,terminalFullscreenAvailable:x.id===`terminal`&&(_??y)===`terminal`,onEnterTerminalFullscreen:D,onOpenSessionWindow:De,showRawEvents:k,showThinking:A,expandThinking:ee,onShowWebAnnotationsPanel:()=>Ke(!0),onHideWebAnnotationsPanel:()=>Ke(!1),onSelectSessionView:le,onToggleRawEvents:P,onToggleThinking:re,onToggleExpandThinking:ie,onError:me},projectSessionCreatePanel:p,workflowStartPanel:m,projectModulePanel:h,currentSessionView:x,sessionViewProps:vt,webAnnotationsPanelRendered:He,webAnnotationsPanelProps:{piboSessionId:t,annotations:Be,selectedIds:Re,loading:We.isLoading||We.isFetching||Ge,error:We.error?vM(We.error):null,collapsed:Ve,onRefresh:()=>void We.refetch(),onToggle:qe,onClear:()=>void Ze(),onCollapse:Xe,onClose:()=>Ke(!1)},composerProps:{sessionId:t,disabled:st,commands:te,skills:j,value:M,focusSignal:ne,selectedWebAnnotations:ze,selectedUploadAttachments:Qe,onValueChange:N,onCommand:F,onDetachWebAnnotation:Je,onClearWebAnnotations:Ye,onAttachUploadedFiles:$e,onDetachUploadAttachment:et,onClearUploadAttachments:tt,onSend:ht}})]})}function TM({mode:e,onSelectSession:t,onNewSession:n,onDeleteSession:r,onRenameSession:i,onSelectRoom:a}){return e.kind===`rooms`?(0,L.jsx)(MM,{candidates:e.candidates,workspace:e.workspace,onSelectRoom:a}):(0,L.jsx)(AM,{sessions:e.sessions,selectedPiboSessionId:e.selectedPiboSessionId,onSelectSession:t,onNewSession:n,onDeleteSession:r,onRenameSession:i})}function EM(e){return e===`running`?`running`:e===`error`?`error`:e===`completed`?`completed`:`idle`}var DM={running:`bg-cyan-400`,idle:`bg-slate-500`,error:`bg-rose-500`,completed:`bg-emerald-500`},OM={running:`running`,idle:`idle`,error:`error`,completed:`completed`};function kM({status:e}){let t=EM(e);return(0,L.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-[10px] uppercase tracking-wider text-slate-400`,children:[(0,L.jsx)(`span`,{className:`inline-block w-1.5 h-1.5 rounded-full ${DM[t]}`,"aria-hidden":`true`}),OM[t]]})}function AM({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,L.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,L.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,L.jsxs)(`ul`,{className:`flex gap-1 overflow-x-auto min-w-0`,children:[o.map(e=>(0,L.jsx)(`li`,{className:`shrink-0`,children:(0,L.jsx)(jM,{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,L.jsx)(`li`,{className:`text-xs text-slate-500 px-2 py-1`,children:`No sessions yet — click + to start one.`})]})]})}function jM({session:e,isActive:t,onSelect:n,onDelete:r,onRename:i}){let[a,o]=(0,v.useState)(!1);return(0,L.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,L.jsxs)(`button`,{type:`button`,onClick:n,className:`inline-flex items-center gap-2 text-left`,children:[(0,L.jsx)(kM,{status:e.status}),(0,L.jsx)(`span`,{className:`text-xs text-slate-200 max-w-[180px] truncate`,children:e.title||`Untitled`})]}),(0,L.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,L.jsxs)(`div`,{className:`absolute z-10 mt-12 -ml-20 bg-[#0a1418] border border-slate-700 rounded shadow-lg text-xs`,children:[(0,L.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,L.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 MM({candidates:e,workspace:t,onSelectRoom:n}){return(0,L.jsxs)(`div`,{className:`border-b border-slate-800 px-3 py-3 bg-[#0c1820]`,"data-testid":`room-picker`,children:[(0,L.jsxs)(`div`,{className:`text-[10px] uppercase tracking-wider text-slate-400 mb-2`,children:[`Multiple rooms found for `,(0,L.jsx)(`span`,{className:`font-mono text-slate-300`,children:t})]}),(0,L.jsx)(`ul`,{className:`flex flex-col gap-1`,children:e.map(e=>(0,L.jsx)(`li`,{children:(0,L.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,L.jsx)(`div`,{className:`font-semibold text-slate-200 text-sm`,children:e.name}),e.topic&&(0,L.jsx)(`div`,{className:`text-xs text-slate-400 mt-0.5`,children:e.topic}),(0,L.jsxs)(`div`,{className:`text-[10px] text-slate-500 mt-1`,children:[`Created `,NM(e.createdAt),` · Updated `,NM(e.updatedAt)]})]})},e.id))})]})}function NM(e){try{return new Date(e).toLocaleString()}catch{return e}}function PM(){return new URLSearchParams(window.location.search).get(`workspace`)}function FM(){return new URLSearchParams(window.location.search).get(`roomId`)}function IM(){let e=(0,v.useMemo)(()=>PM(),[]),[t,n]=(0,v.useState)(()=>FM()),[r,i]=(0,v.useState)(()=>FM()?{kind:`sessions`,roomId:FM(),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(vM(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(vM(e))}},[t,s]),b=(0,v.useCallback)(async()=>{await y()},[y]);(0,v.useEffect)(()=>{if(!t)return;let e=`/api/chat/events?${new URLSearchParams({roomId:t,mode:`summary`,since:`0:999999`}).toString()}`,n=new EventSource(e),r,i=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=void 0,y()},200)};return n.addEventListener(`change`,i),n.addEventListener(`trace`,i),n.addEventListener(`message`,i),n.onerror=()=>{},()=>{r&&clearTimeout(r),n.close()}},[t,y]),(0,v.useEffect)(()=>{let e=e=>{let t=e.data;!t||typeof t!=`object`||(t.type===`pibo/set-selector-mode`?(i(t.mode),t.mode.kind===`sessions`&&n(t.mode.roomId)):t.type===`pibo/refresh-bootstrap`&&y())};return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[y]);let S=(0,v.useMemo)(()=>a?O(a.capabilities.actions):[],[a]),C=(0,v.useMemo)(()=>k(a,s),[a,s]),T=(0,v.useMemo)(()=>r.kind===`sessions`?r.sessions:_,[r,_]),E=(0,v.useCallback)(e=>{c(e),f(e=>e+1)},[]),D=(0,v.useCallback)(async e=>{if(t)try{let n=await te(e,t);await y(),n.session?.id&&c(n.session.id)}catch(e){m(vM(e))}},[t,y]),A=(0,v.useCallback)(async e=>{try{await M(e,`delete`),await y(),s===e&&c(null)}catch(e){m(vM(e))}},[y,s]),P=(0,v.useCallback)(async(e,t)=>{try{await j(e,{title:t}),await y()}catch(e){m(vM(e))}},[y]),re=(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()}`)},[]),ie=(0,v.useCallback)(async e=>{if(!(!s||!t))try{await ne(s,e,w(),t),u(``),f(e=>e+1),await y()}catch(e){m(vM(e))}},[s,t,y]),se=(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=ae(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(vM(e))}return!0}try{let e=oe(i.action,n.slice(r.length).trim());await N(s,i.action,e),await y()}catch(e){m(vM(e))}return!0},[S,s,t,y]),ce=(0,v.useMemo)(()=>zD(),[]),F=(0,v.useMemo)(()=>BD(pe),[]);if(!a)return(0,L.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,L.jsx)(TM,{mode:r,onSelectSession:E,onNewSession:D,onDeleteSession:A,onRenameSession:P,onSelectRoom:re}),(0,L.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,L.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,L.jsx)(TM,{mode:{kind:`rooms`,candidates:a.rooms??r.candidates,workspace:r.workspace},onSelectSession:E,onNewSession:D,onDeleteSession:A,onRenameSession:P,onSelectRoom:re}),(0,L.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 ue=a.sessions.find(e=>e.piboSessionId===s);return(0,L.jsxs)(`div`,{className:`pibo-vscode-panel h-full flex flex-col bg-[#0c1820] text-slate-200`,children:[(0,L.jsx)(TM,{mode:{kind:`sessions`,roomId:t??``,sessions:T,selectedPiboSessionId:s},onSelectSession:E,onNewSession:D,onDeleteSession:A,onRenameSession:P,onSelectRoom:re}),p&&(0,L.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,L.jsx)(`button`,{type:`button`,className:`ml-3 underline`,onClick:()=>m(null),children:`dismiss`})]}),(0,L.jsx)(`div`,{className:`flex-1 min-h-0`,children:(0,L.jsx)(wM,{bootstrap:a,selectedPiboSessionId:s,selectedRoomId:t,selectedRoomArchived:!1,selectedSessionProfile:ue?.profile??`default`,selectedSessionActiveModel:ue?x(a,ue)??void 0:void 0,selectedSessionStatus:ue?.status,sessionViewId:pe,sessionViews:ce,currentSessionView:F,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:se,onThinkingLevelChange:e=>void se(`/thinking ${e}`),onRefreshTrace:b,onRefreshBootstrap:y,onSend:ie,onError:m})})]})}var LM=document.getElementById(`root`);LM&&(0,y.createRoot)(LM).render((0,L.jsx)(v.StrictMode,{children:(0,L.jsx)(IM,{})}));
|