@vantran-se/openchamber-web 1.24.3 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -8
- package/bin/lib/commands-connect-url.js +3 -8
- package/bin/lib/commands-tunnel.js +3 -0
- package/dist/assets/{CodeMirrorCommentWidgets-BjJHrzmU.js → CodeMirrorCommentWidgets-ntXIbhV2.js} +1 -1
- package/dist/assets/DiffView-CjxUovbM.js +4 -0
- package/dist/assets/FilesView-DFWD0RQR.js +17 -0
- package/dist/assets/{GitView-CDOJy5Ay.js → GitView-BWa7e5vw.js} +4 -4
- package/dist/assets/{GuestAttachDialog-D3S0Rjic.js → GuestAttachDialog-DdOuyZzp.js} +1 -1
- package/dist/assets/GuestSurfacePane-DDfzid3U.js +1 -0
- package/dist/assets/{JsonTreeView-D0C9nU7K.js → JsonTreeView-3sGwqexh.js} +1 -1
- package/dist/assets/LinearIssuesView-C6dpIdjw.js +1 -0
- package/dist/assets/MarkdownImageGallery-Q7YR_tl4.js +1 -0
- package/dist/assets/MarkdownRendererImpl-DxDV56bL.js +12 -0
- package/dist/assets/OnboardingScreen-rK4Stg__.js +1 -0
- package/dist/assets/{PatchDiff-DnEhjXcC.js → PatchDiff-DS-IMU1j.js} +1 -1
- package/dist/assets/{PierreDiffViewer-DyxZVVVR.js → PierreDiffViewer-DW23KWKZ.js} +1 -1
- package/dist/assets/PlanView-BCk_VobP.js +5 -0
- package/dist/assets/PluginPane-BPP1dbck.js +3 -0
- package/dist/assets/SettingsView-kMmrpn43.js +29 -0
- package/dist/assets/SettingsWindow-BpvD6IYQ.js +1 -0
- package/dist/assets/SubmoduleDiffSummary-BLttSS1X.js +1 -0
- package/dist/assets/ToolOutputDialog-CtqDqbyr.js +15 -0
- package/dist/assets/ToolPartDiffPreview-5FcKdyRy.js +8 -0
- package/dist/assets/{VirtualizedFileDiff-0pyr_mHY.js → VirtualizedFileDiff-C763hNCR.js} +4 -4
- package/dist/assets/{WalkthroughView-yNj4nOP5.js → WalkthroughView-lap5btCF.js} +2 -2
- package/dist/assets/appThemeRegistry-u4zw1l0B.js +1 -0
- package/dist/assets/{commitAndPush-DvJKa3Ks.js → commitAndPush-CwGJfJG-.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-DxTBMuu-.js → computeVirtualFileMetrics-DW5jjX4n.js} +1 -1
- package/dist/assets/de-CndEg67T.js +10 -0
- package/dist/assets/es-DglvPlaC.js +16 -0
- package/dist/assets/fr-DejPCpbS.js +14 -0
- package/dist/assets/index-C2r64QfD.js +1 -0
- package/dist/assets/index-CLcM8HKx.css +1 -0
- package/dist/assets/index-CvLgnuNI.js +41 -0
- package/dist/assets/{isDiffPlainText-D7FkBMP6.js → isDiffPlainText-D47a6hMP.js} +1 -1
- package/dist/assets/{isFilePlainText-CL2vsrIZ.js → isFilePlainText-B-mGgeKl.js} +1 -1
- package/dist/assets/ja-CVpQawCd.js +16 -0
- package/dist/assets/ko-Bw446h9j.js +16 -0
- package/dist/assets/main-Bz4WWXbr.js +2 -0
- package/dist/assets/main-oreqDsOV.js +896 -0
- package/dist/assets/{markdownCore-Dh7WEsdM.js → markdownCore-D2e5sp9y.js} +4 -4
- package/dist/assets/miniChat-D1v2gsBI.js +2 -0
- package/dist/assets/mobile-DBj3lCf2.js +2 -0
- package/dist/assets/{patchFileDiff-Bsba8KFp.js → patchFileDiff-BpeUOV91.js} +3 -3
- package/dist/assets/pl-BYNlPdhm.js +16 -0
- package/dist/assets/pt-BR-CL-Yfv9H.js +16 -0
- package/dist/assets/renderElectronMiniChatApp-DVtfEB2z.js +2 -0
- package/dist/assets/renderMobileApp-DFp9-xbG.js +25 -0
- package/dist/assets/runtimeEndpointReset-CsIpUep1.js +27 -0
- package/dist/assets/scheduledTasksApi-B5OHVpPM.js +1 -0
- package/dist/assets/{shikiHighlight-8_3csmr6.js → shikiHighlight-DNm2Z_Jc.js} +1 -1
- package/dist/assets/{textMateThemeFromAppTheme-CHo2fCgW.js → textMateThemeFromAppTheme-DGF2kG7g.js} +1 -1
- package/dist/assets/tr-DzmbxLy-.js +7 -0
- package/dist/assets/uk-C7vQnwro.js +16 -0
- package/dist/assets/useAppFontEffects-Ci3FEaPf.js +7337 -0
- package/dist/assets/{useInlineCommentController-DkQ_gqpn.js → useInlineCommentController-CuUuakrt.js} +2 -2
- package/dist/assets/useRootScrollLock-CQIsyERq.js +2 -0
- package/dist/assets/{vendor-codemirror-language-data-CdzUmUyZ.js → vendor-codemirror-language-data-CQa7_1cr.js} +2 -2
- package/dist/assets/vendor-cron-parser-CjvYVigk.js +2 -0
- package/dist/assets/vendor-opencode-client-_BAHQo4R.js +12 -0
- package/dist/assets/{vendor-remixicon-react-BDmGmFCA.js → vendor-remixicon-react-D6dZ0UwF.js} +1 -1
- package/dist/assets/{vendor-zod-CgAdXWZO.js → vendor-zod-Gea9uBlY.js} +1 -1
- package/dist/assets/{web-components-B8IcVQAA.js → web-components-B6tKQyJN.js} +2 -2
- package/dist/assets/zh-CN-Cl0srS-z.js +16 -0
- package/dist/assets/zh-TW-DtII5bDb.js +16 -0
- package/dist/index.html +13 -7
- package/dist/mini-chat.html +5 -5
- package/dist/mobile.html +5 -5
- package/package.json +6 -5
- package/server/index.d.ts +1 -0
- package/server/index.js +246 -91
- package/server/lib/agent-tool/DOCUMENTATION.md +32 -15
- package/server/lib/agent-tool/runtime.js +135 -54
- package/server/lib/agent-tool/runtime.test.js +155 -87
- package/server/lib/browser-control/DOCUMENTATION.md +37 -2
- package/server/lib/browser-control/provider.js +217 -0
- package/server/lib/browser-control/provider.test.js +251 -0
- package/server/lib/context-obligatory/runtime.js +61 -50
- package/server/lib/context-obligatory/runtime.test.js +62 -162
- package/server/lib/event-stream/DOCUMENTATION.md +12 -1
- package/server/lib/event-stream/delta-coalescer.js +0 -0
- package/server/lib/event-stream/delta-coalescer.test.js +68 -57
- package/server/lib/event-stream/directory-ws-bridge.js +1 -1
- package/server/lib/event-stream/global-hub.js +10 -1
- package/server/lib/event-stream/global-hub.test.js +27 -26
- package/server/lib/event-stream/index.js +6 -0
- package/server/lib/event-stream/protocol.js +26 -19
- package/server/lib/event-stream/protocol.test.js +18 -7
- package/server/lib/event-stream/rebind.test.js +5 -5
- package/server/lib/event-stream/runtime.test.js +17 -15
- package/server/lib/event-stream/translate-v2.js +313 -0
- package/server/lib/event-stream/translate-v2.test.js +209 -0
- package/server/lib/event-stream/upstream-reader.test.js +16 -16
- package/server/lib/fs/DOCUMENTATION.md +4 -2
- package/server/lib/fs/byte-range.js +35 -0
- package/server/lib/fs/byte-range.test.js +31 -0
- package/server/lib/fs/routes.js +47 -42
- package/server/lib/fs/routes.test.js +123 -18
- package/server/lib/git/service.js +12 -0
- package/server/lib/github/DOCUMENTATION.md +1 -1
- package/server/lib/github/pr-status.js +22 -2
- package/server/lib/github/pr-status.test.js +27 -14
- package/server/lib/guests/DOCUMENTATION.md +13 -0
- package/server/lib/guests/catalog.js +12 -0
- package/server/lib/guests/catalog.test.js +33 -0
- package/server/lib/guests/routes.js +10 -1
- package/server/lib/guests/service.js +192 -14
- package/server/lib/guests/service.test.js +201 -1
- package/server/lib/guests/surface.js +630 -0
- package/server/lib/guests/surface.test.js +486 -0
- package/server/lib/markdown-image-grants/routes.js +18 -5
- package/server/lib/markdown-image-grants/routes.test.js +9 -6
- package/server/lib/message-queue/DOCUMENTATION.md +33 -22
- package/server/lib/message-queue/runtime.js +155 -100
- package/server/lib/message-queue/runtime.test.js +168 -82
- package/server/lib/notifications/DOCUMENTATION.md +28 -0
- package/server/lib/notifications/control-stream.http.test.js +68 -0
- package/server/lib/notifications/emitter-runtime.js +15 -0
- package/server/lib/notifications/emitter-runtime.test.js +32 -0
- package/server/lib/notifications/push-runtime.js +5 -1
- package/server/lib/notifications/push-runtime.test.js +2 -2
- package/server/lib/notifications/routes.js +1 -1
- package/server/lib/notifications/runtime.js +115 -26
- package/server/lib/notifications/template-runtime.js +13 -15
- package/server/lib/notifications/template-runtime.test.js +16 -9
- package/server/lib/notifications/trigger-runtime.test.js +187 -0
- package/server/lib/openchamber-control/DOCUMENTATION.md +10 -0
- package/server/lib/openchamber-control/actions.js +3 -2
- package/server/lib/openchamber-control/error.js +1 -1
- package/server/lib/openchamber-control/file-open.js +59 -0
- package/server/lib/openchamber-control/file-open.test.js +57 -0
- package/server/lib/openchamber-control/routes.test.js +12 -0
- package/server/lib/openchamber-control/service.js +102 -49
- package/server/lib/openchamber-control/service.test.js +84 -44
- package/server/lib/openchamber-sessions/archive-store.js +224 -0
- package/server/lib/openchamber-sessions/archive-store.test.js +187 -0
- package/server/lib/openchamber-sessions/opencode-client.js +22 -0
- package/server/lib/openchamber-sessions/routes.js +398 -328
- package/server/lib/openchamber-sessions/routes.test.js +777 -740
- package/server/lib/openchamber-sessions/session-metadata-store.js +285 -0
- package/server/lib/openchamber-sessions/session-metadata-store.test.js +259 -0
- package/server/lib/opencode/DOCUMENTATION.md +449 -29
- package/server/lib/opencode/agents.js +233 -327
- package/server/lib/opencode/auth.js +41 -44
- package/server/lib/opencode/auth.test.js +92 -0
- package/server/lib/opencode/cli-upgrade.d.ts +4 -0
- package/server/lib/opencode/cli-upgrade.js +18 -0
- package/server/lib/opencode/cli-upgrade.test.js +36 -0
- package/server/lib/opencode/commands.js +164 -145
- package/server/lib/opencode/compatibility.d.ts +16 -0
- package/server/lib/opencode/compatibility.js +88 -0
- package/server/lib/opencode/compatibility.test.js +62 -0
- package/server/lib/opencode/config-entity-routes.js +58 -29
- package/server/lib/opencode/config-entity-v2.test.js +290 -0
- package/server/lib/opencode/config-mutation-response.js +17 -7
- package/server/lib/opencode/config-mutation-response.test.js +4 -7
- package/server/lib/opencode/config-paths.test.js +2 -2
- package/server/lib/opencode/config-v2.d.ts +183 -0
- package/server/lib/opencode/config-v2.js +801 -0
- package/server/lib/opencode/config-v2.test.js +466 -0
- package/server/lib/opencode/credential-db.js +144 -0
- package/server/lib/opencode/credential-db.test.js +104 -0
- package/server/lib/opencode/env-runtime.js +48 -9
- package/server/lib/opencode/env-runtime.test.js +45 -0
- package/server/lib/opencode/feature-routes-runtime.js +15 -5
- package/server/lib/opencode/lifecycle-process.test.js +7 -4
- package/server/lib/opencode/lifecycle.js +85 -30
- package/server/lib/opencode/lifecycle.test.js +80 -8
- package/server/lib/opencode/login-shell-env.js +27 -0
- package/server/lib/opencode/managed-config-file.js +119 -0
- package/server/lib/opencode/managed-config-file.test.js +152 -0
- package/server/lib/opencode/managed-plugin-config.js +33 -13
- package/server/lib/opencode/mcp.js +43 -149
- package/server/lib/opencode/network-runtime.js +6 -7
- package/server/lib/opencode/openchamber-routes.test.js +2 -5
- package/server/lib/opencode/plugin-routes.js +3 -3
- package/server/lib/opencode/plugin-routes.test.js +6 -24
- package/server/lib/opencode/plugins.js +91 -40
- package/server/lib/opencode/plugins.test.js +28 -15
- package/server/lib/opencode/providers.js +63 -83
- package/server/lib/opencode/providers.test.js +128 -59
- package/server/lib/opencode/proxy-agent-wiring.test.js +4 -2
- package/server/lib/opencode/proxy.js +179 -129
- package/server/lib/opencode/pwa-manifest-routes.js +4 -2
- package/server/lib/opencode/pwa-manifest-routes.test.js +3 -2
- package/server/lib/opencode/response-envelope.js +14 -0
- package/server/lib/opencode/response-envelope.test.js +23 -0
- package/server/lib/opencode/routes-upgrade.test.js +73 -116
- package/server/lib/opencode/routes.js +121 -428
- package/server/lib/opencode/server-utils-runtime.js +10 -4
- package/server/lib/opencode/session-activity.js +78 -0
- package/server/lib/opencode/session-runtime.js +21 -10
- package/server/lib/opencode/session-runtime.test.js +9 -9
- package/server/lib/opencode/settings-helpers.js +9 -9
- package/server/lib/opencode/settings-helpers.test.js +7 -12
- package/server/lib/opencode/settings-registry.json +6 -8
- package/server/lib/opencode/settings-runtime.js +18 -1
- package/server/lib/opencode/settings-runtime.test.js +31 -2
- package/server/lib/opencode/shared.js +54 -22
- package/server/lib/opencode/shared.test.js +8 -4
- package/server/lib/opencode/shutdown-runtime.js +54 -7
- package/server/lib/opencode/shutdown-runtime.test.js +224 -30
- package/server/lib/opencode/skill-routes.js +23 -24
- package/server/lib/opencode/skills.js +7 -5
- package/server/lib/opencode/tunnel-wiring-runtime.js +2 -1
- package/server/lib/opencode/upgrade-capability.test.js +1 -1
- package/server/lib/opencode/v1-migration-topup.js +288 -0
- package/server/lib/opencode/v1-migration-topup.test.js +266 -0
- package/server/lib/opencode/v2-install.d.ts +8 -0
- package/server/lib/opencode/v2-install.js +158 -0
- package/server/lib/opencode/v2-install.test.js +124 -0
- package/server/lib/opencode/watcher.js +10 -3
- package/server/lib/opencode/watcher.test.js +17 -21
- package/server/lib/opencode/websearch-config.js +66 -0
- package/server/lib/package-manager.js +55 -68
- package/server/lib/package-manager.test.js +241 -75
- package/server/lib/permission-auto-accept/runtime.js +38 -22
- package/server/lib/permission-auto-accept/runtime.test.js +39 -17
- package/server/lib/quota/DOCUMENTATION.md +4 -0
- package/server/lib/quota/providers/xai.js +4 -4
- package/server/lib/relay/tunnel-host.js +4 -1
- package/server/lib/relay/tunnel-host.test.js +7 -0
- package/server/lib/routing/DOCUMENTATION.md +52 -21
- package/server/lib/routing/defaults.js +23 -6
- package/server/lib/routing/jev.js +17 -7
- package/server/lib/routing/routes.http.test.js +68 -33
- package/server/lib/routing/routes.js +65 -22
- package/server/lib/routing/runtime.js +145 -48
- package/server/lib/routing/runtime.test.js +79 -55
- package/server/lib/scheduled-tasks/DOCUMENTATION.md +4 -0
- package/server/lib/scheduled-tasks/issue-2710-double-execution.test.js +51 -46
- package/server/lib/scheduled-tasks/runtime.js +81 -74
- package/server/lib/scheduled-tasks/runtime.test.js +53 -1
- package/server/lib/session-assist/DOCUMENTATION.md +8 -3
- package/server/lib/session-assist/context.js +122 -46
- package/server/lib/session-assist/context.test.js +117 -49
- package/server/lib/session-assist/runtime.js +52 -22
- package/server/lib/session-assist/runtime.test.js +145 -173
- package/server/lib/session-goal/DOCUMENTATION.md +23 -15
- package/server/lib/session-goal/create.js +9 -12
- package/server/lib/session-goal/create.test.js +27 -28
- package/server/lib/session-goal/runtime.js +164 -77
- package/server/lib/session-goal/runtime.test.js +271 -519
- package/server/lib/session-knowledge/DOCUMENTATION.md +5 -0
- package/server/lib/session-knowledge/runtime.js +59 -41
- package/server/lib/session-knowledge/runtime.test.js +90 -20
- package/server/lib/small-model/DOCUMENTATION.md +154 -208
- package/server/lib/small-model/client.js +113 -0
- package/server/lib/small-model/index.js +296 -158
- package/server/lib/small-model/index.test.js +423 -256
- package/server/lib/small-model/routes.js +1 -1
- package/server/lib/spaces/DOCUMENTATION.md +807 -0
- package/server/lib/spaces/code-in-bait.js +185 -0
- package/server/lib/spaces/code-in.js +641 -0
- package/server/lib/spaces/code-in.test.js +1048 -0
- package/server/lib/spaces/errors.js +8 -0
- package/server/lib/spaces/exec-http.js +94 -0
- package/server/lib/spaces/gatekeeper-channel.js +202 -0
- package/server/lib/spaces/gatekeeper-channel.test.js +215 -0
- package/server/lib/spaces/gatekeeper-program.cjs +914 -0
- package/server/lib/spaces/gatekeeper-program.test.js +1391 -0
- package/server/lib/spaces/hardening.js +457 -0
- package/server/lib/spaces/hardening.test.js +368 -0
- package/server/lib/spaces/host-git.js +127 -0
- package/server/lib/spaces/host-git.test.js +137 -0
- package/server/lib/spaces/labels.js +234 -0
- package/server/lib/spaces/labels.test.js +219 -0
- package/server/lib/spaces/layout.js +184 -0
- package/server/lib/spaces/layout.test.js +30 -0
- package/server/lib/spaces/manager.js +82 -0
- package/server/lib/spaces/manager.test.js +114 -0
- package/server/lib/spaces/places/code-in.docker.live.test.js +216 -0
- package/server/lib/spaces/places/contract-suite.js +156 -0
- package/server/lib/spaces/places/contract.docker.live.test.js +7 -0
- package/server/lib/spaces/places/contract.test.js +6 -0
- package/server/lib/spaces/places/docker-engine.js +126 -0
- package/server/lib/spaces/places/docker-live-support.js +202 -0
- package/server/lib/spaces/places/docker-tools.js +186 -0
- package/server/lib/spaces/places/docker.js +587 -0
- package/server/lib/spaces/places/docker.test.js +1610 -0
- package/server/lib/spaces/places/escape-suite.js +1018 -0
- package/server/lib/spaces/places/escape.docker.live.test.js +7 -0
- package/server/lib/spaces/places/fake-docker.js +375 -0
- package/server/lib/spaces/places/memory-place.js +103 -0
- package/server/lib/spaces/places/packed.docker.live.test.js +77 -0
- package/server/lib/spaces/places/registry.js +43 -0
- package/server/lib/spaces/places/registry.test.js +50 -0
- package/server/lib/spaces/places/server.docker.live.test.js +225 -0
- package/server/lib/spaces/run-command.js +261 -0
- package/server/lib/spaces/run-command.test.js +396 -0
- package/server/lib/spaces/space-server.js +190 -0
- package/server/lib/spaces/space-server.test.js +335 -0
- package/server/lib/spaces/tools-filler.js +82 -0
- package/server/lib/spaces/tools-filler.test.js +148 -0
- package/server/lib/spaces/tools-pack.js +49 -0
- package/server/lib/spaces/tools-pack.test.js +57 -0
- package/server/lib/spaces/tools.js +138 -0
- package/server/lib/spaces/tools.test.js +153 -0
- package/server/lib/tts/openai-sdk.js +11 -0
- package/server/lib/tts/service.js +7 -5
- package/server/lib/tts/stt.js +3 -2
- package/server/lib/tunnels/DOCUMENTATION.md +2 -0
- package/server/lib/tunnels/routes.js +7 -0
- package/server/lib/tunnels/routes.test.js +55 -0
- package/server/lib/ui-auth/ui-auth.js +38 -2
- package/server/lib/ui-auth/ui-auth.test.js +42 -0
- package/server/lib/ui-auth/ui-passkeys.js +12 -10
- package/server/lib/walkthrough/DOCUMENTATION.md +10 -1
- package/server/lib/walkthrough/pull-request.js +61 -8
- package/server/lib/walkthrough/pull-request.test.js +54 -1
- package/server/lib/walkthrough/routes.js +20 -0
- package/server/lib/walkthrough/routes.test.js +19 -0
- package/server/opencode-proxy.test.js +190 -166
- package/server/opencode-worktree-readiness.test.js +5 -4
- package/dist/assets/DiffView-COVQhWGd.js +0 -4
- package/dist/assets/FilesView-B1V5JxFX.js +0 -13
- package/dist/assets/LinearIssuesView-D7FKg1XJ.js +0 -1
- package/dist/assets/MarkdownImageGallery-BrFjAVEf.js +0 -1
- package/dist/assets/MarkdownRendererImpl-DWepTafh.js +0 -12
- package/dist/assets/OnboardingScreen-Dyxxiqdt.js +0 -1
- package/dist/assets/PlanView-LW2z_EAP.js +0 -5
- package/dist/assets/PluginPane-B4tKno2h.js +0 -3
- package/dist/assets/SettingsView-DEaMulN9.js +0 -29
- package/dist/assets/SettingsWindow-FLDJXOgQ.js +0 -1
- package/dist/assets/SubmoduleDiffSummary-CvVwD-Vi.js +0 -1
- package/dist/assets/ToolOutputDialog-BiP0x2Rw.js +0 -15
- package/dist/assets/ToolPartDiffPreview-CkR4msKP.js +0 -8
- package/dist/assets/appThemeRegistry-BuUKhbYQ.js +0 -1
- package/dist/assets/de-DgxgFyGG.js +0 -10
- package/dist/assets/es-BFsZj5F_.js +0 -16
- package/dist/assets/fr-jdZ5KKQi.js +0 -14
- package/dist/assets/index-CKHjPKbq.js +0 -1
- package/dist/assets/index-Cbci4i1W.js +0 -40
- package/dist/assets/index-DqaMWNrC.css +0 -1
- package/dist/assets/ja-C5kKrhO4.js +0 -16
- package/dist/assets/ko-DXDTT_0O.js +0 -16
- package/dist/assets/main-CZALtVek.js +0 -896
- package/dist/assets/main-CgXMBNvG.js +0 -2
- package/dist/assets/miniChat-CwTmDixi.js +0 -2
- package/dist/assets/mobile-CLf2vCtO.js +0 -2
- package/dist/assets/pl-D-7x4Y8Q.js +0 -16
- package/dist/assets/pt-BR-CSBZrHa8.js +0 -16
- package/dist/assets/renderElectronMiniChatApp-C5gAFBk0.js +0 -2
- package/dist/assets/renderMobileApp-V4hYd32H.js +0 -25
- package/dist/assets/runtimeEndpointReset-DhlHCn-2.js +0 -25
- package/dist/assets/scheduledTasksApi-DzjbLd8P.js +0 -1
- package/dist/assets/tr-Dr-oJ22L.js +0 -7
- package/dist/assets/uk-9Nx83UcI.js +0 -16
- package/dist/assets/useAppFontEffects-khZXpFL_.js +0 -7333
- package/dist/assets/useRootScrollLock-DdvHf9Pt.js +0 -2
- package/dist/assets/vendor-cron-parser-CUcP7OfX.js +0 -2
- package/dist/assets/vendor-opencode-sdk-BJ73u-bH.js +0 -7
- package/dist/assets/zh-CN-Bxy_Hj3r.js +0 -16
- package/dist/assets/zh-TW-0BB4gpHM.js +0 -16
- package/server/lib/opencode/mcp-oauth-callback.test.js +0 -111
- package/server/lib/routing/feature-flag.js +0 -11
- package/server/lib/small-model/call.js +0 -851
- package/server/lib/small-model/call.test.js +0 -1292
- package/server/lib/small-model/catalog.js +0 -13
- package/server/lib/small-model/resolve.js +0 -131
- package/server/lib/small-model/resolve.test.js +0 -197
- package/server/lib/small-model/runtime-providers.js +0 -164
- package/server/lib/small-model/runtime-providers.test.js +0 -118
- package/server/lib/system-prompt/DOCUMENTATION.md +0 -36
- package/server/lib/system-prompt/runtime.js +0 -49
- package/server/lib/system-prompt/runtime.test.js +0 -76
- package/server/lib/walkthrough/reproduce-2607.test.js +0 -148
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-heic2any-CEam9pDc.js","assets/vendor-react-BUCujlKS.js","assets/vendor-scheduler-7OC5HNn7.js","assets/vendor-capacitor-app-BrDJj9I_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-capacitor-core-B4EWRrHz.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{s as m,o as T,n as R,b as Ne,r as it,l as N,a as G,_ as ke,u as me,c as Zt,t as $i,d as Es,j as Wi,e as rr,f as xc}from"./vendor-zod-Gea9uBlY.js";import{_ as ni}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as yt,d as Cn,p as pr,a as Vu}from"./vendor-zustand-BAGL70zf.js";import{e as Ju,C as Yu}from"./vendor-opencode-client-_BAHQo4R.js";import{f as Rc,R as ss}from"./vendor-react-BUCujlKS.js";const Jn=1,Qu="openchamber-relay-v1",Cc=1,Oc=12,Yn=1+Oc,sr=64*1024,or=5,os=128,Mc=0,Dc=1,kn=4,Xu=1+kn,yo=sr-or-Xu,H={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},Zu=new Set(Object.values(H)),ed=e=>Zu.has(e),Qt={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},mt=globalThis.crypto.subtle,_c={name:"ECDH",namedCurve:"P-256"},Lc=16,Ns=32,td=16,wo=4,Fc=8;class Ot extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const nd=()=>mt.generateKey(_c,!0,["deriveBits"]),rd=async e=>{const t=await mt.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},sd=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new Ot("invalid ECDH public key JWK");try{return await mt.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},_c,!0,[])}catch{throw new Ot("invalid ECDH public key JWK")}},od=()=>{const e=new Uint8Array(Lc);return globalThis.crypto.getRandomValues(e),e},id=async(e,t,n)=>{if(n.length!==Lc)throw new Ot("invalid handshake nonce length");const r=await mt.deriveBits({name:"ECDH",public:t},e,256),s=await mt.importKey("raw",r,"HKDF",!1,["deriveBits"]),o=new Uint8Array(await mt.deriveBits({name:"HKDF",hash:"SHA-256",salt:n,info:new TextEncoder().encode(Qu)},s,Ns*2*8)),i=(a,c)=>mt.importKey("raw",a,{name:"AES-GCM"},!1,c);return{clientToHost:await i(o.slice(0,Ns),["encrypt","decrypt"]),hostToClient:await i(o.slice(Ns),["encrypt","decrypt"])}},ad=(e,t,n)=>{for(let r=Fc-1;r>=0;r-=1)e[t+r]=Number(n&0xffn),n>>=8n},cd=(e,t)=>{let n=0n;for(let r=0;r<Fc;r+=1)n=n<<8n|BigInt(e[t+r]);return n},ld=e=>{const t=new Uint8Array(wo);globalThis.crypto.getRandomValues(t);let n=0n;return{async encrypt(r){if(r.length>sr)throw new Ot("plaintext frame exceeds maximum size");n+=1n;const s=new Uint8Array(Oc);s.set(t,0),ad(s,wo,n);const o=new Uint8Array(await mt.encrypt({name:"AES-GCM",iv:s},e,r)),i=new Uint8Array(Yn+o.length);return i[0]=Cc,i.set(s,1),i.set(o,Yn),i}}},ud=e=>{let t=0n;return{async decrypt(n){if(n.length<Yn+td)throw new Ot("encrypted frame too short");if(n[0]!==Cc)throw new Ot("unsupported encrypted frame version");const r=n.slice(1,Yn),s=cd(r,wo);if(s<=t)throw new Ot("frame counter regression");let o;try{o=await mt.decrypt({name:"AES-GCM",iv:r},e,n.slice(Yn))}catch{throw new Ot("frame decryption failed")}return t=s,new Uint8Array(o)}}},Er="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",dd=e=>{let t="";for(let n=0;n<e.length;n+=3){const r=e[n],s=n+1<e.length?e[n+1]:void 0,o=n+2<e.length?e[n+2]:void 0;t+=Er[r>>2],t+=Er[(r&3)<<4|(s??0)>>4],s!==void 0&&(t+=Er[(s&15)<<2|(o??0)>>6]),o!==void 0&&(t+=Er[o&63])}return t},Gi=e=>{let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;const n=t;if(n.v!==Jn)return null;const r=n.batch===!0,s=n.flowControl===!0;return n.t==="ready"?{t:"ready",v:Jn,batch:r,flowControl:s}:n.t==="hello"&&typeof n.nonce=="string"&&typeof n.clientPubJwk=="object"&&n.clientPubJwk!==null?{t:"hello",v:Jn,clientPubJwk:n.clientPubJwk,nonce:n.nonce,batch:r,flowControl:s}:null},fd=e=>({type:"fail",closeCode:Qt.ChannelFailure,reason:e}),pd=async(e,t={})=>{const n=t.batch!==!1,r=await sd(e),s=await nd(),o=od(),i={t:"hello",v:Jn,clientPubJwk:await rd(s.publicKey),nonce:dd(o)};n&&(i.batch=!0),t.flowControl!==!1&&(i.flowControl=!0);let a=!1;return{helloText:JSON.stringify(i),get established(){return a},async handleText(c){if(a)return Gi(c)?.t==="ready"?{type:"ignore"}:fd("plaintext frame on established channel");const l=Gi(c);if(l?.t!=="ready")return{type:"ignore"};const u=await id(s.privateKey,r,o);return a=!0,{type:"established",batch:n&&l.batch===!0,flowControl:t.flowControl!==!1&&l.flowControl===!0,channel:{encryptor:ld(u.clientToHost),decryptor:ud(u.hostToClient)}}}}},Uc=4294967295,hd=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 be extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const We=(e,t,n,r=!1)=>{if(!Number.isInteger(t)||t<0||t>Uc)throw new be("invalid stream id");if(n.length>yo)throw new be("tunnel payload exceeds maximum size");const s=new Uint8Array(or+n.length);return s[0]=r?e|os:e,s[1]=t>>>24&255,s[2]=t>>>16&255,s[3]=t>>>8&255,s[4]=t&255,s.set(n,or),s},md=e=>{if(e.length<or)throw new be("tunnel frame too short");const t=e[0],n=(t&os)!==0,r=t&~os;if(!ed(r))throw new be(`unknown tunnel frame type ${r}`);const s=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:r,streamId:s,payload:e.slice(or),hasMoreFragments:n}},gd=new TextEncoder,yd=new TextDecoder,Pr=e=>gd.encode(JSON.stringify(e)),Ar=(e,t)=>{let n;try{n=JSON.parse(yd.decode(e))}catch{throw new be("malformed JSON tunnel payload")}if(!t(n))throw new be("unexpected JSON tunnel payload shape");return n},jc=(e,t=yo)=>{if(t<=0||t>yo)throw new be("invalid chunk size");if(e.length===0)return[new Uint8Array(0)];const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n},qi=(e,t,n)=>{const r=jc(n);return r.map((s,o)=>We(e,t,s,o<r.length-1))},wd=(e=16*1024*1024)=>{const t=new Map;return{push(n){const r=`${n.streamId}:${n.frameType}`,s=t.get(r);if(!n.hasMoreFragments&&!s)return n.payload;const o=s?.chunks??[],i=(s?.totalBytes??0)+n.payload.length;if(i>e)throw t.delete(r),new be("fragmented message exceeds maximum size");if(o.push(n.payload),n.hasMoreFragments)return t.set(r,{chunks:o,totalBytes:i}),null;t.delete(r);const a=new Uint8Array(i);let c=0;for(const l of o)a.set(l,c),c+=l.length;return a},dropStream(n){for(const r of t.keys())r.startsWith(`${n}:`)&&t.delete(r)}}},bd=e=>{if(e.length===0)throw new be("cannot encode an empty frame batch");if(e.length===1){const s=e[0],o=new Uint8Array(1+s.length);if(o[0]=Mc,o.set(s,1),o.length>sr)throw new be("frame batch exceeds maximum plaintext size");return o}let t=1;for(const s of e)t+=kn+s.length;if(t>sr)throw new be("frame batch exceeds maximum plaintext size");const n=new Uint8Array(t);n[0]=Dc;let r=1;for(const s of e)n[r]=s.length>>>24&255,n[r+1]=s.length>>>16&255,n[r+2]=s.length>>>8&255,n[r+3]=s.length&255,r+=kn,n.set(s,r),r+=s.length;return n},Sd=e=>{if(e.length<1)throw new be("empty batch plaintext");const t=e[0];if(t===Mc)return[e.slice(1)];if(t!==Dc)throw new be(`unknown batch container tag ${t}`);const n=[];let r=1;for(;r<e.length;){if(r+kn>e.length)throw new be("truncated batch frame length");const s=(e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3])>>>0;if(r+=kn,r+s>e.length)throw new be("truncated batch frame body");n.push(e.slice(r,r+s)),r+=s}if(n.length===0)throw new be("empty frame batch");return n},vd=new Set([H.HttpBody,H.WsText,H.WsBinary]),Nc=150,Td=24*1024,kd=32,Ed=e=>{const t=e.windowMs??Nc,n=e.maxBatchBytes??Td,r=e.maxBatchFrames??kd,s=e.now??(()=>Date.now()),o=e.setTimer??((b,w)=>setTimeout(b,w)),i=e.clearTimer??(b=>clearTimeout(b));let a=[],c=0,l=null,u=0,d=!1;const f=()=>{l!==null&&(i(l),l=null)},p=()=>{if(f(),a.length===0)return;const b=a;a=[],c=0,u=s(),e.sendBatch(bd(b))};return{enqueue:b=>{if(d)return;const w=b[0]&~os;if(!vd.has(w)){a.push(b),p();return}const E=s();if(a.length===0&&E-u>=t){a.push(b),p();return}const k=kn+b.length;if(a.length>0&&1+c+k>sr&&p(),a.push(b),c+=k,c>=n||a.length>=r){p();return}l===null&&(l=o(p,t))},flush:p,dispose(){d=!0,f(),a=[],c=0}}},Pd=()=>{let e=1;return{next(){if(e>Uc)throw new be("stream id space exhausted");const t=e;return e+=2,t}}},Ps=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ad=e=>Ps(e)&&Object.values(e).every(t=>typeof t=="string"),Id=e=>Ps(e)&&typeof e.status=="number"&&Ad(e.headers),Ki=e=>Ps(e)&&typeof e.reason=="string",xd=e=>Ps(e)&&typeof e.code=="number"&&typeof e.reason=="string",Bc=/^[a-z][a-z\d+.-]*:\/\//i,ri="http://tunnel.invalid",Rd=e=>{try{const t=Bc.test(e)?new URL(e):new URL(e,ri);return`${t.pathname}${t.search}`}catch{return e}},Ir=e=>({async*[Symbol.asyncIterator](){yield e}}),Cd=e=>({async*[Symbol.asyncIterator](){const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)return;r&&(yield r)}}finally{t.releaseLock()}}}),Od=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},Md=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:Cd(e)};if(typeof e=="string")return{body:Ir(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Ir(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Ir(Od(e))};const t=new Response(e),n=t.headers.get("content-type")??void 0,r=new Uint8Array(await t.arrayBuffer());return{body:Ir(r),contentType:n}},Dd=async(e,t)=>{let n;const r=new Headers;let s="GET",o=null,i;e instanceof Request?(n=e.url,s=e.method,e.headers.forEach((d,f)=>r.set(f,d)),i=e.signal,o=e.body):n=e.toString(),t&&(t.method&&(s=t.method),t.headers&&new Headers(t.headers).forEach((d,f)=>r.set(f,d)),t.body!==void 0&&(o=t.body),t.signal&&(i=t.signal));const a=Bc.test(n)?new URL(n):new URL(n,ri),{body:c,contentType:l}=await Md(o);l&&!r.has("content-type")&&r.set("content-type",l);const u={};return r.forEach((d,f)=>{u[f]=d}),{method:s.toUpperCase(),path:a.pathname,query:a.search.startsWith("?")?a.search.slice(1):a.search,headers:u,body:c,signal:i}},Hc="__openchamberAmbiguousTransport",bo=e=>(Object.defineProperty(e,Hc,{value:!0,enumerable:!1,configurable:!0}),e),Vi=e=>!e||typeof e!="object"?!1:e[Hc]===!0,_d=["local","remote",null],Ld=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function zc(e){if(!e||typeof e!="object")return{valid:!1};const t=e,n=t.localAvailable===!1?{localAvailable:!1}:{},r=t.target,s=t.status;if(r!==null&&(typeof r!="string"||!_d.includes(r)))return{valid:!1};if(typeof s!="string"||!Ld.includes(s))return{valid:!1};if(r==="remote"||r==="local"){if(s==="ok"&&r==="local")return{valid:!0,outcome:{target:"local",status:"ok",...n}};if(s==="ok"&&r==="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,...n}};if(s==="unreachable")return r==="local"?{valid:!0,outcome:{target:"local",status:"unreachable",...n}}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"unreachable",hostId:t.hostId,url:t.url,...n}};if(s==="incompatible"||s==="wrong-service")return r!=="remote"?{valid:!1}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:s,hostId:t.hostId,url:t.url,...n}};if(s==="missing")return r!=="remote"?{valid:!1}:typeof t.hostId!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"missing",hostId:t.hostId,...n}}}if(r===null){if(s==="not-configured")return{valid:!0,outcome:{target:null,status:"not-configured",...n}};if(s==="missing")return{valid:!1}}return{valid:!1}}function YS(e){if(!e.isDesktopShell)return null;const t=e.bootOutcome;if(!t)return null;const n=t.localAvailable===!1?{localAvailable:!1}:{};if(t.status==="ok"){if(t.target==="local")return{screen:"main",...n};if(t.target==="remote")return{screen:"main",hostId:t.hostId,url:t.url,...n}}if(t.target===null&&t.status==="not-configured")return{screen:"chooser",...n};if(t.target==="local"&&t.status==="unreachable")return{screen:"chooser",...n};if(t.target==="remote"){if(t.status==="unreachable")return{screen:"recovery",variant:"remote-unreachable",hostId:t.hostId,url:t.url,...n};if(t.status==="incompatible")return{screen:"recovery",variant:"remote-incompatible",hostId:t.hostId,url:t.url,...n};if(t.status==="wrong-service")return{screen:"recovery",variant:"remote-wrong-service",hostId:t.hostId,url:t.url,...n};if(t.status==="missing")return{screen:"recovery",variant:"remote-missing",hostId:t.hostId,...n}}return null}function QS(e){return e.isDesktopShell?e.bootOutcomeKnown?e.bootViewIsMain===!1?!0:e.isInitialized:!1:e.isInitialized}function XS(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function $c(){if(Fd()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,n=zc(t);return n.valid?n.outcome:null}function Fd(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":zc(e).valid?"valid":"malformed"}const is=/^[a-z][a-z\d+.-]*:\/\//i,Ud=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},as=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),jd=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return as(e)},Nd=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return as(e)},Bd=()=>Object.keys(Rs()).length>0,Hd=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},So=(e,t)=>{if(!t)return;const n=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[r,s]of n)s!=null&&e.searchParams.set(r,String(s))},zd=(e,t)=>{if(!t)return e;const n=new URLSearchParams;So({searchParams:n},t);const r=n.toString();return r?e.includes("?")?`${e}&${r}`:`${e}?${r}`:e},Ji=(e,t,n)=>{if(is.test(t)){const o=new URL(t);return So(o,n),o.toString()}const r=Ud(t);if(!e)return zd(r,n);const s=new URL(r,`${e}/`);return So(s,n),s.toString()},xr=(e,t=Sf())=>{if(!t)return e;const n=is.test(e)?new URL(e):new URL(e,"http://openchamber.local");return n.searchParams.set("oc_url_token",t),is.test(e)?n.toString():`${n.pathname}${n.search}${n.hash}`},Wc=(e,t)=>{const n=is.test(e)?new URL(e):new URL(e,Hd(t));return n.protocol==="ws:"||n.protocol==="wss:"||(n.protocol=n.protocol==="https:"?"wss:":"ws:"),n.toString()},Yi=(e,t,n)=>{if(!Bd())return null;const r=Nd();if(!r)return null;try{const s=new URL(`/api/openchamber/realtime-proxy/${e==="sse"?"sse":"ws"}`,`${r}/`);s.searchParams.set("url",t);const o=vf(r);return o&&s.searchParams.set("oc_url_token",o),e==="ws"?(s.protocol=s.protocol==="https:"?"wss:":"ws:",Wc(s.toString(),n)):s.toString()}catch{return null}},si=(e={})=>{const t=as(e.apiBaseUrl),n=as(e.realtimeBaseUrl),r=()=>t||jd(),s=()=>n||r(),o=(a,c)=>Ji(r(),a,c),i=(a,c)=>Ji(s(),a,c);return{api:o,authenticatedAsset:(a,c)=>xr(o(a,c)),assetWithUrlToken:(a,c,l)=>xr(o(a,l),c),auth:o,health:a=>o("/health",a),rawFile:(a,c)=>o("/api/fs/raw",{path:a,download:c?.download===!0?!0:void 0,allowOutsideWorkspace:c?.allowOutsideWorkspace===!0?!0:void 0,outsideFileGrant:c?.outsideFileGrant}),sse:(a,c)=>{const l=xr(i(a,c));return Yi("sse",l,e)||l},websocket:(a,c)=>{const l=Wc(xr(i(a,c)),e);return Yi("ws",l,e)||l}}};let cs=si();const Pe=()=>cs,$d=e=>{cs=e},Gc=e=>(cs=si(e),cs),vo="openchamber:runtime-endpoint-changed",To="openchamber:runtime-endpoint-will-change";let En="",ir="";const Bs=(e,t,n)=>{try{e[t]=n}catch{}},oi=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"}`}},Wd="mobile-disconnected",Gd="url:default",qc=e=>e===""||e===Gd||e===Wd,Kc=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Vc=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},Jc=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Pn=()=>En||Kc();let Hs="",Qi=null,Xi,Zi;const ea=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},W=()=>{if(ir)return ir;const e=ea("__OPENCHAMBER_API_BASE_URL__"),t=ea("__OPENCHAMBER_LOCAL_ORIGIN__");if(Qi===En&&Xi===e&&Zi===t)return Hs;const n=Pn();return Hs=Jc(n,Vc())?"local":oi(n),Qi=En,Xi=e,Zi=t,Hs},qd=(e={})=>{if(En||ir)return;const t=e.apiBaseUrl?.trim()||Kc(),n=globalThis.window?.location?.origin??"",r=/^https?:\/\//.test(n)?n:"";if(!t&&!r)return;const s=Vc(),o=s&&(!t||Jc(t,s));En=t,ir=e.runtimeKey?.trim()||(o?"local":oi(t||r))},ls=e=>{const t=e.apiBaseUrl.trim(),n=Pn(),r=W(),s=e.runtimeKey?.trim()||oi(t),o={apiBaseUrl:t,previousApiBaseUrl:n,runtimeKey:s,previousRuntimeKey:r};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(To,{detail:o})),En=t,ir=s,typeof window<"u"){const i=window;Bs(i,"__OPENCHAMBER_API_BASE_URL__",t),Bs(i,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),Bs(i,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}Gc({apiBaseUrl:t,realtimeBaseUrl:t}),cl(e.requestHeaders||null),al(e.clientToken||null),e.relay?pf(e.relay):hf(),Cs(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(vo,{detail:o}))},Kd=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(To,t),()=>window.removeEventListener(To,t)},Yc=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(vo,t),()=>window.removeEventListener(vo,t)};let ko=null;const ZS=e=>{ko=e},As=()=>ko||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),Qc=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,Vd=(e=Qc())=>!!e,Jd=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,_t=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,rn=()=>Jd()?.runtime==="electron",Yd=()=>{if(typeof window>"u")return null;const e=window.__OPENCHAMBER_PLATFORM__;return typeof e=="string"?e:null},Qd="right",ev=()=>{if(!rn())return!1;const e=Yd();return e==="win32"||e==="linux"},tv=e=>e==="left"?"left":Qd,nv=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],Ae=()=>typeof _t()?.invoke=="function",On=()=>rn()&&Ae(),Xd=()=>{if(_t()?.pickThemeFile)return{async pick(){const e=_t()?.pickThemeFile;return e?{status:"picked",file:T({name:m(),size:R().nonnegative(),text:m()}).nullable().parse(await e())}:{status:"unsupported"}}}},re=async(e,t)=>{const n=_t();return typeof n?.invoke!="function"?null:n.invoke(e,t??{})},rv=async()=>{if(!Be()||!Ee())return!1;const e=Pn();try{const t=Ne().safeParse(await re("desktop_managed_opencode_compatible",{apiBaseUrl:e}));return t.success&&t.data&&e===Pn()}catch{return!1}},sv=async()=>{if(!On()||!Ee())return null;try{const e=await re("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}},ov=async e=>{if(!On()||!Ee())return null;try{const t=await re("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}},iv=async()=>{if(!On()||!Ee())return null;try{const e=await re("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}},av=async e=>{if(!On()||!Ee())return null;try{const t=await re("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}},cv=async()=>{if(!On()||!Ee())return null;try{const e=await re("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}},lv=async e=>{if(!On()||!Ee())return null;try{const t=await re("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}},ta=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}}},zs=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}}},Zd=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),Nn=e=>{const t=Zd(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},Ee=()=>{if(typeof window>"u"||!Be())return!1;if(W()==="local")return!0;const e=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",t=zs(e),n=zs(Pn());if(!n&&t&&$c()?.target==="local")return!0;if(t&&n){if(t.origin===n.origin)return!0;const i=t.port||(t.protocol==="https:"?"443":"80"),a=n.port||(n.protocol==="https:"?"443":"80");return t.protocol===n.protocol&&i===a&&Nn(t.hostname)&&Nn(n.hostname)}const r=zs(window.location.origin);if(t&&r){if(t.origin===r.origin)return!0;const i=t.port||(t.protocol==="https:"?"443":"80"),a=r.port||(r.protocol==="https:"?"443":"80");return t.protocol===r.protocol&&i===a&&Nn(t.hostname)&&Nn(r.hostname)}const s=ta(e),o=ta(window.location.origin)||window.location.origin;return s&&o&&s===o?!0:!!(r&&Nn(r.hostname))},Be=()=>typeof window>"u"?!1:rn(),uv=async()=>{if(!Be())return!1;try{return!!await re("desktop_focus_window")}catch{return!1}},Xc=()=>Be()&&Ae()&&Ee(),ef=m().min(1),dv=e=>{if(!Xc())return null;try{const t=ef.safeParse(_t()?.pathForFile?.(e));return t.success?t.data:null}catch(t){return console.warn("Failed to resolve dropped file path",t),null}},fv=async()=>{if(!Be())return!1;try{return await re("desktop_start_window_drag"),!0}catch{return!1}},Le=()=>Vd()?!0:As()?.runtime?.isVSCode===!0,pv=()=>{const t=As()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!Le()},hv=(e,t=Be())=>e==="web"&&!t,Zc=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},mv=async e=>{if(Xc())try{const t=await _t()?.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"}},tf=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),gv=async e=>{if(Ae()&&Ee())try{const t=await _t()?.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(!tf(t))return{success:!1,error:"File selection cancelled"};const n=typeof t.path=="string"?t.path:"";return n?{success:!0,path:n,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"}},yv=async e=>({success:!0}),wv=async e=>({success:!0}),bv=async()=>Ae()?await re("desktop_check_for_updates"):null,Sv=async e=>{if(!Ae())return!1;const t=_t();let n=null,r=0,s;try{return typeof e=="function"&&t?.listen&&(n=await t.listen("openchamber:update-progress",o=>{const i=o?.payload;if(!i||typeof i!="object")return;const a=i,c=typeof a.event=="string"?a.event:null,l=a.data&&typeof a.data=="object"?a.data:null;if(c==="Started"){r=0,s=typeof l?.contentLength=="number"?l.contentLength:void 0,e({downloaded:r,total:s});return}if(c==="Progress"){const u=l?.downloaded,d=l?.total;typeof u=="number"&&(r=u),typeof d=="number"&&(s=d),e({downloaded:r,total:s});return}c==="Finished"&&e({downloaded:r,total:s})})),await re("desktop_download_and_install_update"),!0}catch(o){throw o instanceof Error?o:new Error(String(o))}finally{if(n)try{const o=n();o instanceof Promise&&await o}catch{}}},vv=async()=>Ae()?(await re("desktop_restart"),!0):!1,Tv=async()=>{if(!Ae())return!1;try{return await re("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},kv=async()=>{if(!Ae()||!Ee())return null;try{const e=await re("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}},nf=async(e,t)=>{if(!Ae()||!Ee())return!1;const n=e?.trim();if(!n)return!1;try{return await re("desktop_open_path",{path:n,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),!0}catch(r){return console.warn("Failed to open path",r),!1}},Ev=async e=>{if(!Ae()||!Ee())return!1;const t=e?.trim();if(!t)return!1;try{return await re("desktop_reveal_path",{path:t}),!0}catch{return nf(t)}},Pv=async(e,t)=>{if(!Ae()||!Ee())return null;const n=e?.trim();if(!n)return null;try{const r=await re("desktop_save_markdown_file",{defaultFileName:n,content:t});return typeof r=="string"&&r.trim().length>0?r:null}catch(r){return console.warn("Failed to save markdown file",r),null}},Av=async(e,t,n)=>{if(!Ae()||!Ee())return!1;const r=e?.trim(),s=t?.trim(),o=n?.trim();if(!r||!s||!o)return!1;try{return await re("desktop_open_in_app",{projectPath:r,appId:s,appName:o}),!0}catch(i){return console.warn("Failed to open project in app",i),!1}},Iv=async(e,t,n)=>{if(!Ae()||!Ee())return!1;const r=e?.trim(),s=t?.trim(),o=n?.trim();if(!r||!s||!o)return!1;try{return await re("desktop_open_file_in_app",{filePath:r,appId:s,appName:o}),!0}catch(i){return console.warn("Failed to open file in app",i),!1}},xv=async(e,t)=>{if(!Ae()||!Ee())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const n=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];if(n.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const r=await re("desktop_get_installed_apps",{apps:n,force:t===!0?!0:void 0});if(!r||typeof r!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const s=r;return s.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(s.apps)?{apps:s.apps.filter(i=>i&&typeof i=="object").map(i=>{const a=i;return{name:typeof a.name=="string"?a.name:"",iconDataUrl:typeof a.iconDataUrl=="string"?a.iconDataUrl:null}}).filter(i=>i.name.length>0),success:!0,hasCache:s.hasCache===!0,isCacheStale:s.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(r){return console.warn("Failed to fetch installed apps",r),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},hr=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",rf=()=>{if(typeof window>"u")return!1;const e=window.__OPENCHAMBER_ELECTRON__?.arch?.toLowerCase?.();if(e==="arm64"||e==="aarch64")return(navigator.platform||"").toLowerCase().includes("win");const t=window.__VSCODE_CONFIG__?.arch?.toLowerCase?.();if(t==="arm64"||t==="aarch64")return(navigator.platform||"").toLowerCase().includes("win");const n=navigator.userAgentData;if(n?.architecture?.toLowerCase?.()==="arm64"||n?.architecture?.toLowerCase?.()==="aarch64")return(n.platform||navigator.platform||"").toLowerCase().includes("win");const r=navigator.userAgent.toLowerCase();return!!((r.includes("aarch64")||r.includes("arm64")||r.includes("armv"))&&r.includes("windows"))},Rv=()=>{if(typeof window>"u"||!hr()||el()!=="ios")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},el=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Le()?"vscode":Be()?"desktop":"web"},sf="2.0.0",Rr=new Uint8Array(0),of=new TextEncoder,af=new TextDecoder,ze=e=>e instanceof Error?e:new Error(String(e)),Cr=()=>new DOMException("The operation was aborted.","AbortError"),cf=e=>{e.binaryType="arraybuffer";const t={get readyState(){return e.readyState},send(n){e.send(n)},close(n,r){e.close(n,r)},onopen:null,onmessage:null,onclose:null,onerror:null};return e.onopen=()=>t.onopen?.(),e.onmessage=n=>t.onmessage?.({data:n.data}),e.onclose=n=>t.onclose?.({code:n.code,reason:n.reason}),e.onerror=()=>t.onerror?.(),t},lf=e=>{const t={get readyState(){return e.readyState},get binaryType(){return e.binaryType},set binaryType(n){n&&(e.binaryType=n)},onopen:null,onmessage:null,onerror:null,onclose:null,send(n){e.send(n)},close(n,r){e.close(n,r)}};return e.onopen=()=>t.onopen?.(),e.onmessage=n=>{const r=n.data;(typeof r=="string"||r instanceof ArrayBuffer)&&t.onmessage?.({data:r})},e.onerror=()=>t.onerror?.(),e.onclose=n=>t.onclose?.({code:n.code,reason:n.reason}),t},na=0,$s=1,ra=2,sa=3,uf=new Set([Qt.AuthFailed,Qt.DuplicateClient,Qt.LimitExceeded]),df={[Qt.AuthFailed]:"relay authentication failed",[Qt.DuplicateClient]:"relay connection replaced by another client",[Qt.LimitExceeded]:"relay connection limit reached"},oa=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},ii=e=>{const t=e.helloRetryMs??1e3,n=e.helloTimeoutMs??3e4,r=e.pingIntervalMs??3e4,s=e.pingTimeoutMs??15e3,o=e.batchWindowMs??Nc,i=e.batch!==!1,a=e.reconnectBaseDelayMs??1e3,c=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,u=e.createWireSocket??(x=>cf(new WebSocket(x)));let d=!1,f=null,p={state:"idle"};const y=new Set;let b=null,w=null,E=null,k=0,U=0,D=null,J=[],C=!1;const Se=x=>{if(!(p.state===x.state&&p.lastError===x.lastError)){p=x;for(const $ of y)try{$(p)}catch{}}},ae=x=>{const $=J;J=[];for(const M of $)M.reject(x)},Fs=x=>{const $=J;J=[];for(const M of $)M.resolve(x)},Ie=(x,$)=>{x.dead=!0;const M=Array.from(x.streams.values());x.streams.clear();for(const _ of M)try{_.fail($)}catch{}},_n=()=>{D!==null&&(clearTimeout(D),D=null)},Ln=()=>{d||D===null||oa()||(_n(),Qe(),Fn())},Ut=()=>{typeof document<"u"&&document.visibilityState==="visible"&&Ln()},F=()=>{C||typeof window>"u"||(C=!0,window.addEventListener("online",Ln),typeof document<"u"&&document.addEventListener("visibilitychange",Ut))},Qe=()=>{!C||typeof window>"u"||(C=!1,window.removeEventListener("online",Ln),typeof document<"u"&&document.removeEventListener("visibilitychange",Ut))},an=()=>{if(d||D!==null)return;const x=Math.max(0,U-1),$=a*2**Math.min(x,10),M=oa()?l:c,_=Math.min(M,$);F(),D=setTimeout(()=>{D=null,Qe(),Fn()},_)},vr=()=>{const x=new URL(e.relayUrl);return x.searchParams.set("v",String(Jn)),x.searchParams.set("role","client"),x.searchParams.set("serverId",e.serverId),x.searchParams.set("appId","openchamber"),x.searchParams.set("appVersion",sf),x.searchParams.set("platform",el()),e.grant&&x.searchParams.set("grant",e.grant),x.toString()},Fn=async()=>{if(d)return;_n(),k+=1;const x=k;Se({state:U>0?"reconnecting":"connecting",lastError:p.lastError});let $;try{$=await pd(e.hostEncPubJwk,{batch:i,flowControl:e.flowControl})}catch(Y){if(x!==k||d)return;zi(x,ze(Y),!0);return}if(x!==k||d)return;let M;try{M=u(vr())}catch(Y){zi(x,ze(Y));return}w=M;let _=!1,j=null,q=null,Ce=null,ge=null,B=Promise.resolve(),z=null,se=null,at=!1,fe=!1,pe=0,ye=0,we=null,ct=null,Z=Date.now();const bt=()=>{we!==null&&(clearTimeout(we),we=null),j!==null&&(clearInterval(j),j=null),q!==null&&(clearTimeout(q),q=null),Ce!==null&&(clearInterval(Ce),Ce=null),ge!==null&&(clearTimeout(ge),ge=null),ct!==null&&(ct.dispose(),ct=null)};E=bt;function V(Y,oe=!1,X=!1){if(!(_||x!==k)){_=!0,X&&(f=Y),bt(),z&&(b=null,Ie(z,new Error(`relay tunnel reset: ${Y.message}`))),ae(Y);try{M.close()}catch{}if(w===M&&(w=null),!d){if(U+=1,X){Se({state:"error",lastError:Y.message});return}Se({state:oe?"error":"reconnecting",lastError:Y.message}),an()}}}const Un=()=>{try{M.send($.helloText)}catch{}},kr=(Y,oe,X)=>{se=Y,at=oe,fe=X,j!==null&&(clearInterval(j),j=null),q!==null&&(clearTimeout(q),q=null);const ce=new Map,jt=Pd(),He=wd();let Nt=Promise.resolve();const St=jn=>{Nt=Nt.then(async()=>{if(Bt.dead)return;const Ku=await Y.encryptor.encrypt(jn);Bt.dead||M.send(Ku)}).catch(()=>{V(new Error("relay encrypt/send failed"))})},js=oe?Ed({windowMs:o,sendBatch:St}):null;ct=js;const Bt={streams:ce,assembler:He,nextStreamId:()=>jt.next(),dead:!1,send(jn){Bt.dead||(js?js.enqueue(jn):St(jn))}};z=Bt,b=Bt,U=0,Z=Date.now(),Se({state:"connected"}),Fs(Bt),Ce=setInterval(()=>{Date.now()-Z<r||(Bt.send(We(H.Ping,0,Rr)),ge===null&&(ge=setTimeout(()=>{ge=null,V(new Error("relay keepalive timeout"))},s)))},r)},cn=()=>{we!==null&&clearTimeout(we),we=null,!(!z||z.dead||pe===ye)&&(ye=pe,z.send(We(H.DeliveryAck,0,hd(pe))))},qu=(Y,oe)=>{let X;try{X=md(oe)}catch(He){V(ze(He));return}if(X.frameType===H.DeliveryAck){V(new Error("unexpected downstream delivery acknowledgement"));return}if(fe&&X.streamId!==0&&(pe+=oe.length,we===null&&(we=setTimeout(cn,10))),Z=Date.now(),ge!==null&&(clearTimeout(ge),ge=null),X.frameType===H.Ping){Y.send(We(H.Pong,X.streamId,Rr));return}if(X.frameType===H.Pong)return;let ce=X.payload;if(X.frameType===H.WsText||X.frameType===H.WsBinary){let He;try{He=Y.assembler.push(X)}catch(Nt){V(ze(Nt));return}if(He===null)return;ce=He}else if(X.hasMoreFragments){V(new Error("unexpected fragmented tunnel frame"));return}const jt=Y.streams.get(X.streamId);jt&&jt.handleFrame(X.frameType,ce)};M.onopen=()=>{_||x!==k||(Un(),j=setInterval(Un,t))},M.onmessage=Y=>{if(_||x!==k)return;const oe=Y.data;if(typeof oe=="string"){B=B.then(async()=>{if(_||x!==k)return;const ce=await $.handleText(oe);if(ce.type==="established"){if(se)return;kr(ce.channel,ce.batch,ce.flowControl)}else ce.type==="fail"&&V(new Error(`relay handshake failed: ${ce.reason}`))}).catch(ce=>{V(ze(ce))});return}const X=oe instanceof ArrayBuffer?new Uint8Array(oe):oe instanceof Uint8Array?oe:null;X&&(B=B.then(async()=>{if(_||x!==k)return;const ce=z,jt=se;if(!ce||!jt){V(new Error("encrypted frame before handshake completed"));return}let He;try{He=await jt.decryptor.decrypt(X)}catch(St){V(ze(St));return}let Nt;try{Nt=at?Sd(He):[He]}catch(St){V(ze(St));return}for(const St of Nt){if(_||x!==k||ce.dead)return;qu(ce,St)}fe&&pe-ye>=16*1024&&cn()}).catch(ce=>{V(ze(ce))}))},M.onclose=Y=>{const oe=uf.has(Y.code);V(new Error(df[Y.code]??`relay socket closed (code ${Y.code})`),oe,oe)},M.onerror=()=>{},q=setTimeout(()=>{q=null,V(new Error("relay handshake timeout"),!0)},n);function zi(Y,oe,X=!1){Y!==k||d||(ae(oe),U+=1,Se({state:X?"error":"reconnecting",lastError:oe.message}),an())}},Tr=x=>d?Promise.reject(new Error("relay tunnel closed")):x?.aborted?Promise.reject(Cr()):f?Promise.reject(f):b&&!b.dead?Promise.resolve(b):new Promise(($,M)=>{let _=null;const j={resolve(q){_&&x&&x.removeEventListener("abort",_),$(q)},reject(q){_&&x&&x.removeEventListener("abort",_),M(q)}};x&&(_=()=>{J=J.filter(q=>q!==j),M(Cr())},x.addEventListener("abort",_,{once:!0})),J.push(j)}),wt=async(x,$)=>{const M=await Dd(x,$),_=M.signal;if(_?.aborted)throw Cr();const j=await Tr(_),q=j.nextStreamId();return await new Promise((Ce,ge)=>{let B=!1,z=!1,se=null,at=null;const fe=()=>{j.streams.delete(q),j.assembler.dropStream(q),at&&_&&_.removeEventListener("abort",at)},pe=Z=>{if(!z){if(z=!0,fe(),!B){ge(Z);return}try{se?.error(Z)}catch{}}},ye=Z=>{j.dead||j.send(We(H.StreamAbort,q,Pr({reason:Z})))},we=Z=>bo(new Error(Z));at=()=>{ye("aborted"),pe(Cr())},j.streams.set(q,{handleFrame(Z,bt){if(Z===H.HttpResponse){if(B||z)return;let V;try{V=Ar(bt,Id)}catch(cn){ye("malformed response head"),pe(we(ze(cn).message));return}const Un=V.status===204||V.status===205||V.status===304;let kr=null;Un||(kr=new ReadableStream({start(cn){se=cn},cancel(){z||(z=!0,fe(),ye("response body cancelled"))}})),B=!0,Ce(new Response(kr,{status:V.status,headers:V.headers})),Un&&(z=!0,fe());return}if(Z===H.HttpBody){if(!B||z)return;try{se?.enqueue(bt)}catch{}return}if(Z===H.StreamEnd){if(z)return;if(!B){pe(we("tunnel stream ended before response head"));return}z=!0,fe();try{se?.close()}catch{}return}if(Z===H.StreamAbort){let V="stream aborted by host";try{V=Ar(bt,Ki).reason}catch{}pe(we(V))}},fail(Z){pe(we(Z.message))}}),_&&_.addEventListener("abort",at,{once:!0});const ct={method:M.method,path:M.path,query:M.query,headers:M.headers,hasBody:M.body!==null};j.send(We(H.HttpRequest,q,Pr(ct))),(async()=>{try{let Z=!1;if(M.body)for await(const bt of M.body){if(z||j.dead)return;for(const V of jc(bt))j.send(We(H.HttpBody,q,V)),Z=!0}!z&&!j.dead&&(M.body&&!Z&&j.send(We(H.HttpBody,q,Rr)),j.send(We(H.StreamEnd,q,Rr)))}catch(Z){ye("request body failed"),pe(we(ze(Z).message))}})()})},Us=x=>{const $=x.indexOf("?");return $===-1?{path:x,query:""}:{path:x.slice(0,$),query:x.slice($+1)}},Wu=(x,$)=>{let M=na,_=null,j=0,q=!1;const Ce={get readyState(){return M},onopen:null,onmessage:null,onerror:null,onclose:null,send(B){if(M!==$s||!_||_.dead)throw new Error("relay tunnel socket is not open");if(typeof B=="string"){for(const se of qi(H.WsText,j,of.encode(B)))_.send(se);return}const z=B instanceof ArrayBuffer?new Uint8Array(B.slice(0)):(()=>{const se=new Uint8Array(B.byteLength);return se.set(new Uint8Array(B.buffer,B.byteOffset,B.byteLength)),se})();for(const se of qi(H.WsBinary,j,z))_.send(se)},close(B=1e3,z=""){M===sa||M===ra||(M===$s&&_&&!_.dead&&(M=ra,_.send(We(H.WsClose,j,Pr({code:B,reason:z})))),ge(B,z))}},ge=(B,z,se=!1)=>{if(!q){if(q=!0,_&&(_.streams.delete(j),_.assembler.dropStream(j)),M=sa,se)try{Ce.onerror?.()}catch{}try{Ce.onclose?.({code:B,reason:z})}catch{}}};return(async()=>{let B;try{B=await Tr()}catch(fe){ge(1006,ze(fe).message,!0);return}if(q)return;_=B,j=B.nextStreamId(),B.streams.set(j,{handleFrame(fe,pe){if(fe===H.WsOpened){if(M===na){M=$s;try{Ce.onopen?.()}catch{}}return}if(fe===H.WsText){try{Ce.onmessage?.({data:af.decode(pe)})}catch{}return}if(fe===H.WsBinary){const ye=new ArrayBuffer(pe.byteLength);new Uint8Array(ye).set(pe);try{Ce.onmessage?.({data:ye})}catch{}return}if(fe===H.WsClose){let ye=1e3,we="";try{const ct=Ar(pe,xd);ye=ct.code,we=ct.reason}catch{}ge(ye,we);return}if(fe===H.StreamAbort){let ye="stream aborted";try{ye=Ar(pe,Ki).reason}catch{}ge(1006,ye,!0)}},fail(fe){ge(1012,fe.message,!0)}});const{path:z,query:se}=Us(x),at=$&&$.length>0?{path:z,query:se,protocols:$}:{path:z,query:se};B.send(We(H.WsOpen,j,Pr(at)))})(),Ce},Gu=()=>{if(d)return;d=!0,k+=1,_n(),Qe(),E?.(),E=null;const x=b;b=null;const $=new Error("relay tunnel closed");x&&Ie(x,$),ae($);try{w?.close()}catch{}w=null,Se({state:"idle"})};return Fn(),{fetch:wt,openWebSocket:Wu,getStatus:()=>p,subscribeStatus(x){return y.add(x),()=>{y.delete(x)}},close:Gu}};let De=null,gt=null;const ff=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),Is=()=>De,Cv=()=>!De||!gt?null:{relayUrl:gt.relayUrl,serverId:gt.serverId,hostEncPubJwk:{...gt.hostEncPubJwk}},Ov=()=>De!==null,pf=e=>(De&>&&ff(gt,e)||(De?.close(),gt=e,De=ii(e)),De),Mv=(e,t)=>{De!==t&&(De?.close(),gt=e,De=t)},hf=()=>{De?.close(),De=null,gt=null};let tl=()=>null,nl="",us={},en="",ar=0,Kt=null,Sn="",cr=0,tn="",Vt=null,xt="",Jr=0,Yr=0;const ai=1e4,mf=e=>e.toLowerCase()==="authorization",rl=e=>{const t={};for(const[n,r]of Object.entries(e||{})){const s=n.trim(),o=r.trim();s&&o&&!mf(s)&&(t[s]=o)}return t},gf=(e,t)=>{const n=Object.entries(e);return n.length!==Object.keys(t).length?!1:n.every(([r,s])=>t[r]===s)},xs=e=>typeof e!="string"?"":e.trim(),yf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return xs(e)},wf=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},sl=(e,t)=>{const n=typeof e=="string"&&e.trim()?e.trim():wf();if(!n)return t;try{return new URL(t,`${n.replace(/\/+$/,"")}/`).toString()}catch{return t}},ci=e=>{try{return new URL(e).origin}catch{return""}},ol=()=>{Sn="",cr=0,tn="",Vt=null,xt="",Jr+=1},mr=()=>{en="",ar=0,ol()},il=()=>{Yr+=1,Kt=null,mr(),li()},al=e=>{const t=xs(e);nl=t,il(),tl=()=>t?{type:"bearer",token:t}:null},cl=e=>{const t=rl(e);gf(us,t)||(us=t,il())},Rs=()=>{if(Object.keys(us).length>0)return us;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?rl(e):{}},ll=()=>nl||yf(),bf=(e,t)=>{const n=xs(e);if(!n||typeof t!="number"||!Number.isFinite(t)){mr();return}const r=en;en=n,ar=t,r&&r!==n&&Pf()},ul=()=>!en||ar<=Date.now()+ai?(mr(),""):en,dl=e=>{const t=ci(e);return!t||tn!==t?"":!Sn||cr<=Date.now()+ai?(Sn="",cr=0,tn="",""):Sn},Sf=()=>{const e=ul();return!e&&(ll()||typeof window<"u")&&Cs().catch(()=>{}),e},vf=e=>{const t=e?dl(e):"";return!t&&e&&typeof window<"u"&&ml(e).catch(()=>{}),t},fl=async()=>{const e=await tl(),t=e?.type==="bearer"?xs(e.token):ll();return t?{type:"bearer",token:t}:null},Tf=T({token:m(),expiresAt:R()}),pl=async(e,t)=>{const n=await fl(),r=new Headers;for(const[c,l]of Object.entries(Rs()))r.set(c,l);n?.type==="bearer"&&r.set("Authorization",`Bearer ${n.token}`);const s=t?`/auth/url-token?scope=${encodeURIComponent(t)}`:"/auth/url-token",o=Is(),i=o?await o.fetch(s,{method:"POST",headers:r}):await fetch(sl(e,s),{method:"POST",headers:r,credentials:"include"});if(!i.ok)throw new Error(`Failed to mint runtime URL auth token (${i.status})`);const a=Tf.safeParse(await i.json().catch(()=>null));return a.success?{token:a.data.token.trim(),expiresAt:a.data.expiresAt}:{token:"",expiresAt:0}},Dv=async e=>{const t=await pl(null,`guest:${e}`);if(!t.token)throw new Error("Guest URL auth token response was invalid");return t},hl=e=>{if(Kt)return Kt;const t=Yr,r=(async()=>{let s;try{s=await pl(e)}catch(o){throw t===Yr&&mr(),o}if(t!==Yr)throw new Error("Runtime URL auth token response is stale");if(bf(s.token,s.expiresAt),!en)throw new Error("Runtime URL auth token response was invalid");return en})().finally(()=>{Kt===r&&(Kt=null)});return Kt=r,Kt},kf=e=>{const t=ci(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(Vt&&xt===t)return Vt;const n=Jr,s=(async()=>{const o=await fetch(sl(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!o.ok)throw n===Jr&&t===xt&&(Sn="",cr=0,tn=""),new Error(`Failed to mint local runtime URL auth token (${o.status})`);const i=await o.json().catch(()=>null),a=typeof i?.token=="string"?i.token.trim():"",c=typeof i?.expiresAt=="number"?i.expiresAt:0;if(!a||!Number.isFinite(c))throw new Error("Local runtime URL auth token response was invalid");if(n!==Jr||t!==xt)throw new Error("Local runtime URL auth token response is stale");return Sn=a,cr=c,tn=t,a})().finally(()=>{Vt===s&&(Vt=null,xt="")});return Vt=s,xt=t,Vt},Cs=async e=>{const t=ul();return t||hl(e)},ml=async e=>{const t=ci(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const n=dl(t);return n||((tn&&tn!==t||xt&&xt!==t)&&ol(),kf(t))};let yn=0,Qn=null,gl=null;const Eo=new Set,Ef=5e3,Pf=()=>{for(const e of Eo)try{e()}catch{}},yl=()=>{Qn!==null&&(clearTimeout(Qn),Qn=null)},li=()=>{if(yl(),yn<=0||typeof window>"u")return;const e=ar-ai-Ef,t=ar>0?Math.max(0,e-Date.now()):0;Qn=setTimeout(()=>{Qn=null,!(yn<=0)&&hl(gl).catch(()=>{}).finally(()=>{li()})},t)},_v=e=>{typeof e=="string"&&e.trim()&&(gl=e.trim()),yn+=1,li();let t=!1;return()=>{t||(t=!0,yn=Math.max(0,yn-1),yn===0&&yl())}},Lv=e=>(Eo.add(e),()=>{Eo.delete(e)}),Af=async e=>{const t=new Headers(e);for(const[r,s]of Object.entries(Rs()))t.has(r)||t.set(r,s);if(t.has("Authorization"))return t;const n=await fl();return n?.type==="bearer"&&t.set("Authorization",`Bearer ${n.token}`),t},ds=yt(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),If=15e3,xf=5*6e4;let Po=0,Ws=!1;const Rf=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),Cf=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?!1:!Rf(t)},wl=async()=>{if(!Ws){Ws=!0;try{const{runtimeFetch:e}=await ni(async()=>{const{runtimeFetch:n}=await Promise.resolve().then(()=>zf);return{runtimeFetch:n}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){ds.getState().markExpired();return}if(t.ok){const{state:n,markAuthenticated:r}=ds.getState();n==="expired"&&r()}}catch{}finally{Ws=!1}}},Of=(e,t)=>{if(t!==401||ds.getState().state==="expired"||!Cf(e))return;const n=Date.now();n-Po<If||(Po=n,wl())};let ia=!1;const Fv=()=>{if(ia)return;ia=!0;let e=Date.now();const t=()=>{if(ds.getState().state!=="ok")return;const n=Date.now();n-e<xf||(e=n,Po=n,wl())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},nn=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",Mf=()=>typeof window>"u"?"":window.location.origin||"",ui=e=>{if(typeof window>"u")return!1;const t=Mf();if(t&&e.origin===t)return!0;try{const n=new URL(window.location.href||t);return e.protocol===n.protocol&&e.host===n.host}catch{return!1}},di=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),Df=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),At=(e,t)=>{try{Df(new URL(e).hostname)&&!t.has("ngrok-skip-browser-warning")&&t.set("ngrok-skip-browser-warning","openchamber")}catch{}return t},fi=(e,t)=>{if(!t)return;const n=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[r,s]of n)s!=null&&e.searchParams.set(r,String(s))},Qr=e=>{try{const t=Pe().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(t))return!1;const n=new URL(t);return e.origin!==n.origin?!1:nn(e.pathname)}catch{return!1}},Gs=e=>{if(nn(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return ui(t)&&nn(t.pathname)}catch{return!1}},_f=(e,t)=>{try{const n=new URL(e);if(!ui(n))return e;const r=Dt(`${n.pathname}${n.search}`,t);return!di(r)&&(n.protocol==="http:"||n.protocol==="https:")?(fi(n,t),n.toString()):n.hash?`${r}${n.hash}`:r}catch{return e}},Dt=(e,t)=>e==="/health"?Pe().health(t):e.startsWith("/auth/")||e==="/auth"?Pe().auth(e,t):nn(e)?Pe().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?_f(e,t):e,Lf=e=>{const t=e instanceof Request?e.url:e.toString();if(!di(t))return nn(t);try{return Qr(new URL(t))}catch{return!1}},bl=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},Ff=(e,t)=>!bl(t),Ao=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 n=[];let r=!1,s=!1;for(const[o,i]of t)Ff(o,i)?(n.push([o,encodeURIComponent(i)]),r=!0,o.toLowerCase()==="x-opencode-directory"&&(s=!0)):n.push([o,i]);return s&&n.push(["x-opencode-directory-encoding","uri"]),r?n:void 0},lt=async(e,t,n=!0)=>{const r=new Headers(Ao(e)??e);return t&&new Headers(Ao(t)??t).forEach((s,o)=>r.set(o,s)),n?Af(r):r},Uf=(e,t)=>{if(!t)return e;const n=new URL(e,ri);return fi(n,t),`${n.pathname}${n.search}`},Sl=(e,t)=>{const n=e instanceof Request?e.url:e.toString();if(!di(n))return nn(n)?Uf(n,t):null;try{const r=new URL(n);return!ui(r)||!nn(r.pathname)?null:(fi(r,t),`${r.pathname}${r.search}`)}catch{return null}},jf=async(e,t,n)=>{const r=Is();if(!r)return null;const s=Sl(e,n);if(s===null)return null;const o=e instanceof Request?e.headers:void 0,i=await lt(o,t.headers,!0);return e instanceof Request?r.fetch(e,{...t,headers:i}):r.fetch(s,{...t,headers:i})},Nf=(e,t)=>{if(typeof e=="string")return Dt(e,t);if(e instanceof URL)return Dt(e.toString(),t);const n=Dt(e.url,t);return n===e.url?e:new Request(n,e)},Bf=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Or=new Map,Hf=(e,t,n,r)=>n||e!=="GET"||t.includes("/event")||!Bf.test(t)?null:`GET ${t}\0${r.get("x-opencode-directory")??""}`,g=async(e,t={})=>{const{query:n,...r}=t,s=Is(),o=s?Sl(e,n):null;let i,a,c,l;if(s&&o!==null){const b=e instanceof Request?e.headers:void 0,w=await lt(b,r.headers,!0);i=e instanceof Request?()=>s.fetch(e,{...r,headers:w}):()=>s.fetch(o,{...r,headers:w}),l=w,a=o,c=String(r.method??(e instanceof Request?e.method:"GET")).toUpperCase()}else{const b=Nf(e,n),w=b instanceof Request?b.headers:void 0,E=await lt(w,r.headers,Lf(b)),k=b instanceof Request?b.url:b instanceof URL?b.toString():String(b);At(k,E),i=b instanceof Request?()=>fetch(new Request(b,{...r,headers:E})):()=>fetch(b,{...r,headers:E}),l=E,a=k,c=String(r.method??(b instanceof Request?b.method:"GET")).toUpperCase()}const u=i;i=()=>u().then(b=>(Of(a,b.status),b));const d=r.signal!=null||e instanceof Request,f=Hf(c,a,d,l);if(!f)return i();const p=Or.get(f);if(p)return p.then(b=>b.clone());const y=i();return Or.set(f,y),y.then(()=>Or.delete(f),()=>Or.delete(f)),y.then(b=>b.clone())};let aa=!1;const vl=()=>{if(aa||typeof window>"u")return;aa=!0;const e=window.fetch.bind(window);window.fetch=async(t,n)=>{const r=await jf(t,n??{});if(r)return r;if(typeof t=="string"){if(!Gs(t)){try{const i=new URL(t);if(Qr(i)){const a=await lt(void 0,n?.headers);return At(i.toString(),a),e(t,{...n,headers:a})}}catch{}return e(t,n)}const s=await lt(void 0,n?.headers),o=Dt(t);return At(o,s),e(o,{...n,headers:s})}if(t instanceof URL){const s=t.toString();if(!Gs(s)){if(Qr(t)){const a=await lt(void 0,n?.headers);return At(t.toString(),a),e(t,{...n,headers:a})}return e(t,n)}const o=await lt(void 0,n?.headers),i=Dt(s);return At(i,o),e(i,{...n,headers:o})}if(t instanceof Request){if(!Gs(t.url)){try{const a=new URL(t.url);if(Qr(a)){const c=await lt(t.headers,n?.headers);return At(a.toString(),c),e(new Request(t,{...n,headers:c}))}}catch{}return e(t,n)}const s=await lt(t.headers,n?.headers),o=Dt(t.url);At(o,s);const i=o===t.url?t:new Request(o,t);return e(new Request(i,{...n,headers:s}))}return e(t,n)}},zf=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:At,buildRuntimeFetchUrl:Dt,installRuntimeFetchBridge:vl,isLatin1Safe:bl,runtimeFetch:g,sanitizeHeadersForBrowser:Ao},Symbol.toStringTag,{value:"Module"})),vn=16384,fs=globalThis,$f=e=>{if(fs.Buffer)return fs.Buffer.from(e,"utf8").toString("base64url");const t=new TextEncoder().encode(e);let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.slice(r,r+32768));return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")},Tl=e=>{try{if(fs.Buffer)return fs.Buffer.from(e,"base64url").toString("utf8");const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),n=atob(t),r=new Uint8Array(n.length);for(let s=0;s<n.length;s+=1)r[s]=n.charCodeAt(s);return new TextDecoder().decode(r)}catch{return null}},Wf=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?null:(n.hash="",n.toString().replace(/\/+$/g,""))}catch{return null}},Gf=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const n=new URL(t);return n.protocol!=="ws:"&&n.protocol!=="wss:"?null:(n.hash="",n.toString())}catch{return null}},ca=e=>typeof e=="string"&&e.length>0,qf=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!ca(t.x)||!ca(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},Kf=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Vf=e=>{if(!e||typeof e!="object")return null;const t=e,n=Kf(t.priority);if(t.type==="lan"||t.type==="tunnel"){const r=Wf(t.url);return r?n===void 0?{type:t.type,url:r}:{type:t.type,url:r,priority:n}:null}if(t.type==="relay"){const r=Gf(t.relayUrl);if(!r)return null;const s=typeof t.serverId=="string"?t.serverId.trim():"";if(!s)return null;const o=qf(t.hostEncPubJwk);if(!o)return null;const i=typeof t.grant=="string"&&t.grant.trim()?t.grant.trim():void 0;return{type:"relay",relayUrl:r,serverId:s,hostEncPubJwk:o,...i?{grant:i}:{},...n===void 0?{}:{priority:n}}}return null},pi=e=>{if(!e||typeof e!="object")return null;const t=e;if(t.v!==2)return null;const n=typeof t.pairingId=="string"?t.pairingId.trim():"",r=typeof t.secret=="string"?t.secret.trim():"";if(!n||!r)return null;const s=Array.isArray(t.candidates)?t.candidates.map(Vf).filter(c=>!!c):[];if(s.length===0)return null;const o=typeof t.expiresAt=="string"&&t.expiresAt.trim()?t.expiresAt.trim():void 0;if(o){const c=Date.parse(o);if(!Number.isFinite(c)||c<=Date.now())return null}const i=typeof t.label=="string"&&t.label.trim()?t.label.trim():void 0,a=typeof t.fingerprint=="string"&&t.fingerprint.trim()?t.fingerprint.trim():void 0;return{v:2,pairingId:n,secret:r,...i?{label:i}:{},...a?{fingerprint:a}:{},...o?{expiresAt:o}:{},candidates:s}},Uv=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}),jv=e=>{const t=pi(e);if(!t)throw new Error("Invalid pairing connection payload");const n=new URLSearchParams;return n.set("v","2"),n.set("p",$f(JSON.stringify(t))),`openchamber://connect?${n.toString()}`},Jf=e=>{const t=e.trim();if(!t||t.length>vn)return null;try{const n=new URL(t);if(n.protocol!=="openchamber:"||n.hostname!=="connect"||n.searchParams.get("v")!=="2")return null;const r=n.searchParams.get("p")||"";if(!r||r.length>vn)return null;const s=Tl(r);return!s||s.length>vn?null:pi(JSON.parse(s))}catch{return null}},Nv=e=>{const t=e.trim();if(!t||t.length>vn)return null;const n=t.indexOf("?");if(n===-1||!/^openchamber:\/\/connect\/?$/i.test(t.slice(0,n)))return null;let r=null,s=null;for(const i of t.slice(n+1).split("&")){const a=i.indexOf("=");if(a===-1)continue;const c=i.slice(0,a),l=i.slice(a+1);c==="v"?r=l:c==="p"&&(s=l)}if(r!=="2"||!s||s.length>vn)return null;const o=Tl(s);if(!o||o.length>vn)return null;try{return pi(JSON.parse(o))}catch{return null}},An=e=>typeof e=="object"&&e!==null,Yf=e=>e.trim().toLowerCase()==="authorization",Qf=e=>{if(!An(e))return;const t={};for(const[n,r]of Object.entries(e)){const s=n.trim(),o=typeof r=="string"?r.trim():"";!s||!o||/[\r\n:]/.test(s)||/[\r\n]/.test(o)||Yf(s)||(t[s]=o)}return Object.keys(t).length>0?t:void 0},Xf=e=>`relay://${e}`,Zf=e=>{if(!An(e))return null;const t=ve(e,"relayUrl")||ve(e,"relay_url"),n=ve(e,"serverId")||ve(e,"server_id"),r=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!n||!An(r)?null:{relayUrl:t,serverId:n,hostEncPubJwk:r}},ep=()=>{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"},Bv=async(e,t)=>{const n=Jf(e);if(!n)throw new Error("invalid-connect-link");const r=await op().catch(()=>""),s={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({pairingId:n.pairingId,secret:n.secret,clientLabel:n.label||"OpenChamber Desktop",clientKind:"desktop",deviceName:"OpenChamber Desktop",devicePlatform:ep(),...r?{dedupeKey:`desktop:${r}`}:{}})},o=async w=>{if(!w.ok)return null;const E=await w.json().catch(()=>null);return(typeof E?.clientToken=="string"?E.clientToken.trim():"")||null};let i=null;const a=[...n.candidates].sort((w,E)=>(w.type==="relay"?1:0)-(E.type==="relay"?1:0));for(const w of a){if(w.type==="relay"){const k=ii({relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk,...w.grant?{grant:w.grant}:{}});try{const U=await o(await k.fetch("/api/client-auth/pairing/redeem",s));if(U){i={relay:{relayUrl:w.relayUrl,serverId:w.serverId,hostEncPubJwk:w.hostEncPubJwk},token:U};break}}catch{}finally{k.close()}continue}const E=Te(w.url);if(E)try{const k=await o(await fetch(`${E}/api/client-auth/pairing/redeem`,s));if(k){i={directUrl:E,token:k};break}}catch{}}if(!i)throw new Error("pairing-redeem-failed");const c=n.candidates.find(w=>w.type==="relay"),l=i.relay||(c?{relayUrl:c.relayUrl,serverId:c.serverId,hostEncPubJwk:c.hostEncPubJwk}:void 0),u=n.candidates.filter(w=>w.type!=="relay").map(w=>Te(w.url)).find(w=>!!w),d=i.directUrl||u,f=d||(l?Xf(l.serverId):null);if(!f)throw new Error("pairing-missing-transport");const p=t.find(w=>l?w.relay?.serverId===l.serverId:!w.relay&&Te(w.apiUrl||w.url)===f),y=p?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),b={...p||{},id:y,label:n.label||p?.label||kl(f),url:f,apiUrl:d,clientToken:i.token,...l?{relay:l}:{}};return{hostId:y,hosts:p?t.map(w=>w.id===y?b:w):[b,...t]}},tp=/^(t|.*(?:token|auth|secret|api).*)$/i,Te=e=>{const t=e.trim();if(!t)return null;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?null:t.split("#")[0]||null}catch{return null}},Hv=e=>{const t=Te(e);if(!t)return null;try{const n=new URL(t);if((n.pathname.replace(/\/+$/,"")||"/")==="/connect"&&n.searchParams.has("t"))return{persistedUrl:n.origin,redeemUrl:n.toString(),kind:"tunnel-connect-link"}}catch{return null}return{persistedUrl:t,redeemUrl:null,kind:"normal-host"}},kl=e=>{const t=Te(e);if(!t)return e;try{const n=new URL(t);(n.username||n.password)&&(n.username="",n.password="");const r=Array.from(new Set(Array.from(n.searchParams.keys())));for(const s of r)tp.test(s)&&n.searchParams.set(s,"[REDACTED]");return n.toString()}catch{return t}},Mr=(e,t)=>{const n=Te(e),r=Te(t);if(!n||!r)return!1;try{const s=new URL(n),o=new URL(r);if(s.origin!==o.origin||o.search&&s.search!==o.search)return!1;const i=o.pathname.length>1?o.pathname.replace(/\/+$/,""):o.pathname,a=s.pathname.length>1?s.pathname.replace(/\/+$/,""):s.pathname;return i==="/"?!0:a===i||a.startsWith(`${i}/`)}catch{return!1}},ve=(e,t)=>{const n=e[t];return typeof n=="string"?n:null},la=(e,t)=>{const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null},np=e=>{if(!An(e))return null;const t=ve(e,"id"),n=ve(e,"label"),r=ve(e,"url"),s=ve(e,"apiUrl")||ve(e,"api_url"),o=ve(e,"clientToken")||ve(e,"client_token"),i=Qf(e.requestHeaders),a=Zf(e.relay);return!t||!n||!r?null:{id:t,label:n,url:r,...s?{apiUrl:s}:{},...o?{clientToken:o}:{},...i?{requestHeaders:i}:{},...a?{relay:a}:{}}},Xn=e=>Te(e.apiUrl||e.url)||e.apiUrl||e.url,sn=()=>Ae()?(e,t)=>re(e,t):null,hi=async()=>{const e=sn();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!An(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const n=t.hosts,r=Array.isArray(n)?n.map(np).filter(a=>!!a):[],s=ve(t,"defaultHostId")||ve(t,"default_host_id")||ve(t,"defaultHostID"),o=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,i=ve(t,"localOrigin")||ve(t,"local_origin");return{hosts:r,defaultHostId:s,initialHostChoiceCompleted:o,localOrigin:i}},rp=async e=>{const t=sn();if(!t)return;const n={hosts:e.hosts,defaultHostId:e.defaultHostId,initialHostChoiceCompleted:e.initialHostChoiceCompleted};e.localClientToken!==void 0&&(n.localClientToken=e.localClientToken),await t("desktop_hosts_set",{input:n})},sp=async()=>{const e=sn();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},op=async()=>{const e=sn();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},ip=8e3,ap=15e3,cp=400,lp=async(e,t,n,r)=>{const s=new AbortController,o=window.setTimeout(()=>s.abort(),n);try{return await e.fetch(t,{...r,signal:s.signal})}finally{window.clearTimeout(o)}},ua=async(e,t,n,r)=>{for(;;){const s=n-Date.now();if(s<=0)throw new Error("relay probe deadline exceeded");try{return await lp(e,t,Math.min(ip,s),r)}catch(o){if(e.getStatus().state==="error"||Date.now()>=n)throw o;await new Promise(i=>window.setTimeout(i,cp))}}},up=async(e,t)=>{const n=ii({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),r=Date.now(),s=r+ap;let o=!1;try{if(!(await ua(n,"/health",s)).ok)return{status:"unreachable",latencyMs:0};const a=new Headers({Accept:"application/json"});for(const[u,d]of Object.entries(t?.requestHeaders||{}))u.toLowerCase()!=="authorization"&&a.set(u,d);const c=t?.clientToken?.trim();c&&a.set("Authorization",`Bearer ${c}`);const l=await ua(n,"/auth/session",s,{headers:a});return l.status===401||l.status===403?{status:"auth",latencyMs:Math.max(0,Date.now()-r)}:l.ok?(o=t?.keepTunnel===!0,{status:"ok",latencyMs:Math.max(0,Date.now()-r),...o?{tunnel:n}:{}}):{status:"unreachable",latencyMs:0}}catch{return{status:"unreachable",latencyMs:0}}finally{o||n.close()}},mi=async(e,t)=>{const n=sn();if(!n)return{status:"unreachable",latencyMs:0};const r=await n("desktop_host_probe",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0,expectedServerId:t?.expectedServerId||void 0});if(!An(r))return{status:"unreachable",latencyMs:0};const s=r.status,o=s==="ok"||s==="auth"||s==="update-recommended"||s==="incompatible"||s==="wrong-service"||s==="unreachable"?s:"unreachable",i=la(r,"latencyMs")??la(r,"latency_ms")??0;return{status:o,latencyMs:i}},zv=async(e,t)=>{const n=sn();n&&await n("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},$v=async e=>{const t=sn();t&&await t("desktop_new_window_for_host",{hostId:e})},Mt="local",dp=e=>({id:Mt,label:"Local",url:e||El()}),El=()=>typeof window>"u"?"":window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,fp=e=>e.id===Mt?"local":`host:${e.id}`,Wv=e=>{const t=typeof window>"u"?"":window.location.href,n=e.find(u=>u.id===Mt)?.url||El(),r=Pn(),s=Te(n)||n,o=Te(t)||t,i=W(),a=e.find(u=>u.relay&&fp(u)===i);if(a)return{id:a.id,label:a.label,url:a.url};if(r&&Mr(r,n))return{id:Mt,label:"Local",url:s};const c=e.find(u=>r?Mr(r,Xn(u)):!1);if(c)return{id:c.id,label:c.label,url:Te(Xn(c))||Xn(c)};if(t&&Mr(t,n))return{id:Mt,label:"Local",url:s};const l=e.find(u=>t?Mr(t,u.url):!1);return l?{id:l.id,label:l.label,url:Te(l.url)||l.url}:t.startsWith("openchamber-ui://")?{id:Mt,label:"Local",url:s}:{id:"custom",label:kl(o||"Instance"),url:o}},ps=new Map;let Pl=0;const hs=new Map;let Io=0,Al={byHostId:{},isProbing:!1};const xo=new Set,ms=()=>{Al={byHostId:Object.fromEntries(ps),isProbing:Io>0};for(const e of xo)try{e()}catch{}},Gv=e=>(xo.add(e),()=>{xo.delete(e)}),qv=()=>Al,Il=(e,t)=>{ps.set(e,t),ms()},Kv=(e,t)=>{hs.set(e,++Pl),Il(e,t)},pp=e=>{const t=new Set([Mt,...e]);let n=!1;for(const r of Array.from(ps.keys()))t.has(r)||(ps.delete(r),hs.delete(r),n=!0);n&&ms()},hp=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",mp=async()=>rn()?sp().catch(()=>""):"",gp=async(e,t)=>{const n=e.id===Mt?t:e.clientToken||"",r=async()=>{const i=await up(e.relay,{clientToken:n,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0})),a={status:i.status,latencyMs:i.latencyMs};return i.status==="ok"&&(a.via="relay"),a};if(e.relay&&!e.apiUrl)return r();const s=Te(rn()?Xn(e):e.url);if(!s)return{status:"unreachable",latencyMs:0};const o=await mi(s,{clientToken:n||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(hp(o.status)&&e.relay){const i=await r();if(i.status==="ok")return i}return{status:o.status,latencyMs:o.latencyMs}},yp=async e=>{if(!Be())return;const t=++Pl;for(const n of e)hs.set(n.id,t);Io+=1,ms();try{const n=await mp();await Promise.all(e.map(async r=>{const s=await gp(r,n);hs.get(r.id)===t&&Il(r.id,s)}))}finally{Io-=1,ms()}};let da=!1;const wp=async()=>{if(da||!Be())return;da=!0;const e=await hi().catch(()=>null);e&&(pp(e.hosts.map(t=>t.id)),await yp([dp(e.localOrigin),...e.hosts]))},bp=5e3,Sp=1500;let qs=!1;const vp=async e=>{if(!rn()||qs)return;const t=`host:${e}`;if(W()===t){qs=!0;try{const n=await hi().catch(()=>null),r=n?.hosts.find(d=>d.id===e);if(!n||!r?.relay)return;const s=r.apiUrl?Te(r.apiUrl):null;if(s&&s.startsWith("https://"))return;const o=await g("/api/client-auth/connection/candidates").catch(()=>null);if(!o?.ok)return;const i=await o.json().catch(()=>null);if(!i||i.serverId!==r.relay.serverId)return;const a=Array.isArray(i.candidates)?i.candidates:[],c=[];for(const d of a){if(!d||typeof d!="object")continue;const f=d;if(f.type!=="lan"||typeof f.url!="string")continue;const p=Te(f.url);p&&!c.includes(p)&&c.push(p)}if(c.length===0)return;const l=s&&c.includes(s)?s:c[0];l!==s&&await rp({hosts:n.hosts.map(d=>d.id===e?{...d,apiUrl:l}:d),defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>{});const u=await mi(l,{clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,expectedServerId:r.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(u.status==="unreachable"||u.status==="wrong-service"||u.status==="incompatible"||W()!==t)return;ls({apiBaseUrl:l,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:t})}finally{qs=!1}}},Tp=e=>{typeof window>"u"||window.setTimeout(()=>{vp(e).catch(()=>{})},bp)},kp=async e=>{if(!rn())return;const t=await hi().catch(()=>null);if(!t)return;const n=e||(t.defaultHostId!=="local"?t.defaultHostId:null);if(!n)return;const r=t.hosts.find(d=>d.id===n);if(!r?.relay)return;const s=`host:${r.id}`;if(W()===s)return;const o=d=>{ls({apiBaseUrl:d,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:s})},i=()=>{ls({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:r.clientToken||null,runtimeKey:s,relay:r.relay??void 0}),Tp(r.id)},a=r.apiUrl?Te(Xn(r)):null;if(!a){i();return}const c=d=>d.status!=="unreachable"&&d.status!=="wrong-service"&&d.status!=="incompatible",l=mi(a,{clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,expectedServerId:r.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0})),u=await Promise.race([l,new Promise(d=>setTimeout(()=>d(null),Sp))]);if(u){if(c(u)){o(a);return}i();return}i(),l.then(d=>{c(d)&&W()===s&&o(a)})};class Xt extends Error{reason;status;constructor(t,n={}){super(t),this.name="FilesystemError",this.reason=n.reason??"unknown",this.status=n.status}}const Vv=e=>e instanceof Xt||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),gs=e=>{switch(e){case"os-permission":case"already-exists":case"not-found":case"not-directory":case"invalid-response":return e;default:return"unknown"}},fa=500,xl=()=>{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}},Jv=()=>xl(),Ge=(e,t)=>{if(!xl())return;const n=typeof performance<"u"?performance.now():Date.now();window.__OPENCHAMBER_STARTUP_TRACE_START__??=n,window.__OPENCHAMBER_STARTUP_TRACE__??=[],window.__OPENCHAMBER_STARTUP_TRACE__.push({t:Math.round(n-window.__OPENCHAMBER_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__OPENCHAMBER_STARTUP_TRACE__.length>fa&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-fa)},Ep=()=>{const e=typeof window<"u"?window.__OPENCHAMBER_STARTUP_TRACE__??[]:[],t=e.findIndex(r=>r.name==="ModelControls:ready"),n=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,n).filter(r=>r.name.includes("checkConnection")||r.name.includes("checkHealth")||r.name.includes("initializeApp")||r.name.includes("initApp")||r.name.includes("loadProviders")||r.name.includes("loadAgents")||r.name.includes("config.defaults")||r.name.includes("modelsMetadata")||r.name.includes("ModelControls")||r.name.includes("activateDirectory")||r.name.includes("opencodeClient:setDirectory"))};typeof window<"u"&&(window.__OPENCHAMBER_STARTUP_TRACE_SUMMARY__=Ep);const Yv=async(e,t,n)=>{const r=typeof performance<"u"?performance.now():Date.now();Ge(`${e}:start`,n);try{const s=await t(),o=typeof performance<"u"?performance.now():Date.now();return Ge(`${e}:end`,{durationMs:Math.round(o-r)}),s}catch(s){const o=typeof performance<"u"?performance.now():Date.now();throw Ge(`${e}:error`,{durationMs:Math.round(o-r),error:s instanceof Error?s.message:String(s)}),s}},Pp=3,Ap=3e4,Ip=32e3,xp=3600*1e3,Rp=600*1e3,Cp=200,Op=new Set([429,502,503,504]),ft=new Map,gi=e=>JSON.stringify([W(),e]);function Mp(){const e=Date.now();for(const[t,n]of ft){const r=Math.max(n.lastErrorAt,n.circuitOpenAt);e-r>xp&&ft.delete(t)}}typeof setInterval<"u"&&setInterval(Mp,Rp).unref?.();function Dp(e){const t=gi(e);let n=ft.get(t);if(!n)for(n={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:Ap},ft.set(t,n);ft.size>Cp;){const r=ft.keys().next().value;if(!r)break;ft.delete(r)}return n}function _p(e){e&&ft.delete(gi(e))}function Lp(e,t){if(!e)return;const n=Dp(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),Fp(t)&&n.consecutiveErrors>=Pp&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function Fp(e){return e!==void 0&&Op.has(e)}function Up(e){const t=ft.get(gi(e));return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,Ip*4),!1):!0:!1}function jp(e){if(!(!e||!Up(e)))throw new Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}const Rl=/^(?:\/\/\?\/)?[A-Za-z]:\/+$/u,pa=/^(?:\/\/\?\/)?[A-Za-z]:$/u,Np=/^\/\/(?:[^/?][^/]*\/[^/]+|\?\/UNC\/[^/]+\/[^/]+)$/iu,Ye=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const n=t.replace(/\\/g,"/").replace(/^([a-z]):/,(s,o)=>o.toUpperCase()+":");return n==="/"?"/":Rl.test(n)?n.replace(/\/+$/u,"/"):(n.length>1?n.replace(/\/+$/,""):n)||null},Bp=e=>{if(e==="/"||Rl.test(e)||pa.test(e)||Np.test(e))return null;const t=e.lastIndexOf("/");if(t<0)return null;if(t===0)return"/";const n=e.slice(0,t);return pa.test(n)?`${n}/`:n},Hp=e=>Ye(e)??"",zp="openchamber",$p="auto",Wp=(e,t)=>e===zp&&t===$p,Gp=it(m().min(1),T({type:N("running")})),qp=T({id:m().min(1),sessionID:m().min(1),action:m(),resources:G(m())}),Kp=T({id:m().min(1),sessionID:m().min(1),title:m()}),Vp=T({sessions:it(m().min(1),T({status:m(),lastUpdateAt:R()})),pending:it(m().min(1),T({permissions:G(qp),forms:G(Kp)})).optional(),serverTime:R()});function K(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}const Tn={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}`},Qv=e=>e==="completed"||e==="error",Cl=e=>e.role==="user"||e.role==="assistant",Xv=e=>e==="user"||e==="assistant",Zv=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n&&Cl(n))return n}},eT=e=>{if(e)for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.info&&Cl(n.info))return n}},tT=e=>e?.role==="assistant"&&e.time.completed===void 0,ha="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Jp=14;let ma=0,Ks=0;const Yp=e=>{const t=new Uint8Array(e);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(t);else for(let r=0;r<e;r+=1)t[r]=Math.floor(Math.random()*256);let n="";for(let r=0;r<e;r+=1)n+=ha[t[r]%ha.length];return n},ga=e=>{const t=Date.now();t!==ma&&(ma=t,Ks=0),Ks+=1;const n=BigInt(t)*BigInt(4096)+BigInt(Ks),r=new Uint8Array(6);for(let o=0;o<6;o+=1)r[o]=Number(n>>BigInt(40-8*o)&BigInt(255));const s=Array.from(r,o=>o.toString(16).padStart(2,"0")).join("");return`${e}_${s}${Yp(Jp)}`};function Dr(e){return K({id:e.id,parentID:e.parentID,projectID:e.projectID,directory:e.location.directory,subpath:e.subpath,title:e.title??"",agent:e.agent,model:e.model,cost:e.cost,tokens:e.tokens,outcome:e.outcome,time:K({...e.time}),metadata:e.metadata,permissions:e.permissions,revert:e.revert,fork:e.fork})}function Qp(e){return K({id:e.id,worktree:e.canonical,vcs:e.vcs,name:e.name,icon:e.icon,commands:e.commands,time:e.time,sandboxes:[...e.sandboxes]})}function Xp(e){return K({branch:e.branch.current,defaultBranch:e.branch.default})}function ya(e){return!e||e.length===0?"":e.filter(t=>t.type==="text").map(t=>t.text).join(`
|
|
3
|
+
`)}function Zp(e,t){if(!e)return;const n=e.filter(r=>r.type==="file");if(n.length!==0)return n.map((r,s)=>K({id:`${t.callID}:file:${s}`,sessionID:t.sessionID,messageID:t.messageID,type:"file",mime:r.mime,filename:r.name??void 0,url:r.uri}))}function eh(e){return e.message||e.type}function th(e,t){const n=e.time.ran??e.time.created,r=e.time.completed??n,s={sessionID:t.sessionID,messageID:t.messageID,callID:e.id};let o;switch(e.state.status){case"streaming":o={status:"pending",input:{},raw:e.state.input};break;case"running":o=K({status:"running",input:e.state.input,metadata:e.state.metadata,time:{start:n}});break;case"completed":o=K({status:"completed",input:e.state.input,output:ya(e.state.content),metadata:e.state.metadata,time:{start:n,end:r},attachments:Zp(e.state.content,s)});break;case"error":o=K({status:"error",input:e.state.input,error:eh(e.state.error),output:ya(e.state.content)||void 0,metadata:e.state.metadata,time:{start:n,end:r}});break}return K({id:Tn.tool(e.id),sessionID:t.sessionID,messageID:t.messageID,type:"tool",callID:e.id,tool:e.name,state:o,executed:e.executed})}function nh(e,t){const n=[];let r=0,s=0;for(const o of e)switch(o.type){case"text":{const i=r;r+=1,n.push({id:Tn.text(t.messageID,i),sessionID:t.sessionID,messageID:t.messageID,type:"text",text:o.text,time:K({start:t.created,end:t.completed})});break}case"reasoning":{const i=s;s+=1,n.push({id:Tn.reasoning(t.messageID,i),sessionID:t.sessionID,messageID:t.messageID,type:"reasoning",text:o.text,time:K({start:o.time?.created??t.created,end:o.time?.completed})});break}case"tool":n.push(th(o,t));break}return n}function rh(e,t){return K({id:e.id,sessionID:t,role:"assistant",time:K({...e.time}),agent:e.agent,providerID:e.model.providerID,modelID:e.model.id,variant:e.model.variant,finish:e.finish,error:e.error,cost:e.cost,tokens:e.tokens,snapshot:e.snapshot,retry:e.retry,metadata:e.metadata})}function sh(e){return e.source.type==="uri"?e.source.uri:`data:${e.mime};base64,${e.data}`}function oh(e,t){const n=[];return e.text.length>0&&n.push({id:Tn.userText(t.messageID),sessionID:t.sessionID,messageID:t.messageID,type:"text",text:e.text,time:{start:t.created,end:t.created}}),e.files?.forEach((r,s)=>{n.push(K({id:Tn.userFile(t.messageID,s),sessionID:t.sessionID,messageID:t.messageID,type:"file",mime:r.mime,filename:r.name,url:sh(r)}))}),e.agents?.forEach((r,s)=>{n.push({id:Tn.userAgent(t.messageID,s),sessionID:t.sessionID,messageID:t.messageID,type:"agent",name:r.name})}),n}function ih(e,t){const n=e.metadata;switch(e.type){case"user":return{message:K({id:e.id,sessionID:t,role:"user",time:{...e.time},metadata:n}),parts:oh(e,{sessionID:t,messageID:e.id,created:e.time.created})};case"assistant":return{message:rh(e,t),parts:nh(e.content,{sessionID:t,messageID:e.id,created:e.time.created,completed:e.time.completed})};case"synthetic":return{message:K({id:e.id,sessionID:t,role:"synthetic",time:{...e.time},text:e.text,description:e.description,metadata:n}),parts:[]};case"system":return{message:K({id:e.id,sessionID:t,role:"system",time:{...e.time},text:e.text,description:e.description,metadata:n}),parts:[]};case"skill":return{message:K({id:e.id,sessionID:t,role:"skill",time:{...e.time},skill:e.skill,name:e.name,text:e.text,metadata:n}),parts:[]};case"shell":return{message:K({id:e.id,sessionID:t,role:"shell",time:K({...e.time}),shellID:e.shellID,command:e.command,status:e.status,exit:ah(e.exit),output:e.output,metadata:n}),parts:[]};case"compaction":return{message:K({id:e.id,sessionID:t,role:"compaction",time:{...e.time},status:e.status,reason:e.reason,summary:e.status==="failed"?"":e.summary,error:e.status==="failed"?e.error:void 0,cost:e.status==="running"?void 0:e.cost,tokens:e.status==="running"?void 0:e.tokens,metadata:n}),parts:[]};case"agent-switched":return{message:K({id:e.id,sessionID:t,role:"agent-switched",time:{...e.time},agent:e.agent,previous:e.previous,metadata:n}),parts:[]};case"model-switched":return{message:K({id:e.id,sessionID:t,role:"model-switched",time:{...e.time},model:e.model,previous:e.previous,metadata:n}),parts:[]};case"location-switched":return{message:K({id:e.id,sessionID:t,role:"location-switched",time:{...e.time},directory:e.location.directory,previous:e.previous?.location.directory,metadata:n}),parts:[]};case"idle":return{message:K({id:e.id,sessionID:t,role:"idle",time:{...e.time},outcome:e.outcome,metadata:n}),parts:[]}}}function ah(e){return e==="Infinity"||e==="-Infinity"||e==="NaN"?void 0:e}function wa(e,t){return e.map(n=>ih(n,t))}const ch=e=>e.type==="document";function lh(e){const t={};for(const n of e)if(ch(n))for(const[r,s]of Object.entries(n.info)){if(s===void 0)continue;const o=t[r];t[r]=ba(o)&&ba(s)?{...o,...s}:s}return t}function ba(e){return Object.prototype.toString.call(e)==="[object Object]"}const uh=e=>({...e,name:e.id,displayName:e.name}),Sa="/api",dh=1e4,fh=4e3,ph=100,hh=new Map([["InvalidRequestError",400],["InvalidCursorError",400],["FormInvalidAnswerError",400],["UnauthorizedError",401],["ForbiddenError",403],["SessionNotFoundError",404],["MessageNotFoundError",404],["PermissionNotFoundError",404],["FormNotFoundError",404],["AgentNotFoundError",404],["CommandNotFoundError",404],["SkillNotFoundError",404],["ProviderNotFoundError",404],["McpServerNotFoundError",404],["ProjectNotFoundError",404],["FileNotFoundError",404],["PtyNotFoundError",404],["ShellNotFoundError",404],["ConflictError",409],["SessionBusyError",409],["FormAlreadySettledError",409],["ServiceUnavailableError",503],["UnknownError",500]]);class ut extends Error{operation;status;tag;detail;ref;constructor(t,n,r){super(`${t} failed${r.status?` (${r.status})`:""}: ${n}`,{cause:r.cause}),this.name="OpencodeApiError",this.operation=t,this.status=r.status,this.tag=r.tag,this.detail=n,this.ref=r.ref}}const mh=T({_tag:m(),message:m().optional(),ref:m().optional()});function gh(e,t){if(t instanceof ut)return t;if(t instanceof Yu){if(t.reason==="UnexpectedStatus"){const s=t.cause?.status;return new ut(e,"unexpected status",{status:typeof s=="number"?s:void 0,cause:t})}const r=new ut(e,t.reason==="Transport"?"transport failure":t.reason,{cause:t.cause??t});return t.reason==="Transport"&&Vi(t.cause)&&bo(r),r}const n=mh.safeParse(t);if(n.success)return new ut(e,n.data.message??n.data._tag,{status:hh.get(n.data._tag),tag:n.data._tag,ref:n.data.ref,cause:t});if(t instanceof Error){const r=new ut(e,t.message,{cause:t});return Vi(t)&&bo(r),r}return new ut(e,String(t),{cause:t})}const yh=e=>e.tag==="InvalidRequestError"&&e.detail.startsWith("Skill not found"),wh=e=>e instanceof ut&&e.status===404;async function O(e,t){try{return await t()}catch(n){throw gh(e,n)}}const bh=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,va=e=>{const t=typeof e=="string"&&e.trim().length>0?e.trim():"/api";if(bh.test(t)||typeof window>"u")return t;const n=window.location?.href||window.location?.origin;if(!n)return t;try{return new URL(t,n).toString()}catch(r){return console.warn("Failed to normalize OpenCode base URL:",r),t}},Ta=()=>{try{return Pe().api("/api")}catch{return null}},Ol=e=>{const t=typeof AbortSignal<"u"?AbortSignal:void 0;if(typeof t?.timeout=="function")return{signal:t.timeout(e),cleanup:()=>{}};const n=new AbortController,r=setTimeout(()=>n.abort(),e);return{signal:n.signal,cleanup:()=>clearTimeout(r)}},Sh=3e4,vh=e=>e.pathname.endsWith("/event")||e.pathname.endsWith("/log"),Th="x-opencode-directory",kh=e=>e.replace(/\/api\/*$/,"")||"/",Vs=e=>{const t=e.requestTimeoutMs??Sh;return Ju.make({baseUrl:kh(e.baseUrl),headers:e.directory?{[Th]:encodeURIComponent(e.directory)}:void 0,fetch:async(n,r)=>{const s=n instanceof URL?n:new URL(typeof n=="string"?n:n.url),o=String(r?.method??(n instanceof Request?n.method:"GET")).toUpperCase();if(vh(s)||o==="POST")return g(n,r);const i=Ol(t),a=r?.signal!==void 0?r.signal:n instanceof Request?n.signal:void 0,c=typeof AbortSignal<"u"&&typeof AbortSignal.any=="function";let l,u=null;if(a&&c)l=AbortSignal.any([a,i.signal]);else if(a){const p=new AbortController,y=()=>p.abort(a.reason),b=()=>p.abort(i.signal.reason);a.aborted?y():i.signal.aborted?b():(a.addEventListener("abort",y,{once:!0}),i.signal.addEventListener("abort",b,{once:!0}),u=()=>{a.removeEventListener("abort",y),i.signal.removeEventListener("abort",b)}),l=p.signal}else l=i.signal;const d=()=>{u?.(),i.cleanup()};let f=!1;try{const p=await g(n,{...r,signal:l});return f=p.body!==null,p}catch(p){throw i.signal.aborted&&!a?.aborted?new Error(`OpenCode request timed out after ${t}ms`):p}finally{!f||l.aborted?d():l.addEventListener("abort",d,{once:!0})}}})},Eh=T({reason:m().optional(),isDirectory:Ne().optional()}),ln=e=>e.replace(/\\/g,"/"),ka=400,Ea=()=>{const e=As();return e&&e.runtime?.isDesktop&&e.files?e.files:null},_r=m().trim().regex(/^(?:\/|[A-Za-z]:[\\/]|\\\\)/),Ph=T({home:_r,chatsRoot:_r.optional(),canonicalChatsRoot:_r.optional(),canonicalLegacyChatsRoot:_r.optional()}),Js=e=>JSON.parse(JSON.stringify(e)),Pa=e=>K({previous:e.previous??void 0,next:e.next??void 0}),Aa=e=>{const t=[],n=new Set;for(const r of e)for(const s of r)!s?.id||n.has(s.id)||(n.add(s.id),t.push(s));return t};class Ah{client;baseUrl;scopedClients=new Map;currentDirectory=void 0;directoryContextQueue=Promise.resolve();listDirectoryInFlight=new Map;providerCatalogInFlight=new Map;listAgentsInFlight=new Map;configInFlight=new Map;configCache=new Map;configCacheGeneration=0;listDirectoryCache=new Map;constructor(t=Sa){const r=Ta()||t;this.baseUrl=va(r),this.client=Vs({baseUrl:this.baseUrl})}assertRuntimeUnchanged(t){if(t&&t!==W())throw new Error("Message was not sent because the runtime changed.")}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){const t=Ta(),n=va(t||Sa);this.baseUrl=n,this.client=Vs({baseUrl:this.baseUrl}),this.scopedClients.clear(),this.listDirectoryInFlight.clear(),this.providerCatalogInFlight.clear(),this.listAgentsInFlight.clear(),this.clearConfigCache(),this.listDirectoryCache.clear()}getSdkClient(){return this.client}getScopedSdkClient(t){const n=this.normalizeCandidatePath(t)??t,r=n||"",s=this.scopedClients.get(r);if(s)return s;const o=Vs({baseUrl:this.baseUrl,directory:n});return this.scopedClients.set(r,o),o}clientFor(t){const n=this.resolveDirectory(t);return n?this.getScopedSdkClient(n):this.client}resolveDirectory(t){return this.normalizeCandidatePath(t)??this.currentDirectory}normalizeCandidatePath(t){return Ye(t)}deriveHomeDirectory(t){const n=t.match(/^([A-Za-z]:)(?:\/|$)/);if(n){const o=n[1],a=t.slice(o.length+(t.charAt(o.length)==="/"?1:0)).split("/").filter(Boolean);return a.length>=2?{homeDirectory:`${o}/${a[0]}/${a[1]}`,username:a[1]}:a.length===1?{homeDirectory:`${o}/${a[0]}`,username:a[0]}:{homeDirectory:`${o}/`,username:void 0}}const r=t.startsWith("/"),s=t.split("/").filter(Boolean);return s.length>=2&&(s[0]==="Users"||s[0]==="home")?{homeDirectory:`${r?"/":""}${s[0]}/${s[1]}`,username:s[1]}:r?s.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${s.join("/")}`,username:s[s.length-1]}:s.length>0?{homeDirectory:`/${s.join("/")}`,username:s[s.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(t){const n=this.normalizeCandidatePath(t)??t;this.currentDirectory!==n&&Ge("opencodeClient:setDirectory",{previous:this.currentDirectory??null,next:n??null}),this.currentDirectory=n}getDirectory(){return this.currentDirectory}async withDirectory(t,n){const r=async()=>{if(t==null)return n();const o=this.currentDirectory,i=this.normalizeCandidatePath(t)??t;this.currentDirectory=i;try{return await n()}finally{this.currentDirectory===i&&(this.currentDirectory=o)}},s=this.directoryContextQueue.then(r,r);return this.directoryContextQueue=s.then(()=>{},()=>{}),s}async getLocation(t){return O("location.get",()=>this.clientFor(t).location.get())}async listProjects(){return(await O("project.list",()=>this.client.project.list())).map(Qp)}async getCurrentProject(t){return(await O("location.get",()=>this.clientFor(t).location.get())).project}async getVcs(t){return O("vcs.get",()=>this.clientFor(t).vcs.get().then(n=>Xp(n.data)))}async getSystemInfo(){const t=new Set,n=s=>{const o=this.normalizeCandidatePath(s);o&&t.add(o)};try{const s=await this.getLocation();n(s.directory),n(s.project.directory)}catch(s){console.debug("Failed to load location info:",s)}if(!t.size)try{(await this.listSessions()).forEach(o=>n(o.directory))}catch(s){console.debug("Failed to inspect sessions for system info:",s)}if(n(this.currentDirectory),typeof window<"u")try{n(window.localStorage.getItem("lastDirectory")),n(window.localStorage.getItem("homeDirectory"))}catch{}if(!t.size&&typeof process<"u"&&typeof process.cwd=="function"&&n(process.cwd()),!t.size)return{homeDirectory:"/",username:void 0};const[r]=Array.from(t);return this.deriveHomeDirectory(r)}async probeDirectory(t){return await this.getDirectoryAvailability(t)==="available"}async getDirectoryAvailability(t){const n=this.normalizeCandidatePath(t);if(!n)return"unknown";try{const r=await g("/api/fs/directory-stat",{query:{path:n}}),s=Eh.safeParse(await r.json().catch(()=>null)).data;if(r.ok&&s?.isDirectory===!0)return"available";const o=gs(s?.reason);return o==="not-found"||o==="not-directory"?"missing":"unknown"}catch{return"unknown"}}async listSessionsPage(t={}){const n=t.global?void 0:this.resolveDirectory(t.directory),r=n?this.getScopedSdkClient(n):this.client,s=await O("session.list",()=>r.session.list({directory:n,limit:t.limit??ph,order:t.order,search:t.search,cursor:t.cursor,parentID:t.parentID}));return{sessions:s.data.map(Dr),cursor:Pa(s.cursor)}}async listSessions(t){return(await this.listSessionsPage({directory:t})).sessions}async createSession(t,n){const r=this.resolveDirectory(n),s=await O("session.create",()=>this.clientFor(n).session.create({id:t?.id,title:t?.title,agent:t?.agent,model:t?.model&&Wp(t.model.providerID,t.model.id)?void 0:t?.model,location:r?{directory:r}:void 0,metadata:t?.metadata}));return Dr(s)}async getSession(t,n){const r=await O("session.get",()=>this.clientFor(n).session.get({sessionID:t}));return Dr(r)}async deleteSession(t,n){return await O("session.remove",()=>this.clientFor(n).session.remove({sessionID:t})),!0}async renameSession(t,n,r){await O("session.update",()=>this.clientFor(r).session.update({sessionID:t,title:n}))}async moveSession(t,n,r){const s=this.normalizeCandidatePath(n)??n;await O("session.move",()=>this.client.session.move({sessionID:t,directory:s,delivery:r?.delivery}))}async switchSessionModel(t,n,r){await O("session.switchModel",()=>this.clientFor(r).session.switchModel({sessionID:t,model:n}))}async switchSessionAgent(t,n,r){await O("session.switchAgent",()=>this.clientFor(r).session.switchAgent({sessionID:t,agent:n}))}async getSessionMessages(t,n,r){const s=await O("message.list",()=>this.clientFor(r).message.list({sessionID:t,limit:n?.limit,cursor:n?.cursor,order:n?.cursor?void 0:n?.order})),o=wa(s.data,t).map(({message:a,parts:c})=>({info:a,parts:c})),i=n?.limit!==void 0&&o.length<n.limit;return{items:o,cursor:Pa({...s.cursor,next:i?void 0:s.cursor.next})}}async getSessionMessage(t,n,r){const s=await O("session.message.get",()=>this.clientFor(r).session.message.get({sessionID:t,messageID:n})),[o]=wa([s],t);return{info:o.message,parts:o.parts}}shouldNormalizeToTextPlain(t){if(!t)return!1;const n=t.toLowerCase();return n.startsWith("text/")&&n!=="text/plain"?!0:["application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/x-shellscript","application/octet-stream","image/svg+xml"].includes(n)}isHeicMime(t){if(!t)return!1;const n=t.toLowerCase();return n==="image/heic"||n==="image/heif"}async convertHeicToJpeg(t){try{const n=(await ni(async()=>{const{default:d}=await import("./vendor-heic2any-CEam9pDc.js").then(f=>f.h);return{default:d}},__vite__mapDeps([0,1,2]))).default,r=t.url.indexOf(",");if(r===-1)return t;const s=t.url.substring(r+1),o=atob(s),i=new Uint8Array(o.length);for(let d=0;d<o.length;d++)i[d]=o.charCodeAt(d);const a=new Blob([i],{type:t.mime}),c=await n({blob:a,toType:"image/jpeg",quality:.9}),l=await new Promise((d,f)=>{const p=new FileReader;p.onload=()=>d(p.result),p.onerror=f,p.readAsDataURL(c)});let u=t.filename;return u&&(u=u.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:u,url:l}}catch(n){return console.warn("Failed to convert HEIC to JPEG:",n),t}}async normalizeFilePart(t){if(this.isHeicMime(t.mime))return this.convertHeicToJpeg(t);if(!this.shouldNormalizeToTextPlain(t.mime))return t;let n=t.url;if(t.url.startsWith("data:")){const r=t.url.indexOf(",");if(r!==-1){const s=t.url.substring(5,r),o=t.url.substring(r);n=`data:${s.replace(/^[^;,]+/,"text/plain")}${o}`}}return{mime:"text/plain",filename:t.filename,url:n}}async toPromptFile(t){const n=await this.normalizeFilePart(t);return{uri:n.url,name:n.filename}}async applySendSelection(t,n,r,s){n.model&&(this.assertRuntimeUnchanged(s),await this.switchSessionModel(t,n.model,r)),n.agent&&(this.assertRuntimeUnchanged(s),await this.switchSessionAgent(t,n.agent,r))}async sendMessage(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=t.messageId??ga("msg"),r=await Promise.all((t.files??[]).map(a=>this.toPromptFile(a))),s=(t.agentMentions??[]).filter(a=>!!a?.name).map(a=>({name:a.name,mention:a.source?{start:a.source.start,end:a.source.end,text:a.source.value}:void 0}));if(!t.text.trim()&&r.length===0&&(t.context?.length??0)===0)throw new Error("Message must have at least one part (text or file)");jp(t.providerID);const o=async a=>{this.assertRuntimeUnchanged(t.runtimeKey),await O("session.synthetic",()=>this.clientFor(t.directory).session.synthetic({sessionID:t.id,text:a.text,description:a.description,metadata:a.metadata?Js(a.metadata):void 0,delivery:t.delivery,resume:!1}))},i=a=>(this.assertRuntimeUnchanged(t.runtimeKey),O("session.prompt",()=>this.clientFor(t.directory).session.prompt({sessionID:t.id,id:n,text:t.text,files:r.length>0?r:void 0,agents:s.length>0?s:void 0,skills:a.length>0?a.map(c=>({id:c.id})):void 0,metadata:t.metadata,delivery:t.delivery})));try{await this.applySendSelection(t.id,{model:t.model,agent:t.agent},t.directory,t.runtimeKey);const a=await this.resolveSkillMentions(t.skills?.names??[],t.directory),c=t.skills?.instructionFor(a.unresolved)??null;for(const l of t.context??[])l.text.trim()&&await o(l);c&&await o({text:c});try{await i(a.attached)}catch(l){if(a.attached.length===0||!(l instanceof ut)||!yh(l))throw l;const u=t.skills?.instructionFor(a.attached.map(d=>d.name))??null;u&&await o({text:u}),await i([])}}catch(a){throw Lp(t.providerID,a instanceof ut?a.status:void 0),a}return _p(t.providerID),n}async sendCommand(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=await Promise.all((t.files??[]).map(r=>this.toPromptFile(r)));await this.applySendSelection(t.id,{model:t.model,agent:t.agent},t.directory,t.runtimeKey);for(const r of t.context??[])r.text.trim()&&(this.assertRuntimeUnchanged(t.runtimeKey),await O("session.synthetic",()=>this.clientFor(t.directory).session.synthetic({sessionID:t.id,text:r.text,description:r.description,metadata:r.metadata?Js(r.metadata):void 0,delivery:t.delivery,resume:!1})));this.assertRuntimeUnchanged(t.runtimeKey),await O("session.command",()=>this.clientFor(t.directory).session.command({sessionID:t.id,name:t.command,text:t.arguments??"",files:n.length>0?n:void 0,delivery:t.delivery}))}async abortSession(t,n){return(await O("session.interrupt",()=>this.clientFor(n).session.interrupt({sessionID:t}))).interrupted}async shellSession(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=t.messageId??ga("msg");return await O("session.shell",()=>this.clientFor(t.directory).session.shell({sessionID:t.sessionId,id:n,command:t.command})),n}async stageRevert(t,n,r){return O("session.revert.stage",()=>this.clientFor(r?.directory).session.revert.stage({sessionID:t,messageID:n,files:r?.files}))}async commitRevert(t,n){await O("session.revert.commit",()=>this.clientFor(n).session.revert.commit({sessionID:t}))}async clearRevert(t,n){await O("session.revert.clear",()=>this.clientFor(n).session.revert.clear({sessionID:t}))}async compactSession(t,n){await O("session.compact",()=>this.clientFor(n).session.compact({sessionID:t}))}async forkSession(t,n){const r=await O("session.fork",()=>this.clientFor(n?.directory).session.fork({sessionID:t,before:n?.before}));return Dr(r)}async getActiveSessionStatuses(){try{const t=Gp.parse(await O("session.active",()=>this.client.session.active())),n={};for(const r of Object.keys(t))n[r]={type:"busy"};return n}catch{return null}}async getHostSessionStatusSnapshot(){try{const t=await g("/api/sessions/status",{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=Vp.safeParse(await t.json().catch(()=>null));return n.success?n.data:null}catch{return null}}async getWebServerSessionActivity(){try{const t=await g("/api/session-activity",{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=await t.json().catch(()=>null);return!n||typeof n!="object"?null:n}catch{return null}}async generateSessionText(t,n,r){return(await O("session.generate",()=>this.clientFor(r).session.generate({sessionID:t,prompt:n}))).text}async getSessionTurnDiff(t,n){const{from:r,to:s,context:o}=n??{},i={sessionID:t,from:r,to:s,context:o};return[...await O("session.diff",()=>this.clientFor(n?.directory).session.diff(i))]}async generateText(t,n){return(await O("generate.text",()=>this.clientFor(n?.directory).generate.text({prompt:t,model:n?.model}))).text}async replyToPermission(t,n,r,s){return await O("permission.reply",()=>this.clientFor(s?.directory).permission.reply({sessionID:t,requestID:n,decision:r,message:s?.message})),!0}async createPermission(t,n,r,s){try{const o=await O("permission.create",()=>this.clientFor(s?.directory).permission.create({sessionID:t,action:n,resources:r,id:s?.id,save:s?.save,metadata:s?.metadata?Js(s.metadata):void 0,source:s?.source,agent:s?.agent}));return{id:o.id,effect:o.effect}}catch{return null}}async fetchPermission(t,n,r){try{return{state:"ok",permission:await O("permission.get",()=>this.clientFor(r).permission.get({sessionID:t,requestID:n}))}}catch(s){return wh(s)?{state:"resolved"}:{state:"unknown"}}}async listPendingPermissions(t){const n=this.uniqueDirectories(t?.directories,t?.includeGlobal),r=await Promise.all(n.map(s=>O("permission.request.list",()=>(s?this.getScopedSdkClient(s):this.client).permission.request.list().then(o=>o.data))));return Aa(r)}async replyToForm(t,n,r,s){return await O("session.form.reply",()=>this.clientFor(s).session.form.reply({sessionID:t,formID:n,answer:r})),!0}async cancelForm(t,n,r){return await O("session.form.cancel",()=>this.clientFor(r).session.form.cancel({sessionID:t,formID:n})),!0}async listPendingForms(t){const n=this.uniqueDirectories(t?.directories,t?.includeGlobal),r=await Promise.all(n.map(s=>O("form.list",()=>(s?this.getScopedSdkClient(s):this.client).form.list().then(o=>o.data))));return Aa(r)}uniqueDirectories(t,n=!0){const r=new Set;for(const s of t??[]){const o=this.normalizeCandidatePath(s);o&&r.add(o)}return n?[null,...r]:[...r]}clearConfigCache(){this.configCacheGeneration+=1,this.configInFlight.clear(),this.configCache.clear()}async getConfig(t){const n=this.resolveDirectory(t),r=n??"",s=this.configCache.get(r);if(s&&s.expiresAt>Date.now())return Ge("opencodeClient.getConfig:cacheHit",{directory:n??null}),s.config;const o=this.configInFlight.get(r);if(o)return Ge("opencodeClient.getConfig:deduped",{directory:n??null}),o;const i=this.configCacheGeneration,a=(async()=>{Ge("opencodeClient.getConfig:start",{directory:n??null});const c=typeof performance<"u"?performance.now():Date.now(),l=await O("config.get",()=>this.clientFor(n).config.get()),u=lh(l),d=typeof performance<"u"?performance.now():Date.now();return Ge("opencodeClient.getConfig:end",{directory:n??null,durationMs:Math.round(d-c)}),i===this.configCacheGeneration&&this.configCache.set(r,{config:u,expiresAt:Date.now()+dh}),u})();this.configInFlight.set(r,a);try{return await a}finally{this.configInFlight.get(r)===a&&this.configInFlight.delete(r)}}async getProviders(){return this.getProvidersForConfig(this.currentDirectory)}async getProvidersForConfig(t){const n=this.resolveDirectory(t),r=n??"",s=this.providerCatalogInFlight.get(r);if(s)return s;const o=(async()=>{const i=this.clientFor(n),[a,c,l]=await Promise.all([O("provider.list",()=>i.provider.list().then(u=>u.data)),O("model.list",()=>i.model.list().then(u=>u.data)),O("model.default",()=>i.model.default().then(u=>u.data)).catch(()=>{})]);return K({providers:a,models:c,default:l?{id:l.modelID,providerID:l.providerID}:void 0})})();this.providerCatalogInFlight.set(r,o);try{return await o}finally{this.providerCatalogInFlight.get(r)===o&&this.providerCatalogInFlight.delete(r)}}async listAgents(t){const n=this.resolveDirectory(t),r=n??"",s=this.listAgentsInFlight.get(r);if(s)return s;const o=O("agent.list",()=>this.clientFor(n).agent.list().then(i=>i.data.map(uh)));this.listAgentsInFlight.set(r,o);try{return await o}finally{this.listAgentsInFlight.get(r)===o&&this.listAgentsInFlight.delete(r)}}async listCommands(t,n){return O("command.list",()=>this.clientFor(t).command.list(void 0,{signal:n}).then(r=>r.data))}async listSkills(t){return O("skill.list",()=>this.clientFor(t).skill.list().then(n=>n.data))}async resolveSkillMentions(t,n){if(t.length===0)return{attached:[],unresolved:[]};let r;try{r=await this.listSkills(n)}catch(i){return console.warn("[opencode] Could not list skills; naming them in an instruction instead:",i),{attached:[],unresolved:[...t]}}const s=[],o=[];for(const i of t){const a=r.find(c=>c.name===i)??r.find(c=>c.id===i);a?s.some(c=>c.id===a.id)||s.push({id:a.id,name:i}):o.push(i)}return{attached:s,unresolved:o}}async listMcpServers(t){return O("mcp.list",()=>this.clientFor(t).mcp.list().then(n=>n.data))}async connectMcpServer(t,n){await O("mcp.connect",()=>this.clientFor(n).mcp.connect({server:t}))}async disconnectMcpServer(t,n){await O("mcp.disconnect",()=>this.clientFor(n).mcp.disconnect({server:t}))}async checkHealth(){try{const t=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl,n=t==="/api"||t.endsWith("/api")?"/api/opencode/health":`${t}/opencode/health`;Ge("opencodeClient.checkHealth:url",{baseUrl:this.baseUrl,healthUrl:n});const r=Ol(fh),s=await g(n,{signal:r.signal}).finally(r.cleanup);if(Ge("opencodeClient.checkHealth:response",{status:s.status}),!s.ok)return!1;const o=await s.json();return Ge("opencodeClient.checkHealth:result",{healthy:o?.healthy}),o?.healthy===!0}catch{return!1}}async createDirectory(t,n){const r=Ea();if(r?.createDirectory)try{return await r.createDirectory(t)}catch(a){const c=a instanceof Error?a.message:String(a);throw new Error(c||"Failed to create directory")}if(n?.asProject){const a=await g(`${this.baseUrl}/opencode/directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,create:!0})});if(!a.ok){const l=await a.json().catch(()=>({error:"Failed to create project directory"}));throw new Error(l.error||"Failed to create project directory")}return{success:!0,path:(await a.json()).path}}const s={path:t,...n?.allowOutsideWorkspace?{allowOutsideWorkspace:!0}:{}},o=await g(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!o.ok){const a=await o.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await o.json()}async cloneRepository(t){const n=await g(`${this.baseUrl}/fs/clone`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to clone repository"}));throw new Error(r.error||"Failed to clone repository")}return await n.json()}async listLocalDirectory(t,n){const s=`${typeof t=="string"?ln(t.trim()):""}|${n?.respectGitignore?"1":"0"}`,o=Date.now(),i=this.listDirectoryCache.get(s);if(i&&i.expiresAt>o)return i.entries;const a=this.listDirectoryInFlight.get(s);if(a)return a;const l=(async()=>{const u=Ea();try{if(u){const w=await u.listDirectory(t||"",n);if(!w||!Array.isArray(w.entries))throw new Xt("Directory listing returned an invalid response",{reason:"invalid-response"});const E=w.entries.map(k=>({name:k.name,path:ln(k.path),isDirectory:!!k.isDirectory,isFile:!k.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(s,{entries:E,expiresAt:Date.now()+ka}),E}const d=new URLSearchParams;t&&t.trim().length>0&&d.set("path",t),n?.respectGitignore&&d.set("respectGitignore","true");const f=d.toString(),p=await g(`${this.baseUrl}/fs/list${f?`?${f}`:""}`);if(!p.ok){const w=await p.json().catch(()=>({})),E=typeof w.error=="string"?w.error:"Failed to list directory";throw new Xt(E,{reason:gs(w.reason),status:p.status})}const y=await p.json();if(!y||!Array.isArray(y.entries))throw new Xt("Directory listing returned an invalid response",{reason:"invalid-response"});const b=y.entries;return this.listDirectoryCache.set(s,{entries:b,expiresAt:Date.now()+ka}),b}catch(d){throw console.error("Failed to list directory contents:",d),d}})().finally(()=>{this.listDirectoryInFlight.get(s)===l&&this.listDirectoryInFlight.delete(s)});return this.listDirectoryInFlight.set(s,l),l}async searchFiles(t,n){const r=this.resolveDirectory(n?.directory),s=r?ln(r):null;try{return(await O("file.find",()=>this.clientFor(r).file.find({query:t,limit:n?.limit!==void 0&&Number.isFinite(n.limit)?n.limit:void 0,type:n?.type}))).data.map(i=>{const a=ln(i.path),c=a.split("/").filter(Boolean).pop()||a,l=ln(s?`${s}/${a}`:a);return{name:c,path:l,relativePath:a,extension:c.includes(".")?c.split(".").pop()?.toLowerCase():void 0}})}catch(o){throw console.error("Failed to search files:",o),o}}async getFilesystemHome(){const t=W();if(!t||t==="local"){const n=await Zc();if(n)return n}try{const n=await g(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!n.ok){const s=await n.json().catch(()=>({})),o=typeof s.error=="string"&&s.error.length>0?s.error:"Failed to resolve home directory";throw new Error(o)}const r=await n.json();return r&&typeof r.home=="string"&&r.home.length>0?r.home:null}catch(n){return console.warn("Failed to resolve filesystem home directory:",n),null}}async getFilesystemHomeInfo(){const t=await g(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to resolve the chats root (${t.status})`);return Ph.parse(await t.json())}async setOpenCodeWorkingDirectory(t){if(!t||typeof t!="string"||!t.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",t),null;const n=`${this.baseUrl}/opencode/directory`;try{const r=await g(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})}),s=await r.json().catch(()=>null);if(!r.ok){const o=s??{},i=typeof o.error=="string"&&o.error.length>0?o.error:"Failed to update OpenCode working directory";throw new Error(i)}return s&&typeof s=="object"?s:{success:!0,restarted:!1,path:t}}catch(r){throw console.warn("Failed to update OpenCode working directory:",r),r}}}const rt=new Ah;let Ys=null,Qs=null,Xs=null;const Ia=new Set;let xa=!1;const Ml=e=>{if(Ia.add(e),xa||typeof window>"u")return;xa=!0;const t=()=>{for(const n of Ia)n()};try{window.addEventListener("pagehide",t,{capture:!0}),window.addEventListener("beforeunload",t,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&t()}),document.addEventListener("freeze",t))}catch{}},Ih=(e,t)=>{let n;try{n=e()}catch{return}const r=new Map,s=new Set;let o;const i=()=>{if(o=void 0,r.size===0&&s.size===0)return;const c=Array.from(r.entries()),l=Array.from(s);r.clear(),s.clear();for(const[u,d]of c)try{n.setItem(u,JSON.stringify(d,t?.replacer))}catch(f){console.error("Failed to persist deferred storage value",f),!r.has(u)&&!s.has(u)&&r.set(u,d)}for(const u of l)try{n.removeItem(u)}catch(d){console.error("Failed to remove deferred storage value",d),r.has(u)||s.add(u)}},a=()=>{o===void 0&&(o=setTimeout(i,0))};return Ml(i),{getItem:c=>{if(r.has(c))return r.get(c)??null;if(s.has(c))return null;const l=d=>{if(d===null)return null;try{return JSON.parse(d,t?.reviver)}catch{try{n.removeItem(c)}catch{}return null}},u=n.getItem(c);return u instanceof Promise?u.then(l):l(u)},setItem:(c,l)=>{r.set(c,l),s.delete(c),a()},removeItem:c=>{r.delete(c),s.add(c),a()}}},yi=e=>Ih(()=>Ll(),e),xh=e=>{const t=new Map,n=new Set;let r;const s=()=>{if(r=void 0,t.size===0&&n.size===0)return;const i=Array.from(t.entries()),a=Array.from(n);t.clear(),n.clear();for(const[c,l]of i)try{e.setItem(c,l)}catch(u){console.error("Failed to persist deferred storage value",u),!t.has(c)&&!n.has(c)&&t.set(c,l)}for(const c of a)try{e.removeItem(c)}catch(l){console.error("Failed to remove deferred storage value",l),t.has(c)||n.add(c)}},o=()=>{r===void 0&&(r=setTimeout(s,0))};return Ml(s),{getItem:i=>t.has(i)?t.get(i)??null:n.has(i)?null:e.getItem(i),setItem:(i,a)=>{t.set(i,a),n.delete(i),o()},removeItem:i=>{t.delete(i),n.add(i),o()},clear:()=>{t.clear(),n.clear(),r!==void 0&&(clearTimeout(r),r=void 0),e.clear()},key:i=>e.key(i),get length(){return e.length}}},Dl=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},wi=()=>{const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)},clear:()=>{e.clear()},key:t=>Array.from(e.keys())[t]??null,get length(){return e.size}}},_l=e=>{const t=wi(),n=new Set,r=new Set,s=l=>{if(r.has(l))return null;if(n.has(l))return t.getItem(l);try{return e.getItem(l)}catch{return null}},o=(l,u)=>{try{e.setItem(l,u),t.removeItem(l),n.delete(l),r.delete(l);return}catch{try{e.removeItem(l)}catch{}}t.setItem(l,u),n.add(l),r.delete(l)},i=l=>{try{e.removeItem(l),r.delete(l)}catch{r.add(l)}t.removeItem(l),n.delete(l)},a=()=>{const l=[];try{for(let u=0;u<e.length;u+=1){const d=e.key(u);d&&l.push(d)}}catch{}try{e.clear(),r.clear()}catch{for(const u of l)r.add(u)}t.clear(),n.clear()},c=()=>{const l=new Set;try{for(let u=0;u<e.length;u+=1){const d=e.key(u);d&&!r.has(d)&&!n.has(d)&&l.add(d)}}catch{}for(const u of n)l.add(u);return[...l]};return{getItem:s,setItem:o,removeItem:i,clear:a,key:l=>c()[l]??null,get length(){return c().length}}},Rh=()=>{const e=Dl("localStorage");return e?_l(e):wi()},Ll=()=>(Ys||(Ys=Rh()),Ys),gr=()=>(Xs||(Xs=xh(Ll())),Xs),Ch=()=>{const e=Dl("sessionStorage");return e?_l(e):wi()},Oh=()=>(Qs||(Qs=Ch()),Qs),Mh={markdown:"0.875rem",code:"0.75rem",uiHeader:"0.875rem",uiLabel:"0.84375rem",meta:"0.8125rem",micro:"0.8125rem",settingsPageTitle:"1.0625rem"},nT={markdown:"0.8438rem",code:"0.8125rem",uiHeader:"0.8438rem",uiLabel:"0.7813rem",meta:"0.7813rem",micro:"0.75rem",settingsPageTitle:"1rem"};function Ra(e){return`--text-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Lr={semanticMarkdown:{fontSize:"var(--text-markdown)"},semanticCode:{fontSize:"var(--text-code)"},uiHeader:{fontSize:"var(--text-ui-header)"},uiLabel:{fontSize:"var(--text-ui-label)"},meta:{fontSize:"var(--text-meta)"},micro:{fontSize:"var(--text-micro)"},ui:{button:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-line-height)",letterSpacing:"var(--ui-button-letter-spacing)",fontWeight:"var(--ui-button-font-weight)"},buttonSmall:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-button-small-line-height)",letterSpacing:"var(--ui-button-small-letter-spacing)",fontWeight:"var(--ui-button-small-font-weight)"},buttonLarge:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-large-line-height)",letterSpacing:"var(--ui-button-large-letter-spacing)",fontWeight:"var(--ui-button-large-font-weight)"},label:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-label-line-height)",letterSpacing:"var(--ui-label-letter-spacing)",fontWeight:"var(--ui-label-font-weight)"},caption:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-caption-line-height)",letterSpacing:"var(--ui-caption-letter-spacing)",fontWeight:"var(--ui-caption-font-weight)"},badge:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-badge-line-height)",letterSpacing:"var(--ui-badge-letter-spacing)",fontWeight:"var(--ui-badge-font-weight)"},tooltip:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-tooltip-line-height)",letterSpacing:"var(--ui-tooltip-letter-spacing)",fontWeight:"var(--ui-tooltip-font-weight)"},input:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-input-line-height)",letterSpacing:"var(--ui-input-letter-spacing)",fontWeight:"var(--ui-input-font-weight)"},helperText:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-helper-text-line-height)",letterSpacing:"var(--ui-helper-text-letter-spacing)",fontWeight:"var(--ui-helper-text-font-weight)"}},code:{inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"},block:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},lineNumbers:{fontSize:"var(--text-micro)",lineHeight:"var(--code-line-numbers-line-height)",letterSpacing:"var(--code-line-numbers-letter-spacing)",fontWeight:"var(--code-line-numbers-font-weight)"}},markdown:{body:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-line-height)",letterSpacing:"var(--markdown-body-letter-spacing)",fontWeight:"var(--markdown-body-font-weight)"},bodySmall:{fontSize:"var(--text-meta)",lineHeight:"var(--markdown-body-small-line-height)",letterSpacing:"var(--markdown-body-small-letter-spacing)",fontWeight:"var(--markdown-body-small-font-weight)"},bodyLarge:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-large-line-height)",letterSpacing:"var(--markdown-body-large-letter-spacing)",fontWeight:"var(--markdown-body-large-font-weight)"},blockquote:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-blockquote-line-height)",letterSpacing:"var(--markdown-blockquote-letter-spacing)",fontWeight:"var(--markdown-blockquote-font-weight)"},list:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-list-line-height)",letterSpacing:"var(--markdown-list-letter-spacing)",fontWeight:"var(--markdown-list-font-weight)"},link:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-link-line-height)",letterSpacing:"var(--markdown-link-letter-spacing)",fontWeight:"var(--markdown-link-font-weight)"},code:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-line-height)",letterSpacing:"var(--markdown-code-letter-spacing)",fontWeight:"var(--markdown-code-font-weight)"},codeBlock:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-block-line-height)",letterSpacing:"var(--markdown-code-block-letter-spacing)",fontWeight:"var(--markdown-code-block-font-weight)"}},tool:{collapsed:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},popup:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"}}},Zs={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Lr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Zs.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Lr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Zs.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Lr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Zs.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Lr.tool.inline})},Dh=[{id:"inter",label:"Inter",description:"Modern UI sans with excellent readability at small sizes.",stack:'"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Inter",packageName:"@fontsource/inter",filePrefix:"inter",weights:[400,500,600]}},{id:"fixel",label:"Fixel Text",description:"Humanist geometric sans-serif with full Ukrainian support.",stack:'"Fixel Text", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Fixel Text",weights:[400,500,600],urls:{400:"https://cdn.jsdelivr.net/gh/MacPaw/Fixel@f6ee910e98add47e830db87f1a754130506c11a2/fonts/webfonts/FixelText-Regular.woff2",500:"https://cdn.jsdelivr.net/gh/MacPaw/Fixel@f6ee910e98add47e830db87f1a754130506c11a2/fonts/webfonts/FixelText-Medium.woff2",600:"https://cdn.jsdelivr.net/gh/MacPaw/Fixel@f6ee910e98add47e830db87f1a754130506c11a2/fonts/webfonts/FixelText-SemiBold.woff2"}}},{id:"geist-sans",label:"Geist Sans",description:"Crisp sans-serif with a technical interface feel.",stack:'"Geist Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Geist Sans",packageName:"@fontsource/geist-sans",filePrefix:"geist-sans",weights:[400,500,600]}},{id:"atkinson-hyperlegible",label:"Atkinson Hyperlegible",description:"Accessibility-focused sans-serif optimized for character distinction.",stack:'"Atkinson Hyperlegible", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Atkinson Hyperlegible",packageName:"@fontsource/atkinson-hyperlegible",filePrefix:"atkinson-hyperlegible",weights:[400,700]}},{id:"source-sans-3",label:"Source Sans 3",description:"Adobe sans-serif tuned for clean, readable interfaces.",stack:'"Source Sans 3", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Source Sans 3",packageName:"@fontsource/source-sans-3",filePrefix:"source-sans-3",weights:[400,500,600]}},{id:"roboto",label:"Roboto",description:"Familiar Material-style sans-serif with broad UI usage.",stack:'"Roboto", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Roboto",packageName:"@fontsource/roboto",filePrefix:"roboto",weights:[400,500,600]}},{id:"noto-sans",label:"Noto Sans",description:"Readable sans-serif with strong international coverage.",stack:'"Noto Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Noto Sans",packageName:"@fontsource/noto-sans",filePrefix:"noto-sans",weights:[400,500,600]}},{id:"dm-sans",label:"DM Sans",description:"Modern product UI sans-serif with friendly proportions.",stack:'"DM Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"DM Sans",packageName:"@fontsource/dm-sans",filePrefix:"dm-sans",weights:[400,500,600]}},{id:"manrope",label:"Manrope",description:"Polished geometric sans-serif for modern app interfaces.",stack:'"Manrope", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Manrope",packageName:"@fontsource/manrope",filePrefix:"manrope",weights:[400,500,600]}},{id:"system",label:"System",description:"Native operating system interface font.",stack:'-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif'}],_h=[{id:"jetbrains-mono",label:"JetBrains Mono",description:"Developer-focused monospace with strong punctuation clarity.",stack:'"JetBrains Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"JetBrains Mono",packageName:"@fontsource/jetbrains-mono",filePrefix:"jetbrains-mono",weights:[400,500,600]}},{id:"fira-code",label:"Fira Code",description:"Readable coding font with ligature support.",stack:'"Fira Code", "SFMono-Regular", "Menlo", monospace',source:{family:"Fira Code",packageName:"@fontsource/fira-code",filePrefix:"fira-code",weights:[400,500,600]}},{id:"geist-mono",label:"Geist Mono",description:"Sharp monospace pair for Geist Sans.",stack:'"Geist Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"Geist Mono",packageName:"@fontsource/geist-mono",filePrefix:"geist-mono",weights:[400,500,600]}},{id:"commit-mono",label:"Commit Mono",description:"Code-oriented monospace with polished editor ergonomics.",stack:'"Commit Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"Commit Mono",packageName:"@fontsource/commit-mono",filePrefix:"commit-mono",weights:[400,500,600]}},{id:"source-code-pro",label:"Source Code Pro",description:"Adobe monospace designed for source code readability.",stack:'"Source Code Pro", "SFMono-Regular", "Menlo", monospace',source:{family:"Source Code Pro",packageName:"@fontsource/source-code-pro",filePrefix:"source-code-pro",weights:[400,500,600]}},{id:"cascadia-code",label:"Cascadia Code",description:"Microsoft coding font popular in terminals and editors.",stack:'"Cascadia Code", "SFMono-Regular", "Menlo", monospace',source:{family:"Cascadia Code",packageName:"@fontsource/cascadia-code",filePrefix:"cascadia-code",weights:[400,500,600]}},{id:"roboto-mono",label:"Roboto Mono",description:"Neutral monospace companion to Roboto.",stack:'"Roboto Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"Roboto Mono",packageName:"@fontsource/roboto-mono",filePrefix:"roboto-mono",weights:[400,500,600]}},{id:"iosevka",label:"Iosevka",description:"Compact monospace for dense code and terminal layouts.",stack:'"Iosevka", "SFMono-Regular", "Menlo", monospace',source:{family:"Iosevka",packageName:"@fontsource/iosevka",filePrefix:"iosevka",weights:[400,500,600]}},{id:"system-mono",label:"System Mono",description:"Native operating system monospace font.",stack:'ui-monospace, "SFMono-Regular", "Menlo", "Cascadia Mono", "Segoe UI Mono", monospace'}],Fl=e=>Object.fromEntries(e.map(t=>[t.id,t])),Lh=Fl(Dh),Fh=Fl(_h),Uh="system",jh="system-mono",Nh=e=>typeof e=="string"&&e in Lh,Bh=e=>typeof e=="string"&&e in Fh,Ro="openchamber.mobileKeyboardMode",Hh='meta[name="viewport"]',Ca="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover",rT=()=>!0;function Os(e,t="resize-content"){return e==="native"||e==="resize-content"?e:t}const zh=e=>Os(e)==="resize-content"?`${Ca}, interactive-widget=resizes-content`:Ca,$h=()=>{if(typeof window>"u")return"resize-content";try{return Os(localStorage.getItem(Ro))}catch{return"resize-content"}},Ul=e=>{const t=Os(e);if(typeof window<"u")try{t==="resize-content"?localStorage.removeItem(Ro):localStorage.setItem(Ro,t)}catch{}return t},sT=e=>{const t=Ul(e);if(typeof document>"u")return t;document.documentElement.setAttribute("data-oc-mobile-keyboard-mode",t);const n=document.querySelector(Hh);if(n instanceof HTMLMetaElement){const r=zh(t);n.getAttribute("content")!==r&&n.setAttribute("content",r)}return t},eo=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),Wh=new Set(["starting","running","stopping"]),Gh=e=>!!e?.tabs.some(t=>wn(t.purpose)&&t.lifecycle!=="exited"),Co=512*1024,qh=new TextEncoder,Kh=new TextDecoder,to=e=>{const t=qh.encode(e);if(t.byteLength<=Co)return{text:e,byteLength:t.byteLength};let n=t.byteLength-Co;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;const r=t.subarray(n);return{text:Kh.decode(r),byteLength:r.byteLength}},Xe=(e,t)=>`${e}\0${t}`,un=(e,t)=>{let n=null;for(const r of e.keys())t(r)&&(n??=new Map(e),n.delete(r));return n},Vh="terminal-store";let Oa=!1,Ma=0;const Jh=T({type:N("project-action"),actionId:m()}),Wn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(Ma+=1,`tab-${Date.now().toString(36)}-${Ma.toString(36)}`),no=e=>typeof e=="object"&&e!==null,wn=e=>e.type==="project-action",Fr=(e,t)=>wn(e.purpose)?t===void 0?!0:e.purpose.executionId===t:t==null,Yh=()=>Wn().replace(/^tab-/,"exec-"),Da=e=>e==="running"?"running":"exited",Qh=(e,t)=>({type:"project-action",actionId:e.actionId,executionId:t==="running"?e.executionId:null}),Xh=e=>{const t=new Map,n=[];for(const r of e){if(r.purpose?.type!=="project-action"){n.push(r);continue}const s=t.get(r.purpose.actionId);(!s||r.status==="running"&&s.status!=="running"||r.status===s.status&&((r.createdAt??0)>(s.createdAt??0)||r.createdAt===s.createdAt&&r.sessionId>s.sessionId))&&t.set(r.purpose.actionId,r)}return[...n,...t.values()]},ro={previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1},Zh=e=>e.trim()||"Action",em=e=>{const t=/^tab-(\d+)$/.exec(e);if(!t)return null;const n=Number(t[1]);return Number.isFinite(n)?n:null},ee=Hp,ys=(e,t)=>`${e}\0${t}`,Bn=(e,t,n,r)=>{e.set(ys(t,n),r)},_a=(e,t,n,r)=>{if(!r)return!1;const s=ys(t,n),o=e.actionMutationRevisions.get(s)??0,i=r.get(s)??0;return o>i},tm=/^Terminal(?: (\d+))?$/,La=e=>{let t=0;for(const n of e){const r=tm.exec(n.label);if(!r)continue;const s=r[1]?Number.parseInt(r[1],10):1;Number.isSafeInteger(s)&&(t=Math.max(t,s))}return t===0?"Terminal":`Terminal ${t+1}`},oT=e=>e.purpose.type==="project-action"&&e.purpose.executionId!==null&&Wh.has(e.lifecycle),nm=e=>!!(e&&e.terminalSessionId!==null&&e.lifecycle==="running"),Ur=(e,t)=>({id:e,terminalSessionId:null,lifecycle:"idle",purpose:{type:"terminal"},label:t,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),so=e=>({tabs:[e],activeTabId:e.id}),xe=(e,t)=>e.tabs.findIndex(n=>n.id===t);let oo=null,io=null;const rm=e=>{if(io&&oo?.sessions===e.sessions&&oo.nextTabId===e.nextTabId)return io;const t={sessions:Array.from(e.sessions.entries()).map(([n,r])=>[n,{activeTabId:r.activeTabId,tabs:r.tabs.map(s=>({id:s.id,label:s.label,iconKey:s.iconKey,createdAt:s.createdAt,purpose:s.purpose.type==="project-action"?{type:"project-action",actionId:s.purpose.actionId}:{type:"terminal"}}))}]),nextTabId:e.nextTabId};return oo={sessions:e.sessions,nextTabId:e.nextTabId},io=t,t},sm=()=>{const e=Vu(()=>Oh());if(!e)return;let t=null;return{getItem:n=>e.getItem(n),setItem:(n,r)=>{if(r.state!==t)return t=r.state,e.setItem(n,r)},removeItem:n=>(t=null,e.removeItem(n))}},Xr=yt()(Cn(pr((e,t)=>({sessions:new Map,buffers:new Map,actionMutationRevisions:new Map,nextActionMutationRevision:1,nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=ee(n);r&&e(s=>{if(s.sessions.has(r))return s;const o=new Map(s.sessions),i=Wn(),a=Ur(i,"Terminal");return o.set(r,so(a)),{sessions:o,nextTabId:s.nextTabId+1}})},getDirectoryState:n=>{const r=ee(n);return t().sessions.get(r)},getActiveTab:n=>{const r=ee(n),s=t().sessions.get(r);if(!s)return;const o=s.activeTabId;return o?s.tabs.find(i=>i.id===o)??s.tabs[0]:s.tabs[0]},getBuffer:(n,r)=>t().buffers.get(Xe(ee(n),r))??eo,matchesActionExecution:(n,r,s)=>{const o=t().sessions.get(ee(n))?.tabs.find(i=>i.id===r);return!!(o&&wn(o.purpose)&&o.purpose.executionId===s)},captureStartedActionMutationRevisions:n=>{const r=ee(n),s=ys(r,""),o=new Map;for(const[i,a]of t().actionMutationRevisions.entries())i.startsWith(s)&&o.set(i,a);return o},createTab:n=>{const r=ee(n);if(!r)return"tab-invalid";const s=Wn();return e(o=>{const i=new Map(o.sessions),a=i.get(r),c=o.nextTabId+1,l=La(a?.tabs??[]),u=Ur(s,l);return a?i.set(r,{...a,tabs:[...a.tabs,u]}):i.set(r,so(u)),{sessions:i,nextTabId:c}}),s},reconcileServerSessions:(n,r,s)=>{const o=ee(n);o&&e(i=>{const a=i.sessions.get(o);if(!a&&r.length===0)return i;const c=[...a?.tabs??[]];let l=i.buffers,u=!1,d=null;const f=new Set,p=new Set,y=c.length===1&&c[0].terminalSessionId===null&&c[0].lifecycle==="idle"&&c[0].purpose.type==="terminal"&&!i.buffers.has(Xe(o,c[0].id))?c[0]:null;y&&r.length>0&&(c.length=0);for(const C of Xh(r)){let Se=c.findIndex(F=>F.terminalSessionId===C.sessionId||F.id===C.sessionId);const ae=C.purpose,Fs=ae?.type==="project-action"&&_a(i,o,ae.actionId,s?.startedActionMutationRevisions);if(ae?.type==="project-action"){f.add(ae.actionId);const F=c.findIndex(Qe=>wn(Qe.purpose)&&Qe.purpose.actionId===ae.actionId);if(Fs){F>=0&&p.add(c[F].id);continue}Se<0&&(Se=F)}const Ie=ae?.type==="project-action"?Qh(ae,C.status):{type:"terminal"};if(Se>=0){const F=c[Se];let Qe=F.purpose.type==="project-action"||ae?.type==="project-action"?Da(C.status):C.status;F.lifecycle==="stopping"&&C.status==="running"&&F.purpose.type==="project-action"&&Ie.type==="project-action"&&F.purpose.executionId===Ie.executionId&&(Qe="stopping");const an=C.createdAt??F.createdAt,vr=ae?.type==="project-action"&&(F.terminalSessionId!==C.sessionId||Ie.type==="project-action"&&Ie.executionId!==null&&(F.purpose.type!=="project-action"||F.purpose.executionId!==Ie.executionId));if(vr){const wt=Xe(o,F.id);l=un(l,Us=>Us===wt)??l}const Fn=ae?.type==="project-action"&&C.status==="running"&&(F.terminalSessionId!==C.sessionId||F.lifecycle!=="running"),Tr=F.purpose.type!==Ie.type||F.purpose.type==="project-action"&&Ie.type==="project-action"&&(F.purpose.actionId!==Ie.actionId||F.purpose.executionId!==Ie.executionId);if((F.terminalSessionId!==C.sessionId||F.lifecycle!==Qe||F.isConnecting!==!1||F.createdAt!==an||Tr)&&(c[Se]={...F,terminalSessionId:C.sessionId,lifecycle:Qe,purpose:Ie,isConnecting:!1,createdAt:an},vr&&Object.assign(c[Se],ro),u=!0),Fn){const wt={tabId:F.id,createdAt:an,index:Se};(!d||wt.createdAt>d.createdAt||wt.createdAt===d.createdAt&&wt.index>d.index)&&(d=wt)}p.add(F.id);continue}const _n=ae?.type==="project-action"?Zh(ae.actionId):y&&c.length===0?y.label:La(c),Ln=ae?.type==="project-action"?"play":null,Ut={...Ur(C.sessionId,_n),terminalSessionId:C.sessionId,lifecycle:ae?.type==="project-action"?Da(C.status):C.status,purpose:Ie,iconKey:Ln,createdAt:C.createdAt??Date.now()};if(c.push(Ut),u=!0,ae?.type==="project-action"&&C.status==="running"){const F={tabId:Ut.id,createdAt:Ut.createdAt,index:c.length-1};(!d||F.createdAt>d.createdAt||F.createdAt===d.createdAt&&F.index>d.index)&&(d=F)}p.add(Ut.id)}let b=u||!!(y&&r.length>0);const w=c.map(C=>!wn(C.purpose)||f.has(C.purpose.actionId)||p.has(C.id)||C.lifecycle==="starting"||_a(i,o,C.purpose.actionId,s?.startedActionMutationRevisions)||C.lifecycle==="exited"&&!C.isConnecting?C:(b=!0,{...C,lifecycle:"exited",isConnecting:!1,purpose:{type:"project-action",actionId:C.purpose.actionId,executionId:null}})),E=a?.activeTabId??null,k=E&&w.some(C=>C.id===E)?E:w[0]?.id??null,U=k?w.find(C=>C.id===k):w[0],D=d&&!nm(U)?d.tabId:k;if(!b&&a&&D===a.activeTabId&&w.length===a.tabs.length&&w.every((C,Se)=>C===a.tabs[Se]))return i;const J=new Map(i.sessions);return J.set(o,{tabs:w,activeTabId:D}),{sessions:J,buffers:l}})},setActiveTab:(n,r)=>{const s=ee(n);e(o=>{const i=new Map(o.sessions),a=i.get(s);return!a||a.activeTabId===r||xe(a,r)<0?o:(i.set(s,{...a,activeTabId:r}),{sessions:i})})},setTabLabel:(n,r,s)=>{const o=ee(n),i=s.trim();i&&e(a=>{const c=new Map(a.sessions),l=c.get(o);if(!l)return a;const u=xe(l,r);if(u<0||l.tabs[u]?.label===i)return a;const d=[...l.tabs];return d[u]={...d[u],label:i},c.set(o,{...l,tabs:d}),{sessions:c}})},setTabIconKey:(n,r,s)=>{const o=ee(n);e(i=>{const a=new Map(i.sessions),c=a.get(o);if(!c)return i;const l=xe(c,r);if(l<0)return i;const u=s?.trim()||null;if(c.tabs[l]?.iconKey===u)return i;const d=[...c.tabs];return d[l]={...d[l],iconKey:u},a.set(o,{...c,tabs:d}),{sessions:a}})},closeTab:(n,r)=>{const s=ee(n);e(o=>{const i=new Map(o.sessions),a=i.get(s);if(!a)return o;const c=xe(a,r);if(c<0)return o;const l=a.tabs[c].purpose;let u=o.actionMutationRevisions,d=o.nextActionMutationRevision;l.type==="project-action"&&(u=new Map(u),Bn(u,s,l.actionId,d),d+=1);const f={actionMutationRevisions:u,nextActionMutationRevision:d},p=a.tabs.filter(k=>k.id!==r),y=Xe(s,r),b=o.buffers.has(y)?un(o.buffers,k=>k===y):null;if(p.length===0){const k=Wn(),U=Ur(k,"Terminal");i.set(s,so(U));const D={sessions:i,nextTabId:o.nextTabId+1};return b&&(D.buffers=b),{...D,...f}}let w=a.activeTabId;a.activeTabId===r&&(w=p[Math.min(c,p.length-1)]?.id??p[0]?.id??null),i.set(s,{...a,tabs:p,activeTabId:w});const E={sessions:i};return b&&(E.buffers=b),{...E,...f}})},setTabPurpose:(n,r,s)=>{const o=ee(n);e(i=>{const a=i.sessions.get(o);if(!a)return i;const c=xe(a,r);if(c<0)return i;const l=a.tabs[c];if(JSON.stringify(l.purpose)===JSON.stringify(s))return i;const u=[...a.tabs],d=s.type==="project-action"&&s.executionId!==null&&(l.purpose.type!=="project-action"||l.purpose.executionId!==s.executionId);u[c]={...l,purpose:s},d&&Object.assign(u[c],ro);const f=Xe(o,r),p=d?un(i.buffers,w=>w===f)??i.buffers:i.buffers,y=new Map(i.sessions);if(y.set(o,{...a,tabs:u}),s.type!=="project-action")return{sessions:y};const b=new Map(i.actionMutationRevisions);return Bn(b,o,s.actionId,i.nextActionMutationRevision),{sessions:y,buffers:p,actionMutationRevisions:b,nextActionMutationRevision:i.nextActionMutationRevision+1}})},allocateActionExecution:(n,r,s)=>{const o=ee(n),i=t().sessions.get(o);if(!i||xe(i,r)<0)return null;const a=Yh();return e(c=>{const l=c.sessions.get(o);if(!l)return c;const u=xe(l,r);if(u<0)return c;const d=[...l.tabs];d[u]={...d[u],purpose:{type:"project-action",actionId:s,executionId:a},lifecycle:"starting",terminalSessionId:null,...ro,isConnecting:!1};const f=new Map(c.sessions);f.set(o,{...l,tabs:d});const p=new Map(c.actionMutationRevisions);Bn(p,o,s,c.nextActionMutationRevision);const y=Xe(o,r),b=un(c.buffers,w=>w===y)??c.buffers;return{sessions:f,buffers:b,actionMutationRevisions:p,nextActionMutationRevision:c.nextActionMutationRevision+1}}),a},setTabSessionId:(n,r,s,o)=>{const i=ee(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=xe(l,r);if(u<0)return a;const d=l.tabs[u];if(!Fr(d,o?.expectedExecutionId))return a;const f=s!==null&&d.terminalSessionId!==s,p=s?"running":d.terminalSessionId?"exited":d.lifecycle,y={...d,terminalSessionId:s,lifecycle:p,isConnecting:!1},b=Xe(i,r),w=f&&a.buffers.has(b)?un(a.buffers,U=>U===b):null,E=[...l.tabs];E[u]=y,c.set(i,{...l,tabs:E});const k={sessions:c,nextActionMutationRevision:a.nextActionMutationRevision};if(wn(d.purpose)){const U=new Map(a.actionMutationRevisions);Bn(U,i,d.purpose.actionId,a.nextActionMutationRevision),k.actionMutationRevisions=U,k.nextActionMutationRevision=a.nextActionMutationRevision+1}return w&&(k.buffers=w),k})},setTabLifecycle:(n,r,s,o)=>{const i=ee(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=xe(l,r);if(u<0||!Fr(l.tabs[u],o?.expectedExecutionId))return a;const d=l.tabs[u];if(d.lifecycle===s&&!d.isConnecting)return a;const f=[...l.tabs];if(f[u]={...d,lifecycle:s,isConnecting:!1},c.set(i,{...l,tabs:f}),d.purpose.type!=="project-action"||d.lifecycle===s)return{sessions:c};const p=new Map(a.actionMutationRevisions);return Bn(p,i,d.purpose.actionId,a.nextActionMutationRevision),{sessions:c,actionMutationRevisions:p,nextActionMutationRevision:a.nextActionMutationRevision+1}})},setConnecting:(n,r,s,o)=>{const i=ee(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=xe(l,r);if(u<0||!Fr(l.tabs[u],o?.expectedExecutionId))return a;const d=[...l.tabs];return d[u]={...d[u],isConnecting:s},c.set(i,{...l,tabs:d}),{sessions:c}})},replaceBuffer:(n,r,s,o,i)=>{const a=ee(n);e(c=>{const l=c.sessions.get(a);if(!l||xe(l,r)<0)return c;const u=Xe(a,r),d=c.buffers.get(u)??eo;if(d.lastSequence>o)return c;const f=to(s),p=d.chunks[0]?.size;if(d.lastSequence===o&&d.byteLength===f.byteLength&&d.chunks.map(w=>w.data).join("")===f.text&&p?.cols===i?.cols&&p?.rows===i?.rows)return c;const y=c.nextChunkId,b=new Map(c.buffers);return b.set(u,{chunks:f.text?[{id:y,data:f.text,byteLength:f.byteLength,...i?{size:i}:{}}]:[],byteLength:f.byteLength,lastSequence:o}),{buffers:b,nextChunkId:f.text?y+1:y}})},appendToBuffer:(n,r,s,o,i)=>{if(!s)return;const a=ee(n);e(c=>{const l=c.sessions.get(a);if(!l||xe(l,r)<0)return c;const u=Xe(a,r),d=c.buffers.get(u)??eo;if(o!==void 0&&o<=d.lastSequence)return c;const f=c.nextChunkId,p=to(s),y=i!==void 0&&i!==s?to(i).text:void 0,b={id:f,data:p.text,...y!==void 0?{replayData:y}:{},byteLength:p.byteLength},w=[...d.chunks,b];let E=d.byteLength+b.byteLength;for(;E>Co&&w.length>1;){const U=w.shift();if(!U)break;E-=U.byteLength}const k=new Map(c.buffers);return k.set(u,{chunks:w,byteLength:E,lastSequence:o??d.lastSequence}),{buffers:k,nextChunkId:f+1}})},setTabPreviewUrl:(n,r,s,o={})=>{const i=ee(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=xe(l,r);if(u<0)return a;const d=l.tabs[u];if(!Fr(d,o.expectedExecutionId))return a;const f=o.autoOpened??d.previewAutoOpened,p=o.locked??d.previewUrlLocked;if(d.previewUrl===s&&d.previewAutoOpened===f&&d.previewUrlLocked===p)return a;const y=[...l.tabs];return y[u]={...d,previewUrl:s,previewAutoOpened:f,previewUrlLocked:p},c.set(i,{...l,tabs:y}),{sessions:c}})},markPreviewAutoOpened:(n,r)=>{const s=ee(n);e(o=>{const i=new Map(o.sessions),a=i.get(s);if(!a)return o;const c=xe(a,r);if(c<0)return o;const l=a.tabs[c];if(!l.previewUrl||l.previewAutoOpened)return o;const u=[...a.tabs];return u[c]={...l,previewAutoOpened:!0},i.set(s,{...a,tabs:u}),{sessions:i}})},removeDirectory:n=>{const r=ee(n);e(s=>{const o=new Map(s.sessions);o.delete(r);const i=Xe(r,""),a=un(s.buffers,d=>d.startsWith(i)),c=ys(r,"");let l;for(const d of s.actionMutationRevisions.keys())d.startsWith(c)&&(l??=new Map(s.actionMutationRevisions),l.delete(d));const u={sessions:o};return a&&(u.buffers=a),l&&(u.actionMutationRevisions=l),u})},clearAll:()=>{e({sessions:new Map,buffers:new Map,actionMutationRevisions:new Map,nextActionMutationRevision:1,nextChunkId:1,nextTabId:1})}}),{name:Vh,storage:sm(),partialize:rm,merge:(e,t)=>{if(!no(e))return t;const n=Array.isArray(e.sessions)?e.sessions:[],r=new Map;let s=0;for(const a of n){if(!Array.isArray(a)||a.length!==2)continue;const[c,l]=a;if(typeof c!="string"||!no(l))continue;const u=Array.isArray(l.tabs)?l.tabs:[],d=[],f=new Map;for(const w of u){if(!no(w))continue;const E=typeof w.id=="string"?w.id:null;if(!E)continue;const k=em(E);k!==null&&(s=Math.max(s,k));const U=k===null?E:Wn();f.set(E,U);const D=Jh.safeParse(w.purpose).data,J=D?{type:"project-action",actionId:D.actionId,executionId:null}:{type:"terminal"};d.push({id:U,label:typeof w.label=="string"?w.label:"Terminal",iconKey:typeof w.iconKey=="string"?w.iconKey:null,terminalSessionId:null,lifecycle:"idle",purpose:J,createdAt:typeof w.createdAt=="number"?w.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(d.length===0)continue;const p=typeof l.activeTabId=="string"?l.activeTabId:null,y=p?f.get(p)??p:null,b=y?d.some(w=>w.id===y):!1;r.set(c,{tabs:d,activeTabId:b?y:d[0].id})}const o=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,i=Math.max(t.nextTabId,o,s+1);return{...t,sessions:r,buffers:new Map,actionMutationRevisions:new Map,nextActionMutationRevision:1,nextChunkId:1,nextTabId:i,hasHydrated:!0}}})));if(typeof window<"u"&&!Oa){Oa=!0;const e=Xr.persist,t=()=>{Xr.getState().hasHydrated||Xr.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}const Ze=20,om=8,Fa=4096,im=2160*60*6e4,Q=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),n=t.startsWith("//");let r=t.replace(/\/+/g,"/");n&&!r.startsWith("//")&&(r=`/${r}`);const s=r==="/",o=/^[A-Za-z]:\/$/.test(r);return!s&&!o&&(r=r.replace(/\/+$/,"")),r},It=e=>/^[A-Za-z]:\//.test(e)?e.toLowerCase():e,Rt=(e,t)=>{const n=Q(t),r=Q(e);if(!n||!r)return!1;const s=It(n),o=It(r);return o===s||o.startsWith(`${s}/`)},Hn=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,s]of Object.entries(t)){const o=Q(r);if(!o||!s||typeof s!="object")continue;const i=s,a=Array.isArray(i.openPaths)?Array.from(new Set(i.openPaths.filter(p=>typeof p=="string").map(p=>Q(p)).filter(p=>p.length<=Fa&&Rt(p,o)))).slice(-50):[],c=Array.isArray(i.expandedPaths)?Array.from(new Set(i.expandedPaths.filter(p=>typeof p=="string").map(p=>Q(p)).filter(p=>p.length<=Fa&&Rt(p,o)))).slice(-500):[],l=typeof i.selectedPath=="string"?Q(i.selectedPath):null,u=l&&Rt(l,o)?l:a[0]??null,d=typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now();if(Date.now()-d>im)continue;const f=n[o];if(f){const p=Array.from(new Set([...f.openPaths,...a])),y=Array.from(new Set([...f.expandedPaths,...c])),b=f.selectedPath??u??p[0]??null;n[o]={openPaths:p,selectedPath:b,expandedPaths:y,touchedAt:Math.max(f.touchedAt,d)};continue}n[o]={openPaths:a,selectedPath:u,expandedPaths:c,touchedAt:d}}return et(n,Ze)},et=(e,t)=>{const n=Object.entries(e);if(n.length<=t)return e;n.sort((s,o)=>(o[1]?.touchedAt??0)-(s[1]?.touchedAt??0));const r={};for(const[s,o]of n.slice(0,t))r[s]=o;return r},dn=e=>e?{...e,touchedAt:Date.now()}:{openPaths:[],selectedPath:null,expandedPaths:[],touchedAt:Date.now()},am=yt()(Cn(pr((e,t)=>({byRoot:{},activeRuntimeKey:W(),runtimeSnapshots:{},resetForRuntimeSwitch:n=>{e(r=>{const s={...r.runtimeSnapshots,[r.activeRuntimeKey]:{byRoot:Hn(r.byRoot),updatedAt:Date.now()}};return{activeRuntimeKey:n,runtimeSnapshots:s,byRoot:Hn(s[n]?.byRoot)}})},addOpenPath:(n,r,s)=>{const o=Q((n||"").trim()),i=Q((r||"").trim());!o||!i||!s?.allowOutsideRoot&&!Rt(i,o)||e(a=>{const c=a.byRoot[o],l=dn(c),u=l.openPaths.includes(i),d=u?l.openPaths:[...l.openPaths,i],f=l.selectedPath??i;if(c&&u&&c.selectedPath===f)return a;const p={...a.byRoot,[o]:{...l,openPaths:d,selectedPath:f}};return{byRoot:et(p,Ze)}})},removeOpenPath:(n,r)=>{const s=Q((n||"").trim()),o=Q((r||"").trim());!s||!o||e(i=>{const a=i.byRoot[s];if(!a)return i;const c=It(o),l=y=>It(y)===c,u=a.selectedPath?l(a.selectedPath):!1;if(!a.openPaths.some(l)&&!u)return i;const d=a.openPaths.filter(y=>!l(y)),f=u?d[0]??null:a.selectedPath,p={...i.byRoot,[s]:{...a,openPaths:d,selectedPath:f,touchedAt:Date.now()}};return{byRoot:et(p,Ze)}})},removeOpenPathsByPrefix:(n,r)=>{const s=Q((n||"").trim()),o=Q((r||"").trim());!s||!o||e(i=>{const a=i.byRoot[s];if(!a)return i;const c=It(o),l=c.endsWith("/")?c:`${c}/`,u=y=>{const b=It(y);return b===c||b.startsWith(l)},d=a.openPaths.filter(y=>!u(y));if(d.length===a.openPaths.length)return i;const f=a.selectedPath&&u(a.selectedPath)?d[0]??null:a.selectedPath,p={...i.byRoot,[s]:{...a,openPaths:d,selectedPath:f,touchedAt:Date.now()}};return{byRoot:et(p,Ze)}})},removeExpandedPathsByPrefix:(n,r)=>{const s=Q((n||"").trim()),o=Q((r||"").trim());!s||!o||e(i=>{const a=i.byRoot[s];if(!a)return i;const c=It(o),l=c.endsWith("/")?c:`${c}/`,u=a.expandedPaths.filter(f=>{const p=It(f);return p!==c&&!p.startsWith(l)});if(u.length===a.expandedPaths.length)return i;const d={...i.byRoot,[s]:{...a,expandedPaths:u,touchedAt:Date.now()}};return{byRoot:et(d,Ze)}})},setSelectedPath:(n,r,s)=>{const o=Q((n||"").trim()),i=r?Q(r.trim()):null;!o||i&&!s?.allowOutsideRoot&&!Rt(i,o)||e(a=>{const c=a.byRoot[o],l=dn(c),u=i&&!l.openPaths.includes(i)?[...l.openPaths,i]:l.openPaths;if(c&&c.selectedPath===i&&u===c.openPaths)return a;const d={...a.byRoot,[o]:{...l,openPaths:u,selectedPath:i}};return{byRoot:et(d,Ze)}})},ensureSelectedPath:n=>{const r=Q((n||"").trim());if(!r)return;const s=t().byRoot[r];if(!s||s.selectedPath)return;const o=s.openPaths[0]??null;o&&t().setSelectedPath(r,o)},toggleExpandedPath:(n,r)=>{const s=Q((n||"").trim()),o=Q((r||"").trim());!s||!o||!Rt(o,s)||e(i=>{const a=i.byRoot[s],c=dn(a),u=c.expandedPaths.includes(o)?c.expandedPaths.filter(f=>f!==o):[...c.expandedPaths,o];if(a&&a.expandedPaths===u&&a.selectedPath===c.selectedPath&&a.openPaths===c.openPaths)return i;const d={...i.byRoot,[s]:{...c,expandedPaths:u}};return{byRoot:et(d,Ze)}})},collapseAllExpandedPaths:n=>{const r=Q((n||"").trim());r&&e(s=>{const o=s.byRoot[r];if(!o||o.expandedPaths.length===0)return s;const i={...s.byRoot,[r]:{...dn(o),expandedPaths:[]}};return{byRoot:et(i,Ze)}})},expandPath:(n,r)=>{const s=Q((n||"").trim()),o=Q((r||"").trim());!s||!o||!Rt(o,s)||e(i=>{const a=i.byRoot[s],c=dn(a);if(c.expandedPaths.includes(o)&&a)return i;const u={...i.byRoot,[s]:{...c,expandedPaths:[...c.expandedPaths,o]}};return{byRoot:et(u,Ze)}})},expandPaths:(n,r)=>{const s=Q((n||"").trim());if(!s||!r||r.length===0)return;const o=r.map(i=>Q((i||"").trim())).filter(i=>i&&Rt(i,s));o.length!==0&&e(i=>{const a=i.byRoot[s],c=dn(a),l=new Set(c.expandedPaths),u=o.filter(f=>!l.has(f));if(u.length===0)return i;const d={...i.byRoot,[s]:{...c,expandedPaths:[...c.expandedPaths,...u]}};return{byRoot:et(d,Ze)}})}}),{name:"files-view-tabs-store",version:3,storage:yi(),migrate:(e,t)=>t<3||!e||typeof e!="object"?{byRoot:{},activeRuntimeKey:W(),runtimeSnapshots:{}}:e,partialize:e=>{const t={...e.runtimeSnapshots,[e.activeRuntimeKey]:{byRoot:Hn(e.byRoot),updatedAt:Date.now()}},n=Object.fromEntries(Object.entries(t).sort(([,r],[,s])=>s.updatedAt-r.updatedAt).slice(0,om).map(([r,s])=>[r,{byRoot:Hn(s.byRoot),updatedAt:s.updatedAt}]));return{activeRuntimeKey:e.activeRuntimeKey,runtimeSnapshots:n}},merge:(e,t)=>{const n=e&&typeof e=="object"?e:{},r=n.runtimeSnapshots&&typeof n.runtimeSnapshots=="object"?n.runtimeSnapshots:{},s=W();return{...t,activeRuntimeKey:s,runtimeSnapshots:r,byRoot:Hn(r[s]?.byRoot)}}}),{name:"files-view-tabs-store"})),cm=["diff","walkthrough","file","context","plan","chat","browser","git","pr","linear","notes","terminal"],lm=/^plugin:[a-z][a-z0-9-]*$/,um=new Set(cm),dm=e=>lm.test(e),fm=e=>um.has(e)||dm(e),iT=e=>e.slice(7),aT=e=>`plugin:${e}`,bi=["session","repository","usage","telemetry","subagents","mcp","pinned","contextSources"],cT={session:"chat.workStatus.section.session",repository:"chat.workStatus.section.project",usage:"chat.workStatus.section.usage",telemetry:"chat.workStatus.section.telemetry",subagents:"chat.workStatus.section.subagents",mcp:"chat.workStatus.section.mcp",pinned:"chat.workStatus.section.pinned",contextSources:"chat.workStatus.section.contextBreakdown"},pm=new Set(bi),jl=e=>typeof e=="string"&&pm.has(e),Oo=e=>{const t=new Set;if(Array.isArray(e))for(const n of e)jl(n)&&t.add(n);for(const n of bi)t.add(n);return[...t]},lT=(e,t)=>!e?.includes(t),uT=e=>e!=null&&bi.every(t=>e.includes(t)),dT=({visible:e,contentMounted:t,renderedSections:n,allSectionsHidden:r})=>({interactive:e&&(n>0||r),showEmptyState:t&&r}),Nl=(e,t=!0)=>{if(!Array.isArray(e))return[];const n=new Set;for(const r of e)jl(r)&&n.add(r);return t||n.delete("telemetry"),[...n]},hm=e=>Math.min(480,Math.max(200,Math.round(e))),mm=ke(["diff","walkthrough","file","context","plan","chat","browser","git","pr","linear","notes","terminal"]),gm=T({widthByMode:it(m(),R().finite().optional().catch(void 0)).catch({}),widthFractionByMode:it(m(),R().positive().max(1).optional().catch(void 0)).catch({})}),Bl="ask",Ua=e=>e==="attach"||e==="inline"||e==="ask"?e:Bl;function ja(e){return e==="vim"?"vim":"default"}const pt="all";function Na(e){return e==="all"||e==="backlog"||e==="todo"||e==="started"||e==="inReview"||e==="completed"||e==="canceled"||e==="duplicate"?e:"all"}function Ba(e){return e==="me"||e==="any"?e:"any"}function Hl(e){return typeof e!="string"?pt:e.trim()||pt}function Ha(e,t){const n=W();if(qc(n))return e;const r={...e};return t===pt?delete r[n]:r[n]=t,r}function ym(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};for(const[n,r]of Object.entries(e)){if(!n.trim()||typeof r!="string")continue;const s=Hl(r);s!==pt&&(t[n]=s)}return t}function za(e){return e==="none"||e==="urgent"||e==="high"||e==="medium"||e==="low"||e==="all"?e:"all"}const jr={completion:{title:"{agent_name} is ready",message:"{last_message}"},error:{title:"Tool error",message:"{last_message}"},question:{title:"{agent_name} needs input",message:"{last_message}"},subtask:{title:"Subtask complete",message:"{last_message}"}},vt={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},Nr=(e,t)=>e?e.title===t.title&&e.message===t.message:!1,wm=e=>{if(!e||typeof e!="object")return!1;const t=e;return Nr(t.completion,jr.completion)&&Nr(t.error,jr.error)&&Nr(t.question,jr.question)&&Nr(t.subtask,jr.subtask)},bm=380,Sm=320,vm=1e4,zl=12,$a=120,Tm=280;let Wa=0;const km=e=>he(e),he=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),n=t.startsWith("//");let r=t.replace(/\/+$/g,"");return r=r.replace(/\/+/g,"/"),n&&!r.startsWith("//")&&(r=`/${r}`),r===""?t.startsWith("/")?"/":"":r},$l=e=>Number.isFinite(e)?Math.min(vm,Math.max(Sm,Math.round(e))):bm,lr=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.replace(/\\/g,"/"):null},ws=e=>{const t=lr(e);return t&&km(t)||null},bs=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.length>$a?t.slice(0,$a):t:null},Si=e=>e==="working"||e==="staged"||e==="turn"||e==="branch"||e==="commit"||e==="pr"?e:null,Wl=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n=typeof t.id=="string"?t.id.trim():"",r=typeof t.path=="string"?t.path.trim():"";return n&&r?{id:n,path:r}:null},Em=(e,t)=>(e==="file"||e==="browser")&&t||e,Gl=(e,t,n)=>{if(e==="diff")return e;if(typeof n=="string"){const r=n.trim();if(r)return r}return Em(e,t)},ql=(e,t)=>t===e?e:`${e}:${t}`,vi=e=>{const t=lr(e.targetPath),n=e.mode==="terminal"?ws(e.targetDirectory):null,r=Gl(e.mode,t,e.dedupeKey);return{id:ql(e.mode,r),mode:e.mode,targetPath:t,targetDirectory:n,projectPlanId:typeof e.projectPlanId=="string"&&e.projectPlanId.trim()?e.projectPlanId.trim():null,projectPlanRef:Wl(e.projectPlanRef),dedupeKey:r,label:bs(e.label),sessionTitleFallback:bs(e.sessionTitleFallback),readOnly:e.readOnly===!0,stagedDiff:e.stagedDiff===!0,diffScope:Si(e.diffScope)??(e.stagedDiff===!0?"staged":"working"),touchedAt:Date.now()}},Kl=(e,t,n)=>{const r=new Map;for(const i of e)r.set(i.mode,(r.get(i.mode)??0)+1);const s=[...r.entries()].filter(([,i])=>i>t);if(s.length===0)return e;const o=new Set;for(const[i,a]of s){const l=[...e.filter(u=>u.mode===i)].sort((u,d)=>u.touchedAt-d.touchedAt).filter(u=>u.id!==n);for(const u of l.slice(0,a-t))o.add(u.id)}return o.size===0?e:e.filter(i=>!o.has(i.id))},Vl=e=>{if(!Array.isArray(e))return[];const t=Le(),n=[],r=new Set;for(const s of e){if(!s||typeof s!="object")continue;const o=s;if(typeof o.mode!="string"||!fm(o.mode)||t&&o.mode==="browser")continue;const i=lr(typeof o.targetPath=="string"?o.targetPath:null),a=o.mode==="terminal"?ws(o.targetDirectory):null,c=typeof o.projectPlanId=="string"&&o.projectPlanId.trim()?o.projectPlanId.trim():null,l=Wl(o.projectPlanRef);if(o.mode==="plan"&&c!==null!=(l!==null))continue;const u=Gl(o.mode,i,typeof o.dedupeKey=="string"?o.dedupeKey:null),d=ql(o.mode,u);!d||r.has(d)||(r.add(d),n.push({id:d,mode:o.mode,targetPath:i,targetDirectory:a,projectPlanId:c,projectPlanRef:l,dedupeKey:u,label:bs(typeof o.label=="string"?o.label:null),sessionTitleFallback:bs(typeof o.sessionTitleFallback=="string"?o.sessionTitleFallback:null),readOnly:o.readOnly===!0,stagedDiff:o.stagedDiff===!0,diffScope:Si(o.diffScope)??(o.stagedDiff===!0?"staged":"working"),touchedAt:typeof o.touchedAt=="number"&&Number.isFinite(o.touchedAt)?o.touchedAt:Date.now()}))}return n},In=(e,t)=>t&&e.some(n=>n.id===t)?t:e.length===0?null:e[e.length-1].id,Ht=e=>{if(e){const t=Vl(e.tabs),n=In(t,e.activeTabId);return{...e,tabs:t,activeTabId:n,touchedAt:Date.now()}}return{isOpen:!1,expanded:!1,tabs:[],activeTabId:null,widthByMode:{},widthFractionByMode:{},touchedAt:Date.now()}},Pm=(e,t,n)=>{const r=n?.reveal!==!1,s=vi(t),o=s.mode==="file"&&s.targetPath?e.tabs.filter(u=>!(u.mode==="file"&&!u.targetPath)):e.tabs,i=o.findIndex(u=>u.id===s.id),a=i===-1?[...o,s]:o.map((u,d)=>d===i?{...u,mode:s.mode,targetPath:s.targetPath||u.targetPath,targetDirectory:s.targetDirectory,projectPlanId:s.projectPlanId??u.projectPlanId,projectPlanRef:s.projectPlanRef??u.projectPlanRef,dedupeKey:s.dedupeKey,label:s.label,sessionTitleFallback:s.sessionTitleFallback||u.sessionTitleFallback,stagedDiff:s.stagedDiff,diffScope:s.diffScope,readOnly:s.readOnly,touchedAt:Date.now()}:u),c=r?s.id:e.activeTabId??s.id,l=Kl(a,zl,c);return{...e,isOpen:r?!0:e.isOpen,tabs:l,activeTabId:In(l,c),touchedAt:Date.now()}},Am=(e,t)=>{const n=new Set(t),r=e.tabs.filter(l=>n.has(l.id)),s=e.tabs.filter(l=>!n.has(l.id));if(s.length===e.tabs.length)return e;if(!(e.activeTabId?n.has(e.activeTabId):!1))return{...e,tabs:s,activeTabId:In(s,e.activeTabId),isOpen:s.length>0?e.isOpen:!1,touchedAt:Date.now()};const i=r.find(l=>l.id===e.activeTabId)?.mode??null,a=i?s.filter(l=>l.mode===i):[],c=a.length>0?a.reduce((l,u)=>u.touchedAt>=l.touchedAt?u:l):null;if(i==="file"&&!c&&r.some(l=>l.mode==="file"&&l.targetPath)){const l=vi({mode:"file"});return{...e,tabs:[...s,l],activeTabId:l.id,isOpen:e.isOpen,touchedAt:Date.now()}}return{...e,tabs:s,activeTabId:c?.id??In(s,null),isOpen:c?e.isOpen:!1,touchedAt:Date.now()}},Im=(e,t,n)=>{if(t===n)return e;const r=e.tabs.findIndex(a=>a.id===t),s=e.tabs.findIndex(a=>a.id===n);if(r===-1||s===-1)return e;const o=[...e.tabs],[i]=o.splice(r,1);return i?(o.splice(s,0,i),{...e,tabs:o,touchedAt:Date.now()}):e},xm=(e,t,n)=>({...e,tabs:e.tabs.map(r=>r.id===t?{...r,targetPath:n}:r)}),ao=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,s]of Object.entries(t)){const o=he(r);if(!o||!s||typeof s!="object")continue;const i=s;let a=Vl(i.tabs),c=typeof i.activeTabId=="string"?i.activeTabId:null;a.length===0&&(i.mode==="diff"||i.mode==="file"||i.mode==="context"||i.mode==="plan"||i.mode==="chat"||i.mode==="terminal")&&(a=[vi({mode:i.mode,targetPath:typeof i.targetPath=="string"?i.targetPath:null,targetDirectory:i.targetDirectory,dedupeKey:typeof i.dedupeKey=="string"?i.dedupeKey:null,label:typeof i.label=="string"?i.label:null})],c=a[0]?.id??null);const l=In(a,c),u=Kl(a,zl,l),d={},f={},p=gm.parse(s);for(const y of mm.options){const b=p.widthByMode[y],w=p.widthFractionByMode[y];b!==void 0&&(d[y]=$l(b)),w!==void 0&&(f[y]=w)}n[o]={isOpen:i.isOpen===!0,expanded:i.expanded===!0,tabs:u,activeTabId:In(u,l),widthByMode:d,widthFractionByMode:f,touchedAt:typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now()}}return n},zt=(e,t)=>{const n=Object.entries(e);if(n.length<=t)return e;n.sort((s,o)=>(o[1]?.touchedAt??0)-(s[1]?.touchedAt??0));const r={};for(const[s,o]of n.slice(0,t))r[s]=o;return r},v=yt()(Cn(pr((e,t)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:Tm,contextPanelByDirectory:{},contextRailOrder:[],contextRailHiddenSurfaces:[],contextEditorTreeVisible:!0,contextEditorVisible:!0,contextEditorTreeWidth:240,notesPanelHeight:112,workStatusExpandedSections:{},messageQueueExpanded:!0,workStatusScrollTop:0,workStatusPanelEnabled:!0,workStatusPanelVisible:!1,workStatusPanelFits:!1,workStatusOverlayOpen:!1,workStatusHiddenSections:[],workStatusSectionOrder:Oo([]),workStatusHiddenSectionsExplicit:!1,isSessionSwitcherOpen:!1,isSessionDropdownOpen:!1,pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null,pendingFileNavigation:null,pendingFileFocusPath:null,isMobile:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isOpenCodeStatusDialogOpen:!1,openCodeStatusText:"",isSessionCreateDialogOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,openGuestPageId:null,worktreesPageProjectId:null,isSettingsDialogOpen:!1,isNewWorktreeDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",settingsPage:"home",settingsHasOpenedOnce:!1,settingsProjectsSelectedId:null,settingsProjectPath:null,settingsRemoteInstancesSelectedId:null,eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!0,streamingAutoFollowEnabled:!0,sessionRecapEnabled:!0,sessionSuggestionEnabled:!0,sessionGoalEnabled:!0,sessionGoalDefaultBudgetEnabled:!1,sessionGoalDefaultBudget:2e5,collapsibleThinkingBlocks:!0,chatRenderMode:"live",activityRenderMode:"summary",showDeletionDialog:!0,autoDeleteEnabled:!1,autoSaveEnabled:!0,autoDeleteAfterDays:30,sessionRetentionAction:"archive",sessionRetentionOnlyArchived:!1,autoDeleteLastRunAt:null,messageLimit:200,fontSize:100,globalDraftStarters:null,terminalFontSize:14,terminalShell:"auto",terminalLoginShells:[],editorFontSize:13,uiFont:Uh,monoFont:jh,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:$h(),favoriteModels:[],hiddenModels:[],providerOrder:[],collapsedModelProviders:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,walkthroughTocWidth:224,gitChangesViewMode:"flat",toolJsonViewMode:"summary",linearIssueListStatus:"all",linearIssueListAssignee:"any",linearIssueListTeamId:pt,linearIssueListTeamIdByRuntime:{},linearIssueListPriority:"all",linearIssueFocus:null,isTimelineDialogOpen:!1,isPromptNavigatorPanelOpen:!1,isImagePreviewOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",notifyOnSubtasks:!0,dockBadgeEnabled:!0,alwaysShowScrollbars:!1,notifyOnCompletion:!0,notifyOnError:!0,notifyOnQuestion:!0,notificationTemplates:{completion:{...vt.completion},error:{...vt.error},question:{...vt.question},subtask:{...vt.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,sessionTabsEnabled:!1,persistChatDraft:!0,showOpenCodeUpdateNotifications:!rf(),agentControlToolEnabled:!0,agentWebToolEnabled:!0,browserProvider:"builtin",agentMemoryToolEnabled:!1,agentMemoryFeatureAvailable:!1,routingFeatureAvailable:!1,agentMemoryViewedAt:{},projectContextSidebarWidth:168,projectContextTab:"notes",inputSpellcheckEnabled:!1,largeTextPasteBehavior:Bl,enterToSend:!1,enterToSendConfigured:!1,wideChatLayoutEnabled:!1,codeBlockLineWrap:!0,showToolFileIcons:!0,showTurnChangedFiles:!1,showExpandedBashTools:!1,showExpandedEditTools:!1,timeFormatPreference:"auto",weekStartPreference:"auto",desktopWindowControlsPosition:"right",desktopWindowControlsStyle:"classic",mermaidRenderingMode:"svg",userMessageRenderingMode:"markdown",collapsibleUserMessages:!0,stickyUserHeader:!1,promptNavigatorEnabled:!0,showSplitAssistantMessageActions:!1,allowPromptingSubagentSessions:!1,draftStartersVisible:!0,isExpandedInput:!1,reportUsage:!0,shortcutOverrides:{},fileEditorKeymap:"default",setTheme:n=>{e({theme:n}),t().applyTheme()},toggleSidebar:()=>{e(n=>({isSidebarOpen:!n.isSidebarOpen}))},setSidebarOpen:n=>{e(r=>r.isSidebarOpen===n?r:{isSidebarOpen:n})},setSidebarWidth:n=>{e({sidebarWidth:n})},setContextRailOrder:n=>{const r=Array.isArray(n)?n.filter((s,o)=>typeof s=="string"&&s.trim()!==""&&n.indexOf(s)===o):[];e({contextRailOrder:r})},toggleContextEditorTree:()=>{e(n=>n.contextEditorTreeVisible&&!n.contextEditorVisible?{contextEditorTreeVisible:!1,contextEditorVisible:!0}:{contextEditorTreeVisible:!n.contextEditorTreeVisible})},toggleContextEditor:()=>{e(n=>n.contextEditorVisible&&!n.contextEditorTreeVisible?{contextEditorVisible:!1,contextEditorTreeVisible:!0}:{contextEditorVisible:!n.contextEditorVisible})},setContextEditorTreeWidth:n=>{Number.isFinite(n)&&e({contextEditorTreeWidth:hm(n)})},openContextSurface:(n,r)=>{const s=he((n||"").trim());if(!s)return;const o=t(),i=o.contextPanelByDirectory[s],a=i?.tabs??[],c=a.find(d=>d.id===i?.activeTabId)??null,l=()=>{if(r==="terminal"){const f=(a.find(p=>p.mode==="terminal")??null)?.targetDirectory??null;if(f){const p=Xr.getState().getDirectoryState(f);if(Gh(p))return}o.openContextPanelTab(s,{mode:"terminal",targetDirectory:null},{reveal:!1})}};if(i?.isOpen&&c?.mode===r){l(),o.closeContextPanel(s);return}r==="file"&&!o.contextEditorTreeVisible&&e({contextEditorTreeVisible:!0});const u=a.filter(d=>d.mode===r);if(u.length>0){l();const d=u.reduce((f,p)=>p.touchedAt>=f.touchedAt?p:f);o.setActiveContextPanelTab(s,d.id);return}r!=="chat"&&o.openContextPanelTab(s,{mode:r})},openContextPanelTab:(n,r,s)=>{const o=he((n||"").trim());if(!o)return;const i=r.mode==="terminal"?{...r,targetDirectory:ws(r.targetDirectory)===o?null:ws(r.targetDirectory)}:r,a=i.mode==="file"&&!!i.targetPath&&s?.reveal!==!1;e(c=>{const l=c.contextPanelByDirectory[o],u=Ht(l),d={...c.contextPanelByDirectory,[o]:Pm(u,i,s)};return{contextPanelByDirectory:zt(d,20),contextEditorVisible:a||c.contextEditorVisible}})},openContextDiff:(n,r,s=!1,o=null)=>{const i=he((n||"").trim()),a=(r||"").trim();if(!i||!a)return;const c=Si(o)??(s?"staged":"working");t().openContextPanelTab(i,{mode:"diff",targetPath:a,stagedDiff:c==="staged",diffScope:c})},openContextFile:(n,r)=>{const s=he((n||"").trim()),o=lr(r);!s||!o||(t().openContextPanelTab(s,{mode:"file",targetPath:o}),t().setPendingFileFocusPath(o),t().setPendingFileNavigation(null))},openContextFileAtLine:(n,r,s,o)=>{const i=he((n||"").trim()),a=lr(r),c=Number.isFinite(s)?Math.max(1,Math.trunc(s)):1,l=Number.isFinite(o)?Math.max(1,Math.trunc(o)):1;!i||!a||(t().openContextPanelTab(i,{mode:"file",targetPath:a}),t().setPendingFileFocusPath(null),t().setPendingFileNavigation({path:a,line:c,column:l}))},openContextOverview:n=>{const r=he((n||"").trim());r&&t().openContextPanelTab(r,{mode:"context"})},openContextPreview:(n,r)=>{const s=he((n||"").trim()),o=(r||"").trim();!s||!o||Le()||t().openContextPanelTab(s,{mode:"browser",targetPath:o,dedupeKey:o,label:null})},openNewContextBrowserTab:n=>{const r=he((n||"").trim());!r||Le()||(Wa+=1,t().openContextPanelTab(r,{mode:"browser",targetPath:"",dedupeKey:`browser:new:${Date.now()}-${Wa}`,label:null}))},openContextBrowser:(n,r="",s)=>{const o=he((n||"").trim());if(!o||Le())return;const i=typeof r=="string"&&r.trim().length>0?r.trim():"";t().openContextPanelTab(o,{mode:"browser",targetPath:i,dedupeKey:i||"browser",label:null},s)},setContextPanelTabTargetPath:(n,r,s)=>{const o=he((n||"").trim()),i=(r||"").trim();!o||!i||e(a=>{const c=a.contextPanelByDirectory[o];return c?{contextPanelByDirectory:{...a.contextPanelByDirectory,[o]:xm(c,i,s)}}:a})},setActiveContextPanelTab:(n,r)=>{const s=he((n||"").trim()),o=(r||"").trim();!s||!o||e(i=>{const a=i.contextPanelByDirectory[s],c=Ht(a),l=c.tabs.find(f=>f.id===o);if(!l)return i;const u=l.mode==="file"&&!!l.targetPath;if(c.activeTabId===o&&c.isOpen)return u?{contextEditorVisible:!0}:i;const d={...i.contextPanelByDirectory,[s]:{...c,isOpen:!0,activeTabId:o,touchedAt:Date.now(),tabs:c.tabs.map(f=>f.id===o?{...f,touchedAt:Date.now()}:f)}};return{contextPanelByDirectory:zt(d,20),contextEditorVisible:u||i.contextEditorVisible}})},reorderContextPanelTabs:(n,r,s)=>{const o=he((n||"").trim()),i=(r||"").trim(),a=(s||"").trim();!o||!i||!a||e(c=>{const l=c.contextPanelByDirectory[o],u=Ht(l);if(!u.tabs.some(p=>p.id===i)||!u.tabs.some(p=>p.id===a))return c;const d=Im(u,i,a);if(d.tabs===u.tabs)return c;const f={...c.contextPanelByDirectory,[o]:d};return{contextPanelByDirectory:zt(f,20)}})},closeContextPanelTab:(n,r)=>{t().closeContextPanelTabs(n,[r])},closeContextPanelTabs:(n,r)=>{const s=he((n||"").trim()),o=(r??[]).map(a=>(a||"").trim()).filter(a=>a.length>0);if(!s||o.length===0)return;const i=o.map(a=>t().contextPanelByDirectory[s]?.tabs.find(c=>c.id===a)).filter(a=>!!a);e(a=>{const c=a.contextPanelByDirectory[s],l=Ht(c);if(!l.tabs.some(y=>o.includes(y.id)))return a;const u=Am(l,o),d=u.tabs.find(y=>y.id===u.activeTabId),f=u.isOpen&&d?.mode==="file"&&!d.targetPath,p={...a.contextPanelByDirectory,[s]:u};return{contextPanelByDirectory:zt(p,20),contextEditorTreeVisible:f||a.contextEditorTreeVisible}});for(const a of i)a.mode==="file"&&a.targetPath&&am.getState().removeOpenPath(s,a.targetPath)},closeContextPanel:n=>{const r=he((n||"").trim());r&&e(s=>{const o=s.contextPanelByDirectory[r];if(!o||!o.isOpen)return s;const i={...s.contextPanelByDirectory,[r]:{...Ht(o),isOpen:!1}};return{contextPanelByDirectory:zt(i,20)}})},toggleContextPanelExpanded:n=>{const r=he((n||"").trim());r&&e(s=>{const o=s.contextPanelByDirectory[r],i=Ht(o),a={...s.contextPanelByDirectory,[r]:{...i,expanded:!i.expanded}};return{contextPanelByDirectory:zt(a,20)}})},setContextPanelWidth:(n,r,s,o)=>{const i=he((n||"").trim());i&&e(a=>{const c=a.contextPanelByDirectory[i],l=Ht(c),u=$l(s),d={...l.widthFractionByMode};o!==void 0&&Number.isFinite(o)&&o>0?d[r]=Math.min(1,u/o):delete d[r];const f={...a.contextPanelByDirectory,[i]:{...l,widthByMode:{...l.widthByMode,[r]:u},widthFractionByMode:d}};return{contextPanelByDirectory:zt(f,20)}})},setNotesPanelHeight:n=>{e({notesPanelHeight:n})},setWorkStatusSectionExpanded:(n,r)=>{e(s=>s.workStatusExpandedSections[n]===r?s:{workStatusExpandedSections:{...s.workStatusExpandedSections,[n]:r}})},setMessageQueueExpanded:n=>{e(r=>r.messageQueueExpanded===n?r:{messageQueueExpanded:n})},setWorkStatusScrollTop:n=>{e({workStatusScrollTop:Math.max(0,n)})},setWorkStatusPanelEnabled:n=>{e({workStatusPanelEnabled:n})},setWorkStatusPanelVisible:n=>{e(r=>r.workStatusPanelVisible===n?r:{workStatusPanelVisible:n})},setWorkStatusPanelFits:n=>{e(r=>r.workStatusPanelFits===n?r:n?{workStatusPanelFits:!0,workStatusOverlayOpen:!1}:{workStatusPanelFits:!1})},setWorkStatusOverlayOpen:n=>{e(r=>r.workStatusOverlayOpen===n?r:{workStatusOverlayOpen:n})},setWorkStatusSectionVisible:(n,r)=>{e(s=>{const o=s.workStatusHiddenSections,i=o.includes(n);return r===!i?s:{workStatusHiddenSectionsExplicit:!0,workStatusHiddenSections:r?o.filter(a=>a!==n):[...o,n]}})},setWorkStatusHiddenSections:n=>{e({workStatusHiddenSections:[...new Set(n)],workStatusHiddenSectionsExplicit:!0})},setWorkStatusSectionOrder:n=>{e({workStatusSectionOrder:Oo(n)})},setContextRailSurfaceVisible:(n,r)=>{e(s=>{const o=s.contextRailHiddenSurfaces,i=o.includes(n);return r===!i?s:{contextRailHiddenSurfaces:r?o.filter(a=>a!==n):[...o,n]}})},setContextRailHiddenSurfaces:n=>{e({contextRailHiddenSurfaces:[...new Set(n)]})},setSessionSwitcherOpen:n=>{t().isSessionSwitcherOpen!==n&&e({isSessionSwitcherOpen:n})},setSessionDropdownOpen:n=>{t().isSessionDropdownOpen!==n&&e({isSessionDropdownOpen:n})},setPendingDiffFile:(n,r=!1,s=null)=>{e({pendingDiffFile:n,pendingDiffStaged:n?r:!1,pendingDiffScope:n?s:null})},setPendingFileNavigation:n=>{e({pendingFileNavigation:n})},setPendingFileFocusPath:n=>{e({pendingFileFocusPath:n})},navigateToDiff:(n,r=!1,s=null)=>{e({pendingDiffFile:n,pendingDiffStaged:r,pendingDiffScope:s})},consumePendingDiffFile:()=>{const{pendingDiffFile:n}=t();return n&&e({pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null}),n},setIsMobile:n=>{e({isMobile:n})},toggleCommandPalette:()=>{e(n=>({isCommandPaletteOpen:!n.isCommandPaletteOpen}))},setCommandPaletteOpen:n=>{e({isCommandPaletteOpen:n})},toggleHelpDialog:()=>{e(n=>({isHelpDialogOpen:!n.isHelpDialogOpen}))},setHelpDialogOpen:n=>{e({isHelpDialogOpen:n})},setAboutDialogOpen:n=>{e({isAboutDialogOpen:n})},setOpenCodeStatusDialogOpen:n=>{e({isOpenCodeStatusDialogOpen:n})},setOpenCodeStatusText:n=>{e({openCodeStatusText:n})},setSessionCreateDialogOpen:n=>{e({isSessionCreateDialogOpen:n})},setScheduledTasksDialogOpen:n=>{e(n?{isScheduledTasksDialogOpen:!0,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1,openGuestPageId:null}:{isScheduledTasksDialogOpen:!1})},setArchivePageOpen:n=>{e(n?{isArchivePageOpen:!0,isUsageStatsPageOpen:!1,isScheduledTasksDialogOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1,openGuestPageId:null}:{isArchivePageOpen:!1})},setUsageStatsPageOpen:n=>{e(n?{isUsageStatsPageOpen:!0,isArchivePageOpen:!1,isScheduledTasksDialogOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1,openGuestPageId:null}:{isUsageStatsPageOpen:!1})},setWorktreesPageProjectId:n=>{e(n?{worktreesPageProjectId:n,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,isMultiRunLauncherOpen:!1,openGuestPageId:null}:{worktreesPageProjectId:null})},setOpenGuestPage:n=>{e(n?{openGuestPageId:n,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1}:{openGuestPageId:null})},closeMainSurfaces:()=>{const n=t();!n.isScheduledTasksDialogOpen&&!n.isArchivePageOpen&&!n.isUsageStatsPageOpen&&!n.worktreesPageProjectId&&!n.isMultiRunLauncherOpen&&!n.openGuestPageId||e({isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",openGuestPageId:null})},setSettingsDialogOpen:n=>{e(r=>n?r.settingsHasOpenedOnce?{isSettingsDialogOpen:!0}:{isSettingsDialogOpen:!0,settingsHasOpenedOnce:!0}:{isSettingsDialogOpen:!1})},setNewWorktreeDialogOpen:n=>{e({isNewWorktreeDialogOpen:n})},setModelSelectorOpen:n=>{e({isModelSelectorOpen:n})},setSidebarSection:n=>{e({sidebarSection:n})},setSettingsPage:n=>{e({settingsPage:n})},setSettingsProjectPath:n=>{const r=n?.trim();e({settingsProjectPath:r||null})},setSettingsProjectsSelectedId:n=>{e({settingsProjectsSelectedId:n})},setSettingsRemoteInstancesSelectedId:n=>{e({settingsRemoteInstancesSelectedId:n})},setEventStreamStatus:(n,r)=>{e({eventStreamStatus:n,eventStreamHint:r??null})},setShowReasoningTraces:n=>{e({showReasoningTraces:n})},setStreamingAutoFollowEnabled:n=>{e({streamingAutoFollowEnabled:n})},setSessionRecapEnabled:n=>{e({sessionRecapEnabled:n})},setSessionSuggestionEnabled:n=>{e({sessionSuggestionEnabled:n})},setSessionGoalEnabled:n=>{e({sessionGoalEnabled:n})},setSessionGoalDefaultBudgetEnabled:n=>{e({sessionGoalDefaultBudgetEnabled:n})},setSessionGoalDefaultBudget:n=>{e({sessionGoalDefaultBudget:n})},setCollapsibleThinkingBlocks:n=>{e({collapsibleThinkingBlocks:n})},setChatRenderMode:n=>{e({chatRenderMode:n})},setActivityRenderMode:n=>{e({activityRenderMode:n})},setShowDeletionDialog:n=>{e({showDeletionDialog:n})},setAutoDeleteEnabled:n=>{e({autoDeleteEnabled:n})},setAutoSaveEnabled:n=>{e({autoSaveEnabled:n})},setAutoDeleteAfterDays:n=>{const r=Math.max(1,Math.min(365,n));e({autoDeleteAfterDays:r})},setSessionRetentionAction:n=>{e(r=>({sessionRetentionAction:r.sessionRetentionOnlyArchived?"delete":n}))},setSessionRetentionOnlyArchived:n=>{e(r=>({sessionRetentionOnlyArchived:n,sessionRetentionAction:n?"delete":r.sessionRetentionAction}))},setAutoDeleteLastRunAt:n=>{e({autoDeleteLastRunAt:n})},setMessageLimit:n=>{const r=Math.max(10,Math.min(500,Math.round(n)));e({messageLimit:r})},setFontSize:n=>{const r=Math.max(50,Math.min(200,n));e({fontSize:r}),t().applyTypography()},setGlobalDraftStarters:n=>{e({globalDraftStarters:n})},setDraftStartersVisible:n=>{e({draftStartersVisible:n})},setTerminalFontSize:n=>{const r=Math.round(n),s=Math.max(9,Math.min(52,r));e({terminalFontSize:s})},setTerminalShell:n=>{e({terminalShell:n})},setTerminalLoginShells:n=>{e({terminalLoginShells:[...new Set(n)]})},setEditorFontSize:n=>{const r=Math.round(n),s=Math.max(9,Math.min(32,r));e({editorFontSize:s})},setUiFont:n=>{e({uiFont:n})},setMonoFont:n=>{e({monoFont:n})},setPadding:n=>{const r=Math.max(50,Math.min(200,n));e({padding:r}),t().applyPadding()},setCornerRadius:n=>{e({cornerRadius:n})},applyTypography:()=>{const{fontSize:n}=t(),r=document.documentElement,s=n/100,o=Object.entries(Mh);if(s===1){r.style.removeProperty("font-size");for(const[i]of o)r.style.removeProperty(Ra(i));return}r.style.fontSize=`${s*100}%`;for(const[i]of o)r.style.removeProperty(Ra(i))},applyPadding:()=>{const{padding:n}=t(),r=document.documentElement,s=n/100;if(s===1){r.style.removeProperty("--padding-scale"),r.style.removeProperty("--line-height-tight"),r.style.removeProperty("--line-height-normal"),r.style.removeProperty("--line-height-relaxed"),r.style.removeProperty("--line-height-loose");return}const o=Math.sqrt(s);r.style.setProperty("--padding-scale",o.toString());const i=1+(s-1)*.15;r.style.setProperty("--line-height-tight",(1.25*i).toFixed(3)),r.style.setProperty("--line-height-normal",(1.5*i).toFixed(3)),r.style.setProperty("--line-height-relaxed",(1.625*i).toFixed(3)),r.style.setProperty("--line-height-loose",(2*i).toFixed(3))},setDiffLayoutPreference:n=>{e({diffLayoutPreference:n})},setDiffFileLayout:(n,r)=>{e(s=>({diffFileLayout:{...s.diffFileLayout,[n]:r}}))},setDiffWrapLines:n=>{e({diffWrapLines:n})},setWalkthroughTocWidth:n=>{e({walkthroughTocWidth:Math.round(n)})},setGitChangesViewMode:n=>{e({gitChangesViewMode:n})},setToolJsonViewMode:n=>{e({toolJsonViewMode:n})},setLinearIssueListStatus:n=>{e({linearIssueListStatus:Na(n)})},setLinearIssueListAssignee:n=>{e({linearIssueListAssignee:Ba(n)})},setLinearIssueListTeamId:n=>{const r=Hl(n);e(s=>({linearIssueListTeamId:r,linearIssueListTeamIdByRuntime:Ha(s.linearIssueListTeamIdByRuntime,r)}))},applyLinearIssueListFiltersForRuntime:()=>{const n=W();e(r=>({linearIssueListTeamId:qc(n)?pt:r.linearIssueListTeamIdByRuntime[n]??pt}))},setLinearIssueListPriority:n=>{e({linearIssueListPriority:za(n)})},resetLinearIssueListFilters:()=>{e(n=>({linearIssueListStatus:"all",linearIssueListAssignee:"any",linearIssueListTeamId:pt,linearIssueListTeamIdByRuntime:Ha(n.linearIssueListTeamIdByRuntime,pt),linearIssueListPriority:"all"}))},setLinearIssueFocus:n=>{const r=n?.trim()??"";e({linearIssueFocus:r||null})},setInputBarOffset:n=>{e({inputBarOffset:n})},setMobileKeyboardMode:n=>{e(r=>r.mobileKeyboardMode===n?r:{mobileKeyboardMode:n})},toggleFavoriteModel:(n,r)=>{e(s=>s.favoriteModels.some(i=>i.providerID===n&&i.modelID===r)?{favoriteModels:s.favoriteModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{favoriteModels:[{providerID:n,modelID:r},...s.favoriteModels]})},reorderFavoriteModel:(n,r,s,o)=>{e(i=>{const a=i.favoriteModels.findIndex(d=>d.providerID===n&&d.modelID===r),c=i.favoriteModels.findIndex(d=>d.providerID===s&&d.modelID===o);if(a===-1||c===-1||a===c)return i;const l=i.favoriteModels.slice(),[u]=l.splice(a,1);return u?(l.splice(c,0,u),{favoriteModels:l}):i})},setProviderOrder:n=>{e(r=>{const s=n.filter(i=>typeof i=="string"&&i.length>0),o=r.providerOrder;return o.length===s.length&&o.every((i,a)=>i===s[a])?r:{providerOrder:s}})},toggleHiddenModel:(n,r)=>{e(s=>s.hiddenModels.some(i=>i.providerID===n&&i.modelID===r)?{hiddenModels:s.hiddenModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{hiddenModels:[{providerID:n,modelID:r},...s.hiddenModels]})},isHiddenModel:(n,r)=>{const{hiddenModels:s}=t();return s.some(o=>o.providerID===n&&o.modelID===r)},hideAllModels:(n,r)=>{e(s=>{const o=s.hiddenModels.filter(a=>a.providerID!==n);return{hiddenModels:[...r.filter(a=>typeof a=="string"&&a.length>0).map(a=>({providerID:n,modelID:a})),...o]}})},showAllModels:n=>{e(r=>({hiddenModels:r.hiddenModels.filter(s=>s.providerID!==n)}))},toggleModelProviderCollapsed:n=>{const r=typeof n=="string"?n.trim():"";r&&e(s=>s.collapsedModelProviders.includes(r)?{collapsedModelProviders:s.collapsedModelProviders.filter(i=>i!==r)}:{collapsedModelProviders:[...s.collapsedModelProviders,r]})},setModelProvidersCollapsed:(n,r)=>{const s=Array.from(new Set(n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(Boolean)));s.length!==0&&e(o=>{const i=new Set(s),a=o.collapsedModelProviders.filter(c=>!i.has(c));return{collapsedModelProviders:r?[...a,...s]:a}})},isFavoriteModel:(n,r)=>{const{favoriteModels:s}=t();return s.some(o=>o.providerID===n&&o.modelID===r)},addRecentModel:(n,r)=>{e(s=>{const o=s.recentModels.filter(i=>!(i.providerID===n&&i.modelID===r));return{recentModels:[{providerID:n,modelID:r},...o].slice(0,5)}})},addRecentAgent:n=>{const r=typeof n=="string"?n.trim():"";r&&e(s=>{if(s.recentAgents.includes(r))return s;const o=s.recentAgents;return{recentAgents:[r,...o].slice(0,5)}})},addRecentEffort:(n,r,s)=>{const o=typeof n=="string"?n.trim():"",i=typeof r=="string"?r.trim():"";if(!o||!i)return;const a=`${o}/${i}`,c=typeof s=="string"&&s.trim().length>0?s.trim():"default";e(l=>{const u=l.recentEfforts[a]??[];if(u.includes(c))return l;const d=u;return{recentEfforts:{...l.recentEfforts,[a]:[c,...d].slice(0,5)}}})},applyTheme:()=>{const{theme:n}=t(),r=document.documentElement;if(r.classList.remove("light","dark"),n==="system"){const s=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";r.classList.add(s)}else r.classList.add(n)},setMultiRunLauncherOpen:n=>{e(r=>({isMultiRunLauncherOpen:n,multiRunLauncherPrefillPrompt:n?r.multiRunLauncherPrefillPrompt:"",...n?{isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null,openGuestPageId:null}:{}}))},openMultiRunLauncher:()=>{e({openGuestPageId:null,isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null})},openMultiRunLauncherWithPrompt:n=>{e({openGuestPageId:null,isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:n,isSessionSwitcherOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isUsageStatsPageOpen:!1,worktreesPageProjectId:null})},setTimelineDialogOpen:n=>{e({isTimelineDialogOpen:n})},setPromptNavigatorPanelOpen:n=>{e({isPromptNavigatorPanelOpen:n})},togglePromptNavigatorPanel:()=>{e(n=>({isPromptNavigatorPanelOpen:!n.isPromptNavigatorPanelOpen}))},setImagePreviewOpen:n=>{e({isImagePreviewOpen:n})},setNativeNotificationsEnabled:n=>{e({nativeNotificationsEnabled:n})},setNotificationMode:n=>{e({notificationMode:n})},setShowTerminalQuickKeysOnDesktop:n=>{e({showTerminalQuickKeysOnDesktop:n})},setSessionTabsEnabled:n=>{e({sessionTabsEnabled:n})},setNotifyOnSubtasks:n=>{e({notifyOnSubtasks:n})},setDockBadgeEnabled:n=>{e({dockBadgeEnabled:n})},setAlwaysShowScrollbars:n=>{e({alwaysShowScrollbars:n})},setNotifyOnCompletion:n=>{e({notifyOnCompletion:n})},setNotifyOnError:n=>{e({notifyOnError:n})},setNotifyOnQuestion:n=>{e({notifyOnQuestion:n})},setNotificationTemplates:n=>{e(r=>({notificationTemplates:typeof n=="function"?n(r.notificationTemplates):n}))},setSummarizeLastMessage:n=>{e({summarizeLastMessage:n})},setSummaryThreshold:n=>{e({summaryThreshold:n})},setSummaryLength:n=>{e({summaryLength:n})},setMaxLastMessageLength:n=>{e({maxLastMessageLength:n})},setPersistChatDraft:n=>{e({persistChatDraft:n})},setShowOpenCodeUpdateNotifications:n=>{e({showOpenCodeUpdateNotifications:n})},setAgentControlToolEnabled:n=>{e({agentControlToolEnabled:n})},setAgentWebToolEnabled:n=>{e({agentWebToolEnabled:n})},setBrowserProvider:n=>{e({browserProvider:n})},setAgentMemoryToolEnabled:n=>{e({agentMemoryToolEnabled:n})},setAgentMemoryFeatureAvailable:n=>{e({agentMemoryFeatureAvailable:n})},setRoutingFeatureAvailable:n=>{e({routingFeatureAvailable:n})},setProjectContextSidebarWidth:n=>{e({projectContextSidebarWidth:n})},markAgentMemoryViewed:(n,r)=>{e(s=>({agentMemoryViewedAt:r>(s.agentMemoryViewedAt[n]??0)?{...s.agentMemoryViewedAt,[n]:r}:s.agentMemoryViewedAt}))},setProjectContextTab:n=>{e({projectContextTab:n})},setInputSpellcheckEnabled:n=>{e({inputSpellcheckEnabled:n})},setLargeTextPasteBehavior:n=>{e({largeTextPasteBehavior:Ua(n)})},setEnterToSend:n=>{e({enterToSend:n})},setEnterToSendConfigured:n=>{e({enterToSendConfigured:n})},setWideChatLayoutEnabled:n=>{e({wideChatLayoutEnabled:n})},setCodeBlockLineWrap:n=>{e({codeBlockLineWrap:n})},setShowToolFileIcons:n=>{e({showToolFileIcons:n})},setShowTurnChangedFiles:n=>{e({showTurnChangedFiles:n})},setShowExpandedBashTools:n=>{e({showExpandedBashTools:n})},setShowExpandedEditTools:n=>{e({showExpandedEditTools:n})},setTimeFormatPreference:n=>{e({timeFormatPreference:n})},setWeekStartPreference:n=>{e({weekStartPreference:n})},setDesktopWindowControlsPosition:n=>{e({desktopWindowControlsPosition:n==="left"?"left":"right"})},setDesktopWindowControlsStyle:n=>{e({desktopWindowControlsStyle:n==="traffic-lights"?"traffic-lights":"classic"})},setMermaidRenderingMode:n=>{e({mermaidRenderingMode:n})},setUserMessageRenderingMode:n=>{e({userMessageRenderingMode:n})},setCollapsibleUserMessages:n=>{e({collapsibleUserMessages:n})},setStickyUserHeader:n=>{e({stickyUserHeader:n})},setPromptNavigatorEnabled:n=>{e({promptNavigatorEnabled:n})},setShowSplitAssistantMessageActions:n=>{e({showSplitAssistantMessageActions:n})},setAllowPromptingSubagentSessions:n=>{e({allowPromptingSubagentSessions:n})},setReportUsage:n=>{e({reportUsage:n})},viewPagerPage:"center",setViewPagerPage:n=>{e({viewPagerPage:n}),e({isSessionSwitcherOpen:n==="left"})},setShortcutOverride:(n,r)=>{e(s=>({shortcutOverrides:{...s.shortcutOverrides,[n]:r}}))},clearShortcutOverride:n=>{e(r=>{const s={...r.shortcutOverrides};return delete s[n],{shortcutOverrides:s}})},resetAllShortcutOverrides:()=>{e({shortcutOverrides:{}})},setFileEditorKeymap:n=>{e({fileEditorKeymap:ja(n)})},toggleExpandedInput:()=>{e(n=>({isExpandedInput:!n.isExpandedInput}))},setExpandedInput:n=>{e({isExpandedInput:n})}}),{name:"ui-store",storage:yi(),version:21,migrate:(e,t)=>{if(!e||typeof e!="object")return e;const n=e;if(t<21&&n.workStatusHiddenSectionsExplicit!==!0&&(n.workStatusHiddenSections=Array.isArray(n.workStatusHiddenSections)?n.workStatusHiddenSections.filter(r=>r!=="telemetry"):[],n.workStatusHiddenSectionsExplicit=!1),t<16&&(delete n.activeMainTab,delete n.activeSurface),t<17&&delete n.expandedEditorToolbar,t<18&&delete n.shortcutOverrides,t<14){const r=n.contextPanelByDirectory;if(r&&typeof r=="object")for(const s of Object.values(r)){if(!s||typeof s!="object")continue;const o=s,i=o.widthByMode;if(i&&typeof i=="object"){const l=i;l.preview!==void 0&&(l.browser===void 0&&(l.browser=l.preview),delete l.preview)}if(!Array.isArray(o.tabs))continue;const a=new Set,c=[];for(const l of o.tabs){if(!l||typeof l!="object")continue;const u=l;if(u.mode!=="preview"){typeof u.id=="string"&&a.add(u.id),c.push(u);continue}const d=typeof u.targetPath=="string"?u.targetPath:"",f=typeof u.dedupeKey=="string"&&u.dedupeKey.trim()?u.dedupeKey.trim():d||"browser",p=f==="browser"?"browser":`browser:${f}`;a.has(p)||(a.add(p),c.push({...u,mode:"browser",id:p,dedupeKey:f}))}if(o.tabs=c,typeof o.activeTabId=="string"&&o.activeTabId.startsWith("preview")){const l=c.find(u=>typeof u.id=="string");o.activeTabId=l&&typeof l.id=="string"?l.id:null}}}if(t<13&&typeof n.autoSaveEnabled!="boolean"){let r=!0;try{if(typeof localStorage<"u"){const s=localStorage.getItem("openchamber:files:auto-save-enabled");s!==null&&(r=s!=="false",localStorage.removeItem("openchamber:files:auto-save-enabled"))}}catch{r=!0}n.autoSaveEnabled=r}if(t<12&&(n.desktopWindowControlsPosition==="auto"||n.desktopWindowControlsPosition==null)&&(n.desktopWindowControlsPosition="right"),t<11&&n.terminalFontSize===13&&(n.terminalFontSize=14),t<10&&delete n.diffViewMode,t<9&&((!n.workStatusExpandedSections||typeof n.workStatusExpandedSections!="object")&&(n.workStatusExpandedSections={}),(typeof n.workStatusScrollTop!="number"||!Number.isFinite(n.workStatusScrollTop))&&(n.workStatusScrollTop=0),typeof n.workStatusPanelEnabled!="boolean"&&(n.workStatusPanelEnabled=!0),Array.isArray(n.workStatusHiddenSections)||(n.workStatusHiddenSections=[]),(typeof n.notesPanelHeight!="number"||!Number.isFinite(n.notesPanelHeight))&&(n.notesPanelHeight=112)),t<1&&wm(n.notificationTemplates)&&(n.notificationTemplates={completion:{...vt.completion},error:{...vt.error},question:{...vt.question},subtask:{...vt.subtask}}),t<3){const r=new Set([90,120,180,220]),s=n.memoryLimitHistorical,o=n.memoryLimitActiveSession;typeof s=="number"&&!r.has(s)?n.messageLimit=s:typeof o=="number"&&!r.has(o)&&(n.messageLimit=o),delete n.memoryLimitHistorical,delete n.memoryLimitViewport,delete n.memoryLimitActiveSession}if(delete n.isRightSidebarOpen,delete n.rightSidebarWidth,delete n.rightSidebarTab,n.contextPanelByDirectory=ao(n.contextPanelByDirectory),t<5)if(!n.shortcutOverrides||typeof n.shortcutOverrides!="object")n.shortcutOverrides={};else{const r=n.shortcutOverrides,s={};for(const[o,i]of Object.entries(r))typeof o=="string"&&typeof i=="string"&&(s[o]=i);n.shortcutOverrides=s}return t<6&&(n.contextPanelByDirectory=ao(n.contextPanelByDirectory)),t<7&&(n.contextPanelByDirectory=ao(n.contextPanelByDirectory)),t<8&&n.gitChangesViewMode!=="flat"&&n.gitChangesViewMode!=="tree"&&(n.gitChangesViewMode="flat"),n.linearIssueListStatus=Na(n.linearIssueListStatus),n.linearIssueListAssignee=Ba(n.linearIssueListAssignee),delete n.linearIssueListTeamId,n.linearIssueListTeamIdByRuntime=ym(n.linearIssueListTeamIdByRuntime),n.linearIssueListPriority=za(n.linearIssueListPriority),n.fileEditorKeymap=ja(n.fileEditorKeymap),n.largeTextPasteBehavior=Ua(n.largeTextPasteBehavior),n.toolJsonViewMode!=="summary"&&n.toolJsonViewMode!=="formatted"&&n.toolJsonViewMode!=="raw"&&(n.toolJsonViewMode="summary"),typeof n.autoSaveEnabled!="boolean"&&(n.autoSaveEnabled=!0),n.contextRailHiddenSurfaces=Array.isArray(n.contextRailHiddenSurfaces)?n.contextRailHiddenSurfaces.filter(r=>typeof r=="string"&&r.trim()!==""):[],n.contextRailOrder=Array.isArray(n.contextRailOrder)?n.contextRailOrder.filter(r=>typeof r=="string"&&r.trim()!==""):[],n},partialize:e=>({theme:e.theme,isSidebarOpen:e.isSidebarOpen,sidebarWidth:e.sidebarWidth,contextPanelByDirectory:e.contextPanelByDirectory,contextRailOrder:e.contextRailOrder,contextRailHiddenSurfaces:e.contextRailHiddenSurfaces,contextEditorTreeVisible:e.contextEditorTreeVisible,contextEditorVisible:e.contextEditorVisible,contextEditorTreeWidth:e.contextEditorTreeWidth,notesPanelHeight:e.notesPanelHeight,workStatusExpandedSections:e.workStatusExpandedSections,messageQueueExpanded:e.messageQueueExpanded,workStatusScrollTop:e.workStatusScrollTop,workStatusPanelEnabled:e.workStatusPanelEnabled,workStatusHiddenSections:e.workStatusHiddenSections,workStatusSectionOrder:e.workStatusSectionOrder,workStatusHiddenSectionsExplicit:e.workStatusHiddenSectionsExplicit,isSessionSwitcherOpen:e.isSessionSwitcherOpen,sidebarSection:e.sidebarSection,settingsPage:e.settingsPage,settingsHasOpenedOnce:e.settingsHasOpenedOnce,settingsProjectsSelectedId:e.settingsProjectsSelectedId,settingsRemoteInstancesSelectedId:e.settingsRemoteInstancesSelectedId,isSessionCreateDialogOpen:e.isSessionCreateDialogOpen,showReasoningTraces:e.showReasoningTraces,streamingAutoFollowEnabled:e.streamingAutoFollowEnabled,sessionRecapEnabled:e.sessionRecapEnabled,sessionSuggestionEnabled:e.sessionSuggestionEnabled,sessionGoalEnabled:e.sessionGoalEnabled,sessionGoalDefaultBudgetEnabled:e.sessionGoalDefaultBudgetEnabled,sessionGoalDefaultBudget:e.sessionGoalDefaultBudget,collapsibleThinkingBlocks:e.collapsibleThinkingBlocks,chatRenderMode:e.chatRenderMode,activityRenderMode:e.activityRenderMode,showDeletionDialog:e.showDeletionDialog,autoDeleteEnabled:e.autoDeleteEnabled,autoSaveEnabled:e.autoSaveEnabled,autoDeleteAfterDays:e.autoDeleteAfterDays,sessionRetentionAction:e.sessionRetentionAction,sessionRetentionOnlyArchived:e.sessionRetentionOnlyArchived,autoDeleteLastRunAt:e.autoDeleteLastRunAt,messageLimit:e.messageLimit,fontSize:e.fontSize,globalDraftStarters:e.globalDraftStarters,terminalFontSize:e.terminalFontSize,terminalShell:e.terminalShell,terminalLoginShells:e.terminalLoginShells,editorFontSize:e.editorFontSize,uiFont:e.uiFont,monoFont:e.monoFont,padding:e.padding,cornerRadius:e.cornerRadius,favoriteModels:e.favoriteModels,hiddenModels:e.hiddenModels,providerOrder:e.providerOrder,collapsedModelProviders:e.collapsedModelProviders,recentModels:e.recentModels,recentAgents:e.recentAgents,recentEfforts:e.recentEfforts,diffLayoutPreference:e.diffLayoutPreference,diffWrapLines:e.diffWrapLines,walkthroughTocWidth:e.walkthroughTocWidth,gitChangesViewMode:e.gitChangesViewMode,toolJsonViewMode:e.toolJsonViewMode,linearIssueListStatus:e.linearIssueListStatus,linearIssueListAssignee:e.linearIssueListAssignee,linearIssueListTeamIdByRuntime:e.linearIssueListTeamIdByRuntime,linearIssueListPriority:e.linearIssueListPriority,nativeNotificationsEnabled:e.nativeNotificationsEnabled,notificationMode:e.notificationMode,showTerminalQuickKeysOnDesktop:e.showTerminalQuickKeysOnDesktop,sessionTabsEnabled:e.sessionTabsEnabled,notifyOnSubtasks:e.notifyOnSubtasks,dockBadgeEnabled:e.dockBadgeEnabled,alwaysShowScrollbars:e.alwaysShowScrollbars,notifyOnCompletion:e.notifyOnCompletion,notifyOnError:e.notifyOnError,notifyOnQuestion:e.notifyOnQuestion,notificationTemplates:e.notificationTemplates,summarizeLastMessage:e.summarizeLastMessage,summaryThreshold:e.summaryThreshold,summaryLength:e.summaryLength,maxLastMessageLength:e.maxLastMessageLength,persistChatDraft:e.persistChatDraft,showOpenCodeUpdateNotifications:e.showOpenCodeUpdateNotifications,agentControlToolEnabled:e.agentControlToolEnabled,agentWebToolEnabled:e.agentWebToolEnabled,browserProvider:e.browserProvider,agentMemoryToolEnabled:e.agentMemoryToolEnabled,agentMemoryViewedAt:e.agentMemoryViewedAt,projectContextSidebarWidth:e.projectContextSidebarWidth,inputSpellcheckEnabled:e.inputSpellcheckEnabled,largeTextPasteBehavior:e.largeTextPasteBehavior,enterToSend:e.enterToSend,enterToSendConfigured:e.enterToSendConfigured,wideChatLayoutEnabled:e.wideChatLayoutEnabled,codeBlockLineWrap:e.codeBlockLineWrap,showToolFileIcons:e.showToolFileIcons,showTurnChangedFiles:e.showTurnChangedFiles,showExpandedBashTools:e.showExpandedBashTools,showExpandedEditTools:e.showExpandedEditTools,timeFormatPreference:e.timeFormatPreference,weekStartPreference:e.weekStartPreference,desktopWindowControlsPosition:e.desktopWindowControlsPosition,desktopWindowControlsStyle:e.desktopWindowControlsStyle,inputBarOffset:e.inputBarOffset,mermaidRenderingMode:e.mermaidRenderingMode,userMessageRenderingMode:e.userMessageRenderingMode,collapsibleUserMessages:e.collapsibleUserMessages,stickyUserHeader:e.stickyUserHeader,promptNavigatorEnabled:e.promptNavigatorEnabled,showSplitAssistantMessageActions:e.showSplitAssistantMessageActions,allowPromptingSubagentSessions:e.allowPromptingSubagentSessions,draftStartersVisible:e.draftStartersVisible,shortcutOverrides:e.shortcutOverrides,fileEditorKeymap:e.fileEditorKeymap})}),{name:"ui-store"})),Rm=e=>{if(!e||typeof e!="object")return null;const t={};return typeof e.showReasoningTraces=="boolean"&&(t.showReasoningTraces=e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&(t.collapsibleThinkingBlocks=e.collapsibleThinkingBlocks),Object.keys(t).length>0?t:null},Cm=e=>{if(!e||typeof e!="object")return null;const t=e;return{showReasoningTraces:t.showReasoningTraces,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks}},Om=e=>{const t=v.getState();typeof e.showReasoningTraces=="boolean"&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks)},Mm=async()=>{if(typeof window>"u")return null;const e=localStorage.getItem("appearance-preferences");if(!e)return null;try{const t=JSON.parse(e),n=Cm(t);return Rm(n)}catch(t){return console.warn("Failed to parse stored appearance preferences:",t),null}},Dm=768,_m=800,Lm=()=>{if(typeof window>"u")return!1;const e=typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)").matches||window.matchMedia("(hover: none)").matches:!1,t=typeof navigator<"u"?navigator.maxTouchPoints??0:0;return e||t>0},Fm=()=>{if(typeof window>"u")return!1;const e=new URLSearchParams(window.location.search).get("surface");return e==="mobile"||e==="desktop"},Jl=()=>{if(typeof window>"u")return!1;const e=Math.min(window.innerWidth||Number.POSITIVE_INFINITY,window.screen?.width||Number.POSITIVE_INFINITY);return Number.isFinite(e)&&e<=Dm&&Lm()},Yl=()=>{if(typeof window>"u")return"desktop";const e=window.__OPENCHAMBER_SURFACE__;if(e==="mobile"||e==="desktop")return e;const t=new URLSearchParams(window.location.search).get("surface");return t==="mobile"||t==="desktop"?t:hr()?"mobile":Be()||Le()?"desktop":Jl()?"mobile":"desktop"},fT=()=>{const e=Yl();return typeof window<"u"&&(window.__OPENCHAMBER_SURFACE__=e),e},Um=()=>Yl()==="mobile",pT=()=>{if(typeof window>"u")return()=>{};if(hr()||Be()||Le())return()=>{};if(Fm())return()=>{};let e=null;const t=()=>{e&&clearTimeout(e),e=setTimeout(()=>{e=null;const n=window.__OPENCHAMBER_SURFACE__,r=Jl()?"mobile":"desktop";n&&n!==r&&(window.__OPENCHAMBER_SURFACE__=void 0,window.location.reload())},_m)};return window.addEventListener("resize",t),()=>{e&&clearTimeout(e),window.removeEventListener("resize",t)}},Ql="surface",Ti=()=>{try{if(Le())return"vscode";if(Be())return"desktop";if(hr()||Um())return"mobile"}catch{}return"web"},jm=()=>Ti()==="mobile"?"timeline":"projects",Nm=(e,t)=>{const n=e??{};return t<2&&(n.projectSortOrder="manual"),t<3&&n.projectSortOrder==="recent"&&(n.projectSortOrder="manual"),t<4&&delete n.displayMode,t<6&&delete n.sessionGroupingMode,t<7&&delete n.stickyZoneHeaders,t<8&&(n.showRecentSection=!1),n},Mo=yt()(pr(e=>({animatedActivityIndicators:!1,setAnimatedActivityIndicators:t=>e({animatedActivityIndicators:t}),projectDisplayMode:"all",singleProjectId:null,setProjectDisplayMode:t=>e({projectDisplayMode:t}),setSingleProjectId:t=>e({singleProjectId:t}),sidebarViewMode:jm(),setSidebarViewMode:t=>e({sidebarViewMode:t}),showRecentSection:!1,showArchivedSessions:!1,projectSortOrder:"manual",setShowRecentSection:t=>e({showRecentSection:t}),setShowArchivedSessions:t=>e({showArchivedSessions:t}),toggleRecentSection:()=>e(t=>({showRecentSection:!t.showRecentSection})),toggleArchivedSessions:()=>e(t=>({showArchivedSessions:!t.showArchivedSessions})),setProjectSortOrder:t=>e({projectSortOrder:t})}),{name:"session-display-mode",version:8,migrate:Nm})),Xl="directoryTreeShowHidden",Do="directory-show-hidden-change",_o=()=>{if(typeof window>"u")return!0;try{const e=gr().getItem(Xl);return e===null?!0:e==="true"}catch{return!0}},Bm=()=>{typeof window>"u"||window.dispatchEvent(new Event(Do))},Hm=()=>_o(),zm=(e,t={})=>{if(!(typeof window>"u")){try{gr().setItem(Xl,e?"true":"false"),Bm()}catch{}t.persist!==!1&&ht({directoryShowHidden:e})}},hT=()=>{const e=Rc.c(2),[t,n]=ss.useState(_o);let r,s;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const o=()=>{n(_o())};return window.addEventListener("storage",o),window.addEventListener(Do,o),()=>{window.removeEventListener("storage",o),window.removeEventListener(Do,o)}},s=[],e[0]=r,e[1]=s):(r=e[0],s=e[1]),ss.useEffect(r,s),t},Zl=[{name:"explore",icon:"compass-3",labelKey:"chat.draftPresets.explore.label",command:"/explore"},{name:"catch-up",icon:"history",labelKey:"chat.draftPresets.catchup.label",command:"/catch-up"},{name:"weigh",icon:"scales-3",labelKey:"chat.draftPresets.weigh.label",command:"/weigh"},{name:"plan-feature",icon:"survey",labelKey:"chat.draftPresets.plan.label",command:"/plan-feature"},{name:"craft-goal",icon:"target",labelKey:"chat.draftPresets.craftGoal.label",command:"/craft-goal"},{name:"schedule-task",icon:"calendar-schedule",labelKey:"chat.draftPresets.scheduleTask.label",command:"/schedule-task"},{name:"debug",icon:"bug",labelKey:"chat.draftPresets.debug.label",command:"/debug"},{name:"review",icon:"search-eye",labelKey:"chat.draftPresets.review.label",command:"/workspace-review"}],$m=new Map(Zl.map(e=>[e.name,e])),mT=e=>$m.get(e),gT=Zl.map(e=>({type:"command",name:e.name})),yT="terminal-box",wT="book-open",bT=e=>`${e.type}:${e.name}`,ST=(e,t)=>e.type===t.type&&e.name===t.name,vT=e=>{const t=e.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},Wm=e=>{if(!Array.isArray(e))return[];const t=[],n=new Set;for(const r of e){if(!r||typeof r!="object")continue;const s=r,o=s.type==="command"||s.type==="skill"?s.type:null,i=typeof s.name=="string"?s.name.trim():"";if(!o||!i)continue;const a=`${o}:${i}`;n.has(a)||(n.add(a),t.push({type:o,name:i}))}return t},eu="filesViewShowGitignored",Lo="files-view-show-gitignored-change",Fo=()=>{if(typeof window>"u")return!1;try{return gr().getItem(eu)==="true"}catch{return!1}},Gm=()=>{typeof window>"u"||window.dispatchEvent(new Event(Lo))},qm=()=>Fo(),Km=(e,t={})=>{if(!(typeof window>"u")){try{gr().setItem(eu,e?"true":"false"),Gm()}catch{}t.persist!==!1&&ht({filesViewShowGitignored:e})}},TT=()=>{const e=Rc.c(2),[t,n]=ss.useState(Fo);let r,s;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const o=()=>{n(Fo())};return window.addEventListener("storage",o),window.addEventListener(Lo,o),()=>{window.removeEventListener("storage",o),window.removeEventListener(Lo,o)}},s=[],e[0]=r,e[1]=s):(r=e[0],s=e[1]),ss.useEffect(r,s),t},tu="session",nu=40,Vm=1,Jm=100,ru=e=>e==="global"||e==="session",ki=e=>e!=null&&Number.isInteger(e)&&e>=Vm&&e<=Jm,Ym=["bash","zsh","sh","fish","pwsh","powershell","cmd","dash","ksh","nu"],Ei=e=>e==="auto"||typeof e=="string"&&Ym.includes(e),bn="openchamber-input-history.v1",Qm=8,Xm=50,Zm=[40,25,10,5,1],co=Object.freeze([]);let dt=null,Ga=0;const Zn=(e=tu,t=nu)=>({entryLimit:t,scope:e,globalBuckets:{},sessionBuckets:{}}),su=()=>(Ga+=1,Date.now()*1e3+Ga),ou=e=>JSON.stringify([e]),Uo=(e,t,n)=>JSON.stringify([e,t,n]),Pi=()=>{try{return globalThis.window?.localStorage??null}catch{return null}},eg=()=>{const e=Pi(),t=qe?JSON.stringify(es(qe.base)):dt;if(!e)return t;try{return e.getItem(bn)??(qe?null:dt)}catch{return t}},qa=it(m(),me()),tg=T({key:m().min(1),source:Zt([N("file-url"),N("vscode-file")]),filename:m().min(1),mimeType:m().min(1),size:R().finite().nonnegative(),reference:m().min(1)}),ng=T({text:m(),attachmentKeys:G(m()),restorableAttachments:G(tg),submittedAt:R().finite().nonnegative()}),rg=T({touchedAt:R().finite().nonnegative(),entries:G(me())}),sg=(e,t)=>{try{const n=JSON.parse(e),s=(t===1?$i([m().trim().min(1)]):$i([m().trim().min(1),m().trim().min(1),m().trim().min(1)])).safeParse(n);if(!s.success)return null;if(t===3){const o=Ye(s.data[1]);if(!o||o!==s.data[1])return null}return s.data}catch{return null}},Ka=(e,t)=>{const n=[];for(const[r,s]of Object.entries(e)){if(!sg(r,t))continue;const o=rg.safeParse(s);if(!o.success)continue;const i=o.data.entries.map(a=>ng.safeParse(a)).filter(a=>a.success).map(a=>a.data);n.push([r,{touchedAt:o.data.touchedAt,entries:i}])}return Object.fromEntries(n)},og=()=>{const e=eg();if(e===null)return Zn();try{const t=JSON.parse(e),n=T({version:N(1),entryLimit:R().int().optional(),scope:Zt([N("global"),N("session")]).optional(),global:qa.default({}),session:qa.default({})}).safeParse(t);return n.success?{entryLimit:ki(n.data.entryLimit)?n.data.entryLimit:nu,scope:n.data.scope??tu,globalBuckets:Ka(n.data.global,1),sessionBuckets:Ka(n.data.session,3)}:Zn()}catch{const t=Pi();if(t)try{t.removeItem(bn)}catch{}return dt=null,Zn()}};let qe=null,Zr=Zn();const Va=(e,t,n)=>{const r={...e};for(const s of new Set([...Object.keys(t),...Object.keys(n)])){if(JSON.stringify(t[s])===JSON.stringify(n[s]))continue;const o=n[s];if(!o){delete r[s];continue}const i=new Set((t[s]?.entries??[]).map(u=>JSON.stringify(u))),a=new Set(o.entries.map(u=>JSON.stringify(u))),c=(e[s]?.entries??[]).filter(u=>{const d=JSON.stringify(u);return!i.has(d)||a.has(d)}),l=new Set(c.map(u=>JSON.stringify(u)));for(const u of o.entries){const d=JSON.stringify(u);!i.has(d)&&!l.has(d)&&c.push(u)}c.sort((u,d)=>u.submittedAt-d.submittedAt),r[s]={touchedAt:Math.max(o.touchedAt,e[s]?.touchedAt??0),entries:c}}return r},Gn=()=>{const e=og();if(Zr=e,!qe)return e;const{base:t,value:n}=qe;return jo({entryLimit:n.entryLimit===t.entryLimit?e.entryLimit:n.entryLimit,scope:n.scope===t.scope?e.scope:n.scope,globalBuckets:Va(e.globalBuckets,t.globalBuckets,n.globalBuckets),sessionBuckets:Va(e.sessionBuckets,t.sessionBuckets,n.sessionBuckets)})},iu=(e,t)=>e.slice(Math.max(0,e.length-t)),Ja=(e,t,n)=>{const r=Object.entries(e).map(([s,o])=>[s,{touchedAt:o.touchedAt,entries:iu(o.entries,n)}]).sort((s,o)=>o[1].touchedAt-s[1].touchedAt).slice(0,t);return Object.fromEntries(r)},jo=(e,t=e.entryLimit)=>({entryLimit:e.entryLimit,scope:e.scope,globalBuckets:Ja(e.globalBuckets,Qm,t),sessionBuckets:Ja(e.sessionBuckets,Xm,t)}),es=e=>({version:1,entryLimit:e.entryLimit,scope:e.scope,global:e.globalBuckets,session:e.sessionBuckets}),Ya=e=>e instanceof DOMException?e.name==="QuotaExceededError":e instanceof Error&&/quota/i.test(e.message),qn=e=>{const t=jo(e),n=JSON.stringify(es(t));qe={base:Zr,value:t};const r=Pi();if(!r)return dt=n,t;try{return r.setItem(bn,n),qe=null,dt=n,t}catch(i){if(!(i instanceof Error)||!Ya(i))return dt=n,t}try{r.removeItem(bn)}catch{}for(const i of Zm){const a=jo(t,i),c=JSON.stringify(es(a));try{return r.setItem(bn,c),qe=null,dt=c,a}catch(l){if(!(l instanceof Error)||!Ya(l))return qe={base:Zr,value:a},dt=c,a}}const s=Zn(t.scope,t.entryLimit),o=JSON.stringify(es(s));try{r.setItem(bn,o),qe=null}catch{qe={base:Zr,value:s}}return dt=o,s},ig=(e,t,n)=>{const r=e.trim(),s=Ye(t),o=n.trim();return!r||!s||!o?null:{runtimeKey:r,directory:s,sessionId:o}},au=e=>e.source==="vscode"&&e.vscodeSource==="file"?Ye(e.vscodePath??null):e.dataUrl.trim()||null,ag=e=>!(!e||e.startsWith("data:")||(e.startsWith("http://")||e.startsWith("https://"))&&e.includes("?")),No=e=>{const t=au(e),n=t===null?"none":t.startsWith("data:")?"data":t.slice(0,512);return[e.source,e.filename,e.mimeType,String(e.size),n].join("|")},cg=e=>{const t=au(e);return!t||!ag(t)?null:e.source==="vscode"&&e.vscodeSource==="file"?{key:No(e),source:"vscode-file",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}:{key:No(e),source:"file-url",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}},lg=(e,t)=>({text:e,attachmentKeys:t.map(No),restorableAttachments:t.map(cg).filter(n=>n!==null)}),ug=(e,t)=>e.length===t.length&&e.every((n,r)=>{const s=t[r];return s!==void 0&&n.key===s.key&&n.source===s.source&&n.filename===s.filename&&n.mimeType===s.mimeType&&n.size===s.size&&n.reference===s.reference}),dg=(e,t)=>e!==void 0&&e.text===t.text&&e.attachmentKeys.length===t.attachmentKeys.length&&e.attachmentKeys.every((n,r)=>n===t.attachmentKeys[r])&&ug(e.restorableAttachments,t.restorableAttachments),Qa=(e,t,n,r)=>{const s=e?[...e.entries]:[];for(const o of t){const i=s.at(-1);dg(i,o)||s.push({text:o.text,attachmentKeys:[...o.attachmentKeys],restorableAttachments:o.restorableAttachments.map(a=>({...a})),submittedAt:su()})}return{touchedAt:n,entries:iu(s,r)}},fg=qn(Gn()),Kn=yt(e=>({...fg,applyEntryLimit:t=>{ki(t)&&e(n=>{const r=Gn();if(r.entryLimit===t)return{...n,...r};const s=qn({entryLimit:t,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...s}})},applyScope:t=>{ru(t)&&e(n=>{const r=Gn();if(r.scope===t)return{...n,...r};const s=qn({entryLimit:r.entryLimit,scope:t,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...s}})},appendSubmissions:(t,n)=>{n.length!==0&&e(r=>{const s=Gn(),o=su(),i=ou(t.runtimeKey),a=Uo(t.runtimeKey,t.directory,t.sessionId),c=qn({entryLimit:s.entryLimit,scope:s.scope,globalBuckets:{...s.globalBuckets,[i]:Qa(s.globalBuckets[i],n,o,s.entryLimit)},sessionBuckets:{...s.sessionBuckets,[a]:Qa(s.sessionBuckets[a],n,o,s.entryLimit)}});return{...r,...c}})},clearSession:t=>{e(n=>{const r=Gn(),s=Uo(t.runtimeKey,t.directory,t.sessionId);if(!(s in r.sessionBuckets))return{...n,...r};const o={...r.sessionBuckets};delete o[s];const i=qn({entryLimit:r.entryLimit,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:o});return{...n,...i}})}})),kT=(e,t)=>t?e.scope==="session"?e.sessionBuckets[Uo(t.runtimeKey,t.directory,t.sessionId)]?.entries??co:e.globalBuckets[ou(t.runtimeKey)]?.entries??co:co,pg=/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/,hg=e=>{const t=e.terminalId.trim(),n=e.terminalLabel.trim(),r=e.text.replace(/\r\n?/g,`
|
|
4
|
+
`).replace(/^\n+|\n+$/g,"");if(!t||!n||!r)return null;const s=Math.max(1,Math.floor(e.startLine));return{terminalId:t,terminalLabel:n,startLine:s,endLine:Math.max(s,Math.floor(e.endLine)),text:r}},mg=(e,t)=>{const n=t.map(hg).filter(o=>o!==null);if(n.length===0)return e;const s=["<terminal_context>",...n.flatMap((o,i)=>[`- ${o.terminalLabel} lines ${o.startLine}-${o.endLine}:`,...o.text.split(`
|
|
5
|
+
`).map((a,c)=>` ${o.startLine+c} | ${a}`),...i===n.length-1?[]:[""]]),"</terminal_context>"].join(`
|
|
6
|
+
`);return e.trim()?`${e.trim()}
|
|
7
|
+
|
|
8
|
+
${s}`:s},ET=e=>{const t=pg.exec(e);if(!t)return{visibleText:e,contexts:[]};const n=[];let r=null;for(const s of(t[1]??"").split(`
|
|
9
|
+
`)){const o=/^- (.+) lines (\d+)-(\d+):$/.exec(s);if(o){r&&n.push(r),r={terminalLabel:o[1],startLine:Number(o[2]),endLine:Number(o[3]),text:""};continue}const i=/^\s{2}\d+ \| ?(.*)$/.exec(s);r&&i&&(r.text+=`${r.text?`
|
|
10
|
+
`:""}${i[1]}`)}return r&&n.push(r),{visibleText:e.slice(0,t.index).trimEnd(),contexts:n}},Ai="openchamberContext",Ii="opencodeComment";function gg(e){switch(e.kind){case"code-comment":{const t=`lines ${e.startLine}-${e.endLine}`,n=e.source==="diff"&&e.side?` (${e.side})`:"";return`Comment on \`${e.fileLabel}\` ${t}${n}:
|
|
11
|
+
\`\`\`${e.language}
|
|
12
|
+
${e.code}
|
|
13
|
+
\`\`\`
|
|
14
|
+
|
|
15
|
+
${e.text}`}case"terminal":return mg("",[{terminalId:e.terminalId,terminalLabel:e.terminalLabel,startLine:e.startLine,endLine:e.endLine,text:e.output}]);case"browser-annotation":return e.text?`${e.prompt}
|
|
16
|
+
|
|
17
|
+
${e.text}`:e.prompt;case"pr-comment":return`Attached GitHub PR comment (${e.label}):
|
|
18
|
+
|
|
19
|
+
${e.body}${e.text?`
|
|
20
|
+
|
|
21
|
+
${e.text}`:""}`;case"file-quote":{const t=e.startLine!=null&&e.endLine!=null?` lines ${e.startLine}-${e.endLine}`:"",n=e.quote.split(`
|
|
22
|
+
`).map(r=>`> ${r}`).join(`
|
|
23
|
+
`);return`Comment on this fragment of \`${e.fileLabel}\`${t}:
|
|
24
|
+
${n}${e.text?`
|
|
25
|
+
|
|
26
|
+
${e.text}`:""}`}case"chat-quote":return`Comment on this fragment of an earlier message in this conversation:
|
|
27
|
+
${e.quote.split(`
|
|
28
|
+
`).map(n=>`> ${n}`).join(`
|
|
29
|
+
`)}${e.text?`
|
|
30
|
+
|
|
31
|
+
${e.text}`:""}`;case"pr-check":return`Attached failed GitHub PR check (${e.label}):
|
|
32
|
+
\`\`\`
|
|
33
|
+
${e.output}
|
|
34
|
+
\`\`\`${e.text?`
|
|
35
|
+
|
|
36
|
+
${e.text}`:""}`;case"github-issue":case"github-pr":case"linear-issue":case"guest-issue":case"guest-pr":return""}}function PT(e,t){const n=t??gg(e),r={[Ai]:e};return e.kind==="code-comment"&&(r[Ii]={path:e.fileLabel,selection:{startLine:e.startLine,endLine:e.endLine,startChar:0,endChar:0},comment:e.text,preview:e.code,origin:e.source==="diff"?"review":"file"}),{text:n,metadata:r}}function AT(e){switch(e.source){case"terminal":return{kind:"terminal",terminalId:e.terminalId??"",terminalLabel:e.fileLabel,startLine:e.startLine,endLine:e.endLine,output:e.code};case"preview-annotation":return{kind:"browser-annotation",pageUrl:e.fileLabel,prompt:e.code,text:e.text};case"pr-comment":return{kind:"pr-comment",label:e.fileLabel,body:e.code,text:e.text};case"pr-check":return{kind:"pr-check",label:e.fileLabel,output:e.code,text:e.text};case"file-quote":{const t={kind:"file-quote",fileLabel:e.fileLabel,quote:e.code,text:e.text};return e.startLine>0&&e.endLine>0&&(t.startLine=e.startLine,t.endLine=e.endLine),t}case"chat-quote":{const t={kind:"chat-quote",quote:e.code,text:e.text};return e.fileLabel&&(t.messageId=e.fileLabel),t}case"diff":case"file":case"plan":{const t={kind:"code-comment",source:e.source,fileLabel:e.fileLabel,startLine:e.startLine,endLine:e.endLine,language:e.language,code:e.code,text:e.text};return e.source==="diff"&&e.side&&(t.side=e.side),t}}}const cu=Es("kind",[T({kind:N("code-comment"),source:ke(["diff","file","plan"]),fileLabel:m(),startLine:R(),endLine:R(),side:ke(["original","modified"]).optional(),language:m(),code:m(),text:m()}),T({kind:N("terminal"),terminalId:m(),terminalLabel:m(),startLine:R(),endLine:R(),output:m()}),T({kind:N("browser-annotation"),pageUrl:m(),prompt:m(),text:m()}),T({kind:N("pr-comment"),label:m(),body:m(),text:m()}),T({kind:N("pr-check"),label:m(),output:m(),text:m()}),T({kind:N("file-quote"),fileLabel:m(),startLine:R().optional(),endLine:R().optional(),quote:m(),text:m()}),T({kind:N("chat-quote"),messageId:m().optional(),quote:m(),text:m()}),T({kind:N("github-issue"),number:R().int().positive(),title:m(),url:m()}),T({kind:N("github-pr"),number:R().int().positive(),title:m(),url:m()}),T({kind:N("linear-issue"),identifier:m().min(1),title:m(),url:m()}),T({kind:N("guest-issue"),providerId:m().min(1),id:m().min(1),title:m(),url:m(),data:Wi().optional()}),T({kind:N("guest-pr"),providerId:m().min(1),id:m().min(1),title:m(),url:m(),data:Wi().optional()})]),lu=T({path:m(),selection:T({startLine:R().finite(),endLine:R().finite(),startChar:R().finite().optional(),endChar:R().finite().optional()}).optional(),comment:m(),preview:m().optional(),origin:ke(["file","review"]).optional()}),yg=T({[Ai]:cu,[Ii]:lu.optional()});function IT(e){if(e.type!==void 0&&e.type!=="text")return null;const t=cu.safeParse(e.metadata?.[Ai]);if(t.success)return t.data;const n=lu.safeParse(e.metadata?.[Ii]);if(n.success){const r=n.data;return r.selection?{kind:"code-comment",source:r.origin==="review"?"diff":"file",fileLabel:r.path,startLine:r.selection.startLine,endLine:r.selection.endLine,language:"",code:r.preview??"",text:r.comment}:{kind:"file-quote",fileLabel:r.path,quote:r.preview??"",text:r.comment}}return null}function xT(e){switch(e.kind){case"code-comment":{const t={source:e.source,fileLabel:e.fileLabel,startLine:e.startLine,endLine:e.endLine,code:e.code,language:e.language,text:e.text};return e.side&&(t.side=e.side),t}case"terminal":return{source:"terminal",fileLabel:e.terminalLabel,startLine:e.startLine,endLine:e.endLine,code:e.output,language:"",text:"",terminalId:e.terminalId};case"browser-annotation":return{source:"preview-annotation",fileLabel:e.pageUrl,startLine:0,endLine:0,code:e.prompt,language:"",text:e.text};case"pr-comment":return{source:"pr-comment",fileLabel:e.label,startLine:0,endLine:0,code:e.body,language:"",text:e.text};case"pr-check":return{source:"pr-check",fileLabel:e.label,startLine:0,endLine:0,code:e.output,language:"",text:e.text};case"file-quote":return{source:"file-quote",fileLabel:e.fileLabel,startLine:e.startLine??0,endLine:e.endLine??0,code:e.quote,language:"",text:e.text};case"chat-quote":return{source:"chat-quote",fileLabel:e.messageId??"",startLine:0,endLine:0,code:e.quote,language:"",text:e.text};case"github-issue":case"github-pr":case"linear-issue":case"guest-issue":case"guest-pr":return null}}function wg(e){switch(e.kind){case"code-comment":return e.text.trim()||e.code.trim()||e.fileLabel;case"chat-quote":case"file-quote":return e.text.trim()||e.quote;case"browser-annotation":return e.text.trim()||e.prompt.trim()||e.pageUrl;case"pr-comment":return e.text.trim()||e.body.trim()||e.label;case"pr-check":return e.text.trim()||e.label.trim()||e.output;case"terminal":return e.output.trim()||e.terminalLabel;case"github-issue":case"github-pr":case"linear-issue":case"guest-issue":case"guest-pr":return e.title.trim()||e.url}}function bg(e){let t=e.content.trim()||e.contextPreview?.trim()||"";if(!t){for(const r of e.context??[])if(r.kind!=="instruction"&&(t=(r.kind==="context"?wg(r.metadata.openchamberContext):r.text).trim(),t))break}t||=e.attachments?.[0]?.filename??"";const n=t.split(`
|
|
37
|
+
`,1)[0];return n.slice(0,100)+(t.length>n.length||n.length>100?"...":"")}const uu="queue",Sg=e=>e==="steer"||e==="queue",vg=(e,t)=>e==="immediate"?"steer":Sg(e)?e:t===!1?"steer":t===!0?"queue":uu,Pt=()=>!Le(),Xa=50,Bo=(e,t,n=W())=>{const r=Ye(t);return!n||!r||!e?null:{runtimeKey:n,directory:r,sessionId:e}},Ue=e=>`${e.runtimeKey}
|
|
38
|
+
${e.directory}
|
|
39
|
+
${e.sessionId}`,Jt=e=>{const[t,n,...r]=e.split(`
|
|
40
|
+
`);return Bo(r.join(`
|
|
41
|
+
`),n,t)},Tg=T({providerID:m().min(1),modelID:m().min(1),agent:m().optional(),variant:m().optional()}),kg=T({id:m(),filename:m(),mimeType:m(),size:R(),source:ke(["local","server","vscode"]),serverPath:m().optional(),dataUrl:m().optional()}),Eg=Es("kind",[T({kind:N("context"),text:m(),metadata:yg,instructions:m().optional()}),T({kind:N("instruction"),text:m()}),T({kind:N("synthetic"),text:m()})]),xi=T({id:m().min(1),createdAt:R(),content:m(),text:m(),agentMention:m().optional(),attachments:G(kg),context:G(Eg).optional(),contextPreview:m().optional(),sendConfig:Tg}),Ri=T({sessionId:m().min(1),directory:m(),items:G(xi),sendingId:m().nullable()}),Za=T({revision:R(),sessions:G(Ri)}),er=T({revision:R(),session:Ri}),Pg=er.extend({item:xi}),Ag=er.extend({items:G(xi)}),Ig=e=>{const t=e.indexOf(",");if(!e.startsWith("data:")||t===-1)return null;const n=e.slice(5,t),r=e.slice(t+1);try{if(n.endsWith(";base64")){const i=atob(r),a=new ArrayBuffer(i.length),c=new Uint8Array(a);for(let l=0;l<i.length;l+=1)c[l]=i.charCodeAt(l);return a}const s=new TextEncoder().encode(decodeURIComponent(r)),o=new ArrayBuffer(s.byteLength);return new Uint8Array(o).set(s),o}catch{return null}},xg=e=>{const t=e.dataUrl??"",n=t?Ig(t):null,r={id:e.id,file:new File(n?[n]:[],e.filename,{type:e.mimeType}),dataUrl:t,mimeType:e.mimeType,filename:e.filename,size:e.size,source:e.source};return e.serverPath&&(r.serverPath=e.serverPath),r},Br=e=>{const t={id:e.id,content:e.content,text:e.text,createdAt:e.createdAt,sendConfig:{...e.sendConfig}};return e.agentMention&&(t.agentMention=e.agentMention),e.attachments.length>0&&(t.attachments=e.attachments.map(xg)),e.context&&(t.context=e.context),e.contextPreview&&(t.contextPreview=e.contextPreview),t},Rg=e=>{const t={id:e.id,filename:e.filename,mimeType:e.mimeType,size:e.size,source:e.source,dataUrl:e.dataUrl};return e.serverPath&&(t.serverPath=e.serverPath),t},ec=(e,t)=>{const n={content:e.content,text:e.text??e.content,attachments:(e.attachments??[]).filter(s=>!!s.dataUrl).map(Rg),context:e.context??[],sendConfig:t};e.agentMention&&(n.agentMention=e.agentMention);const r=bg({content:"",context:e.context});return r&&(n.contextPreview=r),n},$t=async(e,t,n)=>{const r=await g(t,n);if(!r.ok){const o=new Error(`Message queue request failed (${r.status})`);throw o.status=r.status,o}const s=e.safeParse(await r.json());if(!s.success)throw new Error("Invalid message queue response");return s.data},Tt=(e,t)=>t===void 0?{method:e}:{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},kt=e=>`/api/message-queue/sessions/${encodeURIComponent(e)}`,lo=new Set,tc=new Map,tt=new Map,Hr=new Map;let uo=0;const nc=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.map(r=>({...r,text:r.text??r.content}))])),Cg=(e,t)=>{const n=e??{},r=t<2?n.queuedMessages??{}:{};return{queuedMessages:t<2?{}:nc(n.queuedMessages??{}),quarantinedLegacyMessages:nc({...n.quarantinedLegacyMessages??{},...r}),followUpBehavior:vg(n.followUpBehavior,n.queueModeEnabled??null)}},nt=(e,t)=>{const{[t]:n,...r}=e;return r},zr=(e,t,n)=>{const r=(e.queuedMessages[t]??[]).filter(s=>s.id!==n);return r.length===0?{queuedMessages:nt(e.queuedMessages,t)}:{queuedMessages:{...e.queuedMessages,[t]:r}}},Og=(e,t,n,r)=>{let s=e.queuedMessages,o=e.sendingIds;for(const i of new Set([...Object.keys(s),...Object.keys(o)])){const a=Jt(i);a?.runtimeKey!==t||a.sessionId!==n||(tt.get(i)??-1)>r||(tt.set(i,r),s=nt(s,i),o=nt(o,i))}return{queuedMessages:s,sendingIds:o}},Ho=yt()(Cn(pr((e,t)=>{let n=null,r=!1;const s=(a,c,l)=>{if(l!==W()||(Hr.get(l)??-1)>c)return;const u=Bo(a.sessionId,a.directory,l);if(!u){if(a.items.length>0)return;e(f=>Og(f,l,a.sessionId,c));return}const d=Ue(u);(tt.get(d)??-1)>c||(tt.set(d,c),e(f=>{const p=a.items.map(Br),y=p.length>0?{...f.queuedMessages,[d]:p}:nt(f.queuedMessages,d),b=a.sendingId?{...f.sendingIds,[d]:[a.sendingId]}:nt(f.sendingIds,d);return{queuedMessages:y,sendingIds:b}}))},o=async a=>{try{const c=await $t(Za,"/api/message-queue"),l=c.sessions.find(u=>u.sessionId===a.sessionId)??{sessionId:a.sessionId,directory:a.directory,items:[],sendingId:null};s(l,c.revision,a.runtimeKey)}catch{}},i=async(a,c,l)=>{try{const u=await $t(er,c,l);s(u.session,u.revision,a.runtimeKey)}catch(u){console.warn("[queue] server update failed:",u),await o(a)}};return{queuedMessages:{},quarantinedLegacyMessages:{},followUpBehavior:uu,sendingIds:{},addToQueue:async(a,c)=>{const l=Ue(a),u=`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,d={id:u,content:c.content,text:c.text??c.content,createdAt:Date.now(),sendConfig:c.sendConfig};if(c.agentMention&&(d.agentMention=c.agentMention),c.attachments&&c.attachments.length>0&&(d.attachments=c.attachments),c.context&&c.context.length>0&&(d.context=c.context),e(y=>{const b=y.queuedMessages[l]??[],w={...y.queuedMessages,[l]:[...b,d].slice(-20)},E=Object.keys(w);if(E.length>Xa){E.sort((k,U)=>(w[k]?.[0]?.createdAt??0)-(w[U]?.[0]?.createdAt??0));for(const k of E.slice(0,E.length-Xa))delete w[k]}return{queuedMessages:w}}),!Pt())return;if(!c.sendConfig)throw e(y=>zr(y,l,u)),new Error("A queued message needs a provider and model to be delivered later.");const f=ig(a.runtimeKey,a.directory,a.sessionId),p=lg(c.content,c.attachments??[]);try{const y=await $t(er,`${kt(a.sessionId)}/items`,Tt("POST",{directory:a.directory,item:ec(c,c.sendConfig)}));e(b=>zr(b,l,u)),s(y.session,y.revision,a.runtimeKey),f&&Kn.getState().appendSubmissions(f,[p])}catch(y){throw e(b=>zr(b,l,u)),y}},removeFromQueue:(a,c)=>{const l=Ue(a);e(u=>zr(u,l,c)),Pt()&&i(a,`${kt(a.sessionId)}/items/${encodeURIComponent(c)}`,Tt("DELETE"))},reorderQueue:(a,c,l)=>{if(c===l)return;const u=Ue(a),d=t().queuedMessages[u];if(!d)return;const f=d.findIndex(w=>w.id===c),p=d.findIndex(w=>w.id===l);if(f===-1||p===-1)return;const y=d.slice(),[b]=y.splice(f,1);if(y.splice(p,0,b),e(w=>({queuedMessages:{...w.queuedMessages,[u]:y}})),Pt()){const w=y.map(E=>E.id);i(a,`${kt(a.sessionId)}/order`,Tt("PUT",{itemIds:w}))}},popToInput:async(a,c)=>{const[l]=await t().takeForSend(a,c);return l??null},takeForSend:async(a,c)=>{const l=Ue(a);if(Pt())try{if(c){const b=await $t(Pg,`${kt(a.sessionId)}/items/${encodeURIComponent(c)}/take`,Tt("POST"));return s(b.session,b.revision,a.runtimeKey),[Br(b.item)]}const y=await $t(Ag,`${kt(a.sessionId)}/take`,Tt("POST"));return s(y.session,y.revision,a.runtimeKey),y.items.map(Br)}catch(y){throw await o(a),y}const u=t(),d=u.sendingIds[l]??[],f=(u.queuedMessages[l]??[]).filter(y=>(c?y.id===c:!0)&&!d.includes(y.id));if(f.length===0)return[];const p=new Set(f.map(y=>y.id));return e(y=>{const b=(y.queuedMessages[l]??[]).filter(w=>!p.has(w.id));return b.length===0?{queuedMessages:nt(y.queuedMessages,l)}:{queuedMessages:{...y.queuedMessages,[l]:b}}}),f},clearQueue:a=>{const c=Ue(a);e(l=>{const u=l.sendingIds[c]??[],d=(l.queuedMessages[c]??[]).filter(f=>u.includes(f.id));return d.length>0?{queuedMessages:{...l.queuedMessages,[c]:d}}:{queuedMessages:nt(l.queuedMessages,c)}}),Pt()&&i(a,kt(a.sessionId),Tt("DELETE"))},forgetQueue:a=>{const c=Ue(a);tt.delete(c),e(l=>({queuedMessages:nt(l.queuedMessages,c),sendingIds:nt(l.sendingIds,c)}))},clearAllQueues:()=>{e({queuedMessages:{},sendingIds:{}})},markSending:(a,c)=>{const l=Ue(a);e(u=>{const d=u.sendingIds[l]??[];return d.includes(c)?u:{sendingIds:{...u.sendingIds,[l]:[...d,c]}}})},clearSending:(a,c)=>{const l=Ue(a);e(u=>{const d=u.sendingIds[l];if(!d||!d.includes(c))return u;const f=d.filter(p=>p!==c);return f.length===0?{sendingIds:nt(u.sendingIds,l)}:{sendingIds:{...u.sendingIds,[l]:f}}})},getSendableQueue:a=>{const c=Ue(a),l=t(),u=l.queuedMessages[c]??[],d=l.sendingIds[c];return!d||d.length===0?u:u.filter(f=>!d.includes(f.id))},setFollowUpBehavior:a=>{e({followUpBehavior:a}),ht({followUpBehavior:a})},getQueueForTarget:a=>t().queuedMessages[Ue(a)]??[],hydrate:()=>{if(!Pt())return Promise.resolve();const a=W();if(n?.runtimeKey===a)return n.promise;const c=++uo,l=()=>c===uo&&a===W(),u=(async()=>{let p=tc.get(a);for(p||(p={items:Object.entries(t().queuedMessages).flatMap(([b,w])=>{const E=Jt(b);return!E||E.runtimeKey!==a?[]:w.map(k=>({target:E,message:k}))}),pending:null},tc.set(a,p));p.pending||p.items.length>0;){if(!l())return;if(p.pending){await p.pending;continue}const y=p.items.shift();if(!y?.message.sendConfig)continue;const{target:b,message:w}=y,E=$t(er,`${kt(b.sessionId)}/items`,Tt("POST",{directory:b.directory,item:ec(w,y.message.sendConfig)})).then(()=>{}).catch(U=>{console.warn("[queue] failed to migrate a locally queued message to the server:",U)});p.pending=E;const k=p;E.then(()=>{k.pending===E&&(k.pending=null)}),await E}if(l())do{r=!1;let y;try{y=await $t(Za,"/api/message-queue",{signal:AbortSignal.timeout(15e3)})}catch(b){if(!l())return;if(r)continue;throw b}if(!l())return;lo.add(a),!((Hr.get(a)??-1)>y.revision)&&(Hr.set(a,y.revision),e(b=>{const w=D=>(tt.get(D)??-1)>y.revision,E=D=>Jt(D)?.runtimeKey!==a||w(D),k={},U={};for(const[D,J]of Object.entries(b.queuedMessages))E(D)&&(k[D]=J);for(const[D,J]of Object.entries(b.sendingIds))E(D)&&(U[D]=J);for(const D of y.sessions){const J=Bo(D.sessionId,D.directory,a);if(!J)continue;const C=Ue(J);w(C)||(tt.set(C,y.revision),D.items.length>0&&(k[C]=D.items.map(Br)),D.sendingId&&(U[C]=[D.sendingId]))}return{queuedMessages:k,sendingIds:U}}))}while(r&&l())})(),d={runtimeKey:a,promise:u};n=d;const f=()=>{n===d&&(n=null)};return u.then(f,f),u},resync:()=>(n?.runtimeKey===W()&&(r=!0),t().hydrate()),applyServerSession:s,setServerHold:async(a,c)=>{if(!Pt())return;const l=await g(`${kt(a)}/hold`,Tt("PUT",{held:c}));if(!l.ok)throw new Error(`Message queue hold request failed (${l.status})`)},resetForRuntimeSwitch:a=>{if(uo+=1,n=null,r=!1,a){Hr.delete(a);for(const c of tt.keys())Jt(c)?.runtimeKey===a&&tt.delete(c)}!a||!lo.has(a)||e(c=>{const l={},u={};for(const[d,f]of Object.entries(c.queuedMessages))Jt(d)?.runtimeKey===a?tt.delete(d):l[d]=f;for(const[d,f]of Object.entries(c.sendingIds))Jt(d)?.runtimeKey!==a&&(u[d]=f);return{queuedMessages:l,sendingIds:u}})}}},{name:"message-queue-store",version:3,storage:yi(),partialize:e=>({queuedMessages:Object.fromEntries(Object.entries(e.queuedMessages).filter(([t])=>{const n=Jt(t)?.runtimeKey;return!n||!lo.has(n)})),quarantinedLegacyMessages:e.quarantinedLegacyMessages,followUpBehavior:e.followUpBehavior}),migrate:Cg}),{name:"message-queue-store"})),Mg=T({type:N("openchamber:message-queue.updated"),properties:T({revision:R(),session:Ri})}),RT=(e,t)=>{if(!Pt())return;const n=Mg.safeParse(e);if(!n.success)return;const{session:r,revision:s}=n.data.properties;Ho.getState().applyServerSession(r,s,t)},Dg=e=>{const t=e.replace(/\\/g,"/").replace(/\/+$/g,"").trim();if(!t)return"";const n=new TextEncoder().encode(t);let r="";for(const o of n)r+=String.fromCharCode(o);return`path_${typeof btoa=="function"?btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,""):t.replace(/[^A-Za-z0-9._-]+/g,"_")}`},L=e=>t=>{const n=e.safeParse(t);return n.success?n.data:void 0},Mn=R().refine(Number.isFinite),Fe=m().transform(e=>e.trim()),de=Fe.pipe(m().min(1)),Lt=it(m(),me()),A=L(Ne()),je=L(m().min(1)),gn=L(Fe),fn=L(de),rc=e=>L(m().max(e)),zn=e=>L(Fe.transform(t=>t.slice(0,e))),te=e=>L(Fe.pipe(ke(e))),Wt=L(Mn),_g=(e,t)=>L(Mn.transform(n=>Math.max(e,Math.min(t,Math.round(n))))),fo=e=>L(Mn.transform(t=>Math.max(e,Math.round(t)))),Lg=L(Mn.positive().transform(Math.floor)),Fg=L(Zt([rr(),Mn])),Ug=L(Zt([rr(),Fe.transform(e=>e.length>0?e:null)])),jg=L(Zt([rr(),Fe])),Ci=G(me()).transform(e=>e.filter(t=>m().min(1).safeParse(t).success)),$r=L(Ci.transform(e=>Array.from(new Set(e.map(String))))),po=L(Ci.transform(e=>e.map(String))),Ng=Lt.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){const s=G(me()).safeParse(r);s.success&&(t[n]=s.data.filter(o=>m().safeParse(o).success).map(String))}return t}),ho=L(Ng.pipe(it(m(),G(m())).refine(e=>Object.keys(e).length>0))),Bg=T({providerID:de,modelID:de}),mo=e=>L(G(me()).transform(t=>{const n=[],r=new Set;for(const s of t){const o=Bg.safeParse(s);if(!o.success)continue;const i=`${o.data.providerID}/${o.data.modelID}`;if(!r.has(i)&&(r.add(i),n.push(o.data),n.length>=e))break}return n})),Hg=L(Lt.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){if(!n)continue;const s=Ci.safeParse(r);if(!s.success)continue;const o=Array.from(new Set(s.data.map(String)));o.length>0&&(t[n]=o.slice(0,5))}return t}).refine(e=>Object.keys(e).length>0)),zg=L(Lt.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){const s=n.trim(),o=de.safeParse(r);!s||!o.success||(t[s]=o.data)}return t})),Wr={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."}},$g=T({title:m().catch(""),message:m().catch("")}),Wg=L(Lt.transform(e=>{const t=i=>{const a=$g.safeParse(e[i]);return a.success?a.data:void 0},n=t("completion"),r=t("error"),s=t("question"),o=t("subtask");if(!(!n&&!r&&!s&&!o))return{completion:n??Wr.completion,error:r??Wr.error,question:s??Wr.question,subtask:o??Wr.subtask}}).pipe(xc(e=>e!==void 0))),sc=Lt.transform(e=>Object.fromEntries(Object.entries(e).flatMap(([t,n])=>{const r=m().safeParse(n);return r.success?[[t,r.data]]:[]}))),Gg=T({id:me().transform(e=>String(e??"")),label:me().transform(e=>String(e??"")),models:G(me()).transform(e=>e.filter(t=>m().safeParse(t).success).map(String)).catch([]),order:R().catch(0)}),qg=L(Lt.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){const s=Lt.safeParse(r);if(!s.success)continue;const o={},i=G(me()).safeParse(s.data.customGroups);i.success&&(o.customGroups=i.data.flatMap(l=>{const u=Gg.safeParse(l);return u.success?[u.data]:[]}));const a=sc.safeParse(s.data.modelAssignments);a.success&&(o.modelAssignments=a.data);const c=sc.safeParse(s.data.renamedGroups);c.success&&(o.renamedGroups=c.data),Object.keys(o).length>0&&(t[n]=o)}return t}).refine(e=>Object.keys(e).length>0)),Kg=T({id:de,name:de,hostname:de.transform(e=>e.toLowerCase())}),Vg=L(G(me()).transform(e=>{const t=[],n=new Set,r=new Set;for(const s of e){const o=Kg.safeParse(s);o.success&&(n.has(o.data.id)||r.has(o.data.hostname)||(n.add(o.data.id),r.add(o.data.hostname),t.push(o.data)))}return t})),Jg=L(Lt.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){const s=n.trim(),o=de.safeParse(r);!s||!o.success||(t[s]=o.data)}return t}).refine(e=>Object.keys(e).length>0)),Yg=T({id:de,label:de,source:de,subpath:Fe.optional().catch(void 0),gitIdentityId:Fe.optional().catch(void 0)}),Qg=L(G(me()).transform(e=>{const t=[],n=new Set;for(const r of e){const s=Yg.safeParse(r);if(!s.success||n.has(s.data.id))continue;n.add(s.data.id);const o={id:s.data.id,label:s.data.label,source:s.data.source};s.data.subpath&&(o.subpath=s.data.subpath),s.data.gitIdentityId&&(o.gitIdentityId=s.data.gitIdentityId),t.push(o)}return t})),Xg=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,go=Mn.nonnegative(),Zg=T({path:de,label:de.optional().catch(void 0),icon:de.optional().catch(void 0),iconImage:Zt([rr(),T({mime:de,updatedAt:go.transform(Math.round).pipe(R().positive()),source:ke(["custom","auto"])})]).optional().catch(void 0),color:de.optional().catch(void 0),iconBackground:Zt([rr(),Fe.pipe(m().regex(Xg)).transform(e=>e.toLowerCase())]).optional().catch(void 0),addedAt:go.optional().catch(void 0),lastOpenedAt:go.optional().catch(void 0),sidebarCollapsed:Ne().optional().catch(void 0),defaultModel:de.optional().catch(void 0),defaultAgent:de.optional().catch(void 0),defaultVariant:de.optional().catch(void 0)}),ey=L(G(me()).transform(e=>{const t=[],n=new Set,r=new Set;for(const s of e){const o=Zg.safeParse(s);if(!o.success)continue;const i=Ye(o.data.path);if(!i)continue;const a=Dg(i);if(!a||n.has(a)||r.has(i))continue;n.add(a),r.add(i);const c={id:a,path:i};o.data.label&&(c.label=o.data.label),o.data.icon&&(c.icon=o.data.icon),o.data.iconImage!==void 0&&(c.iconImage=o.data.iconImage),o.data.color&&(c.color=o.data.color),o.data.iconBackground!==void 0&&(c.iconBackground=o.data.iconBackground),o.data.addedAt!==void 0&&(c.addedAt=o.data.addedAt),o.data.lastOpenedAt!==void 0&&(c.lastOpenedAt=o.data.lastOpenedAt),o.data.defaultModel&&(c.defaultModel=o.data.defaultModel),o.data.defaultAgent&&(c.defaultAgent=o.data.defaultAgent),o.data.defaultVariant&&(c.defaultVariant=o.data.defaultVariant),o.data.sidebarCollapsed!==void 0&&(c.sidebarCollapsed=o.data.sidebarCollapsed),t.push(c)}return t}).refine(e=>e.length>0)),ty=ke(["steer","queue"]),ny=(e,t)=>{const n=ty.safeParse(e);if(n.success)return n.data;if(e==="immediate")return"steer";const r=Ne().safeParse(t.queueModeEnabled);if(r.success)return r.data?"queue":"steer"},ry=L(Fe.pipe(ke(["local","openai-compatible","server","browser","wasm"])).transform(e=>e==="server"?"openai-compatible":e==="browser"||e==="wasm"?"local":e)),sy=L(Fe.pipe(ke(["left","right","auto"])).transform(e=>e==="left"?"left":"right")),oy=L(Fe.transform(e=>e.replace(/\s+/g," ").slice(0,64))),iy=e=>L(G(me()).transform(t=>{const n=[];for(const r of t){const s=Fe.transform(o=>o.toLowerCase()).safeParse(r);s.success&&e(s.data)&&!n.includes(s.data)&&n.push(s.data)}return n})),Oi=e=>L(xc(e)),ur=(e,t)=>(n,r)=>{const s=e(n,r);return s===void 0?void 0:t(s)},h=e=>e,S=(e,t,n={})=>({read:()=>v.getState()[e],write:t,autoSave:n.autoSave??!0}),Gt=e=>t=>{v.setState({[e]:t})},oc=()=>globalThis.window?.__zustand_config_store__??null,qt=e=>({read:()=>oc()?.getState()[e],write:t=>{oc()?.setState({[e]:t})},autoSave:!1}),Gr=e=>({read:()=>Mo.getState()[e],write:t=>{Mo.setState({[e]:t})},autoSave:!1}),ay=["concise","detailed","mentor","pushback","noFiller","matchEnergy","warmPeer","custom"],cy=Oi(Ei),ly=Oi(Nh),uy=Oi(Bh),dy=L(m().refine(ru)),fy=L(R().refine(ki)),py=ur(gn,e=>Os(e,void 0)),hy=ur(L(G(me())),Wm),my=ur(L(G(me())),e=>Nl(e)),gy=te(["ask","attach","inline"]),yy=te(["default","vim"]),wy=(e,t)=>{let n=e;const r=(s,o)=>{if(n.some(c=>c.type==="command"&&c.name===s))return;const i=n.findIndex(c=>c.type==="command"&&c.name===o),a=i>=0?i+1:n.length;n=[...n.slice(0,a),{type:"command",name:s},...n.slice(a)]};return t.draftStartersCraftGoalAdded!==!0&&r("craft-goal","plan-feature"),t.draftStartersScheduleTaskAdded!==!0&&r("schedule-task","craft-goal"),n},yr={themeId:h({scope:"profile",perSurface:!0,parse:je}),useSystemTheme:h({scope:"profile",perSurface:!0,parse:A}),themeVariant:h({scope:"profile",derived:!0,parse:te(["light","dark"])}),lightThemeId:h({scope:"profile",perSurface:!0,parse:je}),darkThemeId:h({scope:"profile",perSurface:!0,parse:je}),lastDirectory:h({scope:"instance",adopt:"bootstrap-only",parse:je}),homeDirectory:h({scope:"instance",parse:je}),opencodeBinary:h({scope:"instance",parse:gn}),projects:h({scope:"instance",parse:ey}),activeProjectId:h({scope:"instance",adopt:"bootstrap-only",parse:je}),securityScopedBookmarks:h({scope:"instance",surfaces:["desktop"],parse:po}),pinnedDirectories:h({scope:"instance",parse:$r}),desktopLanAccessEnabled:h({scope:"instance",surfaces:["desktop"],parse:A}),desktopKeepAwakeEnabled:h({scope:"instance",surfaces:["desktop"],parse:A}),desktopMinimizeToTrayEnabled:h({scope:"instance",surfaces:["desktop"],parse:A}),desktopMacMenuBarEnabled:h({scope:"instance",surfaces:["desktop"],parse:A}),desktopUiPassword:h({scope:"instance",secret:!0,surfaces:["desktop"],parse:gn}),hasDesktopUiPassword:h({scope:"instance",computed:!0,surfaces:["desktop"],parse:A}),desktopLanAccessActive:h({scope:"instance",computed:!0,surfaces:["desktop"],parse:A}),desktopLanAccessBlockedReason:h({scope:"instance",computed:!0,surfaces:["desktop"],parse:gn}),githubClientId:h({scope:"instance",parse:fn}),githubScopes:h({scope:"instance",parse:fn}),skillCatalogs:h({scope:"instance",parse:Qg}),defaultGitIdentityId:h({scope:"instance",parse:gn}),permissionAutoAccept:h({scope:"instance",parse:L(T({sessions:it(m().min(1),Ne()).catch({}),revision:R().int().nonnegative().catch(0)}))}),agentControlToolEnabled:h({scope:"instance",parse:A,ui:S("agentControlToolEnabled",e=>v.getState().setAgentControlToolEnabled(e))}),agentWebToolEnabled:h({scope:"instance",parse:A,ui:S("agentWebToolEnabled",e=>v.getState().setAgentWebToolEnabled(e))}),browserProvider:h({scope:"instance",parse:je,ui:S("browserProvider",e=>v.getState().setBrowserProvider(e))}),agentMemoryToolEnabled:h({scope:"instance",parse:A,ui:S("agentMemoryToolEnabled",e=>v.getState().setAgentMemoryToolEnabled(e))}),agentMemoryFeatureAvailable:h({scope:"instance",computed:!0,parse:A,ui:S("agentMemoryFeatureAvailable",e=>v.getState().setAgentMemoryFeatureAvailable(e),{autoSave:!1})}),routingFeatureAvailable:h({scope:"instance",computed:!0,parse:A,ui:S("routingFeatureAvailable",e=>v.getState().setRoutingFeatureAvailable(e),{autoSave:!1})}),openCodeUpdateToastDismissedVersion:h({scope:"instance",parse:zn(128)}),autoDeleteEnabled:h({scope:"instance",parse:A,ui:S("autoDeleteEnabled",e=>v.getState().setAutoDeleteEnabled(e))}),autoDeleteAfterDays:h({scope:"instance",parse:_g(1,365),ui:S("autoDeleteAfterDays",e=>v.getState().setAutoDeleteAfterDays(e))}),sessionRetentionOnlyArchived:h({scope:"instance",parse:A,ui:S("sessionRetentionOnlyArchived",e=>v.getState().setSessionRetentionOnlyArchived(e))}),sessionRetentionAction:h({scope:"instance",parse:te(["archive","delete"]),ui:S("sessionRetentionAction",e=>v.getState().setSessionRetentionAction(e))}),terminalShell:h({scope:"instance",parse:cy,ui:S("terminalShell",e=>v.getState().setTerminalShell(e))}),terminalLoginShells:h({scope:"instance",parse:iy(Ei),ui:S("terminalLoginShells",e=>v.getState().setTerminalLoginShells(e))}),openInAppId:h({scope:"instance",parse:fn}),dictationEnabled:h({scope:"profile",parse:A,ui:qt("dictationEnabled")}),sttProvider:h({scope:"instance",parse:ry,ui:qt("sttProvider")}),sttServerUrl:h({scope:"instance",parse:zn(2048),ui:qt("sttServerUrl")}),sttModel:h({scope:"instance",parse:zn(256),ui:qt("sttModel")}),sttLocalModel:h({scope:"instance",parse:zn(256),ui:qt("sttLocalModel")}),sttLanguage:h({scope:"profile",parse:zn(64),ui:qt("sttLanguage")}),tunnelProvider:h({scope:"instance",parse:ur(fn,e=>e.toLowerCase())}),tunnelMode:h({scope:"instance",parse:L(m().transform(e=>e.trim().toLowerCase()).pipe(ke(["quick","managed-remote","managed-local"])))}),tunnelBootstrapTtlMs:h({scope:"instance",parse:Fg}),tunnelSessionTtlMs:h({scope:"instance",parse:Wt}),managedLocalTunnelConfigPath:h({scope:"instance",parse:Ug}),managedRemoteTunnelHostname:h({scope:"instance",parse:gn}),managedRemoteTunnelToken:h({scope:"instance",secret:!0,parse:jg}),hasManagedRemoteTunnelToken:h({scope:"instance",computed:!0,parse:A}),managedRemoteTunnelPresets:h({scope:"instance",parse:Vg}),managedRemoteTunnelSelectedPresetId:h({scope:"instance",parse:fn}),managedRemoteTunnelPresetTokens:h({scope:"instance",secret:!0,parse:Jg}),sidebarProjectDisplayMode:h({scope:"profile",parse:te(["all","single"]),ui:Gr("projectDisplayMode")}),sidebarViewMode:h({scope:"profile",perSurface:!0,parse:te(["projects","timeline"]),ui:Gr("sidebarViewMode")}),sidebarProjectSortOrder:h({scope:"profile",parse:te(["manual","a-z","z-a","date-added","recent"]),ui:Gr("projectSortOrder")}),sidebarShowRecentSection:h({scope:"profile",parse:A,ui:Gr("showRecentSection")}),workStatusSectionOrder:h({scope:"profile",parse:ur(po,Oo),ui:S("workStatusSectionOrder",e=>v.getState().setWorkStatusSectionOrder(e))}),workStatusPanelEnabled:h({scope:"profile",parse:A,ui:S("workStatusPanelEnabled",e=>v.getState().setWorkStatusPanelEnabled(e))}),workStatusHiddenSections:h({scope:"profile",parse:my,ui:{read:()=>v.getState().workStatusHiddenSections,write:(e,t)=>{const n=t.workStatusHiddenSectionsExplicit===!0;v.setState({workStatusHiddenSections:Nl(e,n),workStatusHiddenSectionsExplicit:n})},autoSave:!0}}),workStatusHiddenSectionsExplicit:h({scope:"profile",parse:A,ui:S("workStatusHiddenSectionsExplicit",()=>{})}),showReasoningTraces:h({scope:"profile",parse:A,ui:S("showReasoningTraces",e=>v.getState().setShowReasoningTraces(e))}),streamingAutoFollowEnabled:h({scope:"profile",perSurface:!0,parse:A,ui:S("streamingAutoFollowEnabled",e=>v.getState().setStreamingAutoFollowEnabled(e))}),collapsibleThinkingBlocks:h({scope:"profile",parse:A,ui:S("collapsibleThinkingBlocks",e=>v.getState().setCollapsibleThinkingBlocks(e))}),showTextJustificationActivity:h({scope:"profile",parse:A}),chatRenderMode:h({scope:"profile",parse:te(["sorted","live"]),ui:S("chatRenderMode",e=>v.getState().setChatRenderMode(e))}),activityRenderMode:h({scope:"profile",parse:te(["collapsed","summary"]),ui:S("activityRenderMode",e=>v.getState().setActivityRenderMode(e))}),mermaidRenderingMode:h({scope:"profile",parse:te(["svg","ascii"]),ui:S("mermaidRenderingMode",e=>v.getState().setMermaidRenderingMode(e))}),userMessageRenderingMode:h({scope:"profile",parse:te(["markdown","plain"]),ui:S("userMessageRenderingMode",e=>v.getState().setUserMessageRenderingMode(e))}),collapsibleUserMessages:h({scope:"profile",parse:A,ui:S("collapsibleUserMessages",e=>v.getState().setCollapsibleUserMessages(e))}),stickyUserHeader:h({scope:"profile",perSurface:!0,parse:A,ui:S("stickyUserHeader",e=>v.getState().setStickyUserHeader(e))}),promptNavigatorEnabled:h({scope:"profile",perSurface:!0,parse:A,ui:S("promptNavigatorEnabled",e=>v.getState().setPromptNavigatorEnabled(e))}),wideChatLayoutEnabled:h({scope:"profile",perSurface:!0,parse:A,ui:S("wideChatLayoutEnabled",e=>v.getState().setWideChatLayoutEnabled(e))}),showSplitAssistantMessageActions:h({scope:"profile",parse:A,ui:S("showSplitAssistantMessageActions",e=>v.getState().setShowSplitAssistantMessageActions(e))}),showToolFileIcons:h({scope:"profile",parse:A,ui:S("showToolFileIcons",e=>v.getState().setShowToolFileIcons(e))}),codeBlockLineWrap:h({scope:"profile",parse:A,ui:S("codeBlockLineWrap",e=>v.getState().setCodeBlockLineWrap(e))}),showTurnChangedFiles:h({scope:"profile",parse:A,ui:S("showTurnChangedFiles",e=>v.getState().setShowTurnChangedFiles(e))}),showExpandedBashTools:h({scope:"profile",parse:A,ui:S("showExpandedBashTools",e=>v.getState().setShowExpandedBashTools(e))}),showExpandedEditTools:h({scope:"profile",parse:A,ui:S("showExpandedEditTools",e=>v.getState().setShowExpandedEditTools(e))}),toolJsonViewMode:h({scope:"profile",parse:te(["summary","formatted","raw"]),ui:S("toolJsonViewMode",e=>v.getState().setToolJsonViewMode(e))}),timeFormatPreference:h({scope:"profile",parse:te(["auto","12h","24h"]),ui:S("timeFormatPreference",e=>v.getState().setTimeFormatPreference(e))}),weekStartPreference:h({scope:"profile",parse:te(["auto","sunday","monday"]),ui:S("weekStartPreference",e=>v.getState().setWeekStartPreference(e))}),messageStreamTransport:h({scope:"profile",parse:te(["auto","ws","sse"]),ui:qt("settingsMessageStreamTransport")}),diffLayoutPreference:h({scope:"profile",parse:te(["dynamic","inline","side-by-side"]),ui:S("diffLayoutPreference",e=>v.getState().setDiffLayoutPreference(e))}),diffWrapLines:h({scope:"profile",parse:A,ui:S("diffWrapLines",e=>v.getState().setDiffWrapLines(e))}),gitChangesViewMode:h({scope:"profile",parse:te(["flat","tree"]),ui:S("gitChangesViewMode",e=>v.getState().setGitChangesViewMode(e))}),gitmojiEnabled:h({scope:"profile",parse:A}),defaultFileViewerPreview:h({scope:"profile",parse:A}),directoryShowHidden:h({scope:"profile",parse:A,ui:{read:Hm,write:e=>zm(e,{persist:!1}),autoSave:!1}}),filesViewShowGitignored:h({scope:"profile",parse:A,ui:{read:qm,write:e=>Km(e,{persist:!1}),autoSave:!1}}),fileEditorKeymap:h({scope:"profile",parse:yy,ui:S("fileEditorKeymap",e=>v.getState().setFileEditorKeymap(e))}),autoSaveEnabled:h({scope:"profile",parse:A,ui:S("autoSaveEnabled",e=>v.getState().setAutoSaveEnabled(e))}),autoCreateWorktree:h({scope:"profile",parse:A}),sessionTabsEnabled:h({scope:"profile",surfaces:["web","desktop","vscode"],parse:A,ui:S("sessionTabsEnabled",e=>v.getState().setSessionTabsEnabled(e))}),allowPromptingSubagentSessions:h({scope:"profile",parse:A,ui:S("allowPromptingSubagentSessions",e=>v.getState().setAllowPromptingSubagentSessions(e))}),inputSpellcheckEnabled:h({scope:"profile",parse:A,ui:S("inputSpellcheckEnabled",e=>v.getState().setInputSpellcheckEnabled(e))}),enterToSend:h({scope:"profile",parse:A,ui:S("enterToSend",e=>v.getState().setEnterToSend(e))}),enterToSendConfigured:h({scope:"profile",parse:A,ui:S("enterToSendConfigured",e=>v.getState().setEnterToSendConfigured(e))}),persistChatDraft:h({scope:"profile",parse:A,ui:S("persistChatDraft",e=>v.getState().setPersistChatDraft(e))}),largeTextPasteBehavior:h({scope:"profile",parse:gy,ui:S("largeTextPasteBehavior",e=>v.getState().setLargeTextPasteBehavior(e))}),followUpBehavior:h({scope:"profile",parse:ny,ui:{read:()=>Ho.getState().followUpBehavior,write:e=>Ho.getState().setFollowUpBehavior(e),autoSave:!1}}),queueModeEnabled:h({scope:"profile",parse:A}),inputHistoryScope:h({scope:"profile",parse:dy,ui:{read:()=>Kn.getState().scope,write:e=>Kn.getState().applyScope(e),autoSave:!1}}),inputHistoryLimit:h({scope:"profile",parse:fy,ui:{read:()=>Kn.getState().entryLimit,write:e=>Kn.getState().applyEntryLimit(e),autoSave:!1}}),draftStarters:h({scope:"profile",parse:hy,ui:{read:()=>v.getState().globalDraftStarters??void 0,write:(e,t)=>v.getState().setGlobalDraftStarters(wy(e,t)),autoSave:!1}}),draftStartersVisible:h({scope:"profile",parse:A,ui:S("draftStartersVisible",e=>v.getState().setDraftStartersVisible(e))}),draftStartersCraftGoalAdded:h({scope:"profile",parse:A}),draftStartersScheduleTaskAdded:h({scope:"profile",parse:A}),fontSize:h({scope:"profile",perSurface:!0,parse:Wt,ui:S("fontSize",e=>v.getState().setFontSize(e))}),terminalFontSize:h({scope:"profile",perSurface:!0,parse:Wt,ui:S("terminalFontSize",e=>v.getState().setTerminalFontSize(e))}),editorFontSize:h({scope:"profile",perSurface:!0,parse:Wt,ui:S("editorFontSize",e=>v.getState().setEditorFontSize(e))}),uiFont:h({scope:"profile",parse:ly,ui:S("uiFont",e=>v.getState().setUiFont(e))}),monoFont:h({scope:"profile",parse:uy,ui:S("monoFont",e=>v.getState().setMonoFont(e))}),padding:h({scope:"profile",perSurface:!0,parse:Wt,ui:S("padding",e=>v.getState().setPadding(e))}),cornerRadius:h({scope:"profile",perSurface:!0,parse:Wt,ui:S("cornerRadius",e=>v.getState().setCornerRadius(e))}),shortcutOverrides:h({scope:"profile",parse:zg,ui:S("shortcutOverrides",Gt("shortcutOverrides"))}),defaultModel:h({scope:"profile",parse:je}),defaultVariant:h({scope:"profile",parse:je}),defaultAgent:h({scope:"profile",parse:je}),smallModelUseDefault:h({scope:"profile",parse:A}),smallModelOverride:h({scope:"profile",parse:je}),walkthroughModelOverride:h({scope:"profile",parse:je}),zenModel:h({scope:"profile",parse:fn}),favoriteModels:h({scope:"profile",parse:mo(64),ui:S("favoriteModels",Gt("favoriteModels"),{autoSave:!1})}),hiddenModels:h({scope:"profile",parse:mo(1024),ui:S("hiddenModels",Gt("hiddenModels"),{autoSave:!1})}),collapsedModelProviders:h({scope:"profile",parse:$r,ui:S("collapsedModelProviders",Gt("collapsedModelProviders"),{autoSave:!1})}),recentModels:h({scope:"profile",parse:mo(16),ui:S("recentModels",Gt("recentModels"),{autoSave:!1})}),recentAgents:h({scope:"profile",parse:$r,ui:S("recentAgents",Gt("recentAgents"),{autoSave:!1})}),recentEfforts:h({scope:"profile",parse:Hg,ui:S("recentEfforts",Gt("recentEfforts"),{autoSave:!1})}),providerOrder:h({scope:"profile",parse:$r,ui:S("providerOrder",e=>v.getState().setProviderOrder(e))}),sessionRecapEnabled:h({scope:"profile",parse:A,ui:S("sessionRecapEnabled",e=>v.getState().setSessionRecapEnabled(e))}),sessionSuggestionEnabled:h({scope:"profile",parse:A,ui:S("sessionSuggestionEnabled",e=>v.getState().setSessionSuggestionEnabled(e))}),sessionGoalEnabled:h({scope:"profile",parse:A,ui:S("sessionGoalEnabled",e=>v.getState().setSessionGoalEnabled(e))}),sessionGoalDefaultBudgetEnabled:h({scope:"profile",parse:A,ui:S("sessionGoalDefaultBudgetEnabled",e=>v.getState().setSessionGoalDefaultBudgetEnabled(e))}),sessionGoalDefaultBudget:h({scope:"profile",parse:Lg,ui:S("sessionGoalDefaultBudget",e=>v.getState().setSessionGoalDefaultBudget(e))}),summarizeLastMessage:h({scope:"profile",parse:A,ui:S("summarizeLastMessage",e=>v.getState().setSummarizeLastMessage(e))}),summaryThreshold:h({scope:"profile",parse:fo(0),ui:S("summaryThreshold",e=>v.getState().setSummaryThreshold(e))}),summaryLength:h({scope:"profile",parse:fo(10),ui:S("summaryLength",e=>v.getState().setSummaryLength(e))}),maxLastMessageLength:h({scope:"profile",parse:fo(10),ui:S("maxLastMessageLength",e=>v.getState().setMaxLastMessageLength(e))}),showDeletionDialog:h({scope:"profile",parse:A,ui:S("showDeletionDialog",e=>v.getState().setShowDeletionDialog(e))}),nativeNotificationsEnabled:h({scope:"profile",parse:A,ui:S("nativeNotificationsEnabled",e=>v.getState().setNativeNotificationsEnabled(e))}),notificationMode:h({scope:"profile",parse:te(["always","hidden-only"]),ui:S("notificationMode",e=>v.getState().setNotificationMode(e))}),notifyOnSubtasks:h({scope:"profile",parse:A,ui:S("notifyOnSubtasks",e=>v.getState().setNotifyOnSubtasks(e))}),notifyOnCompletion:h({scope:"profile",parse:A,ui:S("notifyOnCompletion",e=>v.getState().setNotifyOnCompletion(e))}),notifyOnError:h({scope:"profile",parse:A,ui:S("notifyOnError",e=>v.getState().setNotifyOnError(e))}),notifyOnQuestion:h({scope:"profile",parse:A,ui:S("notifyOnQuestion",e=>v.getState().setNotifyOnQuestion(e))}),notificationTemplates:h({scope:"profile",parse:Wg,ui:S("notificationTemplates",e=>v.getState().setNotificationTemplates(e))}),showOpenCodeUpdateNotifications:h({scope:"profile",parse:A,ui:S("showOpenCodeUpdateNotifications",e=>v.getState().setShowOpenCodeUpdateNotifications(e))}),reportUsage:h({scope:"profile",parse:A,ui:S("reportUsage",e=>v.getState().setReportUsage(e))}),usageDisplayMode:h({scope:"profile",parse:te(["usage","remaining"])}),usageDropdownProviders:h({scope:"profile",parse:po}),usageSelectedModels:h({scope:"profile",parse:ho}),usageCollapsedFamilies:h({scope:"profile",parse:ho}),usageExpandedFamilies:h({scope:"profile",parse:ho}),usageModelGroups:h({scope:"profile",parse:qg}),globalBehaviorPrompt:h({scope:"profile",parse:rc(1024*1024)}),responseStyleEnabled:h({scope:"profile",parse:A}),responseStylePreset:h({scope:"profile",parse:te(ay)}),responseStyleCustomInstructions:h({scope:"profile",parse:rc(5e4)}),pwaAppName:h({scope:"instance",surfaces:["web"],parse:oy}),pwaOrientation:h({scope:"instance",surfaces:["web"],parse:te(["system","portrait","landscape"])}),mobileKeyboardMode:h({scope:"device",surfaces:["mobile"],parse:py,ui:S("mobileKeyboardMode",e=>v.getState().setMobileKeyboardMode(e))}),desktopWindowControlsPosition:h({scope:"device",surfaces:["desktop"],parse:sy,ui:S("desktopWindowControlsPosition",e=>v.getState().setDesktopWindowControlsPosition(e))}),desktopWindowControlsStyle:h({scope:"device",surfaces:["desktop"],parse:te(["classic","traffic-lights"]),ui:S("desktopWindowControlsStyle",e=>v.getState().setDesktopWindowControlsStyle(e))}),inputBarOffset:h({scope:"device",surfaces:["mobile","web"],parse:Wt,ui:S("inputBarOffset",e=>v.getState().setInputBarOffset(e))})},by=e=>Object.prototype.hasOwnProperty.call(yr,e),wr=Object.keys(yr).filter(by),du=e=>yr[e].scope==="device",br=e=>yr[e],Sy=e=>!yr[e].computed&&!du(e),vy=it(m(),me()),Ty=e=>{const t=vy.safeParse(e);if(!t.success)return null;const n=t.data,r={};for(const s of wr){const i=br(s).parse(n[s],n);i!==void 0&&Object.assign(r,{[s]:i})}return r},ky=(e,t)=>e===t?!0:e===void 0||t===void 0?!1:JSON.stringify(e)===JSON.stringify(t),Ey=e=>{for(const t of wr){const n=br(t);if(!n.ui)continue;const r=e[t];r!==void 0&&(ky(n.ui.read(),r)||n.ui.write(r,e))}},Py=wr.filter(e=>br(e).ui?.autoSave===!0),CT=()=>{const e={};for(const t of Py){const r=br(t).ui?.read();r!==void 0&&Object.assign(e,{[t]:r})}return e},Ay=wr.filter(e=>{const t=br(e);return t.scope!=="device"&&!t.secret&&!t.computed}),Iy=e=>{if(!(typeof window>"u")&&!(typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0))try{window.__OPENCHAMBER_HOME__=e}catch{}},ic="openchamber.settingsMirror.v2.index",xy="openchamber.deviceSeeded.v1:",Ry=e=>`${xy}${encodeURIComponent(e)}`,Cy=(e,t)=>{const n=Ry(t);let r=!1;try{r=localStorage.getItem(n)===null,r&&localStorage.setItem(n,String(Date.now()))}catch{r=!1}if(r)return e;const s={};for(const o of wr)e[o]===void 0||du(o)||Object.assign(s,{[o]:e[o]});return s},Oy="openchamber.settingsMirror.v2:",My=5,ac=e=>`${Oy}${encodeURIComponent(e)}`,pn=(e,t)=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)},Dy=(e,t)=>{const n={};for(const o of Ay)e[o]!==void 0&&Object.assign(n,{[o]:e[o]});localStorage.setItem(ac(t),JSON.stringify(n));let r=[];try{const o=JSON.parse(localStorage.getItem(ic)??"[]");Array.isArray(o)&&(r=o.filter(i=>typeof i=="string"))}catch{r=[]}const s=[t,...r.filter(o=>o!==t)].slice(0,My);for(const o of r)s.includes(o)||localStorage.removeItem(ac(o));localStorage.setItem(ic,JSON.stringify(s))},_y=e=>{if(!(typeof window>"u")){if(Dy(e,W()),pn("lastDirectory",e.lastDirectory||null),e.homeDirectory?(localStorage.setItem("homeDirectory",e.homeDirectory),Iy(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(n=>n.sidebarCollapsed===!0).map(n=>n.id).filter(n=>typeof n=="string"&&n.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"),pn("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(Ul(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.sttProvider==="local"||e.sttProvider==="openai-compatible"?localStorage.setItem("sttProvider",e.sttProvider):localStorage.removeItem("sttProvider"),pn("sttServerUrl",typeof e.sttServerUrl=="string"?e.sttServerUrl:null),pn("sttModel",typeof e.sttModel=="string"?e.sttModel:null),pn("sttLocalModel",typeof e.sttLocalModel=="string"?e.sttLocalModel:null),pn("sttLanguage",typeof e.sttLanguage=="string"?e.sttLanguage:null)}},zo=(e,t,n=t)=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:{settings:e,bootstrap:t,adoptTheme:n}}))};let $o="idle",qr=null;const Wo=new Set,OT=()=>$o,MT=e=>(Wo.add(e),()=>Wo.delete(e)),DT=e=>{Ds(),Ke(e)},Ke=e=>{qr&&(clearTimeout(qr),qr=null);const t=e==="saved"?"idle":e;t!==$o&&($o=t,Wo.forEach(n=>n())),t==="error"&&(qr=setTimeout(()=>Ke("saved"),6e3)),!(typeof window>"u")&&window.dispatchEvent(new CustomEvent("openchamber:settings-save-state",{detail:e}))},fu=()=>{const e=v.persist;if(e&&typeof e=="object")return e},pu=()=>As()?.settings??null,hu=()=>`/api/config/settings?${Ql}=${Ti()}`,Ly=e=>{Ey(e)},Ss=e=>Ty(e);class Fy{revision=0;mutations=[];operations=new Set;record(t){if(this.revision+=1,this.operations.size>0){const n=this.mutations.at(-1),r=n?[...this.operations].some(s=>s.revision>=n.revision):!0;n&&!r?(n.revision=this.revision,n.changes={...n.changes,...t}):this.mutations.push({revision:this.revision,changes:t})}return this.revision}begin(t=this.revision){const n={revision:t};return this.operations.add(n),n}reconcile(t,n){let r=t;for(const s of this.mutations)s.revision<=n.revision||(r={...r,...s.changes});return r}finish(t){if(!this.operations.delete(t))return;if(this.operations.size===0){this.mutations=[];return}const n=Math.min(...[...this.operations].map(({revision:r})=>r));this.mutations=this.mutations.filter(r=>r.revision>n)}reset(){this.mutations=[],this.operations.clear()}}let Mi=0,Ct=null,xn={},Go=!1;const _T=()=>Go,qo=e=>{Go=!0;try{Ly(e)}finally{Go=!1}};let Yt=null,Je=null,st=null,Re=null,tr=[],cc=!1,vs=0,ts=[];const _e=new Fy,Uy=2e3,jy=200,Di=()=>({runtimeKey:W(),generation:Mi}),Ms=e=>Object.keys(e),mu=(e,t)=>e===t?!0:e===void 0||t===void 0?!1:JSON.stringify(e)===JSON.stringify(t),ns=e=>{xn={...xn,...e}},Ny=e=>{const t={...xn};for(const n of e)delete t[n];xn=t},By=e=>{const t={};for(const n of Ms(e))mu(e[n],xn[n])||Object.assign(t,{[n]:e[n]});return t},dr=(e,t)=>e.runtimeKey===t.runtimeKey&&e.generation===t.generation,gu=e=>{let t=null;for(const n of ts)dr(n.context,e)&&(t={...t??{},...n.changes});return Je&&st&&dr(st,e)&&(t={...t??{},...Je}),t},lc=(e,t)=>{const n=gu(t);return e&&n?{...e,...n}:e},ie=e=>e.generation===Mi&&e.runtimeKey===W(),$n=()=>{Je&&(Re&&(clearTimeout(Re),Re=null),Ts({keepalive:!0}))},Ds=()=>{if(!(cc||typeof window>"u")){cc=!0,Kd(e=>{e.runtimeKey!==e.previousRuntimeKey&&(Re&&clearTimeout(Re),Je&&Ts())}),Yc(e=>{e.runtimeKey!==e.previousRuntimeKey&&(Mi+=1,_e.reset(),vs=0,Ct=null,Yt=null,xn={},Ke("saved"))});try{window.addEventListener("pagehide",$n,{capture:!0}),window.addEventListener("beforeunload",$n,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&$n()}),document.addEventListener("freeze",$n)),hr()&&ni(async()=>{const{App:e}=await import("./vendor-capacitor-app-BrDJj9I_.js");return{App:e}},__vite__mapDeps([3,4,5])).then(({App:e})=>e.addListener("appStateChange",({isActive:t})=>{t||$n()})).catch(()=>{})}catch{}}},yu=async(e=Di())=>{if(Ds(),Ct&&dr(Ct.context,e)&&Date.now()-Ct.at<Uy)return lc(Ct.value,e);if(Yt&&dr(Yt.context,e))return Yt.promise;const t=_e.begin(),n=gu(e),r=o=>{if(!ie(e)||!o)return null;const i=lc(_e.reconcile({...o,...n},t),e);Ct={value:i,at:Date.now(),context:e};const a={};for(const c of Ms(o))mu(o[c],i?.[c])&&Object.assign(a,{[c]:o[c]});return ns(a),i},s={context:e,promise:(async()=>{const o=pu();if(o)try{const i=await o.load();if(!ie(e))return null;const a=Ss(i.settings);return r(a)}catch(i){if(!ie(e))return null;console.warn("Failed to load shared settings from runtime settings API:",i)}if(!ie(e))return null;try{const i=await g(hu(),{method:"GET",headers:{Accept:"application/json"}});if(!ie(e)||!i.ok)return null;const a=await i.json().catch(()=>null);if(!ie(e))return null;const c=Ss(a);return r(c)}catch(i){return ie(e)&&console.warn("Failed to load shared settings from server:",i),null}})()};return Yt=s,s.promise.finally(()=>{_e.finish(t),Yt===s&&(Yt=null)}),s.promise},LT=async e=>{const t=e?.bootstrap!==!1,n=e?.adoptTheme??t;if(typeof window>"u")return;Ds();const r=Di(),s=_e.begin(),o=[fu(),Mo.persist],i=u=>!u?.hasHydrated||u.hasHydrated()||!u.onFinishHydration?Promise.resolve():new Promise(d=>{let f=!1;const p=()=>{f||(f=!0,d())},y=u.onFinishHydration(()=>{y?.(),p()});u.hasHydrated?.()&&p()}),a=()=>Promise.all(o.map(i)).then(()=>{}),c=u=>!Je||!st||!ie(st)?u:{...u,...Je},l=async u=>{if(!ie(r))return;let d=c(_e.reconcile(u,s));if(await a(),!!ie(r)){d=Cy(c(_e.reconcile(u,s)),r.runtimeKey);try{_y(d)}catch(f){console.warn("persistToLocalStorage failed:",f)}try{qo(d)}catch(f){console.warn("applyDesktopUiPreferences failed:",f)}zo(d,t,n)}};try{const u=await yu(r);u&&ie(r)?await l(u):ie(r)&&window.dispatchEvent(new Event("openchamber:settings-sync-failed"))}catch(u){ie(r)&&window.dispatchEvent(new Event("openchamber:settings-sync-failed")),console.warn("Failed to synchronise settings:",u)}finally{_e.finish(s)}};async function Ts({keepalive:e=!1}={}){let t=!1;const n=Je,r=st,s=vs,o=tr;Je=null,st=null,vs=0,Re=null,tr=[];try{if(!n||!r||Object.keys(n).length===0||!ie(r)){t=!0,Ke("saved");return}const i=_e.begin(s),a={context:r,changes:{...n}};ts.push(a),ns(n);const c=()=>Ny(Ms(n));try{const l=pu();if(l)try{const u=Ss(await l.save(n));if(!ie(r))return;if(u){ns(u);const d=_e.reconcile(u,i);qo(d),zo(d,!1),Ct=null}u||c(),t=!!u,Ke(u?"saved":"error");return}catch(u){if(!ie(r))return;console.warn("Failed to update settings via runtime settings API:",u)}if(!ie(r))return;try{const u=await g(hu(),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n),keepalive:e});if(!ie(r))return;if(!u.ok){console.warn("Failed to update shared settings via API:",u.status,u.statusText),c(),Ke("error");return}const d=Ss(await u.json().catch(()=>null));if(!ie(r))return;if(d){ns(d);const f=_e.reconcile(d,i);qo(f),zo(f,!1),t=!0,Ke("saved"),Ct=null}else c(),Ke("error")}catch(u){ie(r)&&(console.warn("Failed to update shared settings via API:",u),c(),Ke("error"))}}finally{ts=ts.filter(l=>l!==a),_e.finish(i)}}finally{o.forEach(i=>i({ok:t}))}}const FT=()=>yu(),ht=async e=>{if(typeof window>"u")return{ok:!1};Ds();const t=Di();st&&!dr(st,t)&&(Re&&clearTimeout(Re),Ts());const n={};for(const i of Ms(e))Sy(i)&&Object.assign(n,{[i]:e[i]});const r=_e.record(n),s=By({...Je??{},...n});if(Object.keys(s).length===0){Je=null,st=null,Re&&(clearTimeout(Re),Re=null);const i=tr;return tr=[],i.forEach(a=>a({ok:!0})),Ke("saved"),{ok:!0}}Je=s,st=t,vs=r,Ke("saving"),Re&&clearTimeout(Re);const o=new Promise(i=>{tr.push(i)});return Re=setTimeout(()=>{Ts()},jy),o},UT=async()=>{if(typeof window>"u")return;const e=fu();try{const t=await Mm();if(!t)return;const n=()=>Om(t);if(e?.hasHydrated?.()){n();return}if(n(),e?.onFinishHydration){const r=e.onFinishHydration(()=>{r?.(),n()})}}catch(t){console.warn("Failed to load appearance preferences:",t)}},Hy=3e4,zy=40,$y=60,Wy=(e,t,n,r,s,o,i)=>{const a=t.trim(),c=n.trim().toLowerCase();return JSON.stringify([e,a,c,r,s,o,i])},uc=(e,t)=>{try{const n=JSON.parse(e);return Array.isArray(n)&&n[1]===t}catch{return!1}},Gy=yt()(Cn((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(n,r,s=$y,o){if(!n||n.trim().length===0)return[];const i=n.trim(),a=W(),c=typeof r=="string"?r.trim():"",l=!!o?.includeHidden,u=o?.respectGitignore??!0,d=o?.type==="directory"?"directory":"file",f=Wy(a,i,c,s,l,u,d),p=Date.now(),y=t().cache[f];if(y&&p-y.timestamp<Hy)return y.files;const b=t().inFlight[f];if(b)return b;const w=rt.searchFiles(c,{directory:i,limit:s,type:d}).then(E=>(e(k=>{if(k.inFlight[f]!==w)return k;const U={...k.cache,[f]:{files:E,timestamp:Date.now()}},D=k.cacheKeys.filter(J=>J!==f);for(D.push(f);D.length>zy;){const J=D.shift();J&&delete U[J]}return{cache:U,cacheKeys:D}}),E)).finally(()=>{e(E=>{if(E.inFlight[f]!==w)return E;const k={...E.inFlight};return delete k[f],{inFlight:k}})});return e(E=>({inFlight:{...E.inFlight,[f]:w}})),w},invalidateDirectory(n){if(!n||n.trim().length===0){e({cache:{},cacheKeys:[],inFlight:{}});return}const r=n.trim();e(s=>{const o={...s.cache},i=s.cacheKeys.filter(l=>uc(l,r)?(delete o[l],!1):!0),a=Object.entries(s.inFlight).filter(([l])=>!uc(l,r)),c=Object.fromEntries(a);return{cache:o,cacheKeys:i,inFlight:c}})},resetForRuntimeSwitch(){e({cache:{},cacheKeys:[],inFlight:{}})}}),{name:"file-search-store"})),qy=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},Ko="openchamber_stream_perf",Ky=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(Ko)==="1"}catch{return!1}};let wu=Ky(),bu=!1;const on=()=>wu||bu,Su=()=>{on()||!globalThis.window||(delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState)},dc=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),vu=()=>{if(!on()||typeof window>"u")return null;if(!window.__openchamberStreamPerfState){const e=Date.now();window.__openchamberStreamPerfState={counters:new Map,startedAt:e,lastUpdatedAt:e}}return window.__openchamberStreamPerfState},Tu=e=>Array.from(e.entries()).map(([t,n])=>({metric:t,count:n.count,avg:n.count>0?Number((n.total/n.count).toFixed(3)):0,max:Number(n.max.toFixed(3)),total:Number(n.total.toFixed(3)),last:Number(n.last.toFixed(3))})).sort((t,n)=>n.total-t.total||n.count-t.count),_i=(e,t)=>{const n=vu();if(!n)return;const r=n.counters.get(e)??{count:0,total:0,max:0,last:0};r.count+=1,r.total+=t,r.max=Math.max(r.max,t),r.last=t,n.counters.set(e,r),n.lastUpdatedAt=Date.now()},Vy=e=>{if(wu=e,!(typeof window>"u"))try{if(e){window.localStorage.setItem(Ko,"1"),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(Ko),Su()}catch{}},jT=e=>{if(bu=e,!(typeof window>"u")){if(e){vu();return}Su()}},Jy=()=>{typeof window>"u"||(on()&&(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()}))},Yy=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberStreamPerfState;return!on()||!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:Tu(e.counters)}},NT=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberVsCodeStreamPerfState;if(!on()||!e)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const t=typeof e.startedAt=="number"?e.startedAt:null,n=typeof e.lastUpdatedAt=="number"?e.lastUpdatedAt:null;return{enabled:!0,startedAt:t,lastUpdatedAt:n,durationMs:t?Math.max(0,Date.now()-t):0,entries:Tu(e.counters)}},BT=(e,t=1)=>{_i(e,t)},HT=(e,t)=>{_i(e,t)},zT=e=>{!on()||typeof performance>"u"||typeof performance.mark!="function"||performance.mark(`openchamber.${e}`)},$T=(e,t)=>{if(!on())return t();const n=dc();try{return t()}finally{_i(e,dc()-n)}};typeof window<"u"&&(window.__openchamberStreamPerformance={setEnabled:Vy,reset:Jy,getSnapshot:Yy});var Qy={};let ot=null,fc=0;const Ve=gr(),pc=Ve.getItem("lastDirectory"),Xy=typeof pc=="string"&&pc.length>0,Kr=e=>{try{Gy.getState().invalidateDirectory(e)}catch(t){console.warn("Failed to invalidate file search cache:",t)}},Rn=e=>Ye(e)??"",Zy=(e,t)=>{const n=e.trim();return n.startsWith("~")?n==="~"?t||n:(n.startsWith("~/")||n.startsWith("~\\"))&&t?`${t}${n.slice(1)}`:n:n},rs=(e,t)=>{const n=Zy(e,t);return Rn(n)},ew=()=>{const e=Ve.getItem("homeDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Rn(e);return t.length>0?t:null},tw=()=>{const e=Ve.getItem("lastDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Rn(e);return t.length>0?t:null},nw=()=>{if(typeof process>"u")return null;const e=Qy,t=e?.HOME||e?.USERPROFILE||(e?.HOMEDRIVE&&e?.HOMEPATH?`${e.HOMEDRIVE}${e.HOMEPATH}`:void 0);if(typeof t=="string"&&t.trim().length>0){const r=Rn(t);return r.length>0?r:null}const n=process?.cwd?.();if(typeof n=="string"&&n.trim().length>0){const r=Rn(n);return r.length>0?r:null}return null},Li=()=>{if(typeof window<"u"){if(ot)return ot;const t=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(t&&t.length>0)return ot=t,Ve.setItem("homeDirectory",t),t;const n=ew();if(n&&!Le())return ot=n,n}const e=nw();return e||"/"},rw=e=>{const t=Ye(e);return t&&t!=="/"?t:null},sw=e=>(ot=e,typeof window<"u"&&Ve.setItem("homeDirectory",e),ht({homeDirectory:e}),e),Vo=async()=>{const e=r=>{const s=rw(r);return s?sw(s):null};try{const r=await rt.getFilesystemHome(),s=e(r);if(s)return s}catch(r){console.warn("Failed to obtain filesystem home directory:",r)}try{const r=await rt.getSystemInfo(),s=e(r?.homeDirectory);if(s)return s}catch(r){console.warn("Failed to get home directory from system info:",r)}try{const r=await Zc(),s=e(r);if(s)return s}catch(r){console.warn("Failed to obtain desktop-integrated home directory:",r)}const t=Li(),n=e(t);return n||t},ow=()=>{if(!Le())return null;const e=Qc()?.workspaceFolder;if(typeof e!="string"||e.trim().length===0)return null;const t=Rn(e);return t.length>0?t:null},fr=ow()||Li(),ks=(()=>{const e=tw();return e&&!Le()?rs(e,fr):fr})();ks&&rt.setDirectory(ks);const iw=!!(fr&&fr!=="/"),Jo=yt()(Cn((e,t)=>({currentDirectory:ks,directoryHistory:[ks],historyIndex:0,homeDirectory:fr,hasPersistedDirectory:Xy,isHomeReady:iw,isSwitchingDirectory:!1,setDirectory:(n,r)=>{const s=ot||t().homeDirectory||Ve.getItem("homeDirectory"),o=rs(n,s);qy()&&console.log("[DirectoryStore] setDirectory called with path:",o),rt.setDirectory(o),Kr(),e(i=>{const a=i.directoryHistory[i.historyIndex]===o,c=a?i.directoryHistory:[...i.directoryHistory.slice(0,i.historyIndex+1),o];return Ve.setItem("lastDirectory",o),ht({lastDirectory:o}),{currentDirectory:o,directoryHistory:c,historyIndex:a?i.historyIndex:c.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const n=t();if(n.historyIndex>0){const r=n.historyIndex-1,s=n.directoryHistory[r];rt.setDirectory(s),Kr(),Ve.setItem("lastDirectory",s),ht({lastDirectory:s}),e({currentDirectory:s,historyIndex:r,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const n=t();if(n.historyIndex<n.directoryHistory.length-1){const r=n.historyIndex+1,s=n.directoryHistory[r];rt.setDirectory(s),Kr(),Ve.setItem("lastDirectory",s),ht({lastDirectory:s}),e({currentDirectory:s,historyIndex:r,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:n,setDirectory:r}=t(),s=ot||t().homeDirectory||Li();if(n===s)return;const o=Bp(n);o&&r(o)},goHome:async()=>{const n=ot||t().homeDirectory||await Vo();t().setDirectory(n)},synchronizeHomeDirectory:n=>{const r=t(),s=n;ot=s;const o=r.homeDirectory!==s,i=Ve.getItem("lastDirectory"),a=typeof i=="string"&&i.length>0,c=!a&&(r.currentDirectory==="/"||r.currentDirectory===r.homeDirectory||!r.currentDirectory);if(!o&&!c){r.isHomeReady||e({isHomeReady:!0});return}const l=typeof s=="string"&&s!==""&&s!=="/",u=r.currentDirectory?rs(r.currentDirectory,s):r.currentDirectory,d=r.directoryHistory.map(b=>rs(b,s)),f=d.some((b,w)=>b!==r.directoryHistory[w]),p=!!(u&&u!==r.currentDirectory),y={homeDirectory:s,hasPersistedDirectory:a,isHomeReady:l};if(c?(y.currentDirectory=s,y.directoryHistory=[s],y.historyIndex=0,y.isSwitchingDirectory=!1):(p||f)&&(y.currentDirectory=u,y.directoryHistory=d,y.historyIndex=Math.min(r.historyIndex,d.length-1),y.isSwitchingDirectory=!1),e(()=>y),(c||p)&&l){const b=c?s:u;rt.setDirectory(b),Kr(),Ve.setItem("lastDirectory",b),ht({lastDirectory:b})}ht({homeDirectory:s})}}),{name:"directory-store"}));typeof window<"u"&&(Vo().then(e=>{Jo.getState().synchronizeHomeDirectory(e)}),Yc(()=>{ot=null;const e=++fc;Vo().then(t=>{e===fc&&Jo.getState().synchronizeHomeDirectory(t)})}));const aw=(e,t)=>{const n=Is();return n?n.openWebSocket(Rd(e),t):lf(new WebSocket(e))},ku=1,hc=512*1024,cw=0,hn=1,lw=15e3,Fi=new TextEncoder,Eu=new TextDecoder,Ui=ke(["interactive","command"]),Pu=ke(["running","exited","error"]),uw=ke(["node","bun"]),ji=Es("type",[T({type:N("terminal")}),T({type:N("project-action"),actionId:m(),executionId:m()})]),dw=T({sessionId:m(),cols:R(),rows:R(),status:Pu,mode:Ui.optional(),purpose:ji.optional()}),fw=T({sessionId:m(),cwd:m(),status:ke(["running","exited"]),createdAt:R().nullable().optional().transform(e=>e??null),mode:Ui.optional(),purpose:ji.optional()}),mc={mode:Ui.optional(),purpose:ji.optional()},pw=Es("t",[T({t:N("hello")}),T({t:N("pong")}),T({t:N("error"),s:m().optional(),message:m().optional(),code:m().optional(),fatal:Ne().optional()}),T({t:N("snapshot"),s:m(),q:R().int().nonnegative().default(0),history:m().default(""),status:Pu,cols:R().int().positive().optional(),rows:R().int().positive().optional(),exitCode:R().nullish().transform(e=>e??void 0),signal:R().nullable().optional(),runtime:uw.optional(),ptyBackend:m().optional(),...mc}),T({t:N("output"),s:m(),q:R().int().nonnegative(),d:m(),r:m().optional()}),T({t:N("exit"),s:m(),q:R().int().nonnegative(),exitCode:R().nullish().transform(e=>e??void 0),signal:R().nullable().optional()}),T({t:N("restarted"),s:m(),q:R().int().nonnegative(),history:m().default(""),...mc})]),hw=e=>{const t=Fi.encode(JSON.stringify(e)),n=new Uint8Array(t.length+1);return n[0]=ku,n.set(t,1),n},mw=e=>{let t=e instanceof ArrayBuffer?new Uint8Array(e):Fi.encode(e);t[0]===ku&&(t=t.subarray(1));try{return pw.safeParse(JSON.parse(Eu.decode(t))).data??null}catch{return null}};class gw extends Error{code;constructor(t,n){super(t),this.name="TerminalRequestError",this.code=n}}const WT=e=>e.cols!==void 0&&e.rows!==void 0?{cols:e.cols,rows:e.rows}:void 0,yw=T({error:m().optional(),code:m().optional()}),_s=async(e,t)=>{const n=yw.safeParse(await e.json().catch(()=>null)).data;return new gw(n?.error??t,n?.code??null)},ww=e=>{const t=Fi.encode(e);if(t.byteLength<=hc)return e;let n=t.byteLength-hc;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;return Eu.decode(t.subarray(n))},bw=T({sessions:G(me())});class Au{constructor(t={refreshAuth:Cs,openSocket:()=>aw(Pe().websocket("/api/terminal/ws")),clearUrlAuthToken:mr}){this.dependencies=t}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,n){this.cancelIdleClose();const r={handlers:n,lastSequence:-1},s=this.subscribers.get(t)??new Set,o=s.size===0;s.add(r),this.subscribers.set(t,s);const i=this.projections.get(t);i&&(r.lastSequence=i.sequence,n.onEvent({type:"snapshot",sequence:i.sequence,data: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 a=this.socket?.readyState===hn;return this.ensureConnected().then(()=>{const c=this.subscribers.get(t);o&&a&&c===s&&c.size>0&&this.send({t:"attach",v:3,s:t})}).catch(c=>{s.has(r)&&(n.onError?.(c,!1),this.scheduleReconnect())}),()=>{const c=this.subscribers.get(t);if(c?.delete(r),c?.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===hn){this.scheduleIdleClose();return}this.generation+=1,this.opening=null,this.closeSocket()}}}async write(t,n){if(n&&(await this.ensureConnected(),!this.send({t:"write",v:3,s:t,d:n})&&(this.closeSocket(),await this.ensureConnected(),!this.send({t:"write",v:3,s:t,d:n}))))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,n,r){const s=this.projections.get(t);s&&this.projections.set(t,{...s,cols:n,rows:r})}async ensureConnected(){if(this.disposed)throw new Error("Terminal runtime changed");if(this.socket?.readyState===hn)return;if(this.opening)return await this.opening,this.socket?.readyState===hn?void 0:this.ensureConnected();const t=this.generation,n=(async()=>{if(await this.dependencies.refreshAuth(),t!==this.generation||this.disposed)throw new Error("Terminal runtime changed");await new Promise((r,s)=>{let o=!1,i=!1,a=!1,c=null;const l=()=>t===this.generation&&!this.disposed&&c!==null&&this.socket===c,u=()=>{a||i||!l()||(a=!0,this.dependencies.clearUrlAuthToken?.())},d=p=>{o||(o=!0,clearTimeout(f),p?s(p):r())},f=setTimeout(()=>{u(),c?.close(),d(new Error("Terminal connection timed out"))},1e4);try{const p=this.dependencies.openSocket();c=p,p.binaryType="arraybuffer",this.socket=p,p.onopen=()=>{if(!l()){p.close(),d(new Error("Terminal runtime changed"));return}i=!0,this.failures=0,this.send({t:"hello",v:3});for(const y of this.subscribers.keys())this.send({t:"attach",v:3,s:y});this.startKeepalive(),d()},p.onmessage=y=>{this.handleMessage(y.data)},p.onerror=()=>{const y=l();y&&u(),d(new Error("Terminal WebSocket failed")),y&&this.subscribers.size>0&&this.scheduleReconnect()},p.onclose=()=>{const y=l();y&&(this.stopKeepalive(),u()),this.socket===p&&(this.socket=null),d(new Error("Terminal WebSocket closed")),y&&this.subscribers.size>0&&this.scheduleReconnect()}}catch(p){d(p instanceof Error?p:new Error("Terminal WebSocket failed")),!this.disposed&&this.subscribers.size>0&&this.scheduleReconnect()}})})();this.opening=n;try{await n}finally{this.opening===n&&(this.opening=null)}}handleMessage(t){const n=mw(t);if(!n||n.t==="hello"||n.t==="pong")return;if(n.t==="error"){const o=new Error(n.message??"Terminal error");o.code=n.code;const i=n.s?[n.s]:[...this.subscribers.keys()];for(const a of i)for(const c of this.subscribers.get(a)??[])c.handlers.onError?.(o,n.fatal===!0);return}if(!n.s)return;const r=this.subscribers.get(n.s);if(!r)return;if(n.t==="snapshot"){const o={sequence:n.q??0,history:n.history??"",cols:n.cols,rows:n.rows,status:n.status,mode:n.mode,purpose:n.purpose,exitCode:n.exitCode,signal:n.signal??null,runtime:n.runtime,ptyBackend:n.ptyBackend};this.projections.set(n.s,o);for(const i of r)i.lastSequence=o.sequence,i.handlers.onEvent({type:"snapshot",sequence:o.sequence,data:o.history,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 s=this.projections.get(n.s);s&&n.q>s.sequence&&(n.t==="output"?this.projections.set(n.s,{...s,sequence:n.q,history:ww(s.history+(n.r??n.d))}):n.t==="exit"?this.projections.set(n.s,{...s,sequence:n.q,status:"exited",exitCode:n.exitCode,signal:n.signal??null}):n.t==="restarted"&&this.projections.set(n.s,{...s,sequence:n.q,history:n.history??"",status:"running",mode:n.mode??s.mode,purpose:n.purpose??s.purpose,exitCode:void 0,signal:null}));for(const o of r)n.q<=o.lastSequence||(o.lastSequence=n.q,n.t==="output"?o.handlers.onEvent({type:"data",sequence:n.q,data:n.d,replayData:n.r}):n.t==="exit"?o.handlers.onEvent({type:"exit",sequence:n.q,exitCode:n.exitCode,signal:n.signal??null}):n.t==="restarted"&&o.handlers.onEvent({type:"snapshot",sequence:n.q,data:n.history??"",status:"running",mode:n.mode??s?.mode,purpose:n.purpose??s?.purpose}))}send(t){if(!this.socket||this.socket.readyState!==hn)return!1;try{return this.socket.send(hw(t)),!0}catch{return!1}}scheduleReconnect(){if(this.reconnectTimer||this.disposed||this.subscribers.size===0)return;this.failures+=1;const n=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 s of this.subscribers.values())for(const o of s)o.handlers.onEvent({type:"reconnecting",attempt:this.failures,maxAttempts:Number.POSITIVE_INFINITY});const r=()=>{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",r),typeof document<"u"&&document.addEventListener("visibilitychange",r),this.wakeCleanup=()=>{typeof window<"u"&&window.removeEventListener("online",r),typeof document<"u"&&document.removeEventListener("visibilitychange",r)},this.reconnectTimer=setTimeout(r,n)}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())},lw))}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===cw||t.readyState===hn)&&t.close()}}let Ft=new Au;async function Sw(e){const t=await g("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw await _s(t,"Failed to create terminal session");const n=await t.json().catch(()=>null),r=dw.safeParse(n).data;if(!r)throw new Error("Failed to create terminal session");return r}async function vw(e){const t=await g(`/api/terminal/sessions?cwd=${encodeURIComponent(e)}`);if(!t.ok)throw await _s(t,"Failed to list terminal sessions");const n=await t.json().catch(()=>null),r=bw.safeParse(n).data?.sessions;if(!Array.isArray(r))throw new Error("Failed to list terminal sessions");const s=[];for(const o of r){const i=fw.safeParse(o).data;i&&s.push(i)}return s}async function Tw(e){e.length!==0&&await Dn("/api/terminal/touch","POST",{sessionIds:e})}async function kw(){const e=await g("/api/terminal/shells");if(!e.ok)throw await _s(e,"Failed to list terminal shells");const t=await e.json().catch(()=>[]);return Array.isArray(t)?t.filter(n=>n&&typeof n=="object"&&Ei(n.id)&&typeof n.name=="string"&&typeof n.supportsLogin=="boolean"):[]}function Ew(e,t,n){return Ft.subscribe(e,{onEvent:t,onError:n})}async function Pw(e,t){await Ft.write(e,t)}async function Dn(e,t,n){const r={method:t};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const s=await g(e,r);if(!s.ok)throw await _s(s,"Terminal command failed");return s}async function Aw(e,t,n){await Dn(`/api/terminal/${e}/resize`,"POST",{cols:t,rows:n}),Ft.noteResize(e,t,n)}async function Iw(e,t){await Dn(`/api/terminal/${e}/appearance`,"POST",t)}async function xw(e){await Dn(`/api/terminal/${e}`,"DELETE"),Ft.forget(e)}async function Rw(e,t){return(await Dn(`/api/terminal/${e}/restart`,"POST",t)).json()}async function Cw(e){const n=await(await Dn("/api/terminal/force-kill","POST",e)).json().catch(()=>null);if(Array.isArray(n?.killedSessionIds))for(const r of n.killedSessionIds)typeof r=="string"&&Ft.forget(r);else e.sessionId&&Ft.forget(e.sessionId)}function GT(){Ft.dispose(),Ft=new Au}const Ow=()=>({async listShells(){return kw()},async listSessions(e){return vw(e)},async touchSessions(e){await Tw(e)},async createSession(e){return Sw(e)},connect(e,t){const n=Ew(e,t.onEvent,t.onError);return{close:()=>n()}},async sendInput(e,t){await Pw(e,t)},async resize(e){await Aw(e.sessionId,e.cols,e.rows)},async updateAppearance(e,t){await Iw(e,t)},async close(e){await xw(e)},async restartSession(e,t){return Rw(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 Cw(e)}}),Yo=new Set,Mw=e=>(Yo.add(e),()=>{Yo.delete(e)}),Dw=e=>{for(const t of Yo)t(e)},Qo=new Set,_w=(e,t)=>JSON.stringify([t,Ye(e)]);function qT(e){return Qo.add(e),()=>{Qo.delete(e)}}function Lw(e,t){const n=_w(e,t);for(const r of Qo)r(n)}class Fw extends Error{reason;constructor(t,n){super(t),this.name="GitPathUnavailableError",this.reason=n}}const Uw=T({error:m(),code:ke(["path_not_found","nested_repository","untracked_directory"])}),Iu=T({headCommit:m().nullable(),indexCommit:m().nullable(),worktreeCommit:m().nullable(),hasTrackedChanges:Ne(),hasUntrackedFiles:Ne(),hasConflict:Ne()}),P="/api/git",xu=T({diff:m()}),jw=T({files:G(T({path:m(),status:m()}))}),Nw=T({error:m()}),Bw=T({files:G(T({path:m(),previousPath:m().optional(),changeType:m(),insertions:R(),deletions:R(),isBinary:Ne()}))}),gc=T({hash:m(),date:m(),message:m(),refs:m(),body:m(),author_name:m(),author_email:m(),filesChanged:R(),insertions:R(),deletions:R(),parents:G(m())}),Hw=T({all:G(gc),latest:gc.nullable(),total:R()}),zw=T({diff:m(),submodule:Iu.nullable().default(null)}),$w=T({original:m(),modified:m(),path:m(),isBinary:Ne().optional(),submodule:Iu.nullable().default(null)});async function Ru(e,t){const n=Uw.safeParse(await e.json().catch(()=>null));return n.success&&(e.status===404||e.status===422)?new Fw(n.data.error,n.data.code):new Error(`${t}: ${e.statusText}`)}async function Ls(e,t){const n=Nw.safeParse(await e.json().catch(()=>null));return new Error(n.success?n.data.error:`${t}: ${e.statusText}`)}const Ww=1200,Gw=5e3,Xo=new Map,Vn=new Map,Cu=new Map,yc=new Map,Vr=new Map,Ou=e=>e.trim(),Ni=(e,t)=>JSON.stringify([e,Ou(t)]),Mu=(e,t,n)=>JSON.stringify([e,Ou(t),n??"full"]),Zo=(e,t)=>Cu.get(Ni(e,t))??0,Du=(e,t)=>{const n=Ni(e,t);Cu.set(n,Zo(e,t)+1);for(const r of[void 0,"light"]){const s=Mu(e,t,r);Xo.delete(s),Vn.delete(s)}};Mw(e=>{Du(W(),e)});const Sr=e=>{Dw(e)},ne=async(e,t)=>{const n=await t.json();return Sr(e),n};function I(e,t,n){const r={...n};return t&&(r.directory=t),Pe().api(e,r)}async function qw(e){const t=Ni(W(),e),n=Date.now(),r=yc.get(t);if(r&&r.expiresAt>n)return r.value;const s=Vr.get(t);if(s)return s;const o=(async()=>{const i=await g(I(`${P}/check`,e));if(!i.ok)throw new Error(`Failed to check git repository: ${i.statusText}`);const c=!!(await i.json()).isGitRepository;return yc.set(t,{value:c,expiresAt:Date.now()+Gw}),c})();Vr.set(t,o);try{return await o}finally{Vr.get(t)===o&&Vr.delete(t)}}class Kw extends Error{constructor(){super("Nested git repository discovery is not supported by this runtime"),this.name="GitDirectoriesUnsupportedError"}}async function KT(e){const t=await g("/api/fs/git-dirs",{query:{path:e,directory:e}});if(t.status===501)throw new Kw;if(!t.ok)throw new Error(`Failed to list git directories: ${t.statusText}`);const n=await t.json();if(!Array.isArray(n?.repositories))throw new Error("Unexpected git directories response");return n.repositories.map(r=>Ye(r?.path??null)).filter(r=>r!==null)}async function Vw(e,t){const n=t?.mode,r=W();t?.fresh&&Du(r,e);const s=Mu(r,e,n),o=Date.now(),i=Xo.get(s);if(i&&i.expiresAt>o)return i.value;const a=Vn.get(s);if(a)return a;const c=(async()=>{const l=Zo(r,e),u=await g(I(`${P}/status`,e,n?{mode:n}:void 0));if(!u.ok)throw new Error(`Failed to get git status: ${u.statusText}`);const d=await u.json();return Zo(r,e)===l&&Xo.set(s,{value:d,expiresAt:Date.now()+Ww}),d})();Vn.set(s,c);try{return await c}finally{Vn.get(s)===c&&Vn.delete(s)}}async function VT(e){const t=await g(I(`${P}/primary-root`,e));if(!t.ok)throw new Error(`Failed to resolve git primary root: ${t.statusText}`);const n=await t.json().catch(()=>({}));return{root:typeof n.root=="string"&&n.root?n.root:e}}async function JT(e){const t=await g(I(`${P}/toplevel`,e));if(!t.ok)throw new Error(`Failed to resolve git toplevel: ${t.statusText}`);const n=await t.json().catch(()=>({}));return{root:typeof n.root=="string"&&n.root?n.root:e}}async function YT(e,t){const n=await g(I(`${P}/commit-summaries`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shas:t})});if(!n.ok)throw new Error(`Failed to get git commit summaries: ${n.statusText}`);const r=await n.json().catch(()=>({}));return{commits:Array.isArray(r.commits)?r.commits.map(s=>({sha:typeof s.sha=="string"?s.sha:"",short:typeof s.short=="string"?s.short:"",subject:typeof s.subject=="string"?s.subject:""})).filter(s=>s.sha&&s.short):[]}}async function Jw(e,t){const{path:n,staged:r,contextLines:s}=t;if(!n)throw new Error("path is required to fetch git diff");const o=await g(I(`${P}/diff`,e,{path:n,staged:r?"true":void 0,context:s}));if(!o.ok)throw await Ru(o,"Failed to get git diff");return zw.parse(await o.json())}async function Yw(e,t){const{base:n,head:r,path:s,contextLines:o,includeWorkingTree:i}=t;if(!n||!r)throw new Error("base and head are required to fetch git range diff");const a=await g(I(`${P}/range-diff`,e,{base:n,head:r,path:s||void 0,context:o,includeWorkingTree:i}));if(!a.ok)throw await Ls(a,"Failed to get git range diff");return xu.parse(await a.json())}async function Qw(e,t){const n=await g(I(`${P}/commit-diff`,e,{hash:t.hash,path:t.path,previousPath:t.previousPath,context:t.contextLines}));if(!n.ok)throw await Ls(n,"Failed to get commit diff");return xu.parse(await n.json())}async function Xw(e,t){const{base:n,head:r,includeWorkingTree:s}=t;if(!n||!r)throw new Error("base and head are required to fetch git range files");const o=await g(I(`${P}/range-files`,e,{base:n,head:r,includeWorkingTree:s}));if(!o.ok)throw await Ls(o,"Failed to get git range files");return jw.parse(await o.json()).files}async function Zw(e,t){if(!t)throw new Error("branch is required to get branch base");const n=await g(I(`${P}/branch-base`,e,{branch:t}));if(!n.ok)throw new Error(`Failed to get branch base: ${n.statusText}`);return n.json()}async function eb(e,t){const{path:n,staged:r}=t;if(!n)throw new Error("path is required to fetch git file diff");const s=await g(I(`${P}/file-diff`,e,{path:n,staged:r?"true":void 0}));if(!s.ok)throw await Ru(s,"Failed to get git file diff");return $w.parse(await s.json())}async function tb(e,t,n){if(!t)throw new Error("path is required to revert git changes");const r=await g(I(`${P}/revert`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,scope:n?.scope})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to revert git changes")}Sr(e)}async function nb(e,t){await _u(e,[t])}async function _u(e,t){const n=t.map(s=>s.trim()).filter(Boolean);if(n.length===0)throw new Error("path is required to stage git changes");const r=await g(I(`${P}/stage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to stage git changes")}Sr(e)}async function rb(e,t){await Lu(e,[t])}async function Lu(e,t){const n=t.map(s=>s.trim()).filter(Boolean);if(n.length===0)throw new Error("path is required to unstage git changes");const r=await g(I(`${P}/unstage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to unstage git changes")}Sr(e)}async function sb(e,t,n){await Bi(e,t,n,"stage")}async function ob(e,t,n){await Bi(e,t,n,"unstage")}async function ib(e,t,n){await Bi(e,t,n,"discard")}async function Bi(e,t,n,r){if(!t)throw new Error("path is required to apply a git hunk");if(typeof n!="string"||!n.trim())throw new Error("patch is required to apply a git hunk");const s=await g(I(`${P}/apply-hunk`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,patch:n,action:r})});if(!s.ok){const o=await s.json().catch(()=>({error:s.statusText}));throw new Error(o.error||"Failed to apply git hunk")}Sr(e)}async function ab(e){if(!e)return!1;const t=await g(I(`${P}/worktree-type`,e));if(!t.ok)throw new Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function cb(e){const t=await g(I(`${P}/branches`,e));if(!t.ok)throw new Error(`Failed to get branches: ${t.statusText}`);return t.json()}async function lb(e,t){const n=await g(I(`${P}/branch-push-status`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branches:t})});if(!n.ok)throw new Error(`Failed to get branch push status: ${n.statusText}`);return n.json()}async function ub(e,t){if(!t?.branch)throw new Error("branch is required to delete a branch");const n=await g(I(`${P}/branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to delete branch")}return ne(e,n)}async function db(e,t){if(!t?.branch)throw new Error("branch is required to delete remote branch");const n=await g(I(`${P}/remote-branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to delete remote branch")}return ne(e,n)}async function fb(e,t){const n=t?.remote?.trim();if(!n)throw new Error("remote is required to remove a remote");const r=await g(I(`${P}/remotes`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({remote:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to remove remote")}return ne(e,r)}async function pb(e,t,n){if(!Array.isArray(t)||t.length===0)throw new Error("No files provided to generate commit message");const r={files:t};n?.zenModel&&(r.zenModel=n.zenModel),n?.providerId&&(r.providerId=n.providerId),n?.modelId&&(r.modelId=n.modelId);const s=await g(I(`${P}/commit-message`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const c=await s.json().catch(()=>({error:s.statusText}));console.error("[git-generation][browser] http error",{status:s.status,statusText:s.statusText,error:c});const l=typeof c?.traceId=="string"&&c.traceId?` (traceId: ${c.traceId})`:"";throw new Error(`${c.error||"Failed to generate commit message"}${l}`)}const o=await s.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():"",a=Array.isArray(o.message.highlights)?o.message.highlights.filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim()):[];return{message:{subject:i,highlights:a}}}async function hb(e,t){const{base:n,head:r,context:s,zenModel:o,providerId:i,modelId:a}=t;if(!n||!r)throw new Error("base and head are required");const c={base:n,head:r};s?.trim()&&(c.context=s.trim()),o&&(c.zenModel=o),i&&(c.providerId=i),a&&(c.modelId=a);const l=await g(I(`${P}/pr-description`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok){const p=await l.json().catch(()=>({error:l.statusText}));throw new Error(p.error||"Failed to generate PR description")}const u=await l.json().catch(()=>null),d=typeof u?.title=="string"?u.title:"",f=typeof u?.body=="string"?u.body:"";if(!d&&!f)throw new Error("Malformed PR description response");return{title:d,body:f}}async function wc(e){const t=await g(I(`${P}/worktrees`,e));if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to list worktrees")}return t.json()}async function bc(e,t){const n=await g(I(`${P}/worktrees/validate`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to validate worktree")}return n.json()}async function mb(e){const t=await g(I(`${P}/worktrees/bootstrap-status`,e));if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to get worktree bootstrap status")}return t.json()}async function gb(e,t){const n=await g(I(`${P}/worktrees/preview`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to preview worktree")}return n.json()}async function Sc(e,t){const n=await g(I(`${P}/worktrees`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to create worktree")}return n.json()}async function vc(e,t){const n=await g(I(`${P}/worktrees`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to delete worktree")}return n.json()}async function yb(e,t,n={}){const r=await g(I(`${P}/commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:t,addAll:n.addAll??!1,files:n.files,stageFiles:n.stageFiles})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to create commit")}return ne(e,r)}async function wb(e,t={}){const n=W(),r=await g(I(`${P}/push`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to push")}const s=await ne(e,r);return s.success&&Lw(e,n),s}async function bb(e,t={}){const n=await g(I(`${P}/pull`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to pull")}return ne(e,n)}async function Sb(e,t={}){const n=await g(I(`${P}/fetch`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to fetch")}return ne(e,n)}async function vb(e){const t=await g(I(`${P}/stashes`,e));if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to list stashes")}return t.json()}async function Tb(e,t){const n=await g(I(`${P}/stashes/file-counts`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refs:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to count stash files")}return n.json()}async function Fu(e,t={}){const n=await g(I(`${P}/stash`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to stash changes")}return ne(e,n)}const Hi=async(e,t,n)=>{const r=await g(I(`${P}/${t}`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||`Failed to ${t}`)}return ne(e,r)},kb=(e,t)=>Hi(e,"stash/apply",t),Uu=(e,t)=>Hi(e,"stash/pop",t),Eb=(e,t)=>Hi(e,"stash/drop",t);async function Pb(e,t){const n=await g(I(`${P}/checkout`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to checkout branch")}return ne(e,n)}async function Ab(e,t,n){const r=await g(I(`${P}/branches`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,startPoint:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to create branch")}return ne(e,r)}async function Ib(e,t,n){const r=await g(I(`${P}/branches/rename`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:t,newName:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to rename branch")}return ne(e,r)}async function xb(e,t={}){const n=await g(I(`${P}/log`,e,{maxCount:t.maxCount,from:t.from,to:t.to,file:t.file,all:t.all?"true":void 0}));if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(`Failed to get git log: ${r.error||n.statusText}`)}return Hw.parse(await n.json())}async function Rb(e,t){const n=await g(I(`${P}/commit-files`,e,{hash:t}));if(!n.ok)throw await Ls(n,"Failed to get commit files");return Bw.parse(await n.json())}async function QT(e,t,n,r){const s=await g(I(`${P}/commit-file-diff`,e,{hash:t,path:n,binary:r?"true":void 0}));if(!s.ok)throw new Error(`Failed to get commit file diff: ${s.statusText}`);return s.json()}async function Cb(){const e=await g(I(`${P}/identities`,void 0));if(!e.ok)throw new Error(`Failed to get git identities: ${e.statusText}`);return e.json()}async function Ob(e){const t=await g(I(`${P}/identities`,void 0),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to create git identity")}return t.json()}async function Mb(e,t){const n=await g(I(`${P}/identities/${e}`,void 0),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to update git identity")}return n.json()}async function Db(e){const t=await g(I(`${P}/identities/${e}`,void 0),{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to delete git identity")}}async function _b(e){if(!e)return null;const t=await g(I(`${P}/current-identity`,e));if(!t.ok)throw new Error(`Failed to get current git identity: ${t.statusText}`);const n=await t.json();return n?{userName:n.userName??null,userEmail:n.userEmail??null,sshCommand:n.sshCommand??null}:null}async function Lb(e){if(!e)return!1;const t=await g(I(`${P}/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 XT(){const e=await g(I(`${P}/global-identity`,void 0));if(!e.ok)throw new Error(`Failed to get global git identity: ${e.statusText}`);const t=await e.json();return!t||!t.userName&&!t.userEmail?null:{userName:t.userName??null,userEmail:t.userEmail??null,sshCommand:t.sshCommand??null}}async function Fb(e,t){const n=await g(I(`${P}/set-identity`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to set git identity")}return n.json()}async function ZT(){const e=await g(I(`${P}/discover-credentials`,void 0));if(!e.ok)throw new Error(`Failed to discover git credentials: ${e.statusText}`);return e.json()}async function ek(e,t){if(!e)return null;const n=await g(I(`${P}/remote-url`,e,{remote:t}));return n.ok?(await n.json()).url??null:null}async function Ub(e){const t=await g(I(`${P}/remotes`,e));if(!t.ok)throw new Error(`Failed to get remotes: ${t.statusText}`);return t.json()}async function jb(e,t){const n=await g(I(`${P}/rebase`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to rebase")}return ne(e,n)}async function Nb(e){const t=await g(I(`${P}/rebase/abort`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to abort rebase")}return ne(e,t)}async function Bb(e,t){const n=await g(I(`${P}/merge`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to merge")}return ne(e,n)}async function Hb(e,t){const n=await g(I(`${P}/checkout-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to checkout commit")}return ne(e,n)}async function zb(e,t){const n=await g(I(`${P}/cherry-pick`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to cherry-pick")}return ne(e,n)}async function $b(e,t){const n=await g(I(`${P}/revert-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to revert commit")}return ne(e,n)}async function Wb(e,t,n,r){const s=await g(I(`${P}/reset-to-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t,mode:n,force:r})});if(!s.ok){const o=await s.json().catch(()=>({error:s.statusText}));throw new Error(o.error||"Failed to reset")}return ne(e,s)}async function Gb(e){const t=await g(I(`${P}/merge/abort`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to abort merge")}return ne(e,t)}async function qb(e){const t=await g(I(`${P}/rebase/continue`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to continue rebase")}return ne(e,t)}async function Kb(e){const t=await g(I(`${P}/merge/continue`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to continue merge")}return ne(e,t)}async function Vb(e,t){return await Fu(e,{message:t?.message}),{success:!0}}async function Jb(e){return await Uu(e,{ref:"stash@{0}"}),{success:!0}}async function Yb(e){const t=await g(I(`${P}/conflict-details`,e));if(!t.ok)throw new Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function Qb(e,t){const n=await g(`${P}/validate-directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e,worktreeRoot:t})});if(!n.ok)throw new Error(`Failed to validate worktree directory: ${n.statusText}`);return n.json()}async function Xb(e){const t=await g(`${P}/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 Zb=()=>({checkIsGitRepository:qw,getGitStatus:Vw,getGitDiff:Jw,getGitFileDiff:eb,getGitRangeDiff:Yw,getGitRangeFiles:Xw,getBranchBase:Zw,revertGitFile:tb,stageGitFile:nb,stageGitFiles:_u,unstageGitFile:rb,unstageGitFiles:Lu,stageGitHunk:sb,unstageGitHunk:ob,revertGitHunk:ib,isLinkedWorktree:ab,getGitBranches:cb,getGitUnpushedBranchCounts:lb,deleteGitBranch:ub,deleteRemoteBranch:db,removeRemote:fb,generateCommitMessage:pb,generatePullRequestDescription:hb,listGitWorktrees:wc,validateGitWorktree:bc,createGitWorktree:Sc,deleteGitWorktree:vc,validateWorktreeDirectory:Qb,canonicalizeWorktreeState:Xb,createGitCommit(e,t,n){return yb(e,t,n)},gitPush:wb,gitPull:bb,gitFetch:Sb,listGitStashes:vb,countGitStashFiles:Tb,stashGitChanges:Fu,applyGitStash:kb,popGitStash:Uu,dropGitStash:Eb,checkoutBranch:Pb,createBranch:Ab,renameBranch:Ib,getGitLog(e,t){return xb(e,t)},getCommitFiles:Rb,getGitCommitDiff:Qw,getCurrentGitIdentity:_b,hasLocalIdentity:Lb,setGitIdentity:Fb,getGitIdentities:Cb,createGitIdentity:Ob,updateGitIdentity:Mb,deleteGitIdentity:Db,getRemotes:Ub,rebase:jb,abortRebase:Nb,continueRebase:qb,merge:Bb,abortMerge:Gb,continueMerge:Kb,checkoutCommit:Hb,cherryPick:zb,revertCommit:$b,resetToCommit:Wb,stash:Vb,stashPop:Jb,getConflictDetails:Yb,worktree:{list:wc,validate:bc,bootstrapStatus:mb,preview:gb,create:Sc,remove:vc}}),ue=e=>e.replace(/\\/g,"/"),eS=(e,t)=>{if(!t||!Array.isArray(t.entries))throw new Xt("Directory listing returned an invalid response",{reason:"invalid-response"});return{directory:ue(t?.directory||t?.path||e),entries:t.entries.filter(r=>!!(r&&typeof r.name=="string"&&typeof r.path=="string")).map(r=>({name:r.name,path:ue(r.path),isDirectory:!!r.isDirectory}))}},$e=(e,t)=>{const n=t||e?.();return n?{"x-opencode-directory":n}:void 0},tS=({getDirectory:e})=>({async listDirectory(t,n){const r=ue(t),s=new URLSearchParams;r&&s.set("path",r),n?.respectGitignore&&s.set("respectGitignore","true");const o=await g("/api/fs/list",{query:s,headers:$e(e)});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new Xt(a.error||"Failed to list directory",{reason:gs(a.reason),status:o.status})}const i=await o.json();return eS(r,i)},async search(t){const n=new URLSearchParams,r=ue(t.directory);r&&n.set("directory",r),n.set("query",t.query),n.set("dirs","false"),n.set("type","file"),typeof t.maxResults=="number"&&Number.isFinite(t.maxResults)&&n.set("limit",String(t.maxResults));const s=await g("/api/find/file",{query:n,headers:$e(e)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to search files")}const o=await s.json();return(Array.isArray(o)?o:[]).map(a=>({path:ue(`${r}/${a}`),preview:[ue(a)]}))},async createDirectory(t){const n=ue(t),r=await g("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json",...$e(e)},body:JSON.stringify({path:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to create directory")}const s=await r.json();return{success:!!s?.success,path:typeof s?.path=="string"?ue(s.path):n}},async statFile(t,n){const r=ue(t),s=new URLSearchParams({path:r});n?.allowOutsideWorkspace&&s.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&s.set("outsideFileGrant",n.outsideFileGrant);const o=await g("/api/fs/stat",{query:s,signal:AbortSignal.timeout(3e4),headers:$e(e,n?.directory)});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new Error(a.error||"Failed to stat file")}const i=await o.json().catch(()=>({}));return{path:typeof i.path=="string"?ue(i.path):r,isFile:!!i.isFile,size:typeof i.size=="number"?i.size:0,mtimeMs:typeof i.mtimeMs=="number"?i.mtimeMs:void 0}},async readFile(t,n){const r=ue(t),s=new URLSearchParams({path:r});n?.allowOutsideWorkspace&&s.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&s.set("outsideFileGrant",n.outsideFileGrant),n?.optional&&s.set("optional","true");const o=await g("/api/fs/read",{query:s,signal:AbortSignal.timeout(3e4),cache:n?.optional||n?.fresh?"no-store":"default",headers:$e(e,n?.directory)});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new Error(a.error||"Failed to read file")}return{content:await o.text(),path:r}},async writeFile(t,n){const r=ue(t),s=await g("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json",...$e(e)},body:JSON.stringify({path:r,content:n})});if(!s.ok){const i=await s.json().catch(()=>({error:s.statusText}));throw new Error(i.error||"Failed to write file")}const o=await s.json().catch(()=>({}));return{success:!!o.success,path:typeof o.path=="string"?ue(o.path):r}},async uploadFile(t,n,r){const s=ue(t),o=await g("/api/fs/upload",{method:"POST",query:{path:s,overwrite:r?.overwrite?"true":void 0},headers:{"Content-Type":"application/octet-stream",...$e(e,r?.directory)},body:n});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new Xt(a.error||"Failed to upload file",{reason:gs(a.reason),status:o.status})}const i=await o.json().catch(()=>({}));return{success:!!i.success,path:i.path?ue(i.path):s}},async delete(t){const n=ue(t),r=await g("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json",...$e(e)},body:JSON.stringify({path:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to delete file")}return{success:!!(await r.json().catch(()=>({}))).success}},async rename(t,n){const r=await g("/api/fs/rename",{method:"POST",headers:{"Content-Type":"application/json",...$e(e)},body:JSON.stringify({oldPath:t,newPath:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to rename file")}const s=await r.json().catch(()=>({}));return{success:!!s.success,path:typeof s.path=="string"?ue(s.path):n}},async revealPath(t){const n=await g("/api/fs/reveal",{method:"POST",headers:{"Content-Type":"application/json",...$e(e)},body:JSON.stringify({path:ue(t)})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to reveal path")}return{success:!!(await n.json().catch(()=>({}))).success}},async downloadFile(t){const n=ue(t),r=await g("/api/fs/raw",{query:{path:n,download:!0},headers:$e(e)});if(!r.ok)throw new Error(`Download failed (${r.status})`);const s=await r.blob(),o=n.split("/").pop()||"file",i=window.Capacitor,a=new File([s],o,{type:s.type||"application/octet-stream"});if(i?.isNativePlatform?.()===!0&&navigator.canShare?.({files:[a]})){await navigator.share({files:[a]});return}const c=URL.createObjectURL(s),l=document.createElement("a");l.href=c,l.download=o,document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(c),100)}}),nS="/api/config/settings",Tc=()=>`${nS}?${Ql}=${Ti()}`,rS="/api/config/reload",kc=e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid settings response");return e},sS=()=>({async load(){const e=await g(Tc(),{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to load settings: ${e.statusText}`);return{settings:kc(await e.json()),source:"web"}},async save(e){const t=await g(Tc(),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to save settings")}return kc(await t.json())},async restartOpenCode(){const e=await g(rS,{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}}}),oS=()=>({async requestDirectoryAccess(e){return{success:!0,path:e.path}},async startAccessingDirectory(e){return{success:!0}},async stopAccessingDirectory(e){return{success:!0}}}),iS=1500,ei=5e3,aS="openchamber-notification-claim:",nr=new Map,cS=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),lS=e=>{const t=typeof e?.tag=="string"?e.tag.trim():"";return t||[e?.sessionId,e?.kind,e?.title,e?.body].filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>n.trim()).join("|")},uS=e=>{for(const[t,n]of nr)e-n>ei&&nr.delete(t)},dS=e=>{const t=lS(e);if(!t)return!0;const n=Date.now();uS(n);const r=nr.get(t)??0;if(n-r<ei)return!1;try{if(typeof window<"u"&&window.localStorage){const s=`${aS}${t}`,o=Number(window.localStorage.getItem(s)??"0");if(Number.isFinite(o)&&n-o<ei)return nr.set(t,o),!1;Number.isFinite(o)&&o>0&&window.localStorage.removeItem(s),window.localStorage.setItem(s,String(n))}}catch{}return nr.set(t,n),!0},ju=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(n=>{setTimeout(()=>n(null),iS)})])??e}catch{return e}},fS=async e=>{const t=await ju();if(!t||typeof t.showNotification!="function")return!1;try{return await t.showNotification(e?.title??"OpenChamber",{body:e?.body,tag:e?.tag}),!0}catch(n){return console.warn("Failed to send notification via service worker",n),!1}},pS=async()=>{const e=await ju();if(!e||!("pushManager"in e)||!e.pushManager)return!1;try{return!!await e.pushManager.getSubscription()}catch{return!1}},hS=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(!cS()&&await pS()||!dS(e))return!0;try{return await fS(e)||new Notification(e?.title??"OpenChamber",{body:e?.body,tag:e?.tag}),!0}catch(t){return console.warn("Failed to send notification",t),!1}},mS=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,requireHidden:e?.requireHidden}}),!0}catch(n){return console.warn("Failed to send native notification (desktop)",n),!1}},gS=()=>({async notifyAgentCompletion(e){return await mS(e)||await hS(e)},canNotify:()=>typeof window<"u"&&window.__OPENCHAMBER_DESKTOP__?.invoke?!0:typeof Notification<"u"?Notification.permission==="granted":!1}),mn=async(e,t)=>{try{const n=await g(e,{...t,credentials:"include",headers:{Accept:"application/json",...t?.headers??{}}});return n.ok?await n.json():null}catch{return null}},yS=()=>({async getVapidPublicKey(){return mn("/api/push/vapid-public-key")},async subscribe(e){return mn("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unsubscribe(e){return mn("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async setVisibility(e){return mn("/api/push/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0})},async registerApnsToken(e){return mn("/api/push/apns-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unregisterApnsToken(e){return mn("/api/push/apns-token",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}),le=async e=>await e.json().catch(()=>null),wS=({urls:e})=>({async authStatus(){const t=await g("/api/github/auth/status",{method:"GET",headers:{Accept:"application/json"}}),n=await le(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to load GitHub status");return n},async authStart(){const t=await g("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),n=await le(t);if(!t.ok||!n||!("deviceCode"in n))throw new Error(n?.error||t.statusText||"Failed to start GitHub auth");return n},async authComplete(t){const n=await g("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:t})}),r=await le(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to complete GitHub auth");return r},async authDisconnect(){const t=await g("/api/github/auth",{method:"DELETE",headers:{Accept:"application/json"}}),n=await le(t);if(!t.ok)throw new Error(n?.error||t.statusText||"Failed to disconnect GitHub");return{removed:!!n?.removed}},async authActivate(t){const n=await g("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:t})}),r=await le(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to activate GitHub account");return r},async authSetGhCliDisabled(t){const n=await g("/api/github/auth/gh-cli",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({disabled:t})}),r=await le(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to update gh CLI setting");return{disabled:!!r.disabled}},async me(){const t=await g("/api/github/me",{method:"GET",headers:{Accept:"application/json"}}),n=await le(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to fetch GitHub user");return n},async prStatus(t,n,r,s){const o=new URLSearchParams({directory:t,branch:n,...r?{remote:r}:{},...s?.force?{force:"true"}:{}}),i=await g(`/api/github/pr/status?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),a=await le(i);if(!i.ok||!a)throw new Error(a?.error||i.statusText||"Failed to load PR status");return a},async prCreate(t){const n=await g("/api/github/pr/create",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await le(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to create PR");return r},async prUpdate(t){const n=await g("/api/github/pr/update",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await le(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to update PR");return r},async prMerge(t){const n=await g("/api/github/pr/merge",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await le(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to merge PR");return r},async prReady(t){const n=await g("/api/github/pr/ready",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await le(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to mark PR ready");return r},async repoUpstream(t){const n=await g(`/api/github/repo/upstream?directory=${encodeURIComponent(t)}`,{method:"GET",headers:{Accept:"application/json"}}),r=await le(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to detect upstream repo");return r},async repoBranches(t,n){const r=await g(`/api/github/repo/branches?owner=${encodeURIComponent(t)}&repo=${encodeURIComponent(n)}`,{method:"GET",headers:{Accept:"application/json"}}),s=await le(r);if(!r.ok||!s)throw new Error(s?.error||r.statusText||"Failed to fetch repo branches");return s.branches??[]},async prsList(t,n){const r=n?.page??1,s=new URLSearchParams({directory:t,page:String(r)});n?.query&&s.set("query",n.query);const o=await g(`/api/github/pulls/list?${s.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),i=await le(o);if(!o.ok||!i)throw new Error(i?.error||o.statusText||"Failed to load pull requests");return i},async prContext(t,n,r){const s=new URLSearchParams({directory:t,number:String(n)});r?.includeDiff&&s.set("diff","1"),r?.includeCheckDetails&&s.set("checkDetails","1"),r?.sourceRepo?.owner&&r.sourceRepo.repo&&(s.set("owner",r.sourceRepo.owner),s.set("repo",r.sourceRepo.repo));const o=await g(e.api("/api/github/pulls/context",s),{method:"GET",headers:{Accept:"application/json"}}),i=await le(o);if(!o.ok||!i)throw new Error(i?.error||o.statusText||"Failed to load pull request context");return i},async issuesList(t,n){const r=n?.page??1,s=new URLSearchParams({directory:t,page:String(r)});n?.query&&s.set("query",n.query);const o=await g(`/api/github/issues/list?${s.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),i=await le(o);if(!o.ok||!i)throw new Error(i?.error||o.statusText||"Failed to load issues");return i},async issueGet(t,n,r){const s=new URLSearchParams({directory:t,number:String(n)});r?.sourceRepo?.owner&&r.sourceRepo.repo&&(s.set("owner",r.sourceRepo.owner),s.set("repo",r.sourceRepo.repo));const o=await g(e.api("/api/github/issues/get",s),{method:"GET",headers:{Accept:"application/json"}}),i=await le(o);if(!o.ok||!i)throw new Error(i?.error||o.statusText||"Failed to load issue");return i},async issueComments(t,n,r){const s=new URLSearchParams({directory:t,number:String(n)});r?.sourceRepo?.owner&&r.sourceRepo.repo&&(s.set("owner",r.sourceRepo.owner),s.set("repo",r.sourceRepo.repo));const o=await g(e.api("/api/github/issues/comments",s),{method:"GET",headers:{Accept:"application/json"}}),i=await le(o);if(!o.ok||!i)throw new Error(i?.error||o.statusText||"Failed to load issue comments");return i}});async function Oe(e){try{return await e.json()}catch{return null}}function Me(e,t){return e?.error?.trim()||t}function Nu(e){return Number.isFinite(e)?e??null:null}function Bu(e){return Object.prototype.toString.call(e)==="[object String]"?`${e}`:null}function Hu(e){const t=e?.id?.trim();return t?{id:t,name:e?.name?.trim()||null,displayName:e?.displayName?.trim()||null,email:e?.email?.trim()||null,avatarUrl:e?.avatarUrl?.trim()||null}:null}function bS(e){const t=e?.id?.trim(),n=e?.name?.trim();return!t||!n?null:{id:t,name:n,urlKey:e?.urlKey?.trim()||null}}function SS(e){const t=e?.id?.trim();if(!t)return null;const n=e?.authorizedAt;return{id:t,name:e?.name?.trim()||null,urlKey:e?.urlKey?.trim()||null,current:e?.current===!0,user:Hu(e?.user),authorizedAt:Nu(n)}}function Ec(e){if(e?.connected!==!0&&e?.connected!==!1)return null;const t=Array.isArray(e.workspaces)?e.workspaces.map(SS).filter(n=>n!=null):[];return{connected:e.connected,user:Hu(e.user),organization:bS(e.organization),scope:e.scope?.trim()||void 0,workspaces:e.connected?t:void 0}}function vS(e){const t=e?.authorizationUrl?.trim(),n=e?.expiresIn,r=e?.scope?.trim();return!t||!Number.isFinite(n)||n==null||!r?null:{authorizationUrl:t,expiresIn:n,scope:r}}function TS(e){const t=e?.id?.trim()||null,n=e?.name?.trim()||null,r=e?.type?.trim()||null;return!t&&!n&&!r?null:{id:t,name:n,type:r}}function kS(e){const t=e?.id?.trim(),n=e?.name?.trim();if(!t||!n)return null;const r=e?.position;return{id:t,name:n,type:e?.type?.trim()||null,position:Nu(r)??0}}function ES(e){const t=e?.name?.trim()||null,n=e?.displayName?.trim()||null,r=e?.avatarUrl?.trim()||null;return!t&&!n&&!r?null:{name:t,displayName:n,avatarUrl:r}}function PS(e){const t=e?.id?.trim(),n=e?.key?.trim(),r=e?.name?.trim();return!t||!n||!r?null:{id:t,key:n,name:r}}function AS(e){return e!==0&&e!==1&&e!==2&&e!==3&&e!==4?null:e}function IS(e){const t=e?.trim();if(!t)return null;const n=t.startsWith("#")?t.slice(1):t;return/^[0-9A-Fa-f]{6}$/.test(n)?`#${n.toLowerCase()}`:null}function xS(e){if(!e)return null;const t=e?.id?.trim(),n=e?.name?.trim();return!t||!n?null:{id:t,name:n,color:IS(e.color)}}function RS(e){return Array.isArray(e)?e.map(xS).filter(t=>t!=null):[]}function zu(e){if(!e)return null;const t=e?.id?.trim(),n=e?.identifier?.trim(),r=e?.title?.trim(),s=e?.url?.trim();return!t||!n||!r||!s?null:{id:t,identifier:n,title:r,url:s,state:TS(e.state),assignee:ES(e.assignee),team:PS(e.team),priority:AS(e.priority),labels:RS(e.labels)}}function CS(e){const t=e?.id?.trim();if(!t)return null;const n=e?.body;return{id:t,body:Bu(n)??"",createdAt:e?.createdAt?.trim()||null,user:e?.user?{name:e.user.name?.trim()||null,displayName:e.user.displayName?.trim()||null,avatarUrl:e.user.avatarUrl?.trim()||null}:null}}function $u(e){const t=zu(e);if(!t)return null;const n=Array.isArray(e?.comments)?e.comments.map(CS).filter(s=>s!=null):[],r=e?.description;return{...t,description:Bu(r),comments:n}}function OS(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issues:Array.isArray(e.issues)?e.issues.map(zu).filter(n=>n!=null):[],cursor:e.cursor?.trim()||null,hasMore:e.hasMore===!0}}function MS(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issue:$u(e.issue)}}function DS(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,states:Array.isArray(e.states)?e.states.map(kS).filter(n=>n!=null):[]}}function _S(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issue:$u(e.issue)}}function LS(e){const t=e?.id?.trim(),n=e?.key?.trim(),r=e?.name?.trim();if(!t||!n||!r)return null;const s=e?.projectPath?.trim()||null;return{id:t,key:n,name:r,projectPath:s}}function Pc(e){if(e?.connected!==!0&&e?.connected!==!1)return null;if(e.connected===!1)return{connected:!1};const t=Array.isArray(e.teams)?e.teams.map(LS).filter(n=>n!=null):[];return{connected:!0,defaultProjectPath:e.defaultProjectPath?.trim()||null,teams:t}}const FS=["already-posted","issue-not-found","not-started","disabled","origin-not-public"];function US(e){return FS.find(t=>t===e)??null}function Ac(e){return e?.sessionComments!==!0&&e?.sessionComments!==!1?null:{sessionComments:e.sessionComments}}function jS(e){if(e?.connected!==!0&&e?.connected!==!1)return null;if(e.connected===!1)return{connected:!1};if(e.posted===!0)return{connected:!0,posted:!0,commentId:e.commentId?.trim()||null};const t=US(e.skipped);return e.posted===!1&&t?{connected:!0,posted:!1,skipped:t}:null}const NS=()=>({async authStatus(){const e=await g("/api/linear/auth/status",{method:"GET",headers:{Accept:"application/json"}}),t=await Oe(e),n=Ec(t);if(!e.ok||!n)throw new Error(Me(t,e.statusText||"Failed to load Linear status"));return n},async authStart(e){const t=await g("/api/linear/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e?{origin:e}:{})}),n=await Oe(t),r=vS(n);if(!t.ok||!r)throw new Error(Me(n,t.statusText||"Failed to start Linear auth"));return r},async authDisconnect(){const e=await g("/api/linear/auth",{method:"DELETE",headers:{Accept:"application/json"}}),t=await Oe(e);if(!e.ok)throw new Error(Me(t,e.statusText||"Failed to disconnect Linear"));return{removed:t?.removed===!0}},async authActivate(e){const t=await g("/api/linear/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({organizationId:e})}),n=await Oe(t),r=Ec(n);if(!t.ok||!r)throw new Error(Me(n,t.statusText||"Failed to switch Linear workspace"));return r},async issuesList(e){const t=new URLSearchParams,n=e?.query?.trim(),r=e?.cursor?.trim(),s=e?.status?.trim(),o=e?.assignee?.trim(),i=e?.teamId?.trim(),a=e?.priority?.trim();n&&t.set("query",n),r&&t.set("cursor",r),s&&t.set("status",s),o&&t.set("assignee",o),i&&t.set("teamId",i),a&&t.set("priority",a);const c=t.toString(),l=c?`?${c}`:"",u=await g(`/api/linear/issues/list${l}`,{method:"GET",headers:{Accept:"application/json"}}),d=await Oe(u),f=OS(d);if(!u.ok||!f)throw new Error(Me(d,u.statusText||"Failed to load Linear issues"));return f},async issueGet(e){const t=new URLSearchParams({id:e}),n=await g(`/api/linear/issues/get?${t.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),r=await Oe(n),s=MS(r);if(!n.ok||!s)throw new Error(Me(r,n.statusText||"Failed to load Linear issue"));return s},async issueStates(e){const t=new URLSearchParams({teamId:e}),n=await g(`/api/linear/issues/states?${t.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),r=await Oe(n),s=DS(r);if(!n.ok||!s)throw new Error(Me(r,n.statusText||"Failed to load Linear workflow states"));return s},async issueUpdate(e){const t=await g("/api/linear/issues/update",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({id:e.id,stateId:e.stateId})}),n=await Oe(t),r=_S(n);if(!t.ok||!r)throw new Error(Me(n,t.statusText||"Failed to update Linear issue"));return r},async mappingGet(){const e=await g("/api/linear/mapping",{method:"GET",headers:{Accept:"application/json"}}),t=await Oe(e),n=Pc(t);if(!e.ok||!n)throw new Error(Me(t,e.statusText||"Failed to load Linear mapping"));return n},async mappingSet(e){const t=await g("/api/linear/mapping",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({defaultProjectPath:e.defaultProjectPath,teamProjectPaths:e.teamProjectPaths})}),n=await Oe(t),r=Pc(n);if(!t.ok||!r)throw new Error(Me(n,t.statusText||"Failed to save Linear mapping"));return r},async sessionStatusPost(e){const t=await g("/api/linear/session-status",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({kind:e.kind,sessionId:e.sessionId,issueIdentifier:e.issueIdentifier,sessionOrigin:e.sessionOrigin})}),n=await Oe(t),r=jS(n);if(!t.ok||!r)throw new Error(Me(n,t.statusText||"Failed to post Linear session status"));return r},async preferencesGet(){const e=await g("/api/linear/preferences",{method:"GET",headers:{Accept:"application/json"}}),t=await Oe(e),n=Ac(t);if(!e.ok||!n)throw new Error(Me(t,e.statusText||"Failed to load Linear preferences"));return n},async preferencesSet(e){const t=await g("/api/linear/preferences",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({sessionComments:e.sessionComments})}),n=await Oe(t),r=Ac(n);if(!t.ok||!r)throw new Error(Me(n,t.statusText||"Failed to save Linear preferences"));return r}}),Et=async e=>await e.json().catch(()=>null),BS=()=>({async listClients(){const e=await g("/api/client-auth/clients",{method:"GET",headers:{Accept:"application/json"}}),t=await Et(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 g("/api/client-auth/clients",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??""})}),n=await Et(t);if(!t.ok||!n?.client||typeof n.token!="string")throw new Error(n?.error||t.statusText||"Failed to create remote client token");return n},async createPairingSession(e={}){const t=await g("/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}:{}})}),n=await Et(t);if(!t.ok||typeof n?.pairing?.secret!="string"||!n?.server)throw new Error(n?.error||t.statusText||"Failed to create pairing session");return n},async listPendingPairings(){const e=await g("/api/client-auth/pairing/sessions",{method:"GET",headers:{Accept:"application/json"}}),t=await Et(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 g("/api/client-auth/pairing/transports",{method:"GET",headers:{Accept:"application/json"}}),t=await Et(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 g(`/api/client-auth/pairing/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),n=await Et(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to cancel pairing");return{cancelled:n.cancelled===!0}},async revokeClient(e){const t=await g(`/api/client-auth/clients/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),n=await Et(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to revoke remote client");return n},async purgeRevokedClients(){const e=await g("/api/client-auth/clients",{method:"DELETE",headers:{Accept:"application/json"}}),t=await Et(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to clear revoked clients");return t}}),HS=()=>({api:(...e)=>Pe().api(...e),authenticatedAsset:(...e)=>Pe().authenticatedAsset(...e),assetWithUrlToken:(...e)=>Pe().assetWithUrlToken(...e),auth:(...e)=>Pe().auth(...e),health:(...e)=>Pe().health(...e),rawFile:(...e)=>Pe().rawFile(...e),sse:(...e)=>Pe().sse(...e),websocket:(...e)=>Pe().websocket(...e)}),zS=(e={})=>{const t=e.urls??si();$d(t);const n=HS();return{themeFiles:Xd(),runtime:{platform:"web",isDesktop:!1,isVSCode:!1,label:"web"},terminal:Ow(),git:Zb(),files:tS({getDirectory:()=>Jo.getState().currentDirectory}),settings:sS(),permissions:oS(),notifications:gS(),github:wS({urls:n}),linear:NS(),push:yS(),clientAuth:BS()}},$S=3e3,Ic=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},WS=()=>{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__)}};let ti=Promise.resolve();const tk=()=>ti,nk=e=>{const{apiBaseUrl:t,clientToken:n,localOrigin:r,runtimeHeaders:s,relayHostId:o,relay:i}=e??WS(),a=e?null:$c(),c=o||(a?.target==="remote"?a.hostId:""),l=Gc({apiBaseUrl:t||void 0,realtimeBaseUrl:t||void 0});return qd({apiBaseUrl:t,runtimeKey:Ic(t,r)?"local":c?`host:${c}`:null}),al(n||null),cl(s||null),i&&ls({apiBaseUrl:t,clientToken:n||null,requestHeaders:s||null,runtimeKey:o?`host:${o}`:null,relay:i}),rt.reconnectToRuntimeBaseUrl(),Cs(t||void 0).catch(()=>{}),r&&!Ic(t,r)&&Object.keys(Rs()).length>0&&ml(r).catch(()=>{}),vl(),ti=i?Promise.resolve():Promise.race([kp(o||void 0).catch(()=>{}),new Promise(u=>{window.setTimeout(u,1e4)})]).then(()=>{rt.reconnectToRuntimeBaseUrl()}),ti.then(()=>{window.setTimeout(()=>{wp().catch(()=>{})},$S)}),zS({urls:l})};export{Gy as $,ZS as A,rt as B,UT as C,LT as D,Be as E,Ee as F,Fw as G,Av as H,nf as I,Xr as J,WT as K,BT as L,Wd as M,On as N,Le as O,hi as P,El as Q,Wv as R,dp as S,Mt as T,kl as U,re as V,ll as W,fv as X,hv as Y,hT as Z,TT as _,W as a,Yv as a$,yi as a0,Is as a1,Cs as a2,Pe as a3,aw as a4,Rs as a5,km as a6,dm as a7,iT as a8,hm as a9,Sv as aA,rn as aB,DT as aC,FT as aD,yv as aE,wv as aF,Vv as aG,ut as aH,Bp as aI,IT as aJ,Kd as aK,gh as aL,gv as aM,Wh as aN,Fh as aO,jh as aP,GT as aQ,Ho as aR,ev as aS,tv as aT,nv as aU,aT as aV,Vd as aW,Qc as aX,fn as aY,Dg as aZ,qy as a_,Cv as aa,pv as ab,oT as ac,Hp as ad,zT as ae,Xc as af,mv as ag,Yy as ah,NT as ai,Jy as aj,Mr as ak,Xn as al,Oh as am,Ge as an,Jv as ao,Fd as ap,$c as aq,YS as ar,jT as as,sT as at,QS as au,XS as av,Tv as aw,rv as ax,vv as ay,bv as az,el as b,lb as b$,zp as b0,$p as b1,Wp as b2,Ll as b3,Qv as b4,Dw as b5,tT as b6,Zv as b7,Um as b8,Bo as b9,qb as bA,Tb as bB,Ab as bC,yb as bD,Ob as bE,Sc as bF,ub as bG,Db as bH,vc as bI,db as bJ,ZT as bK,Eb as bL,Zw as bM,QT as bN,Rb as bO,Yb as bP,_b as bQ,cb as bR,Qw as bS,YT as bT,Jw as bU,eb as bV,Cb as bW,xb as bX,Yw as bY,Xw as bZ,Vw as b_,Pt as ba,ig as bb,Kn as bc,Vi as bd,xT as be,ga as bf,Tn as bg,mb as bh,Wm as bi,K as bj,ya as bk,eh as bl,Zp as bm,oh as bn,mr as bo,Mg as bp,RT as bq,Gb as br,Nb as bs,kb as bt,Xb as bu,qw as bv,Pb as bw,Hb as bx,zb as by,Kb as bz,nk as c,KT as c$,XT as c0,ek as c1,Ub as c2,bc as c3,wc as c4,Sb as c5,bb as c6,wb as c7,Lb as c8,ab as c9,nT as cA,Mh as cB,qc as cC,CT as cD,_T as cE,Py as cF,Rv as cG,Gv as cH,qv as cI,Te as cJ,rp as cK,pp as cL,yp as cM,fp as cN,mi as cO,up as cP,Kv as cQ,Hv as cR,$v as cS,zv as cT,sp as cU,Tp as cV,Fv as cW,ET as cX,Lr as cY,Zs as cZ,HT as c_,vb as ca,Bb as cb,Uu as cc,gb as cd,jb as ce,fb as cf,Ib as cg,Wb as ch,VT as ci,JT as cj,$b as ck,tb as cl,ib as cm,Fb as cn,nb as co,_u as cp,sb as cq,Vb as cr,Fu as cs,Jb as ct,rb as cu,Lu as cv,ob as cw,Mb as cx,Qb as cy,Ae as cz,gr as d,_v as d$,Kw as d0,Mw as d1,Pv as d2,Ev as d3,Cl as d4,eT as d5,bg as d6,Ue as d7,mT as d8,yT as d9,Uv as dA,jv as dB,kv as dC,Km as dD,uv as dE,dv as dF,ki as dG,rT as dH,Dh as dI,_h as dJ,Ei as dK,Jm as dL,Vm as dM,zm as dN,Os as dO,rf as dP,sv as dQ,iv as dR,cv as dS,ov as dT,av as dU,lv as dV,fm as dW,Dv as dX,_w as dY,qT as dZ,xv as d_,vT as da,wT as db,gT as dc,bT as dd,Zl as de,ST as df,PT as dg,AT as dh,lg as di,kT as dj,Ai as dk,$T as dl,Xv as dm,Oo as dn,uT as dp,cT as dq,lT as dr,dT as ds,Jt as dt,Lh as du,Uh as dv,MT as dw,OT as dx,op as dy,Xf as dz,Pn as e,Lv as e0,Iv as e1,Bv as e2,pt as e3,Ov as f,tk as g,g as h,hr as i,Mv as j,ii as k,At as l,Nv as m,Jo as n,Ye as o,Jf as p,Mo as q,fT as r,ls as s,ht as t,v as u,am as v,pT as w,As as x,Yc as y,ds as z};
|