@piagent/platform 1.47.0 → 1.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +16 -3
  3. package/README.vi.md +16 -3
  4. package/docs/command-reference-vietnamese.md +4 -4
  5. package/docs/company-dev-commands.md +4 -4
  6. package/docs/distribution-standard.md +6 -6
  7. package/docs/languages.json +2 -2
  8. package/docs/operator-manual-vietnamese.md +7 -7
  9. package/docs/publishing-for-teams.md +1 -0
  10. package/docs/release-install-policy.md +2 -2
  11. package/docs/security-threat-model.md +3 -1
  12. package/docs/team-onboarding.md +2 -2
  13. package/docs-site/architecture.html +1 -1
  14. package/docs-site/assets/search-en.json +1 -1
  15. package/docs-site/assets/search-vi.json +1 -1
  16. package/docs-site/benchmark.html +1 -1
  17. package/docs-site/commands.html +1 -1
  18. package/docs-site/context-engine.html +1 -1
  19. package/docs-site/ecosystem.html +1 -1
  20. package/docs-site/en/architecture.html +1 -1
  21. package/docs-site/en/benchmark.html +1 -1
  22. package/docs-site/en/commands.html +1 -1
  23. package/docs-site/en/context-engine.html +1 -1
  24. package/docs-site/en/ecosystem.html +1 -1
  25. package/docs-site/en/index.html +9 -9
  26. package/docs-site/en/mcp-approval.html +1 -1
  27. package/docs-site/en/mcp-auth.html +1 -1
  28. package/docs-site/en/mcp-servers.html +1 -1
  29. package/docs-site/en/mcp.html +1 -1
  30. package/docs-site/en/permissions.html +1 -1
  31. package/docs-site/en/profiles.html +1 -1
  32. package/docs-site/en/quickstart.html +1 -1
  33. package/docs-site/en/runtime.html +1 -1
  34. package/docs-site/en/scope.html +1 -1
  35. package/docs-site/en/security.html +1 -1
  36. package/docs-site/en/team.html +1 -1
  37. package/docs-site/en/update.html +3 -3
  38. package/docs-site/en/whats-new.html +33 -18
  39. package/docs-site/en/windows.html +1 -1
  40. package/docs-site/en/workflows.html +1 -1
  41. package/docs-site/index.html +9 -9
  42. package/docs-site/mcp-approval.html +1 -1
  43. package/docs-site/mcp-auth.html +1 -1
  44. package/docs-site/mcp-servers.html +1 -1
  45. package/docs-site/mcp.html +1 -1
  46. package/docs-site/permissions.html +1 -1
  47. package/docs-site/profiles.html +1 -1
  48. package/docs-site/quickstart.html +1 -1
  49. package/docs-site/releases.json +51 -0
  50. package/docs-site/runtime.html +1 -1
  51. package/docs-site/scope.html +1 -1
  52. package/docs-site/security.html +1 -1
  53. package/docs-site/team.html +1 -1
  54. package/docs-site/update.html +3 -3
  55. package/docs-site/whats-new.html +33 -18
  56. package/docs-site/windows.html +1 -1
  57. package/docs-site/workflows.html +1 -1
  58. package/evals/private-holdout-v1/public-exposure.v2.json +2 -2
  59. package/package.json +2 -1
  60. package/packages/piagent-core/extensions/guard-types.ts +10 -2
  61. package/packages/piagent-core/extensions/piagent-guard.ts +104 -23
  62. package/packages/piagent-core/extensions/policy-core.js +7 -7
  63. package/packages/piagent-core/extensions/shell-ast.js +85 -0
  64. package/packages/piagent-core/extensions/shell-command-words.js +19 -0
  65. package/packages/piagent-core/managed/command-tools.mjs +54 -24
  66. package/packages/piagent-core/managed/fetch-guard.mjs +3 -3
  67. package/packages/piagent-core/managed/host-command.mjs +15 -7
  68. package/packages/piagent-core/managed/member-mcp.mjs +34 -9
  69. package/packages/piagent-core/managed/permission.mjs +19 -12
  70. package/packages/piagent-core/managed/repository-operation.mjs +1 -1
  71. package/packages/piagent-core/managed/session.mjs +2 -2
  72. package/packages/piagent-core/package.json +1 -1
  73. package/packages/piagent-core/runtime/hooks/session-start-hook.ts +1 -1
  74. package/packages/piagent-core/runtime/inspection/approval-broker.ts +33 -16
  75. package/packages/piagent-core/runtime/policy/handoff-policy.mjs +144 -0
  76. package/packages/piagent-core/runtime/registration/permission-commands.ts +2 -2
  77. package/packages/piagent-webui/dist/client/assets/{App-CiwY9VpU.js → App-fZeIRoaD.js} +1 -1
  78. package/packages/piagent-webui/dist/client/assets/{GatewayApp-DrNJW3v_.js → GatewayApp-CpC4lgYK.js} +17 -15
  79. package/packages/piagent-webui/dist/client/assets/{InspectionApp-BBiwSaV0.js → InspectionApp-pD-BqBXm.js} +1 -1
  80. package/packages/piagent-webui/dist/client/assets/{SessionAgentWorkspace-DwyPebIX.js → SessionAgentWorkspace-3tM7Q6HH.js} +1 -1
  81. package/packages/piagent-webui/dist/client/assets/{SessionInspectorDrawer-CpVzaf_G.js → SessionInspectorDrawer-BJ94aQ6y.js} +2 -2
  82. package/packages/piagent-webui/dist/client/assets/SettingsNavigation-BFfqMcuL.js +3 -0
  83. package/packages/piagent-webui/dist/client/assets/SettingsPage-CxpZ7cdM.js +1 -0
  84. package/packages/piagent-webui/dist/client/assets/{TerminalPanel-B8j_r6-y.js → TerminalPanel-CtZyb0tj.js} +1 -1
  85. package/packages/piagent-webui/dist/client/assets/{WorkspaceCodeEditor-BDTPvq-0.js → WorkspaceCodeEditor-BS_ZrjPN.js} +1 -1
  86. package/packages/piagent-webui/dist/client/assets/{WorkspaceExplorer-DVsNU0eu.js → WorkspaceExplorer-CkFBpcM7.js} +3 -3
  87. package/packages/piagent-webui/dist/client/assets/{index-uhJMXxqD.js → index-CNdhIouM.js} +2 -2
  88. package/packages/piagent-webui/dist/client/assets/{index-Dqb2hNan.css → index-CjM70M7D.css} +1 -1
  89. package/packages/piagent-webui/dist/client/assets/transcript-view-model-CpEMY1xb.js +3 -0
  90. package/packages/piagent-webui/dist/client/index.html +2 -2
  91. package/packages/piagent-webui/gateway/gateway-events.ts +5 -1
  92. package/packages/piagent-webui/server/gateway-websocket.ts +5 -1
  93. package/schemas/piagent-webui/approval-v1.schema.json +3 -1
  94. package/schemas/project-profile.schema.json +16 -0
  95. package/scripts/company-terminal.mjs +5 -5
  96. package/scripts/verify-release-identity.mjs +1 -1
  97. package/packages/piagent-core/runtime/policy/bypass-policy.mjs +0 -42
  98. package/packages/piagent-webui/dist/client/assets/SettingsNavigation-C-tO5iXn.js +0 -3
  99. package/packages/piagent-webui/dist/client/assets/SettingsPage-Ca-qRSZa.js +0 -1
  100. package/packages/piagent-webui/dist/client/assets/transcript-view-model-Bq0nkxyu.js +0 -3
@@ -1,6 +1,6 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/WorkspaceQuickOpen-CJmMBmK8.js","assets/rolldown-runtime-hePW80VL.js","assets/vendor-CSDKB7mU.js","assets/ui-preferences-0waeSO-S.js","assets/workspace-api-D8sJkiZB.js","assets/bootstrap-CedkNtRG.js","assets/TerminalPanel-B8j_r6-y.js","assets/index-uhJMXxqD.js","assets/index-Dqb2hNan.css","assets/terminal-transport-Dk5pYNX5.js","assets/tab-close-ITV4Cf4X.js","assets/WorkspaceExplorer-DVsNU0eu.js","assets/api-BQS4Dtrr.js","assets/workspace-navigation-DkVobhwg.js","assets/composer-drafts-BtMaVw8W.js","assets/LineReview-C_0ZpgCH.js","assets/MarkdownMessage-DGt5B-6D.js","assets/SettingsPage-Ca-qRSZa.js","assets/view-model-CWNiS4JN.js","assets/SettingsNavigation-C-tO5iXn.js","assets/SessionInspectorDrawer-CpVzaf_G.js"])))=>i.map(i=>d[i]);
2
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$t as t,A as n,An as r,At as i,Bt as a,Cn as o,Ct as s,D as c,Dn as l,Dt as u,E as d,Et as f,F as p,Fn as m,Ft as h,G as g,Gt as _,Ht as v,I as y,Kt as b,L as x,Lt as S,M as C,Mt as w,N as T,Nt as E,O as D,Ot as O,P as k,Pt as A,R as j,Rt as M,Sn as N,St as P,Tt as F,U as I,Ut as L,Vt as R,W as z,Wt as ee,Xt as B,Yt as te,Zt as ne,_t as re,an as V,cn as H,en as ie,fn as U,gt as ae,ht as oe,in as W,it as G,j as se,jt as ce,k as le,kn as ue,kt as de,ln as fe,mn as K,mt as pe,nn as me,nt as he,on as ge,pt as _e,qt as q,rn as ve,rt as J,st as ye,tn as Y,tt as be,ut as xe,vn as Se,wt as Ce,xn as we,yt as Te,z as Ee,zt as De}from"./vendor-CSDKB7mU.js";import{i as Oe,n as X,o as ke,s as Ae}from"./ui-preferences-0waeSO-S.js";import{n as je,t as Me}from"./index-uhJMXxqD.js";import{a as Ne,i as Pe,n as Fe,o as Ie,r as Le,s as Re,t as ze}from"./bootstrap-CedkNtRG.js";import{E as Be,F as Ve,I as He,K as Ue,N as We,R as Ge,U as Ke,V as qe,b as Je,ft as Ye,n as Xe,o as Ze,p as Qe,r as $e,u as et,ut as tt,w as Z,z as nt}from"./api-BQS4Dtrr.js";import{r as rt}from"./view-model-CWNiS4JN.js";import{A as it,B as at,C as ot,D as st,E as ct,F as lt,H as ut,M as dt,N as ft,O as pt,P as mt,R as ht,S as gt,T as _t,V as vt,_ as yt,a as bt,b as xt,c as St,d as Ct,f as wt,g as Tt,h as Et,i as Dt,j as Ot,k as kt,l as At,m as jt,o as Mt,p as Nt,r as Pt,s as Ft,u as It,v as Lt,w as Rt,y as zt,z as Bt}from"./SettingsNavigation-C-tO5iXn.js";import{a as Vt,i as Ht,n as Ut,t as Wt}from"./workspace-navigation-DkVobhwg.js";import{C as Gt,S as Kt,T as qt,_ as Jt,a as Yt,b as Xt,c as Zt,d as Qt,g as $t,h as en,i as tn,m as nn,o as rn,p as an,r as on,s as sn,t as cn,u as ln,v as un,w as dn,x as fn,y as pn}from"./transcript-view-model-Bq0nkxyu.js";import{a as mn,i as hn,n as gn,o as _n,r as vn,s as yn,t as bn}from"./composer-drafts-BtMaVw8W.js";import{t as xn}from"./latest-request-DXcYQW86.js";import{t as Sn}from"./terminal-transport-Dk5pYNX5.js";function Cn(e){return String(e).match(/[\d.\-+]*\s*(.*)/)[1]||``}function wn(e){return parseFloat(e)}var Q=l();function Tn({value:e,onChange:t}){let{locale:n}=Oe();return(0,Q.jsxs)(M,{value:e,onChange:(e,n)=>t(n),variant:`fullWidth`,"aria-label":X(n,`Thanh bên`,`Sidebar`),children:[(0,Q.jsx)(De,{value:`sessions`,label:X(n,`Phiên`,`Sessions`)}),(0,Q.jsx)(De,{value:`files`,label:X(n,`Tệp`,`Files`)}),(0,Q.jsx)(De,{value:`search`,label:X(n,`Tìm kiếm`,`Search`)})]})}var $=e(m(),1),En=(0,$.lazy)(()=>Me(()=>import(`./WorkspaceQuickOpen-CJmMBmK8.js`),__vite__mapDeps([0,1,2,3,4,5]))),Dn=(0,$.lazy)(()=>Me(()=>import(`./TerminalPanel-B8j_r6-y.js`),__vite__mapDeps([6,1,2,3,7,8,9,5,10]))),On=(0,$.lazy)(()=>Me(()=>import(`./WorkspaceExplorer-DVsNU0eu.js`),__vite__mapDeps([11,1,2,3,7,8,5,12,13,14,15,10,4]))),kn=52,An=36,jn=25,Mn=75,Nn=`piagent-webui-editor-width`;function Pn(){try{let e=Number(window.localStorage.getItem(Nn));return e>=jn&&e<=Mn?e:55}catch{return 55}}var Fn=e=>({color:e?`text.primary`:`text.secondary`,bgcolor:e?`action.selected`:`transparent`,"& .MuiButton-startIcon svg":{fontSize:16,color:e?`primary.main`:`inherit`}});function In({title:e,close:t,onClose:n}){return(0,Q.jsxs)(R,{sx:{display:`flex`,alignItems:`center`,gap:1,px:2,minHeight:48,borderBottom:1,borderColor:`divider`},children:[(0,Q.jsx)(S,{sx:{fontWeight:600,flex:1},children:e}),(0,Q.jsx)(L,{size:`small`,"aria-label":t,onClick:n,children:(0,Q.jsx)(h,{fontSize:`small`})})]})}function Ln({sessionRef:e,children:t,navigationHost:n,sidebarMode:r,onSection:o}){let{locale:s}=Oe(),c=fe(),l=i(c.breakpoints.up(`lg`)),[u,d]=(0,$.useState)(!1),[f,p]=(0,$.useState)(!1),[m,h]=(0,$.useState)(!1),[g,_]=(0,$.useState)(),v=(0,$.useRef)(null),[y,b]=(0,$.useState)(Pn),x=e=>{let t=Math.min(Mn,Math.max(jn,e));b(t);try{window.localStorage.setItem(Nn,String(Math.round(t)))}catch{}},C=e=>{let t=v.current?.getBoundingClientRect();if(!t)return;e.preventDefault(),document.body.style.cursor=`col-resize`,document.body.style.userSelect=`none`;let n=e=>x((e.clientX-t.left)/t.width*100),r=()=>{window.removeEventListener(`pointermove`,n),window.removeEventListener(`pointerup`,r),document.body.style.cursor=``,document.body.style.userSelect=``};window.addEventListener(`pointermove`,n),window.addEventListener(`pointerup`,r)};(0,$.useEffect)(()=>{let t=e=>{(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&e.key.toLowerCase()===`p`&&(e.preventDefault(),p(!0))},n=t=>{let n=t.detail;n?.sessionRef===e&&(_({path:n.path,line:n.line}),d(!0),o(`files`))};return window.addEventListener(`keydown`,t),window.addEventListener(Wt,n),()=>{window.removeEventListener(`keydown`,t),window.removeEventListener(Wt,n)}},[e]),(0,$.useEffect)(()=>{r!==`sessions`&&d(!0)},[r]);let w=(0,Q.jsx)($.Suspense,{fallback:(0,Q.jsx)(ee,{size:24}),children:(0,Q.jsx)(On,{sessionRef:e,target:g,navigationHost:l?n:null,sidebarMode:r,onHide:()=>{d(!1),o(`sessions`)},fill:l})}),T=(0,Q.jsx)($.Suspense,{fallback:(0,Q.jsx)(ee,{size:24}),children:(0,Q.jsx)(Dn,{sessionRef:e,onHide:()=>h(!1)})});return(0,Q.jsxs)(Q.Fragment,{children:[f&&(0,Q.jsx)($.Suspense,{fallback:(0,Q.jsx)(ee,{size:20}),children:(0,Q.jsx)(En,{sessionRef:e,onClose:()=>p(!1),onOpen:e=>{p(!1),d(!0),o(`files`),_({path:e})}})}),(0,Q.jsxs)(R,{sx:{position:`sticky`,top:kn,zIndex:2,height:An,display:`flex`,alignItems:`center`,gap:.5,px:1,bgcolor:`background.default`,borderBottom:1,borderColor:`divider`},children:[(0,Q.jsx)(a,{size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(A,{}),"aria-expanded":u,onClick:()=>{d(e=>!e),o(u?`sessions`:`files`)},sx:Fn(u),children:X(s,`Tệp`,`Files`)}),(0,Q.jsx)(a,{size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(E,{}),"aria-expanded":m,onClick:()=>h(e=>!e),sx:Fn(m),children:`Terminal`}),(0,Q.jsx)(R,{sx:{flex:1}}),l&&(0,Q.jsx)(S,{variant:`caption`,color:`text.disabled`,sx:{pr:.5,display:{xs:`none`,xl:`block`}},children:X(s,`⌘P mở file`,`⌘P to open a file`)})]}),(0,Q.jsxs)(R,{ref:v,sx:{display:`flex`,minWidth:0},children:[l&&(u||m)&&(0,Q.jsxs)(R,{component:`section`,"aria-label":X(s,`Editor và terminal`,`Editor and terminal`),sx:{position:`sticky`,top:88,alignSelf:`flex-start`,flexShrink:0,minWidth:0,width:`clamp(320px, ${y}%, calc(100% - 360px))`,height:`calc(100vh - 88px - var(--piagent-status-bar, 0px))`,display:`flex`,flexDirection:`column`,bgcolor:`background.default`,zIndex:1},children:[u&&(0,Q.jsx)(R,{sx:{flex:1,minHeight:0,overflow:`hidden`},children:w}),m&&(0,Q.jsx)(R,{sx:{flexShrink:0,maxHeight:u?`60%`:`100%`,overflow:`auto`,...u?{}:{flex:1}},children:T}),(0,Q.jsx)(R,{role:`separator`,"aria-orientation":`vertical`,"aria-label":X(s,`Kéo để đổi độ rộng editor`,`Drag to resize the editor`),"aria-valuenow":Math.round(y),"aria-valuemin":jn,"aria-valuemax":Mn,tabIndex:0,onPointerDown:C,onKeyDown:e=>{(e.key===`ArrowLeft`||e.key===`ArrowRight`)&&(e.preventDefault(),x(y+(e.key===`ArrowLeft`?-2:2)))},sx:{position:`absolute`,top:0,right:-3,bottom:0,width:6,cursor:`col-resize`,zIndex:2,borderRight:1,borderColor:`divider`,"&:hover, &:focus-visible":{borderColor:`primary.main`,outline:`none`}}})]}),(0,Q.jsx)(R,{sx:{flex:1,minWidth:0},children:t})]}),!l&&(0,Q.jsxs)(ce,{anchor:`bottom`,open:m,onClose:()=>h(!1),children:[(0,Q.jsx)(In,{title:`Terminal`,close:X(s,`Ẩn terminal`,`Hide terminal`),onClose:()=>h(!1)}),m&&T]}),!l&&(0,Q.jsxs)(ce,{anchor:`left`,open:u,onClose:()=>d(!1),slotProps:{paper:{sx:{width:`min(96vw, 800px)`}}},children:[(0,Q.jsx)(In,{title:X(s,`Tệp`,`Files`),close:X(s,`Đóng`,`Close`),onClose:()=>d(!1)}),u&&w]})]})}var Rn=e=>e.name??e.repo;function zn(e,t,n){let r=n===`vi`,i=t?` ${t}`:``,a=r?` Admin Studio đã được báo.`:` Studio administrators were told.`,o=t=>e.filter(e=>e.kind===t).map(Rn).join(`, `),s=[],c=o(`other_team`),l=o(`unlisted`),u=o(`unregistered`),d=o(`no_repository`);return c&&s.push(r?`${c} thuộc team khác, không phải team${i} của key này.`:`${c} belongs to another team, not this key's team${i}.`),l&&s.push(r?`${l} chưa có trong danh sách project của team${i}.`:`${l} is not in the project list of team${i}.`),u&&s.push(r?`${u} chưa được đăng ký cho team${i}.`:`${u} is not registered to team${i}.`),d&&s.push(r?`Không xác định được project của thư mục ${d}.`:`The project of folder ${d} could not be identified.`),s.join(` `)+a}function Bn({session:e,locale:t}){let n=e.managedProjectWarning;return n?(0,Q.jsx)(v,{severity:`warning`,role:`status`,sx:{maxWidth:820,mx:`auto`,mb:1,py:0},children:zn(n.warnings,n.team,t)}):null}var Vn=q((0,Q.jsx)(`path`,{d:`M16.5 6.75v10.58c0 2.09-1.53 3.95-3.61 4.15-2.39.23-4.39-1.64-4.39-3.98V5.14c0-1.31.94-2.5 2.24-2.63 1.5-.15 2.76 1.02 2.76 2.49v10.5c0 .55-.45 1-1 1s-1-.45-1-1V6.75c0-.41-.34-.75-.75-.75s-.75.34-.75.75v8.61c0 1.31.94 2.5 2.24 2.63 1.5.15 2.76-1.02 2.76-2.49V5.17c0-2.09-1.53-3.95-3.61-4.15C9.01.79 7 2.66 7 5v12.27c0 2.87 2.1 5.44 4.96 5.71 3.29.3 6.04-2.26 6.04-5.48V6.75c0-.41-.34-.75-.75-.75s-.75.34-.75.75`}),`AttachFileRounded`),Hn=q((0,Q.jsx)(`path`,{d:`M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2m4.3 14.3c-.39.39-1.02.39-1.41 0L12 13.41 9.11 16.3c-.39.39-1.02.39-1.41 0a.996.996 0 0 1 0-1.41L10.59 12 7.7 9.11a.996.996 0 0 1 0-1.41c.39-.39 1.02-.39 1.41 0L12 10.59l2.89-2.89c.39-.39 1.02-.39 1.41 0s.39 1.02 0 1.41L13.41 12l2.89 2.89c.38.38.38 1.02 0 1.41`}),`CancelRounded`),Un=q((0,Q.jsx)(`path`,{d:`M13 19V7.83l4.88 4.88c.39.39 1.03.39 1.42 0s.39-1.02 0-1.41l-6.59-6.59a.996.996 0 0 0-1.41 0l-6.6 6.58c-.39.39-.39 1.02 0 1.41s1.02.39 1.41 0L11 7.83V19c0 .55.45 1 1 1s1-.45 1-1`}),`ArrowUpwardRounded`),Wn=q((0,Q.jsx)(`path`,{d:`M2 4v16h20V4zm18 4.67h-2.5V6H20zm-2.5 2H20v2.67h-2.5zM4 6h11.5v12H4zm13.5 12v-2.67H20V18z`}),`ViewSidebarOutlined`),Gn=q((0,Q.jsx)(`path`,{d:`M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m3 14H9c-.55 0-1-.45-1-1V9c0-.55.45-1 1-1h6c.55 0 1 .45 1 1v6c0 .55-.45 1-1 1`}),`StopCircleRounded`),Kn=q((0,Q.jsx)(`path`,{d:`M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z`}),`Person`);function qn(e){return N(`MuiAvatar`,e)}we(`MuiAvatar`,[`root`,`colorDefault`,`circular`,`rounded`,`square`,`img`,`fallback`]);var Jn=e=>{let{classes:t,variant:n,colorDefault:r}=e;return K({root:[`root`,n,r&&`colorDefault`],img:[`img`],fallback:[`fallback`]},qn,t)},Yn=H(`div`,{name:`MuiAvatar`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,t[n.variant],n.colorDefault&&t.colorDefault]}})(V(({theme:e})=>({position:`relative`,display:`flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0,width:40,height:40,fontFamily:e.typography.fontFamily,fontSize:e.typography.pxToRem(20),lineHeight:1,borderRadius:`50%`,overflow:`hidden`,userSelect:`none`,variants:[{props:{variant:`rounded`},style:{borderRadius:(e.vars||e).shape.borderRadius}},{props:{variant:`square`},style:{borderRadius:0}},{props:{colorDefault:!0},style:{color:(e.vars||e).palette.background.default,"@media (forced-colors: active)":{boxSizing:`border-box`,border:`1px solid ButtonBorder`},...e.vars?{backgroundColor:e.vars.palette.Avatar.defaultBg}:{backgroundColor:e.palette.grey[400],...e.applyStyles(`dark`,{backgroundColor:e.palette.grey[600]})}}}]}))),Xn=H(`img`,{name:`MuiAvatar`,slot:`Img`})({width:`100%`,height:`100%`,textAlign:`center`,objectFit:`cover`,color:`transparent`,textIndent:1e4}),Zn=H(Kn,{name:`MuiAvatar`,slot:`Fallback`})({width:`75%`,height:`75%`});function Qn(e,t,n,r){let[i,a]=$.useState(!1);return $.useEffect(()=>{if(!e&&!t)return;a(!1);let i=!0,o=new Image;return o.onload=()=>{i&&a(`loaded`)},o.onerror=()=>{i&&a(`error`)},o.crossOrigin=n,o.referrerPolicy=r,o.src=e,t&&(o.srcset=t),()=>{i=!1}},[n,r,e,t]),i}var $n=$.forwardRef(function(e,t){let n=ge({props:e,name:`MuiAvatar`}),{alt:r,children:i,className:a,component:s=`div`,slots:c={},slotProps:l={},sizes:u,src:d,srcSet:f,variant:p=`circular`,...m}=n,h=null,g={...n,component:s,variant:p},{crossOrigin:_,referrerPolicy:v}=(typeof l.img==`function`?l.img(g):l.img)??{},y=Qn(d,f,_,v),b=d||f,x=b&&y!==`error`;g.colorDefault=!x,delete g.ownerState;let S=Jn(g),C={slots:c,slotProps:l},[w,T]=ne(`root`,{ref:t,className:o(S.root,a),elementType:Yn,externalForwardedProps:{...C,component:s,...m},ownerState:g}),[E,D]=ne(`img`,{className:S.img,elementType:Xn,externalForwardedProps:C,additionalProps:{alt:r,src:d,srcSet:f,sizes:u},ownerState:g}),[O,k]=ne(`fallback`,{className:S.fallback,elementType:Zn,externalForwardedProps:C,shouldForwardComponentProp:!0,ownerState:g});return h=x?(0,Q.jsx)(E,{...D}):i||i===0?i:b&&r?r[0]:(0,Q.jsx)(O,{...k}),(0,Q.jsx)(w,{...T,children:h})});function er(e){return N(`MuiCollapse`,e)}we(`MuiCollapse`,[`root`,`horizontal`,`vertical`,`entered`,`hidden`,`wrapper`,`wrapperInner`]);var tr={},nr=e=>{let{orientation:t,classes:n}=e;return K({root:[`root`,t],entered:[`entered`],hidden:[`hidden`],wrapper:[`wrapper`,t],wrapperInner:[`wrapperInner`,t]},er,n)},rr=H(`div`,{name:`MuiCollapse`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,t[n.orientation],n.state===`entered`&&t.entered,n.state===`exited`&&!n.in&&n.collapsedSize===`0px`&&t.hidden]}})(V(({theme:e})=>({height:0,overflow:`hidden`,transition:e.transitions.create(`height`),variants:[{props:{orientation:`horizontal`},style:{height:`auto`,width:0,transition:e.transitions.create(`width`)}},{props:{state:`entered`},style:{height:`auto`,overflow:`visible`}},{props:{state:`entered`,orientation:`horizontal`},style:{width:`auto`}},{props:({ownerState:e})=>e.state===`exited`&&!e.in&&e.collapsedSize===`0px`,style:{visibility:`hidden`}}]}))),ir=H(`div`,{name:`MuiCollapse`,slot:`Wrapper`})({display:`flex`,width:`100%`,variants:[{props:{orientation:`horizontal`},style:{width:`auto`,height:`100%`}}]}),ar=H(`div`,{name:`MuiCollapse`,slot:`WrapperInner`})({width:`100%`,variants:[{props:{orientation:`horizontal`},style:{width:`auto`,height:`100%`}}]}),or=$.forwardRef(function(e,t){let n=ge({props:e,name:`MuiCollapse`}),{addEndListener:r,children:i,className:a,collapsedSize:s=`0px`,component:c,disablePrefersReducedMotion:l=!1,easing:u,in:d,onEnter:f,onEntered:p,onEntering:m,onExit:h,onExited:g,onExiting:_,orientation:v=`vertical`,slots:y=tr,slotProps:x=tr,style:S,timeout:C=U.standard,TransitionComponent:T=w,...E}=n,D={...n,orientation:v,collapsedSize:s},O=nr(D),k=fe(),A=$.useRef(null),j=$.useRef(null),M=typeof s==`number`?`${s}px`:s,N=v===`horizontal`,P=N?`width`:`height`,F=b(k.motion.reducedMotion,l),I=$.useRef(null),L=ve(t,I),R=()=>A.current?A.current[N?`clientWidth`:`clientHeight`]:0,z=me(I,(e,t)=>{A.current&&N&&(A.current.style.position=`absolute`),e.style[P]=M,f&&f(e,t)}),ee=me(I,(e,t)=>{let n=R();A.current&&N&&(A.current.style.position=``);let{duration:r,easing:i}=ie({style:S,timeout:C,easing:u},{mode:`enter`});if(C===`auto`&&!F.shouldReduceMotion){let e=k.transitions.getAutoHeightDuration(n);j.current=e}else j.current=null;let a=F.getTransitionTiming({duration:j.current??r,delay:void 0});e.style.transitionDuration=typeof a.duration==`string`?a.duration:`${a.duration}ms`,e.style[P]=`${n}px`,e.style.transitionTimingFunction=i,m&&m(e,t)}),B=me(I,(e,t)=>{e.style[P]=`auto`,p&&p(e,t)}),te=me(I,e=>{e.style[P]=`${R()}px`,h&&h(e)}),re=me(I,g),V=me(I,e=>{let t=R(),{duration:n,easing:r}=ie({style:S,timeout:C,easing:u},{mode:`exit`});if(C===`auto`&&!F.shouldReduceMotion){let e=k.transitions.getAutoHeightDuration(t);j.current=e}else j.current=null;let i=F.getTransitionTiming({duration:j.current??n,delay:void 0});e.style.transitionDuration=typeof i.duration==`string`?i.duration:`${i.duration}ms`,e.style[P]=M,e.style.transitionTimingFunction=r,_&&_(e)}),H=r?e=>{r(I.current,e)}:void 0,ae={slots:y,slotProps:x,component:c},[oe,W]=ne(`root`,{ref:L,className:o(O.root,a),elementType:rr,externalForwardedProps:ae,ownerState:D,additionalProps:{style:{[N?`minWidth`:`minHeight`]:M,...S}}}),[G,se]=ne(`wrapper`,{ref:A,className:O.wrapper,elementType:ir,externalForwardedProps:ae,ownerState:D}),[ce,le]=ne(`wrapperInner`,{className:O.wrapperInner,elementType:ar,externalForwardedProps:ae,ownerState:D});return(0,Q.jsx)(T,{in:d,onEnter:z,onEntered:B,onEntering:ee,onExit:te,onExited:re,onExiting:V,addEndListener:H,getAutoTimeout:C===`auto`?()=>j.current:void 0,reduceMotion:F.shouldReduceMotion,nodeRef:I,timeout:C===`auto`?null:C,...E,children:(e,{ownerState:t,...n})=>{let r={...D,state:e};return(0,Q.jsx)(oe,{...W,className:o(W.className,{entered:O.entered,exited:!d&&M===`0px`&&O.hidden}[e]),ownerState:r,...n,children:(0,Q.jsx)(G,{...se,ownerState:r,children:(0,Q.jsx)(ce,{...le,ownerState:r,children:i})})})}})});or&&(or.muiSupportAuto=!0);function sr(e,t,n){return at(e,t,n)}var cr=new Set([`company-quota`,`company-provider-limit`,`company-account`,`company-busy`,`company-trial-limit`,`company-key`,`company-policy`,`company-rejected`,`company-unreachable`,`company-service`,`company-config-changed`,`company-failed`]);function lr(e){return cr.has(e)||!e.startsWith(`company-`)}function ur(e,t){return vt(e,t)}var dr=Bt,fr={"session-revision-stale":[`Danh sách cuộc trò chuyện vừa thay đổi. Gửi lại tin nhắn.`,`The conversation list just changed. Send the message again.`],"catalog-unavailable":[`Danh sách cuộc trò chuyện chưa tải xong. Thử lại sau vài giây.`,`The conversation list has not loaded yet. Try again in a few seconds.`],"session-model-mismatch":[`Cuộc trò chuyện đã tạo nhưng đang dùng model khác model đã chọn, nên tin nhắn chưa được gửi.`,`The conversation was created with a different model than the one chosen, so the message was not sent.`],"gateway-command-response-timeout":[`Piagent chưa xác nhận được cuộc trò chuyện mới sau 2 phút; nó có thể đã được tạo và đang chạy. Xem danh sách cuộc trò chuyện bên trái trước khi gửi lại.`,`Piagent could not confirm the new conversation within 2 minutes; it may have been created and be running. Check the conversation list before sending again.`],"session-command-expired":[`Yêu cầu chờ quá lâu nên đã hết hạn. Gửi lại tin nhắn.`,`The request waited too long and expired. Send the message again.`]};function pr(e,t){let n=e.startsWith(`company-`)?sr(e,null,t):null;if(n)return`${n.title}: ${n.text}`;let r=fr[e]??dr[e];return r?X(t,...r):`${X(t,`Chưa tạo được cuộc trò chuyện`,`The conversation could not be created`)} (${e}).`}function mr(e,t){let n=dr[e?.reasonCode??``];return n?X(t,...n):null}var hr=(e,t)=>e?.state===`connecting`?X(t,`Đang kết nối phiên công ty…`,`Connecting the company runtime…`):mr(e,t)??X(t,`Chưa kết nối phiên công ty. Bấm để kết nối.`,`The company runtime is not connected. Select to connect.`);function gr({locale:e,onConnected:t}){let[n,r]=(0,$.useState)(),[i,o]=(0,$.useState)(!1),s=(0,$.useRef)(!1),c=()=>{s.current&&(s.current=!1,t())};if((0,$.useEffect)(()=>{let e=!0,t=()=>void Qe().then(t=>{e&&(r(t),t?.state===`ready`?c():t&&(s.current=!0))}).catch(()=>void 0);t();let n=window.setInterval(t,5e3);return()=>{e=!1,window.clearInterval(n)}},[]),!n||n.state===`ready`||n.state===`unconfigured`)return null;let l=async()=>{o(!0);try{let e=await Ze();r(e),e.state===`ready`&&c()}catch{r(await Qe().catch(()=>null)??n)}finally{o(!1)}},u=mr(n,e),d=i||n.state===`connecting`;return(0,Q.jsxs)(v,{severity:`warning`,role:`status`,sx:{mb:2},action:(0,Q.jsx)(a,{color:`inherit`,size:`small`,disabled:d,onClick:()=>void l(),sx:{whiteSpace:`nowrap`},children:d?X(e,`Đang kết nối…`,`Connecting…`):X(e,`Kết nối lại`,`Reconnect`)}),children:[X(e,`Chế độ công ty đang tắt nên chưa đọc hay gửi tiếp được cuộc trò chuyện này. Bấm Kết nối lại; macOS có thể hỏi quyền đọc key một lần.`,`Company mode is not running, so this conversation cannot be read or continued yet. Select Reconnect; macOS may ask once to read the key.`),u&&(0,Q.jsxs)(Q.Fragment,{children:[` `,u]})]})}function _r(e){return e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&e.keyCode!==229}var vr=q((0,Q.jsx)(`path`,{d:`M12 7V5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2zM6 19H4v-2h2zm0-4H4v-2h2zm0-4H4V9h2zm0-4H4V5h2zm4 12H8v-2h2zm0-4H8v-2h2zm0-4H8V9h2zm0-4H8V5h2zm9 12h-7v-2h2v-2h-2v-2h2v-2h-2V9h7c.55 0 1 .45 1 1v8c0 .55-.45 1-1 1m-1-8h-2v2h2zm0 4h-2v2h2z`}),`BusinessRounded`),yr=q((0,Q.jsx)(`path`,{d:`m19 9 1.25-2.75L23 5l-2.75-1.25L19 1l-1.25 2.75L15 5l2.75 1.25zm0 6-1.25 2.75L15 19l2.75 1.25L19 23l1.25-2.75L23 19l-2.75-1.25zm-7.5-5.5L9 4 6.5 9.5 1 12l5.5 2.5L9 20l2.5-5.5L17 12zm-1.51 3.49L9 15.17l-.99-2.18L5.83 12l2.18-.99L9 8.83l.99 2.18 2.18.99z`}),`AutoAwesomeOutlined`),br=q((0,Q.jsx)(`path`,{d:`M8 16h8v2H8zm0-4h8v2H8zm6-10H6c-1.1 0-2 .9-2 2v16c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8zm4 18H6V4h7v5h5z`}),`DescriptionOutlined`);function xr(e,t){let n=e.slice(0,t),r=/(^|[\s(])@"([^"\n]*)$/.exec(n);if(r)return{start:r.index+r[1].length,end:e[t]===`"`?t+1:t,query:r[2],quoted:!0};let i=/(^|[\s(])@([^\s"]*)$/.exec(n);return i?{start:i.index+i[1].length,end:t+(/^[^\s"]*/.exec(e.slice(t))?.[0].length??0),query:i[2],quoted:!1}:null}function Sr(e,t,n){let r=t.quoted||/\s/.test(n.value),i=r?`@"${n.value}"`:`@${n.value}`,a=n.kind===`directory`,o=e.slice(t.end),s=a||/^\s/.test(o)?``:` `;return{text:e.slice(0,t.start)+i+s+o,caret:t.start+i.length+s.length-(a&&r?1:0)}}function Cr(e,t){let n=e.slice(0,t);return/^\/[^\s/]*$/.test(n)?{start:0,end:t+(/^[^\s]*/.exec(e.slice(t))?.[0].length??0),query:n.slice(1),quoted:!1}:null}function wr(e,t,n){let r=n.kind===`skill`?`/skill:${n.name}`:`/${n.name}`,i=e.slice(t.end);return{text:r+(/^\s/.test(i)?``:` `)+i,caret:r.length+1}}var Tr=20,Er=e=>e.normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase();function Dr(e,t,n){let r=Er(t.replace(/^skill:/,``)),i=e=>Er(e.name).startsWith(r)?0:Er(e.name).includes(r)?1:Er(e.description).includes(r)?2:3,a=e=>e.origin===`piagent`?`Piagent`:e.plugin?`${e.plugin} · ${e.origin===`claude`?`Claude`:`Codex`} plugin`:`${e.scope===`user`?`~/`:``}.${e.origin===`pi`?`pi`:e.origin}`;return e.filter(e=>i(e)<3&&(!t.startsWith(`skill:`)||e.kind===`skill`)).sort((e,t)=>i(e)-i(t)||e.name.localeCompare(t.name)).slice(0,Tr).map(e=>({key:`${e.kind}:${e.name}`,icon:e.kind,label:e.kind===`skill`?`/skill:${e.name}`:`/${e.name}`,hint:e.argumentHint,detail:`${e.description}${e.description?` · `:``}${e.kind===`skill`?`skill`:X(n,`lệnh`,`command`)} ${a(e)}`,apply:(t,n)=>wr(t,n,e)}))}function Or({projectRef:e,value:t,onChange:n,locale:r,builtIns:i=[]}){let a=(0,$.useRef)(null),o=(0,$.useId)(),[s,c]=(0,$.useState)(null),[l,u]=(0,$.useState)(!1),[d,f]=(0,$.useState)(null),[p,m]=(0,$.useState)(0),[h,g]=(0,$.useState)(null),[_,v]=(0,$.useState)(null),y=e&&s!==null&&s<=t.length?s:null,b=y===null?null:Cr(t,y),x=y===null||b?null:xr(t,y),C=b??x,w=b?`command`:`path`,T=C&&`${w}:${C.start}`!==d?C:null,D=T&&w===`path`?T.query:null;(0,$.useEffect)(()=>{if(D===null||!e){g(null);return}let t=new AbortController,n=setTimeout(()=>{Z(e,D,t.signal).then(e=>{g({query:D,items:e.suggestions.map(e=>({key:e.value,label:e.label,hint:null,icon:e.kind,detail:e.detail.slice(0,Math.max(0,e.detail.length-e.label.replace(/\/$/,``).length)),apply:(t,n)=>Sr(t,n,e)}))}),m(0)}).catch(()=>{t.signal.aborted||g({query:D,items:[]})})},90);return()=>{clearTimeout(n),t.abort()}},[e,D]);let O=!!(T&&w===`command`&&e&&_?.projectRef!==e);(0,$.useEffect)(()=>{if(!O||!e)return;let t=new AbortController;return Be(e,t.signal).then(t=>v({projectRef:e,list:t.commands})).catch(()=>{t.signal.aborted||v({projectRef:e,list:[]})}),()=>t.abort()},[O,e]);let k=T?w===`path`?h?.items??null:_&&_.projectRef===e?Dr([...i,..._.list.filter(e=>!i.some(t=>t.name===e.name))],T.query,r):null:null;(0,$.useEffect)(()=>{m(0)},[w,T?.query]);let j=!!(l&&T&&k&&a.current),M=j?k:[];(0,$.useEffect)(()=>{j&&document.getElementById(`${o}-${p}`)?.scrollIntoView({block:`nearest`})},[j,p,o]);let N=(0,$.useRef)(null);(0,$.useLayoutEffect)(()=>{let e=N.current,n=a.current;!e||!n||e.text!==t||(N.current=null,n.focus(),n.setSelectionRange(e.caret,e.caret),c(e.caret))},[t]);let P=e=>{if(!T)return;let r=e.apply(t,T);N.current=r,n(r.text),c(r.caret)},F=e=>!j||e.nativeEvent.isComposing||e.keyCode===229?!1:e.key===`Escape`?(e.preventDefault(),f(`${w}:${T.start}`),!0):M.length?e.key===`ArrowDown`||e.key===`ArrowUp`?(e.preventDefault(),m(t=>(t+(e.key===`ArrowDown`?1:M.length-1))%M.length),!0):(e.key===`Enter`||e.key===`Tab`)&&!e.shiftKey&&!e.altKey&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),P(M[Math.min(p,M.length-1)]),!0):!1,I=e=>e===`directory`?(0,Q.jsx)(A,{fontSize:`small`,color:`primary`}):e===`file`?(0,Q.jsx)(br,{fontSize:`small`,color:`action`}):e===`skill`?(0,Q.jsx)(yr,{fontSize:`small`,color:`secondary`}):(0,Q.jsx)(E,{fontSize:`small`,color:`primary`}),L=w===`command`?X(r,`Lệnh và skill`,`Commands and skills`):X(r,`File và folder`,`Files and folders`),z=a.current,ee=(0,Q.jsx)(oe,{open:j,anchorEl:z,placement:`top-start`,disablePortal:!0,sx:{zIndex:1350,width:Math.min(640,z?.clientWidth??640)},modifiers:[{name:`offset`,options:{offset:[0,10]}}],children:(0,Q.jsxs)(te,{elevation:8,sx:{borderRadius:1,overflow:`hidden`,display:`flex`,flexDirection:`column`,maxHeight:340},children:[(0,Q.jsx)(S,{variant:`caption`,color:`text.secondary`,sx:{px:1.5,pt:1,pb:.5},children:w===`command`?X(r,`Lệnh và skill của project và trên máy này · Tab để chọn`,`Commands and skills of the project and on this computer · Tab to pick`):X(r,`File và folder · gõ ~/ hoặc / để chọn folder khác trên máy · Tab để chọn`,`Files and folders · type ~/ or / for other folders on this computer · Tab to pick`)}),M.length?(0,Q.jsx)(R,{component:`ul`,role:`listbox`,id:o,"aria-label":L,sx:{listStyle:`none`,m:0,p:.5,pt:0,overflowY:`auto`},children:M.map((e,t)=>(0,Q.jsxs)(R,{component:`li`,id:`${o}-${t}`,role:`option`,"aria-selected":t===p,onMouseDown:e=>e.preventDefault(),onMouseEnter:()=>m(t),onClick:()=>P(e),sx:{display:`flex`,alignItems:`center`,gap:1,minWidth:0,px:1,py:.55,borderRadius:1,cursor:`pointer`,bgcolor:t===p?`action.selected`:`transparent`},children:[I(e.icon),(0,Q.jsx)(S,{noWrap:!0,sx:{flexShrink:0,maxWidth:`55%`,fontSize:14,fontWeight:600},children:e.label}),e.hint&&(0,Q.jsx)(S,{noWrap:!0,variant:`caption`,sx:{flexShrink:0,maxWidth:`25%`,fontFamily:`monospace`},children:e.hint}),(0,Q.jsx)(S,{noWrap:!0,variant:`caption`,color:`text.secondary`,sx:{minWidth:0},children:e.detail})]},e.key))}):(0,Q.jsx)(S,{variant:`body2`,color:`text.secondary`,sx:{px:1.5,pb:1.25},children:w===`command`?X(r,`Không có lệnh hoặc skill khớp`,`No matching command or skill`):X(r,`Không có file hoặc folder khớp`,`No matching file or folder`)})]})}),B=e=>c(e.target.selectionStart??null);return{inputRef:a,menu:ee,onKeyDown:F,track:B,inputProps:{onFocus:()=>u(!0),onBlur:()=>u(!1)},htmlInput:{onSelect:B,"aria-autocomplete":`list`,"aria-controls":j&&M.length?o:void 0,"aria-activedescendant":j&&M.length?`${o}-${p}`:void 0}}}var kr=`agent_watch_managed`;function Ar(e,t,n){return e===`native-project-picker-unavailable`||e===`project-import-picker-failed`?X(n,`Không mở được hộp chọn thư mục của máy. Thử lại; nếu vẫn lỗi, mở cuộc trò chuyện từ Terminal trong thư mục đó (pi hoặc piagent studio).`,`The folder picker could not open. Try again; if it still fails, start a conversation from a Terminal in that folder (pi or piagent studio).`):e===`project-import-folder-invalid`?X(n,`Không dùng được thư mục này: thư mục gốc của ổ đĩa hoặc một liên kết (symlink). Chọn thư mục thật của project.`,`This folder cannot be used: a drive's root or a symbolic link. Choose the project's real folder.`):t===429?X(n,`Thao tác quá nhanh. Đợi vài giây rồi thử lại.`,`Too many attempts. Wait a few seconds and try again.`):X(n,`Không thể thêm thư mục. Thử lại; nếu vẫn lỗi, chạy piagent dashboard doctor.`,`Could not add this folder. Try again; if it still fails, run piagent dashboard doctor.`)}var jr=[[`Đọc project này (chỉ đọc) và ghi lại project context.`,`Read this project (read-only) and record the project context.`],[`Review diff hiện tại. Chỉ đọc.`,`Review the current diff. Read-only.`],[`Chạy test của project và giải thích lỗi nếu có.`,`Run the project's tests and explain any failure.`],[`Lập plan cho việc sau, chưa sửa code: `,`Plan this change before editing any code: `]];function Mr({active:e,defaultProjectRef:t,busy:n,error:r,onCancel:i,onCreate:o}){let{locale:s}=Oe(),[c,l]=(0,$.useState)(),[u,d]=(0,$.useState)(void 0),[f,m]=(0,$.useState)(!1),h=u===null&&c?.models.length===1&&c.models[0].provider===`agent_watch_managed`,[g,_]=(0,$.useState)(!1),[v,b]=(0,$.useState)(``),[C,w]=(0,$.useState)(``),[T,E]=(0,$.useState)(`high`),[D,O]=(0,$.useState)(!1),[A,M]=(0,$.useState)(!1),[N,F]=(0,$.useState)(null),[I,z]=(0,$.useState)(()=>mn(gn)),B=e=>{z(e),yn(gn,e)},[te,ne]=(0,$.useState)(null),[V,H]=(0,$.useState)(()=>hn(`new-chat`)??[]),[ie,U]=(0,$.useState)(null);(0,$.useEffect)(()=>{_n(gn,V.length?V:null)},[V]);let[ae,oe]=(0,$.useState)(!1),W=(0,$.useRef)(0),[se,ce]=(0,$.useState)(null),[le,ue]=(0,$.useState)(null),[fe,K]=(0,$.useState)(!1),[me,ge]=(0,$.useState)(null);(0,$.useEffect)(()=>{if(!e)return;let n=new AbortController;return l(void 0),_(!1),ge(null),U(null),oe(!1),O(!1),W.current=0,He(n.signal).then(e=>{n.signal.aborted||(l(e),b(e.projects.some(e=>e.projectRef===t)?t:e.projects[0]?.projectRef??``),w(e.defaultModelRef??``),E(e.defaultThinkingLevel??`high`),F(null),M(!1))}).catch(()=>{n.signal.aborted||_(!0)}),d(void 0),Qe(n.signal).then(e=>{n.signal.aborted||d(e)}).catch(()=>{n.signal.aborted||d(null)}),()=>n.abort()},[e,t]),(0,$.useEffect)(()=>{if(!e)return;let t=e=>{pn(e.dataTransfer)&&e.preventDefault()};return window.addEventListener(`dragover`,t),window.addEventListener(`drop`,t),()=>{window.removeEventListener(`dragover`,t),window.removeEventListener(`drop`,t)}},[e]);let q=c?.projects.find(e=>e.projectRef===v),ve=Or({projectRef:q?.projectRef,value:I,onChange:B,locale:s}),Y=c?.models.find(e=>e.modelRef===C),be=!h&&Y?.provider===kr,Se=h?[]:c?.models.filter(e=>e.provider===kr)??[],we=(h||be)&&Y?.managedFast===!0,De=h?c?.models??[]:c?.models.filter(e=>e.provider!==kr)??[],ke=async()=>{m(!0);try{let e=await Ze().catch(()=>null),t=await He();l(t),d(e??await Qe().catch(()=>null));let n=t.models.find(e=>e.provider===kr);n&&(w(n.modelRef),Ne())}catch{_(!0)}finally{m(!1)}},Ae=c?.models.find(e=>e.modelRef===c.defaultModelRef),je=(0,$.useMemo)(()=>Y?.thinkingLevels??[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],[Y]);(0,$.useEffect)(()=>{je.includes(T)||E(je.includes(`high`)?`high`:je[0]??`off`)},[C,je]);let Me=e=>t=>{ce(e),ue(t.currentTarget)},Ne=()=>{ce(null),ue(null)},Pe=async()=>{K(!0),ge(null);try{let e=await et(),t=e.projects?.length?e.projects:[e.project];l(e=>e&&{...e,projects:[...e.projects.filter(e=>!t.some(t=>t.projectRef===e.projectRef)),...t]}),b(e.project.projectRef),Ne()}catch(e){e instanceof Xe&&e.status===409?ge(null):ge(Ar(e instanceof Xe?e.code:null,e instanceof Xe?e.status:0,s))}finally{K(!1)}},Fe=e=>{if(!e?.length)return;let t=[...V],n=!1,r=null;for(let i of[...e]){if(t.some(e=>e.name===i.name&&e.size===i.size&&e.lastModified===i.lastModified))continue;let e=Jt(i.name);if(`refused`in e){r=`${i.name}: ${fn(e.refused,s)}`;continue}if(t.length===4){n=!0;continue}t.push(i)}H(t),U(r??(n?X(s,`Mỗi tin nhắn nhận tối đa 4 file.`,`Each message accepts at most 4 files.`):null))},Ie=!n&&!g&&V.length<4,Le=(0,$.useRef)(!1),Re=()=>{Le.current||n||!q||!I.trim()||(Le.current=!0,Promise.resolve(o({projectRef:v,placeRef:q.placeRef,modelRef:C||null,thinkingLevel:T,permissionMode:N,...we&&A?{fast:!0}:{},message:I,files:V})).finally(()=>{Le.current=!1}))};return(0,Q.jsxs)(R,{sx:{minHeight:`calc(100vh - 68px)`,display:`flex`,flexDirection:`column`},children:[(0,Q.jsx)(R,{sx:{p:{xs:1.5,sm:2}},children:(0,Q.jsx)(L,{"aria-label":X(s,`Quay lại`,`Back`),onClick:i,children:(0,Q.jsx)(Ee,{})})}),(0,Q.jsxs)(P,{sx:{flex:1,alignItems:`center`,justifyContent:`center`,px:2,pb:{xs:5,md:12}},spacing:4,children:[(0,Q.jsxs)(P,{spacing:1.75,sx:{alignItems:`center`},children:[(0,Q.jsx)(ut,{size:44}),(0,Q.jsx)(S,{component:`h1`,sx:{fontSize:{xs:`1.9rem`,md:`2.3rem`},fontWeight:650,letterSpacing:`-.04em`,textAlign:`center`},children:X(s,`Hôm nay làm gì?`,`What should we work on?`)}),(0,Q.jsx)(S,{color:`text.secondary`,sx:{textAlign:`center`,maxWidth:520,fontSize:14.5},children:X(s,`Nói việc bằng lời thường. Guard kiểm tra mọi tool call; việc rủi ro chờ bạn duyệt.`,`Say what you need in plain language. The guard checks every tool call; risky actions wait for you.`)})]}),(0,Q.jsxs)(R,{sx:{position:`relative`,width:`100%`,maxWidth:820,border:1,borderColor:ae?`primary.main`:`divider`,borderStyle:ae?`dashed`:`solid`,borderRadius:2.5,bgcolor:`background.paper`,p:1.5,boxShadow:`0 24px 60px -24px rgba(0,0,0,.55)`,transition:`border-color .16s, box-shadow .16s`,"&:focus-within":{borderColor:`rgba(var(--piagent-palette-primary-mainChannel) / .55)`,boxShadow:`0 0 0 4px rgba(var(--piagent-palette-primary-mainChannel) / .12), 0 24px 60px -24px rgba(0,0,0,.55)`}},onDragEnter:e=>{pn(e.dataTransfer)&&(W.current+=1,oe(!0))},onDragOver:e=>{pn(e.dataTransfer)&&(e.preventDefault(),e.dataTransfer.dropEffect=Ie?`copy`:`none`)},onDragLeave:e=>{pn(e.dataTransfer)&&(--W.current,W.current<=0&&(W.current=0,oe(!1)))},onDrop:e=>{pn(e.dataTransfer)&&(e.preventDefault(),W.current=0,oe(!1),Ie&&Fe(e.dataTransfer.files))},children:[ae&&(0,Q.jsxs)(R,{role:`status`,sx:{position:`absolute`,inset:0,zIndex:3,display:`grid`,alignContent:`center`,justifyItems:`center`,gap:.5,borderRadius:1,bgcolor:`background.paper`,opacity:.96,pointerEvents:`none`,textAlign:`center`},children:[(0,Q.jsx)(S,{sx:{fontWeight:650},children:Ie?X(s,`Thả tài liệu vào đây`,`Drop documents here`):V.length>=4?X(s,`Đã đủ 4 file cho tin nhắn đầu tiên`,`The first message already holds 4 files`):X(s,`Chưa nhận file lúc này`,`Files cannot be attached right now`)}),Ie&&(0,Q.jsx)(S,{variant:`caption`,color:`text.secondary`,children:$t(s)})]}),!c&&!g?(0,Q.jsxs)(P,{direction:`row`,spacing:1.5,sx:{minHeight:126,alignItems:`center`,justifyContent:`center`},children:[(0,Q.jsx)(ee,{size:20}),(0,Q.jsx)(S,{color:`text.secondary`,children:X(s,`Đang mở…`,`Opening…`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(re,{autoFocus:!0,fullWidth:!0,multiline:!0,minRows:3,maxRows:8,value:I,disabled:n||g,inputRef:ve.inputRef,...ve.inputProps,onChange:e=>{B(e.target.value),ve.track(e)},onKeyDown:e=>{ve.onKeyDown(e)||_r(e)&&(e.preventDefault(),Re())},onPaste:e=>{e.clipboardData?.files.length&&(e.preventDefault(),Ie&&Fe(e.clipboardData.files))},placeholder:X(s,`Nhắn cho Piagent… (@ để chọn file, folder)`,`Message Piagent… (@ for files and folders)`),variant:`standard`,slotProps:{input:{disableUnderline:!0},htmlInput:{maxLength:32768,...ve.htmlInput}},sx:{px:.5}}),ve.menu,V.length>0&&(0,Q.jsx)(P,{direction:`row`,sx:{flexWrap:`wrap`,gap:.75,px:.5,pt:.75},"aria-label":X(s,`File sẽ gửi cùng tin nhắn đầu tiên`,`Files for the first message`),children:V.map(e=>(0,Q.jsx)(Ce,{size:`small`,variant:`outlined`,label:`${e.name} · ${Xt(e.size)}`,onDelete:n?void 0:()=>{H(t=>t.filter(t=>t!==e)),U(null)},deleteIcon:(0,Q.jsx)(Hn,{"aria-label":`${X(s,`Bỏ`,`Remove`)} ${e.name}`,role:`button`})},`${e.name}:${e.size}:${e.lastModified}`))}),(0,Q.jsx)(or,{in:D,id:`piagent-new-session-options`,children:(0,Q.jsxs)(R,{sx:{mx:.35,mt:1,px:1.1,py:1,borderRadius:1,bgcolor:`action.hover`},children:[(0,Q.jsx)(S,{variant:`caption`,sx:{display:`block`,mb:.75,fontWeight:650},children:X(s,`Tùy chọn cho tin nhắn đầu tiên`,`Options for the first message`)}),(0,Q.jsxs)(P,{direction:`row`,sx:{alignItems:`center`,gap:.75,flexWrap:`wrap`},children:[(0,Q.jsx)(a,{size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(p,{}),endIcon:(0,Q.jsx)(j,{}),onClick:Me(`thinking`),children:rt(T,s)}),(0,Q.jsx)(a,{size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(y,{}),endIcon:(0,Q.jsx)(j,{}),onClick:Me(`permission`),children:h||be?pt(N,s):N?rt(N,s):X(s,`Quyền theo profile`,`Profile access`)}),(0,Q.jsxs)(a,{component:`label`,size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(Vn,{}),disabled:!Ie,"aria-label":`${X(s,`Thêm file`,`Add files`)} (${V.length}/4)`,children:[X(s,`Đính kèm`,`Attach`),(0,Q.jsx)(`input`,{type:`file`,hidden:!0,multiple:!0,disabled:!Ie,accept:``,onChange:e=>{Fe(e.target.files),e.currentTarget.value=``}})]})]}),be&&(0,Q.jsx)(S,{variant:`caption`,color:`text.secondary`,sx:{display:`block`,mt:.75},children:X(s,`Model và quyền theo Harness công ty; thinking chọn ở đây.`,`Models and access follow the company Harness; choose thinking here.`)})]})}),(0,Q.jsxs)(P,{direction:`row`,sx:{mt:1,alignItems:`center`,gap:.65,flexWrap:`nowrap`,minWidth:0},children:[(0,Q.jsx)(pe,{title:D?X(s,`Ẩn tùy chọn`,`Hide options`):X(s,`Thêm tùy chọn`,`More options`),children:(0,Q.jsx)(L,{size:`small`,"aria-label":D?X(s,`Ẩn tùy chọn`,`Hide options`):X(s,`Thêm tùy chọn`,`More options`),"aria-expanded":D,"aria-controls":`piagent-new-session-options`,onClick:()=>O(e=>!e),sx:{flex:`0 0 auto`,bgcolor:D?`action.selected`:`transparent`},children:(0,Q.jsx)(de,{fontSize:`small`,sx:{transition:`transform .16s ease`,transform:D?`rotate(45deg)`:`none`}})})}),(0,Q.jsx)(a,{size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(x,{}),endIcon:(0,Q.jsx)(j,{}),onClick:Me(`project`),"aria-label":`${X(s,`Project`,`Project`)}: ${q?.label??X(s,`Chọn project`,`Choose project`)}`,sx:{minWidth:0,maxWidth:{xs:118,sm:250},px:{xs:.75,sm:1},"& .MuiButton-startIcon":{display:{xs:`none`,sm:`inherit`}}},children:(0,Q.jsx)(R,{component:`span`,sx:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:q?.label??X(s,`Chọn project`,`Choose project`)})}),(0,Q.jsx)(a,{size:`small`,color:`inherit`,startIcon:be?(0,Q.jsx)(vr,{}):(0,Q.jsx)(xe,{}),endIcon:(0,Q.jsx)(j,{}),onClick:Me(`model`),"aria-label":`${X(s,`Model`,`Model`)}: ${be?X(s,`Công ty · agent-watch-auto`,`Company · agent-watch-auto`):Y?.displayName??Ae?.displayName??X(s,`Mặc định của Pi`,`Pi default`)}`,sx:{minWidth:0,maxWidth:{xs:142,sm:250},px:{xs:.75,sm:1},"& .MuiButton-startIcon":{display:{xs:`none`,sm:`inherit`}}},children:(0,Q.jsx)(R,{component:`span`,sx:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:be?X(s,`Công ty · agent-watch-auto`,`Company · agent-watch-auto`):Y?`${Y.displayName}${Y.modelRef===c?.defaultModelRef?X(s,` · mặc định`,` · default`):``}`:Ae?.displayName??X(s,`Mặc định của Pi`,`Pi default`)})}),we&&(0,Q.jsx)(pe,{title:Ot(s),arrow:!0,children:(0,Q.jsx)(a,{size:`small`,color:`inherit`,variant:`outlined`,startIcon:(0,Q.jsx)(_e,{}),"aria-pressed":A,"aria-label":`${dt(A,s)}. ${Ot(s)}`,onClick:()=>M(e=>!e),sx:{flex:`0 0 auto`,minWidth:0,px:{xs:.75,sm:1},borderRadius:1,borderColor:`divider`,color:`text.secondary`,"& .MuiButton-startIcon":{mr:{xs:0,sm:.65},ml:0},...A?ft:{}},children:(0,Q.jsx)(R,{component:`span`,sx:{display:{xs:`none`,sm:`inline`},whiteSpace:`nowrap`},children:dt(A,s)})})}),(0,Q.jsx)(R,{sx:{flex:1,minWidth:0}}),(0,Q.jsx)(L,{"aria-label":X(s,`Gửi`,`Send`),disabled:n||g||!q||!I.trim(),onClick:Re,sx:{flex:`0 0 auto`,width:34,height:34,borderRadius:999,transition:`transform .12s`,bgcolor:`primary.main`,color:`primary.contrastText`,"&:hover":{bgcolor:`primary.main`,color:`primary.contrastText`,transform:`translateY(-1px)`},"&.Mui-disabled":{bgcolor:`action.disabledBackground`}},children:(0,Q.jsx)(Un,{fontSize:`small`})})]}),we&&A&&(0,Q.jsx)(S,{variant:`caption`,sx:{display:`block`,px:.5,pt:.75,color:`warning.main`},children:Ot(s)})]}),(ie||me||r||g)&&(0,Q.jsx)(S,{role:`status`,color:`error`,variant:`caption`,sx:{display:`block`,px:.5,pt:1},children:ie??me??r??X(s,`Không tải được lựa chọn`,`Could not load choices`)})]}),c&&!I&&(0,Q.jsx)(P,{direction:`row`,role:`group`,"aria-label":X(s,`Việc mẫu`,`Starter tasks`),sx:{flexWrap:`wrap`,justifyContent:`center`,gap:1,maxWidth:820,mt:`16px !important`},children:jr.map(([e,t])=>(0,Q.jsx)(Ce,{variant:`outlined`,clickable:!0,label:X(s,e,t),onClick:()=>{B(X(s,e,t)),requestAnimationFrame(()=>ve.inputRef.current?.focus())},sx:{height:30,color:`text.secondary`,"&:hover":{color:`text.primary`}}},t))})]}),(0,Q.jsxs)(Te,{anchorEl:le,open:se===`project`,onClose:Ne,slotProps:{paper:{sx:{width:310,maxHeight:380}}},children:[(c?.projects??[]).map(e=>(0,Q.jsxs)(he,{selected:v===e.projectRef,onClick:()=>{b(e.projectRef),Ne()},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(ht,{name:`folder`,size:26})}),(0,Q.jsx)(J,{primary:e.label,secondary:e.hint,slotProps:{secondary:{noWrap:!0,title:e.hint}}})]},e.projectRef)),(0,Q.jsx)(ye,{}),(0,Q.jsxs)(he,{disabled:fe||c?.projectImport?.status!==`available`,onClick:()=>void Pe(),children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(de,{})}),(0,Q.jsx)(J,{primary:fe?X(s,`Đang chọn…`,`Choosing…`):X(s,`Thêm một hoặc nhiều folder`,`Add one or more folders`)})]})]}),(0,Q.jsxs)(Te,{anchorEl:le,open:se===`model`,onClose:Ne,slotProps:{paper:{sx:{width:360,maxHeight:440}}},children:[!h&&(Se.length>0||u?.available)&&[(0,Q.jsx)(k,{children:X(s,`Công ty`,`Company`)},`company-heading`),...Se.length?Se.map(e=>(0,Q.jsxs)(he,{selected:C===e.modelRef,onClick:()=>{w(e.modelRef),Ne()},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(vr,{})}),(0,Q.jsx)(J,{primary:`agent-watch-auto`,secondary:X(s,`Harness công ty · Studio quản lý model`,`Company Harness · models managed by Studio`)})]},e.modelRef)):[(0,Q.jsxs)(he,{disabled:f,onClick:()=>void ke(),children:[(0,Q.jsx)(G,{children:f?(0,Q.jsx)(ee,{size:20}):(0,Q.jsx)(vr,{})}),(0,Q.jsx)(J,{primary:`agent-watch-auto`,secondary:f?X(s,`Đang kết nối…`,`Connecting…`):hr(u,s),slotProps:{secondary:{sx:{whiteSpace:`normal`}}}})]},`company-connect`)],(0,Q.jsx)(k,{children:X(s,`Cá nhân`,`Personal`)},`personal-heading`)],!c?.defaultModelRef&&(0,Q.jsxs)(he,{selected:!C,onClick:()=>{w(``),Ne()},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(xe,{})}),(0,Q.jsx)(J,{primary:X(s,`Model mặc định của Pi`,`Pi default model`)})]}),De.map(e=>(0,Q.jsxs)(he,{selected:C===e.modelRef,onClick:()=>{w(e.modelRef),Ne()},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(ht,{name:e.provider,size:26})}),(0,Q.jsx)(J,{primary:e.displayName,secondary:e.modelRef===c?.defaultModelRef?X(s,`Mặc định · ${e.provider} · High`,`Default · ${e.provider} · High`):e.provider})]},e.modelRef))]}),(0,Q.jsx)(Te,{anchorEl:le,open:se===`thinking`,onClose:Ne,slotProps:{paper:{sx:{width:250,maxHeight:400}}},children:je.map(e=>(0,Q.jsxs)(he,{value:e,selected:T===e,onClick:()=>{E(e),Ne()},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(p,{})}),(0,Q.jsx)(J,{primary:rt(e,s)})]},e))}),(0,Q.jsx)(Te,{anchorEl:le,open:se===`permission`,onClose:Ne,slotProps:{paper:{sx:{width:310}}},children:h||be?[(0,Q.jsxs)(he,{selected:N!==`trusted-full-access`&&N!==`bypass`,onClick:()=>{F(null),Ne()},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(y,{})}),(0,Q.jsx)(J,{primary:pt(null,s),secondary:X(s,`Hỏi trước mỗi lệnh cần internet`,`Asks before each command that needs the internet`)})]},`ask`),(0,Q.jsxs)(he,{selected:N===`trusted-full-access`,onClick:()=>{Ne(),ne(`trusted-full-access`)},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(y,{color:`warning`})}),(0,Q.jsx)(J,{primary:pt(`trusted-full-access`,s),secondary:X(s,`Chỉ hỏi việc bắt buộc phải xác nhận`,`Asks only what must be confirmed`)})]},`full`),...Y?.managedBypass?[(0,Q.jsxs)(he,{selected:N===`bypass`,onClick:()=>{Ne(),ne(`bypass`)},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(y,{color:`error`})}),(0,Q.jsx)(J,{primary:`Bypass`,secondary:X(s,`Không hỏi gì; admin Studio có thể tắt`,`Asks nothing; a Studio administrator can turn it off`)})]},`bypass`)]:[]]:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(he,{selected:N===null,onClick:()=>{F(null),Ne()},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(y,{})}),(0,Q.jsx)(J,{primary:X(s,`Theo profile project`,`Project profile default`)})]}),[`read-only`,`workspace-write`,`trusted-full-access`,`bypass`].map(e=>(0,Q.jsxs)(he,{selected:N===e,onClick:()=>{Ne(),e===`trusted-full-access`||e===`bypass`?ne(e):F(e)},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(y,{color:e===`bypass`?`error`:e===`trusted-full-access`?`warning`:void 0})}),(0,Q.jsx)(J,{primary:rt(e,s)})]},e))]})}),(0,Q.jsx)(lt,{open:te!==null,title:te===`bypass`?X(s,`Tạo cuộc trò chuyện với Bypass?`,`Create with Bypass?`):X(s,`Tạo session với toàn quyền?`,`Create with full access?`),description:te===`bypass`?h||be?kt(s):mt(s):h||be?it(s):X(s,`Session mới được phép đọc, sửa file và chạy command trong runtime. Xóa dữ liệu và gửi ra ngoài vẫn cần xác nhận riêng.`,`The new session may read and edit files and run commands. Deletion and external transfer still require separate approval.`),cancelLabel:X(s,`Hủy`,`Cancel`),confirmLabel:te===`bypass`?X(s,`Dùng Bypass`,`Use Bypass`):X(s,`Dùng toàn quyền`,`Use full access`),onCancel:()=>ne(null),onConfirm:()=>{let e=te;ne(null),e&&F(e)}})]})}var Nr=(e,t,n)=>e===`vi`?t:n,Pr=[[`⌘K`,`Mở bảng lệnh`,`Open the command palette`],[`⌘⇧O`,`Cuộc trò chuyện mới`,`New chat`],[`⌘,`,`Cài đặt`,`Settings`],[`⌘/`,`Phím tắt và lệnh /`,`Shortcuts and / commands`],[`Esc`,`Dừng lượt đang chạy (trong ô nhập)`,`Stop the running turn (in the composer)`]];function Fr(e,t){let n=/^\/([a-z][a-z-]*)(?:\s+([\s\S]*))?$/.exec(e.trim()),r=n?t.find(e=>e.name===n[1]):void 0;return r?{command:r,argument:(n[2]??``).trim()}:null}var Ir=(e,t,n,r)=>({tone:`error`,text:t instanceof Error&&t.message===`session-runtime-busy`?Nr(e,`${n}: lượt này đang chạy, thử lại khi xong.`,`${r}: this turn is running; try again when it ends.`):Nr(e,`${n}. Thử lại.`,`${r}. Try again.`)});async function Lr(e,t,n,r,i){try{return await t(),n}catch(t){return Ir(e,t,r,i)}}function Rr(e){let{locale:t,actions:n}=e,r=(e,n)=>Nr(t,e,n),i=(e,t)=>({tone:`success`,text:r(e,t)}),a=(e,t)=>({tone:`warning`,text:r(e,t)}),o=[],s=(e,t,n,i,a)=>o.push({name:e,argumentHint:t,description:r(n,i),run:a});return s(`help`,null,`Danh sách lệnh / và phím tắt`,`The / commands and keyboard shortcuts`,async()=>({tone:`info`,text:[...o.map(e=>`/${e.name}${e.argumentHint?` ${e.argumentHint}`:``} — ${e.description}`),...Pr.map(([e,t,n])=>`${e} — ${r(t,n)}`)].join(`
3
- `)})),s(`new`,null,`Cuộc trò chuyện mới`,`New chat`,async()=>(n.newChat(),i(`Đã mở cuộc trò chuyện mới.`,`Opened a new chat.`))),s(`stop`,null,`Dừng lượt đang chạy`,`Stop the running turn`,async()=>e.running?Lr(t,n.stop,i(`Đã dừng lượt đang chạy.`,`Stopped the running turn.`),`Chưa dừng được`,`Could not stop`):{tone:`info`,text:r(`Không có lượt nào đang chạy.`,`No turn is running.`)}),s(`name`,`<tên>`,`Đổi tên cuộc trò chuyện`,`Rename the conversation`,async e=>e?Lr(t,()=>n.rename(e.slice(0,200)),i(`Đã đổi tên thành “${e.slice(0,200)}”.`,`Renamed to “${e.slice(0,200)}”.`),`Chưa đổi được tên`,`Could not rename`):a(`Cách dùng: /name <tên mới>`,`Usage: /name <new name>`)),s(`fork`,null,`Tạo cuộc trò chuyện mới từ cuộc này`,`Fork this conversation`,async()=>Lr(t,n.fork,i(`Đã tạo bản sao của cuộc trò chuyện.`,`Forked the conversation.`),`Chưa tạo được bản sao`,`Could not fork`)),s(`pin`,null,e.pinned?`Bỏ ghim cuộc trò chuyện`:`Ghim cuộc trò chuyện`,e.pinned?`Unpin the conversation`:`Pin the conversation`,async()=>Lr(t,()=>n.pin(!e.pinned),e.pinned?i(`Đã bỏ ghim.`,`Unpinned.`):i(`Đã ghim.`,`Pinned.`),`Chưa đổi được ghim`,`Could not change the pin`)),s(`archive`,null,`Lưu trữ cuộc trò chuyện`,`Archive the conversation`,async()=>Lr(t,n.archive,i(`Đã lưu trữ cuộc trò chuyện.`,`Archived the conversation.`),`Chưa lưu trữ được`,`Could not archive`)),e.thinkingLevels.length&&s(`thinking`,`<${e.thinkingLevels.join(`|`)}>`,`Đổi mức suy luận`,`Change the thinking level`,async r=>e.thinkingLevels.includes(r)?Lr(t,()=>n.setThinking(r),i(`Đã đổi thinking sang ${r}.`,`Thinking is now ${r}.`),`Chưa đổi được thinking`,`Could not change thinking`):a(`Cách dùng: /thinking ${e.thinkingLevels.join(`|`)}`,`Usage: /thinking ${e.thinkingLevels.join(`|`)}`)),e.company?(s(`undo`,null,`Hoàn tác file mà lượt trước của agent đã sửa`,`Undo the files the agent's last turn changed`,async()=>({send:!0})),e.fast&&s(`fast`,`[on|off]`,`Bật/tắt Fast (Harness cho phép)`,`Turn Fast on or off (where the Harness allows it)`,async r=>{let o=r===`on`?!0:r===`off`?!1:r?null:e.fast!==`on`;return o===null?a(`Cách dùng: /fast on|off`,`Usage: /fast on|off`):Lr(t,()=>n.setFast(o),o?i(`Đã bật Fast.`,`Fast is on.`):i(`Đã tắt Fast.`,`Fast is off.`),`Chưa đổi được Fast`,`Could not change Fast`)}),s(`bypass`,`<on|full|off>`,`Bypass (không hỏi gì), Toàn quyền (chỉ hỏi việc bắt buộc) hoặc Hỏi trước`,`Bypass (asks nothing), Full access (asks only what must be asked) or Ask first`,async o=>o===`off`?Lr(t,()=>n.setPermission(`workspace-write`),i(`Đã chuyển sang Hỏi trước.`,`Switched to Ask first.`),`Chưa đổi được quyền`,`Access not changed`):o===`full`?{confirm:{title:r(`Bật Toàn quyền?`,`Turn on Full access?`),confirmLabel:r(`Bật Toàn quyền`,`Turn on Full access`),description:r(`Lệnh cần internet hoặc Docker chạy không hỏi; push, deploy và lệnh trên máy vẫn hỏi.`,`Commands that need the internet or Docker run without asking; pushes, deploys and commands on this machine still ask.`),run:()=>Lr(t,()=>n.setPermission(`trusted-full-access`),i(`Đã bật Toàn quyền.`,`Full access is on.`),`Chưa đổi được quyền`,`Access not changed`)}}:o===`on`?e.bypass?{confirm:{title:r(`Bật Bypass?`,`Turn on Bypass?`),confirmLabel:r(`Bật Bypass`,`Turn on Bypass`),description:r(`Không hỏi gì nữa: internet, Docker, lệnh trên máy, push, deploy, migration đều chạy luôn. Lệnh thường vẫn trong sandbox; /undo vẫn dùng được.`,`Nothing is asked any more: internet, Docker, commands on this machine, pushes, deploys and migrations all run. Plain commands stay in the sandbox; /undo still works.`),run:()=>Lr(t,()=>n.setPermission(`bypass`),i(`Đã bật Bypass.`,`Bypass is on.`),`Chưa đổi được quyền`,`Access not changed`)}}:a(`Harness của team đã tắt Bypass (admin Studio). Dùng /bypass full cho Toàn quyền.`,`The team's Harness has Bypass off (Studio administrator). Use /bypass full for Full access.`):a(`Cách dùng: /bypass on|full|off`,`Usage: /bypass on|full|off`))):(s(`model`,`<tên model>`,`Đổi model`,`Change the model`,async r=>{let o=await e.loadModels().catch(()=>[]),s=r.toLowerCase(),c=s?o.filter(e=>e.label.toLowerCase()===s||e.modelRef.toLowerCase()===s):[],l=c.length?c:s?o.filter(e=>e.label.toLowerCase().includes(s)||e.modelRef.toLowerCase().includes(s)):[];return l.length===1?Lr(t,()=>n.setModel(l[0].modelRef),i(`Đã đổi model sang ${l[0].label}.`,`The model is now ${l[0].label}.`),`Chưa đổi được model`,`Could not change the model`):a(`Cách dùng: /model <tên>. Có: ${o.map(e=>e.label).slice(0,12).join(`, `)||`—`}`,`Usage: /model <name>. Available: ${o.map(e=>e.label).slice(0,12).join(`, `)||`—`}`)}),s(`permission`,`<read-only|ask|full|bypass>`,`Đổi quyền của cuộc trò chuyện`,`Change the conversation's access`,async e=>{let o=e===`read-only`?`read-only`:e===`ask`?`workspace-write`:e===`full`?`trusted-full-access`:e===`bypass`?`bypass`:null;if(!o)return a(`Cách dùng: /permission read-only|ask|full|bypass`,`Usage: /permission read-only|ask|full|bypass`);let s=()=>Lr(t,()=>n.setPermission(o),i(`Đã đổi quyền sang ${e}.`,`Access is now ${e}.`),`Chưa đổi được quyền`,`Access not changed`);return o===`bypass`?{confirm:{title:r(`Bật Bypass?`,`Turn on Bypass?`),confirmLabel:r(`Bật Bypass`,`Turn on Bypass`),description:r(`Không hỏi, không chặn gì trong cuộc trò chuyện này (xoá, push, file được bảo vệ đều chạy luôn). Output vẫn che secret, /undo vẫn hoàn tác được.`,`Nothing is asked or blocked in this conversation (deletes, pushes and protected files all run). Output is still redacted and /undo still works.`),run:s}}:o===`trusted-full-access`?{confirm:{title:r(`Bật toàn quyền?`,`Enable full access?`),confirmLabel:r(`Bật toàn quyền`,`Enable full access`),description:r(`Session được đọc, sửa file và chạy command trong phạm vi runtime; xoá hoặc gửi dữ liệu ra ngoài vẫn cần xác nhận riêng.`,`The session may read and edit files and run commands within the runtime; destructive actions and external transfers still ask.`),run:s}}:s()})),s(`changes`,null,`Mở Source Changes`,`Open Source Changes`,async()=>(n.openChanges(),i(`Đã mở Source Changes.`,`Opened Source Changes.`))),s(`settings`,null,`Mở Cài đặt`,`Open Settings`,async()=>(n.openSettings(),i(`Đã mở Cài đặt.`,`Opened Settings.`))),o}var zr=`piagent dashboard`;function Br(){return(0,$.useSyncExternalStore)(Re,Le,Le)}function Vr({locale:e}){let[t,n]=(0,$.useState)(!1);return(0,Q.jsxs)(P,{role:`alert`,spacing:2,sx:{minHeight:`100vh`,alignItems:`center`,justifyContent:`center`,px:2,textAlign:`center`},children:[(0,Q.jsx)(S,{variant:`h6`,component:`h1`,children:X(e,`Tab này đã hết phiên đăng nhập`,`This tab is no longer signed in`)}),(0,Q.jsx)(S,{color:`text.secondary`,sx:{maxWidth:520},children:X(e,`Piagent vừa khởi động lại, tab không được dùng quá 8 giờ, hoặc tab được mở từ một link cũ. Các cuộc trò chuyện vẫn còn nguyên — mở lại Piagent để vào tiếp.`,`Piagent restarted, this tab was unused for over 8 hours, or this tab came from an old link. Your conversations are kept — open Piagent again to continue.`)}),(0,Q.jsxs)(R,{sx:{display:`flex`,gap:1,alignItems:`center`,flexWrap:`wrap`,justifyContent:`center`},children:[(0,Q.jsx)(R,{component:`code`,sx:{px:1.5,py:.75,borderRadius:1,bgcolor:`action.hover`,fontSize:`.9rem`},children:zr}),(0,Q.jsx)(a,{size:`small`,variant:`outlined`,onClick:()=>{navigator.clipboard?.writeText(zr).then(()=>n(!0),()=>n(!1))},children:t?X(e,`Đã chép`,`Copied`):X(e,`Chép lệnh`,`Copy command`)})]}),(0,Q.jsx)(S,{variant:`body2`,color:`text.secondary`,children:X(e,`Chạy lệnh trên trong terminal, hoặc bấm WebUI trong Agent Watch. Sau đó có thể đóng tab này.`,`Run it in a terminal, or choose WebUI in Agent Watch. You can close this tab afterwards.`)})]})}var Hr=`piagent-update-snooze`,Ur=`piagent-update-job-seen`,Wr=36e5;function Gr(e){try{return window.localStorage.getItem(e)}catch{return null}}function Kr(e,t){try{window.localStorage.setItem(e,t)}catch{}}function qr(e,t){try{let n=JSON.parse(Gr(Hr)??`null`);return n?.version===e&&typeof n.until==`number`&&t<n.until}catch{return!1}}function Jr({locale:e,onDetails:t}){let{status:n,applying:r,error:i,apply:o}=ct(),[c,l]=(0,$.useState)(()=>Date.now()),[u,d]=(0,$.useState)(null),[f,p]=(0,$.useState)(null);(0,$.useEffect)(()=>{let e=window.setInterval(()=>l(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let m=n?.piagent.latest??null,h=n?.job??null;(0,$.useEffect)(()=>{!h||h.state!==`succeeded`||Gr(Ur)===h.startedAt||(Kr(Ur,h.startedAt),p(X(e,`Đã cập nhật Piagent ${h.from} → ${h.installed??h.to}.`,`Piagent updated ${h.from} → ${h.installed??h.to}.`)))},[h,e]);let _=!!(n?.installable&&n.updateAvailable&&m&&!_t(n))&&u!==m&&!qr(m,c),y=()=>{m&&(Kr(Hr,JSON.stringify({version:m,until:Date.now()+Wr})),d(m))},b=(n?.runningConversations??0)>0;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(s,{open:_,onClose:y,fullWidth:!0,maxWidth:`xs`,"aria-labelledby":`piagent-update-offer`,children:[(0,Q.jsxs)(I,{id:`piagent-update-offer`,sx:{display:`flex`,alignItems:`center`,gap:1},children:[(0,Q.jsx)(T,{color:`primary`}),X(e,`Có bản Piagent mới: ${m}`,`Piagent ${m} is available`)]}),(0,Q.jsxs)(z,{sx:{display:`grid`,gap:1.5},children:[(0,Q.jsx)(R,{component:`ul`,sx:{m:0,pl:2.5,display:`grid`,gap:.75},children:n&&ot(e,n).map(e=>(0,Q.jsx)(S,{component:`li`,variant:`body2`,children:e},e))}),b&&(0,Q.jsx)(v,{severity:`info`,children:X(e,`${n?.runningConversations} cuộc trò chuyện đang chạy. Cập nhật khi chúng xong — dialog này sẽ nhắc lại.`,`${n?.runningConversations} conversation(s) running. Update once they finish — this will ask again.`)}),i&&(0,Q.jsx)(v,{severity:`error`,children:gt(e,i)})]}),(0,Q.jsxs)(g,{sx:{flexWrap:`wrap`,gap:1},children:[(0,Q.jsx)(a,{onClick:y,children:X(e,`Để sau (nhắc lại sau 1 giờ)`,`Later (ask again in an hour)`)}),(0,Q.jsx)(a,{onClick:()=>{d(m),t()},children:X(e,`Xem chi tiết`,`Details`)}),(0,Q.jsx)(a,{variant:`contained`,disabled:b||r,onClick:()=>{d(m),o().then(t)},children:X(e,`Cập nhật ngay`,`Update now`)})]})]}),(0,Q.jsx)(be,{open:f!==null,autoHideDuration:8e3,onClose:()=>p(null),anchorOrigin:{vertical:`top`,horizontal:`center`},children:(0,Q.jsx)(v,{severity:`success`,variant:`filled`,onClose:()=>p(null),children:f})})]})}function Yr(e){return N(`MuiSkeleton`,e)}we(`MuiSkeleton`,[`root`,`text`,`rectangular`,`rounded`,`circular`,`pulse`,`wave`,`withChildren`,`fitContent`,`heightAuto`]);var Xr=e=>{let{classes:t,variant:n,animation:r,hasChildren:i,width:a,height:o}=e;return K({root:[`root`,n,r,i&&`withChildren`,i&&!a&&`fitContent`,i&&!o&&`heightAuto`]},Yr,t)},Zr=r`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/WorkspaceQuickOpen-CJmMBmK8.js","assets/rolldown-runtime-hePW80VL.js","assets/vendor-CSDKB7mU.js","assets/ui-preferences-0waeSO-S.js","assets/workspace-api-D8sJkiZB.js","assets/bootstrap-CedkNtRG.js","assets/TerminalPanel-CtZyb0tj.js","assets/index-CNdhIouM.js","assets/index-CjM70M7D.css","assets/terminal-transport-Dk5pYNX5.js","assets/tab-close-ITV4Cf4X.js","assets/WorkspaceExplorer-CkFBpcM7.js","assets/api-BQS4Dtrr.js","assets/workspace-navigation-DkVobhwg.js","assets/composer-drafts-BtMaVw8W.js","assets/LineReview-C_0ZpgCH.js","assets/MarkdownMessage-DGt5B-6D.js","assets/SettingsPage-CxpZ7cdM.js","assets/view-model-CWNiS4JN.js","assets/SettingsNavigation-BFfqMcuL.js","assets/SessionInspectorDrawer-BJ94aQ6y.js"])))=>i.map(i=>d[i]);
2
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$t as t,A as n,An as r,At as i,Bt as a,Cn as o,Ct as s,D as c,Dn as l,Dt as u,E as d,Et as f,F as p,Fn as m,Ft as h,G as g,Gt as _,Ht as v,I as y,Kt as b,L as x,Lt as S,M as C,Mt as w,N as T,Nt as E,O as D,Ot as O,P as k,Pt as A,R as j,Rt as M,Sn as N,St as P,Tt as F,U as I,Ut as L,Vt as R,W as z,Wt as ee,Xt as B,Yt as te,Zt as ne,_t as re,an as V,cn as H,en as ie,fn as U,gt as ae,ht as oe,in as W,it as G,j as se,jt as ce,k as le,kn as ue,kt as de,ln as fe,mn as K,mt as pe,nn as me,nt as he,on as ge,pt as _e,qt as q,rn as ve,rt as J,st as ye,tn as Y,tt as be,ut as xe,vn as Se,wt as Ce,xn as we,yt as Te,z as Ee,zt as De}from"./vendor-CSDKB7mU.js";import{i as Oe,n as X,o as ke,s as Ae}from"./ui-preferences-0waeSO-S.js";import{n as je,t as Me}from"./index-CNdhIouM.js";import{a as Ne,i as Pe,n as Fe,o as Ie,r as Le,s as Re,t as ze}from"./bootstrap-CedkNtRG.js";import{E as Be,F as Ve,I as He,K as Ue,N as We,R as Ge,U as Ke,V as qe,b as Je,ft as Ye,n as Xe,o as Ze,p as Qe,r as $e,u as et,ut as tt,w as Z,z as nt}from"./api-BQS4Dtrr.js";import{r as rt}from"./view-model-CWNiS4JN.js";import{A as it,B as at,C as ot,D as st,E as ct,F as lt,H as ut,M as dt,N as ft,O as pt,P as mt,R as ht,S as gt,T as _t,V as vt,_ as yt,a as bt,b as xt,c as St,d as Ct,f as wt,g as Tt,h as Et,i as Dt,j as Ot,k as kt,l as At,m as jt,o as Mt,p as Nt,r as Pt,s as Ft,u as It,v as Lt,w as Rt,y as zt,z as Bt}from"./SettingsNavigation-BFfqMcuL.js";import{a as Vt,i as Ht,n as Ut,t as Wt}from"./workspace-navigation-DkVobhwg.js";import{C as Gt,S as Kt,T as qt,_ as Jt,a as Yt,b as Xt,c as Zt,d as Qt,g as $t,h as en,i as tn,m as nn,o as rn,p as an,r as on,s as sn,t as cn,u as ln,v as un,w as dn,x as fn,y as pn}from"./transcript-view-model-CpEMY1xb.js";import{a as mn,i as hn,n as gn,o as _n,r as vn,s as yn,t as bn}from"./composer-drafts-BtMaVw8W.js";import{t as xn}from"./latest-request-DXcYQW86.js";import{t as Sn}from"./terminal-transport-Dk5pYNX5.js";function Cn(e){return String(e).match(/[\d.\-+]*\s*(.*)/)[1]||``}function wn(e){return parseFloat(e)}var Q=l();function Tn({value:e,onChange:t}){let{locale:n}=Oe();return(0,Q.jsxs)(M,{value:e,onChange:(e,n)=>t(n),variant:`fullWidth`,"aria-label":X(n,`Thanh bên`,`Sidebar`),children:[(0,Q.jsx)(De,{value:`sessions`,label:X(n,`Phiên`,`Sessions`)}),(0,Q.jsx)(De,{value:`files`,label:X(n,`Tệp`,`Files`)}),(0,Q.jsx)(De,{value:`search`,label:X(n,`Tìm kiếm`,`Search`)})]})}var $=e(m(),1),En=(0,$.lazy)(()=>Me(()=>import(`./WorkspaceQuickOpen-CJmMBmK8.js`),__vite__mapDeps([0,1,2,3,4,5]))),Dn=(0,$.lazy)(()=>Me(()=>import(`./TerminalPanel-CtZyb0tj.js`),__vite__mapDeps([6,1,2,3,7,8,9,5,10]))),On=(0,$.lazy)(()=>Me(()=>import(`./WorkspaceExplorer-CkFBpcM7.js`),__vite__mapDeps([11,1,2,3,7,8,5,12,13,14,15,10,4]))),kn=52,An=36,jn=25,Mn=75,Nn=`piagent-webui-editor-width`;function Pn(){try{let e=Number(window.localStorage.getItem(Nn));return e>=jn&&e<=Mn?e:55}catch{return 55}}var Fn=e=>({color:e?`text.primary`:`text.secondary`,bgcolor:e?`action.selected`:`transparent`,"& .MuiButton-startIcon svg":{fontSize:16,color:e?`primary.main`:`inherit`}});function In({title:e,close:t,onClose:n}){return(0,Q.jsxs)(R,{sx:{display:`flex`,alignItems:`center`,gap:1,px:2,minHeight:48,borderBottom:1,borderColor:`divider`},children:[(0,Q.jsx)(S,{sx:{fontWeight:600,flex:1},children:e}),(0,Q.jsx)(L,{size:`small`,"aria-label":t,onClick:n,children:(0,Q.jsx)(h,{fontSize:`small`})})]})}function Ln({sessionRef:e,children:t,navigationHost:n,sidebarMode:r,onSection:o}){let{locale:s}=Oe(),c=fe(),l=i(c.breakpoints.up(`lg`)),[u,d]=(0,$.useState)(!1),[f,p]=(0,$.useState)(!1),[m,h]=(0,$.useState)(!1),[g,_]=(0,$.useState)(),v=(0,$.useRef)(null),[y,b]=(0,$.useState)(Pn),x=e=>{let t=Math.min(Mn,Math.max(jn,e));b(t);try{window.localStorage.setItem(Nn,String(Math.round(t)))}catch{}},C=e=>{let t=v.current?.getBoundingClientRect();if(!t)return;e.preventDefault(),document.body.style.cursor=`col-resize`,document.body.style.userSelect=`none`;let n=e=>x((e.clientX-t.left)/t.width*100),r=()=>{window.removeEventListener(`pointermove`,n),window.removeEventListener(`pointerup`,r),document.body.style.cursor=``,document.body.style.userSelect=``};window.addEventListener(`pointermove`,n),window.addEventListener(`pointerup`,r)};(0,$.useEffect)(()=>{let t=e=>{(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&e.key.toLowerCase()===`p`&&(e.preventDefault(),p(!0))},n=t=>{let n=t.detail;n?.sessionRef===e&&(_({path:n.path,line:n.line}),d(!0),o(`files`))};return window.addEventListener(`keydown`,t),window.addEventListener(Wt,n),()=>{window.removeEventListener(`keydown`,t),window.removeEventListener(Wt,n)}},[e]),(0,$.useEffect)(()=>{r!==`sessions`&&d(!0)},[r]);let w=(0,Q.jsx)($.Suspense,{fallback:(0,Q.jsx)(ee,{size:24}),children:(0,Q.jsx)(On,{sessionRef:e,target:g,navigationHost:l?n:null,sidebarMode:r,onHide:()=>{d(!1),o(`sessions`)},fill:l})}),T=(0,Q.jsx)($.Suspense,{fallback:(0,Q.jsx)(ee,{size:24}),children:(0,Q.jsx)(Dn,{sessionRef:e,onHide:()=>h(!1)})});return(0,Q.jsxs)(Q.Fragment,{children:[f&&(0,Q.jsx)($.Suspense,{fallback:(0,Q.jsx)(ee,{size:20}),children:(0,Q.jsx)(En,{sessionRef:e,onClose:()=>p(!1),onOpen:e=>{p(!1),d(!0),o(`files`),_({path:e})}})}),(0,Q.jsxs)(R,{sx:{position:`sticky`,top:kn,zIndex:2,height:An,display:`flex`,alignItems:`center`,gap:.5,px:1,bgcolor:`background.default`,borderBottom:1,borderColor:`divider`},children:[(0,Q.jsx)(a,{size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(A,{}),"aria-expanded":u,onClick:()=>{d(e=>!e),o(u?`sessions`:`files`)},sx:Fn(u),children:X(s,`Tệp`,`Files`)}),(0,Q.jsx)(a,{size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(E,{}),"aria-expanded":m,onClick:()=>h(e=>!e),sx:Fn(m),children:`Terminal`}),(0,Q.jsx)(R,{sx:{flex:1}}),l&&(0,Q.jsx)(S,{variant:`caption`,color:`text.disabled`,sx:{pr:.5,display:{xs:`none`,xl:`block`}},children:X(s,`⌘P mở file`,`⌘P to open a file`)})]}),(0,Q.jsxs)(R,{ref:v,sx:{display:`flex`,minWidth:0},children:[l&&(u||m)&&(0,Q.jsxs)(R,{component:`section`,"aria-label":X(s,`Editor và terminal`,`Editor and terminal`),sx:{position:`sticky`,top:88,alignSelf:`flex-start`,flexShrink:0,minWidth:0,width:`clamp(320px, ${y}%, calc(100% - 360px))`,height:`calc(100vh - 88px - var(--piagent-status-bar, 0px))`,display:`flex`,flexDirection:`column`,bgcolor:`background.default`,zIndex:1},children:[u&&(0,Q.jsx)(R,{sx:{flex:1,minHeight:0,overflow:`hidden`},children:w}),m&&(0,Q.jsx)(R,{sx:{flexShrink:0,maxHeight:u?`60%`:`100%`,overflow:`auto`,...u?{}:{flex:1}},children:T}),(0,Q.jsx)(R,{role:`separator`,"aria-orientation":`vertical`,"aria-label":X(s,`Kéo để đổi độ rộng editor`,`Drag to resize the editor`),"aria-valuenow":Math.round(y),"aria-valuemin":jn,"aria-valuemax":Mn,tabIndex:0,onPointerDown:C,onKeyDown:e=>{(e.key===`ArrowLeft`||e.key===`ArrowRight`)&&(e.preventDefault(),x(y+(e.key===`ArrowLeft`?-2:2)))},sx:{position:`absolute`,top:0,right:-3,bottom:0,width:6,cursor:`col-resize`,zIndex:2,borderRight:1,borderColor:`divider`,"&:hover, &:focus-visible":{borderColor:`primary.main`,outline:`none`}}})]}),(0,Q.jsx)(R,{sx:{flex:1,minWidth:0},children:t})]}),!l&&(0,Q.jsxs)(ce,{anchor:`bottom`,open:m,onClose:()=>h(!1),children:[(0,Q.jsx)(In,{title:`Terminal`,close:X(s,`Ẩn terminal`,`Hide terminal`),onClose:()=>h(!1)}),m&&T]}),!l&&(0,Q.jsxs)(ce,{anchor:`left`,open:u,onClose:()=>d(!1),slotProps:{paper:{sx:{width:`min(96vw, 800px)`}}},children:[(0,Q.jsx)(In,{title:X(s,`Tệp`,`Files`),close:X(s,`Đóng`,`Close`),onClose:()=>d(!1)}),u&&w]})]})}var Rn=e=>e.name??e.repo;function zn(e,t,n){let r=n===`vi`,i=t?` ${t}`:``,a=r?` Admin Studio đã được báo.`:` Studio administrators were told.`,o=t=>e.filter(e=>e.kind===t).map(Rn).join(`, `),s=[],c=o(`other_team`),l=o(`unlisted`),u=o(`unregistered`),d=o(`no_repository`);return c&&s.push(r?`${c} thuộc team khác, không phải team${i} của key này.`:`${c} belongs to another team, not this key's team${i}.`),l&&s.push(r?`${l} chưa có trong danh sách project của team${i}.`:`${l} is not in the project list of team${i}.`),u&&s.push(r?`${u} chưa được đăng ký cho team${i}.`:`${u} is not registered to team${i}.`),d&&s.push(r?`Không xác định được project của thư mục ${d}.`:`The project of folder ${d} could not be identified.`),s.join(` `)+a}function Bn({session:e,locale:t}){let n=e.managedProjectWarning;return n?(0,Q.jsx)(v,{severity:`warning`,role:`status`,sx:{maxWidth:820,mx:`auto`,mb:1,py:0},children:zn(n.warnings,n.team,t)}):null}var Vn=q((0,Q.jsx)(`path`,{d:`M16.5 6.75v10.58c0 2.09-1.53 3.95-3.61 4.15-2.39.23-4.39-1.64-4.39-3.98V5.14c0-1.31.94-2.5 2.24-2.63 1.5-.15 2.76 1.02 2.76 2.49v10.5c0 .55-.45 1-1 1s-1-.45-1-1V6.75c0-.41-.34-.75-.75-.75s-.75.34-.75.75v8.61c0 1.31.94 2.5 2.24 2.63 1.5.15 2.76-1.02 2.76-2.49V5.17c0-2.09-1.53-3.95-3.61-4.15C9.01.79 7 2.66 7 5v12.27c0 2.87 2.1 5.44 4.96 5.71 3.29.3 6.04-2.26 6.04-5.48V6.75c0-.41-.34-.75-.75-.75s-.75.34-.75.75`}),`AttachFileRounded`),Hn=q((0,Q.jsx)(`path`,{d:`M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2m4.3 14.3c-.39.39-1.02.39-1.41 0L12 13.41 9.11 16.3c-.39.39-1.02.39-1.41 0a.996.996 0 0 1 0-1.41L10.59 12 7.7 9.11a.996.996 0 0 1 0-1.41c.39-.39 1.02-.39 1.41 0L12 10.59l2.89-2.89c.39-.39 1.02-.39 1.41 0s.39 1.02 0 1.41L13.41 12l2.89 2.89c.38.38.38 1.02 0 1.41`}),`CancelRounded`),Un=q((0,Q.jsx)(`path`,{d:`M13 19V7.83l4.88 4.88c.39.39 1.03.39 1.42 0s.39-1.02 0-1.41l-6.59-6.59a.996.996 0 0 0-1.41 0l-6.6 6.58c-.39.39-.39 1.02 0 1.41s1.02.39 1.41 0L11 7.83V19c0 .55.45 1 1 1s1-.45 1-1`}),`ArrowUpwardRounded`),Wn=q((0,Q.jsx)(`path`,{d:`M2 4v16h20V4zm18 4.67h-2.5V6H20zm-2.5 2H20v2.67h-2.5zM4 6h11.5v12H4zm13.5 12v-2.67H20V18z`}),`ViewSidebarOutlined`),Gn=q((0,Q.jsx)(`path`,{d:`M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m3 14H9c-.55 0-1-.45-1-1V9c0-.55.45-1 1-1h6c.55 0 1 .45 1 1v6c0 .55-.45 1-1 1`}),`StopCircleRounded`),Kn=q((0,Q.jsx)(`path`,{d:`M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z`}),`Person`);function qn(e){return N(`MuiAvatar`,e)}we(`MuiAvatar`,[`root`,`colorDefault`,`circular`,`rounded`,`square`,`img`,`fallback`]);var Jn=e=>{let{classes:t,variant:n,colorDefault:r}=e;return K({root:[`root`,n,r&&`colorDefault`],img:[`img`],fallback:[`fallback`]},qn,t)},Yn=H(`div`,{name:`MuiAvatar`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,t[n.variant],n.colorDefault&&t.colorDefault]}})(V(({theme:e})=>({position:`relative`,display:`flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0,width:40,height:40,fontFamily:e.typography.fontFamily,fontSize:e.typography.pxToRem(20),lineHeight:1,borderRadius:`50%`,overflow:`hidden`,userSelect:`none`,variants:[{props:{variant:`rounded`},style:{borderRadius:(e.vars||e).shape.borderRadius}},{props:{variant:`square`},style:{borderRadius:0}},{props:{colorDefault:!0},style:{color:(e.vars||e).palette.background.default,"@media (forced-colors: active)":{boxSizing:`border-box`,border:`1px solid ButtonBorder`},...e.vars?{backgroundColor:e.vars.palette.Avatar.defaultBg}:{backgroundColor:e.palette.grey[400],...e.applyStyles(`dark`,{backgroundColor:e.palette.grey[600]})}}}]}))),Xn=H(`img`,{name:`MuiAvatar`,slot:`Img`})({width:`100%`,height:`100%`,textAlign:`center`,objectFit:`cover`,color:`transparent`,textIndent:1e4}),Zn=H(Kn,{name:`MuiAvatar`,slot:`Fallback`})({width:`75%`,height:`75%`});function Qn(e,t,n,r){let[i,a]=$.useState(!1);return $.useEffect(()=>{if(!e&&!t)return;a(!1);let i=!0,o=new Image;return o.onload=()=>{i&&a(`loaded`)},o.onerror=()=>{i&&a(`error`)},o.crossOrigin=n,o.referrerPolicy=r,o.src=e,t&&(o.srcset=t),()=>{i=!1}},[n,r,e,t]),i}var $n=$.forwardRef(function(e,t){let n=ge({props:e,name:`MuiAvatar`}),{alt:r,children:i,className:a,component:s=`div`,slots:c={},slotProps:l={},sizes:u,src:d,srcSet:f,variant:p=`circular`,...m}=n,h=null,g={...n,component:s,variant:p},{crossOrigin:_,referrerPolicy:v}=(typeof l.img==`function`?l.img(g):l.img)??{},y=Qn(d,f,_,v),b=d||f,x=b&&y!==`error`;g.colorDefault=!x,delete g.ownerState;let S=Jn(g),C={slots:c,slotProps:l},[w,T]=ne(`root`,{ref:t,className:o(S.root,a),elementType:Yn,externalForwardedProps:{...C,component:s,...m},ownerState:g}),[E,D]=ne(`img`,{className:S.img,elementType:Xn,externalForwardedProps:C,additionalProps:{alt:r,src:d,srcSet:f,sizes:u},ownerState:g}),[O,k]=ne(`fallback`,{className:S.fallback,elementType:Zn,externalForwardedProps:C,shouldForwardComponentProp:!0,ownerState:g});return h=x?(0,Q.jsx)(E,{...D}):i||i===0?i:b&&r?r[0]:(0,Q.jsx)(O,{...k}),(0,Q.jsx)(w,{...T,children:h})});function er(e){return N(`MuiCollapse`,e)}we(`MuiCollapse`,[`root`,`horizontal`,`vertical`,`entered`,`hidden`,`wrapper`,`wrapperInner`]);var tr={},nr=e=>{let{orientation:t,classes:n}=e;return K({root:[`root`,t],entered:[`entered`],hidden:[`hidden`],wrapper:[`wrapper`,t],wrapperInner:[`wrapperInner`,t]},er,n)},rr=H(`div`,{name:`MuiCollapse`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,t[n.orientation],n.state===`entered`&&t.entered,n.state===`exited`&&!n.in&&n.collapsedSize===`0px`&&t.hidden]}})(V(({theme:e})=>({height:0,overflow:`hidden`,transition:e.transitions.create(`height`),variants:[{props:{orientation:`horizontal`},style:{height:`auto`,width:0,transition:e.transitions.create(`width`)}},{props:{state:`entered`},style:{height:`auto`,overflow:`visible`}},{props:{state:`entered`,orientation:`horizontal`},style:{width:`auto`}},{props:({ownerState:e})=>e.state===`exited`&&!e.in&&e.collapsedSize===`0px`,style:{visibility:`hidden`}}]}))),ir=H(`div`,{name:`MuiCollapse`,slot:`Wrapper`})({display:`flex`,width:`100%`,variants:[{props:{orientation:`horizontal`},style:{width:`auto`,height:`100%`}}]}),ar=H(`div`,{name:`MuiCollapse`,slot:`WrapperInner`})({width:`100%`,variants:[{props:{orientation:`horizontal`},style:{width:`auto`,height:`100%`}}]}),or=$.forwardRef(function(e,t){let n=ge({props:e,name:`MuiCollapse`}),{addEndListener:r,children:i,className:a,collapsedSize:s=`0px`,component:c,disablePrefersReducedMotion:l=!1,easing:u,in:d,onEnter:f,onEntered:p,onEntering:m,onExit:h,onExited:g,onExiting:_,orientation:v=`vertical`,slots:y=tr,slotProps:x=tr,style:S,timeout:C=U.standard,TransitionComponent:T=w,...E}=n,D={...n,orientation:v,collapsedSize:s},O=nr(D),k=fe(),A=$.useRef(null),j=$.useRef(null),M=typeof s==`number`?`${s}px`:s,N=v===`horizontal`,P=N?`width`:`height`,F=b(k.motion.reducedMotion,l),I=$.useRef(null),L=ve(t,I),R=()=>A.current?A.current[N?`clientWidth`:`clientHeight`]:0,z=me(I,(e,t)=>{A.current&&N&&(A.current.style.position=`absolute`),e.style[P]=M,f&&f(e,t)}),ee=me(I,(e,t)=>{let n=R();A.current&&N&&(A.current.style.position=``);let{duration:r,easing:i}=ie({style:S,timeout:C,easing:u},{mode:`enter`});if(C===`auto`&&!F.shouldReduceMotion){let e=k.transitions.getAutoHeightDuration(n);j.current=e}else j.current=null;let a=F.getTransitionTiming({duration:j.current??r,delay:void 0});e.style.transitionDuration=typeof a.duration==`string`?a.duration:`${a.duration}ms`,e.style[P]=`${n}px`,e.style.transitionTimingFunction=i,m&&m(e,t)}),B=me(I,(e,t)=>{e.style[P]=`auto`,p&&p(e,t)}),te=me(I,e=>{e.style[P]=`${R()}px`,h&&h(e)}),re=me(I,g),V=me(I,e=>{let t=R(),{duration:n,easing:r}=ie({style:S,timeout:C,easing:u},{mode:`exit`});if(C===`auto`&&!F.shouldReduceMotion){let e=k.transitions.getAutoHeightDuration(t);j.current=e}else j.current=null;let i=F.getTransitionTiming({duration:j.current??n,delay:void 0});e.style.transitionDuration=typeof i.duration==`string`?i.duration:`${i.duration}ms`,e.style[P]=M,e.style.transitionTimingFunction=r,_&&_(e)}),H=r?e=>{r(I.current,e)}:void 0,ae={slots:y,slotProps:x,component:c},[oe,W]=ne(`root`,{ref:L,className:o(O.root,a),elementType:rr,externalForwardedProps:ae,ownerState:D,additionalProps:{style:{[N?`minWidth`:`minHeight`]:M,...S}}}),[G,se]=ne(`wrapper`,{ref:A,className:O.wrapper,elementType:ir,externalForwardedProps:ae,ownerState:D}),[ce,le]=ne(`wrapperInner`,{className:O.wrapperInner,elementType:ar,externalForwardedProps:ae,ownerState:D});return(0,Q.jsx)(T,{in:d,onEnter:z,onEntered:B,onEntering:ee,onExit:te,onExited:re,onExiting:V,addEndListener:H,getAutoTimeout:C===`auto`?()=>j.current:void 0,reduceMotion:F.shouldReduceMotion,nodeRef:I,timeout:C===`auto`?null:C,...E,children:(e,{ownerState:t,...n})=>{let r={...D,state:e};return(0,Q.jsx)(oe,{...W,className:o(W.className,{entered:O.entered,exited:!d&&M===`0px`&&O.hidden}[e]),ownerState:r,...n,children:(0,Q.jsx)(G,{...se,ownerState:r,children:(0,Q.jsx)(ce,{...le,ownerState:r,children:i})})})}})});or&&(or.muiSupportAuto=!0);function sr(e,t,n){return at(e,t,n)}var cr=new Set([`company-quota`,`company-provider-limit`,`company-account`,`company-busy`,`company-trial-limit`,`company-key`,`company-policy`,`company-rejected`,`company-unreachable`,`company-service`,`company-config-changed`,`company-failed`]);function lr(e){return cr.has(e)||!e.startsWith(`company-`)}function ur(e,t){return vt(e,t)}var dr=Bt,fr={"session-revision-stale":[`Danh sách cuộc trò chuyện vừa thay đổi. Gửi lại tin nhắn.`,`The conversation list just changed. Send the message again.`],"catalog-unavailable":[`Danh sách cuộc trò chuyện chưa tải xong. Thử lại sau vài giây.`,`The conversation list has not loaded yet. Try again in a few seconds.`],"session-model-mismatch":[`Cuộc trò chuyện đã tạo nhưng đang dùng model khác model đã chọn, nên tin nhắn chưa được gửi.`,`The conversation was created with a different model than the one chosen, so the message was not sent.`],"gateway-command-response-timeout":[`Piagent chưa xác nhận được cuộc trò chuyện mới sau 2 phút; nó có thể đã được tạo và đang chạy. Xem danh sách cuộc trò chuyện bên trái trước khi gửi lại.`,`Piagent could not confirm the new conversation within 2 minutes; it may have been created and be running. Check the conversation list before sending again.`],"session-command-expired":[`Yêu cầu chờ quá lâu nên đã hết hạn. Gửi lại tin nhắn.`,`The request waited too long and expired. Send the message again.`]};function pr(e,t){let n=e.startsWith(`company-`)?sr(e,null,t):null;if(n)return`${n.title}: ${n.text}`;let r=fr[e]??dr[e];return r?X(t,...r):`${X(t,`Chưa tạo được cuộc trò chuyện`,`The conversation could not be created`)} (${e}).`}function mr(e,t){let n=dr[e?.reasonCode??``];return n?X(t,...n):null}var hr=(e,t)=>e?.state===`connecting`?X(t,`Đang kết nối phiên công ty…`,`Connecting the company runtime…`):mr(e,t)??X(t,`Chưa kết nối phiên công ty. Bấm để kết nối.`,`The company runtime is not connected. Select to connect.`);function gr({locale:e,onConnected:t}){let[n,r]=(0,$.useState)(),[i,o]=(0,$.useState)(!1),s=(0,$.useRef)(!1),c=()=>{s.current&&(s.current=!1,t())};if((0,$.useEffect)(()=>{let e=!0,t=()=>void Qe().then(t=>{e&&(r(t),t?.state===`ready`?c():t&&(s.current=!0))}).catch(()=>void 0);t();let n=window.setInterval(t,5e3);return()=>{e=!1,window.clearInterval(n)}},[]),!n||n.state===`ready`||n.state===`unconfigured`)return null;let l=async()=>{o(!0);try{let e=await Ze();r(e),e.state===`ready`&&c()}catch{r(await Qe().catch(()=>null)??n)}finally{o(!1)}},u=mr(n,e),d=i||n.state===`connecting`;return(0,Q.jsxs)(v,{severity:`warning`,role:`status`,sx:{mb:2},action:(0,Q.jsx)(a,{color:`inherit`,size:`small`,disabled:d,onClick:()=>void l(),sx:{whiteSpace:`nowrap`},children:d?X(e,`Đang kết nối…`,`Connecting…`):X(e,`Kết nối lại`,`Reconnect`)}),children:[X(e,`Chế độ công ty đang tắt nên chưa đọc hay gửi tiếp được cuộc trò chuyện này. Bấm Kết nối lại; macOS có thể hỏi quyền đọc key một lần.`,`Company mode is not running, so this conversation cannot be read or continued yet. Select Reconnect; macOS may ask once to read the key.`),u&&(0,Q.jsxs)(Q.Fragment,{children:[` `,u]})]})}function _r(e){return e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&e.keyCode!==229}var vr=q((0,Q.jsx)(`path`,{d:`M12 7V5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2zM6 19H4v-2h2zm0-4H4v-2h2zm0-4H4V9h2zm0-4H4V5h2zm4 12H8v-2h2zm0-4H8v-2h2zm0-4H8V9h2zm0-4H8V5h2zm9 12h-7v-2h2v-2h-2v-2h2v-2h-2V9h7c.55 0 1 .45 1 1v8c0 .55-.45 1-1 1m-1-8h-2v2h2zm0 4h-2v2h2z`}),`BusinessRounded`),yr=q((0,Q.jsx)(`path`,{d:`m19 9 1.25-2.75L23 5l-2.75-1.25L19 1l-1.25 2.75L15 5l2.75 1.25zm0 6-1.25 2.75L15 19l2.75 1.25L19 23l1.25-2.75L23 19l-2.75-1.25zm-7.5-5.5L9 4 6.5 9.5 1 12l5.5 2.5L9 20l2.5-5.5L17 12zm-1.51 3.49L9 15.17l-.99-2.18L5.83 12l2.18-.99L9 8.83l.99 2.18 2.18.99z`}),`AutoAwesomeOutlined`),br=q((0,Q.jsx)(`path`,{d:`M8 16h8v2H8zm0-4h8v2H8zm6-10H6c-1.1 0-2 .9-2 2v16c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8zm4 18H6V4h7v5h5z`}),`DescriptionOutlined`);function xr(e,t){let n=e.slice(0,t),r=/(^|[\s(])@"([^"\n]*)$/.exec(n);if(r)return{start:r.index+r[1].length,end:e[t]===`"`?t+1:t,query:r[2],quoted:!0};let i=/(^|[\s(])@([^\s"]*)$/.exec(n);return i?{start:i.index+i[1].length,end:t+(/^[^\s"]*/.exec(e.slice(t))?.[0].length??0),query:i[2],quoted:!1}:null}function Sr(e,t,n){let r=t.quoted||/\s/.test(n.value),i=r?`@"${n.value}"`:`@${n.value}`,a=n.kind===`directory`,o=e.slice(t.end),s=a||/^\s/.test(o)?``:` `;return{text:e.slice(0,t.start)+i+s+o,caret:t.start+i.length+s.length-(a&&r?1:0)}}function Cr(e,t){let n=e.slice(0,t);return/^\/[^\s/]*$/.test(n)?{start:0,end:t+(/^[^\s]*/.exec(e.slice(t))?.[0].length??0),query:n.slice(1),quoted:!1}:null}function wr(e,t,n){let r=n.kind===`skill`?`/skill:${n.name}`:`/${n.name}`,i=e.slice(t.end);return{text:r+(/^\s/.test(i)?``:` `)+i,caret:r.length+1}}var Tr=20,Er=e=>e.normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase();function Dr(e,t,n){let r=Er(t.replace(/^skill:/,``)),i=e=>Er(e.name).startsWith(r)?0:Er(e.name).includes(r)?1:Er(e.description).includes(r)?2:3,a=e=>e.origin===`piagent`?`Piagent`:e.plugin?`${e.plugin} · ${e.origin===`claude`?`Claude`:`Codex`} plugin`:`${e.scope===`user`?`~/`:``}.${e.origin===`pi`?`pi`:e.origin}`;return e.filter(e=>i(e)<3&&(!t.startsWith(`skill:`)||e.kind===`skill`)).sort((e,t)=>i(e)-i(t)||e.name.localeCompare(t.name)).slice(0,Tr).map(e=>({key:`${e.kind}:${e.name}`,icon:e.kind,label:e.kind===`skill`?`/skill:${e.name}`:`/${e.name}`,hint:e.argumentHint,detail:`${e.description}${e.description?` · `:``}${e.kind===`skill`?`skill`:X(n,`lệnh`,`command`)} ${a(e)}`,apply:(t,n)=>wr(t,n,e)}))}function Or({projectRef:e,value:t,onChange:n,locale:r,builtIns:i=[]}){let a=(0,$.useRef)(null),o=(0,$.useId)(),[s,c]=(0,$.useState)(null),[l,u]=(0,$.useState)(!1),[d,f]=(0,$.useState)(null),[p,m]=(0,$.useState)(0),[h,g]=(0,$.useState)(null),[_,v]=(0,$.useState)(null),y=e&&s!==null&&s<=t.length?s:null,b=y===null?null:Cr(t,y),x=y===null||b?null:xr(t,y),C=b??x,w=b?`command`:`path`,T=C&&`${w}:${C.start}`!==d?C:null,D=T&&w===`path`?T.query:null;(0,$.useEffect)(()=>{if(D===null||!e){g(null);return}let t=new AbortController,n=setTimeout(()=>{Z(e,D,t.signal).then(e=>{g({query:D,items:e.suggestions.map(e=>({key:e.value,label:e.label,hint:null,icon:e.kind,detail:e.detail.slice(0,Math.max(0,e.detail.length-e.label.replace(/\/$/,``).length)),apply:(t,n)=>Sr(t,n,e)}))}),m(0)}).catch(()=>{t.signal.aborted||g({query:D,items:[]})})},90);return()=>{clearTimeout(n),t.abort()}},[e,D]);let O=!!(T&&w===`command`&&e&&_?.projectRef!==e);(0,$.useEffect)(()=>{if(!O||!e)return;let t=new AbortController;return Be(e,t.signal).then(t=>v({projectRef:e,list:t.commands})).catch(()=>{t.signal.aborted||v({projectRef:e,list:[]})}),()=>t.abort()},[O,e]);let k=T?w===`path`?h?.items??null:_&&_.projectRef===e?Dr([...i,..._.list.filter(e=>!i.some(t=>t.name===e.name))],T.query,r):null:null;(0,$.useEffect)(()=>{m(0)},[w,T?.query]);let j=!!(l&&T&&k&&a.current),M=j?k:[];(0,$.useEffect)(()=>{j&&document.getElementById(`${o}-${p}`)?.scrollIntoView({block:`nearest`})},[j,p,o]);let N=(0,$.useRef)(null);(0,$.useLayoutEffect)(()=>{let e=N.current,n=a.current;!e||!n||e.text!==t||(N.current=null,n.focus(),n.setSelectionRange(e.caret,e.caret),c(e.caret))},[t]);let P=e=>{if(!T)return;let r=e.apply(t,T);N.current=r,n(r.text),c(r.caret)},F=e=>!j||e.nativeEvent.isComposing||e.keyCode===229?!1:e.key===`Escape`?(e.preventDefault(),f(`${w}:${T.start}`),!0):M.length?e.key===`ArrowDown`||e.key===`ArrowUp`?(e.preventDefault(),m(t=>(t+(e.key===`ArrowDown`?1:M.length-1))%M.length),!0):(e.key===`Enter`||e.key===`Tab`)&&!e.shiftKey&&!e.altKey&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),P(M[Math.min(p,M.length-1)]),!0):!1,I=e=>e===`directory`?(0,Q.jsx)(A,{fontSize:`small`,color:`primary`}):e===`file`?(0,Q.jsx)(br,{fontSize:`small`,color:`action`}):e===`skill`?(0,Q.jsx)(yr,{fontSize:`small`,color:`secondary`}):(0,Q.jsx)(E,{fontSize:`small`,color:`primary`}),L=w===`command`?X(r,`Lệnh và skill`,`Commands and skills`):X(r,`File và folder`,`Files and folders`),z=a.current,ee=(0,Q.jsx)(oe,{open:j,anchorEl:z,placement:`top-start`,disablePortal:!0,sx:{zIndex:1350,width:Math.min(640,z?.clientWidth??640)},modifiers:[{name:`offset`,options:{offset:[0,10]}}],children:(0,Q.jsxs)(te,{elevation:8,sx:{borderRadius:1,overflow:`hidden`,display:`flex`,flexDirection:`column`,maxHeight:340},children:[(0,Q.jsx)(S,{variant:`caption`,color:`text.secondary`,sx:{px:1.5,pt:1,pb:.5},children:w===`command`?X(r,`Lệnh và skill của project và trên máy này · Tab để chọn`,`Commands and skills of the project and on this computer · Tab to pick`):X(r,`File và folder · gõ ~/ hoặc / để chọn folder khác trên máy · Tab để chọn`,`Files and folders · type ~/ or / for other folders on this computer · Tab to pick`)}),M.length?(0,Q.jsx)(R,{component:`ul`,role:`listbox`,id:o,"aria-label":L,sx:{listStyle:`none`,m:0,p:.5,pt:0,overflowY:`auto`},children:M.map((e,t)=>(0,Q.jsxs)(R,{component:`li`,id:`${o}-${t}`,role:`option`,"aria-selected":t===p,onMouseDown:e=>e.preventDefault(),onMouseEnter:()=>m(t),onClick:()=>P(e),sx:{display:`flex`,alignItems:`center`,gap:1,minWidth:0,px:1,py:.55,borderRadius:1,cursor:`pointer`,bgcolor:t===p?`action.selected`:`transparent`},children:[I(e.icon),(0,Q.jsx)(S,{noWrap:!0,sx:{flexShrink:0,maxWidth:`55%`,fontSize:14,fontWeight:600},children:e.label}),e.hint&&(0,Q.jsx)(S,{noWrap:!0,variant:`caption`,sx:{flexShrink:0,maxWidth:`25%`,fontFamily:`monospace`},children:e.hint}),(0,Q.jsx)(S,{noWrap:!0,variant:`caption`,color:`text.secondary`,sx:{minWidth:0},children:e.detail})]},e.key))}):(0,Q.jsx)(S,{variant:`body2`,color:`text.secondary`,sx:{px:1.5,pb:1.25},children:w===`command`?X(r,`Không có lệnh hoặc skill khớp`,`No matching command or skill`):X(r,`Không có file hoặc folder khớp`,`No matching file or folder`)})]})}),B=e=>c(e.target.selectionStart??null);return{inputRef:a,menu:ee,onKeyDown:F,track:B,inputProps:{onFocus:()=>u(!0),onBlur:()=>u(!1)},htmlInput:{onSelect:B,"aria-autocomplete":`list`,"aria-controls":j&&M.length?o:void 0,"aria-activedescendant":j&&M.length?`${o}-${p}`:void 0}}}var kr=`agent_watch_managed`;function Ar(e,t,n){return e===`native-project-picker-unavailable`||e===`project-import-picker-failed`?X(n,`Không mở được hộp chọn thư mục của máy. Thử lại; nếu vẫn lỗi, mở cuộc trò chuyện từ Terminal trong thư mục đó (pi hoặc piagent studio).`,`The folder picker could not open. Try again; if it still fails, start a conversation from a Terminal in that folder (pi or piagent studio).`):e===`project-import-folder-invalid`?X(n,`Không dùng được thư mục này: thư mục gốc của ổ đĩa hoặc một liên kết (symlink). Chọn thư mục thật của project.`,`This folder cannot be used: a drive's root or a symbolic link. Choose the project's real folder.`):t===429?X(n,`Thao tác quá nhanh. Đợi vài giây rồi thử lại.`,`Too many attempts. Wait a few seconds and try again.`):X(n,`Không thể thêm thư mục. Thử lại; nếu vẫn lỗi, chạy piagent dashboard doctor.`,`Could not add this folder. Try again; if it still fails, run piagent dashboard doctor.`)}var jr=[[`Đọc project này (chỉ đọc) và ghi lại project context.`,`Read this project (read-only) and record the project context.`],[`Review diff hiện tại. Chỉ đọc.`,`Review the current diff. Read-only.`],[`Chạy test của project và giải thích lỗi nếu có.`,`Run the project's tests and explain any failure.`],[`Lập plan cho việc sau, chưa sửa code: `,`Plan this change before editing any code: `]];function Mr({active:e,defaultProjectRef:t,busy:n,error:r,onCancel:i,onCreate:o}){let{locale:s}=Oe(),[c,l]=(0,$.useState)(),[u,d]=(0,$.useState)(void 0),[f,m]=(0,$.useState)(!1),h=u===null&&c?.models.length===1&&c.models[0].provider===`agent_watch_managed`,[g,_]=(0,$.useState)(!1),[v,b]=(0,$.useState)(``),[C,w]=(0,$.useState)(``),[T,E]=(0,$.useState)(`high`),[D,O]=(0,$.useState)(!1),[A,M]=(0,$.useState)(!1),[N,F]=(0,$.useState)(null),[I,z]=(0,$.useState)(()=>mn(gn)),B=e=>{z(e),yn(gn,e)},[te,ne]=(0,$.useState)(null),[V,H]=(0,$.useState)(()=>hn(`new-chat`)??[]),[ie,U]=(0,$.useState)(null);(0,$.useEffect)(()=>{_n(gn,V.length?V:null)},[V]);let[ae,oe]=(0,$.useState)(!1),W=(0,$.useRef)(0),[se,ce]=(0,$.useState)(null),[le,ue]=(0,$.useState)(null),[fe,K]=(0,$.useState)(!1),[me,ge]=(0,$.useState)(null);(0,$.useEffect)(()=>{if(!e)return;let n=new AbortController;return l(void 0),_(!1),ge(null),U(null),oe(!1),O(!1),W.current=0,He(n.signal).then(e=>{n.signal.aborted||(l(e),b(e.projects.some(e=>e.projectRef===t)?t:e.projects[0]?.projectRef??``),w(e.defaultModelRef??``),E(e.defaultThinkingLevel??`high`),F(null),M(!1))}).catch(()=>{n.signal.aborted||_(!0)}),d(void 0),Qe(n.signal).then(e=>{n.signal.aborted||d(e)}).catch(()=>{n.signal.aborted||d(null)}),()=>n.abort()},[e,t]),(0,$.useEffect)(()=>{if(!e)return;let t=e=>{pn(e.dataTransfer)&&e.preventDefault()};return window.addEventListener(`dragover`,t),window.addEventListener(`drop`,t),()=>{window.removeEventListener(`dragover`,t),window.removeEventListener(`drop`,t)}},[e]);let q=c?.projects.find(e=>e.projectRef===v),ve=Or({projectRef:q?.projectRef,value:I,onChange:B,locale:s}),Y=c?.models.find(e=>e.modelRef===C),be=!h&&Y?.provider===kr,Se=h?[]:c?.models.filter(e=>e.provider===kr)??[],we=(h||be)&&Y?.managedFast===!0,De=h?c?.models??[]:c?.models.filter(e=>e.provider!==kr)??[],ke=async()=>{m(!0);try{let e=await Ze().catch(()=>null),t=await He();l(t),d(e??await Qe().catch(()=>null));let n=t.models.find(e=>e.provider===kr);n&&(w(n.modelRef),Ne())}catch{_(!0)}finally{m(!1)}},Ae=c?.models.find(e=>e.modelRef===c.defaultModelRef),je=(0,$.useMemo)(()=>Y?.thinkingLevels??[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],[Y]);(0,$.useEffect)(()=>{je.includes(T)||E(je.includes(`high`)?`high`:je[0]??`off`)},[C,je]);let Me=e=>t=>{ce(e),ue(t.currentTarget)},Ne=()=>{ce(null),ue(null)},Pe=async()=>{K(!0),ge(null);try{let e=await et(),t=e.projects?.length?e.projects:[e.project];l(e=>e&&{...e,projects:[...e.projects.filter(e=>!t.some(t=>t.projectRef===e.projectRef)),...t]}),b(e.project.projectRef),Ne()}catch(e){e instanceof Xe&&e.status===409?ge(null):ge(Ar(e instanceof Xe?e.code:null,e instanceof Xe?e.status:0,s))}finally{K(!1)}},Fe=e=>{if(!e?.length)return;let t=[...V],n=!1,r=null;for(let i of[...e]){if(t.some(e=>e.name===i.name&&e.size===i.size&&e.lastModified===i.lastModified))continue;let e=Jt(i.name);if(`refused`in e){r=`${i.name}: ${fn(e.refused,s)}`;continue}if(t.length===4){n=!0;continue}t.push(i)}H(t),U(r??(n?X(s,`Mỗi tin nhắn nhận tối đa 4 file.`,`Each message accepts at most 4 files.`):null))},Ie=!n&&!g&&V.length<4,Le=(0,$.useRef)(!1),Re=()=>{Le.current||n||!q||!I.trim()||(Le.current=!0,Promise.resolve(o({projectRef:v,placeRef:q.placeRef,modelRef:C||null,thinkingLevel:T,permissionMode:N,...we&&A?{fast:!0}:{},message:I,files:V})).finally(()=>{Le.current=!1}))};return(0,Q.jsxs)(R,{sx:{minHeight:`calc(100vh - 68px)`,display:`flex`,flexDirection:`column`},children:[(0,Q.jsx)(R,{sx:{p:{xs:1.5,sm:2}},children:(0,Q.jsx)(L,{"aria-label":X(s,`Quay lại`,`Back`),onClick:i,children:(0,Q.jsx)(Ee,{})})}),(0,Q.jsxs)(P,{sx:{flex:1,alignItems:`center`,justifyContent:`center`,px:2,pb:{xs:5,md:12}},spacing:4,children:[(0,Q.jsxs)(P,{spacing:1.75,sx:{alignItems:`center`},children:[(0,Q.jsx)(ut,{size:44}),(0,Q.jsx)(S,{component:`h1`,sx:{fontSize:{xs:`1.9rem`,md:`2.3rem`},fontWeight:650,letterSpacing:`-.04em`,textAlign:`center`},children:X(s,`Hôm nay làm gì?`,`What should we work on?`)}),(0,Q.jsx)(S,{color:`text.secondary`,sx:{textAlign:`center`,maxWidth:520,fontSize:14.5},children:X(s,`Nói việc bằng lời thường. Guard kiểm tra mọi tool call; việc rủi ro chờ bạn duyệt.`,`Say what you need in plain language. The guard checks every tool call; risky actions wait for you.`)})]}),(0,Q.jsxs)(R,{sx:{position:`relative`,width:`100%`,maxWidth:820,border:1,borderColor:ae?`primary.main`:`divider`,borderStyle:ae?`dashed`:`solid`,borderRadius:2.5,bgcolor:`background.paper`,p:1.5,boxShadow:`0 24px 60px -24px rgba(0,0,0,.55)`,transition:`border-color .16s, box-shadow .16s`,"&:focus-within":{borderColor:`rgba(var(--piagent-palette-primary-mainChannel) / .55)`,boxShadow:`0 0 0 4px rgba(var(--piagent-palette-primary-mainChannel) / .12), 0 24px 60px -24px rgba(0,0,0,.55)`}},onDragEnter:e=>{pn(e.dataTransfer)&&(W.current+=1,oe(!0))},onDragOver:e=>{pn(e.dataTransfer)&&(e.preventDefault(),e.dataTransfer.dropEffect=Ie?`copy`:`none`)},onDragLeave:e=>{pn(e.dataTransfer)&&(--W.current,W.current<=0&&(W.current=0,oe(!1)))},onDrop:e=>{pn(e.dataTransfer)&&(e.preventDefault(),W.current=0,oe(!1),Ie&&Fe(e.dataTransfer.files))},children:[ae&&(0,Q.jsxs)(R,{role:`status`,sx:{position:`absolute`,inset:0,zIndex:3,display:`grid`,alignContent:`center`,justifyItems:`center`,gap:.5,borderRadius:1,bgcolor:`background.paper`,opacity:.96,pointerEvents:`none`,textAlign:`center`},children:[(0,Q.jsx)(S,{sx:{fontWeight:650},children:Ie?X(s,`Thả tài liệu vào đây`,`Drop documents here`):V.length>=4?X(s,`Đã đủ 4 file cho tin nhắn đầu tiên`,`The first message already holds 4 files`):X(s,`Chưa nhận file lúc này`,`Files cannot be attached right now`)}),Ie&&(0,Q.jsx)(S,{variant:`caption`,color:`text.secondary`,children:$t(s)})]}),!c&&!g?(0,Q.jsxs)(P,{direction:`row`,spacing:1.5,sx:{minHeight:126,alignItems:`center`,justifyContent:`center`},children:[(0,Q.jsx)(ee,{size:20}),(0,Q.jsx)(S,{color:`text.secondary`,children:X(s,`Đang mở…`,`Opening…`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(re,{autoFocus:!0,fullWidth:!0,multiline:!0,minRows:3,maxRows:8,value:I,disabled:n||g,inputRef:ve.inputRef,...ve.inputProps,onChange:e=>{B(e.target.value),ve.track(e)},onKeyDown:e=>{ve.onKeyDown(e)||_r(e)&&(e.preventDefault(),Re())},onPaste:e=>{e.clipboardData?.files.length&&(e.preventDefault(),Ie&&Fe(e.clipboardData.files))},placeholder:X(s,`Nhắn cho Piagent… (@ để chọn file, folder)`,`Message Piagent… (@ for files and folders)`),variant:`standard`,slotProps:{input:{disableUnderline:!0},htmlInput:{maxLength:32768,...ve.htmlInput}},sx:{px:.5}}),ve.menu,V.length>0&&(0,Q.jsx)(P,{direction:`row`,sx:{flexWrap:`wrap`,gap:.75,px:.5,pt:.75},"aria-label":X(s,`File sẽ gửi cùng tin nhắn đầu tiên`,`Files for the first message`),children:V.map(e=>(0,Q.jsx)(Ce,{size:`small`,variant:`outlined`,label:`${e.name} · ${Xt(e.size)}`,onDelete:n?void 0:()=>{H(t=>t.filter(t=>t!==e)),U(null)},deleteIcon:(0,Q.jsx)(Hn,{"aria-label":`${X(s,`Bỏ`,`Remove`)} ${e.name}`,role:`button`})},`${e.name}:${e.size}:${e.lastModified}`))}),(0,Q.jsx)(or,{in:D,id:`piagent-new-session-options`,children:(0,Q.jsxs)(R,{sx:{mx:.35,mt:1,px:1.1,py:1,borderRadius:1,bgcolor:`action.hover`},children:[(0,Q.jsx)(S,{variant:`caption`,sx:{display:`block`,mb:.75,fontWeight:650},children:X(s,`Tùy chọn cho tin nhắn đầu tiên`,`Options for the first message`)}),(0,Q.jsxs)(P,{direction:`row`,sx:{alignItems:`center`,gap:.75,flexWrap:`wrap`},children:[(0,Q.jsx)(a,{size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(p,{}),endIcon:(0,Q.jsx)(j,{}),onClick:Me(`thinking`),children:rt(T,s)}),(0,Q.jsx)(a,{size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(y,{}),endIcon:(0,Q.jsx)(j,{}),onClick:Me(`permission`),children:h||be?pt(N,s):N?rt(N,s):X(s,`Quyền theo profile`,`Profile access`)}),(0,Q.jsxs)(a,{component:`label`,size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(Vn,{}),disabled:!Ie,"aria-label":`${X(s,`Thêm file`,`Add files`)} (${V.length}/4)`,children:[X(s,`Đính kèm`,`Attach`),(0,Q.jsx)(`input`,{type:`file`,hidden:!0,multiple:!0,disabled:!Ie,accept:``,onChange:e=>{Fe(e.target.files),e.currentTarget.value=``}})]})]}),be&&(0,Q.jsx)(S,{variant:`caption`,color:`text.secondary`,sx:{display:`block`,mt:.75},children:X(s,`Model và quyền theo Harness công ty; thinking chọn ở đây.`,`Models and access follow the company Harness; choose thinking here.`)})]})}),(0,Q.jsxs)(P,{direction:`row`,sx:{mt:1,alignItems:`center`,gap:.65,flexWrap:`nowrap`,minWidth:0},children:[(0,Q.jsx)(pe,{title:D?X(s,`Ẩn tùy chọn`,`Hide options`):X(s,`Thêm tùy chọn`,`More options`),children:(0,Q.jsx)(L,{size:`small`,"aria-label":D?X(s,`Ẩn tùy chọn`,`Hide options`):X(s,`Thêm tùy chọn`,`More options`),"aria-expanded":D,"aria-controls":`piagent-new-session-options`,onClick:()=>O(e=>!e),sx:{flex:`0 0 auto`,bgcolor:D?`action.selected`:`transparent`},children:(0,Q.jsx)(de,{fontSize:`small`,sx:{transition:`transform .16s ease`,transform:D?`rotate(45deg)`:`none`}})})}),(0,Q.jsx)(a,{size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(x,{}),endIcon:(0,Q.jsx)(j,{}),onClick:Me(`project`),"aria-label":`${X(s,`Project`,`Project`)}: ${q?.label??X(s,`Chọn project`,`Choose project`)}`,sx:{minWidth:0,maxWidth:{xs:118,sm:250},px:{xs:.75,sm:1},"& .MuiButton-startIcon":{display:{xs:`none`,sm:`inherit`}}},children:(0,Q.jsx)(R,{component:`span`,sx:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:q?.label??X(s,`Chọn project`,`Choose project`)})}),(0,Q.jsx)(a,{size:`small`,color:`inherit`,startIcon:be?(0,Q.jsx)(vr,{}):(0,Q.jsx)(xe,{}),endIcon:(0,Q.jsx)(j,{}),onClick:Me(`model`),"aria-label":`${X(s,`Model`,`Model`)}: ${be?X(s,`Công ty · agent-watch-auto`,`Company · agent-watch-auto`):Y?.displayName??Ae?.displayName??X(s,`Mặc định của Pi`,`Pi default`)}`,sx:{minWidth:0,maxWidth:{xs:142,sm:250},px:{xs:.75,sm:1},"& .MuiButton-startIcon":{display:{xs:`none`,sm:`inherit`}}},children:(0,Q.jsx)(R,{component:`span`,sx:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:be?X(s,`Công ty · agent-watch-auto`,`Company · agent-watch-auto`):Y?`${Y.displayName}${Y.modelRef===c?.defaultModelRef?X(s,` · mặc định`,` · default`):``}`:Ae?.displayName??X(s,`Mặc định của Pi`,`Pi default`)})}),we&&(0,Q.jsx)(pe,{title:Ot(s),arrow:!0,children:(0,Q.jsx)(a,{size:`small`,color:`inherit`,variant:`outlined`,startIcon:(0,Q.jsx)(_e,{}),"aria-pressed":A,"aria-label":`${dt(A,s)}. ${Ot(s)}`,onClick:()=>M(e=>!e),sx:{flex:`0 0 auto`,minWidth:0,px:{xs:.75,sm:1},borderRadius:1,borderColor:`divider`,color:`text.secondary`,"& .MuiButton-startIcon":{mr:{xs:0,sm:.65},ml:0},...A?ft:{}},children:(0,Q.jsx)(R,{component:`span`,sx:{display:{xs:`none`,sm:`inline`},whiteSpace:`nowrap`},children:dt(A,s)})})}),(0,Q.jsx)(R,{sx:{flex:1,minWidth:0}}),(0,Q.jsx)(L,{"aria-label":X(s,`Gửi`,`Send`),disabled:n||g||!q||!I.trim(),onClick:Re,sx:{flex:`0 0 auto`,width:34,height:34,borderRadius:999,transition:`transform .12s`,bgcolor:`primary.main`,color:`primary.contrastText`,"&:hover":{bgcolor:`primary.main`,color:`primary.contrastText`,transform:`translateY(-1px)`},"&.Mui-disabled":{bgcolor:`action.disabledBackground`}},children:(0,Q.jsx)(Un,{fontSize:`small`})})]}),we&&A&&(0,Q.jsx)(S,{variant:`caption`,sx:{display:`block`,px:.5,pt:.75,color:`warning.main`},children:Ot(s)})]}),(ie||me||r||g)&&(0,Q.jsx)(S,{role:`status`,color:`error`,variant:`caption`,sx:{display:`block`,px:.5,pt:1},children:ie??me??r??X(s,`Không tải được lựa chọn`,`Could not load choices`)})]}),c&&!I&&(0,Q.jsx)(P,{direction:`row`,role:`group`,"aria-label":X(s,`Việc mẫu`,`Starter tasks`),sx:{flexWrap:`wrap`,justifyContent:`center`,gap:1,maxWidth:820,mt:`16px !important`},children:jr.map(([e,t])=>(0,Q.jsx)(Ce,{variant:`outlined`,clickable:!0,label:X(s,e,t),onClick:()=>{B(X(s,e,t)),requestAnimationFrame(()=>ve.inputRef.current?.focus())},sx:{height:30,color:`text.secondary`,"&:hover":{color:`text.primary`}}},t))})]}),(0,Q.jsxs)(Te,{anchorEl:le,open:se===`project`,onClose:Ne,slotProps:{paper:{sx:{width:310,maxHeight:380}}},children:[(c?.projects??[]).map(e=>(0,Q.jsxs)(he,{selected:v===e.projectRef,onClick:()=>{b(e.projectRef),Ne()},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(ht,{name:`folder`,size:26})}),(0,Q.jsx)(J,{primary:e.label,secondary:e.hint,slotProps:{secondary:{noWrap:!0,title:e.hint}}})]},e.projectRef)),(0,Q.jsx)(ye,{}),(0,Q.jsxs)(he,{disabled:fe||c?.projectImport?.status!==`available`,onClick:()=>void Pe(),children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(de,{})}),(0,Q.jsx)(J,{primary:fe?X(s,`Đang chọn…`,`Choosing…`):X(s,`Thêm một hoặc nhiều folder`,`Add one or more folders`)})]})]}),(0,Q.jsxs)(Te,{anchorEl:le,open:se===`model`,onClose:Ne,slotProps:{paper:{sx:{width:360,maxHeight:440}}},children:[!h&&(Se.length>0||u?.available)&&[(0,Q.jsx)(k,{children:X(s,`Công ty`,`Company`)},`company-heading`),...Se.length?Se.map(e=>(0,Q.jsxs)(he,{selected:C===e.modelRef,onClick:()=>{w(e.modelRef),Ne()},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(vr,{})}),(0,Q.jsx)(J,{primary:`agent-watch-auto`,secondary:X(s,`Harness công ty · Studio quản lý model`,`Company Harness · models managed by Studio`)})]},e.modelRef)):[(0,Q.jsxs)(he,{disabled:f,onClick:()=>void ke(),children:[(0,Q.jsx)(G,{children:f?(0,Q.jsx)(ee,{size:20}):(0,Q.jsx)(vr,{})}),(0,Q.jsx)(J,{primary:`agent-watch-auto`,secondary:f?X(s,`Đang kết nối…`,`Connecting…`):hr(u,s),slotProps:{secondary:{sx:{whiteSpace:`normal`}}}})]},`company-connect`)],(0,Q.jsx)(k,{children:X(s,`Cá nhân`,`Personal`)},`personal-heading`)],!c?.defaultModelRef&&(0,Q.jsxs)(he,{selected:!C,onClick:()=>{w(``),Ne()},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(xe,{})}),(0,Q.jsx)(J,{primary:X(s,`Model mặc định của Pi`,`Pi default model`)})]}),De.map(e=>(0,Q.jsxs)(he,{selected:C===e.modelRef,onClick:()=>{w(e.modelRef),Ne()},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(ht,{name:e.provider,size:26})}),(0,Q.jsx)(J,{primary:e.displayName,secondary:e.modelRef===c?.defaultModelRef?X(s,`Mặc định · ${e.provider} · High`,`Default · ${e.provider} · High`):e.provider})]},e.modelRef))]}),(0,Q.jsx)(Te,{anchorEl:le,open:se===`thinking`,onClose:Ne,slotProps:{paper:{sx:{width:250,maxHeight:400}}},children:je.map(e=>(0,Q.jsxs)(he,{value:e,selected:T===e,onClick:()=>{E(e),Ne()},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(p,{})}),(0,Q.jsx)(J,{primary:rt(e,s)})]},e))}),(0,Q.jsx)(Te,{anchorEl:le,open:se===`permission`,onClose:Ne,slotProps:{paper:{sx:{width:310}}},children:h||be?[(0,Q.jsxs)(he,{selected:N!==`trusted-full-access`&&N!==`bypass`,onClick:()=>{F(null),Ne()},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(y,{})}),(0,Q.jsx)(J,{primary:pt(null,s),secondary:X(s,`Hỏi trước mỗi lệnh cần internet`,`Asks before each command that needs the internet`)})]},`ask`),(0,Q.jsxs)(he,{selected:N===`trusted-full-access`,onClick:()=>{Ne(),ne(`trusted-full-access`)},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(y,{color:`warning`})}),(0,Q.jsx)(J,{primary:pt(`trusted-full-access`,s),secondary:X(s,`Chỉ hỏi việc bắt buộc phải xác nhận`,`Asks only what must be confirmed`)})]},`full`),...Y?.managedBypass?[(0,Q.jsxs)(he,{selected:N===`bypass`,onClick:()=>{Ne(),ne(`bypass`)},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(y,{color:`error`})}),(0,Q.jsx)(J,{primary:`Bypass`,secondary:X(s,`Không hỏi gì; admin Studio có thể tắt`,`Asks nothing; a Studio administrator can turn it off`)})]},`bypass`)]:[]]:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(he,{selected:N===null,onClick:()=>{F(null),Ne()},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(y,{})}),(0,Q.jsx)(J,{primary:X(s,`Theo profile project`,`Project profile default`)})]}),[`read-only`,`workspace-write`,`trusted-full-access`,`bypass`].map(e=>(0,Q.jsxs)(he,{selected:N===e,onClick:()=>{Ne(),e===`trusted-full-access`||e===`bypass`?ne(e):F(e)},children:[(0,Q.jsx)(G,{children:(0,Q.jsx)(y,{color:e===`bypass`?`error`:e===`trusted-full-access`?`warning`:void 0})}),(0,Q.jsx)(J,{primary:rt(e,s)})]},e))]})}),(0,Q.jsx)(lt,{open:te!==null,title:te===`bypass`?X(s,`Tạo cuộc trò chuyện với Bypass?`,`Create with Bypass?`):X(s,`Tạo session với toàn quyền?`,`Create with full access?`),description:te===`bypass`?h||be?kt(s):mt(s):h||be?it(s):X(s,`Session mới được phép đọc, sửa file và chạy command trong runtime. Xóa dữ liệu và gửi ra ngoài vẫn cần xác nhận riêng.`,`The new session may read and edit files and run commands. Deletion and external transfer still require separate approval.`),cancelLabel:X(s,`Hủy`,`Cancel`),confirmLabel:te===`bypass`?X(s,`Dùng Bypass`,`Use Bypass`):X(s,`Dùng toàn quyền`,`Use full access`),onCancel:()=>ne(null),onConfirm:()=>{let e=te;ne(null),e&&F(e)}})]})}var Nr=(e,t,n)=>e===`vi`?t:n,Pr=[[`⌘K`,`Mở bảng lệnh`,`Open the command palette`],[`⌘⇧O`,`Cuộc trò chuyện mới`,`New chat`],[`⌘,`,`Cài đặt`,`Settings`],[`⌘/`,`Phím tắt và lệnh /`,`Shortcuts and / commands`],[`Esc`,`Dừng lượt đang chạy (trong ô nhập)`,`Stop the running turn (in the composer)`]];function Fr(e,t){let n=/^\/([a-z][a-z-]*)(?:\s+([\s\S]*))?$/.exec(e.trim()),r=n?t.find(e=>e.name===n[1]):void 0;return r?{command:r,argument:(n[2]??``).trim()}:null}var Ir=(e,t,n,r)=>({tone:`error`,text:t instanceof Error&&t.message===`session-runtime-busy`?Nr(e,`${n}: lượt này đang chạy, thử lại khi xong.`,`${r}: this turn is running; try again when it ends.`):Nr(e,`${n}. Thử lại.`,`${r}. Try again.`)});async function Lr(e,t,n,r,i){try{return await t(),n}catch(t){return Ir(e,t,r,i)}}function Rr(e){let{locale:t,actions:n}=e,r=(e,n)=>Nr(t,e,n),i=(e,t)=>({tone:`success`,text:r(e,t)}),a=(e,t)=>({tone:`warning`,text:r(e,t)}),o=[],s=(e,t,n,i,a)=>o.push({name:e,argumentHint:t,description:r(n,i),run:a});return s(`help`,null,`Danh sách lệnh / và phím tắt`,`The / commands and keyboard shortcuts`,async()=>({tone:`info`,text:[...o.map(e=>`/${e.name}${e.argumentHint?` ${e.argumentHint}`:``} — ${e.description}`),...Pr.map(([e,t,n])=>`${e} — ${r(t,n)}`)].join(`
3
+ `)})),s(`new`,null,`Cuộc trò chuyện mới`,`New chat`,async()=>(n.newChat(),i(`Đã mở cuộc trò chuyện mới.`,`Opened a new chat.`))),s(`stop`,null,`Dừng lượt đang chạy`,`Stop the running turn`,async()=>e.running?Lr(t,n.stop,i(`Đã dừng lượt đang chạy.`,`Stopped the running turn.`),`Chưa dừng được`,`Could not stop`):{tone:`info`,text:r(`Không có lượt nào đang chạy.`,`No turn is running.`)}),s(`name`,`<tên>`,`Đổi tên cuộc trò chuyện`,`Rename the conversation`,async e=>e?Lr(t,()=>n.rename(e.slice(0,200)),i(`Đã đổi tên thành “${e.slice(0,200)}”.`,`Renamed to “${e.slice(0,200)}”.`),`Chưa đổi được tên`,`Could not rename`):a(`Cách dùng: /name <tên mới>`,`Usage: /name <new name>`)),s(`fork`,null,`Tạo cuộc trò chuyện mới từ cuộc này`,`Fork this conversation`,async()=>Lr(t,n.fork,i(`Đã tạo bản sao của cuộc trò chuyện.`,`Forked the conversation.`),`Chưa tạo được bản sao`,`Could not fork`)),s(`pin`,null,e.pinned?`Bỏ ghim cuộc trò chuyện`:`Ghim cuộc trò chuyện`,e.pinned?`Unpin the conversation`:`Pin the conversation`,async()=>Lr(t,()=>n.pin(!e.pinned),e.pinned?i(`Đã bỏ ghim.`,`Unpinned.`):i(`Đã ghim.`,`Pinned.`),`Chưa đổi được ghim`,`Could not change the pin`)),s(`archive`,null,`Lưu trữ cuộc trò chuyện`,`Archive the conversation`,async()=>Lr(t,n.archive,i(`Đã lưu trữ cuộc trò chuyện.`,`Archived the conversation.`),`Chưa lưu trữ được`,`Could not archive`)),e.thinkingLevels.length&&s(`thinking`,`<${e.thinkingLevels.join(`|`)}>`,`Đổi mức suy luận`,`Change the thinking level`,async r=>e.thinkingLevels.includes(r)?Lr(t,()=>n.setThinking(r),i(`Đã đổi thinking sang ${r}.`,`Thinking is now ${r}.`),`Chưa đổi được thinking`,`Could not change thinking`):a(`Cách dùng: /thinking ${e.thinkingLevels.join(`|`)}`,`Usage: /thinking ${e.thinkingLevels.join(`|`)}`)),e.company?(s(`undo`,null,`Hoàn tác file mà lượt trước của agent đã sửa`,`Undo the files the agent's last turn changed`,async()=>({send:!0})),e.fast&&s(`fast`,`[on|off]`,`Bật/tắt Fast (Harness cho phép)`,`Turn Fast on or off (where the Harness allows it)`,async r=>{let o=r===`on`?!0:r===`off`?!1:r?null:e.fast!==`on`;return o===null?a(`Cách dùng: /fast on|off`,`Usage: /fast on|off`):Lr(t,()=>n.setFast(o),o?i(`Đã bật Fast.`,`Fast is on.`):i(`Đã tắt Fast.`,`Fast is off.`),`Chưa đổi được Fast`,`Could not change Fast`)}),s(`bypass`,`<on|full|off>`,`Bypass (chỉ hỏi việc bàn giao), Toàn quyền (hỏi việc bàn giao và việc phá huỷ) hoặc Hỏi trước`,`Bypass (asks only about the handoff), Full access (asks about the handoff and destructive steps) or Ask first`,async o=>o===`off`?Lr(t,()=>n.setPermission(`workspace-write`),i(`Đã chuyển sang Hỏi trước.`,`Switched to Ask first.`),`Chưa đổi được quyền`,`Access not changed`):o===`full`?{confirm:{title:r(`Bật Toàn quyền?`,`Turn on Full access?`),confirmLabel:r(`Bật Toàn quyền`,`Turn on Full access`),description:r(`Lệnh cần internet hoặc Docker chạy không hỏi; push, PR, publish, deploy, migration, xoá không rõ đích và lệnh trên máy vẫn hỏi.`,`Commands that need the internet or Docker run without asking; pushes, pull requests, publish, deploys, migrations, unknown-target deletes and commands on this machine still ask.`),run:()=>Lr(t,()=>n.setPermission(`trusted-full-access`),i(`Đã bật Toàn quyền.`,`Full access is on.`),`Chưa đổi được quyền`,`Access not changed`)}}:o===`on`?e.bypass?{confirm:{title:r(`Bật Bypass?`,`Turn on Bypass?`),confirmLabel:r(`Bật Bypass`,`Turn on Bypass`),description:r(`Việc làm chạy luôn (internet, Docker, lệnh trên máy, migration); việc bàn giao vẫn hỏi: push, PR, publish, deploy, upload, MCP ghi ra ngoài. Lệnh thường vẫn trong sandbox; /undo vẫn dùng được.`,`The work runs (internet, Docker, commands on this machine, migrations); the handoff is still asked: pushes, pull requests, publish, deploys, uploads, MCP writes. Plain commands stay in the sandbox; /undo still works.`),run:()=>Lr(t,()=>n.setPermission(`bypass`),i(`Đã bật Bypass.`,`Bypass is on.`),`Chưa đổi được quyền`,`Access not changed`)}}:a(`Harness của team đã tắt Bypass (admin Studio). Dùng /bypass full cho Toàn quyền.`,`The team's Harness has Bypass off (Studio administrator). Use /bypass full for Full access.`):a(`Cách dùng: /bypass on|full|off`,`Usage: /bypass on|full|off`))):(s(`model`,`<tên model>`,`Đổi model`,`Change the model`,async r=>{let o=await e.loadModels().catch(()=>[]),s=r.toLowerCase(),c=s?o.filter(e=>e.label.toLowerCase()===s||e.modelRef.toLowerCase()===s):[],l=c.length?c:s?o.filter(e=>e.label.toLowerCase().includes(s)||e.modelRef.toLowerCase().includes(s)):[];return l.length===1?Lr(t,()=>n.setModel(l[0].modelRef),i(`Đã đổi model sang ${l[0].label}.`,`The model is now ${l[0].label}.`),`Chưa đổi được model`,`Could not change the model`):a(`Cách dùng: /model <tên>. Có: ${o.map(e=>e.label).slice(0,12).join(`, `)||`—`}`,`Usage: /model <name>. Available: ${o.map(e=>e.label).slice(0,12).join(`, `)||`—`}`)}),s(`permission`,`<read-only|ask|full|bypass>`,`Đổi quyền của cuộc trò chuyện`,`Change the conversation's access`,async e=>{let o=e===`read-only`?`read-only`:e===`ask`?`workspace-write`:e===`full`?`trusted-full-access`:e===`bypass`?`bypass`:null;if(!o)return a(`Cách dùng: /permission read-only|ask|full|bypass`,`Usage: /permission read-only|ask|full|bypass`);let s=()=>Lr(t,()=>n.setPermission(o),i(`Đã đổi quyền sang ${e}.`,`Access is now ${e}.`),`Chưa đổi được quyền`,`Access not changed`);return o===`bypass`?{confirm:{title:r(`Bật Bypass?`,`Turn on Bypass?`),confirmLabel:r(`Bật Bypass`,`Turn on Bypass`),description:r(`Không hỏi, không chặn gì trong cuộc trò chuyện này (xoá, push, file được bảo vệ đều chạy luôn). Output vẫn che secret, /undo vẫn hoàn tác được.`,`Nothing is asked or blocked in this conversation (deletes, pushes and protected files all run). Output is still redacted and /undo still works.`),run:s}}:o===`trusted-full-access`?{confirm:{title:r(`Bật toàn quyền?`,`Enable full access?`),confirmLabel:r(`Bật toàn quyền`,`Enable full access`),description:r(`Session được đọc, sửa file và chạy command trong phạm vi runtime; xoá hoặc gửi dữ liệu ra ngoài vẫn cần xác nhận riêng.`,`The session may read and edit files and run commands within the runtime; destructive actions and external transfers still ask.`),run:s}}:s()})),s(`changes`,null,`Mở Source Changes`,`Open Source Changes`,async()=>(n.openChanges(),i(`Đã mở Source Changes.`,`Opened Source Changes.`))),s(`settings`,null,`Mở Cài đặt`,`Open Settings`,async()=>(n.openSettings(),i(`Đã mở Cài đặt.`,`Opened Settings.`))),o}var zr=`piagent dashboard`;function Br(){return(0,$.useSyncExternalStore)(Re,Le,Le)}function Vr({locale:e}){let[t,n]=(0,$.useState)(!1);return(0,Q.jsxs)(P,{role:`alert`,spacing:2,sx:{minHeight:`100vh`,alignItems:`center`,justifyContent:`center`,px:2,textAlign:`center`},children:[(0,Q.jsx)(S,{variant:`h6`,component:`h1`,children:X(e,`Tab này đã hết phiên đăng nhập`,`This tab is no longer signed in`)}),(0,Q.jsx)(S,{color:`text.secondary`,sx:{maxWidth:520},children:X(e,`Piagent vừa khởi động lại, tab không được dùng quá 8 giờ, hoặc tab được mở từ một link cũ. Các cuộc trò chuyện vẫn còn nguyên — mở lại Piagent để vào tiếp.`,`Piagent restarted, this tab was unused for over 8 hours, or this tab came from an old link. Your conversations are kept — open Piagent again to continue.`)}),(0,Q.jsxs)(R,{sx:{display:`flex`,gap:1,alignItems:`center`,flexWrap:`wrap`,justifyContent:`center`},children:[(0,Q.jsx)(R,{component:`code`,sx:{px:1.5,py:.75,borderRadius:1,bgcolor:`action.hover`,fontSize:`.9rem`},children:zr}),(0,Q.jsx)(a,{size:`small`,variant:`outlined`,onClick:()=>{navigator.clipboard?.writeText(zr).then(()=>n(!0),()=>n(!1))},children:t?X(e,`Đã chép`,`Copied`):X(e,`Chép lệnh`,`Copy command`)})]}),(0,Q.jsx)(S,{variant:`body2`,color:`text.secondary`,children:X(e,`Chạy lệnh trên trong terminal, hoặc bấm WebUI trong Agent Watch. Sau đó có thể đóng tab này.`,`Run it in a terminal, or choose WebUI in Agent Watch. You can close this tab afterwards.`)})]})}var Hr=`piagent-update-snooze`,Ur=`piagent-update-job-seen`,Wr=36e5;function Gr(e){try{return window.localStorage.getItem(e)}catch{return null}}function Kr(e,t){try{window.localStorage.setItem(e,t)}catch{}}function qr(e,t){try{let n=JSON.parse(Gr(Hr)??`null`);return n?.version===e&&typeof n.until==`number`&&t<n.until}catch{return!1}}function Jr({locale:e,onDetails:t}){let{status:n,applying:r,error:i,apply:o}=ct(),[c,l]=(0,$.useState)(()=>Date.now()),[u,d]=(0,$.useState)(null),[f,p]=(0,$.useState)(null);(0,$.useEffect)(()=>{let e=window.setInterval(()=>l(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let m=n?.piagent.latest??null,h=n?.job??null;(0,$.useEffect)(()=>{!h||h.state!==`succeeded`||Gr(Ur)===h.startedAt||(Kr(Ur,h.startedAt),p(X(e,`Đã cập nhật Piagent ${h.from} → ${h.installed??h.to}.`,`Piagent updated ${h.from} → ${h.installed??h.to}.`)))},[h,e]);let _=!!(n?.installable&&n.updateAvailable&&m&&!_t(n))&&u!==m&&!qr(m,c),y=()=>{m&&(Kr(Hr,JSON.stringify({version:m,until:Date.now()+Wr})),d(m))},b=(n?.runningConversations??0)>0;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(s,{open:_,onClose:y,fullWidth:!0,maxWidth:`xs`,"aria-labelledby":`piagent-update-offer`,children:[(0,Q.jsxs)(I,{id:`piagent-update-offer`,sx:{display:`flex`,alignItems:`center`,gap:1},children:[(0,Q.jsx)(T,{color:`primary`}),X(e,`Có bản Piagent mới: ${m}`,`Piagent ${m} is available`)]}),(0,Q.jsxs)(z,{sx:{display:`grid`,gap:1.5},children:[(0,Q.jsx)(R,{component:`ul`,sx:{m:0,pl:2.5,display:`grid`,gap:.75},children:n&&ot(e,n).map(e=>(0,Q.jsx)(S,{component:`li`,variant:`body2`,children:e},e))}),b&&(0,Q.jsx)(v,{severity:`info`,children:X(e,`${n?.runningConversations} cuộc trò chuyện đang chạy. Cập nhật khi chúng xong — dialog này sẽ nhắc lại.`,`${n?.runningConversations} conversation(s) running. Update once they finish — this will ask again.`)}),i&&(0,Q.jsx)(v,{severity:`error`,children:gt(e,i)})]}),(0,Q.jsxs)(g,{sx:{flexWrap:`wrap`,gap:1},children:[(0,Q.jsx)(a,{onClick:y,children:X(e,`Để sau (nhắc lại sau 1 giờ)`,`Later (ask again in an hour)`)}),(0,Q.jsx)(a,{onClick:()=>{d(m),t()},children:X(e,`Xem chi tiết`,`Details`)}),(0,Q.jsx)(a,{variant:`contained`,disabled:b||r,onClick:()=>{d(m),o().then(t)},children:X(e,`Cập nhật ngay`,`Update now`)})]})]}),(0,Q.jsx)(be,{open:f!==null,autoHideDuration:8e3,onClose:()=>p(null),anchorOrigin:{vertical:`top`,horizontal:`center`},children:(0,Q.jsx)(v,{severity:`success`,variant:`filled`,onClose:()=>p(null),children:f})})]})}function Yr(e){return N(`MuiSkeleton`,e)}we(`MuiSkeleton`,[`root`,`text`,`rectangular`,`rounded`,`circular`,`pulse`,`wave`,`withChildren`,`fitContent`,`heightAuto`]);var Xr=e=>{let{classes:t,variant:n,animation:r,hasChildren:i,width:a,height:o}=e;return K({root:[`root`,n,r,i&&`withChildren`,i&&!a&&`fitContent`,i&&!o&&`heightAuto`]},Yr,t)},Zr=r`
4
4
  0% {
5
5
  opacity: 1;
6
6
  }
@@ -41,9 +41,11 @@ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$t as t,A as n,An as r
41
41
  `)?`
42
42
  `:`
43
43
 
44
- `:``}${n}`,assistantMessageRef:r}}function ui(e,t){return e?.state===`ready`&&e.gatewayInstanceRef===t&&Number.isSafeInteger(e.eventSequence)&&e.eventSequence>=0&&Array.isArray(e.operations)&&Array.isArray(e.settlements)?e.eventSequence:null}function di(e,t){return e&&!t?`connected`:`reconnecting`}var fi=100,pi=/^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/,mi=/^[a-z0-9][a-z0-9.-]{0,95}$/,hi=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;function gi(e,t){return typeof t==`string`&&mi.test(t)?t:e===`aborted`?`operation-aborted`:e===`blocked`?`operation-blocked`:e===`error`?`operation-failed`:`operation-settlement-unknown`}function _i(e){if(e.settlement===`completed`||typeof e.operationRef!=`string`||!pi.test(e.operationRef)||typeof e.settledAt!=`string`||!hi.test(e.settledAt)||!Number.isSafeInteger(e.sequence)||Number(e.sequence)<1)return null;let t=[`blocked`,`aborted`,`error`,`unknown`].includes(String(e.settlement))?e.settlement:`unknown`,n=t===`error`?`failed`:t;return{activityRef:e.operationRef,operationRef:e.operationRef,settlement:t,state:n,reasonCode:gi(t,e.reasonCode),settledAt:e.settledAt,sequence:Number(e.sequence)}}function vi(e,t){let n=new Map;for(let r of[...e,...t])n.has(r.operationRef)||n.set(r.operationRef,r);return[...n.values()].sort((e,t)=>t.sequence-e.sequence).slice(0,fi)}function yi(e){if(e.state!==`ready`)return{};let t={};for(let n of e.settlements??[]){let e=_i(n);e&&(t[n.sessionRef]=vi(t[n.sessionRef]??[],[e]))}return t}function bi(e,t){let n=[`completed`,`blocked`,`aborted`,`error`].includes(String(t.settlement))?t.settlement:`unknown`;return{...e,operationRef:t.operationRef,abortable:!1,complete:!0,settlement:n,activities:[],delivery:e.user?`admitted`:e.delivery,assistant:n===`completed`?e.assistant:``,error:n===`completed`?null:String(t.reasonCode??`operation-settlement-unknown`)}}function xi(e,t){return{...e??{assistant:``,activities:[],operationRef:null,complete:!0,error:null},user:t.message,assistant:``,attachments:t.attachments,activities:[],operationRef:null,abortable:!1,complete:!1,settlement:null,error:null,messageRequestId:t.messageRequestId,delivery:`submitting`,startedAt:t.submittedAt,lastEventAt:t.submittedAt}}function Si(e,t,n,r){let i=t===`admitted`&&!!n&&e.operationRef===n&&e.complete;return{...e,delivery:t,operationRef:n??e.operationRef,abortable:t===`admitted`&&!i&&!!(n??e.operationRef),complete:t===`admitted`?i:e.complete,error:null,lastEventAt:r??e.lastEventAt}}function Ci(e,t,n){return!e||e.messageRequestId!==n||e.delivery===`admitted`?e:t}function wi(e,t){if(t.state!==`ready`)return{...e};let n=new Map(t.operations.map(e=>[e.sessionRef,e])),r={...e};for(let[i,a]of Object.entries(e))n.has(i)||a.complete||a.delivery!==`submitting`&&(r[i]={...a,assistant:``,activities:[],operationRef:null,abortable:!1,complete:!0,settlement:`unknown`,error:`operation-settlement-unavailable`,lastEventAt:t.generatedAt});for(let n of t.operations){let i=e[n.sessionRef],a=!(n.messageRequestId&&i?.messageRequestId&&n.messageRequestId!==i.messageRequestId)&&(i?.operationRef===n.operationRef||!!(i?.user&&[`submitting`,`unconfirmed`].includes(String(i.delivery))));r[n.sessionRef]=a?{...i,operationRef:n.operationRef,abortable:n.abortable,complete:!1,settlement:null,messageRequestId:n.messageRequestId??i?.messageRequestId,delivery:i?.user?`admitted`:i?.delivery,error:null,lastEventAt:t.generatedAt}:{user:``,assistant:``,attachments:[],activities:[],operationRef:n.operationRef,messageRequestId:n.messageRequestId??null,abortable:n.abortable,complete:!1,settlement:null,error:null,runtimeRecovery:null,startedAt:t.generatedAt,lastEventAt:t.generatedAt}}return r}function Ti(e,t){let n=e.toLowerCase();return n===`compaction`?t===`vi`?`tóm tắt phần cũ của cuộc trò chuyện`:`summarising the older part of the conversation`:n===`capacity-wait`?t===`vi`?`chờ tài khoản công ty rảnh`:`waiting for a free company account`:n===`ask_user`?t===`vi`?`chờ bạn trả lời câu hỏi`:`waiting for your answer`:/(subagent|scout|delegate|agent)/.test(n)?t===`vi`?`phối hợp agent hỗ trợ`:`coordinating a helper agent`:/(bash|exec|shell|command|terminal)/.test(n)?t===`vi`?`chạy lệnh`:`running a command`:/(read|grep|find|list|glob|search_file)/.test(n)?t===`vi`?`đọc mã nguồn`:`reading source`:/(edit|write|patch|apply)/.test(n)?t===`vi`?`cập nhật file`:`updating files`:/(test|verify|check|lint)/.test(n)?t===`vi`?`kiểm tra kết quả`:`verifying results`:/(web|search|browser|fetch)/.test(n)?t===`vi`?`tìm kiếm thông tin`:`searching`:t===`vi`?`chạy công cụ`:`running a tool`}var Ei=/(?:sk-(?:proj|live|test|svcacct)-[A-Za-z0-9_-]{8,}|as_(?:live|device|run)_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}_|(?:api[_-]?key|password|secret|token)=)/i;function Di(e){if(typeof e!=`string`)return null;let t=(e.replace(/\\/g,`/`).split(`/`).at(-1)??``).trim();return!t||t===`.`||t===`..`||t.length>160||/[\u0000-\u001f\u007f/\\]/.test(t)||Ei.test(t)||t.includes(`[REDACTED`)?null:t}function Oi(e,t=`vi`,n=Date.now()){let r=[...e.activities].reverse().find(e=>e.state===`running`),i=r?Ti(r.toolLabel,t):e.activities.length?t===`vi`?`tổng hợp bước tiếp theo`:`preparing the next step`:t===`vi`?`phân tích yêu cầu`:`analyzing the request`,a=Date.parse(e.lastEventAt??r?.startedAt??e.startedAt??``),o=Number.isFinite(a)?Math.max(0,Math.floor((n-a)/1e3)):null,s=o===null?t===`vi`?`Đang chờ cập nhật tiến trình đầu tiên`:`Waiting for the first progress update`:o<10?t===`vi`?`Tiến trình vừa cập nhật`:`Progress updated just now`:o<60?t===`vi`?`Cập nhật ${o} giây trước`:`Updated ${o}s ago`:t===`vi`?`Cập nhật ${Math.floor(o/60)} phút trước`:`Updated ${Math.floor(o/60)}m ago`,c=Di(r?.fileLabel),l=c?`${c} · ${s}`:s;return{label:t===`vi`?`Piagent đang ${i}…`:`Piagent is ${i}…`,detail:l}}function ki(e,t,n,r){if(e?.state!==`ready`||e.gatewayInstanceRef!==t)return!1;let i=e.operations.find(e=>e.sessionRef===n);return i?.operationRef===r&&i.abortable===!0}function Ai(e,t){return{key:t,user:e,steps:[],answer:null,failure:null,failureDetail:null,requests:0,tokens:0,model:null,process:null,end:null,startedAt:e.recordedAt,endedAt:null,outputTokens:0,generationMs:0}}var ji=new Set([`objection`,`rejudge`,`dispute`]);function Mi(e){let t=[],n=null,r=NaN;for(let i of e){let e=Date.parse(i.recordedAt),a=r;if(i.role!==`custom`&&(r=e),i.role===`user`){n=Ai(i,i.messageRef),t.push(n);continue}if(!n||i.role===`tool-result`)continue;if(n.endedAt=i.recordedAt,i.role===`custom`&&i.turnEnd){n.end=i.turnEnd;continue}if(i.role===`custom`&&i.process){if(n.process&&(n.answer&&(n.steps.push({kind:`note`,key:`${i.messageRef}:round-answer`,text:n.answer,draft:!0}),n.answer=null),n.steps.push({kind:`process`,key:`${i.messageRef}:round`,process:n.process}),n.process=null),i.process.phase===`final`){n.process=i.process;continue}n.answer&&!ji.has(i.process.phase)&&(n.steps.push({kind:`note`,key:`${i.messageRef}:answer`,text:n.answer,draft:!0}),n.answer=null),n.steps.push({kind:`process`,key:i.messageRef,process:i.process});continue}i.role===`assistant`&&i.usage?.outputTokens&&e>a&&(n.outputTokens+=i.usage.outputTokens,n.generationMs+=e-a),i.role===`assistant`&&(i.failure?.local||(n.requests+=1),n.tokens+=i.usage?.totalTokens??0,n.model=i.model??n.model);let o=cn(i);if(o){n.answer||(n.failure=o,n.failureDetail=i.failure??null);continue}for(let e of i.toolCalls)n.steps.push({kind:`tool`,key:`${i.messageRef}:${e.toolCallRef}`,tool:e});if(i.toolCalls.length)continue;let s=i.role===`assistant`?Zt(i.content.text??``):i.content.text;if(s){if(i.role===`custom`){n.steps.push({kind:`note`,key:i.messageRef,text:s});continue}n.answer&&n.answer.trim()!==s.trim()&&n.steps.push({kind:`note`,key:`${i.messageRef}:previous`,text:n.answer}),n.answer=s,n.failure=null,n.failureDetail=null}}for(let e of t){let t=new Set(e.answer?[e.answer.trim()]:[]);e.steps=e.steps.reduceRight((e,n)=>{if(n.kind===`note`&&n.draft){let r=n.text.trim();if(t.has(r))return e;t.add(r)}return[n,...e]},[])}return t}function Ni(e){let t=Date.parse(e.startedAt??``),n=Date.parse(e.endedAt??``);return Number.isFinite(t)&&Number.isFinite(n)&&n>=t?Math.round((n-t)/1e3):null}function Pi(e){if(e.outputTokens<50||e.generationMs<250)return null;let t=e.outputTokens/(e.generationMs/1e3);return t>=10?Math.round(t):Math.round(t*10)/10}function Fi(e,t){return e<40||t<1e3?null:Math.round(e/4/(t/1e3))}function Ii(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(+(e<1e4))}k`:`${(e/1e6).toFixed(1)}M`}var Li=e=>`/api/v1/sessions/${encodeURIComponent(e)}/checkpoints`,Ri=`piagent-webui-checkpoint-v1`;function zi(e){return Array.isArray(e)?`[${e.map(zi).join(`,`)}]`:e&&typeof e==`object`?`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${zi(t)}`).join(`,`)}}`:JSON.stringify(e)}async function Bi(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return`sha256:${[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`}var Vi=e=>typeof e==`string`&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(e),Hi=e=>typeof e==`string`&&/^[a-f0-9]{64}$/.test(e),Ui=(e,t)=>typeof e==`string`&&e.length>0&&e.length<=t,Wi=e=>Array.isArray(e)&&e.length<=1e4&&e.every(e=>Ui(e,4096)),Gi=e=>typeof e==`string`&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(e)&&Number.isFinite(Date.parse(e));function Ki(e){return e&&[`projectRef`,`runtimeInstanceId`,`sessionRef`].every(t=>typeof e[t]==`string`&&/^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/.test(e[t]))&&[`taskId`,`taskRunId`,`agentOperationId`,`toolCallId`].every(t=>e[t]===null||typeof e[t]==`string`&&/^[A-Za-z0-9][A-Za-z0-9._:@~-]{0,159}$/.test(e[t]))}function qi(e){return Vi(e.targetId)&&[`ready`,`conflict`,`busy`,`none`,`unavailable`].includes(e.result)&&(e.previewDigest===null||Hi(e.previewDigest))&&(e.tree===null||typeof e.tree==`string`&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(e.tree))&&Array.isArray(e.steps)&&e.steps.length<=64&&e.steps.every(e=>e&&Vi(e.id)&&Ui(e.turnRef,256)&&Wi(e.restore)&&Wi(e.remove))&&Wi(e.files)&&Wi(e.conflicts)&&(e.stoppedAt===null||Vi(e.stoppedAt))}async function Ji(e,t,n){let r=await fetch(Li(e)+(t?`/${encodeURIComponent(t)}`:``),{credentials:`same-origin`,signal:n,headers:{Accept:`application/json`}});if(r.status===401&&Ie(),!r.ok)throw Error(`checkpoint-unavailable`);let i=await r.json();if(!i||i.schemaVersion!==1||i.version!==Ri||i.identity?.sessionRef!==e||!Ki(i.identity)||i.messageType!==(t?`preview`:`state`)||!/^[a-f0-9]{64}$/.test(i.revisions?.checkpointRevision??``)||i.messageType===`state`&&(typeof i.available!=`boolean`||typeof i.agentRunning!=`boolean`||!Array.isArray(i.points)||i.points.length>64||!i.points.every(e=>e&&Vi(e.id)&&Ui(e.turnRef,256)&&Number.isSafeInteger(e.at)&&e.at>=0))||i.messageType===`preview`&&(i.targetId!==t||!qi(i)))throw Error(`checkpoint-response-invalid`);return i}var Yi=(e,t)=>Ji(e,null,t),Xi=(e,t,n)=>Ji(e,t,n);async function Zi(e){if(!qi(e)||!Ki(e.identity)||!Hi(e.revisions?.checkpointRevision)||!e.previewDigest||!e.tree||!e.steps.length||![`ready`,`conflict`].includes(e.result))throw Error(`checkpoint-preview-unavailable`);let t=Date.now(),n=`checkpoint.restore`,r={...e.identity},i={...e.revisions},a={targetId:e.targetId,previewDigest:e.previewDigest,expectedTree:e.tree,confirmed:!0};return{schemaVersion:1,version:Ri,messageType:`command`,action:n,identity:r,expectedRevisions:i,payload:a,commandId:crypto.randomUUID(),idempotencyKey:crypto.randomUUID(),requestedAt:new Date(t).toISOString(),expiresAt:new Date(t+6e4).toISOString(),actionDigest:await Bi(zi({action:n,identity:r,expectedRevisions:i,payload:a}))}}async function Qi(e,t){let{action:n,identity:r,expectedRevisions:i,payload:a}=e;return e.schemaVersion===1&&e.version===Ri&&e.messageType===`command`&&n===`checkpoint.restore`&&Ki(r)&&r.sessionRef===t&&Hi(i?.checkpointRevision)&&a?.confirmed===!0&&Vi(a.targetId)&&Hi(a.previewDigest)&&typeof a.expectedTree==`string`&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(a.expectedTree)&&typeof e.commandId==`string`&&/^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/.test(e.commandId)&&typeof e.idempotencyKey==`string`&&/^[A-Za-z0-9._~-]{32,128}$/.test(e.idempotencyKey)&&Gi(e.requestedAt)&&Gi(e.expiresAt)&&e.actionDigest===await Bi(zi({action:n,identity:r,expectedRevisions:i,payload:a}))}async function $i(e,t){if(!await Qi(t,e))throw Error(`checkpoint-command-invalid`);let n=Fe();if(!n)throw Error(`checkpoint-unavailable`);let r=await Pe(Li(e),{method:`POST`,credentials:`same-origin`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Piagent-CSRF":n},body:JSON.stringify(t)});if(r.status===401&&Ie(),!r.ok)throw Error(`checkpoint-unavailable`);let i=await r.json();if(!i||i.schemaVersion!==1||i.version!==Ri||i.messageType!==`receipt`||i.commandId!==t.commandId||i.actionDigest!==t.actionDigest||i.action!==t.action||i.targetId!==t.payload.targetId||i.idempotencyKeyDigest!==await Bi(t.idempotencyKey)||zi(i.identity)!==zi(t.identity)||![`settled`,`rejected`,`uncertain`].includes(i.phase)||![`restored`,`conflict`,`stale-revision`,`identity-mismatch`,`read-only`,`busy`,`unavailable`,`expired`,`idempotency-payload-mismatch`,`effect-unknown`].includes(i.resultCode)||i.requestedAt!==t.requestedAt||!Gi(i.settledAt)||typeof i.deduplicated!=`boolean`||!Hi(i.observedRevisionsBefore?.checkpointRevision)||!Hi(i.observedRevisionsAfter?.checkpointRevision)||!Array.isArray(i.completed)||i.completed.length>64||!i.completed.every(Vi)||!Wi(i.files)||!Wi(i.conflicts)||!(i.stoppedAt===null||Vi(i.stoppedAt))||i.phase===`uncertain`!=(i.resultCode===`effect-unknown`)||i.resultCode===`restored`&&i.phase!==`settled`)throw Error(`checkpoint-receipt-invalid`);return i}var ea=`piagent.checkpoint.pending.v1`,ta=64;function na(e){let t=e.getItem(ea);if(t===null)return Object.create(null);if(t.length>262144)throw Error(`checkpoint-pending-invalid`);let n=JSON.parse(t);if(!Array.isArray(n)||n.length>ta)throw Error(`checkpoint-pending-invalid`);let r=Object.create(null);for(let e of n){if(!Array.isArray(e)||e.length!==2)throw Error(`checkpoint-pending-invalid`);let[t,n]=e;if(typeof t!=`string`||!/^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/.test(t)||r[t]||!n||n.schemaVersion!==1||n.version!==`piagent-webui-checkpoint-v1`||n.messageType!==`command`||n.action!==`checkpoint.restore`||n.identity?.sessionRef!==t||n.payload?.confirmed!==!0||typeof n.payload.targetId!=`string`||typeof n.commandId!=`string`||typeof n.idempotencyKey!=`string`)throw Error(`checkpoint-pending-invalid`);r[t]=n}return r}function ra(e,t=window.sessionStorage){return na(t)[e]}function ia(e,t,n=window.sessionStorage){let r=na(n),i=r[e];if(i&&JSON.stringify(i)!==JSON.stringify(t))throw Error(`checkpoint-pending-exists`);if(!i&&Object.keys(r).length>=ta)throw Error(`checkpoint-pending-capacity`);if(t.identity.sessionRef!==e)throw Error(`checkpoint-pending-session`);r[e]=t;let a=JSON.stringify(Object.entries(r));if(a.length>262144)throw Error(`checkpoint-pending-capacity`);if(n.setItem(ea,a),n.getItem(ea)!==a)throw Error(`checkpoint-pending-write-failed`)}function aa(e,t,n=window.sessionStorage){let r=na(n);if(r[e]){if(JSON.stringify(r[e])!==JSON.stringify(t))throw Error(`checkpoint-pending-replaced`);delete r[e],n.setItem(ea,JSON.stringify(Object.entries(r)))}}var oa=(0,$.createContext)(null);function sa({turnRef:e}){let t=(0,$.useContext)(oa),n=t?.state?.points.find(t=>t.turnRef===e);return!t||!n?null:(0,Q.jsx)(a,{size:`small`,disabled:t.busy||t.state?.agentRunning,onClick:()=>t.open(n.id),sx:{alignSelf:`flex-start`},children:X(t.locale,`Khôi phục về trước lượt này`,`Restore before this turn`)})}function ca({sessionRef:e,refresh:t,running:n,locale:r,children:i}){let[o,c]=(0,$.useState)(),[l,u]=(0,$.useState)(0),[d,f]=(0,$.useState)(!1),[p,m]=(0,$.useState)(!1),[h,_]=(0,$.useState)(!1),[y,b]=(0,$.useState)(),[x,C]=(0,$.useState)(),[w,T]=(0,$.useState)(!1),[E]=(0,$.useState)(()=>{try{return{command:ra(e),failed:!1}}catch{return{command:void 0,failed:!0}}}),[D,O]=(0,$.useState)(E.command),[k,A]=(0,$.useState)(E.failed),j=(0,$.useRef)(null),M=(0,$.useRef)(!1),N=(0,$.useRef)(!0);(0,$.useEffect)(()=>(N.current=!0,()=>{N.current=!1,j.current?.abort()}),[]),(0,$.useEffect)(()=>{let t=new AbortController;return Yi(e,t.signal).then(e=>{t.signal.aborted||c(e)}).catch(()=>{}),()=>t.abort()},[e,t,l]);let F=t=>{if(f(!0),C(void 0),T(!1),D)return;j.current?.abort();let n=new AbortController;j.current=n,b(void 0),m(!0),Xi(e,t,n.signal).then(e=>{n.signal.aborted||b(e)}).catch(()=>{n.signal.aborted||T(!0)}).finally(()=>{n.signal.aborted||m(!1)})},L=async()=>{if(!(k||M.current||!D&&(!y||n||o?.agentRunning||![`ready`,`conflict`].includes(y.result)))){M.current=!0,_(!0),T(!1);try{let t=D??await Zi(y);try{ia(e,t)}catch{A(!0);return}O(t);let n=await $i(e,t);if(n.phase!==`uncertain`&&aa(e,t),!N.current)return;C(n),n.phase!==`uncertain`&&O(void 0),u(e=>e+1)}catch{N.current&&T(!0)}finally{window.dispatchEvent(new CustomEvent(`piagent-workspace-changed`,{detail:{sessionRef:e}})),M.current=!1,N.current&&_(!1)}}},R=()=>{M.current||(j.current?.abort(),f(!1),m(!1))},ee=x?.conflicts??y?.conflicts??[],B=x?.phase===`uncertain`||w&&!!D;return(0,Q.jsxs)(oa.Provider,{value:{state:o,busy:n||h||k,open:F,locale:r},children:[o&&!o.available&&(0,Q.jsx)(S,{variant:`caption`,color:`text.secondary`,children:X(r,`Project không dùng Git nên không có checkpoint để khôi phục.`,`This project has no Git repository, so checkpoints are unavailable.`)}),D&&!d&&(0,Q.jsx)(v,{severity:`warning`,action:(0,Q.jsx)(a,{color:`inherit`,onClick:()=>F(D.payload.targetId),children:X(r,`Xem kết quả`,`Check result`)}),children:X(r,`Một lần khôi phục chưa có kết quả xác nhận.`,`A restore is awaiting a confirmed result.`)}),k&&!d&&(0,Q.jsx)(v,{severity:`error`,children:X(r,`Không đọc hoặc lưu được yêu cầu khôi phục đang chờ trong trình duyệt. Chưa gửi yêu cầu mới; hãy kiểm tra file trước khi tiếp tục.`,`The browser could not read or save the pending restore. No new request was sent; inspect your files before continuing.`)}),i,(0,Q.jsxs)(s,{open:d,onClose:R,fullWidth:!0,maxWidth:`sm`,"aria-labelledby":`checkpoint-dialog-title`,children:[(0,Q.jsx)(I,{id:`checkpoint-dialog-title`,children:X(r,`Khôi phục về trước lượt này`,`Restore before this turn`)}),(0,Q.jsx)(z,{children:(0,Q.jsxs)(P,{spacing:2,children:[k&&(0,Q.jsx)(v,{severity:`error`,children:X(r,`Không đọc hoặc lưu được yêu cầu khôi phục đang chờ trong trình duyệt. Chưa gửi yêu cầu mới; hãy kiểm tra file trước khi tiếp tục.`,`The browser could not read or save the pending restore. No new request was sent; inspect your files before continuing.`)}),p&&(0,Q.jsx)(S,{children:X(r,`Đang xem trước…`,`Loading preview…`)}),y&&!x&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(S,{children:X(r,`Sẽ hoàn tác ${y.steps.length} lượt từ mới nhất về lượt đã chọn. Commit và vùng stage được giữ nguyên.`,`Undo ${y.steps.length} turns from newest to the selected turn. Commits and staged changes are preserved.`)}),(0,Q.jsx)(S,{variant:`body2`,sx:{whiteSpace:`pre-wrap`,maxHeight:240,overflow:`auto`},children:y.files.join(`
45
- `)}),![`ready`,`conflict`].includes(y.result)&&(0,Q.jsx)(v,{severity:`info`,children:X(r,`Checkpoint hiện không thể khôi phục. Đóng hộp thoại rồi xem trước lại khi lượt chạy kết thúc.`,`This checkpoint cannot be restored now. Close this dialog and preview again after the running turn ends.`)})]}),ee.length>0&&(0,Q.jsxs)(v,{severity:`warning`,children:[X(r,`Sẽ dừng trước file đã thay đổi sau lượt: `,`Stop before files changed after the turn: `),ee.join(`, `)]}),x&&!B&&(0,Q.jsx)(v,{severity:x.resultCode===`restored`?`success`:`warning`,children:x.resultCode===`restored`?X(r,`Đã khôi phục ${x.completed.length} lượt.`,`Restored ${x.completed.length} turns.`):x.resultCode===`conflict`?X(r,`Đã khôi phục ${x.completed.length} lượt và dừng để giữ thay đổi của bạn.`,`Restored ${x.completed.length} turns and stopped to preserve your changes.`):X(r,`Chưa khôi phục: trạng thái hoặc quyền đã thay đổi. Đóng hộp thoại và xem trước lại.`,`Not restored: state or permissions changed. Close this dialog and preview again.`)}),B&&(0,Q.jsx)(v,{severity:`warning`,children:X(r,`Chưa xác nhận được kết quả; một số file có thể đã thay đổi. Kiểm tra file trước khi tiếp tục. Nút bên dưới chỉ kiểm tra lại cùng yêu cầu.`,`The result is unconfirmed; some files may have changed. Inspect them before continuing. The button below checks the same request.`)}),w&&!D&&(0,Q.jsx)(v,{severity:`error`,children:X(r,`Không tải được preview. Đóng hộp thoại và thử lại.`,`Could not load the preview. Close this dialog and try again.`)})]})}),(0,Q.jsxs)(g,{children:[(0,Q.jsx)(a,{disabled:h,onClick:R,children:X(r,`Đóng`,`Close`)}),(!x||B)&&(0,Q.jsx)(a,{variant:`contained`,disabled:k||h||p||!D&&(n||o?.agentRunning||!y?.steps.length||![`ready`,`conflict`].includes(y?.result??``)),onClick:()=>void L(),children:D?X(r,`Kiểm tra lại kết quả`,`Check result again`):X(r,`Xác nhận khôi phục`,`Confirm restore`)})]})]})]})}var la=q((0,Q.jsx)(`path`,{d:`M19 5v14H5V5zm0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m-4.86 8.86-3 3.87L9 13.14 6 17h12z`}),`ImageOutlined`);function ua(e,t,n){return Je(tt(e,`/api/v1/transcript-images/${encodeURIComponent(t)}?index=${n}`))}function da(e){return`${e.sessionRef}\u0000${e.messageRef}\u0000${e.index}`}function fa(e){let t=e?`staged`in e?`staged:${e.staged}`:da(e):``,n=()=>e?`staged`in e?qt(e.staged):dn(da(e)):null,[r,i]=(0,$.useState)(()=>({key:t,url:n(),failed:!1}));r.key!==t&&i({key:t,url:n(),failed:!1}),(0,$.useEffect)(()=>{if(!e||`staged`in e||dn(t))return;let n=!0;return Gt(t,()=>ua(e.sessionRef,e.messageRef,e.index)).then(e=>{n&&i({key:t,url:e,failed:!e})}),()=>{n=!1}},[t]);let a=r.failed||!e||`staged`in e&&!r.url;return{url:r.key===t?r.url:null,failed:a,fail:()=>i({key:t,url:null,failed:!0})}}function pa({name:e,source:t,locale:n,fallback:r}){let{url:i,failed:a,fail:o}=fa(t),[c,l]=(0,$.useState)(!1);return a?(0,Q.jsx)(Q.Fragment,{children:r}):i?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(_,{onClick:()=>l(!0),"aria-label":X(n,`Xem ảnh ${e}`,`View image ${e}`),title:e,sx:{alignSelf:`flex-start`,borderRadius:1,overflow:`hidden`,border:1,borderColor:`divider`,bgcolor:`background.paper`},children:(0,Q.jsx)(R,{component:`img`,src:i,alt:e,onError:o,loading:`lazy`,sx:{display:`block`,maxWidth:{xs:`100%`,sm:320},maxHeight:220,objectFit:`contain`}})}),(0,Q.jsxs)(s,{open:c,onClose:()=>l(!1),maxWidth:!1,slotProps:{paper:{sx:{bgcolor:`background.default`,m:1,maxWidth:`96vw`,maxHeight:`94vh`}}},children:[(0,Q.jsxs)(R,{sx:{display:`flex`,alignItems:`center`,gap:1,pl:2,pr:.5,py:.5},children:[(0,Q.jsx)(S,{variant:`body2`,noWrap:!0,sx:{flex:1,fontWeight:600},children:e}),(0,Q.jsx)(L,{size:`small`,"aria-label":X(n,`Đóng`,`Close`),onClick:()=>l(!1),children:(0,Q.jsx)(h,{fontSize:`small`})})]}),(0,Q.jsx)(R,{component:`img`,src:i,alt:e,sx:{display:`block`,maxWidth:`96vw`,maxHeight:`calc(94vh - 48px)`,objectFit:`contain`,mx:`auto`}})]})]}):(0,Q.jsx)(ni,{variant:`rounded`,width:220,height:140,"aria-label":X(n,`Đang tải ảnh`,`Loading image`)})}var ma=q((0,Q.jsx)(`path`,{d:`M22 11V3h-7v3H9V3H2v8h7V8h2v10h4v3h7v-8h-7v3h-2V8h2v3zM7 9H4V5h3zm10 6h3v4h-3zm0-10h3v4h-3z`}),`AccountTreeOutlined`),ha=q((0,Q.jsx)(`path`,{d:`m22.61 18.99-9.08-9.08c.93-2.34.45-5.1-1.44-7C9.79.61 6.21.4 3.66 2.26L7.5 6.11 6.08 7.52 2.25 3.69C.39 6.23.6 9.82 2.9 12.11c1.86 1.86 4.57 2.35 6.89 1.48l9.11 9.11c.39.39 1.02.39 1.41 0l2.3-2.3c.4-.38.4-1.01 0-1.41m-3 1.6-9.46-9.46c-.61.45-1.29.72-2 .82-1.36.2-2.79-.21-3.83-1.25C3.37 9.76 2.93 8.5 3 7.26l3.09 3.09 4.24-4.24-3.09-3.09c1.24-.07 2.49.37 3.44 1.31 1.08 1.08 1.49 2.57 1.24 3.96-.12.71-.42 1.37-.88 1.96l9.45 9.45z`}),`BuildOutlined`),ga=q((0,Q.jsx)(`path`,{d:`M22 8c0-.55-.45-1-1-1h-7c-.55 0-1 .45-1 1s.45 1 1 1h7c.55 0 1-.45 1-1m-9 8c0 .55.45 1 1 1h7c.55 0 1-.45 1-1s-.45-1-1-1h-7c-.55 0-1 .45-1 1M10.47 4.63c.39.39.39 1.02 0 1.41l-4.23 4.25c-.39.39-1.02.39-1.42 0L2.7 8.16a.996.996 0 0 1 0-1.41c.39-.39 1.02-.39 1.41 0l1.42 1.42 3.54-3.54c.38-.38 1.02-.38 1.4 0m.01 8.01c.39.39.39 1.02 0 1.41L6.25 18.3c-.39.39-1.02.39-1.42 0L2.7 16.16c-.39-.39-.39-1.02 0-1.41s1.02-.39 1.41 0l1.42 1.42 3.54-3.54c.38-.38 1.02-.38 1.41.01`}),`ChecklistRounded`),_a=q((0,Q.jsx)(`path`,{d:`m14.85 4.85 1.44 1.44-2.88 2.88 1.42 1.42 2.88-2.88 1.44 1.44c.31.31.85.09.85-.36V4.5c0-.28-.22-.5-.5-.5h-4.29c-.45 0-.67.54-.36.85M8.79 4H4.5c-.28 0-.5.22-.5.5v4.29c0 .45.54.67.85.35L6.29 7.7 11 12.4V19c0 .55.45 1 1 1s1-.45 1-1v-7c0-.26-.11-.52-.29-.71l-5-5.01 1.44-1.44c.31-.3.09-.84-.36-.84`}),`CallSplitRounded`),va=q((0,Q.jsx)(`path`,{d:`m14.06 9.02.92.92L5.92 19H5v-.92zM17.66 3c-.25 0-.51.1-.7.29l-1.83 1.83 3.75 3.75 1.83-1.83c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.2-.2-.45-.29-.71-.29m-3.6 3.19L3 17.25V21h3.75L17.81 9.94z`}),`EditOutlined`),ya=q((0,Q.jsx)(`path`,{d:`M8 2c-1.1 0-2 .9-2 2v3.17c0 .53.21 1.04.59 1.42L10 12l-3.42 3.42c-.37.38-.58.89-.58 1.42V20c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2v-3.16c0-.53-.21-1.04-.58-1.41L14 12l3.41-3.4c.38-.38.59-.89.59-1.42V4c0-1.1-.9-2-2-2zm8 14.5V19c0 .55-.45 1-1 1H9c-.55 0-1-.45-1-1v-2.5l4-4zm-4-5-4-4V5c0-.55.45-1 1-1h6c.55 0 1 .45 1 1v2.5z`}),`HourglassEmptyRounded`),ba=q((0,Q.jsx)(`path`,{d:`M13 11h-2v3H8v2h3v3h2v-3h3v-2h-3zm1-9H6c-1.1 0-2 .9-2 2v16c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8zm4 18H6V4h7v5h5z`}),`NoteAddOutlined`),xa=q((0,Q.jsx)(`path`,{d:`M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39`}),`PublicRounded`),Sa=q((0,Q.jsx)(`path`,{d:`M2 6c.55 0 1-.45 1-1V4c0-.55.45-1 1-1h1c.55 0 1-.45 1-1s-.45-1-1-1H4C2.34 1 1 2.34 1 4v1c0 .55.45 1 1 1m3 15H4c-.55 0-1-.45-1-1v-1c0-.55-.45-1-1-1s-1 .45-1 1v1c0 1.66 1.34 3 3 3h1c.55 0 1-.45 1-1s-.45-1-1-1M20 1h-1c-.55 0-1 .45-1 1s.45 1 1 1h1c.55 0 1 .45 1 1v1c0 .55.45 1 1 1s1-.45 1-1V4c0-1.66-1.34-3-3-3m2 17c-.55 0-1 .45-1 1v1c0 .55-.45 1-1 1h-1c-.55 0-1 .45-1 1s.45 1 1 1h1c1.66 0 3-1.34 3-3v-1c0-.55-.45-1-1-1m-3-3.13V9.13c0-.72-.38-1.38-1-1.73l-5-2.88c-.31-.18-.65-.27-1-.27s-.69.09-1 .27L6 7.39c-.62.36-1 1.02-1 1.74v5.74c0 .72.38 1.38 1 1.73l5 2.88c.31.18.65.27 1 .27s.69-.09 1-.27l5-2.88c.62-.35 1-1.01 1-1.73m-8 2.3-4-2.3v-4.63l4 2.33zm1-6.33L8.04 8.53 12 6.25l3.96 2.28zm5 4.03-4 2.3v-4.6l4-2.33z`}),`ViewInArRounded`),Ca=`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,wa={read:br,write:ba,edit:va,command:E,search:c,list:x,"web-search":d,"web-fetch":D,subagent:ma,network:xa,docker:Sa,git:_a,plan:ga,other:ha},Ta={read:[`Đọc`,`Read`],write:[`Tạo`,`Write`],edit:[`Sửa`,`Edit`],command:[`Chạy`,`Run`],search:[`Tìm`,`Search`],list:[`Xem thư mục`,`List`],"web-search":[`Tìm web`,`Web search`],"web-fetch":[`Đọc trang`,`Fetch page`],subagent:[`Subagent`,`Subagent`],network:[`Chạy có mạng`,`Run with network`],docker:[`Chạy với Docker`,`Run with Docker`],git:[`Git`,`Git`],plan:[`Plan`,`Plan`],other:[`Công cụ`,`Tool`]},Ea={read:`read`,write:`write`,edit:`edit`,apply_patch:`edit`,bash:`command`,run_experiment:`command`,grep:`search`,find:`search`,ls:`list`,web_search:`web-search`,web_fetch:`web-fetch`,delegate:`subagent`,subagent:`subagent`,run_with_network:`network`,run_with_docker:`docker`,fetch_origin:`git`,update_plan:`plan`};function Da(e){return Ea[e.toLowerCase()]??`other`}function Oa({preview:e}){return(0,Q.jsx)(R,{component:`pre`,sx:{m:0,fontFamily:Ca,fontSize:12,lineHeight:1.55,overflowX:`auto`},children:e.split(`
46
- `).map((e,t)=>{let n=e[0],r=n===`+`?`success`:n===`-`?`error`:null;return(0,Q.jsx)(R,{component:`div`,sx:{px:1,whiteSpace:`pre`,...r?Et(r):{color:e===`@@`?`text.disabled`:`text.secondary`},bgcolor:r?`rgba(var(--piagent-palette-${r}-mainChannel) / .12)`:`transparent`},children:e===`@@`?`⋯`:e||` `},t)})})}function ka({tool:e,locale:t,live:n,waiting:r}){let i=e.summary??{kind:`other`,target:null,detail:null},a=`change`in e?e.change:void 0,o=`result`in e?e.result:void 0,s=e.state===`failed`||o?.isError===!0,c=`failure`in e&&e.failure?{detail:e.failure,copy:sr(e.failure.reasonCode,e.failure.code,t)}:null,l=n?e.state===`running`:e.state===`requested`,[u,d]=(0,$.useState)(()=>s||(i.kind===`edit`||i.kind===`write`)&&!!a?.preview),f=!!(a?.preview||o?.text||c?.copy||i.detail&&i.kind!==`read`),p=r?ya:wa[i.kind],m=Ta[i.kind][t===`vi`?0:1],g=i.kind===`other`?e.toolName:m;return(0,Q.jsxs)(R,{sx:{border:1,borderColor:s?`error.main`:`divider`,borderRadius:1,bgcolor:`background.paper`,overflow:`hidden`},children:[(0,Q.jsxs)(_,{component:`div`,disabled:!f,onClick:()=>d(e=>!e),"aria-expanded":f?u:void 0,sx:{width:`100%`,display:`flex`,alignItems:`center`,gap:1,px:1.25,py:.85,textAlign:`left`,justifyContent:`flex-start`},children:[(0,Q.jsx)(p,{sx:{fontSize:17,color:s?`error.main`:`text.secondary`,flexShrink:0}}),(0,Q.jsx)(S,{variant:`body2`,sx:{fontWeight:600,flexShrink:0},children:g}),i.target&&(0,Q.jsx)(S,{variant:`body2`,noWrap:!0,title:i.target,sx:{fontFamily:Ca,fontSize:12.5,color:`text.secondary`,minWidth:0,flex:1},children:i.target}),!i.target&&(0,Q.jsx)(R,{sx:{flex:1}}),i.kind===`read`&&i.detail&&(0,Q.jsx)(S,{variant:`caption`,color:`text.disabled`,sx:{flexShrink:0},children:X(t,`dòng ${i.detail}`,`lines ${i.detail}`)}),a&&(a.added>0||a.removed>0)&&(0,Q.jsxs)(S,{variant:`caption`,sx:{fontFamily:Ca,flexShrink:0},children:[a.added>0&&(0,Q.jsxs)(R,{component:`span`,sx:Et(`success`),children:[`+`,a.added,` `]}),a.removed>0&&(0,Q.jsxs)(R,{component:`span`,sx:Et(`error`),children:[`−`,a.removed]})]}),s&&!l&&(0,Q.jsx)(S,{variant:`caption`,sx:{flexShrink:0,fontWeight:600,...Et(`error`)},children:X(t,`Lỗi`,`Failed`)}),l?(0,Q.jsx)(ee,{size:14,thickness:5,"aria-label":X(t,`Đang chạy`,`Running`)}):s?(0,Q.jsx)(h,{sx:{fontSize:16,color:`error.main`},"aria-hidden":`true`}):(0,Q.jsx)(le,{sx:{fontSize:16,color:`success.main`},"aria-label":X(t,`Xong`,`Done`)}),f&&(0,Q.jsx)(j,{sx:{fontSize:18,color:`text.disabled`,transition:`transform .15s`,transform:u?`rotate(180deg)`:`none`}})]}),i.target&&[`read`,`write`,`edit`].includes(i.kind)&&(0,Q.jsx)(Ut,{path:i.target,line:Number.parseInt(i.detail??`1`,10)||1}),(0,Q.jsx)(or,{in:u&&f,unmountOnExit:!0,children:(0,Q.jsxs)(R,{sx:{borderTop:1,borderColor:`divider`,bgcolor:`action.hover`,maxHeight:360,overflow:`auto`},children:[i.detail&&i.kind!==`read`&&(0,Q.jsx)(S,{variant:`body2`,color:`text.secondary`,sx:{px:1.25,py:.75,whiteSpace:`pre-wrap`,overflowWrap:`anywhere`,...i.kind===`command`?{fontFamily:Ca,fontSize:12}:{}},children:i.detail}),c?.copy&&(0,Q.jsxs)(R,{sx:{px:1.25,py:.75},children:[(0,Q.jsxs)(S,{variant:`body2`,sx:{fontWeight:650,...Et(`error`)},children:[ur(c.detail.role,t),` `,X(t,`lỗi`,`failed`),` · `,c.copy.title]}),(0,Q.jsx)(S,{variant:`body2`,color:`text.secondary`,children:c.copy.text}),(0,Q.jsxs)(S,{variant:`caption`,color:`text.secondary`,sx:{fontFamily:Ca,overflowWrap:`anywhere`},title:c.detail.requestRef??void 0,children:[X(t,`Mã`,`Code`),`: `,c.detail.code,c.detail.requestRef?` · request ${c.detail.requestRef.slice(0,8)}`:``]})]}),a?.preview&&(0,Q.jsx)(R,{sx:{py:.5},children:(0,Q.jsx)(Oa,{preview:a.preview})}),o?.text&&!c?.copy&&(0,Q.jsx)(R,{component:`pre`,sx:{m:0,px:1.25,py:.75,fontFamily:Ca,fontSize:12,lineHeight:1.55,whiteSpace:`pre-wrap`,overflowWrap:`anywhere`,color:o.isError?`error.main`:`text.secondary`},children:o.text}),(a?.truncated||o?.truncated)&&(0,Q.jsx)(S,{variant:`caption`,color:`text.disabled`,sx:{display:`block`,px:1.25,pb:.75},children:X(t,`Đã rút gọn`,`Truncated`)})]})})]})}var Aa=null,ja=null,Ma=()=>Aa??=Me(()=>import(`./MarkdownMessage-DGt5B-6D.js`).then(e=>(ja=e.MarkdownMessage,e)),__vite__mapDeps([16,1,2,13,3,12,5])),Na=(0,$.lazy)(async()=>({default:(await Ma()).MarkdownMessage}));function Pa({children:e}){let t=ja;return t?(0,Q.jsx)(t,{children:e}):(0,Q.jsx)($.Suspense,{fallback:(0,Q.jsx)(S,{sx:{whiteSpace:`pre-wrap`,overflowWrap:`anywhere`,lineHeight:1.75},children:e}),children:(0,Q.jsx)(Na,{children:e})})}function Fa({attachments:e,images:t,locale:n}){if(!e.length)return null;let r=0;return(0,Q.jsx)(P,{spacing:.75,sx:{mb:1},"aria-label":X(n,`File đã gửi`,`Sent files`),children:e.map((e,i)=>{let a=`sourceBytes`in e,o=a?en(e,n):`${e.kind===`document`?X(n,`Tài liệu`,`Document`):e.kind===`image`?X(n,`Ảnh`,`Image`):`File`}${e.truncated?` · ${X(n,`đã cắt bớt`,`truncated`)}`:``}`,s=(0,Q.jsxs)(te,{variant:`outlined`,sx:{display:`flex`,alignItems:`center`,gap:1.1,minWidth:220,maxWidth:440,px:1.2,py:1,borderRadius:1,bgcolor:`background.paper`},children:[e.kind===`image`?(0,Q.jsx)(la,{color:`action`}):(0,Q.jsx)(br,{color:`action`}),(0,Q.jsxs)(R,{sx:{minWidth:0},children:[(0,Q.jsx)(S,{variant:`body2`,noWrap:!0,sx:{fontWeight:650},children:e.displayName}),(0,Q.jsx)(S,{variant:`caption`,color:`text.secondary`,children:o})]})]},`${e.displayName}:${i}`);if(e.kind!==`image`)return s;let c=a?{staged:e.attachmentRef}:t?{...t,index:r}:null;return r+=1,(0,Q.jsx)(pa,{name:e.displayName,source:c,locale:n,fallback:s},`${e.displayName}:${i}`)})})}var Ia=new Set([`assistant-response-failed`,`operation-failed`]);function La(e,t){switch(e){case`provider-auth-expired`:return X(t,`Phiên đăng nhập model đã hết hạn. Mở Cài đặt → Nhà cung cấp & model để kết nối lại.`,`The model sign-in expired. Open Settings → Providers & models to reconnect.`);case`provider-auth-required`:return X(t,`Model cần đăng nhập lại. Mở Cài đặt → Nhà cung cấp & model.`,`The model needs to sign in again. Open Settings → Providers & models.`);case`provider-rate-limited`:return X(t,`Model đang bị giới hạn lượt gọi hoặc đã hết hạn mức. Thử lại sau.`,`The model is rate limited or out of quota. Try again later.`);case`provider-unavailable`:return X(t,`Model hoặc máy chủ trung gian đang không phục vụ yêu cầu này. Thử lại; nếu lỗi lặp lại, kiểm tra model đang dùng.`,`The model or its gateway did not serve this request. Retry; if it repeats, check the model in use.`);case`assistant-output-incomplete`:return X(t,`Câu trả lời dừng giữa chừng vì chạm giới hạn độ dài. Gửi “tiếp tục” để model viết tiếp.`,`The answer stopped at the length limit. Send “continue” to resume.`);default:return X(t,`Model trả lỗi và chưa có câu trả lời. Gửi lại; nếu lỗi lặp lại, kiểm tra model đang dùng.`,`The model returned an error without an answer. Send again; if it repeats, check the model in use.`)}}function Ra({code:e,detail:t,locale:r,onContinue:i}){let o=sr(e,t?.code??null,r),s=i&&lr(e)?(0,Q.jsx)(a,{color:`inherit`,size:`small`,onClick:i,children:X(r,`Tiếp tục`,`Continue`)}):void 0;return o?(0,Q.jsxs)(v,{severity:`error`,variant:`outlined`,icon:(0,Q.jsx)(C,{}),action:s,sx:{alignSelf:`stretch`},children:[(0,Q.jsxs)(n,{sx:{fontSize:`inherit`,fontWeight:650,mb:.25},children:[ur(t?.role??`main`,r),` `,X(r,`lỗi`,`failed`),` · `,o.title]}),o.text,t&&(0,Q.jsxs)(S,{variant:`caption`,component:`div`,color:`text.secondary`,sx:{mt:.5,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,overflowWrap:`anywhere`},title:t.requestRef??void 0,children:[X(r,`Mã`,`Code`),`: `,t.code,t.requestRef?` · request ${t.requestRef.slice(0,8)}`:``]})]}):(0,Q.jsx)(v,{severity:`error`,variant:`outlined`,icon:(0,Q.jsx)(C,{}),action:s,sx:{alignSelf:`stretch`},children:La(e,r)})}function za({text:e,attachments:t,images:n,note:r,locale:i}){return(0,Q.jsxs)(R,{sx:{alignSelf:`flex-end`,maxWidth:`82%`,bgcolor:`action.selected`,borderRadius:1,px:2,py:1.4},children:[(0,Q.jsx)(Fa,{attachments:t,images:n,locale:i}),e&&(0,Q.jsx)(S,{sx:{whiteSpace:`pre-wrap`,overflowWrap:`anywhere`,lineHeight:1.7},children:(0,Q.jsx)(Ht,{children:e})}),r&&(0,Q.jsx)(S,{variant:`caption`,color:`text.secondary`,children:r})]})}function Ba({children:e}){return(0,Q.jsxs)(R,{sx:{display:`flex`,gap:1.5,alignItems:`flex-start`},children:[(0,Q.jsx)(ut,{size:26}),(0,Q.jsxs)(P,{spacing:1,sx:{minWidth:0,flex:1},children:[(0,Q.jsx)(S,{sx:{fontWeight:600},children:`Piagent`}),e]})]})}function Va(e,t){return e.content.redacted?X(t,`Đã ẩn dữ liệu nhạy cảm`,`Sensitive data hidden`):e.content.truncated?X(t,`Nội dung đã rút gọn`,`Content truncated`):null}function Ha({turn:e,locale:t}){let n=Ni(e),r=[`${e.requests} request`];e.tokens&&r.push(`${Ii(e.tokens)} token`),n!==null&&n>0&&r.push(n<60?`${n}s`:`${Math.floor(n/60)}m ${n%60}s`);let i=Pi(e);return i!==null&&r.push(`${i} tok/s`),e.model&&r.push(e.model),(0,Q.jsx)(S,{variant:`caption`,color:`text.disabled`,title:X(t,`Request model, token, thời gian và tốc độ sinh token (token đầu ra mỗi giây, tính cả thời gian chờ) của lượt này`,`Model requests, tokens, time and output speed (output tokens per second, waiting included) of this turn`),children:r.join(` · `)})}var Ua=(0,$.memo)(function({turn:e,sessionRef:t,locale:n,onContinue:r}){let i=!!r&&!e.answer&&!e.failure&&!e.end,o=e.steps.length>0||e.answer||e.failure||i||e.process||e.end;return(0,Q.jsxs)(P,{spacing:1.5,children:[(0,Q.jsx)(za,{text:e.user.content.text,attachments:e.user.attachments??[],note:Va(e.user,n),locale:n,images:t?{sessionRef:t,messageRef:e.user.messageRef}:void 0}),o&&(0,Q.jsxs)(Ba,{children:[e.steps.map(e=>e.kind===`tool`?(0,Q.jsx)(ka,{tool:e.tool,locale:n},e.key):e.kind===`process`?(0,Q.jsx)(wt,{process:e.process,locale:n},e.key):(0,Q.jsxs)(R,{sx:{color:`text.secondary`,fontSize:`.875rem`,"& .MuiTypography-root":{fontSize:`inherit`},...e.draft?{borderLeft:2,borderColor:`divider`,pl:1.5}:{}},children:[e.draft&&(0,Q.jsx)(S,{variant:`caption`,component:`div`,color:`text.disabled`,sx:{mb:.5,fontWeight:600},children:X(n,`Trả lời giữa chừng · harness yêu cầu làm tiếp`,`Interim answer · the harness asked for more`)}),(0,Q.jsx)(Pa,{children:e.text})]},e.key)),e.failure&&(0,Q.jsx)(Ra,{code:e.failure,detail:e.failureDetail,locale:n,onContinue:r}),i&&(0,Q.jsx)(v,{severity:`info`,variant:`outlined`,sx:{alignSelf:`stretch`},action:(0,Q.jsx)(a,{color:`inherit`,size:`small`,onClick:r,children:X(n,`Tiếp tục`,`Continue`)}),children:X(n,`Lượt này chưa có câu trả lời: nó đã bị dừng, hoặc ứng dụng hay máy tắt khi đang chạy. Các bước đã làm vẫn được giữ; bấm Tiếp tục để làm tiếp.`,`This turn has no answer: it was stopped, or the app or the machine went down while it ran. Its steps are kept; press Continue to go on.`)}),e.answer&&(0,Q.jsx)(R,{children:(0,Q.jsx)(Pa,{children:e.answer})}),e.process&&(0,Q.jsx)(wt,{process:e.process,locale:n}),e.end&&(0,Q.jsx)(Ct,{end:e.end,locale:n,onContinue:e.failure?void 0:r}),e.requests>0&&(0,Q.jsx)(Ha,{turn:e,locale:n})]}),(0,Q.jsx)(sa,{turnRef:e.user.messageRef})]})});function Wa(e,t){return e===`compaction`?X(t,`Tóm tắt phần cũ của cuộc trò chuyện`,`Summarise the older part of the conversation`):e===`capacity-wait`?X(t,`Chờ tài khoản công ty rảnh (Studio đang bận, sẽ tự gửi lại)`,`Wait for a free company account (Studio is busy; it is sent again by itself)`):e}function Ga({user:e,attachments:t,activities:n,assistant:r,running:i,failure:a,status:o,locale:s}){return(0,Q.jsxs)(P,{spacing:1.5,children:[e&&(0,Q.jsx)(za,{text:e,attachments:t,locale:s}),(0,Q.jsxs)(Ba,{children:[n.map(e=>(0,Q.jsx)(ka,{live:!0,locale:s,waiting:e.toolLabel===`capacity-wait`,tool:{toolName:Wa(e.toolLabel,s),state:e.state,summary:{kind:Da(e.toolLabel),target:e.fileLabel??null,detail:null}}},e.toolCallRef)),a&&(0,Q.jsx)(Ra,{code:a,locale:s}),r&&(0,Q.jsx)(R,{className:i?`streaming-answer`:void 0,children:(0,Q.jsx)(Pa,{children:r})}),i&&o]})]})}function Ka(e){let t=(0,$.useRef)(null),[n,r]=(0,$.useState)(null);return(0,$.useEffect)(()=>{if(!e){t.current=null,r(null);return}t.current??={at:Date.now(),from:e.length},r(Fi(e.length-t.current.from,Date.now()-t.current.at))},[e]),n}function qa({live:e,locale:t,onOpenActivity:n}){let[r,i]=(0,$.useState)(()=>Date.now());(0,$.useEffect)(()=>{let e=window.setInterval(()=>i(Date.now()),1e4);return()=>window.clearInterval(e)},[]);let o=Oi(e,t,r),s=Ka(e.assistant??``),c=e.activities.some(e=>e.state===`running`)||!!e.assistant;return(0,Q.jsxs)(P,{direction:`row`,spacing:1.25,role:`status`,"aria-live":`polite`,sx:{alignItems:`center`,color:`text.secondary`,py:.5,minHeight:36},children:[(0,Q.jsx)(R,{sx:{width:18,display:`grid`,placeItems:`center`,flexShrink:0},children:c?(0,Q.jsx)(R,{sx:{width:6,height:6,borderRadius:`50%`,bgcolor:`primary.main`,opacity:.7}}):(0,Q.jsx)(ee,{size:16,thickness:4.5})}),(0,Q.jsxs)(R,{sx:{minWidth:0},children:[(0,Q.jsx)(S,{variant:`body2`,sx:{fontWeight:600},children:o.label}),(0,Q.jsxs)(S,{variant:`caption`,color:`text.disabled`,children:[o.detail,s!==null&&` · ≈ ${s} tok/s`]})]}),n&&(0,Q.jsx)(a,{size:`small`,variant:`text`,onClick:n,sx:{ml:`auto !important`},children:X(t,`Xem Activity`,`View Activity`)})]})}var Ja=new Map,Ya=96,Xa=()=>document.documentElement.scrollHeight-window.innerHeight,Za=()=>Xa()-window.scrollY<=Ya,Qa=1500,$a=110;function eo(e,t){let n=(0,$.useRef)(null),r=(0,$.useRef)(!1),i=(0,$.useRef)(!0),a=(0,$.useRef)(null),o=(0,$.useRef)(!1),s=()=>{a.current=null,n.current&&(n.current.style.overflowAnchor=``)},c=()=>{let e=a.current;if(!e)return;if(Date.now()>e.until){s();return}let t=n.current?.querySelector(`[data-turn="${CSS.escape(e.key)}"]`);if(!t)return;let r=t.getBoundingClientRect().top-e.top;Math.abs(r)>=1&&window.scrollBy(0,r)};return(0,$.useLayoutEffect)(()=>{if(!t||r.current)return;r.current=!0;let n=Ja.get(e)??`end`;i.current=n===`end`,window.scrollTo(0,n===`end`?Xa():Math.min(n,Xa()))},[t,e]),(0,$.useEffect)(()=>{let t=window.scrollY,s=()=>{if(!r.current)return;window.scrollY<t-2&&(o.current=!0),t=window.scrollY;let s=a.current;if(s){let e=n.current?.querySelector(`[data-turn="${CSS.escape(s.key)}"]`);e&&(s.top=e.getBoundingClientRect().top)}i.current=Za(),Ja.set(e,i.current?`end`:window.scrollY)};window.addEventListener(`scroll`,s,{passive:!0});let l=n.current,u=typeof ResizeObserver>`u`||!l?null:new ResizeObserver(()=>{r.current&&(a.current?c():i.current&&window.scrollTo(0,Xa()))});return l&&u?.observe(l),()=>{window.removeEventListener(`scroll`,s),u?.disconnect()}},[e]),{content:n,hold:()=>{if(window.setTimeout(c,1550),a.current){a.current.until=Date.now()+Qa;return}let e=[...n.current?.querySelectorAll(`[data-turn]`)??[]],t=e.find(e=>e.getBoundingClientRect().bottom>$a)??e[0];!t?.dataset.turn||!n.current||(n.current.style.overflowAnchor=`none`,a.current={key:t.dataset.turn,top:t.getBoundingClientRect().top,until:Date.now()+Qa})},reapply:c,scrolledUp:o,follow:()=>{s(),i.current=!0,o.current=!1}}}function to({turns:e=2,label:t}){return(0,Q.jsx)(P,{spacing:3,role:`status`,"aria-label":t,sx:{py:1},children:Array.from({length:e},(e,t)=>(0,Q.jsxs)(P,{spacing:1.5,children:[(0,Q.jsx)(ni,{variant:`rounded`,animation:`wave`,sx:{alignSelf:`flex-end`,width:`46%`,height:44,borderRadius:2}}),(0,Q.jsxs)(P,{direction:`row`,spacing:1.5,children:[(0,Q.jsx)(ni,{variant:`rounded`,width:26,height:26}),(0,Q.jsxs)(P,{spacing:1,sx:{flex:1},children:[(0,Q.jsx)(ni,{width:`30%`}),(0,Q.jsx)(ni,{width:`92%`}),(0,Q.jsx)(ni,{width:`78%`})]})]})]},t))})}function no({sessionRef:e,sessionRevision:t,live:n,approvals:r,locale:i,onOpenActivity:o,onContinue:s,reload:c=0}){let[l,u]=(0,$.useState)(),[d,f]=(0,$.useState)(!0),[p,m]=(0,$.useState)(!1),[h,g]=(0,$.useState)(0),[_,y]=(0,$.useState)(!1),[b,x]=(0,$.useState)(!1),[w,T]=(0,$.useState)(!1),[E,D]=(0,$.useState)(null);(0,$.useEffect)(()=>{Ma()},[]);let O=on(e,t,n),{completionKey:k,user:A,assistant:j,operationRef:M,messageRequestId:N,startedAt:F}=O;(0,$.useEffect)(()=>{let t=new AbortController;f(!0),x(!1),D(null);let n=window.setTimeout(()=>{Promise.all([Ue(e,null,50,t.signal),Ma().catch(()=>void 0)]).then(([e])=>{u(e),y(!1),k&&Yt(e.items,A,j,{operationRef:M,messageRequestId:N,startedAt:F})&&D(k)}).catch(()=>{t.signal.aborted||x(!0)}).finally(()=>{t.signal.aborted||f(!1)})},k?100:0);return()=>{window.clearTimeout(n),t.abort()}},[O.key,c,h]);let I=l?.state===`ready`?l.items:[],L=(0,$.useMemo)(()=>Mi(I),[I]),z=(0,$.useMemo)(()=>!!(n?.user&&tn(I,n.user,{operationRef:n.operationRef,messageRequestId:n.messageRequestId,startedAt:n.startedAt})),[I,n?.user,n?.operationRef,n?.messageRequestId,n?.startedAt]),ee=!!(n&&!z&&(!n.complete||E!==k)),B=!!(n&&z&&!n.complete&&!n.error),te=(0,$.useMemo)(()=>!!(n?.user&&rn(I,n.user,{operationRef:n.operationRef,messageRequestId:n.messageRequestId,startedAt:n.startedAt})),[I,n?.user,n?.operationRef,n?.messageRequestId,n?.startedAt]),{content:ne,hold:re,reapply:V,scrolledUp:H,follow:ie}=eo(e,!!l||b),U=(0,$.useRef)(!1),ae=(0,$.useRef)(l);ae.current=l;let oe=async()=>{let t=ae.current,n=t?.page.nextBeforeCursor;if(!(!t?.page.hasOlder||!n||U.current)){H.current=!1,U.current=!0,re(),m(!0),T(!1);try{let r=await Ue(e,n,t.page.limit);re();let i=ae.current;if(!i){ae.current=r,u(r);return}let a=ln(i.items,r.items);new Set([...i.items,...r.items].map(e=>e.messageRef)).size>a.length&&y(!0);let o={...i,items:a,page:r.page};ae.current=o,u(o)}catch{T(!0)}finally{U.current=!1,m(!1)}}};(0,$.useLayoutEffect)(()=>{V()},[I.length,p]);let W=(0,$.useRef)(null),G=(0,$.useRef)(()=>{}),ce=!!l?.page.hasOlder;G.current=()=>{if(!H.current||w||U.current)return;let e=W.current?.getBoundingClientRect();e&&e.bottom>=-900&&e.top<=window.innerHeight&&oe()},(0,$.useEffect)(()=>{let e=W.current;if(!e||!ce)return;let t=0,n=()=>{t||=window.requestAnimationFrame(()=>{t=0,G.current()})},r=typeof IntersectionObserver>`u`?null:new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&n()},{rootMargin:`900px 0px 0px 0px`});return r?.observe(e),window.addEventListener(`scroll`,n,{passive:!0}),()=>{r?.disconnect(),window.removeEventListener(`scroll`,n),window.cancelAnimationFrame(t)}},[e,ce]);let le=n?Zt(n.assistant||``):null;return(0,Q.jsx)(ca,{sessionRef:e,refresh:`${O.key}:${c}`,running:!!n&&!n.complete&&!n.error,locale:i,children:(0,Q.jsxs)(P,{ref:ne,spacing:3,children:[l?.page.hasOlder&&(0,Q.jsx)(R,{ref:W,"data-history-sentinel":!0,children:p?(0,Q.jsx)(to,{label:X(i,`Đang tải tin cũ hơn`,`Loading older messages`)}):(0,Q.jsx)(R,{sx:{textAlign:`center`},children:(0,Q.jsx)(a,{size:`small`,variant:`text`,color:`inherit`,startIcon:(0,Q.jsx)(se,{}),onClick:()=>void oe(),sx:{color:w?`warning.main`:`text.secondary`},children:w?X(i,`Chưa tải được tin cũ · thử lại`,`Older messages did not load · retry`):X(i,`Tải tin cũ hơn`,`Load older messages`)})})}),l?.state===`ready`&&!l.page.hasOlder&&L.length>3&&(0,Q.jsx)(S,{variant:`caption`,color:`text.disabled`,sx:{textAlign:`center`,display:`block`},children:X(i,`Đầu cuộc trò chuyện`,`Start of the conversation`)}),d&&!l&&(0,Q.jsx)(to,{turns:3,label:X(i,`Đang tải cuộc trò chuyện`,`Loading the conversation`)}),b&&!l&&(0,Q.jsx)(v,{severity:`warning`,icon:(0,Q.jsx)(C,{}),children:X(i,`Chưa tải được lịch sử cuộc trò chuyện. Thử lại bằng nút làm mới.`,`Session history could not be loaded. You can retry with Refresh.`)}),L.map((t,n)=>(0,Q.jsx)(R,{"data-turn":t.key,children:(0,Q.jsx)(Ua,{turn:t,sessionRef:e,locale:i,onContinue:n===L.length-1&&!ee&&!B&&!r?.pending.length?s:void 0})},t.key)),_&&(0,Q.jsx)(R,{sx:{textAlign:`center`},children:(0,Q.jsx)(a,{size:`small`,variant:`outlined`,onClick:()=>{ie(),g(e=>e+1)},children:X(i,`Tin mới hơn đã ẩn · về tin mới nhất`,`Newer messages are hidden · back to the newest`)})}),ee&&n&&(0,Q.jsx)(Ga,{user:n.user&&!te?n.user:null,attachments:n.attachments,activities:n.activities,assistant:n.error?null:le,running:!n.complete&&!n.error,failure:n.complete&&n.error&&Ia.has(n.error)?n.error:null,locale:i,status:(0,Q.jsx)(qa,{live:n,locale:i,onOpenActivity:o})}),B&&n&&(0,Q.jsx)(Ba,{children:(0,Q.jsx)(qa,{live:n,locale:i,onOpenActivity:o})}),(0,Q.jsx)(ci,{sessionRef:e,waiting:xt(n),approvalRefs:r?.pending.map(e=>e.approvalRef)??[]})]})})}var ro=9e3,io=4,ao={done:[`Xong`,`Done`,`Agent đã trả lời xong.`,`The agent finished its answer.`],failed:[`Lượt bị lỗi`,`Turn failed`,`Mở để xem lỗi và gửi “tiếp tục”.`,`Open it to see the error and continue.`],stopped:[`Đã dừng`,`Stopped`,`Lượt làm việc đã dừng giữa chừng.`,`The turn stopped midway.`],question:[`Cần bạn trả lời`,`Needs your answer`,`Main agent đang chờ bạn chọn phương án.`,`The main agent is waiting for your choice.`],approval:[`Cần bạn duyệt`,`Needs your approval`,`Main agent xin chạy một lệnh và đang chờ bạn duyệt.`,`The main agent asked to run a command and is waiting.`]},oo={done:`success`,failed:`error`,stopped:`neutral`,question:`warning`,approval:`warning`};function so({sessions:e,live:t,selectedRef:n,onOpen:r,locale:i}){let a=(0,$.useRef)(null),[o,s]=(0,$.useState)([]),[c,l]=(0,$.useState)(()=>new Set);(0,$.useEffect)(()=>{let r=yt(e,t);if(a.current){let i=document.visibilityState===`visible`,o=Tt(a.current,r,e,t).filter(e=>!(i&&e.sessionRef===n));if(o.length){s(e=>[...o,...e.filter(e=>!o.some(t=>t.sessionRef===e.sessionRef))].slice(0,12));let e=o.filter(e=>[`done`,`failed`,`stopped`].includes(e.kind)).map(e=>e.sessionRef);e.length&&l(t=>new Set([...t,...e]))}}a.current=r,s(e=>{let t=e.filter(e=>![`question`,`approval`].includes(e.kind)||r[e.sessionRef]?.need===e.kind);return t.length===e.length?e:t})},[e,t,n]),(0,$.useEffect)(()=>{n&&(l(e=>{if(!e.has(n))return e;let t=new Set(e);return t.delete(n),t}),s(e=>e.filter(e=>e.sessionRef!==n)))},[n]);let u=e.filter(e=>!e.archived&&zt(e,t[e.sessionRef])).length;(0,$.useEffect)(()=>{let e=document.title.replace(/^\(\d+\) /,``);document.title=u?`(${u}) ${e}`:e},[u]);let d=e=>s(t=>t.filter(t=>t.id!==e));return{unseen:c,view:(0,Q.jsx)(co,{toasts:o.slice(0,io),more:Math.max(0,o.length-io),locale:i,onClose:d,onOpen:e=>{d(e.id),r(e.sessionRef)}})}}function co({toasts:e,more:t,locale:n,onClose:r,onOpen:i}){return(0,Q.jsxs)(`section`,{className:`attention-toasts`,"aria-label":X(n,`Thông báo cuộc trò chuyện`,`Chat notifications`),"aria-live":`polite`,children:[e.map(e=>(0,Q.jsx)(lo,{event:e,locale:n,onClose:()=>r(e.id),onOpen:()=>i(e)},e.id)),t>0&&(0,Q.jsx)(`p`,{className:`attention-more`,children:X(n,`và ${t} thông báo khác`,`and ${t} more`)})]})}function lo({event:e,locale:t,onClose:n,onOpen:r}){let i=e.kind===`question`||e.kind===`approval`,[a,o,s,c]=ao[e.kind];return(0,$.useEffect)(()=>{if(i)return;let e=window.setTimeout(n,ro);return()=>window.clearTimeout(e)},[i]),(0,Q.jsxs)(`article`,{className:`attention-toast tone-${oo[e.kind]}`,role:i?`alert`:`status`,children:[(0,Q.jsx)(`span`,{className:`attention-toast-mark`,"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{className:`attention-toast-body`,children:[(0,Q.jsxs)(`strong`,{children:[X(t,a,o),` · `,(0,Q.jsx)(`span`,{className:`attention-toast-title`,children:e.title})]}),(0,Q.jsx)(`small`,{children:X(t,s,c)})]}),(0,Q.jsxs)(`div`,{className:`attention-toast-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`attention-open`,onClick:r,children:X(t,`Mở`,`Open`)}),(0,Q.jsx)(`button`,{type:`button`,className:`attention-close`,"aria-label":X(t,`Đóng thông báo`,`Close notification`),onClick:n,children:`×`})]})]})}var uo=q((0,Q.jsx)(`path`,{d:`M18 19H6c-.55 0-1-.45-1-1V6c0-.55.45-1 1-1h12c.55 0 1 .45 1 1v12c0 .55-.45 1-1 1m1-16H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2`}),`CheckBoxOutlineBlankRounded`),fo=q((0,Q.jsx)(`path`,{d:`M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m-8.29 13.29c-.39.39-1.02.39-1.41 0L5.71 12.7a.996.996 0 0 1 0-1.41c.39-.39 1.02-.39 1.41 0L10 14.17l6.88-6.88c.39-.39 1.02-.39 1.41 0s.39 1.02 0 1.41z`}),`CheckBoxRounded`),po=q((0,Q.jsx)(`path`,{d:`m10.8 15.9 4.67-3.5c.27-.2.27-.6 0-.8L10.8 8.1c-.33-.25-.8-.01-.8.4v7c0 .41.47.65.8.4M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8`}),`PlayCircleOutlineRounded`),mo=q((0,Q.jsx)(`path`,{d:`M7 12c0 .55.45 1 1 1h8c.55 0 1-.45 1-1s-.45-1-1-1H8c-.55 0-1 .45-1 1m5-10C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8`}),`RemoveCircleOutlineRounded`);function ho(e){return N(`MuiLinearProgress`,e)}we(`MuiLinearProgress`,[`root`,`colorPrimary`,`colorSecondary`,`determinate`,`indeterminate`,`buffer`,`query`,`dashed`,`bar`,`bar1`,`bar2`]);var go=4,_o={},vo=r`
44
+ `:``}${n}`,assistantMessageRef:r}}function ui(e,t){return e?.state===`ready`&&e.gatewayInstanceRef===t&&Number.isSafeInteger(e.eventSequence)&&e.eventSequence>=0&&Array.isArray(e.operations)&&Array.isArray(e.settlements)?e.eventSequence:null}function di(e,t){return e&&!t?`connected`:`reconnecting`}var fi=100,pi=/^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/,mi=/^[a-z0-9][a-z0-9.-]{0,95}$/,hi=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;function gi(e,t){return typeof t==`string`&&mi.test(t)?t:e===`aborted`?`operation-aborted`:e===`blocked`?`operation-blocked`:e===`error`?`operation-failed`:`operation-settlement-unknown`}function _i(e){if(e.settlement===`completed`||typeof e.operationRef!=`string`||!pi.test(e.operationRef)||typeof e.settledAt!=`string`||!hi.test(e.settledAt)||!Number.isSafeInteger(e.sequence)||Number(e.sequence)<1)return null;let t=[`blocked`,`aborted`,`error`,`unknown`].includes(String(e.settlement))?e.settlement:`unknown`,n=t===`error`?`failed`:t;return{activityRef:e.operationRef,operationRef:e.operationRef,settlement:t,state:n,reasonCode:gi(t,e.reasonCode),settledAt:e.settledAt,sequence:Number(e.sequence)}}function vi(e,t){let n=new Map;for(let r of[...e,...t])n.has(r.operationRef)||n.set(r.operationRef,r);return[...n.values()].sort((e,t)=>t.sequence-e.sequence).slice(0,fi)}function yi(e){if(e.state!==`ready`)return{};let t={};for(let n of e.settlements??[]){let e=_i(n);e&&(t[n.sessionRef]=vi(t[n.sessionRef]??[],[e]))}return t}function bi(e,t){let n=[`completed`,`blocked`,`aborted`,`error`].includes(String(t.settlement))?t.settlement:`unknown`;return{...e,operationRef:t.operationRef,abortable:!1,complete:!0,settlement:n,activities:[],delivery:e.user?`admitted`:e.delivery,assistant:n===`completed`?e.assistant:``,error:n===`completed`?null:String(t.reasonCode??`operation-settlement-unknown`)}}function xi(e,t){return{...e??{assistant:``,activities:[],operationRef:null,complete:!0,error:null},user:t.message,assistant:``,attachments:t.attachments,activities:[],operationRef:null,abortable:!1,complete:!1,settlement:null,error:null,messageRequestId:t.messageRequestId,delivery:`submitting`,startedAt:t.submittedAt,lastEventAt:t.submittedAt}}function Si(e,t,n,r){let i=t===`admitted`&&!!n&&e.operationRef===n&&e.complete;return{...e,delivery:t,operationRef:n??e.operationRef,abortable:t===`admitted`&&!i&&!!(n??e.operationRef),complete:t===`admitted`?i:e.complete,error:null,lastEventAt:r??e.lastEventAt}}function Ci(e,t,n){return!e||e.messageRequestId!==n||e.delivery===`admitted`?e:t}function wi(e,t){if(t.state!==`ready`)return{...e};let n=new Map(t.operations.map(e=>[e.sessionRef,e])),r={...e};for(let[i,a]of Object.entries(e))n.has(i)||a.complete||a.delivery!==`submitting`&&(r[i]={...a,assistant:``,activities:[],operationRef:null,abortable:!1,complete:!0,settlement:`unknown`,error:`operation-settlement-unavailable`,lastEventAt:t.generatedAt});for(let n of t.operations){let i=e[n.sessionRef],a=!(n.messageRequestId&&i?.messageRequestId&&n.messageRequestId!==i.messageRequestId)&&(i?.operationRef===n.operationRef||!!(i?.user&&[`submitting`,`unconfirmed`].includes(String(i.delivery))));r[n.sessionRef]=a?{...i,operationRef:n.operationRef,abortable:n.abortable,complete:!1,settlement:null,messageRequestId:n.messageRequestId??i?.messageRequestId,delivery:i?.user?`admitted`:i?.delivery,error:null,lastEventAt:t.generatedAt}:{user:``,assistant:``,attachments:[],activities:[],operationRef:n.operationRef,messageRequestId:n.messageRequestId??null,abortable:n.abortable,complete:!1,settlement:null,error:null,runtimeRecovery:null,startedAt:t.generatedAt,lastEventAt:t.generatedAt}}return r}function Ti(e,t){let n=e.toLowerCase();return n===`compaction`?t===`vi`?`tóm tắt phần cũ của cuộc trò chuyện`:`summarising the older part of the conversation`:n===`capacity-wait`?t===`vi`?`chờ tài khoản công ty rảnh`:`waiting for a free company account`:n===`ask_user`?t===`vi`?`chờ bạn trả lời câu hỏi`:`waiting for your answer`:/(subagent|scout|delegate|agent)/.test(n)?t===`vi`?`phối hợp agent hỗ trợ`:`coordinating a helper agent`:/(bash|exec|shell|command|terminal)/.test(n)?t===`vi`?`chạy lệnh`:`running a command`:/(read|grep|find|list|glob|search_file)/.test(n)?t===`vi`?`đọc mã nguồn`:`reading source`:/(edit|write|patch|apply)/.test(n)?t===`vi`?`cập nhật file`:`updating files`:/(test|verify|check|lint)/.test(n)?t===`vi`?`kiểm tra kết quả`:`verifying results`:/(web|search|browser|fetch)/.test(n)?t===`vi`?`tìm kiếm thông tin`:`searching`:t===`vi`?`chạy công cụ`:`running a tool`}var Ei=/(?:sk-(?:proj|live|test|svcacct)-[A-Za-z0-9_-]{8,}|as_(?:live|device|run)_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}_|(?:api[_-]?key|password|secret|token)=)/i;function Di(e){if(typeof e!=`string`)return null;let t=(e.replace(/\\/g,`/`).split(`/`).at(-1)??``).trim();return!t||t===`.`||t===`..`||t.length>160||/[\u0000-\u001f\u007f/\\]/.test(t)||Ei.test(t)||t.includes(`[REDACTED`)?null:t}function Oi(e,t=`vi`,n=Date.now()){let r=[...e.activities].reverse().find(e=>e.state===`running`),i=r?Ti(r.toolLabel,t):e.activities.length?t===`vi`?`tổng hợp bước tiếp theo`:`preparing the next step`:t===`vi`?`phân tích yêu cầu`:`analyzing the request`,a=Date.parse(e.lastEventAt??r?.startedAt??e.startedAt??``),o=Number.isFinite(a)?Math.max(0,Math.floor((n-a)/1e3)):null,s=o===null?t===`vi`?`Đang chờ cập nhật tiến trình đầu tiên`:`Waiting for the first progress update`:o<10?t===`vi`?`Tiến trình vừa cập nhật`:`Progress updated just now`:o<60?t===`vi`?`Cập nhật ${o} giây trước`:`Updated ${o}s ago`:t===`vi`?`Cập nhật ${Math.floor(o/60)} phút trước`:`Updated ${Math.floor(o/60)}m ago`,c=Di(r?.fileLabel),l=c?`${c} · ${s}`:s;return{label:t===`vi`?`Piagent đang ${i}…`:`Piagent is ${i}…`,detail:l}}function ki(e,t,n,r){if(e?.state!==`ready`||e.gatewayInstanceRef!==t)return!1;let i=e.operations.find(e=>e.sessionRef===n);return i?.operationRef===r&&i.abortable===!0}function Ai(e){let t=e.lastIndexOf(`
45
+
46
+ `);return(e.slice(0,t<0?0:t).match(/^```/gm)??[]).length%2==1&&(t=e.lastIndexOf("\n```",t)),t>0?[e.slice(0,t).replace(/\n+$/,``),e.slice(t).replace(/^\n+/,``)]:[``,e]}function ji(e,t){return{key:t,user:e,steps:[],answer:null,failure:null,failureDetail:null,requests:0,tokens:0,model:null,process:null,end:null,startedAt:e.recordedAt,endedAt:null,outputTokens:0,generationMs:0}}var Mi=new Set([`objection`,`rejudge`,`dispute`]);function Ni(e){let t=[],n=null,r=NaN;for(let i of e){let e=Date.parse(i.recordedAt),a=r;if(i.role!==`custom`&&(r=e),i.role===`user`){n=ji(i,i.messageRef),t.push(n);continue}if(!n||i.role===`tool-result`)continue;if(n.endedAt=i.recordedAt,i.role===`custom`&&i.turnEnd){n.end=i.turnEnd;continue}if(i.role===`custom`&&i.process){if(n.process&&(n.answer&&(n.steps.push({kind:`note`,key:`${i.messageRef}:round-answer`,text:n.answer,draft:!0}),n.answer=null),n.steps.push({kind:`process`,key:`${i.messageRef}:round`,process:n.process}),n.process=null),i.process.phase===`final`){n.process=i.process;continue}n.answer&&!Mi.has(i.process.phase)&&(n.steps.push({kind:`note`,key:`${i.messageRef}:answer`,text:n.answer,draft:!0}),n.answer=null),n.steps.push({kind:`process`,key:i.messageRef,process:i.process});continue}i.role===`assistant`&&i.usage?.outputTokens&&e>a&&(n.outputTokens+=i.usage.outputTokens,n.generationMs+=e-a),i.role===`assistant`&&(i.failure?.local||(n.requests+=1),n.tokens+=i.usage?.totalTokens??0,n.model=i.model??n.model);let o=cn(i);if(o){n.answer||(n.failure=o,n.failureDetail=i.failure??null);continue}for(let e of i.toolCalls)n.steps.push({kind:`tool`,key:`${i.messageRef}:${e.toolCallRef}`,tool:e});if(i.toolCalls.length)continue;let s=i.role===`assistant`?Zt(i.content.text??``):i.content.text;if(s){if(i.role===`custom`){n.steps.push({kind:`note`,key:i.messageRef,text:s});continue}n.answer&&n.answer.trim()!==s.trim()&&n.steps.push({kind:`note`,key:`${i.messageRef}:previous`,text:n.answer}),n.answer=s,n.failure=null,n.failureDetail=null}}for(let e of t){let t=new Set(e.answer?[e.answer.trim()]:[]);e.steps=e.steps.reduceRight((e,n)=>{if(n.kind===`note`&&n.draft){let r=n.text.trim();if(t.has(r))return e;t.add(r)}return[n,...e]},[])}return t}function Pi(e){let t=Date.parse(e.startedAt??``),n=Date.parse(e.endedAt??``);return Number.isFinite(t)&&Number.isFinite(n)&&n>=t?Math.round((n-t)/1e3):null}function Fi(e){if(e.outputTokens<50||e.generationMs<250)return null;let t=e.outputTokens/(e.generationMs/1e3);return t>=10?Math.round(t):Math.round(t*10)/10}function Ii(e,t){return e<40||t<1e3?null:Math.round(e/4/(t/1e3))}function Li(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(+(e<1e4))}k`:`${(e/1e6).toFixed(1)}M`}var Ri=e=>`/api/v1/sessions/${encodeURIComponent(e)}/checkpoints`,zi=`piagent-webui-checkpoint-v1`;function Bi(e){return Array.isArray(e)?`[${e.map(Bi).join(`,`)}]`:e&&typeof e==`object`?`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${Bi(t)}`).join(`,`)}}`:JSON.stringify(e)}async function Vi(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return`sha256:${[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`}var Hi=e=>typeof e==`string`&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(e),Ui=e=>typeof e==`string`&&/^[a-f0-9]{64}$/.test(e),Wi=(e,t)=>typeof e==`string`&&e.length>0&&e.length<=t,Gi=e=>Array.isArray(e)&&e.length<=1e4&&e.every(e=>Wi(e,4096)),Ki=e=>typeof e==`string`&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(e)&&Number.isFinite(Date.parse(e));function qi(e){return e&&[`projectRef`,`runtimeInstanceId`,`sessionRef`].every(t=>typeof e[t]==`string`&&/^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/.test(e[t]))&&[`taskId`,`taskRunId`,`agentOperationId`,`toolCallId`].every(t=>e[t]===null||typeof e[t]==`string`&&/^[A-Za-z0-9][A-Za-z0-9._:@~-]{0,159}$/.test(e[t]))}function Ji(e){return Hi(e.targetId)&&[`ready`,`conflict`,`busy`,`none`,`unavailable`].includes(e.result)&&(e.previewDigest===null||Ui(e.previewDigest))&&(e.tree===null||typeof e.tree==`string`&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(e.tree))&&Array.isArray(e.steps)&&e.steps.length<=64&&e.steps.every(e=>e&&Hi(e.id)&&Wi(e.turnRef,256)&&Gi(e.restore)&&Gi(e.remove))&&Gi(e.files)&&Gi(e.conflicts)&&(e.stoppedAt===null||Hi(e.stoppedAt))}async function Yi(e,t,n){let r=await fetch(Ri(e)+(t?`/${encodeURIComponent(t)}`:``),{credentials:`same-origin`,signal:n,headers:{Accept:`application/json`}});if(r.status===401&&Ie(),!r.ok)throw Error(`checkpoint-unavailable`);let i=await r.json();if(!i||i.schemaVersion!==1||i.version!==zi||i.identity?.sessionRef!==e||!qi(i.identity)||i.messageType!==(t?`preview`:`state`)||!/^[a-f0-9]{64}$/.test(i.revisions?.checkpointRevision??``)||i.messageType===`state`&&(typeof i.available!=`boolean`||typeof i.agentRunning!=`boolean`||!Array.isArray(i.points)||i.points.length>64||!i.points.every(e=>e&&Hi(e.id)&&Wi(e.turnRef,256)&&Number.isSafeInteger(e.at)&&e.at>=0))||i.messageType===`preview`&&(i.targetId!==t||!Ji(i)))throw Error(`checkpoint-response-invalid`);return i}var Xi=(e,t)=>Yi(e,null,t),Zi=(e,t,n)=>Yi(e,t,n);async function Qi(e){if(!Ji(e)||!qi(e.identity)||!Ui(e.revisions?.checkpointRevision)||!e.previewDigest||!e.tree||!e.steps.length||![`ready`,`conflict`].includes(e.result))throw Error(`checkpoint-preview-unavailable`);let t=Date.now(),n=`checkpoint.restore`,r={...e.identity},i={...e.revisions},a={targetId:e.targetId,previewDigest:e.previewDigest,expectedTree:e.tree,confirmed:!0};return{schemaVersion:1,version:zi,messageType:`command`,action:n,identity:r,expectedRevisions:i,payload:a,commandId:crypto.randomUUID(),idempotencyKey:crypto.randomUUID(),requestedAt:new Date(t).toISOString(),expiresAt:new Date(t+6e4).toISOString(),actionDigest:await Vi(Bi({action:n,identity:r,expectedRevisions:i,payload:a}))}}async function $i(e,t){let{action:n,identity:r,expectedRevisions:i,payload:a}=e;return e.schemaVersion===1&&e.version===zi&&e.messageType===`command`&&n===`checkpoint.restore`&&qi(r)&&r.sessionRef===t&&Ui(i?.checkpointRevision)&&a?.confirmed===!0&&Hi(a.targetId)&&Ui(a.previewDigest)&&typeof a.expectedTree==`string`&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(a.expectedTree)&&typeof e.commandId==`string`&&/^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/.test(e.commandId)&&typeof e.idempotencyKey==`string`&&/^[A-Za-z0-9._~-]{32,128}$/.test(e.idempotencyKey)&&Ki(e.requestedAt)&&Ki(e.expiresAt)&&e.actionDigest===await Vi(Bi({action:n,identity:r,expectedRevisions:i,payload:a}))}async function ea(e,t){if(!await $i(t,e))throw Error(`checkpoint-command-invalid`);let n=Fe();if(!n)throw Error(`checkpoint-unavailable`);let r=await Pe(Ri(e),{method:`POST`,credentials:`same-origin`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Piagent-CSRF":n},body:JSON.stringify(t)});if(r.status===401&&Ie(),!r.ok)throw Error(`checkpoint-unavailable`);let i=await r.json();if(!i||i.schemaVersion!==1||i.version!==zi||i.messageType!==`receipt`||i.commandId!==t.commandId||i.actionDigest!==t.actionDigest||i.action!==t.action||i.targetId!==t.payload.targetId||i.idempotencyKeyDigest!==await Vi(t.idempotencyKey)||Bi(i.identity)!==Bi(t.identity)||![`settled`,`rejected`,`uncertain`].includes(i.phase)||![`restored`,`conflict`,`stale-revision`,`identity-mismatch`,`read-only`,`busy`,`unavailable`,`expired`,`idempotency-payload-mismatch`,`effect-unknown`].includes(i.resultCode)||i.requestedAt!==t.requestedAt||!Ki(i.settledAt)||typeof i.deduplicated!=`boolean`||!Ui(i.observedRevisionsBefore?.checkpointRevision)||!Ui(i.observedRevisionsAfter?.checkpointRevision)||!Array.isArray(i.completed)||i.completed.length>64||!i.completed.every(Hi)||!Gi(i.files)||!Gi(i.conflicts)||!(i.stoppedAt===null||Hi(i.stoppedAt))||i.phase===`uncertain`!=(i.resultCode===`effect-unknown`)||i.resultCode===`restored`&&i.phase!==`settled`)throw Error(`checkpoint-receipt-invalid`);return i}var ta=`piagent.checkpoint.pending.v1`,na=64;function ra(e){let t=e.getItem(ta);if(t===null)return Object.create(null);if(t.length>262144)throw Error(`checkpoint-pending-invalid`);let n=JSON.parse(t);if(!Array.isArray(n)||n.length>na)throw Error(`checkpoint-pending-invalid`);let r=Object.create(null);for(let e of n){if(!Array.isArray(e)||e.length!==2)throw Error(`checkpoint-pending-invalid`);let[t,n]=e;if(typeof t!=`string`||!/^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/.test(t)||r[t]||!n||n.schemaVersion!==1||n.version!==`piagent-webui-checkpoint-v1`||n.messageType!==`command`||n.action!==`checkpoint.restore`||n.identity?.sessionRef!==t||n.payload?.confirmed!==!0||typeof n.payload.targetId!=`string`||typeof n.commandId!=`string`||typeof n.idempotencyKey!=`string`)throw Error(`checkpoint-pending-invalid`);r[t]=n}return r}function ia(e,t=window.sessionStorage){return ra(t)[e]}function aa(e,t,n=window.sessionStorage){let r=ra(n),i=r[e];if(i&&JSON.stringify(i)!==JSON.stringify(t))throw Error(`checkpoint-pending-exists`);if(!i&&Object.keys(r).length>=na)throw Error(`checkpoint-pending-capacity`);if(t.identity.sessionRef!==e)throw Error(`checkpoint-pending-session`);r[e]=t;let a=JSON.stringify(Object.entries(r));if(a.length>262144)throw Error(`checkpoint-pending-capacity`);if(n.setItem(ta,a),n.getItem(ta)!==a)throw Error(`checkpoint-pending-write-failed`)}function oa(e,t,n=window.sessionStorage){let r=ra(n);if(r[e]){if(JSON.stringify(r[e])!==JSON.stringify(t))throw Error(`checkpoint-pending-replaced`);delete r[e],n.setItem(ta,JSON.stringify(Object.entries(r)))}}var sa=(0,$.createContext)(null);function ca({turnRef:e}){let t=(0,$.useContext)(sa),n=t?.state?.points.find(t=>t.turnRef===e);return!t||!n?null:(0,Q.jsx)(a,{size:`small`,disabled:t.busy||t.state?.agentRunning,onClick:()=>t.open(n.id),sx:{alignSelf:`flex-start`},children:X(t.locale,`Khôi phục về trước lượt này`,`Restore before this turn`)})}function la({sessionRef:e,refresh:t,running:n,locale:r,children:i}){let[o,c]=(0,$.useState)(),[l,u]=(0,$.useState)(0),[d,f]=(0,$.useState)(!1),[p,m]=(0,$.useState)(!1),[h,_]=(0,$.useState)(!1),[y,b]=(0,$.useState)(),[x,C]=(0,$.useState)(),[w,T]=(0,$.useState)(!1),[E]=(0,$.useState)(()=>{try{return{command:ia(e),failed:!1}}catch{return{command:void 0,failed:!0}}}),[D,O]=(0,$.useState)(E.command),[k,A]=(0,$.useState)(E.failed),j=(0,$.useRef)(null),M=(0,$.useRef)(!1),N=(0,$.useRef)(!0);(0,$.useEffect)(()=>(N.current=!0,()=>{N.current=!1,j.current?.abort()}),[]),(0,$.useEffect)(()=>{let t=new AbortController;return Xi(e,t.signal).then(e=>{t.signal.aborted||c(e)}).catch(()=>{}),()=>t.abort()},[e,t,l]);let F=t=>{if(f(!0),C(void 0),T(!1),D)return;j.current?.abort();let n=new AbortController;j.current=n,b(void 0),m(!0),Zi(e,t,n.signal).then(e=>{n.signal.aborted||b(e)}).catch(()=>{n.signal.aborted||T(!0)}).finally(()=>{n.signal.aborted||m(!1)})},L=async()=>{if(!(k||M.current||!D&&(!y||n||o?.agentRunning||![`ready`,`conflict`].includes(y.result)))){M.current=!0,_(!0),T(!1);try{let t=D??await Qi(y);try{aa(e,t)}catch{A(!0);return}O(t);let n=await ea(e,t);if(n.phase!==`uncertain`&&oa(e,t),!N.current)return;C(n),n.phase!==`uncertain`&&O(void 0),u(e=>e+1)}catch{N.current&&T(!0)}finally{window.dispatchEvent(new CustomEvent(`piagent-workspace-changed`,{detail:{sessionRef:e}})),M.current=!1,N.current&&_(!1)}}},R=()=>{M.current||(j.current?.abort(),f(!1),m(!1))},ee=x?.conflicts??y?.conflicts??[],B=x?.phase===`uncertain`||w&&!!D;return(0,Q.jsxs)(sa.Provider,{value:{state:o,busy:n||h||k,open:F,locale:r},children:[o&&!o.available&&(0,Q.jsx)(S,{variant:`caption`,color:`text.secondary`,children:X(r,`Project không dùng Git nên không có checkpoint để khôi phục.`,`This project has no Git repository, so checkpoints are unavailable.`)}),D&&!d&&(0,Q.jsx)(v,{severity:`warning`,action:(0,Q.jsx)(a,{color:`inherit`,onClick:()=>F(D.payload.targetId),children:X(r,`Xem kết quả`,`Check result`)}),children:X(r,`Một lần khôi phục chưa có kết quả xác nhận.`,`A restore is awaiting a confirmed result.`)}),k&&!d&&(0,Q.jsx)(v,{severity:`error`,children:X(r,`Không đọc hoặc lưu được yêu cầu khôi phục đang chờ trong trình duyệt. Chưa gửi yêu cầu mới; hãy kiểm tra file trước khi tiếp tục.`,`The browser could not read or save the pending restore. No new request was sent; inspect your files before continuing.`)}),i,(0,Q.jsxs)(s,{open:d,onClose:R,fullWidth:!0,maxWidth:`sm`,"aria-labelledby":`checkpoint-dialog-title`,children:[(0,Q.jsx)(I,{id:`checkpoint-dialog-title`,children:X(r,`Khôi phục về trước lượt này`,`Restore before this turn`)}),(0,Q.jsx)(z,{children:(0,Q.jsxs)(P,{spacing:2,children:[k&&(0,Q.jsx)(v,{severity:`error`,children:X(r,`Không đọc hoặc lưu được yêu cầu khôi phục đang chờ trong trình duyệt. Chưa gửi yêu cầu mới; hãy kiểm tra file trước khi tiếp tục.`,`The browser could not read or save the pending restore. No new request was sent; inspect your files before continuing.`)}),p&&(0,Q.jsx)(S,{children:X(r,`Đang xem trước…`,`Loading preview…`)}),y&&!x&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(S,{children:X(r,`Sẽ hoàn tác ${y.steps.length} lượt từ mới nhất về lượt đã chọn. Commit và vùng stage được giữ nguyên.`,`Undo ${y.steps.length} turns from newest to the selected turn. Commits and staged changes are preserved.`)}),(0,Q.jsx)(S,{variant:`body2`,sx:{whiteSpace:`pre-wrap`,maxHeight:240,overflow:`auto`},children:y.files.join(`
47
+ `)}),![`ready`,`conflict`].includes(y.result)&&(0,Q.jsx)(v,{severity:`info`,children:X(r,`Checkpoint hiện không thể khôi phục. Đóng hộp thoại rồi xem trước lại khi lượt chạy kết thúc.`,`This checkpoint cannot be restored now. Close this dialog and preview again after the running turn ends.`)})]}),ee.length>0&&(0,Q.jsxs)(v,{severity:`warning`,children:[X(r,`Sẽ dừng trước file đã thay đổi sau lượt: `,`Stop before files changed after the turn: `),ee.join(`, `)]}),x&&!B&&(0,Q.jsx)(v,{severity:x.resultCode===`restored`?`success`:`warning`,children:x.resultCode===`restored`?X(r,`Đã khôi phục ${x.completed.length} lượt.`,`Restored ${x.completed.length} turns.`):x.resultCode===`conflict`?X(r,`Đã khôi phục ${x.completed.length} lượt và dừng để giữ thay đổi của bạn.`,`Restored ${x.completed.length} turns and stopped to preserve your changes.`):X(r,`Chưa khôi phục: trạng thái hoặc quyền đã thay đổi. Đóng hộp thoại và xem trước lại.`,`Not restored: state or permissions changed. Close this dialog and preview again.`)}),B&&(0,Q.jsx)(v,{severity:`warning`,children:X(r,`Chưa xác nhận được kết quả; một số file có thể đã thay đổi. Kiểm tra file trước khi tiếp tục. Nút bên dưới chỉ kiểm tra lại cùng yêu cầu.`,`The result is unconfirmed; some files may have changed. Inspect them before continuing. The button below checks the same request.`)}),w&&!D&&(0,Q.jsx)(v,{severity:`error`,children:X(r,`Không tải được preview. Đóng hộp thoại và thử lại.`,`Could not load the preview. Close this dialog and try again.`)})]})}),(0,Q.jsxs)(g,{children:[(0,Q.jsx)(a,{disabled:h,onClick:R,children:X(r,`Đóng`,`Close`)}),(!x||B)&&(0,Q.jsx)(a,{variant:`contained`,disabled:k||h||p||!D&&(n||o?.agentRunning||!y?.steps.length||![`ready`,`conflict`].includes(y?.result??``)),onClick:()=>void L(),children:D?X(r,`Kiểm tra lại kết quả`,`Check result again`):X(r,`Xác nhận khôi phục`,`Confirm restore`)})]})]})]})}var ua=q((0,Q.jsx)(`path`,{d:`M19 5v14H5V5zm0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m-4.86 8.86-3 3.87L9 13.14 6 17h12z`}),`ImageOutlined`);function da(e,t,n){return Je(tt(e,`/api/v1/transcript-images/${encodeURIComponent(t)}?index=${n}`))}function fa(e){return`${e.sessionRef}\u0000${e.messageRef}\u0000${e.index}`}function pa(e){let t=e?`staged`in e?`staged:${e.staged}`:fa(e):``,n=()=>e?`staged`in e?qt(e.staged):dn(fa(e)):null,[r,i]=(0,$.useState)(()=>({key:t,url:n(),failed:!1}));r.key!==t&&i({key:t,url:n(),failed:!1}),(0,$.useEffect)(()=>{if(!e||`staged`in e||dn(t))return;let n=!0;return Gt(t,()=>da(e.sessionRef,e.messageRef,e.index)).then(e=>{n&&i({key:t,url:e,failed:!e})}),()=>{n=!1}},[t]);let a=r.failed||!e||`staged`in e&&!r.url;return{url:r.key===t?r.url:null,failed:a,fail:()=>i({key:t,url:null,failed:!0})}}function ma({name:e,source:t,locale:n,fallback:r}){let{url:i,failed:a,fail:o}=pa(t),[c,l]=(0,$.useState)(!1);return a?(0,Q.jsx)(Q.Fragment,{children:r}):i?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(_,{onClick:()=>l(!0),"aria-label":X(n,`Xem ảnh ${e}`,`View image ${e}`),title:e,sx:{alignSelf:`flex-start`,borderRadius:1,overflow:`hidden`,border:1,borderColor:`divider`,bgcolor:`background.paper`},children:(0,Q.jsx)(R,{component:`img`,src:i,alt:e,onError:o,loading:`lazy`,sx:{display:`block`,maxWidth:{xs:`100%`,sm:320},maxHeight:220,objectFit:`contain`}})}),(0,Q.jsxs)(s,{open:c,onClose:()=>l(!1),maxWidth:!1,slotProps:{paper:{sx:{bgcolor:`background.default`,m:1,maxWidth:`96vw`,maxHeight:`94vh`}}},children:[(0,Q.jsxs)(R,{sx:{display:`flex`,alignItems:`center`,gap:1,pl:2,pr:.5,py:.5},children:[(0,Q.jsx)(S,{variant:`body2`,noWrap:!0,sx:{flex:1,fontWeight:600},children:e}),(0,Q.jsx)(L,{size:`small`,"aria-label":X(n,`Đóng`,`Close`),onClick:()=>l(!1),children:(0,Q.jsx)(h,{fontSize:`small`})})]}),(0,Q.jsx)(R,{component:`img`,src:i,alt:e,sx:{display:`block`,maxWidth:`96vw`,maxHeight:`calc(94vh - 48px)`,objectFit:`contain`,mx:`auto`}})]})]}):(0,Q.jsx)(ni,{variant:`rounded`,width:220,height:140,"aria-label":X(n,`Đang tải ảnh`,`Loading image`)})}var ha=q((0,Q.jsx)(`path`,{d:`M22 11V3h-7v3H9V3H2v8h7V8h2v10h4v3h7v-8h-7v3h-2V8h2v3zM7 9H4V5h3zm10 6h3v4h-3zm0-10h3v4h-3z`}),`AccountTreeOutlined`),ga=q((0,Q.jsx)(`path`,{d:`m22.61 18.99-9.08-9.08c.93-2.34.45-5.1-1.44-7C9.79.61 6.21.4 3.66 2.26L7.5 6.11 6.08 7.52 2.25 3.69C.39 6.23.6 9.82 2.9 12.11c1.86 1.86 4.57 2.35 6.89 1.48l9.11 9.11c.39.39 1.02.39 1.41 0l2.3-2.3c.4-.38.4-1.01 0-1.41m-3 1.6-9.46-9.46c-.61.45-1.29.72-2 .82-1.36.2-2.79-.21-3.83-1.25C3.37 9.76 2.93 8.5 3 7.26l3.09 3.09 4.24-4.24-3.09-3.09c1.24-.07 2.49.37 3.44 1.31 1.08 1.08 1.49 2.57 1.24 3.96-.12.71-.42 1.37-.88 1.96l9.45 9.45z`}),`BuildOutlined`),_a=q((0,Q.jsx)(`path`,{d:`M22 8c0-.55-.45-1-1-1h-7c-.55 0-1 .45-1 1s.45 1 1 1h7c.55 0 1-.45 1-1m-9 8c0 .55.45 1 1 1h7c.55 0 1-.45 1-1s-.45-1-1-1h-7c-.55 0-1 .45-1 1M10.47 4.63c.39.39.39 1.02 0 1.41l-4.23 4.25c-.39.39-1.02.39-1.42 0L2.7 8.16a.996.996 0 0 1 0-1.41c.39-.39 1.02-.39 1.41 0l1.42 1.42 3.54-3.54c.38-.38 1.02-.38 1.4 0m.01 8.01c.39.39.39 1.02 0 1.41L6.25 18.3c-.39.39-1.02.39-1.42 0L2.7 16.16c-.39-.39-.39-1.02 0-1.41s1.02-.39 1.41 0l1.42 1.42 3.54-3.54c.38-.38 1.02-.38 1.41.01`}),`ChecklistRounded`),va=q((0,Q.jsx)(`path`,{d:`m14.85 4.85 1.44 1.44-2.88 2.88 1.42 1.42 2.88-2.88 1.44 1.44c.31.31.85.09.85-.36V4.5c0-.28-.22-.5-.5-.5h-4.29c-.45 0-.67.54-.36.85M8.79 4H4.5c-.28 0-.5.22-.5.5v4.29c0 .45.54.67.85.35L6.29 7.7 11 12.4V19c0 .55.45 1 1 1s1-.45 1-1v-7c0-.26-.11-.52-.29-.71l-5-5.01 1.44-1.44c.31-.3.09-.84-.36-.84`}),`CallSplitRounded`),ya=q((0,Q.jsx)(`path`,{d:`m14.06 9.02.92.92L5.92 19H5v-.92zM17.66 3c-.25 0-.51.1-.7.29l-1.83 1.83 3.75 3.75 1.83-1.83c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.2-.2-.45-.29-.71-.29m-3.6 3.19L3 17.25V21h3.75L17.81 9.94z`}),`EditOutlined`),ba=q((0,Q.jsx)(`path`,{d:`M8 2c-1.1 0-2 .9-2 2v3.17c0 .53.21 1.04.59 1.42L10 12l-3.42 3.42c-.37.38-.58.89-.58 1.42V20c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2v-3.16c0-.53-.21-1.04-.58-1.41L14 12l3.41-3.4c.38-.38.59-.89.59-1.42V4c0-1.1-.9-2-2-2zm8 14.5V19c0 .55-.45 1-1 1H9c-.55 0-1-.45-1-1v-2.5l4-4zm-4-5-4-4V5c0-.55.45-1 1-1h6c.55 0 1 .45 1 1v2.5z`}),`HourglassEmptyRounded`),xa=q((0,Q.jsx)(`path`,{d:`M13 11h-2v3H8v2h3v3h2v-3h3v-2h-3zm1-9H6c-1.1 0-2 .9-2 2v16c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8zm4 18H6V4h7v5h5z`}),`NoteAddOutlined`),Sa=q((0,Q.jsx)(`path`,{d:`M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39`}),`PublicRounded`),Ca=q((0,Q.jsx)(`path`,{d:`M2 6c.55 0 1-.45 1-1V4c0-.55.45-1 1-1h1c.55 0 1-.45 1-1s-.45-1-1-1H4C2.34 1 1 2.34 1 4v1c0 .55.45 1 1 1m3 15H4c-.55 0-1-.45-1-1v-1c0-.55-.45-1-1-1s-1 .45-1 1v1c0 1.66 1.34 3 3 3h1c.55 0 1-.45 1-1s-.45-1-1-1M20 1h-1c-.55 0-1 .45-1 1s.45 1 1 1h1c.55 0 1 .45 1 1v1c0 .55.45 1 1 1s1-.45 1-1V4c0-1.66-1.34-3-3-3m2 17c-.55 0-1 .45-1 1v1c0 .55-.45 1-1 1h-1c-.55 0-1 .45-1 1s.45 1 1 1h1c1.66 0 3-1.34 3-3v-1c0-.55-.45-1-1-1m-3-3.13V9.13c0-.72-.38-1.38-1-1.73l-5-2.88c-.31-.18-.65-.27-1-.27s-.69.09-1 .27L6 7.39c-.62.36-1 1.02-1 1.74v5.74c0 .72.38 1.38 1 1.73l5 2.88c.31.18.65.27 1 .27s.69-.09 1-.27l5-2.88c.62-.35 1-1.01 1-1.73m-8 2.3-4-2.3v-4.63l4 2.33zm1-6.33L8.04 8.53 12 6.25l3.96 2.28zm5 4.03-4 2.3v-4.6l4-2.33z`}),`ViewInArRounded`),wa=`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,Ta={read:br,write:xa,edit:ya,command:E,search:c,list:x,"web-search":d,"web-fetch":D,subagent:ha,network:Sa,docker:Ca,git:va,plan:_a,other:ga},Ea={read:[`Đọc`,`Read`],write:[`Tạo`,`Write`],edit:[`Sửa`,`Edit`],command:[`Chạy`,`Run`],search:[`Tìm`,`Search`],list:[`Xem thư mục`,`List`],"web-search":[`Tìm web`,`Web search`],"web-fetch":[`Đọc trang`,`Fetch page`],subagent:[`Subagent`,`Subagent`],network:[`Chạy có mạng`,`Run with network`],docker:[`Chạy với Docker`,`Run with Docker`],git:[`Git`,`Git`],plan:[`Plan`,`Plan`],other:[`Công cụ`,`Tool`]},Da={read:`read`,write:`write`,edit:`edit`,apply_patch:`edit`,bash:`command`,run_experiment:`command`,grep:`search`,find:`search`,ls:`list`,web_search:`web-search`,web_fetch:`web-fetch`,delegate:`subagent`,subagent:`subagent`,run_with_network:`network`,run_with_docker:`docker`,fetch_origin:`git`,update_plan:`plan`};function Oa(e){return Da[e.toLowerCase()]??`other`}function ka({preview:e}){return(0,Q.jsx)(R,{component:`pre`,sx:{m:0,fontFamily:wa,fontSize:12,lineHeight:1.55,overflowX:`auto`},children:e.split(`
48
+ `).map((e,t)=>{let n=e[0],r=n===`+`?`success`:n===`-`?`error`:null;return(0,Q.jsx)(R,{component:`div`,sx:{px:1,whiteSpace:`pre`,...r?Et(r):{color:e===`@@`?`text.disabled`:`text.secondary`},bgcolor:r?`rgba(var(--piagent-palette-${r}-mainChannel) / .12)`:`transparent`},children:e===`@@`?`⋯`:e||` `},t)})})}function Aa({tool:e,locale:t,live:n,waiting:r}){let i=e.summary??{kind:`other`,target:null,detail:null},a=`change`in e?e.change:void 0,o=`result`in e?e.result:void 0,s=e.state===`failed`||o?.isError===!0,c=`failure`in e&&e.failure?{detail:e.failure,copy:sr(e.failure.reasonCode,e.failure.code,t)}:null,l=n?e.state===`running`:e.state===`requested`,[u,d]=(0,$.useState)(()=>s||(i.kind===`edit`||i.kind===`write`)&&!!a?.preview),f=!!(a?.preview||o?.text||c?.copy||i.detail&&i.kind!==`read`),p=r?ba:Ta[i.kind],m=Ea[i.kind][t===`vi`?0:1],g=i.kind===`other`?e.toolName:m;return(0,Q.jsxs)(R,{sx:{border:1,borderColor:s?`error.main`:`divider`,borderRadius:1,bgcolor:`background.paper`,overflow:`hidden`},children:[(0,Q.jsxs)(_,{component:`div`,disabled:!f,onClick:()=>d(e=>!e),"aria-expanded":f?u:void 0,sx:{width:`100%`,display:`flex`,alignItems:`center`,gap:1,px:1.25,py:.85,textAlign:`left`,justifyContent:`flex-start`},children:[(0,Q.jsx)(p,{sx:{fontSize:17,color:s?`error.main`:`text.secondary`,flexShrink:0}}),(0,Q.jsx)(S,{variant:`body2`,sx:{fontWeight:600,flexShrink:0},children:g}),i.target&&(0,Q.jsx)(S,{variant:`body2`,noWrap:!0,title:i.target,sx:{fontFamily:wa,fontSize:12.5,color:`text.secondary`,minWidth:0,flex:1},children:i.target}),!i.target&&(0,Q.jsx)(R,{sx:{flex:1}}),i.kind===`read`&&i.detail&&(0,Q.jsx)(S,{variant:`caption`,color:`text.disabled`,sx:{flexShrink:0},children:X(t,`dòng ${i.detail}`,`lines ${i.detail}`)}),a&&(a.added>0||a.removed>0)&&(0,Q.jsxs)(S,{variant:`caption`,sx:{fontFamily:wa,flexShrink:0},children:[a.added>0&&(0,Q.jsxs)(R,{component:`span`,sx:Et(`success`),children:[`+`,a.added,` `]}),a.removed>0&&(0,Q.jsxs)(R,{component:`span`,sx:Et(`error`),children:[`−`,a.removed]})]}),s&&!l&&(0,Q.jsx)(S,{variant:`caption`,sx:{flexShrink:0,fontWeight:600,...Et(`error`)},children:X(t,`Lỗi`,`Failed`)}),l?(0,Q.jsx)(ee,{size:14,thickness:5,"aria-label":X(t,`Đang chạy`,`Running`)}):s?(0,Q.jsx)(h,{sx:{fontSize:16,color:`error.main`},"aria-hidden":`true`}):(0,Q.jsx)(le,{sx:{fontSize:16,color:`success.main`},"aria-label":X(t,`Xong`,`Done`)}),f&&(0,Q.jsx)(j,{sx:{fontSize:18,color:`text.disabled`,transition:`transform .15s`,transform:u?`rotate(180deg)`:`none`}})]}),i.target&&[`read`,`write`,`edit`].includes(i.kind)&&(0,Q.jsx)(Ut,{path:i.target,line:Number.parseInt(i.detail??`1`,10)||1}),(0,Q.jsx)(or,{in:u&&f,unmountOnExit:!0,children:(0,Q.jsxs)(R,{sx:{borderTop:1,borderColor:`divider`,bgcolor:`action.hover`,maxHeight:360,overflow:`auto`},children:[i.detail&&i.kind!==`read`&&(0,Q.jsx)(S,{variant:`body2`,color:`text.secondary`,sx:{px:1.25,py:.75,whiteSpace:`pre-wrap`,overflowWrap:`anywhere`,...i.kind===`command`?{fontFamily:wa,fontSize:12}:{}},children:i.detail}),c?.copy&&(0,Q.jsxs)(R,{sx:{px:1.25,py:.75},children:[(0,Q.jsxs)(S,{variant:`body2`,sx:{fontWeight:650,...Et(`error`)},children:[ur(c.detail.role,t),` `,X(t,`lỗi`,`failed`),` · `,c.copy.title]}),(0,Q.jsx)(S,{variant:`body2`,color:`text.secondary`,children:c.copy.text}),(0,Q.jsxs)(S,{variant:`caption`,color:`text.secondary`,sx:{fontFamily:wa,overflowWrap:`anywhere`},title:c.detail.requestRef??void 0,children:[X(t,`Mã`,`Code`),`: `,c.detail.code,c.detail.requestRef?` · request ${c.detail.requestRef.slice(0,8)}`:``]})]}),a?.preview&&(0,Q.jsx)(R,{sx:{py:.5},children:(0,Q.jsx)(ka,{preview:a.preview})}),o?.text&&!c?.copy&&(0,Q.jsx)(R,{component:`pre`,sx:{m:0,px:1.25,py:.75,fontFamily:wa,fontSize:12,lineHeight:1.55,whiteSpace:`pre-wrap`,overflowWrap:`anywhere`,color:o.isError?`error.main`:`text.secondary`},children:o.text}),(a?.truncated||o?.truncated)&&(0,Q.jsx)(S,{variant:`caption`,color:`text.disabled`,sx:{display:`block`,px:1.25,pb:.75},children:X(t,`Đã rút gọn`,`Truncated`)})]})})]})}var ja=null,Ma=null,Na=()=>ja??=Me(()=>import(`./MarkdownMessage-DGt5B-6D.js`).then(e=>(Ma=e.MarkdownMessage,e)),__vite__mapDeps([16,1,2,13,3,12,5])),Pa=(0,$.lazy)(async()=>({default:(await Na()).MarkdownMessage}));function Fa({children:e}){let t=Ma;return t?(0,Q.jsx)(t,{children:e}):(0,Q.jsx)($.Suspense,{fallback:(0,Q.jsx)(S,{sx:{whiteSpace:`pre-wrap`,overflowWrap:`anywhere`,lineHeight:1.75},children:e}),children:(0,Q.jsx)(Pa,{children:e})})}var Ia=(0,$.memo)(function({text:e}){return(0,Q.jsx)(Fa,{children:e})});function La({text:e}){let[t,n]=Ai(e);return(0,Q.jsxs)(Q.Fragment,{children:[t&&(0,Q.jsx)(Ia,{text:t}),n&&(0,Q.jsx)(Fa,{children:n})]})}function Ra({attachments:e,images:t,locale:n}){if(!e.length)return null;let r=0;return(0,Q.jsx)(P,{spacing:.75,sx:{mb:1},"aria-label":X(n,`File đã gửi`,`Sent files`),children:e.map((e,i)=>{let a=`sourceBytes`in e,o=a?en(e,n):`${e.kind===`document`?X(n,`Tài liệu`,`Document`):e.kind===`image`?X(n,`Ảnh`,`Image`):`File`}${e.truncated?` · ${X(n,`đã cắt bớt`,`truncated`)}`:``}`,s=(0,Q.jsxs)(te,{variant:`outlined`,sx:{display:`flex`,alignItems:`center`,gap:1.1,minWidth:220,maxWidth:440,px:1.2,py:1,borderRadius:1,bgcolor:`background.paper`},children:[e.kind===`image`?(0,Q.jsx)(ua,{color:`action`}):(0,Q.jsx)(br,{color:`action`}),(0,Q.jsxs)(R,{sx:{minWidth:0},children:[(0,Q.jsx)(S,{variant:`body2`,noWrap:!0,sx:{fontWeight:650},children:e.displayName}),(0,Q.jsx)(S,{variant:`caption`,color:`text.secondary`,children:o})]})]},`${e.displayName}:${i}`);if(e.kind!==`image`)return s;let c=a?{staged:e.attachmentRef}:t?{...t,index:r}:null;return r+=1,(0,Q.jsx)(ma,{name:e.displayName,source:c,locale:n,fallback:s},`${e.displayName}:${i}`)})})}var za=new Set([`assistant-response-failed`,`operation-failed`]);function Ba(e,t){switch(e){case`provider-auth-expired`:return X(t,`Phiên đăng nhập model đã hết hạn. Mở Cài đặt → Nhà cung cấp & model để kết nối lại.`,`The model sign-in expired. Open Settings → Providers & models to reconnect.`);case`provider-auth-required`:return X(t,`Model cần đăng nhập lại. Mở Cài đặt → Nhà cung cấp & model.`,`The model needs to sign in again. Open Settings → Providers & models.`);case`provider-rate-limited`:return X(t,`Model đang bị giới hạn lượt gọi hoặc đã hết hạn mức. Thử lại sau.`,`The model is rate limited or out of quota. Try again later.`);case`provider-unavailable`:return X(t,`Model hoặc máy chủ trung gian đang không phục vụ yêu cầu này. Thử lại; nếu lỗi lặp lại, kiểm tra model đang dùng.`,`The model or its gateway did not serve this request. Retry; if it repeats, check the model in use.`);case`assistant-output-incomplete`:return X(t,`Câu trả lời dừng giữa chừng vì chạm giới hạn độ dài. Gửi “tiếp tục” để model viết tiếp.`,`The answer stopped at the length limit. Send “continue” to resume.`);default:return X(t,`Model trả lỗi và chưa có câu trả lời. Gửi lại; nếu lỗi lặp lại, kiểm tra model đang dùng.`,`The model returned an error without an answer. Send again; if it repeats, check the model in use.`)}}function Va({code:e,detail:t,locale:r,onContinue:i}){let o=sr(e,t?.code??null,r),s=i&&lr(e)?(0,Q.jsx)(a,{color:`inherit`,size:`small`,onClick:i,children:X(r,`Tiếp tục`,`Continue`)}):void 0;return o?(0,Q.jsxs)(v,{severity:`error`,variant:`outlined`,icon:(0,Q.jsx)(C,{}),action:s,sx:{alignSelf:`stretch`},children:[(0,Q.jsxs)(n,{sx:{fontSize:`inherit`,fontWeight:650,mb:.25},children:[ur(t?.role??`main`,r),` `,X(r,`lỗi`,`failed`),` · `,o.title]}),o.text,t&&(0,Q.jsxs)(S,{variant:`caption`,component:`div`,color:`text.secondary`,sx:{mt:.5,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,overflowWrap:`anywhere`},title:t.requestRef??void 0,children:[X(r,`Mã`,`Code`),`: `,t.code,t.requestRef?` · request ${t.requestRef.slice(0,8)}`:``]})]}):(0,Q.jsx)(v,{severity:`error`,variant:`outlined`,icon:(0,Q.jsx)(C,{}),action:s,sx:{alignSelf:`stretch`},children:Ba(e,r)})}function Ha({text:e,attachments:t,images:n,note:r,locale:i}){return(0,Q.jsxs)(R,{sx:{alignSelf:`flex-end`,maxWidth:`82%`,bgcolor:`action.selected`,borderRadius:1,px:2,py:1.4},children:[(0,Q.jsx)(Ra,{attachments:t,images:n,locale:i}),e&&(0,Q.jsx)(S,{sx:{whiteSpace:`pre-wrap`,overflowWrap:`anywhere`,lineHeight:1.7},children:(0,Q.jsx)(Ht,{children:e})}),r&&(0,Q.jsx)(S,{variant:`caption`,color:`text.secondary`,children:r})]})}function Ua({children:e}){return(0,Q.jsxs)(R,{sx:{display:`flex`,gap:1.5,alignItems:`flex-start`},children:[(0,Q.jsx)(ut,{size:26}),(0,Q.jsxs)(P,{spacing:1,sx:{minWidth:0,flex:1},children:[(0,Q.jsx)(S,{sx:{fontWeight:600},children:`Piagent`}),e]})]})}function Wa(e,t){return e.content.redacted?X(t,`Đã ẩn dữ liệu nhạy cảm`,`Sensitive data hidden`):e.content.truncated?X(t,`Nội dung đã rút gọn`,`Content truncated`):null}function Ga({turn:e,locale:t}){let n=Pi(e),r=[`${e.requests} request`];e.tokens&&r.push(`${Li(e.tokens)} token`),n!==null&&n>0&&r.push(n<60?`${n}s`:`${Math.floor(n/60)}m ${n%60}s`);let i=Fi(e);return i!==null&&r.push(`${i} tok/s`),e.model&&r.push(e.model),(0,Q.jsx)(S,{variant:`caption`,color:`text.disabled`,title:X(t,`Request model, token, thời gian và tốc độ sinh token (token đầu ra mỗi giây, tính cả thời gian chờ) của lượt này`,`Model requests, tokens, time and output speed (output tokens per second, waiting included) of this turn`),children:r.join(` · `)})}var Ka=(0,$.memo)(function({turn:e,sessionRef:t,locale:n,onContinue:r}){let i=!!r&&!e.answer&&!e.failure&&!e.end,o=e.steps.length>0||e.answer||e.failure||i||e.process||e.end;return(0,Q.jsxs)(P,{spacing:1.5,children:[(0,Q.jsx)(Ha,{text:e.user.content.text,attachments:e.user.attachments??[],note:Wa(e.user,n),locale:n,images:t?{sessionRef:t,messageRef:e.user.messageRef}:void 0}),o&&(0,Q.jsxs)(Ua,{children:[e.steps.map(e=>e.kind===`tool`?(0,Q.jsx)(Aa,{tool:e.tool,locale:n},e.key):e.kind===`process`?(0,Q.jsx)(wt,{process:e.process,locale:n},e.key):(0,Q.jsxs)(R,{sx:{color:`text.secondary`,fontSize:`.875rem`,"& .MuiTypography-root":{fontSize:`inherit`},...e.draft?{borderLeft:2,borderColor:`divider`,pl:1.5}:{}},children:[e.draft&&(0,Q.jsx)(S,{variant:`caption`,component:`div`,color:`text.disabled`,sx:{mb:.5,fontWeight:600},children:X(n,`Trả lời giữa chừng · harness yêu cầu làm tiếp`,`Interim answer · the harness asked for more`)}),(0,Q.jsx)(Fa,{children:e.text})]},e.key)),e.failure&&(0,Q.jsx)(Va,{code:e.failure,detail:e.failureDetail,locale:n,onContinue:r}),i&&(0,Q.jsx)(v,{severity:`info`,variant:`outlined`,sx:{alignSelf:`stretch`},action:(0,Q.jsx)(a,{color:`inherit`,size:`small`,onClick:r,children:X(n,`Tiếp tục`,`Continue`)}),children:X(n,`Lượt này chưa có câu trả lời: nó đã bị dừng, hoặc ứng dụng hay máy tắt khi đang chạy. Các bước đã làm vẫn được giữ; bấm Tiếp tục để làm tiếp.`,`This turn has no answer: it was stopped, or the app or the machine went down while it ran. Its steps are kept; press Continue to go on.`)}),e.answer&&(0,Q.jsx)(R,{children:(0,Q.jsx)(Fa,{children:e.answer})}),e.process&&(0,Q.jsx)(wt,{process:e.process,locale:n}),e.end&&(0,Q.jsx)(Ct,{end:e.end,locale:n,onContinue:e.failure?void 0:r}),e.requests>0&&(0,Q.jsx)(Ga,{turn:e,locale:n})]}),(0,Q.jsx)(ca,{turnRef:e.user.messageRef})]})});function qa(e,t){return e===`compaction`?X(t,`Tóm tắt phần cũ của cuộc trò chuyện`,`Summarise the older part of the conversation`):e===`capacity-wait`?X(t,`Chờ tài khoản công ty rảnh (Studio đang bận, sẽ tự gửi lại)`,`Wait for a free company account (Studio is busy; it is sent again by itself)`):e}function Ja({user:e,attachments:t,activities:n,assistant:r,running:i,failure:a,status:o,locale:s}){return(0,Q.jsxs)(P,{spacing:1.5,children:[e&&(0,Q.jsx)(Ha,{text:e,attachments:t,locale:s}),(0,Q.jsxs)(Ua,{children:[n.map(e=>(0,Q.jsx)(Aa,{live:!0,locale:s,waiting:e.toolLabel===`capacity-wait`,tool:{toolName:qa(e.toolLabel,s),state:e.state,summary:{kind:Oa(e.toolLabel),target:e.fileLabel??null,detail:null}}},e.toolCallRef)),a&&(0,Q.jsx)(Va,{code:a,locale:s}),r&&(0,Q.jsx)(R,{className:i?`streaming-answer`:void 0,children:i?(0,Q.jsx)(La,{text:r}):(0,Q.jsx)(Fa,{children:r})}),i&&o]})]})}function Ya(e){let t=(0,$.useRef)(null),[n,r]=(0,$.useState)(null);return(0,$.useEffect)(()=>{if(!e){t.current=null,r(null);return}t.current??={at:Date.now(),from:e.length},r(Ii(e.length-t.current.from,Date.now()-t.current.at))},[e]),n}function Xa({live:e,locale:t,onOpenActivity:n}){let[r,i]=(0,$.useState)(()=>Date.now());(0,$.useEffect)(()=>{let e=window.setInterval(()=>i(Date.now()),1e4);return()=>window.clearInterval(e)},[]);let o=Oi(e,t,r),s=Ya(e.assistant??``),c=e.activities.some(e=>e.state===`running`)||!!e.assistant;return(0,Q.jsxs)(P,{direction:`row`,spacing:1.25,role:`status`,"aria-live":`polite`,sx:{alignItems:`center`,color:`text.secondary`,py:.5,minHeight:36},children:[(0,Q.jsx)(R,{sx:{width:18,display:`grid`,placeItems:`center`,flexShrink:0},children:c?(0,Q.jsx)(R,{sx:{width:6,height:6,borderRadius:`50%`,bgcolor:`primary.main`,opacity:.7}}):(0,Q.jsx)(ee,{size:16,thickness:4.5})}),(0,Q.jsxs)(R,{sx:{minWidth:0},children:[(0,Q.jsx)(S,{variant:`body2`,sx:{fontWeight:600},children:o.label}),(0,Q.jsxs)(S,{variant:`caption`,color:`text.disabled`,children:[o.detail,s!==null&&` · ≈ ${s} tok/s`]})]}),n&&(0,Q.jsx)(a,{size:`small`,variant:`text`,onClick:n,sx:{ml:`auto !important`},children:X(t,`Xem Activity`,`View Activity`)})]})}var Za=new Map,Qa=96,$a=()=>document.documentElement.scrollHeight-window.innerHeight,eo=()=>$a()-window.scrollY<=Qa,to=1500,no=110;function ro(e,t){let n=(0,$.useRef)(null),r=(0,$.useRef)(!1),i=(0,$.useRef)(!0),a=(0,$.useRef)(null),o=(0,$.useRef)(!1),s=()=>{a.current=null,n.current&&(n.current.style.overflowAnchor=``)},c=()=>{let e=a.current;if(!e)return;if(Date.now()>e.until){s();return}let t=n.current?.querySelector(`[data-turn="${CSS.escape(e.key)}"]`);if(!t)return;let r=t.getBoundingClientRect().top-e.top;Math.abs(r)>=1&&window.scrollBy(0,r)};return(0,$.useLayoutEffect)(()=>{if(!t||r.current)return;r.current=!0;let n=Za.get(e)??`end`;i.current=n===`end`,window.scrollTo(0,n===`end`?$a():Math.min(n,$a()))},[t,e]),(0,$.useEffect)(()=>{let t=window.scrollY,s=()=>{if(!r.current)return;window.scrollY<t-2&&(o.current=!0),t=window.scrollY;let s=a.current;if(s){let e=n.current?.querySelector(`[data-turn="${CSS.escape(s.key)}"]`);e&&(s.top=e.getBoundingClientRect().top)}i.current=eo(),Za.set(e,i.current?`end`:window.scrollY)};window.addEventListener(`scroll`,s,{passive:!0});let l=n.current,u=typeof ResizeObserver>`u`||!l?null:new ResizeObserver(()=>{r.current&&(a.current?c():i.current&&window.scrollTo(0,$a()))});return l&&u?.observe(l),()=>{window.removeEventListener(`scroll`,s),u?.disconnect()}},[e]),{content:n,hold:()=>{if(window.setTimeout(c,1550),a.current){a.current.until=Date.now()+to;return}let e=[...n.current?.querySelectorAll(`[data-turn]`)??[]],t=e.find(e=>e.getBoundingClientRect().bottom>no)??e[0];!t?.dataset.turn||!n.current||(n.current.style.overflowAnchor=`none`,a.current={key:t.dataset.turn,top:t.getBoundingClientRect().top,until:Date.now()+to})},reapply:c,scrolledUp:o,follow:()=>{s(),i.current=!0,o.current=!1}}}function io({turns:e=2,label:t}){return(0,Q.jsx)(P,{spacing:3,role:`status`,"aria-label":t,sx:{py:1},children:Array.from({length:e},(e,t)=>(0,Q.jsxs)(P,{spacing:1.5,children:[(0,Q.jsx)(ni,{variant:`rounded`,animation:`wave`,sx:{alignSelf:`flex-end`,width:`46%`,height:44,borderRadius:2}}),(0,Q.jsxs)(P,{direction:`row`,spacing:1.5,children:[(0,Q.jsx)(ni,{variant:`rounded`,width:26,height:26}),(0,Q.jsxs)(P,{spacing:1,sx:{flex:1},children:[(0,Q.jsx)(ni,{width:`30%`}),(0,Q.jsx)(ni,{width:`92%`}),(0,Q.jsx)(ni,{width:`78%`})]})]})]},t))})}function ao({sessionRef:e,sessionRevision:t,live:n,approvals:r,locale:i,onOpenActivity:o,onContinue:s,reload:c=0}){let[l,u]=(0,$.useState)(),[d,f]=(0,$.useState)(!0),[p,m]=(0,$.useState)(!1),[h,g]=(0,$.useState)(0),[_,y]=(0,$.useState)(!1),[b,x]=(0,$.useState)(!1),[w,T]=(0,$.useState)(!1),[E,D]=(0,$.useState)(null);(0,$.useEffect)(()=>{Na()},[]);let O=on(e,t,n),{completionKey:k,user:A,assistant:j,operationRef:M,messageRequestId:N,startedAt:F}=O;(0,$.useEffect)(()=>{let t=new AbortController;f(!0),x(!1),D(null);let n=window.setTimeout(()=>{Promise.all([Ue(e,null,50,t.signal),Na().catch(()=>void 0)]).then(([e])=>{u(e),y(!1),k&&Yt(e.items,A,j,{operationRef:M,messageRequestId:N,startedAt:F})&&D(k)}).catch(()=>{t.signal.aborted||x(!0)}).finally(()=>{t.signal.aborted||f(!1)})},k?100:0);return()=>{window.clearTimeout(n),t.abort()}},[O.key,c,h]);let I=l?.state===`ready`?l.items:[],L=(0,$.useMemo)(()=>Ni(I),[I]),z=(0,$.useMemo)(()=>!!(n?.user&&tn(I,n.user,{operationRef:n.operationRef,messageRequestId:n.messageRequestId,startedAt:n.startedAt})),[I,n?.user,n?.operationRef,n?.messageRequestId,n?.startedAt]),ee=!!(n&&!z&&(!n.complete||E!==k)),B=!!(n&&z&&!n.complete&&!n.error),te=(0,$.useMemo)(()=>!!(n?.user&&rn(I,n.user,{operationRef:n.operationRef,messageRequestId:n.messageRequestId,startedAt:n.startedAt})),[I,n?.user,n?.operationRef,n?.messageRequestId,n?.startedAt]),{content:ne,hold:re,reapply:V,scrolledUp:H,follow:ie}=ro(e,!!l||b),U=(0,$.useRef)(!1),ae=(0,$.useRef)(l);ae.current=l;let oe=async()=>{let t=ae.current,n=t?.page.nextBeforeCursor;if(!(!t?.page.hasOlder||!n||U.current)){H.current=!1,U.current=!0,re(),m(!0),T(!1);try{let r=await Ue(e,n,t.page.limit);re();let i=ae.current;if(!i){ae.current=r,u(r);return}let a=ln(i.items,r.items);new Set([...i.items,...r.items].map(e=>e.messageRef)).size>a.length&&y(!0);let o={...i,items:a,page:r.page};ae.current=o,u(o)}catch{T(!0)}finally{U.current=!1,m(!1)}}};(0,$.useLayoutEffect)(()=>{V()},[I.length,p]);let W=(0,$.useRef)(null),G=(0,$.useRef)(()=>{}),ce=!!l?.page.hasOlder;G.current=()=>{if(!H.current||w||U.current)return;let e=W.current?.getBoundingClientRect();e&&e.bottom>=-900&&e.top<=window.innerHeight&&oe()},(0,$.useEffect)(()=>{let e=W.current;if(!e||!ce)return;let t=0,n=()=>{t||=window.requestAnimationFrame(()=>{t=0,G.current()})},r=typeof IntersectionObserver>`u`?null:new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&n()},{rootMargin:`900px 0px 0px 0px`});return r?.observe(e),window.addEventListener(`scroll`,n,{passive:!0}),()=>{r?.disconnect(),window.removeEventListener(`scroll`,n),window.cancelAnimationFrame(t)}},[e,ce]);let le=n?Zt(n.assistant||``):null;return(0,Q.jsx)(la,{sessionRef:e,refresh:`${O.key}:${c}`,running:!!n&&!n.complete&&!n.error,locale:i,children:(0,Q.jsxs)(P,{ref:ne,spacing:3,children:[l?.page.hasOlder&&(0,Q.jsx)(R,{ref:W,"data-history-sentinel":!0,children:p?(0,Q.jsx)(io,{label:X(i,`Đang tải tin cũ hơn`,`Loading older messages`)}):(0,Q.jsx)(R,{sx:{textAlign:`center`},children:(0,Q.jsx)(a,{size:`small`,variant:`text`,color:`inherit`,startIcon:(0,Q.jsx)(se,{}),onClick:()=>void oe(),sx:{color:w?`warning.main`:`text.secondary`},children:w?X(i,`Chưa tải được tin cũ · thử lại`,`Older messages did not load · retry`):X(i,`Tải tin cũ hơn`,`Load older messages`)})})}),l?.state===`ready`&&!l.page.hasOlder&&L.length>3&&(0,Q.jsx)(S,{variant:`caption`,color:`text.disabled`,sx:{textAlign:`center`,display:`block`},children:X(i,`Đầu cuộc trò chuyện`,`Start of the conversation`)}),d&&!l&&(0,Q.jsx)(io,{turns:3,label:X(i,`Đang tải cuộc trò chuyện`,`Loading the conversation`)}),b&&!l&&(0,Q.jsx)(v,{severity:`warning`,icon:(0,Q.jsx)(C,{}),children:X(i,`Chưa tải được lịch sử cuộc trò chuyện. Thử lại bằng nút làm mới.`,`Session history could not be loaded. You can retry with Refresh.`)}),L.map((t,n)=>(0,Q.jsx)(R,{"data-turn":t.key,children:(0,Q.jsx)(Ka,{turn:t,sessionRef:e,locale:i,onContinue:n===L.length-1&&!ee&&!B&&!r?.pending.length?s:void 0})},t.key)),_&&(0,Q.jsx)(R,{sx:{textAlign:`center`},children:(0,Q.jsx)(a,{size:`small`,variant:`outlined`,onClick:()=>{ie(),g(e=>e+1)},children:X(i,`Tin mới hơn đã ẩn · về tin mới nhất`,`Newer messages are hidden · back to the newest`)})}),ee&&n&&(0,Q.jsx)(Ja,{user:n.user&&!te?n.user:null,attachments:n.attachments,activities:n.activities,assistant:n.error?null:le,running:!n.complete&&!n.error,failure:n.complete&&n.error&&za.has(n.error)?n.error:null,locale:i,status:(0,Q.jsx)(Xa,{live:n,locale:i,onOpenActivity:o})}),B&&n&&(0,Q.jsx)(Ua,{children:(0,Q.jsx)(Xa,{live:n,locale:i,onOpenActivity:o})}),(0,Q.jsx)(ci,{sessionRef:e,waiting:xt(n),approvalRefs:r?.pending.map(e=>e.approvalRef)??[]})]})})}var oo=9e3,so=4,co={done:[`Xong`,`Done`,`Agent đã trả lời xong.`,`The agent finished its answer.`],failed:[`Lượt bị lỗi`,`Turn failed`,`Mở để xem lỗi và gửi “tiếp tục”.`,`Open it to see the error and continue.`],stopped:[`Đã dừng`,`Stopped`,`Lượt làm việc đã dừng giữa chừng.`,`The turn stopped midway.`],question:[`Cần bạn trả lời`,`Needs your answer`,`Main agent đang chờ bạn chọn phương án.`,`The main agent is waiting for your choice.`],approval:[`Cần bạn duyệt`,`Needs your approval`,`Main agent xin chạy một lệnh và đang chờ bạn duyệt.`,`The main agent asked to run a command and is waiting.`]},lo={done:`success`,failed:`error`,stopped:`neutral`,question:`warning`,approval:`warning`};function uo({sessions:e,live:t,selectedRef:n,onOpen:r,locale:i}){let a=(0,$.useRef)(null),[o,s]=(0,$.useState)([]),[c,l]=(0,$.useState)(()=>new Set);(0,$.useEffect)(()=>{let r=yt(e,t);if(a.current){let i=document.visibilityState===`visible`,o=Tt(a.current,r,e,t).filter(e=>!(i&&e.sessionRef===n));if(o.length){s(e=>[...o,...e.filter(e=>!o.some(t=>t.sessionRef===e.sessionRef))].slice(0,12));let e=o.filter(e=>[`done`,`failed`,`stopped`].includes(e.kind)).map(e=>e.sessionRef);e.length&&l(t=>new Set([...t,...e]))}}a.current=r,s(e=>{let t=e.filter(e=>![`question`,`approval`].includes(e.kind)||r[e.sessionRef]?.need===e.kind);return t.length===e.length?e:t})},[e,t,n]),(0,$.useEffect)(()=>{n&&(l(e=>{if(!e.has(n))return e;let t=new Set(e);return t.delete(n),t}),s(e=>e.filter(e=>e.sessionRef!==n)))},[n]);let u=e.filter(e=>!e.archived&&zt(e,t[e.sessionRef])).length;(0,$.useEffect)(()=>{let e=document.title.replace(/^\(\d+\) /,``);document.title=u?`(${u}) ${e}`:e},[u]);let d=e=>s(t=>t.filter(t=>t.id!==e));return{unseen:c,view:(0,Q.jsx)(fo,{toasts:o.slice(0,so),more:Math.max(0,o.length-so),locale:i,onClose:d,onOpen:e=>{d(e.id),r(e.sessionRef)}})}}function fo({toasts:e,more:t,locale:n,onClose:r,onOpen:i}){return(0,Q.jsxs)(`section`,{className:`attention-toasts`,"aria-label":X(n,`Thông báo cuộc trò chuyện`,`Chat notifications`),"aria-live":`polite`,children:[e.map(e=>(0,Q.jsx)(po,{event:e,locale:n,onClose:()=>r(e.id),onOpen:()=>i(e)},e.id)),t>0&&(0,Q.jsx)(`p`,{className:`attention-more`,children:X(n,`và ${t} thông báo khác`,`and ${t} more`)})]})}function po({event:e,locale:t,onClose:n,onOpen:r}){let i=e.kind===`question`||e.kind===`approval`,[a,o,s,c]=co[e.kind];return(0,$.useEffect)(()=>{if(i)return;let e=window.setTimeout(n,oo);return()=>window.clearTimeout(e)},[i]),(0,Q.jsxs)(`article`,{className:`attention-toast tone-${lo[e.kind]}`,role:i?`alert`:`status`,children:[(0,Q.jsx)(`span`,{className:`attention-toast-mark`,"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{className:`attention-toast-body`,children:[(0,Q.jsxs)(`strong`,{children:[X(t,a,o),` · `,(0,Q.jsx)(`span`,{className:`attention-toast-title`,children:e.title})]}),(0,Q.jsx)(`small`,{children:X(t,s,c)})]}),(0,Q.jsxs)(`div`,{className:`attention-toast-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`attention-open`,onClick:r,children:X(t,`Mở`,`Open`)}),(0,Q.jsx)(`button`,{type:`button`,className:`attention-close`,"aria-label":X(t,`Đóng thông báo`,`Close notification`),onClick:n,children:`×`})]})]})}var mo=q((0,Q.jsx)(`path`,{d:`M18 19H6c-.55 0-1-.45-1-1V6c0-.55.45-1 1-1h12c.55 0 1 .45 1 1v12c0 .55-.45 1-1 1m1-16H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2`}),`CheckBoxOutlineBlankRounded`),ho=q((0,Q.jsx)(`path`,{d:`M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m-8.29 13.29c-.39.39-1.02.39-1.41 0L5.71 12.7a.996.996 0 0 1 0-1.41c.39-.39 1.02-.39 1.41 0L10 14.17l6.88-6.88c.39-.39 1.02-.39 1.41 0s.39 1.02 0 1.41z`}),`CheckBoxRounded`),go=q((0,Q.jsx)(`path`,{d:`m10.8 15.9 4.67-3.5c.27-.2.27-.6 0-.8L10.8 8.1c-.33-.25-.8-.01-.8.4v7c0 .41.47.65.8.4M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8`}),`PlayCircleOutlineRounded`),_o=q((0,Q.jsx)(`path`,{d:`M7 12c0 .55.45 1 1 1h8c.55 0 1-.45 1-1s-.45-1-1-1H8c-.55 0-1 .45-1 1m5-10C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8`}),`RemoveCircleOutlineRounded`);function vo(e){return N(`MuiLinearProgress`,e)}we(`MuiLinearProgress`,[`root`,`colorPrimary`,`colorSecondary`,`determinate`,`indeterminate`,`buffer`,`query`,`dashed`,`bar`,`bar1`,`bar2`]);var yo=4,bo={},xo=r`
47
49
  0% {
48
50
  left: -35%;
49
51
  right: 100%;
@@ -58,9 +60,9 @@ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$t as t,A as n,An as r
58
60
  left: 100%;
59
61
  right: -90%;
60
62
  }
61
- `,yo=typeof vo==`string`?null:ue`
62
- animation: ${vo} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite;
63
- `,bo=r`
63
+ `,So=typeof xo==`string`?null:ue`
64
+ animation: ${xo} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite;
65
+ `,Co=r`
64
66
  0% {
65
67
  left: -200%;
66
68
  right: 100%;
@@ -75,9 +77,9 @@ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$t as t,A as n,An as r
75
77
  left: 107%;
76
78
  right: -8%;
77
79
  }
78
- `,xo=typeof bo==`string`?null:ue`
79
- animation: ${bo} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite;
80
- `,So=r`
80
+ `,wo=typeof Co==`string`?null:ue`
81
+ animation: ${Co} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite;
82
+ `,To=r`
81
83
  0% {
82
84
  opacity: 1;
83
85
  background-position: 0 -23px;
@@ -92,6 +94,6 @@ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$t as t,A as n,An as r
92
94
  opacity: 1;
93
95
  background-position: -200px -23px;
94
96
  }
95
- `,Co=typeof So==`string`?null:ue`
96
- animation: ${So} 3s infinite linear;
97
- `,wo=e=>{let{classes:t,variant:n,color:r}=e,i={root:[`root`,`color${W(r)}`,n],dashed:[`dashed`],bar1:[`bar`,`bar1`],bar2:[`bar`,`bar2`,n===`buffer`&&`color${W(r)}`]};return K(i,ho,t)},To=(e,t)=>e.vars?e.vars.palette.LinearProgress[`${t}Bg`]:e.palette.mode===`light`?e.lighten(e.palette[t].main,.62):e.darken(e.palette[t].main,.5),Eo=H(`span`,{name:`MuiLinearProgress`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,t[`color${W(n.color)}`],t[n.variant]]}})(V(({theme:e})=>({position:`relative`,overflow:`hidden`,display:`block`,height:4,zIndex:0,"@media print":{colorAdjust:`exact`},variants:[...Object.entries(e.palette).filter(B()).map(([t])=>({props:{color:t},style:{backgroundColor:To(e,t)}})),{props:({ownerState:e})=>e.color===`inherit`&&e.variant!==`buffer`,style:{"&::before":{content:`""`,position:`absolute`,left:0,top:0,right:0,bottom:0,backgroundColor:`currentColor`,opacity:.3}}},{props:{variant:`buffer`},style:{backgroundColor:`transparent`}},{props:{variant:`query`},style:{transform:`rotate(180deg)`}}]}))),Do=H(`span`,{name:`MuiLinearProgress`,slot:`Dashed`})(V(({theme:e})=>({position:`absolute`,marginTop:0,height:`100%`,width:`100%`,backgroundSize:`10px 10px`,backgroundPosition:`0 -23px`,variants:[{props:{color:`inherit`},style:{opacity:.3,backgroundImage:`radial-gradient(currentColor 0%, currentColor 16%, transparent 42%)`}},...Object.entries(e.palette).filter(B()).map(([t])=>{let n=To(e,t);return{props:{color:t},style:{backgroundImage:`radial-gradient(${n} 0%, ${n} 16%, transparent 42%)`}}})]})),Co||{animation:`${So} 3s infinite linear`},V(({theme:e})=>t(e,{animation:`none`})||_o)),Oo=H(`span`,{name:`MuiLinearProgress`,slot:`Bar1`,overridesResolver:(e,t)=>[t.bar,t.bar1]})(V(({theme:e})=>{let n=t(e,{animation:`none`,left:`30%`,right:`auto`,width:`40%`});return{width:`100%`,position:`absolute`,left:0,bottom:0,top:0,...Y(e,`transform`,{duration:`0.2s`,easing:`linear`}),transformOrigin:`left`,variants:[{props:{color:`inherit`},style:{backgroundColor:`currentColor`}},...Object.entries(e.palette).filter(B()).map(([t])=>({props:{color:t},style:{backgroundColor:(e.vars||e).palette[t].main}})),{props:{variant:`determinate`},style:{...Y(e,`transform`,{duration:`.${go}s`,easing:`linear`})}},{props:{variant:`buffer`},style:{zIndex:1,...Y(e,`transform`,{duration:`.${go}s`,easing:`linear`})}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:{width:`auto`}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:yo||{animation:`${vo} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite`}},...n?[{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:n}]:[]]}})),ko=H(`span`,{name:`MuiLinearProgress`,slot:`Bar2`,overridesResolver:(e,t)=>[t.bar,t.bar2]})(V(({theme:e})=>{let n=t(e,{animation:`none`,display:`none`});return{width:`100%`,position:`absolute`,left:0,bottom:0,top:0,...Y(e,`transform`,{duration:`0.2s`,easing:`linear`}),transformOrigin:`left`,variants:[...Object.entries(e.palette).filter(B()).map(([t])=>({props:{color:t},style:{"--LinearProgressBar2-barColor":(e.vars||e).palette[t].main}})),{props:({ownerState:e})=>e.variant!==`buffer`&&e.color!==`inherit`,style:{backgroundColor:`var(--LinearProgressBar2-barColor, currentColor)`}},{props:({ownerState:e})=>e.variant!==`buffer`&&e.color===`inherit`,style:{backgroundColor:`currentColor`}},{props:{color:`inherit`},style:{opacity:.3}},...Object.entries(e.palette).filter(B()).map(([t])=>({props:{color:t,variant:`buffer`},style:{backgroundColor:To(e,t),...Y(e,`transform`,{duration:`.${go}s`,easing:`linear`})}})),{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:{width:`auto`}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:xo||{animation:`${bo} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite`}},...n?[{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:n}]:[]]}})),Ao=$.forwardRef(function(e,t){let n=ge({props:e,name:`MuiLinearProgress`}),{className:r,color:i=`primary`,max:a,min:s,value:c,valueBuffer:l,variant:u=`indeterminate`,...d}=n,f={...n,color:i,variant:u},p=s??0,m=a??100,h=wo(f),g=Se(),_={},v={bar1:{},bar2:{}};if((u===`determinate`||u===`buffer`)&&c!==void 0){let e=m-p,t=(c-p)/e*100-100;g&&(t=-t),v.bar1.transform=e>0?`translateX(${t}%)`:`translateX(-100%)`,_[`aria-valuenow`]=c,_[`aria-valuemin`]=p,_[`aria-valuemax`]=m}if(u===`buffer`&&l!==void 0){let e=m-p,t=(l-p)/e*100-100;g&&(t=-t),v.bar2.transform=e>0?`translateX(${t}%)`:`translateX(-100%)`}return(0,Q.jsxs)(Eo,{className:o(h.root,r),ownerState:f,role:`progressbar`,..._,ref:t,...d,children:[u===`buffer`?(0,Q.jsx)(Do,{className:h.dashed,ownerState:f}):null,(0,Q.jsx)(Oo,{className:h.bar1,ownerState:f,style:v.bar1}),u===`determinate`?null:(0,Q.jsx)(ko,{className:h.bar2,ownerState:f,style:v.bar2})]})}),jo=`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,Mo={A:`success`,M:`warning`,D:`error`,R:`info`,C:`info`,U:`success`};function No({title:e,action:t,children:n}){return(0,Q.jsxs)(R,{component:`section`,sx:{px:2,py:1.75,borderBottom:1,borderColor:`divider`},children:[(0,Q.jsxs)(P,{direction:`row`,sx:{alignItems:`center`,justifyContent:`space-between`,mb:1},children:[(0,Q.jsx)(S,{variant:`caption`,color:`text.secondary`,sx:{fontWeight:650,textTransform:`uppercase`,letterSpacing:`.06em`},children:e}),t]}),n]})}var Po=3e3;function Fo({session:e,snapshot:t,live:n,locale:r,onOpenReview:i,onClose:o}){let[s,c]=(0,$.useState)(),[l,u]=(0,$.useState)(!1),d=!!(n&&!n.complete);(0,$.useEffect)(()=>{let t=new AbortController;u(!1);let n,r=()=>void Ke(e.sessionRef,`working-tree`,t.signal).then(e=>{t.signal.aborted||(c(e),u(!1))}).catch(()=>{!t.signal.aborted&&!d&&u(!0)}).finally(()=>{d&&!t.signal.aborted&&(n=window.setTimeout(r,Po))});return n=window.setTimeout(r,250),()=>{window.clearTimeout(n),t.abort()}},[e.sessionRef,e.sessionRevision,d]),(0,$.useEffect)(()=>{c(void 0)},[e.sessionRef]);let f=s?.files??[],p=f.reduce((e,t)=>e+(t.stats?.additions??0),0),m=f.reduce((e,t)=>e+(t.stats?.deletions??0),0),g=t?.usage.context,_=g?.state===`known`,v=_?g.percent:e.contextUsage.ratio===null?null:e.contextUsage.ratio*100,y=_?g.contextWindow:e.contextUsage.contextWindow,b=_?g.tokens:e.contextUsage.usedTokens,x=e.managedHelpers?.maximum===0?void 0:e.managedHelpers,C=e.managedPlan,w=e.managedProcess,T=C?.steps.filter(e=>e.status===`completed`).length??0,E=(n?.activities??[]).filter(e=>Da(e.toolLabel)===`subagent`);return(0,Q.jsxs)(R,{role:`region`,sx:{height:`100%`,overflowY:`auto`,bgcolor:`background.paper`},"aria-label":X(r,`Thay đổi và ngữ cảnh`,`Changes and context`),children:[(0,Q.jsxs)(P,{direction:`row`,sx:{alignItems:`center`,gap:1,px:2,minHeight:52,borderBottom:1,borderColor:`divider`},children:[(0,Q.jsx)(S,{sx:{fontWeight:600,flex:1},children:X(r,`Workspace`,`Workspace`)}),o&&(0,Q.jsx)(L,{size:`small`,"aria-label":X(r,`Đóng khung bên`,`Close side panel`),onClick:o,children:(0,Q.jsx)(h,{fontSize:`small`})})]}),(0,Q.jsxs)(No,{title:s?X(r,`Thay đổi · ${f.length} file`,`Changes · ${f.length} files`):X(r,`Thay đổi`,`Changes`),action:f.length>0?(0,Q.jsx)(pe,{title:X(r,`Xem diff đầy đủ, stage hoặc hoàn tác`,`Full diff, stage or revert`),children:(0,Q.jsx)(a,{size:`small`,startIcon:(0,Q.jsx)(O,{fontSize:`small`}),onClick:i,children:X(r,`Review`,`Review`)})}):void 0,children:[(p>0||m>0)&&(0,Q.jsxs)(P,{direction:`row`,sx:{alignItems:`center`,gap:.75,mb:1,color:`text.secondary`},children:[(0,Q.jsx)(_a,{sx:{fontSize:15}}),(0,Q.jsx)(S,{variant:`caption`,children:X(r,`Chưa commit`,`Uncommitted`)}),(0,Q.jsxs)(S,{variant:`caption`,sx:{fontFamily:jo,ml:`auto`},children:[(0,Q.jsxs)(R,{component:`span`,sx:Et(`success`),children:[`+`,p]}),` `,(0,Q.jsxs)(R,{component:`span`,sx:Et(`error`),children:[`−`,m]})]})]}),d&&(0,Q.jsx)(S,{variant:`caption`,color:`text.secondary`,role:`status`,sx:{display:`block`,mb:.75},children:X(r,`Agent đang chạy · cập nhật trực tiếp. Thấy sai thì bấm Dừng.`,`The agent is running · updating live. Stop it if it goes wrong.`)}),s===void 0&&!l&&(0,Q.jsx)(Ao,{sx:{borderRadius:1}}),(l||s?.availability.state===`unavailable`)&&(0,Q.jsx)(S,{variant:`body2`,color:`text.secondary`,children:X(r,`Chưa đọc được thay đổi (thư mục có thể không phải git repo).`,`Changes are unavailable (the folder may not be a git repository).`)}),s&&s.availability.state!==`unavailable`&&f.length===0&&(0,Q.jsx)(S,{variant:`body2`,color:`text.secondary`,children:X(r,`Chưa có thay đổi nào chưa commit.`,`No uncommitted changes.`)}),(0,Q.jsx)(P,{spacing:.25,children:f.slice(0,200).map(e=>(0,Q.jsxs)(P,{direction:`row`,sx:{alignItems:`center`,gap:1,py:.4},children:[(0,Q.jsx)(S,{variant:`caption`,sx:{fontFamily:jo,fontWeight:650,width:12,...Mo[e.status]?Et(Mo[e.status]):{color:`text.secondary`}},children:e.status}),(0,Q.jsx)(S,{variant:`body2`,noWrap:!0,title:e.path,sx:{fontFamily:jo,fontSize:12.5,flex:1,minWidth:0},children:e.path}),(0,Q.jsxs)(S,{variant:`caption`,sx:{fontFamily:jo,flexShrink:0},children:[(e.stats?.additions??0)>0&&(0,Q.jsxs)(R,{component:`span`,sx:Et(`success`),children:[`+`,e.stats.additions,` `]}),(e.stats?.deletions??0)>0&&(0,Q.jsxs)(R,{component:`span`,sx:Et(`error`),children:[`−`,e.stats.deletions]})]})]},e.fileRef))})]}),(C||w)&&(0,Q.jsxs)(No,{title:C?X(r,`Plan · ${T}/${C.steps.length}`,`Plan · ${T}/${C.steps.length}`):X(r,`Tiến trình`,`Process`),children:[C&&(0,Q.jsx)(P,{component:`ol`,spacing:.25,sx:{m:0,p:0,listStyle:`none`},"aria-label":X(r,`Plan của agent`,`Agent plan`),children:C.steps.map((e,t)=>{let n=e.status===`completed`?fo:e.status===`in_progress`?po:e.status===`deferred`?mo:uo;return(0,Q.jsxs)(P,{component:`li`,direction:`row`,sx:{alignItems:`flex-start`,gap:.75,py:.25},"aria-label":`${e.step}: ${e.status===`completed`?X(r,`xong`,`done`):e.status===`in_progress`?X(r,`đang làm`,`in progress`):e.status===`deferred`?X(r,`để sau`,`left for later`):X(r,`chưa làm`,`pending`)}`,children:[(0,Q.jsx)(n,{sx:{fontSize:16,mt:.2,color:e.status===`in_progress`?`primary.main`:`text.secondary`}}),(0,Q.jsx)(S,{variant:`body2`,sx:{flex:1,minWidth:0,overflowWrap:`anywhere`,...e.status===`completed`?{color:`text.secondary`,textDecoration:`line-through`}:e.status===`deferred`?{color:`text.disabled`,fontStyle:`italic`}:{},...e.status===`in_progress`?{fontWeight:600}:{}},children:e.step})]},t)})}),w&&w.outcome!==`no_change`&&(0,Q.jsxs)(S,{variant:`body2`,role:`status`,sx:{mt:+!!C,...Et(jt(w))},children:[X(r,`Lượt sửa code gần nhất: `,`Last code-changing turn: `),Nt(w,r)]})]}),(0,Q.jsxs)(No,{title:X(r,`Ngữ cảnh`,`Context`),children:[(0,Q.jsxs)(P,{direction:`row`,sx:{justifyContent:`space-between`,mb:.75},children:[(0,Q.jsx)(S,{variant:`body2`,children:v==null?`—`:`${Math.round(v)}%`}),(0,Q.jsxs)(S,{variant:`caption`,color:`text.secondary`,children:[b?Ii(b):`—`,y?` / ${Ii(y)}`:``]})]}),(0,Q.jsx)(Ao,{variant:`determinate`,value:Math.min(100,Math.max(0,v??0)),sx:{height:6,borderRadius:1},color:(v??0)>85?`warning`:`primary`,"aria-label":X(r,`Mức dùng ngữ cảnh`,`Context usage`)})]}),(x||E.length>0)&&(0,Q.jsxs)(No,{title:`Subagent`,children:[x&&(0,Q.jsx)(S,{variant:`body2`,color:`text.secondary`,sx:{mb:E.length?.75:0},children:X(r,`${x.active??0}/${x.maximum} đang chạy`,`${x.active??0}/${x.maximum} running`)}),E.map(e=>(0,Q.jsxs)(P,{direction:`row`,sx:{alignItems:`center`,gap:.75,py:.25},children:[(0,Q.jsx)(ma,{sx:{fontSize:15,color:`text.secondary`}}),(0,Q.jsx)(S,{variant:`body2`,sx:{flex:1},children:e.fileLabel??`subagent`}),(0,Q.jsx)(S,{variant:`caption`,color:e.state===`failed`?`error`:`text.secondary`,children:e.state===`running`?X(r,`đang chạy`,`running`):e.state===`failed`?X(r,`lỗi`,`failed`):X(r,`xong`,`done`)})]},e.toolCallRef))]})]})}function Io(e){let{locale:t,actions:n}=e,r=X(t,`Lệnh`,`Commands`),i=At(),a=[];e.canCreate&&a.push({id:`new-chat`,group:r,label:X(t,`Cuộc trò chuyện mới`,`New chat`),hint:`${i} ⇧ O`,keywords:`new create tạo`,run:n.newChat}),e.update.available&&e.update.latest&&a.push({id:`update-now`,group:r,label:X(t,`Cập nhật Piagent ${e.update.latest}`,`Update Piagent ${e.update.latest}`),keywords:`update upgrade nâng cấp phiên bản version`,run:()=>n.settings(`updates`)}),a.push({id:`check-updates`,group:r,label:X(t,`Kiểm tra cập nhật`,`Check for updates`),keywords:`update version phiên bản pi piagent`,run:n.checkUpdates}),e.hasSelection&&a.push({id:`toggle-panel`,group:r,label:X(t,`Bật/tắt khung Workspace`,`Toggle the Workspace panel`),keywords:`panel sidebar changes plan context`,run:n.togglePanel},{id:`open-changes`,group:r,label:X(t,`Mở Source Changes`,`Open Source Changes`),keywords:`diff review thay đổi git`,run:n.openChanges}),a.push({id:`theme`,group:r,label:e.colorMode===`dark`?X(t,`Chuyển sang chủ đề sáng`,`Switch to the light theme`):X(t,`Chuyển sang chủ đề tối`,`Switch to the dark theme`),keywords:`theme chủ đề dark light sáng tối`,run:()=>n.setColorMode(e.colorMode===`dark`?`light`:`dark`)},{id:`language`,group:r,label:t===`vi`?`Switch the interface to English`:`Chuyển giao diện sang tiếng Việt`,keywords:`language ngôn ngữ english tiếng việt`,run:()=>n.setLocale(t===`vi`?`en`:`vi`)},{id:`refresh`,group:r,label:X(t,`Làm mới`,`Refresh`),keywords:`reload tải lại`,run:n.refresh});let o=n.setTheme,s=X(t,`Chủ đề màu`,`Color theme`);if(o)for(let t of ke)a.push({id:`theme-${t.id}`,group:s,label:`${s}: ${t.label}`,hint:t.id===e.themeId?`✓`:void 0,keywords:`theme chủ đề màu color ${t.mode}`,run:()=>o(t.id)});let c=X(t,`Cài đặt`,`Settings`);for(let e of Pt(t))a.push({id:`settings-${e.id}`,group:c,label:`${c}: ${e.label}`,hint:e.id===`general`?`${i} ,`:void 0,keywords:e.keywords,run:()=>n.settings(e.id)});let l=X(t,`Cuộc trò chuyện`,`Conversations`);for(let t of e.sessions)a.push({id:`session-${t.sessionRef}`,group:l,label:t.title,hint:t.projectLabel,keywords:t.projectLabel,run:()=>n.openSession(t.sessionRef)});return a}var Lo=`piagent-gateway-event-cursor-v1`,Ro=3e4,zo=12e4,Bo=4001,Vo=class extends Error{reasonCode;constructor(e){super(e),this.name=`SessionSendRejectedError`,this.reasonCode=e}};function Ho(e,t){if(!e)return null;try{let n=JSON.parse(e);return n.gatewayInstanceRef===t&&Number.isSafeInteger(n.sequence)&&Number(n.sequence)>=0?Number(n.sequence):null}catch{return null}}function Uo(e,t){if(t!==null)try{window.sessionStorage.setItem(Lo,JSON.stringify({gatewayInstanceRef:e,sequence:t}))}catch{}}function Wo(e){return`${e}_${crypto.randomUUID().replaceAll(`-`,``)}`}function Go(e){return e.phase===`rejected`&&e.resultCode===`stale-revision`&&e.error?.code===`session-revision-stale`}var Ko=(0,$.lazy)(()=>Me(()=>import(`./SettingsPage-Ca-qRSZa.js`).then(e=>({default:e.SettingsPage})),__vite__mapDeps([17,1,2,3,12,5,18,19]))),qo=(0,$.lazy)(()=>Me(()=>import(`./SessionInspectorDrawer-CpVzaf_G.js`).then(e=>({default:e.SessionInspectorDrawer})),__vite__mapDeps([20,1,2,3,7,8]))),Jo=272,Yo=52,Xo=320,Zo=`min(44vw, 860px)`,Qo=`piagent-webui-workspace-panel`;function $o({session:e,live:t,locale:n}){let r=Ft(e,t),[i,a]=r===`running`?[X(n,`Đang chạy`,`Running`),`primary`]:r===`elsewhere`?[X(n,`Đang chạy ở nơi khác`,`Running elsewhere`),`info`]:r===`attention`?zt(e,t)===`question`?[X(n,`Cần bạn trả lời`,`Needs your answer`),`warning`]:[X(n,`Cần duyệt`,`Needs approval`),`warning`]:r===`recovery`?[X(n,`Cần khôi phục`,`Recovery needed`),`error`]:r===`failed`?[X(n,`Lượt cuối lỗi`,`Last turn failed`),`error`]:[X(n,`Sẵn sàng`,`Ready`),`default`],o=a==="default"?`text.disabled`:a===`info`?`info.main`:`${a}.main`;return(0,Q.jsxs)(R,{role:`status`,sx:{display:`inline-flex`,alignItems:`center`,gap:.75,height:28,px:1.1,borderRadius:999,whiteSpace:`nowrap`,fontSize:12.5,fontWeight:550,color:a==="default"?`text.secondary`:o,bgcolor:`action.hover`},children:[(0,Q.jsx)(R,{component:`span`,"aria-hidden":`true`,sx:{width:7,height:7,borderRadius:`50%`,bgcolor:o}}),i]})}function es({session:e,snapshot:t,locale:n,live:r,canSend:i,canRestart:o,send:s,abort:c,restart:l,onInspector:u,commandActions:d}){let f=e.sessionRef,p=hn(f),[m,h]=(0,$.useState)(()=>mn(f)),[g,_]=(0,$.useState)(!1),[y,b]=(0,$.useState)(),x=e=>{h(e),yn(f,e)},C=e.modelLabel===`agent-watch-auto`,w=!!(r&&!r.complete),T=Rr({locale:n,company:C,running:w,pinned:e.pinned,bypass:e.managedBypass===!0,fast:e.managedFast===`on`||e.managedFast===`off`?e.managedFast:null,thinkingLevels:e.managedThinkingLevels??(C?[]:[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`]),loadModels:()=>He().then(e=>e.models.map(e=>({modelRef:e.modelRef,label:e.displayName}))),actions:{...d,stop:c}}),E=T.map(e=>({kind:`command`,name:e.name,argumentHint:e.argumentHint,origin:`piagent`,scope:`project`,description:e.description})),[D,O]=(0,$.useState)(null),[k,A]=(0,$.useState)(null);(0,$.useEffect)(()=>{let e=e=>{e.isComposing||k||(e.key===`Escape`&&w&&!e.metaKey&&!e.ctrlKey?(e.preventDefault(),c()):e.key===`/`&&(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&i&&(e.preventDefault(),x(`/`),requestAnimationFrame(()=>{let e=j.inputRef.current;e?.focus(),e?.setSelectionRange(1,1)})))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)});let j=Or({projectRef:e.projectRef,value:m,locale:n,builtIns:E,onChange:e=>{x(e),ie(null)}});(0,$.useEffect)(()=>{let e=e=>{e.detail===f&&(h(mn(f)),requestAnimationFrame(()=>j.inputRef.current?.focus()))};return window.addEventListener(bn,e),()=>window.removeEventListener(bn,e)},[f]);let[M,N]=(0,$.useState)(()=>p?.attachments??[]),[F,I]=(0,$.useState)(!1),[z,ee]=(0,$.useState)(()=>p?.messageRequestId??`message-request.${crypto.randomUUID()}`),[B,te]=(0,$.useState)(!1),[ne,V]=(0,$.useState)(null),[H,ie]=(0,$.useState)(null),[U,ae]=(0,$.useState)(()=>p?.sendUnconfirmed??!1);(0,$.useEffect)(()=>{_n(f,M.length||U?{attachments:M,messageRequestId:z,sendUnconfirmed:U}:null)},[f,M,z,U]),(0,$.useEffect)(()=>{if(!U)return;let e=window.setTimeout(()=>{ae(!1),ie({tone:`error`,text:X(n,`Tin nhắn chưa được gửi: phiên chưa nhận nó trong 2 phút nên nó sẽ không chạy nữa. Nội dung vẫn còn; bấm Gửi để thử lại.`,`The message was not sent: the session did not take it within 2 minutes, so it will not run. Your message is kept; send it again.`)})},zo+15e3);return()=>window.clearTimeout(e)},[U,n]);let[oe,W]=(0,$.useState)(!1),[G,se]=(0,$.useState)(null),[ce,le]=(0,$.useState)(!1),[ue,fe]=(0,$.useState)(0),K=(0,$.useRef)(0);(0,$.useEffect)(()=>{let e=e=>{pn(e.dataTransfer)&&e.preventDefault()};return window.addEventListener(`dragover`,e),window.addEventListener(`drop`,e),()=>{window.removeEventListener(`dragover`,e),window.removeEventListener(`drop`,e)}},[]);let me=t?.capabilities.capabilities.attachments,he=(0,$.useMemo)(()=>new Set(me?.status===`available`?me.mimeTypes:[]),[me]),ge=(0,$.useMemo)(()=>nn(he),[he]),_e=!!t&&me?.status===`available`&&i&&!g&&!U&&!B&&M.length<4,q=async r=>{if(!(!r?.length||!t||me?.status!==`available`||B)){te(!0),V(null);try{let i=await Kt({files:r,snapshot:t,messageRequestId:z,existing:M,allowed:he,locale:n,stage:t=>Ye(e.sessionRef,t)});N(i.attachments),V(i.status)}catch{V(X(n,`Không thể đính kèm; file không được gửi vào Pi.`,`Unable to attach the file; it was not sent to Pi.`))}finally{te(!1)}}},ve=async r=>{if(!(!t||g||B)){te(!0),V(null);try{let i=await un({snapshot:t,messageRequestId:z,attachmentRef:r,locale:n,stage:t=>Ye(e.sessionRef,t)});i.discarded?N(e=>e.filter(e=>e.attachmentRef!==r)):V(i.status)}catch{V(X(n,`Không thể bỏ file; trạng thái session có thể đã thay đổi.`,`Unable to remove the file; session state may have changed.`))}finally{te(!1)}}};(0,$.useEffect)(()=>{let t=new AbortController;return b(void 0),Ve(e.sessionRef,t.signal).then(b).catch(()=>void 0),()=>t.abort()},[e.sessionRef,e.sessionRevision]);let J=(0,$.useRef)(!1),ye=async()=>{let e=m;if(!e.trim()||g||U||J.current)return;let t=M.length===0?Fr(e,T):null;if(t){ie(null),O(null);let e=await t.command.run(t.argument);if(`confirm`in e){A(e.confirm),x(``);return}if(!(`send`in e)){O(e),e.tone!==`warning`&&x(``);return}}J.current=!0,_(!0),ie(null);let r=M.map(e=>e.attachmentRef);try{if((await s(e,r.length>0?{messageRequestId:z,attachmentRefs:r,attachments:M}:void 0)).state===`unconfirmed`){_n(f,{attachments:M,messageRequestId:z,sendUnconfirmed:!0}),ae(!0),ie({tone:`warning`,text:X(n,`Piagent đang xác nhận lần gửi này. Nội dung và file vẫn được giữ; đừng gửi lại để tránh chạy trùng.`,`Piagent is confirming this send. Your message and files remain preserved; do not resend, to avoid a duplicate run.`)});return}x(``),N([]),V(null),ee(`message-request.${crypto.randomUUID()}`),_n(f,null)}catch{ie({tone:`error`,text:X(n,`Tin nhắn chưa được gửi. Nội dung và file vẫn được giữ; có thể thử lại khi session sẵn sàng.`,`The message was not sent. Your message and files are preserved; retry when the session is ready.`)})}finally{J.current=!1,_(!1)}};(0,$.useEffect)(()=>{!U||r?.messageRequestId!==z||r.delivery!==`admitted`||(x(``),N([]),V(null),ie(null),ae(!1),ee(`message-request.${crypto.randomUUID()}`))},[r?.delivery,r?.messageRequestId,z,U]);let Y=async()=>{if(!(g||U)){_(!0),ie(null);try{await s(X(n,`tiếp tục`,`continue`))}catch{ie({tone:`error`,text:X(n,`Chưa gửi được. Thử lại khi session sẵn sàng.`,`Not sent. Retry when the session is ready.`)})}finally{_(!1)}}},be=async t=>{if(t){b(t);return}b(await Ve(e.sessionRef).catch(()=>y))},xe=async()=>{if(!oe){W(!0),se(null);try{await l()}catch(e){se(e instanceof Error?e.message:null)}finally{W(!1)}}},Se=r?.runtimeRecovery??(e.state===`recovery-required`?`stale`:null);return(0,Q.jsxs)(R,{sx:{minHeight:`calc(100vh - 88px - var(--piagent-status-bar, 0px))`,display:`flex`,flexDirection:`column`},children:[(0,Q.jsxs)(R,{sx:{flex:1,width:`100%`,maxWidth:860,mx:`auto`,px:{xs:2,sm:4},py:{xs:3,md:4},display:`flex`,flexDirection:`column`,justifyContent:`flex-end`},children:[!i&&e.modelLabel===`agent-watch-auto`&&(0,Q.jsx)(gr,{locale:n,onConnected:()=>fe(e=>e+1)},e.sessionRef),(0,Q.jsx)(R,{sx:{width:`100%`},children:(0,Q.jsx)(no,{reload:ue,sessionRef:e.sessionRef,sessionRevision:e.sessionRevision,live:r,approvals:t?.approvals,locale:n,onOpenActivity:()=>u(`activity`),onContinue:i&&!g&&!U&&e.liveState!==`running`&&(!r||r.complete)?()=>void Y():void 0},e.sessionRef)})]}),(0,Q.jsxs)(R,{sx:{position:`sticky`,bottom:`var(--piagent-status-bar, 0px)`,px:{xs:1.5,sm:2.5},pb:2.5,background:`linear-gradient(transparent, var(--piagent-palette-background-default) 25%)`},children:[(0,Q.jsx)(Bn,{session:e,locale:n}),e.state===`terminal-owned`&&(0,Q.jsx)(v,{severity:`info`,role:`status`,sx:{maxWidth:820,mx:`auto`,mb:1},children:X(n,`Cuộc trò chuyện này đang chạy trong Terminal hoặc một tiến trình Piagent khác. Trang này tự cập nhật để bạn theo dõi; gửi tin nhắn khi nó chạy xong.`,`This conversation is running in Terminal or another Piagent process. This page follows it; send a message when it has finished.`)}),Se&&(0,Q.jsx)(v,{severity:Se===`recovered`?`success`:Se===`failed`?`error`:`warning`,action:(Se===`failed`||Se===`required`||Se===`stale`)&&o&&e.liveState!==`running`?(0,Q.jsx)(a,{color:`inherit`,size:`small`,disabled:oe,onClick:()=>void xe(),children:oe?X(n,`Đang khởi động…`,`Restarting…`):X(n,`Khởi động lại phiên`,`Restart session`)}):void 0,sx:{maxWidth:860,mx:`auto`,mb:1},children:Se===`recovered`?X(n,`Runtime mới đã được xác minh; lịch sử và context của session được giữ nguyên.`,`The new runtime is verified; session history and context were preserved.`):Se===`failed`?G?.startsWith(`company-`)&&sr(G,null,n)?`${sr(G,null,n).title}: ${sr(G,null,n).text}`:X(n,`Runtime đã đổi nhưng chưa khởi động lại được. Hãy dùng nút bên cạnh hoặc restart Dashboard.`,`The runtime changed but could not restart. Use the action here or restart the Dashboard.`):Se===`stale`&&[`session-runtime-open-failed`,`session-runtime-dispose-failed`].includes(e.reasonCode??``)?X(n,`Runtime của phiên này chưa mở được (thường do key, Harness hoặc Agent Watch lúc đó). Bấm Khởi động lại phiên để thử lại, hoặc lưu trữ phiên; lịch sử được giữ nguyên.`,`This session's runtime did not open (usually the key, the Harness or Agent Watch at the time). Restart the session to try again, or archive it; its history is kept.`):Se===`stale`?X(n,`Phiên này chưa được đóng đúng cách và có thể đang mở ở cửa sổ Terminal khác. Đóng cửa sổ đó (nếu có) rồi bấm Khởi động lại phiên để làm tiếp; lịch sử được giữ nguyên.`,`This session was not closed cleanly and may still be open in a Terminal window. Close it (if any), then restart the session to go on; its history is kept.`):Se===`restarting`?X(n,`Runtime vừa được cập nhật. Piagent đang khởi động lại session an toàn sau lượt hiện tại.`,`The runtime was updated. Piagent is safely restarting the session after the current turn.`):X(n,`Phát hiện runtime mới. Piagent sẽ giữ câu trả lời hiện tại rồi tự khởi động lại session.`,`A new runtime was detected. Piagent will preserve the current response and restart the session automatically.`)}),(0,Q.jsxs)(R,{sx:{position:`relative`,maxWidth:860,mx:`auto`,border:1,borderColor:ce?`primary.main`:`divider`,borderStyle:ce?`dashed`:`solid`,borderRadius:2,bgcolor:`background.paper`,px:1.5,pt:1.25,pb:1,boxShadow:`0 12px 40px -18px rgba(0,0,0,.5)`,transition:`border-color .16s, box-shadow .16s`,"&:focus-within":{borderColor:`rgba(var(--piagent-palette-primary-mainChannel) / .55)`,boxShadow:`0 0 0 3px rgba(var(--piagent-palette-primary-mainChannel) / .14), 0 12px 40px -18px rgba(0,0,0,.5)`}},onDragEnter:e=>{pn(e.dataTransfer)&&(K.current+=1,le(!0))},onDragOver:e=>{pn(e.dataTransfer)&&(e.preventDefault(),e.dataTransfer.dropEffect=_e?`copy`:`none`)},onDragLeave:e=>{pn(e.dataTransfer)&&(--K.current,K.current<=0&&(K.current=0,le(!1)))},onDrop:e=>{pn(e.dataTransfer)&&(e.preventDefault(),K.current=0,le(!1),_e&&q(e.dataTransfer.files))},children:[ce&&(0,Q.jsxs)(R,{role:`status`,sx:{position:`absolute`,inset:0,zIndex:3,display:`grid`,alignContent:`center`,justifyItems:`center`,gap:.5,borderRadius:1,bgcolor:`background.paper`,opacity:.96,pointerEvents:`none`,textAlign:`center`},children:[(0,Q.jsx)(S,{sx:{fontWeight:650},children:_e?X(n,`Thả tài liệu vào đây`,`Drop documents here`):M.length>=4?X(n,`Đã đủ 4 file cho tin nhắn này`,`This message already holds 4 files`):X(n,`Chưa nhận file lúc này`,`Files cannot be attached right now`)}),_e&&(0,Q.jsx)(S,{variant:`caption`,color:`text.secondary`,children:$t(n)})]}),M.length>0&&(0,Q.jsx)(P,{direction:`row`,sx:{flexWrap:`wrap`,gap:.75,px:.5,pb:.75},"aria-label":X(n,`File sẽ gửi cùng tin nhắn`,`Files to send with the message`),children:M.map(e=>(0,Q.jsx)(Ce,{size:`small`,variant:`outlined`,color:e.kind===`document`?`success`:`default`,avatar:e.kind===`image`&&qt(e.attachmentRef)?(0,Q.jsx)($n,{variant:`rounded`,alt:``,src:qt(e.attachmentRef)}):void 0,label:`${e.displayName} · ${en(e,n)}`,onDelete:g||U||B?void 0:()=>void ve(e.attachmentRef),deleteIcon:(0,Q.jsx)(Hn,{"aria-label":`${X(n,`Bỏ`,`Remove`)} ${e.displayName}`,role:`button`})},e.attachmentRef))}),D&&(0,Q.jsx)(v,{severity:D.tone,onClose:()=>O(null),sx:{mb:.75,whiteSpace:`pre-line`},children:D.text}),(0,Q.jsx)(re,{fullWidth:!0,multiline:!0,minRows:2,disabled:!i||g||U,value:m,inputRef:j.inputRef,...j.inputProps,onChange:e=>{x(e.target.value),ie(null),j.track(e)},onKeyDown:e=>{j.onKeyDown(e)||_r(e)&&(e.preventDefault(),ye())},onPaste:e=>{e.clipboardData?.files.length&&(e.preventDefault(),_e&&q(e.clipboardData.files))},placeholder:X(n,`Nhắn cho Piagent… (@ để chọn file, folder)`,`Message Piagent… (@ for files and folders)`),variant:`standard`,slotProps:{input:{disableUnderline:!0},htmlInput:j.htmlInput}}),j.menu,(0,Q.jsx)(lt,{open:k!==null,title:k?.title??``,description:k?.description??``,confirmLabel:k?.confirmLabel??``,cancelLabel:X(n,`Huỷ`,`Cancel`),onCancel:()=>A(null),onConfirm:()=>{let e=k;A(null),e&&e.run().then(O)}}),(0,Q.jsx)(or,{in:F,id:`piagent-message-options`,children:(0,Q.jsxs)(R,{sx:{mt:.65,p:.85,borderRadius:1,bgcolor:`action.hover`},children:[(0,Q.jsx)(st,{session:e,snapshot:t,connections:y,locale:n,onOpenChanges:()=>u(`source`),onConnectionsChanged:be}),(0,Q.jsx)(P,{direction:`row`,sx:{minWidth:0,alignItems:`center`,gap:.75,flexWrap:`wrap`},children:me?.status===`available`&&(0,Q.jsx)(pe,{title:X(n,`Chọn file, hoặc kéo thả / dán thẳng vào khung chat`,`Pick a file, or drag and drop / paste straight into the chat`),children:(0,Q.jsxs)(a,{component:`label`,size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(Vn,{}),disabled:!_e,"aria-label":`${X(n,`Đính kèm`,`Attach`)} (${M.length}/4)`,children:[X(n,`Đính kèm`,`Attach`),(0,Q.jsx)(`input`,{type:`file`,multiple:!0,hidden:!0,disabled:!_e,accept:ge||void 0,onChange:e=>{q(e.target.files),e.currentTarget.value=``}})]})})})]})}),(0,Q.jsxs)(P,{direction:`row`,sx:{justifyContent:`space-between`,alignItems:`center`,mt:.5,gap:1},children:[(0,Q.jsxs)(P,{direction:`row`,sx:{minWidth:0,alignItems:`center`,gap:1},children:[(0,Q.jsx)(pe,{title:F?X(n,`Ẩn tùy chọn`,`Hide options`):X(n,`File và công cụ`,`Files and tools`),children:(0,Q.jsx)(L,{size:`small`,"aria-label":F?X(n,`Ẩn tùy chọn`,`Hide options`):X(n,`Thêm tùy chọn`,`More options`),"aria-expanded":F,"aria-controls":`piagent-message-options`,onClick:()=>I(e=>!e),sx:{bgcolor:F?`action.selected`:`transparent`},children:(0,Q.jsx)(de,{fontSize:`small`,sx:{transition:`transform .16s ease`,transform:F?`rotate(45deg)`:`none`}})})}),(0,Q.jsx)(S,{variant:`caption`,color:ne||H?.tone===`error`?`error`:H?`warning.main`:`text.disabled`,noWrap:!H,sx:{display:{xs:ne||H||B?`block`:`none`,sm:`block`}},children:H?.text??ne??(B?X(n,`Đang đọc tài liệu…`,`Reading documents…`):r&&!r.complete?X(n,`Esc để dừng · gửi việc tiếp khi lượt này xong`,`Esc to stop · send the next task when this turn ends`):i?X(n,`Enter để gửi · Shift+Enter xuống dòng`,`Enter to send · Shift+Enter for a new line`):X(n,`Session hiện chỉ đọc`,`Session is currently read only`))})]}),r?.operationRef&&!r.complete&&r.abortable!==!1?(0,Q.jsx)(a,{color:`error`,variant:`outlined`,size:`small`,startIcon:(0,Q.jsx)(Gn,{}),onClick:()=>void c(),sx:{borderRadius:999},children:X(n,`Dừng`,`Stop`)}):(0,Q.jsx)(L,{"aria-label":X(n,`Gửi`,`Send`),disabled:!i||g||U||!m.trim(),color:`primary`,onClick:()=>void ye(),sx:{width:32,height:32,borderRadius:999,bgcolor:`primary.main`,color:`primary.contrastText`,transition:`transform .12s, background-color .16s`,"&:hover":{bgcolor:`primary.main`,color:`primary.contrastText`,transform:`translateY(-1px)`},"&.Mui-disabled":{bgcolor:`action.disabledBackground`}},children:(0,Q.jsx)(Un,{fontSize:`small`})})]})]})]})]})}function ts({locale:e,canCreate:t,onNew:n}){return(0,Q.jsxs)(P,{sx:{minHeight:`calc(100vh - ${Yo}px - var(--piagent-status-bar, 0px))`,alignItems:`center`,justifyContent:`center`,px:3,textAlign:`center`},spacing:1.5,children:[(0,Q.jsx)(ut,{size:48}),(0,Q.jsx)(S,{variant:`h1`,children:X(e,`Bắt đầu với Piagent`,`Start with Piagent`)}),(0,Q.jsx)(S,{color:`text.secondary`,sx:{maxWidth:520},children:X(e,`Tạo cuộc trò chuyện mới, chọn project và model; session sẽ được lưu để tiếp tục sau khi đóng Gateway.`,`Create a new chat, choose a project and model, and the session will remain available after the Gateway closes.`)}),(0,Q.jsx)(a,{disabled:!t,variant:`contained`,startIcon:(0,Q.jsx)(de,{}),onClick:n,children:X(e,`Cuộc trò chuyện mới`,`New chat`)})]})}function ns({catalog:e,capabilities:t,connection:n,live:r,terminalActivities:o,refresh:c,create:l,send:d,abort:p,restart:m,setModel:h,setThinking:g,setPermission:_,setFast:v,rename:y,pin:b,archive:x,unarchive:C,fork:w}){let{locale:T,colorMode:E,themeId:D,setLocale:k,setColorMode:A,setThemeId:j}=Oe(),M=Br(),N=ct(),[I,z]=(0,$.useState)(!1),[B,te]=(0,$.useState)(`sessions`),ne=i(fe().breakpoints.up(`lg`)),[V,H]=(0,$.useState)(null),[ie,U]=(0,$.useState)(``),[oe,W]=(0,$.useState)(),[G,se]=(0,$.useState)(!1),[le,ue]=(0,$.useState)(!1),[de,K]=(0,$.useState)(`chat`),[me,he]=(0,$.useState)(!1),[ge,_e]=(0,$.useState)(`general`),[q,ve]=(0,$.useState)(!1),[J,ye]=(0,$.useState)(`task`),Y=!ne,[be,xe]=(0,$.useState)(()=>{try{let e=window.localStorage.getItem(Qo);if(e)return e===`open`}catch{}return window.innerWidth>=1200}),[Se,Ce]=(0,$.useState)(!1),we=()=>Y?Ce(e=>!e):xe(e=>{try{window.localStorage.setItem(Qo,e?`closed`:`open`)}catch{}return!e}),Te=(0,$.useRef)(!1);q&&(Te.current=!0);let Ee=(0,$.useRef)(!1);Ee.current=q&&(J===`activity`||J===`source`);let[De,ke]=(0,$.useState)(),Ae=(0,$.useRef)(null),[Me,Pe]=(0,$.useState)(`idle`),Fe=(0,$.useRef)(null),Ie=(0,$.useRef)(null);Ie.current??=new xn;let[Le,Re]=(0,$.useState)(!1),[ze,Be]=(0,$.useState)(null),[Ve,He]=(0,$.useState)(null),[Ue,We]=(0,$.useState)(``),[Ke,qe]=(0,$.useState)(!1),[Je,Xe]=(0,$.useState)(null),[Ze,Qe]=(0,$.useState)(null);(0,$.useEffect)(()=>{de===`chat`&&oe||(window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0)},[de,oe]);let $e=(0,$.useMemo)(()=>(e?.sessions??[]).filter(e=>e.archived===le&&`${e.title} ${e.projectLabel} ${e.preview}`.toLowerCase().includes(ie.trim().toLowerCase())),[e,ie,le]),et=(0,$.useMemo)(()=>{let e=new Map;for(let t of $e){let n=e.get(t.projectRef)??{label:t.projectLabel,gitBranch:t.gitBranch,sessions:[]};n.gitBranch??=t.gitBranch,n.gitRepositories??=t.gitRepositories,n.sessions.push(t),e.set(t.projectRef,n)}return[...e.entries()].map(([e,t])=>({projectRef:e,...t,sessions:t.sessions.sort((e,t)=>Number(t.pinned)-Number(e.pinned)||Date.parse(t.updatedAt)-Date.parse(e.updatedAt))})).sort((e,t)=>Date.parse(t.sessions[0]?.updatedAt??``)-Date.parse(e.sessions[0]?.updatedAt??``))},[$e]),tt=e?.sessions.filter(e=>e.archived).length??0;(0,$.useEffect)(()=>{(!oe||!(e?.sessions??[]).some(e=>e.sessionRef===oe))&&W((e?.sessions??[]).find(e=>!e.archived)?.sessionRef)},[oe,e]);let Z=(e?.sessions??[]).find(e=>e.sessionRef===oe),nt=Z?.sessionRef,rt=Z?.state===`terminal-owned`,it=(e?.sessions??[]).some(e=>e.state===`terminal-owned`);(0,$.useEffect)(()=>{let e=rt?3e3:it?1e4:3e4,t=window.setInterval(()=>{document.visibilityState===`visible`&&c()},e);return()=>window.clearInterval(t)},[rt,it,c]);let at=(0,$.useRef)(nt);at.current=nt;let ot=Ae.current&&Ae.current.sessionRef===nt&&Ae.current.snapshot===De?De:void 0,lt=Fe.current===nt?Me:nt?`loading`:`idle`,ut=Z?r[Z.sessionRef]:void 0,[dt,ft]=(0,$.useState)(null),pt=(0,$.useRef)(!1);(0,$.useEffect)(()=>{if(!e||pt.current)return;pt.current=!0;let t=Ne();t&&(ft(t),K(`new`))},[e]);let mt=e=>{ft(null),W(e),K(`chat`),se(!1)},ht=so({sessions:(0,$.useMemo)(()=>e?.sessions??[],[e]),live:r,selectedRef:de===`chat`?nt:void 0,onOpen:mt,locale:T}),gt=e=>{_e(e),he(!0)};bt({palette:()=>z(!0),settings:()=>gt(`general`),newChat:()=>{xt&&(Be(null),K(`new`))}});let vt=e=>{ye(e),ve(!0)},yt=async()=>{let e=at.current;if(!e)return;Ae.current?.sessionRef!==e&&(Fe.current=e,Pe(`loading`));let t=await Ie.current.run(()=>Ge(e),t=>{at.current===e&&(Ae.current={sessionRef:e,snapshot:t},Fe.current=e,ke(t),Pe(`ready`))},()=>{at.current===e&&(Fe.current=e,Pe(Ae.current?.sessionRef===e?`ready`:`error`))});return at.current===e?t:void 0};(0,$.useEffect)(()=>{if(!nt){Ie.current.invalidate(),Ae.current=null,Fe.current=null,ke(void 0),Pe(`idle`);return}let e=nt,t=new AbortController;return Fe.current=e,Ae.current?.sessionRef!==e&&(Ae.current=null,ke(void 0),Pe(`loading`)),Ie.current.run(()=>Ge(e,t.signal),n=>{t.signal.aborted||at.current!==e||(Ae.current={sessionRef:e,snapshot:n},Fe.current=e,ke(n),Pe(`ready`))},()=>{t.signal.aborted||at.current!==e||(Fe.current=e,Pe(Ae.current?.sessionRef===e?`ready`:`error`))}),()=>t.abort()},[nt,Z?.sessionRevision]),(0,$.useEffect)(()=>{if(!q||J!==`activity`&&J!==`source`||!nt||!ot||!ut?.operationRef||ut.complete)return;let e=nt,t=!1,n,r=async()=>{await Ie.current.run(()=>Ge(e),n=>{t||!Ee.current||at.current!==e||(Ae.current={sessionRef:e,snapshot:n},Fe.current=e,ke(n),Pe(`ready`))},()=>void 0),t||(n=window.setTimeout(()=>void r(),2e3))};return n=window.setTimeout(()=>void r(),2e3),()=>{t=!0,n!==void 0&&window.clearTimeout(n)}},[q,J,nt,!!ot,ut?.operationRef,ut?.complete]);let xt=n===`connected`&&t?.capabilities.sessionActions.create.status===`available`,Ct=async e=>{Re(!0),Be(null);let t=null;try{let n=`message-request.${crypto.randomUUID()}`,r=e.files.length>0,i=await l({projectRef:e.projectRef,placeRef:e.placeRef,modelRef:e.modelRef,thinkingLevel:e.thinkingLevel,workflow:e.workflow,permissionMode:e.permissionMode,fast:e.fast,message:e.message,messageRequestId:n,deferInitialMessage:r});if(t=i.sessionRef,!t)throw Error(`session-create-result-invalid`);if(yn(gn,``),_n(gn,null),i.phase!==`settled`){W(t),K(`chat`),Qe({title:X(T,`Session đã được tạo`,`The session was created`),message:X(T,`Pi đã nhận yêu cầu và session đang tự đồng bộ. Không gửi lại để tránh chạy trùng.`,`Pi received the request and the session is resyncing. Do not resend it, to avoid a duplicate run.`)});return}if(r){let r=(await c())?.sessions.find(e=>e.sessionRef===t);if(!r)throw Error(`session-catalog-refresh-failed`);let i=await Ge(t),a=i.capabilities.capabilities.attachments;if(a.status!==`available`)throw Error(a.reason?.code??`session-attachment-unavailable`);let o=await Kt({files:e.files,snapshot:i,messageRequestId:n,existing:[],allowed:new Set(a.mimeTypes),locale:T,stage:e=>Ye(t,e)});if(o.status||o.attachments.length!==e.files.length)throw await Promise.all(o.attachments.map(async e=>{try{await un({snapshot:i,messageRequestId:n,attachmentRef:e.attachmentRef,locale:T,stage:e=>Ye(t,e)})}catch{}})),Error(o.status??`session-attachment-incomplete`);await d(r,e.message,{messageRequestId:n,attachmentRefs:o.attachments.map(e=>e.attachmentRef),attachments:o.attachments,workflow:e.workflow})}W(t),K(`chat`)}catch(n){let r=n instanceof Error?n.message:`session-create-failed`;t?(e.files.length>0&&yn(t,e.message),W(t),K(`chat`),Qe({title:X(T,`Session đã tạo nhưng file chưa được gửi`,`The session was created, but the files were not sent`),message:r})):Be(pr(r,T))}finally{Re(!1)}},wt=(e,t)=>{if(t===`pin`){b(e,!e.pinned).catch(e=>Qe({title:X(T,`Không thể đổi trạng thái ghim`,`Could not change pin state`),message:e instanceof Error?e.message:`session-pin-failed`}));return}if(t===`unarchive`){C(e).then(()=>ue(!1)).catch(e=>Qe({title:X(T,`Không thể khôi phục cuộc trò chuyện`,`Could not restore chat`),message:e instanceof Error?e.message:`session-unarchive-failed`}));return}Xe(null),We(t===`rename`?e.title:t===`fork`?`${e.title} · ${X(T,`nhánh`,`fork`)}`:``),He({kind:t,session:e})},Tt=async()=>{if(!(!Ve||Ke)){qe(!0),Xe(null);try{if(Ve.kind===`rename`)await y(Ve.session,Ue.trim());else if(Ve.kind===`archive`)await x(Ve.session);else{let e=await w(Ve.session,Ue.trim()||null);e.sessionRef&&(W(e.sessionRef),K(`chat`))}He(null)}catch(e){Xe(as(Ve.kind,e instanceof Error?e.message:`session-action-failed`,T))}finally{qe(!1)}}},Et=(0,Q.jsx)(Mt,{locale:T,canCreate:xt,query:ie,onQuery:U,groups:et,count:$e.length,selectedRef:de===`chat`?Z?.sessionRef:void 0,showArchived:le,archivedCount:tt,settingsOpen:me,connection:n,live:r,unseen:ht.unseen,onSelect:mt,onAction:wt,onNew:()=>{Be(null),K(`new`),se(!1)},onToggleArchived:()=>{ue(e=>!e),se(!1)},updateDot:!!(N.status?.updateAvailable&&N.status.installable),onSettings:()=>{gt(N.status?.updateAvailable&&N.status.installable?`updates`:`general`),se(!1)}}),Ot=de===`chat`&&Z?(0,Q.jsx)(Fo,{session:Z,snapshot:ot,live:ut,locale:T,onOpenReview:()=>vt(`source`),onClose:()=>Y?Ce(!1):xe(!1)}):null,kt=!!Ot&&(Y?Se:be)&&!q;if(M)return(0,Q.jsx)(Vr,{locale:T});if(!e&&n!==`failed`)return(0,Q.jsxs)(P,{sx:{minHeight:`100vh`,alignItems:`center`,justifyContent:`center`},spacing:2,children:[(0,Q.jsx)(ee,{size:24}),(0,Q.jsx)(S,{children:X(T,`Đang mở Piagent…`,`Opening Piagent…`)})]});let At=de===`new`?X(T,`Cuộc trò chuyện mới`,`New chat`):Z?.title??`Piagent`,jt=Io({locale:T,colorMode:E,themeId:D,canCreate:xt,hasSelection:de===`chat`&&!!Z,sessions:(e?.sessions??[]).filter(e=>!e.archived),update:{available:!!(N.status?.updateAvailable&&N.status.installable&&!_t(N.status)),latest:N.status?.piagent.latest??null},actions:{newChat:()=>{Be(null),K(`new`)},togglePanel:we,openChanges:()=>vt(`source`),refresh:()=>void c(),settings:gt,checkUpdates:()=>{gt(`updates`),N.check()},setColorMode:A,setTheme:j,setLocale:k,openSession:mt}}),Nt=Object.values(r).filter(e=>e&&!e.complete).length;return(0,Q.jsx)(Vt,{sessionRef:de===`chat`?nt:void 0,onOpen:()=>ve(!1),children:(0,Q.jsxs)(R,{sx:{minHeight:`100vh`,bgcolor:`background.default`,"--piagent-status-bar":{xs:`0px`,md:`28px`}},children:[(0,Q.jsx)(F,{position:`fixed`,color:`transparent`,elevation:0,sx:{left:{md:`${Jo}px`},right:{lg:kt?`${Xo}px`:0,xl:q?Zo:kt?`${Xo}px`:0},width:{xs:`100%`,md:`auto`},borderBottom:1,transition:`right .2s ease`,borderColor:`divider`,bgcolor:`rgba(var(--piagent-palette-background-defaultChannel) / .9)`,backdropFilter:`blur(18px)`},children:(0,Q.jsxs)(ae,{sx:{minHeight:`${Yo}px !important`,gap:1,px:{xs:1.5,sm:2.5}},children:[(0,Q.jsx)(L,{"aria-label":X(T,`Mở điều hướng`,`Open navigation`),onClick:()=>se(!0),sx:{display:{md:`none`}},children:(0,Q.jsx)(u,{})}),(0,Q.jsxs)(R,{sx:{flex:1,minWidth:0},children:[(0,Q.jsx)(S,{component:`h1`,noWrap:!0,sx:{fontWeight:600,fontSize:14.5,letterSpacing:`-0.01em`,lineHeight:1.3},children:At}),de===`chat`&&Z&&(0,Q.jsxs)(S,{variant:`caption`,color:`text.secondary`,noWrap:!0,component:`div`,sx:{display:`flex`,alignItems:`center`,gap:.75,minWidth:0},children:[(0,Q.jsx)(R,{component:`span`,sx:{overflow:`hidden`,textOverflow:`ellipsis`,flexShrink:3,minWidth:24},children:Z.projectLabel}),(Z.gitBranch||!!Z.gitRepositories?.length)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(R,{component:`span`,"aria-hidden":!0,sx:{color:`text.disabled`},children:`·`}),(0,Q.jsx)(It,{projectRef:Z.projectRef,projectLabel:Z.projectLabel,branch:Z.gitBranch,repositories:Z.gitRepositories,locale:T,maxWidth:`45%`,onSwitched:()=>void c()})]})]})]}),de===`chat`&&Z&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(st,{placement:`header`,compact:q,session:Z,snapshot:ot,locale:T,onOpenChanges:()=>vt(`source`),canSetModel:n===`connected`&&t?.capabilities.sessionActions.setModel.status===`available`,canSetThinking:n===`connected`&&t?.capabilities.sessionActions.setThinking.status===`available`,canSetPermission:n===`connected`&&t?.capabilities.sessionActions.setPermission.status===`available`,onSetModel:e=>h(Z,e),onSetThinking:e=>g(Z,e),onSetPermission:e=>_(Z,e),onSetFast:e=>v(Z,e)}),(0,Q.jsx)(R,{sx:{display:{xs:`none`,sm:q?`none`:`block`}},children:(0,Q.jsx)($o,{session:Z,live:ut,locale:T})}),(0,Q.jsx)(R,{"aria-hidden":`true`,sx:{width:`1px`,height:20,bgcolor:`divider`,mx:.5,display:{xs:`none`,sm:`block`}}}),(0,Q.jsx)(pe,{title:`Source Changes`,children:(0,Q.jsx)(L,{"aria-label":X(T,`Mở Source Changes Inspector`,`Open Source Changes Inspector`),onClick:()=>vt(`source`),children:(0,Q.jsx)(O,{fontSize:`small`})})}),(0,Q.jsx)(pe,{title:X(T,`Khung Workspace: thay đổi, ngữ cảnh, subagent`,`Workspace panel: changes, context, subagents`),children:(0,Q.jsx)(L,{"aria-label":X(T,`Khung Workspace`,`Workspace panel`),"aria-pressed":kt,onClick:()=>we(),color:kt?`primary`:`default`,children:(0,Q.jsx)(Wn,{fontSize:`small`,sx:{transform:`scaleX(-1)`}})})})]}),(0,Q.jsx)(pe,{title:X(T,`Làm mới`,`Refresh`),children:(0,Q.jsx)(L,{"aria-label":X(T,`Làm mới`,`Refresh`),onClick:()=>void c(),children:(0,Q.jsx)(f,{fontSize:`small`})})})]})}),(0,Q.jsxs)(R,{component:`nav`,sx:{width:{md:Jo}},children:[(0,Q.jsx)(ce,{variant:`temporary`,open:G,onClose:()=>se(!1),sx:{display:{xs:`block`,md:`none`},"& .MuiDrawer-paper":{width:Jo}},children:Et}),(0,Q.jsxs)(ce,{variant:`permanent`,sx:{display:{xs:`none`,md:`block`},"& .MuiDrawer-paper":{width:Jo,borderRight:1,borderColor:`divider`,height:`calc(100% - var(--piagent-status-bar, 0px))`}},children:[ne&&Z&&de===`chat`&&(0,Q.jsx)(Tn,{value:B,onChange:te}),!ne||B===`sessions`||!Z||de!==`chat`?Et:(0,Q.jsx)(R,{ref:H,sx:{overflow:`auto`,flex:1}})]})]}),(0,Q.jsx)(R,{component:`main`,sx:{ml:{md:`${Jo}px`},mr:{lg:kt?`${Xo}px`:0,xl:q?Zo:kt?`${Xo}px`:0},pt:`${Yo}px`,transition:`margin-right .2s ease`},children:de===`new`?(0,Q.jsx)(Mr,{active:!0,defaultProjectRef:dt??Z?.projectRef,busy:Le,error:ze,onCancel:()=>K(`chat`),onCreate:e=>Ct(e)}):Z?(0,Q.jsx)(Ln,{sessionRef:Z.sessionRef,navigationHost:V,sidebarMode:B,onSection:te,children:(0,Q.jsx)(es,{session:Z,snapshot:ot,locale:T,live:r[Z.sessionRef],commandActions:{setModel:e=>h(Z,e),setThinking:e=>g(Z,e),setFast:e=>v(Z,e),setPermission:e=>_(Z,e),rename:e=>y(Z,e),fork:()=>w(Z,null),pin:e=>b(Z,e),archive:()=>x(Z),newChat:()=>{Be(null),K(`new`)},openChanges:()=>vt(`source`),openSettings:()=>gt(`general`)},canSend:n===`connected`&&Z.composerAvailable&&t?.capabilities.sessionActions.send.status===`available`&&(!ut||ut.complete)&&![`required`,`restarting`,`failed`].includes(String(r[Z.sessionRef]?.runtimeRecovery)),canRestart:n===`connected`&&t?.capabilities.sessionActions.release.status===`available`&&t?.capabilities.sessionActions.acquire.status===`available`,send:(e,t)=>d(Z,e,t),abort:()=>p(Z).catch(e=>Qe({title:X(T,`Chưa dừng được lượt này`,`This turn could not be stopped`),message:e instanceof Error&&e.message===`operation-unavailable`?X(T,`Lượt đã kết thúc hoặc đang chuyển bước. Nếu vẫn còn chạy, bấm Dừng lần nữa.`,`The turn already ended or is between steps. If it is still running, press Stop again.`):e instanceof Error?e.message:`session-abort-failed`})),restart:()=>m(Z),onInspector:vt},Z.sessionRef)},Z.sessionRef):(0,Q.jsx)(ts,{locale:T,canCreate:xt,onNew:()=>K(`new`)})}),Ot&&kt&&!Y&&(0,Q.jsx)(R,{component:`aside`,sx:{display:{xs:`none`,lg:`block`},position:`fixed`,top:0,right:0,bottom:`var(--piagent-status-bar, 0px)`,width:Xo,borderLeft:1,borderColor:`divider`,zIndex:e=>e.zIndex.appBar-1},children:Ot}),Ot&&(0,Q.jsx)(ce,{anchor:`right`,variant:`temporary`,open:Se&&!q&&Y,onClose:()=>Ce(!1),sx:{display:{xs:`block`,lg:`none`},"& .MuiDrawer-paper":{width:`min(${Xo}px, 88vw)`}},children:Ot}),Te.current&&(0,Q.jsx)($.Suspense,{fallback:null,children:(0,Q.jsx)(qo,{open:q,active:J,snapshot:ot,state:lt,sessionRef:nt,terminalActivities:Z?o[Z.sessionRef]:void 0,liveActivities:ut&&!ut.complete?ut.activities:void 0,onClose:()=>ve(!1),onActive:ye,refresh:yt,findings:Z?.managedReview?.findings,onSendComments:Z&&Z.composerAvailable?e=>{vn(Z.sessionRef,e),ve(!1)}:void 0})}),(0,Q.jsx)(Jr,{locale:T,onDetails:()=>gt(`updates`)}),ht.view,(0,Q.jsx)(St,{locale:T,connection:n,running:Nt,session:de===`chat`?Z:void 0,onBranchSwitched:()=>void c(),onUpdates:()=>gt(`updates`),onPalette:()=>z(!0)}),(0,Q.jsx)(Dt,{open:I,onClose:()=>z(!1),commands:jt,locale:T}),(0,Q.jsx)(s,{open:me,onClose:()=>he(!1),fullWidth:!0,maxWidth:`lg`,"aria-labelledby":`piagent-settings-title`,slotProps:{paper:{sx:{m:{xs:0,sm:2},width:{xs:`100%`,sm:`calc(100% - 32px)`},height:{xs:`100%`,sm:`min(86vh, 840px)`},maxHeight:{xs:`100%`,sm:`86vh`},borderRadius:{xs:0,sm:2.5},overflow:`hidden`}}},children:me&&(0,Q.jsx)(je,{locale:T,children:(0,Q.jsx)(Ko,{section:ge,onSection:_e,onBack:()=>he(!1),session:Z,snapshot:ot,capabilities:t,connection:n,onSetModel:Z?e=>h(Z,e):void 0,onSetThinking:Z?e=>g(Z,e):void 0,onSetPermission:Z?e=>_(Z,e):void 0,onRuntimeChanged:async()=>{await c(),await yt()}})})}),(0,Q.jsx)(s,{open:!!Ve,onClose:()=>!Ke&&He(null),fullWidth:!0,maxWidth:`xs`,children:(0,Q.jsxs)(P,{spacing:2,sx:{p:3},children:[(0,Q.jsx)(S,{variant:`h2`,children:Ve?.kind===`rename`?X(T,`Đổi tên cuộc trò chuyện`,`Rename chat`):Ve?.kind===`fork`?X(T,`Tạo nhánh cuộc trò chuyện`,`Fork chat`):X(T,`Lưu trữ cuộc trò chuyện`,`Archive chat`)}),Ve?.kind===`archive`?(0,Q.jsx)(S,{color:`text.secondary`,children:X(T,`Cuộc trò chuyện vẫn được lưu và có thể khôi phục từ mục Đã lưu trữ.`,`The chat remains saved and can be restored from Archived.`)}):(0,Q.jsx)(re,{autoFocus:!0,label:X(T,`Tên`,`Title`),value:Ue,onChange:e=>We(e.target.value),slotProps:{htmlInput:{maxLength:500}}}),Je&&(0,Q.jsx)(S,{color:`error`,children:Je}),(0,Q.jsxs)(P,{direction:`row`,spacing:1,sx:{justifyContent:`flex-end`},children:[(0,Q.jsx)(a,{disabled:Ke,onClick:()=>He(null),children:X(T,`Hủy`,`Cancel`)}),(0,Q.jsx)(a,{variant:`contained`,disabled:Ke||Ve?.kind!==`archive`&&!Ue.trim(),onClick:()=>void Tt(),children:X(T,`Xác nhận`,`Confirm`)})]})]})}),(0,Q.jsx)(s,{open:!!Ze,onClose:()=>Qe(null),fullWidth:!0,maxWidth:`xs`,"aria-labelledby":`piagent-session-notice-title`,children:(0,Q.jsxs)(P,{spacing:2,sx:{p:3},children:[(0,Q.jsx)(S,{id:`piagent-session-notice-title`,variant:`h2`,children:Ze?.title}),(0,Q.jsx)(S,{color:`text.secondary`,children:Ze?.message}),(0,Q.jsx)(P,{direction:`row`,sx:{justifyContent:`flex-end`},children:(0,Q.jsx)(a,{variant:`contained`,onClick:()=>Qe(null),children:X(T,`Đóng`,`Close`)})})]})})]})})}var rs={"session-revision-stale":[`Cuộc trò chuyện vừa thay đổi trong lúc gửi. Bấm Xác nhận lần nữa.`,`The chat changed while this was sent. Select Confirm again.`],"session-runtime-busy":[`Cuộc trò chuyện đang bận. Thử lại khi lượt này xong.`,`The chat is busy. Try again when this turn ends.`],"session-runtime-unavailable":[`Cuộc trò chuyện chưa mở được. Mở lại cuộc trò chuyện rồi thử lại.`,`The chat is not open. Open it again and retry.`],"session-unavailable":[`Không còn thấy cuộc trò chuyện này trong danh sách. Tải lại trang rồi thử lại.`,`This chat is no longer in the list. Reload the page and retry.`],"session-archived":[`Cuộc trò chuyện đã được lưu trữ. Bỏ lưu trữ trước.`,`The chat is archived. Unarchive it first.`],"session-command-expired":[`Yêu cầu chờ quá lâu nên đã hết hạn. Thử lại.`,`The request waited too long and expired. Try again.`],"gateway-command-response-timeout":[`Piagent chưa trả lời. Xem lại danh sách trước khi thử lại.`,`Piagent did not answer. Check the list before trying again.`]},is={rename:[`Chưa đổi được tên`,`Could not rename`],fork:[`Chưa tạo được nhánh`,`Could not fork`],archive:[`Chưa lưu trữ được`,`Could not archive`]};function as(e,t,n){let r=rs[t];return`${X(n,...is[e])}: ${r?X(n,...r):X(n,`thử lại.`,`try again.`)} (${t})`}function os(e,t=150){let n,r=!1,i=!1,a=!1,o=()=>{if(!a){if(r||n!==void 0){i=r;return}n=setTimeout(()=>{n=void 0,r=!0,e().catch(()=>void 0).finally(()=>{r=!1,i&&(i=!1,o())})},t)}};return{request:o,stop:()=>{a=!0,n!==void 0&&clearTimeout(n),n=void 0}}}var ss=class extends Error{effectMayHaveOccurred;constructor(e,t){super(e),this.name=`GatewayCommandTransportError`,this.effectMayHaveOccurred=t}};async function cs(e,t,n=4){for(let r=1;;r+=1)try{return await e(t)}catch(e){if(r>=n||!(e instanceof ss)||e.message!==`gateway-command-response-timeout`)throw e}}function ls(e,t){return e instanceof ss?e.effectMayHaveOccurred:t}function us(e,t,n=null,r=null){return!e||e.serial<=t||e.operationRef===n||r&&e.messageRequestId&&e.messageRequestId!==r?null:e}function ds(e,t,n=null){return e&&e.operationRef!==t&&!(n&&e.messageRequestId&&e.messageRequestId!==n)?{operationRef:e.operationRef,complete:!1}:null}function fs(e,t){return t?`observed`:e?.phase===`settled`||e?.phase===`accepted`?`confirmed`:e?.phase===`rejected`?`rejected`:`unconfirmed`}function ps(e,t){let n=new AbortController,r=()=>void 0,i=new Promise(e=>{r=e}),a=setTimeout(()=>{n.abort(),r(null)},t);return{promise:Promise.race([e(n.signal).catch(()=>null),i]).finally(()=>clearTimeout(a)),cancel(){n.abort(),r(null),clearTimeout(a)}}}function ms(e,t,n,r,i){let a=e[t];if(!a||a.messageRequestId!==n||i===`unconfirmed`&&(a.delivery===`admitted`||a.operationRef))return e;let o=Si(a,i,r.operationRef,new Date().toISOString()),s=i===`unconfirmed`||r.complete||!!(r.operationRef&&a.operationRef===r.operationRef&&a.complete);return{...e,[t]:{...o,complete:s,abortable:i===`admitted`&&!s&&!!r.operationRef}}}async function hs(e,t={}){let n=()=>{let t=us(e.readLocalObservation?.()??e.localObservation,e.afterSerial,e.priorOperationRef,e.messageRequestId);return t?{operationRef:t.operationRef,complete:t.complete}:null},r=n();if(r)return r;let i=t.timeoutMs??5e3,a=t.readLiveState??nt,o=t.readTranscript??Ue,s=[ps(async t=>{let n=await a(t);return ds(n?.state===`ready`?n.operations.find(t=>t.sessionRef===e.sessionRef):void 0,e.priorOperationRef,e.messageRequestId)},i),ps(async t=>{let n=await o(e.sessionRef,null,50,t);if(n?.state!==`ready`)return null;let r=[...n.items].reverse().find(t=>t.role===`user`&&t.messageRequestId===e.messageRequestId);if(r)return{operationRef:r.agentOperationId,complete:tn(n.items,e.message,{operationRef:r.agentOperationId,messageRequestId:e.messageRequestId,startedAt:null})};let i=Date.parse(e.requestedAt),a=[...n.items].reverse().find(t=>t.role===`user`&&!t.messageRequestId&&sn(t.content.text,e.message)&&Date.parse(t.recordedAt)>=i);return a?{operationRef:a.agentOperationId,complete:tn(n.items,e.message,{operationRef:a.agentOperationId,messageRequestId:null,startedAt:e.requestedAt})}:null},i)],c=new Map(s.map((e,t)=>[t,e.promise.then(e=>({evidence:e,index:t}))]));try{for(;c.size>0;){let e=await Promise.race(c.values());if(c.delete(e.index),e.evidence)return e.evidence;let t=n();if(t)return t}return n()}finally{for(let e of s)e.cancel()}}function gs(e){return(0,$.useMemo)(()=>{let t=[],n=0,r=()=>{if(n&&cancelAnimationFrame(n),n=0,t.length===0)return;let r=t;t=[],e(e=>r.reduce((e,t)=>t(e),e))};return{now:t=>{r(),e(t)},later:e=>{t.push(e),n||=requestAnimationFrame(r)}}},[e])}function _s(){let[e,t]=(0,$.useState)(),[n,r]=(0,$.useState)(),[i,a]=(0,$.useState)(`connecting`),[o,s]=(0,$.useState)({}),{now:c,later:l}=gs(s),[u,d]=(0,$.useState)({}),f=(0,$.useRef)(void 0),p=(0,$.useRef)(null),m=(0,$.useRef)(null),h=(0,$.useRef)({});h.current=o;let g=(0,$.useRef)(0),_=(0,$.useRef)(new Map),v=(0,$.useRef)(null),y=(0,$.useRef)(!0),b=(0,$.useRef)(0),x=(0,$.useRef)(0),S=(0,$.useRef)(new Map),C=(0,$.useCallback)(Uo,[]),w=(0,$.useCallback)(async(e={})=>{let n=++b.current;try{let[r,i]=await Promise.all([We(),nt().catch(()=>void 0)]),o=ui(i,r.gatewayInstanceRef),s=!1;if(n>=x.current){x.current=n,f.current=r,t(r);let l=v.current;l!==null&&l!==r.gatewayInstanceRef&&(y.current=!0),v.current=r.gatewayInstanceRef;let u=e.requireLiveState||y.current,h=p.current?.readyState===WebSocket.OPEN;if(a(di(h,u)),!h&&i&&o!==null)m.current=o,C(r.gatewayInstanceRef,o),c(e=>wi(e,i)),d(yi(i)),y.current=!1,s=!0;else if(l!==r.gatewayInstanceRef){if(d({}),u)m.current=null;else{let e=null;try{e=window.sessionStorage.getItem(Lo)}catch{}m.current=Ho(e,r.gatewayInstanceRef)}}}return e.requireLiveState&&!s?void 0:f.current??r}catch{a(`reconnecting`);return}},[C]),T=(0,$.useCallback)(e=>{let t=p.current;if(!t||t.readyState!==WebSocket.OPEN)return Promise.reject(new ss(`gateway-not-connected`,!1));let n=Wo(`request`);return new Promise((r,i)=>{let a=window.setTimeout(()=>{S.current.delete(n)&&i(new ss(`gateway-command-response-timeout`,!0))},Ro);S.current.set(n,{resolve:r,reject:i,timeout:a});try{t.send(JSON.stringify({schemaVersion:1,version:`piagent-gateway-protocol-v1`,messageType:`request`,requestId:n,method:`sessions.command`,params:{command:e}}))}catch(e){window.clearTimeout(a),S.current.delete(n),i(new ss(e instanceof Error?e.message:`gateway-request-failed`,!1))}})},[]),E=(0,$.useCallback)((e,t,n,r,i,a)=>hs({sessionRef:e,message:t,requestedAt:n,afterSerial:r,priorOperationRef:i,messageRequestId:a,readLocalObservation:()=>_.current.get(e)}),[]),D=(0,$.useCallback)(async e=>{let t=f.current,n=e.message.trim(),r=e.messageRequestId??Wo(`message`);if(!t?.catalogRevision)throw Error(`catalog-unavailable`);if(!n)throw Error(`message-empty`);let i=t=>{if(!t.catalogRevision)throw Error(`catalog-unavailable`);let i=new Date;return cs(T,{schemaVersion:1,version:`piagent-session-command-v1`,messageType:`command`,commandId:Wo(`command`),idempotencyKey:Wo(`idempotency`),action:`session.create`,requestedAt:i.toISOString(),expiresAt:new Date(i.getTime()+3e5).toISOString(),sessionRef:null,expectedCatalogRevision:t.catalogRevision,expectedSessionRevision:null,payload:{projectRef:e.projectRef,placeRef:e.placeRef,modelRef:e.modelRef,thinkingLevel:e.thinkingLevel,workflow:e.workflow,message:n,messageRequestId:r,...e.permissionMode?{permissionMode:e.permissionMode}:{},...e.fast?{fast:!0}:{},...e.deferInitialMessage?{deferInitialMessage:!0}:{}}})},a=await i(t);if(Go(a)){let e=await w();e?.catalogRevision&&(a=await i(e))}if(!(a.phase===`uncertain`&&a.sessionRef)&&a.phase!==`settled`||!a.sessionRef)throw Error(a.error?.code??a.resultCode);let o=a.settledAt??a.requestedAt;return a.phase===`settled`&&!e.deferInitialMessage&&c(e=>{let t=e[a.sessionRef];return{...e,[a.sessionRef]:{...t??{assistant:``,attachments:[],activities:[],complete:!1,error:null},user:n,operationRef:a.operationRef,messageRequestId:r,abortable:!t?.complete&&!!a.operationRef,startedAt:t?.startedAt??o,lastEventAt:t?.lastEventAt??o}}}),await w(),a},[w,T]),O=(0,$.useCallback)(async(e,t,n)=>{let r=f.current;if(!r?.catalogRevision)throw Error(`catalog-unavailable`);let i=t.trim();if(!i)throw Error(`message-empty`);let a=n?.messageRequestId??Wo(`message`),o=n?.attachmentRefs??[],s=h.current[e.sessionRef],l=g.current,u=_.current.get(e.sessionRef)?.operationRef??s?.operationRef??null,d=new Date().toISOString();c(t=>({...t,[e.sessionRef]:xi(t[e.sessionRef],{message:i,attachments:n?.attachments??[],messageRequestId:a,submittedAt:d})}));let p=()=>c(t=>{let n=t[e.sessionRef],r=Ci(n,s,a);if(r===n)return t;let i={...t};return r?i[e.sessionRef]=r:delete i[e.sessionRef],i}),m=(t,n)=>c(r=>ms(r,e.sessionRef,a,t,n)),v=d,y=!1;try{let t=t=>{let r=t.sessions.find(t=>t.sessionRef===e.sessionRef);if(!t.catalogRevision||!r)throw Error(`session-unavailable`);let s=new Date;return v=s.toISOString(),{schemaVersion:1,version:`piagent-session-command-v1`,messageType:`command`,commandId:Wo(`command`),idempotencyKey:Wo(`idempotency`),action:`session.send`,requestedAt:s.toISOString(),expiresAt:new Date(s.getTime()+zo).toISOString(),sessionRef:e.sessionRef,expectedCatalogRevision:t.catalogRevision,expectedSessionRevision:r.sessionRevision,payload:{delivery:`new-operation`,message:i,messageRequestId:a,expectedOperationRef:null,attachmentRefs:o,...n?.workflow?{workflow:n.workflow}:{}}}},s=t(r);y=!0;let c=await T(s);if(Go(c)){let e=await w();e?.catalogRevision&&(s=t(e),c=await T(s))}if(fs(c,null)===`confirmed`)return m({operationRef:c.operationRef,complete:!1},`admitted`),w(),{state:`confirmed`,receipt:c};let d=await E(e.sessionRef,i,v,l,u,a),f=fs(c,d);if(f===`observed`&&d)return m(d,`admitted`),w(),{state:`observed`,receipt:c};if(f===`unconfirmed`)return m({operationRef:null,complete:!0},`unconfirmed`),w(),{state:`unconfirmed`,receipt:c};throw p(),new Vo(c.error?.code??c.resultCode)}catch(t){if(t instanceof Vo)throw t;if(ls(t,y)){let t=await E(e.sessionRef,i,v,l,u,a);return fs(null,t)===`observed`&&t?(m(t,`admitted`),w(),{state:`observed`,receipt:null}):(m({operationRef:null,complete:!0},`unconfirmed`),w(),{state:`unconfirmed`,receipt:null})}throw p(),t}},[E,w,T]),k=(0,$.useCallback)(async e=>{let t=f.current,n=o[e.sessionRef]?.operationRef,r=t?.sessions.find(t=>t.sessionRef===e.sessionRef);if(!t?.catalogRevision||!r||!n||o[e.sessionRef]?.abortable===!1)throw Error(`operation-unavailable`);let i=t=>{let r=t.sessions.find(t=>t.sessionRef===e.sessionRef);if(!t.catalogRevision||!r)throw Error(`operation-unavailable`);let i=new Date;return T({schemaVersion:1,version:`piagent-session-command-v1`,messageType:`command`,commandId:Wo(`command`),idempotencyKey:Wo(`idempotency`),action:`session.abort`,requestedAt:i.toISOString(),expiresAt:new Date(i.getTime()+3e5).toISOString(),sessionRef:e.sessionRef,expectedCatalogRevision:t.catalogRevision,expectedSessionRevision:r.sessionRevision,payload:{operationRef:n,clearQueued:!0}})},a=await i(t);if(Go(a)){let[t,r]=await Promise.all([w(),nt().catch(()=>void 0)]);if(!t||!ki(r,t.gatewayInstanceRef,e.sessionRef,n))throw Error(`operation-unavailable`);a=await i(t)}if(a.phase!==`settled`)throw Error(a.error?.code??a.resultCode);return w(),a},[o,w,T]),A=(0,$.useCallback)(async e=>{let t=async t=>{let n=await w(),r=n?.sessions.find(t=>t.sessionRef===e.sessionRef);if(!n?.catalogRevision||!r)throw Error(`session-unavailable`);let i=new Date,a=await T({schemaVersion:1,version:`piagent-session-command-v1`,messageType:`command`,commandId:Wo(`command`),idempotencyKey:Wo(`idempotency`),action:t,requestedAt:i.toISOString(),expiresAt:new Date(i.getTime()+3e5).toISOString(),sessionRef:e.sessionRef,expectedCatalogRevision:n.catalogRevision,expectedSessionRevision:r.sessionRevision,payload:{}});if(a.phase!==`settled`)throw Error(a.error?.code??a.resultCode);return a};c(t=>({...t,[e.sessionRef]:{...t[e.sessionRef]??{user:``,assistant:``,attachments:[],activities:[],operationRef:null,complete:!0,error:null},runtimeRecovery:`restarting`}}));try{let n=(await w())?.sessions.find(t=>t.sessionRef===e.sessionRef);if(!n)throw Error(`session-unavailable`);n.state===`gateway-owned`&&await t(`session.release`);let r=await t(`session.acquire`);return c(t=>({...t,[e.sessionRef]:{...t[e.sessionRef]??{user:``,assistant:``,attachments:[],activities:[],operationRef:null,complete:!0,error:null},runtimeRecovery:`recovered`}})),await w(),r}catch(t){throw c(t=>({...t,[e.sessionRef]:{...t[e.sessionRef]??{user:``,assistant:``,attachments:[],activities:[],operationRef:null,complete:!0,error:null},runtimeRecovery:`failed`}})),t}},[w,T]),j=(0,$.useCallback)(async(e,t,n)=>{let r=r=>{let i=r?.sessions.find(t=>t.sessionRef===e.sessionRef);if(!r?.catalogRevision||!i)throw Error(`session-unavailable`);let a=new Date;return T({schemaVersion:1,version:`piagent-session-command-v1`,messageType:`command`,commandId:Wo(`command`),idempotencyKey:Wo(`idempotency`),action:t,requestedAt:a.toISOString(),expiresAt:new Date(a.getTime()+3e5).toISOString(),sessionRef:e.sessionRef,expectedCatalogRevision:r.catalogRevision,expectedSessionRevision:i.sessionRevision,payload:n})},i=await r(f.current);for(let e=0;[`session.set-permission`,`session.set-fast`].includes(t)&&Go(i)&&e<2;e++)i=await r(await w());if(i.phase!==`settled`)throw Error(i.error?.code??i.resultCode);return await w(),i},[w,T]),M=(0,$.useCallback)((e,t)=>j(e,`session.set-model`,{modelRef:t}),[j]),N=(0,$.useCallback)((e,t)=>j(e,`session.set-thinking`,{thinkingLevel:t}),[j]),P=(0,$.useCallback)((e,t)=>j(e,`session.set-permission`,{permissionMode:t}),[j]),F=(0,$.useCallback)((e,t)=>j(e,`session.set-fast`,{fast:t}),[j]),I=(0,$.useCallback)(async(e,t,n)=>{let r=r=>{let i=r?.sessions.find(t=>t.sessionRef===e.sessionRef);if(!r?.catalogRevision||!i)throw Error(`session-unavailable`);let a=new Date;return T({schemaVersion:1,version:`piagent-session-command-v1`,messageType:`command`,commandId:Wo(`command`),idempotencyKey:Wo(`idempotency`),action:t,requestedAt:a.toISOString(),expiresAt:new Date(a.getTime()+3e5).toISOString(),sessionRef:e.sessionRef,expectedCatalogRevision:r.catalogRevision,expectedSessionRevision:i.sessionRevision,payload:n})},i=await r(f.current);for(let e=0;t===`session.rename`&&Go(i)&&e<2;e++)i=await r(await w());if(i.phase!==`settled`)throw Error(i.error?.code??i.resultCode);return await w(),i},[w,T]),L=(0,$.useCallback)((e,t)=>I(e,`session.rename`,{title:t}),[I]),R=(0,$.useCallback)((e,t)=>I(e,`session.pin`,{pinned:t}),[I]),z=(0,$.useCallback)(e=>I(e,`session.archive`,{}),[I]),ee=(0,$.useCallback)(e=>I(e,`session.unarchive`,{}),[I]),B=(0,$.useCallback)((e,t)=>I(e,`session.fork`,{entryRef:null,title:t}),[I]);return(0,$.useEffect)(()=>{let e=!1,t,n=0,i=!1,o=os(()=>w()),s=o.request,u=(()=>{try{let e=window.localStorage.getItem(`piagent-gateway-client-ref`);if(e&&/^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/.test(e))return e;let t=Wo(`client`);return window.localStorage.setItem(`piagent-gateway-client-ref`,t),t}catch{return Wo(`client`)}})(),h=()=>{if(e||Le())return;a(n===0?`connecting`:`reconnecting`);let o=window.location.protocol===`https:`?`wss:`:`ws:`,x=new WebSocket(`${o}//${window.location.host}/api/v1/gateway`,`piagent.gateway.v1`);p.current=x,Sn.attach(x);let w=window.setTimeout(()=>x.close(1008,`hello-timeout`),5e3);x.addEventListener(`open`,()=>x.send(JSON.stringify({schemaVersion:1,version:`piagent-gateway-protocol-v1`,messageType:`connect`,clientRef:u,minimumProtocol:1,maximumProtocol:1,lastEventSequence:m.current,catalogRevision:f.current?.catalogRevision??null}))),x.addEventListener(`message`,e=>{let t;try{t=JSON.parse(String(e.data))}catch{x.close(1007,`invalid-json`);return}if(!t||typeof t!=`object`){x.close(1008,`invalid-frame`);return}let o=t;if(o.messageType===`hello`){window.clearTimeout(w);let e=typeof o.capabilities?.gatewayInstanceRef==`string`?o.capabilities.gatewayInstanceRef:null;if(!e||v.current&&e!==v.current){m.current=null,y.current=!0,i=!0,x.close(Bo,`gateway-epoch-changed`);return}v.current=e,n=0,r(o.capabilities),a(`connected`);return}if(o.messageType===`response`){let e=S.current.get(String(o.requestId));if(!e)return;S.current.delete(String(o.requestId)),window.clearTimeout(e.timeout),o.ok===!0&&o.result?e.resolve(o.result):e.reject(new ss(String(o.error?.code??`gateway-request-failed`),!1));return}if(o.messageType!==`event`||!Number.isSafeInteger(o.sequence))return;let u=o.payload,f=typeof o.generatedAt==`string`?o.generatedAt:new Date().toISOString(),p=typeof u.messageRequestId==`string`?u.messageRequestId:null,h=e=>e&&p&&e.messageRequestId&&e.messageRequestId!==p?void 0:e;if(o.kind===`resync.required`){y.current=!0,i=!0,x.close(Bo,`canonical-resync-required`);return}let b=Number(o.sequence),T=m.current;if(!(T!==null&&b<=T)){if(T!==null&&b!==T+1){y.current=!0,i=!0,x.close(Bo,`gateway-event-sequence-gap`);return}if(m.current=b,v.current&&C(v.current,b),typeof u?.sessionRef==`string`&&typeof u.operationRef==`string`&&[`runtime.changed`,`message.delta`,`tool.started`,`tool.completed`,`message.completed`,`operation.settled`].includes(String(o.kind))&&(g.current+=1,_.current.set(u.sessionRef,{serial:g.current,operationRef:u.operationRef,messageRequestId:p,complete:[`message.completed`,`operation.settled`].includes(String(o.kind))})),o.kind===`message.delta`&&typeof u?.sessionRef==`string`&&typeof u.delta==`string`&&l(e=>{let t=h(e[u.sessionRef]);return{...e,[u.sessionRef]:{...t??{user:``,assistant:``,attachments:[],activities:[],complete:!1,error:null},operationRef:u.operationRef,messageRequestId:p??t?.messageRequestId,abortable:!0,complete:!1,delivery:t?.user?`admitted`:t?.delivery,...li(t,u.messageRef,u.delta),startedAt:t?.startedAt??f,lastEventAt:f}}}),[`tool.started`,`tool.completed`].includes(String(o.kind))&&typeof u?.sessionRef==`string`&&typeof u.toolCallRef==`string`&&typeof u.toolLabel==`string`&&c(e=>{let t=h(e[u.sessionRef])??{user:``,assistant:``,attachments:[],activities:[],operationRef:u.operationRef??null,abortable:!0,complete:!1,error:null,runtimeRecovery:null},n=o.kind===`tool.started`?`running`:u.isError===!0?`failed`:`completed`,r=t.activities.find(e=>e.toolCallRef===u.toolCallRef),i=[...t.activities.filter(e=>e.toolCallRef!==u.toolCallRef),{toolCallRef:u.toolCallRef,toolLabel:u.toolLabel,fileLabel:typeof u.fileLabel==`string`?u.fileLabel:r?.fileLabel??null,state:n,reasonCode:u.reasonCode??null,startedAt:r?.startedAt??f,finishedAt:n===`running`?null:f}].slice(-16),a=u.reasonCode===`runtime-restart-required`?`required`:t.runtimeRecovery;return{...e,[u.sessionRef]:{...t,operationRef:u.operationRef??t.operationRef,messageRequestId:p??t.messageRequestId,activities:i,complete:!1,delivery:t.user?`admitted`:t.delivery,runtimeRecovery:a,startedAt:t.startedAt??f,lastEventAt:f}}}),o.kind===`runtime.changed`&&typeof u?.sessionRef==`string`&&c(e=>{let t=[`running`,`paused`,`waiting-approval`].includes(String(u.liveState)),n=h(e[u.sessionRef])??(t&&typeof u.operationRef==`string`?{user:``,assistant:``,attachments:[],activities:[],operationRef:u.operationRef,messageRequestId:p,abortable:!0,complete:!1,settlement:null,error:null,runtimeRecovery:null}:null);if(!n)return e;let r=u.reasonCode===`runtime-restart-required`?`restarting`:u.reasonCode===`runtime-restart-failed`?`failed`:[`required`,`restarting`].includes(String(n.runtimeRecovery))&&u.liveState===`idle`?`recovered`:n.runtimeRecovery;return t?{...e,[u.sessionRef]:{...n,operationRef:u.operationRef??n.operationRef,messageRequestId:p??n.messageRequestId,abortable:!0,complete:!1,settlement:null,delivery:n.user?`admitted`:n.delivery,runtimeRecovery:r,startedAt:n.startedAt??f,lastEventAt:f}}:!n.complete&&u.operationRef===null?{...e,[u.sessionRef]:{...n,assistant:``,activities:[],abortable:!1,complete:!0,settlement:`unknown`,messageRequestId:p??n.messageRequestId,error:u.reasonCode??`operation-settlement-unknown`,runtimeRecovery:r,lastEventAt:f}}:r===n.runtimeRecovery?e:{...e,[u.sessionRef]:{...n,runtimeRecovery:r}}}),o.kind===`message.completed`&&typeof u?.sessionRef==`string`&&c(e=>{let t=h(e[u.sessionRef]);return{...e,[u.sessionRef]:{...t??{user:``,assistant:``,attachments:[],activities:[],operationRef:u.operationRef,error:null},operationRef:u.operationRef,messageRequestId:p??t?.messageRequestId,abortable:!1,complete:!0,settlement:`completed`,delivery:t?.user?`admitted`:t?.delivery,error:null,lastEventAt:f}}}),o.kind===`operation.settled`&&typeof u?.sessionRef==`string`&&typeof u.operationRef==`string`){c(e=>{let t=h(e[u.sessionRef])??{user:``,assistant:``,attachments:[],activities:[],operationRef:u.operationRef,complete:!1,error:null,runtimeRecovery:null};return t.operationRef&&t.operationRef!==u.operationRef?e:{...e,[u.sessionRef]:{...bi(t,{operationRef:u.operationRef,settlement:u.settlement,reasonCode:u.reasonCode}),messageRequestId:p??t.messageRequestId,lastEventAt:f}}});let e=_i({operationRef:u.operationRef,settlement:u.settlement,reasonCode:u.reasonCode,settledAt:o.generatedAt,sequence:b});e&&d(t=>({...t,[u.sessionRef]:vi(t[u.sessionRef]??[],[e])}))}[`catalog.changed`,`session.changed`,`runtime.changed`,`message.completed`,`operation.settled`].includes(String(o.kind))&&s(),[`session.changed`,`tool.completed`,`operation.settled`].includes(String(o.kind))&&typeof u?.sessionRef==`string`&&window.dispatchEvent(new CustomEvent(`piagent-workspace-changed`,{detail:{sessionRef:u.sessionRef}}))}}),x.addEventListener(`close`,()=>{window.clearTimeout(w);for(let e of S.current.values())window.clearTimeout(e.timeout),e.reject(new ss(`gateway-connection-lost`,!0));if(S.current.clear(),!e){if(a(`reconnecting`),i){i=!1,b();return}n+=1,t=window.setTimeout(h,Math.min(5e3,250*2**Math.min(n,5)))}}),x.addEventListener(`error`,()=>{})},b=async()=>{if(e||Le())return;let r=await w({requireLiveState:!0});if(!e){if(r){n=0,h();return}a(`reconnecting`),n+=1,t=window.setTimeout(()=>void b(),Math.min(5e3,250*2**Math.min(n,5)))}};(async()=>{let t=await ze();if(!e){if(t===`failed`){a(`failed`);return}await b()}})();let x=()=>{!e&&document.visibilityState===`visible`&&w()};return document.addEventListener(`visibilitychange`,x),()=>{e=!0,t&&window.clearTimeout(t),o.stop();for(let e of S.current.values())window.clearTimeout(e.timeout),e.reject(new ss(`gateway-client-unmounted`,!0));S.current.clear(),p.current?.close(1e3,`client-unmount`),document.removeEventListener(`visibilitychange`,x)}},[C,w]),{catalog:e,capabilities:n,connection:i,live:o,terminalActivities:u,refresh:w,create:D,send:O,abort:k,restart:A,setModel:M,setThinking:N,setPermission:P,setFast:F,rename:L,pin:R,archive:z,unarchive:ee,fork:B}}async function vs(){let e=await fetch(`/api/v1/preferences`,{credentials:`same-origin`,headers:{Accept:`application/json`}});return e.ok?await e.json():null}async function ys(e){let t=Fe();t&&await Pe(`/api/v1/preferences`,{method:`POST`,credentials:`same-origin`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Piagent-CSRF":t},body:JSON.stringify(e)})}function bs(e,t,n){let r=(0,$.useRef)(!1),i=(0,$.useRef)(t);i.current=t,(0,$.useEffect)(()=>{if(!e||r.current)return;let t=!1;return vs().then(e=>{t||!e||(r.current=!0,e.locale&&n.setLocale(e.locale),e.themeId&&Ae(e.themeId)&&n.setThemeId(e.themeId),(!e.locale||!e.themeId)&&ys({...i.current,...e}).catch(()=>{}))}).catch(()=>{}),()=>{t=!0}},[e]),(0,$.useEffect)(()=>{r.current&&ys(t).catch(()=>{})},[t.locale,t.themeId])}function xs(){let e=_s(),{locale:t,themeId:n,setLocale:r,setThemeId:i}=Oe();return bs(!!e.catalog,{locale:t,themeId:n},{setLocale:r,setThemeId:i}),(0,Q.jsx)(Rt,{children:(0,Q.jsx)(ns,{...e})})}export{xs as default};
97
+ `,Eo=typeof To==`string`?null:ue`
98
+ animation: ${To} 3s infinite linear;
99
+ `,Do=e=>{let{classes:t,variant:n,color:r}=e,i={root:[`root`,`color${W(r)}`,n],dashed:[`dashed`],bar1:[`bar`,`bar1`],bar2:[`bar`,`bar2`,n===`buffer`&&`color${W(r)}`]};return K(i,vo,t)},Oo=(e,t)=>e.vars?e.vars.palette.LinearProgress[`${t}Bg`]:e.palette.mode===`light`?e.lighten(e.palette[t].main,.62):e.darken(e.palette[t].main,.5),ko=H(`span`,{name:`MuiLinearProgress`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,t[`color${W(n.color)}`],t[n.variant]]}})(V(({theme:e})=>({position:`relative`,overflow:`hidden`,display:`block`,height:4,zIndex:0,"@media print":{colorAdjust:`exact`},variants:[...Object.entries(e.palette).filter(B()).map(([t])=>({props:{color:t},style:{backgroundColor:Oo(e,t)}})),{props:({ownerState:e})=>e.color===`inherit`&&e.variant!==`buffer`,style:{"&::before":{content:`""`,position:`absolute`,left:0,top:0,right:0,bottom:0,backgroundColor:`currentColor`,opacity:.3}}},{props:{variant:`buffer`},style:{backgroundColor:`transparent`}},{props:{variant:`query`},style:{transform:`rotate(180deg)`}}]}))),Ao=H(`span`,{name:`MuiLinearProgress`,slot:`Dashed`})(V(({theme:e})=>({position:`absolute`,marginTop:0,height:`100%`,width:`100%`,backgroundSize:`10px 10px`,backgroundPosition:`0 -23px`,variants:[{props:{color:`inherit`},style:{opacity:.3,backgroundImage:`radial-gradient(currentColor 0%, currentColor 16%, transparent 42%)`}},...Object.entries(e.palette).filter(B()).map(([t])=>{let n=Oo(e,t);return{props:{color:t},style:{backgroundImage:`radial-gradient(${n} 0%, ${n} 16%, transparent 42%)`}}})]})),Eo||{animation:`${To} 3s infinite linear`},V(({theme:e})=>t(e,{animation:`none`})||bo)),jo=H(`span`,{name:`MuiLinearProgress`,slot:`Bar1`,overridesResolver:(e,t)=>[t.bar,t.bar1]})(V(({theme:e})=>{let n=t(e,{animation:`none`,left:`30%`,right:`auto`,width:`40%`});return{width:`100%`,position:`absolute`,left:0,bottom:0,top:0,...Y(e,`transform`,{duration:`0.2s`,easing:`linear`}),transformOrigin:`left`,variants:[{props:{color:`inherit`},style:{backgroundColor:`currentColor`}},...Object.entries(e.palette).filter(B()).map(([t])=>({props:{color:t},style:{backgroundColor:(e.vars||e).palette[t].main}})),{props:{variant:`determinate`},style:{...Y(e,`transform`,{duration:`.${yo}s`,easing:`linear`})}},{props:{variant:`buffer`},style:{zIndex:1,...Y(e,`transform`,{duration:`.${yo}s`,easing:`linear`})}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:{width:`auto`}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:So||{animation:`${xo} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite`}},...n?[{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:n}]:[]]}})),Mo=H(`span`,{name:`MuiLinearProgress`,slot:`Bar2`,overridesResolver:(e,t)=>[t.bar,t.bar2]})(V(({theme:e})=>{let n=t(e,{animation:`none`,display:`none`});return{width:`100%`,position:`absolute`,left:0,bottom:0,top:0,...Y(e,`transform`,{duration:`0.2s`,easing:`linear`}),transformOrigin:`left`,variants:[...Object.entries(e.palette).filter(B()).map(([t])=>({props:{color:t},style:{"--LinearProgressBar2-barColor":(e.vars||e).palette[t].main}})),{props:({ownerState:e})=>e.variant!==`buffer`&&e.color!==`inherit`,style:{backgroundColor:`var(--LinearProgressBar2-barColor, currentColor)`}},{props:({ownerState:e})=>e.variant!==`buffer`&&e.color===`inherit`,style:{backgroundColor:`currentColor`}},{props:{color:`inherit`},style:{opacity:.3}},...Object.entries(e.palette).filter(B()).map(([t])=>({props:{color:t,variant:`buffer`},style:{backgroundColor:Oo(e,t),...Y(e,`transform`,{duration:`.${yo}s`,easing:`linear`})}})),{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:{width:`auto`}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:wo||{animation:`${Co} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite`}},...n?[{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:n}]:[]]}})),No=$.forwardRef(function(e,t){let n=ge({props:e,name:`MuiLinearProgress`}),{className:r,color:i=`primary`,max:a,min:s,value:c,valueBuffer:l,variant:u=`indeterminate`,...d}=n,f={...n,color:i,variant:u},p=s??0,m=a??100,h=Do(f),g=Se(),_={},v={bar1:{},bar2:{}};if((u===`determinate`||u===`buffer`)&&c!==void 0){let e=m-p,t=(c-p)/e*100-100;g&&(t=-t),v.bar1.transform=e>0?`translateX(${t}%)`:`translateX(-100%)`,_[`aria-valuenow`]=c,_[`aria-valuemin`]=p,_[`aria-valuemax`]=m}if(u===`buffer`&&l!==void 0){let e=m-p,t=(l-p)/e*100-100;g&&(t=-t),v.bar2.transform=e>0?`translateX(${t}%)`:`translateX(-100%)`}return(0,Q.jsxs)(ko,{className:o(h.root,r),ownerState:f,role:`progressbar`,..._,ref:t,...d,children:[u===`buffer`?(0,Q.jsx)(Ao,{className:h.dashed,ownerState:f}):null,(0,Q.jsx)(jo,{className:h.bar1,ownerState:f,style:v.bar1}),u===`determinate`?null:(0,Q.jsx)(Mo,{className:h.bar2,ownerState:f,style:v.bar2})]})}),Po=`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,Fo={A:`success`,M:`warning`,D:`error`,R:`info`,C:`info`,U:`success`};function Io({title:e,action:t,children:n}){return(0,Q.jsxs)(R,{component:`section`,sx:{px:2,py:1.75,borderBottom:1,borderColor:`divider`},children:[(0,Q.jsxs)(P,{direction:`row`,sx:{alignItems:`center`,justifyContent:`space-between`,mb:1},children:[(0,Q.jsx)(S,{variant:`caption`,color:`text.secondary`,sx:{fontWeight:650,textTransform:`uppercase`,letterSpacing:`.06em`},children:e}),t]}),n]})}var Lo=3e3;function Ro({session:e,snapshot:t,live:n,locale:r,onOpenReview:i,onClose:o}){let[s,c]=(0,$.useState)(),[l,u]=(0,$.useState)(!1),d=!!(n&&!n.complete);(0,$.useEffect)(()=>{let t=new AbortController;u(!1);let n,r=()=>void Ke(e.sessionRef,`working-tree`,t.signal).then(e=>{t.signal.aborted||(c(e),u(!1))}).catch(()=>{!t.signal.aborted&&!d&&u(!0)}).finally(()=>{d&&!t.signal.aborted&&(n=window.setTimeout(r,Lo))});return n=window.setTimeout(r,250),()=>{window.clearTimeout(n),t.abort()}},[e.sessionRef,e.sessionRevision,d]),(0,$.useEffect)(()=>{c(void 0)},[e.sessionRef]);let f=s?.files??[],p=f.reduce((e,t)=>e+(t.stats?.additions??0),0),m=f.reduce((e,t)=>e+(t.stats?.deletions??0),0),g=t?.usage.context,_=g?.state===`known`,v=_?g.percent:e.contextUsage.ratio===null?null:e.contextUsage.ratio*100,y=_?g.contextWindow:e.contextUsage.contextWindow,b=_?g.tokens:e.contextUsage.usedTokens,x=e.managedHelpers?.maximum===0?void 0:e.managedHelpers,C=e.managedPlan,w=e.managedProcess,T=C?.steps.filter(e=>e.status===`completed`).length??0,E=(n?.activities??[]).filter(e=>Oa(e.toolLabel)===`subagent`);return(0,Q.jsxs)(R,{role:`region`,sx:{height:`100%`,overflowY:`auto`,bgcolor:`background.paper`},"aria-label":X(r,`Thay đổi và ngữ cảnh`,`Changes and context`),children:[(0,Q.jsxs)(P,{direction:`row`,sx:{alignItems:`center`,gap:1,px:2,minHeight:52,borderBottom:1,borderColor:`divider`},children:[(0,Q.jsx)(S,{sx:{fontWeight:600,flex:1},children:X(r,`Workspace`,`Workspace`)}),o&&(0,Q.jsx)(L,{size:`small`,"aria-label":X(r,`Đóng khung bên`,`Close side panel`),onClick:o,children:(0,Q.jsx)(h,{fontSize:`small`})})]}),(0,Q.jsxs)(Io,{title:s?X(r,`Thay đổi · ${f.length} file`,`Changes · ${f.length} files`):X(r,`Thay đổi`,`Changes`),action:f.length>0?(0,Q.jsx)(pe,{title:X(r,`Xem diff đầy đủ, stage hoặc hoàn tác`,`Full diff, stage or revert`),children:(0,Q.jsx)(a,{size:`small`,startIcon:(0,Q.jsx)(O,{fontSize:`small`}),onClick:i,children:X(r,`Review`,`Review`)})}):void 0,children:[(p>0||m>0)&&(0,Q.jsxs)(P,{direction:`row`,sx:{alignItems:`center`,gap:.75,mb:1,color:`text.secondary`},children:[(0,Q.jsx)(va,{sx:{fontSize:15}}),(0,Q.jsx)(S,{variant:`caption`,children:X(r,`Chưa commit`,`Uncommitted`)}),(0,Q.jsxs)(S,{variant:`caption`,sx:{fontFamily:Po,ml:`auto`},children:[(0,Q.jsxs)(R,{component:`span`,sx:Et(`success`),children:[`+`,p]}),` `,(0,Q.jsxs)(R,{component:`span`,sx:Et(`error`),children:[`−`,m]})]})]}),d&&(0,Q.jsx)(S,{variant:`caption`,color:`text.secondary`,role:`status`,sx:{display:`block`,mb:.75},children:X(r,`Agent đang chạy · cập nhật trực tiếp. Thấy sai thì bấm Dừng.`,`The agent is running · updating live. Stop it if it goes wrong.`)}),s===void 0&&!l&&(0,Q.jsx)(No,{sx:{borderRadius:1}}),(l||s?.availability.state===`unavailable`)&&(0,Q.jsx)(S,{variant:`body2`,color:`text.secondary`,children:X(r,`Chưa đọc được thay đổi (thư mục có thể không phải git repo).`,`Changes are unavailable (the folder may not be a git repository).`)}),s&&s.availability.state!==`unavailable`&&f.length===0&&(0,Q.jsx)(S,{variant:`body2`,color:`text.secondary`,children:X(r,`Chưa có thay đổi nào chưa commit.`,`No uncommitted changes.`)}),(0,Q.jsx)(P,{spacing:.25,children:f.slice(0,200).map(e=>(0,Q.jsxs)(P,{direction:`row`,sx:{alignItems:`center`,gap:1,py:.4},children:[(0,Q.jsx)(S,{variant:`caption`,sx:{fontFamily:Po,fontWeight:650,width:12,...Fo[e.status]?Et(Fo[e.status]):{color:`text.secondary`}},children:e.status}),(0,Q.jsx)(S,{variant:`body2`,noWrap:!0,title:e.path,sx:{fontFamily:Po,fontSize:12.5,flex:1,minWidth:0},children:e.path}),(0,Q.jsxs)(S,{variant:`caption`,sx:{fontFamily:Po,flexShrink:0},children:[(e.stats?.additions??0)>0&&(0,Q.jsxs)(R,{component:`span`,sx:Et(`success`),children:[`+`,e.stats.additions,` `]}),(e.stats?.deletions??0)>0&&(0,Q.jsxs)(R,{component:`span`,sx:Et(`error`),children:[`−`,e.stats.deletions]})]})]},e.fileRef))})]}),(C||w)&&(0,Q.jsxs)(Io,{title:C?X(r,`Plan · ${T}/${C.steps.length}`,`Plan · ${T}/${C.steps.length}`):X(r,`Tiến trình`,`Process`),children:[C&&(0,Q.jsx)(P,{component:`ol`,spacing:.25,sx:{m:0,p:0,listStyle:`none`},"aria-label":X(r,`Plan của agent`,`Agent plan`),children:C.steps.map((e,t)=>{let n=e.status===`completed`?ho:e.status===`in_progress`?go:e.status===`deferred`?_o:mo;return(0,Q.jsxs)(P,{component:`li`,direction:`row`,sx:{alignItems:`flex-start`,gap:.75,py:.25},"aria-label":`${e.step}: ${e.status===`completed`?X(r,`xong`,`done`):e.status===`in_progress`?X(r,`đang làm`,`in progress`):e.status===`deferred`?X(r,`để sau`,`left for later`):X(r,`chưa làm`,`pending`)}`,children:[(0,Q.jsx)(n,{sx:{fontSize:16,mt:.2,color:e.status===`in_progress`?`primary.main`:`text.secondary`}}),(0,Q.jsx)(S,{variant:`body2`,sx:{flex:1,minWidth:0,overflowWrap:`anywhere`,...e.status===`completed`?{color:`text.secondary`,textDecoration:`line-through`}:e.status===`deferred`?{color:`text.disabled`,fontStyle:`italic`}:{},...e.status===`in_progress`?{fontWeight:600}:{}},children:e.step})]},t)})}),w&&w.outcome!==`no_change`&&(0,Q.jsxs)(S,{variant:`body2`,role:`status`,sx:{mt:+!!C,...Et(jt(w))},children:[X(r,`Lượt sửa code gần nhất: `,`Last code-changing turn: `),Nt(w,r)]})]}),(0,Q.jsxs)(Io,{title:X(r,`Ngữ cảnh`,`Context`),children:[(0,Q.jsxs)(P,{direction:`row`,sx:{justifyContent:`space-between`,mb:.75},children:[(0,Q.jsx)(S,{variant:`body2`,children:v==null?`—`:`${Math.round(v)}%`}),(0,Q.jsxs)(S,{variant:`caption`,color:`text.secondary`,children:[b?Li(b):`—`,y?` / ${Li(y)}`:``]})]}),(0,Q.jsx)(No,{variant:`determinate`,value:Math.min(100,Math.max(0,v??0)),sx:{height:6,borderRadius:1},color:(v??0)>85?`warning`:`primary`,"aria-label":X(r,`Mức dùng ngữ cảnh`,`Context usage`)})]}),(x||E.length>0)&&(0,Q.jsxs)(Io,{title:`Subagent`,children:[x&&(0,Q.jsx)(S,{variant:`body2`,color:`text.secondary`,sx:{mb:E.length?.75:0},children:X(r,`${x.active??0}/${x.maximum} đang chạy`,`${x.active??0}/${x.maximum} running`)}),E.map(e=>(0,Q.jsxs)(P,{direction:`row`,sx:{alignItems:`center`,gap:.75,py:.25},children:[(0,Q.jsx)(ha,{sx:{fontSize:15,color:`text.secondary`}}),(0,Q.jsx)(S,{variant:`body2`,sx:{flex:1},children:e.fileLabel??`subagent`}),(0,Q.jsx)(S,{variant:`caption`,color:e.state===`failed`?`error`:`text.secondary`,children:e.state===`running`?X(r,`đang chạy`,`running`):e.state===`failed`?X(r,`lỗi`,`failed`):X(r,`xong`,`done`)})]},e.toolCallRef))]})]})}function zo(e){let{locale:t,actions:n}=e,r=X(t,`Lệnh`,`Commands`),i=At(),a=[];e.canCreate&&a.push({id:`new-chat`,group:r,label:X(t,`Cuộc trò chuyện mới`,`New chat`),hint:`${i} ⇧ O`,keywords:`new create tạo`,run:n.newChat}),e.update.available&&e.update.latest&&a.push({id:`update-now`,group:r,label:X(t,`Cập nhật Piagent ${e.update.latest}`,`Update Piagent ${e.update.latest}`),keywords:`update upgrade nâng cấp phiên bản version`,run:()=>n.settings(`updates`)}),a.push({id:`check-updates`,group:r,label:X(t,`Kiểm tra cập nhật`,`Check for updates`),keywords:`update version phiên bản pi piagent`,run:n.checkUpdates}),e.hasSelection&&a.push({id:`toggle-panel`,group:r,label:X(t,`Bật/tắt khung Workspace`,`Toggle the Workspace panel`),keywords:`panel sidebar changes plan context`,run:n.togglePanel},{id:`open-changes`,group:r,label:X(t,`Mở Source Changes`,`Open Source Changes`),keywords:`diff review thay đổi git`,run:n.openChanges}),a.push({id:`theme`,group:r,label:e.colorMode===`dark`?X(t,`Chuyển sang chủ đề sáng`,`Switch to the light theme`):X(t,`Chuyển sang chủ đề tối`,`Switch to the dark theme`),keywords:`theme chủ đề dark light sáng tối`,run:()=>n.setColorMode(e.colorMode===`dark`?`light`:`dark`)},{id:`language`,group:r,label:t===`vi`?`Switch the interface to English`:`Chuyển giao diện sang tiếng Việt`,keywords:`language ngôn ngữ english tiếng việt`,run:()=>n.setLocale(t===`vi`?`en`:`vi`)},{id:`refresh`,group:r,label:X(t,`Làm mới`,`Refresh`),keywords:`reload tải lại`,run:n.refresh});let o=n.setTheme,s=X(t,`Chủ đề màu`,`Color theme`);if(o)for(let t of ke)a.push({id:`theme-${t.id}`,group:s,label:`${s}: ${t.label}`,hint:t.id===e.themeId?`✓`:void 0,keywords:`theme chủ đề màu color ${t.mode}`,run:()=>o(t.id)});let c=X(t,`Cài đặt`,`Settings`);for(let e of Pt(t))a.push({id:`settings-${e.id}`,group:c,label:`${c}: ${e.label}`,hint:e.id===`general`?`${i} ,`:void 0,keywords:e.keywords,run:()=>n.settings(e.id)});let l=X(t,`Cuộc trò chuyện`,`Conversations`);for(let t of e.sessions)a.push({id:`session-${t.sessionRef}`,group:l,label:t.title,hint:t.projectLabel,keywords:t.projectLabel,run:()=>n.openSession(t.sessionRef)});return a}var Bo=`piagent-gateway-event-cursor-v1`,Vo=3e4,Ho=12e4,Uo=4001,Wo=class extends Error{reasonCode;constructor(e){super(e),this.name=`SessionSendRejectedError`,this.reasonCode=e}};function Go(e,t){if(!e)return null;try{let n=JSON.parse(e);return n.gatewayInstanceRef===t&&Number.isSafeInteger(n.sequence)&&Number(n.sequence)>=0?Number(n.sequence):null}catch{return null}}function Ko(e,t){if(t!==null)try{window.sessionStorage.setItem(Bo,JSON.stringify({gatewayInstanceRef:e,sequence:t}))}catch{}}function qo(e){return`${e}_${crypto.randomUUID().replaceAll(`-`,``)}`}function Jo(e){return e.phase===`rejected`&&e.resultCode===`stale-revision`&&e.error?.code===`session-revision-stale`}var Yo=(0,$.lazy)(()=>Me(()=>import(`./SettingsPage-CxpZ7cdM.js`).then(e=>({default:e.SettingsPage})),__vite__mapDeps([17,1,2,3,12,5,18,19]))),Xo=(0,$.lazy)(()=>Me(()=>import(`./SessionInspectorDrawer-BJ94aQ6y.js`).then(e=>({default:e.SessionInspectorDrawer})),__vite__mapDeps([20,1,2,3,7,8]))),Zo=272,Qo=52,$o=320,es=`min(44vw, 860px)`,ts=`piagent-webui-workspace-panel`;function ns({session:e,live:t,locale:n}){let r=Ft(e,t),[i,a]=r===`running`?[X(n,`Đang chạy`,`Running`),`primary`]:r===`elsewhere`?[X(n,`Đang chạy ở nơi khác`,`Running elsewhere`),`info`]:r===`attention`?zt(e,t)===`question`?[X(n,`Cần bạn trả lời`,`Needs your answer`),`warning`]:[X(n,`Cần duyệt`,`Needs approval`),`warning`]:r===`recovery`?[X(n,`Cần khôi phục`,`Recovery needed`),`error`]:r===`failed`?[X(n,`Lượt cuối lỗi`,`Last turn failed`),`error`]:[X(n,`Sẵn sàng`,`Ready`),`default`],o=a==="default"?`text.disabled`:a===`info`?`info.main`:`${a}.main`;return(0,Q.jsxs)(R,{role:`status`,sx:{display:`inline-flex`,alignItems:`center`,gap:.75,height:28,px:1.1,borderRadius:999,whiteSpace:`nowrap`,fontSize:12.5,fontWeight:550,color:a==="default"?`text.secondary`:o,bgcolor:`action.hover`},children:[(0,Q.jsx)(R,{component:`span`,"aria-hidden":`true`,sx:{width:7,height:7,borderRadius:`50%`,bgcolor:o}}),i]})}function rs({session:e,snapshot:t,locale:n,live:r,canSend:i,canRestart:o,send:s,abort:c,restart:l,onInspector:u,commandActions:d}){let f=e.sessionRef,p=hn(f),[m,h]=(0,$.useState)(()=>mn(f)),[g,_]=(0,$.useState)(!1),[y,b]=(0,$.useState)(),x=e=>{h(e),yn(f,e)},C=e.modelLabel===`agent-watch-auto`,w=!!(r&&!r.complete),T=Rr({locale:n,company:C,running:w,pinned:e.pinned,bypass:e.managedBypass===!0,fast:e.managedFast===`on`||e.managedFast===`off`?e.managedFast:null,thinkingLevels:e.managedThinkingLevels??(C?[]:[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`]),loadModels:()=>He().then(e=>e.models.map(e=>({modelRef:e.modelRef,label:e.displayName}))),actions:{...d,stop:c}}),E=T.map(e=>({kind:`command`,name:e.name,argumentHint:e.argumentHint,origin:`piagent`,scope:`project`,description:e.description})),[D,O]=(0,$.useState)(null),[k,A]=(0,$.useState)(null);(0,$.useEffect)(()=>{let e=e=>{e.isComposing||k||(e.key===`Escape`&&w&&!e.metaKey&&!e.ctrlKey?(e.preventDefault(),c()):e.key===`/`&&(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&i&&(e.preventDefault(),x(`/`),requestAnimationFrame(()=>{let e=j.inputRef.current;e?.focus(),e?.setSelectionRange(1,1)})))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)});let j=Or({projectRef:e.projectRef,value:m,locale:n,builtIns:E,onChange:e=>{x(e),ie(null)}});(0,$.useEffect)(()=>{let e=e=>{e.detail===f&&(h(mn(f)),requestAnimationFrame(()=>j.inputRef.current?.focus()))};return window.addEventListener(bn,e),()=>window.removeEventListener(bn,e)},[f]);let[M,N]=(0,$.useState)(()=>p?.attachments??[]),[F,I]=(0,$.useState)(!1),[z,ee]=(0,$.useState)(()=>p?.messageRequestId??`message-request.${crypto.randomUUID()}`),[B,te]=(0,$.useState)(!1),[ne,V]=(0,$.useState)(null),[H,ie]=(0,$.useState)(null),[U,ae]=(0,$.useState)(()=>p?.sendUnconfirmed??!1);(0,$.useEffect)(()=>{_n(f,M.length||U?{attachments:M,messageRequestId:z,sendUnconfirmed:U}:null)},[f,M,z,U]),(0,$.useEffect)(()=>{if(!U)return;let e=window.setTimeout(()=>{ae(!1),ie({tone:`error`,text:X(n,`Tin nhắn chưa được gửi: phiên chưa nhận nó trong 2 phút nên nó sẽ không chạy nữa. Nội dung vẫn còn; bấm Gửi để thử lại.`,`The message was not sent: the session did not take it within 2 minutes, so it will not run. Your message is kept; send it again.`)})},Ho+15e3);return()=>window.clearTimeout(e)},[U,n]);let[oe,W]=(0,$.useState)(!1),[G,se]=(0,$.useState)(null),[ce,le]=(0,$.useState)(!1),[ue,fe]=(0,$.useState)(0),K=(0,$.useRef)(0);(0,$.useEffect)(()=>{let e=e=>{pn(e.dataTransfer)&&e.preventDefault()};return window.addEventListener(`dragover`,e),window.addEventListener(`drop`,e),()=>{window.removeEventListener(`dragover`,e),window.removeEventListener(`drop`,e)}},[]);let me=t?.capabilities.capabilities.attachments,he=(0,$.useMemo)(()=>new Set(me?.status===`available`?me.mimeTypes:[]),[me]),ge=(0,$.useMemo)(()=>nn(he),[he]),_e=!!t&&me?.status===`available`&&i&&!g&&!U&&!B&&M.length<4,q=async r=>{if(!(!r?.length||!t||me?.status!==`available`||B)){te(!0),V(null);try{let i=await Kt({files:r,snapshot:t,messageRequestId:z,existing:M,allowed:he,locale:n,stage:t=>Ye(e.sessionRef,t)});N(i.attachments),V(i.status)}catch{V(X(n,`Không thể đính kèm; file không được gửi vào Pi.`,`Unable to attach the file; it was not sent to Pi.`))}finally{te(!1)}}},ve=async r=>{if(!(!t||g||B)){te(!0),V(null);try{let i=await un({snapshot:t,messageRequestId:z,attachmentRef:r,locale:n,stage:t=>Ye(e.sessionRef,t)});i.discarded?N(e=>e.filter(e=>e.attachmentRef!==r)):V(i.status)}catch{V(X(n,`Không thể bỏ file; trạng thái session có thể đã thay đổi.`,`Unable to remove the file; session state may have changed.`))}finally{te(!1)}}};(0,$.useEffect)(()=>{let t=new AbortController;return b(void 0),Ve(e.sessionRef,t.signal).then(b).catch(()=>void 0),()=>t.abort()},[e.sessionRef,e.sessionRevision]);let J=(0,$.useRef)(!1),ye=async()=>{let e=m;if(!e.trim()||g||U||J.current)return;let t=M.length===0?Fr(e,T):null;if(t){ie(null),O(null);let e=await t.command.run(t.argument);if(`confirm`in e){A(e.confirm),x(``);return}if(!(`send`in e)){O(e),e.tone!==`warning`&&x(``);return}}J.current=!0,_(!0),ie(null);let r=M.map(e=>e.attachmentRef);try{if((await s(e,r.length>0?{messageRequestId:z,attachmentRefs:r,attachments:M}:void 0)).state===`unconfirmed`){_n(f,{attachments:M,messageRequestId:z,sendUnconfirmed:!0}),ae(!0),ie({tone:`warning`,text:X(n,`Piagent đang xác nhận lần gửi này. Nội dung và file vẫn được giữ; đừng gửi lại để tránh chạy trùng.`,`Piagent is confirming this send. Your message and files remain preserved; do not resend, to avoid a duplicate run.`)});return}x(``),N([]),V(null),ee(`message-request.${crypto.randomUUID()}`),_n(f,null)}catch{ie({tone:`error`,text:X(n,`Tin nhắn chưa được gửi. Nội dung và file vẫn được giữ; có thể thử lại khi session sẵn sàng.`,`The message was not sent. Your message and files are preserved; retry when the session is ready.`)})}finally{J.current=!1,_(!1)}};(0,$.useEffect)(()=>{!U||r?.messageRequestId!==z||r.delivery!==`admitted`||(x(``),N([]),V(null),ie(null),ae(!1),ee(`message-request.${crypto.randomUUID()}`))},[r?.delivery,r?.messageRequestId,z,U]);let Y=async()=>{if(!(g||U)){_(!0),ie(null);try{await s(X(n,`tiếp tục`,`continue`))}catch{ie({tone:`error`,text:X(n,`Chưa gửi được. Thử lại khi session sẵn sàng.`,`Not sent. Retry when the session is ready.`)})}finally{_(!1)}}},be=async t=>{if(t){b(t);return}b(await Ve(e.sessionRef).catch(()=>y))},xe=async()=>{if(!oe){W(!0),se(null);try{await l()}catch(e){se(e instanceof Error?e.message:null)}finally{W(!1)}}},Se=r?.runtimeRecovery??(e.state===`recovery-required`?`stale`:null);return(0,Q.jsxs)(R,{sx:{minHeight:`calc(100vh - 88px - var(--piagent-status-bar, 0px))`,display:`flex`,flexDirection:`column`},children:[(0,Q.jsxs)(R,{sx:{flex:1,width:`100%`,maxWidth:860,mx:`auto`,px:{xs:2,sm:4},py:{xs:3,md:4},display:`flex`,flexDirection:`column`,justifyContent:`flex-end`},children:[!i&&e.modelLabel===`agent-watch-auto`&&(0,Q.jsx)(gr,{locale:n,onConnected:()=>fe(e=>e+1)},e.sessionRef),(0,Q.jsx)(R,{sx:{width:`100%`},children:(0,Q.jsx)(ao,{reload:ue,sessionRef:e.sessionRef,sessionRevision:e.sessionRevision,live:r,approvals:t?.approvals,locale:n,onOpenActivity:()=>u(`activity`),onContinue:i&&!g&&!U&&e.liveState!==`running`&&(!r||r.complete)?()=>void Y():void 0},e.sessionRef)})]}),(0,Q.jsxs)(R,{sx:{position:`sticky`,bottom:`var(--piagent-status-bar, 0px)`,px:{xs:1.5,sm:2.5},pb:2.5,background:`linear-gradient(transparent, var(--piagent-palette-background-default) 25%)`},children:[(0,Q.jsx)(Bn,{session:e,locale:n}),e.state===`terminal-owned`&&(0,Q.jsx)(v,{severity:`info`,role:`status`,sx:{maxWidth:820,mx:`auto`,mb:1},children:X(n,`Cuộc trò chuyện này đang chạy trong Terminal hoặc một tiến trình Piagent khác. Trang này tự cập nhật để bạn theo dõi; gửi tin nhắn khi nó chạy xong.`,`This conversation is running in Terminal or another Piagent process. This page follows it; send a message when it has finished.`)}),Se&&(0,Q.jsx)(v,{severity:Se===`recovered`?`success`:Se===`failed`?`error`:`warning`,action:(Se===`failed`||Se===`required`||Se===`stale`)&&o&&e.liveState!==`running`?(0,Q.jsx)(a,{color:`inherit`,size:`small`,disabled:oe,onClick:()=>void xe(),children:oe?X(n,`Đang khởi động…`,`Restarting…`):X(n,`Khởi động lại phiên`,`Restart session`)}):void 0,sx:{maxWidth:860,mx:`auto`,mb:1},children:Se===`recovered`?X(n,`Runtime mới đã được xác minh; lịch sử và context của session được giữ nguyên.`,`The new runtime is verified; session history and context were preserved.`):Se===`failed`?G?.startsWith(`company-`)&&sr(G,null,n)?`${sr(G,null,n).title}: ${sr(G,null,n).text}`:X(n,`Runtime đã đổi nhưng chưa khởi động lại được. Hãy dùng nút bên cạnh hoặc restart Dashboard.`,`The runtime changed but could not restart. Use the action here or restart the Dashboard.`):Se===`stale`&&[`session-runtime-open-failed`,`session-runtime-dispose-failed`].includes(e.reasonCode??``)?X(n,`Runtime của phiên này chưa mở được (thường do key, Harness hoặc Agent Watch lúc đó). Bấm Khởi động lại phiên để thử lại, hoặc lưu trữ phiên; lịch sử được giữ nguyên.`,`This session's runtime did not open (usually the key, the Harness or Agent Watch at the time). Restart the session to try again, or archive it; its history is kept.`):Se===`stale`?X(n,`Phiên này chưa được đóng đúng cách và có thể đang mở ở cửa sổ Terminal khác. Đóng cửa sổ đó (nếu có) rồi bấm Khởi động lại phiên để làm tiếp; lịch sử được giữ nguyên.`,`This session was not closed cleanly and may still be open in a Terminal window. Close it (if any), then restart the session to go on; its history is kept.`):Se===`restarting`?X(n,`Runtime vừa được cập nhật. Piagent đang khởi động lại session an toàn sau lượt hiện tại.`,`The runtime was updated. Piagent is safely restarting the session after the current turn.`):X(n,`Phát hiện runtime mới. Piagent sẽ giữ câu trả lời hiện tại rồi tự khởi động lại session.`,`A new runtime was detected. Piagent will preserve the current response and restart the session automatically.`)}),(0,Q.jsxs)(R,{sx:{position:`relative`,maxWidth:860,mx:`auto`,border:1,borderColor:ce?`primary.main`:`divider`,borderStyle:ce?`dashed`:`solid`,borderRadius:2,bgcolor:`background.paper`,px:1.5,pt:1.25,pb:1,boxShadow:`0 12px 40px -18px rgba(0,0,0,.5)`,transition:`border-color .16s, box-shadow .16s`,"&:focus-within":{borderColor:`rgba(var(--piagent-palette-primary-mainChannel) / .55)`,boxShadow:`0 0 0 3px rgba(var(--piagent-palette-primary-mainChannel) / .14), 0 12px 40px -18px rgba(0,0,0,.5)`}},onDragEnter:e=>{pn(e.dataTransfer)&&(K.current+=1,le(!0))},onDragOver:e=>{pn(e.dataTransfer)&&(e.preventDefault(),e.dataTransfer.dropEffect=_e?`copy`:`none`)},onDragLeave:e=>{pn(e.dataTransfer)&&(--K.current,K.current<=0&&(K.current=0,le(!1)))},onDrop:e=>{pn(e.dataTransfer)&&(e.preventDefault(),K.current=0,le(!1),_e&&q(e.dataTransfer.files))},children:[ce&&(0,Q.jsxs)(R,{role:`status`,sx:{position:`absolute`,inset:0,zIndex:3,display:`grid`,alignContent:`center`,justifyItems:`center`,gap:.5,borderRadius:1,bgcolor:`background.paper`,opacity:.96,pointerEvents:`none`,textAlign:`center`},children:[(0,Q.jsx)(S,{sx:{fontWeight:650},children:_e?X(n,`Thả tài liệu vào đây`,`Drop documents here`):M.length>=4?X(n,`Đã đủ 4 file cho tin nhắn này`,`This message already holds 4 files`):X(n,`Chưa nhận file lúc này`,`Files cannot be attached right now`)}),_e&&(0,Q.jsx)(S,{variant:`caption`,color:`text.secondary`,children:$t(n)})]}),M.length>0&&(0,Q.jsx)(P,{direction:`row`,sx:{flexWrap:`wrap`,gap:.75,px:.5,pb:.75},"aria-label":X(n,`File sẽ gửi cùng tin nhắn`,`Files to send with the message`),children:M.map(e=>(0,Q.jsx)(Ce,{size:`small`,variant:`outlined`,color:e.kind===`document`?`success`:`default`,avatar:e.kind===`image`&&qt(e.attachmentRef)?(0,Q.jsx)($n,{variant:`rounded`,alt:``,src:qt(e.attachmentRef)}):void 0,label:`${e.displayName} · ${en(e,n)}`,onDelete:g||U||B?void 0:()=>void ve(e.attachmentRef),deleteIcon:(0,Q.jsx)(Hn,{"aria-label":`${X(n,`Bỏ`,`Remove`)} ${e.displayName}`,role:`button`})},e.attachmentRef))}),D&&(0,Q.jsx)(v,{severity:D.tone,onClose:()=>O(null),sx:{mb:.75,whiteSpace:`pre-line`},children:D.text}),(0,Q.jsx)(re,{fullWidth:!0,multiline:!0,minRows:2,disabled:!i||g||U,value:m,inputRef:j.inputRef,...j.inputProps,onChange:e=>{x(e.target.value),ie(null),j.track(e)},onKeyDown:e=>{j.onKeyDown(e)||_r(e)&&(e.preventDefault(),ye())},onPaste:e=>{e.clipboardData?.files.length&&(e.preventDefault(),_e&&q(e.clipboardData.files))},placeholder:X(n,`Nhắn cho Piagent… (@ để chọn file, folder)`,`Message Piagent… (@ for files and folders)`),variant:`standard`,slotProps:{input:{disableUnderline:!0},htmlInput:j.htmlInput}}),j.menu,(0,Q.jsx)(lt,{open:k!==null,title:k?.title??``,description:k?.description??``,confirmLabel:k?.confirmLabel??``,cancelLabel:X(n,`Huỷ`,`Cancel`),onCancel:()=>A(null),onConfirm:()=>{let e=k;A(null),e&&e.run().then(O)}}),(0,Q.jsx)(or,{in:F,id:`piagent-message-options`,children:(0,Q.jsxs)(R,{sx:{mt:.65,p:.85,borderRadius:1,bgcolor:`action.hover`},children:[(0,Q.jsx)(st,{session:e,snapshot:t,connections:y,locale:n,onOpenChanges:()=>u(`source`),onConnectionsChanged:be}),(0,Q.jsx)(P,{direction:`row`,sx:{minWidth:0,alignItems:`center`,gap:.75,flexWrap:`wrap`},children:me?.status===`available`&&(0,Q.jsx)(pe,{title:X(n,`Chọn file, hoặc kéo thả / dán thẳng vào khung chat`,`Pick a file, or drag and drop / paste straight into the chat`),children:(0,Q.jsxs)(a,{component:`label`,size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(Vn,{}),disabled:!_e,"aria-label":`${X(n,`Đính kèm`,`Attach`)} (${M.length}/4)`,children:[X(n,`Đính kèm`,`Attach`),(0,Q.jsx)(`input`,{type:`file`,multiple:!0,hidden:!0,disabled:!_e,accept:ge||void 0,onChange:e=>{q(e.target.files),e.currentTarget.value=``}})]})})})]})}),(0,Q.jsxs)(P,{direction:`row`,sx:{justifyContent:`space-between`,alignItems:`center`,mt:.5,gap:1},children:[(0,Q.jsxs)(P,{direction:`row`,sx:{minWidth:0,alignItems:`center`,gap:1},children:[(0,Q.jsx)(pe,{title:F?X(n,`Ẩn tùy chọn`,`Hide options`):X(n,`File và công cụ`,`Files and tools`),children:(0,Q.jsx)(L,{size:`small`,"aria-label":F?X(n,`Ẩn tùy chọn`,`Hide options`):X(n,`Thêm tùy chọn`,`More options`),"aria-expanded":F,"aria-controls":`piagent-message-options`,onClick:()=>I(e=>!e),sx:{bgcolor:F?`action.selected`:`transparent`},children:(0,Q.jsx)(de,{fontSize:`small`,sx:{transition:`transform .16s ease`,transform:F?`rotate(45deg)`:`none`}})})}),(0,Q.jsx)(S,{variant:`caption`,color:ne||H?.tone===`error`?`error`:H?`warning.main`:`text.disabled`,noWrap:!H,sx:{display:{xs:ne||H||B?`block`:`none`,sm:`block`}},children:H?.text??ne??(B?X(n,`Đang đọc tài liệu…`,`Reading documents…`):r&&!r.complete?X(n,`Esc để dừng · gửi việc tiếp khi lượt này xong`,`Esc to stop · send the next task when this turn ends`):i?X(n,`Enter để gửi · Shift+Enter xuống dòng`,`Enter to send · Shift+Enter for a new line`):X(n,`Session hiện chỉ đọc`,`Session is currently read only`))})]}),r?.operationRef&&!r.complete&&r.abortable!==!1?(0,Q.jsx)(a,{color:`error`,variant:`outlined`,size:`small`,startIcon:(0,Q.jsx)(Gn,{}),onClick:()=>void c(),sx:{borderRadius:999},children:X(n,`Dừng`,`Stop`)}):(0,Q.jsx)(L,{"aria-label":X(n,`Gửi`,`Send`),disabled:!i||g||U||!m.trim(),color:`primary`,onClick:()=>void ye(),sx:{width:32,height:32,borderRadius:999,bgcolor:`primary.main`,color:`primary.contrastText`,transition:`transform .12s, background-color .16s`,"&:hover":{bgcolor:`primary.main`,color:`primary.contrastText`,transform:`translateY(-1px)`},"&.Mui-disabled":{bgcolor:`action.disabledBackground`}},children:(0,Q.jsx)(Un,{fontSize:`small`})})]})]})]})]})}function is({locale:e,canCreate:t,onNew:n}){return(0,Q.jsxs)(P,{sx:{minHeight:`calc(100vh - ${Qo}px - var(--piagent-status-bar, 0px))`,alignItems:`center`,justifyContent:`center`,px:3,textAlign:`center`},spacing:1.5,children:[(0,Q.jsx)(ut,{size:48}),(0,Q.jsx)(S,{variant:`h1`,children:X(e,`Bắt đầu với Piagent`,`Start with Piagent`)}),(0,Q.jsx)(S,{color:`text.secondary`,sx:{maxWidth:520},children:X(e,`Tạo cuộc trò chuyện mới, chọn project và model; session sẽ được lưu để tiếp tục sau khi đóng Gateway.`,`Create a new chat, choose a project and model, and the session will remain available after the Gateway closes.`)}),(0,Q.jsx)(a,{disabled:!t,variant:`contained`,startIcon:(0,Q.jsx)(de,{}),onClick:n,children:X(e,`Cuộc trò chuyện mới`,`New chat`)})]})}function as({catalog:e,capabilities:t,connection:n,live:r,terminalActivities:o,refresh:c,create:l,send:d,abort:p,restart:m,setModel:h,setThinking:g,setPermission:_,setFast:v,rename:y,pin:b,archive:x,unarchive:C,fork:w}){let{locale:T,colorMode:E,themeId:D,setLocale:k,setColorMode:A,setThemeId:j}=Oe(),M=Br(),N=ct(),[I,z]=(0,$.useState)(!1),[B,te]=(0,$.useState)(`sessions`),ne=i(fe().breakpoints.up(`lg`)),[V,H]=(0,$.useState)(null),[ie,U]=(0,$.useState)(``),[oe,W]=(0,$.useState)(),[G,se]=(0,$.useState)(!1),[le,ue]=(0,$.useState)(!1),[de,K]=(0,$.useState)(`chat`),[me,he]=(0,$.useState)(!1),[ge,_e]=(0,$.useState)(`general`),[q,ve]=(0,$.useState)(!1),[J,ye]=(0,$.useState)(`task`),Y=!ne,[be,xe]=(0,$.useState)(()=>{try{let e=window.localStorage.getItem(ts);if(e)return e===`open`}catch{}return window.innerWidth>=1200}),[Se,Ce]=(0,$.useState)(!1),we=()=>Y?Ce(e=>!e):xe(e=>{try{window.localStorage.setItem(ts,e?`closed`:`open`)}catch{}return!e}),Te=(0,$.useRef)(!1);q&&(Te.current=!0);let Ee=(0,$.useRef)(!1);Ee.current=q&&(J===`activity`||J===`source`);let[De,ke]=(0,$.useState)(),Ae=(0,$.useRef)(null),[Me,Pe]=(0,$.useState)(`idle`),Fe=(0,$.useRef)(null),Ie=(0,$.useRef)(null);Ie.current??=new xn;let[Le,Re]=(0,$.useState)(!1),[ze,Be]=(0,$.useState)(null),[Ve,He]=(0,$.useState)(null),[Ue,We]=(0,$.useState)(``),[Ke,qe]=(0,$.useState)(!1),[Je,Xe]=(0,$.useState)(null),[Ze,Qe]=(0,$.useState)(null);(0,$.useEffect)(()=>{de===`chat`&&oe||(window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0)},[de,oe]);let $e=(0,$.useMemo)(()=>(e?.sessions??[]).filter(e=>e.archived===le&&`${e.title} ${e.projectLabel} ${e.preview}`.toLowerCase().includes(ie.trim().toLowerCase())),[e,ie,le]),et=(0,$.useMemo)(()=>{let e=new Map;for(let t of $e){let n=e.get(t.projectRef)??{label:t.projectLabel,gitBranch:t.gitBranch,sessions:[]};n.gitBranch??=t.gitBranch,n.gitRepositories??=t.gitRepositories,n.sessions.push(t),e.set(t.projectRef,n)}return[...e.entries()].map(([e,t])=>({projectRef:e,...t,sessions:t.sessions.sort((e,t)=>Number(t.pinned)-Number(e.pinned)||Date.parse(t.updatedAt)-Date.parse(e.updatedAt))})).sort((e,t)=>Date.parse(t.sessions[0]?.updatedAt??``)-Date.parse(e.sessions[0]?.updatedAt??``))},[$e]),tt=e?.sessions.filter(e=>e.archived).length??0;(0,$.useEffect)(()=>{(!oe||!(e?.sessions??[]).some(e=>e.sessionRef===oe))&&W((e?.sessions??[]).find(e=>!e.archived)?.sessionRef)},[oe,e]);let Z=(e?.sessions??[]).find(e=>e.sessionRef===oe),nt=Z?.sessionRef,rt=Z?.state===`terminal-owned`,it=(e?.sessions??[]).some(e=>e.state===`terminal-owned`);(0,$.useEffect)(()=>{let e=rt?3e3:it?1e4:3e4,t=window.setInterval(()=>{document.visibilityState===`visible`&&c()},e);return()=>window.clearInterval(t)},[rt,it,c]);let at=(0,$.useRef)(nt);at.current=nt;let ot=Ae.current&&Ae.current.sessionRef===nt&&Ae.current.snapshot===De?De:void 0,lt=Fe.current===nt?Me:nt?`loading`:`idle`,ut=Z?r[Z.sessionRef]:void 0,[dt,ft]=(0,$.useState)(null),pt=(0,$.useRef)(!1);(0,$.useEffect)(()=>{if(!e||pt.current)return;pt.current=!0;let t=Ne();t&&(ft(t),K(`new`))},[e]);let mt=e=>{ft(null),W(e),K(`chat`),se(!1)},ht=uo({sessions:(0,$.useMemo)(()=>e?.sessions??[],[e]),live:r,selectedRef:de===`chat`?nt:void 0,onOpen:mt,locale:T}),gt=e=>{_e(e),he(!0)};bt({palette:()=>z(!0),settings:()=>gt(`general`),newChat:()=>{xt&&(Be(null),K(`new`))}});let vt=e=>{ye(e),ve(!0)},yt=async()=>{let e=at.current;if(!e)return;Ae.current?.sessionRef!==e&&(Fe.current=e,Pe(`loading`));let t=await Ie.current.run(()=>Ge(e),t=>{at.current===e&&(Ae.current={sessionRef:e,snapshot:t},Fe.current=e,ke(t),Pe(`ready`))},()=>{at.current===e&&(Fe.current=e,Pe(Ae.current?.sessionRef===e?`ready`:`error`))});return at.current===e?t:void 0};(0,$.useEffect)(()=>{if(!nt){Ie.current.invalidate(),Ae.current=null,Fe.current=null,ke(void 0),Pe(`idle`);return}let e=nt,t=new AbortController;return Fe.current=e,Ae.current?.sessionRef!==e&&(Ae.current=null,ke(void 0),Pe(`loading`)),Ie.current.run(()=>Ge(e,t.signal),n=>{t.signal.aborted||at.current!==e||(Ae.current={sessionRef:e,snapshot:n},Fe.current=e,ke(n),Pe(`ready`))},()=>{t.signal.aborted||at.current!==e||(Fe.current=e,Pe(Ae.current?.sessionRef===e?`ready`:`error`))}),()=>t.abort()},[nt,Z?.sessionRevision]),(0,$.useEffect)(()=>{if(!q||J!==`activity`&&J!==`source`||!nt||!ot||!ut?.operationRef||ut.complete)return;let e=nt,t=!1,n,r=async()=>{await Ie.current.run(()=>Ge(e),n=>{t||!Ee.current||at.current!==e||(Ae.current={sessionRef:e,snapshot:n},Fe.current=e,ke(n),Pe(`ready`))},()=>void 0),t||(n=window.setTimeout(()=>void r(),2e3))};return n=window.setTimeout(()=>void r(),2e3),()=>{t=!0,n!==void 0&&window.clearTimeout(n)}},[q,J,nt,!!ot,ut?.operationRef,ut?.complete]);let xt=n===`connected`&&t?.capabilities.sessionActions.create.status===`available`,Ct=async e=>{Re(!0),Be(null);let t=null;try{let n=`message-request.${crypto.randomUUID()}`,r=e.files.length>0,i=await l({projectRef:e.projectRef,placeRef:e.placeRef,modelRef:e.modelRef,thinkingLevel:e.thinkingLevel,workflow:e.workflow,permissionMode:e.permissionMode,fast:e.fast,message:e.message,messageRequestId:n,deferInitialMessage:r});if(t=i.sessionRef,!t)throw Error(`session-create-result-invalid`);if(yn(gn,``),_n(gn,null),i.phase!==`settled`){W(t),K(`chat`),Qe({title:X(T,`Session đã được tạo`,`The session was created`),message:X(T,`Pi đã nhận yêu cầu và session đang tự đồng bộ. Không gửi lại để tránh chạy trùng.`,`Pi received the request and the session is resyncing. Do not resend it, to avoid a duplicate run.`)});return}if(r){let r=(await c())?.sessions.find(e=>e.sessionRef===t);if(!r)throw Error(`session-catalog-refresh-failed`);let i=await Ge(t),a=i.capabilities.capabilities.attachments;if(a.status!==`available`)throw Error(a.reason?.code??`session-attachment-unavailable`);let o=await Kt({files:e.files,snapshot:i,messageRequestId:n,existing:[],allowed:new Set(a.mimeTypes),locale:T,stage:e=>Ye(t,e)});if(o.status||o.attachments.length!==e.files.length)throw await Promise.all(o.attachments.map(async e=>{try{await un({snapshot:i,messageRequestId:n,attachmentRef:e.attachmentRef,locale:T,stage:e=>Ye(t,e)})}catch{}})),Error(o.status??`session-attachment-incomplete`);await d(r,e.message,{messageRequestId:n,attachmentRefs:o.attachments.map(e=>e.attachmentRef),attachments:o.attachments,workflow:e.workflow})}W(t),K(`chat`)}catch(n){let r=n instanceof Error?n.message:`session-create-failed`;t?(e.files.length>0&&yn(t,e.message),W(t),K(`chat`),Qe({title:X(T,`Session đã tạo nhưng file chưa được gửi`,`The session was created, but the files were not sent`),message:r})):Be(pr(r,T))}finally{Re(!1)}},wt=(e,t)=>{if(t===`pin`){b(e,!e.pinned).catch(e=>Qe({title:X(T,`Không thể đổi trạng thái ghim`,`Could not change pin state`),message:e instanceof Error?e.message:`session-pin-failed`}));return}if(t===`unarchive`){C(e).then(()=>ue(!1)).catch(e=>Qe({title:X(T,`Không thể khôi phục cuộc trò chuyện`,`Could not restore chat`),message:e instanceof Error?e.message:`session-unarchive-failed`}));return}Xe(null),We(t===`rename`?e.title:t===`fork`?`${e.title} · ${X(T,`nhánh`,`fork`)}`:``),He({kind:t,session:e})},Tt=async()=>{if(!(!Ve||Ke)){qe(!0),Xe(null);try{if(Ve.kind===`rename`)await y(Ve.session,Ue.trim());else if(Ve.kind===`archive`)await x(Ve.session);else{let e=await w(Ve.session,Ue.trim()||null);e.sessionRef&&(W(e.sessionRef),K(`chat`))}He(null)}catch(e){Xe(cs(Ve.kind,e instanceof Error?e.message:`session-action-failed`,T))}finally{qe(!1)}}},Et=(0,Q.jsx)(Mt,{locale:T,canCreate:xt,query:ie,onQuery:U,groups:et,count:$e.length,selectedRef:de===`chat`?Z?.sessionRef:void 0,showArchived:le,archivedCount:tt,settingsOpen:me,connection:n,live:r,unseen:ht.unseen,onSelect:mt,onAction:wt,onNew:()=>{Be(null),K(`new`),se(!1)},onToggleArchived:()=>{ue(e=>!e),se(!1)},updateDot:!!(N.status?.updateAvailable&&N.status.installable),onSettings:()=>{gt(N.status?.updateAvailable&&N.status.installable?`updates`:`general`),se(!1)}}),Ot=de===`chat`&&Z?(0,Q.jsx)(Ro,{session:Z,snapshot:ot,live:ut,locale:T,onOpenReview:()=>vt(`source`),onClose:()=>Y?Ce(!1):xe(!1)}):null,kt=!!Ot&&(Y?Se:be)&&!q;if(M)return(0,Q.jsx)(Vr,{locale:T});if(!e&&n!==`failed`)return(0,Q.jsxs)(P,{sx:{minHeight:`100vh`,alignItems:`center`,justifyContent:`center`},spacing:2,children:[(0,Q.jsx)(ee,{size:24}),(0,Q.jsx)(S,{children:X(T,`Đang mở Piagent…`,`Opening Piagent…`)})]});let At=de===`new`?X(T,`Cuộc trò chuyện mới`,`New chat`):Z?.title??`Piagent`,jt=zo({locale:T,colorMode:E,themeId:D,canCreate:xt,hasSelection:de===`chat`&&!!Z,sessions:(e?.sessions??[]).filter(e=>!e.archived),update:{available:!!(N.status?.updateAvailable&&N.status.installable&&!_t(N.status)),latest:N.status?.piagent.latest??null},actions:{newChat:()=>{Be(null),K(`new`)},togglePanel:we,openChanges:()=>vt(`source`),refresh:()=>void c(),settings:gt,checkUpdates:()=>{gt(`updates`),N.check()},setColorMode:A,setTheme:j,setLocale:k,openSession:mt}}),Nt=Object.values(r).filter(e=>e&&!e.complete).length;return(0,Q.jsx)(Vt,{sessionRef:de===`chat`?nt:void 0,onOpen:()=>ve(!1),children:(0,Q.jsxs)(R,{sx:{minHeight:`100vh`,bgcolor:`background.default`,"--piagent-status-bar":{xs:`0px`,md:`28px`}},children:[(0,Q.jsx)(F,{position:`fixed`,color:`transparent`,elevation:0,sx:{left:{md:`${Zo}px`},right:{lg:kt?`${$o}px`:0,xl:q?es:kt?`${$o}px`:0},width:{xs:`100%`,md:`auto`},borderBottom:1,transition:`right .2s ease`,borderColor:`divider`,bgcolor:`rgba(var(--piagent-palette-background-defaultChannel) / .9)`,backdropFilter:`blur(18px)`},children:(0,Q.jsxs)(ae,{sx:{minHeight:`${Qo}px !important`,gap:1,px:{xs:1.5,sm:2.5}},children:[(0,Q.jsx)(L,{"aria-label":X(T,`Mở điều hướng`,`Open navigation`),onClick:()=>se(!0),sx:{display:{md:`none`}},children:(0,Q.jsx)(u,{})}),(0,Q.jsxs)(R,{sx:{flex:1,minWidth:0},children:[(0,Q.jsx)(S,{component:`h1`,noWrap:!0,sx:{fontWeight:600,fontSize:14.5,letterSpacing:`-0.01em`,lineHeight:1.3},children:At}),de===`chat`&&Z&&(0,Q.jsxs)(S,{variant:`caption`,color:`text.secondary`,noWrap:!0,component:`div`,sx:{display:`flex`,alignItems:`center`,gap:.75,minWidth:0},children:[(0,Q.jsx)(R,{component:`span`,sx:{overflow:`hidden`,textOverflow:`ellipsis`,flexShrink:3,minWidth:24},children:Z.projectLabel}),(Z.gitBranch||!!Z.gitRepositories?.length)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(R,{component:`span`,"aria-hidden":!0,sx:{color:`text.disabled`},children:`·`}),(0,Q.jsx)(It,{projectRef:Z.projectRef,projectLabel:Z.projectLabel,branch:Z.gitBranch,repositories:Z.gitRepositories,locale:T,maxWidth:`45%`,onSwitched:()=>void c()})]})]})]}),de===`chat`&&Z&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(st,{placement:`header`,compact:q,session:Z,snapshot:ot,locale:T,onOpenChanges:()=>vt(`source`),canSetModel:n===`connected`&&t?.capabilities.sessionActions.setModel.status===`available`,canSetThinking:n===`connected`&&t?.capabilities.sessionActions.setThinking.status===`available`,canSetPermission:n===`connected`&&t?.capabilities.sessionActions.setPermission.status===`available`,onSetModel:e=>h(Z,e),onSetThinking:e=>g(Z,e),onSetPermission:e=>_(Z,e),onSetFast:e=>v(Z,e)}),(0,Q.jsx)(R,{sx:{display:{xs:`none`,sm:q?`none`:`block`}},children:(0,Q.jsx)(ns,{session:Z,live:ut,locale:T})}),(0,Q.jsx)(R,{"aria-hidden":`true`,sx:{width:`1px`,height:20,bgcolor:`divider`,mx:.5,display:{xs:`none`,sm:`block`}}}),(0,Q.jsx)(pe,{title:`Source Changes`,children:(0,Q.jsx)(L,{"aria-label":X(T,`Mở Source Changes Inspector`,`Open Source Changes Inspector`),onClick:()=>vt(`source`),children:(0,Q.jsx)(O,{fontSize:`small`})})}),(0,Q.jsx)(pe,{title:X(T,`Khung Workspace: thay đổi, ngữ cảnh, subagent`,`Workspace panel: changes, context, subagents`),children:(0,Q.jsx)(L,{"aria-label":X(T,`Khung Workspace`,`Workspace panel`),"aria-pressed":kt,onClick:()=>we(),color:kt?`primary`:`default`,children:(0,Q.jsx)(Wn,{fontSize:`small`,sx:{transform:`scaleX(-1)`}})})})]}),(0,Q.jsx)(pe,{title:X(T,`Làm mới`,`Refresh`),children:(0,Q.jsx)(L,{"aria-label":X(T,`Làm mới`,`Refresh`),onClick:()=>void c(),children:(0,Q.jsx)(f,{fontSize:`small`})})})]})}),(0,Q.jsxs)(R,{component:`nav`,sx:{width:{md:Zo}},children:[(0,Q.jsx)(ce,{variant:`temporary`,open:G,onClose:()=>se(!1),sx:{display:{xs:`block`,md:`none`},"& .MuiDrawer-paper":{width:Zo}},children:Et}),(0,Q.jsxs)(ce,{variant:`permanent`,sx:{display:{xs:`none`,md:`block`},"& .MuiDrawer-paper":{width:Zo,borderRight:1,borderColor:`divider`,height:`calc(100% - var(--piagent-status-bar, 0px))`}},children:[ne&&Z&&de===`chat`&&(0,Q.jsx)(Tn,{value:B,onChange:te}),!ne||B===`sessions`||!Z||de!==`chat`?Et:(0,Q.jsx)(R,{ref:H,sx:{overflow:`auto`,flex:1}})]})]}),(0,Q.jsx)(R,{component:`main`,sx:{ml:{md:`${Zo}px`},mr:{lg:kt?`${$o}px`:0,xl:q?es:kt?`${$o}px`:0},pt:`${Qo}px`,transition:`margin-right .2s ease`},children:de===`new`?(0,Q.jsx)(Mr,{active:!0,defaultProjectRef:dt??Z?.projectRef,busy:Le,error:ze,onCancel:()=>K(`chat`),onCreate:e=>Ct(e)}):Z?(0,Q.jsx)(Ln,{sessionRef:Z.sessionRef,navigationHost:V,sidebarMode:B,onSection:te,children:(0,Q.jsx)(rs,{session:Z,snapshot:ot,locale:T,live:r[Z.sessionRef],commandActions:{setModel:e=>h(Z,e),setThinking:e=>g(Z,e),setFast:e=>v(Z,e),setPermission:e=>_(Z,e),rename:e=>y(Z,e),fork:()=>w(Z,null),pin:e=>b(Z,e),archive:()=>x(Z),newChat:()=>{Be(null),K(`new`)},openChanges:()=>vt(`source`),openSettings:()=>gt(`general`)},canSend:n===`connected`&&Z.composerAvailable&&t?.capabilities.sessionActions.send.status===`available`&&(!ut||ut.complete)&&![`required`,`restarting`,`failed`].includes(String(r[Z.sessionRef]?.runtimeRecovery)),canRestart:n===`connected`&&t?.capabilities.sessionActions.release.status===`available`&&t?.capabilities.sessionActions.acquire.status===`available`,send:(e,t)=>d(Z,e,t),abort:()=>p(Z).catch(e=>Qe({title:X(T,`Chưa dừng được lượt này`,`This turn could not be stopped`),message:e instanceof Error&&e.message===`operation-unavailable`?X(T,`Lượt đã kết thúc hoặc đang chuyển bước. Nếu vẫn còn chạy, bấm Dừng lần nữa.`,`The turn already ended or is between steps. If it is still running, press Stop again.`):e instanceof Error?e.message:`session-abort-failed`})),restart:()=>m(Z),onInspector:vt},Z.sessionRef)},Z.sessionRef):(0,Q.jsx)(is,{locale:T,canCreate:xt,onNew:()=>K(`new`)})}),Ot&&kt&&!Y&&(0,Q.jsx)(R,{component:`aside`,sx:{display:{xs:`none`,lg:`block`},position:`fixed`,top:0,right:0,bottom:`var(--piagent-status-bar, 0px)`,width:$o,borderLeft:1,borderColor:`divider`,zIndex:e=>e.zIndex.appBar-1},children:Ot}),Ot&&(0,Q.jsx)(ce,{anchor:`right`,variant:`temporary`,open:Se&&!q&&Y,onClose:()=>Ce(!1),sx:{display:{xs:`block`,lg:`none`},"& .MuiDrawer-paper":{width:`min(${$o}px, 88vw)`}},children:Ot}),Te.current&&(0,Q.jsx)($.Suspense,{fallback:null,children:(0,Q.jsx)(Xo,{open:q,active:J,snapshot:ot,state:lt,sessionRef:nt,terminalActivities:Z?o[Z.sessionRef]:void 0,liveActivities:ut&&!ut.complete?ut.activities:void 0,onClose:()=>ve(!1),onActive:ye,refresh:yt,findings:Z?.managedReview?.findings,onSendComments:Z&&Z.composerAvailable?e=>{vn(Z.sessionRef,e),ve(!1)}:void 0})}),(0,Q.jsx)(Jr,{locale:T,onDetails:()=>gt(`updates`)}),ht.view,(0,Q.jsx)(St,{locale:T,connection:n,running:Nt,session:de===`chat`?Z:void 0,onBranchSwitched:()=>void c(),onUpdates:()=>gt(`updates`),onPalette:()=>z(!0)}),(0,Q.jsx)(Dt,{open:I,onClose:()=>z(!1),commands:jt,locale:T}),(0,Q.jsx)(s,{open:me,onClose:()=>he(!1),fullWidth:!0,maxWidth:`lg`,"aria-labelledby":`piagent-settings-title`,slotProps:{paper:{sx:{m:{xs:0,sm:2},width:{xs:`100%`,sm:`calc(100% - 32px)`},height:{xs:`100%`,sm:`min(86vh, 840px)`},maxHeight:{xs:`100%`,sm:`86vh`},borderRadius:{xs:0,sm:2.5},overflow:`hidden`}}},children:me&&(0,Q.jsx)(je,{locale:T,children:(0,Q.jsx)(Yo,{section:ge,onSection:_e,onBack:()=>he(!1),session:Z,snapshot:ot,capabilities:t,connection:n,onSetModel:Z?e=>h(Z,e):void 0,onSetThinking:Z?e=>g(Z,e):void 0,onSetPermission:Z?e=>_(Z,e):void 0,onRuntimeChanged:async()=>{await c(),await yt()}})})}),(0,Q.jsx)(s,{open:!!Ve,onClose:()=>!Ke&&He(null),fullWidth:!0,maxWidth:`xs`,children:(0,Q.jsxs)(P,{spacing:2,sx:{p:3},children:[(0,Q.jsx)(S,{variant:`h2`,children:Ve?.kind===`rename`?X(T,`Đổi tên cuộc trò chuyện`,`Rename chat`):Ve?.kind===`fork`?X(T,`Tạo nhánh cuộc trò chuyện`,`Fork chat`):X(T,`Lưu trữ cuộc trò chuyện`,`Archive chat`)}),Ve?.kind===`archive`?(0,Q.jsx)(S,{color:`text.secondary`,children:X(T,`Cuộc trò chuyện vẫn được lưu và có thể khôi phục từ mục Đã lưu trữ.`,`The chat remains saved and can be restored from Archived.`)}):(0,Q.jsx)(re,{autoFocus:!0,label:X(T,`Tên`,`Title`),value:Ue,onChange:e=>We(e.target.value),slotProps:{htmlInput:{maxLength:500}}}),Je&&(0,Q.jsx)(S,{color:`error`,children:Je}),(0,Q.jsxs)(P,{direction:`row`,spacing:1,sx:{justifyContent:`flex-end`},children:[(0,Q.jsx)(a,{disabled:Ke,onClick:()=>He(null),children:X(T,`Hủy`,`Cancel`)}),(0,Q.jsx)(a,{variant:`contained`,disabled:Ke||Ve?.kind!==`archive`&&!Ue.trim(),onClick:()=>void Tt(),children:X(T,`Xác nhận`,`Confirm`)})]})]})}),(0,Q.jsx)(s,{open:!!Ze,onClose:()=>Qe(null),fullWidth:!0,maxWidth:`xs`,"aria-labelledby":`piagent-session-notice-title`,children:(0,Q.jsxs)(P,{spacing:2,sx:{p:3},children:[(0,Q.jsx)(S,{id:`piagent-session-notice-title`,variant:`h2`,children:Ze?.title}),(0,Q.jsx)(S,{color:`text.secondary`,children:Ze?.message}),(0,Q.jsx)(P,{direction:`row`,sx:{justifyContent:`flex-end`},children:(0,Q.jsx)(a,{variant:`contained`,onClick:()=>Qe(null),children:X(T,`Đóng`,`Close`)})})]})})]})})}var os={"session-revision-stale":[`Cuộc trò chuyện vừa thay đổi trong lúc gửi. Bấm Xác nhận lần nữa.`,`The chat changed while this was sent. Select Confirm again.`],"session-runtime-busy":[`Cuộc trò chuyện đang bận. Thử lại khi lượt này xong.`,`The chat is busy. Try again when this turn ends.`],"session-runtime-unavailable":[`Cuộc trò chuyện chưa mở được. Mở lại cuộc trò chuyện rồi thử lại.`,`The chat is not open. Open it again and retry.`],"session-unavailable":[`Không còn thấy cuộc trò chuyện này trong danh sách. Tải lại trang rồi thử lại.`,`This chat is no longer in the list. Reload the page and retry.`],"session-archived":[`Cuộc trò chuyện đã được lưu trữ. Bỏ lưu trữ trước.`,`The chat is archived. Unarchive it first.`],"session-command-expired":[`Yêu cầu chờ quá lâu nên đã hết hạn. Thử lại.`,`The request waited too long and expired. Try again.`],"gateway-command-response-timeout":[`Piagent chưa trả lời. Xem lại danh sách trước khi thử lại.`,`Piagent did not answer. Check the list before trying again.`]},ss={rename:[`Chưa đổi được tên`,`Could not rename`],fork:[`Chưa tạo được nhánh`,`Could not fork`],archive:[`Chưa lưu trữ được`,`Could not archive`]};function cs(e,t,n){let r=os[t];return`${X(n,...ss[e])}: ${r?X(n,...r):X(n,`thử lại.`,`try again.`)} (${t})`}function ls(e,t=150){let n,r=!1,i=!1,a=!1,o=()=>{if(!a){if(r||n!==void 0){i=r;return}n=setTimeout(()=>{n=void 0,r=!0,e().catch(()=>void 0).finally(()=>{r=!1,i&&(i=!1,o())})},t)}};return{request:o,stop:()=>{a=!0,n!==void 0&&clearTimeout(n),n=void 0}}}var us=class extends Error{effectMayHaveOccurred;constructor(e,t){super(e),this.name=`GatewayCommandTransportError`,this.effectMayHaveOccurred=t}};async function ds(e,t,n=4){for(let r=1;;r+=1)try{return await e(t)}catch(e){if(r>=n||!(e instanceof us)||e.message!==`gateway-command-response-timeout`)throw e}}function fs(e,t){return e instanceof us?e.effectMayHaveOccurred:t}function ps(e,t,n=null,r=null){return!e||e.serial<=t||e.operationRef===n||r&&e.messageRequestId&&e.messageRequestId!==r?null:e}function ms(e,t,n=null){return e&&e.operationRef!==t&&!(n&&e.messageRequestId&&e.messageRequestId!==n)?{operationRef:e.operationRef,complete:!1}:null}function hs(e,t){return t?`observed`:e?.phase===`settled`||e?.phase===`accepted`?`confirmed`:e?.phase===`rejected`?`rejected`:`unconfirmed`}function gs(e,t){let n=new AbortController,r=()=>void 0,i=new Promise(e=>{r=e}),a=setTimeout(()=>{n.abort(),r(null)},t);return{promise:Promise.race([e(n.signal).catch(()=>null),i]).finally(()=>clearTimeout(a)),cancel(){n.abort(),r(null),clearTimeout(a)}}}function _s(e,t,n,r,i){let a=e[t];if(!a||a.messageRequestId!==n||i===`unconfirmed`&&(a.delivery===`admitted`||a.operationRef))return e;let o=Si(a,i,r.operationRef,new Date().toISOString()),s=i===`unconfirmed`||r.complete||!!(r.operationRef&&a.operationRef===r.operationRef&&a.complete);return{...e,[t]:{...o,complete:s,abortable:i===`admitted`&&!s&&!!r.operationRef}}}async function vs(e,t={}){let n=()=>{let t=ps(e.readLocalObservation?.()??e.localObservation,e.afterSerial,e.priorOperationRef,e.messageRequestId);return t?{operationRef:t.operationRef,complete:t.complete}:null},r=n();if(r)return r;let i=t.timeoutMs??5e3,a=t.readLiveState??nt,o=t.readTranscript??Ue,s=[gs(async t=>{let n=await a(t);return ms(n?.state===`ready`?n.operations.find(t=>t.sessionRef===e.sessionRef):void 0,e.priorOperationRef,e.messageRequestId)},i),gs(async t=>{let n=await o(e.sessionRef,null,50,t);if(n?.state!==`ready`)return null;let r=[...n.items].reverse().find(t=>t.role===`user`&&t.messageRequestId===e.messageRequestId);if(r)return{operationRef:r.agentOperationId,complete:tn(n.items,e.message,{operationRef:r.agentOperationId,messageRequestId:e.messageRequestId,startedAt:null})};let i=Date.parse(e.requestedAt),a=[...n.items].reverse().find(t=>t.role===`user`&&!t.messageRequestId&&sn(t.content.text,e.message)&&Date.parse(t.recordedAt)>=i);return a?{operationRef:a.agentOperationId,complete:tn(n.items,e.message,{operationRef:a.agentOperationId,messageRequestId:null,startedAt:e.requestedAt})}:null},i)],c=new Map(s.map((e,t)=>[t,e.promise.then(e=>({evidence:e,index:t}))]));try{for(;c.size>0;){let e=await Promise.race(c.values());if(c.delete(e.index),e.evidence)return e.evidence;let t=n();if(t)return t}return n()}finally{for(let e of s)e.cancel()}}function ys(e){return(0,$.useMemo)(()=>{let t=[],n=0,r=()=>{if(n&&cancelAnimationFrame(n),n=0,t.length===0)return;let r=t;t=[],e(e=>r.reduce((e,t)=>t(e),e))};return{now:t=>{r(),e(t)},later:e=>{t.push(e),n||=requestAnimationFrame(r)}}},[e])}function bs(e,t){if(e===t)return!0;try{return e!==void 0&&JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function xs(){let[e,t]=(0,$.useState)(),[n,r]=(0,$.useState)(),[i,a]=(0,$.useState)(`connecting`),[o,s]=(0,$.useState)({}),{now:c,later:l}=ys(s),[u,d]=(0,$.useState)({}),f=(0,$.useRef)(void 0),p=(0,$.useRef)(null),m=(0,$.useRef)(null),h=(0,$.useRef)({});h.current=o;let g=(0,$.useRef)(0),_=(0,$.useRef)(new Map),v=(0,$.useRef)(null),y=(0,$.useRef)(!0),b=(0,$.useRef)(0),x=(0,$.useRef)(0),S=(0,$.useRef)(new Map),C=(0,$.useCallback)(Ko,[]),w=(0,$.useCallback)(async(e={})=>{let n=++b.current;try{let[r,i]=await Promise.all([We(),nt().catch(()=>void 0)]),o=ui(i,r.gatewayInstanceRef),s=!1;if(n>=x.current){x.current=n,f.current=r,t(e=>bs(e,r)?e:r);let l=v.current;l!==null&&l!==r.gatewayInstanceRef&&(y.current=!0),v.current=r.gatewayInstanceRef;let u=e.requireLiveState||y.current,h=p.current?.readyState===WebSocket.OPEN;if(a(di(h,u)),!h&&i&&o!==null)m.current=o,C(r.gatewayInstanceRef,o),c(e=>wi(e,i)),d(yi(i)),y.current=!1,s=!0;else if(l!==r.gatewayInstanceRef){if(d({}),u)m.current=null;else{let e=null;try{e=window.sessionStorage.getItem(Bo)}catch{}m.current=Go(e,r.gatewayInstanceRef)}}}return e.requireLiveState&&!s?void 0:f.current??r}catch{a(`reconnecting`);return}},[C]),T=(0,$.useCallback)(e=>{let t=p.current;if(!t||t.readyState!==WebSocket.OPEN)return Promise.reject(new us(`gateway-not-connected`,!1));let n=qo(`request`);return new Promise((r,i)=>{let a=window.setTimeout(()=>{S.current.delete(n)&&i(new us(`gateway-command-response-timeout`,!0))},Vo);S.current.set(n,{resolve:r,reject:i,timeout:a});try{t.send(JSON.stringify({schemaVersion:1,version:`piagent-gateway-protocol-v1`,messageType:`request`,requestId:n,method:`sessions.command`,params:{command:e}}))}catch(e){window.clearTimeout(a),S.current.delete(n),i(new us(e instanceof Error?e.message:`gateway-request-failed`,!1))}})},[]),E=(0,$.useCallback)((e,t,n,r,i,a)=>vs({sessionRef:e,message:t,requestedAt:n,afterSerial:r,priorOperationRef:i,messageRequestId:a,readLocalObservation:()=>_.current.get(e)}),[]),D=(0,$.useCallback)(async e=>{let t=f.current,n=e.message.trim(),r=e.messageRequestId??qo(`message`);if(!t?.catalogRevision)throw Error(`catalog-unavailable`);if(!n)throw Error(`message-empty`);let i=t=>{if(!t.catalogRevision)throw Error(`catalog-unavailable`);let i=new Date;return ds(T,{schemaVersion:1,version:`piagent-session-command-v1`,messageType:`command`,commandId:qo(`command`),idempotencyKey:qo(`idempotency`),action:`session.create`,requestedAt:i.toISOString(),expiresAt:new Date(i.getTime()+3e5).toISOString(),sessionRef:null,expectedCatalogRevision:t.catalogRevision,expectedSessionRevision:null,payload:{projectRef:e.projectRef,placeRef:e.placeRef,modelRef:e.modelRef,thinkingLevel:e.thinkingLevel,workflow:e.workflow,message:n,messageRequestId:r,...e.permissionMode?{permissionMode:e.permissionMode}:{},...e.fast?{fast:!0}:{},...e.deferInitialMessage?{deferInitialMessage:!0}:{}}})},a=await i(t);if(Jo(a)){let e=await w();e?.catalogRevision&&(a=await i(e))}if(!(a.phase===`uncertain`&&a.sessionRef)&&a.phase!==`settled`||!a.sessionRef)throw Error(a.error?.code??a.resultCode);let o=a.settledAt??a.requestedAt;return a.phase===`settled`&&!e.deferInitialMessage&&c(e=>{let t=e[a.sessionRef];return{...e,[a.sessionRef]:{...t??{assistant:``,attachments:[],activities:[],complete:!1,error:null},user:n,operationRef:a.operationRef,messageRequestId:r,abortable:!t?.complete&&!!a.operationRef,startedAt:t?.startedAt??o,lastEventAt:t?.lastEventAt??o}}}),await w(),a},[w,T]),O=(0,$.useCallback)(async(e,t,n)=>{let r=f.current;if(!r?.catalogRevision)throw Error(`catalog-unavailable`);let i=t.trim();if(!i)throw Error(`message-empty`);let a=n?.messageRequestId??qo(`message`),o=n?.attachmentRefs??[],s=h.current[e.sessionRef],l=g.current,u=_.current.get(e.sessionRef)?.operationRef??s?.operationRef??null,d=new Date().toISOString();c(t=>({...t,[e.sessionRef]:xi(t[e.sessionRef],{message:i,attachments:n?.attachments??[],messageRequestId:a,submittedAt:d})}));let p=()=>c(t=>{let n=t[e.sessionRef],r=Ci(n,s,a);if(r===n)return t;let i={...t};return r?i[e.sessionRef]=r:delete i[e.sessionRef],i}),m=(t,n)=>c(r=>_s(r,e.sessionRef,a,t,n)),v=d,y=!1;try{let t=t=>{let r=t.sessions.find(t=>t.sessionRef===e.sessionRef);if(!t.catalogRevision||!r)throw Error(`session-unavailable`);let s=new Date;return v=s.toISOString(),{schemaVersion:1,version:`piagent-session-command-v1`,messageType:`command`,commandId:qo(`command`),idempotencyKey:qo(`idempotency`),action:`session.send`,requestedAt:s.toISOString(),expiresAt:new Date(s.getTime()+Ho).toISOString(),sessionRef:e.sessionRef,expectedCatalogRevision:t.catalogRevision,expectedSessionRevision:r.sessionRevision,payload:{delivery:`new-operation`,message:i,messageRequestId:a,expectedOperationRef:null,attachmentRefs:o,...n?.workflow?{workflow:n.workflow}:{}}}},s=t(r);y=!0;let c=await T(s);if(Jo(c)){let e=await w();e?.catalogRevision&&(s=t(e),c=await T(s))}if(hs(c,null)===`confirmed`)return m({operationRef:c.operationRef,complete:!1},`admitted`),w(),{state:`confirmed`,receipt:c};let d=await E(e.sessionRef,i,v,l,u,a),f=hs(c,d);if(f===`observed`&&d)return m(d,`admitted`),w(),{state:`observed`,receipt:c};if(f===`unconfirmed`)return m({operationRef:null,complete:!0},`unconfirmed`),w(),{state:`unconfirmed`,receipt:c};throw p(),new Wo(c.error?.code??c.resultCode)}catch(t){if(t instanceof Wo)throw t;if(fs(t,y)){let t=await E(e.sessionRef,i,v,l,u,a);return hs(null,t)===`observed`&&t?(m(t,`admitted`),w(),{state:`observed`,receipt:null}):(m({operationRef:null,complete:!0},`unconfirmed`),w(),{state:`unconfirmed`,receipt:null})}throw p(),t}},[E,w,T]),k=(0,$.useCallback)(async e=>{let t=f.current,n=o[e.sessionRef]?.operationRef,r=t?.sessions.find(t=>t.sessionRef===e.sessionRef);if(!t?.catalogRevision||!r||!n||o[e.sessionRef]?.abortable===!1)throw Error(`operation-unavailable`);let i=t=>{let r=t.sessions.find(t=>t.sessionRef===e.sessionRef);if(!t.catalogRevision||!r)throw Error(`operation-unavailable`);let i=new Date;return T({schemaVersion:1,version:`piagent-session-command-v1`,messageType:`command`,commandId:qo(`command`),idempotencyKey:qo(`idempotency`),action:`session.abort`,requestedAt:i.toISOString(),expiresAt:new Date(i.getTime()+3e5).toISOString(),sessionRef:e.sessionRef,expectedCatalogRevision:t.catalogRevision,expectedSessionRevision:r.sessionRevision,payload:{operationRef:n,clearQueued:!0}})},a=await i(t);if(Jo(a)){let[t,r]=await Promise.all([w(),nt().catch(()=>void 0)]);if(!t||!ki(r,t.gatewayInstanceRef,e.sessionRef,n))throw Error(`operation-unavailable`);a=await i(t)}if(a.phase!==`settled`)throw Error(a.error?.code??a.resultCode);return w(),a},[o,w,T]),A=(0,$.useCallback)(async e=>{let t=async t=>{let n=await w(),r=n?.sessions.find(t=>t.sessionRef===e.sessionRef);if(!n?.catalogRevision||!r)throw Error(`session-unavailable`);let i=new Date,a=await T({schemaVersion:1,version:`piagent-session-command-v1`,messageType:`command`,commandId:qo(`command`),idempotencyKey:qo(`idempotency`),action:t,requestedAt:i.toISOString(),expiresAt:new Date(i.getTime()+3e5).toISOString(),sessionRef:e.sessionRef,expectedCatalogRevision:n.catalogRevision,expectedSessionRevision:r.sessionRevision,payload:{}});if(a.phase!==`settled`)throw Error(a.error?.code??a.resultCode);return a};c(t=>({...t,[e.sessionRef]:{...t[e.sessionRef]??{user:``,assistant:``,attachments:[],activities:[],operationRef:null,complete:!0,error:null},runtimeRecovery:`restarting`}}));try{let n=(await w())?.sessions.find(t=>t.sessionRef===e.sessionRef);if(!n)throw Error(`session-unavailable`);n.state===`gateway-owned`&&await t(`session.release`);let r=await t(`session.acquire`);return c(t=>({...t,[e.sessionRef]:{...t[e.sessionRef]??{user:``,assistant:``,attachments:[],activities:[],operationRef:null,complete:!0,error:null},runtimeRecovery:`recovered`}})),await w(),r}catch(t){throw c(t=>({...t,[e.sessionRef]:{...t[e.sessionRef]??{user:``,assistant:``,attachments:[],activities:[],operationRef:null,complete:!0,error:null},runtimeRecovery:`failed`}})),t}},[w,T]),j=(0,$.useCallback)(async(e,t,n)=>{let r=r=>{let i=r?.sessions.find(t=>t.sessionRef===e.sessionRef);if(!r?.catalogRevision||!i)throw Error(`session-unavailable`);let a=new Date;return T({schemaVersion:1,version:`piagent-session-command-v1`,messageType:`command`,commandId:qo(`command`),idempotencyKey:qo(`idempotency`),action:t,requestedAt:a.toISOString(),expiresAt:new Date(a.getTime()+3e5).toISOString(),sessionRef:e.sessionRef,expectedCatalogRevision:r.catalogRevision,expectedSessionRevision:i.sessionRevision,payload:n})},i=await r(f.current);for(let e=0;[`session.set-permission`,`session.set-fast`].includes(t)&&Jo(i)&&e<2;e++)i=await r(await w());if(i.phase!==`settled`)throw Error(i.error?.code??i.resultCode);return await w(),i},[w,T]),M=(0,$.useCallback)((e,t)=>j(e,`session.set-model`,{modelRef:t}),[j]),N=(0,$.useCallback)((e,t)=>j(e,`session.set-thinking`,{thinkingLevel:t}),[j]),P=(0,$.useCallback)((e,t)=>j(e,`session.set-permission`,{permissionMode:t}),[j]),F=(0,$.useCallback)((e,t)=>j(e,`session.set-fast`,{fast:t}),[j]),I=(0,$.useCallback)(async(e,t,n)=>{let r=r=>{let i=r?.sessions.find(t=>t.sessionRef===e.sessionRef);if(!r?.catalogRevision||!i)throw Error(`session-unavailable`);let a=new Date;return T({schemaVersion:1,version:`piagent-session-command-v1`,messageType:`command`,commandId:qo(`command`),idempotencyKey:qo(`idempotency`),action:t,requestedAt:a.toISOString(),expiresAt:new Date(a.getTime()+3e5).toISOString(),sessionRef:e.sessionRef,expectedCatalogRevision:r.catalogRevision,expectedSessionRevision:i.sessionRevision,payload:n})},i=await r(f.current);for(let e=0;t===`session.rename`&&Jo(i)&&e<2;e++)i=await r(await w());if(i.phase!==`settled`)throw Error(i.error?.code??i.resultCode);return await w(),i},[w,T]),L=(0,$.useCallback)((e,t)=>I(e,`session.rename`,{title:t}),[I]),R=(0,$.useCallback)((e,t)=>I(e,`session.pin`,{pinned:t}),[I]),z=(0,$.useCallback)(e=>I(e,`session.archive`,{}),[I]),ee=(0,$.useCallback)(e=>I(e,`session.unarchive`,{}),[I]),B=(0,$.useCallback)((e,t)=>I(e,`session.fork`,{entryRef:null,title:t}),[I]);return(0,$.useEffect)(()=>{let e=!1,t,n=0,i=!1,o=ls(()=>w()),s=o.request,u=(()=>{try{let e=window.localStorage.getItem(`piagent-gateway-client-ref`);if(e&&/^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/.test(e))return e;let t=qo(`client`);return window.localStorage.setItem(`piagent-gateway-client-ref`,t),t}catch{return qo(`client`)}})(),h=()=>{if(e||Le())return;a(n===0?`connecting`:`reconnecting`);let o=window.location.protocol===`https:`?`wss:`:`ws:`,x=new WebSocket(`${o}//${window.location.host}/api/v1/gateway`,`piagent.gateway.v1`);p.current=x,Sn.attach(x);let w=window.setTimeout(()=>x.close(1008,`hello-timeout`),5e3);x.addEventListener(`open`,()=>x.send(JSON.stringify({schemaVersion:1,version:`piagent-gateway-protocol-v1`,messageType:`connect`,clientRef:u,minimumProtocol:1,maximumProtocol:1,lastEventSequence:m.current,catalogRevision:f.current?.catalogRevision??null}))),x.addEventListener(`message`,e=>{let t;try{t=JSON.parse(String(e.data))}catch{x.close(1007,`invalid-json`);return}if(!t||typeof t!=`object`){x.close(1008,`invalid-frame`);return}let o=t;if(o.messageType===`hello`){window.clearTimeout(w);let e=typeof o.capabilities?.gatewayInstanceRef==`string`?o.capabilities.gatewayInstanceRef:null;if(!e||v.current&&e!==v.current){m.current=null,y.current=!0,i=!0,x.close(Uo,`gateway-epoch-changed`);return}v.current=e,n=0,r(o.capabilities),a(`connected`);return}if(o.messageType===`response`){let e=S.current.get(String(o.requestId));if(!e)return;S.current.delete(String(o.requestId)),window.clearTimeout(e.timeout),o.ok===!0&&o.result?e.resolve(o.result):e.reject(new us(String(o.error?.code??`gateway-request-failed`),!1));return}if(o.messageType!==`event`||!Number.isSafeInteger(o.sequence))return;let u=o.payload,f=typeof o.generatedAt==`string`?o.generatedAt:new Date().toISOString(),p=typeof u.messageRequestId==`string`?u.messageRequestId:null,h=e=>e&&p&&e.messageRequestId&&e.messageRequestId!==p?void 0:e;if(o.kind===`resync.required`){y.current=!0,i=!0,x.close(Uo,`canonical-resync-required`);return}let b=Number(o.sequence),T=m.current;if(!(T!==null&&b<=T)){if(T!==null&&b!==T+1){y.current=!0,i=!0,x.close(Uo,`gateway-event-sequence-gap`);return}if(m.current=b,v.current&&C(v.current,b),typeof u?.sessionRef==`string`&&typeof u.operationRef==`string`&&[`runtime.changed`,`message.delta`,`tool.started`,`tool.completed`,`message.completed`,`operation.settled`].includes(String(o.kind))&&(g.current+=1,_.current.set(u.sessionRef,{serial:g.current,operationRef:u.operationRef,messageRequestId:p,complete:[`message.completed`,`operation.settled`].includes(String(o.kind))})),o.kind===`message.delta`&&typeof u?.sessionRef==`string`&&typeof u.delta==`string`&&l(e=>{let t=h(e[u.sessionRef]);return{...e,[u.sessionRef]:{...t??{user:``,assistant:``,attachments:[],activities:[],complete:!1,error:null},operationRef:u.operationRef,messageRequestId:p??t?.messageRequestId,abortable:!0,complete:!1,delivery:t?.user?`admitted`:t?.delivery,...li(t,u.messageRef,u.delta),startedAt:t?.startedAt??f,lastEventAt:f}}}),[`tool.started`,`tool.completed`].includes(String(o.kind))&&typeof u?.sessionRef==`string`&&typeof u.toolCallRef==`string`&&typeof u.toolLabel==`string`&&c(e=>{let t=h(e[u.sessionRef])??{user:``,assistant:``,attachments:[],activities:[],operationRef:u.operationRef??null,abortable:!0,complete:!1,error:null,runtimeRecovery:null},n=o.kind===`tool.started`?`running`:u.isError===!0?`failed`:`completed`,r=t.activities.find(e=>e.toolCallRef===u.toolCallRef),i=[...t.activities.filter(e=>e.toolCallRef!==u.toolCallRef),{toolCallRef:u.toolCallRef,toolLabel:u.toolLabel,fileLabel:typeof u.fileLabel==`string`?u.fileLabel:r?.fileLabel??null,state:n,reasonCode:u.reasonCode??null,startedAt:r?.startedAt??f,finishedAt:n===`running`?null:f}].slice(-16),a=u.reasonCode===`runtime-restart-required`?`required`:t.runtimeRecovery;return{...e,[u.sessionRef]:{...t,operationRef:u.operationRef??t.operationRef,messageRequestId:p??t.messageRequestId,activities:i,complete:!1,delivery:t.user?`admitted`:t.delivery,runtimeRecovery:a,startedAt:t.startedAt??f,lastEventAt:f}}}),o.kind===`runtime.changed`&&typeof u?.sessionRef==`string`&&c(e=>{let t=[`running`,`paused`,`waiting-approval`].includes(String(u.liveState)),n=h(e[u.sessionRef])??(t&&typeof u.operationRef==`string`?{user:``,assistant:``,attachments:[],activities:[],operationRef:u.operationRef,messageRequestId:p,abortable:!0,complete:!1,settlement:null,error:null,runtimeRecovery:null}:null);if(!n)return e;let r=u.reasonCode===`runtime-restart-required`?`restarting`:u.reasonCode===`runtime-restart-failed`?`failed`:[`required`,`restarting`].includes(String(n.runtimeRecovery))&&u.liveState===`idle`?`recovered`:n.runtimeRecovery;return t?{...e,[u.sessionRef]:{...n,operationRef:u.operationRef??n.operationRef,messageRequestId:p??n.messageRequestId,abortable:!0,complete:!1,settlement:null,delivery:n.user?`admitted`:n.delivery,runtimeRecovery:r,startedAt:n.startedAt??f,lastEventAt:f}}:!n.complete&&u.operationRef===null?{...e,[u.sessionRef]:{...n,assistant:``,activities:[],abortable:!1,complete:!0,settlement:`unknown`,messageRequestId:p??n.messageRequestId,error:u.reasonCode??`operation-settlement-unknown`,runtimeRecovery:r,lastEventAt:f}}:r===n.runtimeRecovery?e:{...e,[u.sessionRef]:{...n,runtimeRecovery:r}}}),o.kind===`message.completed`&&typeof u?.sessionRef==`string`&&c(e=>{let t=h(e[u.sessionRef]);return{...e,[u.sessionRef]:{...t??{user:``,assistant:``,attachments:[],activities:[],operationRef:u.operationRef,error:null},operationRef:u.operationRef,messageRequestId:p??t?.messageRequestId,abortable:!1,complete:!0,settlement:`completed`,delivery:t?.user?`admitted`:t?.delivery,error:null,lastEventAt:f}}}),o.kind===`operation.settled`&&typeof u?.sessionRef==`string`&&typeof u.operationRef==`string`){c(e=>{let t=h(e[u.sessionRef])??{user:``,assistant:``,attachments:[],activities:[],operationRef:u.operationRef,complete:!1,error:null,runtimeRecovery:null};return t.operationRef&&t.operationRef!==u.operationRef?e:{...e,[u.sessionRef]:{...bi(t,{operationRef:u.operationRef,settlement:u.settlement,reasonCode:u.reasonCode}),messageRequestId:p??t.messageRequestId,lastEventAt:f}}});let e=_i({operationRef:u.operationRef,settlement:u.settlement,reasonCode:u.reasonCode,settledAt:o.generatedAt,sequence:b});e&&d(t=>({...t,[u.sessionRef]:vi(t[u.sessionRef]??[],[e])}))}[`catalog.changed`,`session.changed`,`runtime.changed`,`message.completed`,`operation.settled`].includes(String(o.kind))&&s(),[`session.changed`,`tool.completed`,`operation.settled`].includes(String(o.kind))&&typeof u?.sessionRef==`string`&&window.dispatchEvent(new CustomEvent(`piagent-workspace-changed`,{detail:{sessionRef:u.sessionRef}}))}}),x.addEventListener(`close`,()=>{window.clearTimeout(w);for(let e of S.current.values())window.clearTimeout(e.timeout),e.reject(new us(`gateway-connection-lost`,!0));if(S.current.clear(),!e){if(a(`reconnecting`),i){i=!1,b();return}n+=1,t=window.setTimeout(h,Math.min(5e3,250*2**Math.min(n,5))*(.5+Math.random()))}}),x.addEventListener(`error`,()=>{})},b=async()=>{if(e||Le())return;let r=await w({requireLiveState:!0});if(!e){if(r){n=0,h();return}a(`reconnecting`),n+=1,t=window.setTimeout(()=>void b(),Math.min(5e3,250*2**Math.min(n,5))*(.5+Math.random()))}};(async()=>{let t=await ze();if(!e){if(t===`failed`){a(`failed`);return}await b()}})();let x=()=>{!e&&document.visibilityState===`visible`&&w()};return document.addEventListener(`visibilitychange`,x),()=>{e=!0,t&&window.clearTimeout(t),o.stop();for(let e of S.current.values())window.clearTimeout(e.timeout),e.reject(new us(`gateway-client-unmounted`,!0));S.current.clear(),p.current?.close(1e3,`client-unmount`),document.removeEventListener(`visibilitychange`,x)}},[C,w]),{catalog:e,capabilities:n,connection:i,live:o,terminalActivities:u,refresh:w,create:D,send:O,abort:k,restart:A,setModel:M,setThinking:N,setPermission:P,setFast:F,rename:L,pin:R,archive:z,unarchive:ee,fork:B}}async function Ss(){let e=await fetch(`/api/v1/preferences`,{credentials:`same-origin`,headers:{Accept:`application/json`}});return e.ok?await e.json():null}async function Cs(e){let t=Fe();t&&await Pe(`/api/v1/preferences`,{method:`POST`,credentials:`same-origin`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Piagent-CSRF":t},body:JSON.stringify(e)})}function ws(e,t,n){let r=(0,$.useRef)(!1),i=(0,$.useRef)(t);i.current=t,(0,$.useEffect)(()=>{if(!e||r.current)return;let t=!1;return Ss().then(e=>{t||!e||(r.current=!0,e.locale&&n.setLocale(e.locale),e.themeId&&Ae(e.themeId)&&n.setThemeId(e.themeId),(!e.locale||!e.themeId)&&Cs({...i.current,...e}).catch(()=>{}))}).catch(()=>{}),()=>{t=!0}},[e]),(0,$.useEffect)(()=>{r.current&&Cs(t).catch(()=>{})},[t.locale,t.themeId])}function Ts(){let e=xs(),{locale:t,themeId:n,setLocale:r,setThemeId:i}=Oe();return ws(!!e.catalog,{locale:t,themeId:n},{setLocale:r,setThemeId:i}),(0,Q.jsx)(Rt,{children:(0,Q.jsx)(as,{...e})})}export{Ts as default};