@rexvane/piweb 0.3.14 → 0.3.15

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 (92) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +5 -5
  3. package/.next/build-manifest.json +3 -3
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/react-loadable-manifest.json +1 -1
  6. package/.next/required-server-files.js +3 -1
  7. package/.next/required-server-files.json +3 -1
  8. package/.next/server/app/_global-error.html +1 -1
  9. package/.next/server/app/_global-error.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  13. package/.next/server/app/_not-found.html +1 -1
  14. package/.next/server/app/_not-found.rsc +1 -1
  15. package/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  16. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  17. package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  18. package/.next/server/app/api/agent/[id]/events/route.js.nft.json +1 -1
  19. package/.next/server/app/api/agent/[id]/route.js.nft.json +1 -1
  20. package/.next/server/app/api/agent/[id]/tree/route.js.nft.json +1 -1
  21. package/.next/server/app/api/agent/new/route.js.nft.json +1 -1
  22. package/.next/server/app/api/growth/route.js.nft.json +1 -1
  23. package/.next/server/app/api/models/route.js.nft.json +1 -1
  24. package/.next/server/app/api/plugins/route.js.nft.json +1 -1
  25. package/.next/server/app/api/prompts/route.js.nft.json +1 -1
  26. package/.next/server/app/api/security/route.js.nft.json +1 -1
  27. package/.next/server/app/api/sessions/[id]/export/route.js.nft.json +1 -1
  28. package/.next/server/app/api/sessions/[id]/route.js.nft.json +1 -1
  29. package/.next/server/app/api/sessions/import/route.js +3 -3
  30. package/.next/server/app/api/sessions/route.js.nft.json +1 -1
  31. package/.next/server/app/api/skills/route.js.nft.json +1 -1
  32. package/.next/server/app/api/update/route.js +1 -1
  33. package/.next/server/app/api/update/route.js.nft.json +1 -1
  34. package/.next/server/app/api/version/route.js +1 -1
  35. package/.next/server/app/api/workspaces/route.js.nft.json +1 -1
  36. package/.next/server/app/index.html +1 -1
  37. package/.next/server/app/index.rsc +1 -1
  38. package/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
  39. package/.next/server/app/index.segments/_full.segment.rsc +1 -1
  40. package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  41. package/.next/server/app/login.html +1 -1
  42. package/.next/server/app/login.rsc +1 -1
  43. package/.next/server/app/login.segments/_full.segment.rsc +1 -1
  44. package/.next/server/app/login.segments/_tree.segment.rsc +1 -1
  45. package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +1 -1
  46. package/.next/server/app-paths-manifest.json +5 -5
  47. package/.next/server/chunks/686.js +1 -1
  48. package/.next/server/middleware-build-manifest.js +1 -1
  49. package/.next/server/middleware-react-loadable-manifest.js +1 -1
  50. package/.next/server/pages/404.html +1 -1
  51. package/.next/server/pages/500.html +1 -1
  52. package/.next/server/server-reference-manifest.json +1 -1
  53. package/.next/static/chunks/4632.0ed92ae42905ce40.js +1 -0
  54. package/.next/static/chunks/{webpack-d28e132e1b8c100c.js → webpack-42c5aae79b0e5d8c.js} +1 -1
  55. package/README.md +51 -7
  56. package/assets/archive.png +0 -0
  57. package/assets/growth-1.png +0 -0
  58. package/assets/growth-2.png +0 -0
  59. package/assets/import.png +0 -0
  60. package/assets/main.png +0 -0
  61. package/assets/outline.png +0 -0
  62. package/assets/prompts-1.png +0 -0
  63. package/assets/prompts-2.png +0 -0
  64. package/assets/providers-1.png +0 -0
  65. package/assets/providers-2.png +0 -0
  66. package/assets/providers-3.png +0 -0
  67. package/assets/trace-1.png +0 -0
  68. package/assets/trace-2.png +0 -0
  69. package/assets/trace-3.png +0 -0
  70. package/assets/trace-4.png +0 -0
  71. package/assets/viewer-1.png +0 -0
  72. package/assets/viewer-2.png +0 -0
  73. package/next.config.ts +6 -2
  74. package/package.json +7 -3
  75. package/scripts/launcher.mjs +1 -1
  76. package/scripts/managed-niubash-assets.mjs +146 -0
  77. package/scripts/prepare-niubash-packages.mjs +182 -0
  78. package/scripts/smoke-managed-niubash.mjs +62 -0
  79. package/scripts/verify-package.mjs +53 -0
  80. package/src/components/SessionImportSection.tsx +36 -20
  81. package/src/lib/agent-manager.ts +3 -0
  82. package/src/lib/managed-niubash.ts +227 -0
  83. package/src/lib/session-import/claude.ts +13 -2
  84. package/src/lib/session-import/codex.ts +44 -8
  85. package/src/lib/session-import/files.ts +14 -0
  86. package/src/lib/session-import/grok.ts +54 -24
  87. package/src/lib/session-import/types.ts +12 -0
  88. package/.next/static/chunks/4632.112d2e893d48d188.js +0 -1
  89. package/assets/showcase.png +0 -0
  90. package/bin/pi.js +0 -50
  91. /package/.next/static/{LOFl9bqqMV2goBV8erESO → DdBwPYoHBKtaJ97QIr6Co}/_buildManifest.js +0 -0
  92. /package/.next/static/{LOFl9bqqMV2goBV8erESO → DdBwPYoHBKtaJ97QIr6Co}/_ssgManifest.js +0 -0
@@ -0,0 +1 @@
1
+ (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[4632],{901:e=>{e.exports={mask:"ProviderSetupModal_mask__wwU3u",dialog:"ProviderSetupModal_dialog__BxSeI",builtinDialog:"ProviderSetupModal_builtinDialog__vA7_B",header:"ProviderSetupModal_header__Nvgmb",title:"ProviderSetupModal_title__ZIIXp",body:"ProviderSetupModal_body__QAlNu",builtinBody:"ProviderSetupModal_builtinBody___4EFo",field:"ProviderSetupModal_field__ZMO8M",label:"ProviderSetupModal_label__4_BYS",hint:"ProviderSetupModal_hint__yCwPV",input:"ProviderSetupModal_input__YZYV5",select:"ProviderSetupModal_select___PTpP",providerTrigger:"ProviderSetupModal_providerTrigger__TXtau",picker:"ProviderSetupModal_picker__VQdQc",providerText:"ProviderSetupModal_providerText__l9bwJ",providerName:"ProviderSetupModal_providerName__Hwwfg",providerMeta:"ProviderSetupModal_providerMeta____3za",menu:"ProviderSetupModal_menu__zO5CU",searchWrap:"ProviderSetupModal_searchWrap__5yw1r",searchIcon:"ProviderSetupModal_searchIcon__BZeD1",search:"ProviderSetupModal_search__j_n_8",providerList:"ProviderSetupModal_providerList__bMnFj",providerRow:"ProviderSetupModal_providerRow__Zf7fg",selectedMark:"ProviderSetupModal_selectedMark___8UDb",empty:"ProviderSetupModal_empty__4V1WK",advanced:"ProviderSetupModal_advanced__kWaTH",advancedButton:"ProviderSetupModal_advancedButton__efHwl",catalog:"ProviderSetupModal_catalog__mXakU",catalogHeader:"ProviderSetupModal_catalogHeader__0MDA4",catalogStatus:"ProviderSetupModal_catalogStatus__JRz0P",discoverButton:"ProviderSetupModal_discoverButton__GGuZX",discoverControls:"ProviderSetupModal_discoverControls___0_l8",allowPrivate:"ProviderSetupModal_allowPrivate__zZyZi",modelEmpty:"ProviderSetupModal_modelEmpty__h1N_8",modelList:"ProviderSetupModal_modelList__jkYVz",modelRow:"ProviderSetupModal_modelRow__mHfRv",removeModel:"ProviderSetupModal_removeModel___LjE1",addModel:"ProviderSetupModal_addModel__Q3KOU",error:"ProviderSetupModal_error__EAOK6",footer:"ProviderSetupModal_footer__zVp_c",footerButton:"ProviderSetupModal_footerButton__FL58k",primary:"ProviderSetupModal_primary__ArzeF",modelEntry:"ProviderSetupModal_modelEntry__G067u",rowToggle:"ProviderSetupModal_rowToggle__kc_Za",capacityRow:"ProviderSetupModal_capacityRow__0miDX",capacityField:"ProviderSetupModal_capacityField___TX70",capacityHint:"ProviderSetupModal_capacityHint__z_5re",rowError:"ProviderSetupModal_rowError__2vHrG",catalogError:"ProviderSetupModal_catalogError__ZL5D7",candidateMask:"ProviderSetupModal_candidateMask__YUZn7",candidateDialog:"ProviderSetupModal_candidateDialog__upECk",candidateHeader:"ProviderSetupModal_candidateHeader__bUvHV",candidateList:"ProviderSetupModal_candidateList__JRufC",candidateRow:"ProviderSetupModal_candidateRow__Omm_o",candidateId:"ProviderSetupModal_candidateId__7Hy7u",candidateName:"ProviderSetupModal_candidateName__D4rXE",candidateActions:"ProviderSetupModal_candidateActions__iptOe",candidateAll:"ProviderSetupModal_candidateAll__yhD_R",candidatePicked:"ProviderSetupModal_candidatePicked__cJ78H"}},4632:(e,a,t)=>{"use strict";t.r(a),t.d(a,{SettingsPanel:()=>z});var s=t(5155),r=t(2115),l=t(7650),i=t(560),n=t(9992);let o=[[/^amazon-bedrock$/,"bedrock-color"],[/^ant-ling$/,"antgroup-color"],[/^anthropic$/,"anthropic"],[/^azure-/,"azure-color"],[/^baseten$/,"baseten"],[/^cerebras$/,"cerebras-color"],[/^cloudflare-/,"cloudflare-color"],[/^deepseek$/,"deepseek-color"],[/^fireworks$/,"fireworks-color"],[/^github-copilot$/,"githubcopilot"],[/^google-vertex(?:-|$)/,"googlecloud-color"],[/^google$/,"google-color"],[/^groq$/,"groq"],[/^huggingface$/,"huggingface-color"],[/^kimi(?:-|$)/,"kimi-color"],[/^minimax/,"minimax-color"],[/^mistral$/,"mistral-color"],[/^moonshot(?:ai)?(?:-|$)/,"moonshot"],[/^nvidia$/,"nvidia-color"],[/^openai/,"openai"],[/^opencode(?:-|$)/,"opencode"],[/^openrouter$/,"openrouter-color"],[/^qwen(?:-|$)/,"qwen-color"],[/^together$/,"together-color"],[/^vercel(?:-|$)/,"vercel"],[/^xai$/,"xai"],[/^xiaomi(?:-|$)/,"xiaomimimo"],[/^zai(?:-|$)/,"zai"]];[...new Set(o.map(([,e])=>e))];let d=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,c=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function u(e){let a=new Set(c);return[...c,...[...new Set(e.filter(e=>e&&!a.has(e)))].sort()]}function p({id:e,name:a,size:t=36}){let r,l=o.find(([a])=>a.test(e))?.[1]??null;return(0,s.jsx)("span",{"aria-hidden":"true",className:"inline-flex flex-none items-center justify-center overflow-hidden",style:{width:t,height:t,borderRadius:Math.max(10,Math.round(.3*t)),background:"#f7f7f5",border:"0.5px solid rgba(0,0,0,.09)",color:"#18191b",fontSize:Math.max(10,Math.round(.32*t)),fontWeight:750,letterSpacing:"-0.03em"},children:l?(0,s.jsx)("img",{src:`/provider-icons/${l}.svg`,alt:"",width:Math.round(.66*t),height:Math.round(.66*t)}):(r=a.trim().split(/[\s_-]+/).filter(Boolean)).length>=2?(r[0][0]+r[1][0]).toUpperCase():(r[0]??e).slice(0,2).toUpperCase()})}var m=t(1859);function h(e){let a=e&&"object"==typeof e&&!Array.isArray(e)?e:{id:"string"==typeof e?e:""};return{id:String(a.id??""),name:"string"==typeof a.name?a.name:"",contextWindow:"number"==typeof a.contextWindow?a.contextWindow:void 0,maxTokens:"number"==typeof a.maxTokens?a.maxTokens:void 0,source:a}}function x(e){let a=new Set;for(let t=0;t<e.length;t+=1){let s=e[t],r=s.id.trim();if(!r||a.has(r))return{index:t,reason:"id"};if(a.add(r),[s.contextWindow,s.maxTokens].some(e=>void 0!==e&&(!Number.isSafeInteger(e)||e<=0)))return{index:t,reason:"capacity"}}}function v(e){let a={...e.source},t=e.source?h(e.source):void 0;for(let s of["id","name","contextWindow","maxTokens"]){if(t&&Object.is(e[s],t[s]))continue;let r=e[s];if("id"===s||"name"===s){let e="string"==typeof r?r.trim():"";"id"===s||e?a[s]=e:delete a[s]}else"number"==typeof r&&Number.isSafeInteger(r)&&r>0?a[s]=r:delete a[s]}return a}function f(e,a,t){let s={...e};for(let t of["baseUrl","name","api"]){let r=a[t];void 0!==r&&r!==("string"==typeof e[t]?e[t]:"")&&(r.trim()?s[t]=r.trim():delete s[t])}return a.apiKey?.trim()&&(s.apiKey=a.apiKey.trim()),(a.models.length||Object.prototype.hasOwnProperty.call(e,"models"))&&(s.models=a.models.map(v)),a.models.length&&void 0===e.models&&void 0===s.api&&t&&(s.api=t),s}var g=t(901),b=t.n(g);function y({mode:e,providers:a,existingIds:t,onClose:l,onSaveBuiltin:i,onSaveCustom:o,onOAuthLogin:c}){let{t:h}=(0,m.s)(),[f,g]=(0,r.useState)(a[0]?.id??""),[j,S]=(0,r.useState)(!1),[N,k]=(0,r.useState)(""),[C,_]=(0,r.useState)("api_key"),[z,P]=(0,r.useState)(""),[M,E]=(0,r.useState)(!1),[T,$]=(0,r.useState)(""),[R,D]=(0,r.useState)(""),[L,F]=(0,r.useState)(""),A=u(a.flatMap(e=>e.apis)),[W,O]=(0,r.useState)(A.includes("openai-completions")?"openai-completions":A[0]??"openai-completions"),[I,U]=(0,r.useState)([]),[B,K]=(0,r.useState)(!1),[H,J]=(0,r.useState)(""),q=(0,r.useRef)(null),G=a.find(e=>e.id===f),Q=a.filter(e=>{let a=N.trim().toLocaleLowerCase();return!a||e.name.toLocaleLowerCase().includes(a)||e.id.toLocaleLowerCase().includes(a)});(0,r.useEffect)(()=>{let e=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),j?S(!1):l())};return document.addEventListener("keydown",e,!0),()=>document.removeEventListener("keydown",e,!0)},[l,j]),(0,r.useEffect)(()=>{if(!j)return;let e=e=>{q.current?.contains(e.target)||S(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[j]);let V=(e,a)=>{U(t=>t.map((t,s)=>s===e?{...t,...a}:t))},X=x(I),Z=R.trim(),Y=d.test(Z),ee=Y&&!t.includes(Z)&&!!T.trim()&&I.length>0&&!X,ea=!!G&&("oauth"===C||!X),et=(0,r.useRef)(!1),es=async()=>{if(!et.current&&("builtin"===e?ea:ee)){et.current=!0,K(!0),J("");try{let a;if("builtin"===e&&G)if("oauth"===C&&c)a=await c(G.id);else{let e={};T.trim()&&(e.baseUrl=T.trim()),I.length&&(e.api=G.apis[0]??"openai-completions",e.models=I.map(v)),a=await i({providerId:G.id,apiKey:z.trim(),config:e})}else a=await o({providerId:Z,config:{name:L.trim()||Z,baseUrl:T.trim(),api:W,...z.trim()?{apiKey:z.trim()}:{},models:I.map(v)}});a.success?l():J(a.error||h.toastError)}catch(e){J(e instanceof Error?e.message:h.toastError)}finally{et.current=!1,K(!1)}}},er=async a=>{if(!T.trim())throw Error(h.apiAddress);let t=await fetch("/api/models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"discoverModels",baseUrl:T.trim(),api:"builtin"===e?G?.apis[0]:W,apiKey:z.trim(),providerId:"builtin"===e?G?.id:void 0,allowPrivate:a})}),s=await t.json();if(!t.ok||!s.success)throw Error(s.error||h.toastError);return(s.data.models??[]).map(e=>({id:e.id,name:e.name??""}))};return(0,s.jsx)("div",{className:b().mask,"data-provider-modal":"true",onMouseDown:e=>{e.target===e.currentTarget&&l()},children:(0,s.jsxs)("section",{className:`${b().dialog} ${"builtin"===e?b().builtinDialog:""}`,role:"dialog","aria-modal":"true","aria-labelledby":"provider-setup-title",children:[(0,s.jsxs)("header",{className:b().header,children:[(0,s.jsx)("h2",{id:"provider-setup-title",className:b().title,children:"builtin"===e?h.addProvider:h.customProviderTitle}),(0,s.jsx)("button",{className:"icon-btn",title:h.close,"aria-label":h.close,onClick:l,children:(0,s.jsx)(n.Bh,{size:17})})]}),(0,s.jsxs)("div",{className:`${b().body} ${"builtin"===e?b().builtinBody:""}`,children:["builtin"===e?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("div",{className:b().field,children:[(0,s.jsx)("label",{className:b().label,children:h.providerLabel}),(0,s.jsxs)("div",{className:b().picker,ref:q,children:[(0,s.jsxs)("button",{className:b().providerTrigger,"data-open":j,onClick:()=>S(e=>!e),children:[G?(0,s.jsx)(p,{id:G.id,name:G.name,size:34}):null,(0,s.jsxs)("span",{className:b().providerText,children:[(0,s.jsx)("span",{className:b().providerName,children:G?.name??h.selectProvider}),G?(0,s.jsx)("span",{className:b().providerMeta,children:G.id}):null]}),(0,s.jsx)(n.Cd,{size:15})]}),j?(0,s.jsxs)("div",{className:b().menu,children:[(0,s.jsxs)("div",{className:b().searchWrap,children:[(0,s.jsx)("span",{className:b().searchIcon,children:(0,s.jsx)(n.FG,{size:15})}),(0,s.jsx)("input",{autoFocus:!0,className:b().search,value:N,onChange:e=>k(e.target.value),placeholder:h.searchProviders})]}),(0,s.jsxs)("div",{className:b().providerList,children:[Q.map(e=>(0,s.jsxs)("button",{className:b().providerRow,"data-selected":e.id===f,onClick:()=>{g(e.id),_("api_key"),P(""),O(e.apis[0]??"openai-completions"),$(""),U([]),S(!1)},children:[(0,s.jsx)(p,{id:e.id,name:e.name,size:38}),(0,s.jsxs)("span",{className:b().providerText,children:[(0,s.jsx)("span",{className:b().providerName,children:e.name}),(0,s.jsxs)("span",{className:b().providerMeta,children:[e.id," \xb7 ",h.modelCount.replace("{count}",String(e.modelCount))]})]}),e.id===f?(0,s.jsx)("span",{className:b().selectedMark,children:(0,s.jsx)(n.df,{size:16})}):null]},e.id)),0===Q.length?(0,s.jsx)("div",{className:b().empty,children:h.noProviderMatches}):null]})]}):null]})]}),G?.authTypes.includes("oauth")&&c?(0,s.jsxs)("div",{className:b().field,children:[(0,s.jsx)("label",{className:b().label,children:h.authMethod}),(0,s.jsxs)("select",{className:b().select,value:C,onChange:e=>_(e.target.value),children:[(0,s.jsx)("option",{value:"api_key",children:h.authMethodApiKey}),(0,s.jsx)("option",{value:"oauth",children:h.oauthLogin})]})]}):null,"api_key"===C?(0,s.jsxs)("div",{className:b().field,children:[(0,s.jsx)("label",{className:b().label,children:G?.apiKeyLabel??h.apiKey}),(0,s.jsx)("input",{className:b().input,type:"password",value:z,onChange:e=>P(e.target.value),placeholder:h.apiKeyOptional})]}):null,(0,s.jsxs)("div",{className:b().advanced,children:[(0,s.jsxs)("button",{className:b().advancedButton,"data-open":M,onClick:()=>E(e=>!e),children:[(0,s.jsx)(n.Cd,{size:15}),h.customSettings]}),M?(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:b().field,children:[(0,s.jsx)("label",{className:b().label,children:h.apiAddress}),(0,s.jsx)("input",{className:b().input,value:T,onChange:e=>$(e.target.value),placeholder:G?.baseUrl||h.providerDefault})]}),(0,s.jsx)(w,{models:I,setModels:U,updateModel:V,inheritedCount:G?.modelCount??0,discover:er,discoverDisabled:!T.trim()})]}):null]})]}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("div",{className:b().field,children:[(0,s.jsx)("label",{className:b().label,children:h.providerId}),(0,s.jsx)("input",{className:b().input,autoFocus:!0,value:R,onChange:e=>D(e.target.value.toLocaleLowerCase()),placeholder:"acme-gateway"}),(0,s.jsx)("div",{className:b().hint,children:h.providerIdHint}),Z&&!Y?(0,s.jsx)("div",{className:b().hint,style:{color:"var(--dsw-danger)"},children:h.providerIdInvalid}):null,Z&&t.includes(Z)?(0,s.jsx)("div",{className:b().hint,style:{color:"var(--dsw-danger)"},children:h.providerIdTaken}):null]}),(0,s.jsxs)("div",{className:b().field,children:[(0,s.jsx)("label",{className:b().label,children:h.displayName}),(0,s.jsx)("input",{className:b().input,value:L,onChange:e=>F(e.target.value),placeholder:h.displayName})]}),(0,s.jsxs)("div",{className:b().field,children:[(0,s.jsx)("label",{className:b().label,children:h.apiAddress}),(0,s.jsx)("input",{className:b().input,value:T,onChange:e=>$(e.target.value),placeholder:"https://gateway.example/v1"})]}),(0,s.jsxs)("div",{className:b().field,children:[(0,s.jsx)("label",{className:b().label,children:h.apiProtocol}),(0,s.jsx)("select",{className:b().select,value:W,onChange:e=>O(e.target.value),children:A.map(e=>(0,s.jsx)("option",{value:e,children:e},e))})]}),(0,s.jsxs)("div",{className:b().field,children:[(0,s.jsx)("label",{className:b().label,children:h.apiKey}),(0,s.jsx)("input",{className:b().input,type:"password",value:z,onChange:e=>P(e.target.value),placeholder:h.apiKeyOptional}),(0,s.jsx)("div",{className:b().hint,children:h.customApiKeyHint})]}),(0,s.jsx)(w,{models:I,setModels:U,updateModel:V,discover:er,discoverDisabled:!T.trim()})]}),H?(0,s.jsx)("div",{className:b().error,children:H}):null]}),(0,s.jsxs)("footer",{className:b().footer,children:[(0,s.jsx)("button",{className:b().footerButton,onClick:l,children:h.cancel}),(0,s.jsx)("button",{className:`${b().footerButton} ${b().primary}`,disabled:B||("builtin"===e?!ea:!ee),onClick:es,children:B?h.saving:"builtin"===e?h.save:h.createProvider})]})]})})}function w({models:e,setModels:a,updateModel:t,inheritedCount:l,discover:i,discoverDisabled:o}){let{t:d}=(0,m.s)(),[c,u]=(0,r.useState)(new Set),[p,h]=(0,r.useState)(!1),[v,f]=(0,r.useState)(""),[g,y]=(0,r.useState)(!1),[j,S]=(0,r.useState)(null),[N,k]=(0,r.useState)(new Set),[C,_]=(0,r.useState)({}),z=(e,a,t)=>{var s;return C[`${a}:${t}`]??(void 0===(s=e[t])||!Number.isFinite(s)||s<=0?"":s>=1e6&&s%1e6==0?`${s/1e6}M`:s>=1e3&&s%1e3==0?`${s/1e3}K`:String(s))},P=(e,a,s)=>{_(t=>({...t,[`${e}:${a}`]:s})),t(e,{[a]:function(e){let a=e.trim().toLowerCase();if(!a)return;let t=/^(\d+(?:\.\d+)?)\s*([km]?)$/.exec(a);if(!t)return NaN;let s=Math.round(Number(t[1])*("k"===t[2]?1e3:"m"===t[2]?1e6:1));return Number.isSafeInteger(s)&&s>0?s:NaN}(s)})},M=async()=>{if(i&&!p){h(!0),f("");try{let a=await i(g);if(!a.length)return void f(d.discoverEmpty);let t=new Set(e.map(e=>e.id.trim()).filter(Boolean));S(a),k(new Set(a.filter(e=>!t.has(e.id.trim())).map(e=>e.id)))}catch(e){f(e instanceof Error?e.message:d.toastError)}finally{h(!1)}}},E=()=>{S(null),k(new Set)},T=j??[],$=T.length>0&&T.every(e=>N.has(e.id)),R=x(e);return(0,s.jsxs)("div",{className:b().catalog,children:[(0,s.jsxs)("div",{className:b().catalogHeader,children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{className:b().label,children:d.modelCatalog}),(0,s.jsx)("div",{className:b().catalogStatus,children:l?d.usingDefaultModels.replace("{count}",String(l)):d.customModelsRequired})]}),i?(0,s.jsxs)("div",{className:b().discoverControls,children:[(0,s.jsxs)("label",{className:b().allowPrivate,title:d.allowPrivateHint,children:[(0,s.jsx)("input",{type:"checkbox",checked:g,onChange:e=>y(e.target.checked)}),d.allowPrivateDiscovery]}),(0,s.jsx)("button",{className:b().discoverButton,disabled:o||p,onClick:()=>void M(),children:p?d.discoveringModels:d.discoverModels})]}):null]}),v?(0,s.jsx)("div",{className:b().catalogError,children:v}):null,e.length?(0,s.jsx)("div",{className:b().modelList,children:e.map((e,r)=>{let l=c.has(r),i=Number.isNaN(e.contextWindow)||Number.isNaN(e.maxTokens);return(0,s.jsxs)("div",{className:b().modelEntry,children:[(0,s.jsxs)("div",{className:b().modelRow,children:[(0,s.jsx)("button",{type:"button",className:b().rowToggle,title:d.capacityFields,onClick:()=>u(e=>{let a=new Set(e);return a.delete(r)||a.add(r),a}),children:(0,s.jsx)(n.Cd,{size:13,style:{transform:l?"rotate(0deg)":"rotate(-90deg)",transition:"transform 120ms ease"}})}),(0,s.jsx)("input",{className:b().input,style:{borderColor:e.id.trim()||R?.index!==r?void 0:"var(--dsw-danger)"},value:e.id,onChange:e=>t(r,{id:e.target.value}),placeholder:d.modelId}),(0,s.jsx)("input",{className:b().input,value:e.name,onChange:e=>t(r,{name:e.target.value}),placeholder:d.displayNameOptional}),(0,s.jsx)("button",{className:b().removeModel,title:d.delete,onClick:()=>{a(e=>e.filter((e,a)=>a!==r)),u(e=>{let a=new Set;for(let t of e)t!==r&&a.add(t>r?t-1:t);return a}),_(e=>{let a={};for(let[t,s]of Object.entries(e)){let e=Number(t.slice(0,t.indexOf(":")));e!==r&&(a[e>r?`${e-1}${t.slice(t.indexOf(":"))}`:t]=s)}return a})},children:(0,s.jsx)(n.Vd,{size:15})})]}),l?(0,s.jsxs)("div",{className:b().capacityRow,children:[(0,s.jsxs)("label",{className:b().capacityField,children:[(0,s.jsx)("span",{children:d.contextWindowLabel}),(0,s.jsx)("input",{className:b().input,style:{borderColor:Number.isNaN(e.contextWindow)?"var(--dsw-danger)":void 0},value:z(e,r,"contextWindow"),onChange:e=>P(r,"contextWindow",e.target.value),placeholder:"128K"})]}),(0,s.jsxs)("label",{className:b().capacityField,children:[(0,s.jsx)("span",{children:d.maxTokensLabel}),(0,s.jsx)("input",{className:b().input,style:{borderColor:Number.isNaN(e.maxTokens)?"var(--dsw-danger)":void 0},value:z(e,r,"maxTokens"),onChange:e=>P(r,"maxTokens",e.target.value),placeholder:"16K"})]}),(0,s.jsx)("span",{className:b().capacityHint,children:d.capacityHint})]}):null,i?(0,s.jsx)("div",{className:b().rowError,children:d.capacityInvalid.replace("{n}",String(r+1))}):null]},r)})}):(0,s.jsx)("div",{className:b().modelEmpty,children:l?d.modelCatalogEmptyBuiltin:d.modelCatalogEmptyCustom}),(0,s.jsxs)("button",{className:b().addModel,onClick:()=>a(e=>[...e,{id:"",name:""}]),children:[(0,s.jsx)(n.Xh,{size:14}),d.addModel]}),j?(0,s.jsx)("div",{className:b().candidateMask,children:(0,s.jsxs)("div",{className:b().candidateDialog,role:"dialog","aria-modal":"true","aria-label":d.discoverModels,children:[(0,s.jsx)("div",{className:b().candidateHeader,children:(0,s.jsx)("span",{children:d.candidateTitle.replace("{count}",String(j.length))})}),(0,s.jsxs)("div",{className:b().candidateList,children:[T.map(e=>(0,s.jsxs)("label",{className:b().candidateRow,children:[(0,s.jsx)("input",{type:"checkbox",checked:N.has(e.id),onChange:()=>{let a;return a=e.id,k(e=>{let t=new Set(e);return t.delete(a)||t.add(a),t})}}),(0,s.jsx)("span",{className:b().candidateId,children:e.id}),e.name?(0,s.jsx)("span",{className:b().candidateName,children:e.name}):null]},e.id)),0===T.length?(0,s.jsx)("div",{className:b().modelEmpty,children:"—"}):null]}),(0,s.jsxs)("div",{className:b().candidateActions,children:[(0,s.jsxs)("label",{className:b().candidateAll,children:[(0,s.jsx)("input",{type:"checkbox",checked:$,onChange:()=>k(e=>{let a=new Set(e);return T.every(e=>a.has(e.id))?T.forEach(e=>a.delete(e.id)):T.forEach(e=>a.add(e.id)),a})}),d.candidateAll]}),(0,s.jsx)("span",{className:b().candidatePicked,children:d.candidatePicked.replace("{n}",String(N.size))}),(0,s.jsx)("button",{className:b().footerButton,onClick:E,children:d.cancel}),(0,s.jsx)("button",{className:`${b().footerButton} ${b().primary}`,disabled:0===N.size,onClick:()=>{j&&(a(e=>{let a=new Map(e.map(e=>[e.id.trim(),e]));for(let e of j){let t=e.id.trim();!t||!N.has(t)||a.has(t)||a.set(t,{id:t,name:e.name??""})}return[...a.values()]}),E())},children:d.candidateAdopt.replace("{n}",String(N.size))})]})]})}):null]})}let j=["claude","codex","grok","zcode","dsh","opencode"],S=e=>`${e.source}:${e.externalId}`;function N({cwd:e}){let{t:a}=(0,m.s)(),[t,l]=(0,r.useState)([]),[i,o]=(0,r.useState)([]),[d,c]=(0,r.useState)(new Set),[u,p]=(0,r.useState)(new Set),[h,x]=(0,r.useState)(!1),[v,f]=(0,r.useState)(!1),[g,b]=(0,r.useState)(null),[y,w]=(0,r.useState)(null),[k,C]=(0,r.useState)([]),[_,z]=(0,r.useState)(e),P=(0,r.useCallback)(async()=>{x(!0),w(null);try{let e=await fetch("/api/sessions/import"),t=await e.json();if(!t.success)return void w(t.error||a.toastError);let s=t.data.sessions??[],r=new Set(t.data.imported??[]),i=new Set(s.map(S));l(s),o(t.data.errors??[]),c(r),p(e=>new Set([...e].filter(e=>i.has(e)&&!r.has(e))))}catch(e){w(e instanceof Error?e.message:String(e))}finally{x(!1)}},[a]);(0,r.useEffect)(()=>{(async()=>{try{let e=await (await fetch("/api/workspaces")).json();e.success&&C(e.data.workspaces??[])}catch{}})()},[]),(0,r.useEffect)(()=>{P()},[P]);let M=(0,r.useMemo)(()=>{let e=new Map;for(let a of t){let t=e.get(a.source);t?t.push(a):e.set(a.source,[a])}return j.filter(a=>e.has(a)).map(a=>{let t=[...e.get(a)].sort((e,a)=>(a.updatedAt??a.createdAt??0)-(e.updatedAt??e.createdAt??0));return{source:a,rows:t,imported:t.filter(e=>d.has(S(e))).length}})},[t,d]),[E,T]=(0,r.useState)(""),$=M.reduce((e,a)=>{let t=a.rows[0],s=t?.updatedAt??t?.createdAt??0;return!e||s>e.at?{source:a.source,at:s}:e},null)?.source??"",R=E&&M.some(e=>e.source===E)?E:$,D=M.find(e=>e.source===R),L=(e,a)=>{p(t=>{let s=new Set(t);for(let t of e)d.has(S(t))||(a?s.add(S(t)):s.delete(S(t)));return s})},F=async()=>{if(!u.size)return;let e=t.filter(e=>u.has(S(e))).map(e=>({source:e.source,externalId:e.externalId}));f(!0),w(null),b(null);try{let t=await fetch("/api/sessions/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessions:e,fallbackCwd:_||void 0})}),s=await t.json();if(!s.success)return void w(s.error||a.toastError);b(s.data),p(new Set),await P()}catch(e){w(e instanceof Error?e.message:String(e))}finally{f(!1)}},A=e=>({claude:a.importSourceClaude,codex:a.importSourceCodex,grok:a.importSourceGrok,zcode:a.importSourceZcode,dsh:a.importSourceDsh,opencode:a.importSourceOpencode})[e]??e,W=g?.results.filter(e=>"failed"===e.status)??[],O=g?.results.filter(e=>"skipped"===e.status)??[],I=g?.results.filter(e=>"imported"===e.status&&e.skipped?.length)??[];return(0,s.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"session-import",children:[(0,s.jsx)("div",{style:{fontSize:12,color:"var(--dsw-label-caption)"},children:a.importDesc}),(0,s.jsx)("div",{style:{fontSize:11.5,color:"var(--dsw-label-caption)"},title:a.importLimitHintTooltip,"data-testid":"import-limit-hint",children:a.importLimitHint.replace("{n}",String(15))}),(0,s.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,s.jsxs)("button",{className:"flex items-center gap-1.5 rounded-lg px-2.5 py-1.5",style:{fontSize:12,border:"0.5px solid var(--dsw-border-l2)"},onClick:()=>void P(),disabled:h,"data-testid":"import-rescan",children:[(0,s.jsx)(n.Ct,{size:13})," ",h?a.importScanning:a.importRescan]}),(0,s.jsx)("span",{style:{fontSize:12,color:"var(--dsw-label-caption)"},children:a.importFallbackWorkspace}),(0,s.jsx)("select",{className:"rounded-lg px-2 py-1",style:{fontSize:12,border:"0.5px solid var(--dsw-border-l2)",background:"transparent",maxWidth:260},value:_,onChange:e=>z(e.target.value),"aria-label":a.importFallbackWorkspace,"data-testid":"import-fallback",children:(k.includes(_)||!_?k:[_,...k]).map(e=>(0,s.jsx)("option",{value:e,children:e},e))}),(0,s.jsx)("div",{className:"flex-1"}),(0,s.jsx)("button",{className:"rounded-lg px-2.5 py-1.5",style:{fontSize:12,color:"var(--dsw-label-tertiary)"},onClick:()=>p(new Set),disabled:!u.size,children:a.importClearSelection}),(0,s.jsxs)("button",{className:"flex items-center gap-1.5 rounded-lg px-3 py-1.5",style:{fontSize:12,background:u.size&&!v?"var(--dsw-accent)":"var(--dsw-hover)",color:u.size&&!v?"#fff":"var(--dsw-label-caption)"},onClick:()=>void F(),disabled:!u.size||v,"data-testid":"import-run",children:[(0,s.jsx)(n.FQ,{size:13})," ",v?a.importRunning:a.importRun.replace("{n}",String(u.size))]})]}),y&&(0,s.jsx)("div",{role:"alert",className:"rounded-lg px-3 py-2",style:{fontSize:12.5,background:"var(--dsw-hover)",color:"var(--dsw-danger)"},children:y}),i.map(e=>(0,s.jsx)("div",{className:"rounded-lg px-3 py-2",style:{fontSize:12,background:"var(--dsw-hover)",color:"var(--dsw-label-tertiary)"},children:a.importSourceError.replace("{source}",A(e.source)).replace("{message}",e.message)},e.source)),g&&(0,s.jsxs)("div",{className:"rounded-2xl px-4 py-3",style:{border:"0.5px solid var(--dsw-border-l2)"},"data-testid":"import-report",children:[(0,s.jsx)("div",{style:{fontSize:13},children:a.importReportSummary.replace("{imported}",String(g.imported)).replace("{skipped}",String(g.skipped)).replace("{failed}",String(g.failed))}),O.map(e=>(0,s.jsxs)("div",{className:"mt-1",style:{fontSize:11.5,color:"var(--dsw-label-caption)"},children:[A(e.source)," \xb7 ",e.title||e.externalId," — ",e.reason]},`skip-${e.source}-${e.externalId}`)),I.map(e=>(0,s.jsxs)("div",{className:"mt-1",style:{fontSize:11.5,color:"var(--dsw-label-caption)"},children:[A(e.source)," \xb7 ",e.title||e.externalId," — ",e.skipped?.join(";")]},`note-${e.source}-${e.externalId}`)),W.map(e=>(0,s.jsxs)("div",{className:"mt-1",style:{fontSize:11.5,color:"var(--dsw-danger)"},children:[A(e.source)," \xb7 ",e.title||e.externalId," — ",e.reason]},`fail-${e.source}-${e.externalId}`))]}),!h&&!t.length&&!i.length&&(0,s.jsx)("div",{style:{fontSize:13,color:"var(--dsw-label-caption)"},children:a.importEmpty}),M.length>0&&(0,s.jsx)("div",{className:"flex flex-wrap items-center gap-1.5",role:"tablist","aria-label":a.importPickSource,"data-testid":"import-source-tabs",children:M.map(e=>{let a=e.source===R;return(0,s.jsxs)("button",{type:"button",role:"tab","aria-selected":a,className:"rounded-full px-3 py-1 transition-colors",style:{fontSize:12,border:`0.5px solid ${a?"var(--dsw-accent)":"var(--dsw-border-l2)"}`,background:a?"var(--dsw-accent)":"transparent",color:a?"#fff":"var(--dsw-label-tertiary)"},onClick:()=>T(e.source),"data-testid":`import-source-${e.source}`,children:[A(e.source),(0,s.jsx)("span",{style:{marginLeft:6,opacity:.75},children:e.rows.length})]},e.source)})}),D&&(0,s.jsxs)("div",{className:"flex flex-col gap-2","data-testid":`import-group-${D.source}`,children:[(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)("span",{style:{fontSize:11.5,color:"var(--dsw-label-caption)"},children:a.importGroupCount.replace("{n}",String(D.rows.length)).replace("{imported}",String(D.imported))}),(0,s.jsx)("div",{className:"flex-1"}),(0,s.jsx)("button",{className:"rounded-lg px-2 py-0.5",style:{fontSize:11.5,color:"var(--dsw-label-tertiary)"},onClick:()=>L(D.rows,!0),children:a.importSelectAll}),(0,s.jsx)("button",{className:"rounded-lg px-2 py-0.5",style:{fontSize:11.5,color:"var(--dsw-label-caption)"},onClick:()=>L(D.rows,!1),children:a.importSelectNone})]}),(0,s.jsx)("div",{className:"flex flex-col gap-1.5",children:D.rows.map(e=>{let t=S(e),r=d.has(t),l=u.has(t);return(0,s.jsxs)("label",{className:"flex cursor-pointer items-center gap-3 rounded-xl px-3 py-2",style:{border:`0.5px solid ${l?"var(--dsw-accent)":"var(--dsw-border-l2)"}`,opacity:r?.55:1},children:[(0,s.jsx)("input",{type:"checkbox",checked:l,disabled:r,onChange:()=>{!d.has(S(e))&&p(a=>{let t=new Set(a);return t.has(S(e))?t.delete(S(e)):t.add(S(e)),t})}}),(0,s.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,s.jsx)("div",{className:"truncate",style:{fontSize:12.5},title:e.title,children:e.title||a.importUntitled}),(0,s.jsx)("div",{className:"truncate",style:{fontSize:11,color:"var(--dsw-label-caption)"},title:e.projectPath,children:e.projectPath||a.importNoProject})]}),r&&(0,s.jsx)("span",{className:"rounded-full px-2 py-0.5",style:{fontSize:10,background:"var(--dsw-hover)",color:"var(--dsw-label-caption)"},children:a.importAlready}),(0,s.jsx)("span",{style:{fontSize:11,color:"var(--dsw-label-caption)",whiteSpace:"nowrap"},children:"number"==typeof e.messageCount?a.importMessages.replace("{n}",String(e.messageCount)):"—"}),(0,s.jsx)("span",{style:{fontSize:11,color:"var(--dsw-label-caption)",whiteSpace:"nowrap"},children:function(e){if(!e)return"";let a=new Date(e);if(Number.isNaN(a.getTime()))return"";let t=e=>String(e).padStart(2,"0");return`${a.getFullYear()}-${t(a.getMonth()+1)}-${t(a.getDate())}`}(e.updatedAt??e.createdAt)})]},t)})})]})]})}var k=t(6540);let C=["xai","openai-codex","anthropic","deepseek","openrouter","moonshotai","moonshotai-cn","kimi-coding","github-copilot","vercel-ai-gateway","opencode-go"];function _(e){return C.includes(e)}function z({open:e,onClose:a,cwd:t,toolPreset:l,onToolPresetChange:i,tools:o,onSetTools:d,onOpenFileContent:c}){let{t:u,lang:p,setLang:h}=(0,m.s)(),[x,v]=(0,r.useState)("general");if((0,r.useEffect)(()=>{if(!e)return;let t=e=>{"Escape"!==e.key||document.querySelector('[data-provider-modal="true"]')||a()};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[e,a]),!e)return null;let f=[{id:"general",label:u.setGeneral,icon:(0,s.jsx)(n.Ec,{size:15})},{id:"models",label:u.setModels,icon:(0,s.jsx)(n.se,{size:15})},{id:"tools",label:u.toolsSection,icon:(0,s.jsx)(n.DI,{size:15})},{id:"plugins",label:u.setPlugins,icon:(0,s.jsx)(n.q2,{size:15})},{id:"skills",label:u.setSkills,icon:(0,s.jsx)(n.i7,{size:15})},{id:"import",label:u.importSessions,icon:(0,s.jsx)(n.FQ,{size:15})}];return(0,s.jsx)("div",{className:"modal-mask fixed inset-0 z-[100] flex items-center justify-center",onMouseDown:e=>{e.target===e.currentTarget&&a()},children:(0,s.jsxs)("div",{className:"settings-dialog glass-modal flex overflow-hidden",style:{width:800,maxWidth:"calc(100vw - 48px)",height:"min(800px, calc(100vh - 48px))",borderRadius:32,boxShadow:"var(--dsw-elevation-prominent)"},children:[(0,s.jsxs)("div",{className:"settings-nav flex w-52 flex-none flex-col gap-0.5 py-4 pl-4 pr-3",children:[(0,s.jsx)("div",{className:"settings-title px-2 pb-3",style:{fontSize:16,fontWeight:500},children:u.settings}),f.map(e=>(0,s.jsxs)("button",{className:"flex h-[42px] items-center gap-2 rounded-xl px-3 text-left transition-colors",style:{paddingLeft:8,paddingRight:10,fontSize:14,background:x===e.id?"var(--dsw-active)":"transparent",color:x===e.id?"var(--dsw-label-primary)":"var(--dsw-label-secondary)"},onMouseEnter:a=>{x!==e.id&&(a.currentTarget.style.background="var(--dsw-hover)")},onMouseLeave:a=>{x!==e.id&&(a.currentTarget.style.background="transparent")},onClick:()=>v(e.id),children:[x===e.id?(0,s.jsx)("span",{style:{color:"var(--dsw-accent)"},children:e.icon}):e.icon,e.label]},e.id))]}),(0,s.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col",children:[(0,s.jsxs)("div",{className:"flex items-center gap-2 px-6 py-3.5",children:[(0,s.jsx)("div",{className:"flex-1"}),(0,s.jsxs)("button",{className:"btn-outline",style:{height:32,fontSize:13},onClick:()=>window.open("/api/config","_blank"),children:[(0,s.jsx)(n.FQ,{size:14})," ",u.openConfigFile]}),(0,s.jsx)("button",{className:"icon-btn",onClick:a,children:(0,s.jsx)(n.Bh,{size:15})})]}),(0,s.jsxs)("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-5",children:["general"===x&&(0,s.jsx)(P,{lang:p,setLang:h}),"models"===x&&(0,s.jsx)(L,{}),"skills"===x&&(0,s.jsx)(B,{cwd:t,onOpenFileContent:c}),"tools"===x&&(0,s.jsx)(U,{toolPreset:l,onToolPresetChange:i,tools:o,onSetTools:d}),"plugins"===x&&(0,s.jsx)(K,{cwd:t}),"import"===x&&(0,s.jsx)(N,{cwd:t})]})]})]})})}function P({lang:e,setLang:a}){let{t}=(0,m.s)(),[l,n]=(0,r.useState)("dsh"),[o,d]=(0,r.useState)("system"),[c,u]=(0,r.useState)(14),[p,h]=(0,r.useState)(14),[x,v]=(0,r.useState)("steer"),[f,g]=(0,r.useState)("ask"),[b,y]=(0,r.useState)(!1),[w,j]=(0,r.useState)(null),[S,N]=(0,r.useState)(null),[C,_]=(0,r.useState)(null),[z,L]=(0,r.useState)(!0),[F,A]=(0,r.useState)(!1),[W,O]=(0,r.useState)(null),[I,U]=(0,r.useState)({reserveTokens:"",keepRecentTokens:"",maxRetries:"",baseDelayMs:""}),B=async()=>{L(!0),O(null),y(!1);let e=async e=>{let a=await fetch(e),t=await a.json();if(!a.ok||!t.success)throw Error(t.error||`request failed (${a.status})`);return t.data},[a,t,s,r]=await Promise.allSettled([e("/api/security"),e("/api/pi-settings"),e("/api/version"),e("/api/web-auth")]);"fulfilled"===a.status&&(g(a.value.defaultProjectTrust),y(!0)),"fulfilled"===t.status?(j(t.value),U({reserveTokens:String(t.value.compaction.reserveTokens),keepRecentTokens:String(t.value.compaction.keepRecentTokens),maxRetries:String(t.value.retry.maxRetries),baseDelayMs:String(t.value.retry.baseDelayMs)})):j(null),"fulfilled"===s.status&&s.value?.piWeb?N({piWeb:s.value.piWeb,piEngine:s.value.piEngine}):N(null),"fulfilled"===r.status&&"boolean"==typeof r.value?.enabled?_({enabled:r.value.enabled,authenticated:!0===r.value.authenticated}):_(null),[a,t,s].some(e=>"rejected"===e.status)&&O("load"),L(!1)};(0,r.useEffect)(()=>{n((0,k.m6)()),d((0,k.Xf)());let e=parseInt(localStorage.getItem("piweb.fontSize")??"14",10);Number.isNaN(e)||u(e);let a=parseInt(localStorage.getItem("piweb.chatFontSize")??"14",10);Number.isNaN(a)||h(a),v((0,i.$h)()),B()},[]);let K=async e=>{if(!w||F)return!1;A(!0),O(null);try{let a=await fetch("/api/pi-settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),t=await a.json();if(!a.ok||!t.success)throw Error(t.error||"save failed");return j(t.data),!0}catch{return O("save"),!1}finally{A(!1)}},H=async(e,a)=>{if(!w)return;let t=I[a].trim(),s=Number(t);!t||!Number.isSafeInteger(s)||s<0||s>1e9?O("save"):s!==w[e][a]&&await K({[e]:{[a]:s}})},J=(e,a,t)=>(0,s.jsx)("input",{type:"number",min:0,value:I[a],disabled:!w||z||F,onChange:e=>U(t=>({...t,[a]:e.target.value})),onBlur:()=>void H(e,a),onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()},className:"rounded-lg px-2 py-1",title:t,style:{width:90,textAlign:"right",background:"var(--dsw-hover)"}}),q=async e=>{if(b&&!F){A(!0),O(null);try{let a=await fetch("/api/security",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultProjectTrust:e})}),t=await a.json();if(!a.ok||!t.success)throw Error(t.error||"save failed");g(e)}catch{O("save")}finally{A(!1)}}},G=[{id:"dsh",label:t.themeDsh,light:"#F9FAFB",dark:"#151517",accent:"#4176E6"},{id:"silver-steel",label:t.themeSilverSteel,light:"#F3F4F6",dark:"#1A1C24",accent:"#94A3B8"},{id:"limestone-coal",label:t.themeLimestoneCoal,light:"#F0EFEB",dark:"#171717",accent:"#CEB27E"},{id:"linen-moss",label:t.themeLinenMoss,light:"#F2F2EC",dark:"#1E211E",accent:"#A3B3A3"},{id:"nord-paper",label:t.themeNordPaper,light:"#FCFBF9",dark:"#2E3440",accent:"#88C0D0"},{id:"pebrel",label:t.themePebrel,light:"#F3F4F6",dark:"#0F111A",accent:"#52A8FF"}];return(0,s.jsxs)("div",{className:"flex flex-col gap-6",children:[(z||W)&&(0,s.jsxs)("div",{role:W?"alert":"status",className:"flex items-center gap-3 rounded-lg px-3 py-2",style:{background:"var(--dsw-hover)",color:W?"var(--dsw-danger)":"var(--dsw-label-secondary)"},children:[(0,s.jsx)("span",{className:"flex-1",children:"load"===W?t.settingsLoadFailed:"save"===W?t.settingsSaveFailed:t.settingsLoading}),"load"===W&&(0,s.jsx)("button",{type:"button",className:"pw-chip",onClick:()=>void B(),children:t.settingsRetry})]}),(0,s.jsx)($,{title:t.language,children:(0,s.jsx)(T,{value:e,options:[{value:"zh",label:"中文"},{value:"en",label:"English"}],onChange:e=>a(e)})}),(0,s.jsx)(R,{title:t.appearance,children:(0,s.jsx)("div",{className:"flex w-full flex-wrap gap-2",children:G.map(e=>(0,s.jsxs)("button",{className:"flex flex-col items-center justify-center gap-1 transition-colors",style:{flex:"1 1 150px",padding:"20px 32px",borderRadius:20,border:`0.5px solid ${l===e.id?"var(--dsw-border-strong)":"var(--dsw-border-l4)"}`,background:l===e.id?"var(--dsw-module-platform)":"transparent",color:"var(--dsw-label-primary)",fontSize:14,lineHeight:"22px"},"aria-pressed":l===e.id,onClick:()=>{var a;n(a=e.id),(0,k.kK)(a,o)},children:[(0,s.jsxs)("span",{className:"flex items-center overflow-hidden rounded-md",style:{border:"0.5px solid var(--dsw-border-l3)",width:42,height:20},children:[(0,s.jsx)("span",{style:{background:e.light,flex:1,height:"100%"}}),(0,s.jsx)("span",{style:{background:e.dark,flex:1,height:"100%"}})]}),(0,s.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,s.jsx)("span",{className:"inline-block rounded-full",style:{width:8,height:8,background:e.accent}}),e.label]})]},e.id))})}),(0,s.jsx)(R,{title:t.appearanceMode,children:(0,s.jsx)("div",{className:"flex w-full flex-wrap gap-2",children:[{id:"light",label:t.themeLight},{id:"dark",label:t.themeDark},{id:"system",label:t.themeSystem}].map(e=>(0,s.jsx)("button",{className:"flex flex-col items-center justify-center gap-1 transition-colors",style:{flex:"1 1 120px",padding:"16px 24px",borderRadius:20,border:`0.5px solid ${o===e.id?"var(--dsw-border-strong)":"var(--dsw-border-l4)"}`,background:o===e.id?"var(--dsw-module-platform)":"transparent",color:"var(--dsw-label-primary)",fontSize:14,lineHeight:"22px"},"aria-pressed":o===e.id,onClick:()=>{var a;d(a=e.id),(0,k.kK)(l,a)},children:e.label},e.id))})}),(0,s.jsx)($,{title:t.fontUiSize,desc:t.fontUiSizeDesc,children:(0,s.jsx)(D,{value:c,onChange:e=>{let a=Math.max(12,Math.min(18,e));u(a),localStorage.setItem("piweb.fontSize",String(a)),document.documentElement.style.setProperty("--dsh-content-font-size",`${a}px`),document.documentElement.style.setProperty("--dsh-content-font-delta",`${a-14}px`)},max:18})}),(0,s.jsx)($,{title:t.fontChatSize,desc:t.fontChatSizeDesc,children:(0,s.jsx)(D,{value:p,onChange:e=>{let a=Math.max(12,Math.min(20,e));h(a),localStorage.setItem("piweb.chatFontSize",String(a)),document.documentElement.style.setProperty("--piweb-chat-font-size",`${a}px`)},max:20})}),(0,s.jsx)($,{title:t.enterBehavior,desc:t.enterBehaviorDesc,children:(0,s.jsx)(T,{value:x,options:[{value:"steer",label:t.enterSteer},{value:"queue",label:t.enterQueue}],onChange:e=>{v(e),(0,i.vf)(e)}})}),(0,s.jsx)($,{title:t.autoCompact,desc:t.autoCompactDesc,children:(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)("button",{disabled:!w||F,className:"relative h-5 w-9 flex-none rounded-full transition-colors",style:{background:w?.compaction.enabled?"var(--dsw-accent)":"var(--dsw-border-l3)"},role:"switch","aria-checked":w?.compaction.enabled??!1,onClick:()=>void K({compaction:{enabled:!w?.compaction.enabled}}),children:(0,s.jsx)("span",{className:"absolute top-0.5 h-4 w-4 rounded-full bg-white transition-all",style:{left:w?.compaction.enabled?18:2}})}),J("compaction","reserveTokens",t.reserveTokens),J("compaction","keepRecentTokens",t.keepRecentTokens)]})}),(0,s.jsx)($,{title:t.autoRetry,desc:t.autoRetryDesc,children:(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)("button",{disabled:!w||F,className:"relative h-5 w-9 flex-none rounded-full transition-colors",style:{background:w?.retry.enabled?"var(--dsw-accent)":"var(--dsw-border-l3)"},role:"switch","aria-checked":w?.retry.enabled??!1,onClick:()=>void K({retry:{enabled:!w?.retry.enabled}}),children:(0,s.jsx)("span",{className:"absolute top-0.5 h-4 w-4 rounded-full bg-white transition-all",style:{left:w?.retry.enabled?18:2}})}),J("retry","maxRetries",t.maxRetries),J("retry","baseDelayMs",t.baseDelayMs)]})}),(0,s.jsx)($,{title:t.securityTrust,desc:t.securityTrustDesc,children:(0,s.jsx)(T,{value:f,disabled:!b||z||F,options:[{value:"ask",label:t.trustAsk},{value:"always",label:t.trustAlways},{value:"never",label:t.trustNever}],onChange:e=>q(e)})}),(0,s.jsx)($,{title:t.versionPiweb,desc:t.versionPiwebDesc,children:(0,s.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,s.jsx)(M,{href:"https://github.com/RexVane/PiWeb",value:S?.piWeb}),(0,s.jsx)(E,{target:"piweb"})]})}),(0,s.jsx)($,{title:t.versionPi,desc:t.versionPiDesc,children:(0,s.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,s.jsx)(M,{href:"https://github.com/earendil-works/pi",value:S?.piEngine}),(0,s.jsx)(E,{target:"pi"})]})}),C?.enabled?(0,s.jsx)($,{title:t.webAuth,desc:t.webAuthOn,children:(0,s.jsx)("button",{className:"btn-outline",style:{height:30,padding:"0 14px",fontSize:12.5},onClick:async()=>{await fetch("/api/web-auth",{method:"DELETE"}).catch(()=>{}),window.location.href="/login"},children:t.logout})}):null]})}function M({href:e,value:a}){return(0,s.jsx)("a",{href:e,target:"_blank",rel:"noreferrer",style:{fontFamily:"var(--font-mono)",fontSize:13,color:"var(--dsw-label-secondary)",textDecoration:"none"},onMouseEnter:e=>e.currentTarget.style.color="var(--dsw-accent)",onMouseLeave:e=>e.currentTarget.style.color="var(--dsw-label-secondary)",children:a??"—"})}function E({target:e}){let{t:a}=(0,m.s)(),[t,l]=(0,r.useState)("idle"),[i,n]=(0,r.useState)(""),[o,d]=(0,r.useState)(""),[c,u]=(0,r.useState)(""),p=async a=>(await fetch("/api/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:e,action:a})})).json(),h=async()=>{l("checking"),u("");try{let e=await p("check");if(!e.success)throw Error(e.error);e.data.canUpdate?(n(e.data.latest),d(e.data.command??""),l("available")):l("latest")}catch(e){u(String(e?.message??e)),l("error")}},x=async()=>{l("updating");try{let e=await p("update");if(!e.success)throw Error(e.error);n(e.data.version??i),l("updated")}catch(e){u(String(e?.message??e)),l("error")}};if("idle"===t||"latest"===t||"error"===t){let e="latest"===t?a.upToDate:"error"===t?a.updateFailed:a.checkUpdate;return(0,s.jsx)("button",{type:"button",className:"btn-outline",style:{height:26,padding:"0 10px",fontSize:12,color:"latest"===t?"var(--dsw-label-tertiary)":"error"===t?"var(--dsw-danger)":"var(--dsw-label-primary)"},title:c||void 0,disabled:"checking"===t||"updating"===t,onClick:()=>void h(),children:e})}return"available"===t?o?(0,s.jsxs)("span",{className:"flex flex-col items-end gap-0.5",style:{maxWidth:300},children:[(0,s.jsx)("code",{style:{fontSize:11,color:"var(--dsw-label-primary)",whiteSpace:"nowrap",overflowX:"auto",maxWidth:"100%"},children:o}),(0,s.jsx)("span",{style:{fontSize:11,color:"var(--dsw-label-tertiary)",textAlign:"right"},children:a.updateManualHint})]}):(0,s.jsx)("button",{type:"button",className:"btn-primary-white",style:{height:26,padding:"0 12px",fontSize:12},onClick:()=>void x(),children:a.updateTo.replace("{v}",i)}):"updated"===t?(0,s.jsx)("span",{style:{fontSize:12,color:"var(--dsw-success)",maxWidth:260,textAlign:"right"},children:a.updatedTo.replace("{v}",i)}):(0,s.jsxs)("span",{className:"flex items-center gap-1.5",style:{fontSize:12,color:"var(--dsw-label-tertiary)"},children:[(0,s.jsx)("span",{className:"h-3 w-3 flex-none animate-spin rounded-full border-2 border-current border-t-transparent"}),"updating"===t?a.updatingNow:a.checkingUpdate]})}function T({value:e,options:a,onChange:t,width:i,disabled:o}){let[d,c]=(0,r.useState)(!1),[u,p]=(0,r.useState)(null),m=(0,r.useRef)(null),h=(0,r.useRef)(null);(0,r.useEffect)(()=>{if(!d)return;let e=m.current?.getBoundingClientRect();e&&p({left:e.left,top:e.bottom+6,bottom:e.top-6});let a=e=>{m.current?.contains(e.target)||h.current?.contains(e.target)||c(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[d]),(0,r.useEffect)(()=>{o&&c(!1)},[o]);let x=a.find(a=>a.value===e);return(0,s.jsxs)("div",{className:"relative",children:[(0,s.jsxs)("button",{ref:m,className:"select-chip","data-open":d,disabled:o,onClick:()=>c(e=>!e),children:[x?.label??e,(0,s.jsx)("span",{className:"chevron",children:(0,s.jsx)(n.Cd,{size:14})})]}),d&&!o&&u&&(0,l.createPortal)((0,s.jsx)("div",{ref:h,className:"popover fixed z-[130] p-1.5 shadow-xl",style:{left:u.left,top:Math.min(u.top,window.innerHeight-40),minWidth:i??140,width:"max-content",maxHeight:280,overflowY:"auto"},children:a.map(a=>{let r=a.value===e;return(0,s.jsxs)("button",{className:"flex w-full items-center justify-between gap-3 rounded-xl px-3.5 py-2 text-left transition-colors",style:{background:r?"var(--dsw-accent-soft)":"transparent"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--dsw-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="transparent")},onClick:()=>{t(a.value),c(!1)},children:[(0,s.jsx)("span",{style:{fontSize:13.5,color:r?"var(--dsw-accent)":"var(--dsw-label-primary)",whiteSpace:"nowrap"},children:a.label}),r&&(0,s.jsx)("span",{style:{display:"inline-flex",color:"var(--dsw-accent)",flex:"none"},children:(0,s.jsx)(n.df,{size:14})})]},a.value)})}),document.body)]})}function $({title:e,desc:a,children:t}){return(0,s.jsxs)("div",{className:"hairline-b flex items-center justify-between gap-6 pb-5",children:[(0,s.jsxs)("div",{className:"min-w-0",children:[(0,s.jsx)("div",{style:{fontSize:14,fontWeight:400},children:e}),a&&(0,s.jsx)("div",{className:"mt-0.5",style:{fontSize:12,color:"var(--dsw-label-caption)"},children:a})]}),(0,s.jsx)("div",{className:"flex-none",children:t})]})}function R({title:e,desc:a,children:t}){return(0,s.jsxs)("div",{className:"hairline-b flex flex-col gap-3 pb-5",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{style:{fontSize:14,fontWeight:400},children:e}),a&&(0,s.jsx)("div",{className:"mt-0.5",style:{fontSize:12,color:"var(--dsw-label-caption)"},children:a})]}),t]})}function D({value:e,onChange:a,max:t}){return(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)("button",{className:"icon-btn",style:{width:26,height:26,border:"0.5px solid var(--dsw-border-l3)",borderRadius:8},disabled:e<=12,onClick:()=>a(e-1),"aria-label":"decrease font size",children:"−"}),(0,s.jsxs)("button",{style:{minWidth:48,textAlign:"center",fontSize:13,color:14===e?"var(--dsw-label-tertiary)":"var(--dsw-label-primary)"},title:"reset",onClick:()=>a(14),children:[e," px"]}),(0,s.jsx)("button",{className:"icon-btn",style:{width:26,height:26,border:"0.5px solid var(--dsw-border-l3)",borderRadius:8},disabled:e>=t,onClick:()=>a(e+1),"aria-label":"increase font size",children:"+"})]})}function L(){let{t:e}=(0,m.s)(),[a,t]=(0,r.useState)([]),[l,i]=(0,r.useState)({providers:{}}),[o,d]=(0,r.useState)(null),[c,v]=(0,r.useState)(new Set),[g,b]=(0,r.useState)(null),[j,S]=(0,r.useState)(""),[N,k]=(0,r.useState)(null),[C,z]=(0,r.useState)(""),[P,M]=(0,r.useState)(""),[E,$]=(0,r.useState)("openai-completions"),[R,D]=(0,r.useState)(""),[L,I]=(0,r.useState)([]),[U,B]=(0,r.useState)(""),[K,H]=(0,r.useState)(""),[J,q]=(0,r.useState)([]),[G,Q]=(0,r.useState)(!1),[V,X]=(0,r.useState)(!1),[Z,Y]=(0,r.useState)(null),[ee,ea]=(0,r.useState)(null),[et,es]=(0,r.useState)(null),[er,el]=(0,r.useState)([]),[ei,en]=(0,r.useState)(""),[eo,ed]=(0,r.useState)(null),[ec,eu]=(0,r.useState)(!1),ep=(0,r.useMemo)(()=>{for(let e=er.length-1;e>=0;e--){let a=er[e];if(a.startsWith("{"))try{let e=JSON.parse(a);if("device_code"===e.type&&"string"==typeof e.verificationUri)return{userCode:"string"==typeof e.userCode?e.userCode:"",verificationUri:e.verificationUri,instructions:""};if("auth_url"===e.type&&"string"==typeof e.url)return{userCode:"",verificationUri:e.url,instructions:"string"==typeof e.instructions?e.instructions:""}}catch{}}return null},[er]),em=(0,r.useRef)(null);(0,r.useEffect)(()=>{ep?.verificationUri&&em.current!==ep.verificationUri&&(em.current=ep.verificationUri,window.open(ep.verificationUri,"_blank","noopener"))},[ep]);let eh=(0,r.useCallback)(async()=>{try{let e=await fetch("/api/models?custom=1"),a=await e.json();if(!e.ok||!a.success)throw Error(a.error||"failed to load model configuration");let s=JSON.parse(a.data.customProviders?.content??"{}");if(!s||"object"!=typeof s||Array.isArray(s)||void 0!==s.providers&&(!s.providers||"object"!=typeof s.providers||Array.isArray(s.providers)))throw Error("invalid model configuration");t(a.data.providers),v(new Set(a.data.customProviders?.secretProviderIds??[])),i({...s,providers:s.providers??{}}),d("string"==typeof a.data.customProviders?.revision?a.data.customProviders.revision:null)}catch(e){d(null),Y({ok:!1,msg:e instanceof Error?e.message:"failed to load model configuration"})}},[]);(0,r.useEffect)(()=>{eh()},[eh]),(0,r.useEffect)(()=>{let e;if(!ee)return;let a=!0,t=!1,s=async()=>{try{let e=await fetch("/api/models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"loginState",providerId:ee})}),s=await e.json();if(!a||!s.success)return;es(s.data.prompt),el(s.data.notifyLog??[]),s.data.done&&(t=!0,ed({ok:!s.data.error,msg:s.data.error??ee+" ✓"}),s.data.error||eh())}catch{}finally{a&&!t&&(e=setTimeout(s,1500))}};return s(),()=>{a=!1,e&&clearTimeout(e)}},[ee,eh]);let[ex,ev]=(0,r.useState)(null),[ef,eg]=(0,r.useState)(!1),[eb,ey]=(0,r.useState)(!1),ew=(0,r.useCallback)(async e=>{eg(!0),ey(!1);try{let a=await fetch("/api/models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"providerUsage",providerId:"xai",force:e})}),t=await a.json();if(!a.ok||!t.success)throw Error(t.error||"usage probe failed");ev(t.data.usage??null)}catch{ey(!0)}finally{eg(!1)}},[]),[ej,eS]=(0,r.useState)({}),[eN,ek]=(0,r.useState)(null),[eC,e_]=(0,r.useState)({}),ez=(0,r.useCallback)(async(e,a)=>{ek(e),e_(a=>({...a,[e]:!1}));try{let t=await fetch("/api/models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"providerUsage",providerId:e,force:a})}),s=await t.json();if(!t.ok||!s.success)throw Error(s.error||"usage probe failed");eS(a=>({...a,[e]:s.data.usage??null}))}catch{e_(a=>({...a,[e]:!0}))}finally{ek(a=>a===e?null:a)}},[]),eP=(0,r.useRef)(new Set);(0,r.useEffect)(()=>{for(let e of a)!e.authReady||!_(e.id)||"xai"===e.id||eP.current.has(e.id)||(eP.current.add(e.id),ez(e.id,!1))},[a,ez]);let eM=e=>`${"USD"===e.currency?"$":"CNY"===e.currency?"\xa5":""}${e.amount}${e.currency&&"USD"!==e.currency&&"CNY"!==e.currency?` ${e.currency}`:""}`,eE=(a,t)=>{Y({ok:a,msg:t??(a?e.toastSaved:e.toastError)}),setTimeout(()=>Y(null),2400)},eT=async a=>{try{let e=await fetch("/api/models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),t=await e.json();return e.ok?t:{...t,success:!1,error:t.error||`request failed (${e.status})`}}catch(a){return{success:!1,error:a instanceof Error?a.message:e.toastError}}},e$=async a=>{let t=await eT(a);return eE(t.success,t.success&&t.data?.requiresSessionReopen?e.modelConfigReopen:t.error),t.success&&await eh(),t},eR=async a=>{if(ee)try{let t=await eT({action:"loginAnswer",providerId:ee,text:a});if(!t.success||t.data?.delivered!==!0)throw Error(t.error||e.toastError);en("")}catch(a){eE(!1,a instanceof Error?a.message:e.toastError)}},eD=async()=>{if(ee)try{let a=await eT({action:"loginCancel",providerId:ee});if(!a.success)throw Error(a.error||e.toastError);ea(null)}catch(a){eE(!1,a instanceof Error?a.message:e.toastError)}},eL=new Set(Object.keys(l.providers??{})),eF=a.filter(e=>e.authReady||e.authConfigured||e.keyManaged||eL.has(e.id)),eA=a.filter(e=>e.builtIn&&!eF.some(a=>a.id===e.id)),eW=async e=>{if(null===o){let e={success:!1,error:"Reload model configuration before saving."};return eE(!1,e.error),e}return e$({action:"saveCustomProviders",revision:o,content:JSON.stringify({...l,providers:e},null,2)})},eO=e=>a.find(a=>a.id===e)?.name??e,eI=async()=>{if(!G&&!x(L)&&P.trim()){Q(!0);try{let e={...l.providers},a=g??C.trim(),t=e[a]??{};a!==C.trim()&&delete e[a],e[C.trim()]=f(t,{name:U,baseUrl:P,api:E,apiKey:R,models:L}),(await eW(e)).success&&b(null)}finally{Q(!1)}}},eU=async e=>{if(!G&&!x(J)){Q(!0);try{let a={...l.providers};a[e.id]=f(a[e.id]??{},{baseUrl:K,models:J},e.apis[0]??"openai-completions");let t=await eW(a);t.success&&j.trim()&&(e$({action:"setKey",providerId:e.id,apiKey:j.trim()}),ed(null),ea(e.id)),t.success&&b(null)}finally{Q(!1)}}},eB=async t=>{if(!window.confirm(e.confirmRemoveProvider.replace("{name}",eO(t))))return;let s={...l.providers};delete s[t];let r=a.find(e=>e.id===t);if(r?.builtIn)try{await e$({action:"removeKey",providerId:t})}catch{}(await eW(s)).success&&b(null)},eK=async({providerId:e,apiKey:a,config:t})=>{let s={...l.providers,[e]:{...l.providers[e],...t}},r=await eW(s);return r.success&&a&&(eT({action:"setKey",providerId:e,apiKey:a}),ed(null),ea(e)),r},eH=async({providerId:e,config:a})=>eW({...l.providers,[e]:a}),eJ=async e=>{let a=await eT({action:"loginStart",providerId:e});return a.success?(ed(null),ea(e),{success:!0}):{success:!1,error:a.error}};return(0,s.jsxs)("div",{className:"flex flex-col gap-5",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{style:{fontSize:14,fontWeight:400},children:e.modelsTitle}),(0,s.jsx)("div",{className:"mt-0.5",style:{fontSize:12.5,color:"var(--dsw-label-caption)"},children:e.modelsDesc}),(0,s.jsx)("div",{className:"mt-1",style:{fontSize:12,color:"var(--dsw-label-caption)"},children:e.customModelIdentityNotice})]}),Z&&(0,s.jsx)("div",{className:"rounded-xl px-3 py-2",style:{fontSize:12.5,background:Z.ok?"rgba(34,197,94,.1)":"rgba(236,19,19,.1)",color:Z.ok?"var(--dsw-success)":"var(--dsw-danger)"},children:Z.msg}),(0,s.jsx)("div",{className:"flex flex-col gap-2.5",children:eF.map(t=>{var r;let i,d,m,v,f=eL.has(t.id)&&!t.builtIn,y=g===t.id;return(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex flex-col rounded-2xl px-4 py-3",style:{border:"0.5px solid var(--dsw-border-l2)"},children:[(0,s.jsxs)("div",{className:"flex items-center gap-3",children:[(0,s.jsx)(p,{id:t.id,name:eO(t.id),size:34}),(0,s.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,s.jsx)("div",{className:"truncate",style:{fontSize:14,fontWeight:500},children:eO(t.id)}),(0,s.jsxs)("div",{className:"truncate",style:{fontSize:11.5,color:"var(--dsw-label-caption)"},children:[t.id,t.baseUrl?` \xb7 ${t.baseUrl}`:""]})]}),f&&(0,s.jsx)("span",{className:"rounded-md px-1.5 py-0.5",style:{fontSize:10.5,border:"0.5px solid var(--dsw-border-l3)",color:"var(--dsw-label-tertiary)"},children:e.customBadge}),(0,s.jsx)("span",{className:"inline-block h-2 w-2 rounded-full",style:{background:t.authReady?"var(--dsw-success)":"var(--dsw-danger)"},title:t.authError||(t.authReady?e.providerReady:e.authUnavailable)}),(0,s.jsx)("span",{className:"rounded-md px-1.5 py-0.5",style:{fontSize:10.5,border:"0.5px solid var(--dsw-border-l3)",color:"var(--dsw-label-tertiary)"},children:e.credentialSource.replace("{source}","stored"===(i=t.authSource)?"auth.json":"runtime"===i?e.authSourceRuntime:"environment"===i?e.authSourceEnvironment:"models_json_key"===i?"models.json":"models_json_command"===i?e.authSourceCommand:"fallback"===i?e.authSourceProvider:t.resolvedAuthSource||e.authUnavailable)}),(0,s.jsx)("button",{className:"btn-outline",style:{height:28,padding:"0 12px",fontSize:12},onClick:()=>{var e;let s;return b(g===(e=t.id)?null:e),S(""),Q(!1),X(!1),s=l.providers[e],void(eL.has(e)&&!a.find(a=>a.id===e)?.builtIn?(z(e),M(s?.baseUrl??""),$(s?.api??"openai-completions"),D(""),B("string"==typeof s?.name?s.name:""),I((s?.models??[]).map(h))):(H("string"==typeof s?.baseUrl?s.baseUrl:""),q((s?.models??[]).map(h))))},children:e.edit}),"oauth"===t.storedAuthType&&(0,s.jsx)("button",{style:{height:28,padding:"0 12px",fontSize:12,color:"var(--dsw-danger)"},onClick:async()=>{window.confirm(e.confirmRemoveOAuth.replace("{name}",eO(t.id)))&&await e$({action:"removeKey",providerId:t.id})},children:e.removeOAuth}),t.authTypes?.includes("oauth")&&(0,s.jsx)("button",{className:"btn-outline",style:{height:28,padding:"0 12px",fontSize:12},onClick:()=>{ed(null),e$({action:"loginStart",providerId:t.id}),ea(t.id)},children:e.oauthLogin}),eL.has(t.id)&&(0,s.jsx)("button",{style:{fontSize:12.5,color:"var(--dsw-danger)"},onClick:()=>eB(t.id),children:e.delete})]}),"xai"===t.id&&t.authReady&&(0,s.jsxs)("div",{className:"mt-3 flex items-center gap-2 pt-3",style:{borderTop:"0.5px solid var(--dsw-border-l2)",fontSize:11.5,color:"var(--dsw-label-tertiary)"},children:[ex?(0,s.jsxs)("span",{children:[e.usageQuotaLabel," \xb7 ",ex.model," \xb7 ",e.usageRequests," ",ex.requestRemaining.toLocaleString(),"/",ex.requestLimit.toLocaleString()," \xb7 Tokens ",A(ex.tokenRemaining),"/",A(ex.tokenLimit)]}):(0,s.jsx)("span",{children:eb?e.usageProbeFailed:e.usageProbeDisclosure}),(0,s.jsx)("button",{type:"button",className:"pw-chip",disabled:ef,title:e.usageProbeDisclosure,onClick:()=>void ew(!0),children:ef?e.usageProbing:ex?e.usageRefresh:e.usageProbe})]}),_(t.id)&&"xai"!==t.id&&t.authReady&&(0,s.jsx)("div",{className:"mt-3 flex flex-col gap-1.5 pt-3",style:{borderTop:"0.5px solid var(--dsw-border-l2)",fontSize:11.5,color:"var(--dsw-label-tertiary)"},children:(d=ej[r=t.id],m=eN===r,v=eC[r],(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[!d&&(0,s.jsx)("span",{children:v?e.usageProbeFailed:m?e.queryingQuota:e.usageReadOnlyDisclosure}),d?.kind==="quota"&&d.planType&&(0,s.jsxs)("span",{children:[e.usagePlan," ",W(d.planType)]}),d?.kind==="balance"&&d.primary&&(0,s.jsxs)("span",{children:["used"===d.primaryKey?e.usageBalanceUsed:e.usageQuotaRemaining," ",(0,s.jsx)("span",{style:{color:"var(--dsw-label-secondary)"},children:eM(d.primary)})]}),(0,s.jsx)("button",{type:"button",className:"pw-chip",disabled:m,title:e.usageReadOnlyDisclosure,onClick:()=>void ez(r,!0),children:m?e.usageProbing:d?e.usageRefresh:e.usageProbe})]}),d?.kind==="balance"&&d.details.length>0&&(0,s.jsx)("span",{children:d.details.map(a=>{var t;return`${"granted"===(t=a.key)?e.usageBalanceGranted:"toppedUp"===t?e.usageBalanceToppedUp:"voucher"===t?e.usageBalanceVoucher:"cash"===t?e.usageBalanceCash:"used"===t?e.usageBalanceUsed:e.usageBalanceLimit} ${eM(a)}`}).join(" \xb7 ")}),d?.kind==="quota"&&0===d.windows.length&&(0,s.jsxs)("span",{children:[e.usageQuotaRemaining," —"]}),d?.kind==="quota"&&d.windows.map((a,t)=>{var r;return(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)("span",{style:{width:84,flex:"none"},children:(a=>{var t,s,r,l;if(void 0!==a.limitWindowSeconds){let l;return`${"weekly"==(l=604800===(s=t=a.limitWindowSeconds)?"weekly":2592e3===s?"monthly":s<86400?"hours":"days")?e.usageWindowWeekly:"monthly"===l?e.usageWindowMonthly:("hours"===l?e.usageWindowHours:e.usageWindowDays).replace("{n}",String(Math.round(t/("hours"===l?3600:86400))))}${a.variant?` (${"opus"===(r=a.variant)?e.usageVariantOpus:"code"===r?e.usageVariantCode:W(r)})`:""}`}return a.name?"premium"===(l=a.name)?e.usageWindowPremium:"chat"===l?e.usageWindowChat:"completions"===l?e.usageWindowCompletions:"rolling"===l?e.usageWindowRolling:W(l):""})(a)}),(0,s.jsxs)("span",{style:{width:92,flex:"none"},children:[e.usageQuotaRemaining," ",a.remainingPercent,"%"]}),(0,s.jsxs)("span",{children:[e.usageReset," ",function(e){if(!e)return"—";let a=new Date(e);return Number.isNaN(a.getTime())?"—":a.toLocaleString()}(a.resetAt)]}),(0,s.jsx)("div",{className:"h-1 overflow-hidden rounded-full",style:{width:120,flex:"none",background:"var(--dsw-border-l2)"},children:(0,s.jsx)("div",{className:"h-full rounded-full",style:{width:`${a.remainingPercent}%`,background:(r=a.remainingPercent)<30?"var(--dsw-danger)":r<=60?"var(--dsw-warning)":"var(--dsw-success)"}})})]},`${a.limitWindowSeconds??a.name??"window"}-${a.variant??""}-${t}`)})]}))})]}),y&&(0,s.jsx)("div",{className:"mt-2 rounded-2xl p-4",style:{border:"0.5px solid var(--dsw-border-l2)"},children:f?(0,s.jsxs)("div",{className:"flex flex-col gap-3",children:[(0,s.jsx)(O,{label:e.apiKey,children:(0,s.jsx)("input",{type:"password",value:R,onChange:e=>D(e.target.value),className:F,placeholder:c.has(t.id)?e.apiKeyStored:e.apiKeyOptional})}),(0,s.jsx)(O,{label:e.displayName,children:(0,s.jsx)("input",{value:U,onChange:e=>B(e.target.value),className:F,placeholder:t.id})}),(0,s.jsx)(O,{label:e.baseUrl,children:(0,s.jsx)("input",{value:P,onChange:e=>M(e.target.value),className:F,placeholder:"https://api.example.com/v1"})}),(0,s.jsx)(O,{label:e.apiType,children:(0,s.jsx)(T,{value:E,options:u([E,...t.apis]).map(e=>({value:e,label:e})),onChange:$})}),(0,s.jsx)(w,{models:L,setModels:I,updateModel:(e,a)=>I(t=>t.map((t,s)=>s===e?{...t,...a}:t)),discover:async a=>{let s=await fetch("/api/models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"discoverModels",providerId:t.id,baseUrl:P.trim(),api:E,apiKey:R.trim(),allowPrivate:a})}),r=await s.json();if(!r.success)throw Error(r.error||e.toastError);return(r.data.models??[]).map(e=>({id:e.id,name:e.name??""}))},discoverDisabled:!P.trim()}),(0,s.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,s.jsx)("button",{className:"btn-outline",style:{height:32},disabled:G,onClick:()=>b(null),children:e.cancel}),(0,s.jsx)("button",{className:"btn-primary-white",disabled:G||!P.trim()||!!x(L)||!L.some(e=>e.id.trim()),onClick:()=>void eI(),children:G?e.saving:e.save})]})]}):(0,s.jsxs)("div",{className:"flex flex-col gap-3",children:[(0,s.jsx)(O,{label:e.apiKey,children:(0,s.jsx)("input",{type:"password",value:j,onChange:e=>S(e.target.value),className:F,placeholder:t.keyManaged?e.apiKeyStored:t.apiKeyLabel??e.apiKey})}),(0,s.jsxs)("div",{children:[(0,s.jsxs)("button",{className:"flex w-full items-center gap-2 rounded-xl px-2 py-2 text-left transition-colors",style:{fontSize:13,color:"var(--dsw-label-secondary)",background:V?"var(--dsw-hover)":"transparent"},onClick:()=>X(e=>!e),children:[(0,s.jsx)("span",{style:{display:"inline-flex",transform:V?"none":"rotate(-90deg)",transition:"transform 120ms ease"},children:(0,s.jsx)(n.Cd,{size:13})}),e.customSettings]}),V?(0,s.jsxs)("div",{className:"flex flex-col gap-3 pl-1 pt-2",children:[(0,s.jsx)(O,{label:e.baseUrl,children:(0,s.jsx)("input",{value:K,onChange:e=>H(e.target.value),className:F,placeholder:t.baseUrl??e.providerDefault})}),(0,s.jsx)(w,{models:J,setModels:q,updateModel:(e,a)=>q(t=>t.map((t,s)=>s===e?{...t,...a}:t)),inheritedCount:t.modelCount,discover:async a=>{let s=await fetch("/api/models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"discoverModels",providerId:t.id,baseUrl:K.trim()||t.baseUrl||"",api:t.apis[0],apiKey:j.trim(),allowPrivate:a})}),r=await s.json();if(!r.success)throw Error(r.error||e.toastError);return(r.data.models??[]).map(e=>({id:e.id,name:e.name??""}))},discoverDisabled:!(K.trim()||t.baseUrl)})]}):null]}),(0,s.jsxs)("div",{className:"flex items-center justify-end gap-2",children:[t.keyManaged&&(0,s.jsx)("button",{style:{fontSize:12.5,color:"var(--dsw-danger)"},disabled:G,onClick:async()=>{if("oauth"===t.storedAuthType){if(!window.confirm(e.confirmRemoveOAuth.replace("{name}",t.name)))return}else if(!window.confirm(e.confirmRemoveKey.replace("{name}",t.name)))return;(await e$({action:"removeKey",providerId:t.id})).success&&b(null)},children:"oauth"===t.storedAuthType?e.removeOAuth:e.removeKey}),(0,s.jsx)("button",{className:"btn-outline",style:{height:32},disabled:G,onClick:()=>b(null),children:e.cancel}),(0,s.jsx)("button",{className:"btn-primary-white",disabled:G||null===o||!!x(J),onClick:()=>void eU({id:t.id,apis:t.apis}),children:G?e.saving:e.save})]})]})})]},t.id)})}),(0,s.jsxs)("div",{className:"flex gap-3",children:[(0,s.jsxs)("button",{className:"flex flex-1 items-center justify-center gap-2 rounded-2xl px-4 py-3.5 transition-colors",style:{border:"0.5px solid var(--dsw-border-l3)",fontSize:14},onMouseEnter:e=>e.currentTarget.style.background="var(--dsw-hover)",onMouseLeave:e=>e.currentTarget.style.background="transparent",onClick:()=>k("builtin"),children:[(0,s.jsx)(n.Xh,{size:15}),e.addProvider]}),(0,s.jsxs)("button",{className:"flex flex-1 items-center justify-center gap-2 rounded-2xl px-4 py-3.5 transition-colors",style:{border:"0.5px solid var(--dsw-border-l3)",fontSize:14},onMouseEnter:e=>e.currentTarget.style.background="var(--dsw-hover)",onMouseLeave:e=>e.currentTarget.style.background="transparent",onClick:()=>k("custom"),children:[(0,s.jsx)(n.Xh,{size:15}),e.addCustomProvider]})]}),N?(0,s.jsx)(y,{mode:N,providers:eA,existingIds:a.map(e=>e.id),onClose:()=>k(null),onSaveBuiltin:eK,onSaveCustom:eH,onOAuthLogin:eJ}):null,ee&&(0,s.jsx)("div",{className:"modal-mask fixed inset-0 z-[120] flex items-center justify-center",onMouseDown:e=>{e.target===e.currentTarget&&eD()},children:(0,s.jsxs)("div",{className:"glass-modal flex flex-col gap-4 p-6",style:{width:460,maxWidth:"92vw",borderRadius:24,boxShadow:"var(--dsw-elevation-prominent)"},children:[(0,s.jsxs)("div",{style:{fontSize:15,fontWeight:600},children:[e.oauthLogin," \xb7 ",ee]}),ep&&!eo?(0,s.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,s.jsx)("div",{style:{fontSize:13,color:"var(--dsw-label-primary)"},children:e.oauthDevicePrompt}),ep.instructions?(0,s.jsx)("div",{style:{fontSize:12,color:"var(--dsw-label-tertiary)"},children:ep.instructions}):null,(0,s.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,s.jsx)("a",{href:ep.verificationUri,target:"_blank",rel:"noreferrer",className:"btn-primary-white",style:{fontSize:12.5,textDecoration:"none"},children:e.oauthOpenAuth}),ep.userCode?(0,s.jsx)("button",{className:"btn-outline",style:{height:32},onClick:()=>{if(!ep?.userCode)return;let e=ep.userCode,a=()=>{eu(!0),setTimeout(()=>eu(!1),2e3)};navigator.clipboard.writeText(e).then(a).catch(()=>{let t=document.createElement("textarea");t.value=e,document.body.appendChild(t),t.select(),document.execCommand("copy"),t.remove(),a()})},children:ec?e.oauthCodeCopied:`${e.oauthDeviceCode}: ${ep.userCode}`}):null]})]}):er.length>0?(0,s.jsx)("div",{className:"flex flex-col gap-0.5",style:{fontSize:12,color:"var(--dsw-label-tertiary)"},children:er.slice(-3).map((e,a)=>(0,s.jsx)("div",{className:"truncate",children:e},a))}):null,eo?(0,s.jsx)("div",{style:{fontSize:13,color:eo.ok?"var(--dsw-success)":"var(--dsw-danger)"},children:eo.ok?ee+" ✓":eo.msg}):et?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("div",{style:{fontSize:13.5,color:"var(--dsw-label-primary)"},children:et.message}),et.message.match(/https?:\/\/[^\s)]+/)&&(0,s.jsx)("a",{href:et.message.match(/https?:\/\/[^\s)]+/)[0],target:"_blank",rel:"noreferrer",className:"break-all",style:{fontSize:12.5,color:"var(--dsw-accent)"},children:et.message.match(/https?:\/\/[^\s)]+/)[0]}),et.options?.length?(0,s.jsx)("div",{className:"flex flex-col gap-1.5",children:et.options.map(e=>(0,s.jsx)("button",{className:"btn-outline",style:{height:34,justifyContent:"flex-start",textAlign:"left"},onClick:()=>{eR(e.value)},children:e.label},e.value))}):(0,s.jsx)("input",{autoFocus:!0,type:"secret"===et.type?"password":"text",value:ei,onChange:e=>en(e.target.value),placeholder:et.placeholder??"",className:"w-full rounded-xl px-3 py-2",style:{fontSize:13,background:"var(--dsw-hover)"},onKeyDown:e=>{"Enter"===e.key&&!e.nativeEvent.isComposing&&ei.trim()&&eR(ei.trim())}}),(0,s.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,s.jsx)("span",{style:{fontSize:12,color:"var(--dsw-label-caption)"},children:e.oauthWait}),(0,s.jsxs)("div",{className:"flex gap-2",children:[(0,s.jsx)("button",{className:"btn-outline",style:{height:32},onClick:()=>{eD()},children:e.oauthCancel}),!et.options?.length&&(0,s.jsx)("button",{className:"btn-primary-white",disabled:!ei.trim(),style:{opacity:ei.trim()?1:.5},onClick:()=>{eR(ei.trim())},children:e.confirm})]})]})]}):(0,s.jsx)("div",{style:{fontSize:13,color:"var(--dsw-label-tertiary)"},children:e.oauthWait}),eo&&(0,s.jsx)("div",{className:"flex justify-end",children:(0,s.jsx)("button",{className:"btn-primary-white",onClick:()=>ea(null),children:e.close})})]})})]})}let F="w-full rounded-xl px-3 py-2";function A(e){return e>=1e6?`${Math.round(e/1e5)/10}M`:e.toLocaleString()}function W(e){return 0===e.length?e:e[0].toUpperCase()+e.slice(1)}function O({label:e,children:a}){return(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{className:"mb-1",style:{fontSize:12,color:"var(--dsw-label-caption)"},children:e}),a]})}let I={read:{zh:"读取文件",en:"Read files"},bash:{zh:"执行 Shell 命令",en:"Run shell commands"},powershell:{zh:"执行 PowerShell",en:"Run PowerShell"},edit:{zh:"编辑文件",en:"Edit files"},write:{zh:"写入文件",en:"Write files"},grep:{zh:"搜索文件内容",en:"Search file contents"},find:{zh:"按名称查找文件",en:"Find files by name"},ls:{zh:"列出目录内容",en:"List directories"}};function U({toolPreset:e,onToolPresetChange:a,tools:t,onSetTools:r}){let{t:l,lang:i}=(0,m.s)(),n=new Set(t?.active??[]),o=t?.all??[];return(0,s.jsxs)("div",{className:"flex flex-col gap-5",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{style:{fontSize:14,fontWeight:400},children:l.toolsSection}),(0,s.jsx)("div",{className:"mt-0.5",style:{fontSize:12.5,color:"var(--dsw-label-caption)"},children:l.toolsSectionDesc})]}),(0,s.jsx)($,{title:l.securityToolPreset,desc:l.securityToolPresetDesc,children:(0,s.jsx)(T,{value:e,options:[{value:"readonly",label:l.toolReadonly},{value:"standard",label:l.toolStandard},{value:"full",label:l.toolFull}],onChange:e=>a(e)})}),0===o.length?(0,s.jsx)("div",{className:"rounded-2xl p-4",style:{border:"0.5px dashed var(--dsw-border-l3)",fontSize:12.5,color:"var(--dsw-label-caption)"},children:l.toolsNoSession}):(0,s.jsxs)("div",{className:"flex flex-col gap-2.5",children:[(0,s.jsxs)("div",{className:"flex items-center gap-2",style:{fontSize:12,color:"var(--dsw-label-caption)"},children:[(0,s.jsx)("span",{style:{fontWeight:600},children:l.toolsCurrentSession}),(0,s.jsx)("span",{children:l.toolsActiveCount.replace("{n}",String(n.size)).replace("{total}",String(o.length))})]}),o.map(e=>{let a,t=n.has(e.name),l=e.description||((a=I[e.name])?"zh"===i?a.zh:a.en:"");return(0,s.jsxs)("div",{className:"flex items-center gap-3 rounded-2xl px-4 py-2.5",style:{border:"0.5px solid var(--dsw-border-l2)"},children:[(0,s.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,s.jsx)("div",{style:{fontSize:13.5,fontWeight:500,fontFamily:"var(--font-mono)"},children:e.name}),l&&(0,s.jsx)("div",{className:"truncate",style:{fontSize:11.5,color:"var(--dsw-label-caption)"},children:l})]}),(0,s.jsx)("button",{className:"relative h-5 w-9 flex-none rounded-full transition-colors",style:{background:t?"var(--dsw-accent)":"var(--dsw-border-l3)"},role:"switch","aria-checked":t,"aria-label":e.name,disabled:!r||t&&n.size<=1,onClick:()=>{var a;return a=e.name,void(!r||r(n.has(a)?[...n].filter(e=>e!==a):[...n,a]))},children:(0,s.jsx)("span",{className:"absolute top-0.5 h-4 w-4 rounded-full bg-white transition-all",style:{left:t?18:2}})})]},e.name)})]})]})}function B({cwd:e,onOpenFileContent:a}){let{t}=(0,m.s)(),[l,i]=(0,r.useState)([]),n=(0,r.useCallback)(async()=>{let a=await fetch(`/api/skills${e?`?cwd=${encodeURIComponent(e)}`:""}`),t=await a.json();t.success&&i(t.data.skills)},[e]);(0,r.useEffect)(()=>{n()},[n]);let o=async a=>{let t=await fetch("/api/skills",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"toggle",filePath:a.filePath,disabled:!a.disabled,cwd:e})});(await t.json()).success&&n()},d=async t=>{let s=await fetch("/api/skills",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"read",filePath:t.filePath,cwd:e})}),r=await s.json();r.success&&a?.(t.filePath,r.data.content)},[c,u]=(0,r.useState)(null),p=async a=>{if(!window.confirm(t.confirmDeleteSkill.replace("{name}",a.name)))return;u(null);let s=await fetch("/api/skills",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"delete",filePath:a.filePath,cwd:e})}),r=await s.json();r.success?n():u(r.error||t.toastError)};return(0,s.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,s.jsx)("div",{style:{fontSize:12,color:"var(--dsw-label-caption)"},children:t.skillsDesc}),c&&(0,s.jsx)("div",{role:"alert",className:"rounded-lg px-3 py-2",style:{fontSize:12.5,background:"var(--dsw-hover)",color:"var(--dsw-danger)"},children:c}),0===l.length&&(0,s.jsx)("div",{style:{fontSize:13,color:"var(--dsw-label-caption)"},children:"—"}),(0,s.jsx)("div",{className:"flex flex-col gap-2",children:l.map(e=>{let a;return(0,s.jsx)("div",{className:"rounded-2xl px-4 py-3",style:{border:"0.5px solid var(--dsw-border-l2)"},children:(0,s.jsxs)("div",{className:"flex items-center gap-3",children:[(0,s.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)("span",{style:{fontSize:13.5,fontWeight:500},children:e.name}),(0,s.jsx)("span",{className:"rounded-full px-2 py-0.5",style:{fontSize:10,background:"var(--dsw-hover)",color:"var(--dsw-label-tertiary)"},children:"global"===(a=e.scope)?t.scopeGlobal:"project"===a?t.scopeProject:t.scopePackage})]}),(0,s.jsx)("div",{className:"mt-0.5 truncate",style:{fontSize:12,color:"var(--dsw-label-caption)"},title:e.description,children:e.description})]}),(0,s.jsx)("button",{className:"rounded-lg px-2.5 py-1",style:{fontSize:11.5,color:"var(--dsw-label-tertiary)"},onClick:()=>d(e),children:t.viewSkillFile}),"package"!==e.scope&&(0,s.jsx)("button",{className:"rounded-lg px-2.5 py-1",style:{fontSize:11.5,color:"var(--dsw-danger)"},title:t.deleteSkillHint,onClick:()=>void p(e),children:t.delete}),"package"===e.scope&&(0,s.jsx)("span",{style:{fontSize:10.5,color:"var(--dsw-label-caption)"},title:t.skillDeletePackageHint,children:t.skillDeletePackageHint}),(0,s.jsx)("button",{className:"relative h-5 w-9 flex-none rounded-full transition-colors",style:{background:e.disabled?"var(--dsw-border-l3)":"var(--dsw-accent)"},role:"switch","aria-checked":!e.disabled,onClick:()=>o(e),children:(0,s.jsx)("span",{className:"absolute top-0.5 h-4 w-4 rounded-full bg-white transition-all",style:{left:e.disabled?2:18}})})]})},e.filePath)})})]})}function K({cwd:e}){let{t:a,lang:t}=(0,m.s)(),l=e=>window.confirm(a.confirmUninstallPackage.replace("{source}",e)),[i,o]=(0,r.useState)("config"),[d,c]=(0,r.useState)([]),[u,p]=(0,r.useState)([]),[h,x]=(0,r.useState)(""),[v,f]=(0,r.useState)(new Set),[g,b]=(0,r.useState)(""),[y,w]=(0,r.useState)(!1),[j,S]=(0,r.useState)(!1),[N,k]=(0,r.useState)(null),[C,_]=(0,r.useState)(null),[z,P]=(0,r.useState)(null),M=(0,r.useRef)(null);(0,r.useEffect)(()=>{let e=e=>{e.target instanceof Node&&M.current?.contains(e.target)||P(null)};return window.addEventListener("pointerdown",e),()=>window.removeEventListener("pointerdown",e)},[]);let E=(0,r.useCallback)(async()=>{let a=await fetch(`/api/plugins${e?`?cwd=${encodeURIComponent(e)}`:""}`),t=await a.json();t.success&&(c(t.data.packages),p(t.data.extensions))},[e]);(0,r.useEffect)(()=>{E()},[E]);let T=(e,t)=>{_({ok:e,msg:t??(e?a.toastSaved:a.toastError),loading:!1}),setTimeout(()=>_(null),2600)},$=async(t,s={},r,l,i)=>{S(!0),r&&k(r),l&&_({ok:!0,msg:l,loading:!0});try{let r=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,cwd:e,...s})}),l=await r.json();if(l.success)return T(!0,i??("toggle"===t?s.disabled?a.disabled:a.enabled:a.toastSaved)),await E(),!0;return T(!1,l.error??a.toastError),!1}catch(e){return T(!1,e?.message??a.toastError),!1}finally{S(!1),k(null)}},R=e=>f(a=>{let t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t}),D=e=>{let a=e.replace(/\\/g,"/");return a.includes("/.pi/agent/npm/")||a.includes("/.pi/agent/git/")?"package":a.includes("/.pi/agent/")?"global":(a.includes("/.pi/"),"project")},L=u.filter(e=>"package"!==D(e.path)),F=h.trim().toLowerCase(),A=[...d.map(e=>({key:`pkg:${e.scope}:${e.source}`,kind:"package",name:e.source.replace(/^npm:/,"").replace(/^git[^:]*:/,""),p:e})),...L.map(e=>({key:`ext:${e.path}`,kind:"extension",name:e.name,e}))].filter(e=>!F||e.name.toLowerCase().includes(F)),W=(0,s.jsxs)("span",{className:"flex flex-none items-center gap-1.5 rounded-md px-1.5 py-0.5",style:{fontSize:10.5,background:"rgba(34,197,94,.12)",color:"var(--dsw-success)"},children:[(0,s.jsx)("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:"var(--dsw-success)"}}),a.enabled]});return(0,s.jsxs)("div",{className:"flex flex-col gap-5",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{style:{fontSize:20,fontWeight:600,color:"var(--dsw-label-primary)"},children:a.setPlugins}),(0,s.jsx)("div",{className:"mt-1",style:{fontSize:13,color:"var(--dsw-label-tertiary)"},children:a.pluginPageDesc})]}),C&&(0,s.jsxs)("div",{className:"fixed top-6 left-1/2 -translate-x-1/2 z-[9999] flex items-center gap-2.5 px-4 py-2 rounded-xl shadow-2xl transition-all pointer-events-none",style:{fontSize:13,fontWeight:500,background:"var(--dsw-surface-l1, #1e2025)",border:C.loading?"1px solid var(--dsw-border-l3)":C.ok?"1px solid rgba(34,197,94,.4)":"1px solid rgba(236,19,19,.4)",color:C.loading?"var(--dsw-label-primary)":C.ok?"var(--dsw-success)":"var(--dsw-danger)",backdropFilter:"blur(12px)",boxShadow:"0 10px 30px rgba(0,0,0,0.5)"},children:[C.loading&&(0,s.jsx)("span",{className:"h-3.5 w-3.5 flex-none animate-spin rounded-full border-2 border-current border-t-transparent"}),(0,s.jsx)("span",{children:C.msg})]}),(0,s.jsxs)("div",{className:"hairline-b flex items-center gap-6",children:[(0,s.jsx)("button",{className:"settings-tab-underline","data-active":"config"===i,onClick:()=>o("config"),children:a.pluginConfig}),(0,s.jsx)("button",{className:"settings-tab-underline","data-active":"list"===i,onClick:()=>o("list"),children:a.pluginList})]}),"config"===i&&(0,s.jsxs)("div",{className:"flex flex-col gap-2.5",children:[(0,s.jsxs)("div",{className:"flex flex-col gap-2 rounded-2xl px-4 py-3",style:{border:"0.5px solid var(--dsw-border-l2)"},children:[(0,s.jsx)("div",{style:{fontSize:13.5,fontWeight:500},children:a.addPackage}),(0,s.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,s.jsx)("input",{value:g,onChange:e=>b(e.target.value),placeholder:a.addPackagePlaceholder,className:"min-w-0 flex-1 rounded-xl px-3 py-2",style:{fontSize:13,background:"var(--dsw-hover)",border:"0.5px solid var(--dsw-border-l2)",fontFamily:"var(--font-mono)"},onKeyDown:e=>{"Enter"===e.key&&g.trim()&&!j&&$("install",{source:g.trim(),local:y},void 0,a.installing,a.installSuccess).then(e=>{e&&b("")})}}),(0,s.jsxs)("label",{className:"flex items-center gap-1.5",style:{fontSize:12.5,color:"var(--dsw-label-secondary)"},children:[(0,s.jsx)("input",{type:"checkbox",checked:y,onChange:e=>w(e.target.checked),disabled:!e}),a.installLocal]}),(0,s.jsx)("button",{className:"btn-primary-white",style:{height:32,padding:"0 14px"},disabled:!g.trim()||j,onClick:()=>void $("install",{source:g.trim(),local:y},void 0,a.installing,a.installSuccess).then(e=>{e&&b("")}),children:a.install})]})]}),(0,s.jsx)("div",{className:"flex justify-end",children:(0,s.jsxs)("button",{className:"btn-outline",style:{height:30,fontSize:12.5},disabled:j,onClick:async()=>{S(!0);try{let t=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reload",cwd:e})}),s=await t.json();T(s.success,s.success?a.reloadedSessions.replace("{loaders}",String(s.data?.loaders??0)).replace("{sessions}",String(s.data?.sessions??0)):s.error),s.success&&await E()}finally{S(!1)}},children:[(0,s.jsx)(n.Ct,{size:13})," ",a.reloadExtensions]})}),0===L.length&&(0,s.jsx)("div",{style:{fontSize:12.5,color:"var(--dsw-label-caption)"},children:a.extensionsEmpty}),L.map(e=>{let t=`ext:${e.path}`,r=v.has(t),l=D(e.path);return(0,s.jsxs)("div",{className:"rounded-2xl",style:{border:"0.5px solid var(--dsw-border-l2)"},children:[(0,s.jsxs)("button",{className:"flex w-full items-center gap-3 px-4 py-3.5 text-left",onClick:()=>R(t),children:[(0,s.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,s.jsxs)("div",{className:"flex items-center gap-2",style:{fontSize:14,fontWeight:500},children:[(0,s.jsx)("span",{children:e.name}),e.error&&(0,s.jsx)("span",{className:"rounded px-1.5 py-0.5",style:{fontSize:10.5,color:"var(--dsw-danger)",background:"var(--pw-danger-soft, rgba(236,19,19,.12))"},children:a.extensionLoadError}),e.disabled&&!e.error&&(0,s.jsx)("span",{className:"rounded px-1.5 py-0.5",style:{fontSize:10.5,color:"var(--dsw-label-tertiary)",background:"var(--dsw-selector)"},children:a.disabled})]}),(0,s.jsx)("div",{className:"truncate",style:{fontSize:12,color:e.error?"var(--dsw-danger)":"var(--dsw-label-caption)"},title:e.error??e.path,children:e.error??e.path})]}),(0,s.jsx)("span",{className:"chevron",style:{color:"var(--dsw-label-tertiary)",display:"inline-flex",transform:r?"rotate(180deg)":"none",transition:"transform 120ms var(--ds-ease-in-out)"},children:(0,s.jsx)(n.Cd,{size:14})})]}),r&&(0,s.jsxs)("div",{className:"hairline-t flex flex-col gap-1.5 px-4 py-3",style:{fontSize:12,color:"var(--dsw-label-secondary)"},children:[(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)("span",{className:"rounded-md px-1.5 py-0.5",style:{fontSize:10.5,border:"0.5px solid var(--dsw-border-l3)",color:"var(--dsw-label-tertiary)"},children:"global"===l?a.scopeGlobal:"project"===l?a.scopeProject:a.scopePackage}),W]}),(0,s.jsx)("div",{className:"break-all",style:{fontFamily:"var(--font-mono)",fontSize:11.5,color:"var(--dsw-label-caption)"},children:e.path})]})]},t)})]}),"list"===i&&(0,s.jsxs)("div",{className:"flex flex-col gap-3.5",children:[(0,s.jsxs)("div",{className:"flex items-center gap-2.5 rounded-xl px-3.5 py-2.5 transition-colors",style:{background:"var(--dsw-hover)",border:"0.5px solid var(--dsw-border-l2)"},children:[(0,s.jsx)(n.FG,{size:15,style:{color:"var(--dsw-label-caption)"}}),(0,s.jsx)("input",{value:h,onChange:e=>x(e.target.value),placeholder:a.searchPlugins,className:"w-full bg-transparent outline-none",style:{fontSize:13,color:"var(--dsw-label-primary)"}})]}),(0,s.jsxs)("div",{className:"flex items-baseline gap-2",children:[(0,s.jsx)("span",{style:{fontSize:13.5,fontWeight:600,color:"var(--dsw-label-primary)"},children:a.pluginList}),(0,s.jsx)("span",{style:{fontSize:12,color:"var(--dsw-label-caption)"},children:A.length})]}),0===A.length?(0,s.jsx)("div",{style:{fontSize:12.5,color:"var(--dsw-label-caption)"},children:a.packagesEmpty}):(0,s.jsx)("div",{className:"grid grid-cols-1 items-start sm:grid-cols-2 gap-2.5",children:A.map(e=>{let r=v.has(e.key),i="package"===e.kind?!0===e.p.disabled:!0===e.e.disabled,o=z===e.key,d=N===e.key;return(0,s.jsxs)("div",{className:"flex flex-col rounded-xl transition-colors",style:{background:"var(--dsw-hover)",border:"0.5px solid var(--dsw-border-l2)"},children:[(0,s.jsxs)("div",{className:"flex h-11 items-center justify-between px-3.5 gap-2",children:[(0,s.jsx)("span",{className:"min-w-0 flex-1 truncate font-medium text-[var(--dsw-label-primary)] cursor-pointer select-none",style:{fontSize:13.5},onClick:()=>R(e.key),title:e.name,children:e.name}),(0,s.jsxs)("div",{ref:o?M:void 0,className:"relative flex-none",children:[(0,s.jsxs)("button",{type:"button",className:"flex min-w-[86px] items-center justify-center rounded-lg px-3 transition-colors cursor-pointer select-none disabled:cursor-wait",style:{gap:7,height:30,background:"rgba(255, 255, 255, 0.04)",border:"1px solid rgba(255, 255, 255, 0.08)"},"aria-haspopup":"menu","aria-expanded":o,disabled:d,onClick:a=>{a.stopPropagation(),P(a=>a===e.key?null:e.key)},children:[d?(0,s.jsx)("span",{className:"h-3 w-3 flex-none animate-spin rounded-full border border-[var(--dsw-label-tertiary)] border-t-transparent"}):i?null:(0,s.jsx)("span",{className:"h-2 w-2 flex-none rounded-full",style:{background:"#22c55e",boxShadow:"0 0 5px rgba(34, 197, 94, 0.4)"}}),(0,s.jsx)("span",{style:{fontSize:12,fontWeight:500,color:i?"var(--dsw-label-tertiary)":"var(--dsw-success)",lineHeight:1},children:i?a.disabled:a.enabled}),(0,s.jsx)(n.Cd,{size:13,style:{color:"var(--dsw-label-tertiary)",transform:o?"rotate(180deg)":"none",transition:"transform 140ms ease"}})]}),o&&(0,s.jsxs)("div",{className:"popover absolute right-0 top-full mt-1.5 z-50 w-36 py-1 rounded-xl shadow-xl",role:"menu",style:{background:"var(--dsw-surface-l1, #1e2025)",border:"0.5px solid var(--dsw-border-l3)",boxShadow:"0 10px 25px -5px rgba(0, 0, 0, 0.5), 0 8px 10px -6px rgba(0, 0, 0, 0.5)"},children:[(0,s.jsx)("button",{type:"button",role:"menuitem",className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors hover:bg-[var(--dsw-hover)] cursor-pointer",style:{color:i?"var(--dsw-success)":"var(--dsw-label-primary)"},disabled:j,onClick:()=>{P(null),$("toggle","package"===e.kind?{kind:"package",source:e.p.source,scope:e.p.scope,disabled:!i}:{kind:"extension",path:e.e.path,disabled:!i},e.key,i?"zh"===t?"正在启用...":"Enabling...":"zh"===t?"正在停用...":"Disabling...",i?a.enabled:a.disabled)},children:i?a.enablePlugin:a.disablePlugin}),"package"===e.kind&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("button",{type:"button",role:"menuitem",className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors hover:bg-[var(--dsw-hover)] cursor-pointer disabled:opacity-50",style:{color:"var(--dsw-label-secondary)"},disabled:j,onClick:()=>{P(null),$("update",{source:e.p.source},e.key,a.updating,a.updateSuccess)},children:a.update}),(0,s.jsx)("button",{type:"button",role:"menuitem",className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors hover:bg-[var(--dsw-hover)] cursor-pointer disabled:opacity-50",style:{color:"var(--dsw-danger)"},disabled:j,onClick:()=>{P(null),l(e.p.source)&&$("remove",{source:e.p.source,local:"project"===e.p.scope},e.key,a.uninstalling,a.uninstallSuccess)},children:a.uninstall})]}),(0,s.jsx)("div",{className:"my-1 border-t border-[var(--dsw-border-l1)]"}),(0,s.jsx)("button",{type:"button",role:"menuitem",className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors hover:bg-[var(--dsw-hover)] cursor-pointer",style:{color:"var(--dsw-label-tertiary)"},onClick:()=>{R(e.key),P(null)},children:r?"zh"===t?"收起详情":"Hide details":"zh"===t?"查看详情":"View details"})]})]})]}),r&&(0,s.jsx)("div",{className:"hairline-t flex flex-col gap-2 px-3.5 py-3",style:{fontSize:12},children:"package"===e.kind?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("div",{className:"break-all",style:{color:"var(--dsw-label-tertiary)",fontSize:11.5},children:e.p.source}),(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)("span",{className:"rounded-md px-1.5 py-0.5",style:{fontSize:10.5,border:"0.5px solid var(--dsw-border-l3)",color:"var(--dsw-label-tertiary)"},children:"user"===e.p.scope?a.scopeGlobal:a.scopeProject}),(0,s.jsxs)("span",{style:{color:"var(--dsw-label-caption)",fontSize:11.5},children:[a.resources,": ",e.p.resources.extensions," ext \xb7 ",e.p.resources.skills," skills \xb7 ",e.p.resources.prompts," prompts"]})]}),(0,s.jsxs)("div",{className:"flex items-center justify-end gap-3 pt-1",children:[(0,s.jsx)("button",{disabled:j,style:{fontSize:12,color:"var(--dsw-label-secondary)"},className:"hover:underline cursor-pointer disabled:opacity-50",onClick:()=>void $("update",{source:e.p.source},e.key,a.updating,a.updateSuccess),children:a.update}),(0,s.jsx)("button",{disabled:j,style:{fontSize:12,color:"var(--dsw-danger)"},className:"hover:underline cursor-pointer disabled:opacity-50",onClick:()=>{l(e.p.source)&&$("remove",{source:e.p.source,local:"project"===e.p.scope},e.key,a.uninstalling,a.uninstallSuccess)},children:a.uninstall})]})]}):(0,s.jsx)("div",{className:"break-all",style:{fontFamily:"var(--font-mono)",fontSize:11.5,color:"var(--dsw-label-caption)"},children:e.e.path})})]},e.key)})})]})]})}}}]);
@@ -1 +1 @@
1
- (()=>{"use strict";var e,t,r,o,n,a,i,l,c,u={},s={};function d(e){var t=s[e];if(void 0!==t)return t.exports;var r=s[e]={exports:{}},o=!0;try{u[e].call(r.exports,r,r.exports,d),o=!1}finally{o&&delete s[e]}return r.exports}d.m=u,e=[],d.O=(t,r,o,n)=>{if(r){n=n||0;for(var a=e.length;a>0&&e[a-1][2]>n;a--)e[a]=e[a-1];e[a]=[r,o,n];return}for(var i=1/0,a=0;a<e.length;a++){for(var[r,o,n]=e[a],l=!0,c=0;c<r.length;c++)(!1&n||i>=n)&&Object.keys(d.O).every(e=>d.O[e](r[c]))?r.splice(c--,1):(l=!1,n<i&&(i=n));if(l){e.splice(a--,1);var u=o();void 0!==u&&(t=u)}}return t},d.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return d.d(t,{a:t}),t},r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,d.t=function(e,o){if(1&o&&(e=this(e)),8&o||"object"==typeof e&&e&&(4&o&&e.__esModule||16&o&&"function"==typeof e.then))return e;var n=Object.create(null);d.r(n);var a={};t=t||[null,r({}),r([]),r(r)];for(var i=2&o&&e;"object"==typeof i&&!~t.indexOf(i);i=r(i))Object.getOwnPropertyNames(i).forEach(t=>a[t]=()=>e[t]);return a.default=()=>e,d.d(n,a),n},d.d=(e,t)=>{for(var r in t)d.o(t,r)&&!d.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},d.f={},d.e=e=>Promise.all(Object.keys(d.f).reduce((t,r)=>(d.f[r](e,t),t),[])),d.u=e=>"static/chunks/"+e+"."+({618:"ee5d5bf1c647e483",2155:"2f27fe7098987699",2608:"ec8ff1f5767c9056",2716:"a9e808190a4e2424",4632:"112d2e893d48d188",4673:"d3d0a7f2599080fb"})[e]+".js",d.miniCssF=e=>"static/css/"+({7250:"08815507594e8b8d",8114:"2959bd6b626b7ffe"})[e]+".css",d.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}}(),d.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o={},d.l=(e,t,r,n)=>{if(o[e])return void o[e].push(t);if(void 0!==r)for(var a,i,l=document.getElementsByTagName("script"),c=0;c<l.length;c++){var u=l[c];if(u.getAttribute("src")==e||u.getAttribute("data-webpack")=="_N_E:"+r){a=u;break}}a||(i=!0,(a=document.createElement("script")).charset="utf-8",a.timeout=120,d.nc&&a.setAttribute("nonce",d.nc),a.setAttribute("data-webpack","_N_E:"+r),a.src=d.tu(e)),o[e]=[t];var s=(t,r)=>{a.onerror=a.onload=null,clearTimeout(f);var n=o[e];if(delete o[e],a.parentNode&&a.parentNode.removeChild(a),n&&n.forEach(e=>e(r)),t)return t(r)},f=setTimeout(s.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=s.bind(null,a.onerror),a.onload=s.bind(null,a.onload),i&&document.head.appendChild(a)},d.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},d.tt=()=>(void 0===n&&(n={createScriptURL:e=>e},"u">typeof trustedTypes&&trustedTypes.createPolicy&&(n=trustedTypes.createPolicy("nextjs#bundler",n))),n),d.tu=e=>d.tt().createScriptURL(e),d.p="/_next/",a={8068:0},d.f.miniCss=(e,t)=>{if(a[e])t.push(a[e]);else 0!==a[e]&&({7250:1,8114:1})[e]&&t.push(a[e]=new Promise((t,r)=>{var o=d.miniCssF(e),n=d.p+o;if(((e,t)=>{for(var r=document.getElementsByTagName("link"),o=0;o<r.length;o++){var n=r[o],a=n.getAttribute("data-href")||n.getAttribute("href");if("stylesheet"===n.rel&&(a===e||a===t))return n}for(var i=document.getElementsByTagName("style"),o=0;o<i.length;o++){var n=i[o],a=n.getAttribute("data-href");if(a===e||a===t)return n}})(o,n))return t();((e,t,r,o)=>{var n=document.createElement("link");n.rel="stylesheet",n.type="text/css",n.onerror=n.onload=a=>{if(n.onerror=n.onload=null,"load"===a.type)r();else{var i=a&&("load"===a.type?"missing":a.type),l=a&&a.target&&a.target.href||t,c=Error("Loading CSS chunk "+e+" failed.\n("+l+")");c.code="CSS_CHUNK_LOAD_FAILED",c.type=i,c.request=l,n.parentNode.removeChild(n),o(c)}},n.href=t;if("function"==typeof _N_E_STYLE_LOAD){var a=n.href,i=n.onload,l=n.onerror;_N_E_STYLE_LOAD(0===a.indexOf(window.location.origin)?new URL(a).pathname:a).then(function(){i&&i.call(n,{type:"load"})},function(){l&&l.call(n,{})})}else document.head.appendChild(n)})(e,n,t,r)}).then(()=>{a[e]=0},t=>{throw delete a[e],t}))},i={8068:0,5483:0,7086:0,3334:0},d.f.j=(e,t)=>{var r=d.o(i,e)?i[e]:void 0;if(0!==r)if(r)t.push(r[2]);else if(/^(3334|5483|7086|7250|8068|8114)$/.test(e))i[e]=0;else{var o=new Promise((t,o)=>r=i[e]=[t,o]);t.push(r[2]=o);var n=d.p+d.u(e),a=Error();d.l(n,t=>{if(d.o(i,e)&&(0!==(r=i[e])&&(i[e]=void 0),r)){var o=t&&("load"===t.type?"missing":t.type),n=t&&t.target&&t.target.src;a.message="Loading chunk "+e+" failed.\n("+o+": "+n+")",a.name="ChunkLoadError",a.type=o,a.request=n,r[1](a)}},"chunk-"+e,e)}},d.O.j=e=>0===i[e],l=(e,t)=>{var r,o,[n,a,l]=t,c=0;if(n.some(e=>0!==i[e])){for(r in a)d.o(a,r)&&(d.m[r]=a[r]);if(l)var u=l(d)}for(e&&e(t);c<n.length;c++)o=n[c],d.o(i,o)&&i[o]&&i[o][0](),i[o]=0;return d.O(u)},(c=self.webpackChunk_N_E=self.webpackChunk_N_E||[]).forEach(l.bind(null,0)),c.push=l.bind(null,c.push.bind(c))})();
1
+ (()=>{"use strict";var e,t,r,o,n,a,i,l,c,u={},s={};function d(e){var t=s[e];if(void 0!==t)return t.exports;var r=s[e]={exports:{}},o=!0;try{u[e].call(r.exports,r,r.exports,d),o=!1}finally{o&&delete s[e]}return r.exports}d.m=u,e=[],d.O=(t,r,o,n)=>{if(r){n=n||0;for(var a=e.length;a>0&&e[a-1][2]>n;a--)e[a]=e[a-1];e[a]=[r,o,n];return}for(var i=1/0,a=0;a<e.length;a++){for(var[r,o,n]=e[a],l=!0,c=0;c<r.length;c++)(!1&n||i>=n)&&Object.keys(d.O).every(e=>d.O[e](r[c]))?r.splice(c--,1):(l=!1,n<i&&(i=n));if(l){e.splice(a--,1);var u=o();void 0!==u&&(t=u)}}return t},d.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return d.d(t,{a:t}),t},r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,d.t=function(e,o){if(1&o&&(e=this(e)),8&o||"object"==typeof e&&e&&(4&o&&e.__esModule||16&o&&"function"==typeof e.then))return e;var n=Object.create(null);d.r(n);var a={};t=t||[null,r({}),r([]),r(r)];for(var i=2&o&&e;"object"==typeof i&&!~t.indexOf(i);i=r(i))Object.getOwnPropertyNames(i).forEach(t=>a[t]=()=>e[t]);return a.default=()=>e,d.d(n,a),n},d.d=(e,t)=>{for(var r in t)d.o(t,r)&&!d.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},d.f={},d.e=e=>Promise.all(Object.keys(d.f).reduce((t,r)=>(d.f[r](e,t),t),[])),d.u=e=>"static/chunks/"+e+"."+({618:"ee5d5bf1c647e483",2155:"2f27fe7098987699",2608:"ec8ff1f5767c9056",2716:"a9e808190a4e2424",4632:"0ed92ae42905ce40",4673:"d3d0a7f2599080fb"})[e]+".js",d.miniCssF=e=>"static/css/"+({7250:"08815507594e8b8d",8114:"2959bd6b626b7ffe"})[e]+".css",d.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}}(),d.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o={},d.l=(e,t,r,n)=>{if(o[e])return void o[e].push(t);if(void 0!==r)for(var a,i,l=document.getElementsByTagName("script"),c=0;c<l.length;c++){var u=l[c];if(u.getAttribute("src")==e||u.getAttribute("data-webpack")=="_N_E:"+r){a=u;break}}a||(i=!0,(a=document.createElement("script")).charset="utf-8",a.timeout=120,d.nc&&a.setAttribute("nonce",d.nc),a.setAttribute("data-webpack","_N_E:"+r),a.src=d.tu(e)),o[e]=[t];var s=(t,r)=>{a.onerror=a.onload=null,clearTimeout(f);var n=o[e];if(delete o[e],a.parentNode&&a.parentNode.removeChild(a),n&&n.forEach(e=>e(r)),t)return t(r)},f=setTimeout(s.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=s.bind(null,a.onerror),a.onload=s.bind(null,a.onload),i&&document.head.appendChild(a)},d.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},d.tt=()=>(void 0===n&&(n={createScriptURL:e=>e},"u">typeof trustedTypes&&trustedTypes.createPolicy&&(n=trustedTypes.createPolicy("nextjs#bundler",n))),n),d.tu=e=>d.tt().createScriptURL(e),d.p="/_next/",a={8068:0},d.f.miniCss=(e,t)=>{if(a[e])t.push(a[e]);else 0!==a[e]&&({7250:1,8114:1})[e]&&t.push(a[e]=new Promise((t,r)=>{var o=d.miniCssF(e),n=d.p+o;if(((e,t)=>{for(var r=document.getElementsByTagName("link"),o=0;o<r.length;o++){var n=r[o],a=n.getAttribute("data-href")||n.getAttribute("href");if("stylesheet"===n.rel&&(a===e||a===t))return n}for(var i=document.getElementsByTagName("style"),o=0;o<i.length;o++){var n=i[o],a=n.getAttribute("data-href");if(a===e||a===t)return n}})(o,n))return t();((e,t,r,o)=>{var n=document.createElement("link");n.rel="stylesheet",n.type="text/css",n.onerror=n.onload=a=>{if(n.onerror=n.onload=null,"load"===a.type)r();else{var i=a&&("load"===a.type?"missing":a.type),l=a&&a.target&&a.target.href||t,c=Error("Loading CSS chunk "+e+" failed.\n("+l+")");c.code="CSS_CHUNK_LOAD_FAILED",c.type=i,c.request=l,n.parentNode.removeChild(n),o(c)}},n.href=t;if("function"==typeof _N_E_STYLE_LOAD){var a=n.href,i=n.onload,l=n.onerror;_N_E_STYLE_LOAD(0===a.indexOf(window.location.origin)?new URL(a).pathname:a).then(function(){i&&i.call(n,{type:"load"})},function(){l&&l.call(n,{})})}else document.head.appendChild(n)})(e,n,t,r)}).then(()=>{a[e]=0},t=>{throw delete a[e],t}))},i={8068:0,5483:0,7086:0,3334:0},d.f.j=(e,t)=>{var r=d.o(i,e)?i[e]:void 0;if(0!==r)if(r)t.push(r[2]);else if(/^(3334|5483|7086|7250|8068|8114)$/.test(e))i[e]=0;else{var o=new Promise((t,o)=>r=i[e]=[t,o]);t.push(r[2]=o);var n=d.p+d.u(e),a=Error();d.l(n,t=>{if(d.o(i,e)&&(0!==(r=i[e])&&(i[e]=void 0),r)){var o=t&&("load"===t.type?"missing":t.type),n=t&&t.target&&t.target.src;a.message="Loading chunk "+e+" failed.\n("+o+": "+n+")",a.name="ChunkLoadError",a.type=o,a.request=n,r[1](a)}},"chunk-"+e,e)}},d.O.j=e=>0===i[e],l=(e,t)=>{var r,o,[n,a,l]=t,c=0;if(n.some(e=>0!==i[e])){for(r in a)d.o(a,r)&&(d.m[r]=a[r]);if(l)var u=l(d)}for(e&&e(t);c<n.length;c++)o=n[c],d.o(i,o)&&i[o]&&i[o][0](),i[o]=0;return d.O(u)},(c=self.webpackChunk_N_E=self.webpackChunk_N_E||[]).forEach(l.bind(null,0)),c.push=l.bind(null,c.push.bind(c))})();
package/README.md CHANGED
@@ -16,33 +16,75 @@
16
16
 
17
17
  **PiWeb** brings a sleek, feature-rich browser interface to the [pi coding agent](https://github.com/earendil-works/pi) with zero modifications to the core Pi engine. Install with one command, and all your existing pi configuration, sessions, models, skills, and plugins work out of the box.
18
18
 
19
+ ## Relationship to pi
20
+
21
+ PiWeb and pi are two separate programs, and PiWeb is not another build of pi: it is a web shell that drives the pi already installed on your machine through the official SDK, leaving pi itself untouched. The two **share one set of state** — the same agent directory (`~/.pi/agent`) holds your settings, models and credentials, sessions, skills and packages — so a conversation started in the pi CLI shows up in the browser right away, and the other way round. Updating is **two separate things**: the pi engine and PiWeb each carry their own version and their own update entry point (the two "Check for updates" rows in Settings), and upgrading one leaves the other alone. What runs underneath is native pi; plugin compatibility in the browser, interactive plugins especially, is not finished yet — for now plugins can be managed rather than fully driven from the page.
22
+
19
23
  ## Features
20
24
 
21
25
  ### Real-Time Streaming Chat
22
26
 
23
- Full SSE snapshots with ordered deltas and automatic replay via `Last-Event-ID`. The thinking process and inline tool execution cards stream live.
27
+ Markdown renders as it streams — headings, lists and code blocks take shape before the answer is finished, not after. Thinking and tool calls appear inline as cards. The layout stays restrained: sessions on the left, outline on the right, both collapsible, leaving the screen to the conversation.
28
+
29
+ <p align="center"><img src="assets/main.png" alt="Main page: streaming chat with tool cards" width="840" /></p>
30
+
31
+ ### Chat Navigation
32
+
33
+ The outline on the right of the transcript: **bold entries are messages you sent**, the rest are headings inside the assistant's answers. Collapsed it reads as a column of bars — longer for your messages, shorter the deeper a heading sits; hover to expand the list. It highlights where you are as you scroll, and a click scrolls smoothly to that spot.
24
34
 
25
- <p align="center"><img src="assets/main.png" alt="Streaming chat with tool cards" width="840" /></p>
35
+ <p align="center"><img src="assets/outline.png" alt="Chat navigation: bold entries are your own messages" width="840" /></p>
36
+
37
+ ### Trajectory and Files, In Place
38
+
39
+ Tool cards carry both entry points: **View in trajectory** drops that step into the trajectory panel — a timeline with input / model / tool lanes, laid out by sequence, wall-clock time or duration, searchable, with per-row tokens and timings and detail tabs for summary, preview, raw and source. **Open in editor** jumps straight to the local file that step touched. A card that changed a file also carries the whole diff inline (additions green, deletions red, with +N −M counts), folded to a preview for long changes and expanded on click.
40
+
41
+ <p align="center"><img src="assets/trace-1.png" alt="工具卡片上的两个入口与内联 diff" width="840" /></p>
42
+ <p align="center"><img src="assets/trace-2.png" alt="轨迹入口按钮" /> <img src="assets/trace-3.png" alt="入口按钮细节" /> <img src="assets/trace-4.png" alt="入口按钮细节" /></p>
26
43
 
27
44
  ### Workspaces & Sessions
28
45
 
29
- Sessions grouped by project folder, with a native folder picker (Windows / macOS / Linux), rename and archive. Session tree branches, draft recovery, and JSONL / HTML export.
46
+ Sessions grouped by project folder, with a native folder picker (Windows / macOS / Linux), rename and archive. Archived conversations live together under "Archived" in the sidebar, ready to reopen or unarchive, and **an archived session is deleted automatically after 30 days of inactivity** — no manual cleanup. Session tree branches, draft recovery, and JSONL / HTML export are there too.
47
+
48
+ <p align="center"><img src="assets/archive.png" alt="Archived: archived conversations in one place" width="400" /></p>
30
49
 
31
50
  ### Import Local Sessions
32
51
 
33
- Bring conversation history from Codex, Claude Code, Grok, ZCode, dsh, and opencode on this machine into pi sessions without loss: text, thinking, tool calls and their results, timestamps, and usage are all kept, and the source data is **read-only** — nothing in the other tools is modified. If the original project directory still exists locally the session lands in that workspace; otherwise it falls back to one you pick. Find it under Settings → Import sessions. The 15 most recent conversations per source are listed, and anything already imported is marked and cannot be imported twice.
52
+ Bring conversation history from Codex, Claude Code, Grok, ZCode, dsh and opencode on this machine into pi sessions without loss: text, thinking, tool calls and their results, timestamps and usage are all kept, and the source data is **read-only** — nothing in the other tools is modified. Each source lists only its 15 most recent **main** conversations; work the main agent handed to a subagent is ignored, because the conversation you want is your own. If the original project directory still exists locally the session lands in that workspace, otherwise it falls back to one you pick — and anything already imported is marked and never imported twice.
53
+
54
+ <p align="center"><img src="assets/import.png" alt="Settings → Import sessions: pick a source, tick, import" width="840" /></p>
34
55
 
35
56
  ### Project Growth Tree
36
57
 
37
- Every step the agent takes on your codebase is snapshotted: navigate the timeline round by round, see added/modified/deleted files, and open line-level diffs for any file at any step — even if the workspace has no git history of its own.
58
+ Every file operation pi makes is snapshotted, grouped one round per message you send. Each round shows what changed **relative to the previous one** — files added, modified and deleted, with line-level diffs one click away — so you can review the work round by round, or drill into single steps inside a round. A round with no file changes says so instead of being skipped, and the record is independent of git: it works on a project with no version history at all.
59
+
60
+ <p align="center"><img src="assets/growth-1.png" alt="Project growth tree (1 of 2)" width="840" /></p>
61
+ <p align="center"><img src="assets/growth-2.png" alt="Project growth tree (2 of 2)" width="840" /></p>
62
+
63
+ ### File Viewer
64
+
65
+ Open project files in the page instead of switching to an editor: a centered window with tabs, and fuzzy search behind the "+". Each file has three views — **Changes** (whole-file diff, additions green and deletions red, with one-click jumps between changes), **Content** (line numbers and syntax highlighting; deleted files show their last content), and **Rendered** (Markdown as a document). Quote a selection into the composer, or open the file in your local editor.
66
+
67
+ <p align="center"><img src="assets/viewer-1.png" alt="File viewer (1 of 2)" width="840" /></p>
68
+ <p align="center"><img src="assets/viewer-2.png" alt="File viewer (2 of 2)" width="840" /></p>
38
69
 
39
70
  ### Context Meter
40
71
 
41
72
  Click the ring next to the composer to see the context window broken down into 13 segments — System Prompt, System/Custom Tools, Memory (AGENTS.md), Skills, messages by type, Compacted Data, Auto-Compact Buffer, and Free Space.
42
73
 
74
+ ### Prompt Sources
75
+
76
+ A header button opens a panel listing every prompt that reaches the model's context: the system prompt and its appended sections, project memory (`AGENTS.md`), each skill's `SKILL.md`, prompt templates, tool definitions, plus the assembled prompt actually sent and the compaction summary — each row labelled with where it came from (project / personal / package / extension). Click a row to read the original in the centre viewer. The list is enumerated live for the current workspace, so prompts that arrive with a plugin or package installed later show up on refresh.
77
+
78
+ <p align="center"><img src="assets/prompts-1.png" alt="Prompt sources (1 of 2)" width="840" /></p>
79
+ <p align="center"><img src="assets/prompts-2.png" alt="Prompt sources (2 of 2)" width="840" /></p>
80
+
43
81
  ### Model & Provider Management
44
82
 
45
- 30+ built-in providers, OAuth logins (Claude, Codex, Copilot, etc.), custom providers written to `models.json`, one-click model discovery, and a placeholder key auto-filled for local gateways like Ollama.
83
+ 40 built-in providers, signed in with an API key or OAuth — Anthropic, GitHub Copilot, OpenAI Codex, xAI, OpenRouter, Kimi and Radius support one-click OAuth. Anything else works just as well: give a custom provider its base URL, protocol and models, and it lands in `models.json`; local gateways such as Ollama get a placeholder key automatically. Pull the model catalog in one click, and quota or balance reads (Claude, Codex, xAI, DeepSeek and 7 more) sit right on the provider card.
84
+
85
+ <p align="center"><img src="assets/providers-1.png" alt="Provider setup (1 of 3)" width="840" /></p>
86
+ <p align="center"><img src="assets/providers-2.png" alt="Provider setup (2 of 3)" width="840" /></p>
87
+ <p align="center"><img src="assets/providers-3.png" alt="Provider setup (3 of 3)" width="840" /></p>
46
88
 
47
89
  ### Plugins & Skills
48
90
 
@@ -63,6 +105,8 @@ piweb
63
105
 
64
106
  The package registers only the `piweb` command, so it never conflicts with the official `pi` CLI. Requires Node.js ≥ 22.19.0 (24 recommended); Git is needed for growth-history features.
65
107
 
108
+ On Windows x64 and ARM64, npm automatically installs PiWeb's matching managed [niubash](https://github.com/unixwin/niubash) portable runtime. PiWeb uses it as the `bash` tool through the official Pi SDK—no separate shell install and no changes to `~/.pi/agent/settings.json`. macOS and Linux continue to use Pi's normal system Bash selection. If the optional Windows runtime is omitted or fails integrity validation, PiWeb logs a warning and falls back to Pi's configured/default Bash.
109
+
66
110
  ### Update
67
111
 
68
112
  ```bash
@@ -104,4 +148,4 @@ Set `PI_WEB_PASSWORD` to enable the login page and HTTP Basic Auth (user `pi`).
104
148
 
105
149
  ## License
106
150
 
107
- [MIT](LICENSE)
151
+ [MIT](LICENSE). The optional Windows runtime packages redistribute niubash, rubash, and WinuxCmd under their upstream licenses; the pinned notices are in [`third-party/managed-niubash`](third-party/managed-niubash).
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
package/next.config.ts CHANGED
@@ -13,8 +13,12 @@ export default (phase: string): NextConfig => {
13
13
  // Webpack's dev chunk names are stable. A per-process prefix prevents an older
14
14
  // browser cache entry from hydrating HTML emitted by a newer dev server.
15
15
  assetPrefix: development ? `/_piweb-dev/${devAssetId}` : undefined,
16
- // pi SDK 与其动态加载的扩展都运行在服务端(Node runtime),不对客户端打包
17
- serverExternalPackages: ["@earendil-works/pi-coding-agent"],
16
+ // pi SDK、动态扩展与 Windows 平台运行时都留在服务端由 Node 原生加载。
17
+ serverExternalPackages: [
18
+ "@earendil-works/pi-coding-agent",
19
+ "@rexvane/piweb-niubash-win32-x64",
20
+ "@rexvane/piweb-niubash-win32-arm64",
21
+ ],
18
22
  // Image prompts allow 268 MB of base64 plus text and JSON framing.
19
23
  experimental: { proxyClientMaxBodySize: "272mb" },
20
24
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rexvane/piweb",
3
- "version": "0.3.14",
3
+ "version": "0.3.15",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "Modern web UI for the pi coding agent, driven by the official pi SDK without modifying pi",
@@ -28,7 +28,7 @@
28
28
  "src",
29
29
  "scripts",
30
30
  "public",
31
- "assets/showcase.png",
31
+ "assets",
32
32
  "next.config.ts",
33
33
  "tsconfig.json",
34
34
  "postcss.config.mjs",
@@ -39,9 +39,9 @@
39
39
  "build": "node --max-old-space-size=8192 node_modules/next/dist/bin/next build --webpack",
40
40
  "build:release": "node scripts/release.mjs",
41
41
  "postinstall": "node scripts/postinstall.mjs",
42
+ "prepare:niubash": "node scripts/prepare-niubash-packages.mjs",
42
43
  "prepublishOnly": "npm run typecheck && npm run test",
43
44
  "start": "node bin/piweb.js",
44
- "web": "node bin/pi.js web",
45
45
  "typecheck": "tsc --noEmit",
46
46
  "verify:package": "node scripts/verify-package.mjs",
47
47
  "test": "vitest run",
@@ -73,6 +73,10 @@
73
73
  "tailwindcss": "^4.2.2",
74
74
  "typescript": "^7"
75
75
  },
76
+ "optionalDependencies": {
77
+ "@rexvane/piweb-niubash-win32-arm64": "1.1.4-piweb.0",
78
+ "@rexvane/piweb-niubash-win32-x64": "1.1.4-piweb.0"
79
+ },
76
80
  "devDependencies": {
77
81
  "@testing-library/dom": "^10.4.2",
78
82
  "@testing-library/react": "^16.3.3",
@@ -169,7 +169,7 @@ export async function runLauncher({ args = process.argv.slice(2), env = process.
169
169
  const options = parseLauncherArgs(args, env);
170
170
  const log = dependencies.log ?? console.log;
171
171
  if (options.help) {
172
- log("Usage: pi web [-p, --port <port>] [-H, --hostname <host>] [--dev] [--no-open]");
172
+ log("Usage: piweb [-p, --port <port>] [-H, --hostname <host>] [--dev] [--no-open]");
173
173
  log("默认绑定 127.0.0.1:30141;端口被占自动 +1。开发模式仅允许本机监听。");
174
174
  log("对外监听必须使用生产构建与 PI_WEB_PASSWORD。构建/恢复发布:npm run build:release。");
175
175
  return 0;