@openchamber/web 2.7.1 → 2.7.2-canary.20261112.18

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 (117) hide show
  1. package/dist/assets/{AboutDialog-Byc63m0u.js → AboutDialog-CD63uz39.js} +1 -1
  2. package/dist/assets/{AboutLogo-BwwjES_b.js → AboutLogo-2kHLExbm.js} +1 -1
  3. package/dist/assets/{ArchiveView-DIg8Bq5r.js → ArchiveView-D9AL3G55.js} +1 -1
  4. package/dist/assets/{ChangeRequestDiffUnavailable-DtCWp1bf.js → ChangeRequestDiffUnavailable-BFaXu17a.js} +1 -1
  5. package/dist/assets/{CommandPalette-D1G7W43z.js → CommandPalette-wJg29t3M.js} +1 -1
  6. package/dist/assets/{DataFileArtifact-BPwh4rIZ.js → DataFileArtifact-B8OGvXN-.js} +1 -1
  7. package/dist/assets/{DiffView-B9-zXR21.js → DiffView-CAhUZy1p.js} +1 -1
  8. package/dist/assets/{FilesView-CTKhKCjC.js → FilesView-Bad_K4vM.js} +3 -3
  9. package/dist/assets/{GitView-2p131yFW.js → GitView-ESiTCDSw.js} +1 -1
  10. package/dist/assets/{GuestPanelContent-BY7I-Y-o.js → GuestPanelContent-BHcsCOcI.js} +1 -1
  11. package/dist/assets/{HelpDialog-BfDxlsKj.js → HelpDialog-CLkDLRCv.js} +1 -1
  12. package/dist/assets/{IntegrationsCatalogView-DX9AlNKS.js → IntegrationsCatalogView-CreW2QU2.js} +1 -1
  13. package/dist/assets/{JsonTreeView-Ghbn2jaO.js → JsonTreeView-CuPCB2B8.js} +1 -1
  14. package/dist/assets/{MarkdownDiffPreview-CcER_eYB.js → MarkdownDiffPreview-rDAnCu-X.js} +1 -1
  15. package/dist/assets/{MarkdownRendererImpl-DjBAwXof.js → MarkdownRendererImpl-BQO-q7Gs.js} +4 -4
  16. package/dist/assets/{MemoryDebugPanel-MrH6vI6i.js → MemoryDebugPanel-BA6eNPT5.js} +1 -1
  17. package/dist/assets/{NoteEditor-DnaXw3v6.js → NoteEditor-H5Z5TEv5.js} +1 -1
  18. package/dist/assets/{OfficeArtifact-av3so80I.js → OfficeArtifact-Dp7UZZNN.js} +2 -2
  19. package/dist/assets/{OfficeDocumentDiff-C-XvqPYx.js → OfficeDocumentDiff-Cm9lGPXQ.js} +1 -1
  20. package/dist/assets/{OnboardingScreen-Dlbi5e0G.js → OnboardingScreen-IeS_KnCh.js} +1 -1
  21. package/dist/assets/{OpenCodeStatusDialog-BZzdMaVU.js → OpenCodeStatusDialog-CGFzdIrc.js} +1 -1
  22. package/dist/assets/{OverviewView-CQ82APO2.js → OverviewView-C6HXytWH.js} +1 -1
  23. package/dist/assets/{PatchDiff-EZ_WbikC.js → PatchDiff-DxkfAF18.js} +1 -1
  24. package/dist/assets/{PlanView-jUry4bXu.js → PlanView-D8IoHTf_.js} +1 -1
  25. package/dist/assets/{ProjectActionsDialog-Bt6OXdLD.js → ProjectActionsDialog-BWduOyXA.js} +1 -1
  26. package/dist/assets/{ReplyCommand-CLNJlG5f.js → ReplyCommand-BjRiG3jU.js} +1 -1
  27. package/dist/assets/{ReplyUiBlock-DthlzVWC.js → ReplyUiBlock-B_mKHYbN.js} +1 -1
  28. package/dist/assets/{ReviewCards-qePUMD-z.js → ReviewCards-BnpUajD4.js} +1 -1
  29. package/dist/assets/{RunOverview-CvD2Q7KM.js → RunOverview-BQY-GREp.js} +1 -1
  30. package/dist/assets/{ScheduledTasksDialog-Dtdb6owf.js → ScheduledTasksDialog-CtlWd_VV.js} +1 -1
  31. package/dist/assets/{SettingsView-JBCXhydZ.js → SettingsView-CgbOYmvV.js} +1 -1
  32. package/dist/assets/{SettingsWindow-RJIA1rl5.js → SettingsWindow-ByKOH90R.js} +1 -1
  33. package/dist/assets/{SidebarSectionsManager-4i4NcHs0.js → SidebarSectionsManager-DqrV_u__.js} +1 -1
  34. package/dist/assets/{SourceBoardView-BuYJw-Sp.js → SourceBoardView-B0aGQnwC.js} +1 -1
  35. package/dist/assets/{SpaceAccessDialog-B4-bPo9e.js → SpaceAccessDialog-DMsJ-sxh.js} +1 -1
  36. package/dist/assets/{SpaceApplyDialog-DjTQ5PZT.js → SpaceApplyDialog-3UONCZIV.js} +1 -1
  37. package/dist/assets/{SpaceRow-CYk17vzn.js → SpaceRow-BJuduShI.js} +1 -1
  38. package/dist/assets/{SpaceSetupOutput-DRDEgMzx.js → SpaceSetupOutput-ro_nF8gr.js} +1 -1
  39. package/dist/assets/{SpacesView-BSt0xE6N.js → SpacesView-BqoY_SpZ.js} +1 -1
  40. package/dist/assets/{SubmoduleDiffSummary-CTwpN0TO.js → SubmoduleDiffSummary-NjPxpgMr.js} +1 -1
  41. package/dist/assets/{TableArtifact-BGTFUrHC.js → TableArtifact-oqOE37_Y.js} +1 -1
  42. package/dist/assets/{ToolOutputDialog-DcQ4eDvb.js → ToolOutputDialog-Bqv2rByf.js} +1 -1
  43. package/dist/assets/{ToolPartDiffPreview-idv0MY3G.js → ToolPartDiffPreview-SklZNjf9.js} +1 -1
  44. package/dist/assets/{UiBlock-CVYWc3Px.js → UiBlock-D3PdhNSP.js} +2 -2
  45. package/dist/assets/{UsageStatsView-Cgo61IDa.js → UsageStatsView-DM3iZLEy.js} +1 -1
  46. package/dist/assets/{WalkthroughView-CYr8y2pi.js → WalkthroughView-2TaZc0MB.js} +1 -1
  47. package/dist/assets/{WorktreesView-Duwvqggr.js → WorktreesView-aba8lY_x.js} +1 -1
  48. package/dist/assets/{appThemeRegistry-DgyhfFpu.js → appThemeRegistry-BrFExrgv.js} +1 -1
  49. package/dist/assets/{ar-zwtOisVI.js → ar-DuOBHgr_.js} +1 -1
  50. package/dist/assets/{codeHighlight-DQ8KOMKI.js → codeHighlight-mEwmnZVN.js} +1 -1
  51. package/dist/assets/{columnWidthMemory-Ol4D51DU.js → columnWidthMemory-NVG-9uFM.js} +1 -1
  52. package/dist/assets/{computeVirtualFileMetrics-P_6wH9ys.js → computeVirtualFileMetrics-DkXi0qX-.js} +2 -2
  53. package/dist/assets/{contextFileOpenGuard-9zXH1DLm.js → contextFileOpenGuard-DFp3E2Gd.js} +1 -1
  54. package/dist/assets/{date-time-CRucRasX.js → date-time-DRGzhBlp.js} +1 -1
  55. package/dist/assets/{de-5cm4El6N.js → de-DpOf_BMg.js} +1 -1
  56. package/dist/assets/{documentClient-BbTBnbCU.js → documentClient-UXIlVIAK.js} +2 -2
  57. package/dist/assets/{documentHost-Dxv6OV6h.js → documentHost-BWtn8iCI.js} +1 -1
  58. package/dist/assets/{editorCodeMetrics-BzYZ4PzQ.js → editorCodeMetrics-BaoTimWj.js} +1 -1
  59. package/dist/assets/{es-CYh9u5rf.js → es-BextOZlH.js} +1 -1
  60. package/dist/assets/{fileContentPoller-p6RiDNz7.js → fileContentPoller-BV7Knoib.js} +1 -1
  61. package/dist/assets/{flexokiTheme-BNUmLj3l.js → flexokiTheme-tyakPldH.js} +1 -1
  62. package/dist/assets/{fr-gZGCwYzk.js → fr-BJEccZsE.js} +1 -1
  63. package/dist/assets/{he-DWb3dvEl.js → he-9oI-aOhB.js} +1 -1
  64. package/dist/assets/{highlights-DWR6MS75.js → highlights-8Aapk9tv.js} +1 -1
  65. package/dist/assets/{index-BcEWRtz8.js → index-D0ue7E3H.js} +1 -1
  66. package/dist/assets/{initializeSharedPreferences-u4U22OVN.js → initializeSharedPreferences-DNUHFeIw.js} +1 -1
  67. package/dist/assets/{install-request-C0o_6GEa.js → install-request-DI6T7dQX.js} +1 -1
  68. package/dist/assets/{install-CkKsKExH.js → install-s_PIiJvM.js} +1 -1
  69. package/dist/assets/{isDiffPlainText-B70cjgtm.js → isDiffPlainText-BcgZ-0g8.js} +1 -1
  70. package/dist/assets/{isFilePlainText-DNNat5m3.js → isFilePlainText-DCv6hsjs.js} +1 -1
  71. package/dist/assets/{ja-CAeb9wyo.js → ja-Bf_2zWyq.js} +1 -1
  72. package/dist/assets/{katex.min-2cmqKX7p.js → katex.min-CAwHaRYk.js} +4 -4
  73. package/dist/assets/{ko-DuYqVIuP.js → ko-BAGf67hm.js} +1 -1
  74. package/dist/assets/{main-kUMMbMdC.js → main-CZBlb0Vm.js} +4 -4
  75. package/dist/assets/{main-D9Ri_lHo.js → main-g_cZWPOo.js} +2 -2
  76. package/dist/assets/{miniChat-HoE2mQuK.js → miniChat-jzqDFSB-.js} +2 -2
  77. package/dist/assets/{mobile-BFQ0eaJT.js → mobile-4zqwQ7Sj.js} +2 -2
  78. package/dist/assets/{moveWorkspacePath-BkzUq9fV.js → moveWorkspacePath-D4BOjl1P.js} +1 -1
  79. package/dist/assets/{nl-BPlUOQoY.js → nl-MVCsXAqA.js} +1 -1
  80. package/dist/assets/{officeDocument-C74tIqpD.js → officeDocument-CnopQpfD.js} +1 -1
  81. package/dist/assets/{parseDiffFromFile-COnIA377.js → parseDiffFromFile-CdzPmTcc.js} +1 -1
  82. package/dist/assets/{pierreDiffTint-9AmpxGGB.js → pierreDiffTint-CVXkDTiH.js} +1 -1
  83. package/dist/assets/{pl-DZRSuGdV.js → pl-zi2r4I2L.js} +1 -1
  84. package/dist/assets/{pt-BR-fU-ttTba.js → pt-BR-D-thkXCk.js} +1 -1
  85. package/dist/assets/{relocateRestoredSession-DawfZWX6.js → relocateRestoredSession-CL5sou6T.js} +2 -2
  86. package/dist/assets/{renderElectronMiniChatApp-q30Gq6wf.js → renderElectronMiniChatApp-ByeC9_X9.js} +2 -2
  87. package/dist/assets/{renderMarkdownForExport-0rL6OK8T.js → renderMarkdownForExport-B2BahH3V.js} +1 -1
  88. package/dist/assets/{renderMobileApp-B_PjVgBu.js → renderMobileApp-BHQf77yR.js} +3 -3
  89. package/dist/assets/{resolveLanguages-dF0QdGAX.js → resolveLanguages-D-TyRYRT.js} +1 -1
  90. package/dist/assets/{runtimeEndpointReset-BsAAA4Nf.js → runtimeEndpointReset-DKWDEJh9.js} +5 -5
  91. package/dist/assets/{scheduledTasksApi-CB-Xtp2P.js → scheduledTasksApi-DIaiATcl.js} +1 -1
  92. package/dist/assets/{shiki-CVNu2J2E.js → shiki-CTynytaK.js} +1 -1
  93. package/dist/assets/{space-apply-BmOleF8W.js → space-apply-CYC8IOgP.js} +1 -1
  94. package/dist/assets/{space-close-DqG3RGoP.js → space-close-CDpywx5q.js} +1 -1
  95. package/dist/assets/{spaceNetwork-DUGLrihG.js → spaceNetwork-DYE6zemZ.js} +1 -1
  96. package/dist/assets/{stream-tokenizer-Bzos6Fhy.js → stream-tokenizer-DHz3vo2_.js} +1 -1
  97. package/dist/assets/{textMateThemeFromAppTheme-BRUbLAuj.js → textMateThemeFromAppTheme-ZHLiHrUo.js} +1 -1
  98. package/dist/assets/{tr-CD93vntx.js → tr-BeLCIXLh.js} +1 -1
  99. package/dist/assets/{uk-DTqcJvdn.js → uk-CWz0kaNm.js} +1 -1
  100. package/dist/assets/{useAppFontEffects-xaAfmUwn.js → useAppFontEffects-DEX5CMOn.js} +15 -15
  101. package/dist/assets/{useBranchPullRequestRequest-CIftwmmA.js → useBranchPullRequestRequest-CulIXVeT.js} +1 -1
  102. package/dist/assets/{useCallableModelProviders-DYpBJMqj.js → useCallableModelProviders-CV8ihNIz.js} +1 -1
  103. package/dist/assets/{useDiffFindSurface-CqxU53Ed.js → useDiffFindSurface-DcsqijBv.js} +1 -1
  104. package/dist/assets/{useGitCleanLine-CmVX9s9E.js → useGitCleanLine-DvEtGCIy.js} +1 -1
  105. package/dist/assets/{useInlineCommentController-C-V8vqSj.js → useInlineCommentController-BL4NrAAM.js} +1 -1
  106. package/dist/assets/{useMarkdownLocalAssets-BfOLz9Xm.js → useMarkdownLocalAssets-6zcqySrf.js} +1 -1
  107. package/dist/assets/{useRootScrollLock-Ciuj2iZ_.js → useRootScrollLock-BHTza82m.js} +1 -1
  108. package/dist/assets/{useWalkthroughReview-BdjnKO7o.js → useWalkthroughReview-C_afIgqu.js} +1 -1
  109. package/dist/assets/{useWholeFileComment-DkYtu1tm.js → useWholeFileComment-WwfwT0jq.js} +1 -1
  110. package/dist/assets/{useWorktreeArchiveActions-DGzuZU_x.js → useWorktreeArchiveActions-CORhov5Z.js} +1 -1
  111. package/dist/assets/{vendor-codemirror-language-data-CSQf665k.js → vendor-codemirror-language-data--j1xV4at.js} +2 -2
  112. package/dist/assets/{zh-CN-BJ4oeBCY.js → zh-CN-D2e-OTjQ.js} +1 -1
  113. package/dist/assets/{zh-TW-BMW1G3F_.js → zh-TW-DCj_Doyh.js} +1 -1
  114. package/dist/index.html +2 -2
  115. package/dist/mini-chat.html +2 -2
  116. package/dist/mobile.html +2 -2
  117. package/package.json +3 -3
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-heic2any-CRnROUpT.js","assets/vendor-react--VO_rL_p.js","assets/vendor-scheduler-7OC5HNn7.js","assets/zh-CN-BJ4oeBCY.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-zustand-C9tWdk0j.js","assets/vendor-zod-B_hXR7jf.js","assets/vendor-opencode-client-NJGkA1Ku.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/vendor-streamdown-BbSYZ3NF.js","assets/vendor-markdown-BTUqNk6W.js","assets/vendor-mdast-util-from-markdown-CZHjOE75.js","assets/vendor-micromark-util-decode-numeric-character-reference-CNs1qBpV.js","assets/vendor-micromark-util-decode-string-fHsnqYdj.js","assets/vendor-decode-named-character-reference-C3-224fz.js","assets/vendor-micromark-util-normalize-identifier-C9ANKk3v.js","assets/vendor-micromark-AWM-NZXP.js","assets/vendor-micromark-util-combine-extensions-d8XJZrgA.js","assets/vendor-micromark-util-chunked-DrRIdSP-.js","assets/vendor-micromark-factory-space-PzSHLgmq.js","assets/vendor-micromark-util-character-CW3Cu1MS.js","assets/vendor-micromark-core-commonmark-kzTLNXAm.js","assets/vendor-micromark-util-classify-character-tcLuZZwM.js","assets/vendor-micromark-util-resolve-all-PQCKh0dx.js","assets/vendor-micromark-util-subtokenize-BF1Jf29a.js","assets/vendor-micromark-factory-destination-Sj0xfi0V.js","assets/vendor-micromark-factory-label-amyP0HdC.js","assets/vendor-micromark-factory-title-khnLkZK6.js","assets/vendor-micromark-factory-whitespace-eIB00uTl.js","assets/vendor-micromark-util-html-tag-name-DbKNfynz.js","assets/vendor-unist-util-stringify-position-Ch_qCilz.js","assets/vendor-mdast-util-to-string-C_aolqmU.js","assets/vendor-unist-util-visit-DhPeCsfG.js","assets/vendor-unist-util-visit-parents-DlviEg7Z.js","assets/vendor-unist-util-is-BPZGFiMU.js","assets/vendor-hast-util-raw-DvvLJg15.js","assets/vendor-ungap-structured-clone--gfxRhYI.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-parse5-DwmzEj2o.js","assets/vendor-entities-wUUgTZDW.js","assets/vendor-web-namespaces-bsVAaBS1.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-unist-util-position-60F3QETU.js","assets/vendor-hast-util-from-parse5-Ba3T6RJI.js","assets/vendor-devlop-0Dp3JUBc.js","assets/vendor-property-information-Boo8Xpef.js","assets/vendor-hastscript-BrPNioaz.js","assets/vendor-comma-separated-tokens-CRUGqg4f.js","assets/vendor-space-separated-tokens-D7QSIrTI.js","assets/vendor-hast-util-parse-selector-TXfch5wI.js","assets/vendor-vfile-location-LfEFwJ2h.js","assets/vendor-hast-util-to-parse5-BoysVIPW.js","assets/vendor-hast-util-sanitize-2aGO5ay8.js","assets/vendor-micromark-extension-gfm-CsfPlnlB.js","assets/vendor-micromark-extension-gfm-autolink-literal-BYug7onl.js","assets/vendor-micromark-extension-gfm-footnote-OFl1FCH2.js","assets/vendor-micromark-extension-gfm-strikethrough-CyFiuwBf.js","assets/vendor-micromark-extension-gfm-table-dgw4LfUw.js","assets/vendor-micromark-extension-gfm-task-list-item-Dnadzr9U.js","assets/vendor-mdast-util-gfm-CroMDYLM.js","assets/vendor-mdast-util-gfm-autolink-literal-CTruMtvI.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-mdast-util-find-and-replace-DB9iC-bx.js","assets/vendor-escape-string-regexp-BaJN9MlJ.js","assets/vendor-mdast-util-gfm-footnote-C-csI7OF.js","assets/vendor-mdast-util-gfm-strikethrough-BcskTdio.js","assets/vendor-mdast-util-gfm-table-DhPwQIyj.js","assets/vendor-markdown-table-DvhhVmnL.js","assets/vendor-mdast-util-to-markdown-Cl3qaiyc.js","assets/vendor-longest-streak-CtXnX3Xp.js","assets/vendor-mdast-util-phrasing-4oVbNLC3.js","assets/vendor-mdast-util-gfm-task-list-item-DMU5mK_M.js","assets/vendor-mdast-util-to-hast-CWnLaQSO.js","assets/vendor-micromark-util-sanitize-uri-BbwQ7CLk.js","assets/vendor-trim-lines-D8znQY54.js","assets/vendor-micromark-extension-cjk-friendly-BzZDGrF5.js","assets/vendor-micromark-extension-cjk-friendly-util-D5lVNoxW.js","assets/vendor-get-east-asian-width-CPhS2cOv.js","assets/vendor-micromark-util-symbol-JJPacVTp.js","assets/vendor-mdast-util-to-markdown-cjk-friendly-BZ3pe_qd.js","assets/vendor-micromark-extension-cjk-friendly-gfm-strikethrough-CqW-Ep4M.js","assets/vendor-mdast-util-to-markdown-cjk-friendly-gfm-strikethrough-BdPDQFO7.js","assets/vendor-hast-util-from-html-isomorphic-B0Kn01s9.js","assets/vendor-hast-util-from-dom-DeNf9aYW.js","assets/vendor-katex-DBqql0K7.js","assets/vendor-hast-util-to-text-0GXLnBvt.js","assets/vendor-hast-util-is-element-CuOmiqQi.js","assets/vendor-unist-util-find-after-CMaZmLxc.js","assets/vendor-micromark-extension-math-BRFoDziv.js","assets/vendor-mdast-util-math-wB-IJCL0.js","assets/vendor-remend-r8cP_t-e.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-marked-DN3zOnEe.js","assets/vendor-hast-util-to-jsx-runtime-Bq6JeJCx.js","assets/vendor-style-to-js-CI2G4dgu.js","assets/vendor-style-to-object-BAv4SQXc.js","assets/vendor-inline-style-parser-BlqBsVO4.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/vendor-estree-util-is-identifier-name-BgBfM8ME.js","assets/vendor-vfile-message-DqhD22jI.js","assets/vendor-unified-1CQKw2_w.js","assets/vendor-bail-FqpXQuLt.js","assets/vendor-extend-B94qxKr5.js","assets/vendor-is-plain-obj-C1gvLhAf.js","assets/vendor-trough-B_b8ryxu.js","assets/vendor-vfile-BCWrK60u.js","assets/vendor-html-url-attributes-D46m5wfe.js","assets/vendor-capacitor-core-B4EWRrHz.js","assets/fr-gZGCwYzk.js","assets/nl-BPlUOQoY.js","assets/zh-TW-BMW1G3F_.js","assets/es-CYh9u5rf.js","assets/pt-BR-fU-ttTba.js","assets/uk-DTqcJvdn.js","assets/ko-DuYqVIuP.js","assets/pl-DZRSuGdV.js","assets/de-5cm4El6N.js","assets/ja-CAeb9wyo.js","assets/tr-CD93vntx.js","assets/ar-zwtOisVI.js","assets/he-DWb3dvEl.js","assets/vendor-capacitor-app-BrDJj9I_.js"])))=>i.map(i=>d[i]);
2
- import{_ as Ge}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as Rt,d as jn,p as oi,a as $v}from"./vendor-zustand-C9tWdk0j.js";import{o as d,s as c,n as w,l as m,f as y,c as C,e as X,_ as S,u as M,a as ke,j as at,h as ne,i as Qv,k as wr,p as xs,q as tr,v as Yv,w as Kr,x as Xv,N as eC,y as tC,z as vi}from"./vendor-zod-B_hXR7jf.js";import{e as Xh,C as Vu}from"./vendor-opencode-client-NJGkA1Ku.js";import{f as kt,R as ta,r as sC}from"./vendor-react--VO_rL_p.js";import{F as ef}from"./vendor-fuse.js-Dw8P0qyA.js";import{X as aC}from"./vendor-streamdown-BbSYZ3NF.js";import{u as nC}from"./vendor-unified-1CQKw2_w.js";import{c as oC}from"./vendor-markdown-BTUqNk6W.js";import{registerPlugin as iC}from"./vendor-capacitor-core-B4EWRrHz.js";const bo=1,rC=d({type:m("relay-retire"),code:w().int(),reason:c().catch("")}),cC=e=>{try{const t=rC.safeParse(JSON.parse(e));return t.success?{code:t.data.code,reason:t.data.reason}:null}catch{return null}},lC="openchamber-relay-v1",tf=1,sf=12,ko=1+sf,Bo=64*1024,Lo=5,yr=128,af=0,nf=1,bn=4,dC=1+bn,Ol=Bo-Lo-dC,pC="x-openchamber-tunnel-accept-encoding",uC="x-openchamber-tunnel-content-encoding",ce={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12,DeliveryAck:13},gC=new Set(Object.values(ce)),mC=e=>gC.has(e),Ys={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},ks=globalThis.crypto.subtle,of={name:"ECDH",namedCurve:"P-256"},rf=16,Tc=32,hC=16,Dl=4,cf=8;class Js extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const fC=()=>ks.generateKey(of,!0,["deriveBits"]),bC=async e=>{const t=await ks.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},kC=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new Js("invalid ECDH public key JWK");try{return await ks.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},of,!0,[])}catch{throw new Js("invalid ECDH public key JWK")}},wC=()=>{const e=new Uint8Array(rf);return globalThis.crypto.getRandomValues(e),e},yC=async(e,t,s)=>{if(s.length!==rf)throw new Js("invalid handshake nonce length");const a=await ks.deriveBits({name:"ECDH",public:t},e,256),n=await ks.importKey("raw",a,"HKDF",!1,["deriveBits"]),o=new Uint8Array(await ks.deriveBits({name:"HKDF",hash:"SHA-256",salt:s,info:new TextEncoder().encode(lC)},n,Tc*2*8)),i=(r,l)=>ks.importKey("raw",r,{name:"AES-GCM"},!1,l);return{clientToHost:await i(o.slice(0,Tc),["encrypt","decrypt"]),hostToClient:await i(o.slice(Tc),["encrypt","decrypt"])}},vC=(e,t,s)=>{for(let a=cf-1;a>=0;a-=1)e[t+a]=Number(s&0xffn),s>>=8n},CC=(e,t)=>{let s=0n;for(let a=0;a<cf;a+=1)s=s<<8n|BigInt(e[t+a]);return s},SC=e=>{const t=new Uint8Array(Dl);globalThis.crypto.getRandomValues(t);let s=0n;return{async encrypt(a){if(a.length>Bo)throw new Js("plaintext frame exceeds maximum size");s+=1n;const n=new Uint8Array(sf);n.set(t,0),vC(n,Dl,s);const o=new Uint8Array(await ks.encrypt({name:"AES-GCM",iv:n},e,a)),i=new Uint8Array(ko+o.length);return i[0]=tf,i.set(n,1),i.set(o,ko),i}}},PC=e=>{let t=0n;return{async decrypt(s){if(s.length<ko+hC)throw new Js("encrypted frame too short");if(s[0]!==tf)throw new Js("unsupported encrypted frame version");const a=s.slice(1,ko),n=CC(a,Dl);if(n<=t)throw new Js("frame counter regression");let o;try{o=await ks.decrypt({name:"AES-GCM",iv:a},e,s.slice(ko))}catch{throw new Js("frame decryption failed")}return t=n,new Uint8Array(o)}}},Ci="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",xC=e=>{let t="";for(let s=0;s<e.length;s+=3){const a=e[s],n=s+1<e.length?e[s+1]:void 0,o=s+2<e.length?e[s+2]:void 0;t+=Ci[a>>2],t+=Ci[(a&3)<<4|(n??0)>>4],n!==void 0&&(t+=Ci[(n&15)<<2|(o??0)>>6]),o!==void 0&&(t+=Ci[o&63])}return t},Uu=e=>{let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;const s=t;if(s.v!==bo)return null;const a=s.batch===!0,n=s.flowControl===!0;return s.t==="ready"?{t:"ready",v:bo,batch:a,flowControl:n}:s.t==="hello"&&typeof s.nonce=="string"&&typeof s.clientPubJwk=="object"&&s.clientPubJwk!==null?{t:"hello",v:bo,clientPubJwk:s.clientPubJwk,nonce:s.nonce,batch:a,flowControl:n}:null},TC=e=>({type:"fail",closeCode:Ys.ChannelFailure,reason:e}),AC=async(e,t={})=>{const s=t.batch!==!1,a=await kC(e),n=await fC(),o=wC(),i={t:"hello",v:bo,clientPubJwk:await bC(n.publicKey),nonce:xC(o)};s&&(i.batch=!0),t.flowControl!==!1&&(i.flowControl=!0);let r=!1;return{helloText:JSON.stringify(i),get established(){return r},async handleText(l){if(r)return Uu(l)?.t==="ready"?{type:"ignore"}:TC("plaintext frame on established channel");const p=Uu(l);if(p?.t!=="ready")return{type:"ignore"};const u=await yC(n.privateKey,a,o);return r=!0,{type:"established",batch:s&&p.batch===!0,flowControl:t.flowControl!==!1&&p.flowControl===!0,channel:{encryptor:SC(u.clientToHost),decryptor:PC(u.hostToClient)}}}}},lf=4294967295,zC=e=>{if(!Number.isSafeInteger(e)||e<0)throw new Error("invalid delivery acknowledgement");const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e)),t};class _e extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const Dt=(e,t,s,a=!1)=>{if(!Number.isInteger(t)||t<0||t>lf)throw new _e("invalid stream id");if(s.length>Ol)throw new _e("tunnel payload exceeds maximum size");const n=new Uint8Array(Lo+s.length);return n[0]=a?e|yr:e,n[1]=t>>>24&255,n[2]=t>>>16&255,n[3]=t>>>8&255,n[4]=t&255,n.set(s,Lo),n},RC=e=>{if(e.length<Lo)throw new _e("tunnel frame too short");const t=e[0],s=(t&yr)!==0,a=t&~yr;if(!mC(a))throw new _e(`unknown tunnel frame type ${a}`);const n=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:a,streamId:n,payload:e.slice(Lo),hasMoreFragments:s}},IC=new TextEncoder,jC=new TextDecoder,Si=e=>IC.encode(JSON.stringify(e)),Pi=(e,t)=>{let s;try{s=JSON.parse(jC.decode(e))}catch{throw new _e("malformed JSON tunnel payload")}if(!t(s))throw new _e("unexpected JSON tunnel payload shape");return s},df=(e,t=Ol)=>{if(t<=0||t>Ol)throw new _e("invalid chunk size");if(e.length===0)return[new Uint8Array(0)];const s=[];for(let a=0;a<e.length;a+=t)s.push(e.slice(a,a+t));return s},Wu=(e,t,s)=>{const a=df(s);return a.map((n,o)=>Dt(e,t,n,o<a.length-1))},OC=(e=16*1024*1024)=>{const t=new Map;return{push(s){const a=`${s.streamId}:${s.frameType}`,n=t.get(a);if(!s.hasMoreFragments&&!n)return s.payload;const o=n?.chunks??[],i=(n?.totalBytes??0)+s.payload.length;if(i>e)throw t.delete(a),new _e("fragmented message exceeds maximum size");if(o.push(s.payload),s.hasMoreFragments)return t.set(a,{chunks:o,totalBytes:i}),null;t.delete(a);const r=new Uint8Array(i);let l=0;for(const p of o)r.set(p,l),l+=p.length;return r},dropStream(s){for(const a of t.keys())a.startsWith(`${s}:`)&&t.delete(a)}}},DC=e=>{if(e.length===0)throw new _e("cannot encode an empty frame batch");if(e.length===1){const n=e[0],o=new Uint8Array(1+n.length);if(o[0]=af,o.set(n,1),o.length>Bo)throw new _e("frame batch exceeds maximum plaintext size");return o}let t=1;for(const n of e)t+=bn+n.length;if(t>Bo)throw new _e("frame batch exceeds maximum plaintext size");const s=new Uint8Array(t);s[0]=nf;let a=1;for(const n of e)s[a]=n.length>>>24&255,s[a+1]=n.length>>>16&255,s[a+2]=n.length>>>8&255,s[a+3]=n.length&255,a+=bn,s.set(n,a),a+=n.length;return s},NC=e=>{if(e.length<1)throw new _e("empty batch plaintext");const t=e[0];if(t===af)return[e.slice(1)];if(t!==nf)throw new _e(`unknown batch container tag ${t}`);const s=[];let a=1;for(;a<e.length;){if(a+bn>e.length)throw new _e("truncated batch frame length");const n=(e[a]<<24|e[a+1]<<16|e[a+2]<<8|e[a+3])>>>0;if(a+=bn,a+n>e.length)throw new _e("truncated batch frame body");s.push(e.slice(a,a+n)),a+=n}if(s.length===0)throw new _e("empty frame batch");return s},FC=new Set([ce.HttpBody,ce.WsText,ce.WsBinary]),pf=150,EC=24*1024,MC=32,BC=e=>{const t=e.windowMs??pf,s=e.maxBatchBytes??EC,a=e.maxBatchFrames??MC,n=e.now??(()=>Date.now()),o=e.setTimer??((v,P)=>setTimeout(v,P)),i=e.clearTimer??(v=>clearTimeout(v));let r=[],l=0,p=null,u=0,g=!1;const h=()=>{p!==null&&(i(p),p=null)},b=()=>{if(h(),r.length===0)return;const v=r;r=[],l=0,u=n(),e.sendBatch(DC(v))};return{enqueue:v=>{if(g)return;const P=v[0]&~yr;if(!FC.has(P)){r.push(v),b();return}const z=n();if(r.length===0&&z-u>=t){r.push(v),b();return}const x=bn+v.length;if(r.length>0&&1+l+x>Bo&&b(),r.push(v),l+=x,l>=s||r.length>=a){b();return}p===null&&(p=o(b,t))},flush:b,dispose(){g=!0,h(),r=[],l=0}}},LC=()=>{let e=1;return{next(){if(e>lf)throw new _e("stream id space exhausted");const t=e;return e+=2,t}}},Zr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qC=e=>Zr(e)&&Object.values(e).every(t=>typeof t=="string"),VC=e=>Zr(e)&&typeof e.status=="number"&&qC(e.headers),Hu=e=>Zr(e)&&typeof e.reason=="string",UC=e=>Zr(e)&&typeof e.code=="number"&&typeof e.reason=="string",uf=/^[a-z][a-z\d+.-]*:\/\//i,cp="http://tunnel.invalid",WC=e=>{try{const t=uf.test(e)?new URL(e):new URL(e,cp);return`${t.pathname}${t.search}`}catch{return e}},xi=e=>({async*[Symbol.asyncIterator](){yield e}}),HC=e=>({async*[Symbol.asyncIterator](){const t=e.getReader();try{for(;;){const{done:s,value:a}=await t.read();if(s)return;a&&(yield a)}}finally{t.releaseLock()}}}),GC=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},_C=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:HC(e)};if(typeof e=="string")return{body:xi(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:xi(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:xi(GC(e))};const t=new Response(e),s=t.headers.get("content-type")??void 0,a=new Uint8Array(await t.arrayBuffer());return{body:xi(a),contentType:s}},KC=async(e,t)=>{let s;const a=new Headers;let n="GET",o=null,i;e instanceof Request?(s=e.url,n=e.method,e.headers.forEach((g,h)=>a.set(h,g)),i=e.signal,o=e.body):s=e.toString(),t&&(t.method&&(n=t.method),t.headers&&new Headers(t.headers).forEach((g,h)=>a.set(h,g)),t.body!==void 0&&(o=t.body),t.signal&&(i=t.signal));const r=uf.test(s)?new URL(s):new URL(s,cp),{body:l,contentType:p}=await _C(o);p&&!a.has("content-type")&&a.set("content-type",p);const u={};return a.forEach((g,h)=>{u[h]=g}),{method:n.toUpperCase(),path:r.pathname,query:r.search.startsWith("?")?r.search.slice(1):r.search,headers:u,body:l,signal:i}},gf="__openchamberAmbiguousTransport",mf=new WeakSet,ZC=e=>(mf.add(e),e),JC=e=>mf.has(e),Nl=e=>(Object.defineProperty(e,gf,{value:!0,enumerable:!1,configurable:!0}),e),$C=e=>!e||typeof e!="object"?!1:e[gf]===!0,QC=["local","remote",null],YC=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function hf(e){if(!e||typeof e!="object")return{valid:!1};const t=e,s=t.localAvailable===!1?{localAvailable:!1}:{},a=t.target,n=t.status;if(a!==null&&(typeof a!="string"||!QC.includes(a)))return{valid:!1};if(typeof n!="string"||!YC.includes(n))return{valid:!1};if(a==="remote"||a==="local"){if(n==="ok"&&a==="local"){const o={target:"local",status:"ok",...s},i=c().min(1).safeParse(t.sshStartupFallbackHostId);return i.success&&(o.sshStartupFallbackHostId=i.data),{valid:!0,outcome:o}}if(n==="ok"&&a==="remote")return typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"ok",hostId:t.hostId,url:t.url,...s}};if(n==="unreachable")return a==="local"?{valid:!0,outcome:{target:"local",status:"unreachable",...s}}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"unreachable",hostId:t.hostId,url:t.url,...s}};if(n==="incompatible"||n==="wrong-service")return a!=="remote"?{valid:!1}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:n,hostId:t.hostId,url:t.url,...s}};if(n==="missing")return a!=="remote"?{valid:!1}:typeof t.hostId!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"missing",hostId:t.hostId,...s}}}if(a===null){if(n==="not-configured")return{valid:!0,outcome:{target:null,status:"not-configured",...s}};if(n==="missing")return{valid:!1}}return{valid:!1}}function Z_(e){if(!e.isDesktopShell)return null;const t=e.bootOutcome;if(!t)return null;const s=t.localAvailable===!1?{localAvailable:!1}:{};if(t.status==="ok"){if(t.target==="local")return{screen:"main",...s};if(t.target==="remote")return{screen:"main",hostId:t.hostId,url:t.url,...s}}if(t.target===null&&t.status==="not-configured")return{screen:"chooser",...s};if(t.target==="local"&&t.status==="unreachable")return{screen:"chooser",...s};if(t.target==="remote"){if(t.status==="unreachable")return{screen:"recovery",variant:"remote-unreachable",hostId:t.hostId,url:t.url,...s};if(t.status==="incompatible")return{screen:"recovery",variant:"remote-incompatible",hostId:t.hostId,url:t.url,...s};if(t.status==="wrong-service")return{screen:"recovery",variant:"remote-wrong-service",hostId:t.hostId,url:t.url,...s};if(t.status==="missing")return{screen:"recovery",variant:"remote-missing",hostId:t.hostId,...s}}return null}function J_(e){return!e.isDesktopShell||e.bootOutcomeKnown}function $_(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function ff(){if(XC()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,s=hf(t);return s.valid?s.outcome:null}function XC(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":hf(e).valid?"valid":"malformed"}const vr=/^[a-z][a-z\d+.-]*:\/\//i,eS=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},Cr=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),tS=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return Cr(e)},sS=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return Cr(e)},aS=()=>Object.keys(Nn()).length>0,nS=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},Fl=(e,t)=>{if(!t)return;const s=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[a,n]of s)n!=null&&e.searchParams.set(a,String(n))},oS=(e,t)=>{if(!t)return e;const s=new URLSearchParams;Fl({searchParams:s},t);const a=s.toString();return a?e.includes("?")?`${e}&${a}`:`${e}?${a}`:e},Gu=(e,t,s)=>{if(vr.test(t)){const i=new URL(t);return Fl(i,s),i.toString()}const a=eS(t);if(!e)return oS(a,s);const n=new URL(e),o=new URL(`${n.origin}${n.pathname.replace(/\/+$/,"")}${a}`);return Fl(o,s),o.toString()},Ti=(e,t=HS())=>{if(!t)return e;const s=vr.test(e)?new URL(e):new URL(e,"http://openchamber.local");return s.searchParams.set("oc_url_token",t),vr.test(e)?s.toString():`${s.pathname}${s.search}${s.hash}`},bf=(e,t)=>{const s=vr.test(e)?new URL(e):new URL(e,nS(t));return s.protocol==="ws:"||s.protocol==="wss:"||(s.protocol=s.protocol==="https:"?"wss:":"ws:"),s.toString()},_u=(e,t,s)=>{if(!aS())return null;const a=sS();if(!a)return null;try{const n=new URL(`/api/openchamber/realtime-proxy/${e==="sse"?"sse":"ws"}`,`${a}/`);n.searchParams.set("url",t);const o=GS(a);return o&&n.searchParams.set("oc_url_token",o),e==="ws"?(n.protocol=n.protocol==="https:"?"wss:":"ws:",bf(n.toString(),s)):n.toString()}catch{return null}},lp=(e={})=>{const t=Cr(e.apiBaseUrl),s=Cr(e.realtimeBaseUrl),a=()=>t||tS(),n=()=>s||a(),o=(r,l)=>Gu(a(),r,l),i=(r,l)=>Gu(n(),r,l);return{api:o,authenticatedAsset:(r,l)=>Ti(o(r,l)),assetWithUrlToken:(r,l,p)=>Ti(o(r,p),l),auth:o,health:r=>o("/health",r),rawFile:(r,l)=>o("/api/fs/raw",{path:r,download:l?.download===!0?!0:void 0,allowOutsideWorkspace:l?.allowOutsideWorkspace===!0?!0:void 0,outsideFileGrant:l?.outsideFileGrant}),sse:(r,l)=>{const p=Ti(i(r,l));return _u("sse",p,e)||p},websocket:(r,l)=>{const p=bf(Ti(i(r,l)),e);return _u("ws",p,e)||p}}};let Sr=lp();const vs=()=>Sr,iS=e=>{Sr=e},kf=e=>(Sr=lp(e),Sr),dp=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,qo=()=>{const e=dp();return e?Array.isArray(e.workspaceFolders)?e.workspaceFolders.length===0:!e.workspaceFolder?.trim():!1},pp=(e=dp())=>!!e,El="openchamber:runtime-endpoint-changed",Ml="openchamber:runtime-endpoint-will-change";let kn="",Vo="",Bl=0,Ll=null;const Ac=(e,t,s)=>{try{e[t]=s}catch{}},up=e=>{try{const t=new URL(e);return t.hash="",t.search="",t.pathname=t.pathname.replace(/\/+$/,"")||"/",`url:${t.toString().replace(/\/+$/,"")}`}catch{return`url:${e.trim().replace(/\/+$/,"")||"default"}`}},rS="mobile-disconnected",cS="url:default",ql=e=>e===""||e===rS||e===cS&&!pp(),wf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},yf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},vf=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},ns=()=>kn||wf(),lS=()=>{if(Ll!==null)return Ll;const e=ns();return!!(e&&e===globalThis.window?.__OPENCHAMBER_SSH_FORWARD_API_URL__)};let zc="",Ku=null,Zu,Ju;const $u=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},N=()=>{if(Vo)return Vo;const e=$u("__OPENCHAMBER_API_BASE_URL__"),t=$u("__OPENCHAMBER_LOCAL_ORIGIN__");if(Ku===kn&&Zu===e&&Ju===t)return zc;const s=ns();return zc=vf(s,yf())?"local":up(s),Ku=kn,Zu=e,Ju=t,zc},sr=()=>{const e=Bl,t=N();return()=>e===Bl&&t===N()},dS=(e={})=>{if(kn||Vo)return;const t=e.apiBaseUrl?.trim()||wf(),s=globalThis.window?.location?.origin??"",a=/^https?:\/\//.test(s)?s:"";if(!t&&!a)return;const n=yf(),o=n&&(!t||vf(t,n));kn=t,Vo=e.runtimeKey?.trim()||(o?"local":up(t||a))},Vl=e=>{const t=e.apiBaseUrl.trim(),s=ns(),a=N(),n=e.runtimeKey?.trim()||up(t),o=e.sshForwarded??(t===s&&n===a&&lS()),i={apiBaseUrl:t,previousApiBaseUrl:s,runtimeKey:n,previousRuntimeKey:a};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ml,{detail:i})),kn=t,Vo=n,n!==a&&(Bl+=1),Ll=o,typeof window<"u"){const r=window;Ac(r,"__OPENCHAMBER_API_BASE_URL__",t),Ac(r,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),Ac(r,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}kf({apiBaseUrl:t,realtimeBaseUrl:t}),Ef(e.requestHeaders||null),Ff(e.clientToken||null),e.relay?MS(e.relay):BS(),Xr(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(El,{detail:i}))},Jr=e=>{if(typeof window>"u")return()=>{};const t=s=>{e(s.detail)};return window.addEventListener(Ml,t),()=>window.removeEventListener(Ml,t)},$r=e=>{if(typeof window>"u")return()=>{};const t=s=>{e(s.detail)};return window.addEventListener(El,t),()=>window.removeEventListener(El,t)};let Ul=null;const Q_=e=>{Ul=e},On=()=>Ul||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),pS=e=>e==="stable"||e==="canary",uS=/^v?(\d+\.\d+\.\d+)-canary\.(\d{4})(\d{2})(\d{2})(?:\.(\d+))?$/,Y_=e=>{const t=uS.exec(e??"");if(!t)return null;const[,s,a,n,o,i]=t;return{release:s,builtOn:new Date(Date.UTC(Number(a),Number(n)-1,Number(o))),build:i?Number(i):null}},gS=(e,t)=>new Intl.DateTimeFormat(t,{day:"numeric",month:"short",timeZone:"UTC"}).format(e),X_=(e,t,s)=>{const a=gS(e.builtOn,t);return s!=null&&s.builtOn.getTime()===e.builtOn.getTime()&&s.build!==e.build&&e.build!==null?`${a} #${e.build}`:a},Cf=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,Ts=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,ja=()=>Cf()?.runtime==="electron",Sf=()=>{if(typeof window>"u")return null;const e=window.__OPENCHAMBER_PLATFORM__;return typeof e=="string"?e:null},mS="right",e0=()=>{if(!ja())return!1;const e=Sf();return e==="linux"?Cf()?.nativeFrame!==!0:e==="win32"},t0=e=>e==="left"?"left":mS,s0=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],rt=()=>typeof Ts()?.invoke=="function",wt=()=>ja()&&rt(),hS=()=>{const e=Ts()?.clipboard;if(!e?.readSelection||!e.writeSelection)return;const{readSelection:t,writeSelection:s}=e;return{selection:{readText:async()=>c().parse(await t()),writeText:async a=>{m(!0).parse(await s(a))}}}},fS=()=>{if(Ts()?.pickThemeFile)return{async pick(){const e=Ts()?.pickThemeFile;return e?{status:"picked",file:d({name:c(),size:w().nonnegative(),text:c()}).nullable().parse(await e())}:{status:"unsupported"}}}},oe=async(e,t)=>{const s=Ts();return typeof s?.invoke!="function"?null:s.invoke(e,t??{})},a0=e=>{Sf()!=="darwin"||!wt()||oe("desktop_clear_session_notifications",{sessionId:e}).catch(()=>{})},n0=()=>({apiBaseUrl:ns(),clientToken:bp(),runtimeKey:N()}),o0=async()=>{if(!ot()||!ze())return!1;const e=ns();try{const t=y().safeParse(await oe("desktop_managed_opencode_compatible",{apiBaseUrl:e}));return t.success&&t.data&&e===ns()}catch{return!1}},i0=async()=>{if(!wt()||!ze())return null;try{const e=await oe("desktop_get_launch_at_login");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get launch at login status",e),null}},r0=async e=>{if(!wt()||!ze())return null;try{const t=await oe("desktop_set_launch_at_login",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set launch at login status",t),null}},Pf=e=>pS(e?.channel)?e.channel:null,c0=async()=>{if(!wt()||!ze())return null;try{return Pf(await oe("desktop_get_update_channel"))}catch(e){return console.warn("Failed to get the update channel",e),null}},l0=async e=>{if(!wt()||!ze())return null;try{return Pf(await oe("desktop_set_update_channel",{channel:e}))}catch(t){return console.warn("Failed to set the update channel",t),null}},d0=async()=>{if(!wt()||!ze())return null;try{const e=await oe("desktop_get_minimize_to_tray");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get minimize to tray status",e),null}},p0=async e=>{if(!wt()||!ze())return null;try{const t=await oe("desktop_set_minimize_to_tray",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set minimize to tray status",t),null}},u0=async()=>{if(!wt()||!ze())return null;try{const e=await oe("desktop_get_mini_chat_global_shortcut");return!e||typeof e.supported!="boolean"||e.combo!==null&&typeof e.combo!="string"||typeof e.active!="boolean"?null:e}catch(e){return console.warn("Failed to get Mini Chat global shortcut status",e),null}},g0=async e=>{if(!wt()||!ze())return null;try{const t=await oe("desktop_set_mini_chat_global_shortcut",{combo:e});return!t||typeof t.supported!="boolean"||t.combo!==null&&typeof t.combo!="string"||typeof t.active!="boolean"||t.error!==void 0&&t.error!=="unsupported-combo"?null:t}catch(t){return console.warn("Failed to set Mini Chat global shortcut",t),null}},bS=d({supported:y(),enabled:y(),combo:c().nullable(),storedCombo:c().nullable(),active:y(),heightFraction:w(),error:m("unsupported-combo").optional()}),Qr=async(e,t,s)=>{if(!wt()||!ze())return null;try{const a=bS.safeParse(await oe(e,t));return a.success?a.data:null}catch(a){return console.warn(s,a),null}},m0=()=>Qr("desktop_get_quake_mode",{},"Failed to get Quake Mode status"),h0=e=>Qr("desktop_set_quake_mode_enabled",{enabled:e},"Failed to set Quake Mode"),f0=e=>Qr("desktop_set_quake_mode_shortcut",{combo:e},"Failed to set Quake Mode shortcut"),b0=e=>Qr("desktop_set_quake_mode_height",{heightFraction:e},"Failed to set Quake Mode height"),k0=async()=>{if(!wt()||!ze())return null;try{const e=await oe("desktop_get_keep_awake");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"||typeof e.active!="boolean"?null:e}catch(e){return console.warn("Failed to get keep awake status",e),null}},w0=async e=>{if(!wt()||!ze())return null;try{const t=await oe("desktop_set_keep_awake",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"||typeof t.active!="boolean"?null:t}catch(t){return console.warn("Failed to set keep awake status",t),null}},Qu=e=>{const t=e.trim();if(!t)return null;try{return new URL(t).origin}catch{try{return new URL(t.endsWith("/")?t:`${t}/`).origin}catch{return null}}},Rc=e=>{const t=e.trim();if(!t)return null;try{return new URL(t)}catch{try{return new URL(t.endsWith("/")?t:`${t}/`)}catch{return null}}},kS=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),Zn=e=>{const t=kS(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},ze=()=>{if(typeof window>"u"||!ot())return!1;if(N()==="local")return!0;const e=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",t=Rc(e),s=Rc(ns());if(!s&&t&&ff()?.target==="local")return!0;if(t&&s){if(t.origin===s.origin)return!0;const i=t.port||(t.protocol==="https:"?"443":"80"),r=s.port||(s.protocol==="https:"?"443":"80");return t.protocol===s.protocol&&i===r&&Zn(t.hostname)&&Zn(s.hostname)}const a=Rc(window.location.origin);if(t&&a){if(t.origin===a.origin)return!0;const i=t.port||(t.protocol==="https:"?"443":"80"),r=a.port||(a.protocol==="https:"?"443":"80");return t.protocol===a.protocol&&i===r&&Zn(t.hostname)&&Zn(a.hostname)}const n=Qu(e),o=Qu(window.location.origin)||window.location.origin;return n&&o&&n===o?!0:!!(a&&Zn(a.hostname))},ot=()=>typeof window>"u"?!1:ja(),y0=async()=>{if(!ot())return null;const e=d({visible:y()}).safeParse(await oe("desktop_get_current_window_state"));return e.success?e.data.visible:null},v0=async()=>{if(!ot())return!1;try{return!!await oe("desktop_focus_window")}catch{return!1}},C0=(e,t,s=null)=>!t||t===N()||!wt()?!1:(oe("desktop_open_host_session",s?{runtimeKey:t,sessionId:e,messageId:s}:{runtimeKey:t,sessionId:e}).catch(n=>{console.warn("[desktop] failed to open host session",n)}),!0),xf=()=>ot()&&rt()&&ze(),wS=C(d({sessionId:c().min(1),messageId:c().min(1).optional(),runtimeKey:c().min(1).optional(),requireKnownSession:y().optional()})),S0=async()=>{if(!ot())return[];try{const e=C(c()).safeParse(await oe("desktop_take_pending_extension_installs"));return e.success?e.data:[]}catch{return[]}},P0=async()=>{if(!ot()||!ze())return[];try{const e=wS.safeParse(await oe("desktop_take_pending_session_links"));return e.success?e.data.map(t=>({sessionId:t.sessionId,messageId:t.messageId??null,runtimeKey:t.runtimeKey??null,requireKnownSession:t.requireKnownSession===!0})):[]}catch(e){return console.warn("Failed to read pending session links",e),[]}},yS=C(X("type",[d({type:m("pairing"),link:c().min(1)}),d({type:m("host"),hostId:c().min(1)})])),x0=async()=>{if(!ot())return[];try{const e=yS.safeParse(await oe("desktop_take_pending_host_actions"));return e.success?e.data:[]}catch(e){return console.warn("Failed to read pending host actions",e),[]}},vS=c().min(1),T0=e=>{if(!xf())return null;try{const t=vS.safeParse(Ts()?.pathForFile?.(e));return t.success?t.data:null}catch(t){return console.warn("Failed to resolve dropped file path",t),null}},A0=async()=>{if(!ot())return!1;try{return await oe("desktop_start_window_drag"),!0}catch{return!1}},Ee=()=>pp()?!0:On()?.runtime?.isVSCode===!0,z0=()=>{const t=On()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!Ee()},R0=(e,t=ot())=>e==="web"&&!t,Tf=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},I0=async e=>{if(xf())try{const t=await Ts()?.openDialog?.({directory:!0,multiple:!1,title:"Select Working Directory",...e?{defaultPath:e}:{}});return!t||typeof t!="string"?{success:!1,error:"Directory selection cancelled"}:{success:!0,path:t}}catch(t){return console.warn("Failed to request directory access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native directory picker not available"}},CS=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),j0=async e=>{if(rt()&&ze())try{const t=await Ts()?.openDialog?.({directory:!1,multiple:!1,title:"Select File",returnGrant:!0,...e?.filters?{filters:e.filters}:{},...e?.defaultPath?{defaultPath:e.defaultPath}:{}});if(!t)return{success:!1,error:"File selection cancelled"};if(typeof t=="string")return{success:!0,path:t};if(!CS(t))return{success:!1,error:"File selection cancelled"};const s=typeof t.path=="string"?t.path:"";return s?{success:!0,path:s,outsideFileGrant:typeof t.outsideFileGrant=="string"?t.outsideFileGrant:void 0}:{success:!1,error:"File selection cancelled"}}catch(t){return console.warn("Failed to request file access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native file picker not available"}},O0=async e=>({success:!0}),D0=async e=>({success:!0}),N0=async()=>rt()?await oe("desktop_check_for_updates"):null,F0=async e=>{if(!rt())return!1;const t=Ts();let s=null,a=0,n;try{return typeof e=="function"&&t?.listen&&(s=await t.listen("openchamber:update-progress",o=>{const i=o?.payload;if(!i||typeof i!="object")return;const r=i,l=typeof r.event=="string"?r.event:null,p=r.data&&typeof r.data=="object"?r.data:null;if(l==="Started"){a=0,n=typeof p?.contentLength=="number"?p.contentLength:void 0,e({downloaded:a,total:n});return}if(l==="Progress"){const u=p?.downloaded,g=p?.total;typeof u=="number"&&(a=u),typeof g=="number"&&(n=g),e({downloaded:a,total:n});return}l==="Finished"&&e({downloaded:a,total:n})})),await oe("desktop_download_and_install_update"),!0}catch(o){throw o instanceof Error?o:new Error(String(o))}finally{if(s)try{const o=s();o instanceof Promise&&await o}catch{}}},E0=async()=>rt()?(await oe("desktop_restart"),!0):!1,M0=async()=>{if(!rt())return!1;try{return await oe("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},B0=async()=>{if(!rt()||!ze())return null;try{const e=await oe("desktop_get_lan_address");return typeof e=="string"&&e.trim().length>0?e.trim():null}catch(e){return console.warn("Failed to get desktop LAN address",e),null}},SS=async(e,t)=>{if(!rt()||!ze())return!1;const s=e?.trim();if(!s)return!1;try{return await oe("desktop_open_path",{path:s,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),!0}catch(a){return console.warn("Failed to open path",a),!1}},L0=async e=>{if(!rt()||!ze())return!1;const t=e?.trim();if(!t)return!1;try{return await oe("desktop_reveal_path",{path:t}),!0}catch{return SS(t)}},q0=async(e,t)=>{if(!rt()||!ze())return null;const s=e?.trim();if(!s)return null;try{const a=await oe("desktop_save_markdown_file",{defaultFileName:s,content:t});return typeof a=="string"&&a.trim().length>0?a:null}catch(a){return console.warn("Failed to save markdown file",a),null}},V0=async(e,t,s)=>{if(!rt()||!ze())return!1;const a=e?.trim(),n=t?.trim(),o=s?.trim();if(!a||!n||!o)return!1;try{return await oe("desktop_open_in_app",{projectPath:a,appId:n,appName:o}),!0}catch(i){return console.warn("Failed to open project in app",i),!1}},U0=async(e,t,s)=>{if(!rt()||!ze())return!1;const a=e?.trim(),n=t?.trim(),o=s?.trim();if(!a||!n||!o)return!1;try{return await oe("desktop_open_file_in_app",{filePath:a,appId:n,appName:o}),!0}catch(i){return console.warn("Failed to open file in app",i),!1}},W0=async(e,t)=>{if(!rt()||!ze())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const s=Array.isArray(e)?e.filter(a=>typeof a=="string"):[];if(s.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const a=await oe("desktop_get_installed_apps",{apps:s,force:t===!0?!0:void 0});if(!a||typeof a!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const n=a;return n.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(n.apps)?{apps:n.apps.filter(i=>i&&typeof i=="object").map(i=>{const r=i;return{name:typeof r.name=="string"?r.name:"",iconDataUrl:typeof r.iconDataUrl=="string"?r.iconDataUrl:null}}).filter(i=>i.name.length>0),success:!0,hasCache:n.hasCache===!0,isCacheStale:n.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(a){return console.warn("Failed to fetch installed apps",a),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},H0=()=>navigator.platform.toLowerCase().startsWith("linux"),Oa=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",G0=()=>typeof window>"u"||!Oa()?!1:Af()==="ios"&&PS(),PS=()=>{if(typeof navigator>"u")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},Af=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Ee()?"vscode":ot()?"desktop":"web"},xS="2.7.1",Ai=new Uint8Array(0),TS=typeof DecompressionStream=="function",AS=e=>e.pipeThrough(new TransformStream({transform(t,s){s.enqueue(t.buffer instanceof ArrayBuffer?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t))}})).pipeThrough(new DecompressionStream("gzip")),zf=e=>ArrayBuffer.isView(e)?e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):e,zS=new TextEncoder,RS=new TextDecoder,Ot=e=>e instanceof Error?e:new Error(String(e)),zi=()=>new DOMException("The operation was aborted.","AbortError"),IS=e=>{e.binaryType="arraybuffer";const t={get readyState(){return e.readyState},send(s){e.send(zf(s))},close(s,a){e.close(s,a)},onopen:null,onmessage:null,onclose:null,onerror:null};return e.onopen=()=>t.onopen?.(),e.onmessage=s=>t.onmessage?.({data:s.data}),e.onclose=s=>t.onclose?.({code:s.code,reason:s.reason}),e.onerror=()=>t.onerror?.(),t},jS=e=>{const t={get readyState(){return e.readyState},get binaryType(){return e.binaryType},set binaryType(s){s&&(e.binaryType=s)},onopen:null,onmessage:null,onerror:null,onclose:null,send(s){e.send(zf(s))},close(s,a){e.close(s,a)}};return e.onopen=()=>t.onopen?.(),e.onmessage=s=>{const a=s.data;(typeof a=="string"||a instanceof ArrayBuffer)&&t.onmessage?.({data:a})},e.onerror=()=>t.onerror?.(),e.onclose=s=>t.onclose?.({code:s.code,reason:s.reason}),t},OS=e=>e?.state==="error"&&e.closeCode===Ys.LimitExceeded,Yu=0,Ic=1,Xu=2,eg=3,DS=new Set([Ys.AuthFailed,Ys.DuplicateClient,Ys.LimitExceeded]),NS={[Ys.AuthFailed]:"relay authentication failed",[Ys.DuplicateClient]:"relay connection replaced by another client",[Ys.LimitExceeded]:"relay connection limit reached"},jc=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},gp=e=>{const t=e.helloRetryMs??1e3,s=e.helloTimeoutMs??3e4,a=e.pingIntervalMs??3e4,n=e.pingTimeoutMs??15e3,o=e.batchWindowMs??pf,i=e.batch!==!1,r=e.reconnectBaseDelayMs??1e3,l=e.reconnectMaxDelayMs??3e4,p=e.hiddenOrOfflineMaxDelayMs??6e4,u=e.createWireSocket??(q=>IS(new WebSocket(q)));let g=!1,h=null,b={state:"idle"};const k=new Set;let v=null,P=null,z=null,x=0,j=0,V=null,Z=[],B=!1;const W=q=>{if(!(b.state===q.state&&b.lastError===q.lastError&&b.terminal===q.terminal&&b.closeCode===q.closeCode)){b=q;for(const he of k)try{he(b)}catch{}}},_=q=>{const he=Z;Z=[];for(const J of he)J.reject(q)},te=q=>{const he=Z;Z=[];for(const J of he)J.resolve(q)},se=(q,he)=>{q.dead=!0;const J=Array.from(q.streams.values());q.streams.clear();for(const Q of J)try{Q.fail(he)}catch{}},Ve=()=>{V!==null&&(clearTimeout(V),V=null)},Hn=()=>{if(!g){if(V!==null){if(jc())return;Ve(),It(),Ba();return}jc()||na()}},na=()=>{g||h===null||(It(),h=null,Ba())},$=()=>{typeof document<"u"&&document.visibilityState==="visible"&&Hn()},ut=()=>{B||typeof window>"u"||(B=!0,window.addEventListener("online",Hn),typeof document<"u"&&document.addEventListener("visibilitychange",$))},It=()=>{!B||typeof window>"u"||(B=!1,window.removeEventListener("online",Hn),typeof document<"u"&&document.removeEventListener("visibilitychange",$))},Gn=()=>{if(g||V!==null)return;const q=Math.max(0,j-1),he=r*2**Math.min(q,10),J=jc()?p:l,Q=Math.min(J,he);ut(),V=setTimeout(()=>{V=null,It(),Ba()},Q)},Cc=()=>{const q=new URL(e.relayUrl);return q.searchParams.set("v",String(bo)),q.searchParams.set("role","client"),q.searchParams.set("serverId",e.serverId),q.searchParams.set("appId","openchamber"),q.searchParams.set("appVersion",xS),q.searchParams.set("platform",Af()),e.grant&&q.searchParams.set("grant",e.grant),q.toString()},Ba=async()=>{if(g)return;Ve(),x+=1;const q=x;W({state:j>0?"reconnecting":"connecting",lastError:b.lastError});let he;try{he=await AC(e.hostEncPubJwk,{batch:i,flowControl:e.flowControl})}catch(be){if(q!==x||g)return;qu(q,Ot(be),!0);return}if(q!==x||g)return;let J;try{J=u(Cc())}catch(be){qu(q,Ot(be));return}P=J;let Q=!1,ae=null,fe=null,gt=null,Ue=null,re=Promise.resolve(),le=null,De=null,cs=!1,Be=!1,Le=0,We=0,He=null,ls=null,Te=Date.now();const js=()=>{He!==null&&(clearTimeout(He),He=null),ae!==null&&(clearInterval(ae),ae=null),fe!==null&&(clearTimeout(fe),fe=null),gt!==null&&(clearInterval(gt),gt=null),Ue!==null&&(clearTimeout(Ue),Ue=null),ls!==null&&(ls.dispose(),ls=null)};z=js;function we(be,Re=!1,ye=null){if(!(Q||q!==x)){Q=!0,ye!==null&&(h=be),js(),le&&(v=null,se(le,new Error(`relay tunnel reset: ${be.message}`))),_(be);try{J.close()}catch{}if(P===J&&(P=null),!g){if(j+=1,ye!==null){ut(),W({state:"error",lastError:be.message,terminal:!0,closeCode:ye});return}W({state:Re?"error":"reconnecting",lastError:be.message}),Gn()}}}const _n=()=>{try{J.send(he.helloText)}catch{}},oa=(be,Re,ye)=>{De=be,cs=Re,Be=ye,ae!==null&&(clearInterval(ae),ae=null),fe!==null&&(clearTimeout(fe),fe=null);const mt=new Map,Ze=LC(),jt=OC();let ia=Promise.resolve();const Os=Kn=>{ia=ia.then(async()=>{if(ra.dead)return;const Jv=await be.encryptor.encrypt(Kn);ra.dead||J.send(Jv)}).catch(()=>{we(new Error("relay encrypt/send failed"))})},xc=Re?BC({windowMs:o,sendBatch:Os}):null;ls=xc;const ra={streams:mt,assembler:jt,nextStreamId:()=>Ze.next(),dead:!1,send(Kn){ra.dead||(xc?xc.enqueue(Kn):Os(Kn))}};le=ra,v=ra,j=0,Te=Date.now(),W({state:"connected"}),te(ra),gt=setInterval(()=>{Date.now()-Te<a||(ra.send(Dt(ce.Ping,0,Ai)),Ue===null&&(Ue=setTimeout(()=>{Ue=null,we(new Error("relay keepalive timeout"))},n)))},a)},yi=()=>{He!==null&&clearTimeout(He),He=null,!(!le||le.dead||Le===We)&&(We=Le,le.send(Dt(ce.DeliveryAck,0,zC(Le))))},Pc=(be,Re)=>{let ye;try{ye=RC(Re)}catch(jt){we(Ot(jt));return}if(ye.frameType===ce.DeliveryAck){we(new Error("unexpected downstream delivery acknowledgement"));return}if(Be&&ye.streamId!==0&&(Le+=Re.length,He===null&&(He=setTimeout(yi,10))),Te=Date.now(),Ue!==null&&(clearTimeout(Ue),Ue=null),ye.frameType===ce.Ping){be.send(Dt(ce.Pong,ye.streamId,Ai));return}if(ye.frameType===ce.Pong)return;let mt=ye.payload;if(ye.frameType===ce.WsText||ye.frameType===ce.WsBinary){let jt;try{jt=be.assembler.push(ye)}catch(ia){we(Ot(ia));return}if(jt===null)return;mt=jt}else if(ye.hasMoreFragments){we(new Error("unexpected fragmented tunnel frame"));return}const Ze=be.streams.get(ye.streamId);Ze&&Ze.handleFrame(ye.frameType,mt)};J.onopen=()=>{Q||q!==x||(_n(),ae=setInterval(_n,t))};const La=be=>{const Re=DS.has(be);we(new Error(NS[be]??`relay socket closed (code ${be})`),Re,Re?be:null)};J.onmessage=be=>{if(Q||q!==x)return;const Re=be.data;if(typeof Re=="string"){const mt=cC(Re);if(mt){La(mt.code);return}re=re.then(async()=>{if(Q||q!==x)return;const Ze=await he.handleText(Re);if(Ze.type==="established"){if(De)return;oa(Ze.channel,Ze.batch,Ze.flowControl)}else Ze.type==="fail"&&we(new Error(`relay handshake failed: ${Ze.reason}`))}).catch(Ze=>{we(Ot(Ze))});return}const ye=Re instanceof ArrayBuffer?new Uint8Array(Re):Re instanceof Uint8Array?Re:null;ye&&(re=re.then(async()=>{if(Q||q!==x)return;const mt=le,Ze=De;if(!mt||!Ze){we(new Error("encrypted frame before handshake completed"));return}let jt;try{jt=await Ze.decryptor.decrypt(ye)}catch(Os){we(Ot(Os));return}let ia;try{ia=cs?NC(jt):[jt]}catch(Os){we(Ot(Os));return}for(const Os of ia){if(Q||q!==x||mt.dead)return;Pc(mt,Os)}Be&&Le-We>=16*1024&&yi()}).catch(mt=>{we(Ot(mt))}))},J.onclose=be=>La(be.code),J.onerror=()=>{},fe=setTimeout(()=>{fe=null,we(new Error("relay handshake timeout"),!0)},s);function qu(be,Re,ye=!1){be!==x||g||(_(Re),j+=1,W({state:ye?"error":"reconnecting",lastError:Re.message}),Gn())}},rs=q=>g?Promise.reject(new Error("relay tunnel closed")):q?.aborted?Promise.reject(zi()):h?Promise.reject(h):v&&!v.dead?Promise.resolve(v):new Promise((he,J)=>{let Q=null;const ae={resolve(fe){Q&&q&&q.removeEventListener("abort",Q),he(fe)},reject(fe){Q&&q&&q.removeEventListener("abort",Q),J(fe)}};q&&(Q=()=>{Z=Z.filter(fe=>fe!==ae),J(zi())},q.addEventListener("abort",Q,{once:!0})),Z.push(ae)}),Sc=async(q,he)=>{const J=await KC(q,he),Q=J.signal;if(Q?.aborted)throw zi();const ae=await rs(Q),fe=ae.nextStreamId();return await new Promise((gt,Ue)=>{let re=!1,le=!1,De=null,cs=null;const Be=()=>{ae.streams.delete(fe),ae.assembler.dropStream(fe),cs&&Q&&Q.removeEventListener("abort",cs)},Le=Te=>{if(!le){if(le=!0,Be(),!re){Ue(Te);return}try{De?.error(Te)}catch{}}},We=Te=>{ae.dead||ae.send(Dt(ce.StreamAbort,fe,Si({reason:Te})))},He=Te=>Nl(new Error(Te));cs=()=>{We("aborted"),Le(zi())},ae.streams.set(fe,{handleFrame(Te,js){if(Te===ce.HttpResponse){if(re||le)return;let we;try{we=Pi(js,VC)}catch(La){We("malformed response head"),Le(He(Ot(La).message));return}const _n=we.status===204||we.status===205||we.status===304;let oa=null;_n||(oa=new ReadableStream({start(La){De=La},cancel(){le||(le=!0,Be(),We("response body cancelled"))}})),re=!0;const{[uC]:yi,...Pc}=we.headers;oa&&yi==="gzip"&&(oa=AS(oa)),gt(new Response(oa,{status:we.status,headers:Pc})),_n&&(le=!0,Be());return}if(Te===ce.HttpBody){if(!re||le)return;try{De?.enqueue(js)}catch{}return}if(Te===ce.StreamEnd){if(le)return;if(!re){Le(He("tunnel stream ended before response head"));return}le=!0,Be();try{De?.close()}catch{}return}if(Te===ce.StreamAbort){let we="stream aborted by host";try{we=Pi(js,Hu).reason}catch{}Le(He(we))}},fail(Te){Le(He(Te.message))}}),Q&&Q.addEventListener("abort",cs,{once:!0});const ls={method:J.method,path:J.path,query:J.query,headers:TS?{...J.headers,[pC]:"gzip"}:J.headers,hasBody:J.body!==null};ae.send(Dt(ce.HttpRequest,fe,Si(ls))),(async()=>{try{let Te=!1;if(J.body)for await(const js of J.body){if(le||ae.dead)return;for(const we of df(js))ae.send(Dt(ce.HttpBody,fe,we)),Te=!0}!le&&!ae.dead&&(J.body&&!Te&&ae.send(Dt(ce.HttpBody,fe,Ai)),ae.send(Dt(ce.StreamEnd,fe,Ai)))}catch(Te){We("request body failed"),Le(He(Ot(Te).message))}})()})},_v=q=>{const he=q.indexOf("?");return he===-1?{path:q,query:""}:{path:q.slice(0,he),query:q.slice(he+1)}},Kv=(q,he)=>{let J=Yu,Q=null,ae=0,fe=!1;const gt={get readyState(){return J},onopen:null,onmessage:null,onerror:null,onclose:null,send(re){if(J!==Ic||!Q||Q.dead)throw new Error("relay tunnel socket is not open");if(typeof re=="string"){for(const De of Wu(ce.WsText,ae,zS.encode(re)))Q.send(De);return}const le=re instanceof ArrayBuffer?new Uint8Array(re.slice(0)):(()=>{const De=new Uint8Array(re.byteLength);return De.set(new Uint8Array(re.buffer,re.byteOffset,re.byteLength)),De})();for(const De of Wu(ce.WsBinary,ae,le))Q.send(De)},close(re=1e3,le=""){J===eg||J===Xu||(J===Ic&&Q&&!Q.dead&&(J=Xu,Q.send(Dt(ce.WsClose,ae,Si({code:re,reason:le})))),Ue(re,le))}},Ue=(re,le,De=!1)=>{if(!fe){if(fe=!0,Q&&(Q.streams.delete(ae),Q.assembler.dropStream(ae)),J=eg,De)try{gt.onerror?.()}catch{}try{gt.onclose?.({code:re,reason:le})}catch{}}};return(async()=>{let re;try{re=await rs()}catch(Be){Ue(1006,Ot(Be).message,!0);return}if(fe)return;Q=re,ae=re.nextStreamId(),re.streams.set(ae,{handleFrame(Be,Le){if(Be===ce.WsOpened){if(J===Yu){J=Ic;try{gt.onopen?.()}catch{}}return}if(Be===ce.WsText){try{gt.onmessage?.({data:RS.decode(Le)})}catch{}return}if(Be===ce.WsBinary){const We=new ArrayBuffer(Le.byteLength);new Uint8Array(We).set(Le);try{gt.onmessage?.({data:We})}catch{}return}if(Be===ce.WsClose){let We=1e3,He="";try{const ls=Pi(Le,UC);We=ls.code,He=ls.reason}catch{}Ue(We,He);return}if(Be===ce.StreamAbort){let We="stream aborted";try{We=Pi(Le,Hu).reason}catch{}Ue(1006,We,!0)}},fail(Be){Ue(1012,Be.message,!0)}});const{path:le,query:De}=_v(q),cs=he&&he.length>0?{path:le,query:De,protocols:he}:{path:le,query:De};re.send(Dt(ce.WsOpen,ae,Si(cs)))})(),gt},Zv=()=>{if(g)return;g=!0,x+=1,Ve(),It(),z?.(),z=null;const q=v;v=null;const he=new Error("relay tunnel closed");q&&se(q,he),_(he);try{P?.close()}catch{}P=null,W({state:"idle"})};return Ba(),{fetch:Sc,openWebSocket:Kv,getStatus:()=>b,subscribeStatus(q){return k.add(q),()=>{k.delete(q)}},retry:na,close:Zv}};let as=null,ts=null;const Wl=new Set;let Oc=null;const mp=e=>{Oc?.(),Oc=null,as=e,e&&(Oc=e.subscribeStatus(t=>{for(const s of Wl)s(t)}))},_0=e=>(Wl.add(e),()=>{Wl.delete(e)}),FS=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),Dn=()=>as,K0=()=>!as||!ts?null:{relayUrl:ts.relayUrl,serverId:ts.serverId,hostEncPubJwk:{...ts.hostEncPubJwk}},ES=()=>as!==null,MS=e=>{if(as&&ts&&FS(ts,e))return as;as?.close(),ts=e;const t=gp(e);return mp(t),t},Z0=(e,t)=>{if(as===t){ts=e;return}as?.close(),ts=e,mp(t)},BS=()=>{as?.close(),mp(null),ts=null};let Rf=()=>null,If="",Pr={},wn="",Uo=0,fa=null,cn="",Wo=0,Aa="",ba=null,Vs="",ar=0,nr=0;const hp=1e4,LS=e=>e.toLowerCase()==="authorization",jf=e=>{const t={};for(const[s,a]of Object.entries(e||{})){const n=s.trim(),o=a.trim();n&&o&&!LS(n)&&(t[n]=o)}return t},qS=(e,t)=>{const s=Object.entries(e);return s.length!==Object.keys(t).length?!1:s.every(([a,n])=>t[a]===n)},Yr=e=>typeof e!="string"?"":e.trim(),VS=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return Yr(e)},US=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Of=(e,t)=>{const s=typeof e=="string"&&e.trim()?e.trim():US();if(!s)return t;try{return new URL(t,`${s.replace(/\/+$/,"")}/`).toString()}catch{return t}},fp=e=>{try{return new URL(e).origin}catch{return""}},Df=()=>{cn="",Wo=0,Aa="",ba=null,Vs="",ar+=1},ii=()=>{wn="",Uo=0,Df()},Nf=()=>{nr+=1,fa=null,ii(),kp()},Ff=e=>{const t=Yr(e);If=t,Nf(),Rf=()=>t?{type:"bearer",token:t}:null},Ef=e=>{const t=jf(e);qS(Pr,t)||(Pr=t,Nf())},Nn=()=>{if(Object.keys(Pr).length>0)return Pr;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?jf(e):{}},bp=()=>If||VS(),WS=(e,t)=>{const s=Yr(e);if(!s||typeof t!="number"||!Number.isFinite(t)){ii();return}wn=s,Uo=t},Mf=()=>!wn||Uo<=Date.now()+hp?(ii(),""):wn,Bf=e=>{const t=fp(e);return!t||Aa!==t?"":!cn||Wo<=Date.now()+hp?(cn="",Wo=0,Aa="",""):cn},HS=()=>{const e=Mf();return!e&&(bp()||typeof window<"u")&&Xr().catch(()=>{}),e},GS=e=>{const t=e?Bf(e):"";return!t&&e&&typeof window<"u"&&Uf(e).catch(()=>{}),t},Lf=async()=>{const e=await Rf(),t=e?.type==="bearer"?Yr(e.token):bp();return t?{type:"bearer",token:t}:null},_S=d({token:c(),expiresAt:w(),expiresIn:w().optional()}),qf=async(e,t)=>{const s=await Lf(),a=new Headers;for(const[g,h]of Object.entries(Nn()))a.set(g,h);s?.type==="bearer"&&a.set("Authorization",`Bearer ${s.token}`);const n=t?`/auth/url-token?scope=${encodeURIComponent(t)}`:"/auth/url-token",o=Dn(),i=o?await o.fetch(n,{method:"POST",headers:a}):await fetch(Of(e,n),{method:"POST",headers:a,credentials:"include"});if(!i.ok)throw new Error(`Failed to mint runtime URL auth token (${i.status})`);const r=_S.safeParse(await i.json().catch(()=>null));if(!r.success)return{token:"",expiresAt:0};const{token:l,expiresAt:p,expiresIn:u}=r.data;return{token:l.trim(),expiresAt:u===void 0?p:Date.now()+u}},J0=async e=>{const t=await qf(null,`guest:${e}`);if(!t.token)throw new Error("Guest URL auth token response was invalid");return t},Vf=e=>{if(fa)return fa;const t=nr,a=(async()=>{let n;try{n=await qf(e)}catch(o){throw t===nr&&ii(),o}if(t!==nr)throw new Error("Runtime URL auth token response is stale");if(WS(n.token,n.expiresAt),!wn)throw new Error("Runtime URL auth token response was invalid");return wn})().finally(()=>{fa===a&&(fa=null)});return fa=a,fa},KS=e=>{const t=fp(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(ba&&Vs===t)return ba;const s=ar,n=(async()=>{const o=await fetch(Of(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!o.ok)throw s===ar&&t===Vs&&(cn="",Wo=0,Aa=""),new Error(`Failed to mint local runtime URL auth token (${o.status})`);const i=await o.json().catch(()=>null),r=typeof i?.token=="string"?i.token.trim():"",l=typeof i?.expiresAt=="number"?i.expiresAt:0;if(!r||!Number.isFinite(l))throw new Error("Local runtime URL auth token response was invalid");if(s!==ar||t!==Vs)throw new Error("Local runtime URL auth token response is stale");return cn=r,Wo=l,Aa=t,r})().finally(()=>{ba===n&&(ba=null,Vs="")});return ba=n,Vs=t,ba},Xr=async e=>{const t=Mf();return t||Vf(e)},Uf=async e=>{const t=fp(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const s=Bf(t);return s||((Aa&&Aa!==t||Vs&&Vs!==t)&&Df(),KS(t))};let tn=0,wo=null,ZS=null;const JS=5e3,Wf=()=>{wo!==null&&(clearTimeout(wo),wo=null)},kp=()=>{if(Wf(),tn<=0||typeof window>"u")return;const e=Uo-hp-JS,t=Uo>0?Math.max(0,e-Date.now()):0;wo=setTimeout(()=>{wo=null,!(tn<=0)&&Vf(ZS).catch(()=>{}).finally(()=>{kp()})},t)},$0=e=>{tn+=1,kp();let t=!1;return()=>{t||(t=!0,tn=Math.max(0,tn-1),tn===0&&Wf())}},Hf=async e=>{const t=new Headers(e);for(const[a,n]of Object.entries(Nn()))t.has(a)||t.set(a,n);if(t.has("Authorization"))return t;const s=await Lf();return s?.type==="bearer"&&t.set("Authorization",`Bearer ${s.token}`),t},yn=Rt(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),Q0=e=>new Promise(t=>{if(e.aborted||yn.getState().state==="ok"){t();return}const s=()=>{a(),e.removeEventListener("abort",s),t()},a=yn.subscribe(n=>{n.state==="ok"&&s()});e.addEventListener("abort",s,{once:!0})}),$S=15e3,QS=5*6e4;let Hl=0,Dc=!1;const YS=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),XS=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?!1:!YS(t)},Gf=async()=>{if(!Dc){Dc=!0;try{const{runtimeFetch:e}=await Ge(async()=>{const{runtimeFetch:s}=await Promise.resolve().then(()=>bP);return{runtimeFetch:s}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){yn.getState().markExpired();return}if(t.ok){const{state:s,markAuthenticated:a}=yn.getState();s==="expired"&&a()}}catch{}finally{Dc=!1}}},eP=(e,t)=>{if(t!==401||yn.getState().state==="expired"||!XS(e))return;const s=Date.now();s-Hl<$S||(Hl=s,Gf())};let tg=!1;const Y0=()=>{if(tg)return;tg=!0;let e=Date.now();const t=()=>{if(yn.getState().state!=="ok")return;const s=Date.now();s-e<QS||(e=s,Hl=s,Gf())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},tP=/^\/spaces\/([0-9a-f]{12})(?:\/|$)/,zt=e=>{if(!e)return null;const t=tP.exec(e);return t?t[1]:null},Gl=e=>zt(e)!==null,sP=()=>pp()||On()?.runtime?.isVSCode===!0,aP=e=>!e||sP()||!Gl(e)?null:{"x-opencode-directory":encodeURIComponent(e),"x-opencode-directory-encoding":"uri"},_f=e=>`/spaces/${e}`,za=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",nP=()=>typeof window>"u"?"":window.location.origin||"",wp=e=>{if(typeof window>"u")return!1;const t=nP();if(t&&e.origin===t)return!0;try{const s=new URL(window.location.href||t);return e.protocol===s.protocol&&e.host===s.host}catch{return!1}},yp=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),oP=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),gs=(e,t)=>{try{oP(new URL(e).hostname)&&!t.has("ngrok-skip-browser-warning")&&t.set("ngrok-skip-browser-warning","openchamber")}catch{}return t},vp=(e,t)=>{if(!t)return;const s=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[a,n]of s)n!=null&&e.searchParams.set(a,String(n))},iP=e=>{if(!e)return!1;if(e instanceof Headers)return e.has("x-opencode-directory");const t=Array.isArray(e)?e:Object.entries(e);for(const[s]of t)if(s.toLowerCase()==="x-opencode-directory")return!0;return!1},rP=(e,t,s)=>{const a=aP(s);if(a===null||iP(t.headers)||e instanceof Request&&e.headers.has("x-opencode-directory"))return t;const n=t.headers?t.headers instanceof Headers?Array.from(t.headers.entries()):Array.isArray(t.headers)?t.headers:Object.entries(t.headers):[];return{...t,headers:[...n,...Object.entries(a)]}},cP=()=>{const e=vs().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return null;const t=new URL(e);return`${t.origin}${t.pathname.replace(/\/api$/,"")}`},lP=e=>{try{const t=cP();if(!t)return null;const s=new URL(t);if(e.origin!==s.origin)return null;const a=s.pathname.replace(/\/+$/,"");return a?e.pathname!==a&&!e.pathname.startsWith(`${a}/`)?null:e.pathname.slice(a.length)||"/":e.pathname}catch{return null}},or=e=>{const t=lP(e);return t!==null&&za(t)},Nc=e=>{if(za(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return wp(t)&&za(t.pathname)}catch{return!1}},dP=(e,t)=>{try{const s=new URL(e);if(!wp(s))return e;const a=Xs(`${s.pathname}${s.search}`,t);return!yp(a)&&(s.protocol==="http:"||s.protocol==="https:")?(vp(s,t),s.toString()):s.hash?`${a}${s.hash}`:a}catch{return e}},Xs=(e,t)=>e==="/health"?vs().health(t):e.startsWith("/auth/")||e==="/auth"?vs().auth(e,t):za(e)?vs().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?dP(e,t):e,Kf=e=>{const t=e instanceof Request?e.url:e.toString();if(!yp(t))return za(t);try{return or(new URL(t))}catch{return!1}},Zf=(e,t)=>Object.keys(Nn()).length>0&&Oa()&&Kf(e)?{...t,redirect:"error"}:t,Jf=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},pP=(e,t)=>!Jf(t),xr=e=>{if(!e)return;const t=e instanceof Headers?Array.from(e.entries()):Array.isArray(e)?e:Object.entries(e);if(t.length===0)return;const s=[];let a=!1,n=!1;for(const[o,i]of t)pP(o,i)?(s.push([o,encodeURIComponent(i)]),a=!0,o.toLowerCase()==="x-opencode-directory"&&(n=!0)):s.push([o,i]);return n&&s.push(["x-opencode-directory-encoding","uri"]),a?s:void 0},ms=async(e,t,s=!0)=>{const a=new Headers(xr(e)??e);return t&&new Headers(xr(t)??t).forEach((n,o)=>a.set(o,n)),s?Hf(a):a},uP=(e,t)=>{if(!t)return e;const s=new URL(e,cp);return vp(s,t),`${s.pathname}${s.search}`},$f=(e,t)=>{const s=e instanceof Request?e.url:e.toString();if(!yp(s))return za(s)?uP(s,t):null;try{const a=new URL(s);return!wp(a)||!za(a.pathname)?null:(vp(a,t),`${a.pathname}${a.search}`)}catch{return null}},gP=async(e,t,s)=>{const a=Dn();if(!a)return null;const n=$f(e,s);if(n===null)return null;const o=e instanceof Request?e.headers:void 0,i=await ms(o,t.headers,!0);return e instanceof Request?a.fetch(e,{...t,headers:i}):a.fetch(n,{...t,headers:i})},mP=(e,t)=>{if(typeof e=="string")return Xs(e,t);if(e instanceof URL)return Xs(e.toString(),t);const s=Xs(e.url,t);return s===e.url?e:new Request(s,e)},hP=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Ri=new Map,fP=(e,t,s,a)=>s||e!=="GET"||t.includes("/event")||!hP.test(t)?null:`GET ${t}\0${a.get("x-opencode-directory")??""}`,T=async(e,t={})=>{const{query:s,directory:a,...n}=t,o=e,i=rP(o,n,a),r=Dn(),l=r?$f(o,s):null;let p,u,g,h;if(r&&l!==null){const x=o instanceof Request?o.headers:void 0,j=await ms(x,i.headers,!0);p=o instanceof Request?()=>r.fetch(o,{...i,headers:j}):()=>r.fetch(l,{...i,headers:j}),h=j,u=l,g=String(i.method??(o instanceof Request?o.method:"GET")).toUpperCase()}else{const x=mP(o,s),j=x instanceof Request?x.headers:void 0,V=await ms(j,i.headers,Kf(x)),Z=x instanceof Request?x.url:x instanceof URL?x.toString():String(x);gs(Z,V);const B=Zf(x,{...i,headers:V});p=x instanceof Request?()=>fetch(new Request(x,B)):()=>fetch(x,B),h=V,u=Z,g=String(i.method??(x instanceof Request?x.method:"GET")).toUpperCase()}const b=p;p=()=>b().then(x=>(eP(u,x.status),x));const k=i.signal!=null||o instanceof Request,v=fP(g,u,k,h);if(!v)return p();const P=Ri.get(v);if(P)return P.then(x=>x.clone());const z=p();return Ri.set(v,z),z.then(()=>Ri.delete(v),()=>Ri.delete(v)),z.then(x=>x.clone())};let sg=!1,Qf=null;const Yf=(e,t)=>(Qf??globalThis.fetch.bind(globalThis))(e,t),Xf=()=>{if(sg||typeof window>"u")return;sg=!0;const e=window.fetch.bind(window);Qf=e;const t=(s,a)=>e(s,Zf(s,a));window.fetch=async(s,a)=>{const n=await gP(s,a??{});if(n)return n;if(typeof s=="string"){if(!Nc(s)){try{const r=new URL(s);if(or(r)){const l=await ms(void 0,a?.headers);return gs(r.toString(),l),t(s,{...a,headers:l})}}catch{}return t(s,a)}const o=await ms(void 0,a?.headers),i=Xs(s);return gs(i,o),t(i,{...a,headers:o})}if(s instanceof URL){const o=s.toString();if(!Nc(o)){if(or(s)){const l=await ms(void 0,a?.headers);return gs(s.toString(),l),t(s,{...a,headers:l})}return t(s,a)}const i=await ms(void 0,a?.headers),r=Xs(o);return gs(r,i),t(r,{...a,headers:i})}if(s instanceof Request){if(!Nc(s.url)){try{const l=new URL(s.url);if(or(l)){const p=await ms(s.headers,a?.headers);return gs(l.toString(),p),t(new Request(s,{...a,headers:p}))}}catch{}return t(s,a)}const o=await ms(s.headers,a?.headers),i=Xs(s.url);gs(i,o);const r=i===s.url?s:new Request(i,s);return t(new Request(r,{...a,headers:o}))}return t(s,a)}},bP=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:gs,buildRuntimeFetchUrl:Xs,fetchBypassingRuntimeBridge:Yf,installRuntimeFetchBridge:Xf,isLatin1Safe:Jf,runtimeFetch:T,sanitizeHeadersForBrowser:xr},Symbol.toStringTag,{value:"Module"})),ln=16384,Tr=globalThis,kP=e=>{if(Tr.Buffer)return Tr.Buffer.from(e,"utf8").toString("base64url");const t=new TextEncoder().encode(e);let s="";for(let a=0;a<t.length;a+=32768)s+=String.fromCharCode(...t.slice(a,a+32768));return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")},eb=e=>{try{if(Tr.Buffer)return Tr.Buffer.from(e,"base64url").toString("utf8");const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),s=atob(t),a=new Uint8Array(s.length);for(let n=0;n<s.length;n+=1)a[n]=s.charCodeAt(n);return new TextDecoder().decode(a)}catch{return null}},wP=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?null:(s.hash="",s.toString().replace(/\/+$/g,""))}catch{return null}},yP=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="ws:"&&s.protocol!=="wss:"?null:(s.hash="",s.toString())}catch{return null}},ag=e=>typeof e=="string"&&e.length>0,vP=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!ag(t.x)||!ag(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},CP=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,SP=e=>{if(!e||typeof e!="object")return null;const t=e,s=CP(t.priority);if(t.type==="lan"||t.type==="tunnel"){const a=wP(t.url);return a?s===void 0?{type:t.type,url:a}:{type:t.type,url:a,priority:s}:null}if(t.type==="relay"){const a=yP(t.relayUrl);if(!a)return null;const n=typeof t.serverId=="string"?t.serverId.trim():"";if(!n)return null;const o=vP(t.hostEncPubJwk);if(!o)return null;const i=typeof t.grant=="string"&&t.grant.trim()?t.grant.trim():void 0;return{type:"relay",relayUrl:a,serverId:n,hostEncPubJwk:o,...i?{grant:i}:{},...s===void 0?{}:{priority:s}}}return null},Cp=e=>{if(!e||typeof e!="object")return null;const t=e;if(t.v!==2)return null;const s=typeof t.pairingId=="string"?t.pairingId.trim():"",a=typeof t.secret=="string"?t.secret.trim():"";if(!s||!a)return null;const n=Array.isArray(t.candidates)?t.candidates.map(SP).filter(l=>!!l):[];if(n.length===0)return null;const o=typeof t.expiresAt=="string"&&t.expiresAt.trim()?t.expiresAt.trim():void 0;if(o){const l=Date.parse(o);if(!Number.isFinite(l)||l<=Date.now())return null}const i=typeof t.label=="string"&&t.label.trim()?t.label.trim():void 0,r=typeof t.fingerprint=="string"&&t.fingerprint.trim()?t.fingerprint.trim():void 0;return{v:2,pairingId:s,secret:a,...i?{label:i}:{},...r?{fingerprint:r}:{},...o?{expiresAt:o}:{},candidates:n}},X0=e=>({v:2,pairingId:e.pairingId.trim(),secret:e.secret.trim(),...e.label?.trim()?{label:e.label.trim()}:{},...e.fingerprint?.trim()?{fingerprint:e.fingerprint.trim()}:{},...e.expiresAt?.trim()?{expiresAt:e.expiresAt.trim()}:{},candidates:e.candidates}),eK=e=>{const t=Cp(e);if(!t)throw new Error("Invalid pairing connection payload");const s=new URLSearchParams;return s.set("v","2"),s.set("p",kP(JSON.stringify(t))),`openchamber://connect?${s.toString()}`},PP=e=>{const t=e.trim();if(!t||t.length>ln)return null;try{const s=new URL(t);if(s.protocol!=="openchamber:"||s.hostname!=="connect"||s.searchParams.get("v")!=="2")return null;const a=s.searchParams.get("p")||"";if(!a||a.length>ln)return null;const n=eb(a);return!n||n.length>ln?null:Cp(JSON.parse(n))}catch{return null}},tK=e=>{const t=e.trim();if(!t||t.length>ln)return null;const s=t.indexOf("?");if(s===-1||!/^openchamber:\/\/connect\/?$/i.test(t.slice(0,s)))return null;let a=null,n=null;for(const i of t.slice(s+1).split("&")){const r=i.indexOf("=");if(r===-1)continue;const l=i.slice(0,r),p=i.slice(r+1);l==="v"?a=p:l==="p"&&(n=p)}if(a!=="2"||!n||n.length>ln)return null;const o=eb(n);if(!o||o.length>ln)return null;try{return Cp(JSON.parse(o))}catch{return null}},vn=e=>typeof e=="object"&&e!==null,xP=e=>e.trim().toLowerCase()==="authorization",TP=e=>{if(!vn(e))return;const t={};for(const[s,a]of Object.entries(e)){const n=s.trim(),o=typeof a=="string"?a.trim():"";!n||!o||/[\r\n:]/.test(n)||/[\r\n]/.test(o)||xP(n)||(t[n]=o)}return Object.keys(t).length>0?t:void 0},AP=e=>`relay://${e}`,zP=e=>{if(!vn(e))return null;const t=Ye(e,"relayUrl")||Ye(e,"relay_url"),s=Ye(e,"serverId")||Ye(e,"server_id"),a=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!s||!vn(a)?null:{relayUrl:t,serverId:s,hostEncPubJwk:a}},RP=()=>{if(typeof navigator>"u")return;const e=navigator.userAgent;if(/Macintosh|Mac OS X/i.test(e))return"macos";if(/Windows/i.test(e))return"windows";if(/Linux/i.test(e))return"linux"},ng=15e3,sK=async(e,t)=>{const s=PP(e);if(!s)throw new Error("invalid-connect-link");const a=await NP().catch(()=>""),n={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({pairingId:s.pairingId,secret:s.secret,clientLabel:s.label||"OpenChamber Desktop",clientKind:"desktop",deviceName:"OpenChamber Desktop",devicePlatform:RP(),...a?{dedupeKey:`desktop:${a}`}:{}})},o=async P=>{if(!P.ok)return null;const z=await P.json().catch(()=>null);return(typeof z?.clientToken=="string"?z.clientToken.trim():"")||null};let i=null;const r=[...s.candidates].sort((P,z)=>(P.type==="relay"?1:0)-(z.type==="relay"?1:0));for(const P of r){if(P.type==="relay"){const x=gp({relayUrl:P.relayUrl,serverId:P.serverId,hostEncPubJwk:P.hostEncPubJwk,...P.grant?{grant:P.grant}:{}});try{const j=await o(await x.fetch("/api/client-auth/pairing/redeem",{...n,signal:AbortSignal.timeout(ng)}));if(j){i={relay:{relayUrl:P.relayUrl,serverId:P.serverId,hostEncPubJwk:P.hostEncPubJwk},token:j};break}}catch{}finally{x.close()}continue}const z=Ke(P.url);if(z)try{const x=await o(await fetch(`${z}/api/client-auth/pairing/redeem`,{...n,signal:AbortSignal.timeout(ng)}));if(x){i={directUrl:z,token:x};break}}catch{}}if(!i)throw new Error("pairing-redeem-failed");const l=s.candidates.find(P=>P.type==="relay"),p=i.relay||(l?{relayUrl:l.relayUrl,serverId:l.serverId,hostEncPubJwk:l.hostEncPubJwk}:void 0),u=s.candidates.filter(P=>P.type!=="relay").map(P=>Ke(P.url)).find(P=>!!P),g=i.directUrl||u,h=g||(p?AP(p.serverId):null);if(!h)throw new Error("pairing-missing-transport");const b=t.find(P=>p?P.relay?.serverId===p.serverId:!P.relay&&Ke(P.apiUrl||P.url)===h),k=b?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),v={...b||{},id:k,label:s.label||b?.label||tb(h),url:h,apiUrl:g,clientToken:i.token,...p?{relay:p}:{}};return{hostId:k,hosts:b?t.map(P=>P.id===k?v:P):[v,...t]}},IP=/^(t|.*(?:token|auth|secret|api).*)$/i,Ke=e=>{const t=e.trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?null:t.split("#")[0]||null}catch{return null}},aK=e=>{const t=Ke(e);if(!t)return null;try{const s=new URL(t);if((s.pathname.replace(/\/+$/,"")||"/")==="/connect"&&s.searchParams.has("t"))return{persistedUrl:s.origin,redeemUrl:s.toString(),kind:"tunnel-connect-link"}}catch{return null}return{persistedUrl:t,redeemUrl:null,kind:"normal-host"}},tb=e=>{const t=Ke(e);if(!t)return e;try{const s=new URL(t);(s.username||s.password)&&(s.username="",s.password="");const a=Array.from(new Set(Array.from(s.searchParams.keys())));for(const n of a)IP.test(n)&&s.searchParams.set(n,"[REDACTED]");return s.toString()}catch{return t}},Ii=(e,t)=>{const s=Ke(e),a=Ke(t);if(!s||!a)return!1;try{const n=new URL(s),o=new URL(a);if(n.origin!==o.origin||o.search&&n.search!==o.search)return!1;const i=o.pathname.length>1?o.pathname.replace(/\/+$/,""):o.pathname,r=n.pathname.length>1?n.pathname.replace(/\/+$/,""):n.pathname;return i==="/"?!0:r===i||r.startsWith(`${i}/`)}catch{return!1}},Ye=(e,t)=>{const s=e[t];return typeof s=="string"?s:null},og=(e,t)=>{const s=e[t];return typeof s=="number"&&Number.isFinite(s)?s:null},jP=e=>{if(!vn(e))return null;const t=Ye(e,"id"),s=Ye(e,"label"),a=Ye(e,"url"),n=Ye(e,"apiUrl")||Ye(e,"api_url"),o=Ye(e,"clientToken")||Ye(e,"client_token"),i=TP(e.requestHeaders),r=zP(e.relay);if(!t||!s||!a)return null;const l={id:t,label:s,url:a,...n?{apiUrl:n}:{},...o?{clientToken:o}:{},...i?{requestHeaders:i}:{},...r?{relay:r}:{}};return e.sshForwarded===!0&&(l.sshForwarded=!0),l},dn=e=>Ke(e.apiUrl||e.url)||e.apiUrl||e.url,Rs=()=>rt()?(e,t)=>oe(e,t):null,Ho=async()=>{const e=Rs();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!vn(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const s=t.hosts,a=Array.isArray(s)?s.map(jP).filter(r=>!!r):[],n=Ye(t,"defaultHostId")||Ye(t,"default_host_id")||Ye(t,"defaultHostID"),o=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,i=Ye(t,"localOrigin")||Ye(t,"local_origin");return{hosts:a,defaultHostId:n,initialHostChoiceCompleted:o,localOrigin:i}},OP=async e=>{const t=Rs();if(!t)return;const s={hosts:e.hosts,defaultHostId:e.defaultHostId,initialHostChoiceCompleted:e.initialHostChoiceCompleted};e.localClientToken!==void 0&&(s.localClientToken=e.localClientToken),await t("desktop_hosts_set",{input:s})},DP=async()=>{const e=Rs();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},nK=async()=>{const e=Rs();return e?await e("desktop_switch_to_local").catch(()=>!1)===!0:!1},NP=async()=>{const e=Rs();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},FP=8e3,EP=15e3,MP=400,BP=async(e,t,s,a)=>{const n=new AbortController,o=window.setTimeout(()=>n.abort(),s);try{return await e.fetch(t,{...a,signal:n.signal})}finally{window.clearTimeout(o)}},ig=async(e,t,s,a)=>{for(;;){const n=s-Date.now();if(n<=0)throw new Error("relay probe deadline exceeded");try{return await BP(e,t,Math.min(FP,n),a)}catch(o){if(e.getStatus().state==="error"||Date.now()>=s)throw o;await new Promise(i=>window.setTimeout(i,MP))}}},LP=async(e,t)=>{const s=gp({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),a=Date.now()+EP;let n=!1;try{if(!(await ig(s,"/health",a)).ok)return{status:"unreachable",latencyMs:0};const i=Date.now(),r=new Headers({Accept:"application/json"});for(const[u,g]of Object.entries(t?.requestHeaders||{}))u.toLowerCase()!=="authorization"&&r.set(u,g);const l=t?.clientToken?.trim();l&&r.set("Authorization",`Bearer ${l}`);const p=await ig(s,"/auth/session",a,{headers:r});return p.status===401||p.status===403?{status:"auth",latencyMs:Math.max(0,Date.now()-i)}:p.ok?(n=t?.keepTunnel===!0,{status:"ok",latencyMs:Math.max(0,Date.now()-i),...n?{tunnel:s}:{}}):{status:"unreachable",latencyMs:0}}catch{return{status:OS(s.getStatus())?"relay-limit":"unreachable",latencyMs:0}}finally{n||s.close()}},ec=async(e,t)=>{const s=Rs();if(!s)return{status:"unreachable",latencyMs:0};const a=await s("desktop_host_probe",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0,expectedServerId:t?.expectedServerId||void 0});if(!vn(a))return{status:"unreachable",latencyMs:0};const n=a.status,o=n==="ok"||n==="auth"||n==="update-recommended"||n==="incompatible"||n==="wrong-service"||n==="unreachable"?n:"unreachable",i=og(a,"latencyMs")??og(a,"latency_ms")??0;return{status:o,latencyMs:i}},qP=X("status",[d({status:m("started")}),d({status:m("auth")}),d({status:m("failed"),error:c().nullable()})]),oK=async e=>{const t=Rs();if(!t)return{status:"failed",error:null};const s=await t("desktop_host_update_server",{hostId:e}).catch(()=>null),a=qP.safeParse(s);return a.success?a.data:{status:"failed",error:null}},VP=600*1e3,UP=3e3,iK=async(e,{maxWaitMs:t=VP,intervalMs:s=UP,readHosts:a=Ho,probe:n=ec}={})=>{const o=Date.now()+t;for(;Date.now()<o;){await new Promise(l=>setTimeout(l,Math.min(s,Math.max(0,o-Date.now()))));const i=(await a()).hosts.find(l=>l.id===e);if(!i)return"timeout";const r=await n(dn(i),{clientToken:i.clientToken,requestHeaders:i.requestHeaders});if(r.status==="ok"||r.status==="update-recommended"||r.status==="auth")return"updated"}return"timeout"},rK=async(e,t)=>{const s=Rs();s&&await s("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},cK=async e=>{const t=Rs();t&&await t("desktop_new_window_for_host",{hostId:e})},$s="local",WP=()=>typeof window>"u"?"":window.__OPENCHAMBER_LOCAL_ORIGIN__?.trim()||"",HP=(e,t)=>t?[{id:$s,label:"Local",url:t},...e]:e,GP=e=>e.id===$s?"local":`host:${e.id}`,lK=e=>{const t=typeof window>"u"?"":window.location.href,s=e.find(h=>h.id===$s)?.url||WP(),a=ns(),n=Ke(s)||s,o=Ke(t)||t,i=N(),r=e.find(h=>h.relay&&GP(h)===i);if(r)return{id:r.id,label:r.label,url:r.url};if(a&&Ii(a,s))return{id:$s,label:"Local",url:n};const l=e.find(h=>a?Ii(a,dn(h)):!1);if(l)return{id:l.id,label:l.label,url:Ke(dn(l))||dn(l)};if(t&&Ii(t,s))return{id:$s,label:"Local",url:n};const p=e.find(h=>t?Ii(t,h.url):!1);if(p)return{id:p.id,label:p.label,url:Ke(p.url)||p.url};const u=t.startsWith("openchamber-ui://");if(u&&s&&!a)return{id:$s,label:"Local",url:n};const g=a?Ke(a)||a:u?"":o;return{id:"custom",label:tb(g||"Instance"),url:g}},Ar=new Map;let sb=0;const yo=new Map,pn=new Set;let _l=0,ab={byHostId:{},isProbing:!1};const Kl=new Set,zr=()=>{ab={byHostId:Object.fromEntries(Ar),isProbing:_l>0};for(const e of Kl)try{e()}catch{}},dK=e=>(Kl.add(e),()=>{Kl.delete(e)}),pK=()=>ab,nb=(e,t)=>{Ar.set(e,t),zr()},uK=(e,t)=>{yo.set(e,++sb),pn.delete(e),nb(e,t)},gK=e=>pn.has(e),_P=e=>{const t=new Set([$s,...e]);let s=!1;for(const a of Array.from(Ar.keys()))t.has(a)||(Ar.delete(a),yo.delete(a),pn.delete(a),s=!0);s&&zr()},KP=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",ZP=async()=>ja()?DP().catch(()=>""):"",JP=async(e,t)=>{const s=e.id===$s?t:e.clientToken||"",a=async()=>{const i=await LP(e.relay,{clientToken:s,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0})),r={status:i.status,latencyMs:i.latencyMs};return i.status==="ok"&&(r.via="relay"),r};if(e.relay&&!e.apiUrl)return a();const n=Ke(ja()?dn(e):e.url);if(!n)return{status:"unreachable",latencyMs:0};const o=await ec(n,{clientToken:s||null,requestHeaders:e.requestHeaders||null,expectedServerId:e.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0}));if(KP(o.status)&&e.relay){const i=await a();if(i.status==="ok"||i.status==="relay-limit")return i}return{status:o.status,latencyMs:o.latencyMs}},$P=async e=>{if(!ot())return;const t=++sb;for(const s of e)yo.set(s.id,t),pn.add(s.id);_l+=1,zr();try{const s=await ZP();await Promise.all(e.map(async a=>{const n=await JP(a,s);yo.get(a.id)===t&&(pn.delete(a.id),nb(a.id,n))}))}finally{for(const s of e)yo.get(s.id)===t&&pn.delete(s.id);_l-=1,zr()}};let rg=!1;const QP=async()=>{if(rg||!ot())return;rg=!0;const e=await Ho().catch(()=>null);e&&(_P(e.hosts.map(t=>t.id)),await $P(HP(e.hosts,e.localOrigin)))},YP=5e3,XP=1500;let Fc=!1;const Ec=e=>{const t=String(e??"").trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?null:(s.hash="",s.toString())}catch{return null}},ex=async e=>{if(!ja()||Fc)return;const t=`host:${e}`;if(N()===t){Fc=!0;try{const s=await Ho().catch(()=>null),a=s?.hosts.find(k=>k.id===e);if(!s||!a?.relay)return;const n=a.apiUrl?Ke(a.apiUrl):null;if(n&&n.startsWith("https://"))return;const o=await T("/api/client-auth/connection/candidates").catch(()=>null);if(!o?.ok)return;const i=await o.json().catch(()=>null);if(!i||i.serverId!==a.relay.serverId)return;const r=Array.isArray(i.candidates)?i.candidates:[],l=[];for(const k of r){if(!k||typeof k!="object")continue;const v=k;if(v.type!=="lan"||typeof v.url!="string")continue;const P=Ke(v.url);P&&!l.includes(P)&&l.push(P)}if(l.length===0)return;const p=n&&l.includes(n)?n:l[0],u=Ec(p);u&&u!==Ec(n)&&await OP({hosts:s.hosts.map(k=>k.id===e?{...k,apiUrl:p}:k),defaultHostId:s.defaultHostId,initialHostChoiceCompleted:s.initialHostChoiceCompleted}).catch(()=>{});const h=(await Ho().catch(()=>null))?.hosts.find(k=>k.id===e)??null;if(!h||!u||Ec(h.apiUrl)!==u)return;const b=await ec(p,{clientToken:a.clientToken||null,requestHeaders:a.requestHeaders||null,expectedServerId:a.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(b.status==="unreachable"||b.status==="wrong-service"||b.status==="incompatible"||N()!==t)return;Vl({apiBaseUrl:p,clientToken:a.clientToken||null,requestHeaders:a.requestHeaders||null,runtimeKey:t})}finally{Fc=!1}}},tx=e=>{typeof window>"u"||window.setTimeout(()=>{ex(e).catch(()=>{})},YP)},cg=async(e,t)=>{if(!ja())return;const s=await Ho().catch(()=>null);if(!s)return;const a=e||(s.defaultHostId!=="local"?s.defaultHostId:null);if(!a)return;const n=s.hosts.find(h=>h.id===a);if(!n?.relay)return;const o=`host:${n.id}`;if(N()===o&&!t?.reconnectActive)return;const i=h=>{Vl({apiBaseUrl:h,clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,runtimeKey:o})},r=()=>{Vl({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:n.clientToken||null,runtimeKey:o,relay:n.relay??void 0}),tx(n.id)},l=n.apiUrl?Ke(dn(n)):null;if(!l){r();return}const p=h=>h.status!=="unreachable"&&h.status!=="wrong-service"&&h.status!=="incompatible",u=ec(l,{clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,expectedServerId:n.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0})),g=await Promise.race([u,new Promise(h=>setTimeout(()=>h(null),XP))]);if(g){if(p(g)){i(l);return}r();return}r(),u.then(h=>{p(h)&&N()===o&&i(l)})};class lg extends Error{constructor(t,s){super(`Agent '${t}' is not available in ${s??"the session's folder"}`),this.agent=t,this.directory=s,this.name="AgentUnavailableError"}agent;directory}const sx=e=>e!==void 0&&"tag"in e&&e.tag==="LocationNotFoundError";class Mt extends Error{reason;status;maxBytes;constructor(t,s={}){super(t),this.name="FilesystemError",this.reason=s.reason??"unknown",this.status=s.status,this.maxBytes=s.maxBytes}}const ax=e=>e instanceof Mt||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),vo=e=>{switch(e){case"os-permission":case"already-exists":case"not-found":case"not-directory":case"too-large":case"outside-workspace":case"invalid-response":return e;default:return"unknown"}},nx=d({message:c()}),mK=e=>{if(ax(e)&&e.reason==="not-found")return!0;const t=nx.safeParse(e),a=(e instanceof Error?e.message:t.success?t.data.message:String(e??"")).toLowerCase();return a.includes("file not found")||a.includes("enoent")||a.includes("no such file")||a.includes("does not exist")},ca=new Map;let Mc;async function dg(e){const t=vs().api("/api").replace(/\/api\/?$/,""),s=Dn(),a=await Hf();if(N()!==e)throw new Error("Runtime changed while preparing cleanup");return{fetch:async(o,i)=>{const r=o instanceof Request?o.url:String(o),l=r.startsWith("/")?`${t}${r}`:r,p=new Headers(o instanceof Request?o.headers:void 0);return new Headers(xr(i?.headers)??i?.headers).forEach((u,g)=>p.set(g,u)),a.forEach((u,g)=>p.set(g,u)),s?s.fetch(o,{...i,headers:p}):(gs(l,p),Yf(o instanceof Request?new Request(l,o):l,{...i,headers:p}))},baseUrl:t}}async function ob(e){const t=!!ns()&&!Dn(),s=await dg(e);return async a=>{let n=!1;const o=async()=>{if(!n){n=!0;try{const r=N()===e;if(!t&&!r)return;await a(r?await dg(e):s),ca.get(e)?.delete(o),ca.get(e)?.size===0&&ca.delete(e),ca.size===0&&(Mc?.(),Mc=void 0)}catch{}finally{n=!1}}},i=ca.get(e)??new Set;i.add(o),ca.set(e,i),Mc??=$r(({runtimeKey:r})=>{for(const l of ca.get(r)??[])l()}),await o()}}const Rr=()=>({active:0,waiters:[],activeSessionWaiters:[]});let Us=Rr(),Ca=Rr();const ox=3,pg=2;Jr(({runtimeKey:e,previousRuntimeKey:t})=>{if(e===t)return;const s=[Us,Ca];Us=Rr(),Ca=Rr();for(const a of s){for(const n of[...a.activeSessionWaiters,...a.waiters])n(!1);a.activeSessionWaiters.length=0,a.waiters.length=0}});const ug=()=>{for(;Us.active+Ca.active<ox;){const e=Ca.active<pg&&Ca.waiters.length>0?Ca:Us.active<pg&&(Us.activeSessionWaiters.length>0||Us.waiters.length>0)?Us:null;if(!e)return;const t=e.activeSessionWaiters.shift()??e.waiters.shift();if(!t)return;e.active+=1,t(!0)}};async function ib(e,t,s){const a=sr();if(await new Promise(o=>{s==="active-session"?e.activeSessionWaiters.push(o):e.waiters.push(o),ug()}))try{if(!a())return;const o=await t();return a()?o:void 0}finally{e.active-=1,ug()}}const ix=(e,t="normal")=>ib(Us,e,t),hK=e=>ib(Ca,e,"normal"),rb="/api/opencode/trust",rx="opencode_trust_required",cx=d({kind:S(["plugin","package","mcp","lsp","formatter","shell","config"]),source:c(),name:c(),detail:c()}),lx=d({directory:c(),trusted:y(),fingerprint:c().nullable(),items:C(cx)}),dx=d({code:m(rx),directory:c()});let Pa=null;const Zl=new Set,ro=new Map,Go=new Set,Cs=new Map;let Jl=Promise.resolve(),Ws=0;const un=()=>{for(const e of Zl)e()},fK=()=>Pa,bK=e=>(Zl.add(e),()=>{Zl.delete(e)}),kK=e=>Pa?Pa.settle(e):Promise.resolve("skipped");Jr(()=>{Ws+=1,Pa?.settle("skip"),ro.clear(),Go.clear(),Cs.clear(),Jl=Promise.resolve(),un()});const wK=e=>e?Cs.has(e):!1,cb=(e,t)=>{Cs.set(e,e);for(const s of t)Cs.set(s,e)},_o=e=>{const t=Cs.get(e);if(t!==void 0){for(const[s,a]of Cs)a===t&&Cs.delete(s);un()}},px=()=>{Go.clear()},ux=async e=>{if(e.status!==403)return null;try{const t=dx.safeParse(await e.clone().json());return t.success?t.data.directory:null}catch{return null}},lb=async e=>lx.parse(await e.json()),ir=async e=>{const t=await T(rb,{query:{directory:e}});if(!t.ok)throw new Error(`Folder trust check answered ${t.status}`);return lb(t)},gx=async e=>{const t=await T(rb,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({directory:e.directory,fingerprint:e.fingerprint})});if(t.status===409)return{kind:"changed",assessment:await lb(t)};if(!t.ok)throw new Error(`Saving folder trust answered ${t.status}`);return{kind:"trusted"}},mx=(e,t,s)=>new Promise(a=>{const n=o=>{if(t!==Ws){a(!1);return}Pa={directory:o.directory,items:o.items,settle:async i=>{if(i==="skip")return Go.add(`${o.directory}
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-heic2any-CRnROUpT.js","assets/vendor-react--VO_rL_p.js","assets/vendor-scheduler-7OC5HNn7.js","assets/zh-CN-D2e-OTjQ.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-zustand-C9tWdk0j.js","assets/vendor-zod-B_hXR7jf.js","assets/vendor-opencode-client-NJGkA1Ku.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/vendor-streamdown-BbSYZ3NF.js","assets/vendor-markdown-BTUqNk6W.js","assets/vendor-mdast-util-from-markdown-CZHjOE75.js","assets/vendor-micromark-util-decode-numeric-character-reference-CNs1qBpV.js","assets/vendor-micromark-util-decode-string-fHsnqYdj.js","assets/vendor-decode-named-character-reference-C3-224fz.js","assets/vendor-micromark-util-normalize-identifier-C9ANKk3v.js","assets/vendor-micromark-AWM-NZXP.js","assets/vendor-micromark-util-combine-extensions-d8XJZrgA.js","assets/vendor-micromark-util-chunked-DrRIdSP-.js","assets/vendor-micromark-factory-space-PzSHLgmq.js","assets/vendor-micromark-util-character-CW3Cu1MS.js","assets/vendor-micromark-core-commonmark-kzTLNXAm.js","assets/vendor-micromark-util-classify-character-tcLuZZwM.js","assets/vendor-micromark-util-resolve-all-PQCKh0dx.js","assets/vendor-micromark-util-subtokenize-BF1Jf29a.js","assets/vendor-micromark-factory-destination-Sj0xfi0V.js","assets/vendor-micromark-factory-label-amyP0HdC.js","assets/vendor-micromark-factory-title-khnLkZK6.js","assets/vendor-micromark-factory-whitespace-eIB00uTl.js","assets/vendor-micromark-util-html-tag-name-DbKNfynz.js","assets/vendor-unist-util-stringify-position-Ch_qCilz.js","assets/vendor-mdast-util-to-string-C_aolqmU.js","assets/vendor-unist-util-visit-DhPeCsfG.js","assets/vendor-unist-util-visit-parents-DlviEg7Z.js","assets/vendor-unist-util-is-BPZGFiMU.js","assets/vendor-hast-util-raw-DvvLJg15.js","assets/vendor-ungap-structured-clone--gfxRhYI.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-parse5-DwmzEj2o.js","assets/vendor-entities-wUUgTZDW.js","assets/vendor-web-namespaces-bsVAaBS1.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-unist-util-position-60F3QETU.js","assets/vendor-hast-util-from-parse5-Ba3T6RJI.js","assets/vendor-devlop-0Dp3JUBc.js","assets/vendor-property-information-Boo8Xpef.js","assets/vendor-hastscript-BrPNioaz.js","assets/vendor-comma-separated-tokens-CRUGqg4f.js","assets/vendor-space-separated-tokens-D7QSIrTI.js","assets/vendor-hast-util-parse-selector-TXfch5wI.js","assets/vendor-vfile-location-LfEFwJ2h.js","assets/vendor-hast-util-to-parse5-BoysVIPW.js","assets/vendor-hast-util-sanitize-2aGO5ay8.js","assets/vendor-micromark-extension-gfm-CsfPlnlB.js","assets/vendor-micromark-extension-gfm-autolink-literal-BYug7onl.js","assets/vendor-micromark-extension-gfm-footnote-OFl1FCH2.js","assets/vendor-micromark-extension-gfm-strikethrough-CyFiuwBf.js","assets/vendor-micromark-extension-gfm-table-dgw4LfUw.js","assets/vendor-micromark-extension-gfm-task-list-item-Dnadzr9U.js","assets/vendor-mdast-util-gfm-CroMDYLM.js","assets/vendor-mdast-util-gfm-autolink-literal-CTruMtvI.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-mdast-util-find-and-replace-DB9iC-bx.js","assets/vendor-escape-string-regexp-BaJN9MlJ.js","assets/vendor-mdast-util-gfm-footnote-C-csI7OF.js","assets/vendor-mdast-util-gfm-strikethrough-BcskTdio.js","assets/vendor-mdast-util-gfm-table-DhPwQIyj.js","assets/vendor-markdown-table-DvhhVmnL.js","assets/vendor-mdast-util-to-markdown-Cl3qaiyc.js","assets/vendor-longest-streak-CtXnX3Xp.js","assets/vendor-mdast-util-phrasing-4oVbNLC3.js","assets/vendor-mdast-util-gfm-task-list-item-DMU5mK_M.js","assets/vendor-mdast-util-to-hast-CWnLaQSO.js","assets/vendor-micromark-util-sanitize-uri-BbwQ7CLk.js","assets/vendor-trim-lines-D8znQY54.js","assets/vendor-micromark-extension-cjk-friendly-BzZDGrF5.js","assets/vendor-micromark-extension-cjk-friendly-util-D5lVNoxW.js","assets/vendor-get-east-asian-width-CPhS2cOv.js","assets/vendor-micromark-util-symbol-JJPacVTp.js","assets/vendor-mdast-util-to-markdown-cjk-friendly-BZ3pe_qd.js","assets/vendor-micromark-extension-cjk-friendly-gfm-strikethrough-CqW-Ep4M.js","assets/vendor-mdast-util-to-markdown-cjk-friendly-gfm-strikethrough-BdPDQFO7.js","assets/vendor-hast-util-from-html-isomorphic-B0Kn01s9.js","assets/vendor-hast-util-from-dom-DeNf9aYW.js","assets/vendor-katex-DBqql0K7.js","assets/vendor-hast-util-to-text-0GXLnBvt.js","assets/vendor-hast-util-is-element-CuOmiqQi.js","assets/vendor-unist-util-find-after-CMaZmLxc.js","assets/vendor-micromark-extension-math-BRFoDziv.js","assets/vendor-mdast-util-math-wB-IJCL0.js","assets/vendor-remend-r8cP_t-e.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-marked-DN3zOnEe.js","assets/vendor-hast-util-to-jsx-runtime-Bq6JeJCx.js","assets/vendor-style-to-js-CI2G4dgu.js","assets/vendor-style-to-object-BAv4SQXc.js","assets/vendor-inline-style-parser-BlqBsVO4.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/vendor-estree-util-is-identifier-name-BgBfM8ME.js","assets/vendor-vfile-message-DqhD22jI.js","assets/vendor-unified-1CQKw2_w.js","assets/vendor-bail-FqpXQuLt.js","assets/vendor-extend-B94qxKr5.js","assets/vendor-is-plain-obj-C1gvLhAf.js","assets/vendor-trough-B_b8ryxu.js","assets/vendor-vfile-BCWrK60u.js","assets/vendor-html-url-attributes-D46m5wfe.js","assets/vendor-capacitor-core-B4EWRrHz.js","assets/fr-BJEccZsE.js","assets/nl-MVCsXAqA.js","assets/zh-TW-DCj_Doyh.js","assets/es-BextOZlH.js","assets/pt-BR-D-thkXCk.js","assets/uk-CWz0kaNm.js","assets/ko-BAGf67hm.js","assets/pl-zi2r4I2L.js","assets/de-DpOf_BMg.js","assets/ja-Bf_2zWyq.js","assets/tr-BeLCIXLh.js","assets/ar-DuOBHgr_.js","assets/he-9oI-aOhB.js","assets/vendor-capacitor-app-BrDJj9I_.js"])))=>i.map(i=>d[i]);
2
+ import{_ as Ge}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as Rt,d as jn,p as oi,a as $v}from"./vendor-zustand-C9tWdk0j.js";import{o as d,s as c,n as w,l as m,f as y,c as C,e as X,_ as S,u as M,a as ke,j as at,h as ne,i as Qv,k as wr,p as xs,q as tr,v as Yv,w as Kr,x as Xv,N as eC,y as tC,z as vi}from"./vendor-zod-B_hXR7jf.js";import{e as Xh,C as Vu}from"./vendor-opencode-client-NJGkA1Ku.js";import{f as kt,R as ta,r as sC}from"./vendor-react--VO_rL_p.js";import{F as ef}from"./vendor-fuse.js-Dw8P0qyA.js";import{X as aC}from"./vendor-streamdown-BbSYZ3NF.js";import{u as nC}from"./vendor-unified-1CQKw2_w.js";import{c as oC}from"./vendor-markdown-BTUqNk6W.js";import{registerPlugin as iC}from"./vendor-capacitor-core-B4EWRrHz.js";const bo=1,rC=d({type:m("relay-retire"),code:w().int(),reason:c().catch("")}),cC=e=>{try{const t=rC.safeParse(JSON.parse(e));return t.success?{code:t.data.code,reason:t.data.reason}:null}catch{return null}},lC="openchamber-relay-v1",tf=1,sf=12,ko=1+sf,Bo=64*1024,Lo=5,yr=128,af=0,nf=1,bn=4,dC=1+bn,Ol=Bo-Lo-dC,pC="x-openchamber-tunnel-accept-encoding",uC="x-openchamber-tunnel-content-encoding",ce={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12,DeliveryAck:13},gC=new Set(Object.values(ce)),mC=e=>gC.has(e),Ys={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},ks=globalThis.crypto.subtle,of={name:"ECDH",namedCurve:"P-256"},rf=16,Tc=32,hC=16,Dl=4,cf=8;class Js extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const fC=()=>ks.generateKey(of,!0,["deriveBits"]),bC=async e=>{const t=await ks.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},kC=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new Js("invalid ECDH public key JWK");try{return await ks.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},of,!0,[])}catch{throw new Js("invalid ECDH public key JWK")}},wC=()=>{const e=new Uint8Array(rf);return globalThis.crypto.getRandomValues(e),e},yC=async(e,t,s)=>{if(s.length!==rf)throw new Js("invalid handshake nonce length");const a=await ks.deriveBits({name:"ECDH",public:t},e,256),n=await ks.importKey("raw",a,"HKDF",!1,["deriveBits"]),o=new Uint8Array(await ks.deriveBits({name:"HKDF",hash:"SHA-256",salt:s,info:new TextEncoder().encode(lC)},n,Tc*2*8)),i=(r,l)=>ks.importKey("raw",r,{name:"AES-GCM"},!1,l);return{clientToHost:await i(o.slice(0,Tc),["encrypt","decrypt"]),hostToClient:await i(o.slice(Tc),["encrypt","decrypt"])}},vC=(e,t,s)=>{for(let a=cf-1;a>=0;a-=1)e[t+a]=Number(s&0xffn),s>>=8n},CC=(e,t)=>{let s=0n;for(let a=0;a<cf;a+=1)s=s<<8n|BigInt(e[t+a]);return s},SC=e=>{const t=new Uint8Array(Dl);globalThis.crypto.getRandomValues(t);let s=0n;return{async encrypt(a){if(a.length>Bo)throw new Js("plaintext frame exceeds maximum size");s+=1n;const n=new Uint8Array(sf);n.set(t,0),vC(n,Dl,s);const o=new Uint8Array(await ks.encrypt({name:"AES-GCM",iv:n},e,a)),i=new Uint8Array(ko+o.length);return i[0]=tf,i.set(n,1),i.set(o,ko),i}}},PC=e=>{let t=0n;return{async decrypt(s){if(s.length<ko+hC)throw new Js("encrypted frame too short");if(s[0]!==tf)throw new Js("unsupported encrypted frame version");const a=s.slice(1,ko),n=CC(a,Dl);if(n<=t)throw new Js("frame counter regression");let o;try{o=await ks.decrypt({name:"AES-GCM",iv:a},e,s.slice(ko))}catch{throw new Js("frame decryption failed")}return t=n,new Uint8Array(o)}}},Ci="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",xC=e=>{let t="";for(let s=0;s<e.length;s+=3){const a=e[s],n=s+1<e.length?e[s+1]:void 0,o=s+2<e.length?e[s+2]:void 0;t+=Ci[a>>2],t+=Ci[(a&3)<<4|(n??0)>>4],n!==void 0&&(t+=Ci[(n&15)<<2|(o??0)>>6]),o!==void 0&&(t+=Ci[o&63])}return t},Uu=e=>{let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;const s=t;if(s.v!==bo)return null;const a=s.batch===!0,n=s.flowControl===!0;return s.t==="ready"?{t:"ready",v:bo,batch:a,flowControl:n}:s.t==="hello"&&typeof s.nonce=="string"&&typeof s.clientPubJwk=="object"&&s.clientPubJwk!==null?{t:"hello",v:bo,clientPubJwk:s.clientPubJwk,nonce:s.nonce,batch:a,flowControl:n}:null},TC=e=>({type:"fail",closeCode:Ys.ChannelFailure,reason:e}),AC=async(e,t={})=>{const s=t.batch!==!1,a=await kC(e),n=await fC(),o=wC(),i={t:"hello",v:bo,clientPubJwk:await bC(n.publicKey),nonce:xC(o)};s&&(i.batch=!0),t.flowControl!==!1&&(i.flowControl=!0);let r=!1;return{helloText:JSON.stringify(i),get established(){return r},async handleText(l){if(r)return Uu(l)?.t==="ready"?{type:"ignore"}:TC("plaintext frame on established channel");const p=Uu(l);if(p?.t!=="ready")return{type:"ignore"};const u=await yC(n.privateKey,a,o);return r=!0,{type:"established",batch:s&&p.batch===!0,flowControl:t.flowControl!==!1&&p.flowControl===!0,channel:{encryptor:SC(u.clientToHost),decryptor:PC(u.hostToClient)}}}}},lf=4294967295,zC=e=>{if(!Number.isSafeInteger(e)||e<0)throw new Error("invalid delivery acknowledgement");const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e)),t};class _e extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const Dt=(e,t,s,a=!1)=>{if(!Number.isInteger(t)||t<0||t>lf)throw new _e("invalid stream id");if(s.length>Ol)throw new _e("tunnel payload exceeds maximum size");const n=new Uint8Array(Lo+s.length);return n[0]=a?e|yr:e,n[1]=t>>>24&255,n[2]=t>>>16&255,n[3]=t>>>8&255,n[4]=t&255,n.set(s,Lo),n},RC=e=>{if(e.length<Lo)throw new _e("tunnel frame too short");const t=e[0],s=(t&yr)!==0,a=t&~yr;if(!mC(a))throw new _e(`unknown tunnel frame type ${a}`);const n=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:a,streamId:n,payload:e.slice(Lo),hasMoreFragments:s}},IC=new TextEncoder,jC=new TextDecoder,Si=e=>IC.encode(JSON.stringify(e)),Pi=(e,t)=>{let s;try{s=JSON.parse(jC.decode(e))}catch{throw new _e("malformed JSON tunnel payload")}if(!t(s))throw new _e("unexpected JSON tunnel payload shape");return s},df=(e,t=Ol)=>{if(t<=0||t>Ol)throw new _e("invalid chunk size");if(e.length===0)return[new Uint8Array(0)];const s=[];for(let a=0;a<e.length;a+=t)s.push(e.slice(a,a+t));return s},Wu=(e,t,s)=>{const a=df(s);return a.map((n,o)=>Dt(e,t,n,o<a.length-1))},OC=(e=16*1024*1024)=>{const t=new Map;return{push(s){const a=`${s.streamId}:${s.frameType}`,n=t.get(a);if(!s.hasMoreFragments&&!n)return s.payload;const o=n?.chunks??[],i=(n?.totalBytes??0)+s.payload.length;if(i>e)throw t.delete(a),new _e("fragmented message exceeds maximum size");if(o.push(s.payload),s.hasMoreFragments)return t.set(a,{chunks:o,totalBytes:i}),null;t.delete(a);const r=new Uint8Array(i);let l=0;for(const p of o)r.set(p,l),l+=p.length;return r},dropStream(s){for(const a of t.keys())a.startsWith(`${s}:`)&&t.delete(a)}}},DC=e=>{if(e.length===0)throw new _e("cannot encode an empty frame batch");if(e.length===1){const n=e[0],o=new Uint8Array(1+n.length);if(o[0]=af,o.set(n,1),o.length>Bo)throw new _e("frame batch exceeds maximum plaintext size");return o}let t=1;for(const n of e)t+=bn+n.length;if(t>Bo)throw new _e("frame batch exceeds maximum plaintext size");const s=new Uint8Array(t);s[0]=nf;let a=1;for(const n of e)s[a]=n.length>>>24&255,s[a+1]=n.length>>>16&255,s[a+2]=n.length>>>8&255,s[a+3]=n.length&255,a+=bn,s.set(n,a),a+=n.length;return s},NC=e=>{if(e.length<1)throw new _e("empty batch plaintext");const t=e[0];if(t===af)return[e.slice(1)];if(t!==nf)throw new _e(`unknown batch container tag ${t}`);const s=[];let a=1;for(;a<e.length;){if(a+bn>e.length)throw new _e("truncated batch frame length");const n=(e[a]<<24|e[a+1]<<16|e[a+2]<<8|e[a+3])>>>0;if(a+=bn,a+n>e.length)throw new _e("truncated batch frame body");s.push(e.slice(a,a+n)),a+=n}if(s.length===0)throw new _e("empty frame batch");return s},FC=new Set([ce.HttpBody,ce.WsText,ce.WsBinary]),pf=150,EC=24*1024,MC=32,BC=e=>{const t=e.windowMs??pf,s=e.maxBatchBytes??EC,a=e.maxBatchFrames??MC,n=e.now??(()=>Date.now()),o=e.setTimer??((v,P)=>setTimeout(v,P)),i=e.clearTimer??(v=>clearTimeout(v));let r=[],l=0,p=null,u=0,g=!1;const h=()=>{p!==null&&(i(p),p=null)},b=()=>{if(h(),r.length===0)return;const v=r;r=[],l=0,u=n(),e.sendBatch(DC(v))};return{enqueue:v=>{if(g)return;const P=v[0]&~yr;if(!FC.has(P)){r.push(v),b();return}const z=n();if(r.length===0&&z-u>=t){r.push(v),b();return}const x=bn+v.length;if(r.length>0&&1+l+x>Bo&&b(),r.push(v),l+=x,l>=s||r.length>=a){b();return}p===null&&(p=o(b,t))},flush:b,dispose(){g=!0,h(),r=[],l=0}}},LC=()=>{let e=1;return{next(){if(e>lf)throw new _e("stream id space exhausted");const t=e;return e+=2,t}}},Zr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qC=e=>Zr(e)&&Object.values(e).every(t=>typeof t=="string"),VC=e=>Zr(e)&&typeof e.status=="number"&&qC(e.headers),Hu=e=>Zr(e)&&typeof e.reason=="string",UC=e=>Zr(e)&&typeof e.code=="number"&&typeof e.reason=="string",uf=/^[a-z][a-z\d+.-]*:\/\//i,cp="http://tunnel.invalid",WC=e=>{try{const t=uf.test(e)?new URL(e):new URL(e,cp);return`${t.pathname}${t.search}`}catch{return e}},xi=e=>({async*[Symbol.asyncIterator](){yield e}}),HC=e=>({async*[Symbol.asyncIterator](){const t=e.getReader();try{for(;;){const{done:s,value:a}=await t.read();if(s)return;a&&(yield a)}}finally{t.releaseLock()}}}),GC=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},_C=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:HC(e)};if(typeof e=="string")return{body:xi(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:xi(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:xi(GC(e))};const t=new Response(e),s=t.headers.get("content-type")??void 0,a=new Uint8Array(await t.arrayBuffer());return{body:xi(a),contentType:s}},KC=async(e,t)=>{let s;const a=new Headers;let n="GET",o=null,i;e instanceof Request?(s=e.url,n=e.method,e.headers.forEach((g,h)=>a.set(h,g)),i=e.signal,o=e.body):s=e.toString(),t&&(t.method&&(n=t.method),t.headers&&new Headers(t.headers).forEach((g,h)=>a.set(h,g)),t.body!==void 0&&(o=t.body),t.signal&&(i=t.signal));const r=uf.test(s)?new URL(s):new URL(s,cp),{body:l,contentType:p}=await _C(o);p&&!a.has("content-type")&&a.set("content-type",p);const u={};return a.forEach((g,h)=>{u[h]=g}),{method:n.toUpperCase(),path:r.pathname,query:r.search.startsWith("?")?r.search.slice(1):r.search,headers:u,body:l,signal:i}},gf="__openchamberAmbiguousTransport",mf=new WeakSet,ZC=e=>(mf.add(e),e),JC=e=>mf.has(e),Nl=e=>(Object.defineProperty(e,gf,{value:!0,enumerable:!1,configurable:!0}),e),$C=e=>!e||typeof e!="object"?!1:e[gf]===!0,QC=["local","remote",null],YC=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function hf(e){if(!e||typeof e!="object")return{valid:!1};const t=e,s=t.localAvailable===!1?{localAvailable:!1}:{},a=t.target,n=t.status;if(a!==null&&(typeof a!="string"||!QC.includes(a)))return{valid:!1};if(typeof n!="string"||!YC.includes(n))return{valid:!1};if(a==="remote"||a==="local"){if(n==="ok"&&a==="local"){const o={target:"local",status:"ok",...s},i=c().min(1).safeParse(t.sshStartupFallbackHostId);return i.success&&(o.sshStartupFallbackHostId=i.data),{valid:!0,outcome:o}}if(n==="ok"&&a==="remote")return typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"ok",hostId:t.hostId,url:t.url,...s}};if(n==="unreachable")return a==="local"?{valid:!0,outcome:{target:"local",status:"unreachable",...s}}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"unreachable",hostId:t.hostId,url:t.url,...s}};if(n==="incompatible"||n==="wrong-service")return a!=="remote"?{valid:!1}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:n,hostId:t.hostId,url:t.url,...s}};if(n==="missing")return a!=="remote"?{valid:!1}:typeof t.hostId!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"missing",hostId:t.hostId,...s}}}if(a===null){if(n==="not-configured")return{valid:!0,outcome:{target:null,status:"not-configured",...s}};if(n==="missing")return{valid:!1}}return{valid:!1}}function Z_(e){if(!e.isDesktopShell)return null;const t=e.bootOutcome;if(!t)return null;const s=t.localAvailable===!1?{localAvailable:!1}:{};if(t.status==="ok"){if(t.target==="local")return{screen:"main",...s};if(t.target==="remote")return{screen:"main",hostId:t.hostId,url:t.url,...s}}if(t.target===null&&t.status==="not-configured")return{screen:"chooser",...s};if(t.target==="local"&&t.status==="unreachable")return{screen:"chooser",...s};if(t.target==="remote"){if(t.status==="unreachable")return{screen:"recovery",variant:"remote-unreachable",hostId:t.hostId,url:t.url,...s};if(t.status==="incompatible")return{screen:"recovery",variant:"remote-incompatible",hostId:t.hostId,url:t.url,...s};if(t.status==="wrong-service")return{screen:"recovery",variant:"remote-wrong-service",hostId:t.hostId,url:t.url,...s};if(t.status==="missing")return{screen:"recovery",variant:"remote-missing",hostId:t.hostId,...s}}return null}function J_(e){return!e.isDesktopShell||e.bootOutcomeKnown}function $_(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function ff(){if(XC()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,s=hf(t);return s.valid?s.outcome:null}function XC(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":hf(e).valid?"valid":"malformed"}const vr=/^[a-z][a-z\d+.-]*:\/\//i,eS=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},Cr=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),tS=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return Cr(e)},sS=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return Cr(e)},aS=()=>Object.keys(Nn()).length>0,nS=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},Fl=(e,t)=>{if(!t)return;const s=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[a,n]of s)n!=null&&e.searchParams.set(a,String(n))},oS=(e,t)=>{if(!t)return e;const s=new URLSearchParams;Fl({searchParams:s},t);const a=s.toString();return a?e.includes("?")?`${e}&${a}`:`${e}?${a}`:e},Gu=(e,t,s)=>{if(vr.test(t)){const i=new URL(t);return Fl(i,s),i.toString()}const a=eS(t);if(!e)return oS(a,s);const n=new URL(e),o=new URL(`${n.origin}${n.pathname.replace(/\/+$/,"")}${a}`);return Fl(o,s),o.toString()},Ti=(e,t=HS())=>{if(!t)return e;const s=vr.test(e)?new URL(e):new URL(e,"http://openchamber.local");return s.searchParams.set("oc_url_token",t),vr.test(e)?s.toString():`${s.pathname}${s.search}${s.hash}`},bf=(e,t)=>{const s=vr.test(e)?new URL(e):new URL(e,nS(t));return s.protocol==="ws:"||s.protocol==="wss:"||(s.protocol=s.protocol==="https:"?"wss:":"ws:"),s.toString()},_u=(e,t,s)=>{if(!aS())return null;const a=sS();if(!a)return null;try{const n=new URL(`/api/openchamber/realtime-proxy/${e==="sse"?"sse":"ws"}`,`${a}/`);n.searchParams.set("url",t);const o=GS(a);return o&&n.searchParams.set("oc_url_token",o),e==="ws"?(n.protocol=n.protocol==="https:"?"wss:":"ws:",bf(n.toString(),s)):n.toString()}catch{return null}},lp=(e={})=>{const t=Cr(e.apiBaseUrl),s=Cr(e.realtimeBaseUrl),a=()=>t||tS(),n=()=>s||a(),o=(r,l)=>Gu(a(),r,l),i=(r,l)=>Gu(n(),r,l);return{api:o,authenticatedAsset:(r,l)=>Ti(o(r,l)),assetWithUrlToken:(r,l,p)=>Ti(o(r,p),l),auth:o,health:r=>o("/health",r),rawFile:(r,l)=>o("/api/fs/raw",{path:r,download:l?.download===!0?!0:void 0,allowOutsideWorkspace:l?.allowOutsideWorkspace===!0?!0:void 0,outsideFileGrant:l?.outsideFileGrant}),sse:(r,l)=>{const p=Ti(i(r,l));return _u("sse",p,e)||p},websocket:(r,l)=>{const p=bf(Ti(i(r,l)),e);return _u("ws",p,e)||p}}};let Sr=lp();const vs=()=>Sr,iS=e=>{Sr=e},kf=e=>(Sr=lp(e),Sr),dp=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,qo=()=>{const e=dp();return e?Array.isArray(e.workspaceFolders)?e.workspaceFolders.length===0:!e.workspaceFolder?.trim():!1},pp=(e=dp())=>!!e,El="openchamber:runtime-endpoint-changed",Ml="openchamber:runtime-endpoint-will-change";let kn="",Vo="",Bl=0,Ll=null;const Ac=(e,t,s)=>{try{e[t]=s}catch{}},up=e=>{try{const t=new URL(e);return t.hash="",t.search="",t.pathname=t.pathname.replace(/\/+$/,"")||"/",`url:${t.toString().replace(/\/+$/,"")}`}catch{return`url:${e.trim().replace(/\/+$/,"")||"default"}`}},rS="mobile-disconnected",cS="url:default",ql=e=>e===""||e===rS||e===cS&&!pp(),wf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},yf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},vf=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},ns=()=>kn||wf(),lS=()=>{if(Ll!==null)return Ll;const e=ns();return!!(e&&e===globalThis.window?.__OPENCHAMBER_SSH_FORWARD_API_URL__)};let zc="",Ku=null,Zu,Ju;const $u=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},N=()=>{if(Vo)return Vo;const e=$u("__OPENCHAMBER_API_BASE_URL__"),t=$u("__OPENCHAMBER_LOCAL_ORIGIN__");if(Ku===kn&&Zu===e&&Ju===t)return zc;const s=ns();return zc=vf(s,yf())?"local":up(s),Ku=kn,Zu=e,Ju=t,zc},sr=()=>{const e=Bl,t=N();return()=>e===Bl&&t===N()},dS=(e={})=>{if(kn||Vo)return;const t=e.apiBaseUrl?.trim()||wf(),s=globalThis.window?.location?.origin??"",a=/^https?:\/\//.test(s)?s:"";if(!t&&!a)return;const n=yf(),o=n&&(!t||vf(t,n));kn=t,Vo=e.runtimeKey?.trim()||(o?"local":up(t||a))},Vl=e=>{const t=e.apiBaseUrl.trim(),s=ns(),a=N(),n=e.runtimeKey?.trim()||up(t),o=e.sshForwarded??(t===s&&n===a&&lS()),i={apiBaseUrl:t,previousApiBaseUrl:s,runtimeKey:n,previousRuntimeKey:a};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ml,{detail:i})),kn=t,Vo=n,n!==a&&(Bl+=1),Ll=o,typeof window<"u"){const r=window;Ac(r,"__OPENCHAMBER_API_BASE_URL__",t),Ac(r,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),Ac(r,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}kf({apiBaseUrl:t,realtimeBaseUrl:t}),Ef(e.requestHeaders||null),Ff(e.clientToken||null),e.relay?MS(e.relay):BS(),Xr(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(El,{detail:i}))},Jr=e=>{if(typeof window>"u")return()=>{};const t=s=>{e(s.detail)};return window.addEventListener(Ml,t),()=>window.removeEventListener(Ml,t)},$r=e=>{if(typeof window>"u")return()=>{};const t=s=>{e(s.detail)};return window.addEventListener(El,t),()=>window.removeEventListener(El,t)};let Ul=null;const Q_=e=>{Ul=e},On=()=>Ul||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),pS=e=>e==="stable"||e==="canary",uS=/^v?(\d+\.\d+\.\d+)-canary\.(\d{4})(\d{2})(\d{2})(?:\.(\d+))?$/,Y_=e=>{const t=uS.exec(e??"");if(!t)return null;const[,s,a,n,o,i]=t;return{release:s,builtOn:new Date(Date.UTC(Number(a),Number(n)-1,Number(o))),build:i?Number(i):null}},gS=(e,t)=>new Intl.DateTimeFormat(t,{day:"numeric",month:"short",timeZone:"UTC"}).format(e),X_=(e,t,s)=>{const a=gS(e.builtOn,t);return s!=null&&s.builtOn.getTime()===e.builtOn.getTime()&&s.build!==e.build&&e.build!==null?`${a} #${e.build}`:a},Cf=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,Ts=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,ja=()=>Cf()?.runtime==="electron",Sf=()=>{if(typeof window>"u")return null;const e=window.__OPENCHAMBER_PLATFORM__;return typeof e=="string"?e:null},mS="right",e0=()=>{if(!ja())return!1;const e=Sf();return e==="linux"?Cf()?.nativeFrame!==!0:e==="win32"},t0=e=>e==="left"?"left":mS,s0=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],rt=()=>typeof Ts()?.invoke=="function",wt=()=>ja()&&rt(),hS=()=>{const e=Ts()?.clipboard;if(!e?.readSelection||!e.writeSelection)return;const{readSelection:t,writeSelection:s}=e;return{selection:{readText:async()=>c().parse(await t()),writeText:async a=>{m(!0).parse(await s(a))}}}},fS=()=>{if(Ts()?.pickThemeFile)return{async pick(){const e=Ts()?.pickThemeFile;return e?{status:"picked",file:d({name:c(),size:w().nonnegative(),text:c()}).nullable().parse(await e())}:{status:"unsupported"}}}},oe=async(e,t)=>{const s=Ts();return typeof s?.invoke!="function"?null:s.invoke(e,t??{})},a0=e=>{Sf()!=="darwin"||!wt()||oe("desktop_clear_session_notifications",{sessionId:e}).catch(()=>{})},n0=()=>({apiBaseUrl:ns(),clientToken:bp(),runtimeKey:N()}),o0=async()=>{if(!ot()||!ze())return!1;const e=ns();try{const t=y().safeParse(await oe("desktop_managed_opencode_compatible",{apiBaseUrl:e}));return t.success&&t.data&&e===ns()}catch{return!1}},i0=async()=>{if(!wt()||!ze())return null;try{const e=await oe("desktop_get_launch_at_login");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get launch at login status",e),null}},r0=async e=>{if(!wt()||!ze())return null;try{const t=await oe("desktop_set_launch_at_login",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set launch at login status",t),null}},Pf=e=>pS(e?.channel)?e.channel:null,c0=async()=>{if(!wt()||!ze())return null;try{return Pf(await oe("desktop_get_update_channel"))}catch(e){return console.warn("Failed to get the update channel",e),null}},l0=async e=>{if(!wt()||!ze())return null;try{return Pf(await oe("desktop_set_update_channel",{channel:e}))}catch(t){return console.warn("Failed to set the update channel",t),null}},d0=async()=>{if(!wt()||!ze())return null;try{const e=await oe("desktop_get_minimize_to_tray");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get minimize to tray status",e),null}},p0=async e=>{if(!wt()||!ze())return null;try{const t=await oe("desktop_set_minimize_to_tray",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set minimize to tray status",t),null}},u0=async()=>{if(!wt()||!ze())return null;try{const e=await oe("desktop_get_mini_chat_global_shortcut");return!e||typeof e.supported!="boolean"||e.combo!==null&&typeof e.combo!="string"||typeof e.active!="boolean"?null:e}catch(e){return console.warn("Failed to get Mini Chat global shortcut status",e),null}},g0=async e=>{if(!wt()||!ze())return null;try{const t=await oe("desktop_set_mini_chat_global_shortcut",{combo:e});return!t||typeof t.supported!="boolean"||t.combo!==null&&typeof t.combo!="string"||typeof t.active!="boolean"||t.error!==void 0&&t.error!=="unsupported-combo"?null:t}catch(t){return console.warn("Failed to set Mini Chat global shortcut",t),null}},bS=d({supported:y(),enabled:y(),combo:c().nullable(),storedCombo:c().nullable(),active:y(),heightFraction:w(),error:m("unsupported-combo").optional()}),Qr=async(e,t,s)=>{if(!wt()||!ze())return null;try{const a=bS.safeParse(await oe(e,t));return a.success?a.data:null}catch(a){return console.warn(s,a),null}},m0=()=>Qr("desktop_get_quake_mode",{},"Failed to get Quake Mode status"),h0=e=>Qr("desktop_set_quake_mode_enabled",{enabled:e},"Failed to set Quake Mode"),f0=e=>Qr("desktop_set_quake_mode_shortcut",{combo:e},"Failed to set Quake Mode shortcut"),b0=e=>Qr("desktop_set_quake_mode_height",{heightFraction:e},"Failed to set Quake Mode height"),k0=async()=>{if(!wt()||!ze())return null;try{const e=await oe("desktop_get_keep_awake");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"||typeof e.active!="boolean"?null:e}catch(e){return console.warn("Failed to get keep awake status",e),null}},w0=async e=>{if(!wt()||!ze())return null;try{const t=await oe("desktop_set_keep_awake",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"||typeof t.active!="boolean"?null:t}catch(t){return console.warn("Failed to set keep awake status",t),null}},Qu=e=>{const t=e.trim();if(!t)return null;try{return new URL(t).origin}catch{try{return new URL(t.endsWith("/")?t:`${t}/`).origin}catch{return null}}},Rc=e=>{const t=e.trim();if(!t)return null;try{return new URL(t)}catch{try{return new URL(t.endsWith("/")?t:`${t}/`)}catch{return null}}},kS=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),Zn=e=>{const t=kS(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},ze=()=>{if(typeof window>"u"||!ot())return!1;if(N()==="local")return!0;const e=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",t=Rc(e),s=Rc(ns());if(!s&&t&&ff()?.target==="local")return!0;if(t&&s){if(t.origin===s.origin)return!0;const i=t.port||(t.protocol==="https:"?"443":"80"),r=s.port||(s.protocol==="https:"?"443":"80");return t.protocol===s.protocol&&i===r&&Zn(t.hostname)&&Zn(s.hostname)}const a=Rc(window.location.origin);if(t&&a){if(t.origin===a.origin)return!0;const i=t.port||(t.protocol==="https:"?"443":"80"),r=a.port||(a.protocol==="https:"?"443":"80");return t.protocol===a.protocol&&i===r&&Zn(t.hostname)&&Zn(a.hostname)}const n=Qu(e),o=Qu(window.location.origin)||window.location.origin;return n&&o&&n===o?!0:!!(a&&Zn(a.hostname))},ot=()=>typeof window>"u"?!1:ja(),y0=async()=>{if(!ot())return null;const e=d({visible:y()}).safeParse(await oe("desktop_get_current_window_state"));return e.success?e.data.visible:null},v0=async()=>{if(!ot())return!1;try{return!!await oe("desktop_focus_window")}catch{return!1}},C0=(e,t,s=null)=>!t||t===N()||!wt()?!1:(oe("desktop_open_host_session",s?{runtimeKey:t,sessionId:e,messageId:s}:{runtimeKey:t,sessionId:e}).catch(n=>{console.warn("[desktop] failed to open host session",n)}),!0),xf=()=>ot()&&rt()&&ze(),wS=C(d({sessionId:c().min(1),messageId:c().min(1).optional(),runtimeKey:c().min(1).optional(),requireKnownSession:y().optional()})),S0=async()=>{if(!ot())return[];try{const e=C(c()).safeParse(await oe("desktop_take_pending_extension_installs"));return e.success?e.data:[]}catch{return[]}},P0=async()=>{if(!ot()||!ze())return[];try{const e=wS.safeParse(await oe("desktop_take_pending_session_links"));return e.success?e.data.map(t=>({sessionId:t.sessionId,messageId:t.messageId??null,runtimeKey:t.runtimeKey??null,requireKnownSession:t.requireKnownSession===!0})):[]}catch(e){return console.warn("Failed to read pending session links",e),[]}},yS=C(X("type",[d({type:m("pairing"),link:c().min(1)}),d({type:m("host"),hostId:c().min(1)})])),x0=async()=>{if(!ot())return[];try{const e=yS.safeParse(await oe("desktop_take_pending_host_actions"));return e.success?e.data:[]}catch(e){return console.warn("Failed to read pending host actions",e),[]}},vS=c().min(1),T0=e=>{if(!xf())return null;try{const t=vS.safeParse(Ts()?.pathForFile?.(e));return t.success?t.data:null}catch(t){return console.warn("Failed to resolve dropped file path",t),null}},A0=async()=>{if(!ot())return!1;try{return await oe("desktop_start_window_drag"),!0}catch{return!1}},Ee=()=>pp()?!0:On()?.runtime?.isVSCode===!0,z0=()=>{const t=On()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!Ee()},R0=(e,t=ot())=>e==="web"&&!t,Tf=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},I0=async e=>{if(xf())try{const t=await Ts()?.openDialog?.({directory:!0,multiple:!1,title:"Select Working Directory",...e?{defaultPath:e}:{}});return!t||typeof t!="string"?{success:!1,error:"Directory selection cancelled"}:{success:!0,path:t}}catch(t){return console.warn("Failed to request directory access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native directory picker not available"}},CS=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),j0=async e=>{if(rt()&&ze())try{const t=await Ts()?.openDialog?.({directory:!1,multiple:!1,title:"Select File",returnGrant:!0,...e?.filters?{filters:e.filters}:{},...e?.defaultPath?{defaultPath:e.defaultPath}:{}});if(!t)return{success:!1,error:"File selection cancelled"};if(typeof t=="string")return{success:!0,path:t};if(!CS(t))return{success:!1,error:"File selection cancelled"};const s=typeof t.path=="string"?t.path:"";return s?{success:!0,path:s,outsideFileGrant:typeof t.outsideFileGrant=="string"?t.outsideFileGrant:void 0}:{success:!1,error:"File selection cancelled"}}catch(t){return console.warn("Failed to request file access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native file picker not available"}},O0=async e=>({success:!0}),D0=async e=>({success:!0}),N0=async()=>rt()?await oe("desktop_check_for_updates"):null,F0=async e=>{if(!rt())return!1;const t=Ts();let s=null,a=0,n;try{return typeof e=="function"&&t?.listen&&(s=await t.listen("openchamber:update-progress",o=>{const i=o?.payload;if(!i||typeof i!="object")return;const r=i,l=typeof r.event=="string"?r.event:null,p=r.data&&typeof r.data=="object"?r.data:null;if(l==="Started"){a=0,n=typeof p?.contentLength=="number"?p.contentLength:void 0,e({downloaded:a,total:n});return}if(l==="Progress"){const u=p?.downloaded,g=p?.total;typeof u=="number"&&(a=u),typeof g=="number"&&(n=g),e({downloaded:a,total:n});return}l==="Finished"&&e({downloaded:a,total:n})})),await oe("desktop_download_and_install_update"),!0}catch(o){throw o instanceof Error?o:new Error(String(o))}finally{if(s)try{const o=s();o instanceof Promise&&await o}catch{}}},E0=async()=>rt()?(await oe("desktop_restart"),!0):!1,M0=async()=>{if(!rt())return!1;try{return await oe("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},B0=async()=>{if(!rt()||!ze())return null;try{const e=await oe("desktop_get_lan_address");return typeof e=="string"&&e.trim().length>0?e.trim():null}catch(e){return console.warn("Failed to get desktop LAN address",e),null}},SS=async(e,t)=>{if(!rt()||!ze())return!1;const s=e?.trim();if(!s)return!1;try{return await oe("desktop_open_path",{path:s,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),!0}catch(a){return console.warn("Failed to open path",a),!1}},L0=async e=>{if(!rt()||!ze())return!1;const t=e?.trim();if(!t)return!1;try{return await oe("desktop_reveal_path",{path:t}),!0}catch{return SS(t)}},q0=async(e,t)=>{if(!rt()||!ze())return null;const s=e?.trim();if(!s)return null;try{const a=await oe("desktop_save_markdown_file",{defaultFileName:s,content:t});return typeof a=="string"&&a.trim().length>0?a:null}catch(a){return console.warn("Failed to save markdown file",a),null}},V0=async(e,t,s)=>{if(!rt()||!ze())return!1;const a=e?.trim(),n=t?.trim(),o=s?.trim();if(!a||!n||!o)return!1;try{return await oe("desktop_open_in_app",{projectPath:a,appId:n,appName:o}),!0}catch(i){return console.warn("Failed to open project in app",i),!1}},U0=async(e,t,s)=>{if(!rt()||!ze())return!1;const a=e?.trim(),n=t?.trim(),o=s?.trim();if(!a||!n||!o)return!1;try{return await oe("desktop_open_file_in_app",{filePath:a,appId:n,appName:o}),!0}catch(i){return console.warn("Failed to open file in app",i),!1}},W0=async(e,t)=>{if(!rt()||!ze())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const s=Array.isArray(e)?e.filter(a=>typeof a=="string"):[];if(s.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const a=await oe("desktop_get_installed_apps",{apps:s,force:t===!0?!0:void 0});if(!a||typeof a!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const n=a;return n.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(n.apps)?{apps:n.apps.filter(i=>i&&typeof i=="object").map(i=>{const r=i;return{name:typeof r.name=="string"?r.name:"",iconDataUrl:typeof r.iconDataUrl=="string"?r.iconDataUrl:null}}).filter(i=>i.name.length>0),success:!0,hasCache:n.hasCache===!0,isCacheStale:n.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(a){return console.warn("Failed to fetch installed apps",a),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},H0=()=>navigator.platform.toLowerCase().startsWith("linux"),Oa=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",G0=()=>typeof window>"u"||!Oa()?!1:Af()==="ios"&&PS(),PS=()=>{if(typeof navigator>"u")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},Af=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Ee()?"vscode":ot()?"desktop":"web"},xS="2.7.2-canary.20261112.18",Ai=new Uint8Array(0),TS=typeof DecompressionStream=="function",AS=e=>e.pipeThrough(new TransformStream({transform(t,s){s.enqueue(t.buffer instanceof ArrayBuffer?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t))}})).pipeThrough(new DecompressionStream("gzip")),zf=e=>ArrayBuffer.isView(e)?e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):e,zS=new TextEncoder,RS=new TextDecoder,Ot=e=>e instanceof Error?e:new Error(String(e)),zi=()=>new DOMException("The operation was aborted.","AbortError"),IS=e=>{e.binaryType="arraybuffer";const t={get readyState(){return e.readyState},send(s){e.send(zf(s))},close(s,a){e.close(s,a)},onopen:null,onmessage:null,onclose:null,onerror:null};return e.onopen=()=>t.onopen?.(),e.onmessage=s=>t.onmessage?.({data:s.data}),e.onclose=s=>t.onclose?.({code:s.code,reason:s.reason}),e.onerror=()=>t.onerror?.(),t},jS=e=>{const t={get readyState(){return e.readyState},get binaryType(){return e.binaryType},set binaryType(s){s&&(e.binaryType=s)},onopen:null,onmessage:null,onerror:null,onclose:null,send(s){e.send(zf(s))},close(s,a){e.close(s,a)}};return e.onopen=()=>t.onopen?.(),e.onmessage=s=>{const a=s.data;(typeof a=="string"||a instanceof ArrayBuffer)&&t.onmessage?.({data:a})},e.onerror=()=>t.onerror?.(),e.onclose=s=>t.onclose?.({code:s.code,reason:s.reason}),t},OS=e=>e?.state==="error"&&e.closeCode===Ys.LimitExceeded,Yu=0,Ic=1,Xu=2,eg=3,DS=new Set([Ys.AuthFailed,Ys.DuplicateClient,Ys.LimitExceeded]),NS={[Ys.AuthFailed]:"relay authentication failed",[Ys.DuplicateClient]:"relay connection replaced by another client",[Ys.LimitExceeded]:"relay connection limit reached"},jc=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},gp=e=>{const t=e.helloRetryMs??1e3,s=e.helloTimeoutMs??3e4,a=e.pingIntervalMs??3e4,n=e.pingTimeoutMs??15e3,o=e.batchWindowMs??pf,i=e.batch!==!1,r=e.reconnectBaseDelayMs??1e3,l=e.reconnectMaxDelayMs??3e4,p=e.hiddenOrOfflineMaxDelayMs??6e4,u=e.createWireSocket??(q=>IS(new WebSocket(q)));let g=!1,h=null,b={state:"idle"};const k=new Set;let v=null,P=null,z=null,x=0,j=0,V=null,Z=[],B=!1;const W=q=>{if(!(b.state===q.state&&b.lastError===q.lastError&&b.terminal===q.terminal&&b.closeCode===q.closeCode)){b=q;for(const he of k)try{he(b)}catch{}}},_=q=>{const he=Z;Z=[];for(const J of he)J.reject(q)},te=q=>{const he=Z;Z=[];for(const J of he)J.resolve(q)},se=(q,he)=>{q.dead=!0;const J=Array.from(q.streams.values());q.streams.clear();for(const Q of J)try{Q.fail(he)}catch{}},Ve=()=>{V!==null&&(clearTimeout(V),V=null)},Hn=()=>{if(!g){if(V!==null){if(jc())return;Ve(),It(),Ba();return}jc()||na()}},na=()=>{g||h===null||(It(),h=null,Ba())},$=()=>{typeof document<"u"&&document.visibilityState==="visible"&&Hn()},ut=()=>{B||typeof window>"u"||(B=!0,window.addEventListener("online",Hn),typeof document<"u"&&document.addEventListener("visibilitychange",$))},It=()=>{!B||typeof window>"u"||(B=!1,window.removeEventListener("online",Hn),typeof document<"u"&&document.removeEventListener("visibilitychange",$))},Gn=()=>{if(g||V!==null)return;const q=Math.max(0,j-1),he=r*2**Math.min(q,10),J=jc()?p:l,Q=Math.min(J,he);ut(),V=setTimeout(()=>{V=null,It(),Ba()},Q)},Cc=()=>{const q=new URL(e.relayUrl);return q.searchParams.set("v",String(bo)),q.searchParams.set("role","client"),q.searchParams.set("serverId",e.serverId),q.searchParams.set("appId","openchamber"),q.searchParams.set("appVersion",xS),q.searchParams.set("platform",Af()),e.grant&&q.searchParams.set("grant",e.grant),q.toString()},Ba=async()=>{if(g)return;Ve(),x+=1;const q=x;W({state:j>0?"reconnecting":"connecting",lastError:b.lastError});let he;try{he=await AC(e.hostEncPubJwk,{batch:i,flowControl:e.flowControl})}catch(be){if(q!==x||g)return;qu(q,Ot(be),!0);return}if(q!==x||g)return;let J;try{J=u(Cc())}catch(be){qu(q,Ot(be));return}P=J;let Q=!1,ae=null,fe=null,gt=null,Ue=null,re=Promise.resolve(),le=null,De=null,cs=!1,Be=!1,Le=0,We=0,He=null,ls=null,Te=Date.now();const js=()=>{He!==null&&(clearTimeout(He),He=null),ae!==null&&(clearInterval(ae),ae=null),fe!==null&&(clearTimeout(fe),fe=null),gt!==null&&(clearInterval(gt),gt=null),Ue!==null&&(clearTimeout(Ue),Ue=null),ls!==null&&(ls.dispose(),ls=null)};z=js;function we(be,Re=!1,ye=null){if(!(Q||q!==x)){Q=!0,ye!==null&&(h=be),js(),le&&(v=null,se(le,new Error(`relay tunnel reset: ${be.message}`))),_(be);try{J.close()}catch{}if(P===J&&(P=null),!g){if(j+=1,ye!==null){ut(),W({state:"error",lastError:be.message,terminal:!0,closeCode:ye});return}W({state:Re?"error":"reconnecting",lastError:be.message}),Gn()}}}const _n=()=>{try{J.send(he.helloText)}catch{}},oa=(be,Re,ye)=>{De=be,cs=Re,Be=ye,ae!==null&&(clearInterval(ae),ae=null),fe!==null&&(clearTimeout(fe),fe=null);const mt=new Map,Ze=LC(),jt=OC();let ia=Promise.resolve();const Os=Kn=>{ia=ia.then(async()=>{if(ra.dead)return;const Jv=await be.encryptor.encrypt(Kn);ra.dead||J.send(Jv)}).catch(()=>{we(new Error("relay encrypt/send failed"))})},xc=Re?BC({windowMs:o,sendBatch:Os}):null;ls=xc;const ra={streams:mt,assembler:jt,nextStreamId:()=>Ze.next(),dead:!1,send(Kn){ra.dead||(xc?xc.enqueue(Kn):Os(Kn))}};le=ra,v=ra,j=0,Te=Date.now(),W({state:"connected"}),te(ra),gt=setInterval(()=>{Date.now()-Te<a||(ra.send(Dt(ce.Ping,0,Ai)),Ue===null&&(Ue=setTimeout(()=>{Ue=null,we(new Error("relay keepalive timeout"))},n)))},a)},yi=()=>{He!==null&&clearTimeout(He),He=null,!(!le||le.dead||Le===We)&&(We=Le,le.send(Dt(ce.DeliveryAck,0,zC(Le))))},Pc=(be,Re)=>{let ye;try{ye=RC(Re)}catch(jt){we(Ot(jt));return}if(ye.frameType===ce.DeliveryAck){we(new Error("unexpected downstream delivery acknowledgement"));return}if(Be&&ye.streamId!==0&&(Le+=Re.length,He===null&&(He=setTimeout(yi,10))),Te=Date.now(),Ue!==null&&(clearTimeout(Ue),Ue=null),ye.frameType===ce.Ping){be.send(Dt(ce.Pong,ye.streamId,Ai));return}if(ye.frameType===ce.Pong)return;let mt=ye.payload;if(ye.frameType===ce.WsText||ye.frameType===ce.WsBinary){let jt;try{jt=be.assembler.push(ye)}catch(ia){we(Ot(ia));return}if(jt===null)return;mt=jt}else if(ye.hasMoreFragments){we(new Error("unexpected fragmented tunnel frame"));return}const Ze=be.streams.get(ye.streamId);Ze&&Ze.handleFrame(ye.frameType,mt)};J.onopen=()=>{Q||q!==x||(_n(),ae=setInterval(_n,t))};const La=be=>{const Re=DS.has(be);we(new Error(NS[be]??`relay socket closed (code ${be})`),Re,Re?be:null)};J.onmessage=be=>{if(Q||q!==x)return;const Re=be.data;if(typeof Re=="string"){const mt=cC(Re);if(mt){La(mt.code);return}re=re.then(async()=>{if(Q||q!==x)return;const Ze=await he.handleText(Re);if(Ze.type==="established"){if(De)return;oa(Ze.channel,Ze.batch,Ze.flowControl)}else Ze.type==="fail"&&we(new Error(`relay handshake failed: ${Ze.reason}`))}).catch(Ze=>{we(Ot(Ze))});return}const ye=Re instanceof ArrayBuffer?new Uint8Array(Re):Re instanceof Uint8Array?Re:null;ye&&(re=re.then(async()=>{if(Q||q!==x)return;const mt=le,Ze=De;if(!mt||!Ze){we(new Error("encrypted frame before handshake completed"));return}let jt;try{jt=await Ze.decryptor.decrypt(ye)}catch(Os){we(Ot(Os));return}let ia;try{ia=cs?NC(jt):[jt]}catch(Os){we(Ot(Os));return}for(const Os of ia){if(Q||q!==x||mt.dead)return;Pc(mt,Os)}Be&&Le-We>=16*1024&&yi()}).catch(mt=>{we(Ot(mt))}))},J.onclose=be=>La(be.code),J.onerror=()=>{},fe=setTimeout(()=>{fe=null,we(new Error("relay handshake timeout"),!0)},s);function qu(be,Re,ye=!1){be!==x||g||(_(Re),j+=1,W({state:ye?"error":"reconnecting",lastError:Re.message}),Gn())}},rs=q=>g?Promise.reject(new Error("relay tunnel closed")):q?.aborted?Promise.reject(zi()):h?Promise.reject(h):v&&!v.dead?Promise.resolve(v):new Promise((he,J)=>{let Q=null;const ae={resolve(fe){Q&&q&&q.removeEventListener("abort",Q),he(fe)},reject(fe){Q&&q&&q.removeEventListener("abort",Q),J(fe)}};q&&(Q=()=>{Z=Z.filter(fe=>fe!==ae),J(zi())},q.addEventListener("abort",Q,{once:!0})),Z.push(ae)}),Sc=async(q,he)=>{const J=await KC(q,he),Q=J.signal;if(Q?.aborted)throw zi();const ae=await rs(Q),fe=ae.nextStreamId();return await new Promise((gt,Ue)=>{let re=!1,le=!1,De=null,cs=null;const Be=()=>{ae.streams.delete(fe),ae.assembler.dropStream(fe),cs&&Q&&Q.removeEventListener("abort",cs)},Le=Te=>{if(!le){if(le=!0,Be(),!re){Ue(Te);return}try{De?.error(Te)}catch{}}},We=Te=>{ae.dead||ae.send(Dt(ce.StreamAbort,fe,Si({reason:Te})))},He=Te=>Nl(new Error(Te));cs=()=>{We("aborted"),Le(zi())},ae.streams.set(fe,{handleFrame(Te,js){if(Te===ce.HttpResponse){if(re||le)return;let we;try{we=Pi(js,VC)}catch(La){We("malformed response head"),Le(He(Ot(La).message));return}const _n=we.status===204||we.status===205||we.status===304;let oa=null;_n||(oa=new ReadableStream({start(La){De=La},cancel(){le||(le=!0,Be(),We("response body cancelled"))}})),re=!0;const{[uC]:yi,...Pc}=we.headers;oa&&yi==="gzip"&&(oa=AS(oa)),gt(new Response(oa,{status:we.status,headers:Pc})),_n&&(le=!0,Be());return}if(Te===ce.HttpBody){if(!re||le)return;try{De?.enqueue(js)}catch{}return}if(Te===ce.StreamEnd){if(le)return;if(!re){Le(He("tunnel stream ended before response head"));return}le=!0,Be();try{De?.close()}catch{}return}if(Te===ce.StreamAbort){let we="stream aborted by host";try{we=Pi(js,Hu).reason}catch{}Le(He(we))}},fail(Te){Le(He(Te.message))}}),Q&&Q.addEventListener("abort",cs,{once:!0});const ls={method:J.method,path:J.path,query:J.query,headers:TS?{...J.headers,[pC]:"gzip"}:J.headers,hasBody:J.body!==null};ae.send(Dt(ce.HttpRequest,fe,Si(ls))),(async()=>{try{let Te=!1;if(J.body)for await(const js of J.body){if(le||ae.dead)return;for(const we of df(js))ae.send(Dt(ce.HttpBody,fe,we)),Te=!0}!le&&!ae.dead&&(J.body&&!Te&&ae.send(Dt(ce.HttpBody,fe,Ai)),ae.send(Dt(ce.StreamEnd,fe,Ai)))}catch(Te){We("request body failed"),Le(He(Ot(Te).message))}})()})},_v=q=>{const he=q.indexOf("?");return he===-1?{path:q,query:""}:{path:q.slice(0,he),query:q.slice(he+1)}},Kv=(q,he)=>{let J=Yu,Q=null,ae=0,fe=!1;const gt={get readyState(){return J},onopen:null,onmessage:null,onerror:null,onclose:null,send(re){if(J!==Ic||!Q||Q.dead)throw new Error("relay tunnel socket is not open");if(typeof re=="string"){for(const De of Wu(ce.WsText,ae,zS.encode(re)))Q.send(De);return}const le=re instanceof ArrayBuffer?new Uint8Array(re.slice(0)):(()=>{const De=new Uint8Array(re.byteLength);return De.set(new Uint8Array(re.buffer,re.byteOffset,re.byteLength)),De})();for(const De of Wu(ce.WsBinary,ae,le))Q.send(De)},close(re=1e3,le=""){J===eg||J===Xu||(J===Ic&&Q&&!Q.dead&&(J=Xu,Q.send(Dt(ce.WsClose,ae,Si({code:re,reason:le})))),Ue(re,le))}},Ue=(re,le,De=!1)=>{if(!fe){if(fe=!0,Q&&(Q.streams.delete(ae),Q.assembler.dropStream(ae)),J=eg,De)try{gt.onerror?.()}catch{}try{gt.onclose?.({code:re,reason:le})}catch{}}};return(async()=>{let re;try{re=await rs()}catch(Be){Ue(1006,Ot(Be).message,!0);return}if(fe)return;Q=re,ae=re.nextStreamId(),re.streams.set(ae,{handleFrame(Be,Le){if(Be===ce.WsOpened){if(J===Yu){J=Ic;try{gt.onopen?.()}catch{}}return}if(Be===ce.WsText){try{gt.onmessage?.({data:RS.decode(Le)})}catch{}return}if(Be===ce.WsBinary){const We=new ArrayBuffer(Le.byteLength);new Uint8Array(We).set(Le);try{gt.onmessage?.({data:We})}catch{}return}if(Be===ce.WsClose){let We=1e3,He="";try{const ls=Pi(Le,UC);We=ls.code,He=ls.reason}catch{}Ue(We,He);return}if(Be===ce.StreamAbort){let We="stream aborted";try{We=Pi(Le,Hu).reason}catch{}Ue(1006,We,!0)}},fail(Be){Ue(1012,Be.message,!0)}});const{path:le,query:De}=_v(q),cs=he&&he.length>0?{path:le,query:De,protocols:he}:{path:le,query:De};re.send(Dt(ce.WsOpen,ae,Si(cs)))})(),gt},Zv=()=>{if(g)return;g=!0,x+=1,Ve(),It(),z?.(),z=null;const q=v;v=null;const he=new Error("relay tunnel closed");q&&se(q,he),_(he);try{P?.close()}catch{}P=null,W({state:"idle"})};return Ba(),{fetch:Sc,openWebSocket:Kv,getStatus:()=>b,subscribeStatus(q){return k.add(q),()=>{k.delete(q)}},retry:na,close:Zv}};let as=null,ts=null;const Wl=new Set;let Oc=null;const mp=e=>{Oc?.(),Oc=null,as=e,e&&(Oc=e.subscribeStatus(t=>{for(const s of Wl)s(t)}))},_0=e=>(Wl.add(e),()=>{Wl.delete(e)}),FS=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),Dn=()=>as,K0=()=>!as||!ts?null:{relayUrl:ts.relayUrl,serverId:ts.serverId,hostEncPubJwk:{...ts.hostEncPubJwk}},ES=()=>as!==null,MS=e=>{if(as&&ts&&FS(ts,e))return as;as?.close(),ts=e;const t=gp(e);return mp(t),t},Z0=(e,t)=>{if(as===t){ts=e;return}as?.close(),ts=e,mp(t)},BS=()=>{as?.close(),mp(null),ts=null};let Rf=()=>null,If="",Pr={},wn="",Uo=0,fa=null,cn="",Wo=0,Aa="",ba=null,Vs="",ar=0,nr=0;const hp=1e4,LS=e=>e.toLowerCase()==="authorization",jf=e=>{const t={};for(const[s,a]of Object.entries(e||{})){const n=s.trim(),o=a.trim();n&&o&&!LS(n)&&(t[n]=o)}return t},qS=(e,t)=>{const s=Object.entries(e);return s.length!==Object.keys(t).length?!1:s.every(([a,n])=>t[a]===n)},Yr=e=>typeof e!="string"?"":e.trim(),VS=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return Yr(e)},US=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Of=(e,t)=>{const s=typeof e=="string"&&e.trim()?e.trim():US();if(!s)return t;try{return new URL(t,`${s.replace(/\/+$/,"")}/`).toString()}catch{return t}},fp=e=>{try{return new URL(e).origin}catch{return""}},Df=()=>{cn="",Wo=0,Aa="",ba=null,Vs="",ar+=1},ii=()=>{wn="",Uo=0,Df()},Nf=()=>{nr+=1,fa=null,ii(),kp()},Ff=e=>{const t=Yr(e);If=t,Nf(),Rf=()=>t?{type:"bearer",token:t}:null},Ef=e=>{const t=jf(e);qS(Pr,t)||(Pr=t,Nf())},Nn=()=>{if(Object.keys(Pr).length>0)return Pr;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?jf(e):{}},bp=()=>If||VS(),WS=(e,t)=>{const s=Yr(e);if(!s||typeof t!="number"||!Number.isFinite(t)){ii();return}wn=s,Uo=t},Mf=()=>!wn||Uo<=Date.now()+hp?(ii(),""):wn,Bf=e=>{const t=fp(e);return!t||Aa!==t?"":!cn||Wo<=Date.now()+hp?(cn="",Wo=0,Aa="",""):cn},HS=()=>{const e=Mf();return!e&&(bp()||typeof window<"u")&&Xr().catch(()=>{}),e},GS=e=>{const t=e?Bf(e):"";return!t&&e&&typeof window<"u"&&Uf(e).catch(()=>{}),t},Lf=async()=>{const e=await Rf(),t=e?.type==="bearer"?Yr(e.token):bp();return t?{type:"bearer",token:t}:null},_S=d({token:c(),expiresAt:w(),expiresIn:w().optional()}),qf=async(e,t)=>{const s=await Lf(),a=new Headers;for(const[g,h]of Object.entries(Nn()))a.set(g,h);s?.type==="bearer"&&a.set("Authorization",`Bearer ${s.token}`);const n=t?`/auth/url-token?scope=${encodeURIComponent(t)}`:"/auth/url-token",o=Dn(),i=o?await o.fetch(n,{method:"POST",headers:a}):await fetch(Of(e,n),{method:"POST",headers:a,credentials:"include"});if(!i.ok)throw new Error(`Failed to mint runtime URL auth token (${i.status})`);const r=_S.safeParse(await i.json().catch(()=>null));if(!r.success)return{token:"",expiresAt:0};const{token:l,expiresAt:p,expiresIn:u}=r.data;return{token:l.trim(),expiresAt:u===void 0?p:Date.now()+u}},J0=async e=>{const t=await qf(null,`guest:${e}`);if(!t.token)throw new Error("Guest URL auth token response was invalid");return t},Vf=e=>{if(fa)return fa;const t=nr,a=(async()=>{let n;try{n=await qf(e)}catch(o){throw t===nr&&ii(),o}if(t!==nr)throw new Error("Runtime URL auth token response is stale");if(WS(n.token,n.expiresAt),!wn)throw new Error("Runtime URL auth token response was invalid");return wn})().finally(()=>{fa===a&&(fa=null)});return fa=a,fa},KS=e=>{const t=fp(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(ba&&Vs===t)return ba;const s=ar,n=(async()=>{const o=await fetch(Of(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!o.ok)throw s===ar&&t===Vs&&(cn="",Wo=0,Aa=""),new Error(`Failed to mint local runtime URL auth token (${o.status})`);const i=await o.json().catch(()=>null),r=typeof i?.token=="string"?i.token.trim():"",l=typeof i?.expiresAt=="number"?i.expiresAt:0;if(!r||!Number.isFinite(l))throw new Error("Local runtime URL auth token response was invalid");if(s!==ar||t!==Vs)throw new Error("Local runtime URL auth token response is stale");return cn=r,Wo=l,Aa=t,r})().finally(()=>{ba===n&&(ba=null,Vs="")});return ba=n,Vs=t,ba},Xr=async e=>{const t=Mf();return t||Vf(e)},Uf=async e=>{const t=fp(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const s=Bf(t);return s||((Aa&&Aa!==t||Vs&&Vs!==t)&&Df(),KS(t))};let tn=0,wo=null,ZS=null;const JS=5e3,Wf=()=>{wo!==null&&(clearTimeout(wo),wo=null)},kp=()=>{if(Wf(),tn<=0||typeof window>"u")return;const e=Uo-hp-JS,t=Uo>0?Math.max(0,e-Date.now()):0;wo=setTimeout(()=>{wo=null,!(tn<=0)&&Vf(ZS).catch(()=>{}).finally(()=>{kp()})},t)},$0=e=>{tn+=1,kp();let t=!1;return()=>{t||(t=!0,tn=Math.max(0,tn-1),tn===0&&Wf())}},Hf=async e=>{const t=new Headers(e);for(const[a,n]of Object.entries(Nn()))t.has(a)||t.set(a,n);if(t.has("Authorization"))return t;const s=await Lf();return s?.type==="bearer"&&t.set("Authorization",`Bearer ${s.token}`),t},yn=Rt(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),Q0=e=>new Promise(t=>{if(e.aborted||yn.getState().state==="ok"){t();return}const s=()=>{a(),e.removeEventListener("abort",s),t()},a=yn.subscribe(n=>{n.state==="ok"&&s()});e.addEventListener("abort",s,{once:!0})}),$S=15e3,QS=5*6e4;let Hl=0,Dc=!1;const YS=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),XS=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?!1:!YS(t)},Gf=async()=>{if(!Dc){Dc=!0;try{const{runtimeFetch:e}=await Ge(async()=>{const{runtimeFetch:s}=await Promise.resolve().then(()=>bP);return{runtimeFetch:s}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){yn.getState().markExpired();return}if(t.ok){const{state:s,markAuthenticated:a}=yn.getState();s==="expired"&&a()}}catch{}finally{Dc=!1}}},eP=(e,t)=>{if(t!==401||yn.getState().state==="expired"||!XS(e))return;const s=Date.now();s-Hl<$S||(Hl=s,Gf())};let tg=!1;const Y0=()=>{if(tg)return;tg=!0;let e=Date.now();const t=()=>{if(yn.getState().state!=="ok")return;const s=Date.now();s-e<QS||(e=s,Hl=s,Gf())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},tP=/^\/spaces\/([0-9a-f]{12})(?:\/|$)/,zt=e=>{if(!e)return null;const t=tP.exec(e);return t?t[1]:null},Gl=e=>zt(e)!==null,sP=()=>pp()||On()?.runtime?.isVSCode===!0,aP=e=>!e||sP()||!Gl(e)?null:{"x-opencode-directory":encodeURIComponent(e),"x-opencode-directory-encoding":"uri"},_f=e=>`/spaces/${e}`,za=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",nP=()=>typeof window>"u"?"":window.location.origin||"",wp=e=>{if(typeof window>"u")return!1;const t=nP();if(t&&e.origin===t)return!0;try{const s=new URL(window.location.href||t);return e.protocol===s.protocol&&e.host===s.host}catch{return!1}},yp=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),oP=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),gs=(e,t)=>{try{oP(new URL(e).hostname)&&!t.has("ngrok-skip-browser-warning")&&t.set("ngrok-skip-browser-warning","openchamber")}catch{}return t},vp=(e,t)=>{if(!t)return;const s=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[a,n]of s)n!=null&&e.searchParams.set(a,String(n))},iP=e=>{if(!e)return!1;if(e instanceof Headers)return e.has("x-opencode-directory");const t=Array.isArray(e)?e:Object.entries(e);for(const[s]of t)if(s.toLowerCase()==="x-opencode-directory")return!0;return!1},rP=(e,t,s)=>{const a=aP(s);if(a===null||iP(t.headers)||e instanceof Request&&e.headers.has("x-opencode-directory"))return t;const n=t.headers?t.headers instanceof Headers?Array.from(t.headers.entries()):Array.isArray(t.headers)?t.headers:Object.entries(t.headers):[];return{...t,headers:[...n,...Object.entries(a)]}},cP=()=>{const e=vs().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return null;const t=new URL(e);return`${t.origin}${t.pathname.replace(/\/api$/,"")}`},lP=e=>{try{const t=cP();if(!t)return null;const s=new URL(t);if(e.origin!==s.origin)return null;const a=s.pathname.replace(/\/+$/,"");return a?e.pathname!==a&&!e.pathname.startsWith(`${a}/`)?null:e.pathname.slice(a.length)||"/":e.pathname}catch{return null}},or=e=>{const t=lP(e);return t!==null&&za(t)},Nc=e=>{if(za(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return wp(t)&&za(t.pathname)}catch{return!1}},dP=(e,t)=>{try{const s=new URL(e);if(!wp(s))return e;const a=Xs(`${s.pathname}${s.search}`,t);return!yp(a)&&(s.protocol==="http:"||s.protocol==="https:")?(vp(s,t),s.toString()):s.hash?`${a}${s.hash}`:a}catch{return e}},Xs=(e,t)=>e==="/health"?vs().health(t):e.startsWith("/auth/")||e==="/auth"?vs().auth(e,t):za(e)?vs().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?dP(e,t):e,Kf=e=>{const t=e instanceof Request?e.url:e.toString();if(!yp(t))return za(t);try{return or(new URL(t))}catch{return!1}},Zf=(e,t)=>Object.keys(Nn()).length>0&&Oa()&&Kf(e)?{...t,redirect:"error"}:t,Jf=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},pP=(e,t)=>!Jf(t),xr=e=>{if(!e)return;const t=e instanceof Headers?Array.from(e.entries()):Array.isArray(e)?e:Object.entries(e);if(t.length===0)return;const s=[];let a=!1,n=!1;for(const[o,i]of t)pP(o,i)?(s.push([o,encodeURIComponent(i)]),a=!0,o.toLowerCase()==="x-opencode-directory"&&(n=!0)):s.push([o,i]);return n&&s.push(["x-opencode-directory-encoding","uri"]),a?s:void 0},ms=async(e,t,s=!0)=>{const a=new Headers(xr(e)??e);return t&&new Headers(xr(t)??t).forEach((n,o)=>a.set(o,n)),s?Hf(a):a},uP=(e,t)=>{if(!t)return e;const s=new URL(e,cp);return vp(s,t),`${s.pathname}${s.search}`},$f=(e,t)=>{const s=e instanceof Request?e.url:e.toString();if(!yp(s))return za(s)?uP(s,t):null;try{const a=new URL(s);return!wp(a)||!za(a.pathname)?null:(vp(a,t),`${a.pathname}${a.search}`)}catch{return null}},gP=async(e,t,s)=>{const a=Dn();if(!a)return null;const n=$f(e,s);if(n===null)return null;const o=e instanceof Request?e.headers:void 0,i=await ms(o,t.headers,!0);return e instanceof Request?a.fetch(e,{...t,headers:i}):a.fetch(n,{...t,headers:i})},mP=(e,t)=>{if(typeof e=="string")return Xs(e,t);if(e instanceof URL)return Xs(e.toString(),t);const s=Xs(e.url,t);return s===e.url?e:new Request(s,e)},hP=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Ri=new Map,fP=(e,t,s,a)=>s||e!=="GET"||t.includes("/event")||!hP.test(t)?null:`GET ${t}\0${a.get("x-opencode-directory")??""}`,T=async(e,t={})=>{const{query:s,directory:a,...n}=t,o=e,i=rP(o,n,a),r=Dn(),l=r?$f(o,s):null;let p,u,g,h;if(r&&l!==null){const x=o instanceof Request?o.headers:void 0,j=await ms(x,i.headers,!0);p=o instanceof Request?()=>r.fetch(o,{...i,headers:j}):()=>r.fetch(l,{...i,headers:j}),h=j,u=l,g=String(i.method??(o instanceof Request?o.method:"GET")).toUpperCase()}else{const x=mP(o,s),j=x instanceof Request?x.headers:void 0,V=await ms(j,i.headers,Kf(x)),Z=x instanceof Request?x.url:x instanceof URL?x.toString():String(x);gs(Z,V);const B=Zf(x,{...i,headers:V});p=x instanceof Request?()=>fetch(new Request(x,B)):()=>fetch(x,B),h=V,u=Z,g=String(i.method??(x instanceof Request?x.method:"GET")).toUpperCase()}const b=p;p=()=>b().then(x=>(eP(u,x.status),x));const k=i.signal!=null||o instanceof Request,v=fP(g,u,k,h);if(!v)return p();const P=Ri.get(v);if(P)return P.then(x=>x.clone());const z=p();return Ri.set(v,z),z.then(()=>Ri.delete(v),()=>Ri.delete(v)),z.then(x=>x.clone())};let sg=!1,Qf=null;const Yf=(e,t)=>(Qf??globalThis.fetch.bind(globalThis))(e,t),Xf=()=>{if(sg||typeof window>"u")return;sg=!0;const e=window.fetch.bind(window);Qf=e;const t=(s,a)=>e(s,Zf(s,a));window.fetch=async(s,a)=>{const n=await gP(s,a??{});if(n)return n;if(typeof s=="string"){if(!Nc(s)){try{const r=new URL(s);if(or(r)){const l=await ms(void 0,a?.headers);return gs(r.toString(),l),t(s,{...a,headers:l})}}catch{}return t(s,a)}const o=await ms(void 0,a?.headers),i=Xs(s);return gs(i,o),t(i,{...a,headers:o})}if(s instanceof URL){const o=s.toString();if(!Nc(o)){if(or(s)){const l=await ms(void 0,a?.headers);return gs(s.toString(),l),t(s,{...a,headers:l})}return t(s,a)}const i=await ms(void 0,a?.headers),r=Xs(o);return gs(r,i),t(r,{...a,headers:i})}if(s instanceof Request){if(!Nc(s.url)){try{const l=new URL(s.url);if(or(l)){const p=await ms(s.headers,a?.headers);return gs(l.toString(),p),t(new Request(s,{...a,headers:p}))}}catch{}return t(s,a)}const o=await ms(s.headers,a?.headers),i=Xs(s.url);gs(i,o);const r=i===s.url?s:new Request(i,s);return t(new Request(r,{...a,headers:o}))}return t(s,a)}},bP=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:gs,buildRuntimeFetchUrl:Xs,fetchBypassingRuntimeBridge:Yf,installRuntimeFetchBridge:Xf,isLatin1Safe:Jf,runtimeFetch:T,sanitizeHeadersForBrowser:xr},Symbol.toStringTag,{value:"Module"})),ln=16384,Tr=globalThis,kP=e=>{if(Tr.Buffer)return Tr.Buffer.from(e,"utf8").toString("base64url");const t=new TextEncoder().encode(e);let s="";for(let a=0;a<t.length;a+=32768)s+=String.fromCharCode(...t.slice(a,a+32768));return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")},eb=e=>{try{if(Tr.Buffer)return Tr.Buffer.from(e,"base64url").toString("utf8");const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),s=atob(t),a=new Uint8Array(s.length);for(let n=0;n<s.length;n+=1)a[n]=s.charCodeAt(n);return new TextDecoder().decode(a)}catch{return null}},wP=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?null:(s.hash="",s.toString().replace(/\/+$/g,""))}catch{return null}},yP=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="ws:"&&s.protocol!=="wss:"?null:(s.hash="",s.toString())}catch{return null}},ag=e=>typeof e=="string"&&e.length>0,vP=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!ag(t.x)||!ag(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},CP=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,SP=e=>{if(!e||typeof e!="object")return null;const t=e,s=CP(t.priority);if(t.type==="lan"||t.type==="tunnel"){const a=wP(t.url);return a?s===void 0?{type:t.type,url:a}:{type:t.type,url:a,priority:s}:null}if(t.type==="relay"){const a=yP(t.relayUrl);if(!a)return null;const n=typeof t.serverId=="string"?t.serverId.trim():"";if(!n)return null;const o=vP(t.hostEncPubJwk);if(!o)return null;const i=typeof t.grant=="string"&&t.grant.trim()?t.grant.trim():void 0;return{type:"relay",relayUrl:a,serverId:n,hostEncPubJwk:o,...i?{grant:i}:{},...s===void 0?{}:{priority:s}}}return null},Cp=e=>{if(!e||typeof e!="object")return null;const t=e;if(t.v!==2)return null;const s=typeof t.pairingId=="string"?t.pairingId.trim():"",a=typeof t.secret=="string"?t.secret.trim():"";if(!s||!a)return null;const n=Array.isArray(t.candidates)?t.candidates.map(SP).filter(l=>!!l):[];if(n.length===0)return null;const o=typeof t.expiresAt=="string"&&t.expiresAt.trim()?t.expiresAt.trim():void 0;if(o){const l=Date.parse(o);if(!Number.isFinite(l)||l<=Date.now())return null}const i=typeof t.label=="string"&&t.label.trim()?t.label.trim():void 0,r=typeof t.fingerprint=="string"&&t.fingerprint.trim()?t.fingerprint.trim():void 0;return{v:2,pairingId:s,secret:a,...i?{label:i}:{},...r?{fingerprint:r}:{},...o?{expiresAt:o}:{},candidates:n}},X0=e=>({v:2,pairingId:e.pairingId.trim(),secret:e.secret.trim(),...e.label?.trim()?{label:e.label.trim()}:{},...e.fingerprint?.trim()?{fingerprint:e.fingerprint.trim()}:{},...e.expiresAt?.trim()?{expiresAt:e.expiresAt.trim()}:{},candidates:e.candidates}),eK=e=>{const t=Cp(e);if(!t)throw new Error("Invalid pairing connection payload");const s=new URLSearchParams;return s.set("v","2"),s.set("p",kP(JSON.stringify(t))),`openchamber://connect?${s.toString()}`},PP=e=>{const t=e.trim();if(!t||t.length>ln)return null;try{const s=new URL(t);if(s.protocol!=="openchamber:"||s.hostname!=="connect"||s.searchParams.get("v")!=="2")return null;const a=s.searchParams.get("p")||"";if(!a||a.length>ln)return null;const n=eb(a);return!n||n.length>ln?null:Cp(JSON.parse(n))}catch{return null}},tK=e=>{const t=e.trim();if(!t||t.length>ln)return null;const s=t.indexOf("?");if(s===-1||!/^openchamber:\/\/connect\/?$/i.test(t.slice(0,s)))return null;let a=null,n=null;for(const i of t.slice(s+1).split("&")){const r=i.indexOf("=");if(r===-1)continue;const l=i.slice(0,r),p=i.slice(r+1);l==="v"?a=p:l==="p"&&(n=p)}if(a!=="2"||!n||n.length>ln)return null;const o=eb(n);if(!o||o.length>ln)return null;try{return Cp(JSON.parse(o))}catch{return null}},vn=e=>typeof e=="object"&&e!==null,xP=e=>e.trim().toLowerCase()==="authorization",TP=e=>{if(!vn(e))return;const t={};for(const[s,a]of Object.entries(e)){const n=s.trim(),o=typeof a=="string"?a.trim():"";!n||!o||/[\r\n:]/.test(n)||/[\r\n]/.test(o)||xP(n)||(t[n]=o)}return Object.keys(t).length>0?t:void 0},AP=e=>`relay://${e}`,zP=e=>{if(!vn(e))return null;const t=Ye(e,"relayUrl")||Ye(e,"relay_url"),s=Ye(e,"serverId")||Ye(e,"server_id"),a=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!s||!vn(a)?null:{relayUrl:t,serverId:s,hostEncPubJwk:a}},RP=()=>{if(typeof navigator>"u")return;const e=navigator.userAgent;if(/Macintosh|Mac OS X/i.test(e))return"macos";if(/Windows/i.test(e))return"windows";if(/Linux/i.test(e))return"linux"},ng=15e3,sK=async(e,t)=>{const s=PP(e);if(!s)throw new Error("invalid-connect-link");const a=await NP().catch(()=>""),n={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({pairingId:s.pairingId,secret:s.secret,clientLabel:s.label||"OpenChamber Desktop",clientKind:"desktop",deviceName:"OpenChamber Desktop",devicePlatform:RP(),...a?{dedupeKey:`desktop:${a}`}:{}})},o=async P=>{if(!P.ok)return null;const z=await P.json().catch(()=>null);return(typeof z?.clientToken=="string"?z.clientToken.trim():"")||null};let i=null;const r=[...s.candidates].sort((P,z)=>(P.type==="relay"?1:0)-(z.type==="relay"?1:0));for(const P of r){if(P.type==="relay"){const x=gp({relayUrl:P.relayUrl,serverId:P.serverId,hostEncPubJwk:P.hostEncPubJwk,...P.grant?{grant:P.grant}:{}});try{const j=await o(await x.fetch("/api/client-auth/pairing/redeem",{...n,signal:AbortSignal.timeout(ng)}));if(j){i={relay:{relayUrl:P.relayUrl,serverId:P.serverId,hostEncPubJwk:P.hostEncPubJwk},token:j};break}}catch{}finally{x.close()}continue}const z=Ke(P.url);if(z)try{const x=await o(await fetch(`${z}/api/client-auth/pairing/redeem`,{...n,signal:AbortSignal.timeout(ng)}));if(x){i={directUrl:z,token:x};break}}catch{}}if(!i)throw new Error("pairing-redeem-failed");const l=s.candidates.find(P=>P.type==="relay"),p=i.relay||(l?{relayUrl:l.relayUrl,serverId:l.serverId,hostEncPubJwk:l.hostEncPubJwk}:void 0),u=s.candidates.filter(P=>P.type!=="relay").map(P=>Ke(P.url)).find(P=>!!P),g=i.directUrl||u,h=g||(p?AP(p.serverId):null);if(!h)throw new Error("pairing-missing-transport");const b=t.find(P=>p?P.relay?.serverId===p.serverId:!P.relay&&Ke(P.apiUrl||P.url)===h),k=b?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),v={...b||{},id:k,label:s.label||b?.label||tb(h),url:h,apiUrl:g,clientToken:i.token,...p?{relay:p}:{}};return{hostId:k,hosts:b?t.map(P=>P.id===k?v:P):[v,...t]}},IP=/^(t|.*(?:token|auth|secret|api).*)$/i,Ke=e=>{const t=e.trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?null:t.split("#")[0]||null}catch{return null}},aK=e=>{const t=Ke(e);if(!t)return null;try{const s=new URL(t);if((s.pathname.replace(/\/+$/,"")||"/")==="/connect"&&s.searchParams.has("t"))return{persistedUrl:s.origin,redeemUrl:s.toString(),kind:"tunnel-connect-link"}}catch{return null}return{persistedUrl:t,redeemUrl:null,kind:"normal-host"}},tb=e=>{const t=Ke(e);if(!t)return e;try{const s=new URL(t);(s.username||s.password)&&(s.username="",s.password="");const a=Array.from(new Set(Array.from(s.searchParams.keys())));for(const n of a)IP.test(n)&&s.searchParams.set(n,"[REDACTED]");return s.toString()}catch{return t}},Ii=(e,t)=>{const s=Ke(e),a=Ke(t);if(!s||!a)return!1;try{const n=new URL(s),o=new URL(a);if(n.origin!==o.origin||o.search&&n.search!==o.search)return!1;const i=o.pathname.length>1?o.pathname.replace(/\/+$/,""):o.pathname,r=n.pathname.length>1?n.pathname.replace(/\/+$/,""):n.pathname;return i==="/"?!0:r===i||r.startsWith(`${i}/`)}catch{return!1}},Ye=(e,t)=>{const s=e[t];return typeof s=="string"?s:null},og=(e,t)=>{const s=e[t];return typeof s=="number"&&Number.isFinite(s)?s:null},jP=e=>{if(!vn(e))return null;const t=Ye(e,"id"),s=Ye(e,"label"),a=Ye(e,"url"),n=Ye(e,"apiUrl")||Ye(e,"api_url"),o=Ye(e,"clientToken")||Ye(e,"client_token"),i=TP(e.requestHeaders),r=zP(e.relay);if(!t||!s||!a)return null;const l={id:t,label:s,url:a,...n?{apiUrl:n}:{},...o?{clientToken:o}:{},...i?{requestHeaders:i}:{},...r?{relay:r}:{}};return e.sshForwarded===!0&&(l.sshForwarded=!0),l},dn=e=>Ke(e.apiUrl||e.url)||e.apiUrl||e.url,Rs=()=>rt()?(e,t)=>oe(e,t):null,Ho=async()=>{const e=Rs();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!vn(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const s=t.hosts,a=Array.isArray(s)?s.map(jP).filter(r=>!!r):[],n=Ye(t,"defaultHostId")||Ye(t,"default_host_id")||Ye(t,"defaultHostID"),o=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,i=Ye(t,"localOrigin")||Ye(t,"local_origin");return{hosts:a,defaultHostId:n,initialHostChoiceCompleted:o,localOrigin:i}},OP=async e=>{const t=Rs();if(!t)return;const s={hosts:e.hosts,defaultHostId:e.defaultHostId,initialHostChoiceCompleted:e.initialHostChoiceCompleted};e.localClientToken!==void 0&&(s.localClientToken=e.localClientToken),await t("desktop_hosts_set",{input:s})},DP=async()=>{const e=Rs();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},nK=async()=>{const e=Rs();return e?await e("desktop_switch_to_local").catch(()=>!1)===!0:!1},NP=async()=>{const e=Rs();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},FP=8e3,EP=15e3,MP=400,BP=async(e,t,s,a)=>{const n=new AbortController,o=window.setTimeout(()=>n.abort(),s);try{return await e.fetch(t,{...a,signal:n.signal})}finally{window.clearTimeout(o)}},ig=async(e,t,s,a)=>{for(;;){const n=s-Date.now();if(n<=0)throw new Error("relay probe deadline exceeded");try{return await BP(e,t,Math.min(FP,n),a)}catch(o){if(e.getStatus().state==="error"||Date.now()>=s)throw o;await new Promise(i=>window.setTimeout(i,MP))}}},LP=async(e,t)=>{const s=gp({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),a=Date.now()+EP;let n=!1;try{if(!(await ig(s,"/health",a)).ok)return{status:"unreachable",latencyMs:0};const i=Date.now(),r=new Headers({Accept:"application/json"});for(const[u,g]of Object.entries(t?.requestHeaders||{}))u.toLowerCase()!=="authorization"&&r.set(u,g);const l=t?.clientToken?.trim();l&&r.set("Authorization",`Bearer ${l}`);const p=await ig(s,"/auth/session",a,{headers:r});return p.status===401||p.status===403?{status:"auth",latencyMs:Math.max(0,Date.now()-i)}:p.ok?(n=t?.keepTunnel===!0,{status:"ok",latencyMs:Math.max(0,Date.now()-i),...n?{tunnel:s}:{}}):{status:"unreachable",latencyMs:0}}catch{return{status:OS(s.getStatus())?"relay-limit":"unreachable",latencyMs:0}}finally{n||s.close()}},ec=async(e,t)=>{const s=Rs();if(!s)return{status:"unreachable",latencyMs:0};const a=await s("desktop_host_probe",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0,expectedServerId:t?.expectedServerId||void 0});if(!vn(a))return{status:"unreachable",latencyMs:0};const n=a.status,o=n==="ok"||n==="auth"||n==="update-recommended"||n==="incompatible"||n==="wrong-service"||n==="unreachable"?n:"unreachable",i=og(a,"latencyMs")??og(a,"latency_ms")??0;return{status:o,latencyMs:i}},qP=X("status",[d({status:m("started")}),d({status:m("auth")}),d({status:m("failed"),error:c().nullable()})]),oK=async e=>{const t=Rs();if(!t)return{status:"failed",error:null};const s=await t("desktop_host_update_server",{hostId:e}).catch(()=>null),a=qP.safeParse(s);return a.success?a.data:{status:"failed",error:null}},VP=600*1e3,UP=3e3,iK=async(e,{maxWaitMs:t=VP,intervalMs:s=UP,readHosts:a=Ho,probe:n=ec}={})=>{const o=Date.now()+t;for(;Date.now()<o;){await new Promise(l=>setTimeout(l,Math.min(s,Math.max(0,o-Date.now()))));const i=(await a()).hosts.find(l=>l.id===e);if(!i)return"timeout";const r=await n(dn(i),{clientToken:i.clientToken,requestHeaders:i.requestHeaders});if(r.status==="ok"||r.status==="update-recommended"||r.status==="auth")return"updated"}return"timeout"},rK=async(e,t)=>{const s=Rs();s&&await s("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},cK=async e=>{const t=Rs();t&&await t("desktop_new_window_for_host",{hostId:e})},$s="local",WP=()=>typeof window>"u"?"":window.__OPENCHAMBER_LOCAL_ORIGIN__?.trim()||"",HP=(e,t)=>t?[{id:$s,label:"Local",url:t},...e]:e,GP=e=>e.id===$s?"local":`host:${e.id}`,lK=e=>{const t=typeof window>"u"?"":window.location.href,s=e.find(h=>h.id===$s)?.url||WP(),a=ns(),n=Ke(s)||s,o=Ke(t)||t,i=N(),r=e.find(h=>h.relay&&GP(h)===i);if(r)return{id:r.id,label:r.label,url:r.url};if(a&&Ii(a,s))return{id:$s,label:"Local",url:n};const l=e.find(h=>a?Ii(a,dn(h)):!1);if(l)return{id:l.id,label:l.label,url:Ke(dn(l))||dn(l)};if(t&&Ii(t,s))return{id:$s,label:"Local",url:n};const p=e.find(h=>t?Ii(t,h.url):!1);if(p)return{id:p.id,label:p.label,url:Ke(p.url)||p.url};const u=t.startsWith("openchamber-ui://");if(u&&s&&!a)return{id:$s,label:"Local",url:n};const g=a?Ke(a)||a:u?"":o;return{id:"custom",label:tb(g||"Instance"),url:g}},Ar=new Map;let sb=0;const yo=new Map,pn=new Set;let _l=0,ab={byHostId:{},isProbing:!1};const Kl=new Set,zr=()=>{ab={byHostId:Object.fromEntries(Ar),isProbing:_l>0};for(const e of Kl)try{e()}catch{}},dK=e=>(Kl.add(e),()=>{Kl.delete(e)}),pK=()=>ab,nb=(e,t)=>{Ar.set(e,t),zr()},uK=(e,t)=>{yo.set(e,++sb),pn.delete(e),nb(e,t)},gK=e=>pn.has(e),_P=e=>{const t=new Set([$s,...e]);let s=!1;for(const a of Array.from(Ar.keys()))t.has(a)||(Ar.delete(a),yo.delete(a),pn.delete(a),s=!0);s&&zr()},KP=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",ZP=async()=>ja()?DP().catch(()=>""):"",JP=async(e,t)=>{const s=e.id===$s?t:e.clientToken||"",a=async()=>{const i=await LP(e.relay,{clientToken:s,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0})),r={status:i.status,latencyMs:i.latencyMs};return i.status==="ok"&&(r.via="relay"),r};if(e.relay&&!e.apiUrl)return a();const n=Ke(ja()?dn(e):e.url);if(!n)return{status:"unreachable",latencyMs:0};const o=await ec(n,{clientToken:s||null,requestHeaders:e.requestHeaders||null,expectedServerId:e.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0}));if(KP(o.status)&&e.relay){const i=await a();if(i.status==="ok"||i.status==="relay-limit")return i}return{status:o.status,latencyMs:o.latencyMs}},$P=async e=>{if(!ot())return;const t=++sb;for(const s of e)yo.set(s.id,t),pn.add(s.id);_l+=1,zr();try{const s=await ZP();await Promise.all(e.map(async a=>{const n=await JP(a,s);yo.get(a.id)===t&&(pn.delete(a.id),nb(a.id,n))}))}finally{for(const s of e)yo.get(s.id)===t&&pn.delete(s.id);_l-=1,zr()}};let rg=!1;const QP=async()=>{if(rg||!ot())return;rg=!0;const e=await Ho().catch(()=>null);e&&(_P(e.hosts.map(t=>t.id)),await $P(HP(e.hosts,e.localOrigin)))},YP=5e3,XP=1500;let Fc=!1;const Ec=e=>{const t=String(e??"").trim();if(!t)return null;try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?null:(s.hash="",s.toString())}catch{return null}},ex=async e=>{if(!ja()||Fc)return;const t=`host:${e}`;if(N()===t){Fc=!0;try{const s=await Ho().catch(()=>null),a=s?.hosts.find(k=>k.id===e);if(!s||!a?.relay)return;const n=a.apiUrl?Ke(a.apiUrl):null;if(n&&n.startsWith("https://"))return;const o=await T("/api/client-auth/connection/candidates").catch(()=>null);if(!o?.ok)return;const i=await o.json().catch(()=>null);if(!i||i.serverId!==a.relay.serverId)return;const r=Array.isArray(i.candidates)?i.candidates:[],l=[];for(const k of r){if(!k||typeof k!="object")continue;const v=k;if(v.type!=="lan"||typeof v.url!="string")continue;const P=Ke(v.url);P&&!l.includes(P)&&l.push(P)}if(l.length===0)return;const p=n&&l.includes(n)?n:l[0],u=Ec(p);u&&u!==Ec(n)&&await OP({hosts:s.hosts.map(k=>k.id===e?{...k,apiUrl:p}:k),defaultHostId:s.defaultHostId,initialHostChoiceCompleted:s.initialHostChoiceCompleted}).catch(()=>{});const h=(await Ho().catch(()=>null))?.hosts.find(k=>k.id===e)??null;if(!h||!u||Ec(h.apiUrl)!==u)return;const b=await ec(p,{clientToken:a.clientToken||null,requestHeaders:a.requestHeaders||null,expectedServerId:a.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(b.status==="unreachable"||b.status==="wrong-service"||b.status==="incompatible"||N()!==t)return;Vl({apiBaseUrl:p,clientToken:a.clientToken||null,requestHeaders:a.requestHeaders||null,runtimeKey:t})}finally{Fc=!1}}},tx=e=>{typeof window>"u"||window.setTimeout(()=>{ex(e).catch(()=>{})},YP)},cg=async(e,t)=>{if(!ja())return;const s=await Ho().catch(()=>null);if(!s)return;const a=e||(s.defaultHostId!=="local"?s.defaultHostId:null);if(!a)return;const n=s.hosts.find(h=>h.id===a);if(!n?.relay)return;const o=`host:${n.id}`;if(N()===o&&!t?.reconnectActive)return;const i=h=>{Vl({apiBaseUrl:h,clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,runtimeKey:o})},r=()=>{Vl({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:n.clientToken||null,runtimeKey:o,relay:n.relay??void 0}),tx(n.id)},l=n.apiUrl?Ke(dn(n)):null;if(!l){r();return}const p=h=>h.status!=="unreachable"&&h.status!=="wrong-service"&&h.status!=="incompatible",u=ec(l,{clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,expectedServerId:n.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0})),g=await Promise.race([u,new Promise(h=>setTimeout(()=>h(null),XP))]);if(g){if(p(g)){i(l);return}r();return}r(),u.then(h=>{p(h)&&N()===o&&i(l)})};class lg extends Error{constructor(t,s){super(`Agent '${t}' is not available in ${s??"the session's folder"}`),this.agent=t,this.directory=s,this.name="AgentUnavailableError"}agent;directory}const sx=e=>e!==void 0&&"tag"in e&&e.tag==="LocationNotFoundError";class Mt extends Error{reason;status;maxBytes;constructor(t,s={}){super(t),this.name="FilesystemError",this.reason=s.reason??"unknown",this.status=s.status,this.maxBytes=s.maxBytes}}const ax=e=>e instanceof Mt||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),vo=e=>{switch(e){case"os-permission":case"already-exists":case"not-found":case"not-directory":case"too-large":case"outside-workspace":case"invalid-response":return e;default:return"unknown"}},nx=d({message:c()}),mK=e=>{if(ax(e)&&e.reason==="not-found")return!0;const t=nx.safeParse(e),a=(e instanceof Error?e.message:t.success?t.data.message:String(e??"")).toLowerCase();return a.includes("file not found")||a.includes("enoent")||a.includes("no such file")||a.includes("does not exist")},ca=new Map;let Mc;async function dg(e){const t=vs().api("/api").replace(/\/api\/?$/,""),s=Dn(),a=await Hf();if(N()!==e)throw new Error("Runtime changed while preparing cleanup");return{fetch:async(o,i)=>{const r=o instanceof Request?o.url:String(o),l=r.startsWith("/")?`${t}${r}`:r,p=new Headers(o instanceof Request?o.headers:void 0);return new Headers(xr(i?.headers)??i?.headers).forEach((u,g)=>p.set(g,u)),a.forEach((u,g)=>p.set(g,u)),s?s.fetch(o,{...i,headers:p}):(gs(l,p),Yf(o instanceof Request?new Request(l,o):l,{...i,headers:p}))},baseUrl:t}}async function ob(e){const t=!!ns()&&!Dn(),s=await dg(e);return async a=>{let n=!1;const o=async()=>{if(!n){n=!0;try{const r=N()===e;if(!t&&!r)return;await a(r?await dg(e):s),ca.get(e)?.delete(o),ca.get(e)?.size===0&&ca.delete(e),ca.size===0&&(Mc?.(),Mc=void 0)}catch{}finally{n=!1}}},i=ca.get(e)??new Set;i.add(o),ca.set(e,i),Mc??=$r(({runtimeKey:r})=>{for(const l of ca.get(r)??[])l()}),await o()}}const Rr=()=>({active:0,waiters:[],activeSessionWaiters:[]});let Us=Rr(),Ca=Rr();const ox=3,pg=2;Jr(({runtimeKey:e,previousRuntimeKey:t})=>{if(e===t)return;const s=[Us,Ca];Us=Rr(),Ca=Rr();for(const a of s){for(const n of[...a.activeSessionWaiters,...a.waiters])n(!1);a.activeSessionWaiters.length=0,a.waiters.length=0}});const ug=()=>{for(;Us.active+Ca.active<ox;){const e=Ca.active<pg&&Ca.waiters.length>0?Ca:Us.active<pg&&(Us.activeSessionWaiters.length>0||Us.waiters.length>0)?Us:null;if(!e)return;const t=e.activeSessionWaiters.shift()??e.waiters.shift();if(!t)return;e.active+=1,t(!0)}};async function ib(e,t,s){const a=sr();if(await new Promise(o=>{s==="active-session"?e.activeSessionWaiters.push(o):e.waiters.push(o),ug()}))try{if(!a())return;const o=await t();return a()?o:void 0}finally{e.active-=1,ug()}}const ix=(e,t="normal")=>ib(Us,e,t),hK=e=>ib(Ca,e,"normal"),rb="/api/opencode/trust",rx="opencode_trust_required",cx=d({kind:S(["plugin","package","mcp","lsp","formatter","shell","config"]),source:c(),name:c(),detail:c()}),lx=d({directory:c(),trusted:y(),fingerprint:c().nullable(),items:C(cx)}),dx=d({code:m(rx),directory:c()});let Pa=null;const Zl=new Set,ro=new Map,Go=new Set,Cs=new Map;let Jl=Promise.resolve(),Ws=0;const un=()=>{for(const e of Zl)e()},fK=()=>Pa,bK=e=>(Zl.add(e),()=>{Zl.delete(e)}),kK=e=>Pa?Pa.settle(e):Promise.resolve("skipped");Jr(()=>{Ws+=1,Pa?.settle("skip"),ro.clear(),Go.clear(),Cs.clear(),Jl=Promise.resolve(),un()});const wK=e=>e?Cs.has(e):!1,cb=(e,t)=>{Cs.set(e,e);for(const s of t)Cs.set(s,e)},_o=e=>{const t=Cs.get(e);if(t!==void 0){for(const[s,a]of Cs)a===t&&Cs.delete(s);un()}},px=()=>{Go.clear()},ux=async e=>{if(e.status!==403)return null;try{const t=dx.safeParse(await e.clone().json());return t.success?t.data.directory:null}catch{return null}},lb=async e=>lx.parse(await e.json()),ir=async e=>{const t=await T(rb,{query:{directory:e}});if(!t.ok)throw new Error(`Folder trust check answered ${t.status}`);return lb(t)},gx=async e=>{const t=await T(rb,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({directory:e.directory,fingerprint:e.fingerprint})});if(t.status===409)return{kind:"changed",assessment:await lb(t)};if(!t.ok)throw new Error(`Saving folder trust answered ${t.status}`);return{kind:"trusted"}},mx=(e,t,s)=>new Promise(a=>{const n=o=>{if(t!==Ws){a(!1);return}Pa={directory:o.directory,items:o.items,settle:async i=>{if(i==="skip")return Go.add(`${o.directory}
3
3
  ${o.fingerprint}`),cb(o.directory,s),Pa=null,un(),a(!1),"skipped";let r;try{r=await gx(o)}catch(l){return console.warn("[opencode-trust] Failed to save the answer:",l),"failed"}return t!==Ws?"skipped":r.kind==="changed"?(n(r.assessment),"changed"):(Pa=null,_o(o.directory),un(),a(!0),"saved")}},un()};n(e)}),hx=(e,{deliberate:t,background:s=!1,throwOnError:a=!1,alias:n})=>{const o=g=>a?g:g.catch(h=>(console.warn("[opencode-trust] Could not check the folder:",h),!1)),i=ro.get(e);if(i)return n&&i.spellings.add(n),o(i.request);const r=new Set([e,...n?[n]:[]]),l=g=>(Cs.has(g)&&[...r].some(h=>!Cs.has(h))&&(cb(g,r),un()),!1),p=Ws,u=(async()=>{const g=await(s?ix(()=>p===Ws?ir(e):Promise.resolve(null)):ir(e));if(!g||p!==Ws)return!1;if(g.trusted)return _o(g.directory),!0;if(!t&&Go.has(`${g.directory}
4
4
  ${g.fingerprint}`))return l(g.directory);const h=Jl.then(async()=>{if(p!==Ws)return!1;const b=await ir(e);return p!==Ws?!1:b.trusted?(_o(b.directory),!0):!t&&Go.has(`${b.directory}
5
5
  ${b.fingerprint}`)?l(b.directory):mx(b,p,r)});return Jl=h.catch(()=>{}),h})().finally(()=>{ro.get(e)?.request===u&&ro.delete(e)});return ro.set(e,{request:u,spellings:r}),o(u)},yK=async e=>{try{const t=await ir(e);return t.trusted&&_o(t.directory),!t.trusted}catch{return!1}},fx=/\/api\/(?:session|(?:experimental\/)?session\/[^/]+\/(?:prompt|command|shell|skill|move))$/,bx=(e,t)=>e==="POST"&&fx.test(t.replace(/\/+$/,"")),ge="/api/openchamber/spaces",Fn=c().regex(/^[0-9a-f]{12}$/),Sp=d({title:c().min(1).max(120),by:S(["user","agent"])}),Da=d({code:c(),message:c()}),Co=d({count:w().int().min(0),paths:C(c())}),kx=d({path:c().optional(),other:c().nullable().optional(),branch:c().optional(),stillThere:Co.optional(),ignoredInTheWay:Co.optional(),filteredInTheWay:Co.optional(),tooLarge:C(c()).optional(),failed:w().int().min(0).optional()});class Bc extends Error{code;status;details;constructor(t,s,a,n={}){super(s),this.name="SpacesRequestError",this.code=t,this.status=a,this.details=n}}const wx=d({id:Fn,name:c(),state:c()}),yx=X("enabled",[d({enabled:m(!1)}),d({enabled:m(!0),spaces:C(wx).nullable(),failure:Da.optional()})]),vx=d({id:Fn,name:c(),code:c(),message:c()}),Cx=d({enabled:y(),stopped:C(d({id:Fn,name:c()})),stillRunning:C(vx),unknown:Da.optional()}),db=d({mode:S(["allowlist","open"]),domains:C(c())}),pb=X("kind",[d({kind:m("model"),id:c(),provider:c(),upstream:c(),source:X("kind",[d({kind:m("typed")}),d({kind:m("env"),name:c()})]),url:c()}),d({kind:m("login"),id:c(),provider:c(),method:c(),url:c()}),d({kind:m("custom"),id:c(),provider:c(),url:c()}),d({kind:m("domain"),id:c(),upstream:c(),url:c()})]),vK=(e,t)=>e.find(s=>(s.kind==="model"||s.kind==="login"||s.kind==="custom")&&s.provider===t),Sx=["checking_place","creating","downloading_image","preparing_tools","setting_network","bringing_code","giving_access","ready"],Px=S(Sx),ub=X("state",[d({state:m("queued"),total:w().int().min(1)}),d({state:m("running"),index:w().int().min(0),total:w().int().min(1),command:c()}),d({state:m("done"),total:w().int().min(1)}),d({state:m("failed"),index:w().int().min(0),total:w().int().min(1),command:c(),exitCode:w().int().nullable(),timedOut:y(),startedAt:c().nullable().default(null),finishedAt:c().nullable().default(null)}),d({state:m("interrupted"),total:w().int().min(1)})]),Na=d({id:Fn,name:c(),taskTitle:Sp.nullish(),placeId:c(),machine:c().nullable().default(null),projectDirectory:c().nullable(),directory:c().nullable(),projectFolder:d({path:c().nullable(),found:y().nullable()}).default({path:null,found:null}),state:S(["preparing","running","exited","missing","failed","unreachable"]),stoppedIdle:y().default(!1),step:M([Px,m("failed")]).nullable(),failure:Da.nullable(),network:db.nullable(),grants:C(pb),access:S(["granted","needs_access","unknown"]).nullable(),needsAccess:C(c()),accessFailures:C(d({provider:c(),code:c(),message:c()})).default([]),damage:S(["repairable","gatekeeper_gone"]).nullable().default(null),setup:ub.nullable().default(null)}),gb=["install_all","install_cli","start_colima","start_desktop"],xx=[...gb,"get_brew","linux_install","linux_start","permission","windows_install","windows_start"],Pp=d({action:S(gb),running:y(),failure:Da.extend({output:c().default("")}).nullable()}),gg=d({remedy:S(xx).nullable().catch(null),job:Pp.nullable(),memory:d({bytes:w().min(0),engine:S(["colima","docker_desktop","other"]).catch("other"),low:y()}).nullable()}).nullable().default(null),mb=M([d({id:c(),machine:c().nullable().default(null),available:m(!0),hostIsolation:y(),version:c().default(""),setup:gg}),d({id:c(),machine:c().nullable().default(null),available:m(!1),code:c(),message:c(),setup:gg})]),CK="docker-ssh",Tx=d({provider:c(),method:c(),expires:c().nullable(),state:S(["usable","expired","unsupported"])}),Ax=d({id:c(),name:c(),package:c(),baseURL:c().nullable(),loopback:y(),models:C(c()),hasKey:y(),supported:y()}),zx=d({code:c(),message:c(),details:kx.nullable().optional().catch(null)}),me=async(e,t,s={})=>{const a=await T(e,{...s,headers:s.body===void 0?s.headers:{"Content-Type":"application/json",...s.headers}}),n=await a.json().catch(()=>null);if(!a.ok){const i=zx.safeParse(n);throw i.success?new Bc(i.data.code,i.data.message,a.status,i.data.details??{}):new Bc("space_request_failed",`The server answered ${a.status}.`,a.status)}const o=t.safeParse(n);if(!o.success)throw new Bc("space_answer_malformed","The server answered in a shape this version does not know.",a.status);return o.data},Rx=e=>e.enabled?e.spaces!==null?{enabled:!0,spaces:e.spaces}:{enabled:!0,spaces:null,failure:e.failure??{code:"space_journey_failed",message:""}}:{enabled:!1},SK=async e=>Rx(await me(`${ge}/switch`,yx,{signal:e})),PK=e=>me(`${ge}/switch`,Cx,{method:"PUT",body:JSON.stringify({enabled:e})}),xK=async e=>(await me(`${ge}/places`,d({places:C(mb)}),{signal:e})).places,TK=async e=>(await me(`${ge}/machine`,d({place:mb.nullable()}),{method:"PUT",body:JSON.stringify({machine:e})})).place,xp=d({imageBytes:w().min(0).nullable(),imagePulling:y().default(!1),imageFailure:Da.nullable().default(null),toolsBytes:w().min(0),spacesBytes:w().min(0),bytesBySpace:ke(c(),w().min(0)).default({}),freeBytes:w().min(0),freesImage:y()}),Ix=d({freedBytes:w().min(0),kept:C(d({kind:c(),reason:S(["in_use","failed"])})),disk:xp}),AK=(e,t)=>me(`${ge}/places/${encodeURIComponent(e)}/disk`,xp,{signal:t}),zK=e=>me(`${ge}/places/${encodeURIComponent(e)}/clean-up`,Ix,{method:"POST"}),RK=async e=>(await me(`${ge}/places/local/setup`,d({job:Pp.nullable()}),{signal:e})).job,IK=async e=>(await me(`${ge}/places/local/setup`,d({job:Pp.nullable()}),{method:"POST",body:JSON.stringify({action:e})})).job,jK=e=>me(`${ge}/places/${encodeURIComponent(e)}/image`,xp,{method:"POST"}),jx=async e=>(await me(ge,d({spaces:C(Na)}),{signal:e})).spaces,OK=e=>me(ge,Na,{method:"POST",body:JSON.stringify(e)}),DK=async e=>(await me(`${ge}/logins`,d({logins:C(Tx)}),{signal:e})).logins,Ox=async(e,t)=>(await me(`${ge}/custom-providers?directory=${encodeURIComponent(e)}`,d({providers:C(Ax)}),{signal:t})).providers,NK=async(e,t)=>(await me(`${ge}/${e}/grants`,d({grant:pb}),{method:"POST",body:JSON.stringify(t)})).grant,FK=async(e,t)=>(await me(`${ge}/${e}/network/domains`,d({network:db}),{method:"POST",body:JSON.stringify({domain:t})})).network,Dx=d({at:c(),listener:c(),host:c(),port:w(),decision:c()}),Nx=d({records:C(Dx),dropped:w(),since:c()}),EK=(e,t)=>me(`${ge}/${e}/journal`,Nx,{signal:t}),Fx=d({saved:w().int().min(0)}),hb=d({id:Fn,removed:y(),failures:C(Da),chats:Fx.nullable().default(null)}),MK=e=>me(`${ge}/${e}/start`,Na,{method:"POST"}),BK=async(e,t)=>{await me(`${ge}/${e}/task-title`,d({applied:y(),taskTitle:Sp.nullable()}),{method:"PUT",body:JSON.stringify({title:t})})},LK=e=>me(`${ge}/${e}/stop`,Na,{method:"POST"}),qK=e=>me(`${ge}/${e}/restart`,Na,{method:"POST"}),VK=e=>me(`${ge}/${e}/restart-opencode`,Na,{method:"POST"}),Ex=1,Mx=168,fb=d({enabled:y(),hours:w().int().min(Ex).max(Mx)}),UK=e=>me(`${ge}/idle-stop`,fb,{signal:e}),WK=e=>me(`${ge}/idle-stop`,fb,{method:"PUT",body:JSON.stringify(e)}),HK=(e,t)=>me(`${ge}/${e}/setup`,Na,{method:"POST",body:JSON.stringify({commands:t})}),Bx=d({setup:ub.nullable(),output:c().nullable()}),GK=(e,t)=>me(`${ge}/${e}/setup`,Bx,{signal:t}),_K=(e,{deleteUnsavedChats:t=!1}={})=>me(`${ge}/${e}${t?"?unsavedChats=delete":""}`,hb,{method:"DELETE"}),Lx=d({spaceId:Fn,name:c(),directory:c()}),KK=async e=>(await me(`${ge}/archives`,d({archives:C(Lx)}),{signal:e})).archives,qx=d({changedPaths:w().int().min(0),changedBytes:w().min(0),nestedRepositories:Co,unmerged:Co,changesRoute:S(["open","closed"]),lastApplied:c().nullable(),newPaths:w().int().min(0).nullable(),newPathsUndecided:y().default(!1)}),Vx=M([d({status:m("applied"),branch:c()}),d({status:m("applied"),appliedPaths:w().int().min(0)}),d({status:m("nothing_to_apply")})]),Ux=d({applied:Vx,removal:hb.nullable(),kept:Da.nullable().default(null)}),ZK=(e,t)=>me(`${ge}/${e}/apply`,qx,{signal:t}),JK=(e,t)=>me(`${ge}/${e}/apply`,Ux,{method:"POST",body:JSON.stringify(t)}),bb=/^(?:\/\/\?\/)?[A-Za-z]:\/+$/u,mg=/^(?:\/\/\?\/)?[A-Za-z]:$/u,Wx=/^\/\/(?:[^/?][^/]*\/[^/]+|\?\/UNC\/[^/]+\/[^/]+)$/iu,je=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const s=t.replace(/\\/g,"/").replace(/^([a-z]):/,(n,o)=>o.toUpperCase()+":");return s==="/"?"/":bb.test(s)?s.replace(/\/+$/u,"/"):(s.length>1?s.replace(/\/+$/,""):s)||null},Hx=e=>{if(e==="/"||bb.test(e)||mg.test(e)||Wx.test(e))return null;const t=e.lastIndexOf("/");if(t<0)return null;if(t===0)return"/";const s=e.slice(0,t);return mg.test(s)?`${s}/`:s},Gx=e=>je(e)??"",_x=d({id:c().regex(/^[0-9a-f]{12}$/),name:c().default(""),taskTitle:Sp.nullish(),state:S(["complete","partial","stale","unknown"]),projectDirectory:c().nullable().default(null),directory:c().nullable().default(null)}),$l=new Map,qa=new Map,Kx=(e,t)=>t.step==="failed"?{...e,state:"failed",failure:t.failure}:{...e,state:t.step==="ready"?"running":"preparing",step:t.step==="ready"?null:t.step,failure:null},hg=(e,t,s)=>{const a=e.get(t);if(!a||a.state===s)return e;const n=new Map(e);return n.set(t,{...a,state:s}),n},it=Rt((e,t)=>({spaces:$l,journey:null,progressRevision:0,applyJourney:(s,a)=>e(n=>{const o=new Map(s.map(i=>[i.id,i]));for(const[i,r]of qa){const l=n.journey?.get(i);r>a&&l&&o.set(i,l)}return{journey:o}}),addJourneyEntry:s=>e(a=>{const n=a.progressRevision+1;qa.set(s.id,n);const o=new Map(a.journey??[]);return o.set(s.id,s),{journey:o,progressRevision:n}}),noteTaskTitle:(s,a)=>{const n=t(),o=n.journey?.get(s),i=n.spaces.get(s),r=n.progressRevision+1;qa.set(s,r);const l=o?new Map(n.journey).set(s,{...o,taskTitle:a}):n.journey,p=i?new Map(n.spaces).set(s,{...i,taskTitle:a}):n.spaces;return e({journey:l,spaces:p,progressRevision:r}),!!o},noteGrantGiven:(s,a)=>e(n=>{const o=n.journey?.get(s);if(!o)return n;const i=n.progressRevision+1;qa.set(s,i);const r=new Map(n.journey);return r.set(s,{...o,grants:[...o.grants.filter(l=>l.id!==a.id),a],needsAccess:o.needsAccess.filter(l=>l!==a.id),accessFailures:a.kind==="domain"?o.accessFailures:o.accessFailures.filter(l=>l.provider!==a.provider)}),{journey:r,progressRevision:i}}),customProviders:new Map,noteCustomProviders:(s,a)=>e(n=>{const o=new Map(n.customProviders);return o.set(s,a),{customProviders:o}}),accessDialog:null,openAccessDialog:(s,a=null)=>e({accessDialog:{spaceId:s,providerId:a}}),closeAccessDialog:()=>e({accessDialog:null}),actions:new Map,noteAction:(s,a)=>e(n=>{const o=new Map(n.actions);return a?o.set(s,a):o.delete(s),{actions:o}}),applyDialog:null,openApplyDialog:s=>e({applyDialog:s}),closeApplyDialog:()=>e({applyDialog:null}),deleteDialog:null,deleteUnsaved:null,openDeleteDialog:(s,a=null)=>e({deleteDialog:s,deleteUnsaved:a}),closeDeleteDialog:()=>e({deleteDialog:null,deleteUnsaved:null}),archivedNotice:null,noteChatsArchived:s=>e({archivedNotice:s}),setupOutputDialog:null,openSetupOutputDialog:s=>e({setupOutputDialog:s}),closeSetupOutputDialog:()=>e({setupOutputDialog:null}),actionsSheet:null,openActionsSheet:s=>e({actionsSheet:s}),closeActionsSheet:()=>e({actionsSheet:null}),noteProgress:s=>{const a=t().progressRevision+1;qa.set(s.spaceId,a);const n=t().journey?.get(s.spaceId);if(!n)return e({progressRevision:a}),!1;const o=new Map(t().journey);return o.set(s.spaceId,Kx(n,s)),e({journey:o,progressRevision:a}),!0},applyMarks:s=>e(a=>{const n=new Map(s.map(o=>[o.id,o]));return n.size===0&&a.spaces.size===0?a:{spaces:n}}),noteStream:(s,a)=>e(n=>a==="connected"?n:{spaces:hg(n.spaces,s,"stale")}),noteReachable:s=>e(a=>({spaces:hg(a.spaces,s,"complete")})),resetForRuntimeSwitch:()=>{qa.clear(),Cn+=1,e({spaces:$l,journey:null,progressRevision:0,customProviders:new Map,accessDialog:null,actions:new Map,applyDialog:null,deleteDialog:null,deleteUnsaved:null,archivedNotice:null,setupOutputDialog:null,actionsSheet:null})},forgetForSwitchOff:()=>t().resetForRuntimeSwitch()}));let Cn=0;const $K=()=>Cn,Zx=async()=>{const e=Cn,t=it.getState().progressRevision,s=await jx();if(e===Cn){it.getState().applyJourney(s,t);for(const a of new Set(s.flatMap(n=>n.projectDirectory?[n.projectDirectory]:[])))it.getState().customProviders.has(a)||Jx(a)}},Lc=new Map,Jx=e=>{const t=Lc.get(e);if(t)return t;const s=Cn,a=Ox(e).then(n=>{s===Cn&&it.getState().noteCustomProviders(e,n)}).catch(()=>{}).finally(()=>{Lc.delete(e)});return Lc.set(e,a),a},$x=e=>it.getState().spaces.get(e)??null,kb=e=>e?.state==="exited"||e?.state==="missing"||e?.state==="unreachable",Qx=e=>kb(it.getState().journey?.get(e)),wb=e=>e?.state==="failed"||e?.state==="missing"||e?.state==="unreachable",QK=e=>{const t=kt.c(2);let s;return t[0]!==e?(s=a=>e!=null&&wb(a.journey?.get(e)),t[0]=e,t[1]=s):s=t[1],it(s)},YK=e=>{const t=zt(e);return t!==null&&wb(it.getState().journey?.get(t))},yb=(e,t)=>{const s=zt(t);return s===null?null:e.spaces.get(s)?.projectDirectory??e.journey?.get(s)?.projectDirectory??null},XK=e=>yb(it.getState(),e),e1=e=>{const t=kt.c(2);let s;return t[0]!==e?(s=a=>yb(a,e),t[0]=e,t[1]=s):s=t[1],it(s)},t1=e=>{const t=zt(e);return t!==null&&Qx(t)},Yx=e=>new Set([...e.spaces.keys(),...e.journey?.keys()??[]]),s1=e=>{const t=zt(e);return t===null||Yx(it.getState()).has(t)},a1=(e,t)=>Array.from(e).filter(s=>!t.has(s)),n1=e=>{const t=kt.c(4);let s;t[0]!==e?(s=zt(e),t[0]=e,t[1]=s):s=t[1];const a=s;let n;return t[2]!==a?(n=o=>a!==null&&kb(o.journey?.get(a)),t[2]=a,t[3]=n):n=t[3],it(n)},Xx=(e,t)=>{const s=Array.from(e.values(),a=>{const n=t?.get(a.id);return n?{...a,taskTitle:n.taskTitle??null}:a});for(const a of t?.values()??[])e.has(a.id)||a.projectDirectory===null||a.directory===null||s.push({id:a.id,name:a.name,taskTitle:a.taskTitle??null,state:"complete",projectDirectory:a.projectDirectory,directory:a.directory});return s},o1=e=>{const t=kt.c(7),s=e===void 0?!0:e;let a;t[0]!==s?(a=l=>s?l.spaces:$l,t[0]=s,t[1]=a):a=t[1];const n=it(a);let o;t[2]!==s?(o=l=>s?l.journey:null,t[2]=s,t[3]=o):o=t[3];const i=it(o);let r;return t[4]!==i||t[5]!==n?(r=Xx(n,i),t[4]=i,t[5]=n,t[6]=r):r=t[6],r},i1=(e,t)=>{const s=je(t);return Array.from(e.values()).filter(a=>s!==null&&je(a.projectDirectory)===s)},r1=e=>Array.from(e.values()).filter(t=>t.projectDirectory===null),c1=()=>{const e=kt.c(5),t=it(eT),[s,a]=ta.useState(null);let n,o;e[0]===Symbol.for("react.memo_cache_sentinel")?(n=()=>{let r=!0;return Zx().then(()=>{r&&a(null)},l=>{r&&a(l)}),()=>{r=!1}},o=[],e[0]=n,e[1]=o):(n=e[0],o=e[1]),ta.useEffect(n,o);let i;return e[2]!==s||e[3]!==t?(i={journey:t,error:s},e[2]=s,e[3]=t,e[4]=i):i=e[4],i};function eT(e){return e.journey}const fg=500,vb=()=>{if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("startupTrace")==="1"||window.localStorage?.getItem("OPENCHAMBER_STARTUP_TRACE")==="1"}catch{return!1}},l1=()=>vb(),Et=(e,t)=>{if(!vb())return;const s=typeof performance<"u"?performance.now():Date.now();window.__OPENCHAMBER_STARTUP_TRACE_START__??=s,window.__OPENCHAMBER_STARTUP_TRACE__??=[],window.__OPENCHAMBER_STARTUP_TRACE__.push({t:Math.round(s-window.__OPENCHAMBER_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__OPENCHAMBER_STARTUP_TRACE__.length>fg&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-fg)},tT=()=>{const e=typeof window<"u"?window.__OPENCHAMBER_STARTUP_TRACE__??[]:[],t=e.findIndex(a=>a.name==="ModelControls:ready"),s=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,s).filter(a=>a.name.includes("checkConnection")||a.name.includes("checkHealth")||a.name.includes("initializeApp")||a.name.includes("initApp")||a.name.includes("loadProviders")||a.name.includes("loadAgents")||a.name.includes("config.defaults")||a.name.includes("modelsMetadata")||a.name.includes("ModelControls")||a.name.includes("activateDirectory")||a.name.includes("opencodeClient:setDirectory"))};typeof window<"u"&&(window.__OPENCHAMBER_STARTUP_TRACE_SUMMARY__=tT);const d1=async(e,t,s)=>{const a=typeof performance<"u"?performance.now():Date.now();Et(`${e}:start`,s);try{const n=await t(),o=typeof performance<"u"?performance.now():Date.now();return Et(`${e}:end`,{durationMs:Math.round(o-a)}),n}catch(n){const o=typeof performance<"u"?performance.now():Date.now();throw Et(`${e}:error`,{durationMs:Math.round(o-a),error:n instanceof Error?n.message:String(n)}),n}},sT=3,aT=3e4,nT=32e3,oT=3600*1e3,iT=600*1e3,rT=200,cT=new Set([429,502,503,504]),fs=new Map,Tp=e=>JSON.stringify([N(),e]);function lT(){const e=Date.now();for(const[t,s]of fs){const a=Math.max(s.lastErrorAt,s.circuitOpenAt);e-a>oT&&fs.delete(t)}}typeof setInterval<"u"&&setInterval(lT,iT).unref?.();function dT(e){const t=Tp(e);let s=fs.get(t);if(!s)for(s={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:aT},fs.set(t,s);fs.size>rT;){const a=fs.keys().next().value;if(!a)break;fs.delete(a)}return s}function pT(e){e&&fs.delete(Tp(e))}function uT(e,t){if(!e)return;const s=dT(e);s.consecutiveErrors+=1,s.lastErrorAt=Date.now(),gT(t)&&s.consecutiveErrors>=sT&&(s.circuitOpen=!0,s.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${s.consecutiveErrors} consecutive errors`))}function gT(e){return e!==void 0&&cT.has(e)}function mT(e){const t=fs.get(Tp(e));return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,nT*4),!1):!0:!1}function hT(e){if(!(!e||!mT(e)))throw new Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}function qc({providerID:e,id:t,variant:s}){return s?{providerID:e,id:t,variant:s}:{providerID:e,id:t}}function p1(e,t){return e.providerID===t.providerID&&e.id===t.id&&(e.variant??"default")===(t.variant??"default")}function u1(e,t){if(!(!e||!t))return e.find(s=>s.id===t)??e.find(s=>s.modelID===t)}function ie(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}const gn={text:(e,t)=>`${e}:text:${t}`,reasoning:(e,t)=>`${e}:reasoning:${t}`,tool:e=>e,userText:e=>`${e}:text:0`,userFile:(e,t)=>`${e}:file:${t}`,userAgent:(e,t)=>`${e}:agent:${t}`},g1=e=>e==="completed"||e==="error",Cb=e=>e.role==="user"||e.role==="assistant",m1=e=>e==="user"||e==="assistant",h1=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const s=e[t];if(s&&Cb(s))return s}},f1=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const s=e[t];if(s?.info&&Cb(s.info))return s}},b1=e=>e?.role==="assistant"&&e.time.completed===void 0,U={edit:"edit",execute:"execute",glob:"glob",grep:"grep",patch:"patch",question:"question",read:"read",shell:"shell",skill:"skill",subagent:"subagent",todowrite:"todowrite",webfetch:"webfetch",websearch:"websearch",write:"write",sessionRename:"session_rename",sessionMove:"session_move",models:"models"};function nt(e){const t=e?.trim().toLowerCase();if(!t)return"";const s=t.replace(/:\d+$/,"");if(!s.includes("."))return s;const a=s.split(".").filter(Boolean);return a[a.length-1]??s}const Is=e=>t=>nt(t)===e,fT=Is(U.shell),k1=Is(U.execute),Ap=Is(U.subagent),w1=Is(U.question),y1=Is(U.skill),v1=Is(U.edit),C1=Is(U.write),S1=Is(U.patch),P1=Is(U.todowrite),bT=new Set([U.read,U.skill]),kT=e=>bT.has(nt(e)),wT=new Set([U.edit,U.write,U.patch]),yT=new Set([U.read,U.grep,U.glob,U.skill]),vT=new Set([U.webfetch,U.websearch]),x1=e=>wT.has(nt(e)),T1=e=>{const t=nt(e);return t===U.edit||t===U.patch},A1=e=>yT.has(nt(e)),z1=e=>vT.has(nt(e)),R1=e=>nt(e)===U.websearch,H=c().trim().min(1).optional().catch(void 0),bg=w().int().nonnegative().optional().catch(void 0),Ql=M([y(),S(["true","false"]).transform(e=>e==="true")]).optional().catch(void 0),CT=d({path:H,filePath:H,file_path:H,command:H,description:H,agent:H,name:H,id:H,server:H,uri:H,prompt:H,title:H,directory:H,search:H,provider:H,patchText:H,pattern:H,query:H,url:H,code:H,questions:C(ne()).optional().catch(void 0),action:H,parameters:d({title:H,name:H,prompt:H,path:H,url:H,query:H,text:H,selector:H,taskId:H,providerId:H,body:H,identifier:H,link:d({identifier:H,title:H}).optional().catch(void 0)}).optional().catch(void 0)}).catch({}),ST=d({file:H,patch:H,additions:bg,deletions:bg,status:S(["added","deleted","modified"]).optional().catch(void 0)}),PT=d({tool:H,status:H,input:at().optional().catch(void 0)}),En=d({files:C(ST.nullable().catch(null)).optional().catch(void 0),sessionID:H,sessionId:H,shellID:H,status:H,name:H,toolCalls:C(PT.nullable().catch(null)).optional().catch(void 0),truncated:y().optional().catch(void 0),outputPath:H}).catch({}),Fa=e=>CT.parse(e??{}),Yl=d({html:c().optional().catch(void 0),ui:c().optional().catch(void 0),title:H,awaitAnswer:Ql}),xT=Yl.extend({parameters:Yl.optional().catch(void 0)}).catch({}),kg=ke(c(),at()),TT=d({action:c()}).transform(({action:e})=>{let t;try{t=JSON.parse(e)}catch{return{}}const s=kg.safeParse(t);if(!s.success)return{};const{parameters:a,...n}=s.data,o=kg.safeParse(a);return Yl.parse({...n,...o.data})}).catch({}),Sb=e=>TT.parse(e??{}),AT=M([d({answered:m(!0),summary:c(),data:at().catch(null)}),d({answered:m(!1),reason:c().optional().catch(void 0)})]),zT=d({openchamber:d({ok:y().optional().catch(void 0),answer:AT.optional().catch(void 0)}).optional().catch(void 0)}).catch({});function RT(e){const t=Fa(e);return t.path??t.filePath??t.file_path}function Xl(e){return(En.parse(e??{}).files??[]).filter(s=>s!==null&&s.file!==void 0)}const wg=160;function I1(e){const t=En.parse(e??{});return t.shellID||t.status==="running"&&(t.sessionID||t.sessionId)?!0:(t.toolCalls??[]).some(s=>s?.status==="running"&&(fT(s.tool)||Ap(s.tool)))}function Pb(e){const t=En.parse(e??{}).toolCalls??[],s=[];for(const a of t){if(!a?.tool)continue;const n={tool:a.tool},o=Nb(a.tool,a.input)?.action;o&&(n.action=o),a.status&&(n.status=a.status);const i=DT(a.input);i&&i!=="{}"&&i!=="null"&&(n.input=i.length>wg?`${i.slice(0,wg)}…`:i),s.push(n)}return s}const zp=d({toolCalls:C(d({tool:H,status:H,input:at().optional().catch(void 0)}).nullable().catch(null)).optional().catch(void 0),error:y().optional().catch(void 0)}).catch({});function j1(e){const t=zp.parse(e??{}).toolCalls??[];for(let s=t.length-1;s>=0;s-=1){const a=t[s];if(a?.tool)return{tool:a.tool,input:a.input}}}function xb(e){const t=zp.parse(e??{}).toolCalls??[];if(!(t.length!==1||!t[0]?.tool))return{...t[0],tool:t[0].tool}}function Tb(e,{input:t,status:s}){return{tool:e,input:t&&typeof t=="object"&&!Array.isArray(t)?t:{},status:s}}function O1(e){const t=xb(e);if(!t)return;const s=Op(t.tool),a=Nb(t.tool,t.input)?.tool??(s?`opencode.${s}`:void 0);return a?Tb(a,t):void 0}function IT(e){return e.replaceAll(".","_")}const jT=new Set(["search","fetch"]),OT=new Set(Object.values(U));function D1(e){const t=xb(e);if(!t||t.status!=="completed"||jT.has(t.tool)||zp.parse(e??{}).error)return;const s=IT(t.tool);return OT.has(nt(s))?void 0:Tb(s,t)}function N1(e){const t=new Set(Pb(e).map(({tool:a})=>{if(Op(a))return"opencode";if(ri.has(nt(a)))return nt(a);const n=a.indexOf(".");return n>0?a.slice(0,n).toLowerCase():""})),[s]=t;return t.size===1&&s?s:void 0}function DT(e){if(e!=null)try{return JSON.stringify(e)}catch{return}}function F1(e){const t=En.parse(e??{});return t.truncated?t.outputPath?{outputPath:t.outputPath}:{}:null}function E1(e){return Fa(e).code}const NT=d({content:c().trim().min(1),status:S(["pending","in_progress","completed","cancelled"]).catch("pending")}),FT=d({todos:C(NT.nullable().catch(null)).optional().catch(void 0)}).catch({});function ET(e){const t=FT.parse(e??{}).todos;return t?t.filter(s=>s!==null):null}const MT=e=>e===jp,BT={amp:"&",lt:"<",gt:">",quot:'"',"#39":"'",apos:"'",nbsp:" "},LT=120,yg=(e,t)=>(t.exec(e)?.[1]??"").replace(/<[^>]*>/g," ").replace(/&(amp|lt|gt|quot|#39|apos|nbsp);/g,(s,a)=>BT[a]).replace(/\s+/g," ").trim(),qT=e=>(yg(e,/<title\b[^>]*>([\s\S]*?)<\/title>/i)||yg(e,/<h[1-3]\b[^>]*>([\s\S]*?)<\/h[1-3]>/i)).slice(0,LT).trim();function VT(e,t){if(!MT(e))return null;const s=xT.parse(t.input??{}),a=Sb(t.input),n=s.parameters?.html??s.html??a.html??"",o=s.parameters?.ui??s.ui??a.ui,i=o?.trim()?{html:"",ui:o}:n.trim()?{html:n}:null;if(!i)return null;const r=(s.parameters?.title??s.title??a.title)?.trim()||qT(n);if((s.parameters?.awaitAnswer??s.awaitAnswer??a.awaitAnswer)===!0){if(t.status==="running")return{...i,title:r,ask:{kind:"waiting"}};if(t.status==="error")return{...i,title:r,ask:{kind:"unanswered"}}}if(t.status!=="completed")return null;const l=zT.parse(t.metadata??{}).openchamber;if(l?.ok!==!0)return null;const p=l.answer;if(p?.answered===!0)return{...i,title:r,ask:{kind:"answered",summary:p.summary,data:p.data}};if(p?.answered===!1){const u=p.reason==="chat-sent-earlier"?"chat-sent-earlier":p.reason==="ui-not-drawn"?"not-drawn":p.reason==="declined"?"declined":"answered-in-chat";return{...i,title:r,ask:{kind:u}}}return{...i,title:r,ask:{kind:"show"}}}const vg=d({label:H,reason:H,placeholder:H}),Ab=vg.extend({parameters:vg.optional().catch(void 0)}).catch({}),UT=d({env:c().trim().min(1),label:c().trim().min(1),placeholder:H}),Cg=d({program:H,args:C(c()).optional().catch(void 0),reason:H,inputs:C(UT).min(1).optional().catch(void 0)}),Rp=Cg.extend({action:c().optional().catch(void 0),parameters:Cg.optional().catch(void 0)}).catch({}),zb=e=>e==="secret.run"||e==="run",Rb=e=>e==="secret.forget"||e==="forget";function Ib(e,t){const s=o=>o<32||o>=127&&o<=159||o===1564||o>=8203&&o<=8207||o>=8232&&o<=8238||o>=8288&&o<=8297||o===65279,a=o=>Array.from(o,i=>{const r=i.codePointAt(0)??0;return s(r)?`\\u{${r.toString(16).toUpperCase().padStart(4,"0")}}`:i}).join(""),n=o=>/^[A-Za-z0-9_/.,:=@%+-]+$/.test(o)?o:`'${a(o).replaceAll("'","'\\''")}'`;return[e,...t].map(n).join(" ")}function jb(e,t){if(e==="secret.run"||e==="run"){const s=Rp.parse(t??{}),a=s.parameters?.program??s.program;return a?Ib(a,s.parameters?.args??s.args??[]):void 0}if(e==="secret.request"||e==="request"){const s=Ab.parse(t??{});return s.parameters?.label??s.label}}function WT(e,t){if(e!==tc||t.status!=="running")return null;const s=Rp.parse(t.input??{});if(!zb(s.action))return null;const a=s.parameters?.program??s.program,n=s.parameters?.reason??s.reason,o=s.parameters?.inputs??s.inputs;if(!a||!n||!o)return null;const i=s.parameters?.args??s.args??[];return{reason:n,program:a,command:Ib(a,i),fields:o.map(r=>({env:r.env,label:r.label,placeholder:r.placeholder}))}}function HT(e,t){if(e!==tc||t.status!=="running")return null;const s=Rp.parse(t.input??{}).action;if(zb(s)||Rb(s))return null;const a=Ab.parse(t.input??{}),n=a.parameters?.label??a.label,o=a.parameters?.reason??a.reason;return!n||!o?null:{label:n,reason:o,placeholder:a.parameters?.placeholder??a.placeholder}}function M1(e){return Fa(e).agent}function B1(e){return Fa(e).description}function GT(e){const t=En.parse(e??{});return t.sessionID??t.sessionId}const Ip=100,_T=4,KT=120,jp="openchamber_render",tc="openchamber_secret",Ob="openchamber_workflow",Db="openchamber_image",ri=new Set(["openchamber","openchamber_schedule","openchamber_web","openchamber_memory","openchamber_knowledge","openchamber_notify","openchamber_usage",jp,Db,tc,Ob]),L1=e=>ri.has(nt(e)),ZT=d({ok:m(!0),action:m("workflow.run"),data:d({runId:c().min(1)})});function JT(e,t){if(e!==Ob||t.status!=="completed")return null;let s;try{s=JSON.parse(t.output)}catch{return null}const a=ZT.safeParse(s);return a.success?a.data.data.runId:null}const $T=d({ok:m(!0),action:m("image.generate"),data:d({images:C(d({path:c().min(1)})).min(1)})});function QT(e,t){if(e!==Db||t.status!=="completed")return[];let s;try{s=JSON.parse(t.output)}catch{return[]}const a=$T.safeParse(s);return a.success?a.data.data.images.map(n=>n.path):[]}const q1=(e,t)=>VT(e,t)!==null||JT(e,t)!==null||QT(e,t).length>0||HT(e,t)!==null||WT(e,t)!==null,YT=d({action:H,awaitAnswer:Ql,parameters:d({awaitAnswer:Ql}).optional().catch(void 0)}).catch({}),XT=new Set(["session_rename","session_move","worktree_create","worktree_list","worktree_remove","models","list_mcp_resources","read_mcp_resource","schedule_create","schedule_list","schedule_pause","schedule_resume","schedule_delete","artifact_create","artifact_read","artifact_update","artifact_delete"]),Sg="opencode_";function Op(e){const t=e?.trim().toLowerCase()??"",s=t.startsWith(Sg)?t.slice(Sg.length):nt(t);return XT.has(s)?s:void 0}function V1(e,t){const s=e?.trim()??"";let a;for(const n of t){const o=`${n.replace(/[^a-zA-Z0-9_-]/g,"_")}_`;s.length>o.length&&s.startsWith(o)&&n.length>(a?.length??0)&&(a=n)}return a}function Nb(e,t){const s=nt(e);if(!ri.has(s))return null;const a=YT.parse(t??{}),n=s===jp?Sb(t).awaitAnswer:void 0,o=a.parameters?.awaitAnswer??a.awaitAnswer??n,i=s===tc&&!Rb(a.action)||o===!0;return{tool:s,action:a.action,awaitsAnswer:i}}function Fb(e){const t=e.parameters,s=t?.link;return(s?[s.identifier,s.title].filter(Boolean).join(" "):void 0)||t?.identifier||t?.title||t?.name||t?.path||t?.url||t?.query||t?.text||t?.selector||t?.prompt?.split(`
@@ -31,7 +31,7 @@ A new session could conflict with them. You may want to commit them first or use
31
31
 
32
32
  Skip creates the worktree without running them. You can run them yourself after reading the code.`,"session.newWorktree.toast.worktreeCreated":"Worktree created","session.newWorktree.toast.worktreeCreatedDescription":"{target} - bootstrapping in background","session.newWorktree.toast.fetchSourceFailed":"Couldn't fetch from remote — created from local state","session.newWorktree.toast.fetchSourceAccess":"Couldn't fetch: this repository's access needs attention in Configure repository. Created from local state.","session.newWorktree.toast.startFolderMissing":'This worktree has no "{folder}" folder, so OpenCode started at the worktree root.',"session.newWorktree.toast.startFolderUnverified":`Couldn't check the "{folder}" folder, so OpenCode started at the worktree root.`,"session.newWorktree.toast.startFolderUnknown":"Couldn't tell which folder of the repository this project opens, so OpenCode started at the worktree root.","session.newWorktree.toast.branchBackup":"{branch} now matches the remote. Its previous commits are kept in {backup}.","session.githubIntegration.tabs.pullRequests":"Pull Requests","session.githubIntegration.validation.branchAlreadyCheckedOut":"Branch is already checked out in a worktree","session.githubIntegration.validation.failed":"Validation failed","chat.fileAttachment.toast.attachFailed":"Failed to attach file","chat.fileAttachment.toast.tooLarge":"{name} is too large to attach (over {size}). Mention it with @ if it is in the project.","chat.fileAttachment.toast.heicConversionFailed":"{name} could not be converted from HEIC to JPEG, so it was not attached. Save the photo as JPEG and attach it again.","chat.fileAttachment.toast.overSendLimit":"{name} is too large to attach (over {size}).","chat.fileAttachment.toast.someFilesSkipped":`Some files were skipped:
33
33
  {summary}`,"chat.fileAttachment.toast.vscodePickFailed":"Failed to pick files in VS Code","chat.fileAttachment.fileFallback":"file","chat.fileAttachment.skippedFallback":"skipped","chat.fileAttachment.actions.attachAria":"Attach files","chat.fileAttachment.actions.attach":"Attach files","chat.fileAttachment.actions.removeNamed":"Remove {name}","chat.fileAttachment.actions.removeImage":"Remove image","chat.fileAttachment.activeEditor.addFile":"Add file:{name} to context","chat.fileAttachment.activeEditor.pinSelection":"Pin selection to context","chat.fileAttachment.activeEditor.remove":"Remove from context","chat.fileAttachment.openInDiagram":"Open in diagram view","chat.changedFiles.title":"Changed files","chat.changedFiles.actions.openFileTitle":"Open {path}","chat.changedFiles.actions.otherFiles":"Other changed files ({count})","chat.changedFiles.actions.showFewer":"Show fewer files","chat.emptyState.opencodeUnreachable":"OpenCode is not reachable","chat.emptyState.startNewChat":"Start a new chat","chat.emptyState.draftTitle":"What are we working on?","chat.emptyState.draftTitleWithProject":"What are we working on in {project}?","chat.draftPresets.explore.label":"Explore the codebase","chat.draftPresets.catchup.label":"Catch me up","chat.draftPresets.weigh.label":"Weigh my options","chat.draftPresets.plan.label":"Start feature planning","chat.draftPresets.craftGoal.label":"Craft a Goal","chat.draftPresets.scheduleTask.label":"Schedule a Task","chat.draftPresets.debug.label":"Debug an issue","chat.draftPresets.review.label":"Review my changes","chat.draftStarters.add":"Add a starter","chat.draftStarters.searchPlaceholder":"Search commands and skills…","chat.draftStarters.empty":"Nothing to add","chat.draftStarters.sectionBuiltIn":"Built-in","chat.draftStarters.sectionCommands":"Commands","chat.draftStarters.sectionSkills":"Skills","chat.draftStarters.remove":"Remove","chat.draftStarters.sharedTitle":"Pinned in the repository config; change it there","chat.draftStarters.share":"Move to repository config","chat.draftStarters.makePersonal":"Move to my settings","chat.draftStarters.sectionPinned":"Your starters","chat.draftStarters.moveToFront":"Move to the front","chat.scrollToBottom.aria":"Scroll to bottom","chat.promptNavigator.aria":"Prompt navigation","chat.promptNavigator.currentPrompt":"Current prompt","chat.promptNavigator.loadMore":"Load more prompts","chat.timeline.relative.justNow":"just now","chat.timeline.relative.minutesAgo":"{count}m ago","chat.timeline.relative.hoursAgo":"{count}h ago","chat.timeline.relative.daysAgo":"{count}d ago","chat.timeline.title":"Conversation Timeline","chat.timeline.description":"Navigate to any point in the conversation or fork a new session","chat.timeline.searchPlaceholder":"Search messages...","chat.timeline.empty.search":"No messages found","chat.timeline.empty.session":"No messages in this session yet","chat.timeline.noTextContent":"[No text content]","chat.timeline.actions.title":"Actions","chat.timeline.actions.revertFromHere":"Revert from here","chat.timeline.actions.forkFromHere":"Fork from here","chat.timeline.actions.previousTurn":"Previous turn","chat.timeline.actions.latest":"Latest","chat.timeline.help.clickMessage":"Click on a message to scroll to it in the conversation","chat.timeline.help.undoToPoint":"Undo to this point (message text will populate input)","chat.timeline.help.createSessionFromHere":"Create a new session starting from here","chat.statusRow.todo.status.inProgress":"In progress","chat.statusRow.todo.status.pending":"Pending","chat.statusRow.todo.status.completed":"Completed","chat.statusRow.todo.status.cancelled":"Cancelled","chat.statusRow.todo.priority.high":"High priority","chat.statusRow.todo.priority.medium":"Medium priority","chat.statusRow.todo.priority.low":"Low priority","chat.statusRow.actions.stopGeneratingAria":"Stop generating","chat.statusRow.tasksTitle":"Tasks","chat.statusRow.modelStatus":"{model} is {status}","chat.statusRow.summary.activeLeft":"{active} active · {left} left","chat.revertIndicator.redo":"Redo","chat.revertIndicator.redoAria":"Redo — restore reverted messages","chat.revertPopover.title":"Reverted","chat.revertPopover.noTextContent":"No text content","chat.revertPopover.forkFromHere":"Fork from here","chat.revertPopover.forkFromMessage":"Fork from this message","chat.revertPopover.restoreAll":"Restore all","chat.revertPopover.restore":"Restore","chat.revertPopover.revert":"Revert","chat.revert.toast.undo":"Reverted to {preview}","chat.revert.toast.redo":"Redone","chat.revert.toast.restored":"Restored all messages","chat.toast.opencodeRestartInterrupted.title":"Chat interrupted","chat.toast.opencodeRestartInterrupted.description":"OpenCode restarted while a response was still running. Send a message to continue.","chat.toast.opencodeRestartInterrupted.autoResumeDescription":"OpenCode restarted while a response was still running. The chat will resume automatically; send a message if it does not.","chat.toast.opencodeRestartInterrupted.openSession":"Open session","chat.errorBoundary.title":"Chat Error","chat.errorBoundary.description":"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data.","chat.errorBoundary.sessionLabel":"Session","chat.errorBoundary.detailsSummary":"Error details","chat.errorBoundary.resetAction":"Reset Chat","chat.errorBoundary.persistentHint":"If the problem persists, try refreshing the page.","chat.autocomplete.tabs.commands":"Commands","chat.autocomplete.tabs.agents":"Agents","chat.autocomplete.tabs.files":"Files","chat.autocomplete.keyboardHint":"↑↓ navigate • Enter select • Esc close","chat.commandAutocomplete.command.initDescription":"Create/update AGENTS.md file","chat.commandAutocomplete.command.undoDescription":"Undo the last message","chat.commandAutocomplete.command.redoDescription":"Redo previously undone messages","chat.commandAutocomplete.command.timelineDescription":"Open the conversation timeline","chat.commandAutocomplete.command.compactDescription":"Compress session history using AI to reduce context size","chat.commandAutocomplete.command.summaryDescription":"Non-destructive session summary. Optional topic hint after the command.","chat.commandAutocomplete.command.workspaceReviewDescription":"Review the workspace diff for intent, correctness, and adequacy, graded by severity.","chat.commandAutocomplete.command.handoffReviewDescription":"Create or reuse a separate review session from a generated handoff.","chat.commandAutocomplete.command.featurePlanDescription":"Start a guided, back-and-forth planning session for a new feature.","chat.commandAutocomplete.command.craftGoalDescription":"Turn an idea or task into a clear, verifiable Goal.","chat.commandAutocomplete.command.scheduleTaskDescription":"Define a scheduled task through a guided dialogue.","chat.chatInput.toast.craftGoalFailed":"Failed to start Goal crafting","chat.chatInput.toast.scheduleTaskFailed":"Failed to start scheduled task setup","chat.commandAutocomplete.command.catchUpDescription":"Re-establish context: what you were doing and where to pick up.","chat.commandAutocomplete.command.debugDescription":"Guided root-cause investigation for a bug before proposing a fix.","chat.commandAutocomplete.command.weighDescription":"Weigh 2-3 approaches with trade-offs and a recommendation before you commit.","chat.commandAutocomplete.command.exploreDescription":"Get oriented in this codebase: a high-level tour of the architecture and main parts.","chat.commandAutocomplete.command.btwDescription":"Ask a side question in a temporary child session without derailing this chat.","chat.commandAutocomplete.command.forkDescription":"Fork this chat from the last finished reply and continue there; text after /fork is sent to the fork.","chat.commandAutocomplete.empty":"No commands found","chat.agentMentionAutocomplete.badge.system":"system","chat.agentMentionAutocomplete.empty":"No agents found","chat.fileMentionAutocomplete.searchMoreAgents":"Type to search more agents","chat.fileMentionAutocomplete.empty":"No matches found","chat.queuedMessage.attachments":"+{count} file(s)","chat.queuedMessage.empty":"(empty)","chat.queuedMessage.title":"Queued messages","chat.queuedMessage.edit":"edit","chat.queuedMessage.send":"send","chat.queuedMessage.removeAria":"Remove from queue","chat.queuedMessage.goal":"Starts a goal when sent","chat.queuedMessage.sendsAsAgent":"Sends as {agent}.","chat.queuedMessage.reorderAria":"Drag to reorder","chat.queuedMessage.toast.queueFailed":"Couldn't queue the message. It's back in the composer.","chat.queuedMessage.toast.takeFailed":"Couldn't load the queued message. Please try again.","chat.container.returnToParent.aria":"Return to parent session","chat.container.returnToParent.titleNamed":"Return to: {title}","chat.container.returnToParent.title":"Return to parent session","chat.container.returnToParent.label":"Parent","chat.container.readOnlySubagentPromptBanner":"Subagent sessions cannot be prompted.","chat.btw.destroyAria":"Destroy this btw session","chat.btw.titleFallback":"btw session","chat.btw.mainComposerPlaceholder":"Ask in this btw session…","chat.btw.loading":"Starting btw session…","chat.btw.toast.emptyArgument":"Type a question after /btw","chat.btw.toast.createFailed":"Failed to start the btw session","chat.btw.toast.destroyFailed":"Failed to destroy the btw session. It will remain in the sidebar.","chat.btw.working":"Working…","chat.btw.collapseAria":"Collapse the btw panel","chat.btw.draftHint":"Ask your question","chat.btw.cancelAria":"Cancel this BTW question","chat.btw.expandAria":"Expand the btw panel","chat.btw.promoteAria":"Keep as a separate session","chat.btw.toast.promoteFailed":"Failed to keep the btw session","chat.container.sessionLoadError.title":"Session could not be loaded","chat.container.sessionLoadError.description":"The conversation could not be fetched — the server may be offline or unreachable. Nothing is lost; retry once it is back.","chat.container.sessionLoadError.authDescription":"Your session expired, so the server refused the request. Log in and the conversation will load.","chat.container.sessionLoadError.retry":"Try again","sessions.sidebar.group.empty.loadingSessions":"Loading sessions…","sessions.sidebar.group.empty.loadFailed":"Could not refresh sessions.","sessions.sidebar.group.empty.initializationFailed":"Could not initialize workspace.","sessions.sidebar.group.empty.trustPaused":"Agents are paused until you trust this folder.","sessions.sidebar.group.empty.reviewTrust":"Review and trust","sessions.sidebar.group.empty.retry":"Try again","sessions.sidebar.group.empty.permissionDenied":"Folder access is required.","sessions.sidebar.group.empty.grantAccess":"Grant access","chat.unifiedControls.title":"Controls","chat.unifiedControls.model.title":"Model","chat.unifiedControls.model.noRecent":"No recent models","chat.unifiedControls.model.moreAria":"More models","chat.unifiedControls.effort.title":"Effort","chat.unifiedControls.effort.moreAria":"More effort options","chat.questionCard.summaryTab":"Summary","chat.questionCard.noAnswer":"(no answer)","chat.questionCard.inputNeeded":"Input needed","chat.questionCard.fromSubagent":"From subagent","chat.questionCard.questionFallback":"Question {index}","chat.questionCard.selectMultiple":"Select multiple","chat.questionCard.recommended":"recommended","chat.questionCard.other":"Other…","chat.questionCard.yourAnswer":"Your answer","chat.questionCard.submit":"Submit","chat.questionCard.next":"Next","chat.questionCard.dismiss":"Dismiss","chat.questionCard.copyMarkdown":"Copy as Markdown","chat.questionCard.copyJson":"Copy as JSON","chat.questionCard.copiedMarkdown":"Question copied as Markdown","chat.questionCard.copiedJson":"Question copied as JSON","chat.questionCard.copyFailed":"Failed to copy question","chat.questionCard.submitFailed":"Failed to send response","chat.questionCard.dismissFailed":"Failed to dismiss question","chat.questionCard.noLongerPending":"This question is no longer waiting for a response.","chat.questionCard.tryAgain":"Please try again in a moment.","chat.textSelection.toast.noProject":"No project found for this session","chat.textSelection.toast.addToNotesFailed":"Failed to add to notes","chat.textSelection.toast.addToNotesSuccess":"Added selected text to notes","chat.textSelection.toast.addToNotesSummaryFailed":"Could not summarize selection, added selected text to notes","chat.textSelection.actions.addToInput":"Quote","chat.textSelection.actions.read":"Read","chat.textSelection.actions.stopReading":"Stop","chat.textSelection.actions.comment":"Comment","chat.textSelection.actions.askOpenChamber":"By the way…","chat.textSelection.title.askOpenChamber":"Open a BTW draft with the selection","chat.textSelection.title.commentOnSelection":"Comment on selection","chat.textSelection.comment.placeholder":"Add an optional comment...","chat.textSelection.comment.attach":"Attach","chat.textSelection.comment.save":"Save comment","chat.textSelection.comment.attachFailed":"Could not attach the comment. Shorten it or remove other attached context, then try again.","chat.textSelection.actions.addToNotes":"Add to notes","chat.textSelection.title.addToCurrentChat":"Add to current chat","chat.textSelection.title.saveInsightToNotes":"Save selected text to notes","chat.messageBody.actions.revertAria":"Revert to this message","chat.messageBody.actions.revert":"Revert from here","chat.messageBody.actions.forkAria":"Fork from this message","chat.messageBody.actions.fork":"Fork from here","chat.messageBody.actions.copyMessageAria":"Copy message text","chat.messageBody.actions.copyMessage":"Copy message","chat.messageBody.actions.copyLink":"Copy link","chat.messageBody.toast.linkCopied":"Link copied","chat.messageBody.toast.linkCopyFailed":"Could not copy the link","chat.messageLink.notFound":"The linked message is not in this session","chat.messageBody.actions.pinContext":"Pin into context (survives compaction)","chat.messageBody.actions.unpinContext":"Unpin from context (will not survive compaction)","chat.messageBody.actions.contextPinFailed":"Could not update the context pin","chat.messageBody.actions.copyAnswer":"Copy answer","chat.messageBody.actions.moreActions":"More actions","chat.messageBody.toast.copied":"Copied to clipboard","chat.messageBody.actions.savingImage":"Saving image...","chat.messageBody.actions.saveAsImage":"Save as image","chat.messageBody.actions.saveAsPlan":"Save as plan","chat.messageBody.actions.startNewSession":"Start new session from this answer","chat.messageBody.actions.startNewMultiRun":"Start new multi-run from this answer","chat.messageBody.actions.branchMenu":"Continue from this answer","chat.messageBody.footer.reasoningTooltip":"Reasoning: {effort}","chat.messageBody.forkDialog.instructions.label":"Instructions","chat.messageBody.forkDialog.instructions.placeholder":"Add instructions for the new session…","chat.messageBody.forkDialog.createWorktree":"Create worktree","chat.generatedResult.actions.copy":"Copy","chat.generatedResult.actions.copied":"Copied","chat.generatedResult.commit.title":"Generated commit message","chat.generatedResult.commit.highlights":"Highlights","chat.generatedResult.pullRequest.title":"Generated pull request","chat.generatedResult.mergeRequest.title":"Generated merge request","chat.generatedResult.pullRequest.titleLabel":"Title","chat.generatedResult.pullRequest.bodyLabel":"Body","chat.messageBody.tts.stopSpeaking":"Stop speaking","chat.messageBody.tts.readAloud":"Read aloud","chat.messageBody.tts.readAloudWithProvider":"Read aloud ({provider} voice)","planView.tts.readAloud":"Read plan aloud","planView.tts.stopSpeaking":"Stop speaking","filesView.tts.readAloud":"Read file aloud","filesView.tts.stopSpeaking":"Stop speaking","chat.messageBody.toast.noProject":"No project found for this session","chat.messageBody.toast.savePlanFailed":"Failed to save plan","chat.messageBody.toast.planSaved":"Plan saved","chat.messageBody.toast.imageSaved":"Image saved","chat.messageBody.toast.generateImageFailed":"Failed to generate image","chat.chatInput.actions.commands":"Commands","chat.chatInput.actions.attachFiles":"Attach files","chat.chatInput.actions.addAttachment":"Add attachment","chat.chatInput.actions.modelAgentSettings":"Model and agent settings","chat.chatInput.actions.sendMessageAria":"Send message","chat.chatInput.actions.queueMessageAria":"Queue message","chat.chatInput.actions.stopGeneratingAria":"Stop generating","chat.chatInput.linked.byAuthor":"by {author}","chat.chatInput.linked.issue.openInBrowserAria":"Open issue in browser","chat.chatInput.linked.issue.removeAria":"Remove linked issue","chat.chatInput.linked.pr.openInBrowserAria":"Open pull request in browser","chat.chatInput.linked.mr.openInBrowserAria":"Open merge request in browser","chat.chatInput.linked.pr.removeAria":"Remove linked pull request","chat.chatInput.linked.mr.removeAria":"Remove linked merge request","chat.chatInput.placeholder.shell":"Enter shell command...","chat.chatInput.placeholder.chat":"Plan, build, or ask. @ to mention, $ for skills, / for commands","chat.chatInput.placeholder.chatCompact":"Plan, build, or ask","chat.chatInput.placeholder.selectSession":"Select or create a session to start chatting","chat.dictation.start":"Start dictation","chat.dictation.overlayAria":"Dictation","chat.dictation.downloadingModel":"Downloading speech model...","chat.dictation.downloadingModelProgress":"Downloading speech model... {percent}%","chat.dictation.listening":"Listening...","chat.dictation.processing":"Transcribing...","chat.dictation.failed":"Transcription failed","chat.dictation.cancel":"Discard dictation","chat.dictation.insert":"Insert transcript","chat.dictation.insertAndSend":"Insert and send","chat.dictation.retry":"Retry transcription","chat.dictation.discard":"Discard recording","chat.snippetAutocomplete.action.addNew":"Add new snippet","chat.snippetAutocomplete.empty":"No snippets found","chat.snippetAutocomplete.footer":"↑↓ navigate • Enter select • Esc close","chat.chatInput.toast.compactFailed":"Failed to compact session","chat.chatInput.toast.forkFailed":"Couldn't fork the session","chat.chatInput.toast.forkNothingToFork":"Nothing to fork yet: no reply has finished in this session","chat.chatInput.toast.forkSendFailed":"Forked, but the message wasn't sent. It's back in the composer.","chat.chatInput.toast.summaryFailed":"Failed to generate summary","chat.messageBody.actions.sendReviewFeedback":"Send review feedback to implementing agent","chat.messageBody.actions.sendImplementationResponse":"Send implementation response to reviewing agent","chat.chatInput.toast.reviewFailed":"Failed to review changes","chat.chatInput.toast.planFeatureFailed":"Failed to start feature planning","chat.chatInput.toast.catchUpFailed":"Failed to catch up","chat.chatInput.toast.debugFailed":"Failed to start debugging","chat.chatInput.toast.weighFailed":"Failed to weigh options","chat.chatInput.toast.exploreFailed":"Failed to start the tour","chat.chatInput.toast.attachmentsTooLarge":"Attachments are too large to send. Please try reducing the number or size of images.","chat.chatInput.toast.sendAttachmentsFailed":"Failed to send attachments. Try fewer files or smaller images.","chat.chatInput.toast.messageSendFailed":"Message failed to send. Attachments restored.","chat.chatInput.toast.agentUnavailable":`Agent "{agent}" isn't available in this session's folder. Pick another agent and send again.`,"chat.chatInput.toast.noModelSelected":"Select a provider and model before sending.","chat.chatInput.toast.clipboardAttachFailed":"Failed to attach image from clipboard","chat.chatInput.toast.clipboardTextAttachFailed":"Failed to attach pasted text as a file","chat.chatInput.largeTextPaste.title":"Large text detected","chat.chatInput.largeTextPaste.attach":"Attach as file","chat.chatInput.largeTextPaste.inline":"Paste inline","chat.chatInput.toast.addedFileMentions":"Added {count} file mention(s)","chat.chatInput.toast.attachFileFailed":"Failed to attach file","chat.chatInput.mentionChip.editHint":"Double-click to edit as text","chat.chatInput.toast.attachNamedFailed":"Failed to attach {name}","chat.chatInput.toast.unsupportedAttachmentModalities":"{model} does not support {modalities} input required by {files}. You can still send the message, but these attachments may be ignored.","chat.chatInput.toast.imagesSaving":"Saving {files}…","chat.chatInput.toast.imagesSavedForTextModel":"{model} can't read images. Saved {files} to {folder}.","chat.chatInput.toast.imageSaveFailed":"Couldn't save {files}. Attached instead.","chat.chatInput.toast.imagesSaved":"Saved {files} to {folder}.","chat.chatInput.toast.imageCopySaveFailed":"Couldn't save {files}.","chat.chatInput.toast.someFilesSkipped":`Some files were skipped:
34
- {summary}`,"chat.chatInput.toast.vscodePickFailed":"Failed to pick files in VS Code","chat.chatInput.toast.openSessionFirst":"Open a session first","chat.chatInput.toast.dictationKeptForOriginalSession":"Dictation saved as a draft in the session where you started it","chat.chatInput.toast.togglePermissionAutoAcceptFailed":"Failed to toggle permission auto-accept","chat.chatInput.reviewComments":"Review comments:","chat.chatInput.reviewCommentsRemove":"Remove review comments","chat.chatInput.previewAnnotations":"Preview annotations:","chat.chatInput.previewContext":"Preview context:","chat.chatInput.previewContextRemove":"Remove preview context","chat.chatInput.projectRoot":"Project root","chat.chatInput.branch":"Branch","chat.chatInput.draftPicker.projectTitle":"Project","chat.chatInput.draftPicker.searchProjects":"Search projects...","chat.chatInput.draftPicker.searchBranches":"Search branches...","chat.chatInput.draftPicker.noProjectsFound":"No projects found.","chat.chatInput.draftPicker.addProject":"Add project…","chat.chatInput.worktrees":"Worktrees","chat.chatInput.worktreeQuick":"Quick worktree","chat.chatInput.worktreeCustom":"New worktree…","chat.chatInput.drop.insertMention":"Drop to insert as mention","chat.chatInput.drop.attachFiles":"Drop files here to attach","chat.chatInput.fileFallback":"file","chat.toolOutputDialog.image.previousAria":"Previous image","chat.toolOutputDialog.image.nextAria":"Next image","chat.toolOutputDialog.image.closeAria":"Close image preview","chat.toolOutputDialog.mermaid.missingSource":"Missing Mermaid source URL.","chat.toolOutputDialog.mermaid.loadFailed":"Unable to load Mermaid diagram.","chat.toolOutputDialog.mermaid.dataUrlMalformed":"The Mermaid data URL is malformed.","chat.toolOutputDialog.mermaid.invalidLocalPath":"The local Mermaid file path is invalid.","chat.toolOutputDialog.mermaid.readFileFailedWithStatus":"Unable to read Mermaid file. Status: {status}.","chat.toolOutputDialog.mermaid.unsupportedUrlProtocol":"The Mermaid URL protocol is unsupported.","chat.toolOutputDialog.mermaid.loadFailedWithStatus":"Unable to load Mermaid diagram. Status: {status}.","chat.toolOutputDialog.mermaid.closeAria":"Close diagram preview","chat.toolOutputDialog.mermaid.loading":"Loading diagram...","chat.toolOutputDialog.mermaid.renderFailed":"Unable to render Mermaid diagram.","chat.toolOutputDialog.mermaid.retry":"Retry","chat.toolOutputDialog.commandCompleted":"Command completed successfully","chat.toolOutputDialog.noOutputProduced":"No output was produced","chat.statusRow.background.action":"Move to background — the agent stops waiting and continues","chat.statusRow.background.failed":"Couldn't move the work to the background","chat.toolPart.background.label":"in background","chat.toolPart.background.stop":"Stop command","chat.toolPart.background.stopLabel":"Stop","chat.toolPart.background.stopFailed":"Couldn't stop the command","chat.toolPart.background.stoppedLabel":"stopped","chat.toolPart.background.stoppedNotice":"Stopped by you. The agent was told this was your stop, not a failure.","chat.toolPart.subagent.stop":"Stop subagent","chat.toolPart.subagent.stopFailed":"Couldn't stop the subagent","chat.toolPart.lspErrors":"LSP errors","chat.toolPart.moreErrors":"+{count} more errors","chat.toolPart.moreRows":"+{count} more rows","chat.toolPart.error":"Error:","chat.toolPart.awaitingResponse":"Awaiting response...","chat.toolPart.noOutputProduced":"No output produced","chat.toolPart.questionsAsked":"Questions asked: {count}","chat.toolPart.filesCount":"Files: {count}","chat.toolPart.moreToolCalls":"+{count} more","chat.toolPart.scriptCalls":"Tool calls","chat.toolPart.outputTruncated":"Output was truncated","chat.toolPart.content.loading":"Loading the result…","chat.toolPart.content.loadFailed":"Couldn't load the result.","chat.toolPart.content.retry":"Retry","chat.toolPart.output":"Output","chat.toolPart.showRawJson":"Show raw JSON","chat.toolPart.showFormattedJson":"Show formatted JSON","chat.toolPart.showNavigableJson":"Show navigable JSON","chat.toolPart.openFile":"Open file","chat.toolPart.openImageExpanded":"Open","chat.toolPart.openFileAtFirstChange":"Open file at first change","chat.toolPart.openFileDiff":"Open file diff","chat.toolPart.copyOutput":"Copy output","chat.toolPart.copiedOutput":"Copied output","chat.toolPart.copyOutputFailed":"Failed to copy output","chat.toolPart.openSubtask":"Open {type} subtask","chat.todo.total":"Total","chat.todo.inProgress":"In Progress","chat.todo.pending":"Pending","chat.todo.completed":"Completed","chat.todo.cancelled":"Cancelled","chat.permissionCard.workingDirectory":"Working Directory:","chat.permissionCard.timeout":"Timeout:","chat.permissionCard.request":"Request:","chat.permissionCard.headers":"Headers:","chat.permissionCard.body":"Body:","chat.permissionCard.action":"Action:","chat.permissionCard.patterns":"Patterns:","chat.permissionToast.sessionFallback":"Session","chat.permissionToast.permissionFallback":"Permission details unavailable","chat.permissionToast.labels.session":"Session:","chat.permissionToast.labels.permission":"Permission:","chat.permissionToast.actions.once":"Once","chat.permissionToast.actions.always":"Always","chat.permissionToast.actions.deny":"Deny","chat.permissionToast.actions.approveOnceAria":"Approve once","chat.permissionToast.actions.approveOnceAriaWithSession":"Approve once for {session}","chat.permissionToast.actions.approveAlwaysAria":"Approve always","chat.permissionToast.actions.approveAlwaysAriaWithSession":"Approve always for {session}","chat.permissionToast.actions.denyAria":"Deny permission","chat.permissionToast.actions.denyAriaWithSession":"Deny permission for {session}","chat.permissionRequest.required":"Permission required:","chat.permissionRequest.actions.once":"Once","chat.permissionRequest.actions.always":"Always","chat.permissionRequest.actions.reject":"Reject","chat.modelControls.provider":"Provider","chat.modelControls.capability.toolCalling":"Tool calling","chat.modelControls.capability.reasoning":"Reasoning","chat.modelControls.modality.text":"Text","chat.modelControls.modality.image":"Image","chat.modelControls.modality.video":"Video","chat.modelControls.modality.audio":"Audio","chat.modelControls.modality.pdf":"PDF","chat.modelControls.capabilities":"Capabilities","chat.modelControls.modalities":"Modalities","chat.modelControls.input":"Input","chat.modelControls.output":"Output","chat.modelControls.limits":"Limits","chat.modelControls.context":"Context","chat.modelControls.metadata":"Metadata","chat.modelControls.knowledge":"Knowledge","chat.modelControls.release":"Release","chat.modelControls.mode":"Mode","chat.modelControls.model":"Model","chat.modelControls.temperature":"Temperature","chat.modelControls.topP":"Top P","chat.modelControls.permissions":"Permissions","chat.modelControls.edit":"Edit","chat.modelControls.bash":"Bash","chat.modelControls.webFetch":"WebFetch","chat.modelControls.customPrompt":"Custom Prompt","chat.modelControls.selectModel":"Select model","chat.modelControls.thinking":"Thinking","chat.modelControls.inheritedVariantTooltip":"Thinking: {variant}, this model's default","chat.modelControls.rememberedVariantTooltip":"Thinking: {variant}, last used with this model","chat.modelControls.default":"Default","chat.modelControls.selectAgent":"Select agent","chat.modelControls.costPerMillion":"Cost ($/1M tokens)","chat.modelControls.metadataUnavailable":"Model metadata unavailable.","chat.modelControls.addNewProvider":"Add new provider","chat.modelControls.noAgentSelected":"No agent selected.","chat.modelControls.agentUnavailable":`Agent "{agent}" isn't available in this session's folder. Pick another agent.`,"chat.modelControls.modelUnavailable":`Model "{model}" isn't available anymore. Its provider was removed or switched off. Pick another model.`,"chat.modelControls.searchModels":"Search models","chat.modelControls.modelListAria":"Models","chat.modelControls.searchAgents":"Search agents","chat.modelControls.noModelsFound":"No models found","chat.modelControls.favorites":"Favorites","chat.modelControls.agentsSection":"Agents","chat.modelControls.favoriteAgentsCycleHint":"{shortcut} to cycle","chat.modelControls.favoriteAgentsTapHint":"Tap the agent to cycle","chat.modelControls.noAgentsFound":"No agents found","chat.modelControls.recent":"Recent","chat.modelControls.addToFavorites":"Add to favorites","chat.modelControls.removeFromFavorites":"Remove from favorites","chat.modelControls.useModel":"Use model","chat.modelControls.favoriteAria":"Favorite","chat.modelControls.unfavoriteAria":"Unfavorite","chat.modelControls.collapseProvider":"Collapse provider","chat.modelControls.expandProvider":"Expand provider","chat.modelControls.keyboardHint":"↑↓ navigate{thinking} • Enter select • Esc close","chat.modelControls.keyboardHintNavigate":"↑↓ navigate","chat.modelControls.keyboardHintSwitchAgent":"{shortcut} switch agent","chat.modelControls.keyboardHintSwitchThinking":"{shortcut} switch","chat.modelControls.keyboardHintThinking":"←→ thinking","chat.modelControls.reorderProviderTitle":"Drag to reorder provider","chat.modelControls.permissionLabel.custom":"Custom","chat.modelControls.permissionLabel.allow":"Allow","chat.modelControls.permissionLabel.deny":"Deny","chat.modelControls.permissionLabel.ask":"Ask","chat.modelControls.modeValue.primary":"Primary","chat.modelControls.modeValue.subagent":"Subagent","chat.modelControls.modeValue.all":"All","chat.modelControls.modeValue.none":"—","chat.reasoningTrace.thinking":"Thinking","chat.reasoningTrace.expandAria":"Expand reasoning trace","chat.reasoningTrace.collapseAria":"Collapse reasoning trace","chat.reasoningTrace.thought":"Thought","chat.messageBody.subtask.title":"Delegated task","chat.messageBody.subtask.hidePrompt":"Hide prompt","chat.messageBody.subtask.showPrompt":"Show prompt","chat.messageBody.subtask.openSession":"Open subtask session","chat.messageBody.shellCommand.copied":"Copied","chat.messageBody.shellCommand.copyOutput":"Copy output","commandPalette.title":"Command Palette","commandPalette.description":"Search files, sessions, and commands.","commandPalette.input.placeholder":"Search files, sessions, commands...","commandPalette.empty.noResults":"No results found.","commandPalette.empty.searchingFiles":"Searching files...","commandPalette.item.newSession":"New Session","commandPalette.item.newMiniChat":"New Mini Chat Window","commandPalette.item.quickWorktree":"Quick Worktree","commandPalette.item.newWorktreeDialog":"New Worktree…","commandPalette.item.addProject":"Add Project","commandPalette.item.showSessionSwitcher":"Show Session Switcher","commandPalette.item.toggleSidebar":"Toggle Sidebar","commandPalette.item.showContextUsage":"Show Context Usage","commandPalette.item.toggleTerminal":"Toggle Terminal","commandPalette.item.cycleTheme":"Cycle theme","commandPalette.item.showOpenCodeStatus":"Show diagnostic timeline","commandPalette.item.restartOpenCode":"Restart OpenCode","commandPalette.item.toggleMemoryDebug":"Toggle memory debug panel","commandPalette.item.pinSession":"Pin or unpin session","commandPalette.item.copySessionId":"Copy session ID","commandPalette.item.openMultiRun":"Run in parallel","commandPalette.item.openArchive":"Open archived sessions","commandPalette.item.openNotes":"Open notes surface","commandPalette.item.openTodos":"Open todos surface","commandPalette.item.openSettings":"Open Settings...","commandPalette.session.untitled":"Untitled Session","commandPalette.item.reloadUi":"Reload UI","commandPalette.group.openFiles":"Open files","commandPalette.group.commands":"Commands","commandPalette.group.settings":"Settings","chat.search.placeholder":"Search this conversation","chat.search.position":"{current} of {total}","chat.search.noResults":"No results","chat.search.searching":"Searching…","chat.search.tooShort":"3+ characters","chat.search.error":"Couldn't search","chat.search.unavailable":"Not available here","chat.search.previous":"Previous match","chat.search.next":"Next match","chat.search.close":"Close search","commandPalette.group.sessions":"Sessions","commandPalette.group.messages":"Messages","commandPalette.messages.showAll":"Show all message results","commandPalette.messages.placeholder":"Search messages…","commandPalette.messages.inReasoning":"Thinking","commandPalette.messages.indexing":"Still indexing older conversations: {done} of {total}.","commandPalette.messages.loadMore":"Load more","commandPalette.messages.byYou":"Your message","commandPalette.messages.byAgent":"Agent reply","commandPalette.group.files":"Files","commandPalette.group.projects":"Projects","commandPalette.footer.navigate":"to navigate","commandPalette.footer.open":"to open","commandPalette.footer.close":"to close","openCodeStatusDialog.title":"Diagnostic timeline","openCodeStatusDialog.description":"Local events in time order. Private log text and remote sources are excluded.","openCodeStatusDialog.actions.download":"Download log","openCodeStatusDialog.toast.collectFailed":"Failed to collect diagnostics","openCodeStatusDialog.actions.copy":"Copy","openCodeStatusDialog.empty.noData":"No data.","openCodeStatusDialog.toast.copiedTitle":"Copied","openCodeStatusDialog.toast.copiedDescription":"Diagnostic log copied to clipboard","openCodeStatusDialog.toast.copyFailed":"Failed to copy diagnostic log","saveProjectPlanDialog.title":"Save Project Plan","saveProjectPlanDialog.description":"Save this plan into your project as a Markdown file.","saveProjectPlanDialog.field.title":"Title","saveProjectPlanDialog.field.titlePlaceholder":"Plan title","saveProjectPlanDialog.field.contentPreview":"Content preview","saveProjectPlanDialog.actions.cancel":"Cancel","saveProjectPlanDialog.actions.save":"Save","saveProjectPlanDialog.actions.saving":"Saving...","branchPickerDialog.title":"Branch Picker","branchPickerDialog.description.localBranchesForProject":"Local branches for {project}","branchPickerDialog.description.selectProject":"Select a project to view branches","branchPickerDialog.search.placeholder":"Search branches...","branchPickerDialog.search.renameBranchPlaceholder":"Rename branch","branchPickerDialog.state.noProjectSelected":"No project selected","branchPickerDialog.state.loadingBranches":"Loading branches...","branchPickerDialog.state.noMatchingBranches":"No matching branches","branchPickerDialog.state.noBranchesFound":"No branches found","branchPickerDialog.badge.head":"HEAD","branchPickerDialog.badge.worktree":"worktree","branchPickerDialog.actions.createWorktreeAria":"Create worktree from branch","branchPickerDialog.actions.renameAria":"Rename branch","branchPickerDialog.actions.deleteAria":"Delete branch","branchPickerDialog.actions.deleteWorktreeAria":"Remove worktree","branchPickerDialog.actions.confirmRenameAria":"Confirm rename","branchPickerDialog.actions.cancelRenameAria":"Cancel rename","branchPickerDialog.actions.confirmDeleteAria":"Confirm delete branch","branchPickerDialog.actions.cancelDeleteAria":"Cancel delete branch","branchPickerDialog.actions.deletePrompt":"Delete","branchPickerDialog.actions.forceDeletePrompt":"Force Delete","branchPickerDialog.tooltip.createWorktree":"Create worktree","branchPickerDialog.tooltip.worktreeAlreadyExists":"Worktree already exists","branchPickerDialog.tooltip.rename":"Rename branch","branchPickerDialog.tooltip.renameDisabledForRoot":"Cannot rename root branch","branchPickerDialog.tooltip.delete":"Delete branch","branchPickerDialog.tooltip.deleteCurrentBranch":"Cannot delete current branch","branchPickerDialog.tooltip.deleteDisabledForRoot":"Cannot delete root branch","branchPickerDialog.tooltip.deleteWorktree":"Remove worktree","branchPickerDialog.tooltip.deleteWorktreeRootProtected":"Cannot remove root worktree","branchPickerDialog.toast.branchRenamed":"Branch renamed","branchPickerDialog.toast.failedToRenameBranch":"Failed to rename branch","branchPickerDialog.toast.branchDeleted":"Branch deleted","branchPickerDialog.toast.branchNotMerged":"Branch is not fully merged","branchPickerDialog.toast.confirmAgainToForceDelete":"Confirm again to force delete","branchPickerDialog.toast.failedToDeleteBranch":"Failed to delete branch","branchPickerDialog.toast.worktreeCreated":"Worktree created","branchPickerDialog.toast.failedToCreateWorktree":"Failed to create worktree","branchPickerDialog.error.failedToLoad":"Failed to load branches","branchPickerDialog.error.renameRejected":"Rename was rejected","branchPickerDialog.error.renameFailed":"Failed to rename branch","branchPickerDialog.error.deleteRejected":"Delete was rejected","branchPickerDialog.error.deleteFailed":"Failed to delete branch","branchPickerDialog.error.createWorktreeFailed":"Failed to create worktree","projectEditDialog.title":"Edit project","projectEditDialog.field.name":"Name","projectEditDialog.field.namePlaceholder":"Project name","projectEditDialog.field.color":"Color","projectEditDialog.field.icon":"Icon","projectEditDialog.field.preview":"Preview","projectEditDialog.field.iconBackground":"Icon Background","projectEditDialog.field.iconBackgroundAria":"Project icon background color","projectEditDialog.option.none":"None","projectEditDialog.actions.uploadIcon":"Upload Icon","projectEditDialog.actions.uploading":"Uploading...","projectEditDialog.actions.discoverFavicon":"Discover Favicon","projectEditDialog.actions.discovering":"Discovering...","projectEditDialog.actions.removeProjectIcon":"Remove Project Icon","projectEditDialog.actions.removing":"Removing...","projectEditDialog.actions.undoRemove":"Undo Remove","projectEditDialog.actions.clear":"Clear","projectEditDialog.actions.cancel":"Cancel","projectEditDialog.actions.save":"Save","projectEditDialog.toast.failedToUploadIcon":"Failed to upload project icon","projectEditDialog.toast.iconUpdated":"Project icon updated","projectEditDialog.toast.failedToRemoveIcon":"Failed to remove project icon","projectEditDialog.toast.iconRemoved":"Project icon removed","projectEditDialog.toast.failedToDiscoverIcon":"Failed to discover project icon","projectEditDialog.toast.customIconAlreadySet":"Custom icon already set for this project","projectEditDialog.toast.iconDiscovered":"Project icon discovered","openInApp.actions.open":"Open","openInApp.actions.openInAria":"Open in {app}","openInApp.actions.copyPath":"Copy Path","openInApp.actions.refreshApps":"Refresh Apps","openInApp.toast.pathCopied":"Path copied to clipboard","projectActions.actions.addActionAria":"Add action","projectActions.actions.addAction":"Add action","projectActions.actions.addNewAction":"Add new action","projectActions.actions.autoDiscover":"Auto-discover dev server","projectActions.menu.sharedBadge":"repo","projects.sharedTrust.title":"Run the commands stored in this repository?","projects.sharedTrust.description":"{path} in this repository defines commands that run on this machine. Trust them once, and OpenChamber asks again only when they change.","projects.sharedTrust.setupCommands":"Worktree setup commands","projects.sharedTrust.teardownCommands":"Worktree teardown commands","projects.sharedTrust.actions":"Actions","projects.sharedTrust.skip":"Not this time","projects.sharedTrust.trust":"Trust and run","projects.opencodeTrust.title":"Let OpenCode run code from this folder?","projects.opencodeTrust.description":"OpenCode runs the plugins and commands in the configuration of {path} as soon as it opens the folder. Trust them once, and OpenChamber asks again only when they change.","projects.opencodeTrust.plugins":"Plugins","projects.opencodeTrust.commands":"Commands","projects.opencodeTrust.kind.package":"{name} (npm package)","projects.opencodeTrust.kind.config":"{path}: a configuration file OpenChamber can't read","projects.opencodeTrust.kind.mcp":"MCP server {name}","projects.opencodeTrust.kind.lsp":"Language server {name}","projects.opencodeTrust.kind.formatter":"Formatter {name}","projects.opencodeTrust.kind.shell":"Shell","projects.opencodeTrust.paused":"Without trust, agents can't work in this folder, but you can still browse its files and Git changes.","projects.opencodeTrust.skip":"Not this time","projects.opencodeTrust.trust":"Trust and open","projects.opencodeTrust.saveFailed":"Couldn't save your answer. Try again.","projectActions.actions.autoDiscoverTooltip":"Automatically discover and run the development server","projectActions.actions.chooseActionAria":"Choose project action","projectActions.actions.openPreview":"Open Preview","projectActions.actions.runNamedAria":"Run {name}","projectActions.actions.stopNamedAria":"Stop {name}","projectActions.label.fallbackAction":"Action","projectActions.toast.openedUrlFromOutput":"Opened URL from action output","projectActions.toast.openedForwardedUrl":"Opened forwarded URL","projectActions.toast.openedActionUrl":"Opened action URL","projectActions.error.noActiveDirectory":"No active directory","projectActions.error.noActiveDirectoryForAction":"No active directory for action","projectActions.error.failedToCreateTerminalSession":"Failed to create terminal session","projectActions.error.invalidCustomUrlFormat":"Invalid custom URL format","projectActions.error.openUrlTemplateUnresolved":"Couldn't read the branch for the action URL","projectActions.error.selectedDesktopSshForwardUnavailable":"Selected desktop SSH forward is unavailable","projectActions.error.failedToRunAction":"Failed to run action","sessionAuth.error.rateLimitTitle":"Too many attempts","sessionAuth.error.networkTitle":"Unable to reach server","sessionAuth.error.rateLimitDescriptionSingle":"Please wait {minutes} minute before trying again.","sessionAuth.error.rateLimitDescriptionPlural":"Please wait {minutes} minutes before trying again.","sessionAuth.error.networkDescription":"We could not verify the UI session. If you're opening OpenChamber from another device on your local network, make sure Desktop Network Access is enabled on the desktop app and use the LAN address shown in Settings.","sessionAuth.error.retry":"Retry","sessionAuth.error.passkeySetupFailed":"Passkey setup failed.","sessionAuth.error.incorrectPassword":"Incorrect password. Try again.","sessionAuth.error.unexpectedResponse":"Unexpected response from server.","sessionAuth.error.networkRetry":"Network error. Check connection and retry.","sessionAuth.error.passkeySignInCanceled":"Passkey sign-in was canceled.","sessionAuth.error.enterPasswordForPasskey":"Enter your password to add a passkey.","sessionAuth.locked.tunnelTitle":"Tunnel access required","sessionAuth.expired.banner":"Your session expired — log in to continue.","sessionAuth.expired.loginAction":"Log in","sessionAuth.expired.sendBlocked":"Session expired — log in to send messages.","sessionAuth.locked.unlockTitle":"Unlock OpenChamber","sessionAuth.locked.tunnelDescription":"Open this tunnel using the one-time connect link from the desktop app.","sessionAuth.locked.passwordDescription":"This session is password-protected.","sessionAuth.locked.hostSwitcherHint":"Use Local if remote is unreachable.","sessionAuth.actions.cancelPasskey":"Cancel passkey","sessionAuth.actions.usePasskey":"Use passkey","sessionAuth.actions.unlockingAria":"Unlocking","sessionAuth.actions.unlockAria":"Unlock","sessionAuth.actions.trustDevice":"Trust this device","sessionAuth.actions.trustDeviceAria":"Trust this device","sessionAuth.actions.cancelPasskeySetup":"Cancel passkey setup","sessionAuth.actions.addPasskey":"Add passkey","sessionAuth.password.placeholder":"Enter password","sessionAuth.toast.passkeyAdded":"Passkey added","sessionAuth.toast.passkeySetupCanceled":"Passkey setup canceled","desktopHostSwitcher.title":"Instance","desktopHostSwitcher.description":"Switch between Local and remote OpenChamber servers","desktopHostSwitcher.header.current":"Current","desktopHostSwitcher.header.default":"Default","desktopHostSwitcher.header.currentColon":"Current:","desktopHostSwitcher.header.currentDefaultColon":"Current default:","desktopHostSwitcher.status.connected":"Connected","desktopHostSwitcher.status.authRequired":"Auth required","desktopHostSwitcher.status.checking":"Checking","desktopHostSwitcher.status.updateRecommended":"Update recommended","desktopHostSwitcher.status.incompatible":"Incompatible","desktopHostSwitcher.status.wrongService":"Wrong service","desktopHostSwitcher.status.unreachable":"Unreachable","desktopHostSwitcher.status.relayLimit":"Relay limit reached","desktopHostSwitcher.status.unknown":"Unknown","desktopHostSwitcher.status.ping":" · {ms}ms ping","desktopHostSwitcher.statusAria":"Instance status","desktopHostSwitcher.sshPhase.ready":"Ready","desktopHostSwitcher.sshPhase.error":"Error","desktopHostSwitcher.sshPhase.reconnecting":"Reconnecting","desktopHostSwitcher.sshPhase.resolvingConfig":"Resolving config","desktopHostSwitcher.sshPhase.checkingAuth":"Checking auth","desktopHostSwitcher.sshPhase.connectingSsh":"Connecting SSH","desktopHostSwitcher.sshPhase.probingRemote":"Probing remote","desktopHostSwitcher.sshPhase.installing":"Installing","desktopHostSwitcher.sshPhase.updating":"Updating","desktopHostSwitcher.sshPhase.detectingServer":"Detecting server","desktopHostSwitcher.sshPhase.startingServer":"Starting server","desktopHostSwitcher.sshPhase.forwardingPorts":"Forwarding ports","desktopHostSwitcher.sshPhase.idle":"Idle","desktopHostSwitcher.ssh.needInstancesHint":"Need SSH instances? Manage them in Settings.","desktopHostSwitcher.ssh.instanceFallback":"SSH instance","desktopHostSwitcher.ssh.connectingTo":"Connecting to {host}","desktopHostSwitcher.actions.refresh":"Refresh","desktopHostSwitcher.actions.refreshInstancesAria":"Refresh instances","desktopHostSwitcher.actions.remoteSsh":"Remote SSH","desktopHostSwitcher.actions.instanceActionsAria":"Instance actions","desktopHostSwitcher.actions.edit":"Edit","desktopHostSwitcher.actions.delete":"Delete","desktopHostSwitcher.actions.connect":"Connect","desktopHostSwitcher.actions.defaultInstanceAria":"Default instance","desktopHostSwitcher.actions.setAsDefaultAria":"Set as default","desktopHostSwitcher.actions.setAsDefault":"Set as default","desktopHostSwitcher.actions.openInNewWindowAria":"Open in new window","desktopHostSwitcher.actions.openInNewWindow":"Open in new window","desktopHostSwitcher.actions.addInstance":"Add instance","desktopHostSwitcher.actions.cancel":"Cancel","desktopHostSwitcher.actions.save":"Save","desktopHostSwitcher.actions.add":"Add","desktopHostSwitcher.actions.switchToLocal":"Switch to Local","desktopHostSwitcher.actions.retry":"Retry","desktopHostSwitcher.actions.switchInstanceAria":"Switch instance","desktopHostSwitcher.actions.switchInstance":"Switch instance","desktopHostSwitcher.actions.switchToAria":"Switch to {instance}","desktopHostSwitcher.field.labelPlaceholder":"Label","desktopHostSwitcher.field.labelOptionalPlaceholder":"Label (optional)","desktopHostSwitcher.field.urlPlaceholder":"https://host:port","desktopHostSwitcher.state.limitedOnPage":"Instance switcher is limited on this page. Use Local to recover.","desktopHostSwitcher.state.loading":"Loading...","desktopHostSwitcher.state.instanceUnreachable":"Instance unreachable","desktopHostSwitcher.edit.title":"Edit instance","desktopHostSwitcher.add.title":"Add instance","desktopHostSwitcher.error.failedToSave":"Failed to save","desktopHostSwitcher.error.failedToLoad":"Failed to load","desktopHostSwitcher.error.invalidUrl":"Invalid URL (must be http/https)","desktopHostSwitcher.error.pairingRejected":"Pairing link is invalid or expired. Generate a new one.","desktopHostSwitcher.error.pairingFailed":"Pairing failed (HTTP {status}).","desktopHostSwitcher.error.pairingInvalidResponse":"The server returned an invalid pairing response.","desktopHostSwitcher.error.failedToOpenNewWindow":"Failed to open new window","desktopHostSwitcher.instance.local":"Local","desktopHostSwitcher.instance.fallback":"Instance","desktopHostSwitcher.startup.title":"Default SSH instance unavailable","desktopHostSwitcher.startup.connectingTo":"Connecting to {host}...","desktopHostSwitcher.startup.failed":"Failed to connect the default SSH instance.","desktopHostSwitcher.toast.sshConnected":'SSH instance "{host}" connected',"desktopHostSwitcher.toast.sshFailedToConnect":'SSH instance "{host}" failed to connect',"desktopHostSwitcher.toast.instanceUnreachable":'Instance "{host}" is unreachable',"desktopHostSwitcher.toast.relayLimit":'The relay refused the connection to "{host}": too many devices or reconnects. Close OpenChamber on another device or wait a minute, then try again.',"relayConnection.limitReached.title":"The relay refused the connection","relayConnection.limitReached.description":"Too many devices or reconnects for this instance. Close OpenChamber on another device or wait a minute, then try again.","relayConnection.limitReached.retry":"Try again","miniChat.header.newSession":"New session","miniChat.header.session":"Session","miniChat.header.defaultAgent":"Default agent","miniChat.header.noModel":"No model","miniChat.status.busy":"Running","miniChat.status.retry":"Retrying","miniChat.status.idle":"Idle","miniChat.actions.pin":"Pin above other windows","miniChat.actions.unpin":"Unpin window","miniChat.actions.pinAria":"Pin Mini Chat window","miniChat.actions.unpinAria":"Unpin Mini Chat window","miniChat.actions.openMain":"Open in main window","miniChat.actions.openMainAria":"Open session in main window","miniChat.unavailable.title":"Session unavailable","miniChat.unavailable.description":"This session could not be loaded. It may have been deleted, archived, or opened from a different project context.","sessions.sidebar.session.menu.openMiniChatWindow":"Open in Mini Chat Window","header.windowControls.groupAria":"Window controls","header.windowControls.minimize":"Minimize window","header.windowControls.maximize":"Maximize window","header.windowControls.restore":"Restore window","header.windowControls.close":"Close window","errorBoundary.title":"Something went wrong","errorBoundary.description":"The application encountered an unexpected error. This has been logged for debugging.","errorBoundary.state.unknownError":"Unknown error","errorBoundary.state.componentStackLabel":"Component stack:","errorBoundary.actions.errorDetails":"Error details","errorBoundary.actions.tryAgain":"Try again","errorBoundary.actions.copy":"Copy","errorBoundary.actions.copied":"Copied","jsonTreeView.error.emptyJson":"Empty JSON content","jsonTreeView.error.invalidJson":"Invalid JSON","jsonTreeView.error.invalidJsonTitle":"Invalid JSON","jsonTreeView.actions.expandAll":"Expand All","jsonTreeView.actions.collapseAll":"Collapse All","numberInput.actions.decreaseAria":"Decrease value","numberInput.actions.increaseAria":"Increase value","goToLineDialog.field.linePlaceholderShort":"Line","goToLineDialog.field.linePlaceholder":"Line number","goToLineDialog.actions.go":"Go","goToLineDialog.helper.editorUnavailable":"Editor unavailable.","goToLineDialog.helper.currentLineRange":"Current Line: {current}. Type a line number between 1 and {max} to navigate to.","goToLineDialog.helper.goToLine":"Go to line {line}","dialog.common.actions.close":"Close","session.newWorktree.trust.run":"Run","session.newWorktree.trust.skip":"Skip","session.newWorktree.trust.title":"Run setup on code from a fork?","gitView.publish.contributorCommitFirstAction":"Continue","gitView.publish.contributorCommitFirstTitle":"Commit, then choose where to push?","dialog.common.actions.cancel":"Cancel","filesView.toast.relativePathCopied":"Relative path copied","filesView.tree.menu.copyRelativePath":"Copy Relative Path","multiRun.branchSelector.placeholder.selectSourceBranch":"Select source branch...","multiRun.branchSelector.status.loadingBranches":"Loading branches...","multiRun.branchSelector.status.noBranchesFound":"No branches found","multiRun.branchSelector.status.notInGitRepository":"Not in a git repository.","multiRun.branchSelector.groups.localBranches":"Local branches","multiRun.branchSelector.groups.remoteBranches":"Remote branches","multiRun.window.actions.closeAria":"Close multi-run","multiRun.window.description":"OpenChamber Multi-Run window.","voice.status.idle":"Voice Ready","voice.status.listening":"Listening...","voice.status.processing":"Processing...","voice.status.speaking":"Speaking...","voice.status.error":"Voice Error","voice.status.conversationModeActiveAria":"Conversation mode active","voice.action.finishAndTranscribe":"Finish and transcribe voice input","onboarding.common.actions.back":"Back","onboarding.common.copyToClipboard":"Copy to clipboard","onboarding.common.status.copiedToClipboard":"Copied to clipboard","onboarding.chooser.title":"Welcome to OpenChamber","onboarding.chooser.description":"Choose how you want to connect to get started.","onboarding.chooser.tabs.localInstall":"Local Install","onboarding.chooser.tabs.connectRemote":"Connect Remote","onboarding.localSetup.title":"Setting Up OpenCode","onboarding.localSetup.description":"Install OpenCode v2 CLI to continue.","onboarding.localSetup.dialog.selectOpencodeBinary":"Select opencode binary","onboarding.localSetup.errors.cliNotReady":"OpenCode CLI is not ready yet. Please confirm installation is complete and try again.","onboarding.localSetup.errors.detectionFailed":"Detection failed","onboarding.localSetup.windows.title":"Windows setup","onboarding.localSetup.windows.stepInstallWsl":"Install OpenCode with the command below.","onboarding.localSetup.windows.stepInstallWslSuffix":"","onboarding.localSetup.windows.stepRunInstallInWsl":"Run the install command below in a Windows terminal.","onboarding.localSetup.windows.stepSetBinaryPath":"If OpenChamber does not detect OpenCode automatically, set the binary path below.","onboarding.localSetup.intro":"Install OpenCode v2 CLI to continue.","onboarding.localSetup.docs.windows":"Installation guide","onboarding.localSetup.docs.default":"Installation guide","onboarding.localSetup.actions.checking":"Checking…","onboarding.localSetup.actions.checkAndContinue":"I've completed installation, check and continue","onboarding.localSetup.actions.checkNow":"Check now","onboarding.localSetup.helper.checkAndContinue":"Click to check if OpenCode CLI is available. If successful, you'll automatically enter the main screen.","onboarding.localSetup.status.watching":"Waiting for OpenCode v2","onboarding.localSetup.status.autoContinue":"We'll continue automatically once it's detected.","onboarding.localSetup.field.alreadyInstalled":"Already installed? Set the OpenCode CLI path:","onboarding.localSetup.advanced.title":"Set a custom binary path","onboarding.localSetup.troubleshoot.title":"Having trouble?","onboarding.localSetup.actions.browse":"Browse","onboarding.localSetup.actions.apply":"Apply","onboarding.localSetup.helper.saveAndReload":"Saves to OpenChamber settings and reloads OpenCode configuration.","onboarding.localSetup.helper.pinnedByAdministrator":"Your administrator set this path. If OpenCode isn’t there, ask them to install it.","onboarding.localSetup.remotePreference":"Prefer to use a remote server?","onboarding.localSetup.actions.connectRemoteServer":"Connect to Remote Server →","onboarding.localSetup.windows.hintInstallInWsl":"On Windows, install and run OpenCode natively.","onboarding.localSetup.windows.hintDetectionFailed":"If detection fails, set a native path such as opencode.cmd or opencode.exe.","onboarding.localSetup.hint.ensurePath":"Already installed? Make sure opencode is in your PATH.","onboarding.localSetup.hint.setEnv":"Or set OPENCODE_BINARY environment variable.","onboarding.localSetup.hint.missingRuntime":'If you see "env: node: No such file or directory" or "env: bun: No such file or directory", install that runtime or ensure it is on PATH.',"onboarding.remoteConnection.title":"Connect to Remote Server","onboarding.remoteConnection.titleRecovery":"Connect to a Different Server","onboarding.remoteConnection.description":"Enter the address of an OpenChamber server to connect to.","onboarding.remoteConnection.field.serverAddress":"Server Address","onboarding.remoteConnection.field.serverAddressPlaceholder":"https://your-server.example.com:4096","onboarding.remoteConnection.field.nameOptional":"Name (optional)","onboarding.remoteConnection.field.namePlaceholder":"My Remote Server","onboarding.remoteConnection.errors.connectionTestFailed":"Connection test failed","onboarding.remoteConnection.errors.failedToSaveConnection":"Failed to save connection","onboarding.remoteConnection.status.connectedSuccessfully":"Connected successfully ({latencyMs}ms)","onboarding.remoteConnection.status.authWarning":"Server requires authentication. You can still connect.","onboarding.remoteConnection.status.connectionFailed":"Connection Failed","onboarding.remoteConnection.status.suggestionsUnreachable":"Suggestions: Check the server address, verify the server is running, or check your network connection.","onboarding.remoteConnection.status.suggestionsWrongService":"Suggestions: Verify the URL points to an OpenChamber server, or contact the server administrator.","onboarding.remoteConnection.actions.testing":"Testing…","onboarding.remoteConnection.actions.testConnection":"Test Connection","onboarding.remoteConnection.actions.connectAndRestart":"Connect & Restart","onboarding.remoteConnection.actions.whatToDo":"What would you like to do?","onboarding.remoteConnection.actions.chooseDifferentServer":"Choose Different Server","onboarding.remoteConnection.actions.useLocalInstead":"Use Local Instead","onboarding.remoteConnection.probe.authMessage":"Server requires authentication. You can still connect, but may need to provide credentials.","onboarding.remoteConnection.probe.updateRecommendedMessage":"This instance is running a different OpenChamber version. You can connect, but update both apps if something does not work.","onboarding.remoteConnection.probe.incompatibleMessage":"Server is running OpenChamber but is not compatible with this app version. Update OpenChamber on the server, then try again.","onboarding.remoteConnection.probe.wrongServiceMessage":"Server responded but is not running OpenChamber. Verify the address points to an OpenChamber server.","onboarding.remoteConnection.probe.unreachableMessage":"Server is unreachable. Check your network connection and verify the server address.","onboarding.desktopRecovery.localUnavailable.title":"Local OpenCode Unavailable","onboarding.desktopRecovery.localUnavailable.description":"OpenCode CLI could not be started or is not installed. Install OpenCode or connect to a remote server instead.","onboarding.desktopRecovery.localUnavailable.retry":"Retry Local","onboarding.desktopRecovery.localUnavailable.useLocal":"Set Up Local","onboarding.desktopRecovery.noDefaultConnection.title":"No Default Connection","onboarding.desktopRecovery.noDefaultConnection.description":"Your saved default connection could not be found. Choose how you want to connect.","onboarding.desktopRecovery.remoteUnreachable.title":"Remote Server Unreachable","onboarding.desktopRecovery.remoteUnreachable.description":'Could not connect to "{host}". Check your network connection and verify the server address.',"onboarding.desktopRecovery.remoteUnreachable.retry":"Retry Connection","onboarding.desktopRecovery.incompatibleServer.title":"Incompatible Server","onboarding.desktopRecovery.incompatibleServer.description":'The server at "{host}" is not running OpenChamber. Verify the address points to an OpenChamber server.',"onboarding.desktopRecovery.remoteIncompatible.title":"Server Update Required","onboarding.desktopRecovery.remoteIncompatible.description":'The OpenChamber server at "{host}" is not compatible with this app version. Update OpenChamber on the server, then try again.',"onboarding.desktopRecovery.remoteIncompatible.updateServer":"Update server","onboarding.desktopRecovery.remoteIncompatible.updatingServer":"Updating the server...","onboarding.desktopRecovery.remoteIncompatible.updatingHint":"The server installs the update and restarts. The app connects as soon as it is back.","onboarding.desktopRecovery.remoteIncompatible.updateRefused":"The server could not update itself.","onboarding.desktopRecovery.remoteIncompatible.updateAuth":"The server did not accept this app's sign-in, so it could not be updated from here.","onboarding.desktopRecovery.remoteIncompatible.updateTimeout":"The server has not come back with the new version yet. Check it, then retry the connection.","onboarding.desktopRecovery.remoteIncompatible.manualUpdate":"To update it by hand, run this on the server, then restart OpenChamber there:","onboarding.desktopRecovery.common.useLocal":"Use Local","onboarding.desktopRecovery.common.useRemote":"Use Remote","onboarding.desktopRecovery.actions.retrying":"Retrying…","onboarding.desktopRecovery.actions.retryConnection":"Retry Connection","projectConfigError.toast.title":"OpenCode can't load this project's config","projectConfigError.toast.unknownFile":"Project config","projectConfigError.toast.hint":"Fix the file, then retry. Other projects keep working.","projectConfigError.toast.retry":"Retry","projectConfigError.toast.retrying":"Retrying…","startup.initRecovery.title":"Startup failed","startup.serverOutdated.title":"Server update required","startup.serverOutdated.description":"The server runs OpenChamber {version}, and this app needs 2.0 or later there. Update OpenChamber on the server to continue.","startup.serverOutdated.checking":"Checking the server...","startup.serverOutdated.noUpdate":"The server did not offer an update it can install itself.","startup.initRecovery.openCodeUnavailable":"OpenChamber is reachable, but OpenCode is not ready. Check OpenCode on the server, then retry.","startup.initRecovery.binary":"OpenCode executable","startup.initRecovery.error":"OpenCode error","startup.initRecovery.serverUnreachable":"OpenChamber could not reach its server. Check that the server is running, then retry.","startup.initRecovery.loadAgentsFailed":"The server is running, but OpenCode could not load agents. Retry once the cause is fixed.","startup.initRecovery.unexpected":"OpenChamber could not finish starting. Retry once the cause is fixed.","startup.initRecovery.lastError":"Last error","startup.initRecovery.retry":"Retry","startup.initRecovery.retrying":"Retrying…","startup.overlay.slow":"Startup is taking longer than expected…","onboarding.desktopRecovery.placeholders.remoteServer":"the remote server","onboarding.desktopRecovery.placeholders.unknownServer":"unknown","vscodeLayout.title.chat":"Chat","vscodeLayout.title.newSession":"New session","vscodeLayout.title.sessions":"Sessions","vscodeLayout.title.sessionFallback":"Session","vscodeLayout.actions.backToSessionsAria":"Back to sessions","vscodeLayout.actions.archiveAllAria":"Archive all sessions","vscodeLayout.actions.archiveAllConfirm":"Archive all","vscodeLayout.actions.archiveAllSuccess":"Archived {count} session(s)","vscodeLayout.actions.archiveAllError":"Failed to archive {count} session(s)","vscodeLayout.actions.cancel":"Cancel","vscodeLayout.actions.newSessionAria":"New session","vscodeLayout.actions.resizeSessionsSidebarAria":"Resize sessions sidebar","vscodeLayout.actions.showSessionsAria":"Show sessions","vscodeLayout.actions.hideSessionsAria":"Hide sessions","vscodeLayout.actions.settingsAria":"Settings","updateDialog.header.updateAvailable":"Update Available","updateDialog.header.updating":"Updating OpenChamber...","updateDialog.changelog.title":"What's new","updateDialog.status.installingUpdate":"Installing update...","updateDialog.status.serverRestarting":"Server restarting...","updateDialog.status.waitingForServer":"Waiting for server...","updateDialog.status.autoReloadHint":"The page will reload automatically when the update is complete.","updateDialog.fallback.updateViaTerminal":"Or update via terminal:","updateDialog.desktopHostInstall":"OpenChamber {version} is available. Update it on the computer it runs on.","updateDialog.openCodeTooOld":"OpenChamber {version} needs OpenCode {required}. This server has {current}. Update OpenCode first.","updateDialog.actions.copyCommand":"Copy command","updateDialog.actions.copied":"Copied!","updateDialog.status.downloadingPayload":"Downloading update payload...","updateDialog.actions.downloadUpdate":"Download Update","updateDialog.status.downloading":"Downloading...","updateDialog.actions.restartToUpdate":"Restart to Update","updateDialog.status.restarting":"Restarting...","updateDialog.actions.updateNow":"Update Now","updateDialog.actions.openMobileUpdate":"Open update","updateDialog.status.updating":"Updating...","updateDialog.error.updateFailed":"Update failed","updateDialog.error.takingLonger":"Update is taking longer than expected. Wait a bit and refresh, or run: openchamber update","updateDialog.error.signatureRejected":"The downloaded update was rejected: its code signature does not match this installation. This usually means the running copy was not installed from an official signed release. Install OpenChamber from an official release, then update again.","updateDialog.error.updaterDisabled":"The updater stopped after a failed install. Quit OpenChamber, open it again, and retry the update.","updateDialog.error.restartFailed":"Could not restart to install the update.","updateDialog.error.restartUnavailable":"Installing the update requires the OpenChamber desktop app.","mobileUpdate.toast.available.title":"OpenChamber update available","mobileUpdate.toast.available.description":"Version {version} is ready for Android.","mobileUpdate.toast.actions.download":"Download","opencodeUpdate.toast.available.title":"OpenCode update","opencodeUpdate.toast.available.description":"Version {version} available.","opencodeUpdate.toast.available.manualDescription":"Version {version} available. Update OpenCode the way you installed it, then restart OpenChamber.","opencodeUpdate.toast.actions.update":"Update","opencodeUpdate.toast.actions.reload":"Reload OpenCode","opencodeUpdate.toast.upgrading.title":"Updating OpenCode...","opencodeUpdate.toast.upgrading.description":"Keep OpenChamber open.","opencodeUpdate.toast.updated.title":"OpenCode updated","opencodeUpdate.toast.updated.description":"Update installed.","opencodeUpdate.toast.updated.descriptionWithVersion":"Version {version} installed.","opencodeUpdate.toast.failed.title":"Could not update OpenCode","opencodeUpdate.toast.failed.description":"The OpenCode upgrade failed.","opencodeUpdate.toast.reload.message":"Restarting OpenCode...","memoryDebugPanel.title":"Debug Panel","memoryDebugPanel.tabs.memory":"Memory","memoryDebugPanel.tabs.streaming":"Streaming","memoryDebugPanel.tabs.requests":"Requests","memoryDebugPanel.section.sessionsInMemory":"Sessions in Memory","memoryDebugPanel.section.uiStreamingMetrics":"UI Streaming Metrics","memoryDebugPanel.section.vscodeBridgeMetrics":"VS Code Bridge Metrics","memoryDebugPanel.section.noUiSamples":"No UI streaming samples yet. Start a stream and keep this panel open.","memoryDebugPanel.section.noVscodeSamples":"No VS Code bridge samples yet.","memoryDebugPanel.metric.totalMessages":"Total Messages","memoryDebugPanel.metric.cachedSessions":"Cached Sessions","memoryDebugPanel.metric.userMessages":"User Messages","memoryDebugPanel.metric.assistantMessages":"Assistant Messages","memoryDebugPanel.metric.viewportWindow":"Viewport Window","memoryDebugPanel.metric.zombieTimeout":"Zombie Timeout","memoryDebugPanel.metric.githubTotalRequests":"GitHub Total Requests","memoryDebugPanel.metric.metrics":"Metrics","memoryDebugPanel.metric.samples":"Samples","memoryDebugPanel.metric.lastUpdate":"Last Update","memoryDebugPanel.metric.uiMetrics":"UI Metrics","memoryDebugPanel.metric.vscodeMetrics":"VS Code Metrics","memoryDebugPanel.metric.messageListRenders":"MsgList Renders","memoryDebugPanel.metric.messageListStreamRenders":"MsgList Stream Renders","memoryDebugPanel.metric.chatMessageRenders":"ChatMessage Renders","memoryDebugPanel.metric.chatMessageStreamRenders":"ChatMessage Stream Renders","memoryDebugPanel.metric.chatMessageStaticDuringStream":"ChatMessage Static During Stream","memoryDebugPanel.metric.chatMessageStaticOutsideActiveTurn":"ChatMessage Static Outside Active Turn","memoryDebugPanel.metric.messagesValue":"{count} messages","memoryDebugPanel.metric.minutesValue":"{count} minutes","memoryDebugPanel.metric.msgsValue":"{count} msgs","memoryDebugPanel.metric.roleMsgsValue":"U {user} / A {assistant}","memoryDebugPanel.metric.countValue":"count {value}","memoryDebugPanel.metric.avgValue":"avg {value}","memoryDebugPanel.metric.maxValue":"max {value}","memoryDebugPanel.metric.totalValue":"total {value}","memoryDebugPanel.actions.logState":"Log State","memoryDebugPanel.actions.copyJson":"Copy JSON","memoryDebugPanel.tooltip.logCurrentState":"Log current memory state to browser console","memoryDebugPanel.streaming.copy.copied":"Streaming debug JSON copied","memoryDebugPanel.streaming.copy.failed":"Failed to copy JSON","memoryDebugPanel.streaming.copy.hint":"Copy exports both UI and VS Code streaming metrics as JSON","memoryDebugPanel.requests.inFlight":"In flight","memoryDebugPanel.requests.peak":"Peak","memoryDebugPanel.requests.duration":"Duration","memoryDebugPanel.requests.totalRequests":"Total Requests","memoryDebugPanel.requests.tracking":"Tracking","memoryDebugPanel.requests.now":"now","memoryDebugPanel.requests.noSamples":"No requests tracked yet. Keep this panel open to record fetch activity.","memoryDebugPanel.requests.chartLabel":"Fetch requests in flight over time, peak {peak}","memoryDebugPanel.requests.windowHint":"last {seconds}s","memoryDebugPanel.requests.percentileChartLabel":"In-flight request age percentiles (p50, p90, p99, max) over time","memoryDebugPanel.common.idle":"idle","memoryDebugPanel.common.live":"live","memoryDebugPanel.common.notAvailable":"n/a","memoryDebugPanel.common.untitled":"Untitled","directoryTree.field.newDirectoryPlaceholder":"new_directory","textarea.resizeHandleAria":"Resize textarea","sidebar.resize.leftPanelAria":"Resize left panel","sidebar.resize.rightPanelAria":"Resize right panel","mainLayout.mobile.closeDrawerAria":"Close drawer","sortableTabsStrip.aria.tabs":"Tabs","openChamberLogo.aria.logo":"OpenChamber logo","markdownRenderer.code.proposal":"Proposal","markdownRenderer.code.actions.copyTitle":"Copy code","markdownRenderer.code.actions.copiedTitle":"Copied","markdownRenderer.code.actions.runTitle":"Run command. The agent continues from its output","markdownRenderer.code.actions.stopTitle":"Stop command","markdownRenderer.code.run.startFailed":"Could not start the command","markdownRenderer.code.run.running":"Running","markdownRenderer.code.run.finished":"Finished","markdownRenderer.code.run.failed":"Exit code {code}","markdownRenderer.code.run.stopped":"Stopped","markdownRenderer.table.actions.copyTitle":"Copy table","markdownRenderer.code.actions.enableWrapTitle":"Enable line wrap","markdownRenderer.code.actions.disableWrapTitle":"Disable line wrap","markdownRenderer.table.actions.enableWrapTitle":"Enable cell wrap","markdownRenderer.table.actions.disableWrapTitle":"Disable cell wrap","markdownRenderer.table.actions.downloadTitle":"Download table","markdownRenderer.table.toast.downloadedAsFormat":"Table downloaded as {format}","markdownRenderer.mermaid.actions.copyTitle":"Copy","markdownRenderer.mermaid.actions.copySourceTitle":"Copy source","markdownRenderer.mermaid.actions.downloadSvgTitle":"Download SVG","markdownRenderer.mermaid.actions.zoomInTitle":"Zoom in","markdownRenderer.mermaid.actions.zoomOutTitle":"Zoom out","markdownRenderer.mermaid.actions.resetViewTitle":"Reset view","markdownRenderer.mermaid.toast.downloadFailed":"Failed to download diagram","common.date.today":"Today","common.date.yesterday":"Yesterday","common.date.yesterdayWithTime":"Yesterday {time}","common.relative.justNow":"Just now","common.relative.minutesAgoShort":"{count}min ago","common.relative.hoursAgoShort":"{count}h ago","common.relative.daysAgoShort":"{count}d ago","common.relative.weeksAgoShort":"{count}w ago","common.relative.yearsAgoShort":"{count}y ago","common.relative.minutesAgoCompact":"{count}m","common.relative.hoursAgoCompact":"{count}h","common.relative.daysAgoCompact":"{count}d","common.relative.weeksAgoCompact":"{count}w","common.relative.monthsAgoCompact":"{count}mo","common.relative.yearsAgoCompact":"{count}y","common.duration.secondsCompact":"{seconds}s","common.duration.minutesSecondsCompact":"{minutes}m {seconds}s","common.duration.hoursMinutesCompact":"{hours}h {minutes}m","contextFileOpen.failure.tooLarge":"{name} is too large to open","contextFileOpen.failure.tooLargeDetail":"More than {count} lines · {size}","contextFileOpen.failure.tooLargeSize":"Larger than {limit} · {size}","contextFileOpen.failure.missing":"{name} was not found","contextFileOpen.failure.unreadable":"Couldn't open {name}","quota.window.5h":"5-Hour","quota.window.7d":"7-Day Limit","quota.window.extraUsage":"Extra Usage","quota.window.weekly":"Weekly","quota.window.daily":"Daily","quota.window.monthly":"Monthly","quota.window.credits":"Credits","quota.value.creditsUsed":"{credits} Credits Used","quota.window.keyLimit":"Key Limit","quota.window.creditsBalance":"Credits Balance","quota.window.monthlyCredits":"Monthly Credits","quota.window.purchasedCredits":"Purchased Credits","quota.window.freeCredits":"Free Credits","quota.window.billingCycle":"Billing Cycle","quota.window.auto":"Auto","quota.window.api":"API","quota.window.planLimit":"Plan Limit","quota.window.onDemand":"On-demand","quota.window.session":"Session","quota.window.premium":"Premium Interactions","quota.window.chat":"Chat Requests","quota.window.completions":"Completions","quota.window.premiumInteractions":"AI Credits","chat.workStatus.ariaLabel":"Work status","chat.workStatus.mobileEmpty":"Nothing to show for this session yet","chat.workStatus.context.label":"Context","chat.workStatus.cost.breakdown":"Session {session} · Subagents {subagents}","chat.workStatus.git.changedFileSingle":"{count} file changed","chat.workStatus.git.changedFilePlural":"{count} files changed","chat.workStatus.pr.untitled":"Untitled pull request","chat.workStatus.mr.untitled":"Untitled merge request","chat.workStatus.pr.draft":"Draft","chat.workStatus.pr.checks":"Checks","chat.workStatus.pr.checksFailed":"{count} failed","chat.workStatus.pr.checksPending":"{count} running","chat.workStatus.pr.checksPassed":"{count} passed","chat.workStatus.attention.merge":"Merge in progress","chat.workStatus.attention.rebase":"Rebase in progress","chat.workStatus.attention.cherryPick":"Cherry-pick in progress","chat.workStatus.attention.revert":"Revert in progress","chat.workStatus.attention.bisect":"Bisect in progress","chat.workStatus.subagent.done":"Done","chat.workStatus.subagent.failed":"Failed","chat.workStatus.subagent.untitled":"Subagent","chat.workStatus.mcp.toggle":"Toggle {name}","chat.workStatus.mcp.needsAuth":"Sign in","chat.workStatus.mcp.failed":"Failed","chat.workStatus.pinned.unavailable":"Pinned message","chat.workStatus.section.session":"Session","chat.workStatus.section.project":"Project","chat.workStatus.section.subagents":"Subagents","chat.workStatus.section.mcp":"MCP","chat.workStatus.section.pinned":"Pinned messages","chat.workStatus.section.tasks":"Tasks","chat.workStatus.subagent.working":"is working","chat.workStatus.subagent.needsPermission":"needs permission","chat.workStatus.subagent.askedQuestion":"asked a question","chat.workStatus.section.contextBreakdown":"Context sources","chat.workStatus.breakdown.skills":"Skills","chat.workStatus.breakdown.pinnedNote":"note","chat.workStatus.breakdown.unpin":"Unpin from context","chat.workStatus.breakdown.pinnedPlan":"plan","chat.workStatus.breakdown.memory":"Agent memory","chat.workStatus.breakdown.pinnedKnowledgeSingle":"{count} pinned","chat.workStatus.breakdown.pinnedKnowledgePlural":"{count} pinned","chat.workStatus.breakdown.mcp":"MCP servers","chat.workStatus.action.openChanges":"Open changes","chat.workStatus.action.openGit":"Open Git panel","chat.workStatus.action.openPr":"Open pull request","chat.workStatus.action.openMr":"Open merge request","chat.workStatus.action.openSubagent":"Open {name}","chat.workStatus.section.usage":"Usage","chat.workStatus.section.telemetry":"Turn stats","chat.workStatus.telemetry.previousTurn":"Previous turn","chat.workStatus.telemetry.previousTurnRate":"Previous turn · {rate}","chat.workStatus.telemetry.responseSpeed":"Response","chat.workStatus.telemetry.responseSpeedDescription":"How fast the final text arrived. Excludes the initial wait, reasoning, and earlier tool calls. An estimate from text timestamps, not a provider speed measurement.","chat.workStatus.telemetry.speed":"Whole turn","chat.workStatus.telemetry.speedDescription":"Tokens generated across all steps, including reasoning, divided by time with tool execution removed. Waiting for the model still counts, so many short tool calls can lower this number.","chat.workStatus.telemetry.elapsed":"Elapsed","chat.workStatus.telemetry.elapsedDescription":"Wall-clock time from the first user message to the final assistant response. Includes model waiting, tool execution, compaction, and other gaps.","chat.workStatus.telemetry.llmDuration":"Model time","chat.workStatus.telemetry.llmDurationDescription":"Time spent on all model steps, including waiting for responses. Tool execution time is removed. This is not just time spent generating text.","chat.workStatus.telemetry.toolDuration":"Tool time","chat.workStatus.telemetry.toolDurationDescription":"Time spent running tools, including failed calls. Tools running at the same time are counted once, not added together.","chat.workStatus.telemetry.ttft":"Average TTFT","chat.workStatus.telemetry.ttftDescription":"Average wait before the first text or reasoning starts in each model step. Hidden when a step has no start after it was created, which is common for tool-only steps and for parts stamped at creation time.","chat.workStatus.telemetry.steps":"Steps","chat.workStatus.telemetry.stepsDescription":"How many times the model was called for this prompt. Reading tool results and deciding what to do next usually takes another step.","chat.workStatus.telemetry.tokens":"Tokens","chat.workStatus.telemetry.tokens.inOut":"{input} ↑ · {output} ↓","chat.workStatus.telemetry.tokensDescription":"↑ Input without cached tokens: {input}. ↓ Generated tokens: {output} for text and tool calls, plus {reasoning} for reasoning. Totals cover all steps of this prompt.","chat.workStatus.telemetry.cacheHit":"Cache","chat.workStatus.telemetry.cacheHitDescription":"Share of input tokens reused from the prompt cache across all steps. Reusing context can reduce cost and waiting, but this is not a speed score.","chat.workStatus.telemetry.cost":"Cost","chat.workStatus.telemetry.costDescription":"Cost reported by the provider for all model steps of this prompt, in US dollars. Excludes separate subagent sessions. Zero can mean a free model or a provider that reports no charge.","chat.workStatus.goal.open":"Manage goal","chat.workStatus.goal.pause":"Pause","chat.workStatus.goal.resume":"Resume","chat.workStatus.goal.updateFailed":"Could not update the goal","chat.workStatus.pinned.unpin":"Unpin message","chat.workStatus.pinned.reveal":"Go to message","chat.workStatus.pinned.unpinFailed":"Could not unpin the message","chat.workStatus.action.openContext":"Open context panel","chat.workStatus.section.linkedIssues":"Linked","chat.workStatus.linkedIssues.openOnProvider":"Open {reference} on {provider}","chat.workStatus.linkedIssues.unlink":"Remove link","chat.workStatus.linkedIssues.unlinkFailed":"Could not remove the link","chat.workStatus.linkedIssues.link":"Link to session","chat.workStatus.linkedIssues.linkFailed":"Could not link","chat.workStatus.breakdown.issueCountSingle":"{count} issue","chat.workStatus.breakdown.issueCountPlural":"{count} issues","chat.workStatus.breakdown.prCountSingle":"{count} PR","chat.workStatus.breakdown.mrCountSingle":"{count} MR","chat.workStatus.breakdown.prCountPlural":"{count} PRs","chat.workStatus.breakdown.mrCountPlural":"{count} MRs","chat.workStatus.breakdown.skillCountSingle":"{count} skill","chat.workStatus.breakdown.skillCountPlural":"{count} skills","chat.workStatus.breakdown.mcpCountSingle":"{count} MCP","chat.workStatus.breakdown.mcpCountPlural":"{count} MCP","chat.workStatus.breakdown.planCountSingle":"{count} plan","chat.workStatus.breakdown.planCountPlural":"{count} plans","chat.workStatus.linkedPlans.open":"Open plan {title}","chat.workStatus.sections.open":"Choose sections","chat.workStatus.sections.dialogTitle":"Panel sections","chat.workStatus.sections.reorder":"Drag {label} to reorder","chat.workStatus.sections.dragInstructions":"Press Space to pick up a section, use the arrow keys to move it, and press Space to drop. Press Escape to cancel.","chat.workStatus.sections.position":"{label}, position {position} of {count}.","chat.workStatus.sections.dragCancelled":"Reordering cancelled.","chat.workStatus.sections.dialogDescription":"Choose what the work-status panel shows. Hidden sections keep their data — they are only left out of the panel.","chat.workStatus.sections.allHidden":"No sections selected","chat.workStatus.sections.showAll":"Show all","chat.workStatus.sections.noneWarning":"The panel will appear empty.","header.workStatusPanel.toggleAria":"Toggle work-status panel","header.actions.newMiniChat":"New Mini Chat Window","header.actions.newMiniChatAria":"Open a new Mini Chat window","header.actions.openSessionMiniChat":"Open Session in Mini Chat","header.actions.openSessionMiniChatAria":"Open current session in Mini Chat","header.workStatusPanel.hide":"Hide work status","header.workStatusPanel.show":"Show work status","chat.workStatus.mcp.authorizeOpenFailed":"Could not open the authorization page","chat.workStatus.mcp.authorizeFailed":"Authorization failed","chat.formCard.inputNeeded":"Input needed","chat.formCard.fromSubagent":"from a subagent","chat.formCard.required":"Required","chat.formCard.openLink":"Open link","chat.formCard.yes":"Yes","chat.formCard.other":"Other","chat.formCard.yourAnswer":"Your answer","chat.formCard.submit":"Submit","chat.formCard.cancel":"Cancel","chat.formCard.missingRequired":"Fill in the required fields first.","chat.formCard.submitFailed":"Could not submit the answer","chat.formCard.cancelFailed":"Could not cancel the request","chat.formCard.tryAgain":"Try again.","chat.formCard.connectionLost":"Connection to the server was lost. Nothing was sent; try again once it reconnects.","chat.formCard.connectionLostReason":"Connection to the server was lost ({reason}). Nothing was sent; try again once it reconnects.","chat.formCard.notConnected":"Not connected to the server yet. Nothing was sent; try again once it connects.","chat.formCard.recoveredNotice":"The turn stopped while waiting. Submit starts a new paid turn.","chat.formDock.progress":"{current} of {total}","chat.formDock.waiting":"{count} more waiting","chat.formDock.back":"Back","chat.formDock.expandAria":"Expand the question","chat.formDock.collapseAria":"Collapse the question","chat.formDock.stepAria":"Question {index}: {title}","chat.formDock.linkInfo":"Open the link, then continue.","chat.permissionCard.title":"Permission required","chat.permissionCard.summary.externalDirectory":"Access files outside the project","chat.permissionCard.summary.read":"Read a file","chat.permissionCard.summary.edit":"Edit files","chat.permissionCard.summary.shell":"Run a command","chat.permissionCard.summary.glob":"Find files","chat.permissionCard.summary.grep":"Search file contents","chat.permissionCard.summary.webfetch":"Open a web page","chat.permissionCard.summary.websearch":"Search the web","chat.permissionCard.summary.skill":"Load a skill","chat.permissionCard.summary.tool":"Use {tool}","chat.permissionCard.summary.inPath":"in {path}","chat.permissionCard.showDetails":"Show details","chat.permissionDock.expandAria":"Expand the permission request","chat.permissionDock.collapseAria":"Collapse the permission request","chat.permissionDock.stepAria":"Request {index}: {tool}","chat.permissionCard.allowOnce":"Allow once","chat.permissionCard.alwaysAllow":"Always allow","chat.permissionCard.alwaysAllowPatterns":"Always: {patterns}","chat.permissionCard.deny":"Deny","chat.permissionCard.replaceAll":"Replaces every occurrence","chat.compaction.running":"Compacting the conversation","chat.compaction.completed":"Conversation compacted","chat.compaction.failed":"Compaction failed","chat.compaction.showSummary":"Show summary","chat.compaction.hideSummary":"Hide summary","chat.dispatchedSession.completed":"Session finished: {title}","chat.dispatchedSession.failed":"Session failed: {title}","chat.dispatchedSession.cancelled":"Session stopped: {title}","chat.dispatchedSession.completedUntitled":"Session finished","chat.dispatchedSession.failedUntitled":"Session failed","chat.dispatchedSession.cancelledUntitled":"Session stopped","chat.dispatchedSession.showAnswer":"Show answer","chat.dispatchedSession.hideAnswer":"Hide answer","chat.dispatchedSession.open":"Open session","chat.fileOpenRequest.toast.description":"Shown in {session}","chat.fileOpenRequest.toast.descriptionUntitled":"Shown in another session","chat.fileOpenRequest.toast.openSession":"Open session","chat.revertPopover.staged":"Reverted: {count}","chat.revertPopover.toast.restoreFailed":"Couldn't restore the reverted messages","chat.workStatus.mcp.needsAuthHint":"Sign in to this MCP server from Settings → MCP.","header.services.tooltip.currentInstance":"Current instance: {current} ({toggle})","header.workStatusPanel.showOverlay":"Show work status over the chat","settings.mcp.page.connection.title":"How to reach it","settings.mcp.page.connection.description":"Paste the command that starts it, or the link to a hosted server.","settings.mcp.page.registration.title":"This server needs its own app","settings.mcp.page.registration.description":"It does not hand out credentials automatically. Create an app in the service’s own settings, paste its details here, then sign in.","settings.mcp.page.registration.callbackLabel":"Give the service this address","settings.mcp.page.registration.clientId":"App ID","settings.mcp.page.registration.clientSecret":"App secret","settings.mcp.page.registration.afterSaving":"Save, then press Authorize to sign in.","settings.mcp.page.toast.copiedCallbackUrl":"Address copied","settings.mcp.page.toast.clipboardWriteFailed":"Could not copy to the clipboard","settings.mcp.page.scope.everywhere":"Available in every project","settings.mcp.page.scope.thisProject":"Only in this project","settings.mcp.page.env.description":"Values the server needs, such as an API key.","settings.mcp.page.connection.kindCommand":"Command","settings.mcp.page.connection.kindLink":"Link","settings.mcp.page.connection.hintCommand":"Runs on this machine. Paste a whole command and it is split into one argument per line.","settings.mcp.page.connection.hintLink":"Connects to a server someone else hosts. Paste its https address.","chat.messageBody.actions.askOtherModels":"Ask other models","chat.modelControls.runInParallel":"Run on several models","chat.parallel.defaultTitle":"Parallel run","chat.parallel.exit":"Leave parallel mode","chat.parallel.fuse.judge":"Fuse with {model}","chat.parallel.fuse.off":"Fuse: off","chat.parallel.isolation.shared":"Shared directory","chat.parallel.isolation.worktrees":"Separate worktrees","chat.parallel.models.add":"Add model","chat.parallel.models.decrement":"Run {model} one time less","chat.parallel.models.increment":"Run {model} one more time","chat.parallel.runAria":"Start parallel runs ({count})","chat.parallel.setup.dialogDescription":"Commands run in every new worktree before its prompt, one per line.","chat.parallel.toast.failed":"Could not start the parallel run.","chat.parallel.toast.incomplete":"Every prompt variant needs text and at least one model.","chat.parallel.variant.removeAria":"Remove variant {variant}","chat.parallel.variant.runsPlural":"{count} runs","chat.parallel.variant.runsSingle":"{count} run","chat.parallel.variant.tabsAria":"Prompt variants","multirun.ask.checking":"Checking this answer…","multirun.ask.description":"This chat becomes the first run. Each model gets the same first prompt in its own worktree.","multirun.ask.failed":"Could not ask other models.","multirun.ask.notFirstTurn":"Only the first answer of a chat can be compared for now.","multirun.ask.startPlural":"Run {count} more","multirun.ask.startSingle":"Run {count} more","multirun.ask.title":"Ask other models","multirun.overview.archive.action":"Archive run","multirun.overview.archive.failed":"Some runs could not be archived.","multirun.overview.ask.failed":"Could not add the model to this run.","multirun.overview.ask.working":"Adding…","multirun.overview.bar.fuse":"Fuse results","multirun.overview.bar.hint":"Fuse the answers into one result","multirun.overview.cancel":"Cancel","multirun.overview.card.changesUnavailable":"Changes unavailable","multirun.overview.card.diff":"Diff","multirun.overview.card.filesPlural":"{count} files","multirun.overview.card.filesSingle":"{count} file","multirun.overview.card.noChanges":"No file changes","multirun.overview.card.noReply":"No answer yet","multirun.overview.card.openChat":"Open chat","multirun.overview.card.replyUnavailable":"Answer unavailable","multirun.overview.card.selectAria":"Select {name}","multirun.overview.card.working":"Working…","multirun.overview.fuse.modeAnswers":"Combines the final answers","multirun.overview.fuse.modeCode":"Works in its own worktree and reads each run with git","multirun.overview.fuse.selected":"{count} of {total} selected","multirun.overview.fuse.with":"Fuse with","multirun.overview.fusedResult":"Fused result","multirun.overview.headerTitle":"Run in parallel","multirun.overview.keep.confirm":"Keep and clean up","multirun.overview.keep.confirmPlural":"Keep {name}? The other {count} runs are archived and their worktrees removed. Their work stays recoverable.","multirun.overview.keep.confirmSingle":"Keep {name}? The other run is archived and its worktree removed. Its work stays recoverable.","multirun.overview.keep.done":"Kept {name}","multirun.overview.keep.failed":"Could not clean up the other runs.","multirun.overview.keep.partialPlural":"Kept {name}. {count} runs could not be cleaned up and were left as they were.","multirun.overview.keep.partialSingle":"Kept {name}. One run could not be cleaned up and was left as it was.","multirun.overview.keep.working":"Cleaning up…","multirun.overview.meta.autoFusion":"Fuses with {model} when all finish","multirun.overview.meta.progress":"{done} of {total} finished","multirun.overview.meta.runsPlural":"{count} runs","multirun.overview.meta.runsSingle":"{count} run","multirun.overview.meta.sharedDirectory":"Shared directory","multirun.overview.meta.variants":"{count} prompt variants","multirun.overview.meta.worktrees":"Separate worktrees","multirun.overview.missing":"This run is no longer available.","multirun.overview.rename.aria":"Rename run","multirun.overview.rename.failed":"Some runs kept the old name.","sessions.sidebar.run.collapse":"Hide runs","sessions.sidebar.run.expand":"Show runs","sessions.sidebar.run.laneCountPlural":"{count} runs","sessions.sidebar.run.laneCountSingle":"{count} run","sessions.sidebar.run.openOverviewAria":"Open parallel run {title}","sessions.sidebar.run.menu.openOverview":"Open overview","sessions.sidebar.session.menu.openRunOverview":"Open run overview","chat.parallel.models.effortAria":"Thinking effort: {effort}","chat.parallel.settings.title":"Launch settings","chat.parallel.settings.whereTitle":"Where the runs work","chat.parallel.settings.setupTitle":"Setup commands","chat.parallel.settings.fusionTitle":"Fusion","chat.parallel.settings.variantsTitle":"Prompt variants","chat.parallel.settings.variantsDescription":"Send different prompts, for example to compare skills or wording. Each variant gets its own tab.","chat.parallel.settings.addVariant":"Add a prompt variant","chat.parallel.settings.done":"Done","chat.parallel.settings.openAria":"Launch settings: {summary}","multirun.overview.card.keep":"Keep this","multirun.overview.addModel.action":"Add a model","multirun.overview.addModel.hint":"Runs the same prompt on one more model in this run","chat.parallel.settings.whereShared":"Project directory","chat.parallel.settings.whereSharedHint":"All runs work in your checkout. Best for questions and research.","chat.parallel.settings.whereWorktrees":"Separate worktrees","chat.parallel.settings.whereWorktreesHint":"Each run gets its own branch, so code changes never collide. Keep the best one.","chat.parallel.settings.baseBranchTitle":"Base branch","chat.parallel.settings.fusionOff":"Off","chat.parallel.settings.fusionOffHint":"Compare the results yourself.","chat.parallel.settings.fusionAuto":"Automatic","chat.parallel.settings.fusionAutoHint":"Fuse the results as soon as every run finishes.","chat.parallel.settings.judgeTitle":"Fusion model","multirun.overview.card.detach":"Make a separate session","multirun.overview.card.detachHint":"Leave this run and continue as an ordinary session","multirun.overview.card.detachDone":"{name} is now a separate session","multirun.overview.card.detachFailed":"Could not move this session out of the run.","multirun.overview.card.archive":"Archive this session","multirun.overview.addModel.confirm":"Run","multirun.overview.status.permission":"Waiting for your permission","multirun.overview.status.question":"Waiting for your answer","multirun.overview.status.working":"Working","multirun.overview.status.failed":"Failed","multirun.overview.status.stopped":"Stopped","multirun.overview.status.notStarted":"Not started","multirun.overview.status.noReply":"Finished without an answer","multirun.overview.status.finished":"Finished","multirun.overview.status.count.permission":"{count} waiting for permission","multirun.overview.status.count.question":"{count} waiting for an answer","multirun.overview.status.count.working":"{count} working","multirun.overview.status.count.failed":"{count} failed","multirun.overview.status.count.stopped":"{count} stopped","multirun.overview.status.count.notStarted":"{count} not started","multirun.overview.status.count.noReply":"{count} without an answer","multirun.overview.status.count.finished":"{count} finished","multirun.overview.card.body.permission":"Waiting for your permission to go on. Open the chat to answer.","multirun.overview.card.body.question":"Asked you a question. Open the chat to answer.","multirun.overview.card.body.failed":"Failed. Open the chat for details.","multirun.overview.card.body.notStarted":"Has not started yet.","multirun.overview.card.body.stopped":"Stopped before answering.","multirun.overview.bar.waiting":"Runs waiting for you: {count}. The run can't finish until you answer them.","multirun.overview.prompt.expand":"Show all","multirun.overview.prompt.collapse":"Show less","gitView.changes.revertFileDialogTitle":"Revert file changes?","gitView.changes.revertFileDescription":"This will discard your local changes in {path}.","gitView.changes.revertFileConfirm":"Revert file","diffView.hunk.discardDialogTitle":"Discard this hunk?","diffView.hunk.discardDescription":"This will discard these local changes in {path}.","sessions.sidebar.project.actions.archiveAll":"Archive all sessions","sessions.sidebar.project.archiveAll.title":"Archive sessions in {project}?","sessions.sidebar.project.archiveAll.descriptionSingle":"{count} session moves to the archive. Pinned, running and In work sessions stay.","sessions.sidebar.project.archiveAll.descriptionPlural":"{count} sessions move to the archive. Pinned, running and In work sessions stay.","sessions.sidebar.project.archiveAll.nothing":"Nothing to archive: every session here is pinned, running or In work.","contextPanel.browser.devServers.hide":"Hide port {port} from this list","contextPanel.browser.devServers.showHiddenSingle":"Show {count} hidden port","contextPanel.browser.devServers.showHiddenPlural":"Show {count} hidden ports","sidebarFilesTree.menu.openInDefaultApp":"Open in default app","sessions.sidebar.header.displayMode.showChats":"Show chats section","sessions.scheduledTasks.editor.useDefaults.label":"Use session defaults","sessions.scheduledTasks.editor.useDefaults.hint":"Each run takes the default model, thinking level and agent from Settings → Sessions (or the project's own defaults) at the time it starts.","sessions.scheduledTasks.editor.worktree.label":"Run each run in a fresh worktree","sessions.scheduledTasks.editor.worktree.hint":"Each run gets its own worktree and branch.","sessions.scheduledTasks.editor.worktree.baseBranch.label":"Source branch","sessions.scheduledTasks.editor.worktree.cleanup.label":"Clean up worktree after run","sessions.scheduledTasks.editor.worktree.cleanup.hint":"The worktree and its branch are removed when the run ends.","sessions.scheduledTasks.editor.worktree.cleanup.keepHint":"The worktree and its branch stay after the run so you can review the result.","sessions.scheduledTasks.editor.worktree.notRepo":"The project folder is not a git repository; runs will use the checkout as-is.","sessions.scheduledTasks.dialog.usesDefaults":"Session defaults","sessions.moveSession.menu":"Move session…","sessions.moveSession.hint":"Files stay in the old folder","sessions.moveSession.title":"Move session","sessions.moveSession.description":"The session continues in the chosen folder. Files stay where they are.","sessions.moveSession.chooseFolder":"Choose folder…","sessions.moveSession.current":"Current folder","sessions.moveSession.success":"Session moved","sessions.moveSession.failed":"Could not move the session","chat.folderMissing.text":"Folder {name} no longer exists","chat.folderMissing.action":"Move session","chat.trustPaused.text":"Agents can't work in {name} until you trust its plugins and commands.","chat.trustPaused.action":"Review and trust","chat.worktreeSetup.running":"Setting up the worktree: running the project's setup commands…","chat.draft.creatingSession":"Creating session…","desktopHostSwitcher.startup.fellBackToLocal":"Its connection didn't open, so OpenChamber started on Local. Connect it from the instance switcher once it's reachable.","desktopSafeStart.title":"OpenChamber kept crashing","desktopSafeStart.description":"Panels are closed and folders collapsed.","chat.chatInput.contextPreview.saveEdit":"Save comment","chat.chatInput.contextPreview.cancelEdit":"Cancel editing","sessions.scheduledTasks.dialog.actions.openSession":"Open session","sessions.scheduledTasks.dialog.actions.openSessionAria":"Open the session from the last run of {taskName}","sessions.scheduledTasks.dialog.toast.alreadyRunningSince":"This task already has a run in progress, started at {time}","sessions.scheduledTasks.dialog.toast.alreadyRunning":"This task already has a run in progress","sessions.scheduledTasks.dialog.toast.alreadyQueued":"This task is already waiting in the queue and will run when a slot frees up","chat.modelControls.agentFavoriteAdd":"Add to favorites. With favorites, Tab cycles through them only","notifications.error.bodyFallback":"An error occurred","notifications.question.bodyFallback":"Agent is waiting for your response","notifications.permission.bodyFallback":"Agent is waiting for your approval","notifications.permission.title":"Permission required","chat.promptHistorySearch.title":"Search prompt history","chat.promptHistorySearch.searchPlaceholder":"Search remembered prompts","chat.promptHistorySearch.close":"Close prompt history search","chat.promptHistorySearch.empty":"No prompts to search yet","chat.promptHistorySearch.noMatches":"No matching prompts","chat.promptHistorySearch.attachmentsSingle":"{count} attachment","chat.promptHistorySearch.attachmentsPlural":"{count} attachments","chat.promptHistorySearch.hint":"↑ ↓ to browse · Enter to load · Esc to close","helpDialog.item.searchPromptHistory":"Search prompt history (chat input)"},Vk=new RegExp("\\p{L}[\\p{L}\\p{M}‌]*","gu"),Uk="\\p{Script=Arabic}\\p{Script=Hebrew}\\p{Script=Syriac}\\p{Script=Thaana}\\p{Script=Nko}\\p{Script=Adlam}\\p{Script=Samaritan}\\p{Script=Mandaic}",vO=new RegExp(`^[${Uk}]`,"u"),Kp=new RegExp(`[${Uk}]`,"u"),Wk=new RegExp("\\p{L}","u"),CO=e=>Kp.test(e),SO=(e,t)=>Wk.test(e)&&(t||Kp.test(e))?`⁨${e}⁩`:e,Hk=e=>{let t=0;for(const s of e)vO.test(s)&&(t+=1);if(e.length!==0)return t*2>=e.length?"rtl":"ltr"},hJ=(...e)=>Hk(e.flatMap(t=>t?Array.from(t.matchAll(Vk),([s])=>s):[])),PO=/`[^`\n]*`|https?:\/\/\S+/g,fJ=e=>Kp.test(e)?Hk(e.replace(PO," ").split(/\s+/).flatMap(t=>{const s=t.match(Vk)?.[0];return s?[s]:[]})):Wk.test(e)?"ltr":void 0,fd=new Map([[Ko,Zo]]);async function xO(e){const t=fd.get(e);if(t)return t;const s=e==="zh-CN"?await Ge(()=>import("./zh-CN-BJ4oeBCY.js"),__vite__mapDeps([3,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="fr"?await Ge(()=>import("./fr-gZGCwYzk.js"),__vite__mapDeps([109,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="nl"?await Ge(()=>import("./nl-BPlUOQoY.js"),__vite__mapDeps([110,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="zh-TW"?await Ge(()=>import("./zh-TW-BMW1G3F_.js"),__vite__mapDeps([111,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="es"?await Ge(()=>import("./es-CYh9u5rf.js"),__vite__mapDeps([112,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="pt-BR"?await Ge(()=>import("./pt-BR-fU-ttTba.js"),__vite__mapDeps([113,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="uk"?await Ge(()=>import("./uk-DTqcJvdn.js"),__vite__mapDeps([114,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="ko"?await Ge(()=>import("./ko-DuYqVIuP.js"),__vite__mapDeps([115,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="pl"?await Ge(()=>import("./pl-DZRSuGdV.js"),__vite__mapDeps([116,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="de"?await Ge(()=>import("./de-5cm4El6N.js"),__vite__mapDeps([117,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="ja"?await Ge(()=>import("./ja-CAeb9wyo.js"),__vite__mapDeps([118,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="tr"?await Ge(()=>import("./tr-CD93vntx.js"),__vite__mapDeps([119,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="ar"?await Ge(()=>import("./ar-zwtOisVI.js"),__vite__mapDeps([120,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="he"?await Ge(()=>import("./he-DWb3dvEl.js"),__vite__mapDeps([121,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):{dict:Zo};return fd.set(e,s.dict),s.dict}const Er=Rt()((e,t)=>({locale:Ko,dictionary:Zo,loadingLocale:null,setLocale:s=>{const a=t(),n=fd.get(s);a.locale===s&&a.loadingLocale!==s&&n||($I(s),e({locale:s,dictionary:n??a.dictionary,loadingLocale:n?null:s}),!n&&xO(s).then(o=>{t().locale===s&&e({dictionary:o,loadingLocale:null})}).catch(o=>{console.error(`[i18n] failed to load locale ${s}`,o),t().locale===s&&e({dictionary:Zo,loadingLocale:null})}))}}));function TO(){Er.getState().setLocale(QI())}function AO(e,t,s){const a=e[t]??Zo[t]??t;if(!s)return a;const n=CO(a);return a.replace(/\{([^{}]+)\}/g,(o,i)=>{const r=s[i.trim()];if(r==null)return o;const l=String(r);return l===r?SO(l,n):l})}const bJ=Object.freeze(Object.defineProperty({__proto__:null,formatMessage:AO,initializeLocale:TO,useI18nStore:Er},Symbol.toStringTag,{value:"Module"})),Gk="session",_k=40,zO=1,RO=100,Kk=e=>e==="global"||e==="session",Zp=e=>e!=null&&Number.isInteger(e)&&e>=zO&&e<=RO,IO=["bash","zsh","sh","fish","pwsh","powershell","cmd","dash","ksh","nu"],Jp=e=>e==="auto"||typeof e=="string"&&IO.includes(e),sn="openchamber-input-history.v1",jO=8,OO=50,DO=[40,25,10,5,1],cl=Object.freeze([]);let hs=null,im=0;const To=(e=Gk,t=_k)=>({entryLimit:t,scope:e,globalBuckets:{},sessionBuckets:{}}),Zk=()=>(im+=1,Date.now()*1e3+im),Jk=e=>JSON.stringify([e]),bd=(e,t,s)=>JSON.stringify([e,t,s]),$p=()=>{try{return globalThis.window?.localStorage??null}catch{return null}},NO=()=>{const e=$p(),t=Lt?JSON.stringify(ur(Lt.base)):hs;if(!e)return t;try{return e.getItem(sn)??(Lt?null:hs)}catch{return t}},rm=ke(c(),ne()),FO=d({key:c().min(1),source:M([m("file-url"),m("vscode-file")]),filename:c().min(1),mimeType:c().min(1),size:w().finite().nonnegative(),reference:c().min(1),path:c().min(1).optional()}),EO=d({text:c(),attachmentKeys:C(c()),restorableAttachments:C(FO),submittedAt:w().finite().nonnegative()}),MO=d({touchedAt:w().finite().nonnegative(),entries:C(ne())}),BO=(e,t)=>{try{const s=JSON.parse(e),n=(t===1?wr([c().trim().min(1)]):wr([c().trim().min(1),c().trim().min(1),c().trim().min(1)])).safeParse(s);if(!n.success)return null;if(t===3){const o=je(n.data[1]);if(!o||o!==n.data[1])return null}return n.data}catch{return null}},cm=(e,t)=>{const s=[];for(const[a,n]of Object.entries(e)){if(!BO(a,t))continue;const o=MO.safeParse(n);if(!o.success)continue;const i=o.data.entries.map(r=>EO.safeParse(r)).filter(r=>r.success).map(r=>r.data);s.push([a,{touchedAt:o.data.touchedAt,entries:i}])}return Object.fromEntries(s)},LO=()=>{const e=NO();if(e===null)return To();try{const t=JSON.parse(e),s=d({version:m(1),entryLimit:w().int().optional(),scope:M([m("global"),m("session")]).optional(),global:rm.default({}),session:rm.default({})}).safeParse(t);return s.success?{entryLimit:Zp(s.data.entryLimit)?s.data.entryLimit:_k,scope:s.data.scope??Gk,globalBuckets:cm(s.data.global,1),sessionBuckets:cm(s.data.session,3)}:To()}catch{const t=$p();if(t)try{t.removeItem(sn)}catch{}return hs=null,To()}};let Lt=null,pr=To();const lm=(e,t,s)=>{const a={...e};for(const n of new Set([...Object.keys(t),...Object.keys(s)])){if(JSON.stringify(t[n])===JSON.stringify(s[n]))continue;const o=s[n];if(!o){delete a[n];continue}const i=new Set((t[n]?.entries??[]).map(u=>JSON.stringify(u))),r=new Set(o.entries.map(u=>JSON.stringify(u))),l=(e[n]?.entries??[]).filter(u=>{const g=JSON.stringify(u);return!i.has(g)||r.has(g)}),p=new Set(l.map(u=>JSON.stringify(u)));for(const u of o.entries){const g=JSON.stringify(u);!i.has(g)&&!p.has(g)&&l.push(u)}l.sort((u,g)=>u.submittedAt-g.submittedAt),a[n]={touchedAt:Math.max(o.touchedAt,e[n]?.touchedAt??0),entries:l}}return a},uo=()=>{const e=LO();if(pr=e,!Lt)return e;const{base:t,value:s}=Lt;return kd({entryLimit:s.entryLimit===t.entryLimit?e.entryLimit:s.entryLimit,scope:s.scope===t.scope?e.scope:s.scope,globalBuckets:lm(e.globalBuckets,t.globalBuckets,s.globalBuckets),sessionBuckets:lm(e.sessionBuckets,t.sessionBuckets,s.sessionBuckets)})},$k=(e,t)=>e.slice(Math.max(0,e.length-t)),dm=(e,t,s)=>{const a=Object.entries(e).map(([n,o])=>[n,{touchedAt:o.touchedAt,entries:$k(o.entries,s)}]).sort((n,o)=>o[1].touchedAt-n[1].touchedAt).slice(0,t);return Object.fromEntries(a)},kd=(e,t=e.entryLimit)=>({entryLimit:e.entryLimit,scope:e.scope,globalBuckets:dm(e.globalBuckets,jO,t),sessionBuckets:dm(e.sessionBuckets,OO,t)}),ur=e=>({version:1,entryLimit:e.entryLimit,scope:e.scope,global:e.globalBuckets,session:e.sessionBuckets}),pm=e=>e instanceof DOMException?e.name==="QuotaExceededError":e instanceof Error&&/quota/i.test(e.message),go=e=>{const t=kd(e),s=JSON.stringify(ur(t));Lt={base:pr,value:t};const a=$p();if(!a)return hs=s,t;try{return a.setItem(sn,s),Lt=null,hs=s,t}catch(i){if(!(i instanceof Error)||!pm(i))return hs=s,t}try{a.removeItem(sn)}catch{}for(const i of DO){const r=kd(t,i),l=JSON.stringify(ur(r));try{return a.setItem(sn,l),Lt=null,hs=l,r}catch(p){if(!(p instanceof Error)||!pm(p))return Lt={base:pr,value:r},hs=l,r}}const n=To(t.scope,t.entryLimit),o=JSON.stringify(ur(n));try{a.setItem(sn,o),Lt=null}catch{Lt={base:pr,value:n}}return hs=o,n},qO=(e,t,s)=>{const a=e.trim(),n=je(t),o=s.trim();return!a||!n||!o?null:{runtimeKey:a,directory:n,sessionId:o}},Qk=e=>e.source==="vscode"&&e.vscodeSource==="file"?je(e.vscodePath??null):e.dataUrl.trim()||null,VO=e=>!(!e||e.startsWith("data:")||(e.startsWith("http://")||e.startsWith("https://"))&&e.includes("?")),wd=e=>{const t=Qk(e),s=t===null?"none":t.startsWith("data:")?"data":t.slice(0,512);return[e.source,e.filename,e.mimeType,String(e.size),s].join("|")},UO=e=>{const t=Qk(e);if(!t)return null;const s=e.agentPath&&e.serverPath===e.agentPath?e.agentPath:void 0;return!s&&!VO(t)?null:e.source==="vscode"&&e.vscodeSource==="file"?{key:wd(e),source:"vscode-file",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}:{key:wd(e),source:"file-url",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t,path:s}},WO=(e,t)=>({text:e,attachmentKeys:t.map(wd),restorableAttachments:t.map(UO).filter(s=>s!==null)}),HO=(e,t)=>e.length===t.length&&e.every((s,a)=>{const n=t[a];return n!==void 0&&s.key===n.key&&s.source===n.source&&s.filename===n.filename&&s.mimeType===n.mimeType&&s.size===n.size&&s.reference===n.reference&&s.path===n.path}),GO=(e,t)=>e!==void 0&&e.text===t.text&&e.attachmentKeys.length===t.attachmentKeys.length&&e.attachmentKeys.every((s,a)=>s===t.attachmentKeys[a])&&HO(e.restorableAttachments,t.restorableAttachments),um=(e,t,s,a)=>{const n=e?[...e.entries]:[];for(const o of t){const i=n.at(-1);GO(i,o)||n.push({text:o.text,attachmentKeys:[...o.attachmentKeys],restorableAttachments:o.restorableAttachments.map(r=>({...r})),submittedAt:Zk()})}return{touchedAt:s,entries:$k(n,a)}},_O=go(uo()),mo=Rt(e=>({..._O,applyEntryLimit:t=>{Zp(t)&&e(s=>{const a=uo();if(a.entryLimit===t)return{...s,...a};const n=go({entryLimit:t,scope:a.scope,globalBuckets:a.globalBuckets,sessionBuckets:a.sessionBuckets});return{...s,...n}})},applyScope:t=>{Kk(t)&&e(s=>{const a=uo();if(a.scope===t)return{...s,...a};const n=go({entryLimit:a.entryLimit,scope:t,globalBuckets:a.globalBuckets,sessionBuckets:a.sessionBuckets});return{...s,...n}})},appendSubmissions:(t,s)=>{s.length!==0&&e(a=>{const n=uo(),o=Zk(),i=Jk(t.runtimeKey),r=bd(t.runtimeKey,t.directory,t.sessionId),l=go({entryLimit:n.entryLimit,scope:n.scope,globalBuckets:{...n.globalBuckets,[i]:um(n.globalBuckets[i],s,o,n.entryLimit)},sessionBuckets:{...n.sessionBuckets,[r]:um(n.sessionBuckets[r],s,o,n.entryLimit)}});return{...a,...l}})},clearSession:t=>{e(s=>{const a=uo(),n=bd(t.runtimeKey,t.directory,t.sessionId);if(!(n in a.sessionBuckets))return{...s,...a};const o={...a.sessionBuckets};delete o[n];const i=go({entryLimit:a.entryLimit,scope:a.scope,globalBuckets:a.globalBuckets,sessionBuckets:o});return{...s,...i}})}})),kJ=(e,t)=>t?e.scope==="session"?e.sessionBuckets[bd(t.runtimeKey,t.directory,t.sessionId)]?.entries??cl:e.globalBuckets[Jk(t.runtimeKey)]?.entries??cl:cl,KO="openchamber.sdk",ZO=1,JO=[1],$O=/^(>=)?\d+\.\d+\.\d+$/,QO=1e3,YO=6e4,XO=16,eD=2,tD=6,sD=120,aD=2,nD=4,oD=200,iD=300,Yk=/^[a-z0-9][a-z0-9-]{0,39}$/,aa=/^[a-z][a-z0-9-]*$/,rD=["top","bottom","left","right"],wJ="top",yJ=40,cD=24,lD=480,dD=60,Xk=24,ew=480,pD=120,uD=8,gD=40,mD=8,hD=80,fD=/^[a-z][a-z0-9-]{0,23}$/,bD=256,kD=16,wD=128,yD=/^[A-Za-z0-9_.:-]+\*?$/,yd=40,Mr=200,vJ=200,vD=32,CD=16,SD=64,PD=8,xD=16,TD=64,CJ=2048,AD=["auto","text","json","markdown","code","table","card"],tw=["neutral","info","success","warning","error"],SJ=["input","output","metadata"],Br=e=>new RegExp(`\\{(${e.join("|")})((?:\\.[A-Za-z0-9_-]+)*)\\}`,"g"),vd=["input","output","metadata","settings"],zD=e=>{const t=new Set;for(const s of e??[])for(const a of(s.card?.link?.url??"").matchAll(Br(["settings"])))a[2]&&t.add(a[2].slice(1));return[...t]},RD=e=>[!!e.oauth,!!e.token,!!e.host].filter(Boolean).length!==1?null:e.host?"host":e.oauth?"oauth":"token",gm=["browser","source-control","notifications","tracker","quota","opencode"],mm=28,hm=28,fm=28,ID=16,jD=/^[a-z0-9][a-z0-9._-]{0,63}$/,sw=e=>jD.test(e),bm=28,PJ=e=>`ext-${e}`,aw=8,OD=256,Qp=["{id}","{segment}","{segments+}"],DD=/^[A-Za-z0-9._~-]+$/,ND=new Set(Qp),FD=/^([A-Za-z0-9_.-]{1,64})=\{id\}$/,Yp=e=>{if(!e.startsWith("/")||e.length>OD)return!1;const t=e.indexOf("?"),s=t===-1?e:e.slice(0,t),a=t===-1?null:e.slice(t+1),n=s==="/"?[]:s.slice(1).split("/");if(n.some(i=>i==="."||i==="..")||n.some(i=>!ND.has(i)&&!DD.test(i)))return!1;const o=i=>n.filter(r=>r===i).length;return o("{segments+}")>1?!1:a===null?o("{id}")===1:FD.test(a)&&o("{id}")===0},ll=["open","all"],ED=16,nw=["key-number","number","short-code"],MD=4,BD=8,LD=256,ow=["{owner}","{namespace+}","{repo}","{number}"],xJ=(e,t)=>!!e?.provides?.includes(t),TJ=["prompt","sessions","files","model","shells","conversation","service","network","filesystem","origins","transcript","sessionControl","sessionAnswers","instructions","skills","opencodePlugin","opencode","links","wake","marks"],qD=["prompt","sessions","files","model","shells"],VD=8,UD=16,iw=256,WD=e=>e.length===0||e.length>iw||e.includes("\0")||e.includes("\\")||!e.startsWith("/")&&!e.startsWith("~/")?!1:!e.split("/").slice(1).some(s=>s===""||s===".."),HD=40,GD=8,_D=/^[A-Z][A-Z0-9_]{0,31}$/,KD=["open","attach"],ZD=e=>Yp(e)&&!e.includes("{segment}")&&!e.includes("{segments+}"),AJ=(e,t,s)=>`${e}${t.replace("{id}",encodeURIComponent(s))}`,JD=/^[A-Z][A-Za-z0-9]{1,31}$/,$D=/^[a-z][A-Za-z0-9]{0,31}$/,QD=4,YD=8,XD=120,zJ=120,eN=960,qi=e=>!!e.panel.entry,RJ=e=>e.requested.every(t=>e.granted.includes(t)),IJ=(e,t)=>e.granted.includes(t),tN=e=>e!==void 0&&e!==!0&&e!==!1&&e!=="panel"&&e!=="dialog",jJ=e=>e===!0||e==="panel"?"panel":e==="dialog"?"dialog":tN(e)?e.mode:null,OJ=e=>Number.isFinite(e)?Math.min(ew,Math.max(Xk,Math.round(e))):pD,xt=e=>e.includes("\0")||e.includes("\\")||e.startsWith("/")||e.includes("://")||e.split("/").some(s=>s===""||s==="."||s==="..")?!1:/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(e),sN=e=>xt(e)&&e.toLowerCase().endsWith(".svg"),aN=e=>xt(e)&&/\.(?:svg|png)$/i.test(e),rw=["sent","no-model","skipped","failed"],nN=2e3,oN=["started","completed","failure"],iN=["file","directory","other"],cw=["file","directory","other","missing"],DJ={connected:!1,account:""},rN=["phone","tablet","desktop"],cN=["coarse","fine"],NJ=e=>e!==null&&e.kind==="link",FJ=e=>e!==null&&(e.kind===void 0||e.kind==="issue"||e.kind==="pull"),lw=/^[0-9a-f]{7,64}$/i,EJ=e=>lw.test(e),lN=500,km=32e3,Cd=16e3,Xp=128,dw=200,rc=2e3,pw=16e3,uw=80,Sd=200,gw=16e3,dN=200,pN=200,uN=80,gN=2e3,Pd=2e3,wm=64e3,mN=8e6,MJ=2e4,mw=1024,hw=2e6,hN=2e3,fN=64e3,bN=8e3,kN=4e3,wN=256e3,BJ=60*6e4,LJ=8,eu=2e5,yN=2e6,vN=999,CN=1e4,dl=500,fw=["HOST_UNAVAILABLE","HOST_TIMEOUT","HOST_REJECTED","DISCONNECTED","DISABLED","BAD_PATH","NO_INTEGRATION","NO_SERVICE","SERVICE_FAILED","REQUEST_FAILED","RESPONSE_TOO_LARGE","NO_SESSION","SESSION_BUSY","NOT_GRANTED","NO_DIRECTORY","NOT_FOUND","FILE_TOO_LARGE","DENIED","NO_MODEL","MODEL_FAILED","UNSUPPORTED"],bw=["stopped","starting","ready","failed"],SN=new Set(fw),PN=e=>SN.has(e),xN=e=>e&&PN(e)?e:"HOST_REJECTED",xd=e=>e===void 0?!1:e===null||e===!0||e===!1||String(e)===e?!0:Number(e)===e?Number.isFinite(e):Array.isArray(e)?e.every(xd):Object(e)===e?Object.values(e).every(xd):!1,TN=e=>xd(e)&&JSON.stringify(e).length<=gw,ym=e=>e?.trim().slice(0,Sd)??"",AN=e=>{const t=e.id.trim().slice(0,Xp),s=e.title.trim().slice(0,dw),a=e.url.trim().slice(0,rc),n=e.text?.trim().slice(0,pw),o=e.author?.trim().slice(0,uw),i=e.kind==="pull"?"pull":"issue",r={providerId:e.providerId.trim(),id:t,title:s||t,url:a,kind:i};if(n&&(r.text=n),o&&(r.author=o),i==="pull"){const l=ym(e.branches?.head),p=ym(e.branches?.base);l&&p&&(r.branches={head:l,base:p})}return TN(e.data)&&(r.data=e.data),r},qJ=e=>{const t=AN(e);return e.projectId&&(t.projectId=e.projectId),e.navigation&&(t.navigation=e.navigation),e.worktree&&(t.worktree=e.worktree),t},VJ=e=>{const t={text:e.text.trim().slice(0,Cd)};return e.send&&(t.send=!0),t},UJ=e=>e.startsWith("/")||e==="~"||e.startsWith("~/")?"filesystem":"project",zN=e=>e.length>0&&e.length<=mw&&!e.includes("\0")&&!e.includes("\\"),RN=/^[a-z][a-z0-9-]*$/,IN=/^[a-z][a-z0-9-]*$/,Td=e=>!e.startsWith("/")||e.includes("\0")||e.includes("\\")||e.includes("://")||e.length>Pd?!1:!e.split("/").some(s=>s==="."||s==="..");new Set(bw);new Set(cw);const WJ=e=>!!(e&&"text"in e&&String(e.text)===e.text&&!("status"in e)),Ad=["turn-finished","turn-failed","permission-asked","question-asked","turn-started","session-created","session-archived","session-deleted"],jN=2e3;new Set(Ad);const kw=64e3,ON=4096,DN=64,NN=200,FN=200,EN=2048,MN=8,BN=64,LN=64,qN=e=>e.length<=BN&&/^[A-Za-z0-9*/,\-?]+(?: +[A-Za-z0-9*/,\-?]+){4}$/.test(e),vm=120,VN=256,UN=16e3,WN=2e3,HN=8,GN=/^[a-z][a-z0-9-]{0,31}$/,_N=40,KN=200,Cm=8,ZN=/^[a-zA-Z][a-zA-Z0-9_]{0,31}$/,JN=200,$N=["string","number","boolean"],QN=1e4,YN=36e5,XN=4096,eF=2e3,tF=80,sF=2e3,aF=8,nF=60,oF=16,iF=128,ww=2e7,zd=256,yw=e=>e.length>0&&e.length<=iF&&!/[/\\\0]/.test(e)&&/[^*?]/.test(e),Sm=new Map,rF=e=>{const t=Sm.get(e);if(t)return t;const s=e.split("").map(n=>n==="*"?".*":n==="?"?".":n.replace(/[\\^$.|+()[\]{}]/g,"\\$&")).join(""),a=new RegExp(`^${s}$`,"is");return Sm.set(e,a),a},HJ=(e,t)=>yw(t)&&rF(t).test(e),tu=e=>aa.test(e)||sN(e),Jo=e=>{try{const t=new URL(e);return t.protocol==="https:"&&t.username===""&&t.password===""}catch{return!1}},cF=/^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/,vw=e=>Mn(e)?cF.test(new URL(e).hostname):!1,Mn=e=>{try{const t=new URL(e);return t.protocol==="https:"&&t.username===""&&t.password===""&&t.pathname==="/"&&t.search===""&&t.hash===""&&e===t.origin}catch{return!1}},di=e=>!e.startsWith("/")||e.includes("\0")||e.includes("\\")||e.includes("://")?!1:!e.split("/").some(s=>s==="."||s===".."),Cw=/^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)*$/,Sw=S(["panel","dialog"]),lF=d({mode:Sw,entry:c().trim().refine(xt).optional()}).refine(e=>e.mode==="dialog"||e.entry===void 0,{path:["entry"]}),dF=M([y(),Sw,lF]),pF=d({id:c().trim().regex(aa),name:c().trim().min(1),icon:c().trim().refine(tu),entry:c().trim().refine(xt).optional(),dock:S(rD).optional(),size:w().int().min(cD).max(lD).optional(),mobile:m(!0).optional()}),uF=d({id:c().trim().regex(aa),label:c().trim().min(1),secret:m(!0).optional()}),gF=d({authorizeUrl:c().trim().refine(Jo),tokenUrl:c().trim().refine(Jo),apiOrigin:c().trim().refine(Mn),scopes:C(c().trim().min(1)).optional(),account:d({path:c().trim().refine(di),name:c().trim().regex(Cw)}).optional()}),mF=d({apiOrigin:c().trim().refine(Mn),account:d({path:c().trim().refine(di),name:c().trim().regex(Cw)}).optional(),scheme:S(["raw","bearer","basic"]).optional(),usernameLabel:c().trim().min(1).max(64).optional()}),hF=d({provider:S(["linear"])}),fF=d({name:c().trim().min(1),description:c().trim().min(1),oauth:gF.optional(),token:mF.optional(),host:hF.optional(),settings:C(uF).optional()}).refine(e=>RD(e)!==null,{path:["oauth"]}),Pm=["linux","darwin","win32"],Ao=c().trim().min(1).max(512),bF=d({linux:C(Ao).max(16).optional(),darwin:C(Ao).max(16).optional(),win32:C(Ao).max(16).optional()}).strict(),kF=d({id:c().trim().regex(aa).max(64),path:Ao.optional(),candidates:bF.optional()}).strict().refine(e=>!!e.path||!!e.candidates,{message:"socket binding needs path or candidates"}),wF=e=>{const t={};if(e.candidates)for(const s of Pm){const a=e.candidates[s];a&&a.length>0&&(t[s]=[...a])}else if(e.path)for(const s of Pm)t[s]=[e.path];return{id:e.id,candidatesByPlatform:t}},yF=M([Ao.transform(e=>({id:e,candidatesByPlatform:{linux:[e],darwin:[e],win32:[e]}})),kF.transform(wF)]),vF=d({sockets:C(yF).max(32).optional(),exec:C(c().trim().min(1).max(128)).max(32).optional()}).strict().transform(e=>{const t={};return e.sockets&&e.sockets.length>0&&(t.sockets=e.sockets),e.exec&&e.exec.length>0&&(t.exec=[...e.exec]),t}),CF=d({entry:c().trim().refine(xt),runtime:m("host"),permissions:vF.optional(),provides:C(S(gm)).min(1).max(gm.length).refine(e=>new Set(e).size===e.length,{message:"provides entries must be unique"}).optional(),surface:m(!0).optional(),keepRunning:m(!0).optional(),schedule:C(d({id:c().trim().regex(aa).max(64),cron:c().trim().refine(qN),timezone:c().trim().min(1).max(LN).optional()}).strict()).min(1).max(MN).refine(e=>Bn(e,t=>t.id),{message:"schedule ids must be unique"}).optional()}),SF=/^[MmLlHhVvCcSsQqTtAaZz0-9eE.,\s+-]+$/,PF=/^[A-Za-z0-9._~-]+$/,xF=new Set(ow),TF=(e,t)=>{if(!e.startsWith("/")||e.length>LD)return!1;const s=e.slice(1).split("/");if(s.some(i=>i==="."||i==="..")||s.some(i=>!xF.has(i)&&!PF.test(i)))return!1;const a=i=>s.filter(r=>r===i).length,n=t==="owner/name"?"{owner}":"{namespace+}",o=t==="owner/name"?"{namespace+}":"{owner}";return a("{repo}")===1&&a("{number}")===1&&a(n)===1&&a(o)===0},AF=/^[A-Za-z0-9._-]+$/,zF=e=>e.length>0&&e.split("/").every(t=>AF.test(t)&&t!=="."&&t!==".."),xm=c().min(1).max(4).regex(/^\S+$/),Pn=c().trim().min(1).max(64),RF=d({projects:y().default(!1),issues:y().default(!1),changeRequests:y().default(!1),draftChangeRequests:y().default(!1),draftConversion:y().optional(),merge:M([m(!1),d({methods:C(S(["merge","squash","rebase","submit"])).min(1).max(3).refine(e=>new Set(e).size===e.length,{message:"merge methods must be unique"}).refine(e=>!e.includes("submit")||e.length===1,{message:'"submit" is the only merge method when present'})}).strict()]).default(!1),ci:y().default(!1),comments:y().default(!1),reviews:y().default(!1),state:y().default(!1),labels:y().default(!1),reviewers:y().default(!1),changeRequestPatch:y().default(!1),liveSummaries:y().default(!1),reviewModel:S(["verdict","votes"]).optional(),revisions:y().optional()}).strict(),IF=/^[A-Za-z0-9._-]{1,64}$/,Tm=C(c().trim().min(1)).max(BD),Rd=d({kind:m("service"),hint:c().min(1).max(2e3)}),jF=d({wire:m(1),label:Pn,terminology:d({changeRequest:S(["pullRequest","mergeRequest","change"]),ci:S(["checks","pipeline"])}).strict(),referencePrefix:d({changeRequest:xm,issue:xm}).strict(),repositoryPath:S(["owner/name","namespace/name"]),instances:d({defaultInstances:C(c().trim().refine(Mn,{message:"must be an https origin with no path, like https://git.example.com"})).max(MD).refine(e=>new Set(e).size===e.length,{message:"default instances must be unique"}),custom:y(),allowLoopbackHttp:y(),allowPort:y(),placeholder:c().trim().max(256)}).strict().refine(e=>e.custom||e.defaultInstances.length>0,{message:"without custom instances, defaultInstances names at least one"}),capabilities:RF,login:Rd.extend({hint:c().trim().pipe(Rd.shape.hint)}).strict().optional(),token:d({header:S(["authorization","private-token"]),scheme:S(["bearer","token","basic","none"]),username:y().optional(),scopes:C(c().trim().min(1).max(64)).max(32),createPath:c().trim().max(256).refine(di,{message:'must be a path on the instance starting with "/", with no "." or ".." segment'}).optional()}).strict().refine(e=>e.header==="private-token"==(e.scheme==="none"),{message:"private-token takes the bare token; authorization takes a bearer, token or basic scheme"}).refine(e=>e.scheme==="basic"==(e.username===!0),{message:"the basic scheme needs username: true, and username is only for the basic scheme"}).optional(),transport:d({httpsUsername:M([d({kind:m("login")}).strict(),d({kind:m("fixed"),value:c().regex(IF)}).strict()]),appendDotGitToHttpsClone:y()}).strict(),limits:d({commentMaxLength:w().int().min(1).max(1e6),reviewerId:S(["numeric","login"]),labelsMax:w().int().min(0).max(100),reviewersMax:w().int().min(0).max(50)}).strict(),trackedItems:d({batchLimit:w().int().min(1).max(50)}).strict(),presentation:d({abbreviation:c().trim().min(1).max(8),promptNoun:Pn,sharedNumberSpace:y(),iconPath:c().max(8192).regex(SF).optional(),urls:d({changeRequest:Tm,issue:Tm}).strict(),features:d({authorCanReview:y().default(!1),issueCloseReason:y().default(!1),submitRequirements:y().optional()}).strict(),changeRequestTemplates:C(c().trim().max(256).refine(zF,{message:'must be a file path inside the repository, like .gitea/pull_request_template.md, with no "." or ".." segment'})).max(8)}).strict()}).strict().superRefine((e,t)=>{!e.login&&!e.token&&t.addIssue({code:"custom",path:["login"],message:"at least login or token is required"});for(const a of["changeRequest","issue"])e.presentation.urls[a].forEach((n,o)=>{TF(n,e.repositoryPath)||t.addIssue({code:"custom",path:["presentation","urls",a,o],message:`templates start with "/" and use literal segments and ${ow.join(", ")}: {repo} and {number} once, and ${e.repositoryPath==="owner/name"?"{owner}":"{namespace+}"} once for ${e.repositoryPath} paths.`})});const s=new Set(e.presentation.urls.changeRequest);e.presentation.urls.issue.forEach((a,n)=>{s.has(a)&&t.addIssue({code:"custom",path:["presentation","urls","issue",n],message:"is also a changeRequest template; a link names either a change request or an issue."})})}),Pw=d({header:S(["authorization","private-token"]),scheme:S(["bearer","token","basic","none"]),username:y().optional(),scopes:C(c().trim().min(1).max(64)).max(32).optional(),createPath:c().trim().max(256).refine(di,{message:'must be a path on the instance starting with "/", with no "." or ".." segment'}).optional()}).strict().refine(e=>e.header==="private-token"==(e.scheme==="none"),{message:"private-token takes the bare token; authorization takes a bearer, token or basic scheme"}).refine(e=>e.scheme==="basic"==(e.username===!0),{message:"the basic scheme needs username: true, and username is only for the basic scheme"}),OF=d({label:Pn,instances:M([d({kind:m("fixed"),origin:c().trim().refine(Mn,{message:"must be an https origin with no path, like https://slack.com"})}).strict(),d({kind:m("user"),label:Pn,placeholder:c().trim().max(256).optional()}).strict()]),token:Pw}).strict(),Bn=(e,t)=>new Set(e.map(t)).size===e.length,DF=/^[a-z][a-zA-Z0-9-]{0,31}$/,NF=Pw,Am=c().trim().min(1).max(2048).refine(e=>Jo(e)||di(e),{message:'must be an https URL, or a path on the instance starting with "/"'}),FF=d({wire:m(1),label:Pn,instances:M([d({kind:m("fixed"),origin:c().trim().refine(Mn,{message:"must be an https origin with no path, like https://tracker.example.com"})}).strict(),d({kind:m("user"),label:Pn,placeholder:c().trim().max(256).optional()}).strict()]),auth:d({token:NF.optional(),oauth:d({authorizeUrl:Am,tokenUrl:Am,scopes:C(c().trim().min(1).max(64)).max(32).optional()}).strict().optional()}).strict().refine(e=>e.token!==void 0||e.oauth!==void 0,{message:"declare token, oauth or both"}),capabilities:d({multipleAccounts:y().default(!1),stateUpdate:y().default(!1),children:y().default(!1),labels:y().default(!1),priority:y().default(!1),filters:d({people:y().default(!1),priority:y().default(!1)}).strict().default({people:!1,priority:!1}),projectMapping:y().default(!1),sessionComments:y().default(!1)}).strict(),stateFilters:C(c().trim().regex(DF)).min(ll.length).max(ED).refine(e=>new Set(e).size===e.length,{message:"state filters must be unique"}).refine(e=>ll.every((t,s)=>e[s]===t),{message:`state filters start with ${ll.map(e=>`"${e}"`).join(", ")}`}),identifier:S(nw),urls:d({item:C(c().trim().min(1)).min(1).max(aw).refine(e=>new Set(e).size===e.length,{message:"link templates must be unique"})}).strict()}).strict().superRefine((e,t)=>{e.urls.item.forEach((s,a)=>{Yp(s)||t.addIssue({code:"custom",path:["urls","item",a],message:`templates start with "/" and use literal segments and ${Qp.join(", ")}, with {id} once, in the path or as "?name={id}".`})})}),EF=d({providers:C(c().trim().refine(sw,{message:'must be an OpenCode provider id, like "openrouter"'})).max(ID).refine(e=>new Set(e).size===e.length,{message:"provider ids must be unique"})}).strict(),MF=d({id:c().trim().regex(aa).max(64),label:c().trim().min(1).max(gD),icon:c().trim().refine(tu).optional(),where:S(["message","session","selection","file","diff"]),mode:S(["open","background"]).optional(),roles:C(S(["user","assistant"])).min(1).max(2).optional(),payload:C(S(["messages"])).max(1).optional(),display:S(["label","icon","both"]).optional()}).refine(e=>e.where==="message"||e.roles===void 0,{path:["roles"]}).refine(e=>e.where==="session"||e.payload===void 0,{path:["payload"]}).refine(e=>e.where==="selection"||e.display===void 0,{path:["display"]}),BF=C(MF).min(1).max(uD).refine(e=>Bn(e,t=>t.id),{message:"action ids must be unique"}),LF=d({name:c().trim().regex(fD),description:c().trim().min(1).max(hD).optional()}),qF=C(LF).min(1).max(mD).refine(e=>Bn(e,t=>t.name),{message:"command names must be unique"}),xw=e=>[...e.matchAll(Br(vd))].map(t=>({text:t[0],root:t[1]??"",path:(t[2]??"").slice(1)})),Vi=c().trim().min(1).max(Mr).superRefine((e,t)=>{const s=xw(e),a=s.find(n=>n.root!=="output");if(a){t.addIssue({code:"custom",message:`a card reads the tool's output only: write {output.path} where it says ${a.text}.`});return}s.length===0&&t.addIssue({code:"custom",message:"needs at least one {output.path} placeholder."})}),VF=c().trim().min(1).max(Mr).superRefine((e,t)=>{const s=xw(e),a=s.find(r=>r.root==="input"||r.root==="metadata");if(a){t.addIssue({code:"custom",message:`a card link reads {output.path} and {settings.<id>} only, and it says ${a.text}.`});return}const n=s.find(r=>r.root==="settings"&&!aa.test(r.path));if(n){t.addIssue({code:"custom",message:`${n.text} must name one contributes.integration.settings field, like {settings.site}.`});return}if(!s.some(r=>r.root==="output")){t.addIssue({code:"custom",message:"needs at least one {output.path} placeholder."});return}if(s.length===1&&s[0]?.text===e)return;if(!Jo(e.replace(Br(vd),"x"))){t.addIssue({code:"custom",message:"an address written around placeholders starts with https://, has no user name or password, and takes no placeholder as its port."});return}const o=e.slice(8).split(/[/?#\\]/,1)[0]??"",i=[...o.matchAll(Br(vd))].find(r=>(o[r.index-1]??".")!=="."||(o[r.index+r[0].length]??".")!==".");i&&t.addIssue({code:"custom",message:`in the host ${i[0]} stands between dots or at either end, like https://{settings.site}/… or https://{output.team}.tracker.example/…; start the path with / before a placeholder.`})}),UF=d({label:Vi.optional(),title:Vi.optional(),status:d({value:Vi,tones:ke(c().min(1).max(TD),S(tw)).refine(e=>Object.keys(e).length<=xD).optional()}).strict().optional(),fields:C(d({label:c().trim().min(1).max(yd),value:Vi}).strict()).min(1).max(PD).optional(),link:d({label:c().trim().min(1).max(yd),url:VF}).strict().optional()}).strict().refine(e=>e.label!==void 0||e.title!==void 0||e.status!==void 0||e.fields!==void 0,{message:"needs label, title, status or fields; a link alone is not a card."}),WF=d({match:c().trim().min(1).max(wD).regex(yD),name:c().trim().min(1).max(yd).optional(),icon:c().trim().refine(tu).optional(),title:c().trim().min(1).max(Mr).optional(),subtitle:c().trim().min(1).max(Mr).optional(),output:S(AD).optional(),language:c().trim().min(1).max(vD).optional(),columns:C(c().trim().min(1).max(SD)).min(1).max(CD).optional(),card:UF.optional()}).refine(e=>e.output==="code"||e.language===void 0,{path:["language"]}).refine(e=>e.output==="table"==(e.columns!==void 0),{path:["columns"]}).refine(e=>e.output==="card"==(e.card!==void 0),{path:["card"],message:'card and output "card" come together: declare both or neither.'}),HF=C(WF).min(1).max(kD),GF=ke(c().refine(sw),c().trim().refine(aN)).refine(e=>{const t=Object.keys(e).length;return t>=1&&t<=bD}),_F=d({id:c().trim().regex(aa),title:c().trim().min(1).max(nF),match:C(c().trim().refine(yw)).min(1).max(oF),entry:c().trim().refine(e=>xt(e)&&e.toLowerCase().endsWith(".html")),content:S(["text","binary"]).optional()}),KF=C(_F).min(1).max(aF).refine(e=>Bn(e,t=>t.id),{message:"file editor ids must be unique"}),ZF=d({name:c().trim().regex(JD),description:c().trim().min(1).max(XD),args:C(c().trim().regex($D)).max(YD).refine(e=>new Set(e).size===e.length,{message:"argument names must be unique"}),entry:c().trim().refine(e=>xt(e)&&e.toLowerCase().endsWith(".html")),height:w().int().min(24).max(eN).optional(),answers:y().optional()}).strict(),JF=/^\d+(?:\.\d+){3}$/,$F=e=>vw(e)&&!JF.test(new URL(e).hostname),QF=d({action:S(KD),identifier:d({keys:C(c().trim().regex(_D)).min(1).max(GD).refine(e=>new Set(e).size===e.length,{message:"keys must be unique"})}).strict().optional(),urls:d({origin:c().trim().refine($F,{message:"must be a public https origin with no path, like https://tasks.example.com"}),identifier:S(nw),item:C(c().trim().min(1)).min(1).max(aw).refine(e=>new Set(e).size===e.length,{message:"link templates must be unique"})}).strict().optional()}).strict().superRefine((e,t)=>{if(!e.identifier&&!e.urls){t.addIssue({code:"custom",path:[],message:"declare identifier, urls or both"});return}if(e.urls?.item.forEach((s,a)=>{Yp(s)||t.addIssue({code:"custom",path:["urls","item",a],message:`templates start with "/" and use literal segments and ${Qp.join(", ")}, with {id} once, in the path or as "?name={id}".`})}),e.action==="attach"&&!e.urls?.item.some(ZD)){t.addIssue({code:"custom",path:["urls"],message:'action "attach" needs urls with at least one template without {segment} or {segments+}, so a chip can name its link.'});return}e.action==="attach"&&e.identifier&&e.urls?.identifier==="number"&&t.addIssue({code:"custom",path:["urls","identifier"],message:'action "attach" with identifier keys needs urls.identifier "key-number" or "short-code": a key like PROJ-12 cannot fill a "number" {id}, so its chip would have no link.'})}),YF=C(ZF).min(1).max(QD).refine(e=>Bn(e,t=>t.name),{message:"block names must be unique"}),XF=d({id:c().regex(GN),title:c().trim().min(1).max(_N),description:c().trim().min(1).max(KN),params:ke(c().regex(ZN),d({type:S($N),description:c().trim().min(1).max(JN).optional(),required:m(!0).optional()}).strict()).refine(e=>Object.keys(e).length<=Cm,{message:`at most ${Cm} params`}).optional(),interval:w().int().min(QN).max(YN).optional()}).strict(),eE=C(XF).min(1).max(HN).refine(e=>Bn(e,t=>t.id),{message:"wait ids must be unique"}),tE=d({panel:pF,background:d({entry:c().trim().refine(e=>xt(e)&&e.toLowerCase().endsWith(".html"))}).optional(),attach:dF.optional(),page:M([m(!0),d({entry:c().trim().refine(xt),title:c().trim().min(1).max(200).optional(),mobile:m(!0).optional()})]).optional(),statusSection:M([m(!0),d({entry:c().trim().refine(e=>xt(e)&&e.toLowerCase().endsWith(".html")).optional(),source:d({path:c().trim().refine(Td),interval:w().int().min(QO).max(YO).optional()}).strict().optional(),title:c().trim().min(1).max(dD).optional(),height:w().int().min(Xk).max(ew).optional(),defaultExpanded:y().optional(),requiresProject:y().optional()}).refine(e=>e.entry!==void 0||e.source!==void 0)]).optional(),capabilities:C(S(qD)).max(8).optional(),integration:fF.optional(),service:CF.optional(),filesystem:C(c().max(iw).refine(WD)).min(1).max(UD).optional(),origins:C(c().trim().refine(vw)).min(1).max(VD).refine(e=>new Set(e).size===e.length,{message:"origins must be unique"}).optional(),actions:BF.optional(),commands:qF.optional(),tools:HF.optional(),providerLogos:GF.optional(),fileEditors:KF.optional(),sourceControl:jF.optional(),sessionEvents:d({events:C(S(Ad)).min(1).max(Ad.length).refine(e=>new Set(e).size===e.length,{message:"event types must be unique"}),content:m(!0).optional()}).strict().optional(),waits:eE.optional(),notifications:OF.optional(),tracker:FF.optional(),quota:EF.optional(),sessionControl:d({content:m(!0).optional(),answers:m(!0).optional()}).strict().optional(),instructions:m(!0).optional(),marks:m(!0).optional(),skills:c().trim().refine(xt).optional(),opencodePlugin:c().trim().refine(xt).optional(),mentions:d({label:c().trim().min(1).max(HD)}).strict().optional(),blocks:YF.optional(),links:QF.optional()}),Tw=e=>!!(e.statusSection&&e.statusSection!==!0&&e.statusSection.source),sE=e=>e.statusSection===!0||!!e.statusSection?.entry,aE=e=>!!(e.page&&e.page!==!0),nE=e=>{const t=[];return e.page!==void 0&&t.push("page"),e.attach!==void 0&&e.attach!==!1&&t.push("attach"),e.capabilities&&e.capabilities.length>0&&t.push("capabilities"),e.integration!==void 0&&t.push("integration"),e.service!==void 0&&!e.service.provides?.length&&!e.service.surface&&!e.service.keepRunning&&!e.service.schedule&&!Tw(e)&&e.sessionEvents===void 0&&e.mentions===void 0&&e.waits===void 0&&t.push("service"),e.filesystem!==void 0&&t.push("filesystem"),e.origins!==void 0&&t.push("origins"),e.actions!==void 0&&t.push("actions"),e.commands!==void 0&&t.push("commands"),t},oE=d({apiVersion:m(JO[0]),engines:d({openchamber:c().trim().regex($O)}).strict().optional(),contributes:tE.superRefine((e,t)=>{const s=new Map((e.integration?.settings??[]).map(p=>[p.id,p]));e.tools?.forEach((p,u)=>{for(const g of zD([p])){const h=s.get(g);h&&!h.secret||t.addIssue({code:"custom",path:["tools",u,"card","link","url"],message:h?`{settings.${g}} names a secret field, and a link reads only a field without "secret".`:`{settings.${g}} names no contributes.integration.settings field.`})}});const a=e.service?.provides?.includes("source-control")===!0;if(a!==(e.sourceControl!==void 0)){t.addIssue({code:"custom",path:["service","provides"],message:'service.provides "source-control" and contributes.sourceControl come together: declare both or neither.'});return}if(a&&e.panel.id.length>mm){t.addIssue({code:"custom",path:["service","provides"],message:`A source-control extension's panel.id is at most ${mm} characters: OpenChamber names its Git host "ext-<panel.id>".`});return}const n=e.service?.provides?.includes("notifications")===!0;if(n!==(e.notifications!==void 0)){t.addIssue({code:"custom",path:["service","provides"],message:'service.provides "notifications" and contributes.notifications come together: declare both or neither.'});return}if(n&&e.panel.id.length>hm){t.addIssue({code:"custom",path:["service","provides"],message:`A notifications extension's panel.id is at most ${hm} characters: OpenChamber names its channel "ext-<panel.id>".`});return}const o=e.service?.provides?.includes("tracker")===!0;if(o!==(e.tracker!==void 0)){t.addIssue({code:"custom",path:["service","provides"],message:'service.provides "tracker" and contributes.tracker come together: declare both or neither.'});return}if(o&&e.panel.id.length>bm){t.addIssue({code:"custom",path:["service","provides"],message:`A tracker extension's panel.id is at most ${bm} characters: OpenChamber names its tracker "ext-<panel.id>".`});return}if(o&&a){t.addIssue({code:"custom",path:["service","provides"],message:'An extension is a Git host ("source-control") or a tracker ("tracker"), never both: the two roles would share the id "ext-<panel.id>".'});return}const i=e.service?.provides?.includes("quota")===!0;if(i!==(e.quota!==void 0)){t.addIssue({code:"custom",path:["service","provides"],message:'service.provides "quota" and contributes.quota come together: declare both or neither.'});return}if(i&&e.panel.id.length>fm){t.addIssue({code:"custom",path:["service","provides"],message:`A quota extension's panel.id is at most ${fm} characters: OpenChamber names its usage provider "ext-<panel.id>".`});return}if((e.panel.dock!==void 0||e.panel.size!==void 0)&&!(e.service?.surface&&qi(e))){t.addIssue({code:"custom",path:["panel","dock"],message:"panel.dock and panel.size place panel.entry beside service.surface; they need both."});return}if(e.statusSection===!0&&!qi(e)){t.addIssue({code:"custom",path:["statusSection"],message:'contributes.statusSection: true reuses panel.entry; without a panel page, name its own { "entry": "<package .html>" }.'});return}if(Tw(e)&&!e.service){t.addIssue({code:"custom",path:["statusSection","source"],message:"contributes.statusSection.source is read from the extension's service; declare contributes.service."});return}if(e.sessionEvents!==void 0&&!e.service){t.addIssue({code:"custom",path:["sessionEvents"],message:"contributes.sessionEvents are posted to the extension's service; declare contributes.service."});return}if(e.links?.action==="open"&&!qi(e)){t.addIssue({code:"custom",path:["links","action"],message:'contributes.links action "open" opens panel.entry with the link; declare panel.entry, or use action "attach".'});return}for(const p of["sessionControl","instructions","marks","mentions","waits"])if(e[p]!==void 0&&!e.service){t.addIssue({code:"custom",path:[p],message:`contributes.${p} is served by the extension's service; declare contributes.service.`});return}if(qi(e))return;if(e.background){const p=[];e.page===!0&&p.push("page: true"),e.attach!==void 0&&e.attach!==!1&&p.push("attach"),e.actions?.some(u=>u.mode!=="background")&&p.push('actions with mode "open"'),p.length>0&&t.addIssue({code:"custom",path:["panel"],message:`${p.join(", ")} needs panel.entry; background-only actions must declare mode "background".`});return}if(sE(e)||e.fileEditors||e.blocks||aE(e)){const p=[];e.page===!0&&p.push("page"),e.attach!==void 0&&e.attach!==!1&&p.push("attach"),e.actions!==void 0&&p.push("actions"),e.commands!==void 0&&p.push("commands"),p.length>0&&t.addIssue({code:"custom",path:["panel"],message:`${p.map(u=>`contributes.${u}`).join(", ")} needs panel.entry or background.entry; a status section, file editor or block only hosts itself.`});return}const l=nE(e);l.length!==0&&t.addIssue({code:"custom",path:["panel"],message:`${l.map(p=>`contributes.${p}`).join(", ")} needs panel.entry or background.entry; an extension without either may only declare tools and provider logos.`})})}),iE=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,rE=c().trim().regex(iE).max(64);d({version:rE.optional(),openchamber:oE});M([d({openchamber:xs()}),d({openchamber:d({}).passthrough()})]);const cE=tr({id:c().optional(),name:c().optional(),icon:c().optional(),contributes:tr({panel:tr({}).optional()}).optional()});tr({openchamber:cE});const lE=128,dE=65536,GJ=2097152,_J=16777216,pE=2e3,ct=c().trim().min(1).max(1024),Ui=S(["loading","ready","error"]),zm=d({directory:ct,name:c(),branch:c(),status:S(["ready","pending","invalid","missing"])}),Rm=X("kind",[d({kind:m("projects")}).strict(),d({kind:m("worktrees"),projectId:ct}).strict(),d({kind:m("sessions"),projectId:ct}).strict()]),Aw=X("kind",[d({kind:m("projects"),state:Ui,projects:C(d({id:ct,name:c(),directory:ct}))}),d({kind:m("worktrees"),projectId:ct,state:Ui,worktrees:C(zm)}),d({kind:m("sessions"),projectId:ct,state:Ui,coverage:C(d({directory:ct,state:Ui})),sessions:C(d({id:ct,title:c(),projectId:ct,directory:ct,agent:c().optional(),parentId:ct.nullable(),createdAt:w(),updatedAt:w(),archivedAt:w().nullable(),worktree:zm.nullable(),activity:S(["unknown","idle","running","retrying","waiting-permission","waiting-question"]),outcome:S(["completed","failed"]).nullable(),items:C(d({id:ct,data:at().optional()})),links:C(d({title:c(),url:c(),kind:S(["issue","change"]),linkedAt:w()})).optional(),inWork:y().optional(),unread:y().optional(),tool:d({name:c(),target:c().nullable()}).nullable().optional(),context:d({tokens:w().nonnegative(),limit:w().positive().nullable()}).nullable().optional()}))})]),uE=M([y(),d({kind:m("existing"),directory:ct}).strict(),d({kind:m("new"),name:c().trim().min(1).max(200).optional(),baseBranch:c().trim().min(1).max(200).optional()}).strict()]),gr=c().min(1).max(lE),gE=X("op",[d({op:m("get"),key:gr,scope:S(["instance","device"]).optional()}).strict(),d({op:m("delete"),key:gr,scope:S(["instance","device"]).optional()}).strict(),d({op:m("set"),key:gr,value:at().refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=dE),scope:S(["instance","device"]).optional()}).strict(),d({op:m("keys"),scope:S(["instance","device"]).optional()}).strict()]),mE=M([d({storage:m(!0),op:m("get"),found:m(!1)}),d({storage:m(!0),op:m("get"),found:m(!0),value:at()}),d({storage:m(!0),op:S(["set","delete"])}),d({storage:m(!0),op:m("keys"),keys:C(gr).max(pE)})]),hE=4,zw=/^[a-z][a-z0-9-]{0,39}$/,Rw=60,Iw=16,cc=80,su=c().regex(zw),au=c().min(1).max(Rw),fE=d({value:c().min(1).max(cc),label:au}).strict(),bE=d({kind:m("button"),id:su,label:au,disabled:y().optional()}).strict(),kE=d({kind:m("select"),id:su,label:au,value:c().min(1).max(cc),options:C(fE).min(1).max(Iw),disabled:y().optional()}).strict().refine(e=>new Set(e.options.map(t=>t.value)).size===e.options.length,{message:"status control option values must be unique",path:["options"]}).refine(e=>e.options.some(t=>t.value===e.value),{message:"status control value must be one of its options",path:["value"]}),jw=C(X("kind",[bE,kE])).max(hE).refine(e=>new Set(e.map(t=>t.id)).size===e.length,{message:"status control ids must be unique"}),wE=d({id:su,value:c().min(1).max(cc).optional()}).strict(),xn=c().regex(zw),ea=c().min(1).max(Rw),nu=c().min(1).max(cc),Ow=c().min(1).max(oD),xa=S(["default","muted","accent","success","warning","error","info"]),Wi=w().finite(),yE=e=>{try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}},vE=d({value:nu,label:ea}).strict(),Dw=(e,t,s)=>d({kind:m(e),id:xn,label:ea,value:nu,options:C(vE).min(t).max(s),disabled:y().optional()}).strict().refine(a=>new Set(a.options.map(n=>n.value)).size===a.options.length,{message:"option values must be unique",path:["options"]}).refine(a=>a.options.some(n=>n.value===a.value),{message:"value must be one of its options",path:["value"]}),CE=d({id:xn,label:ea,tone:xa.optional(),url:c().max(2e3).refine(yE,{message:"chip url must be http(s)"}).optional()}).strict(),SE=M([d({kind:m("bar"),value:Wi.min(0).max(100),tone:xa.optional()}).strict(),d({kind:m("chart"),values:C(Wi.min(0)).max(sD),max:Wi.positive().optional(),tone:xa.optional(),unit:S(["bytes","percent","count"]).optional(),step:Wi.positive().max(3600).optional()}).strict(),d({kind:m("chips"),chips:C(CE).min(1).max(tD)}).strict(),d({kind:m("text"),text:Ow,tone:xa.optional()}).strict(),Dw("segmented",aD,nD)]),PE=M([d({kind:m("button"),id:xn,label:ea,variant:S(["default","outline","destructive"]).optional(),confirm:ea.optional(),disabled:y().optional()}).strict(),d({kind:m("switch"),id:xn,label:ea,checked:y(),disabled:y().optional()}).strict(),Dw("select",1,Iw)]),xE=M([d({kind:m("line"),id:xn,label:ea,icon:c().regex(Yk).optional(),dot:xa.optional(),content:SE.optional(),value:nu.optional(),valueTone:xa.optional(),badge:d({label:ea,tone:xa.optional()}).strict().optional(),tooltip:Ow.optional(),actions:C(PE).max(eD).optional()}).strict(),d({kind:m("note"),id:xn,text:c().min(1).max(iD),tone:S(["muted","info","warning","error"]).optional()}).strict()]),TE=e=>[...(e.controls??[]).map(t=>t.id),...e.rows.flatMap(t=>t.kind==="line"?[...(t.actions??[]).map(s=>s.id),...t.content?.kind==="segmented"?[t.content.id]:[]]:[])],KJ=d({rows:C(xE).max(XO),controls:jw.optional()}).strict().refine(e=>new Set(e.rows.map(t=>t.id)).size===e.rows.length,{message:"row ids must be unique",path:["rows"]}).refine(e=>{const t=TE(e);return new Set(t).size===t.length},{message:"control ids must be unique across the view"}),Im=c().trim().min(1).max(kw),Bs=c().trim().min(1).max(256),Ls=c().trim().min(1).max(256),Id=c().trim().min(1).max(4096),jm=c().trim().min(1).max(WN),AE=d({target:M([d({sessionId:Bs}).strict(),d({directory:Id,branch:Ls.optional()}).strict()]),mark:d({icon:c().regex(Yk),tone:S(tw),text:c().trim().min(1).max(FN),url:c().trim().max(EN).refine(Jo).optional()}).strict().nullable()}).strict();X("method",[d({method:m("sessions.start"),input:d({prompt:Im,projectId:Ls.optional(),directory:Id.optional(),title:Ls.optional(),model:Ls.optional(),variant:Ls.optional(),agent:Ls.optional()}).strict().refine(e=>!(e.projectId&&e.directory),{message:"Give projectId or directory, not both"})}).strict(),d({method:m("sessions.send"),input:d({sessionId:Bs,prompt:Im}).strict()}).strict(),d({method:m("sessions.retry"),input:d({sessionId:Bs}).strict()}).strict(),d({method:m("sessions.status"),input:d({sessionId:Bs}).strict()}).strict(),d({method:m("sessions.lastReply"),input:d({sessionId:Bs}).strict()}).strict(),d({method:m("sessions.stop"),input:d({sessionId:Bs}).strict()}).strict(),d({method:m("sessions.answerPermission"),input:d({sessionId:Bs,requestId:Ls,decision:S(["allow","deny"]),message:jm.optional()}).strict()}).strict(),d({method:m("sessions.answerForm"),input:d({sessionId:Bs,formId:Ls,values:ke(c().min(1).max(256),M([c().max(kw),w(),y(),C(c().max(1e3)).max(100)])).nullable(),message:jm.optional()}).strict()}).strict(),d({method:m("instructions.set"),input:d({directory:Id.nullable(),text:c().max(ON)}).strict()}).strict(),d({method:m("panels.emit"),input:d({topic:c().trim().min(1).max(DN),data:at().optional()}).strict()}).strict(),d({method:m("settings.read"),input:d({}).strict()}).strict(),d({method:m("status.set"),input:d({needsConfiguration:c().trim().min(1).max(NN).nullable()}).strict()}).strict(),d({method:m("marks.set"),input:AE}).strict()]);d({id:c().min(1).max(VN),title:c().trim().min(1).max(vm),subtitle:c().trim().min(1).max(vm).optional(),url:Yv({protocol:/^https?$/}).max(2048).optional()});d({text:c().trim().min(1).max(UN)});const Nw=/^[A-Za-z0-9_-]{1,80}$/,Wa=1e5,zE=160,RE=640,IE=48,jE=480,zo=16e3,OE=32,DE=["left","right","top","bottom"],NE=["escape","outside","anchor","owner","closed","replaced"],FE=M([c().max(zo),w(),y(),xs()]),EE=ke(c().max(zo),ne()),Fw=Kr(e=>{const t=[{value:e,depth:0}];let s=0;for(;t.length>0;){const a=t.pop();if(!a)break;const n=a.value;if(a.depth>=OE)return!1;if(Array.isArray(n)){if(n.length>zo||Object.keys(n).some(o=>!/^(0|[1-9]\d*)$/.test(o)||Number(o)>=n.length))return!1;s+=2+Math.max(0,n.length-1);for(const o of n)t.push({value:o,depth:a.depth+1})}else{const o=FE.safeParse(n);if(o.success)s+=JSON.stringify(o.data).length;else{if(!EE.safeParse(n).success)return!1;const r=Object.getPrototypeOf(n);if(r!==null&&r!==Object.prototype)return!1;const l=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,p])=>p.enumerable);s+=2+Math.max(0,l.length-1);for(const[p,u]of l){if(!("value"in u)||(s+=JSON.stringify(p).length+1,s>zo))return!1;t.push({value:u.value,depth:a.depth+1})}}}if(s>zo)return!1}return!0},"Popover data must be finite JSON within its size and depth limits."),ME=d({id:c().regex(Nw),anchor:d({x:w().finite().min(-Wa).max(Wa),y:w().finite().min(-Wa).max(Wa),width:w().finite().positive().max(Wa),height:w().finite().positive().max(Wa)}).strict(),width:w().int().min(zE).max(RE),height:w().int().min(IE).max(jE),side:S(DE).optional(),focus:y().optional(),data:Fw}).strict(),BE=d({id:c().regex(Nw),reason:S(NE)}).strict(),jd=128,Om=200,LE=65536,qE=["exited","timeout","killed","stopped","unknown"],Ew=Xv(Uint8Array).refine(e=>e.byteLength<=ww),Mw=c().max(ww),L={channel:m(KO),v:m(ZO)},VE=d({background:c().min(1),elevated:c().min(1),foreground:c().min(1),muted:c().min(1),subtle:c().min(1),border:c().min(1),hover:c().min(1),selection:c().min(1),focus:c().min(1),primary:c().min(1),mutedSurface:c().min(1),elevatedForeground:c().min(1),active:c().min(1),selectionForeground:c().min(1),primaryForeground:c().min(1),primaryText:c().min(1),successText:c().min(1),warningText:c().min(1),errorText:c().min(1),infoText:c().min(1),success:c().min(1),warning:c().min(1),error:c().min(1),info:c().min(1),font:c().min(1),fontSize:c().min(1).optional(),mono:c().min(1),radius:c().min(1),syntaxKeyword:c().min(1).optional(),syntaxString:c().min(1).optional(),syntaxNumber:c().min(1).optional(),syntaxFunction:c().min(1).optional(),syntaxType:c().min(1).optional(),syntaxComment:c().min(1).optional(),syntaxVariable:c().min(1).optional(),syntaxOperator:c().min(1).optional()}),Bw=d({id:c().min(1),title:c().min(1),busy:y().optional().default(!1),model:c().min(1).max(pN).optional(),agent:c().min(1).max(uN).optional()}).nullable(),Lw=d({connected:y(),account:c().max(dN)}),qw=ke(c().regex(IN),c().max(gN)),UE=d({status:w().int().min(100).max(599),body:c().max(mN)}),Dm=d({directory:c(),name:c(),branch:c(),status:S(["ready","pending","invalid","missing"])}),WE=M([d({sessionId:c().min(1),sent:S(rw),directory:c().optional(),worktree:Dm.optional(),linked:y().optional()}),d({sessionId:xs(),sent:m("skipped"),directory:c(),worktree:Dm,failure:S(["bootstrap-failed","session-create-failed"])})]),HE=d({sent:S(rw)}),GE=d({status:S(bw)}),_E=d({content:c().max(hw)}),KE=d({written:m(!0)}),ZE=d({entries:C(d({name:c().min(1),kind:S(iN)})).max(hN)}),JE=d({kind:S(cw),size:w().int().min(0),mtime:w().int().min(0)}),Vw=d({text:c().max(wN)}),Od=d({prompt:c().trim().min(1).max(fN),system:c().trim().min(1).max(bN).optional(),maxOutputTokens:w().int().min(1).max(kN).optional()}),$E=X("ok",[d({request:Od,ok:m(!0),result:Vw}),d({request:Od,ok:m(!1),code:S(fw),error:c().min(1)})]),QE=d({output:c(),cursor:w(),skipped:y()}),YE=d({stopped:m(!0)}),XE=M([mE,Aw,QE,YE,WE,UE,HE,GE,_E,KE,ZE,JE,Vw]),ho=d({providerId:c().trim().regex(RN),id:c().trim().min(1).max(Xp),title:c().trim().min(1).max(dw),url:c().trim().min(1).max(rc),text:c().trim().min(1).max(pw).optional(),kind:S(["issue","pull"]).optional(),author:c().trim().min(1).max(uw).optional(),branches:d({head:c().trim().min(1).max(Sd),base:c().trim().min(1).max(Sd)}).optional(),data:at().refine(e=>JSON.stringify(e).length<=gw).optional()}),Uw=S(["user","assistant"]),Ww=d({kind:m("message"),action:c().trim().min(1).max(64),sessionId:c().min(1),sessionTitle:c(),directory:c().nullable(),messageId:c().min(1),role:Uw,text:c().max(eu)}),Hw=d({kind:m("session"),action:c().trim().min(1).max(64),sessionId:c().min(1),sessionTitle:c(),directory:c().nullable(),messages:C(d({id:c().min(1),role:Uw,text:c().max(eu),createdAt:w().int().min(0)})).optional(),truncated:y().optional()}).refine(e=>JSON.stringify(e).length<=yN),Gw=d({kind:m("selection"),action:c().trim().min(1).max(64),sessionId:c().min(1),directory:c().nullable(),messageId:c().min(1),text:c().max(eu)}),_w=d({kind:m("file"),action:c().trim().min(1).max(64),directory:c().nullable(),path:c().min(1),isDirectory:y()}),Kw=d({kind:m("diff"),action:c().trim().min(1).max(64),directory:c().nullable(),path:c().min(1),startLine:w().int().min(0),endLine:w().int().min(0),side:S(["additions","deletions"]).optional()}),eM=d({kind:m("link"),identifier:c().trim().min(1).max(Xp),url:c().trim().min(1).max(rc).optional()}).strict(),Zw=M([Ww,Hw,Gw,_w,Kw,eM,ho]).nullable(),Xn=w().finite().min(0),tM=d({formFactor:S(rN),pointer:S(cN),insets:d({top:Xn,right:Xn,bottom:Xn,left:Xn}),keyboard:Xn}),sM=d({theme:d({mode:S(["light","dark"]),tokens:VE}),locale:c().min(1),directory:c().nullable(),session:Bw,surface:S(["panel","dialog","page","background","status","file","popover","block"]),connection:Lw,settings:qw,item:Zw,block:d({name:c().min(1),args:ke(c(),c()),answered:c().nullable()}).optional(),popover:d({id:c().min(1).max(80),data:Fw}).strict().optional(),features:d({deviceStorage:m(!0).optional(),statusControls:m(!0).optional(),popovers:m(!0).optional(),lateGenerateResults:m(!0).optional()}).optional(),device:tM.optional()}),aM=d({...L,type:m("result"),id:c().min(1),ok:y(),error:c().min(1).optional(),code:c().min(1).optional(),payload:XE.optional()}).transform((e,t)=>e.ok?e.payload?{channel:e.channel,v:e.v,type:"result",id:e.id,ok:!0,payload:e.payload}:{channel:e.channel,v:e.v,type:"result",id:e.id,ok:!0}:e.error?{channel:e.channel,v:e.v,type:"result",id:e.id,ok:!1,error:e.error,code:xN(e.code)}:(t.addIssue({code:"custom",message:"Failed result needs an error string."}),eC)),Jw=d({id:c().min(1).max(jd),sessionID:c().min(1).max(1024),command:c(),startedAt:w().nonnegative(),background:y()}).strict(),nM=Jw.extend({status:S(qE),exit:w().int().optional(),endedAt:w().nonnegative()}).strict(),$w=X("kind",[d({kind:m("session"),sessionId:c().min(1).max(1024)}).strict(),d({kind:m("project"),projectId:c().min(1).max(1024)}).strict(),d({kind:m("global")}).strict()]),oM=d({kind:m("shells"),scope:$w,shells:C(Jw).max(Om),ended:C(nM).max(Om)}).strict();M([d({...L,type:m("workspace"),payload:d({subscriptionId:c().min(1).max(128),snapshot:Aw})}),d({...L,type:m("shells"),payload:d({subscriptionId:c().min(1).max(128),snapshot:oM})}),d({...L,type:m("ready"),payload:sM}),d({...L,type:m("directory"),payload:d({directory:c().nullable()})}),d({...L,type:m("session"),payload:d({session:Bw})}),d({...L,type:m("connection"),payload:d({connection:Lw})}),d({...L,type:m("settings"),payload:d({settings:qw})}),d({...L,type:m("session-lifecycle"),payload:d({sessionId:c().min(1),phase:S(oN)})}),d({...L,type:m("item"),payload:d({item:Zw})}),d({...L,type:m("service-event"),payload:d({topic:c().min(1),data:at()})}),d({...L,type:m("status-control-event"),payload:wE}),d({...L,type:m("popover-closed"),payload:BE}),d({...L,type:m("resolve"),id:c().min(1),payload:d({command:c().min(1),args:c()})}),aM,d({...L,type:m("action"),id:c().min(1),payload:M([Ww,Hw,Gw,_w,Kw])}),d({...L,type:m("file-open"),payload:M([d({path:c().min(1).max(4096),name:c().min(1).max(1024),readOnly:y(),encoding:m("text"),content:Mw}),d({path:c().min(1).max(4096),name:c().min(1).max(1024),readOnly:y(),encoding:m("binary"),bytes:Ew})])}),d({...L,type:m("file-snapshot"),id:c().min(1),payload:d({purpose:S(["save","handoff"])})}),d({...L,type:m("file-saved"),payload:d({version:c().max(zd)})}),d({...L,type:m("generate-late"),payload:$E})]);const Hi=c().min(1).max(mw).refine(zN),ZJ=X("type",[d({...L,type:m("action-result"),id:c().min(1),payload:X("ok",[d({ok:m(!0)}),d({ok:m(!1),error:c().trim().min(1).max(dl)})])}),d({...L,type:m("workspace-read"),id:c().min(1),payload:Rm}),d({...L,type:m("workspace-subscribe"),id:c().min(1),payload:d({subscriptionId:c().min(1).max(128),query:Rm})}),d({...L,type:m("workspace-unsubscribe"),id:c().min(1),payload:d({subscriptionId:c().min(1).max(128)})}),d({...L,type:m("shells-subscribe"),id:c().min(1),payload:d({subscriptionId:c().min(1).max(128),scope:$w}).strict()}),d({...L,type:m("shells-unsubscribe"),id:c().min(1),payload:d({subscriptionId:c().min(1).max(128)}).strict()}),d({...L,type:m("shell-output"),id:c().min(1),payload:d({shellId:c().min(1).max(jd),cursor:w().int().nonnegative().optional(),tailBytes:w().int().positive().max(LE).optional()}).strict()}),d({...L,type:m("shell-stop"),id:c().min(1),payload:d({shellId:c().min(1).max(jd)}).strict()}),d({...L,type:m("storage"),id:c().min(1),payload:gE}),d({...L,type:m("status-controls"),id:c().min(1),payload:d({controls:jw}).strict()}),d({...L,type:m("popover-open"),id:c().min(1),payload:ME}),d({...L,type:m("popover-close"),id:c().min(1),payload:d({id:c().min(1).max(80),reason:S(["closed","escape"]).optional()}).strict()}),d({...L,type:m("popover-anchor"),id:c().min(1),payload:d({id:c().min(1).max(80),active:y()}).strict()}),d({...L,type:m("open-session"),id:c().min(1),payload:d({sessionId:c().min(1).max(1024)})}),d({...L,type:m("hello")}),d({...L,type:m("toast"),id:c().min(1),payload:d({kind:S(["info","success","error"]),message:c().trim().min(1).max(lN),copy:M([y(),d({text:c().min(1).max(km)})]).optional(),dismiss:y().optional(),persistent:y().optional()})}),d({...L,type:m("open-url"),id:c().min(1),payload:d({url:c().trim().min(1).max(rc)})}),d({...L,type:m("block-answer"),id:c().min(1),payload:d({text:c().trim().min(1).max(nN)})}),d({...L,type:m("open-surface"),id:c().min(1),payload:d({surfaceId:c().trim().min(1).max(64)})}),d({...L,type:m("clipboard-write"),id:c().min(1),payload:d({text:c().min(1).max(km)})}),d({...L,type:m("compose"),id:c().min(1),payload:d({text:c().trim().min(1).max(Cd),mode:S(["replace","append"]).optional()})}),d({...L,type:m("attach"),id:c().min(1),payload:ho}),d({...L,type:m("start-session"),id:c().min(1),payload:ho.extend({worktree:uE.optional(),projectId:c().trim().min(1).max(1024).optional(),navigation:S(["preserve","open"]).optional()})}),d({...L,type:m("prompt"),id:c().min(1),payload:d({text:c().trim().min(1).max(Cd),send:y().optional()})}),d({...L,type:m("session-link"),id:c().min(1),payload:ho}),d({...L,type:m("close"),id:c().min(1)}),d({...L,type:m("oauth-start"),id:c().min(1)}),d({...L,type:m("oauth-disconnect"),id:c().min(1)}),d({...L,type:m("request"),id:c().min(1),payload:d({method:S(["GET","POST","PUT","PATCH","DELETE"]),path:c().trim().min(1).max(Pd).refine(Td),query:ke(c().min(1).max(128),c().max(2e3)).optional(),body:c().max(wm).optional()})}),d({...L,type:m("service-request"),id:c().min(1),payload:d({method:S(["GET","POST","PUT","PATCH","DELETE"]),path:c().trim().min(1).max(Pd).refine(Td),query:ke(c().min(1).max(128),c().max(2e3)).optional(),body:c().max(wm).optional()})}),d({...L,type:m("service-status"),id:c().min(1)}),d({...L,type:m("file-read"),id:c().min(1),payload:d({path:Hi})}),d({...L,type:m("file-write"),id:c().min(1),payload:d({path:Hi,content:c().max(hw)})}),d({...L,type:m("file-list"),id:c().min(1),payload:d({path:Hi})}),d({...L,type:m("file-stat"),id:c().min(1),payload:d({path:Hi})}),d({...L,type:m("generate"),id:c().min(1),payload:Od}),d({...L,type:m("badge"),id:c().min(1),payload:d({count:w().int().min(0).max(vN).nullable()})}),d({...L,type:m("open-commit"),id:c().min(1),payload:d({sha:c().regex(lw)})}),d({...L,type:m("resize"),id:c().min(1),payload:d({height:w().int().min(0).max(CN)})}),d({...L,type:m("resolve-result"),id:c().min(1),payload:M([d({item:ho.nullable()}),d({error:c().trim().min(1).max(dl)})])}),d({...L,type:m("file-snapshot-result"),id:c().min(1),payload:M([d({snapshot:M([d({content:Mw,version:c().max(zd)}),d({bytes:Ew,version:c().max(zd)})])}),d({error:c().trim().min(1).max(dl)})])}),d({...L,type:m("file-change"),payload:d({dirty:y(),edited:y()})}),d({...L,type:m("file-save")}),d({...L,type:m("file-unsupported")}),d({...L,type:m("generate-late-listen")})]),Qw=["browser.open","browser.snapshot","browser.click","browser.type","browser.select","browser.scroll","browser.back","browser.forward","browser.inspect","browser.capture","browser.resize","browser.close"];new Set(Qw);const iM=["auth.verify","auth.probe","auth.status","changeRequestStatus","listChangeRequests","changeRequestContext","listIssues","getIssue","issueComments","projectUpstream","projectBranches","listLabels","listReviewerCandidates","readChangeRequestPatch","readChangeRequestFile","liveSummaries","readChangeRequestHead","resolveChangeRequestSource","mutation.resolveTarget","mutation.perform","mutation.reconcile"],rM=8e6,Yw=2e3,Nm=4096,cM=["GET","POST","PUT","PATCH","DELETE"],lM=["accept","content-type","if-none-match","range"],dM=1e6,pM=["auth.verify","auth.probe","notify"],uM=["auth.probe","auth.verify","items.list","items.get","items.updateState","items.liveSummaries","states.list","containers.list","comments.create"],$o=100,gM=50,mM=500,hM=["usage.read"],fM=2e3,Fm=32,Em=64,bM=128,kM=128;M([d({ok:m(!0),data:d({}).passthrough()}),d({ok:m(!1),error:c().min(1).max(2e3)})]);M([d({ok:m(!0)}).strict(),d({ok:m(!1),error:c().min(1).max(jN)}).strict()]);S(Qw);const ee=c().min(1).max(1024),Lr=c().max(1024).optional(),As=w().int().positive().max(Number.MAX_SAFE_INTEGER),wM=c().min(1).max(256),yM=M([As,wM]),vM=w().int().nonnegative().max(Number.MAX_SAFE_INTEGER),ou=c().regex(/^[0-9a-fA-F]{40}$/).transform(e=>e.toLowerCase()),Qo=d({id:ee,owner:ee,name:ee}).strict(),CM=d({message:c().min(1).max(Yw),status:w().int().min(400).max(599).optional(),code:c().regex(/^[A-Z_]{1,64}$/).optional()}).strict();M([d({ok:m(!0),data:at()}).strict(),d({ok:m(!1),error:CM}).strict()]);const Xw=d({id:yM,login:c().min(1).max(256),name:Lr,email:Lr,avatarUrl:c().max(2048).optional()});d({user:Xw});d({supported:y(),version:c().max(128).optional(),message:c().max(Yw).optional()});d({project:Qo,headSha:ou,headBranch:ee,headOwner:ee});d({sourceProject:Qo,targetProject:Qo,classification:S(["same-repository","contributor-fork"]),headSha:ou,headRef:c().regex(/^refs\/heads\/\S+$/).max(1024),endpoint:c().min(1).max(2048)});const SM=d({repositoryId:ee,bindingRevision:vM,primaryRemote:ee,project:Qo,number:As.optional(),head:ee.optional(),base:ee.optional(),headSha:ee.optional()}).strict(),ey=ke(c(),at());d({providerTarget:ey.refine(e=>JSON.stringify(e).length<=Nm,{message:`providerTarget is at most ${Nm} characters of JSON`}),target:SM}).strict();const PM=d({project:Qo.optional(),number:As.optional(),head:ee.optional(),base:ee.optional(),headSha:ee.optional(),state:ee.optional(),merged:y().optional(),outcome:S(["queued","merging"]).optional(),stacked:y().optional(),ready:y().optional(),draft:y().optional(),commented:y().optional(),failureStatus:w().int().min(400).max(599).optional(),failureCode:ee.optional()}).strict();d({state:S(["succeeded","failed","outcome-unknown"]),result:PM.optional()}).strict();const Mm=50,xM=d({owner:ee,repo:ee,number:As,state:S(["open","closed","merged"]),draft:y(),title:c().max(4096),mergeable:y().nullable(),mergeableState:c().max(64).nullable(),checks:d({state:c().max(64)}).passthrough().nullable(),headSha:c().max(128).optional(),base:c().max(1024).optional()}),TM=d({owner:ee,repo:ee,number:As,title:c().max(4096),state:S(["open","completed","not_planned"])});d({summaries:C(xM).max(Mm),issueSummaries:C(TM).max(Mm)});const AM=d({provider:ee,instance:ee}).passthrough(),Bm=d({provider:ee,instance:ee,id:ee,owner:ee,name:ee,url:ee}).passthrough(),zM=50,RM=d({number:As.nullable(),base:ee,layers:C(d({number:As,title:c().max(4096),url:ee,state:S(["open","closed","merged"]),draft:y(),head:ee}).passthrough()).max(zM)}).passthrough(),IM=d({sha:ou,changeId:c().min(1).max(128).nullable(),uploadedAs:As.nullable()}).strict();d({identity:AM,fetchedAt:w().optional(),project:Bm.nullable(),branch:c().min(1).max(1024),changeRequest:d({provider:ee,instance:ee,id:ee,number:As,project:Bm,title:c().max(4096),url:ee,state:S(["open","closed","merged"]),draft:y(),base:ee,head:ee}).passthrough().nullable(),ci:d({summary:d({state:c().max(64)}).passthrough()}).passthrough().nullable().optional(),canMerge:y().optional(),defaultBranch:c().max(1024).nullable().optional(),resolvedRemoteName:c().max(1024).nullable().optional(),localRevision:IM.optional(),stack:RM.nullable().optional()}).strict();M([ey,C(at())]).refine(e=>JSON.stringify(e).length<=rM,{message:"answer is larger than the response cap"});d({user:Xw.nullable()});d({method:S(cM),path:c().min(1).max(2048).regex(/^\/(?!\/)/),query:ke(c().max(256),c().max(2048)).optional(),headers:tC(S(lM),c().max(1024)).optional(),body:c().max(dM).optional()}).strict();S(iM);d({account:d({id:c().min(1).max(256),login:c().min(1).max(256),name:Lr})});d({delivered:m(!0)}).strict();S(pM);const Ia=c().min(1).max(1024),ty=c().max(4096),jM=c().min(1).max(2048).refine(e=>/^https?:\/\//i.test(e)&&URL.canParse(e),{message:"must be an http(s) URL"}),iu=S(["triage","backlog","todo","in-progress","done","canceled"]),OM=S(["none","urgent","high","medium","low"]),sy=d({name:c().max(256).nullable(),avatarUrl:c().max(2048).nullable()}).strict(),ay=d({id:Ia,key:c().max(64).nullable(),name:c().min(1).max(256)}).strict(),DM=d({id:Ia.nullable(),name:c().max(256),category:iu.nullable()}).strict(),ny={id:Ia,identifier:c().min(1).max(128),title:ty,url:jM,state:DM.nullable(),priority:OM.nullable().optional(),labels:C(d({id:Ia,name:c().min(1).max(256),color:c().max(32).nullable()}).strict()).max($o).optional(),assignee:sy.nullable().optional(),container:ay.nullable().optional(),progress:d({total:w().int().nonnegative(),done:w().int().nonnegative(),more:y()}).strict().nullable().optional(),updatedAt:c().max(64).nullable().optional()},oy=d({...ny,parent:xs().optional()}).strict(),iy=d({...ny,parent:oy.nullable().optional()}).strict(),NM=d({id:Ia,body:c().max(65536),createdAt:c().max(64).nullable(),author:sy.nullable()}).strict(),FM=iy.extend({description:c().max(262144).nullable().optional(),comments:C(NM).max($o).optional(),children:C(oy).max($o).optional(),childrenMore:y().optional()}).strict();d({account:d({id:c().min(1).max(256),login:c().min(1).max(256).nullable(),name:Lr,avatarUrl:c().max(2048).optional()}).strict()}).strict();d({items:C(iy).max($o),cursor:c().min(1).max(2048).nullable(),hasMore:y()}).strict();d({item:FM.nullable()}).strict();d({states:C(d({id:Ia,name:c().min(1).max(256),category:iu.nullable(),position:w()}).strict()).max($o*2)}).strict();d({items:C(d({identifier:c().min(1).max(128),title:ty,state:d({name:c().max(256),category:iu}).strict()}).strict()).max(gM)}).strict();d({containers:C(ay).max(mM)}).strict();d({comment:d({id:Ia}).strict().nullable()}).strict();S(uM);const EM=new Set(["__proto__","constructor","prototype"]),ry=c().min(1).max(bM).refine(e=>!EM.has(e),{message:"reserved name"}),cy=c().max(kM),Gi=w().finite().nonnegative(),MM=d({usedPercent:Gi.nullable(),windowSeconds:w().int().positive().max(Number.MAX_SAFE_INTEGER).nullable().optional(),resetAt:w().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable().optional(),valueLabel:cy.nullable().optional(),value:X("kind",[d({kind:m("requests"),count:Gi}).strict(),d({kind:m("spend"),spent:Gi,limit:w().finite().positive().nullable()}).strict()]).optional(),creditsUsed:Gi.optional()}).strict(),Lm=ke(ry,MM).refine(e=>Object.keys(e).length<=Fm,{message:`at most ${Fm} windows`}),BM=d({windows:Lm,models:ke(ry,d({windows:Lm}).strict()).refine(e=>Object.keys(e).length<=Em,{message:`at most ${Em} models`}).optional()}).strict();d({ok:y(),configured:y(),error:c().min(1).max(fM).optional(),planLabel:cy.nullable().optional(),usage:BM.nullable()}).strict();S(hM);const ly=Kr(e=>e!==void 0&&JSON.stringify(e).length<=XN);M([d({ok:m(!0),state:ly.optional(),label:c().trim().min(1).max(tF).optional()}).strict(),d({ok:m(!1),error:c().min(1).max(sF)}).strict()]);d({results:C(at())}).strict();M([d({id:c().min(1),fired:m(!1),state:ly.optional()}).strict(),d({id:c().min(1),fired:m(!0),summary:c().trim().min(1).max(eF)}).strict()]);const LM=["image/jpeg","image/png"],qM=256,ru=64e3,VM=200,UM=16384,dy=["none","agent","user"];new Set(dy);const pl=d({alt:y(),ctrl:y(),meta:y(),shift:y()}),Ha=w().finite(),WM=X("type",[d({type:m("pointer"),action:S(["down","up","move"]),x:Ha,y:Ha,button:w().int().min(-1).max(4),buttons:w().int().min(0).max(31),modifiers:pl}),d({type:m("wheel"),x:Ha,y:Ha,deltaX:Ha,deltaY:Ha,modifiers:pl}),d({type:m("key"),action:S(["down","up"]),key:c().min(1).max(64),code:c().max(64),keyCode:w().int().min(0).max(255).optional(),modifiers:pl}),d({type:m("text"),text:c().min(1).max(ru)})]),Qs=w().int().min(1).max(UM);X("type",[d({type:m("ack"),seq:w().int().min(0)}),d({type:m("input"),events:C(WM).min(1).max(qM)}),d({type:m("release")}),d({type:m("resize"),width:Qs,height:Qs}),d({type:m("clipboard-read"),id:c().min(1).max(64)})]);const HM=S(dy),JJ=X("type",[d({type:m("hello"),viewerId:c().min(1)}),d({type:m("frame"),seq:w().int().min(0),width:Qs,height:Qs,mime:S(LM),bytes:w().int().min(1),title:c().max(VM).optional(),agentActive:y()}),d({type:m("control"),controller:HM,mine:y()}),d({type:m("resized"),width:Qs,height:Qs}),d({type:m("clipboard"),id:c().min(1).max(64),text:c().max(ru)}),d({type:m("error"),code:c().min(1).max(64),message:c().min(1).max(500)}),d({type:m("ended"),reason:S(["service-stopped","extension-unavailable","host-shutdown"])})]);d({width:Qs,height:Qs});d({text:c().max(ru)});const py=["guest","link","external","repository"],GM=new Set([...py,"linear"]),_s=c().regex(/^[a-z][a-z0-9-]{0,31}$/).refine(e=>!GM.has(e),{message:"Reserved provider id"}),_M=S(["pullRequest","mergeRequest","change"]),KM=S(["checks","pipeline"]),ZM=S(["device","pat","cli"]),JM=M([S(["instance-url","personal-access-token","username","http-password"]),c().transform(()=>"unknown")]),$M=c().max(8192).regex(/^[MmLlHhVvCcSsQqTtAaZz0-9eE.,\s+-]+$/),qm=c().min(1).max(64),eo=C(c().min(1).max(256)).max(8),QM=d({id:_s,label:qm,order:w().int(),terminology:d({changeRequest:_M.catch("pullRequest"),changeRequestPrefix:c().min(1).max(4),issuePrefix:c().min(1).max(4),sharedNumberSpace:y(),abbreviation:c().min(1).max(8),promptNoun:qm,ci:KM.catch("checks")}),icon:d({sprite:c().max(64).optional(),filledSprite:c().max(64).optional(),path:$M.optional()}),repository:d({nestedNamespaces:y(),pathStyle:m("path").optional().catch(void 0)}),instances:d({format:S(["host","origin"]),defaultInstance:c().min(1).max(256).nullable(),defaultInstances:C(c().min(1).max(256)).max(16).optional().catch(void 0),multiple:y(),allowLoopbackHttp:y(),allowPort:y(),reserved:C(c().max(256)).max(16),placeholder:c().max(256),legacyFlow:d({instance:c().min(1).max(256),kind:m("github-com-device")}).optional()}),auth:d({methods:C(M([ZM,c().transform(()=>null)])).transform(e=>e.filter(t=>t!==null)),cliName:c().min(1).max(32).optional(),login:Rd.optional(),cliTransport:y(),token:d({scopes:C(c().min(1).max(64)).max(32),createPath:c().max(256).optional()}).optional()}),settings:d({fields:C(d({id:c().min(1).max(64),kind:JM,secret:y()})).max(16)}),urls:d({changeRequest:eo,issue:eo,discussion:eo.default([]).catch([]),commit:eo.default([]).catch([]),user:eo.default([]).catch([])}),features:d({referenceSearch:y().default(!1),referenceDetail:y().default(!1),listStatuses:y().default(!1),referencesAcross:y().default(!1),startThread:y().default(!1),reviewDrafts:y().default(!1),reviewDraftFileComments:y().default(!1),authorCanReview:y().default(!1),projectUploads:y().default(!1),issueCloseReason:y().default(!1),changeRequestTemplates:C(c().min(1).max(256)).max(8).default([]),changeRequestPatch:y().default(!0),reviewModel:S(["verdict","votes"]).default("verdict").catch("verdict"),revisions:y().default(!1).catch(!1),submitRequirements:y().default(!1).catch(!1),createByPush:y().default(!1).catch(!1),branchHeads:y().default(!0).catch(!0),discussions:y().default(!1).catch(!1)}),extension:d({guestId:c().min(1).max(128),name:c().min(1).max(200),version:c().min(1).max(64)}).optional().catch(void 0)}),YM=(e,t)=>e.order-t.order||(e.id<t.id?-1:e.id>t.id?1:0),Dd=C(QM.nullable().catch(null)).transform(e=>{const t=new Set,s=[];for(const a of e)!a||t.has(a.id)||(t.add(a.id),s.push(a));return s.sort(YM)}),Vm=new Map,cu=e=>{const t=Vm.get(e);if(t)return t;const s={id:e,label:e,order:Number.MAX_SAFE_INTEGER,terminology:{changeRequest:"pullRequest",changeRequestPrefix:"#",issuePrefix:"#",sharedNumberSpace:!0,abbreviation:"PR",promptNoun:"pull request",ci:"checks"},icon:{sprite:"git-branch"},repository:{nestedNamespaces:!1},instances:{format:"origin",defaultInstance:null,multiple:!1,allowLoopbackHttp:!1,allowPort:!1,reserved:[],placeholder:""},auth:{methods:[],cliTransport:!1},settings:{fields:[]},urls:{changeRequest:[],issue:[],discussion:[],commit:[],user:[]},features:{referenceSearch:!1,referenceDetail:!1,listStatuses:!1,referencesAcross:!1,startThread:!1,reviewDrafts:!1,reviewDraftFileComments:!1,authorCanReview:!1,projectUploads:!1,issueCloseReason:!1,changeRequestTemplates:[],changeRequestPatch:!1,reviewModel:"verdict",revisions:!1,submitRequirements:!1,createByPush:!1,branchHeads:!0,discussions:!1}};return Vm.set(e,s),s},XM=16,eB=(e,t)=>{const s=C(wr([c(),t])),a=()=>{try{const n=s.safeParse(JSON.parse(window.localStorage.getItem(e)??"[]"));return n.success?n.data:[]}catch{return[]}};return{read:n=>ql(n)?null:a().find(([o])=>o===n)?.[1]??null,remember:(n,o)=>{if(ql(n))return;const i=a().filter(([r])=>r!==n);i.push([n,[...o]]);try{window.localStorage.setItem(e,JSON.stringify(i.slice(-XM)))}catch{}}}},tB=(e,t)=>e===t||e.length===t.length&&JSON.stringify(e)===JSON.stringify(t),sB=e=>Math.min(6e4,2e3*2**Math.max(0,e-1)),uy=eB("openchamber.sourceControlProviders.v1",Dd),lu=e=>({ordered:e,byId:new Map(e.map(t=>[t.id,t]))}),aB=lu([]),Um=e=>{const t=uy.read(e);return t?{runtimeKey:e,...lu(t),status:"stale",holdsList:!0}:{runtimeKey:e,...aB,status:"idle",holdsList:!1}};let ua=0,Ga=null,_a=null,_i=0,Ro=null;const Wm=()=>{Ro!==null&&clearTimeout(Ro),Ro=null},Ea=Rt((e,t)=>{const s=a=>{ua+=1,Ga=null,_a=null,_i=0,Wm(),e(Um(a))};return{...Um(N()),refresh:a=>{const n=N();if(n!==t().runtimeKey&&s(n),Ga){if(!_a){const u=ua,g=Ga.then(()=>{if(_a===g&&(_a=null),u===ua)return t().refresh(a)});_a=g}return _a}Wm();const o=ua,{holdsList:i,ordered:r}=t();e({status:"loading"});const p=(async()=>{try{const u=await a.providers();if(o!==ua)return;_i=0,uy.remember(n,u),e(i&&tB(r,u)?{status:"ready"}:{...lu(u),status:"ready",holdsList:!0})}catch{if(o!==ua)return;if(i){e({status:"stale"});return}e({status:"error"}),_i+=1,Ro=setTimeout(()=>{Ro=null,o===ua&&t().refresh(a)},sB(_i))}})().finally(()=>{Ga===p&&(Ga=null)});return Ga=p,p},resetForRuntimeSwitch:s}});queueMicrotask(()=>{const e=Ea.getState(),t=N();e.status==="idle"&&t!==e.runtimeKey&&e.resetForRuntimeSwitch(t)});const $J=()=>Ea(oB),nB=e=>{const t=kt.c(5);let s;t[0]!==e?(s=o=>e?o.byId.get(e):void 0,t[0]=e,t[1]=s):s=t[1];const a=Ea(s);let n;return t[2]!==a||t[3]!==e?(n=a??cu(e??""),t[2]=a,t[3]=e,t[4]=n):n=t[4],n},QJ=e=>nB(e).terminology.changeRequest,YJ=e=>{const t=kt.c(2);let s;return t[0]!==e?(s=a=>e&&a.byId.has(e)?"served":a.holdsList?"not-served":"unknown",t[0]=e,t[1]=s):s=t[1],Ea(s)},XJ=e=>{const t=kt.c(2);let s;return t[0]!==e?(s=a=>{const n=e?a.byId.get(e):void 0;return n?n.features.changeRequestPatch?"served":"not-served":a.holdsList?"not-served":"unknown"},t[0]=e,t[1]=s):s=t[1],Ea(s)},e$=()=>{const e=kt.c(2),t=Ea(iB);let s;return e[0]!==t?(s=a=>(a?t.get(a):void 0)??cu(a??""),e[0]=t,e[1]=s):s=e[1],s},lc=e=>(e?Ea.getState().byId.get(e):void 0)??cu(e??"");function oB(e){return e.ordered}function iB(e){return e.byId}const rB=d({text:c(),prefix:c(),suffix:c(),start:w(),page:d({partId:c(),kind:m("ui").optional()}).optional()}),Hm=32,gy=200,cB="[data-chat-quote-root]";function t$(e,t){return[...e.querySelectorAll(`[data-message-id="${CSS.escape(t)}"]`)].flatMap(s=>s.querySelector(cB)??[]).sort((s,a)=>s.getBoundingClientRect().top-a.getBoundingClientRect().top)}function s$(e,t,s){return e.querySelector(`[data-ui-render-message="${CSS.escape(t)}"][data-ui-render-part="${CSS.escape(s)}"]`)}function my(e,t,s){const a=s+t.text.length,n=e.slice(Math.max(0,s-t.prefix.length),s),o=e.slice(a,a+t.suffix.length);return t.prefix.endsWith(n)&&t.suffix.startsWith(o)}function Gm(e,t,s){const a=e.ownerDocument.createRange();return a.setStart(e,0),a.setEnd(t,s),a.toString().length}function hy(e){const t=[];let s="";for(const a of e)t.push(s.length),s+=a.textContent??"";return{stream:s,bases:t}}function a$(e,t){const s=Array.isArray(e)?e:[e],a=s.findIndex(u=>u.contains(t.startContainer)),n=s.findIndex(u=>u.contains(t.endContainer));if(a<0||n<a)return null;const{stream:o,bases:i}=hy(s),r=i[a]+Gm(s[a],t.startContainer,t.startOffset),l=i[n]+Gm(s[n],t.endContainer,t.endOffset),p=o.slice(r,l);return p.trim()?{text:p,prefix:o.slice(Math.max(0,r-Hm),r),suffix:o.slice(l,l+Hm),start:r}:null}function lB(e,t){if(!t.text)return null;const s=[];for(let n=e.indexOf(t.text);n!==-1&&s.length<gy;n=e.indexOf(t.text,n+1))s.push(n);if(s.length<=1)return s[0]??null;if(!t.prefix&&!t.suffix)return null;const a=s.filter(n=>my(e,t,n));return a.length===0?null:a.reduce((n,o)=>Math.abs(o-t.start)<Math.abs(n-t.start)?o:n)}function fy(e,t){for(let s=e.firstChild;s;s=s.nextSibling)s.nodeType===3?t.push(s):fy(s,t);return t}function dB(e){const t=new Set;let s=1;for(const a of e){const n=a.closest("[data-message-id]")?.getAttribute("data-message-row");if(!n)return e.length===1;const[o,i]=n.split("/");t.add(o),s=Number(i)}return t.size===s}const to=32;function pB(e,t){const{text:s,prefix:a,suffix:n}=t,o=!!(a||n),i=p=>{const u=[];for(let g=e.indexOf(p);g!==-1&&u.length<gy;g=e.indexOf(p,g+1))u.push(g);return u},r=[];for(const p of i(s))(!o||my(e,t,p))&&r.push({start:p,end:p+s.length});if(s.length>to&&(r.length===0||!o)){for(const p of i(s.slice(0,to))){const u=e.slice(p);u.length<s.length&&s.startsWith(u)&&a.endsWith(e.slice(Math.max(0,p-a.length),p))&&r.push({start:p,end:e.length})}for(const p of i(s.slice(-to))){const u=p+to;u<s.length&&s.endsWith(e.slice(0,u))&&n.startsWith(e.slice(u,u+n.length))&&r.push({start:0,end:u})}e.length>=to&&e.length<s.length&&s.includes(e)&&r.push({start:0,end:e.length})}return o?r[0]??null:new Set(r.map(p=>`${p.start}:${p.end}`)).size===1?r[0]:null}function uB(e,t){const{stream:s}=hy(e);let a,n;if(dB(e))a=lB(s,t),n=(a??0)+t.text.length;else{const r=pB(s,t);a=r?.start??null,n=r?.end??0}if(a===null||n<=a)return null;const o=[];let i=0;for(const r of e){let l=null;for(const p of fy(r,[])){const u=p.data.length;if(!l&&a<i+u&&n>i&&(l=r.ownerDocument.createRange(),l.setStart(p,Math.max(0,a-i)),l.setEnd(r,r.childNodes.length)),l&&n<=i+u)return l.setEnd(p,n-i),o.push(l),o;i+=u}l&&o.push(l)}return null}function n$(e,t){return uB([e],t)?.[0]??null}const gB=aC.gfm,mB=nC().use(oC).use(gB[0],{singleTilde:!1});function o$(e){const t=s=>{if("children"in s){if(s.type==="list")return`
34
+ {summary}`,"chat.chatInput.toast.vscodePickFailed":"Failed to pick files in VS Code","chat.chatInput.toast.openSessionFirst":"Open a session first","chat.chatInput.toast.dictationKeptForOriginalSession":"Dictation saved as a draft in the session where you started it","chat.chatInput.toast.togglePermissionAutoAcceptFailed":"Failed to toggle permission auto-accept","chat.chatInput.reviewComments":"Review comments:","chat.chatInput.reviewCommentsRemove":"Remove review comments","chat.chatInput.previewAnnotations":"Preview annotations:","chat.chatInput.previewContext":"Preview context:","chat.chatInput.previewContextRemove":"Remove preview context","chat.chatInput.projectRoot":"Project root","chat.chatInput.branch":"Branch","chat.chatInput.draftPicker.projectTitle":"Project","chat.chatInput.draftPicker.searchProjects":"Search projects...","chat.chatInput.draftPicker.searchBranches":"Search branches...","chat.chatInput.draftPicker.noProjectsFound":"No projects found.","chat.chatInput.draftPicker.addProject":"Add project…","chat.chatInput.worktrees":"Worktrees","chat.chatInput.worktreeQuick":"Quick worktree","chat.chatInput.worktreeCustom":"New worktree…","chat.chatInput.drop.insertMention":"Drop to insert as mention","chat.chatInput.drop.attachFiles":"Drop files here to attach","chat.chatInput.fileFallback":"file","chat.toolOutputDialog.image.previousAria":"Previous image","chat.toolOutputDialog.image.nextAria":"Next image","chat.toolOutputDialog.image.closeAria":"Close image preview","chat.toolOutputDialog.mermaid.missingSource":"Missing Mermaid source URL.","chat.toolOutputDialog.mermaid.loadFailed":"Unable to load Mermaid diagram.","chat.toolOutputDialog.mermaid.dataUrlMalformed":"The Mermaid data URL is malformed.","chat.toolOutputDialog.mermaid.invalidLocalPath":"The local Mermaid file path is invalid.","chat.toolOutputDialog.mermaid.readFileFailedWithStatus":"Unable to read Mermaid file. Status: {status}.","chat.toolOutputDialog.mermaid.unsupportedUrlProtocol":"The Mermaid URL protocol is unsupported.","chat.toolOutputDialog.mermaid.loadFailedWithStatus":"Unable to load Mermaid diagram. Status: {status}.","chat.toolOutputDialog.mermaid.closeAria":"Close diagram preview","chat.toolOutputDialog.mermaid.loading":"Loading diagram...","chat.toolOutputDialog.mermaid.renderFailed":"Unable to render Mermaid diagram.","chat.toolOutputDialog.mermaid.retry":"Retry","chat.toolOutputDialog.commandCompleted":"Command completed successfully","chat.toolOutputDialog.noOutputProduced":"No output was produced","chat.statusRow.background.action":"Move to background — the agent stops waiting and continues","chat.statusRow.background.failed":"Couldn't move the work to the background","chat.toolPart.background.label":"in background","chat.toolPart.background.stop":"Stop command","chat.toolPart.background.stopLabel":"Stop","chat.toolPart.background.stopFailed":"Couldn't stop the command","chat.toolPart.background.stoppedLabel":"stopped","chat.toolPart.background.stoppedNotice":"Stopped by you. The agent was told this was your stop, not a failure.","chat.toolPart.subagent.stop":"Stop subagent","chat.toolPart.subagent.stopFailed":"Couldn't stop the subagent","chat.toolPart.lspErrors":"LSP errors","chat.toolPart.moreErrors":"+{count} more errors","chat.toolPart.moreRows":"+{count} more rows","chat.toolPart.error":"Error:","chat.toolPart.awaitingResponse":"Awaiting response...","chat.toolPart.noOutputProduced":"No output produced","chat.toolPart.questionsAsked":"Questions asked: {count}","chat.toolPart.filesCount":"Files: {count}","chat.toolPart.moreToolCalls":"+{count} more","chat.toolPart.scriptCalls":"Tool calls","chat.toolPart.outputTruncated":"Output was truncated","chat.toolPart.content.loading":"Loading the result…","chat.toolPart.content.loadFailed":"Couldn't load the result.","chat.toolPart.content.retry":"Retry","chat.toolPart.output":"Output","chat.toolPart.showRawJson":"Show raw JSON","chat.toolPart.showFormattedJson":"Show formatted JSON","chat.toolPart.showNavigableJson":"Show navigable JSON","chat.toolPart.openFile":"Open file","chat.toolPart.openImageExpanded":"Open","chat.toolPart.openFileAtFirstChange":"Open file at first change","chat.toolPart.openFileDiff":"Open file diff","chat.toolPart.copyOutput":"Copy output","chat.toolPart.copiedOutput":"Copied output","chat.toolPart.copyOutputFailed":"Failed to copy output","chat.toolPart.openSubtask":"Open {type} subtask","chat.todo.total":"Total","chat.todo.inProgress":"In Progress","chat.todo.pending":"Pending","chat.todo.completed":"Completed","chat.todo.cancelled":"Cancelled","chat.permissionCard.workingDirectory":"Working Directory:","chat.permissionCard.timeout":"Timeout:","chat.permissionCard.request":"Request:","chat.permissionCard.headers":"Headers:","chat.permissionCard.body":"Body:","chat.permissionCard.action":"Action:","chat.permissionCard.patterns":"Patterns:","chat.permissionToast.sessionFallback":"Session","chat.permissionToast.permissionFallback":"Permission details unavailable","chat.permissionToast.labels.session":"Session:","chat.permissionToast.labels.permission":"Permission:","chat.permissionToast.actions.once":"Once","chat.permissionToast.actions.always":"Always","chat.permissionToast.actions.deny":"Deny","chat.permissionToast.actions.approveOnceAria":"Approve once","chat.permissionToast.actions.approveOnceAriaWithSession":"Approve once for {session}","chat.permissionToast.actions.approveAlwaysAria":"Approve always","chat.permissionToast.actions.approveAlwaysAriaWithSession":"Approve always for {session}","chat.permissionToast.actions.denyAria":"Deny permission","chat.permissionToast.actions.denyAriaWithSession":"Deny permission for {session}","chat.permissionRequest.required":"Permission required:","chat.permissionRequest.actions.once":"Once","chat.permissionRequest.actions.always":"Always","chat.permissionRequest.actions.reject":"Reject","chat.modelControls.provider":"Provider","chat.modelControls.capability.toolCalling":"Tool calling","chat.modelControls.capability.reasoning":"Reasoning","chat.modelControls.modality.text":"Text","chat.modelControls.modality.image":"Image","chat.modelControls.modality.video":"Video","chat.modelControls.modality.audio":"Audio","chat.modelControls.modality.pdf":"PDF","chat.modelControls.capabilities":"Capabilities","chat.modelControls.modalities":"Modalities","chat.modelControls.input":"Input","chat.modelControls.output":"Output","chat.modelControls.limits":"Limits","chat.modelControls.context":"Context","chat.modelControls.metadata":"Metadata","chat.modelControls.knowledge":"Knowledge","chat.modelControls.release":"Release","chat.modelControls.mode":"Mode","chat.modelControls.model":"Model","chat.modelControls.temperature":"Temperature","chat.modelControls.topP":"Top P","chat.modelControls.permissions":"Permissions","chat.modelControls.edit":"Edit","chat.modelControls.bash":"Bash","chat.modelControls.webFetch":"WebFetch","chat.modelControls.customPrompt":"Custom Prompt","chat.modelControls.selectModel":"Select model","chat.modelControls.thinking":"Thinking","chat.modelControls.inheritedVariantTooltip":"Thinking: {variant}, this model's default","chat.modelControls.rememberedVariantTooltip":"Thinking: {variant}, last used with this model","chat.modelControls.default":"Default","chat.modelControls.selectAgent":"Select agent","chat.modelControls.costPerMillion":"Cost ($/1M tokens)","chat.modelControls.metadataUnavailable":"Model metadata unavailable.","chat.modelControls.addNewProvider":"Add new provider","chat.modelControls.noAgentSelected":"No agent selected.","chat.modelControls.agentUnavailable":`Agent "{agent}" isn't available in this session's folder. Pick another agent.`,"chat.modelControls.modelUnavailable":`Model "{model}" isn't available anymore. Its provider was removed or switched off. Pick another model.`,"chat.modelControls.searchModels":"Search models","chat.modelControls.modelListAria":"Models","chat.modelControls.searchAgents":"Search agents","chat.modelControls.noModelsFound":"No models found","chat.modelControls.favorites":"Favorites","chat.modelControls.agentsSection":"Agents","chat.modelControls.favoriteAgentsCycleHint":"{shortcut} to cycle","chat.modelControls.favoriteAgentsTapHint":"Tap the agent to cycle","chat.modelControls.noAgentsFound":"No agents found","chat.modelControls.recent":"Recent","chat.modelControls.addToFavorites":"Add to favorites","chat.modelControls.removeFromFavorites":"Remove from favorites","chat.modelControls.useModel":"Use model","chat.modelControls.favoriteAria":"Favorite","chat.modelControls.unfavoriteAria":"Unfavorite","chat.modelControls.collapseProvider":"Collapse provider","chat.modelControls.expandProvider":"Expand provider","chat.modelControls.keyboardHint":"↑↓ navigate{thinking} • Enter select • Esc close","chat.modelControls.keyboardHintNavigate":"↑↓ navigate","chat.modelControls.keyboardHintSwitchAgent":"{shortcut} switch agent","chat.modelControls.keyboardHintSwitchThinking":"{shortcut} switch","chat.modelControls.keyboardHintThinking":"←→ thinking","chat.modelControls.reorderProviderTitle":"Drag to reorder provider","chat.modelControls.permissionLabel.custom":"Custom","chat.modelControls.permissionLabel.allow":"Allow","chat.modelControls.permissionLabel.deny":"Deny","chat.modelControls.permissionLabel.ask":"Ask","chat.modelControls.modeValue.primary":"Primary","chat.modelControls.modeValue.subagent":"Subagent","chat.modelControls.modeValue.all":"All","chat.modelControls.modeValue.none":"—","chat.reasoningTrace.thinking":"Thinking","chat.reasoningTrace.expandAria":"Expand reasoning trace","chat.reasoningTrace.collapseAria":"Collapse reasoning trace","chat.reasoningTrace.thought":"Thought","chat.messageBody.subtask.title":"Delegated task","chat.messageBody.subtask.hidePrompt":"Hide prompt","chat.messageBody.subtask.showPrompt":"Show prompt","chat.messageBody.subtask.openSession":"Open subtask session","chat.messageBody.shellCommand.copied":"Copied","chat.messageBody.shellCommand.copyOutput":"Copy output","commandPalette.title":"Command Palette","commandPalette.description":"Search files, sessions, and commands.","commandPalette.input.placeholder":"Search files, sessions, commands...","commandPalette.empty.noResults":"No results found.","commandPalette.empty.searchingFiles":"Searching files...","commandPalette.item.newSession":"New Session","commandPalette.item.newMiniChat":"New Mini Chat Window","commandPalette.item.quickWorktree":"Quick Worktree","commandPalette.item.newWorktreeDialog":"New Worktree…","commandPalette.item.addProject":"Add Project","commandPalette.item.showSessionSwitcher":"Show Session Switcher","commandPalette.item.toggleSidebar":"Toggle Sidebar","commandPalette.item.showContextUsage":"Show Context Usage","commandPalette.item.toggleTerminal":"Toggle Terminal","commandPalette.item.cycleTheme":"Cycle theme","commandPalette.item.showOpenCodeStatus":"Show diagnostic timeline","commandPalette.item.restartOpenCode":"Restart OpenCode","commandPalette.item.toggleMemoryDebug":"Toggle memory debug panel","commandPalette.item.pinSession":"Pin or unpin session","commandPalette.item.copySessionId":"Copy session ID","commandPalette.item.openMultiRun":"Run in parallel","commandPalette.item.openArchive":"Open archived sessions","commandPalette.item.openNotes":"Open notes surface","commandPalette.item.openTodos":"Open todos surface","commandPalette.item.openSettings":"Open Settings...","commandPalette.session.untitled":"Untitled Session","commandPalette.item.reloadUi":"Reload UI","commandPalette.group.openFiles":"Open files","commandPalette.group.commands":"Commands","commandPalette.group.settings":"Settings","chat.search.placeholder":"Search this conversation","chat.search.position":"{current} of {total}","chat.search.noResults":"No results","chat.search.searching":"Searching…","chat.search.tooShort":"3+ characters","chat.search.error":"Couldn't search","chat.search.unavailable":"Not available here","chat.search.previous":"Previous match","chat.search.next":"Next match","chat.search.close":"Close search","commandPalette.group.sessions":"Sessions","commandPalette.group.messages":"Messages","commandPalette.messages.showAll":"Show all message results","commandPalette.messages.placeholder":"Search messages…","commandPalette.messages.inReasoning":"Thinking","commandPalette.messages.indexing":"Still indexing older conversations: {done} of {total}.","commandPalette.messages.loadMore":"Load more","commandPalette.messages.byYou":"Your message","commandPalette.messages.byAgent":"Agent reply","commandPalette.group.files":"Files","commandPalette.group.projects":"Projects","commandPalette.footer.navigate":"to navigate","commandPalette.footer.open":"to open","commandPalette.footer.close":"to close","openCodeStatusDialog.title":"Diagnostic timeline","openCodeStatusDialog.description":"Local events in time order. Private log text and remote sources are excluded.","openCodeStatusDialog.actions.download":"Download log","openCodeStatusDialog.toast.collectFailed":"Failed to collect diagnostics","openCodeStatusDialog.actions.copy":"Copy","openCodeStatusDialog.empty.noData":"No data.","openCodeStatusDialog.toast.copiedTitle":"Copied","openCodeStatusDialog.toast.copiedDescription":"Diagnostic log copied to clipboard","openCodeStatusDialog.toast.copyFailed":"Failed to copy diagnostic log","saveProjectPlanDialog.title":"Save Project Plan","saveProjectPlanDialog.description":"Save this plan into your project as a Markdown file.","saveProjectPlanDialog.field.title":"Title","saveProjectPlanDialog.field.titlePlaceholder":"Plan title","saveProjectPlanDialog.field.contentPreview":"Content preview","saveProjectPlanDialog.actions.cancel":"Cancel","saveProjectPlanDialog.actions.save":"Save","saveProjectPlanDialog.actions.saving":"Saving...","branchPickerDialog.title":"Branch Picker","branchPickerDialog.description.localBranchesForProject":"Local branches for {project}","branchPickerDialog.description.selectProject":"Select a project to view branches","branchPickerDialog.search.placeholder":"Search branches...","branchPickerDialog.search.renameBranchPlaceholder":"Rename branch","branchPickerDialog.state.noProjectSelected":"No project selected","branchPickerDialog.state.loadingBranches":"Loading branches...","branchPickerDialog.state.noMatchingBranches":"No matching branches","branchPickerDialog.state.noBranchesFound":"No branches found","branchPickerDialog.badge.head":"HEAD","branchPickerDialog.badge.worktree":"worktree","branchPickerDialog.actions.createWorktreeAria":"Create worktree from branch","branchPickerDialog.actions.renameAria":"Rename branch","branchPickerDialog.actions.deleteAria":"Delete branch","branchPickerDialog.actions.deleteWorktreeAria":"Remove worktree","branchPickerDialog.actions.confirmRenameAria":"Confirm rename","branchPickerDialog.actions.cancelRenameAria":"Cancel rename","branchPickerDialog.actions.confirmDeleteAria":"Confirm delete branch","branchPickerDialog.actions.cancelDeleteAria":"Cancel delete branch","branchPickerDialog.actions.deletePrompt":"Delete","branchPickerDialog.actions.forceDeletePrompt":"Force Delete","branchPickerDialog.tooltip.createWorktree":"Create worktree","branchPickerDialog.tooltip.worktreeAlreadyExists":"Worktree already exists","branchPickerDialog.tooltip.rename":"Rename branch","branchPickerDialog.tooltip.renameDisabledForRoot":"Cannot rename root branch","branchPickerDialog.tooltip.delete":"Delete branch","branchPickerDialog.tooltip.deleteCurrentBranch":"Cannot delete current branch","branchPickerDialog.tooltip.deleteDisabledForRoot":"Cannot delete root branch","branchPickerDialog.tooltip.deleteWorktree":"Remove worktree","branchPickerDialog.tooltip.deleteWorktreeRootProtected":"Cannot remove root worktree","branchPickerDialog.toast.branchRenamed":"Branch renamed","branchPickerDialog.toast.failedToRenameBranch":"Failed to rename branch","branchPickerDialog.toast.branchDeleted":"Branch deleted","branchPickerDialog.toast.branchNotMerged":"Branch is not fully merged","branchPickerDialog.toast.confirmAgainToForceDelete":"Confirm again to force delete","branchPickerDialog.toast.failedToDeleteBranch":"Failed to delete branch","branchPickerDialog.toast.worktreeCreated":"Worktree created","branchPickerDialog.toast.failedToCreateWorktree":"Failed to create worktree","branchPickerDialog.error.failedToLoad":"Failed to load branches","branchPickerDialog.error.renameRejected":"Rename was rejected","branchPickerDialog.error.renameFailed":"Failed to rename branch","branchPickerDialog.error.deleteRejected":"Delete was rejected","branchPickerDialog.error.deleteFailed":"Failed to delete branch","branchPickerDialog.error.createWorktreeFailed":"Failed to create worktree","projectEditDialog.title":"Edit project","projectEditDialog.field.name":"Name","projectEditDialog.field.namePlaceholder":"Project name","projectEditDialog.field.color":"Color","projectEditDialog.field.icon":"Icon","projectEditDialog.field.preview":"Preview","projectEditDialog.field.iconBackground":"Icon Background","projectEditDialog.field.iconBackgroundAria":"Project icon background color","projectEditDialog.option.none":"None","projectEditDialog.actions.uploadIcon":"Upload Icon","projectEditDialog.actions.uploading":"Uploading...","projectEditDialog.actions.discoverFavicon":"Discover Favicon","projectEditDialog.actions.discovering":"Discovering...","projectEditDialog.actions.removeProjectIcon":"Remove Project Icon","projectEditDialog.actions.removing":"Removing...","projectEditDialog.actions.undoRemove":"Undo Remove","projectEditDialog.actions.clear":"Clear","projectEditDialog.actions.cancel":"Cancel","projectEditDialog.actions.save":"Save","projectEditDialog.toast.failedToUploadIcon":"Failed to upload project icon","projectEditDialog.toast.iconUpdated":"Project icon updated","projectEditDialog.toast.failedToRemoveIcon":"Failed to remove project icon","projectEditDialog.toast.iconRemoved":"Project icon removed","projectEditDialog.toast.failedToDiscoverIcon":"Failed to discover project icon","projectEditDialog.toast.customIconAlreadySet":"Custom icon already set for this project","projectEditDialog.toast.iconDiscovered":"Project icon discovered","openInApp.actions.open":"Open","openInApp.actions.openInAria":"Open in {app}","openInApp.actions.copyPath":"Copy Path","openInApp.actions.refreshApps":"Refresh Apps","openInApp.toast.pathCopied":"Path copied to clipboard","projectActions.actions.addActionAria":"Add action","projectActions.actions.addAction":"Add action","projectActions.actions.addNewAction":"Add new action","projectActions.actions.autoDiscover":"Auto-discover dev server","projectActions.menu.sharedBadge":"repo","projects.sharedTrust.title":"Run the commands stored in this repository?","projects.sharedTrust.description":"{path} in this repository defines commands that run on this machine. Trust them once, and OpenChamber asks again only when they change.","projects.sharedTrust.setupCommands":"Worktree setup commands","projects.sharedTrust.teardownCommands":"Worktree teardown commands","projects.sharedTrust.actions":"Actions","projects.sharedTrust.skip":"Not this time","projects.sharedTrust.trust":"Trust and run","projects.opencodeTrust.title":"Let OpenCode run code from this folder?","projects.opencodeTrust.description":"OpenCode runs the plugins and commands in the configuration of {path} as soon as it opens the folder. Trust them once, and OpenChamber asks again only when they change.","projects.opencodeTrust.plugins":"Plugins","projects.opencodeTrust.commands":"Commands","projects.opencodeTrust.kind.package":"{name} (npm package)","projects.opencodeTrust.kind.config":"{path}: a configuration file OpenChamber can't read","projects.opencodeTrust.kind.mcp":"MCP server {name}","projects.opencodeTrust.kind.lsp":"Language server {name}","projects.opencodeTrust.kind.formatter":"Formatter {name}","projects.opencodeTrust.kind.shell":"Shell","projects.opencodeTrust.paused":"Without trust, agents can't work in this folder, but you can still browse its files and Git changes.","projects.opencodeTrust.skip":"Not this time","projects.opencodeTrust.trust":"Trust and open","projects.opencodeTrust.saveFailed":"Couldn't save your answer. Try again.","projectActions.actions.autoDiscoverTooltip":"Automatically discover and run the development server","projectActions.actions.chooseActionAria":"Choose project action","projectActions.actions.openPreview":"Open Preview","projectActions.actions.runNamedAria":"Run {name}","projectActions.actions.stopNamedAria":"Stop {name}","projectActions.label.fallbackAction":"Action","projectActions.toast.openedUrlFromOutput":"Opened URL from action output","projectActions.toast.openedForwardedUrl":"Opened forwarded URL","projectActions.toast.openedActionUrl":"Opened action URL","projectActions.error.noActiveDirectory":"No active directory","projectActions.error.noActiveDirectoryForAction":"No active directory for action","projectActions.error.failedToCreateTerminalSession":"Failed to create terminal session","projectActions.error.invalidCustomUrlFormat":"Invalid custom URL format","projectActions.error.openUrlTemplateUnresolved":"Couldn't read the branch for the action URL","projectActions.error.selectedDesktopSshForwardUnavailable":"Selected desktop SSH forward is unavailable","projectActions.error.failedToRunAction":"Failed to run action","sessionAuth.error.rateLimitTitle":"Too many attempts","sessionAuth.error.networkTitle":"Unable to reach server","sessionAuth.error.rateLimitDescriptionSingle":"Please wait {minutes} minute before trying again.","sessionAuth.error.rateLimitDescriptionPlural":"Please wait {minutes} minutes before trying again.","sessionAuth.error.networkDescription":"We could not verify the UI session. If you're opening OpenChamber from another device on your local network, make sure Desktop Network Access is enabled on the desktop app and use the LAN address shown in Settings.","sessionAuth.error.retry":"Retry","sessionAuth.error.passkeySetupFailed":"Passkey setup failed.","sessionAuth.error.incorrectPassword":"Incorrect password. Try again.","sessionAuth.error.unexpectedResponse":"Unexpected response from server.","sessionAuth.error.networkRetry":"Network error. Check connection and retry.","sessionAuth.error.passkeySignInCanceled":"Passkey sign-in was canceled.","sessionAuth.error.enterPasswordForPasskey":"Enter your password to add a passkey.","sessionAuth.locked.tunnelTitle":"Tunnel access required","sessionAuth.expired.banner":"Your session expired — log in to continue.","sessionAuth.expired.loginAction":"Log in","sessionAuth.expired.sendBlocked":"Session expired — log in to send messages.","sessionAuth.locked.unlockTitle":"Unlock OpenChamber","sessionAuth.locked.tunnelDescription":"Open this tunnel using the one-time connect link from the desktop app.","sessionAuth.locked.passwordDescription":"This session is password-protected.","sessionAuth.locked.hostSwitcherHint":"Use Local if remote is unreachable.","sessionAuth.actions.cancelPasskey":"Cancel passkey","sessionAuth.actions.usePasskey":"Use passkey","sessionAuth.actions.unlockingAria":"Unlocking","sessionAuth.actions.unlockAria":"Unlock","sessionAuth.actions.trustDevice":"Trust this device","sessionAuth.actions.trustDeviceAria":"Trust this device","sessionAuth.actions.cancelPasskeySetup":"Cancel passkey setup","sessionAuth.actions.addPasskey":"Add passkey","sessionAuth.password.placeholder":"Enter password","sessionAuth.toast.passkeyAdded":"Passkey added","sessionAuth.toast.passkeySetupCanceled":"Passkey setup canceled","desktopHostSwitcher.title":"Instance","desktopHostSwitcher.description":"Switch between Local and remote OpenChamber servers","desktopHostSwitcher.header.current":"Current","desktopHostSwitcher.header.default":"Default","desktopHostSwitcher.header.currentColon":"Current:","desktopHostSwitcher.header.currentDefaultColon":"Current default:","desktopHostSwitcher.status.connected":"Connected","desktopHostSwitcher.status.authRequired":"Auth required","desktopHostSwitcher.status.checking":"Checking","desktopHostSwitcher.status.updateRecommended":"Update recommended","desktopHostSwitcher.status.incompatible":"Incompatible","desktopHostSwitcher.status.wrongService":"Wrong service","desktopHostSwitcher.status.unreachable":"Unreachable","desktopHostSwitcher.status.relayLimit":"Relay limit reached","desktopHostSwitcher.status.unknown":"Unknown","desktopHostSwitcher.status.ping":" · {ms}ms ping","desktopHostSwitcher.statusAria":"Instance status","desktopHostSwitcher.sshPhase.ready":"Ready","desktopHostSwitcher.sshPhase.error":"Error","desktopHostSwitcher.sshPhase.reconnecting":"Reconnecting","desktopHostSwitcher.sshPhase.resolvingConfig":"Resolving config","desktopHostSwitcher.sshPhase.checkingAuth":"Checking auth","desktopHostSwitcher.sshPhase.connectingSsh":"Connecting SSH","desktopHostSwitcher.sshPhase.probingRemote":"Probing remote","desktopHostSwitcher.sshPhase.installing":"Installing","desktopHostSwitcher.sshPhase.updating":"Updating","desktopHostSwitcher.sshPhase.detectingServer":"Detecting server","desktopHostSwitcher.sshPhase.startingServer":"Starting server","desktopHostSwitcher.sshPhase.forwardingPorts":"Forwarding ports","desktopHostSwitcher.sshPhase.idle":"Idle","desktopHostSwitcher.ssh.needInstancesHint":"Need SSH instances? Manage them in Settings.","desktopHostSwitcher.ssh.instanceFallback":"SSH instance","desktopHostSwitcher.ssh.connectingTo":"Connecting to {host}","desktopHostSwitcher.actions.refresh":"Refresh","desktopHostSwitcher.actions.refreshInstancesAria":"Refresh instances","desktopHostSwitcher.actions.remoteSsh":"Remote SSH","desktopHostSwitcher.actions.instanceActionsAria":"Instance actions","desktopHostSwitcher.actions.edit":"Edit","desktopHostSwitcher.actions.delete":"Delete","desktopHostSwitcher.actions.connect":"Connect","desktopHostSwitcher.actions.defaultInstanceAria":"Default instance","desktopHostSwitcher.actions.setAsDefaultAria":"Set as default","desktopHostSwitcher.actions.setAsDefault":"Set as default","desktopHostSwitcher.actions.openInNewWindowAria":"Open in new window","desktopHostSwitcher.actions.openInNewWindow":"Open in new window","desktopHostSwitcher.actions.addInstance":"Add instance","desktopHostSwitcher.actions.cancel":"Cancel","desktopHostSwitcher.actions.save":"Save","desktopHostSwitcher.actions.add":"Add","desktopHostSwitcher.actions.switchToLocal":"Switch to Local","desktopHostSwitcher.actions.retry":"Retry","desktopHostSwitcher.actions.switchInstanceAria":"Switch instance","desktopHostSwitcher.actions.switchInstance":"Switch instance","desktopHostSwitcher.actions.switchToAria":"Switch to {instance}","desktopHostSwitcher.field.labelPlaceholder":"Label","desktopHostSwitcher.field.labelOptionalPlaceholder":"Label (optional)","desktopHostSwitcher.field.urlPlaceholder":"https://host:port","desktopHostSwitcher.state.limitedOnPage":"Instance switcher is limited on this page. Use Local to recover.","desktopHostSwitcher.state.loading":"Loading...","desktopHostSwitcher.state.instanceUnreachable":"Instance unreachable","desktopHostSwitcher.edit.title":"Edit instance","desktopHostSwitcher.add.title":"Add instance","desktopHostSwitcher.error.failedToSave":"Failed to save","desktopHostSwitcher.error.failedToLoad":"Failed to load","desktopHostSwitcher.error.invalidUrl":"Invalid URL (must be http/https)","desktopHostSwitcher.error.pairingRejected":"Pairing link is invalid or expired. Generate a new one.","desktopHostSwitcher.error.pairingFailed":"Pairing failed (HTTP {status}).","desktopHostSwitcher.error.pairingInvalidResponse":"The server returned an invalid pairing response.","desktopHostSwitcher.error.failedToOpenNewWindow":"Failed to open new window","desktopHostSwitcher.instance.local":"Local","desktopHostSwitcher.instance.fallback":"Instance","desktopHostSwitcher.startup.title":"Default SSH instance unavailable","desktopHostSwitcher.startup.connectingTo":"Connecting to {host}...","desktopHostSwitcher.startup.failed":"Failed to connect the default SSH instance.","desktopHostSwitcher.toast.sshConnected":'SSH instance "{host}" connected',"desktopHostSwitcher.toast.sshFailedToConnect":'SSH instance "{host}" failed to connect',"desktopHostSwitcher.toast.instanceUnreachable":'Instance "{host}" is unreachable',"desktopHostSwitcher.toast.relayLimit":'The relay refused the connection to "{host}": too many devices or reconnects. Close OpenChamber on another device or wait a minute, then try again.',"relayConnection.limitReached.title":"The relay refused the connection","relayConnection.limitReached.description":"Too many devices or reconnects for this instance. Close OpenChamber on another device or wait a minute, then try again.","relayConnection.limitReached.retry":"Try again","miniChat.header.newSession":"New session","miniChat.header.session":"Session","miniChat.header.defaultAgent":"Default agent","miniChat.header.noModel":"No model","miniChat.status.busy":"Running","miniChat.status.retry":"Retrying","miniChat.status.idle":"Idle","miniChat.actions.pin":"Pin above other windows","miniChat.actions.unpin":"Unpin window","miniChat.actions.pinAria":"Pin Mini Chat window","miniChat.actions.unpinAria":"Unpin Mini Chat window","miniChat.actions.openMain":"Open in main window","miniChat.actions.openMainAria":"Open session in main window","miniChat.unavailable.title":"Session unavailable","miniChat.unavailable.description":"This session could not be loaded. It may have been deleted, archived, or opened from a different project context.","sessions.sidebar.session.menu.openMiniChatWindow":"Open in Mini Chat Window","header.windowControls.groupAria":"Window controls","header.windowControls.minimize":"Minimize window","header.windowControls.maximize":"Maximize window","header.windowControls.restore":"Restore window","header.windowControls.close":"Close window","errorBoundary.title":"Something went wrong","errorBoundary.description":"The application encountered an unexpected error. This has been logged for debugging.","errorBoundary.state.unknownError":"Unknown error","errorBoundary.state.componentStackLabel":"Component stack:","errorBoundary.actions.errorDetails":"Error details","errorBoundary.actions.tryAgain":"Try again","errorBoundary.actions.copy":"Copy","errorBoundary.actions.copied":"Copied","jsonTreeView.error.emptyJson":"Empty JSON content","jsonTreeView.error.invalidJson":"Invalid JSON","jsonTreeView.error.invalidJsonTitle":"Invalid JSON","jsonTreeView.actions.expandAll":"Expand All","jsonTreeView.actions.collapseAll":"Collapse All","numberInput.actions.decreaseAria":"Decrease value","numberInput.actions.increaseAria":"Increase value","goToLineDialog.field.linePlaceholderShort":"Line","goToLineDialog.field.linePlaceholder":"Line number","goToLineDialog.actions.go":"Go","goToLineDialog.helper.editorUnavailable":"Editor unavailable.","goToLineDialog.helper.currentLineRange":"Current Line: {current}. Type a line number between 1 and {max} to navigate to.","goToLineDialog.helper.goToLine":"Go to line {line}","dialog.common.actions.close":"Close","session.newWorktree.trust.run":"Run","session.newWorktree.trust.skip":"Skip","session.newWorktree.trust.title":"Run setup on code from a fork?","gitView.publish.contributorCommitFirstAction":"Continue","gitView.publish.contributorCommitFirstTitle":"Commit, then choose where to push?","dialog.common.actions.cancel":"Cancel","filesView.toast.relativePathCopied":"Relative path copied","filesView.tree.menu.copyRelativePath":"Copy Relative Path","multiRun.branchSelector.placeholder.selectSourceBranch":"Select source branch...","multiRun.branchSelector.status.loadingBranches":"Loading branches...","multiRun.branchSelector.status.noBranchesFound":"No branches found","multiRun.branchSelector.status.notInGitRepository":"Not in a git repository.","multiRun.branchSelector.groups.localBranches":"Local branches","multiRun.branchSelector.groups.remoteBranches":"Remote branches","multiRun.window.actions.closeAria":"Close multi-run","multiRun.window.description":"OpenChamber Multi-Run window.","voice.status.idle":"Voice Ready","voice.status.listening":"Listening...","voice.status.processing":"Processing...","voice.status.speaking":"Speaking...","voice.status.error":"Voice Error","voice.status.conversationModeActiveAria":"Conversation mode active","voice.action.finishAndTranscribe":"Finish and transcribe voice input","onboarding.common.actions.back":"Back","onboarding.common.copyToClipboard":"Copy to clipboard","onboarding.common.status.copiedToClipboard":"Copied to clipboard","onboarding.chooser.title":"Welcome to OpenChamber","onboarding.chooser.description":"Choose how you want to connect to get started.","onboarding.chooser.tabs.localInstall":"Local Install","onboarding.chooser.tabs.connectRemote":"Connect Remote","onboarding.localSetup.title":"Setting Up OpenCode","onboarding.localSetup.description":"Install OpenCode v2 CLI to continue.","onboarding.localSetup.dialog.selectOpencodeBinary":"Select opencode binary","onboarding.localSetup.errors.cliNotReady":"OpenCode CLI is not ready yet. Please confirm installation is complete and try again.","onboarding.localSetup.errors.detectionFailed":"Detection failed","onboarding.localSetup.windows.title":"Windows setup","onboarding.localSetup.windows.stepInstallWsl":"Install OpenCode with the command below.","onboarding.localSetup.windows.stepInstallWslSuffix":"","onboarding.localSetup.windows.stepRunInstallInWsl":"Run the install command below in a Windows terminal.","onboarding.localSetup.windows.stepSetBinaryPath":"If OpenChamber does not detect OpenCode automatically, set the binary path below.","onboarding.localSetup.intro":"Install OpenCode v2 CLI to continue.","onboarding.localSetup.docs.windows":"Installation guide","onboarding.localSetup.docs.default":"Installation guide","onboarding.localSetup.actions.checking":"Checking…","onboarding.localSetup.actions.checkAndContinue":"I've completed installation, check and continue","onboarding.localSetup.actions.checkNow":"Check now","onboarding.localSetup.helper.checkAndContinue":"Click to check if OpenCode CLI is available. If successful, you'll automatically enter the main screen.","onboarding.localSetup.status.watching":"Waiting for OpenCode v2","onboarding.localSetup.status.autoContinue":"We'll continue automatically once it's detected.","onboarding.localSetup.field.alreadyInstalled":"Already installed? Set the OpenCode CLI path:","onboarding.localSetup.advanced.title":"Set a custom binary path","onboarding.localSetup.troubleshoot.title":"Having trouble?","onboarding.localSetup.actions.browse":"Browse","onboarding.localSetup.actions.apply":"Apply","onboarding.localSetup.helper.saveAndReload":"Saves to OpenChamber settings and reloads OpenCode configuration.","onboarding.localSetup.helper.pinnedByAdministrator":"Your administrator set this path. If OpenCode isn’t there, ask them to install it.","onboarding.localSetup.remotePreference":"Prefer to use a remote server?","onboarding.localSetup.actions.connectRemoteServer":"Connect to Remote Server →","onboarding.localSetup.windows.hintInstallInWsl":"On Windows, install and run OpenCode natively.","onboarding.localSetup.windows.hintDetectionFailed":"If detection fails, set a native path such as opencode.cmd or opencode.exe.","onboarding.localSetup.hint.ensurePath":"Already installed? Make sure opencode is in your PATH.","onboarding.localSetup.hint.setEnv":"Or set OPENCODE_BINARY environment variable.","onboarding.localSetup.hint.missingRuntime":'If you see "env: node: No such file or directory" or "env: bun: No such file or directory", install that runtime or ensure it is on PATH.',"onboarding.remoteConnection.title":"Connect to Remote Server","onboarding.remoteConnection.titleRecovery":"Connect to a Different Server","onboarding.remoteConnection.description":"Enter the address of an OpenChamber server to connect to.","onboarding.remoteConnection.field.serverAddress":"Server Address","onboarding.remoteConnection.field.serverAddressPlaceholder":"https://your-server.example.com:4096","onboarding.remoteConnection.field.nameOptional":"Name (optional)","onboarding.remoteConnection.field.namePlaceholder":"My Remote Server","onboarding.remoteConnection.errors.connectionTestFailed":"Connection test failed","onboarding.remoteConnection.errors.failedToSaveConnection":"Failed to save connection","onboarding.remoteConnection.status.connectedSuccessfully":"Connected successfully ({latencyMs}ms)","onboarding.remoteConnection.status.authWarning":"Server requires authentication. You can still connect.","onboarding.remoteConnection.status.connectionFailed":"Connection Failed","onboarding.remoteConnection.status.suggestionsUnreachable":"Suggestions: Check the server address, verify the server is running, or check your network connection.","onboarding.remoteConnection.status.suggestionsWrongService":"Suggestions: Verify the URL points to an OpenChamber server, or contact the server administrator.","onboarding.remoteConnection.actions.testing":"Testing…","onboarding.remoteConnection.actions.testConnection":"Test Connection","onboarding.remoteConnection.actions.connectAndRestart":"Connect & Restart","onboarding.remoteConnection.actions.whatToDo":"What would you like to do?","onboarding.remoteConnection.actions.chooseDifferentServer":"Choose Different Server","onboarding.remoteConnection.actions.useLocalInstead":"Use Local Instead","onboarding.remoteConnection.probe.authMessage":"Server requires authentication. You can still connect, but may need to provide credentials.","onboarding.remoteConnection.probe.updateRecommendedMessage":"This instance is running a different OpenChamber version. You can connect, but update both apps if something does not work.","onboarding.remoteConnection.probe.incompatibleMessage":"Server is running OpenChamber but is not compatible with this app version. Update OpenChamber on the server, then try again.","onboarding.remoteConnection.probe.wrongServiceMessage":"Server responded but is not running OpenChamber. Verify the address points to an OpenChamber server.","onboarding.remoteConnection.probe.unreachableMessage":"Server is unreachable. Check your network connection and verify the server address.","onboarding.desktopRecovery.localUnavailable.title":"Local OpenCode Unavailable","onboarding.desktopRecovery.localUnavailable.description":"OpenCode CLI could not be started or is not installed. Install OpenCode or connect to a remote server instead.","onboarding.desktopRecovery.localUnavailable.retry":"Retry Local","onboarding.desktopRecovery.localUnavailable.useLocal":"Set Up Local","onboarding.desktopRecovery.noDefaultConnection.title":"No Default Connection","onboarding.desktopRecovery.noDefaultConnection.description":"Your saved default connection could not be found. Choose how you want to connect.","onboarding.desktopRecovery.remoteUnreachable.title":"Remote Server Unreachable","onboarding.desktopRecovery.remoteUnreachable.description":'Could not connect to "{host}". Check your network connection and verify the server address.',"onboarding.desktopRecovery.remoteUnreachable.retry":"Retry Connection","onboarding.desktopRecovery.incompatibleServer.title":"Incompatible Server","onboarding.desktopRecovery.incompatibleServer.description":'The server at "{host}" is not running OpenChamber. Verify the address points to an OpenChamber server.',"onboarding.desktopRecovery.remoteIncompatible.title":"Server Update Required","onboarding.desktopRecovery.remoteIncompatible.description":'The OpenChamber server at "{host}" is not compatible with this app version. Update OpenChamber on the server, then try again.',"onboarding.desktopRecovery.remoteIncompatible.updateServer":"Update server","onboarding.desktopRecovery.remoteIncompatible.updatingServer":"Updating the server...","onboarding.desktopRecovery.remoteIncompatible.updatingHint":"The server installs the update and restarts. The app connects as soon as it is back.","onboarding.desktopRecovery.remoteIncompatible.updateRefused":"The server could not update itself.","onboarding.desktopRecovery.remoteIncompatible.updateAuth":"The server did not accept this app's sign-in, so it could not be updated from here.","onboarding.desktopRecovery.remoteIncompatible.updateTimeout":"The server has not come back with the new version yet. Check it, then retry the connection.","onboarding.desktopRecovery.remoteIncompatible.manualUpdate":"To update it by hand, run this on the server, then restart OpenChamber there:","onboarding.desktopRecovery.common.useLocal":"Use Local","onboarding.desktopRecovery.common.useRemote":"Use Remote","onboarding.desktopRecovery.actions.retrying":"Retrying…","onboarding.desktopRecovery.actions.retryConnection":"Retry Connection","projectConfigError.toast.title":"OpenCode can't load this project's config","projectConfigError.toast.unknownFile":"Project config","projectConfigError.toast.hint":"Fix the file, then retry. Other projects keep working.","projectConfigError.toast.retry":"Retry","projectConfigError.toast.retrying":"Retrying…","startup.initRecovery.title":"Startup failed","startup.serverOutdated.title":"Server update required","startup.serverOutdated.description":"The server runs OpenChamber {version}, and this app needs 2.0 or later there. Update OpenChamber on the server to continue.","startup.serverOutdated.checking":"Checking the server...","startup.serverOutdated.noUpdate":"The server did not offer an update it can install itself.","startup.initRecovery.openCodeUnavailable":"OpenChamber is reachable, but OpenCode is not ready. Check OpenCode on the server, then retry.","startup.initRecovery.binary":"OpenCode executable","startup.initRecovery.error":"OpenCode error","startup.initRecovery.serverUnreachable":"OpenChamber could not reach its server. Check that the server is running, then retry.","startup.initRecovery.loadAgentsFailed":"The server is running, but OpenCode could not load agents. Retry once the cause is fixed.","startup.initRecovery.unexpected":"OpenChamber could not finish starting. Retry once the cause is fixed.","startup.initRecovery.lastError":"Last error","startup.initRecovery.retry":"Retry","startup.initRecovery.retrying":"Retrying…","startup.overlay.slow":"Startup is taking longer than expected…","onboarding.desktopRecovery.placeholders.remoteServer":"the remote server","onboarding.desktopRecovery.placeholders.unknownServer":"unknown","vscodeLayout.title.chat":"Chat","vscodeLayout.title.newSession":"New session","vscodeLayout.title.sessions":"Sessions","vscodeLayout.title.sessionFallback":"Session","vscodeLayout.actions.backToSessionsAria":"Back to sessions","vscodeLayout.actions.archiveAllAria":"Archive all sessions","vscodeLayout.actions.archiveAllConfirm":"Archive all","vscodeLayout.actions.archiveAllSuccess":"Archived {count} session(s)","vscodeLayout.actions.archiveAllError":"Failed to archive {count} session(s)","vscodeLayout.actions.cancel":"Cancel","vscodeLayout.actions.newSessionAria":"New session","vscodeLayout.actions.resizeSessionsSidebarAria":"Resize sessions sidebar","vscodeLayout.actions.showSessionsAria":"Show sessions","vscodeLayout.actions.hideSessionsAria":"Hide sessions","vscodeLayout.actions.settingsAria":"Settings","updateDialog.header.updateAvailable":"Update Available","updateDialog.header.updating":"Updating OpenChamber...","updateDialog.changelog.title":"What's new","updateDialog.status.installingUpdate":"Installing update...","updateDialog.status.serverRestarting":"Server restarting...","updateDialog.status.waitingForServer":"Waiting for server...","updateDialog.status.autoReloadHint":"The page will reload automatically when the update is complete.","updateDialog.fallback.updateViaTerminal":"Or update via terminal:","updateDialog.desktopHostInstall":"OpenChamber {version} is available. Update it on the computer it runs on.","updateDialog.openCodeTooOld":"OpenChamber {version} needs OpenCode {required}. This server has {current}. Update OpenCode first.","updateDialog.actions.copyCommand":"Copy command","updateDialog.actions.copied":"Copied!","updateDialog.status.downloadingPayload":"Downloading update payload...","updateDialog.actions.downloadUpdate":"Download Update","updateDialog.status.downloading":"Downloading...","updateDialog.actions.restartToUpdate":"Restart to Update","updateDialog.status.restarting":"Restarting...","updateDialog.actions.updateNow":"Update Now","updateDialog.actions.openMobileUpdate":"Open update","updateDialog.status.updating":"Updating...","updateDialog.error.updateFailed":"Update failed","updateDialog.error.takingLonger":"Update is taking longer than expected. Wait a bit and refresh, or run: openchamber update","updateDialog.error.signatureRejected":"The downloaded update was rejected: its code signature does not match this installation. This usually means the running copy was not installed from an official signed release. Install OpenChamber from an official release, then update again.","updateDialog.error.updaterDisabled":"The updater stopped after a failed install. Quit OpenChamber, open it again, and retry the update.","updateDialog.error.restartFailed":"Could not restart to install the update.","updateDialog.error.restartUnavailable":"Installing the update requires the OpenChamber desktop app.","mobileUpdate.toast.available.title":"OpenChamber update available","mobileUpdate.toast.available.description":"Version {version} is ready for Android.","mobileUpdate.toast.actions.download":"Download","opencodeUpdate.toast.available.title":"OpenCode update","opencodeUpdate.toast.available.description":"Version {version} available.","opencodeUpdate.toast.available.manualDescription":"Version {version} available. Update OpenCode the way you installed it, then restart OpenChamber.","opencodeUpdate.toast.actions.update":"Update","opencodeUpdate.toast.actions.reload":"Reload OpenCode","opencodeUpdate.toast.upgrading.title":"Updating OpenCode...","opencodeUpdate.toast.upgrading.description":"Keep OpenChamber open.","opencodeUpdate.toast.updated.title":"OpenCode updated","opencodeUpdate.toast.updated.description":"Update installed.","opencodeUpdate.toast.updated.descriptionWithVersion":"Version {version} installed.","opencodeUpdate.toast.failed.title":"Could not update OpenCode","opencodeUpdate.toast.failed.description":"The OpenCode upgrade failed.","opencodeUpdate.toast.reload.message":"Restarting OpenCode...","memoryDebugPanel.title":"Debug Panel","memoryDebugPanel.tabs.memory":"Memory","memoryDebugPanel.tabs.streaming":"Streaming","memoryDebugPanel.tabs.requests":"Requests","memoryDebugPanel.section.sessionsInMemory":"Sessions in Memory","memoryDebugPanel.section.uiStreamingMetrics":"UI Streaming Metrics","memoryDebugPanel.section.vscodeBridgeMetrics":"VS Code Bridge Metrics","memoryDebugPanel.section.noUiSamples":"No UI streaming samples yet. Start a stream and keep this panel open.","memoryDebugPanel.section.noVscodeSamples":"No VS Code bridge samples yet.","memoryDebugPanel.metric.totalMessages":"Total Messages","memoryDebugPanel.metric.cachedSessions":"Cached Sessions","memoryDebugPanel.metric.userMessages":"User Messages","memoryDebugPanel.metric.assistantMessages":"Assistant Messages","memoryDebugPanel.metric.viewportWindow":"Viewport Window","memoryDebugPanel.metric.zombieTimeout":"Zombie Timeout","memoryDebugPanel.metric.githubTotalRequests":"GitHub Total Requests","memoryDebugPanel.metric.metrics":"Metrics","memoryDebugPanel.metric.samples":"Samples","memoryDebugPanel.metric.lastUpdate":"Last Update","memoryDebugPanel.metric.uiMetrics":"UI Metrics","memoryDebugPanel.metric.vscodeMetrics":"VS Code Metrics","memoryDebugPanel.metric.messageListRenders":"MsgList Renders","memoryDebugPanel.metric.messageListStreamRenders":"MsgList Stream Renders","memoryDebugPanel.metric.chatMessageRenders":"ChatMessage Renders","memoryDebugPanel.metric.chatMessageStreamRenders":"ChatMessage Stream Renders","memoryDebugPanel.metric.chatMessageStaticDuringStream":"ChatMessage Static During Stream","memoryDebugPanel.metric.chatMessageStaticOutsideActiveTurn":"ChatMessage Static Outside Active Turn","memoryDebugPanel.metric.messagesValue":"{count} messages","memoryDebugPanel.metric.minutesValue":"{count} minutes","memoryDebugPanel.metric.msgsValue":"{count} msgs","memoryDebugPanel.metric.roleMsgsValue":"U {user} / A {assistant}","memoryDebugPanel.metric.countValue":"count {value}","memoryDebugPanel.metric.avgValue":"avg {value}","memoryDebugPanel.metric.maxValue":"max {value}","memoryDebugPanel.metric.totalValue":"total {value}","memoryDebugPanel.actions.logState":"Log State","memoryDebugPanel.actions.copyJson":"Copy JSON","memoryDebugPanel.tooltip.logCurrentState":"Log current memory state to browser console","memoryDebugPanel.streaming.copy.copied":"Streaming debug JSON copied","memoryDebugPanel.streaming.copy.failed":"Failed to copy JSON","memoryDebugPanel.streaming.copy.hint":"Copy exports both UI and VS Code streaming metrics as JSON","memoryDebugPanel.requests.inFlight":"In flight","memoryDebugPanel.requests.peak":"Peak","memoryDebugPanel.requests.duration":"Duration","memoryDebugPanel.requests.totalRequests":"Total Requests","memoryDebugPanel.requests.tracking":"Tracking","memoryDebugPanel.requests.now":"now","memoryDebugPanel.requests.noSamples":"No requests tracked yet. Keep this panel open to record fetch activity.","memoryDebugPanel.requests.chartLabel":"Fetch requests in flight over time, peak {peak}","memoryDebugPanel.requests.windowHint":"last {seconds}s","memoryDebugPanel.requests.percentileChartLabel":"In-flight request age percentiles (p50, p90, p99, max) over time","memoryDebugPanel.common.idle":"idle","memoryDebugPanel.common.live":"live","memoryDebugPanel.common.notAvailable":"n/a","memoryDebugPanel.common.untitled":"Untitled","directoryTree.field.newDirectoryPlaceholder":"new_directory","textarea.resizeHandleAria":"Resize textarea","sidebar.resize.leftPanelAria":"Resize left panel","sidebar.resize.rightPanelAria":"Resize right panel","mainLayout.mobile.closeDrawerAria":"Close drawer","sortableTabsStrip.aria.tabs":"Tabs","openChamberLogo.aria.logo":"OpenChamber logo","markdownRenderer.code.proposal":"Proposal","markdownRenderer.code.actions.copyTitle":"Copy code","markdownRenderer.code.actions.copiedTitle":"Copied","markdownRenderer.code.actions.runTitle":"Run command. The agent continues from its output","markdownRenderer.code.actions.stopTitle":"Stop command","markdownRenderer.code.run.startFailed":"Could not start the command","markdownRenderer.code.run.running":"Running","markdownRenderer.code.run.finished":"Finished","markdownRenderer.code.run.failed":"Exit code {code}","markdownRenderer.code.run.stopped":"Stopped","markdownRenderer.table.actions.copyTitle":"Copy table","markdownRenderer.code.actions.enableWrapTitle":"Enable line wrap","markdownRenderer.code.actions.disableWrapTitle":"Disable line wrap","markdownRenderer.table.actions.enableWrapTitle":"Enable cell wrap","markdownRenderer.table.actions.disableWrapTitle":"Disable cell wrap","markdownRenderer.table.actions.downloadTitle":"Download table","markdownRenderer.table.toast.downloadedAsFormat":"Table downloaded as {format}","markdownRenderer.mermaid.actions.copyTitle":"Copy","markdownRenderer.mermaid.actions.copySourceTitle":"Copy source","markdownRenderer.mermaid.actions.downloadSvgTitle":"Download SVG","markdownRenderer.mermaid.actions.zoomInTitle":"Zoom in","markdownRenderer.mermaid.actions.zoomOutTitle":"Zoom out","markdownRenderer.mermaid.actions.resetViewTitle":"Reset view","markdownRenderer.mermaid.toast.downloadFailed":"Failed to download diagram","common.date.today":"Today","common.date.yesterday":"Yesterday","common.date.yesterdayWithTime":"Yesterday {time}","common.relative.justNow":"Just now","common.relative.minutesAgoShort":"{count}min ago","common.relative.hoursAgoShort":"{count}h ago","common.relative.daysAgoShort":"{count}d ago","common.relative.weeksAgoShort":"{count}w ago","common.relative.yearsAgoShort":"{count}y ago","common.relative.minutesAgoCompact":"{count}m","common.relative.hoursAgoCompact":"{count}h","common.relative.daysAgoCompact":"{count}d","common.relative.weeksAgoCompact":"{count}w","common.relative.monthsAgoCompact":"{count}mo","common.relative.yearsAgoCompact":"{count}y","common.duration.secondsCompact":"{seconds}s","common.duration.minutesSecondsCompact":"{minutes}m {seconds}s","common.duration.hoursMinutesCompact":"{hours}h {minutes}m","contextFileOpen.failure.tooLarge":"{name} is too large to open","contextFileOpen.failure.tooLargeDetail":"More than {count} lines · {size}","contextFileOpen.failure.tooLargeSize":"Larger than {limit} · {size}","contextFileOpen.failure.missing":"{name} was not found","contextFileOpen.failure.unreadable":"Couldn't open {name}","quota.window.5h":"5-Hour","quota.window.7d":"7-Day Limit","quota.window.extraUsage":"Extra Usage","quota.window.weekly":"Weekly","quota.window.daily":"Daily","quota.window.monthly":"Monthly","quota.window.credits":"Credits","quota.value.creditsUsed":"{credits} Credits Used","quota.window.keyLimit":"Key Limit","quota.window.creditsBalance":"Credits Balance","quota.window.monthlyCredits":"Monthly Credits","quota.window.purchasedCredits":"Purchased Credits","quota.window.freeCredits":"Free Credits","quota.window.billingCycle":"Billing Cycle","quota.window.auto":"Auto","quota.window.api":"API","quota.window.planLimit":"Plan Limit","quota.window.onDemand":"On-demand","quota.window.session":"Session","quota.window.premium":"Premium Interactions","quota.window.chat":"Chat Requests","quota.window.completions":"Completions","quota.window.premiumInteractions":"AI Credits","chat.workStatus.ariaLabel":"Work status","chat.workStatus.mobileEmpty":"Nothing to show for this session yet","chat.workStatus.context.label":"Context","chat.workStatus.cost.breakdown":"Session {session} · Subagents {subagents}","chat.workStatus.git.changedFileSingle":"{count} file changed","chat.workStatus.git.changedFilePlural":"{count} files changed","chat.workStatus.pr.untitled":"Untitled pull request","chat.workStatus.mr.untitled":"Untitled merge request","chat.workStatus.pr.draft":"Draft","chat.workStatus.pr.checks":"Checks","chat.workStatus.pr.checksFailed":"{count} failed","chat.workStatus.pr.checksPending":"{count} running","chat.workStatus.pr.checksPassed":"{count} passed","chat.workStatus.attention.merge":"Merge in progress","chat.workStatus.attention.rebase":"Rebase in progress","chat.workStatus.attention.cherryPick":"Cherry-pick in progress","chat.workStatus.attention.revert":"Revert in progress","chat.workStatus.attention.bisect":"Bisect in progress","chat.workStatus.subagent.done":"Done","chat.workStatus.subagent.failed":"Failed","chat.workStatus.subagent.untitled":"Subagent","chat.workStatus.mcp.toggle":"Toggle {name}","chat.workStatus.mcp.needsAuth":"Sign in","chat.workStatus.mcp.failed":"Failed","chat.workStatus.pinned.unavailable":"Pinned message","chat.workStatus.section.session":"Session","chat.workStatus.section.project":"Project","chat.workStatus.section.subagents":"Subagents","chat.workStatus.section.mcp":"MCP","chat.workStatus.section.pinned":"Pinned messages","chat.workStatus.section.tasks":"Tasks","chat.workStatus.subagent.working":"is working","chat.workStatus.subagent.needsPermission":"needs permission","chat.workStatus.subagent.askedQuestion":"asked a question","chat.workStatus.section.contextBreakdown":"Context sources","chat.workStatus.breakdown.skills":"Skills","chat.workStatus.breakdown.pinnedNote":"note","chat.workStatus.breakdown.unpin":"Unpin from context","chat.workStatus.breakdown.pinnedPlan":"plan","chat.workStatus.breakdown.memory":"Agent memory","chat.workStatus.breakdown.pinnedKnowledgeSingle":"{count} pinned","chat.workStatus.breakdown.pinnedKnowledgePlural":"{count} pinned","chat.workStatus.breakdown.mcp":"MCP servers","chat.workStatus.action.openChanges":"Open changes","chat.workStatus.action.openGit":"Open Git panel","chat.workStatus.action.openPr":"Open pull request","chat.workStatus.action.openMr":"Open merge request","chat.workStatus.action.openSubagent":"Open {name}","chat.workStatus.section.usage":"Usage","chat.workStatus.section.telemetry":"Turn stats","chat.workStatus.telemetry.previousTurn":"Previous turn","chat.workStatus.telemetry.previousTurnRate":"Previous turn · {rate}","chat.workStatus.telemetry.responseSpeed":"Response","chat.workStatus.telemetry.responseSpeedDescription":"How fast the final text arrived. Excludes the initial wait, reasoning, and earlier tool calls. An estimate from text timestamps, not a provider speed measurement.","chat.workStatus.telemetry.speed":"Whole turn","chat.workStatus.telemetry.speedDescription":"Tokens generated across all steps, including reasoning, divided by time with tool execution removed. Waiting for the model still counts, so many short tool calls can lower this number.","chat.workStatus.telemetry.elapsed":"Elapsed","chat.workStatus.telemetry.elapsedDescription":"Wall-clock time from the first user message to the final assistant response. Includes model waiting, tool execution, compaction, and other gaps.","chat.workStatus.telemetry.llmDuration":"Model time","chat.workStatus.telemetry.llmDurationDescription":"Time spent on all model steps, including waiting for responses. Tool execution time is removed. This is not just time spent generating text.","chat.workStatus.telemetry.toolDuration":"Tool time","chat.workStatus.telemetry.toolDurationDescription":"Time spent running tools, including failed calls. Tools running at the same time are counted once, not added together.","chat.workStatus.telemetry.ttft":"Average TTFT","chat.workStatus.telemetry.ttftDescription":"Average wait before the first text or reasoning starts in each model step. Hidden when a step has no start after it was created, which is common for tool-only steps and for parts stamped at creation time.","chat.workStatus.telemetry.steps":"Steps","chat.workStatus.telemetry.stepsDescription":"How many times the model was called for this prompt. Reading tool results and deciding what to do next usually takes another step.","chat.workStatus.telemetry.tokens":"Tokens","chat.workStatus.telemetry.tokens.inOut":"{input} ↑ · {output} ↓","chat.workStatus.telemetry.tokensDescription":"↑ Input without cached tokens: {input}. ↓ Generated tokens: {output} for text and tool calls, plus {reasoning} for reasoning. Totals cover all steps of this prompt.","chat.workStatus.telemetry.cacheHit":"Cache","chat.workStatus.telemetry.cacheHitDescription":"Share of input tokens reused from the prompt cache across all steps. Reusing context can reduce cost and waiting, but this is not a speed score.","chat.workStatus.telemetry.cost":"Cost","chat.workStatus.telemetry.costDescription":"Cost reported by the provider for all model steps of this prompt, in US dollars. Excludes separate subagent sessions. Zero can mean a free model or a provider that reports no charge.","chat.workStatus.goal.open":"Manage goal","chat.workStatus.goal.pause":"Pause","chat.workStatus.goal.resume":"Resume","chat.workStatus.goal.updateFailed":"Could not update the goal","chat.workStatus.pinned.unpin":"Unpin message","chat.workStatus.pinned.reveal":"Go to message","chat.workStatus.pinned.unpinFailed":"Could not unpin the message","chat.workStatus.action.openContext":"Open context panel","chat.workStatus.section.linkedIssues":"Linked","chat.workStatus.linkedIssues.openOnProvider":"Open {reference} on {provider}","chat.workStatus.linkedIssues.unlink":"Remove link","chat.workStatus.linkedIssues.unlinkFailed":"Could not remove the link","chat.workStatus.linkedIssues.link":"Link to session","chat.workStatus.linkedIssues.linkFailed":"Could not link","chat.workStatus.breakdown.issueCountSingle":"{count} issue","chat.workStatus.breakdown.issueCountPlural":"{count} issues","chat.workStatus.breakdown.prCountSingle":"{count} PR","chat.workStatus.breakdown.mrCountSingle":"{count} MR","chat.workStatus.breakdown.prCountPlural":"{count} PRs","chat.workStatus.breakdown.mrCountPlural":"{count} MRs","chat.workStatus.breakdown.skillCountSingle":"{count} skill","chat.workStatus.breakdown.skillCountPlural":"{count} skills","chat.workStatus.breakdown.mcpCountSingle":"{count} MCP","chat.workStatus.breakdown.mcpCountPlural":"{count} MCP","chat.workStatus.breakdown.planCountSingle":"{count} plan","chat.workStatus.breakdown.planCountPlural":"{count} plans","chat.workStatus.linkedPlans.open":"Open plan {title}","chat.workStatus.sections.open":"Choose sections","chat.workStatus.sections.dialogTitle":"Panel sections","chat.workStatus.sections.reorder":"Drag {label} to reorder","chat.workStatus.sections.dragInstructions":"Press Space to pick up a section, use the arrow keys to move it, and press Space to drop. Press Escape to cancel.","chat.workStatus.sections.position":"{label}, position {position} of {count}.","chat.workStatus.sections.dragCancelled":"Reordering cancelled.","chat.workStatus.sections.dialogDescription":"Choose what the work-status panel shows. Hidden sections keep their data — they are only left out of the panel.","chat.workStatus.sections.allHidden":"No sections selected","chat.workStatus.sections.showAll":"Show all","chat.workStatus.sections.noneWarning":"The panel will appear empty.","header.workStatusPanel.toggleAria":"Toggle work-status panel","header.actions.newMiniChat":"New Mini Chat Window","header.actions.newMiniChatAria":"Open a new Mini Chat window","header.actions.openSessionMiniChat":"Open Session in Mini Chat","header.actions.openSessionMiniChatAria":"Open current session in Mini Chat","header.workStatusPanel.hide":"Hide work status","header.workStatusPanel.show":"Show work status","chat.workStatus.mcp.authorizeOpenFailed":"Could not open the authorization page","chat.workStatus.mcp.authorizeFailed":"Authorization failed","chat.formCard.inputNeeded":"Input needed","chat.formCard.fromSubagent":"from a subagent","chat.formCard.required":"Required","chat.formCard.openLink":"Open link","chat.formCard.yes":"Yes","chat.formCard.other":"Other","chat.formCard.yourAnswer":"Your answer","chat.formCard.submit":"Submit","chat.formCard.cancel":"Cancel","chat.formCard.missingRequired":"Fill in the required fields first.","chat.formCard.submitFailed":"Could not submit the answer","chat.formCard.cancelFailed":"Could not cancel the request","chat.formCard.tryAgain":"Try again.","chat.formCard.connectionLost":"Connection to the server was lost. Nothing was sent; try again once it reconnects.","chat.formCard.connectionLostReason":"Connection to the server was lost ({reason}). Nothing was sent; try again once it reconnects.","chat.formCard.notConnected":"Not connected to the server yet. Nothing was sent; try again once it connects.","chat.formCard.recoveredNotice":"The turn stopped while waiting. Submit starts a new paid turn.","chat.formDock.progress":"{current} of {total}","chat.formDock.waiting":"{count} more waiting","chat.formDock.back":"Back","chat.formDock.expandAria":"Expand the question","chat.formDock.collapseAria":"Collapse the question","chat.formDock.stepAria":"Question {index}: {title}","chat.formDock.linkInfo":"Open the link, then continue.","chat.permissionCard.title":"Permission required","chat.permissionCard.summary.externalDirectory":"Access files outside the project","chat.permissionCard.summary.read":"Read a file","chat.permissionCard.summary.edit":"Edit files","chat.permissionCard.summary.shell":"Run a command","chat.permissionCard.summary.glob":"Find files","chat.permissionCard.summary.grep":"Search file contents","chat.permissionCard.summary.webfetch":"Open a web page","chat.permissionCard.summary.websearch":"Search the web","chat.permissionCard.summary.skill":"Load a skill","chat.permissionCard.summary.tool":"Use {tool}","chat.permissionCard.summary.inPath":"in {path}","chat.permissionCard.showDetails":"Show details","chat.permissionDock.expandAria":"Expand the permission request","chat.permissionDock.collapseAria":"Collapse the permission request","chat.permissionDock.stepAria":"Request {index}: {tool}","chat.permissionCard.allowOnce":"Allow once","chat.permissionCard.alwaysAllow":"Always allow","chat.permissionCard.alwaysAllowPatterns":"Always: {patterns}","chat.permissionCard.deny":"Deny","chat.permissionCard.replaceAll":"Replaces every occurrence","chat.compaction.running":"Compacting the conversation","chat.compaction.completed":"Conversation compacted","chat.compaction.failed":"Compaction failed","chat.compaction.showSummary":"Show summary","chat.compaction.hideSummary":"Hide summary","chat.dispatchedSession.completed":"Session finished: {title}","chat.dispatchedSession.failed":"Session failed: {title}","chat.dispatchedSession.cancelled":"Session stopped: {title}","chat.dispatchedSession.completedUntitled":"Session finished","chat.dispatchedSession.failedUntitled":"Session failed","chat.dispatchedSession.cancelledUntitled":"Session stopped","chat.dispatchedSession.showAnswer":"Show answer","chat.dispatchedSession.hideAnswer":"Hide answer","chat.dispatchedSession.open":"Open session","chat.fileOpenRequest.toast.description":"Shown in {session}","chat.fileOpenRequest.toast.descriptionUntitled":"Shown in another session","chat.fileOpenRequest.toast.openSession":"Open session","chat.revertPopover.staged":"Reverted: {count}","chat.revertPopover.toast.restoreFailed":"Couldn't restore the reverted messages","chat.workStatus.mcp.needsAuthHint":"Sign in to this MCP server from Settings → MCP.","header.services.tooltip.currentInstance":"Current instance: {current} ({toggle})","header.workStatusPanel.showOverlay":"Show work status over the chat","settings.mcp.page.connection.title":"How to reach it","settings.mcp.page.connection.description":"Paste the command that starts it, or the link to a hosted server.","settings.mcp.page.registration.title":"This server needs its own app","settings.mcp.page.registration.description":"It does not hand out credentials automatically. Create an app in the service’s own settings, paste its details here, then sign in.","settings.mcp.page.registration.callbackLabel":"Give the service this address","settings.mcp.page.registration.clientId":"App ID","settings.mcp.page.registration.clientSecret":"App secret","settings.mcp.page.registration.afterSaving":"Save, then press Authorize to sign in.","settings.mcp.page.toast.copiedCallbackUrl":"Address copied","settings.mcp.page.toast.clipboardWriteFailed":"Could not copy to the clipboard","settings.mcp.page.scope.everywhere":"Available in every project","settings.mcp.page.scope.thisProject":"Only in this project","settings.mcp.page.env.description":"Values the server needs, such as an API key.","settings.mcp.page.connection.kindCommand":"Command","settings.mcp.page.connection.kindLink":"Link","settings.mcp.page.connection.hintCommand":"Runs on this machine. Paste a whole command and it is split into one argument per line.","settings.mcp.page.connection.hintLink":"Connects to a server someone else hosts. Paste its https address.","chat.messageBody.actions.askOtherModels":"Ask other models","chat.modelControls.runInParallel":"Run on several models","chat.parallel.defaultTitle":"Parallel run","chat.parallel.exit":"Leave parallel mode","chat.parallel.fuse.judge":"Fuse with {model}","chat.parallel.fuse.off":"Fuse: off","chat.parallel.isolation.shared":"Shared directory","chat.parallel.isolation.worktrees":"Separate worktrees","chat.parallel.models.add":"Add model","chat.parallel.models.decrement":"Run {model} one time less","chat.parallel.models.increment":"Run {model} one more time","chat.parallel.runAria":"Start parallel runs ({count})","chat.parallel.setup.dialogDescription":"Commands run in every new worktree before its prompt, one per line.","chat.parallel.toast.failed":"Could not start the parallel run.","chat.parallel.toast.incomplete":"Every prompt variant needs text and at least one model.","chat.parallel.variant.removeAria":"Remove variant {variant}","chat.parallel.variant.runsPlural":"{count} runs","chat.parallel.variant.runsSingle":"{count} run","chat.parallel.variant.tabsAria":"Prompt variants","multirun.ask.checking":"Checking this answer…","multirun.ask.description":"This chat becomes the first run. Each model gets the same first prompt in its own worktree.","multirun.ask.failed":"Could not ask other models.","multirun.ask.notFirstTurn":"Only the first answer of a chat can be compared for now.","multirun.ask.startPlural":"Run {count} more","multirun.ask.startSingle":"Run {count} more","multirun.ask.title":"Ask other models","multirun.overview.archive.action":"Archive run","multirun.overview.archive.failed":"Some runs could not be archived.","multirun.overview.ask.failed":"Could not add the model to this run.","multirun.overview.ask.working":"Adding…","multirun.overview.bar.fuse":"Fuse results","multirun.overview.bar.hint":"Fuse the answers into one result","multirun.overview.cancel":"Cancel","multirun.overview.card.changesUnavailable":"Changes unavailable","multirun.overview.card.diff":"Diff","multirun.overview.card.filesPlural":"{count} files","multirun.overview.card.filesSingle":"{count} file","multirun.overview.card.noChanges":"No file changes","multirun.overview.card.noReply":"No answer yet","multirun.overview.card.openChat":"Open chat","multirun.overview.card.replyUnavailable":"Answer unavailable","multirun.overview.card.selectAria":"Select {name}","multirun.overview.card.working":"Working…","multirun.overview.fuse.modeAnswers":"Combines the final answers","multirun.overview.fuse.modeCode":"Works in its own worktree and reads each run with git","multirun.overview.fuse.selected":"{count} of {total} selected","multirun.overview.fuse.with":"Fuse with","multirun.overview.fusedResult":"Fused result","multirun.overview.headerTitle":"Run in parallel","multirun.overview.keep.confirm":"Keep and clean up","multirun.overview.keep.confirmPlural":"Keep {name}? The other {count} runs are archived and their worktrees removed. Their work stays recoverable.","multirun.overview.keep.confirmSingle":"Keep {name}? The other run is archived and its worktree removed. Its work stays recoverable.","multirun.overview.keep.done":"Kept {name}","multirun.overview.keep.failed":"Could not clean up the other runs.","multirun.overview.keep.partialPlural":"Kept {name}. {count} runs could not be cleaned up and were left as they were.","multirun.overview.keep.partialSingle":"Kept {name}. One run could not be cleaned up and was left as it was.","multirun.overview.keep.working":"Cleaning up…","multirun.overview.meta.autoFusion":"Fuses with {model} when all finish","multirun.overview.meta.progress":"{done} of {total} finished","multirun.overview.meta.runsPlural":"{count} runs","multirun.overview.meta.runsSingle":"{count} run","multirun.overview.meta.sharedDirectory":"Shared directory","multirun.overview.meta.variants":"{count} prompt variants","multirun.overview.meta.worktrees":"Separate worktrees","multirun.overview.missing":"This run is no longer available.","multirun.overview.rename.aria":"Rename run","multirun.overview.rename.failed":"Some runs kept the old name.","sessions.sidebar.run.collapse":"Hide runs","sessions.sidebar.run.expand":"Show runs","sessions.sidebar.run.laneCountPlural":"{count} runs","sessions.sidebar.run.laneCountSingle":"{count} run","sessions.sidebar.run.openOverviewAria":"Open parallel run {title}","sessions.sidebar.run.menu.openOverview":"Open overview","sessions.sidebar.session.menu.openRunOverview":"Open run overview","chat.parallel.models.effortAria":"Thinking effort: {effort}","chat.parallel.settings.title":"Launch settings","chat.parallel.settings.whereTitle":"Where the runs work","chat.parallel.settings.setupTitle":"Setup commands","chat.parallel.settings.fusionTitle":"Fusion","chat.parallel.settings.variantsTitle":"Prompt variants","chat.parallel.settings.variantsDescription":"Send different prompts, for example to compare skills or wording. Each variant gets its own tab.","chat.parallel.settings.addVariant":"Add a prompt variant","chat.parallel.settings.done":"Done","chat.parallel.settings.openAria":"Launch settings: {summary}","multirun.overview.card.keep":"Keep this","multirun.overview.addModel.action":"Add a model","multirun.overview.addModel.hint":"Runs the same prompt on one more model in this run","chat.parallel.settings.whereShared":"Project directory","chat.parallel.settings.whereSharedHint":"All runs work in your checkout. Best for questions and research.","chat.parallel.settings.whereWorktrees":"Separate worktrees","chat.parallel.settings.whereWorktreesHint":"Each run gets its own branch, so code changes never collide. Keep the best one.","chat.parallel.settings.baseBranchTitle":"Base branch","chat.parallel.settings.fusionOff":"Off","chat.parallel.settings.fusionOffHint":"Compare the results yourself.","chat.parallel.settings.fusionAuto":"Automatic","chat.parallel.settings.fusionAutoHint":"Fuse the results as soon as every run finishes.","chat.parallel.settings.judgeTitle":"Fusion model","multirun.overview.card.detach":"Make a separate session","multirun.overview.card.detachHint":"Leave this run and continue as an ordinary session","multirun.overview.card.detachDone":"{name} is now a separate session","multirun.overview.card.detachFailed":"Could not move this session out of the run.","multirun.overview.card.archive":"Archive this session","multirun.overview.addModel.confirm":"Run","multirun.overview.status.permission":"Waiting for your permission","multirun.overview.status.question":"Waiting for your answer","multirun.overview.status.working":"Working","multirun.overview.status.failed":"Failed","multirun.overview.status.stopped":"Stopped","multirun.overview.status.notStarted":"Not started","multirun.overview.status.noReply":"Finished without an answer","multirun.overview.status.finished":"Finished","multirun.overview.status.count.permission":"{count} waiting for permission","multirun.overview.status.count.question":"{count} waiting for an answer","multirun.overview.status.count.working":"{count} working","multirun.overview.status.count.failed":"{count} failed","multirun.overview.status.count.stopped":"{count} stopped","multirun.overview.status.count.notStarted":"{count} not started","multirun.overview.status.count.noReply":"{count} without an answer","multirun.overview.status.count.finished":"{count} finished","multirun.overview.card.body.permission":"Waiting for your permission to go on. Open the chat to answer.","multirun.overview.card.body.question":"Asked you a question. Open the chat to answer.","multirun.overview.card.body.failed":"Failed. Open the chat for details.","multirun.overview.card.body.notStarted":"Has not started yet.","multirun.overview.card.body.stopped":"Stopped before answering.","multirun.overview.bar.waiting":"Runs waiting for you: {count}. The run can't finish until you answer them.","multirun.overview.prompt.expand":"Show all","multirun.overview.prompt.collapse":"Show less","gitView.changes.revertFileDialogTitle":"Revert file changes?","gitView.changes.revertFileDescription":"This will discard your local changes in {path}.","gitView.changes.revertFileConfirm":"Revert file","diffView.hunk.discardDialogTitle":"Discard this hunk?","diffView.hunk.discardDescription":"This will discard these local changes in {path}.","sessions.sidebar.project.actions.archiveAll":"Archive all sessions","sessions.sidebar.project.archiveAll.title":"Archive sessions in {project}?","sessions.sidebar.project.archiveAll.descriptionSingle":"{count} session moves to the archive. Pinned, running and In work sessions stay.","sessions.sidebar.project.archiveAll.descriptionPlural":"{count} sessions move to the archive. Pinned, running and In work sessions stay.","sessions.sidebar.project.archiveAll.nothing":"Nothing to archive: every session here is pinned, running or In work.","contextPanel.browser.devServers.hide":"Hide port {port} from this list","contextPanel.browser.devServers.showHiddenSingle":"Show {count} hidden port","contextPanel.browser.devServers.showHiddenPlural":"Show {count} hidden ports","sidebarFilesTree.menu.openInDefaultApp":"Open in default app","sessions.sidebar.header.displayMode.showChats":"Show chats section","sessions.scheduledTasks.editor.useDefaults.label":"Use session defaults","sessions.scheduledTasks.editor.useDefaults.hint":"Each run takes the default model, thinking level and agent from Settings → Sessions (or the project's own defaults) at the time it starts.","sessions.scheduledTasks.editor.worktree.label":"Run each run in a fresh worktree","sessions.scheduledTasks.editor.worktree.hint":"Each run gets its own worktree and branch.","sessions.scheduledTasks.editor.worktree.baseBranch.label":"Source branch","sessions.scheduledTasks.editor.worktree.cleanup.label":"Clean up worktree after run","sessions.scheduledTasks.editor.worktree.cleanup.hint":"The worktree and its branch are removed when the run ends.","sessions.scheduledTasks.editor.worktree.cleanup.keepHint":"The worktree and its branch stay after the run so you can review the result.","sessions.scheduledTasks.editor.worktree.notRepo":"The project folder is not a git repository; runs will use the checkout as-is.","sessions.scheduledTasks.dialog.usesDefaults":"Session defaults","sessions.moveSession.menu":"Move session…","sessions.moveSession.hint":"Files stay in the old folder","sessions.moveSession.title":"Move session","sessions.moveSession.description":"The session continues in the chosen folder. Files stay where they are.","sessions.moveSession.chooseFolder":"Choose folder…","sessions.moveSession.current":"Current folder","sessions.moveSession.success":"Session moved","sessions.moveSession.failed":"Could not move the session","chat.folderMissing.text":"Folder {name} no longer exists","chat.folderMissing.action":"Move session","chat.trustPaused.text":"Agents can't work in {name} until you trust its plugins and commands.","chat.trustPaused.action":"Review and trust","chat.worktreeSetup.running":"Setting up the worktree: running the project's setup commands…","chat.draft.creatingSession":"Creating session…","desktopHostSwitcher.startup.fellBackToLocal":"Its connection didn't open, so OpenChamber started on Local. Connect it from the instance switcher once it's reachable.","desktopSafeStart.title":"OpenChamber kept crashing","desktopSafeStart.description":"Panels are closed and folders collapsed.","chat.chatInput.contextPreview.saveEdit":"Save comment","chat.chatInput.contextPreview.cancelEdit":"Cancel editing","sessions.scheduledTasks.dialog.actions.openSession":"Open session","sessions.scheduledTasks.dialog.actions.openSessionAria":"Open the session from the last run of {taskName}","sessions.scheduledTasks.dialog.toast.alreadyRunningSince":"This task already has a run in progress, started at {time}","sessions.scheduledTasks.dialog.toast.alreadyRunning":"This task already has a run in progress","sessions.scheduledTasks.dialog.toast.alreadyQueued":"This task is already waiting in the queue and will run when a slot frees up","chat.modelControls.agentFavoriteAdd":"Add to favorites. With favorites, Tab cycles through them only","notifications.error.bodyFallback":"An error occurred","notifications.question.bodyFallback":"Agent is waiting for your response","notifications.permission.bodyFallback":"Agent is waiting for your approval","notifications.permission.title":"Permission required","chat.promptHistorySearch.title":"Search prompt history","chat.promptHistorySearch.searchPlaceholder":"Search remembered prompts","chat.promptHistorySearch.close":"Close prompt history search","chat.promptHistorySearch.empty":"No prompts to search yet","chat.promptHistorySearch.noMatches":"No matching prompts","chat.promptHistorySearch.attachmentsSingle":"{count} attachment","chat.promptHistorySearch.attachmentsPlural":"{count} attachments","chat.promptHistorySearch.hint":"↑ ↓ to browse · Enter to load · Esc to close","helpDialog.item.searchPromptHistory":"Search prompt history (chat input)"},Vk=new RegExp("\\p{L}[\\p{L}\\p{M}‌]*","gu"),Uk="\\p{Script=Arabic}\\p{Script=Hebrew}\\p{Script=Syriac}\\p{Script=Thaana}\\p{Script=Nko}\\p{Script=Adlam}\\p{Script=Samaritan}\\p{Script=Mandaic}",vO=new RegExp(`^[${Uk}]`,"u"),Kp=new RegExp(`[${Uk}]`,"u"),Wk=new RegExp("\\p{L}","u"),CO=e=>Kp.test(e),SO=(e,t)=>Wk.test(e)&&(t||Kp.test(e))?`⁨${e}⁩`:e,Hk=e=>{let t=0;for(const s of e)vO.test(s)&&(t+=1);if(e.length!==0)return t*2>=e.length?"rtl":"ltr"},hJ=(...e)=>Hk(e.flatMap(t=>t?Array.from(t.matchAll(Vk),([s])=>s):[])),PO=/`[^`\n]*`|https?:\/\/\S+/g,fJ=e=>Kp.test(e)?Hk(e.replace(PO," ").split(/\s+/).flatMap(t=>{const s=t.match(Vk)?.[0];return s?[s]:[]})):Wk.test(e)?"ltr":void 0,fd=new Map([[Ko,Zo]]);async function xO(e){const t=fd.get(e);if(t)return t;const s=e==="zh-CN"?await Ge(()=>import("./zh-CN-D2e-OTjQ.js"),__vite__mapDeps([3,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="fr"?await Ge(()=>import("./fr-BJEccZsE.js"),__vite__mapDeps([109,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="nl"?await Ge(()=>import("./nl-MVCsXAqA.js"),__vite__mapDeps([110,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="zh-TW"?await Ge(()=>import("./zh-TW-DCj_Doyh.js"),__vite__mapDeps([111,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="es"?await Ge(()=>import("./es-BextOZlH.js"),__vite__mapDeps([112,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="pt-BR"?await Ge(()=>import("./pt-BR-D-thkXCk.js"),__vite__mapDeps([113,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="uk"?await Ge(()=>import("./uk-CWz0kaNm.js"),__vite__mapDeps([114,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="ko"?await Ge(()=>import("./ko-BAGf67hm.js"),__vite__mapDeps([115,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="pl"?await Ge(()=>import("./pl-zi2r4I2L.js"),__vite__mapDeps([116,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="de"?await Ge(()=>import("./de-DpOf_BMg.js"),__vite__mapDeps([117,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="ja"?await Ge(()=>import("./ja-Bf_2zWyq.js"),__vite__mapDeps([118,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="tr"?await Ge(()=>import("./tr-BeLCIXLh.js"),__vite__mapDeps([119,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="ar"?await Ge(()=>import("./ar-DuOBHgr_.js"),__vite__mapDeps([120,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):e==="he"?await Ge(()=>import("./he-9oI-aOhB.js"),__vite__mapDeps([121,4,5,1,2,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108])):{dict:Zo};return fd.set(e,s.dict),s.dict}const Er=Rt()((e,t)=>({locale:Ko,dictionary:Zo,loadingLocale:null,setLocale:s=>{const a=t(),n=fd.get(s);a.locale===s&&a.loadingLocale!==s&&n||($I(s),e({locale:s,dictionary:n??a.dictionary,loadingLocale:n?null:s}),!n&&xO(s).then(o=>{t().locale===s&&e({dictionary:o,loadingLocale:null})}).catch(o=>{console.error(`[i18n] failed to load locale ${s}`,o),t().locale===s&&e({dictionary:Zo,loadingLocale:null})}))}}));function TO(){Er.getState().setLocale(QI())}function AO(e,t,s){const a=e[t]??Zo[t]??t;if(!s)return a;const n=CO(a);return a.replace(/\{([^{}]+)\}/g,(o,i)=>{const r=s[i.trim()];if(r==null)return o;const l=String(r);return l===r?SO(l,n):l})}const bJ=Object.freeze(Object.defineProperty({__proto__:null,formatMessage:AO,initializeLocale:TO,useI18nStore:Er},Symbol.toStringTag,{value:"Module"})),Gk="session",_k=40,zO=1,RO=100,Kk=e=>e==="global"||e==="session",Zp=e=>e!=null&&Number.isInteger(e)&&e>=zO&&e<=RO,IO=["bash","zsh","sh","fish","pwsh","powershell","cmd","dash","ksh","nu"],Jp=e=>e==="auto"||typeof e=="string"&&IO.includes(e),sn="openchamber-input-history.v1",jO=8,OO=50,DO=[40,25,10,5,1],cl=Object.freeze([]);let hs=null,im=0;const To=(e=Gk,t=_k)=>({entryLimit:t,scope:e,globalBuckets:{},sessionBuckets:{}}),Zk=()=>(im+=1,Date.now()*1e3+im),Jk=e=>JSON.stringify([e]),bd=(e,t,s)=>JSON.stringify([e,t,s]),$p=()=>{try{return globalThis.window?.localStorage??null}catch{return null}},NO=()=>{const e=$p(),t=Lt?JSON.stringify(ur(Lt.base)):hs;if(!e)return t;try{return e.getItem(sn)??(Lt?null:hs)}catch{return t}},rm=ke(c(),ne()),FO=d({key:c().min(1),source:M([m("file-url"),m("vscode-file")]),filename:c().min(1),mimeType:c().min(1),size:w().finite().nonnegative(),reference:c().min(1),path:c().min(1).optional()}),EO=d({text:c(),attachmentKeys:C(c()),restorableAttachments:C(FO),submittedAt:w().finite().nonnegative()}),MO=d({touchedAt:w().finite().nonnegative(),entries:C(ne())}),BO=(e,t)=>{try{const s=JSON.parse(e),n=(t===1?wr([c().trim().min(1)]):wr([c().trim().min(1),c().trim().min(1),c().trim().min(1)])).safeParse(s);if(!n.success)return null;if(t===3){const o=je(n.data[1]);if(!o||o!==n.data[1])return null}return n.data}catch{return null}},cm=(e,t)=>{const s=[];for(const[a,n]of Object.entries(e)){if(!BO(a,t))continue;const o=MO.safeParse(n);if(!o.success)continue;const i=o.data.entries.map(r=>EO.safeParse(r)).filter(r=>r.success).map(r=>r.data);s.push([a,{touchedAt:o.data.touchedAt,entries:i}])}return Object.fromEntries(s)},LO=()=>{const e=NO();if(e===null)return To();try{const t=JSON.parse(e),s=d({version:m(1),entryLimit:w().int().optional(),scope:M([m("global"),m("session")]).optional(),global:rm.default({}),session:rm.default({})}).safeParse(t);return s.success?{entryLimit:Zp(s.data.entryLimit)?s.data.entryLimit:_k,scope:s.data.scope??Gk,globalBuckets:cm(s.data.global,1),sessionBuckets:cm(s.data.session,3)}:To()}catch{const t=$p();if(t)try{t.removeItem(sn)}catch{}return hs=null,To()}};let Lt=null,pr=To();const lm=(e,t,s)=>{const a={...e};for(const n of new Set([...Object.keys(t),...Object.keys(s)])){if(JSON.stringify(t[n])===JSON.stringify(s[n]))continue;const o=s[n];if(!o){delete a[n];continue}const i=new Set((t[n]?.entries??[]).map(u=>JSON.stringify(u))),r=new Set(o.entries.map(u=>JSON.stringify(u))),l=(e[n]?.entries??[]).filter(u=>{const g=JSON.stringify(u);return!i.has(g)||r.has(g)}),p=new Set(l.map(u=>JSON.stringify(u)));for(const u of o.entries){const g=JSON.stringify(u);!i.has(g)&&!p.has(g)&&l.push(u)}l.sort((u,g)=>u.submittedAt-g.submittedAt),a[n]={touchedAt:Math.max(o.touchedAt,e[n]?.touchedAt??0),entries:l}}return a},uo=()=>{const e=LO();if(pr=e,!Lt)return e;const{base:t,value:s}=Lt;return kd({entryLimit:s.entryLimit===t.entryLimit?e.entryLimit:s.entryLimit,scope:s.scope===t.scope?e.scope:s.scope,globalBuckets:lm(e.globalBuckets,t.globalBuckets,s.globalBuckets),sessionBuckets:lm(e.sessionBuckets,t.sessionBuckets,s.sessionBuckets)})},$k=(e,t)=>e.slice(Math.max(0,e.length-t)),dm=(e,t,s)=>{const a=Object.entries(e).map(([n,o])=>[n,{touchedAt:o.touchedAt,entries:$k(o.entries,s)}]).sort((n,o)=>o[1].touchedAt-n[1].touchedAt).slice(0,t);return Object.fromEntries(a)},kd=(e,t=e.entryLimit)=>({entryLimit:e.entryLimit,scope:e.scope,globalBuckets:dm(e.globalBuckets,jO,t),sessionBuckets:dm(e.sessionBuckets,OO,t)}),ur=e=>({version:1,entryLimit:e.entryLimit,scope:e.scope,global:e.globalBuckets,session:e.sessionBuckets}),pm=e=>e instanceof DOMException?e.name==="QuotaExceededError":e instanceof Error&&/quota/i.test(e.message),go=e=>{const t=kd(e),s=JSON.stringify(ur(t));Lt={base:pr,value:t};const a=$p();if(!a)return hs=s,t;try{return a.setItem(sn,s),Lt=null,hs=s,t}catch(i){if(!(i instanceof Error)||!pm(i))return hs=s,t}try{a.removeItem(sn)}catch{}for(const i of DO){const r=kd(t,i),l=JSON.stringify(ur(r));try{return a.setItem(sn,l),Lt=null,hs=l,r}catch(p){if(!(p instanceof Error)||!pm(p))return Lt={base:pr,value:r},hs=l,r}}const n=To(t.scope,t.entryLimit),o=JSON.stringify(ur(n));try{a.setItem(sn,o),Lt=null}catch{Lt={base:pr,value:n}}return hs=o,n},qO=(e,t,s)=>{const a=e.trim(),n=je(t),o=s.trim();return!a||!n||!o?null:{runtimeKey:a,directory:n,sessionId:o}},Qk=e=>e.source==="vscode"&&e.vscodeSource==="file"?je(e.vscodePath??null):e.dataUrl.trim()||null,VO=e=>!(!e||e.startsWith("data:")||(e.startsWith("http://")||e.startsWith("https://"))&&e.includes("?")),wd=e=>{const t=Qk(e),s=t===null?"none":t.startsWith("data:")?"data":t.slice(0,512);return[e.source,e.filename,e.mimeType,String(e.size),s].join("|")},UO=e=>{const t=Qk(e);if(!t)return null;const s=e.agentPath&&e.serverPath===e.agentPath?e.agentPath:void 0;return!s&&!VO(t)?null:e.source==="vscode"&&e.vscodeSource==="file"?{key:wd(e),source:"vscode-file",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}:{key:wd(e),source:"file-url",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t,path:s}},WO=(e,t)=>({text:e,attachmentKeys:t.map(wd),restorableAttachments:t.map(UO).filter(s=>s!==null)}),HO=(e,t)=>e.length===t.length&&e.every((s,a)=>{const n=t[a];return n!==void 0&&s.key===n.key&&s.source===n.source&&s.filename===n.filename&&s.mimeType===n.mimeType&&s.size===n.size&&s.reference===n.reference&&s.path===n.path}),GO=(e,t)=>e!==void 0&&e.text===t.text&&e.attachmentKeys.length===t.attachmentKeys.length&&e.attachmentKeys.every((s,a)=>s===t.attachmentKeys[a])&&HO(e.restorableAttachments,t.restorableAttachments),um=(e,t,s,a)=>{const n=e?[...e.entries]:[];for(const o of t){const i=n.at(-1);GO(i,o)||n.push({text:o.text,attachmentKeys:[...o.attachmentKeys],restorableAttachments:o.restorableAttachments.map(r=>({...r})),submittedAt:Zk()})}return{touchedAt:s,entries:$k(n,a)}},_O=go(uo()),mo=Rt(e=>({..._O,applyEntryLimit:t=>{Zp(t)&&e(s=>{const a=uo();if(a.entryLimit===t)return{...s,...a};const n=go({entryLimit:t,scope:a.scope,globalBuckets:a.globalBuckets,sessionBuckets:a.sessionBuckets});return{...s,...n}})},applyScope:t=>{Kk(t)&&e(s=>{const a=uo();if(a.scope===t)return{...s,...a};const n=go({entryLimit:a.entryLimit,scope:t,globalBuckets:a.globalBuckets,sessionBuckets:a.sessionBuckets});return{...s,...n}})},appendSubmissions:(t,s)=>{s.length!==0&&e(a=>{const n=uo(),o=Zk(),i=Jk(t.runtimeKey),r=bd(t.runtimeKey,t.directory,t.sessionId),l=go({entryLimit:n.entryLimit,scope:n.scope,globalBuckets:{...n.globalBuckets,[i]:um(n.globalBuckets[i],s,o,n.entryLimit)},sessionBuckets:{...n.sessionBuckets,[r]:um(n.sessionBuckets[r],s,o,n.entryLimit)}});return{...a,...l}})},clearSession:t=>{e(s=>{const a=uo(),n=bd(t.runtimeKey,t.directory,t.sessionId);if(!(n in a.sessionBuckets))return{...s,...a};const o={...a.sessionBuckets};delete o[n];const i=go({entryLimit:a.entryLimit,scope:a.scope,globalBuckets:a.globalBuckets,sessionBuckets:o});return{...s,...i}})}})),kJ=(e,t)=>t?e.scope==="session"?e.sessionBuckets[bd(t.runtimeKey,t.directory,t.sessionId)]?.entries??cl:e.globalBuckets[Jk(t.runtimeKey)]?.entries??cl:cl,KO="openchamber.sdk",ZO=1,JO=[1],$O=/^(>=)?\d+\.\d+\.\d+$/,QO=1e3,YO=6e4,XO=16,eD=2,tD=6,sD=120,aD=2,nD=4,oD=200,iD=300,Yk=/^[a-z0-9][a-z0-9-]{0,39}$/,aa=/^[a-z][a-z0-9-]*$/,rD=["top","bottom","left","right"],wJ="top",yJ=40,cD=24,lD=480,dD=60,Xk=24,ew=480,pD=120,uD=8,gD=40,mD=8,hD=80,fD=/^[a-z][a-z0-9-]{0,23}$/,bD=256,kD=16,wD=128,yD=/^[A-Za-z0-9_.:-]+\*?$/,yd=40,Mr=200,vJ=200,vD=32,CD=16,SD=64,PD=8,xD=16,TD=64,CJ=2048,AD=["auto","text","json","markdown","code","table","card"],tw=["neutral","info","success","warning","error"],SJ=["input","output","metadata"],Br=e=>new RegExp(`\\{(${e.join("|")})((?:\\.[A-Za-z0-9_-]+)*)\\}`,"g"),vd=["input","output","metadata","settings"],zD=e=>{const t=new Set;for(const s of e??[])for(const a of(s.card?.link?.url??"").matchAll(Br(["settings"])))a[2]&&t.add(a[2].slice(1));return[...t]},RD=e=>[!!e.oauth,!!e.token,!!e.host].filter(Boolean).length!==1?null:e.host?"host":e.oauth?"oauth":"token",gm=["browser","source-control","notifications","tracker","quota","opencode"],mm=28,hm=28,fm=28,ID=16,jD=/^[a-z0-9][a-z0-9._-]{0,63}$/,sw=e=>jD.test(e),bm=28,PJ=e=>`ext-${e}`,aw=8,OD=256,Qp=["{id}","{segment}","{segments+}"],DD=/^[A-Za-z0-9._~-]+$/,ND=new Set(Qp),FD=/^([A-Za-z0-9_.-]{1,64})=\{id\}$/,Yp=e=>{if(!e.startsWith("/")||e.length>OD)return!1;const t=e.indexOf("?"),s=t===-1?e:e.slice(0,t),a=t===-1?null:e.slice(t+1),n=s==="/"?[]:s.slice(1).split("/");if(n.some(i=>i==="."||i==="..")||n.some(i=>!ND.has(i)&&!DD.test(i)))return!1;const o=i=>n.filter(r=>r===i).length;return o("{segments+}")>1?!1:a===null?o("{id}")===1:FD.test(a)&&o("{id}")===0},ll=["open","all"],ED=16,nw=["key-number","number","short-code"],MD=4,BD=8,LD=256,ow=["{owner}","{namespace+}","{repo}","{number}"],xJ=(e,t)=>!!e?.provides?.includes(t),TJ=["prompt","sessions","files","model","shells","conversation","service","network","filesystem","origins","transcript","sessionControl","sessionAnswers","instructions","skills","opencodePlugin","opencode","links","wake","marks"],qD=["prompt","sessions","files","model","shells"],VD=8,UD=16,iw=256,WD=e=>e.length===0||e.length>iw||e.includes("\0")||e.includes("\\")||!e.startsWith("/")&&!e.startsWith("~/")?!1:!e.split("/").slice(1).some(s=>s===""||s===".."),HD=40,GD=8,_D=/^[A-Z][A-Z0-9_]{0,31}$/,KD=["open","attach"],ZD=e=>Yp(e)&&!e.includes("{segment}")&&!e.includes("{segments+}"),AJ=(e,t,s)=>`${e}${t.replace("{id}",encodeURIComponent(s))}`,JD=/^[A-Z][A-Za-z0-9]{1,31}$/,$D=/^[a-z][A-Za-z0-9]{0,31}$/,QD=4,YD=8,XD=120,zJ=120,eN=960,qi=e=>!!e.panel.entry,RJ=e=>e.requested.every(t=>e.granted.includes(t)),IJ=(e,t)=>e.granted.includes(t),tN=e=>e!==void 0&&e!==!0&&e!==!1&&e!=="panel"&&e!=="dialog",jJ=e=>e===!0||e==="panel"?"panel":e==="dialog"?"dialog":tN(e)?e.mode:null,OJ=e=>Number.isFinite(e)?Math.min(ew,Math.max(Xk,Math.round(e))):pD,xt=e=>e.includes("\0")||e.includes("\\")||e.startsWith("/")||e.includes("://")||e.split("/").some(s=>s===""||s==="."||s==="..")?!1:/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(e),sN=e=>xt(e)&&e.toLowerCase().endsWith(".svg"),aN=e=>xt(e)&&/\.(?:svg|png)$/i.test(e),rw=["sent","no-model","skipped","failed"],nN=2e3,oN=["started","completed","failure"],iN=["file","directory","other"],cw=["file","directory","other","missing"],DJ={connected:!1,account:""},rN=["phone","tablet","desktop"],cN=["coarse","fine"],NJ=e=>e!==null&&e.kind==="link",FJ=e=>e!==null&&(e.kind===void 0||e.kind==="issue"||e.kind==="pull"),lw=/^[0-9a-f]{7,64}$/i,EJ=e=>lw.test(e),lN=500,km=32e3,Cd=16e3,Xp=128,dw=200,rc=2e3,pw=16e3,uw=80,Sd=200,gw=16e3,dN=200,pN=200,uN=80,gN=2e3,Pd=2e3,wm=64e3,mN=8e6,MJ=2e4,mw=1024,hw=2e6,hN=2e3,fN=64e3,bN=8e3,kN=4e3,wN=256e3,BJ=60*6e4,LJ=8,eu=2e5,yN=2e6,vN=999,CN=1e4,dl=500,fw=["HOST_UNAVAILABLE","HOST_TIMEOUT","HOST_REJECTED","DISCONNECTED","DISABLED","BAD_PATH","NO_INTEGRATION","NO_SERVICE","SERVICE_FAILED","REQUEST_FAILED","RESPONSE_TOO_LARGE","NO_SESSION","SESSION_BUSY","NOT_GRANTED","NO_DIRECTORY","NOT_FOUND","FILE_TOO_LARGE","DENIED","NO_MODEL","MODEL_FAILED","UNSUPPORTED"],bw=["stopped","starting","ready","failed"],SN=new Set(fw),PN=e=>SN.has(e),xN=e=>e&&PN(e)?e:"HOST_REJECTED",xd=e=>e===void 0?!1:e===null||e===!0||e===!1||String(e)===e?!0:Number(e)===e?Number.isFinite(e):Array.isArray(e)?e.every(xd):Object(e)===e?Object.values(e).every(xd):!1,TN=e=>xd(e)&&JSON.stringify(e).length<=gw,ym=e=>e?.trim().slice(0,Sd)??"",AN=e=>{const t=e.id.trim().slice(0,Xp),s=e.title.trim().slice(0,dw),a=e.url.trim().slice(0,rc),n=e.text?.trim().slice(0,pw),o=e.author?.trim().slice(0,uw),i=e.kind==="pull"?"pull":"issue",r={providerId:e.providerId.trim(),id:t,title:s||t,url:a,kind:i};if(n&&(r.text=n),o&&(r.author=o),i==="pull"){const l=ym(e.branches?.head),p=ym(e.branches?.base);l&&p&&(r.branches={head:l,base:p})}return TN(e.data)&&(r.data=e.data),r},qJ=e=>{const t=AN(e);return e.projectId&&(t.projectId=e.projectId),e.navigation&&(t.navigation=e.navigation),e.worktree&&(t.worktree=e.worktree),t},VJ=e=>{const t={text:e.text.trim().slice(0,Cd)};return e.send&&(t.send=!0),t},UJ=e=>e.startsWith("/")||e==="~"||e.startsWith("~/")?"filesystem":"project",zN=e=>e.length>0&&e.length<=mw&&!e.includes("\0")&&!e.includes("\\"),RN=/^[a-z][a-z0-9-]*$/,IN=/^[a-z][a-z0-9-]*$/,Td=e=>!e.startsWith("/")||e.includes("\0")||e.includes("\\")||e.includes("://")||e.length>Pd?!1:!e.split("/").some(s=>s==="."||s==="..");new Set(bw);new Set(cw);const WJ=e=>!!(e&&"text"in e&&String(e.text)===e.text&&!("status"in e)),Ad=["turn-finished","turn-failed","permission-asked","question-asked","turn-started","session-created","session-archived","session-deleted"],jN=2e3;new Set(Ad);const kw=64e3,ON=4096,DN=64,NN=200,FN=200,EN=2048,MN=8,BN=64,LN=64,qN=e=>e.length<=BN&&/^[A-Za-z0-9*/,\-?]+(?: +[A-Za-z0-9*/,\-?]+){4}$/.test(e),vm=120,VN=256,UN=16e3,WN=2e3,HN=8,GN=/^[a-z][a-z0-9-]{0,31}$/,_N=40,KN=200,Cm=8,ZN=/^[a-zA-Z][a-zA-Z0-9_]{0,31}$/,JN=200,$N=["string","number","boolean"],QN=1e4,YN=36e5,XN=4096,eF=2e3,tF=80,sF=2e3,aF=8,nF=60,oF=16,iF=128,ww=2e7,zd=256,yw=e=>e.length>0&&e.length<=iF&&!/[/\\\0]/.test(e)&&/[^*?]/.test(e),Sm=new Map,rF=e=>{const t=Sm.get(e);if(t)return t;const s=e.split("").map(n=>n==="*"?".*":n==="?"?".":n.replace(/[\\^$.|+()[\]{}]/g,"\\$&")).join(""),a=new RegExp(`^${s}$`,"is");return Sm.set(e,a),a},HJ=(e,t)=>yw(t)&&rF(t).test(e),tu=e=>aa.test(e)||sN(e),Jo=e=>{try{const t=new URL(e);return t.protocol==="https:"&&t.username===""&&t.password===""}catch{return!1}},cF=/^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/,vw=e=>Mn(e)?cF.test(new URL(e).hostname):!1,Mn=e=>{try{const t=new URL(e);return t.protocol==="https:"&&t.username===""&&t.password===""&&t.pathname==="/"&&t.search===""&&t.hash===""&&e===t.origin}catch{return!1}},di=e=>!e.startsWith("/")||e.includes("\0")||e.includes("\\")||e.includes("://")?!1:!e.split("/").some(s=>s==="."||s===".."),Cw=/^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)*$/,Sw=S(["panel","dialog"]),lF=d({mode:Sw,entry:c().trim().refine(xt).optional()}).refine(e=>e.mode==="dialog"||e.entry===void 0,{path:["entry"]}),dF=M([y(),Sw,lF]),pF=d({id:c().trim().regex(aa),name:c().trim().min(1),icon:c().trim().refine(tu),entry:c().trim().refine(xt).optional(),dock:S(rD).optional(),size:w().int().min(cD).max(lD).optional(),mobile:m(!0).optional()}),uF=d({id:c().trim().regex(aa),label:c().trim().min(1),secret:m(!0).optional()}),gF=d({authorizeUrl:c().trim().refine(Jo),tokenUrl:c().trim().refine(Jo),apiOrigin:c().trim().refine(Mn),scopes:C(c().trim().min(1)).optional(),account:d({path:c().trim().refine(di),name:c().trim().regex(Cw)}).optional()}),mF=d({apiOrigin:c().trim().refine(Mn),account:d({path:c().trim().refine(di),name:c().trim().regex(Cw)}).optional(),scheme:S(["raw","bearer","basic"]).optional(),usernameLabel:c().trim().min(1).max(64).optional()}),hF=d({provider:S(["linear"])}),fF=d({name:c().trim().min(1),description:c().trim().min(1),oauth:gF.optional(),token:mF.optional(),host:hF.optional(),settings:C(uF).optional()}).refine(e=>RD(e)!==null,{path:["oauth"]}),Pm=["linux","darwin","win32"],Ao=c().trim().min(1).max(512),bF=d({linux:C(Ao).max(16).optional(),darwin:C(Ao).max(16).optional(),win32:C(Ao).max(16).optional()}).strict(),kF=d({id:c().trim().regex(aa).max(64),path:Ao.optional(),candidates:bF.optional()}).strict().refine(e=>!!e.path||!!e.candidates,{message:"socket binding needs path or candidates"}),wF=e=>{const t={};if(e.candidates)for(const s of Pm){const a=e.candidates[s];a&&a.length>0&&(t[s]=[...a])}else if(e.path)for(const s of Pm)t[s]=[e.path];return{id:e.id,candidatesByPlatform:t}},yF=M([Ao.transform(e=>({id:e,candidatesByPlatform:{linux:[e],darwin:[e],win32:[e]}})),kF.transform(wF)]),vF=d({sockets:C(yF).max(32).optional(),exec:C(c().trim().min(1).max(128)).max(32).optional()}).strict().transform(e=>{const t={};return e.sockets&&e.sockets.length>0&&(t.sockets=e.sockets),e.exec&&e.exec.length>0&&(t.exec=[...e.exec]),t}),CF=d({entry:c().trim().refine(xt),runtime:m("host"),permissions:vF.optional(),provides:C(S(gm)).min(1).max(gm.length).refine(e=>new Set(e).size===e.length,{message:"provides entries must be unique"}).optional(),surface:m(!0).optional(),keepRunning:m(!0).optional(),schedule:C(d({id:c().trim().regex(aa).max(64),cron:c().trim().refine(qN),timezone:c().trim().min(1).max(LN).optional()}).strict()).min(1).max(MN).refine(e=>Bn(e,t=>t.id),{message:"schedule ids must be unique"}).optional()}),SF=/^[MmLlHhVvCcSsQqTtAaZz0-9eE.,\s+-]+$/,PF=/^[A-Za-z0-9._~-]+$/,xF=new Set(ow),TF=(e,t)=>{if(!e.startsWith("/")||e.length>LD)return!1;const s=e.slice(1).split("/");if(s.some(i=>i==="."||i==="..")||s.some(i=>!xF.has(i)&&!PF.test(i)))return!1;const a=i=>s.filter(r=>r===i).length,n=t==="owner/name"?"{owner}":"{namespace+}",o=t==="owner/name"?"{namespace+}":"{owner}";return a("{repo}")===1&&a("{number}")===1&&a(n)===1&&a(o)===0},AF=/^[A-Za-z0-9._-]+$/,zF=e=>e.length>0&&e.split("/").every(t=>AF.test(t)&&t!=="."&&t!==".."),xm=c().min(1).max(4).regex(/^\S+$/),Pn=c().trim().min(1).max(64),RF=d({projects:y().default(!1),issues:y().default(!1),changeRequests:y().default(!1),draftChangeRequests:y().default(!1),draftConversion:y().optional(),merge:M([m(!1),d({methods:C(S(["merge","squash","rebase","submit"])).min(1).max(3).refine(e=>new Set(e).size===e.length,{message:"merge methods must be unique"}).refine(e=>!e.includes("submit")||e.length===1,{message:'"submit" is the only merge method when present'})}).strict()]).default(!1),ci:y().default(!1),comments:y().default(!1),reviews:y().default(!1),state:y().default(!1),labels:y().default(!1),reviewers:y().default(!1),changeRequestPatch:y().default(!1),liveSummaries:y().default(!1),reviewModel:S(["verdict","votes"]).optional(),revisions:y().optional()}).strict(),IF=/^[A-Za-z0-9._-]{1,64}$/,Tm=C(c().trim().min(1)).max(BD),Rd=d({kind:m("service"),hint:c().min(1).max(2e3)}),jF=d({wire:m(1),label:Pn,terminology:d({changeRequest:S(["pullRequest","mergeRequest","change"]),ci:S(["checks","pipeline"])}).strict(),referencePrefix:d({changeRequest:xm,issue:xm}).strict(),repositoryPath:S(["owner/name","namespace/name"]),instances:d({defaultInstances:C(c().trim().refine(Mn,{message:"must be an https origin with no path, like https://git.example.com"})).max(MD).refine(e=>new Set(e).size===e.length,{message:"default instances must be unique"}),custom:y(),allowLoopbackHttp:y(),allowPort:y(),placeholder:c().trim().max(256)}).strict().refine(e=>e.custom||e.defaultInstances.length>0,{message:"without custom instances, defaultInstances names at least one"}),capabilities:RF,login:Rd.extend({hint:c().trim().pipe(Rd.shape.hint)}).strict().optional(),token:d({header:S(["authorization","private-token"]),scheme:S(["bearer","token","basic","none"]),username:y().optional(),scopes:C(c().trim().min(1).max(64)).max(32),createPath:c().trim().max(256).refine(di,{message:'must be a path on the instance starting with "/", with no "." or ".." segment'}).optional()}).strict().refine(e=>e.header==="private-token"==(e.scheme==="none"),{message:"private-token takes the bare token; authorization takes a bearer, token or basic scheme"}).refine(e=>e.scheme==="basic"==(e.username===!0),{message:"the basic scheme needs username: true, and username is only for the basic scheme"}).optional(),transport:d({httpsUsername:M([d({kind:m("login")}).strict(),d({kind:m("fixed"),value:c().regex(IF)}).strict()]),appendDotGitToHttpsClone:y()}).strict(),limits:d({commentMaxLength:w().int().min(1).max(1e6),reviewerId:S(["numeric","login"]),labelsMax:w().int().min(0).max(100),reviewersMax:w().int().min(0).max(50)}).strict(),trackedItems:d({batchLimit:w().int().min(1).max(50)}).strict(),presentation:d({abbreviation:c().trim().min(1).max(8),promptNoun:Pn,sharedNumberSpace:y(),iconPath:c().max(8192).regex(SF).optional(),urls:d({changeRequest:Tm,issue:Tm}).strict(),features:d({authorCanReview:y().default(!1),issueCloseReason:y().default(!1),submitRequirements:y().optional()}).strict(),changeRequestTemplates:C(c().trim().max(256).refine(zF,{message:'must be a file path inside the repository, like .gitea/pull_request_template.md, with no "." or ".." segment'})).max(8)}).strict()}).strict().superRefine((e,t)=>{!e.login&&!e.token&&t.addIssue({code:"custom",path:["login"],message:"at least login or token is required"});for(const a of["changeRequest","issue"])e.presentation.urls[a].forEach((n,o)=>{TF(n,e.repositoryPath)||t.addIssue({code:"custom",path:["presentation","urls",a,o],message:`templates start with "/" and use literal segments and ${ow.join(", ")}: {repo} and {number} once, and ${e.repositoryPath==="owner/name"?"{owner}":"{namespace+}"} once for ${e.repositoryPath} paths.`})});const s=new Set(e.presentation.urls.changeRequest);e.presentation.urls.issue.forEach((a,n)=>{s.has(a)&&t.addIssue({code:"custom",path:["presentation","urls","issue",n],message:"is also a changeRequest template; a link names either a change request or an issue."})})}),Pw=d({header:S(["authorization","private-token"]),scheme:S(["bearer","token","basic","none"]),username:y().optional(),scopes:C(c().trim().min(1).max(64)).max(32).optional(),createPath:c().trim().max(256).refine(di,{message:'must be a path on the instance starting with "/", with no "." or ".." segment'}).optional()}).strict().refine(e=>e.header==="private-token"==(e.scheme==="none"),{message:"private-token takes the bare token; authorization takes a bearer, token or basic scheme"}).refine(e=>e.scheme==="basic"==(e.username===!0),{message:"the basic scheme needs username: true, and username is only for the basic scheme"}),OF=d({label:Pn,instances:M([d({kind:m("fixed"),origin:c().trim().refine(Mn,{message:"must be an https origin with no path, like https://slack.com"})}).strict(),d({kind:m("user"),label:Pn,placeholder:c().trim().max(256).optional()}).strict()]),token:Pw}).strict(),Bn=(e,t)=>new Set(e.map(t)).size===e.length,DF=/^[a-z][a-zA-Z0-9-]{0,31}$/,NF=Pw,Am=c().trim().min(1).max(2048).refine(e=>Jo(e)||di(e),{message:'must be an https URL, or a path on the instance starting with "/"'}),FF=d({wire:m(1),label:Pn,instances:M([d({kind:m("fixed"),origin:c().trim().refine(Mn,{message:"must be an https origin with no path, like https://tracker.example.com"})}).strict(),d({kind:m("user"),label:Pn,placeholder:c().trim().max(256).optional()}).strict()]),auth:d({token:NF.optional(),oauth:d({authorizeUrl:Am,tokenUrl:Am,scopes:C(c().trim().min(1).max(64)).max(32).optional()}).strict().optional()}).strict().refine(e=>e.token!==void 0||e.oauth!==void 0,{message:"declare token, oauth or both"}),capabilities:d({multipleAccounts:y().default(!1),stateUpdate:y().default(!1),children:y().default(!1),labels:y().default(!1),priority:y().default(!1),filters:d({people:y().default(!1),priority:y().default(!1)}).strict().default({people:!1,priority:!1}),projectMapping:y().default(!1),sessionComments:y().default(!1)}).strict(),stateFilters:C(c().trim().regex(DF)).min(ll.length).max(ED).refine(e=>new Set(e).size===e.length,{message:"state filters must be unique"}).refine(e=>ll.every((t,s)=>e[s]===t),{message:`state filters start with ${ll.map(e=>`"${e}"`).join(", ")}`}),identifier:S(nw),urls:d({item:C(c().trim().min(1)).min(1).max(aw).refine(e=>new Set(e).size===e.length,{message:"link templates must be unique"})}).strict()}).strict().superRefine((e,t)=>{e.urls.item.forEach((s,a)=>{Yp(s)||t.addIssue({code:"custom",path:["urls","item",a],message:`templates start with "/" and use literal segments and ${Qp.join(", ")}, with {id} once, in the path or as "?name={id}".`})})}),EF=d({providers:C(c().trim().refine(sw,{message:'must be an OpenCode provider id, like "openrouter"'})).max(ID).refine(e=>new Set(e).size===e.length,{message:"provider ids must be unique"})}).strict(),MF=d({id:c().trim().regex(aa).max(64),label:c().trim().min(1).max(gD),icon:c().trim().refine(tu).optional(),where:S(["message","session","selection","file","diff"]),mode:S(["open","background"]).optional(),roles:C(S(["user","assistant"])).min(1).max(2).optional(),payload:C(S(["messages"])).max(1).optional(),display:S(["label","icon","both"]).optional()}).refine(e=>e.where==="message"||e.roles===void 0,{path:["roles"]}).refine(e=>e.where==="session"||e.payload===void 0,{path:["payload"]}).refine(e=>e.where==="selection"||e.display===void 0,{path:["display"]}),BF=C(MF).min(1).max(uD).refine(e=>Bn(e,t=>t.id),{message:"action ids must be unique"}),LF=d({name:c().trim().regex(fD),description:c().trim().min(1).max(hD).optional()}),qF=C(LF).min(1).max(mD).refine(e=>Bn(e,t=>t.name),{message:"command names must be unique"}),xw=e=>[...e.matchAll(Br(vd))].map(t=>({text:t[0],root:t[1]??"",path:(t[2]??"").slice(1)})),Vi=c().trim().min(1).max(Mr).superRefine((e,t)=>{const s=xw(e),a=s.find(n=>n.root!=="output");if(a){t.addIssue({code:"custom",message:`a card reads the tool's output only: write {output.path} where it says ${a.text}.`});return}s.length===0&&t.addIssue({code:"custom",message:"needs at least one {output.path} placeholder."})}),VF=c().trim().min(1).max(Mr).superRefine((e,t)=>{const s=xw(e),a=s.find(r=>r.root==="input"||r.root==="metadata");if(a){t.addIssue({code:"custom",message:`a card link reads {output.path} and {settings.<id>} only, and it says ${a.text}.`});return}const n=s.find(r=>r.root==="settings"&&!aa.test(r.path));if(n){t.addIssue({code:"custom",message:`${n.text} must name one contributes.integration.settings field, like {settings.site}.`});return}if(!s.some(r=>r.root==="output")){t.addIssue({code:"custom",message:"needs at least one {output.path} placeholder."});return}if(s.length===1&&s[0]?.text===e)return;if(!Jo(e.replace(Br(vd),"x"))){t.addIssue({code:"custom",message:"an address written around placeholders starts with https://, has no user name or password, and takes no placeholder as its port."});return}const o=e.slice(8).split(/[/?#\\]/,1)[0]??"",i=[...o.matchAll(Br(vd))].find(r=>(o[r.index-1]??".")!=="."||(o[r.index+r[0].length]??".")!==".");i&&t.addIssue({code:"custom",message:`in the host ${i[0]} stands between dots or at either end, like https://{settings.site}/… or https://{output.team}.tracker.example/…; start the path with / before a placeholder.`})}),UF=d({label:Vi.optional(),title:Vi.optional(),status:d({value:Vi,tones:ke(c().min(1).max(TD),S(tw)).refine(e=>Object.keys(e).length<=xD).optional()}).strict().optional(),fields:C(d({label:c().trim().min(1).max(yd),value:Vi}).strict()).min(1).max(PD).optional(),link:d({label:c().trim().min(1).max(yd),url:VF}).strict().optional()}).strict().refine(e=>e.label!==void 0||e.title!==void 0||e.status!==void 0||e.fields!==void 0,{message:"needs label, title, status or fields; a link alone is not a card."}),WF=d({match:c().trim().min(1).max(wD).regex(yD),name:c().trim().min(1).max(yd).optional(),icon:c().trim().refine(tu).optional(),title:c().trim().min(1).max(Mr).optional(),subtitle:c().trim().min(1).max(Mr).optional(),output:S(AD).optional(),language:c().trim().min(1).max(vD).optional(),columns:C(c().trim().min(1).max(SD)).min(1).max(CD).optional(),card:UF.optional()}).refine(e=>e.output==="code"||e.language===void 0,{path:["language"]}).refine(e=>e.output==="table"==(e.columns!==void 0),{path:["columns"]}).refine(e=>e.output==="card"==(e.card!==void 0),{path:["card"],message:'card and output "card" come together: declare both or neither.'}),HF=C(WF).min(1).max(kD),GF=ke(c().refine(sw),c().trim().refine(aN)).refine(e=>{const t=Object.keys(e).length;return t>=1&&t<=bD}),_F=d({id:c().trim().regex(aa),title:c().trim().min(1).max(nF),match:C(c().trim().refine(yw)).min(1).max(oF),entry:c().trim().refine(e=>xt(e)&&e.toLowerCase().endsWith(".html")),content:S(["text","binary"]).optional()}),KF=C(_F).min(1).max(aF).refine(e=>Bn(e,t=>t.id),{message:"file editor ids must be unique"}),ZF=d({name:c().trim().regex(JD),description:c().trim().min(1).max(XD),args:C(c().trim().regex($D)).max(YD).refine(e=>new Set(e).size===e.length,{message:"argument names must be unique"}),entry:c().trim().refine(e=>xt(e)&&e.toLowerCase().endsWith(".html")),height:w().int().min(24).max(eN).optional(),answers:y().optional()}).strict(),JF=/^\d+(?:\.\d+){3}$/,$F=e=>vw(e)&&!JF.test(new URL(e).hostname),QF=d({action:S(KD),identifier:d({keys:C(c().trim().regex(_D)).min(1).max(GD).refine(e=>new Set(e).size===e.length,{message:"keys must be unique"})}).strict().optional(),urls:d({origin:c().trim().refine($F,{message:"must be a public https origin with no path, like https://tasks.example.com"}),identifier:S(nw),item:C(c().trim().min(1)).min(1).max(aw).refine(e=>new Set(e).size===e.length,{message:"link templates must be unique"})}).strict().optional()}).strict().superRefine((e,t)=>{if(!e.identifier&&!e.urls){t.addIssue({code:"custom",path:[],message:"declare identifier, urls or both"});return}if(e.urls?.item.forEach((s,a)=>{Yp(s)||t.addIssue({code:"custom",path:["urls","item",a],message:`templates start with "/" and use literal segments and ${Qp.join(", ")}, with {id} once, in the path or as "?name={id}".`})}),e.action==="attach"&&!e.urls?.item.some(ZD)){t.addIssue({code:"custom",path:["urls"],message:'action "attach" needs urls with at least one template without {segment} or {segments+}, so a chip can name its link.'});return}e.action==="attach"&&e.identifier&&e.urls?.identifier==="number"&&t.addIssue({code:"custom",path:["urls","identifier"],message:'action "attach" with identifier keys needs urls.identifier "key-number" or "short-code": a key like PROJ-12 cannot fill a "number" {id}, so its chip would have no link.'})}),YF=C(ZF).min(1).max(QD).refine(e=>Bn(e,t=>t.name),{message:"block names must be unique"}),XF=d({id:c().regex(GN),title:c().trim().min(1).max(_N),description:c().trim().min(1).max(KN),params:ke(c().regex(ZN),d({type:S($N),description:c().trim().min(1).max(JN).optional(),required:m(!0).optional()}).strict()).refine(e=>Object.keys(e).length<=Cm,{message:`at most ${Cm} params`}).optional(),interval:w().int().min(QN).max(YN).optional()}).strict(),eE=C(XF).min(1).max(HN).refine(e=>Bn(e,t=>t.id),{message:"wait ids must be unique"}),tE=d({panel:pF,background:d({entry:c().trim().refine(e=>xt(e)&&e.toLowerCase().endsWith(".html"))}).optional(),attach:dF.optional(),page:M([m(!0),d({entry:c().trim().refine(xt),title:c().trim().min(1).max(200).optional(),mobile:m(!0).optional()})]).optional(),statusSection:M([m(!0),d({entry:c().trim().refine(e=>xt(e)&&e.toLowerCase().endsWith(".html")).optional(),source:d({path:c().trim().refine(Td),interval:w().int().min(QO).max(YO).optional()}).strict().optional(),title:c().trim().min(1).max(dD).optional(),height:w().int().min(Xk).max(ew).optional(),defaultExpanded:y().optional(),requiresProject:y().optional()}).refine(e=>e.entry!==void 0||e.source!==void 0)]).optional(),capabilities:C(S(qD)).max(8).optional(),integration:fF.optional(),service:CF.optional(),filesystem:C(c().max(iw).refine(WD)).min(1).max(UD).optional(),origins:C(c().trim().refine(vw)).min(1).max(VD).refine(e=>new Set(e).size===e.length,{message:"origins must be unique"}).optional(),actions:BF.optional(),commands:qF.optional(),tools:HF.optional(),providerLogos:GF.optional(),fileEditors:KF.optional(),sourceControl:jF.optional(),sessionEvents:d({events:C(S(Ad)).min(1).max(Ad.length).refine(e=>new Set(e).size===e.length,{message:"event types must be unique"}),content:m(!0).optional()}).strict().optional(),waits:eE.optional(),notifications:OF.optional(),tracker:FF.optional(),quota:EF.optional(),sessionControl:d({content:m(!0).optional(),answers:m(!0).optional()}).strict().optional(),instructions:m(!0).optional(),marks:m(!0).optional(),skills:c().trim().refine(xt).optional(),opencodePlugin:c().trim().refine(xt).optional(),mentions:d({label:c().trim().min(1).max(HD)}).strict().optional(),blocks:YF.optional(),links:QF.optional()}),Tw=e=>!!(e.statusSection&&e.statusSection!==!0&&e.statusSection.source),sE=e=>e.statusSection===!0||!!e.statusSection?.entry,aE=e=>!!(e.page&&e.page!==!0),nE=e=>{const t=[];return e.page!==void 0&&t.push("page"),e.attach!==void 0&&e.attach!==!1&&t.push("attach"),e.capabilities&&e.capabilities.length>0&&t.push("capabilities"),e.integration!==void 0&&t.push("integration"),e.service!==void 0&&!e.service.provides?.length&&!e.service.surface&&!e.service.keepRunning&&!e.service.schedule&&!Tw(e)&&e.sessionEvents===void 0&&e.mentions===void 0&&e.waits===void 0&&t.push("service"),e.filesystem!==void 0&&t.push("filesystem"),e.origins!==void 0&&t.push("origins"),e.actions!==void 0&&t.push("actions"),e.commands!==void 0&&t.push("commands"),t},oE=d({apiVersion:m(JO[0]),engines:d({openchamber:c().trim().regex($O)}).strict().optional(),contributes:tE.superRefine((e,t)=>{const s=new Map((e.integration?.settings??[]).map(p=>[p.id,p]));e.tools?.forEach((p,u)=>{for(const g of zD([p])){const h=s.get(g);h&&!h.secret||t.addIssue({code:"custom",path:["tools",u,"card","link","url"],message:h?`{settings.${g}} names a secret field, and a link reads only a field without "secret".`:`{settings.${g}} names no contributes.integration.settings field.`})}});const a=e.service?.provides?.includes("source-control")===!0;if(a!==(e.sourceControl!==void 0)){t.addIssue({code:"custom",path:["service","provides"],message:'service.provides "source-control" and contributes.sourceControl come together: declare both or neither.'});return}if(a&&e.panel.id.length>mm){t.addIssue({code:"custom",path:["service","provides"],message:`A source-control extension's panel.id is at most ${mm} characters: OpenChamber names its Git host "ext-<panel.id>".`});return}const n=e.service?.provides?.includes("notifications")===!0;if(n!==(e.notifications!==void 0)){t.addIssue({code:"custom",path:["service","provides"],message:'service.provides "notifications" and contributes.notifications come together: declare both or neither.'});return}if(n&&e.panel.id.length>hm){t.addIssue({code:"custom",path:["service","provides"],message:`A notifications extension's panel.id is at most ${hm} characters: OpenChamber names its channel "ext-<panel.id>".`});return}const o=e.service?.provides?.includes("tracker")===!0;if(o!==(e.tracker!==void 0)){t.addIssue({code:"custom",path:["service","provides"],message:'service.provides "tracker" and contributes.tracker come together: declare both or neither.'});return}if(o&&e.panel.id.length>bm){t.addIssue({code:"custom",path:["service","provides"],message:`A tracker extension's panel.id is at most ${bm} characters: OpenChamber names its tracker "ext-<panel.id>".`});return}if(o&&a){t.addIssue({code:"custom",path:["service","provides"],message:'An extension is a Git host ("source-control") or a tracker ("tracker"), never both: the two roles would share the id "ext-<panel.id>".'});return}const i=e.service?.provides?.includes("quota")===!0;if(i!==(e.quota!==void 0)){t.addIssue({code:"custom",path:["service","provides"],message:'service.provides "quota" and contributes.quota come together: declare both or neither.'});return}if(i&&e.panel.id.length>fm){t.addIssue({code:"custom",path:["service","provides"],message:`A quota extension's panel.id is at most ${fm} characters: OpenChamber names its usage provider "ext-<panel.id>".`});return}if((e.panel.dock!==void 0||e.panel.size!==void 0)&&!(e.service?.surface&&qi(e))){t.addIssue({code:"custom",path:["panel","dock"],message:"panel.dock and panel.size place panel.entry beside service.surface; they need both."});return}if(e.statusSection===!0&&!qi(e)){t.addIssue({code:"custom",path:["statusSection"],message:'contributes.statusSection: true reuses panel.entry; without a panel page, name its own { "entry": "<package .html>" }.'});return}if(Tw(e)&&!e.service){t.addIssue({code:"custom",path:["statusSection","source"],message:"contributes.statusSection.source is read from the extension's service; declare contributes.service."});return}if(e.sessionEvents!==void 0&&!e.service){t.addIssue({code:"custom",path:["sessionEvents"],message:"contributes.sessionEvents are posted to the extension's service; declare contributes.service."});return}if(e.links?.action==="open"&&!qi(e)){t.addIssue({code:"custom",path:["links","action"],message:'contributes.links action "open" opens panel.entry with the link; declare panel.entry, or use action "attach".'});return}for(const p of["sessionControl","instructions","marks","mentions","waits"])if(e[p]!==void 0&&!e.service){t.addIssue({code:"custom",path:[p],message:`contributes.${p} is served by the extension's service; declare contributes.service.`});return}if(qi(e))return;if(e.background){const p=[];e.page===!0&&p.push("page: true"),e.attach!==void 0&&e.attach!==!1&&p.push("attach"),e.actions?.some(u=>u.mode!=="background")&&p.push('actions with mode "open"'),p.length>0&&t.addIssue({code:"custom",path:["panel"],message:`${p.join(", ")} needs panel.entry; background-only actions must declare mode "background".`});return}if(sE(e)||e.fileEditors||e.blocks||aE(e)){const p=[];e.page===!0&&p.push("page"),e.attach!==void 0&&e.attach!==!1&&p.push("attach"),e.actions!==void 0&&p.push("actions"),e.commands!==void 0&&p.push("commands"),p.length>0&&t.addIssue({code:"custom",path:["panel"],message:`${p.map(u=>`contributes.${u}`).join(", ")} needs panel.entry or background.entry; a status section, file editor or block only hosts itself.`});return}const l=nE(e);l.length!==0&&t.addIssue({code:"custom",path:["panel"],message:`${l.map(p=>`contributes.${p}`).join(", ")} needs panel.entry or background.entry; an extension without either may only declare tools and provider logos.`})})}),iE=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,rE=c().trim().regex(iE).max(64);d({version:rE.optional(),openchamber:oE});M([d({openchamber:xs()}),d({openchamber:d({}).passthrough()})]);const cE=tr({id:c().optional(),name:c().optional(),icon:c().optional(),contributes:tr({panel:tr({}).optional()}).optional()});tr({openchamber:cE});const lE=128,dE=65536,GJ=2097152,_J=16777216,pE=2e3,ct=c().trim().min(1).max(1024),Ui=S(["loading","ready","error"]),zm=d({directory:ct,name:c(),branch:c(),status:S(["ready","pending","invalid","missing"])}),Rm=X("kind",[d({kind:m("projects")}).strict(),d({kind:m("worktrees"),projectId:ct}).strict(),d({kind:m("sessions"),projectId:ct}).strict()]),Aw=X("kind",[d({kind:m("projects"),state:Ui,projects:C(d({id:ct,name:c(),directory:ct}))}),d({kind:m("worktrees"),projectId:ct,state:Ui,worktrees:C(zm)}),d({kind:m("sessions"),projectId:ct,state:Ui,coverage:C(d({directory:ct,state:Ui})),sessions:C(d({id:ct,title:c(),projectId:ct,directory:ct,agent:c().optional(),parentId:ct.nullable(),createdAt:w(),updatedAt:w(),archivedAt:w().nullable(),worktree:zm.nullable(),activity:S(["unknown","idle","running","retrying","waiting-permission","waiting-question"]),outcome:S(["completed","failed"]).nullable(),items:C(d({id:ct,data:at().optional()})),links:C(d({title:c(),url:c(),kind:S(["issue","change"]),linkedAt:w()})).optional(),inWork:y().optional(),unread:y().optional(),tool:d({name:c(),target:c().nullable()}).nullable().optional(),context:d({tokens:w().nonnegative(),limit:w().positive().nullable()}).nullable().optional()}))})]),uE=M([y(),d({kind:m("existing"),directory:ct}).strict(),d({kind:m("new"),name:c().trim().min(1).max(200).optional(),baseBranch:c().trim().min(1).max(200).optional()}).strict()]),gr=c().min(1).max(lE),gE=X("op",[d({op:m("get"),key:gr,scope:S(["instance","device"]).optional()}).strict(),d({op:m("delete"),key:gr,scope:S(["instance","device"]).optional()}).strict(),d({op:m("set"),key:gr,value:at().refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=dE),scope:S(["instance","device"]).optional()}).strict(),d({op:m("keys"),scope:S(["instance","device"]).optional()}).strict()]),mE=M([d({storage:m(!0),op:m("get"),found:m(!1)}),d({storage:m(!0),op:m("get"),found:m(!0),value:at()}),d({storage:m(!0),op:S(["set","delete"])}),d({storage:m(!0),op:m("keys"),keys:C(gr).max(pE)})]),hE=4,zw=/^[a-z][a-z0-9-]{0,39}$/,Rw=60,Iw=16,cc=80,su=c().regex(zw),au=c().min(1).max(Rw),fE=d({value:c().min(1).max(cc),label:au}).strict(),bE=d({kind:m("button"),id:su,label:au,disabled:y().optional()}).strict(),kE=d({kind:m("select"),id:su,label:au,value:c().min(1).max(cc),options:C(fE).min(1).max(Iw),disabled:y().optional()}).strict().refine(e=>new Set(e.options.map(t=>t.value)).size===e.options.length,{message:"status control option values must be unique",path:["options"]}).refine(e=>e.options.some(t=>t.value===e.value),{message:"status control value must be one of its options",path:["value"]}),jw=C(X("kind",[bE,kE])).max(hE).refine(e=>new Set(e.map(t=>t.id)).size===e.length,{message:"status control ids must be unique"}),wE=d({id:su,value:c().min(1).max(cc).optional()}).strict(),xn=c().regex(zw),ea=c().min(1).max(Rw),nu=c().min(1).max(cc),Ow=c().min(1).max(oD),xa=S(["default","muted","accent","success","warning","error","info"]),Wi=w().finite(),yE=e=>{try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}},vE=d({value:nu,label:ea}).strict(),Dw=(e,t,s)=>d({kind:m(e),id:xn,label:ea,value:nu,options:C(vE).min(t).max(s),disabled:y().optional()}).strict().refine(a=>new Set(a.options.map(n=>n.value)).size===a.options.length,{message:"option values must be unique",path:["options"]}).refine(a=>a.options.some(n=>n.value===a.value),{message:"value must be one of its options",path:["value"]}),CE=d({id:xn,label:ea,tone:xa.optional(),url:c().max(2e3).refine(yE,{message:"chip url must be http(s)"}).optional()}).strict(),SE=M([d({kind:m("bar"),value:Wi.min(0).max(100),tone:xa.optional()}).strict(),d({kind:m("chart"),values:C(Wi.min(0)).max(sD),max:Wi.positive().optional(),tone:xa.optional(),unit:S(["bytes","percent","count"]).optional(),step:Wi.positive().max(3600).optional()}).strict(),d({kind:m("chips"),chips:C(CE).min(1).max(tD)}).strict(),d({kind:m("text"),text:Ow,tone:xa.optional()}).strict(),Dw("segmented",aD,nD)]),PE=M([d({kind:m("button"),id:xn,label:ea,variant:S(["default","outline","destructive"]).optional(),confirm:ea.optional(),disabled:y().optional()}).strict(),d({kind:m("switch"),id:xn,label:ea,checked:y(),disabled:y().optional()}).strict(),Dw("select",1,Iw)]),xE=M([d({kind:m("line"),id:xn,label:ea,icon:c().regex(Yk).optional(),dot:xa.optional(),content:SE.optional(),value:nu.optional(),valueTone:xa.optional(),badge:d({label:ea,tone:xa.optional()}).strict().optional(),tooltip:Ow.optional(),actions:C(PE).max(eD).optional()}).strict(),d({kind:m("note"),id:xn,text:c().min(1).max(iD),tone:S(["muted","info","warning","error"]).optional()}).strict()]),TE=e=>[...(e.controls??[]).map(t=>t.id),...e.rows.flatMap(t=>t.kind==="line"?[...(t.actions??[]).map(s=>s.id),...t.content?.kind==="segmented"?[t.content.id]:[]]:[])],KJ=d({rows:C(xE).max(XO),controls:jw.optional()}).strict().refine(e=>new Set(e.rows.map(t=>t.id)).size===e.rows.length,{message:"row ids must be unique",path:["rows"]}).refine(e=>{const t=TE(e);return new Set(t).size===t.length},{message:"control ids must be unique across the view"}),Im=c().trim().min(1).max(kw),Bs=c().trim().min(1).max(256),Ls=c().trim().min(1).max(256),Id=c().trim().min(1).max(4096),jm=c().trim().min(1).max(WN),AE=d({target:M([d({sessionId:Bs}).strict(),d({directory:Id,branch:Ls.optional()}).strict()]),mark:d({icon:c().regex(Yk),tone:S(tw),text:c().trim().min(1).max(FN),url:c().trim().max(EN).refine(Jo).optional()}).strict().nullable()}).strict();X("method",[d({method:m("sessions.start"),input:d({prompt:Im,projectId:Ls.optional(),directory:Id.optional(),title:Ls.optional(),model:Ls.optional(),variant:Ls.optional(),agent:Ls.optional()}).strict().refine(e=>!(e.projectId&&e.directory),{message:"Give projectId or directory, not both"})}).strict(),d({method:m("sessions.send"),input:d({sessionId:Bs,prompt:Im}).strict()}).strict(),d({method:m("sessions.retry"),input:d({sessionId:Bs}).strict()}).strict(),d({method:m("sessions.status"),input:d({sessionId:Bs}).strict()}).strict(),d({method:m("sessions.lastReply"),input:d({sessionId:Bs}).strict()}).strict(),d({method:m("sessions.stop"),input:d({sessionId:Bs}).strict()}).strict(),d({method:m("sessions.answerPermission"),input:d({sessionId:Bs,requestId:Ls,decision:S(["allow","deny"]),message:jm.optional()}).strict()}).strict(),d({method:m("sessions.answerForm"),input:d({sessionId:Bs,formId:Ls,values:ke(c().min(1).max(256),M([c().max(kw),w(),y(),C(c().max(1e3)).max(100)])).nullable(),message:jm.optional()}).strict()}).strict(),d({method:m("instructions.set"),input:d({directory:Id.nullable(),text:c().max(ON)}).strict()}).strict(),d({method:m("panels.emit"),input:d({topic:c().trim().min(1).max(DN),data:at().optional()}).strict()}).strict(),d({method:m("settings.read"),input:d({}).strict()}).strict(),d({method:m("status.set"),input:d({needsConfiguration:c().trim().min(1).max(NN).nullable()}).strict()}).strict(),d({method:m("marks.set"),input:AE}).strict()]);d({id:c().min(1).max(VN),title:c().trim().min(1).max(vm),subtitle:c().trim().min(1).max(vm).optional(),url:Yv({protocol:/^https?$/}).max(2048).optional()});d({text:c().trim().min(1).max(UN)});const Nw=/^[A-Za-z0-9_-]{1,80}$/,Wa=1e5,zE=160,RE=640,IE=48,jE=480,zo=16e3,OE=32,DE=["left","right","top","bottom"],NE=["escape","outside","anchor","owner","closed","replaced"],FE=M([c().max(zo),w(),y(),xs()]),EE=ke(c().max(zo),ne()),Fw=Kr(e=>{const t=[{value:e,depth:0}];let s=0;for(;t.length>0;){const a=t.pop();if(!a)break;const n=a.value;if(a.depth>=OE)return!1;if(Array.isArray(n)){if(n.length>zo||Object.keys(n).some(o=>!/^(0|[1-9]\d*)$/.test(o)||Number(o)>=n.length))return!1;s+=2+Math.max(0,n.length-1);for(const o of n)t.push({value:o,depth:a.depth+1})}else{const o=FE.safeParse(n);if(o.success)s+=JSON.stringify(o.data).length;else{if(!EE.safeParse(n).success)return!1;const r=Object.getPrototypeOf(n);if(r!==null&&r!==Object.prototype)return!1;const l=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,p])=>p.enumerable);s+=2+Math.max(0,l.length-1);for(const[p,u]of l){if(!("value"in u)||(s+=JSON.stringify(p).length+1,s>zo))return!1;t.push({value:u.value,depth:a.depth+1})}}}if(s>zo)return!1}return!0},"Popover data must be finite JSON within its size and depth limits."),ME=d({id:c().regex(Nw),anchor:d({x:w().finite().min(-Wa).max(Wa),y:w().finite().min(-Wa).max(Wa),width:w().finite().positive().max(Wa),height:w().finite().positive().max(Wa)}).strict(),width:w().int().min(zE).max(RE),height:w().int().min(IE).max(jE),side:S(DE).optional(),focus:y().optional(),data:Fw}).strict(),BE=d({id:c().regex(Nw),reason:S(NE)}).strict(),jd=128,Om=200,LE=65536,qE=["exited","timeout","killed","stopped","unknown"],Ew=Xv(Uint8Array).refine(e=>e.byteLength<=ww),Mw=c().max(ww),L={channel:m(KO),v:m(ZO)},VE=d({background:c().min(1),elevated:c().min(1),foreground:c().min(1),muted:c().min(1),subtle:c().min(1),border:c().min(1),hover:c().min(1),selection:c().min(1),focus:c().min(1),primary:c().min(1),mutedSurface:c().min(1),elevatedForeground:c().min(1),active:c().min(1),selectionForeground:c().min(1),primaryForeground:c().min(1),primaryText:c().min(1),successText:c().min(1),warningText:c().min(1),errorText:c().min(1),infoText:c().min(1),success:c().min(1),warning:c().min(1),error:c().min(1),info:c().min(1),font:c().min(1),fontSize:c().min(1).optional(),mono:c().min(1),radius:c().min(1),syntaxKeyword:c().min(1).optional(),syntaxString:c().min(1).optional(),syntaxNumber:c().min(1).optional(),syntaxFunction:c().min(1).optional(),syntaxType:c().min(1).optional(),syntaxComment:c().min(1).optional(),syntaxVariable:c().min(1).optional(),syntaxOperator:c().min(1).optional()}),Bw=d({id:c().min(1),title:c().min(1),busy:y().optional().default(!1),model:c().min(1).max(pN).optional(),agent:c().min(1).max(uN).optional()}).nullable(),Lw=d({connected:y(),account:c().max(dN)}),qw=ke(c().regex(IN),c().max(gN)),UE=d({status:w().int().min(100).max(599),body:c().max(mN)}),Dm=d({directory:c(),name:c(),branch:c(),status:S(["ready","pending","invalid","missing"])}),WE=M([d({sessionId:c().min(1),sent:S(rw),directory:c().optional(),worktree:Dm.optional(),linked:y().optional()}),d({sessionId:xs(),sent:m("skipped"),directory:c(),worktree:Dm,failure:S(["bootstrap-failed","session-create-failed"])})]),HE=d({sent:S(rw)}),GE=d({status:S(bw)}),_E=d({content:c().max(hw)}),KE=d({written:m(!0)}),ZE=d({entries:C(d({name:c().min(1),kind:S(iN)})).max(hN)}),JE=d({kind:S(cw),size:w().int().min(0),mtime:w().int().min(0)}),Vw=d({text:c().max(wN)}),Od=d({prompt:c().trim().min(1).max(fN),system:c().trim().min(1).max(bN).optional(),maxOutputTokens:w().int().min(1).max(kN).optional()}),$E=X("ok",[d({request:Od,ok:m(!0),result:Vw}),d({request:Od,ok:m(!1),code:S(fw),error:c().min(1)})]),QE=d({output:c(),cursor:w(),skipped:y()}),YE=d({stopped:m(!0)}),XE=M([mE,Aw,QE,YE,WE,UE,HE,GE,_E,KE,ZE,JE,Vw]),ho=d({providerId:c().trim().regex(RN),id:c().trim().min(1).max(Xp),title:c().trim().min(1).max(dw),url:c().trim().min(1).max(rc),text:c().trim().min(1).max(pw).optional(),kind:S(["issue","pull"]).optional(),author:c().trim().min(1).max(uw).optional(),branches:d({head:c().trim().min(1).max(Sd),base:c().trim().min(1).max(Sd)}).optional(),data:at().refine(e=>JSON.stringify(e).length<=gw).optional()}),Uw=S(["user","assistant"]),Ww=d({kind:m("message"),action:c().trim().min(1).max(64),sessionId:c().min(1),sessionTitle:c(),directory:c().nullable(),messageId:c().min(1),role:Uw,text:c().max(eu)}),Hw=d({kind:m("session"),action:c().trim().min(1).max(64),sessionId:c().min(1),sessionTitle:c(),directory:c().nullable(),messages:C(d({id:c().min(1),role:Uw,text:c().max(eu),createdAt:w().int().min(0)})).optional(),truncated:y().optional()}).refine(e=>JSON.stringify(e).length<=yN),Gw=d({kind:m("selection"),action:c().trim().min(1).max(64),sessionId:c().min(1),directory:c().nullable(),messageId:c().min(1),text:c().max(eu)}),_w=d({kind:m("file"),action:c().trim().min(1).max(64),directory:c().nullable(),path:c().min(1),isDirectory:y()}),Kw=d({kind:m("diff"),action:c().trim().min(1).max(64),directory:c().nullable(),path:c().min(1),startLine:w().int().min(0),endLine:w().int().min(0),side:S(["additions","deletions"]).optional()}),eM=d({kind:m("link"),identifier:c().trim().min(1).max(Xp),url:c().trim().min(1).max(rc).optional()}).strict(),Zw=M([Ww,Hw,Gw,_w,Kw,eM,ho]).nullable(),Xn=w().finite().min(0),tM=d({formFactor:S(rN),pointer:S(cN),insets:d({top:Xn,right:Xn,bottom:Xn,left:Xn}),keyboard:Xn}),sM=d({theme:d({mode:S(["light","dark"]),tokens:VE}),locale:c().min(1),directory:c().nullable(),session:Bw,surface:S(["panel","dialog","page","background","status","file","popover","block"]),connection:Lw,settings:qw,item:Zw,block:d({name:c().min(1),args:ke(c(),c()),answered:c().nullable()}).optional(),popover:d({id:c().min(1).max(80),data:Fw}).strict().optional(),features:d({deviceStorage:m(!0).optional(),statusControls:m(!0).optional(),popovers:m(!0).optional(),lateGenerateResults:m(!0).optional()}).optional(),device:tM.optional()}),aM=d({...L,type:m("result"),id:c().min(1),ok:y(),error:c().min(1).optional(),code:c().min(1).optional(),payload:XE.optional()}).transform((e,t)=>e.ok?e.payload?{channel:e.channel,v:e.v,type:"result",id:e.id,ok:!0,payload:e.payload}:{channel:e.channel,v:e.v,type:"result",id:e.id,ok:!0}:e.error?{channel:e.channel,v:e.v,type:"result",id:e.id,ok:!1,error:e.error,code:xN(e.code)}:(t.addIssue({code:"custom",message:"Failed result needs an error string."}),eC)),Jw=d({id:c().min(1).max(jd),sessionID:c().min(1).max(1024),command:c(),startedAt:w().nonnegative(),background:y()}).strict(),nM=Jw.extend({status:S(qE),exit:w().int().optional(),endedAt:w().nonnegative()}).strict(),$w=X("kind",[d({kind:m("session"),sessionId:c().min(1).max(1024)}).strict(),d({kind:m("project"),projectId:c().min(1).max(1024)}).strict(),d({kind:m("global")}).strict()]),oM=d({kind:m("shells"),scope:$w,shells:C(Jw).max(Om),ended:C(nM).max(Om)}).strict();M([d({...L,type:m("workspace"),payload:d({subscriptionId:c().min(1).max(128),snapshot:Aw})}),d({...L,type:m("shells"),payload:d({subscriptionId:c().min(1).max(128),snapshot:oM})}),d({...L,type:m("ready"),payload:sM}),d({...L,type:m("directory"),payload:d({directory:c().nullable()})}),d({...L,type:m("session"),payload:d({session:Bw})}),d({...L,type:m("connection"),payload:d({connection:Lw})}),d({...L,type:m("settings"),payload:d({settings:qw})}),d({...L,type:m("session-lifecycle"),payload:d({sessionId:c().min(1),phase:S(oN)})}),d({...L,type:m("item"),payload:d({item:Zw})}),d({...L,type:m("service-event"),payload:d({topic:c().min(1),data:at()})}),d({...L,type:m("status-control-event"),payload:wE}),d({...L,type:m("popover-closed"),payload:BE}),d({...L,type:m("resolve"),id:c().min(1),payload:d({command:c().min(1),args:c()})}),aM,d({...L,type:m("action"),id:c().min(1),payload:M([Ww,Hw,Gw,_w,Kw])}),d({...L,type:m("file-open"),payload:M([d({path:c().min(1).max(4096),name:c().min(1).max(1024),readOnly:y(),encoding:m("text"),content:Mw}),d({path:c().min(1).max(4096),name:c().min(1).max(1024),readOnly:y(),encoding:m("binary"),bytes:Ew})])}),d({...L,type:m("file-snapshot"),id:c().min(1),payload:d({purpose:S(["save","handoff"])})}),d({...L,type:m("file-saved"),payload:d({version:c().max(zd)})}),d({...L,type:m("generate-late"),payload:$E})]);const Hi=c().min(1).max(mw).refine(zN),ZJ=X("type",[d({...L,type:m("action-result"),id:c().min(1),payload:X("ok",[d({ok:m(!0)}),d({ok:m(!1),error:c().trim().min(1).max(dl)})])}),d({...L,type:m("workspace-read"),id:c().min(1),payload:Rm}),d({...L,type:m("workspace-subscribe"),id:c().min(1),payload:d({subscriptionId:c().min(1).max(128),query:Rm})}),d({...L,type:m("workspace-unsubscribe"),id:c().min(1),payload:d({subscriptionId:c().min(1).max(128)})}),d({...L,type:m("shells-subscribe"),id:c().min(1),payload:d({subscriptionId:c().min(1).max(128),scope:$w}).strict()}),d({...L,type:m("shells-unsubscribe"),id:c().min(1),payload:d({subscriptionId:c().min(1).max(128)}).strict()}),d({...L,type:m("shell-output"),id:c().min(1),payload:d({shellId:c().min(1).max(jd),cursor:w().int().nonnegative().optional(),tailBytes:w().int().positive().max(LE).optional()}).strict()}),d({...L,type:m("shell-stop"),id:c().min(1),payload:d({shellId:c().min(1).max(jd)}).strict()}),d({...L,type:m("storage"),id:c().min(1),payload:gE}),d({...L,type:m("status-controls"),id:c().min(1),payload:d({controls:jw}).strict()}),d({...L,type:m("popover-open"),id:c().min(1),payload:ME}),d({...L,type:m("popover-close"),id:c().min(1),payload:d({id:c().min(1).max(80),reason:S(["closed","escape"]).optional()}).strict()}),d({...L,type:m("popover-anchor"),id:c().min(1),payload:d({id:c().min(1).max(80),active:y()}).strict()}),d({...L,type:m("open-session"),id:c().min(1),payload:d({sessionId:c().min(1).max(1024)})}),d({...L,type:m("hello")}),d({...L,type:m("toast"),id:c().min(1),payload:d({kind:S(["info","success","error"]),message:c().trim().min(1).max(lN),copy:M([y(),d({text:c().min(1).max(km)})]).optional(),dismiss:y().optional(),persistent:y().optional()})}),d({...L,type:m("open-url"),id:c().min(1),payload:d({url:c().trim().min(1).max(rc)})}),d({...L,type:m("block-answer"),id:c().min(1),payload:d({text:c().trim().min(1).max(nN)})}),d({...L,type:m("open-surface"),id:c().min(1),payload:d({surfaceId:c().trim().min(1).max(64)})}),d({...L,type:m("clipboard-write"),id:c().min(1),payload:d({text:c().min(1).max(km)})}),d({...L,type:m("compose"),id:c().min(1),payload:d({text:c().trim().min(1).max(Cd),mode:S(["replace","append"]).optional()})}),d({...L,type:m("attach"),id:c().min(1),payload:ho}),d({...L,type:m("start-session"),id:c().min(1),payload:ho.extend({worktree:uE.optional(),projectId:c().trim().min(1).max(1024).optional(),navigation:S(["preserve","open"]).optional()})}),d({...L,type:m("prompt"),id:c().min(1),payload:d({text:c().trim().min(1).max(Cd),send:y().optional()})}),d({...L,type:m("session-link"),id:c().min(1),payload:ho}),d({...L,type:m("close"),id:c().min(1)}),d({...L,type:m("oauth-start"),id:c().min(1)}),d({...L,type:m("oauth-disconnect"),id:c().min(1)}),d({...L,type:m("request"),id:c().min(1),payload:d({method:S(["GET","POST","PUT","PATCH","DELETE"]),path:c().trim().min(1).max(Pd).refine(Td),query:ke(c().min(1).max(128),c().max(2e3)).optional(),body:c().max(wm).optional()})}),d({...L,type:m("service-request"),id:c().min(1),payload:d({method:S(["GET","POST","PUT","PATCH","DELETE"]),path:c().trim().min(1).max(Pd).refine(Td),query:ke(c().min(1).max(128),c().max(2e3)).optional(),body:c().max(wm).optional()})}),d({...L,type:m("service-status"),id:c().min(1)}),d({...L,type:m("file-read"),id:c().min(1),payload:d({path:Hi})}),d({...L,type:m("file-write"),id:c().min(1),payload:d({path:Hi,content:c().max(hw)})}),d({...L,type:m("file-list"),id:c().min(1),payload:d({path:Hi})}),d({...L,type:m("file-stat"),id:c().min(1),payload:d({path:Hi})}),d({...L,type:m("generate"),id:c().min(1),payload:Od}),d({...L,type:m("badge"),id:c().min(1),payload:d({count:w().int().min(0).max(vN).nullable()})}),d({...L,type:m("open-commit"),id:c().min(1),payload:d({sha:c().regex(lw)})}),d({...L,type:m("resize"),id:c().min(1),payload:d({height:w().int().min(0).max(CN)})}),d({...L,type:m("resolve-result"),id:c().min(1),payload:M([d({item:ho.nullable()}),d({error:c().trim().min(1).max(dl)})])}),d({...L,type:m("file-snapshot-result"),id:c().min(1),payload:M([d({snapshot:M([d({content:Mw,version:c().max(zd)}),d({bytes:Ew,version:c().max(zd)})])}),d({error:c().trim().min(1).max(dl)})])}),d({...L,type:m("file-change"),payload:d({dirty:y(),edited:y()})}),d({...L,type:m("file-save")}),d({...L,type:m("file-unsupported")}),d({...L,type:m("generate-late-listen")})]),Qw=["browser.open","browser.snapshot","browser.click","browser.type","browser.select","browser.scroll","browser.back","browser.forward","browser.inspect","browser.capture","browser.resize","browser.close"];new Set(Qw);const iM=["auth.verify","auth.probe","auth.status","changeRequestStatus","listChangeRequests","changeRequestContext","listIssues","getIssue","issueComments","projectUpstream","projectBranches","listLabels","listReviewerCandidates","readChangeRequestPatch","readChangeRequestFile","liveSummaries","readChangeRequestHead","resolveChangeRequestSource","mutation.resolveTarget","mutation.perform","mutation.reconcile"],rM=8e6,Yw=2e3,Nm=4096,cM=["GET","POST","PUT","PATCH","DELETE"],lM=["accept","content-type","if-none-match","range"],dM=1e6,pM=["auth.verify","auth.probe","notify"],uM=["auth.probe","auth.verify","items.list","items.get","items.updateState","items.liveSummaries","states.list","containers.list","comments.create"],$o=100,gM=50,mM=500,hM=["usage.read"],fM=2e3,Fm=32,Em=64,bM=128,kM=128;M([d({ok:m(!0),data:d({}).passthrough()}),d({ok:m(!1),error:c().min(1).max(2e3)})]);M([d({ok:m(!0)}).strict(),d({ok:m(!1),error:c().min(1).max(jN)}).strict()]);S(Qw);const ee=c().min(1).max(1024),Lr=c().max(1024).optional(),As=w().int().positive().max(Number.MAX_SAFE_INTEGER),wM=c().min(1).max(256),yM=M([As,wM]),vM=w().int().nonnegative().max(Number.MAX_SAFE_INTEGER),ou=c().regex(/^[0-9a-fA-F]{40}$/).transform(e=>e.toLowerCase()),Qo=d({id:ee,owner:ee,name:ee}).strict(),CM=d({message:c().min(1).max(Yw),status:w().int().min(400).max(599).optional(),code:c().regex(/^[A-Z_]{1,64}$/).optional()}).strict();M([d({ok:m(!0),data:at()}).strict(),d({ok:m(!1),error:CM}).strict()]);const Xw=d({id:yM,login:c().min(1).max(256),name:Lr,email:Lr,avatarUrl:c().max(2048).optional()});d({user:Xw});d({supported:y(),version:c().max(128).optional(),message:c().max(Yw).optional()});d({project:Qo,headSha:ou,headBranch:ee,headOwner:ee});d({sourceProject:Qo,targetProject:Qo,classification:S(["same-repository","contributor-fork"]),headSha:ou,headRef:c().regex(/^refs\/heads\/\S+$/).max(1024),endpoint:c().min(1).max(2048)});const SM=d({repositoryId:ee,bindingRevision:vM,primaryRemote:ee,project:Qo,number:As.optional(),head:ee.optional(),base:ee.optional(),headSha:ee.optional()}).strict(),ey=ke(c(),at());d({providerTarget:ey.refine(e=>JSON.stringify(e).length<=Nm,{message:`providerTarget is at most ${Nm} characters of JSON`}),target:SM}).strict();const PM=d({project:Qo.optional(),number:As.optional(),head:ee.optional(),base:ee.optional(),headSha:ee.optional(),state:ee.optional(),merged:y().optional(),outcome:S(["queued","merging"]).optional(),stacked:y().optional(),ready:y().optional(),draft:y().optional(),commented:y().optional(),failureStatus:w().int().min(400).max(599).optional(),failureCode:ee.optional()}).strict();d({state:S(["succeeded","failed","outcome-unknown"]),result:PM.optional()}).strict();const Mm=50,xM=d({owner:ee,repo:ee,number:As,state:S(["open","closed","merged"]),draft:y(),title:c().max(4096),mergeable:y().nullable(),mergeableState:c().max(64).nullable(),checks:d({state:c().max(64)}).passthrough().nullable(),headSha:c().max(128).optional(),base:c().max(1024).optional()}),TM=d({owner:ee,repo:ee,number:As,title:c().max(4096),state:S(["open","completed","not_planned"])});d({summaries:C(xM).max(Mm),issueSummaries:C(TM).max(Mm)});const AM=d({provider:ee,instance:ee}).passthrough(),Bm=d({provider:ee,instance:ee,id:ee,owner:ee,name:ee,url:ee}).passthrough(),zM=50,RM=d({number:As.nullable(),base:ee,layers:C(d({number:As,title:c().max(4096),url:ee,state:S(["open","closed","merged"]),draft:y(),head:ee}).passthrough()).max(zM)}).passthrough(),IM=d({sha:ou,changeId:c().min(1).max(128).nullable(),uploadedAs:As.nullable()}).strict();d({identity:AM,fetchedAt:w().optional(),project:Bm.nullable(),branch:c().min(1).max(1024),changeRequest:d({provider:ee,instance:ee,id:ee,number:As,project:Bm,title:c().max(4096),url:ee,state:S(["open","closed","merged"]),draft:y(),base:ee,head:ee}).passthrough().nullable(),ci:d({summary:d({state:c().max(64)}).passthrough()}).passthrough().nullable().optional(),canMerge:y().optional(),defaultBranch:c().max(1024).nullable().optional(),resolvedRemoteName:c().max(1024).nullable().optional(),localRevision:IM.optional(),stack:RM.nullable().optional()}).strict();M([ey,C(at())]).refine(e=>JSON.stringify(e).length<=rM,{message:"answer is larger than the response cap"});d({user:Xw.nullable()});d({method:S(cM),path:c().min(1).max(2048).regex(/^\/(?!\/)/),query:ke(c().max(256),c().max(2048)).optional(),headers:tC(S(lM),c().max(1024)).optional(),body:c().max(dM).optional()}).strict();S(iM);d({account:d({id:c().min(1).max(256),login:c().min(1).max(256),name:Lr})});d({delivered:m(!0)}).strict();S(pM);const Ia=c().min(1).max(1024),ty=c().max(4096),jM=c().min(1).max(2048).refine(e=>/^https?:\/\//i.test(e)&&URL.canParse(e),{message:"must be an http(s) URL"}),iu=S(["triage","backlog","todo","in-progress","done","canceled"]),OM=S(["none","urgent","high","medium","low"]),sy=d({name:c().max(256).nullable(),avatarUrl:c().max(2048).nullable()}).strict(),ay=d({id:Ia,key:c().max(64).nullable(),name:c().min(1).max(256)}).strict(),DM=d({id:Ia.nullable(),name:c().max(256),category:iu.nullable()}).strict(),ny={id:Ia,identifier:c().min(1).max(128),title:ty,url:jM,state:DM.nullable(),priority:OM.nullable().optional(),labels:C(d({id:Ia,name:c().min(1).max(256),color:c().max(32).nullable()}).strict()).max($o).optional(),assignee:sy.nullable().optional(),container:ay.nullable().optional(),progress:d({total:w().int().nonnegative(),done:w().int().nonnegative(),more:y()}).strict().nullable().optional(),updatedAt:c().max(64).nullable().optional()},oy=d({...ny,parent:xs().optional()}).strict(),iy=d({...ny,parent:oy.nullable().optional()}).strict(),NM=d({id:Ia,body:c().max(65536),createdAt:c().max(64).nullable(),author:sy.nullable()}).strict(),FM=iy.extend({description:c().max(262144).nullable().optional(),comments:C(NM).max($o).optional(),children:C(oy).max($o).optional(),childrenMore:y().optional()}).strict();d({account:d({id:c().min(1).max(256),login:c().min(1).max(256).nullable(),name:Lr,avatarUrl:c().max(2048).optional()}).strict()}).strict();d({items:C(iy).max($o),cursor:c().min(1).max(2048).nullable(),hasMore:y()}).strict();d({item:FM.nullable()}).strict();d({states:C(d({id:Ia,name:c().min(1).max(256),category:iu.nullable(),position:w()}).strict()).max($o*2)}).strict();d({items:C(d({identifier:c().min(1).max(128),title:ty,state:d({name:c().max(256),category:iu}).strict()}).strict()).max(gM)}).strict();d({containers:C(ay).max(mM)}).strict();d({comment:d({id:Ia}).strict().nullable()}).strict();S(uM);const EM=new Set(["__proto__","constructor","prototype"]),ry=c().min(1).max(bM).refine(e=>!EM.has(e),{message:"reserved name"}),cy=c().max(kM),Gi=w().finite().nonnegative(),MM=d({usedPercent:Gi.nullable(),windowSeconds:w().int().positive().max(Number.MAX_SAFE_INTEGER).nullable().optional(),resetAt:w().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable().optional(),valueLabel:cy.nullable().optional(),value:X("kind",[d({kind:m("requests"),count:Gi}).strict(),d({kind:m("spend"),spent:Gi,limit:w().finite().positive().nullable()}).strict()]).optional(),creditsUsed:Gi.optional()}).strict(),Lm=ke(ry,MM).refine(e=>Object.keys(e).length<=Fm,{message:`at most ${Fm} windows`}),BM=d({windows:Lm,models:ke(ry,d({windows:Lm}).strict()).refine(e=>Object.keys(e).length<=Em,{message:`at most ${Em} models`}).optional()}).strict();d({ok:y(),configured:y(),error:c().min(1).max(fM).optional(),planLabel:cy.nullable().optional(),usage:BM.nullable()}).strict();S(hM);const ly=Kr(e=>e!==void 0&&JSON.stringify(e).length<=XN);M([d({ok:m(!0),state:ly.optional(),label:c().trim().min(1).max(tF).optional()}).strict(),d({ok:m(!1),error:c().min(1).max(sF)}).strict()]);d({results:C(at())}).strict();M([d({id:c().min(1),fired:m(!1),state:ly.optional()}).strict(),d({id:c().min(1),fired:m(!0),summary:c().trim().min(1).max(eF)}).strict()]);const LM=["image/jpeg","image/png"],qM=256,ru=64e3,VM=200,UM=16384,dy=["none","agent","user"];new Set(dy);const pl=d({alt:y(),ctrl:y(),meta:y(),shift:y()}),Ha=w().finite(),WM=X("type",[d({type:m("pointer"),action:S(["down","up","move"]),x:Ha,y:Ha,button:w().int().min(-1).max(4),buttons:w().int().min(0).max(31),modifiers:pl}),d({type:m("wheel"),x:Ha,y:Ha,deltaX:Ha,deltaY:Ha,modifiers:pl}),d({type:m("key"),action:S(["down","up"]),key:c().min(1).max(64),code:c().max(64),keyCode:w().int().min(0).max(255).optional(),modifiers:pl}),d({type:m("text"),text:c().min(1).max(ru)})]),Qs=w().int().min(1).max(UM);X("type",[d({type:m("ack"),seq:w().int().min(0)}),d({type:m("input"),events:C(WM).min(1).max(qM)}),d({type:m("release")}),d({type:m("resize"),width:Qs,height:Qs}),d({type:m("clipboard-read"),id:c().min(1).max(64)})]);const HM=S(dy),JJ=X("type",[d({type:m("hello"),viewerId:c().min(1)}),d({type:m("frame"),seq:w().int().min(0),width:Qs,height:Qs,mime:S(LM),bytes:w().int().min(1),title:c().max(VM).optional(),agentActive:y()}),d({type:m("control"),controller:HM,mine:y()}),d({type:m("resized"),width:Qs,height:Qs}),d({type:m("clipboard"),id:c().min(1).max(64),text:c().max(ru)}),d({type:m("error"),code:c().min(1).max(64),message:c().min(1).max(500)}),d({type:m("ended"),reason:S(["service-stopped","extension-unavailable","host-shutdown"])})]);d({width:Qs,height:Qs});d({text:c().max(ru)});const py=["guest","link","external","repository"],GM=new Set([...py,"linear"]),_s=c().regex(/^[a-z][a-z0-9-]{0,31}$/).refine(e=>!GM.has(e),{message:"Reserved provider id"}),_M=S(["pullRequest","mergeRequest","change"]),KM=S(["checks","pipeline"]),ZM=S(["device","pat","cli"]),JM=M([S(["instance-url","personal-access-token","username","http-password"]),c().transform(()=>"unknown")]),$M=c().max(8192).regex(/^[MmLlHhVvCcSsQqTtAaZz0-9eE.,\s+-]+$/),qm=c().min(1).max(64),eo=C(c().min(1).max(256)).max(8),QM=d({id:_s,label:qm,order:w().int(),terminology:d({changeRequest:_M.catch("pullRequest"),changeRequestPrefix:c().min(1).max(4),issuePrefix:c().min(1).max(4),sharedNumberSpace:y(),abbreviation:c().min(1).max(8),promptNoun:qm,ci:KM.catch("checks")}),icon:d({sprite:c().max(64).optional(),filledSprite:c().max(64).optional(),path:$M.optional()}),repository:d({nestedNamespaces:y(),pathStyle:m("path").optional().catch(void 0)}),instances:d({format:S(["host","origin"]),defaultInstance:c().min(1).max(256).nullable(),defaultInstances:C(c().min(1).max(256)).max(16).optional().catch(void 0),multiple:y(),allowLoopbackHttp:y(),allowPort:y(),reserved:C(c().max(256)).max(16),placeholder:c().max(256),legacyFlow:d({instance:c().min(1).max(256),kind:m("github-com-device")}).optional()}),auth:d({methods:C(M([ZM,c().transform(()=>null)])).transform(e=>e.filter(t=>t!==null)),cliName:c().min(1).max(32).optional(),login:Rd.optional(),cliTransport:y(),token:d({scopes:C(c().min(1).max(64)).max(32),createPath:c().max(256).optional()}).optional()}),settings:d({fields:C(d({id:c().min(1).max(64),kind:JM,secret:y()})).max(16)}),urls:d({changeRequest:eo,issue:eo,discussion:eo.default([]).catch([]),commit:eo.default([]).catch([]),user:eo.default([]).catch([])}),features:d({referenceSearch:y().default(!1),referenceDetail:y().default(!1),listStatuses:y().default(!1),referencesAcross:y().default(!1),startThread:y().default(!1),reviewDrafts:y().default(!1),reviewDraftFileComments:y().default(!1),authorCanReview:y().default(!1),projectUploads:y().default(!1),issueCloseReason:y().default(!1),changeRequestTemplates:C(c().min(1).max(256)).max(8).default([]),changeRequestPatch:y().default(!0),reviewModel:S(["verdict","votes"]).default("verdict").catch("verdict"),revisions:y().default(!1).catch(!1),submitRequirements:y().default(!1).catch(!1),createByPush:y().default(!1).catch(!1),branchHeads:y().default(!0).catch(!0),discussions:y().default(!1).catch(!1)}),extension:d({guestId:c().min(1).max(128),name:c().min(1).max(200),version:c().min(1).max(64)}).optional().catch(void 0)}),YM=(e,t)=>e.order-t.order||(e.id<t.id?-1:e.id>t.id?1:0),Dd=C(QM.nullable().catch(null)).transform(e=>{const t=new Set,s=[];for(const a of e)!a||t.has(a.id)||(t.add(a.id),s.push(a));return s.sort(YM)}),Vm=new Map,cu=e=>{const t=Vm.get(e);if(t)return t;const s={id:e,label:e,order:Number.MAX_SAFE_INTEGER,terminology:{changeRequest:"pullRequest",changeRequestPrefix:"#",issuePrefix:"#",sharedNumberSpace:!0,abbreviation:"PR",promptNoun:"pull request",ci:"checks"},icon:{sprite:"git-branch"},repository:{nestedNamespaces:!1},instances:{format:"origin",defaultInstance:null,multiple:!1,allowLoopbackHttp:!1,allowPort:!1,reserved:[],placeholder:""},auth:{methods:[],cliTransport:!1},settings:{fields:[]},urls:{changeRequest:[],issue:[],discussion:[],commit:[],user:[]},features:{referenceSearch:!1,referenceDetail:!1,listStatuses:!1,referencesAcross:!1,startThread:!1,reviewDrafts:!1,reviewDraftFileComments:!1,authorCanReview:!1,projectUploads:!1,issueCloseReason:!1,changeRequestTemplates:[],changeRequestPatch:!1,reviewModel:"verdict",revisions:!1,submitRequirements:!1,createByPush:!1,branchHeads:!0,discussions:!1}};return Vm.set(e,s),s},XM=16,eB=(e,t)=>{const s=C(wr([c(),t])),a=()=>{try{const n=s.safeParse(JSON.parse(window.localStorage.getItem(e)??"[]"));return n.success?n.data:[]}catch{return[]}};return{read:n=>ql(n)?null:a().find(([o])=>o===n)?.[1]??null,remember:(n,o)=>{if(ql(n))return;const i=a().filter(([r])=>r!==n);i.push([n,[...o]]);try{window.localStorage.setItem(e,JSON.stringify(i.slice(-XM)))}catch{}}}},tB=(e,t)=>e===t||e.length===t.length&&JSON.stringify(e)===JSON.stringify(t),sB=e=>Math.min(6e4,2e3*2**Math.max(0,e-1)),uy=eB("openchamber.sourceControlProviders.v1",Dd),lu=e=>({ordered:e,byId:new Map(e.map(t=>[t.id,t]))}),aB=lu([]),Um=e=>{const t=uy.read(e);return t?{runtimeKey:e,...lu(t),status:"stale",holdsList:!0}:{runtimeKey:e,...aB,status:"idle",holdsList:!1}};let ua=0,Ga=null,_a=null,_i=0,Ro=null;const Wm=()=>{Ro!==null&&clearTimeout(Ro),Ro=null},Ea=Rt((e,t)=>{const s=a=>{ua+=1,Ga=null,_a=null,_i=0,Wm(),e(Um(a))};return{...Um(N()),refresh:a=>{const n=N();if(n!==t().runtimeKey&&s(n),Ga){if(!_a){const u=ua,g=Ga.then(()=>{if(_a===g&&(_a=null),u===ua)return t().refresh(a)});_a=g}return _a}Wm();const o=ua,{holdsList:i,ordered:r}=t();e({status:"loading"});const p=(async()=>{try{const u=await a.providers();if(o!==ua)return;_i=0,uy.remember(n,u),e(i&&tB(r,u)?{status:"ready"}:{...lu(u),status:"ready",holdsList:!0})}catch{if(o!==ua)return;if(i){e({status:"stale"});return}e({status:"error"}),_i+=1,Ro=setTimeout(()=>{Ro=null,o===ua&&t().refresh(a)},sB(_i))}})().finally(()=>{Ga===p&&(Ga=null)});return Ga=p,p},resetForRuntimeSwitch:s}});queueMicrotask(()=>{const e=Ea.getState(),t=N();e.status==="idle"&&t!==e.runtimeKey&&e.resetForRuntimeSwitch(t)});const $J=()=>Ea(oB),nB=e=>{const t=kt.c(5);let s;t[0]!==e?(s=o=>e?o.byId.get(e):void 0,t[0]=e,t[1]=s):s=t[1];const a=Ea(s);let n;return t[2]!==a||t[3]!==e?(n=a??cu(e??""),t[2]=a,t[3]=e,t[4]=n):n=t[4],n},QJ=e=>nB(e).terminology.changeRequest,YJ=e=>{const t=kt.c(2);let s;return t[0]!==e?(s=a=>e&&a.byId.has(e)?"served":a.holdsList?"not-served":"unknown",t[0]=e,t[1]=s):s=t[1],Ea(s)},XJ=e=>{const t=kt.c(2);let s;return t[0]!==e?(s=a=>{const n=e?a.byId.get(e):void 0;return n?n.features.changeRequestPatch?"served":"not-served":a.holdsList?"not-served":"unknown"},t[0]=e,t[1]=s):s=t[1],Ea(s)},e$=()=>{const e=kt.c(2),t=Ea(iB);let s;return e[0]!==t?(s=a=>(a?t.get(a):void 0)??cu(a??""),e[0]=t,e[1]=s):s=e[1],s},lc=e=>(e?Ea.getState().byId.get(e):void 0)??cu(e??"");function oB(e){return e.ordered}function iB(e){return e.byId}const rB=d({text:c(),prefix:c(),suffix:c(),start:w(),page:d({partId:c(),kind:m("ui").optional()}).optional()}),Hm=32,gy=200,cB="[data-chat-quote-root]";function t$(e,t){return[...e.querySelectorAll(`[data-message-id="${CSS.escape(t)}"]`)].flatMap(s=>s.querySelector(cB)??[]).sort((s,a)=>s.getBoundingClientRect().top-a.getBoundingClientRect().top)}function s$(e,t,s){return e.querySelector(`[data-ui-render-message="${CSS.escape(t)}"][data-ui-render-part="${CSS.escape(s)}"]`)}function my(e,t,s){const a=s+t.text.length,n=e.slice(Math.max(0,s-t.prefix.length),s),o=e.slice(a,a+t.suffix.length);return t.prefix.endsWith(n)&&t.suffix.startsWith(o)}function Gm(e,t,s){const a=e.ownerDocument.createRange();return a.setStart(e,0),a.setEnd(t,s),a.toString().length}function hy(e){const t=[];let s="";for(const a of e)t.push(s.length),s+=a.textContent??"";return{stream:s,bases:t}}function a$(e,t){const s=Array.isArray(e)?e:[e],a=s.findIndex(u=>u.contains(t.startContainer)),n=s.findIndex(u=>u.contains(t.endContainer));if(a<0||n<a)return null;const{stream:o,bases:i}=hy(s),r=i[a]+Gm(s[a],t.startContainer,t.startOffset),l=i[n]+Gm(s[n],t.endContainer,t.endOffset),p=o.slice(r,l);return p.trim()?{text:p,prefix:o.slice(Math.max(0,r-Hm),r),suffix:o.slice(l,l+Hm),start:r}:null}function lB(e,t){if(!t.text)return null;const s=[];for(let n=e.indexOf(t.text);n!==-1&&s.length<gy;n=e.indexOf(t.text,n+1))s.push(n);if(s.length<=1)return s[0]??null;if(!t.prefix&&!t.suffix)return null;const a=s.filter(n=>my(e,t,n));return a.length===0?null:a.reduce((n,o)=>Math.abs(o-t.start)<Math.abs(n-t.start)?o:n)}function fy(e,t){for(let s=e.firstChild;s;s=s.nextSibling)s.nodeType===3?t.push(s):fy(s,t);return t}function dB(e){const t=new Set;let s=1;for(const a of e){const n=a.closest("[data-message-id]")?.getAttribute("data-message-row");if(!n)return e.length===1;const[o,i]=n.split("/");t.add(o),s=Number(i)}return t.size===s}const to=32;function pB(e,t){const{text:s,prefix:a,suffix:n}=t,o=!!(a||n),i=p=>{const u=[];for(let g=e.indexOf(p);g!==-1&&u.length<gy;g=e.indexOf(p,g+1))u.push(g);return u},r=[];for(const p of i(s))(!o||my(e,t,p))&&r.push({start:p,end:p+s.length});if(s.length>to&&(r.length===0||!o)){for(const p of i(s.slice(0,to))){const u=e.slice(p);u.length<s.length&&s.startsWith(u)&&a.endsWith(e.slice(Math.max(0,p-a.length),p))&&r.push({start:p,end:e.length})}for(const p of i(s.slice(-to))){const u=p+to;u<s.length&&s.endsWith(e.slice(0,u))&&n.startsWith(e.slice(u,u+n.length))&&r.push({start:0,end:u})}e.length>=to&&e.length<s.length&&s.includes(e)&&r.push({start:0,end:e.length})}return o?r[0]??null:new Set(r.map(p=>`${p.start}:${p.end}`)).size===1?r[0]:null}function uB(e,t){const{stream:s}=hy(e);let a,n;if(dB(e))a=lB(s,t),n=(a??0)+t.text.length;else{const r=pB(s,t);a=r?.start??null,n=r?.end??0}if(a===null||n<=a)return null;const o=[];let i=0;for(const r of e){let l=null;for(const p of fy(r,[])){const u=p.data.length;if(!l&&a<i+u&&n>i&&(l=r.ownerDocument.createRange(),l.setStart(p,Math.max(0,a-i)),l.setEnd(r,r.childNodes.length)),l&&n<=i+u)return l.setEnd(p,n-i),o.push(l),o;i+=u}l&&o.push(l)}return null}function n$(e,t){return uB([e],t)?.[0]??null}const gB=aC.gfm,mB=nC().use(oC).use(gB[0],{singleTilde:!1});function o$(e){const t=s=>{if("children"in s){if(s.type==="list")return`
35
35
  ${s.children.map(t).join(`
36
36
  `)}
37
37
  `;if(s.type==="listItem"){const o=s.children.map(i=>t(i)).join(`
@@ -86,4 +86,4 @@ ${t}`,so=(e,t)=>({...t,directory:e.directory}),ul=(e,t)=>Xa(FB,"/api/message-que
86
86
  `||a==="\r"?"":a??""}),JB=/\/\*[\s\S]*?\*\/|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|\burl\(\s*(?:"((?:\\[\s\S]|[^"\\])*)"|'((?:\\[\s\S]|[^'\\])*)'|((?:\\[\s\S]|[^)\\])*?))\s*\)|@import\s+(?:"((?:\\[\s\S]|[^"\\])*)"|'((?:\\[\s\S]|[^'\\])*)')/gi,b$=async(e,t,s,a=[])=>{const n=`/api/guests/${e}/`,o=new URL(t,`${ml}${n}`),i=new Map;let r=0,l=0;const p=async v=>{if(v.origin!==ml||!v.pathname.startsWith(n))throw new Error("Extension resource is outside its package");const P=await s(`${v.pathname}${v.search}`);if(!P.ok)throw new Error(`Could not load extension resource (HTTP ${P.status})`);const z=P.body?.getReader();if(!z)throw new Error("Extension resource has no response body");const x=[];try{for(;;){const{done:j,value:V}=await z.read();if(j)break;if(r+=V.byteLength,r>KB)throw new Error("Extension document exceeds the resource size limit");x.push(new Uint8Array(V))}}catch(j){throw await z.cancel().catch(()=>{}),j}finally{z.releaseLock()}return new Blob(x,{type:P.headers.get("content-type")?.split(";")[0]||"application/octet-stream"})},u=async(v,P,z)=>{const x=v.trim();if(!x||x.startsWith("#"))return v;const j=new URL(x,P);if(j.origin!==ml)return j.href;const V=j.hash;j.hash="";const Z=j.href;if(z.includes(Z))throw new Error("Circular extension resource reference");let B=i.get(Z);if(!B){if(i.size>=_B)throw new Error("Extension document has too many resources");const _=[...z,Z];B=p(j).then(async te=>{const se=te.type.split(";")[0];return se==="text/css"||j.pathname.endsWith(".css")?mr(new Blob([await g(await te.text(),j,_)],{type:"text/css"})):mr(se==="text/html"?new Blob([await b(await te.text(),j,_)],{type:"text/html"}):te)}),i.set(Z,B)}const W=`${await B}${V}`;if(l+=W.length,l>th)throw new Error("Extension document exceeds the embedded size limit");return W},g=async(v,P,z)=>{let x="",j=0;for(const V of v.matchAll(JB)){const Z=V[1]??V[2]??V[3]??V[4]??V[5];if(Z===void 0)continue;x+=v.slice(j,V.index);const B=await u(ZB(Z.trim()),P,z),W=JSON.stringify(B);x+=V[4]!==void 0||V[5]!==void 0?`@import url(${W})`:`url(${W})`,j=V.index+V[0].length}return x+v.slice(j)},h=async(v,P,z)=>{const x=[];let j=v;for(;j.trim();){j=j.replace(/^[\s,]+/,"");const V=/^\S+/.exec(j);if(!V)break;const Z=V[0];j=j.slice(Z.length);let B="";if(!Z.endsWith(",")){const _=j.indexOf(",");B=(_<0?j:j.slice(0,_)).trim(),j=_<0?"":j.slice(_+1)}const W=await u(Z.replace(/,+$/,""),P,z);x.push(B?`${W} ${B}`:W)}return x.join(", ")},b=async(v,P,z)=>{const x=new DOMParser().parseFromString(v,"text/html"),j=x.querySelector("base[href]")?.getAttribute("href"),V=x.querySelector("base[target]")?.getAttribute("target"),Z=j?new URL(j,P):P;for(const te of x.querySelectorAll("base"))te.remove();const B=x.createElement("base");B.href=Z.href,V&&(B.target=V),x.head.prepend(B);const W=x.createElement("meta");W.httpEquiv="Content-Security-Policy",W.content=GB(null,a),x.head.prepend(W);for(const te of x.querySelectorAll("script[src], link[href], img[src], source[src], video[src], audio[src], iframe[src], embed[src], object[data], image[href], image[xlink\\:href], use[href], use[xlink\\:href]"))for(const se of["src","href","data","xlink:href"]){const Ve=te.getAttribute(se);Ve!==null&&te.setAttribute(se,await u(Ve,Z,z))}for(const te of x.querySelectorAll("[poster]"))te.setAttribute("poster",await u(te.getAttribute("poster")??"",Z,z));for(const te of x.querySelectorAll("img[srcset], source[srcset]"))te.setAttribute("srcset",await h(te.getAttribute("srcset")??"",Z,z));for(const te of x.querySelectorAll("style"))te.textContent=await g(te.textContent??"",Z,z);for(const te of x.querySelectorAll("[style]"))te.setAttribute("style",await g(te.getAttribute("style")??"",Z,z));const _=`<!doctype html>
87
87
  ${x.documentElement.outerHTML}`;if(_.length>th)throw new Error("Extension document exceeds the size limit");return _},k=await p(o);if(k.type.split(";")[0]!=="text/html")throw new Error("Extension entry is not HTML");return b(await k.text(),o,[o.href])},$B=200,QB=/^image\/(?:png|jpeg|webp|gif)\b/,Ut=new Map,YB=(e,t)=>[ns()||"same-origin",e,t].join("|"),XB=()=>{for(;Ut.size>$B;){const e=Ut.keys().next().value;if(typeof e!="string")return;const t=Ut.get(e);t?.url&&typeof URL<"u"&&typeof URL.revokeObjectURL=="function"&&URL.revokeObjectURL(t.url),Ut.delete(e)}},eL=(e,t,s)=>{const a=Ut.get(e);if(a?.url)return Promise.resolve(a.url);if(a?.promise)return a.promise;const n=T(t,{method:"GET",headers:{Accept:"image/*"},query:new URLSearchParams(s)}).then(async o=>{if(!o.ok||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;const i=await o.blob(),r=QB.test(i.type)?URL.createObjectURL(i):await mr(i);return Ut.set(e,{url:r}),XB(),r}).catch(()=>null).finally(()=>{const o=Ut.get(e);o?.promise===n&&!o.url&&Ut.delete(e)});return Ut.set(e,{promise:n}),n},tL=(e,t)=>{const s=kt.c(10);let a;s[0]!==e||s[1]!==t?(a=e?YB(e,t):null,s[0]=e,s[1]=t,s[2]=a):a=s[2];const n=a;let o;s[3]!==n?(o=()=>({url:n?Ut.get(n)?.url??null:null,failed:!1}),s[3]=n,s[4]=o):o=s[4];const[i,r]=ta.useState(o);let l,p;return s[5]!==n||s[6]!==e||s[7]!==t?(l=()=>{const u=(b,k)=>r(v=>v.url===b&&v.failed===k?v:{url:b,failed:k});if(!n||!e){u(null,!1);return}const g=Ut.get(n)?.url;if(g){u(g,!1);return}let h=!1;return u(null,!1),eL(n,e,t).then(b=>{h||u(b,b===null)}),()=>{h=!0}},p=[n,e,t],s[5]=n,s[6]=e,s[7]=t,s[8]=l,s[9]=p):(l=s[8],p=s[9]),ta.useEffect(l,p),i},sL=["image/png","image/jpeg","image/webp","image/svg+xml"],aL=1024*1024,Sy=S(sL),Py=d({mime:Sy,updatedAt:w().int().positive()}),k$=()=>!Ee(),hu=e=>`/api/provider/${encodeURIComponent(e)}/logo`,nL=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["webp","image/webp"],["svg","image/svg+xml"]]),xy=e=>Sy.safeParse(e.type.trim().toLowerCase()).data??nL.get(e.name.toLowerCase().split(".").pop()??"")??null,w$=e=>xy(e)?e.size<=0||e.size>aL?"size":null:"type",oL=(e,t)=>new Promise((s,a)=>{const n=new FileReader;n.onload=()=>{const o=c().safeParse(n.result);o.success?s(o.data.replace(/^data:[^;,]*;/i,`data:${t};`)):a(new Error("Could not read the file"))},n.onerror=()=>a(n.error??new Error("Could not read the file")),n.readAsDataURL(e)}),Ty=async e=>{const t=await e.json().catch(()=>null),s=d({error:c()}).safeParse(t).data?.error;return new Error(s??`HTTP ${e.status}`)},y$=async(e,t)=>{const s=xy(t);if(!s)throw new Error("Logo must be PNG, JPEG, WebP or SVG");const a=await T(hu(e),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({dataUrl:await oL(t,s)})});if(!a.ok)throw await Ty(a);const n=d({logo:Py}).safeParse(await a.json().catch(()=>null));if(!n.success)throw new Error("Unexpected response");return n.data.logo},v$=async e=>{const t=await T(hu(e),{method:"DELETE",headers:{Accept:"application/json"}});if(!t.ok)throw await Ty(t)},C$=(e,t,s)=>{const a=kt.c(6);let n;a[0]!==t||a[1]!==e?(n=t?hu(e):null,a[0]=t,a[1]=e,a[2]=n):n=a[2];const o=n;let i;return a[3]!==t||a[4]!==s?(i=t?new URLSearchParams(t.mime==="image/svg+xml"?{v:String(t.updatedAt),theme:s}:{v:String(t.updatedAt)}).toString():"",a[3]=t,a[4]=s,a[5]=i):i=a[5],tL(o,i)},iL=e=>{const t=e.replace(/\\/g,"/").replace(/\/+$/g,"").trim();if(!t)return"";const s=new TextEncoder().encode(t);let a="";for(const o of s)a+=String.fromCharCode(o);return`path_${typeof btoa=="function"?btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,""):t.replace(/[^A-Za-z0-9._-]+/g,"_")}`},S$=e=>{if(!e.startsWith("path_"))return"";const t=e.slice(5);if(!t||!/^[A-Za-z0-9_-]+$/.test(t))return"";try{const s=atob(t.replace(/-/g,"+").replace(/_/g,"/"));return new TextDecoder().decode(Uint8Array.from(s,a=>a.charCodeAt(0)))}catch{return""}},G=e=>t=>{const s=e.safeParse(t);return s.success?s.data:void 0},Ln=w().refine(Number.isFinite),pt=c().transform(e=>e.trim()),Ne=pt.pipe(c().min(1)),os=ke(c(),ne()),I=G(y()),qe=G(c().min(1)),en=G(pt),ha=G(Ne),Ka=e=>G(c().max(e)),Za=e=>G(pt.transform(t=>t.slice(0,e))),pe=e=>G(pt.pipe(S(e))),Ns=G(Ln),hl=(e,t)=>G(Ln.transform(s=>Math.max(e,Math.min(t,Math.round(s))))),fl=e=>G(Ln.transform(t=>Math.max(e,Math.round(t)))),rL=G(Ln.positive().transform(Math.floor)),cL=G(M([xs(),Ln])),lL=G(M([xs(),pt.transform(e=>e.length>0?e:null)])),dL=G(M([xs(),pt])),fu=C(ne()).transform(e=>e.filter(t=>c().min(1).safeParse(t).success)),Ja=G(fu.transform(e=>Array.from(new Set(e.map(String))))),bl=G(fu.transform(e=>e.map(String))),pL=os.transform(e=>{const t={};for(const[s,a]of Object.entries(e)){const n=C(ne()).safeParse(a);n.success&&(t[s]=n.data.filter(o=>c().safeParse(o).success).map(String))}return t}),kl=G(pL.pipe(ke(c(),C(c())).refine(e=>Object.keys(e).length>0))),uL=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[s,a]of Object.entries(e)){const n=s.trim();n&&HB(a)&&(t[n]=a)}return t},gL=G(os.transform(e=>{const t={};for(const[s,a]of Object.entries(e)){const n=s.trim(),o=Py.safeParse(a);n&&o.success&&(t[n]=o.data)}return t})),mL=d({providerID:Ne,modelID:Ne}),wl=e=>G(C(ne()).transform(t=>{const s=[],a=new Set;for(const n of t){const o=mL.safeParse(n);if(!o.success)continue;const i=`${o.data.providerID}/${o.data.modelID}`;if(!a.has(i)&&(a.add(i),s.push(o.data),s.length>=e))break}return s})),hL=G(os.transform(e=>{const t={};for(const[s,a]of Object.entries(e)){if(!s)continue;const n=fu.safeParse(a);if(!n.success)continue;const o=Array.from(new Set(n.data.map(String)));o.length>0&&(t[s]=o.slice(0,5))}return t}).refine(e=>Object.keys(e).length>0)),fL=G(os.transform(e=>{const t={};for(const[s,a]of Object.entries(e)){const n=s.trim();if(!n)continue;if(a===null){t[n]=null;continue}const o=Ne.safeParse(a);o.success&&(t[n]=o.data)}return t}).refine(e=>Object.keys(e).length>0)),bL=G(os.transform(e=>{const t={};for(const[s,a]of Object.entries(e)){const n=s.trim(),o=Ne.safeParse(a);!n||!o.success||(t[n]=o.data)}return t})),$i={completion:{title:"Task Complete",message:"Your task has finished."},error:{title:"Error Occurred",message:"An error occurred while processing your task."},question:{title:"Input Needed",message:"Please provide input to continue."},subtask:{title:"Subtask Complete",message:"A subtask has finished."}},kL=d({title:c().catch(""),message:c().catch("")}),wL=G(os.transform(e=>{const t=i=>{const r=kL.safeParse(e[i]);return r.success?r.data:void 0},s=t("completion"),a=t("error"),n=t("question"),o=t("subtask");if(!(!s&&!a&&!n&&!o))return{completion:s??$i.completion,error:a??$i.error,question:n??$i.question,subtask:o??$i.subtask}}).pipe(Kr(e=>e!==void 0))),sh=os.transform(e=>Object.fromEntries(Object.entries(e).flatMap(([t,s])=>{const a=c().safeParse(s);return a.success?[[t,a.data]]:[]}))),yL=d({id:ne().transform(e=>String(e??"")),label:ne().transform(e=>String(e??"")),models:C(ne()).transform(e=>e.filter(t=>c().safeParse(t).success).map(String)).catch([]),order:w().catch(0)}),vL=G(os.transform(e=>{const t={};for(const[s,a]of Object.entries(e)){const n=os.safeParse(a);if(!n.success)continue;const o={},i=C(ne()).safeParse(n.data.customGroups);i.success&&(o.customGroups=i.data.flatMap(p=>{const u=yL.safeParse(p);return u.success?[u.data]:[]}));const r=sh.safeParse(n.data.modelAssignments);r.success&&(o.modelAssignments=r.data);const l=sh.safeParse(n.data.renamedGroups);l.success&&(o.renamedGroups=l.data),Object.keys(o).length>0&&(t[s]=o)}return t}).refine(e=>Object.keys(e).length>0)),CL=d({id:Ne,name:Ne,hostname:Ne.transform(e=>e.toLowerCase())}),SL=G(C(ne()).transform(e=>{const t=[],s=new Set,a=new Set;for(const n of e){const o=CL.safeParse(n);o.success&&(s.has(o.data.id)||a.has(o.data.hostname)||(s.add(o.data.id),a.add(o.data.hostname),t.push(o.data)))}return t})),PL=G(os.transform(e=>{const t={};for(const[s,a]of Object.entries(e)){const n=s.trim(),o=Ne.safeParse(a);!n||!o.success||(t[n]=o.data)}return t}).refine(e=>Object.keys(e).length>0)),xL=d({id:Ne,label:Ne,source:Ne,subpath:pt.optional().catch(void 0),gitIdentityId:pt.optional().catch(void 0)}),TL=G(C(ne()).transform(e=>{const t=[],s=new Set;for(const a of e){const n=xL.safeParse(a);if(!n.success||s.has(n.data.id))continue;s.add(n.data.id);const o={id:n.data.id,label:n.data.label,source:n.data.source};n.data.subpath&&(o.subpath=n.data.subpath),n.data.gitIdentityId&&(o.gitIdentityId=n.data.gitIdentityId),t.push(o)}return t})),AL=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,yl=Ln.nonnegative(),zL=d({path:Ne,label:Ne.optional().catch(void 0),labelSource:S(["auto","manual"]).optional().catch(void 0),icon:Ne.optional().catch(void 0),iconImage:M([xs(),d({mime:Ne,updatedAt:yl.transform(Math.round).pipe(w().positive()),source:S(["custom","auto"])})]).optional().catch(void 0),color:Ne.optional().catch(void 0),iconBackground:M([xs(),pt.pipe(c().regex(AL)).transform(e=>e.toLowerCase())]).optional().catch(void 0),addedAt:yl.optional().catch(void 0),lastOpenedAt:yl.optional().catch(void 0),sidebarCollapsed:y().optional().catch(void 0),defaultModel:Ne.optional().catch(void 0),defaultAgent:Ne.optional().catch(void 0),defaultVariant:Ne.optional().catch(void 0)}),RL=G(C(ne()).transform(e=>{const t=[],s=new Set,a=new Set;for(const n of e){const o=zL.safeParse(n);if(!o.success)continue;const i=je(o.data.path);if(!i)continue;const r=iL(i);if(!r||s.has(r)||a.has(i))continue;s.add(r),a.add(i);const l={id:r,path:i};o.data.label&&(l.label=o.data.label),o.data.label&&o.data.labelSource&&(l.labelSource=o.data.labelSource),o.data.icon&&(l.icon=o.data.icon),o.data.iconImage!==void 0&&(l.iconImage=o.data.iconImage),o.data.color&&(l.color=o.data.color),o.data.iconBackground!==void 0&&(l.iconBackground=o.data.iconBackground),o.data.addedAt!==void 0&&(l.addedAt=o.data.addedAt),o.data.lastOpenedAt!==void 0&&(l.lastOpenedAt=o.data.lastOpenedAt),o.data.defaultModel&&(l.defaultModel=o.data.defaultModel),o.data.defaultAgent&&(l.defaultAgent=o.data.defaultAgent),o.data.defaultVariant&&(l.defaultVariant=o.data.defaultVariant),o.data.sidebarCollapsed!==void 0&&(l.sidebarCollapsed=o.data.sidebarCollapsed),t.push(l)}return t}).refine(e=>e.length>0)),IL=S(["steer","queue"]),jL=(e,t)=>{const s=IL.safeParse(e);if(s.success)return s.data;if(e==="immediate")return"steer";const a=y().safeParse(t.queueModeEnabled);if(a.success)return a.data?"queue":"steer"},OL=pt.pipe(S(["collapsed","summary"])),DL=(e,t)=>{if(t.chatRenderMode==="sorted")return"collapsed";const s=OL.safeParse(e);return s.success?s.data:void 0},NL=G(pt.pipe(S(["local","openai-compatible","server","browser","wasm"])).transform(e=>e==="server"?"openai-compatible":e==="browser"||e==="wasm"?"local":e)),FL=G(pt.pipe(S(["left","right","auto"])).transform(e=>e==="left"?"left":"right")),EL=G(pt.transform(e=>e.replace(/\s+/g," ").slice(0,64))),ML=e=>G(C(ne()).transform(t=>{const s=[];for(const a of t){const n=pt.transform(o=>o.toLowerCase()).safeParse(a);n.success&&e(n.data)&&!s.includes(n.data)&&s.push(n.data)}return s})),bu=e=>G(Kr(e)),Yo=(e,t)=>(s,a)=>{const n=e(s,a);return n===void 0?void 0:t(n)},f=e=>e,A=(e,t,s={})=>({read:()=>R.getState()[e],write:t,autoSave:s.autoSave??!0}),yt=e=>t=>{R.setState({[e]:t})},ah=()=>globalThis.window?.__zustand_config_store__??null,Kt=e=>({read:()=>ah()?.getState()[e],write:t=>{ah()?.setState({[e]:t})},autoSave:!1}),vt=e=>({read:()=>Bt.getState()[e],write:t=>{Bt.setState({[e]:t})},autoSave:!1}),BL=["concise","detailed","mentor","pushback","noFiller","matchEnergy","warmPeer","custom"],LL=bu(Jp),qL=bu(Hz),VL=bu(Gz),UL=G(c().refine(Kk)),WL=G(w().refine(Zp)),HL=Yo(en,e=>sc(e,void 0)),GL=Yo(G(C(ne())),WI),_L=Yo(G(C(ne())),e=>mk(e)),KL=pe(["ask","attach","inline","inline-double-paste"]),ZL=pe(["default","vim"]),JL=(e,t)=>{let s=e;const a=(n,o)=>{if(s.some(l=>l.type==="command"&&l.name===n))return;const i=s.findIndex(l=>l.type==="command"&&l.name===o),r=i>=0?i+1:s.length;s=[...s.slice(0,r),{type:"command",name:n},...s.slice(r)]};return t.draftStartersCraftGoalAdded!==!0&&a("craft-goal","plan-feature"),t.draftStartersScheduleTaskAdded!==!0&&a("schedule-task","craft-goal"),s},pi={themeId:f({scope:"profile",perSurface:!0,parse:qe}),useSystemTheme:f({scope:"profile",perSurface:!0,parse:I}),themeVariant:f({scope:"profile",derived:!0,parse:pe(["light","dark"])}),lightThemeId:f({scope:"profile",perSurface:!0,parse:qe}),darkThemeId:f({scope:"profile",perSurface:!0,parse:qe}),locale:f({scope:"profile",parse:pe(KI),ui:{read:()=>Er.getState().locale,write:e=>Er.getState().setLocale(e),autoSave:!1}}),lastDirectory:f({scope:"instance",adopt:"bootstrap-only",parse:qe}),homeDirectory:f({scope:"instance",parse:qe}),opencodeBinary:f({scope:"instance",parse:en}),serverUpdateChannel:f({scope:"instance",surfaces:["web"],parse:pe(["stable","canary"])}),projects:f({scope:"instance",parse:RL}),activeProjectId:f({scope:"instance",adopt:"bootstrap-only",parse:qe}),securityScopedBookmarks:f({scope:"instance",surfaces:["desktop"],parse:bl}),pinnedDirectories:f({scope:"instance",parse:Ja}),desktopLanAccessEnabled:f({scope:"instance",surfaces:["desktop"],parse:I}),desktopKeepAwakeEnabled:f({scope:"instance",surfaces:["desktop"],parse:I}),desktopMinimizeToTrayEnabled:f({scope:"instance",surfaces:["desktop"],parse:I}),desktopUpdateChannel:f({scope:"instance",surfaces:["desktop"],parse:pe(["stable","canary"])}),desktopMacMenuBarEnabled:f({scope:"instance",surfaces:["desktop"],parse:I}),desktopLinuxNativeFrame:f({scope:"instance",surfaces:["desktop"],parse:I}),desktopUiPassword:f({scope:"instance",secret:!0,surfaces:["desktop"],parse:en}),hasDesktopUiPassword:f({scope:"instance",computed:!0,surfaces:["desktop"],parse:I}),desktopLanAccessActive:f({scope:"instance",computed:!0,surfaces:["desktop"],parse:I}),desktopLanAccessBlockedReason:f({scope:"instance",computed:!0,surfaces:["desktop"],parse:en}),githubClientId:f({scope:"instance",parse:ha}),githubScopes:f({scope:"instance",parse:ha}),gitlabClientId:f({scope:"instance",parse:ha}),skillCatalogs:f({scope:"instance",parse:TL}),defaultGitIdentityId:f({scope:"instance",parse:en}),permissionAutoAccept:f({scope:"instance",parse:G(d({sessions:ke(c().min(1),M([y(),S(["ask","safety","auto"])])).catch({}),revision:w().int().nonnegative().catch(0)}))}),permissionDefaultMode:f({scope:"instance",surfaces:["web","desktop","mobile"],parse:G(S(["ask","safety","auto"])),ui:A("permissionDefaultMode",e=>R.getState().setPermissionDefaultMode(e))}),messageSearchEnabled:f({scope:"instance",surfaces:["web","desktop","mobile"],parse:I,ui:A("messageSearchEnabled",e=>R.getState().setMessageSearchEnabled(e))}),messageSearchReasoningEnabled:f({scope:"instance",surfaces:["web","desktop","mobile"],parse:I,ui:A("messageSearchReasoningEnabled",e=>R.getState().setMessageSearchReasoningEnabled(e))}),agentControlToolEnabled:f({scope:"instance",parse:I,ui:A("agentControlToolEnabled",e=>R.getState().setAgentControlToolEnabled(e))}),agentScheduleToolEnabled:f({scope:"instance",parse:I,ui:A("agentScheduleToolEnabled",e=>R.getState().setAgentScheduleToolEnabled(e))}),agentWebToolEnabled:f({scope:"instance",parse:I,ui:A("agentWebToolEnabled",e=>R.getState().setAgentWebToolEnabled(e))}),browserProvider:f({scope:"instance",parse:qe,ui:A("browserProvider",e=>R.getState().setBrowserProvider(e))}),agentNotifyToolEnabled:f({scope:"instance",parse:I,ui:A("agentNotifyToolEnabled",e=>R.getState().setAgentNotifyToolEnabled(e))}),agentRenderToolEnabled:f({scope:"instance",parse:I,ui:A("agentRenderToolEnabled",e=>R.getState().setAgentRenderToolEnabled(e))}),agentUsageToolEnabled:f({scope:"instance",parse:I,ui:A("agentUsageToolEnabled",e=>R.getState().setAgentUsageToolEnabled(e))}),agentImageToolEnabled:f({scope:"instance",parse:I,ui:A("agentImageToolEnabled",e=>R.getState().setAgentImageToolEnabled(e))}),agentImageModel:f({scope:"instance",parse:qe,ui:A("agentImageModel",e=>R.getState().setAgentImageModel(e))}),agentSecretToolEnabled:f({scope:"instance",parse:I,ui:A("agentSecretToolEnabled",e=>R.getState().setAgentSecretToolEnabled(e))}),agentMemoryToolEnabled:f({scope:"instance",parse:I,ui:A("agentMemoryToolEnabled",e=>R.getState().setAgentMemoryToolEnabled(e))}),agentMemoryDreamingEnabled:f({scope:"instance",parse:I,ui:A("agentMemoryDreamingEnabled",e=>R.getState().setAgentMemoryDreamingEnabled(e))}),agentMemoryDreamingModel:f({scope:"instance",parse:G(c()),ui:A("agentMemoryDreamingModel",e=>R.getState().setAgentMemoryDreamingModel(e))}),agentMemoryDreamingVariant:f({scope:"instance",parse:G(c()),ui:A("agentMemoryDreamingVariant",e=>R.getState().setAgentMemoryDreamingVariant(e))}),agentKnowledgeToolEnabled:f({scope:"instance",parse:I,ui:A("agentKnowledgeToolEnabled",e=>R.getState().setAgentKnowledgeToolEnabled(e))}),agentWorkflowToolEnabled:f({scope:"instance",parse:I,ui:A("agentWorkflowToolEnabled",e=>R.getState().setAgentWorkflowToolEnabled(e))}),isolatedSpacesEnabled:f({scope:"instance",parse:I,ui:A("isolatedSpacesEnabled",e=>R.getState().setIsolatedSpacesEnabled(e))}),isolatedSpacesIdleStop:f({scope:"instance",parse:G(d({enabled:y(),hours:w().int().min(1).max(168)}).strict())}),isolatedSpacesSshHost:f({scope:"instance",parse:Za(320)}),agentMemoryFeatureAvailable:f({scope:"instance",computed:!0,parse:I,ui:A("agentMemoryFeatureAvailable",e=>R.getState().setAgentMemoryFeatureAvailable(e),{autoSave:!1})}),agentWorkflowFeatureAvailable:f({scope:"instance",computed:!0,parse:I,ui:A("agentWorkflowFeatureAvailable",e=>R.getState().setAgentWorkflowFeatureAvailable(e),{autoSave:!1})}),overviewFeatureAvailable:f({scope:"instance",computed:!0,parse:I,ui:A("overviewFeatureAvailable",e=>R.getState().setOverviewFeatureAvailable(e),{autoSave:!1})}),routingFeatureAvailable:f({scope:"instance",computed:!0,parse:I,ui:A("routingFeatureAvailable",e=>R.getState().setRoutingFeatureAvailable(e),{autoSave:!1})}),openCodeUpdateToastDismissedVersion:f({scope:"instance",parse:Za(128)}),autoDeleteEnabled:f({scope:"instance",parse:I,ui:A("autoDeleteEnabled",e=>R.getState().setAutoDeleteEnabled(e))}),autoDeleteAfterDays:f({scope:"instance",parse:hl(1,365),ui:A("autoDeleteAfterDays",e=>R.getState().setAutoDeleteAfterDays(e))}),sessionRetentionOnlyArchived:f({scope:"instance",parse:I,ui:A("sessionRetentionOnlyArchived",e=>R.getState().setSessionRetentionOnlyArchived(e))}),sessionRetentionIncludeInWork:f({scope:"instance",parse:I,ui:A("sessionRetentionIncludeInWork",e=>R.getState().setSessionRetentionIncludeInWork(e))}),sessionRetentionAction:f({scope:"instance",parse:pe(["archive","delete"]),ui:A("sessionRetentionAction",e=>R.getState().setSessionRetentionAction(e))}),mergedWorktreeCleanupEnabled:f({scope:"instance",parse:I,ui:A("mergedWorktreeCleanupEnabled",e=>R.getState().setMergedWorktreeCleanupEnabled(e))}),worktreeArchiveOnDoneEnabled:f({scope:"instance",parse:I,ui:A("worktreeArchiveOnDoneEnabled",e=>R.getState().setWorktreeArchiveOnDoneEnabled(e))}),terminalShell:f({scope:"instance",parse:LL,ui:A("terminalShell",e=>R.getState().setTerminalShell(e))}),terminalLoginShells:f({scope:"instance",parse:ML(Jp),ui:A("terminalLoginShells",e=>R.getState().setTerminalLoginShells(e))}),openInAppId:f({scope:"instance",parse:ha}),dictationEnabled:f({scope:"profile",parse:I,ui:Kt("dictationEnabled")}),dictationAutoSend:f({scope:"profile",parse:I,ui:Kt("dictationAutoSend")}),sttProvider:f({scope:"instance",parse:NL,ui:Kt("sttProvider")}),sttServerUrl:f({scope:"instance",parse:Za(2048),ui:Kt("sttServerUrl")}),sttEndpointPath:f({scope:"instance",parse:G(c().trim().max(1024)),ui:Kt("sttEndpointPath")}),sttModel:f({scope:"instance",parse:Za(256),ui:Kt("sttModel")}),sttLocalModel:f({scope:"instance",parse:Za(256),ui:Kt("sttLocalModel")}),sttLanguage:f({scope:"profile",parse:Za(64),ui:Kt("sttLanguage")}),sttCorrectTranscript:f({scope:"profile",parse:I,ui:Kt("sttCorrectTranscript")}),tunnelProvider:f({scope:"instance",parse:Yo(ha,e=>e.toLowerCase())}),tunnelMode:f({scope:"instance",parse:G(c().transform(e=>e.trim().toLowerCase()).pipe(S(["quick","managed-remote","managed-local","serve","funnel"])))}),tunnelHttpsPort:f({scope:"instance",parse:hl(1,65535)}),tunnelBootstrapTtlMs:f({scope:"instance",parse:cL}),tunnelSessionTtlMs:f({scope:"instance",parse:Ns}),managedLocalTunnelConfigPath:f({scope:"instance",parse:lL}),managedRemoteTunnelHostname:f({scope:"instance",parse:en}),managedRemoteTunnelToken:f({scope:"instance",secret:!0,parse:dL}),hasManagedRemoteTunnelToken:f({scope:"instance",computed:!0,parse:I}),managedRemoteTunnelPresets:f({scope:"instance",parse:SL}),managedRemoteTunnelSelectedPresetId:f({scope:"instance",parse:ha}),managedRemoteTunnelPresetTokens:f({scope:"instance",secret:!0,parse:PL}),sidebarProjectDisplayMode:f({scope:"profile",parse:pe(["all","single"]),ui:vt("projectDisplayMode")}),sidebarViewMode:f({scope:"profile",perSurface:!0,parse:pe(["projects","timeline"]),ui:vt("sidebarViewMode")}),sidebarListSessionGrouping:f({scope:"profile",perSurface:!0,parse:pe(["project","time"]),ui:vt("listSessionGrouping")}),sidebarGrouping:f({scope:"profile",perSurface:!0,parse:pe(["project","time"]),ui:vt("sidebarGrouping")}),sidebarKeepWorkInPlace:f({scope:"profile",perSurface:!0,parse:I,ui:vt("keepWorkInPlace")}),sidebarKeepPinnedInPlace:f({scope:"profile",perSurface:!0,parse:I,ui:vt("keepPinnedInPlace")}),sidebarProjectSortOrder:f({scope:"profile",parse:pe(["manual","a-z","z-a","date-added","recent"]),ui:vt("projectSortOrder")}),sidebarShowChatsSection:f({scope:"profile",perSurface:!0,parse:I,ui:vt("showChatsSection")}),sidebarShowWorkSection:f({scope:"profile",perSurface:!0,parse:I,ui:vt("showWorkSection")}),sidebarShowPinnedSection:f({scope:"profile",perSurface:!0,parse:I,ui:vt("showPinnedSection")}),sidebarDetailedZoneRows:f({scope:"profile",perSurface:!0,parse:I,ui:vt("detailedZoneRows")}),sidebarWorktreeNameByBranch:f({scope:"profile",parse:I,ui:vt("worktreeNameByBranch")}),sidebarSections:f({scope:"profile",parse:G(pd),ui:{read:()=>Bt.getState().sections,write:e=>Bt.getState().setSections(e),autoSave:!1}}),sidebarPinLists:f({scope:"profile",parse:G(Ok),ui:{read:()=>Bt.getState().pinLists,write:e=>Bt.getState().setPinLists(e),autoSave:!1}}),sidebarHiddenSections:f({scope:"profile",perSurface:!0,parse:G(Dk),ui:{read:()=>Bt.getState().hiddenSections,write:e=>Bt.getState().setHiddenSections(e),autoSave:!1}}),workStatusSectionOrder:f({scope:"profile",parse:Yo(bl,mn),ui:A("workStatusSectionOrder",(e,t)=>{const s=t.workStatusSectionOrderExplicit===!0;R.setState({workStatusSectionOrder:mn(e,s),workStatusSectionOrderExplicit:s})})}),workStatusSectionOrderExplicit:f({scope:"profile",parse:I,ui:A("workStatusSectionOrderExplicit",e=>R.setState({workStatusSectionOrderExplicit:e}))}),workStatusPanelEnabled:f({scope:"profile",parse:I,ui:A("workStatusPanelEnabled",e=>R.getState().setWorkStatusPanelEnabled(e))}),workStatusHiddenSections:f({scope:"profile",parse:_L,ui:{read:()=>R.getState().workStatusHiddenSections,write:(e,t)=>{const s=t.workStatusHiddenSectionsExplicit===!0;R.setState({workStatusHiddenSections:mk(e,s),workStatusHiddenSectionsExplicit:s})},autoSave:!0}}),workStatusHiddenSectionsExplicit:f({scope:"profile",parse:I,ui:A("workStatusHiddenSectionsExplicit",()=>{})}),showReasoningTraces:f({scope:"profile",parse:I,ui:A("showReasoningTraces",e=>R.getState().setShowReasoningTraces(e))}),streamingAutoFollowEnabled:f({scope:"profile",perSurface:!0,parse:I,ui:A("streamingAutoFollowEnabled",e=>R.getState().setStreamingAutoFollowEnabled(e))}),collapsibleThinkingBlocks:f({scope:"profile",parse:I,ui:A("collapsibleThinkingBlocks",e=>R.getState().setCollapsibleThinkingBlocks(e))}),expandReasoningWhileStreaming:f({scope:"profile",parse:I,ui:A("expandReasoningWhileStreaming",e=>R.getState().setExpandReasoningWhileStreaming(e))}),showTextJustificationActivity:f({scope:"profile",parse:I}),chatRenderMode:f({scope:"profile",parse:pe(["sorted","live"])}),activityRenderMode:f({scope:"profile",parse:DL,ui:A("activityRenderMode",e=>R.getState().setActivityRenderMode(e))}),mermaidRenderingMode:f({scope:"profile",parse:pe(["svg","ascii"]),ui:A("mermaidRenderingMode",e=>R.getState().setMermaidRenderingMode(e))}),userMessageRenderingMode:f({scope:"profile",parse:pe(["markdown","plain"]),ui:A("userMessageRenderingMode",e=>R.getState().setUserMessageRenderingMode(e))}),collapsibleUserMessages:f({scope:"profile",parse:I,ui:A("collapsibleUserMessages",e=>R.getState().setCollapsibleUserMessages(e))}),stickyUserHeader:f({scope:"profile",perSurface:!0,parse:I,ui:A("stickyUserHeader",e=>R.getState().setStickyUserHeader(e))}),promptNavigatorEnabled:f({scope:"profile",perSurface:!0,parse:I,ui:A("promptNavigatorEnabled",e=>R.getState().setPromptNavigatorEnabled(e))}),wideChatLayoutEnabled:f({scope:"profile",perSurface:!0,parse:I,ui:A("wideChatLayoutEnabled",e=>R.getState().setWideChatLayoutEnabled(e))}),showSplitAssistantMessageActions:f({scope:"profile",parse:I,ui:A("showSplitAssistantMessageActions",e=>R.getState().setShowSplitAssistantMessageActions(e))}),showToolFileIcons:f({scope:"profile",parse:I,ui:A("showToolFileIcons",e=>R.getState().setShowToolFileIcons(e))}),codeBlockLineWrap:f({scope:"profile",parse:I,ui:A("codeBlockLineWrap",e=>R.getState().setCodeBlockLineWrap(e))}),tableCellWrap:f({scope:"profile",parse:I,ui:A("tableCellWrap",e=>R.getState().setTableCellWrap(e))}),copyMessagesAsPlainText:f({scope:"profile",parse:I,ui:A("copyMessagesAsPlainText",e=>R.getState().setCopyMessagesAsPlainText(e))}),selectionApprovalText:f({scope:"profile",parse:Ka(1e3),ui:A("selectionApprovalText",e=>R.getState().setSelectionApprovalText(e))}),showTurnChangedFiles:f({scope:"profile",parse:I,ui:A("showTurnChangedFiles",e=>R.getState().setShowTurnChangedFiles(e))}),toolJsonViewMode:f({scope:"profile",parse:pe(["summary","formatted","raw"]),ui:A("toolJsonViewMode",e=>R.getState().setToolJsonViewMode(e))}),timeFormatPreference:f({scope:"profile",parse:pe(["auto","12h","24h"]),ui:A("timeFormatPreference",e=>R.getState().setTimeFormatPreference(e))}),weekStartPreference:f({scope:"profile",parse:pe(["auto","sunday","monday"]),ui:A("weekStartPreference",e=>R.getState().setWeekStartPreference(e))}),messageStreamTransport:f({scope:"profile",parse:pe(["auto","ws","sse"]),ui:Kt("settingsMessageStreamTransport")}),diffLayoutPreference:f({scope:"profile",parse:pe(["dynamic","inline","side-by-side"]),ui:A("diffLayoutPreference",e=>R.getState().setDiffLayoutPreference(e))}),diffWrapLines:f({scope:"profile",parse:I,ui:A("diffWrapLines",e=>R.getState().setDiffWrapLines(e))}),diffHideWhitespace:f({scope:"profile",parse:I,ui:A("diffHideWhitespace",e=>R.getState().setDiffHideWhitespace(e))}),gitChangesViewMode:f({scope:"profile",parse:pe(["flat","tree"]),ui:A("gitChangesViewMode",e=>R.getState().setGitChangesViewMode(e))}),gitmojiEnabled:f({scope:"profile",parse:I}),defaultFileViewerPreview:f({scope:"profile",parse:I}),directoryShowHidden:f({scope:"profile",parse:I,ui:{read:qI,write:e=>VI(e,{persist:!1}),autoSave:!1}}),filesViewShowGitignored:f({scope:"profile",parse:I,ui:{read:GI,write:e=>_I(e,{persist:!1}),autoSave:!1}}),fileEditorKeymap:f({scope:"profile",parse:ZL,ui:A("fileEditorKeymap",e=>R.getState().setFileEditorKeymap(e))}),fileEditorVimMappings:f({scope:"profile",parse:Ka(1e4),ui:A("fileEditorVimMappings",e=>R.getState().setFileEditorVimMappings(e))}),autoSaveEnabled:f({scope:"profile",parse:I,ui:A("autoSaveEnabled",e=>R.getState().setAutoSaveEnabled(e))}),fileEditorWrapLines:f({scope:"profile",parse:I,ui:A("fileEditorWrapLines",e=>R.getState().setFileEditorWrapLines(e))}),confirmFileTreeMove:f({scope:"profile",parse:I,ui:A("confirmFileTreeMove",e=>R.getState().setConfirmFileTreeMove(e))}),fileTreeSide:f({scope:"profile",surfaces:["web","desktop"],parse:pe(["left","right"]),ui:A("fileTreeSide",e=>R.getState().setFileTreeSide(e))}),layoutAnimations:f({scope:"profile",surfaces:["web","desktop"],parse:I,ui:A("layoutAnimations",e=>R.getState().setLayoutAnimations(e))}),openLinksInBrowserPanel:f({scope:"profile",surfaces:["desktop"],parse:I,ui:A("openLinksInBrowserPanel",e=>R.getState().setOpenLinksInBrowserPanel(e))}),liveBrowserTabLimit:f({scope:"profile",surfaces:["desktop"],parse:hl(ik,rk),ui:A("liveBrowserTabLimit",e=>R.getState().setLiveBrowserTabLimit(e))}),openTrackerLinksOnBoard:f({scope:"profile",surfaces:["web","desktop","mobile"],parse:I,ui:A("openTrackerLinksOnBoard",e=>R.getState().setOpenTrackerLinksOnBoard(e))}),terminalCloseOnExit:f({scope:"profile",surfaces:["web","desktop","mobile"],parse:I,ui:A("terminalCloseOnExit",e=>R.getState().setTerminalCloseOnExit(e))}),autoCreateWorktree:f({scope:"profile",parse:I}),sessionTabsEnabled:f({scope:"profile",surfaces:["web","desktop","vscode"],parse:I,ui:A("sessionTabsEnabled",e=>R.getState().setSessionTabsEnabled(e))}),sessionTabsPerWorkspace:f({scope:"profile",surfaces:["web","desktop"],parse:I,ui:A("sessionTabsPerWorkspace",e=>R.getState().setSessionTabsPerWorkspace(e))}),allowPromptingSubagentSessions:f({scope:"profile",parse:I,ui:A("allowPromptingSubagentSessions",e=>R.getState().setAllowPromptingSubagentSessions(e))}),inputSpellcheckEnabled:f({scope:"profile",parse:I,ui:A("inputSpellcheckEnabled",e=>R.getState().setInputSpellcheckEnabled(e))}),enterToSend:f({scope:"profile",parse:I,ui:A("enterToSend",e=>R.getState().setEnterToSend(e))}),enterToSendConfigured:f({scope:"profile",parse:I,ui:A("enterToSendConfigured",e=>R.getState().setEnterToSendConfigured(e))}),mobileReturnKeySends:f({scope:"profile",parse:I,ui:A("mobileReturnKeySends",e=>R.getState().setMobileReturnKeySends(e))}),largeTextPasteBehavior:f({scope:"profile",parse:KL,ui:A("largeTextPasteBehavior",e=>R.getState().setLargeTextPasteBehavior(e))}),savePastedImagesAsFiles:f({scope:"profile",parse:I,ui:A("savePastedImagesAsFiles",e=>R.getState().setSavePastedImagesAsFiles(e))}),followUpBehavior:f({scope:"profile",parse:jL,ui:{read:()=>Ed.getState().followUpBehavior,write:e=>Ed.getState().setFollowUpBehavior(e),autoSave:!1}}),queueModeEnabled:f({scope:"profile",parse:I}),inputHistoryScope:f({scope:"profile",parse:UL,ui:{read:()=>mo.getState().scope,write:e=>mo.getState().applyScope(e),autoSave:!1}}),inputHistoryLimit:f({scope:"profile",parse:WL,ui:{read:()=>mo.getState().entryLimit,write:e=>mo.getState().applyEntryLimit(e),autoSave:!1}}),draftStarters:f({scope:"profile",parse:GL,ui:{read:()=>R.getState().globalDraftStarters??void 0,write:(e,t)=>R.getState().setGlobalDraftStarters(JL(e,t)),autoSave:!1}}),draftStartersVisible:f({scope:"profile",parse:I,ui:A("draftStartersVisible",e=>R.getState().setDraftStartersVisible(e))}),draftStartersCraftGoalAdded:f({scope:"profile",parse:I}),draftStartersScheduleTaskAdded:f({scope:"profile",parse:I}),fontSize:f({scope:"profile",perSurface:!0,parse:Ns,ui:A("fontSize",e=>R.getState().setFontSize(e))}),chatFontSize:f({scope:"profile",perSurface:!0,parse:Ns,ui:A("chatFontSize",e=>R.getState().setChatFontSize(e))}),terminalFontSize:f({scope:"profile",perSurface:!0,parse:Ns,ui:A("terminalFontSize",e=>R.getState().setTerminalFontSize(e))}),editorFontSize:f({scope:"profile",perSurface:!0,parse:Ns,ui:A("editorFontSize",e=>R.getState().setEditorFontSize(e))}),uiFont:f({scope:"profile",parse:qL,ui:A("uiFont",e=>R.getState().setUiFont(e))}),monoFont:f({scope:"profile",parse:VL,ui:A("monoFont",e=>R.getState().setMonoFont(e))}),customUiFont:f({scope:"profile",parse:Ka(100),ui:A("customUiFont",e=>R.getState().setCustomUiFont(e))}),customMonoFont:f({scope:"profile",parse:Ka(100),ui:A("customMonoFont",e=>R.getState().setCustomMonoFont(e))}),uiFontWeight:f({scope:"profile",parse:pe(Ez),ui:A("uiFontWeight",e=>R.getState().setUiFontWeight(e))}),padding:f({scope:"profile",perSurface:!0,parse:Ns,ui:A("padding",e=>R.getState().setPadding(e))}),cornerRadius:f({scope:"profile",perSurface:!0,parse:Ns,ui:A("cornerRadius",e=>R.getState().setCornerRadius(e))}),shortcutOverrides:f({scope:"profile",parse:bL,ui:A("shortcutOverrides",yt("shortcutOverrides"))}),defaultModel:f({scope:"profile",parse:qe}),defaultVariant:f({scope:"profile",parse:qe}),defaultAgent:f({scope:"profile",parse:qe}),smallModelUseDefault:f({scope:"profile",parse:I}),smallModelOverride:f({scope:"profile",parse:qe}),smallModelVariant:f({scope:"profile",parse:qe}),walkthroughModelOverride:f({scope:"profile",parse:qe}),walkthroughModelVariant:f({scope:"profile",parse:qe}),fallbackModel:f({scope:"profile",parse:qe}),fallbackVariant:f({scope:"profile",parse:qe}),accountSwitchProviders:f({scope:"profile",parse:Ja}),zenModel:f({scope:"profile",parse:ha}),favoriteModels:f({scope:"profile",parse:wl(64),ui:A("favoriteModels",yt("favoriteModels"),{autoSave:!1})}),hiddenModels:f({scope:"profile",parse:wl(1024),ui:A("hiddenModels",yt("hiddenModels"),{autoSave:!1})}),collapsedModelProviders:f({scope:"profile",parse:Ja,ui:A("collapsedModelProviders",yt("collapsedModelProviders"),{autoSave:!1})}),customProviderIcons:f({scope:"profile",parse:uL,ui:A("customProviderIcons",yt("customProviderIcons"),{autoSave:!1})}),customProviderLogos:f({scope:"profile",parse:gL,ui:A("customProviderLogos",yt("customProviderLogos"),{autoSave:!1})}),recentModels:f({scope:"profile",parse:wl(16),ui:A("recentModels",yt("recentModels"),{autoSave:!1})}),lastSelectedModel:f({scope:"profile",parse:qe,ui:A("lastSelectedModel",yt("lastSelectedModel"))}),recentAgents:f({scope:"profile",parse:Ja,ui:A("recentAgents",yt("recentAgents"),{autoSave:!1})}),favoriteAgents:f({scope:"profile",parse:Ja,ui:A("favoriteAgents",yt("favoriteAgents"),{autoSave:!1})}),recentEfforts:f({scope:"profile",parse:hL,ui:A("recentEfforts",yt("recentEfforts"),{autoSave:!1})}),lastUsedEfforts:f({scope:"profile",parse:fL,ui:A("lastUsedEfforts",yt("lastUsedEfforts"),{autoSave:!1})}),providerOrder:f({scope:"profile",parse:Ja,ui:A("providerOrder",e=>R.getState().setProviderOrder(e))}),sessionRecapEnabled:f({scope:"profile",parse:I,ui:A("sessionRecapEnabled",e=>R.getState().setSessionRecapEnabled(e))}),sessionSuggestionEnabled:f({scope:"profile",parse:I,ui:A("sessionSuggestionEnabled",e=>R.getState().setSessionSuggestionEnabled(e))}),sessionWorkEnabled:f({scope:"profile",parse:I,ui:A("sessionWorkEnabled",e=>R.getState().setSessionWorkEnabled(e))}),sessionReviewOfferEnabled:f({scope:"profile",surfaces:["web","desktop","mobile"],parse:I,ui:A("sessionReviewOfferEnabled",e=>R.getState().setSessionReviewOfferEnabled(e))}),sessionGoalEnabled:f({scope:"profile",parse:I,ui:A("sessionGoalEnabled",e=>R.getState().setSessionGoalEnabled(e))}),sessionGoalChecker:f({scope:"profile",surfaces:["web","desktop","mobile"],parse:pe(["classifier","small-model"]),ui:A("sessionGoalChecker",e=>R.getState().setSessionGoalChecker(e))}),sessionGoalMaxAutoTurns:f({scope:"profile",surfaces:["web","desktop","mobile"],parse:G(w().refine(Jb)),ui:A("sessionGoalMaxAutoTurns",e=>R.getState().setSessionGoalMaxAutoTurns(e))}),sessionGoalDefaultBudgetEnabled:f({scope:"profile",parse:I,ui:A("sessionGoalDefaultBudgetEnabled",e=>R.getState().setSessionGoalDefaultBudgetEnabled(e))}),sessionGoalDefaultBudget:f({scope:"profile",parse:rL,ui:A("sessionGoalDefaultBudget",e=>R.getState().setSessionGoalDefaultBudget(e))}),summarizeLastMessage:f({scope:"profile",parse:I,ui:A("summarizeLastMessage",e=>R.getState().setSummarizeLastMessage(e))}),summaryThreshold:f({scope:"profile",parse:fl(0),ui:A("summaryThreshold",e=>R.getState().setSummaryThreshold(e))}),summaryLength:f({scope:"profile",parse:fl(10),ui:A("summaryLength",e=>R.getState().setSummaryLength(e))}),maxLastMessageLength:f({scope:"profile",parse:fl(10),ui:A("maxLastMessageLength",e=>R.getState().setMaxLastMessageLength(e))}),showDeletionDialog:f({scope:"profile",parse:I,ui:A("showDeletionDialog",e=>R.getState().setShowDeletionDialog(e))}),nativeNotificationsEnabled:f({scope:"profile",parse:I,ui:A("nativeNotificationsEnabled",e=>R.getState().setNativeNotificationsEnabled(e))}),notificationMode:f({scope:"profile",parse:pe(["always","hidden-only"]),ui:A("notificationMode",e=>R.getState().setNotificationMode(e))}),notifyOnSubtasks:f({scope:"profile",parse:I,ui:A("notifyOnSubtasks",e=>R.getState().setNotifyOnSubtasks(e))}),notifyOnCompletion:f({scope:"profile",parse:I,ui:A("notifyOnCompletion",e=>R.getState().setNotifyOnCompletion(e))}),notifyOnPullRequests:f({scope:"profile",parse:I,ui:A("notifyOnPullRequests",e=>R.getState().setNotifyOnPullRequests(e))}),notifyOnError:f({scope:"profile",parse:I,ui:A("notifyOnError",e=>R.getState().setNotifyOnError(e))}),notifyOnQuestion:f({scope:"profile",parse:I,ui:A("notifyOnQuestion",e=>R.getState().setNotifyOnQuestion(e))}),notificationTemplates:f({scope:"profile",parse:wL,ui:A("notificationTemplates",e=>R.getState().setNotificationTemplates(e))}),showOpenCodeUpdateNotifications:f({scope:"profile",parse:I,ui:A("showOpenCodeUpdateNotifications",e=>R.getState().setShowOpenCodeUpdateNotifications(e))}),reportUsage:f({scope:"profile",parse:I,ui:A("reportUsage",e=>R.getState().setReportUsage(e))}),usageDisplayMode:f({scope:"profile",parse:pe(["usage","remaining"])}),usageDropdownProviders:f({scope:"profile",parse:bl}),usageSelectedModels:f({scope:"profile",parse:kl}),usageCollapsedFamilies:f({scope:"profile",parse:kl}),usageExpandedFamilies:f({scope:"profile",parse:kl}),usageModelGroups:f({scope:"profile",parse:vL}),globalBehaviorPrompt:f({scope:"profile",parse:Ka(1024*1024)}),responseStyleEnabled:f({scope:"profile",parse:I}),responseStylePreset:f({scope:"profile",parse:pe(BL)}),responseStyleCustomInstructions:f({scope:"profile",parse:Ka(5e4)}),pwaAppName:f({scope:"instance",surfaces:["web"],parse:EL}),pwaOrientation:f({scope:"instance",surfaces:["web"],parse:pe(["system","portrait","landscape"])}),mobileKeyboardMode:f({scope:"device",surfaces:["mobile"],parse:HL,ui:A("mobileKeyboardMode",e=>R.getState().setMobileKeyboardMode(e))}),desktopWindowControlsPosition:f({scope:"device",surfaces:["desktop"],parse:FL,ui:A("desktopWindowControlsPosition",e=>R.getState().setDesktopWindowControlsPosition(e))}),desktopWindowControlsStyle:f({scope:"device",surfaces:["desktop"],parse:pe(["classic","traffic-lights"]),ui:A("desktopWindowControlsStyle",e=>R.getState().setDesktopWindowControlsStyle(e))}),inputBarOffset:f({scope:"device",surfaces:["mobile","web"],parse:Ns,ui:A("inputBarOffset",e=>R.getState().setInputBarOffset(e))})},$L=e=>Object.prototype.hasOwnProperty.call(pi,e),ui=Object.keys(pi).filter($L),Ay=e=>pi[e].scope==="device",gi=e=>pi[e],QL=e=>!pi[e].computed&&!Ay(e),YL=ke(c(),ne()),XL=e=>{const t=YL.safeParse(e);if(!t.success)return null;const s=t.data,a={};for(const n of ui){const i=gi(n).parse(s[n],s);i!==void 0&&Object.assign(a,{[n]:i})}return a},eq=(e,t)=>e===t?!0:e===void 0||t===void 0?!1:JSON.stringify(e)===JSON.stringify(t),tq=e=>{for(const t of ui){const s=gi(t);if(!s.ui)continue;const a=e[t];a!==void 0&&(eq(s.ui.read(),a)||s.ui.write(a,e))}},sq=ui.filter(e=>gi(e).ui?.autoSave===!0),P$=()=>{const e={};for(const t of sq){const a=gi(t).ui?.read();a!==void 0&&Object.assign(e,{[t]:a})}return e},aq=ui.filter(e=>{const t=gi(e);return t.scope!=="device"&&!t.secret&&!t.computed}),zy=e=>{if(!(typeof window>"u")&&!(typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0))try{window.__OPENCHAMBER_HOME__=e}catch{}},nh="openchamber.settingsMirror.v2.index",nq="openchamber.deviceSeeded.v1:",oq=e=>`${nq}${encodeURIComponent(e)}`,iq=(e,t)=>{const s=oq(t);let a=!1;try{a=localStorage.getItem(s)===null,a&&localStorage.setItem(s,String(Date.now()))}catch{a=!1}if(a)return e;const n={};for(const o of ui)e[o]===void 0||Ay(o)||Object.assign(n,{[o]:e[o]});return n},rq="openchamber.settingsMirror.v2:",cq=5,Md=e=>`${rq}${encodeURIComponent(e)}`,Fs=(e,t)=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)},lq=(e,t)=>{const s={};for(const o of aq)e[o]!==void 0&&Object.assign(s,{[o]:e[o]});localStorage.setItem(Md(t),JSON.stringify(s));let a=[];try{const o=JSON.parse(localStorage.getItem(nh)??"[]");Array.isArray(o)&&(a=o.filter(i=>typeof i=="string"))}catch{a=[]}const n=[t,...a.filter(o=>o!==t)].slice(0,cq);for(const o of a)n.includes(o)||localStorage.removeItem(Md(o));localStorage.setItem(nh,JSON.stringify(n))},dq=e=>{if(!(typeof window>"u")){if(lq(e,N()),Fs("lastDirectory",e.lastDirectory||null),e.homeDirectory?(localStorage.setItem("homeDirectory",e.homeDirectory),zy(e.homeDirectory)):localStorage.removeItem("homeDirectory"),Array.isArray(e.projects)&&e.projects.length>0?localStorage.setItem("projects",JSON.stringify(e.projects)):localStorage.removeItem("projects"),e.activeProjectId?localStorage.setItem("activeProjectId",e.activeProjectId):localStorage.removeItem("activeProjectId"),Array.isArray(e.pinnedDirectories)&&e.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(e.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"),Array.isArray(e.projects)&&e.projects.length>0){const t=e.projects.filter(s=>s.sidebarCollapsed===!0).map(s=>s.id).filter(s=>typeof s=="string"&&s.length>0);t.length>0?localStorage.setItem("oc.sessions.projectCollapse",JSON.stringify(t)):localStorage.removeItem("oc.sessions.projectCollapse")}else localStorage.removeItem("oc.sessions.projectCollapse");if(typeof e.gitmojiEnabled=="boolean"?localStorage.setItem("gitmojiEnabled",String(e.gitmojiEnabled)):localStorage.removeItem("gitmojiEnabled"),typeof e.directoryShowHidden=="boolean"?localStorage.setItem("directoryTreeShowHidden",e.directoryShowHidden?"true":"false"):localStorage.removeItem("directoryTreeShowHidden"),typeof e.filesViewShowGitignored=="boolean"?localStorage.setItem("filesViewShowGitignored",e.filesViewShowGitignored?"true":"false"):localStorage.removeItem("filesViewShowGitignored"),Fs("openInAppId",typeof e.openInAppId=="string"&&e.openInAppId.length>0?e.openInAppId:null),typeof e.pwaAppName=="string"){const t=e.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);t.length>0?localStorage.setItem("openchamber.pwaName",t):localStorage.removeItem("openchamber.pwaName")}else localStorage.removeItem("openchamber.pwaName");if(ak(e.mobileKeyboardMode),typeof e.openCodeUpdateToastDismissedVersion=="string"){const t=e.openCodeUpdateToastDismissedVersion.trim();t?localStorage.setItem("opencode-update-toast-dismissed-version",t):localStorage.removeItem("opencode-update-toast-dismissed-version")}else localStorage.removeItem("opencode-update-toast-dismissed-version");typeof e.dictationEnabled=="boolean"?localStorage.setItem("dictationEnabled",String(e.dictationEnabled)):localStorage.removeItem("dictationEnabled"),e.dictationAutoSend!==void 0?localStorage.setItem("dictationAutoSend",String(e.dictationAutoSend)):localStorage.removeItem("dictationAutoSend"),e.sttProvider==="local"||e.sttProvider==="openai-compatible"?localStorage.setItem("sttProvider",e.sttProvider):localStorage.removeItem("sttProvider"),Fs("sttServerUrl",typeof e.sttServerUrl=="string"?e.sttServerUrl:null),Fs("sttEndpointPath",e.sttEndpointPath??null),Fs("sttModel",typeof e.sttModel=="string"?e.sttModel:null),Fs("sttLocalModel",typeof e.sttLocalModel=="string"?e.sttLocalModel:null),Fs("sttLanguage",typeof e.sttLanguage=="string"?e.sttLanguage:null),Fs("sttCorrectTranscript",e.sttCorrectTranscript===void 0?null:String(e.sttCorrectTranscript))}},Bd=(e,t,s=t)=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:{settings:e,bootstrap:t,adoptTheme:s}}))};let Ld="idle",Qi=null;const qd=new Set,pq=()=>Ld,uq=e=>(qd.add(e),()=>qd.delete(e)),gq=e=>{pc(),qt(e)},qt=e=>{Qi&&(clearTimeout(Qi),Qi=null);const t=e==="saved"?"idle":e;t!==Ld&&(Ld=t,qd.forEach(s=>s())),t==="error"&&(Qi=setTimeout(()=>qt("saved"),6e3)),!(typeof window>"u")&&window.dispatchEvent(new CustomEvent("openchamber:settings-save-state",{detail:e}))},Ry=()=>{const e=R.persist;if(e&&typeof e=="object")return e},Iy=()=>On()?.settings??null,jy=()=>`/api/config/settings?${xk}=${ic()}`,mq=e=>{tq(e)},qr=e=>XL(e);class hq{revision=0;mutations=[];operations=new Set;record(t){if(this.revision+=1,this.operations.size>0){const s=this.mutations.at(-1),a=s?[...this.operations].some(n=>n.revision>=s.revision):!0;s&&!a?(s.revision=this.revision,s.changes={...s.changes,...t}):this.mutations.push({revision:this.revision,changes:t})}return this.revision}begin(t=this.revision){const s={revision:t};return this.operations.add(s),s}reconcile(t,s){let a=t;for(const n of this.mutations)n.revision<=s.revision||(a={...a,...n.changes});return a}finish(t){if(!this.operations.delete(t))return;if(this.operations.size===0){this.mutations=[];return}const s=Math.min(...[...this.operations].map(({revision:a})=>a));this.mutations=this.mutations.filter(a=>a.revision>s)}reset(){this.mutations=[],this.operations.clear()}}let ku=0,Zs=null,Tn={},Vd=!1;const fq=()=>Vd,Ud=e=>{Vd=!0;try{mq(e)}finally{Vd=!1}};let wa=null,Ht=null,ss=null,lt=null,jo=[],oh=!1,Vr=0,hr=[];const ft=new hq,bq=2e3,kq=200,wu=()=>({runtimeKey:N(),generation:ku}),dc=e=>Object.keys(e),Oy=(e,t)=>e===t?!0:e===void 0||t===void 0?!1:JSON.stringify(e)===JSON.stringify(t),fr=e=>{Tn={...Tn,...e}},wq=e=>{const t={...Tn};for(const s of e)delete t[s];Tn=t},yq=e=>{const t={};for(const s of dc(e))Oy(e[s],Tn[s])||Object.assign(t,{[s]:e[s]});return t},Xo=(e,t)=>e.runtimeKey===t.runtimeKey&&e.generation===t.generation,Dy=e=>{let t=null;for(const s of hr)Xo(s.context,e)&&(t={...t??{},...s.changes});return Ht&&ss&&Xo(ss,e)&&(t={...t??{},...Ht}),t},ih=(e,t)=>{const s=Dy(t);return e&&s?{...e,...s}:e},Fe=e=>e.generation===ku&&e.runtimeKey===N(),no=()=>{Ht&&(lt&&(clearTimeout(lt),lt=null),Ur({keepalive:!0}))},pc=()=>{if(!(oh||typeof window>"u")){oh=!0,Jr(e=>{e.runtimeKey!==e.previousRuntimeKey&&(lt&&clearTimeout(lt),Ht&&Ur())}),$r(e=>{e.runtimeKey!==e.previousRuntimeKey&&(ku+=1,ft.reset(),Vr=0,Zs=null,wa=null,Tn={},qt("saved"))});try{window.addEventListener("pagehide",no,{capture:!0}),window.addEventListener("beforeunload",no,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&no()}),document.addEventListener("freeze",no)),Oa()&&Ge(async()=>{const{App:e}=await import("./vendor-capacitor-app-BrDJj9I_.js");return{App:e}},__vite__mapDeps([122,4,108])).then(({App:e})=>e.addListener("appStateChange",({isActive:t})=>{t||no()})).catch(()=>{})}catch{}}},Ny=async(e=wu())=>{if(pc(),Zs&&Xo(Zs.context,e)&&Date.now()-Zs.at<bq)return ih(Zs.value,e);if(wa&&Xo(wa.context,e))return wa.promise;const t=ft.begin(),s=Dy(e),a=o=>{if(!Fe(e)||!o)return null;const i=ih(ft.reconcile({...o,...s},t),e);Zs={value:i,at:Date.now(),context:e};const r={};for(const l of dc(o))Oy(o[l],i?.[l])&&Object.assign(r,{[l]:o[l]});return fr(r),i},n={context:e,promise:(async()=>{const o=Iy();if(o)try{const i=await o.load();if(!Fe(e))return null;const r=qr(i.settings);return a(r)}catch(i){if(!Fe(e))return null;console.warn("Failed to load shared settings from runtime settings API:",i)}if(!Fe(e))return null;try{const i=await T(jy(),{method:"GET",headers:{Accept:"application/json"}});if(!Fe(e)||!i.ok)return null;const r=await i.json().catch(()=>null);if(!Fe(e))return null;const l=qr(r);return a(l)}catch(i){return Fe(e)&&console.warn("Failed to load shared settings from server:",i),null}})()};return wa=n,n.promise.finally(()=>{ft.finish(t),wa===n&&(wa=null)}),n.promise},vq=async e=>{const t=e?.bootstrap!==!1,s=e?.adoptTheme??t;if(typeof window>"u")return;pc();const a=wu(),n=ft.begin(),o=[Ry(),Bt.persist],i=u=>!u?.hasHydrated||u.hasHydrated()||!u.onFinishHydration?Promise.resolve():new Promise(g=>{let h=!1;const b=()=>{h||(h=!0,g())},k=u.onFinishHydration(()=>{k?.(),b()});u.hasHydrated?.()&&b()}),r=()=>Promise.all(o.map(i)).then(()=>{}),l=u=>!Ht||!ss||!Fe(ss)?u:{...u,...Ht},p=async u=>{if(!Fe(a))return;let g=l(ft.reconcile(u,n));if(await r(),!!Fe(a)){g=iq(l(ft.reconcile(u,n)),a.runtimeKey);try{dq(g)}catch(h){console.warn("persistToLocalStorage failed:",h)}try{Ud(g)}catch(h){console.warn("applyDesktopUiPreferences failed:",h)}Bd(g,t,s)}};try{const u=await Ny(a);u&&Fe(a)?await p(u):Fe(a)&&window.dispatchEvent(new Event("openchamber:settings-sync-failed"))}catch(u){Fe(a)&&window.dispatchEvent(new Event("openchamber:settings-sync-failed")),console.warn("Failed to synchronise settings:",u)}finally{ft.finish(n)}};async function Ur({keepalive:e=!1}={}){let t=!1;const s=Ht,a=ss,n=Vr,o=jo;Ht=null,ss=null,Vr=0,lt=null,jo=[];try{if(!s||!a||Object.keys(s).length===0||!Fe(a)){t=!0,qt("saved");return}const i=ft.begin(n),r={context:a,changes:{...s}};hr.push(r),fr(s);const l=()=>wq(dc(s));try{const p=Iy();if(p)try{const u=qr(await p.save(s));if(!Fe(a))return;if(u){fr(u);const g=ft.reconcile(u,i);Ud(g),Bd(g,!1),Zs=null}u||l(),t=!!u,qt(u?"saved":"error");return}catch(u){if(!Fe(a))return;console.warn("Failed to update settings via runtime settings API:",u)}if(!Fe(a))return;try{const u=await T(jy(),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(s),keepalive:e});if(!Fe(a))return;if(!u.ok){console.warn("Failed to update shared settings via API:",u.status,u.statusText),l(),qt("error");return}const g=qr(await u.json().catch(()=>null));if(!Fe(a))return;if(g){fr(g);const h=ft.reconcile(g,i);Ud(h),Bd(h,!1),t=!0,qt("saved"),Zs=null}else l(),qt("error")}catch(u){Fe(a)&&(console.warn("Failed to update shared settings via API:",u),l(),qt("error"))}}finally{hr=hr.filter(p=>p!==r),ft.finish(i)}}finally{o.forEach(i=>i({ok:t}))}}const Cq=()=>Ny(),Xt=async e=>{if(typeof window>"u")return{ok:!1};pc();const t=wu();ss&&!Xo(ss,t)&&(lt&&clearTimeout(lt),Ur());const s={};for(const i of dc(e))QL(i)&&Object.assign(s,{[i]:e[i]});const a=ft.record(s),n=yq({...Ht??{},...s});if(Object.keys(n).length===0){Ht=null,ss=null,lt&&(clearTimeout(lt),lt=null);const i=jo;return jo=[],i.forEach(r=>r({ok:!0})),qt("saved"),{ok:!0}}Ht=n,ss=t,Vr=a,qt("saving"),lt&&clearTimeout(lt);const o=new Promise(i=>{jo.push(i)});return lt=setTimeout(()=>{Ur()},kq),o},Sq=async()=>{if(typeof window>"u")return;const e=Ry();try{const t=await aI();if(!t)return;const s=()=>sI(t);if(e?.hasHydrated?.()){s();return}if(s(),e?.onFinishHydration){const a=e.onFinishHydration(()=>{a?.(),s()})}}catch(t){console.warn("Failed to load appearance preferences:",t)}},x$=Object.freeze(Object.defineProperty({__proto__:null,applyPersistedHomeDirectoryToWindow:zy,getRuntimeSettingsMirrorStorageKey:Md,getSettingsSaveState:pq,initializeAppearancePreferences:Sq,isApplyingServerSettings:fq,loadDesktopSettings:Cq,reportSettingsSaveState:gq,subscribeToSettingsSaveState:uq,syncDesktopSettings:vq,updateDesktopSettings:Xt},Symbol.toStringTag,{value:"Module"})),T$="openchamber:chats",vl=new Map,Fy=new Map,Wd=new Set,Ey=(e,...t)=>[e.replace(/[\\/]+$/,""),...t].join("/");function My(e){const t=je(e);return t?Ey(t,".config","openchamber","chats"):null}function an(e,t){return!e.split("/").some(s=>s===".."||s===".")&&(e===t||e.startsWith(`${t}/`))}function By(){return Fy.get(N())}function Pq(e){const t=je(e),s=By();return!t||!s?null:an(t,s.configured)||an(t,s.canonicalConfigured)?s.configured:an(t,s.legacy)||an(t,s.canonicalLegacy)?s.legacy:null}function xq(e){return Pq(e)!==null}function A$(e,t){if(xq(e))return!0;const s=je(e),a=My(t);return!!(s&&a&&an(s,a))}function Tq(){return By()?.configured??null}function z$(e){return Wd.add(e),()=>Wd.delete(e)}async function mi(){const e=N(),t=vl.get(e);if(t)return t;const s=et.getFilesystemHomeInfo().then(({home:a,chatsRoot:n,canonicalChatsRoot:o,canonicalLegacyChatsRoot:i})=>{const r=My(a),l=je(n)??r;if(!r||!l)throw new Error("Unable to resolve chat directories");const p={configured:l,legacy:r,canonicalConfigured:je(o)??l,canonicalLegacy:je(i)??r};Fy.set(e,p);for(const u of Wd)u();return p}).catch(a=>{throw vl.delete(e),a});return vl.set(e,s),s}async function Aq(){await mi()}async function zq(){return(await mi()).configured}function R$(){return Aq().catch(()=>{})}async function I$(e=new Date){const t=N(),s=await mi();if(N()!==t)throw new Error("Runtime changed while preparing chat directory");const a=[e.getFullYear(),String(e.getMonth()+1).padStart(2,"0"),String(e.getDate()).padStart(2,"0")].join("-"),n=globalThis.crypto?.randomUUID?.()??`${e.getTime()}-${Math.random().toString(36).slice(2)}`,o=Ey(s.configured,a,`session-${n}`);return await et.createDirectory(o),o}async function Ly(e,t,s){const a=je(e);if(!a)return;const n=[t.configured,t.legacy,t.canonicalConfigured,t.canonicalLegacy];if(n.includes(a)||!n.some(i=>an(a,i)))return;const o=await s("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!o.ok&&o.status!==404)throw new Error(`Failed to delete chat directory (${o.status})`)}async function j$(e){if(!je(e))return;const t=N(),s=await mi();if(N()!==t)throw new Error("Runtime changed while deleting chat directory");await Ly(e,s,T)}async function O$(e){const t=await ob(e),s=await mi();if(N()!==e)throw new Error("Runtime changed while preparing chat cleanup");return async a=>{await t(async({fetch:n})=>{await Ly(a,s,n)})}}const Rq=3e4,Iq=40,jq=60,Oq=(e,t,s,a,n,o,i)=>{const r=t.trim(),l=s.trim().toLowerCase();return JSON.stringify([e,r,l,a,n,o,i])},rh=(e,t)=>{try{const s=JSON.parse(e);return Array.isArray(s)&&s[1]===t}catch{return!1}},ch=new WeakMap,lh=(e,t)=>{if(!t){e.waiters=1/0;return}e.waiters+=1,t.addEventListener("abort",()=>{e.waiters-=1,e.waiters===0&&e.abandon()},{once:!0})},Dq=Rt()(jn((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(s,a,n=jq,o){if(!s||s.trim().length===0)return[];const i=s.trim(),r=N(),l=typeof a=="string"?a.trim():"",p=!!o?.includeHidden,u=o?.respectGitignore??!0,g=o?.type==="directory"?"directory":"file",h=Oq(r,i,l,n,p,u,g),b=Date.now(),k=t().cache[h];if(k&&b-k.timestamp<Rq)return k.files;const v=t().inFlight[h];if(v){const W=ch.get(v);return W&&lh(W,o?.signal),v}const P=g==="file"&&(p||!u)?On()?.files:void 0,z=P?t().searchFiles(i,l,n,{type:g}):et.searchFiles(l,{directory:i,limit:n,type:g});let x=!1;const j=new AbortController,V=P?P.search({directory:i,query:l,maxResults:n,includeHidden:p,respectGitignore:u,signal:j.signal}).then(W=>W.map(_=>{const te=_.path.replace(/\\/g,"/"),se=_.preview?.[0]?_.preview[0].replace(/\\/g,"/"):te,Ve=se.split("/").filter(Boolean).pop()||te.split("/").filter(Boolean).pop()||"";return{name:Ve,path:te,relativePath:se,extension:Ve.includes(".")?Ve.split(".").pop()?.toLowerCase():void 0}})).catch(W=>(x=!0,j.signal.aborted||console.warn("Supplemental file search failed; keeping indexed results:",W),[])):Promise.resolve([]),Z=Promise.all([z,V]).then(([W,_])=>{if(_.length===0)return W;const te=new Set(W.map(se=>se.path.replace(/\\/g,"/")));return[...W,..._.filter(se=>te.has(se.path)?!1:(te.add(se.path),!0))].slice(0,n)}).then(W=>(x||e(_=>{if(_.inFlight[h]!==Z)return _;const te={..._.cache,[h]:{files:W,timestamp:Date.now()}},se=_.cacheKeys.filter(Ve=>Ve!==h);for(se.push(h);se.length>Iq;){const Ve=se.shift();Ve&&delete te[Ve]}return{cache:te,cacheKeys:se}}),W)).finally(B);function B(){e(W=>{if(W.inFlight[h]!==Z)return W;const _={...W.inFlight};return delete _[h],{inFlight:_}})}if(e(W=>({inFlight:{...W.inFlight,[h]:Z}})),P){const W={controller:j,waiters:0,abandon:()=>{j.abort(),B()}};ch.set(Z,W),lh(W,o?.signal)}return Z},invalidateDirectory(s){if(!s||s.trim().length===0){e({cache:{},cacheKeys:[],inFlight:{}});return}const a=s.trim();e(n=>{const o={...n.cache},i=n.cacheKeys.filter(p=>rh(p,a)?(delete o[p],!1):!0),r=Object.entries(n.inFlight).filter(([p])=>!rh(p,a)),l=Object.fromEntries(r);return{cache:o,cacheKeys:i,inFlight:l}})},resetForRuntimeSwitch(){e({cache:{},cacheKeys:[],inFlight:{}})}}),{name:"file-search-store"})),Nq=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},Hd="openchamber_stream_perf",Fq=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(Hd)==="1"}catch{return!1}};let qy=Fq(),Vy=!1;const Ma=()=>qy||Vy,Uy=()=>{Ma()||!globalThis.window||(delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState)},dh=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),Wy=()=>{if(!Ma()||typeof window>"u")return null;if(!window.__openchamberStreamPerfState){const e=Date.now();window.__openchamberStreamPerfState={counters:new Map,startedAt:e,lastUpdatedAt:e}}return window.__openchamberStreamPerfState},Hy=e=>Array.from(e.entries()).map(([t,s])=>({metric:t,count:s.count,avg:s.count>0?Number((s.total/s.count).toFixed(3)):0,max:Number(s.max.toFixed(3)),total:Number(s.total.toFixed(3)),last:Number(s.last.toFixed(3))})).sort((t,s)=>s.total-t.total||s.count-t.count),yu=(e,t)=>{const s=Wy();if(!s)return;const a=s.counters.get(e)??{count:0,total:0,max:0,last:0};a.count+=1,a.total+=t,a.max=Math.max(a.max,t),a.last=t,s.counters.set(e,a),s.lastUpdatedAt=Date.now()},Eq=e=>{if(qy=e,!(typeof window>"u"))try{if(e){window.localStorage.setItem(Hd,"1"),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(Hd),Uy()}catch{}},D$=e=>{if(Vy=e,!(typeof window>"u")){if(e){Wy();return}Uy()}},Mq=()=>{typeof window>"u"||(Ma()&&(window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}),window.__openchamberVsCodeStreamPerfState&&(window.__openchamberVsCodeStreamPerfState={...window.__openchamberVsCodeStreamPerfState,counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}))},Bq=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberStreamPerfState;return!Ma()||!e?{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]}:{enabled:!0,startedAt:e.startedAt,lastUpdatedAt:e.lastUpdatedAt,durationMs:Math.max(0,Date.now()-e.startedAt),entries:Hy(e.counters)}},N$=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberVsCodeStreamPerfState;if(!Ma()||!e)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const t=typeof e.startedAt=="number"?e.startedAt:null,s=typeof e.lastUpdatedAt=="number"?e.lastUpdatedAt:null;return{enabled:!0,startedAt:t,lastUpdatedAt:s,durationMs:t?Math.max(0,Date.now()-t):0,entries:Hy(e.counters)}},F$=(e,t=1)=>{yu(e,t)},E$=(e,t)=>{yu(e,t)},M$=e=>{!Ma()||typeof performance>"u"||typeof performance.mark!="function"||performance.mark(`openchamber.${e}`)},B$=(e,t)=>{if(!Ma())return t();const s=dh();try{return t()}finally{yu(e,dh()-s)}};typeof window<"u"&&(window.__openchamberStreamPerformance={setEnabled:Eq,reset:Mq,getSnapshot:Bq});var Lq={};const qq=e=>!e.isHomeReady&&(e.currentDirectory==="/"||e.currentDirectory===""),ph=(e,t)=>qo()?t||"":!Ee()&&t||e,Gy=async()=>{if(Ee()&&!qo())return null;const e=N();try{const t=await zq();return N()!==e?null:(qo()&&await et.createDirectory(t),t)}catch{return null}};let ws=null,Gd=0,_y=!0;const Pt=ci(),uh=Pt.getItem("lastDirectory"),Vq=typeof uh=="string"&&uh.length>0,$a=e=>{try{Dq.getState().invalidateDirectory(e)}catch(t){console.warn("Failed to invalidate file search cache:",t)}},An=e=>je(e)??"",Uq=(e,t)=>{const s=e.trim();return s.startsWith("~")?s==="~"?t||s:(s.startsWith("~/")||s.startsWith("~\\"))&&t?`${t}${s.slice(1)}`:s:s},br=(e,t)=>{const s=Uq(e,t);return An(s)},Wq=()=>{const e=Pt.getItem("homeDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=An(e);return t.length>0?t:null},Hq=()=>{const e=Pt.getItem("lastDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=An(e);return t.length>0?t:null},Gq=()=>{if(typeof process>"u")return null;const e=Lq,t=e?.HOME||e?.USERPROFILE||(e?.HOMEDRIVE&&e?.HOMEPATH?`${e.HOMEDRIVE}${e.HOMEPATH}`:void 0);if(typeof t=="string"&&t.trim().length>0){const a=An(t);return a.length>0?a:null}const s=process?.cwd?.();if(typeof s=="string"&&s.trim().length>0){const a=An(s);return a.length>0?a:null}return null},vu=()=>{if(typeof window<"u"){if(ws)return ws;const t=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(t&&t.length>0)return ws=t,Pt.setItem("homeDirectory",t),t;const s=Wq();if(s&&!Ee())return ws=s,s}const e=Gq();return e||"/"},fo=e=>{const t=je(e);return t&&t!=="/"?t:null},Ky=async()=>{try{const s=await et.getFilesystemHome(),a=fo(s);if(a)return a}catch(s){console.warn("Failed to obtain filesystem home directory:",s)}if(!_y)return"/";try{const s=await et.getSystemInfo(),a=fo(s?.homeDirectory);if(a)return a}catch(s){console.warn("Failed to get home directory from system info:",s)}try{const s=await Tf(),a=fo(s);if(a)return a}catch(s){console.warn("Failed to obtain desktop-integrated home directory:",s)}const e=vu(),t=fo(e);return t||e},_q=()=>{if(!Ee())return null;const e=dp()?.workspaceFolder;if(typeof e!="string"||e.trim().length===0)return null;const t=An(e);return t.length>0?t:null},ei=_q()||vu(),ti=(()=>{const e=Hq();return e&&!Ee()?br(e,ei):Ee()&&!qo()?ei:""})();ti&&et.setDirectory(ti);const Kq=!!(ei&&ei!=="/"&&ti),Cu=Rt()(jn((e,t)=>({currentDirectory:ti,directoryHistory:[ti],historyIndex:0,homeDirectory:ei,hasPersistedDirectory:Vq,isHomeReady:Kq,isSwitchingDirectory:!1,setDirectory:(s,a)=>{const n=ws||t().homeDirectory||Pt.getItem("homeDirectory"),o=br(s,n);Nq()&&console.log("[DirectoryStore] setDirectory called with path:",o),et.setDirectory(o),$a(),e(i=>{const r=i.directoryHistory[i.historyIndex]===o,l=r?i.directoryHistory:[...i.directoryHistory.slice(0,i.historyIndex+1),o];return Pt.setItem("lastDirectory",o),Xt({lastDirectory:o}),{currentDirectory:o,directoryHistory:l,historyIndex:r?i.historyIndex:l.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const s=t();if(s.historyIndex>0){const a=s.historyIndex-1,n=s.directoryHistory[a];et.setDirectory(n),$a(),Pt.setItem("lastDirectory",n),Xt({lastDirectory:n}),e({currentDirectory:n,historyIndex:a,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const s=t();if(s.historyIndex<s.directoryHistory.length-1){const a=s.historyIndex+1,n=s.directoryHistory[a];et.setDirectory(n),$a(),Pt.setItem("lastDirectory",n),Xt({lastDirectory:n}),e({currentDirectory:n,historyIndex:a,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:s,setDirectory:a}=t(),n=ws||t().homeDirectory||vu();if(s===n)return;const o=Hx(s);o&&a(o)},goToNoProjectDirectory:async()=>{const s=N(),a=t().currentDirectory,[n,o]=await Promise.all([ws||t().homeDirectory||Ky(),Gy()]);if(N()!==s||t().currentDirectory!==a)return;const i=ph(n,o);et.setDirectory(i),$a(),Pt.removeItem("lastDirectory"),Xt({lastDirectory:""}),e(r=>{const l=r.directoryHistory[r.historyIndex]===i,p=l?r.directoryHistory:[...r.directoryHistory.slice(0,r.historyIndex+1),i];return{currentDirectory:i,directoryHistory:p,historyIndex:l?r.historyIndex:p.length-1,hasPersistedDirectory:!1,isHomeReady:!0,isSwitchingDirectory:!1}})},synchronizeHomeDirectory:(s,a)=>{const n=t(),o=s;ws=o;const i=n.homeDirectory!==o,r=Pt.getItem("lastDirectory"),l=typeof r=="string"&&r.length>0,p=ph(o,a),u=qq(n)||!l&&(n.currentDirectory==="/"||n.currentDirectory===n.homeDirectory||n.currentDirectory===Tq()||!n.currentDirectory);if(!i&&!u){n.isHomeReady||e({isHomeReady:!0});return}const g=typeof o=="string"&&o!==""&&o!=="/",h=n.currentDirectory?br(n.currentDirectory,o):n.currentDirectory,b=n.directoryHistory.map(x=>br(x,o)),k=b.some((x,j)=>x!==n.directoryHistory[j]),v=!!(h&&h!==n.currentDirectory),P=u&&(!Ee()||qo())&&!a,z={homeDirectory:o,hasPersistedDirectory:l,isHomeReady:g&&!P};if(u?(z.currentDirectory=p,z.directoryHistory=[p],z.historyIndex=0,z.isSwitchingDirectory=!1):(v||k)&&(z.currentDirectory=h,z.directoryHistory=b,z.historyIndex=Math.min(n.historyIndex,b.length-1),z.isSwitchingDirectory=!1),e(()=>z),(u||v)&&g&&!P){const x=u?p:h;et.setDirectory(x),$a(),u||(Pt.setItem("lastDirectory",x),Xt({lastDirectory:x}))}Xt({homeDirectory:o})},resetForRuntimeSwitch:()=>{et.setDirectory(void 0),$a(),e({currentDirectory:"/",directoryHistory:["/"],historyIndex:0,homeDirectory:"/",hasPersistedDirectory:!1,isHomeReady:!1,isSwitchingDirectory:!1})}}),{name:"directory-store"}));let Oo=null;const _d=()=>{const e=++Gd,t=Promise.all([Ky(),Gy()]).then(([s,a])=>{if(e!==Gd)return;const n=fo(s);n&&Pt.setItem("homeDirectory",n),Cu.getState().synchronizeHomeDirectory(s,a)}).finally(()=>{Oo===t&&(Oo=null)});return Oo=t,t},L$=async()=>{Oo&&await Oo,!Cu.getState().isHomeReady&&await _d()};typeof window<"u"&&(_d(),$r(e=>{e.runtimeKey!==e.previousRuntimeKey&&(_y=!1),ws=null,Gd+=1,queueMicrotask(()=>{_d()})}));const Zq=X("type",[d({id:c(),type:m("open")}),d({id:c(),type:m("message"),data:c(),binary:y()}),d({id:c(),type:m("error")}),d({id:c(),type:m("close"),code:w().int(),reason:c()})]),Jq=iC("RuntimeWebSocket"),$q=(e,t,s)=>{const a=new URL(e),n=new URL(t);return a.protocol!=="ws:"&&a.protocol!=="wss:"||a.username||a.password?null:(a.protocol=a.protocol==="wss:"?"https:":"http:",a.origin===n.origin&&a.pathname.startsWith(n.pathname)?{...s}:null)},Qq=e=>{const t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);let s="";for(let a=0;a<t.length;a+=8192)s+=String.fromCharCode(...t.subarray(a,a+8192));return btoa(s)},Yq=(e,t,s=[],a=Jq)=>{if(new Set(s).size!==s.length||s.some(k=>!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(k)))throw new SyntaxError("Invalid WebSocket protocols");const n=crypto.randomUUID();let o=0,i=null,r=!1,l=Promise.resolve(),p=0;const u=(k,v)=>{o!==3&&(o=3,i?.remove().catch(()=>{}),i=null,globalThis.window?.removeEventListener("pagehide",b),h.onclose?.({code:k,reason:v}))},g=()=>{o!==3&&(h.onerror?.(),u(1006,""),r&&a.close({id:n,code:1e3,reason:""}).catch(()=>{}))},h={get readyState(){return o},binaryType:"arraybuffer",onopen:null,onmessage:null,onerror:null,onclose:null,send(k){if(o===0)throw new DOMException("WebSocket is connecting","InvalidStateError");if(o!==1)return;const v=k instanceof ArrayBuffer||ArrayBuffer.isView(k),P=v?k.byteLength:new TextEncoder().encode(k).byteLength;if(p+=P,p>16*1024*1024){g();return}const z=v?Qq(k):k;l=l.then(async()=>{o!==3&&await a.send({id:n,data:z,binary:v})}).catch(g).finally(()=>{p-=P})},close(k=1e3,v=""){if(k!==1e3&&(k<3e3||k>4999||!Number.isInteger(k)))throw new DOMException("Invalid close code","InvalidAccessError");if(new TextEncoder().encode(v).byteLength>123)throw new SyntaxError("Close reason is too long");if(!(o>=2)){if(o=2,!r){u(1e3,"");return}l=l.then(()=>a.close({id:n,code:k,reason:v})).catch(g)}}},b=()=>h.close();return globalThis.window?.addEventListener("pagehide",b),a.addListener("socketEvent",k=>{const v=Zq.safeParse(k);if(!v.success||v.data.id!==n||o===3)return;const P=v.data;switch(P.type){case"open":if(o!==0)return;o=1,h.onopen?.();break;case"message":{if(o!==1)return;let z=P.data;if(P.binary)try{z=Uint8Array.from(atob(P.data),x=>x.charCodeAt(0)).buffer}catch{g();return}h.onmessage?.({data:z});break}case"error":g();break;case"close":u(P.code,P.reason);break}}).then(async k=>{if(o===3){await k.remove();return}i=k,r=!0,l=a.open({id:n,url:e,headers:{...t},protocols:s}),await l}).catch(g),h},Xq=(e,t)=>{const s=Dn();if(s)return s.openWebSocket(WC(e),t);const a=Nn();if(Object.keys(a).length>0&&Oa()){const n=$q(e,vs().api("/"),a);if(n)return Yq(e,n,t)}return jS(new WebSocket(e))},Zy=1,nn=512*1024,Cl=8*1024,eV=0,Qa=1,tV=15e3,zn=new TextEncoder,Su=new TextDecoder,Pu=S(["interactive","command"]),Jy=S(["running","exited","error"]),sV=S(["node","bun"]),xu=X("type",[d({type:m("terminal")}),d({type:m("project-action"),actionId:c(),executionId:c()})]),aV=d({sessionId:c(),cols:w(),rows:w(),status:Jy,mode:Pu.optional(),purpose:xu.optional()}),nV=d({sessionId:c(),cwd:c(),status:S(["running","exited"]),createdAt:w().nullable().optional().transform(e=>e??null),mode:Pu.optional(),purpose:xu.optional()}),gh={mode:Pu.optional(),purpose:xu.optional()},oV=X("t",[d({t:m("hello")}),d({t:m("pong")}),d({t:m("error"),s:c().optional(),message:c().optional(),code:c().optional(),fatal:y().optional()}),d({t:m("snapshot"),s:c(),q:w().int().nonnegative().default(0),history:c().default(""),status:Jy,cols:w().int().positive().optional(),rows:w().int().positive().optional(),exitCode:w().nullish().transform(e=>e??void 0),signal:w().nullable().optional(),runtime:sV.optional(),ptyBackend:c().optional(),...gh}),d({t:m("output"),s:c(),q:w().int().nonnegative(),d:c(),r:c().optional()}),d({t:m("exit"),s:c(),q:w().int().nonnegative(),exitCode:w().nullish().transform(e=>e??void 0),signal:w().nullable().optional()}),d({t:m("restarted"),s:c(),q:w().int().nonnegative(),history:c().default(""),...gh})]),iV=e=>{const t=zn.encode(JSON.stringify(e)),s=new Uint8Array(t.length+1);return s[0]=Zy,s.set(t,1),s},rV=e=>{let t=e instanceof ArrayBuffer?new Uint8Array(e):zn.encode(e);t[0]===Zy&&(t=t.subarray(1));try{return oV.safeParse(JSON.parse(Su.decode(t))).data??null}catch{return null}};class cV extends Error{code;constructor(t,s){super(t),this.name="TerminalRequestError",this.code=s}}const q$=e=>e.cols!==void 0&&e.rows!==void 0?{cols:e.cols,rows:e.rows}:void 0,lV=d({error:c().optional(),code:c().optional()}),uc=async(e,t)=>{const s=lV.safeParse(await e.json().catch(()=>null)).data;return new cV(s?.error??t,s?.code??null)},dV=e=>{const t=zn.encode(e);if(t.byteLength<=nn)return e;let s=t.byteLength-nn;for(;s<t.byteLength&&(t[s]&192)===128;)s+=1;return Su.decode(t.subarray(s))},Kd=e=>{for(let t=0;t<e.length;t+=1){const s=e.charCodeAt(t);if(s>=55296&&s<=56319){const a=e.charCodeAt(++t);if(a<56320||a>57343||Number.isNaN(a))return!1}else if(s>=56320&&s<=57343)return!1}return!0},Zd=e=>{if(e.malformed!==null)return e.malformed;const t=new Uint8Array(e.byteLength);let s=0;for(const a of e.parts)t.set(a.bytes.subarray(a.start,a.end),s),s+=a.end-a.start;return Su.decode(t)},Jd=(e,t)=>{if(t.length>=nn){let a=t.length-nn;for(;a<t.length&&(t[a]&192)===128;)a+=1;const n=t.slice(a);e.parts=[{bytes:n,start:0,end:n.length}],e.byteLength=n.length;return}const s=e.parts.at(-1);if(s&&s.bytes.length===Cl&&s.end+t.length<=s.bytes.length)s.bytes.set(t,s.end),s.end+=t.length;else if(t.length<Cl){const a=new Uint8Array(Cl);a.set(t),e.parts.push({bytes:a,start:0,end:t.length})}else e.parts.push({bytes:t,start:0,end:t.length});for(e.byteLength+=t.length;e.byteLength>nn;){const a=e.parts[0],n=e.byteLength-nn,o=a.start+n;if(o>=a.end){e.byteLength-=a.end-a.start,e.parts.shift();continue}let i=o;for(;i<a.end&&(a.bytes[i]&192)===128;)i+=1;e.byteLength-=i-a.start,a.start=i,a.start===a.end&&e.parts.shift()}},pV=(e,t)=>{if(t){if(e.malformed!==null||!Kd(t)){const s=dV(Zd(e)+t);if(e.parts=[],e.byteLength=0,!Kd(s)){e.malformed=s;return}e.malformed=null,Jd(e,zn.encode(s));return}Jd(e,zn.encode(t))}},mh=e=>{const t={parts:[],byteLength:0,malformed:null};return Kd(e)?e&&Jd(t,zn.encode(e)):t.malformed=e,t},uV=d({sessions:C(ne())});class gV{constructor(t=$y(null)){this.dependencies=t}dependencies;socket=null;opening=null;subscribers=new Map;projections=new Map;reconnectTimer=null;keepaliveTimer=null;idleCloseTimer=null;failures=0;wakeCleanup=null;generation=0;disposed=!1;subscribe(t,s){this.cancelIdleClose();const a={handlers:s,lastSequence:-1},n=this.subscribers.get(t)??new Set,o=n.size===0;n.add(a),this.subscribers.set(t,n);const i=this.projections.get(t);i&&(a.lastSequence=i.sequence,s.onEvent({type:"snapshot",sequence:i.sequence,data:Zd(i.history),cols:i.cols,rows:i.rows,status:i.status,mode:i.mode,purpose:i.purpose,exitCode:i.exitCode,signal:i.signal,runtime:i.runtime,ptyBackend:i.ptyBackend}));const r=this.socket?.readyState===Qa;return this.ensureConnected().then(()=>{const l=this.subscribers.get(t);o&&r&&l===n&&l.size>0&&this.send({t:"attach",v:3,s:t})}).catch(l=>{n.has(a)&&(s.onError?.(l,!1),this.scheduleReconnect())}),()=>{const l=this.subscribers.get(t);if(l?.delete(a),l?.size===0&&(this.subscribers.delete(t),this.projections.delete(t),this.send({t:"detach",v:3,s:t})),this.subscribers.size===0){if(this.cancelReconnect(),this.failures=0,this.socket?.readyState===Qa){this.scheduleIdleClose();return}this.generation+=1,this.opening=null,this.closeSocket()}}}async write(t,s){if(s&&(await this.ensureConnected(),!this.send({t:"write",v:3,s:t,d:s})&&(this.closeSocket(),await this.ensureConnected(),!this.send({t:"write",v:3,s:t,d:s}))))throw new Error("Terminal connection is unavailable")}dispose(){this.disposed=!0,this.generation+=1,this.opening=null,this.subscribers.clear(),this.projections.clear(),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.cancelIdleClose(),this.wakeCleanup?.(),this.wakeCleanup=null,this.closeSocket()}forget(t){this.projections.delete(t)}noteResize(t,s,a){const n=this.projections.get(t);n&&this.projections.set(t,{...n,cols:s,rows:a})}async ensureConnected(){if(this.disposed)throw new Error("Terminal runtime changed");if(this.socket?.readyState===Qa)return;if(this.opening)return await this.opening,this.socket?.readyState===Qa?void 0:this.ensureConnected();const t=this.generation,s=(async()=>{if(await this.dependencies.refreshAuth(),t!==this.generation||this.disposed)throw new Error("Terminal runtime changed");await new Promise((a,n)=>{let o=!1,i=!1,r=!1,l=null;const p=()=>t===this.generation&&!this.disposed&&l!==null&&this.socket===l,u=()=>{r||i||!p()||(r=!0,this.dependencies.clearUrlAuthToken?.())},g=b=>{o||(o=!0,clearTimeout(h),b?n(b):a())},h=setTimeout(()=>{u(),l?.close(),g(new Error("Terminal connection timed out"))},1e4);try{const b=this.dependencies.openSocket();l=b,b.binaryType="arraybuffer",this.socket=b,b.onopen=()=>{if(!p()){b.close(),g(new Error("Terminal runtime changed"));return}i=!0,this.failures=0,this.send({t:"hello",v:3});for(const k of this.subscribers.keys())this.send({t:"attach",v:3,s:k});this.startKeepalive(),g()},b.onmessage=k=>{this.handleMessage(k.data)},b.onerror=()=>{const k=p();k&&u(),g(new Error("Terminal WebSocket failed")),k&&this.subscribers.size>0&&this.scheduleReconnect()},b.onclose=()=>{const k=p();k&&(this.stopKeepalive(),u()),this.socket===b&&(this.socket=null),g(new Error("Terminal WebSocket closed")),k&&this.subscribers.size>0&&this.scheduleReconnect()}}catch(b){g(b instanceof Error?b:new Error("Terminal WebSocket failed")),!this.disposed&&this.subscribers.size>0&&this.scheduleReconnect()}})})();this.opening=s;try{await s}finally{this.opening===s&&(this.opening=null)}}handleMessage(t){const s=rV(t);if(!s||s.t==="hello"||s.t==="pong")return;if(s.t==="error"){const o=new Error(s.message??"Terminal error");o.code=s.code;const i=s.s?[s.s]:[...this.subscribers.keys()];for(const r of i)for(const l of this.subscribers.get(r)??[])l.handlers.onError?.(o,s.fatal===!0);return}if(!s.s)return;const a=this.subscribers.get(s.s);if(!a)return;if(s.t==="snapshot"){const o={sequence:s.q??0,history:mh(s.history??""),cols:s.cols,rows:s.rows,status:s.status,mode:s.mode,purpose:s.purpose,exitCode:s.exitCode,signal:s.signal??null,runtime:s.runtime,ptyBackend:s.ptyBackend};this.projections.set(s.s,o);const i=Zd(o.history);for(const r of a)r.lastSequence=o.sequence,r.handlers.onEvent({type:"snapshot",sequence:o.sequence,data:i,cols:o.cols,rows:o.rows,status:o.status,mode:o.mode,purpose:o.purpose,exitCode:o.exitCode,signal:o.signal,runtime:o.runtime,ptyBackend:o.ptyBackend});return}const n=this.projections.get(s.s);n&&s.q>n.sequence&&(s.t==="output"?(pV(n.history,s.r??s.d),this.projections.set(s.s,{...n,sequence:s.q})):s.t==="exit"?this.projections.set(s.s,{...n,sequence:s.q,status:"exited",exitCode:s.exitCode,signal:s.signal??null}):s.t==="restarted"&&this.projections.set(s.s,{...n,sequence:s.q,history:mh(s.history??""),status:"running",mode:s.mode??n.mode,purpose:s.purpose??n.purpose,exitCode:void 0,signal:null}));for(const o of a)s.q<=o.lastSequence||(o.lastSequence=s.q,s.t==="output"?o.handlers.onEvent({type:"data",sequence:s.q,data:s.d,replayData:s.r}):s.t==="exit"?o.handlers.onEvent({type:"exit",sequence:s.q,exitCode:s.exitCode,signal:s.signal??null}):s.t==="restarted"&&o.handlers.onEvent({type:"snapshot",sequence:s.q,data:s.history??"",status:"running",mode:s.mode??n?.mode,purpose:s.purpose??n?.purpose}))}send(t){if(!this.socket||this.socket.readyState!==Qa)return!1;try{return this.socket.send(iV(t)),!0}catch{return!1}}scheduleReconnect(){if(this.reconnectTimer||this.disposed||this.subscribers.size===0)return;this.failures+=1;const s=typeof document<"u"&&document.visibilityState==="hidden"||typeof navigator<"u"&&!navigator.onLine?6e4:Math.min(500*2**Math.min(this.failures-1,10),8e3);for(const n of this.subscribers.values())for(const o of n)o.handlers.onEvent({type:"reconnecting",attempt:this.failures,maxAttempts:Number.POSITIVE_INFINITY});const a=()=>{typeof document<"u"&&document.visibilityState==="hidden"||typeof navigator<"u"&&!navigator.onLine||(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wakeCleanup?.(),this.wakeCleanup=null,this.ensureConnected().catch(()=>this.scheduleReconnect()))};typeof window<"u"&&window.addEventListener("online",a),typeof document<"u"&&document.addEventListener("visibilitychange",a),this.wakeCleanup=()=>{typeof window<"u"&&window.removeEventListener("online",a),typeof document<"u"&&document.removeEventListener("visibilitychange",a)},this.reconnectTimer=setTimeout(a,s)}scheduleIdleClose(){this.idleCloseTimer||this.disposed||(this.idleCloseTimer=setTimeout(()=>{this.idleCloseTimer=null,!(this.disposed||this.subscribers.size>0)&&(this.generation+=1,this.opening=null,this.closeSocket())},tV))}cancelIdleClose(){this.idleCloseTimer&&(clearTimeout(this.idleCloseTimer),this.idleCloseTimer=null)}startKeepalive(){this.stopKeepalive(),this.keepaliveTimer=setInterval(()=>this.send({t:"ping",v:3}),45e3)}stopKeepalive(){this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.keepaliveTimer=null}cancelReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wakeCleanup?.(),this.wakeCleanup=null}closeSocket(){this.stopKeepalive();const t=this.socket;this.socket=null,t&&(t.readyState===eV||t.readyState===Qa)&&t.close()}}const mV="",Wr=new Map,hV=e=>e===null?"/api/terminal/ws":`/api/terminal/ws?directory=${encodeURIComponent(_f(e))}`;function $y(e){return{refreshAuth:Xr,openSocket:()=>Xq(vs().websocket(hV(e))),clearUrlAuthToken:ii}}function hi(e){const t=zt(e),s=t??mV,a=Wr.get(s);if(a)return a;const n=new gV($y(t));return Wr.set(s,n),n}async function fV(e){const t=await T("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),directory:e.cwd});if(!t.ok)throw await uc(t,"Failed to create terminal session");const s=await t.json().catch(()=>null),a=aV.safeParse(s).data;if(!a)throw new Error("Failed to create terminal session");return a}async function bV(e){const t=await T(`/api/terminal/sessions?cwd=${encodeURIComponent(e)}`,{directory:e});if(!t.ok)throw await uc(t,"Failed to list terminal sessions");const s=await t.json().catch(()=>null),a=uV.safeParse(s).data?.sessions;if(!Array.isArray(a))throw new Error("Failed to list terminal sessions");const n=[];for(const o of a){const i=nV.safeParse(o).data;i&&n.push(i)}return n}async function kV(e,t){e.length!==0&&await qn("/api/terminal/touch","POST",{sessionIds:e},t)}async function wV(){const e=await T("/api/terminal/shells");if(!e.ok)throw await uc(e,"Failed to list terminal shells");const t=await e.json().catch(()=>[]);return Array.isArray(t)?t.filter(s=>s&&typeof s=="object"&&Jp(s.id)&&typeof s.name=="string"&&typeof s.supportsLogin=="boolean"):[]}function yV(e,t,s,a){return hi(a).subscribe(e,{onEvent:t,onError:s})}async function vV(e,t,s){await hi(s).write(e,t)}async function qn(e,t,s,a){const n={method:t,directory:a};s!==void 0&&(n.headers={"Content-Type":"application/json"},n.body=JSON.stringify(s));const o=await T(e,n);if(!o.ok)throw await uc(o,"Terminal command failed");return o}async function CV(e,t,s,a){await qn(`/api/terminal/${e}/resize`,"POST",{cols:t,rows:s},a),hi(a).noteResize(e,t,s)}async function SV(e,t,s){await qn(`/api/terminal/${e}/appearance`,"POST",t,s)}async function PV(e,t){await qn(`/api/terminal/${e}`,"DELETE",void 0,t),hi(t).forget(e)}async function xV(e,t){return(await qn(`/api/terminal/${e}/restart`,"POST",t,t.cwd)).json()}async function TV(e){const s=await(await qn("/api/terminal/force-kill","POST",e,e.cwd)).json().catch(()=>null),a=hi(e.cwd);if(Array.isArray(s?.killedSessionIds))for(const n of s.killedSessionIds)typeof n=="string"&&a.forget(n);else e.sessionId&&a.forget(e.sessionId)}function V$(){for(const e of Wr.values())e.dispose();Wr.clear()}const AV=()=>({async listShells(){return wV()},async listSessions(e){return bV(e)},async touchSessions(e,t){await kV(e,t)},async createSession(e){return fV(e)},connect(e,t,s){const a=yV(e,t.onEvent,t.onError,s);return{close:()=>a()}},async sendInput(e,t,s){await vV(e,t,s)},async resize(e){await CV(e.sessionId,e.cols,e.rows,e.directory)},async updateAppearance(e,t,s){await SV(e,t,s)},async close(e,t){await PV(e,t)},async restartSession(e,t){return xV(e,{cwd:t.cwd??"",cols:t.cols,rows:t.rows,themeMode:t.themeMode,terminalBackground:t.terminalBackground,terminalForeground:t.terminalForeground,shell:t.shell,loginShell:t.loginShell})},async forceKill(e){await TV(e)}});class Tu extends Error{code;status;constructor(t,s,a){super(s),this.name="GitNetworkOperationRequestError",this.code=t,this.status=a}}class Au extends Error{code;status;remoteName;constructor(t,s,a,n){super(s),this.name="GitWorktreeRequestError",this.code=t,this.status=a,this.remoteName=n}}class zV extends Error{provider;constructor(t,s){super(t),this.name="SourceControlInstanceOtherProviderError",this.provider=s}}class RV extends Error{reason;alias;constructor(t,s,a){super(t),this.name="SourceControlInstanceAliasError",this.reason=s,this.alias=a}}const IV=c().trim().min(1).max(200),Do=c().trim().min(1).max(512),Yi=c().trim().max(512).nullable().optional(),jV=d({provider:_s,instance:Do,accountId:Do}).strict(),OV=S(["account","ssh","system","anonymous"]),Rn=d({id:IV,name:Do,userName:Do,userEmail:Do,account:jV.nullable().optional(),transport:OV.optional(),sshCredentialId:Yi,signCommits:y().optional(),signingKey:Yi,color:Yi,icon:Yi}).strict().superRefine((e,t)=>{e.transport==="account"&&!e.account&&t.addIssue({code:"custom",path:["account"],message:"An account transport requires an account"}),e.transport==="ssh"&&!e.sshCredentialId?.trim()&&t.addIssue({code:"custom",path:["sshCredentialId"],message:"An SSH transport requires a managed key"}),e.transport!=="ssh"&&e.sshCredentialId&&t.addIssue({code:"custom",path:["sshCredentialId"],message:"Only an SSH transport names a managed key"})}),U$=e=>e?.transport??"system",DV=C(Rn).max(256).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Git identity profile IDs must be unique"),Qy=d({userName:c().max(512).nullable(),userEmail:c().max(512).nullable()}).strict(),NV=d({success:y(),profile:Rn.nullable()}).strict(),W$=e=>!!e.userName&&!!e.userEmail&&(e.transport==="account"&&!!e.account||e.transport==="anonymous"||e.transport==="system"||e.transport===void 0||e.transport==="ssh"&&!!e.sshCredentialId),$d=new Set,FV=e=>($d.add(e),()=>{$d.delete(e)}),Yy=e=>{for(const t of $d)t(e)},Qd=new Set,EV=(e,t)=>JSON.stringify([t,je(e)]);function H$(e){return Qd.add(e),()=>{Qd.delete(e)}}function MV(e,t){const s=EV(e,t);for(const a of Qd)a(s)}class BV extends Error{reason;constructor(t,s){super(t),this.name="GitPathUnavailableError",this.reason=s}}const LV=d({error:c(),code:S(["path_not_found","nested_repository","untracked_directory"])}),zu=d({headCommit:c().nullable(),indexCommit:c().nullable(),worktreeCommit:c().nullable(),hasTrackedChanges:y(),hasUntrackedFiles:y(),hasConflict:y()}),Ru="GIT_REPOSITORY_UNREADABLE";class Xy extends Error{code=Ru;constructor(t){super(t),this.name="GitRepositoryUnreadableError"}}const D="/api/git",qV=d({original:c(),modified:c()}),ev=d({diff:c()}),VV=d({files:C(d({path:c(),status:c(),previousPath:c().optional(),revision:c().optional()}))}),UV=d({error:c()}),WV=d({error:c(),code:m(Ru)}),HV=d({files:C(d({path:c(),previousPath:c().optional(),changeType:c(),insertions:w(),deletions:w(),isBinary:y()}))}),hh=d({hash:c(),date:c(),message:c(),refs:c(),body:c(),author_name:c(),author_email:c(),filesChanged:w(),insertions:w(),deletions:w(),parents:C(c())}),GV=d({all:C(hh),latest:hh.nullable(),total:w()}),_V=d({diff:c(),submodule:zu.nullable().default(null)}),KV=d({diffs:C(M([d({path:c(),diff:c(),submodule:zu.nullable().default(null)}),d({path:c(),error:c(),code:S(["path_not_found","nested_repository","untracked_directory"]).nullable()})]))}),ZV=d({original:c(),modified:c(),path:c(),isBinary:y().optional(),submodule:zu.nullable().default(null)});async function Iu(e,t){const s=await e.json().catch(()=>null),a=d({code:m("not_repository"),error:c()}).safeParse(s);if(e.status===409&&a.success)return new Error(a.data.error);const n=LV.safeParse(s);return n.success&&(e.status===404||e.status===422)?new BV(n.data.error,n.data.code):new Error(`${t}: ${e.statusText}`)}async function fi(e,t){const s=UV.safeParse(await e.json().catch(()=>null));return new Error(s.success?s.data.error:`${t}: ${e.statusText}`)}const tv=1200,sv=5e3,si=new Map,on=new Map,av=new Map,Hr=new Map,Xi=new Map,JV=256,$V=900*1e3,QV=3600*1e3,bi=8192,YV=/^[A-Za-z0-9_-]{1,200}$/,Yd=/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i,XV=/^[A-Za-z0-9_-]{43}$/,eU=/^SHA256:[A-Za-z0-9+/]{43}=?$/,is=e=>c().trim().min(1).max(e),nv=c().regex(YV),gc=c().regex(XV),qs=is(1024),ju=is(4096),Ie=is(512),ov=c().min(1).max(4096).refine(e=>e.trim()===e&&!Array.from(e).some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127)&&e!==".."&&!e.startsWith("/")&&!e.startsWith("../")&&!e.includes("/../")&&!e.includes("\\")&&!/^[A-Za-z]:\//.test(e),"Checkout path must be repository-relative"),fh=c().max(4096).refine(e=>{if(!e)return!0;try{const t=new URL(e);return!t.username&&!t.password&&!t.search&&!t.hash}catch{return e.includes("://")?!1:!/[?#]/.test(e)}},"Git remote display URLs must not contain credentials, query parameters, or fragments"),tU=C(d({name:Ie,fetchUrl:fh,pushUrl:fh}).strict()).max(256),sU=d({selectionId:nv,provenanceRevision:w().int().safe().positive(),sourceSha:c().regex(Yd),expiresInMs:w().int().safe().positive().max(900*1e3)}).strict(),aU=d({remote:d({name:Ie,endpoint:d({displayUrl:ju,fingerprint:gc}).strict()}).strict(),transportMode:m("managed"),classification:S(["contributor-fork","own-fork","bound-repository","other"])}).strict(),nU=X("kind",[d({kind:m("ordinary")}).strict(),d({kind:m("contributor"),repositoryId:Ie,bindingRevision:w().int().safe().nonnegative(),configRevision:Ie,provenanceRevision:w().int().safe().positive(),candidates:C(aU).max(128)}).strict()]),oU=d({state:m("awaiting-trust"),digest:gc,actions:C(d({kind:S(["post-checkout-hook","project-start-command","setup-command"]),label:c().max(65536)}).strict()).max(3)}).strict(),Vt=new Map,iU=e=>{if(!e.includes("://")){const t=e.match(/^(?:[A-Za-z0-9._-]+@)?[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?:([^\s:\\]+)$/);return!!(t&&!/[?#]/.test(e)&&!t[1].startsWith("-")&&t[1].split("/").every(s=>s&&s!=="."&&s!==".."))}try{const t=new URL(e),s=decodeURIComponent(t.pathname);return(t.protocol==="https:"||t.protocol==="ssh:")&&!t.username&&!t.password&&!t.search&&!t.hash&&!!(t.hostname&&t.pathname&&t.pathname!=="/")&&!/[\0-\x20\x7f\\]/.test(s)&&s.split("/").slice(1).every(a=>a&&a!=="."&&a!=="..")}catch{return!1}},rn=d({displayUrl:ju.refine(iU),fingerprint:gc}).strict(),rU=d({displayName:is(1024),fingerprint:gc}).strict(),cU=d({id:Ie,platform:S(["web","desktop","vscode"]),label:is(512).optional()}).strict(),lU=X("kind",[d({kind:m("provider"),provider:Ie,instance:ju,accountId:Ie,login:Ie.optional()}).strict(),d({kind:m("ssh-key"),fingerprint:c().regex(eU)}).strict()]),Sl=X("mode",[d({mode:m("anonymous"),verification:d({status:m("anonymous")}).strict()}).strict(),d({mode:m("managed"),verification:d({status:m("verified"),method:S(["credential","git-identity"])}).strict(),actor:lU.optional()}).strict(),d({mode:m("system"),verification:d({status:m("unverified"),reason:m("system-credentials")}).strict()}).strict()]),dU=M([Sl,d({fetch:Sl,push:Sl}).strict()]),kr=d({name:Ie,endpoint:rn}).strict(),Pl={repositoryId:Ie,bindingRevision:w().int().safe().nonnegative(),configRevision:Ie,remote:kr,sourceRef:qs,destinationRef:qs},pU=X("operation",[d({operation:m("push"),...Pl,forceWithLease:d({expectedRemoteSha:c().regex(Yd)}).strict().optional(),configureUpstream:y().optional()}).strict(),X("fetchScope",[d({operation:m("fetch"),fetchScope:m("ref").optional(),...Pl}).strict(),d({operation:m("fetch"),fetchScope:m("remote"),repositoryId:Ie,bindingRevision:w().int().safe().nonnegative(),configRevision:Ie,remote:kr,force:y()}).strict()]),d({operation:m("pull"),...Pl}).strict(),d({operation:m("delete-remote-branch"),repositoryId:Ie,bindingRevision:w().int().safe().nonnegative(),configRevision:Ie,remote:kr,destinationRef:qs}).strict(),d({operation:m("checkout-hydration"),repositoryId:Ie,bindingRevision:w().int().safe().nonnegative(),configRevision:Ie,remote:kr,requirements:C(d({kind:S(["submodule","lfs"]),path:ov,endpoint:rn}).strict()).max(256)}).strict(),d({operation:m("sync"),repositoryId:Ie,bindingRevision:w().int().safe().nonnegative(),configRevision:Ie,fetch:d({name:Ie,endpoint:rn,sourceRef:qs,destinationRef:qs}).strict(),pull:d({destinationRef:qs}).strict(),push:d({name:Ie,endpoint:rn,sourceRef:qs,destinationRef:qs,forceWithLease:d({expectedRemoteSha:c().regex(Yd)}).strict().optional()}).strict()}).strict(),d({operation:m("clone"),remote:rn,destination:rU}).strict()]),uU=S(["validated","authenticated","transferred","updated-local-repository","checked-out","cleaned-up"]),mc=S(["INVALID_REQUEST","NOT_FOUND","STALE_REPOSITORY","STALE_BINDING","STALE_CONFIG","REMOTE_CHANGED","REMOTE_URL_USERINFO","AUTHENTICATION_REQUIRED","DESTINATION_SELECTION_REQUIRED","CONTRIBUTOR_MANAGED_TRANSPORT_REQUIRED","AUTHENTICATION_FAILED","TRANSPORT_FAILED","CONFLICT","CANCELLED","TIMEOUT","OUTCOME_UNKNOWN","RUNTIME_UNSUPPORTED","GIT_LFS_CLIENT_MISSING","CHECKOUT_TOO_LARGE","PATH_LENGTH_LIMIT","BRANCH_NAME_CONFLICT","UNKNOWN"]),oo=e=>d({code:S(e),message:is(bi)}).strict(),gU=d({step:S(["fetch","pull","push"]),status:S(["succeeded","skipped","conflicted","failed","cancelled"]),error:d({code:mc,message:is(bi)}).strict().optional()}).strict(),iv=S(["succeeded","authorization-required","invalid","client-missing","failed","cancelled","not-needed"]),mU=["cancelled","invalid","client-missing","authorization-required","failed"],bh=d({path:ov,status:iv,endpoint:rn.optional(),error:d({code:mc,message:is(bi)}).strict().optional()}).strict().superRefine((e,t)=>{(e.status!=="succeeded"&&e.status!=="not-needed")!==(e.error!==void 0)&&t.addIssue({code:"custom",message:"Git hydration status and error do not match"})}),rv=d({status:iv,submodules:C(bh).max(256),lfs:C(bh).max(256)}).strict().superRefine((e,t)=>{const s=[...e.submodules,...e.lfs].map(n=>n.status);let a="succeeded";!s.length||s.every(n=>n==="not-needed")?a="not-needed":a=mU.find(n=>s.includes(n))??"succeeded",e.status!==a&&t.addIssue({code:"custom",message:"Git hydration summary does not match its results"})}),hU=d({status:S(["pending","ready","failed"]),phase:S(["directory-created","git-ready","setup-ready"]).optional(),error:is(bi).nullable(),errorCode:mc.optional(),updatedAt:w().int().safe().nonnegative(),hydration:rv.optional()}).strict().superRefine((e,t)=>{e.status!=="failed"&&(e.errorCode||e.hydration)&&t.addIssue({code:"custom",message:"Only failed worktree bootstrap status may include failure details"})}),Ou=d({error:is(bi),code:mc}).strict(),Es={operationId:nv,runtimeIdentity:cU,transport:dU,target:pU,completedSteps:C(uU),stepResults:C(gU).length(3).optional(),hydration:rv.optional()},fU=X("state",[d({...Es,state:m("planned")}).strict(),d({...Es,state:m("running")}).strict(),d({...Es,state:m("succeeded")}).strict(),d({...Es,state:m("partial"),error:oo(["INVALID_REQUEST","AUTHENTICATION_REQUIRED","AUTHENTICATION_FAILED","TRANSPORT_FAILED","RUNTIME_UNSUPPORTED","GIT_LFS_CLIENT_MISSING","CHECKOUT_TOO_LARGE","UNKNOWN"])}).strict(),d({...Es,state:m("failed"),error:oo(["INVALID_REQUEST","AUTHENTICATION_REQUIRED","AUTHENTICATION_FAILED","TRANSPORT_FAILED","RUNTIME_UNSUPPORTED","GIT_LFS_CLIENT_MISSING","CHECKOUT_TOO_LARGE","UNKNOWN"])}).strict(),d({...Es,state:m("cancelled"),error:oo(["CANCELLED","TIMEOUT"])}).strict(),d({...Es,state:m("outcome-unknown"),error:oo(["OUTCOME_UNKNOWN"])}).strict(),d({...Es,state:m("conflicted"),error:oo(["STALE_REPOSITORY","STALE_BINDING","STALE_CONFIG","REMOTE_CHANGED","CONFLICT"])}).strict()]).superRefine((e,t)=>{e.target.operation==="clone"&&e.state==="partial"&&!e.completedSteps.includes("checked-out")&&t.addIssue({code:"custom",message:"Partial clone must retain a completed checkout"});const s=e.target.operation==="sync",a=e.state!=="planned"&&e.state!=="running";s&&a&&e.stepResults===void 0&&t.addIssue({code:"custom",message:"Sync operation result is missing step results"});for(const n of e.stepResults??[])(n.status!=="succeeded"&&n.status!=="skipped")!==(n.error!==void 0)&&t.addIssue({code:"custom",message:"Git sync step status and error do not match"});!s&&e.stepResults!==void 0&&t.addIssue({code:"custom",message:"Non-sync operation contains sync step results"}),e.state==="succeeded"&&e.hydration&&e.hydration.status!=="succeeded"&&e.hydration.status!=="not-needed"&&t.addIssue({code:"custom",message:"Successful Git operation contains incomplete hydration"}),s!=="fetch"in e.transport&&t.addIssue({code:"custom",message:"Git operation transport does not match its target"})}),cv=e=>e.trim(),ki=(e,t)=>JSON.stringify([e,cv(t)]),hc=(e,t,s)=>JSON.stringify([e,cv(t),s??"full"]),ai=(e,t)=>av.get(ki(e,t))??0,Du=(e,t)=>{const s=ki(e,t);av.set(s,ai(e,t)+1);for(const a of[void 0,"light"]){const n=hc(e,t,a);si.delete(n),on.delete(n)}},bU=(e,t,s)=>JSON.stringify([e,t,s]),Nu=(e=Date.now())=>{for(const[t,s]of Vt){const a=s.terminalState?QV:$V;s.observedAt<=e-a&&Vt.delete(t)}for(;Vt.size>JV;){let t=null;for(const[s,a]of Vt)a.terminalState&&(!t||a.observedAt<t.observedAt)&&(t={key:s,observedAt:a.observedAt});if(!t)for(const[s,a]of Vt)(!t||a.observedAt<t.observedAt)&&(t={key:s,observedAt:a.observedAt});if(!t)return;Vt.delete(t.key)}},Xd=(e,t,s)=>{Nu();for(const[a,n]of Vt)if(n.runtimeKey===e&&n.operationId===t&&(!s||n.runtimeIdentity.id===s))return{key:a,value:n};return null},kU=(e,t)=>{let s=null;for(const[a,n]of Vt)if(n.runtimeKey===e&&n.operationId===t){if(s)return;s=a}s&&Vt.delete(s)},wU=(e,t)=>{Nu();const s=Date.now();for(const a of Vt.values())a.runtimeKey===e&&a.operationId===t&&!a.terminalState&&(a.observedAt=s)},es=(e,t)=>JSON.stringify(e)===JSON.stringify(t),yU=e=>JSON.stringify(e,(t,s)=>{if(t==="forceWithLease")return;if(t!=="displayUrl")return s;const a=c().safeParse(s);if(!a.success||a.data.includes("://"))return s;const n=a.data.match(/^(?:[^@/\s]+@)?([^:/\s]+):(.+)$/);return n?`${n[1]}:${n[2]}`:a.data}),vU=e=>{const t=e.trim();try{const s=new URL(t);return s.username="",s.password="",s.hostname=s.hostname.toLowerCase(),s.search="",s.hash="",s.toString().replace(/\/$/,"")}catch{const s=t.match(/^([^@/:\s]+)@([^/:\s]+):(.+)$/);return s?`${s[1]}@${s[2].toLowerCase()}:${s[3].replace(/[?#].*$/,"")}`:t.replace(/[?#].*$/,"")}},CU=(e,t)=>{if(t.target.operation!==e.operation)throw new Error("Malformed Git network operation plan response");if(e.operation==="sync"){if(!("fetch"in t.transport)||t.transport.fetch.mode!==e.fetch.transportMode||t.transport.push.mode!==e.push.transportMode)throw new Error("Malformed Git network operation plan response");const n={...e.push.remote,sourceRef:e.push.sourceRef,destinationRef:e.push.destinationRef,forceWithLease:e.push.forceWithLease},o={operation:"sync",repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,fetch:{...e.fetch.remote,sourceRef:e.fetch.sourceRef,destinationRef:e.fetch.destinationRef},pull:e.pull,push:n};if(!es(t.target,o))throw new Error("Malformed Git network operation plan response");return}if("fetch"in t.transport)throw new Error("Malformed Git network operation plan response");if(e.operation==="checkout-hydration"){const n=t.target;if(n.operation!=="checkout-hydration"||!es({repositoryId:n.repositoryId,bindingRevision:n.bindingRevision,configRevision:n.configRevision,remote:n.remote},{repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,remote:e.remote}))throw new Error("Malformed Git network operation plan response");return}if(t.transport.mode!==e.transportMode)throw new Error("Malformed Git network operation plan response");if(e.operation==="clone"){const n=t.target;if(n.operation!=="clone")throw new Error("Malformed Git network operation plan response");const o=e.destinationPath.trim().split(/[\\/]/).filter(Boolean).at(-1);if(n.remote.displayUrl!==vU(e.remoteUrl)||n.destination.displayName!==o)throw new Error("Malformed Git network operation plan response");return}if(e.operation==="delete-remote-branch"){if(!es(t.target,{operation:"delete-remote-branch",repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,remote:e.remote,destinationRef:e.destinationRef}))throw new Error("Malformed Git network operation plan response");return}if(e.operation==="fetch"&&e.fetchScope==="remote"){const n=t.target;if(n.operation!=="fetch"||n.fetchScope!=="remote"||!es(n,{operation:"fetch",fetchScope:"remote",repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,remote:e.remote,force:n.force}))throw new Error("Malformed Git network operation plan response");return}const s={repositoryId:e.repositoryId,bindingRevision:e.bindingRevision,configRevision:e.configRevision,remote:e.remote,sourceRef:e.sourceRef,destinationRef:e.destinationRef},a=e.operation==="fetch"?{operation:"fetch",fetchScope:e.fetchScope,...s}:{operation:e.operation,...s};if(e.operation==="push"&&e.forceWithLease&&Object.assign(a,{forceWithLease:e.forceWithLease}),e.operation==="push"&&e.configureUpstream&&Object.assign(a,{configureUpstream:!0}),!es(t.target,a))throw new Error("Malformed Git network operation plan response")},SU=e=>e.target.operation==="clone"?!1:e.state==="succeeded"?!0:e.completedSteps.includes("transferred")||e.completedSteps.includes("updated-local-repository"),ep=(e,t,s=!1)=>"fetch"in e||"fetch"in t?"fetch"in e&&"fetch"in t&&ep(e.fetch,t.fetch,s)&&ep(e.push,t.push,s):e.mode===t.mode&&es(e.verification,t.verification)&&(e.mode!=="managed"||t.mode==="managed"&&(!e.actor||s&&!t.actor||es(e.actor,t.actor)));FV(e=>{Du(N(),e),Hr.delete(ki(N(),e))});const Vn=e=>{Yy(e)},Oe=async(e,t)=>{const s=await t.json();return Vn(e),s};function F(e,t,s){const a={...s};return t&&(a.directory=t),vs().api(e,a)}const PU=15,kh=200,xU=e=>e==="worktrees"?`${D}/project-worktrees`:`${D}/projects`,TU=(e,t)=>JSON.stringify(e==="status"||e==="root"?{directories:t,fields:[e]}:{directories:t}),AU=(e,t)=>`${e}\0${zt(t)??""}`,No=new Map,wh=async e=>{const t=No.get(e);if(No.delete(e),!t)return;if(t.runtimeKey!==N()){const r=new Error("Runtime changed before project repository batch was sent");for(const l of t.waiters.values())for(const p of l)p.reject(r);return}const s=[...t.waiters.keys()],a=new Map;for(const r of s)a.set(r,ai(t.runtimeKey,r));const n=xU(t.field),o=new Map,i=[];for(let r=0;r<s.length;r+=kh)i.push(s.slice(r,r+kh));await Promise.all(i.map(async r=>{try{const l=await T(F(n,r[0]),{method:"POST",headers:{"Content-Type":"application/json"},body:TU(t.field,r)});if(!l.ok)throw new Error(`Failed to read project repositories: ${l.statusText}`);const p=await l.json();for(const u of p?.projects??[])o.set(u.directory,u)}catch(l){const p=l instanceof Error?l.message:"Failed to read project repositories";for(const u of r)o.set(u,{directory:u,error:p})}}));for(const[r,l]of o)typeof l.isGitRepository=="boolean"&&Hr.set(ki(t.runtimeKey,r),{value:l.isGitRepository,expiresAt:Date.now()+sv}),l.status&&ai(t.runtimeKey,r)===a.get(r)&&si.set(hc(t.runtimeKey,r,void 0),{value:l.status,expiresAt:Date.now()+tv});for(const[r,l]of t.waiters){const p=o.get(r)??null;for(const u of l)p?p.error?u.reject(p.code===Ru?new Xy(p.error):new Error(p.error)):p.errors?.includes(t.field)?u.reject(new Error(`Failed to read project ${t.field}`)):u.resolve(p):u.reject(new Error("Project repository read missing from batch response"))}},fc=(e,t)=>{const s=N(),a=AU(t,e),n=No.get(a);n&&n.runtimeKey!==s&&wh(a);let o=No.get(a);o||(o={runtimeKey:s,field:t,waiters:new Map,timer:null},No.set(a,o));const i=o;return new Promise((r,l)=>{const p=i.waiters.get(e)??[];p.push({resolve:r,reject:l}),i.waiters.set(e,p),i.timer===null&&(i.timer=setTimeout(()=>{wh(a)},PU))})};async function zU(e){const t=N(),s=Date.now(),a=e.filter(n=>{const o=hc(t,n,void 0),i=si.get(o);return!(i&&i.expiresAt>s)&&!on.has(o)});await Promise.allSettled(a.map(n=>fc(n,"status")))}async function RU(e){const t=ki(N(),e),s=Date.now(),a=Hr.get(t);if(a&&a.expiresAt>s)return a.value;const n=Xi.get(t);if(n)return n;const o=(async()=>{const r=(await fc(e,"repo")).isGitRepository===!0;return Hr.set(t,{value:r,expiresAt:Date.now()+sv}),r})();Xi.set(t,o);try{return await o}finally{Xi.get(t)===o&&Xi.delete(t)}}class IU extends Error{constructor(){super("Nested git repository discovery is not supported by this runtime"),this.name="GitDirectoriesUnsupportedError"}}async function G$(e){const t=await T("/api/fs/git-dirs",{query:{path:e,directory:e}});if(t.status===501)throw new IU;if(!t.ok)throw new Error(`Failed to list git directories: ${t.statusText}`);const s=await t.json();if(!Array.isArray(s?.repositories))throw new Error("Unexpected git directories response");return s.repositories.map(a=>je(a?.path??null)).filter(a=>a!==null)}async function jU(e,t){const s=t?.mode,a=N();t?.fresh&&Du(a,e);const n=hc(a,e,s),o=Date.now(),i=si.get(n);if(i&&i.expiresAt>o)return i.value;const r=on.get(n);if(r)return r;const l=(async()=>{const p=ai(a,e),u=await T(F(`${D}/status`,e,s?{mode:s}:void 0));if(!u.ok){const h=WV.safeParse(await u.json().catch(()=>null));throw h.success?new Xy(h.data.error):new Error(`Failed to get git status: ${u.statusText}`)}const g=await u.json();return ai(a,e)===p&&si.set(n,{value:g,expiresAt:Date.now()+tv}),g})();on.set(n,l);try{return await l}finally{on.get(n)===l&&on.delete(n)}}async function _$(e){const t=await fc(e,"root");return{root:t.root?t.root:e}}async function K$(e){const t=await T(F(`${D}/toplevel`,e));if(!t.ok)throw new Error(`Failed to resolve the repository folder: ${t.statusText}`);const s=await t.json().catch(()=>({}));if(s.prefix===void 0||s.prefix===null)throw new Error("The server did not report the repository folder");return s.prefix}async function Z$(e){const t=await T(F(`${D}/toplevel`,e));if(!t.ok)throw new Error(`Failed to resolve git toplevel: ${t.statusText}`);const s=await t.json().catch(()=>({}));return{root:typeof s.root=="string"&&s.root?s.root:e}}async function J$(e,t){const s=await T(F(`${D}/commit-summaries`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shas:t})});if(!s.ok)throw new Error(`Failed to get git commit summaries: ${s.statusText}`);const a=await s.json().catch(()=>({}));return{commits:Array.isArray(a.commits)?a.commits.map(n=>({sha:typeof n.sha=="string"?n.sha:"",short:typeof n.short=="string"?n.short:"",subject:typeof n.subject=="string"?n.subject:""})).filter(n=>n.sha&&n.short):[]}}async function OU(e,t){const{path:s,staged:a,contextLines:n,previousPath:o}=t;if(!s)throw new Error("path is required to fetch git diff");const i=await T(F(`${D}/diff`,e,{path:s,staged:a?"true":void 0,context:n,previousPath:o||void 0}));if(!i.ok)throw await Iu(i,"Failed to get git diff");return _V.parse(await i.json())}const yh=1e3;async function DU(e,t){const{paths:s,staged:a,contextLines:n}=t,o=[];for(let i=0;i<s.length;i+=yh){const r=await T(F(`${D}/diffs`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:s.slice(i,i+yh),staged:a===!0,context:n})});if(!r.ok)throw await Iu(r,"Failed to get git diffs");for(const l of KV.parse(await r.json()).diffs)o.push("diff"in l?{path:l.path,ok:!0,diff:{diff:l.diff,submodule:l.submodule}}:{path:l.path,ok:!1,error:l.error,reason:l.code})}return o}async function NU(e,t){const{base:s,head:a,path:n,contextLines:o,includeWorkingTree:i,previousPath:r}=t;if(!s||!a)throw new Error("base and head are required to fetch git range diff");const l=await T(F(`${D}/range-diff`,e,{base:s,head:a,path:n||void 0,context:o,includeWorkingTree:i,previousPath:r||void 0}));if(!l.ok)throw await fi(l,"Failed to get git range diff");return ev.parse(await l.json())}async function FU(e,t){const s=await T(F(`${D}/commit-diff`,e,{hash:t.hash,path:t.path,previousPath:t.previousPath,context:t.contextLines}));if(!s.ok)throw await fi(s,"Failed to get commit diff");return ev.parse(await s.json())}async function EU(e,t){const{base:s,head:a,includeWorkingTree:n}=t;if(!s||!a)throw new Error("base and head are required to fetch git range files");const o=await T(F(`${D}/range-files`,e,{base:s,head:a,includeWorkingTree:n}));if(!o.ok)throw await fi(o,"Failed to get git range files");return VV.parse(await o.json()).files}async function MU(e,t){if(!t)throw new Error("branch is required to get branch base");const s=await T(F(`${D}/branch-base`,e,{branch:t}));if(!s.ok)throw new Error(`Failed to get branch base: ${s.statusText}`);return s.json()}async function BU(e,t){const{path:s,staged:a,previousPath:n}=t;if(!s)throw new Error("path is required to fetch git file diff");const o=await T(F(`${D}/file-diff`,e,{path:s,staged:a?"true":void 0,previousPath:n||void 0}));if(!o.ok)throw await Iu(o,"Failed to get git file diff");return ZV.parse(await o.json())}async function LU(e,t,s){if(!t)throw new Error("path is required to revert git changes");const a=await T(F(`${D}/revert`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,scope:s?.scope})});if(!a.ok){const n=await a.json().catch(()=>({error:a.statusText}));throw new Error(n.error||"Failed to revert git changes")}Vn(e)}async function qU(e,t){await lv(e,[t])}async function lv(e,t){const s=t.map(n=>n.trim()).filter(Boolean);if(s.length===0)throw new Error("path is required to stage git changes");const a=await T(F(`${D}/stage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:s})});if(!a.ok){const n=await a.json().catch(()=>({error:a.statusText}));throw new Error(n.error||"Failed to stage git changes")}Vn(e)}async function VU(e,t){await dv(e,[t])}async function dv(e,t){const s=t.map(n=>n.trim()).filter(Boolean);if(s.length===0)throw new Error("path is required to unstage git changes");const a=await T(F(`${D}/unstage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:s})});if(!a.ok){const n=await a.json().catch(()=>({error:a.statusText}));throw new Error(n.error||"Failed to unstage git changes")}Vn(e)}async function UU(e,t,s){await Fu(e,t,s,"stage")}async function WU(e,t,s){await Fu(e,t,s,"unstage")}async function HU(e,t,s){await Fu(e,t,s,"discard")}async function Fu(e,t,s,a){if(!t)throw new Error("path is required to apply a git hunk");if(typeof s!="string"||!s.trim())throw new Error("patch is required to apply a git hunk");const n=await T(F(`${D}/apply-hunk`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,patch:s,action:a})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to apply git hunk")}Vn(e)}async function GU(e){if(!e)return!1;const t=await T(F(`${D}/worktree-type`,e));if(!t.ok)throw new Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function _U(e,t){const s=await T(F(`${D}/branches`,e,t?.remote?{remote:t.remote}:void 0));if(!s.ok)throw new Error(`Failed to get branches: ${s.statusText}`);return s.json()}async function KU(e,t){const s=await T(F(`${D}/branch-push-status`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branches:t})});if(!s.ok)throw new Error(`Failed to get branch push status: ${s.statusText}`);return s.json()}async function ZU(e,t){if(!t?.branch)throw new Error("branch is required to delete a branch");const s=await T(F(`${D}/branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to delete branch")}return Oe(e,s)}async function JU(e,t){const s=t?.remote?.trim();if(!s)throw new Error("remote is required to remove a remote");const a=await T(F(`${D}/remotes`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({remote:s})});if(!a.ok){const n=await a.json().catch(()=>({error:a.statusText}));throw new Error(n.error||"Failed to remove remote")}return Oe(e,a)}async function $U(e,t,s){if(!Array.isArray(t)||t.length===0)throw new Error("No files provided to generate commit message");const a={files:t};s?.zenModel&&(a.zenModel=s.zenModel),s?.providerId&&(a.providerId=s.providerId),s?.modelId&&(a.modelId=s.modelId);const n=await T(F(`${D}/commit-message`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!n.ok){const l=await n.json().catch(()=>({error:n.statusText}));console.error("[git-generation][browser] http error",{status:n.status,statusText:n.statusText,error:l});const p=typeof l?.traceId=="string"&&l.traceId?` (traceId: ${l.traceId})`:"";throw new Error(`${l.error||"Failed to generate commit message"}${p}`)}const o=await n.json();if(!o?.message||typeof o.message!="object")throw new Error("Malformed commit generation response");const i=typeof o.message.subject=="string"&&o.message.subject.trim().length>0?o.message.subject.trim():"",r=Array.isArray(o.message.highlights)?o.message.highlights.filter(l=>typeof l=="string"&&l.trim().length>0).map(l=>l.trim()):[];return{message:{subject:i,highlights:r}}}async function QU(e,t){const{base:s,head:a,context:n,zenModel:o,providerId:i,modelId:r}=t;if(!s||!a)throw new Error("base and head are required");const l={base:s,head:a};n?.trim()&&(l.context=n.trim()),o&&(l.zenModel=o),i&&(l.providerId=i),r&&(l.modelId=r);const p=await T(F(`${D}/pr-description`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!p.ok){const b=await p.json().catch(()=>({error:p.statusText}));throw new Error(b.error||"Failed to generate PR description")}const u=await p.json().catch(()=>null),g=typeof u?.title=="string"?u.title:"",h=typeof u?.body=="string"?u.body:"";if(!g&&!h)throw new Error("Malformed PR description response");return{title:g,body:h}}async function vh(e){return(await fc(e,"worktrees")).worktrees??[]}async function Ch(e,t){const s=await T(F(`${D}/worktrees/validate`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to validate worktree")}return s.json()}async function YU(e){const t=await T(F(`${D}/worktrees/bootstrap-status`,e));if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to get worktree bootstrap status")}return hU.parse(await t.json())}async function XU(e,t){const s=await T(F(`${D}/worktrees/preview`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to preview worktree")}return s.json()}async function Sh(e,t){const s=await T(F(`${D}/worktrees`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!s.ok){const a=d({error:c().optional(),code:c().optional(),remoteName:c().optional()}).strict().parse(await s.json().catch(()=>({error:s.statusText})));throw new Au(a.code||"UNKNOWN",a.error||"Failed to create worktree",s.status,a.remoteName)}return s.json()}async function Ph(e,t){const s=await T(F(`${D}/worktrees`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});return s.ok||await pv(s,"Failed to delete worktree"),s.json()}async function eW(e,t){const s=await T(F(`${D}/worktrees/teardown`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return s.ok||await pv(s,"Failed to tear down worktree"),s.json()}const pv=async(e,t)=>{const s=d({error:c().optional(),code:c().optional()}).catch({}).parse(await e.json().catch(()=>null)),a=s.error||e.statusText||t;throw s.code?new Au(s.code,a,e.status):new Error(a)},tW=d({title:c(),branch:c()});async function sW(e,t,s="user"){const a=await T(F(`${D}/worktrees/title`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:t,by:s})}),n=await a.json().catch(()=>null);if(!a.ok){const i=d({error:c()}).safeParse(n).data?.error;throw new Error(i||"Failed to rename the task")}const o=tW.safeParse(n);if(!o.success)throw new Error("Malformed task title response");return o.data}const aW=d({pinned:y(),branch:c()});async function nW(e,t,s=null){const a=await T(F(`${D}/worktrees/pin`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s?{pinned:t,list:s}:{pinned:t})}),n=await a.json().catch(()=>null);if(!a.ok){const i=d({error:c()}).safeParse(n).data?.error;throw new Error(i||"Failed to pin the task")}const o=aW.safeParse(n);if(!o.success)throw new Error("Malformed pin response");return o.data}const uv=d({id:c().min(1),ref:c().min(1),commit:c().min(1),head:c(),path:c().min(1),branch:c(),branchExists:y(),title:c(),archivedAt:w(),sessionIds:C(c())}),bc=async(e,t,s,a,n)=>{const o=await T(F(`${D}/worktrees/archives${e}`,t),{...s,headers:s.body?{"Content-Type":"application/json"}:void 0});if(!o.ok){const i=d({error:c().optional(),code:c().optional()}).catch({}).parse(await o.json().catch(()=>null)),r=i.error||o.statusText||n;throw i.code?new Au(i.code,r,o.status):new Error(r)}return a.parse(await o.json())},oW=(e,t)=>bc("",e,{method:"POST",body:JSON.stringify(t)},uv,"Failed to archive worktree"),iW=async e=>(await bc("",e,{method:"GET"},d({archives:C(uv)}),"Failed to list worktree archives")).archives,rW=(e,t)=>bc("/restore",e,{method:"POST",body:JSON.stringify({id:t})},d({id:c(),conflicts:y()}),"Failed to restore worktree archive"),cW=(e,t)=>bc("",e,{method:"DELETE",body:JSON.stringify(t)},d({id:c(),branchDeleted:y()}),"Failed to delete worktree archive"),lW=d({ref:c(),commit:c().min(1),head:c().min(1)});async function dW(e,t){const s=await T(F(`${D}/worktrees/snapshot`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to snapshot worktree")}return lW.parse(await s.json())}async function pW(e,t,s={}){const a=await T(F(`${D}/commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:t,addAll:s.addAll??!1,files:s.files,stageFiles:s.stageFiles})});if(!a.ok){const n=await a.json().catch(()=>({error:a.statusText}));throw new Error(n.error||"Failed to create commit")}return Oe(e,a)}async function uW(e,t={}){const s=N(),a=await T(F(`${D}/push`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){const o=await a.json().catch(()=>({error:a.statusText}));throw new Error(o.error||"Failed to push")}const n=await Oe(e,a);return n.success&&MV(e,s),n}async function gW(e,t={}){const s=await T(F(`${D}/pull`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to pull")}return Oe(e,s)}async function mW(e,t={}){const s=await T(F(`${D}/fetch`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to fetch")}return Oe(e,s)}const gv=async(e,t,s)=>{const a=await T(e,t);if(!a.ok){const n=Ou.parse(await a.json());throw n.code==="NOT_FOUND"&&s&&kU(s.runtimeKey,s.operationId),new Tu(n.code,n.error,a.status)}return fU.parse(await a.json())},hW=(e,t,s)=>{if(s.operationId!==e)throw new Error("Malformed Git network operation response");const a=Xd(t,e,s.runtimeIdentity.id);if(!a&&Xd(t,e))throw new Error("Malformed Git network operation response");if(a){const n=a.value.transport,o=s.state!=="planned"&&s.state!=="running",i=es(a.value.target,s.target)||o&&yU(a.value.target)===JSON.stringify(s.target);if(!es(a.value.runtimeIdentity,s.runtimeIdentity)||!i||!ep(n,s.transport,o))throw new Error("Malformed Git network operation response");if(a.value.terminalState&&(s.state==="planned"||s.state==="running"||s.state!==a.value.terminalState))throw new Error("Malformed Git network operation response");es(n,s.transport)===!1&&(a.value.transport=s.transport),s.state!=="planned"&&s.state!=="running"?a.value.terminalState||(SU(s)&&(Du(a.value.runtimeKey,a.value.directory),a.value.runtimeKey===N()&&Yy(a.value.directory)),a.value.terminalState=s.state,a.value.observedAt=Date.now()):a.value.observedAt=Date.now()}if(N()!==t)throw new Error("Git network operation response belongs to a stale runtime");return s};async function fW(e){const t=N(),s=await gv(`${D}/network-operations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(s.state!=="planned")throw new Error("Malformed Git network operation plan response");if(N()!==t)throw new Error("Git network operation response belongs to a stale runtime");CU(e,s);const a=bU(t,s.runtimeIdentity.id,s.operationId);if(Xd(t,s.operationId,s.runtimeIdentity.id)?.value.terminalState)throw new Error("Malformed Git network operation plan response");return Vt.set(a,{operationId:s.operationId,runtimeKey:t,directory:e.operation==="clone"?e.destinationPath:e.directory,runtimeIdentity:s.runtimeIdentity,transport:s.transport,target:s.target,observedAt:Date.now()}),Nu(),s}async function bW(e){const t=await T(`${D}/contributor-destinations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){const s=Ou.parse(await t.json());throw new Tu(s.code,s.error,t.status)}return sU.parse(await t.json())}async function kW(e){const t=N(),s=await T(F(`${D}/contributor-destinations`,e));if(!s.ok){const n=Ou.parse(await s.json());throw new Tu(n.code,n.error,s.status)}const a=nU.parse(await s.json());if(N()!==t)throw new Error("Contributor destinations belong to a stale runtime");return a}async function wW(e){const t=await T(F(`${D}/worktrees/checkout-trust`,e));if(!t.ok)throw new Error((await t.json()).error||"Failed to inspect checkout actions");return oU.parse(await t.json())}async function yW(e,t,s){const a=await T(F(`${D}/worktrees/checkout-trust`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({digest:t,decision:s})});if(!a.ok)throw new Error((await a.json()).error||"Failed to apply checkout trust decision");return d({state:c().min(1)}).passthrough().parse(await a.json())}const Eu=async(e,t)=>{const s=N();wU(s,e);const a=t?`/${t}`:"",n=t?{method:"POST"}:void 0,o=await gv(`${D}/network-operations/${encodeURIComponent(e)}${a}`,n,{runtimeKey:s,operationId:e});return hW(e,s,o)};async function vW(e){return Eu(e,"execute")}async function CW(e){return Eu(e)}async function SW(e){return Eu(e,"cancel")}async function PW(e){const t=await T(F(`${D}/stashes`,e));if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to list stashes")}return t.json()}async function xW(e,t){const s=await T(F(`${D}/stashes/file-counts`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refs:t})});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to count stash files")}return s.json()}async function mv(e,t={}){const s=await T(F(`${D}/stash`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to stash changes")}return Oe(e,s)}const Mu=async(e,t,s)=>{const a=await T(F(`${D}/${t}`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!a.ok){const n=await a.json().catch(()=>({error:a.statusText}));throw new Error(n.error||`Failed to ${t}`)}return Oe(e,a)},TW=(e,t)=>Mu(e,"stash/apply",t),hv=(e,t)=>Mu(e,"stash/pop",t),AW=(e,t)=>Mu(e,"stash/drop",t);async function zW(e,t){const s=await T(F(`${D}/checkout`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:t})});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to checkout branch")}return Oe(e,s)}async function RW(e,t,s){const a=await T(F(`${D}/branches`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,startPoint:s})});if(!a.ok){const n=await a.json().catch(()=>({error:a.statusText}));throw new Error(n.error||"Failed to create branch")}return Oe(e,a)}async function IW(e,t,s){const a=await T(F(`${D}/branches/rename`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:t,newName:s})});if(!a.ok){const n=await a.json().catch(()=>({error:a.statusText}));throw new Error(n.error||"Failed to rename branch")}return Oe(e,a)}async function jW(e,t={}){const s=await T(F(`${D}/log`,e,{maxCount:t.maxCount,from:t.from,to:t.to,file:t.file,all:t.all?"true":void 0}));if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(`Failed to get git log: ${a.error||s.statusText}`)}return GV.parse(await s.json())}const OW=d({sha:c().regex(/^[0-9a-f]{40}$/),changeId:c().regex(/^I[0-9a-f]{40}$/)});async function DW(e,t){const s=await T(F(`${D}/change-id`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expectedHead:t})});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to add a Change-Id")}return Vn(e),OW.parse(await s.json())}async function NW(e,t){const s=await T(F(`${D}/commit-files`,e,{hash:t}));if(!s.ok)throw await fi(s,"Failed to get commit files");return HV.parse(await s.json())}async function $$(e,t){const{base:s,head:a,path:n,previousPath:o,includeWorkingTree:i}=t,r=await T(F(`${D}/range-file-versions`,e,{base:s,head:a,path:n,previousPath:o,includeWorkingTree:i?"true":void 0}));if(!r.ok)throw await fi(r,"Failed to read file versions");return qV.parse(await r.json())}async function FW(e,t,s,a,n){const o=await T(F(`${D}/commit-file-diff`,e,{hash:t,path:s,binary:a?"true":void 0,previousPath:n}));if(!o.ok)throw new Error(`Failed to get commit file diff: ${o.statusText}`);return o.json()}async function EW(){const e=await T(F(`${D}/identities`,void 0));if(!e.ok)throw new Error(`Failed to get git identities: ${e.statusText}`);return DV.parse(await e.json())}async function MW(e){const t=Rn.parse(e),s=await T(F(`${D}/identities`,void 0),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to create git identity")}return Rn.parse(await s.json())}async function BW(e,t){const s=Rn.parse(t);if(s.id!==e)throw new Error("Git identity profile ID does not match the update target");const a=await T(F(`${D}/identities/${e}`,void 0),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!a.ok){const n=await a.json().catch(()=>({error:a.statusText}));throw new Error(n.error||"Failed to update git identity")}return Rn.parse(await a.json())}async function LW(e){const t=await T(F(`${D}/identities/${e}`,void 0),{method:"DELETE"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to delete git identity")}}async function qW(e){if(!e)return null;const t=await T(F(`${D}/current-identity`,e));if(!t.ok)throw new Error(`Failed to get current git identity: ${t.statusText}`);const s=await t.json();return s?Qy.parse(s):null}async function VW(e){if(!e)return!1;const t=await T(F(`${D}/has-local-identity`,e));if(!t.ok)throw new Error(`Failed to check local identity: ${t.statusText}`);return(await t.json().catch(()=>null))?.hasLocalIdentity===!0}async function UW(){const e=await T(F(`${D}/global-identity`,void 0));if(!e.ok)throw new Error(`Failed to get global git identity: ${e.statusText}`);const t=await e.json();if(!t)return null;const s=Qy.parse(t);return s.userName||s.userEmail?s:null}async function WW(e,t){const s=await T(F(`${D}/set-identity`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:t})});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to set git identity")}return NV.parse(await s.json())}async function HW(e){const t=await T(F(`${D}/remotes`,e));if(!t.ok)throw new Error(`Failed to get remotes: ${t.statusText}`);return tU.parse(await t.json())}async function GW(e,t){const s=await T(F(`${D}/rebase`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to rebase")}return Oe(e,s)}async function _W(e){const t=await T(F(`${D}/rebase/abort`,e),{method:"POST"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to abort rebase")}return Oe(e,t)}async function KW(e,t){const s=await T(F(`${D}/merge`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to merge")}return Oe(e,s)}async function ZW(e,t){const s=await T(F(`${D}/checkout-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to checkout commit")}return Oe(e,s)}async function JW(e,t){const s=await T(F(`${D}/cherry-pick`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to cherry-pick")}return Oe(e,s)}async function $W(e,t){const s=await T(F(`${D}/revert-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to revert commit")}return Oe(e,s)}async function QW(e,t,s,a){const n=await T(F(`${D}/reset-to-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t,mode:s,force:a})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to reset")}return Oe(e,n)}async function YW(e){const t=await T(F(`${D}/merge/abort`,e),{method:"POST"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to abort merge")}return Oe(e,t)}async function XW(e){const t=await T(F(`${D}/rebase/continue`,e),{method:"POST"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to continue rebase")}return Oe(e,t)}async function eH(e){const t=await T(F(`${D}/merge/continue`,e),{method:"POST"});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||"Failed to continue merge")}return Oe(e,t)}async function tH(e,t){return await mv(e,{message:t?.message}),{success:!0}}async function sH(e){return await hv(e,{ref:"stash@{0}"}),{success:!0}}async function aH(e){const t=await T(F(`${D}/conflict-details`,e));if(!t.ok)throw new Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function nH(e,t){const s=await T(`${D}/validate-directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e,worktreeRoot:t})});if(!s.ok)throw new Error(`Failed to validate worktree directory: ${s.statusText}`);return s.json()}async function oH(e){const t=await T(`${D}/canonicalize-worktree-state`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e})});if(!t.ok)throw new Error(`Failed to canonicalize worktree state: ${t.statusText}`);return t.json()}const iH=/^[a-z][a-z0-9-]{0,31}$/,Gr=e=>Object.prototype.toString.call(e)==="[object String]"&&iH.test(e),xh="ext-",fv=e=>Gr(e)&&e.startsWith(xh)&&Gr(e.slice(xh.length)),bv=(e,t,s)=>{if(typeof s!="string"||!s.startsWith(`${t}#`))return!1;const a=s.slice(t.length+1);return fv(e)?a.length>0&&a.length<=256:/^\d+$/.test(a)},rH=e=>Object.prototype.toString.call(e)==="[object String]"&&/^[\x20-\x39\x3b-\x7e]{1,256}$/.test(e)&&e.trim()===e,kv=e=>e!==null&&Object.prototype.toString.call(e)==="[object Object]"&&Object.getPrototypeOf(e)===Object.prototype,cH=e=>Object.prototype.toString.call(e)==="[object String]",St=e=>cH(e)&&e.length>0,Th=(e,t=512)=>St(e)&&e.length<=t&&e.trim()===e&&!/[\0\r\n]/.test(e),lH=/^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/,dH=e=>{const t=e.toLowerCase();return t==="localhost"||t==="::1"||t==="[::1]"||lH.test(t)},pH=e=>{if(!e.instance.includes("://"))return/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(e.instance);try{const t=new URL(e.instance),s=dH(t.hostname);return t.origin===e.instance&&!t.username&&!t.password&&["","/"].includes(t.pathname)&&!t.search&&!t.hash&&(t.protocol==="https:"||t.protocol==="http:"&&s)}catch{return!1}},bs=(e,t,s=[])=>kv(e)&&t.every(a=>Object.hasOwn(e,a))&&Object.keys(e).every(a=>t.includes(a)||s.includes(a)),Ah=e=>{let t;try{t=decodeURIComponent(e)}catch{return!1}const s=t.replace(/^\/+|\/+$/g,"");return!!(s&&!/[\0\r\n]/.test(s)&&!s.split("/").some(a=>!a||a==="."||a===".."))},uH=e=>{if(!St(e)||e.trim()!==e||e.length>4096||/[\0\r\n]/.test(e))return!1;if(!e.includes("://")){const t=e.match(/^(?:[A-Za-z0-9._-]+@)?[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?:([^\s:\\]+)$/);return!!(t&&!/[?#]/.test(e)&&!t[1].startsWith("-")&&Ah(`/${t[1]}`))}try{const t=new URL(e);return["http:","https:","ssh:"].includes(t.protocol)&&!!t.hostname&&(!t.username||t.protocol==="ssh:")&&!t.password&&!t.search&&!t.hash&&Ah(t.pathname)}catch{return!1}},tp=e=>bs(e,["displayUrl","fingerprint"])&&uH(e.displayUrl)&&St(e.fingerprint)&&e.fingerprint.length<=128&&/^[A-Za-z0-9_-]+$/.test(e.fingerprint),er=tp,zh=e=>["managed","system","anonymous"].includes(e.mode)&&(e.mode==="managed"?St(e.credentialId):!Object.hasOwn(e,"credentialId")),gH=e=>kv(e)&&Object.hasOwn(e,"status")&&(e.status==="unavailable"&&bs(e,["status"])||e.status==="available"&&(bs(e,["status","transport","fingerprint"])&&e.transport==="ssh"&&/^SHA256:[A-Za-z0-9+/]{43}=?$/.test(e.fingerprint)||bs(e,["status","transport","provider","instance","source","username","providerUserId"])&&e.transport==="https"&&Gr(e.provider)&&["oauth","pat","cli"].includes(e.source)&&Th(e.instance,2048)&&rH(e.username)&&Th(e.providerUserId)&&pH(e)&&bv(e.provider,e.instance,e.providerUserId))),xl=(e,t)=>new Set(e.map(t)).size===e.length,io=()=>Object.assign(new Error("Source control binding storage is invalid"),{code:"INVALID_SOURCE_CONTROL_BINDINGS"}),mH=(e,t=!1)=>{if(!bs(e,["repositoryId","revision","state","configRevision","providers","remotes"],["auxiliary"])||!St(e.repositoryId)||!Number.isSafeInteger(e.revision)||e.revision<1||!St(e.configRevision)||!["bound","needs-attention"].includes(e.state)||!Array.isArray(e.providers)||!Array.isArray(e.remotes)||!Array.isArray(e.auxiliary))throw io();for(const s of e.providers)if(!bs(s,["provider","instance","accountId","primaryRemote","readiness","endpoint"],["repository"])||!Gr(s.provider)||!St(s.instance)||!St(s.accountId)||!St(s.primaryRemote)||s.repository!==void 0&&(!bs(s.repository,["owner","name"])||!St(s.repository.owner)||!St(s.repository.name))||!["ready","confirmation-required","account-unavailable","config-changed"].includes(s.readiness)||!(s.endpoint===null&&s.readiness!=="ready"||er(s.endpoint)))throw io();for(const s of e.remotes)if(!bs(s,["name","fetch","push","mode","readiness"],["credentialId",...t&&s.mode==="managed"?["presentation"]:[],...t?["inherited"]:[]])||!St(s.name)||!er(s.fetch)||!er(s.push)||!zh(s)||s.presentation!==void 0&&!gH(s.presentation)||s.inherited!==void 0&&(s.inherited!==!0||s.readiness!=="ready")||s.mode==="anonymous"&&!s.fetch.displayUrl.startsWith("https://")||!["ready","confirmation-required","config-changed"].includes(s.readiness))throw io();for(const s of e.auxiliary??[])if(!bs(s,["kind","endpoint","mode","readiness"],["credentialId"])||!["submodule","lfs"].includes(s.kind)||!er(s.endpoint)||!zh(s)||s.mode==="anonymous"&&!s.endpoint.displayUrl.startsWith("https://")||!["ready","confirmation-required"].includes(s.readiness))throw io();if((e.auxiliary?.length??0)>256||!xl(e.remotes,s=>s.name)||!xl(e.providers,s=>`${s.provider}\0${s.instance}\0${s.primaryRemote}`)||!xl(e.auxiliary??[],s=>`${s.kind}\0${s.endpoint.fingerprint}`))throw io()},hH=e=>[...e.providers,...e.remotes,...e.auxiliary].some(t=>t.readiness!=="ready")?"needs-attention":"bound",fH=e=>(mH(e,!0),structuredClone(e)),bH=(e,t)=>{const s=new Map(t.remotes.map(i=>[i.name,i])),a=e.providers.map(i=>i.readiness==="ready"&&i.endpoint?.fingerprint!==s.get(i.primaryRemote)?.fetch.fingerprint?{...i,readiness:"config-changed"}:i),n=e.remotes.map(i=>{const r=s.get(i.name);return i.readiness==="ready"&&(!r||i.fetch.fingerprint!==r.fetch.fingerprint||i.push.fingerprint!==r.push.fingerprint)?{...i,readiness:"config-changed"}:i}),o={...e,providers:a,remotes:n};return o.state=hH(o),o},Rh={referenceSearch:!1,referenceDetail:!1,listStatuses:!1,referencesAcross:!1,startThread:!1,authorCanReview:!1,projectUploads:!1,issueCloseReason:!1,changeRequestTemplates:[],changeRequestPatch:!1},wv=[{id:"github",label:"GitHub",order:0,terminology:{changeRequest:"pullRequest",changeRequestPrefix:"#",issuePrefix:"#",sharedNumberSpace:!0,abbreviation:"PR",promptNoun:"pull request",ci:"checks"},icon:{sprite:"github",filledSprite:"github-fill"},repository:{nestedNamespaces:!1},instances:{format:"host",defaultInstance:"github.com",defaultInstances:["github.com"],multiple:!0,allowLoopbackHttp:!1,allowPort:!1,reserved:["github.com"],placeholder:"https://github.example.com",legacyFlow:{instance:"github.com",kind:"github-com-device"}},auth:{methods:["device","pat","cli"],cliName:"gh",cliTransport:!0,token:{scopes:["repo","read:org","workflow","read:user","user:email"],createPath:"/settings/tokens"}},settings:{fields:[{id:"instance",kind:"instance-url",secret:!1},{id:"token",kind:"personal-access-token",secret:!0}]},urls:{changeRequest:["/{owner}/{repo}/pull/{number}"],issue:["/{owner}/{repo}/issues/{number}"],commit:["/{owner}/{repo}/commit/{sha}"],user:["/{user}"]},features:{...Rh,referenceSearch:!0,referenceDetail:!0,listStatuses:!0,referencesAcross:!0,issueCloseReason:!0,changeRequestPatch:!0}},{id:"gitlab",label:"GitLab",order:1,terminology:{changeRequest:"mergeRequest",changeRequestPrefix:"!",issuePrefix:"#",sharedNumberSpace:!1,abbreviation:"MR",promptNoun:"merge request",ci:"pipeline"},icon:{sprite:"gitlab"},repository:{nestedNamespaces:!0},instances:{format:"origin",defaultInstance:"https://gitlab.com",defaultInstances:["https://gitlab.com"],multiple:!0,allowLoopbackHttp:!0,allowPort:!0,reserved:[],placeholder:"https://gitlab.example.com"},auth:{methods:["device","pat","cli"],cliName:"glab",cliTransport:!1,token:{scopes:["api"],createPath:"/-/user_settings/personal_access_tokens"}},settings:{fields:[{id:"instance",kind:"instance-url",secret:!1},{id:"token",kind:"personal-access-token",secret:!0}]},urls:{changeRequest:["/{namespace+}/{repo}/-/merge_requests/{number}"],issue:["/{namespace+}/{repo}/-/issues/{number}","/{namespace+}/{repo}/-/work_items/{number}"],commit:["/{namespace+}/{repo}/-/commit/{sha}"],user:["/{user}"]},features:{...Rh,startThread:!0,authorCanReview:!0,projectUploads:!0,changeRequestPatch:!0,changeRequestTemplates:[".gitlab/merge_request_templates/Default.md"]}}],Un=(e,t)=>`/api/source-control/${e.provider}${t}`,kH=d({providers:C(ne())}),wH=d({error:c()}),yH=async e=>{const t=await e("/api/source-control/providers",{headers:{Accept:"application/json"}});if(t.status===404)return Dd.parse(wv);const s=await t.json().catch(()=>null);if(!t.ok){const o=wH.safeParse(s);throw new Error(o.success&&o.data.error||t.statusText||"Failed to load source control providers")}const a=kH.parse(s).providers,n=Dd.parse(a);if(a.length>0&&n.length===0)throw new Error("Source control providers response contained no readable provider");return n},yv=d({state:S(["success","failure","pending","unknown"]),total:w(),success:w(),failure:w(),pending:w(),inProgress:w().optional(),queued:w().optional(),startedAt:c().optional()}),Tl={number:w(),title:c(),url:c(),body:c(),bodyTruncated:y(),createdAt:c().nullable(),updatedAt:c().nullable(),author:d({login:c(),avatarUrl:c().optional()}).nullable(),labels:C(d({name:c(),color:c().optional()})),commentCount:w(),sourceRepo:d({owner:c(),repo:c(),source:c()})},vv=X("kind",[d({kind:m("issue"),...Tl,state:S(["open","completed","not_planned"])}),d({kind:m("pull"),...Tl,state:S(["open","closed","merged"]),draft:y(),head:c(),base:c(),headSha:c(),headRepo:d({owner:c(),repo:c(),url:c(),cloneUrl:c().optional(),sshUrl:c().optional()}).nullable()}),d({kind:m("discussion"),...Tl,state:S(["open","resolved","outdated","duplicate"]),answered:y().nullable(),upvotes:w(),locked:y(),category:d({name:c(),emoji:c().nullable(),answerable:y()})})]),vH=X("connected",[d({connected:m(!1)}),d({connected:m(!0),repo:d({owner:c(),repo:c(),url:c()}).nullable(),items:C(vv),cursor:c().nullable(),hasMore:y(),total:w()})]),Ih={author:d({login:c(),avatarUrl:c().optional()}).nullable(),body:c(),createdAt:c().nullable(),url:c(),path:c().nullable(),line:w().nullable(),review:S(["approved","changes_requested","commented","dismissed"]).nullable(),excerpt:d({startLine:w().int().positive(),lines:C(c()).max(200)}).optional().catch(void 0)},CH=X("connected",[d({connected:m(!1)}),d({connected:m(!0),detail:d({number:w(),comments:C(d({...Ih,thread:d({id:c().min(1),resolved:y(),canResolve:y(),canReply:y(),replies:C(d(Ih))}).optional(),answer:d({chosen:y(),canChange:y()}).optional()})),commentTotal:w(),pull:d({reviewDecision:S(["approved","changes_requested","review_required"]).nullable(),reviewers:C(d({id:c(),login:c(),avatarUrl:c().optional()})).default([]),checks:yv.nullable().optional(),additions:w(),deletions:w(),changedFiles:w(),commits:C(d({sha:c(),headline:c(),author:d({login:c(),avatarUrl:c().optional()}).nullable(),authorName:c().nullable(),committedAt:c().nullable(),url:c().nullable()})).default([]),commitTotal:w().nullable().default(null),stack:d({number:w().nullable(),base:c(),layers:C(d({number:w(),title:c(),url:c(),state:S(["open","closed","merged"]),draft:y(),head:c()}))}).nullable().optional().catch(void 0)}).nullable(),discussion:d({canComment:y(),canClose:y(),canReopen:y()}).optional()}).nullable()})]),SH=vi({items:C(vv.and(d({directory:c().min(1)}))),cursor:c().nullable(),hasMore:y(),total:w().int().nonnegative(),repositories:C(M([vi({directory:c().min(1),status:m("included"),repo:vi({owner:c(),repo:c(),url:c(),host:c().optional()})}),vi({directory:c().min(1),status:S(["no-repo","disconnected","invalid-context","error"])})]))}),PH=X("connected",[d({connected:m(!1)}),d({connected:m(!0),statuses:C(d({owner:c(),repo:c(),number:w(),checks:yv.nullable(),mergeable:y().nullable(),mergeableState:c().nullable()}))})]),xH=d({error:c()}),kc=e=>{const t=new URLSearchParams({directory:e.directory,instance:e.instance,repositoryId:e.repositoryId,accountId:e.accountId,bindingRevision:String(e.bindingRevision),primaryRemote:e.primaryRemote});return e.linked&&t.set("linked","1"),t},wi=async(e,t,s)=>{const a=await e.json().catch(()=>null);if(!e.ok){const n=xH.safeParse(a);throw new Error(n.success&&n.data.error||e.statusText||s)}return t.parse(a)},TH=async(e,t,s)=>{const a=kc(t);a.set("kind",s.kind),s.state&&a.set("state",s.state),s.people&&a.set("people",s.people),s.query?.trim()&&a.set("query",s.query.trim()),s.cursor&&a.set("cursor",s.cursor);const n=await e(Un(t,"/references"),{query:a,headers:{Accept:"application/json"}}),o=await wi(n,vH,"Failed to load issues and pull requests");return o.connected?{...o,items:o.items.map(i=>({...i,provider:t.provider}))}:o},AH=async(e,t,s)=>{const a=kc(t);a.set("owner",s.owner),a.set("repo",s.repo),a.set("number",String(s.number)),s.kind==="discussion"&&a.set("kind","discussion");const n=s.host?.trim();n&&n!=="github.com"&&a.set("host",n);const o=await e(Un(t,"/references/detail"),{query:a,headers:{Accept:"application/json"}});return wi(o,CH,"Failed to load issue or pull request detail")},jh=d({login:c(),avatarUrl:c().optional()}).nullable(),Oh=S(["old","new"]),zH=X("connected",[d({connected:m(!1)}),d({connected:m(!0),viewerIsAuthor:y(),headSha:c(),draft:d({id:c(),body:c(),comments:C(d({id:c(),path:c(),side:Oh,line:w().int().nullable(),startLine:w().int().nullable(),body:c(),author:jh}))}).nullable(),threads:C(d({id:c(),path:c(),side:Oh,line:w().int().nullable(),startLine:w().int().nullable(),resolved:y(),canReply:y(),canResolve:y(),comments:C(d({id:c(),body:c(),createdAt:c(),url:c(),author:jh}))})),truncated:y()})]),RH=async(e,t,s)=>{const a=kc(t);a.set("owner",s.owner),a.set("repo",s.repo),a.set("number",String(s.number));const n=await e(Un(t,"/pr/review/state"),{query:a,headers:{Accept:"application/json"}});return wi(n,zH,"Failed to load the review")},IH=async(e,t,s)=>{const[a]=t;if(!a||t.some(i=>i.provider!==a.provider))throw new Error("A search across repositories needs contexts of one provider");const n=await e(Un(a,"/references/across"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({contexts:t,...s,query:s.query?.trim()})}),o=await wi(n,SH,"Failed to load issues and pull requests");return{...o,items:o.items.map(i=>({...i,provider:a.provider}))}},jH=async(e,t,s)=>{const a=kc(t);a.set("pulls",s.map(o=>{const i=o.host?.trim().toLowerCase();return`${o.owner}/${o.repo}#${o.number}${i&&i!=="github.com"?`@${i}`:""}`}).join(","));const n=await e(Un(t,"/references/status"),{query:a,headers:{Accept:"application/json"}});return wi(n,PH,"Failed to load pull request statuses")};class ys extends Error{constructor(t,s){super(t),this.code=s}code}const wc=new Map,Cv=e=>{for(const t of e)wc.set(t.id,{format:t.instances.format,label:t.label,pathStyle:t.repository.pathStyle==="path"})},Bu=(e,t)=>Y(t)&&(t.trim().length>0||t===""&&wc.get(e.provider)?.pathStyle!==!1);Cv(wv);const ni=e=>wc.get(e.provider)?.label??e.provider,OH=e=>{const t=e.instance.trim();let s;try{s=new URL(t.includes("://")?t:`https://${t}`)}catch{throw new Error(`Invalid source control instance: ${e.instance}`)}const a=["localhost","127.0.0.1","::1","[::1]"].includes(s.hostname.toLowerCase());if(s.username||s.password||s.search||s.hash||s.pathname&&s.pathname!=="/"||s.protocol!=="https:"&&!(s.protocol==="http:"&&a))throw new Error(`Invalid ${ni(e)} instance: ${e.instance}`);return{provider:e.provider,instance:s.origin}},DH=e=>{const t=e.instance.trim().toLowerCase().replace(/\.$/,"");let s=t;if(t.includes("://"))try{const a=new URL(t);if(a.protocol!=="https:"||a.username||a.password||a.port||a.search||a.hash||a.pathname&&a.pathname!=="/")throw new Error(`Invalid ${ni(e)} instance: ${e.instance}`);s=a.hostname.toLowerCase().replace(/\.$/,"")}catch{throw new Error(`Invalid ${ni(e)} instance: ${e.instance}`)}return{provider:e.provider,instance:s}},K=e=>{const t=(wc.get(e.provider)?.format??"origin")==="host"?DH(e):OH(e),s=e.instanceSshUrl?.trim()?{...t,instanceSshUrl:e.instanceSshUrl.trim()}:t,a=Array.isArray(e.instanceAliases)?e.instanceAliases.filter(O):[];return a.length?{...s,instanceAliases:a}:s},Sv=e=>{if(!e||!Y(e.repositoryId)||!e.repositoryId||!Y(e.configRevision)||!e.configRevision||Object.prototype.toString.call(e.bare)!=="[object Boolean]"||!Array.isArray(e.remotes))throw new Error("Source control response contained an invalid repository context");const t=e.remotes.map(s=>{if(!s||!Y(s.name)||!s.name||!tp(s.fetch)||!tp(s.push))throw new Error("Source control response contained an invalid repository remote");return{name:s.name,fetch:{displayUrl:s.fetch.displayUrl,fingerprint:s.fetch.fingerprint},push:{displayUrl:s.push.displayUrl,fingerprint:s.push.fingerprint}}});return{repositoryId:e.repositoryId,configRevision:e.configRevision,bare:e.bare,remotes:t}},fn=e=>{const t=Sv(e.repository);if(!Number.isInteger(e.revision)||e.revision<0)throw new Error("Source control response contained an invalid binding revision");if(e.binding===null)return{status:"missing",repository:t,revision:e.revision,binding:null};const s=fH(e.binding);if(!s||s.repositoryId!==t.repositoryId||s.revision!==e.revision||!Y(s.configRevision)||!Array.isArray(s.providers)||!Array.isArray(s.auxiliary)||s.state!=="bound"&&s.state!=="needs-attention")throw new Error("Source control response contained an invalid repository binding");const a=bH({...s,providers:s.providers.map(n=>({...n,...K(n)}))},t);return{status:a.state,repository:t,revision:e.revision,binding:a}},Dh=async(e,t,s)=>{const a=await e(t,{query:new URLSearchParams({directory:s}),headers:{Accept:"application/json"}}),n=await a.json();if(!a.ok)throw new ys(n.error||a.statusText||"Source control repository request failed",n.code);return n},NH=async(e,t=T)=>{const s=await t("/api/source-control/binding/transport",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)}),a=await s.json();if(!s.ok)throw new ys(a.error||"Git transport configuration failed",a.code);return{status:"configured",binding:fn(a)}},FH=async(e,t=T)=>{const s=await t("/api/source-control/binding/transport/remove",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)}),a=await s.json();if(!s.ok)throw new ys(a.error||"Git transport removal failed",a.code);return{status:"removed",binding:fn(a)}},EH=async(e,t=T)=>{const s=await t("/api/source-control/binding/auxiliary",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)}),a=await s.json();if(!s.ok)throw new ys(a.error||"Git auxiliary transport configuration failed",a.code);return{status:"configured",binding:fn(a)}},Qe=async(e,t,s,a={},n)=>{const o=K(t),i=await e(Un(o,s),{...a,query:new URLSearchParams([["instance",o.instance],...n?Array.from(n.entries()):[]]),headers:{Accept:"application/json",...a.headers}}),r=await i.json();if(!i.ok){const l=r?.error||i.statusText||"Source control request failed";throw r?.code==="SOURCE_CONTROL_INSTANCE_OTHER_PROVIDER"&&O(r.provider)?new zV(l,r.provider):new ys(l,r?.code)}return r},ps=e=>{const t=new URLSearchParams({directory:e.directory,repositoryId:e.repositoryId,accountId:e.accountId,bindingRevision:String(e.bindingRevision),primaryRemote:e.primaryRemote});return e.linked&&t.set("linked","1"),t},MH=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>!O(t)))throw new Error("Source control response contained invalid incomplete projects");return[...e]}},de=(e,t,s,a)=>Qe(e,t,s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),Wt=(e,t)=>{const s=Object.keys(e);return s.length===t.length&&s.every(a=>t.includes(a))};function ve(e,t,s){const a=e.target;if(!O(e.directory)||!O(e.repositoryId)||!O(e.accountId)||!Tv(e.bindingRevision)||!O(e.primaryRemote)||!O(e.idempotencyKey)||!a||!Bu(t,a.project?.owner)||!O(a.project?.name)||s==="create"&&("number"in a||"headSha"in a)||s==="create"&&(!O(a.head)||!O(a.base))||s==="existing"&&!Gt(a.number)||a.number!==void 0&&!Gt(a.number)||a.head!==void 0&&!O(a.head)||a.base!==void 0&&!O(a.base)||a.headSha!==void 0&&!O(a.headSha))throw new Error("Source control mutation context is invalid");const n={...t,directory:e.directory,repositoryId:e.repositoryId,accountId:e.accountId,bindingRevision:e.bindingRevision,primaryRemote:e.primaryRemote,idempotencyKey:e.idempotencyKey};if(s==="create"){if(!O(a.head)||!O(a.base))throw new Error("Source control mutation context is invalid");return{...n,target:{project:{owner:a.project.owner,name:a.project.name},head:a.head,base:a.base}}}if(!Gt(a.number))throw new Error("Source control mutation context is invalid");const o={project:{owner:a.project.owner,name:a.project.name},number:a.number};return a.head!==void 0&&(o.head=a.head),a.base!==void 0&&(o.base=a.base),a.headSha!==void 0&&(o.headSha=a.headSha),{...n,target:o}}const BH=(e,t)=>e.repositoryId===t.repositoryId&&e.bindingRevision===t.bindingRevision&&e.primaryRemote===t.primaryRemote&&e.project.owner===t.target.project.owner&&e.project.name===t.target.project.name&&(t.target.number===void 0||e.number===t.target.number)&&(t.target.head===void 0||e.head===t.target.head)&&(t.target.base===void 0||e.base===t.target.base)&&(t.target.headSha===void 0||e.headSha===t.target.headSha),Ce=(e,t,s,a)=>{const n=e?.actor,o=e?.target,i=o?.project;if(!e||!Wt(e,["status","actor","target","replayed","result"])||e.status!=="succeeded"||!Ae(e.replayed)||!n||!Wt(n,["provider","instance","providerAccountId"])||n.provider!==s.provider||n.instance!==s.instance||!O(n.providerAccountId)||!bv(s.provider,s.instance,n.providerAccountId)||!o||!Wt(o,["repositoryId","bindingRevision","primaryRemote","project",...["number","head","base","headSha"].filter(l=>o[l]!==void 0)])||!O(o.repositoryId)||!Tv(o.bindingRevision)||!O(o.primaryRemote)||!i||!Wt(i,["id","owner","name"])||!O(i.id)||!Bu(s,i.owner)||!O(i.name)||o.number!==void 0&&!Gt(o.number)||o.head!==void 0&&!O(o.head)||o.base!==void 0&&!O(o.base)||o.headSha!==void 0&&!O(o.headSha)||!BH(o,t)||!e.result||Object.prototype.toString.call(e.result)!=="[object Object]")throw new Error("Source control response contained an invalid mutation receipt");const r={repositoryId:o.repositoryId,bindingRevision:o.bindingRevision,primaryRemote:o.primaryRemote,project:{id:i.id,owner:i.owner,name:i.name}};return o.number!==void 0&&(r.number=o.number),o.head!==void 0&&(r.head=o.head),o.base!==void 0&&(r.base=o.base),o.headSha!==void 0&&(r.headSha=o.headSha),{status:"succeeded",actor:{...s,providerAccountId:n.providerAccountId},target:r,replayed:e.replayed,result:a(e.result)}},$e=e=>{if(!Wt(e,[]))throw new Error("Source control response contained an invalid mutation result");return{}},LH=["queued","merging","auto-merge","cancelled"],qH=e=>LH.find(t=>t===e)??null,VH=e=>{if(!Wt(e,e.stacked===void 0?[]:["stacked"])||e.stacked!==void 0&&!Ae(e.stacked))throw new Error("Source control response contained an invalid create result");return e.stacked===void 0?{}:{stacked:e.stacked}},UH=e=>{const t=["merged",...e.message===void 0?[]:["message"],...e.outcome===void 0?[]:["outcome"]],s=e.outcome===void 0?void 0:qH(e.outcome);if(!Wt(e,t)||!Ae(e.merged)||e.message!==void 0&&!Y(e.message)||s===null)throw new Error("Source control response contained an invalid merge result");const a={merged:e.merged};return e.message!==void 0&&(a.message=e.message),s!==void 0&&(a.outcome=s),a},WH=e=>{if(!Wt(e,["commented"])||!Ae(e.commented))throw new Error("Source control response contained an invalid review result");return{commented:e.commented}},Nh=async(e,t,s,a)=>{const n=K(t),o=ps(t);o.set("owner",s.owner),o.set("repo",s.repo);const i=await Qe(e,n,a,{},o);if(i.connected!==!0)throw new Error(`${ni(n)} is not connected`);if(!Array.isArray(i.items))throw new Error("Source control response contained an invalid list");return i.items},HH=e=>e.map(t=>{if(!O(t.name)||t.color!==void 0&&!Y(t.color))throw new Error("Source control response contained an invalid label");return t.color?{name:t.name,color:t.color}:{name:t.name}}),GH=e=>e.map(t=>{if(!O(t.id)||!O(t.login)||t.avatarUrl!==void 0&&!zs(t.avatarUrl))throw new Error("Source control response contained an invalid user");return t.avatarUrl?{id:t.id,login:t.login,avatarUrl:t.avatarUrl}:{id:t.id,login:t.login}}),Al=e=>{if(!Wt(e,["state"])||e.state!=="open"&&e.state!=="closed")throw new Error("Source control response contained an invalid state result");return{state:e.state}},_H=e=>{if(!Wt(e,["ready"])||!Ae(e.ready))throw new Error("Source control response contained an invalid ready result");return{ready:e.ready}},KH=e=>{if(!Wt(e,["draft"])||!Ae(e.draft))throw new Error("Source control response contained an invalid draft result");return{draft:e.draft}},bt=(e,t)=>{const s=e?.username||e?.login,a=fv(t.provider)?typeof e?.id=="string"&&e.id.length>0&&e.id.length<=256||Gt(e?.id):e&&Ps(e.id);if(!e||!a||!O(s)||!rG(e,t)||e.avatarUrl!==void 0&&!zs(e.avatarUrl)||e.name!==void 0&&!Y(e.name)||e.email!==void 0&&!Y(e.email))throw new Error("Source control response contained an invalid user");const n={...t,id:String(e.id),username:s};return e.avatarUrl&&(n.avatarUrl=e.avatarUrl),e.name&&(n.name=e.name),e.email&&(n.email=e.email),n},In=(e,t)=>{if(!e||!Ps(e.id)||!Bu(t,e.owner)||!O(e.name)||!zs(e.url)||!Tt(e,t)||e.cloneUrl!==void 0&&!O(e.cloneUrl)||e.sshUrl!==void 0&&!O(e.sshUrl)||e.defaultBranch!==void 0&&!O(e.defaultBranch)||e.defaultBranchSha!==void 0&&e.defaultBranchSha!==null&&!O(e.defaultBranchSha)||e.remoteName!==void 0&&e.remoteName!==null&&!O(e.remoteName))throw new Error("Source control response contained an invalid project");const s={...t,id:String(e.id),owner:e.owner,name:e.name,url:e.url};return e.cloneUrl&&(s.cloneUrl=e.cloneUrl),e.sshUrl&&(s.sshUrl=e.sshUrl),e.defaultBranch&&(s.defaultBranch=e.defaultBranch),e.defaultBranchSha!==void 0&&(s.defaultBranchSha=e.defaultBranchSha),e.remoteName!==void 0&&(s.remoteName=e.remoteName),s},Pv=(e,t)=>{if(e==null)return null;if(!e.summary)throw new Error("Source control response contained an invalid CI summary");if(dG(e.summary),e.runs!==void 0){if(!Array.isArray(e.runs)||e.runs.some(s=>!s||!Ps(s.id)||!O(s.name)||!Tt(s,t)||s.detailsUrl!==void 0&&!zs(s.detailsUrl)))throw new Error("Source control response contained invalid CI runs");for(const s of e.runs){if(s.startedAt!==void 0&&!O(s.startedAt)||s.completedAt!==void 0&&!O(s.completedAt)||s.status!==void 0&&!O(s.status)||s.conclusion!==void 0&&s.conclusion!==null&&!Y(s.conclusion))throw new Error("Source control response contained invalid CI run fields");if(s.application!==void 0&&(Object.prototype.toString.call(s.application)!=="[object Object]"||s.application.name!==void 0&&!Y(s.application.name)||s.application.slug!==void 0&&!Y(s.application.slug)))throw new Error("Source control response contained an invalid CI application");if(s.job!==void 0&&(Object.prototype.toString.call(s.job)!=="[object Object]"||s.job.runId!==void 0&&!Ps(s.job.runId)||s.job.jobId!==void 0&&!Ps(s.job.jobId)||s.job.url!==void 0&&!zs(s.job.url)||s.job.name!==void 0&&!Y(s.job.name)||s.job.workflowName!==void 0&&!Y(s.job.workflowName)||s.job.conclusion!==void 0&&s.job.conclusion!==null&&!Y(s.job.conclusion)))throw new Error("Source control response contained an invalid CI job");if(s.job?.steps!==void 0&&(!Array.isArray(s.job.steps)||s.job.steps.some(a=>!a||!O(a.name)||a.status!==void 0&&!Y(a.status)||a.conclusion!==void 0&&a.conclusion!==null&&!Y(a.conclusion)||a.number!==void 0&&(!Number.isInteger(a.number)||a.number<0)||a.startedAt!==void 0&&!O(a.startedAt)||a.completedAt!==void 0&&!O(a.completedAt))))throw new Error("Source control response contained invalid CI steps");if(s.output!==void 0&&(Object.prototype.toString.call(s.output)!=="[object Object]"||s.output.title!==void 0&&!Y(s.output.title)||s.output.summary!==void 0&&!Y(s.output.summary)||s.output.text!==void 0&&!Y(s.output.text)))throw new Error("Source control response contained invalid CI output");if(s.annotations!==void 0&&(!Array.isArray(s.annotations)||s.annotations.some(a=>!a||!O(a.message)||a.path!==void 0&&!Y(a.path)||a.startLine!==void 0&&(!Number.isInteger(a.startLine)||a.startLine<0)||a.endLine!==void 0&&(!Number.isInteger(a.endLine)||a.endLine<0)||a.level!==void 0&&!Y(a.level)||a.title!==void 0&&!Y(a.title)||a.rawDetails!==void 0&&!Y(a.rawDetails))))throw new Error("Source control response contained invalid CI annotations")}}return{summary:{state:e.summary.state,total:e.summary.total,success:e.summary.success,failure:e.summary.failure,pending:e.summary.pending,inProgress:e.summary.inProgress,queued:e.summary.queued,startedAt:e.summary.startedAt},runs:e.runs?.map(s=>({...t,id:String(s.id),name:s.name,status:s.status,conclusion:s.conclusion,startedAt:s.startedAt,completedAt:s.completedAt,detailsUrl:s.detailsUrl,application:s.application,job:s.job,output:s.output,annotations:s.annotations}))}},sp=(e,t)=>{if(!e||!Ps(e.id)||!Number.isInteger(e.number)||e.number<1||!O(e.title)||!zs(e.url)||!["open","closed","merged"].includes(e.state)||!Ae(e.draft)||!O(e.base)||!O(e.head)||!Tt(e,t)||e.body!==void 0&&!Y(e.body)||e.headSha!==void 0&&!O(e.headSha)||e.author!==void 0&&e.author!==null&&!Tt(e.author,t)||e.createdAt!==void 0&&!O(e.createdAt)||e.updatedAt!==void 0&&!O(e.updatedAt)||e.headLabel!==void 0&&!O(e.headLabel)||e.mergeable!==void 0&&e.mergeable!==null&&!Ae(e.mergeable)||e.mergeableState!==void 0&&e.mergeableState!==null&&!Y(e.mergeableState)||e.labels!==void 0&&(!Array.isArray(e.labels)||e.labels.some(a=>!a||!O(a.name)||a.color!==void 0&&!Y(a.color)))||e.workInProgress!==void 0&&!Ae(e.workInProgress)||e.private!==void 0&&!Ae(e.private)||e.topic!==void 0&&!Y(e.topic)||e.hashtags!==void 0&&(!Array.isArray(e.hashtags)||e.hashtags.some(a=>!O(a)))||e.revisionNumber!==void 0&&!Gt(e.revisionNumber))throw new Error("Source control response contained an invalid change request");const s={...t,id:String(e.id),number:e.number,project:In(e.project,t),title:e.title,url:e.url,state:e.state,draft:e.draft,base:e.base,head:e.head};return e.body!==void 0&&(s.body=e.body),e.headSha&&(s.headSha=e.headSha),e.author!==void 0&&e.author!==null&&(s.author=bt(e.author,t)),e.createdAt&&(s.createdAt=e.createdAt),e.updatedAt&&(s.updatedAt=e.updatedAt),e.headLabel&&(s.headLabel=e.headLabel),e.headProject!==void 0&&e.headProject!==null&&(s.headProject=In(e.headProject,t)),e.mergeable!==void 0&&(s.mergeable=e.mergeable),e.mergeableState!==void 0&&(s.mergeableState=e.mergeableState),e.labels!==void 0&&(s.labels=e.labels.map(a=>({name:a.name,color:a.color}))),e.workInProgress!==void 0&&(s.workInProgress=e.workInProgress),e.private!==void 0&&(s.private=e.private),e.topic&&(s.topic=e.topic),e.hashtags!==void 0&&(s.hashtags=[...e.hashtags]),e.revisionNumber!==void 0&&(s.revisionNumber=e.revisionNumber),s},Fh=(e,t)=>{if(!e||!Ps(e.id)||!Number.isInteger(e.number)||e.number<1||!O(e.title)||!zs(e.url)||e.state!=="open"&&e.state!=="closed"||!Tt(e,t)||e.body!==void 0&&!Y(e.body)||e.author!==void 0&&e.author!==null&&!Tt(e.author,t)||e.createdAt!==void 0&&!O(e.createdAt)||e.updatedAt!==void 0&&!O(e.updatedAt))throw new Error("Source control response contained an invalid issue");if(e.assignees!==void 0&&(!Array.isArray(e.assignees)||e.assignees.some(a=>!Tt(a,t))))throw new Error("Source control response contained invalid issue assignees");if(e.labels!==void 0&&(!Array.isArray(e.labels)||e.labels.some(a=>!a||!O(a.name)||a.color!==void 0&&!Y(a.color))))throw new Error("Source control response contained invalid issue labels");const s={...t,id:String(e.id),number:e.number,project:In(e.project,t),title:e.title,url:e.url,state:e.state};return e.body!==void 0&&(s.body=e.body),e.author!==void 0&&(s.author=e.author?bt(e.author,t):null),e.assignees!==void 0&&(s.assignees=e.assignees.map(a=>bt(a,t))),e.labels!==void 0&&(s.labels=e.labels.map(a=>({name:a.name,color:a.color}))),e.createdAt&&(s.createdAt=e.createdAt),e.updatedAt&&(s.updatedAt=e.updatedAt),s},ZH=e=>{if(!e||!O(e.sha)||!Y(e.headline)||e.authorName!==null&&!Y(e.authorName)||e.committedAt!==null&&!O(e.committedAt)||e.url!==null&&!zs(e.url))throw new Error("Source control response contained an invalid commit");return{sha:e.sha,headline:e.headline,authorName:e.authorName,committedAt:e.committedAt,url:e.url}},JH=["open","closed","merged"],$H=e=>{if(!e||!O(e.base)||!Array.isArray(e.layers)||e.number!==null&&!Number.isSafeInteger(e.number))throw new Error("Source control response contained an invalid merge request chain");return{number:e.number,base:e.base,layers:e.layers.map(t=>{const s=JH.find(a=>a===t?.state);if(!t||!Number.isSafeInteger(t.number)||!Y(t.title)||!zs(t.url)||!s||!Ae(t.draft)||!O(t.head))throw new Error("Source control response contained an invalid merge request chain");return{number:t.number,title:t.title,url:t.url,state:s,draft:t.draft,head:t.head}})}},xv=e=>{try{return $H(e)}catch{return}},QH=(e,t)=>{if(!e||e.state!=="approved"&&e.state!=="changes_requested"||!O(e.url)||e.createdAt!==null&&!O(e.createdAt))throw new Error("Source control response contained an invalid review verdict");const s={state:e.state,url:e.url,createdAt:e.createdAt};return e.author&&(s.author=bt(e.author,t)),s},YH=["approved","rejected","recommended","disliked","neutral"],XH=["satisfied","unsatisfied","overridden","not-applicable","error","forced"],eG=["rework","trivial-rebase","merge-first-parent-update","no-code-change","no-change"],Fo=e=>yc(e)&&Number.isInteger(e)&&e>=-10&&e<=10,tG=(e,t)=>{if(!e||!Fo(e.value)||e.revision!==void 0&&!Gt(e.revision))throw new Error("Source control response contained an invalid vote");const s={user:bt(e.user,t),value:e.value};return e.revision!==void 0&&(s.revision=e.revision),s},sG=(e,t)=>{const s=YH.find(a=>a===e?.status);if(!e||!O(e.name)||!s||!Fo(e.defaultValue)||!Ae(e.blocking)||!Array.isArray(e.values)||e.values.some(a=>!a||!Fo(a.value)||!Y(a.description))||!Array.isArray(e.permitted)||e.permitted.some(a=>!Fo(a))||!Array.isArray(e.votes))throw new Error("Source control response contained an invalid vote label");return{name:e.name,values:e.values.map(a=>({value:a.value,description:a.description})),defaultValue:e.defaultValue,permitted:[...e.permitted],blocking:e.blocking,status:s,votes:e.votes.map(a=>tG(a,t))}},aG=e=>{const t=XH.find(a=>a===e?.status);if(!e||!O(e.name)||!t||e.description!==void 0&&!Y(e.description))throw new Error("Source control response contained an invalid submit requirement");const s={name:e.name,status:t};return e.description&&(s.description=e.description),s},nG=(e,t)=>{const s=e?.kind===void 0?void 0:eG.find(n=>n===e.kind);if(!e||!Gt(e.number)||!O(e.sha)||!O(e.ref)||e.createdAt!==null&&!O(e.createdAt)||e.kind!==void 0&&!s)throw new Error("Source control response contained an invalid revision");const a={number:e.number,sha:e.sha,createdAt:e.createdAt,ref:e.ref};return e.uploader&&(a.uploader=bt(e.uploader,t)),s&&(a.kind=s),a},oG=e=>{if(!e||!O(e.sha)||e.changeId!==null&&!O(e.changeId)||e.uploadedAs!==null&&!Gt(e.uploadedAs))throw new Error("Source control response contained an invalid local revision");return{sha:e.sha,changeId:e.changeId,uploadedAs:e.uploadedAs}},iG=(e,t)=>{if(e?.revision!==void 0&&!Gt(e.revision))throw new Error("Source control response contained an invalid review comment");const s={...ap(e,t),path:e.path,line:e.line,position:e.position};return e.revision!==void 0&&(s.revision=e.revision),s},ap=(e,t)=>{if(!e||!Ps(e.id)||!O(e.url)||!Y(e.body)||!Tt(e,t)||e.author!==void 0&&e.author!==null&&!Tt(e.author,t)||e.createdAt!==void 0&&!O(e.createdAt)||e.updatedAt!==void 0&&!O(e.updatedAt))throw new Error("Source control response contained an invalid comment");const s=e.thread;if(s!==void 0&&(!s||!Ps(s.id)||!Ae(s.resolved)||!Ae(s.resolvable)||!Ae(s.first)||s.canResolve!==void 0&&!Ae(s.canResolve)||s.canReply!==void 0&&!Ae(s.canReply)))throw new Error("Source control response contained an invalid comment thread");const a={...t,id:String(e.id),url:e.url,body:e.body};return s&&(a.thread={id:String(s.id),resolved:s.resolved,resolvable:s.resolvable,first:s.first},s.canResolve!==void 0&&(a.thread.canResolve=s.canResolve),s.canReply!==void 0&&(a.thread.canReply=s.canReply)),e.author&&(a.author=bt(e.author,t)),e.createdAt&&(a.createdAt=e.createdAt),e.updatedAt&&(a.updatedAt=e.updatedAt),a},Y=e=>Object.prototype.toString.call(e)==="[object String]",Ae=e=>Object.prototype.toString.call(e)==="[object Boolean]",yc=e=>Object.prototype.toString.call(e)==="[object Number]",O=e=>Y(e)&&e.trim().length>0,Gt=e=>yc(e)&&Number.isSafeInteger(e)&&e>=1,Tv=e=>yc(e)&&Number.isSafeInteger(e)&&e>=0,Ps=e=>O(e)||Number.isFinite(e),zs=e=>{if(!O(e))return!1;try{const t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"}catch{return!1}},Tt=(e,t)=>e?.provider===t.provider&&e.instance===t.instance,rG=(e,t)=>e.provider===void 0&&e.instance===void 0?!0:Tt(e,t),cG=(e,t)=>{if(!yc(e)||!Number.isInteger(e)||e<1||!Ae(t))throw new Error("Source control response contained invalid pagination");return{page:e,hasMore:t}},Eh=(e,t)=>{const s={items:t,...cG(e.page,e.hasMore)},a=MH(e.incompleteProjectIds);return a?.length&&(s.incompleteProjectIds=a),s},lG=e=>{if(!e||!Array.isArray(e.branches)||e.branches.some(t=>!O(t)))throw new Error("Source control response contained invalid branches");return[...e.branches]},dG=e=>{if(!["success","failure","pending","unknown"].includes(e.state)||!Number.isInteger(e.total)||e.total<0||!Number.isInteger(e.success)||e.success<0||!Number.isInteger(e.failure)||e.failure<0||!Number.isInteger(e.pending)||e.pending<0||e.inProgress!==void 0&&(!Number.isInteger(e.inProgress)||e.inProgress<0)||e.queued!==void 0&&(!Number.isInteger(e.queued)||e.queued<0)||e.startedAt!==void 0&&!O(e.startedAt))throw new Error("Source control response contained an invalid CI summary")},pG=(e,t,s)=>{if(!e||!Tt(e.identity,t)||!O(e.branch)||e.branch!==s||e.project===void 0||e.changeRequest===void 0||e.fetchedAt!==void 0&&(!Number.isFinite(e.fetchedAt)||e.fetchedAt<0)||e.canMerge!==void 0&&!Ae(e.canMerge)||e.defaultBranch!==void 0&&e.defaultBranch!==null&&!O(e.defaultBranch)||e.resolvedRemoteName!==void 0&&e.resolvedRemoteName!==null&&!O(e.resolvedRemoteName))throw new Error("Source control response contained an invalid change request status");const a={identity:t,project:e.project===null?null:In(e.project,t),branch:e.branch,changeRequest:e.changeRequest===null?null:sp(e.changeRequest,t)};if(e.ci!==void 0&&(a.ci=Pv(e.ci,t)),e.canMerge!==void 0&&(a.canMerge=e.canMerge),e.defaultBranch!==void 0&&(a.defaultBranch=e.defaultBranch),e.resolvedRemoteName!==void 0&&(a.resolvedRemoteName=e.resolvedRemoteName),e.fetchedAt!==void 0&&(a.fetchedAt=e.fetchedAt),e.localRevision!==void 0&&(a.localRevision=oG(e.localRevision)),e.stack===null)a.stack=null;else if(e.stack!==void 0){const n=xv(e.stack);n&&(a.stack=n)}return a},zl=(e,t)=>(e??[]).map(s=>{if(!O(s.id)||s.id!==s.credentialId||!Gt(s.credentialRevision)||!O(s.providerUserId)||!["available","unavailable"].includes(s.providerUserStatus)||!Ae(s.current)||!["oauth","pat","cli"].includes(s.source)||!["valid","invalid"].includes(s.status))throw new Error("Source control response contained an invalid auth credential");return{id:s.id,credentialId:s.credentialId,credentialRevision:s.credentialRevision,providerUserId:s.providerUserId,providerUserStatus:s.providerUserStatus,user:bt(s.user,t),scope:s.scope,current:s.current,source:s.source,status:s.status}}),Rl=(e,t)=>{if(!e.connected){if(!e.status){const s={...t,status:"disconnected",connected:!1};return e.cli&&(s.cli={available:e.cli.available,disabled:e.cli.disabled,active:e.cli.active,user:e.cli.user?bt(e.cli.user,t):void 0}),s.accounts=zl(e.accounts,t),s}return{...e,...t,connected:!1,accounts:zl(e.accounts,t)}}return{...t,status:"connected",connected:!0,user:bt(e.user,t),scope:e.scope,accounts:zl(e.accounts,t),cli:e.cli?{available:e.cli.available,disabled:e.cli.disabled,active:e.cli.active,user:e.cli.user?bt(e.cli.user,t):void 0}:void 0}},uG=(e={})=>{const t=e.fetch??T;return{repositoryContext:async s=>Sv(await Dh(t,"/api/source-control/repository-context",s)),repositoryBinding:async s=>fn(await Dh(t,"/api/source-control/binding",s)),resetRepositoryBinding:async s=>{const a=await t("/api/source-control/binding/reset",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(s)}),n=await a.json();if(!a.ok)throw new ys(n.error||a.statusText||"Source control binding reset failed",n.code);return fn(n)},repositoryProviderBindingMutate:async s=>{const a=await t("/api/source-control/binding/provider",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(s)}),n=await a.json();if(!a.ok)throw new ys(n.error||a.statusText||"Source control binding request failed",n.code);return fn(n)},providers:async()=>{const s=await yH(t);return Cv(s),s},authInstances:async()=>{const s=await t("/api/source-control/instances",{headers:{Accept:"application/json"}}),a=await s.json();if(!s.ok)throw new Error(a.error||s.statusText||"Failed to list source control instances");return a.instances.map(K)},capabilities:async s=>{const a=await Qe(t,s,"/capabilities");return{identity:K(a.identity),authentication:a.authentication,authenticationMethods:a.authenticationMethods,multipleAccounts:a.multipleAccounts,projects:a.projects,issues:a.issues,changeRequests:a.changeRequests,draftChangeRequests:a.draftChangeRequests,draftConversion:a.draftConversion===!0,mergeChangeRequests:a.mergeChangeRequests,mergeMethods:a.mergeMethods?[...a.mergeMethods]:void 0,ci:a.ci}},authStatus:async s=>{const a=K(s);return Rl(await Qe(t,a,"/auth/status"),a)},authStart:async s=>{const a=await Qe(t,s,"/auth/start",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),n={flowId:a.flowId,userCode:a.userCode,verificationUri:a.verificationUri,expiresIn:a.expiresIn,interval:a.interval};return a.verificationUriComplete&&(n.verificationUriComplete=a.verificationUriComplete),a.scope&&(n.scope=a.scope),n},authComplete:async(s,a)=>{let n;try{n=await de(t,s,"/auth/complete",{flowId:a})}catch(i){if(i instanceof ys&&i.code==="SOURCE_CONTROL_OAUTH_FLOW_UNAVAILABLE")return{status:"error",code:"expired",message:i.message};throw i}if(n.connected){const i={status:"connected",user:bt(n.user,K(s))};return n.scope&&(i.scope=n.scope),i}if(n.status==="authorization_pending"||n.status==="slow_down"){const i={status:"pending"};return n.status==="slow_down"&&(i.slowDown=!0),i}let o="provider-error";return n.status==="access_denied"?o="access-denied":n.status==="expired_token"&&(o="expired"),{status:"error",code:o,message:n.error||n.status||`${ni(s)} authentication failed`}},authSetToken:async(s,a,n)=>{const o=K(s);return await de(t,o,"/auth/token",n?.username?{token:a,username:n.username}:{token:a}),Rl(await Qe(t,o,"/auth/status"),o)},authSetSshUrl:async(s,a)=>{const n=K(s),o=await de(t,n,"/auth/ssh-url",{sshUrl:a});if(o.sshUrl!==null&&!O(o.sshUrl))throw new Error("Source control response contained an invalid SSH URL");return{sshUrl:o.sshUrl??null}},setInstanceAliases:async(s,a)=>{const n=K(s),o=await t("/api/source-control/instances/aliases",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({provider:n.provider,instance:n.instance,aliases:a})}),i=await o.json();if(!o.ok){const r=i.error||o.statusText||"Failed to save instance aliases";throw(i.code==="INVALID_INSTANCE_ALIAS"||i.code==="INSTANCE_ALIAS_TAKEN")&&O(i.alias)?new RV(r,i.code==="INSTANCE_ALIAS_TAKEN"?"taken":"invalid",i.alias):new ys(r,i.code)}if(!Array.isArray(i.aliases)||!i.aliases.every(O))throw new Error("Source control response contained invalid instance aliases");return{aliases:[...i.aliases]}},authDisconnect:async(s,a)=>{if(!O(a)||a.trim()!==a)throw new Error("Source control credential accountId is required");const n=new URLSearchParams({accountId:a}),o=await Qe(t,s,"/auth",{method:"DELETE"},n);if(!Ae(o.removed))throw new Error("Source control response contained an invalid account removal result");return{removed:o.removed}},authActivate:async(s,a)=>{const n=K(s);return Rl(await de(t,n,"/auth/activate",{accountId:a}),n)},authSetCliDisabled:async(s,a)=>{const n=K(s);return{disabled:!!(await de(t,n,"/auth/cli",{disabled:a})).disabled}},changeRequestStatus:async(s,a,n)=>{const o=K(s),i=ps(s);i.set("branch",a),n?.force&&i.set("force","true");const r=await Qe(t,o,"/pr/status",{},i);return pG(r,o,a)},changeRequestCreate:async s=>{const a=K(s),o={...ve(s,a,"create"),title:s.title};s.body!==void 0&&(o.body=s.body),s.draft!==void 0&&(o.draft=s.draft),s.remote&&(o.remote=s.remote),s.headRemote&&(o.headRemote=s.headRemote);const i=await de(t,a,"/pr/create",o);return Ce(i,s,a,VH)},changeRequestUpdate:async s=>{const a=K(s),n={...ve(s,a,"existing"),title:s.title};s.body!==void 0&&(n.body=s.body);const o=await de(t,a,"/pr/update",n);return Ce(o,s,a,$e)},changeRequestMerge:async s=>{const a=K(s),n=await de(t,a,"/pr/merge",{...ve(s,a,"existing"),method:s.method,cancel:s.cancel});return Ce(n,s,a,UH)},changeRequestReady:async s=>{const a=K(s),n=await de(t,a,"/pr/ready",ve(s,a,"existing"));return Ce(n,s,a,_H)},changeRequestDraft:async s=>{const a=K(s),n=await de(t,a,"/pr/draft",ve(s,a,"existing"));return Ce(n,s,a,KH)},changeRequestComment:async s=>{const a=K(s),n=await de(t,a,"/pr/comment",{...ve(s,a,"existing"),body:s.body});return Ce(n,s,a,$e)},changeRequestStartThread:async s=>{const a=K(s),n=await de(t,a,"/pr/thread/start",{...ve(s,a,"existing"),body:s.body});return Ce(n,s,a,$e)},changeRequestReplyToThread:async s=>{const a=K(s),n=await de(t,a,"/pr/thread/reply",{...ve(s,a,"existing"),threadId:s.threadId,body:s.body});return Ce(n,s,a,$e)},changeRequestResolveThread:async s=>{const a=K(s),n=await de(t,a,"/pr/thread/resolve",{...ve(s,a,"existing"),threadId:s.threadId,resolved:s.resolved});return Ce(n,s,a,$e)},changeRequestReview:async s=>{const a=K(s),n=ve(s,a,"existing");let o;if(s.votes!==void 0){const r=Object.entries(s.votes);if(s.verdict!==void 0||r.length===0&&s.publishDrafts!==!0||r.some(([l,p])=>!O(l)||!Fo(p)))throw new Error("Source control review input is invalid");o={...n,votes:Object.fromEntries(r),publishDrafts:s.publishDrafts}}else o={...n,verdict:s.verdict};s.body!==void 0&&(o.body=s.body);const i=await de(t,a,"/pr/review",o);return Ce(i,s,a,WH)},changeRequestReviewState:(s,a)=>RH(t,s,a),changeRequestReviewComment:async s=>{const a=K(s),n=s.line===void 0?{path:s.path}:{path:s.path,side:s.side,line:s.line,startLine:s.startLine},o=await de(t,a,"/pr/review/comment",{...ve(s,a,"existing"),...n,body:s.body});return Ce(o,s,a,$e)},changeRequestReviewCommentUpdate:async s=>{const a=K(s),n=await de(t,a,"/pr/review/comment/update",{...ve(s,a,"existing"),commentId:s.commentId,body:s.body});return Ce(n,s,a,$e)},changeRequestReviewCommentDelete:async s=>{const a=K(s),n=await de(t,a,"/pr/review/comment/delete",{...ve(s,a,"existing"),commentId:s.commentId});return Ce(n,s,a,$e)},changeRequestReviewDiscard:async s=>{const a=K(s),n=await de(t,a,"/pr/review/discard",ve(s,a,"existing"));return Ce(n,s,a,$e)},changeRequestSetState:async s=>{const a=K(s),n=await de(t,a,"/pr/state",{...ve(s,a,"existing"),state:s.state});return Ce(n,s,a,Al)},issueSetState:async s=>{const a=K(s),n=await de(t,a,"/issues/state",{...ve(s,a,"existing"),state:s.state});return Ce(n,s,a,Al)},changeRequestSetLabels:async s=>{const a=K(s),n=await de(t,a,"/pr/labels",{...ve(s,a,"existing"),labels:s.labels});return Ce(n,s,a,$e)},issueSetLabels:async s=>{const a=K(s),n=await de(t,a,"/issues/labels",{...ve(s,a,"existing"),labels:s.labels});return Ce(n,s,a,$e)},changeRequestSetReviewers:async s=>{const a=K(s),n=await de(t,a,"/pr/reviewers",{...ve(s,a,"existing"),reviewers:s.reviewers});return Ce(n,s,a,$e)},refreshProviderReads:async(s,a)=>{const n="item"in a?new URLSearchParams({scope:"item",owner:a.item.owner,repo:a.item.repo,number:String(a.item.number)}):new URLSearchParams({scope:"lists"});await Qe(t,s,"/read-cache/refresh",{method:"POST"},n)},referenceLabels:async(s,a)=>HH(await Nh(t,s,a,"/references/labels")),referenceReviewers:async(s,a)=>GH(await Nh(t,s,a,"/references/reviewers")),issueComment:async s=>{const a=K(s),n=await de(t,a,"/issues/comment",{...ve(s,a,"existing"),body:s.body});return Ce(n,s,a,$e)},discussionComment:async s=>{const a=K(s),n={...ve(s,a,"existing"),body:s.body};s.replyTo&&(n.replyTo=s.replyTo);const o=await de(t,a,"/discussions/comment",n);return Ce(o,s,a,$e)},discussionSetState:async s=>{const a=K(s),n=ve(s,a,"existing"),o=await de(t,a,"/discussions/state",s.state==="closed"?{...n,state:"closed",reason:s.reason}:{...n,state:"open"});return Ce(o,s,a,Al)},discussionSetAnswer:async s=>{const a=K(s),n=await de(t,a,"/discussions/answer",{...ve(s,a,"existing"),commentId:s.commentId,answer:s.answer});return Ce(n,s,a,$e)},discussionSetLabels:async s=>{const a=K(s),n=await de(t,a,"/discussions/labels",{...ve(s,a,"existing"),labels:s.labels});return Ce(n,s,a,$e)},changeRequestsList:async(s,a)=>{const n=K(s),o=ps(s);o.set("page",String(a?.page??1)),a?.query&&o.set("query",a.query),a?.state&&o.set("state",a.state),a?.people&&o.set("people",a.people);const i=await Qe(t,n,"/pulls/list",{},o);if(!i||!Array.isArray(i.items))throw new Error("Source control response contained invalid change requests");return Eh(i,i.items.map(r=>sp(r,n)))},changeRequestContext:async(s,a,n)=>{const o=K(s),i=ps(s);i.set("number",String(a)),n?.includeDiff&&i.set("diff","1"),n?.includeCIDetails&&i.set("checkDetails","1"),n?.includeTimeline&&i.set("timeline","1"),n?.revision&&i.set("revision",n.revision),n?.project&&(i.set("owner",n.project.owner),i.set("repo",n.project.name));const r=await Qe(t,o,"/pulls/context",{},i),l={identity:o,project:r.project?In(r.project,o):null,changeRequest:r.changeRequest?sp(r.changeRequest,o):null,issueComments:r.issueComments.map(p=>ap(p,o)),reviewComments:r.reviewComments.map(p=>iG(p,o)),files:r.files.map(p=>({...p})),diff:r.diff,ci:Pv(r.ci,o),fetchedAt:r.fetchedAt};if(r.commits&&(l.commits=r.commits.map(ZH),l.commitsComplete=r.commitsComplete!==!1,l.verdicts=(r.verdicts??[]).map(p=>QH(p,o)),r.reviewers&&(l.reviewers=r.reviewers.map(p=>bt(p,o)))),r.stack===null)l.stack=null;else if(r.stack!==void 0){const p=xv(r.stack);p&&(l.stack=p)}if(r.voteLabels!==void 0){if(!Array.isArray(r.voteLabels))throw new Error("Source control response contained invalid vote labels");l.voteLabels=r.voteLabels.map(p=>sG(p,o))}if(r.submitRequirements!==void 0){if(!Array.isArray(r.submitRequirements))throw new Error("Source control response contained invalid submit requirements");l.submitRequirements=r.submitRequirements.map(aG)}if(r.revisions!==void 0){if(!Array.isArray(r.revisions))throw new Error("Source control response contained invalid revisions");l.revisions=r.revisions.map(p=>nG(p,o))}return l},issuesList:async(s,a)=>{const n=K(s),o=ps(s);o.set("page",String(a?.page??1)),a?.query&&o.set("query",a.query),a?.state&&o.set("state",a.state),a?.people&&o.set("people",a.people);const i=await Qe(t,n,"/issues/list",{},o);if(!i||!Array.isArray(i.items))throw new Error("Source control response contained invalid issues");return Eh(i,i.items.map(r=>Fh(r,n)))},issueGet:async(s,a,n)=>{const o=K(s),i=ps(s);i.set("number",String(a)),n&&(i.set("owner",n.owner),i.set("repo",n.name));const r=await Qe(t,o,"/issues/get",{},i);return r===null?null:Fh(r,o)},issueComments:async(s,a,n)=>{const o=K(s),i=ps(s);i.set("number",String(a)),n&&(i.set("owner",n.owner),i.set("repo",n.name));const r=await Qe(t,o,"/issues/comments",{},i);if(!Array.isArray(r))throw new Error("Source control response contained invalid comments");return r.map(l=>ap(l,o))},projectUpstream:async s=>{const a=K(s),n=ps(s),o=await Qe(t,a,"/repo/upstream",{},n);if(!o||!Tt(o.identity,a)||!Ae(o.isFork)||o.upstream!==null&&o.upstream===void 0||o.isFork!==!!o.upstream)throw new Error("Source control response contained an invalid upstream");return{identity:a,isFork:o.isFork,upstream:o.upstream?In(o.upstream,a):null}},projectBranches:async(s,a,n)=>{const o=K(s),i=ps(s);i.set("owner",a),i.set("repo",n);const r=await Qe(t,o,"/repo/branches",{},i);return lG(r)},references:(s,a)=>TH(t,s,a),referencesAcross:(s,a)=>IH(t,s,a),referenceDetail:(s,a)=>AH(t,s,a),changeRequestListStatuses:(s,a)=>jH(t,s,a)}},gG=d({status:m("unsupported"),reason:m("host-setup-required")}).strict(),Av=c().regex(/^SHA256:[A-Za-z0-9+/]{43}=?$/),np=d({credentialId:c().regex(/^ocgit:v1:ssh:[A-Za-z0-9_-]{1,267}$/),label:m("SSH"),fingerprint:Av,capability:M([d({status:m("ready")}).strict(),d({status:m("unavailable"),reason:S(["unreadable","encrypted-or-unverifiable","fingerprint-mismatch"])}).strict()])}).strict(),mG=np.extend({capability:d({status:m("ready")}).strict()}),Mh=c().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/),hG=M([d({candidateId:c().regex(/^[A-Za-z0-9_-]{1,200}$/),label:Mh,fingerprint:Av,capability:d({status:m("ready")}).strict()}).strict(),d({label:Mh,capability:d({status:m("unavailable"),reason:S(["unreadable","encrypted-or-unverifiable","insecure-permissions"])}).strict()}).strict()]),fG=M([gG,d({status:m("available"),credentials:C(np).max(256)}).strict(),d({status:m("discovered"),candidates:C(hG).max(128),truncated:y()}).strict(),d({status:m("imported"),credentials:C(np).max(256),selectedCredential:mG}).strict(),d({status:m("rejected"),reason:S(["candidate-expired","candidate-changed","fingerprint-mismatch","candidate-unavailable","inventory-full"])}).strict()]),bG=async(e,t=T)=>{const s=await t("/api/git/managed-ssh-credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!s.ok)throw new Error("Managed SSH inventory request failed");const a=fG.parse(await s.json());if(a.status==="imported"&&!a.credentials.some(n=>n.credentialId===a.selectedCredential.credentialId&&n.fingerprint===a.selectedCredential.fingerprint&&n.capability.status==="ready"))throw new Error("Managed SSH import response is inconsistent");return a},kG=()=>({managedSshCredentials:bG,configureTransportBinding:NH,removeTransportBinding:FH,configureAuxiliaryBinding:EH,checkIsGitRepository:RU,getGitStatus:jU,prefetchProjectStatuses:zU,getGitDiff:OU,getGitDiffs:DU,getGitFileDiff:BU,getGitRangeDiff:NU,getGitRangeFiles:EU,getBranchBase:MU,revertGitFile:LU,stageGitFile:qU,stageGitFiles:lv,unstageGitFile:VU,unstageGitFiles:dv,stageGitHunk:UU,unstageGitHunk:WU,revertGitHunk:HU,isLinkedWorktree:GU,getGitBranches:_U,getGitUnpushedBranchCounts:KU,deleteGitBranch:ZU,removeRemote:JU,generateCommitMessage:$U,generatePullRequestDescription:QU,listGitWorktrees:vh,validateGitWorktree:Ch,createGitWorktree:Sh,deleteGitWorktree:Ph,validateWorktreeDirectory:nH,canonicalizeWorktreeState:oH,createGitCommit(e,t,s){return pW(e,t,s)},gitPush:uW,gitPull:gW,gitFetch:mW,planNetworkOperation:fW,issueContributorDestination:bW,listContributorDestinations:kW,inspectCheckoutTrust:wW,decideCheckoutTrust:yW,executeNetworkOperation:vW,getNetworkOperation:CW,cancelNetworkOperation:SW,listGitStashes:PW,countGitStashFiles:xW,stashGitChanges:mv,applyGitStash:TW,popGitStash:hv,dropGitStash:AW,checkoutBranch:zW,createBranch:RW,renameBranch:IW,getGitLog(e,t){return jW(e,t)},addChangeIdToHead:DW,getCommitFiles:NW,getCommitFileDiff:FW,getGitCommitDiff:FU,getCurrentGitIdentity:qW,hasLocalIdentity:VW,setGitIdentity:WW,getGitIdentities:EW,createGitIdentity:MW,updateGitIdentity:BW,deleteGitIdentity:LW,getGlobalGitIdentity:UW,getRemotes:HW,rebase:GW,abortRebase:_W,continueRebase:XW,merge:KW,abortMerge:YW,continueMerge:eH,checkoutCommit:ZW,cherryPick:JW,revertCommit:$W,resetToCommit:QW,stash:tH,stashPop:sH,getConflictDetails:aH,worktree:{list:vh,validate:Ch,bootstrapStatus:YU,preview:XU,create:Sh,remove:Ph,teardown:eW,setTitle:sW,setPinned:nW,snapshot:dW,archive:oW,listArchives:iW,restoreArchive:rW,deleteArchive:cW}});let Bh=null;const wG=()=>window.Capacitor,yG=e=>e.getPlatform?.()!=="android"||!e.registerPlugin?null:(Bh??=e.registerPlugin("FileShare"),Bh),vG=async e=>{const t=new Uint8Array(await e.arrayBuffer());let s="";for(let a=0;a<t.length;a+=32768)s+=String.fromCharCode(...t.subarray(a,a+32768));return btoa(s)},CG=async e=>{const t=wG(),s=t?yG(t):null;if(s){await s.share({fileName:e.name,mimeType:e.type||"application/octet-stream",data:await vG(e)});return}if(!navigator.canShare?.({files:[e]}))throw new Error("File sharing is unavailable in this mobile runtime");await navigator.share({files:[e]})},xe=e=>e.replace(/\\/g,"/"),SG=(e,t)=>et.searchFiles(e,t),PG=(e,t)=>{if(!t||!Array.isArray(t.entries))throw new Mt("Directory listing returned an invalid response",{reason:"invalid-response"});return{directory:xe(t?.directory||t?.path||e),entries:t.entries.filter(a=>!!(a&&typeof a.name=="string"&&typeof a.path=="string")).map(a=>({name:a.name,path:xe(a.path),isDirectory:!!a.isDirectory}))}},Ct=(e,t,s)=>{const a=e?.(),n=zt(s),o=t||(n!==null&&zt(a)!==n?_f(n):a);return o?{"x-opencode-directory":o}:void 0},xG=d({matches:C(d({path:c(),relativePath:c(),line:w().int().positive(),column:w().int().positive(),text:c(),ranges:C(wr([w().int().nonnegative(),w().int().nonnegative()])),cutStart:y()})),stopped:S(["limit","deadline"]).nullable()}),TG=d({error:c().optional(),reason:c().optional()}),AG=d({files:C(d({path:c(),relativePath:c()}))}),zG=({getDirectory:e,searchFiles:t=SG})=>({async listDirectory(s,a){const n=xe(s),o=new URLSearchParams;n&&o.set("path",n),a?.respectGitignore&&o.set("respectGitignore","true");const i=await T("/api/fs/list",{query:o,headers:Ct(e,void 0,n)});if(!i.ok){const l=await i.json().catch(()=>({error:i.statusText}));throw new Mt(l.error||"Failed to list directory",{reason:vo(l.reason),status:i.status})}const r=await i.json();return PG(n,r)},async search(s){const a=xe(s.directory),n=!!s.includeHidden,o=s.respectGitignore!==!1;if(n||!o){const r=new URLSearchParams;r.set("query",s.query),a&&r.set("directory",a),typeof s.maxResults=="number"&&Number.isFinite(s.maxResults)&&r.set("limit",String(s.maxResults)),n&&r.set("includeHidden","true"),o||r.set("respectGitignore","false");const l=await T("/api/fs/search",{query:r,signal:s.signal,headers:Ct(e,a)});if(!l.ok){const u=await l.json().catch(()=>({error:l.statusText}));throw new Error(u.error||"Failed to search files")}const p=AG.safeParse(await l.json().catch(()=>null));if(!p.success)throw new Mt("File search returned an invalid response",{reason:"invalid-response"});return p.data.files.map(u=>({path:xe(u.path),preview:[xe(u.relativePath)]}))}return(await t(s.query,{directory:a,limit:typeof s.maxResults=="number"&&Number.isFinite(s.maxResults)?s.maxResults:void 0,type:"file"})).map(r=>({path:xe(r.path),preview:[xe(r.relativePath)]}))},async searchContents(s){const a=xe(s.directory),n=new URLSearchParams({query:s.query,regex:s.regex?"true":"false"});s.limit!==void 0&&n.set("limit",String(s.limit)),s.includeHidden&&n.set("includeHidden","true"),s.respectGitignore===!1&&n.set("respectGitignore","false");const o=await T("/api/fs/find-in-files",{query:n,cache:"no-store",signal:s.signal,headers:Ct(e,a)});if(o.ok){const l=xG.safeParse(await o.json().catch(()=>null));if(!l.success)throw new Mt("Content search returned an invalid response",{reason:"invalid-response"});return{status:"ok",matches:l.data.matches.map(p=>({...p,path:xe(p.path)})),stopped:l.data.stopped}}const i=TG.safeParse(await o.json().catch(()=>null)),r=i.success?i.data.reason:void 0;if(o.status===501&&r==="search-unavailable")return{status:"unavailable"};if(o.status===400&&r==="invalid-pattern")return{status:"invalid-pattern",message:i.success&&i.data.error?i.data.error:"Invalid regular expression"};throw new Mt(i.success&&i.data.error||o.statusText||"Failed to search file contents",{status:o.status})},async createDirectory(s){const a=xe(s),n=await T("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json",...Ct(e,void 0,a)},body:JSON.stringify({path:a})});if(!n.ok){const i=await n.json().catch(()=>({error:n.statusText}));throw new Error(i.error||"Failed to create directory")}const o=await n.json();return{success:!!o?.success,path:typeof o?.path=="string"?xe(o.path):a}},async statFile(s,a){const n=xe(s),o=new URLSearchParams({path:n});a?.allowOutsideWorkspace&&o.set("allowOutsideWorkspace","true"),a?.outsideFileGrant&&o.set("outsideFileGrant",a.outsideFileGrant);const i=await T("/api/fs/stat",{query:o,signal:AbortSignal.timeout(3e4),headers:Ct(e,a?.directory,n)});if(!i.ok){const l=await i.json().catch(()=>({error:i.statusText}));throw new Error(l.error||"Failed to stat file")}const r=await i.json().catch(()=>({}));return{path:typeof r.path=="string"?xe(r.path):n,isFile:!!r.isFile,size:typeof r.size=="number"?r.size:0,mtimeMs:typeof r.mtimeMs=="number"?r.mtimeMs:void 0}},async readFile(s,a){const n=xe(s),o=new URLSearchParams({path:n});a?.allowOutsideWorkspace&&o.set("allowOutsideWorkspace","true"),a?.outsideFileGrant&&o.set("outsideFileGrant",a.outsideFileGrant),a?.optional&&o.set("optional","true");const i=await T("/api/fs/read",{query:o,signal:AbortSignal.timeout(3e4),cache:a?.optional||a?.fresh?"no-store":"default",headers:Ct(e,a?.directory,n)});if(!i.ok){const l=await i.json().catch(()=>({error:i.statusText}));throw new Error(l.error||"Failed to read file")}return{content:await i.text(),path:n}},async writeFile(s,a){const n=xe(s),o=await T("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json",...Ct(e,void 0,n)},body:JSON.stringify({path:n,content:a})});if(!o.ok){const r=await o.json().catch(()=>({error:o.statusText}));throw new Error(r.error||"Failed to write file")}const i=await o.json().catch(()=>({}));return{success:!!i.success,path:typeof i.path=="string"?xe(i.path):n}},async uploadFile(s,a,n){const o=xe(s),i=await T("/api/fs/upload",{method:"POST",query:{path:o,overwrite:n?.overwrite?"true":void 0},headers:{"Content-Type":"application/octet-stream",...Ct(e,n?.directory,o)},body:a});if(!i.ok){const l=await i.json().catch(()=>({error:i.statusText}));throw new Mt(l.error||"Failed to upload file",{reason:vo(l.reason),status:i.status,maxBytes:l.maxBytes})}const r=await i.json().catch(()=>({}));return{success:!!r.success,path:r.path?xe(r.path):o}},async delete(s){const a=xe(s),n=await T("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json",...Ct(e,void 0,a)},body:JSON.stringify({path:a})});if(!n.ok){const i=await n.json().catch(()=>({error:n.statusText}));throw new Error(i.error||"Failed to delete file")}return{success:!!(await n.json().catch(()=>({}))).success}},async rename(s,a){const n=await T("/api/fs/rename",{method:"POST",headers:{"Content-Type":"application/json",...Ct(e,void 0,s)},body:JSON.stringify({oldPath:s,newPath:a})});if(!n.ok){const i=await n.json().catch(()=>({error:n.statusText}));throw new Mt(i.error||"Failed to rename file",{reason:vo(i.reason),status:n.status})}const o=await n.json().catch(()=>({}));return{success:!!o.success,path:o.path?xe(o.path):a}},async revealPath(s){const a=await T("/api/fs/reveal",{method:"POST",headers:{"Content-Type":"application/json",...Ct(e,void 0,s)},body:JSON.stringify({path:xe(s)})});if(!a.ok){const o=await a.json().catch(()=>({error:a.statusText}));throw new Error(o.error||"Failed to reveal path")}return{success:!!(await a.json().catch(()=>({}))).success}},async downloadFile(s,a){const n=xe(s),o=new URLSearchParams({path:n,download:"true"});a?.allowOutsideWorkspace&&o.set("allowOutsideWorkspace","true"),a?.outsideFileGrant&&o.set("outsideFileGrant",a.outsideFileGrant);const i=await T("/api/fs/raw",{query:o,headers:Ct(e,a?.directory,n)});if(!i.ok)throw new Error(`Download failed (${i.status})`);const r=await i.blob(),l=n.split("/").pop()||"file";if(window.Capacitor?.isNativePlatform?.()===!0){await CG(new File([r],l,{type:r.type||"application/octet-stream"}));return}const u=URL.createObjectURL(r),g=document.createElement("a");g.href=u,g.download=l,document.body.appendChild(g),g.click(),document.body.removeChild(g),setTimeout(()=>URL.revokeObjectURL(u),100)}}),RG="/api/config/settings",Lh=()=>`${RG}?${xk}=${ic()}`,IG="/api/config/reload",qh=e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid settings response");return e},jG=()=>({async load(){const e=await T(Lh(),{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to load settings: ${e.statusText}`);return{settings:qh(await e.json()),source:"web"}},async save(e){const t=await T(Lh(),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!t.ok){const a=await t.json().catch(()=>({error:t.statusText}));throw new Error(a.error||"Failed to save settings")}return qh(await t.json())},async restartOpenCode(){const e=await T(IG,{method:"POST"});if(!e.ok){const t=await e.json().catch(()=>({error:e.statusText}));throw new Error(t.error||"Failed to restart OpenCode")}return{restarted:!0}}}),OG=()=>({async requestDirectoryAccess(e){return{success:!0,path:e.path}},async startAccessingDirectory(e){return{success:!0}},async stopAccessingDirectory(e){return{success:!0}}}),DG=d({type:m("openchamber:notification-navigation"),url:c().url(),expiresAt:w().finite()});let Eo=null;function zv(e){if(!Eo)return!1;try{const t=new URL(e,window.location.origin);return t.origin===window.location.origin&&t.pathname===window.location.pathname&&Eo(t)}catch{return!1}}function Q$(e){Eo=e;const t="serviceWorker"in navigator?navigator.serviceWorker:null,s=a=>{const n=DG.safeParse(a.data),o=a.ports[0];if(!(!n.success||!o))try{const i=a.origin===window.location.origin&&Date.now()<n.data.expiresAt&&zv(n.data.url);o.postMessage(i)}catch{o.postMessage(!1)}finally{o.close()}};return t?.addEventListener("message",s),()=>{t?.removeEventListener("message",s),Eo===e&&(Eo=null)}}const NG=1500,op=5e3,FG="openchamber-notification-claim:",Mo=new Map,EG=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),MG=e=>{if(typeof e!="string")return null;const t=e.trim();return t?`/?session=${encodeURIComponent(t)}`:null},Rv=e=>{const t=typeof e?.sessionId=="string"?e.sessionId.trim():"";if(!t)return;const s=MG(t);if(s)return{url:s,sessionId:t}},Iv=(e,t)=>{const s={body:e?.body,tag:e?.tag};return t&&(s.data=t),s},BG=e=>{try{if(typeof window>"u"||(typeof window.focus=="function"&&window.focus(),!e)||`${window.location.pathname}${window.location.search}`===e.url||zv(e.url))return;window.location.assign(e.url)}catch{}},LG=e=>{const t=typeof e?.tag=="string"?e.tag.trim():"";return t||[e?.sessionId,e?.kind,e?.title,e?.body].filter(s=>typeof s=="string"&&s.trim().length>0).map(s=>s.trim()).join("|")},qG=e=>{for(const[t,s]of Mo)e-s>op&&Mo.delete(t)},VG=e=>{const t=LG(e);if(!t)return!0;const s=Date.now();qG(s);const a=Mo.get(t)??0;if(s-a<op)return!1;try{if(typeof window<"u"&&window.localStorage){const n=`${FG}${t}`,o=Number(window.localStorage.getItem(n)??"0");if(Number.isFinite(o)&&s-o<op)return Mo.set(t,o),!1;Number.isFinite(o)&&o>0&&window.localStorage.removeItem(n),window.localStorage.setItem(n,String(s))}}catch{}return Mo.set(t,s),!0},jv=async()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;let e=null;try{e=await navigator.serviceWorker.getRegistration()??null}catch{e=null}if(e?.active)return e;if(!e)return null;try{return await Promise.race([navigator.serviceWorker.ready,new Promise(s=>{setTimeout(()=>s(null),NG)})])??e}catch{return e}},UG=async e=>{const t=await jv();if(!t||typeof t.showNotification!="function")return!1;try{const s=Rv(e);return await t.showNotification(e?.title??"OpenChamber",Iv(e,s)),!0}catch(s){return console.warn("Failed to send notification via service worker",s),!1}},WG=async()=>{const e=await jv();if(!e||!("pushManager"in e)||!e.pushManager)return!1;try{return!!await e.pushManager.getSubscription()}catch{return!1}},HG=async e=>{if(e?.requireHidden&&typeof document<"u"&&document.hasFocus())return!0;if(typeof Notification>"u")return console.info("Notifications not supported in this environment",e),!1;if(Notification.permission==="default"&&await Notification.requestPermission()!=="granted"||Notification.permission!=="granted")return console.warn("Notification permission not granted"),!1;if(!EG()&&await WG()||!VG(e))return!0;try{if(await UG(e))return!0;const t=Rv(e),s=new Notification(e?.title??"OpenChamber",Iv(e,t));return s.onclick=a=>{a.preventDefault(),BG(t),s.close()},!0}catch(t){return console.warn("Failed to send notification",t),!1}},GG=async e=>{if(typeof window>"u")return!1;const t=window.__OPENCHAMBER_DESKTOP__;if(!t?.invoke)return!1;try{return await t.invoke("desktop_notify",{payload:{title:e?.title,body:e?.body,tag:e?.tag,kind:e?.kind,sessionId:e?.sessionId,directory:e?.directory,runtimeKey:e?.runtimeKey,requireHidden:e?.requireHidden,showWhenFocused:e?.showWhenFocused}}),!0}catch(s){return console.warn("Failed to send native notification (desktop)",s),!1}},_G=()=>({async notifyAgentCompletion(e){return await GG(e)||await HG(e)},canNotify:()=>typeof window<"u"&&window.__OPENCHAMBER_DESKTOP__?.invoke?!0:typeof Notification<"u"?Notification.permission==="granted":!1}),Ya=async(e,t)=>{try{const s=await T(e,{...t,credentials:"include",headers:{Accept:"application/json",...t?.headers??{}}});return s.ok?await s.json():null}catch{return null}},KG=()=>({async getVapidPublicKey(){return Ya("/api/push/vapid-public-key")},async subscribe(e){return Ya("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unsubscribe(e){return Ya("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async setVisibility(e){return Ya("/api/push/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0})},async registerApnsToken(e){return Ya("/api/push/apns-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unregisterApnsToken(e){return Ya("/api/push/apns-token",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}),ZG=new Set(py),JG=c().regex(/^[a-z][a-z0-9-]{0,31}$/).refine(e=>!ZG.has(e),{message:"Reserved tracker id"}),$G=e=>{try{return new RegExp(e),!0}catch{return!1}},Vh=c().min(1).max(2048).refine($G),Zt=y().catch(!1),QG=d({id:JG,name:c().min(1).max(64),authMethods:C(c()).transform(e=>e.filter(t=>t==="oauth"||t==="token")),capabilities:d({multipleAccounts:Zt,stateUpdate:Zt,children:Zt,labels:Zt,priority:Zt,filters:d({people:Zt,priority:Zt}).catch({people:!1,priority:!1}),projectMapping:Zt,sessionComments:Zt,hostAccess:Zt}),stateFilters:C(c().min(1).max(32)).max(32),urlPatterns:C(d({host:c().min(1).max(256),path:Vh,query:d({name:c().min(1).max(64)}).optional().catch(void 0)}).nullable().catch(null)).max(8).transform(e=>e.filter(t=>t!==null)),identifierPattern:Vh}),YG=C(QG.nullable().catch(null)).transform(e=>{const t=new Set,s=[];for(const a of e)!a||t.has(a.id)||(t.add(a.id),s.push(a));return s}),Uh=new Map,Y$=e=>{const t=Uh.get(e);if(t)return t;const s={id:e,name:e,authMethods:[],capabilities:{multipleAccounts:!1,stateUpdate:!1,children:!1,labels:!1,priority:!1,filters:{people:!1,priority:!1},projectMapping:!1,sessionComments:!1,hostAccess:!1},stateFilters:["open","all"],urlPatterns:[],identifierPattern:"^[A-Za-z0-9][A-Za-z0-9._-]*$"};return Uh.set(e,s),s},XG=d({error:c()}),Ov=async(e,t)=>{const s=XG.safeParse(await e.json().catch(()=>null));return new Error(s.success&&s.data.error.trim()||e.statusText||t)};async function Dv(e,t,s,a,n){const o=new Headers({Accept:"application/json"});s.body!==void 0&&o.set("Content-Type","application/json");const i=await e(t,{method:s.method,body:s.body,headers:o});if(!i.ok)throw await Ov(i,n);const r=a.safeParse(await i.json().catch(()=>null));if(!r.success)throw new Error(`${n}: unreadable answer`);return r.data}const Xe=c().trim().min(1),At=c().trim().nullish().catch(null).transform(e=>e||null),Nv=S(["triage","backlog","todo","in-progress","done","canceled"]),e_=S(["none","urgent","high","medium","low"]),sa=e=>C(ne()).catch([]).transform(t=>t.flatMap(s=>{const a=e.safeParse(s);return a.success?[a.data]:[]})),Lu=d({name:At,avatarUrl:At}).nullish().catch(null).transform(e=>e&&(e.name||e.avatarUrl)?e:null),t_=c().nullish().catch(null).transform(e=>{const t=e?.trim().replace(/^#/,"")??"";return/^[0-9a-f]{6}$/i.test(t)?`#${t.toLowerCase()}`:null}),s_=d({id:At,name:c().trim().catch(""),category:Nv.nullable().catch(null)}).nullish().catch(null).transform(e=>e??null),a_=d({total:w().int().positive(),done:w(),more:y().catch(!1)}).nullish().catch(null).transform(e=>e?{...e,done:Math.min(Math.max(e.done,0),e.total)}:null),Fv={provider:Xe,id:Xe,identifier:Xe,title:Xe,url:Xe,state:s_,priority:e_.nullish().catch(null),assignee:Lu.optional(),container:d({id:Xe,key:At,name:Xe}).nullish().catch(null),updatedAt:At.optional()},Ev=d(Fv),Mv=d({...Fv,labels:sa(d({id:Xe,name:Xe,color:t_})).optional(),parent:Ev.nullish().catch(null),progress:a_.optional()}),n_=Mv,o_=d({id:Xe,body:c().catch(""),createdAt:At,author:Lu}),i_=Mv.extend({description:c().nullish().catch(null).transform(e=>e??null),comments:sa(o_),children:sa(Ev),childrenMore:y().catch(!1)}),Wn=d({connected:m(!1)}).transform(()=>({connected:!1})),r_=M([Wn,d({connected:m(!0),items:sa(n_),cursor:At,hasMore:y().catch(!1)})]),Wh=M([Wn,d({connected:m(!0),item:i_.nullish().catch(null).transform(e=>e??null)})]),c_=d({id:Xe,name:Xe,category:Nv.nullable().catch(null),position:w().catch(0)}),l_=M([Wn,d({connected:m(!0),states:sa(c_)})]),Il=d({id:Xe,name:At,user:Lu.optional(),current:y().catch(!1),authorizedAt:w().nullish().catch(null),status:S(["valid","invalid"]).optional().catch(void 0),invalidReason:c().trim().min(1).max(256).optional().catch(void 0),method:S(["oauth","token"]).optional().catch(void 0)}),Hh=d({instance:c().trim().min(1).max(2048).nullable().catch(null),instances:M([d({kind:m("fixed"),origin:c().trim().min(1).max(2048)}),d({kind:m("user"),label:c().trim().min(1).max(64),placeholder:c().trim().min(1).max(256).optional()})]),hasClient:y().catch(!1),redirectUri:c().trim().min(1).max(2048).nullable().catch(null)}),Gh=M([d({connected:m(!1),accounts:sa(Il).optional(),connect:Hh.optional().catch(void 0)}),d({connected:m(!0),account:Il.nullish().catch(null),accounts:sa(Il),connect:Hh.optional().catch(void 0)})]),d_=["UNSUPPORTED","INSTANCE_REQUIRED","INSTANCE_MISMATCH","UNSUPPORTED_INSTANCE","TOKEN_REQUIRED","TOKEN_REFUSED","USERNAME_REQUIRED","USERNAME_INVALID","CLIENT_MISSING","CONNECT_SUPERSEDED","TRACKER_UNAVAILABLE"],p_=d({error:c().optional(),code:c().optional()}),_h=async e=>{if(e.ok)return{ok:!0};const t=p_.safeParse(await e.json().catch(()=>null));if(!t.success)return{ok:!1,code:"failed",message:null};const s=S(d_).safeParse(t.data.code);return{ok:!1,code:s.success?s.data:"failed",message:t.data.error?.trim()||null}},u_=d({authorizationUrl:Xe,expiresIn:w().positive()}),Kh=M([Wn,d({connected:m(!0),defaultProjectPath:At,containers:sa(d({id:Xe,key:At,name:Xe,projectPath:At}))})]),_r=d({sessionComments:y()}),Bv=M([Wn,d({connected:m(!0),posted:m(!0),commentId:At}),d({connected:m(!0),posted:m(!1),skipped:S(["already-posted","issue-not-found","not-started","disabled","origin-not-public"])})]),g_=new Map([["triage","triage"],["backlog","backlog"],["unstarted","todo"],["started","in-progress"],["completed","done"],["canceled","canceled"],["duplicate","canceled"]]),Lv=e=>e?g_.get(e)??null:null,m_=new Map([["linear","linear"]]),X$=e=>m_.get(e)??"tracker",qv={id:"linear",name:"Linear",authMethods:["oauth"],capabilities:{multipleAccounts:!0,stateUpdate:!0,children:!0,labels:!0,priority:!0,filters:{people:!0,priority:!0},projectMapping:!0,sessionComments:!0,hostAccess:!0},stateFilters:["open","all","backlog","todo","in-progress","inReview","done","canceled","duplicate"],urlPatterns:[{host:"linear.app",path:"^/[^/]+/issue/([A-Za-z][A-Za-z0-9]*-\\d+)(?:/|$)"}],identifierPattern:"^[A-Za-z][A-Za-z0-9]*-\\d+$"},h_=["none","urgent","high","medium","low"],f_=new Map([["in-progress","started"],["done","completed"]]),tt=c().trim().min(1),st=c().trim().nullish().catch(null).transform(e=>e||null),Ta=e=>C(ne()).catch([]).transform(t=>t.flatMap(s=>{const a=e.safeParse(s);return a.success?[a.data]:[]})),vc=d({name:st,displayName:st,avatarUrl:st}).nullish().catch(null).transform(e=>{const t=e?.displayName||e?.name||null,s=e?.avatarUrl??null;return t||s?{name:t,avatarUrl:s}:null}),b_=d({id:st,name:st,type:st}).nullish().catch(null).transform(e=>e&&(e.id||e.name||e.type)?{id:e.id,name:e.name??"",category:Lv(e.type)}:null),Vv={id:tt,identifier:tt,title:tt,url:tt,state:b_,assignee:vc,team:d({id:tt,key:st,name:tt}).nullish().catch(null),priority:w().int().nullish().catch(null),updatedAt:st},ip=(e,t)=>({provider:t,id:e.id,identifier:e.identifier,title:e.title,url:e.url,state:e.state,priority:e.priority!=null?h_[e.priority]??null:null,assignee:e.assignee,container:e.team?{id:e.team.id,key:e.team.key,name:e.team.name}:null,updatedAt:e.updatedAt}),Uv=d(Vv),Wv=d({...Vv,labels:Ta(d({id:tt,name:tt,color:c().nullish().catch(null).transform(e=>{const t=e?.trim().replace(/^#/,"")??"";return/^[0-9a-f]{6}$/i.test(t)?`#${t.toLowerCase()}`:null})})),parent:Uv.nullish().catch(null),subIssueProgress:d({total:w().int().positive(),done:w(),more:y().catch(!1)}).nullish().catch(null)}),Hv=(e,t)=>({...ip(e,t),labels:e.labels,parent:e.parent?ip(e.parent,t):null,progress:e.subIssueProgress?{...e.subIssueProgress,done:Math.min(Math.max(e.subIssueProgress.done,0),e.subIssueProgress.total)}:null}),k_=Wv.extend({description:c().nullish().catch(null),comments:Ta(d({id:tt,body:c().catch(""),createdAt:st,user:vc})),subIssues:Ta(Uv),subIssuesMore:y().catch(!1)}),w_=(e,t)=>({...Hv(e,t),description:e.description??null,comments:e.comments.map(s=>({id:s.id,body:s.body,createdAt:s.createdAt,author:s.user})),children:e.subIssues.map(s=>ip(s,t)),childrenMore:e.subIssuesMore}),y_=d({id:tt,name:st,current:y().catch(!1),user:vc,authorizedAt:w().nullish().catch(null)}),Zh=d({connected:y(),user:vc,organization:d({id:tt,name:st}).nullish().catch(null),workspaces:Ta(y_)}).transform(e=>{if(!e.connected)return{connected:!1};const t=[...e.workspaces];return t.length===0&&e.organization&&t.push({id:e.organization.id,name:e.organization.name,user:e.user,current:!0,authorizedAt:null}),{connected:!0,account:t.find(s=>s.current)??null,accounts:t}}),v_=e=>{const t=new URLSearchParams,s=(o,i)=>{const r=i?.trim();r&&t.set(o,r)},a=e?.state?.trim();s("query",e?.query),s("cursor",e?.cursor),s("status",a?f_.get(a)??a:void 0),s("assignee",e?.people),s("teamId",e?.containerId),s("priority",e?.priority);const n=t.toString();return n?`?${n}`:""},C_=e=>{const t=async(i,r,l,p,u)=>{if(i!==qv.id)throw new Error(`Unknown tracker: ${i}`);return Dv(e,`/api/linear${r}`,l,p,u)},s={method:"GET"},a=i=>M([Wn,i]),n=i=>a(d({connected:m(!0),issue:k_.nullish().catch(null)}).transform(({issue:r})=>({connected:!0,item:r?w_(r,i):null}))),o=a(d({connected:m(!0),defaultProjectPath:st,teams:Ta(d({id:tt,key:st,name:tt,projectPath:st}))}).transform(({defaultProjectPath:i,teams:r})=>({connected:!0,defaultProjectPath:i,containers:r})));return{authStatus:i=>t(i,"/auth/status",s,Zh,"Failed to load Linear status"),authStart:(i,r)=>t(i,"/auth/start",{method:"POST",body:JSON.stringify({origin:r})},d({authorizationUrl:tt,expiresIn:w().positive()}),"Failed to start Linear auth"),authConnectToken:async()=>({ok:!1,code:"UNSUPPORTED",message:null}),authSaveOAuthClient:async()=>({ok:!1,code:"UNSUPPORTED",message:null}),authDisconnect:i=>t(i,"/auth",{method:"DELETE"},d({removed:y().catch(!1)}),"Failed to disconnect Linear").then(({removed:r})=>({removed:r})),authActivate:(i,r)=>t(i,"/auth/activate",{method:"POST",body:JSON.stringify({organizationId:r})},Zh,"Failed to switch Linear workspace"),list:(i,r)=>t(i,`/issues/list${v_(r)}`,s,a(d({connected:m(!0),issues:Ta(Wv),cursor:st,hasMore:y().catch(!1)}).transform(({issues:l,cursor:p,hasMore:u})=>({connected:!0,items:l.map(g=>Hv(g,i)),cursor:p,hasMore:u}))),"Failed to load Linear issues"),refreshListReads:async i=>{await t(i,"/read-cache/refresh?scope=lists",{method:"POST"},ne(),"Failed to refresh Linear lists")},get:(i,r)=>t(i,`/issues/get?${new URLSearchParams({id:r}).toString()}`,s,n(i),"Failed to load Linear issue"),states:(i,r)=>t(i,`/issues/states?${new URLSearchParams({teamId:r}).toString()}`,s,a(d({connected:m(!0),states:Ta(d({id:tt,name:tt,type:st,position:w().catch(0)}).transform(({id:l,name:p,type:u,position:g})=>({id:l,name:p,category:Lv(u),position:g})))})),"Failed to load Linear workflow states"),updateState:(i,r)=>t(i,"/issues/update",{method:"POST",body:JSON.stringify({id:r.id,stateId:r.stateId})},n(i),"Failed to update Linear issue"),mappingGet:i=>t(i,"/mapping",s,o,"Failed to load Linear mapping"),mappingSet:(i,r)=>t(i,"/mapping",{method:"PUT",body:JSON.stringify({defaultProjectPath:r.defaultProjectPath,teamProjectPaths:r.containerProjectPaths})},o,"Failed to save Linear mapping"),sessionStatusPost:(i,r)=>t(i,"/session-status",{method:"POST",body:JSON.stringify({kind:r.kind,sessionId:r.sessionId,issueIdentifier:r.identifier,sessionOrigin:r.sessionOrigin})},Bv,"Failed to post Linear session status"),preferencesGet:i=>t(i,"/preferences",s,_r,"Failed to load Linear preferences"),preferencesSet:(i,r)=>t(i,"/preferences",{method:"PUT",body:JSON.stringify({sessionComments:r.sessionComments})},_r,"Failed to save Linear preferences")}},S_=d({providers:C(ne())}),P_=e=>{const t=e?.split(";")[0]?.trim().toLowerCase()??"";return t==="application/json"||t.endsWith("+json")};async function x_(e){const t=await e("/api/tracker/providers",{headers:{Accept:"application/json"}});if(t.status===404)return{kind:"legacy-linear"};if(!t.ok)throw await Ov(t,"Failed to load trackers");if(!P_(t.headers.get("content-type")))return{kind:"legacy-linear"};const s=S_.parse(await t.json().catch(()=>null)).providers,a=YG.parse(s);if(s.length>0&&a.length===0)throw new Error("Trackers response contained no readable tracker");return{kind:"tracker",descriptors:a}}const jl=(e,t)=>`/api/tracker/${encodeURIComponent(e)}${t}`,T_=({fetch:e=T,runtimeKey:t=N}={})=>{const s=C_(e);let a=null;const n=()=>{const p=x_(e),u={runtimeKey:t(),request:p};return a=u,p.catch(()=>{a===u&&(a=null)}),p},o=async()=>(await((a?.runtimeKey===t()?a.request:null)??n())).kind==="legacy-linear",i=(p,u,g,h,b)=>Dv(e,jl(p,u),g,h,b),r={method:"GET"},l=p=>{const u=new URLSearchParams,g=(b,k)=>{const v=k?.trim();v&&u.set(b,v)};g("query",p?.query),g("cursor",p?.cursor),g("state",p?.state),g("people",p?.people),g("priority",p?.priority),g("containerId",p?.containerId);const h=u.toString();return h?`?${h}`:""};return{async providers(){const p=await n();return p.kind==="legacy-linear"?[qv]:p.descriptors},async authStatus(p){return await o()?s.authStatus(p):i(p,"/auth/status",r,Gh,"Failed to load tracker status")},async authStart(p,u,g){if(await o())return s.authStart(p,u);const h=g?.instance?{origin:u,instance:g.instance}:{origin:u};return i(p,"/auth/start",{method:"POST",body:JSON.stringify(h)},u_,"Failed to start tracker sign-in")},async authConnectToken(p,u){if(await o())return s.authConnectToken(p,u);try{const g=await e(jl(p,"/auth/token"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(u)});return await _h(g)}catch{return{ok:!1,code:"failed",message:null}}},async authSaveOAuthClient(p,u){if(await o())return s.authSaveOAuthClient(p,u);try{const g=await e(jl(p,"/auth/oauth-client"),{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(u)});return await _h(g)}catch{return{ok:!1,code:"failed",message:null}}},async authDisconnect(p){return await o()?s.authDisconnect(p):i(p,"/auth",{method:"DELETE"},d({removed:y().catch(!1)}),"Failed to disconnect tracker").then(({removed:u})=>({removed:u}))},async authActivate(p,u){return await o()?s.authActivate(p,u):i(p,"/auth/activate",{method:"POST",body:JSON.stringify({accountId:u})},Gh,"Failed to switch tracker account")},async list(p,u){return await o()?s.list(p,u):i(p,`/items/list${l(u)}`,r,r_,"Failed to load tracker items")},async refreshListReads(p){if(await o())return s.refreshListReads(p);await i(p,"/read-cache/refresh?scope=lists",{method:"POST"},ne(),"Failed to refresh tracker lists")},async get(p,u){return await o()?s.get(p,u):i(p,`/items/get?${new URLSearchParams({id:u}).toString()}`,r,Wh,"Failed to load tracker item")},async states(p,u){return await o()?s.states(p,u):i(p,`/states?${new URLSearchParams({containerId:u}).toString()}`,r,l_,"Failed to load workflow states")},async updateState(p,u){return await o()?s.updateState(p,u):i(p,"/items/update",{method:"POST",body:JSON.stringify({id:u.id,stateId:u.stateId})},Wh,"Failed to update tracker item")},async mappingGet(p){return await o()?s.mappingGet(p):i(p,"/mapping",r,Kh,"Failed to load project mapping")},async mappingSet(p,u){return await o()?s.mappingSet(p,u):i(p,"/mapping",{method:"PUT",body:JSON.stringify({defaultProjectPath:u.defaultProjectPath,containerProjectPaths:u.containerProjectPaths})},Kh,"Failed to save project mapping")},async sessionStatusPost(p,u){return await o()?s.sessionStatusPost(p,u):i(p,"/session-status",{method:"POST",body:JSON.stringify({kind:u.kind,sessionId:u.sessionId,identifier:u.identifier,sessionOrigin:u.sessionOrigin})},Bv,"Failed to post session status")},async preferencesGet(p){return await o()?s.preferencesGet(p):i(p,"/preferences",r,_r,"Failed to load tracker preferences")},async preferencesSet(p,u){return await o()?s.preferencesSet(p,u):i(p,"/preferences",{method:"PUT",body:JSON.stringify({sessionComments:u.sessionComments})},_r,"Failed to save tracker preferences")}}},Ms=async e=>await e.json().catch(()=>null),A_=d({identityConflict:y().catch(!1)}),Jh=async(e,t)=>{const s=await T(e,{method:t,headers:{Accept:"application/json"}}),a=await s.json().catch(()=>null),n=A_.safeParse(a);if(!s.ok||!n.success)throw new Error(s.statusText||"Failed to read relay status");return n.data},z_=()=>({async listClients(){const e=await T("/api/client-auth/clients",{method:"GET",headers:{Accept:"application/json"}}),t=await Ms(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load remote clients");return Array.isArray(t.clients)?t.clients:[]},async createClient(e={}){const t=await T("/api/client-auth/clients",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??""})}),s=await Ms(t);if(!t.ok||!s?.client||typeof s.token!="string")throw new Error(s?.error||t.statusText||"Failed to create remote client token");return s},async createPairingSession(e={}){const t=await T("/api/client-auth/pairing/sessions",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??"",...e.allowedClientKinds?{allowedClientKinds:e.allowedClientKinds}:{},...e.serverUrl?{serverUrl:e.serverUrl}:{},...typeof e.includeRelay=="boolean"?{includeRelay:e.includeRelay}:{},...typeof e.includeDirect=="boolean"?{includeDirect:e.includeDirect}:{}})}),s=await Ms(t);if(!t.ok||typeof s?.pairing?.secret!="string"||!s?.server)throw new Error(s?.error||t.statusText||"Failed to create pairing session");return s},async listPendingPairings(){const e=await T("/api/client-auth/pairing/sessions",{method:"GET",headers:{Accept:"application/json"}}),t=await Ms(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load pending pairings");return Array.isArray(t.pending)?t.pending:[]},async getPairingTransports(){const e=await T("/api/client-auth/pairing/transports",{method:"GET",headers:{Accept:"application/json"}}),t=await Ms(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load pairing transports");return{local:t.local??null,lan:t.lan??null,relayAvailable:t.relayAvailable!==!1}},async cancelPairing(e){const t=await T(`/api/client-auth/pairing/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),s=await Ms(t);if(!t.ok||!s)throw new Error(s?.error||t.statusText||"Failed to cancel pairing");return{cancelled:s.cancelled===!0}},async revokeClient(e){const t=await T(`/api/client-auth/clients/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),s=await Ms(t);if(!t.ok||!s)throw new Error(s?.error||t.statusText||"Failed to revoke remote client");return s},getRelayHostStatus:()=>Jh("/api/openchamber/relay/status","GET"),resetRelayIdentity:()=>Jh("/api/openchamber/relay/reset-identity","POST"),async purgeRevokedClients(){const e=await T("/api/client-auth/clients",{method:"DELETE",headers:{Accept:"application/json"}}),t=await Ms(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to clear revoked clients");return t}}),R_=(e={})=>{const t=e.urls??lp();return iS(t),{clipboard:hS(),themeFiles:fS(),runtime:{platform:"web",isDesktop:!1,isVSCode:!1,label:"web"},terminal:AV(),git:kG(),files:zG({getDirectory:()=>Cu.getState().currentDirectory}),settings:jG(),permissions:OG(),notifications:_G(),sourceControl:uG(),trackers:T_(),push:KG(),clientAuth:z_()}},I_=3e3,$h=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},j_=()=>{const e=t=>typeof t=="string"?t.trim():"";return{apiBaseUrl:e(window.__OPENCHAMBER_API_BASE_URL__),clientToken:e(window.__OPENCHAMBER_CLIENT_TOKEN__),localOrigin:e(window.__OPENCHAMBER_LOCAL_ORIGIN__),runtimeHeaders:window.__OPENCHAMBER_RUNTIME_HEADERS__,relayHostId:e(window.__OPENCHAMBER_RELAY_HOST_ID__),explicitRuntime:window.__OPENCHAMBER_EXPLICIT_RUNTIME__===!0}};let rp=Promise.resolve();const eQ=()=>rp,tQ=()=>{const{apiBaseUrl:e,clientToken:t,localOrigin:s,runtimeHeaders:a,relayHostId:n,explicitRuntime:o}=j_(),i=ff(),r=n||(i?.target==="remote"?i.hostId:""),l=kf({apiBaseUrl:e||void 0,realtimeBaseUrl:e||void 0});dS({apiBaseUrl:e,runtimeKey:$h(e,s)?"local":r?`host:${r}`:null});const p=g=>{const h=g.trim(),b=window.__OPENCHAMBER_DESKTOP__?.invoke;!h||!b||b("desktop_set_window_runtime_key",{runtimeKey:h}).catch(()=>{})};p(N()),$r(g=>p(g.runtimeKey)),Ff(t||null),Ef(a||null),et.reconnectToRuntimeBaseUrl(),Xr(e||void 0).catch(()=>{}),s&&!$h(e,s)&&Object.keys(Nn()).length>0&&Uf(s).catch(()=>{}),Xf();const u=()=>n?cg(n,{reconnectActive:!0}):o?Promise.resolve():cg();return rp=Promise.race([u().catch(()=>{}),new Promise(g=>{window.setTimeout(g,1e4)})]).then(()=>{et.reconnectToRuntimeBaseUrl()}),rp.then(()=>{window.setTimeout(()=>{QP().catch(()=>{})},I_)}),R_({urls:l})},Qh="openchamber:chunk-import-reload",O_=250,D_=3e4,N_=[/Importing a module script failed/i,/Failed to fetch dynamically imported module/i,/error loading dynamically imported module/i,/Loading chunk \S+ failed/i,/ChunkLoadError/i];function Gv(e){if(e instanceof Error)return`${e.name}
88
88
  ${e.message}
89
- ${e.stack??""}`;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Yh(e){const t=Gv(e);return N_.some(s=>s.test(t))}function F_(e){return`2.7.1:${Gv(e).slice(0,500)}`}function E_(e){if(typeof window>"u"||Ee())return;const t=Date.now(),s=F_(e);let a=null;try{const o=window.sessionStorage.getItem(Qh);if(o)try{a=JSON.parse(o)}catch{a=null}}catch{return}const n=typeof a?.timestamp=="number"?a.timestamp:0;if(!(a?.signature===s&&t-n<D_)){try{window.sessionStorage.setItem(Qh,JSON.stringify({signature:s,timestamp:t}))}catch{return}window.setTimeout(()=>{window.location.reload()},0)}}async function M_(e,t={}){const s=t.retries??1;let a;for(let n=0;n<=s;n+=1)try{return await e()}catch(o){if(a=o,!Yh(o)||n>=s)break;await new Promise(i=>setTimeout(i,O_*(n+1)))}throw Yh(a)&&E_(a),a}const sQ=e=>sC.lazy(()=>M_(e));export{kO as $,wI as A,kI as B,bI as C,yI as D,fI as E,hI as F,PI as G,xI as H,S$ as I,Xt as J,Bq as K,N$ as L,Mq as M,c1 as N,i1 as O,tQ as P,M_ as Q,YI as R,Bc as S,XI as T,ej as U,nj as V,aj as W,sj as X,tj as Y,yO as Z,wO as _,Sq as a,rj as a$,bO as a0,fO as a1,hO as a2,mO as a3,gO as a4,uO as a5,pO as a6,dO as a7,lO as a8,cO as a9,Nj as aA,Dj as aB,Oj as aC,jj as aD,Ij as aE,Rj as aF,zj as aG,Aj as aH,Tj as aI,xj as aJ,Pj as aK,Sj as aL,Cj as aM,vj as aN,yj as aO,wj as aP,kj as aQ,bj as aR,fj as aS,hj as aT,mj as aU,gj as aV,uj as aW,pj as aX,dj as aY,lj as aZ,cj as a_,rO as aa,iO as ab,oO as ac,nO as ad,aO as ae,sO as af,tO as ag,eO as ah,Xj as ai,Yj as aj,Qj as ak,$j as al,Jj as am,Zj as an,Kj as ao,_j as ap,Gj as aq,Hj as ar,Wj as as,Uj as at,Vj as au,Lj as av,Bj as aw,Mj as ax,Ej as ay,Fj as az,it as b,aK as b$,ij as b0,qj as b1,o1 as b2,N as b3,AK as b4,gJ as b5,Uc as b6,ze as b7,L0 as b8,XJ as b9,JZ as bA,nB as bB,Dq as bC,wt as bD,oe as bE,n0 as bF,ot as bG,z0 as bH,cr as bI,OZ as bJ,zJ as bK,eN as bL,xq as bM,uJ as bN,ja as bO,Q_ as bP,C0 as bQ,W0 as bR,wZ as bS,ax as bT,e0 as bU,t0 as bV,s0 as bW,ck as bX,va as bY,OR as bZ,Ho as b_,QJ as ba,d$ as bb,H$ as bc,EV as bd,T$ as be,$r as bf,ix as bg,yb as bh,c$ as bi,ii as bj,Xr as bk,JJ as bl,Xq as bm,vs as bn,jZ as bo,cD as bp,fT as bq,Ap as br,$c as bs,C1 as bt,_Z as bu,KZ as bv,eQ as bw,Gb as bx,$J as by,cu as bz,ZK as c,BZ as c$,ec as c0,OP as c1,M0 as c2,sK as c3,Cq as c4,A0 as c5,j0 as c6,tb as c7,Ke as c8,oK as c9,kZ as cA,ac as cB,Af as cC,ci as cD,Oa as cE,Vl as cF,OS as cG,Dn as cH,Z0 as cI,gp as cJ,gs as cK,K0 as cL,bp as cM,PP as cN,tK as cO,tJ as cP,Or as cQ,DZ as cR,qp as cS,On as cT,rS as cU,yn as cV,_0 as cW,lk as cX,NZ as cY,e1 as cZ,A$ as c_,iK as ca,_m as cb,BV as cc,YJ as cd,kB as ce,W$ as cf,U$ as cg,fJ as ch,Jr as ci,R0 as cj,SS as ck,AN as cl,Ea as cm,lI as cn,dJ as co,_I as cp,ww as cq,HJ as cr,ns as cs,sJ as ct,U0 as cu,mK as cv,yZ as cw,vZ as cx,GR as cy,ES as cz,GK as d,NP as d$,V0 as d0,rr as d1,F$ as d2,e$ as d3,lA as d4,sQ as d5,Vp as d6,dt as d7,Sa as d8,zR as d9,Ii as dA,dn as dB,Fz as dC,x0 as dD,cg as dE,GP as dF,Et as dG,l1 as dH,XC as dI,ff as dJ,Z_ as dK,D$ as dL,fZ as dM,J_ as dN,P0 as dO,$_ as dP,Y_ as dQ,X_ as dR,c0 as dS,l0 as dT,pI as dU,qA as dV,cZ as dW,zg as dX,u1 as dY,lZ as dZ,az as d_,MZ as da,BR as db,cd as dc,dk as dd,SZ as de,CZ as df,Ep as dg,zt as dh,Xb as di,Gl as dj,n1 as dk,lr as dl,PZ as dm,xZ as dn,AZ as dp,zZ as dq,mR as dr,TZ as ds,RZ as dt,IZ as du,Ra as dv,EZ as dw,q$ as dx,nc as dy,S0 as dz,EK as e,ik as e$,AP as e0,X0 as e1,eK as e2,LP as e3,B0 as e4,gq as e5,w$ as e6,Cy as e7,k$ as e8,y$ as e9,Ex as eA,r1 as eB,UK as eC,WK as eD,m0 as eE,h0 as eF,f0 as eG,b0 as eH,i0 as eI,d0 as eJ,k0 as eK,r0 as eL,p0 as eM,w0 as eN,u0 as eO,g0 as eP,Rz as eQ,Iz as eR,Ed as eS,mo as eT,Zp as eU,RO as eV,zO as eW,GZ as eX,VI as eY,Jp as eZ,rk as e_,v$ as ea,v0 as eb,RV as ec,zV as ed,uA as ee,xJ as ef,xf as eg,I0 as eh,T0 as ei,hZ as ej,sk as ek,Bz as el,Uz as em,Lz as en,Wz as eo,Ez as ep,nm as eq,sc as er,CK as es,xK as et,zK as eu,jK as ev,TK as ew,SK as ex,PK as ey,Mx as ez,JK as f,hK as f$,o0 as f0,E0 as f1,N0 as f2,F0 as f3,r$ as f4,uq as f5,pq as f6,Q$ as f7,IJ as f8,FN as f9,lS as fA,_f as fB,uR as fC,Nn as fD,rt as fE,Jz as fF,Vz as fG,Tu as fH,Qt as fI,V$ as fJ,pJ as fK,mJ as fL,KI as fM,pp as fN,dp as fO,ha as fP,iL as fQ,Nq as fR,hx as fS,XK as fT,zq as fU,yK as fV,sx as fW,d1 as fX,dZ as fY,dA as fZ,pA as f_,tw as fa,Yk as fb,CI as fc,SI as fd,DI as fe,ka as ff,uI as fg,Pq as fh,HP as fi,WP as fj,lK as fk,$s as fl,Gx as fm,bZ as fn,ic as fo,t1 as fp,g$ as fq,M$ as fr,QK as fs,BK as ft,XZ as fu,bK as fv,wK as fw,qo as fx,YZ as fy,QZ as fz,NK as g,dv as g$,b1 as g0,h1 as g1,ji as g2,ed as g3,PA as g4,ZC as g5,qc as g6,p1 as g7,AA as g8,yA as g9,Tq as gA,KK as gB,YU as gC,WI as gD,RU as gE,_U as gF,jU as gG,eW as gH,dW as gI,Ph as gJ,Sh as gK,Ch as gL,vh as gM,cW as gN,rW as gO,iW as gP,oW as gQ,_$ as gR,nH as gS,K$ as gT,LW as gU,BW as gV,MW as gW,UW as gX,EW as gY,lv as gZ,qU as g_,X1 as ga,eZ as gb,OA as gc,wB as gd,_s as ge,rB as gf,g1 as gg,Yy as gh,x1 as gi,k1 as gj,W1 as gk,Hx as gl,xd as gm,X$ as gn,Fd as go,ds as gp,qO as gq,ie as gr,JC as gs,$C as gt,lg as gu,m$ as gv,j$ as gw,gn as gx,Ag as gy,Aq as gz,$K as h,sq as h$,VU as h0,EU as h1,NW as h2,NU as h3,FU as h4,FW as h5,$$ as h6,OU as h7,KU as h8,jW as h9,Px as hA,Q0 as hB,_1 as hC,R$ as hD,JG as hE,Lv as hF,UB as hG,h$ as hH,$x as hI,ql as hJ,y0 as hK,$1 as hL,s1 as hM,Yx as hN,a1 as hO,Qx as hP,I$ as hQ,qq as hR,O$ as hS,YK as hT,K1 as hU,pZ as hV,ek as hW,G0 as hX,oI as hY,P$ as hZ,fq as h_,TW as ha,ZW as hb,JW as hc,xW as hd,RW as he,AW as hf,MU as hg,aH as hh,J$ as hi,PW as hj,KW as hk,hv as hl,GW as hm,QW as hn,Z$ as ho,$W as hp,nW as hq,sW as hr,mv as hs,a0 as ht,RA as hu,Rg as hv,HA as hw,WA as hx,JA as hy,Sp as hz,TO as i,O1 as i$,ZZ as i0,dK as i1,pK as i2,_P as i3,$P as i4,nK as i5,gK as i6,uK as i7,cK as i8,rK as i9,o$ as iA,l$ as iB,rc as iC,AJ as iD,i$ as iE,Mt as iF,EJ as iG,FZ as iH,Di as iI,T1 as iJ,sN as iK,CJ as iL,Br as iM,SJ as iN,vd as iO,vJ as iP,CG as iQ,Pb as iR,Q1 as iS,U1 as iT,P1 as iU,ET as iV,L1 as iW,E1 as iX,F1 as iY,R1 as iZ,Z1 as i_,DP as ia,tx as ib,L$ as ic,Y0 as id,MV as ie,RJ as ig,tL as ih,C$ as ii,f$ as ij,FV as ik,G$ as il,IU as im,Xy as io,w1 as ip,z$ as iq,tB as ir,sB as is,eB as it,YG as iu,Y$ as iv,S1 as iw,v1 as ix,Op as iy,nt as iz,T as j,ZO as j$,D1 as j0,Y1 as j1,aZ as j2,nZ as j3,iZ as j4,B1 as j5,J1 as j6,N1 as j7,M1 as j8,Xl as j9,ew as jA,dD as jB,QO as jC,YO as jD,Td as jE,rD as jF,ZD as jG,aw as jH,_D as jI,GD as jJ,KD as jK,Ad as jL,gm as jM,fD as jN,$D as jO,YD as jP,JD as jQ,UF as jR,AD as jS,yD as jT,yw as jU,oF as jV,nF as jW,jJ as jX,J0 as jY,b$ as jZ,MJ as j_,H1 as ja,G1 as jb,RT as jc,E$ as jd,oZ as je,SB as jf,CB as jg,q0 as jh,Cb as ji,eu as jj,yN as jk,yJ as jl,wJ as jm,qi as jn,TJ as jo,aF as jp,aN as jq,sw as jr,kD as js,mD as jt,uD as ju,QD as jv,_N as jw,GN as jx,HN as jy,Xk as jz,sr as k,dE as k$,KO as k0,a$ as k1,t$ as k2,s$ as k3,n$ as k4,y1 as k5,kT as k6,U as k7,Nb as k8,q1 as k9,qK as kA,LK as kB,MK as kC,OK as kD,IK as kE,RK as kF,Jx as kG,DK as kH,pN as kI,uN as kJ,hw as kK,iN as kL,hN as kM,cw as kN,xN as kO,wN as kP,WJ as kQ,LJ as kR,BJ as kS,DJ as kT,VJ as kU,qJ as kV,Om as kW,GJ as kX,_J as kY,lE as kZ,pE as k_,f1 as ka,VT as kb,qz as kc,JT as kd,QT as ke,HT as kf,WT as kg,lc as kh,hJ as ki,ht as kj,zB as kk,$0 as kl,aJ as km,oJ as kn,lJ as ko,iJ as kp,nJ as kq,rJ as kr,Mk as ks,cJ as kt,p$ as ku,u$ as kv,PS as kw,HK as kx,_K as ky,VK as kz,Cu as l,gE as l0,mE as l1,PJ as l2,ZJ as l3,IE as l4,jE as l5,UJ as l6,FJ as l7,NJ as l8,IV as l9,KJ as lA,OJ as lB,pD as lC,HZ as lD,uZ as lE,rZ as lF,fK as lG,kK as lH,H0 as lI,$t as lJ,Au as lK,mZ as lL,gZ as lM,bJ as lN,x$ as lO,Rn as la,Qy as lb,DV as lc,O0 as ld,D0 as le,WO as lf,kJ as lg,du as lh,sZ as li,tZ as lj,GT as lk,A1 as ll,z1 as lm,B$ as ln,j1 as lo,I1 as lp,V1 as lq,uB as lr,RR as ls,qZ as lt,VZ as lu,WZ as lv,NR as lw,LZ as lx,UZ as ly,m1 as lz,Ee as m,je as n,FK as o,vK as p,AO as q,Zx as r,vq as s,Er as t,R as u,et as v,Bt as w,$Z as x,vI as y,eJ as z};
89
+ ${e.stack??""}`;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Yh(e){const t=Gv(e);return N_.some(s=>s.test(t))}function F_(e){return`2.7.2-canary.20261112.18:${Gv(e).slice(0,500)}`}function E_(e){if(typeof window>"u"||Ee())return;const t=Date.now(),s=F_(e);let a=null;try{const o=window.sessionStorage.getItem(Qh);if(o)try{a=JSON.parse(o)}catch{a=null}}catch{return}const n=typeof a?.timestamp=="number"?a.timestamp:0;if(!(a?.signature===s&&t-n<D_)){try{window.sessionStorage.setItem(Qh,JSON.stringify({signature:s,timestamp:t}))}catch{return}window.setTimeout(()=>{window.location.reload()},0)}}async function M_(e,t={}){const s=t.retries??1;let a;for(let n=0;n<=s;n+=1)try{return await e()}catch(o){if(a=o,!Yh(o)||n>=s)break;await new Promise(i=>setTimeout(i,O_*(n+1)))}throw Yh(a)&&E_(a),a}const sQ=e=>sC.lazy(()=>M_(e));export{kO as $,wI as A,kI as B,bI as C,yI as D,fI as E,hI as F,PI as G,xI as H,S$ as I,Xt as J,Bq as K,N$ as L,Mq as M,c1 as N,i1 as O,tQ as P,M_ as Q,YI as R,Bc as S,XI as T,ej as U,nj as V,aj as W,sj as X,tj as Y,yO as Z,wO as _,Sq as a,rj as a$,bO as a0,fO as a1,hO as a2,mO as a3,gO as a4,uO as a5,pO as a6,dO as a7,lO as a8,cO as a9,Nj as aA,Dj as aB,Oj as aC,jj as aD,Ij as aE,Rj as aF,zj as aG,Aj as aH,Tj as aI,xj as aJ,Pj as aK,Sj as aL,Cj as aM,vj as aN,yj as aO,wj as aP,kj as aQ,bj as aR,fj as aS,hj as aT,mj as aU,gj as aV,uj as aW,pj as aX,dj as aY,lj as aZ,cj as a_,rO as aa,iO as ab,oO as ac,nO as ad,aO as ae,sO as af,tO as ag,eO as ah,Xj as ai,Yj as aj,Qj as ak,$j as al,Jj as am,Zj as an,Kj as ao,_j as ap,Gj as aq,Hj as ar,Wj as as,Uj as at,Vj as au,Lj as av,Bj as aw,Mj as ax,Ej as ay,Fj as az,it as b,aK as b$,ij as b0,qj as b1,o1 as b2,N as b3,AK as b4,gJ as b5,Uc as b6,ze as b7,L0 as b8,XJ as b9,JZ as bA,nB as bB,Dq as bC,wt as bD,oe as bE,n0 as bF,ot as bG,z0 as bH,cr as bI,OZ as bJ,zJ as bK,eN as bL,xq as bM,uJ as bN,ja as bO,Q_ as bP,C0 as bQ,W0 as bR,wZ as bS,ax as bT,e0 as bU,t0 as bV,s0 as bW,ck as bX,va as bY,OR as bZ,Ho as b_,QJ as ba,d$ as bb,H$ as bc,EV as bd,T$ as be,$r as bf,ix as bg,yb as bh,c$ as bi,ii as bj,Xr as bk,JJ as bl,Xq as bm,vs as bn,jZ as bo,cD as bp,fT as bq,Ap as br,$c as bs,C1 as bt,_Z as bu,KZ as bv,eQ as bw,Gb as bx,$J as by,cu as bz,ZK as c,BZ as c$,ec as c0,OP as c1,M0 as c2,sK as c3,Cq as c4,A0 as c5,j0 as c6,tb as c7,Ke as c8,oK as c9,kZ as cA,ac as cB,Af as cC,ci as cD,Oa as cE,Vl as cF,OS as cG,Dn as cH,Z0 as cI,gp as cJ,gs as cK,K0 as cL,bp as cM,PP as cN,tK as cO,tJ as cP,Or as cQ,DZ as cR,qp as cS,On as cT,rS as cU,yn as cV,_0 as cW,lk as cX,NZ as cY,e1 as cZ,A$ as c_,iK as ca,_m as cb,BV as cc,YJ as cd,kB as ce,W$ as cf,U$ as cg,fJ as ch,Jr as ci,R0 as cj,SS as ck,AN as cl,Ea as cm,lI as cn,dJ as co,_I as cp,ww as cq,HJ as cr,ns as cs,sJ as ct,U0 as cu,mK as cv,yZ as cw,vZ as cx,GR as cy,ES as cz,GK as d,NP as d$,V0 as d0,rr as d1,F$ as d2,e$ as d3,lA as d4,sQ as d5,Vp as d6,dt as d7,Sa as d8,zR as d9,Ii as dA,dn as dB,Fz as dC,x0 as dD,cg as dE,GP as dF,Et as dG,l1 as dH,XC as dI,ff as dJ,Z_ as dK,D$ as dL,fZ as dM,J_ as dN,P0 as dO,$_ as dP,Y_ as dQ,X_ as dR,c0 as dS,l0 as dT,pI as dU,qA as dV,cZ as dW,zg as dX,u1 as dY,lZ as dZ,az as d_,MZ as da,BR as db,cd as dc,dk as dd,SZ as de,CZ as df,Ep as dg,zt as dh,Xb as di,Gl as dj,n1 as dk,lr as dl,PZ as dm,xZ as dn,AZ as dp,zZ as dq,mR as dr,TZ as ds,RZ as dt,IZ as du,Ra as dv,EZ as dw,q$ as dx,nc as dy,S0 as dz,EK as e,ik as e$,AP as e0,X0 as e1,eK as e2,LP as e3,B0 as e4,gq as e5,w$ as e6,Cy as e7,k$ as e8,y$ as e9,Ex as eA,r1 as eB,UK as eC,WK as eD,m0 as eE,h0 as eF,f0 as eG,b0 as eH,i0 as eI,d0 as eJ,k0 as eK,r0 as eL,p0 as eM,w0 as eN,u0 as eO,g0 as eP,Rz as eQ,Iz as eR,Ed as eS,mo as eT,Zp as eU,RO as eV,zO as eW,GZ as eX,VI as eY,Jp as eZ,rk as e_,v$ as ea,v0 as eb,RV as ec,zV as ed,uA as ee,xJ as ef,xf as eg,I0 as eh,T0 as ei,hZ as ej,sk as ek,Bz as el,Uz as em,Lz as en,Wz as eo,Ez as ep,nm as eq,sc as er,CK as es,xK as et,zK as eu,jK as ev,TK as ew,SK as ex,PK as ey,Mx as ez,JK as f,hK as f$,o0 as f0,E0 as f1,N0 as f2,F0 as f3,r$ as f4,uq as f5,pq as f6,Q$ as f7,IJ as f8,FN as f9,lS as fA,_f as fB,uR as fC,Nn as fD,rt as fE,Jz as fF,Vz as fG,Tu as fH,Qt as fI,V$ as fJ,pJ as fK,mJ as fL,KI as fM,pp as fN,dp as fO,ha as fP,iL as fQ,Nq as fR,hx as fS,XK as fT,zq as fU,yK as fV,sx as fW,d1 as fX,dZ as fY,dA as fZ,pA as f_,tw as fa,Yk as fb,CI as fc,SI as fd,DI as fe,ka as ff,uI as fg,Pq as fh,HP as fi,WP as fj,lK as fk,$s as fl,Gx as fm,bZ as fn,ic as fo,t1 as fp,g$ as fq,M$ as fr,QK as fs,BK as ft,XZ as fu,bK as fv,wK as fw,qo as fx,YZ as fy,QZ as fz,NK as g,dv as g$,b1 as g0,h1 as g1,ji as g2,ed as g3,PA as g4,ZC as g5,qc as g6,p1 as g7,AA as g8,yA as g9,Tq as gA,KK as gB,YU as gC,WI as gD,RU as gE,_U as gF,jU as gG,eW as gH,dW as gI,Ph as gJ,Sh as gK,Ch as gL,vh as gM,cW as gN,rW as gO,iW as gP,oW as gQ,_$ as gR,nH as gS,K$ as gT,LW as gU,BW as gV,MW as gW,UW as gX,EW as gY,lv as gZ,qU as g_,X1 as ga,eZ as gb,OA as gc,wB as gd,_s as ge,rB as gf,g1 as gg,Yy as gh,x1 as gi,k1 as gj,W1 as gk,Hx as gl,xd as gm,X$ as gn,Fd as go,ds as gp,qO as gq,ie as gr,JC as gs,$C as gt,lg as gu,m$ as gv,j$ as gw,gn as gx,Ag as gy,Aq as gz,$K as h,sq as h$,VU as h0,EU as h1,NW as h2,NU as h3,FU as h4,FW as h5,$$ as h6,OU as h7,KU as h8,jW as h9,Px as hA,Q0 as hB,_1 as hC,R$ as hD,JG as hE,Lv as hF,UB as hG,h$ as hH,$x as hI,ql as hJ,y0 as hK,$1 as hL,s1 as hM,Yx as hN,a1 as hO,Qx as hP,I$ as hQ,qq as hR,O$ as hS,YK as hT,K1 as hU,pZ as hV,ek as hW,G0 as hX,oI as hY,P$ as hZ,fq as h_,TW as ha,ZW as hb,JW as hc,xW as hd,RW as he,AW as hf,MU as hg,aH as hh,J$ as hi,PW as hj,KW as hk,hv as hl,GW as hm,QW as hn,Z$ as ho,$W as hp,nW as hq,sW as hr,mv as hs,a0 as ht,RA as hu,Rg as hv,HA as hw,WA as hx,JA as hy,Sp as hz,TO as i,O1 as i$,ZZ as i0,dK as i1,pK as i2,_P as i3,$P as i4,nK as i5,gK as i6,uK as i7,cK as i8,rK as i9,o$ as iA,l$ as iB,rc as iC,AJ as iD,i$ as iE,Mt as iF,EJ as iG,FZ as iH,Di as iI,T1 as iJ,sN as iK,CJ as iL,Br as iM,SJ as iN,vd as iO,vJ as iP,CG as iQ,Pb as iR,Q1 as iS,U1 as iT,P1 as iU,ET as iV,L1 as iW,E1 as iX,F1 as iY,R1 as iZ,Z1 as i_,DP as ia,tx as ib,L$ as ic,Y0 as id,MV as ie,RJ as ig,tL as ih,C$ as ii,f$ as ij,FV as ik,G$ as il,IU as im,Xy as io,w1 as ip,z$ as iq,tB as ir,sB as is,eB as it,YG as iu,Y$ as iv,S1 as iw,v1 as ix,Op as iy,nt as iz,T as j,ZO as j$,D1 as j0,Y1 as j1,aZ as j2,nZ as j3,iZ as j4,B1 as j5,J1 as j6,N1 as j7,M1 as j8,Xl as j9,ew as jA,dD as jB,QO as jC,YO as jD,Td as jE,rD as jF,ZD as jG,aw as jH,_D as jI,GD as jJ,KD as jK,Ad as jL,gm as jM,fD as jN,$D as jO,YD as jP,JD as jQ,UF as jR,AD as jS,yD as jT,yw as jU,oF as jV,nF as jW,jJ as jX,J0 as jY,b$ as jZ,MJ as j_,H1 as ja,G1 as jb,RT as jc,E$ as jd,oZ as je,SB as jf,CB as jg,q0 as jh,Cb as ji,eu as jj,yN as jk,yJ as jl,wJ as jm,qi as jn,TJ as jo,aF as jp,aN as jq,sw as jr,kD as js,mD as jt,uD as ju,QD as jv,_N as jw,GN as jx,HN as jy,Xk as jz,sr as k,dE as k$,KO as k0,a$ as k1,t$ as k2,s$ as k3,n$ as k4,y1 as k5,kT as k6,U as k7,Nb as k8,q1 as k9,qK as kA,LK as kB,MK as kC,OK as kD,IK as kE,RK as kF,Jx as kG,DK as kH,pN as kI,uN as kJ,hw as kK,iN as kL,hN as kM,cw as kN,xN as kO,wN as kP,WJ as kQ,LJ as kR,BJ as kS,DJ as kT,VJ as kU,qJ as kV,Om as kW,GJ as kX,_J as kY,lE as kZ,pE as k_,f1 as ka,VT as kb,qz as kc,JT as kd,QT as ke,HT as kf,WT as kg,lc as kh,hJ as ki,ht as kj,zB as kk,$0 as kl,aJ as km,oJ as kn,lJ as ko,iJ as kp,nJ as kq,rJ as kr,Mk as ks,cJ as kt,p$ as ku,u$ as kv,PS as kw,HK as kx,_K as ky,VK as kz,Cu as l,gE as l0,mE as l1,PJ as l2,ZJ as l3,IE as l4,jE as l5,UJ as l6,FJ as l7,NJ as l8,IV as l9,KJ as lA,OJ as lB,pD as lC,HZ as lD,uZ as lE,rZ as lF,fK as lG,kK as lH,H0 as lI,$t as lJ,Au as lK,mZ as lL,gZ as lM,bJ as lN,x$ as lO,Rn as la,Qy as lb,DV as lc,O0 as ld,D0 as le,WO as lf,kJ as lg,du as lh,sZ as li,tZ as lj,GT as lk,A1 as ll,z1 as lm,B$ as ln,j1 as lo,I1 as lp,V1 as lq,uB as lr,RR as ls,qZ as lt,VZ as lu,WZ as lv,NR as lw,LZ as lx,UZ as ly,m1 as lz,Ee as m,je as n,FK as o,vK as p,AO as q,Zx as r,vq as s,Er as t,R as u,et as v,Bt as w,$Z as x,vI as y,eJ as z};