@piagent/platform 1.50.0 → 1.51.1

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 (116) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/catalog/capabilities.json +2 -2
  3. package/docs/command-reference-vietnamese.md +5 -3
  4. package/docs/company-dev-commands.md +1 -1
  5. package/docs/distribution-standard.md +6 -6
  6. package/docs/herdr-workflow.md +30 -0
  7. package/docs/operator-manual-vietnamese.md +7 -7
  8. package/docs/publishing-for-teams.md +2 -0
  9. package/docs/release-install-policy.md +2 -2
  10. package/docs/security-threat-model.md +2 -0
  11. package/docs/team-onboarding.md +2 -2
  12. package/docs-site/architecture.html +1 -1
  13. package/docs-site/assets/search-en.json +1 -1
  14. package/docs-site/assets/search-vi.json +1 -1
  15. package/docs-site/benchmark.html +1 -1
  16. package/docs-site/commands.html +1 -1
  17. package/docs-site/content/en/workflows.html +6 -0
  18. package/docs-site/content/workflows.html +6 -0
  19. package/docs-site/context-engine.html +1 -1
  20. package/docs-site/ecosystem.html +1 -1
  21. package/docs-site/en/architecture.html +1 -1
  22. package/docs-site/en/benchmark.html +1 -1
  23. package/docs-site/en/commands.html +1 -1
  24. package/docs-site/en/context-engine.html +1 -1
  25. package/docs-site/en/ecosystem.html +1 -1
  26. package/docs-site/en/index.html +15 -15
  27. package/docs-site/en/mcp-approval.html +1 -1
  28. package/docs-site/en/mcp-auth.html +1 -1
  29. package/docs-site/en/mcp-servers.html +1 -1
  30. package/docs-site/en/mcp.html +1 -1
  31. package/docs-site/en/permissions.html +1 -1
  32. package/docs-site/en/profiles.html +1 -1
  33. package/docs-site/en/quickstart.html +1 -1
  34. package/docs-site/en/runtime.html +1 -1
  35. package/docs-site/en/scope.html +1 -1
  36. package/docs-site/en/security.html +1 -1
  37. package/docs-site/en/team.html +1 -1
  38. package/docs-site/en/update.html +3 -3
  39. package/docs-site/en/whats-new.html +54 -30
  40. package/docs-site/en/windows.html +1 -1
  41. package/docs-site/en/workflows.html +7 -1
  42. package/docs-site/index.html +15 -15
  43. package/docs-site/mcp-approval.html +1 -1
  44. package/docs-site/mcp-auth.html +1 -1
  45. package/docs-site/mcp-servers.html +1 -1
  46. package/docs-site/mcp.html +1 -1
  47. package/docs-site/permissions.html +1 -1
  48. package/docs-site/profiles.html +1 -1
  49. package/docs-site/quickstart.html +1 -1
  50. package/docs-site/releases.json +72 -0
  51. package/docs-site/runtime.html +1 -1
  52. package/docs-site/scope.html +1 -1
  53. package/docs-site/security.html +1 -1
  54. package/docs-site/team.html +1 -1
  55. package/docs-site/update.html +3 -3
  56. package/docs-site/whats-new.html +54 -30
  57. package/docs-site/windows.html +1 -1
  58. package/docs-site/workflows.html +7 -1
  59. package/evals/private-holdout-v1/public-exposure.v2.json +2 -2
  60. package/package.json +2 -1
  61. package/packages/piagent-core/extensions/fallback-base-policy.ts +1 -1
  62. package/packages/piagent-core/extensions/guard-types.ts +4 -1
  63. package/packages/piagent-core/{managed/herdr-reporter.mjs → extensions/herdr-reporter.js} +29 -13
  64. package/packages/piagent-core/extensions/piagent-guard.ts +20 -9
  65. package/packages/piagent-core/extensions/session-status.d.ts +1 -0
  66. package/packages/piagent-core/extensions/session-status.js +217 -0
  67. package/packages/piagent-core/managed/check-questions.mjs +24 -14
  68. package/packages/piagent-core/managed/command-tools.mjs +46 -7
  69. package/packages/piagent-core/managed/dist/workspace/assets/packages/piagent-core/policies/base-policy.json +2 -1
  70. package/packages/piagent-core/managed/dist/workspace/manifest.json +1 -1
  71. package/packages/piagent-core/managed/fetch-guard.mjs +2 -1
  72. package/packages/piagent-core/managed/helper-run.mjs +4 -2
  73. package/packages/piagent-core/managed/host-command.mjs +8 -4
  74. package/packages/piagent-core/managed/member-mcp.mjs +2 -0
  75. package/packages/piagent-core/managed/permission.mjs +11 -3
  76. package/packages/piagent-core/managed/session.mjs +5 -5
  77. package/packages/piagent-core/managed/tool-boundary.mjs +4 -4
  78. package/packages/piagent-core/package.json +1 -1
  79. package/packages/piagent-core/policies/base-policy.json +2 -1
  80. package/packages/piagent-core/runtime/hooks/session-start-hook.ts +3 -0
  81. package/packages/piagent-core/runtime/policy/critical-removal.mjs +122 -0
  82. package/packages/piagent-core/runtime/policy/handoff-policy.mjs +23 -4
  83. package/packages/piagent-core/runtime/registration/permission-commands.ts +14 -6
  84. package/packages/piagent-core/runtime/registration/task-evidence-tools.ts +1 -1
  85. package/packages/piagent-webui/dist/client/assets/{ActivityPanel-CmjxPmNT.js → ActivityPanel-DeeJLOYx.js} +1 -1
  86. package/packages/piagent-webui/dist/client/assets/App-C9tlGPMb.js +5 -0
  87. package/packages/piagent-webui/dist/client/assets/{GatewayApp-BmkqeXih.js → GatewayApp-Dvo96qoX.js} +17 -17
  88. package/packages/piagent-webui/dist/client/assets/{InspectionApp-9jBsgkVJ.js → InspectionApp-CGgHsOyC.js} +1 -1
  89. package/packages/piagent-webui/dist/client/assets/{SessionAgentWorkspace-RQ0N65d9.js → SessionAgentWorkspace-n8UMMcrP.js} +1 -1
  90. package/packages/piagent-webui/dist/client/assets/{SessionInspectorDrawer-BWyEN4bf.js → SessionInspectorDrawer-B62kkr8J.js} +2 -2
  91. package/packages/piagent-webui/dist/client/assets/SettingsNavigation-BZijmuPt.js +3 -0
  92. package/packages/piagent-webui/dist/client/assets/SettingsPage-DKg0SfZQ.js +1 -0
  93. package/packages/piagent-webui/dist/client/assets/{TerminalPanel-DzHdSjpN.js → TerminalPanel-BPTVsNjP.js} +1 -1
  94. package/packages/piagent-webui/dist/client/assets/{WorkspaceCodeEditor-CEuPTTBd.js → WorkspaceCodeEditor-BHGFFBc2.js} +1 -1
  95. package/packages/piagent-webui/dist/client/assets/{WorkspaceExplorer-B_NwYf4S.js → WorkspaceExplorer-nd4kghwK.js} +3 -3
  96. package/packages/piagent-webui/dist/client/assets/{index-fUpioGMZ.js → index-BiLVX8S-.js} +2 -2
  97. package/packages/piagent-webui/dist/client/assets/{transcript-view-model-acWtHGyE.js → transcript-view-model-BB1niiXd.js} +1 -1
  98. package/packages/piagent-webui/dist/client/assets/{view-model-CWNiS4JN.js → view-model-BrdSO09E.js} +1 -1
  99. package/packages/piagent-webui/dist/client/index.html +1 -1
  100. package/packages/piagent-webui/gateway/managed-projection.ts +1 -1
  101. package/packages/piagent-webui/gateway/runtime-session-controls.ts +1 -1
  102. package/packages/piagent-webui/gateway/session-command-controller.ts +4 -4
  103. package/packages/piagent-webui/gateway/session-inspection-registry.ts +1 -1
  104. package/packages/piagent-webui/gateway/session-runtime-supervisor.ts +1 -1
  105. package/schemas/piagent-webui/session-catalog-v1.schema.json +1 -1
  106. package/schemas/piagent-webui/session-command-v1.schema.json +1 -1
  107. package/schemas/piagent-webui/snapshot-v1.schema.json +2 -1
  108. package/schemas/project-profile.schema.json +2 -1
  109. package/scripts/company-terminal.mjs +8 -7
  110. package/scripts/pi-auto.sh +5 -1
  111. package/scripts/piagent-cli.mjs +3 -1
  112. package/scripts/piagent-sessions.mjs +97 -0
  113. package/scripts/piagent-studio.mjs +5 -3
  114. package/packages/piagent-webui/dist/client/assets/App-JrRb7jgn.js +0 -5
  115. package/packages/piagent-webui/dist/client/assets/SettingsNavigation-Wx-q5QQk.js +0 -3
  116. package/packages/piagent-webui/dist/client/assets/SettingsPage-xAt6kSyZ.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/WorkspaceCodeEditor-CEuPTTBd.js","assets/rolldown-runtime-hePW80VL.js","assets/vendor-DNZbaWhT.js","assets/ui-preferences-OfS30-ZV.js","assets/index-fUpioGMZ.js","assets/index-De7bIeMc.css","assets/dist-D6i5SpQu.js"])))=>i.map(i=>d[i]);
2
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{An as t,Bt as n,Et as r,G as i,Gt as a,Ht as o,K as s,Kt as c,Ln as l,Lt as u,R as d,Rn as f,Tt as p,Ut as m,Vt as h,W as g,Wt as _,Xt as v,bt as y,qt as b,t as ee}from"./vendor-DNZbaWhT.js";import{i as x,n as S}from"./ui-preferences-OfS30-ZV.js";import{t as C}from"./index-fUpioGMZ.js";import{i as w,n as T,o as E}from"./bootstrap-CedkNtRG.js";import{G as D,lt as te}from"./api-BQS4Dtrr.js";import{l as O}from"./workspace-navigation-DW8zhH6U.js";import{r as k}from"./composer-drafts-BtMaVw8W.js";import{a as A,c as j,d as M,f as N,i as P,l as F,o as I,s as L,t as ne,u as re}from"./LineReview-CB3mQe7m.js";import{a as ie,i as ae,o as oe,t as R}from"./workspace-api-CFBR73lU.js";import{n as se,t as ce}from"./WorkspaceFilePreview-CvIBYige.js";import{t as le}from"./tab-close-BwkkhMH7.js";var z=e(f(),1),B=t();function ue(e,t,n,a=[]){let{locale:o}=x(),[s,c]=(0,z.useState)(()=>j(e)),[l,u]=(0,z.useState)();(0,z.useEffect)(()=>{c(j(e)),u(void 0);let t=t=>{t.detail===e&&c(j(e))};return window.addEventListener(I,t),()=>window.removeEventListener(I,t)},[e]),(0,z.useEffect)(()=>u(void 0),[t]);let d=t=>{c(t),M(e,t)},f={locale:o,comments:s,editing:l?L(l.path,l.side,l.line):null,open:(e,t,n,r)=>u({path:e,line:n,code:r,side:t}),cancel:()=>u(void 0),save:t=>{l&&d(re(j(e),{...l,text:t})),u(void 0)},remove:t=>d(j(e).filter(e=>L(e.path,e.side,e.line)!==t))},p=new Map(n.split(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/WorkspaceCodeEditor-BHGFFBc2.js","assets/rolldown-runtime-hePW80VL.js","assets/vendor-DNZbaWhT.js","assets/ui-preferences-OfS30-ZV.js","assets/index-BiLVX8S-.js","assets/index-De7bIeMc.css","assets/dist-D6i5SpQu.js"])))=>i.map(i=>d[i]);
2
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{An as t,Bt as n,Et as r,G as i,Gt as a,Ht as o,K as s,Kt as c,Ln as l,Lt as u,R as d,Rn as f,Tt as p,Ut as m,Vt as h,W as g,Wt as _,Xt as v,bt as y,qt as b,t as ee}from"./vendor-DNZbaWhT.js";import{i as x,n as S}from"./ui-preferences-OfS30-ZV.js";import{t as C}from"./index-BiLVX8S-.js";import{i as w,n as T,o as E}from"./bootstrap-CedkNtRG.js";import{G as D,lt as te}from"./api-BQS4Dtrr.js";import{l as O}from"./workspace-navigation-DW8zhH6U.js";import{r as k}from"./composer-drafts-BtMaVw8W.js";import{a as A,c as j,d as M,f as N,i as P,l as F,o as I,s as L,t as ne,u as re}from"./LineReview-CB3mQe7m.js";import{a as ie,i as ae,o as oe,t as R}from"./workspace-api-CFBR73lU.js";import{n as se,t as ce}from"./WorkspaceFilePreview-CvIBYige.js";import{t as le}from"./tab-close-BwkkhMH7.js";var z=e(f(),1),B=t();function ue(e,t,n,a=[]){let{locale:o}=x(),[s,c]=(0,z.useState)(()=>j(e)),[l,u]=(0,z.useState)();(0,z.useEffect)(()=>{c(j(e)),u(void 0);let t=t=>{t.detail===e&&c(j(e))};return window.addEventListener(I,t),()=>window.removeEventListener(I,t)},[e]),(0,z.useEffect)(()=>u(void 0),[t]);let d=t=>{c(t),M(e,t)},f={locale:o,comments:s,editing:l?L(l.path,l.side,l.line):null,open:(e,t,n,r)=>u({path:e,line:n,code:r,side:t}),cancel:()=>u(void 0),save:t=>{l&&d(re(j(e),{...l,text:t})),u(void 0)},remove:t=>d(j(e).filter(e=>L(e.path,e.side,e.line)!==t))},p=new Map(n.split(`
3
3
  `).map((e,n)=>[L(t??``,`new`,n+1),e.slice(0,400)]));for(let e of a)for(let n of e.lines)n.oldLineNumber!==null&&p.set(L(t??``,`old`,n.oldLineNumber),n.text.slice(0,400));return{open:(e,n,r=`new`)=>{t&&u({path:t,line:e,code:n,side:r})},dialog:(0,B.jsxs)(r,{open:!!l,onClose:()=>u(void 0),fullWidth:!0,children:[(0,B.jsxs)(g,{children:[S(o,`Comment theo dòng`,`Line comment`),` · `,l?.path,`:`,l?.line]}),(0,B.jsx)(i,{children:(0,B.jsx)(A.Provider,{value:f,children:l&&(0,B.jsx)(P,{path:l.path,side:l.side,line:l.line})})})]}),bar:(0,B.jsx)(ne,{comments:s,lines:p,linesPath:t,locale:o,onClear:()=>d([]),onSend:()=>{let t=j(e);t.length&&k(e,F(t,o===`en`)),d([])}})}}var V=new Map;function de(e,t,o,c,l){let{locale:u}=x(),d=`${e}\0${t??``}`,f=`${d}\0${o}\0${c}`,p=(0,z.useRef)(f);p.current=f;let h=(0,z.useRef)(d);h.current=d;let v=(0,z.useRef)(!1),[y,b]=(0,z.useState)(!1),[ee,C]=(0,z.useState)(!1),[w,T]=(0,z.useState)(),[E,O]=(0,z.useState)(),[k,A]=(0,z.useState)(!1);(0,z.useEffect)(()=>{C(!1),T(void 0),O(void 0),A(V.has(d))},[d]);let j=async n=>{if(!(v.current||!c||!l||l.file.path!==t||l.file.currentDigest!==`sha256:${o}`)&&(C(!0),O(void 0),T(void 0),A(V.has(d)),!V.has(d))){v.current=!0,b(!0);try{let r=await D(e,l.file.fileRef,n);if(p.current!==f)return;if(r.state!==`ready`||!r.target||r.target.path!==t||r.target.fileRef!==l.file.fileRef||r.target.fileRevision!==l.file.fileRevision||!r.target.hunkRefs.some(e=>e===n))throw Error(`preview-unavailable`);T({value:r,scope:f})}catch{p.current===f&&O(S(u,`Chưa thể hoàn tác an toàn. Tải lại diff và thử lại.`,`Safe revert is unavailable. Refresh the diff and try again.`))}finally{v.current=!1,b(!1)}}},M=async()=>{if(!(v.current||!c||!V.has(d)&&(!w||w.scope!==f))){v.current=!0,b(!0),O(void 0);try{let t=V.get(d)??await N(w.value);if(p.current!==f)return;if(!V.has(d)&&V.size>=128){O(S(u,`Có quá nhiều lệnh chưa rõ kết quả. Kiểm tra lại các lệnh trước trước khi hoàn tác thêm.`,`Too many commands still need their results checked. Check earlier commands before reverting more.`));return}V.set(d,t),A(!0);let n=await te(t,void 0,e);if(n.phase!==`uncertain`&&V.delete(d),h.current===d&&A(V.has(d)),window.dispatchEvent(new CustomEvent(`piagent-workspace-changed`,{detail:{sessionRef:e}})),p.current!==f)return;A(V.has(d)),n.phase===`settled`?(C(!1),T(void 0)):(n.phase===`rejected`&&T(void 0),O(n.phase===`uncertain`?S(u,`Chưa xác định được kết quả. Kiểm tra tệp; kiểm tra lại sẽ dùng đúng lệnh cũ.`,`The result is uncertain. Inspect the file; checking again uses the same command.`):S(u,`Tệp hoặc quyền đã thay đổi. Hãy đóng và xem preview mới.`,`The file or permission changed. Close this dialog and request a new preview.`)))}catch{p.current===f&&O(S(u,`Chưa nhận được kết quả. Kiểm tra lại dùng cùng lệnh, không tạo lần hoàn tác mới.`,`No result received. Checking again reuses the same command.`))}finally{v.current=!1,b(!1)}}},P=w&&w.scope!==f;return{request:j,dialog:(0,B.jsxs)(r,{open:ee,onClose:()=>{y||C(!1)},fullWidth:!0,maxWidth:`md`,children:[(0,B.jsx)(g,{children:S(u,`Hoàn tác thay đổi của agent`,`Revert agent changes`)}),(0,B.jsxs)(i,{children:[(0,B.jsx)(n,{children:t}),(0,B.jsx)(n,{children:S(u,`Các dòng dưới đây sẽ được hoàn tác. Git index được giữ nguyên.`,`The changes below will be reverted. The Git index is preserved.`)}),E&&(0,B.jsx)(a,{severity:`warning`,children:E}),P&&(0,B.jsx)(a,{severity:`warning`,children:S(u,`Nội dung editor đã đổi. Mở lại preview trước khi hoàn tác.`,`Editor contents changed. Open a new preview before reverting.`)}),k&&!w&&(0,B.jsx)(a,{severity:`info`,children:S(u,`Có lệnh chưa xác nhận kết quả cho tệp này.`,`A command for this file still needs its result confirmed.`)}),w?.value.preview?.hunks.map(e=>(0,B.jsxs)(_,{component:`pre`,sx:{whiteSpace:`pre-wrap`,overflowWrap:`anywhere`},children:[e.header,`
4
4
  `,e.lines.map(e=>`${e.marker}${e.text}`).join(`
5
- `)]},e.hunkRef))]}),(0,B.jsxs)(s,{children:[(0,B.jsx)(m,{disabled:y,onClick:()=>C(!1),children:S(u,`Đóng`,`Close`)}),(0,B.jsx)(m,{color:`error`,disabled:y||!c||!k&&(!w||!!P),onClick:()=>void M(),children:k?S(u,`Kiểm tra lại`,`Check again`):S(u,`Xác nhận hoàn tác`,`Confirm revert`)})]})]}),hasPending:k,checkPending:()=>{A(V.has(d)),C(!0)}}}async function H(e,t,n){let r=await fetch(`/api/v1/sessions/${encodeURIComponent(e)}/source-review${t?`/${encodeURIComponent(t)}`:``}`,{credentials:`same-origin`,headers:{Accept:`application/json`},signal:n});if(r.status===401&&E(),!r.ok)throw Error(`source-review-unavailable`);return r.json()}var U=(e,t)=>H(e,void 0,t),fe=(e,t,n)=>H(e,t,n);function pe(e,t,n,r,i){if(!e||!r||!n||e.file.path!==t||e.file.currentDigest!==`sha256:${n}`||e.availability.state!==`current`||e.truncation.truncated||e.redaction.applied)return[];let a=new Set(e.agentHunkRefs??[]);return e.hunks.filter(e=>a.has(e.hunkRef)&&!i.has(`${t}:${n}:${e.hunkRef}`))}var W=new Set,G=new Map,K=new Set,q=`piagent.kept-hunks.`,J=`piagent.kept-hunks`;function Y(e){try{let t=JSON.parse(localStorage.getItem(q+e)??`[]`);return Array.isArray(t)?new Set(t.filter(e=>typeof e==`string`).slice(-4096)):W}catch{return W}}function me(e,t){try{let n=[...JSON.parse(localStorage.getItem(J)??`[]`).filter(t=>t!==e),e];for(let e of n.splice(0,Math.max(0,n.length-64)))localStorage.removeItem(q+e);localStorage.setItem(q+e,JSON.stringify([...t])),localStorage.setItem(J,JSON.stringify(n))}catch{}}var he=e=>(G.has(e)||G.set(e,Y(e)),G.get(e)??W);function ge(e,t,n,r){let i=new Set([...he(e),`${t}:${n}:${r}`].slice(-4096));for(G.delete(e),G.set(e,i);G.size>64;)G.delete(G.keys().next().value);me(e,i);for(let e of K)e()}function X(e){return(0,z.useSyncExternalStore)(e=>(K.add(e),()=>{K.delete(e)}),()=>he(e))}function _e(e,t,n){let[r,i]=(0,z.useState)(),a=X(e),o=JSON.stringify(t.map(e=>e.file.path).sort());(0,z.useEffect)(()=>{let t=JSON.parse(o);if(!t.length){i(void 0);return}let n=new AbortController,r=!1,a=!1,s=async()=>{if(!n.signal.aborted){if(r){a=!0;return}r=!0;try{let r=await U(e,n.signal),a=new Map;for(let i of t){if(n.signal.aborted)return;let t=r.files.find(e=>e.path===i&&e.pathDisplay===`exact-safe`);if(t)try{a.set(i,await fe(e,t.fileRef,n.signal))}catch{}}n.signal.aborted||i({session:e,diffs:a})}catch{n.signal.aborted||i(void 0)}finally{r=!1,a&&!n.signal.aborted&&(a=!1,s())}}};s();let c=window.setInterval(()=>void s(),3e3),l=t=>{t.detail?.sessionRef===e&&s()};return window.addEventListener(`piagent-workspace-saved`,l),window.addEventListener(`piagent-workspace-changed`,l),()=>{n.abort(),clearInterval(c),window.removeEventListener(`piagent-workspace-saved`,l),window.removeEventListener(`piagent-workspace-changed`,l)}},[e,o]);let s=r?.session===e?r.diffs:void 0,c=e=>pe(s?.get(e.file.path),e.file.path,e.file.digest,!e.fresh&&!e.pending&&e.draft===(e.file.content??``),a),l=t.find(e=>e.file.path===n),u=l?c(l):[];return{diff:n?s?.get(n):void 0,hunks:u,counts:new Map(t.map(e=>[e.file.path,c(e).length])),keep:t=>{l?.file.digest&&u.some(e=>e.hunkRef===t)&&ge(e,l.file.path,l.file.digest,t)}}}var Z=new Map,ve=new Set,ye={tabs:[]},Q=e=>e.fresh||e.draft!==(e.file.content??``);window.addEventListener(`beforeunload`,e=>{[...Z.values()].some(e=>e.tabs.some(Q))&&(e.preventDefault(),e.returnValue=``)});var be=e=>Z.get(e)??ye;function xe(e){let t=(0,z.useSyncExternalStore)(e=>(ve.add(e),()=>{ve.delete(e)}),()=>Z.get(e)??ye),n=t=>{Z.set(e,t(Z.get(e)??ye));for(let e of ve)e()};return{...t,update:n}}function Se(e,t,n){return e.file!==t||e.file.path!==n.path||e.pending||e.fresh||e.file.digest===n.digest&&e.file.protected===n.protected&&e.file.readOnly===n.readOnly?{tab:e}:e.draft===(e.file.content??``)?{tab:{...e,file:n,draft:n.content??``}}:{tab:e,conflict:n}}function Ce(e,t,n){let{update:r}=xe(e),i=(0,z.useRef)({update:r,conflict:n});i.current={update:r,conflict:n},(0,z.useEffect)(()=>{let n=new AbortController,r=new Map,a=!1,o=!1,s,c=async()=>{if(!(n.signal.aborted||t.current)){if(a){o=!0;return}a=!0;try{for(let a of be(e).tabs)if(!(a.fresh||a.pending||t.current))try{let o=await R(e,a.file.path,n.signal);if(n.signal.aborted||t.current)return;let s;if(i.current.update(e=>({...e,tabs:e.tabs.map(t=>{if(t.file.path!==a.file.path)return t;let n=Se(t,a.file,o);return n.conflict&&e.active===t.file.path&&(s=n.conflict),n.tab})})),s){let e=`${s.digest}:${s.protected}:${s.readOnly}`;r.get(s.path)!==e&&(r.set(s.path,e),i.current.conflict(s))}}catch{}}finally{a=!1,o&&!n.signal.aborted&&(o=!1,l())}}},l=()=>{s||=setTimeout(()=>{s=void 0,c()},100)},u=t=>{t.detail?.sessionRef===e&&l()};window.addEventListener(`piagent-workspace-changed`,u),window.addEventListener(`piagent-workspace-saved`,u);let d=setInterval(l,5e3);return l(),()=>{n.abort(),clearTimeout(s),clearInterval(d),window.removeEventListener(`piagent-workspace-changed`,u),window.removeEventListener(`piagent-workspace-saved`,u)}},[e,t])}var we=e=>`/api/v1/sessions/${encodeURIComponent(e)}/workspace/write`;function $(e){return Array.isArray(e)?`[${e.map($).join(`,`)}]`:e&&typeof e==`object`?`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${$(t)}`).join(`,`)}}`:JSON.stringify(e)}async function Te(e,t){let n=await fetch(we(e),{credentials:`same-origin`,signal:t,headers:{Accept:`application/json`}});if(n.status===401&&E(),!n.ok)throw Error(`workspace-write-unavailable`);return await n.json()}async function Ee(e,t){let n=Date.now(),r=`workspace.write`,i=e.identity,a=e.revisions,o=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode($({action:r,identity:i,expectedRevisions:a,payload:t})));return{schemaVersion:1,version:`piagent-webui-workspace-write-v1`,messageType:`command`,action:r,identity:i,expectedRevisions:a,payload:t,commandId:crypto.randomUUID(),idempotencyKey:crypto.randomUUID(),requestedAt:new Date(n).toISOString(),expiresAt:new Date(n+6e4).toISOString(),actionDigest:`sha256:${[...new Uint8Array(o)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`}}async function De(e,t){let n=T();if(!n)throw Error(`workspace-write-unavailable`);let r=await w(we(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&&E(),!r.ok)throw Error(`workspace-write-unavailable`);let i=await r.json(),a=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t.idempotencyKey)),o=`sha256:${[...new Uint8Array(a)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`;if(i.schemaVersion!==1||i.version!==t.version||i.messageType!==`receipt`||i.path!==t.payload.path||i.commandId!==t.commandId||i.action!==t.action||i.actionDigest!==t.actionDigest||i.idempotencyKeyDigest!==o||$(i.identity)!==$(t.identity)||![`settled`,`rejected`,`uncertain`].includes(i.phase)||i.phase===`settled`&&(i.resultCode!==`saved`||!/^[a-f0-9]{64}$/.test(i.digest??``)))throw Error(`workspace-write-receipt-invalid`);return i}function Oe(e){let{locale:t}=x(),n=xe(e),[r,i]=(0,z.useState)(),[a,o]=(0,z.useState)(!1),s=(0,z.useRef)(!1),[c,l]=(0,z.useState)(),[u,d]=(0,z.useState)();Ce(e,s,d),(0,z.useEffect)(()=>{let t=new AbortController,n=!1,r=()=>{n||(n=!0,Te(e,t.signal).then(i).catch(()=>{t.signal.aborted||i(void 0)}).finally(()=>{n=!1}))};r();let a=window.setInterval(r,5e3);return()=>{t.abort(),clearInterval(a)}},[e]);let f=(e,t=1,r=!1)=>n.update(n=>({active:e.path,tabs:[...n.tabs.filter(t=>t.file.path!==e.path),{file:e,line:t,fresh:r,draft:e.content??``}]})),p=(e,t)=>n.update(n=>({...n,active:e,tabs:n.tabs.map(n=>n.file.path===e&&t!==void 0?{...n,line:t}:n)})),m=(e,t)=>n.update(n=>({...n,tabs:n.tabs.map(n=>n.file.path===e?{...n,draft:t}:n)})),h=r=>{let i=be(e).tabs.find(e=>e.file.path===r);i&&(Q(i)||i.pending)&&!window.confirm(S(t,`Bỏ thay đổi chưa lưu và đóng tệp?`,`Discard unsaved changes and close this file?`))||n.update(e=>({tabs:e.tabs.filter(e=>e.file.path!==r),active:e.active===r?e.tabs.find(e=>e.file.path!==r)?.file.path:e.active}))},g=async n=>{try{f(await R(e,n)),d(void 0),l(void 0)}catch{l(S(t,`Chưa tải lại được tệp. Bản sửa của bạn vẫn được giữ.`,`Could not reload the file. Your draft is preserved.`))}},_=async(r,a)=>{let c=be(e).tabs.find(e=>e.file.path===r);if(!(!c||s.current||!Q(c)&&!c.pending||c.file.protected||c.file.readOnly)&&!(a&&!window.confirm(S(t,`Ghi đè phiên bản trên đĩa bằng bản sửa của bạn?`,`Replace the version on disk with your draft?`)))){s.current=!0,o(!0),l(void 0);try{let o=await Te(e);if(i(o),!o.writable)throw Error(`read-only`);let s=a?.digest??(c.fresh?`absent`:c.file.digest);if(!s)throw Error(`unavailable`);let u=c.pending??await Ee(o,{path:r,content:c.draft,expectedDigest:s});n.update(e=>({...e,tabs:e.tabs.map(e=>e.file.path===r?{...e,pending:u}:e)}));let f=await De(e,u);if(f.phase===`uncertain`){l(S(t,`Chưa xác định được kết quả lưu. Tải lại để kiểm tra trước khi lưu tiếp.`,`The save result is uncertain. Reload to check before saving again.`));return}n.update(e=>({...e,tabs:e.tabs.map(e=>e.file.path===r?{...e,pending:void 0}:e)})),f.phase===`settled`&&f.resultCode===`saved`?(n.update(e=>({...e,tabs:e.tabs.map(e=>e.file.path===r?{...e,fresh:!1,file:{...e.file,content:u.payload.content,digest:f.digest,revision:f.observedRevisionsAfter.workspaceRevision}}:e)})),d(void 0),window.dispatchEvent(new CustomEvent(`piagent-workspace-saved`,{detail:{sessionRef:e,path:r}}))):f.resultCode===`stale-content`||f.resultCode===`stale-revision`?d(await R(e,r)):l(S(t,`Chưa lưu được tệp. Kiểm tra quyền ghi và thử lại.`,`Could not save the file. Check write access and try again.`))}catch{l(S(t,`Chưa lưu được tệp. Bản sửa vẫn được giữ; thử lưu lại hoặc tải lại để kiểm tra.`,`Could not confirm the save. Your draft is preserved; retry the save or reload to check.`))}finally{s.current=!1,o(!1)}}},v=async(r,a)=>{let c=be(e).tabs.find(e=>e.file.path===r);if(s.current||c&&(Q(c)||c.pending))return l(S(t,`Lưu hoặc bỏ thay đổi trước khi đổi tên hay xóa tệp.`,`Save or discard your changes before renaming or deleting the file.`)),!1;s.current=!0,o(!0),l(void 0);try{let o=await Te(e);i(o);let s=c?.file.digest??(await R(e,r)).digest;if(!o.writable||!s)throw Error(`unavailable`);let u=await De(e,await Ee(o,a?{path:r,content:``,expectedDigest:s,operation:`rename`,destination:a}:{path:r,content:``,expectedDigest:s,operation:`delete`}));return u.phase===`settled`&&u.resultCode===`saved`?(n.update(e=>({tabs:e.tabs.filter(e=>e.file.path!==r),active:e.active===r?void 0:e.active})),a&&f(await R(e,a)),window.dispatchEvent(new CustomEvent(`piagent-workspace-saved`,{detail:{sessionRef:e,path:r}})),!0):(l(u.phase===`uncertain`?S(t,`Chưa xác định được kết quả. Tải lại danh sách tệp để kiểm tra.`,`The result is uncertain. Reload the file list to check.`):u.resultCode===`stale-content`?S(t,`Tệp đã thay đổi trên đĩa hoặc tên mới đã có. Tải lại rồi thử lại.`,`The file changed on disk or the new name exists. Reload and try again.`):S(t,`Không thực hiện được. Kiểm tra quyền ghi và tên tệp.`,`This could not be done. Check write access and the file name.`)),!1)}catch{return l(S(t,`Chưa xác nhận được thao tác. Tải lại danh sách tệp để kiểm tra.`,`Could not confirm the action. Reload the file list to check.`)),!1}finally{s.current=!1,o(!1)}};return{...n,authority:r,saving:a,message:c,conflict:u,setConflict:d,load:f,select:p,change:m,close:h,reload:g,save:_,move:v}}var ke=e(l(),1);function Ae({sessionRef:e,onOpen:t}){let{locale:r}=x(),[i,o]=(0,z.useState)(``),[s,c]=(0,z.useState)(),[l,u]=(0,z.useState)(!1),[d,f]=(0,z.useState)(!1);return(0,z.useEffect)(()=>{let t=new AbortController;if(c(void 0),f(!1),u(!1),!i.trim())return()=>t.abort();u(!0);let n=setTimeout(()=>{oe(e,i,t.signal).then(e=>{t.signal.aborted||c(e)}).catch(()=>{t.signal.aborted||f(!0)}).finally(()=>{t.signal.aborted||u(!1)})},250);return()=>{clearTimeout(n),t.abort()}},[i,e]),(0,B.jsxs)(p,{spacing:1,sx:{p:1},children:[(0,B.jsx)(y,{size:`small`,label:S(r,`Tìm nội dung`,`Search contents`),value:i,onChange:e=>o(e.target.value),slotProps:{htmlInput:{maxLength:512}}}),l&&(0,B.jsx)(b,{size:18}),(d||s?.available===!1)&&(0,B.jsx)(a,{severity:`warning`,children:S(r,`Chưa tìm được nội dung trong project này.`,`Content search is unavailable for this project.`)}),s?.available&&s.backend===`fts`&&(0,B.jsx)(n,{variant:`caption`,children:S(r,`Tìm trong các tệp đã lập chỉ mục.`,`Searching indexed files.`)}),s?.matches.map(e=>(0,B.jsxs)(m,{onClick:()=>t(e.path,e.line),sx:{textTransform:`none`,display:`block`,textAlign:`left`,overflowWrap:`anywhere`},children:[(0,B.jsxs)(n,{variant:`caption`,component:`span`,children:[e.path,`:`,e.line,`:`,e.column]}),(0,B.jsx)(n,{variant:`body2`,component:`span`,sx:{display:`block`},children:e.preview})]},`${e.path}:${e.line}:${e.column}`)),s?.truncated&&(0,B.jsx)(n,{variant:`caption`,children:S(r,`Đã giới hạn kết quả. Hãy tìm cụ thể hơn.`,`Results were limited. Refine your search.`)}),s?.available&&!s.matches.length&&!s.truncated&&(0,B.jsx)(n,{variant:`caption`,children:S(r,`Không tìm thấy.`,`No matches.`)})]})}var je=v((0,B.jsx)(`path`,{d:`M10 6 8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z`}),`ChevronRight`),Me=v((0,B.jsx)(`path`,{d:`M16.59 8.59 12 13.17 7.41 8.59 6 10l6 6 6-6z`}),`ExpandMore`),Ne=v((0,B.jsx)(`path`,{d:`M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8zM6 20V4h7v5h5v11z`}),`InsertDriveFileOutlined`),Pe=e=>e.split(`/`).slice(0,-1).map((e,t,n)=>n.slice(0,t+1).join(`/`));function Fe({sessionRef:e,refresh:t,active:r,onOpen:i,onFolder:a}){let{locale:o}=x(),[s,c]=(0,z.useState)(()=>new Set([``])),[l,f]=(0,z.useState)(()=>new Map),[p,h]=(0,z.useState)(),g=(t,n)=>{f(e=>new Map(e).set(t,e.get(t)??`loading`)),ae(e,t,n).then(e=>{n?.aborted||f(n=>new Map(n).set(t,e))}).catch(()=>{n?.aborted||f(e=>new Map(e).set(t,`error`))})};(0,z.useEffect)(()=>{f(new Map),c(new Set([``]))},[e]),(0,z.useEffect)(()=>{let e=new AbortController;for(let t of s)g(t,e.signal);return()=>e.abort()},[e,t]),(0,z.useEffect)(()=>{if(!r)return;let e=Pe(r).filter(e=>!s.has(e));if(e.length){c(t=>new Set([...t,...e]));for(let t of e)l.has(t)||g(t)}},[r]);let v=e=>{if(h(e),a(e),s.has(e)){c(t=>{let n=new Set(t);return n.delete(e),n});return}c(t=>new Set(t).add(e)),(!l.has(e)||l.get(e)===`error`)&&g(e)},y=(e,t)=>{let a=l.get(e);return!a||a===`loading`?(0,B.jsx)(b,{size:14,sx:{ml:1.5+t*1.5,my:.5}}):a===`error`?(0,B.jsx)(n,{variant:`caption`,color:`warning.main`,sx:{pl:1.5+t*1.5},children:S(o,`Chưa đọc được thư mục này.`,`This folder could not be read.`)}):(0,B.jsxs)(B.Fragment,{children:[a.entries.map(e=>{let n=e.kind===`directory`,a=n&&s.has(e.path),c=n?p===e.path:r===e.path,l=n?(0,B.jsxs)(B.Fragment,{children:[a?(0,B.jsx)(Me,{sx:{fontSize:16}}):(0,B.jsx)(je,{sx:{fontSize:16}}),a?(0,B.jsx)(d,{sx:{fontSize:16}}):(0,B.jsx)(u,{sx:{fontSize:16}})]}):(0,B.jsx)(Ne,{sx:{fontSize:16,ml:`16px`}});return(0,B.jsxs)(_,{children:[(0,B.jsxs)(m,{fullWidth:!0,size:`small`,disabled:e.protected||e.kind===`symlink`||e.kind===`other`,"aria-label":e.protected?`${e.name} (${S(o,`được bảo vệ`,`protected`)})`:e.name,"aria-expanded":n?a:void 0,"aria-current":!n&&r===e.path?`true`:void 0,onClick:()=>n?v(e.path):(h(void 0),i(e.path)),sx:{justifyContent:`flex-start`,textTransform:`none`,gap:.5,minHeight:24,py:0,pl:.5+t*1.5,pr:1,color:`text.primary`,fontWeight:400,whiteSpace:`nowrap`,bgcolor:c?`action.selected`:void 0},children:[l,(0,B.jsxs)(_,{component:`span`,sx:{overflow:`hidden`,textOverflow:`ellipsis`},children:[e.name,e.protected?` 🔒`:``]})]}),a&&y(e.path,t+1)]},e.path)}),a.truncated&&(0,B.jsx)(n,{variant:`caption`,sx:{pl:1.5+t*1.5},children:S(o,`Danh sách đã được giới hạn.`,`Listing limit reached.`)})]})};return(0,B.jsx)(_,{role:`group`,"aria-label":S(o,`Cây thư mục`,`Folder tree`),sx:{py:.5},children:y(``,0)})}var Ie=(0,z.lazy)(()=>C(()=>import(`./WorkspaceCodeEditor-CEuPTTBd.js`),__vite__mapDeps([0,1,2,3,4,5,6])));function Le({sessionRef:e,target:t,navigationHost:l,sidebarMode:u,onHide:d,fill:f}){let{locale:v}=x(),[C,w]=(0,z.useState)(`files`),[T,E]=(0,z.useState)(!1),[D,te]=(0,z.useState)(``),[k,A]=(0,z.useState)(!1),[j,M]=(0,z.useState)(),[N,P]=(0,z.useState)(``),F=Oe(e),{tabs:I,active:L}=F,[ne,re]=(0,z.useState)(``),[ae,oe]=(0,z.useState)(!1),[V,H]=(0,z.useState)(!1),U=(0,z.useRef)(null),[fe,pe]=(0,z.useState)(0);(0,z.useEffect)(()=>{let t=t=>{t.detail?.sessionRef===e&&pe(e=>e+1)};return window.addEventListener(`piagent-workspace-saved`,t),()=>window.removeEventListener(`piagent-workspace-saved`,t)},[e]),(0,z.useEffect)(()=>()=>U.current?.abort(),[]);let W=async(t,n=1)=>{if(U.current?.abort(),H(!1),I.find(e=>e.file.path===t)){F.select(t,n);return}U.current?.abort();let r=new AbortController;U.current=r,H(!0),oe(!1);try{let i=await R(e,t,r.signal);if(r.signal.aborted)return;if(i.protected){oe(!0);return}F.load(i,n)}catch{r.signal.aborted||oe(!0)}finally{r.signal.aborted||H(!1)}};(0,z.useEffect)(()=>{t&&W(t.path,t.line??1)},[t]),(0,z.useEffect)(()=>{u&&u!==`sessions`&&w(u)},[u]);let G=I.find(e=>e.file.path===L),K=G?.file,q=_e(e,I,L),J=de(e,K?.path,K?.digest??null,!!G&&!Q(G),q.diff),Y=ue(e,K?.path,G?.draft??``,q.hunks),[me,he]=(0,z.useState)(new Set),ge=!!K&&!K.binary&&!K.oversized&&se(K.path)===`image`&&!me.has(K.path),X=I.find(e=>e.file.path===F.conflict?.path),Z=(0,B.jsxs)(_,{component:`nav`,"aria-label":S(v,`Tệp dự án`,`Project files`),sx:{width:l?`100%`:{xs:136,sm:200},flexShrink:0,overflow:`auto`,borderRight:1,borderColor:`divider`},children:[!l&&(0,B.jsxs)(h,{value:C,onChange:(e,t)=>w(t),"aria-label":S(v,`Khám phá project`,`Explore project`),children:[(0,B.jsx)(o,{value:`files`,label:S(v,`Tệp`,`Files`)}),(0,B.jsx)(o,{value:`search`,label:S(v,`Tìm kiếm`,`Search`)})]}),C===`search`?(0,B.jsx)(Ae,{sessionRef:e,onOpen:(e,t)=>void W(e,t)}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(m,{disabled:!F.authority?.writable,onClick:()=>{te(ne?`${ne}/`:``),E(!0)},children:S(v,`Tệp mới`,`New file`)}),(0,B.jsx)(Fe,{sessionRef:e,refresh:fe,active:L,onOpen:e=>{re(e.split(`/`).slice(0,-1).join(`/`)),W(e)},onFolder:re})]})]});return(0,B.jsxs)(B.Fragment,{children:[J.dialog,Y.dialog,(0,B.jsxs)(p,{direction:`row`,sx:{height:f?`100%`:`calc(100vh - 150px)`,minHeight:f?160:320},children:[l?(0,ke.createPortal)(Z,l):Z,(0,B.jsxs)(_,{sx:{minWidth:0,flex:1,display:`flex`,flexDirection:`column`},children:[ae&&(0,B.jsx)(a,{severity:`warning`,children:S(v,`Chưa đọc được tệp hoặc thư mục này.`,`This file or folder could not be read.`)}),Y.bar,F.message&&(0,B.jsx)(a,{severity:`warning`,children:F.message}),F.authority?.agentRunning&&(0,B.jsx)(a,{severity:`info`,children:S(v,`Agent đang chạy và có thể sửa tệp này.`,`The agent is running and may change this file.`)}),(0,B.jsxs)(p,{direction:`row`,sx:{alignItems:`center`,borderBottom:1,borderColor:`divider`,minHeight:36},children:[(0,B.jsx)(h,{value:L??!1,onChange:(e,t)=>F.select(t),variant:`scrollable`,scrollButtons:`auto`,"aria-label":S(v,`Các tệp đang mở`,`Open files`),sx:{flex:1,minWidth:0,minHeight:36},children:I.map(e=>(0,B.jsx)(o,{value:e.file.path,sx:{minHeight:36,py:0},"aria-label":`${e.file.path}${Q(e)?` ●`:``}${q.counts.get(e.file.path)?` (${q.counts.get(e.file.path)})`:``}`,label:le(`${e.file.path}${Q(e)?` ●`:``}${q.counts.get(e.file.path)?` (${q.counts.get(e.file.path)})`:``}`,S(v,`Đóng ${e.file.path}`,`Close ${e.file.path}`),()=>F.close(e.file.path))},e.file.path))}),d&&(0,B.jsx)(c,{size:`small`,"aria-label":S(v,`Ẩn khung tệp`,`Hide files panel`),title:S(v,`Ẩn khung tệp (tệp đang mở vẫn giữ)`,`Hide files panel (open files are kept)`),onClick:d,children:(0,B.jsx)(ee,{fontSize:`small`})})]}),V&&(0,B.jsx)(b,{size:20}),K&&(0,B.jsxs)(p,{direction:`row`,sx:{flexShrink:0,overflowX:`auto`,"& .MuiButton-root":{whiteSpace:`nowrap`,flexShrink:0}},children:[!K.binary&&!K.oversized&&se(K.path)===`image`&&(0,B.jsx)(m,{size:`small`,onClick:()=>he(e=>{let t=new Set(e);return t.has(K.path)?t.delete(K.path):t.add(K.path),t}),children:ge?S(v,`Xem mã`,`View code`):S(v,`Xem hình`,`View picture`)}),(0,B.jsx)(m,{size:`small`,onClick:()=>void ie(e,K.path),children:S(v,`Tải về`,`Download`)}),J.hasPending&&(0,B.jsx)(m,{onClick:J.checkPending,children:S(v,`Kiểm tra hoàn tác`,`Check revert`)}),(0,B.jsx)(m,{size:`small`,disabled:!F.authority?.writable||K.readOnly||!G||!Q(G)&&!G.pending||F.saving,onClick:()=>void F.save(K.path),children:S(v,`Lưu`,`Save`)}),(0,B.jsx)(m,{size:`small`,onClick:()=>F.close(K.path),children:S(v,`Đóng tệp`,`Close file`)}),(0,B.jsx)(m,{size:`small`,disabled:!F.authority?.writable||K.readOnly||!K.digest||F.saving,onClick:()=>{P(K.path),M(K.path)},children:S(v,`Đổi tên`,`Rename`)}),(0,B.jsx)(m,{size:`small`,color:`error`,disabled:!F.authority?.writable||K.readOnly||!K.digest||F.saving,onClick:()=>{window.confirm(S(v,`Xóa ${K.path}? Có thể khôi phục bằng Git nếu tệp đã commit.`,`Delete ${K.path}? Git can restore it if it was committed.`))&&F.move(K.path)},children:S(v,`Xóa`,`Delete`)}),(0,B.jsx)(m,{size:`small`,onClick:()=>{(!G||!Q(G)||window.confirm(S(v,`Bỏ thay đổi chưa lưu và tải lại?`,`Discard unsaved changes and reload?`)))&&F.reload(K.path)},children:S(v,`Tải lại`,`Reload`)})]}),K?.binary||K?.oversized||ge?(0,B.jsx)(ce,{sessionRef:e,path:K.path}):K?.content!==null&&K?.content!==void 0?(0,B.jsx)(_,{sx:{flex:1,minHeight:0},children:(0,B.jsx)(z.Suspense,{fallback:(0,B.jsx)(b,{size:20}),children:(0,B.jsx)(Ie,{onComment:Y.open,hunks:q.hunks,onKeep:q.keep,onRevert:F.authority?.writable?e=>void J.request(e):void 0,content:G?.draft??K.content,path:K.path,line:G?.line??1,readOnly:!F.authority?.writable||K.readOnly,onChange:e=>F.change(K.path,e),onSave:()=>void F.save(K.path)})})}):(0,B.jsx)(n,{sx:{p:2},children:S(v,`Chọn một tệp để mở.`,`Select a file to open.`)})]})]}),(0,B.jsxs)(r,{open:T,onClose:()=>E(!1),fullWidth:!0,children:[(0,B.jsx)(g,{children:S(v,`Tạo tệp mới`,`Create a new file`)}),(0,B.jsx)(i,{children:(0,B.jsx)(y,{autoFocus:!0,fullWidth:!0,label:S(v,`Đường dẫn trong project`,`Path in project`),value:D,onChange:e=>te(e.target.value)})}),(0,B.jsxs)(s,{children:[(0,B.jsx)(m,{onClick:()=>E(!1),children:S(v,`Hủy`,`Cancel`)}),(0,B.jsx)(m,{disabled:!O(D)||!F.authority?.writable,onClick:()=>{let e=O(D);!e||!F.authority||(I.some(t=>t.file.path===e.path)?F.select(e.path):F.load({schemaVersion:1,version:`piagent-webui-workspace-file-v1`,generatedAt:new Date().toISOString(),identity:F.authority.identity,path:e.path,language:`text`,protected:!1,readOnly:!1,binary:!1,oversized:!1,content:``,digest:null,revision:null},1,!0),E(!1))},children:S(v,`Tạo`,`Create`)})]})]}),(0,B.jsxs)(r,{open:!!j,onClose:()=>M(void 0),fullWidth:!0,children:[(0,B.jsx)(g,{children:S(v,`Đổi tên tệp`,`Rename file`)}),(0,B.jsx)(i,{children:(0,B.jsx)(y,{autoFocus:!0,fullWidth:!0,label:S(v,`Đường dẫn mới trong project`,`New path in project`),value:N,onChange:e=>P(e.target.value)})}),(0,B.jsxs)(s,{children:[(0,B.jsx)(m,{onClick:()=>M(void 0),children:S(v,`Hủy`,`Cancel`)}),(0,B.jsx)(m,{disabled:!O(N)||O(N)?.path===j||F.saving,onClick:()=>{let e=O(N);!e||!j||F.move(j,e.path).then(e=>{e&&M(void 0)})},children:S(v,`Đổi tên`,`Rename`)})]})]}),(0,B.jsxs)(r,{open:!!F.conflict,onClose:()=>{F.setConflict(void 0),A(!1)},fullWidth:!0,maxWidth:k?`lg`:`sm`,children:[(0,B.jsx)(g,{children:S(v,`Tệp đã thay đổi trên đĩa`,`The file changed on disk`)}),(0,B.jsxs)(i,{children:[(0,B.jsx)(n,{children:F.conflict?.path}),(0,B.jsx)(n,{children:S(v,`Bản sửa của bạn vẫn được giữ. Chọn cách xử lý xung đột.`,`Your draft is preserved. Choose how to resolve the conflict.`)}),k&&F.conflict&&X&&(0,B.jsxs)(p,{direction:`row`,spacing:1,children:[(0,B.jsxs)(_,{sx:{width:`50%`,height:360},children:[(0,B.jsx)(n,{children:S(v,`Trên đĩa`,`On disk`)}),(0,B.jsx)(z.Suspense,{fallback:(0,B.jsx)(b,{size:20}),children:(0,B.jsx)(Ie,{path:F.conflict.path,content:F.conflict.content??``})})]}),(0,B.jsxs)(_,{sx:{width:`50%`,height:360},children:[(0,B.jsx)(n,{children:S(v,`Bản sửa của bạn`,`Your draft`)}),(0,B.jsx)(z.Suspense,{fallback:(0,B.jsx)(b,{size:20}),children:(0,B.jsx)(Ie,{path:X.file.path,content:X.draft})})]})]})]}),(0,B.jsxs)(s,{children:[(0,B.jsx)(m,{onClick:()=>{F.setConflict(void 0),A(!1)},children:S(v,`Để sau`,`Later`)}),(0,B.jsx)(m,{onClick:()=>{F.conflict&&(F.load(F.conflict),F.setConflict(void 0),A(!1))},children:S(v,`Tải lại`,`Reload`)}),(0,B.jsx)(m,{onClick:()=>A(!0),children:S(v,`Xem khác biệt`,`Compare`)}),(0,B.jsx)(m,{disabled:F.saving||!F.conflict?.digest||F.conflict.protected||F.conflict.readOnly,onClick:()=>{F.conflict&&F.save(F.conflict.path,F.conflict)},children:S(v,`Ghi đè`,`Overwrite`)})]})]})]})}export{Le as default};
5
+ `)]},e.hunkRef))]}),(0,B.jsxs)(s,{children:[(0,B.jsx)(m,{disabled:y,onClick:()=>C(!1),children:S(u,`Đóng`,`Close`)}),(0,B.jsx)(m,{color:`error`,disabled:y||!c||!k&&(!w||!!P),onClick:()=>void M(),children:k?S(u,`Kiểm tra lại`,`Check again`):S(u,`Xác nhận hoàn tác`,`Confirm revert`)})]})]}),hasPending:k,checkPending:()=>{A(V.has(d)),C(!0)}}}async function H(e,t,n){let r=await fetch(`/api/v1/sessions/${encodeURIComponent(e)}/source-review${t?`/${encodeURIComponent(t)}`:``}`,{credentials:`same-origin`,headers:{Accept:`application/json`},signal:n});if(r.status===401&&E(),!r.ok)throw Error(`source-review-unavailable`);return r.json()}var U=(e,t)=>H(e,void 0,t),fe=(e,t,n)=>H(e,t,n);function pe(e,t,n,r,i){if(!e||!r||!n||e.file.path!==t||e.file.currentDigest!==`sha256:${n}`||e.availability.state!==`current`||e.truncation.truncated||e.redaction.applied)return[];let a=new Set(e.agentHunkRefs??[]);return e.hunks.filter(e=>a.has(e.hunkRef)&&!i.has(`${t}:${n}:${e.hunkRef}`))}var W=new Set,G=new Map,K=new Set,q=`piagent.kept-hunks.`,J=`piagent.kept-hunks`;function Y(e){try{let t=JSON.parse(localStorage.getItem(q+e)??`[]`);return Array.isArray(t)?new Set(t.filter(e=>typeof e==`string`).slice(-4096)):W}catch{return W}}function me(e,t){try{let n=[...JSON.parse(localStorage.getItem(J)??`[]`).filter(t=>t!==e),e];for(let e of n.splice(0,Math.max(0,n.length-64)))localStorage.removeItem(q+e);localStorage.setItem(q+e,JSON.stringify([...t])),localStorage.setItem(J,JSON.stringify(n))}catch{}}var he=e=>(G.has(e)||G.set(e,Y(e)),G.get(e)??W);function ge(e,t,n,r){let i=new Set([...he(e),`${t}:${n}:${r}`].slice(-4096));for(G.delete(e),G.set(e,i);G.size>64;)G.delete(G.keys().next().value);me(e,i);for(let e of K)e()}function X(e){return(0,z.useSyncExternalStore)(e=>(K.add(e),()=>{K.delete(e)}),()=>he(e))}function _e(e,t,n){let[r,i]=(0,z.useState)(),a=X(e),o=JSON.stringify(t.map(e=>e.file.path).sort());(0,z.useEffect)(()=>{let t=JSON.parse(o);if(!t.length){i(void 0);return}let n=new AbortController,r=!1,a=!1,s=async()=>{if(!n.signal.aborted){if(r){a=!0;return}r=!0;try{let r=await U(e,n.signal),a=new Map;for(let i of t){if(n.signal.aborted)return;let t=r.files.find(e=>e.path===i&&e.pathDisplay===`exact-safe`);if(t)try{a.set(i,await fe(e,t.fileRef,n.signal))}catch{}}n.signal.aborted||i({session:e,diffs:a})}catch{n.signal.aborted||i(void 0)}finally{r=!1,a&&!n.signal.aborted&&(a=!1,s())}}};s();let c=window.setInterval(()=>void s(),3e3),l=t=>{t.detail?.sessionRef===e&&s()};return window.addEventListener(`piagent-workspace-saved`,l),window.addEventListener(`piagent-workspace-changed`,l),()=>{n.abort(),clearInterval(c),window.removeEventListener(`piagent-workspace-saved`,l),window.removeEventListener(`piagent-workspace-changed`,l)}},[e,o]);let s=r?.session===e?r.diffs:void 0,c=e=>pe(s?.get(e.file.path),e.file.path,e.file.digest,!e.fresh&&!e.pending&&e.draft===(e.file.content??``),a),l=t.find(e=>e.file.path===n),u=l?c(l):[];return{diff:n?s?.get(n):void 0,hunks:u,counts:new Map(t.map(e=>[e.file.path,c(e).length])),keep:t=>{l?.file.digest&&u.some(e=>e.hunkRef===t)&&ge(e,l.file.path,l.file.digest,t)}}}var Z=new Map,ve=new Set,ye={tabs:[]},Q=e=>e.fresh||e.draft!==(e.file.content??``);window.addEventListener(`beforeunload`,e=>{[...Z.values()].some(e=>e.tabs.some(Q))&&(e.preventDefault(),e.returnValue=``)});var be=e=>Z.get(e)??ye;function xe(e){let t=(0,z.useSyncExternalStore)(e=>(ve.add(e),()=>{ve.delete(e)}),()=>Z.get(e)??ye),n=t=>{Z.set(e,t(Z.get(e)??ye));for(let e of ve)e()};return{...t,update:n}}function Se(e,t,n){return e.file!==t||e.file.path!==n.path||e.pending||e.fresh||e.file.digest===n.digest&&e.file.protected===n.protected&&e.file.readOnly===n.readOnly?{tab:e}:e.draft===(e.file.content??``)?{tab:{...e,file:n,draft:n.content??``}}:{tab:e,conflict:n}}function Ce(e,t,n){let{update:r}=xe(e),i=(0,z.useRef)({update:r,conflict:n});i.current={update:r,conflict:n},(0,z.useEffect)(()=>{let n=new AbortController,r=new Map,a=!1,o=!1,s,c=async()=>{if(!(n.signal.aborted||t.current)){if(a){o=!0;return}a=!0;try{for(let a of be(e).tabs)if(!(a.fresh||a.pending||t.current))try{let o=await R(e,a.file.path,n.signal);if(n.signal.aborted||t.current)return;let s;if(i.current.update(e=>({...e,tabs:e.tabs.map(t=>{if(t.file.path!==a.file.path)return t;let n=Se(t,a.file,o);return n.conflict&&e.active===t.file.path&&(s=n.conflict),n.tab})})),s){let e=`${s.digest}:${s.protected}:${s.readOnly}`;r.get(s.path)!==e&&(r.set(s.path,e),i.current.conflict(s))}}catch{}}finally{a=!1,o&&!n.signal.aborted&&(o=!1,l())}}},l=()=>{s||=setTimeout(()=>{s=void 0,c()},100)},u=t=>{t.detail?.sessionRef===e&&l()};window.addEventListener(`piagent-workspace-changed`,u),window.addEventListener(`piagent-workspace-saved`,u);let d=setInterval(l,5e3);return l(),()=>{n.abort(),clearTimeout(s),clearInterval(d),window.removeEventListener(`piagent-workspace-changed`,u),window.removeEventListener(`piagent-workspace-saved`,u)}},[e,t])}var we=e=>`/api/v1/sessions/${encodeURIComponent(e)}/workspace/write`;function $(e){return Array.isArray(e)?`[${e.map($).join(`,`)}]`:e&&typeof e==`object`?`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${$(t)}`).join(`,`)}}`:JSON.stringify(e)}async function Te(e,t){let n=await fetch(we(e),{credentials:`same-origin`,signal:t,headers:{Accept:`application/json`}});if(n.status===401&&E(),!n.ok)throw Error(`workspace-write-unavailable`);return await n.json()}async function Ee(e,t){let n=Date.now(),r=`workspace.write`,i=e.identity,a=e.revisions,o=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode($({action:r,identity:i,expectedRevisions:a,payload:t})));return{schemaVersion:1,version:`piagent-webui-workspace-write-v1`,messageType:`command`,action:r,identity:i,expectedRevisions:a,payload:t,commandId:crypto.randomUUID(),idempotencyKey:crypto.randomUUID(),requestedAt:new Date(n).toISOString(),expiresAt:new Date(n+6e4).toISOString(),actionDigest:`sha256:${[...new Uint8Array(o)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`}}async function De(e,t){let n=T();if(!n)throw Error(`workspace-write-unavailable`);let r=await w(we(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&&E(),!r.ok)throw Error(`workspace-write-unavailable`);let i=await r.json(),a=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t.idempotencyKey)),o=`sha256:${[...new Uint8Array(a)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`;if(i.schemaVersion!==1||i.version!==t.version||i.messageType!==`receipt`||i.path!==t.payload.path||i.commandId!==t.commandId||i.action!==t.action||i.actionDigest!==t.actionDigest||i.idempotencyKeyDigest!==o||$(i.identity)!==$(t.identity)||![`settled`,`rejected`,`uncertain`].includes(i.phase)||i.phase===`settled`&&(i.resultCode!==`saved`||!/^[a-f0-9]{64}$/.test(i.digest??``)))throw Error(`workspace-write-receipt-invalid`);return i}function Oe(e){let{locale:t}=x(),n=xe(e),[r,i]=(0,z.useState)(),[a,o]=(0,z.useState)(!1),s=(0,z.useRef)(!1),[c,l]=(0,z.useState)(),[u,d]=(0,z.useState)();Ce(e,s,d),(0,z.useEffect)(()=>{let t=new AbortController,n=!1,r=()=>{n||(n=!0,Te(e,t.signal).then(i).catch(()=>{t.signal.aborted||i(void 0)}).finally(()=>{n=!1}))};r();let a=window.setInterval(r,5e3);return()=>{t.abort(),clearInterval(a)}},[e]);let f=(e,t=1,r=!1)=>n.update(n=>({active:e.path,tabs:[...n.tabs.filter(t=>t.file.path!==e.path),{file:e,line:t,fresh:r,draft:e.content??``}]})),p=(e,t)=>n.update(n=>({...n,active:e,tabs:n.tabs.map(n=>n.file.path===e&&t!==void 0?{...n,line:t}:n)})),m=(e,t)=>n.update(n=>({...n,tabs:n.tabs.map(n=>n.file.path===e?{...n,draft:t}:n)})),h=r=>{let i=be(e).tabs.find(e=>e.file.path===r);i&&(Q(i)||i.pending)&&!window.confirm(S(t,`Bỏ thay đổi chưa lưu và đóng tệp?`,`Discard unsaved changes and close this file?`))||n.update(e=>({tabs:e.tabs.filter(e=>e.file.path!==r),active:e.active===r?e.tabs.find(e=>e.file.path!==r)?.file.path:e.active}))},g=async n=>{try{f(await R(e,n)),d(void 0),l(void 0)}catch{l(S(t,`Chưa tải lại được tệp. Bản sửa của bạn vẫn được giữ.`,`Could not reload the file. Your draft is preserved.`))}},_=async(r,a)=>{let c=be(e).tabs.find(e=>e.file.path===r);if(!(!c||s.current||!Q(c)&&!c.pending||c.file.protected||c.file.readOnly)&&!(a&&!window.confirm(S(t,`Ghi đè phiên bản trên đĩa bằng bản sửa của bạn?`,`Replace the version on disk with your draft?`)))){s.current=!0,o(!0),l(void 0);try{let o=await Te(e);if(i(o),!o.writable)throw Error(`read-only`);let s=a?.digest??(c.fresh?`absent`:c.file.digest);if(!s)throw Error(`unavailable`);let u=c.pending??await Ee(o,{path:r,content:c.draft,expectedDigest:s});n.update(e=>({...e,tabs:e.tabs.map(e=>e.file.path===r?{...e,pending:u}:e)}));let f=await De(e,u);if(f.phase===`uncertain`){l(S(t,`Chưa xác định được kết quả lưu. Tải lại để kiểm tra trước khi lưu tiếp.`,`The save result is uncertain. Reload to check before saving again.`));return}n.update(e=>({...e,tabs:e.tabs.map(e=>e.file.path===r?{...e,pending:void 0}:e)})),f.phase===`settled`&&f.resultCode===`saved`?(n.update(e=>({...e,tabs:e.tabs.map(e=>e.file.path===r?{...e,fresh:!1,file:{...e.file,content:u.payload.content,digest:f.digest,revision:f.observedRevisionsAfter.workspaceRevision}}:e)})),d(void 0),window.dispatchEvent(new CustomEvent(`piagent-workspace-saved`,{detail:{sessionRef:e,path:r}}))):f.resultCode===`stale-content`||f.resultCode===`stale-revision`?d(await R(e,r)):l(S(t,`Chưa lưu được tệp. Kiểm tra quyền ghi và thử lại.`,`Could not save the file. Check write access and try again.`))}catch{l(S(t,`Chưa lưu được tệp. Bản sửa vẫn được giữ; thử lưu lại hoặc tải lại để kiểm tra.`,`Could not confirm the save. Your draft is preserved; retry the save or reload to check.`))}finally{s.current=!1,o(!1)}}},v=async(r,a)=>{let c=be(e).tabs.find(e=>e.file.path===r);if(s.current||c&&(Q(c)||c.pending))return l(S(t,`Lưu hoặc bỏ thay đổi trước khi đổi tên hay xóa tệp.`,`Save or discard your changes before renaming or deleting the file.`)),!1;s.current=!0,o(!0),l(void 0);try{let o=await Te(e);i(o);let s=c?.file.digest??(await R(e,r)).digest;if(!o.writable||!s)throw Error(`unavailable`);let u=await De(e,await Ee(o,a?{path:r,content:``,expectedDigest:s,operation:`rename`,destination:a}:{path:r,content:``,expectedDigest:s,operation:`delete`}));return u.phase===`settled`&&u.resultCode===`saved`?(n.update(e=>({tabs:e.tabs.filter(e=>e.file.path!==r),active:e.active===r?void 0:e.active})),a&&f(await R(e,a)),window.dispatchEvent(new CustomEvent(`piagent-workspace-saved`,{detail:{sessionRef:e,path:r}})),!0):(l(u.phase===`uncertain`?S(t,`Chưa xác định được kết quả. Tải lại danh sách tệp để kiểm tra.`,`The result is uncertain. Reload the file list to check.`):u.resultCode===`stale-content`?S(t,`Tệp đã thay đổi trên đĩa hoặc tên mới đã có. Tải lại rồi thử lại.`,`The file changed on disk or the new name exists. Reload and try again.`):S(t,`Không thực hiện được. Kiểm tra quyền ghi và tên tệp.`,`This could not be done. Check write access and the file name.`)),!1)}catch{return l(S(t,`Chưa xác nhận được thao tác. Tải lại danh sách tệp để kiểm tra.`,`Could not confirm the action. Reload the file list to check.`)),!1}finally{s.current=!1,o(!1)}};return{...n,authority:r,saving:a,message:c,conflict:u,setConflict:d,load:f,select:p,change:m,close:h,reload:g,save:_,move:v}}var ke=e(l(),1);function Ae({sessionRef:e,onOpen:t}){let{locale:r}=x(),[i,o]=(0,z.useState)(``),[s,c]=(0,z.useState)(),[l,u]=(0,z.useState)(!1),[d,f]=(0,z.useState)(!1);return(0,z.useEffect)(()=>{let t=new AbortController;if(c(void 0),f(!1),u(!1),!i.trim())return()=>t.abort();u(!0);let n=setTimeout(()=>{oe(e,i,t.signal).then(e=>{t.signal.aborted||c(e)}).catch(()=>{t.signal.aborted||f(!0)}).finally(()=>{t.signal.aborted||u(!1)})},250);return()=>{clearTimeout(n),t.abort()}},[i,e]),(0,B.jsxs)(p,{spacing:1,sx:{p:1},children:[(0,B.jsx)(y,{size:`small`,label:S(r,`Tìm nội dung`,`Search contents`),value:i,onChange:e=>o(e.target.value),slotProps:{htmlInput:{maxLength:512}}}),l&&(0,B.jsx)(b,{size:18}),(d||s?.available===!1)&&(0,B.jsx)(a,{severity:`warning`,children:S(r,`Chưa tìm được nội dung trong project này.`,`Content search is unavailable for this project.`)}),s?.available&&s.backend===`fts`&&(0,B.jsx)(n,{variant:`caption`,children:S(r,`Tìm trong các tệp đã lập chỉ mục.`,`Searching indexed files.`)}),s?.matches.map(e=>(0,B.jsxs)(m,{onClick:()=>t(e.path,e.line),sx:{textTransform:`none`,display:`block`,textAlign:`left`,overflowWrap:`anywhere`},children:[(0,B.jsxs)(n,{variant:`caption`,component:`span`,children:[e.path,`:`,e.line,`:`,e.column]}),(0,B.jsx)(n,{variant:`body2`,component:`span`,sx:{display:`block`},children:e.preview})]},`${e.path}:${e.line}:${e.column}`)),s?.truncated&&(0,B.jsx)(n,{variant:`caption`,children:S(r,`Đã giới hạn kết quả. Hãy tìm cụ thể hơn.`,`Results were limited. Refine your search.`)}),s?.available&&!s.matches.length&&!s.truncated&&(0,B.jsx)(n,{variant:`caption`,children:S(r,`Không tìm thấy.`,`No matches.`)})]})}var je=v((0,B.jsx)(`path`,{d:`M10 6 8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z`}),`ChevronRight`),Me=v((0,B.jsx)(`path`,{d:`M16.59 8.59 12 13.17 7.41 8.59 6 10l6 6 6-6z`}),`ExpandMore`),Ne=v((0,B.jsx)(`path`,{d:`M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8zM6 20V4h7v5h5v11z`}),`InsertDriveFileOutlined`),Pe=e=>e.split(`/`).slice(0,-1).map((e,t,n)=>n.slice(0,t+1).join(`/`));function Fe({sessionRef:e,refresh:t,active:r,onOpen:i,onFolder:a}){let{locale:o}=x(),[s,c]=(0,z.useState)(()=>new Set([``])),[l,f]=(0,z.useState)(()=>new Map),[p,h]=(0,z.useState)(),g=(t,n)=>{f(e=>new Map(e).set(t,e.get(t)??`loading`)),ae(e,t,n).then(e=>{n?.aborted||f(n=>new Map(n).set(t,e))}).catch(()=>{n?.aborted||f(e=>new Map(e).set(t,`error`))})};(0,z.useEffect)(()=>{f(new Map),c(new Set([``]))},[e]),(0,z.useEffect)(()=>{let e=new AbortController;for(let t of s)g(t,e.signal);return()=>e.abort()},[e,t]),(0,z.useEffect)(()=>{if(!r)return;let e=Pe(r).filter(e=>!s.has(e));if(e.length){c(t=>new Set([...t,...e]));for(let t of e)l.has(t)||g(t)}},[r]);let v=e=>{if(h(e),a(e),s.has(e)){c(t=>{let n=new Set(t);return n.delete(e),n});return}c(t=>new Set(t).add(e)),(!l.has(e)||l.get(e)===`error`)&&g(e)},y=(e,t)=>{let a=l.get(e);return!a||a===`loading`?(0,B.jsx)(b,{size:14,sx:{ml:1.5+t*1.5,my:.5}}):a===`error`?(0,B.jsx)(n,{variant:`caption`,color:`warning.main`,sx:{pl:1.5+t*1.5},children:S(o,`Chưa đọc được thư mục này.`,`This folder could not be read.`)}):(0,B.jsxs)(B.Fragment,{children:[a.entries.map(e=>{let n=e.kind===`directory`,a=n&&s.has(e.path),c=n?p===e.path:r===e.path,l=n?(0,B.jsxs)(B.Fragment,{children:[a?(0,B.jsx)(Me,{sx:{fontSize:16}}):(0,B.jsx)(je,{sx:{fontSize:16}}),a?(0,B.jsx)(d,{sx:{fontSize:16}}):(0,B.jsx)(u,{sx:{fontSize:16}})]}):(0,B.jsx)(Ne,{sx:{fontSize:16,ml:`16px`}});return(0,B.jsxs)(_,{children:[(0,B.jsxs)(m,{fullWidth:!0,size:`small`,disabled:e.protected||e.kind===`symlink`||e.kind===`other`,"aria-label":e.protected?`${e.name} (${S(o,`được bảo vệ`,`protected`)})`:e.name,"aria-expanded":n?a:void 0,"aria-current":!n&&r===e.path?`true`:void 0,onClick:()=>n?v(e.path):(h(void 0),i(e.path)),sx:{justifyContent:`flex-start`,textTransform:`none`,gap:.5,minHeight:24,py:0,pl:.5+t*1.5,pr:1,color:`text.primary`,fontWeight:400,whiteSpace:`nowrap`,bgcolor:c?`action.selected`:void 0},children:[l,(0,B.jsxs)(_,{component:`span`,sx:{overflow:`hidden`,textOverflow:`ellipsis`},children:[e.name,e.protected?` 🔒`:``]})]}),a&&y(e.path,t+1)]},e.path)}),a.truncated&&(0,B.jsx)(n,{variant:`caption`,sx:{pl:1.5+t*1.5},children:S(o,`Danh sách đã được giới hạn.`,`Listing limit reached.`)})]})};return(0,B.jsx)(_,{role:`group`,"aria-label":S(o,`Cây thư mục`,`Folder tree`),sx:{py:.5},children:y(``,0)})}var Ie=(0,z.lazy)(()=>C(()=>import(`./WorkspaceCodeEditor-BHGFFBc2.js`),__vite__mapDeps([0,1,2,3,4,5,6])));function Le({sessionRef:e,target:t,navigationHost:l,sidebarMode:u,onHide:d,fill:f}){let{locale:v}=x(),[C,w]=(0,z.useState)(`files`),[T,E]=(0,z.useState)(!1),[D,te]=(0,z.useState)(``),[k,A]=(0,z.useState)(!1),[j,M]=(0,z.useState)(),[N,P]=(0,z.useState)(``),F=Oe(e),{tabs:I,active:L}=F,[ne,re]=(0,z.useState)(``),[ae,oe]=(0,z.useState)(!1),[V,H]=(0,z.useState)(!1),U=(0,z.useRef)(null),[fe,pe]=(0,z.useState)(0);(0,z.useEffect)(()=>{let t=t=>{t.detail?.sessionRef===e&&pe(e=>e+1)};return window.addEventListener(`piagent-workspace-saved`,t),()=>window.removeEventListener(`piagent-workspace-saved`,t)},[e]),(0,z.useEffect)(()=>()=>U.current?.abort(),[]);let W=async(t,n=1)=>{if(U.current?.abort(),H(!1),I.find(e=>e.file.path===t)){F.select(t,n);return}U.current?.abort();let r=new AbortController;U.current=r,H(!0),oe(!1);try{let i=await R(e,t,r.signal);if(r.signal.aborted)return;if(i.protected){oe(!0);return}F.load(i,n)}catch{r.signal.aborted||oe(!0)}finally{r.signal.aborted||H(!1)}};(0,z.useEffect)(()=>{t&&W(t.path,t.line??1)},[t]),(0,z.useEffect)(()=>{u&&u!==`sessions`&&w(u)},[u]);let G=I.find(e=>e.file.path===L),K=G?.file,q=_e(e,I,L),J=de(e,K?.path,K?.digest??null,!!G&&!Q(G),q.diff),Y=ue(e,K?.path,G?.draft??``,q.hunks),[me,he]=(0,z.useState)(new Set),ge=!!K&&!K.binary&&!K.oversized&&se(K.path)===`image`&&!me.has(K.path),X=I.find(e=>e.file.path===F.conflict?.path),Z=(0,B.jsxs)(_,{component:`nav`,"aria-label":S(v,`Tệp dự án`,`Project files`),sx:{width:l?`100%`:{xs:136,sm:200},flexShrink:0,overflow:`auto`,borderRight:1,borderColor:`divider`},children:[!l&&(0,B.jsxs)(h,{value:C,onChange:(e,t)=>w(t),"aria-label":S(v,`Khám phá project`,`Explore project`),children:[(0,B.jsx)(o,{value:`files`,label:S(v,`Tệp`,`Files`)}),(0,B.jsx)(o,{value:`search`,label:S(v,`Tìm kiếm`,`Search`)})]}),C===`search`?(0,B.jsx)(Ae,{sessionRef:e,onOpen:(e,t)=>void W(e,t)}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(m,{disabled:!F.authority?.writable,onClick:()=>{te(ne?`${ne}/`:``),E(!0)},children:S(v,`Tệp mới`,`New file`)}),(0,B.jsx)(Fe,{sessionRef:e,refresh:fe,active:L,onOpen:e=>{re(e.split(`/`).slice(0,-1).join(`/`)),W(e)},onFolder:re})]})]});return(0,B.jsxs)(B.Fragment,{children:[J.dialog,Y.dialog,(0,B.jsxs)(p,{direction:`row`,sx:{height:f?`100%`:`calc(100vh - 150px)`,minHeight:f?160:320},children:[l?(0,ke.createPortal)(Z,l):Z,(0,B.jsxs)(_,{sx:{minWidth:0,flex:1,display:`flex`,flexDirection:`column`},children:[ae&&(0,B.jsx)(a,{severity:`warning`,children:S(v,`Chưa đọc được tệp hoặc thư mục này.`,`This file or folder could not be read.`)}),Y.bar,F.message&&(0,B.jsx)(a,{severity:`warning`,children:F.message}),F.authority?.agentRunning&&(0,B.jsx)(a,{severity:`info`,children:S(v,`Agent đang chạy và có thể sửa tệp này.`,`The agent is running and may change this file.`)}),(0,B.jsxs)(p,{direction:`row`,sx:{alignItems:`center`,borderBottom:1,borderColor:`divider`,minHeight:36},children:[(0,B.jsx)(h,{value:L??!1,onChange:(e,t)=>F.select(t),variant:`scrollable`,scrollButtons:`auto`,"aria-label":S(v,`Các tệp đang mở`,`Open files`),sx:{flex:1,minWidth:0,minHeight:36},children:I.map(e=>(0,B.jsx)(o,{value:e.file.path,sx:{minHeight:36,py:0},"aria-label":`${e.file.path}${Q(e)?` ●`:``}${q.counts.get(e.file.path)?` (${q.counts.get(e.file.path)})`:``}`,label:le(`${e.file.path}${Q(e)?` ●`:``}${q.counts.get(e.file.path)?` (${q.counts.get(e.file.path)})`:``}`,S(v,`Đóng ${e.file.path}`,`Close ${e.file.path}`),()=>F.close(e.file.path))},e.file.path))}),d&&(0,B.jsx)(c,{size:`small`,"aria-label":S(v,`Ẩn khung tệp`,`Hide files panel`),title:S(v,`Ẩn khung tệp (tệp đang mở vẫn giữ)`,`Hide files panel (open files are kept)`),onClick:d,children:(0,B.jsx)(ee,{fontSize:`small`})})]}),V&&(0,B.jsx)(b,{size:20}),K&&(0,B.jsxs)(p,{direction:`row`,sx:{flexShrink:0,overflowX:`auto`,"& .MuiButton-root":{whiteSpace:`nowrap`,flexShrink:0}},children:[!K.binary&&!K.oversized&&se(K.path)===`image`&&(0,B.jsx)(m,{size:`small`,onClick:()=>he(e=>{let t=new Set(e);return t.has(K.path)?t.delete(K.path):t.add(K.path),t}),children:ge?S(v,`Xem mã`,`View code`):S(v,`Xem hình`,`View picture`)}),(0,B.jsx)(m,{size:`small`,onClick:()=>void ie(e,K.path),children:S(v,`Tải về`,`Download`)}),J.hasPending&&(0,B.jsx)(m,{onClick:J.checkPending,children:S(v,`Kiểm tra hoàn tác`,`Check revert`)}),(0,B.jsx)(m,{size:`small`,disabled:!F.authority?.writable||K.readOnly||!G||!Q(G)&&!G.pending||F.saving,onClick:()=>void F.save(K.path),children:S(v,`Lưu`,`Save`)}),(0,B.jsx)(m,{size:`small`,onClick:()=>F.close(K.path),children:S(v,`Đóng tệp`,`Close file`)}),(0,B.jsx)(m,{size:`small`,disabled:!F.authority?.writable||K.readOnly||!K.digest||F.saving,onClick:()=>{P(K.path),M(K.path)},children:S(v,`Đổi tên`,`Rename`)}),(0,B.jsx)(m,{size:`small`,color:`error`,disabled:!F.authority?.writable||K.readOnly||!K.digest||F.saving,onClick:()=>{window.confirm(S(v,`Xóa ${K.path}? Có thể khôi phục bằng Git nếu tệp đã commit.`,`Delete ${K.path}? Git can restore it if it was committed.`))&&F.move(K.path)},children:S(v,`Xóa`,`Delete`)}),(0,B.jsx)(m,{size:`small`,onClick:()=>{(!G||!Q(G)||window.confirm(S(v,`Bỏ thay đổi chưa lưu và tải lại?`,`Discard unsaved changes and reload?`)))&&F.reload(K.path)},children:S(v,`Tải lại`,`Reload`)})]}),K?.binary||K?.oversized||ge?(0,B.jsx)(ce,{sessionRef:e,path:K.path}):K?.content!==null&&K?.content!==void 0?(0,B.jsx)(_,{sx:{flex:1,minHeight:0},children:(0,B.jsx)(z.Suspense,{fallback:(0,B.jsx)(b,{size:20}),children:(0,B.jsx)(Ie,{onComment:Y.open,hunks:q.hunks,onKeep:q.keep,onRevert:F.authority?.writable?e=>void J.request(e):void 0,content:G?.draft??K.content,path:K.path,line:G?.line??1,readOnly:!F.authority?.writable||K.readOnly,onChange:e=>F.change(K.path,e),onSave:()=>void F.save(K.path)})})}):(0,B.jsx)(n,{sx:{p:2},children:S(v,`Chọn một tệp để mở.`,`Select a file to open.`)})]})]}),(0,B.jsxs)(r,{open:T,onClose:()=>E(!1),fullWidth:!0,children:[(0,B.jsx)(g,{children:S(v,`Tạo tệp mới`,`Create a new file`)}),(0,B.jsx)(i,{children:(0,B.jsx)(y,{autoFocus:!0,fullWidth:!0,label:S(v,`Đường dẫn trong project`,`Path in project`),value:D,onChange:e=>te(e.target.value)})}),(0,B.jsxs)(s,{children:[(0,B.jsx)(m,{onClick:()=>E(!1),children:S(v,`Hủy`,`Cancel`)}),(0,B.jsx)(m,{disabled:!O(D)||!F.authority?.writable,onClick:()=>{let e=O(D);!e||!F.authority||(I.some(t=>t.file.path===e.path)?F.select(e.path):F.load({schemaVersion:1,version:`piagent-webui-workspace-file-v1`,generatedAt:new Date().toISOString(),identity:F.authority.identity,path:e.path,language:`text`,protected:!1,readOnly:!1,binary:!1,oversized:!1,content:``,digest:null,revision:null},1,!0),E(!1))},children:S(v,`Tạo`,`Create`)})]})]}),(0,B.jsxs)(r,{open:!!j,onClose:()=>M(void 0),fullWidth:!0,children:[(0,B.jsx)(g,{children:S(v,`Đổi tên tệp`,`Rename file`)}),(0,B.jsx)(i,{children:(0,B.jsx)(y,{autoFocus:!0,fullWidth:!0,label:S(v,`Đường dẫn mới trong project`,`New path in project`),value:N,onChange:e=>P(e.target.value)})}),(0,B.jsxs)(s,{children:[(0,B.jsx)(m,{onClick:()=>M(void 0),children:S(v,`Hủy`,`Cancel`)}),(0,B.jsx)(m,{disabled:!O(N)||O(N)?.path===j||F.saving,onClick:()=>{let e=O(N);!e||!j||F.move(j,e.path).then(e=>{e&&M(void 0)})},children:S(v,`Đổi tên`,`Rename`)})]})]}),(0,B.jsxs)(r,{open:!!F.conflict,onClose:()=>{F.setConflict(void 0),A(!1)},fullWidth:!0,maxWidth:k?`lg`:`sm`,children:[(0,B.jsx)(g,{children:S(v,`Tệp đã thay đổi trên đĩa`,`The file changed on disk`)}),(0,B.jsxs)(i,{children:[(0,B.jsx)(n,{children:F.conflict?.path}),(0,B.jsx)(n,{children:S(v,`Bản sửa của bạn vẫn được giữ. Chọn cách xử lý xung đột.`,`Your draft is preserved. Choose how to resolve the conflict.`)}),k&&F.conflict&&X&&(0,B.jsxs)(p,{direction:`row`,spacing:1,children:[(0,B.jsxs)(_,{sx:{width:`50%`,height:360},children:[(0,B.jsx)(n,{children:S(v,`Trên đĩa`,`On disk`)}),(0,B.jsx)(z.Suspense,{fallback:(0,B.jsx)(b,{size:20}),children:(0,B.jsx)(Ie,{path:F.conflict.path,content:F.conflict.content??``})})]}),(0,B.jsxs)(_,{sx:{width:`50%`,height:360},children:[(0,B.jsx)(n,{children:S(v,`Bản sửa của bạn`,`Your draft`)}),(0,B.jsx)(z.Suspense,{fallback:(0,B.jsx)(b,{size:20}),children:(0,B.jsx)(Ie,{path:X.file.path,content:X.draft})})]})]})]}),(0,B.jsxs)(s,{children:[(0,B.jsx)(m,{onClick:()=>{F.setConflict(void 0),A(!1)},children:S(v,`Để sau`,`Later`)}),(0,B.jsx)(m,{onClick:()=>{F.conflict&&(F.load(F.conflict),F.setConflict(void 0),A(!1))},children:S(v,`Tải lại`,`Reload`)}),(0,B.jsx)(m,{onClick:()=>A(!0),children:S(v,`Xem khác biệt`,`Compare`)}),(0,B.jsx)(m,{disabled:F.saving||!F.conflict?.digest||F.conflict.protected||F.conflict.readOnly,onClick:()=>{F.conflict&&F.save(F.conflict.path,F.conflict)},children:S(v,`Ghi đè`,`Overwrite`)})]})]})]})}export{Le as default};
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/InspectionApp-9jBsgkVJ.js","assets/rolldown-runtime-hePW80VL.js","assets/vendor-DNZbaWhT.js","assets/bootstrap-CedkNtRG.js","assets/api-BQS4Dtrr.js","assets/latest-request-DXcYQW86.js","assets/App-JrRb7jgn.js","assets/ui-preferences-OfS30-ZV.js","assets/ActivityPanel-CmjxPmNT.js","assets/view-model-CWNiS4JN.js","assets/workspace-navigation-DW8zhH6U.js","assets/AttachmentImage-eZKqLYZ2.js","assets/transcript-view-model-acWtHGyE.js","assets/LineReview-CB3mQe7m.js","assets/GatewayApp-BmkqeXih.js","assets/SettingsNavigation-Wx-q5QQk.js","assets/composer-drafts-BtMaVw8W.js","assets/terminal-transport-Dk5pYNX5.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/InspectionApp-CGgHsOyC.js","assets/rolldown-runtime-hePW80VL.js","assets/vendor-DNZbaWhT.js","assets/bootstrap-CedkNtRG.js","assets/api-BQS4Dtrr.js","assets/latest-request-DXcYQW86.js","assets/App-C9tlGPMb.js","assets/ui-preferences-OfS30-ZV.js","assets/ActivityPanel-DeeJLOYx.js","assets/view-model-BrdSO09E.js","assets/workspace-navigation-DW8zhH6U.js","assets/AttachmentImage-eZKqLYZ2.js","assets/transcript-view-model-BB1niiXd.js","assets/LineReview-CB3mQe7m.js","assets/GatewayApp-Dvo96qoX.js","assets/SettingsNavigation-BZijmuPt.js","assets/composer-drafts-BtMaVw8W.js","assets/terminal-transport-Dk5pYNX5.js"])))=>i.map(i=>d[i]);
2
2
  import{r as e,t}from"./rolldown-runtime-hePW80VL.js";import{An as n,Cn as r,Dn as i,Fn as a,Gt as o,In as s,Ln as c,On as l,Pn as u,Rn as d,Sn as f,Ut as p,Wt as m,bn as h,gn as g,jn as _,kn as v,ln as y,mn as b,pn as x,un as S,vn as ee,yn as te}from"./vendor-DNZbaWhT.js";import{a as ne,n as re,o as ie,s as ae,t as oe}from"./ui-preferences-OfS30-ZV.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var se=t((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0<n;){var r=n-1>>>1,a=e[r];if(0<i(a,t))e[r]=t,e[n]=a,n=r;else break a}}function n(e){return e.length===0?null:e[0]}function r(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;a:for(var r=0,a=e.length,o=a>>>1;r<o;){var s=2*(r+1)-1,c=e[s],l=s+1,u=e[l];if(0>i(c,n))l<a&&0>i(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(l<a&&0>i(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m){if(n(c)!==null)m=!0,S||(S=!0,ae());else{var t=n(l);t!==null&&ce(x,t.startTime-e)}}}var S=!1,ee=-1,te=5,ne=-1;function re(){return g?!0:!(e.unstable_now()-ne<te)}function ie(){if(g=!1,S){var t=e.unstable_now();ne=t;var i=!0;try{a:{m=!1,h&&(h=!1,v(ee),ee=-1),p=!0;var a=f;try{b:{for(b(t),d=n(c);d!==null&&!(d.expirationTime>t&&re());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&ce(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}}}finally{i?ae():S=!1}}}var ae;if(typeof y==`function`)ae=function(){y(ie)};else if(typeof MessageChannel<`u`){var oe=new MessageChannel,se=oe.port2;oe.port1.onmessage=ie,ae=function(){se.postMessage(null)}}else ae=function(){_(ie,0)};function ce(t,n){ee=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125<e?console.error(`forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported`):te=0<e?Math.floor(1e3/e):5},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(e){switch(f){case 1:case 2:case 3:var t=3;break;default:t=f}var n=f;f=t;try{return e()}finally{f=n}},e.unstable_requestPaint=function(){g=!0},e.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=f;f=e;try{return t()}finally{f=n}},e.unstable_scheduleCallback=function(r,i,a){var o=e.unstable_now();switch(typeof a==`object`&&a?(a=a.delay,a=typeof a==`number`&&0<a?o+a:o):a=o,r){case 1:var s=-1;break;case 2:s=250;break;case 5:s=1073741823;break;case 4:s=1e4;break;default:s=5e3}return s=a+s,r={id:u++,callback:i,priorityLevel:r,startTime:a,expirationTime:s,sortIndex:-1},a>o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(ee),ee=-1):h=!0,ce(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,ae()))),r},e.unstable_shouldYield=re,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),ce=t(((e,t)=>{t.exports=se()})),le=t((e=>{var t=ce(),n=d(),r=c();function i(e){var t=`https://react.dev/errors/`+e;if(1<arguments.length){t+=`?args[]=`+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n])}return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}function a(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function o(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,t.flags&4098&&(n=t.return),e=t.return;while(e)}return t.tag===3?n:null}function s(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function l(e){if(e.tag===31){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function u(e){if(o(e)!==e)throw Error(i(188))}function f(e){var t=e.alternate;if(!t){if(t=o(e),t===null)throw Error(i(188));return t===e?e:null}for(var n=e,r=t;;){var a=n.return;if(a===null)break;var s=a.alternate;if(s===null){if(r=a.return,r!==null){n=r;continue}break}if(a.child===s.child){for(s=a.child;s;){if(s===n)return u(a),e;if(s===r)return u(a),t;s=s.sibling}throw Error(i(188))}if(n.return!==r.return)n=a,r=s;else{for(var c=!1,l=a.child;l;){if(l===n){c=!0,n=a,r=s;break}if(l===r){c=!0,r=a,n=s;break}l=l.sibling}if(!c){for(l=s.child;l;){if(l===n){c=!0,n=s,r=a;break}if(l===r){c=!0,r=s,n=a;break}l=l.sibling}if(!c)throw Error(i(189))}}if(n.alternate!==r)throw Error(i(190))}if(n.tag!==3)throw Error(i(188));return n.stateNode.current===n?e:t}function p(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=p(e),t!==null)return t;e=e.sibling}return null}var m=Object.assign,h=Symbol.for(`react.element`),g=Symbol.for(`react.transitional.element`),_=Symbol.for(`react.portal`),v=Symbol.for(`react.fragment`),y=Symbol.for(`react.strict_mode`),b=Symbol.for(`react.profiler`),x=Symbol.for(`react.consumer`),S=Symbol.for(`react.context`),ee=Symbol.for(`react.forward_ref`),te=Symbol.for(`react.suspense`),ne=Symbol.for(`react.suspense_list`),re=Symbol.for(`react.memo`),ie=Symbol.for(`react.lazy`),ae=Symbol.for(`react.activity`),oe=Symbol.for(`react.memo_cache_sentinel`),se=Symbol.iterator;function le(e){return typeof e!=`object`||!e?null:(e=se&&e[se]||e[`@@iterator`],typeof e==`function`?e:null)}var ue=Symbol.for(`react.client.reference`);function C(e){if(e==null)return null;if(typeof e==`function`)return e.$$typeof===ue?null:e.displayName||e.name||null;if(typeof e==`string`)return e;switch(e){case v:return`Fragment`;case b:return`Profiler`;case y:return`StrictMode`;case te:return`Suspense`;case ne:return`SuspenseList`;case ae:return`Activity`}if(typeof e==`object`)switch(e.$$typeof){case _:return`Portal`;case S:return e.displayName||`Context`;case x:return(e._context.displayName||`Context`)+`.Consumer`;case ee:var t=e.render;return e=e.displayName,e||=(e=t.displayName||t.name||``,e===``?`ForwardRef`:`ForwardRef(`+e+`)`),e;case re:return t=e.displayName||null,t===null?C(e.type)||`Memo`:t;case ie:t=e._payload,e=e._init;try{return C(e(t))}catch{}}return null}var de=Array.isArray,w=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,T=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,E={pending:!1,data:null,method:null,action:null},fe=[],pe=-1;function me(e){return{current:e}}function D(e){0>pe||(e.current=fe[pe],fe[pe]=null,pe--)}function O(e,t){pe++,fe[pe]=e.current,e.current=t}var he=me(null),ge=me(null),_e=me(null),ve=me(null);function ye(e,t){switch(O(_e,t),O(ge,e),O(he,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Vd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Vd(t),e=Hd(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}D(he),O(he,e)}function be(){D(he),D(ge),D(_e)}function xe(e){e.memoizedState!==null&&O(ve,e);var t=he.current,n=Hd(t,e.type);t!==n&&(O(ge,e),O(he,n))}function Se(e){ge.current===e&&(D(he),D(ge)),ve.current===e&&(D(ve),Qf._currentValue=E)}var Ce,we;function Te(e){if(Ce===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);Ce=t&&t[1]||``,we=-1<e.stack.indexOf(`
3
3
  at`)?` (<anonymous>)`:-1<e.stack.indexOf(`@`)?`@unknown:0:0`:``}return`
4
4
  `+Ce+e+we}var Ee=!1;function De(e,t){if(!e||Ee)return``;Ee=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var r={DetermineComponentFrameRoot:function(){try{if(t){var n=function(){throw Error()};if(Object.defineProperty(n.prototype,"props",{set:function(){throw Error()}}),typeof Reflect==`object`&&Reflect.construct){try{Reflect.construct(n,[])}catch(e){var r=e}Reflect.construct(e,[],n)}else{try{n.call()}catch(e){r=e}e.call(n.prototype)}}else{try{throw Error()}catch(e){r=e}(n=e())&&typeof n.catch==`function`&&n.catch(function(){})}}catch(e){if(e&&r&&typeof e.stack==`string`)return[e.stack,r.stack]}return[null,null]}};r.DetermineComponentFrameRoot.displayName=`DetermineComponentFrameRoot`;var i=Object.getOwnPropertyDescriptor(r.DetermineComponentFrameRoot,`name`);i&&i.configurable&&Object.defineProperty(r.DetermineComponentFrameRoot,"name",{value:`DetermineComponentFrameRoot`});var a=r.DetermineComponentFrameRoot(),o=a[0],s=a[1];if(o&&s){var c=o.split(`
@@ -34,4 +34,4 @@ try {
34
34
  if (colorScheme) {
35
35
  ${l}
36
36
  }
37
- } catch(e){}})();`}},`mui-color-scheme-init`)}function be(){}var xe=({key:e,storageWindow:t})=>(!t&&typeof window<`u`&&(t=window),{get(n){if(typeof window>`u`)return;if(!t)return n;let r;try{r=t.localStorage.getItem(e)}catch{}return r||n},set:n=>{if(t)try{t.localStorage.setItem(e,n)}catch{}},subscribe:n=>{if(!t)return be;let r=t=>{let r=t.newValue;t.key===e&&n(r)};return t.addEventListener(`storage`,r),()=>{t.removeEventListener(`storage`,r)}}});function Se(){}function Ce(e){if(typeof window<`u`&&typeof window.matchMedia==`function`&&e===`system`)return window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`}function we(e,t){if(e.mode===`light`||e.mode===`system`&&e.systemMode===`light`)return t(`light`);if(e.mode===`dark`||e.mode===`system`&&e.systemMode===`dark`)return t(`dark`)}function Te(e){return we(e,t=>{if(t===`light`)return e.lightColorScheme;if(t===`dark`)return e.darkColorScheme})}function Ee(e){let{defaultMode:t=`light`,defaultLightColorScheme:n,defaultDarkColorScheme:r,supportedColorSchemes:i=[],modeStorageKey:a=ge,colorSchemeStorageKey:o=_e,storageWindow:s=typeof window>`u`?void 0:window,storageManager:c=xe,noSsr:l=!1}=e,u=i.join(`,`),d=i.length>1,f=C.useMemo(()=>c?.({key:a,storageWindow:s}),[c,a,s]),p=C.useMemo(()=>c?.({key:`${o}-light`,storageWindow:s}),[c,o,s]),m=C.useMemo(()=>c?.({key:`${o}-dark`,storageWindow:s}),[c,o,s]),[h,g]=C.useState(()=>{let e=f?.get(t)||t,i=p?.get(n)||n,a=m?.get(r)||r;return{mode:e,systemMode:Ce(e),lightColorScheme:i,darkColorScheme:a}}),[_,v]=C.useState(l||!d);C.useEffect(()=>{v(!0)},[]);let y=Te(h),b=C.useCallback(e=>{g(n=>{if(e===n.mode)return n;let r=e??t;return f?.set(r),{...n,mode:r,systemMode:Ce(r)}})},[f,t]),x=C.useCallback(e=>{e?typeof e==`string`?e&&!u.includes(e)?console.error(`\`${e}\` does not exist in \`theme.colorSchemes\`.`):g(t=>{let n={...t};return we(t,t=>{t===`light`&&(p?.set(e),n.lightColorScheme=e),t===`dark`&&(m?.set(e),n.darkColorScheme=e)}),n}):g(t=>{let i={...t},a=e.light===null?n:e.light,o=e.dark===null?r:e.dark;return a&&(u.includes(a)?(i.lightColorScheme=a,p?.set(a)):console.error(`\`${a}\` does not exist in \`theme.colorSchemes\`.`)),o&&(u.includes(o)?(i.darkColorScheme=o,m?.set(o)):console.error(`\`${o}\` does not exist in \`theme.colorSchemes\`.`)),i}):g(e=>(p?.set(n),m?.set(r),{...e,lightColorScheme:n,darkColorScheme:r}))},[u,p,m,n,r]),S=C.useCallback(e=>{h.mode===`system`&&g(t=>{let n=e?.matches?`dark`:`light`;return t.systemMode===n?t:{...t,systemMode:n}})},[h.mode]),ee=C.useRef(S);return ee.current=S,C.useEffect(()=>{if(typeof window.matchMedia!=`function`||!d)return;let e=(...e)=>ee.current(...e),t=window.matchMedia(`(prefers-color-scheme: dark)`);return t.addListener(e),e(t),()=>{t.removeListener(e)}},[d]),C.useEffect(()=>{if(d){let e=f?.subscribe(e=>{(!e||[`light`,`dark`,`system`].includes(e))&&b(e||t)})||Se,n=p?.subscribe(e=>{(!e||u.match(e))&&x({light:e})})||Se,r=m?.subscribe(e=>{(!e||u.match(e))&&x({dark:e})})||Se;return()=>{e(),n(),r()}}},[x,b,u,t,s,d,f,p,m]),{...h,mode:_?h.mode:void 0,systemMode:_?h.systemMode:void 0,colorScheme:_?y:void 0,setMode:b,setColorScheme:x}}var De=`*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}`;function Oe(e){let{themeId:t,theme:n={},modeStorageKey:i=ge,colorSchemeStorageKey:a=_e,disableTransitionOnChange:o=!1,defaultColorScheme:s,resolveTheme:c}=e,l={allColorSchemes:[],colorScheme:void 0,darkColorScheme:void 0,lightColorScheme:void 0,mode:void 0,setColorScheme:()=>{},setMode:()=>{},systemMode:void 0},u=C.createContext(void 0),d=()=>C.useContext(u)||l,f={},p={};function m(e){let{children:l,theme:d,modeStorageKey:m=i,colorSchemeStorageKey:h=a,disableTransitionOnChange:g=o,storageManager:_,storageWindow:y=typeof window>`u`?void 0:window,documentNode:b=typeof document>`u`?void 0:document,colorSchemeNode:x=typeof document>`u`?void 0:document.documentElement,disableNestedContext:S=!1,disableStyleSheetGeneration:ee=!1,defaultMode:te=`system`,forceThemeRerender:ne=!1,noSsr:re}=e,ie=C.useRef(!1),ae=w(),oe=C.useContext(u),se=!!oe&&!S,ce=C.useMemo(()=>d||(typeof n==`function`?n():n),[d]),le=ce[t],ue=le||ce,{colorSchemes:de=f,components:T=p,cssVarPrefix:fe}=ue,pe=Object.keys(de).filter(e=>!!de[e]).join(`,`),me=C.useMemo(()=>pe.split(`,`),[pe]),D=typeof s==`string`?s:s.light,O=typeof s==`string`?s:s.dark,{mode:ge,setMode:_e,systemMode:ve,lightColorScheme:ye,darkColorScheme:be,colorScheme:xe,setColorScheme:Se}=Ee({supportedColorSchemes:me,defaultLightColorScheme:D,defaultDarkColorScheme:O,modeStorageKey:m,colorSchemeStorageKey:h,defaultMode:de[D]&&de[O]?te:de[ue.defaultColorScheme]?.palette?.mode||ue.palette?.mode,storageManager:_,storageWindow:y,noSsr:re}),Ce=ge,we=xe;se&&(Ce=oe.mode,we=oe.colorScheme);let Te=we||ue.defaultColorScheme;ue.vars&&!ne&&(Te=ue.defaultColorScheme);let Oe=C.useMemo(()=>{let e=ue.generateThemeVars?.()||ue.vars,t={...ue,components:T,colorSchemes:de,cssVarPrefix:fe,vars:e};if(typeof t.generateSpacing==`function`&&(t.spacing=t.generateSpacing()),Te){let e=de[Te];e&&typeof e==`object`&&Object.keys(e).forEach(n=>{e[n]&&typeof e[n]==`object`?t[n]={...t[n],...e[n]}:t[n]=e[n]})}return c?c(t):t},[ue,Te,T,de,fe]),ke=ue.colorSchemeSelector;r(()=>{if(we&&x&&ke&&ke!==`media`){let e=ke,t=ke;if(e===`class`&&(t=`.%s`),e===`data`&&(t=`[data-%s]`),e?.startsWith(`data-`)&&!e.includes(`%s`)&&(t=`[${e}="%s"]`),t.startsWith(`.`))x.classList.remove(...me.map(e=>t.substring(1).replace(`%s`,e))),x.classList.add(t.substring(1).replace(`%s`,we));else{let e=t.replace(`%s`,we).match(/\[([^\]]+)\]/);if(e){let[t,n]=e[1].split(`=`);n||me.forEach(e=>{x.removeAttribute(t.replace(we,e))}),x.setAttribute(t,n?n.replace(/"|'/g,``):``)}else x.setAttribute(t,we)}}},[we,ke,x,me]),C.useEffect(()=>{let e;if(g&&ie.current&&b){let t=b.createElement(`style`);t.appendChild(b.createTextNode(De)),b.head.appendChild(t),window.getComputedStyle(b.body),e=setTimeout(()=>{b.head.removeChild(t)},1)}return()=>{clearTimeout(e)}},[we,g,b]),C.useEffect(()=>(ie.current=!0,()=>{ie.current=!1}),[]);let Ae=C.useMemo(()=>({allColorSchemes:me,colorScheme:we,darkColorScheme:be,lightColorScheme:ye,mode:Ce,setColorScheme:Se,setMode:_e,systemMode:ve}),[me,we,be,ye,Ce,Se,_e,ve,Oe.colorSchemeSelector]),je=!0;(ee||ue.cssVariables===!1||se&&ae?.cssVarPrefix===fe)&&(je=!1);let Me=(0,E.jsxs)(C.Fragment,{children:[(0,E.jsx)(he,{themeId:le?t:void 0,theme:Oe,children:l}),je&&(0,E.jsx)(v,{styles:Oe.generateStyleSheets?.()||[]})]});return se?Me:(0,E.jsx)(u.Provider,{value:Ae,children:Me})}let h=typeof s==`string`?s:s.light,g=typeof s==`string`?s:s.dark;return{CssVarsProvider:m,useColorScheme:d,getInitColorSchemeScript:e=>ye({colorSchemeStorageKey:a,defaultLightColorScheme:h,defaultDarkColorScheme:g,modeStorageKey:i,...e})}}var ke=typeof S({})==`function`,Ae=(e,t)=>({WebkitFontSmoothing:`antialiased`,MozOsxFontSmoothing:`grayscale`,boxSizing:`border-box`,WebkitTextSizeAdjust:`100%`,...t&&!e.vars&&{colorScheme:e.palette.mode}}),je=e=>({color:(e.vars||e).palette.text.primary,...e.typography.body1,backgroundColor:(e.vars||e).palette.background.default,"@media print":{backgroundColor:(e.vars||e).palette.common.white}}),Me=(e,t=!1)=>{let n={};t&&e.colorSchemes&&typeof e.getColorSchemeSelector==`function`&&Object.entries(e.colorSchemes).forEach(([t,r])=>{let i=e.getColorSchemeSelector(t);i.startsWith(`@`)?n[i]={":root":{colorScheme:r.palette?.mode}}:n[i.replace(/\s*&/,``)]={colorScheme:r.palette?.mode}});let r={html:Ae(e,t),"*, *::before, *::after":{boxSizing:`inherit`},"strong, b":{fontWeight:e.typography.fontWeightBold},body:{margin:0,...je(e),"&::backdrop":{backgroundColor:(e.vars||e).palette.background.default}},...n},i=e.components?.MuiCssBaseline?.styleOverrides;return i&&(r=[r,i]),r},Ne=`mui-ecs`,Pe=e=>{let t=Me(e,!1),n=Array.isArray(t)?t[0]:t;return!e.vars&&n&&(n.html[`:root:has(${Ne})`]={colorScheme:e.palette.mode}),e.colorSchemes&&Object.entries(e.colorSchemes).forEach(([t,r])=>{let i=e.getColorSchemeSelector(t);i.startsWith(`@`)?n[i]={[`:root:not(:has(.${Ne}))`]:{colorScheme:r.palette?.mode}}:n[i.replace(/\s*&/,``)]={[`&:not(:has(.${Ne}))`]:{colorScheme:r.palette?.mode}}}),t},Fe=S(ke?({theme:e,enableColorScheme:t})=>Me(e,t):({theme:e})=>Pe(e));function Ie(e){let{children:t,enableColorScheme:n=!1}=y({props:e,name:`MuiCssBaseline`});return(0,E.jsxs)(C.Fragment,{children:[ke&&(0,E.jsx)(Fe,{enableColorScheme:n}),!ke&&!n&&(0,E.jsx)(`span`,{className:Ne,style:{display:`none`}}),t]})}function Le({theme:e,...t}){let n=`$$material`in e?e[x]:void 0;return(0,E.jsx)(he,{...t,themeId:n?x:void 0,theme:n||e})}var Re={attribute:`data-mui-color-scheme`,colorSchemeStorageKey:`mui-color-scheme`,defaultLightColorScheme:`light`,defaultDarkColorScheme:`dark`,modeStorageKey:`mui-mode`},{CssVarsProvider:ze,useColorScheme:Be,getInitColorSchemeScript:Ve}=Oe({themeId:x,theme:()=>b({cssVariables:!0}),colorSchemeStorageKey:Re.colorSchemeStorageKey,modeStorageKey:Re.modeStorageKey,defaultColorScheme:{light:Re.defaultLightColorScheme,dark:Re.defaultDarkColorScheme},resolveTheme:e=>{let t={...e,typography:g(e.palette,e.typography)};return t.unstable_sx=function(e){return _({sx:e,theme:this})},t}}),He=ze;function Ue({theme:e,...t}){let n=C.useMemo(()=>{if(typeof e==`function`)return e;let t=`$$material`in e?e[x]:e;return`colorSchemes`in t?null:`vars`in t?e:{...e,vars:null}},[e]);return n?(0,E.jsx)(Le,{theme:n,...t}):(0,E.jsx)(He,{theme:e,...t})}var We=ue(),Ge=class extends C.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}render(){let{locale:e,children:t}=this.props;return this.state.failed?(0,E.jsxs)(m,{sx:{p:3},children:[(0,E.jsx)(o,{severity:`error`,children:re(e,`Không tải được giao diện. Vui lòng tải lại để thử lại.`,`Could not load this view. Reload to try again.`)}),(0,E.jsx)(p,{onClick:()=>window.location.reload(),children:re(e,`Tải lại trang`,`Reload page`)})]}):(0,E.jsx)(C.Suspense,{fallback:(0,E.jsx)(m,{role:`status`,sx:{p:3},children:re(e,`Đang tải giao diện…`,`Loading view…`)}),children:t})}};function Ke(e){let t=e.mode===`dark`,n=e.mode,{primary:r,secondary:i,background:a,paper:o,text:s,muted:c,divider:l}=e,u=t?`0 16px 48px -12px ${f(`#000`,.7)}, 0 0 0 1px ${f(s,.06)}`:`0 16px 40px -16px ${f(`#1a1a2e`,.25)}, 0 0 0 1px ${f(s,.06)}`,d=`0 0 0 3px ${f(r,t?.28:.22)}`;return b({cssVariables:{cssVarPrefix:`piagent`},palette:{mode:n,primary:{main:r,contrastText:e.onPrimary},secondary:{main:i},success:{main:i},warning:{main:e.warning},error:{main:e.error},background:{default:a,paper:o},text:{primary:s,secondary:c,disabled:c},divider:l,action:{hover:f(s,.05),selected:f(s,.08),focus:f(r,.14)}},shape:{borderRadius:6},transitions:{duration:{shortest:120,shorter:160,short:180,standard:200,complex:260,enteringScreen:200,leavingScreen:160}},typography:{fontFamily:`system-ui, -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, sans-serif`,fontSize:14,fontWeightRegular:400,fontWeightMedium:500,fontWeightBold:600,h1:{fontSize:`1.6rem`,fontWeight:650,letterSpacing:`-0.03em`,lineHeight:1.2},h2:{fontSize:`1.15rem`,fontWeight:600,letterSpacing:`-0.02em`},h3:{fontSize:`0.95rem`,fontWeight:600},body2:{fontSize:`0.8125rem`},button:{fontSize:`0.8125rem`,fontWeight:550,textTransform:`none`,letterSpacing:0},caption:{fontSize:`0.72rem`,letterSpacing:0},overline:{fontSize:`0.68rem`,fontWeight:600,letterSpacing:`0.08em`}},components:{MuiCssBaseline:{styleOverrides:{html:{backgroundColor:a,WebkitFontSmoothing:`antialiased`},body:{minWidth:320,minHeight:`100vh`,backgroundColor:a},"::selection":{backgroundColor:f(r,.28)},"*":{scrollbarWidth:`thin`,scrollbarColor:`${f(s,.18)} transparent`}}},MuiPaper:{defaultProps:{elevation:0},styleOverrides:{root:{backgroundImage:`none`}}},MuiButtonBase:{defaultProps:{disableRipple:!0}},MuiButton:{defaultProps:{disableElevation:!0},styleOverrides:{root:{minHeight:32,borderRadius:8,paddingInline:12,transition:`background-color .16s, border-color .16s, box-shadow .16s, color .16s`,"&.Mui-focusVisible":{boxShadow:d}},sizeSmall:{minHeight:28,paddingInline:10,fontSize:`0.78rem`},outlined:{borderColor:f(s,.14),"&:hover":{borderColor:f(s,.28),backgroundColor:f(s,.04)}},contained:{"&.MuiButton-colorPrimary:hover":{backgroundColor:f(r,.88),boxShadow:`0 0 0 3px ${f(r,.18)}`}},text:{"&:hover":{backgroundColor:f(s,.06)}}}},MuiIconButton:{styleOverrides:{root:{borderRadius:8,color:c,transition:`background-color .16s, color .16s`,"&:hover":{color:s,backgroundColor:f(s,.07)},"&.Mui-focusVisible":{boxShadow:d}},sizeSmall:{padding:5}}},MuiChip:{styleOverrides:{root:{height:24,borderRadius:999,fontWeight:500,fontSize:`0.75rem`},outlined:{borderColor:f(s,.14)},label:{paddingInline:9}}},MuiListItemButton:{styleOverrides:{root:{minHeight:36,margin:`1px 8px`,borderRadius:8,color:c,transition:`background-color .12s, color .12s`,"&:hover":{backgroundColor:f(s,.05),color:s},"&.Mui-selected":{color:s,backgroundColor:f(s,t?.08:.07)},"&.Mui-selected:hover":{backgroundColor:f(s,t?.11:.09)},"&.Mui-focusVisible":{boxShadow:d}}}},MuiTabs:{styleOverrides:{root:{minHeight:40},indicator:{height:2,borderRadius:2}}},MuiTab:{styleOverrides:{root:{minHeight:40,paddingInline:14,textTransform:`none`,fontWeight:550,fontSize:`0.8125rem`,color:c,"&.Mui-selected":{color:s}}}},MuiOutlinedInput:{styleOverrides:{root:{borderRadius:8,backgroundColor:f(s,t?.03:.02),transition:`box-shadow .16s`,"& .MuiOutlinedInput-notchedOutline":{borderColor:f(s,.12)},"&:hover .MuiOutlinedInput-notchedOutline":{borderColor:f(s,.24)},"&.Mui-focused":{boxShadow:d},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:r,borderWidth:1}}}},MuiTooltip:{defaultProps:{arrow:!1,enterDelay:350},styleOverrides:{tooltip:{fontSize:`0.75rem`,fontWeight:500,padding:`5px 9px`,borderRadius:6,color:t?s:`#fafafa`,backgroundColor:t?f(o,.98):`#1f1f24`,boxShadow:u}}},MuiMenu:{styleOverrides:{paper:{borderRadius:10,boxShadow:u,backgroundImage:`none`,marginTop:4},list:{padding:4}}},MuiPopover:{styleOverrides:{paper:{borderRadius:10,boxShadow:u}}},MuiMenuItem:{styleOverrides:{root:{minHeight:32,borderRadius:6,fontSize:`0.8125rem`,"&:hover":{backgroundColor:f(s,.06)},"&.Mui-selected":{backgroundColor:f(r,.12)}}}},MuiDialog:{styleOverrides:{paper:{borderRadius:14,boxShadow:u,backgroundImage:`none`}}},MuiBackdrop:{styleOverrides:{root:{backgroundColor:f(`#000`,t?.6:.32),backdropFilter:`blur(2px)`}}},MuiDrawer:{styleOverrides:{paper:{backgroundImage:`none`,backgroundColor:o}}},MuiAlert:{styleOverrides:{root:{borderRadius:10,border:`1px solid ${f(s,.1)}`,fontSize:`0.8125rem`,alignItems:`center`}}},MuiDivider:{styleOverrides:{root:{borderColor:l}}},MuiLinearProgress:{styleOverrides:{root:{borderRadius:999,height:4},bar:{borderRadius:999}}}}})}function qe(e){for(let t of e??[]){let e=String(t).toLowerCase().split(`-`)[0];if(e===`vi`)return`vi`;if(e)return`en`}return`en`}var Je=`modulepreload`,Ye=function(e){return`/`+e},Xe={},Ze=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=Ye(t,n),t=s(t),t in Xe)return;Xe[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:Je,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Qe=document.getElementById(`root`);if(!Qe)throw Error(`Piagent WebUI root is missing`);var $e=document.querySelector(`meta[name="csp-nonce"]`)?.content,et=s({key:`piagent-mui`,nonce:$e&&!$e.startsWith(`__PIAGENT_`)?$e:void 0,prepend:!0}),tt=(0,C.lazy)(()=>Ze(()=>import(`./InspectionApp-9jBsgkVJ.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]))),nt=(0,C.lazy)(()=>Ze(()=>import(`./GatewayApp-BmkqeXih.js`),__vite__mapDeps([14,1,2,7,3,4,9,15,10,11,12,16,5,17])));function rt(e,t,n){try{let r=window.localStorage.getItem(e);return r&&t.includes(r)?r:n}catch{return n}}function it(){let[e,t]=(0,C.useState)(()=>rt(`piagent-webui-locale`,[`vi`,`en`],qe(window.navigator?.languages??[window.navigator?.language??``]))),[n,r]=(0,C.useState)(()=>rt(`piagent-webui-theme`,ie.map(e=>e.id),``)||ne[rt(`piagent-webui-color-mode`,[`light`,`dark`],window.matchMedia?.(`(prefers-color-scheme: light)`).matches?`light`:`dark`)]),i=ae(n)??ae(ne.dark),a=i.mode,o=(0,C.useCallback)(e=>r(t=>ae(t)?.mode===e?t:ne[e]),[]),s=(0,C.useMemo)(()=>Ke(i),[i]);(0,C.useEffect)(()=>{document.documentElement.lang=e,document.documentElement.dataset.piagentColorMode=a,document.documentElement.dataset.piagentTheme=i.id;try{window.localStorage.setItem(`piagent-webui-locale`,e),window.localStorage.setItem(`piagent-webui-color-mode`,a),window.localStorage.setItem(`piagent-webui-theme`,i.id)}catch{}},[a,e,i]);let c=(0,C.useMemo)(()=>({locale:e,colorMode:a,themeId:i.id,setLocale:t,setColorMode:o,setThemeId:r}),[a,e,i,o]),l=document.querySelector(`meta[name="piagent-webui-mode"]`)?.content;return(0,E.jsx)(oe,{value:c,children:(0,E.jsxs)(Ue,{theme:s,children:[(0,E.jsx)(Ie,{}),(0,E.jsx)(Ge,{locale:e,children:l===`gateway`?(0,E.jsx)(nt,{}):(0,E.jsx)(tt,{})})]})})}(0,We.createRoot)(Qe).render((0,E.jsx)(C.StrictMode,{children:(0,E.jsx)(u,{value:et,children:(0,E.jsx)(it,{})})}));export{Ge as n,Ze as t};
37
+ } catch(e){}})();`}},`mui-color-scheme-init`)}function be(){}var xe=({key:e,storageWindow:t})=>(!t&&typeof window<`u`&&(t=window),{get(n){if(typeof window>`u`)return;if(!t)return n;let r;try{r=t.localStorage.getItem(e)}catch{}return r||n},set:n=>{if(t)try{t.localStorage.setItem(e,n)}catch{}},subscribe:n=>{if(!t)return be;let r=t=>{let r=t.newValue;t.key===e&&n(r)};return t.addEventListener(`storage`,r),()=>{t.removeEventListener(`storage`,r)}}});function Se(){}function Ce(e){if(typeof window<`u`&&typeof window.matchMedia==`function`&&e===`system`)return window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`}function we(e,t){if(e.mode===`light`||e.mode===`system`&&e.systemMode===`light`)return t(`light`);if(e.mode===`dark`||e.mode===`system`&&e.systemMode===`dark`)return t(`dark`)}function Te(e){return we(e,t=>{if(t===`light`)return e.lightColorScheme;if(t===`dark`)return e.darkColorScheme})}function Ee(e){let{defaultMode:t=`light`,defaultLightColorScheme:n,defaultDarkColorScheme:r,supportedColorSchemes:i=[],modeStorageKey:a=ge,colorSchemeStorageKey:o=_e,storageWindow:s=typeof window>`u`?void 0:window,storageManager:c=xe,noSsr:l=!1}=e,u=i.join(`,`),d=i.length>1,f=C.useMemo(()=>c?.({key:a,storageWindow:s}),[c,a,s]),p=C.useMemo(()=>c?.({key:`${o}-light`,storageWindow:s}),[c,o,s]),m=C.useMemo(()=>c?.({key:`${o}-dark`,storageWindow:s}),[c,o,s]),[h,g]=C.useState(()=>{let e=f?.get(t)||t,i=p?.get(n)||n,a=m?.get(r)||r;return{mode:e,systemMode:Ce(e),lightColorScheme:i,darkColorScheme:a}}),[_,v]=C.useState(l||!d);C.useEffect(()=>{v(!0)},[]);let y=Te(h),b=C.useCallback(e=>{g(n=>{if(e===n.mode)return n;let r=e??t;return f?.set(r),{...n,mode:r,systemMode:Ce(r)}})},[f,t]),x=C.useCallback(e=>{e?typeof e==`string`?e&&!u.includes(e)?console.error(`\`${e}\` does not exist in \`theme.colorSchemes\`.`):g(t=>{let n={...t};return we(t,t=>{t===`light`&&(p?.set(e),n.lightColorScheme=e),t===`dark`&&(m?.set(e),n.darkColorScheme=e)}),n}):g(t=>{let i={...t},a=e.light===null?n:e.light,o=e.dark===null?r:e.dark;return a&&(u.includes(a)?(i.lightColorScheme=a,p?.set(a)):console.error(`\`${a}\` does not exist in \`theme.colorSchemes\`.`)),o&&(u.includes(o)?(i.darkColorScheme=o,m?.set(o)):console.error(`\`${o}\` does not exist in \`theme.colorSchemes\`.`)),i}):g(e=>(p?.set(n),m?.set(r),{...e,lightColorScheme:n,darkColorScheme:r}))},[u,p,m,n,r]),S=C.useCallback(e=>{h.mode===`system`&&g(t=>{let n=e?.matches?`dark`:`light`;return t.systemMode===n?t:{...t,systemMode:n}})},[h.mode]),ee=C.useRef(S);return ee.current=S,C.useEffect(()=>{if(typeof window.matchMedia!=`function`||!d)return;let e=(...e)=>ee.current(...e),t=window.matchMedia(`(prefers-color-scheme: dark)`);return t.addListener(e),e(t),()=>{t.removeListener(e)}},[d]),C.useEffect(()=>{if(d){let e=f?.subscribe(e=>{(!e||[`light`,`dark`,`system`].includes(e))&&b(e||t)})||Se,n=p?.subscribe(e=>{(!e||u.match(e))&&x({light:e})})||Se,r=m?.subscribe(e=>{(!e||u.match(e))&&x({dark:e})})||Se;return()=>{e(),n(),r()}}},[x,b,u,t,s,d,f,p,m]),{...h,mode:_?h.mode:void 0,systemMode:_?h.systemMode:void 0,colorScheme:_?y:void 0,setMode:b,setColorScheme:x}}var De=`*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}`;function Oe(e){let{themeId:t,theme:n={},modeStorageKey:i=ge,colorSchemeStorageKey:a=_e,disableTransitionOnChange:o=!1,defaultColorScheme:s,resolveTheme:c}=e,l={allColorSchemes:[],colorScheme:void 0,darkColorScheme:void 0,lightColorScheme:void 0,mode:void 0,setColorScheme:()=>{},setMode:()=>{},systemMode:void 0},u=C.createContext(void 0),d=()=>C.useContext(u)||l,f={},p={};function m(e){let{children:l,theme:d,modeStorageKey:m=i,colorSchemeStorageKey:h=a,disableTransitionOnChange:g=o,storageManager:_,storageWindow:y=typeof window>`u`?void 0:window,documentNode:b=typeof document>`u`?void 0:document,colorSchemeNode:x=typeof document>`u`?void 0:document.documentElement,disableNestedContext:S=!1,disableStyleSheetGeneration:ee=!1,defaultMode:te=`system`,forceThemeRerender:ne=!1,noSsr:re}=e,ie=C.useRef(!1),ae=w(),oe=C.useContext(u),se=!!oe&&!S,ce=C.useMemo(()=>d||(typeof n==`function`?n():n),[d]),le=ce[t],ue=le||ce,{colorSchemes:de=f,components:T=p,cssVarPrefix:fe}=ue,pe=Object.keys(de).filter(e=>!!de[e]).join(`,`),me=C.useMemo(()=>pe.split(`,`),[pe]),D=typeof s==`string`?s:s.light,O=typeof s==`string`?s:s.dark,{mode:ge,setMode:_e,systemMode:ve,lightColorScheme:ye,darkColorScheme:be,colorScheme:xe,setColorScheme:Se}=Ee({supportedColorSchemes:me,defaultLightColorScheme:D,defaultDarkColorScheme:O,modeStorageKey:m,colorSchemeStorageKey:h,defaultMode:de[D]&&de[O]?te:de[ue.defaultColorScheme]?.palette?.mode||ue.palette?.mode,storageManager:_,storageWindow:y,noSsr:re}),Ce=ge,we=xe;se&&(Ce=oe.mode,we=oe.colorScheme);let Te=we||ue.defaultColorScheme;ue.vars&&!ne&&(Te=ue.defaultColorScheme);let Oe=C.useMemo(()=>{let e=ue.generateThemeVars?.()||ue.vars,t={...ue,components:T,colorSchemes:de,cssVarPrefix:fe,vars:e};if(typeof t.generateSpacing==`function`&&(t.spacing=t.generateSpacing()),Te){let e=de[Te];e&&typeof e==`object`&&Object.keys(e).forEach(n=>{e[n]&&typeof e[n]==`object`?t[n]={...t[n],...e[n]}:t[n]=e[n]})}return c?c(t):t},[ue,Te,T,de,fe]),ke=ue.colorSchemeSelector;r(()=>{if(we&&x&&ke&&ke!==`media`){let e=ke,t=ke;if(e===`class`&&(t=`.%s`),e===`data`&&(t=`[data-%s]`),e?.startsWith(`data-`)&&!e.includes(`%s`)&&(t=`[${e}="%s"]`),t.startsWith(`.`))x.classList.remove(...me.map(e=>t.substring(1).replace(`%s`,e))),x.classList.add(t.substring(1).replace(`%s`,we));else{let e=t.replace(`%s`,we).match(/\[([^\]]+)\]/);if(e){let[t,n]=e[1].split(`=`);n||me.forEach(e=>{x.removeAttribute(t.replace(we,e))}),x.setAttribute(t,n?n.replace(/"|'/g,``):``)}else x.setAttribute(t,we)}}},[we,ke,x,me]),C.useEffect(()=>{let e;if(g&&ie.current&&b){let t=b.createElement(`style`);t.appendChild(b.createTextNode(De)),b.head.appendChild(t),window.getComputedStyle(b.body),e=setTimeout(()=>{b.head.removeChild(t)},1)}return()=>{clearTimeout(e)}},[we,g,b]),C.useEffect(()=>(ie.current=!0,()=>{ie.current=!1}),[]);let Ae=C.useMemo(()=>({allColorSchemes:me,colorScheme:we,darkColorScheme:be,lightColorScheme:ye,mode:Ce,setColorScheme:Se,setMode:_e,systemMode:ve}),[me,we,be,ye,Ce,Se,_e,ve,Oe.colorSchemeSelector]),je=!0;(ee||ue.cssVariables===!1||se&&ae?.cssVarPrefix===fe)&&(je=!1);let Me=(0,E.jsxs)(C.Fragment,{children:[(0,E.jsx)(he,{themeId:le?t:void 0,theme:Oe,children:l}),je&&(0,E.jsx)(v,{styles:Oe.generateStyleSheets?.()||[]})]});return se?Me:(0,E.jsx)(u.Provider,{value:Ae,children:Me})}let h=typeof s==`string`?s:s.light,g=typeof s==`string`?s:s.dark;return{CssVarsProvider:m,useColorScheme:d,getInitColorSchemeScript:e=>ye({colorSchemeStorageKey:a,defaultLightColorScheme:h,defaultDarkColorScheme:g,modeStorageKey:i,...e})}}var ke=typeof S({})==`function`,Ae=(e,t)=>({WebkitFontSmoothing:`antialiased`,MozOsxFontSmoothing:`grayscale`,boxSizing:`border-box`,WebkitTextSizeAdjust:`100%`,...t&&!e.vars&&{colorScheme:e.palette.mode}}),je=e=>({color:(e.vars||e).palette.text.primary,...e.typography.body1,backgroundColor:(e.vars||e).palette.background.default,"@media print":{backgroundColor:(e.vars||e).palette.common.white}}),Me=(e,t=!1)=>{let n={};t&&e.colorSchemes&&typeof e.getColorSchemeSelector==`function`&&Object.entries(e.colorSchemes).forEach(([t,r])=>{let i=e.getColorSchemeSelector(t);i.startsWith(`@`)?n[i]={":root":{colorScheme:r.palette?.mode}}:n[i.replace(/\s*&/,``)]={colorScheme:r.palette?.mode}});let r={html:Ae(e,t),"*, *::before, *::after":{boxSizing:`inherit`},"strong, b":{fontWeight:e.typography.fontWeightBold},body:{margin:0,...je(e),"&::backdrop":{backgroundColor:(e.vars||e).palette.background.default}},...n},i=e.components?.MuiCssBaseline?.styleOverrides;return i&&(r=[r,i]),r},Ne=`mui-ecs`,Pe=e=>{let t=Me(e,!1),n=Array.isArray(t)?t[0]:t;return!e.vars&&n&&(n.html[`:root:has(${Ne})`]={colorScheme:e.palette.mode}),e.colorSchemes&&Object.entries(e.colorSchemes).forEach(([t,r])=>{let i=e.getColorSchemeSelector(t);i.startsWith(`@`)?n[i]={[`:root:not(:has(.${Ne}))`]:{colorScheme:r.palette?.mode}}:n[i.replace(/\s*&/,``)]={[`&:not(:has(.${Ne}))`]:{colorScheme:r.palette?.mode}}}),t},Fe=S(ke?({theme:e,enableColorScheme:t})=>Me(e,t):({theme:e})=>Pe(e));function Ie(e){let{children:t,enableColorScheme:n=!1}=y({props:e,name:`MuiCssBaseline`});return(0,E.jsxs)(C.Fragment,{children:[ke&&(0,E.jsx)(Fe,{enableColorScheme:n}),!ke&&!n&&(0,E.jsx)(`span`,{className:Ne,style:{display:`none`}}),t]})}function Le({theme:e,...t}){let n=`$$material`in e?e[x]:void 0;return(0,E.jsx)(he,{...t,themeId:n?x:void 0,theme:n||e})}var Re={attribute:`data-mui-color-scheme`,colorSchemeStorageKey:`mui-color-scheme`,defaultLightColorScheme:`light`,defaultDarkColorScheme:`dark`,modeStorageKey:`mui-mode`},{CssVarsProvider:ze,useColorScheme:Be,getInitColorSchemeScript:Ve}=Oe({themeId:x,theme:()=>b({cssVariables:!0}),colorSchemeStorageKey:Re.colorSchemeStorageKey,modeStorageKey:Re.modeStorageKey,defaultColorScheme:{light:Re.defaultLightColorScheme,dark:Re.defaultDarkColorScheme},resolveTheme:e=>{let t={...e,typography:g(e.palette,e.typography)};return t.unstable_sx=function(e){return _({sx:e,theme:this})},t}}),He=ze;function Ue({theme:e,...t}){let n=C.useMemo(()=>{if(typeof e==`function`)return e;let t=`$$material`in e?e[x]:e;return`colorSchemes`in t?null:`vars`in t?e:{...e,vars:null}},[e]);return n?(0,E.jsx)(Le,{theme:n,...t}):(0,E.jsx)(He,{theme:e,...t})}var We=ue(),Ge=class extends C.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}render(){let{locale:e,children:t}=this.props;return this.state.failed?(0,E.jsxs)(m,{sx:{p:3},children:[(0,E.jsx)(o,{severity:`error`,children:re(e,`Không tải được giao diện. Vui lòng tải lại để thử lại.`,`Could not load this view. Reload to try again.`)}),(0,E.jsx)(p,{onClick:()=>window.location.reload(),children:re(e,`Tải lại trang`,`Reload page`)})]}):(0,E.jsx)(C.Suspense,{fallback:(0,E.jsx)(m,{role:`status`,sx:{p:3},children:re(e,`Đang tải giao diện…`,`Loading view…`)}),children:t})}};function Ke(e){let t=e.mode===`dark`,n=e.mode,{primary:r,secondary:i,background:a,paper:o,text:s,muted:c,divider:l}=e,u=t?`0 16px 48px -12px ${f(`#000`,.7)}, 0 0 0 1px ${f(s,.06)}`:`0 16px 40px -16px ${f(`#1a1a2e`,.25)}, 0 0 0 1px ${f(s,.06)}`,d=`0 0 0 3px ${f(r,t?.28:.22)}`;return b({cssVariables:{cssVarPrefix:`piagent`},palette:{mode:n,primary:{main:r,contrastText:e.onPrimary},secondary:{main:i},success:{main:i},warning:{main:e.warning},error:{main:e.error},background:{default:a,paper:o},text:{primary:s,secondary:c,disabled:c},divider:l,action:{hover:f(s,.05),selected:f(s,.08),focus:f(r,.14)}},shape:{borderRadius:6},transitions:{duration:{shortest:120,shorter:160,short:180,standard:200,complex:260,enteringScreen:200,leavingScreen:160}},typography:{fontFamily:`system-ui, -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, sans-serif`,fontSize:14,fontWeightRegular:400,fontWeightMedium:500,fontWeightBold:600,h1:{fontSize:`1.6rem`,fontWeight:650,letterSpacing:`-0.03em`,lineHeight:1.2},h2:{fontSize:`1.15rem`,fontWeight:600,letterSpacing:`-0.02em`},h3:{fontSize:`0.95rem`,fontWeight:600},body2:{fontSize:`0.8125rem`},button:{fontSize:`0.8125rem`,fontWeight:550,textTransform:`none`,letterSpacing:0},caption:{fontSize:`0.72rem`,letterSpacing:0},overline:{fontSize:`0.68rem`,fontWeight:600,letterSpacing:`0.08em`}},components:{MuiCssBaseline:{styleOverrides:{html:{backgroundColor:a,WebkitFontSmoothing:`antialiased`},body:{minWidth:320,minHeight:`100vh`,backgroundColor:a},"::selection":{backgroundColor:f(r,.28)},"*":{scrollbarWidth:`thin`,scrollbarColor:`${f(s,.18)} transparent`}}},MuiPaper:{defaultProps:{elevation:0},styleOverrides:{root:{backgroundImage:`none`}}},MuiButtonBase:{defaultProps:{disableRipple:!0}},MuiButton:{defaultProps:{disableElevation:!0},styleOverrides:{root:{minHeight:32,borderRadius:8,paddingInline:12,transition:`background-color .16s, border-color .16s, box-shadow .16s, color .16s`,"&.Mui-focusVisible":{boxShadow:d}},sizeSmall:{minHeight:28,paddingInline:10,fontSize:`0.78rem`},outlined:{borderColor:f(s,.14),"&:hover":{borderColor:f(s,.28),backgroundColor:f(s,.04)}},contained:{"&.MuiButton-colorPrimary:hover":{backgroundColor:f(r,.88),boxShadow:`0 0 0 3px ${f(r,.18)}`}},text:{"&:hover":{backgroundColor:f(s,.06)}}}},MuiIconButton:{styleOverrides:{root:{borderRadius:8,color:c,transition:`background-color .16s, color .16s`,"&:hover":{color:s,backgroundColor:f(s,.07)},"&.Mui-focusVisible":{boxShadow:d}},sizeSmall:{padding:5}}},MuiChip:{styleOverrides:{root:{height:24,borderRadius:999,fontWeight:500,fontSize:`0.75rem`},outlined:{borderColor:f(s,.14)},label:{paddingInline:9}}},MuiListItemButton:{styleOverrides:{root:{minHeight:36,margin:`1px 8px`,borderRadius:8,color:c,transition:`background-color .12s, color .12s`,"&:hover":{backgroundColor:f(s,.05),color:s},"&.Mui-selected":{color:s,backgroundColor:f(s,t?.08:.07)},"&.Mui-selected:hover":{backgroundColor:f(s,t?.11:.09)},"&.Mui-focusVisible":{boxShadow:d}}}},MuiTabs:{styleOverrides:{root:{minHeight:40},indicator:{height:2,borderRadius:2}}},MuiTab:{styleOverrides:{root:{minHeight:40,paddingInline:14,textTransform:`none`,fontWeight:550,fontSize:`0.8125rem`,color:c,"&.Mui-selected":{color:s}}}},MuiOutlinedInput:{styleOverrides:{root:{borderRadius:8,backgroundColor:f(s,t?.03:.02),transition:`box-shadow .16s`,"& .MuiOutlinedInput-notchedOutline":{borderColor:f(s,.12)},"&:hover .MuiOutlinedInput-notchedOutline":{borderColor:f(s,.24)},"&.Mui-focused":{boxShadow:d},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:r,borderWidth:1}}}},MuiTooltip:{defaultProps:{arrow:!1,enterDelay:350},styleOverrides:{tooltip:{fontSize:`0.75rem`,fontWeight:500,padding:`5px 9px`,borderRadius:6,color:t?s:`#fafafa`,backgroundColor:t?f(o,.98):`#1f1f24`,boxShadow:u}}},MuiMenu:{styleOverrides:{paper:{borderRadius:10,boxShadow:u,backgroundImage:`none`,marginTop:4},list:{padding:4}}},MuiPopover:{styleOverrides:{paper:{borderRadius:10,boxShadow:u}}},MuiMenuItem:{styleOverrides:{root:{minHeight:32,borderRadius:6,fontSize:`0.8125rem`,"&:hover":{backgroundColor:f(s,.06)},"&.Mui-selected":{backgroundColor:f(r,.12)}}}},MuiDialog:{styleOverrides:{paper:{borderRadius:14,boxShadow:u,backgroundImage:`none`}}},MuiBackdrop:{styleOverrides:{root:{backgroundColor:f(`#000`,t?.6:.32),backdropFilter:`blur(2px)`}}},MuiDrawer:{styleOverrides:{paper:{backgroundImage:`none`,backgroundColor:o}}},MuiAlert:{styleOverrides:{root:{borderRadius:10,border:`1px solid ${f(s,.1)}`,fontSize:`0.8125rem`,alignItems:`center`}}},MuiDivider:{styleOverrides:{root:{borderColor:l}}},MuiLinearProgress:{styleOverrides:{root:{borderRadius:999,height:4},bar:{borderRadius:999}}}}})}function qe(e){for(let t of e??[]){let e=String(t).toLowerCase().split(`-`)[0];if(e===`vi`)return`vi`;if(e)return`en`}return`en`}var Je=`modulepreload`,Ye=function(e){return`/`+e},Xe={},Ze=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=Ye(t,n),t=s(t),t in Xe)return;Xe[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:Je,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Qe=document.getElementById(`root`);if(!Qe)throw Error(`Piagent WebUI root is missing`);var $e=document.querySelector(`meta[name="csp-nonce"]`)?.content,et=s({key:`piagent-mui`,nonce:$e&&!$e.startsWith(`__PIAGENT_`)?$e:void 0,prepend:!0}),tt=(0,C.lazy)(()=>Ze(()=>import(`./InspectionApp-CGgHsOyC.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]))),nt=(0,C.lazy)(()=>Ze(()=>import(`./GatewayApp-Dvo96qoX.js`),__vite__mapDeps([14,1,2,7,3,4,9,15,10,11,12,16,5,17])));function rt(e,t,n){try{let r=window.localStorage.getItem(e);return r&&t.includes(r)?r:n}catch{return n}}function it(){let[e,t]=(0,C.useState)(()=>rt(`piagent-webui-locale`,[`vi`,`en`],qe(window.navigator?.languages??[window.navigator?.language??``]))),[n,r]=(0,C.useState)(()=>rt(`piagent-webui-theme`,ie.map(e=>e.id),``)||ne[rt(`piagent-webui-color-mode`,[`light`,`dark`],window.matchMedia?.(`(prefers-color-scheme: light)`).matches?`light`:`dark`)]),i=ae(n)??ae(ne.dark),a=i.mode,o=(0,C.useCallback)(e=>r(t=>ae(t)?.mode===e?t:ne[e]),[]),s=(0,C.useMemo)(()=>Ke(i),[i]);(0,C.useEffect)(()=>{document.documentElement.lang=e,document.documentElement.dataset.piagentColorMode=a,document.documentElement.dataset.piagentTheme=i.id;try{window.localStorage.setItem(`piagent-webui-locale`,e),window.localStorage.setItem(`piagent-webui-color-mode`,a),window.localStorage.setItem(`piagent-webui-theme`,i.id)}catch{}},[a,e,i]);let c=(0,C.useMemo)(()=>({locale:e,colorMode:a,themeId:i.id,setLocale:t,setColorMode:o,setThemeId:r}),[a,e,i,o]),l=document.querySelector(`meta[name="piagent-webui-mode"]`)?.content;return(0,E.jsx)(oe,{value:c,children:(0,E.jsxs)(Ue,{theme:s,children:[(0,E.jsx)(Ie,{}),(0,E.jsx)(Ge,{locale:e,children:l===`gateway`?(0,E.jsx)(nt,{}):(0,E.jsx)(tt,{})})]})})}(0,We.createRoot)(Qe).render((0,E.jsx)(C.StrictMode,{children:(0,E.jsx)(u,{value:et,children:(0,E.jsx)(it,{})})}));export{Ge as n,Ze as t};
@@ -1,3 +1,3 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{An as t,Rn as n}from"./vendor-DNZbaWhT.js";import{i as r,n as i}from"./ui-preferences-OfS30-ZV.js";import{M as a,d as o,s}from"./api-BQS4Dtrr.js";import{r as c}from"./view-model-CWNiS4JN.js";import{i as l}from"./AttachmentImage-eZKqLYZ2.js";function u(e){return Array.isArray(e)?`[${e.map(u).join(`,`)}]`:e&&typeof e==`object`?`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${u(t)}`).join(`,`)}}`:JSON.stringify(e)}async function d(e){let t=new TextEncoder().encode(typeof e==`string`?e:u(e)),n=await crypto.subtle.digest(`SHA-256`,t);return`sha256:${[...new Uint8Array(n)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`}async function f(e,t,n,r){let i=new Date,a=new Date(i.getTime()+3e5),o=r?.attachmentRefs??[],s={messageRequestId:r?.messageRequestId??`message-request.${crypto.randomUUID()}`,capabilityAction:n===`steer`?`interruptAndSend`:n===`hold`?`hold`:`send`,delivery:n,text:t,attachmentRefs:o,contentDigest:await d({attachmentRefs:o,text:t})},c={runtimeRevision:e.revision.runtimeRevision,taskRevision:e.revision.taskRevision,controlRevision:e.revision.controlRevision,workspaceRevision:e.revision.workspaceRevision,indexRevision:e.revision.indexRevision,approvalRevision:e.revision.approvalRevision,sessionOptionRevision:e.revision.sessionOptionRevision,queueRevision:e.revision.queueRevision,workspacePreimage:null,indexPreimage:null,patchPreimage:null},l={schemaVersion:1,version:`piagent-webui-control-v1`,messageType:`command`,commandId:`command.${crypto.randomUUID()}`,idempotencyKey:crypto.randomUUID(),requestedAt:i.toISOString(),expiresAt:a.toISOString(),capabilityScope:`control.chat`,action:`chat.send`,actionDigest:``,identity:structuredClone(e.identity),expectedRevisions:c,payload:s};return l.actionDigest=await d({action:l.action,identity:l.identity,expectedRevisions:c,payload:s}),l}async function ee(e,t,n){let r=new Date,i=new Date(r.getTime()+3e5);return{schemaVersion:1,version:`piagent-webui-attachment-v1`,messageType:`stage-command`,commandId:`attachment-command.${crypto.randomUUID()}`,idempotencyKey:crypto.randomUUID(),requestedAt:r.toISOString(),expiresAt:i.toISOString(),identity:{...structuredClone(e.identity),toolCallId:null},expectedRuntimeRevision:e.revision.runtimeRevision,messageRequestId:t,file:n}}function p(e,t,n){let r=new Date,i=new Date(r.getTime()+3e5);return{schemaVersion:1,version:`piagent-webui-attachment-v1`,messageType:`discard-command`,commandId:`attachment-command.${crypto.randomUUID()}`,idempotencyKey:crypto.randomUUID(),requestedAt:r.toISOString(),expiresAt:i.toISOString(),identity:{...structuredClone(e.identity),toolCallId:null},expectedRuntimeRevision:e.revision.runtimeRevision,messageRequestId:t,attachmentRef:n}}async function m(e,t,n){let r=new Date,i=new Date(r.getTime()+3e5),a={runtimeRevision:e.revision.runtimeRevision,taskRevision:e.revision.taskRevision,controlRevision:e.revision.controlRevision,workspaceRevision:e.revision.workspaceRevision,indexRevision:e.revision.indexRevision,approvalRevision:e.revision.approvalRevision,sessionOptionRevision:e.revision.sessionOptionRevision,queueRevision:e.revision.queueRevision,workspacePreimage:null,indexPreimage:null,patchPreimage:null},o={schemaVersion:1,version:`piagent-webui-control-v1`,messageType:`command`,commandId:`command.${crypto.randomUUID()}`,idempotencyKey:crypto.randomUUID(),requestedAt:r.toISOString(),expiresAt:i.toISOString(),capabilityScope:`control.chat`,action:t,actionDigest:``,identity:structuredClone(e.identity),expectedRevisions:a,payload:n};return o.actionDigest=await d({action:t,identity:o.identity,expectedRevisions:a,payload:n}),o}async function h(e,t){let n=[];return{queueItemRef:e,text:t,attachmentRefs:n,contentDigest:await d({attachmentRefs:n,text:t})}}async function g(e,t,n){let r=new Date,i=new Date(r.getTime()+3e5),a={runtimeRevision:e.revision.runtimeRevision,taskRevision:e.revision.taskRevision,controlRevision:e.revision.controlRevision,workspaceRevision:e.revision.workspaceRevision,indexRevision:e.revision.indexRevision,approvalRevision:e.revision.approvalRevision,sessionOptionRevision:e.revision.sessionOptionRevision,queueRevision:e.revision.queueRevision,workspacePreimage:null,indexPreimage:null,patchPreimage:null},o=t===`session-options.set-model`?{modelRef:n,effectScopeAcknowledged:`session-and-user-default`}:{thinkingLevel:n,effectScopeAcknowledged:`session-and-user-default`},s={schemaVersion:1,version:`piagent-webui-control-v1`,messageType:`command`,commandId:`command.${crypto.randomUUID()}`,idempotencyKey:crypto.randomUUID(),requestedAt:r.toISOString(),expiresAt:i.toISOString(),capabilityScope:`control.sessionOptions`,action:t,actionDigest:``,identity:structuredClone(e.identity),expectedRevisions:a,payload:o};return s.actionDigest=await d({action:t,identity:s.identity,expectedRevisions:a,payload:o}),s}async function _(e,t){let n=new Date,r=new Date(n.getTime()+3e5),i={runtimeRevision:e.revision.runtimeRevision,taskRevision:e.revision.taskRevision,controlRevision:e.revision.controlRevision,workspaceRevision:e.revision.workspaceRevision,indexRevision:e.revision.indexRevision,approvalRevision:e.revision.approvalRevision,sessionOptionRevision:e.revision.sessionOptionRevision,queueRevision:e.revision.queueRevision,workspacePreimage:null,indexPreimage:null,patchPreimage:null},a=t===`lifecycle.stop`?{requestedScope:`current-agent-operation`}:t===`lifecycle.pause`?{safePointPolicy:`after-current-atomic-unit`}:{},o={schemaVersion:1,version:`piagent-webui-control-v1`,messageType:`command`,commandId:`command.${crypto.randomUUID()}`,idempotencyKey:crypto.randomUUID(),requestedAt:n.toISOString(),expiresAt:r.toISOString(),capabilityScope:`control.lifecycle`,action:t,actionDigest:``,identity:structuredClone(e.identity),expectedRevisions:i,payload:a};return o.actionDigest=await d({action:t,identity:o.identity,expectedRevisions:i,payload:a}),o}async function v(e,t,n){let r=new Date,i=new Date(r.getTime()+3e5),a=n?.attachmentRefs??[],o={messageRequestId:n?.messageRequestId??`message-request.${crypto.randomUUID()}`,capabilityAction:`send`,delivery:`new-operation`,text:t,attachmentRefs:a,contentDigest:await d({attachmentRefs:a,text:t})},s={runtimeRevision:e.revision.runtimeRevision,taskRevision:e.revision.taskRevision,controlRevision:e.revision.controlRevision,workspaceRevision:e.revision.workspaceRevision,indexRevision:e.revision.indexRevision,approvalRevision:e.revision.approvalRevision,sessionOptionRevision:e.revision.sessionOptionRevision,queueRevision:e.revision.queueRevision,workspacePreimage:null,indexPreimage:null,patchPreimage:null},c={schemaVersion:1,version:`piagent-webui-control-v1`,messageType:`command`,commandId:`command.${crypto.randomUUID()}`,idempotencyKey:crypto.randomUUID(),requestedAt:r.toISOString(),expiresAt:i.toISOString(),capabilityScope:`control.resumeAndContinue`,action:`lifecycle.resume-and-continue`,actionDigest:``,identity:structuredClone(e.identity),expectedRevisions:s,payload:o};return c.actionDigest=await d({action:c.action,identity:c.identity,expectedRevisions:s,payload:o}),c}function y(e,t,n){return e===`vi`?t:n}var b={txt:`text/plain`,text:`text/plain`,md:`text/markdown`,markdown:`text/markdown`,csv:`text/csv`,tsv:`text/tab-separated-values`,json:`application/json`,yaml:`application/yaml`,yml:`application/yaml`,pdf:`application/pdf`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,xlsx:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,xlsm:`application/vnd.ms-excel.sheet.macroenabled.12`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,odp:`application/vnd.oasis.opendocument.presentation`,rtf:`application/rtf`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,bmp:`image/bmp`},x={xls:`sheet`,numbers:`sheet`,ppt:`slides`,key:`slides`,doc:`word`,pages:`word`,...Object.fromEntries(`zip.gz.tgz.bz2.xz.rar.7z.tar.jar.war.exe.dmg.pkg.msi.deb.rpm.apk.ipa.bin.so.dylib.dll.o.a.lib.class.pyc.wasm.node.iso.img.sqlite.sqlite3.db.mdb.mp3.mp4.m4a.m4v.mov.avi.mkv.wav.flac.ogg.webm.aac.woff.woff2.ttf.otf.eot.ico.icns.heic.heif.tif.tiff.psd.ai.sketch.fig.xd.avif.raw.cr2.nef.dng.blend.fbx.glb`.split(`.`).map(e=>[e,`binary`]))};function S(e){let t=e.lastIndexOf(`.`),n=t>0||t===0&&e.length>1?e.slice(t+1).toLowerCase():``,r=b[n];if(r)return{mime:r};let i=x[n];return i?{refused:i}:{mime:`text/plain`}}var C=new Set([`application/pdf`,...Object.entries(b).filter(([e])=>[`docx`,`xlsx`,`xlsm`,`pptx`,`odt`,`ods`,`odp`,`rtf`].includes(e)).map(([,e])=>e)]);function w(e){return y(e,`Code, văn bản, .pdf .docx .xlsx .pptx .odt .ods .odp .rtf và ảnh`,`Code, text, .pdf .docx .xlsx .pptx .odt .ods .odp .rtf and images`)}function T(e){return e>=1048576?`${(e/1024/1024).toFixed(1)} MiB`:`${(e/1024).toFixed(+(e<10240))} KiB`}function E(e,t){let n=e.truncated?` · ${y(t,`đã cắt bớt`,`truncated`)}`:``;return e.kind===`image`?`${y(t,`Ảnh`,`Image`)} · ${T(e.sizeBytes)}`:e.kind===`document`?`${y(t,`Tài liệu`,`Document`)} · ${T(e.sourceBytes)} → ${T(e.sizeBytes)} ${y(t,`văn bản`,`text`)}${n}`:`File · ${T(e.sizeBytes)}${n}`}function te(e){return e.has(`text/plain`)?``:[...e,...Object.entries(b).filter(([,t])=>e.has(t)).map(([e])=>`.${e}`)].join(`,`)}function ne(e){return!!(e&&[...e.types].includes(`Files`))}function D(e,t){switch(e){case`sheet`:return y(t,`định dạng bảng tính này chưa đọc trực tiếp được; hãy lưu sang .xlsx hoặc .csv rồi đính kèm.`,`this spreadsheet format cannot be read directly; save it as .xlsx or .csv and attach that.`);case`slides`:return y(t,`định dạng trình chiếu này chưa đọc trực tiếp được; hãy lưu sang .pptx hoặc .pdf rồi đính kèm.`,`this slide format cannot be read directly; save it as .pptx or .pdf and attach that.`);case`word`:return y(t,`định dạng này chưa đọc được; hãy lưu sang .docx, .pdf, .rtf hoặc .txt.`,`this format cannot be read; save it as .docx, .pdf, .rtf or .txt.`);default:return y(t,`file nhị phân không gửi vào chat được; hãy để file trong project để agent tự đọc bằng tool.`,`binary files cannot go into the chat; keep it in the project and the agent can use its tools on it.`)}}async function re(e){let{snapshot:t,locale:n}=e,r=[...e.existing],i=null,a=Math.max(0,4-r.length);e.files.length>a&&(i=y(n,`Chỉ nhận tối đa 4 file mỗi tin nhắn; đã bỏ qua ${e.files.length-a} file.`,`At most 4 files per message; ${e.files.length-a} skipped.`));for(let o of[...e.files].slice(0,a)){let a=S(o.name);if(`refused`in a){i=`${o.name}: ${D(a.refused,n)}`;continue}let s=a.mime;if(!e.allowed.has(s)){i=`${o.name}: ${s===`application/pdf`?y(n,`host chưa cài pdftotext (poppler) nên chưa đọc được .pdf.`,`this host has no pdftotext (poppler), so .pdf cannot be read.`):y(n,`phiên Pi hiện tại không nhận loại file này.`,`the current Pi session does not accept this file type.`)}`;continue}let u=s.startsWith(`image/`)||C.has(s)?Math.min(t.capabilities.limits.maxAttachmentFileBytes,8388608):262144;if(o.size<1||o.size>u||r.reduce((e,t)=>e+t.sourceBytes,0)+o.size>t.capabilities.limits.maxAttachmentTotalBytes){i=`${o.name}: ${C.has(s)?y(n,`vượt giới hạn gửi trực tiếp ${T(u)}. Hãy đặt tài liệu lớn trong project rồi mở ở mục Tài liệu; Pi sẽ đọc theo phần thay vì nhét cả file vào chat.`,`exceeds the ${T(u)} direct-send limit. Put a large document in the project and open Documents; Pi can read it in parts instead of placing the whole file in chat.`):y(n,`vượt giới hạn đính kèm (tối đa ${T(u)}).`,`attachment limit exceeded (max ${T(u)}).`)}`;continue}let d=new Uint8Array(await o.arrayBuffer()),f=``;for(let e=0;e<d.length;e+=32768)f+=String.fromCharCode(...d.subarray(e,e+32768));let p=btoa(f),m=await e.stage(await ee(t,e.messageRequestId,{displayName:o.name,declaredMimeType:s,dataBase64:p}));if(m.resultCode!==`staged`||!(`attachment`in m)||!m.attachment){i=`${o.name}: ${c(m.error?.code??m.resultCode,n)}`;continue}m.attachment.kind===`image`&&l(m.attachment.attachmentRef,m.attachment.mimeType,p),r=[...r,m.attachment]}return{attachments:r,status:i}}async function ie(e){let t=await e.stage(p(e.snapshot,e.messageRequestId,e.attachmentRef));return t.messageType===`discard-receipt`&&t.resultCode===`discarded`?{discarded:!0,status:null}:{discarded:!1,status:`${y(e.locale,`Chưa thể bỏ file`,`Unable to remove file`)} · ${c(t.error?.code??t.resultCode,e.locale)}`}}var O=e(n(),1),k=(e,t,n)=>e===`vi`?t:n,A={"workspace-patch":[`Sửa trong project`,`Change in the project`],"external-provider-action":[`Tác động ra bên ngoài`,`Reaches outside this machine`]},j={"one-shell-command":[`Đúng một lệnh`,`This one command`],"network-command-once":[`Đúng một lệnh, có mạng`,`This one command, with network`],"docker-command-once":[`Đúng một lệnh, có mạng và Docker`,`This one command, with network and Docker`],"host-command-once":[`Đúng một lệnh, chạy trên máy bạn (ngoài sandbox)`,`This one command, on your machine (outside the sandbox)`],"start-docker-once":[`Mở Docker trên máy`,`Start Docker on this machine`],"one-external-action":[`Đúng một hành động`,`This one action`],"one-handoff":[`Đúng một bước bàn giao ra ngoài`,`This one handoff`],"handoff-once":[`Đúng một bước bàn giao ra ngoài`,`This one handoff`],"mcp-handoff-once":[`Đúng một lệnh gọi MCP ghi ra ngoài`,`This one MCP call that writes outside`],"checks-waiver-once":[`Bỏ qua kiểm tra cho đúng code hiện tại`,`Skip the checks for the code as it is now`]},M={"Run this exact command once, after the guard checks the working tree again.":[`Chạy đúng lệnh này một lần, sau khi guard kiểm tra lại thư mục làm việc.`,``],"The command does not run; the agent is told you declined.":[`Lệnh không chạy; agent được báo là bạn đã từ chối.`,``],"Run this exact action once, after the guard checks its authority again.":[`Thực hiện đúng hành động này một lần, sau khi guard kiểm tra lại quyền.`,``],"The action does not run; nothing outside changes.":[`Hành động không chạy; không có gì bên ngoài bị thay đổi.`,``],"Run this exact command once, with internet access.":[`Chạy đúng lệnh này một lần, có mạng.`,``],"Run this exact command once, with internet access; a server it starts accepts connections while it runs.":[`Chạy đúng lệnh này một lần, có mạng; server mà lệnh mở nhận kết nối trong lúc chạy.`,``],"Run this exact command once, with internet access and the Docker engine; a container it starts can read folders Docker shares from this machine and may keep running.":[`Chạy đúng lệnh này một lần, có mạng và Docker; container mà lệnh tạo đọc được các thư mục Docker chia sẻ trên máy và có thể tiếp tục chạy.`,``],"Run this exact command once on this machine, outside the sandbox, as you: it can read and change your files and use your sign-ins.":[`Chạy đúng lệnh này một lần trên máy bạn, ngoài sandbox, bằng quyền của bạn: lệnh đọc/sửa được file và dùng được tài khoản đã đăng nhập trên máy.`,``],"Docker is not started; the agent is told you declined.":[`Không mở Docker; agent được báo là bạn đã từ chối.`,``]},N=(e,t,n)=>{let r=e[t];return r?k(n,r[0],r[1]||t):null};function P(e,t){return t===`vi`?e.split(`; `).map(e=>{let t=e.match(/^Confirmation required: the command runs (.+)$/);if(t)return`Lệnh có ${t[1]} nên cần bạn duyệt trước khi chạy.`;let n=e.match(/^External provider action (.+) requires confirmation$/);return n?`Hành động ra bên ngoài (${n[1]}) cần bạn duyệt.`:e}).join(` `):e}var F=(e,t)=>N(A,e.kind,t)??c(e.kind,t),I=(e,t)=>N(j,e.requestedScope,t)??c(e.requestedScope,t);function L(e,t){let n=t===`vi`?/^Start (.+) on this machine; it keeps running after the conversation\.$/.exec(e):null;return n?`Mở ${n[1]} trên máy; nó vẫn chạy sau cuộc trò chuyện.`:N(M,e,t)??e}var R=e=>!/handoff|waiver/.test(String(e.action.requestedScope));function z(e,t){let n=t===`allow`||t===`session`?`allow`:`deny`;return{schemaVersion:1,version:`piagent-webui-approval-v1`,recordType:`decision`,approvalRef:e.approvalRef,decisionId:`decision.${crypto.randomUUID()}`,decisionToken:e.decisionToken,identity:structuredClone(e.identity),actionDigest:e.action.actionDigest,expectedRevisions:structuredClone(e.expectedRevisions),decision:n,reason:null,decidedAt:new Date().toISOString(),expiresAt:e.expiresAt,decisionSurface:`webui`,executor:`pi-guard`,directExecution:!1,...t===`session`?{scope:`session`}:t===`stop`?{stop:!0}:{}}}var B=t();function V({state:e,setState:t,refreshSnapshot:n,locale:r,asker:a}){let o=e.request;if(!o)return(0,B.jsx)(`article`,{className:`approval-card`,children:(0,B.jsx)(`p`,{children:e.error??i(r,`Đang tải yêu cầu phê duyệt…`,`Loading approval request…`)})});let l=o.action,u=Math.max(0,Math.ceil((Date.parse(o.expiresAt)-Date.now())/1e3)),d=async e=>{t({request:o,deciding:e});try{await s(z(o,e)),await n?.()}catch{t({request:o,error:i(r,`Yêu cầu đã hết hạn, thay đổi hoặc được trả lời ở terminal. Hãy tải trạng thái mới.`,`The request expired, changed, or was answered in the terminal. Refresh status.`)})}};return(0,B.jsxs)(`article`,{className:`approval-card risk-${l.riskClass}`,"aria-labelledby":`approval-${o.approvalRef}`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`p`,{className:`section-kicker`,children:a?i(r,`${a} cần bạn duyệt`,`${a} needs your approval`):i(r,`Cần phê duyệt`,`Approval required`)}),(0,B.jsx)(`h2`,{id:`approval-${o.approvalRef}`,children:l.toolName})]}),(0,B.jsx)(`span`,{className:`approval-risk`,children:c(l.riskClass,r)})]}),(0,B.jsx)(`p`,{className:`approval-reason`,children:P(l.reason,r)}),l.commandPreview&&(0,B.jsx)(`pre`,{className:`approval-preview`,children:(0,B.jsx)(`code`,{children:l.commandPreview})}),!l.commandPreview&&l.parameterPreview&&l.parameterPreview!==`No additional parameters`&&(0,B.jsx)(`p`,{className:`approval-preview`,children:l.parameterPreview}),(0,B.jsxs)(`dl`,{className:`approval-facts`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:i(r,`Hành động`,`Action`)}),(0,B.jsx)(`dd`,{children:F(l,r)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:i(r,`Phạm vi`,`Scope`)}),(0,B.jsx)(`dd`,{children:I(l,r)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:i(r,`Thư mục`,`Directory`)}),(0,B.jsx)(`dd`,{children:l.cwdDisplay??i(r,`Đã ẩn`,`Hidden`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:i(r,`Hết hạn`,`Expires`)}),(0,B.jsxs)(`dd`,{children:[u,`s`]})]})]}),l.targetPaths.length>0&&(0,B.jsxs)(`div`,{className:`approval-targets`,children:[(0,B.jsx)(`strong`,{children:i(r,`Đích tác động`,`Targets`)}),(0,B.jsx)(`ul`,{children:l.targetPaths.map(e=>(0,B.jsx)(`li`,{children:e===`.`?i(r,`Cả thư mục project`,`The whole project folder`):e},e))})]}),(0,B.jsxs)(`div`,{className:`approval-consequences`,children:[(0,B.jsxs)(`p`,{children:[(0,B.jsx)(`strong`,{children:i(r,`Nếu cho phép:`,`If allowed:`)}),` `,L(l.consequences.allow,r)]}),(0,B.jsxs)(`p`,{children:[(0,B.jsx)(`strong`,{children:i(r,`Nếu từ chối:`,`If denied:`)}),` `,L(l.consequences.deny,r)]})]}),e.error&&(0,B.jsx)(`p`,{className:`form-error`,role:`alert`,children:e.error}),(0,B.jsxs)(`footer`,{children:[(0,B.jsx)(`button`,{type:`button`,className:`secondary-action`,disabled:!!e.deciding,title:i(r,`Từ chối và kết thúc lượt này, agent không thử lại`,`Deny and end this turn so the agent does not retry`),onClick:()=>void d(`stop`),children:i(r,`Từ chối và dừng`,`Deny and stop`)}),(0,B.jsx)(`button`,{type:`button`,className:`secondary-action`,disabled:!!e.deciding,onClick:()=>void d(`deny`),children:i(r,`Từ chối`,`Deny`)}),R(o)&&(0,B.jsx)(`button`,{type:`button`,className:`secondary-action`,disabled:!!e.deciding,title:i(r,`Lệnh giống hệt sẽ chạy không hỏi lại cho tới hết session`,`The same exact command runs without asking until the session ends`),onClick:()=>void d(`session`),children:i(r,`Cho cả session`,`Allow for session`)}),(0,B.jsx)(`button`,{type:`button`,className:`danger-action`,disabled:!!e.deciding,onClick:()=>void d(`allow`),children:e.deciding===`allow`||e.deciding===`session`?i(r,`Đang kiểm tra lại…`,`Rechecking…`):i(r,`Cho phép đúng 1 lần`,`Allow once`)})]})]})}function H(e,t,n){let r=(0,O.useMemo)(()=>e,[e.join(`\0`)]),[s,c]=(0,O.useState)({});return(0,O.useEffect)(()=>{let e=new AbortController;for(let s of r)(t?a(t,s,e.signal):o(s,e.signal)).then(e=>c(t=>({...t,[s]:{request:e}})),()=>c(e=>({...e,[s]:{error:i(n,`Không thể tải yêu cầu phê duyệt hiện tại.`,`Unable to load the current approval request.`)}})));return()=>e.abort()},[n,t,r]),{refs:r,states:s,set:(e,t)=>c(n=>({...n,[e]:t}))}}function U({approvalRefs:e,sessionRef:t,refreshSnapshot:n}){let{locale:a}=r(),{refs:o,states:s,set:c}=H(e,t,a);return o.length===0?null:(0,B.jsx)(`section`,{className:`approval-stack`,"aria-label":i(a,`Yêu cầu phê duyệt đang chờ`,`Pending approval requests`),"aria-live":`polite`,children:o.map(e=>(0,B.jsx)(V,{state:s[e]??{},setState:t=>c(e,t),refreshSnapshot:n,locale:a},e))})}function ae({snapshot:e,refreshSnapshot:t}){let n=(0,O.useMemo)(()=>e.approvals.pending.map(e=>e.approvalRef),[e.approvals.pending]);return(0,B.jsx)(U,{approvalRefs:n,refreshSnapshot:t})}var W=16384,G=1e3;function K(e,t){let n=new Map;for(let r of[...t,...e])n.has(r.messageRef)||n.set(r.messageRef,r);return[...n.values()].slice(0,G)}function q(e){let t=new Map,n=new Map;for(let r of e.slice(-500)){let e=r.kind,i=r.payload??{},a=r.messageRef;if([`agent-operation.settled`,`session.replacement-pending`,`session.replacement-committed`,`session.shutdown`].includes(String(e))){t.clear(),n.clear();continue}if(e===`message.started`&&i.role===`assistant`&&typeof a==`string`)t.set(a,{messageRef:a,text:``,thinking:!1,truncated:!1});else if(e===`message.text-delta`&&typeof a==`string`&&typeof i.delta==`string`){let e=t.get(a);if(!e)continue;let n=`${e.text}${i.delta}`;t.set(a,{...e,text:n.slice(0,W),truncated:e.truncated||n.length>W})}else if(e===`message.thinking-state`&&typeof a==`string`){let e=t.get(a);if(!e)continue;t.set(a,{...e,thinking:i.state!==`completed`})}else[`message.completed`,`message.failed`].includes(String(e))&&typeof a==`string`&&t.delete(a);[`activity.started`,`activity.progress`,`activity.finished`,`activity.failed`,`activity.blocked`,`activity.aborted`].includes(String(e))&&typeof r.toolCallId==`string`&&typeof i.activityRef==`string`&&typeof i.toolName==`string`&&n.set(r.toolCallId,{toolCallId:r.toolCallId,activityRef:i.activityRef,toolName:i.toolName,state:String(i.state??`unknown`)})}return{assistants:[...t.values()].slice(-2),tools:[...n.values()].slice(-8)}}var J=/^(?:\p{White_Space}|\p{Cc}|\p{Default_Ignorable_Code_Point})$/u,oe=/\u001b(?:\[[0-?]*[ -/]*[@-~]|[@-_])/g;function se(e){for(let t of e.replace(oe,``))if(!J.test(t))return!0;return!1}function ce(e,t,n){if(!n?.complete)return{key:`${e}:${t}:active`,completionKey:null,user:``,assistant:``,operationRef:null,messageRequestId:null,startedAt:null};let r=n.startedAt??null,i=n.messageRequestId??null,a=`${i??`unknown`}:${n.operationRef??`unknown`}:${r??`unknown`}:${n.user}:${n.assistant.length}`;return{key:`${e}:${t}:complete:${a}`,completionKey:a,user:n.user,assistant:n.assistant,operationRef:n.operationRef,messageRequestId:i,startedAt:r}}function le(e){let t=/^\[Piagent completion gate: (CONTINUING|NOT APPROVED)\][\t ]*/i.exec(e);if(!t)return{text:e,completionGate:null};let n=t[1]?.toUpperCase()===`CONTINUING`?`continuing`:`not-approved`,r=e.indexOf(`
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{An as t,Rn as n}from"./vendor-DNZbaWhT.js";import{i as r,n as i}from"./ui-preferences-OfS30-ZV.js";import{M as a,d as o,s}from"./api-BQS4Dtrr.js";import{a as c}from"./view-model-BrdSO09E.js";import{i as l}from"./AttachmentImage-eZKqLYZ2.js";function u(e){return Array.isArray(e)?`[${e.map(u).join(`,`)}]`:e&&typeof e==`object`?`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${u(t)}`).join(`,`)}}`:JSON.stringify(e)}async function d(e){let t=new TextEncoder().encode(typeof e==`string`?e:u(e)),n=await crypto.subtle.digest(`SHA-256`,t);return`sha256:${[...new Uint8Array(n)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`}async function f(e,t,n,r){let i=new Date,a=new Date(i.getTime()+3e5),o=r?.attachmentRefs??[],s={messageRequestId:r?.messageRequestId??`message-request.${crypto.randomUUID()}`,capabilityAction:n===`steer`?`interruptAndSend`:n===`hold`?`hold`:`send`,delivery:n,text:t,attachmentRefs:o,contentDigest:await d({attachmentRefs:o,text:t})},c={runtimeRevision:e.revision.runtimeRevision,taskRevision:e.revision.taskRevision,controlRevision:e.revision.controlRevision,workspaceRevision:e.revision.workspaceRevision,indexRevision:e.revision.indexRevision,approvalRevision:e.revision.approvalRevision,sessionOptionRevision:e.revision.sessionOptionRevision,queueRevision:e.revision.queueRevision,workspacePreimage:null,indexPreimage:null,patchPreimage:null},l={schemaVersion:1,version:`piagent-webui-control-v1`,messageType:`command`,commandId:`command.${crypto.randomUUID()}`,idempotencyKey:crypto.randomUUID(),requestedAt:i.toISOString(),expiresAt:a.toISOString(),capabilityScope:`control.chat`,action:`chat.send`,actionDigest:``,identity:structuredClone(e.identity),expectedRevisions:c,payload:s};return l.actionDigest=await d({action:l.action,identity:l.identity,expectedRevisions:c,payload:s}),l}async function ee(e,t,n){let r=new Date,i=new Date(r.getTime()+3e5);return{schemaVersion:1,version:`piagent-webui-attachment-v1`,messageType:`stage-command`,commandId:`attachment-command.${crypto.randomUUID()}`,idempotencyKey:crypto.randomUUID(),requestedAt:r.toISOString(),expiresAt:i.toISOString(),identity:{...structuredClone(e.identity),toolCallId:null},expectedRuntimeRevision:e.revision.runtimeRevision,messageRequestId:t,file:n}}function p(e,t,n){let r=new Date,i=new Date(r.getTime()+3e5);return{schemaVersion:1,version:`piagent-webui-attachment-v1`,messageType:`discard-command`,commandId:`attachment-command.${crypto.randomUUID()}`,idempotencyKey:crypto.randomUUID(),requestedAt:r.toISOString(),expiresAt:i.toISOString(),identity:{...structuredClone(e.identity),toolCallId:null},expectedRuntimeRevision:e.revision.runtimeRevision,messageRequestId:t,attachmentRef:n}}async function m(e,t,n){let r=new Date,i=new Date(r.getTime()+3e5),a={runtimeRevision:e.revision.runtimeRevision,taskRevision:e.revision.taskRevision,controlRevision:e.revision.controlRevision,workspaceRevision:e.revision.workspaceRevision,indexRevision:e.revision.indexRevision,approvalRevision:e.revision.approvalRevision,sessionOptionRevision:e.revision.sessionOptionRevision,queueRevision:e.revision.queueRevision,workspacePreimage:null,indexPreimage:null,patchPreimage:null},o={schemaVersion:1,version:`piagent-webui-control-v1`,messageType:`command`,commandId:`command.${crypto.randomUUID()}`,idempotencyKey:crypto.randomUUID(),requestedAt:r.toISOString(),expiresAt:i.toISOString(),capabilityScope:`control.chat`,action:t,actionDigest:``,identity:structuredClone(e.identity),expectedRevisions:a,payload:n};return o.actionDigest=await d({action:t,identity:o.identity,expectedRevisions:a,payload:n}),o}async function h(e,t){let n=[];return{queueItemRef:e,text:t,attachmentRefs:n,contentDigest:await d({attachmentRefs:n,text:t})}}async function g(e,t,n){let r=new Date,i=new Date(r.getTime()+3e5),a={runtimeRevision:e.revision.runtimeRevision,taskRevision:e.revision.taskRevision,controlRevision:e.revision.controlRevision,workspaceRevision:e.revision.workspaceRevision,indexRevision:e.revision.indexRevision,approvalRevision:e.revision.approvalRevision,sessionOptionRevision:e.revision.sessionOptionRevision,queueRevision:e.revision.queueRevision,workspacePreimage:null,indexPreimage:null,patchPreimage:null},o=t===`session-options.set-model`?{modelRef:n,effectScopeAcknowledged:`session-and-user-default`}:{thinkingLevel:n,effectScopeAcknowledged:`session-and-user-default`},s={schemaVersion:1,version:`piagent-webui-control-v1`,messageType:`command`,commandId:`command.${crypto.randomUUID()}`,idempotencyKey:crypto.randomUUID(),requestedAt:r.toISOString(),expiresAt:i.toISOString(),capabilityScope:`control.sessionOptions`,action:t,actionDigest:``,identity:structuredClone(e.identity),expectedRevisions:a,payload:o};return s.actionDigest=await d({action:t,identity:s.identity,expectedRevisions:a,payload:o}),s}async function _(e,t){let n=new Date,r=new Date(n.getTime()+3e5),i={runtimeRevision:e.revision.runtimeRevision,taskRevision:e.revision.taskRevision,controlRevision:e.revision.controlRevision,workspaceRevision:e.revision.workspaceRevision,indexRevision:e.revision.indexRevision,approvalRevision:e.revision.approvalRevision,sessionOptionRevision:e.revision.sessionOptionRevision,queueRevision:e.revision.queueRevision,workspacePreimage:null,indexPreimage:null,patchPreimage:null},a=t===`lifecycle.stop`?{requestedScope:`current-agent-operation`}:t===`lifecycle.pause`?{safePointPolicy:`after-current-atomic-unit`}:{},o={schemaVersion:1,version:`piagent-webui-control-v1`,messageType:`command`,commandId:`command.${crypto.randomUUID()}`,idempotencyKey:crypto.randomUUID(),requestedAt:n.toISOString(),expiresAt:r.toISOString(),capabilityScope:`control.lifecycle`,action:t,actionDigest:``,identity:structuredClone(e.identity),expectedRevisions:i,payload:a};return o.actionDigest=await d({action:t,identity:o.identity,expectedRevisions:i,payload:a}),o}async function v(e,t,n){let r=new Date,i=new Date(r.getTime()+3e5),a=n?.attachmentRefs??[],o={messageRequestId:n?.messageRequestId??`message-request.${crypto.randomUUID()}`,capabilityAction:`send`,delivery:`new-operation`,text:t,attachmentRefs:a,contentDigest:await d({attachmentRefs:a,text:t})},s={runtimeRevision:e.revision.runtimeRevision,taskRevision:e.revision.taskRevision,controlRevision:e.revision.controlRevision,workspaceRevision:e.revision.workspaceRevision,indexRevision:e.revision.indexRevision,approvalRevision:e.revision.approvalRevision,sessionOptionRevision:e.revision.sessionOptionRevision,queueRevision:e.revision.queueRevision,workspacePreimage:null,indexPreimage:null,patchPreimage:null},c={schemaVersion:1,version:`piagent-webui-control-v1`,messageType:`command`,commandId:`command.${crypto.randomUUID()}`,idempotencyKey:crypto.randomUUID(),requestedAt:r.toISOString(),expiresAt:i.toISOString(),capabilityScope:`control.resumeAndContinue`,action:`lifecycle.resume-and-continue`,actionDigest:``,identity:structuredClone(e.identity),expectedRevisions:s,payload:o};return c.actionDigest=await d({action:c.action,identity:c.identity,expectedRevisions:s,payload:o}),c}function y(e,t,n){return e===`vi`?t:n}var b={txt:`text/plain`,text:`text/plain`,md:`text/markdown`,markdown:`text/markdown`,csv:`text/csv`,tsv:`text/tab-separated-values`,json:`application/json`,yaml:`application/yaml`,yml:`application/yaml`,pdf:`application/pdf`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,xlsx:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,xlsm:`application/vnd.ms-excel.sheet.macroenabled.12`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,odp:`application/vnd.oasis.opendocument.presentation`,rtf:`application/rtf`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,bmp:`image/bmp`},x={xls:`sheet`,numbers:`sheet`,ppt:`slides`,key:`slides`,doc:`word`,pages:`word`,...Object.fromEntries(`zip.gz.tgz.bz2.xz.rar.7z.tar.jar.war.exe.dmg.pkg.msi.deb.rpm.apk.ipa.bin.so.dylib.dll.o.a.lib.class.pyc.wasm.node.iso.img.sqlite.sqlite3.db.mdb.mp3.mp4.m4a.m4v.mov.avi.mkv.wav.flac.ogg.webm.aac.woff.woff2.ttf.otf.eot.ico.icns.heic.heif.tif.tiff.psd.ai.sketch.fig.xd.avif.raw.cr2.nef.dng.blend.fbx.glb`.split(`.`).map(e=>[e,`binary`]))};function S(e){let t=e.lastIndexOf(`.`),n=t>0||t===0&&e.length>1?e.slice(t+1).toLowerCase():``,r=b[n];if(r)return{mime:r};let i=x[n];return i?{refused:i}:{mime:`text/plain`}}var C=new Set([`application/pdf`,...Object.entries(b).filter(([e])=>[`docx`,`xlsx`,`xlsm`,`pptx`,`odt`,`ods`,`odp`,`rtf`].includes(e)).map(([,e])=>e)]);function w(e){return y(e,`Code, văn bản, .pdf .docx .xlsx .pptx .odt .ods .odp .rtf và ảnh`,`Code, text, .pdf .docx .xlsx .pptx .odt .ods .odp .rtf and images`)}function T(e){return e>=1048576?`${(e/1024/1024).toFixed(1)} MiB`:`${(e/1024).toFixed(+(e<10240))} KiB`}function E(e,t){let n=e.truncated?` · ${y(t,`đã cắt bớt`,`truncated`)}`:``;return e.kind===`image`?`${y(t,`Ảnh`,`Image`)} · ${T(e.sizeBytes)}`:e.kind===`document`?`${y(t,`Tài liệu`,`Document`)} · ${T(e.sourceBytes)} → ${T(e.sizeBytes)} ${y(t,`văn bản`,`text`)}${n}`:`File · ${T(e.sizeBytes)}${n}`}function te(e){return e.has(`text/plain`)?``:[...e,...Object.entries(b).filter(([,t])=>e.has(t)).map(([e])=>`.${e}`)].join(`,`)}function ne(e){return!!(e&&[...e.types].includes(`Files`))}function D(e,t){switch(e){case`sheet`:return y(t,`định dạng bảng tính này chưa đọc trực tiếp được; hãy lưu sang .xlsx hoặc .csv rồi đính kèm.`,`this spreadsheet format cannot be read directly; save it as .xlsx or .csv and attach that.`);case`slides`:return y(t,`định dạng trình chiếu này chưa đọc trực tiếp được; hãy lưu sang .pptx hoặc .pdf rồi đính kèm.`,`this slide format cannot be read directly; save it as .pptx or .pdf and attach that.`);case`word`:return y(t,`định dạng này chưa đọc được; hãy lưu sang .docx, .pdf, .rtf hoặc .txt.`,`this format cannot be read; save it as .docx, .pdf, .rtf or .txt.`);default:return y(t,`file nhị phân không gửi vào chat được; hãy để file trong project để agent tự đọc bằng tool.`,`binary files cannot go into the chat; keep it in the project and the agent can use its tools on it.`)}}async function re(e){let{snapshot:t,locale:n}=e,r=[...e.existing],i=null,a=Math.max(0,4-r.length);e.files.length>a&&(i=y(n,`Chỉ nhận tối đa 4 file mỗi tin nhắn; đã bỏ qua ${e.files.length-a} file.`,`At most 4 files per message; ${e.files.length-a} skipped.`));for(let o of[...e.files].slice(0,a)){let a=S(o.name);if(`refused`in a){i=`${o.name}: ${D(a.refused,n)}`;continue}let s=a.mime;if(!e.allowed.has(s)){i=`${o.name}: ${s===`application/pdf`?y(n,`host chưa cài pdftotext (poppler) nên chưa đọc được .pdf.`,`this host has no pdftotext (poppler), so .pdf cannot be read.`):y(n,`phiên Pi hiện tại không nhận loại file này.`,`the current Pi session does not accept this file type.`)}`;continue}let u=s.startsWith(`image/`)||C.has(s)?Math.min(t.capabilities.limits.maxAttachmentFileBytes,8388608):262144;if(o.size<1||o.size>u||r.reduce((e,t)=>e+t.sourceBytes,0)+o.size>t.capabilities.limits.maxAttachmentTotalBytes){i=`${o.name}: ${C.has(s)?y(n,`vượt giới hạn gửi trực tiếp ${T(u)}. Hãy đặt tài liệu lớn trong project rồi mở ở mục Tài liệu; Pi sẽ đọc theo phần thay vì nhét cả file vào chat.`,`exceeds the ${T(u)} direct-send limit. Put a large document in the project and open Documents; Pi can read it in parts instead of placing the whole file in chat.`):y(n,`vượt giới hạn đính kèm (tối đa ${T(u)}).`,`attachment limit exceeded (max ${T(u)}).`)}`;continue}let d=new Uint8Array(await o.arrayBuffer()),f=``;for(let e=0;e<d.length;e+=32768)f+=String.fromCharCode(...d.subarray(e,e+32768));let p=btoa(f),m=await e.stage(await ee(t,e.messageRequestId,{displayName:o.name,declaredMimeType:s,dataBase64:p}));if(m.resultCode!==`staged`||!(`attachment`in m)||!m.attachment){i=`${o.name}: ${c(m.error?.code??m.resultCode,n)}`;continue}m.attachment.kind===`image`&&l(m.attachment.attachmentRef,m.attachment.mimeType,p),r=[...r,m.attachment]}return{attachments:r,status:i}}async function ie(e){let t=await e.stage(p(e.snapshot,e.messageRequestId,e.attachmentRef));return t.messageType===`discard-receipt`&&t.resultCode===`discarded`?{discarded:!0,status:null}:{discarded:!1,status:`${y(e.locale,`Chưa thể bỏ file`,`Unable to remove file`)} · ${c(t.error?.code??t.resultCode,e.locale)}`}}var O=e(n(),1),k=(e,t,n)=>e===`vi`?t:n,A={"workspace-patch":[`Sửa trong project`,`Change in the project`],"external-provider-action":[`Tác động ra bên ngoài`,`Reaches outside this machine`]},j={"one-shell-command":[`Đúng một lệnh`,`This one command`],"network-command-once":[`Đúng một lệnh, có mạng`,`This one command, with network`],"docker-command-once":[`Đúng một lệnh, có mạng và Docker`,`This one command, with network and Docker`],"host-command-once":[`Đúng một lệnh, chạy trên máy bạn (ngoài sandbox)`,`This one command, on your machine (outside the sandbox)`],"start-docker-once":[`Mở Docker trên máy`,`Start Docker on this machine`],"one-external-action":[`Đúng một hành động`,`This one action`],"one-handoff":[`Đúng một bước bàn giao ra ngoài`,`This one handoff`],"handoff-once":[`Đúng một bước bàn giao ra ngoài`,`This one handoff`],"mcp-handoff-once":[`Đúng một lệnh gọi MCP ghi ra ngoài`,`This one MCP call that writes outside`],"checks-waiver-once":[`Bỏ qua kiểm tra cho đúng code hiện tại`,`Skip the checks for the code as it is now`]},M={"Run this exact command once, after the guard checks the working tree again.":[`Chạy đúng lệnh này một lần, sau khi guard kiểm tra lại thư mục làm việc.`,``],"The command does not run; the agent is told you declined.":[`Lệnh không chạy; agent được báo là bạn đã từ chối.`,``],"Run this exact action once, after the guard checks its authority again.":[`Thực hiện đúng hành động này một lần, sau khi guard kiểm tra lại quyền.`,``],"The action does not run; nothing outside changes.":[`Hành động không chạy; không có gì bên ngoài bị thay đổi.`,``],"Run this exact command once, with internet access.":[`Chạy đúng lệnh này một lần, có mạng.`,``],"Run this exact command once, with internet access; a server it starts accepts connections while it runs.":[`Chạy đúng lệnh này một lần, có mạng; server mà lệnh mở nhận kết nối trong lúc chạy.`,``],"Run this exact command once, with internet access and the Docker engine; a container it starts can read folders Docker shares from this machine and may keep running.":[`Chạy đúng lệnh này một lần, có mạng và Docker; container mà lệnh tạo đọc được các thư mục Docker chia sẻ trên máy và có thể tiếp tục chạy.`,``],"Run this exact command once on this machine, outside the sandbox, as you: it can read and change your files and use your sign-ins.":[`Chạy đúng lệnh này một lần trên máy bạn, ngoài sandbox, bằng quyền của bạn: lệnh đọc/sửa được file và dùng được tài khoản đã đăng nhập trên máy.`,``],"Docker is not started; the agent is told you declined.":[`Không mở Docker; agent được báo là bạn đã từ chối.`,``]},N=(e,t,n)=>{let r=e[t];return r?k(n,r[0],r[1]||t):null};function P(e,t){return t===`vi`?e.split(`; `).map(e=>{let t=e.match(/^Confirmation required: the command runs (.+)$/);if(t)return`Lệnh có ${t[1]} nên cần bạn duyệt trước khi chạy.`;let n=e.match(/^External provider action (.+) requires confirmation$/);return n?`Hành động ra bên ngoài (${n[1]}) cần bạn duyệt.`:e}).join(` `):e}var F=(e,t)=>N(A,e.kind,t)??c(e.kind,t),I=(e,t)=>N(j,e.requestedScope,t)??c(e.requestedScope,t);function L(e,t){let n=t===`vi`?/^Start (.+) on this machine; it keeps running after the conversation\.$/.exec(e):null;return n?`Mở ${n[1]} trên máy; nó vẫn chạy sau cuộc trò chuyện.`:N(M,e,t)??e}var R=e=>!/handoff|waiver/.test(String(e.action.requestedScope));function z(e,t){let n=t===`allow`||t===`session`?`allow`:`deny`;return{schemaVersion:1,version:`piagent-webui-approval-v1`,recordType:`decision`,approvalRef:e.approvalRef,decisionId:`decision.${crypto.randomUUID()}`,decisionToken:e.decisionToken,identity:structuredClone(e.identity),actionDigest:e.action.actionDigest,expectedRevisions:structuredClone(e.expectedRevisions),decision:n,reason:null,decidedAt:new Date().toISOString(),expiresAt:e.expiresAt,decisionSurface:`webui`,executor:`pi-guard`,directExecution:!1,...t===`session`?{scope:`session`}:t===`stop`?{stop:!0}:{}}}var B=t();function V({state:e,setState:t,refreshSnapshot:n,locale:r,asker:a}){let o=e.request;if(!o)return(0,B.jsx)(`article`,{className:`approval-card`,children:(0,B.jsx)(`p`,{children:e.error??i(r,`Đang tải yêu cầu phê duyệt…`,`Loading approval request…`)})});let l=o.action,u=Math.max(0,Math.ceil((Date.parse(o.expiresAt)-Date.now())/1e3)),d=async e=>{t({request:o,deciding:e});try{await s(z(o,e)),await n?.()}catch{t({request:o,error:i(r,`Yêu cầu đã hết hạn, thay đổi hoặc được trả lời ở terminal. Hãy tải trạng thái mới.`,`The request expired, changed, or was answered in the terminal. Refresh status.`)})}};return(0,B.jsxs)(`article`,{className:`approval-card risk-${l.riskClass}`,"aria-labelledby":`approval-${o.approvalRef}`,children:[(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`p`,{className:`section-kicker`,children:a?i(r,`${a} cần bạn duyệt`,`${a} needs your approval`):i(r,`Cần phê duyệt`,`Approval required`)}),(0,B.jsx)(`h2`,{id:`approval-${o.approvalRef}`,children:l.toolName})]}),(0,B.jsx)(`span`,{className:`approval-risk`,children:c(l.riskClass,r)})]}),(0,B.jsx)(`p`,{className:`approval-reason`,children:P(l.reason,r)}),l.commandPreview&&(0,B.jsx)(`pre`,{className:`approval-preview`,children:(0,B.jsx)(`code`,{children:l.commandPreview})}),!l.commandPreview&&l.parameterPreview&&l.parameterPreview!==`No additional parameters`&&(0,B.jsx)(`p`,{className:`approval-preview`,children:l.parameterPreview}),(0,B.jsxs)(`dl`,{className:`approval-facts`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:i(r,`Hành động`,`Action`)}),(0,B.jsx)(`dd`,{children:F(l,r)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:i(r,`Phạm vi`,`Scope`)}),(0,B.jsx)(`dd`,{children:I(l,r)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:i(r,`Thư mục`,`Directory`)}),(0,B.jsx)(`dd`,{children:l.cwdDisplay??i(r,`Đã ẩn`,`Hidden`)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:i(r,`Hết hạn`,`Expires`)}),(0,B.jsxs)(`dd`,{children:[u,`s`]})]})]}),l.targetPaths.length>0&&(0,B.jsxs)(`div`,{className:`approval-targets`,children:[(0,B.jsx)(`strong`,{children:i(r,`Đích tác động`,`Targets`)}),(0,B.jsx)(`ul`,{children:l.targetPaths.map(e=>(0,B.jsx)(`li`,{children:e===`.`?i(r,`Cả thư mục project`,`The whole project folder`):e},e))})]}),(0,B.jsxs)(`div`,{className:`approval-consequences`,children:[(0,B.jsxs)(`p`,{children:[(0,B.jsx)(`strong`,{children:i(r,`Nếu cho phép:`,`If allowed:`)}),` `,L(l.consequences.allow,r)]}),(0,B.jsxs)(`p`,{children:[(0,B.jsx)(`strong`,{children:i(r,`Nếu từ chối:`,`If denied:`)}),` `,L(l.consequences.deny,r)]})]}),e.error&&(0,B.jsx)(`p`,{className:`form-error`,role:`alert`,children:e.error}),(0,B.jsxs)(`footer`,{children:[(0,B.jsx)(`button`,{type:`button`,className:`secondary-action`,disabled:!!e.deciding,title:i(r,`Từ chối và kết thúc lượt này, agent không thử lại`,`Deny and end this turn so the agent does not retry`),onClick:()=>void d(`stop`),children:i(r,`Từ chối và dừng`,`Deny and stop`)}),(0,B.jsx)(`button`,{type:`button`,className:`secondary-action`,disabled:!!e.deciding,onClick:()=>void d(`deny`),children:i(r,`Từ chối`,`Deny`)}),R(o)&&(0,B.jsx)(`button`,{type:`button`,className:`secondary-action`,disabled:!!e.deciding,title:i(r,`Lệnh giống hệt sẽ chạy không hỏi lại cho tới hết session`,`The same exact command runs without asking until the session ends`),onClick:()=>void d(`session`),children:i(r,`Cho cả session`,`Allow for session`)}),(0,B.jsx)(`button`,{type:`button`,className:`danger-action`,disabled:!!e.deciding,onClick:()=>void d(`allow`),children:e.deciding===`allow`||e.deciding===`session`?i(r,`Đang kiểm tra lại…`,`Rechecking…`):i(r,`Cho phép đúng 1 lần`,`Allow once`)})]})]})}function H(e,t,n){let r=(0,O.useMemo)(()=>e,[e.join(`\0`)]),[s,c]=(0,O.useState)({});return(0,O.useEffect)(()=>{let e=new AbortController;for(let s of r)(t?a(t,s,e.signal):o(s,e.signal)).then(e=>c(t=>({...t,[s]:{request:e}})),()=>c(e=>({...e,[s]:{error:i(n,`Không thể tải yêu cầu phê duyệt hiện tại.`,`Unable to load the current approval request.`)}})));return()=>e.abort()},[n,t,r]),{refs:r,states:s,set:(e,t)=>c(n=>({...n,[e]:t}))}}function U({approvalRefs:e,sessionRef:t,refreshSnapshot:n}){let{locale:a}=r(),{refs:o,states:s,set:c}=H(e,t,a);return o.length===0?null:(0,B.jsx)(`section`,{className:`approval-stack`,"aria-label":i(a,`Yêu cầu phê duyệt đang chờ`,`Pending approval requests`),"aria-live":`polite`,children:o.map(e=>(0,B.jsx)(V,{state:s[e]??{},setState:t=>c(e,t),refreshSnapshot:n,locale:a},e))})}function ae({snapshot:e,refreshSnapshot:t}){let n=(0,O.useMemo)(()=>e.approvals.pending.map(e=>e.approvalRef),[e.approvals.pending]);return(0,B.jsx)(U,{approvalRefs:n,refreshSnapshot:t})}var W=16384,G=1e3;function K(e,t){let n=new Map;for(let r of[...t,...e])n.has(r.messageRef)||n.set(r.messageRef,r);return[...n.values()].slice(0,G)}function q(e){let t=new Map,n=new Map;for(let r of e.slice(-500)){let e=r.kind,i=r.payload??{},a=r.messageRef;if([`agent-operation.settled`,`session.replacement-pending`,`session.replacement-committed`,`session.shutdown`].includes(String(e))){t.clear(),n.clear();continue}if(e===`message.started`&&i.role===`assistant`&&typeof a==`string`)t.set(a,{messageRef:a,text:``,thinking:!1,truncated:!1});else if(e===`message.text-delta`&&typeof a==`string`&&typeof i.delta==`string`){let e=t.get(a);if(!e)continue;let n=`${e.text}${i.delta}`;t.set(a,{...e,text:n.slice(0,W),truncated:e.truncated||n.length>W})}else if(e===`message.thinking-state`&&typeof a==`string`){let e=t.get(a);if(!e)continue;t.set(a,{...e,thinking:i.state!==`completed`})}else[`message.completed`,`message.failed`].includes(String(e))&&typeof a==`string`&&t.delete(a);[`activity.started`,`activity.progress`,`activity.finished`,`activity.failed`,`activity.blocked`,`activity.aborted`].includes(String(e))&&typeof r.toolCallId==`string`&&typeof i.activityRef==`string`&&typeof i.toolName==`string`&&n.set(r.toolCallId,{toolCallId:r.toolCallId,activityRef:i.activityRef,toolName:i.toolName,state:String(i.state??`unknown`)})}return{assistants:[...t.values()].slice(-2),tools:[...n.values()].slice(-8)}}var J=/^(?:\p{White_Space}|\p{Cc}|\p{Default_Ignorable_Code_Point})$/u,oe=/\u001b(?:\[[0-?]*[ -/]*[@-~]|[@-_])/g;function se(e){for(let t of e.replace(oe,``))if(!J.test(t))return!0;return!1}function ce(e,t,n){if(!n?.complete)return{key:`${e}:${t}:active`,completionKey:null,user:``,assistant:``,operationRef:null,messageRequestId:null,startedAt:null};let r=n.startedAt??null,i=n.messageRequestId??null,a=`${i??`unknown`}:${n.operationRef??`unknown`}:${r??`unknown`}:${n.user}:${n.assistant.length}`;return{key:`${e}:${t}:complete:${a}`,completionKey:a,user:n.user,assistant:n.assistant,operationRef:n.operationRef,messageRequestId:i,startedAt:r}}function le(e){let t=/^\[Piagent completion gate: (CONTINUING|NOT APPROVED)\][\t ]*/i.exec(e);if(!t)return{text:e,completionGate:null};let n=t[1]?.toUpperCase()===`CONTINUING`?`continuing`:`not-approved`,r=e.indexOf(`
2
2
 
3
3
  `,t[0].length);return{text:r<0?``:e.slice(r+2).trimStart(),completionGate:n}}var ue=new Set([`provider-auth-expired`,`provider-auth-required`,`provider-rate-limited`,`provider-unavailable`,`provider-response-failed`,`assistant-output-incomplete`]);function Y(e){let t=e.content.reasonCode;return e.role===`assistant`&&e.toolCalls.length===0&&e.content.state===`unavailable`&&t&&(ue.has(t)||t.startsWith(`company-`))?t:null}function X(e){let t=le(e);return t.completionGate===null&&se(t.text)?t.text:null}function Z(e,t){let n=e?.trim(),r=t.trim();return!!(n&&r&&(n===r||n.startsWith(`/`)&&n.endsWith(` ${r}`)))}function Q(e,t){if(e.agentOperationId&&t.operationRef&&e.agentOperationId!==t.operationRef)return!1;if(e.messageRequestId&&t.messageRequestId)return e.messageRequestId===t.messageRequestId;if(e.agentOperationId&&t.operationRef)return e.agentOperationId===t.operationRef;let n=Date.parse(e.recordedAt),r=Date.parse(t.startedAt??``);return Number.isFinite(n)&&Number.isFinite(r)&&n>=r}function $(e,t,n){let r=t.trim();if(!r)return-1;for(let t=e.length-1;t>=0;--t){let i=e[t];if(i?.role===`user`&&Z(i.content.text,r)&&Q(i,n))return t}return-1}function de(e,t,n){return $(e,t,n)>=0}function fe(e,t,n,r){let i=$(e,t,r);if(i<0)return!1;let a=X(n)?.trim()??``;if(!a)return!0;let o=e[i]?.messageRef??null;for(let t=i+1;t<e.length;t+=1){let n=e[t];if(n?.role===`user`)return!1;if(!(n?.role!==`assistant`&&n?.role!==`custom`||n.toolCalls.length>0)&&!(o&&n.parentMessageRef&&n.parentMessageRef!==o)&&X(n.content.text??``)?.trim()===a)return!0}return!1}function pe(e,t,n){let r=$(e,t,n);if(r<0)return!1;let i=e[r]?.messageRef??null;for(let t=r+1;t<e.length;t+=1){let n=e[t];if(n?.role===`user`)return!1;if(!(n?.role!==`assistant`&&n?.role!==`custom`||n.toolCalls.length>0)&&!(i&&n.parentMessageRef&&n.parentMessageRef!==i)&&(X(n.content.text??``)||Y(n)))return!0}return!1}function me(e){let t=[],n=new Map,r=new Set,i=null,a=!1,o=null;for(let s of e){if(s.role===`user`){n.clear(),r.add(s.messageRef),i=s.messageRef,t.push(s),a=!1,o=null;continue}if(s.role!==`assistant`&&s.role!==`custom`||(s.parentMessageRef?!r.has(s.parentMessageRef):i===null)||s.toolCalls.length>0)continue;if(Y(s)){if(a)continue;o?t[t.indexOf(o)]=s:t.push(s),o=s;continue}let e=X(s.content.text??``);if(!e)continue;a=!0,o&&=(t.splice(t.indexOf(o),1),null);let c=`${s.role}:${e.trim()}`,l=n.get(c);l===void 0?(n.set(c,t.length),t.push(s)):t[l]=s}return t}export{f as C,g as D,v as E,h as O,re as S,m as T,S as _,fe as a,T as b,X as c,V as d,ae as f,w as g,E as h,pe as i,q as l,te as m,me as n,de as o,H as p,ce as r,Z as s,Y as t,K as u,ie as v,_ as w,D as x,ne as y};
@@ -1 +1 @@
1
- var e={active:`Đang hoạt động`,"pause-requested":`Đang yêu cầu tạm dừng`,paused:`Đã tạm dừng`,terminal:`Đã kết thúc`,idle:`Đang chờ`,running:`Đang chạy`,stopping:`Đang dừng`,settled:`Đã ổn định`,unknown:`Chưa xác định`,pending:`Chưa xong`,completed:`Hoàn thành`,blocked:`Bị chặn`,partial:`Một phần`,failed:`Thất bại`,satisfied:`Đã đạt`,unavailable:`Không có dữ liệu`,connected:`Đã kết nối`,disconnected:`Mất kết nối`,reconnecting:`Đang kết nối lại`,"resync-required":`Cần đồng bộ lại`,none:`Không có`,waiting:`Đang chờ duyệt`,current:`Mới nhất`,stale:`Đã cũ`,"not-run":`Chưa chạy`,"in-progress":`Đang làm`,done:`Đã xong`,skipped:`Bỏ qua`,resume:`Tiếp tục`,retry:`Thử lại`,observed:`Đã ghi nhận`,requested:`Đã yêu cầu`,"possible-interruption":`Có thể bị gián đoạn`,complete:`Đầy đủ`,"aggregate-only":`Chỉ có dữ liệu tổng hợp`,off:`Tắt`,minimal:`Tối thiểu`,low:`Thấp`,medium:`Trung bình`,high:`Cao`,xhigh:`Rất cao`,max:`Tối đa`,orphaned:`Mất owner`,cancelled:`Đã hủy`,succeeded:`Thành công`,"stale-result":`Kết quả đến muộn`,accepted:`Đã nhận`,rejected:`Không nhận`,"not-recorded":`Chưa có kết quả`,parent:`Task cha`,helper:`Helper`,"read-only":`Chỉ đọc`,"workspace-write":`Ghi trong project`,"trusted-full-access":`Toàn quyền`,bypass:`Bypass`,"single-writer":`Một writer`,retriever:`Retriever`,scout:`Scout`,planner:`Planner`,worker:`Worker`,reviewer:`Reviewer`,oracle:`Oracle`,researcher:`Researcher`,ready:`Sẵn sàng`,missing:`Chưa có bằng chứng`,interrupted:`Bị gián đoạn`,stopped:`Đã dừng`,aborted:`Đã hủy do lỗi`,incomplete:`Chưa có kết luận`,passed:`Đạt`,"not-applicable":`Không áp dụng`,smoke:`Smoke`,"public-regression":`Public regression`,capability:`Capability`,"private-holdout":`Private holdout`,"production-shadow":`Production shadow`,"pdf-converter-unavailable":`Host chưa cài pdftotext (poppler) nên chưa đọc được .pdf`,"pdf-text-unavailable":`PDF này không có text bóc được; nhiều khả năng là bản scan, cần OCR trước`,"pdf-extraction-failed":`Không chuyển được PDF này sang text`,"docx-unreadable":`File .docx này hỏng, bị mã hóa, hoặc không phải file Word thật`,"document-text-empty":`Tài liệu không có chữ nào để đọc`,"document-size-limit":`Tài liệu vượt giới hạn dung lượng`,"text-size-limit":`File text vượt giới hạn dung lượng`,"text-content-invalid":`Nội dung file không phải văn bản (file nhị phân), chưa gửi vào chat được`,"image-mime-mismatch":`Nội dung ảnh không khớp với đuôi file`,"model-image-input-unavailable":`Model hiện tại không nhận ảnh`,"attachment-capacity-limit":`Đã chạm giới hạn số file hoặc dung lượng đính kèm`,"no-readable-root":`Chưa có thư mục nào đọc được`,"document-roots-unavailable":`Không xác định được thư mục tài liệu`,"document-not-listed":`Tài liệu không còn trong danh sách; hãy tải lại`,"document-unavailable":`Không mở được tài liệu này`,"document-protected":`Tài liệu nằm trong protectedPaths nên không được đọc`,"document-changed":`File đã thay đổi sau khi liệt kê; chưa đọc gì cả`,"document-unreadable":`Không đọc được nội dung tài liệu`,"document-needs-ocr":`Tài liệu là bản scan, cần OCR trước khi đọc được chữ`,"document-converter-unavailable":`Host chưa cài pdftotext (poppler) nên chưa đọc được .pdf`,"session-command-effect-unknown":`Pi đã nhận yêu cầu nhưng đang đồng bộ trạng thái; không gửi lại để tránh chạy trùng`},t={active:`Active`,"pause-requested":`Pause requested`,paused:`Paused`,terminal:`Finished`,idle:`Idle`,running:`Running`,stopping:`Stopping`,settled:`Settled`,unknown:`Unknown`,pending:`Pending`,completed:`Completed`,blocked:`Blocked`,partial:`Partial`,failed:`Failed`,satisfied:`Satisfied`,unavailable:`Unavailable`,connected:`Connected`,disconnected:`Disconnected`,reconnecting:`Reconnecting`,"resync-required":`Resync required`,none:`None`,waiting:`Awaiting approval`,current:`Current`,stale:`Stale`,"not-run":`Not run`,"in-progress":`In progress`,done:`Done`,skipped:`Skipped`,resume:`Resume`,retry:`Retry`,observed:`Observed`,requested:`Requested`,"possible-interruption":`Possible interruption`,complete:`Complete`,"aggregate-only":`Aggregate only`,off:`Off`,minimal:`Minimal`,low:`Low`,medium:`Medium`,high:`High`,xhigh:`Extra high`,max:`Maximum`,orphaned:`Owner missing`,cancelled:`Cancelled`,succeeded:`Succeeded`,"stale-result":`Stale result`,accepted:`Accepted`,rejected:`Rejected`,"not-recorded":`Not recorded`,parent:`Parent task`,helper:`Helper`,"read-only":`Read only`,"workspace-write":`Workspace write`,"trusted-full-access":`Full access`,bypass:`Bypass`,"single-writer":`Single writer`,retriever:`Retriever`,scout:`Scout`,planner:`Planner`,worker:`Worker`,reviewer:`Reviewer`,oracle:`Oracle`,researcher:`Researcher`,ready:`Ready`,missing:`Evidence missing`,interrupted:`Interrupted`,stopped:`Stopped`,aborted:`Aborted`,incomplete:`Incomplete`,passed:`Passed`,"not-applicable":`Not applicable`,smoke:`Smoke`,"public-regression":`Public regression`,capability:`Capability`,"private-holdout":`Private holdout`,"production-shadow":`Production shadow`,"pdf-converter-unavailable":`This host has no pdftotext (poppler), so .pdf cannot be read`,"pdf-text-unavailable":`This PDF holds no extractable text; it is probably scanned and needs OCR first`,"pdf-extraction-failed":`The PDF could not be converted to text`,"docx-unreadable":`This .docx is corrupt, encrypted, or not really a Word document`,"document-text-empty":`The document contains no readable text`,"document-size-limit":`The document is over the size limit`,"text-size-limit":`The text file is over the size limit`,"text-content-invalid":`The file is not text (binary), so it cannot go into the chat`,"image-mime-mismatch":`The image content does not match its file extension`,"model-image-input-unavailable":`The current model does not accept images`,"attachment-capacity-limit":`The attachment count or size limit was reached`,"no-readable-root":`No readable directory is available`,"document-roots-unavailable":`The document directories could not be resolved`,"document-not-listed":`The document is no longer listed; reload the list`,"document-unavailable":`This document could not be opened`,"document-protected":`The document is under protectedPaths and is not readable`,"document-changed":`The file changed after it was listed; nothing was read`,"document-unreadable":`The document content could not be read`,"document-needs-ocr":`The document is scanned and needs OCR before it holds text`,"document-converter-unavailable":`This host has no pdftotext (poppler), so .pdf cannot be read`,"session-command-effect-unknown":`Pi received the request and is resyncing; do not resend it, to avoid a duplicate run`};function n(n,r=`vi`){return n?(r===`vi`?e:t)[n]??n.replaceAll(`-`,` `):r===`vi`?`Chưa có`:`Not available`}function r(e){return[`completed`,`satisfied`,`current`,`connected`,`done`,`passed`].includes(e??``)?`positive`:[`blocked`,`failed`,`error`,`expired`].includes(e??``)?`danger`:[`pause-requested`,`paused`,`waiting`,`stale`,`stale-result`,`orphaned`,`partial`,`reconnecting`].includes(e??``)?`warning`:[`running`,`active`,`in-progress`].includes(e??``)?`info`:`neutral`}function i(e){return e?e.length>22?`${e.slice(0,10)}…${e.slice(-7)}`:e:`—`}function a(e,t=`vi`){return e.session.model.state===`known`&&e.session.model.value?e.session.model.value.displayName:t===`vi`?`Model chưa xác định`:`Unknown model`}function o(e,t=`vi`){return e.session.thinking.state===`known`&&e.session.thinking.value?n(e.session.thinking.value,t):t===`vi`?`Chưa xác định`:`Unknown`}function s(e,t=`vi`){let r=e.session.permissionProfile;return r.state===`known`&&r.value?n(r.value,t):t===`vi`?`Quyền chưa xác định`:`Unknown permission`}function c(e,t=`vi`){let n=e.relatedFileRefs.length,r=e.verifierAttemptRefs.length;return!n&&!r?t===`vi`?`Chưa có bằng chứng liên kết`:`No linked evidence`:t===`vi`?`${n} file · ${r} lần kiểm tra`:`${n} files · ${r} verifier runs`}function l(e,t=`vi`){let n=e.task;return n?{completed:n.progress.completed,total:n.progress.total,percent:Math.max(0,Math.min(100,n.progress.percent)),text:t===`vi`?`${n.progress.completed}/${n.progress.total} tiêu chí`:`${n.progress.completed}/${n.progress.total} criteria`}:{completed:0,total:0,percent:0,text:t===`vi`?`Chưa có task đang chạy`:`No active task`}}export{s as a,r as c,a as i,c as n,l as o,n as r,o as s,i as t};
1
+ var e={active:`Đang hoạt động`,"pause-requested":`Đang yêu cầu tạm dừng`,paused:`Đã tạm dừng`,terminal:`Đã kết thúc`,idle:`Đang chờ`,running:`Đang chạy`,stopping:`Đang dừng`,settled:`Đã ổn định`,unknown:`Chưa xác định`,pending:`Chưa xong`,completed:`Hoàn thành`,blocked:`Bị chặn`,partial:`Một phần`,failed:`Thất bại`,satisfied:`Đã đạt`,unavailable:`Không có dữ liệu`,connected:`Đã kết nối`,disconnected:`Mất kết nối`,reconnecting:`Đang kết nối lại`,"resync-required":`Cần đồng bộ lại`,none:`Không có`,waiting:`Đang chờ duyệt`,current:`Mới nhất`,stale:`Đã cũ`,"not-run":`Chưa chạy`,"in-progress":`Đang làm`,done:`Đã xong`,skipped:`Bỏ qua`,resume:`Tiếp tục`,retry:`Thử lại`,observed:`Đã ghi nhận`,requested:`Đã yêu cầu`,"possible-interruption":`Có thể bị gián đoạn`,complete:`Đầy đủ`,"aggregate-only":`Chỉ có dữ liệu tổng hợp`,off:`Tắt`,minimal:`Tối thiểu`,low:`Thấp`,medium:`Trung bình`,high:`Cao`,xhigh:`Rất cao`,max:`Tối đa`,orphaned:`Mất owner`,cancelled:`Đã hủy`,succeeded:`Thành công`,"stale-result":`Kết quả đến muộn`,accepted:`Đã nhận`,rejected:`Không nhận`,"not-recorded":`Chưa có kết quả`,parent:`Task cha`,helper:`Helper`,"read-only":`Chỉ đọc`,"workspace-write":`Ghi trong project`,"trusted-full-access":`Toàn quyền`,bypass:`Bypass`,"always-bypass":`Always bypass`,"single-writer":`Một writer`,retriever:`Retriever`,scout:`Scout`,planner:`Planner`,worker:`Worker`,reviewer:`Reviewer`,oracle:`Oracle`,researcher:`Researcher`,ready:`Sẵn sàng`,missing:`Chưa có bằng chứng`,interrupted:`Bị gián đoạn`,stopped:`Đã dừng`,aborted:`Đã hủy do lỗi`,incomplete:`Chưa có kết luận`,passed:`Đạt`,"not-applicable":`Không áp dụng`,smoke:`Smoke`,"public-regression":`Public regression`,capability:`Capability`,"private-holdout":`Private holdout`,"production-shadow":`Production shadow`,"pdf-converter-unavailable":`Host chưa cài pdftotext (poppler) nên chưa đọc được .pdf`,"pdf-text-unavailable":`PDF này không có text bóc được; nhiều khả năng là bản scan, cần OCR trước`,"pdf-extraction-failed":`Không chuyển được PDF này sang text`,"docx-unreadable":`File .docx này hỏng, bị mã hóa, hoặc không phải file Word thật`,"document-text-empty":`Tài liệu không có chữ nào để đọc`,"document-size-limit":`Tài liệu vượt giới hạn dung lượng`,"text-size-limit":`File text vượt giới hạn dung lượng`,"text-content-invalid":`Nội dung file không phải văn bản (file nhị phân), chưa gửi vào chat được`,"image-mime-mismatch":`Nội dung ảnh không khớp với đuôi file`,"model-image-input-unavailable":`Model hiện tại không nhận ảnh`,"attachment-capacity-limit":`Đã chạm giới hạn số file hoặc dung lượng đính kèm`,"no-readable-root":`Chưa có thư mục nào đọc được`,"document-roots-unavailable":`Không xác định được thư mục tài liệu`,"document-not-listed":`Tài liệu không còn trong danh sách; hãy tải lại`,"document-unavailable":`Không mở được tài liệu này`,"document-protected":`Tài liệu nằm trong protectedPaths nên không được đọc`,"document-changed":`File đã thay đổi sau khi liệt kê; chưa đọc gì cả`,"document-unreadable":`Không đọc được nội dung tài liệu`,"document-needs-ocr":`Tài liệu là bản scan, cần OCR trước khi đọc được chữ`,"document-converter-unavailable":`Host chưa cài pdftotext (poppler) nên chưa đọc được .pdf`,"session-command-effect-unknown":`Pi đã nhận yêu cầu nhưng đang đồng bộ trạng thái; không gửi lại để tránh chạy trùng`},t={active:`Active`,"pause-requested":`Pause requested`,paused:`Paused`,terminal:`Finished`,idle:`Idle`,running:`Running`,stopping:`Stopping`,settled:`Settled`,unknown:`Unknown`,pending:`Pending`,completed:`Completed`,blocked:`Blocked`,partial:`Partial`,failed:`Failed`,satisfied:`Satisfied`,unavailable:`Unavailable`,connected:`Connected`,disconnected:`Disconnected`,reconnecting:`Reconnecting`,"resync-required":`Resync required`,none:`None`,waiting:`Awaiting approval`,current:`Current`,stale:`Stale`,"not-run":`Not run`,"in-progress":`In progress`,done:`Done`,skipped:`Skipped`,resume:`Resume`,retry:`Retry`,observed:`Observed`,requested:`Requested`,"possible-interruption":`Possible interruption`,complete:`Complete`,"aggregate-only":`Aggregate only`,off:`Off`,minimal:`Minimal`,low:`Low`,medium:`Medium`,high:`High`,xhigh:`Extra high`,max:`Maximum`,orphaned:`Owner missing`,cancelled:`Cancelled`,succeeded:`Succeeded`,"stale-result":`Stale result`,accepted:`Accepted`,rejected:`Rejected`,"not-recorded":`Not recorded`,parent:`Parent task`,helper:`Helper`,"read-only":`Read only`,"workspace-write":`Workspace write`,"trusted-full-access":`Full access`,bypass:`Bypass`,"always-bypass":`Always bypass`,"single-writer":`Single writer`,retriever:`Retriever`,scout:`Scout`,planner:`Planner`,worker:`Worker`,reviewer:`Reviewer`,oracle:`Oracle`,researcher:`Researcher`,ready:`Ready`,missing:`Evidence missing`,interrupted:`Interrupted`,stopped:`Stopped`,aborted:`Aborted`,incomplete:`Incomplete`,passed:`Passed`,"not-applicable":`Not applicable`,smoke:`Smoke`,"public-regression":`Public regression`,capability:`Capability`,"private-holdout":`Private holdout`,"production-shadow":`Production shadow`,"pdf-converter-unavailable":`This host has no pdftotext (poppler), so .pdf cannot be read`,"pdf-text-unavailable":`This PDF holds no extractable text; it is probably scanned and needs OCR first`,"pdf-extraction-failed":`The PDF could not be converted to text`,"docx-unreadable":`This .docx is corrupt, encrypted, or not really a Word document`,"document-text-empty":`The document contains no readable text`,"document-size-limit":`The document is over the size limit`,"text-size-limit":`The text file is over the size limit`,"text-content-invalid":`The file is not text (binary), so it cannot go into the chat`,"image-mime-mismatch":`The image content does not match its file extension`,"model-image-input-unavailable":`The current model does not accept images`,"attachment-capacity-limit":`The attachment count or size limit was reached`,"no-readable-root":`No readable directory is available`,"document-roots-unavailable":`The document directories could not be resolved`,"document-not-listed":`The document is no longer listed; reload the list`,"document-unavailable":`This document could not be opened`,"document-protected":`The document is under protectedPaths and is not readable`,"document-changed":`The file changed after it was listed; nothing was read`,"document-unreadable":`The document content could not be read`,"document-needs-ocr":`The document is scanned and needs OCR before it holds text`,"document-converter-unavailable":`This host has no pdftotext (poppler), so .pdf cannot be read`,"session-command-effect-unknown":`Pi received the request and is resyncing; do not resend it, to avoid a duplicate run`};function n(n,r=`vi`){return n?(r===`vi`?e:t)[n]??n.replaceAll(`-`,` `):r===`vi`?`Chưa có`:`Not available`}function r(e){return[`completed`,`satisfied`,`current`,`connected`,`done`,`passed`].includes(e??``)?`positive`:[`blocked`,`failed`,`error`,`expired`].includes(e??``)?`danger`:[`pause-requested`,`paused`,`waiting`,`stale`,`stale-result`,`orphaned`,`partial`,`reconnecting`].includes(e??``)?`warning`:[`running`,`active`,`in-progress`].includes(e??``)?`info`:`neutral`}function i(e){return e?e.length>22?`${e.slice(0,10)}…${e.slice(-7)}`:e:`—`}function a(e,t=`vi`){return e.session.model.state===`known`&&e.session.model.value?e.session.model.value.displayName:t===`vi`?`Model chưa xác định`:`Unknown model`}function o(e,t=`vi`){return e.session.thinking.state===`known`&&e.session.thinking.value?n(e.session.thinking.value,t):t===`vi`?`Chưa xác định`:`Unknown`}function s(e,t=`vi`){let r=e.session.permissionProfile;return r.state===`known`&&r.value?n(r.value,t):t===`vi`?`Quyền chưa xác định`:`Unknown permission`}function c(e,t=`vi`){let n=e.relatedFileRefs.length,r=e.verifierAttemptRefs.length;return!n&&!r?t===`vi`?`Chưa có bằng chứng liên kết`:`No linked evidence`:t===`vi`?`${n} file · ${r} lần kiểm tra`:`${n} files · ${r} verifier runs`}function l(e,t=`vi`){let n=e.task;return n?{completed:n.progress.completed,total:n.progress.total,percent:Math.max(0,Math.min(100,n.progress.percent)),text:t===`vi`?`${n.progress.completed}/${n.progress.total} tiêu chí`:`${n.progress.completed}/${n.progress.total} criteria`}:{completed:0,total:0,percent:0,text:t===`vi`?`Chưa có task đang chạy`:`No active task`}}var u=`piagent.alwaysBypass.accepted`;function d(){try{return window.localStorage.getItem(u)===`1`}catch{return!1}}function f(){try{window.localStorage.setItem(u,`1`)}catch{}}export{n as a,l as c,c as i,o as l,d as n,a as o,i as r,s,f as t,r as u};
@@ -7,7 +7,7 @@
7
7
  <meta name="csp-nonce" content="__PIAGENT_CSP_NONCE__" />
8
8
  <meta name="piagent-webui-mode" content="__PIAGENT_WEBUI_MODE__" />
9
9
  <title>Piagent WebUI</title>
10
- <script type="module" crossorigin src="/assets/index-fUpioGMZ.js"></script>
10
+ <script type="module" crossorigin src="/assets/index-BiLVX8S-.js"></script>
11
11
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-hePW80VL.js">
12
12
  <link rel="modulepreload" crossorigin href="/assets/vendor-DNZbaWhT.js">
13
13
  <link rel="modulepreload" crossorigin href="/assets/ui-preferences-OfS30-ZV.js">
@@ -40,7 +40,7 @@ export function managedProjection(context: any, entries: any[]) {
40
40
  // The member's access choice; Bypass only while the Harness allows it, else
41
41
  // it applies as Full access (permission.mjs).
42
42
  const chosen = last('agent-watch-permission')?.mode, bypassAllowed = last('agent-watch-bypass')?.allowed === true;
43
- const permission = chosen === 'bypass' ? (bypassAllowed ? 'bypass' : 'trusted-full-access') : chosen === 'trusted-full-access' ? 'trusted-full-access' : 'workspace-write';
43
+ const permission = chosen === 'always-bypass' ? 'always-bypass' : chosen === 'bypass' ? (bypassAllowed ? 'bypass' : 'trusted-full-access') : chosen === 'trusted-full-access' ? 'trusted-full-access' : 'workspace-write';
44
44
  // Fast mode, only where the conversation's Harness allows it (fast-mode.mjs).
45
45
  const fast = last('agent-watch-fast');
46
46
  // Projects Studio says do not belong to the key's team (workspace-report.mjs);
@@ -14,7 +14,7 @@ type RuntimeCommandOutput = {
14
14
  };
15
15
 
16
16
  export async function executePermissionCommand(session: any,
17
- permissionMode: "read-only" | "workspace-write" | "trusted-full-access" | "bypass"): Promise<void> {
17
+ permissionMode: "read-only" | "workspace-write" | "trusted-full-access" | "bypass" | "always-bypass"): Promise<void> {
18
18
  // A company conversation: "Ask first" or "Bypass" (no read-only mode); the
19
19
  // runtime keeps the choice in the conversation and reads it at each command,
20
20
  // so it may change while a turn runs (the supervisor lets it).
@@ -57,7 +57,7 @@ function validPayload(action: SessionAction, payload: Record<string, unknown>):
57
57
  if (action === "session.set-thinking") return exactKeys(payload, ["thinkingLevel"])
58
58
  && ["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes(String(payload.thinkingLevel));
59
59
  if (action === "session.set-permission") return exactKeys(payload, ["permissionMode"])
60
- && ["read-only", "workspace-write", "trusted-full-access", "bypass"].includes(String(payload.permissionMode));
60
+ && ["read-only", "workspace-write", "trusted-full-access", "bypass", "always-bypass"].includes(String(payload.permissionMode));
61
61
  if (action === "session.set-fast") return exactKeys(payload, ["fast"]) && typeof payload.fast === "boolean";
62
62
  if (action === "session.rename") return exactKeys(payload, ["title"]) && typeof payload.title === "string"
63
63
  && payload.title.length >= 1 && payload.title.length <= 500 && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(payload.title);
@@ -71,7 +71,7 @@ function validPayload(action: SessionAction, payload: Record<string, unknown>):
71
71
  && ["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes(String(payload.thinkingLevel))
72
72
  && typeof payload.message === "string" && payload.message.length >= 1 && payload.message.length <= 32_768 && !payload.message.includes("\0")
73
73
  && REF.test(String(payload.messageRequestId)) && (payload.deferInitialMessage === undefined || typeof payload.deferInitialMessage === "boolean")
74
- && (payload.permissionMode === undefined || ["read-only", "workspace-write", "trusted-full-access", "bypass"].includes(String(payload.permissionMode)))
74
+ && (payload.permissionMode === undefined || ["read-only", "workspace-write", "trusted-full-access", "bypass", "always-bypass"].includes(String(payload.permissionMode)))
75
75
  && (payload.fast === undefined || typeof payload.fast === "boolean")
76
76
  && (payload.workflow === undefined || isWebUiWorkflowId(payload.workflow));
77
77
  }
@@ -180,7 +180,7 @@ export class SessionCommandController {
180
180
  }
181
181
  if (command.payload.permissionMode !== undefined) {
182
182
  await this.#runtimes.setPermission(targetSessionRef, String(command.payload.permissionMode) as
183
- "read-only" | "workspace-write" | "trusted-full-access" | "bypass");
183
+ "read-only" | "workspace-write" | "trusted-full-access" | "bypass" | "always-bypass");
184
184
  }
185
185
  // Fast mode chosen on the new chat page is on before the first message
186
186
  // runs; a Harness that does not allow it refuses the create.
@@ -232,7 +232,7 @@ export class SessionCommandController {
232
232
  resultCode = await this.#runtimes.setThinking(command.sessionRef!, String(command.payload.thinkingLevel));
233
233
  } else if (command.action === "session.set-permission") {
234
234
  resultCode = await this.#runtimes.setPermission(command.sessionRef!, String(command.payload.permissionMode) as
235
- "read-only" | "workspace-write" | "trusted-full-access" | "bypass");
235
+ "read-only" | "workspace-write" | "trusted-full-access" | "bypass" | "always-bypass");
236
236
  } else if (command.action === "session.set-fast") {
237
237
  resultCode = await this.#runtimes.setFast(command.sessionRef!, command.payload.fast === true);
238
238
  } else if (command.action === "session.rename") {
@@ -232,7 +232,7 @@ export class SessionInspectionRegistry {
232
232
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1_048_576) return [];
233
233
  const value = JSON.parse(fs.readFileSync(file, "utf8")) as Record<string, unknown>;
234
234
  return [{ id: entry, displayName: safeName(value.displayName ?? entry),
235
- permissionMode: ["read-only", "workspace-write", "trusted-full-access", "bypass"].includes(String(value.permissionProfile))
235
+ permissionMode: ["read-only", "workspace-write", "trusted-full-access", "bypass", "always-bypass"].includes(String(value.permissionProfile))
236
236
  ? String(value.permissionProfile) : null }];
237
237
  }).slice(0, 100), []);
238
238
  const models = availableModels.flatMap((value) => {
@@ -362,7 +362,7 @@ export class SessionRuntimeSupervisor {
362
362
  if (effective !== thinkingLevel) throw new Error("session-thinking-mismatch");
363
363
  this.#touchCreated(sessionRef); return "thinking-changed";
364
364
  }
365
- async setPermission(sessionRef: string, permissionMode: "read-only" | "workspace-write" | "trusted-full-access" | "bypass"): Promise<"permission-changed"> {
365
+ async setPermission(sessionRef: string, permissionMode: "read-only" | "workspace-write" | "trusted-full-access" | "bypass" | "always-bypass"): Promise<"permission-changed"> {
366
366
  await this.acquire(sessionRef);
367
367
  const active = this.#active.get(sessionRef), session = active?.runtime.session;
368
368
  if (!active || !session) throw new Error("session-runtime-unavailable");
@@ -92,7 +92,7 @@
92
92
  "composerAvailable": { "type": "boolean" },
93
93
  "needsAttention": { "type": "boolean" },
94
94
  "managedHelpers": { "type": "object", "additionalProperties": false, "required": ["active", "maximum"], "properties": {"active": {"type": ["integer", "null"], "minimum": 0, "maximum": 4}, "maximum": {"type": "integer", "minimum": 0, "maximum": 4}, "roles": {"type": "array", "maxItems": 4, "items": {"type": "string", "maxLength": 32, "pattern": "^[a-z][a-z0-9_-]{0,31}$"}}, "since": {"type": "string", "maxLength": 40, "format": "date-time"}} },
95
- "managedThinkingLevels": {"type": "array", "uniqueItems": true, "maxItems": 7, "items": {"enum": ["off","minimal","low","medium","high","xhigh","max"]}}, "managedPermission": {"enum": ["workspace-write","trusted-full-access","bypass"]}, "managedBypass": {"const": true}, "managedProjectWarning": {"type": "object", "additionalProperties": false, "required": ["warnings"], "properties": {"team": {"type": "string", "minLength": 1, "maxLength": 80}, "warnings": {"type": "array", "minItems": 1, "maxItems": 6, "items": {"type": "object", "additionalProperties": false, "required": ["repo", "kind"], "properties": {"repo": {"type": "string", "minLength": 1, "maxLength": 200}, "name": {"type": "string", "minLength": 1, "maxLength": 80}, "kind": {"enum": ["other_team", "unlisted", "unregistered", "no_repository"]}}}}}}, "managedFast": {"enum": ["off","on"]},
95
+ "managedThinkingLevels": {"type": "array", "uniqueItems": true, "maxItems": 7, "items": {"enum": ["off","minimal","low","medium","high","xhigh","max"]}}, "managedPermission": {"enum": ["workspace-write","trusted-full-access","bypass","always-bypass"]}, "managedBypass": {"const": true}, "managedProjectWarning": {"type": "object", "additionalProperties": false, "required": ["warnings"], "properties": {"team": {"type": "string", "minLength": 1, "maxLength": 80}, "warnings": {"type": "array", "minItems": 1, "maxItems": 6, "items": {"type": "object", "additionalProperties": false, "required": ["repo", "kind"], "properties": {"repo": {"type": "string", "minLength": 1, "maxLength": 200}, "name": {"type": "string", "minLength": 1, "maxLength": 80}, "kind": {"enum": ["other_team", "unlisted", "unregistered", "no_repository"]}}}}}}, "managedFast": {"enum": ["off","on"]},
96
96
  "managedPlan": { "type": "object", "additionalProperties": false, "required": ["steps"], "properties": {
97
97
  "steps": { "type": "array", "minItems": 1, "maxItems": 30, "items": { "type": "object", "additionalProperties": false, "required": ["step", "status"], "properties": {
98
98
  "step": { "type": "string", "minLength": 1, "maxLength": 200 }, "status": { "enum": ["pending", "in_progress", "completed", "deferred"] } } } } } },
@@ -14,7 +14,7 @@
14
14
  "pattern": "^[A-Za-z0-9_-]+$"
15
15
  },
16
16
  "thinkingLevel": { "enum": ["off", "minimal", "low", "medium", "high", "xhigh", "max"] },
17
- "permissionMode": { "enum": ["read-only", "workspace-write", "trusted-full-access", "bypass"] },
17
+ "permissionMode": { "enum": ["read-only", "workspace-write", "trusted-full-access", "bypass", "always-bypass"] },
18
18
  "workflow": { "enum": ["task", "scout", "be-to-fe", "discuss", "plan", "review", "commit", "pr", "onboard", "platform-improve"] },
19
19
  "baseCommandProperties": {
20
20
  "type": "object",
@@ -944,6 +944,7 @@
944
944
  "workspace-write",
945
945
  "trusted-full-access",
946
946
  "bypass",
947
+ "always-bypass",
947
948
  null
948
949
  ]
949
950
  },
@@ -972,7 +973,7 @@
972
973
  "then": {
973
974
  "type": "object",
974
975
  "properties": {
975
- "value": { "enum": ["read-only", "workspace-write", "trusted-full-access", "bypass"] },
976
+ "value": { "enum": ["read-only", "workspace-write", "trusted-full-access", "bypass", "always-bypass"] },
976
977
  "evidence": { "enum": ["observed", "derived"] },
977
978
  "reasonCode": { "type": "null" }
978
979
  }