cuelo 0.8.3 → 0.9.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/.next/BUILD_ID +1 -1
- package/.next/app-path-routes-manifest.json +9 -6
- package/.next/build-manifest.json +2 -2
- package/.next/prerender-manifest.json +3 -3
- package/.next/required-server-files.js +5 -3
- package/.next/required-server-files.json +5 -3
- package/.next/routes-manifest.json +20 -0
- package/.next/server/app/_global-error/page.js +3 -3
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page.js +2 -2
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +3 -3
- package/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
- package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_index.segment.rsc +3 -3
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/api/agent/[id]/account/route.js +1 -1
- package/.next/server/app/api/agent/[id]/account/route.js.nft.json +1 -1
- package/.next/server/app/api/agent/[id]/bash-output/route.js +1 -1
- package/.next/server/app/api/agent/[id]/bash-output/route.js.nft.json +1 -1
- package/.next/server/app/api/agent/[id]/events/route.js +2 -2
- package/.next/server/app/api/agent/[id]/events/route.js.nft.json +1 -1
- package/.next/server/app/api/agent/[id]/route.js +1 -1
- package/.next/server/app/api/agent/[id]/route.js.nft.json +1 -1
- package/.next/server/app/api/agent/new/route.js +1 -1
- package/.next/server/app/api/agent/new/route.js.nft.json +1 -1
- package/.next/server/app/api/agent/running/route.js +1 -1
- package/.next/server/app/api/agent/running/route.js.nft.json +1 -1
- package/.next/server/app/api/attachment-settings/route.js +1 -0
- package/.next/server/app/api/attachment-settings/route.js.nft.json +1 -0
- package/.next/server/app/api/attachment-settings/route_client-reference-manifest.js +1 -0
- package/.next/server/app/api/attachments/[id]/transcription/route.js +2 -0
- package/.next/server/app/api/attachments/[id]/transcription/route.js.nft.json +1 -0
- package/.next/server/app/api/attachments/[id]/transcription/route_client-reference-manifest.js +1 -0
- package/.next/server/app/api/attachments/draft/route.js +1 -0
- package/.next/server/app/api/attachments/draft/route.js.nft.json +1 -0
- package/.next/server/app/api/attachments/draft/route_client-reference-manifest.js +1 -0
- package/.next/server/app/api/attachments/route.js +28 -5
- package/.next/server/app/api/attachments/route.js.nft.json +1 -1
- package/.next/server/app/api/auth/all-providers/route.js +1 -1
- package/.next/server/app/api/auth/api-key/[provider]/route.js +1 -1
- package/.next/server/app/api/auth/login/[provider]/route.js +2 -2
- package/.next/server/app/api/auth/logout/[provider]/route.js +1 -1
- package/.next/server/app/api/auth/providers/route.js +1 -1
- package/.next/server/app/api/cwd/browse/route.js +1 -1
- package/.next/server/app/api/cwd/validate/route.js +1 -1
- package/.next/server/app/api/cwd/validate/route.js.nft.json +1 -1
- package/.next/server/app/api/default-cwd/route.js +1 -1
- package/.next/server/app/api/default-cwd/route.js.nft.json +1 -1
- package/.next/server/app/api/display-settings/route.js +1 -1
- package/.next/server/app/api/display-settings/route.js.nft.json +1 -1
- package/.next/server/app/api/document-text/route.js +4 -4
- package/.next/server/app/api/experiments/route.js +1 -1
- package/.next/server/app/api/file-index/route.js +1 -1
- package/.next/server/app/api/file-index/route.js.nft.json +1 -1
- package/.next/server/app/api/files/[...path]/route.js +2 -2
- package/.next/server/app/api/files/[...path]/route.js.nft.json +1 -1
- package/.next/server/app/api/git/diff/route.js +2 -2
- package/.next/server/app/api/git/diff/route.js.nft.json +1 -1
- package/.next/server/app/api/git/status/route.js +2 -2
- package/.next/server/app/api/git/status/route.js.nft.json +1 -1
- package/.next/server/app/api/gpt6/handles/route.js +1 -1
- package/.next/server/app/api/gpt6/handles/route.js.nft.json +1 -1
- package/.next/server/app/api/gpt6/reply/route.js +1 -1
- package/.next/server/app/api/gpt6/reply/route.js.nft.json +1 -1
- package/.next/server/app/api/gpt6/token/route.js +1 -1
- package/.next/server/app/api/gpt6/token/route.js.nft.json +1 -1
- package/.next/server/app/api/gpt6/web6-session/route.js +1 -1
- package/.next/server/app/api/gpt6/web6-session/route.js.nft.json +1 -1
- package/.next/server/app/api/home/route.js +1 -1
- package/.next/server/app/api/live/call/[callId]/route.js +1 -1
- package/.next/server/app/api/live/call/[callId]/route.js.nft.json +1 -1
- package/.next/server/app/api/live/character-voice/route.js +1 -1
- package/.next/server/app/api/live/character-voice/route.js.nft.json +1 -1
- package/.next/server/app/api/live/events/route.js +2 -2
- package/.next/server/app/api/live/events/route.js.nft.json +1 -1
- package/.next/server/app/api/live/offer/route.js +1 -1
- package/.next/server/app/api/live/offer/route.js.nft.json +1 -1
- package/.next/server/app/api/live/voices/route.js +1 -1
- package/.next/server/app/api/live/voices/route.js.nft.json +1 -1
- package/.next/server/app/api/lounge/events/route.js +2 -2
- package/.next/server/app/api/lounge/events/route.js.nft.json +1 -1
- package/.next/server/app/api/lounge/route.js +1 -1
- package/.next/server/app/api/lounge/route.js.nft.json +1 -1
- package/.next/server/app/api/mcp/route.js +2 -2
- package/.next/server/app/api/mcp/route.js.nft.json +1 -1
- package/.next/server/app/api/model-roles/route.js +1 -1
- package/.next/server/app/api/model-roles/route.js.nft.json +1 -1
- package/.next/server/app/api/models/route.js +1 -1
- package/.next/server/app/api/models/route.js.nft.json +1 -1
- package/.next/server/app/api/models-config/catalog/route.js +1 -1
- package/.next/server/app/api/models-config/discover/route.js +1 -1
- package/.next/server/app/api/models-config/route.js +4 -4
- package/.next/server/app/api/models-config/test/route.js +1 -1
- package/.next/server/app/api/office-avatars/[id]/route.js +1 -1
- package/.next/server/app/api/office-avatars/route.js +1 -1
- package/.next/server/app/api/plugins/route.js +1 -1
- package/.next/server/app/api/plugins/route.js.nft.json +1 -1
- package/.next/server/app/api/project-trust/route.js +1 -1
- package/.next/server/app/api/project-trust/route.js.nft.json +1 -1
- package/.next/server/app/api/projects/route.js +1 -1
- package/.next/server/app/api/projects/route.js.nft.json +1 -1
- package/.next/server/app/api/runs/[runId]/route.js +1 -1
- package/.next/server/app/api/runs/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/auto-name/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/auto-name/route.js.nft.json +1 -1
- package/.next/server/app/api/sessions/[id]/context/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/context/route.js.nft.json +1 -1
- package/.next/server/app/api/sessions/[id]/entries/[entryId]/thinking/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/entries/[entryId]/thinking/route.js.nft.json +1 -1
- package/.next/server/app/api/sessions/[id]/export/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/export/route.js.nft.json +1 -1
- package/.next/server/app/api/sessions/[id]/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/route.js.nft.json +1 -1
- package/.next/server/app/api/sessions/[id]/state/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/state/route.js.nft.json +1 -1
- package/.next/server/app/api/sessions/route.js +1 -1
- package/.next/server/app/api/sessions/route.js.nft.json +1 -1
- package/.next/server/app/api/sessions/search/route.js +1 -1
- package/.next/server/app/api/sessions/search/route.js.nft.json +1 -1
- package/.next/server/app/api/settings/route.js +1 -1
- package/.next/server/app/api/settings/route.js.nft.json +1 -1
- package/.next/server/app/api/sidecars/[service]/[...path]/route.js +1 -1
- package/.next/server/app/api/skills/check/route.js +1 -1
- package/.next/server/app/api/skills/check/route.js.nft.json +1 -1
- package/.next/server/app/api/skills/install/route.js +2 -2
- package/.next/server/app/api/skills/install/route.js.nft.json +1 -1
- package/.next/server/app/api/skills/route.js +2 -2
- package/.next/server/app/api/skills/route.js.nft.json +1 -1
- package/.next/server/app/api/skills/search/route.js +1 -1
- package/.next/server/app/api/skills/update/route.js +1 -1
- package/.next/server/app/api/skills/update/route.js.nft.json +1 -1
- package/.next/server/app/api/theme/route.js +1 -1
- package/.next/server/app/api/theme/route.js.nft.json +1 -1
- package/.next/server/app/api/tool-image/route.js +1 -1
- package/.next/server/app/api/tool-image/route.js.nft.json +1 -1
- package/.next/server/app/api/update-maintenance/route.js +3 -3
- package/.next/server/app/api/update-maintenance/route.js.nft.json +1 -1
- package/.next/server/app/api/updates/route.js +1 -1
- package/.next/server/app/api/web-access/recovery/route.js +1 -1
- package/.next/server/app/api/web-access/route.js +1 -1
- package/.next/server/app/api/web6/consults/route.js +1 -1
- package/.next/server/app/api/worktrees/route.js +1 -1
- package/.next/server/app/api/worktrees/route.js.nft.json +1 -1
- package/.next/server/app/favicon.ico/route.js +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +5 -5
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
- package/.next/server/app/index.segments/_full.segment.rsc +5 -5
- package/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/.next/server/app/index.segments/_index.segment.rsc +3 -3
- package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/manifest.webmanifest/route.js +2 -2
- package/.next/server/app/office/page.js +2 -2
- package/.next/server/app/office/page_client-reference-manifest.js +1 -1
- package/.next/server/app/office-preview/page.js +2 -2
- package/.next/server/app/office-preview/page_client-reference-manifest.js +1 -1
- package/.next/server/app/office-preview.html +1 -1
- package/.next/server/app/office-preview.rsc +3 -3
- package/.next/server/app/office-preview.segments/_full.segment.rsc +3 -3
- package/.next/server/app/office-preview.segments/_head.segment.rsc +1 -1
- package/.next/server/app/office-preview.segments/_index.segment.rsc +3 -3
- package/.next/server/app/office-preview.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/office-preview.segments/office-preview/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/office-preview.segments/office-preview.segment.rsc +1 -1
- package/.next/server/app/office.html +1 -1
- package/.next/server/app/office.rsc +5 -5
- package/.next/server/app/office.segments/_full.segment.rsc +5 -5
- package/.next/server/app/office.segments/_head.segment.rsc +1 -1
- package/.next/server/app/office.segments/_index.segment.rsc +3 -3
- package/.next/server/app/office.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/office.segments/office/__PAGE__.segment.rsc +3 -3
- package/.next/server/app/office.segments/office.segment.rsc +1 -1
- package/.next/server/app/page.js +2 -2
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app/recover/page.js +2 -2
- package/.next/server/app/recover/page_client-reference-manifest.js +1 -1
- package/.next/server/app/recover.html +1 -1
- package/.next/server/app/recover.rsc +3 -3
- package/.next/server/app/recover.segments/_full.segment.rsc +3 -3
- package/.next/server/app/recover.segments/_head.segment.rsc +1 -1
- package/.next/server/app/recover.segments/_index.segment.rsc +3 -3
- package/.next/server/app/recover.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/recover.segments/recover/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/recover.segments/recover.segment.rsc +1 -1
- package/.next/server/app-paths-manifest.json +9 -6
- package/.next/server/chunks/1517.js +1 -1
- package/.next/server/chunks/2651.js +1 -1
- package/.next/server/chunks/4649.js +1 -1
- package/.next/server/chunks/5270.js +8 -0
- package/.next/server/chunks/5489.js +14 -14
- package/.next/server/chunks/5582.js +6 -6
- package/.next/server/chunks/7121.js +4 -0
- package/.next/server/chunks/7362.js +1 -1
- package/.next/server/chunks/8741.js +1 -0
- package/.next/server/chunks/877.js +1 -1
- package/.next/server/functions-config-manifest.json +9 -2
- package/.next/server/instrumentation.js +1 -0
- package/.next/server/instrumentation.js.nft.json +1 -0
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/middleware.js +4 -4
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/A-KXZPM3YkTqPPzKrND64/_buildManifest.js +1 -0
- package/.next/static/chunks/6110-691c0f77641fc07e.js +1 -0
- package/.next/static/chunks/9575-916cd5a97ceda30f.js +22 -0
- package/.next/static/chunks/app/_global-error/page-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/agent/[id]/account/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/agent/[id]/bash-output/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/agent/[id]/events/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/agent/[id]/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/agent/new/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/agent/running/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/attachment-settings/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/attachments/[id]/transcription/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/attachments/draft/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/attachments/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/auth/all-providers/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/auth/api-key/[provider]/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/auth/login/[provider]/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/auth/logout/[provider]/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/auth/providers/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/cwd/browse/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/cwd/validate/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/default-cwd/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/display-settings/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/document-text/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/experiments/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/file-index/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/files/[...path]/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/git/diff/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/git/status/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/gpt6/handles/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/gpt6/reply/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/gpt6/token/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/gpt6/web6-session/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/home/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/live/call/[callId]/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/live/character-voice/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/live/events/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/live/offer/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/live/voices/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/lounge/events/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/lounge/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/mcp/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/model-roles/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/models/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/models-config/catalog/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/models-config/discover/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/models-config/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/models-config/test/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/office-avatars/[id]/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/office-avatars/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/plugins/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/project-trust/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/projects/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/runs/[runId]/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/runs/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/auto-name/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/context/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/thinking/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/export/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/state/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/sessions/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/sessions/search/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/settings/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/sidecars/[service]/[...path]/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/skills/check/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/skills/install/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/skills/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/skills/search/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/skills/update/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/theme/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/tool-image/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/update-maintenance/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/updates/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/web-access/recovery/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/web-access/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/web6/consults/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/api/worktrees/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/app/{layout-427af3ea4f595064.js → layout-eb09a412f4f55812.js} +1 -1
- package/.next/static/chunks/app/manifest.webmanifest/route-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/{main-2603b128da53b28c.js → main-26b32c580fb6231f.js} +3 -3
- package/.next/static/chunks/next/dist/client/components/builtin/app-error-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/next/dist/client/components/builtin/forbidden-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/next/dist/client/components/builtin/not-found-6b1496af498bb4fd.js +1 -0
- package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-6b1496af498bb4fd.js +1 -0
- package/.next/static/css/81a05eb6255ef12e.css +1 -0
- package/.next/trace +107 -107
- package/.next/trace-build +1 -1
- package/.next/types/app/api/attachment-settings/route.ts +351 -0
- package/.next/types/app/api/attachments/[id]/transcription/route.ts +351 -0
- package/.next/types/app/api/attachments/draft/route.ts +351 -0
- package/.next/types/routes.d.ts +4 -1
- package/.next/types/validator.ts +27 -0
- package/README.md +5 -2
- package/Tools/CUELO_Setup/files/native-runtime-patch.js +3 -3
- package/Tools/CUELO_Setup/files/usage-server.js +56 -3
- package/Tools/OMP_Global_Config/agent/AGENTS.md +2 -0
- package/Tools/OMP_Global_Config/agent/agents/maker.md +3 -1
- package/Tools/OMP_Global_Config/agent/prompt-copies/AGENTS.en.md +3 -1
- package/Tools/OMP_Global_Config/agent/rules/omp-harness.md +5 -0
- package/Tools/OMP_Global_Config/agent/rules/subagent.md +15 -0
- package/Tools/OMP_Global_Config/agent/sop/_writer.md +2 -0
- package/Tools/OMP_Global_Config/patches/apply-core-patch.mjs +296 -0
- package/next.config.ts +1 -0
- package/package.json +10 -7
- package/.next/static/A6e8vaM_XsMnaMJbdHUo9/_buildManifest.js +0 -1
- package/.next/static/chunks/6110-46b1b16915b39e5b.js +0 -1
- package/.next/static/chunks/9575-7c8d686e116aef58.js +0 -22
- package/.next/static/chunks/app/_global-error/page-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/agent/[id]/account/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/agent/[id]/bash-output/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/agent/[id]/events/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/agent/[id]/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/agent/new/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/agent/running/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/attachments/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/auth/all-providers/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/auth/api-key/[provider]/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/auth/login/[provider]/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/auth/logout/[provider]/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/auth/providers/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/cwd/browse/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/cwd/validate/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/default-cwd/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/display-settings/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/document-text/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/experiments/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/file-index/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/files/[...path]/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/git/diff/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/git/status/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/gpt6/handles/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/gpt6/reply/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/gpt6/token/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/gpt6/web6-session/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/home/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/live/call/[callId]/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/live/character-voice/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/live/events/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/live/offer/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/live/voices/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/lounge/events/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/lounge/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/mcp/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/model-roles/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/models/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/models-config/catalog/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/models-config/discover/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/models-config/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/models-config/test/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/office-avatars/[id]/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/office-avatars/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/plugins/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/project-trust/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/projects/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/runs/[runId]/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/runs/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/auto-name/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/context/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/thinking/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/export/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/state/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/sessions/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/sessions/search/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/settings/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/sidecars/[service]/[...path]/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/skills/check/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/skills/install/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/skills/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/skills/search/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/skills/update/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/theme/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/tool-image/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/update-maintenance/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/updates/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/web-access/recovery/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/web-access/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/web6/consults/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/api/worktrees/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/app/manifest.webmanifest/route-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/next/dist/client/components/builtin/app-error-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/next/dist/client/components/builtin/forbidden-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/next/dist/client/components/builtin/not-found-b73c548944bb1320.js +0 -1
- package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-b73c548944bb1320.js +0 -1
- package/.next/static/css/67b6e19482963224.css +0 -1
- /package/.next/static/{A6e8vaM_XsMnaMJbdHUo9 → A-KXZPM3YkTqPPzKrND64}/_ssgManifest.js +0 -0
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[9575],{13004:e=>{e.exports={backdrop:"SettingsConfig_backdrop__i6KYG",window:"SettingsConfig_window__m7dcs",sidebar:"SettingsConfig_sidebar__vEMEr",brand:"SettingsConfig_brand__DlYlu",eyebrow:"SettingsConfig_eyebrow__uTa5R",title:"SettingsConfig_title__DWTnA",context:"SettingsConfig_context__N0fl0",searchWrap:"SettingsConfig_searchWrap___PWrc",searchIcon:"SettingsConfig_searchIcon__8_YYE",search:"SettingsConfig_search__DUhSs",nav:"SettingsConfig_nav__V8P9S",navLabel:"SettingsConfig_navLabel__M1wMP",navButton:"SettingsConfig_navButton__CUOqu",navIcon:"SettingsConfig_navIcon__Wagpr",closeRail:"SettingsConfig_closeRail__PW3pT",closeButton:"SettingsConfig_closeButton__5y_6F",content:"SettingsConfig_content__n_a5Z",scrollContent:"SettingsConfig_scrollContent__03BsO",contentHeader:"SettingsConfig_contentHeader__tNmzv",contentTitle:"SettingsConfig_contentTitle__oiHOO",contentDescription:"SettingsConfig_contentDescription___l2QU",reloadNotice:"SettingsConfig_reloadNotice__enzeE",settingsBody:"SettingsConfig_settingsBody__QRFVu",group:"SettingsConfig_group__JQ_dy",groupTitle:"SettingsConfig_groupTitle__0SrM9",settingRow:"SettingsConfig_settingRow__Jy73r",settingLabel:"SettingsConfig_settingLabel__n8vtU",settingDescription:"SettingsConfig_settingDescription__TGWfP",settingControl:"SettingsConfig_settingControl__oz5Gn",select:"SettingsConfig_select__A5aGy",textInput:"SettingsConfig_textInput___NjZ2",jsonEditor:"SettingsConfig_jsonEditor__yTYDb",numberInput:"SettingsConfig_numberInput__TVVeJ",switch:"SettingsConfig_switch__5UYqz",multiSelect:"SettingsConfig_multiSelect__PTjyr",choice:"SettingsConfig_choice__Os8WR",choiceToggle:"SettingsConfig_choiceToggle__lyl75",reorder:"SettingsConfig_reorder__JR6tX",error:"SettingsConfig_error__j6wEj",saveState:"SettingsConfig_saveState__1tIL4",themeGrid:"SettingsConfig_themeGrid__7Lw8A",themeCard:"SettingsConfig_themeCard__DQFsT",themePreview:"SettingsConfig_themePreview__QzqXK",themePreviewBar:"SettingsConfig_themePreviewBar__ZbchX",themePreviewPanel:"SettingsConfig_themePreviewPanel__YN9ty",themePreviewLine:"SettingsConfig_themePreviewLine__jP0qg",themeCardBody:"SettingsConfig_themeCardBody__xiOe6",themeCardHeader:"SettingsConfig_themeCardHeader__YPRN2",themeSlot:"SettingsConfig_themeSlot__vGn9a",themeActive:"SettingsConfig_themeActive__PNmdk",mcpLayout:"SettingsConfig_mcpLayout__ek_Fi",mcpList:"SettingsConfig_mcpList__gZ9_o",scopeTabs:"SettingsConfig_scopeTabs__9bybS",scopeButton:"SettingsConfig_scopeButton__d4XPe",serverRows:"SettingsConfig_serverRows__JSJy0",serverRow:"SettingsConfig_serverRow__6gJdE",serverSelect:"SettingsConfig_serverSelect__cuYFx",serverToggle:"SettingsConfig_serverToggle__X5N_o",serverName:"SettingsConfig_serverName__lbfcK",sourceBadge:"SettingsConfig_sourceBadge__XDE2u",serverListEmpty:"SettingsConfig_serverListEmpty___icit",statusDot:"SettingsConfig_statusDot__dVcD4",addServer:"SettingsConfig_addServer__g0ivB",mcpEditor:"SettingsConfig_mcpEditor__XGcLp",editorHeader:"SettingsConfig_editorHeader__qDvAk",readOnlyNotice:"SettingsConfig_readOnlyNotice__KNzML",editorActions:"SettingsConfig_editorActions__h9p7Y",linkButton:"SettingsConfig_linkButton__0DH3I",primaryButton:"SettingsConfig_primaryButton__Eocwv",dangerButton:"SettingsConfig_dangerButton__XF_f_",empty:"SettingsConfig_empty__erg3A"}},14755:(e,t,n)=>{"use strict";n.d(t,{C1:()=>s,IN:()=>i,getPresetFromTools:()=>l,xG:()=>o});let r=[],i=["read","bash","edit","write"],s=["read","bash","edit","write","grep","glob"],a=Object.fromEntries(s.map(e=>[e,!0]));function l(e){let t=e.filter(e=>e.active);if(0===t.length)return"none";let n=t.map(e=>e.name).filter(e=>!0===a[e]).sort().join(",");return n===[...i].sort().join(",")?"default":n===[...s].sort().join(",")?"full":"default"}function o(e){return"none"===e?[...r]:"full"===e?[...s]:[...i]}},21340:()=>{},36266:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>cG});var r=n(95155),i=n(12115),s=n(73321),a=n(16871),l=n(81886),o=n(68890),d=n(66919);let c=["chat","process","subagents","files","resource","sidechat","efficiency"],u=["characters","usage","models"];Object.freeze({transcript:550,composer:384,navigator:240,deck:384});let p=Object.freeze({navigator:791,deck:1176}),h=Object.freeze({activeView:"chat",transientLayer:null}),m=Object.fromEntries(c.map(e=>[e,!0]));function f(e){return"string"==typeof e&&!0===m[e]?e:h.activeView}function g(e,t){switch(t.type){case"select-view":return{activeView:f(t.view),transientLayer:null};case"open-layer":return{activeView:f(e.activeView),transientLayer:t.layer};case"toggle-layer":return{activeView:f(e.activeView),transientLayer:e.transientLayer===t.layer?null:t.layer};case"close-layer":return{activeView:f(e.activeView),transientLayer:null}}}function x(e){let t=Number.isFinite(e)?Math.max(0,e):0;return{availableWidth:t,navigator:t>=p.navigator?"pinned":"drawer",deck:t>=p.deck?"pinned":"view-stack"}}let v=null,b=!1,y=-1/0;function w(e,t=Date.now()){b=e,e||(y=t)}let k=["projects","priority"],j="omp-web:navigator-mode",S="omp-prio-on",C=["omp-relay-session-","omp-cwd-","ompscope_"];function N(e){let t=e.trim().replace(/\\/g,"/");return"/"===(t=t.startsWith("//")?`//${t.slice(2).replace(/\/{2,}/g,"/")}`:t.replace(/\/{2,}/g,"/"))||/^[a-zA-Z]:\/$/.test(t)||(t=t.replace(/\/+$/,"")),/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}function I(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=N(e),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{project:e,modified:n.modified})}return[...t.values()].sort((e,t)=>t.modified.localeCompare(e.modified)).map(e=>e.project)}function T(e,t){let n=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&n.set(N(e.key),e.order);let r=[...e],i=new Set(e.map(N));for(let e of t){let t=N(e.key);!t||i.has(t)||(r.push(e.path??e.key),i.add(t))}return r.map((e,t)=>({project:e,defaultIndex:t,order:n.get(N(e))})).sort((e,t)=>{let n=void 0!==e.order,r=void 0!==t.order;return n!==r?n?-1:1:n&&r&&e.order!==t.order?e.order-t.order:e.defaultIndex-t.defaultIndex}).map(({project:e})=>e)}let M=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function $(e){let t=e.match(M);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}var R=n(92176);let E=`(max-width: ${p.navigator-1}px)`;function L(e){return{subscribe(t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)},getSnapshot:()=>!!window.matchMedia&&window.matchMedia(e).matches}}let A=L("(max-width: 640px)"),z=L(E);function W(){return!1}function F(){return(0,i.useSyncExternalStore)(A.subscribe,A.getSnapshot,W)}var P=n(47650);async function D(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);return r}function _(){return(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function O(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,r.jsx)("path",{d:"M2 9h12"}),(0,r.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function H({onCancel:e,onSelect:t,busy:n=!1,error:s}){let{t:a}=(0,R.s)(),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(""),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(""),[f,g]=(0,i.useState)([]),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(null),[w,k]=(0,i.useState)(!0),j=(0,i.useCallback)(async e=>{k(!0),y(null);try{let t=await D(e),n=t.path??e??"/";c(n),p(t.parentPath??null),m(n),g(t.directories??[]),v(t.drives??null)}catch(e){y(e instanceof Error?e.message:String(e))}finally{k(!1)}},[]);(0,i.useEffect)(()=>{o(document.body),j()},[j]);let S=h.trim()!==d,C=!!d&&!S&&!n,N=!!u||/^[a-zA-Z]:[\\/]?$/.test(d);return l?(0,P.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":a("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||n||e()},onKeyDown:t=>{"Escape"!==t.key||n||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:a("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:n,title:a("i18n.close"),"aria-label":a("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:n?"default":"pointer",opacity:n?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=h.trim();t&&j(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void j(u??void 0),disabled:w||!N,title:a("directoryPicker.goToParent"),"aria-label":a("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:N?"pointer":"default",opacity:N?1:.45},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:a("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:h,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{m(e.target.value),y(null)},style:{minWidth:0,flex:1,height:36,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:w||!h.trim(),title:a("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:w||!h.trim()?"default":"pointer",opacity:w||!h.trim()?.6:1},children:a("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[w?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.loadingDirectories")}):null!==x?(0,r.jsx)(r.Fragment,{children:x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void j(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(O,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.noDrives")})}):f.length>0?f.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void j(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(_,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.noSubdirectories")}),(b||s)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:b??s})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:n,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text-muted)",cursor:n?"default":"pointer",fontSize:13},children:a("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(d),disabled:!C,title:a(S?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",border:0,borderRadius:6,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontSize:13,fontWeight:600,opacity:C?1:.6,cursor:C?"pointer":"default"},children:a(n?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),l):null}function B({label:e="CUELO",markSize:t=22,gap:n=10,style:i,labelStyle:s}){return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:n,minWidth:0,color:"var(--text)",...i},children:[(0,r.jsxs)("svg",{viewBox:"0 0 100 100",width:t,height:t,"aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M77.9 30.5 A34 34 0 0 0 16 50 A26 26 0 0 0 68 50",fill:"none",stroke:"currentColor",strokeWidth:"10",strokeLinecap:"round"}),(0,r.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:'"Plus Jakarta Sans", Geist, ui-sans-serif, system-ui, sans-serif',fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...s},children:e})]})}var U=n(17028);let q="omp-web:unread-session-ids",V="omp-web:pinned-session-ids",K="omp-web:removed-projects";function J(e,t){return{minHeight:t?36:30,padding:"3px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:e?"var(--text-dim)":"var(--text-muted)",cursor:e?"default":"pointer",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.3,textAlign:"left",whiteSpace:"normal",overflowWrap:"anywhere"}}function G(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function Y({text:e,style:t}){return(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...t},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:e})})}function Z({open:e,children:t,style:n}){let[s,a]=(0,i.useState)(e),[l,o]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(a(!0),o(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>o(!0))})):(o(!1),n=setTimeout(()=>a(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),s)?(0,r.jsx)("div",{style:{...n,opacity:+!!l,transform:l?"translateY(0) scale(1)":"translateY(-8px) scale(0.96)",transformOrigin:"top center",transition:"opacity 140ms ease, transform 140ms ease",pointerEvents:e?"auto":"none"},children:t}):null}let X="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function Q(){let[e,t]=(0,i.useState)(!1),[n,s]=(0,i.useState)(!1),a=(0,i.useRef)(null),l=function(e,t){let[n,r]=(0,i.useState)(e),s=(0,i.useRef)(null),a=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void r(e);a.current=0;let n=4*e.length,i=()=>{a.current+=1;let t=Math.floor(a.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:X[Math.floor(Math.random()*X.length)]).join("")),a.current<n?s.current=requestAnimationFrame(i):r(e)};return s.current=requestAnimationFrame(i),()=>{s.current&&cancelAnimationFrame(s.current)}},[e,t]),n}(e?"0.8.3/18.5.1":"CUELO",n),o=(0,i.useCallback)(e=>{t(e),s(!0),setTimeout(()=>s(!1),(e?6:8)*4*(1e3/60)+100)},[]),d=(0,i.useCallback)(()=>{a.current&&clearTimeout(a.current);let t=!e;o(t),t&&(a.current=setTimeout(()=>o(!1),3e3))},[e,o]);return(0,i.useEffect)(()=>()=>{a.current&&clearTimeout(a.current)},[]),(0,r.jsx)("button",{className:"navigator-brand",onClick:d,style:{display:"flex",alignItems:"center",background:"none",border:"none",padding:0,cursor:"default",color:e?"var(--accent)":"var(--text)",minWidth:"6ch"},children:(0,r.jsx)(B,{label:l,labelStyle:e?{fontFamily:"var(--font-mono)",letterSpacing:"-0.01em"}:void 0})})}async function ee(e){let t=await fetch("/api/projects",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:e})});if(!t.ok)throw Error(`HTTP ${t.status}`)}function et({selectedSessionId:e,optimisticSession:t,onSelectSession:n,onNewSession:s,initialSessionId:a,skipInitialProjectSelection:l,onInitialRestoreDone:o,refreshKey:d,onSessionDeleted:c,selectedCwd:u,onCwdChange:p,onBackgroundTaskDone:h,loungePanel:m,loungeActive:f=!1,onLoungeActiveChange:g}){let x,{lt:v}=(0,U.H)(),{t:b,locale:y}=(0,R.s)(),w=F(),[M,$]=(0,i.useState)([]),E=t&&!M.some(e=>e.id===t.id)?[t,...M]:M,[L,A]=(0,i.useState)(!0),[z,W]=(0,i.useState)(null),[P,D]=(0,i.useState)(null),[_,O]=(0,i.useState)(""),[B,X]=(0,i.useState)(""),[er,el]=(0,i.useState)("projects"),[eo,ec]=(0,i.useState)(()=>new Set),[eu,ep]=(0,i.useState)(()=>new Set),[eh,em]=(0,i.useState)(null),[ef,eg]=(0,i.useState)(null),[ex,ev]=(0,i.useState)({version:1,projects:[]}),[eb,ey]=(0,i.useState)(!1),[ew,ek]=(0,i.useState)(!1),[ej,eS]=(0,i.useState)(!1),[eC,eN]=(0,i.useState)(null),[eI,eT]=(0,i.useState)(""),[eM,e$]=(0,i.useState)(!1),[eR,eE]=(0,i.useState)(null),[eL,eA]=(0,i.useState)(""),[ez,eW]=(0,i.useState)(!1),[eF,eP]=(0,i.useState)(null),[eD,e_]=(0,i.useState)(!1),[eO,eH]=(0,i.useState)(null),[eB,eU]=(0,i.useState)(!1),[eq,eV]=(0,i.useState)(!1),[eK,eJ]=(0,i.useState)(""),[eG,eY]=(0,i.useState)(null),[eZ,eX]=(0,i.useState)(!1),[eQ,e0]=(0,i.useState)(null),e1=(0,i.useRef)(null),e2=(0,i.useRef)(null),e4=(0,i.useRef)(null),e5=(0,i.useRef)(!1),e8=(0,i.useRef)(!1),[e6,e3]=(0,i.useState)(!1),[e7,e9]=(0,i.useState)(()=>new Set),[te,tt]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(q);if(!e)return new Set;let t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(e=>"string"==typeof e));return new Set}catch{return new Set}})()),[tn,tr]=(0,i.useState)(()=>new Set),ti=(0,i.useRef)(new Set),ts=(0,i.useRef)(!1),ta=(0,i.useRef)(null);(0,i.useEffect)(()=>{tr(function(){try{let e=window.localStorage.getItem(V);if(!e)return new Set;let t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(e=>"string"==typeof e)):new Set}catch{return new Set}}())},[]);let tl=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/projects",{cache:"no-store",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw Error(`HTTP ${e.status}`);ev(await e.json())}catch{ev({version:1,projects:[]})}finally{ey(!0)}},[]);(0,i.useEffect)(()=>{tl()},[tl,d]),(0,i.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(K)}catch{return}if(!e)return;let t=[];try{let n=JSON.parse(e);Array.isArray(n)&&(t=n.filter(e=>"string"==typeof e))}catch{t=[]}(async()=>{try{for(let e=0;e<t.length;e+=500){let n=t.slice(e,e+500);await ee(n.map(e=>({key:N(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(K)}catch{}await tl()})()},[tl]);let to=(0,i.useCallback)(async e=>{if(e8.current)throw Error("Project update in progress");e8.current=!0,e$(!0);try{await ee(e),await tl()}finally{e8.current=!1,e$(!1)}},[tl]);(0,i.useEffect)(()=>{eC&&e4.current?.select()},[eC]);let td=(0,i.useCallback)(async(e=!1,t=!1)=>{try{e&&A(!0);let n=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();$(r.sessions),ts.current||e9(new Set(r.runningSessionIds??[])),W(null),e||(e3(!0),ta.current&&clearTimeout(ta.current),ta.current=setTimeout(()=>e3(!1),2e3))}catch(e){W(String(e))}finally{e&&A(!1)}},[]),tc=(0,i.useCallback)(e=>{tt(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),tr(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),c?.(e),td()},[td,c]),[tu,tp]=(0,i.useState)(null),[th,tm]=(0,i.useState)(!1),[tf,tg]=(0,i.useState)(null),tx=(0,i.useCallback)(()=>{th||(tp(null),tg(null))},[th]),tv=(0,i.useCallback)(async e=>{tm(!0),tg(null);let t=[],n=[],r=[];for(let i of e)if(!i.transient)try{let e=await fetch(`/api/sessions/${encodeURIComponent(i.id)}?skipRunning=1`,{method:"DELETE"});if(409===e.status){n.push(i.id);continue}if(!e.ok)throw Error(`HTTP ${e.status}`);t.push(i.id)}catch{r.push(i.name?.trim()||i.id.slice(0,8))}if(n.length>0&&(ts.current=!0,e9(e=>{if(n.every(t=>e.has(t)))return e;let t=new Set(e);for(let e of n)t.add(e);return t})),t.length>0){let e=new Set(t),n=n=>t.some(e=>n.has(e))?new Set([...n].filter(t=>!e.has(t))):n;for(let e of(tt(n),tr(n),t))c?.(e)}(await td(),tm(!1),r.length>0)?tg(b("sidebar.clearSessionsFailed",{count:r.length,names:r.join(", ")})):n.length>0||tp(null)},[td,c,b]),[tb,ty]=(0,i.useState)(0),tw=(0,i.useCallback)(()=>{ty(e=>e+1),td()},[td]),tk=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!tk.current;tk.current=!0,td(e,!e)},[td,d]),(0,i.useEffect)(()=>{try{el(function(e,t){return"gpt6"===e?"projects":"string"==typeof e&&k.includes(e)?e:"1"===t?"priority":"projects"}(window.localStorage.getItem(j),window.localStorage.getItem(S)))}catch{}},[]);let tj=(0,i.useCallback)(e=>{el(e);try{window.localStorage.setItem(j,e),window.localStorage.setItem(S,"priority"===e?"1":"0")}catch{}},[]);(0,i.useEffect)(()=>{if("priority"!==er)return;let e=()=>{"visible"===document.visibilityState&&td(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[td,er]),(0,i.useEffect)(()=>{try{0===te.size?window.localStorage.removeItem(q):window.localStorage.setItem(q,JSON.stringify([...te]))}catch{}},[te]),(0,i.useEffect)(()=>{try{0===tn.size?window.localStorage.removeItem(V):window.localStorage.setItem(V,JSON.stringify([...tn]))}catch{}},[tn]);let tS=(0,i.useCallback)(e=>{tr(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]);(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let s=new AbortController;n?.abort(),n=s;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:s.signal});if(!t.ok)return;let r=await t.json();if(e||n!==s)return;ts.current=!0,e9(new Set(r.runningSessionIds??[]))}catch{}finally{n===s&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},s=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",s),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",s)}},[]),(0,i.useEffect)(()=>{let t=ti.current,n=[...t].filter(t=>!e7.has(t)&&t!==e),r=[...e7].filter(e=>!t.has(e));(n.length>0||r.length>0)&&tt(e=>{let t=new Set(e);return e7.forEach(e=>t.delete(e)),n.forEach(e=>t.add(e)),t});let i=r.some(e=>!M.some(t=>t.id===e));(n.length>0||i)&&td(!1,!0),n.length>0&&h?.(),ti.current=e7},[e7,e,M,td,h]),(0,i.useEffect)(()=>{e&&tt(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[e]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&O(e.home)}).catch(()=>{})},[]);let tC=(0,i.useRef)(!1),tN=(0,i.useCallback)(e=>{if(!e)return null;if(eO&&eO.forCwd===e||eO?.worktrees.some(t=>t.path===e))return eO.projectRoot;let t=E.find(t=>t.cwd===e);return t?.projectRoot??e},[eO,E]),tI=(0,i.useRef)(null);(0,i.useEffect)(()=>{tI.current!==P&&(tI.current=P,p?.(P,tN(P)))},[P,p,tN]);let tT=(0,i.useRef)(null);(0,i.useEffect)(()=>{u&&u!==tT.current&&(tT.current=u,D(u))},[u]);let[tM,t$]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!P)return void eH(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(P)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void eH(null);eH({forCwd:P,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||eH(null)}),()=>{e=!0}},[P,tM,d]),(0,i.useEffect)(()=>{if(0!==M.length&&!l&&null===P){if(a&&!tC.current){tC.current=!0;let e=M.find(e=>e.id===a);if(e){D(e.cwd),n(e,!0);return}o?.()}if(!eb)return;let e=new Map(ex.projects.map(e=>[e.key,e])),t=T(M.length>0?I(M):[],ex.projects).filter(t=>!e.get(N(t))?.hidden);t.length>0&&D(t[0])}},[M,P,a,l,n,o,ex,eb]);let tR=(0,i.useCallback)(async e=>{let t=e.trim();if(t&&!eD){e_(!0),eP(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),n=await e.json().catch(()=>({}));if(!e.ok||n.error)return void eP(n.error??b("workspace.unable"));let r=n.cwd??t,i=N(r),s=ex.projects.find(e=>e.key===i);if(s?.hidden===!0)try{await to([{key:i,path:r,hidden:!1}])}catch{}D(r),eW(!1)}catch{eP(b("workspace.unable"))}finally{e_(!1)}}},[to,eD,ex.projects,b]),tE=(0,i.useCallback)(()=>{eW(!0),eP(null)},[]),tL=(0,i.useCallback)(async()=>{let e=eK.trim();if(e&&!eZ&&eO){eX(!0),eY(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eO.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void eY(n.error??`HTTP ${t.status}`);eV(!1),eJ(""),eU(!1),eH(t=>t?{...t,forCwd:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),D(n.path),t$(e=>e+1)}catch(e){eY(e instanceof Error?e.message:String(e))}finally{eX(!1)}}},[eK,eZ,eO]),tA=(0,i.useCallback)(async(e,t)=>{if(eO&&!eZ){eX(!0),eY(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eO.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void e0(e);eY(r.error??`HTTP ${n.status}`);return}e0(null),P===e&&D(eO.projectRoot),t$(e=>e+1)}catch(e){eY(e instanceof Error?e.message:String(e))}finally{eX(!1)}}},[eO,eZ,P]);(0,i.useEffect)(()=>{let e=e=>{e1.current&&!e1.current.contains(e.target)&&(eg(null),eU(!1),eV(!1),eJ(""),eY(null),e0(null),eA(""),em(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tz=(0,i.useCallback)(e=>{e.cwd&&D(e.cwd),n(e)},[n]),tW=(0,i.useCallback)((e=P)=>{if(!e)return;let t="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;D(e),s?.(t,e)},[P,s]),[tF,tP]=(0,i.useState)(!1),[tD,t_]=(0,i.useState)(null),tO=(0,i.useCallback)(async()=>{tP(!0),t_(null);try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json().catch(()=>({}));if(!e.ok||!t.cwd)throw Error(t.error??`HTTP ${e.status}`);tW(t.cwd)}catch(e){t_(b("sidebar.newScratchSessionFailed",{error:e instanceof Error?e.message:String(e)}))}finally{tP(!1)}},[tW,b]),tH=(0,i.useCallback)(e=>{ep(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),tB=tN(P),tU=null===tB?null:N(tB),tq=(0,i.useMemo)(()=>new Map(ex.projects.map(e=>[e.key,e])),[ex.projects]),tV=I(E);if(null!==tB){let e=N(tB);tV.some(t=>N(t)===e)||tV.unshift(tB)}let tK=T(tV,ex.projects),tJ=tK.filter(e=>ew||!tq.get(N(e))?.hidden),tG=tK.some(e=>tq.get(N(e))?.hidden),tY=()=>{eg(null),eU(!1),eV(!1),eJ(""),eY(null),e0(null),eA("")},tZ=async(e,t)=>{tY();try{await to([{key:N(e),path:e,hidden:t}]),t&&tU&&tU===N(e)&&D(null),t||tK.some(t=>N(t)!==N(e)&&tq.get(N(t))?.hidden)||ek(!1)}catch{}},tX=async e=>{if(e5.current){e5.current=!1,eN(null);return}let t=eI.trim();if(t===(tq.get(N(e))?.alias??""))return void eN(null);eE(null);try{await to([{key:N(e),path:e,alias:t||null}]),eN(null)}catch{eE(b("sidebar.projectUpdateFailed"))}},tQ=async(e,t)=>{if(B)return;let n=tJ.indexOf(e),r=n+t;if(n<0||r<0||r>=tJ.length)return;let i=new Set(tJ),s=tK.map((e,t)=>i.has(e)?t:-1).filter(e=>e>=0),a=[...tK],l=s[n],o=s[r];[a[l],a[o]]=[a[o],a[l]],tY();try{await to(a.map((e,t)=>({key:N(e),path:e,order:t})))}catch{}},t0=new Map;for(let e of E){let t=e.projectRoot??e.cwd;if(!t)continue;let n=N(t),r=t0.get(n);r?r.push(e):t0.set(n,[e])}let t1=(0,i.useMemo)(()=>{let e=new Map;for(let t of E){let n=t.projectRoot??t.cwd;if(!n)continue;let r=N(n),i=e.get(r);i||(i={running:0,unread:0},e.set(r,i)),e7.has(t.id)&&i.running++,te.has(t.id)&&i.unread++}return e},[E,e7,te]),t2=B.trim().toLowerCase(),t4=B.length>0,t5=tJ.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,n=N(e),r=tq.get(n),i=r?.alias??t,s=(t0.get(n)??[]).slice().sort((e,t)=>{let n=Number(tn.has(t.id))-Number(tn.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!t2)return[{project:e,key:n,name:i,sessions:s,hidden:r?.hidden===!0}];let a=i.toLowerCase().includes(t2)||t.toLowerCase().includes(t2),l=s.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(t2));return a||0!==l.length?[{project:e,key:n,name:i,sessions:a?s:l,hidden:r?.hidden===!0}]:[]}),t8=[],t6=[];for(let e of t5){let t=e.key===tU||(t1.get(e.key)?.running??0)>0;(function(e){let t=e.trim().replace(/\\/g,"/").toLowerCase();return!!(/^[a-z]:\/?$/.test(t)||"/"===t||/(^|\/)appdata\/local\/temp(\/|$)/.test(t)||/^\/(?:var\/|private\/)?tmp(?:\/|$)/.test(t)||/^[a-z]:\/(?:tmp|temp)(?:\/|$)/.test(t)||/(^|\/)(?:users|home)\/[^/]+\/\.omp(\/|$)/.test(t))||t.split("/").some(e=>C.some(t=>e.startsWith(t)))})(e.project)&&!t?t6.push(e):t8.push(e)}let t3={running:0,unread:0};for(let e of t6){let t=t1.get(e.key);t&&(t3.running+=t.running,t3.unread+=t.unread)}let t7=t4||ej,t9=[...t8.map(e=>({kind:"project",group:e})),...t6.length>0?[{kind:"temporary"}]:[],...t7?t6.map(e=>({kind:"project",group:e})):[]],ne=function(e){let t=new Map;for(let n of e){let e=n.toLowerCase();t.set(e,(t.get(e)??0)+1)}return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}(t9.flatMap(e=>"project"===e.kind?[e.group.name]:[])),nt=(0,i.useMemo)(()=>(function(e,t,n,r,i="Priority",s=new Set,a="Pinned"){let l=e.filter(e=>!e.transient).slice().sort((e,t)=>{let n=Date.parse(e.modified),r=Date.parse(t.modified);return(Number.isFinite(r)?r:0)-(Number.isFinite(n)?n:0)}),o=l.filter(e=>s.has(e.id)),d=[],c=new Map,u=0;for(let e of l){if(s.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let n=new Date(e.modified);if(u>=10)continue;u+=1;let r=[n.getFullYear(),String(n.getMonth()+1).padStart(2,"0"),String(n.getDate()).padStart(2,"0")].join("-"),i=c.get(r);i?i.push(e):c.set(r,[e])}let p=[];for(let e of(o.length>0&&p.push({key:"pinned",label:a,running:!1,sessions:o}),d.length>0&&p.push({key:"priority",label:i,running:!0,sessions:d}),[...c.keys()].sort().reverse()))p.push({key:e,label:function(e,t,n){let[r,i,s]=e.split("-").map(Number),a=new Date(r,i-1,s),l=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(a.getFullYear(),a.getMonth(),a.getDate()))/864e5);return 0===l||1===l?new Intl.RelativeTimeFormat(n,{numeric:"auto"}).format(-l,"day"):l>=0&&l<7?new Intl.DateTimeFormat(n,{weekday:"long"}).format(a):new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(a)}(e,n,r),running:!1,sessions:c.get(e)??[]});return p})(E,e7,new Date,y,b("navigator.priority"),tn,b("sidebar.pinned")),[y,tn,e7,E,b]),nn=!!(eO?.isGit&&eO.isTopLevel&&P&&tB===eO.projectRoot),nr=eO?.worktrees.find(e=>e.path===P)??eO?.worktrees.find(e=>e.isMain),ni=(eO?.worktrees.length??0)>=8,ns=ni&&eL.trim()?(eO?.worktrees??[]).filter(e=>(e.branch??G(e.path,_)).toLowerCase().includes(eL.trim().toLowerCase())):eO?.worktrees??[],na=(()=>{if(!tu)return[];let e="project"===tu.kind?t0.get(N(tu.project))??[]:nt.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),nl=na.filter(e=>!e7.has(e.id)),no=e=>{let t=new Set;for(let n of e)n.transient||e7.has(n.id)||t.has(n.id)||t.add(n.id);return t.size},nd=void 0!==m&&f;return(0,r.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[ez&&(0,r.jsx)(H,{busy:eD,error:eF,onCancel:()=>{eW(!1),eP(null)},onSelect:e=>void tR(e)}),tu&&(0,r.jsx)(en,{scope:tu,eligible:nl.length,runningExcluded:na.length-nl.length,busy:th,error:tf,onCancel:tx,onConfirm:()=>void tv(nl)}),(0,r.jsx)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(Q,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,r.jsx)("button",{className:"navigator-icon-action",onClick:()=>tW(),disabled:!P,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:"1px solid var(--border)",color:P?"var(--text-muted)":"var(--text-dim)",cursor:P?"pointer":"not-allowed",width:32,height:32,padding:0,borderRadius:7,fontSize:12,flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},title:P?b("sidebar.newSessionTitle",{path:P}):b("sidebar.selectProject"),"aria-label":P?b("sidebar.newSessionTitle",{path:P}):b("sidebar.selectProject"),onMouseEnter:e=>{P&&(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=P?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,r.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]})}),(0,r.jsx)("button",{className:`navigator-icon-action${e6?" is-success":""}`,onClick:()=>td(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:e6?"rgba(74,222,128,0.18)":"var(--bg-hover)",border:`1px solid ${e6?"rgba(74,222,128,0.4)":"var(--border)"}`,color:e6?"#4ade80":"var(--text-muted)",cursor:"pointer",width:32,height:32,borderRadius:7,padding:0,flexShrink:0,transition:"background 0.3s, color 0.3s, border-color 0.3s"},onMouseEnter:e=>{e6||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{e6||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)")},title:b("sidebar.refresh"),children:e6?(0,r.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"var(--success)",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})})]})]})}),(0,r.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,r.jsxs)("div",{className:"navigator-mode-switcher",role:"toolbar","aria-label":b("navigator.toolbar"),style:{display:"flex",alignItems:"center",gap:2,flex:1,minWidth:0,padding:2,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[k.map(e=>{let t="projects"===e?b("sidebar.projects"):b("navigator.priority"),n=!nd&&er===e;return(0,r.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:t}),"aria-pressed":n,"aria-controls":`navigator-${e}-panel`,"data-navigator-mode":e,onClick:()=>{tj(e),nd&&g?.(!1)},style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:n?"var(--bg-selected)":"transparent",color:n?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:n?600:500,whiteSpace:"nowrap"},children:t},e)}),void 0!==m&&(0,r.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:v("lounge.tab")}),"aria-pressed":nd,"aria-controls":"navigator-lounge-panel","data-navigator-mode":"lounge",onClick:()=>g?.(!nd),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:nd?"var(--bg-selected)":"transparent",color:nd?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:nd?600:500,whiteSpace:"nowrap"},children:v("lounge.tab")})]}),!nd&&"projects"===er&&(0,r.jsx)("button",{type:"button",onClick:()=>ek(e=>!e),disabled:!tG,title:b("sidebar.projectShowHidden"),"aria-label":b("sidebar.projectShowHidden"),"aria-pressed":ew,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:5,background:ew?"var(--bg-selected)":"transparent",color:ew?"var(--accent)":"var(--text-dim)",cursor:tG?"pointer":"default",opacity:tG?1:.45,flexShrink:0},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!ew&&(0,r.jsx)("path",{d:"m4 4 16 16"})]})}),!nd&&"projects"===er&&(0,r.jsx)("button",{className:"navigator-add-project",type:"button",onClick:tE,title:b("sidebar.addProject"),"aria-label":b("sidebar.addProject"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"}),(0,r.jsx)("path",{d:"M15.5 10.5v5M13 13h5"})]})})]}),nd&&m,!nd&&"projects"===er&&(0,r.jsxs)("label",{className:"navigator-search",style:{position:"relative",display:"block",margin:"0 8px 8px"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",style:{position:"absolute",left:10,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-3.5-3.5"})]}),(0,r.jsx)("input",{className:"navigator-search-input",type:"search",value:B,onChange:e=>X(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),X(""),e.currentTarget.blur())},placeholder:b("sidebar.searchProjectsAndSessions"),"aria-label":b("sidebar.searchProjectsAndSessions"),style:{width:"100%",height:34,padding:"0 10px 0 32px",border:"1px solid var(--border)",borderRadius:7,outline:"none",background:"var(--bg-hover)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})]}),!nd&&"projects"===er&&(0,r.jsxs)("div",{id:"navigator-projects-panel",className:"navigator-session-list",style:{flex:"1 1 auto",overflowY:"auto",minHeight:80,padding:"0 6px 10px"},children:[(L||!eb)&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),z&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:z}),eR&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eR}),!L&&eb&&!z&&0===t5.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:t2?b("sidebar.noMatchingProjects"):b("sidebar.noSessions")}),!L&&eb&&!z&&t9.map(t=>{let n,i,s;if("temporary"===t.kind)return(0,r.jsx)("div",{className:"navigator-project-group",children:(0,r.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":t7,title:b("sidebar.temporaryProjects"),onClick:()=>eS(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:34,padding:"0 6px 0 2px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:[(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,flexShrink:0,color:"var(--text-dim)"},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:t7?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.temporaryProjects")}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10,flexShrink:0},children:t6.length}),ed(t3,b)]})},"navigator-temporary-projects");let{project:a,key:l,name:o,sessions:d,hidden:c}=t.group,u=l===tU,p=ne.has(o.toLowerCase())&&G((i=Math.max((n=a.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,i),_)||null,h=!eu.has(a)&&!t2,m=eo.has(a),f=eC===a,g=tJ.indexOf(a),x=eM||t4||g<=0,v=eM||t4||g>=tJ.length-1,y=function(e){let t=new Map;for(let n of e)t.set(n.id,{session:n,children:[]});let n=new Map;for(let t of e)t.parentSessionId&&n.set(t.id,t.parentSessionId);let r=[];for(let e of t.values()){let i=function(e){let r=n.get(e),i=new Set;for(;r&&!i.has(r);){if(i.add(r),t.has(r))return r;r=n.get(r)}return null}(e.session.id);i?t.get(i).children.push(e):r.push(e)}let i=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>i(e.children))};return i(r),r}(m?d:d.slice(0,5)),k=d.length>5;return(0,r.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:h?3:9},children:[(0,r.jsxs)("div",{className:`navigator-project-row${u?" is-selected":""}`,ref:ef===a?e1:void 0,onMouseEnter:()=>em(a),onMouseLeave:()=>em(e=>e===a&&ef!==a?null:e),style:{display:"flex",alignItems:"center",minHeight:34,position:"relative",borderRadius:6,background:u?"var(--bg-hover)":"transparent",opacity:c?.55:1},children:[(0,r.jsx)("button",{type:"button",onClick:()=>tH(a),title:h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-label":h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-expanded":!h,style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,marginLeft:2,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:h?"rotate(-90deg)":"rotate(0deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),f?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px"},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--accent)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("input",{ref:e4,value:eI,onChange:e=>eT(e.target.value),onBlur:()=>void tX(a),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),e5.current=!0,eN(null))},"aria-label":b("sidebar.projectAlias"),style:{flex:1,minWidth:0,height:24,padding:"2px 6px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12,fontWeight:600}})]}):(0,r.jsxs)("button",{className:"navigator-project-name",type:"button",onClick:()=>D(a),title:a,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:u?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:u?600:500},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:u?"var(--accent)":"var(--text-dim)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o}),null===p?null:(0,r.jsx)("span",{style:{flexShrink:2,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:p}),ed(t1.get(l),b)]}),(0,r.jsx)("button",{type:"button",onClick:()=>tW(a),title:b("sidebar.newSessionTitle",{path:a}),"aria-label":b("sidebar.newSessionTitle",{path:a}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:5,background:"transparent",color:"var(--text-dim)",cursor:"pointer",opacity:w||eh===a?1:0,pointerEvents:w||eh===a?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>em(a),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,r.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,r.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{eg(ef===a?null:a),eU(!1),eV(!1),eY(null),u||D(a)},title:b("sidebar.projectActions"),"aria-label":b("sidebar.projectActions"),"aria-expanded":ef===a,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:5,background:ef===a?"var(--bg-selected)":"transparent",color:u&&nr&&!nr.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:w||eh===a||ef===a?1:0,pointerEvents:w||eh===a||ef===a?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>em(a),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,r.jsxs)(Z,{open:ef===a,style:{position:"absolute",top:"calc(100% + 4px)",right:3,width:"min(260px, calc(100vw - 24px))",zIndex:110,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"var(--shadow-float)",boxSizing:"border-box",overflow:"hidden"},children:[nn&&eO&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>eU(e=>!e),title:nr?b("sidebar.switchWorktreeTitle",{path:nr.path}):b("sidebar.switchWorktree"),"aria-label":b("sidebar.worktrees"),"aria-expanded":eB,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderBottom:eB?"1px solid var(--border)":"none",background:eB?"var(--bg-selected)":"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{style:{flex:1},children:b("sidebar.worktrees")}),(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"4 2.5 8 6 4 9.5"})})]}),(0,r.jsxs)(Z,{open:eB,style:{position:"static",width:"auto",zIndex:100,background:"var(--bg)",border:"none",borderTop:"1px solid var(--border)",borderRadius:0,boxShadow:"none",boxSizing:"border-box",overflow:"hidden"},children:[ni&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:eL,onChange:e=>eA(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eA(""),eU(!1))},placeholder:b("sidebar.filterWorktrees"),autoFocus:!0,style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[ns.map(e=>{let t=e.path===P||e.isMain&&!eO.worktrees.some(e=>e.path===P);return eQ===e.path?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.06)"},children:[(0,r.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void tA(e.path,!0),disabled:eZ,style:{padding:"3px 9px",background:"var(--danger)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:b("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>e0(null),style:{padding:"3px 9px",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer",flexShrink:0},children:b("sidebar.cancel")})]},e.path):(0,r.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("button",{onClick:()=>{D(e.path),eU(!1),eY(null),eA("")},title:e.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)(Y,{text:e.branch??G(e.path,_),style:{flex:1}}),e.isMain&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:b("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void tA(e.path,!1),disabled:eZ,title:b("sidebar.removeWorktreeTitle",{path:e.path}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:34,height:28,padding:0,marginRight:4,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",borderRadius:5,flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="#ef4444",e.currentTarget.style.background="rgba(239,68,68,0.08)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.path)}),ni&&0===ns.length&&eL.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:b("sidebar.noMatchingWorktrees")})]}),eq?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:e2,value:eK,onChange:e=>{eJ(e.target.value),eY(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),tL()),"Escape"===e.key&&(eV(!1),eJ(""),eY(null))},placeholder:b("sidebar.branchName"),style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,r.jsx)("button",{onClick:()=>void tL(),disabled:eZ||!eK.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:eZ||!eK.trim()?"not-allowed":"pointer",opacity:eZ||!eK.trim()?.65:1},children:eZ?b("sidebar.creating"):b("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{eV(!1),eJ(""),eY(null)},style:{flex:1,padding:"4px 0",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer"},children:b("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),eV(!0),eY(null),setTimeout(()=>e2.current?.focus(),0)},title:b("sidebar.createWorktreeTitle"),style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{children:b("sidebar.newWorktree")})]}),eG&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:eG})]})]}),(0,r.jsxs)("button",{type:"button",disabled:eM,onClick:()=>{let e;return e=tq.get(N(a))?.alias??"",void(e5.current=!1,eE(null),eT(e),eN(a),tY())},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:eM?"default":"pointer",textAlign:"left",fontSize:11,opacity:eM?.55:1},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m4 20 4.5-1 10-10a2.1 2.1 0 0 0-3-3l-10 10L4 20Z"}),(0,r.jsx)("path",{d:"m13.5 8 3 3"})]}),b(tq.get(N(a))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:x,title:t4?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void tQ(a,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:x?"default":"pointer",textAlign:"left",fontSize:11,opacity:x?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 15 6-6 6 6"})}),b("sidebar.projectMoveUp")]}),(0,r.jsxs)("button",{type:"button",disabled:v,title:t4?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void tQ(a,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:v?"default":"pointer",textAlign:"left",fontSize:11,opacity:v?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})}),b("sidebar.projectMoveDown")]}),(0,r.jsxs)("button",{type:"button",disabled:eM,onClick:()=>void tZ(a,!c),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:eM?"default":"pointer",textAlign:"left",fontSize:11,opacity:eM?.55:1},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!c&&(0,r.jsx)("path",{d:"m4 4 16 16"})]}),b(c?"sidebar.projectUnhide":"sidebar.projectHide")]}),(s=0===no(t0.get(l)??[])||th,(0,r.jsxs)("button",{type:"button",disabled:s,onClick:()=>{tY(),tg(null),tp({kind:"project",project:a,label:o})},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:s?"default":"pointer",textAlign:"left",fontSize:11,opacity:s?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),b("sidebar.clearProjectSessions")]}))]})]})]}),!h&&0===d.length&&u&&(0,r.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:b("sidebar.noSessions")}),!h&&y.length>0&&(0,r.jsx)("div",{style:{paddingLeft:12},children:y.map(t=>(0,r.jsx)(ea,{node:t,selectedSessionId:e,runningSessionIds:e7,unreadSessionIds:te,pinnedSessionIds:tn,onSelectSession:tz,onTogglePinnedSession:tS,onRenamed:td,onSessionDeleted:tc,onSessionArchived:tw,depth:0},t.session.id))}),!h&&k&&(0,r.jsx)("button",{type:"button",onClick:()=>{ec(e=>{let t=new Set(e);return t.has(a)?t.delete(a):t.add(a),t})},style:{display:"block",margin:"3px 0 3px 32px",padding:"5px 8px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:m?b("sidebar.showLess"):b("sidebar.showMore")})]},a)})]}),!nd&&(0,r.jsx)(es,{refreshKey:tb,selectedSessionId:e,onSelectSession:tz,onRestored:tw}),!nd&&"priority"===er&&(0,r.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[L&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),z&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:z}),!L&&!z&&(x=no(nt.flatMap(e=>e.sessions)),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"8px 2px 2px"},children:[(0,r.jsx)("button",{type:"button",disabled:tF,onClick:()=>void tO(),title:b("sidebar.newScratchSessionTitle"),style:J(tF,w),children:b("sidebar.newScratchSession")}),nt.length>0&&(0,r.jsx)("button",{type:"button",disabled:0===x||th,onClick:()=>{tg(null),tp({kind:"priority"})},style:J(0===x||th,w),children:b("sidebar.clearPriorityList")})]})),tD&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:tD}),!L&&!z&&0===nt.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.noSessions")}),!L&&!z&&nt.map((t,n)=>(0,r.jsxs)("section",{"aria-labelledby":`priority-group-${t.key}`,children:[(0,r.jsx)("h2",{id:`priority-group-${t.key}`,style:{margin:0,padding:0===n?"2px 8px 4px":"14px 8px 4px",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.label}),t.sessions.map(t=>(0,r.jsx)(ei,{session:t,selected:t.id===e,running:e7.has(t.id),unread:te.has(t.id),pinned:tn.has(t.id),onSelect:tz,onTogglePin:tS},t.id))]},t.key))]})]})}function en({scope:e,eligible:t,runningExcluded:n,busy:s,error:a,onCancel:l,onConfirm:o}){let{t:d}=(0,R.s)(),c=s||0===t,u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(s);h.current=s;let m=(0,i.useRef)(l);return m.current=l,(0,i.useEffect)(()=>{let e=u.current;if(!e)return;let t=document.activeElement,n=t instanceof HTMLElement&&t!==document.body&&t!==document.documentElement&&!e.contains(t)?t:null;(p.current??e).focus();let r=t=>{if("Escape"===t.key){if(h.current)return;t.preventDefault(),m.current();return}if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],s=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),s.focus()):t.shiftKey||r!==s&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",r),()=>{e.removeEventListener("keydown",r);let t=n?.isConnected?n:e.closest(".session-navigator");t?.focus()}},[]),(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:e=>{s||e.target!==e.currentTarget||l()},children:(0,r.jsxs)("div",{ref:u,role:"alertdialog","aria-modal":"true","aria-labelledby":"bulk-clear-title","aria-describedby":"bulk-clear-body",tabIndex:-1,style:{width:420,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"var(--shadow-float)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"18px 18px 14px"},children:[(0,r.jsx)("div",{id:"bulk-clear-title",style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:d("sidebar.clearSessionsTitle")}),(0,r.jsxs)("div",{id:"bulk-clear-body",style:{marginTop:8,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,overflowWrap:"anywhere"},children:["project"===e.kind?d("sidebar.clearSessionsProjectBody",{project:e.label,count:t}):d("sidebar.clearSessionsPriorityBody",{count:t}),n>0&&(0,r.jsx)("div",{style:{marginTop:6},children:d("sidebar.clearSessionsRunningExcluded",{count:n})}),0===t&&(0,r.jsx)("div",{style:{marginTop:6},children:d("sidebar.clearSessionsNone")})]}),a&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:a})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{ref:p,type:"button",onClick:l,disabled:s,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:s?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:d("sidebar.clearSessionsCancel")}),(0,r.jsx)("button",{type:"button",onClick:o,disabled:c,"aria-busy":s,style:{minHeight:36,padding:"0 14px",border:"1px solid var(--danger)",borderRadius:"var(--radius-control)",background:"transparent",color:c?"var(--text-dim)":"var(--danger)",cursor:c?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:d(s?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function er({filled:e=!1}){return(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:e?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M5 17h14"}),(0,r.jsx)("path",{d:"M6 3h12l-1 8 2 3H5l2-3-1-8z"})]})}function ei({session:e,selected:t,running:n,unread:i,pinned:s,onSelect:a,onTogglePin:l}){let{t:o}=(0,R.s)(),d=(e.name||e.firstMessage||e.id.slice(0,8)).replace(/\s+/g," ").trim(),c=e.cwd.split(/[\\/]/).filter(Boolean).at(-1)??"";return(0,r.jsxs)("div",{className:`priority-session-row${t?" is-selected":""}${n?" is-running":""}${i?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:5,background:t?"var(--bg-selected)":"transparent"},children:[(0,r.jsxs)("button",{type:"button","aria-current":t?"page":void 0,onClick:()=>a(e),title:`${d}
|
|
2
|
-
${e.cwd}
|
|
3
|
-
${new Date(e.modified).toLocaleString()}`,style:{minWidth:0,flex:1,display:"block",padding:"7px 8px",border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12.5,fontWeight:500,lineHeight:1.4},children:d}),n&&(0,r.jsx)(el,{}),!n&&i&&(0,r.jsx)(eo,{})]}),(0,r.jsx)("span",{style:{display:"block",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:c})]}),(0,r.jsx)("button",{type:"button","aria-pressed":s,"aria-label":o(s?"sidebar.unpin":"sidebar.pin"),title:o(s?"sidebar.unpin":"sidebar.pin"),onClick:()=>l(e.id),style:{width:30,border:"none",background:"transparent",color:s?"var(--accent)":"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)(er,{filled:s})})]})}function es({refreshKey:e,selectedSessionId:t,onSelectSession:n,onRestored:s}){let{t:a}=(0,R.s)(),[l,o]=(0,i.useState)(!1),[d,c]=(0,i.useState)([]);(0,i.useEffect)(()=>{let e=!1;return(async()=>{try{let t=await fetch("/api/sessions?archived=1",{cache:"no-store"});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();e||c(n.sessions)}catch{}})(),()=>{e=!0}},[e]);let u=(0,i.useCallback)(async(e,t)=>{e.stopPropagation();try{await fetch(`/api/sessions/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:!1})}),s(t)}catch{}},[s]);return 0!==d.length||l?(0,r.jsxs)("section",{style:{borderTop:"1px solid var(--border)",marginTop:4},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>o(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"7px 12px",background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:600,textAlign:"left"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:l?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.1s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})}),a("sidebar.archived")," (",d.length,")"]}),l&&(0,r.jsxs)("div",{style:{paddingLeft:12},children:[0===d.length&&(0,r.jsx)("div",{style:{padding:"4px 12px 8px 20px",color:"var(--text-dim)",fontSize:11},children:a("sidebar.noArchivedSessions")}),d.map(e=>{let i=$(e.firstMessage)??e.firstMessage,s=e.name||i.slice(0,50)||e.id.slice(0,12);return(0,r.jsxs)("div",{onClick:()=>n(e),style:{height:40,display:"flex",alignItems:"center",paddingLeft:20,paddingRight:4,gap:4,cursor:"pointer",overflow:"hidden",borderLeft:e.id===t?"2px solid var(--accent)":"2px solid transparent",background:e.id===t?"var(--bg-selected)":"transparent"},children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s}),(0,r.jsx)("button",{onClick:t=>u(t,e.id),title:a("sidebar.restore"),style:{display:"flex",alignItems:"center",justifyContent:"center",height:24,padding:"0 8px",flexShrink:0,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:500},children:a("sidebar.restore")})]},e.id)})]})]}):null}function ea({node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:s,pinnedSessionIds:a,onSelectSession:l,onRenamed:o,onSessionDeleted:d,onTogglePinnedSession:c,onSessionArchived:u,depth:p}){let[h,m]=(0,i.useState)(!1),f=e.children.length>0;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{position:"relative"},children:[p>0&&(0,r.jsx)("div",{style:{position:"absolute",left:10*p+6,top:0,bottom:0,width:1,background:"var(--border)",pointerEvents:"none"}}),(0,r.jsx)(ec,{session:e.session,isSelected:e.session.id===t,isRunning:n.has(e.session.id),isUnread:s.has(e.session.id),isPinned:a.has(e.session.id),onClick:()=>l(e.session),onTogglePin:()=>c(e.session.id),onRenamed:o,onDeleted:e=>d?.(e),onArchived:e=>u?.(e),depth:p,hasChildren:f,collapsed:h,onToggleCollapse:()=>m(e=>!e)})]}),f&&!h&&(0,r.jsx)("div",{children:e.children.map(e=>(0,r.jsx)(ea,{node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:s,pinnedSessionIds:a,onSelectSession:l,onTogglePinnedSession:c,onRenamed:o,onSessionDeleted:d,onSessionArchived:u,depth:p+1},e.session.id))})]})}function el(){let{t:e}=(0,R.s)();return(0,r.jsx)("span",{title:e("sidebar.agentRunning"),"aria-label":e("sidebar.agentRunning"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,r.jsx)("svg",{className:"session-running-spinner",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})})})}function eo(){let{t:e}=(0,R.s)();return(0,r.jsx)("span",{title:e("sidebar.newActivity"),"aria-label":e("sidebar.newSessionActivity"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",style:{display:"block"},children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"2.5",fill:"currentColor"}),(0,r.jsx)("circle",{className:"session-unread-ring",cx:"7",cy:"7",r:"3",stroke:"currentColor",strokeWidth:"1.4"})]})})}function ed(e,t){return e&&(0!==e.running||0!==e.unread)?(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,flexShrink:0,marginLeft:6},children:[e.running>0&&(0,r.jsxs)("span",{title:t("sidebar.agentRunning"),"aria-label":`${t("sidebar.agentRunning")} (${e.running})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("svg",{className:"session-running-spinner",width:"10",height:"10",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})}),e.running]}),e.unread>0&&(0,r.jsxs)("span",{title:t("sidebar.newSessionActivity"),"aria-label":`${t("sidebar.newSessionActivity")} (${e.unread})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"currentColor",display:"inline-block"}}),e.unread]})]}):null}function ec({session:e,isSelected:t,isRunning:n,isUnread:s,isPinned:a,onClick:l,onTogglePin:o,onRenamed:d,onDeleted:c,onArchived:u,depth:p=0,hasChildren:h=!1,collapsed:m=!1,onToggleCollapse:f}){let{t:g}=(0,R.s)(),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(!1),[w,k]=(0,i.useState)(""),[j,S]=(0,i.useState)(!1),[C,N]=(0,i.useState)(!1),I=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(b){let e=requestAnimationFrame(()=>I.current?.select());return()=>cancelAnimationFrame(e)}},[b]);let T=$(e.firstMessage)??e.firstMessage,M=e.name||T.slice(0,50)||e.id.slice(0,12),E=(0,i.useCallback)(t=>{t.stopPropagation(),e.transient||(k(e.name||T.slice(0,50)||e.id.slice(0,12)),y(!0))},[e.name,e.transient,T,e.id]),L=(0,i.useCallback)(async()=>{let t=w.trim();if(y(!1),w!==M&&t!==(e.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})}),d?.()}catch{}},[w,e.id,e.name,d,M]),A=(0,i.useCallback)(async()=>{if(!e.transient){S(!1),N(!0);try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"}),c?.(e.id)}catch{N(!1)}}},[e.id,e.transient,c]),z=(0,i.useCallback)(async t=>{if(t.stopPropagation(),!e.transient)try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:!0})}),u?.(e.id)}catch{}},[e.id,e.transient,u]),W=(0,i.useCallback)(e=>{e.stopPropagation(),e.shiftKey?A():S(!0)},[A]),F=(0,i.useCallback)(e=>{e.stopPropagation(),A()},[A]),P=(0,i.useCallback)(e=>{e.stopPropagation(),S(!1)},[]),D=(0,i.useCallback)(t=>{(function(e,t=window){let n=new CustomEvent("pi-web:session-row-contextmenu",{cancelable:!0,detail:e});return!t.dispatchEvent(n)})({id:e.id,path:e.path,cwd:e.cwd,name:e.name,clientX:t.clientX,clientY:t.clientY,refresh:()=>{d?.()}})&&(t.preventDefault(),t.stopPropagation())},[d,e.cwd,e.id,e.name,e.path]);return(0,r.jsx)("div",{className:`navigator-session-row${t?" is-selected":""}${n?" is-running":""}${s?" is-unread":""}${j?" is-confirming":""}`,onClick:j||b?void 0:l,onContextMenu:j||b?void 0:D,onMouseEnter:()=>v(!0),onMouseLeave:()=>{v(!1)},style:{height:40,display:"flex",alignItems:"center",paddingLeft:p>0?10*p+8:8,paddingRight:4,cursor:j||b?"default":"pointer",background:t?"var(--bg-selected)":x?"var(--bg-hover)":"transparent",borderLeft:"2px solid transparent",transition:"background 0.1s",opacity:C?.5:1,gap:4,overflow:"hidden"},children:j?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g("sidebar.deleteSession",{title:M.slice(0,22)+(M.length>22?"…":"")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,r.jsxs)("button",{onClick:F,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,height:30,padding:"0 11px",background:"var(--danger)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),g("sidebar.delete")]}),(0,r.jsx)("button",{onClick:P,style:{display:"flex",alignItems:"center",justifyContent:"center",height:30,padding:"0 11px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:500,whiteSpace:"nowrap"},children:g("sidebar.cancel")})]})]}):b?(0,r.jsx)("input",{ref:I,value:w,onChange:e=>k(e.target.value),onBlur:L,onKeyDown:e=>{"Enter"===e.key&&L(),"Escape"===e.key&&y(!1)},autoFocus:!0,style:{flex:1,fontSize:12,padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",height:30}}):(0,r.jsxs)(r.Fragment,{children:[p>0&&(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),l()},"aria-current":t?"page":void 0,title:M,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,color:"var(--text)",fontSize:12.5,fontWeight:t?500:400,lineHeight:1.35,padding:0,border:"none",background:"transparent",fontFamily:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M}),n&&(0,r.jsx)(el,{}),!n&&s&&(0,r.jsx)(eo,{}),e.worktreeBranch&&(0,r.jsx)("span",{title:g("sidebar.worktreePath",{path:e.cwd}),style:{display:"flex",color:"var(--accent)",flexShrink:0},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})})]}),h&&(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),f?.()},title:g(m?"sidebar.expandForks":"sidebar.collapseForks"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",transform:m?"rotate(-90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),!e.transient&&(0,r.jsxs)("div",{style:{display:"flex",gap:4,flexShrink:0},children:[(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),o?.()},title:g(a?"sidebar.unpin":"sidebar.pin"),"aria-label":g(a?"sidebar.unpin":"sidebar.pin"),"aria-pressed":a,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:a?"var(--bg-selected)":"transparent",border:"none",borderRadius:5,color:a?"var(--accent)":"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:x||a?1:0,pointerEvents:x||a?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>v(!0),children:(0,r.jsx)(er,{filled:a})}),(0,r.jsx)("button",{onClick:E,title:g("sidebar.rename"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:+!!x,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>v(!0),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="transparent"},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),(0,r.jsx)("button",{onClick:z,title:g("sidebar.archive"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"4",rx:"1"}),(0,r.jsx)("path",{d:"M5 8v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"}),(0,r.jsx)("path",{d:"M10 12h4"})]})}),(0,r.jsx)("button",{onClick:W,title:g("sidebar.deleteWithShiftClick"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:+!!x,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>v(!0),onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)",e.currentTarget.style.color="#ef4444",e.currentTarget.style.borderColor="rgba(239,68,68,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="transparent"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]})]})})}let eu=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,ep=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,eh=/\x1B\[([0-9;]*)m/g,em=/\x1B_pi:c\x07/g,ef=["#1f2937","#dc2626","#16a34a","#d97706","#2563eb","#9333ea","#0891b2","#6b7280"],eg=["#9ca3af","#ef4444","#22c55e","#f59e0b","#3b82f6","#a855f7","#06b6d4","#e5e7eb"];function ex(e){return e.replace(em,"").replace(eu,"")}function ev(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(ep);if(t){n+=t[0].length;continue}}let r=e.codePointAt(n);if(void 0===r)break;let i=String.fromCodePoint(r);t.push({start:n,end:n+i.length,char:i}),n+=i.length}return t}function eb(e,t){let n=ev(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function ey(e){return ev(e)[0]?.char}function ew(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(em,""),i=ex(e).trimEnd();if(t.test(i))continue;let s=e,a=ey(s);("│"===a||"┃"===a)&&" "===ey(s=eb(s,0))&&(s=eb(s,0));let l=function(e){let t=ev(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(s),o=l>=0?ev(s)[l]?.char:void 0;("│"===o||"┃"===o)&&(s=eb(s,l)),n.push(function(e){let t=e;for(;;){let e=ev(t),n=e[e.length-1];if(!n||""!==n.char.trim())return t;t=t.slice(0,n.start)+t.slice(n.end)}}(s))}for(;n.length>0&&""===ex(n[0]).trim();)n.shift();for(;n.length>0&&""===ex(n[n.length-1]).trim();)n.pop();return n.length?n:e}function ek(e){let t,n=[],r={},i=0;for(eh.lastIndex=0;null!==(t=eh.exec(e));)t.index>i&&n.push({text:e.slice(i,t.index),style:r}),r=function(e,t){let n={...e};for(let e=0;e<t.length;e++){let r=t[e];if(0===r)for(let e of Object.keys(n))delete n[e];else if(1===r)n.fontWeight=700;else if(2===r)n.opacity=.65;else if(3===r)n.fontStyle="italic";else if(4===r)n.textDecoration="underline";else if(22===r)delete n.fontWeight,delete n.opacity;else if(23===r)delete n.fontStyle;else if(24===r)delete n.textDecoration;else if(39===r)delete n.color;else if(49===r)delete n.backgroundColor;else if(r>=30&&r<=37)n.color=ef[r-30];else if(r>=90&&r<=97)n.color=eg[r-90];else if(r>=40&&r<=47)n.backgroundColor=ef[r-40];else if(r>=100&&r<=107)n.backgroundColor=eg[r-100];else if((38===r||48===r)&&2===t[e+1]){let[i,s,a]=[t[e+2],t[e+3],t[e+4]];[i,s,a].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===r?n.color=`rgb(${i}, ${s}, ${a})`:n.backgroundColor=`rgb(${i}, ${s}, ${a})`),e+=4}else if((38===r||48===r)&&5===t[e+1]){let i=function(e){if(e>=0&&e<8)return ef[e];if(e>=8&&e<16)return eg[e-8];if(e>=16&&e<=231){let t=e-16,n=Math.floor(t/36),r=Math.floor(t%36/6),i=e=>0===e?0:55+40*e;return`rgb(${i(n)}, ${i(r)}, ${i(t%6)})`}if(e>=232&&e<=255){let t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}}(t[e+2]);i&&(38===r?n.color=i:n.backgroundColor=i),e+=2}}return n}(r,t[1]?t[1].split(";").map(e=>Number(e||"0")):[0]),i=t.index+t[0].length;return i<e.length&&n.push({text:e.slice(i),style:r}),n}let ej={ArrowUp:"\x1b[A",ArrowDown:"\x1b[B",ArrowRight:"\x1b[C",ArrowLeft:"\x1b[D",Home:"\x1b[H",End:"\x1b[F",Insert:"\x1b[2~",Delete:"\x1b[3~",PageUp:"\x1b[5~",PageDown:"\x1b[6~",Escape:"\x1b",Backspace:""},eS={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"},eC={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},eN={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm",webm:"audio/webm"};function eI(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function eT(e){return null!==(eC[eI(e)]??null)}function eM(e,t,n={}){let r={...e,content:t};return n.omitUsage&&(r.usage=void 0),r}function e$(e,t={}){return!!t.hideThinking&&"thinking"===e.type||function(e,t={}){return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===e.thinking.trim()}(e,t)}function eR(e,t={}){return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function eE(e,t={}){let n=[];for(let r of function(e,t={}){return(e.content??[]).filter(e=>!e$(e,t))}(e,t)){let e="image"===r.type||"text"===r.type&&r.text.trim().length>0?"answer":"process",t=n[n.length-1];t?.kind===e?t.blocks.push(r):n.push({kind:e,blocks:[r]})}return n}function eL(e){return e.filter(e=>"toolCall"===e.type).length}function eA(e,t,n){let r=new URLSearchParams({sessionId:e,toolCallId:t});return void 0!==n&&r.set("index",String(n)),`/api/tool-image?${r}`}function ez(e){let t=new Map;for(let n of e)"toolResult"===n.role&&t.set(n.toolCallId,n);let n=[],r=-1;return{collect(e,i){for(let s of i)"toolCall"===s.type&&function(e,t){if(!t||t.isError)return!1;if(t.content?.some(e=>"image"===e.type))return!0;let n=e.input??{};return"generate_image"===e.toolName||("write"===e.toolName?"xd://generate_image"===n.path:"read"===e.toolName&&"string"==typeof n.path&&eT(n.path))}(s,t.get(s.toolCallId))&&(n.push({type:"image",source:{type:"url",url:""},toolImage:{toolCallId:s.toolCallId}}),r=e)},attach(e){if(0===n.length)return e;let t=[...n,...e];return n=[],t},takeRemaining(){if(0===n.length)return null;let e={idx:r,blocks:n};return n=[],e}}}let eW=new Map,eF=new Map,eP="command",eD="autolearn-saved";function e_(e){return"custom"===e.role&&(e.customType===eP||e.customType===eD&&!1!==e.display)}let eO="local-command:";function eH(e){return e?.startsWith(eO)===!0}function eB(e,t,n){let r=new Set(n.map(e=>e.message)),i=[],s=[];for(let n=0;n<e.length;n++){let a=n<t.length;!(r.has(e[n])||a&&eH(t[n]))&&(i.push(e[n]),a&&s.push(t[n]))}for(let e of n){let t=0;if(null!==e.baseEntryId){let n=s.indexOf(e.baseEntryId);if(-1===n)continue;t=n+1}let n=e.message.timestamp??0;for(;t<i.length;){let e=i[t];if(!r.has(e)&&"number"==typeof e.timestamp&&e.timestamp>n)break;t+=1}i.splice(t,0,e.message),t<=s.length&&s.splice(t,0,e.entryId)}return{messages:i,entryIds:s}}function eU(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}let eq={create:!0,update:!0};function eV(e){return"string"==typeof e?e.replace(/\s+/g," ").trim():""}function eK(e){if("string"==typeof e)return e;if(!Array.isArray(e))return"";let t=[];for(let n of e)n&&"object"==typeof n&&"type"in n&&"text"===n.type&&"text"in n&&"string"==typeof n.text&&t.push(n.text);return t.join("\n")}function eJ(e,t){if(0===e.length)return -1;if(!t)return 0;let n=-1;for(let r=0;r<e.length;r++){let i=e[r];if(i.item===t.item){if(i.k===t.k)return r;n=r}}return -1===n?0:n}function eG(e){try{return decodeURIComponent(e)}catch{return e}}function eY(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function eZ(e){let t=eY(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),i=t.startsWith("/")&&!n&&!r,s=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){s.length>0&&".."!==s[s.length-1]?s.pop():i||n||r||s.push(e);continue}s.push(e)}let a=s.join("/");return n?a:r?`//${a}`:i?`/${a}`:a}function eX(e,t,n=t){let r,i,s,a,l;if(!e)return null;let o=e.split("#",1)[0].split("?",1)[0].trim();if(!o)return null;let d=null,c=null,u=eG(o),p=u.startsWith("\\\\"),h=eY(u),m=h.toLowerCase();if(m.startsWith("/api/")||m.startsWith("/_next/")||!p&&h.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(h)&&!m.startsWith("file:")&&!/^[a-zA-Z]:\//.test(h))return null;if(m.startsWith("file:")?c=(d=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=eG(t.pathname);if(t.hostname)return`//${t.hostname}${n.startsWith("/")?n:`/${n}`}`;if(/^\/[a-zA-Z]:\//.test(n))return n.slice(1);return n}catch{return null}}(h))?"absolute":null:/^[a-zA-Z]:\//.test(h)||h.startsWith("/")?(d=h,c="absolute"):t&&!(h.startsWith("#")||h.startsWith("?"))&&(h.startsWith("./")||h.startsWith("../")||h.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(h))&&(d=`${eY(t).replace(/\/+$/,"")}/${h}`,c="relative"),!d)return null;let f=eZ(d).replace(/:\d+(?::\d+)?$/,"");return"relative"===c&&n&&(r=eZ(f).replace(/\/+$/,""),i=eZ(n).replace(/\/+$/,""),a=(s=/^[a-zA-Z]:\//.test(r)||/^[a-zA-Z]:\//.test(i))?r.toLowerCase():r,!(a===(l=s?i.toLowerCase():i)||a.startsWith(`${l}/`)))?null:f}function eQ(e,t,n){let r=new Set,i=[];for(let s of e){if("toolCall"!==s.type||!function(e){let t,n;return"write"===(t=e.toLowerCase())||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")||"edit"===(n=e.toLowerCase())||n.startsWith("edit_")||n.endsWith(".edit")||n.endsWith("_edit")||n.includes("str_replace")||n.includes("replace_editor")}(s.toolName))continue;let e=t?.get(s.toolCallId);if(!e||e.isError)continue;let a=function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(s.input);if(!a||!/^[a-zA-Z]:[\\/]/.test(a)&&/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(a))continue;let l=function(e,t){let n;if(!e)return null;let r=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),i=e=>r?e.replace(/\\/g,"/"):e,s=i(e),a=t?i(t).replace(/\/+$/,""):void 0,l=/^[a-zA-Z]:\//.test(s),o=s.startsWith("//");if(l||o)n=s;else if(s.startsWith("/")){let e=a?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??a?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${s}`:s}else{if(!a)return null;n=`${a}/${s}`}return eZ(n)}(a,n);l&&(r.has(l)||(r.add(l),i.push({filePath:l})))}return i}function e0(e,t){var n;let r;if(t){let e=t.details,n=e&&"object"==typeof e&&"phases"in e?e.phases:void 0;if(!Array.isArray(n))return{kind:"unknown"};let{phases:r,malformed:i}=function(e){let t=[];for(let n of e){if(!n||"object"!=typeof n||!("name"in n)||!("tasks"in n))return{phases:t,malformed:!0};let{name:e,tasks:r}=n;if("string"!=typeof e||!Array.isArray(r))return{phases:t,malformed:!0};let i=Array.isArray(r)?r.flatMap(e=>{if(!e||"object"!=typeof e||!("content"in e)||!("status"in e))return[];let{content:t,status:n}=e;return"string"!=typeof t||"pending"!==n&&"in_progress"!==n&&"completed"!==n&&"abandoned"!==n&&"blocked"!==n?[]:[{content:t,status:n,blocker:"blocker"in e&&"string"==typeof e.blocker?e.blocker:void 0}]}):[];if(i.length!==r.length)return{phases:t,malformed:!0};i.length>0&&t.push({name:e,tasks:i})}return{phases:t,malformed:!1}}(n);return i?{kind:"unknown"}:{kind:"authoritative",phases:r}}let i=Array.isArray(r=(n=e.input)&&"object"==typeof n&&"list"in n?n.list:void 0)?r.flatMap(e=>{if(!e||"object"!=typeof e||!("phase"in e)||!("items"in e))return[];let{phase:t,items:n}=e;if("string"!=typeof t||!Array.isArray(n))return[];let r=n.filter(e=>"string"==typeof e).map(e=>({content:e,status:"pending"}));return r.length>0?[{name:t,tasks:r}]:[]}):[];return i.length>0?{kind:"preview",phases:i}:{kind:"unknown"}}var e1=n(65063),e2=n(7644),e4=n(32316);function e5(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function e8(e){return e5(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function e6(e){let t=e5(e).replace(/\/+$/,"");return t.split("/").pop()??t}function e3(e,t){if(!t)return e;let n=e5(e),r=e5(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}var e7=n(88374),e9=n(63280),te=n(94764),tt=n(63835),tn=n(54152),tr=n(84678),ti=n(98164);let ts={...te.j,attributes:{...te.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},strip:[...te.j.strip||[],"iframe","object","style","form"]};function ta(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,s=0,a=null,l=new Map;for(let e=0;e<n.length;e++){var o;let t=n[e];if(a){r.push(t),RegExp(`</${a}\\s*>`,"i").test(t)&&(a=null);continue}let d=t.match(/^ {0,3}(`{3,}|~{3,})/);if(d){let e=d[1][0],n=d[1].length;i?e===i.marker&&n>=i.size&&(i=null):i={marker:e,size:n},s=0,r.push(t);continue}if(i){r.push(t);continue}let c=t.match(/<(code|pre|script|style)\b/i);if(c){let e=c[1].toLowerCase(),n=t.slice((c.index??0)+c[0].length);RegExp(`</${e}\\s*>`,"i").test(n)||(a=e),s=0,r.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){s=0,r.push(t);continue}if(s||t.includes("`")){s=function(e,t){let n=t;for(let t=0;t<e.length;){if("`"!==e[t]){t++;continue}let r=t+1;for(;"`"===e[r];)r++;let i=r-t;0===n?n=i:i===n&&(n=0),t=r}return n}(t,s),r.push(t);continue}let u=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(u){let e=u[2].trim();if(e){r.push(`${u[1]}$$`,`${u[1]}${e}`,`${u[1]}$$`);continue}}let p=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(p){let t=function(e,t){for(let n=t;n<e.length;n++){let t=e[n];if(/^ {0,3}\\\][ \t]*$/.test(t))return n;if(/^ {0,3}(`{3,}|~{3,})/.test(t)||/^ {0,3}\\\[[ \t]*$/.test(t)||/<(code|pre|script|style)\b/i.test(t))break}return -1}(n,e+1);if(-1!==t){r.push(`${p[1]}$$`,...n.slice(e+1,t).map(e=>to(e,p[1])),`${p[1]}$$`),e=t;continue}}let h=t.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \t]*$/);if(h){let e=h[2].trim();if(e){r.push(`${h[1]}$$`,`${h[1]}${e}`,`${h[1]}$$`);continue}}let m=t.match(/^([ \t]{0,3})\$\$(.+)$/);if(m){let t=m[1],i=m[2].trimEnd();if(i&&!i.includes("$$")){let s=tl(n,e+1,t,l);if(s){r.push(`${t}$$`,`${t}${i}`);for(let i=e+1;i<s.index;i++)r.push(to(n[i],t));s.content&&r.push(`${t}${s.content}`),r.push(`${t}$$`),e=s.index;continue}}}let f=t.match(/^([ \t]{0,3})\$\$\s*$/);if(f){let t=f[1],i=tl(n,e+1,t,l);if(i&&(i.glued||""!==t)){r.push(`${t}$$`);for(let s=e+1;s<i.index;s++)r.push(to(n[s],t));i.content&&r.push(`${t}${i.content}`),r.push(`${t}$$`),e=i.index;continue}}r.push((o=t,/^\s{0,3}\[[^\]]+\]:/.test(o)||/]\s*\(/.test(o)||/<(?:!--|\/?[A-Za-z][^>]*>)/.test(o)||/\b(?:https?|file|mailto):/i.test(o)||/\b[A-Za-z]:\\/.test(o)?o:o.replace(/(?<!\\)\\\(([^`\r\n$]+?)(?<!\\)\\\)/g,(e,t)=>t.trim()?`$${t}$`:e)))}return r.join(t)}function tl(e,t,n,r){let i=r.get(n);if(void 0!==i&&t<i)return null;for(let i=t;i<e.length;i++){var s,a,l,o;let t=e[i];if(s=t,""===(a=n)?/^ {0,3}\$\$\s*$/.test(s):s.startsWith(a)&&/^\$\$\s*$/.test(s.slice(a.length)))return{index:i,content:"",glued:!1};if(l=t,/^ {0,3}(`{3,}|~{3,})/.test(l)||/^[ \t]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/.test(l)||/^ {0,3}#{1,6}(?:[ \t]+|$)/.test(l)||/^ {0,3}>/.test(l)||/<(code|pre|script|style)\b/i.test(l)||(o=t,/^ {0,3}\$\$(?:\S|[ \t]+\S)/.test(o)))return r.set(n,i),null;let d=function(e,t){if(!e.startsWith(t))return null;let n=e.slice(t.length).match(/^(.+?)\$\$\s*$/);if(!n)return null;let r=n[1].trimEnd();return r&&!r.includes("$$")?r:null}(t,n);if(null!==d)return{index:i,content:d,glued:!0}}return r.set(n,e.length),null}function to(e,t){if(!t||!e||e.startsWith(" "))return e;let n=e.match(/^ */)?.[0].length??0;return n>=t.length?e:`${t.slice(n)}${e}`}let td={singleTilde:!1},tc=[[tn.A,["yaml"]],[tr.A,td],ti.A],tu=[[tn.A,["yaml"]],[tr.A,td],ti.A],tp=[e9.A,[tt.A,ts],[e7.A,{throwOnError:!1,strict:!1}]],th=[e9.A,[tt.A,ts],[e7.A,{throwOnError:!1,strict:!1}]],tm="pi-theme",tf=["light","dark","auto"],tg={preference:"auto",theme:"light"},tx="omp-theme",tv=null,tb=0,ty=new Set,tw=null,tk=!1;function tj(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function tS(e){return"auto"===e?tj():e}let tC="--omp-md-";function tN(e){let t=document.documentElement,n=tv?.palettes[e];t.dataset.ompThemeMode=e,t.setAttribute("data-seed-color-mode","dark"===e?"dark-only":"light-only"),t.classList.toggle("dark","dark"===e);for(let e=t.style.length-1;e>=0;e-=1){let n=t.style.item(e);n.startsWith("--")&&!n.startsWith(tC)&&t.style.removeProperty(n)}if(n){for(let[e,r]of Object.entries(n.variables))e.startsWith(tC)&&t.style.setProperty(e,r);t.dataset.ompThemeName=n.name}try{localStorage.setItem(tx,e)}catch{}}function tI(){if(tw)return tw;let e=function(){try{let e=localStorage.getItem(tm);if("light"===e||"dark"===e||"auto"===e)return e;let t=localStorage.getItem(tx);if("light"===t||"dark"===t)return t}catch{}return"auto"}(),t=tS(e);return tN(t),tw={preference:e,theme:t}}function tT(e,t,n){if(tN(t),n)try{localStorage.setItem(tm,e)}catch{}tw={preference:e,theme:t},ty.forEach(e=>e())}function tM(){let e=tI();if("auto"!==e.preference)return;let t=tj();t!==e.theme&&tT("auto",t,!1)}function t$(e){return ty.add(e),tI(),tk||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",tM),window.addEventListener("focus",tM),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&tM()}),tk=!0),tM(),()=>{ty.delete(e)}}function tR(){return tI()}function tE(){return tg}async function tL(e){let t=++tb,n=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/theme${n}`,{cache:"no-store"});if(!r.ok)throw Error(`Theme request failed (${r.status})`);let i=await r.json();if(t===tb){tv=i;try{localStorage.setItem("omp-theme-config",JSON.stringify(tv))}catch{}tN(tI().theme)}}function tA(e){let t=(0,i.useSyncExternalStore)(t$,tR,tE);(0,i.useEffect)(()=>{e?.syncWithOmp&&tL(e.cwd).catch(()=>{})},[e?.cwd,e?.syncWithOmp]);let n=(0,i.useCallback)((e,t)=>{let n=tS(e),r=()=>{tT(e,n,!0)},i=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||i)return void r();let s=t?.x??window.innerWidth/2,a=t?.y??window.innerHeight/2,l=Math.hypot(Math.max(s,window.innerWidth-s),Math.max(a,window.innerHeight-a));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${s}px ${a}px)`,`circle(${l}px at ${s}px ${a}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]),r=(0,i.useCallback)(e=>{var t;let r;n((t=tI().preference,r=tf.indexOf(t),tf[(r+1)%tf.length]),e)},[n]),s=(0,i.useCallback)((e,t)=>{n(e,t)},[n]);return{theme:t.theme,preference:t.preference,toggleTheme:r,setPreference:s,isDark:"dark"===t.theme}}function tz(e){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);try{let t=document.createElement("textarea");return t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),Promise.resolve()}catch{return Promise.reject()}}function tW({code:e,isStreaming:t,defaultPreview:s=!1}){let{isDark:a}=tA(),{t:l}=(0,R.s)(),[o,d]=(0,i.useState)(s),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),m=`${a?"dark":"light"}
|
|
4
|
-
${e}`,f=o&&!t;(0,i.useEffect)(()=>{if(!f)return;let t=!1;return u({key:m,status:"loading"}),(async()=>{let{default:r}=await Promise.all([n.e(866),n.e(8367),n.e(3308)]).then(n.bind(n,43328));if(r.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:a?"dark":"default"}),!await r.parse(e,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let i="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,s=await r.render(i,e);t||u({key:m,status:"ready",svg:s.svg})})().catch(()=>{t||u({key:m,status:"error"})}),()=>{t=!0}},[e,m,a,f]);let g=(0,i.useMemo)(()=>(0,r.jsx)("button",{type:"button",onClick:()=>d(e=>!e),disabled:t,title:t?l("i18n.previewAfterStreaming"):f?l("i18n.showMermaidSource"):l("i18n.previewMermaid"),className:["markdown-code-action",f?"is-active":""].filter(Boolean).join(" "),children:f?l("i18n.source"):l("i18n.preview")}),[t,f,l]);if(!f)return(0,r.jsx)(tP,{code:e,lang:"mermaid",headerAction:g,isStreaming:t});let x=c?.key===m&&"error"===c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:l("i18n.invalidMermaid")}):c?.key!==m||"ready"!==c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":l("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!p&&(0,r.jsx)("button",{type:"button",className:"mermaid-block mermaid-preview-button",title:l("i18n.openMermaidViewer"),"aria-label":l("i18n.openMermaidViewer"),onClick:()=>h(!0),dangerouslySetInnerHTML:{__html:c.svg}}),p&&(0,r.jsx)(tF,{svg:c.svg,onClose:()=>h(!1)})]});return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:"mermaid"}),g]}),x]})}function tF({svg:e,onClose:t}){let{t:n}=(0,R.s)(),s=(0,i.useRef)(null),[a,l]=(0,i.useState)(1);return(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,r.jsx)("dialog",{ref:s,className:"mermaid-zoom-dialog","aria-label":n("i18n.mermaidViewer"),onCancel:e=>{e.preventDefault(),t()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),t())},children:(0,r.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,r.jsx)("span",{className:"mermaid-zoom-title",children:n("i18n.mermaidDiagram")}),(0,r.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>Math.max(.5,e-.25)),disabled:a<=.5,title:n("i18n.zoomOut"),"aria-label":n("i18n.zoomOut"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 12h14"})})}),(0,r.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*a),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>Math.min(3,e+.25)),disabled:a>=3,title:n("i18n.zoomIn"),"aria-label":n("i18n.zoomIn"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>l(1),title:n("i18n.fitToWidth"),"aria-label":n("i18n.fitToWidth"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M8 3H3v5M16 3h5v5M8 21H3v-5M16 21h5v-5"})})}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:t,title:n("i18n.close"),"aria-label":n("i18n.close"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]}),(0,r.jsx)("div",{className:"mermaid-zoom-viewport",onClick:e=>{e.target===e.currentTarget&&t()},children:(0,r.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*a}%`},dangerouslySetInnerHTML:{__html:e}})})]})})}let tP=(0,i.memo)(function({code:e,lang:t,headerAction:n,isStreaming:s}){let{isDark:a}=tA(),{t:l}=(0,R.s)(),[o,d]=(0,i.useState)(!1);return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:t||"text"}),(0,r.jsxs)("div",{className:"markdown-code-actions",children:[n,(0,r.jsx)("button",{onClick:()=>{tz(e).then(()=>{d(!0),setTimeout(()=>d(!1),1500)})},className:"markdown-code-action",children:l(o?"i18n.copied":"i18n.copy")})]})]}),s?(0,r.jsx)("pre",{style:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,overflowX:"auto",background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},children:(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:e})}):(0,r.jsx)(e1.A,{language:t||"text",style:a?e2.xJ:e2.vs,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-dim)",fontStyle:"normal"},customStyle:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,borderRadius:0,background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e})]})});function tD({children:e,className:t,isStreaming:n,cwd:s,onOpenFile:a}){let l=(0,i.useMemo)(()=>ta(e),[e]),o=(0,i.useMemo)(()=>({code({className:e,children:t,...i}){let s=e?.replace("language-","").toLowerCase()??"",a=String(t);return e?.includes("language-")||a.includes("\n")?"mermaid"===s?(0,r.jsx)(tW,{code:a.replace(/\n$/,""),isStreaming:n}):(0,r.jsx)(tP,{code:a.replace(/\n$/,""),lang:s,isStreaming:n}):(0,r.jsx)("code",{className:"markdown-inline-code",...i,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:t,...n}){delete n.node;let i=a?eX(e,s):null;return i&&a?(0,r.jsx)("a",{href:e,...n,onClick:e=>{if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),a(i))},children:t}):(0,r.jsx)("a",{href:e,...n,target:"_blank",rel:"noopener noreferrer",children:t})},img({src:e,alt:t,...n}){delete n.node;let i="string"==typeof e?eX(e,s):null,a=i?`/api/files/${e8(i)}?type=read`:e;return(0,r.jsx)("img",{src:a,alt:t??"",loading:"lazy",...n})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})}),[s,n,a]);return(0,r.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,r.jsx)(e4.oz,{remarkPlugins:tc,rehypePlugins:tp,components:o,children:l})})}let t_=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,tO=/(?:\r?\n){2,}((?:[ \t]*<(?:read-files|modified-files)>[ \t]*\r?\n[\s\S]*?\r?\n[ \t]*<\/(?:read-files|modified-files)>[ \t]*(?:\r?\n)?)+)\s*$/;function tH(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let tB={hideThinkingBlock:!1},tU=new Set,tq=tB,tV=0;function tK(e){return tU.add(e),()=>{tU.delete(e)}}function tJ(){return tq}function tG(){return tB}async function tY(e){let t=++tV,n=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/display-settings${n}`,{cache:"no-store"});if(!r.ok)throw Error(`Display settings request failed (${r.status})`);let i=await r.json();t!==tV||i.hideThinkingBlock!==tq.hideThinkingBlock&&(tq={hideThinkingBlock:!0===i.hideThinkingBlock},tU.forEach(e=>e()))}function tZ(){return(0,i.useSyncExternalStore)(tK,tJ,tG)}var tX=n(64178);let tQ={faces:new Map,pins:new Map},t0=[],t1=tQ,t2=null,t4=new Map,t5=new Set;function t8(e){return t5.add(e),()=>{t5.delete(e)}}function t6(e){t1=e,t5.forEach(e=>e())}function t3(e){return Number.isSafeInteger(e)&&e>0}function t7(e,t){return`${e}:${t}`}function t9(e,t,n){if(!t)return null;if(t3(n)){let e=t1.faces.get(t7(t,n));if(e)return e}let r=e?t1.pins.get(e):void 0;if(r&&r.provider===t){let e=t1.faces.get(t7(t,r.credentialId));if(e)return e}return(0,tX.e$)(t)}function ne(e,t,n){let r=!!t&&!t3(n)&&!!e;return(0,i.useEffect)(()=>{r&&e&&t&&function(e,t){let n=Date.now(),r=t1.pins.get(e);if(r&&r.provider===t&&n-r.observedAt<3e4)return;let i=`${e}\u0000${t}`,s=t4.get(i);void 0!==s&&n-s<3e4||(t4.set(i,n),(0,tX.ST)(e).then(t=>{let n=t.data;if(!n||"resolved"!==n.state)return;let{provider:r,credentialId:i}=n;if("string"!=typeof r||""===r||!t3(i))return;let s=new Map(t1.pins);s.set(e,{provider:r,credentialId:i,observedAt:Date.now()}),t6({faces:t1.faces,pins:s})}).catch(()=>{}))}(e,t)},[r,e,t]),(0,i.useSyncExternalStore)(t8,()=>t9(e,t,n),()=>null)}var nt=n(2730);let nn={ko:{"dispatch.title":"서브에이전트 {count}명","dispatch.tally":"실행 중 {running} \xb7 실행 완료 {done} \xb7 Main 수용 {accepted}","dispatch.expand":"발주 상세 펼치기","dispatch.collapse":"발주 상세 접기","dock.label":"서브에이전트","dock.running":"실행 중 {count}","dock.awaiting":"판정 대기 {count}","dock.jump":"발주 카드로 이동 — {title}","dock.openPanel":"서브에이전트 상세 열기 — {title}","run.dispatching":"발주 중","run.pending":"대기","run.running":"실행 중","run.completed":"실행 완료","run.failed":"실행 실패","run.aborted":"중단됨","run.unobserved":"실행 상태 미관측","verdict.accepted":"Main 수용","verdict.rework":"Main 재작업 요청","verdict.held":"Main 보류","verdict.none":"검수 미기록","verdict.attempt":"{attempt}차","detail.stage":"현재 단계","detail.stageNone":"기록 없음","detail.model":"모델","detail.modelNone":"미관측","detail.fallback":"대체 모델","detail.agentId":"담당 ID","detail.reason":"판정 사유","detail.source.live":"실시간 관측","detail.source.record":"세션 기록","detail.openSubagents":"서브에이전트 상세 열기","detail.openProcess":"작업 기록 열기","summary.files":"변경 파일 {count}","summary.checks":"검사 {count}","summary.checksFailed":"실패 {count}","summary.unverified":"미확인 {count}","summary.expand":"턴 요약 펼치기","summary.collapse":"턴 요약 접기","summary.heading.files":"변경 파일","summary.heading.checks":"실행한 검사","summary.heading.unverified":"미확인","summary.check.exit":"exit {code}","summary.check.error":"오류로 끝남","summary.check.unobserved":"결과 미관측","summary.u.checkFailed":"검사 실패 — {command}","summary.u.checkUnobserved":"검사 결과 미관측 — {command}","delivery.title":"보낸 입력 {count}","delivery.kind.steer":"지금 지시","delivery.kind.followUp":"완료 후 요청","delivery.stage.sending":"보내는 중","delivery.stage.accepted":"접수됨 \xb7 전달 대기","delivery.stage.delivered":"전달됨 \xb7 대화에 들어감","delivery.stage.failed":"보내지 못함 \xb7 입력창에 되돌림","delivery.stage.unconfirmed":"전달 확인 못 함 \xb7 큐에서 빠짐","delivery.images":"이미지 {count}개","delivery.showOlder":"이전 {count}개 더 보기","delivery.showRecent":"최근 {count}개만 보기","live.nativeVoice":"기본 음성"},en:{"dispatch.title":"Subagents: {count}","dispatch.tally":"{running} running \xb7 {done} finished \xb7 {accepted} accepted by Main","dispatch.expand":"Show dispatch details","dispatch.collapse":"Hide dispatch details","dock.label":"Subagents","dock.running":"{count} running","dock.awaiting":"{count} awaiting verdict","dock.jump":"Go to the dispatch card — {title}","dock.openPanel":"Open subagent details — {title}","run.dispatching":"Dispatching","run.pending":"Queued","run.running":"Running","run.completed":"Run finished","run.failed":"Run failed","run.aborted":"Stopped","run.unobserved":"Run state not observed","verdict.accepted":"Accepted by Main","verdict.rework":"Main asked for rework","verdict.held":"Held by Main","verdict.none":"No review recorded","verdict.attempt":"attempt {attempt}","detail.stage":"Current step","detail.stageNone":"Not recorded","detail.model":"Model","detail.modelNone":"Not observed","detail.fallback":"fallback","detail.agentId":"Agent ID","detail.reason":"Review note","detail.source.live":"live","detail.source.record":"session record","detail.openSubagents":"Open subagent details","detail.openProcess":"Open work log","summary.files":"{count} files changed","summary.checks":"{count} checks","summary.checksFailed":"{count} failed","summary.unverified":"{count} unverified","summary.expand":"Show turn summary","summary.collapse":"Hide turn summary","summary.heading.files":"Files changed","summary.heading.checks":"Checks run","summary.heading.unverified":"Unverified","summary.check.exit":"exit {code}","summary.check.error":"ended with an error","summary.check.unobserved":"result not observed","summary.u.checkFailed":"Check failed — {command}","summary.u.checkUnobserved":"Check result not observed — {command}","delivery.title":"{count} sent","delivery.kind.steer":"Now","delivery.kind.followUp":"After this run","delivery.stage.sending":"Sending","delivery.stage.accepted":"Received \xb7 waiting to deliver","delivery.stage.delivered":"Delivered \xb7 in the conversation","delivery.stage.failed":"Not sent \xb7 back in the composer","delivery.stage.unconfirmed":"Delivery not confirmed \xb7 left the queue","delivery.images":"{count} image(s)","delivery.showOlder":"Show {count} earlier","delivery.showRecent":"Show only the latest {count}","live.nativeVoice":"default voice"},"zh-CN":{"dispatch.title":"{count} 个子代理","dispatch.tally":"运行中 {running} \xb7 运行完成 {done} \xb7 Main 已接受 {accepted}","dispatch.expand":"展开派发详情","dispatch.collapse":"收起派发详情","dock.label":"子代理","dock.running":"运行中 {count}","dock.awaiting":"等待判定 {count}","dock.jump":"转到派发卡片 — {title}","dock.openPanel":"打开子代理详情 — {title}","run.dispatching":"派发中","run.pending":"等待中","run.running":"运行中","run.completed":"运行完成","run.failed":"运行失败","run.aborted":"已中止","run.unobserved":"未观测到运行状态","verdict.accepted":"Main 已接受","verdict.rework":"Main 要求返工","verdict.held":"Main 暂缓","verdict.none":"未记录审查","verdict.attempt":"第 {attempt} 次","detail.stage":"当前步骤","detail.stageNone":"无记录","detail.model":"模型","detail.modelNone":"未观测","detail.fallback":"备用模型","detail.agentId":"代理 ID","detail.reason":"审查说明","detail.source.live":"实时观测","detail.source.record":"会话记录","detail.openSubagents":"打开子代理详情","detail.openProcess":"打开工作记录","summary.files":"变更文件 {count}","summary.checks":"检查 {count}","summary.checksFailed":"失败 {count}","summary.unverified":"未确认 {count}","summary.expand":"展开本轮摘要","summary.collapse":"收起本轮摘要","summary.heading.files":"变更文件","summary.heading.checks":"已运行的检查","summary.heading.unverified":"未确认","summary.check.exit":"exit {code}","summary.check.error":"以错误结束","summary.check.unobserved":"未观测到结果","summary.u.checkFailed":"检查失败 — {command}","summary.u.checkUnobserved":"未观测到检查结果 — {command}","delivery.title":"已发送 {count}","delivery.kind.steer":"立即指示","delivery.kind.followUp":"完成后请求","delivery.stage.sending":"发送中","delivery.stage.accepted":"已接收 \xb7 等待送达","delivery.stage.delivered":"已送达 \xb7 已进入对话","delivery.stage.failed":"未发送 \xb7 已退回输入框","delivery.stage.unconfirmed":"未能确认送达 \xb7 已离开队列","delivery.images":"图片 {count} 张","delivery.showOlder":"显示更早的 {count} 条","delivery.showRecent":"仅显示最近 {count} 条","live.nativeVoice":"默认语音"}};function nr(){let{locale:e}=(0,R.s)();return{st:(0,i.useCallback)((t,n)=>(0,nt.u0)(e,t,nn,n),[e]),locale:e}}function ni({seed:e,size:t,provider:n}){let[s,a]=(0,i.useState)(!1),[l,o]=(0,i.useState)(!1);return s?(0,r.jsx)("span",{className:"account-avatar account-avatar-mono","data-tone":e%6,style:{width:t,height:t,fontSize:Math.round(.46*t)},"aria-hidden":"true",children:(0,tX.xl)(e).slice(0,1)}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:"account-avatar-button",style:{width:t,height:t},onClick:e=>{e.stopPropagation(),o(!0)},"aria-label":(0,tX.xl)(e),children:(0,r.jsx)("img",{className:"account-avatar",src:(0,tX.uk)(e),width:t,height:t,alt:"","aria-hidden":"true",draggable:!1,onError:()=>a(!0)})}),l&&(0,r.jsx)(ns,{seed:e,provider:n,onClose:()=>o(!1)})]})}function ns({seed:e,provider:t,onClose:n}){let{t:s}=(0,R.s)(),a=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=a.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]);let l=(0,tX.xl)(e);return(0,P.createPortal)((0,r.jsxs)("dialog",{ref:a,className:"account-avatar-dialog","aria-label":l,onCancel:e=>{e.preventDefault(),n()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),n())},onClick:e=>{e.stopPropagation(),e.target===e.currentTarget&&n()},children:[(0,r.jsx)("img",{className:"account-avatar-full",src:(0,tX.uk)(e),width:256,height:256,alt:l,draggable:!1}),(0,r.jsxs)("p",{className:"account-avatar-caption",children:[(0,r.jsx)("span",{className:"account-avatar-caption-alias",children:l}),t?(0,r.jsx)("span",{className:"account-avatar-caption-provider",children:(0,tX.bN)(t)}):null]}),(0,r.jsx)("button",{type:"button",className:"account-avatar-close",onClick:n,children:s("i18n.close")})]}),document.body)}function na(e){let t,n=[],r=null,i=0,s=0,a=0,l=0,o=[],d=[],c=()=>({lineNo:null,text:"",type:"empty"}),u=()=>{if(!r){o=[],d=[];return}let e=Math.max(o.length,d.length);for(let t=0;t<e;t++){let e=o[t]?{lineNo:o[t].lineNo,text:o[t].text,type:"removed"}:c(),n=d[t]?{lineNo:d[t].lineNo,text:d[t].text,type:"added"}:c();r.rows.push({type:"line",left:e,right:n})}o=[],d=[]};for(let c of e.split(/\r?\n/)){if(!(a>0||l>0)){if(c.startsWith("--- ")){u(),t=nl(c.slice(4));continue}if(c.startsWith("+++ ")){u(),r={oldPath:t,newPath:nl(c.slice(4)),rows:[]},n.push(r);continue}}let e=c.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){r||(r={rows:[]},n.push(r)),u(),i=Number(e[1]),s=Number(e[3]),a=void 0===e[2]?1:Number(e[2]),l=void 0===e[4]?1:Number(e[4]),r.rows.push({type:"hunk",text:c});continue}if(!r)continue;if(c.startsWith("\\ ")){u(),r.rows.push({type:"hunk",text:c});continue}let p=c[0],h=c.slice(1);" "===p?(u(),r.rows.push({type:"line",left:{lineNo:i++,text:h,type:"context"},right:{lineNo:s++,text:h,type:"context"}}),a>0&&a--,l>0&&l--):"-"===p?(o.push({lineNo:i++,text:h}),a>0&&a--):"+"===p?(d.push({lineNo:s++,text:h}),l>0&&l--):""!==c&&(u(),r.rows.push({type:"hunk",text:c}))}u();let p=n.filter(e=>e.rows.some(e=>"line"===e.type));return p.length>0?p:null}function nl(e){return e.split(" ")[0].trim()}function no({task:e}){let t="completed"===e.status,n="abandoned"===e.status,i="in_progress"===e.status,s="blocked"===e.status;return(0,r.jsxs)("div",{role:"listitem","aria-label":`${e.status}: ${e.content}`,className:`todo-checklist-row ${t?"is-completed":n?"is-abandoned":s?"is-blocked":i?"is-active":"is-pending"}`,children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-checklist-marker",children:t?"✓":n?"\xd7":s?"!":i?"›":""}),(0,r.jsxs)("span",{className:"todo-checklist-content",children:[e.content,s&&e.blocker?(0,r.jsxs)("span",{className:"todo-checklist-blocker",children:[" (",e.blocker,")"]}):null]})]})}let nd="/icons/catppuccin";function nc({name:e,size:t=14}){let n={width:t,height:t,"--catppuccin-icon-light":`url(${nd}/latte/${e}.svg)`,"--catppuccin-icon-dark":`url(${nd}/mocha/${e}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:n})}function nu({size:e=14,open:t=!1}){return(0,r.jsx)(nc,{name:t?"_folder_open":"_folder",size:e})}function np({size:e=14}){return(0,r.jsx)(nc,{name:"_file",size:e})}let nh={ts:"typescript",tsx:"typescript-react",js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"javascript-react",py:"python",json:"json",jsonl:"json",css:"css",less:"css",scss:"sass",html:"html",htm:"html",md:"markdown",markdown:"markdown",mdx:"markdown",yaml:"yaml",yml:"yaml",toml:"toml",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",rs:"rust",go:"go",sql:"database",graphql:"graphql",gql:"graphql",tf:"terraform",hcl:"terraform",docx:"ms-word",pdf:"pdf",lock:"lock"};function nm(e,t=14){let n=e.toLowerCase(),i="dockerfile"===n||n.startsWith("dockerfile.")?"docker":".env"===n||n.startsWith(".env.")?"env":[".gitignore",".gitattributes",".gitmodules"].includes(n)?"git":"package-lock.json"===n?"npm-lock":"bun.lock"===n?"bun-lock":["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"].includes(n)?"next":[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(n)?"eslint":["yarn.lock","pnpm-lock.yaml","cargo.lock"].includes(n)?"lock":n.endsWith(".config.ts")||n.endsWith(".config.js")||n.endsWith(".config.mjs")||n.endsWith(".config.cjs")?"config":void 0;if(i)return(0,r.jsx)(nc,{name:i,size:t});let s=nh[n.split(".").pop()??""];return s?(0,r.jsx)(nc,{name:s,size:t}):(0,r.jsx)(np,{size:t})}function nf({files:e,onOpenFile:t}){let{t:n}=(0,R.s)();return 0===e.length?null:(0,r.jsx)("div",{"aria-label":n("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:e.map(({filePath:e})=>{let i=e6(e);return(0,r.jsxs)("button",{type:"button",title:e,"aria-label":n("chat.openWrittenFile",{name:i}),onClick:()=>t?.(e),style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",fontSize:12,fontFamily:"var(--font-mono)",color:"var(--text)",background:"var(--bg-subtle)",border:"1px solid var(--border)",borderRadius:6,cursor:"pointer"},children:[nm(i,12),(0,r.jsx)("span",{children:i})]},e)})})}var ng=n(59959);let nx={verdicts:new Map,runs:new Map,latestByAgent:new Map};function nv(e){return Array.isArray(e)?e.filter(e=>"object"==typeof e&&null!==e):[]}function nb(e){return"string"==typeof e&&e.trim()?e:null}function ny(e){switch(e){case"pending":case"queued":return"pending";case"running":return"running";case"completed":case"success":return"completed";case"failed":case"error":return"failed";case"aborted":case"cancelled":case"canceled":return"aborted";default:return null}}function nw(e){return"string"==typeof e?e:e.map(e=>"text"===e.type?e.text:"").join("\n")}function nk(e,t){if(t?.isError)return null;let n=nv(e.input.tasks),r=nv(t?.details?.progress),i=Math.max(n.length,r.length),s=[];for(let a=0;a<i;a++){let i=r.find(e=>e.index===a)??r[a],l=n[a],o=nb(i?.id)??nb(l?.name);o&&s.push({key:`${e.toolCallId}#${a}`,toolCallId:e.toolCallId,index:a,agentId:o,agent:nb(i?.agent)??nb(l?.agent),task:nb(i?.task)??nb(l?.task)??"",spawned:!!t})}return s}let nj=/<task-result\b([^>]*)>/g,nS=/(\w+)="([^"]*)"/g;function nC(e,t,n){let r,i=t.find(t=>t.parentToolCallId?t.parentToolCallId===e.toolCallId&&t.id===e.agentId:t.id===e.agentId&&n.latestByAgent.get(e.agentId)===e.key),s=i?{key:e.key,identity:"live",live:i.assignment?i:{...i,assignment:e.task}}:{key:e.key,identity:"live",live:{id:e.agentId,index:e.index,agent:e.agent??"",agentSource:"user",status:"unknown",task:e.task,lastUpdate:0}},a=(0,ng.$V)(s),l=n.runs.get(e.key),o=null;i&&"unknown"!==i.status?(r=i.status,o="live"):l&&"unknown"!==l.status?(r=l.status,o="record"):r=e.spawned?"unobserved":"dispatching";let d=n.verdicts.get(e.key);return{member:e,title:a.title,explicitTitle:a.explicitTitle,stage:i?a.stage:null,model:i?(0,ng.A7)(s):null,run:r,runSource:o,verdict:d&&d.length>0?d[d.length-1]:null}}let nN={dispatching:"running",pending:"running",running:"running",completed:"awaiting",failed:"awaiting",aborted:"awaiting",unobserved:null},nI=(0,i.createContext)({ledger:nx,subagents:[],toolResults:new Map}),nT={dispatching:"run.dispatching",pending:"run.pending",running:"run.running",completed:"run.completed",failed:"run.failed",aborted:"run.aborted",unobserved:"run.unobserved"},nM={accepted:"verdict.accepted",rework:"verdict.rework",held:"verdict.held",none:"verdict.none"};function n$({maker:e,st:t}){let n=e.verdict?.verdict??"none",i=e.verdict?.attempt;return(0,r.jsxs)("span",{className:"answer-status-pair",children:[(0,r.jsx)("span",{className:"answer-status-run","data-state":e.run,children:t(nT[e.run])}),(0,r.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→"}),(0,r.jsxs)("span",{className:"answer-status-verdict","data-verdict":n,children:[t(nM[n]),null!=i&&i>1?` \xb7 ${t("verdict.attempt",{attempt:i})}`:null]})]})}function nR({calls:e}){let{ledger:t,subagents:n,toolResults:s,onOpenPanel:a,focusedDispatch:l}=(0,i.useContext)(nI),{st:o}=nr(),[d,c]=(0,i.useState)(!1),u=(0,i.useId)(),p=(0,i.useMemo)(()=>e.flatMap(e=>nk(e,s.get(e.toolCallId))??[]).map(e=>nC(e,n,t)),[e,s,n,t]);if(0===p.length)return null;let h=0,m=0,f=0;for(let e of p)("dispatching"===e.run||"pending"===e.run||"running"===e.run)&&(h+=1),"completed"===e.run&&(m+=1),e.verdict?.verdict==="accepted"&&(f+=1);return(0,r.jsxs)("section",{className:l&&p.some(e=>e.member.key===l)?"answer-dispatch answer-dispatch-flash":"answer-dispatch","aria-label":o("dispatch.title",{count:p.length}),children:[(0,r.jsxs)("button",{type:"button",className:"answer-dispatch-toggle","aria-expanded":d,"aria-controls":u,title:o(d?"dispatch.collapse":"dispatch.expand"),onClick:()=>c(e=>!e),children:[(0,r.jsx)("span",{className:"answer-dispatch-heading",children:o("dispatch.title",{count:p.length})}),(0,r.jsx)("span",{className:"answer-dispatch-tally",children:o("dispatch.tally",{running:h,done:m,accepted:f})}),(0,r.jsx)("svg",{className:"answer-chevron",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),(0,r.jsx)("ul",{className:"answer-dispatch-list",id:u,children:p.map(e=>(0,r.jsxs)("li",{className:"answer-dispatch-row","data-focused":e.member.key===l?"":void 0,children:[(0,r.jsxs)("div",{className:"answer-dispatch-line",children:[(0,r.jsx)("span",{className:"answer-dispatch-name",title:e.title,children:e.title}),(0,r.jsx)(n$,{maker:e,st:o})]}),d&&(0,r.jsxs)("dl",{className:"answer-dispatch-detail",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:o("detail.stage")}),(0,r.jsx)("dd",{children:e.stage??o("detail.stageNone")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:o("detail.model")}),(0,r.jsx)("dd",{title:e.model?.model??void 0,children:e.model?.modelShort?`${e.model.modelShort}${e.model.effort?` \xb7 ${e.model.effort}`:""}${e.model.modelIsFallback?` \xb7 ${o("detail.fallback")}`:""}`:o("detail.modelNone")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:o("detail.agentId")}),(0,r.jsxs)("dd",{children:[(0,r.jsx)("span",{className:"answer-mono",children:e.member.agentId}),e.runSource?` \xb7 ${o("live"===e.runSource?"detail.source.live":"detail.source.record")}`:""]})]}),e.verdict?.reason&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:o("detail.reason")}),(0,r.jsx)("dd",{children:e.verdict.reason})]})]})]},e.member.key))}),d&&a&&(0,r.jsxs)("div",{className:"answer-dispatch-links",children:[(0,r.jsx)("button",{type:"button",className:"answer-link",onClick:()=>a("subagents"),children:o("detail.openSubagents")}),(0,r.jsx)("button",{type:"button",className:"answer-link",onClick:()=>a("process"),children:o("detail.openProcess")})]})]})}function nE({summary:e,onOpenFile:t}){let{ledger:n,subagents:s,toolResults:a}=(0,i.useContext)(nI),{st:l}=nr(),[o,d]=(0,i.useState)(!1),c=(0,i.useId)(),u=(0,i.useMemo)(()=>e.dispatchCalls.flatMap(e=>nk(e,a.get(e.toolCallId))??[]).map(e=>nC(e,s,n)),[e.dispatchCalls,a,s,n]),p=e.checks.filter(e=>"failed"===e.state),h=e.checks.filter(e=>"passed"!==e.state),m=u.filter(e=>"failed"===e.run||"aborted"===e.run||"unobserved"===e.run||e.verdict?.verdict!=="accepted"),f=h.length+m.length;if(0===e.files.length&&0===e.checks.length&&0===u.length)return null;let g=[l("summary.files",{count:e.files.length}),l("summary.checks",{count:e.checks.length})];return p.length>0&&g.push(l("summary.checksFailed",{count:p.length})),f>0&&g.push(l("summary.unverified",{count:f})),(0,r.jsxs)("div",{className:"answer-summary",children:[(0,r.jsxs)("button",{type:"button",className:"answer-summary-toggle","aria-expanded":o,"aria-controls":c,title:l(o?"summary.collapse":"summary.expand"),onClick:()=>d(e=>!e),children:[(0,r.jsx)("span",{className:"answer-summary-text","data-unverified":f>0?"":void 0,children:g.join(" \xb7 ")}),(0,r.jsx)("svg",{className:"answer-chevron",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),o&&(0,r.jsxs)("div",{className:"answer-summary-body",id:c,children:[e.files.length>0&&(0,r.jsxs)("section",{children:[(0,r.jsx)("h4",{className:"answer-summary-heading",children:l("summary.heading.files")}),(0,r.jsx)(nf,{files:e.files,onOpenFile:t})]}),e.checks.length>0&&(0,r.jsxs)("section",{children:[(0,r.jsx)("h4",{className:"answer-summary-heading",children:l("summary.heading.checks")}),(0,r.jsx)("ul",{className:"answer-summary-list",children:e.checks.map(e=>(0,r.jsxs)("li",{className:"answer-check","data-state":e.state,children:[(0,r.jsx)("code",{className:"answer-check-command",title:e.command,children:e.command}),(0,r.jsx)("span",{className:"answer-check-result",children:null!==e.exitCode?l("summary.check.exit",{code:e.exitCode}):l("failed"===e.state?"summary.check.error":"summary.check.unobserved")})]},e.toolCallId))})]}),f>0&&(0,r.jsxs)("section",{children:[(0,r.jsx)("h4",{className:"answer-summary-heading",children:l("summary.heading.unverified")}),(0,r.jsxs)("ul",{className:"answer-summary-list",children:[h.map(e=>(0,r.jsx)("li",{children:l("failed"===e.state?"summary.u.checkFailed":"summary.u.checkUnobserved",{command:e.command})},`check-${e.toolCallId}`)),m.map(e=>(0,r.jsxs)("li",{className:"answer-summary-maker",children:[(0,r.jsx)("span",{className:"answer-dispatch-name",title:e.title,children:e.title}),(0,r.jsx)(n$,{maker:e,st:l})]},`maker-${e.member.key}`))]})]})]})]})}class nL extends Error{constructor(e,t){super(t),this.code=e,this.name="DocumentAttachmentError"}}let nA={markdown:"text/markdown",text:"text/plain",pdf:"application/pdf"},nz={".txt":!0,".csv":!0,".tsv":!0,".json":!0,".log":!0},nW={"text/plain":!0,"text/csv":!0,"text/tab-separated-values":!0,"application/json":!0,"text/json":!0};function nF(e){let t=e.name.toLocaleLowerCase();if(t.endsWith(".md")||t.endsWith(".markdown"))return"markdown";if(t.endsWith(".pdf"))return"pdf";let n=t.lastIndexOf(".");if(n>0&&nz[t.slice(n)])return"text";let r=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return"text/markdown"===r?"markdown":"application/pdf"===r?"pdf":r&&nW[r]?"text":null}let nP={".mp3":"audio/mpeg",".wav":"audio/wav",".wave":"audio/wav",".m4a":"audio/mp4",".ogg":"audio/ogg",".oga":"audio/ogg",".opus":"audio/ogg",".flac":"audio/flac",".webm":"audio/webm",".aac":"audio/aac",".aif":"audio/aiff",".aiff":"audio/aiff"};function nD(e){let t=e.name.toLocaleLowerCase(),n=t.lastIndexOf("."),r=n>0?nP[t.slice(n)]:void 0;if(r)return r;let i=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return i?.startsWith("audio/")?i:null}function n_(e,t){try{let n=new TextDecoder(e,{fatal:!0}).decode(t);return n.includes("\0")?null:n}catch{return null}}function nO(e){if(!Array.isArray(e))return[];let t=[],n=0,r=0;for(let i of e){if(i&&"object"==typeof i&&"string"==typeof i.name&&i.name.length>0&&("text/markdown"===i.mimeType||"text/plain"===i.mimeType||"application/pdf"===i.mimeType)&&"number"==typeof i.size&&Number.isSafeInteger(i.size)&&i.size>=0&&i.size<=8388608&&"string"==typeof i.text&&i.text.length<=12e4){if(t.length>=3)break;!(n+i.size>0x1000000)&&(r+i.text.length>24e4||(t.push({name:i.name,mimeType:i.mimeType,size:i.size,text:i.text}),n+=i.size,r+=i.text.length))}}return t}async function nH(e){let t,n=nF(e);if(!n)throw new nL("unsupported",`Unsupported document type: ${e.name}`);if(e.size>8388608)throw new nL("file_too_large",`${e.name} exceeds the document size limit`);if("pdf"===n)t=await nY(e);else{try{t=await e.text()}catch(e){throw new nL("read_failed",e instanceof Error?e.message:String(e))}nZ(t)}return{name:e.name,mimeType:nA[n],size:e.size,text:t}}function nB(e,t){let n=nO(t);if(0===n.length)return e;let r={userMessageLength:e.length,documents:n.map(({name:e,mimeType:t,size:n,text:r})=>({name:e,mimeType:t,size:n,textLength:r.length}))},i=`${nX}${JSON.stringify(r)}${nQ}
|
|
5
|
-
${n0}${e}${n1}`;return n.forEach((e,t)=>{i+=n2(t,e),i+=e.text,i+=n4(t)}),i}function nU(e){let t;if(!e.startsWith(nX))return null;let n=e.indexOf("\n");if(n<0)return null;let r=e.slice(0,n);if(!r.endsWith(nQ))return null;try{t=JSON.parse(r.slice(nX.length,-nQ.length))}catch{return null}if(!function(e){if(!e||"object"!=typeof e||!Number.isSafeInteger(e.userMessageLength)||(e.userMessageLength??-1)<0||!Array.isArray(e.documents)||0===e.documents.length||e.documents.length>3)return!1;let t=0,n=0;for(let r of e.documents){if(!r||"object"!=typeof r||"string"!=typeof r.name||0===r.name.length||"text/markdown"!==r.mimeType&&"text/plain"!==r.mimeType&&"application/pdf"!==r.mimeType||!Number.isSafeInteger(r.size)||(r.size??-1)<0||(r.size??0)>8388608||!Number.isSafeInteger(r.textLength)||(r.textLength??-1)<0||(r.textLength??0)>12e4)return!1;t+=r.size??0,n+=r.textLength??0}return t<=0x1000000&&n<=24e4}(t))return null;let i=n+1;if(!e.startsWith(n0,i))return null;let s=(i+=n0.length)+t.userMessageLength;if(s>e.length)return null;let a=e.slice(i,s);if(i=s,!e.startsWith(n1,i))return null;i+=n1.length;let l=[];for(let n=0;n<t.documents.length;n+=1){let r=t.documents[n],s=n2(n,r);if(!e.startsWith(s,i))return null;let a=(i+=s.length)+r.textLength;if(a>e.length)return null;let o=e.slice(i,a);i=a;let d=n4(n);if(!e.startsWith(d,i))return null;i+=d.length,l.push({name:r.name,mimeType:r.mimeType,size:r.size,text:o})}return i===e.length?{message:a,documents:l}:null}function nq(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(+(e<10240))} KB`:`${(e/1048576).toFixed(1)} MB`}let nV="\n[transcript truncated to fit the attachment limit]",nK="File saved at: ";function nJ(e){return"application/pdf"===e.mimeType?"pdf":"text/markdown"===e.mimeType?"markdown":e.text.startsWith(nK)?nD({name:e.name,type:""})?"audio":"file":"text"}async function nG(e,t){let n=new FormData;n.append("file",e,e.name),t&&n.append("sessionId",t);let r=await fetch("/api/attachments",{method:"POST",body:n}),i=await r.json().catch(()=>null);if(!r.ok||"string"!=typeof i?.path||"number"!=typeof i.size||"string"!=typeof i.mimeType)throw Error("string"==typeof i?.error?i.error:`HTTP ${r.status}`);return{path:i.path,size:i.size,mimeType:i.mimeType,..."string"==typeof i.transcript?{transcript:i.transcript}:{},..."string"==typeof i.transcriptError?{transcriptError:i.transcriptError}:{}}}async function nY(e){let t;try{t=await fetch("/api/document-text",{method:"POST",headers:{"Content-Type":"application/pdf"},body:e})}catch(e){throw new nL("read_failed",e instanceof Error?e.message:String(e))}let n=await t.json().catch(()=>null);if(!t.ok){var r;throw new nL("string"==typeof n?.code&&("unsupported"===(r=n.code)||"file_too_large"===r||"text_too_large"===r||"too_many_pages"===r||"no_extractable_text"===r||"password_protected"===r||"invalid_pdf"===r||"read_failed"===r)?n.code:"invalid_pdf","string"==typeof n?.error?n.error:`Unable to read ${e.name}`)}if("string"!=typeof n?.text)throw new nL("invalid_pdf",`Unable to read ${e.name}`);return nZ(n.text),n.text}function nZ(e){if(e.length>12e4)throw new nL("text_too_large","Document exceeds the extracted text limit")}let nX="\x3c!-- omp-web-document-context-v1:",nQ=" --\x3e",n0="User message:\n",n1="\n\nAttached documents (locally extracted text supplied by the user):\n";function n2(e,t){return`
|
|
6
|
-
--- Begin attached document ${e+1}: ${JSON.stringify(t.name)} (${t.mimeType}, ${t.size} bytes) ---
|
|
7
|
-
`}function n4(e){return`
|
|
8
|
-
--- End attached document ${e+1} ---`}let n5=/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}\uac00-\ud7af]/u;function n8(e){let t=0,n=0;for(let r of e)n5.test(r)?t++:n++;return t+n/4}let n6=new Map;function n3({children:e,className:t,...n}){let{t:s}=(0,R.s)(),[a,l]=(0,i.useState)(!1);if(e.length<=1e5)return(0,r.jsx)(tD,{className:t,...n,children:e});if(!a){var o;return(0,r.jsxs)("button",{onClick:()=>l(!0),style:{display:"block",width:"100%",margin:"4px 0",padding:"7px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:["⚠ ",s("i18n.largeMessageReveal",{size:(o=e.length)>=1e6?`${(o/1e6).toFixed(1)} MB`:o>=1e3?`${Math.round(o/1e3)} KB`:`${o} B`})]})}return(0,r.jsx)("div",{className:t,style:{maxHeight:420,overflow:"auto",fontSize:12,lineHeight:1.5},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)",color:"var(--text-muted)"},children:e})})}let n7=null,n9=null,re=null;function rt(e){if(!e)return null;let t=new Date(e),n=new Date,r=t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate(),i=(n7??=new Intl.DateTimeFormat([],{hour:"2-digit",minute:"2-digit"})).format(t);if(r)return i;let s=t.getFullYear()!==n.getFullYear()?(re??=new Intl.DateTimeFormat([],{month:"short",day:"numeric",year:"numeric"})).format(t):(n9??=new Intl.DateTimeFormat([],{month:"short",day:"numeric"})).format(t);return`${s} ${i}`}let rn=(0,i.memo)(function({message:e,isStreaming:t,toolResults:n,modelNames:i,cwd:s,onOpenFile:a,entryId:l,onFork:o,forking:d,onNavigate:c,prevAssistantEntryId:u,onEditContent:p,showTimestamp:h,prevTimestamp:m,sessionId:f,writtenFiles:g,dispatchSlot:x,turnSummary:v}){return"user"===e.role?(0,r.jsx)(rr,{message:e,cwd:s,onOpenFile:a,entryId:l,onFork:o,forking:d,onNavigate:c,prevAssistantEntryId:u,onEditContent:p}):"assistant"===e.role?(0,r.jsx)(ri,{message:e,isStreaming:t,toolResults:n,modelNames:i,cwd:s,onOpenFile:a,showTimestamp:h,prevTimestamp:m,sessionId:f,entryId:l,writtenFiles:g,dispatchSlot:x,turnSummary:v}):"toolResult"===e.role?null:"custom"===e.role?"compaction"===e.customType?(0,r.jsx)(rC,{message:e}):(0,r.jsx)(rT,{message:e,cwd:s,onOpenFile:a}):"bashExecution"===e.role?(0,r.jsx)(rR,{message:e,sessionId:f}):null},(e,t)=>e.message===t.message&&e.isStreaming===t.isStreaming&&function(e,t,n){if(t===n||"assistant"!==e.role)return!0;for(let r of e.content??[])if("toolCall"===r.type&&t?.get(r.toolCallId)!==n?.get(r.toolCallId))return!1;return!0}(e.message,e.toolResults,t.toolResults)&&e.modelNames===t.modelNames&&e.cwd===t.cwd&&e.onOpenFile===t.onOpenFile&&e.entryId===t.entryId&&e.onFork===t.onFork&&e.forking===t.forking&&e.onNavigate===t.onNavigate&&e.prevAssistantEntryId===t.prevAssistantEntryId&&e.onEditContent===t.onEditContent&&e.showTimestamp===t.showTimestamp&&e.prevTimestamp===t.prevTimestamp&&e.sessionId===t.sessionId&&e.dispatchSlot===t.dispatchSlot&&e.turnSummary===t.turnSummary);function rr({message:e,cwd:t,onOpenFile:n,entryId:s,onFork:a,forking:l,onNavigate:o,prevAssistantEntryId:d,onEditContent:c}){let{t:u}=(0,R.s)(),[p,h]=(0,i.useState)(!1),[m,f]=(0,i.useState)(!1),g="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),x=nU(g),v=x?.message??g,b=x?.documents??[],y="string"==typeof e.content?[]:e.content.filter(e=>"image"===e.type),w=rt(e.timestamp),k=!!s&&!!a,j=!!d&&!!o;return(0,r.jsxs)("div",{className:"message-user",style:{marginBottom:16,display:"flex",flexDirection:"column",alignItems:"flex-end"},onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,maxWidth:"85%"},children:(0,r.jsxs)("div",{className:"message-user-bubble",style:{flex:1,minWidth:0,background:"var(--user-bg)",border:"1px solid var(--accent-line)",borderRadius:"var(--seed-radius-r3)",padding:"8px 12px",fontSize:14,lineHeight:1.6,color:"var(--text)",wordBreak:"break-word",maxHeight:300,overflowY:"auto"},children:[y.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!v},children:y.map((e,t)=>{let n=e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:"";return(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}},t)})}),b.length>0&&(0,r.jsx)("div",{role:"list","aria-label":u("chat.attachments"),style:{display:"flex",flexDirection:"column",gap:5,marginBottom:8*!!v},children:b.map((e,t)=>{var n;return(0,r.jsxs)("div",{role:"listitem",style:{display:"flex",alignItems:"center",gap:7,minWidth:0,padding:"5px 7px",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",background:"color-mix(in srgb, var(--user-bg) 70%, var(--bg-panel))"},children:[nm(e.name,14),(0,r.jsx)("span",{title:e.name,style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12},children:e.name}),(0,r.jsxs)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:[(n=nJ(e),"pdf"===n?"PDF":"markdown"===n?"Markdown":"audio"===n?u("chat.attachKindAudio"):"file"===n?u("chat.attachKindFile"):"Text")," \xb7 ",nq(e.size)]})]},`${e.name}-${t}`)})}),v&&(0,r.jsx)(n3,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:v})]})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:3},children:[(0,r.jsx)("div",{style:{display:"flex",gap:3,opacity:+!!p,pointerEvents:p?"auto":"none",transition:"opacity 0.12s"},children:(0,r.jsxs)("button",{onClick:()=>{tz(function(e){let t=nU(e);if(!t)return e;let n=t.documents.map(e=>e.name).join(", ");return t.message.trim()?`${t.message}
|
|
9
|
-
|
|
10
|
-
Attached: ${n}`:`Attached: ${n}`}(g)).then(()=>{f(!0),setTimeout(()=>f(!1),1500)})},title:u("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:m?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{m||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{m||(e.currentTarget.style.color="var(--text-dim)")},children:[m?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),m?u("i18n.copied"):u("i18n.copy")]})}),(k||j)&&(0,r.jsxs)("div",{style:{display:"flex",gap:3,opacity:p||l?1:0,pointerEvents:p||l?"auto":"none",transition:"opacity 0.12s"},children:[j&&(0,r.jsxs)("button",{onClick:()=>{o(d),c?.(e)},title:u("i18n.editFromHereTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"15 10 20 15 15 20"}),(0,r.jsx)("path",{d:"M4 4v7a4 4 0 0 0 4 4h12"})]}),u("i18n.editFromHere")]}),k&&(0,r.jsxs)("button",{onClick:()=>{a(s)},disabled:l,title:l?u("i18n.creatingSession"):u("i18n.newSessionTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:l?"var(--accent)":"var(--text-dim)",cursor:l?"not-allowed":"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{l||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{l||(e.currentTarget.style.color="var(--text-dim)")},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),l?u("i18n.creating"):u("i18n.newSession")]})]}),w&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:w})]})]})}function ri({message:e,isStreaming:t,toolResults:n,modelNames:s,cwd:a,onOpenFile:l,showTimestamp:o,prevTimestamp:d,sessionId:c,entryId:u,writtenFiles:p,dispatchSlot:h,turnSummary:m}){var f;let g,{t:x}=(0,R.s)(),{hideThinkingBlock:v}=tZ(),b=o?rt(e.timestamp):null,y=ne(c,e.provider,e.credentialId),w=e.liveSpeaker?tX.o.find(t=>t.alias===e.liveSpeaker?.alias):void 0,k=w?{seed:w.seed,alias:w.alias}:y,j=!!w&&e.liveSpeaker?.mode==="native",{st:S}=nr(),C=s?.[`${e.provider}:${e.model}`]??s?.[e.model]??e.model,N=(0,i.useMemo)(()=>(e.content??[]).map((e,t)=>({block:e,originalIndex:t})).filter(({block:e})=>!e$(e,{isStreaming:t,hideThinking:v})),[e.content,t,v]),I=(0,i.useMemo)(()=>N.map(({block:e})=>e),[N]),T=eR(e,{isStreaming:t}),[M,$]=(0,i.useState)(!1),[E,L]=(0,i.useState)(!1),[A,z]=(0,i.useState)(!1),W=(0,i.useRef)(null),[F,P]=(0,i.useState)(null),D=(0,i.useRef)(N);D.current=N;let _=(0,i.useRef)(new Map),O=(0,i.useMemo)(()=>{if(!t)return _.current=new Map,0;let e=new Map,n=0;for(let{block:t,originalIndex:r}of N){let i="text"===t.type?t.text:"thinking"===t.type?t.thinking:"toolCall"===t.type?JSON.stringify(t.input??{})??"":null;if(null===i)continue;let s=function(e,t){var n,r;if(!e||!t.startsWith(e.text))return n8(t);let i=e.tokens,s=e.text.length;return s>0&&s<t.length&&(n=e.text.charCodeAt(s-1))>=55296&&n<=56319&&(r=t.charCodeAt(s))>=56320&&r<=57343&&(i-=1/4,s--),i+n8(t.slice(s))}(_.current.get(r),i);e.set(r,{text:i,tokens:s}),n+=s}return _.current=e,n},[N,t]),H=(0,i.useRef)(O);H.current=O;let B=(0,i.useRef)(new Map),[U,q]=(0,i.useState)(new Map),V=(0,i.useMemo)(()=>{if(!e.timestamp||!d)return;let t=Math.round((e.timestamp-d)/1e3);return t>0?t:void 0},[e.timestamp,d]),K=(0,i.useMemo)(()=>(function(e,t){let n=new Map,r=e.completedAt;if(!t||!r)return n;for(let[e,i]of t){if(!i.timestamp||i.details?.executed===!1)continue;let t=Math.round((i.timestamp-r)/1e3);t>0&&n.set(e,t)}return n})(e,n),[e,n]),J=I.filter(e=>"text"===e.type).map(e=>e.text).join("\n");return((0,i.useEffect)(()=>{if(!t){let e=new Date().getTime();q(t=>{let n=new Map(t);for(let[t,r]of B.current)n.has(t)||n.set(t,Math.round((e-r)/1e3));return n}),W.current=null,P(null);return}let e=setInterval(()=>{let e=D.current,t=Date.now();e.forEach(({originalIndex:e})=>{B.current.has(e)||B.current.set(e,t)}),q(n=>{let r=!1,i=new Map(n);for(let n=0;n<e.length-1;n++){let s=e[n].originalIndex,a=e[n+1].originalIndex;if(!i.has(s)&&B.current.has(s)){let e=B.current.get(s),n=B.current.get(a)??t;i.set(s,Math.round((n-e)/1e3)),r=!0}}return r?i:n});let n=H.current;if(0===n)return;null===W.current&&(W.current=t);let r=(t-W.current)/1e3;r>.5&&P(n/r)},300);return()=>clearInterval(e)},[t]),0!==I.length||t||T)?(0,r.jsxs)("div",{className:`message-assistant${t?" is-streaming":""}`,style:{marginBottom:16},onMouseEnter:()=>$(!0),onMouseLeave:()=>$(!1),children:[(0,r.jsx)("div",{className:"message-assistant-role",style:{fontSize:11,color:"var(--text-dim)",marginBottom:2,display:"flex",alignItems:"center",gap:9,...k?{minHeight:40}:null},children:e.provider&&(0,r.jsxs)(r.Fragment,{children:[k&&(0,r.jsx)(ni,{seed:k.seed,size:40,provider:e.provider}),k&&(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:k.alias}),j&&(0,r.jsx)("span",{children:S("live.nativeVoice")}),(0,r.jsx)("span",{children:`${(0,tX.bN)(e.provider)} \xb7 ${C}`})]})}),h?.placement==="before"&&(0,r.jsx)(nR,{calls:h.calls}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:N.map(({block:e,originalIndex:i})=>(0,r.jsx)(rs,{block:e,toolResults:n,isStreaming:t,streamingDuration:U.get(i)??("thinking"===e.type?V:void 0),toolCallDurations:K,cwd:a,onOpenFile:l,sessionId:c,entryId:u,blockIndex:i},`${u??"stream"}-${i}`))}),h?.placement==="after"&&(0,r.jsx)(nR,{calls:h.calls}),T&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:8*(I.length>0),padding:"7px 10px",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",background:"var(--danger-soft)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Error: ",T]}),m?(0,r.jsx)(nE,{summary:m,onOpenFile:l}):p&&p.length>0&&(0,r.jsx)(nf,{files:p,onOpenFile:l}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:4},children:[e.usage&&!t&&(0,r.jsx)("button",{type:"button",onClick:()=>z(e=>!e),onFocus:()=>$(!0),onBlur:()=>$(!1),"aria-expanded":A,title:x("i18n.messageUsageTitle"),style:{padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:A?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:M||A?1:0,pointerEvents:M||A?"auto":"none",transition:"opacity 0.12s, color 0.12s"},children:A?(f=e.usage,g=[],f.input&&g.push(`${f.input.toLocaleString()} in`),f.output&&g.push(`${f.output.toLocaleString()} out`),f.cacheRead&&g.push(`${f.cacheRead.toLocaleString()} cache R`),f.cacheWrite&&g.push(`${f.cacheWrite.toLocaleString()} cache W`),f.cost?.total&&g.push(`$${f.cost.total.toFixed(4)}`),g.join(" \xb7 ")):x("i18n.messageUsage")}),t&&Math.round(O)>0&&(0,r.jsx)("button",{type:"button",onClick:()=>z(e=>!e),"aria-expanded":A,title:x("i18n.estimatedTokens"),style:{padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:A?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},children:A?`~${Math.round(O)}${null!==F?` \xb7 ${F.toFixed(1)} t/s`:""}`:x("i18n.messageUsage")}),J&&!t&&(0,r.jsxs)("button",{onClick:()=>{tz(J).then(()=>{L(!0),setTimeout(()=>L(!1),1500)})},title:x("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:E?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:+!!M,pointerEvents:M?"auto":"none",transition:"opacity 0.12s, color 0.12s"},onMouseEnter:e=>{E||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{E||(e.currentTarget.style.color="var(--text-dim)")},children:[E?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),x(E?"i18n.copied":"i18n.copy")]}),b&&!t&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginLeft:"auto"},children:b})]})]}):null}function rs({block:e,toolResults:t,isStreaming:n,streamingDuration:i,toolCallDurations:s,cwd:a,onOpenFile:l,sessionId:o,entryId:d,blockIndex:c}){if("text"===e.type)return(0,r.jsx)(rd,{block:e,isStreaming:n,cwd:a,onOpenFile:l});if("thinking"===e.type)return(0,r.jsx)(rc,{block:e,duration:i,sessionId:o,entryId:d,blockIndex:c});if("toolCall"===e.type){let n=t?.get(e.toolCallId),i=s?.get(e.toolCallId);return(0,r.jsx)(ru,{block:e,result:n,duration:i})}if("image"===e.type)return"image"===e.type&&"toolImage"in e?o?(0,r.jsx)(rl,{sessionId:o,toolCallId:e.toolImage.toolCallId}):null:(0,r.jsx)(ra,{block:e});return null}function ra({block:e}){let t=r$(e);return t?(0,r.jsx)("img",{src:t,alt:"",style:{maxWidth:"100%",maxHeight:420,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}}):null}function rl({sessionId:e,toolCallId:t}){let{t:n}=(0,R.s)(),[s,a]=(0,i.useState)(()=>eW.get(`${e}
|
|
11
|
-
${t}`)),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{if(void 0!==s)return;let n=!0;return(function(e,t){let n=`${e}
|
|
12
|
-
${t}`,r=eW.get(n);if(void 0!==r)return Promise.resolve(r);let i=eF.get(n);if(i)return i;let s=fetch(eA(e,t),{cache:"no-store"}).then(async e=>{if(!e.ok)return 0;let t=await e.json(),r=Number.isSafeInteger(t.count)&&t.count>=0?t.count:0;return eW.set(n,r),r}).catch(()=>0).finally(()=>eF.delete(n));return eF.set(n,s),s})(e,t).then(e=>{n&&a(e)}),()=>{n=!1}},[s,e,t]),!s)return null;let u=Array.from({length:s},(e,t)=>t).filter(e=>!d.has(e));return 0===u.length?null:(0,r.jsxs)("div",{className:"tool-image-strip","data-tool-call-id":t,children:[u.map(i=>(0,r.jsx)("button",{type:"button",className:"tool-image-thumb","aria-label":n("i18n.zoomIn"),onClick:()=>o(i),children:(0,r.jsx)("img",{src:eA(e,t,i),alt:"",loading:"lazy",draggable:!1,onError:()=>c(e=>new Set(e).add(i))})},i)),null!==l&&(0,r.jsx)(ro,{src:eA(e,t,l),onClose:()=>o(null)})]})}function ro({src:e,onClose:t}){let{t:n}=(0,R.s)(),s=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,P.createPortal)((0,r.jsxs)("dialog",{ref:s,className:"tool-image-dialog",onCancel:e=>{e.preventDefault(),t()},onClick:e=>{e.target===e.currentTarget&&t()},children:[(0,r.jsx)("img",{className:"tool-image-full",src:e,alt:"",draggable:!1}),(0,r.jsx)("button",{type:"button",className:"tool-image-close",onClick:t,children:n("i18n.close")})]}),document.body)}function rd({block:e,isStreaming:t,cwd:n,onOpenFile:i}){return(0,r.jsx)(n3,{isStreaming:t,cwd:n,onOpenFile:i,children:e.text})}function rc({block:e,duration:t,sessionId:n,entryId:s,blockIndex:a}){let{t:l}=(0,R.s)(),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!0===e.deferred),[p,h]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!e.deferred){d(null),u(!1),h(null);return}let t=!1;return n&&s?(u(!0),h(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=n6.get(r);if(i)return n6.delete(r),n6.set(r,i),i;let s=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${n}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw n6.delete(r),e});if(n6.set(r,s),n6.size>100){let e=n6.keys().next().value;e&&n6.delete(e)}return s})(n,s,a).then(e=>{t||d(e)}).catch(e=>{t||h(e instanceof Error?e.message:String(e))}).finally(()=>{t||u(!1)}),()=>{t=!0}):(u(!1),h(l("i18n.thinkingUnavailable")),()=>{t=!0})},[e.deferred,e.thinking,a,s,n,l]);let m=e.deferred?o:e.thinking,f="string"==typeof m&&m.trim().length>0;return(0,r.jsxs)("div",{className:"markdown-thinking","aria-label":l("i18n.thinking"),children:[(0,r.jsx)("div",{className:"markdown-thinking-content",children:c?(0,r.jsx)("span",{className:"markdown-thinking-status",children:l("i18n.loadingThinking")}):p?(0,r.jsx)("span",{className:"markdown-thinking-error",children:p}):f?(0,r.jsx)(tD,{className:"markdown-thinking-body",children:m}):(0,r.jsx)("span",{className:"markdown-thinking-status",children:l("chat.thinking")})}),void 0!==t&&f&&(0,r.jsxs)("span",{className:"markdown-thinking-duration",children:[t,"s"]})]})}function ru({block:e,result:t,duration:n}){let s,a=e.toolName.toLowerCase(),l="edit"===a||a.startsWith("edit_")||a.endsWith(".edit")||a.endsWith("_edit")||a.includes("str_replace")||a.includes("replace_editor"),[o,d]=(0,i.useState)(l),c=JSON.stringify(e.input,null,2),u="todo"===a||a.endsWith(".todo")||a.endsWith("_todo"),p="bash"===a||a.startsWith("bash ")||a.endsWith(".bash")||a.endsWith("_bash"),h=t&&!t.isError?function(e){let t=e.details;if(!rj(t))return null;let n="string"==typeof t.patch?t.patch:null;if(n)return{text:n};let r="string"==typeof t.diff?t.diff:null;return r?{text:r}:null}(t):null,m=u?"unknown"===(s=e0(e,t)).kind||0===s.phases.length?null:s.phases:null,f=h?h.text.split(/\r?\n/).reduce((e,t)=>(t.startsWith("+")&&!t.startsWith("+++")&&(e.added+=1),t.startsWith("-")&&!t.startsWith("---")&&(e.removed+=1),e),{added:0,removed:0}):null,g=t?t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,x=null!==g&&("(no output)"===g.trim()||""===g.trim()),v=t?.isError??!1;if(p)return(0,r.jsx)(rx,{command:rj(e.input)&&"string"==typeof e.input.command?e.input.command:"",output:g??"",pending:!t,isError:v,duration:n,local:a.includes("(local)")});if(u&&m)return(0,r.jsx)(rg,{phases:m});let b=!!(m||h),y=function(e,t){if(t){let e=t.flatMap(e=>e.tasks),n=e.filter(e=>"completed"===e.status||"abandoned"===e.status).length;return`${n}/${e.length} tasks`}return function(e){var t;let n=e.input;if(!n||"object"!=typeof n)return"";let r=Object.keys(n);if(0===r.length)return"";let i=e.toolName.toLowerCase();if(t=i,["grep","read","write","glob"].some(e=>t===e||t.endsWith(`.${e}`)||t.endsWith(`_${e}`))&&"string"==typeof n.i){let e=n.i.trim();if(e)return e.slice(0,120)}if(("eval"===i||i.endsWith(".eval")||i.endsWith("_eval"))&&"string"==typeof n.title){let e=n.title.trim();if(e)return e.slice(0,120)}if("command"in n)return String(n.command).slice(0,120);if("path"in n)return String(n.path).slice(0,120);if("file_path"in n)return String(n.file_path).slice(0,120);if("pattern"in n)return String(n.pattern).slice(0,120);if("query"in n)return String(n.query).slice(0,120);let s=r.map(e=>n[e]).find(e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e);if(void 0!==s)return String(s).slice(0,120);try{return JSON.stringify(n).slice(0,120)}catch{return r.join(", ").slice(0,120)}}(e)}(e,m);return(0,r.jsxs)("div",{className:`tool-call-card${v?" is-error":" is-success"}`,style:{borderRadius:7,overflow:"hidden",fontSize:12,border:v?"1px solid var(--danger-line)":"1px solid var(--success-line)",background:v?"var(--danger-soft)":"var(--success-soft)"},children:[(0,r.jsxs)("button",{className:"tool-call-header",onClick:()=>d(e=>!e),"aria-expanded":o,style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"6px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",minWidth:0},children:[(0,r.jsx)(rm,{toolName:e.toolName,isError:v}),(0,r.jsx)("span",{className:"tool-call-name",style:{color:v?"var(--danger)":"var(--success)",fontFamily:"var(--font-mono)",fontWeight:600,fontSize:11,flexShrink:0},children:e.toolName}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:y}),f&&(0,r.jsxs)("span",{title:`${f.added} lines added, ${f.removed} lines removed`,"aria-label":`${f.added} lines added, ${f.removed} lines removed`,style:{display:"inline-flex",alignItems:"center",gap:6,flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,fontVariantNumeric:"tabular-nums"},children:[(0,r.jsxs)("span",{style:{color:"var(--success)"},children:["+",f.added]}),(0,r.jsxs)("span",{style:{color:"var(--danger)"},children:["−",f.removed]})]}),void 0!==n&&(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:[n,"s"]}),(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:o?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),h&&(0,r.jsx)("div",{style:{maxHeight:o?560:260,overflowY:"auto",overflowX:"hidden",borderTop:"1px solid var(--success-line)"},children:(0,r.jsx)(rv,{diff:h})}),t&&v&&(0,r.jsx)(rS,{text:g??"",isEmpty:x,isError:!0}),o&&!b&&(0,r.jsx)("pre",{className:"tool-call-input",style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",background:"var(--bg-subtle)",borderTop:v?"1px solid var(--danger-line)":"1px solid var(--success-line)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:c}),o&&t&&!b&&!v&&(0,r.jsx)(rS,{text:g??"",isEmpty:x,isError:!1})]})}let rp={read:"var(--accent)",write:"var(--warning)",glob:"var(--accent-hover)",grep:"var(--accent)",edit:"var(--warning)",bash:"var(--success)",todo:"var(--warning)",eval:"var(--accent-hover)",task:"var(--accent)",browser:"var(--accent-hover)",image:"var(--success)",generic:"var(--text-dim)"};function rh(e,t){let n=e.trim().toLowerCase();return n===t||n.endsWith(`.${t}`)||n.endsWith(`_${t}`)||n.split(/[.\s:_-]+/).includes(t)}function rm({toolName:e,isError:t}){let n,i=(n=e.trim().toLowerCase()).includes("str_replace")||n.includes("replace_editor")||rh(n,"edit")?"edit":rh(n,"read")||rh(n,"cat")?"read":rh(n,"write")||rh(n,"save")?"write":rh(n,"glob")||rh(n,"find")?"glob":rh(n,"grep")||rh(n,"search")?"grep":rh(n,"bash")||rh(n,"shell")||rh(n,"exec")?"bash":rh(n,"todo")?"todo":rh(n,"eval")?"eval":rh(n,"task")||rh(n,"agent")?"task":rh(n,"browser")||rh(n,"web_search")||rh(n,"fetch")?"browser":rh(n,"image")||rh(n,"inspect_image")?"image":"generic",s=t?"var(--danger)":rp[i];return(0,r.jsx)("span",{"aria-hidden":"true","data-tool-icon":i,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0,color:s},children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.15",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)(rf,{kind:i})})})}function rf({kind:e}){switch(e){case"read":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,r.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,r.jsx)("path",{d:"M4.2 9.1c1.1-1.4 3.6-1.4 4.7 0-1.1 1.4-3.6 1.4-4.7 0Z"}),(0,r.jsx)("circle",{cx:"6.55",cy:"9.1",r:"0.7",fill:"currentColor",stroke:"none"})]});case"write":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,r.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,r.jsx)("path",{d:"M6.55 6.25v4.15m-1.7-1.55 1.7 1.7 1.7-1.7"})]});case"glob":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M1.75 4.5A1.25 1.25 0 0 1 3 3.25h2.25l1.35 1.35h4.4A1.25 1.25 0 0 1 12.25 5.85v5.1A1.25 1.25 0 0 1 11 12.2H3a1.25 1.25 0 0 1-1.25-1.25V4.5Z"}),(0,r.jsx)("path",{d:"M9 7.1v3.8M7.1 9h3.8M7.65 7.65l2.7 2.7m0-2.7-2.7 2.7"})]});case"grep":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"5.9",cy:"5.9",r:"3.25"}),(0,r.jsx)("path",{d:"m8.35 8.35 3.25 3.25"}),(0,r.jsx)("path",{d:"M4.6 5.2h2.5M4.6 6.8h1.7"})]});case"edit":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,r.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,r.jsx)("path",{d:"m4.45 10.55 4.75-4.75 1.45 1.45-4.75 4.75-1.95.5.5-1.95Z"}),(0,r.jsx)("path",{d:"m8.45 6.55 1.45 1.45"})]});case"bash":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"1.5",y:"2.1",width:"11",height:"9.8",rx:"1.3"}),(0,r.jsx)("path",{d:"m4 5.2 1.8 1.8L4 8.8M7.2 8.8h2.3"})]});case"todo":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7"}),(0,r.jsx)("path",{d:"m1.5 3.1 1 1 1.7-1.9M1.5 6.85l1 1 1.7-1.9M1.5 10.6l1 1 1.7-1.9"})]});case"eval":return(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"m5 2.5-3 4.5 3 4.5M9 2.5l3 4.5-3 4.5M7.8 2 6.2 12"})});case"task":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"3.1",cy:"3.2",r:"1.25"}),(0,r.jsx)("circle",{cx:"10.9",cy:"3.2",r:"1.25"}),(0,r.jsx)("circle",{cx:"10.9",cy:"10.8",r:"1.25"}),(0,r.jsx)("path",{d:"M4.35 3.2h2.1a2.9 2.9 0 0 1 2.9 2.9v3.45"}),(0,r.jsx)("path",{d:"M9.35 3.2h-1.1"})]});case"browser":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"5.2"}),(0,r.jsx)("path",{d:"M1.9 7h10.2M7 1.8c1.45 1.4 2.2 3.15 2.2 5.2S8.45 10.8 7 12.2C5.55 10.8 4.8 9.05 4.8 7S5.55 3.2 7 1.8Z"})]});case"image":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"1.75",y:"2.25",width:"10.5",height:"9.5",rx:"1.15"}),(0,r.jsx)("circle",{cx:"4.8",cy:"5.1",r:"1"}),(0,r.jsx)("path",{d:"m2.6 10 2.6-2.7 1.8 1.8 1.45-1.45 2.95 2.95"})]});case"generic":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"1.75",y:"2",width:"10.5",height:"10",rx:"1.3"}),(0,r.jsx)("path",{d:"M4.35 5h5.3M4.35 7.35h3.8M4.35 9.7h4.6"})]})}}function rg({phases:e}){let t=e.reduce((e,t)=>e+t.tasks.length,0),n=e.reduce((e,t)=>e+t.tasks.filter(e=>"completed"===e.status).length,0);return(0,r.jsxs)("div",{className:"todo-checklist-preview",role:"list","aria-label":`Todo ${t} tasks`,children:[(0,r.jsxs)("div",{className:"todo-checklist-header",children:[(0,r.jsxs)("svg",{className:"todo-checklist-icon",width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"}),(0,r.jsx)("path",{d:"m1.5 3.1 1 1 1.7-1.9M1.5 6.85l1 1 1.7-1.9M1.5 10.6l1 1 1.7-1.9",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]}),(0,r.jsx)("span",{className:"todo-checklist-title",children:"Todo"}),(0,r.jsxs)("span",{className:"todo-checklist-count",children:[t," ",1===t?"task":"tasks"]}),n>0&&n<t&&(0,r.jsxs)("span",{className:"todo-checklist-progress",children:[n,"/",t]})]}),(0,r.jsx)("div",{className:"todo-checklist-body",children:e.map((t,n)=>(0,r.jsxs)("div",{className:"todo-checklist-phase",children:[e.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:t.name}),t.tasks.map((e,t)=>(0,r.jsx)(no,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`))})]})}function rx({command:e,output:t,pending:n,isError:i,duration:s,local:a}){let{isDark:l}=tA(),{t:o}=(0,R.s)(),d=ew(t.split(/\r?\n/)),c=1===d.length&&""===d[0]?[]:d,u=n?o("chat.runningCommand"):i?"failed":"";return(0,r.jsxs)("div",{className:`shell-output-preview${i?" is-error":""}`,children:[(0,r.jsxs)("div",{className:"shell-command-line",children:[(0,r.jsx)("span",{className:"shell-command-prompt","aria-hidden":"true",children:"$"}),(0,r.jsx)(e1.A,{className:"shell-command-code",language:"bash",style:l?e2.xJ:e2.vs,PreTag:"span",CodeTag:"span",wrapLongLines:!0,customStyle:{flex:1,minWidth:0,margin:0,padding:0,border:"none",overflow:"visible",background:"transparent",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.55,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e||" "}),a&&(0,r.jsx)("span",{className:"shell-local-label",children:"local"})]}),(0,r.jsxs)("div",{className:"shell-output-panel",children:[(0,r.jsxs)("div",{className:"shell-output-divider",children:[(0,r.jsx)("span",{className:"shell-output-label",children:"Output"}),u&&(0,r.jsx)("span",{className:`shell-output-status${i?" is-error":n?" is-pending":""}`,children:u})]}),(0,r.jsxs)("div",{className:"shell-output-body","aria-live":n?"polite":void 0,children:[0===c.length&&!n&&(0,r.jsx)("span",{className:"shell-output-empty",children:o("i18n.noOutput")}),c.map((e,t)=>{let n=ex(e).trimStart(),s=i||/^(?:error|fatal|failed|failure|✖|x\b)/i.test(n)?"is-error":/^(?:warning|warn|!)/i.test(n)?"is-warning":/^(?:success|passed|ok\b|✓|\+)/i.test(n)?"is-success":"";return(0,r.jsxs)("div",{className:`shell-output-line ${s}`.trim(),children:[ek(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},t):(0,r.jsx)("span",{children:e.text},t)),""===e?"\xa0":null]},t)}),n&&(0,r.jsx)("span",{className:"shell-output-pending","aria-label":o("chat.runningCommand"),children:"▋"})]})]}),void 0!==s&&(0,r.jsxs)("div",{className:"shell-output-footer",children:[s,"s"]})]})}function rv({diff:e}){return(0,r.jsx)("div",{style:{borderTop:"1px solid var(--success-line)",background:"var(--bg)"},children:(0,r.jsx)(rb,{text:e.text})})}function rb({text:e}){let{t}=(0,R.s)(),n=(0,i.useMemo)(()=>na(e),[e]);if(!n)return(0,r.jsx)(rk,{text:e});let s=n.length>1;return(0,r.jsx)("div",{style:{background:"var(--bg)"},children:n.map((e,n)=>(0,r.jsxs)("div",{style:{minWidth:0,borderTop:0===n?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55},children:[s&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)(ry,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,r.jsx)(ry,{title:e.newPath||t("i18n.after"),side:"right"})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)"},children:e.rows.map((e,t)=>"hunk"===e.type?null:(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)(rw,{cell:e.left,side:"left"}),(0,r.jsx)(rw,{cell:e.right,side:"right"})]},t))})]},n))})}function ry({title:e,side:t}){return(0,r.jsx)("div",{title:e,style:{padding:"5px 10px",color:"var(--text-dim)",borderRight:"left"===t?"1px solid var(--border)":"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})}function rw({cell:e,side:t}){let n="added"===e.type?"var(--success-soft)":"removed"===e.type?"var(--danger-soft)":"empty"===e.type?"var(--bg-subtle)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",s="added"===e.type?"var(--success)":"removed"===e.type?"var(--danger)":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",minWidth:0,background:n,borderRight:"left"===t?"1px solid var(--border)":"none"},children:[(0,r.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",flexShrink:0},children:e.lineNo??""}),(0,r.jsx)("span",{style:{width:18,padding:"0 5px",color:s,userSelect:"none",fontWeight:"context"===e.type||"empty"===e.type?400:700,flexShrink:0},children:i}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===e.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:e.text||"\xa0"})]})}function rk({text:e}){let t=e.split(/\r?\n/);return(0,r.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55,minWidth:0},children:t.map((e,t)=>{let n=e.startsWith("@@")?"hunk":e.startsWith("+")&&!e.startsWith("+++")?"added":e.startsWith("-")&&!e.startsWith("---")?"removed":"context";return(0,r.jsxs)("div",{style:{display:"flex",background:"added"===n?"var(--success-soft)":"removed"===n?"var(--danger-soft)":"hunk"===n?"var(--accent-soft)":"transparent",borderLeft:"added"===n?"3px solid var(--success)":"removed"===n?"3px solid var(--danger)":"hunk"===n?"3px solid var(--accent)":"3px solid transparent"},children:[(0,r.jsx)("span",{style:{width:48,padding:"0 8px",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",textAlign:"right",userSelect:"none",flexShrink:0},children:t+1}),(0,r.jsx)("span",{style:{padding:"0 10px",whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:"added"===n?"var(--success)":"removed"===n?"var(--danger)":"hunk"===n?"var(--accent)":"var(--text)"},children:e||"\xa0"})]},t)})})}function rj(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function rS({text:e,isEmpty:t,isError:n}){let{t:i}=(0,R.s)();return(0,r.jsx)("div",{style:{borderTop:`1px solid ${n?"var(--danger-line)":"var(--success-line)"}`,background:n?"var(--danger-soft)":"var(--bg-subtle)"},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:n?"var(--danger)":t?"var(--text-dim)":"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",maxHeight:400,background:"var(--bg)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontStyle:t?"italic":"normal",opacity:t?.6:1},children:t?i("i18n.noOutput"):e})})}function rC({message:e}){let{t}=(0,R.s)(),n=rM(e.content),s=(0,i.useMemo)(()=>{let e,t,r,i,s;return e=[],t=[],r=n.match(tO),i=r?.[1]??"",s=r?.index===void 0?n:n.slice(0,r.index),i.replace(t_,(n,r,i)=>{let s=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...s):t.push(...s),""}),{body:s.trim(),readFiles:e,modifiedFiles:t}},[n]),a=rt(e.timestamp),l=e.details&&"object"==typeof e.details&&"tokensBefore"in e.details&&"number"==typeof e.details.tokensBefore&&e.details.tokensBefore>0?e.details.tokensBefore:null;return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:"compaction"}),null!==l&&(0,r.jsx)("span",{style:{fontSize:11},children:t("chat.compactedFrom",{tokens:tH(l)})}),a&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:a})]}),(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:15,fontWeight:700,lineHeight:1.35},children:t("i18n.conversationCompacted")}),(0,r.jsx)("div",{style:{marginTop:3,marginBottom:10,color:"var(--text)",fontSize:14,lineHeight:1.5},children:t("i18n.compactionDescription")}),s.body?(0,r.jsx)(tD,{className:"markdown-compaction-message",children:s.body}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:t("i18n.noSummary")}),(0,r.jsx)(rN,{readFiles:s.readFiles,modifiedFiles:s.modifiedFiles})]})]})})}function rN({readFiles:e,modifiedFiles:t}){let{t:n}=(0,R.s)();if(0===e.length+t.length)return null;let i=[];return e.length>0&&i.push(`${e.length} read`),t.length>0&&i.push(`${t.length} modified`),(0,r.jsxs)("details",{className:"compaction-file-details",children:[(0,r.jsx)("summary",{children:n("i18n.fileContext",{details:i.join(", ")})}),t.length>0&&(0,r.jsx)(rI,{title:n("i18n.modifiedFiles"),files:t}),e.length>0&&(0,r.jsx)(rI,{title:n("i18n.readFiles"),files:e})]})}function rI({title:e,files:t}){return(0,r.jsxs)("div",{className:"compaction-file-section",children:[(0,r.jsx)("div",{className:"compaction-file-title",children:e}),(0,r.jsx)("ul",{className:"compaction-file-list",children:t.map(e=>(0,r.jsx)("li",{children:e},e))})]})}function rT({message:e,cwd:t,onOpenFile:n}){var s;let a,{t:l}=(0,R.s)(),o=!1===e.display,[d,c]=(0,i.useState)(!o),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(!1),f=rM(e.content),g="string"==typeof(s=e.content)?[]:s.filter(e=>"image"===e.type),x=void 0!==e.details,v=x?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(e.details):"",b=e.customType||"extension",y=rt(e.timestamp);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:o?"var(--bg-subtle)":"var(--bg)",opacity:o&&!d?.82:1},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:b}),o&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:l("i18n.hiddenExtensionMessage")}),y&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:y})]}),d?(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[g.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!f},children:g.map((e,t)=>{let n=r$(e);return n?(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}},t):null})}),f?(0,r.jsx)(tD,{className:"markdown-custom-message",cwd:t,onOpenFile:n,children:f}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:l("i18n.noMessage")})]}):(0,r.jsx)("button",{onClick:()=>c(!0),style:{display:"block",width:"100%",padding:"8px 10px",border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:12,textAlign:"left"},children:f?(a=f.replace(/\s+/g," ").trim())?a.length>140?`${a.slice(0,140)}...`:a:"Show extension message":l("i18n.showExtensionMessage")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[f||v?(0,r.jsx)("button",{onClick:()=>{tz(f||v).then(()=>{m(!0),setTimeout(()=>m(!1),1500)})},style:{padding:"3px 7px",border:"none",background:"none",color:h?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:l(h?"i18n.copied":"i18n.copy")}):null,(x||o)&&(0,r.jsx)("button",{onClick:()=>{o?c(e=>!e):p(e=>!e)},style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:l(o?d?"i18n.collapse":"i18n.expand":u?"i18n.hideDetails":"i18n.showDetails")})]}),x&&(o&&d||!o&&u)&&(0,r.jsx)("pre",{style:{margin:0,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto",fontFamily:"var(--font-mono)"},children:v})]})})}function rM(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function r$(e){return e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:""}function rR({message:e,sessionId:t}){let[n,s]=(0,i.useState)(null),[a,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(null),c=!e.output&&void 0===e.exitCode&&!e.cancelled,u=e.cancelled||void 0!==e.exitCode&&0!==e.exitCode,p=t&&e.fullOutputPath?`/api/agent/${encodeURIComponent(t)}/bash-output?path=${encodeURIComponent(e.fullOutputPath)}`:null,h=e.truncated&&p&&null===n,m=n??e.output;async function f(){if(p){l(!0),d(null);try{let e=await fetch(p),t=await e.json();t.success?s(t.data?.output??""):d(t.error??"failed")}catch(e){d(String(e))}finally{l(!1)}}}let g=e.excludeFromContext?"bash (local)":"bash",x={type:"toolCall",toolCallId:`bash-${e.timestamp??""}`,toolName:g,input:{command:e.command}},v=c?void 0:{role:"toolResult",toolCallId:x.toolCallId,toolName:g,content:m?[{type:"text",text:m}]:[],isError:u,timestamp:e.timestamp};return(0,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(ru,{block:x,result:v}),e.truncated&&p&&(0,r.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[h&&(0,r.jsx)("button",{onClick:f,disabled:a,style:{background:"none",border:"none",color:"var(--accent)",cursor:a?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:a?"loading…":"view full output"}),(0,r.jsx)("a",{href:`${p}&download=1`,style:{marginLeft:10*!!h,color:"var(--accent)",fontSize:11,textDecoration:"underline"},children:"download full output"}),o&&(0,r.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:["(",o,")"]})]})]})}function rE({summary:e,onJump:t,onOpenPanel:n}){let{st:i}=nr();if(!e)return null;let{target:s}=e,a=s.position;if(null===a&&!n)return null;let l=i(null!==a?"dock.jump":"dock.openPanel",{title:s.maker.title});return(0,r.jsxs)("button",{type:"button",className:"run-status-line answer-dock-line","data-tone":"accent",title:l,onClick:()=>{null!==a?t(a,s.maker.member.key):n?.()},children:[(0,r.jsx)("span",{className:"run-status-label",children:i("dock.label")}),(0,r.jsxs)("span",{className:"answer-dock-counts",children:[e.running>0&&(0,r.jsx)("span",{className:"answer-dock-count","data-phase":"running",children:i("dock.running",{count:e.running})}),e.awaiting>0&&(0,r.jsx)("span",{className:"answer-dock-count","data-phase":"awaiting",children:i("dock.awaiting",{count:e.awaiting})})]}),(0,r.jsx)("span",{className:"answer-dock-title",children:s.maker.title}),(0,r.jsx)("svg",{className:"answer-dock-go",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"18 15 12 9 6 15"})})]})}n(21340);let rL=/(?:^|[^\w-])(?:tests?|typecheck|tsc|lint|eslint|vitest|jest|pytest|build|check|verify|smoke)(?![\w])/i,rA="cuelo-chat-search",rz="cuelo-chat-search-active";function rW(e,t){if("u">typeof CSS&&"highlights"in CSS){if(0===t.length||"u"<typeof Highlight)return void CSS.highlights.delete(e);CSS.highlights.set(e,new Highlight(...t))}}function rF({open:e,onClose:t,containerRef:n,index:s,renderedStart:a,renderedEnd:l,contentKey:o,onReveal:d,onProgrammaticScroll:c,focusRequest:u,t:p}){let h=(0,i.useRef)(null),[m,f]=(0,i.useState)(""),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)({index:-1,total:0}),y=(0,i.useDeferredValue)(m),w=e?y.trim().toLowerCase():"",k=(0,i.useRef)(g);k.current=g;let j=(0,i.useRef)([]),S=(0,i.useRef)({key:null,needle:"",rendered:!1});(0,i.useEffect)(()=>{if(!e)return;let t=requestAnimationFrame(()=>h.current?.select());return()=>cancelAnimationFrame(t)},[e,u]),(0,i.useEffect)(()=>()=>{rW(rA,[]),rW(rz,[])},[]),(0,i.useLayoutEffect)(()=>{let t=n.current;if(!e||!w||!t){rW(rA,[]),rW(rz,[]),j.current=[],S.current={key:null,needle:"",rendered:!1},b(e=>0===e.total&&-1===e.index?e:{index:-1,total:0});return}let r=requestAnimationFrame(()=>{let e=function(e,t){let n=new Map,r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>(e.textContent??"").toLowerCase().includes(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(let e=r.nextNode();e;e=r.nextNode()){let r=e.parentElement?.closest("[data-chat-item]"),i=r?Number(r.dataset.chatItem):NaN;if(!Number.isInteger(i))continue;let s=(e.textContent??"").toLowerCase(),a=n.get(i);a||(a=[],n.set(i,a));for(let n=s.indexOf(t);-1!==n;n=s.indexOf(t,n+t.length)){let r=document.createRange();r.setStart(e,n),r.setEnd(e,n+t.length),a.push(r)}}return n}(t,w),n=new Map;for(let[t,r]of e)n.set(t,r.length);let r=function(e,t,n,r,i){let s=[];if(!t)return s;for(let a=0;a<e.length;a++){let l=a>=r&&a<i?n.get(a)??0:function(e,t){if(!t)return 0;let n=0;for(let r=e.indexOf(t);-1!==r;r=e.indexOf(t,r+t.length))n+=1;return n}(e[a],t);for(let e=0;e<l;e++)s.push({item:a,k:e})}return s}(s,w,n,a,l);j.current=r;let i=eJ(r,k.current);b(e=>e.index===i&&e.total===r.length?e:{index:i,total:r.length});let o=[];for(let t of e.values())for(let e of t)o.push(e);if(rW(rA,o),i<0){rW(rz,[]),S.current={key:null,needle:w,rendered:!1};return}let u=r[i],p=k.current;p&&p.item===u.item&&p.k===u.k||x(u);let h=u.item>=a&&u.item<l,m=S.current,f=m.needle!==w||m.key?.item!==u.item||m.key?.k!==u.k||!m.rendered&&h;if(S.current={key:u,needle:w,rendered:h},!h){rW(rz,[]),f&&d(u.item);return}let g=e.get(u.item)?.[u.k];if(rW(rz,g?[g]:[]),f)if(c(),g){let e,n;e=g.getBoundingClientRect(),n=t.getBoundingClientRect(),e.height<=0||e.top>=n.top+48&&e.bottom<=n.bottom-48||(t.scrollTop+=e.top-n.top-(t.clientHeight-e.height)/2)}else t.querySelector(`[data-chat-item="${u.item}"] > *`)?.scrollIntoView({block:"center"})});return()=>cancelAnimationFrame(r)},[e,w,s,a,l,o,g,n,d,c]);let C=(0,i.useCallback)(e=>{let t=j.current;if(0===t.length)return;let n=eJ(t,k.current);x(t[(n+e+t.length)%t.length])},[]);if(!e)return null;let N=m.trim().length>0?0===v.total?p("chat.searchNoResults"):p("chat.searchCount",{index:v.index+1,total:v.total}):"";return(0,r.jsxs)("div",{className:"chat-find-bar",role:"search","data-dismissible-layer":"",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),t())},children:[(0,r.jsx)("input",{ref:h,type:"search",value:m,onChange:e=>f(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),C(e.shiftKey?-1:1))},placeholder:p("chat.searchPlaceholder"),"aria-label":p("chat.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),(0,r.jsx)("span",{className:"chat-find-count","aria-live":"polite",children:N}),(0,r.jsx)("button",{type:"button",onClick:()=>C(-1),disabled:0===v.total,"aria-label":p("chat.searchPrevious"),title:`${p("chat.searchPrevious")} (Shift+Enter)`,children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("button",{type:"button",onClick:()=>C(1),disabled:0===v.total,"aria-label":p("chat.searchNext"),title:`${p("chat.searchNext")} (Enter)`,children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})})}),(0,r.jsx)("button",{type:"button",onClick:t,"aria-label":p("chat.searchClose"),title:`${p("chat.searchClose")} (Esc)`,children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]})}function rP({questions:e,containerRef:t,layoutKey:n,onJump:s,label:a}){let l=(0,i.useRef)(null),[o,d]=(0,i.useState)(-1),[c,u]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=setTimeout(()=>u(!0),0);return()=>clearTimeout(e)},[]);let p=c&&e.length>=2;(0,i.useEffect)(()=>{let n=t.current;if(!n||!p)return;let r=0,i=null,s=()=>{r=0,i?.[0]?.isConnected||(i=n.querySelectorAll("[data-chat-item]"));let t=n.getBoundingClientRect().top+8,s=0,a=i.length-1,l=i.length-1;for(;s<=a;){let e=s+a>>1,n=i[e].firstElementChild?.getBoundingClientRect();n&&n.bottom>t?(l=e,a=e-1):s=e+1}let o=l>=0?Number(i[l].dataset.chatItem):-1,c=-1;for(let t of e){if(t.item>o)break;c=t.item}d(c)},a=()=>{r||(r=requestAnimationFrame(s))};return r=requestAnimationFrame(s),n.addEventListener("scroll",a,{passive:!0}),()=>{n.removeEventListener("scroll",a),r&&cancelAnimationFrame(r)}},[e,p,n,t]),(0,i.useEffect)(()=>{let e=l.current,t=e?.querySelector("[aria-current='true']");if(!e||!t)return;let n=t.offsetTop-e.scrollTop;(n<0||n+t.offsetHeight>e.clientHeight)&&(e.scrollTop=t.offsetTop-(e.clientHeight-t.offsetHeight)/2)},[o]);let h=e.length,m=(0,i.useCallback)((e,t)=>{let n="ArrowUp"===e.key?t-1:"ArrowDown"===e.key?t+1:"Home"===e.key?0:"End"===e.key?h-1:null;if(null===n)return;e.preventDefault();let r=Math.max(0,Math.min(h-1,n));l.current?.querySelectorAll("button")[r]?.focus()},[h]);if(!p)return null;let f=e.some(e=>e.item===o)?o:e[0].item;return(0,r.jsx)("nav",{className:"question-rail","aria-label":a,children:(0,r.jsx)("div",{ref:l,className:"question-rail-list",children:e.map((e,t)=>(0,r.jsx)(rD,{question:e,position:t,count:h,active:e.item===o,focusable:e.item===f,onJump:s,onMoveFocus:m},e.item))})})}let rD=(0,i.memo)(function({question:e,position:t,count:n,active:i,focusable:s,onJump:a,onMoveFocus:l}){let o=e.text.length>140?`${e.text.slice(0,140)}…`:e.text;return(0,r.jsx)("button",{type:"button",className:"question-rail-tick",tabIndex:s?0:-1,"aria-current":i?"true":void 0,"aria-label":`${t+1}/${n} ${o}`,title:o,onClick:()=>a(e.item),onKeyDown:e=>l(e,t),children:(0,r.jsx)("span",{"aria-hidden":"true"})})});function r_({label:e,tone:t,children:n}){return(0,r.jsxs)("div",{className:"run-status-line","data-tone":t,role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{className:"run-status-label",children:e}),(0,r.jsx)("span",{className:"run-status-text",children:n})]})}let rO={manual:!0,threshold:!0,overflow:!0,idle:!0,incomplete:!0};function rH({compaction:e,t}){let[n,s]=(0,i.useState)(()=>Date.now());if((0,i.useEffect)(()=>{if(!e)return;s(Date.now());let t=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(t)},[e]),!e)return null;let a=Math.max(0,Math.floor((n-e.startedAt)/1e3)),l=e.reason&&!0===rO[e.reason]?t(`chat.compactionReason.${e.reason}`):null;return(0,r.jsxs)(r_,{label:t("chat.compactionLabel"),tone:"accent",children:[t("chat.compactionProgress",{seconds:a}),l?` \xb7 ${l}`:""]})}function rB({onDismiss:e,t}){return(0,r.jsxs)("div",{className:"interrupted-run-notice",role:"status",children:[(0,r.jsx)("span",{className:"interrupted-run-mark","aria-hidden":"true"}),(0,r.jsxs)("span",{className:"interrupted-run-text",children:[(0,r.jsx)("strong",{children:t("chat.interruptedTitle")}),(0,r.jsx)("span",{children:t("chat.interruptedDetail")})]}),(0,r.jsx)("button",{type:"button",onClick:e,"aria-label":t("chat.interruptedDismiss"),title:t("chat.interruptedDismiss"),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]})}var rU=n(39092),rq=n.n(rU);let rV=["YUKI(유키)","ISANA(이사나)","MIO(미오)","RIN(린)","NOVA(노바)","SHION(시온)","HIKARI(히카리)"],rK={"YUKI(유키)":"yuki","ISANA(이사나)":"isana","MIO(미오)":"mio","RIN(린)":"rin","NOVA(노바)":"nova","SHION(시온)":"shion","HIKARI(히카리)":"hikari"},rJ=["approval","choice","done","failed","blocked","working"],rG={approval:"부름",choice:"물음",done:"기쁨",failed:"사과",blocked:"난처",working:"시작"},rY={approval:!1,choice:!1,done:!1,failed:!1,blocked:!1,working:!0};function rZ(e){switch(e){case"completed":return"done";case"failed":return"failed";case"aborted":return null;default:return"neutral"}}function rX(e){return void 0===e?"done":"string"==typeof e&&Object.hasOwn(rG,e)?e:null}function rQ(e,t){let n=new Map,r=new Map;if(!Array.isArray(e))return{files:n,lines:r};for(let i of e){if("object"!=typeof i||null===i)continue;let{file:e,tag:s,ko:a}=i;if("string"!=typeof e||""===e)continue;let l=rX(s);if(null===l)continue;let o=t+e.replace(/^\/+/,""),d=n.get(l);d?d.push(o):n.set(l,[o]),"string"==typeof a&&""!==a.trim()&&r.set(o,a.trim())}return{files:n,lines:r}}function r0(e,t,n){let r=t&&Object.hasOwn(rK,t)?rK[t]:null;return r?e.get(r)?.get(n)??null:null}async function r1(e=fetch){try{let t=await e("/audio/completion/voices.json");if(!t.ok)return new Map;return function(e){let t=new Map;if("object"!=typeof e||null===e)return t;let{characters:n}=e;if(!Array.isArray(n))return t;for(let e of n){if("object"!=typeof e||null===e)continue;let{id:n,clips:r,stickers:i,captions:s}=e;if("string"!=typeof n||""===n)continue;let a=rQ(r,"/audio/completion/"),l=rQ(i,"/stickers/"),o=function(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e){if("object"!=typeof n||null===n)continue;let{tag:e,ko:r}=n;if("string"!=typeof r||""===r.trim())continue;let i=rX(e);if(null===i)continue;let s=t.get(i);s?s.push(r.trim()):t.set(i,[r.trim()])}return t}(s),d=new Map;for(let e of rJ){let t=a.files.get(e)??[],n=new Map;for(let e of t){let t=a.lines.get(e);void 0!==t&&n.set(e,t)}d.set(e,{voices:t,stickers:l.files.get(e)??[],lines:n,captions:o.get(e)??[]})}t.set(n,d)}return t}(await t.json())}catch{return new Map}}function r2(e,t,n=Math.random){if(0===e.length)return null;if(1===e.length)return e[0];let r=null===t?-1:e.indexOf(t),i=-1===r?e.length:e.length-1,s=Math.min(i-1,Math.max(0,Math.floor(n()*i)));return e[-1!==r&&s>=r?s+1:s]}function r4(e){let t=[];if("bashExecution"!==e.role){if("string"==typeof e.content)t.push(e.content.trim());else for(let n of e.content)if("text"===n.type)t.push(n.text.trim());else if("toolCall"===n.type){let e="id"in n&&"string"==typeof n.id?n.id:"";t.push(`toolCall:${n.toolCallId||e}`)}}let n="toolResult"===e.role?e.toolCallId:"custom"===e.role?e.customType:"bashExecution"===e.role?e.command:null;return JSON.stringify([e.role,n,t.filter(Boolean)])}let r5=["01","02","03"];function r8(e,t,n){if(!e||"streaming"===t||!rV.includes(e))return null;let r="failed"===t?"failed":"done",i=e.slice(0,e.indexOf("(")).toLowerCase(),s=r2(r5.map(e=>`/stickers/${i}/${r}/${e}.webp`),null,()=>(function(e){let t=0x811c9dc5;for(let n=0;n<e.length;n+=1)t=Math.imul(t^e.charCodeAt(n),0x1000193);return(t>>>0)/0x100000000})(n));return s?{src:s,alt:rG[r]}:null}let r6=new Map,r3=(0,i.createContext)(r6);function r7({utterances:e,children:t}){return(0,r.jsx)(r3.Provider,{value:e,children:t})}function r9({turnIndex:e,turnEntryId:t,sessionId:n,cwd:s,onOpenFile:a}){let l=(0,i.useContext)(r3).get(e);return l&&0!==l.length?(0,r.jsx)("div",{className:"inline-utterance-thread","data-turn":e,"data-turn-entry":t,style:{display:"contents"},children:l.map(e=>(0,r.jsx)(ie,{utterance:e,sessionId:n,cwd:s,onOpenFile:a},e.key))}):null}function ie({utterance:e,sessionId:t,cwd:n,onOpenFile:s}){let a=ne(null===e.accountSessionId?void 0:e.accountSessionId??t,e.provider,e.credentialId),[l,o]=(0,i.useState)(!1),[d,c]=(0,i.useState)(!1),u=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=u.current;e&&!l&&c(e.scrollHeight>e.clientHeight+1)},[e.text,l]);let p=e.text.trim().length>0,h=e.label?.trim(),m=a?.alias??h??(0,tX.bN)(e.provider),f=a?.alias.split("(",1)[0]?.trim(),g=a&&h&&h!==a.alias&&h!==f?`작업 \xb7 ${h}`:null,x=r8(a?.alias,e.status,e.key),v="failed"===e.status?"중단됨":"streaming"===e.status&&p?"작업 중":null;return(0,r.jsxs)("div",{className:"inline-utterance","data-status":e.status,style:{marginBottom:16},children:[(0,r.jsxs)("div",{className:"inline-utterance-role",style:{display:"flex",alignItems:"center",gap:9,marginBottom:2,fontSize:11,color:"var(--text-dim)",...a?{minHeight:40}:null},children:[a&&(0,r.jsx)(ni,{seed:a.seed,size:40,provider:e.provider}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:m}),v&&(0,r.jsx)("span",{style:{color:"failed"===e.status?"var(--danger)":"var(--text-dim)"},children:v})]}),g&&(0,r.jsx)("div",{style:{marginTop:1,fontSize:11,lineHeight:1.35,color:"var(--text-muted)",overflowWrap:"anywhere"},children:g})]})]}),p?(0,r.jsx)("div",{ref:u,style:{fontSize:12.5,lineHeight:1.6,...l?null:{maxHeight:240,overflow:"hidden"}},children:(0,r.jsx)(tD,{isStreaming:"streaming"===e.status,cwd:n,onOpenFile:s,children:e.text})}):(0,r.jsx)("div",{role:"status",style:{color:"var(--text-muted)",fontSize:11.5,lineHeight:1.6},children:"failed"===e.status?"발화 없이 중단되었습니다":"아직 발화가 없습니다"}),p&&(d||l)&&(0,r.jsx)("button",{type:"button",onClick:()=>o(e=>!e),"aria-expanded":l,style:{marginTop:4,padding:"3px 9px",height:22,border:"1px solid var(--border)",borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:l?"접기":"더보기"}),x&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("img",{src:x.src,alt:x.alt,style:{display:"block",width:"min(148px, 34vw)",maxWidth:"100%",height:"auto"},className:"jsx-8e1a78d1ba768be9 inline-utterance-sticker"}),(0,r.jsx)(rq(),{id:"8e1a78d1ba768be9",children:".inline-utterance-sticker{transform-origin:center 75%;animation:inline-utterance-sticker-pop 200ms cubic-bezier(0,0,.15,1)both}@keyframes inline-utterance-sticker-pop{from{opacity:0;transform:scale(.88)}to{opacity:1;transform:scale(1)}}@media(prefers-reduced-motion:reduce){.inline-utterance-sticker{animation:none}}"})]})]})}let it=/^\[character-summon alias="([^"\r\n]+)" model="([^"\r\n]+)"(?: oauth-position="\d+")?\]\r?$/mu;function ir(e,t,n,r){if("string"!=typeof n)return[];let i=it.exec(n),s=i?.[1],a=i?.[2];return s&&a?[{toolCallId:e,...t?{name:t}:{},alias:s,model:a,batchSize:r}]:[]}function ii(e){if(!e||"assistant"!==e.role)return[];let t=[];for(let n of e.content??[]){if("toolCall"!==n.type||"task"!==n.toolName)continue;let e=n.input,r=+(void 0!==e.task)+(Array.isArray(e.tasks)?e.tasks.length:0);if(t.push(...ir(n.toolCallId,"string"==typeof e.name?e.name:void 0,e.task,r)),Array.isArray(e.tasks))for(let i of e.tasks)!i||"object"!=typeof i||Array.isArray(i)||t.push(...ir(n.toolCallId,"name"in i&&"string"==typeof i.name?i.name:void 0,"task"in i?i.task:void 0,r))}return t}function is(e){if(!e||"assistant"!==e.role)return[];let t=[];for(let n of e.content??[])"toolCall"===n.type&&"task"===n.toolName&&t.push(n.toolCallId);return t}let ia=/^agent:\/\/([^/?#]+)\/?$/i;function il(e,t){if(!e||"assistant"!==e.role)return[];let n=[];for(let r of e.content??[]){if("toolCall"!==r.type||"write"!==r.toolName)continue;let e=r.input,i="string"==typeof e.path?ia.exec(e.path):null,s=i?.[1],a=e.content;if(!s||"string"!=typeof a)continue;let l=t?.get(r.toolCallId);n.push({toolCallId:r.toolCallId,to:s,message:a,...l?.from?{from:l.from}:{},...l?.receipts?{receipts:l.receipts}:{}})}return n}var io=n(75514);let id=["greeting","utterance","message","text"],ic=function(e){let t=(0,i.useMemo)(()=>(0,ng.Et)(),[]),n=function(e,t){let[n,r]=(0,i.useState)(null);return(0,i.useEffect)(()=>{if(!t)return void r(null);let n=!1,i=new AbortController;return r(null),e.getArchive(t,i.signal).then(e=>{n||r(e)}).catch(()=>{}),()=>{n=!0,i.abort()}},[e,t]),n}(t,e.sessionId),r=(0,i.useMemo)(()=>{let t=new Set(e.subagents.map(e=>e.id)),r=[];if(n&&n.sessionId===e.sessionId){let i=e.turns.flatMap(e=>e.characterSummons);for(let s of n.subagents){if(t.has(s.name))continue;let n=[...i].reverse().find(e=>e.name===s.name);n&&r.push(function(e,t,n){let r=e.status??"unknown",i={id:e.name,index:n,agent:"",agentSource:"bundled",status:r,task:e.firstTask||void 0,lastUpdate:e.modified,parentToolCallId:t.toolCallId},s="string"==typeof e.model&&e.model.trim()?e.model.trim():void 0,a="string"==typeof e.errorMessage&&e.errorMessage.trim()?e.errorMessage.trim():void 0;return(void 0!==s||void 0!==a)&&(i.progress={index:n,id:e.name,agent:"",status:r,task:e.firstTask,recentTools:[],recentOutput:[],toolCount:0,requests:0,tokens:0,cost:0,durationMs:0,...void 0!==s?{resolvedModel:s,resolvedModelIsFallback:!0===e.modelIsFallback}:{},...void 0!==a?{retryFailure:{attempt:0,errorMessage:a}}:{}}),i}(s,n,e.subagents.length+r.length))}}return function(e,t){let n=new Map;for(let t of e)for(let e of t.characterSummons){let r=n.get(e.toolCallId)??{turnIndex:t.index,requests:[]};r.requests.push(e),n.set(e.toolCallId,r)}return t.flatMap(t=>{let r=t.parentToolCallId?n.get(t.parentToolCallId):void 0;if(!r)return[];let i=r.requests.filter(e=>e.name),s="string"==typeof t.task?it.exec(t.task):null,a=s?.[1],l=s?.[2],o=i.find(e=>e.name===t.id)??(a&&l?r.requests.find(e=>e.alias===a&&e.model===l):void 0)??(1===r.requests.length&&1===r.requests[0].batchSize?r.requests[0]:void 0);if(!o)return[];let d=e.flatMap(e=>e.peerSends.filter(e=>e.to===t.id||"all"===e.to).map(t=>({turnIndex:e.index,send:t})));return[{snapshot:t,turnIndex:r.turnIndex,summon:o,sends:d}]})}(e.turns,[...e.subagents,...r])},[e.subagents,e.turns,e.sessionId,n]),s=(0,i.useMemo)(()=>r.map(({snapshot:t})=>{let n=t.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||t.id;return e.subagents.some(e=>e.id===t.id)?{key:t.id,liveId:t.id,status:t.status,archiveName:n}:{key:t.id,status:t.status,archiveName:n}}),[r,e.subagents]),a=(0,io._Z)(s,{sessionId:e.sessionId??"",client:t,enabled:!!e.sessionId&&s.length>0});return(0,i.useMemo)(()=>r.flatMap(t=>(function(e,t,n){var r;let{snapshot:i,summon:s}=e,a="completed"===(r=i.status)||"unknown"===r?"settled":"failed"===r||"aborted"===r?"failed":"streaming",l="failed"===a,o=s?.model.split("/",1)[0]?.trim()||void 0,d=l&&o?o:function(e,t,n){let r="string"==typeof e.progress?.resolvedModel?e.progress.resolvedModel.trim():"",i=r.indexOf("/");if(i>0)return r.slice(0,i);let s=t?.model.trim()??"",a=s.indexOf("/");return a>0?s.slice(0,a):n?.trim()||void 0}(i,s,n),c=i.id.trim()||void 0,u=`subagent:${i.id}`,p=[],h=e.turnIndex,m=0;if((t?.entries??[]).forEach((t,n)=>{var r;let f;if("irc"in t){let{from:n,message:r,truncated:s}=t.irc;if(s||"string"!=typeof n||"string"!=typeof r)return;for(let t=m;t<e.sends.length;t+=1){let s=e.sends[t];if(s.send.message===r&&function(e,t){if(!e.from)return!1;let n=e.receipts;return!!n&&n.some(e=>e.to===t&&("injected"===e.outcome||"woken"===e.outcome||"revived"===e.outcome))}(s.send,i.id)&&s.send.from===n){h=s.turnIndex,m=t+1;break}}return}if("assistant"!==t.message.role)return;let g=t.message.provider||d;if(!g||l&&o&&g!==o)return;let x=((f=((r=t.message).content??[]).filter(e=>"text"===e.type).map(e=>e.text.trim()).filter(e=>e.length>0).join("\n\n")).length>0?f:function(e){let t="";for(let n of e.content??[]){if("toolCall"!==n.type||"yield"!==n.toolName)continue;let e=n.input.data,r="";if("string"==typeof e)r=e;else if("object"==typeof e&&null!==e&&!Array.isArray(e))for(let t of["report",...id]){let n=e[t];if("string"==typeof n&&n.trim().length>0){r=n;break}}let i=r.trim();i.length>0&&(t=i)}return t}(r))||(l?t.message.errorMessage?.trim()??"":"");0!==x.length&&p.push({key:`${i.id}:${n}`,turnIndex:h,speakerId:u,provider:g,credentialId:t.message.credentialId,accountSessionId:null,label:l&&s?s.alias:c,text:x,status:a})}),0===p.length&&"settled"!==a&&d){let e=l?i.progress?.retryFailure?.errorMessage?.trim():void 0;p.push({key:`${i.id}:pending`,turnIndex:h,speakerId:u,provider:d,accountSessionId:null,label:l&&s?s.alias:c,text:e||"",status:a})}return p})(t,a.get(t.snapshot.id),e.sessionProvider)),[r,a,e.sessionProvider])},iu="web6",ip=[],ih=[],im=function(e){let t=(0,i.useMemo)(()=>(function(e=(e,t)=>fetch(e,t),t="/api/web6/consults"){return{async listConsults(n,r){let i=n.trim();if(!i)throw Error("sessionId가 필요하다");let s=`${t}?sessionId=${encodeURIComponent(i)}`,a=await e(s,{signal:r});if(!a.ok)throw Error(`HTTP ${a.status}`);let l=await a.json(),o=l&&"object"==typeof l&&"consults"in l?l.consults:null;if(!Array.isArray(o))throw Error("consults 배열이 아니다");return o.flatMap(e=>{let t=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t="string"==typeof e.sessionId?e.sessionId.trim():"";if(!t)return null;let n=e.startedAt;if("number"!=typeof n||!Number.isFinite(n))return null;let r=e.status;if("ok"!==r&&"failed"!==r)return null;let i="number"==typeof e.finishedAt&&Number.isFinite(e.finishedAt)?e.finishedAt:n,{conversationId:s,text:a,error:l}=e;return{sessionId:t,startedAt:n,finishedAt:i,elapsedMs:"number"==typeof e.elapsedMs&&Number.isFinite(e.elapsedMs)?e.elapsedMs:i-n,model:"string"==typeof e.model?e.model:"",status:r,conversationId:"string"==typeof s&&""!==s?s:void 0,text:"string"==typeof a&&""!==a?a:void 0,error:"string"==typeof l&&""!==l?l:void 0}}(e);return t?.sessionId===i?[t]:[]})}}})(),[]),[n,r]=(0,i.useState)(ih),s=(0,i.useRef)(""),a=e.sessionId??"",l=a.length>0;return(0,i.useEffect)(()=>{if(!l){s.current="",r(ih);return}let e=new AbortController,n=async()=>{if("u"<typeof document||"hidden"!==document.visibilityState)try{let n=await t.listConsults(a,e.signal),i=n.map(e=>`${e.startedAt}.${e.finishedAt}.${e.status}`).join("|");if(i===s.current)return;s.current=i,r(n)}catch{}};n();let i=setInterval(()=>void n(),5e3);return()=>{e.abort(),clearInterval(i)}},[t,l,a]),(0,i.useMemo)(()=>(function(e,t,n){if(0===e.length)return ip;let r=function(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if("user"!==r.role)continue;let i=r.timestamp;"number"==typeof i&&Number.isFinite(i)&&t.push({index:n,openedAt:i})}return t}(t);if(0===r.length)return ip;let i=[];for(let t of[...e].sort((e,t)=>e.startedAt-t.startedAt)){if(t.sessionId!==n||"failed"!==t.status)continue;let e=function(e,t){let n;for(let r of e)r.openedAt>t||(!n||r.openedAt>=n.openedAt)&&(n=r);return n?.index}(r,t.startedAt);if(void 0===e)continue;let s=t.error??"";0!==s.trim().length&&i.push({key:`${iu}:${t.startedAt}:${t.finishedAt}`,turnIndex:e,provider:"web6",speakerId:`${iu}:${t.conversationId??"unknown"}`,text:s,status:"failed"})}return i.length>0?i:ip})(n,e.messages,a),[n,e.messages,a])},ig={sending:!0,accepted:!0,delivered:!1,unconfirmed:!1,failed:!1};function ix(e){return e.trim()}function iv(e){return ix(e.text)||(e.images>0?"[Image]":"")}function ib(e){let t=e.filter(e=>!ig[e.stage]);if(t.length<=4)return e;let n=new Set(t.slice(0,t.length-4).map(e=>e.id));return e.filter(e=>!n.has(e.id))}function iy(e,t){switch(t.type){case"submit":return ib([...e,{id:t.id,kind:t.kind,text:t.text,images:t.images??0,stage:"sending",inQueue:!1}]);case"ack":return e.map(e=>e.id===t.id&&"sending"===e.stage?{...e,stage:"accepted"}:e);case"fail":return ib(e.map(e=>e.id===t.id&&ig[e.stage]?{...e,stage:"failed",inQueue:!1}:e));case"queue":return function(e,t,n){let r=new Map,i=(e,t)=>{let n=`${e}\u0000${ix(t)}`;r.set(n,(r.get(n)??0)+1)};for(let e of t)i("steer",e);for(let e of n)i("followUp",e);let s=!1,a=e.map(e=>{if(!ig[e.stage])return e;let t=`${e.kind}\u0000${iv(e)}`,n=r.get(t)??0;return n>0?(r.set(t,n-1),e.inQueue&&"accepted"===e.stage)?e:(s=!0,{...e,stage:"accepted",inQueue:!0}):e.inQueue?(s=!0,{...e,stage:"unconfirmed",inQueue:!1}):e});return s?a:e}(e,t.steering,t.followUp);case"user-message":{let n=ix(t.text);if(!n&&0===t.images)return e;let r=e.find(e=>(ig[e.stage]||"unconfirmed"===e.stage)&&e.kind===t.kind&&ix(e.text)===n&&e.images===t.images);if(!r)return e;return ib(e.map(e=>e===r?{...e,stage:"delivered",inQueue:!1}:e))}case"withdraw":{let n=e=>ig[e.stage]||"unconfirmed"===e.stage;if(void 0===t.text)return e.filter(e=>!n(e));let r=ix(t.text),i=e.find(e=>n(e)&&e.kind===t.kind&&(ix(e.text)===r||iv(e)===r));return i?e.filter(e=>e!==i):e}case"idle":{let t=e.filter(e=>e.inQueue);return t.length===e.length?e:t}case"reset":return 0===e.length?e:[]}}let iw={steer:"delivery.kind.steer",followUp:"delivery.kind.followUp"},ik={sending:"delivery.stage.sending",accepted:"delivery.stage.accepted",delivered:"delivery.stage.delivered",unconfirmed:"delivery.stage.unconfirmed",failed:"delivery.stage.failed"};function ij({rows:e,removeLabel:t,onRemove:n}){let s,{st:a}=nr(),[l,o]=(0,i.useState)(!1),{rows:d,hidden:c}=(s=Math.max(0,e.length-4),l||0===s?{rows:e,hidden:s}:{rows:e.slice(s),hidden:s}),u=e.length>4;return(0,i.useEffect)(()=>{u||o(!1)},[u]),(0,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("button",{type:"button",className:"answer-delivery-toggle","aria-expanded":l,onClick:()=>o(e=>!e),children:l?a("delivery.showRecent",{count:4}):a("delivery.showOlder",{count:c})}),(0,r.jsx)("ul",{className:"answer-delivery-list","aria-live":"polite",children:d.map(e=>{let i=nU(e.text),s=[i?[i.message,i.documents.map(e=>e.name).join(", ")].filter(Boolean).join(" \xb7 "):e.text.trim(),e.images>0?a("delivery.images",{count:e.images}):""].filter(Boolean).join(" \xb7 ");return(0,r.jsxs)("li",{className:"answer-delivery-row","data-kind":e.kind,"data-stage":e.stage,children:[(0,r.jsx)("span",{className:"answer-delivery-kind",children:a(iw[e.kind])}),(0,r.jsx)("span",{className:"answer-delivery-text",title:s,children:s}),(0,r.jsx)("span",{className:"answer-delivery-stage",children:a(ik[e.stage])}),e.removable&&n&&(0,r.jsx)("button",{type:"button",className:"answer-delivery-remove",title:t,"aria-label":`${t}: ${s}`,onClick:()=>n(e.kind,e.text),children:(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]},e.key)})})]})}let iS=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"})]}),iC=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("path",{d:"m22 9-6 6m0-6 6 6"})]});function iN({soundEnabled:e,onToggle:t}){let n=e?"완료음 끄기":"완료음 켜기";return(0,r.jsx)("div",{role:"group","aria-label":"오디오",style:{display:"flex",alignItems:"center",gap:6},children:(0,r.jsx)("button",{type:"button",className:`composer-icon-button${e?" is-active":""}`,onClick:t,"aria-pressed":e,title:n,"aria-label":n,children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e?iS:iC})})})}let iI=RegExp("^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀)*(?:(?:통화|전화)(?:를|좀|그만)*)?(?:좀|그만)*(?:끊어|끊을게|끊자|끊겠습니다)(?:줘|주세요|요)?$|^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀)*(?:통화|전화)(?:를|좀|그만)*(?:종료|종료해|종료할게|종료하자)(?:줘|주세요|요)?$","u");class iT{#e;#t;#n;#r;#i;#s;constructor(e=()=>new AudioContext){this.#t=null,this.#n=0,this.#r=0,this.#i=null,this.#s=new Set,this.#e=e}unlock(){let e=this.#a();e?.state==="suspended"&&e.resume().catch(()=>{})}get speaking(){return this.#s.size>0}push(e,t){if(e<this.#n)return;e>this.#n&&this.reset(e);let n=this.#a();if(!n)return;let r=function(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}(t);if(null!==this.#i){let e=new Uint8Array(r.length+1);e[0]=this.#i,e.set(r,1),r=e,this.#i=null}r.length%2==1&&(this.#i=r[r.length-1],r=r.subarray(0,r.length-1));let i=r.length/2;if(0===i)return;let s=n.createBuffer(1,i,24e3),a=s.getChannelData(0),l=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let e=0;e<i;e+=1)a[e]=l.getInt16(2*e,!0)/32768;let o=n.createBufferSource();o.buffer=s,o.connect(n.destination);let d=Math.max(n.currentTime+.05,this.#r);o.onended=()=>{this.#s.delete(o)},this.#s.add(o),o.start(d),this.#r=d+s.duration}reset(e){for(let t of(this.#n=Math.max(this.#n,e),this.#r=0,this.#i=null,this.#s)){t.onended=null;try{t.stop()}catch{}}this.#s.clear()}close(){this.reset(this.#n);let e=this.#t;this.#t=null,e&&e.close().catch(()=>{})}#a(){if(this.#t&&"closed"!==this.#t.state)return this.#t;try{this.#t=this.#e()}catch{this.#t=null}return this.#t}}function iM(e){return e&&"object"==typeof e&&"mode"in e?"character"===e.mode&&"string"==typeof e.alias&&("accepted"===e.tuning||"provisional"===e.tuning)?{mode:"character",alias:e.alias,tuning:e.tuning}:"native"===e.mode&&("no-key"===e.reason||"character-unknown"===e.reason||"voice-not-ready"===e.reason)?{mode:"native",alias:"string"==typeof e.alias?e.alias:null,reason:e.reason}:null:null}let i$={idle:!0,connecting:!0,live:!0,working:!0,error:!0,closed:!0},iR={unsupported:"chat.liveUnsupported","mic-denied":"chat.liveMicDenied","mic-unavailable":"chat.liveMicUnavailable",auth:"chat.liveAuthRequired",upstream:"chat.liveUpstreamFailed",voice:"chat.liveVoiceFailed",failed:"chat.liveFailed"},iE=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,r.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),iL=(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"})});function iA({sessionId:e,onEnsureSession:t,onTranscriptPersisted:n}){let{t:s}=(0,R.s)(),a=function(e,t,n){let{locale:r}=(0,R.s)(),[s,a]=(0,i.useState)("idle"),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),b=(0,i.useRef)(null),y=(0,i.useRef)(null),w=(0,i.useRef)(null),k=(0,i.useRef)(null),j=(0,i.useRef)(null),S=(0,i.useRef)(null),C=(0,i.useRef)(null),N=(0,i.useRef)(0);(0,i.useEffect)(()=>{g("u">typeof RTCPeerConnection&&"u">typeof navigator&&"function"==typeof navigator.mediaDevices?.getUserMedia)},[]);let I=(0,i.useCallback)(e=>{N.current+=1;let t=j.current;for(let e of(j.current=null,k.current?.close(),k.current=null,b.current?.close(),b.current=null,y.current?.getTracks()??[]))e.stop();y.current=null;let n=w.current;w.current=null,n&&(n.srcObject=null,n.remove()),S.current?.close(),S.current=null,C.current=null,t&&fetch(`/api/live/call/${encodeURIComponent(t)}`,{method:"DELETE"}).catch(()=>{}),a(e),p(null),m(null),v(!1)},[]),T=(0,i.useCallback)((e,t)=>{o(e),c(t??null),I("error")},[I]),M=(0,i.useCallback)(async()=>{let i,s=N.current+1;N.current=s,o(null),c(null),v(!0),a("connecting"),S.current?.close();let l=new iT;l.unlock(),S.current=l;let d=e;if(!d&&t){try{d=await t()}catch{d=void 0}if(N.current!==s)return}if(!d){N.current===s&&(v(!1),T("failed"));return}try{i=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(t){let e=t instanceof DOMException?t.name:"";N.current===s&&(v(!1),T("NotAllowedError"===e||"SecurityError"===e?"mic-denied":"mic-unavailable"));return}if(N.current!==s){for(let e of i.getTracks())e.stop();return}y.current=i;try{let e,t,l=new RTCPeerConnection;for(let e of(b.current=l,i.getTracks()))l.addTrack(e,i);let o=document.createElement("audio");if(o.autoplay=!0,w.current=o,l.ontrack=e=>{let[t]=e.streams;t&&C.current?.mode!=="character"&&(o.srcObject=t)},await l.setLocalDescription(await l.createOffer()),await function(e){if("complete"===e.iceGatheringState)return Promise.resolve();let{promise:t,resolve:n}=Promise.withResolvers(),r=()=>{clearTimeout(s),e.removeEventListener("icegatheringstatechange",i),n()},i=()=>{"complete"===e.iceGatheringState&&r()},s=setTimeout(r,3e3);return e.addEventListener("icegatheringstatechange",i),t}(l),N.current!==s)return;let c=l.localDescription?.sdp;if(!c)throw Error("The browser produced no offer SDP.");let f=await fetch("/api/live/offer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:d,sdp:c,locale:r})}),g=await f.json().catch(()=>({})),x="",y="";if(g&&"object"==typeof g&&("error"in g&&(e=g.error),"message"in g&&"string"==typeof g.message&&(t=g.message),"callId"in g&&"string"==typeof g.callId&&(x=g.callId),"sdp"in g&&"string"==typeof g.sdp&&(y=g.sdp),"voice"in g&&N.current===s&&(C.current=iM(g.voice))),!f.ok||!x||!y){if(N.current===s){var u,h;v(!1),T((u=f.status,h=e,401===u||"live-auth"===h?"auth":502===u||"live-upstream"===h?"upstream":"failed"),t)}return}if(N.current!==s)return void fetch(`/api/live/call/${encodeURIComponent(x)}`,{method:"DELETE"}).catch(()=>{});if(await l.setRemoteDescription({type:"answer",sdp:y}),N.current!==s){l.close(),fetch(`/api/live/call/${encodeURIComponent(x)}`,{method:"DELETE"}).catch(()=>{});return}j.current=x,m(C.current);let M=new EventSource(`/api/live/events?callId=${encodeURIComponent(x)}`);k.current=M,M.onmessage=e=>{let t;if(N.current===s){try{t=JSON.parse(e.data)}catch{return}if(t&&"object"==typeof t&&"type"in t){if("state"===t.type&&"state"in t){var r;if("string"!=typeof t.state||(r=t.state,!0!==i$[r]))return;"closed"===t.state?I("closed"):a(t.state);return}if("transcript"===t.type&&"role"in t&&"text"in t){if(("user"===t.role||"assistant"===t.role)&&"string"==typeof t.text){let e;p({role:t.role,text:t.text}),"final"in t&&!0===t.final&&n&&Promise.resolve().then(()=>n(d)).catch(()=>{}),"final"in t&&!0===t.final&&"user"===t.role&&(e=t.text.normalize("NFC").replace(/[^\p{L}\p{N}]+/gu,"")).length>0&&iI.test(e)&&I("idle")}return}if("voice"===t.type&&"voice"in t){let e=iM(t.voice);e&&e.mode===C.current?.mode&&(C.current=e,m(e));return}if("speech"===t.type&&"epoch"in t&&"audio"in t){"number"==typeof t.epoch&&"string"==typeof t.audio&&S.current?.push(t.epoch,t.audio);return}if("speech-reset"===t.type&&"epoch"in t){"number"==typeof t.epoch&&S.current?.reset(t.epoch);return}if("speech-error"===t.type&&"message"in t&&"string"==typeof t.message)return void T("voice",t.message);"error"===t.type&&"message"in t&&"string"==typeof t.message&&T("upstream",t.message)}}},M.onerror=()=>{N.current===s&&j.current&&T("failed")},a("live")}catch(e){N.current===s&&T("failed",e instanceof Error?e.message:String(e))}finally{N.current===s&&v(!1)}},[e,t,n,r,T,I]),$=(0,i.useCallback)(()=>{if("idle"===s||"closed"===s||"error"===s){x||M();return}I("idle")},[x,s,M,I]);return(0,i.useEffect)(()=>()=>I("closed"),[I]),{state:s,failure:l,detail:d,transcript:u,voice:h,supported:f,toggle:$}}(e,t,n),l="connecting"===a.state||"live"===a.state||"working"===a.state,o="connecting"===a.state?"chat.liveConnecting":"working"===a.state?"chat.liveWorking":"live"===a.state?"chat.liveOn":null,d=s(l?"chat.liveStop":"chat.liveStart"),c=!1===a.supported?iR.unsupported:a.failure?iR[a.failure]:null,u=!!(e||t),p=u?null:"chat.liveNeedsSession",h=l?function(e,t){if(!e)return null;if("character"===e.mode){let n=t("chat.liveVoiceCharacter",{name:e.alias});return"provisional"===e.tuning?`${n} \xb7 ${t("chat.liveVoiceProvisional")}`:n}return"voice-not-ready"===e.reason&&e.alias?t("chat.liveVoiceNativeNotReady",{name:e.alias}):"character-unknown"===e.reason?t("chat.liveVoiceNativeUnknown"):null}(a.voice,s):null;return(0,r.jsxs)("div",{role:"group","aria-label":s("chat.liveVoice"),style:{display:"flex",alignItems:"center",gap:6,flex:"0 1 auto",minWidth:0},children:[c&&(0,r.jsx)("span",{role:"status",style:{fontSize:11,color:"var(--danger)",maxWidth:220,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:a.detail??void 0,children:s(c)}),o&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s(o)}),h&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",maxWidth:200,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:h,children:h}),(0,r.jsx)("button",{type:"button",className:`composer-icon-button${l?" is-active":""}`,onClick:a.toggle,disabled:!a.supported||!u,"aria-pressed":l,title:p?s(p):d,"aria-label":p?s(p):d,children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:l?iL:iE})})]})}let iz={display:"inline-flex",alignItems:"center",flexShrink:0,height:32,padding:"0 10px",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",background:"var(--accent-soft)",color:"var(--accent-hover)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600,lineHeight:1.3,whiteSpace:"nowrap"};function iW({sessionId:e}){let{t}=(0,R.s)(),[n,s]=(0,i.useState)(null);return((0,i.useEffect)(()=>{if(!e)return void s(null);let t=!1,n=0,r=!1,i=async()=>{if("visible"===document.visibilityState)try{let n=await fetch("/api/gpt6/handles",{cache:"no-store"});if(!n.ok)return;let i=await n.json();if(t)return;let a=Array.isArray(i.handles)?i.handles:[],l=a.find(t=>t.sessionId===e&&"active"===t.status)?.handle??null;r=null!==l,s(l)}catch{}},a=async()=>{await i(),t||(n=window.setTimeout(()=>void a(),r?5e3:3e4))};return a(),document.addEventListener("visibilitychange",i),()=>{t=!0,window.clearTimeout(n),document.removeEventListener("visibilitychange",i)}},[e]),n)?(0,r.jsx)("span",{style:iz,title:t("gpt6.boundBadgeHint",{handle:n}),children:t("gpt6.boundBadge",{handle:n})}):null}function iF(e){if(!e||"object"!=typeof e||"string"!=typeof e.data||"string"!=typeof e.mimeType||!e.mimeType.startsWith("image/"))return!1;let t=function(e){if(!e||e.length%4!=0)return null;let t=e.endsWith("==")?2:+!!e.endsWith("="),n=e.length-t;for(let t=0;t<n;t+=1){var r;if(!((r=e.charCodeAt(t))>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||43===r||47===r))return null}for(let t=n;t<e.length;t+=1)if("="!==e[t])return null;return e.length/4*3-t}(e.data);return null!==t&&t<=0xa00000}let iP=new Map,iD="ompweb-drafts-for-reload-v1",i_=!1;function iO(){if(i_||"u"<typeof sessionStorage)return;i_=!0;let e=sessionStorage.getItem(iD);if(e){sessionStorage.removeItem(iD);try{let t=JSON.parse(e);if(!Array.isArray(t))return;for(let e of t){if(!Array.isArray(e)||2!==e.length||"string"!=typeof e[0])continue;let t=e[1];t&&"string"==typeof t.value&&Array.isArray(t.images)&&Array.isArray(t.documents)&&iP.set(e[0],iB(t))}}catch{}}}function iH(){if("u"<typeof sessionStorage)return{ok:!1,error:"sessionStorage unavailable"};try{return sessionStorage.setItem(iD,JSON.stringify([...iP.entries()].map(([e,t])=>[e,iB(t)]))),{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function iB(e){return{value:e.value,images:e.images.map(e=>({...e})),documents:e.documents.map(e=>({...e}))}}function iU(e){return!e.value&&0===e.images.length&&0===e.documents.length}function iq(e){iO();let t=iP.get(e);return t?iB(t):null}function iV(e,t){(iO(),iU(t))?iP.delete(e):iP.set(e,iB(t))}function iK(e){iP.delete(e)}function iJ(e,t,n,r,i,s=[]){let a=[...t??[],...r].filter(iF).slice(0,10).map(({data:e,mimeType:t})=>({data:e,mimeType:t})),l=nO([...i??[],...s]);return{value:e.trim()?n.trim()?`${e}
|
|
13
|
-
|
|
14
|
-
${n}`:e:n,images:a,documents:l}}function iG(e,t,n){if(e===t)return n?iB(n):iq(t);let r=iq(e),i=n&&!iU(n)?iB(n):r??(n?iB(n):null),s=iq(t);if(iK(e),!i)return s;let a=s?iJ(s.value,s.images,i.value,i.images,s.documents,i.documents):i;return iV(t,a),iB(a)}function iY(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let n=/(?:^|\s)@([^\s"]*)$/.exec(e);return n?{start:e.length-(n[1].length+1),query:n[1],quoted:!1}:null}function iZ(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function iX(e,t){if(!e)return!0;let n=0;for(let r=0;r<t.length&&n<e.length;r++)t[r]===e[n]&&n++;return n===e.length}let iQ="omp-web:model-picks";function i0(){try{let e=JSON.parse(window.localStorage.getItem(iQ)??"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))"number"==typeof r&&Number.isFinite(r)&&r>0&&(t[n]=Math.floor(r));return t}catch{return{}}}function i1(e,t,n,r,i={}){let s=i.gap??8,a=i.margin??8,l=i.prefer??"above",o=Math.min(i.minHeight??120,Math.max(0,n-2*a)),d=Math.max(0,e-s-a),c=Math.max(0,n-t-s-a),u="above"===l?d:c,p="above"===l?c:d,h=u>=r||u>=p;return{side:h?l:"above"===l?"below":"above",maxHeight:Math.max(o,Math.min(r,h?u:p))}}function i2(e,t,n){return Math.min(e*t,n)}function i4(e,t,n){let{viewportFraction:r,cap:s,gap:a,margin:l,minHeight:o,prefer:d}=n,[c,u]=(0,i.useState)({side:d??"above",maxHeight:s}),p=(0,i.useCallback)(()=>{let t=e.current;if(!t)return;let n=window.visualViewport?.height??window.innerHeight,i=t.getBoundingClientRect(),c=i1(i.top,i.bottom,n,i2(n,r,s),{gap:a,margin:l,minHeight:o,prefer:d});u(e=>e.side===c.side&&e.maxHeight===c.maxHeight?e:c)},[e,s,a,l,o,d,r]);return(0,i.useEffect)(()=>{if(!t)return;p();let n=e.current,r=n?new ResizeObserver(p):null;return n&&r&&r.observe(n),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),window.visualViewport?.addEventListener("resize",p),window.visualViewport?.addEventListener("scroll",p),()=>{r?.disconnect(),window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0),window.visualViewport?.removeEventListener("resize",p),window.visualViewport?.removeEventListener("scroll",p)}},[e,p,t]),c}var i5=n(14755);async function i8(e,t,n,r,i,s,a){let l=e.slice(1).split(/\s/,1)[0];try{let o=t?.length?t:await a?.()??[],d=[...so,...o].find(e=>e.name===l||"aliases"in e&&e.aliases?.includes(l));if(s&&(!d||"builtin"===d.source))return i(`/${l} cannot run with attachments. Remove them and retry.`),!1;let c=await n?.(e);if(c?.handled){if(c.error)return!1;return c.prompt&&r(c.prompt),!0}if(d&&"builtin"!==d.source)return r(e),!0;return i(`/${l} is not available in this web session.`),!1}catch(e){return i(e instanceof Error?e.message:String(e)),!1}}let i6=["off","default","full"],i3={off:"none",default:"default",full:"full"},i7=i5.IN.join(" \xb7 "),i9=i5.C1.filter(e=>!i5.IN.includes(e)).join(" \xb7 ");function se(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let st=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),sn=0,sr={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function si(e,t){return st.compare(e.name||e.modelId,t.name||t.modelId)||st.compare(e.provider,t.provider)||st.compare(e.modelId,t.modelId)}let ss=["auto","off","minimal","low","medium","high","xhigh","max"],sa=["low","medium","high","xhigh"],sl={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},so=[{name:"compact",descriptionKey:"chat.commandCompact",source:"builtin"},{name:"reload",descriptionKey:"chat.commandReload",source:"builtin"},{name:"name",descriptionKey:"chat.commandName",source:"builtin"},{name:"session",descriptionKey:"chat.commandSession",source:"builtin"},{name:"copy",descriptionKey:"chat.commandCopy",source:"builtin"}],sd=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],sc={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},su={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function sp(e,t,n){let r=e.name.toLowerCase(),i=sh(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function sh(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function sm(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function sf(e){return{data:e.data,mimeType:e.mimeType}}function sg(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function sx(e){return(e??[]).filter(iF).slice(0,10).map(sg)}function sv(e){return nO(e).map(e=>{let t=nJ(e);return{...e,id:++sn,status:"ready",..."audio"===t||"file"===t?{stored:t}:{}}})}function sb(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function sy({tone:e,title:t,body:n}){let i="error"===e?"danger":"warning";return(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid var(--${i}-line)`,borderRadius:"var(--radius-control)",background:`var(--${i}-soft)`,color:`var(--${i})`,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:t}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n})]})]})}function sw({error:e}){return e?(0,r.jsx)(sy,{tone:"error",title:"Model error",body:e}):null}function sk({warnings:e}){return e&&0!==e.length?(0,r.jsx)(sy,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let sj=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,onFollowUp:s,isStreaming:l,model:o,isAutoModelSelection:d,modelNames:c,modelList:u,modelError:p,modelScopeWarnings:h,onModelChange:m,onMainPresetChange:f,mainPresetActiveAlias:g,modelRoles:x,onRoleModelChange:v,modelSwitching:b,onCompact:y,onAbortCompaction:w,isCompacting:k,compactError:j,compactResult:S,toolPreset:C,onToolPresetChange:N,thinkingLevel:I,effectiveThinkingLevel:T,thinkingCeiling:M,onThinkingLevelChange:$,availableThinkingLevels:E,thinkingLevelMap:L,fastMode:A=null,fastModeBusy:z=!1,onFastModeToggle:W,retryInfo:P,deliveryRows:D=[],inputHistory:_=[],onRecallQueue:O,onRemoveQueuedMessage:H,slashCommands:B,slashCommandsLoading:U,onLoadSlashCommands:q,onBuiltinCommand:V,soundEnabled:K,onSoundToggle:J,onAudioUnlock:G,onPromptWithStreamingBehavior:Y,draftKey:Z,cwd:X,sessionId:Q,onEnsureSession:ee,onLiveTranscriptPersisted:et},en){let er,ei,es,ea,el,eo,ed,ec,eu,ep,{t:eh}=(0,R.s)(),{st:em}=nr(),ef=D.some(e=>e.removable),eg=F(),[ex,ev]=(0,i.useState)(()=>Z?iq(Z)?.value??"":""),[eb,ey]=(0,i.useState)(!1),[ew,ek]=(0,i.useState)(null),[ej,eS]=(0,i.useState)(""),[eC,eN]=(0,i.useState)({});(0,i.useEffect)(()=>{eb&&eN(i0())},[eb]);let[eI,eT]=(0,i.useState)(!1),[eM,e$]=(0,i.useState)(null),[eR,eE]=(0,i.useState)(!1),[eL,eA]=(0,i.useState)(!1),[ez,eW]=(0,i.useState)(null),[eF,eP]=(0,i.useState)(!1),[eD,e_]=(0,i.useState)(()=>Z?sx(iq(Z)?.images):[]),[eO,eH]=(0,i.useState)(()=>Z?sv(iq(Z)?.documents):[]),[eB,eU]=(0,i.useState)(null),eq=(0,i.useMemo)(()=>eO.filter(e=>"ready"===e.status),[eO]),eV=eO.some(e=>"ready"!==e.status),eK=ex.trimStart(),eJ=0===eD.length&&0===eO.length&&eK.startsWith("!"),eG=eJ&&eK.startsWith("!!"),[eY,eZ]=(0,i.useState)(!1),[eX,eQ]=(0,i.useState)(0),[e0,e1]=(0,i.useState)(null),[e2,e4]=(0,i.useState)(!1),[e5,e8]=(0,i.useState)(0),[e6,e3]=(0,i.useState)(!1),[e7,e9]=(0,i.useState)(0),[te,tt]=(0,i.useState)(null),[tn,tr]=(0,i.useState)(!1),[ti,ts]=(0,i.useState)(null),[ta,tl]=(0,i.useState)(null),to=X&&ta?.cwd===X?ta.values:{},td=(0,i.useRef)(null),tc=(0,i.useRef)(null),tu=(0,i.useRef)(null),tp=(0,i.useRef)(null),th=(0,i.useRef)(null),tm=(0,i.useRef)(null),tf=(0,i.useRef)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),tb=(0,i.useRef)(null),ty=(0,i.useRef)(!1),tw=(0,i.useRef)(0),tk=(0,i.useRef)(!1),tj=(0,i.useRef)([]),tS=(0,i.useRef)([]),tC=(0,i.useRef)([]),tN=(0,i.useRef)(null),tI=(0,i.useRef)(null),tT=(0,i.useRef)(Z),tM=(0,i.useRef)(ex),t$=(0,i.useRef)(eD),tR=(0,i.useRef)(0),tE=(0,i.useRef)(eO);tM.current=ex,t$.current=eD,tE.current=eO,(0,i.useImperativeHandle)(en,()=>({insertIfEmpty(e){let t=td.current;(t?t.value:ex).trim()||(tM.current=e,ev(e),e1(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){let t,n,r=td.current;if(!function(e,t,n,r=0){return!e.trim()&&0===t&&0===n&&0===r}(r?r.value:ex,t$.current.length,tR.current,tE.current.length))return;let i=(t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),nU(t)?.message??t),s=sx("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,n=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof n)return[];let r={data:t,mimeType:n};return iF(r)?[r]:[]})),a=sv((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),nU(n)?.documents??[]));tM.current=i,t$.current=s,tE.current=a,ev(i),e1(null),e3(!1),e_(e=>(e.forEach(sb),s)),eH(a),requestAnimationFrame(()=>{r&&(r.focus(),r.style.height="auto",r.style.height=`${Math.min(r.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(tT.current!==e)return void iG(e,t);let n={value:tM.current,images:t$.current.map(sf),documents:tE.current.filter(e=>"ready"===e.status).map(({name:e,mimeType:t,size:n,text:r})=>({name:e,mimeType:t,size:n,text:r}))},r=iG(e,t,n)??{value:"",images:[],documents:[]},i=r.value===n.value&&r.images.length===n.images.length&&r.images.every((e,t)=>e.data===n.images[t]?.data&&e.mimeType===n.images[t]?.mimeType)&&r.documents.length===n.documents.length&&r.documents.every((e,t)=>e.name===n.documents[t]?.name&&e.mimeType===n.documents[t]?.mimeType&&e.size===n.documents[t]?.size&&e.text===n.documents[t]?.text);if(tT.current=t,i)return;let s=sx(r.images),a=sv(r.documents),l=r.value;tM.current=l,t$.current=s,tE.current=a,ev(l),e_(e=>(e.forEach(sb),s)),eH(a),e1(null),e3(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let i=tT.current,s=r??i,a=s===i,l=!a&&s?iq(s):null,o=iJ(e,t,a?tM.current:l?.value??"",a?t$.current.map(sf):l?.images??[],n,a?tE.current.filter(e=>"ready"===e.status).map(({name:e,mimeType:t,size:n,text:r})=>({name:e,mimeType:t,size:n,text:r})):l?.documents??[]);if(s&&iV(s,o),!a)return;let d=t?.length?[...sx(t).slice(0,Math.max(0,10-t$.current.length)),...t$.current].slice(0,10):t$.current,c=sv(o.documents);tM.current=o.value,t$.current=d,tE.current=c,ev(o.value),e1(null),e3(!1),t?.length&&e_(e=>{let n=Math.max(0,10-e.length),r=sx(t).slice(0,n),i=r.length>0?[...r,...e]:e;return t$.current=i,i}),eH(c),requestAnimationFrame(()=>{let e=td.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},insertText(e){let t=td.current;if(!t)return void ev(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n),s=t.value.slice(r),a=i.length>0&&!i.endsWith(" ")?" ":"",l=i+a+e+s;tM.current=l,ev(l),e1(null),requestAnimationFrame(()=>{if(!t)return;let r=n+a.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){tF(e)}}));let tL=(0,i.useCallback)(async e=>{let t=Math.max(0,10-t$.current.length-tR.current),n=e.filter(e=>e.size>0xa00000);n.length>0&&eU(eh("chat.attachImageTooLarge",{name:n.map(e=>e.name).join(", "),limit:nq(0xa00000)}));let r=e.filter(e=>e.size<=0xa00000),i=r.slice(0,t);if(i.length<r.length&&eU(eh("chat.attachImageLimit",{count:10})),i.length){tR.current+=i.length;try{let e=await Promise.all(i.map(e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result.split(",")[1];t({data:n,mimeType:e.type,previewUrl:URL.createObjectURL(e)})},r.onerror=n,r.readAsDataURL(e)})));e_(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(sb);let r=[...t,...n];return t$.current=r,r})}finally{tR.current-=i.length}}},[eh]),tA=(0,i.useCallback)(async e=>{for(let t of e){let e=nF(t);if(!e)continue;if(tE.current.length>=3){eU(eh("chat.attachLimit",{count:3}));continue}if(t.size>8388608){eU(eh("chat.attachTooLarge",{name:t.name,limit:nq(8388608)}));continue}if(tE.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eU(eh("chat.attachTotalTooLarge",{limit:nq(0x1000000)}));continue}let n={id:++sn,name:t.name,mimeType:nA[e],size:t.size,text:"",status:"extracting"},r=[...tE.current,n];tE.current=r,eH(r);try{let e=await nH(t);if(tE.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new nL("text_too_large","Total extracted text exceeds 240000 characters");let r=tE.current.map(t=>t.id===n.id?{...e,id:t.id,status:"ready"}:t);tE.current=r,eH(r)}catch(i){let e=tE.current.some(e=>e.id===n.id),r=tE.current.filter(e=>e.id!==n.id);if(tE.current=r,eH(r),!e)continue;i instanceof nL?"text_too_large"===i.code?eU(eh("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===i.code?eU(eh("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===i.code?eU(eh("chat.attachNoPdfText",{name:t.name})):"password_protected"===i.code?eU(eh("chat.attachPasswordProtected",{name:t.name})):eU(eh("chat.attachExtractFailed",{name:t.name})):eU(eh("chat.attachExtractFailed",{name:t.name}))}}},[eh]),tz=(0,i.useCallback)((e,t)=>{if(!tE.current.some(t=>t.id===e))return!1;let n=t?tE.current.map(n=>n.id===e?t:n):tE.current.filter(t=>t.id!==e);return tE.current=n,eH(n),!0},[]),tW=(0,i.useCallback)(async(e,t)=>{for(let n of e){if(tE.current.length>=3){eU(eh("chat.attachLimit",{count:3}));continue}if(n.size>0x1900000){eU(eh("chat.attachStoredTooLarge",{name:n.name,limit:nq(0x1900000)}));continue}let e={id:++sn,name:n.name,mimeType:"text/plain",size:n.size,text:"",status:"audio"===t?"transcribing":"extracting",sourceSize:n.size},r=[...tE.current,e];tE.current=r,eH(r);let i=(t,n)=>{let r=tE.current.filter(t=>t.id!==e.id);return t<=12e4&&r.reduce((e,t)=>e+t.text.length,0)+t<=24e4&&r.reduce((e,t)=>e+t.size,0)+n<=0x1000000};if("file"===t&&n.size<=8388608){let t=await n.arrayBuffer().then(e=>{var t;return 255===(t=new Uint8Array(e))[0]&&254===t[1]?n_("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?n_("utf-16be",t.subarray(2)):t.includes(0)?null:n_("utf-8",t)??n_("euc-kr",t)},()=>null);if(null!==t&&i(t.length,n.size)){tz(e.id,{...e,text:t,status:"ready"});continue}}let s={...e,stored:t,status:"audio"===t?"transcribing":"uploading"};if(tz(e.id,s))try{let r=await nG(n,Q),a=tE.current.filter(t=>t.id!==e.id).reduce((e,t)=>e+t.text.length,0),l=function(e,t=12e4){let n=`${nK}${e.path}
|
|
15
|
-
(${e.mimeType}, ${e.size} bytes) Open it with a tool when its contents are needed.`;if(void 0!==e.transcript){let r=`${n}
|
|
16
|
-
|
|
17
|
-
Transcript of the audio (speech-to-text by Gemini; may contain recognition errors):
|
|
18
|
-
`,i=r+e.transcript;return i.length<=t?i:r+e.transcript.slice(0,Math.max(0,t-r.length-nV.length))+nV}return e.transcriptError?`${n}
|
|
19
|
-
The audio could not be transcribed: ${e.transcriptError}`:n}(r,Math.min(12e4,24e4-a)),o=new TextEncoder().encode(l).byteLength;if(!i(l.length,o)){tz(e.id,null)&&eU(eh("chat.attachTotalTooLarge",{limit:nq(0x1000000)}));continue}let d="audio"===t&&void 0===r.transcript;tz(e.id,{...s,text:l,size:o,status:"ready",transcriptFailed:d})&&d&&eU(eh("chat.attachTranscribeFailedNotice",{name:n.name,error:r.transcriptError??""}))}catch(t){tz(e.id,null)&&eU(eh("chat.attachUploadFailed",{name:n.name,error:t instanceof Error?t.message:String(t)}))}}},[tz,Q,eh]),tF=(0,i.useCallback)(async e=>{eU(null);let{images:t,documents:n,audio:r,files:i}=function(e){let t=[],n=[],r=[],i=[];for(let s of e)s.type.startsWith("image/")?t.push(s):null!==nF(s)?n.push(s):nD(s)?r.push(s):i.push(s);return{images:t,documents:n,audio:r,files:i}}(e);await Promise.all([tL(t),tA(n),tW(r,"audio"),tW(i,"file")])},[tA,tW,tL]),tP=(0,i.useCallback)(e=>{e_(t=>{let n=[...t],[r]=n.splice(e,1);return r&&sb(r),t$.current=n,n})},[]),tD=(0,i.useCallback)(e=>{let t=tE.current.filter(t=>t.id!==e);tE.current=t,eH(t)},[]),t_=(0,i.useCallback)(()=>{t$.current=[],e_(e=>(e.forEach(sb),[]))},[]),tO=(0,i.useCallback)(()=>{tE.current=[],eH([])},[]),tB=(0,i.useCallback)(()=>{tM.current="",ev(""),e1(null),e3(!1),Z&&iK(Z),tT.current&&tT.current!==Z&&iK(tT.current),t_(),tO(),eU(null),td.current&&(td.current.style.height="auto")},[tO,t_,Z]);(0,i.useEffect)(()=>{Z&&tT.current===Z&&iV(Z,{value:ex,images:eD.map(sf),documents:eq.map(({name:e,mimeType:t,size:n,text:r})=>({name:e,mimeType:t,size:n,text:r}))})},[eD,Z,eq,ex]),(0,i.useEffect)(()=>{let e=tT.current;if(e===Z)return;e&&iV(e,{value:tM.current,images:t$.current.map(sf),documents:tE.current.filter(e=>"ready"===e.status).map(({name:e,mimeType:t,size:n,text:r})=>({name:e,mimeType:t,size:n,text:r}))});let t=Z?iq(Z):null;tT.current=Z;let n=t?.value??"",r=sx(t?.images),i=sv(t?.documents);tM.current=n,t$.current=r,tE.current=i,ev(n),e1(null),e3(!1),e_(e=>(e.forEach(sb),r)),eH(i)},[Z]),(0,i.useEffect)(()=>{let e=td.current;e&&(e.style.height="auto",ex&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[ex]),(0,i.useEffect)(()=>()=>{t$.current.forEach(sb)},[]);let tU=(0,i.useCallback)(async()=>{let t=ex.trim(),n=eK.trim(),r=n.startsWith("/")||n.startsWith("!")?n:t;if((r||eD.length||eq.length)&&!l&&!eV){if(G?.(),r.startsWith("/")){await i8(r,B,V,t=>e(t,eD.length?eD:void 0,eq.length?eq:void 0),eU,!!(eD.length||eq.length),q)&&tB();return}tB(),e(r,eD.length?eD:void 0,eq.length?eq:void 0)}},[ex,eK,eD,eq,eV,l,V,B,q,e,tB,G]),tq=eK.startsWith("/")&&!/\s/.test(eK.slice(1))?eK.slice(1).toLowerCase():null,tV=(()=>{if(null===tq)return[];let e=[...l?[]:so,...B??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=sh(e,eh).toLowerCase();return t.includes(tq)||n.includes(tq)}).sort((e,t)=>{let n=sp(e,tq,eh)-sp(t,tq,eh);return 0!==n?n:su[e.source]-su[t.source]||st.compare(e.name,t.name)}).filter(e=>{let n=e.name.toLowerCase();return!t.has(n)&&(t.add(n),!0)})})(),{commands:tK,groups:tJ}=(er=0,{commands:(ei=sd.map(e=>{let t=tV.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!sm(e,to)),...t.filter(e=>sm(e,to))]:t;return{source:e,items:n.map(e=>({command:e,index:er++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:ei}),tG=1===tV.length?eh(tq?"chat.match":"chat.command"):eh(tq?"chat.matches":"chat.commands",{count:tV.length}),tY=!!ex.trim(),tZ=!eV&&(tY||eD.length>0||eq.length>0),tQ=(0,i.useCallback)((e,t)=>{if(!X)return void e1(null);let n=t??e.length;e1(iY(e.slice(0,n)))},[X]),t0=e0?.query??null,t1=i.useMemo(()=>null!==t0&&te&&te.cwd===X?function(e,t,n=20){let r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:iX(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),i=-1===e?n:n.slice(e+1);i===t?r=100:i.startsWith(t)?r=80:i.includes(t)?r=50:n.includes(t)?r=30:iX(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||iZ(e.entry.path)-iZ(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(te.entries,t0):[],[t0,te,X]),t2=!!(t0&&te?.truncated&&te.cwd===X);(0,i.useEffect)(()=>{if(!t2||!X||!t0)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(X)}&q=${encodeURIComponent(t0)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>ts({cwd:X,query:t0,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[t2,t0,X]);let t4=t2&&null!==ti&&ti.cwd===X&&ti.query===t0,t5=t4?ti.matches:t1,t8=null===e0?null:`${e0.start}:${+!!e0.quoted}:${e0.query}`;(0,i.useEffect)(()=>{if(null===t8){e4(!1),e8(0);return}e4(!0),e8(0)},[t8]);let t6=null!==e0,t3=i4(tv,e6,{viewportFraction:.44,cap:360}),t7=i4(tv,eY,{viewportFraction:.56,cap:460}),t9=i4(tv,e2,{viewportFraction:.48,cap:400});(0,i.useEffect)(()=>{if(!t6||!X)return;let e=tN.current;e&&e.cwd===X&&Date.now()-e.fetchedAt<1e4||tI.current===X||(tI.current=X,tr(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{tt({cwd:X,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>iZ(e.path)-iZ(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tN.current={cwd:X,fetchedAt:Date.now()}}).catch(()=>{tN.current=null}).finally(()=>{tI.current=null,tr(!1)}))},[t6,X]);let ne=(0,i.useCallback)(e=>{if(!e0)return;let t=td.current,n=t?.selectionStart??ex.length,r=ex.slice(0,e0.start),i=ex.slice(n);e0.quoted&&i.startsWith('"')&&(i=i.slice(1));let s=function(e,t,n=!1){let r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let s=i?`@"${r}" `:`@${r} `;return{text:s,cursorOffset:s.length}}(e.path,e.isDir,e0.quoted),a=r+s.text+i,l=r.length+s.cursorOffset;ev(a),e1(iY(a.slice(0,l))),requestAnimationFrame(()=>{let e=td.current;e&&(e.focus(),e.setSelectionRange(l,l),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[e0,ex]);(0,i.useEffect)(()=>{e5>=t5.length&&e8(Math.max(0,t5.length-1))},[t5.length,e5]),(0,i.useEffect)(()=>{tS.current.length=t5.length},[t5.length]),(0,i.useEffect)(()=>{e2&&tS.current[e5]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e5,e2]),(0,i.useEffect)(()=>{e7>=_.length&&e9(Math.max(0,_.length-1))},[_.length,e7]),(0,i.useEffect)(()=>{tC.current.length=_.length},[_.length]),(0,i.useEffect)(()=>{e6&&tC.current[e7]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e7,e6]);let nt=(0,i.useCallback)(e=>{tM.current=e,ev(e),e3(!1),e9(0),e1(null),requestAnimationFrame(()=>{let t=td.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),nn=(0,i.useCallback)(e=>{let t=`/${e.name} `;tM.current=t,ev(t),eZ(!1),eQ(0),requestAnimationFrame(()=>{let e=td.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),ni=(0,i.useCallback)(async e=>{let t=ex.trim(),r=eK.trim(),i=r.startsWith("/")||r.startsWith("!")?r:t,a=eV||!i&&0===eD.length&&0===eq.length?null:{message:i,images:eD.length?eD:void 0,documents:eq.length?eq:void 0};if(!a)return;G?.();let l="steer"===e?"steer":"followUp";if(i.startsWith("/")){await i8(i,B,V,e=>{if(!Y)throw Error("Cannot queue this command while the session is busy.");Y(e,l,a.images,a.documents)},eU,!!(a.images?.length||a.documents?.length),q)&&tB();return}tB(),"steer"===e&&n?n(a.message,a.images,a.documents):"followup"===e&&s&&s(a.message,a.images,a.documents)},[ex,eK,eD,eq,eV,B,q,V,Y,n,s,tB,G]),ns=(0,i.useCallback)(e=>{let t=tK.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eX-1);if("right"===e)return Math.min(t,eX+1);let n=tj.current[eX];if(!n)return"down"===e?Math.min(t,eX+1):Math.max(0,eX-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,s=r.top+r.height/2,a=-1,l=1/0;for(let n=0;n<=t;n+=1){if(n===eX)continue;let t=tj.current[n];if(!t)continue;let r=t.getBoundingClientRect(),o=r.top+r.height/2-s;if("down"===e?o<=4:o>=-4)continue;let d=1e3*Math.abs(o)+Math.abs(r.left+r.width/2-i);d<l&&(a=n,l=d)}return a>=0?a:"down"===e?Math.min(t,eX+1):Math.max(0,eX-1)},[tK.length,eX]),na=(0,i.useCallback)(e=>{let r=e.nativeEvent,i=Date.now()-tw.current<100,a=ty.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(a||i)){i&&e.preventDefault();return}if(e6&&!a){if("ArrowDown"===e.key){e.preventDefault(),e9(e=>Math.min(Math.max(0,_.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),e9(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e3(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&_[e7]){e.preventDefault(),nt(_[e7]);return}}if(eY&&null!==tq){if("ArrowDown"===e.key){e.preventDefault(),eQ(ns("down"));return}if("ArrowUp"===e.key){e.preventDefault(),eQ(ns("up"));return}if("ArrowRight"===e.key){e.preventDefault(),eQ(ns("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),eQ(ns("left"));return}if("Escape"===e.key){e.preventDefault(),eZ(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&tK[eX]){e.preventDefault(),nn(tK[eX]);return}}if(e2&&null!==e0&&!a){if("ArrowDown"===e.key){e.preventDefault(),e8(e=>Math.min(Math.max(0,t5.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),e8(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e4(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&t5[e5]){e.preventDefault(),ne(t5[e5]);return}}if("ArrowUp"===e.key&&!a&&!l&&_.length>0&&0===ex.trim().length){e.preventDefault(),eZ(!1),e4(!1),e9(_.length-1),e3(!0);return}if("Escape"===e.key&&!a&&l&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),l&&(n||s)?ni(n?"steer":"followup"):tU())},[l,n,s,t,eY,tq,tK,eX,nn,ni,tU,ns,e2,e0,t5,e5,ne,e6,_,e7,nt,ex]),nl=(0,i.useCallback)(()=>{let e=td.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),no=(0,i.useCallback)(e=>{let t=function(e){let t=Array.from(e.files??[]);if(t.length>0)return t;let n=[];for(let t of Array.from(e.items??[])){if("file"!==t.kind)continue;let e=t.getAsFile();e&&n.push(e)}return n}(e.clipboardData);t.length&&(e.preventDefault(),tF(t))},[tF]);(0,i.useEffect)(()=>{if(null===tq){eZ(!1),eQ(0),tk.current=!1;return}eZ(!0),eQ(0),!tk.current&&q&&(tk.current=!0,Promise.resolve(q()).catch(()=>{tk.current=!1}))},[tq,q]),(0,i.useEffect)(()=>{if(!eY||!X)return;let e=!1;return tl({cwd:X,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;tl({cwd:X,values:n})}).catch(()=>{e||tl({cwd:X,values:{}})}),()=>{e=!0}},[eY,X]),(0,i.useEffect)(()=>{eX>=tK.length&&eQ(Math.max(0,tK.length-1))},[tK.length,eX]),(0,i.useEffect)(()=>{tj.current.length=tK.length},[tK.length]),(0,i.useEffect)(()=>{eY&&tj.current[eX]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eX,eY]);let nd=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(si):Object.entries(c??{}).map(([e,t])=>({provider:o?.provider??"unknown",modelId:e,name:t})).sort(si),nc=g??null,np=tX.bo.find(e=>e.alias===nc)?.provider??null,nh=np?nd.filter(e=>e.provider===np):nd,nf=(es=ej.trim().toLocaleLowerCase())?nh.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(es)):nh,ng=nh.length>8,nx=[];for(let e of nf){let t=nx.find(t=>t.provider===e.provider);t?t.options.push(e):nx.push({provider:e.provider,options:[e]})}let nv=np?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),nb=o?nv.find(e=>e.resolved?.provider===o.provider&&e.resolved?.modelId===o.modelId):void 0,ny=ej.trim()?[]:nh.map((e,t)=>{var n,r;return{option:e,order:t,count:eC[n=e.provider,r=e.modelId,`${n}/${r}`]??0}}).filter(e=>e.count>=2).sort((e,t)=>t.count-e.count||e.order-t.order).slice(0,5).map(({option:e,count:t})=>({option:e,count:t})),nw=(e,t,n)=>{let i=e.modelId===o?.modelId&&e.provider===o?.provider;return(0,r.jsxs)("button",{onClick:()=>{if(ey(!1),eS(""),!i||d){var t,n;let r=function(e,t){let n={...e,[t]:(e[t]??0)+1},r=Object.keys(n);if(r.length<=30)return n;for(let e of(r.sort((e,t)=>n[e]-n[t]),r)){if(Object.keys(n).length<=30)break;e!==t&&delete n[e]}return n}(i0(),(t=e.provider,n=e.modelId,`${t}/${n}`));try{window.localStorage.setItem(iQ,JSON.stringify(r))}catch{}eN(r),m?.(e.provider,e.modelId)}},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),e.name,void 0!==n&&n>=2&&(0,r.jsx)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10.5},children:eh("chat.modelPickCount",{count:n})})]},`${t}:${e.provider}:${e.modelId}`)},nk=o?nd.find(e=>e.modelId===o.modelId&&e.provider===o.provider)?.name??o.modelId:null,nj=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,nS=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:eh("chat.compacted")} ${tH(S.tokensBefore)} -> ${tH(S.estimatedTokensAfter)} tokens (${eh("chat.tokensSaved",{saved:tH(nj)})})`:null,nC=e=>{let t=L?.[e];return null!=t&&t!==e?t:null},nN="auto"===(ea=I??"auto")?M?`auto ≤ ${nC(M)??M}`:"auto":L?L[ea]??ea:ea,nI=(I??"auto")==="auto"&&T&&"auto"!==T?L?.[T]??T:null,nT=$&&nI?eh("chat.currentReasoning",{level:nI}):null,nM=e=>!E||E.includes(e),n$=[{level:"auto",ceiling:null},...sa.filter(nM).map(e=>({level:"auto",ceiling:e})),...ss.filter(e=>"auto"!==e&&nM(e)).map(e=>({level:e,ceiling:null}))],nR=Object.entries(i3).find(([,e])=>e===(C??"default"))?.[0]??"default";return(0,i.useEffect)(()=>{let e=e=>{tc.current&&!tc.current.contains(e.target)&&tu.current&&!tu.current.contains(e.target)&&(ey(!1),eS("")),tp.current&&!tp.current.contains(e.target)&&th.current&&!th.current.contains(e.target)&&eT(!1),tm.current&&!tm.current.contains(e.target)&&eE(!1),tf.current&&!tf.current.contains(e.target)&&eA(!1),tg.current&&!tg.current.contains(e.target)&&eP(!1),!tx.current||tx.current.contains(e.target)||td.current?.contains(e.target)||e3(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{eg||eP(!1)},[eg]),(0,r.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,r.jsx)("input",{ref:tb,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{tF(Array.from(e.target.files??[])),e.target.value=""}}),(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(sw,{error:p}),(0,r.jsx)(sk,{warnings:h}),D.length>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:em("delivery.title",{count:D.length})}),O&&ef&&(0,r.jsxs)("button",{onClick:O,title:eh("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),eh("chat.recall")]})]}),(0,r.jsx)(ij,{rows:D,removeLabel:eh("chat.queueRemove"),onRemove:H?(e,t)=>H("steer"===e?"steering":"followUp",t):void 0})]}),P&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--warning-soft)",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--warning)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),eh("chat.retrying",{attempt:P.attempt,max:P.maxAttempts}),P.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",P.errorMessage]})]}),nS&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--success-soft)",border:"1px solid var(--success-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--success)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),nS]}),j&&(0,r.jsx)("div",{role:"alert",style:{marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:j}),eB&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontSize:12,lineHeight:1.5},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"},children:eB}),(0,r.jsx)("button",{type:"button",onClick:()=>eU(null),"aria-label":eh("i18n.close"),title:eh("i18n.close"),style:{flexShrink:0,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"inherit",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,r.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(eD.length>0||eO.length>0)&&(0,r.jsxs)("div",{role:"list","aria-label":eh("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[eD.map((e,t)=>(0,r.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",display:"block"}}),(0,r.jsx)("button",{type:"button","aria-label":eh("chat.removeImage",{index:t+1}),onClick:()=>tP(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},`image-${t}`)),eO.map(e=>(0,r.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||void 0,style:{display:"flex",alignItems:"center",gap:7,minWidth:0,maxWidth:320,height:32,padding:"0 7px 0 9px"},children:["ready"!==e.status?(0,r.jsx)("span",{"aria-hidden":"true",style:{width:13,height:13,flexShrink:0,border:"1.5px solid var(--border-strong)",borderTopColor:"var(--accent)",borderRadius:"50%",animation:"spin 0.8s linear infinite"}}):nm(e.name,14),(0,r.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,r.jsx)("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:e.name}),(0,r.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===e.stored?eh("chat.attachKindAudio"):"file"===e.stored?eh("chat.attachKindFile"):sr[e.mimeType]," \xb7 ",nq(e.sourceSize??e.size),"extracting"===e.status?` \xb7 ${eh("chat.attachExtracting")}`:"","uploading"===e.status?` \xb7 ${eh("chat.attachUploading")}`:"","transcribing"===e.status?` \xb7 ${eh("chat.attachTranscribing")}`:"",e.transcriptFailed&&(0,r.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${eh("chat.attachTranscribeFailed")}`})]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>tD(e.id),"aria-label":eh("chat.removeAttachment",{name:e.name}),title:eh("chat.removeAttachment",{name:e.name}),style:{width:24,height:24,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,r.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},e.id))]}),(0,r.jsxs)("div",{ref:tv,style:{position:"relative",minWidth:0},children:[e6&&_.length>0&&(0,r.jsxs)("div",{ref:tx,style:{position:"absolute",left:0,right:0,...se(t3.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:t3.maxHeight},children:[(0,r.jsx)("div",{title:"Input history",style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,t3.maxHeight-31),overflowY:"auto",padding:4},children:_.map((e,t)=>{let n=t===e7;return(0,r.jsxs)("button",{ref:e=>{tC.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nt(e)},onMouseEnter:()=>e9(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),eY&&null!==tq&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...se(t7.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:t7.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:U?eh("chat.loadingCommands"):eh("chat.slashCommands",{label:tG})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,t7.maxHeight-34),overflowY:"auto",padding:10},children:U||0!==tV.length?tJ.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:eh(sc[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(({command:e,index:t})=>{let n=t===eX,i=sm(e,to);return(0,r.jsxs)("button",{ref:e=>{tj.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nn(e)},onMouseEnter:()=>eQ(t),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${n?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:n?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:i?"var(--text-dim)":void 0},children:["/",e.name,i&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:eh("chat.dormant")})]}),sh(e,eh)&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:sh(e,eh)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eh("chat.noCommands")})})]}),e2&&null!==e0&&(el=tn&&(!te||te.cwd!==X),eo=1===t5.length?eh("chat.match"):eh("chat.matches",{count:t5.length}),ed=te?.truncated&&!t4?e0.query?eh("chat.searchingAll"):eh("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...se(t9.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:t9.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:el?eh("chat.loadingFiles"):eh("chat.files",{label:eo,hint:ed})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,t9.maxHeight-34),overflowY:"auto",padding:4},children:el||0!==t5.length?t5.map((e,t)=>{let n=t===e5,i=e.path.split("/").pop()??e.path,s=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tS.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),ne(e)},onMouseEnter:()=>e8(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(nu,{size:14}):nm(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[s&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:s}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:t2&&!t4?eh("chat.searching"):eh("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:`chat-composer-field${eJ?" is-bash":""}${l?" is-streaming":""}`,style:{minWidth:0,display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:`1px solid ${eJ?"var(--tool-bg)":l&&(n||s)?"var(--warning-line)":"var(--border)"}`,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",boxShadow:"var(--seed-shadow-s1)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("textarea",{className:"chat-composer-textarea",ref:td,value:ex,onChange:e=>{tM.current=e.target.value,ev(e.target.value),e3(!1),tQ(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;tQ(t.value,t.selectionStart)},onKeyDown:na,onCompositionStart:()=>{ty.current=!0},onCompositionEnd:e=>{ty.current=!1,tw.current=Date.now();let t=e.currentTarget;tQ(t.value,t.selectionStart)},onInput:nl,onPaste:no,placeholder:l&&(n||s)?eh("chat.steerPlaceholder"):l?eh("chat.agentPlaceholder"):eh("chat.messagePlaceholder"),rows:1,style:{flex:1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:14,lineHeight:1.6,fontFamily:"inherit",minHeight:24,maxHeight:200,overflow:"auto"}}),l?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[n&&(0,r.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>ni("steer"),disabled:!tZ,title:eV?eh("chat.attachExtractingWait"):eh("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tZ?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:tZ?"var(--warning)":"var(--text-dim)",cursor:tZ?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),eh("chat.steer")]}),s&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>ni("followup"),disabled:!tZ,title:eV?eh("chat.attachExtractingWait"):eh("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tZ?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:tZ?"var(--accent-hover)":"var(--text-dim)",cursor:tZ?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),eh("chat.followUp")]})]}):(0,r.jsxs)("button",{className:"chat-composer-send",onClick:tU,disabled:!tZ,"aria-busy":eV||void 0,title:eV?eh("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",gap:6,padding:"7px 14px",background:tZ?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:tZ?"var(--accent-hover)":"var(--text-dim)",cursor:tZ?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),eh("chat.send")]})]})]}),eJ&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eG?"var(--text-muted)":"var(--accent)",marginTop:4},children:[eh("chat.shell")," \xb7 ",eG?eh("chat.outputLocal"):eh("chat.outputModel")]}),(0,r.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:eg?"1 1 0%":"0 0 auto",minWidth:eg?"min-content":0,display:"flex",alignItems:"center",gap:2},children:[(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eD.length||eO.length?" is-active":""}`,onClick:()=>tb.current?.click(),title:eh("chat.attachFile"),"aria-label":eh("chat.attachFile"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:"var(--radius-control)",color:eD.length||eO.length?"var(--accent)":"var(--text-muted)",cursor:"pointer",opacity:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=eD.length||eO.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=eD.length||eO.length?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),f&&tX.bo.length>0&&(0,r.jsxs)("div",{ref:tp,style:{position:"relative",flexShrink:+!!eg,minWidth:0},children:[(0,r.jsxs)("button",{className:`${eg?"composer-icon-button":"composer-chip"}${eI?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();e$({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ey(!1),eS(""),eT(e=>!e)},disabled:l||b,"aria-haspopup":"menu","aria-expanded":eI,onKeyDown:e=>{"Escape"===e.key&&eI&&(e.stopPropagation(),eT(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:eI?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l||b?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eI?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:eh("chat.mainPreset"),"aria-label":eh("chat.mainPreset"),children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 3l2.2 5.1 5.6.5-4.2 3.7 1.2 5.5L12 15l-4.8 2.8 1.2-5.5L4.2 8.6l5.6-.5z"})}),eg?null:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:eh("chat.mainPreset")})]}),eI&&eM&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=i1(eM.top,eM.bottom,e,i2(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eM.top+6}:{top:eM.bottom+6},s=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eM.left,width:"max-content",minWidth:eM.width};return(0,r.jsx)("div",{ref:th,role:"menu","aria-label":eh("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(eT(!1),tp.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...s,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:(0,r.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:tX.bo.map(e=>{let t=e.alias===nc;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eT(!1),f((0,tX.zq)(e))},title:`${e.provider}/${e.model}`,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:t?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("img",{className:"account-avatar",src:(0,tX.uk)(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,r.jsx)("span",{children:e.alias}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[e.provider,"/",e.model,void 0!==e.oauthPosition?` \xb7 OAuth ${e.oauthPosition}`:""]})]},e.alias)})})})})()]}),(nd.length>0||nk||p)&&m&&(0,r.jsxs)("div",{ref:tc,style:{position:"relative",flex:eg?"1 1 0%":void 0,width:eg?0:void 0,minWidth:44*!!eg},children:[(0,r.jsxs)("button",{className:`composer-chip${eb?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();ek({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ey(e=>(e&&eS(""),!e))},disabled:l||b,"aria-busy":b||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:eg?"flex-start":void 0,padding:eg?"8px 10px":"8px 12px",height:32,width:eg?"100%":void 0,maxWidth:eg?"100%":220,overflow:"hidden",background:eb?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l||b?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eb?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:b?"Switching model":nd.length>0?"Change model":"No available models",children:[b?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:nk??(nd.length>0?"Select model":"No models")})]}),eb&&ew&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=i1(ew.top,ew.bottom,e,i2(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ew.top+6}:{top:ew.bottom+6},s=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ew.left,width:"max-content",minWidth:ew.width};return(0,r.jsxs)("div",{ref:tu,style:{position:"fixed",...i,...s,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:[ng&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsx)("input",{value:ej,onChange:e=>eS(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eS(""),ey(!1))},placeholder:eh("chat.filterModels"),"aria-label":eh("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!eg,fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[ny.length>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eh("chat.frequentModels")}),ny.map(({option:e,count:t})=>nw(e,"frequent",t))]}),nv.length>0&&!ej.trim()&&v&&(0,r.jsxs)("div",{style:{borderTop:ny.length>0?"1px solid var(--border)":"none"},children:[(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eh("chat.modelRoles")}),nv.map(e=>{let t=nb?.role===e.role,n=e.resolved?.name??e.resolved?.modelId??"";return(0,r.jsxs)("button",{onClick:()=>{ey(!1),eS(""),v(e.role)},title:e.selector??n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,minWidth:58,padding:"1px 6px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-subtle)",color:t?"var(--accent)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:e.tag??e.role.toUpperCase()}),(0,r.jsx)("span",{style:{fontWeight:t?600:500},children:e.name}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[n,e.resolved?.thinkingLevel?` \xb7 ${e.resolved.thinkingLevel}`:""]})]},e.role)}),(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:"1px solid var(--border)"},children:eh("chat.allModels")})]}),0===nx.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:ej.trim()?eh("chat.noMatchingModels"):"No available models"}):nx.map((e,t)=>(0,r.jsxs)("div",{children:[nx.length>1&&(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:t>0?"1px solid var(--border)":"none"},children:e.provider}),e.options.map(e=>nw(e,"all"))]},e.provider))]})]})})()]}),$&&(0,r.jsxs)("div",{ref:tf,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,r.jsxs)("button",{type:"button",className:`${eg?"composer-icon-button":"composer-chip"}${eL?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eW({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ey(!1),eS(""),eT(!1),eA(e=>!e)},disabled:l||b,"aria-haspopup":"menu","aria-expanded":eL,onKeyDown:e=>{"Escape"===e.key&&eL&&(e.stopPropagation(),eA(!1))},title:eh("chat.changeReasoning",{level:nN}),"aria-label":eh("chat.changeReasoning",{level:nN}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eg?0:"8px 12px",height:32,background:eL?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l||b?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eL?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),eg?null:(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nN})]}),eL&&ez&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=i1(ez.top,ez.bottom,e,i2(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ez.top+6}:{top:ez.bottom+6},s=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ez.left,width:"max-content",minWidth:Math.max(180,ez.width)};return(0,r.jsx)("div",{role:"menu","aria-label":eh("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(eA(!1),tf.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...s,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:n},children:n$.map(({level:e,ceiling:t})=>{let n=(I??"auto")===e&&("auto"!==e||(M??null)===t),i=t??e,s="auto"===e&&null===t?null:nC(i),a=t?`auto ≤ ${s??t}`:s??e,l=t?eh("chat.thinkingAutoCapped",{level:s??t}):eh(sl[e]);return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{eA(!1),$(e,t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsxs)("span",{style:{flex:1},children:[a,null!==s&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",i,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:l})]},t?`auto-${t}`:e)})})})()]}),W&&(ec=z?eh("chat.fastModeBusy"):null===A?eh("chat.fastModeUnknown"):A.active?eh("chat.fastModeActive"):A.enabled?eh("chat.fastModeInactive"):eh("chat.fastModeOff"),eu=z||l||b,ep=A?.enabled===!0,(0,r.jsx)("button",{type:"button",className:`composer-icon-button${A?.active?" is-active":""}`,onClick:W,disabled:eu,"aria-pressed":null===A?void 0:A.enabled,"aria-busy":z||void 0,title:ec,"aria-label":ec,style:{flexShrink:0,opacity:l?.5:1},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:A?.active?"var(--accent)":"none",stroke:ep?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===A?"3 2":void 0,style:{opacity:ep&&!A?.active?.6:1},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})),!eg&&nT&&(0,r.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:nT}),(0,r.jsx)(iW,{sessionId:Q})]}),(0,r.jsxs)("div",{ref:tg,style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:eg?4:2},children:[eg?(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eF?" is-active":""}`,title:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eF,onClick:()=>{ey(!1),eS(""),eP(e=>!e)},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,r.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,r.jsx)(a.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:eF?void 0:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eF,onClick:()=>{ey(!1),eS(""),eP(e=>!e)},children:eh("chat.moreControls")}),(0,r.jsxs)("div",{role:"group","aria-label":eh("chat.moreControls"),style:{display:eF?"flex":"none",alignItems:"center",gap:1,position:"absolute",right:0,bottom:"100%",marginBottom:"var(--seed-dimension-x1)",zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"wrap",justifyContent:"flex-end",border:"1px solid var(--seed-color-stroke-neutral-muted)",borderRadius:"var(--seed-radius-r2)",background:"var(--seed-color-bg-layer-floating)",boxShadow:"var(--seed-shadow-s2)"},children:[!l&&N&&(0,r.jsxs)("div",{ref:tm,style:{position:"relative"},children:[(0,r.jsxs)("button",{className:`composer-chip${eR?" is-active":""}`,onClick:()=>!l&&eE(e=>!e),disabled:l,title:eh("chat.changeToolPreset")+`: ${nR}`,"aria-label":eh("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:eR?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eR?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nR})]}),eR&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",minWidth:120},children:i6.map(e=>{let t=i3[e],n=(C??"default")===t,i="off"===e?eh("chat.noTools"):"default"===e?eh("chat.builtInTools",{tools:i7}):eh("chat.allBuiltInTools",{tools:`${i7} + ${i9}`});return(0,r.jsxs)("button",{onClick:()=>{eE(!1),n||N(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:i})]},e)})})]}),!l&&y&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{className:`composer-chip${k?" is-active is-danger":""}`,onClick:k?w:y,disabled:l&&!k,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:k?"var(--danger-soft)":"none",border:"none",borderRadius:"var(--radius-control)",color:k?"var(--danger)":"var(--text-muted)",cursor:l&&!k?"not-allowed":"pointer",fontSize:12,opacity:l&&!k?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!l||k)&&(e.currentTarget.style.background=k?"var(--danger-soft)":"var(--bg-hover)",e.currentTarget.style.color=k?"var(--danger)":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=k?"var(--danger-soft)":"none",e.currentTarget.style.color=k?"var(--danger)":"var(--text-muted)"},title:k?eh("chat.stopCompaction"):eh("chat.compactContext"),"aria-label":k?eh("chat.stopCompaction"):eh("chat.compactContext"),children:k?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compact")})]})})}),eF&&(0,r.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:eh("chat.collapseControls"),"aria-label":eh("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eE(!1),eA(!1),eP(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),l&&(0,r.jsxs)("button",{className:"composer-chip is-danger is-active",onClick:t,title:eh("chat.stopAgent"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:32,background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--danger-soft)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),eh("chat.stop")]}),(0,r.jsx)(iA,{sessionId:Q,onEnsureSession:ee,onTranscriptPersisted:et}),void 0!==J&&(0,r.jsx)(iN,{soundEnabled:K??!0,onToggle:J})]})]}),eg&&nT&&(0,r.jsx)("div",{style:{marginTop:4,padding:"0 4px",fontSize:12,color:"var(--text-muted)",overflowWrap:"anywhere"},children:nT})]})]})});function sS({statuses:e}){if(0===e.length)return null;let t=[...e].sort((e,t)=>e.key.localeCompare(t.key)).map(({text:e})=>e.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()).join(" "),n=ex(t);return(0,r.jsx)("div",{role:"status","aria-label":n,title:n,style:{display:"flex",alignItems:"center",flexShrink:0,minWidth:0,height:36,padding:"0 12px",borderTop:"1px solid var(--border)",background:"transparent"},children:(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ek(t).map((e,t)=>(0,r.jsx)("span",{style:e.style,children:e.text},t))})})}function sC({phases:e}){let{t}=(0,R.s)(),[n,s]=(0,i.useState)(!1),[a,l]=(0,i.useState)(!1),{currentPhase:o,activeTask:d,remaining:c,completed:u,total:p,percent:h}=function(e){let t=0,n=0,r=null,i=null,s=null;for(let a of e)for(let e of a.tasks){if("completed"===e.status){t+=1;continue}"abandoned"!==e.status&&(n+=1,"in_progress"===e.status?r||(r={phase:a,task:e}):"blocked"===e.status?s||(s={phase:a,task:e}):i||(i={phase:a,task:e}))}let a=r??i??s,l=t+n;return{currentPhase:a?.phase??null,activeTask:a?.task??null,remaining:n,completed:t,total:l,percent:l>0?Math.round(t/l*100):null}}(e);if(0===p)return null;let m=0===c;return(0,r.jsxs)("div",{className:`todo-strip${m?" is-done":""}`,children:[(0,r.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":n,onClick:()=>s(e=>!e),children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:m?"✓":"›"}),o&&(0,r.jsx)("span",{className:"todo-strip-phase",children:o.name}),(0,r.jsx)("span",{className:"todo-strip-task",children:m?t("todo.allDone",{count:u}):d?.content??""}),(0,r.jsx)("span",{className:"todo-strip-count",children:m?t("todo.progressDone",{percent:h??0,completed:u,total:p}):t("todo.progress",{percent:h??0,completed:u,total:p,remaining:c})})]}),n&&(0,r.jsxs)("div",{className:"todo-strip-body",children:[e.map((t,n)=>{let i=t.tasks.filter(e=>a||"completed"!==e.status);return 0===i.length?null:(0,r.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[e.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:t.name}),i.map((e,t)=>(0,r.jsx)(no,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`)}),u>0&&(0,r.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":a,onClick:()=>l(e=>!e),children:t(a?"todo.hideCompleted":"todo.showCompleted",{count:u})})]})]})}function sN(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function sI(e){switch(e.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==e.closed;default:return!1}}async function sT(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let n={body:e.body,...e.tag?{tag:e.tag}:{}};if(t.getServiceWorkerRegistration)try{let r=await t.getServiceWorkerRegistration();if(r)return await r.showNotification(e.title,{...n,data:{url:e.sessionUrl}}),"service-worker"}catch{}try{let r=t.createWindowNotification(e.title,n);return r.onclick=()=>{r.close(),e.onClick()},"window"}catch{return null}}var sM=n(62503);class s$ extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function sR(e,t){let n=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)throw new s$(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let sE="ompweb-update-client-id",sL="ompweb-update-resume-intent-v2",sA="ompweb-update-return-v1",sz="cuelo-restart-return-v1",sW="ompweb:update-wake";function sF(e){return null===e||"running"===e?null:"failed"===e?3e4:8e3}function sP(){let e=sessionStorage.getItem(sE);if(e&&/^[A-Za-z0-9_-]{16,128}$/.test(e))return e;let t="function"==typeof crypto.randomUUID?crypto.randomUUID().replaceAll("-",""):Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("");return sessionStorage.setItem(sE,t),t}function sD(){let e=sessionStorage.getItem(sA);if(!e)return null;try{let t=JSON.parse(e);if(1!==t.schemaVersion||"string"!=typeof t.requestId||!/^[0-9a-f]{32}$/.test(t.requestId)||"string"!=typeof t.stageHash||!/^[0-9a-f]{64}$/.test(t.stageHash)||"boolean"!=typeof t.dismissed)return null;return t}catch{return null}}function s_(e){let t=sD();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(sA,JSON.stringify(n))}catch{}return n}async function sO(e){let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"heartbeat",clientId:sP(),sessionId:e.sessionId,resumeUrl:e.resumeUrl,preservationError:e.preservationError??null,...e.update?{requestId:e.update.requestId,stageHash:e.update.stageHash}:{}}),cache:"no-store"});if(!t.ok)throw Error(`maintenance heartbeat HTTP ${t.status}`);return await t.json()}async function sH(e){if(e.sessionId){let t=await fetch(`/api/sessions/${encodeURIComponent(e.sessionId)}?deferThinking=1&deferMedia=1`,{cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(!t.ok)throw Error(`session resume HTTP ${t.status}`);if((await t.json()).sessionId!==e.sessionId)throw Error("resumed session identity mismatch")}let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"resume-confirm",requestId:e.requestId,stageHash:e.stageHash,clientId:e.clientId,sessionId:e.sessionId}),cache:"no-store"});if(!t.ok)throw Error(`resume confirm HTTP ${t.status}`);let n=await t.json().catch(()=>null);!function(e){let t=sD();if(t&&t.requestId===e.requestId&&t.stageHash===e.stageHash)return;let n={schemaVersion:1,requestId:e.requestId,stageHash:e.stageHash,dismissed:!1};try{sessionStorage.setItem(sA,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),sessionStorage.removeItem(sL);let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(sW,{detail:{sessionId:e.sessionId}}))}function sB(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"update":return{isStreaming:!0,streamingMessage:t.message};case"end":case"reset":return{isStreaming:!1,streamingMessage:null};default:return e}}function sU(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function sq(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function sV(e){return t=>{let n=e?.isCompacting?e.compaction:null;if(!n)return t;let r=Date.now()-n.elapsedMs;return{startedAt:t?Math.min(t.startedAt,r):r,reason:t?.reason??n.reason}}}function sK(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.name!==i.name||r.tasks.length!==i.tasks.length)return!1;for(let e=0;e<r.tasks.length;e+=1){let t=r.tasks[e],n=i.tasks[e];if(!t||!n||t.content!==n.content||t.status!==n.status||t.blocker!==n.blocker)return!1}}return!0}function sJ(e,t){let n=new Map(e.map(e=>[e.id,e]));for(let e of t)n.set(e.id,e);let r=[...n.values()];return[...r.filter(e=>"pending"===e.status||"running"===e.status).sort((e,t)=>e.index-t.index||e.id.localeCompare(t.id)),...r.filter(e=>"pending"!==e.status&&"running"!==e.status).sort((e,t)=>t.lastUpdate-e.lastUpdate||e.id.localeCompare(t.id))].slice(0,128)}function sG(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function sY(e,t){for(let n=e.length-1;n>=0;n--){let r=t[n]??null;if(!eH(r??void 0))return{message:e[n],entryId:r}}return null}let sZ=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class sX extends Error{constructor(e){super("timeout"===e?"Timed out connecting to the agent event stream. Please try again.":"Failed to connect to the agent event stream. Please try again."),this.status=e,this.name="EventStreamConnectionError"}}function sQ(e){return new Promise(t=>setTimeout(t,e))}function s0(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function s1(e,t){switch(t.type){case"add":if(e.visible.some(e=>e.exiting)||e.visible.length>=5)return{visible:e.visible.some(e=>e.exiting)?e.visible:s0(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:s0(e.visible)};case"remove":return function(e,t){let n=e,r=t;for(;r.length>0&&n.length<5;){let[e,...t]=r;n=[...n,e],r=t}return r.length>0&&!n.some(e=>e.exiting)&&(n=s0(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function s2(e){if(!e||"object"!=typeof e||"image"!==e.type)return"";let t=e.source;return t&&"object"==typeof t?["url"===t.type?"url":"base64","string"==typeof t.media_type?t.media_type:"","string"==typeof t.data?t.data:"","string"==typeof t.url?t.url:""].join(":"):["base64","string"==typeof e.mimeType?e.mimeType:"","string"==typeof e.data?e.data:"",""].join(":")}function s4(e){let t,n=e.content;return"string"==typeof n?JSON.stringify({text:n,images:[]}):Array.isArray(n)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:n.map(s2).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function s5(e){return"user"===e.role?`user:${s4(e)}`:"bashExecution"===e.role?JSON.stringify({role:e.role,command:e.command,output:e.output,exitCode:e.exitCode,cancelled:e.cancelled,truncated:e.truncated,fullOutputPath:e.fullOutputPath,excludeFromContext:e.excludeFromContext}):JSON.stringify({role:e.role,content:e.content,model:e.model,provider:e.provider,customType:e.customType})}function s8(e,t){return e&&"object"==typeof e?"number"!=typeof e.tokensBefore||"number"!=typeof e.estimatedTokensAfter?null:{reason:t,tokensBefore:e.tokensBefore,estimatedTokensAfter:e.estimatedTokensAfter}:null}function s6(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}let s3={count:50,end:null};function s7(e,t){let n=Math.max(e,0),r=null===t.end?n:Math.min(Math.max(t.end,0),n),i=Math.min(Math.max(t.count,0),r),s=r-i;return{startIndex:s,endIndex:r,hasMore:s>0,hasLater:r<n}}function s9(e,t,n){let{startIndex:r,endIndex:i}=s7(e,n);if(t>=r&&t<i)return n;let s=Math.max(0,t-10),a=Math.max(t+1,s+50);return a>=e?{count:e-s,end:null}:{count:a-s,end:a}}function ae({sticker:e,text:t,tag:n,followRef:s}){let a=(0,i.useRef)(null);return((0,i.useEffect)(()=>{(!s||s.current)&&a.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,r.jsxs)("div",{ref:a,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,r.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:rG[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(rq(),{id:"ad10be785ccf4f7",children:".cue-bubble-sticker{transform-origin:center 75%;animation:cue-sticker-pop 200ms cubic-bezier(0,0,.15,1)both}@keyframes cue-sticker-pop{from{opacity:0;transform:scale(.88)}to{opacity:1;transform:scale(1)}}@media(prefers-reduced-motion:reduce){.cue-bubble-sticker{animation:none}}"})]}):null}function at(e){if("user"!==e.role)return null;let t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),n=(nU(t)?.message??t).trim();return n.length>0?n:null}function an(e){return`omp-cues:${e}`}function ar(e,t){let n=[];for(let r of t)r.sessionId===e&&null!==r.anchorEntryId&&n.push({id:r.id,anchorEntryId:r.anchorEntryId,sticker:r.sticker,text:r.text,tag:r.tag});try{window.localStorage.setItem(an(e),JSON.stringify(n.slice(-200)))}catch{}}let ai=[];function as(e){return`omp-web:interrupted-dismissed:${e}`}let aa=(0,i.memo)(function({messages:e,entryIds:t,toolResultsMap:n,modelNames:s,messageCwd:a,onOpenFile:l,sessionBusy:o,isNew:d,isStreaming:c,handleFork:u,forkingEntryId:p,handleNavigate:h,handleEditContent:m,sessionId:f,main:g,process:x,dispatchSlots:v,startIndex:b,endIndex:y,sentinelRef:w,laterSentinelRef:k,flashItem:j,t:S,onProcessLogChange:C,cues:N,cueFollowRef:I}){(0,i.useEffect)(()=>{C({groups:x,messages:e,entryIds:t,toolResults:n,modelNames:s,cwd:a,sessionId:f})},[C,x,e,t,n,s,a,f]);let T=(0,i.useMemo)(()=>{let t=new Map;for(let[r,i]of function(e,t,n,r){let i=new Map;e.forEach((e,t)=>{"answer"===e.kind&&i.set(e.idx,t)});let s=new Map,a=new Map;for(let e of t){let t=a.get(e.anchorIdx);for(let l of(t||(t=new Set,a.set(e.anchorIdx,t)),e.entries)){let e=n[l.idx];if(e?.role!=="assistant")continue;let a=Math.max(0,(l.blocks?i.get(l.idx):void 0)??l.afterMainIndex??-1),o=t;!function(e,t,n){for(let r of e){if("toolCall"!==r.type||"learn"!==r.toolName&&"manage_skill"!==r.toolName)continue;let e=t?.get(r.toolCallId);if(!e||e.isError)continue;let i=r.input??{};if("manage_skill"===r.toolName){let e=eV(i.action);if(!0===eq[e]){let t={kind:"skill",action:e,name:eV(i.name)};n(JSON.stringify(t),t)}continue}let s=eV(i.memory),a=i.skill,l=a?{action:eV(a.action),name:eV(a.name)}:void 0;n(JSON.stringify({kind:"lesson",memory:s,skill:l}),{kind:"lesson",memory:s.length>160?`${s.slice(0,160)}…`:s,...l?{skill:l}:{}})}}(l.blocks??e.content??[],r,(e,t)=>{if(o.has(e))return;o.add(e);let n=s.get(a);n?n.push(t):s.set(a,[t])})}}return s}(g,x,e,n)){let e=i.map(e=>{if("skill"===e.kind)return S("chat.savedSkill",{action:e.action,name:e.name});let t=S("chat.savedLesson",{memory:e.memory});return e.skill?`${t} (${S("chat.savedSkill",e.skill)})`:t});t.set(r,{role:"custom",customType:eD,content:[S("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[g,x,e,n,S]),M=(0,i.useMemo)(()=>{let t=null;if(o)for(let n of g)"message"===n.kind&&e[n.idx]?.role==="user"&&(t=n.idx);let r=new Map;for(let[i,s]of function(e,t,n){let r=new Map,i=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user").map(e=>e.idx),s=new Map;for(let[a,l]of(e.forEach((e,t)=>{"answer"===e.kind&&s.set(e.anchorIdx,t)}),s)){if(a===n)continue;let e=i.find(e=>e>a);r.set(l,{from:a+1,to:e??t.length})}return r}(g,e,t))r.set(i,function(e,t,n){let r=[],i=[];for(let n of e){if("toolCall"!==n.type)continue;if("task"===n.toolName){i.push(n);continue}if("bash"!==n.toolName)continue;let e="string"==typeof n.input.command?n.input.command.trim():"";if(!e||!rL.test(e))continue;let s=t.get(n.toolCallId),a=s?function(e){let t=e.details;if("number"==typeof t?.exitCode)return t.exitCode;let n=e.content.map(e=>"text"===e.type?e.text:"").join("\n"),r=/Command exited with code (-?\d+)\s*$/.exec(n.trimEnd());return r?Number(r[1]):null}(s):null,l=null===a?s?.isError?"failed":"unobserved":0===a?"passed":"failed";r.push({toolCallId:n.toolCallId,command:e,state:l,exitCode:a})}return{checks:r,dispatchCalls:i,files:eQ(e,t,n)}}(function(e,t,n){let r=[];for(let i=Math.max(0,t);i<Math.min(e.length,n);i++){let t=e[i];"assistant"===t.role&&r.push(...t.content??[])}return r}(e,s.from,s.to),n,a));return r},[g,e,n,a,o]),$=b>0,R=y<g.length,E=(i,g={})=>{let x=g.messageOverride??e[i],v=i-1;for(;v>=0&&eH(t[v]);)v-=1;let b="user"===x.role&&v>=0&&"assistant"===e[v].role?t[v]:void 0,y=g.keyPrefix??"message",w=!1;if("assistant"===x.role){w=!0;for(let t=i+1;t<e.length;t++){let n=e[t].role;if("user"===n)break;if("assistant"===n){w=!1;break}}w&&c&&i===e.length-1&&(w=!1)}return void 0!==g.showTimestamp&&(w=g.showTimestamp),(0,r.jsx)(rn,{message:x,toolResults:n,modelNames:s,cwd:a,onOpenFile:l,entryId:t[i],onFork:o||d||0===i&&"user"===x.role?void 0:u,forking:p===t[i],onNavigate:o?void 0:h,prevAssistantEntryId:o?void 0:b,onEditContent:m,showTimestamp:w,prevTimestamp:i>0?e[i-1].timestamp:void 0,sessionId:f,writtenFiles:g.writtenFiles,dispatchSlot:g.dispatchSlot,turnSummary:g.turnSummary},`${y}-view-${i}`)},L=(t,n)=>{let i=g[t],s="message"===i.kind&&e[i.idx]?.role==="user";return(0,r.jsx)("div",{"data-chat-item":t,"data-chat-question":s?"":void 0,className:j===t?"chat-item chat-jump-flash":"chat-item",children:n})};return(0,r.jsxs)(r.Fragment,{children:[$&&(0,r.jsx)("div",{ref:w,className:"py-3 text-center text-xs text-text-muted",children:S("chat.loadEarlier",{count:b})}),g.slice(b,y).map((s,o)=>{let d=b+o,c="message"===s.kind?s.anchorIdx??s.idx:s.anchorIdx,u=g[d+1],p=u?"message"===u.kind?u.anchorIdx??u.idx:u.anchorIdx:null,h=u?u.idx:1/0,m=N.filter(n=>{let r=null!==n.anchorEntryId?t.indexOf(n.anchorEntryId):Math.min(n.liveIndex??-1,e.length-1);return r>=s.idx&&r<h}).map(e=>(0,r.jsx)(ae,{sticker:e.sticker,text:e.text,tag:e.tag,followRef:I},`cue-${e.id}`)),x=p!==c,y=T.get(d),w=y?(0,r.jsx)(rn,{message:y,cwd:a,onOpenFile:l},`saved-lessons-${d}`):null,k=x?(0,r.jsx)(r9,{turnIndex:c,turnEntryId:t[c],sessionId:f,cwd:a,onOpenFile:l}):null;if("message"===s.kind)return(0,r.jsxs)(i.Fragment,{children:[L(d,E(s.idx)),w,k,m]},`message-${s.idx}`);let j=eQ(s.precedingBlocks,n,a);return(0,r.jsxs)(i.Fragment,{children:[L(d,E(s.idx,{keyPrefix:`answer-${s.runIndex}`,messageOverride:eM(e[s.idx],s.blocks),writtenFiles:j,dispatchSlot:v.get(d),turnSummary:M.get(d)})),w,k,m]},`answer-${s.idx}-${s.runIndex}`)}),R&&(0,r.jsx)("div",{ref:k,className:"py-3 text-center text-xs text-text-muted",children:S("chat.loadLater",{count:g.length-y})})]})});function al({session:e,newSessionCwd:t,initialSessionData:s,transitioning:a=!1,onAgentEnd:l,onAttentionNeeded:o,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsChange:f,onSessionStatsPanelOpen:g,onContextUsageChange:x,onSubagentsChange:b,onMainIdentityChange:y,onOpenWorkspaceView:w,onProcessLogChange:k,onOpenFile:j,transcriptReplacement:S,onComposerFocusChange:C,onSessionBusyChange:N,onWaitingChange:I,onAttentionChange:T,soundEnabled:M=!0,onSoundToggle:$,playCueSound:E=async()=>({sticker:null,text:null}),preloadCueSound:L,unlockAudio:A,jumpRequest:z=null,onJumpHandled:W}){var F,D;let _,O,H,{t:U}=(0,R.s)(),q=(0,i.useRef)(E);q.current=E;let V=(0,i.useRef)(null),K=(0,i.useRef)(L);K.current=L;let J=(0,i.useRef)(null),[G,Y]=(0,i.useState)([]),Z=(0,i.useRef)(G);Z.current=G;let X=(0,i.useRef)(0),Q=(0,i.useRef)([]),ee=(0,i.useRef)([]),et=(0,i.useRef)(null),en=(0,i.useRef)(0),er=(0,i.useRef)(-1),ei=(0,i.useRef)(-1),es=(0,i.useCallback)(()=>{let e=et.current?.current;return e?{sessionId:e,turn:en.current}:null},[]),ea=(0,i.useCallback)(e=>et.current?.current===e.sessionId&&en.current===e.turn,[]),el=(0,i.useCallback)((e,t,n,r)=>{if(!e.sticker&&!e.text)return;X.current=Math.max(X.current+1,Date.now());let i={id:X.current,sticker:e.sticker,text:e.text,tag:t,sessionId:n.sessionId},s="entry"===r.kind?{...i,anchorEntryId:r.entryId}:{...i,anchorEntryId:null,liveIndex:r.liveIndex,intent:r.intent};Y(e=>{let t=[...e,s];return null!==s.anchorEntryId&&ar(n.sessionId,t),t})},[]),eo=(0,i.useCallback)((e,t,n,r)=>{let i=()=>ea(n)&&("working"!==t||ei.current!==n.turn);i()&&q.current(e,t,i).then(e=>{null!==t&&null!==r&&i()&&el(e,t,n,r)}).catch(()=>{})},[ea,el]),ed=(0,i.useCallback)(async(e,t,n)=>{let r=t9(e,t,n);if(r||!t)return r?.alias??null;let i=J.current;if(i&&i.sessionId===e&&i.provider===t)return i.alias;try{let{data:n}=await (0,tX.ST)(e),r=n?.state==="resolved"&&n.provider===t?n.credentialId:void 0,i=t9(e,t,r)?.alias??null;return i&&(J.current={sessionId:e,provider:t,alias:i},K.current?.(i)),i}catch{return null}},[]),ec=(0,i.useCallback)((e,t,n,r)=>{let i=function(e,t){let n=e.length-1;if(n<0)return null;let r=Math.min(e.length,t.length);if(n<r)return{kind:"entry",entryId:t[n]};let i=r4(e[n]),s=0;for(let t=r;t<=n;t++)r4(e[t])===i&&(s+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:i,occurrence:s}}}(Q.current,ee.current);ed(t.sessionId,n,r).then(n=>{eo(n,e,t,i)})},[eo,ed]),[eu,ep]=(0,i.useState)(0),eh=(0,i.useRef)([]),em=(0,i.useCallback)(e=>{if(en.current+=1,null!==rZ(e.outcome)){let t=e.sessionId;eh.current.push({completion:e,trigger:t?{sessionId:t,turn:en.current}:null}),ep(e=>e+1)}l?.(e)},[l]);(0,i.useEffect)(()=>{for(let{completion:e,trigger:t}of eh.current.splice(0)){let n=rZ(e.outcome),r="neutral"===n?null:n;t?ec(r,t,e.provider,e.credentialId):q.current(null,r).catch(()=>{})}},[eu,ec]);let ef=(0,i.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:eg,error:ev,messages:eb,entryIds:ey,streamState:ew,agentRunning:ek,bashRunning:ej,pendingBash:eS,modelNames:eC,modelList:eN,modelError:eI,modelScopeWarnings:eT,modelThinkingLevels:e$,modelThinkingLevelMaps:eA,modelRoles:eW,toolPreset:eF,thinkingLevel:eD,effectiveThinkingLevel:eq,thinkingCeiling:eV,fastMode:eJ,fastModeBusy:eG,handleFastModeToggle:eY,retryInfo:eZ,contextUsage:eX,forkingEntryId:eQ,isCompacting:e1,compaction:e2,compactError:e4,compactResult:e5,displayModel:e8,modelSwitching:e6,sessionStats:e3,runStateKnown:e7,slashCommands:e9,slashCommandsLoading:te,deliveryRows:tt,subagents:tn,todoPhases:tr,notices:ti,extensionDialog:ts,extensionResponse:ta,extensionCustomUi:tl,extensionStatuses:to,extensionWidgets:td,respondToExtensionUi:tc,sendExtensionCustomInput:tu,isAutoModelSelection:tp,agentPhase:th,isNew:tm,autoFollowPaused:tf,resumeAutoFollow:tg,pauseAutoFollow:tx,goalStatus:tv,sessionIdRef:tb,messagesEndRef:ty,scrollContainerRef:tw,handleSend:tk,handleAbort:tj,handleFork:tS,handleNavigate:tC,handleModelChange:tN,handleRoleModelChange:tI,handleMainPresetChange:tT,newSessionAccount:tM,handleCompact:t$,handleSteer:tR,handleFollowUp:tE,handlePromptWithStreamingBehavior:tL,handleAbortCompaction:tA,handleRecallQueue:tz,handleRemoveQueuedMessage:tW,handleBuiltinSlashCommand:tF,handleToolPresetChange:tP,handleThinkingLevelChange:tD,loadSlashCommands:t_,ensureNewSession:tO,refreshLiveTranscript:tH}=function(e){let{session:t,newSessionCwd:r,initialData:s,onAgentEnd:a,onAttentionNeeded:l,onSessionCreated:o,onSessionForked:d,modelsRefreshKey:c,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,m=null===t&&null!==r,f=s&&s.sessionId===t?.id?s:null,[g,x]=(0,i.useState)(f),[v,b]=(0,i.useState)(!m&&!f),[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(f?.leafId??null),[S,C]=(0,i.useState)(f?.context.messages??[]),[N,I]=(0,i.useState)(f?.context.entryIds??[]),[T,M]=(0,i.useReducer)(sB,{isStreaming:!1,streamingMessage:null}),[$,R]=(0,i.useState)(!1),[E,L]=(0,i.useState)(!1),[A,z]=(0,i.useState)(null),[W,F]=(0,i.useState)({}),[P,D]=(0,i.useState)([]),[_,O]=(0,i.useState)(null),[H,B]=(0,i.useState)([]),[U,q]=(0,i.useState)({}),[V,K]=(0,i.useState)({}),[J,G]=(0,i.useState)([]),[Y,Z]=(0,i.useState)(null),[X,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(null),[en,er]=(0,i.useState)("default"),[ei,es]=(0,i.useState)(()=>{let e=f?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[ea,el]=(0,i.useState)(),[eo,ed]=(0,i.useState)(null),[ec,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(!1),em=(0,i.useRef)(0),ef=(0,i.useRef)(""),[eg,ev]=(0,i.useState)(null),[eb,ey]=(0,i.useState)(f?.contextUsage??null),[ew,ek]=(0,i.useState)(null),[ej,eS]=(0,i.useState)(null),[eC,eN]=(0,i.useState)(null),[eI,eT]=(0,i.useState)(null),[eM,e$]=(0,i.useState)(!1),[eR,eE]=(0,i.useState)(!1),[eL,eA]=(0,i.useState)(null),[ez,eW]=(0,i.useState)(null),[eF,eD]=(0,i.useState)(null),e_=(0,i.useRef)(null),[eU,eq]=(0,i.useState)(!1),[eV,eK]=(0,i.useState)(null),[eJ,eG]=(0,i.useState)([]),[eY,eZ]=(0,i.useState)(!1),[eX,eQ]=(0,i.useReducer)(s1,{visible:[],pending:[]}),[e0,e1]=(0,i.useState)(null),[e2,e4]=(0,i.useState)(null),[e5,e8]=(0,i.useState)(null),e6=(0,i.useRef)(null),[e3,e7]=(0,i.useState)(null),[e9,te]=(0,i.useState)([]),[tt,tn]=(0,i.useState)([]),[tr,ti]=(0,i.useState)({steering:[],followUp:[]}),[ts,ta]=(0,i.useState)([]),[tl,to]=(0,i.useReducer)(iy,[]),td=(0,i.useRef)(0);(0,i.useEffect)(()=>{to({type:"queue",steering:tr.steering,followUp:tr.followUp})},[tr]),(0,i.useEffect)(()=>{$||to({type:"idle"})},[$]),(0,i.useEffect)(()=>{to({type:"reset"})},[t?.id]);let tc=(0,i.useMemo)(()=>(function(e,t){let n=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${iv(t)}`;n.set(e,(n.get(e)??0)+1)}let r=[],i=(e,t)=>{t.forEach((t,i)=>{let s=`${e}\u0000${ix(t)}`,a=n.get(s)??0;a>0?n.set(s,a-1):r.push({key:`queue-${e}-${i}`,kind:e,text:t,images:0,stage:"accepted",removable:!0})})};for(let n of(i("steer",t?.steering??[]),i("followUp",t?.followUp??[]),e))r.push({key:`sent-${n.id}`,kind:n.kind,text:n.text,images:n.images,stage:n.stage,removable:n.inQueue});return r})(tl,tr),[tl,tr]),[tu,tp]=(0,i.useState)(null),th=(0,i.useRef)(null),tm=(0,i.useRef)(null),tf=(0,i.useRef)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(0),tb=(0,i.useRef)(!1),ty=(0,i.useRef)(t?.id??null),tw=(0,i.useRef)(f?.leafId??null),tk=(0,i.useRef)(S),tj=(0,i.useRef)(N);tk.current=S,tj.current=N;let tS=(0,i.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),tC=(0,i.useRef)(!1),tN=(0,i.useRef)(!1),tI=(0,i.useRef)(!1),tT=(0,i.useRef)(-1),tM=(0,i.useRef)("unknown"),t$=(0,i.useRef)(null),tR=(0,i.useRef)(null),tE=(0,i.useRef)(0),tL=(0,i.useRef)(!1),tA=(0,i.useRef)(0),tz=(0,i.useRef)(null),tW=(0,i.useRef)(null),tF=(0,i.useRef)(null),tP=(0,i.useRef)(!1),tD=(0,i.useRef)(!0),[t_,tO]=(0,i.useState)(!1),[tH,tB]=(0,i.useState)(null),tU=(0,i.useRef)(void 0),tq=(0,i.useRef)(0),tV=(0,i.useRef)(0),tK=(0,i.useRef)(()=>{}),tJ=(0,i.useRef)(null),tG=(0,i.useRef)(null),tY=(0,i.useRef)(null),tZ=(0,i.useRef)(!1),tX=(0,i.useRef)(null),tQ=(0,i.useRef)(null),t0=(0,i.useRef)(null),t1=(0,i.useRef)(null),t2=(0,i.useRef)(null),t4=(0,i.useRef)(!1);t4.current=e.transitioning??!1;let t5=(0,i.useRef)(Date.now()),t8=(0,i.useRef)(0),t6=(0,i.useRef)(0),t3=(0,i.useRef)(null),t7=(0,i.useRef)(!1),t9=(0,i.useRef)(Promise.resolve()),ne=e.setToolPreset??er,nt=eC??g?.context.model??eI??null,nn=m?Y??ee:nt,nr=(0,i.useMemo)(()=>{if(e0)return{...e0,totalActiveMs:g?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},n=0,r=0,i=0,s=0,a=0;for(let t of S){if("user"===t.role&&(r+=1),"toolResult"===t.role&&(s+=1),"assistant"!==t.role)continue;i+=1;let l=t.usage;a+=t.content.filter(e=>"toolCall"===e.type).length,l&&(e.input+=l.input??0,e.output+=l.output??0,e.cacheRead+=l.cacheRead??0,e.cacheWrite+=l.cacheWrite??0,n+=l.cost?.total??0)}return(e.total=e.input+e.output+e.cacheRead+e.cacheWrite,0===e.total&&0===S.length)?null:{sessionFile:g?.filePath||void 0,sessionId:ty.current??t?.id??"",sessionName:t?.name,userMessages:r,assistantMessages:i,toolCalls:a,toolResults:s,totalMessages:S.length,tokens:e,cost:n,totalActiveMs:g?.totalActiveMs,...eb?{contextUsage:eb}:{}}},[S,e0,eb,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),ni=(0,i.useRef)(0),ns=(0,i.useCallback)((e,t)=>{e&&ty.current===e&&Array.isArray(t)&&(ni.current+=1,tp(n=>n?.sid===e&&sK(n.phases,t)?n:{sid:e,phases:t}))},[]),na=(0,i.useCallback)((e,t,n)=>{ty.current===e&&ni.current===n&&Array.isArray(t)&&tp(n=>n?.sid===e&&sK(n.phases,t)?n:{sid:e,phases:t})},[]),nl=(0,i.useCallback)(e=>{let t="function"==typeof e?e(tk.current):e;tk.current=t,C(t)},[]),no=(0,i.useCallback)(e=>{tj.current=e,I(e)},[]),nd=(0,i.useCallback)(async(e,t=!1,n=!1,r)=>{let i=!1;try{t&&b(!0);let s=r??null;if(!s){let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),r=await fetch(`/api/sessions/${encodeURIComponent(e)}?${n}`);if(404===r.status)return t&&(x(null),j(null),nl([]),w(null)),null;if(!r.ok)throw Error(`HTTP ${r.status}`);s=await r.json()}if(ty.current!==e)return null;x(s),j(s.leafId),tw.current=s.leafId??null;let a=eB(s.context.messages,s.context.entryIds??[],tS.current.sessionId===e?tS.current.outputs:[]);if(nl(a.messages),no(a.entryIds),ey(s.contextUsage??null),eN(e=>t7.current?e:null),w(null),es(s.context.configuredThinkingLevel??s.context.thinkingLevel??"off"),el(s.context.thinkingLevel),ed(s.context.thinkingCeiling??null),i=!0,t&&b(!1),!n)return null;try{let t=ni.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(ty.current!==e)return null;let i=r.state;return i?(void 0!==i.contextUsage&&ey(i.contextUsage??null),void 0!==i.systemPrompt&&ek(i.systemPrompt??null),void 0!==i.thinkingLevel&&(es(i.configuredThinkingLevel??i.thinkingLevel),el(i.thinkingLevel)),void 0!==i.thinkingCeiling&&ed(i.thinkingCeiling??null),void 0!==i.extensionStatuses&&te(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&tn(i.extensionWidgets??[]),void 0!==i.queuedMessages&&ti(sU(i.queuedMessages)),void 0!==i.subagents&&ta(e=>sJ(e,i.subagents??[])),na(e,i.todoPhases,t)):r.running||ti({steering:[],followUp:[]}),r}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),null}finally{t&&!i&&b(!1)}},[na,no,nl]),nc=(0,i.useCallback)(e=>{let t=t9.current.then(async()=>{ty.current===e&&await nd(e)});return t9.current=t.catch(()=>{}),t},[nd]),nu=(0,i.useCallback)(async(e,t)=>{try{let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&n.set("leafId",t);let r=`/api/sessions/${encodeURIComponent(e)}/context?${n}`,i=await fetch(r);if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json();tw.current=t;let a=eB(s.context.messages,s.context.entryIds??[],tS.current.sessionId===e?tS.current.outputs:[]);nl(a.messages),no(a.entryIds),ey(s.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[no,nl]),np=(0,i.useCallback)(async e=>{try{let t=await sR(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));ne(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[ne]),nh=(0,i.useCallback)((e=0,t="(no messages)")=>{let n=ty.current;m&&r&&n&&!tZ.current&&(tZ.current=!0,o?.({id:n,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t,transient:!0}))},[m,r,o]),nm=(0,i.useCallback)(async()=>{if(tY.current)return tY.current;let e=ty.current;if(e&&t2.current!==e||!e&&(!m||!r))return e;let t=(async()=>{let t=e;if(!t){let e=tX.current,n=t0.current,i=tQ.current;e&&eT(e);let s=(0,i5.xG)(en),a=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r,type:"ensure_session",toolNames:s,...e?{provider:e.provider,modelId:e.modelId}:{},...n?{thinkingLevel:n}:{},...e&&null!==i?{oauthPosition:i}:{}})});if(!a.ok)throw Error(`HTTP ${a.status}`);let l=await a.json();t=l.sessionId,ty.current=t,null!==t1.current&&(t2.current=t),l.model&&tX.current===e&&(eT(l.model),e||et(l.model)),l.thinkingLevel&&t0.current===n&&(es(l.configuredThinkingLevel??l.thinkingLevel),el(l.thinkingLevel))}for(;t2.current===t;){let e=t1.current;await sR(t,{type:"set_thinking_ceiling",ceiling:e}),t1.current===e&&t2.current===t&&(t2.current=null)}return t})();tY.current=t;try{return await t}finally{tY.current=null}},[m,r,en]),nf=(0,i.useCallback)(async()=>{let e=ty.current??await nm();if(!e)return eG([]),[];eZ(!0);try{let t=await sR(e,{type:"get_commands"}),n=t?.commands??[];return eG(n),n}catch(e){return console.error("Failed to load slash commands:",e),eG([]),[]}finally{eZ(!1)}},[nm]),ng=(0,i.useCallback)(()=>{tv.current+=1,tb.current=!1,tx.current&&(clearTimeout(tx.current),tx.current=null)},[]),nx=(0,i.useCallback)(()=>{th.current?.close(),th.current=null,tm.current=null,tf.current=null},[]),nv=(0,i.useCallback)(()=>{tg.current?.close(),tg.current=null},[]),nb=(0,i.useCallback)(e=>{nv();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);tg.current=t,t.onmessage=t=>{try{let n=JSON.parse(t.data);"session_snapshot"===n.type?tz.current?.(n):"agent_start"===n.type&&tW.current?.(e)}catch{}}},[nv]),ny=(0,i.useCallback)(e=>{nx();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);th.current=t,tm.current=e;let n=new Promise(n=>{let r=!1,i=e=>{r||(r=!0,clearTimeout(s),tf.current?.source===t&&(tf.current.pending=!1),n({status:e,source:t}))},s=setTimeout(()=>i("timeout"),5e3);t.onmessage=e=>{try{let t=JSON.parse(e.data);"update_maintenance"===t.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:t})),"connected"===t.type&&i("connected"),tz.current?.(t)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(i("closed"),th.current===t&&(tC.current||tb.current))){th.current=null,tm.current=null,tf.current=null;let t=tv.current;setTimeout(()=>{t===tv.current&&!th.current&&(tC.current||tb.current)&&ny(e)},1e3)}}});return tf.current={source:t,promise:n,pending:!0},n},[nx]),nw=(0,i.useCallback)(async e=>{let t=th.current;if(t&&tm.current===e){if(t.readyState===EventSource.OPEN)return;let e=tf.current;if(e?.source===t&&e.pending&&(await e.promise,th.current===t&&t.readyState===EventSource.OPEN))return}let n=await ny(e);if("connected"!==n.status&&n.source.readyState!==EventSource.OPEN)throw th.current===n.source&&(th.current=null),tm.current===e&&(tm.current=null),tf.current?.source===n.source&&(tf.current=null),n.source.close(),new sX(n.status)},[ny]),nk=(0,i.useCallback)(async(e,t)=>{let n=e6.current;if(n?.id===e.id&&"sending"===n.status)return;let r=ty.current,i=e=>{e6.current=e,e8(e)};if(!r)return void i({id:e.id,status:"failed",error:"no session"});i({id:e.id,status:"sending"});try{await sR(r,{type:"extension_ui_response",id:e.id,...t})}catch(t){i({id:e.id,status:"failed",error:t instanceof Error?t.message:String(t)});return}i(null),e4(t=>t?.id===e.id?null:t)},[]),nj=(0,i.useCallback)(async(e,t)=>{let n=ty.current;if(n)try{await sR(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),nS=(0,i.useCallback)(e=>{let t=e.message.trim();t&&eQ({type:"add",notice:{id:e.id??("u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`),message:t,type:e.type??"info"}})},[]),nC=(0,i.useCallback)(e=>{let t={role:"custom",customType:eP,content:ex(e).trim(),display:!0,timestamp:Date.now()},n=tS.current,r=ty.current;n.sessionId!==r&&(n.sessionId=r,n.outputs=[]);let i=tj.current.slice(0,tk.current.length),s=null;for(let e=i.length-1;e>=0;e--)if(!eH(i[e])){s=i[e];break}n.seq+=1,n.outputs.push({entryId:`${eO}${n.seq}`,baseEntryId:s,message:t}),nl(e=>[...e,t])},[nl]),nN=(0,i.useCallback)(t=>{if("custom"!==t.method&&"closed"in t&&t.closed){e4(e=>e?.id===t.id?null:e),e6.current?.id===t.id&&(e6.current=null,e8(null));return}switch(sI(t)&&l?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":e4(t);break;case"notify":nS({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":te(e=>{let n=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...n,{key:t.statusKey,text:t.statusText}]:n});break;case"setWidget":tn(e=>{let n=e.filter(e=>e.key!==t.widgetKey);return t.widgetLines?[...n,{key:t.widgetKey,lines:t.widgetLines,placement:t.widgetPlacement??"aboveEditor"}]:n});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":e7(e=>t.closed?e?.id===t.id?null:e:t)}},[nS,l,e.chatInputRef]),nI=(0,i.useCallback)(()=>{let e=tC.current;return tC.current=!1,R(!1),eK(null),ev(null),M({type:"end"}),e},[]),nT=(0,i.useCallback)(()=>{tM.current="unknown",t$.current=null;let e=sY(tk.current,tj.current);tR.current=e?{entryId:e.entryId,key:s5(e.message)}:null,tE.current+=1},[]),nM=(0,i.useCallback)(()=>{let e=tM.current,t=t$.current;if("unknown"===e){let n=sY(tk.current,tj.current),r=n?.message,i=tR.current;null!==n&&(null===i||(null!==n.entryId&&null!==i.entryId?n.entryId!==i.entryId:s5(n.message)!==i.key))&&r?.role==="assistant"&&r.stopReason&&(e=sG(r),t??={provider:r.provider,...void 0!==r.credentialId?{credentialId:r.credentialId}:{}})}return{outcome:e,sessionId:ty.current,...t?{provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),n$=(0,i.useCallback)(e=>{let t=nM();if("unknown"!==t.outcome||!e)return void a?.(t);let n=tE.current;e.catch(()=>void 0).then(()=>{let e=ty.current===t.sessionId&&tE.current===n;a?.(e?nM():t)})},[a,nM]),nR=(0,i.useCallback)((e,t)=>tT.current!==e&&(tT.current=e,n$(t),!0),[n$]),nE=(0,i.useCallback)(e=>{ng(),tb.current=!0;let t=tv.current,n=async()=>{if(t===tv.current&&ty.current===e&&tb.current)try{let r=ni.current,i=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json();if(t!==tv.current||ty.current!==e||!tb.current)return;let a=s.state;if(ta(e=>sJ(e,a?.subagents??[])),na(e,a?.todoPhases,r),s.running&&a&&(a.isStreaming||a.isPromptRunning||a.isHandoffRunning)){tb.current=!1,tx.current=null,tN.current=!!a?.isStreaming,tI.current=!!a?.isPromptRunning,tC.current=!0,R(!0),eK(a?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(s.running&&a?.isCompacting){eE(!0),eD(sV(a)),tx.current=setTimeout(()=>void n(),600);return}if(s.running&&(a?.subagents?.length??0)>0){tx.current=setTimeout(()=>void n(),1e3);return}tb.current=!1,tx.current=null,nx()}catch{if(t!==tv.current||ty.current!==e||!tb.current)return;tx.current=setTimeout(()=>void n(),600)}};tx.current=setTimeout(()=>void n(),3e4)},[na,ng,nx]),nL=(0,i.useCallback)(async(e=ty.current,t=t8.current)=>{if(t8.current===t)try{e&&await nd(e)}finally{if(t8.current!==t)return;let n=tI.current,r=tN.current;tI.current=!1,tN.current=!1,t3.current=null;let i=nI();n?nR(t):r&&i&&n$(),e&&nE(e)}},[nd,n$,nR,nE,nI]),nA=(0,i.useCallback)(async(e,t)=>{await sQ(800);let n=Date.now();for(;tC.current&&Date.now()-n<2e4;){if(void 0!==t&&t8.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await nL(e,t)}}catch{}await sQ(600)}},[nL]),nz=(0,i.useCallback)(async e=>{let t=tA.current+1;for(tA.current=t;tL.current&&tA.current===t&&ty.current===e;){await sQ(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(r.state?.isBashRunning)continue;if(await nd(e),tA.current!==t||ty.current!==e)return;tL.current=!1,L(!1),z(null);return}catch{}}},[nd]),nW=(0,i.useCallback)(async e=>{if(!tC.current)return;let t=t8.current;try{let n=ni.current,r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(t8.current!==t)return;let s=i.state;if(eE(s?.isCompacting??!1),eD(sV(s)),ti(sU(s?.queuedMessages)),s?.contextUsage!==void 0&&ey(s.contextUsage??null),ta(e=>sJ(e,s?.subagents??[])),na(e,s?.todoPhases,n),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isCompacting||s.isHandoffRunning)||!tC.current)return;s&&(void 0!==s.systemPrompt&&ek(s.systemPrompt??null),void 0!==s.extensionStatuses&&te(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tn(s.extensionWidgets??[])),await nL(e,t)}catch{}},[na,nL]),nF=(0,i.useCallback)(async e=>{let t=await nd(e,!1,!0),n=t?.state;return!!t?.running&&!!n&&ty.current===e&&!tC.current&&!!(n.isStreaming||n.isPromptRunning||n.isHandoffRunning)&&(tN.current=!!n.isStreaming,tI.current=!!n.isPromptRunning,tC.current=!0,R(!0),eK(n.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),M({type:"start"}),ny(e),!n.isStreaming&&n.isPromptRunning&&nA(e),!0)},[ny,nd,nA]),nP=(0,i.useCallback)(async(e,t=t8.current)=>{let n=t6.current+1;t6.current=n;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(n!==t6.current||ty.current!==e||t8.current!==t)return;i.state?.contextUsage!==void 0&&ey(i.state.contextUsage??null)}catch{}},[]);(0,i.useEffect)(()=>{if(!eR){e_.current=null,eD(null);return}eD(e=>e??{startedAt:Date.now(),reason:e_.current})},[eR]),(0,i.useEffect)(()=>{if(!$&&!eR)return;let e=()=>{let e=ty.current;e&&nP(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[$,eR,nP]),(0,i.useEffect)(()=>{if(!$)return;let e=()=>{let e=ty.current;e&&nW(e)},t=()=>{"visible"===document.visibilityState&&e()},n=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[$,nW]),(0,i.useEffect)(()=>{if($)return;let e=()=>{let e=ty.current;e&&!tC.current&&nF(e)},t=()=>{"visible"===document.visibilityState&&e()},n=e=>{let t=ty.current,n=e.detail?.sessionId;t&&n===t&&!tC.current&&nF(t).then(e=>{e||ty.current!==t||tC.current||nd(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(sW,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(sW,n)}},[$,nF,nd]),tW.current=e=>{if(ty.current!==e||tC.current||th.current||tF.current)return;let t=nF(e).then(async t=>{t||ty.current!==e||tC.current||await nd(e)}).catch(()=>{}).finally(()=>{tF.current===t&&(tF.current=null)});tF.current=t},(0,i.useEffect)(()=>{tC.current=$},[$]),tz.current=(0,i.useCallback)(e=>{switch(e.type){case"session_snapshot":{let t=function(e,t,n,r,i){if("session_snapshot"!==e.type||"string"!=typeof e.sessionId||e.sessionId!==t||"string"!=typeof e.entryId||""===e.entryId||e.entryId===n||!e.context||!Array.isArray(e.context.messages)||!Array.isArray(e.context.entryIds)||e.context.messages.length!==e.context.entryIds.length)return null;let s=e.context.messages,a=new Map;for(let e of s){let t=s5(e);a.set(t,(a.get(t)??0)+1)}let l=Math.min(r.length,i.length);for(let e of r.slice(0,l)){let t=s5(e),n=a.get(t)??0;n>0&&a.set(t,n-1)}let o=r.slice(l).filter(e=>{let t=s5(e),n=a.get(t)??0;return 0===n||(a.set(t,n-1),!1)});return{entryId:e.entryId,messages:[...s,...o],entryIds:[...e.context.entryIds]}}(e,ty.current,tw.current,tk.current,tj.current);if(!t)break;tw.current=t.entryId;let n=eB(t.messages,t.entryIds,tS.current.sessionId===ty.current?tS.current.outputs:[]);nl(n.messages),no(n.entryIds);break}case"agent_start":{let e=!tC.current;ng(),e&&nT(),tN.current=!0,tC.current=!0,R(!0),eK({kind:"waiting_model"}),M({type:"start"});break}case"agent_end":if(!tC.current)break;if(eK(null),ev(null),M({type:"end"}),ty.current){nd(ty.current);let e=ni.current;fetch(`/api/agent/${encodeURIComponent(ty.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&ey(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&ek(t.state.systemPrompt??null),t.state?.extensionStatuses!==void 0&&te(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&tn(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&ta(e=>sJ(e,t.state?.subagents??[])),ty.current&&na(ty.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tB(t.state.goal??null),ti(sU(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tB(e.status??null);break;case"agent_settled":{let e=tN.current;if(tN.current=!1,!e||tI.current)break;let t=ty.current,n=nI();eE(!1);let r=t?nd(t):void 0;t&&nE(t),n&&n$(r);break}case"prompt_done":{let e=t8.current,t=tI.current;tI.current=!1,t3.current=null;let n=tT.current!==e;if(!t&&!n)break;let r=ty.current;nR(e,r?nd(r):void 0),!tN.current&&(nI(),r&&nE(r))}break;case"prompt_error":tM.current="failed",nS({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":tM.current="failed",nS({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!tC.current)break;let t=e.message;if(t?.role!=="assistant")break;t&&M({type:"update",message:(0,sM.B)(t)}),eK(null);break}case"message_end":{if(!tC.current)break;let t=e.message;if(t?.role==="assistant"&&(t$.current={provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}},tM.current=sG(t)),t&&"user"===t.role){let e=(0,sM.B)(t),n=s4(e),r=t3.current;t3.current=null,nl(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&s4(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]}),r||to({type:"user-message",kind:"steering"in e&&!0===e.steering?"steer":"followUp",text:"user"!==e.role?"":"string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),images:"user"!==e.role||"string"==typeof e.content?0:e.content.filter(e=>"image"===e.type).length})}else t&&nl(e=>[...e,(0,sM.B)(t)]);let n=ty.current;n&&nP(n),M({type:"reset"}),eK({kind:"waiting_model"});break}case"todo_changed":ns(ty.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args;eK(e=>{let i=e?.kind==="running_tools"?[...e.tools]:[];return i.some(e=>e.id===t)||i.push({id:t,name:n,args:r}),{kind:"running_tools",tools:i}});break}case"tool_execution_end":{let t=e.toolCallId;eK(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"subagent_lifecycle":{let t=e.payload;if(!t?.id)break;if("started"!==t.status){let e="failed"===t.status?"failed":"aborted"===t.status?"aborted":"completed";ta(n=>{let r=n.find(e=>e.id===t.id);return sJ(n,[{id:t.id,index:t.index??r?.index??0,agent:t.agent??r?.agent??t.id,agentSource:t.agentSource??r?.agentSource??"bundled",description:t.description??r?.description,status:e,task:r?.task,assignment:r?.assignment,sessionFile:t.sessionFile??r?.sessionFile,parentToolCallId:t.parentToolCallId??r?.parentToolCallId,lastUpdate:Date.now(),progress:r?.progress?{...r.progress,status:e}:void 0}])});break}let n={id:t.id,index:t.index??0,agent:t.agent??t.id,agentSource:t.agentSource??"bundled",description:t.description,status:"running",sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now()};ta(e=>sJ(e,[n]));break}case"subagent_progress":{let t=e.payload;if(!t?.progress)break;let n=t.progress,r={id:n.id,index:t.index??n.index,agent:t.agent??n.agent,agentSource:t.agentSource??"bundled",description:n.description,status:n.status,task:t.task??n.task,assignment:t.assignment??n.assignment,sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now(),progress:n};ta(e=>sJ(e,[r]));break}case"queue_update":ti({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":ev({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":ev(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof e.reason){e_.current=e.reason;let t=e.reason;eD(e=>e?{...e,reason:t}:e)}eE(!0),eA(null),eW(null);break;case"auto_compaction_end":case"compaction_end":if(eE(!1),e.errorMessage)eA(e.errorMessage),eW(null);else if(!e.aborted){eW(s8(e.result,e.reason??"auto"));let t=ty.current;t&&(nd(t),nP(t))}break;case"extension_ui_request":nN(e)}},[nS,ns,na,ng,nN,nd,n$,nR,nP,nT,nE,nI,no,nl]);let nD=(0,i.useCallback)(async(n,i,s)=>{let a=n.trim();if(!a&&!i?.length&&!s?.length||tC.current||tL.current||t7.current)return;let l=nB(n,s??[]),o=!i?.length&&!s?.length&&a.startsWith("/");if(!i?.length&&!s?.length&&a.startsWith("!")){let e=a.startsWith("!!"),t=(e?a.slice(2):a.slice(1)).trim();if(!t)return;await tU.current?.(t,e);return}nT();let d=t8.current+1;ng(),tI.current=!0;let c=i?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),u={role:"user",content:c?.length?[...l.trim()?[{type:"text",text:l}]:[],...c]:l,timestamp:Date.now()};nl(e=>[...e,u]),t3.current=s4(u),t8.current=d,tC.current=!0,R(!0),eK(o?{kind:"running_command"}:{kind:"waiting_model"}),M({type:"start"}),tK.current(!0);let p=i?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),h=null,f=!1;try{if(m&&r){let e=ty.current??await tY.current,t=await nm();t&&(h=t,Y&&(eT(Y),e&&await sR(t,{type:"set_model",provider:Y.provider,modelId:Y.modelId})),await nw(t),f=!0,await sR(t,{type:"prompt",message:l,...p?.length?{images:p}:{}}),nh(1,n))}else t&&(h=t.id,await nw(t.id),f=!0,await sR(t.id,{type:"prompt",message:l,...p?.length?{images:p}:{}}));o&&h&&nA(h,d)}catch(l){console.error("Failed to send message:",l);let r=l instanceof s$&&"update_draining"===l.code&&!1===l.accepted;if(!(!f||l instanceof s$&&"prompt_rejected"===l.code&&!1===l.accepted||r)&&h)return void nA(h,d);tI.current=!1,tC.current=!1,nx();let a=t3.current;a&&nl(e=>{let t=e[e.length-1];return t?.role==="user"&&s4(t)===a?e.slice(0,-1):e}),nS({type:"error",message:l instanceof Error?l.message:String(l)}),e.chatInputRef?.current?.restoreSubmission?.(n,s6(i),s,t?.id??h??void 0),t3.current=null,R(!1),eK(null),M({type:"end"})}},[m,r,Y,t,nm,nw,nh,nA,nS,ng,nx,e.chatInputRef,nT,nl]);tU.current=(0,i.useCallback)(async(n,r)=>{if(tC.current||tL.current)return;let i=`${r?"!!":"!"}${n}`;tL.current=!0,tK.current(!0),z({command:n,excludeFromContext:r}),L(!0);try{let e=ty.current??t?.id??await nm();if(!e)throw Error("Unable to create a session for the shell command");await sR(e,{type:"bash",command:n,excludeFromContext:r}),await nd(e),nh(1,i)}catch(t){console.error("Failed to execute shell command:",t),nS({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(i)}finally{tL.current=!1,z(null),L(!1)}},[nS,nm,nd,e.chatInputRef,nh,t]);let n_=(0,i.useCallback)(async()=>{let e=ty.current;if(e){if(tL.current){try{await sR(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await sR(e,{type:"abort"}),tM.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),nO=(0,i.useCallback)(async e=>{if(tL.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let t=ty.current;if(!t)return{forked:!1,error:"No active session to fork"};eS(e??null);try{let{cancelled:n,newSessionId:r}=await sR(t,{type:"fork",...e?{entryId:e}:{}})??{};if(!n&&r)return d?.(r),{forked:!0};return{forked:!1,error:"Fork was cancelled"}}catch(e){return console.error("Fork failed:",e),{forked:!1,error:e instanceof Error?e.message:String(e)}}finally{eS(null)}},[d]),nH=(0,i.useCallback)(async e=>{if(tL.current)return;let t=ty.current;t&&(sR(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await nu(t,e))},[nu]),nU=(0,i.useCallback)(async e=>{if(tL.current)return;j(e);let t=ty.current;t&&(await nu(t,e),e&&sR(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[nu]),nq=(0,i.useCallback)(async(e,t)=>{if(m){let n={provider:e,modelId:t},r=tX.current?.provider===e;tX.current=n,r||(tQ.current=null,Q(null)),Z(n),eT(n);let i=ty.current??await tY.current;if(!i)return;try{await sR(i,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=ty.current;if(n&&!t7.current){t7.current=!0,eN({provider:e,modelId:t}),e$(!0);try{await sR(n,{type:"set_model",provider:e,modelId:t}),t7.current=!1,await nd(n)}catch(e){console.error("Failed to set model:",e),t7.current=!1,eN(eC),nS({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nd(n)}finally{t7.current=!1,e$(!1)}}},[nS,eC,m,nd,Z]),nV=(0,i.useCallback)(async e=>{let t={provider:e.provider,modelId:e.modelId},n=e.oauthPosition,r={type:"set_model",provider:e.provider,modelId:e.modelId,thinkingLevel:"auto",...void 0!==n?{oauthPosition:n}:{}},i=t=>`${e.alias} preset was not applied: ${t instanceof Error?t.message:String(t)}`;if(m){if(t7.current)return!1;t7.current=!0,e$(!0);let e=tX.current,s=tQ.current,a=t0.current;try{tX.current=t,tQ.current=n??null,t0.current="auto";let e=ty.current??await tY.current;return e&&await sR(e,r),Z(t),Q(n??null),eT(t),es("auto"),el(void 0),e&&await nd(e),!0}catch(n){console.error("Failed to apply Main preset:",n),tX.current=e,tQ.current=s,t0.current=a,nS({type:"error",message:i(n)});let t=ty.current;return t&&await nd(t),!1}finally{t7.current=!1,e$(!1)}}let s=ty.current;if(!s||t7.current)return!1;t7.current=!0,eN(t),e$(!0);try{return await sR(s,r),await nd(s),!0}catch(e){return console.error("Failed to apply Main preset:",e),eN(eC),nS({type:"error",message:i(e)}),await nd(s),!1}finally{t7.current=!1,e$(!1)}},[nS,eC,ea,m,nd,Z,ei]),nK=(0,i.useCallback)(async e=>{let t=J.find(t=>t.role===e),n=t?.resolved;if(!n)return;if(m){let e={provider:n.provider,modelId:n.modelId},t=n.thinkingLevel;t0.current=t??null,es(t??"auto"),el(void 0),tX.current=e,tQ.current=null,Q(null),Z(e),eT(e)}let r=ty.current??(m?await tY.current:null);if(r)try{await sR(r,{type:"set_role_model",role:e}),m||eN({provider:n.provider,modelId:n.modelId})}catch(e){console.error("Failed to set role model:",e)}},[m,J,Z]),nJ=(0,i.useCallback)(async()=>{let e=ty.current;if(e&&!eR){e_.current="manual",eE(!0),eA(null),eW(null);try{let t=await sR(e,{type:"compact"});eW(s8(t,"manual")),await nd(e,!0)}catch(e){eA(e instanceof Error?e.message:String(e)),eW(null)}finally{eE(!1)}}},[eR,nd]),nG=(0,i.useCallback)(async e=>{let n=r??t?.cwd??"",i=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",s=await fetch(i,e?{signal:e}:void 0);if(!s.ok)throw Error(`HTTP ${s.status}`);let a=await s.json();F(a.models),O(a.modelError??null),B(a.modelScopeWarnings??[]),q(a.thinkingLevels??{}),K(a.thinkingLevelMaps??{}),G(a.roles??[]);let l=a.modelList??[];if(D(l),m&&!ty.current){let e=(a.defaultModel?l.find(e=>e.id===a.defaultModel?.modelId&&e.provider===a.defaultModel?.provider):void 0)??l[0];et(e?{provider:e.provider,modelId:e.id}:null);let t=e&&a.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===t0.current&&es(t??"auto")}},[m,r,t?.cwd]),nY=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,n,r=""]=t,i=r.trim(),s=await nm(),a=e=>(e.handled&&(e.error?nS({type:"error",message:e.error}):"openSessionStats"!==e.action&&nS({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!s||eR)return a({handled:!0,error:"No active session to compact"});e_.current="manual",eE(!0),eA(null),eW(null);let e=await sR(s,{type:"compact",...i?{customInstructions:i}:{}});return eW(s8(e,"manual")),await nd(s,!0)&&nh(),a({handled:!0,message:"Compacted context"})}case"reload":if(!s)return a({handled:!0,error:"No active session to reload"});return await sR(s,{type:"reload"}),await Promise.all([nd(s,!1,!0),np(s),nf(),nG()]),a({handled:!0,message:"Reloaded session resources"});case"name":if(!s)return a({handled:!0,error:"No active session to name"});if(!i)return a({handled:!0,error:"Usage: /name <name>"});return await sR(s,{type:"set_session_name",name:i}),await nd(s)&&nh(),a({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!s)return a({handled:!0,error:"No active session"});let e=await sR(s,{type:"get_session_stats"});return e&&e1(e),h?.(),a({handled:!0,action:"openSessionStats"})}case"copy":{if(!s)return a({handled:!0,error:"No active session"});let e=await sR(s,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return a({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),a({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!s)return a({handled:!0,error:"No active session to fork"});let e=await nO();if(!e.forked)return a({handled:!0,error:e.error??"Fork failed"});return a({handled:!0,message:"Forked a new session"})}case"goal":{if(!s)return a({handled:!0,error:"No active session"});let e=await sR(s,{type:"goal",args:i});if(tB(e?.status??null),e?.error)return a({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(nC(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&nS({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return a({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!s)return a({handled:!0,error:"No active session"});if(tC.current||tL.current)return a({handled:!0,error:"Cannot hand off while the session is busy"});tC.current=!0,R(!0),eK({kind:"running_command"});try{await nw(s);let e=await sR(s,{type:"handoff",...i?{customInstructions:i}:{}});if(!e||e.cancelled)return a({handled:!0,error:"Handoff cancelled"});return await nd(s,!0)&&nh(),a({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tC.current=!1,R(!1),eK(null),ty.current===s&&nE(s)}default:{if(!s)return a({handled:!0,error:"No active session"});let t=await sR(s,{type:"execute_slash_command",message:e});if(!t?.handled)return{handled:!1};let n=t.output?.filter(e=>e.trim()).join("\n\n")??"";if(n&&nC(n),t.prompt)return{handled:!0,prompt:t.prompt};if(n)return{handled:!0};return a({handled:!0,message:"Command completed"})}}}catch(e){return a({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&eE(!1)}},[nS,nC,nw,nm,nO,eR,nG,nd,nf,np,nh,h,nE]),nZ=(0,i.useCallback)(async(t,n,r)=>{let i=ty.current;if(!i){nS({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,s6(n),r);return}let s=nB(t,r??[]),a=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++td.current;to({type:"submit",id:l,kind:"steer",text:s,images:a?.length??0});try{await sR(i,{type:"steer",message:s,...a?.length?{images:a}:{}}),to({type:"ack",id:l})}catch(s){to({type:"fail",id:l}),console.error("Failed to steer:",s),nS({type:"error",message:s instanceof Error?s.message:String(s)}),e.chatInputRef?.current?.restoreSubmission?.(t,s6(n),r,i)}},[nS,e.chatInputRef]),nX=(0,i.useCallback)(async(t,n,r,i)=>{let s=ty.current;if(!s){nS({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,s6(r),i);return}let a=nB(t,i??[]),l=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++td.current;to({type:"submit",id:o,kind:n,text:a,images:l?.length??0});try{await sR(s,{type:"prompt",message:a,streamingBehavior:n,...l?.length?{images:l}:{}}),to({type:"ack",id:o})}catch(n){to({type:"fail",id:o}),console.error("Failed to queue prompt:",n),nS({type:"error",message:n instanceof Error?n.message:String(n)}),e.chatInputRef?.current?.restoreSubmission?.(t,s6(r),i,s)}},[nS,e.chatInputRef]),nQ=(0,i.useCallback)(async(t,n,r)=>{let i=ty.current;if(!i){nS({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,s6(n),r);return}let s=nB(t,r??[]),a=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++td.current;to({type:"submit",id:l,kind:"followUp",text:s,images:a?.length??0});try{await sR(i,{type:"follow_up",message:s,...a?.length?{images:a}:{}}),to({type:"ack",id:l})}catch(s){to({type:"fail",id:l}),console.error("Failed to follow up:",s),nS({type:"error",message:s instanceof Error?s.message:String(s)}),e.chatInputRef?.current?.restoreSubmission?.(t,s6(n),r,i)}},[nS,e.chatInputRef]),n0=(0,i.useCallback)(async()=>{let e=ty.current;if(e)try{await sR(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),n1=(0,i.useCallback)(async()=>{let t=ty.current;if(t)try{var n;let r=await sR(t,{type:"clear_queue"});to({type:"withdraw"}),ti({steering:[],followUp:[]});let i={text:(n=[...r?.steering??[],...r?.followUp??[]]).map(({text:e,images:t})=>t?.length&&"[Image]"===e?"":e).filter(e=>e.trim()).join("\n\n"),images:n.flatMap(({images:e})=>e??[]).map(({data:e,mimeType:t})=>({data:e,mimeType:t}))};e.chatInputRef?.current?.restoreSubmission?.(i.text,i.images.length?i.images:void 0,void 0,t)}catch(e){console.error("Failed to recall queued messages:",e),nS({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,nS]),n2=(0,i.useCallback)(async(e,t)=>{let n=ty.current;if(n)try{let r=await sR(n,{type:"remove_queued_message",message:t,queue:e});if(!r?.removed)return;to({type:"withdraw",kind:"steering"===e?"steer":"followUp",text:t}),ti(n=>{let r=n[e].indexOf(t);return(r<0&&""===t.trim()&&(r=n[e].indexOf("[Image]")),r<0)?n:{...n,[e]:n[e].filter((e,t)=>t!==r)}})}catch(e){console.error("Failed to remove queued message:",e),nS({type:"error",message:"Failed to remove queued message"})}},[nS]),n4=(0,i.useCallback)(async(e,t=null)=>{let n="auto"===e?t:null,r=n!==eo;es(e),ed(n),m&&(!ty.current||t2.current===ty.current)&&(t0.current=e,t1.current=n),el(void 0);let i=ty.current??await tY.current;if(i)try{t2.current===i?await nm():r&&await sR(i,{type:"set_thinking_ceiling",ceiling:n}),await sR(i,{type:"set_thinking_level",level:e}),await nd(i)}catch(e){console.error("Failed to set thinking level:",e),nS({type:"error",message:"Failed to set thinking level"}),await nd(i)}},[m,nd,nS,eo,nm]);ef.current=nn?`${nn.provider}/${nn.modelId}`:"";let n5=e=>e?`${e}|${ef.current}`:null,n8=t?.id??ty.current,n6=n5(n8),n3=ec&&ec.key===n6?ec.value:null;(0,i.useEffect)(()=>{let e=++em.current;n6&&n8&&!$&&!eM&&fetch(`/api/agent/${encodeURIComponent(n8)}`).then(e=>e.json()).then(t=>{em.current===e&&n5(ty.current)===n6&&eu({key:n6,value:(t.running?sq(t.state):void 0)??null})}).catch(()=>{})},[n6,$,eM]);let n7=(0,i.useCallback)(async()=>{let e=ty.current??await nm(),t=n5(ty.current);if(!e||!t)return;let n=++em.current,r=()=>em.current===n&&n5(ty.current)===t,i=e=>{r()&&eu({key:t,value:e})};eh(!0);try{let n=ec?.key===t?ec.value?.enabled:void 0;if(void 0===n){let t=sq(await sR(e,{type:"get_state"}));if(!t)throw Error("Could not read the session's Fast state");n=t.enabled}if(!r())return;let s=await sR(e,{type:"set_fast_mode",enabled:!n});i({enabled:s?.enabled===!0,active:s?.active===!0})}catch(t){if(!r())return;nS({type:"error",message:t instanceof Error?t.message:String(t)});try{i(sq(await sR(e,{type:"get_state"}))??null)}catch{i(null)}}finally{eh(!1)}},[nm,ec,nS]),n9=(0,i.useCallback)(async e=>{let t=(0,i5.xG)(e);ne(e);let n=ty.current??await tY.current;if(n)try{await sR(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[ne]),re=(0,i.useCallback)(e=>{tD.current=e,tO(t=>!e===t?t:!e)},[]);tK.current=re;let rt=(0,i.useCallback)((e="smooth")=>{tV.current=Date.now()+700,tJ.current?.scrollIntoView({behavior:e})},[]),rn=(0,i.useCallback)(()=>{tq.current=0,re(!0),rt("smooth")},[rt,re]),rr=(0,i.useCallback)(()=>{tq.current=0,re(!1)},[re]),ri=(0,i.useCallback)(e=>{e instanceof KeyboardEvent&&(!sZ.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tq.current=Date.now()+1200)},[]),rs=(0,i.useCallback)(()=>{if(!tC.current&&!tL.current)return;let e=tG.current;if(!e)return;let t=Date.now()<=tq.current;!t&&Date.now()<tV.current||(e.scrollHeight-e.scrollTop-e.clientHeight<=72?re(!0):t&&re(!1))},[re]);return(0,i.useEffect)(()=>(ty.current=t?.id??null,tS.current.sessionId!==ty.current&&(tS.current={sessionId:ty.current,outputs:[],seq:0}),t&&nd(t.id,!f,!0,f).then(e=>{if(ty.current!==t.id)return;nb(t.id),e?.running&&(np(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(tN.current=!!e.state.isStreaming,tI.current=!!e.state.isPromptRunning,tC.current=!0,R(!0),eK(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),M({type:"start"}),ny(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nA(t.id)),e.state?.isBashRunning&&(tL.current=!0,L(!0),nz(t.id)),(e.state?.subagents?.length??0)>0&&ny(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&eE(n.isCompacting),eD(sV(n)),void 0!==n.contextUsage&&ey(n.contextUsage??null),void 0!==n.systemPrompt&&ek(n.systemPrompt??null),void 0!==n.thinkingLevel&&(es(n.configuredThinkingLevel??n.thinkingLevel),el(n.thinkingLevel)),void 0!==n.thinkingCeiling&&ed(n.thinkingCeiling??null),void 0!==n.extensionStatuses&&te(n.extensionStatuses??[]),void 0!==n.extensionWidgets&&tn(n.extensionWidgets??[]),void 0!==n.queuedMessages&&ti(sU(n.queuedMessages)),void 0!==n.subagents&&ta(e=>sJ(e,n.subagents??[])),void 0!==n.goal&&tB(n.goal??null)),e&&eq(!0)}),()=>{tA.current+=1,ng(),nx(),nv()}),[t?.id]),(0,i.useEffect)(()=>{p?.(ew)},[ew,p]),(0,i.useEffect)(()=>{u&&u(g?.tree??[],k,nU)},[g?.tree,k,nU,u]),(0,i.useEffect)(()=>(window.addEventListener("keydown",ri),()=>{window.removeEventListener("keydown",ri)}),[ri]),(0,i.useEffect)(()=>{let e=tG.current;if(e)return e.addEventListener("pointerdown",ri,{passive:!0}),e.addEventListener("wheel",ri,{passive:!0}),e.addEventListener("touchstart",ri,{passive:!0}),e.addEventListener("scroll",rs,{passive:!0}),()=>{e.removeEventListener("pointerdown",ri),e.removeEventListener("wheel",ri),e.removeEventListener("touchstart",ri),e.removeEventListener("scroll",rs)}},[S.length,v,rs,ri]),(0,i.useEffect)(()=>{if(t4.current||!$&&!E||!tD.current)return;let e=tG.current;if(!e)return;let t=requestAnimationFrame(()=>{tV.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"})});return()=>cancelAnimationFrame(t)},[$,E,S.length,T.streamingMessage,eV,A,e.transitioning]),(0,i.useLayoutEffect)(()=>{if(0!==S.length){if(!tP.current){tP.current=!0,rt("instant");return}if(!t4.current&&tD.current){let e=Date.now()-t5.current<1500;rt(tC.current||tL.current||e?"instant":"smooth")}}},[S.length,$,E,rt,e.transitioning]),(0,i.useEffect)(()=>{let e=new AbortController;return nG(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[nG,c]),(0,i.useEffect)(()=>{if(!ez)return;let e=setTimeout(()=>eW(null),6e3);return()=>clearTimeout(e)},[ez]),(0,i.useEffect)(()=>{if(0===eX.visible.length)return;let e=eX.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{eQ({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!eX.visible[0])return;let t=setTimeout(()=>{eQ({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[eX.visible]),(0,i.useEffect)(()=>{e1(null)},[S.length,eb?.tokens,eb?.percent,eb?.contextWindow]),{data:g,loading:v,error:y,activeLeafId:k,messages:S,entryIds:N,streamState:T,agentRunning:$,modelNames:W,modelList:P,modelError:_,modelScopeWarnings:H,modelThinkingLevels:U,modelThinkingLevelMaps:V,modelRoles:J,newSessionModel:Y,toolPreset:en,thinkingLevel:ei,effectiveThinkingLevel:ea,thinkingCeiling:eo,retryInfo:eg,contextUsage:eb,systemPrompt:ew,forkingEntryId:ej,isCompacting:eR,compaction:eF,compactError:eL,compactResult:ez,currentModel:nt,displayModel:nn,modelSwitching:eM,sessionStats:nr,runStateKnown:eU,slashCommands:eJ,slashCommandsLoading:eY,queuedMessages:tr,deliveryRows:tc,subagents:ts,todoPhases:tu&&tu.sid===ty.current?tu.phases:null,notices:eX.visible,extensionDialog:e2,extensionResponse:e5,extensionCustomUi:e3,extensionStatuses:e9,extensionWidgets:tt,respondToExtensionUi:nk,sendExtensionCustomInput:nj,isAutoModelSelection:m&&null===Y,agentPhase:eV,isNew:m,autoFollowPaused:t_,resumeAutoFollow:rn,pauseAutoFollow:rr,goalStatus:tH,sessionIdRef:ty,eventSourceRef:th,messagesEndRef:tJ,scrollContainerRef:tG,handleSend:nD,handleAbort:n_,handleFork:nO,handleNavigate:nH,handleModelChange:nq,handleRoleModelChange:nK,handleMainPresetChange:nV,newSessionAccount:X,handleCompact:nJ,handleSteer:nZ,handleFollowUp:nQ,handlePromptWithStreamingBehavior:nX,handleAbortCompaction:n0,handleRecallQueue:n1,handleRemoveQueuedMessage:n2,handleBuiltinSlashCommand:nY,handleToolPresetChange:n9,handleThinkingLevelChange:n4,fastMode:n3,fastModeBusy:ep,handleFastModeToggle:n7,loadTools:np,loadSlashCommands:nf,ensureNewSession:nm,refreshLiveTranscript:nc,setActiveLeafId:j,setData:x,setMessages:C,dispatch:M,setAgentRunning:R,setForkingEntryId:eS,bashRunning:E,pendingBash:A,handleAgentEventRef:tz}}({session:e,newSessionCwd:t,initialData:s,transitioning:a,onAgentEnd:em,onAttentionNeeded:o,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsPanelOpen:g}),tB=ne(e?.id,e8?.provider,void 0),tU=tB?.alias;(0,i.useEffect)(()=>{tU&&K.current?.(tU)},[tU]);let tq=(0,i.useMemo)(()=>{if(!e8)return null;let e=tm?tM:tX.bo.find(e=>e.alias===tB?.alias)?.oauthPosition;return tX.bo.find(t=>t.provider===e8.provider&&(void 0===t.oauthPosition||t.oauthPosition===e))?.alias??null},[e8,tm,tM,tB]),tV=e8?.provider,tK=e8?.modelId,tJ=tB?.alias,tG=tB?.seed,tQ=(0,i.useRef)(tB);tQ.current=tB,(0,i.useEffect)(()=>{y&&y(tV&&tK?{provider:tV,modelId:tK,face:tQ.current,presetAlias:tq,isNew:tm}:null)},[y,tV,tK,tJ,tG,tq,tm]),(0,i.useEffect)(()=>()=>{y?.(null)},[y]);let t0=ek||ej,t1=e?.id;Q.current=eb,ee.current=ey,et.current=tb;let t2=(0,i.useRef)(!0);t2.current=!tf;let t4=(0,i.useRef)(!1);(0,i.useEffect)(()=>{ek&&!t4.current&&(en.current+=1),t4.current=ek},[ek]),(0,i.useEffect)(()=>()=>{en.current+=1},[]),(0,i.useEffect)(()=>{Y(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(an(e))??"[]");if(!Array.isArray(t))return[];return t.filter(e=>e&&"string"==typeof e.anchorEntryId).map(t=>({..."string"==typeof t.sticker?{...t,sticker:t.sticker.replace(/^(\/stickers\/.+)\.png$/,"$1.webp")}:t,sessionId:e}))}catch{return[]}}(t1),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===t1)])},[t1]),(0,i.useEffect)(()=>{let e=tb.current;e&&Z.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&Y(t=>{let n=!1,r=[];for(let i of t){if(null!==i.anchorEntryId||!i.intent||i.sessionId!==e){r.push(i);continue}let s=function(e,t,n){let r=Math.min(t.length,n.length),i=0;if(null!==e.baseEntryId){let t=n.indexOf(e.baseEntryId);if(-1===t||t>=r)return{kind:"drop"};i=t+1}let s=0;for(let a=i;a<r;a++)if(r4(t[a])===e.identity&&(s+=1)===e.occurrence)return{kind:"entry",entryId:n[a]};return null}(i.intent,eb,ey);if(null===s){r.push(i);continue}n=!0,"drop"!==s.kind&&("working"===i.tag&&[...t,...r].some(e=>"working"===e.tag&&e.anchorEntryId===s.entryId)||r.push({id:i.id,anchorEntryId:s.entryId,sticker:i.sticker,text:i.text,tag:i.tag,sessionId:i.sessionId}))}return n?(ar(e,r),r):t})},[eb,ey,tb]);let t5=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tb.current,t=t5.current;if(t5.current=e?{sessionId:e,entryIds:ey}:null,!e||!t||t.sessionId!==e)return;let n=function(e,t,n){if(0===e.length||t.length<=e.length)return[];for(let n=0;n<e.length;n++)if(e[n]!==t[n])return[];let r=[],i=Math.min(n.length,t.length);for(let s=e.length;s<i;s++){let e=n[s];"assistant"===e.role&&"web6"===e.provider&&"ChatGPT 6PRO"===e.model&&r.push(t[s])}return r}(t.entryIds,ey,eb),r=es();if(0===n.length||!r)return;let i=t9(e,"web6",void 0)?.alias??null;for(let e of n)Z.current.some(t=>t.anchorEntryId===e)||eo(i,"done",r,{kind:"entry",entryId:e})},[ey,eb,tb,es,eo]);let t8=ek&&th?.kind==="running_tools"&&th.tools.length>0&&th.tools.every(e=>"wait"===e.name),t6=eg||a,{hideThinkingBlock:t3}=(F=t??e?.cwd??null,_=tZ(),(0,i.useEffect)(()=>{tY(F).catch(()=>{})},[F]),_),t7=(0,i.useMemo)(()=>({hideThinking:t3}),[t3]);(0,i.useEffect)(()=>{if(!ts||V.current===ts.id)return;V.current=ts.id;let e=es();if(e){var t;ei.current=e.turn,ec("select"===(t=ts.method)||"ask"===t?"choice":"approval",e,e8?.provider,void 0)}},[ts,e8?.provider,es,ec]),(0,i.useEffect)(()=>(v=t0?tj:null,()=>void(v=null)),[t0,tj]),(0,i.useEffect)(()=>{N?.(t0)},[N,t0]),(0,i.useEffect)(()=>()=>N?.(!1),[N]),(0,i.useEffect)(()=>{I?.(t8)},[t8,I]),(0,i.useEffect)(()=>()=>I?.(!1),[I]),(0,i.useEffect)(()=>{T?.(null!==ts)},[T,ts]),(0,i.useEffect)(()=>()=>T?.(!1),[T]);let{main:nt,process:nn}=(0,i.useMemo)(()=>(function(e,t,n={}){let r=[],i=[],s=-1,a=null,l=(e,t,n)=>{if(0===t.length)return;let s=(a&&a.anchorIdx===e||(a={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},i.push(a)),a),l=r.length-1;for(let e of t)s.entries.push({...e,afterMainIndex:l});s.messageCount+=t.length,s.toolCallCount+=n},o=ez(e),d=new Map,c=(e,t)=>{let n=d.get(e)??0;d.set(e,n+1),r.push({kind:"answer",anchorIdx:s,idx:e,runIndex:n,blocks:o.attach(t),precedingBlocks:[]})},u=()=>{let e=o.takeRemaining();e&&c(e.idx,e.blocks)};for(let i of t){if("answer"===i.kind){r.push(i);continue}if("process"===i.kind){l(i.anchorIdx,i.entries,i.toolCallCount);continue}let t=e[i.idx];if(!t)continue;if("user"===t.role){u(),s=i.idx,r.push(i);continue}if(e_(t)){r.push(void 0!==i.anchorIdx||s<0?i:{...i,anchorIdx:s});continue}if("assistant"!==t.role){"toolResult"!==t.role&&l(s,[{idx:i.idx}],0);continue}let a=eE(t,n),d=!1;for(let e of a){if("answer"===e.kind){c(i.idx,e.blocks),d=!0;continue}l(s,[{idx:i.idx,blocks:e.blocks}],eL(e.blocks)),o.collect(i.idx,e.blocks)}!d&&eR(t,n)&&c(i.idx,[])}return u(),{main:r,process:i}})(eb,function(e,t={}){let n=-1;for(let t=e.length-1;t>=0;t--)if(eU(e[t])){n=t;break}let r=[];for(let i=0;i<e.length;){if(!eU(e[i])){r.push({kind:"message",idx:i}),i+=1;continue}let s=i,a=s+1;for(;a<e.length&&!eU(e[a]);)a+=1;if((t.sessionBusy||t.isStreaming)&&a===e.length&&s===n||!function(e,t,n){for(let r=t;r<n;r++)if(e[r]?.role==="assistant")return!0;return!1}(e,s+1,a)){for(let e=s;e<a;e++)r.push({kind:"message",idx:e});i=a;continue}for(let n of(r.push({kind:"message",idx:s}),function(e,t,n,r){let i=[],s=[],a=0,l=[],o=0,d=0,c=ez(e.slice(t+1,n)),u=()=>{0!==s.length&&(i.push({kind:"process",anchorIdx:t,idx:s[0].idx,groupIndex:d++,entries:s,messageCount:s.length,toolCallCount:a,turnHasAnswer:!1}),s=[],a=0)},p=(e,n)=>{u(),i.push({kind:"answer",anchorIdx:t,idx:e,runIndex:o++,blocks:c.attach(n),precedingBlocks:l}),l=[]};for(let o=t+1;o<n;o++){let n=e[o];if("assistant"!==n.role){if(e_(n)){u(),i.push({kind:"message",idx:o,anchorIdx:t});continue}"toolResult"!==n.role&&s.push({idx:o});continue}let d=eE(n,r),h=d.reduce((e,t)=>"answer"===t.kind?e+1:e,0);for(let e of d){if("answer"===e.kind){p(o,e.blocks);continue}for(let t of(s.push(h>0?{idx:o,blocks:e.blocks}:{idx:o}),a+=eL(e.blocks),c.collect(o,e.blocks),e.blocks))l.push(t)}0===h&&eR(n,r)&&p(o,[])}u();let h=c.takeRemaining();h&&i.push({kind:"answer",anchorIdx:t,idx:h.idx,runIndex:o++,blocks:h.blocks,precedingBlocks:[]});let m=i.some(e=>"answer"===e.kind);for(let e of i)"process"===e.kind&&(e.turnHasAnswer=m);return i}(e,s,a,{hideThinking:t.hideThinking})))r.push(n);i=a}return r}(eb,{sessionBusy:t0,isStreaming:ew.isStreaming,hideThinking:t7.hideThinking}),t7),[eb,t0,ew.isStreaming,t7]),nr=(0,i.useMemo)(()=>(function(e,t){let n=new Map,r=e.map((e,t)=>({item:e,position:t})).filter(e=>"answer"===e.item.kind);if(0===r.length)return n;let i=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user").map(e=>e.idx);return t.forEach((e,t)=>{if("assistant"!==e.role)return;let s=e.content?.filter(e=>"toolCall"===e.type&&"task"===e.toolName)??[];if(0===s.length)return;let a=-1;for(let e of i)e<t&&(a=e);let l=r.filter(e=>e.item.anchorIdx===a),o=l.filter(e=>e.item.idx<=t).pop(),d=o??l.find(e=>e.item.idx>t);if(!d)return;let c=n.get(d.position);c?c.calls.push(...s):n.set(d.position,{calls:[...s],placement:o?"after":"before"})}),n})(nt,eb),[nt,eb]),[ni,ns]=(0,i.useState)(s3),{startIndex:na,endIndex:nl,hasLater:no}=s7(nt.length,ni),nd=null!==ni.end&&no,nc=(0,i.useRef)(nt.length);nc.current=nt.length;let nu=(0,i.useRef)(null),np=(0,i.useRef)(null),nh=(0,i.useRef)(null);(0,i.useEffect)(()=>{null!==ni.end&&ni.end>=nt.length&&ns(e=>({count:e.count,end:null}))},[ni.end,nt.length]),(0,i.useEffect)(()=>{let e=nu.current,t=tw.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(nh.current=t.scrollHeight-t.scrollTop,ns(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[ni,nt.length,tw]),(0,i.useEffect)(()=>{if(null==nh.current)return;let e=tw.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nh.current),nh.current=null}},[ni.count,tw]),(0,i.useEffect)(()=>{let e=np.current,t=tw.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&ns(e=>(function(e,t,n=50){if(null===t.end)return t;let{startIndex:r,endIndex:i}=s7(e,t),s=i+n;return s>=e?{count:e-r,end:null}:{count:s-r,end:s}})(nc.current,e))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[ni,nt.length,tw]);let[nm,nf]=(0,i.useState)(null),[ng,nx]=(0,i.useState)(null),[nT,nM]=(0,i.useState)(0),n$=(0,i.useRef)(null),nR=(0,i.useCallback)((e,t=null)=>{tx(),n$.current={item:e,dispatchKey:t},nf(null),nx(null),ns(t=>s9(nc.current,e,t)),nM(e=>e+1)},[tx]);(0,i.useLayoutEffect)(()=>{let e,t=n$.current,n=tw.current;if(null===t||!n)return;let r=n.querySelector(`[data-chat-item="${t.item}"]`);if(!r)return;n$.current=null;let i=t.dispatchKey?r.querySelector(".answer-dispatch"):null;if(i)e=i.getBoundingClientRect().top;else{let t=document.createRange();t.selectNodeContents(r),e=t.getBoundingClientRect().top}n.scrollTop+=e-n.getBoundingClientRect().top-24,i&&t.dispatchKey?nx(t.dispatchKey):nf(t.item)},[nT,ni,nt,tw]),(0,i.useEffect)(()=>{if(null===nm)return;let e=setTimeout(()=>nf(null),1800);return()=>clearTimeout(e)},[nm]),(0,i.useEffect)(()=>{if(null===ng)return;let e=setTimeout(()=>nx(null),1800);return()=>clearTimeout(e)},[ng]);let nE=(0,i.useCallback)(()=>{(0,P.flushSync)(()=>ns(s3));let e=tw.current;e&&(e.scrollTop=e.scrollHeight)},[tw]),nL=(0,i.useCallback)(()=>{nd&&nE(),tg()},[nd,nE,tg]),nA=(0,i.useRef)(null),[nz,nW]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!z||nA.current===z.id||z.sessionId!==e?.id||eg||0===eb.length)return;nA.current=z.id,W?.(z.id);let t=ey.indexOf(z.entryId);if(t<0)return void nW(!0);let n=0;for(let e=0;e<nt.length;e++){let r=nt[e].idx;if(r>t||(n=e,r===t))break}nR(n)},[z,e?.id,eg,eb.length,ey,nt,nR,W]),(0,i.useEffect)(()=>{if(!nz)return;let e=setTimeout(()=>nW(!1),6e3);return()=>clearTimeout(e)},[nz]);let[nF,nP]=(0,i.useState)(!1),[nD,n_]=(0,i.useState)(0),nO=(0,i.useMemo)(()=>nF?nt.map(e=>(function(e,t){if("answer"===e.kind)return eK(e.blocks);let n=t[e.idx];return n&&"content"in n?eK(n.content):""})(e,eb).toLowerCase()):ai,[nF,nt,eb]),nH=(0,i.useCallback)(e=>{tx(),ns(t=>s9(nc.current,e,t))},[tx]),nU=(0,i.useCallback)(()=>nP(!1),[]);(0,i.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.shiftKey||!(e.ctrlKey||e.metaKey)||"f"!==e.key.toLowerCase())return;let t=tw.current;if(!t||!t.checkVisibility({visibilityProperty:!0}))return;let n=e.target instanceof Element?e.target:null;if(n?.closest("[data-capture-keys], [role='dialog']"))return;let r=n?.closest("input, textarea, select, [contenteditable='true']");(!r||r.closest("[data-chat-composer], .chat-find-bar"))&&(e.preventDefault(),nP(!0),n_(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tw]);let nq=(0,i.useMemo)(()=>{let e=[];return nt.forEach((t,n)=>{if("message"!==t.kind)return;let r=at(eb[t.idx]);null!==r&&e.push({item:n,text:r})}),e},[nt,eb]),nV=`${na}:${nl}`,nK=ey.length>0?ey[ey.length-1]:null,[nJ,nG]=(0,i.useState)(null),nY=(0,i.useRef)(!1);(0,i.useEffect)(()=>{nY.current||!e7||eg||!e?.id||(nY.current=!0,t0||!nK||!function(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if("user"===n.role||"toolResult"===n.role)return!0;if("assistant"===n.role){if(!n.stopReason)return!0;if("aborted"===n.stopReason)break;return n.content.some(e=>"toolCall"===e.type)}}return!1}(eb)||function(e){try{return window.localStorage.getItem(as(e))}catch{return null}}(e.id)!==nK&&nG(nK))},[e7,eg,e?.id,t0,nK,eb]);let nZ=(0,i.useCallback)(()=>{e?.id&&nJ&&function(e,t){try{window.localStorage.setItem(as(e),t)}catch{}}(e.id,nJ),nG(null)},[e?.id,nJ]),nX=null!==nJ&&nJ===nK&&!t0&&!nd,nQ=e3?[e3.sessionId,e3.sessionFile??"",e3.sessionName??"",e3.userMessages,e3.assistantMessages,e3.toolCalls,e3.toolResults,e3.totalMessages,e3.tokens.input,e3.tokens.output,e3.tokens.cacheRead,e3.tokens.cacheWrite,e3.tokens.total,e3.cost??0,e3.totalActiveMs??0].join("|"):null,n0=(0,i.useRef)(e3);n0.current=e3,(0,i.useEffect)(()=>{f?.(n0.current)},[nQ,f]),(0,i.useEffect)(()=>()=>{f?.(null)},[f]);let n1=eX?`${eX.percent??"null"}|${eX.contextWindow}|${eX.tokens??"null"}`:null,n2=(0,i.useRef)(eX);n2.current=eX,(0,i.useEffect)(()=>{x?.(n2.current)},[n1,x]),(0,i.useEffect)(()=>()=>{x?.(null)},[x]),(0,i.useEffect)(()=>{b?.(tn)},[b,tn]),(0,i.useEffect)(()=>()=>{b?.([])},[b]);let{isDragOver:n4,handleDragEnter:n5,handleDragOver:n8,handleDragLeave:n6,handleDrop:n3}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),r.current+=1,n(!0))},[]),a=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:s,handleDragOver:a,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{t0||p?.current?.addAttachments(e)},[t0,p])),n7=(0,i.useMemo)(()=>{let e=new Map;for(let t of eb)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[eb]),n9=(0,i.useMemo)(()=>{let e,t,n,r;return e=new Map,t=new Map,n=new Map,r=(e,r,i)=>{let s=n.get(e);s&&r&&t.set(s,{status:r,order:i})},eb.forEach((t,i)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=n7.get(e.toolCallId);if(t)for(let r of nk(e,t)??[])n.set(r.agentId,r.key)}return}if("toolResult"===t.role){if("routing_verdict"===t.toolName){let n=function(e){if(e.isError)return null;let t=e.details?.record;if("object"!=typeof t||null===t)try{let n=JSON.parse(nw(e.content));t=n?.ok===!0?n.record:void 0}catch{return null}if("object"!=typeof t||null===t)return null;let n=t.verdict;if("accepted"!==n&&"rework"!==n&&"held"!==n)return null;let r=nb(t.assignmentId),i=r?.split("#")??[];if(i.length<3)return null;let s=i[i.length-1],a=i.slice(1,-1).join("#");return/^\d+$/.test(s)&&a?{key:`${a}#${s}`,record:{verdict:n,attempt:"number"==typeof t.attempt?t.attempt:null,reason:nb(t.reason)}}:null}(t);if(!n)return;let r=e.get(n.key)??[];r.push({...n.record,order:i}),e.set(n.key,r);return}if("wait"===t.toolName)for(let e of nv(t.details?.jobs)){if("task"!==e.type)continue;let t=nb(e.id);t&&r(t,ny(e.status),i)}return}if("custom"===t.role&&"async-result"===t.customType)for(let e of nw(t.content).matchAll(nj)){let t=Object.fromEntries([...e[1].matchAll(nS)].map(e=>[e[1],e[2]]));t.id&&r(t.id,ny(t.status),i)}}),{verdicts:e,runs:t,latestByAgent:n}},[eb,n7]),re=(0,i.useMemo)(()=>({ledger:n9,subagents:tn,toolResults:n7,onOpenPanel:w,focusedDispatch:ng}),[n9,tn,n7,w,ng]),rt=(0,i.useMemo)(()=>(function(e,t,n,r,i,s){let a=-1;e.forEach((e,t)=>{"user"===e.role&&(a=t)});let l=new Map;for(let[e,t]of n)for(let n of t.calls)l.set(n.toolCallId,e);let o=[];if(e.forEach((e,n)=>{if("assistant"!==e.role)return;let d=n>a;for(let n of e.content??[])if("toolCall"===n.type&&"task"===n.toolName)for(let e of nk(n,t.get(n.toolCallId))??[]){let t=nC(e,r,i),a=nN[t.run],c=null;"running"===a&&("live"===t.runSource||d&&s)?c="running":"awaiting"===a&&d&&!t.verdict&&(c="awaiting"),c&&o.push({maker:t,phase:c,position:l.get(n.toolCallId)??null})}}),0===o.length)return null;let d=0;for(let e of o)"running"===e.phase&&(d+=1);let c=o.filter(e=>null!==e.position);return{running:d,awaiting:o.length-d,target:c.length>0?c[c.length-1]:o[o.length-1]}})(eb,n7,nr,tn,n9,t0),[eb,n7,nr,tn,n9,t0]),rr=(0,i.useMemo)(()=>w?()=>w("subagents"):void 0,[w]),ri=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=eb.length-1;n>=0;n-=1){let r=at(eb[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[eb]),rs=(0,i.useMemo)(()=>(function(e,t,n=null){return n||function(e,t){for(let n=e.length-1;n>=0;n-=1){let r=e[n];if("assistant"!==r.role)continue;let i=r.content;if(Array.isArray(i))for(let e=i.length-1;e>=0;e-=1){let n=i[e];if("toolCall"!==n.type||!function(e){if(!e)return!1;let t=e.toLowerCase();return"todo"===t||t.endsWith(".todo")||t.endsWith("_todo")}(n.toolName))continue;let r=e0(n,t.get(n.toolCallId));if("unknown"!==r.kind)return r.phases}}return null}(e,t)})(eb,n7,tr),[eb,n7,tr]),ra=(0,i.useMemo)(()=>is(ew.streamingMessage).join("|"),[ew.streamingMessage]),rl=(0,i.useMemo)(()=>JSON.stringify(ii(ew.streamingMessage)),[ew.streamingMessage]),ro=(0,i.useMemo)(()=>JSON.stringify(il(ew.streamingMessage)),[ew.streamingMessage]),rd=(0,i.useMemo)(()=>(function(e,t,n=[],r=[],i=[]){let s=function(e){let t=new Map;for(let n of e){if("toolResult"!==n.role||"write"!==n.toolName)continue;let e=n.details;if(!e||"object"!=typeof e||Array.isArray(e))continue;let r=e.message;if(!r||"object"!=typeof r||Array.isArray(r)||"send"!==r.op)continue;let i=Array.isArray(r.receipts)?r.receipts.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)).map(e=>({to:"string"==typeof e.to?e.to:void 0,outcome:"string"==typeof e.outcome?e.outcome:void 0})):void 0;t.set(n.toolCallId,{from:"string"==typeof r.from?r.from:void 0,receipts:i})}return t}(e),a=[],l=new Map,o=-1;for(let n=0;n<e.length;n+=1){let r=e[n];if("user"===r.role){o=n;continue}let i=is(r),d=il(r,s);if(0===i.length&&0===d.length||o<0)continue;let c=ii(r),u=l.get(o);u||(u={index:o,entryId:t[o],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(o,u),a.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...i],u.characterSummons=[...u.characterSummons,...c],u.peerSends=[...u.peerSends,...d]}if(n.length>0||i.length>0){let s=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){s=t;break}if(s>=0){let e=l.get(s);e||(e={index:s,entryId:t[s],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(s,e),a.push(e));let o=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...n.filter(e=>!o.has(e))];let d=new Set(e.characterSummons.map(e=>`${e.toolCallId} ${e.name??""}`));e.characterSummons=[...e.characterSummons,...r.filter(e=>!d.has(`${e.toolCallId} ${e.name??""}`))];let c=new Set(e.peerSends.map(e=>e.toolCallId));e.peerSends=[...e.peerSends,...i.filter(e=>!c.has(e.toolCallId))]}}return a.sort((e,t)=>e.index-t.index)})(eb,ey,ra.length>0?ra.split("|"):[],JSON.parse(rl),JSON.parse(ro)),[eb,ey,ra,rl,ro]),rc=e?.id??tb.current??void 0,ru=(O=ic(D=(0,i.useMemo)(()=>({sessionId:rc,sessionProvider:e8?.provider,turns:rd,messages:eb,subagents:tn}),[rc,e8?.provider,rd,eb,tn])),H=im(D),(0,i.useMemo)(()=>(function(e){let t=new Map;for(let n of e){let e=t.get(n.turnIndex);e?e.push(n):t.set(n.turnIndex,[n])}return t})(function(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&e.speakerId===n.speakerId&&e.turnIndex===n.turnIndex&&e.text===n.text){t[t.length-1]=n;continue}t.push(n)}return t}([...O,...H])),[O,H])),rp=tm&&0===eb.length&&!ew.isStreaming&&!t0,rh=e?.cwd??t??void 0,rm=e8?e$[`${e8.provider}:${e8.modelId}`]??null:null,rf=e8?eA[`${e8.provider}:${e8.modelId}`]??null:null,rg=(0,i.useRef)(null),rx=(0,i.useRef)(null),rv=(0,i.useCallback)(()=>{rg.current?.querySelector("textarea")?.focus({preventScroll:!0})},[]);(0,i.useEffect)(()=>(C?.(rv),()=>C?.(null)),[rv,C]),(0,i.useLayoutEffect)(()=>{let e=rx.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=tw.current?.clientHeight??0,r=()=>{let r=Math.ceil(e.getBoundingClientRect().height);r>0&&t.style.setProperty("--omp-dock-h",`${r}px`);let i=tw.current;if(!i)return;let s=n-i.clientHeight;n=i.clientHeight,s<=0||i.scrollHeight-i.scrollTop-i.clientHeight-s<=1&&(i.scrollTop+=s)};r();let i=new ResizeObserver(r);return i.observe(e),()=>i.disconnect()},[eg,tw]);let rb=(0,i.useCallback)((...e)=>(null!==ni.end&&nE(),tk(...e)),[tk,ni.end,nE]),ry=(0,r.jsx)("div",{ref:rg,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(sj,{ref:p,sessionId:e?.id??tb.current??void 0,onEnsureSession:tm&&t?tO:void 0,onLiveTranscriptPersisted:tH,onSend:rb,onAbort:tj,onSteer:ek?tR:void 0,onFollowUp:ek?tE:void 0,onPromptWithStreamingBehavior:ek?tL:void 0,isStreaming:t0,model:e8,isAutoModelSelection:tp,modelNames:eC,modelList:eN,modelError:eI,modelScopeWarnings:eT,onModelChange:tN,onMainPresetChange:e||tm?tT:void 0,mainPresetActiveAlias:tq,modelRoles:eW,onRoleModelChange:tI,modelSwitching:e6,onCompact:e||tm?t$:void 0,onAbortCompaction:tA,isCompacting:e1,compactError:e4,compactResult:e5,toolPreset:eF,onToolPresetChange:e||tm?tP:void 0,thinkingLevel:eD,effectiveThinkingLevel:eq,thinkingCeiling:eV,onThinkingLevelChange:e||tm?tD:void 0,fastMode:eJ,fastModeBusy:eG,onFastModeToggle:e||tm?eY:void 0,availableThinkingLevels:rm,thinkingLevelMap:rf,retryInfo:eZ,deliveryRows:tt,inputHistory:ri,onRecallQueue:tz,onRemoveQueuedMessage:tW,slashCommands:e9,slashCommandsLoading:te,onLoadSlashCommands:t_,onBuiltinCommand:tF,soundEnabled:M,onSoundToggle:$,onAudioUnlock:A,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t})}),rw=ew.streamingMessage,rk=(0,i.useMemo)(()=>rw?eE(rw,{isStreaming:!0}):[],[rw]),rj=(0,i.useMemo)(()=>rk.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[rk]),rS=(0,i.useMemo)(()=>rk.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[rk]),rC=rw?.role==="assistant"?rw:null,rN=ek&&(th?.kind==="running_tools"||(rC?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),rI=rC?.provider??e8?.provider,rT=rC?.credentialId;(0,i.useEffect)(()=>{if(!rN)return;let e=es();e&&er.current!==e.turn&&ei.current!==e.turn&&(er.current=e.turn,ec("working",e,rI,rT))},[rN,rI,rT,es,ec]);let[rM,r$]=(0,i.useState)(null),rR=(0,i.useCallback)(e=>{r$(e)},[]),rL=(0,i.useMemo)(()=>eS?{role:"bashExecution",command:eS.command,output:"",excludeFromContext:eS.excludeFromContext}:null,[eS]),rA=(0,i.useMemo)(()=>{let e=[ek&&!rw&&th?function(e,t){if(e?.kind==="running_tools"){let n=e.tools.map(e=>e.name);return 0===n.length?t("chat.runningTool"):1===n.length?t("chat.runningNamedTool",{name:n[0]}):n.length<=3?t("chat.runningTools",{names:n.join(", ")}):t("chat.runningToolsMore",{names:n.slice(0,2).join(", "),count:n.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(th,U):null,ej&&!eS?U("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[ek,rw,th,ej,eS,U]);(0,i.useEffect)(()=>{if(!rM)return void k?.(null);let e=[],t=[],n=0;if(rw&&rS.length>0){let r=rM.messages.length+e.length;for(let i of(e.push(rw),rS))t.push({idx:r,blocks:i}),n+=eL(i)}if(rL&&(t.push({idx:rM.messages.length+e.length}),e.push(rL)),0===t.length)return void k?.(rA?{...rM,status:rA}:rM);let r=-1;for(let e=rM.messages.length-1;e>=0;e--)if(eU(rM.messages[e])){r=e;break}let i=rM.groups.slice(),s=i.length>0?i[i.length-1]:void 0;s&&s.anchorIdx===r?i[i.length-1]={...s,entries:[...s.entries,...t],messageCount:s.messageCount+t.length,toolCallCount:s.toolCallCount+n}:i.push({anchorIdx:r,entries:t,messageCount:t.length,toolCallCount:n}),k?.({...rM,groups:i,messages:[...rM.messages,...e],status:rA})},[rM,rS,rw,rL,rA,k]),(0,i.useEffect)(()=>()=>k?.(null),[k]);let rz=td.filter(e=>"belowEditor"!==e.placement),rW=td.filter(e=>"belowEditor"===e.placement);return ev?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ev}):(0,r.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":t6,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:n5,onDragOver:n8,onDragLeave:n6,onDrop:n3,children:[t6?(0,r.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,r.jsx)("div",{className:"absolute right-3 top-3 border border-border bg-bg-panel px-3 py-2 text-sm text-text-muted shadow-sm",role:"status",children:U("chat.loadingSession")})}):null,n4&&!t0&&(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center",style:{background:"var(--accent-soft)",border:"2px dashed var(--accent-line)"},children:(0,r.jsx)("span",{className:"px-3 py-1 text-sm font-medium",style:{background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)"},children:U("chat.attachFile")})}),tl&&(0,r.jsx)(ah,{request:tl,onInput:tu}),rp&&!S?(0,r.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,r.jsxs)("div",{className:"my-auto w-full max-w-[820px] py-8",children:[(0,r.jsxs)("div",{className:"mb-3",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginLeft:16,marginRight:52,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,r.jsx)(B,{})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.8.3"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.5.1"]})]})]})]}),(0,r.jsx)(ac,{notices:ti,align:"right"})]})}):(0,r.jsxs)(r.Fragment,{children:[S&&(0,r.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:S}),(0,r.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!S,style:{display:S?"none":"flex"},children:[(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:0,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,r.jsx)(rF,{open:nF,onClose:nU,containerRef:tw,index:nO,renderedStart:na,renderedEnd:nl,contentKey:eb,onReveal:nH,onProgrammaticScroll:tx,focusRequest:nD,t:U}),nz&&(0,r.jsx)("div",{className:"chat-jump-missing",role:"status",children:U("chat.jumpMissing")}),(0,r.jsx)(ac,{notices:ti,floating:!0,align:"right"})]})}),(0,r.jsx)("div",{ref:tw,className:"chat-session-scroll min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{width:"100%",minWidth:0,maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(ad,{widgets:rz}),(0,r.jsx)(nI.Provider,{value:re,children:(0,r.jsx)(r7,{utterances:ru,children:(0,r.jsx)(aa,{messages:eb,entryIds:ey,toolResultsMap:n7,modelNames:eC,messageCwd:rh,onOpenFile:j,sessionBusy:t0,isNew:tm,isStreaming:ew.isStreaming,handleFork:tS,forkingEntryId:eQ,handleNavigate:tC,handleEditContent:ef,sessionId:e?.id??tb.current??void 0,main:nt,dispatchSlots:nr,process:nn,startIndex:na,endIndex:nl,sentinelRef:nu,laterSentinelRef:np,flashItem:nm,t:U,cues:G,cueFollowRef:t2,onProcessLogChange:rR})})}),!nd&&ew.isStreaming&&ew.streamingMessage&&rj.length>0&&(0,r.jsx)(rn,{message:eM(ew.streamingMessage,rj),sessionId:e?.id??tb.current??void 0,isStreaming:!0,modelNames:eC,cwd:rh,onOpenFile:j}),nX&&(0,r.jsx)(rB,{onDismiss:nZ,t:U}),(0,r.jsx)("div",{ref:ty})]})})}),(0,r.jsx)(rP,{questions:nq,containerRef:tw,layoutKey:nV,onJump:nR,label:U("chat.questionRail")}),(t0&&tf||nd)&&(0,r.jsxs)("button",{type:"button",onClick:nL,"aria-label":U("chat.jumpToBottom"),title:U("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:999,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",cursor:"pointer",boxShadow:"0 2px 10px rgba(0,0,0,0.28)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 5v14"}),(0,r.jsx)("path",{d:"m19 12-7 7-7-7"})]}),U("chat.jumpToBottom")]})]})]}),(0,r.jsxs)("div",{ref:rx,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[ts&&(0,r.jsx)("div",{style:{padding:"0 16px"},children:(0,r.jsx)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:(0,r.jsx)(ap,{request:ts,onRespond:tc,onActivity:e=>void tu(e,"activity"),delivery:ta})})}),(0,r.jsx)("div",{className:"min-h-0 overflow-y-auto",style:{padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(rH,{compaction:e2,t:U}),(0,r.jsx)(ao,{goal:tv,t:U}),(0,r.jsx)(rE,{summary:rt,onJump:nR,onOpenPanel:rr}),(0,r.jsx)(ad,{widgets:rW}),rs&&(0,r.jsx)(sC,{phases:rs})]})}),ry,(0,r.jsx)(sS,{statuses:to})]})]})}function ao({goal:e,t}){if(!e)return null;let n=!e.enabled,i=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:tH(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:tH(e.tokensUsed)});return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"5px 10px",border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",opacity:n?.7:1},children:[(0,r.jsx)("span",{style:{color:n?"var(--text-dim)":"var(--accent)",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",flexShrink:0},children:t("chat.goalLabel")}),(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:e.objective}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:n?t("chat.goalPaused"):e.status}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:i})]})}function ad({widgets:e}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,r.jsx)("div",{style:{padding:"5px 9px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:e.key}),(0,r.jsx)("pre",{style:{margin:0,padding:"8px 9px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)"},children:e.lines.join("\n")})]},e.key))})}function ac({notices:e,floating:t=!1,align:n="left"}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===n?"flex-end":"stretch",marginBottom:10*!t},children:e.map((n,i)=>{let s="error"===n.type?"var(--danger)":"warning"===n.type?"var(--warning)":"success"===n.type?"var(--success)":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:60,height:60,maxHeight:60,marginBottom:6*(i!==e.length-1),overflow:"hidden",borderRadius:"var(--seed-radius-r3)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:t?"var(--seed-shadow-s3)":"var(--seed-shadow-s2)",fontSize:18,lineHeight:1.45,transformOrigin:"top center",animation:n.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s,flexShrink:0}}),(0,r.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.message})]},n.id)})})}function au({focusKey:e,label:t,labelledBy:n,maxBlockSize:s="min(56dvh, 620px)",onCancel:a,delivery:l,children:o}){let{t:d}=(0,R.s)(),c=(0,i.useRef)(null),u=(0,i.useRef)({key:"",element:null});if(u.current.key!==e){let t="u"<typeof document?null:document.activeElement;u.current={key:e,element:t instanceof HTMLElement&&!c.current?.contains(t)?t:null}}return(0,i.useEffect)(()=>{let e=c.current;e&&!e.contains(document.activeElement)&&(e.querySelector('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')??e).focus();let t=u.current.element;return()=>{if(!t?.isConnected)return;let n=document.activeElement;(null===n||n===document.body||e?.contains(n))&&t.focus()}},[e]),(0,r.jsxs)("div",{ref:c,role:"dialog","aria-modal":"false","aria-label":t,"aria-labelledby":n,className:"chat-response-surface",tabIndex:-1,onKeyDown:a?e=>{"Escape"===e.key&&(e.stopPropagation(),a())}:void 0,"aria-busy":l?.status==="sending"||void 0,style:{maxBlockSize:s},children:[l?(0,r.jsx)("p",{className:"chat-response-delivery",role:"failed"===l.status?"alert":"status","data-state":l.status,children:"sending"===l.status?d("chat.responseSending"):`${d("chat.responseFailed")}${l.error?` (${l.error})`:""}`}):null,o]})}function ap({request:e,onRespond:t,onActivity:n,delivery:s}){let{t:a}=(0,R.s)(),[l,o]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[d,c]=(0,i.useState)({}),[u,p]=(0,i.useState)({}),[h,m]=(0,i.useState)(""),f=(0,i.useRef)(0),g=(0,i.useCallback)(()=>{if("ask"!==e.method||!e.timeout||!n)return;let t=Date.now();t-f.current<1e3||(f.current=t,n(e))},[e,n]);(0,i.useEffect)(()=>{if(o("editor"===e.method?e.prefill??"":""),m(""),p({}),"ask"!==e.method)return void c({});let t={};for(let n of e.questions)t[n.id]=void 0!==n.recommended&&void 0!==n.options[n.recommended]?[n.recommended]:[];c(t)},[e]);let x=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:l})};if("ask"===e.method){let n=e.questions.every(e=>(d[e.id]?.length??0)>0||(u[e.id]?.trim().length??0)>0),i=()=>{n&&t(e,{value:JSON.stringify({kind:"submit",results:e.questions.map(e=>{let t=u[e.id]?.trim();return{id:e.id,question:e.question,options:e.options.map(e=>e.label),multi:e.multi??!1,selectedOptions:(d[e.id]??[]).map(t=>e.options[t]?.label).filter(e=>void 0!==e),...t?{customInput:t}:{}}})})})};return(0,r.jsx)(au,{focusKey:e.id,label:a("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:s,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:a("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:a("chat.agentQuestionHint")}),e.timeout?(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:a("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,r.jsx)("div",{style:{display:"grid",gap:20},children:e.questions.map((t,n)=>{let s=d[t.id]??[];return(0,r.jsxs)("section",{style:{paddingTop:20*(0!==n),borderTop:0===n?"none":"1px solid var(--hairline)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[t.header&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.header}),e.questions.length>1&&(0,r.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[n+1,"/",e.questions.length]})]}),(0,r.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:t.question}),(0,r.jsx)("div",{role:t.multi?"group":"radiogroup","aria-label":t.question,style:{display:"grid",gap:4},children:t.options.map((e,n)=>{let i=s.includes(n),l=t.recommended===n;return(0,r.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":i,onClick:()=>{var e,r;return e=t.id,r=t.multi??!1,void(g(),c(t=>{let i=t[e]??[],s=r?i.includes(n)?i.filter(e=>e!==n):[...i,n]:[n];return{...t,[e]:s}}))},style:{display:"grid",gridTemplateColumns:"18px minmax(0, 1fr) auto",alignItems:"start",gap:9,width:"100%",minHeight:40,padding:"9px 10px",border:`1px solid ${i?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:i?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{display:"grid",placeItems:"center",width:16,height:16,marginTop:1,border:`1px solid ${i?"var(--text)":"var(--text-dim)"}`,borderRadius:t.multi?"var(--radius-control)":"50%",background:i?"var(--seed-color-fg-neutral)":"transparent",color:"var(--seed-color-fg-neutral-inverted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1},children:i&&(t.multi?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 5.2 4.1 7.2 8 2.8"})}):(0,r.jsx)("span",{style:{width:5,height:5,borderRadius:"50%",background:"currentColor"}}))}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:"var(--seed-font-size-t4-static)",fontWeight:i?600:500},children:e.label}),e.description&&(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.45},children:e.description}),i&&e.preview&&(0,r.jsx)("span",{style:{display:"block",marginTop:8,padding:"7px 8px",borderLeft:"2px solid var(--border-strong)",background:"var(--bg-subtle)",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,whiteSpace:"pre-wrap"},children:e.preview})]}),l&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:a("chat.recommended")})]},`${t.id}:${n}`)})}),(0,r.jsx)("input",{value:u[t.id]??"",onChange:e=>{g(),p(n=>({...n,[t.id]:e.target.value}))},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&i()},placeholder:a("chat.customAnswer"),"aria-label":a("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"}})]},t.id)})})}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:a("chat.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({kind:"chat"})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:a("chat.chatAboutThis")}),(0,r.jsx)("button",{type:"button",disabled:!n||s?.status==="sending",onClick:i,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:n&&s?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:n&&s?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:n&&s?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:s?.status==="sending"?a("chat.responseSending"):a("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,r.jsx)(au,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:s,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:a("chat.planApproval")}),(0,r.jsx)("div",{id:`plan-review-${e.id}`,style:{marginTop:4,color:"var(--text)",fontSize:"var(--seed-font-size-t5-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:5,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)",overflowWrap:"anywhere"},children:e.planFilePath})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,r.jsx)(tD,{children:e.planContent})}),(0,r.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("textarea",{value:h,onChange:e=>m(e.target.value),placeholder:a("chat.planFeedback"),"aria-label":a("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",resize:"vertical",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"refine",feedback:h.trim()})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:a("chat.refinePlan")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"approve"})}),style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:a("chat.approvePlan")})]})]})]})}):(0,r.jsx)(au,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:s,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{id:`extension-request-${e.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:a("chat.extensionRequest")})]}),(0,r.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===e.method&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,r.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(n=>(0,r.jsx)("button",{onClick:()=>t(e,{value:n}),style:{width:"100%",minHeight:40,padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t4-static)"},children:n},n))}),"input"===e.method&&(0,r.jsx)("input",{autoFocus:!0,value:l,placeholder:e.placeholder,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&x()},style:{width:"100%",padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",fontSize:"var(--seed-font-size-t4-static)"}}),"editor"===e.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:l,onChange:e=>o(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&x()},style:{width:"100%",minHeight:220,padding:10,borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:a("chat.cancel")}),"confirm"===e.method?(0,r.jsx)("button",{onClick:x,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:a("chat.confirm")}):"select"!==e.method?(0,r.jsx)("button",{onClick:x,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:a("chat.submit")}):null]})]})})}function ah({request:e,onInput:t}){let{t:n}=(0,R.s)(),s=(0,i.useRef)(null),a=(0,i.useRef)(!1),l=ew(e.lines);return(0,i.useEffect)(()=>{s.current?.focus()},[e.id]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"var(--seed-color-bg-overlay-muted)"},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:e=>{e.target.closest("button")||s.current?.focus()},style:{position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:s,"aria-label":n("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(a.current||n.nativeEvent.isComposing)return;let r=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=eS[e.key];if(t)return t;if(1===e.key.length)return`\x1b${e.key}`}return"Enter"===e.key?e.shiftKey?"\n":"\r":"Tab"===e.key?e.shiftKey?"\x1b[Z":" ":ej[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(a.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{a.current=!0},onCompositionEnd:n=>{a.current=!1;let r=n.currentTarget;queueMicrotask(()=>{let n=r.value;r.value="",n&&t(e,n)})},onPaste:n=>{n.preventDefault();let r=n.clipboardData.getData("text");r&&t(e,`\x1b[200~${r}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:n("chat.extensionPanel")}),(0,r.jsx)("button",{onClick:()=>t(e,"\x03"),style:{padding:"5px 9px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:n("chat.close")})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,maxHeight:"calc(min(760px, 100vh - 40px) - 48px)",overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(l.length?l:[""]).map((e,t,n)=>{var s;return(0,r.jsxs)(i.Fragment,{children:[(s=`line-${t}`,ek(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${s}-${t}`):e.text)),t<n.length-1?"\n":null]},t)})})]})})}function am({onPick:e,t}){let[n,s]=(0,i.useState)(""),[a,l]=(0,i.useState)({kind:"idle"}),o=(0,i.useRef)(null),d=n.trim();(0,i.useEffect)(()=>{if(d.length<2)return void l({kind:"idle"});let e=new AbortController;l({kind:"loading"});let t=setTimeout(()=>{fetch(`/api/sessions/search?q=${encodeURIComponent(d)}`,{signal:e.signal,cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);l({kind:"done",data:await e.json()})}).catch(()=>{e.signal.aborted||l({kind:"error"})})},250);return()=>{clearTimeout(t),e.abort()}},[d]);let c=e=>{let t=o.current?.querySelectorAll("button");t&&0!==t.length&&t[Math.max(0,Math.min(t.length-1,e))]?.focus()},u="done"===a.kind?a.data:null,p=u?.truncated?t(`palette.searchTruncated.${u.truncated}`,{scanned:u.scannedSessions,total:u.totalSessions}):null;return(0,r.jsxs)("div",{className:"palette-search",children:[(0,r.jsx)("input",{type:"search",value:n,onChange:e=>s(e.target.value),onKeyDown:t=>{if(!t.nativeEvent.isComposing){if("ArrowDown"===t.key)t.preventDefault(),c(0);else if("Enter"===t.key&&u&&u.hits.length>0){t.preventDefault();let n=u.hits[0],r=u.sessions[n.sessionId];r&&e(r,n,u.query)}}},placeholder:t("palette.searchPlaceholder"),"aria-label":t("palette.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),d.length>=2&&(0,r.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":t("palette.searchResults"),"aria-busy":"loading"===a.kind,children:[(0,r.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===a.kind&&t("palette.searching"),"error"===a.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),p?` \xb7 ${p}`:"",u&&u.compactedHits>0?` \xb7 ${t("palette.searchCompacted",{count:u.compactedHits})}`:""]}),u&&u.hits.length>0&&(0,r.jsx)("div",{ref:o,className:"palette-search-list",children:u.hits.map((n,i)=>{let s=u.sessions[n.sessionId],a=n.matchStart+u.query.length;return(0,r.jsxs)("button",{type:"button",disabled:!s,onClick:()=>s&&e(s,n,u.query),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),c(i+("ArrowDown"===e.key?1:-1)))},children:[(0,r.jsxs)("span",{className:"palette-search-title",children:[(0,r.jsx)("span",{children:s?s.name?.trim()||s.firstMessage?.trim()||s.id:""}),(0,r.jsx)("small",{children:"user"===n.role?t("palette.searchRoleUser"):t("palette.searchRoleAssistant")})]}),(0,r.jsxs)("span",{className:"palette-search-snippet",children:[n.snippet.slice(0,n.matchStart),(0,r.jsx)("mark",{children:n.snippet.slice(n.matchStart,a)}),n.snippet.slice(a)]})]},`${n.sessionId}:${n.entryId}`)})})]})]})}var af=n(50640),ag=n(73620);let ax=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function av(e){return function e(t,n){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(n.has(t))return"[Circular]";n.add(t);try{return t.map(t=>e(t,n)).filter(Boolean).join(", ")}finally{n.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}let ab=["tags","categories","keywords","tag","category"];function ay({data:e}){var t;if(!e)return null;let n=Object.entries(e);if(0===n.length)return null;let i="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,s=ab.find(t=>Array.isArray(e[t])),a=s?e[s].map(av).filter(Boolean):[],l=n.filter(([e])=>e!==s&&("title"!==e||!i));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:i}),a.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:a.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),l.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:l.map(([e,t])=>(0,r.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,r.jsx)("dt",{children:e}),(0,r.jsx)("dd",{children:function(e){let t=av(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,r.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(t)})]},e))})]})}let aw={source:"Source",preview:"Preview",diff:"Diff"},ak={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},aj={width:48,minWidth:48,padding:"0 10px",textAlign:"right",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:11,fontStyle:"normal",fontVariantNumeric:"tabular-nums",lineHeight:"20.8px",userSelect:"none",flexShrink:0,verticalAlign:"top"};function aS(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function aC(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function aN(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let n=t.getRangeAt(0);if(!e.contains(n.startContainer)||!e.contains(n.endContainer))return null;let r=aC(n.startContainer),i=aC(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let s=Number(r.dataset.lineNumber),a=Number(i.dataset.lineNumber);if(!Number.isInteger(s)||!Number.isInteger(a))return null;if(s<a){let e=r.querySelector(".file-source-line-content");if(e?.contains(n.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(n.startContainer,n.startOffset),0===t.toString().length){let e=r.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((r=e).dataset.lineNumber))}}let t=i.querySelector(".file-source-line-content");if(t?.contains(n.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(n.endContainer,n.endOffset),0===e.toString().length){let e=i.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(a=Number((i=e).dataset.lineNumber))}}}return s>a?null:{startLine:s,endLine:a}}function aI({rows:e,stylesheet:t,useInlineStyles:n,wrapLines:i}){return e.map((e,s)=>{let a=e.children??[],l=a[0]?.properties?.className,o=Array.isArray(l)&&l.includes("react-syntax-highlighter-line-number"),d=o?a[0]:null,c=o?a.slice(1):a;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":s+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,af.Ay)({node:d,stylesheet:t,useInlineStyles:n,key:`source-line-number-${s}`}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:i?"anywhere":"normal",whiteSpace:i?"pre-wrap":"pre"},children:c.map((e,r)=>(0,af.Ay)({node:e,stylesheet:t,useInlineStyles:n,key:`source-token-${s}-${r}`}))})]},`source-line-${s}`)})}function aT(e,t,n,r={}){let i=e8(e),s=new URLSearchParams({type:t});for(let[e,t]of(n&&s.set("sessionId",n),Object.entries(r)))void 0!==t&&s.set(e,String(t));return`/api/files/${i}?${s.toString()}`}function aM({filePath:e,sourceSessionId:t}){let{t:n}=(0,R.s)();return(0,r.jsx)("a",{href:aT(e,"download",t),download:e6(e),title:n("i18n.downloadFile"),"aria-label":n("i18n.downloadFile"),className:"file-viewer-icon-button",children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})}function a$(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function aR({patch:e}){let t,{t:n}=(0,R.s)(),i=(t=na(e))?t.flatMap(e=>e.rows.flatMap(e=>{if("hunk"===e.type)return[];if("context"===e.left.type&&"context"===e.right.type)return[{type:"unchanged",text:e.right.text,oldLineNo:e.left.lineNo,newLineNo:e.right.lineNo}];let t=[];return"removed"===e.left.type&&t.push({type:"removed",text:e.left.text,oldLineNo:e.left.lineNo,newLineNo:null}),"added"===e.right.type&&t.push({type:"added",text:e.right.text,oldLineNo:null,newLineNo:e.right.lineNo}),t})):[];if(!i.some(e=>"unchanged"!==e.type))return(0,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:n("i18n.noChanges")});let s=new Set(i.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),a=new Set;for(let e of s)for(let t=Math.max(0,e-3);t<=Math.min(i.length-1,e+3);t++)a.add(t);let l=[],o=0;for(;o<i.length;)if(a.has(o)){let e=[];for(;o<i.length&&a.has(o);)e.push(i[o]),o++;l.push({hidden:!1,lines:e})}else{let e=0;for(;o<i.length&&!a.has(o);)e++,o++;l.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...ak},children:l.map((e,t)=>{if(e.hidden)return(0,r.jsxs)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:["... ",e.count," unchanged lines ..."]},t);let n=e.lines.map((e,t)=>{let n="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",s="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:n,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,r.jsx)("span",{style:aj,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:s,userSelect:"none",flexShrink:0,fontWeight:600},children:i}),(0,r.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},t)});return(0,r.jsx)("div",{children:n},t)})})}function aE({filePath:e,cwd:t,sourceSessionId:n}){let{t:s}=(0,R.s)(),[a,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(null),g=(0,i.useRef)(null),x=e6(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{d(0),u(null),h(null),f(null),l(!1),g.current&&(g.current.close(),g.current=null);let t=new EventSource(aT(e,"watch",n));return g.current=t,t.addEventListener("connected",()=>l(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&u(t.size)}catch{}d(e=>e+1)}),t.addEventListener("error",()=>l(!1)),t.onerror=()=>l(!1),()=>{t.close(),g.current=null}},[e,n]);let v=aT(e,"read",n,o?{v:o}:void 0),b=null!=c?a$(c):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:e3(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:x||"image"}),p&&(0,r.jsxs)("span",{children:[p.w," \xd7 ",p.h]}),b&&(0,r.jsx)("span",{children:b}),(0,r.jsxs)("span",{title:s(a?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(aM,{filePath:e,sourceSessionId:n})]}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:m?(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13},children:m}):(0,r.jsx)("img",{src:v,alt:e,onLoad:e=>{let t=e.currentTarget;h({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>f("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function aL({filePath:e,cwd:t,sourceSessionId:n}){let{t:s}=(0,R.s)(),[a,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(null),g=(0,i.useRef)(null),x=e6(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{d(0),u(null),h(null),f(null),l(!1),g.current&&(g.current.close(),g.current=null);let t=new EventSource(aT(e,"watch",n));return g.current=t,t.addEventListener("connected",()=>l(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&u(t.size)}catch{}h(null),f(null),d(e=>e+1)}),t.addEventListener("error",()=>l(!1)),t.onerror=()=>l(!1),()=>{t.close(),g.current=null}},[e,n]);let v=aT(e,"read",n,o?{v:o}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:e3(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:x||"audio"}),null!=p&&(0,r.jsx)("span",{children:function(e){if(!Number.isFinite(e))return"";let t=Math.round(e),n=Math.floor(t/60);return`${n}:${String(t%60).padStart(2,"0")}`}(p)}),null!=c&&(0,r.jsx)("span",{children:a$(c)}),(0,r.jsxs)("span",{title:s(a?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(aM,{filePath:e,sourceSessionId:n})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,r.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[m&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:m}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:v,onLoadedMetadata:e=>h(e.currentTarget.duration),onError:()=>f("Failed to load audio"),style:{width:"100%"}},v)]})})]})}function aA({filePath:e,cwd:t,sourceSessionId:n}){let{t:s}=(0,R.s)(),[a,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),m=(0,i.useRef)(null),f=eI(e),g="pdf"===f,x=g?aT(e,"read",n,o?{v:o}:void 0):aT(e,"preview",n,o?{v:o}:void 0);return(0,i.useEffect)(()=>{d(0),u(null),h(null),l(!1),m.current&&(m.current.close(),m.current=null),fetch(aT(e,"meta",n)).then(e=>e.json()).then(e=>{e.error&&h(e.error),"number"==typeof e.size&&(u(e.size),!g&&e.size>0xa00000&&h("DOCX too large for preview (>10MB)"))}).catch(e=>h(String(e)));let t=new EventSource(aT(e,"watch",n));return m.current=t,t.addEventListener("connected",()=>l(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(u(t.size),!g&&t.size>0xa00000))return void h("DOCX too large for preview (>10MB)")}catch{}h(null),d(e=>e+1)}),t.addEventListener("error",()=>l(!1)),t.onerror=()=>l(!1),()=>{t.close(),m.current=null}},[e,g,n]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:e3(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===f?"docx preview":"pdf"}),null!=c&&(0,r.jsx)("span",{children:a$(c)}),(0,r.jsx)(aM,{filePath:e,sourceSessionId:n}),(0,r.jsxs)("span",{title:s(a?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]})]}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:p?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:p}):(0,r.jsx)("iframe",{src:x,sandbox:g?void 0:"allow-same-origin",title:s("i18n.previewFile",{file:e6(e)}),style:{width:"100%",height:"100%",border:"none",background:g?"var(--bg)":"#eef1f5"}},x)})]})}function az({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:s,onAtMention:a,gitRefreshKey:l,initialDisplayMode:o}){let d;return eT(e)?(0,r.jsx)(aE,{filePath:e,cwd:t,sourceSessionId:n}):null!==(eN[eI(e)]??null)?(0,r.jsx)(aL,{filePath:e,cwd:t,sourceSessionId:n}):null!==("pdf"===(d=eI(e))||"docx"===d?d:null)?(0,r.jsx)(aA,{filePath:e,cwd:t,sourceSessionId:n}):(0,r.jsx)(aW,{filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:s,onAtMention:a,gitRefreshKey:l,initialDisplayMode:o})}function aW({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:s,onMentionLines:a,onAtMention:l,gitRefreshKey:o,initialDisplayMode:d}){let c,u,{isDark:p}=tA(),{t:h}=(0,R.s)(),[m,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(!1),[y,w]=(0,i.useState)(!0),[k,j]=(0,i.useState)(null),[S,C]=(0,i.useState)("source"),[N,I]=(0,i.useState)(!1),[T,M]=(0,i.useState)(!1),$=(0,i.useRef)(null),E=(0,i.useRef)(0),L=(0,i.useRef)(null),[A,z]=(0,i.useState)(null),W=(0,i.useCallback)(e=>fetch(aT(e,"read",n)).then(e=>e.json()).then(e=>e.error?(j(e.error),null):(j(null),f(e),e)).catch(e=>(j(String(e)),null)),[n]),F=(0,i.useCallback)(async e=>{let n=++E.current;if(b(!0),!t){x(null),b(!1);return}try{let r=new URLSearchParams({cwd:t,path:e}),i=await fetch(`/api/git/diff?${r.toString()}`),s=await i.json();if(n!==E.current)return;x(i.ok&&s.supported&&"string"==typeof s.patch?s:null)}catch{n===E.current&&x(null)}finally{n===E.current&&b(!1)}},[t]);(0,i.useEffect)(()=>{w(!0),j(null),f(null),x(null),C("source"),I(!1),M(!1),$.current&&($.current.close(),$.current=null),W(e).finally(()=>w(!1));let t=new EventSource(aT(e,"watch",n));return $.current=t,t.addEventListener("connected",()=>{M(!0)}),t.addEventListener("change",()=>{W(e),F(e)}),t.addEventListener("error",()=>{M(!1)}),t.onerror=()=>{M(!1)},()=>{t.close(),$.current=null}},[e,W,F,n]),(0,i.useEffect)(()=>{F(e)},[F,e,o]),(0,i.useEffect)(()=>{(m?.language==="markdown"||m?.language==="html")&&"diff"!==d&&C("preview")},[m?.language,d]);let P=g?.supported===!0&&"string"==typeof g.patch,D=P&&"deleted"===g.status;(0,i.useEffect)(()=>{P||"diff"!==S||C("source")},[S,P]),(0,i.useEffect)(()=>{D&&$.current&&($.current.close(),$.current=null,M(!1))},[D]);let _=(0,i.useRef)(!1);(0,i.useEffect)(()=>{_.current=!1},[e]),(0,i.useEffect)(()=>{"diff"===d&&P&&!_.current&&(_.current=!0,C("diff"))},[d,P]);let O=(0,i.useMemo)(()=>m?.language==="markdown"?ta(m.content):"",[m]),H=(0,i.useMemo)(()=>m?.language==="markdown"?function(e){let t=function(e){let t=ax.exec(e);if(!t)return null;let n=/^---[ \t]*(?:(?:\r\n|\n|\r)|$)/gm;n.lastIndex=t[0].length;let r=n.exec(e);return r?{yaml:e.slice(t[0].length,r.index).replace(/(?:\r\n|\n|\r)$/,""),rest:e.slice(r.index+r[0].length)}:null}(e);if(!t)return{data:null,rest:e};try{let e=(0,ag.Hh)(t.yaml);if(e&&"object"==typeof e&&!Array.isArray(e))return{data:e,rest:t.rest}}catch{}return{data:null,rest:t.rest}}(m.content):null,[m]);(0,i.useEffect)(()=>{let e=()=>{let e=L.current;z(a&&"source"===S&&e?aN(e,window.getSelection()):null)};if(e(),a&&"source"===S)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[m?.content,S,a]);let B=(0,i.useCallback)(n=>{a&&n&&a(e3(e,t),n.startLine,n.endLine)},[t,e,a]);if((0,i.useEffect)(()=>{if(!a||"source"!==S)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let n=L.current,r=n?aN(n,window.getSelection()):null;r&&(e.preventDefault(),B(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[S,B,a]),y||"diff"===d&&v&&!m)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:h("i18n.loading")});if(k&&!D)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:k});if(!m&&!D)return null;let U=m?.language??"text",q=m?.content??"",V="html"===U,K="markdown"===U,J=(u=(c=e5(e).replace(/\/+$/,"")).lastIndexOf("/"))<0?"":0===u?"/":2===u&&/^[a-zA-Z]:\//.test(c)?c.slice(0,3):c.slice(0,u),G=q.split("\n"),Y=D?"diff":S,Z=D?["diff"]:["source",...V||K?["preview"]:[],...P?["diff"]:[]],X=D?h("files.deleted"):`${U} \xb7 ${G.length} lines \xb7 ${a$(m.size)}`;return(0,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{className:"file-viewer-toolbar",style:{display:"flex",alignItems:"center",gap:8,padding:"5px 12px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{className:"file-viewer-path",style:{fontFamily:"var(--font-mono)"},title:e,children:e3(e,t)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:X,children:X}),!D&&(0,r.jsx)("span",{title:T?h("i18n.liveSync"):h("i18n.notWatching"),"aria-label":T?h("i18n.liveSync"):h("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:T?"#4ade80":"var(--border)",boxShadow:T?"0 0 4px #4ade80":"none"}}),(0,r.jsxs)("div",{className:"file-viewer-controls",children:[Z.length>1&&(0,r.jsx)("div",{className:"file-viewer-mode-switch","aria-label":h("i18n.fileViewMode"),children:Z.map(e=>{let t=Y===e;return(0,r.jsx)("button",{type:"button",onClick:()=>C(e),title:"diff"===e?h("i18n.compareHead"):void 0,"aria-pressed":t,className:"file-viewer-mode-button",style:{background:t?"var(--bg-selected)":"transparent",color:t?"var(--text)":"var(--text-muted)"},children:aw[e]},e)})}),(0,r.jsxs)("div",{className:"file-viewer-actions",children:[(l||a)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{A&&a?B(A):l?.(e3(e,t),!1)},title:A&&a?`${h("i18n.mentionSelectedLines")} (L${A.startLine}${A.startLine!==A.endLine?`-L${A.endLine}`:""})`:h("files.insertPath"),"aria-label":h("files.mention"),disabled:!l&&!a,className:"file-viewer-icon-button",children:(0,r.jsx)(aS,{})}),"source"===Y&&(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("button",{type:"button",onClick:()=>I(e=>!e),title:N?h("i18n.disableWrap"):h("i18n.enableWrap"),"aria-label":N?h("i18n.disableWrap"):h("i18n.enableWrap"),"aria-pressed":N,className:"file-viewer-icon-button",style:{background:N?"var(--bg-selected)":"transparent",color:N?"var(--text)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,r.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,r.jsx)("path",{d:"M3 18h7"})]})})})]}),!D&&(0,r.jsx)(aM,{filePath:e,sourceSessionId:n})]})]}),(0,r.jsx)("div",{ref:L,className:"file-viewer-content",style:{flex:1,overflow:"auto",background:"var(--bg)"},children:"diff"===Y&&P?(0,r.jsx)(aR,{patch:g.patch}):V&&"preview"===Y?(0,r.jsx)("iframe",{srcDoc:q,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:h("i18n.htmlPreview")}):K&&"preview"===Y?(0,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[H?.data&&(0,r.jsx)(ay,{data:H.data}),(0,r.jsx)(e4.oz,{remarkPlugins:tu,rehypePlugins:th,components:{code({className:e,children:t,...n}){let i=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===i?(0,r.jsx)(tW,{code:s.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(tP,{code:s.replace(/\n$/,""),lang:i}):(0,r.jsx)("code",{className:e,...n,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:n,...i}){delete i.node;let a=s?eX(e,J,t??J):null;return a&&s?(0,r.jsx)("a",{href:e,...i,onClick:e=>{e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),s(a))},children:n}):(0,r.jsx)("a",{href:e,...i,children:n})},img({src:e,alt:i,...s}){delete s.node;let a="string"==typeof e?eX(e,J,t??J):null,l=a?aT(a,"read",n):e;return(0,r.jsx)("img",{src:l,alt:i??"",loading:"lazy",...s})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})},children:O})]}):(0,r.jsx)(e1.A,{className:N?"file-source-view is-wrapped":"file-source-view",language:"text"===U?"plaintext":U,style:p?e2.xJ:e2.vs,showLineNumbers:!0,lineNumberStyle:{...aj},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...ak,width:N?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",overflowWrap:N?"anywhere":"normal"}},renderer:e=>(0,r.jsx)(aI,{...e,wrapLines:N}),wrapLongLines:N,children:q})})]})}function aF({tabs:e,activeTabId:t,onSelectTab:n,onCloseTab:s}){let{t:a,locale:l}=(0,R.s)(),[o,d]=(0,i.useState)(null);return(0,r.jsx)("div",{className:"file-tab-list",role:"tablist","aria-label":"ko"===l?"열린 파일 탭":"Open file tabs",style:{display:"flex",alignItems:"flex-end",overflowX:"auto",flexShrink:0,height:36},children:e.map(e=>{let i=e.id===t;return(0,r.jsxs)("div",{className:`file-tab${i?" is-active":""}`,role:"presentation",onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:t=>{1===t.button&&(t.preventDefault(),t.stopPropagation(),s(e.id))},style:{display:"flex",alignItems:"center",height:36,paddingRight:6,borderRight:"1px solid var(--border)",fontSize:12,whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,r.jsxs)("button",{type:"button",role:"tab","aria-selected":i,onClick:()=>n(e.id),title:e.filePath,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,height:"100%",padding:"0 0 0 12px",border:"none",background:"none",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,r.jsx)("span",{style:{flexShrink:0,opacity:i?1:.7,display:"flex",alignItems:"center"},children:nm(e.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:i?500:400},children:e.label})]}),(0,r.jsx)("button",{className:"file-tab-close",onClick:t=>{t.stopPropagation(),s(e.id)},onMouseEnter:()=>d(e.id),onMouseLeave:()=>d(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:o===e.id?"var(--bg-hover)":"transparent",border:"none",color:o===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:a("i18n.close"),"aria-label":`${a("i18n.close")} ${e.label}`,children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,r.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})})}let aP=["inherit","off","auto","minimal","low","medium","high","xhigh","max"],aD=new Set(aP);function a_(e){return void 0!==e&&aD.has(e)}function aO(e){if(!e)return[...aP];let t=new Set(e);return aP.filter(e=>"inherit"===e||"off"===e||"auto"===e||t.has(e))}function aH(e){if(!e)return"inherit";let t=e.lastIndexOf(":"),n=t>=0?e.slice(t+1):void 0;return a_(n)?n:"inherit"}function aB(e,t){let n=e.lastIndexOf(":"),r=a_(n>=0?e.slice(n+1):void 0)?e.slice(0,n):e;return"inherit"===t?r:`${r}:${t}`}var aU=n(98795),aq=n.n(aU);function aV(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase()}function aK({value:e,options:t,onChange:n,disabled:s=!1,placeholder:a="Select…",searchPlaceholder:l="Search options…",noResultsLabel:o="No matching options",ariaLabel:d,className:c,style:u}){let p=(0,i.useRef)(null),h=(0,i.useRef)(null),m=(0,i.useRef)(null),f=(0,i.useRef)([]),[g,x]=(0,i.useState)(!1),[v,b]=(0,i.useState)(""),[y,w]=(0,i.useState)(0),k=(0,i.useId)(),j=t.find(t=>t.value===e),S=(0,i.useMemo)(()=>{let e=aV(v.trim());return e?t.filter(t=>aV(`${t.label} ${t.value} ${t.searchText??""}`).includes(e)):t},[t,v]);(0,i.useEffect)(()=>{if(!g)return;let e=e=>{p.current?.contains(e.target)||x(!1)};return document.addEventListener("pointerdown",e),()=>document.removeEventListener("pointerdown",e)},[g]),(0,i.useEffect)(()=>{g?requestAnimationFrame(()=>m.current?.focus()):b("")},[g]),(0,i.useEffect)(()=>{if(!g)return;let t=S.findIndex(t=>t.value===e&&!t.disabled);w(t>=0?t:Math.max(0,S.findIndex(e=>!e.disabled)))},[S,g,e]),(0,i.useEffect)(()=>{(y>=S.length||S[y]?.disabled)&&w(Math.max(0,S.findIndex(e=>!e.disabled)))},[y,S]),(0,i.useEffect)(()=>{g&&f.current[y]?.scrollIntoView({block:"nearest"})},[y,g]);let{side:C,maxHeight:N}=i4(p,g,{viewportFraction:.6,cap:296,gap:5,prefer:"below",minHeight:160}),I=e=>{e.disabled||(n(e.value),x(!1))},T=e=>{if(!S.length)return;let t=y;for(let n=0;n<S.length;n+=1)if(t=(t+e+S.length)%S.length,!S[t].disabled)return void w(t)};return(0,r.jsxs)("div",{ref:p,className:`${aq().root}${c?` ${c}`:""}`,style:u,children:[(0,r.jsxs)("button",{ref:h,type:"button",className:aq().trigger,disabled:s,"aria-label":d,"aria-haspopup":"listbox","aria-expanded":g,"aria-controls":g?k:void 0,onClick:()=>x(e=>!e),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),x(!0))},children:[(0,r.jsx)("span",{className:j?aq().value:aq().placeholder,children:j?.label??(e||a)}),(0,r.jsx)("svg",{className:aq().chevron,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m3 4.5 3 3 3-3"})})]}),g&&(0,r.jsxs)("div",{className:aq().popover,style:"above"===C?{bottom:"calc(100% + 5px)",maxHeight:N}:{top:"calc(100% + 5px)",maxHeight:N},"data-dismissible-layer":"searchable-select",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),x(!1),h.current?.focus())},children:[(0,r.jsxs)("div",{className:aq().searchWrap,children:[(0,r.jsxs)("svg",{className:aq().searchIcon,viewBox:"0 0 16 16","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"4.25"}),(0,r.jsx)("path",{d:"m10.2 10.2 3.1 3.1"})]}),(0,r.jsx)("input",{ref:m,className:aq().search,value:v,placeholder:l,"aria-label":l,role:"combobox","aria-expanded":"true","aria-controls":k,"aria-activedescendant":S[y]?`${k}-${y}`:void 0,autoComplete:"off",spellCheck:!1,onChange:e=>{b(e.target.value),w(0)},onKeyDown:e=>{if("ArrowDown"===e.key)e.preventDefault(),T(1);else if("ArrowUp"===e.key)e.preventDefault(),T(-1);else if("Enter"===e.key){e.preventDefault();let t=S[y];t&&I(t)}else"Tab"===e.key&&x(!1)}})]}),(0,r.jsx)("div",{id:k,className:aq().options,role:"listbox","aria-label":d,style:{maxHeight:Math.max(0,N-46)},children:S.length?S.map((t,n)=>(0,r.jsxs)("button",{ref:e=>{f.current[n]=e},id:`${k}-${n}`,type:"button",role:"option","aria-selected":t.value===e,className:aq().option,"data-active":n===y,"data-selected":t.value===e,disabled:t.disabled,onMouseEnter:()=>w(n),onClick:()=>I(t),children:[(0,r.jsxs)("span",{className:aq().optionCopy,children:[(0,r.jsx)("span",{className:aq().optionLabel,children:t.label}),t.description&&(0,r.jsx)("span",{className:aq().optionDescription,children:t.description})]}),t.value===e&&(0,r.jsx)("svg",{className:aq().check,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m2.3 6.2 2.2 2.2 5.2-5.2"})})]},t.value)):(0,r.jsx)("div",{className:aq().empty,children:o})})]})]})}let aJ=["global","project"],aG=["implSonnet","implOpus","implDeepSeek","makerHardUiOpus","makerHardCodeOpus","makerHardCodeSonnet"];function aY(e){return`${e.provider}/${e.id}`}function aZ({cwd:e,onRolesChanged:t}){let{t:n}=(0,R.s)(),[s,a]=(0,i.useState)([]),[l,o]=(0,i.useState)([]),[d,c]=(0,i.useState)({}),[u,p]=(0,i.useState)("global"),[h,m]=(0,i.useState)(!0),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),b=(0,i.useCallback)(async t=>{if(!e){a([]),o([]),c({}),m(!1);return}m(!0),g(null);try{let n=`?cwd=${encodeURIComponent(e)}`,[r,i]=await Promise.all([fetch(`/api/model-roles${n}`,t?{signal:t}:void 0),fetch(`/api/models${n}`,t?{signal:t}:void 0)]);if(!r.ok)throw Error(`HTTP ${r.status}`);let s=await r.json();if(s.error)throw Error(s.error);if(!i.ok)throw Error(`HTTP ${i.status}`);let l=await i.json();a(s.roles??[]),o(l.modelList??[]),c(l.thinkingLevels??{})}catch(e){if("AbortError"===e.name)return;g(e instanceof Error?e.message:String(e))}finally{m(!1)}},[e]);(0,i.useEffect)(()=>{let e=new AbortController;return b(e.signal),()=>e.abort()},[b]);let y=(0,i.useCallback)(async(n,r)=>{if(e){v(n),g(null);try{let i=await fetch("/api/model-roles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,role:n,selector:r,scope:u})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);a(s.roles??[]),t?.()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(null)}}},[e,u,t]),w=(0,i.useMemo)(()=>s.filter(e=>!e.hidden),[s]),k=w.some(e=>aG.includes(e.role)&&!e.selector);return e?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:700,color:"var(--text)",marginBottom:4},children:n("roles.title")}),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:n("roles.description")}),!h&&k&&(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",lineHeight:1.5,marginTop:4},children:n("roles.harnessNote")})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:n("roles.scope")}),(0,r.jsx)("div",{style:{display:"flex",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,overflow:"hidden"},children:aJ.map(e=>(0,r.jsx)("button",{onClick:()=>p(e),style:{padding:"4px 10px",border:"none",background:u===e?"var(--bg-selected)":"transparent",color:u===e?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:u===e?600:400},children:"global"===e?n("roles.scopeGlobal"):n("roles.scopeProject")},e))}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:"global"===u?"~/.omp/agent/config.yml":".omp/config.yml"})]}),f&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--danger, #ff4757)"},children:f}),h?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("i18n.loading")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:w.map(e=>{let t=e.resolved?`${e.resolved.provider}/${e.resolved.modelId}`:aB(e.selector??"","inherit"),i=aH(e.selector),s=aO(d[e.resolved?`${e.resolved.provider}:${e.resolved.modelId}`:""]),a=aG.includes(e.role);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,rowGap:6},children:[(0,r.jsx)("span",{style:{flexShrink:0,minWidth:62,padding:"2px 6px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-subtle)",color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:e.tag??e.role.toUpperCase()}),(0,r.jsxs)("div",{style:{minWidth:0,flex:"0 0 auto",width:128},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontWeight:600},children:e.name}),a&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-muted)",lineHeight:1.35},children:n(`roles.harness.${e.role}`)}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)"},children:a&&!e.selector?n("roles.harnessUnset"):n(`roles.source.${e.source}`)})]}),(0,r.jsx)(aK,{value:t,disabled:x===e.role,ariaLabel:e.name,style:{flex:"1 1 160px",minWidth:0},onChange:t=>{if(!t)return void y(e.role,null);let n=l.find(e=>aY(e)===t),r=n?d[`${n.provider}:${n.id}`]:void 0,i=aH(e.selector),s=aO(r).includes(i)?i:"inherit";y(e.role,aB(t,s))},options:[{value:"",label:n("roles.unset")},...l.map(e=>({value:aY(e),label:`${e.name} — ${e.provider}`,searchText:aY(e)})),...t&&!l.some(e=>aY(e)===t)?[{value:t,label:t}]:[]]}),e.warning&&(0,r.jsx)("span",{title:e.warning,style:{color:"var(--warning, #ffb347)",fontSize:12},children:"!"})]}),e.resolved&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",paddingLeft:72},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,whiteSpace:"nowrap"},children:n("roles.thinking")}),(0,r.jsx)("div",{role:"group","aria-label":`${e.name} ${n("roles.thinking")}`,style:{display:"flex",flex:"1 1 auto",minWidth:0,flexWrap:"wrap",gap:3},children:s.map(s=>{let a=i===s;return(0,r.jsx)("button",{type:"button","aria-pressed":a,disabled:x===e.role,title:"inherit"===s?n("roles.thinkingInherit"):s,onClick:()=>{a||y(e.role,aB(t,s))},style:{padding:"3px 7px",border:`1px solid ${a?"var(--accent)":"var(--border)"}`,borderRadius:4,background:a?"var(--bg-selected)":"transparent",color:a?"var(--accent)":"var(--text-muted)",cursor:x===e.role?"not-allowed":"pointer",fontFamily:"var(--font-mono)",fontSize:10,fontWeight:a?700:500,lineHeight:1.2,opacity:x===e.role?.55:1},children:s},s)})})]})]},e.role)})})]}):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("roles.needsProject")})}function aX(e){window.open(e,"_blank","noopener,noreferrer")}var aQ=n(67381),a0=n(64433),a1=n(70350),a2=n(88195),a4=n(9312),a5=n(87275),a8=n(22008),a6=n(95476),a3=n(35029),a7=n(14489),a9=n(78728),le=n(19872),lt=n(7751),ln=n(92526),lr=n(48238),li=n(57794),ls=n(41098),la=n(84604),ll=n(15315),lo=n(74278),ld=n(55457),lc=n(71437),lu=n(29167),lp=n(97283),lh=n(34166),lm=n(33889),lf=n(85486),lg=n(74068),lx=n(83546),lv=n(83709);let lb={anthropic:{Icon:aQ.A,hasColor:!1},openai:{Icon:a0.A,hasColor:!1},"openai-codex":{Icon:a0.A,hasColor:!1},google:{Icon:a1.A,hasColor:!0},"google-vertex":{Icon:a1.A,hasColor:!0},"ant-ling":{Icon:lm.A,hasColor:!0},deepseek:{Icon:a2.A,hasColor:!0},groq:{Icon:a4.A,hasColor:!1},mistral:{Icon:a5.A,hasColor:!0},moonshotai:{Icon:a8.A,hasColor:!1},"moonshotai-cn":{Icon:a8.A,hasColor:!1},moonshot:{Icon:a8.A,hasColor:!1},minimax:{Icon:a6.A,hasColor:!0},"minimax-cn":{Icon:a6.A,hasColor:!0},fireworks:{Icon:a3.A,hasColor:!0},huggingface:{Icon:a7.A,hasColor:!0},cerebras:{Icon:a9.A,hasColor:!0},openrouter:{Icon:le.A,hasColor:!1},xai:{Icon:lt.A,hasColor:!1},"cloudflare-ai-gateway":{Icon:ln.A,hasColor:!0},"cloudflare-workers-ai":{Icon:ln.A,hasColor:!0},"vercel-ai-gateway":{Icon:lr.A,hasColor:!1},"github-copilot":{Icon:li.A,hasColor:!1},"amazon-bedrock":{Icon:ls.A,hasColor:!0},"azure-openai-responses":{Icon:la.A,hasColor:!0},"kimi-coding":{Icon:ll.A,hasColor:!0},nvidia:{Icon:lf.A,hasColor:!0},opencode:{Icon:lg.A,hasColor:!1},"opencode-go":{Icon:lg.A,hasColor:!1},qwen:{Icon:lo.A,hasColor:!0},xiaomi:{Icon:lx.A,hasColor:!1},"xiaomi-token-plan-ams":{Icon:lx.A,hasColor:!1},"xiaomi-token-plan-cn":{Icon:lx.A,hasColor:!1},"xiaomi-token-plan-sgp":{Icon:lx.A,hasColor:!1},zai:{Icon:lv.A,hasColor:!1},"zai-coding-cn":{Icon:lv.A,hasColor:!1},zhipu:{Icon:ld.A,hasColor:!0},cohere:{Icon:lc.A,hasColor:!0},perplexity:{Icon:lu.A,hasColor:!0},together:{Icon:lp.A,hasColor:!0},grok:{Icon:lh.A,hasColor:!1}},ly=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function lw({label:e,children:t}){return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("label",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:e}),t]})}let lk={padding:"6px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",width:"100%",boxSizing:"border-box"};function lj({value:e,onChange:t,placeholder:n,mono:i}){return(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:n,style:{...lk,fontFamily:i?"var(--font-mono)":"inherit"}})}function lS({value:e,onChange:t,placeholder:n,mono:s,onKeyDown:a,autoComplete:l="off",spellCheck:o=!1,style:d}){let[c,u]=(0,i.useState)(!1),{t:p}=(0,R.s)();return(0,i.useEffect)(()=>{e||u(!1)},[e]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...d},children:[(0,r.jsx)("input",{type:c?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:a,placeholder:n,style:{...lk,paddingRight:34,fontFamily:s?"var(--font-mono)":"inherit"},autoComplete:l,spellCheck:o}),(0,r.jsx)("button",{type:"button",onClick:()=>u(e=>!e),"aria-label":p(c?"i18n.hideDetails":"i18n.showDetails"),title:p(c?"i18n.hideDetails":"i18n.showDetails"),style:{position:"absolute",right:5,top:"50%",transform:"translateY(-50%)",width:24,height:24,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:c?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C7 20 2.73 16.89 1 12a18.45 18.45 0 0 1 5.06-6.94"}),(0,r.jsx)("path",{d:"M9.9 4.24A10.94 10.94 0 0 1 12 4c5 0 9.27 3.11 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,r.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,r.jsx)("path",{d:"M1 1l22 22"})]}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function lC({value:e,onChange:t,placeholder:n}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:n,style:lk})}function lN({value:e,onChange:t,options:n,required:i}){let{t:s}=(0,R.s)();return(0,r.jsx)(aK,{value:e,onChange:t,options:[...i?[]:[{value:"",label:`— ${s("i18n.default")} / none —`}],...n.map(e=>({value:e,label:e}))]})}function lI({label:e,checked:t,onChange:n}){return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:t,onChange:e=>n(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function lT({children:e}){return(0,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:e})}function lM({name:e,provider:t,onChange:n,onRename:s,onDelete:a,onAddModels:l}){let{t:o}=(0,R.s)(),[d,c]=(0,i.useState)(e),[u,p]=(0,i.useState)({phase:"idle"}),[h,m]=(0,i.useState)(""),[f,g]=(0,i.useState)([]),x=(0,i.useRef)(0),v=(0,i.useRef)(null);(0,i.useEffect)(()=>c(e),[e]);let b=(e,r)=>n({...t,[e]:r});(0,i.useEffect)(()=>{t.api||n({...t,api:"openai-completions"})},[t.api]),(0,i.useEffect)(()=>{x.current+=1,p({phase:"idle"}),m(""),g([])},[e,t.baseUrl,t.api,t.apiKey]);let y=(0,i.useCallback)(async()=>{if(!t.baseUrl?.trim()||"loading"===u.phase)return;let n=++x.current;p({phase:"loading"}),g([]);try{let r=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:{...t,models:void 0}})}),i=await r.json();if(n!==x.current)return;if(!r.ok||i.error||!i.models)return void p({phase:"error",message:i.error??`HTTP ${r.status}`});p({phase:"success",models:i.models,endpoint:i.endpoint??t.baseUrl})}catch(e){if(n!==x.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,e,t]),w=new Set((t.models??[]).map(e=>e.id)),k="success"===u.phase?u.models:[],j=h.trim().toLocaleLowerCase(),S=k.filter(e=>!j||e.id.toLocaleLowerCase().includes(j)||e.name?.toLocaleLowerCase().includes(j)),C=S.slice(0,300),N=C.filter(e=>!w.has(e.id)).map(e=>e.id),I=f.filter(e=>!w.has(e)).length,T=N.length>0&&N.every(e=>f.includes(e)),M=!T&&N.some(e=>f.includes(e));return(0,i.useEffect)(()=>{v.current&&(v.current.indeterminate=M)},[M]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(lT,{children:o("i18n.provider")}),(0,r.jsx)("button",{onClick:a,style:{padding:"3px 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11},children:o("i18n.delete")})]}),(0,r.jsxs)(lw,{label:o("i18n.providerName"),children:[(0,r.jsx)(lj,{value:d,onChange:c,placeholder:"provider-name",mono:!0}),d!==e&&d.trim()&&(0,r.jsx)("button",{onClick:()=>s(d.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:4,color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:o("i18n.rename")})]}),(0,r.jsx)(lw,{label:"Base URL",children:(0,r.jsx)(lj,{value:t.baseUrl??"",onChange:e=>b("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsxs)(lw,{label:"API Key",children:[(0,r.jsx)(lS,{value:t.apiKey??"",onChange:e=>b("apiKey",e||void 0),placeholder:"ENV_VAR_NAME, !shell-command, or literal key",mono:!0}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:["Prefix with ",(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:"!"})," to run a shell command, or use an env var name"]})]}),(0,r.jsx)(lw,{label:"API",children:(0,r.jsx)(lN,{value:t.api??"openai-completions",onChange:e=>b("api",e),options:ly,required:!0})}),(0,r.jsxs)(lw,{label:"Headers",children:[(0,r.jsx)(lA,{headers:t.headers,onChange:e=>b("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to every request from this provider (e.g. User-Agent). Useful for gateways with bot detection."})]}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==u.phase&&(0,r.jsx)("button",{onClick:y,disabled:!t.baseUrl?.trim()||"loading"===u.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:t.baseUrl?.trim()&&"loading"!==u.phase?"var(--text-muted)":"var(--text-dim)",cursor:t.baseUrl?.trim()&&"loading"!==u.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===u.phase?o("models.discoveryFetching"):o("models.discoveryFetch")}),"error"===u.phase&&(0,r.jsx)("div",{style:{padding:"7px 9px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",fontSize:11,lineHeight:1.4},children:u.message}),"success"===u.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:h,onChange:e=>m(e.target.value),placeholder:o("models.discoveryFilterPlaceholder",{count:u.models.length}),"aria-label":o("models.discoveryFilter"),style:{...lk,width:"100%",minWidth:0}}),(0,r.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,r.jsxs)("label",{style:{minHeight:32,padding:"5px 9px",display:"flex",alignItems:"center",gap:8,position:"sticky",top:0,zIndex:1,borderBottom:"1px solid var(--border)",background:"var(--bg)",cursor:N.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:v,type:"checkbox",checked:T,disabled:0===N.length,onChange:()=>{let e=new Set(N);g(t=>T?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...N])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),o("models.discoverySelectShown")]}),0===C.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:o("models.discoveryNoMatches")}):C.map((e,t)=>{let n=w.has(e.id),i=f.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:i||n,disabled:n,onChange:()=>{var t;return t=e.id,void g(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),n&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:o("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:u.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:S.length>C.length?o("models.discoveryShowing",{shown:C.length,total:S.length}):o("models.discoveryFetched",{count:u.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==u.phase)return;let e=new Set(f),t=u.models.filter(t=>e.has(t.id)&&!w.has(t.id));0!==t.length&&(l(t),g([]))},disabled:0===I,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:I?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",color:I?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:I?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:I?o("models.discoveryAddSelectedCount",{count:I}):o("models.discoveryAddSelected")})]})]})]})]})}let l$=["off","minimal","low","medium","high","xhigh","max"],lR={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function lE({value:e,onChange:t}){let n=e??{},i=(e,r)=>{let i={...n};"omit"===r?delete i[e]:i[e]=r,t(Object.keys(i).length?i:void 0)};return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:l$.map(e=>{let t=n[e],s=e in n?null===t?"null":"string":"omit",a="string"==typeof t?t:"",l=lR[e],o={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},d={background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontWeight:600};return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:l,flexShrink:0,opacity:"null"===s?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===s?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===s?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>i(e,"omit"),style:{...o,..."omit"===s?d:{}},children:"Default"}),(0,r.jsx)("button",{onClick:()=>i(e,null),style:{...o,borderLeft:"1px solid var(--border)",..."null"===s?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===s?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>i(e,a||e),style:{...o,..."string"===s?d:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,r.jsx)("input",{value:a,onChange:t=>i(e,t.target.value),onFocus:()=>{"string"!==s&&i(e,a||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===s?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===s?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let lL={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function lA({headers:e,onChange:t}){let[n,s]=(0,i.useState)(()=>Object.entries(e??{}).map(([e,t],n)=>({id:n,name:e,value:t}))),a=(0,i.useRef)(n.length),l=e=>{s(e),t(function(e){let t={};for(let n of e){let e=n.name.trim();e&&(t[e]=n.value)}return Object.keys(t).length?t:void 0}(e))},o=(e,t)=>{l(n.map(n=>n.id===e?{...n,...t}:n))},d={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[n.map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{value:e.name,onChange:t=>o(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...lk,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>o(e.id,{value:t.target.value}),placeholder:"value",style:{...lk,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void l(n.filter(e=>e.id!==t))},style:d,children:"✕"})]},e.id)),(0,r.jsx)("button",{onClick:()=>s(e=>[...e,{id:a.current++,name:"",value:""}]),style:{padding:"5px 9px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,alignSelf:"flex-start"},children:"+ Add header"})]})}function lz({providerName:e,provider:t,model:n,onChange:s,onDelete:a}){let[l,o]=(0,i.useState)({phase:"idle"}),{t:d}=(0,R.s)(),[c,u]=(0,i.useState)({phase:"idle"}),p=(0,i.useRef)(0),h=(0,i.useRef)(null),m=(e,t)=>s({...n,[e]:t}),f=(()=>{if("idle"===l.phase)return null;if("testing"===l.phase)return d("i18n.testingModel");let e=[void 0!==l.latencyMs?`${l.latencyMs}ms`:null,void 0!==l.status?`HTTP ${l.status}`:null].filter(Boolean);return"success"===l.phase?[d("i18n.connected"),...e,l.responseText||null].filter(Boolean).join(" \xb7 "):[d("i18n.failed"),...e,l.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>{o({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,n.id,n.api]),(0,i.useEffect)(()=>{p.current+=1,u({phase:"idle"}),h.current=null},[e,t.baseUrl,n.id]);let g=(0,i.useCallback)(async()=>{if(n.id.trim()&&"testing"!==l.phase){o({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:n})}),i=await r.json();if(!r.ok||!i.ok)return void o({phase:"error",message:i.error??`HTTP ${r.status}`,latencyMs:i.latencyMs,status:i.status});o({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(e){o({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[n,t,e,l.phase]),x=(0,i.useCallback)(async()=>{let r=n.id.trim();if(!r||"loading"===c.phase)return;let i=++p.current;u({phase:"loading"});try{let a=new URLSearchParams({q:r,provider:e,limit:"50"});t.baseUrl?.trim()&&a.set("baseUrl",t.baseUrl.trim());let l=await fetch(`/api/models-config/catalog?${a}`),o=await l.json();if(i!==p.current)return;if(!l.ok||o.error||!o.recommendation)return void u({phase:"error",message:o.error??`HTTP ${l.status}`});let d=function(e,t){let n={...e},r=0;if(!e.name?.trim()&&t.name&&(n.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(n.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(n.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(n.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(n.maxTokens=t.maxTokens,r+=1),t.cost){let i={...e.cost??{}},s=!1;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],s=!0,r+=1);s&&(n.cost=i)}return{model:n,appliedCount:r}}(n,o.recommendation.preset);d.appliedCount>0&&(h.current=n,s(d.model)),u({phase:"success",recommendation:o.recommendation,appliedCount:d.appliedCount})}catch(e){if(i!==p.current)return;u({phase:"error",message:e instanceof Error?e.message:String(e)})}},[c.phase,n,s,t.baseUrl,e]),v=(()=>{if("success"!==c.phase)return null;let{recommendation:t,appliedCount:n}=c,r=n>0?d("models.catalogFilled",{count:n}):d("models.catalogNoEmptyFields");if("unreliable"===t.price.status){let e="no-exact-match"===t.price.reason?d("models.catalogNoExactMatch"):d("models.catalogPriceUnreliable");return`${r} \xb7 ${e}`}let i="provider"===t.price.method?d("models.catalogPriceProvider",{provider:t.price.providerName??t.price.providerId??e}):"base-url"===t.price.method?d("models.catalogPriceBaseUrl",{provider:t.price.providerName??t.price.providerId??e}):d("models.catalogPriceConsensus",{support:t.price.support,total:t.price.total});return`${r} \xb7 ${i}`})(),b="error"===c.phase?c.message:v,y="error"===c.phase?"#ef4444":"success"===c.phase&&"unreliable"===c.recommendation.price.status?"#d97706":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(lT,{children:d("i18n.model")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[f&&(0,r.jsx)("span",{title:f,style:{maxWidth:260,height:24,padding:"0 8px",border:`1px solid ${"error"===l.phase?"#fecaca":"success"===l.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===l.phase?"#fee2e2":"success"===l.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:f}),(0,r.jsxs)("button",{onClick:g,disabled:!n.id.trim()||"testing"===l.phase,title:d("i18n.testConnection"),style:{height:24,padding:"0 8px",background:"success"===l.phase?"#16a34a":"none",border:`1px solid ${"success"===l.phase?"#16a34a":"var(--border)"}`,borderRadius:4,color:"success"===l.phase?"#fff":n.id.trim()&&"testing"!==l.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"testing"!==l.phase?"pointer":"not-allowed",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",gap:5},children:["success"===l.phase&&(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===l.phase?d("i18n.checking"):"success"===l.phase?d("common.ok"):d("i18n.test")]}),(0,r.jsx)("button",{onClick:a,style:{height:24,padding:"0 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,boxSizing:"border-box"},children:d("i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(lw,{label:"ID *",children:(0,r.jsx)(lj,{value:n.id,onChange:e=>m("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(lw,{label:"Name",children:(0,r.jsx)(lj,{value:n.name??"",onChange:e=>m("name",e||void 0),placeholder:"Display name"})})]}),(0,r.jsxs)("div",{style:{padding:"10px 0",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>void x(),disabled:!n.id.trim()||"loading"===c.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:n.id.trim()&&"loading"!==c.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"loading"!==c.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===c.phase?d("models.catalogFilling"):d("models.catalogFill")}),(0,r.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:d("models.catalogSource")})]}),(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:6,height:20,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:y,fontSize:10},children:[(0,r.jsx)("span",{title:b??void 0,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b}),h.current&&(0,r.jsx)("button",{onClick:()=>{let e=h.current;e&&(h.current=null,s(e),u({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:d("models.catalogUndo")})]})]}),(0,r.jsx)(lw,{label:"API override",children:(0,r.jsx)(lN,{value:n.api??"",onChange:e=>m("api",e||void 0),options:ly})}),(0,r.jsxs)(lw,{label:"Headers",children:[(0,r.jsx)(lA,{headers:n.headers,onChange:e=>m("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to this model's requests; overrides the provider headers for this model."})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,r.jsx)(lI,{label:"Reasoning / thinking",checked:n.reasoning??!1,onChange:e=>m("reasoning",e||void 0)}),(0,r.jsx)(lI,{label:"Image input",checked:n.input?.includes("image")??!1,onChange:e=>m("input",e?["text","image"]:void 0)})]}),n.reasoning&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(lI,{label:"DeepSeek thinking compat",checked:n.compat?.thinkingFormat==="deepseek",onChange:e=>s(function(e,t){if(t)return{...e,compat:{...e.compat??{},...lL}};if(!e.compat)return e;let n={...e.compat};return delete n.thinkingFormat,delete n.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(n).length?n:void 0}}(n,e))}),(0,r.jsx)(lI,{label:"Use 'developer' role for the system prompt (disable if server rejects it)",checked:!1!==({...t.compat??{},...n.compat??{}}).supportsDeveloperRole,onChange:e=>s({...n,compat:{...n.compat??{},supportsDeveloperRole:e}})}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,r.jsx)(lT,{children:"Thinking level map"}),n.thinkingLevelMap&&(0,r.jsx)("button",{onClick:()=>m("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 7px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-dim)",cursor:"pointer"},children:"clear all"})]}),(0,r.jsx)(lE,{value:n.thinkingLevelMap,onChange:e=>m("thinkingLevelMap",e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(lw,{label:"Context window (tokens)",children:(0,r.jsx)(lC,{value:void 0!==n.contextWindow?String(n.contextWindow):"",onChange:e=>m("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(lw,{label:"Max output tokens",children:(0,r.jsx)(lC,{value:void 0!==n.maxTokens?String(n.maxTokens):"",onChange:e=>m("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(lT,{children:"Cost (per million tokens)"}),(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8},children:["input","output","cacheRead","cacheWrite"].map(e=>(0,r.jsx)(lw,{label:e,children:(0,r.jsx)(lC,{value:n.cost?.[e]!==void 0?String(n.cost[e]):"",onChange:t=>{let r;return r=parseFloat(t),void s({...n,cost:{...n.cost??{},[e]:isNaN(r)?void 0:r}})},placeholder:"0"})},e))})]})]})}function lW({provider:e,onRefresh:t}){let[n,s]=(0,i.useState)({phase:"idle"}),{t:a}=(0,R.s)(),[l,o]=(0,i.useState)(""),d=(0,i.useRef)(null),c=(0,i.useRef)(null);(0,i.useEffect)(()=>{("auth"===n.phase||"prompt"===n.phase)&&setTimeout(()=>c.current?.focus(),50)},[n.phase]),(0,i.useEffect)(()=>{s({phase:"idle"}),o(""),d.current?.close(),d.current=null},[e.id]),(0,i.useEffect)(()=>()=>{d.current?.close()},[]);let u=(0,i.useCallback)(()=>{d.current?.close(),s({phase:"connecting"}),o("");let n=new EventSource(`/api/auth/login/${encodeURIComponent(e.id)}`);d.current=n,n.onmessage=e=>{let r=JSON.parse(e.data);"auth"===r.type?(s({phase:"auth",url:r.url,instructions:r.instructions??null,token:r.token}),aX(r.url)):"device_code"===r.type?(s({phase:"device_code",userCode:r.userCode,verificationUri:r.verificationUri,intervalSeconds:r.intervalSeconds??null,expiresInSeconds:r.expiresInSeconds??null}),aX(r.verificationUri)):"prompt_request"===r.type?s({phase:"prompt",message:r.message,placeholder:r.placeholder??null,token:r.token}):"select_request"===r.type?s({phase:"select",message:r.message,options:r.options??[],token:r.token}):"progress"===r.type?s({phase:"progress",message:r.message}):"success"===r.type?(n.close(),s({phase:"success"}),t()):"error"===r.type?(n.close(),s({phase:"error",message:r.message})):"cancelled"===r.type&&(n.close(),s({phase:"idle"}))},n.onerror=()=>{n.close(),s(e=>"success"===e.phase?e:{phase:"error",message:"Connection lost"})}},[e.id,t]),p=(0,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(e.id)}`,{method:"POST"}),s({phase:"idle"}),t()},[e.id,t]),h=(0,i.useCallback)(async(t,n)=>{if(n.trim()){s({phase:"progress",message:"Verifying…"});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:n.trim()})});if(!r.ok){let e=await r.json().catch(()=>({}));s({phase:"error",message:e.error??`Server error ${r.status}`});return}o("")}catch(e){s({phase:"error",message:e instanceof Error?e.message:"Network error"})}}},[e.id]),m=(0,i.useCallback)(async(t,n)=>{s({phase:"progress",message:"Continuing…"});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:n})});if(!r.ok){let e=await r.json().catch(()=>({}));s({phase:"error",message:e.error??`Server error ${r.status}`})}}catch(e){s({phase:"error",message:e instanceof Error?e.message:"Network error"})}},[e.id]),f="connecting"===n.phase||"progress"===n.phase||"auth"===n.phase||"device_code"===n.phase||"prompt"===n.phase||"select"===n.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(lT,{children:a("i18n.subscription")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"#4ade80":"var(--text-dim)"},children:a(e.loggedIn?"i18n.connected":"i18n.notConnected")})]})]}),(0,r.jsxs)("div",{style:{minHeight:48},children:["idle"===n.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.loggedIn?"Already connected. You can re-login or disconnect.":`Connect your ${e.name} account.`}),"connecting"===n.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:a("i18n.openingBrowser")}),"select"===n.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:n.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:n.options.map(e=>(0,r.jsx)("button",{onClick:()=>m(n.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),("auth"===n.phase||"prompt"===n.phase)&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"auth"===n.phase?"Complete sign-in in the browser, then copy the redirect URL from the address bar and paste it below.":n.message}),"auth"===n.phase&&(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:["If the browser window did not open,"," ",(0,r.jsx)("a",{href:n.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:"click here to open the login page"}),"."]}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{ref:c,value:l,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&h(n.token,l)},placeholder:"auth"===n.phase?"http://localhost:1455/auth/callback?code=…":n.placeholder??"Enter value…",style:{flex:1,padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",fontFamily:"var(--font-mono)",boxSizing:"border-box"}}),(0,r.jsx)("button",{onClick:()=>h(n.token,l),disabled:!l.trim(),style:{padding:"6px 12px",background:l.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:l.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:l.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,flexShrink:0},children:a("i18n.submit")})]})]}),"device_code"===n.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:n.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:n.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:n.verificationUri}),n.expiresInSeconds?` Expires in ${Math.ceil(n.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===n.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:n.message}),"success"===n.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:a("i18n.connectedSuccessfully")}),"error"===n.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:n.message})]}),(0,r.jsx)("div",{style:{display:"flex",gap:8},children:f?(0,r.jsx)("button",{onClick:()=>{d.current?.close(),s({phase:"idle"})},style:{padding:"5px 12px",background:"none",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:a("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{onClick:u,style:{padding:"5px 14px",background:"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:5,color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontSize:12,fontWeight:600},children:a(e.loggedIn?"i18n.relogin":"i18n.login")}),e.loggedIn&&(0,r.jsx)("button",{onClick:p,style:{padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:"pointer",fontSize:12},children:a("i18n.disconnect")})]})})]})}function lF({provider:e,onRefresh:t}){let[n,s]=(0,i.useState)(""),[a,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),{t:m}=(0,R.s)();(0,i.useEffect)(()=>{s(""),u(null),h(!1)},[e.id]);let f=(0,i.useCallback)(async()=>{if(n.trim()){l(!0),u(null),h(!1);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:n.trim()})}),i=await r.json();!r.ok||i.error?u(i.error??`HTTP ${r.status}`):(s(""),h(!0),setTimeout(()=>h(!1),2e3),t())}catch(e){u(String(e))}finally{l(!1)}}},[n,e.id,t]),g=(0,i.useCallback)(async()=>{d(!0),u(null);try{let n=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),r=await n.json();!n.ok||r.error?u(r.error??`HTTP ${n.status}`):t()}catch(e){u(String(e))}finally{d(!1)}},[e.id,t]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(lT,{children:"API Key"}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.configured?"#4ade80":"var(--text-dim)"},children:m(e.configured?"i18n.configured":"i18n.notConfigured")})]})]}),(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.configured?"API key is stored. Enter a new key below to replace it, or disconnect to remove it.":`Enter your ${e.displayName} API key to enable ${e.modelCount} model${1!==e.modelCount?"s":""}.`}),(0,r.jsx)(lw,{label:"API Key",children:(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(lS,{value:n,onChange:s,onKeyDown:e=>{"Enter"===e.key&&n.trim()&&f()},placeholder:e.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:f,disabled:a||!n.trim()||p,style:{padding:"6px 12px",background:p?"#16a34a":n.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:p?"#fff":n.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:a||!n.trim()||p?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[p&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),m(p?"i18n.saved":a?"i18n.saving":"i18n.save")]})]})}),c&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:c}),e.configured&&(0,r.jsx)("button",{onClick:g,disabled:o,style:{alignSelf:"flex-start",padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:o?"not-allowed":"pointer",fontSize:12},children:m(o?"i18n.removing":"i18n.disconnect")})]})}function lP({id:e,size:t}){let n=lb[e];if(!n){let n=e.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,r.jsx)("span",{"aria-hidden":"true",style:{width:t,height:t,border:"1px solid var(--border)",borderRadius:4,color:"var(--text-dim)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:Math.max(8,Math.floor(.42*t)),fontWeight:700,lineHeight:1},children:n})}return n.hasColor?(0,r.jsx)(n.Icon,{size:t}):(0,r.jsx)(n.Icon,{size:t,style:{color:"var(--text-muted)"}})}function lD({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:n,onSelectApiKey:s,onAddCustom:a,onClose:l}){let[o,d]=(0,i.useState)(""),{t:c}=(0,R.s)(),u=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let p=o.trim().toLowerCase(),h=e.filter(e=>!e.loggedIn&&(!p||e.name.toLowerCase().includes(p))),m=t.filter(e=>!e.configured&&(!p||e.displayName.toLowerCase().includes(p)||e.id.toLowerCase().includes(p))),f=!p||"custom".includes(p)||"openai-compatible".includes(p)||"anthropic-compatible".includes(p),g=h.length+m.length+ +!!f,x={display:"flex",flexDirection:"row",alignItems:"center",gap:8,padding:"10px 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:7,boxSizing:"border-box",cursor:"pointer",minWidth:0,textAlign:"left",transition:"border-color 0.12s, background 0.12s",width:"100%"};return(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&l()},children:(0,r.jsxs)("div",{style:{width:820,maxWidth:"calc(100vw - 32px)",maxHeight:"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{ref:u,value:o,onChange:e=>d(e.target.value),onKeyDown:e=>{"Escape"===e.key&&l()},placeholder:c("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===g?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:c("i18n.noProviders")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[f&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.custom")}),f&&(0,r.jsxs)("button",{onClick:()=>{a(),l()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:c("i18n.customEndpoint")})]}),(0,r.jsx)("span",{style:{width:26,height:26,borderRadius:5,background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),h.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!f,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.subscriptions")}),h.map(e=>(0,r.jsxs)("button",{onClick:()=>{n(e.id),l()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(lP,{id:e.id,size:28})]},e.id)),m.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(h.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),m.map(e=>(0,r.jsxs)("button",{onClick:()=>{s(e.id),l()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[e.modelCount," models"]})]}),(0,r.jsx)(lP,{id:e.id,size:28})]},e.id))]})})]})})}function l_({cwd:e,onClose:t,embedded:n=!1,onModelsChanged:s}){let a=F(),{t:l}=(0,R.s)(),[o,d]=(0,i.useState)({providers:{}}),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(!1),[m,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(!1),[v,b]=(0,i.useState)({type:"roles"}),[y,w]=(0,i.useState)([]),[k,j]=(0,i.useState)([]),[S,C]=(0,i.useState)(!1),N=(0,i.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>w(e.providers)).catch(()=>{})},[]),I=(0,i.useCallback)(()=>{fetch("/api/auth/all-providers").then(e=>e.json()).then(e=>j(e.providers)).catch(()=>{})},[]),T=(0,i.useCallback)(()=>{N(),I()},[N,I]);(0,i.useEffect)(()=>{fetch("/api/models-config").then(e=>e.json()).then(e=>{d(e.providers?e:{...e,providers:{}})}).catch(()=>d({providers:{}})).finally(()=>u(!1)),T()},[T]);let M=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;o.providers?.[e];)e=`new-provider-${t++}`;d(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),b({type:"provider",name:e})},[o.providers]),$=(0,i.useCallback)((e,t)=>{d(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),E=(0,i.useCallback)((e,t)=>{d(n=>{let r=Object.entries(n.providers??{}),i=r.findIndex(([t])=>t===e);return -1===i?n:(r[i]=[t,r[i][1]],{...n,providers:Object.fromEntries(r)})}),b(n=>n?"provider"===n.type&&n.name===e?{type:"provider",name:t}:"model"===n.type&&n.providerName===e?{...n,providerName:t}:n:n)},[]),L=(0,i.useCallback)(e=>{d(t=>{let n={...t.providers??{}};return delete n[e],{...t,providers:n}}),d(e=>{let t=Object.keys(e.providers??{});return b(t.length>0?{type:"provider",name:t[0]}:null),e})},[]),A=(0,i.useCallback)(e=>{d(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),d(t=>{let n=(t.providers?.[e]?.models?.length??1)-1;return b({type:"model",providerName:e,index:n}),t})},[]),z=(0,i.useCallback)((e,t)=>{d(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]],s=new Set(i.map(e=>e.id));for(let e of t)s.has(e.id)||(s.add(e.id),i.push({id:e.id,name:e.name}));return{...n,providers:{...n.providers??{},[e]:{...r,models:i}}}})},[]),W=(0,i.useCallback)((e,t,n)=>{d(r=>{let i=r.providers?.[e]??{},s=[...i.models??[]];return s[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:s}}}})},[]),P=(0,i.useCallback)((e,t)=>{d(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]];return i.splice(t,1),{...n,providers:{...n.providers??{},[e]:{...r,models:i.length?i:void 0}}}}),b({type:"provider",name:e})},[]),D=(0,i.useCallback)(async()=>{h(!0),f(null),x(!1);try{let e=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),t=await e.json();!e.ok||t.error?f(t.error??`HTTP ${e.status}`):(x(!0),s?.(),setTimeout(()=>x(!1),2e3))}catch(e){f(String(e))}finally{h(!1)}},[o,s]),_=Object.entries(o.providers??{}),O=y.filter(e=>e.loggedIn),H=k.filter(e=>e.configured),B=(()=>{if(!v)return null;if("roles"===v.type)return(0,r.jsx)(aZ,{cwd:e??null,onRolesChanged:s});if("oauth"===v.type){let e=y.find(e=>e.id===v.providerId);return e?(0,r.jsx)(lW,{provider:e,onRefresh:T},e.id):null}if("apikey"===v.type){let e=k.find(e=>e.id===v.providerId);return e?(0,r.jsx)(lF,{provider:e,onRefresh:T},e.id):null}if("provider"===v.type){let e=o.providers?.[v.name];return e?(0,r.jsx)(lM,{name:v.name,provider:e,onChange:e=>$(v.name,e),onRename:e=>E(v.name,e),onDelete:()=>L(v.name),onAddModels:e=>z(v.name,e)},v.name):null}let t=o.providers?.[v.providerName],n=t?.models?.[v.index];return n?(0,r.jsx)(lz,{providerName:v.providerName,provider:t,model:n,onChange:e=>W(v.providerName,v.index,e),onDelete:()=>P(v.providerName,v.index)},`${v.providerName}-${v.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{position:n?"relative":"fixed",inset:n?void 0:0,width:"100%",height:"100%",zIndex:n?void 0:1e3,background:n?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{n||e.target!==e.currentTarget||t()},children:(0,r.jsxs)("div",{style:{width:n?"100%":a?"calc(100vw - 16px)":860,maxWidth:n?"none":"calc(100vw - 16px)",height:n?"100%":a?"calc(100dvh - 16px)":"78vh",maxHeight:n?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:n?"none":"1px solid var(--border)",borderRadius:10*!n,display:"flex",flexDirection:"column",boxShadow:n?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:l("common.models")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.omp/agent/models.yml"})]}),(0,r.jsx)("button",{onClick:t,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:a?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:a?"100%":210,maxHeight:a?"40vh":void 0,borderRight:a?"none":"1px solid var(--border)",borderBottom:a?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[(0,r.jsxs)("div",{onClick:()=>b({type:"roles"}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:v?.type==="roles"?"var(--bg-selected)":"none"},onMouseEnter:e=>{v?.type!=="roles"&&(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{v?.type!=="roles"&&(e.currentTarget.style.background="none")},children:[(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-muted)",flexShrink:0},children:[(0,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("circle",{cx:"9",cy:"7",r:"2.2"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"15",cy:"17",r:"2.2"})]}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1},children:l("roles.title")})]}),(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),O.map(e=>{let t=v?.type==="oauth"&&v.providerId===e.id;return(0,r.jsxs)("div",{onClick:()=>b({type:"oauth",providerId:e.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,r.jsx)(lP,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.id)}),H.map(e=>{let t=v?.type==="apikey"&&v.providerId===e.id;return(0,r.jsxs)("div",{onClick:()=>b({type:"apikey",providerId:e.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,r.jsx)(lP,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName})]},e.id)}),(O.length>0||H.length>0)&&_.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),c?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:l("i18n.loading")}):_.map(([e,t])=>{let n=v?.type==="provider"&&v.name===e,i=t.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)("div",{onClick:()=>b({type:"provider",name:e}),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{fontSize:12,fontWeight:n?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})]}),i.map((t,n)=>{let i=v?.type==="model"&&v.providerName===e&&v.index===n;return(0,r.jsxs)("div",{onClick:()=>b({type:"model",providerName:e,index:n}),style:{display:"flex",alignItems:"center",gap:6,padding:"5px 8px 5px 26px",borderRadius:5,cursor:"pointer",background:i?"var(--bg-selected)":"none"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:t.id?"var(--text-muted)":"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.id||l("i18n.newModel")}),t.reasoning&&(0,r.jsx)("span",{style:{fontSize:9,padding:"1px 4px",background:"rgba(99,102,241,0.12)",color:"rgba(99,102,241,0.8)",borderRadius:3,flexShrink:0},children:"T"})]},n)}),(0,r.jsx)("div",{onClick:t=>{t.stopPropagation(),A(e)},style:{display:"flex",alignItems:"center",gap:4,padding:"4px 8px 4px 26px",borderRadius:5,cursor:"pointer",color:"var(--text-dim)"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,r.jsxs)("span",{style:{fontSize:11},children:["+ ",l("i18n.model")]})})]},e)})]}),(0,r.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 6px"},children:(0,r.jsxs)("button",{onClick:()=>C(!0),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:"100%",padding:"6px 0",background:"none",border:"1px dashed var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.color="var(--text-muted)"},children:["+ ",l("i18n.addProvider")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:c?null:B??(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:l("i18n.selectProviderModel")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:10,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[m&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:m}),(0,r.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:l("i18n.cancel")}),(0,r.jsxs)("button",{onClick:D,disabled:p||g,style:{position:"relative",padding:"6px 16px",minWidth:92,background:g?"#16a34a":p?"var(--bg-panel)":"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:6,color:g?"#fff":p?"var(--text-muted)":"var(--seed-color-fg-neutral-inverted)",cursor:p||g?"default":"pointer",fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,transition:"background-color 0.2s ease, color 0.2s ease",animation:g?"saved-pop 0.45s ease":void 0},children:[g&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:18,animation:"saved-check-draw 0.35s ease forwards",flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:g?l("i18n.saved"):p?l("i18n.saving"):l("i18n.save")})]})]})]})}),S&&(0,r.jsx)(lD,{oauthProviders:y,apiKeyProviders:k,onSelectOAuth:e=>b({type:"oauth",providerId:e}),onSelectApiKey:e=>b({type:"apikey",providerId:e}),onAddCustom:M,onClose:()=>C(!1)})]})}function lO(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function lH(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function lB(e){let t=lH(e);return"path"===t?t:e.install?.skillsShUrl?`${t} / skills.sh`:t}function lU(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function lq(e){return e?e.slice(0,8):"unknown"}function lV({enabled:e,loading:t,onToggle:n}){let{t:i}=(0,R.s)();return(0,r.jsx)("button",{onClick:n,disabled:t,title:i(e?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),style:{flexShrink:0,width:40,height:22,borderRadius:11,border:"none",padding:0,cursor:t?"wait":"pointer",background:e?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none"},children:(0,r.jsx)("span",{style:{position:"absolute",top:3,left:e?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function lK({skill:e,cwd:t,onToggle:n,toggling:i,saveError:s,updateStatus:a,checkingUpdate:l,updating:o,updateError:d,onCheckUpdate:c,onUpdate:u}){let{t:p}=(0,R.s)(),h=lH(e),m=!e.disableModelInvocation;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===h?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===h?"rgba(99,102,241,0.8)":"var(--text-dim)"},children:h}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:function(e){if("project"===h&&e.startsWith(t)){let n=e.slice(t.length).replace(/^[/\\]/,"");return`./${n}`}return lO(e)}(e.filePath)}),(0,r.jsx)(lV,{enabled:m,loading:i,onToggle:()=>n(e)})]}),(0,r.jsxs)("div",{style:{minHeight:16,display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,flexWrap:"wrap",textAlign:"right"},children:[!m&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:p("i18n.hiddenButInvocable")}),s&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:s})]})]}),e.install?.skillsShUrl&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Source"}),(0,r.jsx)("a",{href:e.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:e.install.skillsShUrl,style:{display:"flex",alignItems:"center",gap:8,width:"fit-content",maxWidth:"100%",color:"var(--accent)",textDecoration:"none"},children:(0,r.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})]}),e.install&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Version"}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text-muted)"},children:lq(a?.currentVersion??e.install.versionHash)}),e.install.canCheckForUpdates&&(0,r.jsx)("button",{onClick:c,disabled:l||o,style:{padding:"4px 9px",border:"1px solid var(--border)",borderRadius:5,background:"none",color:"var(--text-muted)",cursor:l||o?"not-allowed":"pointer",opacity:l||o?.5:1,fontSize:11},children:p("i18n.check")}),a?.state==="update-available"&&(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"#d97706"},children:lq(a.latestVersion)}),(l||a&&"update-available"!==a.state)&&(0,r.jsx)("span",{style:{fontSize:12,color:l?"var(--accent)":a?.state==="up-to-date"?"#16a34a":a?.state==="error"?"#ef4444":"var(--text-dim)"},children:l?p("i18n.checking"):a?.state==="up-to-date"?p("i18n.upToDate"):a?.state==="unsupported"?p("i18n.automaticChecksUnavailable"):a?.message||p("i18n.checkFailed")}),a?.state==="update-available"&&(0,r.jsx)("button",{onClick:u,disabled:o||l,style:{padding:"4px 10px",border:"none",borderRadius:5,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:o||l?"not-allowed":"pointer",opacity:o||l?.5:1,fontSize:11,fontWeight:600},children:p(o?"i18n.updating":"i18n.update")})]}),d&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:d})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Name"}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:14,color:"var(--text)"},children:e.name})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Description"}),(0,r.jsx)("span",{style:{fontSize:14,color:"var(--text-muted)",lineHeight:1.6},children:e.description})]})]})}function lJ({cwd:e,installedPackages:t,projectResourcesLoaded:n,onInstalled:s}){let{t:a}=(0,R.s)(),[l,o]=(0,i.useState)(""),[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(new Set),[w,k]=(0,i.useState)("global"),j=(0,i.useRef)(null);(0,i.useEffect)(()=>{j.current?.focus()},[]);let S=(0,i.useCallback)(async e=>{if(e.trim()){p(!0),m(null),c([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),n=await t.json();if(n.error)return void m(n.error);c(n.results??[]),0===(n.results??[]).length&&m("No skills found")}catch(e){m(String(e))}finally{p(!1)}}},[]),C=(0,i.useCallback)(async t=>{g(t),v(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:w,cwd:e})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);y(e=>new Set(e).add(`${w}:${t}`)),s()}catch(e){v(String(e))}finally{g(null)}},[s,w,e]),N="global"===w?"~/.claude/skills/":`${lO(e)}/.claude/skills/`;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:a("i18n.addSkill")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:j,value:l,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&S(l)},placeholder:a("i18n.skillSearchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:13,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",outline:"none"}}),(0,r.jsx)("button",{onClick:()=>S(l),disabled:u||!l.trim(),style:{padding:"7px 16px",fontSize:13,borderRadius:6,border:"none",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:u||!l.trim()?"not-allowed":"pointer",opacity:u||!l.trim()?.5:1,flexShrink:0},children:u?a("i18n.searching"):a("i18n.search")})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(e=>(0,r.jsx)("button",{onClick:()=>{("global"===e||n)&&k(e)},disabled:"project"===e&&!n,title:"project"!==e||n?void 0:a("trust.projectScopeUnavailable"),style:{padding:"3px 10px",border:"none",cursor:"project"!==e||n?"pointer":"not-allowed",background:w===e?"var(--bg-selected)":"none",color:w===e?"var(--text)":"var(--text-dim)",fontWeight:w===e?600:400,opacity:"project"!==e||n?1:.45,borderRight:"global"===e?"1px solid var(--border)":"none"},children:e},e))}),(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",N]})]}),h&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:h}),x&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:x})]}),d.length>0?(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:d.map(e=>{let n=t[w].has(e.package)||b.has(`${w}:${e.package}`),i=f===e.package,s=e.package.indexOf("@"),l=s>-1?e.package.slice(0,s):e.package,o=s>-1?e.package.slice(s+1):null;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:o??l}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:l}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,r.jsx)("button",{onClick:()=>!n&&!i&&C(e.package),disabled:n||i||null!==f,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:5,border:"1px solid var(--border)",cursor:n||i||null!==f?"not-allowed":"pointer",background:n?"rgba(34,197,94,0.1)":"none",color:n?"#16a34a":i?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:n?`✓ ${a("i18n.installed")}`:i?a("i18n.installing"):a("i18n.install")})]},e.package)})}):!h&&!u&&(0,r.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:["Search"," ",(0,r.jsx)("a",{href:"https://skills.sh",target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",textDecoration:"none"},children:"skills.sh"})," ","to discover and install skills for your agent."]})]})}function lG({cwd:e,onClose:t,embedded:n=!1}){let s=F(),{t:a}=(0,R.s)(),[l,o]=(0,i.useState)([]),[d,c]=(0,i.useState)(!0),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(new Set),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(!1),[w,k]=(0,i.useState)({}),[j,S]=(0,i.useState)(new Set),[C,N]=(0,i.useState)(!1),[I,T]=(0,i.useState)(null),[M,$]=(0,i.useState)(null),[E,L]=(0,i.useState)(!0),[A,z]=(0,i.useState)({}),W=(0,i.useCallback)(async()=>{c(!0),p(null);try{let t=await fetch(`/api/skills?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);let r=n.skills??[];if(o(r),L(n.projectResourcesLoaded??!0),r.length>0&&!h){let e=r.find(e=>!e.disableModelInvocation)??r[0];m(e.filePath),e.disableModelInvocation&&z(t=>({...t,[lB(e)]:!0}))}return r}catch(e){return p(String(e)),[]}finally{c(!1)}},[e,h]);(0,i.useEffect)(()=>{k({}),$(null),W()},[e]);let P=(0,i.useCallback)(async t=>{let n=(t?[t]:l.filter(e=>!!e.install)).map(lU).filter(e=>!!e);if(0!==n.length){$(null),S(e=>new Set([...e,...n])),t||N(!0);try{let n=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t?.install?.package,scope:t?.install?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);k(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){$(e instanceof Error?e.message:String(e))}finally{S(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),t||N(!1)}}},[e,l]),D=(0,i.useCallback)(async t=>{if(!t.install)return;let n=lU(t);T(n),$(null);try{let r=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t.install.package,scope:t.install.scope})}),i=await r.json();if(!r.ok||i.error||!i.success)throw Error(i.error??`HTTP ${r.status}`);await W();let s=i.skill?.install?.versionHash;k(e=>({...e,[n]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:s,latestVersion:s}}))}catch(e){$(e instanceof Error?e.message:String(e))}finally{T(null)}},[e,W]),_=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;g(t=>new Set(t).add(e.filePath)),v(null);try{let n=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);o(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n)),t&&z(t=>({...t,[lB(e)]:!0}))}catch(e){v(String(e))}finally{g(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),O=l.find(e=>e.filePath===h)??null;return(0,r.jsx)("div",{style:{position:n?"relative":"fixed",inset:n?void 0:0,width:"100%",height:"100%",zIndex:n?void 0:1e3,background:n?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{n||e.target!==e.currentTarget||t()},children:(0,r.jsxs)("div",{style:{width:n?"100%":s?"calc(100vw - 16px)":860,maxWidth:n?"none":"calc(100vw - 16px)",height:n?"100%":s?"calc(100dvh - 16px)":"78vh",maxHeight:n?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:n?"none":"1px solid var(--border)",borderRadius:10*!n,display:"flex",flexDirection:"column",boxShadow:n?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:a("common.skills")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:lO(e)})]}),(0,r.jsx)("button",{onClick:t,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!E&&(0,r.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:a("trust.skillsNotLoaded")}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:s?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:s?"100%":210,maxHeight:s?"40vh":void 0,borderRight:s?"none":"1px solid var(--border)",borderBottom:s?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:d?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:a("i18n.loading")}):u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#f87171"},children:u}):0===l.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:a("i18n.noSkills")}):(()=>{let e=[];for(let{label:t,matches:n}of[{label:"project / skills.sh",matches:e=>"project"===lH(e)&&!!e.install?.skillsShUrl},{label:"project",matches:e=>"project"===lH(e)&&!e.install?.skillsShUrl},{label:"global / skills.sh",matches:e=>"global"===lH(e)&&!!e.install?.skillsShUrl},{label:"global",matches:e=>"global"===lH(e)&&!e.install?.skillsShUrl},{label:"path",matches:e=>"path"===lH(e)}]){let r=l.filter(n);r.length>0&&e.push({label:t,skills:r})}let t=e=>{let t,n,i=!b&&h===e.filePath,s=e.disableModelInvocation;return(0,r.jsxs)("div",{onClick:()=>{m(e.filePath),y(!1)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:i?"var(--bg-selected)":"none"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:s?"var(--border)":"var(--accent)",boxShadow:s?"none":"0 0 4px var(--accent)",transition:"background 0.15s, box-shadow 0.15s"}}),(0,r.jsx)("span",{style:{fontSize:12,fontWeight:i?600:400,color:s?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(n=(t=lU(e))?w[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:a("i18n.updateAvailable"),style:{color:"#d97706",fontSize:13,lineHeight:1,flexShrink:0},children:"↑"}))]},e.filePath)};return e.map(({label:e,skills:n})=>{let i=n.filter(e=>!e.disableModelInvocation),s=n.filter(e=>e.disableModelInvocation),l=A[e]??!1;return(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em"},children:e}),i.map(t),s.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{onClick:()=>z(t=>({...t,[e]:!l})),style:{display:"flex",alignItems:"center",gap:5,padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",cursor:"pointer",userSelect:"none"},children:[(0,r.jsx)("span",{style:{fontSize:8},children:l?"▾":"▸"}),a("i18n.dormant")," (",s.length,")"]}),l&&s.map(t)]})]},e)})})()}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{onClick:()=>y(!0),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:b?"var(--bg-selected)":"none",color:b?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:e=>{b||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{b||(e.currentTarget.style.background="none")},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),a("i18n.addSkill")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,r.jsx)(lJ,{cwd:e,projectResourcesLoaded:E,installedPackages:{global:new Set(l.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(l.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{W()}}):d?null:O?(0,r.jsx)(lK,{skill:O,cwd:e,onToggle:_,toggling:f.has(O.filePath),saveError:x,updateStatus:lU(O)?w[lU(O)]:void 0,checkingUpdate:!!lU(O)&&j.has(lU(O)),updating:I===lU(O),updateError:M,onCheckUpdate:()=>void P(O),onUpdate:()=>void D(O)},O.filePath):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:a("i18n.selectSkill")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[l.some(e=>!!e.install)&&(0,r.jsx)("button",{onClick:()=>void P(),disabled:C||null!==I,style:{padding:"6px 12px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:C||null!==I?"not-allowed":"pointer",opacity:C||null!==I?.5:1,fontSize:12},children:C?a("i18n.checking"):a("i18n.checkUpdates")}),Object.values(w).filter(e=>"update-available"===e.state).length>0&&(0,r.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(w).filter(e=>"update-available"===e.state).length," ",1===Object.values(w).filter(e=>"update-available"===e.state).length?a("i18n.update"):a("i18n.updates")]})]}),(0,r.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:a("i18n.close")})]})]})})}let lY="global";function lZ(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function lX(e){let t=e.trim().match(/^\$?\s*omp\s+plugin\s+(?:add|install)\s+(\S+)\s*$/);return t?.[1]??e}function lQ(e){return`${e.scope}\0${e.source}`}function l0(e,t){if(e.disabled)return t("i18n.disabled");let n=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t("i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t("i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t("i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t("i18n.themeShort")}):""].filter(Boolean);return n.length?n.join(" \xb7 "):t("i18n.noResources")}function l1(e,t){let n=[];return e.version&&n.push(t("i18n.installedVersion",{version:e.version})),e.configuredVersion&&n.push(t("i18n.configuredVersion",{version:e.configuredVersion})),n.length?n.join(" \xb7 "):t("i18n.unknown")}function l2(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function l4({pkg:e}){let{t}=(0,R.s)(),n=[["extension",t("i18n.extensions")],["skill",t("i18n.skills")],["prompt",t("i18n.prompts")],["theme",t("i18n.themes")]].map(([t,n])=>({kind:t,label:n,resources:e.resources.filter(e=>e.kind===t)})).filter(e=>e.resources.length>0);return 0===n.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:t(e.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:n.map((e,t)=>(0,r.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function l5({scope:e}){return(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===e?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===e?"rgba(99,102,241,0.85)":"var(--text-dim)"},children:e})}function l8(e,t){return{padding:"6px 12px",background:t?"rgba(239,68,68,0.08)":"none",border:"1px solid var(--border)",borderRadius:6,color:t?"#ef4444":"var(--text-muted)",cursor:e?"not-allowed":"pointer",fontSize:12,opacity:e?.5:1}}function l6({enabled:e,loading:t,onToggle:n,label:i}){return(0,r.jsx)("button",{type:"button",onClick:n,disabled:t,title:i,"aria-label":i,"aria-pressed":e,style:{flexShrink:0,width:40,height:22,borderRadius:11,border:"none",padding:0,cursor:t?"wait":"pointer",background:e?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none",opacity:t?.65:1},children:(0,r.jsx)("span",{style:{position:"absolute",top:3,left:e?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function l3({installDir:e,source:t,busy:n,actionError:s,onSourceChange:a,onInstall:l}){let{t:o}=(0,R.s)(),d=(0,i.useRef)(null);return(0,i.useEffect)(()=>{d.current?.focus()},[]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:660,minHeight:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:o("i18n.addPlugin")}),(0,r.jsxs)("a",{href:"https://github.com/can1357/oh-my-pi#plugins",target:"_blank",rel:"noopener noreferrer",style:{display:"inline-flex",alignItems:"center",gap:5,color:"var(--accent)",fontSize:12,textDecoration:"none",whiteSpace:"nowrap"},children:[(0,r.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",style:{flexShrink:0},children:[(0,r.jsx)("path",{fill:"#000",fillRule:"evenodd",d:"M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"}),(0,r.jsx)("path",{fill:"#000",d:"M517.36 400H634.72V634.72H517.36Z"})]}),"oh-my-pi plugins"]})]}),e&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:lZ(e)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("label",{htmlFor:"plugin-source",style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Source"}),(0,r.jsx)("input",{id:"plugin-source",ref:d,value:t,onChange:e=>a(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),n=lX(t);n!==t&&(e.preventDefault(),a(n))},onBlur:e=>a(lX(e.currentTarget.value)),placeholder:"@scope/package or github:user/repo",style:{width:"100%",height:36,padding:"0 11px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,outline:"none"},onKeyDown:e=>{"Enter"===e.key&&t.trim()&&!n&&l()}})]}),(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:(0,r.jsx)("button",{type:"button",onClick:l,disabled:n||!t.trim(),style:{...l8(n||!t.trim()),background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",borderColor:"transparent"},children:o(n?"i18n.installing":"i18n.install")})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Examples"}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:["@scope/omp-plugin","github:user/repo","pkg[feature]"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>a(e),style:{width:"100%",minHeight:30,textAlign:"left",padding:"6px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"pointer",fontFamily:"var(--font-mono)",fontSize:11},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-panel)",e.currentTarget.style.color="var(--text-dim)"},children:e},e))})]}),s&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:s})]})}function l7({pkg:e,cwd:t,busyKey:n,actionError:i,actionMessage:s,sessionId:a,onAction:l,onReloadSession:o}){let{t:d}=(0,R.s)(),c=lQ(e),u=n?.endsWith(c)??!1,p="reload"===n,h=!e.disabled;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20,maxWidth:680},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,minWidth:0,flexWrap:"wrap"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:180,flex:1},children:[(0,r.jsx)(l6,{enabled:h,loading:u||p,onToggle:()=>l(e.disabled?"enable":"disable",e),label:d(e.disabled?"i18n.enablePackage":"i18n.disablePackage")}),(0,r.jsx)(l5,{scope:e.scope}),e.disabled?(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:d("i18n.disabled")}):e.filtered&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:d("i18n.filtered")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>l("update",e),disabled:u||p,style:l8(u||p),children:d(n===`update:${c}`?"i18n.updating":"i18n.update")}),(0,r.jsx)("button",{onClick:o,disabled:!a||p||u,style:l8(!a||p||u),title:d(a?"i18n.reloadSessionHint":"i18n.openSessionToReload"),children:d(p?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)("button",{onClick:()=>l("remove",e),disabled:u||p,style:l8(u||p,!0),children:d(n===`remove:${c}`?"i18n.removing":"i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.status")}),(0,r.jsx)("div",{style:{color:l2(e.status),textTransform:"capitalize"},children:e.status}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.version")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:l1(e,d)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.package")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.packageName??d("i18n.unknown")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.resources")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)"},children:l0(e,d)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.installedPath")}),(0,r.jsx)("div",{style:{color:e.installedPath?"var(--text-muted)":"#ef4444",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.installedPath?lZ(e.installedPath):d("i18n.notFound")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.cwd")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:lZ(t)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)"},children:d("i18n.resolvedResources")}),(0,r.jsx)(l4,{pkg:e})]}),s&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:s}),i&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:i})]})}function l9({cwd:e,sessionId:t,onClose:n,onReloaded:s,embedded:a=!1}){let l=F(),{t:o}=(0,R.s)(),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!0),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(""),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),I=(0,i.useMemo)(()=>d?.packages??[],[d?.packages]),T=I.find(e=>lQ(e)===f)??null,M=d?.projectResourcesLoaded??!0,$=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:I.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[I]),E=(0,i.useCallback)(async()=>{p(!0),m(null);try{let t=await fetch(`/api/plugins?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);c(n),v(e=>0===n.packages.length||e),g(e=>e&&n.packages.some(t=>lQ(t)===e)?e:n.packages[0]?lQ(n.packages[0]):null)}catch(e){m(e instanceof Error?e.message:String(e))}finally{p(!1)}},[e]);(0,i.useEffect)(()=>{E()},[E]);let L=(0,i.useCallback)(async(t,n)=>{let r=lQ(n);k(`${t}:${r}`),S(null),N(null);try{let r=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:n.source,scope:n.scope,cwd:e})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);if(c(i),"remove"===t)g(i.packages[0]?lQ(i.packages[0]):null),0===i.packages.length&&v(!0),N(o("i18n.packageRemoved"));else{let e={install:o("i18n.packageInstalled"),update:o("i18n.packageUpdated"),disable:o("i18n.packageDisabledRestartRequired"),enable:o("i18n.packageEnabled")};N(e[t])}}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}},[e,o]),A=(0,i.useCallback)(async()=>{let t=lX(b).trim();if(!t)return;y(t);let n=`${lY}\0${t}`;k(`install:${n}`),S(null),N(null);try{var r;let i,s,a=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:lY,cwd:e})}),l=await a.json();if(!a.ok||l.error)throw Error(l.error??`HTTP ${a.status}`);c(l);let d=(r=l.packages,s=(i=t.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===lY&&e.source===i)??r.find(e=>e.scope===lY&&e.source===`npm:${s}`)??r.find(e=>e.scope===lY&&e.source.endsWith(i)));g(d?lQ(d):n),v(!1),y(""),N(o("i18n.packageInstalled"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}},[e,b,o]),z=(0,i.useCallback)(async()=>{if(t){k("reload"),S(null),N(null);try{await sR(t,{type:"reload"}),s?.(),await E(),N(o("i18n.sessionReloaded"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}}},[E,s,t,o]),W=w?.startsWith("install:")??!1;return(0,r.jsx)("div",{style:{position:a?"relative":"fixed",inset:a?void 0:0,width:"100%",height:"100%",zIndex:a?void 0:1e3,background:a?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{a||e.target!==e.currentTarget||n()},children:(0,r.jsxs)("div",{style:{width:a?"100%":l?"calc(100vw - 16px)":860,maxWidth:a?"none":"calc(100vw - 16px)",height:a?"100%":l?"calc(100dvh - 16px)":"76vh",maxHeight:a?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:a?"none":"1px solid var(--border)",borderRadius:8*!a,display:"flex",flexDirection:"column",boxShadow:a?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:o("common.plugins")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:lZ(e)})]}),(0,r.jsx)("button",{onClick:n,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!M&&(0,r.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:o("trust.pluginsNotLoaded")}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:l?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:l?"100%":245,maxHeight:l?"40vh":void 0,borderRight:l?"none":"1px solid var(--border)",borderBottom:l?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:"Loading..."}):h?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#ef4444"},children:h}):0===I.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:"No plugins configured"}):$.map(e=>(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase"},children:e.scope}),e.packages.map(e=>{let t=lQ(e),n=!x&&f===t;return(0,r.jsxs)("div",{onClick:()=>{g(t),v(!1),S(null),N(null)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:l2(e.status)}}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:n?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:l0(e,o)}),(e.version||e.configuredVersion)&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:l1(e,o)})]})]},t)})]},e.scope))}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("button",{type:"button",onClick:()=>{v(!0),S(null),N(null)},style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,border:"none",width:"100%",cursor:"pointer",background:x?"var(--bg-selected)":"none",color:x?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:e=>{x||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{x||(e.currentTarget.style.background="none")},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),o("i18n.addPlugin")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:x?(0,r.jsx)(l3,{installDir:d?.installDir,source:b,busy:W,actionError:j,onSourceChange:y,onInstall:A}):u?null:T?(0,r.jsx)(l7,{pkg:T,cwd:e,busyKey:w,actionError:j,actionMessage:C,sessionId:t,onAction:L,onReloadSession:z},lQ(T)):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:o("i18n.selectPackage")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,fontSize:11,color:"var(--text-dim)",overflow:"hidden"},children:d?.diagnostics.length?(0,r.jsxs)("span",{title:d.diagnostics.map(e=>`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`).join("\n"),style:{color:d.diagnostics.some(e=>"error"===e.type)?"#ef4444":"#d97706"},children:[d.diagnostics.length," diagnostic",1===d.diagnostics.length?"":"s"]}):(0,r.jsx)("span",{children:d?`${d.totals.extensions} ext \xb7 ${d.totals.skills} skills \xb7 ${d.totals.prompts} prompts \xb7 ${d.totals.themes} themes`:""})}),(0,r.jsx)("button",{onClick:()=>void E(),disabled:u||null!==w,style:l8(u||null!==w),children:o("i18n.refresh")}),(0,r.jsx)("button",{onClick:n,style:l8(!1),children:o("i18n.close")})]})]})})}var oe=n(13004),ot=n.n(oe);function on(){let[e,t]=(0,i.useState)(null),[n,s]=(0,i.useState)(null),[a,l]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(""),[m,f]=(0,i.useState)(""),g=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/web-access",{cache:"no-store"}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);t(n),s(null)}catch(e){s(e instanceof Error?e.message:String(e))}},[]);(0,i.useEffect)(()=>{g()},[g]);let x=(0,i.useCallback)(async(e,n={})=>{u(!0),l(null),d(null);try{let r=await fetch("/api/web-access",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,...n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);return t(i),i}catch(e){return l(e instanceof Error?e.message:String(e)),null}finally{u(!1)}},[]),v=(0,i.useCallback)(async()=>{if(p!==m)return void l("The two passwords do not match.");let e=await x("set-password",{password:p});e&&(h(""),f(""),d(`Password saved and password access turned on. The browser will ask for the username "${e.username}" and this password on the next request.`))},[m,p,x]),b=(0,i.useCallback)(async()=>{if(!e)return;let t=await x(e.enabled?"disable":"enable");t&&d(t.enabled?`Password access is on. The browser will ask for the username "${t.username}" and your password on the next request.`:"Password access is off. The stored password is kept and can be switched back on here.")},[x,e]),y=(0,i.useCallback)(async()=>{await x("clear")&&d("The stored password was removed and password access is off.")},[x]);if(!e)return(0,r.jsx)("div",{className:ot().empty,children:n??"Loading password access…"});let w=e.managedByEnvironment,k=!c&&!w&&p.length>=8&&p===m;return(0,r.jsxs)("div",{className:ot().scrollContent,children:[(0,r.jsxs)("header",{className:ot().contentHeader,children:[(0,r.jsx)("h2",{className:ot().contentTitle,children:"Access"}),(0,r.jsxs)("p",{className:ot().contentDescription,children:["A password locks the web interface and every API endpoint behind HTTP Basic Auth, with the fixed username ",(0,r.jsx)("code",{children:e.username}),". It is stored as a scrypt hash in ",(0,r.jsx)("code",{children:e.file})," — CUELO never keeps the password itself, which is why forgetting it means recovering rather than reading it back."]}),w&&(0,r.jsxs)("div",{className:ot().readOnlyNotice,children:["Read-only \xb7 ",(0,r.jsx)("code",{children:"CUELO_PASSWORD"})," is set and overrides the stored credential. Unset it and restart CUELO to manage the password here."]}),o&&(0,r.jsx)("div",{className:ot().reloadNotice,children:(0,r.jsx)("span",{children:o})})]}),(0,r.jsxs)("div",{className:ot().settingsBody,children:[(0,r.jsxs)("section",{className:ot().group,children:[(0,r.jsx)("h3",{className:ot().groupTitle,children:"Password access"}),(0,r.jsxs)("div",{className:ot().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:ot().settingLabel,children:"Require a password"}),(0,r.jsx)("div",{className:ot().settingDescription,children:e.managedByEnvironment?"Every request needs the password from CUELO_PASSWORD.":e.unreadable?"The credential file exists but could not be read, so every request is being refused.":e.configured?e.enabled?"Every request needs the username and password.":"A password is stored but the lock is off.":"No password is set. Anyone who can reach this server can use it."}),!e.configured&&!w&&(0,r.jsx)("div",{className:ot().settingDescription,children:"Set a password below before turning this on."}),a&&(0,r.jsx)("div",{className:ot().error,children:a})]}),(0,r.jsx)("div",{className:ot().settingControl,children:(0,r.jsx)("button",{type:"button",className:ot().switch,"data-on":e.enabled,"aria-pressed":e.enabled,"aria-label":"Require a password",disabled:c||w||!e.enabled&&!e.stored,onClick:()=>void b()})})]})]}),(0,r.jsxs)("section",{className:ot().group,children:[(0,r.jsx)("h3",{className:ot().groupTitle,children:e.stored?"Replace the password":"Set a password"}),(0,r.jsxs)("div",{className:ot().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:ot().settingLabel,children:"New password"}),(0,r.jsxs)("div",{className:ot().settingDescription,children:["At least ",8," characters. Saving a password also turns password access on."]})]}),(0,r.jsx)("div",{className:ot().settingControl,children:(0,r.jsx)("input",{className:ot().textInput,type:"password",autoComplete:"new-password",value:p,disabled:c||w,onChange:e=>h(e.target.value)})})]}),(0,r.jsxs)("div",{className:ot().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:ot().settingLabel,children:"Confirm password"}),(0,r.jsx)("div",{className:ot().settingDescription,children:"Both entries have to match before it can be saved."})]}),(0,r.jsx)("div",{className:ot().settingControl,children:(0,r.jsx)("input",{className:ot().textInput,type:"password",autoComplete:"new-password",value:m,disabled:c||w,onChange:e=>f(e.target.value),onKeyDown:e=>{"Enter"===e.key&&k&&v()}})})]}),(0,r.jsxs)("div",{className:ot().editorActions,children:[(0,r.jsx)("div",{children:(0,r.jsx)("div",{className:ot().saveState,children:e.stored&&e.updatedAt?`Last changed ${new Date(e.updatedAt).toLocaleString()}`:"No password stored yet"})}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[e.stored&&!w&&(0,r.jsx)("button",{type:"button",className:ot().dangerButton,disabled:c,onClick:()=>void y(),children:"Remove password"}),(0,r.jsx)("button",{type:"button",className:ot().primaryButton,disabled:!k,onClick:()=>void v(),children:c?"Saving…":"Save password"})]})]})]}),(0,r.jsxs)("section",{className:ot().group,children:[(0,r.jsx)("h3",{className:ot().groupTitle,children:"If you forget it"}),(0,r.jsxs)("div",{className:ot().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:ot().settingLabel,children:"Recovery"}),(0,r.jsxs)("div",{className:ot().settingDescription,children:["Run ",(0,r.jsx)("code",{children:"cuelo --reset-password"})," on this machine to set a new one, or open ",(0,r.jsx)("code",{children:"/recover"})," in the browser: CUELO prints a one-time code on its own console, and entering that code sets a new password. Both paths require access to the machine running the server — nothing can hand the password back."]})]}),(0,r.jsx)("div",{className:ot().settingControl,children:(0,r.jsx)("a",{className:ot().linkButton,href:"/recover",target:"_blank",rel:"noreferrer",children:"Open /recover"})})]}),(0,r.jsxs)("div",{className:ot().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:ot().settingLabel,children:"Basic Auth is not encryption"}),(0,r.jsx)("div",{className:ot().settingDescription,children:"The password crosses the network in a reversible encoding. Over plain HTTP on an untrusted network it can be read in transit, so put CUELO behind HTTPS or a trusted VPN before exposing it beyond loopback."})]}),(0,r.jsx)("div",{className:ot().settingControl})]})]})]})]})}let or="/api/live/character-voice",oi={ready:"chat.liveVoiceStateReady","not-prepared":"chat.liveVoiceStateNotPrepared",preparing:"chat.liveVoiceStatePreparing","needs-check":"chat.liveVoiceStateNeedsCheck",failed:"chat.liveVoiceStateFailed","missing-asset":"chat.liveVoiceStateMissingAsset"},os={failed:!0,"needs-check":!0,"missing-asset":!0};async function oa(e){let t=await e.json().catch(()=>({}));if(!e.ok||!t||"object"!=typeof t||!("characters"in t))throw Error(t&&"object"==typeof t&&"message"in t&&"string"==typeof t.message?t.message:`HTTP ${e.status}`);return t}function ol(){let{t:e}=(0,R.s)(),t=(0,i.useId)(),n=(0,i.useId)(),[s,a]=(0,i.useState)(null),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(""),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(!1),f=(0,i.useCallback)(async()=>{try{a(await oa(await fetch(or,{cache:"no-store"})))}catch(t){o(t instanceof Error?t.message:e("chat.liveVoiceLoadFailed"))}},[e]);(0,i.useEffect)(()=>{f()},[f]);let g=s?.preparing===!0;(0,i.useEffect)(()=>{if(!g)return;let e=setTimeout(()=>void f(),2e3);return()=>clearTimeout(e)},[g,s,f]);let x=(0,i.useCallback)(async e=>{m(!0),o(null);try{return a(await oa(await fetch(or,e))),!0}catch(e){return o(e instanceof Error?e.message:String(e)),!1}finally{m(!1)}},[]),v=async()=>{let e=d.trim();e&&await x({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})})&&c("")};if(!s)return(0,r.jsx)("div",{className:ot().empty,children:l?`${e("chat.liveVoiceLoadFailed")}: ${l}`:"…"});let b=s.configured,y=l??s.lastError??null;return(0,r.jsxs)("div",{className:ot().scrollContent,children:[(0,r.jsxs)("header",{className:ot().contentHeader,children:[(0,r.jsx)("h2",{className:ot().contentTitle,children:e("chat.liveVoiceSettingsTitle")}),(0,r.jsx)("p",{className:ot().contentDescription,children:e("chat.liveVoiceSettingsDescription")})]}),(0,r.jsxs)("div",{className:ot().settingsBody,children:[(0,r.jsxs)("section",{className:ot().group,children:[(0,r.jsx)("h3",{className:ot().groupTitle,children:e("chat.liveVoiceKeyLabel")}),(0,r.jsxs)("div",{className:ot().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("label",{htmlFor:t,className:ot().settingLabel,style:{display:"block"},children:e("chat.liveVoiceKeyLabel")}),(0,r.jsx)("div",{className:ot().settingDescription,children:e("chat.liveVoiceKeyHelp")}),b&&s.keyHint&&(0,r.jsx)("div",{className:ot().saveState,style:{overflowWrap:"anywhere"},children:e("chat.liveVoiceKeySaved",{hint:s.keyHint})})]}),(0,r.jsx)("div",{className:ot().settingControl,children:(0,r.jsx)("input",{id:t,className:ot().textInput,type:"password",autoComplete:"off",spellCheck:!1,value:d,disabled:h,onChange:e=>c(e.target.value),onKeyDown:e=>{"Enter"===e.key&&v()},placeholder:"sk_car_…"})})]}),(0,r.jsxs)("div",{className:ot().editorActions,children:[(0,r.jsx)("div",{}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8},children:[b&&(0,r.jsx)("button",{type:"button",className:ot().dangerButton,disabled:h||g,onClick:()=>void x({method:"DELETE"}),children:e("chat.liveVoiceKeyRemove")}),(0,r.jsx)("button",{type:"button",className:ot().primaryButton,disabled:h||!d.trim(),onClick:()=>void v(),children:e("chat.liveVoiceKeySave")})]})]})]}),(0,r.jsxs)("section",{className:ot().group,children:[(0,r.jsx)("h3",{className:ot().groupTitle,children:e("chat.liveVoicePrepare")}),(0,r.jsxs)("div",{className:ot().settingRow,children:[(0,r.jsxs)("div",{style:{display:"flex",gap:8,alignItems:"flex-start",minWidth:0},children:[(0,r.jsx)("input",{id:n,type:"checkbox",checked:u,onChange:e=>p(e.target.checked),style:{marginTop:3,flex:"none"}}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("label",{htmlFor:n,className:ot().settingDescription,style:{display:"block",color:"var(--text)"},children:e("chat.liveVoiceConsent")}),(0,r.jsxs)("div",{className:ot().settingDescription,style:{marginTop:4},children:[e("chat.liveVoicePlanNote")," ",(0,r.jsx)("a",{href:"/audio/live/ACML-1.0.txt",target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)"},children:e("chat.liveVoiceLicense")})]})]})]}),(0,r.jsx)("div",{className:ot().settingControl,style:{alignItems:"center"},children:(0,r.jsx)("button",{type:"button",className:ot().primaryButton,disabled:h||g||!b||!u,onClick:()=>void x({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prepare:!0,acknowledged:!0})}),"aria-busy":g,children:g?e("chat.liveVoicePreparing"):e("chat.liveVoicePrepare")})})]}),y&&(0,r.jsx)("div",{className:ot().error,role:"alert",style:{overflowWrap:"anywhere"},children:y})]}),(0,r.jsxs)("section",{className:ot().group,children:[(0,r.jsx)("h3",{className:ot().groupTitle,children:e("chat.liveVoiceCharacters")}),(0,r.jsx)("ul",{"aria-live":"polite",style:{listStyle:"none",margin:0,padding:0},children:s.characters.map(t=>(0,r.jsxs)("li",{className:ot().settingRow,style:{minHeight:44},title:t.error,children:[(0,r.jsxs)("div",{className:ot().settingLabel,style:{marginBottom:0},children:[t.alias,"provisional"===t.tuning&&(0,r.jsxs)("span",{className:ot().settingDescription,style:{fontWeight:400},children:[" \xb7 ",e("chat.liveVoiceProvisional")]})]}),(0,r.jsx)("div",{className:ot().settingControl,style:{fontSize:12,color:os[t.state]?"var(--danger)":"ready"===t.state?"var(--text)":"var(--text-muted)"},children:e(oi[t.state])})]},t.id))})]})]})]})}function oo({cwd:e}){let{t}=(0,R.s)(),[n,s]=(0,i.useState)(null),[a,l]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)({}),[m,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(new Map);(0,i.useEffect)(()=>{g&&c!==g&&(v.current.get(g)?.querySelector("button:not(:disabled)")?.focus(),x(null))},[c,n,g]);let b=(0,i.useRef)(0),y=(0,i.useRef)(null),w=(0,i.useRef)(null),k=(0,i.useRef)(!1),j=(0,i.useCallback)(async()=>{if(k.current||"visible"!==document.visibilityState)return;let n=++b.current;y.current?.abort();let r=new AbortController;y.current=r;try{let i=e?`?include=${encodeURIComponent(e)}`:"",a=await fetch(`/api/project-trust${i}`,{cache:"no-store",signal:r.signal}),o=await a.json();if(n!==b.current||r.signal.aborted)return;if(!a.ok||!o.projects)throw Error(o.error??`HTTP ${a.status}`);let d=o.projects.find(e=>null===e.pending&&!e.error&&w.current?.some(t=>t.cwd===e.cwd&&("grant"===t.pending?e.trusted:"revoke"===t.pending&&!e.trusted)));w.current=o.projects,s(o.projects),l(null),d&&f({cwd:d.cwd,text:t("trust.doneApplied")})}catch(e){if(n!==b.current||r.signal.aborted)return;l(e instanceof Error?e.message:String(e))}finally{y.current===r&&(y.current=null)}},[e,t]);(0,i.useEffect)(()=>(j(),()=>{y.current?.abort()}),[j]);let S=n?.some(e=>null!==e.pending)??!1;(0,i.useEffect)(()=>{let e;if(!S||null!==c||null!==o)return;let t=()=>{window.clearTimeout(e),e="visible"===document.visibilityState?window.setTimeout(()=>void j(),2500):void 0},n=()=>{"visible"===document.visibilityState?j():(t(),++b.current,y.current?.abort())};return t(),document.addEventListener("visibilitychange",n),()=>{window.clearTimeout(e),document.removeEventListener("visibilitychange",n)}},[c,o,n,S,j]);let C=(0,i.useCallback)(async(e,n)=>{if(!k.current){k.current=!0,++b.current,y.current?.abort(),u(e),d(null),x(e),f(null),h(t=>{let n={...t};return delete n[e],n});try{let r=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,action:n})}),i=await r.json();if(!r.ok)throw Error(i.error??`HTTP ${r.status}`);let a=w.current?.map(t=>t.cwd===e?{...i,cwd:e}:t)??null;w.current=a,s(a),"cancel"===n?f({cwd:e,text:t("trust.doneCancelled")}):i.error||null!==i.pending||f({cwd:e,text:t("trust.doneApplied")})}catch(t){h(n=>({...n,[e]:t instanceof Error?t.message:String(t)}))}finally{k.current=!1,u(null)}}},[t]);if(!n)return(0,r.jsxs)("div",{className:ot().empty,children:[a?t("trust.loadFailed",{error:a}):"…",a&&(0,r.jsx)("button",{type:"button",className:ot().linkButton,onClick:()=>void j(),children:t("trust.refresh")})]});let N=null!==c;return(0,r.jsxs)("div",{className:ot().scrollContent,children:[(0,r.jsxs)("header",{className:ot().contentHeader,children:[(0,r.jsx)("h2",{className:ot().contentTitle,children:t("trust.settingsNav")}),(0,r.jsx)("p",{className:ot().contentDescription,children:t("trust.settingsDescription")}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,marginTop:12},children:[(0,r.jsx)("button",{type:"button",className:ot().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void j(),children:t("trust.refresh")}),a&&(0,r.jsx)("div",{className:ot().error,role:"alert",children:t("trust.loadFailed",{error:a})})]})]}),(0,r.jsx)("div",{className:ot().settingsBody,children:(0,r.jsxs)("section",{className:ot().group,children:[0===n.length&&(0,r.jsx)("div",{className:ot().settingDescription,children:t("trust.settingsEmpty")}),n.map(e=>{var n;let i=c===e.cwd,s=o?.cwd===e.cwd?o:null,a=e.requiresTrust?e.trusted?t("trust.stateTrusted"):t("trust.stateRestricted"):t("trust.stateNotRequired"),l=p[e.cwd]??(e.error?t("trust.applyFailed",{error:e.error}):null);return(0,r.jsxs)("div",{className:ot().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{className:ot().settingLabel,style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.jsx)("span",{className:ot().statusDot,"data-off":!e.trusted||!e.requiresTrust,"aria-hidden":"true"}),(0,r.jsx)("span",{children:(n=e.cwd).split(/[\\/]/).filter(Boolean).pop()??n}),(0,r.jsx)("span",{className:ot().settingDescription,style:{fontWeight:600},children:a})]}),(0,r.jsx)("code",{className:ot().settingDescription,style:{display:"block",overflowWrap:"anywhere"},children:e.cwd}),(0,r.jsx)("div",{className:ot().saveState,children:t("trust.runtime",{sessions:e.runtime.sessions,running:e.runtime.running,loaded:e.requiresTrust?e.runtime.projectCodeLoaded:0})}),(0,r.jsxs)("div",{"aria-live":"polite",children:["grant"===e.pending&&(0,r.jsx)("div",{className:ot().settingDescription,children:t("trust.pendingGrant")}),"revoke"===e.pending&&(0,r.jsx)("div",{className:ot().settingDescription,children:t("trust.pendingRevoke",{count:e.runtime.projectCodeLoaded})}),s&&(0,r.jsx)("div",{className:ot().settingDescription,style:{color:"var(--text)"},children:"revoke"===s.action?t("trust.confirmRevoke"):s.again?t("trust.confirmTrustAgain"):t("trust.confirmGrant")}),m?.cwd===e.cwd&&(0,r.jsx)("div",{className:ot().saveState,children:m.text})]}),l&&(0,r.jsx)("div",{className:ot().error,role:"alert",children:l})]}),(0,r.jsx)("div",{ref:t=>{t?v.current.set(e.cwd,t):v.current.delete(e.cwd)},className:ot().settingControl,style:{flexWrap:"wrap",gap:8,alignItems:"flex-start"},children:s?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:ot().linkButton,style:{background:"transparent",cursor:"pointer"},autoFocus:!0,onClick:()=>{d(null),x(e.cwd)},children:t("trust.cancel")}),(0,r.jsx)("button",{type:"button",className:"revoke"===s.action?ot().dangerButton:ot().primaryButton,disabled:N,onClick:()=>void C(e.cwd,s.action),children:"revoke"===s.action?t("trust.revoke"):t("trust.confirm")})]}):i?(0,r.jsx)("button",{type:"button",className:ot().primaryButton,disabled:!0,children:t("trust.working")}):(0,r.jsxs)(r.Fragment,{children:["grant"===e.pending&&(0,r.jsx)("button",{type:"button",className:ot().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void C(e.cwd,"cancel"),children:t("trust.cancelSchedule")}),e.requiresTrust&&!e.trusted&&"grant"!==e.pending&&(0,r.jsx)("button",{type:"button",className:ot().primaryButton,disabled:N,onClick:()=>d({cwd:e.cwd,action:"grant",again:"revoke"===e.pending}),children:"revoke"===e.pending?t("trust.trustAgain"):t("trust.trustProject")}),e.trusted&&(0,r.jsx)("button",{type:"button",className:ot().dangerButton,disabled:N,onClick:()=>d({cwd:e.cwd,action:"revoke",again:!1}),children:t("trust.revoke")})]})})]},e.cwd)})]})})]})}let od=JSON.parse('{"tabs":{"appearance":"외관","model":"모델","interaction":"상호작용","context":"컨텍스트","memory":"메모리","files":"파일","shell":"Shell","tools":"도구","tasks":"작업","providers":"제공자"},"groups":{"Theme":"테마","Status Line":"상태 표시줄","Display":"표시","Images":"이미지","Thinking":"사고","Sampling":"샘플링","Prompt":"프롬프트","Retry & Fallback":"재시도 및 폴백","Advisor":"어드바이저","Prewalk":"Prewalk","Vision":"비전","Input":"입력","Approvals":"승인","Notifications":"알림","Speech":"음성","Collab":"협업","Magic Keywords":"매직 키워드","Startup & Updates":"시작 및 업데이트","Power (macOS)":"전원 (macOS)","Agent":"에이전트","Git":"Git","General":"일반","Compaction":"압축","Rules (TTSR)":"규칙 (TTSR)","Experimental":"실험적 기능","Auto-Learn":"자동 학습","Mnemopi":"Mnemopi","Hindsight":"Hindsight","Editing":"편집","Reading":"읽기","Read Summaries":"읽기 요약","LSP":"LSP","Bash":"Bash","Eval & Runtimes":"평가 및 런타임","Available Tools":"사용 가능한 도구","Todos":"할 일","Grep & Browser":"Grep 및 브라우저","Computer":"컴퓨터","GitHub":"GitHub","Output Limits":"출력 제한","Execution":"실행","Discovery & MCP":"탐색 및 MCP","Developer":"개발자","Modes":"모드","Subagents":"서브에이전트","Isolation":"격리","Commands & Skills":"명령 및 스킬","Services":"서비스","Fireworks":"Fireworks","Tiny Model":"Tiny Model","Protocol":"프로토콜","Timeouts":"타임아웃","Privacy":"개인정보"},"shell":{"Loading omp settings…":"omp 설정을 불러오는 중…","Settings unavailable":"설정을 사용할 수 없음","Matching canonical /settings entries across every category.":"모든 카테고리에서 표준 /settings 항목을 일치시킨다.","Canonical omp /settings values. Changes are saved immediately to the shared agent configuration.":"표준 omp /settings 값이다. 변경 사항은 공유 에이전트 설정에 즉시 저장된다.","Saved. Reload the active session to apply runtime settings.":"저장됨. 런타임 설정을 적용하려면 활성 세션을 다시 불러온다.","Reloading…":"다시 불러오는 중…","Reload session":"세션 다시 불러오기","No settings match this search.":"이 검색과 일치하는 설정이 없다.","Search /settings":"/settings 검색","Configuration":"구성","OMP settings":"OMP 설정","Close settings":"설정 닫기","Global configuration":"전역 구성","Settings":"설정","Search":"검색","Models":"모델","Themes":"테마","Skills":"스킬","Plugins":"플러그인","MCP":"MCP","Loading themes…":"테마를 불러오는 중…","Themes unavailable":"테마를 사용할 수 없음","Active on web":"웹에서 활성","Preview ":"미리보기 ","The web interface uses the same dark and light theme mappings as omp. Changes are persisted to ":"웹 인터페이스는 omp와 동일한 다크 및 라이트 테마 매핑을 사용한다. 변경 사항은 다음에 저장된다: "," and applied here immediately.":" 그리고 여기에 즉시 적용된다."," mapping":" 매핑","requires a project":"프로젝트가 필요하다"},"fields":{"theme.dark":{"label":"다크 테마","description":"터미널 배경이 어두울 때 사용하는 테마이다"},"theme.light":{"label":"라이트 테마","description":"터미널 배경이 밝을 때 사용하는 테마이다"},"symbolPreset":{"label":"심볼 프리셋","description":"아이콘과 기호에 사용하는 글리프 세트이다 (Unicode, Nerd Font, ASCII)"},"colorBlindMode":{"label":"색맹 모드","description":"diff 추가 표시에 초록색 대신 파란색을 사용한다"},"statusLine.preset":{"label":"상태 표시줄 프리셋","description":"미리 구성된 상태 표시줄 설정이다"},"statusLine.separator":{"label":"상태 표시줄 구분자","description":"세그먼트 사이 구분자의 스타일이다"},"statusLine.sessionAccent":{"label":"세션 강조색","description":"에디터 테두리와 상태 표시줄 여백에 세션 이름 색상을 사용한다"},"statusLine.transparent":{"label":"투명 상태 표시줄","description":"상태 표시줄에 테마의 `statusLineBg` 대신 터미널 기본 배경을 사용한다. Powerline 끝 캡은 주변 터미널로 이어지려면 대비되는 채움색이 필요하므로 제거된다."},"statusLine.compactThinkingLevel":{"label":"간결한 thinking 레벨","description":"thinking 레벨을 별도의 ` \xb7 <level>` 접미사 대신 모델 이름에 아이콘 하나로 표시한다."},"statusLine.showHookStatus":{"label":"hook 상태 표시","description":"상태 표시줄 아래에 hook 상태 메시지를 표시한다"},"terminal.showImages":{"label":"인라인 이미지 표시","description":"터미널에 이미지를 인라인으로 렌더링한다"},"images.autoResize":{"label":"이미지 자동 크기 조정","description":"모델 호환성을 높이기 위해 큰 이미지를 최대 2000x2000으로 축소한다"},"images.blockImages":{"label":"이미지 차단","description":"이미지가 LLM 제공자에게 전송되지 않도록 한다"},"terminal.showProgress":{"label":"네이티브 터미널 진행 표시","description":"에이전트나 컨텍스트 유지 작업이 실행되는 동안 OSC 9;4 부정형 진행 표시를 내보낸다"},"tui.textSizing":{"label":"큰 제목 (Kitty)","description":"Kitty의 OSC 66 text-sizing 프로토콜을 사용해 Markdown H1 제목을 2배 크기로 렌더링한다. Kitty 터미널에서만 적용되며 그 외에서는 무시된다. 기본값은 꺼짐이다."},"tui.renderMermaid":{"label":"Mermaid 다이어그램 렌더링","description":"Mermaid 코드 블록을 ASCII 다이어그램으로 렌더링한다"},"tui.codexResetFireworks":{"label":"Codex 리셋 불꽃놀이","description":"예정에 없던 Codex 주간 사용량 리셋과 새로 적립된 저장 리셋을 화면 상단 1/3의 불꽃놀이 오버레이로 축하하며, Escape를 누를 때까지 유지된다"},"tui.titleState":{"label":"터미널 제목 실행 상태","description":"터미널 제목의 구분자에 에이전트 실행 상태를 표시한다 — 작업 중에는 애니메이션 스피너(Windows에서는 고정된 \':\'), 사용자 차례일 때는 \'>\', 에이전트가 사용자를 기다릴 때는 \'!\'이다"},"tui.hyperlinks":{"label":"터미널 하이퍼링크","description":"터미널 자체의 클릭 열기를 위해 경로와 URL을 OSC 8 하이퍼링크로 감싼다 (auto: 지원 여부 감지, off: 사용 안 함, always: 무조건 사용)"},"tui.tight":{"label":"조밀한 레이아웃","description":"터미널 출력 좌우의 1문자 가로 여백을 제거한다"},"tui.scrollbackRebuild":{"label":"스크롤백 다시 쓰기","description":"블록의 최종 형태가 실시간 미리보기를 대체할 때 터미널 스크롤백을 지우고 다시 출력한다. 꺼짐(기본값)일 때는 오래된 미리보기 사본이 기록에 남고 최종 내용이 그 아래에 추가된다."},"display.shimmer":{"label":"셔머","description":"작업/로딩 메시지의 애니메이션 스타일이다"},"display.smoothStreaming":{"label":"부드러운 스트리밍","description":"청크가 도착하는 동안 어시스턴트 텍스트와 스트리밍되는 도구 입력을 부드럽게 표시한다"},"display.hideToolActivity":{"label":"도구 활동 숨김","description":"모델이 시작한 도구 호출과 결과를 대화 기록에서 숨긴다"},"display.showTokenUsage":{"label":"토큰 사용량 표시","description":"어시스턴트 메시지에 턴별 토큰 사용량을 표시한다"},"display.cacheMissMarker":{"label":"캐시 미스 표시","description":"요청이 프롬프트 캐시를 놓친(miss) 어시스턴트 턴 위에 구분선을 표시한다"},"display.collapseCompacted":{"label":"압축 히스토리 접기","description":"라이브 트랜스크립트에서 compaction 이전 히스토리를 요약 구분선 뒤로 접는다. 비활성화하면 각 compaction 지점에 구분선을 둔 채 전체 트랜스크립트를 인라인으로 유지한다"},"showHardwareCursor":{"label":"하드웨어 커서 표시","description":"IME 지원을 위해 터미널 커서를 표시한다"},"tui.imeSafeCursor":{"label":"IME 안전 프롬프트 레이아웃","description":"macOS IME preedit가 프롬프트 하단 테두리를 밀어내지 못하도록 테두리를 별도 행으로 옮긴다"},"task.showResolvedModelBadge":{"label":"확정 모델 배지 표시","description":"task 위젯 상태줄에 각 subagent가 실제로 사용한 모델 ID를 표시한다"},"advisor.enabled":{"label":"Advisor 활성화","description":"\'advisor\' 역할에 배정된 두 번째 모델을 함께 두어 각 턴을 수동적으로 검토하고 메모를 주입한다."},"prewalk.enabled":{"label":"Prewalk 활성화","description":"활성 모델로 시작한 뒤, plan nudge의 todo 목록이 생성된 이후 첫 edit/write 시점에 빠르고 저렴한 모델(기본값은 \'smol\' 역할)로 전환한다 — 강한 모델이 계획하고 todo를 확정하며 구현을 시작한 후 인계한다. 세션별로 --prewalk / --no-prewalk로 재정의할 수 있다."},"advisor.syncBacklog":{"label":"Advisor 동기화 백로그","description":"advisor가 이 턴 수만큼 뒤처지면 메인 에이전트를 최대 30초 동안 멈춘다. Off로 두면 따라잡기 지연을 비활성화한다."},"advisor.immuneTurns":{"label":"Advisor 면역 턴","description":"advisor의 concern 또는 blocker가 한 번 인터럽트한 뒤에는, 이 primary 턴 수 동안 이후 concern/blocker를 인터럽트 없이 전달한다."},"modelRoleStorage":{"label":"모델 역할 저장소","description":"모델 선택기의 역할 배정이 저장되는 위치이다"},"images.describeForTextModels":{"label":"텍스트 모델용 이미지 설명","description":"vision을 지원하지 않는 모델에 이미지가 첨부되면, 이미지를 버리지 않고 local:// 아래에 저장한 뒤 vision 지원 모델이 만든 설명을 주입한다"},"defaultThinkingLevel":{"label":"Thinking 레벨","description":"thinking을 지원하는 모델의 추론 깊이이다"},"hideThinkingBlock":{"label":"Thinking 블록 숨김","description":"어시스턴트 응답에서 thinking 블록을 숨긴다"},"proseOnlyThinking":{"label":"산문 전용 Thinking","description":"thinking 요약에서 코드 블록을 제외하고 생략 부호로 대체한다"},"omitThinking":{"label":"Thinking 요약 생략","description":"응답에서 thinking 요약을 완전히 생략하도록 업스트림 provider에 지시한다(지원되는 경우)"},"externalThinking":{"label":"외부 Thinking","description":"사용자에게 표시되지 않는 비공개 스크래치패드이다. 지원되는 GPT, Claude, Gemini의 reasoning을 비활성화한다"},"model.loopGuard.enabled":{"label":"Loop Guard","description":"모델 reasoning과 산문에 대한 자동 스트림 루프 감지를 활성화한다"},"model.loopGuard.checkAssistantContent":{"label":"Loop Guard 산문 검사","description":"thinking 로그 외에 어시스턴트 산문 메시지에도 loop guard를 적용한다"},"model.loopGuard.toolCallReminder":{"label":"Loop Guard 도구 호출 알림","description":"Gemini reasoning 스트림이 도구를 호출하지 않고 계획 헤더를 연속으로 다수 출력하면 중단하고 도구 호출을 요구하는 알림을 주입한다(Loop Guard 필요)"},"model.toolCallLoopGuard.enabled":{"label":"도구 호출 Loop Guard","description":"여러 턴에 걸친 동일한 연속 도구 호출을 감지하고 교정용 steer를 주입한다"},"inlineToolDescriptors":{"label":"인라인 도구 디스크립터","description":"시스템 프롬프트에 전체 도구 디스크립터를 렌더링하고 provider 도구 스키마에서 최상위/중첩 description을 제거해 디스크립터 텍스트를 한 번만 전송한다. Auto는 Gemini 모델에서 이를 활성화하고 그 외에는 비활성화한다"},"includeModelInPrompt":{"label":"프롬프트에 모델 포함","description":"에이전트가 자신이 어떤 모델인지 알 수 있도록 시스템 프롬프트에 활성 모델 식별자를 노출한다"},"includeWorkspaceTree":{"label":"워크스페이스 트리 포함","description":"시스템 프롬프트에 워크스페이스 디렉터리 트리를 렌더링한다. 경고: 파일이 수정되면 세션 간 프롬프트 캐싱이 깨질 수 있다."},"personality":{"label":"성격","description":"시스템 프롬프트의 personality 블록에 렌더링되는 의사소통 스타일이다"},"temperature":{"label":"Temperature","description":"샘플링 temperature이다(0 = 결정적, 1 = 창의적, -1 = provider 기본값)"},"topP":{"label":"Top P","description":"Nucleus 샘플링 컷오프이다(0-1, -1 = provider 기본값)"},"topK":{"label":"Top K","description":"상위 K개 토큰에서 샘플링한다(-1 = provider 기본값)"},"minP":{"label":"Min P","description":"최소 확률 임계값 (0-1, -1 = provider 기본값)"},"presencePenalty":{"label":"Presence Penalty","description":"이미 등장한 토큰을 도입하는 데 대한 페널티 (-1 = provider 기본값)"},"repetitionPenalty":{"label":"Repetition Penalty","description":"반복된 토큰에 대한 페널티 (-1 = provider 기본값)"},"textVerbosity":{"label":"텍스트 상세도","description":"OpenAI Responses 및 Codex 응답의 상세도 (low, medium, high)"},"tier.openai":{"label":"서비스 티어 — OpenAI","description":"OpenAI / OpenAI-Codex 요청 및 OpenRouter를 경유하는 OpenAI 계열 모델의 처리 티어 (none = 생략). `service_tier`로 전송한다."},"tier.anthropic":{"label":"서비스 티어 — Anthropic","description":"Claude 요청의 처리 티어. `priority`는 지원되는 직접 Anthropic 모델에서 fast 모드(`speed: \\"fast\\"`)를 활성화하며, Bedrock/Vertex Claude 및 OpenRouter 경유에서는 무시된다."},"tier.google":{"label":"서비스 티어 — Google","description":"Gemini(Google AI Studio + Vertex) 요청 및 OpenRouter를 경유하는 Google 계열 모델의 처리 티어 (none = 생략). 최상위 `serviceTier` 필드로 전송한다."},"tier.subagent":{"label":"서비스 티어 — 서브에이전트","description":"생성된 task/eval 서브에이전트의 서비스 티어. Inherit = 메인 에이전트의 실시간 계열별 티어를 따른다(/fast를 추적한다). 값을 지정하면 서브에이전트 모델이 속한 계열에 그 값을 적용한다."},"tier.advisor":{"label":"서비스 티어 — Advisor","description":"advisor 모델의 서비스 티어. None = 표준 처리, Inherit = 메인 에이전트의 실시간 계열별 티어를 따른다. 값을 지정하면 advisor 모델의 계열에 그 값을 적용한다."},"retry.maxRetries":{"label":"재시도 횟수","description":"API 오류 시 최대 재시도 횟수"},"retry.modelFallback":{"label":"재시도 모델 폴백","description":"재시도 복구 시 설정된 폴백 모델로 전환하도록 허용한다"},"retry.usageAwareFallback":{"label":"사용량 인식 폴백","description":"신뢰할 수 있는 coding-plan 할당량 보고를 활용해, 하드 사용량 한도에 도달하기 전에 동일 provider 계정을 먼저 사용하고 그다음 설정된 폴백 모델을 사용한다. 일반 설정 API 키는 제외한다."},"retry.usageReservePct":{"label":"예비 마진","description":"남은 비율이 이 값 미만이면 coding-plan 모델이 한도에 근접한 것으로 간주한다. 사용량을 알 수 없거나 매핑되지 않은 경우 주 모델을 유지한다."},"retry.usageReservePolicy":{"label":"예비 정책","description":"동일 provider의 모든 coding-plan 계정이 예비 마진 안에 들어왔을 때의 동작이다."},"retry.fallbackChains":{"label":"재시도 폴백 체인","description":"모델 역할, 모델 선택자(\\"provider/model-id\\"), 또는 provider 와일드카드(\\"provider/*\\")를 순서가 있는 폴백 선택자에 매핑하는 JSON 객체이다. 예: {\\"default\\":[\\"openai/gpt-4o-mini\\"],\\"google-antigravity/*\\":[\\"google/*\\",\\"google-vertex/*\\"]}. 모델 지향 키는 역할과 무관하게 해당 모델/provider가 활성일 때마다 적용되며, \\"provider/*\\" 항목은 실패한 모델의 id를 유지한 채 provider만 교체한다. id 접두사 와일드카드(\\"openrouter/google/*\\")는 실패한 모델의 순수 id에 접두사를 다시 붙이고(google-antigravity/gemini-x -> openrouter/google/gemini-x), 키로 사용될 때는 해당 접두사 아래의 그 provider id에만 매칭된다."},"retry.fallbackRevertPolicy":{"label":"폴백 복귀 정책","description":"폴백 이후 주 모델로 되돌아가는 시점이다"},"providers.anthropic.serverSideFallback":{"label":"Anthropic 서버 사이드 폴백 (Fable 5)","description":"Claude Fable 5 / Mythos 5 요청이 Anthropic의 안전 분류기에 의해 차단되면 서버 사이드에서 Claude Opus 4.8로 재시도한다(Anthropic `server-side-fallback-2026-06-01` 베타). 옵트인 방식이며, 끄면 모든 요청에 대해 폴백 이전 동작이 유지된다."},"providers.autoThinkingModel":{"label":"Auto Thinking 모델","description":"`auto` thinking 레벨의 난이도 분류기이다. 기본값은 온라인(/models의 TINY 역할, 없으면 smol)이며, 로컬 온디바이스 모델도 사용할 수 있다"},"providers.autoThinkingMaxEffort":{"label":"Auto Thinking 상한","description":"`auto` 분류기가 도달할 수 있는 최고 effort이다. `xhigh`는 분류기를 최상위보다 한 단계 아래로 유지해 명시적인 `ultrathink`만 `max`에 도달하게 하며, `max`는 분류기가 예외적이라고 판단한 턴이 이를 노출하는 모델에서 최상위 티어로 과금되도록 허용한다."},"autoResume":{"label":"자동 재개","description":"현재 디렉터리의 가장 최근 세션을 자동으로 재개한다"},"power.sleepPrevention":{"label":"절전 방지","description":"활성 세션 동안 macOS 절전을 방지한다. 각 레벨은 누적되며, 하위 레벨의 플래그를 모두 포함한다."},"git.enabled":{"label":"Git 통합 활성화","description":"TUI에 git 브랜치, 상태, PR 정보를 표시하고 저장소 메타데이터를 감시한다."},"steeringMode":{"label":"Steering 모드","description":"에이전트가 작업하는 동안 대기 중인 메시지를 처리하는 방식이다"},"followUpMode":{"label":"후속 메시지 모드","description":"턴이 완료된 후 후속 메시지를 처리하는 방식이다"},"interruptMode":{"label":"인터럽트 모드","description":"steering 메시지가 도구 실행을 중단하는 시점이다"},"loop.mode":{"label":"Loop 모드","description":"/loop 반복 사이에 프롬프트를 다시 제출하기 전에 일어나는 동작이다"},"doubleEscapeAction":{"label":"이중 Escape 동작","description":"편집기가 비어 있는 상태에서 Escape를 두 번 누를 때의 동작이다"},"treeFilterMode":{"label":"세션 트리 필터","description":"세션 트리를 열 때의 기본 필터 모드이다"},"autocompleteMaxVisible":{"label":"자동완성 항목 수","description":"자동완성 드롭다운에 표시되는 최대 항목 수이다 (3-20)"},"emojiAutocomplete":{"label":"이모지 자동완성","description":"`:name:` 숏코드로 이모지를 제안하고 `:D` 또는 `:-)` 같은 텍스트 이모티콘을 확장한다"},"paste.largeMenuThreshold":{"label":"대용량 붙여넣기 메뉴","description":"붙여넣기가 이 줄 수에 도달하면 코드 블록으로 감싸기, XML 태그로 감싸기, 파일로 저장하기 메뉴를 제공한다. 0은 메뉴를 비활성화한다(대용량 붙여넣기는 여전히 [Paste] 마커로 축약된다)."},"startup.quiet":{"label":"조용한 시작","description":"환영 화면과 시작 상태 메시지를 건너뛴다"},"startup.showSplash":{"label":"시작 스플래시 표시","description":"설정을 다시 실행하지 않고 일반 대화형 시작 시 전체 애니메이션 설정 스플래시를 표시한다. 조용한 시작은 여전히 이를 억제한다."},"startup.setupWizard":{"label":"설정 위저드","description":"새로 추가된 온보딩 단계를 설정 버전마다 한 번 표시한다"},"startup.checkUpdate":{"label":"업데이트 확인","description":"시작 시 omp 업데이트를 확인한다"},"marketplace.autoUpdate":{"label":"마켓플레이스 자동 업데이트","description":"시작 시 플러그인 업데이트를 확인한다"},"startup.changelogMode":{"label":"시작 변경 내역","description":"업데이트 노트를 요약으로 시작할지, 전체 상세로 시작할지, 숨긴 상태로 둘지 선택한다"},"magicKeywords.enabled":{"label":"매직 키워드","description":"단독으로 쓰인 ultrathink, orchestrate, workflowz 키워드에 대한 숨겨진 공지를 활성화한다"},"magicKeywords.ultrathink":{"label":"Ultrathink 키워드","description":"단독으로 쓰인 ultrathink가 최대 자동 사고를 요청하고 숨겨진 공지를 덧붙이도록 한다"},"magicKeywords.orchestrate":{"label":"Orchestrate 키워드","description":"단독으로 쓰인 orchestrate가 숨겨진 멀티 에이전트 오케스트레이션 공지를 덧붙이도록 한다"},"magicKeywords.workflow":{"label":"Workflow 키워드","description":"단독으로 쓰인 workflowz가 숨겨진 eval 워크플로 공지를 덧붙이도록 한다"},"completion.notify":{"label":"완료 알림","description":"에이전트가 턴을 마쳤을 때 알린다"},"error.notify":{"label":"오류 알림","description":"에이전트가 오류로 중단되었을 때 알린다"},"ask.timeout":{"label":"Ask 타임아웃","description":"이 초가 지나면 권장 ask 옵션을 자동 선택한다 (0은 비활성화)"},"ask.notify":{"label":"Ask 알림","description":"ask 도구가 입력을 기다릴 때 알린다"},"recap.enabled":{"label":"유휴 요약","description":"터미널이 유휴 상태가 된 후 현재 상황에 대한 간단한 LLM 요약을 생성한다"},"recap.idleSeconds":{"label":"유휴 요약 지연","description":"요약을 표시하기 전 유휴 상태로 대기하는 초이다"},"collab.relayUrl":{"label":"Relay URL","description":"/collab에서 사용하는 relay이다 (wss://host[:port])"},"collab.webUrl":{"label":"웹 UI URL","description":"/collab 링크에 사용되는 브라우저 UI이다. 비어 있으면 collab.relayUrl에서 파생되며, 명시적인 http://는 localhost에서만 사용된다"},"collab.displayName":{"label":"표시 이름","description":"다른 collab 참가자에게 표시되는 이름이다 (기본값: OS 사용자 이름)"},"share.serverUrl":{"label":"Share 서버","description":"/share에서 사용하는 공유 뷰어/업로드 기준 주소이다 (암호화된 blob 업로드 + 뷰어, 링크는 <base>/<id>#<key> 형식이다)"},"share.store":{"label":"Share 저장소","description":"/share가 암호화된 세션 blob을 업로드하는 위치이다"},"share.redactSecrets":{"label":"공유 시 비밀정보 삭제","description":"업로드 전에 /share 스냅샷에 대해 secret obfuscator를 실행한다(secrets.* 설정을 사용한다)"},"stt.enabled":{"label":"음성 인식","description":"마이크를 통한 speech-to-text 입력을 활성화한다"},"stt.modelName":{"label":"음성 모델","description":"로컬 온디바이스 음성 모델이다. Parakeet TDT v3(sherpa-onnx)가 SoTA 기본값이며, Whisper base/small/large-v3-turbo 등급(transformers.js)은 크기를 다국어 지원과 맞바꾼다. 첫 사용 시 다운로드된다."},"stt.submitTrigger":{"label":"음성 입력 전송 트리거","description":"음성 받아쓰기가 자동으로 전송되는 시점을 선택한다: Never, Release(2단어 이상), 완전한 문장으로 Release, 또는 When I Say Submit."},"tools.approval":{"label":"도구 승인 정책","description":"도구별 승인 정책이다. \'allow\'는 자동 승인, \'prompt\'는 확인 요구, \'deny\'는 차단으로 설정한다. 재정의는 모든 승인 모드에서 적용된다."},"tools.approvalMode":{"label":"도구 승인","description":"도구 호출의 기본 승인 동작이다. \'Always ask\'는 읽기 전용 도구만 자동 승인한다. \'Write\'는 읽기 및 workspace-write 도구를 자동 승인한다. \'Yolo\'는 모든 등급을 자동 승인하지만, 사용자 정책에 따라 확인이나 차단이 발생할 수 있다."},"features.unexpectedStopDetection":{"label":"예상치 못한 중단","description":"어시스턴트가 예상치 못하게 멈추면 자동으로 복구한다. \'기계적\'(기본값)은 표시할 답변 없이 끝난 경우를 재시도하고 도구 호출이 있었던 중단은 제외한다. \'스마트\'는 기계적 감지에 더해 작은 모델로 텍스트만 남긴 중단도 판별하며, \'사용 안 함\'은 감지를 끈다."},"contextPromotion.enabled":{"label":"컨텍스트 자동 승격","description":"컨텍스트 초과 시 compaction 대신 더 큰 컨텍스트 모델로 승격한다"},"compaction.enabled":{"label":"자동 Compact","description":"컨텍스트가 너무 커지면 자동으로 compact한다"},"compaction.midTurnEnabled":{"label":"턴 중간 Compaction","description":"다음 provider 요청 전에 안전한 턴 중간 tool-loop 경계에서 임계값을 확인한다"},"compaction.strategy":{"label":"Compaction 전략","description":"제자리 context-full 유지, auto-handoff, surgical shake(무거운 콘텐츠 제거), snapcompact(히스토리를 밀집 이미지로 보관) 중에서 선택하거나 자동 유지를 비활성화(off)한다"},"compaction.thresholdPercent":{"label":"Compaction 임계값","description":"컨텍스트 유지의 퍼센트 임계값이다. Default로 설정하면 기존 reserve 기반 동작을 사용한다"},"compaction.thresholdTokens":{"label":"Compaction 토큰 한도","description":"컨텍스트 유지의 고정 토큰 한도이다. 설정하면 퍼센트 값을 재정의한다"},"compaction.handoffSaveToDisk":{"label":"Handoff 문서 저장","description":"auto-handoff 흐름에서 생성된 handoff 문서를 markdown 파일로 저장한다"},"compaction.remoteEnabled":{"label":"원격 Compaction","description":"가능한 경우 로컬 요약 대신 원격 compaction 엔드포인트를 사용한다"},"compaction.remoteStreamingV2Enabled":{"label":"원격 Compaction V2","description":"호환되는 원격 compaction 모델에 대해 Responses 스트리밍 compaction을 사용한다"},"compaction.idleEnabled":{"label":"유휴 Compaction","description":"토큰 수가 임계값을 넘으면 유휴 상태에서 컨텍스트를 compact한다"},"compaction.idleThresholdTokens":{"label":"유휴 Compaction 임계값","description":"유휴 compaction이 트리거되는 토큰 수 기준이다"},"compaction.idleTimeoutSeconds":{"label":"유휴 Compaction 지연","description":"compact하기 전 유휴 상태로 대기하는 초이다"},"compaction.supersedeReads":{"label":"오래된 읽기 대체","description":"같은 파일을 다시 읽으면 이전 읽기 결과를 정리한다(캐시 인식, 매 턴 실행)"},"compaction.dropUseless":{"label":"무의미한 결과 제거","description":"컨텍스트상 무용하다고 표시된 도구 결과(일치 없음, 시간 초과된 대기)를 소비된 후 정리한다(캐시 인식)"},"snapcompact.systemPrompt":{"label":"Snapcompact 시스템 프롬프트","description":"실험적 기능이다: 선택한 시스템 프롬프트 텍스트를 밀집 PNG 이미지로 렌더링해 첫 사용자 메시지에 첨부한다(비전 모델 전용). 토큰을 절약하지만 이미지화된 텍스트의 prompt caching을 잃는다."},"snapcompact.toolResults":{"label":"Snapcompact 도구 결과","description":"실험적 기능이다: 큰 과거 도구 결과를 텍스트 대신 밀집 PNG 이미지로 렌더링한다(비전 모델 전용). 누적된 읽기/검색 출력의 토큰을 절약한다."},"tools.format":{"label":"도구 호출 모드","description":"도구가 모델에 노출되는 방식을 제어한다. Auto는 provider-native 도구 호출을 사용하지만, 선택된 모델이 이를 지원하지 않는다고 표시된 경우 GLM owned dialect로 대체한다. Native는 provider-native 도구를 강제하고, 나머지 값은 지정된 owned dialect를 강제한다. 세션 시작 시 적용된다."},"snapcompact.shape":{"label":"Snapcompact 형태","description":"snapcompact가 텍스트를 출력하는 프레임 형태이다(compaction 보관 및 인라인 이미지화). Auto는 현재 모델에 맞게 조정된 형태를 선택한다."},"branchSummary.enabled":{"label":"브랜치 요약","description":"브랜치를 떠날 때 요약을 요청한다"},"ttsr.enabled":{"label":"TTSR","description":"출력이 규칙 패턴과 일치하면 스트리밍 도중에 에이전트를 중단한다(Time-Traveling Stream Rules)"},"ttsr.contextMode":{"label":"TTSR 컨텍스트 모드","description":"TTSR이 발동할 때 부분 출력을 어떻게 처리할지 정한다"},"ttsr.interruptMode":{"label":"TTSR 인터럽트 모드","description":"스트리밍 도중에 중단할지, 완료 후 경고를 주입할지 정한다"},"ttsr.repeatMode":{"label":"TTSR 반복 모드","description":"규칙이 반복되는 방식을 정한다: 세션당 한 번 또는 메시지 간격 이후"},"ttsr.repeatGap":{"label":"TTSR 반복 간격","description":"규칙이 다시 발동할 수 있기까지의 메시지 수이다"},"ttsr.builtinRules":{"label":"기본 제공 규칙","description":"에이전트에 기본 포함된 규칙을 로드한다(ttsr.disabledRules로 개별 해제 가능)"},"memory.backend":{"label":"메모리 백엔드","description":"끄기, 로컬 요약 파이프라인, Mnemopi SQLite, 또는 Hindsight 원격 메모리 중에서 선택한다"},"autolearn.enabled":{"label":"자동 학습 (실험적)","description":"에이전트가 멈춘 뒤 교훈을 메모리에 기록하고 격리된 관리형 skill을 생성/보강하도록 유도한다"},"autolearn.autoContinue":{"label":"중지 시 캡처 자동 실행","description":"켜면 중지 시 비공개 캡처 턴을 한 번 자동 실행한다(추가 토큰을 사용한다). 끄면 상시 자동 학습 안내만 남는다."},"mnemopi.dbPath":{"label":"Mnemopi DB 경로","description":"선택적 SQLite DB 경로이다. 기본값은 에이전트 memories 디렉터리이다."},"mnemopi.bank":{"label":"Mnemopi 뱅크","description":"선택적 공유 뱅크 기본 이름이다. per-project 모드는 이를 기반으로 프로젝트 로컬 뱅크를 파생한다."},"mnemopi.scoping":{"label":"Mnemopi 스코핑","description":"global = 공유 뱅크 하나, per-project = cwd별 격리 뱅크, per-project-tagged = 프로젝트 로컬 쓰기에 global recall 가시성을 더한 방식이다"},"mnemopi.embeddingVariant":{"label":"임베딩 variant","description":"로컬 임베딩 모델 계열이다. en = 더 강력한 영어 모델, multilingual = 교차 언어 모델이다. 이를 변경하면 다음 시작 시 기존 메모리 임베딩을 다시 생성한다."},"mnemopi.autoRecall":{"label":"Mnemopi 자동 recall","description":"각 세션의 첫 턴에 로컬 메모리를 recall한다"},"mnemopi.autoRetain":{"label":"Mnemopi 자동 retain","description":"완료된 대화 턴을 로컬 Mnemopi 메모리에 retain한다"},"mnemopi.polyphonicRecall":{"label":"Mnemopi 폴리포닉 recall","description":"reciprocal rank fusion으로 융합한 4-voice recall(vector, graph, fact, temporal)을 활성화한다"},"mnemopi.enhancedRecall":{"label":"Mnemopi 향상된 recall","description":"반복되거나 유사한 recall 쿼리를 위한 계층형 쿼리 결과 캐시를 활성화한다"},"mnemopi.proactiveLinking":{"label":"Mnemopi 선제적 링킹","description":"새 메모리를 저장하는 즉시 episodic 그래프에 수집해 관련 엔터티 및 메모리와 연결한다"},"mnemopi.noEmbeddings":{"label":"Mnemopi 임베딩 비활성화","description":"vector 임베딩 대신 결정적인 FTS 전용 recall을 강제한다"},"mnemopi.embeddingModel":{"label":"Mnemopi 임베딩 모델","description":"고급: variant를 재정의하는 명시적 임베딩 모델 id이다. 비워 두면 mnemopi.embeddingVariant를 사용한다."},"mnemopi.embeddingApiUrl":{"label":"Mnemopi 임베딩 API URL","description":"Mnemopi에 전달하는 선택적 OpenAI 호환 임베딩 엔드포인트이다"},"mnemopi.embeddingApiKey":{"label":"Mnemopi 임베딩 API 키","description":"Mnemopi에 전달하는 선택적 임베딩 API 키이다"},"mnemopi.llmMode":{"label":"Mnemopi LLM 모드","description":"LLM 미사용, 온라인 tiny 모델(/models의 TINY 역할, 없으면 @smol), 또는 원격 OpenAI 호환 엔드포인트를 사용한다"},"mnemopi.llmBaseUrl":{"label":"Mnemopi LLM Base URL","description":"Mnemopi 원격 모드를 위한 선택적 OpenAI 호환 LLM 엔드포인트이다"},"mnemopi.llmApiKey":{"label":"Mnemopi LLM API 키","description":"Mnemopi 원격 모드를 위한 선택적 LLM API 키이다"},"mnemopi.llmModel":{"label":"Mnemopi LLM 모델","description":"Mnemopi 원격 모드를 위한 선택적 LLM 모델 이름이다"},"hindsight.apiUrl":{"label":"Hindsight API URL","description":"Hindsight 서버 URL(Cloud 또는 self-hosted)이다"},"hindsight.apiToken":{"label":"Hindsight API 토큰","description":"인증이 필요한 Hindsight 서버용 Bearer 토큰이다"},"hindsight.bankId":{"label":"Hindsight Bank ID","description":"메모리 뱅크 식별자다(기본값: 프로젝트 이름)"},"hindsight.scoping":{"label":"Hindsight 범위","description":"global = 하나의 공유 뱅크, per-project = cwd별로 격리된 뱅크, per-project-tagged = 프로젝트 태그가 붙은 공유 뱅크로 recall 시 global 메모리와 프로젝트 메모리가 병합된다"},"hindsight.autoRecall":{"label":"Hindsight 자동 recall","description":"각 세션의 첫 턴에 메모리를 recall한다"},"hindsight.autoRetain":{"label":"Hindsight 자동 retain","description":"N턴마다 그리고 세션 경계에서 대화 기록을 retain한다"},"hindsight.retainMode":{"label":"Hindsight retain 모드","description":"full-session = 세션당 문서 하나를 upsert하고, last-turn = 청크 단위로 저장한다"},"hindsight.mentalModelsEnabled":{"label":"Hindsight 멘탈 모델","description":"부팅 시 정리된 reflect 요약(멘탈 모델)을 developer instructions로 읽어들인다. 뱅크에 있는 기존 모델을 로드하며 쓰기는 하지 않는다. 내장 seed 세트를 자동 생성하려면 hindsight.mentalModelAutoSeed와 함께 사용한다."},"hindsight.mentalModelAutoSeed":{"label":"Hindsight 멘탈 모델 자동 seed","description":"세션 시작 시 뱅크에 아직 없는 내장 멘탈 모델(project-conventions, project-decisions, user-preferences)을 생성한다."},"providers.memoryModel":{"label":"메모리 모델","description":"사실 추출 및 통합에 사용하는 Mnemopi LLM이다: 기본값은 online(/models의 TINY 역할, 없으면 smol/remote)이며, 로컬 on-device 모델도 사용할 수 있다"},"edit.mode":{"label":"편집 모드","description":"edit 도구 변형을 선택한다(replace, patch, hashline, apply_patch)"},"edit.fuzzyMatch":{"label":"퍼지 매치","description":"공백 차이에 대해 신뢰도가 높은 퍼지 매치를 허용한다"},"edit.fuzzyThreshold":{"label":"퍼지 매치 임계값","description":"퍼지 매치를 허용하는 유사도 임계값(0-1)이다"},"edit.streamingAbort":{"label":"프리뷰 실패 시 중단","description":"패치 프리뷰가 실패하면 스트리밍 edit 도구 호출을 중단한다"},"edit.blockAutoGenerated":{"label":"자동 생성 파일 차단","description":"자동 생성된 것으로 보이는 파일(protoc, sqlc, swagger 등)의 편집을 막는다"},"edit.enforceSeenLines":{"label":"확인된 줄 가드 적용","description":"이전 read/search가 전체를 표시하지 않은 줄을 기준으로 하는 편집을 거부한다"},"readLineNumbers":{"label":"줄 번호","description":"기본적으로 read 도구 출력에 줄 번호를 앞에 붙인다"},"read.defaultLimit":{"label":"기본 read 제한","description":"에이전트가 limit 없이 read를 호출할 때 반환하는 기본 줄 수다"},"read.renderMarkdown":{"label":"Markdown 프리뷰","description":"Markdown read 결과를 원본 소스가 아니라 서식이 적용된 터미널 Markdown 프리뷰로 렌더링한다"},"read.summarize.enabled":{"label":"read 요약","description":"명시적 selector 없이 read가 호출되면 구조적 코드 요약을 반환한다"},"read.summarize.prose":{"label":"산문 요약","description":"Markdown 및 일반 텍스트 read에 대해 구조적 요약을 반환한다"},"read.toolResultPreview":{"label":"인라인 read 프리뷰","description":"read 도구 결과를 요약 행이 아니라 대화 기록에 인라인으로 렌더링한다"},"lsp.enabled":{"label":"LSP","description":"코드 인텔리전스(정의, 참조, 진단, 이름 변경)를 위한 lsp 도구를 활성화한다"},"lsp.lazy":{"label":"LSP 지연 시작","description":"세션 시작 시점이 아니라 처음 사용할 때(lsp 도구 호출 또는 해당 파일 타입 편집) language server를 시작한다"},"lsp.shared":{"label":"공유 language server","description":"daemon broker를 통해 프로젝트당 하나의 language server를 omp 인스턴스 간에 공유한다(사용할 수 없으면 개별 서버로 대체된다)"},"lsp.formatOnWrite":{"label":"쓰기 시 포맷","description":"파일을 쓴 후 LSP로 코드 파일을 자동 포맷한다"},"lsp.diagnosticsOnWrite":{"label":"쓰기 시 진단","description":"코드 파일을 쓴 후 LSP 진단을 반환한다"},"lsp.diagnosticsOnEdit":{"label":"편집 시 진단","description":"코드 파일을 편집한 후 LSP 진단을 반환한다"},"lsp.diagnosticsDeduplicate":{"label":"진단 중복 제거","description":"파일에 대해 이미 표시된 편집 후 LSP 진단을 억제하고, 새롭거나 변경된 것만 표시한다"},"bash.enabled":{"label":"Bash","description":"셸 명령 실행을 위한 bash 도구를 활성화한다"},"bash.autoBackground.enabled":{"label":"Bash 자동 백그라운드","description":"오래 실행되는 bash 명령을 자동으로 백그라운드로 보내고 결과를 나중에 전달한다"},"bashInterceptor.enabled":{"label":"Bash 인터셉터","description":"전용 도구가 있는 셸 명령을 차단한다"},"bash.direnv":{"label":"direnv 자동 로드","description":"저장소의 direnv/devenv `.envrc`를 bash 세션에 자동으로 로드해 수동 `direnv exec` 없이 devenv 도구와 환경 변수를 사용할 수 있게 한다. direnv의 허용 목록을 따르며, `direnv allow`하지 않은 `.envrc`는 절대 실행되지 않는다"},"shellMinimizer.enabled":{"label":"셸 출력 축소","description":"장황한 셸 출력(git, npm, cargo 등)을 에이전트에 반환하기 전에 압축한다"},"shellMinimizer.sourceOutlineLevel":{"label":"셸 축소 소스 아웃라인","description":"소스 파일의 cat/read에 대한 소스 아웃라인 모드: default 또는 aggressive"},"eval.py":{"label":"Python Eval 백엔드","description":"eval 도구가 Python 셀을 IPython 커널로 보내도록 허용한다"},"eval.js":{"label":"JavaScript Eval 백엔드","description":"eval 도구가 JavaScript 셀을 인프로세스 런타임으로 보내도록 허용한다"},"eval.rb":{"label":"Ruby Eval 백엔드","description":"eval 도구가 Ruby 셀을 상시 유지되는 Ruby 커널로 보내도록 허용한다"},"eval.jl":{"label":"Julia Eval 백엔드","description":"eval 도구가 Julia 셀을 상시 유지되는 Julia 커널로 보내도록 허용한다"},"python.kernelMode":{"label":"Python 커널 모드","description":"eval 호출 간에 IPython 커널을 유지할지 매번 새로 시작할지 정한다"},"python.interpreter":{"label":"Python 인터프리터","description":"정확한 Python 실행 파일의 선택적 경로이다. 설정하면 자동 Python 런타임 탐색을 건너뛴다."},"ruby.interpreter":{"label":"Ruby 인터프리터","description":"정확한 Ruby 실행 파일의 선택적 경로이다. 설정하면 자동 Ruby 런타임 탐색을 건너뛴다."},"julia.interpreter":{"label":"Julia 인터프리터","description":"정확한 Julia 실행 파일의 선택적 경로이다. 설정하면 자동 Julia 런타임 탐색을 건너뛴다."},"tools.artifactSpillThreshold":{"label":"아티팩트 분리 임계값(KB)","description":"이 크기를 넘는 도구 출력은 아티팩트로 저장되고, 끝부분은 인라인으로 유지된다"},"tools.artifactTailBytes":{"label":"아티팩트 끝부분 크기(KB)","description":"출력이 아티팩트로 넘어갈 때 인라인으로 유지되는 끝부분 내용의 양이다"},"tools.artifactHeadBytes":{"label":"아티팩트 앞부분 크기(KB)","description":"출력이 아티팩트로 넘어갈 때 끝부분과 함께 인라인으로 유지되는 앞부분 내용의 양이다(중간 생략). 0이면 비활성화되어 끝부분만 유지한다."},"tools.outputMaxColumns":{"label":"출력 열 제한","description":"스트리밍 도구 출력(bash, python, js eval)과 `read`에 대한 줄당 바이트 제한이다. 이보다 긴 줄은 말줄임표로 잘리고, 다음 줄바꿈까지 남은 바이트는 버려진다. 0이면 비활성화된다."},"tools.artifactTailLines":{"label":"아티팩트 끝부분 줄 수","description":"출력이 아티팩트로 넘어갈 때 인라인으로 유지되는 끝부분 내용의 최대 줄 수이다"},"todo.enabled":{"label":"할 일 목록","description":"작업 추적을 위한 todo 도구를 활성화한다"},"todo.reminders":{"label":"할 일 알림","description":"중지하기 전에 할 일을 완료하도록 에이전트에 상기시킨다"},"todo.remindersMax":{"label":"할 일 알림 제한","description":"포기하기 전까지의 최대 할 일 알림 횟수이다"},"todo.eager":{"label":"할 일 자동 생성","description":"첫 메시지 이후 자동 할 일 목록 생성을 얼마나 강하게 유도할지 정한다"},"glob.enabled":{"label":"Glob","description":"glob 기반 파일 조회를 위한 glob 도구를 활성화한다"},"grep.enabled":{"label":"Grep","description":"정규식 내용 검색을 위한 grep 도구를 활성화한다"},"grep.contextBefore":{"label":"Grep 앞 컨텍스트","description":"각 grep 일치 항목 앞에 표시할 컨텍스트 줄 수이다"},"grep.contextAfter":{"label":"Grep 뒤 컨텍스트","description":"각 grep 일치 항목 뒤에 표시할 컨텍스트 줄 수이다"},"astGrep.enabled":{"label":"AST Grep","description":"구조적 AST 검색을 위한 ast_grep 도구를 활성화한다"},"astEdit.enabled":{"label":"AST Edit","description":"구조적 AST 재작성을 위한 ast_edit 도구를 활성화한다"},"debug.enabled":{"label":"디버그","description":"DAP 기반 디버깅을 위한 debug 도구를 활성화한다"},"launch.enabled":{"label":"Launch","description":"공유되는 장기 실행 프로젝트 프로세스를 감독하는 launch 도구를 활성화한다"},"speechgen.enabled":{"label":"음성 생성","description":"온디바이스(Kokoro) 또는 xAI Grok Voice 음성 파일 합성을 위한 tts 도구를 활성화한다"},"generate_image.enabled":{"label":"이미지 생성","description":"generate_image 도구(텍스트-이미지 생성 및 편집)를 활성화한다. tools.xdev가 켜져 있으면 xd:// 장치로 노출된다."},"inspect_image.mode":{"label":"이미지 분석","description":"이미지 이해를 비전 지원 모델에 위임하는 inspect_image 도구를 제어한다. \'auto\'는 활성 모델이 네이티브 이미지 입력을 지원하지 않을 때만 노출하고, \'on\'은 항상 노출하며, \'off\'는 노출하지 않는다."},"computer.enabled":{"label":"컴퓨터","description":"스크립트 가능한 호스트 데스크톱 제어 도구(스크린샷, 입력, 접근성)를 활성화한다"},"computer.display":{"label":"컴퓨터 디스플레이","description":"모든 디스플레이를 합성하거나 네이티브 display id를 선택한다"},"inspect_image.timeoutMs":{"label":"이미지 분석 타임아웃","description":"inspect_image 비전 모델 호출의 요청당 타임아웃이며 단위는 milliseconds이다. 응답이 멈춘 제공자는 수동 중단까지 차단되지 않고 타임아웃 오류로 빠르게 실패한다. 0으로 설정하면 타임아웃을 비활성화한다."},"checkpoint.enabled":{"label":"체크포인트/되돌리기","description":"컨텍스트 체크포인팅을 위한 checkpoint 및 rewind 도구를 활성화한다"},"fetch.enabled":{"label":"URL 읽기","description":"read 도구가 URL을 가져와 처리하도록 허용한다"},"vault.enabled":{"label":"Obsidian Vault","description":"Obsidian CLI를 통해 Obsidian vault 내용을 읽고 편집하는 vault:// 내부 URL을 활성화한다. 비활성화하면 vault:// 해석이 거부되고 시스템 프롬프트에서 vault:// 항목이 생략된다."},"github.enabled":{"label":"GitHub CLI","description":"github 도구(리포지터리, 이슈, pull request, diff, 검색, checkout, push, Actions watch 워크플로에 대한 op 기반 디스패치)를 활성화한다"},"github.cache.enabled":{"label":"GitHub 뷰 캐시","description":"렌더링된 이슈/PR 뷰 출력을 ~/.omp/cache/github-cache.db에 캐시해 반복 읽기 비용을 없앤다"},"web_search.enabled":{"label":"웹 검색","description":"실시간 웹 결과를 위한 web_search 도구를 활성화한다"},"security.enabled":{"label":"보안","description":"OMP 네이티브 보안 스캔 계획과 실행, 그리고 읽기 전용 security:// 리소스 네임스페이스를 활성화한다"},"ask.enabled":{"label":"Ask","description":"대화형 사용자 질문을 위한 ask 도구를 활성화한다"},"browser.enabled":{"label":"브라우저","description":"스크립트 기반 Chromium 자동화(puppeteer)를 위한 browser 도구를 활성화한다"},"browser.cdpUrl":{"label":"브라우저 CDP URL","description":"브라우저를 실행하는 대신 연결할 기본 HTTP CDP 디스커버리 엔드포인트이다(예: http://127.0.0.1:9222). 도구 호출에 명시된 app.cdp_url 또는 app.path가 우선한다."},"browser.relay":{"label":"브라우저 릴레이","description":"omp browser relay를 통해 사용자의 Chrome 탭을 제어한다. 확장 프로그램을 한 번 설치하면(`omp browser-relay install`) browser 도구가 필요할 때 릴레이 서버가 자동으로 시작된다. Browser CDP URL보다 우선하며, PI_BROWSER_RELAY=0 또는 PI_BROWSER_RELAY=1로 재정의한다."},"browser.relayUrl":{"label":"브라우저 릴레이 URL","description":"omp browser relay 엔드포인트이다(기본값 http://127.0.0.1:9224)."},"browser.headless":{"label":"헤드리스 브라우저","description":"브라우저를 headless 모드로 실행한다(비활성화하면 브라우저 UI를 표시한다)"},"browser.cmux":{"label":"cmux 브라우저","description":"cmux 소켓을 사용할 수 있을 때 브라우저 자동화에 cmux WKWebView 서피스를 사용한다. PI_BROWSER_CMUX=0 또는 PI_BROWSER_CMUX=1로 재정의한다."},"browser.screenshotDir":{"label":"스크린샷 디렉터리","description":"스크린샷을 저장할 디렉터리이다. 설정하지 않으면 스크린샷은 임시 파일로 저장된다. ~를 지원한다. 예: ~/Downloads, ~/Desktop, /sdcard/Download (Android)"},"tools.intentTracing":{"label":"인텐트 트레이싱","description":"각 도구 호출을 실행하기 전에 그 의도를 설명하도록 에이전트에 요청한다"},"tools.abortOnFabricatedResult":{"label":"조작된 도구 결과 시 중단","description":"in-band 도구 호출에서 모델이 턴 중간에 도구 결과를 환각하기 시작하면 즉시 중단한다. 비활성화하면 모델이 생성을 끝내도록 두고 조작된 이어쓰기를 폐기한다."},"tools.maxTimeout":{"label":"최대 도구 타임아웃","description":"에이전트가 임의의 도구에 설정할 수 있는 최대 타임아웃(초, 0 = 무제한)"},"async.enabled":{"label":"비동기 실행","description":"비동기 bash 명령과 백그라운드 작업 실행을 활성화한다"},"tools.xdev":{"label":"xd:// 도구","description":"드물게 쓰이는(탐색 가능한) 도구의 스키마를 매 요청마다 보내는 대신 read/write로 구동되는 xd:// 디바이스 URL 아래에 마운트한다. write 도구가 허용되지 않은 세션은 마운트를 건너뛰고 모든 도구를 최상위로 노출한다. 비활성화하면 활성화된 모든 도구를 최상위로 노출한다."},"tools.xdevDocs":{"label":"xd:// 프롬프트 문서","description":"시스템 프롬프트에 인라인으로 포함할 마운트된 디바이스 문서와 스키마를 선택한다. Built-ins는 핵심 도구를 인라인으로 유지하고 MCP 및 확장 도구는 on-demand로 남긴다."},"mcp.selection":{"label":"MCP 연결 선택","description":"all은 시작 시 기존 설정대로 연결한다. per-request는 JEV가 요청에 필요한 서버를 선택해 연결하며, 설치\xb7인증\xb7권한은 자동 승인하지 않는다. 변경 후 새 세션에서 적용된다."},"mcp.enableProjectConfig":{"label":"MCP 프로젝트 설정","description":"프로젝트 루트에서 .mcp.json/mcp.json을 로드한다"},"mcp.renderMarkdownResults":{"label":"MCP Markdown 결과","description":"JSON이 아닌 MCP 텍스트 결과를 트랜스크립트에서 Markdown으로 렌더링한다"},"mcp.notifications":{"label":"MCP 업데이트 주입","description":"MCP 리소스 업데이트를 에이전트 대화에 주입한다"},"tasks.todoClearDelay":{"label":"Todo 자동 정리 지연","description":"완료되거나 중단된 todo가 todo 위젯에서 제거되기까지의 지연 시간이다"},"dev.autoqa":{"label":"Auto QA","description":"자동 도구 이슈 보고(xd://report_issue)이다. 기본적으로 켜져 있으며, 첫 보고 시 동의를 요청하고 거부하면 명시적으로 다시 활성화할 때까지 보고를 비활성화한다"},"dev.autoqaPush.endpoint":{"label":"Auto QA 푸시 엔드포인트","description":"Auto QA JSON 보고를 수신하는 전체 URL이다(기본값 https://qa.omp.sh/v1/grievances)"},"plan.enabled":{"label":"Plan 모드","description":"실행 전 읽기 전용 탐색과 계획 수립을 위한 plan 모드를 활성화한다"},"plan.defaultOnStartup":{"label":"Plan 모드로 시작","description":"모든 새 세션 시작 시 자동으로 plan 모드로 진입한다"},"goal.enabled":{"label":"Goal 모드","description":"세션별 goal 모드와 숨겨진 goal 도구를 활성화한다"},"goal.statusInFooter":{"label":"푸터의 Goal 상태","description":"상태 표시줄에서 goal 표시기와 함께 토큰 예산을 표시한다"},"title.refreshOnReplan":{"label":"재계획 시 제목 갱신","description":"사용자가 제목을 설정한 경우가 아니면 todo init 재계획 이후 생성된 세션 제목을 갱신한다"},"task.isolation.mode":{"label":"격리 모드","description":"서브에이전트의 격리 백엔드이다. \\"auto\\"는 네이티브 PAL이 사용 가능한 최적 백엔드를 선택하게 한다(CoW를 지원하는 파일시스템, 그다음 overlayfs/ProjFS, 그다음 git worktree / 재귀 복사 폴백)."},"task.isolation.apply":{"label":"격리 변경 적용","description":"성공한 격리 작업의 변경을 부모 체크아웃에 자동으로 적용한다. 비활성화하면 patch 또는 branch 아티팩트를 유지한다"},"task.isolation.merge":{"label":"격리 병합 전략","description":"격리 작업의 변경을 통합하는 방식이다(patch apply 또는 branch merge)"},"task.isolation.commits":{"label":"격리 커밋 스타일","description":"중첩 저장소 변경의 커밋 메시지 스타일이다(generic 또는 AI 생성)"},"worktree.base":{"label":"Worktree 기본 디렉터리","description":"에이전트가 관리하는 worktree의 기본 디렉터리로, 작업 격리 사본, `github` PR 체크아웃, `omp worktree` 정리가 모두 여기에 위치한다. 설정하지 않으면 ~/.omp/wt를 사용한다. 절대 경로 또는 ~ 기준 경로여야 하며, 상대 경로는 무시된다. OMP_WORKTREE_DIR 환경 변수가 이 값을 재정의한다."},"task.eager":{"label":"작업 위임 선호도","description":"서브에이전트에 작업을 위임하도록 얼마나 강하게 유도할지를 정한다"},"task.batch":{"label":"작업 호출 배치","description":"task 도구를 배치 형태로 전환한다: 한 번의 호출이 { context, tasks[] }를 전달하며, 항목당 서브에이전트 하나가 실행되고, 항목별 agent(기본값은 세션 spawn-policy 에이전트)와 항목별 격리를 지정할 수 있으며, 공유 context는 모든 assignment 앞에 필수로 붙는다. async.enabled=true인 경우 각 spawn은 일반적인 idle/parked 수명 주기를 갖는 독립 백그라운드 에이전트로 실행되고, 그렇지 않으면 호출은 병합된 결과를 기다리며 블로킹된다. 비활성화하면 평면적인 단일 spawn 스키마로 되돌아간다."},"task.enableEffort":{"label":"작업별 effort","description":"task spawn에서 선택적 effort 파라미터를 노출해, 호출자가 각 서브에이전트의 thinking 레벨을 재정의할 수 있게 한다"},"task.maxConcurrency":{"label":"최대 동시 작업 수","description":"동시에 실행되는 서브에이전트의 최대 개수이다"},"task.enableLsp":{"label":"서브에이전트 LSP","description":"task 도구로 생성된 서브에이전트가 lsp 도구를 사용할 수 있게 한다. 서브에이전트 비용을 낮게 유지하기 위해 기본적으로 꺼져 있으며, LSP를 활용한 위임이 추가 토큰만큼 가치가 있을 때 활성화한다."},"task.maxRecursionDepth":{"label":"최대 작업 재귀 깊이","description":"서브에이전트가 자신의 서브에이전트를 생성할 수 있는 최대 깊이이다"},"task.maxRuntimeMs":{"label":"서브에이전트 최대 실행 시간","description":"서브에이전트당 절대 실행 시간 제한(ms)이다. 0이면 비활성화된다. 추론 계층 워치독을 빠져나가는 프로바이더 측 스트림 정지에 대한 심층 방어 수단이며, \'timed out\' 사유로 일반적인 서브에이전트 중단을 발생시킨다."},"task.softRequestBudget":{"label":"서브에이전트 소프트 요청 예산","description":"서브에이전트당 소프트 요청 예산(실행당 assistant 요청 수)이다. 이를 초과하면 마무리를 유도하는 steering 알림이 주입되며(task.softRequestBudgetNotice 참고), 예산의 1.5배에 도달하면 실행이 강제 중단되고 에이전트는 부분 결과를 내놓아야 한다. 0이면 이 보호 장치가 비활성화된다. 번들된 scout/sonic 에이전트는 더 낮은 내장 예산이 상한이므로, 그 상한보다 낮은 값은 이들에게도 적용된다."},"task.softRequestBudgetNotice":{"label":"소프트 요청 예산 알림","description":"서브에이전트가 소프트 요청 예산을 초과할 때 steering 알림을 한 번 주입해, 1.5배 강제 중단 전에 마무리하도록 요청한다."},"task.maxEffort":{"label":"spawn당 최대 effort","description":"task 도구의 spawn별 effort 힌트에 허용되는 최대 추론 effort이다. 값을 낮추면 호출자가 서브에이전트를 이 상한 이상으로 올릴 수 없으며, 기본값은 모델의 전체 범위를 유지한다."},"task.prewalk":{"label":"일반 작업 prewalk","description":"번들된 일반 `task` 서브에이전트에 prewalk를 적용한다: 해석된 모델로 시작해 계획을 세우고 구현을 시작한 뒤, 첫 편집/쓰기 시점에 \'smol\' 역할로 넘긴다. 에이전트별 재정의(/agents 허브에서 설정하는 task.agentPrewalk)와 사용자 에이전트의 `prewalk` frontmatter는 이 토글과 무관하게 적용된다."},"skills.enableSkillCommands":{"label":"스킬 명령","description":"스킬을 /skill:name 명령으로 등록한다"},"commands.enableClaudeUser":{"label":"Claude 사용자 명령","description":"~/.claude/commands/에서 명령을 로드한다"},"commands.enableClaudeProject":{"label":"Claude 프로젝트 명령","description":".claude/commands/에서 명령을 로드한다"},"commands.enableOpencodeUser":{"label":"OpenCode 사용자 명령","description":"~/.config/opencode/commands/에서 명령을 로드한다"},"commands.enableOpencodeProject":{"label":"OpenCode 프로젝트 명령","description":".opencode/commands/에서 명령을 로드한다"},"providers.maxInFlightRequests":{"label":"최대 동시 요청 수","description":"프로바이더 id별(예: \\"openai\\" 또는 \\"anthropic\\") 최대 동시 LLM 요청 수로, 같은 config root를 쓰는 로컬 OMP 프로세스 간에 공유된다. 명시되지 않은 프로바이더는 제한이 없다."},"secrets.enabled":{"label":"시크릿 숨김","description":"AI 프로바이더로 전송하기 전에 설정된 시크릿을 난독화하고 자격 증명 형태의 토큰을 마스킹한다"},"providers.webSearchOrder":{"label":"웹 검색 프로바이더 순서","description":"web_search 도구에 사용할 프로바이더의 우선순위이며, 목록에 없는 프로바이더는 그 뒤에 기본 순서를 유지한다"},"providers.webSearchExclude":{"label":"제외할 웹 검색 프로바이더","description":"web_search가 폴백으로도 절대 사용하지 않을 프로바이더이다"},"providers.webSearchTimeoutSeconds":{"label":"웹 검색 타임아웃","description":"web_search가 다음 폴백으로 넘어가기 전 각 프로바이더 검색 전송에 적용되는 절대 타임아웃이며 단위는 초이다(최대 300)"},"providers.webSearchGeminiModel":{"label":"Gemini web_search 모델","description":"Gemini Google Search grounding에 사용할 모델 ID이다. 기본값은 gemini-2.5-flash이다."},"providers.antigravityEndpoint":{"label":"Antigravity 엔드포인트 모드","description":"google-antigravity 프로바이더의 엔드포인트 라우팅 전략이다(chat, search, image, discovery)"},"providers.imageOrder":{"label":"이미지 프로바이더 순서","description":"이미지 생성에 사용할 프로바이더의 우선순위이며, 목록에 없는 프로바이더는 활성 세션 프로바이더와 내장 순서를 따른다"},"providers.fireworksTier":{"label":"Fireworks 티어","description":"Fireworks 요청의 서빙 경로이다. Priority는 `service_tier: \\"priority\\"`를 전송해 트래픽이 몰릴 때 더 높은 신뢰성을 더 높은 가격에 제공하고, Standard는 이를 생략한다. Fast(`-fast`) 모델은 이 설정을 무시하며, Fast는 별도의 서빙 경로이다."},"live.voice":{"label":"Live 음성","description":"Codex 기반 realtime 음성 세션에서 사용하는 음성이다"},"providers.tts":{"label":"TTS 제공자","description":"tts 도구의 백엔드이다: 로컬 온디바이스 신경망 TTS(Kokoro-82M) 또는 xAI Grok Voice 중 하나이다"},"tts.localModel":{"label":"로컬 TTS 모델","description":"로컬 TTS 백엔드가 사용하는 온디바이스 신경망 TTS 모델(Kokoro-82M)이다"},"tts.localVoice":{"label":"로컬 TTS 음성","description":"로컬 TTS 백엔드가 사용하는 Kokoro 음성이다(미국/영국, 여성/남성)"},"speech.enabled":{"label":"음성 출력","description":"어시스턴트의 출력을 스트리밍되는 대로 스피커로 소리내어 읽는다"},"speech.mode":{"label":"음성 출력 모드","description":"읽을 대상이다: all = 어시스턴트 메시지 + 사고 과정, assistant = 메시지만, yield = 턴 종료 시 마지막 메시지만이다"},"speech.enhanced":{"label":"향상된 음성 재작성","description":"합성 전에 tiny/smol 모델로 어시스턴트 출력을 자연스러운 구어체 산문으로 재작성한다(코드는 설명으로 바꾸고 링크와 markdown은 제거한다). 실패하면 기계적 정리로 대체된다"},"speech.voice":{"label":"음성 출력 목소리","description":"어시스턴트의 출력을 소리내어 읽을 때 사용하는 Kokoro 음성이다"},"providers.tinyModel":{"label":"Tiny 모델","description":"세션 제목 생성 모델이다: 기본값은 온라인(/models의 TINY 역할, 없으면 @smol)이며, 로컬 온디바이스 모델도 가능하다"},"providers.tinyModelDevice":{"label":"Tiny 모델 디바이스","description":"로컬 tiny 모델(제목 + 메모리)에 사용하는 ONNX 실행 제공자이다. 기본값은 CPU 전용 추론을 사용한다. PI_TINY_DEVICE 환경 변수가 이 값을 덮어쓴다."},"providers.tinyModelDtype":{"label":"Tiny 모델 정밀도","description":"로컬 tiny 모델의 ONNX 양자화/정밀도이다. 기본값은 각 모델에 포함된 dtype(q4)을 사용하며, 정밀도가 낮으면 더 빠르고 높으면 원본에 더 충실하다. PI_TINY_DTYPE 환경 변수가 이 값을 덮어쓴다."},"providers.unexpectedStopModel":{"label":"예기치 않은 중단 모델","description":"예기치 않은 중단 감지용 분류기이다: 기본값은 온라인(/models의 TINY 역할, 없으면 smol)이며, 로컬 온디바이스 모델도 가능하다."},"providers.kimiApiFormat":{"label":"Kimi API 형식","description":"Kimi Code 제공자의 API 형식이다(auto는 라이브 모델 메타데이터를 따른다)"},"providers.openaiWebsockets":{"label":"OpenAI WebSockets","description":"OpenAI Codex 모델의 websocket 정책이다(auto는 모델 기본값을 사용하고, on은 강제하며, off는 비활성화한다)"},"providers.streamFirstEventTimeoutSeconds":{"label":"스트림 첫 이벤트 타임아웃","description":"모델 스트림의 첫 이벤트를 기다리는 초이다. -1은 provider/env 기본값을 사용하고, 0은 워치독을 비활성화한다"},"providers.streamIdleTimeoutSeconds":{"label":"스트림 유휴 타임아웃","description":"모델 스트림이 이벤트 사이에 무응답 상태로 있을 수 있는 초이다. -1은 provider/env 기본값을 사용하고, 0은 워치독을 비활성화한다"},"providers.openrouterVariant":{"label":"OpenRouter 라우팅","description":"OpenRouter 모델 ID에 덧붙이는 기본 라우팅 variant 접미사이다(선택기에서 이미 variant를 지정한 경우 무시된다)"},"providers.fetch":{"label":"Fetch 제공자","description":"fetch/read URL 도구의 리더 백엔드 우선순위이다"},"codexResets.autoRedeem":{"label":"Codex 리셋 자동 사용","description":"저장된 Codex rate-limit 리셋을 자동으로 사용한다: 턴이 멈추고 다른 계정이 대체할 수 없을 때 5h 또는 weekly 창을 소진해 차단된 계정을 복구하고, 곧 만료될 크레딧을 회수한다. unset은 첫 사용 전에 확인하고, yes는 확인 없이 사용하며, no는 두 검사 모두 비활성화한다."},"provider.appendOnlyContext":{"label":"추가 전용 컨텍스트","description":"시스템 프롬프트 + 도구 명세를 캐시하고 추가 전용 메시지 로그를 유지해 provider prefix 캐시(DeepSeek, Xiaomi/SGLang, Anthropic) 적중률을 최대화한다. auto는 prefix 캐시가 알려진 제공자에 대해 활성화한다."},"exa.enabled":{"label":"Exa","description":"Exa 웹 검색 제공자를 활성화한다"},"searxng.endpoint":{"label":"SearXNG 엔드포인트","description":"웹 검색에 사용하는 자체 호스팅 SearXNG 인스턴스의 기본 URL이다"}}}'),oc=[{id:"models",label:"Models",icon:"model"},{id:"themes",label:"Themes",icon:"theme"},{id:"skills",label:"Skills",icon:"skill",requiresCwd:!0},{id:"plugins",label:"Plugins",icon:"plugin",requiresCwd:!0},{id:"mcp",label:"MCP",icon:"mcp"},{id:"access",label:"Access",icon:"access"},{id:"trust",label:"Project trust",labelKey:"trust.settingsNav",icon:"trust"},{id:"live-voice",label:"Call voice",labelKey:"chat.liveVoiceSettingsNav",icon:"liveVoice"}],ou={model:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"}),(0,r.jsx)("path",{d:"M9 9h6v6H9zM9 1v3m6-3v3M9 20v3m6-3v3M1 9h3m16 0h3M1 15h3m16 0h3"})]}),theme:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"8"}),(0,r.jsx)("path",{d:"M12 4a8 8 0 0 0 0 16z"})]}),skill:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"m12 3 8 4-8 4-8-4 8-4Z"}),(0,r.jsx)("path",{d:"m4 12 8 4 8-4M4 17l8 4 8-4"})]}),plugin:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M8 3v5m8-5v5M6 8h12v5a6 6 0 0 1-12 0V8Zm6 11v3"})}),mcp:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"6",cy:"6",r:"2"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"2"}),(0,r.jsx)("circle",{cx:"12",cy:"18",r:"2"}),(0,r.jsx)("path",{d:"M8 7.5 11 16m5-8.5L13 16M8 6h8"})]}),access:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"4",y:"10",width:"16",height:"10",rx:"2"}),(0,r.jsx)("path",{d:"M8 10V7a4 4 0 0 1 8 0v3M12 14v2"})]}),trust:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),liveVoice:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,r.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2M12 19v3"})]}),appearance:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 3v18M3 12h18"})]}),interaction:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M4 5h16v11H9l-5 4V5Z"}),(0,r.jsx)("path",{d:"M8 9h8m-8 3h5"})]}),context:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M5 3h11l3 3v15H5z"}),(0,r.jsx)("path",{d:"M15 3v4h4M8 11h8m-8 4h8"})]}),memory:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M9 4a3 3 0 0 0-3 3v1a3 3 0 0 0-1 5v1a3 3 0 0 0 3 3h1m6-13a3 3 0 0 1 3 3v1a3 3 0 0 1 1 5v1a3 3 0 0 1-3 3h-1M9 4v16m6-16v16"})}),files:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M3 6h7l2 2h9v11H3z"})}),shell:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),(0,r.jsx)("path",{d:"m7 9 3 3-3 3m6 0h4"})]}),tools:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"m14 6 4-4 4 4-4 4M3 18l8-8m-6 4 5 5-3 3-5-5 3-3Z"})}),tasks:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M9 6h11M9 12h11M9 18h11M4 6l1 1 2-2m-3 7 1 1 2-2m-3 7 1 1 2-2"})}),providers:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M7 4h10v5H7zM4 15h6v5H4zm10 0h6v5h-6zM12 9v3m-5 0h10M7 12v3m10-3v3"})})};function op({kind:e}){return(0,r.jsx)("svg",{className:ot().navIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:ou[e]??ou.tools})}function oh({field:e,busy:t,onSave:n}){let[s,a]=(0,i.useState)("secret"===e.type?"":String(e.value??""));(0,i.useEffect)(()=>{a("secret"===e.type?"":String(e.value??""))},[e.path,e.type,e.value]);let l="secret"===e.type?"":String(e.value??"");return(0,r.jsx)("input",{className:ot().textInput,type:"secret"===e.type?"password":"text",value:s,disabled:t,placeholder:"secret"===e.type&&e.configured?"Configured — enter to replace":void 0,onChange:e=>a(e.target.value),onBlur:()=>{s!==l&&("secret"!==e.type||s.length>0)&&n(s)},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})}function om({field:e,busy:t,onSave:n}){let s=JSON.stringify(e.value??{},null,2),[a,l]=(0,i.useState)(s),[o,d]=(0,i.useState)(null);return(0,i.useEffect)(()=>{l(s),d(null)},[s]),(0,r.jsxs)("div",{style:{width:"100%"},children:[(0,r.jsx)("textarea",{className:ot().jsonEditor,style:{minHeight:92},value:a,disabled:t,onChange:e=>l(e.target.value),onBlur:()=>{if(a!==s)try{n(JSON.parse(a)),d(null)}catch(e){d(e instanceof Error?e.message:String(e))}}}),o&&(0,r.jsx)("div",{className:ot().error,children:o})]})}function of({field:e,busy:t,onSave:n}){let i=Array.isArray(e.value)?e.value:[],s=(e,t)=>{let r=e+t;if(r<0||r>=i.length)return;let s=[...i];[s[e],s[r]]=[s[r],s[e]],n(s)};return(0,r.jsx)("div",{className:ot().multiSelect,children:e.options?.map(a=>{let l=i.indexOf(a.value);return(0,r.jsxs)("span",{className:ot().choice,"data-selected":l>=0,title:a.description,children:[(0,r.jsx)("button",{type:"button",className:ot().choiceToggle,disabled:t,onClick:()=>{let e;return e=a.value,n(i.includes(e)?i.filter(t=>t!==e):[...i,e])},children:a.label}),e.ordered&&l>=0&&(0,r.jsxs)("span",{className:ot().reorder,children:[(0,r.jsx)("button",{type:"button",disabled:t||0===l,onClick:()=>s(l,-1),children:"←"}),(0,r.jsx)("button",{type:"button",disabled:t||l===i.length-1,onClick:()=>s(l,1),children:"→"})]})]},a.value)})})}function og({field:e,busy:t,onSave:n}){return"boolean"===e.type?(0,r.jsx)("button",{type:"button",className:ot().switch,"data-on":!0===e.value,disabled:t,"aria-pressed":!0===e.value,onClick:()=>n(!0!==e.value)}):"select"===e.type?(0,r.jsx)(aK,{value:String(e.value??""),disabled:t,ariaLabel:e.label,options:(e.options??[]).map(e=>({value:e.value,label:e.label,description:e.description})),onChange:t=>n("number"==typeof e.value||"number"==typeof e.defaultValue?Number(t):t)}):"multiselect"===e.type?(0,r.jsx)(of,{field:e,busy:t,onSave:n}):"providerLimits"===e.type?(0,r.jsx)(om,{field:e,busy:t,onSave:n}):(0,r.jsx)(oh,{field:e,busy:t,onSave:n})}function ox({field:e,busy:t,error:n,onSave:i}){return(0,r.jsxs)("div",{className:ot().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:ot().settingLabel,children:e.label}),(0,r.jsx)("div",{className:ot().settingDescription,children:e.description}),n&&(0,r.jsx)("div",{className:ot().error,children:n})]}),(0,r.jsx)("div",{className:ot().settingControl,children:(0,r.jsx)(og,{field:e,busy:t,onSave:i})})]})}function ov({mode:e,palette:t}){let n=t.variables["--omp-md-heading"];return(0,r.jsxs)("div",{className:ot().themePreview,"data-seed-color-mode":"dark"===e?"dark-only":"light-only",children:[(0,r.jsx)("div",{className:ot().themePreviewBar,style:n?{background:n}:void 0}),(0,r.jsxs)("div",{className:ot().themePreviewPanel,children:[(0,r.jsx)("div",{className:ot().themePreviewLine}),(0,r.jsx)("div",{className:ot().themePreviewLine})]})]})}let ob='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',oy=new Set(["hideThinkingBlock"]);function ow({cwd:e,sessionId:t,initialSection:n="models",onClose:s,onModelsChanged:a,onReloaded:l}){let[o,d]=(0,i.useState)(n),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!0),[m,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(""),[v,b]=(0,i.useState)(new Set),[y,w]=(0,i.useState)({}),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),{theme:N,setPreference:I}=tA(),{locale:T,t:M}=(0,R.s)(),$=(0,i.useRef)(null),E=e=>"ko"===T?od.shell[e]??e:e,L=(0,i.useCallback)(async()=>{h(!0),f(null);try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/settings${t}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);u(r)}catch(e){f(e instanceof Error?e.message:String(e))}finally{h(!1)}},[e]);(0,i.useEffect)(()=>{L()},[L]),(0,i.useEffect)(()=>{let e=$.current;if(!e)return;(Array.from(e.querySelectorAll(ob)).find(e=>e.getClientRects().length>0)??e).focus();let t=t=>{if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll(ob)).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],s=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),s.focus()):t.shiftKey||r!==s&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)},[]);let A=(0,i.useCallback)(async(t,n)=>{b(e=>new Set(e).add(t.path)),w(e=>{let n={...e};return delete n[t.path],n});try{let r=await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,value:n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);u(e=>e?{...e,fields:e.fields.map(e=>e.path===t.path?{...e,value:i.value??n,configured:!0}:e)}:e),"theme.dark"===t.path||"theme.light"===t.path?(await tL(e),await L()):oy.has(t.path)?await tY(e):j(!0)}catch(e){w(n=>({...n,[t.path]:e instanceof Error?e.message:String(e)}))}finally{b(e=>{let n=new Set(e);return n.delete(t.path),n})}},[e,L]),z=(0,i.useMemo)(()=>new Map(c?.fields.map(e=>[e.path,e.value])??[]),[c?.fields]),W=(0,i.useMemo)(()=>c?.fields.filter(e=>(function(e,t){switch(e.condition){case void 0:default:return!0;case"hasImageProtocol":return!1;case"advisorEnabled":return!0===t.get("advisor.enabled");case"hindsightActive":return"hindsight"===t.get("memory.backend");case"mnemopiActive":return"mnemopi"===t.get("memory.backend");case"autolearnActive":return!0===t.get("autolearn.enabled");case"autoThinkingActive":return"auto"===t.get("defaultThinkingLevel");case"usageAwareFallbackEnabled":return!0===t.get("retry.usageAwareFallback");case"planModeEnabled":return!0===t.get("plan.enabled");case"unexpectedStopDetection":return!0===t.get("features.unexpectedStopDetection")}})(e,z))??[],[c?.fields,z]),F=o.startsWith("settings:")?o.slice(9):null,P=(0,i.useMemo)(()=>{let e=g.trim().toLowerCase();return e?W.filter(t=>`${t.label} ${t.description} ${t.path} ${t.group??""}`.toLowerCase().includes(e)):F?W.filter(e=>e.tab===F&&("appearance"!==F||"Theme"!==e.group)):[]},[F,g,W]),D=(0,i.useCallback)(()=>{a?.(),s()},[s,a]),_=(0,i.useCallback)(async()=>{if(t){C(!0);try{await sR(t,{type:"reload"}),j(!1),l?.()}catch(e){f(e instanceof Error?e.message:String(e))}finally{C(!1)}}},[l,t]),O=c?.tabs.find(e=>e.id===F),H=g.trim()?`${E("Search")} \xb7 ${P.length}`:O?.label??E("Settings"),B=(e,t)=>[...new Set([...t,...e.map(e=>e.group??"General").filter(e=>!t.includes(e))])].map(t=>{let n=e.filter(e=>(e.group??"General")===t);return n.length?(0,r.jsxs)("section",{className:ot().group,children:[(0,r.jsx)("h3",{className:ot().groupTitle,children:t}),n.map(e=>(0,r.jsx)(ox,{field:e,busy:v.has(e.path),error:y[e.path],onSave:t=>void A(e,t)},e.path))]},t):null}),U=()=>p?(0,r.jsx)("div",{className:ot().empty,children:E("Loading omp settings…")}):m||!c?(0,r.jsx)("div",{className:ot().empty,children:m??E("Settings unavailable")}):(0,r.jsxs)("div",{className:ot().scrollContent,children:[(0,r.jsxs)("header",{className:ot().contentHeader,children:[(0,r.jsx)("h2",{className:ot().contentTitle,children:H}),(0,r.jsx)("p",{className:ot().contentDescription,children:E(g.trim()?"Matching canonical /settings entries across every category.":"Canonical omp /settings values. Changes are saved immediately to the shared agent configuration.")}),k&&t&&(0,r.jsxs)("div",{className:ot().reloadNotice,children:[(0,r.jsx)("span",{children:E("Saved. Reload the active session to apply runtime settings.")}),(0,r.jsx)("button",{type:"button",onClick:()=>void _(),disabled:S,children:E(S?"Reloading…":"Reload session")})]})]}),(0,r.jsx)("div",{className:ot().settingsBody,children:P.length?B(P,O?.groups??[]):(0,r.jsx)("div",{className:ot().empty,children:E("No settings match this search.")})})]});return(0,r.jsx)("div",{className:ot().backdrop,onMouseDown:e=>{e.target===e.currentTarget&&D()},children:(0,r.jsxs)("div",{ref:$,tabIndex:-1,className:ot().window,role:"dialog","aria-modal":"true","aria-label":E("Settings"),children:[(0,r.jsxs)("aside",{className:ot().sidebar,children:[(0,r.jsxs)("div",{className:ot().brand,children:[(0,r.jsx)("div",{className:ot().eyebrow,children:"omp /settings"}),(0,r.jsx)("h1",{className:ot().title,children:E("Settings")}),(0,r.jsx)("code",{className:ot().context,title:e??E("Global configuration"),children:e??E("Global configuration")})]}),(0,r.jsxs)("div",{className:ot().searchWrap,children:[(0,r.jsxs)("svg",{className:ot().searchIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]}),(0,r.jsx)("input",{className:ot().search,value:g,"aria-label":E("Search /settings"),placeholder:E("Search /settings"),onChange:e=>x(e.target.value)})]}),(0,r.jsxs)("nav",{className:ot().nav,children:[(0,r.jsx)("div",{className:ot().navLabel,children:E("Configuration")}),oc.map(t=>{let n=t.labelKey?M(t.labelKey):E(t.label);return(0,r.jsxs)("button",{type:"button",className:ot().navButton,"data-active":!g&&o===t.id,disabled:t.requiresCwd&&!e,title:t.requiresCwd&&!e?`${n} ${E("requires a project")}`:n,onClick:()=>{x(""),d(t.id)},children:[(0,r.jsx)(op,{kind:t.icon}),(0,r.jsx)("span",{children:n})]},t.id)}),(0,r.jsx)("div",{className:ot().navLabel,children:E("OMP settings")}),c?.tabs.map(e=>(0,r.jsxs)("button",{type:"button",className:ot().navButton,"data-active":!g&&F===e.id,onClick:()=>{x(""),d(`settings:${e.id}`)},children:[(0,r.jsx)(op,{kind:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id))]}),(0,r.jsx)("div",{className:ot().closeRail,children:(0,r.jsxs)("button",{type:"button",className:ot().closeButton,onClick:D,children:[(0,r.jsx)("span",{children:E("Close settings")}),(0,r.jsx)("span",{"aria-hidden":"true",children:"\xd7"})]})})]}),(0,r.jsx)("main",{className:ot().content,children:g.trim()?U():"models"===o?(0,r.jsx)(l_,{cwd:e,embedded:!0,onClose:D,onModelsChanged:a}):"themes"===o?c?(0,r.jsxs)("div",{className:ot().scrollContent,children:[(0,r.jsxs)("header",{className:ot().contentHeader,children:[(0,r.jsx)("h2",{className:ot().contentTitle,children:E("Themes")}),(0,r.jsxs)("p",{className:ot().contentDescription,children:[E("The web interface uses the same dark and light theme mappings as omp. Changes are persisted to "),(0,r.jsx)("code",{children:"~/.omp/agent/config.yml"}),E(" and applied here immediately.")]})]}),(0,r.jsxs)("div",{className:ot().settingsBody,children:[(0,r.jsx)("div",{className:ot().themeGrid,children:["dark","light"].map(e=>{let t=c.fields.find(t=>t.path===`theme.${e}`),n=c.theme.palettes[e];return(0,r.jsxs)("div",{className:ot().themeCard,children:[(0,r.jsx)(ov,{mode:e,palette:n}),(0,r.jsxs)("div",{className:ot().themeCardBody,children:[(0,r.jsxs)("div",{className:ot().themeCardHeader,children:[(0,r.jsxs)("span",{className:ot().themeSlot,children:[e,E(" mapping")]}),N===e&&(0,r.jsx)("span",{className:ot().themeActive,children:E("Active on web")})]}),(0,r.jsx)(aK,{value:String(t.value),disabled:v.has(t.path),ariaLabel:`${e} theme`,options:(t.options??[]).map(e=>({value:e.value,label:e.label,description:e.description})),onChange:e=>void A(t,e)}),N!==e&&(0,r.jsxs)("button",{type:"button",className:ot().closeButton,style:{marginTop:8},onClick:()=>I(e),children:[E("Preview "),e]})]})]},e)})}),B(c.fields.filter(e=>"appearance"===e.tab&&"Theme"===e.group&&!e.path.startsWith("theme.")),["Theme"])]})]}):(0,r.jsx)("div",{className:ot().empty,children:p?E("Loading themes…"):m??E("Themes unavailable")}):"skills"===o&&e?(0,r.jsx)(lG,{cwd:e,embedded:!0,onClose:D}):"plugins"===o&&e?(0,r.jsx)(l9,{cwd:e,sessionId:t,embedded:!0,onClose:D,onReloaded:l}):"mcp"===o?(0,r.jsx)(ok,{cwd:e,sessionId:t,onReloaded:l}):"access"===o?(0,r.jsx)(on,{}):"trust"===o?(0,r.jsx)(oo,{cwd:e}):"live-voice"===o?(0,r.jsx)(ol,{}):U()})]})})}function ok({cwd:e,sessionId:t,onReloaded:n}){let[s,a]=(0,i.useState)(null),[l,o]=(0,i.useState)("user"),[d,c]=(0,i.useState)(0),[u,p]=(0,i.useState)(""),[h,m]=(0,i.useState)(""),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(null),w=(0,i.useCallback)(async()=>{try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/mcp${t}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);a(r),g(null)}catch(e){g(e instanceof Error?e.message:String(e))}},[e]);(0,i.useEffect)(()=>{w()},[w]);let k=s?"user"===l?s.user:s.project:null,j=k?.servers[d]??null;(0,i.useEffect)(()=>{m(j?.name??""),p(j?JSON.stringify(j.config,null,2):"")},[j]);let S=e=>{a(t=>{if(!t)return t;let n={..."user"===l?t.user:t.project,servers:e};return"user"===l?{...t,user:n}:{...t,project:n}})},C=async()=>{if(k){v(!0),g(null);try{let t,n=(t=k?.servers??[],(j?.editable===!1?t:t.map((e,t)=>t===d?{...e,name:h,config:JSON.parse(u)}:e)).filter(e=>!1!==e.editable).map(({name:e,config:t})=>({name:e,config:t}))),r=e?`?cwd=${encodeURIComponent(e)}`:"",i=await fetch(`/api/mcp${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:l,servers:n})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);await w()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(!1)}}},N=async r=>{y(`${l}:${r.name}`),g(null);try{let i=e?`?cwd=${encodeURIComponent(e)}`:"",s=await fetch(`/api/mcp${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:l,name:r.name,enabled:!r.enabled})}),a=await s.json();if(!s.ok||a.error)throw Error(a.error??`HTTP ${s.status}`);await w(),t&&(await sR(t,{type:"reload"}),n?.())}catch(e){g(e instanceof Error?e.message:String(e))}finally{y(null)}};return(0,r.jsxs)("div",{className:ot().scrollContent,children:[(0,r.jsxs)("header",{className:ot().contentHeader,children:[(0,r.jsx)("h2",{className:ot().contentTitle,children:"MCP servers"}),(0,r.jsx)("p",{className:ot().contentDescription,children:"All MCP servers discovered by OMP are listed by scope and can be enabled or disabled here. Native OMP entries are editable; configurations owned by Claude, Codex, Gemini, plugins, or other providers remain read-only at their source."})]}),(0,r.jsx)("div",{className:ot().settingsBody,children:s?(0,r.jsxs)("div",{className:ot().mcpLayout,children:[(0,r.jsxs)("aside",{className:ot().mcpList,children:[(0,r.jsxs)("div",{className:ot().scopeTabs,children:[(0,r.jsxs)("button",{type:"button",className:ot().scopeButton,"data-active":"user"===l,onClick:()=>{o("user"),c(0)},children:["User \xb7 ",s.user.servers.length]}),(0,r.jsxs)("button",{type:"button",className:ot().scopeButton,"data-active":"project"===l,disabled:!s.project,onClick:()=>{o("project"),c(0)},children:["Project \xb7 ",s.project?.servers.length??0]})]}),k?.error?(0,r.jsx)("div",{className:ot().error,style:{padding:12},children:k.error}):(0,r.jsx)("div",{className:ot().serverRows,children:k?.servers.length?k.servers.map((e,t)=>{let n=`${l}:${e.name}`;return(0,r.jsxs)("div",{className:ot().serverRow,"data-active":d===t,children:[(0,r.jsxs)("button",{type:"button",className:ot().serverSelect,title:e.source?.path,onClick:()=>c(t),children:[(0,r.jsx)("span",{className:ot().statusDot,"data-off":!e.enabled}),(0,r.jsx)("span",{className:ot().serverName,children:e.name}),!1===e.editable&&(0,r.jsx)("span",{className:ot().sourceBadge,children:e.source?.provider??"external"})]}),(0,r.jsx)("button",{type:"button",className:ot().serverToggle,"data-on":e.enabled,disabled:b===n,"aria-pressed":e.enabled,"aria-label":`${e.enabled?"Disable":"Enable"} ${e.name}`,title:`${e.enabled?"Disable":"Enable"} ${e.name}`,onClick:()=>void N(e),children:b===n?"…":e.enabled?"ON":"OFF"})]},`${e.name}-${e.source?.path??t}`)}):(0,r.jsx)("div",{className:ot().serverListEmpty,children:"No servers in this scope."})}),(0,r.jsx)("button",{type:"button",className:ot().addServer,disabled:!!k?.error,onClick:()=>{if(!k)return;let e="new-server",t=2;for(;k.servers.some(t=>t.name===e);)e=`new-server-${t++}`;let n=[...k.servers,{name:e,config:{type:"stdio",command:""},enabled:!0,editable:!0}];S(n),c(n.length-1)},children:"+ Add OMP server"})]}),(0,r.jsx)("section",{className:ot().mcpEditor,children:j?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:ot().editorHeader,children:[(0,r.jsx)("input",{className:ot().textInput,value:h,readOnly:!1===j.editable,onChange:e=>m(e.target.value),placeholder:"server-name"}),!1!==j.editable&&(0,r.jsx)("button",{type:"button",className:ot().dangerButton,onClick:()=>{k&&j&&!1!==j.editable&&(S(k.servers.filter((e,t)=>t!==d)),c(Math.max(0,d-1)))},children:"Delete"})]}),!1===j.editable&&(0,r.jsxs)("div",{className:ot().readOnlyNotice,children:["Configuration read-only \xb7 managed by ",j.source?.provider??"an external provider",". Status can be changed from the server list."]}),(0,r.jsx)("textarea",{className:ot().jsonEditor,value:u,readOnly:!1===j.editable,spellCheck:!1,onChange:e=>p(e.target.value)}),(0,r.jsxs)("div",{className:ot().editorActions,children:[(0,r.jsxs)("div",{children:[f&&(0,r.jsx)("div",{className:ot().error,children:f}),(0,r.jsx)("div",{className:ot().saveState,children:j.source?.path??k?.path})]}),!1!==j.editable&&(0,r.jsx)("button",{type:"button",className:ot().primaryButton,disabled:x,onClick:()=>void C(),children:x?"Saving…":"Save MCP"})]})]}):(0,r.jsx)("div",{className:ot().empty,children:"Add or select an MCP server."})})]}):(0,r.jsx)("div",{className:ot().empty,children:f??"Loading MCP configuration…"})})]})}let oj="cuelo-notification-prompt-dismissed";function oS({variant:e,locale:t,permission:n,dismissed:i,request:s,dismiss:a}){let l="ko"===t;return null===n||"granted"===n?null:"banner"===e?"default"!==n||i?null:(0,r.jsxs)("div",{className:"workspace-update-banner",role:"region","aria-label":l?"알림 권한 안내":"Notification permission",children:[(0,r.jsx)("span",{className:"workspace-update-banner-detail",style:{fontFamily:"inherit",fontSize:"inherit",color:"inherit"},children:l?"백그라운드 작업 완료 알림을 받으세요.":"Get notified when background work finishes."}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:s,children:l?"알림 켜기":"Enable notifications"}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:a,"aria-label":l?"알림 권한 안내 닫기":"Dismiss notification prompt",children:l?"닫기":"Dismiss"})]}):(0,r.jsx)(d.k.Item,{disabled:"denied"===n,onClick:"default"===n?s:void 0,children:(0,r.jsxs)(d.k.ItemBody,{children:[(0,r.jsx)(d.k.ItemLabel,{children:"default"===n?l?"알림 켜기":"Enable notifications":l?"알림 차단됨":"Notifications blocked"}),"denied"===n&&(0,r.jsx)(d.k.ItemDescription,{children:l?"주소창 옆 사이트 설정에서 알림을 허용하세요.":"Allow notifications in site settings beside the address bar."})]})})}function oC({cwd:e,busy:t,scheduled:n,error:s,onCancel:a,onConfirm:l,onCancelSchedule:o}){let{t:d}=(0,R.s)(),c=(0,i.useRef)(null);(0,i.useEffect)(()=>{c.current?.focus()},[n]);let u={height:32,padding:"0 12px",borderRadius:5,cursor:t?"not-allowed":"pointer",fontSize:12};return(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"rgba(0,0,0,0.4)"},onClick:e=>{t||e.target!==e.currentTarget||a()},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title","aria-describedby":"project-trust-body",style:{width:440,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg-panel)",boxShadow:"0 12px 36px rgba(0,0,0,0.24)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:1},children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),n?(0,r.jsx)("path",{d:"M12 8v4l2 2"}):(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{id:"project-trust-title",style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:d(n?"trust.scheduledTitle":"trust.dialogTitle")}),(0,r.jsx)("div",{id:"project-trust-body","aria-live":"polite",style:{marginTop:7,fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:d(n?"trust.scheduledBody":"trust.dialogBody")}),(0,r.jsx)("code",{style:{display:"block",marginTop:10,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:e}),s&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"#ef4444",fontSize:12,lineHeight:1.5},children:s})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[n&&(0,r.jsx)("button",{type:"button",onClick:o,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:d("trust.cancelSchedule")}),(0,r.jsx)("button",{ref:c,type:"button",onClick:a,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:d(n?"trust.close":"trust.cancel")}),!n&&(0,r.jsx)("button",{type:"button",onClick:l,disabled:t,style:{...u,border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:t?"wait":"pointer",opacity:t?.7:1,fontWeight:600},children:d(t?"trust.trusting":"trust.trustProject")})]})]})})}var oN=n(55681),oI=n(54265);let oT={kind:"loading"};function oM(e){return"failed"===e.status?"var(--danger)":"aborted"===e.status||e.progress?.retryState?"var(--warning)":(0,io.Ch)(e.status)?"var(--accent)":"var(--success)"}function o$(e){return"live-archive"===e.identity?"실시간 + 디스크":"live"===e.identity?"실시간":"디스크 기록"}let oR={bundled:"기본 제공",user:"사용자 정의",project:"프로젝트 정의"};function oE(e){return e.lastUpdate||e.progress?.durationMs||0}function oL(){return{display:"grid",placeItems:"center",width:32,height:30,padding:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"}}function oA({sessionId:e,sessionCwd:t,record:n,client:s,visible:a,onBack:l}){let o=(0,i.useMemo)(()=>[{key:n.key,liveId:n.live?.id,status:n.live?.status,archiveName:n.archive?.name}],[n.key,n.live?.id,n.live?.status,n.archive?.name]),d=(0,i.useRef)(null),c=(0,io._Z)(o,{sessionId:e,client:s,enabled:a}).get(n.key)?.state??oT;(0,i.useEffect)(()=>{if(!a||"ready-live"!==c.kind&&"ready-archive"!==c.kind)return;let e=requestAnimationFrame(()=>{let e=d.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[c,a]);let u="ready-live"===c.kind?c.entries:[],p=(0,i.useMemo)(()=>{let e=new Map;for(let t of u)"message"in t&&"toolResult"===t.message.role&&e.set(t.message.toolCallId,t.message);return e},[u]),h=n.live?.id||n.archive?.name||"Subagent";return(0,r.jsxs)("div",{role:"dialog","aria-label":`${h} 기록`,style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:l,"aria-label":"Subagent 목록으로 돌아가기",title:"목록",style:oL(),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m10.5 3-5 5 5 5"})})}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11.5,fontWeight:700},children:h}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9},children:o$(n)})]}),n.live&&(0,r.jsx)("span",{style:{color:oM(n.live),fontFamily:"var(--font-mono)",fontSize:9.5},children:n.live.status})]}),(0,r.jsxs)("div",{ref:d,style:{flex:1,minHeight:0,overflowY:"auto",padding:"10px 12px 18px"},children:["loading"===c.kind&&(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"기록 불러오는 중…"}),"ready-live"===c.kind&&c.entries.flatMap((e,n)=>{if(!("message"in e))return[];let i=c.entries[n-1];return[(0,r.jsx)(rn,{message:e.message,toolResults:p,cwd:t,showTimestamp:!0,prevTimestamp:i&&"message"in i?i.message.timestamp:void 0},e.id)]}),"ready-archive"===c.kind&&(0,r.jsxs)(r.Fragment,{children:[c.note&&(0,r.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--text-muted)",fontSize:9.5,lineHeight:1.5},children:c.note}),c.truncated&&(0,r.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--warning)",fontSize:9.5},children:"최근 400개 기록만 표시합니다."}),c.entries.map((e,t)=>(0,r.jsxs)("div",{style:{margin:"0 0 7px",padding:"8px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontSize:11,lineHeight:1.55},children:[(0,r.jsxs)("div",{style:{marginBottom:5,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:8.5,letterSpacing:"0.04em"},children:[e.role," \xb7 ",e.kind]}),e.text||"(내용 없음)"]},`${e.at??0}:${t}`))]}),"empty"===c.kind&&(0,r.jsxs)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:[c.note&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:c.note}),(0,r.jsx)("br",{})]}),"대화 내용이 없습니다."]}),"unreachable"===c.kind&&(0,r.jsx)("div",{role:"status",style:{padding:10,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",fontSize:10.5,lineHeight:1.5},children:c.message}),"error"===c.kind&&(0,r.jsx)("div",{role:"alert",style:{padding:10,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--danger)",fontSize:10.5,lineHeight:1.5},children:c.message})]})]})}function oz({record:e,onSelect:t}){let n=e.live,i=e.archive,s=(0,ng.$V)(e),a=n?.id||i?.name||"Subagent",l=o$(e),o=(0,ng.wX)(e),d=(0,ng.A7)(e),c=d.modelShort??"모델 미확인",u=d.effort??"추론 미확인",p="known"===o.kind?o.label:"역할 미확인";return(0,r.jsxs)("button",{type:"button",role:"listitem",onClick:t,"data-identity":e.identity,title:`${a}
|
|
20
|
-
${d.model??"모델 미확인"} \xb7 ${u}
|
|
21
|
-
${s.title}${s.stage?`
|
|
22
|
-
현재 단계: ${s.stage}`:""}`,"aria-label":`${p} ${a}, 업무 ${s.title}${s.stage?`, 현재 단계 ${s.stage}`:""}, ${n?n.status:i?.status??"미확인"}, 모델 ${d.model??"미확인"}, 추론 ${u}`,style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",gap:"4px 8px",width:"100%",marginBottom:8,padding:12,border:"1px solid var(--seed-color-stroke-neutral-weak)",borderRadius:"var(--seed-radius-r2)",background:"var(--seed-color-bg-layer-default)",color:"var(--seed-color-fg-neutral)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:["known"===o.kind?(0,r.jsxs)("span",{className:"subagent-role","data-role-kind":"known","data-role":o.agent,title:`${o.agent} \xb7 ${oR[o.source]}`,children:[(0,r.jsx)("span",{className:"sr-only",children:"역할 "}),o.label]}):(0,r.jsx)("span",{className:"subagent-role","data-role-kind":"unknown",title:"역할 정보가 없는 기록입니다.",children:"역할 미확인"}),(0,r.jsx)("span",{className:"subagent-task-line",style:{minWidth:0},children:s.title})]}),n?(0,r.jsx)("span",{style:{color:oM(n),fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:n.status}):i?(0,r.jsx)("span",{style:{color:"failed"===i.status?"var(--danger)":"aborted"===i.status?"var(--warning)":"var(--seed-color-fg-neutral-subtle)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:i.status??"미확인"}):(0,r.jsx)("span",{"aria-hidden":"true"}),s.stage&&(0,r.jsxs)("span",{className:"subagent-stage-line",title:`현재 단계: ${s.stage}`,style:{gridColumn:"1 / -1",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--seed-color-fg-neutral-subtle)",fontSize:"var(--seed-font-size-t2-static)"},children:[(0,r.jsx)("span",{style:{fontWeight:600},children:"현재 단계"})," \xb7 ",s.stage]}),(0,r.jsxs)("span",{className:"subagent-model-line","data-observed":d.model?d.effort?"both":"model":d.effort?"effort":"none","aria-hidden":"true",style:{gridColumn:"1 / -1"},children:[c,d.modelIsFallback&&(0,r.jsx)("span",{className:"subagent-effort",children:" (대체 모델)"}),(0,r.jsxs)("span",{className:"subagent-effort",children:[" \xb7 ",u]})]}),(0,r.jsxs)("span",{style:{gridColumn:"1 / -1",display:"flex",flexWrap:"wrap",gap:"4px 8px",minWidth:0,color:"var(--seed-color-fg-neutral-subtle)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t1-static)"},children:[(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a}),(0,r.jsx)("span",{children:l})]}),(0,r.jsxs)("span",{style:{gridColumn:"1 / -1",display:"flex",flexWrap:"wrap",gap:"4px 10px",color:"var(--seed-color-fg-neutral-subtle)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t1-static)",fontVariantNumeric:"tabular-nums"},children:[n?.progress&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{children:["도구 ",n.progress.toolCount]}),(0,r.jsxs)("span",{children:[n.progress.tokens.toLocaleString()," Token"]}),(0,r.jsx)("span",{children:function(e=0){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}초`;let n=Math.floor(t/60);return n<60?`${n}분${t%60?` ${t%60}초`:""}`:`${Math.floor(n/60)}시간 ${n%60}분`}(n.progress.durationMs)})]}),i&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:null===i.messages?"메시지 수 미확인":`메시지 ${i.messages}`}),(0,r.jsxs)("span",{children:[(i.bytes/1024).toFixed(+(i.bytes<10240))," KB"]}),(0,r.jsx)("span",{children:function(e=0){let t=Math.max(0,Date.now()-e);return t<1e4?"방금 전":t<6e4?`${Math.floor(t/1e3)}초 전`:t<36e5?`${Math.floor(t/6e4)}분 전`:t<864e5?`${Math.floor(t/36e5)}시간 전`:`${Math.floor(t/864e5)}일 전`}(i.modified)})]})]})]})}function oW({title:e,sessionId:t,sessionPath:n,sessionCwd:s,liveSubagents:a,client:l,visible:o=!0,onClose:d,onReturnFocus:c}){let u=(0,i.useMemo)(()=>l??(0,ng.Et)(),[l]),[p,h]=(0,i.useState)([]),[m,f]=(0,i.useState)({kind:"loading"}),[g,x]=(0,i.useState)({kind:"loading"}),[v,b]=(0,i.useState)(!1),[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(0);(0,i.useEffect)(()=>{h([]),f({kind:"loading"}),x({kind:"loading"}),b(!1),w(null)},[t]),(0,i.useEffect)(()=>{if(!o||!t)return;let e=!1,n=!1,r=null,i=async()=>{if(e||n||"visible"!==document.visibilityState)return;n=!0,r=new AbortController;let[i,s]=await Promise.allSettled([u.getLiveSnapshots(t,r.signal),u.getArchive(t,r.signal)]);if(!e&&!r.signal.aborted){if("fulfilled"===i.status)h(i.value.subagents),f(i.value.subagents.length>0?{kind:"ready",data:i.value.subagents}:{kind:"empty",data:[]});else{let e=(0,io.HK)(i.reason);f("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}if("fulfilled"===s.status)b(!0===s.value.listTruncated),x(s.value.subagents.length>0?{kind:"ready",data:s.value.subagents}:{kind:"empty",data:[]});else{let e=(0,io.HK)(s.reason);x("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}n=!1}};i();let s=setInterval(()=>void i(),io.P0),a=()=>{"visible"===document.visibilityState&&i()};return document.addEventListener("visibilitychange",a),()=>{e=!0,r?.abort(),clearInterval(s),document.removeEventListener("visibilitychange",a)}},[k,u,t,o]);let S=(0,i.useMemo)(()=>(function(e,t){let n=new Map,r=[];for(let i of[...e,...t]){let e=n.get(i.id);if(!e){r.push(i.id),n.set(i.id,i);continue}let[t,s]=oE(i)>=oE(e)?[i,e]:[e,i];n.set(i.id,{...t,assignment:t.assignment??s.assignment,description:t.description??s.description})}return r.flatMap(e=>{let t=n.get(e);return t?[t]:[]})})(a,p),[a,p]),C="ready"===g.kind||"empty"===g.kind?g.data:[],N=(0,i.useMemo)(()=>(0,ng.IA)(S,C),[C,S]),I=y?N.find(e=>e.key===y)??null:null;if((0,i.useEffect)(()=>{y&&!I&&w(null)},[I,y]),I&&t)return(0,r.jsx)(oA,{sessionId:t,sessionCwd:s,record:I,client:u,visible:o,onBack:()=>w(null)});let T=0===N.length&&"loading"===m.kind&&"loading"===g.kind,M=0===N.length&&("empty"===m.kind||0===a.length)&&"empty"===g.kind;return(0,r.jsxs)("section",{"aria-label":"Subagent 기록","data-state":T?"loading":M?"empty":"ready",style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minWidth:0,minHeight:0,overflow:"hidden",background:"var(--bg-panel)",color:"var(--text)"},children:[(0,r.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:750,letterSpacing:"0.08em",textTransform:"uppercase"},children:e}),(0,r.jsx)("div",{title:n??void 0,style:{marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9},children:t?.slice(0,8)||"세션 없음"})]}),(0,r.jsx)("button",{type:"button",onClick:()=>j(e=>e+1),"aria-label":"Subagent 기록 새로고침",title:"새로고침",style:oL(),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 5V2m0 0h-3m3 0-2.1 2.1A5.5 5.5 0 1 0 13.3 9"})})}),d&&(0,r.jsx)("button",{type:"button",onClick:()=>{d?.(),c?.()},"aria-label":"Subagent 기록 닫기",title:"닫기",style:oL(),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})})})]}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"9px 10px 16px"},children:[t?T?(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"Subagent 기록 불러오는 중…"}):M?(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:"이 세션은 아직 Subagent를 실행한 적이 없습니다."}):(0,r.jsx)("div",{role:"list","aria-label":"Subagent 실시간 및 디스크 기록",children:N.map(e=>(0,r.jsx)(oz,{record:e,onSelect:()=>w(e.key)},e.key))}):(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"세션을 선택한 뒤 다시 시도하세요."}),!T&&"loading"===m.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"실시간 상태 불러오는 중…"}),!T&&"loading"===g.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"디스크 기록 불러오는 중…"}),"unreachable"===m.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",fontSize:9.5},children:m.message}),"error"===m.kind&&(0,r.jsx)("div",{role:"alert",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--danger)",fontSize:9.5},children:m.message}),"unreachable"===g.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",fontSize:9.5},children:g.message}),"error"===g.kind&&(0,r.jsx)("div",{role:"alert",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--danger)",fontSize:9.5},children:g.message}),v&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--warning)",fontSize:9.5},children:"최근 디스크 기록 60개만 표시합니다."})]})]})}let oF=["process","efficiency","subagents","files","resource","sidechat"];function oP({activeView:e,onViewChange:t,viewLabels:n,sessionId:i,sessionPath:s,sessionName:o,sessionCwd:d,liveSubagents:c,subagentClient:u,processSlot:p,fileSlot:h,sideChatSlot:m,resourceSlot:f,efficiencySlot:g,visible:x=!0,onClose:v,onReturnFocus:b}){return(0,r.jsx)("aside",{className:"auxiliary-deck","aria-label":"보조 패널","data-auxiliary-view":e,children:(0,r.jsxs)(oN.J.Root,{className:"auxiliary-deck-tabs",size:"small",contentLayout:"fill",triggerLayout:"hug",value:e,onValueChange:e=>t(e),children:[(0,r.jsxs)("div",{className:"auxiliary-deck-tabbar",children:[(0,r.jsxs)(oN.J.List,{"aria-label":"보조 패널 보기",children:[oF.map(e=>{let t="subagents"===e?c.filter(e=>"pending"===e.status||"running"===e.status).length:0;return(0,r.jsxs)(oN.J.Trigger,{value:e,"aria-label":t>0?`${n[e]} (실행 중 ${t})`:void 0,children:[(0,r.jsx)("span",{className:"auxiliary-deck-tab-label",children:n[e]}),t>0&&(0,r.jsx)(oI.E,{size:"medium",variant:"weak",tone:"informative","aria-hidden":"true",children:t})]},e)}),(0,r.jsx)(oN.J.Indicator,{})]}),v&&(0,r.jsx)(a.r,{className:"auxiliary-deck-close",variant:"ghost",size:"small",layout:"iconOnly",onClick:()=>{v?.(),b?.()},"aria-label":"보조 패널 닫기",children:(0,r.jsx)(l.In,{size:"16px",svg:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})})})})]}),(0,r.jsx)(oN.J.Content,{value:"process",className:"auxiliary-deck-panel",children:p}),(0,r.jsx)(oN.J.Content,{value:"efficiency",className:"auxiliary-deck-panel",children:g}),(0,r.jsx)(oN.J.Content,{value:"subagents",className:"auxiliary-deck-panel",children:(0,r.jsx)(oW,{title:n.subagents,sessionId:i,sessionPath:s,sessionCwd:d,liveSubagents:c,client:u,visible:x&&"subagents"===e})}),(0,r.jsx)(oN.J.Content,{value:"files",className:"auxiliary-deck-panel",children:h}),(0,r.jsx)(oN.J.Content,{value:"sidechat",className:"auxiliary-deck-panel",children:m}),(0,r.jsx)(oN.J.Content,{value:"resource",className:"auxiliary-deck-panel",children:f})]})})}function oD({title:e,data:t,onOpenFile:n}){let{t:s}=(0,R.s)(),l=t?.groups??[],[o,d]=(0,i.useState)(()=>new Set);return(0,r.jsxs)("section",{className:"process-log","aria-label":e,children:[(0,r.jsxs)("header",{className:"process-log-header",children:[(0,r.jsx)("h2",{children:e}),(0,r.jsx)("span",{className:"process-log-count",children:l.length>0?`${l.length} ${s(1===l.length?"process.turn":"process.turns")}`:""})]}),(0,r.jsxs)("div",{className:"process-log-body",children:[t?.status?(0,r.jsxs)("p",{className:"process-log-status",role:"status",children:[(0,r.jsx)("span",{className:"process-log-status-pulse","aria-hidden":"true"}),t.status]}):null,0===l.length?(0,r.jsx)("p",{className:"process-log-empty",children:s("process.empty")}):l.map((e,i)=>{let l=o.has(e.anchorIdx),c=function(e){if(!e||"user"!==e.role)return null;let t=("string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join(" ")).replace(/\s+/g," ").trim();return 0===t.length?null:t.length>72?`${t.slice(0,72)}…`:t}(t?.messages[e.anchorIdx]),u=[`${e.messageCount} ${s(1===e.messageCount?"chat.message":"chat.messages")}`];return e.toolCallCount>0&&u.push(`${e.toolCallCount} ${s(1===e.toolCallCount?"chat.toolCall":"chat.toolCalls")}`),(0,r.jsxs)("article",{className:"process-log-turn","data-process-turn":e.anchorIdx,children:[(0,r.jsxs)(a.r,{className:"process-log-turn-toggle",variant:"ghost",size:"small",layout:"withText","aria-expanded":!l,onClick:()=>d(t=>{let n=new Set(t);return n.has(e.anchorIdx)?n.delete(e.anchorIdx):n.add(e.anchorIdx),n}),title:l?s("chat.expandProcess"):s("chat.collapseProcess"),children:[(0,r.jsx)("span",{className:"process-log-turn-title",children:c??s("chat.processDetails")}),(0,r.jsx)("span",{className:"process-log-turn-meta",children:u.join(" \xb7 ")})]}),!l&&(0,r.jsx)("div",{className:"process-log-entries",children:e.entries.map((i,s)=>{let a=t?.messages[i.idx];return a?(0,r.jsx)(rn,{message:i.blocks?eM(a,i.blocks,{omitUsage:!0}):a,toolResults:t?.toolResults,modelNames:t?.modelNames,cwd:t?.cwd,onOpenFile:n,entryId:t?.entryIds[i.idx],sessionId:t?.sessionId,showTimestamp:!1},`process-${e.anchorIdx}-${s}`):null})})]},`turn-${e.anchorIdx}-${i}`)})]})]})}let o_=6,oO="omp-btw-log:",oH="omp-btw-log-index";function oB(e){return e.trim().toLowerCase()}function oU(e){return e.map(e=>({q:e.q,a:e.a,at:e.at}))}function oq(e){if(!Array.isArray(e))return[];let t=[],n=0;for(let r of e){if(!r||"object"!=typeof r||"string"!=typeof r.q||"string"!=typeof r.a)continue;let e={q:r.q,a:r.a,at:"number"==typeof r.at&&Number.isFinite(r.at)?r.at:0};t.push(e),n+=e.q.length+e.a.length}for(;t.length>40||n>12e4;){let e=t.shift();if(!e)break;n-=e.q.length+e.a.length}return t}function oV(e){return!!e&&"object"==typeof e&&("QuotaExceededError"===e.name||22===e.code||1014===e.code)}function oK(e,t={}){let n=t.now??Date.now,r=new Map,i=new Set,s=!1,a=[],l=t=>{if(e)try{e.removeItem(t)}catch{}},o=e=>{r.delete(e),i.delete(e),l(oO+e)},d=()=>{let e=new Set,t=[];for(let n of(a.sort((e,t)=>t.updatedAt-e.updatedAt),a))!n.id||e.has(n.id)||(e.add(n.id),t.length<20?t.push(n):o(n.id));a=t},c=()=>{if(!s){if(s=!0,e)try{let t=e.getItem(oH),n=t?JSON.parse(t):[];Array.isArray(n)&&(a=n.flatMap(e=>e&&"object"==typeof e&&"string"==typeof e.id&&e.id?[{id:oB(e.id),updatedAt:"number"==typeof e.updatedAt&&Number.isFinite(e.updatedAt)?e.updatedAt:0}]:[]))}catch{a=[]}d()}},u=e=>{c();for(let t=a.length-1;t>=0;t-=1){if(a[t].id===e)continue;let[n]=a.splice(t,1);return o(n.id),!0}return!1},p=t=>{if(e){try{e.setItem(oH,JSON.stringify(a));return}catch(e){if(!oV(e)||!u(t))return}try{e.setItem(oH,JSON.stringify(a))}catch{}}},h=t=>{let n=oB(t);if(!n)return[];if(i.has(n))return oU(r.get(n)??[]);if(e)try{let t=e.getItem(oO+n);if(t){let e=JSON.parse(t),i=oq(e?.entries);return r.set(n,i),oU(i)}}catch{}return oU(r.get(n)??[])},m=e=>{let t=oB(e);t&&(c(),a=a.filter(e=>e.id!==t),o(t),p(null))};return{read:h,append:(t,s)=>((t,s)=>{let l=oB(t);if(!l)return[];let o=oq(s),h=n();if(r.set(l,oU(o)),c(),(a=a.filter(e=>e.id!==l)).unshift({id:l,updatedAt:h}),d(),p(l),!e)return oU(o);let m=JSON.stringify({updatedAt:h,entries:o});try{return e.setItem(oO+l,m),i.delete(l),oU(o)}catch(e){if(!oV(e)||!u(l))return i.add(l),oU(o)}p(l);try{e.setItem(oO+l,m),i.delete(l)}catch{i.add(l)}return oU(o)})(t,[...h(t),s]),history:(e,t=o_)=>h(e).slice(-Math.max(0,t)).map(({q:e,a:t})=>({q:e,a:t})),clear:m,cleanup:(t,r)=>{if(!t.complete)return;c();let i=new Map;for(let e of t.sessions){if(!e||"string"!=typeof e.id||!e.id)continue;let t=oB(e.id),n="number"==typeof e.modified?e.modified:Date.parse(e.modified);i.set(t,Number.isFinite(n)?n:0)}let s=r?oB(r):null,o=n();for(let e of[...a])if(e.id!==s){if(!i.has(e.id)){m(e.id);continue}o-Math.max(i.get(e.id)??0,e.updatedAt)>6048e5&&m(e.id)}if(!e||"function"!=typeof e.key||"number"!=typeof e.length)return;let d=[];try{for(let t=0;t<e.length;t+=1){let n=e.key(t);if(!n?.startsWith(oO))continue;let r=oB(n.slice(oO.length));i.has(r)||r===s||d.push(n)}}catch{return}for(let e of d)l(e)}}}function oJ(){let e=new Map,t=new Map,n=new Map,r=e=>{n.get(e)?.forEach(e=>{e()})};return{read(t){let n=e.get(t);return n?{...n.snapshot}:null},begin(t,n){if(e.has(t))return null;let i=new AbortController;return e.set(t,{snapshot:{sessionId:t,question:n,text:"",model:null},controller:i}),r(t),{controller:i}},ingest(t,n){let i=e.get(t);i&&("d"===n.t?i.snapshot.text+=n.v:"done"===n.t?i.snapshot.text=n.v||i.snapshot.text:"m"===n.t&&(i.snapshot.model=n.v),r(t))},abort(t){let n=e.get(t);return!!n&&(n.controller.abort(),!0)},finish(n,i){e.has(n)&&(e.delete(n),t.set(n,i),r(n))},takeOutcome(e){let n=t.get(e)??null;return n&&t.delete(e),n},subscribe(e,t){let r=n.get(e);return r||(r=new Set,n.set(e,r)),r.add(t),()=>{r.delete(t),0===r.size&&n.delete(e)}}}}class oG extends Error{constructor(e,t,n){super(t),this.kind=e,this.status=n,this.name="SideChatRequestError"}}function oY(e){let t;try{t=JSON.parse(e)}catch{throw new oG("stream","사이드채팅 스트림을 해석할 수 없습니다.")}if(!t||"object"!=typeof t)throw new oG("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");let n=t;if("d"!==n.t&&"done"!==n.t&&"m"!==n.t&&"err"!==n.t||"string"!=typeof n.v)throw new oG("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");return{t:n.t,v:n.v}}class oZ{push(e){this.buffer+="string"==typeof e?e:this.decoder.decode(e,{stream:!0});let t=this.buffer.split("\n");return this.buffer=t.pop()??"",t.flatMap(e=>e.trim()?[oY(e)]:[])}finish(){this.buffer+=this.decoder.decode();let e=this.buffer.trim();return this.buffer="",e?[oY(e)]:[]}constructor(){this.decoder=new TextDecoder,this.buffer=""}}async function oX(e){let t=await e.text().catch(()=>"");if(!t)return`HTTP ${e.status}`;try{let e=JSON.parse(t);if("string"==typeof e.error&&e.error)return e.error}catch{}return t}function oQ(e=!1){return{minHeight:30,padding:"4px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:e?"var(--text-dim)":"var(--text-muted)",cursor:e?"default":"pointer",fontSize:"var(--seed-font-size-t2-static)",fontWeight:650}}function o0({children:e}){return(0,r.jsx)("div",{className:"side-chat-question",style:{alignSelf:"flex-end",maxWidth:"92%",padding:"8px 10px",border:"1px solid var(--border)",color:"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55},children:e})}function o1({children:e,streaming:t=!1}){return(0,r.jsxs)("div",{className:`side-chat-answer${t?" is-streaming":""}`,style:{alignSelf:"flex-start",maxWidth:"100%",padding:"8px 10px",border:"1px solid var(--border)",color:"var(--text)",overflowWrap:"anywhere",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.58},children:[e?(0,r.jsx)(tD,{isStreaming:t,children:e}):t?"응답을 기다리는 중…":null,t&&(0,r.jsx)("span",{"aria-hidden":"true",style:{marginLeft:2,color:"var(--accent)"},children:"▍"})]})}function o2({identity:e,status:t,utteranceKey:n,children:i}){let s=ne(e?.sessionId,e?.provider,e?.credentialId),a=r8(s?.alias,t,n);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:5},children:[s&&e?.provider&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:9,minHeight:40,marginBottom:2},children:[(0,r.jsx)(ni,{seed:s.seed,size:40,provider:e.provider}),(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:s.alias})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:7,minWidth:0,maxWidth:"100%"},children:[i,a&&(0,r.jsx)("img",{src:a.src,alt:a.alt,width:52,height:52,style:{flex:"0 0 auto",objectFit:"contain"}})]})]})}function o4({title:e,sessionId:t,sessionPath:n,sessionName:s,historyStore:a,flights:l,sessionCensus:o,client:d,visible:c=!0,onClose:u,onReturnFocus:p}){let h,m,f=(0,i.useMemo)(()=>d??function(e=(e,t)=>fetch(e,t),t="/api/sidecars/sidechat/ask"){return{async ask(n){let r;try{r=await e(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionPath:n.sessionPath,question:n.question,history:n.history.slice(-o_)}),signal:n.signal})}catch(e){if(n.signal?.aborted)throw e;throw new oG("unreachable","사이드채팅 사이드카(30143)에 연결할 수 없습니다.")}if(!r.ok)throw new oG("http",await oX(r),r.status);if(!r.body)throw new oG("stream","사이드채팅 스트림을 열 수 없습니다.");let i=r.body.getReader(),s=new oZ,a="",l=null,o=e=>{for(let t of e)if(n.onEvent?.(t),"d"===t.t)a+=t.v;else if("done"===t.t)a=t.v||a;else if("m"===t.t)l=t.v;else throw new oG("server",t.v)};try{for(;;){let e=await i.read();if(e.done)break;o(s.push(e.value))}o(s.finish())}catch(e){if(n.signal?.aborted||e instanceof oG)throw e;throw new oG("stream",e instanceof Error?e.message:"사이드채팅 스트림이 중단되었습니다.")}finally{i.releaseLock()}if(!a)throw new oG("empty","사이드채팅이 빈 응답을 반환했습니다.");return{text:a,model:l}}}}(),[d]),g=t?.toLowerCase()??null,[x,v]=(0,i.useState)([]),[b,y]=(0,i.useState)({}),w=g??"",k=b[w]??"",j=(e,t)=>{y(n=>{if((n[e]??"")===t)return n;let r={...n};return t?r[e]=t:delete r[e],r})},[S,C]=(0,i.useState)(0),[N,I]=(0,i.useState)({}),[T,M]=(0,i.useState)({}),[$,R]=(0,i.useState)({}),[E,L]=(0,i.useState)(null),[A,z]=(0,i.useState)(null),[W,F]=(0,i.useState)({}),[P,D]=(0,i.useState)({}),[_,O]=(0,i.useState)({}),H=(0,i.useRef)((h=new Set,m=new Set,{claim:e=>!(!e||h.has(e)||m.has(e))&&(h.add(e),!0),markSent(e){h.delete(e),m.add(e)},release(e){h.delete(e)}})),B=(0,i.useRef)(!0),U=(0,i.useRef)(g),q=(0,i.useRef)(c),V=(0,i.useRef)(null),K=(0,i.useRef)(!1),J=(0,i.useRef)(0),G=(0,i.useRef)(null);U.current=g,q.current=c,(0,i.useEffect)(()=>(B.current=!0,()=>{B.current=!1}),[]),(0,i.useEffect)(()=>{v(g?a.read(g):[])},[a,g]),(0,i.useEffect)(()=>{if(L(null),!g)return;let e=!0;return fetch(`/api/sessions/${encodeURIComponent(g)}?deferThinking=1&deferMedia=1`,{cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return function(e){if(!e||"object"!=typeof e||!("context"in e))return null;let t=e.context;if(!t||"object"!=typeof t||!("messages"in t))return null;let n=t.messages;if(!Array.isArray(n))return null;for(let e=n.length-1;e>=0;e-=1){let t=n[e];if(!t||"object"!=typeof t||!("role"in t)||"assistant"!==t.role)continue;if(!("provider"in t)||"string"!=typeof t.provider||!t.provider)break;let r="credentialId"in t?t.credentialId:void 0;return{provider:t.provider,..."number"==typeof r&&Number.isSafeInteger(r)&&r>0?{credentialId:r}:{}}}return null}(await e.json())}).then(t=>{e&&L(t?{...t,sessionId:g}:null)}).catch(()=>{e&&L(null)}),()=>{e=!1}},[g]),(0,i.useEffect)(()=>{if(!g)return;let e=()=>{if(!B.current||U.current!==g)return;let e=l.takeOutcome(g);if(e){if("aborted"===e.kind)M(t=>({...t,[g]:e.saved?"응답 생성을 중단했습니다. 받은 내용은 현재 세션 기록에 저장했습니다.":"응답 생성을 중단했습니다."}));else if("failed"===e.kind)I(t=>({...t,[g]:[...t[g]??[],{question:e.question,partialAnswer:e.partialAnswer,kind:e.errorKind,message:e.errorMessage}]})),y(t=>(t[g]??"").trim()?t:{...t,[g]:e.question});else if(e.model){let t=e.model;R(e=>({...e,[g]:t}))}v(a.read(g))}else null===l.read(g)&&v(a.read(g));C(e=>e+1)},t=l.subscribe(g,e);return e(),t},[l,a,g]),(0,i.useEffect)(()=>{o&&a.cleanup(o,g)},[a,g,o]),(0,i.useEffect)(()=>{c&&V.current?.focus()},[c,g]),(0,i.useEffect)(()=>{if(!c)return;let e=requestAnimationFrame(()=>{let e=G.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[S,g,x.length,c]);let Y=async e=>{if(!g||!n){let e=g??"";M(t=>({...t,[e]:"세션 파일이 준비되지 않았습니다. 기록이 생성된 뒤 다시 시도하세요."}));return}let t=l.begin(g,e);if(!t)return;let{signal:r}=t.controller;M(e=>{let t={...e};return delete t[g],t});try{let t=await f.ask({sessionPath:n,question:e,history:a.history(g),signal:r,onEvent:e=>l.ingest(g,e)});a.append(g,{q:e,a:t.text,at:Date.now()}),l.finish(g,{kind:"done",model:t.model})}catch(n){let t=l.read(g)?.text??"";if(r.aborted){let n=!1;t&&(a.append(g,{q:e,a:t,at:Date.now()}),n=!0),l.finish(g,{kind:"aborted",saved:n})}else{let r=n instanceof oG?n.kind:"unknown",i=n instanceof Error?n.message:String(n);l.finish(g,{kind:"failed",question:e,partialAnswer:t,errorKind:r,errorMessage:i})}}finally{B.current&&q.current&&V.current?.focus()}},Z=async(e,t,n)=>{if(!g)return;let r=`${g}:${t}`;if(H.current.claim(r)){D(e=>({...e,[r]:"sending"})),O(e=>{let t={...e};return delete t[r],t});try{var i,s;let t,a=await fetch(`/api/agent/${encodeURIComponent(g)}`,{cache:"no-store"}),l=null;try{l=await a.json()}catch{}if(!a.ok){if(l&&"object"==typeof l&&"error"in l&&"string"==typeof l.error)throw Error(l.error);throw Error(`HTTP ${a.status}`)}let o=function(e){if(!e||"object"!=typeof e||!("running"in e)||"boolean"!=typeof e.running)return null;if(!e.running)return!1;if(!("state"in e)||!e.state||"object"!=typeof e.state)return null;let t=e.state;return"isStreaming"in t&&"boolean"==typeof t.isStreaming&&"isPromptRunning"in t&&"boolean"==typeof t.isPromptRunning&&"isBashRunning"in t&&"boolean"==typeof t.isBashRunning&&"isCompacting"in t&&"boolean"==typeof t.isCompacting&&"isHandoffRunning"in t&&"boolean"==typeof t.isHandoffRunning?t.isStreaming||t.isPromptRunning||t.isBashRunning||t.isCompacting||t.isHandoffRunning:null}(l);if(null===o)throw Error("메인 세션 실행 상태를 확인할 수 없습니다.");let d=(i=e.q,s=e.a,t=n.trim(),["사이드채팅 문답을 메인 대화에서 이어서 처리해 주세요.","","[사이드채팅 질문]",i,"","[사이드채팅 답변]",s,...t?["","[추가 지시]",t]:[]].join("\n"));await sR(g,{type:o?"steer":"prompt",message:d}),H.current.markSent(r),D(e=>({...e,[r]:"sent"}))}catch(e){H.current.release(r),D(e=>{let t={...e};return delete t[r],t}),O(t=>({...t,[r]:e instanceof Error?e.message:String(e)}))}}},X=()=>{if(g&&null!==l.read(g))return void l.abort(g);let e=k.trim();e&&(j(w,""),Y(e))},Q=N[g??""]??[],ee=T[g??""],et=g?l.read(g):null,en=x.length>0||Q.length>0||null!==et,er=et?.model??$[g??""],ei=!g||!n,es=null!==et,ea=!es&&!ei&&k.trim().length>0,el=!g||es,eo=E?.sessionId===g?E:null;return(0,r.jsxs)("section",{className:"side-chat-panel","aria-label":"사이드채팅","aria-busy":null!==et,"data-state":g&&n?et?"streaming":"ready":"unavailable",style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minWidth:0,minHeight:0,overflow:"hidden",background:"var(--bg-panel)",color:"var(--text)"},children:[(0,r.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:e}),(0,r.jsxs)("div",{title:n??void 0,style:{marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)"},children:[s||g?.slice(0,8)||"세션 없음",er?` \xb7 ${er}`:""]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>{g&&null===l.read(g)&&(a.clear(g),v([]),I(e=>{let t={...e};return delete t[g],t}),M(e=>({...e,[g]:"현재 세션의 사이드채팅 기록을 비웠습니다."})))},disabled:el,style:oQ(el),children:"Clear"}),u&&(0,r.jsx)("button",{type:"button",onClick:()=>{u?.(),p?.()},"aria-label":"사이드채팅 닫기",title:"닫기",style:{...oQ(),width:32,padding:0},children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})})})]}),(0,r.jsxs)("div",{ref:G,"aria-live":"polite",style:{display:"flex",flex:1,minHeight:0,flexDirection:"column",gap:7,overflowY:"auto",padding:"11px 12px 18px"},children:[g&&n?(0,r.jsxs)(r.Fragment,{children:[x.map((e,t)=>{let n=`${e.at}:${t}`,i=`${g}:${n}`,s=P[i],a=A===i;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(o0,{children:e.q}),(0,r.jsx)(o2,{identity:eo,status:"settled",utteranceKey:n,children:(0,r.jsx)(o1,{children:e.a})}),"sent"===s?(0,r.jsx)("span",{role:"status",style:{color:"var(--text-muted)",fontSize:10.5},children:"보냄"}):(0,r.jsxs)(r.Fragment,{children:[!a&&(0,r.jsx)("button",{type:"button","aria-expanded":"false",onClick:()=>z(i),style:{...oQ(),alignSelf:"flex-start"},children:"메인에 보내기"}),a&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:6},children:[(0,r.jsx)("label",{htmlFor:`side-chat-forward-${t}`,style:{color:"var(--text-muted)",fontSize:10.5},children:"메인에 덧붙일 지시 (선택)"}),(0,r.jsx)("textarea",{id:`side-chat-forward-${t}`,rows:2,value:W[i]??"",onChange:e=>F(t=>({...t,[i]:e.target.value})),style:{width:"100%",minWidth:0,boxSizing:"border-box",resize:"vertical",padding:"7px 8px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void Z(e,n,W[i]??""),disabled:"sending"===s,style:oQ("sending"===s),children:"sending"===s?"보내는 중…":"메인으로 전송"}),"sending"!==s&&(0,r.jsx)("button",{type:"button",onClick:()=>z(null),style:oQ(),children:"취소"})]})]}),_[i]&&(0,r.jsx)("div",{role:"alert",style:{color:"var(--danger)",fontSize:10.5,lineHeight:1.5,overflowWrap:"anywhere"},children:_[i]})]})]},n)}),Q.map((e,t)=>(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(o0,{children:e.question}),(0,r.jsxs)(o2,{identity:eo,status:"failed",utteranceKey:`failed:${e.question}:${t}`,children:[e.partialAnswer&&(0,r.jsx)(o1,{children:e.partialAnswer}),(0,r.jsx)("div",{role:"alert","data-error-kind":e.kind,style:{padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--danger)",fontSize:10.5,lineHeight:1.5,overflowWrap:"anywhere"},children:e.message})]})]},`${e.question}:${t}`)),et&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(o0,{children:et.question}),(0,r.jsx)(o2,{identity:eo,status:"streaming",utteranceKey:`stream:${et.question}`,children:(0,r.jsx)(o1,{streaming:!0,children:et.text})})]}),!en&&(0,r.jsxs)("div",{style:{margin:"auto 0",padding:16,color:"var(--text-muted)",textAlign:"center",fontSize:11,lineHeight:1.65},children:["현재 세션의 전체 맥락을 보고 답합니다.",(0,r.jsx)("br",{}),"사이드채팅 기록은 부모 세션별로 보관됩니다."]})]}):(0,r.jsxs)("div",{role:"status",style:{margin:"auto 0",padding:16,color:"var(--text-muted)",textAlign:"center",fontSize:11,lineHeight:1.6},children:["세션 기록을 준비하는 중입니다.",(0,r.jsx)("br",{}),"세션 파일이 생성되면 사이드채팅을 사용할 수 있습니다."]}),ee&&(0,r.jsx)("div",{role:"status",style:{padding:"7px 9px",color:"var(--text-muted)",fontSize:10.5,lineHeight:1.5},children:ee})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault(),X()},style:{display:"flex",flexDirection:"column",gap:6,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("label",{htmlFor:"side-chat-question",style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:"사이드채팅 질문"}),(0,r.jsx)("textarea",{ref:V,id:"side-chat-question",rows:4,value:k,onChange:e=>j(w,e.target.value),onCompositionStart:()=>{K.current=!0},onCompositionEnd:()=>{K.current=!1,J.current=Date.now()},onKeyDown:e=>{if("Enter"!==e.key||e.shiftKey)return;let t=e.nativeEvent,n=Date.now()-J.current<100;if(K.current||t.isComposing||229===t.keyCode||n){n&&e.preventDefault();return}es||(e.preventDefault(),X())},disabled:es||ei,placeholder:"질문 입력 — Enter 전송, Shift+Enter 줄바꿈",style:{width:"100%",minWidth:0,minHeight:88,maxHeight:240,boxSizing:"border-box",resize:"vertical",padding:"8px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{"aria-live":"polite",style:{flex:1,minWidth:0,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.4,overflowWrap:"anywhere"},children:ei?"세션 파일이 준비되면 질문할 수 있습니다.":es?"응답을 받는 중입니다.":"Enter 전송 \xb7 Shift+Enter 줄바꿈"}),(0,r.jsx)("button",{type:"submit",disabled:!es&&!ea,style:oQ(!es&&!ea),children:es?"중단":"전송"})]})]})]})}function o5(e){let[t,n]=(0,i.useState)(()=>Date.now());return(0,i.useEffect)(()=>{let t=setInterval(()=>n(Date.now()),e);return()=>clearInterval(t)},[e]),t}let o8="min-h-9 border border-border bg-bg px-3 text-xs font-medium text-text transition-colors hover:bg-bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-not-allowed disabled:opacity-50";function o6(...e){return e.filter(Boolean).join(" ")}function o3(e,t){let n=Math.floor((e-t)/6e4);if(n<=0)return"리셋됨";let r=Math.floor(n/1440),i=Math.floor(n%1440/60),s=n%60;return r>0?`${r}d ${i}h 후 리셋`:i>0?`${i}h ${s}m 후 리셋`:`${s}m 후 리셋`}function o7(e,t){if(!e)return null;let n=Date.parse(e);if(!Number.isFinite(n))return null;let r=Math.floor((n-t)/6e4);if(r<=0)return"만료됨";let i=Math.floor(r/1440),s=Math.floor(r%1440/60),a=r%60;return i>0?`${i}d ${s}h 후 만료`:s>0?`${s}h ${a}m 후 만료`:`${a}m 후 만료`}function o9(e){return"number"==typeof e&&Number.isFinite(e)?0===e?"$0":e>=100?`$${e.toFixed(0)}`:e>=1?`$${e.toFixed(2)}`:e>=.01?`$${e.toFixed(3)}`:`$${e.toFixed(4)}`:"—"}function de(e){return"number"==typeof e&&Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"—"}function dt(e){return"number"==typeof e&&Number.isFinite(e)?e>=1e9?`${(e/1e9).toFixed(1)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(Math.round(e)):"—"}function dn(e,t=0){return"number"==typeof e&&Number.isFinite(e)?`${(100*e).toFixed(t)}%`:"—"}function dr(e){return"number"==typeof e&&Number.isFinite(e)?`${(e/1e3).toFixed(1)}s`:"—"}function di(e){let t=new Date(e);return`${t.getMonth()+1}/${t.getDate()}`}function ds({label:e,value:t}){return(0,r.jsxs)("div",{className:"flex min-w-0 items-baseline justify-between gap-3 border-b border-border py-1.5 last:border-b-0",children:[(0,r.jsx)("dt",{className:"text-xs text-text-muted",children:e}),(0,r.jsx)("dd",{className:"m-0 font-mono text-xs tabular-nums text-text",children:t})]})}function da({state:e,loading:t,subject:n}){return t&&"idle"===e.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:[n," 불러오는 중…"]}):"error"===e.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsxs)("div",{className:"font-medium",children:[n,"을 불러오지 못했습니다."]}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:e.error.message}),(0,r.jsx)("div",{className:"mt-2 text-xs text-text-dim",children:"사이드카(127.0.0.1:30142)가 실행 중인지 확인하세요."})]}):"stale"===e.status?(0,r.jsxs)("div",{className:"border-b border-border bg-bg px-4 py-2 text-xs text-text-muted",role:"status",children:["마지막 데이터를 표시합니다. 새로고침 실패: ",e.error.message]}):null}function dl(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0");return`${t.getMonth()+1}/${t.getDate()} ${n}:${r}`}function dd({limit:e,now:t,detailed:n}){let i="number"==typeof e.amount?.usedFraction?e.amount.usedFraction:0,s=Math.max(0,Math.min(100,100*i)),a=Math.round(100*i),l=function(e,t){let n=e.window,r=e.amount?.usedFraction;if(!n?.resetsAt||"number"!=typeof r)return null;let i=Math.max(0,n.resetsAt-t),s=100*r,a=Math.max(0,100-s);if(!n.durationMs){let e=i/864e5;return{burnOnly:!0,unit:"하루",partial:e<1,burn:e>=1?a/e:a}}let l=Math.min(n.durationMs,Math.max(0,n.durationMs-i)),o=n.durationMs>432e5,d=o?864e5:36e5,c=n.durationMs/d,u=i/d,p=l/n.durationMs*100;return{burnOnly:!1,unit:o?"하루":"시간",partial:u<1,burn:u>=1?a/u:a,pacePct:p,deltaPct:s-p,nominal:100/c}}(e,t),o=e.daySlot,d=o?.usedPct==null||null==o.baselinePct?null:Math.max(0,Math.min(o.baselinePct,100)),c=null==d?null:Math.max(d,Math.min(100*i,100)),u=l?.pacePct==null?null:Math.min(l.pacePct,99.6),p=a>=90,h=l?.deltaPct!=null&&l.deltaPct>=.5?l.deltaPct:null,m=o?"unknown"===o.quality||null==o.usedPct?"구간 사용 — 기록 부족":"approx"===o.quality?`구간 사용 ≈${o.usedPct.toFixed(0)}% \xb7 추정`:`구간 사용 ${o.usedPct.toFixed(1)}%`:null;return(0,r.jsxs)("div",{className:"usage-limit py-2",children:[(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-2",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate text-[13px] text-text-muted",children:e.label||e.id}),i>=1?(0,r.jsx)("span",{className:"usage-chip","data-tone":"danger",children:i>1?"한도 초과":"한도 도달"}):null,null!=h?(0,r.jsx)("span",{className:"usage-chip","data-tone":"warning",children:`과속 +${h.toFixed(1)}%`}):null,(0,r.jsxs)("span",{className:o6("shrink-0 font-mono text-sm font-semibold tabular-nums",p?"text-danger":"text-text"),children:[a,"%"]})]}),(0,r.jsxs)("div",{className:"relative mt-1 h-3.5 overflow-hidden border border-border-strong bg-metric-track",role:"progressbar","aria-label":`${e.label||e.id} 사용량`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":a,children:[(0,r.jsx)("div",{className:o6("absolute inset-y-0 left-0",p?"bg-danger":"bg-metric"),style:{width:`${s}%`}}),null!=d&&null!=c&&c>d?(0,r.jsx)("div",{className:"absolute inset-y-0 bg-metric-recent",style:{left:`${d}%`,width:`${c-d}%`,boxShadow:"inset 1px 0 var(--bg-panel)"}}):null,null!=u?(0,r.jsx)("div",{className:"absolute inset-y-0 w-0.5 bg-text",style:{left:`${u}%`,boxShadow:"0 0 0 1px color-mix(in srgb, var(--bg-panel) 80%, transparent)"},"aria-hidden":"true"}):null,i>1?(0,r.jsx)("div",{className:"absolute inset-y-0 right-0 w-1 bg-danger","aria-hidden":"true"}):null]}),m||e.window?.resetsAt?(0,r.jsxs)("div",{className:"mt-1 flex items-baseline justify-between gap-3 font-mono text-[11px] tabular-nums text-text-muted",children:[(0,r.jsx)("span",{className:"min-w-0 truncate",children:m??""}),e.window?.resetsAt?(0,r.jsx)("span",{className:"shrink-0",children:o3(e.window.resetsAt,t)}):null]}):null,n?(0,r.jsxs)("dl",{className:"m-0 mt-1.5 border-s-2 border-border ps-2.5",children:[l?.pacePct!=null?(0,r.jsx)(ds,{label:"페이스",value:`${l.pacePct.toFixed(1)}%`}):null,l?(0,r.jsx)(ds,{label:l.partial?"남은 한도":`앞으로 ${l.unit}`,value:`${l.burn.toFixed(1)}%`}):null,l?.nominal!=null?(0,r.jsx)(ds,{label:"균등 배분 기준",value:`${l.nominal.toFixed(1)}%/${"하루"===l.unit?"일":"시간"} \xb7 계산값`}):null,o?(0,r.jsx)(ds,{label:"구간",value:`${dl(o.slotStart)} ~ ${dl(o.slotEnd)} \xb7 ${o.slotIndex+1}/${o.slotCount}`}):null,o?(0,r.jsx)(ds,{label:"기록 품질",value:function(e){let t;if("unknown"===e.quality)return"기록 부족 \xb7 구간 시작 전 표본이 없습니다";let n=null==e.gapMs||0===e.gapMs?null:(t=Math.round(e.gapMs/6e4))<60?`${t}분`:`${Math.floor(t/60)}시간 ${t%60}분`;return"exact"===e.quality?n?`실측 \xb7 경계 ${n} 전 표본`:"실측 \xb7 구간 시작이 창의 시작":`추정 \xb7 경계 ${n??"?"} 전 표본`}(o)}):null]}):null]})}let dc={"anthropic:5h":"5시간","anthropic:7d":"주간","anthropic:7d:opus":"주간","anthropic:7d:sonnet":"주간"};function du({confirmId:e,pending:t,primaryRef:n,summary:i,onConfirm:s,onCancel:a}){return(0,r.jsxs)("div",{className:"resource-reset resource-reset-confirm-group","data-reset-state":t?"pending":"confirming","data-dismissible-layer":!0,role:"group","aria-label":"리셋 사용 확인",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),a())},children:[(0,r.jsxs)("p",{className:"m-0 text-xs leading-5 text-text-muted",children:["저장된 리셋 ",i]}),(0,r.jsx)("p",{id:e,className:"m-0 text-xs leading-5 text-text",children:"리셋 1개를 지금 사용합니다. 되돌릴 수 없습니다."}),(0,r.jsx)("p",{className:"m-0 mt-1 text-xs leading-5 text-text-muted",children:"이 계정의 차단 기록도 함께 지워집니다."}),(0,r.jsxs)("div",{className:"mt-2 flex flex-wrap justify-end gap-2",children:[(0,r.jsx)("button",{ref:n,type:"button",className:o6(o8,"resource-reset-confirm"),"aria-describedby":e,disabled:t,onClick:s,children:t?"사용 중…":"리셋 사용"}),(0,r.jsx)("button",{type:"button",className:o8,disabled:t,onClick:a,children:"취소"})]})]})}function dp({report:e,brokerOk:t,now:n,active:s,identity:a,recommendation:l,pendingAction:o,feedback:d,onToggle:c,onReset:u}){let p=e.metadata??{},h=a??(0,tX.k)([e])[0],m=e.credentialId,f=Number.isSafeInteger(m)&&m>0,g=e.accountRole,x="usage-only"===g?"사용량":"control-only"===g?"계정 제어":p.planType,v=!0!==e.disabled&&"number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>n,b=s?"active":e.disabled?"off":v?"auto-blocked":"idle",y="toggle"===o?"전환 중…":"reset"===o?"리셋 사용 중…":f?s?"현재 사용 \xb7 이 세션":e.disabled?"꺼둠":v?`자동 차단 \xb7 ${o3(e.autoBlockedUntilMs,n)}`:"control-only"===g?"로그인 계정 \xb7 ON/OFF 제어":"대기":"usage-only"===g?"할당량 정보 \xb7 계정 연결 없음":"제어 불가 \xb7 credential id 없음",w=(0,i.useId)(),k=(0,i.useId)(),[j,S]=(0,i.useState)(!1),[C,N]=(0,i.useState)(!1),[I,T]=(0,i.useState)(null),M=(0,i.useRef)(null),$=(0,i.useRef)(null),R=(0,i.useRef)(!1),E=(0,i.useRef)(!1),L="openai-codex"===e.provider||"anthropic"===e.provider?e.savedReset:void 0,A=function(e){let t=e.savedReset?.credits??[],n=null;for(let e of t){if(!e.id)continue;let t=e.expiresAt?Date.parse(e.expiresAt):NaN,r=Number.isFinite(t)?t:null;(!n||null!=r&&(null==n.timestamp||r<n.timestamp))&&(n={id:e.id,expiresAt:e.expiresAt,timestamp:r})}return n?{id:n.id,expiresAt:n.expiresAt}:null}(e),z=A?.id??null,W=o7(A?.expiresAt??null,n),F=L?.availableCount,P=L&&"unavailable"!==L.state?"empty"===L.state||0===F?"없음":`${F??L.credits.length}개${W?` \xb7 ${W}`:""}`:"확인 불가",D=function(e){if("anthropic"!==e.provider)return null;let t=e.savedReset,n=t?.credits.find(e=>e.id===t.nextCreditId)??t?.credits[0],r=[...new Set((n?.clears??[]).map(e=>dc[e]).filter(e=>void 0!==e))];return r.length?`${r.join("\xb7")} 한도만`:null}(e),_=function(e,t){if(!e)return null;if("blocked-account"===e.reason){if(e.scope)return`권고 — ${e.scope}가 소진됐습니다. 저장된 리셋권 사용을 검토하세요.`;let n="number"==typeof e.naturalResetAt?o3(e.naturalResetAt,t).replace(/ 후 리셋$/,""):null;return n?`권고 — 지금 쓸 수 있는 다른 계정이 없고 자연 리셋까지 ${n} 남았습니다.`:"권고 — 지금 쓸 수 있는 다른 계정이 없어 저장된 리셋 사용을 검토하세요."}let n=o7(e.expiresAt??null,t),r="number"==typeof e.usedFraction?` 현재 ${Math.round(100*e.usedFraction)}% 소모한 ${"weekly"===e.window?"주간":"5시간"} 한도를 초기화할 수 있습니다.`:"";return`권고 — 리셋 1개가 ${n&&"만료됨"!==n?n:"곧 만료"}됩니다.${r}`}(l,n),O=("openai-codex"===e.provider||"anthropic"===e.provider)&&t&&!0!==e.disabled&&L?.state==="available"&&0!==F&&null!=z;(0,i.useLayoutEffect)(()=>{if(I)return void $.current?.focus();if(R.current){var e;R.current=!1,e=M.current,e?.focus()}},[I]),(0,i.useEffect)(()=>{"reset"!==o&&(e.disabled||!t||L?.state!=="available")&&(R.current=!1,T(null))},[t,o,e.disabled,L?.state]);let H=async()=>{if(I&&!E.current){E.current=!0;try{await u(e,I.creditId)}finally{E.current=!1,R.current=!0,T(null)}}},B=(e.limits??[]).reduce((e,t)=>{let r=t.window?.resetsAt;return"number"!=typeof r||r<=n?e:null==e||r<e?r:e},null),U=o?"pending":s?"active":e.disabled?"off":v?"blocked":"idle";return(0,r.jsxs)("section",{className:"resource-account border-b border-border-strong px-4 py-3 last:border-b-0","data-account-state":b,"aria-current":s?"true":void 0,children:[(0,r.jsxs)("div",{className:"resource-account-head flex min-w-0 items-start gap-2.5",children:[(0,r.jsx)(ni,{seed:h.seed,size:48,provider:e.provider}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("h3",{className:"m-0 flex min-w-0 flex-wrap items-baseline gap-x-1.5 text-sm font-semibold text-text",children:[(0,r.jsx)("span",{children:h.alias}),(0,r.jsx)("span",{className:"min-w-0 truncate text-xs font-normal text-text-muted",children:`${(0,tX.bN)(e.provider)}${x?` \xb7 ${x}`:""}`})]}),(0,r.jsxs)("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[(0,r.jsx)("span",{className:"resource-account-state resource-account-badge","data-tone":U,role:o?"status":void 0,children:y}),null!=B&&B-n<=72e5?(0,r.jsx)("span",{className:"usage-chip",children:`곧 리셋 \xb7 ${o3(B,n).replace(/ 후 리셋$/,"")}`}):null]})]}),f?(0,r.jsxs)("span",{className:"resource-account-toggle",children:[(0,r.jsx)("span",{className:"resource-account-toggle-label",children:"사용 설정"}),(0,r.jsx)("button",{type:"button",role:"switch",className:o6(o8,"resource-account-switch min-w-[3.25rem]"),disabled:null!=o||!t,"aria-label":`${h.alias} 계정 사용 설정`,"aria-checked":!e.disabled,"aria-busy":null!=o||void 0,title:t?void 0:"제어 서버에 연결할 수 없습니다.",onClick:()=>{R.current=!1,T(null),c(e)},children:e.disabled?"OFF":"ON"})]}):null]}),e.disabled?(0,r.jsx)("div",{className:"mt-2 text-xs text-text-muted",children:"다른 계정이 있으면 이 계정을 사용하지 않습니다."}):v?(0,r.jsx)("div",{className:"mt-2 text-xs text-text-muted",children:(e.limits??[]).some(tX.xL)?"한도를 다 써서 코어가 자동으로 차단했습니다.":"한도는 남아 있지만 토큰 갱신 실패나 일시 오류로 코어가 잠시 막았습니다. 해제 시각이 지나면 다시 씁니다."}):null,d?(0,r.jsx)("div",{className:"mt-2 text-xs text-text",role:"error"===d.tone?"alert":"status",children:d.message}):null,(0,r.jsxs)("div",{id:k,className:"resource-account-limits divide-y divide-border",children:[j?(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-3 py-2",children:[(0,r.jsx)("span",{className:"text-xs text-text-muted",children:"계정"}),(0,r.jsxs)("span",{className:"flex min-w-0 items-baseline gap-2",children:[(0,r.jsx)("span",{className:"min-w-0 truncate font-mono text-xs text-text",children:C?h.raw:h.masked||"—"}),h.raw?(0,r.jsx)("button",{type:"button",className:"resource-account-reveal","aria-pressed":C,onClick:()=>N(!C),children:C?"가리기":"이메일 보기"}):null]})]}):null,(e.limits??[]).map(e=>(0,r.jsx)(dd,{limit:e,now:n,detailed:j},e.id))]}),(e.limits??[]).length>0||h.raw?(0,r.jsx)("button",{type:"button",className:"resource-account-more","aria-expanded":j,"aria-controls":k,onClick:()=>{let e=!j;S(e),e||N(!1)},children:j?"간단히":"자세히"}):null,"openai-codex"===e.provider||"anthropic"===e.provider?I?(0,r.jsx)(du,{confirmId:w,pending:"reset"===o,primaryRef:$,summary:I.summary,onConfirm:()=>{H()},onCancel:()=>{R.current=!0,T(null)}}):(0,r.jsxs)("div",{className:"resource-reset mt-3 border-t border-border pt-2.5","data-reset-state":t?L&&"unavailable"!==L.state?"empty"===L.state||0===F?"empty":"reset"===o?"pending":"ready":"unavailable":"offline",children:[(0,r.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1.5",children:[(0,r.jsxs)("div",{className:"flex min-w-[10.5rem] flex-1 items-baseline justify-between gap-x-3",children:[(0,r.jsx)("span",{className:"text-xs text-text-muted",children:"저장된 리셋"}),(0,r.jsx)("span",{className:o6("font-mono text-xs tabular-nums text-text",l?.reason==="expiring-credit"&&"text-warning"),children:P})]}),D?(0,r.jsx)("span",{className:"text-xs text-text-muted",children:D}):null,O?(0,r.jsx)("button",{ref:M,type:"button",className:o6(o8,"ml-auto flex-none"),disabled:null!=o,onClick:()=>{z&&T({creditId:z,summary:P})},children:"리셋 사용"}):t&&e.disabled&&L?.state==="available"?(0,r.jsx)("span",{className:"ml-auto text-xs text-text-muted",children:"켠 뒤 사용 가능"}):null]}),_?(0,r.jsx)("p",{className:"m-0 mt-1.5 text-xs leading-5 text-text-muted",children:_}):null]}):null]})}function dh({state:e,loading:t,accountState:n,pendingActions:i,feedbackByCredential:s,onToggle:a,onReset:l}){let o=o5(1e4),d=e.data,c=n?.state==="resolved"&&"session-pin"===n.source&&Number.isSafeInteger(n.credentialId)&&n.credentialId>0?n.credentialId:null,u=(0,tX.k)(d?.reports??[]),p=null==c?-1:d?.reports.findIndex(e=>e.credentialId===c)??-1;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(da,{state:e,loading:t,subject:"사용량"}),d?.brokerOk===!1?(0,r.jsx)("div",{className:"border-b border-border bg-bg px-4 py-2 text-xs text-text-muted",role:"status",children:"제어 서버에 연결할 수 없어 계정 전환과 리셋 사용을 잠시 쓸 수 없습니다. 사용량 표시는 계속 갱신됩니다."}):null,(0,r.jsxs)("div",{className:"flex min-h-7 items-center gap-4 border-b border-border bg-bg-raised px-4 text-[11px] font-semibold tracking-[0.08em] text-text-muted uppercase","aria-label":"사용량 그래프 범례",children:[(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"size-2 bg-metric","aria-hidden":"true"}),"누적"]}),(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"size-2 bg-metric-recent","aria-hidden":"true"}),"이번 구간"]}),(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"h-3 w-0.5 bg-text","aria-hidden":"true"}),"페이스"]})]}),d&&0===d.reports.length?(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"인증된 계정의 사용량 정보가 없습니다. `omp usage`로 확인하세요."}):null,d?.reports.map((e,t)=>{let c=e.credentialId;return(0,r.jsx)(dp,{report:e,brokerOk:!0===d.brokerOk,now:o,active:t===p,identity:u[t],recommendation:null==c?void 0:n?.resetRecommendations.find(e=>e.credentialId===c),pendingAction:null==c?null:i.get(c)??null,feedback:null==c?void 0:s.get(c),onToggle:a,onReset:l},`${e.provider}:${c??e.metadata?.accountId??e.metadata?.email??t}`)})]})}function dm({model:e}){let t=Math.max(1,Math.min(100,100*e.costShare));return(0,r.jsxs)("section",{className:"border-b border-border px-4 py-3 last:border-b-0",children:[(0,r.jsxs)("div",{className:"flex items-baseline gap-2",children:[(0,r.jsx)("h3",{className:"m-0 min-w-0 flex-1 truncate text-sm font-semibold text-text",title:e.model,children:e.model}),(0,r.jsx)("span",{className:"text-xs text-text-muted",children:e.provider}),(0,r.jsxs)("span",{className:"font-mono text-xs tabular-nums text-text",children:[o9(e.cost)," \xb7 ",dn(e.costShare)]})]}),(0,r.jsx)("div",{className:"my-2 h-1 overflow-hidden border border-border-strong bg-metric-track","aria-hidden":"true",children:(0,r.jsx)("div",{className:"h-full bg-metric",style:{width:`${t}%`}})}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(ds,{label:"요청",value:de(e.requests)}),(0,r.jsx)(ds,{label:"요청당",value:o9(e.costPerRequest)}),(0,r.jsx)(ds,{label:"토큰/요청",value:dt(e.tokensPerRequest)}),(0,r.jsx)(ds,{label:"출력/요청",value:dt(e.outputPerRequest)}),(0,r.jsx)(ds,{label:"캐시율",value:dn(e.cacheRate,1)}),(0,r.jsx)(ds,{label:"TTFT",value:dr(e.avgTtft)})]})]})}function df({agent:e}){let t={main:"메인",subagent:"SubAgent",advisor:"advisor"}[e.agentType]??e.agentType,n=Math.max(1,Math.min(100,100*e.costShare));return(0,r.jsxs)("section",{className:"border-b border-border px-4 py-3 last:border-b-0",children:[(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-3",children:[(0,r.jsx)("h3",{className:"m-0 text-sm font-semibold text-text",children:t}),(0,r.jsxs)("span",{className:"font-mono text-xs tabular-nums text-text",children:[o9(e.cost)," \xb7 ",dn(e.costShare)]})]}),(0,r.jsx)("div",{className:"my-2 h-1 overflow-hidden border border-border-strong bg-metric-track","aria-hidden":"true",children:(0,r.jsx)("div",{className:"h-full bg-metric",style:{width:`${n}%`}})}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(ds,{label:"요청",value:de(e.requests)}),(0,r.jsx)(ds,{label:"요청당",value:o9(e.costPerRequest)}),(0,r.jsx)(ds,{label:"토큰/요청",value:dt(e.tokensPerRequest)})]})]})}function dg({day:e}){let t=e.models.slice(0,3).map(e=>e.model).join(", ");return(0,r.jsxs)("div",{className:"grid grid-cols-[auto_minmax(0,1fr)_auto] items-baseline gap-3 border-b border-border px-4 py-2 last:border-b-0",children:[(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text-muted",children:di(e.timestamp)}),(0,r.jsx)("span",{className:"truncate text-xs text-text-muted",title:t,children:t}),(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:o9(e.cost)})]})}function dx({state:e,loading:t}){let n=e.data;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(da,{state:e,loading:t,subject:"모델 집계"}),n?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("section",{"aria-labelledby":"resource-overall-heading",children:[(0,r.jsx)("h2",{id:"resource-overall-heading",className:"m-0 border-b border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"전체"}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4 px-4 py-3",children:[(0,r.jsx)(ds,{label:"요청",value:de(n.overall.requests)}),(0,r.jsx)(ds,{label:"비용",value:o9(n.overall.cost)}),(0,r.jsx)(ds,{label:"토큰",value:dt(n.overall.tokens)}),(0,r.jsx)(ds,{label:"캐시율",value:dn(n.overall.cacheRate,1)}),(0,r.jsx)(ds,{label:"캐시 절감",value:dn(n.overall.cacheSavings,1)}),(0,r.jsx)(ds,{label:"평균 TTFT",value:dr(n.overall.avgTtft)})]})]}),(0,r.jsxs)("section",{"aria-labelledby":"resource-models-heading",children:[(0,r.jsx)("h2",{id:"resource-models-heading",className:"m-0 border-y border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"모델별"}),n.models.length?n.models.map(e=>(0,r.jsx)(dm,{model:e},`${e.provider}:${e.model}`)):(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"모델 기록이 없습니다."})]}),(0,r.jsxs)("section",{"aria-labelledby":"resource-agents-heading",children:[(0,r.jsx)("h2",{id:"resource-agents-heading",className:"m-0 border-y border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"에이전트 종류별"}),n.agents.length?n.agents.map(e=>(0,r.jsx)(df,{agent:e},e.agentType)):(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"기록이 없습니다."})]}),n.daily.length?(0,r.jsxs)("section",{"aria-labelledby":"resource-daily-heading",children:[(0,r.jsx)("h2",{id:"resource-daily-heading",className:"m-0 border-y border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"일별 비용"}),n.daily.map(e=>(0,r.jsx)(dg,{day:e},e.timestamp))]}):null,(0,r.jsx)("p",{className:"m-0 border-t border-border px-4 py-3 text-xs leading-5 text-text-dim",children:"`omp stats` 기준 누적값입니다. 구독 한도 %는 계정 한도 탭에서 확인하세요."})]}):null]})}function dv({reports:e,providerConnections:t}){return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("section",{className:"character-roster-intro","aria-labelledby":"character-roster-heading",children:[(0,r.jsx)("h2",{id:"character-roster-heading",children:"호출 가능한 캐릭터"}),(0,r.jsxs)("p",{children:[(0,r.jsx)("strong",{children:"호출\xb7불러\xb7소환"}),"은 캐릭터를 SubAgent로 이 대화에 부릅니다.",(0,r.jsx)("strong",{children:" 교체"}),"는 이 대화의 Main을 바꿉니다."]})]}),(0,r.jsx)("div",{className:"character-roster",role:"list","aria-label":"호출 가능한 캐릭터 목록",children:tX.o.map(n=>{let i=`character-roster-${n.seed}`,s=`character-roster-${n.seed}-status`,a=`${n.provider}/${n.model}`,l=!1,o=!1;if(e){for(let t of e)if(t.provider===n.provider&&(l=!0,!0!==t.disabled)){o=!0;break}}let d="web6"!==n.provider&&(t?.get(n.provider)===!1||l&&!o);return(0,r.jsxs)("article",{className:o6("character-roster-item",d&&"is-unavailable"),role:"listitem","aria-labelledby":i,"aria-describedby":d?s:void 0,children:[(0,r.jsxs)("div",{className:"character-roster-identity",children:[(0,r.jsx)(ni,{seed:n.seed,size:48,provider:n.provider}),(0,r.jsxs)("div",{children:[(0,r.jsx)("h3",{id:i,children:n.alias}),d?(0,r.jsx)("span",{id:s,className:"character-roster-availability",children:"연결 안 됨"}):null,(0,r.jsx)("p",{children:n.voice})]})]}),(0,r.jsxs)("dl",{className:"character-roster-model",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"모델"}),(0,r.jsx)("dd",{title:a,children:a})]}),void 0!==n.oauthPosition?(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"계정"}),(0,r.jsxs)("dd",{children:["OAuth ",n.oauthPosition]})]}):null]}),(0,r.jsxs)("dl",{className:"character-roster-examples",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"호출"}),(0,r.jsxs)("dd",{children:[(0,r.jsx)("code",{children:n.summonExample}),(0,r.jsx)("span",{children:n.summonNote??"SubAgent로 이 대화에 부릅니다."})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"Main 교체"}),(0,r.jsxs)("dd",{children:[n.switchExample?(0,r.jsx)("code",{children:n.switchExample}):(0,r.jsx)("strong",{children:"교체 불가"}),(0,r.jsx)("span",{children:n.switchNote??"이 대화의 Main을 바꿉니다."})]})]})]})]},n.alias)})})]})}function db({open:e,sessionId:t,activeTab:n,onTabChange:s,usage:l,className:o}){let d=(0,i.useId)(),c=l.state,u=l.loading,[p,h]=(0,i.useState)({status:"idle",data:null,error:null}),[m,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(!1),[v,b]=(0,i.useState)(null),[y,w]=(0,i.useState)(()=>new Map),[k,j]=(0,i.useState)(()=>new Map),S=(0,i.useRef)(p),C=(0,i.useRef)(null),N=(0,i.useRef)(null),I=(0,i.useRef)(new Set),T=(0,i.useRef)(new Set);S.current=p,(0,i.useEffect)(()=>{if(!e||"characters"!==n)return;let t=new AbortController;return b(null),Promise.all([fetch("/api/auth/all-providers",{signal:t.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return e.json()}),fetch("/api/auth/providers",{signal:t.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return e.json()})]).then(([e,n])=>{if(t.signal.aborted)return;let r=new Map(e.providers.map(e=>[e.id,e.configured]));for(let e of n.providers)r.set(e.id,!0===r.get(e.id)||e.loggedIn);b(r)}).catch(()=>{t.signal.aborted||b(null)}),()=>t.abort()},[n,e,c.data]),(0,i.useEffect)(()=>{if(f(null),!e||"usage"!==n||!t)return;let r=(0,tX._Q)({onClear(){f(null)},onResult(e){f("fresh"===e.status?e.data:null)}});return C.current=r,r.setSessionId(t),()=>{r.stop(),C.current===r&&(C.current=null)}},[n,e,t]);let M=(0,i.useCallback)(async e=>{N.current?.abort();let t=new AbortController;N.current=t,x(!0);let n=await (0,tX.t6)({refresh:e,previous:S.current.data,signal:t.signal});N.current!==t||t.signal.aborted||(h(n),x(!1))},[]);(0,i.useEffect)(()=>{e&&"models"===n&&("idle"===S.current.status||"error"===S.current.status)&&M(!1)},[n,e,M]),(0,i.useEffect)(()=>()=>{for(let e of(N.current?.abort(),I.current))e.abort()},[]);let $=(0,i.useCallback)(()=>{"models"===n?M(!0):l.refresh()},[n,M,l]),R=(0,i.useCallback)(()=>l.refresh(),[l]),E=(0,i.useCallback)(async e=>{if(!Number.isSafeInteger(e.credentialId)||e.credentialId<=0)return;let t=e.credentialId,n=(0,tX.U3)(T.current,t);if(!n)return;let r=new AbortController;I.current.add(r),l.setPaused(!0),w(e=>new Map(e).set(t,"toggle")),j(e=>{let n=new Map(e);return n.delete(t),n});try{await (0,tX.vy)(t,!0===e.disabled,{signal:r.signal});let n=await R();r.signal.aborted||j(r=>new Map(r).set(t,{tone:"status",message:"fresh"===n.status?`계정을 ${e.disabled?"켰습니다":"껐습니다"}.`:"계정 설정 저장됨 \xb7 표시 상태 새로고침 실패."}))}catch(e){if(!r.signal.aborted){let n=e instanceof tX.OO&&("timeout"===e.kind||e.outcomeUnknown);j(r=>new Map(r).set(t,n?{tone:"error",message:"적용 여부 확인 필요 — 새로고침으로 계정 상태를 확인하세요."}:{tone:"error",message:`계정 전환 실패: ${e instanceof Error?e.message:String(e)}`}))}}finally{I.current.delete(r),n(),l.setPaused(T.current.size>0),w(e=>{let n=new Map(e);return n.delete(t),n})}},[R,l]),L=(0,i.useCallback)(async(e,t)=>{if(!Number.isSafeInteger(e.credentialId)||e.credentialId<=0)return;let n=e.credentialId,r=(0,tX.U3)(T.current,n);if(!r)return;let i=new AbortController;I.current.add(i),l.setPaused(!0),w(e=>new Map(e).set(n,"reset")),j(e=>{let t=new Map(e);return t.delete(n),t});try{let e=await (0,tX.tR)(n,t,{signal:i.signal}),r=function(e){switch(e.code){case"reset":return{tone:"status",message:"리셋 사용함"};case"no_credit":return{tone:"status",message:"사용할 수 있는 리셋이 없습니다."};case"already_redeemed":return{tone:"status",message:"이미 사용된 리셋입니다."};case"nothing_to_reset":return{tone:"status",message:"지금은 초기화할 한도가 없습니다."};case"ineligible":return{tone:"status",message:"지금은 이 리셋을 쓸 수 없습니다(한도 미도달 또는 자격 없음)."};case"cooldown":return{tone:"status",message:"리셋 재사용 대기 중입니다. 잠시 뒤 다시 시도하세요."};case"offer_changed":return{tone:"status",message:"리셋 목록이 바뀌었습니다. 새로고침 후 다시 시도하세요."};case"rate_limited":return{tone:"error",message:"리셋 사용 실패: 요청이 많아 잠시 막혔습니다."};case"reset_unconfirmed":return{tone:"error",message:"이전 리셋 요청 결과를 아직 확인하지 못했습니다. 잠시 뒤 확인하세요."};case"no_account":return{tone:"error",message:"리셋 사용 실패: 계정을 찾을 수 없습니다."};case"account_unavailable":return{tone:"error",message:"리셋 사용 실패: 계정에 연결할 수 없습니다."};case"credit_list_failed":return{tone:"error",message:"리셋 사용 실패: 저장된 리셋 목록을 확인하지 못했습니다."};default:return e.code.startsWith("http_")?{tone:"error",message:`리셋 사용 실패: 서비스 응답 오류 (${e.code})`}:{tone:"error",message:`리셋 사용 실패: ${e.code}`}}}(e),s=await R();if(e.ok){let e="fresh"===s.status?s.data.reports.find(e=>e.credentialId===n):void 0,t=e?.savedReset?.availableCount;r.message="number"==typeof t?`리셋 사용함 \xb7 남은 리셋 ${t}개`:"리셋 사용함 \xb7 남은 개수를 확인하지 못했습니다."}i.signal.aborted||j(e=>new Map(e).set(n,r))}catch(e){e instanceof tX.OO&&(e.outcomeUnknown||"timeout"===e.kind)&&!i.signal.aborted&&await R(),i.signal.aborted||j(t=>new Map(t).set(n,function(e){if(e instanceof tX.OO){if(e.outcomeUnknown||"timeout"===e.kind)return{tone:"error",message:"적용 여부 확인 필요 — 자동으로 다시 시도하지 않았습니다. 새로고침으로 남은 개수를 확인하세요."};switch(e.code){case"account_disabled":return{tone:"error",message:"리셋 사용 실패: 꺼둔 계정에서는 사용할 수 없습니다."};case"no_account":return{tone:"error",message:"리셋 사용 실패: 계정을 찾을 수 없습니다."};case"account_unavailable":return{tone:"error",message:"리셋 사용 실패: 계정에 연결할 수 없습니다."};case"credit_list_failed":return{tone:"error",message:"리셋 사용 실패: 저장된 리셋 목록을 확인하지 못했습니다."};default:return{tone:"error",message:`리셋 사용 실패: ${e.message}`}}}return{tone:"error",message:`리셋 사용 실패: ${e instanceof Error?e.message:String(e)}`}}(e)))}finally{I.current.delete(i),r(),l.setPaused(T.current.size>0),w(e=>{let t=new Map(e);return t.delete(n),t})}},[R,l]);if(!e)return null;let A="models"===n?p.data?.generatedAt:c.data?.generatedAt,z="models"===n?p.data?.range:void 0,W=z?.from&&z.to?`${di(z.from)}~${di(z.to)}`:A?new Date(A).toLocaleTimeString():"",F="models"===n?g:"usage"===n&&u,P=F?"models"===n?"집계 중…":"불러오는 중…":"새로고침";return(0,r.jsxs)("section",{className:o6("resource-panel flex min-h-0 w-full flex-col overflow-hidden bg-bg-panel text-text",o),"aria-labelledby":d,"aria-busy":F,children:[(0,r.jsx)("h1",{id:d,className:"sr-only",children:"캐릭터"}),(0,r.jsxs)(oN.J.Root,{className:"resource-view-tabs",size:"small",contentLayout:"fill",triggerLayout:"fill",value:n,onValueChange:e=>s(e),children:[(0,r.jsxs)(oN.J.List,{"aria-label":"캐릭터와 사용량 보기",children:[(0,r.jsx)(oN.J.Trigger,{value:"characters",children:"캐릭터"}),(0,r.jsx)(oN.J.Trigger,{value:"usage",children:"계정 한도"}),(0,r.jsx)(oN.J.Trigger,{value:"models",children:"모델 통계"}),(0,r.jsx)(oN.J.Indicator,{})]}),(0,r.jsx)(oN.J.Content,{value:"characters",className:"resource-view-content",children:(0,r.jsx)(dv,{reports:c.data?.reports,providerConnections:v})}),(0,r.jsxs)(oN.J.Content,{value:"usage",className:"resource-view-content",children:[(0,r.jsxs)("div",{className:"resource-usage-toolbar",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] tabular-nums text-text-dim",children:W}),(0,r.jsx)(a.r,{variant:"neutralWeak",size:"xsmall",onClick:$,disabled:F,children:P})]}),(0,r.jsx)("h2",{className:"resource-group-heading",children:"계정 한도"}),(0,r.jsx)(dh,{state:c,loading:u,accountState:m?.sessionId===t?m:null,pendingActions:y,feedbackByCredential:k,onToggle:e=>{E(e)},onReset:L})]}),(0,r.jsxs)(oN.J.Content,{value:"models",className:"resource-view-content",children:[(0,r.jsxs)("div",{className:"resource-usage-toolbar",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] tabular-nums text-text-dim",children:W}),(0,r.jsx)(a.r,{variant:"neutralWeak",size:"xsmall",onClick:$,disabled:F,children:P})]}),(0,r.jsx)(dx,{state:p,loading:g})]})]})]})}let dy="/api/runs";class dw extends Error{constructor(e,t,n=null){super(t),this.name="EfficiencyClientError",this.kind=e,this.status=n}}let dk=["completed","error","aborted","interrupted","running"],dj=["main","maker","checker","advisor","unattributed"],dS=["primary","rework","review"],dC=["wait-attribution","unpriced-cost","effort-unrecorded","role-unattributed","busy-unrecorded"],dN=["all","attributed"];function dI(e){return"object"==typeof e&&null!==e}function dT(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function dM(e){return!!dI(e)&&"string"==typeof e.runId&&"string"==typeof e.sessionId&&"string"==typeof e.entryId&&"number"==typeof e.index&&Number.isFinite(e.index)&&(null===e.title||"string"==typeof e.title)&&"number"==typeof e.startedAt&&Number.isFinite(e.startedAt)&&(null===e.endedAt||"number"==typeof e.endedAt&&Number.isFinite(e.endedAt))&&"number"==typeof e.wallClockMs&&Number.isFinite(e.wallClockMs)&&"string"==typeof e.outcome&&dk.includes(e.outcome)&&"number"==typeof e.busyMs&&Number.isFinite(e.busyMs)&&"number"==typeof e.childCount&&Number.isFinite(e.childCount)&&"number"==typeof e.totalTokens&&Number.isFinite(e.totalTokens)&&"number"==typeof e.estimatedCostUsd&&Number.isFinite(e.estimatedCostUsd)&&"number"==typeof e.unpricedRequests&&Number.isFinite(e.unpricedRequests)&&"string"==typeof e.configSignature}function d$(e){return!!dI(e)&&"string"==typeof e.id&&"string"==typeof e.kind&&dj.includes(e.kind)&&(null===e.purpose||"string"==typeof e.purpose&&dS.includes(e.purpose))&&dT(e.models)&&dT(e.efforts)&&"number"==typeof e.requestCount&&Number.isFinite(e.requestCount)&&"number"==typeof e.busyMs&&Number.isFinite(e.busyMs)&&"number"==typeof e.spanMs&&Number.isFinite(e.spanMs)&&"number"==typeof e.startedAt&&Number.isFinite(e.startedAt)&&"number"==typeof e.endedAt&&Number.isFinite(e.endedAt)&&"number"==typeof e.inputTokens&&Number.isFinite(e.inputTokens)&&"number"==typeof e.outputTokens&&Number.isFinite(e.outputTokens)&&"number"==typeof e.cacheReadTokens&&Number.isFinite(e.cacheReadTokens)&&"number"==typeof e.cacheWriteTokens&&Number.isFinite(e.cacheWriteTokens)&&"number"==typeof e.totalTokens&&Number.isFinite(e.totalTokens)&&"number"==typeof e.estimatedCostUsd&&Number.isFinite(e.estimatedCostUsd)&&"number"==typeof e.unpricedRequests&&Number.isFinite(e.unpricedRequests)&&"number"==typeof e.untimedRequests&&Number.isFinite(e.untimedRequests)&&"number"==typeof e.errorCount&&Number.isFinite(e.errorCount)&&"number"==typeof e.abortedCount&&Number.isFinite(e.abortedCount)&&"number"==typeof e.toolCalls&&Number.isFinite(e.toolCalls)}function dR(e){return!!dI(e)&&("role-busy"===e.kind||"unmeasured-gap"===e.kind)&&"string"==typeof e.id&&"number"==typeof e.ms&&Number.isFinite(e.ms)&&"number"==typeof e.relative&&Number.isFinite(e.relative)}function dE(e){return!!dI(e)&&"string"==typeof e.toolName&&"number"==typeof e.calls&&Number.isFinite(e.calls)&&"number"==typeof e.errors&&Number.isFinite(e.errors)}function dL(e){return!!dI(e)&&"string"==typeof e.kind&&dj.includes(e.kind)&&"string"==typeof e.model&&(null===e.effort||"string"==typeof e.effort)&&"number"==typeof e.count&&Number.isFinite(e.count)}function dA(e){return!!dI(e)&&"string"==typeof e.signature&&Array.isArray(e.roles)&&e.roles.every(dL)&&"number"==typeof e.runCount&&Number.isFinite(e.runCount)&&"number"==typeof e.medianWallClockMs&&Number.isFinite(e.medianWallClockMs)&&"number"==typeof e.medianBusyMs&&Number.isFinite(e.medianBusyMs)&&"number"==typeof e.medianTotalTokens&&Number.isFinite(e.medianTotalTokens)&&"number"==typeof e.medianEstimatedCostUsd&&Number.isFinite(e.medianEstimatedCostUsd)&&"number"==typeof e.totalEstimatedCostUsd&&Number.isFinite(e.totalEstimatedCostUsd)&&"number"==typeof e.unpricedRuns&&Number.isFinite(e.unpricedRuns)&&"number"==typeof e.untimedRuns&&Number.isFinite(e.untimedRuns)&&"number"==typeof e.reworkRuns&&Number.isFinite(e.reworkRuns)&&"number"==typeof e.errorRuns&&Number.isFinite(e.errorRuns)&&"number"==typeof e.childRunsAvg&&Number.isFinite(e.childRunsAvg)&&"number"==typeof e.firstSeenAt&&Number.isFinite(e.firstSeenAt)&&"number"==typeof e.lastSeenAt&&Number.isFinite(e.lastSeenAt)}function dz(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e&&dC.includes(e))}async function dW(e){try{return await e.json()}catch{throw new dw("invalid-response","효율 응답 JSON을 해석할 수 없습니다.",e.status)}}function dF(e,t){return e instanceof dw||e instanceof Error?e.message:t}let dP={completed:"positive",error:"critical",aborted:"warning",interrupted:"warning",running:"informative"},dD={main:"informative",maker:"neutral",checker:"neutral",advisor:"neutral",unattributed:"warning"};function d_(...e){return e.filter(Boolean).join(" ")}function dO(e){return"number"==typeof e&&Number.isFinite(e)?0===e?"$0":e>=100?`$${e.toFixed(0)}`:e>=1?`$${e.toFixed(2)}`:e>=.01?`$${e.toFixed(3)}`:`$${e.toFixed(4)}`:"—"}function dH(e){return"number"==typeof e&&Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"—"}function dB(e){return"number"==typeof e&&Number.isFinite(e)?e>=1e9?`${(e/1e9).toFixed(1)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(Math.round(e)):"—"}function dU(e){if("number"!=typeof e||!Number.isFinite(e))return"—";let t=Math.max(0,e);if(t<1e3)return`${Math.round(t)}ms`;let n=Math.round(t/1e3);if(n<60)return`${(t/1e3).toFixed(1)}s`;let r=Math.floor(n/60),i=n-60*r;return r<60?0===i?`${r}m`:`${r}m ${i}s`:`${Math.floor(r/60)}h ${r%60}m`}function dq(e,t=0){return"number"==typeof e&&Number.isFinite(e)?`${(100*e).toFixed(t)}%`:"—"}function dV({label:e,value:t}){return(0,r.jsxs)("div",{className:"flex min-w-0 items-baseline justify-between gap-3 border-b border-border py-1.5 last:border-b-0",children:[(0,r.jsx)("dt",{className:"min-w-0 flex-1 truncate text-xs text-text-muted",children:e}),(0,r.jsx)("dd",{className:"m-0 flex-none font-mono text-xs tabular-nums text-text",children:t})]})}function dK({share:e,label:t}){let n=Number.isFinite(e)?Math.max(1,Math.min(100,100*e)):1;return(0,r.jsxs)("div",{className:"efficiency-bar","aria-hidden":"true",children:[(0,r.jsx)("div",{className:"efficiency-bar-fill",style:{width:`${n}%`}}),(0,r.jsx)("span",{className:"efficiency-bar-value",children:t})]})}function dJ({costUsd:e,unpriced:t,t:n}){return(0,r.jsxs)("span",{className:"font-mono tabular-nums",children:[n("efficiency.estimatedCostValue").replace("{value}",dO(e)),t>0?` \xb7 ${n("efficiency.unpricedLowerBound")}`:""]})}function dG({outcome:e,t}){return(0,r.jsx)(oI.E,{tone:dP[e],variant:"weak",size:"medium",children:t({completed:"efficiency.outcomeCompleted",error:"efficiency.outcomeError",aborted:"efficiency.outcomeAborted",interrupted:"efficiency.outcomeInterrupted",running:"efficiency.outcomeRunning"}[e])})}function dY({purpose:e,t}){return null===e?(0,r.jsx)("span",{className:"efficiency-dim",children:t("efficiency.unmeasuredShort")}):(0,r.jsx)(oI.E,{tone:"rework"===e?"warning":"neutral",variant:"weak",size:"medium",children:t({primary:"efficiency.purposePrimary",rework:"efficiency.purposeRework",review:"efficiency.purposeReview"}[e]??"efficiency.unmeasuredShort")})}function dZ({run:e,selected:t,onSelect:n,t:i}){let s=e.title&&e.title.trim().length>0?e.title:i("efficiency.noTitle");return(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",onClick:n,"aria-current":t?"true":void 0,className:d_("efficiency-run-item",t&&"is-selected"),children:[(0,r.jsxs)("span",{className:"efficiency-run-top",children:[(0,r.jsxs)("span",{className:"efficiency-run-index",children:["#",e.index]}),(0,r.jsx)("span",{className:"efficiency-run-title",title:s,children:s}),(0,r.jsx)(dG,{outcome:e.outcome,t:i})]}),(0,r.jsxs)("span",{className:"efficiency-run-meta",children:[(0,r.jsx)("span",{className:"font-mono tabular-nums",children:i("efficiency.elapsedValue").replace("{value}",dU(e.wallClockMs))}),(0,r.jsx)(dJ,{costUsd:e.estimatedCostUsd,unpriced:e.unpricedRequests,t:i})]})]})})}function dX({role:e,t}){let n=e.models.length>0?e.models.join(", "):t("efficiency.unmeasuredShort"),i=e.efforts.length>0?e.efforts.join(", "):t("efficiency.unmeasuredShort"),s=e.outputTokens-e.helpers.reduce((e,t)=>e+t.outputTokens,0);return(0,r.jsxs)("section",{className:"efficiency-card",children:[(0,r.jsxs)("div",{className:"efficiency-card-top",children:[(0,r.jsx)("h4",{className:"efficiency-card-title",title:e.id,children:e.id}),(0,r.jsx)(oI.E,{tone:dD[e.kind]??"neutral",variant:"weak",size:"medium",children:t(`efficiency.role${"main"===e.kind?"Main":"maker"===e.kind?"Maker":"checker"===e.kind?"Checker":"advisor"===e.kind?"Advisor":"Unattributed"}`)}),(0,r.jsx)(dY,{purpose:e.purpose,t:t})]}),(0,r.jsx)("p",{className:"efficiency-model-line",title:n,children:n}),(0,r.jsxs)("p",{className:"efficiency-dim",children:[t("efficiency.effortLabel").replace("{value}",i),` \xb7 ${t("efficiency.requestsValue").replace("{value}",String(e.requestCount))}`,` \xb7 ${t("efficiency.toolCallsValue").replace("{value}",String(e.toolCalls))}`]}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(dV,{label:t("efficiency.busyTime"),value:dU(e.busyMs)}),(0,r.jsx)(dV,{label:t("efficiency.estimatedCost"),value:dO(e.estimatedCostUsd)}),(0,r.jsx)(dV,{label:t("efficiency.tokens"),value:dB(e.totalTokens)}),(0,r.jsx)(dV,{label:t("efficiency.unpricedRequests"),value:dH(e.unpricedRequests)}),(0,r.jsx)(dV,{label:t("efficiency.firstTokenAvg"),value:null!==e.ttftMs&&e.ttftRequests>0?dU(e.ttftMs/e.ttftRequests):t("efficiency.unmeasuredShort")}),(0,r.jsx)(dV,{label:t("efficiency.outputTokens"),value:dB(s)})]}),e.ttftRequests>0&&e.ttftRequests<e.requestCount?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.firstTokenPartial",{recorded:e.ttftRequests,total:e.requestCount})}):null,e.untimedRequests>0?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.untimedLowerBound").replace("{value}",dH(e.untimedRequests))}):null,e.unpricedRequests>0?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.unpricedLowerBound")}):null,e.helpers.length>0?(0,r.jsxs)("section",{"aria-label":t("efficiency.helpersTitle"),children:[(0,r.jsx)("p",{className:"efficiency-dim",children:t("efficiency.helpersTitle")}),(0,r.jsx)("dl",{className:"m-0",children:e.helpers.map(e=>(0,r.jsx)(dV,{label:`${e.purpose} \xb7 ${e.model}`,value:t("efficiency.helperCallsValue",{count:e.requestCount,output:dB(e.outputTokens),tokens:dB(e.totalTokens),cost:dO(e.estimatedCostUsd)})},`${e.purpose}:${e.role??""}:${e.model}`))}),(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.helpersIncludedNote")})]}):null]})}function dQ({item:e,t}){let n="unmeasured-gap"===e.kind?t("efficiency.unmeasuredGap"):e.id;return(0,r.jsxs)("li",{className:"efficiency-bottleneck",children:[(0,r.jsxs)("div",{className:"efficiency-bottleneck-top",children:[(0,r.jsx)("span",{className:"efficiency-bottleneck-label",title:n,children:n}),(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:dU(e.ms)})]}),(0,r.jsx)(dK,{share:e.relative,label:dU(e.ms)})]})}function d0({detail:e,t}){return(0,r.jsxs)("div",{className:"efficiency-detail",children:[(0,r.jsxs)("section",{"aria-label":t("efficiency.summarySection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.summarySection")}),(0,r.jsxs)("div",{className:"efficiency-dual",children:[(0,r.jsxs)("div",{className:"efficiency-dual-cell",children:[(0,r.jsx)("span",{className:"efficiency-dual-label",children:t("efficiency.elapsed")}),(0,r.jsx)("span",{className:"efficiency-dual-value",children:dU(e.wallClockMs)})]}),(0,r.jsxs)("div",{className:"efficiency-dual-cell",children:[(0,r.jsx)("span",{className:"efficiency-dual-label",children:t("efficiency.busyTotal")}),(0,r.jsx)("span",{className:"efficiency-dual-value",children:dU(e.busyMs)})]})]}),(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.noSumNote")}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(dV,{label:t("efficiency.estimatedCost"),value:dO(e.estimatedCostUsd)}),(0,r.jsx)(dV,{label:t("efficiency.tokens"),value:dB(e.totalTokens)})]}),e.unpricedRequests>0?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.unpricedLowerBound")}):null]}),(0,r.jsxs)("section",{"aria-label":t("efficiency.rolesSection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.rolesSection")}),e.roles.length>0?(0,r.jsx)("div",{className:"efficiency-stack",children:e.roles.map(e=>(0,r.jsx)(dX,{role:e,t:t},e.id))}):(0,r.jsx)("p",{className:"efficiency-empty",children:t("efficiency.rolesEmpty")})]}),(0,r.jsxs)("section",{"aria-label":t("efficiency.bottlenecksSection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.bottlenecksSection")}),(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.bottleneckOrderNote")}),e.bottlenecks.length>0?(0,r.jsx)("ul",{className:"efficiency-stack",children:e.bottlenecks.map(e=>(0,r.jsx)(dQ,{item:e,t:t},`${e.kind}:${e.id}`))}):(0,r.jsx)("p",{className:"efficiency-empty",children:t("efficiency.bottlenecksEmpty")}),e.unmeasuredMs>0?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.unmeasuredGapValue").replace("{value}",dU(e.unmeasuredMs))}):null]}),e.toolTotals.length>0?(0,r.jsxs)("section",{"aria-label":t("efficiency.toolsSection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.toolsSection")}),(0,r.jsx)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:e.toolTotals.map(e=>(0,r.jsx)(dV,{label:`${e.toolName} \xb7 ${t("efficiency.toolErrorsValue").replace("{value}",String(e.errors))}`,value:dH(e.calls)},e.toolName))})]}):null]})}function d1(e){return e.map(e=>{let t=e.effort??"–",n=e.count>1?` x${e.count}`:"";return`${e.kind} ${e.model}:${t}${n}`}).join(" \xb7 ")}function d2({response:e,t}){return(0,r.jsx)("section",{className:"efficiency-card",children:(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(dV,{label:t("efficiency.scopeSessions"),value:dH(e.sessionCount)}),(0,r.jsx)(dV,{label:t("efficiency.scopeRuns"),value:dH(e.runCount)}),(0,r.jsx)(dV,{label:t("efficiency.scopeExcludedRuns"),value:dH(e.excludedRunCount)})]})})}function d4({config:e,baselineRuns:t,t:n}){let i=t>0?e.runCount/t:0,s=e.runCount>0?e.reworkRuns/e.runCount:0,a=e.runCount>0?e.errorRuns/e.runCount:0;return(0,r.jsxs)("section",{className:"efficiency-card",children:[(0,r.jsx)("p",{className:"efficiency-model-line",title:d1(e.roles),children:d1(e.roles)}),(0,r.jsxs)("div",{className:"efficiency-bottleneck-top",children:[(0,r.jsx)("span",{className:"efficiency-dim",children:n("efficiency.runsValue").replace("{value}",String(e.runCount))}),(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:dq(i)})]}),(0,r.jsx)(dK,{share:i,label:dq(i)}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(dV,{label:n("efficiency.medianElapsed"),value:dU(e.medianWallClockMs)}),(0,r.jsx)(dV,{label:n("efficiency.medianBusy"),value:dU(e.medianBusyMs)}),(0,r.jsx)(dV,{label:n("efficiency.medianTokens"),value:dB(e.medianTotalTokens)}),(0,r.jsx)(dV,{label:n("efficiency.medianEstimatedCost"),value:dO(e.medianEstimatedCostUsd)}),(0,r.jsx)(dV,{label:n("efficiency.totalEstimatedCost"),value:dO(e.totalEstimatedCostUsd)}),(0,r.jsx)(dV,{label:n("efficiency.reworkRate"),value:dq(s,1)}),(0,r.jsx)(dV,{label:n("efficiency.errorRate"),value:dq(a,1)}),(0,r.jsx)(dV,{label:n("efficiency.unpricedRuns"),value:dH(e.unpricedRuns)}),(0,r.jsx)(dV,{label:n("efficiency.untimedRuns"),value:dH(e.untimedRuns)})]}),e.untimedRuns>0?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.untimedMedianLowerBound").replace("{value}",dH(e.untimedRuns))}):null,e.unpricedRuns>0?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.unpricedLowerBound")}):null]})}function d5({open:e,sessionId:t,activeTab:n,onTabChange:s,client:l,className:d}){let c=(0,i.useId)(),u=(0,i.useId)(),{t:p}=(0,R.s)(),h=function({sessionId:e,visible:t,activeTab:n,client:r}){let[s]=(0,i.useState)(()=>r??function(e=(e,t)=>fetch(e,t)){let t=async(t,n)=>{let r;try{r=await e(t,n)}catch(e){if(n.signal?.aborted)throw e;throw new dw("unreachable","효율 기록에 연결할 수 없습니다.")}let i=await dW(r);if(!r.ok){var s;throw new dw("http",(s=`HTTP ${r.status}`,null!==i&&"object"==typeof i&&"error"in i&&"string"==typeof i.error&&i.error?i.error:s),r.status)}return{response:r,body:i}};return{async listRuns(e,n,r){let{response:i,body:s}=await t(`${dy}?sessionId=${encodeURIComponent(e)}&limit=${encodeURIComponent(String(n))}`,{method:"GET",signal:r});return function(e,t,n=null){try{if(!dI(e)||!("string"==typeof e.sessionId&&Array.isArray(e.runs)&&e.runs.every(dM)&&dz(e.unmeasured)))throw new dw("invalid-response","실행 목록 응답이 올바르지 않습니다.");return e}catch{throw new dw("invalid-response",t,n)}}(s,"실행 목록 응답이 올바르지 않습니다.",i.status)},async getRun(e,n){let{response:r,body:i}=await t(`${dy}/${encodeURIComponent(e)}`,{method:"GET",signal:n});return function(e,t,n=null){try{if(!dM(e)||!(Array.isArray(e.roles)&&e.roles.every(d$)&&Array.isArray(e.bottlenecks)&&e.bottlenecks.every(dR)&&"number"==typeof e.unmeasuredMs&&Number.isFinite(e.unmeasuredMs)&&Array.isArray(e.toolTotals)&&e.toolTotals.every(dE)&&dz(e.unmeasured)))throw new dw("invalid-response","실행 상세 응답이 올바르지 않습니다.");return e}catch{throw new dw("invalid-response",t,n)}}(i,"실행 상세 응답이 올바르지 않습니다.",r.status)},async listExperiments(e,n,r,i){let s=new URLSearchParams;null!==e&&""!==e&&s.set("folder",e),s.set("sessions",String(n)),s.set("scope",r);let{response:a,body:l}=await t(`/api/experiments?${s.toString()}`,{method:"GET",signal:i});return function(e,t,n=null){try{if(!dI(e)||!((null===e.folder||"string"==typeof e.folder)&&dT(e.folders)&&"string"==typeof e.scope&&dN.includes(e.scope)&&Array.isArray(e.configs)&&e.configs.every(dA)&&"number"==typeof e.runCount&&Number.isFinite(e.runCount)&&"number"==typeof e.sessionCount&&Number.isFinite(e.sessionCount)&&"number"==typeof e.excludedRunCount&&Number.isFinite(e.excludedRunCount)&&dz(e.unmeasured)))throw new dw("invalid-response","구성 비교 응답이 올바르지 않습니다.");return e}catch{throw new dw("invalid-response",t,n)}}(l,"구성 비교 응답이 올바르지 않습니다.",a.status)}}}()),[a,l]=(0,i.useState)({status:"idle",runs:[],error:null}),[o,d]=(0,i.useState)({status:"idle",runId:null,detail:null,error:null}),[c,u]=(0,i.useState)({status:"idle",response:null,error:null}),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(null);(0,i.useEffect)(()=>{x.current?.abort(),x.current=null,h(null),d({status:"idle",runId:null,detail:null,error:null}),l({status:"idle",runs:[],error:null})},[e]);let y=(0,i.useCallback)(()=>{if(!t||"governor"!==n||!e)return;g.current?.abort();let r=new AbortController;g.current=r,l(e=>({status:"loading",runs:"ready"===e.status||"empty"===e.status?e.runs:[],error:null})),s.listRuns(e,20,r.signal).then(e=>{if(!r.signal.aborted&&g.current===r){if(0===e.runs.length)return void l({status:"empty",runs:[],error:null});l({status:"ready",runs:e.runs,error:null})}}).catch(e=>{r.signal.aborted||g.current!==r||l({status:"error",runs:[],error:dF(e,"실행 목록을 불러오지 못했습니다.")})})},[n,s,e,t]),w=(0,i.useCallback)(e=>{if(!t)return;x.current?.abort();let n=new AbortController;x.current=n,d({status:"loading",runId:e,detail:null,error:null}),s.getRun(e,n.signal).then(t=>{n.signal.aborted||x.current!==n||d({status:"ready",runId:e,detail:t,error:null})}).catch(t=>{n.signal.aborted||x.current!==n||d({status:"error",runId:e,detail:null,error:dF(t,"실행 상세를 불러오지 못했습니다.")})})},[s,t]),k=(0,i.useCallback)((e,r="all")=>{if(!t||"lab"!==n)return;v.current?.abort();let i=new AbortController;v.current=i,u(e=>({status:"loading",response:"ready"===e.status||"empty"===e.status?e.response:null,error:null})),s.listExperiments(e,30,r,i.signal).then(e=>{if(!i.signal.aborted&&v.current===i){if(0===e.configs.length)return void u({status:"empty",response:e,error:null});u({status:"ready",response:e,error:null})}}).catch(e=>{i.signal.aborted||v.current!==i||u({status:"error",response:null,error:dF(e,"구성 비교를 불러오지 못했습니다.")})})},[n,s,t]);(0,i.useEffect)(()=>{if(t&&"governor"===n)return y(),()=>{g.current?.abort(),g.current=null}},[n,y,e,t]),(0,i.useEffect)(()=>{if(t&&"lab"===n)return k(b.current),()=>{v.current?.abort(),v.current=null}},[n,k,t]),(0,i.useEffect)(()=>{if(t&&"governor"===n&&null!==p)return w(p),()=>{x.current?.abort(),x.current=null}},[n,w,p,t]),(0,i.useEffect)(()=>()=>{g.current?.abort(),x.current?.abort(),v.current?.abort()},[]);let j=(0,i.useCallback)(e=>{x.current?.abort(),x.current=null,h(e),null===e&&d({status:"idle",runId:null,detail:null,error:null})},[]);return{list:a,detail:o,experiments:c,selectedRunId:p,selectRun:j,refreshRuns:(0,i.useCallback)(()=>{y()},[y]),refreshExperiments:(0,i.useCallback)((e,t="all")=>{let n=void 0===e?b.current:e;void 0!==e&&(b.current=e,f(e)),k(n,t)},[k]),experimentFolder:m}}({sessionId:t,visible:e,activeTab:n,client:l}),[m,f]=(0,i.useState)(""),g=(0,i.useMemo)(()=>h.experiments.response?.folders??[],[h.experiments.response]),x=(0,i.useMemo)(()=>h.experiments.response?.configs.reduce((e,t)=>Math.max(e,t.runCount),0)??0,[h.experiments.response]),v=h.experimentFolder,b=h.experiments.response?.scope??"all";if(!e)return null;let y="governor"===n&&"loading"===h.list.status||"lab"===n&&"loading"===h.experiments.status,w=y?p("efficiency.refreshing"):p("efficiency.refresh"),k="governor"===n?h.list.runs.length>0?p("efficiency.runsValue").replace("{value}",String(h.list.runs.length)):"":h.experiments.response?p("efficiency.runsValue").replace("{value}",String(h.experiments.response.runCount)):"";return(0,r.jsxs)("section",{className:d_("efficiency-panel flex min-h-0 w-full flex-col overflow-hidden bg-bg-panel text-text",d),"aria-labelledby":c,"aria-busy":y,children:[(0,r.jsxs)("header",{className:"flex min-h-12 items-center gap-3 border-b border-border bg-bg px-3",children:[(0,r.jsx)("h1",{id:c,className:"m-0 text-sm font-semibold text-text",children:p("efficiency.title")}),(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate text-right font-mono text-[11px] tabular-nums text-text-dim",children:k}),(0,r.jsx)(a.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>{"governor"===n?h.refreshRuns():h.refreshExperiments(void 0,b)},disabled:y,children:w})]}),(0,r.jsx)("div",{className:"grid grid-cols-2 border-b border-border bg-bg",role:"tablist","aria-label":p("efficiency.title"),children:["governor","lab"].map(e=>(0,r.jsx)("button",{type:"button",role:"tab","aria-selected":n===e,id:`${u}-${e}-tab`,"aria-controls":u,className:d_("min-h-10 border-0 border-r border-border bg-bg px-4 text-sm text-text-muted last:border-r-0 hover:bg-bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent",n===e&&"bg-bg-selected font-semibold text-text"),onClick:()=>s(e),children:"governor"===e?p("efficiency.governor"):p("efficiency.lab")},e))}),"lab"===n?(0,r.jsxs)("div",{className:"efficiency-folderbar",children:[(0,r.jsx)("label",{className:"efficiency-folder-label",htmlFor:`${u}-folder`,children:p("efficiency.folder")}),(0,r.jsxs)("select",{id:`${u}-folder`,className:"efficiency-folder-select",value:v??"",onChange:e=>{let t=""===e.target.value?null:e.target.value;f(t??""),h.refreshExperiments(t,b)},children:[(0,r.jsx)("option",{value:"",children:p("efficiency.folderAll")}),g.map(e=>(0,r.jsx)("option",{value:e,children:e},e)),v&&!g.includes(v)?(0,r.jsx)("option",{value:v,children:v}):null]}),(0,r.jsx)("input",{className:"efficiency-folder-input",value:m,placeholder:p("efficiency.folderPlaceholder"),"aria-label":p("efficiency.folder"),onChange:e=>f(e.target.value),onKeyDown:e=>{if("Enter"===e.key){let e=""===m.trim()?null:m.trim();h.refreshExperiments(e,b)}}}),(0,r.jsxs)("div",{className:"col-span-full flex flex-col items-start gap-2",children:[(0,r.jsx)(o.f,{variant:"neutralWeak",size:"xsmall",pressed:"attributed"===b,onPressedChange:e=>h.refreshExperiments(void 0,e?"attributed":"all"),children:p("efficiency.scopeAttributed")}),(0,r.jsx)(oI.E,{tone:"attributed"===b?"informative":"neutral",variant:"weak",size:"medium",children:p("attributed"===b?"efficiency.scopeAttributed":"efficiency.scopeAll")})]})]}):null,(0,r.jsx)("div",{id:u,className:"min-h-0 flex-1 overflow-y-auto overscroll-contain",role:"tabpanel","aria-labelledby":`${u}-${n}-tab`,children:"governor"===n?t?"idle"===h.list.status||"loading"===h.list.status?(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:p("efficiency.loadingRuns")}):"error"===h.list.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsx)("div",{className:"font-medium",children:p("efficiency.runsError")}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:h.list.error})]}):"empty"===h.list.status?(0,r.jsx)("p",{className:"efficiency-empty",children:p("efficiency.runsEmpty")}):(0,r.jsxs)("div",{className:"efficiency-governor",children:[(0,r.jsx)("ul",{className:"efficiency-run-list",children:h.list.runs.map(e=>(0,r.jsx)(dZ,{run:e,selected:h.selectedRunId===e.runId,onSelect:()=>h.selectRun(h.selectedRunId===e.runId?null:e.runId),t:p},e.runId))}),(0,r.jsx)("div",{className:"efficiency-detail-pane",children:null===h.selectedRunId||"idle"===h.detail.status?(0,r.jsx)("p",{className:"efficiency-empty",children:p("efficiency.selectRun")}):"loading"===h.detail.status?(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:p("efficiency.loadingDetail")}):"error"===h.detail.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsx)("div",{className:"font-medium",children:p("efficiency.detailError")}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:h.detail.error})]}):h.detail.detail?(0,r.jsx)(d0,{detail:h.detail.detail,t:p}):null})]}):(0,r.jsx)("p",{className:"efficiency-empty",children:p("efficiency.noSession")}):(()=>{if("idle"===h.experiments.status||"loading"===h.experiments.status)return(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:p("efficiency.loadingExperiments")});if("error"===h.experiments.status)return(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsx)("div",{className:"font-medium",children:p("efficiency.experimentsError")}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:h.experiments.error})]});let e=h.experiments.response;return"empty"!==h.experiments.status&&e?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"efficiency-note",children:p("efficiency.difficultyNote")}),(0,r.jsxs)("div",{className:"efficiency-stack",children:[(0,r.jsx)(d2,{response:e,t:p}),e.configs.map(e=>(0,r.jsx)(d4,{config:e,baselineRuns:x,t:p},e.signature))]})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"efficiency-empty",children:p("efficiency.experimentsEmpty")}),e?(0,r.jsx)("div",{className:"efficiency-stack",children:(0,r.jsx)(d2,{response:e,t:p})}):null,(0,r.jsx)("p",{className:"efficiency-note",children:p("efficiency.difficultyNote")})]})})()})]})}function d8(e){return"message"===e.type&&"message"in e}function d6(e){let t=e,n=t.branchPreview,r=d8(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&d8(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function d3({node:e,activePathIds:t,depth:n,isLast:i,parentLines:s,onSelect:a}){let{node:l,skipped:o,branchPreview:d,labelEntry:c}=d6(e),u=t.has(l.entry.id),p=t.has(e.entry.id)||t.has(l.entry.id),h=d?.text??function(e){if("message"===e.type&&"message"in e){let t=e.message,n=t.content,r="";if("string"==typeof n?r=n:Array.isArray(n)&&(r=n.filter(e=>"text"===e.type).map(e=>e.text).join(" ")),r.length>40&&(r=r.slice(0,40)+"…"),r)return r;if("assistant"===t.role)return"[assistant]"}return e.type}(c),m=d?d.role??null:d8(c)?c.message.role:null;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:"pointer"},onClick:()=>a(l.entry.id),children:[s.map((e,t)=>(0,r.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,r.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:i?"50%":0,width:1,background:"var(--border)"}}),(0,r.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,r.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:u?"var(--accent)":p?"var(--text-muted)":"var(--border)",border:u?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),m&&(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===m?"var(--accent)":"var(--text-dim)",background:"user"===m?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===m?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===m?"U":"A"}),o>0&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",o]}),(0,r.jsx)("span",{style:{fontSize:11,color:u?"var(--text)":p?"var(--text-muted)":"var(--text-dim)",fontWeight:u?500:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:h})]}),l.children.map((e,o)=>(0,r.jsx)(d3,{node:e,activePathIds:t,depth:n+1,isLast:o===l.children.length-1,parentLines:[...s,!i],onSelect:a},e.entry.id))]})}function d7({tree:e,activeLeafId:t,onLeafChange:n,hasSession:s}){let{t:a}=(0,R.s)(),l=(0,i.useMemo)(()=>t?new Set(function e(n,r){for(let i of n){let n=[...r,i.entry.id];if(i.entry.id===t||i.compressedEntryIds?.includes(t))return n;let s=e(i.children,n);if(s)return s}return null}(e,[])??[]):new Set,[e,t]),o=(0,i.useCallback)(e=>{n(e)},[n]),d=s?!function e(t){if(t.length>1)return!0;for(let n of t)if(n.children.length>1||e(n.children))return!0;return!1}(e)?a("i18n.noBranches"):null:a("i18n.noActiveSession"),c=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=d6(e[0]).node;return t.children.length>1?t.children:[]}(e);return!d&&c.length>0?(0,r.jsx)("div",{className:"branch-navigator-tree",children:c.map((e,t)=>(0,r.jsx)(d3,{node:e,activePathIds:l,depth:0,isLast:t===c.length-1,parentLines:[],onSelect:o},e.entry.id))}):(0,r.jsx)("p",{className:"branch-navigator-empty",children:d??a("i18n.noBranches")})}function d9(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e)}function ce(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function ct(e){let t=e.currentTime;[523.25,659.25].forEach((n,r)=>{let i=e.createOscillator(),s=e.createGain();i.connect(s),s.connect(e.destination),i.type="sine",i.frequency.value=n;let a=t+.18*r;s.gain.setValueAtTime(0,a),s.gain.linearRampToValueAtTime(.18,a+.02),s.gain.exponentialRampToValueAtTime(.001,a+.45),i.start(a),i.stop(a+.45)})}async function cn(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status}`);return t.arrayBuffer()}function cr(e){let t,n=e.window?.durationMs;if("number"==typeof n&&Number.isFinite(n)&&n>0)return n>=5184e5?"weekly":n<=432e5?"short":"other";let r=(t=e.scope?.windowId,`${"string"==typeof t?t:""} ${e.id} ${e.label??""}`.toLowerCase());return/(^|[^0-9])7d\b|week|7 day|주간/.test(r)?"weekly":/(^|[^0-9])(5h|1h)\b|hour|시간/.test(r)?"short":"other"}function ci(e){let t=e.amount?.usedFraction;return"number"==typeof t&&Number.isFinite(t)?Math.round(100*t):null}function cs(e){let t=ci(e);return(0,tX.xL)(e)||"warning"===e.status||null!==t&&t>=90}let ca="omp-sidebar-usage-collapsed";function cl(e){let t=e.amount?.usedFraction;return"number"==typeof t&&Number.isFinite(t)?t:null}function co(e){let t=new Date(e);return`${t.getMonth()+1}/${t.getDate()}`}function cd({usage:e,onOpen:t}){var n;let s,a,l,{t:o}=(0,R.s)(),d=F(),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(!0);(0,i.useEffect)(()=>{try{h("0"!==window.localStorage.getItem(ca))}catch{}},[]);let m=e.bai,f=e.state.data?.reports??[],g=o5(1e4),x=(s=(0,tX.k)(f),a=[],l=[],f.forEach((e,t)=>{if(!0===e.disabled)return;let n=s[t],r="number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>g,i=(e.limits??[]).some(e=>e.scope?.shared===!0&&(0,tX.xL)(e)),o=(e.limits??[]).some(e=>null!==cl(e)&&"short"!==cr(e));for(let t of e.limits??[]){let s=cl(t);if(null===s||o&&"short"===cr(t)&&!cs(t))continue;let d=r?"blocked":i?"account-spent":(0,tX.xL)(t)?"spent":"usable",c={key:`${e.provider}:${e.credentialId??n.seed}:${t.id}`,account:n.alias,seed:n.seed,provider:e.provider,label:t.label||t.id,percent:Math.round(100*s),state:d};("usable"===d?a:l).push(c)}}),[...a,...l]),v=c?x:x.slice(0,2),b=x.length-v.length,y="measured"===m.status?(n=m.tokens)>=1e9?`${(n/1e9).toFixed(1)}B`:n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1e3?`${Math.round(n/1e3)}K`:String(Math.round(n)):o("empty"===m.status?"usage.baiEmpty":"usage.baiUnmeasured"),w="measured"===m.status&&null!==m.from&&null!==m.to?o("usage.baiRange",{from:co(m.from),to:co(m.to)}):null,k=e=>"usable"===e.state?null:o("blocked"===e.state?"usage.accountBlocked":"account-spent"===e.state?"usage.accountSpent":"usage.limitSpent"),j=o("usage.open",{rows:[...v.map(e=>{let t=k(e);return`${e.account} ${e.label} ${e.percent}%${null===t?"":` (${t})`}`}),`${o("usage.bai")} ${y}${null===w?"":` \xb7 ${w}`}`].join(", ")})+(b>0?o("usage.openMore",{count:b}):""),S=0===x.length?{label:o("usage.bai"),value:y,danger:!1}:{label:x[0].label,value:`${x[0].percent}%`,danger:x[0].percent>=90},C=(0,r.jsxs)("div",{role:"button",tabIndex:0,className:"navigator-usage",onClick:t,onKeyDown:e=>{e.target!==e.currentTarget||("Enter"===e.key||" "===e.key)&&(" "===e.key&&e.preventDefault(),t())},"aria-label":j,children:[0===v.length?(0,r.jsx)("span",{className:"navigator-usage-empty",children:o("usage.none")}):v.map(e=>(0,r.jsxs)("span",{className:"navigator-usage-row",children:[(0,r.jsxs)("span",{className:"navigator-usage-head",children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:e.label}),(0,r.jsxs)("span",{className:"navigator-usage-value",style:e.percent>=90?{color:"var(--danger)"}:void 0,children:[e.percent,"%"]})]}),(0,r.jsxs)("span",{className:"navigator-usage-account",children:[(0,r.jsx)(ni,{seed:e.seed,size:24,provider:e.provider}),e.account,null===k(e)?null:(0,r.jsx)("span",{className:"navigator-usage-state",children:k(e)})]}),(0,r.jsx)("span",{"aria-hidden":"true",className:"navigator-usage-track",children:(0,r.jsx)("span",{className:"navigator-usage-fill",style:{width:`${Math.max(0,Math.min(100,e.percent))}%`,background:e.percent>=90?"var(--danger)":"var(--metric)"}})})]},e.key)),(b>0||c)&&(0,r.jsx)("button",{type:"button",className:"navigator-usage-more","aria-expanded":c,onClick:e=>{e.stopPropagation(),u(e=>!e)},children:c?o("usage.showLess"):o("usage.showMore",{count:b})}),(0,r.jsxs)("span",{className:"navigator-usage-row",children:[(0,r.jsxs)("span",{className:"navigator-usage-head",children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:o("usage.bai")}),(0,r.jsx)("span",{className:"navigator-usage-value",style:"measured"===m.status?void 0:{color:"var(--text-dim)"},children:y})]}),null===w?null:(0,r.jsx)("span",{className:"navigator-usage-account",children:w})]})]});return d?(0,r.jsxs)("div",{className:"navigator-usage-shell",children:[(0,r.jsxs)("button",{type:"button",className:"navigator-usage-toggle","aria-expanded":!p,"aria-label":p?j:o("usage.showLess"),onClick:()=>{let e=!p;h(e);try{window.localStorage.setItem(ca,e?"1":"0")}catch{}},children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:p?S.label:o("usage.showLess")}),p&&(0,r.jsx)("span",{className:"navigator-usage-value",style:S.danger?{color:"var(--danger)"}:void 0,children:S.value}),(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:p?"rotate(0deg)":"rotate(180deg)"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})]}),p?null:C]}):C}let cc={snapshot:null,revision:0,streaming:new Map};function cu(e,t,n){if(0===e.size)return e;let r=new Set(n.map(e=>e.id)),i=new Map(e);for(let[n,s]of e)(s.generation<t||r.has(n))&&i.delete(n);return i.size===e.size?e:i}function cp(e,t){switch(t.type){case"snapshot":{let n=t.data;if(n.revision<e.revision)return e;let r="sse"===t.source?new Map:cu(e.streaming,n.run.generation,n.messages);return{snapshot:n,revision:n.revision,streaming:r}}case"state":{let n=t.data;if(!e.snapshot||n.revision<e.revision)return e;let r={...e.snapshot,revision:n.revision,room:n.room,members:n.members,run:n.run,loadError:n.loadError};return{snapshot:r,revision:n.revision,streaming:cu(e.streaming,n.run.generation,r.messages)}}case"message":{let n=t.data;if(!e.snapshot||n.revision<e.revision)return e;let r=function(e,t){let n=e.findIndex(e=>e.id===t.id);if(n>=0){let r=e.slice();return r[n]=t,r}let r=[...e,t];return e.length>0&&e[e.length-1].createdAt>t.createdAt&&r.sort((e,t)=>e.createdAt-t.createdAt),r}(e.snapshot.messages,n.message),i=e.streaming;if(i.has(n.message.id)){let e=new Map(i);e.delete(n.message.id),i=e}return{snapshot:{...e.snapshot,revision:n.revision,messages:r},revision:n.revision,streaming:i}}case"delta":{let n=t.data;if(!e.snapshot||n.generation<e.snapshot.run.generation||e.snapshot.messages.some(e=>e.id===n.messageId))return e;let r=e.streaming.get(n.messageId);if(r&&r.text===n.text&&r.generation===n.generation)return e;let i=new Map(e.streaming);return i.set(n.messageId,{messageId:n.messageId,memberId:n.memberId,text:n.text,generation:n.generation}),{...e,streaming:i}}}}let ch="/api/lounge";function cm(e){try{return JSON.parse(e.data)}catch{return null}}async function cf(e){try{let t=await e.json();if("string"==typeof t?.error&&t.error)return t.error}catch{}return`HTTP ${e.status}`}var cg=n(96607);let cx=["slow","normal","active"],cv=[5,10,20,30,60,120].filter(e=>e>=1&&e<=120);function cb({row:e,lt:t,locale:n,now:i,compact:s}){let a="weekly"!==e.kind?e.label:e.tier?t("lounge.usage.weeklyTier",{tier:e.tier}):t("lounge.usage.weekly"),l="blocked"===e.state?t("lounge.usage.blocked"):"spent"===e.state?t("lounge.usage.spent"):null,o=!s&&null!==e.resetsAt&&e.resetsAt>i?t("lounge.usage.resets",{when:(0,nt.fw)(new Date(e.resetsAt),n,new Date(i))}):null,d="usable"!==e.state;return(0,r.jsxs)("span",{className:"lounge-usage","data-compact":s?"true":void 0,"data-state":e.state,children:[(0,r.jsxs)("span",{className:"lounge-usage-head",children:[(0,r.jsx)("span",{className:"lounge-usage-label",children:a}),o?(0,r.jsx)("span",{className:"lounge-usage-reset",children:o}):null,l?(0,r.jsx)("span",{className:"lounge-usage-state",children:l}):null,(0,r.jsxs)("span",{className:"lounge-usage-value",children:[e.percent,"%"]})]}),s?null:(0,r.jsx)("span",{"aria-hidden":"true",className:"lounge-usage-track",children:(0,r.jsx)("span",{className:"lounge-usage-fill",style:{width:`${Math.max(0,Math.min(100,e.percent))}%`,background:d?"var(--danger)":"var(--metric)"}})})]})}function cy({member:e,lounge:t,usage:n,now:s,disabled:a}){let{lt:l,locale:o}=(0,U.H)(),d=(0,U.a)(e.alias,o),c=function(e,t,n){let r=t.account,i=[],s=[];if(r&&(r.selectionRequired||void 0===r.credentialId))return{selectionRequired:!0,primary:i,warnings:s};let a=(0,tX.k)(e);return e.forEach((e,l)=>{if(e.provider!==t.provider||(r?e.credentialId!==r.credentialId:a[l].alias!==t.alias)||!0===e.disabled)return;let o="number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>n,d=(e.limits??[]).flatMap(t=>{let n=ci(t);if(null===n)return[];let r=o?"blocked":(0,tX.xL)(t)?"spent":"warning"===t.status||n>=90?"warning":"usable",i=t.window?.resetsAt,s=t.scope?.tier??t.scope?.modelId;return[{row:{key:`${e.provider}:${e.credentialId??l}:${t.id}`,label:t.label||t.id,kind:cr(t),tier:"string"==typeof s&&s?s:null,percent:n,resetsAt:"number"==typeof i&&Number.isFinite(i)?i:null,state:r},alert:cs(t)}]}),c=d.filter(({row:e})=>"short"!==e.kind);c.length>0?(i.push(...c.map(({row:e})=>e)),s.push(...d.filter(({row:e,alert:t})=>"short"===e.kind&&t).map(({row:e})=>e))):i.push(...d.map(({row:e})=>e))}),{selectionRequired:!1,primary:i,warnings:s}}(n.state.data?.reports??[],e,s),u=e.weeklyUsage?[{key:`${e.id}:weekly`,label:l("lounge.usage.weekly"),kind:"weekly",tier:null,percent:Math.round(100*e.weeklyUsage.usedFraction),resetsAt:e.weeklyUsage.resetsAt??null,state:e.weeklyUsage.usedFraction>=1?"spent":"usable"}]:c.primary,p=null===n.state.data&&n.loading,h=l(`lounge.state.${e.state}`),m=`lounge-member-${e.id}-status`,f=t.snapshot?.room.participants??[],g=e.account,x=g?.credentialId,v=void 0!==x&&!g?.choices.some(e=>e.credentialId===x),b=void 0!==g&&(g.selectionRequired||void 0===x||v),y=void 0!==g&&g.choices.length>1,[w,k]=(0,i.useState)(!1),j=void 0!==g&&(b||y&&w),S=`lounge-member-${e.id}-account`,C=u.filter(e=>null===e.tier),N=[...u.filter(e=>null!==e.tier),...c.warnings];return(0,r.jsxs)("li",{className:"lounge-member","data-state":e.state,"data-enabled":e.enabled?"true":"false",children:[(0,r.jsxs)("span",{className:"lounge-member-face",children:[(0,r.jsx)(ni,{seed:e.seed,size:40,provider:e.provider}),(0,r.jsx)("span",{className:"lounge-member-dot","aria-hidden":"true"})]}),(0,r.jsxs)("span",{className:"lounge-member-body",children:[(0,r.jsxs)("span",{className:"lounge-member-head",children:[(0,r.jsxs)("span",{className:"lounge-member-title",children:[(0,r.jsx)("span",{className:"lounge-member-name",children:d}),(0,r.jsx)("span",{id:m,className:"lounge-member-state",children:h})]}),(0,r.jsxs)(cg.h.Root,{size:"16",tone:"neutral",className:"lounge-switch",checked:e.enabled,disabled:a,onCheckedChange:n=>{let r=n?[...f.filter(t=>t!==e.id),e.id]:f.filter(t=>t!==e.id);t.updateSettings({participants:r})},children:[(0,r.jsx)(cg.h.HiddenInput,{"aria-label":l("lounge.participate",{name:d}),"aria-describedby":m}),(0,r.jsx)(cg.h.Control,{children:(0,r.jsx)(cg.h.Thumb,{})})]})]}),e.reason?(0,r.jsx)("span",{className:"lounge-member-reason",children:e.reason}):null,C.length+N.length>0?(0,r.jsxs)("span",{className:"lounge-member-usage",children:[C.map(e=>(0,r.jsx)(cb,{row:e,lt:l,locale:o,now:s},e.key)),N.map(e=>(0,r.jsx)(cb,{row:e,lt:l,locale:o,now:s,compact:!0},e.key))]}):(0,r.jsx)("span",{className:"lounge-member-usage-empty",children:p?l("lounge.usage.loading"):c.selectionRequired?l("lounge.account.required"):l("lounge.usage.none")}),(0,r.jsxs)("span",{className:"lounge-member-meta",children:[(0,r.jsxs)("span",{className:"lounge-member-model",children:[(0,tX.bN)(e.provider)," \xb7 ",e.model]}),y&&!b?(0,r.jsx)("button",{type:"button",className:"lounge-member-account-toggle","aria-expanded":w,"aria-controls":S,onClick:()=>k(e=>!e),children:l("lounge.account.change")}):null]}),j&&g?(0,r.jsxs)("span",{className:"lounge-member-account",children:[(0,r.jsx)("label",{className:"sr-only",htmlFor:S,children:l("lounge.account.for",{name:d})}),(0,r.jsxs)("select",{id:S,className:"lounge-select",value:void 0===x?"":String(x),disabled:a||0===g.choices.length,"aria-describedby":"lounge-account-hint",onChange:n=>{let r=Number(n.target.value);Number.isInteger(r)&&(t.updateSettings({accountBindings:{[e.id]:r}}),k(!1))},children:[void 0===x?(0,r.jsx)("option",{value:"",disabled:!0,children:l("lounge.account.choose")}):null,v?(0,r.jsx)("option",{value:String(x),disabled:!0,children:l("lounge.account.missing",{id:x})}):null,g.choices.map(e=>(0,r.jsx)("option",{value:String(e.credentialId),children:e.label},e.credentialId))]})]}):null]})]})}function cw({lounge:e,usage:t,onOpenLounge:n,loungeOpen:i=!1}){var s;let a,{lt:l,locale:o}=(0,U.H)(),d=o5(1e4),c=e.snapshot,u=c?.room??null,p=c?.members??[],h=c?.loadError??null,m=e.pending.has("settings"),f=null===c||null!==h,g=p.filter(e=>e.enabled).length,x=new Intl.DateTimeFormat(o,{hour:"2-digit",minute:"2-digit"}),v=u&&!cv.includes(u.sleepAfterMinutes)?[...cv,u.sleepAfterMinutes].sort((e,t)=>e-t):cv,b=c?.run??null;return(0,r.jsxs)("div",{id:"navigator-lounge-panel",className:"lounge-panel",children:[(0,r.jsxs)("div",{className:"lounge-panel-room",children:[(0,r.jsxs)("div",{className:"lounge-panel-room-head",children:[(0,r.jsx)("span",{className:"lounge-panel-title",children:l("lounge.title")}),(0,r.jsxs)(cg.h.Root,{size:"24",tone:"neutral",className:"lounge-switch lounge-room-switch",checked:u?.enabled??!1,disabled:f||m,onCheckedChange:t=>{e.updateSettings({enabled:t})},children:[(0,r.jsx)(cg.h.Label,{className:"lounge-room-switch-label",children:u?.enabled?l("lounge.roomOn"):l("lounge.roomOff")}),(0,r.jsx)(cg.h.HiddenInput,{"aria-label":l("lounge.roomSwitch")}),(0,r.jsx)(cg.h.Control,{children:(0,r.jsx)(cg.h.Thumb,{})})]})]}),null===c?(0,r.jsx)("p",{className:"lounge-panel-note",role:e.loadError?"alert":"status",children:e.loadError?l("lounge.loadFailed",{error:e.loadError}):l("lounge.connecting")}):h?(0,r.jsx)("p",{className:"lounge-panel-note","data-tone":"danger",role:"alert",children:l("lounge.loadFailed",{error:h})}):u&&!u.enabled?(0,r.jsx)("p",{className:"lounge-panel-note",children:l("lounge.roomOffHint")}):u?.asleep?(0,r.jsx)("p",{className:"lounge-panel-note",children:l("lounge.asleep")}):null,"reconnecting"===e.connection&&null!==c?(0,r.jsx)("p",{className:"lounge-panel-note",role:"status",children:l("lounge.reconnecting")}):null,e.actionError?(0,r.jsx)("p",{className:"lounge-panel-note","data-tone":"danger",role:"alert",children:l("lounge.actionFailed",{error:e.actionError})}):null,n?(0,r.jsx)("button",{type:"button",className:"lounge-panel-open","aria-pressed":i,onClick:n,children:l("lounge.open")}):null]}),(0,r.jsxs)("div",{className:"lounge-panel-members",children:[(0,r.jsxs)("div",{className:"lounge-panel-section-head",children:[(0,r.jsx)("span",{children:l("lounge.members")}),p.length>0?(0,r.jsx)("span",{className:"lounge-panel-count",children:l("lounge.membersCount",{active:g,total:p.length})}):null]}),(0,r.jsx)("ul",{className:"lounge-member-list","aria-label":l("lounge.members"),children:p.map(n=>(0,r.jsx)(cy,{member:n,lounge:e,usage:t,now:d,disabled:f||m},n.id))}),p.some(e=>e.account)?(0,r.jsx)("p",{id:"lounge-account-hint",className:"lounge-panel-hint",children:l("lounge.account.hint")}):null]}),u?(0,r.jsxs)("div",{className:"lounge-panel-settings",role:"group","aria-label":l("lounge.settings"),children:[(0,r.jsx)("div",{className:"lounge-panel-section-head",children:(0,r.jsx)("span",{children:l("lounge.settings")})}),(0,r.jsxs)("div",{className:"lounge-setting",children:[(0,r.jsx)("span",{className:"lounge-setting-label",id:"lounge-pace-label",children:l("lounge.pace")}),(0,r.jsx)("div",{className:"lounge-segmented",role:"radiogroup","aria-labelledby":"lounge-pace-label",children:cx.map(t=>(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":u.pace===t,disabled:f||m,onClick:()=>{u.pace!==t&&e.updateSettings({pace:t})},children:l(`lounge.pace.${t}`)},t))})]}),(0,r.jsxs)("label",{className:"lounge-setting lounge-setting-inline",children:[(0,r.jsx)("span",{className:"lounge-setting-label",children:l("lounge.sleep")}),(0,r.jsx)("select",{className:"lounge-select",value:u.sleepAfterMinutes,disabled:f||m,onChange:t=>{e.updateSettings({sleepAfterMinutes:Number(t.target.value)})},children:v.map(e=>(0,r.jsx)("option",{value:e,children:l("lounge.sleepMinutes",{minutes:e})},e))})]}),(0,r.jsxs)("div",{className:"lounge-setting",children:[(0,r.jsxs)(cg.h.Root,{size:"16",tone:"neutral",className:"lounge-switch lounge-setting-switch",checked:u.autoTalk,disabled:f||m,onCheckedChange:t=>{e.updateSettings({autoTalk:t})},children:[(0,r.jsx)(cg.h.Label,{className:"lounge-setting-label",children:l("lounge.autoTalk")}),(0,r.jsx)(cg.h.HiddenInput,{"aria-describedby":"lounge-autotalk-hint"}),(0,r.jsx)(cg.h.Control,{children:(0,r.jsx)(cg.h.Thumb,{})})]}),(0,r.jsx)("span",{id:"lounge-autotalk-hint",className:"lounge-setting-hint",children:l("lounge.autoTalkHint")}),u.autoTalk&&u.autoTalkPausedReason?(0,r.jsx)("span",{className:"lounge-setting-hint","data-tone":"warning",role:"status",children:u.autoTalkPausedReason}):null]}),(0,r.jsxs)("div",{className:"lounge-panel-limits",children:[b?(0,r.jsx)("span",{children:l("lounge.calls",{window:(s=b.calls.windowMs,(a=Math.round(s/36e5))>=1?new Intl.NumberFormat(o,{style:"unit",unit:"hour",unitDisplay:"long"}).format(a):l("lounge.sleepMinutes",{minutes:Math.max(1,Math.round(s/6e4))})),used:b.calls.used,limit:b.calls.limit})}):null,b?(0,r.jsx)("span",{children:l("lounge.perTurn",{limit:b.perTurnLimit})}):null,u.enabled&&!u.asleep&&null!==u.sleepAt&&u.sleepAt>d?(0,r.jsx)("span",{children:l("lounge.sleepAt",{time:x.format(new Date(u.sleepAt))})}):null]})]}):null]})}let ck="cuelo-lounge-draft",cj=["\uD83D\uDC4D","❤️","\uD83D\uDE02","\uD83D\uDE2E","\uD83D\uDE4F","\uD83D\uDC40"],cS=Math.floor(1600),cC=[],cN=[];function cI(e,t){if(0===t.length)return e;let n=t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),i=RegExp(`(@(?:${n.join("|")}))`,"giu");return e.split(i).map((e,t)=>t%2==1?(0,r.jsx)("span",{className:"lounge-mention",children:e},t):e)}function cT({lounge:e,visible:t=!0,onBack:n}){let{lt:s,locale:l}=(0,U.H)(),o=e.snapshot,d=o?.room??null,c=o?.run??null,u=o?.members??cC,p=o?.messages??cN,h=o?.loadError??null,m=(0,i.useMemo)(()=>new Map(u.map(e=>[e.id,e])),[u]),f=(0,i.useMemo)(()=>new Map(p.map(e=>[e.id,e])),[p]),g=(0,i.useCallback)(e=>{if("user"===e)return s("lounge.you");let t=m.get(e);return t?(0,U.a)(t.alias,l):e},[l,s,m]),x=(0,i.useMemo)(()=>u.flatMap(e=>[(0,U.a)(e.alias,"ko"),(0,U.a)(e.alias,"en")]),[u]),v=(0,i.useMemo)(()=>new Intl.DateTimeFormat(l,{hour:"2-digit",minute:"2-digit"}),[l]),[b,y]=(0,i.useState)(""),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),I=(0,i.useRef)(null),T=(0,i.useRef)(null),M=(0,i.useRef)(!0),$=(0,i.useId)();(0,i.useEffect)(()=>{y(function(){try{return window.sessionStorage.getItem(ck)??""}catch{return""}}())},[]);let R=(0,i.useCallback)(e=>{y(e);try{e?window.sessionStorage.setItem(ck,e):window.sessionStorage.removeItem(ck)}catch{}},[]),E=e.streaming.map(e=>`${e.messageId}:${e.text.length}`).join("|");(0,i.useLayoutEffect)(()=>{let e=T.current;e&&t&&M.current&&(e.scrollTop=e.scrollHeight)},[p.length,E,t]),(0,i.useEffect)(()=>{let e=T.current;if(!e||"u"<typeof ResizeObserver)return;let t=new ResizeObserver(()=>{M.current&&(e.scrollTop=e.scrollHeight)});return t.observe(e),()=>t.disconnect()},[]),(0,i.useEffect)(()=>{t&&I.current?.focus({preventScroll:!0})},[t]);let L=(0,i.useMemo)(()=>{if(!j)return[];let e=j.query.toLowerCase();return u.filter(t=>!e||(0,U.a)(t.alias,"ko").toLowerCase().startsWith(e)||(0,U.a)(t.alias,"en").toLowerCase().startsWith(e)||t.id.startsWith(e))},[u,j]),A=d?.enabled===!0&&null===h&&null!==o,z=e.pending.has("send"),W=b.trim(),F=w?f.get(w)??null:null,P=e=>{if(!j)return;let t=(0,U.a)(e.alias,l),n=I.current,r=n?.selectionStart??b.length;R(`${b.slice(0,j.start)}@${t} ${b.slice(r)}`),S(null);let i=j.start+t.length+2;window.requestAnimationFrame(()=>{n?.focus(),n?.setSelectionRange(i,i)})},D=async()=>{!A||z||!W||W.length>2e3||await e.send(W,F?.id)&&(R(""),k(null),M.current=!0)},_=c?.active?c.currentMemberId:null,O=e.streaming.some(e=>e.memberId===_),H=c?.active?c.queuedMemberIds.map(g):[],B=(t,n,i,a)=>{let l="user"===n,o=m.get(n),d=a.message,c=d?.replyToId?f.get(d.replyToId)??null:null;return(0,r.jsxs)("div",{id:d?`lounge-message-${d.id}`:void 0,className:"lounge-bubble-row","data-mine":l?"true":void 0,"data-grouped":a.grouped?"true":void 0,"data-streaming":a.streaming?"true":void 0,children:[l?null:(0,r.jsx)("span",{className:"lounge-bubble-face",children:a.grouped||!o?null:(0,r.jsx)(ni,{seed:o.seed,size:32,provider:o.provider})}),(0,r.jsxs)("div",{className:"lounge-bubble-stack",children:[l||a.grouped?null:(0,r.jsx)("span",{className:"lounge-bubble-name",children:g(n)}),(0,r.jsxs)("div",{className:"lounge-bubble-line",children:[(0,r.jsxs)("div",{className:"lounge-bubble",children:[d?.replyToId?(0,r.jsxs)("button",{type:"button",className:"lounge-bubble-quote",onClick:()=>{document.getElementById(`lounge-message-${d.replyToId}`)?.scrollIntoView({block:"center",behavior:"smooth"})},children:[(0,r.jsx)("span",{className:"lounge-bubble-quote-name",children:c?g(c.memberId):s("lounge.missingMessage")}),(0,r.jsx)("span",{className:"lounge-bubble-quote-text",children:c?c.text:""})]}):null,(0,r.jsx)("div",{className:"lounge-bubble-text",children:i})]}),void 0!==a.createdAt?(0,r.jsx)("time",{className:"lounge-bubble-time",dateTime:new Date(a.createdAt).toISOString(),children:v.format(new Date(a.createdAt))}):null]}),d?(0,r.jsxs)("div",{className:"lounge-bubble-foot",children:[d.reactions.filter(e=>e.by.length>0).map(t=>(0,r.jsxs)("button",{type:"button",className:"lounge-reaction","aria-pressed":t.by.includes("user"),"aria-label":s("lounge.reaction",{emoji:t.emoji,count:t.by.length}),title:t.by.map(g).join(", "),disabled:!A,onClick:()=>{e.react(d.id,t.emoji)},children:[(0,r.jsx)("span",{"aria-hidden":"true",children:t.emoji}),(0,r.jsx)("span",{className:"lounge-reaction-count",children:t.by.length})]},t.emoji)),(0,r.jsxs)("span",{className:"lounge-bubble-actions",children:[(0,r.jsx)("button",{type:"button",className:"lounge-bubble-action",disabled:!A,onClick:()=>{k(d.id),I.current?.focus()},children:s("lounge.reply")}),(0,r.jsx)("button",{type:"button",className:"lounge-bubble-action","aria-expanded":C===d.id,disabled:!A,onClick:()=>N(e=>e===d.id?null:d.id),children:s("lounge.react")})]}),C===d.id?(0,r.jsx)("span",{className:"lounge-reaction-picker",role:"group","aria-label":s("lounge.react"),children:cj.map(t=>(0,r.jsx)("button",{type:"button",onClick:()=>{N(null),e.react(d.id,t)},children:t},t))}):null]}):null]})]},t)},q=_?s("lounge.speaking",{name:g(_)}):null;return(0,r.jsxs)("section",{className:"lounge-view","aria-label":s("lounge.title"),hidden:!t,children:[(0,r.jsxs)("header",{className:"lounge-view-header",children:[n?(0,r.jsx)(a.r,{variant:"ghost",size:"small",className:"lounge-view-back",onClick:n,children:s("lounge.back")}):null,(0,r.jsxs)("div",{className:"lounge-view-heading",children:[(0,r.jsx)("h2",{className:"lounge-view-title",children:s("lounge.title")}),(0,r.jsx)("span",{className:"lounge-view-room","data-on":d?.enabled?"true":"false",children:d?.enabled?s("lounge.roomOn"):s("lounge.roomOff")})]}),(0,r.jsx)("ul",{className:"lounge-view-faces","aria-label":s("lounge.members"),children:u.filter(e=>e.enabled).map(e=>(0,r.jsxs)("li",{className:"lounge-view-face","data-state":e.state,children:[(0,r.jsx)(ni,{seed:e.seed,size:24,provider:e.provider}),(0,r.jsx)("span",{className:"lounge-member-dot","aria-hidden":"true"}),(0,r.jsx)("span",{className:"sr-only",children:`${g(e.id)} ${s(`lounge.state.${e.state}`)}`})]},e.id))})]}),e.loadError&&!o?(0,r.jsx)("p",{className:"lounge-banner","data-tone":"danger",role:"alert",children:s("lounge.loadFailed",{error:e.loadError})}):null,h?(0,r.jsx)("p",{className:"lounge-banner","data-tone":"danger",role:"alert",children:s("lounge.loadFailed",{error:h})}):null,"reconnecting"===e.connection&&o?(0,r.jsx)("p",{className:"lounge-banner",role:"status",children:s("lounge.reconnecting")}):null,e.actionError?(0,r.jsxs)("p",{className:"lounge-banner","data-tone":"danger",role:"alert",children:[(0,r.jsx)("span",{children:s("lounge.actionFailed",{error:e.actionError})}),(0,r.jsx)("button",{type:"button",className:"lounge-banner-action",onClick:e.dismissActionError,"aria-label":"✕",children:"✕"})]}):null,!d||d.enabled||h?d?.asleep?(0,r.jsx)("p",{className:"lounge-banner",children:s("lounge.asleep")}):d?.autoTalk&&d.autoTalkPausedReason?(0,r.jsx)("p",{className:"lounge-banner",role:"status",children:d.autoTalkPausedReason}):null:(0,r.jsxs)("p",{className:"lounge-banner",children:[(0,r.jsx)("span",{children:s("lounge.roomOffBanner")}),(0,r.jsx)("button",{type:"button",className:"lounge-banner-action",disabled:e.pending.has("settings"),onClick:()=>{e.updateSettings({enabled:!0})},children:s("lounge.turnOn")})]}),(0,r.jsxs)("div",{ref:T,className:"lounge-log",role:"log","aria-label":s("lounge.messages"),onScroll:e=>{let t=e.currentTarget;M.current=t.scrollHeight-t.scrollTop-t.clientHeight<80},children:[o&&0===p.length&&0===e.streaming.length?(0,r.jsx)("p",{className:"lounge-empty",children:s("lounge.empty")}):null,o||e.loadError?null:(0,r.jsx)("p",{className:"lounge-empty",children:s("lounge.connecting")}),p.map((e,t)=>{let n=t>0?p[t-1]:null,r=null!==n&&n.memberId===e.memberId&&e.createdAt-n.createdAt<3e5&&!e.replyToId;return B(e.id,e.memberId,cI(e.text,x),{message:e,createdAt:e.createdAt,grouped:r})}),e.streaming.map(e=>B(`stream-${e.messageId}`,e.memberId,(0,r.jsxs)(r.Fragment,{children:[cI(e.text,x),(0,r.jsx)("span",{className:"lounge-caret","aria-hidden":"true"})]}),{grouped:!1,streaming:!0})),_&&!O?B(`typing-${_}`,_,(0,r.jsxs)("span",{className:"lounge-typing","aria-hidden":"true",children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{}),(0,r.jsx)("span",{})]}),{grouped:!1,streaming:!0}):null]}),(0,r.jsxs)("div",{className:"lounge-composer",children:[(0,r.jsxs)("div",{className:"lounge-composer-status",role:"status","aria-live":"polite",children:[q?(0,r.jsx)("span",{children:q}):null,H.length>0?(0,r.jsx)("span",{children:s("lounge.queued",{names:H.join(", ")})}):null]}),F?(0,r.jsxs)("div",{className:"lounge-reply-chip",children:[(0,r.jsxs)("span",{className:"lounge-reply-chip-text",children:[(0,r.jsx)("strong",{children:s("lounge.replyTo",{name:g(F.memberId)})}),(0,r.jsx)("span",{children:F.text})]}),(0,r.jsx)("button",{type:"button",className:"lounge-banner-action",onClick:()=>k(null),children:s("lounge.cancelReply")})]}):null,(0,r.jsxs)("div",{className:"lounge-composer-row",children:[j&&L.length>0?(0,r.jsx)("ul",{id:$,className:"lounge-mention-list",role:"listbox","aria-label":s("lounge.mentionList"),children:L.map((e,t)=>(0,r.jsxs)("li",{id:`${$}-${e.id}`,role:"option","aria-selected":t===j.index,onMouseDown:t=>{t.preventDefault(),P(e)},children:[(0,r.jsx)(ni,{seed:e.seed,size:20,provider:e.provider}),(0,r.jsx)("span",{children:(0,U.a)(e.alias,l)}),(0,r.jsx)("span",{className:"lounge-mention-state",children:s(`lounge.state.${e.state}`)})]},e.id))}):null,(0,r.jsx)("textarea",{ref:I,className:"lounge-composer-input",rows:1,value:b,maxLength:2e3,disabled:!A,placeholder:A?s("lounge.placeholder"):s("lounge.placeholderOff"),"aria-label":s("lounge.composer"),role:"combobox","aria-expanded":null!==j&&L.length>0,"aria-controls":$,"aria-autocomplete":"list","aria-activedescendant":j&&L[j.index]?`${$}-${L[j.index].id}`:void 0,onChange:e=>{var t;let n,r,i=e.target.value;R(i);let s=(t=e.target.selectionStart??i.length,n=i.slice(0,t),(r=/(^|\s)@([^\s@]*)$/u.exec(n))?{start:t-r[2].length-1,query:r[2]}:null);S(s?{...s,index:0}:null)},onBlur:()=>S(null),onKeyDown:e=>{if(!e.nativeEvent.isComposing){if(j&&L.length>0){if("ArrowDown"===e.key||"ArrowUp"===e.key){e.preventDefault();let t="ArrowDown"===e.key?1:-1;S({...j,index:(j.index+t+L.length)%L.length});return}if("Enter"===e.key||"Tab"===e.key){e.preventDefault(),P(L[Math.min(j.index,L.length-1)]);return}if("Escape"===e.key){e.preventDefault(),S(null);return}}if("Escape"===e.key&&w){e.preventDefault(),k(null);return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),D())}}}),c?.active?(0,r.jsxs)(a.r,{variant:"neutralOutline",size:"small",className:"lounge-composer-button lounge-stop-button",loading:e.pending.has("stop"),onClick:()=>{e.stop()},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10","aria-hidden":"true",children:(0,r.jsx)("rect",{width:"10",height:"10",rx:"2",fill:"currentColor"})}),s("lounge.stop")]}):null,(0,r.jsx)(a.r,{variant:"neutralSolid",size:"small",className:"lounge-composer-button",disabled:!A||!W||W.length>2e3,loading:z,onClick:()=>{D()},children:s("lounge.send")})]}),b.length>=cS?(0,r.jsx)("span",{className:"lounge-composer-counter",children:s("lounge.textLimit",{count:b.length,max:2e3})}):null]})]})}var cM=n(45926),c$=n(86110),cR=n(13994),cE=n(43796),cL=n.n(cE);let cA=[],cz={kind:"loading"};function cW({participant:e,sessionId:t,cwd:n,recipient:s,onBackToMain:a,onOpenFile:l,client:o}){let{ot:d}=(0,cR.v)(),c=(0,cM.Jg)(),u=c(e),p=(0,i.useMemo)(()=>o??(0,ng.Et)(),[o]),{snapshot:h}=e,m=(0,i.useMemo)(()=>[{key:e.key,liveId:h.id,status:h.status}],[e.key,h.id,h.status]),f=(0,io._Z)(m,{sessionId:t??"",client:p,enabled:!!t}).get(e.key),g=f?.state??cz,x="ready-archive"===g.kind,v=f?.entries??cA,b=(0,i.useMemo)(()=>"ready-live"===g.kind?g.entries:"ready-archive"===g.kind?(0,io.RO)(g.entries):v,[v,g]),y=(0,i.useMemo)(()=>b.flatMap(e=>"message"in e?[e.message]:[]),[b]),w=(0,i.useMemo)(()=>{let e=new Map;for(let t of y)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[y]),k=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let r of y)if("assistant"===r.role)for(let i of eQ(r.content,w,n))e.has(i.filePath)||(e.add(i.filePath),t.push(i));return t},[n,y,w]),[j,S]=(0,i.useState)("transcript"),C=(0,i.useId)(),N=(0,i.useRef)(null);(0,i.useEffect)(()=>{if("transcript"!==j)return;let e=requestAnimationFrame(()=>{let e=N.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[y.length,j]);let I=["transcript","files"],T=e=>{if("ArrowRight"!==e.key&&"ArrowLeft"!==e.key)return;e.preventDefault();let t=I[(I.indexOf(j)+1)%I.length];S(t),document.getElementById(`${C}-${t}-tab`)?.focus()},M=(0,io.Ch)(e.status)&&h.progress?.lastIntent?.trim()||null,$=e.agent?`${d("office.maker")} \xb7 ${e.agent}`:d("office.maker");return(0,r.jsxs)("section",{className:cL().maker,"aria-label":d("office.makerRecord",{name:e.name}),children:[(0,r.jsxs)("header",{className:cL().makerHeader,children:[(0,r.jsx)(cM.AT,{seat:e.seat,size:32}),(0,r.jsxs)("div",{className:cL().makerIdentity,children:[(0,r.jsx)("h2",{className:cL().makerName,children:e.name}),(0,r.jsxs)("p",{className:cL().makerMeta,children:[(0,r.jsx)("span",{className:cL().viewOnly,children:d("office.viewOnly")}),(0,r.jsx)("span",{children:$}),(0,r.jsx)("span",{className:cL().mono,children:e.model??d("office.modelUnknown")})]})]}),(0,r.jsxs)("span",{className:cL().status,"data-tone":u.tone,children:[(0,r.jsx)("span",{className:cL().dot,"aria-hidden":"true"}),u.status]})]}),(M||"completed"===e.status)&&(0,r.jsx)("p",{className:cL().makerNote,children:M?`${d("office.currentStep")} \xb7 ${M}`:d("office.notAccepted")}),(0,r.jsx)("div",{className:cL().tabs,role:"tablist","aria-label":e.name,children:I.map(e=>(0,r.jsx)("button",{id:`${C}-${e}-tab`,type:"button",role:"tab",className:cL().tab,"aria-selected":j===e,"aria-controls":`${C}-${e}-panel`,tabIndex:j===e?0:-1,onClick:()=>S(e),onKeyDown:T,children:"transcript"===e?d("office.tabTranscript"):d("office.tabFiles",{count:x?"?":k.length})},e))}),(0,r.jsx)("div",{ref:N,id:`${C}-${j}-panel`,role:"tabpanel","aria-labelledby":`${C}-${j}-tab`,className:cL().makerBody,children:"transcript"===j?(0,r.jsxs)(r.Fragment,{children:["loading"===g.kind&&(0,r.jsx)("p",{role:"status",className:cL().bodyNote,children:d("office.loading")}),"unreachable"===g.kind&&(0,r.jsx)("p",{role:"status",className:cL().bodyNote,children:g.message}),"error"===g.kind&&(0,r.jsx)("p",{role:"alert",className:cL().bodyNote,"data-tone":"failed",children:g.message}),"empty"===g.kind&&(0,r.jsx)("p",{role:"status",className:cL().bodyNote,children:g.note??d("office.transcriptEmpty")}),x&&(0,r.jsx)("p",{role:"status",className:cL().bodyNote,children:g.note??d("office.archiveNote")}),"ready-live"===g.kind&&y.map((e,t)=>(0,r.jsx)(rn,{message:e,toolResults:w,cwd:n,onOpenFile:l,showTimestamp:!0,prevTimestamp:y[t-1]?.timestamp},`${t}:${e.timestamp??0}`)),x&&g.entries.map((e,t)=>(0,r.jsxs)("div",{className:cL().archiveEntry,children:[(0,r.jsxs)("span",{className:cL().archiveRole,children:[e.role," \xb7 ",e.kind]}),e.text||d("office.transcriptEmpty")]},`${e.at??0}:${t}`))]}):x?(0,r.jsx)("p",{className:cL().bodyNote,children:d("office.filesArchive")}):0===k.length?(0,r.jsx)("p",{className:cL().bodyNote,children:d("office.filesEmpty")}):(0,r.jsx)("ul",{className:cL().files,children:k.map(e=>(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:cL().file,onClick:()=>l(e.filePath),title:e.filePath,children:[(0,r.jsx)("span",{className:cL().fileName,children:e6(e.filePath)}),(0,r.jsx)("span",{className:cL().filePath,children:e.filePath})]})},e.filePath))})}),(0,r.jsxs)("footer",{className:cL().makerFooter,children:[(0,r.jsx)("p",{className:cL().composerNote,children:d("office.composerNote",{name:c(s).name})}),(0,r.jsx)("button",{type:"button",className:cL().backButton,onClick:a,children:d("office.backToMain")})]})]})}var cF=n(67219),cP=n(14199);let cD="git pull && bun install && bun run build && node Tools/CUELO_Setup/files/native-runtime-patch.js --target .";function c_(e){return"unknown"===e?e:`v${e}`}function cO(){let{locale:e,t}=(0,R.s)(),n=F(),[s,a]=(0,i.useState)(null),[l,o]=(0,i.useState)("idle"),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),f=(0,i.useRef)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(null),[b,y]=(0,i.useState)(null),w=(0,i.useCallback)(()=>{let e=g.current?.getBoundingClientRect();if(!e)return;let t=window.visualViewport?.height??window.innerHeight,{side:n,maxHeight:r}=i1(e.top,e.bottom,t,i2(t,.72,620),{margin:12,minHeight:0}),i=Math.min(430,window.innerWidth-24),s=Math.max(12,window.innerWidth-i-12);y({left:Math.min(e.right+8,s),width:i,maxHeight:r,..."above"===n?{bottom:t-e.top+8}:{top:e.bottom+8}})},[]);(0,i.useEffect)(()=>d?(w(),window.addEventListener("resize",w),window.addEventListener("scroll",w,!0),window.visualViewport?.addEventListener("resize",w),window.visualViewport?.addEventListener("scroll",w),()=>{window.removeEventListener("resize",w),window.removeEventListener("scroll",w,!0),window.visualViewport?.removeEventListener("resize",w),window.visualViewport?.removeEventListener("scroll",w)}):void y(null),[d,w]);let k=(0,i.useCallback)(async e=>{o("loading");try{let t=await fetch("/api/updates",{cache:"no-store",signal:e});if(!t.ok)return;let n=await t.json();a(n),o("ready")}catch{e?.aborted||o("ready")}},[]);if((0,i.useEffect)(()=>{let e=new AbortController;return k(e.signal),()=>e.abort()},[k]),(0,i.useEffect)(()=>()=>{clearTimeout(f.current??void 0),f.current=null},[]),(0,i.useEffect)(()=>{if(!d)return;let e=e=>{g.current?.contains(e.target)||x.current?.contains(e.target)||c(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),c(!1),v.current?.focus({preventScroll:!0}))};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[d]),"ready"!==l||!s?.updateAvailable||!s.latestRelease)return null;let j=s.latestRelease,S=j.publishedAt?new Intl.DateTimeFormat(e,{dateStyle:"medium"}).format(new Date(j.publishedAt)):null,C=j.body.trim()||j.name,N=async e=>{try{await tz(e),clearTimeout(f.current??void 0),m(e),f.current=setTimeout(()=>m(null),1600)}catch{p(t("updates.copyFailed"))}};return(0,r.jsxs)("div",{ref:g,"data-dismissible-layer":d?"":void 0,style:{position:"relative",width:"100%"},children:[(0,r.jsxs)("button",{ref:v,type:"button","aria-expanded":d,"aria-haspopup":"dialog",onClick:()=>{c(e=>!e),p(null)},title:t("updates.availableTitle",{version:c_(j.version)}),style:{width:"100%",minHeight:n?44:34,display:"flex",alignItems:"center",justifyContent:"center",gap:8,padding:"7px 10px",border:"1px solid color-mix(in srgb, var(--warning) 54%, var(--border))",borderRadius:9,background:"color-mix(in srgb, var(--warning) 8%, transparent)",color:"var(--warning)",cursor:"pointer",fontSize:11,fontFamily:"var(--font-mono)",transition:"background 0.12s, border-color 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--warning) 14%, var(--bg-hover))",e.currentTarget.style.borderColor="var(--warning)"},onMouseLeave:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--warning) 8%, transparent)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--warning) 54%, var(--border))"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{width:6,height:6,borderRadius:"50%",background:"var(--warning)",boxShadow:"0 0 0 3px color-mix(in srgb, var(--warning) 14%, transparent)"}}),(0,r.jsx)("span",{children:t("updates.available")}),(0,r.jsx)("span",{style:{color:"var(--text)",fontVariantNumeric:"tabular-nums"},children:c_(j.version)})]}),d&&b&&(0,P.createPortal)((0,r.jsxs)("div",{ref:x,"data-dismissible-layer":"",role:"dialog","aria-label":t("updates.dialogTitle"),style:{position:"fixed",left:b.left,top:b.top,bottom:b.bottom,zIndex:700,width:b.width,maxHeight:b.maxHeight,display:"flex",flexDirection:"column",overflow:"hidden",border:"1px solid var(--border)",borderRadius:10,background:"var(--bg-panel)",boxShadow:"0 18px 46px rgba(0,0,0,0.28)"},children:[(0,r.jsxs)("div",{style:{padding:"13px 14px 11px",borderBottom:"1px solid var(--border)",background:"linear-gradient(135deg, color-mix(in srgb, var(--warning) 10%, var(--bg-panel)), var(--bg-panel) 65%)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontSize:10,letterSpacing:"0.08em",textTransform:"uppercase"},children:t("updates.dialogEyebrow")}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text)",fontSize:15,fontWeight:650},children:t("updates.dialogTitle")})]}),(0,r.jsx)("div",{style:{color:"var(--warning)",fontFamily:"var(--font-mono)",fontSize:12,fontVariantNumeric:"tabular-nums"},children:c_(j.version)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 14px",marginTop:9,color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{children:t("updates.current",{version:c_(s.currentAppVersion)})}),S&&(0,r.jsx)("span",{children:S})]})]}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"11px 14px 14px"},children:[(0,r.jsx)("div",{style:{marginBottom:7,color:"var(--text-dim)",fontSize:10,letterSpacing:"0.08em",textTransform:"uppercase"},children:t("updates.changelog")}),(0,r.jsx)("div",{className:"update-changelog",style:{color:"var(--text-muted)",fontSize:11,lineHeight:1.5},children:(0,r.jsx)(tD,{children:C})})]}),(0,r.jsxs)("div",{style:{flexShrink:0,padding:"10px 14px 12px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:9,marginBottom:10},children:(0,r.jsx)("a",{href:j.htmlUrl,target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",fontSize:11,textDecoration:"underline",textUnderlineOffset:3},children:t("updates.viewRelease")})}),(0,r.jsxs)("div",{style:{color:"var(--text-muted)",fontSize:11,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{marginBottom:7,color:"var(--text-dim)"},children:t("updates.manual")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,minWidth:0,marginTop:6,padding:"6px 7px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("code",{style:{flex:1,minWidth:0,overflowWrap:"anywhere",color:"var(--text)"},children:cD}),(0,r.jsx)("button",{type:"button",onClick:()=>void N(cD),title:h===cD?t("updates.commandCopied"):t("updates.copyCommand"),"aria-label":h===cD?t("updates.commandCopied"):t("updates.copyCommand"),style:{flex:"0 0 auto",width:n?44:24,height:n?44:24,padding:0,border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:h===cD?"var(--accent)":"var(--text-dim)",cursor:"pointer"},children:h===cD?(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]})]}),u&&(0,r.jsx)("div",{role:"alert",style:{marginTop:9,color:"var(--danger)",fontSize:11,lineHeight:1.45},children:u})]})]}),document.body)]})}let cH="pi-web:last-open-by-workspace";function cB(){try{return window.localStorage}catch{return null}}function cU(e){let t=e.getItem(cH);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function cq(e,t=cB()){if(t)try{let n=cU(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(cH):t.setItem(cH,JSON.stringify(n))}catch{}}let cV="button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])",cK="omp-web:wide-chat";function cJ(){try{return oK(window.localStorage)}catch{return oK(null)}}function cG({auxiliaryDeck:e,resourcePanel:t,variant:n="chat"}={}){var p,m,f,k;let j,S,C,N,I,T,M,$,E,L,A,F,P,D,_,O,H,B,U="office"===n,q=U?"/office":"/",V=(0,s.useRouter)(),K=(0,s.useSearchParams)(),[J]=(0,i.useState)(()=>{let e;return{requestedCwd:e=K.get("cwd")?.trim()||null,sessionId:e?null:K.get("session")}}),{preference:G,toggleTheme:Y}=tA(),{locale:Z,setLocale:X,t:Q,supportedLocales:ee}=(0,R.s)(),en=function(){let[e,t]=(0,i.useState)(null),[n,r]=(0,i.useState)(!1),s=(0,i.useCallback)(()=>{t("Notification"in window?Notification.permission:null)},[]);return(0,i.useEffect)(()=>{try{r("1"===window.localStorage.getItem(oj))}catch{}return s(),window.addEventListener("focus",s),()=>window.removeEventListener("focus",s)},[s]),{permission:e,dismissed:n,request:(0,i.useCallback)(()=>{"Notification"in window&&"default"===Notification.permission&&Notification.requestPermission().then(t,s)},[s]),dismiss:(0,i.useCallback)(()=>{r(!0);try{window.localStorage.setItem(oj,"1")}catch{}},[])}}(),er=(0,i.useSyncExternalStore)(z.subscribe,z.getSnapshot,W);(0,i.useEffect)(()=>{let e=window.visualViewport;if(!e)return;let t=document.documentElement,n=null,r=()=>{let r;n=null,!function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r}){let i=.01>Math.abs(r-1);return e&&i&&t-n>1}({hasFocusedEditable:(r=document.activeElement)instanceof HTMLElement&&(r.isContentEditable||"INPUT"===r.tagName||"SELECT"===r.tagName||"TEXTAREA"===r.tagName),innerHeight:window.innerHeight,viewportHeight:e.height,viewportScale:e.scale})?t.style.removeProperty("--app-viewport-height"):t.style.setProperty("--app-viewport-height",`${e.height}px`);let i=0!==window.scrollX||0!==window.scrollY,s=.01>Math.abs(e.scale-1);i&&s&&window.scrollTo(0,0)},i=()=>{null!==n&&window.cancelAnimationFrame(n),n=window.requestAnimationFrame(r)};return i(),e.addEventListener("resize",i),e.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("focusin",i),window.addEventListener("focusout",i),window.addEventListener("pageshow",i),()=>{e.removeEventListener("resize",i),e.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("focusin",i),window.removeEventListener("focusout",i),window.removeEventListener("pageshow",i),null!==n&&window.cancelAnimationFrame(n),t.style.removeProperty("--app-viewport-height")}},[]);let{soundEnabled:ei,onSoundToggle:es,playCueSound:ea,preloadCueSound:el,unlockAudio:eo,soundEnabledRef:ed}=function(){let[e,t]=(0,i.useState)(()=>{let e=localStorage.getItem("omp-sound-enabled");return null===e||"true"===e}),n=(0,i.useRef)(e);(0,i.useEffect)(()=>{n.current=e},[e]);let r=(0,i.useRef)(null),s=(0,i.useRef)(null),a=(0,i.useRef)(0),l=(0,i.useRef)(new Map),o=(0,i.useRef)(new Map),d=(0,i.useRef)(new Map),c=(0,i.useRef)(null),u=(0,i.useRef)(new Map),p=(0,i.useRef)(new Map),h=(0,i.useRef)(new Map),m=(0,i.useCallback)(e=>{let t=p.current.get(e);return t||(t=cn(e).catch(t=>{throw p.current.delete(e),t}),p.current.set(e,t)),t},[]),f=(0,i.useCallback)(()=>{if(r.current&&"closed"!==r.current.state)return r.current;try{r.current=new AudioContext}catch{return null}return r.current},[]),g=(0,i.useCallback)(()=>(c.current??=r1(),c.current),[]);(0,i.useEffect)(()=>{g()},[g]);let x=(0,i.useCallback)(async e=>{if(!e)return;let t=await g();for(let r of rJ){let i=r0(t,e,r);if(i){for(let e of i.stickers){if(h.current.has(e))continue;let t=new Image;t.decoding="async",t.src=e,h.current.set(e,t)}if(n.current)for(let e of i.voices)m(e).catch(()=>{})}}},[g,m]),v=(0,i.useCallback)(()=>{a.current+=1;let e=s.current;if(s.current=null,e)try{e.stop()}catch{}},[]),b=(0,i.useCallback)((e=!1)=>{if(!e&&!n.current)return;let t=f();t&&"suspended"===t.state&&t.resume().catch(()=>{})},[f]);(0,i.useEffect)(()=>{let e=()=>b(),t={capture:!0,passive:!0};return window.addEventListener("pointerdown",e,t),window.addEventListener("keydown",e,t),()=>{window.removeEventListener("pointerdown",e,t),window.removeEventListener("keydown",e,t)}},[b]);let y=(0,i.useCallback)(()=>{let e=!n.current;e?b(!0):v(),n.current=e,localStorage.setItem("omp-sound-enabled",String(e)),t(e)},[v,b]),w=(0,i.useCallback)(e=>{if(!n.current)return;let t=f();if(!t)return;v();let r=a.current,i=()=>{if(r===a.current&&n.current&&(!e||e()))try{ct(t)}catch{}};"suspended"===t.state?t.resume().then(i).catch(()=>{}):i()},[f,v]);return{soundEnabled:e,onSoundToggle:y,playCueSound:(0,i.useCallback)(async(e,t="done",r)=>{let i=await g(),c=null===t?null:r0(i,e,t),p=`${e??""}\u0000${t??""}`,h=c?r2(c.stickers,o.current.get(p)??null):null;null!==h&&o.current.set(p,h);let x=c?r2(c.voices,l.current.get(p)??null):null,b=x?c?.lines.get(x)??null:null;!x&&c&&null!==(b=r2(c.captions,d.current.get(p)??null))&&d.current.set(p,b);let y={sticker:h,text:b};if(!n.current||r&&!r())return y;let k=f();if(!k)return y;if(!x)return null!==t&&rY[t]||w(r),y;v();let j=a.current,S=()=>j!==a.current||!n.current||void 0!==r&&!r();return(async()=>{if(!("suspended"===k.state&&(await k.resume().catch(()=>{}),S())))try{let e=u.current.get(x);e||(e=m(x).then(e=>k.decodeAudioData(e.slice(0))).catch(e=>{throw u.current.delete(x),e}),u.current.set(x,e));let t=await e;if(S())return;let n=k.createBufferSource(),r=k.createGain();n.buffer=t,n.connect(r),r.connect(k.destination),r.gain.setValueAtTime(.82,k.currentTime),n.onended=()=>{s.current===n&&(s.current=null)},s.current=n,n.start(),l.current.set(p,x)}catch{if(S()||null!==t&&rY[t])return;try{ct(k)}catch{}}})(),y},[f,w,v,g,m]),preloadCueSound:x,unlockAudio:b,soundEnabledRef:n}}(),ec=function(){let[e,t]=(0,i.useState)({status:"idle",data:null,error:null}),[n,r]=(0,i.useState)(!0),[s,a]=(0,i.useState)(null),l=(0,i.useRef)(null),o=(0,i.useRef)(null),d=(0,i.useCallback)(()=>{o.current?.abort();let e=new AbortController;o.current=e,(0,tX.t6)({signal:e.signal}).then(t=>{e.signal.aborted||a(t)})},[]);(0,i.useEffect)(()=>{let e=(0,tX.oI)({onResult(e){t(e),r(!1)}});return l.current=e,e.start(),d(),()=>{e.stop(),o.current?.abort(),l.current===e&&(l.current=null)}},[d]);let c=(0,i.useCallback)(async()=>{let e=l.current;if(!e)return{status:"error",data:null,error:new tX.OO("사용량 폴링이 시작되지 않았습니다.","aborted")};r(!0),d();let t=await e.refresh();return r(!1),t},[d]);return{state:e,loading:n,refresh:c,setPaused:(0,i.useCallback)(e=>{l.current?.setPaused(e)},[]),bai:(0,i.useMemo)(()=>(function(e){let t=e?.data;if(!t)return{status:"unmeasured"};let n=t.models.filter(e=>"b-ai"===e.provider);return 0===n.length?{status:"empty"}:{status:"measured",tokens:n.reduce((e,t)=>e+t.tokens,0),from:"number"==typeof t.range?.from?t.range.from:null,to:"number"==typeof t.range?.to?t.range.to:null}})(s),[s])}}();p=ec.state.data?.reports,(0,i.useEffect)(()=>{!function(e){let t=e??t0,n=t.map(e=>[e.provider,e.credentialId??"",e.metadata?.accountId??"",e.metadata?.email??""].join("\0")).join("|");if(n===t2)return;t2=n;let r=(0,tX.k)(t),i=new Map;t.forEach((e,t)=>{let n=e.credentialId;if(!t3(n))return;let s=t7(e.provider,n);i.has(s)||i.set(s,{seed:r[t].seed,alias:r[t].alias})}),t6({faces:i,pins:t1.pins})}(p)},[p]);let[eu,ep]=(0,i.useState)(!1),[eh,em]=(0,i.useState)(!1),ef=function(e=!0){let[t,n]=(0,i.useReducer)(cp,cc),[r,s]=(0,i.useState)("connecting"),[a,l]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(()=>new Set),p=(0,i.useRef)(!1);p.current=null!==t.snapshot,(0,i.useEffect)(()=>{let t;if(!e)return;let r=!1,i=null,a=new AbortController;fetch(ch,{cache:"no-store",signal:a.signal}).then(async e=>{if(!e.ok)throw Error(await cf(e));let t=await e.json();r||(n({type:"snapshot",source:"get",data:t}),l(null))}).catch(e=>{r||a.signal.aborted||p.current||l(e instanceof Error?e.message:String(e))});let o=()=>{if(r)return;let e=new EventSource("/api/lounge/events");i=e,e.onopen=()=>{r||s("live")},e.onerror=()=>{r||(s("reconnecting"),e.readyState===EventSource.CLOSED&&(e.close(),t=window.setTimeout(o,3e3)))},e.addEventListener("snapshot",e=>{let t=cm(e);t&&!r&&(n({type:"snapshot",source:"sse",data:t}),l(null),s("live"))}),e.addEventListener("state",e=>{let t=cm(e);t&&!r&&n({type:"state",data:t})}),e.addEventListener("message",e=>{let t=cm(e);t&&!r&&n({type:"message",data:t})}),e.addEventListener("delta",e=>{let t=cm(e);t&&!r&&n({type:"delta",data:t})})};return o(),()=>{r=!0,a.abort(),window.clearTimeout(t),i?.close()}},[e]);let h=(0,i.useCallback)(async e=>{let t={...e,requestId:"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,roomId:"main"};u(t=>new Set(t).add(e.action));try{let e=await fetch(ch,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!e.ok)return d(await cf(e)),!1;let r=await e.json();return r?.snapshot&&n({type:"snapshot",source:"post",data:r.snapshot}),d(null),!0}catch(e){return d(e instanceof Error?e.message:String(e)),!1}finally{u(t=>{let n=new Set(t);return n.delete(e.action),n})}},[]),m=(0,i.useCallback)(e=>h({action:"settings",...e}),[h]),f=(0,i.useCallback)((e,t)=>h(t?{action:"send",text:e,replyToId:t}:{action:"send",text:e}),[h]),g=(0,i.useCallback)(()=>h({action:"stop"}),[h]),x=(0,i.useCallback)((e,t)=>h({action:"reaction",messageId:e,emoji:t}),[h]),v=(0,i.useCallback)(()=>d(null),[]),b=(0,i.useMemo)(()=>[...t.streaming.values()],[t.streaming]);return{snapshot:t.snapshot,streaming:b,connection:r,loadError:a,actionError:o,pending:c,updateSettings:m,send:f,stop:g,react:x,dismissActionError:v}}(eh),eg=(0,i.useRef)(new Set),ex=(0,i.useCallback)(()=>{ed.current&&ea(null,"done")},[ea,ed]),[ev,eb]=(0,i.useState)(null),[ey,ew]=(0,i.useState)(null),[ek,ej]=(0,i.useState)(null),eS=(0,i.useRef)(0),eC=(0,i.useRef)(null),[eN,eI]=(0,i.useState)(null),eT=(0,i.useRef)(0),eM=(0,i.useCallback)(e=>{eI(t=>t?.id===e?null:t)},[]),[e$,eR]=(0,i.useState)(!1);(0,i.useEffect)(()=>{try{eR("1"===window.localStorage.getItem(cK))}catch{}},[]);let eE=(0,i.useCallback)(()=>{eR(e=>{let t=!e;try{window.localStorage.setItem(cK,t?"1":"0")}catch{}return t})},[]),[eL,eA]=(0,i.useState)(null),[ez,eW]=(0,i.useState)(()=>J.requestedCwd?"validating":"idle"),[eF,eP]=(0,i.useState)(null),[eD,e_]=(0,i.useState)(0),[eO,eH]=(0,i.useState)(0),[eB,eU]=(0,i.useState)(0),[eq,eV]=(0,i.useState)(0),[eK,eJ]=(0,i.useState)(!1),[eG,eY]=(0,i.useState)(null),[eZ,eX]=(0,i.useState)(0),eQ=(0,i.useRef)(null),e0=(0,i.useRef)(null),[e1,e2]=(0,i.useState)(!1),[e4,e5]=(0,i.useState)(!1),[e8,e3]=(0,i.useState)(null),[e7,e9]=(0,i.useReducer)(g,h),[te,tt]=(0,i.useState)("characters"),[tn,tr]=(0,i.useState)("governor"),[ti,ts]=(0,i.useState)(()=>x(0)),[ta]=(0,i.useState)(cJ),[tl]=(0,i.useState)(oJ),[to,td]=(0,i.useState)([]),[tc,tu]=(0,i.useState)({sessions:[],complete:!1}),[tp,th]=(0,i.useState)(!1),[tm,tf]=(0,i.useState)(!1),[tg,tx]=(0,i.useState)(0),tv=(0,i.useRef)(null),tb=(0,i.useRef)(null),ty=(0,i.useRef)(null),tw=(0,i.useCallback)(()=>{tx(e=>e+1)},[]),tk=(0,i.useCallback)(e=>{e&&em(!0),ep(e),e||tw()},[tw]),tj=(0,i.useCallback)(e=>{tb.current=e},[]),tS=(0,i.useRef)(!1),[tC,tN]=(0,i.useState)(!1),tI=(0,i.useRef)(!1),tT=(0,i.useRef)(!1),tM=(0,i.useRef)(0),[t$,tR]=(0,i.useState)(!1),[tE,tL]=(0,i.useState)(!1),tW=(0,i.useRef)(null),[tF,tP]=(0,i.useState)(null),[tD,t_]=(0,i.useState)(null),tO=(0,i.useRef)(null),tH=(0,i.useRef)(!1);tO.current=tF,(0,i.useEffect)(()=>{tP(sD())},[]),(0,i.useEffect)(()=>{let e=!1,t=null,n=n=>{if(e||tS.current||"IDLE"===n.phase||!n.requestId||!n.stageHash)return;let r=`${window.location.pathname}${window.location.search}${window.location.hash}`,i=function(e){let t=iH();if(!t.ok)return{entered:!1,error:t.error};let n={schemaVersion:2,requestId:e.requestId,stageHash:e.stageHash,clientId:sP(),sessionId:e.sessionId,resumeUrl:e.resumeUrl};try{sessionStorage.setItem(sL,JSON.stringify(n))}catch(e){return{entered:!1,error:e instanceof Error?e.message:String(e)}}let r=new URLSearchParams({mode:"wait",requestId:n.requestId,stageHash:n.stageHash,clientId:n.clientId});return window.location.replace(`/api/update-maintenance?${r}`),{entered:!0}}({requestId:n.requestId,stageHash:n.stageHash,sessionId:ev?.id??null,resumeUrl:r});if(i.entered){tS.current=!0;return}t=i.error},r=async()=>{if(!e&&!tS.current)try{let i=tH.current?null:tO.current,s=await sO({sessionId:ev?.id??null,resumeUrl:`${window.location.pathname}${window.location.search}${window.location.hash}`,preservationError:t,update:i?{requestId:i.requestId,stageHash:i.stageHash}:null});tM.current=0;let a=!!(s.serverBootId&&tW.current&&s.serverBootId!==tW.current);if(tI.current||a){var r=ev?.id??null;iH();try{sessionStorage.setItem(sz,JSON.stringify({schemaVersion:1,sessionId:r,at:Date.now()}))}catch{}window.location.reload();return}s.serverBootId&&(tW.current=s.serverBootId),tT.current=!0,!e&&s.update&&(t_(s.update),s.update.cleanup&&"running"!==s.update.cleanup.status&&(tH.current=!0)),n(s)}catch{tM.current+=1,!e&&tT.current&&tM.current>=2&&(tI.current=!0,tN(!0))}},i=e=>{n(e.detail??{}),t&&r()};window.addEventListener("ompweb:update-maintenance",i),r();let s=window.setInterval(()=>void r(),2e3);return()=>{e=!0,window.clearInterval(s),window.removeEventListener("ompweb:update-maintenance",i)}},[ev?.id]),(0,i.useEffect)(()=>{if(!tC)return;let e=window.setTimeout(()=>tR(!0),12e4);return()=>window.clearTimeout(e)},[tC]),(0,i.useEffect)(()=>{(function(e,t=Date.now()){let n,r=sessionStorage.getItem(sz);if(!r)return!1;try{n=JSON.parse(r)}catch{n=null}return!n||1!==n.schemaVersion||"number"!=typeof n.at||t-n.at>6e4||null!==n.sessionId&&"string"!=typeof n.sessionId?(sessionStorage.removeItem(sz),!1):n.sessionId===e&&(sessionStorage.removeItem(sz),!0)})(ev?.id??null)&&tL(!0)},[ev?.id]),(0,i.useEffect)(()=>{if(!tE)return;let e=window.setTimeout(()=>tL(!1),8e3);return()=>window.clearTimeout(e)},[tE]);let tB=tF?.requestId??null,tU=tF?.dismissed??!0,tq=tD?.requestId??null,tV=tD?.deploymentCompleted??!1,tK=tD?.cleanup?.status??null;(0,i.useEffect)(()=>{if(!tB||tU||tq!==tB||!tV)return;let e=sF(tK);if(null===e)return;let t=window.setTimeout(()=>{tP(s_(tB))},e);return()=>window.clearTimeout(t)},[tB,tU,tq,tV,tK]),(0,i.useEffect)(()=>{let e=function(){let e=sessionStorage.getItem(sL);if(!e)return null;try{let t=JSON.parse(e);if(2!==t.schemaVersion||"string"!=typeof t.requestId||!/^[0-9a-f]{32}$/.test(t.requestId)||"string"!=typeof t.stageHash||!/^[0-9a-f]{64}$/.test(t.stageHash)||"string"!=typeof t.clientId||"string"!=typeof t.resumeUrl||null!==t.sessionId&&"string"!=typeof t.sessionId)return null;return t}catch{return null}}();if(!e||e.sessionId&&ev?.id!==e.sessionId)return;let t=!1;return sH(e).then(()=>{t||(tH.current=!1,tP(sD()),e_(e=>e+1),eU(e=>e+1))}).catch(()=>{}),()=>{t=!0}},[ev?.id]);let tJ=(0,i.useCallback)(e=>{if("Tab"!==e.key)return;let t=ty.current;if(!t)return;let n=Array.from(t.querySelectorAll(cV));if(0===n.length)return;let r=e.shiftKey?n[0]:n[n.length-1],i=document.activeElement;i!==r&&t.contains(i)||(e.preventDefault(),(e.shiftKey?n[n.length-1]:n[0]).focus())},[]),[tG,tY]=(0,i.useState)(!U),[tZ,tQ]=(0,i.useState)(!1),[t4,t5]=(0,i.useState)(!1),t8=(0,i.useRef)(tG),ne=(0,i.useRef)(!1),nt=(0,i.useRef)(!U),nn=(0,i.useRef)(null);t8.current=tG;let nr=(j=(m={clientPainted:tZ,compactWorkspace:er,requestedOpen:tG}).requestedOpen&&m.clientPainted,{laidOut:m.requestedOpen&&(!m.compactWorkspace||m.clientPainted),presented:j,drawer:j&&m.compactWorkspace}),ni=(0,i.useCallback)(e=>{ne.current=e,tY(e),e9(e?{type:"open-layer",layer:"navigator-drawer"}:{type:"close-layer"})},[]),ns=(0,i.useRef)(null),na=(0,i.useRef)(!1),nl=(0,i.useRef)(260),no=(0,i.useCallback)(()=>(function(e){let{viewportWidth:t,rightPanelOpen:n,rightPanelWidth:r}=e;if(t<=640)return 480;let i=t<960;return Math.min(480,t-(i?320:420)-(!i&&n?r:0))})({viewportWidth:window.innerWidth,rightPanelOpen:!1,rightPanelWidth:0}),[]),nd=function(e){let{ariaLabel:t,cssVariable:n,defaultWidth:r,getDefaultWidth:s,getMaxWidth:a,growthDirection:l,maxWidth:o,minWidth:d,storageKey:c,widthRef:u}=e,p=(0,i.useRef)(null),h=(0,i.useRef)(null),m=(0,i.useRef)(!1),[f,g]=(0,i.useState)(r),[x,v]=(0,i.useState)(!1),b=(0,i.useCallback)(()=>Math.min(o,Math.max(d,a())),[a,o,d]),y=(0,i.useCallback)(e=>{var t;let n,r;return t=b(),n=Number.isFinite(e)?e:d,r=Math.max(d,t),Math.round(Math.max(d,Math.min(r,n)))},[b,d]),w=(0,i.useCallback)(e=>{u.current=e,p.current?.style.setProperty(n,`${e}px`)},[n,u]),k=(0,i.useCallback)((e,t={})=>{let{forcePersist:n=!1,persist:r=!0}=t,i=y(e),s=i!==u.current;return w(i),g(i),r&&(s||n)&&ce(c,i),i},[w,y,c,u]),j=(0,i.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),S=(0,i.useCallback)(e=>{let t=h.current;if(t&&t.pointerId===e){h.current=null,j(t),v(!1),k(u.current,{forcePersist:!0});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[k,j,u]),C=(0,i.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=h.current;t&&S(t.pointerId);let n=e.currentTarget;n.focus({preventScroll:!0}),n.setPointerCapture(e.pointerId),h.current={pointerId:e.pointerId,startX:e.clientX,startWidth:u.current,target:n,previousCursor:document.body.style.cursor,previousUserSelect:document.body.style.userSelect},document.body.style.cursor="col-resize",document.body.style.userSelect="none",v(!0)},[S,u]),N=(0,i.useCallback)(e=>{let t=h.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void S(e.pointerId);e.preventDefault();let n="right"===l?1:-1,r=y(t.startWidth+(e.clientX-t.startX)*n);w(r),e.currentTarget.setAttribute("aria-valuenow",String(r)),e.currentTarget.setAttribute("aria-valuetext",`${r} px`)},[w,y,S,l]),I=(0,i.useCallback)(e=>{S(e.pointerId)},[S]),T=(0,i.useCallback)(e=>{S(e.pointerId)},[S]),M=(0,i.useCallback)(e=>{S(e.pointerId)},[S]),$=(0,i.useCallback)(()=>{k(s?.()??r,{forcePersist:!0})},[k,r,s]),R=(0,i.useCallback)(()=>{k(u.current)},[k,u]),E=(0,i.useCallback)(e=>{let t=e.shiftKey?32:12,n="right"===l?"ArrowRight":"ArrowLeft",r="right"===l?"ArrowLeft":"ArrowRight";e.key===n?(e.preventDefault(),k(u.current+t,{forcePersist:!0})):e.key===r?(e.preventDefault(),k(u.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),k(d,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),k(b(),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),$())},[k,b,l,d,$,u]);return(0,i.useEffect)(()=>{if(m.current)return;m.current=!0;let e=function(e){try{let t=window.localStorage.getItem(e);if(null===t)return null;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:null}catch{return null}}(c),t=k(e??s?.()??r,{persist:!1});null!==e&&e!==t&&ce(c,t)},[k,r,s,c]),(0,i.useEffect)(()=>{if(!m.current)return;k(u.current);let e=()=>{k(u.current)};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[k,u]),(0,i.useEffect)(()=>{if(!x)return;let e=()=>{let e=h.current;e&&S(e.pointerId)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[S,x]),(0,i.useEffect)(()=>()=>{let e=h.current;e&&(h.current=null,j(e))},[j]),{isResizing:x,panelRef:p,reclampWidth:R,resetWidth:$,separatorProps:{"aria-label":t,"aria-orientation":"vertical","aria-valuemax":b(),"aria-valuemin":d,"aria-valuenow":f,"aria-valuetext":`${f} px`,onDoubleClick:$,onKeyDown:E,onLostPointerCapture:M,onPointerCancel:T,onPointerDown:C,onPointerMove:N,onPointerUp:I,role:"separator",tabIndex:0},width:f}}({ariaLabel:Q("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:no,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"omp-sidebar-width",widthRef:nl}),nc=nd.reclampWidth;(0,i.useEffect)(()=>{let e=nn.current;if(e===er)return;t5(!0),null!==e&&(e?ne.current=t8.current:nt.current=t8.current),nn.current=er;let t=er?ne.current:nt.current;er?ni(t):tY(t);let n=0,r=requestAnimationFrame(()=>{n=requestAnimationFrame(()=>t5(!1))});return()=>{cancelAnimationFrame(r),n&&cancelAnimationFrame(n)}},[er,ni]),(0,i.useEffect)(()=>{tQ(!0)},[]),(0,i.useEffect)(()=>{let e=na.current;if(na.current=nr.drawer,nr.drawer){let e=nd.panelRef.current;if(!e||e.contains(document.activeElement))return;let t=requestAnimationFrame(()=>{e.querySelector(cV)?.focus()});return()=>cancelAnimationFrame(t)}if(!e)return;let t=0,n=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>{let e=document.activeElement;e&&e!==document.body||ns.current?.focus()})});return()=>{cancelAnimationFrame(n),t&&cancelAnimationFrame(t)}},[nr.drawer,nd.panelRef]),(0,i.useEffect)(()=>{nc()},[nc,e7.activeView]),(0,i.useEffect)(()=>{let e=tv.current;if(!e)return;let t=e=>{ts(t=>{let n=x(e);return t.navigator===n.navigator&&t.deck===n.deck?t:n})};t(e.getBoundingClientRect().width);let n=new ResizeObserver(e=>{let n=e[0]?.contentRect.width;"number"==typeof n&&t(n)});return n.observe(e),()=>n.disconnect()},[]),(0,i.useEffect)(()=>{if(!tg)return;let e=0,t=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>tb.current?.())});return()=>{cancelAnimationFrame(t),e&&cancelAnimationFrame(e)}},[tg]),(0,i.useEffect)(()=>{if("command-palette"!==e7.transientLayer)return;let e=ty.current;if(!e)return;let t=requestAnimationFrame(()=>{e.querySelector(cV)?.focus()});return()=>cancelAnimationFrame(t)},[e7.transientLayer]),(0,i.useEffect)(()=>{er||"navigator-drawer"!==e7.transientLayer||e9({type:"close-layer"})},[er,e7.transientLayer]),(0,i.useEffect)(()=>{let e=new AbortController;return tu(e=>({...e,complete:!1})),fetch("/api/sessions",{cache:"no-store",signal:e.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if(!Array.isArray(t.sessions))throw Error("Invalid session census");td(t.sessions),tu({sessions:t.sessions.map(e=>({id:e.id,modified:e.modified})),complete:!0})}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load the complete session census:",e)}),()=>e.abort()},[eD,ev?.id]);let nu=(0,i.useRef)(null),np=(0,i.useRef)(null),[nh,nm]=(0,i.useState)({sessionId:null,tree:[],leafId:null,navigation:0}),nf=(0,i.useRef)(null),nx=(0,i.useCallback)((e,t,n)=>{nf.current=n,nm(n=>{let r=nF.current;return n.sessionId!==r?{sessionId:r,tree:e,leafId:t,navigation:0}:{...n,tree:e,leafId:t}})},[]),nv=(0,i.useCallback)(e=>{nm(t=>t.leafId===e?t:{...t,navigation:t.navigation+1}),nf.current?.(e)},[]),[nb,ny]=(0,i.useState)(null),nw=(0,i.useCallback)(e=>{ny(e)},[]),[nk,nj]=(0,i.useState)(null),[nS,nC]=(0,i.useState)([]),[nN,nI]=(0,i.useState)(null),nT=function(e,{subagents:t,enabled:n}){let[r,s]=(0,i.useState)(cF.h7),[a,l]=(0,i.useState)("floor"),[o,d]=(0,i.useState)(cP.Jq);(0,i.useEffect)(()=>{s(cF.h7)},[e]);let c=(0,i.useCallback)(e=>{s(e),l("target")},[]),u=(0,i.useMemo)(()=>(0,ng.Et)(),[]),p=(0,i.useMemo)(()=>e?t.map(t=>({key:`${e}\u0000${t.id}`,liveId:t.id,status:t.status})):[],[e,t]),h=(0,io._Z)(p,{sessionId:e??"",client:u,enabled:n&&p.length>0});return{selected:r,select:c,pane:a,setPane:l,accounts:(0,i.useMemo)(()=>(function(e,t,n){let r=new Map;if(!e)return r;for(let i of t){let t=n.get(`${e}\u0000${i.id}`);if(!t)continue;let s=function(e){let{state:t}=e;return("ready-live"===t.kind?t.entries:"ready-archive"===t.kind?(0,io.RO)(t.entries):e.entries).flatMap(e=>"message"in e?[e.message]:[])}(t);s.some(e=>"assistant"===e.role)&&r.set(i.id,(0,cF.O2)(i,s))}return r})(e,t,h),[h,e,t]),view:o,setView:d}}(ev?.id??null,{subagents:nS,enabled:U}),{ot:nM}=(0,cR.v)(),[n$,nR]=(0,i.useState)(null),[nE,nL]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=new AbortController;return fetch("/api/settings",{cache:"no-store",signal:e.signal}).then(async t=>{if(!t.ok)return;let n=await t.json(),r=n.fields?.find(e=>"task.maxConcurrency"===e.path),i=r?.value??r?.defaultValue,s="number"==typeof i?i:"string"==typeof i?Number.parseInt(i,10):NaN;!e.signal.aborted&&Number.isFinite(s)&&s>0&&nR(s)}).catch(()=>{}),()=>e.abort()},[]);let[nA,nz]=(0,i.useState)({kind:"idle"}),nW=(0,i.useRef)(null),nF=(0,i.useRef)(ev?.id??null);nF.current=ev?.id??null;let nP=(0,i.useCallback)(e=>{nj(e)},[]),[nD,n_]=(0,i.useState)(null),nO=(0,i.useRef)(null),nH=(0,i.useCallback)((e,t)=>{tz(t).then(()=>{nO.current&&clearTimeout(nO.current),n_(e),nO.current=setTimeout(()=>n_(null),1400)})},[]);(0,i.useEffect)(()=>()=>{nO.current&&clearTimeout(nO.current),nW.current&&clearTimeout(nW.current)},[]),(0,i.useEffect)(()=>()=>eC.current?.abort(),[]);let[nB,nU]=(0,i.useState)(null),nq=(0,i.useCallback)(e=>{nU(e)},[]),[nV,nK]=(0,i.useState)(null),[nJ,nG]=(0,i.useState)(null),[nY,nZ]=(0,i.useState)(null),[nX,nQ]=(0,i.useState)(!1),[n0,n1]=(0,i.useState)("subagents"),n2=(0,i.useCallback)((e,t=!1)=>{e9({type:"select-view",view:e}),nG(null),er&&ni(!1),(t||"chat"===e)&&tw()},[er,tw,ni]),n4=(0,i.useCallback)(e=>{let t=e7.transientLayer===e;nG(null),er&&"navigator-drawer"===e7.transientLayer&&ni(!1),e9({type:"toggle-layer",layer:e}),t&&tw()},[er,tw,ni,e7.transientLayer]),n5=(0,i.useCallback)(()=>{if("chat"!==e7.activeView){n1(e7.activeView),n2("chat",!0);return}n2(n0,!0)},[n0,n2,e7.activeView]),n8=(0,i.useCallback)(()=>e1?(e4||(e2(!1),tw()),!0):eK?(eJ(!1),tw(),!0):nX?(nQ(!1),tw(),!0):nJ?(nG(null),tw(),!0):e7.transientLayer?("navigator-drawer"===e7.transientLayer&&ni(!1),e9({type:"close-layer"}),tw(),!0):"chat"!==e7.activeView&&(e9({type:"select-view",view:"chat"}),tw(),!0),[nX,nJ,e4,e1,tw,ni,eK,e7.activeView,e7.transientLayer]),n6=(0,i.useCallback)(e=>{e9({type:"close-layer"}),er&&ni(!1),nG(t=>t===e?null:e)},[er,ni]),n3=(0,i.useCallback)(()=>{e9({type:"close-layer"}),er&&ni(!1),nG("session")},[er,ni]),n7=(0,i.useCallback)(()=>{if(nG(null),er){let e="navigator-drawer"!==e7.transientLayer;ni(e),e||tw();return}e9({type:"close-layer"}),tY(e=>{let t=!e;return nt.current=t,t})},[er,tw,ni,e7.transientLayer]);(0,i.useEffect)(()=>{if(!nJ||!np.current)return;let e=()=>{let e=np.current.getBoundingClientRect();nZ({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(np.current),()=>t.disconnect()},[nJ]);let[n9,re]=(0,i.useState)([]),[rt,rn]=(0,i.useState)(null),rr=(0,i.useCallback)(()=>{("view-stack"===ti.deck||U)&&e9({type:"select-view",view:"chat"}),er&&ni(!1),tw()},[er,U,ti.deck,tw,ni]),ri=(0,i.useCallback)((e,t)=>{let n;nu.current?.insertText((n=t?`${e}/`:e).includes(" ")?`@"${n}" `:`@${n} `),rr()},[rr]),rs=(0,i.useCallback)((e,t,n)=>{let r,i,s,a;nu.current?.insertText((r=Math.max(1,Math.min(t,n)),i=Math.max(1,Math.max(t,n)),s=e.includes(" ")?`@"${e}"`:`@${e}`,a=r===i?`:${r}`:`:${r}-${i}`,`${s}${a} `)),rr()},[rr]),ra=J.sessionId,[rl,ro]=(0,i.useState)(null);tA({cwd:ev?.cwd??eL??rl,syncWithOmp:!0});let rd=(0,i.useRef)(null),[rc,ru]=(0,i.useState)(()=>!ra),rp=(0,i.useRef)(!1),rh=(0,i.useRef)(0),rm=(0,i.useCallback)(()=>{rh.current+=1},[]);(0,i.useEffect)(()=>{ev&&function(e,t,n=cB()){if(n)try{let r=cU(n);r[e]=t,n.setItem(cH,JSON.stringify(r))}catch{}}(ev.projectRoot??rd.current??ev.cwd,ev.id)},[ev]),(0,i.useEffect)(()=>{let e=J.requestedCwd;if(!e)return;let t=new AbortController;return eW("validating"),eP(null),fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e}),signal:t.signal}).then(async e=>{let t=await e.json().catch(()=>({}));if(!e.ok||!t.cwd)throw Error(t.error??`HTTP ${e.status}`);rp.current=!0,eA(t.cwd),eW("ready")}).catch(e=>{t.signal.aborted||(eP(e instanceof Error?e.message:String(e)),eW("error"))}),()=>t.abort()},[J]);let rf=(0,i.useCallback)(e=>{let t=++rh.current,n=function(e,t=cB()){if(!t)return null;try{let n=cU(t)[e];return"string"==typeof n&&n.length>0?n:null}catch{return null}}(e);n&&fetch("/api/sessions").then(e=>e.ok?e.json():null).then(r=>{if(t!==rh.current)return;let i=r?.sessions.find(e=>e.id===n);if(!i){r&&cq(e);return}(i.projectRoot??i.cwd)!==e?cq(e):(eb(i),eH(e=>e+1),new URLSearchParams(window.location.search).get("session")!==i.id&&V.replace(`?session=${encodeURIComponent(i.id)}`,{scroll:!1}))}).catch(()=>{})},[V]),rg=(0,i.useCallback)((e,t)=>{if(rm(),ro(e),!e)return;let n=t??e,r=rd.current??(ev?ev.projectRoot??ev.cwd:null);if(rd.current=n,rp.current){rp.current=!1;return}r!==n&&(eS.current+=1,eC.current?.abort(),eC.current=null,ew(null),ej(null),eb(null),eA(t=>t&&t!==e?null:t),eH(e=>e+1),nm({sessionId:null,tree:[],leafId:null,navigation:0}),ny(null),nG(null),re([]),rn(null),e9({type:"select-view",view:"chat"}),rf(n),V.replace(q,{scroll:!1}))},[q,V,ev,rm,rf]),rx=(0,i.useCallback)((e,t,n)=>{eA(null),ej(n),eb(e),nm({sessionId:e.id,tree:[],leafId:null,navigation:0}),eH(e=>e+1),ny(null),ru(!0),er&&!t&&(ni(!1),e9({type:"select-view",view:"chat"})),t&&(rp.current=!0),t||V.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[er,V,ni]),rv=(0,i.useCallback)((e,t=!1)=>{if(rd.current=e.projectRoot??e.cwd,rm(),!t&&ev){let t=(ev.projectRoot??ev.cwd)===(e.projectRoot??e.cwd);if(ev.id===e.id&&t){eS.current+=1,eC.current?.abort(),eC.current=null,ew(null),er&&ni(!1);return}}if(!t&&ey?.id===e.id)return;eS.current+=1;let n=eS.current;if(eC.current?.abort(),t||!ev){eC.current=null,ew(null),rx(e,t,null);return}let r=new AbortController;eC.current=r,ew(e);let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"});fetch(`/api/sessions/${encodeURIComponent(e.id)}?${i}`,{cache:"no-store",signal:r.signal}).then(async t=>{if(!t.ok)throw Error(`HTTP ${t.status}`);let r=await t.json();if(r.sessionId!==e.id)throw Error("Session preload returned the wrong session");eS.current===n&&rx(e,!1,r)}).catch(t=>{r.signal.aborted||eS.current!==n||(console.error("Failed to preload session before switching:",t),rx(e,!1,null))}).finally(()=>{eS.current===n&&(eC.current=null,ew(null))})},[rx,rm,er,ey?.id,ev,ni]),rb=(0,i.useCallback)((e,t)=>{eS.current+=1,eC.current?.abort(),eC.current=null,ew(null),ej(null),rm(),eb(null),eA(t),eH(e=>e+1),nm({sessionId:null,tree:[],leafId:null,navigation:0}),ny(null),nG(null),e9({type:"select-view",view:"chat"}),er&&ni(!1),V.replace(q,{scroll:!1})},[q,rm,er,V,ni]),ry=(0,i.useCallback)(e=>{let t=ev?.projectRoot??rd.current??ev?.cwd??rl;if(!t||!ev)return;let n=to.filter(e=>(e.projectRoot??e.cwd)===t),r=n.findIndex(e=>e.id===ev.id);if(r<0)return;let i=n[r+e];i&&(nG(null),e9({type:"close-layer"}),rv(i),tw())},[rl,to,rv,tw,ev]);f={onNewSession:e=>rb(`kb-${Date.now()}`,e),onToggleCommandPalette:()=>n4("command-palette"),onToggleNavigator:n7,onToggleResources:()=>n2("resource"===e7.activeView?"chat":"resource",!0),onSelectView:e=>n2(e,!0),onCycleView:(0,i.useCallback)(e=>{let t=(c.indexOf(e7.activeView)+e+c.length)%c.length;n2(c[t],!0)},[n2,e7.activeView]),onNavigateSession:ry,onEscape:n8,enabled:!eK&&!e1,activeCwd:rl},(S=(0,i.useRef)(f)).current=f,(0,i.useEffect)(()=>{let e=e=>{!function(e,t){if(e.defaultPrevented)return;let n=t.now?.()??Date.now();if(b||e.isComposing||229===e.keyCode||n-y<100)return;let r=e.target,i="u">typeof Element&&r instanceof Element?r:null,s=!!i?.closest("input, textarea, select, [contenteditable='true']");if("Escape"===e.key)return!i?.closest("[data-dismissible-layer], [data-capture-keys], [role='listbox'], [role='menu'], [role='combobox'][aria-expanded='true'], [aria-haspopup][aria-expanded='true']")&&(t.onEscape?.()?(e.preventDefault(),e.stopPropagation()):!(s||i?.closest("[role='dialog']"))&&v&&(e.preventDefault(),v()));if(i?.closest("[data-capture-keys]")||!1===t.enabled)return;let a=e.key.toLowerCase(),l=(e.ctrlKey||e.metaKey)&&!e.altKey;if(l&&!e.shiftKey&&"k"===a)return t.onToggleCommandPalette&&(e.preventDefault(),t.onToggleCommandPalette());if(l&&!e.shiftKey&&"b"===a)return t.onToggleNavigator&&(e.preventDefault(),t.onToggleNavigator());if(l&&!e.shiftKey&&"u"===a)return t.onToggleResources&&(e.preventDefault(),t.onToggleResources());if(l&&!e.shiftKey&&/^[1-7]$/.test(a)){if(!t.onSelectView)return;let n=c[Number(a)-1];return n&&(e.preventDefault(),t.onSelectView(n))}l&&e.shiftKey&&("Period"===e.code||"Comma"===e.code)?t.onCycleView&&(e.preventDefault(),t.onCycleView("Period"===e.code?1:-1)):!e.altKey||e.ctrlKey||e.metaKey||"ArrowUp"!==e.key&&"ArrowDown"!==e.key?e.ctrlKey&&e.altKey&&!e.metaKey&&"n"===a&&t.activeCwd&&t.onNewSession&&(e.preventDefault(),t.onNewSession(t.activeCwd)):t.onNavigateSession&&(e.preventDefault(),t.onNavigateSession("ArrowUp"===e.key?-1:1))}(e,S.current)},t=()=>w(!0),n=()=>w(!1);return window.addEventListener("compositionstart",t,{capture:!0}),window.addEventListener("compositionend",n,{capture:!0}),window.addEventListener("keydown",e,{capture:!0}),()=>{window.removeEventListener("keydown",e,{capture:!0}),window.removeEventListener("compositionstart",t,{capture:!0}),window.removeEventListener("compositionend",n,{capture:!0})}},[]);let rw=(0,i.useCallback)(e=>{fetch("/api/sessions",{cache:"no-store"}).then(e=>e.ok?e.json():null).then(t=>{let n=t?.sessions.find(t=>t.id===e);n&&eb(t=>t?.id===e?{...t,...n,transient:n.transient??!1}:t)}).catch(()=>{})},[]),rk=(0,i.useCallback)(e=>{rm(),eA(null),eb(e),e_(e=>e+1),rw(e.id),V.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[rm,V,rw]),rj=(0,i.useCallback)(({targetSession:e,title:t,body:n,tag:r})=>{"Notification"in window&&"granted"===Notification.permission&&sT({title:t,body:n,sessionUrl:e?`/?session=${encodeURIComponent(e.id)}`:"/",tag:r,onClick:()=>{window.focus(),e&&rv(e)}})},[rv]),rS=(0,i.useCallback)(e=>{e_(e=>e+1),eQ.current?.pending&&eX(e=>e+1),eU(e=>e+1),ev&&rw(ev.id),"completed"===e.outcome&&sN()&&rj({targetSession:ev,title:ev?.name??Q("i18n.sessionComplete"),body:Q("i18n.taskFinished")})},[rj,rw,ev,Q]),rC=(0,i.useCallback)(e=>{var t;sN()&&(t=eg.current,!(!sI(e)||t.has(e.id))&&(t.add(e.id),1)&&rj({targetSession:ev,title:Q("i18n.attentionNeeded"),body:"custom"===e.method?Q("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[rj,ev,Q]),rN=(0,i.useCallback)(async()=>{let e=ev?.id;if(e&&"naming"!==nA.kind){nW.current&&clearTimeout(nW.current),nG(null),nz({kind:"naming"});try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}/auto-name`,{method:"POST"}),n=await t.json().catch(()=>({}));if(!t.ok||!n.title)throw Error(n.error||`HTTP ${t.status}`);let r=n.title.trim();if(e_(e=>e+1),nF.current!==e)return;eb(t=>t?.id===e?{...t,name:r}:t),nj(t=>t?.sessionId===e?{...t,sessionName:r}:t),nz({kind:"success"}),nW.current=setTimeout(()=>nz({kind:"idle"}),1800)}catch(t){if(nF.current!==e)return;nz({kind:"error",message:t instanceof Error?t.message:String(t)}),nW.current=setTimeout(()=>nz({kind:"idle"}),5e3)}}},[nA.kind,ev?.id]);(0,i.useEffect)(()=>{nW.current&&clearTimeout(nW.current),nz({kind:"idle"})},[ev?.id]);let rI=(0,i.useCallback)(e=>{rm(),e_(e=>e+1),eH(e=>e+1),eA(null),eb(t=>({...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1})),rw(e),V.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1})},[rm,V,rw]),rT=(0,i.useCallback)(()=>{ru(!0)},[]),rM=(0,i.useCallback)(e=>{if(rm(),e_(e=>e+1),ev?.id===e){let e=ev.cwd;eb(null),eA(e??null),eH(e=>e+1),nm({sessionId:null,tree:[],leafId:null,navigation:0}),ny(null),nG(null),e9({type:"select-view",view:"chat"}),tw(),V.replace(q,{scroll:!1})}},[q,rm,tw,ev,V]),r$=(0,i.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,i=n?.modeHint,s=`file:${e}`;re(n=>{let a=n.find(e=>e.id===s);if(!a)return[...n,{id:s,label:t,filePath:e,sourceSessionId:r,initialDisplayMode:i}];let l=!r||a.sourceSessionId===r,o=!i||a.initialDisplayMode===i;return l&&o?n:n.map(e=>{if(e.id!==s)return e;let t={...e};return r&&(t.sourceSessionId=r),i&&(t.initialDisplayMode=i),t})}),rn(s),e9({type:"select-view",view:"files"}),nG(null),er&&ni(!1)},[er,ni]),rR=(0,i.useCallback)(e=>{r$(e,e6(e),{sourceSessionId:ev?.id??null})},[r$,ev?.id]),rE=(0,i.useCallback)(e=>{let t=n9.filter(t=>t.id!==e);re(t),rn(n=>n!==e?n:t.length>0?t[t.length-1].id:null),0===t.length&&"files"===e7.activeView&&n2("chat",!0)},[n9,n2,e7.activeView]),rL=(0,i.useCallback)(()=>{ev&&window.open(`/api/sessions/${encodeURIComponent(ev.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[ev]),rA=eL??(null===ev&&rl?rl:null),rz=null!==ev||null!==rA,rW="chat"!==e7.activeView,rF=ev?.cwd??rA,rP=rc&&!rz,rD=(0,i.useCallback)((e,t)=>{eQ.current=e,eY(e),e3(e.error?Q("trust.applyFailed",{error:e.error}):null),null!==t&&null===e.pending&&(t.trusted!==e.trusted||"revoke"===t.pending)&&(e.trusted&&e2(!1),eV(e=>e+1),eH(e=>e+1))},[Q]);(0,i.useEffect)(()=>{let e=e0.current!==rF;if(e0.current=rF,e&&(eQ.current=null,eY(null),e2(!1),e3(null)),!rF)return;let t=eQ.current,n=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(rF)}`,{signal:n.signal}).then(async e=>{let n=await e.json();if(!e.ok)throw Error(n.error??`HTTP ${e.status}`);rD(n,t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>n.abort()},[rD,rF,eZ]);let r_=(0,i.useCallback)(async e=>{if(rF&&!e4){e5(!0),e3(null);try{let t=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:rF,action:e})}),n=await t.json();if(!t.ok)throw Error(n.error??`HTTP ${t.status}`);let r=eQ.current;rD(n,r),(n.trusted||"cancel"===e)&&(e2(!1),tw())}catch(e){e3(e instanceof Error?e.message:String(e))}finally{e5(!1)}}},[rD,e4,rF,tw]),rO=n9.find(e=>e.id===rt)??null,rH=rl?e6(rl)||rl:null,rB=(ev?.name?.trim()||ev?.firstMessage?.trim()||(rA?Q("i18n.newSession"):rH)||"CUELO").replace(/\s+/g," ").trim(),rU=rB.length>96?`${rB.slice(0,93)}…`:rB,rq=rH?`${rU} — ${rH} — CUELO`:`${rU} — CUELO`,rV=U?`${nM("office.toOffice")} \xb7 ${rq}`:rq,rK=rH?`${rB} — ${rH}`:rB,rG=ev?.transient?`${rK} \xb7 ${Q("session.inMemory")}`:rK,rZ=nS.filter(e=>"pending"===e.status||"running"===e.status).length,rX=nE?Q("workspace.mainAttention"):tm?Q("workspace.mainWaiting"):tp?Q("workspace.mainWorking"):Q("workspace.mainIdle"),rQ=`${nE?"⚠":tm?"○":tp?"●":"○"} Main ${rX} \xb7 Sub ${rZ}${n$?`/${n$}`:""}`,r4=(0,i.useCallback)(e=>n2(e,!0),[n2]),r5=U?(0,cF.GM)({main:{provider:nN?.provider??null,modelId:nN?.modelId??null,face:nN?.face??null,state:nE?"attention":tm?"waiting":tp?"working":"idle"},subagents:nS,accounts:nT.accounts,resolveFace:(e,t)=>t9(void 0,e,t)}):null,r8=r5?(0,cF.nk)(r5,nT.selected):nT.selected,r6=r5?.participants.find(e=>"main"===e.kind),r3=r5?.participants.find(e=>"maker"===e.kind&&e.key===r8),r7=U?eu?"target":nT.pane:null,r9="floor"===r7,ie=rW&&(U||"view-stack"===ti.deck),it=ev?`?session=${encodeURIComponent(ev.id)}`:rA?`?cwd=${encodeURIComponent(rA)}`:"";(0,i.useEffect)(()=>{let e=()=>{document.title!==rV&&(document.title=rV)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[rV]);let ir="ko"===Z?{chat:"대화",process:"작업 과정",efficiency:"효율",subagents:"서브에이전트",files:"파일",resource:"캐릭터",sidechat:"사이드챗"}:{chat:"Chat",process:"Process",efficiency:"Efficiency",subagents:"Subagents",files:"Files",resource:"캐릭터",sidechat:"Side Chat"},ii="chat"!==e7.activeView,is=ii?ir[e7.activeView]:ir[n0],ia=(C=nB&&Number.isFinite(nB.contextWindow)&&nB.contextWindow>0?nB.contextWindow:null,N=nB&&"number"==typeof nB.tokens&&Number.isFinite(nB.tokens)?Math.max(0,nB.tokens):null,T=null===(I=nB&&"number"==typeof nB.percent&&Number.isFinite(nB.percent)?nB.percent:null!==N&&null!==C?N/C*100:null)?"normal":I>90?"critical":I>70?"warning":"normal",M=null===N?"?":d9(N),$=null===C?"?":d9(C),E=null===I?"?":`${I.toFixed(0)}%`,{level:T,percent:I,fillPercent:null===I?0:Math.min(100,Math.max(0,I)),readout:null===C?null:`${E} \xb7 ${M}/${$}`,usedLabel:M,limitLabel:$,percentLabel:E}),il=ia.readout,id=il?Q("chat.contextUsageTitle",{used:ia.usedLabel,limit:ia.limitLabel,percent:ia.percentLabel}):null,ic="critical"===ia.level?Q("chat.contextUsageCritical"):"warning"===ia.level?Q("chat.contextUsageWarning"):null,iu=(k=nk?.userMessages,!ev||ev.transient?"unsaved":("number"==typeof k?k:0)>0||ev.messageCount>0?null:"no-messages"),ip="unsaved"===iu?Q("title.unsaved"):"no-messages"===iu?Q("title.noMessages"):null,ih=ip??("error"===nA.kind?nA.message:null),im="naming"===nA.kind?Q("title.generating"):"success"===nA.kind?Q("title.updated"):"error"===nA.kind?Q("title.failed"):Q("title.generate"),ig=(0,r.jsxs)("div",{id:"workspace-file-view",className:"workspace-file-view",children:[(0,r.jsx)("div",{className:"workspace-file-tabs",children:(0,r.jsx)(aF,{tabs:n9,activeTabId:rt??"",onSelectTab:rn,onCloseTab:rE})}),(0,r.jsx)("div",{className:"workspace-file-content",children:rO?.filePath?(0,r.jsx)(az,{filePath:rO.filePath,cwd:rl??void 0,sourceSessionId:rO.sourceSessionId,gitRefreshKey:eB,initialDisplayMode:rO.initialDisplayMode,onMentionLines:rs,onAtMention:ri,onOpenFile:e=>r$(e,e6(e),{sourceSessionId:rO.sourceSessionId})}):(0,r.jsx)("div",{className:"workspace-file-empty",children:Q("files.noneOpen")})})]}),ix=(0,r.jsx)(db,{open:"resource"===e7.activeView,sessionId:ev?.id??null,activeTab:te,onTabChange:tt,usage:ec}),iv=(0,r.jsx)(d5,{open:"efficiency"===e7.activeView,sessionId:ev?.id??null,activeTab:tn,onTabChange:tr}),ib=(0,r.jsx)(oD,{title:ir.process,data:nV,onOpenFile:rR}),iy=ev?ev.path?ev.path:nk?.sessionId===ev.id&&nk.sessionFile?nk.sessionFile:null:null,iw=(0,r.jsx)(o4,{title:ir.sidechat,sessionId:ev?.id??null,sessionPath:iy,sessionName:ev?.name,historyStore:ta,flights:tl,sessionCensus:tc,visible:"sidechat"===e7.activeView}),ik=rW?(0,r.jsx)(oP,{activeView:e7.activeView,onViewChange:e=>n2(e),viewLabels:ir,sessionId:ev?.id??null,sessionPath:iy,sessionName:ev?.name,sessionCwd:ev?.cwd??rA??void 0,liveSubagents:nS,processSlot:ib,fileSlot:ig,sideChatSlot:iw,resourceSlot:t??ix,efficiencySlot:iv,visible:!0,onClose:()=>e9({type:"select-view",view:"chat"}),onReturnFocus:tw}):null,ij=e??ik,iS=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(et,{selectedSessionId:ey?.id??ev?.id??null,optimisticSession:ey??ev,onSelectSession:rv,onNewSession:rb,initialSessionId:ra,skipInitialProjectSelection:null!==J.requestedCwd,onInitialRestoreDone:rT,refreshKey:eD,onSessionDeleted:rM,selectedCwd:ev?.cwd??eL??null,onCwdChange:rg,onBackgroundTaskDone:ex,loungePanel:(0,r.jsx)(cw,{lounge:ef,usage:ec,loungeOpen:eu,onOpenLounge:er?()=>ni(!1):void 0}),loungeActive:eu,onLoungeActiveChange:tk}),(0,r.jsxs)("div",{className:"navigator-footer",style:{padding:"8px",flexShrink:0},children:[eu?null:(0,r.jsx)(cd,{usage:ec,onOpen:()=>{tt("usage"),n2("resource",!1)}}),(0,r.jsx)(cO,{}),(0,r.jsxs)("button",{className:"navigator-settings-action",onClick:()=>{nG(null),e9({type:"close-layer"}),er&&ni(!1),eJ(!0)},title:Q("common.settings"),style:{width:"100%",height:34,display:"flex",alignItems:"center",justifyContent:"center",gap:8,background:"none",border:"1px solid var(--border)",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontFamily:"var(--font-mono)",transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)",e.currentTarget.style.borderColor="var(--text-dim)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,r.jsx)("path",{d:"M19.4 15a1.7 1.7 0 0 0 .34 1.88l.06.06-2.83 2.83-.06-.06A1.7 1.7 0 0 0 15 19.4a1.7 1.7 0 0 0-1 .6 1.7 1.7 0 0 0-.4 1.1V21h-4v-.09A1.7 1.7 0 0 0 8.5 19.4a1.7 1.7 0 0 0-1.88.34l-.06.06-2.83-2.83.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-.6-1 1.7 1.7 0 0 0-1.1-.4H3v-4h.09A1.7 1.7 0 0 0 4.6 8.5a1.7 1.7 0 0 0-.34-1.88l-.06-.06 2.83-2.83.06.06A1.7 1.7 0 0 0 9 4.6a1.7 1.7 0 0 0 1-.6 1.7 1.7 0 0 0 .4-1.1V3h4v.09A1.7 1.7 0 0 0 15.5 4.6a1.7 1.7 0 0 0 1.88-.34l.06-.06 2.83 2.83-.06.06A1.7 1.7 0 0 0 19.4 9c.12.39.33.74.6 1 .3.28.69.42 1.1.4h.09v4h-.09A1.7 1.7 0 0 0 19.4 15Z"})]}),Q("common.settings")]})]})]}),iC=tF&&tD&&tD.requestId===tF.requestId&&tD.deploymentCompleted?tD:null,iN=iC?.cleanup??null,iI=iC&&!tF?.dismissed?function(e){if(!e)return{tone:"neutral",title:"업데이트 완료",detail:"임시 산출물 정리 상태를 확인하고 있습니다.",dismissible:!0,autoHideMs:null};let t=`${e.completedCount}/${e.totalCount} 완료`,n=`${Math.round(e.elapsedSeconds)}초 경과`;return"running"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 중",detail:`${t} \xb7 ${n} \xb7 현재 ${e.currentTarget??"대상 선택 중"}`,dismissible:!1,autoHideMs:null}:"failed"===e.status?{tone:"warning",title:"업데이트 완료 \xb7 산출물 정리 실패",detail:`${t} \xb7 ${n} \xb7 보존 ${e.keptCount}건 \xb7 실패 ${e.failureCount}건. 업데이트 자체는 성공했고 실패 증거는 보존했습니다.`,dismissible:!0,autoHideMs:sF(e.status)}:"pending-approval"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 승인 대기",detail:`${t} \xb7 ${n} \xb7 보존 ${e.keptCount}건. 삭제는 승인 후 실행합니다.`,dismissible:!0,autoHideMs:sF(e.status)}:"skipped"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 건너뜀",detail:`${t} \xb7 ${n}`,dismissible:!0,autoHideMs:sF(e.status)}:{tone:"positive",title:"업데이트 완료 \xb7 산출물 정리 완료",detail:`${t} \xb7 ${n}`,dismissible:!0,autoHideMs:sF(e.status)}}(iN):null;return(0,r.jsxs)(r.Fragment,{children:[tC?(0,r.jsx)("div",{className:"server-restart-overlay",role:"status","aria-live":"polite",children:(0,r.jsxs)("div",{className:"server-restart-card",children:[(0,r.jsx)("div",{className:"server-restart-spinner","aria-hidden":"true"}),(0,r.jsx)("strong",{children:Q("restart.title")}),(0,r.jsx)("span",{children:Q(t$?"restart.slow":"restart.body")})]})}):null,(0,r.jsxs)("div",{ref:tv,className:"workspace-shell","data-active-view":e7.activeView,"data-deck-mode":ti.deck,"data-deck-visible":rW,"data-chat-wide":e$?"true":void 0,children:[(0,r.jsx)("div",{"aria-hidden":"true",className:`sidebar-overlay-backdrop${nr.drawer?" is-open":""}${tZ?"":" sidebar-mobile-pending"}${t4?" sidebar-mode-shift":""}`,onClick:()=>{ni(!1),tw()}}),(0,r.jsx)("div",{ref:nd.panelRef,id:"session-sidebar",className:`sidebar-container${nr.laidOut?" sidebar-open":" sidebar-closed"}${tZ?"":" sidebar-mobile-pending"}${t4?" sidebar-mode-shift":""}${nd.isResizing?" sidebar-resizing":""}`,"aria-hidden":er&&!nr.presented,inert:er&&!nr.presented,style:{"--sidebar-width":`${nd.width}px`},children:iS}),nr.laidOut&&(0,r.jsx)("div",{...nd.separatorProps,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${nd.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${Q("layout.resizeSidebar")}: ${Q("layout.resizeHint")}`}),(0,r.jsxs)("div",{className:"workspace-session-region","data-active-view":e7.activeView,"aria-hidden":nr.drawer,inert:nr.drawer,children:[(0,r.jsxs)("div",{ref:np,className:"workspace-header-stack",children:[iI&&tF&&(0,r.jsxs)("div",{className:"workspace-update-banner","data-tone":iI.tone,role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{className:"workspace-update-banner-title",children:iI.title}),(0,r.jsx)("span",{className:"workspace-update-banner-detail",children:iI.detail}),iI.dismissible&&(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>tP(s_(tF.requestId)),"aria-label":"업데이트 상태 알림 닫기",children:"닫기"})]}),tE&&!(iI&&tF)&&(0,r.jsxs)("div",{className:"workspace-update-banner","data-tone":"positive",role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{className:"workspace-update-banner-title",children:Q("restart.returnedTitle")}),(0,r.jsx)("span",{className:"workspace-update-banner-detail",children:Q("restart.returnedBody")}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>tL(!1),"aria-label":Q("restart.returnedDismiss"),children:Q("i18n.close")})]}),(0,r.jsx)(oS,{variant:"banner",locale:Z,...en}),(0,r.jsxs)("header",{className:"workspace-header-seam",children:[(0,r.jsx)(a.r,{ref:ns,className:"workspace-header-nav-toggle",variant:"ghost",size:"small",layout:"iconOnly",type:"button",onClick:n7,"aria-controls":"session-sidebar","aria-expanded":nr.presented,title:nr.presented?Q("sidebar.hide"):Q("sidebar.show"),"aria-label":nr.presented?Q("sidebar.hide"):Q("sidebar.show"),children:nr.presented?(0,r.jsx)(l.In,{size:"16px",svg:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}):(0,r.jsx)(l.In,{size:"18px",svg:(0,r.jsxs)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),(0,r.jsx)("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),(0,r.jsx)("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})})}),(0,r.jsxs)("div",{className:"workspace-session-identity",title:rG,children:[(0,r.jsx)("strong",{children:rU}),(0,r.jsx)("span",{"aria-live":"polite",children:rQ})]}),(0,r.jsx)("span",{className:"sr-only",role:"status",children:"error"===nA.kind?nA.message:""}),rz&&eG?.requiresTrust&&!eG.trusted&&(0,r.jsxs)(a.r,{className:"workspace-header-action",variant:"ghost",size:"small",color:"fg.warning",type:"button",onClick:()=>{e3(eG.error?Q("trust.applyFailed",{error:eG.error}):null),nG(null),e9({type:"close-layer"}),e2(!0),eG.pending&&eX(e=>e+1)},title:Q("grant"===eG.pending?"trust.pendingBadge":"trust.resourcesNotLoaded"),"aria-label":Q("grant"===eG.pending?"trust.pendingBadge":"trust.resourcesNotLoaded"),children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"M12 8v4"}),(0,r.jsx)("path",{d:"M12 16h.01"})]}),!er&&(0,r.jsx)("span",{children:Q("trust.resourcesNotLoaded")})]}),rz&&il&&(0,r.jsxs)(a.r,{className:"workspace-context-usage",variant:"ghost",size:"small",type:"button",onClick:n3,"aria-expanded":"session"===nJ,title:id??Q("session.title"),"aria-label":ic?`${id}. ${ic}`:id??void 0,children:[(0,r.jsx)("span",{className:"workspace-context-meter","aria-hidden":"true",children:(0,r.jsx)("span",{className:"workspace-context-meter-fill","data-level":ia.level,style:{inlineSize:`${ia.fillPercent}%`}})}),(0,r.jsx)("span",{className:"workspace-context-readout","data-level":ia.level,children:il})]}),U?(0,r.jsx)(a.r,{asChild:!0,className:"workspace-header-action",variant:"ghost",size:"small",children:(0,r.jsx)("a",{href:`/${it}`,"data-office-link":"chat",title:nM("office.toChatTitle"),children:nM("office.toChat")})}):(0,r.jsx)(a.r,{asChild:!0,className:"workspace-header-action",variant:"ghost",size:"small",children:(0,r.jsxs)("a",{href:`/office${it}`,target:"_blank",rel:"noopener","data-office-link":"office",title:nM("office.toOfficeTitle"),"aria-label":`${nM("office.toOffice")} (${nM("office.newTab")})`,children:[nM("office.toOffice"),(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M14 4h6v6"}),(0,r.jsx)("path",{d:"M20 4 11 13"}),(0,r.jsx)("path",{d:"M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"})]})]})}),rz&&!U&&(0,r.jsx)(o.f,{className:"workspace-panel-toggle",variant:"neutralWeak",size:"small",pressed:ii,onPressedChange:n5,"aria-controls":"workspace-auxiliary-panel",title:"ko"===Z?"보조 패널":"Auxiliary panel",children:is}),(0,r.jsxs)(d.k.Root,{open:nX,onOpenChange:e=>nQ(e),placement:"bottom-end",strategy:"fixed",children:[(0,r.jsx)(d.k.Trigger,{asChild:!0,children:(0,r.jsx)(a.r,{className:"workspace-header-more",variant:"ghost",size:"small",layout:"iconOnly",type:"button",title:"ko"===Z?"더 보기":"More","aria-label":"ko"===Z?"더 보기":"More",children:(0,r.jsx)(l.In,{size:"16px",svg:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"5",r:"1"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1"}),(0,r.jsx)("circle",{cx:"12",cy:"19",r:"1"})]})})})}),(0,r.jsx)(d.k.Positioner,{children:(0,r.jsx)(d.k.Content,{"aria-label":"ko"===Z?"세션 및 환경 메뉴":"Session and environment menu",children:(0,r.jsxs)(d.k.ScrollArea,{children:[(0,r.jsxs)(d.k.Group,{children:[(0,r.jsx)(d.k.GroupLabel,{children:"ko"===Z?"세션":"Session"}),(0,r.jsx)(d.k.Item,{onClick:n3,children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:Q("session.title")})})}),(0,r.jsx)(d.k.Item,{onClick:rL,disabled:!ev,children:(0,r.jsxs)(d.k.ItemBody,{children:[(0,r.jsx)(d.k.ItemLabel,{children:Q("history.label")}),!ev&&(0,r.jsx)(d.k.ItemDescription,{children:Q("history.unsaved")})]})}),(0,r.jsx)(d.k.Item,{onClick:()=>void rN(),disabled:null!==ip||"naming"===nA.kind,children:(0,r.jsxs)(d.k.ItemBody,{children:[(0,r.jsx)(d.k.ItemLabel,{children:im}),ih&&(0,r.jsx)(d.k.ItemDescription,{children:ih})]})}),(0,r.jsx)(d.k.Item,{onClick:()=>n6("branches"),children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:Q("i18n.branches")})})}),(0,r.jsx)(d.k.Item,{onClick:()=>n6("system"),children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:Q("system.label")})})})]}),(0,r.jsxs)(d.k.Group,{children:[(0,r.jsx)(d.k.GroupLabel,{children:"ko"===Z?"환경":"Environment"}),(0,r.jsx)(oS,{variant:"menu",locale:Z,...en}),(0,r.jsx)(d.k.Item,{onClick:e=>{let t=e.currentTarget.getBoundingClientRect();Y({x:t.left+t.width/2,y:t.top+t.height/2})},children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:Q("light"===G?"theme.light":"dark"===G?"theme.dark":"theme.auto")})})}),ee.map(e=>(0,r.jsx)(d.k.Item,{role:"menuitemradio","aria-checked":Z===e.id,onClick:()=>X(e.id),children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:e.label})})},e.id)),(0,r.jsx)(d.k.Item,{onClick:()=>{nG(null),e9({type:"close-layer"}),er&&ni(!1),eJ(!0)},children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:Q("common.settings")})})})]})]})})})]})]}),nJ&&nY&&(0,r.jsxs)("div",{style:{position:"fixed",top:nY.top,left:nY.left,width:nY.width,maxHeight:`calc(100dvh - ${nY.top}px - var(--omp-dock-h, 204px) - 8px)`,overflowY:"auto",zIndex:500},children:["branches"===nJ&&(0,r.jsx)("div",{className:"workspace-top-panel","aria-label":Q("i18n.branches"),children:(0,r.jsx)(d7,{tree:nh.sessionId===(ev?.id??null)?nh.tree:[],activeLeafId:nh.sessionId===(ev?.id??null)?nh.leafId:null,onLeafChange:nv,hasSession:!!ev})}),"system"===nJ&&(0,r.jsx)("div",{style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:nb?(0,r.jsx)("div",{style:{maxHeight:"min(600px, 75vh)",overflowY:"auto",padding:"12px 16px",color:"var(--text-muted)",fontSize:12,lineHeight:1.6,whiteSpace:"pre-wrap",fontFamily:"var(--font-mono)"},children:nb}):""===nb?(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:Q("system.empty")}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:Q("system.load")})}),"session"===nJ&&(0,r.jsx)("div",{className:"session-info-popover",style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",padding:"12px 16px"},children:nk?(L=nk.totalActiveMs??0,A=[...nk.sessionName?[{label:Q("session.name"),value:nk.sessionName,copyField:null}]:[],{label:Q("session.file"),value:nk.sessionFile??Q("session.inMemory"),copyField:"file"},{label:Q("session.id"),value:nk.sessionId,copyField:"id"},...L>0?[{label:Q("session.totalActive"),value:(e=>{if(e<=0)return"0s";let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${i}s`:`${i}s`})(L),copyField:null}]:[]],F=[[Q("session.user"),nk.userMessages.toLocaleString(Z)],[Q("session.assistant"),nk.assistantMessages.toLocaleString(Z)],[Q("session.toolCalls"),nk.toolCalls.toLocaleString(Z)],[Q("session.toolResults"),nk.toolResults.toLocaleString(Z)],[Q("session.total"),nk.totalMessages.toLocaleString(Z)]],P=[[Q("session.input"),nk.tokens.input.toLocaleString(Z)],[Q("session.output"),nk.tokens.output.toLocaleString(Z)],...nk.tokens.cacheRead>0?[[Q("session.cacheRead"),nk.tokens.cacheRead.toLocaleString(Z)]]:[],...nk.tokens.cacheWrite>0?[[Q("session.cacheWrite"),nk.tokens.cacheWrite.toLocaleString(Z)]]:[],[Q("session.total"),nk.tokens.total.toLocaleString(Z)]],D=nB??nk.contextUsage,_=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e),O=[...nk.cost>0?[[Q("session.cost"),`$${nk.cost.toFixed(4)}`]]:[],...D?.contextWindow?[[Q("session.context"),`${null!==D.tokens?_(D.tokens):"?"} / ${_(D.contextWindow)}${null!==D.percent?` \xb7 ${D.percent.toFixed(1)}%`:""}`]]:[],...nk.tokens.cacheRead+nk.tokens.cacheWrite>0&&nk.tokens.cacheRead+nk.tokens.cacheWrite+nk.tokens.input>0?[[Q("session.cacheHitRate"),`${(nk.tokens.cacheRead/(nk.tokens.cacheRead+nk.tokens.cacheWrite+nk.tokens.input)*100).toFixed(1)}%`]]:[]],H=(e,t,n="left",i=!1)=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:e}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:i?"max-content max-content":"auto minmax(0, 1fr)",columnGap:i?14:12,rowGap:4,justifyContent:i?"start":void 0},children:t.map(([t,s])=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:t}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:i?"normal":"anywhere",textAlign:n,whiteSpace:"right"===n?"nowrap":"normal"},children:s})]},`${e}:${t}`))})]}),B=(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:Q("session.infoSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:A.map(e=>{var t,n;let i;return(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,r.jsx)("div",{children:e.copyField?(t=e.copyField,n=e.value,i=nD===t,(0,r.jsx)("button",{type:"button",title:i?Q("session.copied"):Q("file"===t?"session.copyFile":"session.copyId"),onClick:()=>nH(t,n),style:{alignSelf:"start",display:"inline-flex",alignItems:"center",justifyContent:"center",width:22,height:22,marginTop:-2,color:i?"var(--accent)":"var(--text-dim)",background:"transparent",border:"1px solid var(--border)",borderRadius:4,cursor:"pointer",flex:"0 0 auto",transition:"color 0.12s, border-color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color=i?"var(--accent)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="transparent"},children:i?(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})):null})]},`session-info:${e.label}`)})})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:er?"1fr":"minmax(360px, 1.7fr) minmax(140px, 0.55fr) minmax(190px, 0.75fr)",gap:er?16:24,fontSize:12,lineHeight:1.5,fontFamily:"var(--font-mono)"},children:[B,H(Q("session.messages"),F),H(Q("session.tokens"),[...P,...O],"right",!0)]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:Q("session.load")})})]})]}),(0,r.jsxs)("div",{className:`chat-content-layout${U?` ${cL().page}`:""}`,"data-office-pane":U?r7:void 0,children:[r5&&"floor"===r7?(0,r.jsx)(c$.t,{roster:r5,selected:r8,onSelect:nT.select,view:nT.view,onViewChange:nT.setView}):null,(0,r.jsxs)("div",{id:"workspace-transcript",className:"chat-session-column","data-lounge-open":eu?"true":void 0,inert:r9||void 0,children:[rz?(0,r.jsx)(al,{session:ev,newSessionCwd:rA,initialSessionData:ek,transitioning:null!==ey,onAgentEnd:rS,onAttentionNeeded:rC,onSessionCreated:rk,onSessionForked:rI,modelsRefreshKey:eq,chatInputRef:nu,onBranchDataChange:nx,onSystemPromptChange:nw,onSessionStatsChange:nP,onSessionStatsPanelOpen:n3,onContextUsageChange:nq,onSubagentsChange:nC,onMainIdentityChange:nI,onOpenWorkspaceView:r4,onProcessLogChange:nK,onOpenFile:rR,transcriptReplacement:ie?(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:ij}):r3&&r6?(0,r.jsx)(cW,{participant:r3,recipient:r6,sessionId:ev?.id??null,cwd:ev?.cwd??rA??void 0,onBackToMain:()=>nT.select(cF.h7),onOpenFile:rR},r3.key):null,onComposerFocusChange:tj,onSessionBusyChange:th,onWaitingChange:tf,onAttentionChange:nL,soundEnabled:ei,onSoundToggle:es,playCueSound:ea,preloadCueSound:el,unlockAudio:eo,jumpRequest:eN,onJumpHandled:eM},eO):ie?(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:ij}):"validating"===ez?(0,r.jsxs)("div",{role:"status",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"var(--text)"},children:Q("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:J.requestedCwd})]}):"error"===ez?(0,r.jsxs)("div",{role:"alert",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"var(--danger)"},children:Q("workspace.unable")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:J.requestedCwd}),(0,r.jsx)("div",{style:{maxWidth:720,fontSize:12},children:eF})]}):rP?rl?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:Q("workspace.selectSession")}):(0,r.jsxs)("div",{style:{position:"absolute",top:12,left:12,display:"flex",alignItems:"flex-start",gap:8,userSelect:"none",pointerEvents:"none"},children:[(0,r.jsxs)("svg",{width:"44",height:"44",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",style:{opacity:.7,flexShrink:0},children:[(0,r.jsx)("line",{x1:"20",y1:"12",x2:"4",y2:"12"}),(0,r.jsx)("polyline",{points:"10 6 4 12 10 18"})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:18,fontWeight:600,color:"var(--text)",marginBottom:8},children:Q("workspace.getStarted")}),(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.8},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"1."}),Q("workspace.selectProject"),(0,r.jsx)("br",{}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),Q("workspace.addModels")]})]})]}):null,eh?(0,r.jsx)(cT,{lounge:ef,visible:eu,onBack:()=>tk(!1)}):null]}),"pinned"===ti.deck&&rW&&!U&&(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-pinned","data-workspace-region":"deck",children:ij})]}),r5&&r7?(0,r.jsx)(cM.FC,{roster:r5,selected:r8,onSelect:e=>{eu&&tk(!1),nT.select(e)},pane:r7,onShowFloor:()=>{eu&&tk(!1),nT.setPane("floor")},selectionGone:nT.selected!==r8}):null]}),"command-palette"===e7.transientLayer&&(0,r.jsx)("div",{className:"workspace-command-layer",onMouseDown:e=>{e.target===e.currentTarget&&(e9({type:"close-layer"}),tw())},children:(0,r.jsxs)("div",{ref:ty,className:"workspace-command-palette",role:"dialog","aria-modal":"true",onKeyDown:tJ,"aria-label":"ko"===Z?"명령 팔레트":"Command palette",children:[(0,r.jsxs)("header",{children:[(0,r.jsx)("strong",{children:"ko"===Z?"명령 팔레트":"Command palette"}),(0,r.jsx)("kbd",{children:"Ctrl K"})]}),(0,r.jsx)(am,{t:Q,onPick:(e,t)=>{e9({type:"close-layer"}),n2("chat",!1),eT.current+=1,eI({id:eT.current,sessionId:e.id,entryId:t.entryId}),rv(e)}}),(0,r.jsxs)("div",{className:"workspace-command-list",children:[c.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>n2(e,!0),children:[(0,r.jsx)("span",{children:ir[e]}),(0,r.jsx)("small",{children:e7.activeView===e?"ko"===Z?"현재 보기":"Current view":""})]},e)),u.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>{tt(e),n2("resource",!1)},children:[(0,r.jsx)("span",{children:"characters"===e?"캐릭터":"usage"===e?"계정 한도":"모델 통계"}),(0,r.jsx)("small",{children:ir.resource})]},e)),(0,r.jsxs)("button",{type:"button",onClick:n7,children:[(0,r.jsx)("span",{children:nr.presented?Q("sidebar.hide"):Q("sidebar.show")}),(0,r.jsx)("small",{children:"Ctrl B"})]}),(0,r.jsx)("button",{type:"button",onClick:eE,children:(0,r.jsx)("span",{children:Q(e$?"palette.wideChatOff":"palette.wideChatOn")})}),(0,r.jsx)("button",{type:"button",onClick:()=>{e9({type:"close-layer"}),eJ(!0)},children:(0,r.jsx)("span",{children:Q("common.settings")})})]})]})})]}),eK&&(0,r.jsx)(ow,{cwd:rF,sessionId:ev?.id??null,onClose:()=>{eJ(!1),eX(e=>e+1),tw()},onModelsChanged:()=>eV(e=>e+1),onReloaded:()=>eH(e=>e+1)}),e1&&rF&&(0,r.jsx)(oC,{cwd:rF,busy:e4,scheduled:eG?.pending==="grant",error:e8,onCancel:()=>{e4||(e2(!1),tw())},onConfirm:()=>void r_("grant"),onCancelSchedule:()=>void r_("cancel")})]})}},69575:(e,t,n)=>{Promise.resolve().then(n.bind(n,36266)),Promise.resolve().then(n.bind(n,92176))},98795:e=>{e.exports={root:"SearchableSelect_root__FMhaH",trigger:"SearchableSelect_trigger__eqMdt",value:"SearchableSelect_value__eJ2RU",placeholder:"SearchableSelect_placeholder__Hkg33",chevron:"SearchableSelect_chevron__DSTnM",popover:"SearchableSelect_popover__5VxMd",searchWrap:"SearchableSelect_searchWrap__IoKKk",searchIcon:"SearchableSelect_searchIcon__A6f0C",search:"SearchableSelect_search__W_1al",options:"SearchableSelect_options__tjHyi",option:"SearchableSelect_option__LRRH9",optionCopy:"SearchableSelect_optionCopy__W87H8",optionLabel:"SearchableSelect_optionLabel__G7jIg",optionDescription:"SearchableSelect_optionDescription__cE_cC",check:"SearchableSelect_check__1Likw",empty:"SearchableSelect_empty__vZzXQ"}}}]);
|