@oscharko-dev/keiko 0.2.6 → 0.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/ui/csp-hashes.json +21 -21
- package/dist/ui/static/404.html +1 -1
- package/dist/ui/static/__next.__PAGE__.txt +2 -2
- package/dist/ui/static/__next._full.txt +4 -4
- package/dist/ui/static/__next._head.txt +1 -1
- package/dist/ui/static/__next._index.txt +2 -2
- package/dist/ui/static/__next._tree.txt +2 -2
- package/dist/ui/static/_next/static/chunks/{2063.443bb736720d0976.js → 1587.33fc772cb66c38d7.js} +1 -1
- package/dist/ui/static/_next/static/chunks/{7301.0c053ca1f6a524e6.js → 2063.a7cd2441b60aa093.js} +1 -1
- package/dist/ui/static/_next/static/chunks/{3170.2539679cfc72865c.js → 3170.e25f90ed08f303e3.js} +4 -4
- package/dist/ui/static/_next/static/chunks/{3868.3ebf6f39d31a4cce.js → 3868.ea5f0ddf5e222dba.js} +1 -1
- package/dist/ui/static/_next/static/chunks/{4905.e5c0de0e634d5b31.js → 4905.73672d3d0c642e75.js} +1 -1
- package/dist/ui/static/_next/static/chunks/{6028.c73575c441d46324.js → 6028.7deb9c5d26bfce83.js} +1 -1
- package/dist/ui/static/_next/static/chunks/{1587.561c8a85eac6595a.js → 7301.501daea6a309d3f5.js} +1 -1
- package/dist/ui/static/_next/static/chunks/8776.8b33803959adfdcf.js +3 -0
- package/dist/ui/static/_next/static/chunks/8824-1b90854002e51dae.js +98 -0
- package/dist/ui/static/_next/static/chunks/{8835-d642f66c1962fa68.js → 8835-7a3269c7abf41dca.js} +1 -1
- package/dist/ui/static/_next/static/chunks/{8948.d928ebd17b05f4df.js → 8948.a434bd4eee007dec.js} +1 -1
- package/dist/ui/static/_next/static/chunks/9385.6543855a745f1347.js +1 -0
- package/dist/ui/static/_next/static/chunks/app/_not-found/page-d11b06e05aafdf7f.js +1 -0
- package/dist/ui/static/_next/static/chunks/app/launch/page-82ed92234aabb847.js +1 -0
- package/dist/ui/static/_next/static/chunks/app/layout-6e7d5a2f606bb912.js +1 -0
- package/dist/ui/static/_next/static/chunks/app/local-knowledge/capsule/page-a2af3bbd82315c1e.js +1 -0
- package/dist/ui/static/_next/static/chunks/app/local-knowledge/page-9124d233dd58858c.js +1 -0
- package/dist/ui/static/_next/static/chunks/app/page-dcdb404becd4ddb6.js +1 -0
- package/dist/ui/static/_next/static/chunks/main-app-78f8504d5fb3159e.js +1 -0
- package/dist/ui/static/_next/static/chunks/next/dist/client/components/builtin/global-error-6a6cbc4b4b1897d4.js +1 -0
- package/dist/ui/static/_next/static/chunks/{webpack-284633a353ab8ff4.js → webpack-b38f050528b4d7a7.js} +1 -1
- package/dist/ui/static/_next/static/css/a1d25933a2ce4659.css +3 -0
- package/dist/ui/static/_not-found/__next._full.txt +3 -3
- package/dist/ui/static/_not-found/__next._head.txt +1 -1
- package/dist/ui/static/_not-found/__next._index.txt +2 -2
- package/dist/ui/static/_not-found/__next._not-found.__PAGE__.txt +1 -1
- package/dist/ui/static/_not-found/__next._not-found.txt +1 -1
- package/dist/ui/static/_not-found/__next._tree.txt +2 -2
- package/dist/ui/static/_not-found.html +1 -1
- package/dist/ui/static/_not-found.txt +3 -3
- package/dist/ui/static/favicon.ico +0 -0
- package/dist/ui/static/favicon.svg +55 -4
- package/dist/ui/static/index.html +1 -1
- package/dist/ui/static/index.txt +4 -4
- package/dist/ui/static/launch/__next._full.txt +4 -4
- package/dist/ui/static/launch/__next._head.txt +1 -1
- package/dist/ui/static/launch/__next._index.txt +2 -2
- package/dist/ui/static/launch/__next._tree.txt +2 -2
- package/dist/ui/static/launch/__next.launch.__PAGE__.txt +2 -2
- package/dist/ui/static/launch/__next.launch.txt +1 -1
- package/dist/ui/static/launch.html +1 -1
- package/dist/ui/static/launch.txt +4 -4
- package/dist/ui/static/local-knowledge/__next._full.txt +4 -4
- package/dist/ui/static/local-knowledge/__next._head.txt +1 -1
- package/dist/ui/static/local-knowledge/__next._index.txt +2 -2
- package/dist/ui/static/local-knowledge/__next._tree.txt +2 -2
- package/dist/ui/static/local-knowledge/__next.local-knowledge.__PAGE__.txt +2 -2
- package/dist/ui/static/local-knowledge/__next.local-knowledge.txt +1 -1
- package/dist/ui/static/local-knowledge/capsule/__next._full.txt +4 -4
- package/dist/ui/static/local-knowledge/capsule/__next._head.txt +1 -1
- package/dist/ui/static/local-knowledge/capsule/__next._index.txt +2 -2
- package/dist/ui/static/local-knowledge/capsule/__next._tree.txt +2 -2
- package/dist/ui/static/local-knowledge/capsule/__next.local-knowledge.capsule.__PAGE__.txt +2 -2
- package/dist/ui/static/local-knowledge/capsule/__next.local-knowledge.capsule.txt +1 -1
- package/dist/ui/static/local-knowledge/capsule/__next.local-knowledge.txt +1 -1
- package/dist/ui/static/local-knowledge/capsule.html +1 -1
- package/dist/ui/static/local-knowledge/capsule.txt +4 -4
- package/dist/ui/static/local-knowledge.html +1 -1
- package/dist/ui/static/local-knowledge.txt +4 -4
- package/dist/ui/static/memoriaviva/__next._full.txt +3 -3
- package/dist/ui/static/memoriaviva/__next._head.txt +1 -1
- package/dist/ui/static/memoriaviva/__next._index.txt +2 -2
- package/dist/ui/static/memoriaviva/__next._tree.txt +2 -2
- package/dist/ui/static/memoriaviva/__next.memoriaviva.__PAGE__.txt +1 -1
- package/dist/ui/static/memoriaviva/__next.memoriaviva.txt +1 -1
- package/dist/ui/static/memoriaviva/consolidation/__next._full.txt +3 -3
- package/dist/ui/static/memoriaviva/consolidation/__next._head.txt +1 -1
- package/dist/ui/static/memoriaviva/consolidation/__next._index.txt +2 -2
- package/dist/ui/static/memoriaviva/consolidation/__next._tree.txt +2 -2
- package/dist/ui/static/memoriaviva/consolidation/__next.memoriaviva.consolidation.__PAGE__.txt +1 -1
- package/dist/ui/static/memoriaviva/consolidation/__next.memoriaviva.consolidation.txt +1 -1
- package/dist/ui/static/memoriaviva/consolidation/__next.memoriaviva.txt +1 -1
- package/dist/ui/static/memoriaviva/consolidation.html +1 -1
- package/dist/ui/static/memoriaviva/consolidation.txt +3 -3
- package/dist/ui/static/memoriaviva/detail/__next._full.txt +3 -3
- package/dist/ui/static/memoriaviva/detail/__next._head.txt +1 -1
- package/dist/ui/static/memoriaviva/detail/__next._index.txt +2 -2
- package/dist/ui/static/memoriaviva/detail/__next._tree.txt +2 -2
- package/dist/ui/static/memoriaviva/detail/__next.memoriaviva.detail.__PAGE__.txt +1 -1
- package/dist/ui/static/memoriaviva/detail/__next.memoriaviva.detail.txt +1 -1
- package/dist/ui/static/memoriaviva/detail/__next.memoriaviva.txt +1 -1
- package/dist/ui/static/memoriaviva/detail.html +1 -1
- package/dist/ui/static/memoriaviva/detail.txt +3 -3
- package/dist/ui/static/memoriaviva/review-queue/__next._full.txt +3 -3
- package/dist/ui/static/memoriaviva/review-queue/__next._head.txt +1 -1
- package/dist/ui/static/memoriaviva/review-queue/__next._index.txt +2 -2
- package/dist/ui/static/memoriaviva/review-queue/__next._tree.txt +2 -2
- package/dist/ui/static/memoriaviva/review-queue/__next.memoriaviva.review-queue.__PAGE__.txt +1 -1
- package/dist/ui/static/memoriaviva/review-queue/__next.memoriaviva.review-queue.txt +1 -1
- package/dist/ui/static/memoriaviva/review-queue/__next.memoriaviva.txt +1 -1
- package/dist/ui/static/memoriaviva/review-queue.html +1 -1
- package/dist/ui/static/memoriaviva/review-queue.txt +3 -3
- package/dist/ui/static/memoriaviva.html +1 -1
- package/dist/ui/static/memoriaviva.txt +3 -3
- package/node_modules/@oscharko-dev/keiko-cli/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-cli/dist/run.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-cli/dist/run.js +2 -0
- package/node_modules/@oscharko-dev/keiko-cli/dist/tool-shaper.d.ts +3 -0
- package/node_modules/@oscharko-dev/keiko-cli/dist/tool-shaper.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-cli/dist/tool-shaper.js +70 -0
- package/node_modules/@oscharko-dev/keiko-cli/package.json +14 -14
- package/node_modules/@oscharko-dev/keiko-contracts/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-contracts/dist/bff-wire.d.ts +70 -20
- package/node_modules/@oscharko-dev/keiko-contracts/dist/bff-wire.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-contracts/dist/bff-wire.js +52 -1
- package/node_modules/@oscharko-dev/keiko-contracts/dist/connected-context.d.ts +14 -0
- package/node_modules/@oscharko-dev/keiko-contracts/dist/connected-context.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-contracts/dist/connected-context.js +49 -0
- package/node_modules/@oscharko-dev/keiko-contracts/dist/context-engineering-compaction-validation.d.ts +11 -0
- package/node_modules/@oscharko-dev/keiko-contracts/dist/context-engineering-compaction-validation.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-contracts/dist/context-engineering-compaction-validation.js +270 -0
- package/node_modules/@oscharko-dev/keiko-contracts/dist/context-engineering-validation.d.ts +12 -0
- package/node_modules/@oscharko-dev/keiko-contracts/dist/context-engineering-validation.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-contracts/dist/context-engineering-validation.js +171 -0
- package/node_modules/@oscharko-dev/keiko-contracts/dist/context-engineering.d.ts +148 -0
- package/node_modules/@oscharko-dev/keiko-contracts/dist/context-engineering.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-contracts/dist/context-engineering.js +80 -0
- package/node_modules/@oscharko-dev/keiko-contracts/dist/context-observations-validation.d.ts +9 -0
- package/node_modules/@oscharko-dev/keiko-contracts/dist/context-observations-validation.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-contracts/dist/context-observations-validation.js +252 -0
- package/node_modules/@oscharko-dev/keiko-contracts/dist/context-observations.d.ts +88 -0
- package/node_modules/@oscharko-dev/keiko-contracts/dist/context-observations.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-contracts/dist/context-observations.js +19 -0
- package/node_modules/@oscharko-dev/keiko-contracts/dist/evidence.d.ts +14 -0
- package/node_modules/@oscharko-dev/keiko-contracts/dist/evidence.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-contracts/dist/index.d.ts +12 -4
- package/node_modules/@oscharko-dev/keiko-contracts/dist/index.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-contracts/dist/index.js +7 -2
- package/node_modules/@oscharko-dev/keiko-contracts/dist/prompt-enhancer-analyzer.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-contracts/dist/prompt-enhancer-analyzer.js +198 -22
- package/node_modules/@oscharko-dev/keiko-contracts/dist/tools.d.ts +4 -0
- package/node_modules/@oscharko-dev/keiko-contracts/dist/tools.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-contracts/package.json +9 -1
- package/node_modules/@oscharko-dev/keiko-evaluations/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-evaluations/package.json +9 -9
- package/node_modules/@oscharko-dev/keiko-evidence/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-evidence/dist/compaction-evidence.d.ts +27 -0
- package/node_modules/@oscharko-dev/keiko-evidence/dist/compaction-evidence.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-evidence/dist/compaction-evidence.js +215 -0
- package/node_modules/@oscharko-dev/keiko-evidence/dist/connected-context-evidence.d.ts +2 -1
- package/node_modules/@oscharko-dev/keiko-evidence/dist/connected-context-evidence.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-evidence/dist/connected-context-evidence.js +20 -0
- package/node_modules/@oscharko-dev/keiko-evidence/dist/context-assembly-redaction.d.ts +5 -0
- package/node_modules/@oscharko-dev/keiko-evidence/dist/context-assembly-redaction.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-evidence/dist/context-assembly-redaction.js +62 -0
- package/node_modules/@oscharko-dev/keiko-evidence/dist/index-api.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-evidence/dist/index-api.js +2 -0
- package/node_modules/@oscharko-dev/keiko-evidence/dist/index.d.ts +1 -0
- package/node_modules/@oscharko-dev/keiko-evidence/dist/index.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-evidence/dist/index.js +1 -0
- package/node_modules/@oscharko-dev/keiko-evidence/dist/types.d.ts +1 -1
- package/node_modules/@oscharko-dev/keiko-evidence/dist/types.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-evidence/package.json +4 -4
- package/node_modules/@oscharko-dev/keiko-harness/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-harness/dist/context.d.ts +4 -0
- package/node_modules/@oscharko-dev/keiko-harness/dist/context.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-harness/dist/executor.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-harness/dist/executor.js +26 -0
- package/node_modules/@oscharko-dev/keiko-harness/dist/index.d.ts +1 -0
- package/node_modules/@oscharko-dev/keiko-harness/dist/index.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-harness/dist/session.d.ts +2 -0
- package/node_modules/@oscharko-dev/keiko-harness/dist/session.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-harness/dist/session.js +2 -0
- package/node_modules/@oscharko-dev/keiko-harness/dist/shaper-port.d.ts +9 -0
- package/node_modules/@oscharko-dev/keiko-harness/dist/shaper-port.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-harness/dist/shaper-port.js +14 -0
- package/node_modules/@oscharko-dev/keiko-harness/package.json +6 -6
- package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-local-knowledge/package.json +5 -5
- package/node_modules/@oscharko-dev/keiko-memory-capture/package.json +3 -3
- package/node_modules/@oscharko-dev/keiko-memory-consolidation/package.json +3 -3
- package/node_modules/@oscharko-dev/keiko-memory-governance/package.json +3 -3
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/package.json +3 -3
- package/node_modules/@oscharko-dev/keiko-memory-vault/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-vault/package.json +3 -3
- package/node_modules/@oscharko-dev/keiko-model-gateway/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-model-gateway/dist/promptEnhancer/generator.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-model-gateway/dist/promptEnhancer/generator.js +417 -14
- package/node_modules/@oscharko-dev/keiko-model-gateway/package.json +3 -3
- package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-quality-intelligence/package.json +3 -3
- package/node_modules/@oscharko-dev/keiko-sandbox/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-sandbox/package.json +2 -2
- package/node_modules/@oscharko-dev/keiko-sdk/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-sdk/package.json +9 -9
- package/node_modules/@oscharko-dev/keiko-security/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-security/package.json +2 -2
- package/node_modules/@oscharko-dev/keiko-server/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/chat-compaction-evidence.d.ts +12 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/chat-compaction-evidence.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/chat-compaction-evidence.js +46 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/chat-handlers.d.ts +16 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/chat-handlers.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/chat-handlers.js +78 -28
- package/node_modules/@oscharko-dev/keiko-server/dist/chat-stream-handlers.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/chat-stream-handlers.js +13 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/conversation-compaction.d.ts +12 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/conversation-compaction.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/conversation-compaction.js +102 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/deps.d.ts +3 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/deps.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/deps.js +3 -2
- package/node_modules/@oscharko-dev/keiko-server/dist/files.d.ts +18 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/files.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/files.js +174 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/gateway-readiness.d.ts +6 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/gateway-readiness.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/gateway-readiness.js +624 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/grounded-context-diagnostics.d.ts +5 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/grounded-context-diagnostics.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/grounded-context-diagnostics.js +77 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/grounded-orchestrator.d.ts +2 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/grounded-orchestrator.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/grounded-orchestrator.js +122 -53
- package/node_modules/@oscharko-dev/keiko-server/dist/grounded-qa-hybrid.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/grounded-qa-hybrid.js +7 -4
- package/node_modules/@oscharko-dev/keiko-server/dist/grounded-qa-multi-source.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/grounded-qa-multi-source.js +49 -2
- package/node_modules/@oscharko-dev/keiko-server/dist/grounded-qa.d.ts +4 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/grounded-qa.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/grounded-qa.js +36 -2
- package/node_modules/@oscharko-dev/keiko-server/dist/index.d.ts +3 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/index.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/index.js +6 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/local-knowledge-grounded-qa.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/local-knowledge-grounded-qa.js +11 -2
- package/node_modules/@oscharko-dev/keiko-server/dist/routes.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/routes.js +5 -10
- package/node_modules/@oscharko-dev/keiko-server/dist/run-handlers.d.ts +0 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/run-handlers.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/run-handlers.js +0 -217
- package/node_modules/@oscharko-dev/keiko-server/dist/store/db.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/store/db.js +2 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/store/index.d.ts +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/store/index.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/store/messages.d.ts +2 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/store/messages.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/store/messages.js +46 -4
- package/node_modules/@oscharko-dev/keiko-server/dist/store/schema.d.ts +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/store/schema.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/store/schema.js +7 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/store/types.d.ts +3 -2
- package/node_modules/@oscharko-dev/keiko-server/dist/store/types.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/package.json +19 -19
- package/node_modules/@oscharko-dev/keiko-tools/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-tools/dist/exec.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-tools/dist/exec.js +8 -1
- package/node_modules/@oscharko-dev/keiko-tools/dist/registry.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-tools/dist/registry.js +3 -0
- package/node_modules/@oscharko-dev/keiko-tools/package.json +5 -5
- package/node_modules/@oscharko-dev/keiko-verification/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-verification/package.json +5 -5
- package/node_modules/@oscharko-dev/keiko-workflows/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-workflows/dist/context-budget/allocator.d.ts +29 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/context-budget/allocator.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/context-budget/allocator.js +185 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/context-budget/compaction-helpers.d.ts +44 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/context-budget/compaction-helpers.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/context-budget/compaction-helpers.js +203 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/context-budget/compaction.d.ts +14 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/context-budget/compaction.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/context-budget/compaction.js +97 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/context-budget/defaults.d.ts +3 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/context-budget/defaults.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/context-budget/defaults.js +75 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/context-budget/index.d.ts +8 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/context-budget/index.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/context-budget/index.js +6 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/context-budget/rehydration.d.ts +11 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/context-budget/rehydration.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/context-budget/rehydration.js +76 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/contextpack/assemble.d.ts +2 -1
- package/node_modules/@oscharko-dev/keiko-workflows/dist/contextpack/assemble.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-workflows/dist/contextpack/assemble.js +19 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/index.d.ts +2 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/index.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-workflows/dist/index.js +4 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/observations/command.d.ts +6 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/observations/command.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/observations/command.js +67 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/observations/index.d.ts +5 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/observations/index.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/observations/index.js +6 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/observations/search.d.ts +9 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/observations/search.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/observations/search.js +43 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/observations/shared.d.ts +18 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/observations/shared.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/observations/shared.js +63 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/observations/test.d.ts +6 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/observations/test.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/observations/test.js +47 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/planner/anchors.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-workflows/dist/planner/anchors.js +3 -1
- package/node_modules/@oscharko-dev/keiko-workflows/dist/planner/intent.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-workflows/dist/planner/intent.js +6 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/ranking/rank.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-workflows/dist/ranking/rank.js +5 -3
- package/node_modules/@oscharko-dev/keiko-workflows/dist/ranking/scoring.d.ts +4 -0
- package/node_modules/@oscharko-dev/keiko-workflows/dist/ranking/scoring.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-workflows/dist/ranking/scoring.js +29 -1
- package/node_modules/@oscharko-dev/keiko-workflows/dist/ranking/signals.d.ts +5 -1
- package/node_modules/@oscharko-dev/keiko-workflows/dist/ranking/signals.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-workflows/dist/ranking/signals.js +23 -3
- package/node_modules/@oscharko-dev/keiko-workflows/package.json +10 -10
- package/node_modules/@oscharko-dev/keiko-workspace/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-workspace/dist/ecosystems.d.ts +46 -0
- package/node_modules/@oscharko-dev/keiko-workspace/dist/ecosystems.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-workspace/dist/ecosystems.js +1173 -0
- package/node_modules/@oscharko-dev/keiko-workspace/dist/index.d.ts +4 -2
- package/node_modules/@oscharko-dev/keiko-workspace/dist/index.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-workspace/dist/index.js +3 -1
- package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearchMatchers.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearchMatchers.js +61 -10
- package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearchPolicy.d.ts +10 -2
- package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearchPolicy.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearchPolicy.js +115 -61
- package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearchQueryTerms.d.ts +2 -0
- package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearchQueryTerms.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearchQueryTerms.js +152 -0
- package/node_modules/@oscharko-dev/keiko-workspace/dist/retrieval.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-workspace/dist/retrieval.js +39 -0
- package/node_modules/@oscharko-dev/keiko-workspace/dist/stableId.d.ts +4 -0
- package/node_modules/@oscharko-dev/keiko-workspace/dist/stableId.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-workspace/dist/stableId.js +38 -0
- package/node_modules/@oscharko-dev/keiko-workspace/package.json +3 -3
- package/package.json +25 -22
- package/dist/ui/static/_next/static/chunks/4621-88a84538a70dcf6d.js +0 -98
- package/dist/ui/static/_next/static/chunks/8776.140362f8c6f4d7f1.js +0 -3
- package/dist/ui/static/_next/static/chunks/9385.4cf1f094775e2625.js +0 -1
- package/dist/ui/static/_next/static/chunks/app/_not-found/page-f21e3f25e28a4fe0.js +0 -1
- package/dist/ui/static/_next/static/chunks/app/launch/page-e1218f7643eb0a6e.js +0 -1
- package/dist/ui/static/_next/static/chunks/app/layout-b771eb1e519fd8e1.js +0 -1
- package/dist/ui/static/_next/static/chunks/app/local-knowledge/capsule/page-97eb36a77e8d4e78.js +0 -1
- package/dist/ui/static/_next/static/chunks/app/local-knowledge/page-d8f34047a97108ae.js +0 -1
- package/dist/ui/static/_next/static/chunks/app/page-919e12de0b674447.js +0 -1
- package/dist/ui/static/_next/static/chunks/main-app-f9e2c4e6329295bb.js +0 -1
- package/dist/ui/static/_next/static/chunks/next/dist/client/components/builtin/global-error-af3824b7b26275df.js +0 -1
- package/dist/ui/static/_next/static/css/0fcf744e25b17e8a.css +0 -3
- package/node_modules/@oscharko-dev/keiko-server/dist/grounded-handoff.d.ts +0 -4
- package/node_modules/@oscharko-dev/keiko-server/dist/grounded-handoff.d.ts.map +0 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/grounded-handoff.js +0 -445
- /package/dist/ui/static/_next/static/{oUkwnS6PllEZCcS8tUuTR → V6PH3CS6q84y0pJQupf9J}/_buildManifest.js +0 -0
- /package/dist/ui/static/_next/static/{oUkwnS6PllEZCcS8tUuTR → V6PH3CS6q84y0pJQupf9J}/_ssgManifest.js +0 -0
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[4621],{54621:(e,t,n)=>{Promise.resolve().then(n.bind(n,84853));},84853:(e,t,n)=>{"use strict";let l;n.d(t,{KeikoDesktop:()=>uC});var a=n(54568),i=n(7620);let r=(0,i.createContext)(null);function s(e){let{value:t,children:n}=e;return(0,a.jsx)(r.Provider,{value:t,children:n});}function o(){let e=(0,i.useContext)(r);if(null===e)throw Error("useChatSessionContext must be used inside ChatSessionProvider");return e;}function c(){return(0,i.useContext)(r);}let d=[{id:"read",action:"Read files",scope:"workspace",decision:"allow"},{id:"write",action:"Write files",scope:"src/** \xb7 docs/**",decision:"allow"},{id:"write-prod",action:"Write files",scope:"prod/** \xb7 infra/**",decision:"deny"},{id:"command",action:"Run commands",scope:"test \xb7 build \xb7 lint",decision:"allow"},{id:"command-danger",action:"Run commands",scope:"deploy \xb7 rm \xb7 db",decision:"ask"},{id:"network",action:"Network / fetch",scope:"allowlist",decision:"ask"},{id:"pr",action:"Open pull request",scope:"feature branches",decision:"allow"},{id:"mail",action:"Mail / calendar",scope:"any",decision:"ask"}],u={calendar:!0,mail:!1,jira:!0,docs:!0},p="keiko.twin.mode",m="keiko.twin.persona",h="keiko.twin.policy",f="keiko.twin.bridges",g=(0,i.createContext)(null);function v(e,t){try{let n=window.localStorage.getItem(e);if(null===n)return t;let l=JSON.parse(n);return null==l?t:l;}catch{return t;}}function b(e,t){try{window.localStorage.setItem(e,t);}catch{}}function x(e,t){try{window.localStorage.setItem(e,JSON.stringify(t));}catch{}}function y(e){let{children:t}=e,[n,l]=(0,i.useState)("manual"),[r,s]=(0,i.useState)("Developer"),[o,c]=(0,i.useState)(d),[y,w]=(0,i.useState)(u),[j,k]=(0,i.useState)(!1);(0,i.useEffect)(()=>{l(function(){try{let e=window.localStorage.getItem(p);return"manual"===e||"autonomous"===e?e:"manual";}catch{return"manual";}}()),s(function(){try{let e=window.localStorage.getItem(m);if("Developer"===e||"Product Owner"===e||"Designer"===e)return e;return"Developer";}catch{return"Developer";}}()),c(v(h,d)),w(v(f,u));try{window.localStorage.removeItem("keiko.twin.memory");}catch{}k(!0);},[]),(0,i.useEffect)(()=>{j&&b(p,n);},[n,j]),(0,i.useEffect)(()=>{j&&b(m,r);},[r,j]),(0,i.useEffect)(()=>{j&&x(h,o);},[o,j]),(0,i.useEffect)(()=>{j&&x(f,y);},[y,j]);let N=(0,i.useCallback)((e,t)=>{var n,l,a,i,r,s,c;let d;return d=e=>{var t,n;return null!=(t=null==(n=o.find(t=>t.id===e))?void 0:n.decision)?t:null;},"write"===e?"high"===t?null!=(i=d("write-prod"))?i:"deny":null!=(r=d("write"))?r:"allow":"command"===e?"high"===t?null!=(s=d("command-danger"))?s:"ask":null!=(c=d("command"))?c:"allow":"git"===e?null!=(n=d("pr"))?n:"allow":"mail"===e?null!=(l=d("mail"))?l:"ask":"network"===e&&null!=(a=d("network"))?a:"ask";},[o]),S=(0,i.useMemo)(()=>({mode:n,setMode:l,persona:r,setPersona:s,policy:o,setPolicy:c,bridges:y,setBridges:w,decide:N}),[n,r,o,y,N]);return(0,a.jsx)(g.Provider,{value:S,children:t});}function w(){let e=(0,i.useContext)(g);if(null===e)throw Error("useTwin must be used inside <TwinProvider>");return e;}let j=(0,i.createContext)({wins:[],active:null,winCount:0});var k=n(73599),N=n(75571);let S={w:150,h:110},C={w:290,h:190},I={chat:{title:"Chat",icon:"newChat",accent:!0,desc:"Talk to Keiko",w:480,h:480,min:{w:300,h:260},config:[{key:"title",label:"Title",type:"text",def:"New chat",optional:!0,placeholder:"Name this conversation"}]},chatHistory:{title:"Chat History",icon:"archive",desc:"Manage conversations",w:380,h:560,min:{w:300,h:320},tiny:{w:260,h:220},tool:!0,singleton:!0},memoria:{title:"MemoriaViva",icon:"brain",desc:"Review governed memory",w:680,h:600,min:{w:420,h:360},tiny:{w:300,h:220},tool:!0,singleton:!0},files:{title:"Files",icon:"files",accent:!0,desc:"Browse a folder",w:290,h:340,tiny:{w:200,h:150},config:[{key:"root",label:"Folder",type:"directory",def:""}]},editor:{title:"Editor",icon:"editor",desc:"Open a folder or file",w:920,h:620,min:{w:620,h:380},config:[{key:"root",label:"Folder",type:"directory",def:"",optional:!0,placeholder:"/absolute/folder/path"},{key:"file",label:"File path",type:"text",def:"",optional:!0,placeholder:"optional relative file path"}]},browser:{title:"Browser",icon:"browser",desc:"Open a URL",w:460,h:340,config:[{key:"url",label:"URL",type:"text",def:"",optional:!0,placeholder:"https://…"}]},terminal:{title:"Terminal",icon:"terminal",accent:!0,desc:"Run commands",w:460,h:250,tiny:{w:250,h:140},config:[{key:"projectPath",label:"Project path",type:"text",def:""},{key:"cwd",label:"Working directory",type:"directory",def:""}]},review:{title:"Review",icon:"review",desc:"Review a proposed diff",w:520,h:420,config:[{key:"runId",label:"Run ID",type:"text",def:"",optional:!0,placeholder:"e.g. r-2026-06-01-…"}]},agents:{title:"Agents",icon:"agents",desc:"Choose a coding agent",w:520,h:560,tiny:{w:250,h:140},cta:"Start agent",config:[]},integ:{title:"Integrations",icon:"plugins",desc:"Connect apps",w:320,h:300,config:[{key:"provider",label:"Provider",type:"select",options:["GitHub","Linear","Slack","Sentry"],def:"GitHub"}]},keiko:{title:"Keiko",icon:"spark",desc:"Keiko twin",w:344,h:520,tool:!0,singleton:!0},settings:{title:"Settings",icon:"settings",desc:"Preferences",w:470,h:560,tool:!0,singleton:!0},project:{title:"Project",icon:"folder",desc:"Project tree",w:304,h:440,tool:!0,singleton:!0},search:{title:"Search",icon:"search",desc:"Search the workspace",w:320,h:500,tool:!0,singleton:!0},plugins:{title:"Plugins",icon:"plugins",desc:"Plugins & tools",w:320,h:470,tool:!0,singleton:!0},automations:{title:"Automations",icon:"automations",desc:"Workflow automations",w:320,h:300,tool:!0,singleton:!0},mobile:{title:"Keiko Mobile",icon:"mobile",desc:"Mobile companion",w:300,h:380,tool:!0,singleton:!0},inspector:{title:"Inspector",icon:"layers",desc:"Inspect the workspace",w:290,h:440,tool:!0,singleton:!0},activity:{title:"Activity",icon:"activity",desc:"Activity timeline",w:322,h:460,tool:!0,singleton:!0},notifications:{title:"Notifications",icon:"bell",desc:"Review alerts & updates",w:300,h:360,tool:!0,singleton:!0},resources:{title:"Resources",icon:"cube",desc:"System resources",w:300,h:320,tool:!0,singleton:!0},connector:{title:"Knowledge Connector",icon:"server",accent:!0,desc:"Pick a Local Knowledge connector",w:320,h:380,min:{w:220,h:180},config:[],cta:"Select connector"},localKnowledge:{title:"Local Knowledge",icon:"localKnowledge",accent:!0,desc:"Manage knowledge capsules",w:720,h:560,min:{w:360,h:320},tiny:{w:300,h:220},tool:!0,singleton:!0},quality:{title:"Quality Intelligence",icon:"check",accent:!0,desc:"Design & review test cases",w:384,h:580,min:{w:300,h:320},tiny:{w:260,h:200},tool:!0,singleton:!0},promptEnhancer:{title:"Prompt Enhancer",icon:"spark",accent:!0,desc:"Turn a raw prompt into a governed, reviewable Enhanced Prompt",w:460,h:620,min:{w:340,h:360},tiny:{w:280,h:220},tool:!0,singleton:!0},qiRun:{title:"QI Run",icon:"check",desc:"Generated test cases",w:760,h:660,min:{w:320,h:280},tiny:{w:280,h:200},config:[{key:"runId",label:"Run ID",type:"text",def:""}]},relationships:{title:"Relationships",icon:"branch",accent:!0,desc:"Inspect the relationship graph",w:760,h:600,min:{w:360,h:320},tiny:{w:300,h:220},tool:!0,singleton:!0},figma:{title:"Figma Snapshot",icon:"layers",accent:!0,desc:"Manage Figma snapshots",w:420,h:540,min:{w:320,h:360},tiny:{w:280,h:240},tool:!0,singleton:!0},figmaView:{title:"Figma View",icon:"layers",accent:!0,desc:"Inspect a scoped Figma screen view",w:360,h:360,min:{w:300,h:260},tiny:{w:260,h:200}},figmaJson:{title:"Figma JSON",icon:"file",accent:!0,desc:"Inspect scoped Figma Screen-IR JSON",w:520,h:540,min:{w:340,h:300},tiny:{w:280,h:220}},figmaImage:{title:"Figma Image",icon:"file",accent:!0,desc:"Inspect a scoped Figma screen render",w:560,h:420,min:{w:300,h:240},tiny:{w:240,h:180}}},R=new Map();function E(e,t){R.set(e,t);}let $=(l={},Object.keys(I).forEach(e=>{var t,n,a;let i,r;l[e]=(i={title:(t=I[e]).title,icon:t.icon,desc:t.desc,w:t.w,h:t.h,min:null!=(n=t.min)?n:S,tiny:null!=(a=t.tiny)?a:C,render:(t,n)=>{let l=R.get(e);return void 0!==l?l(t,n):null;}},r={},!0===t.accent&&(r.accent=!0),!0===t.tool&&(r.tool=!0),!0===t.singleton&&(r.singleton=!0),void 0!==t.config&&(r.config=t.config),void 0!==t.cta&&(r.cta=t.cta),{...i,...r});}),l),A={agents:["files","terminal","plugins","review","browser","agents","keiko"],chat:["files","browser","plugins","keiko","connector"],files:["agents","chat","quality","editor"],editor:["files","connector"],terminal:["agents"],plugins:["agents","chat"],review:["agents"],browser:["agents","chat"],keiko:["agents","chat"],connector:["chat","quality","editor"],quality:["files","connector","figma","figmaView","figmaJson","figmaImage"],figma:["quality"],figmaView:["quality"],figmaJson:["quality"],figmaImage:["quality"]};function F(e,t){var n,l;return void 0!==e&&void 0!==t&&e!==t&&((null!=(n=A[e])?n:[]).includes(t)||(null!=(l=A[t])?l:[]).includes(e));}function T(e,t){let n="files"===e.type?e:"files"===t.type?t:null,l=null===n?null:n===e?t:e;if(null!==n&&null!==l&&("chat"===l.type||"agents"===l.type||"quality"===l.type||"editor"===l.type)){let e=function(e){if(void 0===e)return null;let t=e.resolvedRoot;if("string"==typeof t&&t.length>0)return t;let n=e.root;return"string"==typeof n&&n.length>0?n:null;}(n.cfg);return null===e?"no folder selected":`uses ${function(e,t){var n,l,a;let i=null==e?void 0:e.activeFilePath;if("string"==typeof i&&i.length>0)return null!=(l=i.split(/[/\\]/u).filter(Boolean).pop())?l:i;let r=null==e?void 0:e.activeDirectoryPath;return"string"==typeof r&&r.length>0?`${null!=(a=r.split(/[/\\]/u).filter(Boolean).pop())?a:r}/`:`${null!=(n=t.split(/[/\\]/u).filter(Boolean).pop())?n:t}/`;}(n.cfg,e)}`;}let a=[e.type,t.type];if(a.includes("connector"))return"uses knowledge";if(a.includes("figmaJson"))return"uses JSON";if(a.includes("figmaImage"))return"uses image";if(a.includes("figmaView"))return"uses view";if(a.includes("figma")){var i;let n="figma"===e.type?e:"figma"===t.type?t:null,l=null==n||null==(i=n.cfg)?void 0:i.selectedScreenName;return"string"==typeof l&&l.trim().length>0?"uses view":"uses snapshot";}return a.includes("keiko")?"governed by":"agents"===a[0]&&"agents"===a[1]?"delegates":a.includes("terminal")?"runs in":a.includes("plugins")?"uses tools":a.includes("review")?"reviews":a.includes("browser")?"browses":"connected";}function D(e){return{left:{x:e.x,y:e.y,w:e.w/2,h:e.h},right:{x:e.x+e.w/2,y:e.y,w:e.w/2,h:e.h},maxi:{x:e.x,y:e.y,w:e.w,h:e.h},tl:{x:e.x,y:e.y,w:e.w/2,h:e.h/2},tr:{x:e.x+e.w/2,y:e.y,w:e.w/2,h:e.h/2},bl:{x:e.x,y:e.y+e.h/2,w:e.w/2,h:e.h/2},br:{x:e.x+e.w/2,y:e.y+e.h/2,w:e.w/2,h:e.h/2}};}function q(e,t){if(void 0===t)return null;let n=e=>{let n=t[e];return"string"==typeof n&&n.length>0?n:null;};switch(e){case"files":return n("root");case"browser":return n("url");case"editor":{let e=n("file"),t=n("root");return null!==e&&null!==t?`${e} — ${t}`:e;}case"terminal":return n("cwd");case"review":{let e=n("base"),t=n("head");return null!==e&&null!==t?`${e} → ${t}`:null;}case"agents":return n("role");case"chat":{let e=n("title");return null!==e&&"New chat"!==e?e:null;}case"figma":case"figmaView":return n("selectedScreenName");case"figmaJson":var l;return null!=(l=n("selectedScreenName"))?l:n("screenId");default:return null;}}function M(e){let{winCount:t,windows:n,windowPaletteOpen:l,onToggleWindowPalette:r,onSelectWindow:s,onCloseWindowPalette:o,statusRef:c}=e,d=(0,i.useRef)(null),[u,p]=(0,i.useState)("version loading"),m=`${String(t)} ${1===t?"window":"windows"}`,h=[...n].sort((e,t)=>t.z-e.z);return(0,i.useEffect)(()=>{let e=!1;return async function(){try{let t=await(0,k.T7)();e||p(t.version);}catch{e||p("version unavailable");}}(),()=>{e=!0;};},[]),(0,i.useEffect)(()=>{if(!l)return;if(0===t)return void o();let e=e=>{let t=e.target;t instanceof Node&&null!==d.current&&!d.current.contains(t)&&o();},n=e=>{"Escape"===e.key&&o();};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",n),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",n);};},[o,t,l]),(0,a.jsxs)("footer",{ref:c,className:"footer mono",tabIndex:-1,"aria-label":"Workspace status","aria-live":"polite",children:[(0,a.jsx)("span",{className:"spacer"}),(0,a.jsxs)("span",{className:"ft-brand","aria-label":`Keiko version ${u}`,children:["Keiko | ",u]}),(0,a.jsxs)("span",{className:"ft-window-wrap",ref:d,children:[(0,a.jsxs)("button",{type:"button",className:"ft-seg ft-accent ft-window-trigger ui-tip","aria-atomic":"true","aria-expanded":l,"aria-controls":"footer-window-palette",disabled:0===t,"data-tip":"Open windows",onClick:r,children:[(0,a.jsx)(N.F.tile,{size:13})," ",m]}),l&&t>0?(0,a.jsxs)("div",{id:"footer-window-palette",className:"ft-window-palette",role:"menu","aria-label":"Open windows",children:[(0,a.jsx)("div",{className:"ft-window-palette-head",children:"Open windows"}),(0,a.jsx)("div",{className:"ft-window-list",children:h.map(e=>{let t=$[e.type],n=N.F[t.icon],l=q(e.type,e.cfg),i=!0===e.minimized?"Minimized":e.max?"Fullscreen":"Visible",r=!0===e.minimized?"Restore":"Focus";return(0,a.jsxs)("button",{type:"button",className:"ft-window-card",role:"menuitem","data-minimized":!0===e.minimized?"true":"false","aria-label":`${r} ${t.title} window${null!==l?` - ${l}`:""}`,onClick:()=>s(e.id),children:[(0,a.jsx)("span",{className:"ft-window-icon",style:{color:!0===t.accent?"var(--accent)":void 0},children:(0,a.jsx)(n,{size:14})}),(0,a.jsxs)("span",{className:"ft-window-copy",children:[(0,a.jsx)("span",{className:"ft-window-title",children:t.title}),(0,a.jsx)("span",{className:"ft-window-sub",title:null!=l?l:i,children:null!=l?l:i})]}),(0,a.jsx)("span",{className:"ft-window-state",children:i})]},e.id);})})]}):null]})]});}function P(e){let{openPalette:t,openCommandPalette:n,onTileAll:l,onSplitFront:i,onCascade:r}=e;return(0,a.jsxs)("header",{className:"header",children:[(0,a.jsxs)("div",{className:"hd-brand",children:[(0,a.jsx)("img",{className:"hd-logo",src:"/assets/keiko-logo.svg",alt:""}),(0,a.jsx)("span",{className:"hd-wordmark",children:"Keiko"})]}),(0,a.jsx)("span",{className:"spacer"}),(0,a.jsxs)("div",{className:"hd-tools",children:[(0,a.jsx)("button",{type:"button",className:"hd-tool ui-tip",onClick:l,"data-tip":"Tile all windows","aria-label":"Tile all windows",children:(0,a.jsx)(N.F.tile,{size:16})}),(0,a.jsx)("button",{type:"button",className:"hd-tool ui-tip",onClick:i,"data-tip":"Split front windows","aria-label":"Split front windows",children:(0,a.jsx)(N.F.split,{size:16})}),(0,a.jsx)("button",{type:"button",className:"hd-tool ui-tip",onClick:r,"data-tip":"Cascade windows","aria-label":"Cascade windows",children:(0,a.jsx)(N.F.cascade,{size:16})})]})]});}let L=[{id:"chatHistory",icon:"archive",label:"Chat History"}];function z(e){let{tool:t,active:n,onClick:l}=e,i=N.F[t.icon];return(0,a.jsx)("button",{type:"button",className:"rail-btn","data-active":n?"true":"false","data-side":"left","aria-label":t.label,"aria-pressed":n,"data-tip":t.label,onClick:l,children:void 0!==t.img?(0,a.jsx)("img",{className:"rail-img",src:t.img,alt:""}):(0,a.jsx)(i,{size:19})});}function O(e){let{openTools:t,onTool:n,onNewChat:l,theme:i,onToggleTheme:r}=e;return(0,a.jsxs)("nav",{className:"rail rail-left","aria-label":"Primary workspace navigation",children:[(0,a.jsx)("button",{type:"button",className:"rail-new",onClick:l,"data-side":"left","aria-label":"New chat","data-tip":"New chat",children:(0,a.jsx)(N.F.newChat,{size:18})}),(0,a.jsx)("div",{className:"rail-div"}),(0,a.jsx)("div",{className:"rail-group",children:L.map(e=>(0,a.jsx)(z,{tool:e,active:t.has(e.id),onClick:()=>n(e.id)},e.id))}),(0,a.jsx)("span",{className:"spacer"}),(0,a.jsxs)("div",{className:"rail-group",children:[(0,a.jsx)("button",{type:"button",className:"rail-btn","data-active":t.has("memoria")?"true":"false","data-side":"left","aria-label":"MemoriaViva","aria-pressed":t.has("memoria"),"data-tip":"MemoriaViva",onClick:()=>n("memoria"),children:(0,a.jsx)(N.F.brain,{size:19})}),(0,a.jsx)("button",{type:"button",className:"rail-btn","data-side":"left","data-active":t.has("quality")?"true":"false","aria-label":"Quality Intelligence","aria-pressed":t.has("quality"),"data-tip":"Quality Intelligence",onClick:()=>n("quality"),children:(0,a.jsx)(N.F.check,{size:19})}),(0,a.jsx)("button",{type:"button",className:"rail-btn","data-side":"left","data-active":t.has("promptEnhancer")?"true":"false","aria-label":"Prompt Enhancer","aria-pressed":t.has("promptEnhancer"),"data-tip":"Prompt Enhancer",onClick:()=>n("promptEnhancer"),children:(0,a.jsx)(N.F.spark,{size:19})}),(0,a.jsx)("button",{type:"button",className:"rail-btn","data-side":"left","data-active":t.has("localKnowledge")?"true":"false","aria-label":"Local Knowledge","aria-pressed":t.has("localKnowledge"),"data-tip":"Local Knowledge",onClick:()=>n("localKnowledge"),children:(0,a.jsx)(N.F.localKnowledge,{size:19})}),(0,a.jsx)("button",{type:"button",className:"rail-btn","data-side":"left","data-active":t.has("figma")?"true":"false","aria-label":"Figma Snapshot","aria-pressed":t.has("figma"),"data-tip":"Figma Snapshot",onClick:()=>n("figma"),children:(0,a.jsx)(N.F.layers,{size:19})})]}),(0,a.jsx)("div",{className:"rail-div"}),(0,a.jsx)("button",{type:"button",className:"rail-btn","data-side":"left","aria-label":"light"===i?"Dark mode":"Light mode","aria-pressed":"light"===i,"data-tip":"light"===i?"Dark mode":"Light mode",onClick:r,children:"light"===i?(0,a.jsx)(N.F.moon,{size:19}):(0,a.jsx)(N.F.sun,{size:19})}),(0,a.jsx)("button",{type:"button",className:"rail-btn","data-side":"left","data-active":t.has("settings")?"true":"false","aria-label":"Settings","aria-pressed":t.has("settings"),"data-tip":"Settings",onClick:()=>n("settings"),children:(0,a.jsx)(N.F.settings,{size:19})})]});}function K(e){return(0,a.jsx)("aside",{className:"rail rail-right","aria-label":"Workspace utilities",children:(0,a.jsx)("span",{className:"spacer"})});}function B(e){return e.toFixed(2);}function W(e){let{onNewWindow:t}=e,n=(0,i.useId)(),l=`ewb-${n.replace(/:/gu,"")}`,r=(0,i.useRef)(null),s=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=e=>{var t;null==(t=r.current)||t.setAttribute("d",function(e){var t,n,l,a;let i=[];for(let t=0;t<150;t++){let n=t/150*Math.PI*2,l=1+.07*(.55*Math.sin(3*n+e)+.32*Math.sin(5*n-.8*e+1.7)+.22*Math.sin(2*n+.5*e+.4));i.push([140+127.44000000000001*l*Math.cos(n),140+118*l*Math.sin(n)]);}let r=`M${B(null!=(t=null==(l=i[0])?void 0:l[0])?t:140)} ${B(null!=(n=null==(a=i[0])?void 0:a[1])?n:140)} `;for(let e=0;e<i.length;e++){let t=i[(e-1+i.length)%i.length],n=i[e],l=i[(e+1)%i.length],a=i[(e+2)%i.length],s=n[0]+(l[0]-t[0])/6,o=n[1]+(l[1]-t[1])/6,c=l[0]-(a[0]-n[0])/6,d=l[1]-(a[1]-n[1])/6;r+=`C${B(s)} ${B(o)} ${B(c)} ${B(d)} ${B(l[0])} ${B(l[1])} `;}return`${r}Z`;}(e));};if(e(.7),"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches||"function"!=typeof window.requestAnimationFrame)return;let t=0,n=()=>{0!==t&&(window.cancelAnimationFrame(t),t=0);},l=n=>{e(85e-5*n),t=window.requestAnimationFrame(l);},a=()=>{0===t&&!0!==document.hidden&&(t=window.requestAnimationFrame(l));},i=()=>{!0===document.hidden?n():a();};return a(),document.addEventListener("visibilitychange",i),window.addEventListener("blur",n),window.addEventListener("focus",a),()=>{n(),document.removeEventListener("visibilitychange",i),window.removeEventListener("blur",n),window.removeEventListener("focus",a);};},[]);let o=(0,i.useCallback)(()=>{let e=s.current;null!==e&&(e.classList.remove("is-pulse"),e.getBoundingClientRect(),e.classList.add("is-pulse")),t();},[t]);return(0,a.jsx)("button",{type:"button",className:"empty-workspace-blob","aria-label":"Open a new window",onClick:o,children:(0,a.jsxs)("svg",{width:"320",height:"320",viewBox:"0 0 280 280","aria-hidden":"true",children:[(0,a.jsx)("defs",{children:(0,a.jsxs)("mask",{id:l,maskUnits:"userSpaceOnUse",x:"0",y:"0",width:"280",height:"280",children:[(0,a.jsx)("rect",{x:"0",y:"0",width:"280",height:"280",fill:"#fff"}),(0,a.jsx)("g",{transform:"translate(107,64) scale(0.080625)",children:(0,a.jsx)("g",{transform:"translate(1024 0) scale(-1 1)",children:(0,a.jsx)("g",{transform:"translate(1024,1024) scale(-0.1,-0.1)",fill:"#000",children:(0,a.jsx)("path",{d:"M3465 8223 c-144 -8 -314 -52 -408 -105 -69 -39 -146 -99 -146 -113 0 -5 30 -24 68 -42 146 -70 323 -229 377 -340 25 -49 29 -70 29 -138 -1 -72 -5 -88 -39 -160 -36 -75 -54 -95 -265 -305 -134 -132 -270 -279 -331 -355 -339 -425 -552 -896 -626 -1390 -25 -165 -25 -549 0 -720 92 -645 368 -1196 826 -1655 322 -324 710 -562 1145 -704 389 -126 793 -172 1155 -130 235 27 377 63 579 149 205 87 268 86 423 -7 102 -62 231 -115 335 -138 247 -56 562 -26 794 74 92 40 244 136 232 146 -4 3 -26 12 -48 19 -86 28 -246 116 -385 211 -162 112 -284 182 -357 207 l-48 17 40 15 c185 70 436 223 595 363 438 386 695 1014 678 1663 l-3 120 -50 -70 c-64 -90 -248 -280 -350 -362 -171 -136 -366 -255 -645 -391 -288 -140 -442 -243 -590 -391 -136 -137 -247 -316 -325 -526 -47 -127 -114 -262 -160 -326 -79 -107 -237 -224 -384 -283 -136 -55 -355 -96 -514 -96 -274 0 -548 71 -832 215 -242 123 -375 216 -553 389 -175 171 -287 332 -361 517 -44 114 -63 216 -63 359 0 152 17 233 74 350 35 70 59 102 136 179 l95 94 21 -29 c55 -75 219 -277 277 -338 171 -183 337 -256 582 -256 56 0 126 -3 155 -7 53 -6 54 -7 76 -57 30 -66 97 -128 172 -156 151 -57 318 11 395 160 33 62 34 193 3 261 -30 64 -88 125 -148 157 -44 23 -63 27 -141 27 -78 0 -97 -4 -140 -27 -58 -30 -131 -105 -141 -142 -6 -25 -8 -26 -93 -26 -47 0 -131 5 -186 10 -87 8 -111 15 -182 51 -45 22 -109 66 -143 96 -59 53 -326 361 -319 367 14 11 179 47 241 52 102 9 177 -7 318 -66 158 -66 243 -89 357 -99 157 -12 413 5 582 40 l93 19 44 -39 c59 -52 135 -75 228 -69 117 8 212 72 262 176 23 47 28 71 28 138 0 70 -4 89 -29 138 -55 110 -145 167 -270 174 -65 3 -91 0 -137 -18 -107 -40 -183 -140 -195 -257 l-6 -52 -51 -11 c-104 -23 -285 -41 -411 -42 -149 -1 -211 12 -402 88 -186 74 -256 88 -403 81 -193 -8 -377 -70 -546 -182 -342 -228 -485 -611 -399 -1064 30 -157 119 -388 209 -541 20 -35 35 -64 33 -66 -8 -8 -111 108 -190 214 -154 206 -278 489 -324 737 -28 154 -25 492 6 635 46 216 133 391 256 514 82 82 161 128 271 156 152 39 300 23 529 -57 217 -76 308 -101 410 -114 137 -17 284 -7 426 30 272 70 414 145 809 425 217 153 399 238 610 283 64 14 129 18 265 18 197 0 269 -9 615 -76 461 -89 843 -149 952 -149 41 0 41 0 23 -20 -28 -31 -169 -119 -254 -158 -167 -77 -388 -145 -716 -222 -399 -93 -508 -128 -608 -194 -102 -68 -160 -160 -217 -346 -35 -115 -102 -286 -149 -378 -85 -168 -227 -341 -377 -458 -105 -82 -115 -107 -69 -162 29 -34 65 -44 109 -29 86 29 261 181 371 322 126 162 201 309 295 581 61 176 90 232 145 283 62 57 163 93 470 165 439 104 640 169 863 278 206 100 368 240 434 375 32 67 33 71 33 198 -1 120 -3 138 -34 229 -98 294 -319 655 -573 936 -381 421 -968 723 -1618 834 -448 76 -767 83 -1169 25 -80 -12 -165 -19 -190 -17 -26 3 -90 26 -146 53 -343 162 -576 233 -842 255 -114 9 -141 10 -248 3z m2926 -1227 c164 -27 346 -102 485 -202 181 -129 354 -348 354 -448 0 -64 -75 -126 -154 -126 -60 0 -63 4 -52 70 8 50 7 65 -9 100 -29 64 -74 93 -151 98 -54 4 -70 1 -107 -21 -42 -25 -61 -52 -91 -129 -25 -64 -55 -73 -246 -73 -121 0 -187 5 -248 18 -318 70 -556 242 -556 402 0 218 388 374 775 311z m-2249 -611 c119 -21 208 -50 321 -106 114 -56 177 -100 266 -184 67 -63 157 -173 148 -181 -2 -3 -61 18 -130 45 -131 52 -298 100 -427 122 -113 20 -367 17 -470 -4 -502 -106 -885 -433 -1160 -992 -70 -142 -160 -379 -160 -424 0 -9 -5 -23 -11 -31 -13 -19 -5 316 10 410 80 482 295 846 661 1117 145 107 350 197 522 228 100 18 326 18 430 0z m1485 -1456 c95 -36 119 -159 42 -223 -78 -66 -209 -1 -209 104 0 60 33 100 99 121 36 10 36 10 68 -2z m-591 -822 c29 -26 37 -42 40 -77 6 -54 -9 -86 -55 -117 -41 -28 -70 -29 -119 -4 -44 22 -62 55 -62 112 0 51 13 75 53 99 50 31 101 26 143 -13z"})})})}),(0,a.jsx)("text",{x:"140",y:"172",textAnchor:"middle",fill:"#000",fontFamily:"var(--font-ui)",fontSize:"16",fontWeight:"700",children:"Empty workspace"}),(0,a.jsx)("text",{x:"140",y:"191",textAnchor:"middle",fill:"#000",fontFamily:"var(--font-ui)",fontSize:"11",fontWeight:"400",children:"Open a window to start working"})]})}),(0,a.jsx)("g",{ref:s,className:"empty-workspace-blob__group",children:(0,a.jsx)("path",{ref:r,className:"empty-workspace-blob__fill",mask:`url(#${l})`})})]})});}function U(e){return 0===e.button&&!(0===e.button&&e.ctrlKey);}function _(e){return e instanceof Element&&null!==e.closest("button,input,textarea,select,a[href],summary,[contenteditable='true'],[contenteditable=''],[role='button'],[role='checkbox'],[role='dialog'],[role='link'],[role='menuitem'],[role='option'],[role='radio'],[role='switch'],[role='tab'],.dlg-overlay,.mc-dialog-backdrop,.cmdk-overlay,.window,.ws-zoom,.ws-fab,.empty-workspace-blob,.conn-badge");}function V(){return!("u"<typeof document)&&"true"===document.documentElement.getAttribute("data-keiko-modal-open");}let H=0,J="",Y="";function X(){if("u"<typeof document)return()=>void 0;let e=document.body;0===H&&(J=e.style.cursor,Y=e.style.userSelect,e.style.cursor="grabbing",e.style.userSelect="none"),H+=1;let t=!1;return()=>{t||(t=!0,0===(H=Math.max(0,H-1))&&(e.style.cursor=J,e.style.userSelect=Y));};}let G="keiko.wallpaper.enabled",Q="keiko.wallpaper.opacity",Z="keiko.workspace.background.brightness",ee="keiko.workspace.grid.strength",et="keiko.frame.border.strength",en="keiko.frame.inner.glow.strength",el="keiko:wallpaper-enabled",ea="keiko:wallpaper-opacity",ei="keiko:workspace-background-brightness",er="keiko:workspace-grid-strength",es="keiko:frame-border-strength",eo="keiko:frame-inner-glow-strength";function ec(e){return Number.isFinite(e)?Math.max(0,Math.min(100,e)):0;}function ed(){try{var e;if("function"!=typeof(null==(e=window.localStorage)?void 0:e.getItem))return!1;return"true"===window.localStorage.getItem(G);}catch{return!1;}}function eu(){try{var e;if("function"!=typeof(null==(e=window.localStorage)?void 0:e.getItem))return 100;let t=window.localStorage.getItem(Q);if(null===t)return 100;return ec(Number.parseInt(t,10));}catch{return 100;}}function ep(){try{var e;if("function"!=typeof(null==(e=window.localStorage)?void 0:e.getItem))return 0;let t=window.localStorage.getItem(Z);if(null===t)return 0;return ec(Number.parseInt(t,10));}catch{return 0;}}function em(){try{var e;if("function"!=typeof(null==(e=window.localStorage)?void 0:e.getItem))return 28;let t=window.localStorage.getItem(ee);if(null===t)return 28;return ec(Number.parseInt(t,10));}catch{return 28;}}function eh(){try{var e;if("function"!=typeof(null==(e=window.localStorage)?void 0:e.getItem))return 42;let t=window.localStorage.getItem(et);if(null===t)return 42;return ec(Number.parseInt(t,10));}catch{return 42;}}function ef(){try{var e;if("function"!=typeof(null==(e=window.localStorage)?void 0:e.getItem))return 0;let t=window.localStorage.getItem(en);if(null===t)return 0;return ec(Number.parseInt(t,10));}catch{return 0;}}function eg(e){"u">typeof document&&document.documentElement.style.setProperty("--workspace-bg-brightness",`${ec(e)}%`);}function ev(e){"u">typeof document&&document.documentElement.style.setProperty("--workspace-grid-strength",`${ec(e)}%`);}function eb(e){"u">typeof document&&document.documentElement.style.setProperty("--frame-border-strength",`${ec(e)}%`);}function ex(e){"u">typeof document&&document.documentElement.style.setProperty("--frame-inner-glow-strength",`${ec(e)}%`);}let ey=`
|
|
2
|
-
attribute vec2 aPos;
|
|
3
|
-
void main(){ gl_Position = vec4(aPos, 0.0, 1.0); }
|
|
4
|
-
`,ew=`
|
|
5
|
-
precision highp float;
|
|
6
|
-
uniform vec2 uRes;
|
|
7
|
-
uniform float uTime;
|
|
8
|
-
uniform float uLight; // 1 = light theme, 0 = dark; WebGL default 0 keeps failure mode dark
|
|
9
|
-
uniform vec2 uRip[4]; // ripple origins (0..1, y up)
|
|
10
|
-
uniform float uRipT[4]; // seconds since each ripple fired (large = inactive)
|
|
11
|
-
|
|
12
|
-
float hash(vec2 p){
|
|
13
|
-
p = fract(p * vec2(123.34, 456.21));
|
|
14
|
-
p += dot(p, p + 45.32);
|
|
15
|
-
return fract(p.x * p.y);
|
|
16
|
-
}
|
|
17
|
-
float vnoise(vec2 p){
|
|
18
|
-
vec2 i = floor(p), f = fract(p);
|
|
19
|
-
vec2 u = f * f * (3.0 - 2.0 * f);
|
|
20
|
-
float a = hash(i), b = hash(i + vec2(1.,0.));
|
|
21
|
-
float c = hash(i + vec2(0.,1.)), d = hash(i + vec2(1.,1.));
|
|
22
|
-
return mix(mix(a,b,u.x), mix(c,d,u.x), u.y);
|
|
23
|
-
}
|
|
24
|
-
float fbm(vec2 p){
|
|
25
|
-
float v = 0.0, a = 0.5;
|
|
26
|
-
mat2 m = mat2(1.6, 1.2, -1.2, 1.6);
|
|
27
|
-
for(int i = 0; i < 5; i++){ v += a * vnoise(p); p = m * p; a *= 0.5; }
|
|
28
|
-
return v;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
void main(){
|
|
32
|
-
vec2 uv = gl_FragCoord.xy / uRes.xy;
|
|
33
|
-
float aspect = uRes.x / uRes.y;
|
|
34
|
-
vec2 p = vec2(uv.x * aspect, uv.y);
|
|
35
|
-
|
|
36
|
-
float t = uTime * 0.06;
|
|
37
|
-
|
|
38
|
-
// --- click ripples ---------------------------------------------------
|
|
39
|
-
float rip = 0.0;
|
|
40
|
-
for(int i = 0; i < 4; i++){
|
|
41
|
-
float age = uRipT[i];
|
|
42
|
-
if(age < 2.4){
|
|
43
|
-
vec2 rc = vec2(uRip[i].x * aspect, uRip[i].y);
|
|
44
|
-
float d = distance(p, rc);
|
|
45
|
-
float ring = sin(d * 15.0 - age * 9.0);
|
|
46
|
-
float env = exp(-d * 3.6) * exp(-age * 2.1);
|
|
47
|
-
rip += ring * env;
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
// --- liquid domain warp ---------------------------------------------
|
|
52
|
-
vec2 warp = vec2(
|
|
53
|
-
fbm(p * 2.1 + vec2(0.0, t)),
|
|
54
|
-
fbm(p * 2.1 + vec2(t, 4.7))
|
|
55
|
-
);
|
|
56
|
-
warp += rip * 0.07;
|
|
57
|
-
|
|
58
|
-
float f = fbm(p * 2.4 + warp * 1.7 + vec2(t * 0.6, 0.0));
|
|
59
|
-
|
|
60
|
-
// --- chrome banding (sharp metallic streaks) ------------------------
|
|
61
|
-
float bands = abs(sin((f * 4.0 + warp.x * 2.0) * 3.14159 + t * 1.4));
|
|
62
|
-
float chrome = pow(bands, 2.6);
|
|
63
|
-
|
|
64
|
-
// --- palette (brand) -------------------------------------------------
|
|
65
|
-
vec3 baseD = vec3(0.072, 0.085, 0.079); // warm near-black ~ --bg
|
|
66
|
-
vec3 metalD = vec3(0.205, 0.230, 0.216); // chrome mid grey
|
|
67
|
-
vec3 baseL = vec3(0.930, 0.942, 0.935); // near-white
|
|
68
|
-
vec3 metalL = vec3(0.795, 0.835, 0.812); // soft grey
|
|
69
|
-
vec3 green = vec3(0.306, 0.729, 0.529); // #4EBA87
|
|
70
|
-
|
|
71
|
-
vec3 base = mix(baseD, baseL, uLight);
|
|
72
|
-
vec3 metal = mix(metalD, metalL, uLight);
|
|
73
|
-
|
|
74
|
-
vec3 col = mix(base, metal, chrome * 0.85);
|
|
75
|
-
|
|
76
|
-
// orca-green sheen on the brightest specular ridges
|
|
77
|
-
float spec = smoothstep(0.80, 1.0, bands);
|
|
78
|
-
col += green * spec * mix(0.16, 0.085, uLight);
|
|
79
|
-
|
|
80
|
-
// ripple highlight
|
|
81
|
-
vec3 ripCol = mix(vec3(1.0), green, uLight);
|
|
82
|
-
col += ripCol * max(rip, 0.0) * 0.032;
|
|
83
|
-
|
|
84
|
-
// keep it dezent — pull back toward base
|
|
85
|
-
col = mix(base, col, 0.84);
|
|
86
|
-
|
|
87
|
-
gl_FragColor = vec4(col, 1.0);
|
|
88
|
-
}
|
|
89
|
-
`;function ej(e,t,n){let l=e.createShader(t);return null===l?null:(e.shaderSource(l,n),e.compileShader(l),e.getShaderParameter(l,e.COMPILE_STATUS))?l:(e.deleteShader(l),null);}function ek(){let e=(0,i.useRef)(null),[t,n]=(0,i.useState)(ed);return(0,i.useEffect)(()=>{eg(ep()),ev(em()),eb(eh()),ex(ef());let e=e=>{let t=e.detail;eg("number"==typeof t?t:ep());},t=e=>{let t=e.detail;ev("number"==typeof t?t:em());},n=e=>{let t=e.detail;eb("number"==typeof t?t:eh());},l=e=>{let t=e.detail;ex("number"==typeof t?t:ef());};return window.addEventListener(ei,e),window.addEventListener(er,t),window.addEventListener(es,n),window.addEventListener(eo,l),()=>{window.removeEventListener(ei,e),window.removeEventListener(er,t),window.removeEventListener(es,n),window.removeEventListener(eo,l);};},[]),(0,i.useEffect)(()=>{let e=e=>{let t=e.detail;n("boolean"==typeof t?t:ed());},t=e=>{(null===e.key||e.key===G)&&n(ed());};return window.addEventListener(el,e),window.addEventListener("storage",t),()=>{window.removeEventListener(el,e),window.removeEventListener("storage",t);};},[]),(0,i.useEffect)(()=>{let n;if(!t)return;let l=e.current;if(null===l)return;let a=l.parentElement;if(null===a)return;let i=window.matchMedia("(prefers-reduced-motion: reduce)"),r=()=>{i.matches?(null==n||n(),n=void 0):void 0===n&&(n=function(e,t){var n;t.style.opacity=String(eu()/100);let l=e=>{let n=e.detail,l="number"==typeof n?n:eu();t.style.opacity=String(ec(l)/100);};window.addEventListener(ea,l);let a=null;try{a=t.getContext("webgl",{antialias:!1,alpha:!1,premultipliedAlpha:!1,depth:!1});}catch{a=null;}if(null===a)return()=>{window.removeEventListener(ea,l);};let i=ej(a,a.VERTEX_SHADER,ey),r=ej(a,a.FRAGMENT_SHADER,ew);if(null===i||null===r)return()=>{window.removeEventListener(ea,l);};let s=a.createProgram();if(null===s||(a.attachShader(s,i),a.attachShader(s,r),a.linkProgram(s),!a.getProgramParameter(s,a.LINK_STATUS)))return()=>{window.removeEventListener(ea,l);};a.useProgram(s);let o=a.createBuffer();a.bindBuffer(a.ARRAY_BUFFER,o),a.bufferData(a.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),a.STATIC_DRAW);let c=a.getAttribLocation(s,"aPos");a.enableVertexAttribArray(c),a.vertexAttribPointer(c,2,a.FLOAT,!1,0,0);let d=a.getUniformLocation(s,"uRes"),u=a.getUniformLocation(s,"uTime"),p=a.getUniformLocation(s,"uLight"),m=a.getUniformLocation(s,"uRip"),h=a.getUniformLocation(s,"uRipT"),f=1,g=1,v=Math.min(null!=(n=window.devicePixelRatio)?n:1,1.5),b=new Float32Array(8),x=[,,,,].fill(-1/0),y=0;function w(){let n=e.getBoundingClientRect();f=Math.max(1,Math.round(n.width)),g=Math.max(1,Math.round(n.height)),t.width=Math.round(f*v),t.height=Math.round(g*v),t.style.width=`${String(f)}px`,t.style.height=`${String(g)}px`,null!==a&&a.viewport(0,0,t.width,t.height);}w();let j="u">typeof ResizeObserver?new ResizeObserver(w):null;null!==j?j.observe(e):window.addEventListener("resize",w);let k=t=>{let n=e.getBoundingClientRect(),l=(t.clientX-n.left)/Math.max(1,n.width),a=1-(t.clientY-n.top)/Math.max(1,n.height);l<0||l>1||a<0||a>1||(b[2*y]=l,b[2*y+1]=a,x[y]=performance.now(),y=(y+1)%4);};e.addEventListener("pointerdown",k);let N=performance.now(),S=0,C=!0,I=new Float32Array(4);function R(){if(!C)return;let e=performance.now();for(let t=0;t<4;t++){var n;I[t]=(e-(null!=(n=x[t])?n:-1/0))/1e3;}let l=+("light"===document.documentElement.dataset.theme);null!==a&&(a.uniform2f(d,t.width,t.height),a.uniform1f(u,(e-N)/1e3),a.uniform1f(p,l),a.uniform2fv(m,b),a.uniform1fv(h,I),a.drawArrays(a.TRIANGLES,0,3)),S=requestAnimationFrame(R);}S=requestAnimationFrame(R);let E=()=>{document.hidden?(C=!1,cancelAnimationFrame(S)):C||(C=!0,S=requestAnimationFrame(R));};return document.addEventListener("visibilitychange",E),()=>{C=!1,cancelAnimationFrame(S),document.removeEventListener("visibilitychange",E),window.removeEventListener(ea,l),e.removeEventListener("pointerdown",k),null!==j?j.disconnect():window.removeEventListener("resize",w),null!==a&&(a.deleteBuffer(o),a.deleteProgram(s),a.deleteShader(i),a.deleteShader(r));};}(a,l));};return r(),i.addEventListener("change",r),()=>{i.removeEventListener("change",r),null==n||n();};},[t]),t?(0,a.jsx)("canvas",{ref:e,className:"ws-shader","aria-hidden":"true"}):null;}let eN=new Set(["files","connector","browser","plugins","agents","quality"]);function eS(e,t){return e>=4||t>=8192;}function eC(e){let{pathId:t,intensity:n}=e,l="heavy"===n?3:1,i="heavy"===n?1.1:2.2;return(0,a.jsx)(a.Fragment,{children:Array.from({length:l},(e,r)=>(0,a.jsx)("circle",{className:"conn-particle",r:"heavy"===n?3:2.4,"aria-hidden":"true",children:(0,a.jsx)("animateMotion",{dur:`${String(i)}s`,repeatCount:"indefinite",begin:`${String(i/l*r)}s`,rotate:"auto",keyPoints:"0;1",keyTimes:"0;1",calcMode:"linear",children:(0,a.jsx)("mpath",{href:`#${t}`})})},r))});}function eI(e){let{wins:t,conns:n,connecting:l,api:r}=e,s=c(),o=function(){let[e,t]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{let e=window.matchMedia("(prefers-reduced-motion: reduce)");t(e.matches);let n=e=>t(e.matches);return e.addEventListener("change",n),()=>e.removeEventListener("change",n);},[]),e;}(),{armedId:d,arm:u,disarm:p}=function(){let[e,t]=(0,i.useState)(null);return(0,i.useEffect)(()=>{if(null===e)return;let n=setTimeout(()=>t(null),3e3);return()=>clearTimeout(n);},[e]),{armedId:e,arm:e=>t(e),disarm:()=>t(null)};}(),{flowing:m,intensity:h}=function(e,t){let[n,l]=(0,i.useState)("light"),[a,r]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{if(void 0===t)return;l(function(e){switch(e.groundingKind){case"connected-context":return eS(e.contextPack.usage.filesRead,e.contextPack.usage.excerptBytes)?"heavy":"light";case"hybrid":return eS(e.contextPack.folder.usage.filesRead,e.contextPack.folder.usage.excerptBytes)||e.contextPack.knowledge.referencesUsed>=4?"heavy":"light";case"local-knowledge":return e.contextPack.referencesUsed>=4?"heavy":"light";default:return"light";}}(t)),r(!0);let e=setTimeout(()=>r(!1),2500);return()=>clearTimeout(e);},[t]),{flowing:e||a,intensity:n};}((null==s?void 0:s.sending)===!0,null==s?void 0:s.latestGrounded),f=function(e,t){let n=new Map(e.map(e=>[e.id,e])),l=[];for(let e of t){let t=n.get(e.a),a=n.get(e.b);if(void 0===t||void 0===a)continue;let i=function(e,t){let n,l,a,i,r={x:e.x+e.w/2,y:e.y+e.h/2},s={x:t.x+t.w/2,y:t.y+t.h/2},o=s.x-r.x,c=s.y-r.y;if(Math.abs(o)>=Math.abs(c)){n=o>=0?{x:e.x+e.w,y:r.y}:{x:e.x,y:r.y};let c=Math.max(40,Math.abs((l=o>=0?{x:t.x,y:s.y}:{x:t.x+t.w,y:s.y}).x-n.x)/2),d=o>=0?1:-1;a={x:n.x+d*c,y:n.y},i={x:l.x-d*c,y:l.y};}else{n=c>=0?{x:r.x,y:e.y+e.h}:{x:r.x,y:e.y};let o=Math.max(40,Math.abs((l=c>=0?{x:s.x,y:t.y}:{x:s.x,y:t.y+t.h}).y-n.y)/2),d=c>=0?1:-1;a={x:n.x,y:n.y+d*o},i={x:l.x,y:l.y-d*o};}let d={x:(n.x+3*a.x+3*i.x+l.x)/8,y:(n.y+3*a.y+3*i.y+l.y)/8};return{d:`M${String(n.x)},${String(n.y)} C${String(a.x)},${String(a.y)} ${String(i.x)},${String(i.y)} ${String(l.x)},${String(l.y)}`,mid:d};}(t,a);l.push({c:e,d:i.d,mid:i.mid,label:T(t,a),dataChannel:function(e,t){let n=[e.type,t.type].includes("chat"),l="chat"===e.type?eN.has(t.type):eN.has(e.type);return n&&l;}(t,a)});}return l;}(t,n),g=null!==l?function(e,t){let n=t.find(t=>t.id===e.from);if(void 0===n)return null;let l={x:n.x+n.w/2,y:n.y+n.h/2},a=e.x-l.x,i=e.y-l.y,r=Math.abs(a)>=Math.abs(i),s=r?{x:a>=0?n.x+n.w:n.x,y:l.y}:{x:l.x,y:i>=0?n.y+n.h:n.y},o=Math.max(40,Math.abs(r?a:i)/2),c=r?{x:s.x+(a>=0?o:-o),y:s.y}:{x:s.x,y:s.y+(i>=0?o:-o)},d=e.x,u=e.y;return{d:`M${String(s.x)},${String(s.y)} C${String(c.x)},${String(c.y)} ${String(d)},${String(u)} ${String(d)},${String(u)}`,ex:d,ey:u};}(l,t):null;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("div",{className:"conn-layer",children:(0,a.jsxs)("svg",{className:"conn-svg",viewBox:"-10000 -10000 20000 20000",preserveAspectRatio:"xMidYMid meet",children:[f.map(e=>{let t=m&&e.dataChannel,n=`conn-path-${e.c.id}`;return(0,a.jsxs)("g",{children:[(0,a.jsx)("path",{id:n,className:"conn-path",d:e.d,"data-active":t?"true":void 0,"data-intensity":t?h:void 0,"data-reduced-motion":t&&o?"true":void 0}),t&&!o?(0,a.jsx)(eC,{pathId:n,intensity:h}):null]},e.c.id);}),null!==g?(0,a.jsx)("path",{className:"conn-path conn-temp",d:g.d}):null,null!==g?(0,a.jsx)("circle",{className:"conn-dot",cx:g.ex,cy:g.ey,r:"5"}):null]})}),(0,a.jsx)("div",{className:"conn-badge-layer",children:f.map(e=>{let n,l=m&&e.dataChannel;if(!function(e,t){let n,l=arguments.length>2&&void 0!==arguments[2]&&arguments[2],a=(n=Math.min(240,Math.max(40,7.2*e.label.length))+(44+18*!!l),{left:e.mid.x-n/2,right:e.mid.x+n/2,top:e.mid.y-13,bottom:e.mid.y+13});return!t.some(e=>{var t;return!0!==e.minimized&&(t={left:e.x,top:e.y,right:e.x+e.w,bottom:e.y+e.h},a.left<t.right&&a.right>t.left&&a.top<t.bottom&&a.bottom>t.top);});}(e,t,l))return null;let i=d===e.c.id,s=(n=[`Connection: ${e.label}`],void 0!==e.c.boundRoot&&n.push(`Root: ${e.c.boundRoot}`),void 0!==e.c.boundScopeKind&&n.push(`Scope: ${e.c.boundScopeKind}`),void 0!==e.c.boundRelativePath&&e.c.boundRelativePath.length>0&&n.push(`Path: ${e.c.boundRelativePath}`),void 0!==e.c.boundConnectorKind&&void 0!==e.c.boundConnectorId&&n.push(`Knowledge: ${e.c.boundConnectorKind} ${e.c.boundConnectorId}`),n.join("\n"));return(0,a.jsxs)("button",{type:"button",className:"conn-badge","data-active":l?"true":void 0,"data-intensity":l?h:void 0,"data-armed":i?"true":void 0,style:{left:e.mid.x,top:e.mid.y},onClick:()=>{i?(p(),r.removeConn(e.c.id)):u(e.c.id);},onBlur:()=>{i&&p();},title:i?`Click again to remove: ${e.label}
|
|
90
|
-
|
|
91
|
-
${s}`:`${s}
|
|
92
|
-
|
|
93
|
-
Click once to arm removal.`,"aria-label":i?`Confirm removal of connection: ${e.label}. Activate again to remove.`:l?`${e.label} — ${h} data exchange in progress. Activate to remove connection.`:`Remove connection: ${e.label}`,children:[(0,a.jsx)(N.F.git,{size:11})," ",(0,a.jsx)("span",{children:i?"Remove?":e.label}),l&&!i?(0,a.jsx)("span",{className:"conn-flow-tag","aria-hidden":"true",children:"heavy"===h?"⇶":"→"}):null]},e.c.id);})})]});}let eR=["n","s","e","w","ne","nw","se","sw"],eE=["t","r","b","l"];function e$(e){let{icon:t,label:n}=e,l=N.F[t];return(0,a.jsxs)("div",{className:"too-small",children:[(0,a.jsx)("div",{className:"ts-ico",children:(0,a.jsx)(l,{size:28})}),(0,a.jsxs)("div",{className:"ts-title",children:["Too small to show ",n]}),(0,a.jsx)("div",{className:"ts-sub",children:"Enlarge the window or zoom its content out"}),(0,a.jsx)("div",{className:"ts-arrow","aria-hidden":"true",children:(0,a.jsx)("svg",{width:"22",height:"22",viewBox:"0 0 22 22",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:(0,a.jsx)("path",{d:"M8 8l8 8M16 11v5h-5"})})})]});}function eA(e){var t,n,l,r,s,o;let{win:c,top:d,connState:u,view:p,api:m,wsRef:h}=e,f=$[c.type],g=void 0!==(s=c.type)&&((null!=(o=A[s])?o:[]).length>0||Object.values(A).some(e=>e.includes(s))),v=N.F[f.icon],[b,x]=(0,i.useState)(!1),y=(0,i.useRef)(null),w=(0,i.useRef)(null),j=null!=(t=c.zoom)?t:1,k="chat"===c.type||"agents"===c.type||"quality"===c.type||"editor"===c.type,S="agents"===c.type||"quality"===c.type||"editor"===c.type,C="quality"===c.type||"editor"===c.type,I=k?m.linkedFilesRoot(c.id):null,R=S?null==(n=m.linkedFilesContext(c.id))?void 0:n.activeFilePath:void 0,E="quality"===c.type?m.linkedAllFilesRoots(c.id):null!==I?[I]:[],F=C?m.linkedConnectorCapsuleIds(c.id):[],T=C?m.linkedConnectorCapsuleSetIds(c.id):[],D="quality"===c.type?m.linkedFigmaSnapshotRunIds(c.id):[],M="quality"===c.type?null==(l=m.linkedFigmaSnapshotSources)?void 0:l.call(m,c.id):void 0,P="quality"===c.type?null==(r=m.linkedImageSources)?void 0:r.call(m,c.id):void 0,L=c.w/j,z=c.h/j,O=(0,i.useCallback)(e=>{m.update(c.id,{cfg:{...c.cfg,...e}});},[m,c.cfg,c.id]),K=(0,i.useCallback)((e,t)=>m.add(e,t),[m]),{mode:B,node:W}=function(e,t,n,l,i,r,s,o,c,d,u,p,m,h,f){let g=$[t];if("chat"===t){let t=n<520,a=n<430;return{mode:a?"mini":"full",node:g.render(i,{windowId:e,mini:a,minimalChat:n<360||l<320,compact:n<640,controlsNarrow:t,barCompact:n<520,workflowCompact:t,linkedRoot:r,linkedFilePath:s,linkedRoots:o,linkedCapsuleIds:c,linkedCapsuleSetIds:d,linkedFigmaSnapshotRunIds:u,linkedFigmaSnapshotSources:p,linkedImageSources:m,updateCfg:h,openWindow:f})};}return n<g.tiny.w||l<g.tiny.h?{mode:"tiny",node:(0,a.jsx)(e$,{icon:g.icon,label:g.title})}:{mode:"full",node:g.render(i,{windowId:e,linkedRoot:r,linkedFilePath:s,linkedRoots:o,linkedCapsuleIds:c,linkedCapsuleSetIds:d,linkedFigmaSnapshotRunIds:u,linkedFigmaSnapshotSources:p,linkedImageSources:m,updateCfg:h,openWindow:f})};}(c.id,c.type,L,z,c.cfg,I,R,E,F,T,D,M,P,O,K),_=(0,i.useCallback)(e=>m.update(c.id,{zoom:Math.max(.5,Math.min(2,Math.round(10*e)/10))}),[m,c.id]);(0,i.useEffect)(()=>{var e,t;if(e=c.type,t=c.cfg,"figmaView"!==e||"string"!=typeof t.selectedScreenIdsJson||!(t.selectedScreenIdsJson.length>0)||c.max||"full"!==B)return;let n=y.current;if(null===n)return;let l=null,a=()=>{l=null;let e=n.scrollHeight-n.clientHeight;if(e<=8)return;let t=Math.ceil(c.h+e);t<=c.h+8||m.update(c.id,{h:t});},i=()=>{null===l&&(l="function"==typeof window.requestAnimationFrame?window.requestAnimationFrame(a):window.setTimeout(a,0));};i();let r="u">typeof ResizeObserver?new ResizeObserver(i):null;null==r||r.observe(n);let s=n.firstElementChild;return null!==s&&(null==r||r.observe(s)),()=>{null!==l&&("function"==typeof window.cancelAnimationFrame?window.cancelAnimationFrame(l):window.clearTimeout(l)),null==r||r.disconnect();};},[m,B,c.cfg,c.h,c.id,c.max,c.type]),(0,i.useEffect)(()=>()=>{var e;null==(e=w.current)||e.call(w),w.current=null;},[]);let V=(0,i.useCallback)(e=>{e instanceof Element&&null!==e.closest("button,input,textarea,select,a[href],summary,[contenteditable='true'],[contenteditable=''],[role='button'],[role='checkbox'],[role='link'],[role='menuitem'],[role='option'],[role='radio'],[role='switch'],[role='tab']")?window.setTimeout(()=>m.focus(c.id),0):m.focus(c.id);},[m,c.id]),H=(0,i.useCallback)(e=>{var t,n,l,a,i,r,s,o;let d,f,g,v,b;if(!(U(o=e)||1===o.button)||"valid"===u)return;e.preventDefault(),V(e.target);let y=h.current;if(null===y)return;let w=(i=y.getBoundingClientRect(),{z:d=p.zoom,vpx0:-p.x/d,vpy0:-p.y/d,vpw:i.width/d,vph:i.height/d,toWX:e=>(e-i.left-p.x)/d,toWY:e=>(e-i.top-p.y)/d}),j=c.max,k=j?null!=(t=null==(l=c.prev)?void 0:l.w)?t:480:c.w,N=j?null!=(n=null==(a=c.prev)?void 0:a.h)?n:360:c.h,S=j?k/2:w.toWX(e.clientX)-c.x,C=j?18:w.toWY(e.clientY)-c.y;j&&m.update(c.id,{max:!1,w:k,h:N}),x(!0),r={winId:c.id,offX:S,offY:C,W:k},s=()=>x(!1),f=30/w.z,g=e=>{let t,n,l,a,i=w.toWX(e.clientX),s=w.toWY(e.clientY),o=i-r.offX,c=s-r.offY;o=Math.max(w.vpx0-(r.W-120),Math.min(w.vpx0+w.vpw-120,o)),c=Math.max(w.vpy0,Math.min(w.vpy0+w.vph-38,c)),m.setSnap((t=i-w.vpx0<f,n=w.vpx0+w.vpw-i<f,l=s-w.vpy0<f,a=w.vpy0+w.vph-s<f,l&&t?"tl":l&&n?"tr":a&&t?"bl":a&&n?"br":t?"left":n?"right":l?"maxi":null)),m.update(r.winId,{x:o,y:c});},v=()=>{window.removeEventListener("pointermove",g),window.removeEventListener("pointerup",v),window.removeEventListener("pointercancel",v),m.commitSnap(r.winId),b(),null==s||s();},b=X(),window.addEventListener("pointermove",g),window.addEventListener("pointerup",v),window.addEventListener("pointercancel",v);},[m,c.id,c.x,c.y,c.w,c.h,c.max,c.prev,p,h,u,V]),J=(0,i.useCallback)(e=>t=>{var n;if(!U(t))return;t.preventDefault(),t.stopPropagation(),null==(n=w.current)||n.call(w),w.current=null,m.focus(c.id);let l={x:c.x,y:c.y,w:c.w,h:c.h},a=l,i=t.clientX,r=t.clientY,s=p.zoom,o=document.body.style.cursor,d=!0,u=()=>{d&&(d=!1,window.removeEventListener("pointermove",f),window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",h),window.removeEventListener("blur",h),document.body.style.cursor=o,w.current===u&&(w.current=null));},h=()=>{u();},f=t=>{var n;if(!d)return;if(0===t.buttons)return void u();let o=function(e,t,n,l,a){let{x:i,y:r,w:s,h:o}=e;t.includes("e")&&(s=e.w+n),t.includes("s")&&(o=e.h+l),t.includes("w")&&(s=e.w-n,i=e.x+n),t.includes("n")&&(o=e.h-l,r=e.y+l);let c=$[a].min,d=c.w>0?c.w:240,u=c.h>0?c.h:150;return s<d&&(t.includes("w")&&(i-=d-s),s=d),o<u&&(t.includes("n")&&(r-=u-o),o=u),{x:i,y:r,w:s,h:o};}(l,e,(t.clientX-i)/s,(t.clientY-r)/s,c.type);((n=a).x!==o.x||n.y!==o.y||n.w!==o.w||n.h!==o.h)&&(a=o,m.update(c.id,{...o,max:!1}));};document.body.style.cursor="n"===e||"s"===e?"ns-resize":"e"===e||"w"===e?"ew-resize":"ne"===e||"sw"===e?"nesw-resize":"nwse-resize",window.addEventListener("pointermove",f),window.addEventListener("pointerup",h),window.addEventListener("pointercancel",h),window.addEventListener("blur",h),w.current=u;},[m,c.id,c.x,c.y,c.w,c.h,c.type,p.zoom]),Y=(0,i.useCallback)((e,t)=>{let n=e.getBoundingClientRect();m.startConnect(c.id,{clientX:"clientX"in t?t.clientX:n.left+n.width/2,clientY:"clientY"in t?t.clientY:n.top+n.height/2,preventDefault:()=>t.preventDefault(),stopPropagation:()=>t.stopPropagation()});},[m,c.id]),G=(0,i.useCallback)(e=>{U(e)&&(e.preventDefault(),e.stopPropagation(),Y(e.currentTarget,e));},[Y]),Q=(0,i.useCallback)(e=>{if("Enter"===e.key||" "===e.key||"Spacebar"===e.key){if("valid"===u)return void m.confirmConnect(c.id,{preventDefault:()=>e.preventDefault(),stopPropagation:()=>e.stopPropagation()});e.preventDefault(),e.stopPropagation(),Y(e.currentTarget,e);}},[Y,u,m,c.id]),Z=(0,i.useCallback)(()=>{m.close(c.id),requestAnimationFrame(()=>{var e;let t=null!=(e=document.querySelector('.window[data-top="true"]'))?e:document.querySelector(".ws-fab");null==t||t.focus({preventScroll:!0});});},[m,c.id]),ee=(0,i.useCallback)(()=>{m.minimize(c.id),requestAnimationFrame(()=>{var e;let t=null!=(e=document.querySelector('.window[data-top="true"]'))?e:document.querySelector(".ws-fab");null==t||t.focus({preventScroll:!0});});},[m,c.id]),et="full"===B?q(c.type,c.cfg):null,en="full"===B&&L>=340,el="tiny"===B?{}:{zoom:j},ea={left:c.x,top:c.y,width:c.w,height:c.h,zIndex:c.z};return(0,a.jsxs)("section",{className:"window","aria-label":null!==et?`${f.title} — ${et}`:f.title,"aria-roledescription":"window","data-top":d?"true":"false","data-max":c.max?"true":"false","data-conn":null!=u?u:void 0,"data-dragging":b?"true":void 0,"data-window-id":c.id,style:ea,tabIndex:-1,onPointerDown:e=>{"valid"===u&&m.confirmConnect(c.id,e),V(e.target);},onFocusCapture:()=>{d||window.setTimeout(()=>m.focus(c.id),0);},children:[(0,a.jsxs)("header",{className:"win-head",onPointerDown:H,onDoubleClick:e=>{(function(e){let t=e.target;if(t instanceof Element&&null!==t.closest("button,[role='button']"))return!1;let n=e.currentTarget.getBoundingClientRect(),l=Math.min(210,n.width/2);return e.clientX<n.right-l;})(e)&&m.maximize(c.id);},children:[(0,a.jsx)("span",{className:"win-ico",style:{color:!0===f.accent?"var(--accent)":"var(--fg-muted)"},children:(0,a.jsx)(v,{size:14})}),(0,a.jsx)("span",{className:"win-title",children:f.title}),null!==et?(0,a.jsx)("span",{className:"win-sub mono",title:et,children:(0,a.jsx)("span",{className:"win-sub-text",children:et})}):null,(0,a.jsx)("span",{className:"spacer"}),en?(0,a.jsxs)("div",{className:"win-zoom",children:[(0,a.jsx)("button",{type:"button",className:"win-zbtn ui-tip","data-tip":"Zoom content out","aria-label":`Zoom ${f.title} content out`,disabled:j<=.5,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation();},onClick:()=>_(j-.1),children:(0,a.jsx)(N.F.zoomOut,{size:13})}),(0,a.jsxs)("button",{type:"button",className:"win-zpct ui-tip","data-tip":"Reset content zoom to 100%","aria-label":`${String(Math.round(100*j))}% — reset ${f.title} content zoom`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation();},onClick:()=>m.update(c.id,{zoom:1}),children:[Math.round(100*j),"%"]}),(0,a.jsx)("button",{type:"button",className:"win-zbtn ui-tip","data-tip":"Zoom content in","aria-label":`Zoom ${f.title} content in`,disabled:j>=2,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation();},onClick:()=>_(j+.1),children:(0,a.jsx)(N.F.zoomIn,{size:13})})]}):null,(0,a.jsxs)("div",{className:"win-traffic",role:"group","aria-label":`${f.title} window controls`,children:[(0,a.jsx)("button",{type:"button",className:"win-traffic-btn win-traffic-minimize ui-tip","data-tip":"Minimize","aria-label":`Minimize ${f.title} window`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation();},onClick:ee,children:(0,a.jsx)(N.F.minimize,{size:17})}),(0,a.jsx)("button",{type:"button",className:"win-traffic-btn win-traffic-maximize ui-tip","data-tip":c.max?"Restore":"Full screen","aria-label":c.max?`Restore ${f.title} window`:`Full screen ${f.title} window`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation();},onClick:()=>m.maximize(c.id),children:c.max?(0,a.jsx)(N.F.restore,{size:17}):(0,a.jsx)(N.F.maximize,{size:17})}),(0,a.jsx)("button",{type:"button",className:"win-traffic-btn win-traffic-close ui-tip","data-tip":"Close","aria-label":`Close ${f.title} window`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation();},onClick:Z,children:(0,a.jsx)(N.F.close,{size:17})})]})]}),(0,a.jsx)("div",{ref:y,className:"win-body","data-mode":B,style:el,children:W}),c.max?null:eR.map(e=>(0,a.jsx)("div",{className:`wz wz-${e}`,onPointerDown:J(e)},e)),!c.max&&g?eE.map(e=>(0,a.jsx)("button",{type:"button",className:`win-port wp-${e}`,title:"Click to connect to another window","aria-label":`Connect ${f.title} from ${"t"===e?"top":"r"===e?"right":"b"===e?"bottom":"left"} edge`,onPointerDown:G,onKeyDown:Q},`p${e}`)):null]});}let eF=[/\bsk-[A-Za-z0-9_-]{20,}\b/,/\bAKIA[0-9A-Z]{16}\b/,/\bgh[pousr]_[A-Za-z0-9]{36,}\b/,/\bxox[abporsu]-[A-Za-z0-9-]{10,}\b/,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/,/-----BEGIN [A-Z ]*PRIVATE KEY-----/],eT=/\b(?:\d[ -]?){13,19}\b/g;n(63680);let eD={chat:{lifecycle:["draft","streaming","final","archived"],trustBoundary:["ui","model","evidence"],authority:"user-confirm",persistence:"durable.ui"},chatHistory:{lifecycle:["live","archived"],trustBoundary:["ui"],authority:"user-confirm",persistence:"durable.ui"},memoria:{lifecycle:["live","needs-review","archived"],trustBoundary:["ui","memory"],authority:"user-confirm",persistence:"memory-reference"},files:{lifecycle:["connecting","connected","degraded","disconnected","error"],trustBoundary:["ui","fs"],authority:"user",persistence:"fs-reference"},connector:{lifecycle:["connecting","connected","degraded","disconnected","error"],trustBoundary:["ui","fs"],authority:"user",persistence:"fs-reference"},localKnowledge:{lifecycle:["idle","connecting","connected","degraded","disconnected","error"],trustBoundary:["ui","fs","model"],authority:"user-confirm",persistence:"durable.ui"},editor:{lifecycle:["viewing","editing","unsaved","saved","error"],trustBoundary:["ui","fs"],authority:"user",persistence:"fs-reference"},browser:{lifecycle:["idle","live","error"],trustBoundary:["ui","network"],authority:"user-confirm",persistence:"transient"},terminal:{lifecycle:["idle","running","blocked","cancelled","error"],trustBoundary:["ui","tool"],authority:"user-confirm",persistence:"transient"},review:{lifecycle:["proposed","needs-review","applied","reverted","archived"],trustBoundary:["ui","evidence"],authority:"user-confirm",persistence:"evidence-reference"},agents:{lifecycle:["proposed","running","blocked","needs-review","verified","cancelled"],trustBoundary:["ui","model","tool","evidence"],authority:"user-confirm",persistence:"durable.ui"},integ:{lifecycle:["idle","connecting","connected","degraded","disconnected","error"],trustBoundary:["ui","network"],authority:"user-confirm",persistence:"durable.config"},keiko:{lifecycle:["live"],trustBoundary:["ui","memory"],authority:"user",persistence:"memory-reference"},settings:{lifecycle:["viewing","editing","saved"],trustBoundary:["ui"],authority:"user",persistence:"durable.config"},project:{lifecycle:["none","connecting","connected","disconnected"],trustBoundary:["ui","fs"],authority:"user",persistence:"durable.config"},search:{lifecycle:["idle","searching","results","error"],trustBoundary:["ui","fs"],authority:"read-only",persistence:"transient"},plugins:{lifecycle:["idle","installed","disabled","enabled"],trustBoundary:["ui"],authority:"user",persistence:"durable.config"},automations:{lifecycle:["idle","enabled","disabled"],trustBoundary:["ui"],authority:"user",persistence:"durable.config"},mobile:{lifecycle:["paired","unpaired","error"],trustBoundary:["ui","network"],authority:"user-confirm",persistence:"durable.config"},inspector:{lifecycle:["empty","focused"],trustBoundary:["ui"],authority:"ui-only",persistence:"transient"},activity:{lifecycle:["live","archived"],trustBoundary:["ui"],authority:"read-only",persistence:"transient"},notifications:{lifecycle:["unread","read","dismissed"],trustBoundary:["ui"],authority:"ui-only",persistence:"transient"},resources:{lifecycle:["live"],trustBoundary:["ui"],authority:"read-only",persistence:"transient"},quality:{lifecycle:["idle","running","results","error"],trustBoundary:["ui","model","evidence"],authority:"user-confirm",persistence:"evidence-reference"},promptEnhancer:{lifecycle:["idle","running","results","error"],trustBoundary:["ui","model","evidence"],authority:"user-confirm",persistence:"transient"},qiRun:{lifecycle:["running","final","needs-review","verified","failed","cancelled"],trustBoundary:["ui","model","evidence"],authority:"user-confirm",persistence:"evidence-reference"},relationships:{lifecycle:["idle","live","degraded","blocked","error"],trustBoundary:["ui","evidence"],authority:"user-confirm",persistence:"durable.ui"},figma:{lifecycle:["idle","running","results","error"],trustBoundary:["ui","evidence","network"],authority:"user-confirm",persistence:"evidence-reference"},figmaView:{lifecycle:["idle","results","error"],trustBoundary:["ui","evidence"],authority:"user-confirm",persistence:"evidence-reference"},figmaJson:{lifecycle:["idle","results","error"],trustBoundary:["ui","evidence"],authority:"user-confirm",persistence:"evidence-reference"},figmaImage:{lifecycle:["idle","results","error"],trustBoundary:["ui","evidence","model"],authority:"user-confirm",persistence:"evidence-reference"}},eq=["apikey","accesskey","clientsecret","credential","password","privatekey","secret","token"],eM=["api_key=","apikey=","client_secret=","clientsecret=","credential=","authorization:","password=","secret=","token="],eP=[".env",".env.local",".env.development",".env.test",".env.production"],eL={chat:["chatId"],editor:["openFiles","layoutJson"],files:["activeFilePath","activeDirectoryPath","resolvedRoot"],figma:["snapshotRunId","selectedScreenIdsJson","selectedScreenName"],figmaView:["snapshotRunId","selectedScreenIdsJson","selectedScreenName"],figmaJson:["snapshotRunId","screenId","selectedScreenIdsJson","selectedScreenName"],figmaImage:["snapshotRunId","screenId","selectedScreenName","imageSrc"]};function ez(e){return"number"==typeof e&&Number.isFinite(e);}function eO(e){return"object"==typeof e&&null!==e&&!Array.isArray(e);}function eK(e){let t=e.trim();if(0===t.length)return!1;let n=t.toLowerCase();return function(e){for(let t of eF)if(t.test(e))return!0;for(let t of e.matchAll(eT)){let e=t[0].replaceAll(/[ -]/g,"");if(e.length>=13&&e.length<=19&&function(e){let t=0,n=!1;for(let l=e.length-1;l>=0;l-=1){let a=Number(e[l]);n&&(a*=2)>9&&(a-=9),t+=a,n=!n;}return t%10==0;}(e))return!0;}return!1;}(t)||function(e){let t="bearer ",n=e.toLowerCase().indexOf(t);if(-1===n)return!1;let l=0;for(let i=n+t.length;i<e.length;i+=1){var a;if(0===(null!=(a=e[i])?a:"").trim().length)break;l+=1;}return l>=8;}(t)||function(e){if(!e.includes("://"))return!1;try{let t=new URL(e);return t.username.length>0||t.password.length>0;}catch{return!1;}}(t)||eM.some(e=>n.includes(e))||function(e){let t=e.toLowerCase().replaceAll("\\","/").split("/");for(let e=0;e<t.length;e+=1){var n,l;let a=null!=(n=t[e])?n:"",i=null!=(l=t[e+1])?l:"";if(eP.includes(a)||".npmrc"===a||"credentials.json"===a||".aws"===a&&"credentials"===i||".ssh"===a&&i.startsWith("id_"))return!0;}return!1;}(t);}function eB(e){if(0===e.length||e.length>256||e.startsWith(".")||e.trim()!==e||eK(e))return!1;for(let t of e)if(!function(e){let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||46===t||95===t||45===t;}(t))return!1;return!0;}function eW(e){if(0===e.length||e.length>256||e.trim()!==e||eK(e))return!1;for(let t of e){let e=t.charCodeAt(0),n=e>=48&&e<=57,l=e>=65&&e<=90,a=e>=97&&e<=122,i=46===e||58===e||95===e||45===e;if(!n&&!l&&!a&&!i)return!1;}return!0;}function eU(e){if(!Array.isArray(e)||0===e.length)return;let t=[];for(let n of e){if("string"!=typeof n)return;let e=n.trim().replace(/\\/gu,"/").replace(/^\/+/u,"");if(!(0===e.length||e.length>512||eK(e)||t.includes(e))&&(t.push(e),t.length>=64))break;}return t.length>0?t:void 0;}function e_(e){let t=[];for(let n of e){let e=function(e){var t;if(!eO(e)||!("string"==typeof(t=e.type)&&t in $))return null;let n=e.type;if("transient"===eD[n].persistence||"string"!=typeof e.id||!ez(e.x)||!ez(e.y)||!ez(e.w)||!ez(e.h)||!ez(e.z)||"boolean"!=typeof e.max)return null;let l={id:e.id,type:n,x:e.x,y:e.y,w:e.w,h:e.h,z:e.z,cfg:function(e,t){var n,l;if(!eO(t)||"durable.config"===eD[e].persistence)return{};let a=new Set([...(null!=(n=$[e].config)?n:[]).map(e=>e.key),...(null!=(l=eL[e])?l:[])]),i={};for(let[n,l]of Object.entries(t)){if(!a.has(n))continue;let t=function(e,t,n){let l;if("editor"===e&&"openFiles"===t)return eU(n);if("editor"===e&&"layoutJson"===t)return function(e){let t;if("string"!=typeof e||0===e.length)return;try{t=JSON.parse(e);}catch{return;}if("object"!=typeof t||null===t||Array.isArray(t))return;let n=t;if(2===n.schemaVersion||2===n.version){let e=eO(n.panes)?n.panes:{},t={};for(let[n,a]of Object.entries(e)){var l;if(!eO(a))continue;let e="string"==typeof a.activeFile?a.activeFile.trim():"",i=eU(a.openFiles),r=null!=(l=eU(a.tabOrder))?l:i;if(void 0===i&&0===e.length)continue;let s=null!=i?i:eU([e]);void 0!==s&&(t[n.slice(0,48)]={id:n.slice(0,48),activeFile:e.length>0?e.replace(/\\/gu,"/").replace(/^\/+/u,""):s[0],openFiles:s,tabOrder:null!=r?r:s});}let a=new Set(Object.keys(t)),i=e=>{if(!eO(e))return null;if("pane"===e.type&&"string"==typeof e.paneId&&a.has(e.paneId))return{type:"pane",paneId:e.paneId};if("split"===e.type){let t=i(e.first),n=i(e.second);if(null===t||null===n)return null;let l="number"==typeof e.ratio&&Number.isFinite(e.ratio)?Math.min(85,Math.max(15,Math.round(e.ratio))):50;return{type:"split",id:"string"==typeof e.id?e.id.slice(0,48):"split-1",direction:"column"===e.direction?"column":"row",ratio:l,first:t,second:n};}return null;},r=i(n.tree),s=Object.keys(t)[0];if(null===r||void 0===s)return;let o="string"==typeof n.activePaneId&&a.has(n.activePaneId)?n.activePaneId:s,c="number"==typeof n.sidebarWidth&&Number.isFinite(n.sidebarWidth)?Math.min(440,Math.max(180,Math.round(n.sidebarWidth))):260;return JSON.stringify({schemaVersion:2,root:"string"==typeof n.root?n.root:"",activePaneId:o,tree:r,panes:t,sidebarWidth:c,sidebarCollapsed:!0===n.sidebarCollapsed});}let a=Array.isArray(n.panes)?n.panes.slice(0,2):[],i=[];for(let[e,t]of a.entries()){if("object"!=typeof t||null===t||Array.isArray(t))return;let n="string"==typeof t.file?t.file.trim():"",l=eU(t.openFiles);if(n.length>512||eK(n))continue;let a=null!=l?l:n.length>0?eU([n]):void 0;void 0!==a&&i.push({id:"string"==typeof t.id&&t.id.trim().length>0?t.id.trim().slice(0,32):`pane-${e+1}`,file:n.length>0?n.replace(/\\/gu,"/").replace(/^\/+/u,""):a[0],openFiles:a});}if(0===i.length)return;let r="column"===n.direction?"column":"row",s="number"==typeof n.splitRatio&&Number.isFinite(n.splitRatio)?Math.min(75,Math.max(25,Math.round(n.splitRatio))):50,o="number"==typeof n.sidebarWidth&&Number.isFinite(n.sidebarWidth)?Math.min(440,Math.max(180,Math.round(n.sidebarWidth))):260,c="string"==typeof n.activePaneId&&i.some(e=>e.id===n.activePaneId)?n.activePaneId:i[0].id;return JSON.stringify({version:1,panes:i,activePaneId:c,direction:r,splitRatio:s,sidebarWidth:o,sidebarCollapsed:!0===n.sidebarCollapsed});}(n);if("figma"===e||"figmaView"===e||"figmaJson"===e||"figmaImage"===e)return function(e,t){if("string"==typeof t){if("snapshotRunId"===e)return eB(t)?t:void 0;if("screenId"===e)return eW(t)?t:void 0;if("imageSrc"===e)return /^\/api\/figma\/snapshots\/[^/?#]+\/screens\/\d+\/image$/u.test(t)?t:void 0;if("selectedScreenIdsJson"===e){let e;try{e=JSON.parse(t);}catch{return;}if(!Array.isArray(e)||0===e.length||e.length>16)return;let n=[];for(let t of e){if("string"!=typeof t)return;let e=t.trim();if(!eW(e))return;n.push(e);}return JSON.stringify(n);}if("selectedScreenName"===e){if(t.length>256||eK(t))return;return t;}}}(t,n);if("string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||(l=function(e){let t="";for(let n of e.toLowerCase())(n>="a"&&n<="z"||n>="0"&&n<="9")&&(t+=n);return t;}(t),eq.some(e=>l.includes(e))))return;if("string"!=typeof n)return n;let a=eD[e].persistence;return"evidence-reference"===a?eB(n)?n:void 0:eK(n)?"durable.ui"===a?"[REDACTED]":void 0:n;}(e,n,l);void 0!==t&&(i[n]=t);}return i;}(n,e.cfg),max:e.max},a=function(e){if(eO(e)&&ez(e.x)&&ez(e.y)&&ez(e.w)&&ez(e.h))return{x:e.x,y:e.y,w:e.w,h:e.h};}(e.prev);return{...l,...(!0===e.minimized?{minimized:!0}:{}),...(void 0!==a?{prev:a}:{}),...(ez(e.zoom)?{zoom:e.zoom}:{})};}(n);null!==e&&t.push("figma"!==e.type||void 0===function(e){let t=e.selectedScreenIdsJson;if("string"==typeof t)try{let e=JSON.parse(t);if(!Array.isArray(e))return;let n=e[0];return"string"==typeof n&&n.length>0?n:void 0;}catch{return;}}(e.cfg)?e:{...e,type:"figmaView",cfg:{...e.cfg}});}let n=t.filter(e=>"figma"===e.type);if(n.length<=1)return t;let l=n.reduce((e,t)=>t.z>e.z?t:e);return t.filter(e=>"figma"!==e.type||e.id===l.id);}function eV(e,t){let n=new Set(t.map(e=>e.id)),l=[];for(let t of e){if("string"!=typeof t.id||"string"!=typeof t.a||"string"!=typeof t.b||!n.has(t.a)||!n.has(t.b))continue;let e="string"==typeof t.boundRoot&&t.boundRoot.length>0,a="workspace-root"===t.boundScopeKind||"directory"===t.boundScopeKind||"files"===t.boundScopeKind,i="string"==typeof t.boundRelativePath&&t.boundRelativePath.length>0,r="string"==typeof t.boundChatWindowId&&t.boundChatWindowId.length>0&&n.has(t.boundChatWindowId),s=("capsule"===t.boundConnectorKind||"capsule-set"===t.boundConnectorKind)&&"string"==typeof t.boundConnectorId&&t.boundConnectorId.length>0;l.push({id:t.id,a:t.a,b:t.b,...(r?{boundChatWindowId:t.boundChatWindowId}:{}),...(e?{boundRoot:t.boundRoot}:{}),...(a?{boundScopeKind:t.boundScopeKind}:{}),...(i?{boundRelativePath:t.boundRelativePath}:{}),...(s?{boundConnectorKind:t.boundConnectorKind,boundConnectorId:t.boundConnectorId}:{})});}return l;}function eH(e,t,n,l,a){return{x:e.x+Math.max(16,Math.min(a+26*l,e.w-t-16)),y:e.y+Math.max(16,Math.min(a+26*l,e.h-n-16))};}function eJ(e){let{prev:t,...n}=e;return n;}function eY(e,t,n){return e.some(e=>e.a===t&&e.b===n||e.a===n&&e.b===t);}function eX(e,t){return(null==e?void 0:e.type)==="chat"?e.id:(null==t?void 0:t.type)==="chat"?t.id:null;}function eG(e){return e.length>0&&(e.startsWith("/")||/^[A-Za-z]:[/\\]/u.test(e));}function eQ(e){return /^[A-Za-z]:[/\\]?$/u.test(e)?e.replace(/\\/gu,"/"):e.replace(/\\/gu,"/").replace(/\/+$/u,"");}function eZ(e){if("files"!==e.type)return null;let t=e.cfg.resolvedRoot,n=e.cfg.root,l="string"==typeof t&&t.length>0?t:"string"==typeof n&&n.length>0?n:null;return null!==l&&eG(l)?l:null;}function e0(e){return e.replace(/\\/gu,"/").replace(/^\/+/u,"").replace(/\/+$/u,"");}function e1(e,t){return void 0!==e.root&&void 0!==t.root&&eQ(e.root)===eQ(t.root)&&e.kind===t.kind&&e.relativePaths.length===t.relativePaths.length&&e.relativePaths.every((e,n)=>{var l;return e0(e)===e0(null!=(l=t.relativePaths[n])?l:"");});}function e2(e,t,n){let l="files"===e.type?e:"files"===t.type?t:null,a="chat"===e.type?e:"chat"===t.type?t:null;if(null===l||null===a)return null;let i=eZ(l);if(null===i)return null;let r=l.cfg.activeFilePath;if("string"==typeof r&&r.length>0)return{kind:"files",relativePaths:[e0(r)],root:eQ(i),connectedAtMs:n};let s=l.cfg.activeDirectoryPath;return"string"==typeof s&&s.length>0?{kind:"directory",relativePaths:[e0(s)],root:eQ(i),connectedAtMs:n}:{kind:"workspace-root",relativePaths:[],root:eQ(i),connectedAtMs:n};}function e3(e){if("string"!=typeof e.boundRoot||0===e.boundRoot.length)return null;let t=Date.now();return"directory"===e.boundScopeKind?"string"!=typeof e.boundRelativePath||0===e.boundRelativePath.length?null:{kind:"directory",relativePaths:[e0(e.boundRelativePath)],root:eQ(e.boundRoot),connectedAtMs:t}:"files"===e.boundScopeKind?"string"!=typeof e.boundRelativePath||0===e.boundRelativePath.length?null:{kind:"files",relativePaths:[e0(e.boundRelativePath)],root:eQ(e.boundRoot),connectedAtMs:t}:{kind:"workspace-root",relativePaths:[],root:eQ(e.boundRoot),connectedAtMs:t};}function e4(e){return Math.max(e.maxConnectedSources,e.maxLocalKnowledgeSources);}function e6(e,t){return e.filter(e=>!e1(e,t));}function e5(e){var t;return null!=(t=e.connectedScopes)?t:void 0!==e.connectedScope?[e.connectedScope]:[];}function e8(e){var t;return null!=(t=e.localKnowledgeScopes)?t:void 0!==e.localKnowledgeScope?[e.localKnowledgeScope]:[];}function e7(e){return"capsule"===e.kind?`capsule:${e.capsuleId}`:`set:${e.capsuleSetId}`;}function e9(e){return"string"!=typeof e.boundConnectorId||0===e.boundConnectorId.length?null:"capsule"===e.boundConnectorKind?{kind:"capsule",capsuleId:e.boundConnectorId,connectedAtMs:0}:"capsule-set"===e.boundConnectorKind?{kind:"capsule-set",capsuleSetId:e.boundConnectorId,connectedAtMs:0}:null;}function te(e,t){let n="connector"===e.type?e:"connector"===t.type?t:null,l="chat"===e.type?e:"chat"===t.type?t:null;if(null===n||null===l)return null;let a=n.cfg.selectedKind,i=n.cfg.selectedId;if("string"!=typeof a||"string"!=typeof i)return null;let r=i.trim();return 0===r.length?null:"capsule"===a?{kind:"capsule",capsuleId:r,connectedAtMs:Date.now()}:"capsule-set"===a?{kind:"capsule-set",capsuleSetId:r,connectedAtMs:Date.now()}:null;}let tt="keiko.workspace.v4",tn="keiko.conns.v1",tl="keiko.view";function ta(){try{let e=window.localStorage.getItem(tl);if(null===e)return{zoom:1,x:0,y:0};let t=JSON.parse(e);if("object"==typeof t&&null!==t&&"zoom"in t&&"number"==typeof t.zoom)return{zoom:t.zoom,x:"number"==typeof t.x?t.x:0,y:"number"==typeof t.y?t.y:0};}catch{}return{zoom:1,x:0,y:0};}function ti(e){return Math.max(.3,Math.min(2.5,e));}function tr(e){return Math.max(.5,Math.min(2,Math.round(10*e)/10));}function ts(e){let t=null;for(let n=0;n<e.length;n++){let l=e[n];if(!0!==l.minimized){if(null===t){t=l;continue;}l.z>t.z&&(t=l);}}return t;}function to(e,t){try{window.localStorage.setItem(e,JSON.stringify(t));}catch{}}function tc(e){let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?16:2===e.deltaMode?800:1;return{x:e.deltaX*t,y:e.deltaY*t};}let td={Equal:"=",NumpadAdd:"+",Minus:"-",NumpadSubtract:"-",Digit0:"0",Numpad0:"0"},tu="application/x-keiko-local-knowledge-connector",tp="keiko:local-knowledge-connector-drop";function tm(e){if(!Array.from(e.types).includes(tu))return null;try{let t=JSON.parse(e.getData(tu));if("object"!=typeof t||null===t||"capsule"!==t.kind||"string"!=typeof t.id||0===t.id.trim().length)return null;let n="string"==typeof t.label?t.label.trim():"",l="string"==typeof t.lifecycleState?t.lifecycleState.trim():"";return{kind:"capsule",id:t.id.trim(),...(n.length>0?{label:n}:{}),...(l.length>0?{lifecycleState:l}:{})};}catch{return null;}}let th="application/x-keiko-figma-view",tf="keiko:figma-view-drop";function tg(e){return"string"==typeof e&&e.trim().length>0?e.trim():null;}function tv(e){if(!Array.from(e.types).includes(th))return null;try{let t=JSON.parse(e.getData(th));if("object"!=typeof t||null===t)return null;let n=tg(t.snapshotRunId),l=tg(t.screenId),a=tg(t.name);if(null===n||null===l||null===a)return null;return{snapshotRunId:n,screenId:l,name:a};}catch{return null;}}let tb="application/x-keiko-figma-json",tx="keiko:figma-json-drop";function ty(e){return"string"==typeof e&&e.trim().length>0?e.trim():null;}function tw(e){if(!Array.from(e.types).includes(tb))return null;try{let t=JSON.parse(e.getData(tb));if("object"!=typeof t||null===t)return null;let n=ty(t.snapshotRunId),l=ty(t.screenId),a=ty(t.name);if(null===n||null===l||null===a)return null;let i=ty(t.sourceWindowId);return{snapshotRunId:n,screenId:l,name:a,...(null!==i?{sourceWindowId:i}:{})};}catch{return null;}}let tj="application/x-keiko-figma-image",tk="keiko:figma-image-drop";function tN(e){return"string"==typeof e&&e.trim().length>0?e.trim():null;}function tS(e){if(!Array.from(e.types).includes(tj))return null;try{let t=JSON.parse(e.getData(tj));if("object"!=typeof t||null===t)return null;let n=tN(t.snapshotRunId),l=tN(t.screenId),a=tN(t.name),i=tN(t.imageSrc);if(null===n||null===l||null===a||null===i||!/^\/api\/figma\/snapshots\/[^/?#]+\/screens\/\d+\/image$/u.test(i))return null;let r=tN(t.sourceWindowId);return{snapshotRunId:n,screenId:l,name:a,imageSrc:i,...(null!==r?{sourceWindowId:r}:{})};}catch{return null;}}let tC={w:260,h:220},tI={w:360,h:360},tR={w:520,h:540},tE={w:560,h:420};function t$(e){let{clientX:t,clientY:n,rect:l,view:a,size:i=tC}=e;return{x:Math.round((t-l.left-a.x)/a.zoom-i.w/2),y:Math.round((n-l.top-a.y)/a.zoom-28)};}function tA(e,t){let n=e+t;return e<1&&n>1||e>1&&n<1?1:n;}function tF(e,t,n){var l;t.preventDefault();let a=t.currentTarget;null==(l=a.setPointerCapture)||l.call(a,t.pointerId);let i=t.clientX,r=t.clientY,s=X();n(!0);let o=t=>{e(t.clientX-i,t.clientY-r),i=t.clientX,r=t.clientY;},c=()=>{var e,l;window.removeEventListener("pointermove",o),window.removeEventListener("pointerup",c),window.removeEventListener("pointercancel",c),n(!1),(null==(e=a.hasPointerCapture)?void 0:e.call(a,t.pointerId))===!0&&(null==(l=a.releasePointerCapture)||l.call(a,t.pointerId)),s();};window.addEventListener("pointermove",o),window.addEventListener("pointerup",c),window.addEventListener("pointercancel",c);}function tT(e){let{wins:t,connecting:n,conns:l}=e,[r,s]=(0,i.useState)(""),o=(0,i.useRef)(null),c=(0,i.useRef)(l.length);return(0,i.useEffect)(()=>{let e=o.current;o.current=n;let a=c.current;if(c.current=l.length,null===e&&null!==n){let e=null==t?void 0:t.find(e=>e.id===n.from),l=void 0!==e?$[e.type].title:"window";s(`Connecting from ${l} — select a highlighted window, press Escape to cancel`);return;}if(null!==e&&null===n)if(l.length>a){let e=l[l.length-1],n=void 0!==e?null==t?void 0:t.find(t=>t.id===e.a):void 0,a=void 0!==e?null==t?void 0:t.find(t=>t.id===e.b):void 0;s(void 0!==n&&void 0!==a?`Connected: ${T(n,a)}`:"Connected");}else s("Connection cancelled");},[n,l,t]),(0,a.jsx)("div",{className:"sr-only","aria-live":"polite",children:r});}function tD(e){var t,n;let{ws:l,wsRef:r,openPalette:s,palette:o}=e,{wins:c,view:d,snapPrev:u,conns:p,connecting:m,api:h}=l,[f,g]=(0,i.useState)(!1),[v,b]=(0,i.useState)(!1),x=(0,i.useRef)(!1),y=(0,i.useMemo)(()=>null===c?null:c.filter(e=>!0!==e.minimized),[c]),w=function(e){if(null===e||0===e.length)return null;let t=null;for(let n=0;n<e.length;n++){let l=e[n];if(!0!==l.minimized){if(null===t){t=l;continue;}l.z>t.z&&(t=l);}}return t;}(y),j=null!==m&&null!==y&&null!=(t=y.find(e=>e.id===m.from))?t:null;(0,i.useEffect)(()=>{let e=e=>{x.current=e,b(e);},t=t=>{var n;!("Space"!==t.code||(n=t.target)instanceof Element&&null!==n.closest("input,textarea,select,button,a[href],summary,[contenteditable='true'],[contenteditable=''],[role='button'],[role='checkbox'],[role='dialog'],[role='link'],[role='menuitem'],[role='option'],[role='radio'],[role='switch'],[role='tab']"))&&(t.preventDefault(),x.current||e(!0));},n=t=>{"Space"===t.code&&e(!1);},l=()=>{e(!1);};return window.addEventListener("keydown",t),window.addEventListener("keyup",n),window.addEventListener("blur",l),()=>{window.removeEventListener("keydown",t),window.removeEventListener("keyup",n),window.removeEventListener("blur",l);};},[]);let k=(0,i.useMemo)(()=>({backgroundSize:`${String(22*d.zoom)}px ${String(22*d.zoom)}px`,backgroundPosition:`${String(d.x)}px ${String(d.y)}px`}),[d]),S=(0,i.useMemo)(()=>({transform:`translate(${String(d.x/d.zoom)}px, ${String(d.y/d.zoom)}px)`,transformOrigin:"0 0",zoom:d.zoom}),[d]),C=(0,i.useCallback)((e,t,n,l)=>{let a=h.add("connector",{presentation:"node",selectedKind:e.kind,selectedId:e.id,...(void 0!==e.label?{selectedLabel:e.label}:{}),...(void 0!==e.lifecycleState?{selectedState:e.lifecycleState}:{})});null!==a&&h.update(a,{...t$({clientX:t,clientY:n,rect:l,view:d}),...tC});},[h,d]),I=(0,i.useCallback)((e,t,n,l)=>{let a=h.add("figmaView",{snapshotRunId:e.snapshotRunId,selectedScreenIdsJson:JSON.stringify([e.screenId]),selectedScreenName:e.name});null!==a&&h.update(a,{...t$({clientX:t,clientY:n,rect:l,view:d,size:tI}),...tI});},[h,d]),R=(0,i.useCallback)(e=>{if(null===c)return[];let t=new Map(c.map(e=>[e.id,e])),n=[];for(let l of p){let a=l.a===e?l.b:l.b===e?l.a:null;if(null===a)continue;let i=t.get(a);(null==i?void 0:i.type)==="quality"&&n.push({connId:l.id,qualityId:i.id});}return n;},[p,c]),E=(0,i.useCallback)((e,t,n,l)=>{let a=h.add("figmaJson",{snapshotRunId:e.snapshotRunId,screenId:e.screenId,selectedScreenIdsJson:JSON.stringify([e.screenId]),selectedScreenName:e.name});if(null===a||(h.update(a,{...t$({clientX:t,clientY:n,rect:l,view:d,size:tR}),...tR}),void 0===e.sourceWindowId))return;let i=R(e.sourceWindowId);if(0!==i.length){for(let e of i)h.removeConn(e.connId);window.setTimeout(()=>{for(let e of i)h.connect(a,e.qualityId);},0);}},[h,R,d]),$=(0,i.useCallback)((e,t,n,l)=>{let a=h.add("figmaImage",{snapshotRunId:e.snapshotRunId,screenId:e.screenId,selectedScreenName:e.name,imageSrc:e.imageSrc});if(null===a||(h.update(a,{...t$({clientX:t,clientY:n,rect:l,view:d,size:tE}),...tE}),void 0===e.sourceWindowId))return;let i=R(e.sourceWindowId);if(0!==i.length){for(let e of i)h.removeConn(e.connId);window.setTimeout(()=>{for(let e of i)h.connect(a,e.qualityId);},0);}},[h,R,d]);(0,i.useEffect)(()=>{let e=e=>{var t;if(!(e instanceof CustomEvent)||!function(e){if("object"!=typeof e||null===e)return!1;let t=e.payload;return"number"==typeof e.clientX&&"number"==typeof e.clientY&&"object"==typeof t&&null!==t&&"capsule"===t.kind&&"string"==typeof t.id;}(e.detail))return;let n=null==(t=r.current)?void 0:t.getBoundingClientRect();if(void 0===n)return;let{clientX:l,clientY:a,payload:i}=e.detail;l<n.left||l>n.right||a<n.top||a>n.bottom||C(i,l,a,n);};return window.addEventListener(tp,e),()=>{window.removeEventListener(tp,e);};},[C,r]),(0,i.useEffect)(()=>{let e=e=>{var t;if(!(e instanceof CustomEvent)||!function(e){if("object"!=typeof e||null===e)return!1;let t=e.payload;return"number"==typeof e.clientX&&"number"==typeof e.clientY&&"object"==typeof t&&null!==t&&"string"==typeof t.snapshotRunId&&"string"==typeof t.screenId&&"string"==typeof t.name;}(e.detail))return;let n=null==(t=r.current)?void 0:t.getBoundingClientRect();if(void 0===n)return;let{clientX:l,clientY:a,payload:i}=e.detail;l<n.left||l>n.right||a<n.top||a>n.bottom||I(i,l,a,n);};return window.addEventListener(tf,e),()=>{window.removeEventListener(tf,e);};},[I,r]),(0,i.useEffect)(()=>{let e=e=>{var t;if(!(e instanceof CustomEvent)||!function(e){if("object"!=typeof e||null===e)return!1;let t=e.payload;return"number"==typeof e.clientX&&"number"==typeof e.clientY&&"object"==typeof t&&null!==t&&"string"==typeof t.snapshotRunId&&"string"==typeof t.screenId&&"string"==typeof t.name&&(void 0===t.sourceWindowId||"string"==typeof t.sourceWindowId);}(e.detail))return;let n=null==(t=r.current)?void 0:t.getBoundingClientRect();if(void 0===n)return;let{clientX:l,clientY:a,payload:i}=e.detail;l<n.left||l>n.right||a<n.top||a>n.bottom||E(i,l,a,n);};return window.addEventListener(tx,e),()=>{window.removeEventListener(tx,e);};},[E,r]),(0,i.useEffect)(()=>{let e=e=>{var t;if(!(e instanceof CustomEvent)||!function(e){if("object"!=typeof e||null===e)return!1;let t=e.payload;return"number"==typeof e.clientX&&"number"==typeof e.clientY&&"object"==typeof t&&null!==t&&"string"==typeof t.snapshotRunId&&"string"==typeof t.screenId&&"string"==typeof t.name&&"string"==typeof t.imageSrc&&(void 0===t.sourceWindowId||"string"==typeof t.sourceWindowId);}(e.detail))return;let n=null==(t=r.current)?void 0:t.getBoundingClientRect();if(void 0===n)return;let{clientX:l,clientY:a,payload:i}=e.detail;l<n.left||l>n.right||a<n.top||a>n.bottom||$(i,l,a,n);};return window.addEventListener(tk,e),()=>{window.removeEventListener(tk,e);};},[$,r]);let A=null!==c&&0===c.length,T=null!=(n=null==c?void 0:c.some(e=>e.max))&&n;return(0,a.jsxs)("main",{className:"workspace",ref:r,"aria-label":"Workspace surface",tabIndex:0,"data-window-maxed":T?"true":void 0,"data-canvas-overlays-hidden":T?"true":"false","data-connecting":null!==m?"true":void 0,"data-panning":f?"true":void 0,"data-hand-tool":v?"true":void 0,onPointerDownCapture:e=>{var t;if(V())return;if(x.current&&U(e)&&null===m&&!((t=e.target)instanceof Element&&null!==t.closest("input, textarea, select, [contenteditable='true'], [contenteditable='']"))&&!_(e.target)){tF(h.panBy,e,g),e.stopPropagation();return;}if(0!==e.button||null===m||null===j||null===y)return;let n=function(e){if(!(e instanceof Element))return;let t=e.closest(".window[data-window-id]");return null==t?void 0:t.dataset.windowId;}(e.target);if(void 0===n||n===j.id)return;let l=y.find(e=>e.id===n);void 0!==l&&F(j.type,l.type)&&h.confirmConnect(l.id,e);},onPointerDown:e=>{if(!(V()||_(e.target))){var t;if(null!==m){U(e)&&h.cancelConnect();return;}(U(t=e)||1===t.button)&&tF(h.panBy,e,g);}},onKeyDown:e=>{if(e.target!==e.currentTarget)return;let t=e.shiftKey?192:48;switch(e.key){case"ArrowLeft":h.panBy(t,0);break;case"ArrowRight":h.panBy(-t,0);break;case"ArrowUp":h.panBy(0,t);break;case"ArrowDown":h.panBy(0,-t);break;default:return;}e.preventDefault();},onDragOver:e=>{(null!==tm(e.dataTransfer)||null!==tv(e.dataTransfer)||null!==tw(e.dataTransfer)||null!==tS(e.dataTransfer))&&(e.preventDefault(),e.dataTransfer.dropEffect="copy");},onDrop:e=>{let t=tm(e.dataTransfer),n=tv(e.dataTransfer),l=tw(e.dataTransfer),a=tS(e.dataTransfer);if(null===t&&null===n&&null===l&&null===a)return;e.preventDefault(),e.stopPropagation();let i=e.currentTarget.getBoundingClientRect();null!==t?C(t,e.clientX,e.clientY,i):null!==n?I(n,e.clientX,e.clientY,i):null!==l?E(l,e.clientX,e.clientY,i):null!==a&&$(a,e.clientX,e.clientY,i);},children:[(0,a.jsx)(ek,{}),(0,a.jsx)("div",{className:"ws-grid",style:k,"aria-hidden":"true"}),(0,a.jsx)(tT,{wins:y,connecting:m,conns:p}),null!==m?(0,a.jsx)("div",{className:"ws-connect-hint","aria-hidden":"true",children:"Click a highlighted window to connect — Esc to cancel"}):null,A?(0,a.jsx)("div",{className:"ws-empty",children:(0,a.jsx)(W,{onNewWindow:s})}):null,(0,a.jsxs)("div",{className:"ws-scene",style:S,children:[null!==u?(0,a.jsx)("div",{className:"snap-ghost",style:{left:u.x,top:u.y,width:u.w,height:u.h}}):null,null!==y?(0,a.jsx)(eI,{wins:y,conns:p,connecting:m,api:h}):null,null!==y?y.map(e=>(0,a.jsx)(eA,{win:e,top:null!==w&&e.id===w.id,connState:null===j?null:e.id===j.id?"source":F(j.type,e.type)?"valid":"invalid",view:d,api:h,wsRef:r},e.id)):null]}),(0,a.jsxs)("div",{className:"ws-zoom",children:[(0,a.jsx)("button",{type:"button",className:"ws-zoom-btn ui-tip cmp-tip-start",onClick:()=>h.zoomTo(tA(d.zoom,-.2)),disabled:d.zoom<=.3,"aria-label":"Zoom out","data-tip":"Zoom out",children:(0,a.jsx)(N.F.zoomOut,{size:15})}),(0,a.jsx)("button",{type:"button",className:"ws-zoom-btn ui-tip cmp-tip-start",onClick:h.fitView,disabled:null===y||0===y.length,"aria-label":"Fit workspace to windows","data-tip":"Fit workspace to windows",children:(0,a.jsx)(N.F.expand,{size:15})}),(0,a.jsxs)("button",{type:"button",className:"ws-zoom-pct mono ui-tip",onClick:h.resetView,"aria-label":`${String(Math.round(100*d.zoom))}% — reset`,"data-tip":"Reset",children:[Math.round(100*d.zoom),"%"]}),(0,a.jsx)("button",{type:"button",className:"ws-zoom-btn ui-tip cmp-tip-end",onClick:()=>h.zoomTo(tA(d.zoom,.2)),disabled:d.zoom>=2.5,"aria-label":"Zoom in","data-tip":"Zoom in",children:(0,a.jsx)(N.F.zoomIn,{size:15})})]}),(0,a.jsx)("button",{type:"button",className:"ws-fab ui-tip cmp-tip-end",onPointerDown:e=>e.stopPropagation(),onClick:s,"aria-label":"New window","data-tip":"New window",children:(0,a.jsx)(N.F.add,{size:20})}),T?null:null!=o?o:null]});}function tq(e){let{commands:t,onClose:n}=e,[l,r]=(0,i.useState)(""),[s,o]=(0,i.useState)(0),c=(0,i.useRef)(null),d=(0,i.useRef)(null),u=(0,i.useRef)(null);(0,i.useEffect)(()=>(d.current=document.activeElement,()=>{var e,t;null==(t=d.current)||null==(e=t.focus)||e.call(t);}),[]),(0,i.useEffect)(()=>{var e;null==(e=c.current)||e.focus();},[]);let p=(0,i.useMemo)(()=>{let e=l.toLowerCase();return t.filter(t=>{var n;return`${t.label} ${null!=(n=t.group)?n:""}`.toLowerCase().includes(e);});},[t,l]);(0,i.useEffect)(()=>{o(0);},[l]),(0,i.useEffect)(()=>{var e,t;null==(t=document.getElementById(`cmdk-row-${String(s)}`))||null==(e=t.scrollIntoView)||e.call(t,{block:"nearest"});},[s,p]);let m=e=>{void 0!==e&&(e.run(),n());};return(0,a.jsx)("div",{className:"cmdk-overlay",onPointerDown:n,children:(0,a.jsxs)("div",{ref:u,className:"cmdk",role:"dialog","aria-modal":"true","aria-labelledby":"cmdk-title","aria-describedby":"cmdk-desc",tabIndex:-1,onPointerDown:e=>e.stopPropagation(),onKeyDown:e=>{if("Tab"===e.key){var t,l;let n=Array.from(null!=(t=null==(l=u.current)?void 0:l.querySelectorAll("button:not([disabled]),input:not([disabled]),[tabindex]:not([tabindex='-1'])"))?t:[]);if(n.length>0){let t=n[0],l=n[n.length-1];if(e.shiftKey&&document.activeElement===t){e.preventDefault(),l.focus();return;}if(!e.shiftKey&&document.activeElement===l){e.preventDefault(),t.focus();return;}}}if("ArrowDown"===e.key){e.preventDefault(),o(e=>Math.min(p.length-1,e+1));return;}if("ArrowUp"===e.key){e.preventDefault(),o(e=>Math.max(0,e-1));return;}if("Enter"===e.key){e.preventDefault(),m(p[s]);return;}"Escape"===e.key&&n();},children:[(0,a.jsx)("h2",{id:"cmdk-title",className:"sr-only",children:"Command palette"}),(0,a.jsx)("p",{id:"cmdk-desc",className:"sr-only",children:"Search commands and press Enter to run the selected action."}),(0,a.jsxs)("div",{className:"cmdk-input",children:[(0,a.jsx)(N.F.search,{size:16}),(0,a.jsx)("input",{ref:c,role:"combobox","aria-expanded":"true","aria-controls":"cmdk-list","aria-activedescendant":p.length>0?`cmdk-row-${String(s)}`:void 0,"aria-label":"Command query",placeholder:"Type a command…",value:l,onChange:e=>r(e.target.value)}),(0,a.jsx)("span",{className:"kbd",children:"esc"})]}),(0,a.jsx)("div",{className:"sr-only",role:"status",children:0===p.length?"No matching commands":`${String(p.length)} command${1===p.length?"":"s"}`}),(0,a.jsxs)("div",{id:"cmdk-list",role:"listbox",className:"cmdk-list",children:[0===p.length&&(0,a.jsx)("div",{className:"cmdk-empty",children:"No matching commands"}),p.map((e,t)=>{var n,l;let i;return(0,a.jsxs)("div",{role:"option",id:`cmdk-row-${String(t)}`,"aria-selected":t===s,className:"cmdk-row","data-sel":t===s,tabIndex:-1,onMouseEnter:()=>o(t),onClick:()=>m(e),children:[(0,a.jsx)("span",{className:"cmdk-ico",children:(n=e.icon,i=null!=(l=N.F[n])?l:N.F.spark,(0,a.jsx)(i,{size:16}))}),(0,a.jsx)("span",{className:"cmdk-label",children:e.label}),(0,a.jsx)("span",{className:"spacer"}),void 0!==e.shortcut&&(0,a.jsx)("span",{className:"kbd",children:e.shortcut}),void 0!==e.group&&(0,a.jsx)("span",{className:"cmdk-group mono",children:e.group})]},e.id);})]})]})});}var tM=n(97509);function tP(e){return Array.from(new Set(e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e.length>0)));}function tL(e){let{onCancel:t,preserveExisting:n=!1,storedApiKeyHeaderName:l,storedModels:r=[]}=e,s=(0,i.useRef)(null),o=(0,i.useRef)(null),c=(0,i.useRef)(null),d=(0,i.useRef)(null),u=(0,i.useRef)(void 0),[p,m]=(0,i.useState)(""),[h,f]=(0,i.useState)(""),[g,v]=(0,i.useState)(""),[b,x]=(0,i.useState)(""),[y,w]=(0,i.useState)(""),[j,S]=(0,i.useState)(""),[C,I]=(0,i.useState)(""),[R,E]=(0,i.useState)(!1),[$,A]=(0,i.useState)(),[F,T]=(0,i.useState)(),[D,q]=(0,i.useState)();async function M(e){var t,l,a,i;if(e.preventDefault(),!R){E(!0),A(void 0),T(void 0),q(void 0),null==(t=s.current)||t.focus();try{let e,t=tP(y);if(function(e){try{return new URL(e.trim()).hostname.endsWith(".services.ai.azure.com");}catch{return!1;}}(p)&&0===t.length){A("Azure AI Foundry requires deployment names. Paste the names from the Deployments tab."),E(!1);return;}try{e=function(e){let t=e.trim();if(""===t)return;let n=Number(t);if(!Number.isInteger(n)||n<=0)throw Error("Request timeout must be a positive integer in milliseconds.");return n;}(b);}catch(e){A(e instanceof Error?e.message:"Request timeout is invalid."),E(!1);return;}let r=tP(j),s=!n||""!==p.trim()||""!==h.trim()||""!==g.trim()||t.length>0||r.length>0,o=s||void 0!==e,c=""!==C.trim(),d=await(0,k.qe)({baseUrl:""===p.trim()?void 0:p.trim(),apiKey:""===h.trim()?void 0:h.trim(),apiKeyHeaderName:""===g.trim()?void 0:g.trim(),...(void 0===e?{}:{timeoutMs:e}),deploymentNames:t,preserveExisting:n,...(0===r.length?{}:{imageInputModelIds:r}),...(""===C.trim()?{}:{figmaAccessToken:C.trim()})}),m=d.testedModelIds.length,f=(i=null!=(l=d.skippedModelIds)?l:[],0===i.length?"":` Could not verify deployment${1===i.length?"":"s"}: ${i.join(", ")}.`);E(!1),c&&!o?q("Verified Figma access token. Reloading Keiko…"):c&&!s?q("Updated model gateway settings and verified Figma access token. Reloading Keiko…"):c||s?c?q(`Verified ${String(m)} workflow chat model${1===m?"":"s"} and Figma access token. Reloading Keiko…${f}`):q(`Verified ${String(m)} workflow chat model${1===m?"":"s"}. Reloading Keiko…${f}`):q("Updated model gateway settings. Reloading Keiko…"),u.current=window.setTimeout(()=>window.location.reload(),0===(null!=(a=d.skippedModelIds)?a:[]).length?800:1800);}catch(t){let e=t instanceof k.hD?{message:t.message,code:t.code}:t instanceof Error?{message:t.message}:{message:"The gateway could not be configured."};A(e.message),T(e.code),E(!1);}}}(0,i.useEffect)(()=>{var e,t,l,a;let i=document.documentElement,r=Number(null!=(e=i.dataset.keikoModalOpenCount)?e:"0");i.dataset.keikoModalOpenCount=String(r+1),i.setAttribute("data-keiko-modal-open","true");let s=Number(null!=(t=i.dataset.keikoGatewaySetupOpenCount)?t:"0");return i.dataset.keikoGatewaySetupOpenCount=String(s+1),i.setAttribute("data-keiko-gateway-setup-open","true"),d.current=document.activeElement,n?null==(l=c.current)||l.focus():null==(a=o.current)||a.focus(),()=>{var e,t,n,l;void 0!==u.current&&window.clearTimeout(u.current);let a=Math.max(0,Number(null!=(e=i.dataset.keikoModalOpenCount)?e:"1")-1);0===a?(delete i.dataset.keikoModalOpenCount,i.removeAttribute("data-keiko-modal-open")):i.dataset.keikoModalOpenCount=String(a);let r=Math.max(0,Number(null!=(t=i.dataset.keikoGatewaySetupOpenCount)?t:"1")-1);0===r?(delete i.dataset.keikoGatewaySetupOpenCount,i.removeAttribute("data-keiko-gateway-setup-open")):i.dataset.keikoGatewaySetupOpenCount=String(r),null==(l=d.current)||null==(n=l.focus)||n.call(l);};},[n]),(0,i.useEffect)(()=>{let e=s.current;if(null===e)return;let n=n=>{if("Escape"===n.key){if(R||void 0!==D||void 0===t)return;n.preventDefault(),t();return;}if("Tab"!==n.key)return;let l=Array.from(e.querySelectorAll("button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),summary,[tabindex]:not([tabindex='-1'])"));if(0===l.length)return;let a=l[0],i=l[l.length-1];n.shiftKey&&document.activeElement===a?(n.preventDefault(),i.focus()):n.shiftKey||document.activeElement!==i||(n.preventDefault(),a.focus());};return e.addEventListener("keydown",n),()=>e.removeEventListener("keydown",n);},[R,t,D]),(0,i.useEffect)(()=>{if(void 0!==$&&!R){var e,t;n&&""===p.trim()&&""===h.trim()?null==(e=c.current)||e.focus():null==(t=o.current)||t.focus();}},[h,p,R,$,n]);let P=tP(y),L=tP(j),z=!n,O=""!==p.trim()||""!==h.trim()||""!==g.trim()||""!==b.trim()||P.length>0||L.length>0,K=""!==C.trim(),B=!R&&void 0===D&&(z?""!==p.trim()&&""!==h.trim():O||K),W=r.map(e=>e.id),U=W.slice(0,6),_=Math.max(0,W.length-U.length),V=(0,a.jsxs)("div",{className:"gw-grid",children:[(0,a.jsxs)("label",{className:"gw-field gw-span-2",children:[(0,a.jsxs)("span",{children:["Base URL ",n?(0,a.jsx)("span",{className:"dlg-opt",children:"leave blank to keep"}):null]}),(0,a.jsx)("input",{className:"gw-input mono",value:p,placeholder:n?"Only enter a value to replace the stored gateway URL":"https://llm-gateway.example.com/v1",autoComplete:"off",disabled:R||void 0!==D,ref:o,onChange:e=>m(e.target.value)})]}),(0,a.jsxs)("label",{className:"gw-field",children:[(0,a.jsxs)("span",{children:["API token ",n?(0,a.jsx)("span",{className:"dlg-opt",children:"leave blank to keep"}):null]}),(0,a.jsx)("input",{className:"gw-input mono",type:"password",value:h,placeholder:n?"Only enter a value to replace the stored token":"Paste your API token",autoComplete:"off",disabled:R||void 0!==D,onChange:e=>f(e.target.value)})]}),(0,a.jsxs)("label",{className:"gw-field",children:[(0,a.jsxs)("span",{children:["API key header ",(0,a.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,a.jsx)("input",{className:"gw-input mono",value:g,placeholder:n?"Leave blank to keep stored header":"Authorization",autoComplete:"off",disabled:R||void 0!==D,onChange:e=>v(e.target.value)})]}),(0,a.jsxs)("label",{className:"gw-field",children:[(0,a.jsxs)("span",{children:["Request timeout (ms) ",(0,a.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,a.jsx)("input",{className:"gw-input mono",inputMode:"numeric",value:b,placeholder:n?"Leave blank to keep stored timeout":"30000",autoComplete:"off",disabled:R||void 0!==D,onChange:e=>x(e.target.value)})]}),(0,a.jsxs)("label",{className:"gw-field",children:[(0,a.jsx)("span",{children:"Deployment names for Azure"}),(0,a.jsx)("textarea",{className:"gw-input gw-textarea mono",value:y,placeholder:"Paste deployment names, one per line",autoComplete:"off",disabled:R||void 0!==D,onChange:e=>w(e.target.value)})]}),(0,a.jsxs)("label",{className:"gw-field",children:[(0,a.jsxs)("span",{children:["Image-input models ",(0,a.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,a.jsx)("textarea",{className:"gw-input gw-textarea mono",value:j,placeholder:"Paste image-capable model names, one per line",autoComplete:"off",disabled:R||void 0!==D,onChange:e=>S(e.target.value)})]})]}),H=(0,a.jsx)("div",{className:"gw-setup-backdrop",role:"presentation",children:(0,a.jsx)("div",{ref:s,className:"gw-setup",role:"dialog","aria-modal":"true","aria-labelledby":"gw-setup-title","aria-describedby":"gw-setup-desc",tabIndex:-1,children:(0,a.jsxs)("form",{className:"gw-form",onSubmit:e=>void M(e),children:[(0,a.jsxs)("div",{className:"gw-head",children:[(0,a.jsxs)("div",{className:"gw-setup-badge",children:[(0,a.jsx)(N.F.cube,{size:18}),n?"Credential update":"Model gateway setup"]}),(0,a.jsx)("h1",{id:"gw-setup-title",children:n?"Update Keiko credentials":"Connect Keiko to your internal LLMs"}),(0,a.jsx)("p",{id:"gw-setup-desc",children:n?"Leave stored gateway fields blank to keep the current value. Keiko never returns existing secrets to the browser.":"Keiko needs the internal gateway URL and API token before chat and agent workflows can run. The token is tested once and stored only on this machine."})]}),(0,a.jsxs)("section",{className:"gw-section","aria-labelledby":"gw-model-section-title",children:[(0,a.jsx)("div",{className:"gw-section-head",children:(0,a.jsxs)("div",{children:[(0,a.jsx)("h2",{id:"gw-model-section-title",children:"Model gateway"}),(0,a.jsx)("p",{children:n?"Blank gateway fields keep the stored value.":"Base URL and API token are required."})]})}),n?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"gw-current","aria-label":"Stored model gateway credentials",children:[(0,a.jsxs)("div",{className:"gw-current-row",children:[(0,a.jsx)("span",{children:"Gateway URL"}),(0,a.jsx)("strong",{children:"Stored"})]}),(0,a.jsxs)("div",{className:"gw-current-row",children:[(0,a.jsx)("span",{children:"API token"}),(0,a.jsx)("strong",{className:"mono",children:"••••••••••••"})]}),(0,a.jsxs)("div",{className:"gw-current-row",children:[(0,a.jsx)("span",{children:"API key header"}),(0,a.jsx)("strong",{className:"mono",children:null!=l?l:"authorization"})]}),(0,a.jsxs)("div",{className:"gw-current-models",children:[(0,a.jsx)("span",{children:"Configured models"}),(0,a.jsxs)("div",{className:"gw-model-chips",children:[0===U.length?(0,a.jsx)("strong",{children:"Stored"}):U.map(e=>(0,a.jsx)("strong",{className:"mono",children:e},e)),_>0?(0,a.jsxs)("strong",{children:["+",_.toString()]}):null]})]})]}),(0,a.jsxs)("details",{className:"gw-replace",children:[(0,a.jsx)("summary",{children:"Replace model gateway settings"}),V]})]}):V]}),(0,a.jsxs)("section",{className:"gw-section","aria-labelledby":"gw-figma-section-title",children:[(0,a.jsx)("div",{className:"gw-section-head",children:(0,a.jsxs)("div",{children:[(0,a.jsx)("h2",{id:"gw-figma-section-title",children:"Figma Snapshot"}),(0,a.jsx)("p",{children:"Optional connector credential."})]})}),(0,a.jsxs)("label",{className:"gw-field",children:[(0,a.jsxs)("span",{children:["Figma access token ",(0,a.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,a.jsx)("input",{className:"gw-input mono",type:"password",value:C,placeholder:n?"Stored Figma token is kept when blank":"Paste a read-only Figma PAT when needed",autoComplete:"off",disabled:R||void 0!==D,ref:c,onChange:e=>I(e.target.value)})]})]}),(0,a.jsx)("div",{className:"gw-note",children:"Stored secrets stay local and are never returned to the browser. Supported API-key headers: Authorization, X-Litellm-Key, X-Api-Key, api-key."}),void 0!==$?(0,a.jsxs)("div",{className:"gw-error",role:"alert",children:[$,void 0!==F?(0,a.jsx)("div",{className:"gw-error-code mono",children:F}):null]}):null,void 0!==D?(0,a.jsx)("div",{className:"gw-success",role:"status",children:D}):null,R?(0,a.jsx)("div",{className:"gw-pending",role:"status",children:"Testing credentials…"}):null,(0,a.jsx)("span",{id:"gw-submit-requirements",className:"visually-hidden",children:n?"Enter at least one field to update. Blank stored gateway fields keep their current value.":"Base URL and API token are required. The Figma access token is optional."}),(0,a.jsxs)("div",{className:"gw-actions",children:[void 0!==t?(0,a.jsx)("button",{className:"gw-cancel",type:"button",disabled:R||void 0!==D,onClick:t,children:"Cancel"}):null,(0,a.jsx)("button",{className:"gw-submit",type:"submit",disabled:!B,"aria-busy":R,"aria-describedby":"gw-submit-requirements",children:R?"Testing credentials…":"Test & save"})]})]})})});return"u"<typeof document?H:(0,tM.createPortal)(H,document.body);}function tz(e){return e.findIndex(e=>!0!==e.disabled);}function tO(e,t,n){if(0===e.length)return-1;let l=t;for(let t=0;t<e.length;t+=1){var a;if(l=(l+n+e.length)%e.length,(null==(a=e[l])?void 0:a.disabled)!==!0)return l;}return-1;}function tK(e){let{active:t,index:n,onCommit:l,onOptionKeyDown:r,option:s,setOptionRef:o}=e,c=(0,i.useRef)(null),d=(0,i.useRef)(null),u=(0,i.useRef)(null),[p,m]=(0,i.useState)(null),h=()=>{null!==u.current&&(clearTimeout(u.current),u.current=null),m(null);},f=()=>{null!==u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{let e=d.current,t=c.current;if(null===e||null===t||e.scrollWidth<=e.clientWidth)return;let n=t.getBoundingClientRect(),l=Math.min(520,window.innerWidth-32),a=n.right+8+l<=window.innerWidth-16?"top-left":"top-right";m({left:"top-left"===a?n.right+8:n.left-8,placement:a,top:n.top-6});},1500);};return(0,i.useEffect)(()=>h,[]),(0,a.jsxs)("button",{ref:e=>{c.current=e,o(n,e);},"aria-selected":t,className:`ksel-option${t?" ksel-option-active":""}`,"data-disabled":!0===s.disabled?"true":void 0,disabled:s.disabled,onBlur:h,onClick:()=>l(s),onFocus:f,onKeyDown:e=>r(e,n),onPointerEnter:f,onPointerLeave:h,role:"option",type:"button",children:[(0,a.jsxs)("span",{className:"ksel-option-copy",children:[(0,a.jsx)("span",{className:"ksel-option-label",ref:d,children:s.label}),void 0!==s.description?(0,a.jsx)("span",{className:"ksel-option-desc",children:s.description}):null]}),void 0!==s.badge?(0,a.jsx)("span",{className:"ksel-option-badge",children:s.badge}):null,null!==p?(0,tM.createPortal)((0,a.jsx)("div",{className:"ksel-overflow-tooltip","data-placement":p.placement,role:"tooltip",style:{left:`${p.left.toString()}px`,top:`${p.top.toString()}px`},children:s.label}),document.body):null]});}function tB(e){var t,n,l;let{value:r,sections:s,onValueChange:o,disabled:c=!1,placeholder:d="Select an option",ariaLabel:u,ariaDescribedBy:p,ariaLabelledBy:m,triggerClassName:h,menuClassName:f,menuTitle:g,menuCountLabel:v,showMenuHeader:b=!0,leadingVisual:x,mono:y=!1,showChevron:w=!0,menuMinWidth:j,attached:k=!0,triggerStyle:N,autoFocus:S=!1}=e,C=(0,i.useRef)(null),I=(0,i.useRef)(null),R=(0,i.useRef)([]),E=(0,i.useId)(),[$,A]=(0,i.useState)(!1),[F,T]=(0,i.useState)(-1),[D,q]=(0,i.useState)(null),[M,P]=(0,i.useState)(!1),L=(0,i.useMemo)(()=>s.flatMap((e,t)=>e.options.map((n,l)=>{var a;return{...n,key:`${null!=(a=e.label)?a:"section"}-${t.toString()}-${n.value}-${l.toString()}`,sectionLabel:e.label};})),[s]),z=L.findIndex(e=>e.value===r),O=-1===z?null:L[z],K=null!=(t=null==O?void 0:O.label)?t:d,B=null!=(n=null==O?void 0:O.description)?n:null,W=()=>{A(!1),T(-1);},U=e=>{var t,n;if(c||0===L.length)return;let l=void 0!==e&&(null==(t=L[e])?void 0:t.disabled)!==!0?e:z>=0&&(null==(n=L[z])?void 0:n.disabled)!==!0?z:tz(L);A(!0),T(l);};function _(e){var t;e.disabled||(o(e.value),W(),null==(t=C.current)||t.focus());}function V(e,t){if("Escape"===e.key){var n;e.preventDefault(),W(),null==(n=C.current)||n.focus();return;}if("Tab"===e.key)return void W();if("ArrowDown"===e.key){e.preventDefault(),T(tO(L,t,1));return;}if("ArrowUp"===e.key){e.preventDefault(),T(tO(L,t,-1));return;}if("Home"===e.key){e.preventDefault(),T(tz(L));return;}if("End"===e.key){e.preventDefault(),T(tO(L,0,-1));return;}if("Enter"===e.key||" "===e.key){e.preventDefault();let n=L[t];void 0!==n&&_(n);}}(0,i.useEffect)(()=>{if(!$)return;let e=e=>{let t=e.target;null!==C.current&&t instanceof Node&&C.current.contains(t)||null!==I.current&&t instanceof Node&&I.current.contains(t)||W();},t=()=>W();return window.addEventListener("pointerdown",e,!0),window.addEventListener("blur",t),()=>{window.removeEventListener("pointerdown",e,!0),window.removeEventListener("blur",t);};},[$]),(0,i.useLayoutEffect)(()=>{if(!$||null===C.current)return;let e=()=>{var e;let t=null==(e=C.current)?void 0:e.getBoundingClientRect();if(void 0===t)return;let n=Math.min(void 0!==j&&t.width<Math.min(j,96)?j:t.width,window.innerWidth-32),l=k&&1>Math.abs(n-t.width),a=l?-1:6,i=window.innerHeight-t.bottom-16,r=t.top-16,s=i<Math.max(96,2*t.height)&&r>i;P(s);let o=s?r:i,c=50*!!b+2,d=Math.max(t.height,Math.min(Math.max(t.height,o-c),380)),u=d+c,p=window.getComputedStyle(C.current);q({left:Math.min(Math.max(16,t.left),window.innerWidth-n-16),width:n,top:s?Math.max(16,t.top-u-a):Math.min(t.bottom+a,window.innerHeight-16-u),optionHeight:Math.max(28,Math.min(t.height,30)),maxHeight:d,openUp:s,attached:l,fontFamily:p.fontFamily,fontSize:p.fontSize,fontWeight:p.fontWeight,letterSpacing:p.letterSpacing,lineHeight:p.lineHeight});};return e(),window.addEventListener("resize",e),window.addEventListener("scroll",e,!0),()=>{window.removeEventListener("resize",e),window.removeEventListener("scroll",e,!0);};},[$,k,j,b]),(0,i.useLayoutEffect)(()=>{if(!$||null===D||!D.openUp||null===C.current||null===I.current)return;let e=C.current.getBoundingClientRect(),t=I.current.getBoundingClientRect();if(t.height<=0)return;let n=D.attached?-1:6,l=Math.max(16,e.top-t.height-n);.5>Math.abs(l-D.top)||q(e=>null===e?e:{...e,top:l});},[$,D]),(0,i.useEffect)(()=>{var e,t;$&&!(F<0)&&(null==(e=R.current[F])||e.focus(),null==(t=R.current[F])||t.scrollIntoView({block:"nearest"}));},[$,F]),(0,i.useEffect)(()=>{if(!$)return;let e=e=>{var t,n;if("Escape"===e.key){W(),null==(t=C.current)||t.focus();return;}if(1===e.key.length&&!e.metaKey&&!e.ctrlKey&&!e.altKey){if((n=e.target)instanceof HTMLElement&&("INPUT"===n.tagName||"TEXTAREA"===n.tagName||"SELECT"===n.tagName||n.isContentEditable))return;let t=e.key.toLowerCase(),l=F>=0?F:z>=0?z:0;for(let e=1;e<=L.length;e+=1){let n=(l+e)%L.length,a=L[n];if(void 0!==a&&!0!==a.disabled&&a.label.toLowerCase().startsWith(t)){T(n);break;}}}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e);},[$,F,L,z]);let H=["ksel-trigger",y?"mono":"",null!=h?h:"",$?"ksel-trigger-open":"",$&&(null==D?void 0:D.attached)===!0?M?"ksel-trigger-open-up":"ksel-trigger-open-down":"",c?"ksel-trigger-disabled":""].filter(e=>e.length>0).join(" "),J=$&&null!==D?(0,tM.createPortal)((0,a.jsxs)("div",{ref:I,className:["ksel-menu",D.attached?"ksel-menu-attached":"",D.openUp?"ksel-menu-open-up":"ksel-menu-open-down",null!=f?f:""].filter(e=>e.length>0).join(" "),style:{left:`${D.left.toString()}px`,top:`${D.top.toString()}px`,width:`${D.width.toString()}px`,"--ksel-option-height":`${D.optionHeight.toString()}px`,fontFamily:D.fontFamily,fontSize:D.fontSize,fontWeight:D.fontWeight,letterSpacing:D.letterSpacing,lineHeight:D.lineHeight},children:[b?(0,a.jsxs)("div",{className:"ksel-menu-head",children:[(0,a.jsx)("div",{className:"ksel-menu-title",children:null!=(l=null!=g?g:u)?l:d}),(0,a.jsx)("div",{className:"ksel-menu-note",children:null!=v?v:`${L.length.toString()} options`})]}):null,(0,a.jsx)("div",{className:"ksel-menu-scroll",role:"listbox",id:E,style:{maxHeight:`${D.maxHeight.toString()}px`},children:s.map((e,t)=>{var n;return(0,a.jsxs)("div",{className:"ksel-section",children:[void 0!==e.label?(0,a.jsx)("div",{className:"ksel-section-label",children:e.label}):null,e.options.map(t=>{var n;let l=L.findIndex(n=>n.value===t.value&&n.sectionLabel===e.label),i=l===z,r=L[l];return void 0===r?null:(0,a.jsx)(tK,{active:i,index:l,onCommit:_,onOptionKeyDown:V,option:r,setOptionRef:(e,t)=>{R.current[e]=t;}},`${null!=(n=e.label)?n:"section"}-${t.value}`);})]},`${null!=(n=e.label)?n:"section"}-${t.toString()}`);})})]}),document.body):null;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("button",{ref:C,"aria-controls":E,"aria-describedby":p,"aria-expanded":$,"aria-haspopup":"listbox","aria-label":u,"aria-labelledby":m,autoFocus:S,className:H,disabled:c,onClick:()=>{$?W():U();},onKeyDown:function(e){if(!c){if("ArrowDown"===e.key||"ArrowUp"===e.key){e.preventDefault(),U(z>=0?z:tz(L));return;}("Enter"===e.key||" "===e.key)&&(e.preventDefault(),$?W():U());}},role:"combobox",style:N,type:"button",children:[void 0!==x?(0,a.jsx)("span",{className:"ksel-trigger-leading",children:x}):null,(0,a.jsxs)("span",{className:"ksel-trigger-copy",children:[(0,a.jsx)("span",{className:"ksel-trigger-label",children:K}),null!==B?(0,a.jsx)("span",{className:"ksel-trigger-desc",children:B}):null]}),w?(0,a.jsx)("span",{"aria-hidden":"true",className:`ksel-trigger-caret${$?" ksel-trigger-caret-open":""}`,children:(0,a.jsx)("svg",{fill:"none",height:"12",viewBox:"0 0 12 12",width:"12",children:(0,a.jsx)("path",{d:"M2.25 4.5 6 8.25 9.75 4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5"})})}):null]}),J]});}let tW=[["ask","Ask every action"],["full","Full access"]];function tU(e){let{cfg:t,set:n}=e,l=!1!==t.keikoMode,i="full"===t.access?"full":"ask",r=l?"No rights by default. You approve while manual; Keiko governs per policy when autonomous.":"full"===i?"Legacy: agent acts without prompts.":"Legacy: you approve each privileged action.";return(0,a.jsxs)("div",{className:"permctl",children:[(0,a.jsxs)("button",{type:"button",className:"perm-toggle","data-on":l,"aria-pressed":l,onClick:()=>n("keikoMode",!l),children:[(0,a.jsx)("img",{className:"perm-orca",src:"/assets/keiko-logo.svg",alt:""}),(0,a.jsxs)("span",{className:"perm-tt",children:[(0,a.jsx)("span",{className:"perm-name",children:"Keiko-Mode"}),(0,a.jsx)("span",{className:"perm-desc",children:"Zero standing rights \xb7 Keiko governs"})]}),(0,a.jsx)("span",{className:"perm-sw"+(l?" on":""),children:(0,a.jsx)("span",{})})]}),!l&&(0,a.jsx)("div",{className:"perm-legacy",children:tW.map(e=>{let[t,l]=e;return(0,a.jsx)("button",{type:"button",className:"perm-opt","data-on":i===t,"aria-pressed":i===t,onClick:()=>n("access",t),children:l},t);})}),(0,a.jsx)("div",{className:"perm-note",children:r})]});}function t_(e){return"chat"===e.kind&&e.toolCalling&&e.structuredOutput;}function tV(e){if(e instanceof k.hD){if("BAD_ROOT"===e.code)return"Enter an absolute folder path.";if("DENIED"===e.code)return"That location is excluded.";}return e instanceof Error?e.message:"Unable to read directories.";}function tH(e){let{value:t,projectId:n,selectProjectRoot:l=!1,onSelect:r,onClose:s}=e,[o,c]=(0,i.useState)(null),[d,u]=(0,i.useState)(t),[p,m]=(0,i.useState)(!1),[h,f]=(0,i.useState)(null),g=null!=n?n:t.trim(),v=(0,i.useCallback)(async e=>{if(0===g.length){c(null),f("Enter an absolute folder path.");return;}m(!0),f(null);try{let t=await(0,k.xe)(g,e);c(t),u(t.path);}catch(e){f(tV(e));}finally{m(!1);}},[g]);return(0,i.useEffect)(()=>{v(t.length>0?t:void 0);},[]),(0,a.jsxs)("div",{className:"dir-picker",role:"group","aria-label":"Directory picker",children:[(0,a.jsxs)("div",{className:"dir-top",children:[(0,a.jsx)("input",{className:"dlg-input mono dir-path",value:d,"aria-label":"Folder path",placeholder:"/absolute/folder/path",onChange:e=>u(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),v(d));}}),(0,a.jsx)("button",{type:"button",className:"dlg-btn dir-go",onClick:()=>void v(d),children:"Go"})]}),null!==o?(0,a.jsx)("div",{className:"dir-roots",children:o.roots.map(e=>(0,a.jsx)("button",{type:"button",className:"dir-chip",onClick:()=>void v(e.path),children:e.label},`${e.label}:${e.path}`))}):null,(0,a.jsxs)("div",{className:"dir-list",children:[(null==o?void 0:o.parent)!==null&&(null==o?void 0:o.parent)!==void 0?(0,a.jsxs)("button",{type:"button",className:"dir-row",onClick:()=>{var e;v(null!=(e=o.parent)?e:void 0);},children:[(0,a.jsx)(N.F.back,{size:14}),(0,a.jsx)("span",{children:"Parent directory"})]}):null,null==o?void 0:o.entries.map(e=>(0,a.jsxs)("button",{type:"button",className:"dir-row",onClick:()=>void v(e.path),children:[(0,a.jsx)(N.F.folder,{size:14}),(0,a.jsx)("span",{children:e.name})]},e.path)),p?(0,a.jsx)("div",{className:"dir-note",role:"status",children:"Loading directories…"}):null,p||null===o||0!==o.entries.length?null:(0,a.jsx)("div",{className:"dir-note",children:"No child directories."}),null!==h?(0,a.jsx)("div",{className:"dir-error",role:"alert",children:h}):null]}),(0,a.jsxs)("div",{className:"dir-actions",children:[(0,a.jsx)("button",{type:"button",className:"dlg-btn",onClick:s,children:"Close"}),(0,a.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",onClick:()=>{if(null!==o){var e,t;r(l&&null!=(e=null==(t=o.roots[0])?void 0:t.path)?e:o.path),s();}},disabled:null===o,children:"Use directory"})]})]});}let tJ=[{id:"unit-test-generation",label:"Unit Test Agent",scope:"Source file"},{id:"bug-investigation",label:"Bugfix Agent",scope:"Bug report"}];function tY(e){return e.filter(e=>e.available).map(e=>e.path);}function tX(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e.length>0);}function tG(e){let t=tQ(e.trim()).replace(/\/+$/u,""),n=t.lastIndexOf("/");return n>0?t.slice(0,n):"";}function tQ(e){return e.replaceAll("\\","/");}function tZ(e,t){let n=tQ(t.trim());if(0===n.length)return"";let l=tQ(e.trim()).replace(/\/+$/u,"");if(0===l.length)return n;if(n===l)return".";let a=`${l}/`;return n.startsWith(a)?n.slice(a.length):n;}function t0(e){let{root:t,value:n,onSelect:l,onClose:r}=e,s=tZ(t,n),[o,c]=(0,i.useState)(tG(s)),[d,u]=(0,i.useState)(s),[p,m]=(0,i.useState)([]),[h,f]=(0,i.useState)(!1),[g,v]=(0,i.useState)(!1),[b,x]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(0===t.trim().length){m([]),f(!1),v(!1),x("Select a repository first.");return;}let e=!1;return v(!0),x(null),(0,k.KD)(t.trim(),o).then(t=>{e||(m(t.entries),f(t.truncated));}).catch(t=>{e||(m([]),f(!1),x(tV(t)));}).finally(()=>{e||v(!1);}),()=>{e=!0;};},[o,t]);let y=p.filter(e=>"directory"===e.kind),w=p.filter(e=>"directory"!==e.kind);return(0,a.jsxs)("div",{className:"file-picker",role:"group","aria-label":"File picker",children:[(0,a.jsx)("div",{className:"file-picker-head",children:(0,a.jsx)("span",{className:"file-picker-path mono",children:0===o.length?"Repository root":o})}),(0,a.jsxs)("div",{className:"dir-list file-picker-list",children:[o.length>0?(0,a.jsxs)("button",{type:"button",className:"dir-row",onClick:()=>c(tG(o)),children:[(0,a.jsx)(N.F.back,{size:14}),(0,a.jsx)("span",{children:"Parent folder"})]}):null,y.map(e=>(0,a.jsxs)("button",{type:"button",className:"dir-row file-picker-row",disabled:!e.readable,onClick:()=>c(e.path),title:e.path,children:[(0,a.jsx)(N.F.folder,{size:14}),(0,a.jsx)("span",{children:e.name})]},e.path)),w.map(e=>(0,a.jsxs)("button",{type:"button",className:"dir-row file-picker-row","data-selected":d===e.path?"true":void 0,disabled:!e.readable,"aria-pressed":d===e.path,onClick:()=>u(e.path),title:e.path,children:[(0,a.jsx)(N.F.file,{size:14}),(0,a.jsx)("span",{children:e.name}),(0,a.jsx)("span",{className:"file-picker-meta mono",children:function(e){if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=e,l=0;for(;n>=1024&&l<t.length-1;)n/=1024,l+=1;let a=0===l?n.toFixed(0):n.toFixed(n>=10?1:2);return`${a} ${t[l]}`;}(e.sizeBytes)})]},e.path)),g?(0,a.jsx)("div",{className:"dir-note",role:"status",children:"Loading files…"}):null,g||null!==b||0!==p.length?null:(0,a.jsx)("div",{className:"dir-note",children:"No files in this folder."}),h?(0,a.jsxs)("div",{className:"dir-note file-picker-warning",role:"status",children:["Showing only the first ",p.length.toString()," entries."]}):null,null!==b?(0,a.jsx)("div",{className:"dir-error",role:"alert",children:b}):null]}),(0,a.jsxs)("div",{className:"dir-actions",children:[(0,a.jsx)("button",{type:"button",className:"dlg-btn",onClick:r,children:"Close"}),(0,a.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",onClick:()=>{0!==d.trim().length&&(l(tZ(t,d)),r());},disabled:0===d.trim().length,children:"Use file"})]})]});}function t1(e){var t,n;let{filesContext:l,firstRef:r,directoryField:s,setDirectoryField:o,setDialogError:c,onConfirm:d}=e,[u,p]=(0,i.useState)("unit-test-generation"),[m,h]=(0,i.useState)(null!=(t=null==l?void 0:l.root)?t:""),[f,g]=(0,i.useState)(""),[v,b]=(0,i.useState)([]),[x,y]=(0,i.useState)([]),[w,j]=(0,i.useState)(()=>{var e,t,n,a;let i;return n=null!=(e=null==l?void 0:l.root)?e:"",{verifyTargetFiles:i=null===(a=null!=(t=null==l?void 0:l.activeFilePath)?t:null)?"":tZ(n,a),explainFilePath:i,explainQuestion:"",unitFilePath:i,bugDescription:"",bugFailingOutput:"",bugStackTrace:"",bugTargetFiles:i};}),[S,C]=(0,i.useState)(!0),[I,R]=(0,i.useState)(!1),[E,$]=(0,i.useState)(!1),A=m.trim(),F=null!==l&&l.root===A&&void 0!==l.activeFilePath?l.activeFilePath:null,T=A.length>0&&x.includes(A),D=0===A.length?"Repository is required.":0===f.length?"No compatible model is available.":"explain-plan"===u&&0===w.explainFilePath.trim().length?"Explain plan requires a file path.":"unit-test-generation"===u&&0===w.unitFilePath.trim().length?"Unit Test Agent requires a source file.":"bug-investigation"===u&&0===w.bugDescription.trim().length?"Bugfix Agent requires an observed behavior.":null,q=null===D&&T&&!E&&!S,M=null!=(n=tJ.find(e=>e.id===u))?n:tJ[0],P="unit-test-generation"===u?"Start Unit Test Agent":"Start Bugfix Agent";(0,i.useEffect)(()=>{let e=!1;return C(!0),c(null),Promise.all([(0,k.ZC)(),(0,k.vj)()]).then(t=>{let[n,l]=t;if(e)return;let a=n.models.filter(t_);b(a),g(e=>{var t,n;return e||(null!=(t=null==(n=a[0])?void 0:n.id)?t:"");}),y(tY(l.projects));}).catch(t=>{e||c(tV(t));}).finally(()=>{e||C(!1);}),()=>{e=!0;};},[c]);let L=e=>{j(t=>({...t,...e}));};(0,i.useEffect)(()=>{if(null===F)return;let e=tZ(A,F);j(t=>{let n={};return 0===t.verifyTargetFiles.trim().length&&(n.verifyTargetFiles=e),0===t.explainFilePath.trim().length&&(n.explainFilePath=e),0===t.unitFilePath.trim().length&&(n.unitFilePath=e),0===t.bugTargetFiles.trim().length&&(n.bugTargetFiles=e),0===Object.keys(n).length?t:{...t,...n};});},[F,A]);let z=async()=>{y(tY((await(0,k.vj)()).projects));},O=async()=>{if(0!==A.length){R(!0),c(null);try{await(0,k.gA)({path:A}),await z();}catch(e){c(tV(e));}finally{R(!1);}}},K=async()=>{if(!q)return void c(null!=D?D:"Repository is not registered.");$(!0),c(null);let e=function(e,t,n,l){if("verify"===e){let e=tX(l.verifyTargetFiles).map(e=>tZ(t,e));return{taskType:"verify",modelId:n,input:{workspaceRoot:t,...(e.length>0?{targetFiles:e}:{})}};}return"explain-plan"===e?{taskType:"explain-plan",modelId:n,input:{workspaceRoot:t,filePath:tZ(t,l.explainFilePath),...(l.explainQuestion.trim().length>0?{question:l.explainQuestion.trim()}:{})}}:"unit-test-generation"===e?{workflowId:"unit-test-generation",modelId:n,input:{workspaceRoot:t,target:{kind:"file",filePath:tZ(t,l.unitFilePath)}}}:{workflowId:"bug-investigation",modelId:n,input:{workspaceRoot:t,report:{...(l.bugDescription.trim().length>0?{description:l.bugDescription.trim()}:{}),...(l.bugFailingOutput.trim().length>0?{failingOutput:l.bugFailingOutput.trim()}:{}),...(l.bugStackTrace.trim().length>0?{stackTrace:l.bugStackTrace.trim()}:{}),...(tX(l.bugTargetFiles).length>0?{targetFiles:tX(l.bugTargetFiles).map(e=>tZ(t,e))}:{})}}};}(u,A,f,w);try{let t=await(0,k.AD)(e);d({workflow:u,model:f,runId:t.runId,fingerprint:t.fingerprint,workspaceRoot:A,inputJson:JSON.stringify(e.input),...(null!==l&&l.root===A?{__connectFilesId:l.id}:{})});}catch(e){e instanceof k.hD&&"WORKSPACE_NOT_REGISTERED"===e.code?(await z().catch(()=>void 0),c("Repository is not registered.")):c(tV(e));}finally{$(!1);}};return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"dlg-agent-grid",children:[(0,a.jsxs)("div",{className:"dlg-field",children:[(0,a.jsx)("span",{className:"dlg-label",children:"Agent"}),(0,a.jsx)("span",{className:"dlg-selwrap",children:(0,a.jsx)(tB,{triggerClassName:"dlg-input",value:u,ariaLabel:"Agent",autoFocus:!0,menuTitle:"Agent",menuCountLabel:`${tJ.length.toString()} agents`,sections:[{options:tJ.map(e=>({value:e.id,label:e.label}))}],onValueChange:e=>{let t=tJ.find(t=>t.id===e);void 0!==t&&p(t.id);}})})]}),(0,a.jsxs)("div",{className:"dlg-field",children:[(0,a.jsx)("span",{className:"dlg-label",children:"Model"}),(0,a.jsx)("span",{className:"dlg-selwrap",children:(0,a.jsx)(tB,{triggerClassName:"dlg-input mono",value:f,ariaLabel:"Model",disabled:0===v.length,menuTitle:"Model",mono:!0,sections:[{options:v.map(e=>({value:e.id,label:e.id}))}],onValueChange:g})})]})]}),(0,a.jsxs)("label",{className:"dlg-field",children:[(0,a.jsx)("span",{className:"dlg-label",children:"Repository"}),(0,a.jsxs)("span",{className:"dlg-dirwrap",children:[(0,a.jsx)("input",{className:"dlg-input mono",value:m,placeholder:"/absolute/repository/path",onClick:()=>o("agentWorkspace"),onChange:e=>h(e.target.value)}),(0,a.jsx)("button",{type:"button",className:"dlg-btn dlg-dirbtn",onClick:()=>o("agentWorkspace"),children:"Browse"})]}),"agentWorkspace"===s?(0,a.jsx)(tH,{value:m,projectId:T?A:void 0,onSelect:h,onClose:()=>o(null)}):null]}),A.length>0&&!T?(0,a.jsxs)("div",{className:"dlg-agent-warning",children:[(0,a.jsx)("span",{children:"Repository is not registered."}),(0,a.jsx)("button",{type:"button",className:"dlg-btn",disabled:I,onClick:()=>void O(),children:I?"Registering…":"Register repository"})]}):null,null!==F?(0,a.jsxs)("button",{type:"button",className:"dlg-current-file",onClick:()=>{if(null===F)return;let e=tZ(A,F);"unit-test-generation"===u?L({unitFilePath:e}):L({bugTargetFiles:e});},title:F,children:[(0,a.jsx)(N.F.files,{size:13})," Use current file ",(0,a.jsx)("span",{className:"mono",children:F})]}):null,(0,a.jsxs)("div",{className:"dlg-agent-task",children:[(0,a.jsxs)("div",{className:"dlg-agent-task-head",children:[(0,a.jsx)("span",{className:"dlg-agent-task-title",children:M.label}),(0,a.jsx)("span",{className:"dlg-agent-task-scope",children:M.scope})]}),"unit-test-generation"===u?(0,a.jsxs)("label",{className:"dlg-field",children:[(0,a.jsx)("span",{className:"dlg-label",children:"Source file"}),(0,a.jsxs)("span",{className:"dlg-dirwrap",children:[(0,a.jsx)("input",{className:"dlg-input mono",placeholder:"src/file.ts",value:w.unitFilePath,onChange:e=>L({unitFilePath:e.target.value}),onBlur:e=>L({unitFilePath:tZ(A,e.target.value)})}),(0,a.jsx)("button",{type:"button",className:"dlg-btn dlg-dirbtn","aria-label":"Browse source file",onClick:()=>o("unitSourceFile"),children:"Browse"})]}),"unitSourceFile"===s?(0,a.jsx)(t0,{root:A,value:w.unitFilePath,onSelect:e=>L({unitFilePath:e}),onClose:()=>o(null)}):null]}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("label",{className:"dlg-field",children:[(0,a.jsx)("span",{className:"dlg-label",children:"Observed behavior"}),(0,a.jsx)("textarea",{className:"dlg-input dlg-textarea",rows:2,placeholder:"Describe the observed bug.",value:w.bugDescription,onChange:e=>L({bugDescription:e.target.value})})]}),(0,a.jsxs)("label",{className:"dlg-field",children:[(0,a.jsxs)("span",{className:"dlg-label",children:["Failing output ",(0,a.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,a.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,value:w.bugFailingOutput,onChange:e=>L({bugFailingOutput:e.target.value})})]}),(0,a.jsxs)("label",{className:"dlg-field",children:[(0,a.jsxs)("span",{className:"dlg-label",children:["Stack trace ",(0,a.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,a.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,value:w.bugStackTrace,onChange:e=>L({bugStackTrace:e.target.value})})]}),(0,a.jsxs)("label",{className:"dlg-field",children:[(0,a.jsxs)("span",{className:"dlg-label",children:["Related files ",(0,a.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,a.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,placeholder:"src/file.ts, src/other.ts",value:w.bugTargetFiles,onChange:e=>L({bugTargetFiles:e.target.value}),onBlur:e=>L({bugTargetFiles:tX(e.target.value).map(e=>tZ(A,e)).join(", ")})})]})]})]}),(0,a.jsxs)("div",{className:"dlg-agent-actions",children:[(0,a.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",disabled:!q,"aria-busy":E,"aria-describedby":q||E?void 0:"agent-start-validation",onClick:()=>void K(),children:E?"Starting…":P}),S?(0,a.jsx)("span",{id:"agent-start-validation",className:"dlg-note",role:"status",children:"Loading models and projects…"}):null,S||null===D?null:(0,a.jsx)("span",{id:"agent-start-validation",className:"dlg-note",role:"status",children:D})]})]});}function t2(e){var t,n;let{type:l,types:r,filesContext:s=null,onConfirm:o,onClose:c}=e,d=r[l],u=null!=(t=d.config)?t:[],[p,m]=(0,i.useState)(()=>function(e){let t={};for(let l of e){var n;t[l.key]=null!=(n=l.def)?n:"";}return t;}(u)),[h,f]=(0,i.useState)(!1),[g,v]=(0,i.useState)(null),[b,x]=(0,i.useState)(null),y=(0,i.useRef)(null),w=(0,i.useRef)(null),j=(0,i.useRef)(null);(0,i.useEffect)(()=>(j.current=document.activeElement,()=>{let e=j.current;null!==e&&e.isConnected?e.focus():requestAnimationFrame(()=>{var e,t;(null!=(e=null!=(t=document.querySelector('.window[data-top="true"]'))?t:document.querySelector(".ws-fab"))?e:document.body).focus({preventScroll:!0});});}),[]),(0,i.useEffect)(()=>{let e=requestAnimationFrame(()=>{var e,t;f(!0),null==(t=null!=(e=y.current)?e:w.current)||t.focus();});return()=>cancelAnimationFrame(e);},[]),(0,i.useEffect)(()=>{let e=e=>{"Escape"===e.key&&c();};return window.addEventListener("keydown",e),()=>{window.removeEventListener("keydown",e);};},[c]),(0,i.useEffect)(()=>{if("files"!==l&&"editor"!==l)return;let e=!1,t=p.root;if("string"!=typeof t||!(t.length>0))return v(null),(0,k.vj)().then(t=>{let n=tY(t.projects)[0];e||void 0===n||m(e=>({...e,root:n}));}).catch(t=>{e||v(tV(t));}),()=>{e=!0;};},[p.root,l]);let S=(e,t)=>m(n=>({...n,[e]:t})),C=()=>{"agents"!==l&&o(p);},I=N.F[d.icon],R=null!=(n=d.cta)?n:`Open ${d.title}`;return(0,a.jsx)("div",{className:"dlg-overlay"+(h?" in":""),onPointerDown:c,children:(0,a.jsxs)("div",{ref:w,className:"agents"===l?"dlg dlg-agents":"dlg",role:"dialog","aria-modal":"true","aria-labelledby":"new-window-title","aria-describedby":"new-window-desc",tabIndex:-1,onPointerDown:e=>e.stopPropagation(),onKeyDown:e=>{let t,n;if("Escape"===e.key)return void c();if("Enter"===e.key&&(e.metaKey||e.ctrlKey))return void C();if("Enter"===e.key){let t=e.target instanceof HTMLElement?e.target.tagName:"";("INPUT"===t||"SELECT"===t)&&(e.preventDefault(),C());return;}if("Tab"!==e.key)return;let l=(t=e.currentTarget.querySelectorAll("button,input,select,textarea"),n=[],t.forEach(e=>{e.hasAttribute("disabled")||(null!==e.offsetParent||"BUTTON"===e.tagName)&&n.push(e);}),n);if(0===l.length)return;let a=l[0],i=l[l.length-1];e.shiftKey&&document.activeElement===a?(e.preventDefault(),i.focus()):e.shiftKey||document.activeElement!==i||(e.preventDefault(),a.focus());},children:[(0,a.jsxs)("div",{className:"dlg-head",children:[(0,a.jsx)("span",{className:"dlg-ico",children:(0,a.jsx)(I,{size:20})}),(0,a.jsxs)("div",{className:"dlg-htext",children:[(0,a.jsxs)("span",{id:"new-window-title",className:"dlg-title",children:["New ",d.title," window"]}),(0,a.jsx)("span",{id:"new-window-desc",className:"dlg-sub",children:d.desc})]}),(0,a.jsx)("span",{className:"spacer"}),(0,a.jsx)("button",{type:"button",className:"palette-x",onClick:c,"aria-label":"Cancel",title:"Cancel",children:(0,a.jsx)(N.F.close,{size:16})})]}),(0,a.jsxs)("div",{className:"dlg-body",children:["agents"===l?(0,a.jsx)(t1,{filesContext:s,firstRef:e=>{y.current=e;},directoryField:b,setDirectoryField:x,setDialogError:v,onConfirm:o}):0===u.length&&(0,a.jsxs)("div",{className:"dlg-empty",children:["Add a new ",d.title," window to your workspace."]}),"agents"!==l&&u.map((e,t)=>(0,a.jsxs)("label",{className:"dlg-field",children:[(0,a.jsxs)("span",{className:"dlg-label",children:[e.label,!0===e.optional&&(0,a.jsx)("span",{className:"dlg-opt",children:"optional"})]}),function(e,t,n,l,i){var r,s,o,c;if("perm"===e.type)return(0,a.jsx)(tU,{cfg:t,set:n});let d=t[e.key],u="string"==typeof d?d:void 0===d?"":String(d);if("select"===e.type){let t=null!=(s=e.options)?s:[];return(0,a.jsx)("span",{className:"dlg-selwrap",children:(0,a.jsx)(tB,{triggerClassName:"dlg-input mono",value:u,disabled:0===t.length,autoFocus:null!==l,menuTitle:e.label,mono:!0,sections:[{options:t.map(t=>{var n;return{value:t,label:`${null!=(n=e.prefix)?n:""}${t}`};})}],onValueChange:t=>n(e.key,t)})});}return"textarea"===e.type?(0,a.jsx)("textarea",{ref:null!=l?l:void 0,className:"dlg-input dlg-textarea",rows:3,placeholder:null!=(o=e.placeholder)?o:"",value:u,onChange:t=>n(e.key,t.target.value)}):"directory"===e.type?(0,a.jsxs)("span",{className:"dlg-dirwrap",children:[(0,a.jsx)("input",{ref:null!=l?l:void 0,className:"dlg-input mono",placeholder:null!=(c=e.placeholder)?c:e.label,value:u,onClick:()=>i(e.key),onChange:t=>n(e.key,t.target.value)}),(0,a.jsx)("button",{type:"button",className:"dlg-btn dlg-dirbtn",onClick:()=>i(e.key),children:"Browse"})]}):(0,a.jsx)("input",{ref:null!=l?l:void 0,className:"dlg-input mono",placeholder:null!=(r=e.placeholder)?r:e.label,value:u,onChange:t=>n(e.key,t.target.value)});}(e,p,S,0===t?e=>{y.current=e;}:null,x),"directory"===e.type&&b===e.key?(0,a.jsx)(tH,{value:"string"==typeof p[e.key]?p[e.key]:"",selectProjectRoot:"root"===e.key,onSelect:t=>S(e.key,t),onClose:()=>x(null)}):null]},e.key)),null!==g?(0,a.jsx)("div",{className:"dlg-error",role:"alert",children:g}):null]}),(0,a.jsxs)("div",{className:"dlg-foot",children:[(0,a.jsx)("button",{type:"button",className:"dlg-btn",onClick:c,children:"Cancel"}),"agents"!==l?(0,a.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",onClick:C,children:R}):null]})]})});}function t3(e){let{types:t,order:n,onAdd:l,onClose:r}=e,s=n.length<=4?2:3,o=(0,i.useRef)(null),c=(0,i.useRef)(null),[d,u]=(0,i.useState)(0);return(0,i.useEffect)(()=>{var e;c.current=document.activeElement;let t=null==(e=o.current)?void 0:e.querySelector(".pal-card");return null==t||t.focus(),()=>{var e,t;let n=document.activeElement;(null===n||n===document.body)&&(null==(t=c.current)||null==(e=t.focus)||e.call(t));};},[]),(0,i.useEffect)(()=>{let e=e=>{null!==o.current&&e.target instanceof Node&&!o.current.contains(e.target)&&r();};return document.addEventListener("pointerdown",e),()=>{document.removeEventListener("pointerdown",e);};},[r]),(0,a.jsxs)("div",{ref:o,className:"palette",role:"dialog","aria-labelledby":"palette-title","aria-describedby":"palette-desc",tabIndex:-1,onPointerDown:e=>e.stopPropagation(),onKeyDown:e=>{var t,n,l;if("Escape"===e.key){e.preventDefault(),r();return;}if(!(e.target instanceof HTMLElement)||!e.target.classList.contains("pal-card"))return;let a=Array.from(null!=(t=null==(n=o.current)?void 0:n.querySelectorAll(".pal-card"))?t:[]),i=function(e,t,n,l){let a;if(0===n)return null;if("Home"===e)return 0;if("End"===e)return n-1;if("ArrowRight"===e)a=1;else if("ArrowLeft"===e)a=-1;else if("ArrowDown"===e)a=l;else{if("ArrowUp"!==e)return null;a=-l;}return Math.max(0,Math.min(n-1,t+a));}(e.key,a.indexOf(e.target),a.length,s);null!==i&&(e.preventDefault(),u(i),null==(l=a[i])||l.focus());},onBlur:e=>{var t;e.relatedTarget instanceof Node&&(null==(t=o.current)?void 0:t.contains(e.relatedTarget))!==!0&&r();},"data-columns":s,children:[(0,a.jsxs)("div",{className:"palette-head",children:[(0,a.jsx)("span",{className:"palette-badge",children:(0,a.jsx)(N.F.add,{size:17})}),(0,a.jsxs)("div",{className:"palette-htext",children:[(0,a.jsx)("span",{id:"palette-title",className:"palette-title",children:"New window"}),(0,a.jsx)("span",{id:"palette-desc",className:"palette-sub",children:"Pick a card to add to your workspace"})]}),(0,a.jsx)("span",{className:"spacer"}),(0,a.jsx)("button",{type:"button",className:"palette-x",onClick:r,"aria-label":"Close",title:"Close",children:(0,a.jsx)(N.F.close,{size:16})})]}),(0,a.jsx)("div",{className:"palette-grid",children:n.map((e,n)=>{let i=t[e],r=N.F[i.icon];return(0,a.jsxs)("button",{type:"button",className:"pal-card pal-main",tabIndex:n===d?0:-1,onFocus:()=>u(n),onClick:()=>l(e),children:[(0,a.jsx)("span",{className:"pal-ico",children:(0,a.jsx)(r,{size:18})}),(0,a.jsx)("span",{className:"pal-name",children:i.title}),(0,a.jsx)("span",{className:"pal-desc",children:i.desc}),(0,a.jsx)("span",{className:"pal-add","aria-hidden":"true",children:(0,a.jsx)(N.F.plus,{size:15})})]},e);})})]});}async function t4(e){try{let t=await e.json();return{code:t.error.code,message:t.error.message};}catch{return{code:"INTERNAL",message:`HTTP ${e.status.toString()}`};}}async function t6(e,t){var n;let l,a,i=(null!=(n=null==t?void 0:t.method)?n:"GET").toUpperCase(),r=null==t?void 0:t.body,s=await fetch(e,{...t,headers:(l={Accept:"application/json"},((a="GET"!==i&&"HEAD"!==i)||null!=r)&&(l["Content-Type"]="application/json"),a&&(l["X-Keiko-CSRF"]="1"),l)});if(!s.ok){let{code:e,message:t}=await t4(s);throw new k.hD(e,t,s.status);}return s.json();}async function t5(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t6,n=new URLSearchParams();void 0!==e.scope&&e.scope.length>0&&n.set("scope",e.scope.join(",")),void 0!==e.type&&e.type.length>0&&n.set("type",e.type.join(",")),void 0!==e.status&&e.status.length>0&&n.set("status",e.status.join(",")),void 0!==e.sensitivity&&e.sensitivity.length>0&&n.set("sensitivity",e.sensitivity.join(",")),void 0!==e.limit&&n.set("limit",e.limit.toString()),void 0!==e.offset&&n.set("offset",e.offset.toString());let l=n.toString();return t(`/api/memory${l.length>0?`?${l}`:""}`);}async function t8(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:t6;return e("/api/memory/review-queue");}async function t7(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t6;return t("/api/memory/consolidation/jobs",{method:"POST",body:JSON.stringify({settings:e})});}async function t9(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t6;return t(`/api/memory/consolidation/jobs/${encodeURIComponent(e)}`);}async function ne(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t6;return t(`/api/memory/consolidation/jobs/${encodeURIComponent(e)}/cancel`,{method:"POST",body:"{}"});}async function nt(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t6;return t(`/api/memory/${encodeURIComponent(e)}`);}async function nn(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t6;return n(`/api/memory/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)});}async function nl(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t6;return t(`/api/memory/${encodeURIComponent(e)}/pin`,{method:"POST",body:"{}"});}async function na(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t6;return t(`/api/memory/${encodeURIComponent(e)}/unpin`,{method:"POST",body:"{}"});}async function ni(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t6;return n(`/api/memory/${encodeURIComponent(e)}/archive`,{method:"POST",body:JSON.stringify({...(void 0!==t?{reason:t}:{})})});}async function nr(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t6;return n(`/api/memory/${encodeURIComponent(e)}/forget`,{method:"POST",body:JSON.stringify({acknowledged:!0,...(void 0!==t?{reason:t}:{})})});}async function ns(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t6;return n(`/api/memory/${encodeURIComponent(e)}`,{method:"DELETE",body:JSON.stringify({acknowledged:!0,...(void 0!==t?{reason:t}:{})})});}async function no(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t6;return n(`/api/memory/${encodeURIComponent(e)}/correct`,{method:"POST",body:JSON.stringify({body:t})});}async function nc(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t6;return t(`/api/memory/proposals/${encodeURIComponent(e)}/accept`,{method:"POST",body:"{}"});}async function nd(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t6;return n(`/api/memory/proposals/${encodeURIComponent(e)}/reject`,{method:"POST",body:JSON.stringify({...(void 0!==t?{reason:t}:{})})});}let nu=[{workflowId:"unit-test-generation",label:"Generate unit tests",description:"Drafts a reviewable unit-test patch for a target file. Dry-run only from chat — apply from the workflow view.",prompt:"Target file (workspace-relative)",placeholder:"src/example.ts",buildInput:(e,t)=>({workspaceRoot:e,target:{kind:"file",filePath:t.trim()}})},{workflowId:"bug-investigation",label:"Investigate bug",description:"Investigates a reported issue and proposes a root-cause hypothesis. Dry-run only from chat.",prompt:"Describe the bug",placeholder:"The login button does nothing when the form is empty…",buildInput:(e,t)=>({workspaceRoot:e,report:{description:t.trim()}})}];function np(e){return nu.find(t=>t.workflowId===e);}let nm=new Set(["completed","dry-run","fix-applied","fix-proposed","investigation-only"]);function nh(e){return e.length>200?e.slice(0,200):e;}function nf(e){if(null!==e&&"object"==typeof e)return e;}function ng(){return"Investigation complete; root cause documented.";}function nv(e){let t=e.workflowId;return"unit-test-generation"===t||"unit-tests"===t?"unit-tests":"bug-investigation"===t?"bug":"verify"===e.taskType?"verify":"explain-plan"===e.taskType?"explain":"other";}var nb=n(4503);let nx=[/\bsk-[A-Za-z0-9_-]{12,}\b/g,/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}\b/gi,/\bgho_[A-Za-z0-9_]{12,}\b/g,/\bghp_[A-Za-z0-9_]{12,}\b/g],ny=/\s+\(([A-Z][A-Z0-9_/-]{2,})\)\s*$/;function nw(e){let t=e;for(let e of nx)t=t.replace(e,"[REDACTED]");return t.replace(/\bBearer\s+\[REDACTED\]/gi,"[REDACTED]");}function nj(e,t){return"BAD_REQUEST"===t&&e.toLowerCase().includes("too broad")&&e.toLowerCase().includes("connected");}function nk(e){return"CLARIFICATION_NEEDED"===e;}function nN(e,t,n){return"GATEWAY_TIMEOUT"===t&&(0===e.length||e===t)?"The model gateway timed out before the model returned a response.":e.length>0?e:n;}function nS(e,t){return nk(t)?"Keiko braucht mehr Kontext":nj(e,t)?"Narrow the connected-source question":"GATEWAY_TIMEOUT"===t?"Model gateway timed out":"PAYLOAD_TOO_LARGE"===t?"Request is too large":"NO_MODEL"===t?"No model is available":void 0!==t?"Request failed":"Something went wrong";}function nC(e,t){return nk(t)?"Nenne eine konkrete Datei, einen Identifier, eine Fehlermeldung oder eine exakte Phrase.":nj(e,t)?"Ask about a specific file, folder, symbol, identifier, or exact phrase. For broad questions over large project folders, narrow the Files scope first.":"GATEWAY_TIMEOUT"===t?"Retry the request. If it repeats, choose a smaller prompt or another configured model, then check the gateway base URL, proxy, and model deployment availability in Settings.":"PAYLOAD_TOO_LARGE"===t?"Reduce the selected scope or remove large attachments before retrying.":void 0;}function nI(e,t){if(e instanceof k.hD){let n=nN(nw(e.message.trim()),e.code,t);return`${n} (${e.code})`;}return e instanceof Error&&e.message.trim().length>0?nw(e.message.trim()):t;}let nR="\n…[truncated]",nE=["text/"],n$=new Set(["application/json","application/x-yaml","application/yaml"]),nA=new TextEncoder();function nF(e){return nA.encode(e).length;}function nT(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t>=0?e.slice(t+1):e;}let nD=`${String(256)} KB`;function nq(e){return`"${e}" won't be sent — the ${nD} attachment limit was already used by earlier files.`;}async function nM(e,t){var n,l;let a,i,r,s,o;if(e.remainingAggregate<=0)return nq(nT(t.name));try{a=await t.file.text();}catch{return n=nT(t.name),`Couldn't read "${n}" — it will be skipped. Your message will be sent without it.`;}let c=Math.min(65536,Math.max(e.remainingAggregate-nF(nR),0));if(c<=0)return nq(nT(t.name));let{entry:d,consumed:u}=(r=(i=nF(l=a)>c)?function(e,t){if(t<=0)return"";if(nF(e)<=t)return e;let n=0,l="";for(let a of e){let e=n+nF(a);if(e>t)break;n=e,l+=a;}return l;}(l,c):l,s=nF(r),o=i?nF(nR):0,{entry:{id:t.id,displayName:nT(t.name),mimeType:t.mimeType,sizeBytes:t.sizeBytes,extractedBytes:s,truncated:i,truncationMarker:i?nR:void 0,text:r},consumed:s+o});if(0===d.text.length)return 0===a.length?void 0:nq(nT(t.name));e.entries.push(d),e.remainingAggregate-=u;}async function nP(e){let t=e.filter(e=>{var t;return t=e.mimeType,!!nE.some(e=>t.startsWith(e))||n$.has(t);}),n=t.slice(0,16),l={entries:[],remainingAggregate:262144},a=[];for(let e of n){let t=await nM(l,e);void 0!==t&&a.push(t);}for(let e of t.slice(16)){var i;a.push((i=nT(e.name),`"${i}" won't be sent — only the first ${String(16)} documents are included.`));}return{entries:l.entries,failures:a};}let nL=["text/"],nz=new Set(["application/pdf","application/json","application/x-yaml","application/yaml"]),nO="New chat",nK="keiko:chat-upsert",nB="keiko:chat-delete",nW=["completed","failed","cancelled"];function nU(e){return"idle"!==e&&!nW.includes(e);}let n_="The conversation context exceeded the model's window. Clear history or pick a larger-context model.",nV="The model request completed, but the provider did not return any answer text. Retry once; if it happens again, check the selected model deployment in Settings.",nH=new Set(["CONVERSATION_OVERSIZED_CONTEXT","GATEWAY_CONTEXT_OVERFLOW"]),nJ=["context length","context_length_exceeded","max_tokens","too many tokens"],nY=["empty assistant response","empty grounded answer","without assistant content"];function nX(e){return void 0!==e&&e.contextWindowTokens>0&&"exceeded"===e.pressure;}function nG(e){let t;return function(e){if(e instanceof k.hD&&nH.has(e.code))return!0;let t=e instanceof Error?e.message.toLowerCase():"";return 0!==t.length&&nJ.some(e=>t.includes(e));}(e)?n_:0!==(t=e instanceof Error?e.message.toLowerCase():"").length&&nY.some(e=>t.includes(e))?e instanceof k.hD?`${nV} (${e.code})`:nV:nI(e,"Something went wrong. Try again.");}function nQ(e){return[...e].sort((e,t)=>t.updatedAt-e.updatedAt);}function nZ(e){window.dispatchEvent(new CustomEvent(nK,{detail:e}));}function n0(e){var t;return null==(t=e.find(nb.S_))?void 0:t.id;}function n1(e,t){return void 0!==e&&t.some(t=>t.id===e&&(0,nb.S_)(t))?e:n0(t);}function n2(e){return void 0!==e.connectedScope||void 0!==e.connectedScopes&&e.connectedScopes.length>0||void 0!==e.localKnowledgeScope||void 0!==e.localKnowledgeScopes&&e.localKnowledgeScopes.length>0;}let n3={projects:[],chats:[],messages:[],models:[],activeProject:void 0,activeChat:void 0,selectedModel:void 0};function n4(e,t){if(0===t.length)return Array.from(e);let n=new Map(t.map(e=>[e.id,e])),l=e.map(e=>{var t;return null!=(t=n.get(e.id))?t:e;}),a=new Set(e.map(e=>e.id));for(let e of t)a.has(e.id)||l.push(e);return l;}async function n6(e){var t;let n=(await(0,k.ZC)()).models.filter(nb.S_),l=n0(n),a=[...(await(0,k.vj)().catch(()=>({projects:[]}))).projects].sort((e,t)=>e.favorite!==t.favorite?e.favorite?-1:1:e.lastOpenedAt!==t.lastOpenedAt?t.lastOpenedAt-e.lastOpenedAt:e.path.localeCompare(t.path)),i=null!=(t=a.find(e=>e.available))?t:a[0];if(void 0!==i){let e=nQ((await(0,k.Oz)(i.path).catch(()=>({chats:[]}))).chats),t=e[0];if(void 0!==t){let l=await(0,k.T$)(t.id,i.path),r=n1(t.selectedModel,n);return{models:n,selectedModel:r,projects:Array.from(a),activeProject:i,chats:e,activeChat:t,messages:Array.from(l.messages)};}}if(void 0===l||!e)return{models:n,selectedModel:l,projects:Array.from(a),activeProject:i,chats:[],activeChat:void 0,messages:[]};let r={modelId:l,title:nO};(null==i?void 0:i.available)===!0&&(r.projectPath=i.path);let s=await(0,k.tA)(r);return nZ(s.chat),{models:n,selectedModel:s.chat.selectedModel,projects:Array.from(s.projects),activeProject:s.project,chats:nQ(s.chats),activeChat:s.chat,messages:Array.from(s.messages)};}function n5(){var e,t;let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},l=null==(e=n.autoCreate)||e,[a,r]=(0,i.useState)(n3),[s,o]=(0,i.useState)(""),[c,d]=(0,i.useState)(!0),[u,p]=(0,i.useState)("idle"),m=nU(u),h=(0,i.useRef)("idle"),f=(0,i.useRef)(null),[g,v]=(0,i.useState)(),[b,x]=(0,i.useState)(),[y,w]=(0,i.useState)(),[j,N]=(0,i.useState)(!0),[S,C]=(0,i.useState)(1200),I=(0,i.useRef)(!0),R=(0,i.useRef)(void 0),E=(0,i.useRef)(new Set()),$=(0,i.useRef)(0),A=(0,i.useRef)([]),[F,T]=(0,i.useState)([]),[D,q]=(0,i.useState)([]),M=(0,i.useCallback)(async e=>{var t;let n;if(0===e.size)return{ok:!1,reason:"empty"};if(e.size>8388608)return{ok:!1,reason:"oversized"};let l=(t=e.type).startsWith("image/")?"image":nL.some(e=>t.startsWith(e))||nz.has(t)?"document":"unsupported-type";if("unsupported-type"===l)return{ok:!1,reason:"unsupported-type"};let i=a.models.find(e=>e.id===a.selectedModel);if(void 0!==i&&("image"===l&&!i.supportsImageInput||"document"===l&&!i.supportsDocumentInput))return{ok:!1,reason:"text-only-model"};if("image"===l)try{n=await new Promise((t,n)=>{let l=new FileReader();l.onload=()=>t(l.result),l.onerror=()=>n(Error("FileReader error")),l.readAsDataURL(e);});}catch{return{ok:!1,reason:"unsupported-type"};}let r={id:crypto.randomUUID(),kind:l,name:e.name,mimeType:e.type,sizeBytes:e.size,previewDataUrl:n,file:e};return T(e=>[...e,r]),{ok:!0};},[a.models,a.selectedModel]),P=(0,i.useCallback)(e=>{T(t=>t.filter(t=>t.id!==e));},[]),L=(0,i.useCallback)(()=>{T([]);},[]),z=(0,i.useCallback)(async()=>{let e=F.filter(e=>"document"===e.kind&&void 0!==e.file).map(e=>({id:e.id,name:e.name,mimeType:e.mimeType,sizeBytes:e.sizeBytes,file:e.file}));if(0===e.length)return{entries:[],disclosures:[]};let{entries:t,failures:n}=await nP(e);n.length>0&&v(n.join(" "));let l=t.map(e=>({id:e.id,displayName:e.displayName,truncated:e.truncated}));return{entries:t,disclosures:l};},[F]),O=(0,i.useCallback)(()=>{w(void 0);},[]),K=(0,i.useCallback)((e,t)=>({enabled:j,budgetTokens:S,context:{userId:"local-operator",workspaceId:t.path,projectId:t.path,conversationId:e.id}}),[S,j]),B=(0,i.useCallback)(async e=>{await nc(e),w(t=>void 0===t?t:{...t,actions:t.actions.filter(t=>"candidate"!==t.kind||t.proposalId!==e)});},[]),W=(0,i.useCallback)(async e=>{await nd(e),w(t=>void 0===t?t:{...t,actions:t.actions.filter(t=>"candidate"!==t.kind||t.proposalId!==e)});},[]),U=(0,i.useCallback)(async e=>{await nr(e,"user-initiated forget from Conversation Center"),w(t=>void 0===t?t:{...t,actions:t.actions.filter(t=>"forget"!==t.kind||t.memoryId!==e)});},[]),_=(0,i.useCallback)(e=>{h.current=e,p(e);},[]),V=(0,i.useCallback)(async(e,t,n,l)=>{let a=n.runId;if(void 0===a)return void E.current.delete(l);let i={...(void 0===n.workflowId?{}:{workflowId:n.workflowId}),...(void 0===n.taskType?{}:{taskType:n.taskType})};try{for(let l=0;l<120;l+=1){let s;if(!I.current||R.current!==e.id)return;try{let e=await(0,k.Qe)(a),t=function(e,t){let n=nf(e);if(void 0===n)return{kind:"unknown"};let l=function(e){let t=e.status;if("string"==typeof t)return t;}(n),a=nv(t);return"running"===l?{kind:"running"}:"cancelled"===l?{kind:"terminal",summary:{workflowStatus:"cancelled",shortResult:"Run cancelled."}}:"failed"===l||"rejected"===l?{kind:"terminal",summary:{workflowStatus:"failed",shortResult:nh(function(e){let t,n,l=(t=nf(e.failure),n=null==t?void 0:t.message,"string"==typeof n&&n.length>0?n:void 0);return void 0!==l?nh(`Run failed: ${l}.`):"Run failed.";}(n))}}:void 0!==l&&nm.has(l)?{kind:"terminal",summary:{workflowStatus:"completed",shortResult:nh(function(e,t){if("unit-tests"===t)return function(e){let t,n=e.addedTestFiles;if(Array.isArray(n)){let e=0,l=!1;for(let t of n){let n=nf(t),a=null==n?void 0:n.estimatedTestCount;"number"==typeof a&&Number.isFinite(a)&&(e+=a,l=!0);}l&&(t=e);}let l=Array.isArray(n)?n.length:0;return l>0&&void 0!==t?`Generated ${String(l)} test files; ${String(t)} tests proposed.`:l>0?`Generated ${String(l)} test files.`:"Completed.";}(e);if("bug"===t)return ng();if("verify"===t){let t,n;return t=nf(e.verificationSummary),n=null==t?void 0:t.results,Array.isArray(n)&&n.length>0?`Verification passed: ${String(n.length)} classifications.`:"Verification passed.";}if("explain"===t){let t=e.dryRunPreview;if("string"==typeof t&&t.length>0){let e=t.split("\n").filter(e=>e.trim().length>0);if(e.length>0)return`Plan generated; ${String(e.length)} steps.`;}return"Plan generated.";}return"Completed.";}(n,a))}}:{kind:"unknown"};}(e.report,i);"terminal"===t.kind&&(s=t.summary);}catch(e){if(!(e instanceof k.hD)||404!==e.status)return;try{let e=await(0,k.tZ)(a),t=function(e,t){let n=nf(e),l=void 0===n?void 0:nf(n.run),a=void 0===l?void 0:l.outcome,i=nv(t);return"cancelled"===a?{workflowStatus:"cancelled",shortResult:"Run cancelled."}:"failed"===a||"limit-exceeded"===a?{workflowStatus:"failed",shortResult:"Run failed."}:"completed"===a?{workflowStatus:"completed",shortResult:nh("bug"===i?ng():"verify"===i?"Verification passed.":"explain"===i?"Plan generated.":"unit-tests"===i?"Generated tests.":"Completed.")}:{workflowStatus:"completed",shortResult:"Completed."};}(e.manifest,i);s={workflowStatus:"failed"===t.workflowStatus||"cancelled"===t.workflowStatus?t.workflowStatus:"completed",shortResult:t.shortResult};}catch{}}if(void 0!==s){let l=await(0,k.mj)(n.id,e.id,t,s);if(!I.current||R.current!==e.id)return;r(t=>{var a;return(null==(a=t.activeChat)?void 0:a.id)!==e.id?t:{...t,messages:t.messages.map(e=>e.id===n.id?l.message:e)};});return;}l<119&&(await new Promise(e=>{globalThis.setTimeout(e,1e3);}));}}finally{E.current.delete(l);}},[]);(0,i.useEffect)(()=>{var e;R.current=null==(e=a.activeChat)?void 0:e.id;},[null==(t=a.activeChat)?void 0:t.id]),(0,i.useEffect)(()=>{A.current=a.models;},[a.models]),(0,i.useEffect)(()=>{let e=!1;return async function(){d(!0),v(void 0);try{let t=await n6(l);e||r(e=>({...e,...t}));}catch(t){e||v(nG(t));}finally{e||d(!1);}}(),()=>{e=!0;};},[l]),(0,i.useEffect)(()=>{let e=e=>{let t=e.detail;"object"==typeof t&&null!==t&&"string"==typeof t.id&&"string"==typeof t.projectPath&&"string"==typeof t.title&&"string"==typeof t.selectedModel&&r(e=>{var n,l;return{...e,chats:nQ([t,...e.chats.filter(e=>e.id!==t.id)]),activeChat:(null==(n=e.activeChat)?void 0:n.id)===t.id?t:e.activeChat,selectedModel:(null==(l=e.activeChat)?void 0:l.id)===t.id?n1(t.selectedModel,e.models):e.selectedModel};});},t=e=>{let t=e.detail;"object"==typeof t&&null!==t&&"string"==typeof t.chatId&&r(e=>{var n,l;return{...e,chats:e.chats.filter(e=>e.id!==t.chatId),activeChat:(null==(n=e.activeChat)?void 0:n.id)===t.chatId?void 0:e.activeChat,messages:(null==(l=e.activeChat)?void 0:l.id)===t.chatId?[]:e.messages};});};return window.addEventListener(nK,e),window.addEventListener(nB,t),()=>{window.removeEventListener(nK,e),window.removeEventListener(nB,t);};},[]),(0,i.useEffect)(()=>(I.current=!0,()=>{var e;I.current=!1,null==(e=f.current)||e.abort();}),[]),(0,i.useEffect)(()=>{let e=a.activeChat,t=a.activeProject;if(void 0!==e&&void 0!==t)for(let n of a.messages){if("system"!==n.role||"string"!=typeof n.runId||void 0!==n.workflowStatus&&"pending"!==n.workflowStatus&&"running"!==n.workflowStatus)continue;let l=n.runId;if(void 0===l)continue;let a=`${n.id}:${l}`;E.current.has(a)||(E.current.add(a),V(e,t.path,n,a));}},[a.activeChat,a.activeProject,a.messages,V]);let H=(0,i.useCallback)(e=>{let t;v(void 0),r(n=>(t={selectedModel:n.selectedModel,activeChat:n.activeChat,chats:n.chats},{...n,selectedModel:e,activeChat:void 0===n.activeChat?n.activeChat:{...n.activeChat,selectedModel:e},chats:n.chats.map(t=>void 0!==n.activeChat&&t.id===n.activeChat.id?{...t,selectedModel:e}:t)})),T(t=>t.filter(t=>{let n;return void 0===(n=A.current.find(t=>t.id===e))||("image"===t.kind?n.supportsImageInput:n.supportsDocumentInput);}));let n=R.current;if(void 0===n)return;let l=$.current+1;$.current=l,(0,k.wi)(n,{selectedModel:e}).then(e=>{$.current!==l||R.current===e.chat.id&&(nZ(e.chat),r(t=>{var n;return{...t,selectedModel:e.chat.selectedModel,activeChat:(null==(n=t.activeChat)?void 0:n.id)===e.chat.id?e.chat:t.activeChat,chats:t.chats.map(t=>t.id===e.chat.id?e.chat:t)};}));}).catch(e=>{if($.current===l&&R.current===n&&(v(nG(e)),void 0!==t)){let e=t;r(t=>{var l,a;return{...t,selectedModel:(null==(l=t.activeChat)?void 0:l.id)===n?e.selectedModel:t.selectedModel,activeChat:(null==(a=t.activeChat)?void 0:a.id)===n?e.activeChat:t.activeChat,chats:t.chats.map(t=>{if(t.id!==n)return t;let l=e.chats.find(e=>e.id===n);return void 0!==l?{...t,selectedModel:l.selectedModel}:t;})};});}});},[]),J=(0,i.useCallback)(async(e,t)=>{let n=n1(a.selectedModel,a.models);if(void 0===n)return void v("No conversation-eligible model is configured. Connect a gateway in Settings.");v(void 0);try{var l,i;let s=null==t?void 0:t.trim(),o={modelId:n,title:void 0!==s&&s.length>0?s:nO},c=null!=(l=null==e?void 0:e.path)?l:null==(i=a.activeProject)?void 0:i.path;void 0!==c&&(o.projectPath=c);let d=await(0,k.tA)(o);return R.current=d.chat.id,nZ(d.chat),r({projects:Array.from(d.projects),chats:nQ(d.chats),messages:Array.from(d.messages),models:a.models,activeProject:d.project,activeChat:d.chat,selectedModel:d.chat.selectedModel}),d.chat;}catch(e){v(nG(e));return;}},[a.selectedModel,a.activeProject,a.models]),Y=(0,i.useCallback)(async e=>{v(void 0),r(t=>({...t,activeProject:e}));try{let t=await(0,k.Oz)(e.path),n=nQ(t.chats),l=n[0];if(void 0===l)return void(await J(e));let i=await(0,k.T$)(l.id,e.path);R.current=l.id;let s=n1(l.selectedModel,a.models);r(e=>({...e,chats:n,activeChat:l,selectedModel:s,messages:Array.from(i.messages)})),w(void 0);}catch(e){v(nG(e));}},[J,a.models]),X=(0,i.useCallback)(async e=>{var t;v(void 0),null==(t=f.current)||t.abort(),f.current=null,R.current=e.id,x(void 0),w(void 0),q([]);try{let t=await(0,k.T$)(e.id,e.projectPath),n=n1(e.selectedModel,a.models);r(l=>{let a=l.projects.find(t=>t.path===e.projectPath);return{...l,activeProject:a,activeChat:e,selectedModel:n,messages:Array.from(t.messages)};});}catch(e){v(nG(e));}},[a.models]),G=(0,i.useCallback)(async e=>{let t=e.trim();if(0!==t.length){v(void 0);try{let e=await(0,k.gA)({path:t}),n=await(0,k.vj)();r(e=>({...e,projects:Array.from(n.projects)})),await J(e.project);}catch(e){v(nG(e));}}},[J]),Q=(0,i.useCallback)(e=>{r(t=>({...t,messages:t.messages.filter(t=>t.id!==e)}));},[]),Z=(0,i.useCallback)((e,t,n)=>{let l=!1;return{onToken:t=>{l||(_("streaming"),l=!0),r(n=>({...n,messages:n.messages.map(n=>n.id===e?{...n,content:n.content+t}:n)}));},onDone:l=>{r(n=>({...n,activeChat:l.chat,chats:nQ([l.chat,...n.chats.filter(e=>e.id!==l.chat.id)]),messages:[...n.messages.filter(n=>n.id!==t&&n.id!==e),...Array.from(l.messages)]})),nZ(l.chat),void 0!==l.memory&&w(l.memory),n("completed");},onError:t=>{let{code:l,message:a}=t;v(nG(new k.hD(l,a,0))),Q(e),n("failed");},onCancelled:()=>{Q(e),n("cancelled");}};},[Q,_]),ee=(0,i.useCallback)((e,t,n,l,a,i,s)=>{let o=`stream-${String(Date.now())}`;r(t=>({...t,messages:[...t.messages,{id:o,chatId:e.id,role:"assistant",content:"",timestamp:Date.now(),runId:void 0,workflowId:void 0,workflowStatus:void 0,shortResult:void 0,taskType:void 0}]}));let c={chatId:e.id,projectPath:t.path,content:n,modelId:a,memory:K(e,t),...(s.length>0?{documentContext:s}:{})};return new Promise((e,t)=>{let n=Z(o,l,e);(0,k.nk)(c,i,n).catch(n=>{Q(o),n instanceof k.ZF?t(n):n instanceof DOMException&&"AbortError"===n.name?e("cancelled"):(v(nG(n)),r(e=>({...e,messages:e.messages.filter(e=>e.id!==l)})),e("failed"));});});},[K,Z,Q]),et=(0,i.useCallback)(async(e,t,n,l,a,i,s)=>{try{_("contacting");let o=await(0,k.xp)({chatId:e.id,projectPath:t.path,content:n,modelId:a,memory:K(e,t),...(s.length>0?{documentContext:s}:{})},i);if(i.aborted)return"cancelled";return r(e=>({...e,activeChat:o.chat,chats:nQ([o.chat,...e.chats.filter(e=>e.id!==o.chat.id)]),messages:[...e.messages.filter(e=>e.id!==l),...Array.from(o.messages)]})),nZ(o.chat),w(o.memory),"completed";}catch(n){if(n instanceof DOMException&&"AbortError"===n.name)return"cancelled";v(nG(n));try{let n=await(0,k.T$)(e.id,t.path);r(e=>({...e,messages:Array.from(n.messages)}));}catch{r(e=>({...e,messages:e.messages.filter(e=>e.id!==l)}));}return"failed";}},[K,_]),en=(0,i.useCallback)(async(e,t,n,l,i,r,s)=>{var o;if((null==(o=a.models.find(e=>e.id===i))?void 0:o.streaming)!==!0)return et(e,t,n,l,i,r,s);_("contacting");try{return await ee(e,t,n,l,i,r,s);}catch(e){if(!(e instanceof k.ZF))throw e;}return et(e,t,n,l,i,r,s);},[a.models,et,ee,_]),el=(0,i.useCallback)(async(e,t,n,l,a,i)=>{x(void 0);try{_("contacting");let t=await(0,k.Wk)({chatId:e.id,content:n,modelId:a},i);if(R.current!==e.id)return"completed";if(i.aborted)return"cancelled";x(t),w(void 0);let[l,s]=await Promise.all([(0,k.T$)(e.id,e.projectPath),(0,k.Oz)(e.projectPath)]),o=s.chats.find(t=>t.id===e.id);return r(e=>({...e,messages:Array.from(l.messages),chats:nQ(s.chats),activeChat:null!=o?o:e.activeChat})),void 0!==o&&nZ(o),"completed";}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return"cancelled";return v(nG(e)),r(e=>({...e,messages:e.messages.filter(e=>e.id!==l)})),"failed";}},[_]),ea=(0,i.useCallback)(()=>{var e;nU(h.current)&&(null==(e=f.current)||e.abort(),f.current=null,_("cancelled"));},[_]),ei=(0,i.useCallback)(async()=>{var e,t,n,l;if(nU(h.current))return;let i=s.trim(),c=a.activeChat,d=a.activeProject,u=n1(a.selectedModel,a.models);if(0===i.length||void 0===c||void 0===d||void 0===u)return;if(nX((0,nb.pk)({modelContextWindow:null!=(e=null==(n=a.models.find(e=>e.id===u))?void 0:n.contextWindow)?e:0,modelMaxOutputTokens:null!=(t=null==(l=a.models.find(e=>e.id===u))?void 0:l.maxOutputTokens)?t:0,userDraftText:i,conversationHistory:a.messages.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.content}))})))return void v(n_);if(n2(c)&&F.length>0)return void v("Attachments are not supported for grounded chats. Remove the attachment or switch to a non-grounded chat.");let p={id:`local-${String(Date.now())}`,chatId:c.id,role:"user",content:i,timestamp:Date.now(),runId:void 0,workflowId:void 0,workflowStatus:void 0,shortResult:void 0,taskType:void 0};_("queued"),o(""),v(void 0),r(e=>({...e,messages:[...e.messages,p]}));let m=new AbortController();f.current=m,w(void 0);try{let e=n2(c),{entries:t,disclosures:n}=e?{entries:[],disclosures:[]}:await z(),l=e?await el(c,d,i,p.id,u,m.signal):await en(c,d,i,p.id,u,m.signal,t);"cancelled"===h.current||_(l),"completed"===l&&(L(),q(n));}finally{f.current=null;}},[s,a.activeChat,a.activeProject,a.selectedModel,a.models,a.messages,F,el,en,z,L,_]),er=(0,i.useCallback)(()=>{x(void 0),w(void 0),r(e=>({...e,messages:[]}));},[]),es=(0,i.useMemo)(()=>{let e=a.models.find(e=>e.id===a.selectedModel);if(void 0===e)return;let t=a.messages.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.content})),n=0,l=0;void 0!==b&&(("connected-context"===b.groundingKind||"hybrid"===b.groundingKind)&&(n=("hybrid"===b.groundingKind?b.contextPack.folder:b.contextPack).usage.excerptBytes),("local-knowledge"===b.groundingKind||"hybrid"===b.groundingKind)&&(l=4*("hybrid"===b.groundingKind?b.contextPack.knowledge:b.contextPack).referenceBudget));let i=j&&void 0!==y&&y.context.enabled?y.context.text.length:0;return(0,nb.pk)({modelContextWindow:e.contextWindow,modelMaxOutputTokens:e.maxOutputTokens,userDraftText:s,conversationHistory:t,repoContextPackBytes:n,knowledgeCapsuleBytes:l,memoryContextBytes:i});},[a.models,a.selectedModel,a.messages,s,b,y,j]),eo=(0,i.useCallback)(async e=>{if(nU(h.current))return{ok:!1,reason:"request-failed",message:"A request is already in flight."};let t=e.text.trim();if(0===t.length)return{ok:!1,reason:"missing-input"};let n=a.activeChat,l=a.activeProject;if(void 0===n||void 0===l)return{ok:!1,reason:"missing-chat"};let i=a.models.find(t=>t.id===e.modelId);if(void 0===i||!t_(i))return{ok:!1,reason:"not-workflow-eligible"};let s=np(e.workflowId);if(void 0===s)return{ok:!1,reason:"unknown-workflow"};let o=Date.now(),c=s.buildInput(l.path,t);try{let a=await(0,k.qV)({chatId:n.id,projectPath:l.path,run:{workflowId:e.workflowId,input:c,modelId:e.modelId},user:{content:t,timestamp:o},summary:{content:`Launched: ${s.label}`,timestamp:o+1}});return r(e=>({...e,messages:n4(e.messages,a.messages)})),{ok:!0,runId:a.run.runId};}catch(t){let e=nG(t);return v(e),{ok:!1,reason:"request-failed",message:e};}},[a.activeChat,a.activeProject,a.models]),ec=(0,i.useCallback)(async e=>{if(nU(h.current))return{ok:!1,reason:"request-failed",message:"A request is already in flight."};if(void 0===a.activeChat)return{ok:!1,reason:"missing-chat"};if(0===e.modelId.trim().length)return{ok:!1,reason:"missing-model"};try{let t=await(0,k.Is)({assistantMessageId:e.assistantMessageId,chatId:a.activeChat.id,modelId:e.modelId,workflowKind:e.workflowKind,input:e.input,editablePaths:e.editablePaths,...(void 0===e.expectedChecks?{}:{expectedChecks:e.expectedChecks}),...(void 0===e.unknowns?{}:{unknowns:e.unknowns}),requestedAtMs:Date.now()});return r(e=>({...e,messages:n4(e.messages,t.messages)})),{ok:!0,runId:t.run.runId};}catch(t){let e=nG(t);return v(e),{ok:!1,reason:"request-failed",message:e};}},[a.activeChat]),ed=(0,i.useCallback)(e=>{nZ(e),r(t=>{var n;return{...t,chats:t.chats.map(t=>t.id===e.id?e:t),activeChat:(null==(n=t.activeChat)?void 0:n.id)===e.id?e:t.activeChat};});},[]),eu=(0,i.useCallback)(()=>{v(void 0);},[]);return{projects:a.projects,chats:a.chats,messages:a.messages,models:a.models,activeProject:a.activeProject,activeChat:a.activeChat,selectedModel:a.selectedModel,noEligibleModels:!c&&void 0===n1(a.selectedModel,a.models),draft:s,loading:c,sending:m,sendStatus:u,error:g,clearError:eu,setDraft:o,setSelectedModel:H,openNewChat:J,openProject:Y,openChat:X,addProject:G,sendMessage:ei,cancelSend:ea,replaceChat:ed,latestGrounded:b,cancelGrounded:ea,pendingAttachments:F,addPendingAttachment:M,removePendingAttachment:P,clearPendingAttachments:L,lastSentDocuments:D,budget:es,memoryEnabled:j,setMemoryEnabled:N,memoryBudgetTokens:S,setMemoryBudgetTokens:C,latestMemory:y,clearLatestMemory:O,acceptMemoryCandidate:B,rejectMemoryCandidate:W,forgetMemoryAction:U,clearHistory:er,launchWorkflowFromConversation:eo,launchGroundedWorkflowHandoff:ec};}let n8="keiko.theme",n7="dark",n9=["agent","capsule","capsule-set","chat","connector","data-source","evidence-run","mcp-tool","memory","patch-proposal","skill","tool","workflow-run","workspace-path"],le=["capsule","capsule-set","chat","evidence-run","memory","patch-proposal","tool","workflow-run","workspace-path"],lt=["reads-context","proposes-patch","uses-tool","starts-workflow","produces-evidence","references-document","depends-on"],ln=["draft","active","archived","superseded","revoked","blocked","stale"],ll={"reads-context":{id:"reads-context",displayName:"reads context",semantics:"A consumer endpoint reads the contextual content of the target at a specific point in time.",validSourceKinds:["workflow-run","chat"],validTargetKinds:["memory","capsule","capsule-set","evidence-run","workspace-path","connector","data-source"],cardinality:"N:N",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!1,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"per-endpoint"},"proposes-patch":{id:"proposes-patch",displayName:"proposes patch",semantics:"A workflow run proposes a patch against one or more workspace paths. The relationship records the proposal; diff content stays in the harness PatchProposedEvent.",validSourceKinds:["workflow-run"],validTargetKinds:["workspace-path","patch-proposal"],cardinality:"1:N",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!0,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"fs"},"uses-tool":{id:"uses-tool",displayName:"uses tool",semantics:"A workflow run uses a registered tool. Per-call arguments and results remain in the harness ToolCallRequest / ToolCallResult envelopes.",validSourceKinds:["workflow-run"],validTargetKinds:["tool","mcp-tool"],cardinality:"N:N",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!1,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"tool"},"starts-workflow":{id:"starts-workflow",displayName:"starts workflow",semantics:"A chat or a parent workflow run initiates a workflow run. The relationship records the origin; run identity belongs to the workflow ledger.",validSourceKinds:["chat","workflow-run"],validTargetKinds:["workflow-run"],cardinality:"1:N",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!1,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"per-endpoint"},"produces-evidence":{id:"produces-evidence",displayName:"produces evidence",semantics:"A workflow run produces exactly one durable evidence-run record. If a run produces no evidence, no relationship is recorded.",validSourceKinds:["workflow-run"],validTargetKinds:["evidence-run"],cardinality:"1:1",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!1,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"produces",ownerPackage:"@oscharko-dev/keiko-evidence",trustBoundary:"evidence"},"references-document":{id:"references-document",displayName:"references document",semantics:"A chat or workflow run holds a structural pointer to a document (workspace file or local-knowledge capsule). Distinct from reads-context: a reference is structural, a read is an event.",validSourceKinds:["chat","workflow-run"],validTargetKinds:["workspace-path","capsule","capsule-set"],cardinality:"N:N",direction:"directed",lifecycle:{creatable:!0,immutable:!1,reconnectable:!0,deletable:!0,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"per-endpoint"},"depends-on":{id:"depends-on",displayName:"depends on",semantics:"A capsule, capsule-set, workflow run, or memory depends on another. Used by impact analysis (#542). Self-loops and direct two-edge cycles are forbidden at validation time; transitive cycle detection is deferred to impact traversal.",validSourceKinds:["capsule","capsule-set","workflow-run","memory"],validTargetKinds:["capsule","capsule-set","workflow-run","memory","evidence-run","workspace-path"],cardinality:"N:N",direction:"directed",lifecycle:{creatable:!0,immutable:!1,reconnectable:!0,deletable:!0,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-contracts",trustBoundary:"per-endpoint"}},la=["prompt","documentcontent","filecontent","toolstdout","toolstderr","secret","credential","apikey","password","token"],li="Unable to reach the local backend. Check that the Keiko server is running (keiko ui).";class lr extends Error{constructor(e,t,n,l=[]){super(t),this.name="RelationshipApiError",this.code=e,this.status=n,this.reasons=l;}}async function ls(e){let t;try{t=await e.json();}catch{throw new lr("relationship/parse-error","Response is not valid JSON.",e.status);}if(!e.ok){var n;let l=t,a=null!=(n=l.error)?n:l,i="string"==typeof a.code?a.code:"relationship/unknown-error",r="string"==typeof a.message?a.message:"An unknown error occurred.",s=Array.isArray(l.reasons)?l.reasons:[];throw new lr(i,r,e.status,s);}return t;}function lo(e){let t={"Content-Type":"application/json","X-Keiko-CSRF":"1"};return void 0!==e.idempotencyKey&&(t["Idempotency-Key"]=e.idempotencyKey),void 0!==e.ifMatch&&(t["If-Match"]=e.ifMatch),t;}async function lc(e){let t={schemaVersion:"1",proposal:{type:e.type,source:{kind:e.source.kind,id:e.source.id},target:{kind:e.target.kind,id:e.target.id},...(void 0!==e.summary?{summary:e.summary}:{})}},n=await fetch("/api/relationships/validate",{method:"POST",headers:lo({}),body:JSON.stringify(t)});return{decision:(await ls(n)).decision};}async function ld(e,t){let n={schemaVersion:"1",proposal:{type:e.type,source:{kind:e.source.kind,id:e.source.id},target:{kind:e.target.kind,id:e.target.id},...(void 0!==e.summary?{summary:e.summary}:{})}},l=await fetch("/api/relationships",{method:"POST",headers:lo({idempotencyKey:t}),body:JSON.stringify(n)}),a=await ls(l);return{relationship:a.relationship,etag:a.etag};}async function lu(e){let t=new URLSearchParams();void 0!==e.lifecycle&&t.set("lifecycle",e.lifecycle),void 0!==e.type&&t.set("type",e.type),void 0!==e.sourceKind&&t.set("sourceKind",e.sourceKind),void 0!==e.targetKind&&t.set("targetKind",e.targetKind),void 0!==e.sourceId&&t.set("sourceId",e.sourceId),void 0!==e.targetId&&t.set("targetId",e.targetId),void 0!==e.limit&&t.set("limit",String(e.limit)),void 0!==e.cursor&&t.set("cursor",e.cursor);let n=await fetch(`/api/relationships?${t.toString()}`),l=await ls(n);return{entries:l.entries,truncated:l.truncated,nextCursor:l.nextCursor};}async function lp(e){let t=await fetch(`/api/relationships/${encodeURIComponent(e)}`);return(await ls(t)).relationship;}async function lm(e,t,n,l){let a=await fetch(`/api/relationships/${encodeURIComponent(e)}`,{method:"PATCH",headers:lo({idempotencyKey:l,ifMatch:n}),body:JSON.stringify({schemaVersion:"1",...t})}),i=await ls(a);return{relationship:i.relationship,etag:i.etag};}async function lh(e,t,n){let l=await fetch(`/api/relationships/${encodeURIComponent(e)}`,{method:"DELETE",headers:lo({idempotencyKey:n,ifMatch:t})});return(await ls(l)).relationship;}async function lf(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=new URLSearchParams();void 0!==t.direction&&n.set("direction",t.direction),void 0!==t.maxDepth&&n.set("maxDepth",String(t.maxDepth)),void 0!==t.maxNodes&&n.set("maxNodes",String(t.maxNodes)),void 0!==t.maxRelationships&&n.set("maxRelationships",String(t.maxRelationships));let l=await fetch(`/api/relationships/${encodeURIComponent(e)}/dependencies?${n.toString()}`);return(await ls(l)).report;}async function lg(e){return ls(await fetch(`/api/relationships/${encodeURIComponent(e)}/explain`));}async function lv(){return ls(await fetch("/api/relationships/health"));}let lb=[{key:"t",mod:["cmd"]},{key:"t",mod:["ctrl"]},{key:"r",mod:["cmd"]},{key:"r",mod:["ctrl"]},{key:"n",mod:["cmd","shift"]},{key:"n",mod:["ctrl","shift"]},{key:"w",mod:["cmd"]},{key:"w",mod:["ctrl"]}];function lx(e){switch(e.kind){case"ui.window.move":return"Move window";case"ui.window.resize":return"Resize window";case"ui.window.zorder":return"Reorder window";case"ui.window.close":return"Close window";case"ui.window.open":return"Open window";case"ui.workspace.pan":return"Pan workspace";case"ui.workspace.zoom":return"Zoom workspace";case"ui.workspace.fit":return"Fit workspace to view";case"ui.panel.toggle":return`Toggle ${e.panel} panel`;case"ui.selection.change":return"Change selection";case"ui.tab.switch":return"Switch tab";}}function ly(e){let t=[...e.mod].sort();return`${t.join("+")}|${e.key.toLowerCase()}`;}let lw={undoStack:[],redoStack:[]};class lj extends Error{constructor(e){super(`Workspace keyboard shortcut conflicts detected: ${e.map(e=>`${ly(e.chord)} (${e.commandIds.join(", ")})`).join("; ")}`),this.name="WorkspaceShortcutConflictError",this.conflicts=e;}}class lk extends Error{constructor(e){super(`Workspace keyboard shortcut bindings refused: ${e.map(e=>`${e.commandId} → ${ly(e.chord)}`).join("; ")} are browser-reserved`),this.name="WorkspaceShortcutReservedError",this.reserved=e;}}let lN=[{commandId:"undo",chord:{key:"z",mod:["cmd"]}},{commandId:"redo",chord:{key:"z",mod:["cmd","shift"]}},{commandId:"focus-status",chord:{key:"s",mod:["alt"]}}];var lS=n(82175);let lC="cmp-budget-exceeded-alert",lI={low:"Low",moderate:"Moderate",high:"High",exceeded:"Exceeded"},lR={low:"cmp-budget-badge cmp-budget-badge-low",moderate:"cmp-budget-badge cmp-budget-badge-moderate",high:"cmp-budget-badge cmp-budget-badge-high",exceeded:"cmp-budget-badge cmp-budget-badge-exceeded"},lE="Token counts are approximate. Actual model usage may vary.";function l$(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toString();}function lA(e){let{budget:t,onClearHistory:n,disabled:l,compact:r=!1}=e,[s,o]=(0,i.useState)(!1),[c,d]=(0,i.useState)(!1),u=(0,i.useRef)(null),p=(0,i.useRef)(null);if((0,i.useEffect)(()=>{if(s){var e;null==(e=u.current)||e.focus();}},[s]),void 0===t)return null;let m=t.contextWindowTokens>0,h=l$(t.approximateTokens),f=l$(t.contextWindowTokens),g=t.pressure,v=m&&"exceeded"===g;return(0,a.jsxs)("div",{className:"cmp-budget","data-pressure":m?g:"unknown",children:[(0,a.jsxs)("div",{className:"cmp-budget-row",children:[(0,a.jsx)("span",{className:"cmp-budget-count",children:m?r?`Context: ${h} / ${f}`:`Approximate context: ${h} / ${f} tokens`:r?`Context: ${h}`:`Approximate context: ${h} tokens`}),m?(0,a.jsx)("span",{className:lR[g],"aria-label":`Context pressure: ${lI[g]}`,children:lI[g]}):null,(0,a.jsx)("span",{className:"cmp-budget-info",role:"img",tabIndex:0,"aria-label":lE,"data-tip":lE,children:"i"}),s?(0,a.jsxs)("span",{className:"cmp-budget-confirm",children:[(0,a.jsx)("span",{className:"cmp-budget-confirm-label",id:"cmp-budget-confirm-label",children:"Clear history?"}),(0,a.jsx)("button",{type:"button",ref:u,className:"cmp-budget-clear","aria-describedby":"cmp-budget-confirm-label",onClick:function(){n(),o(!1),d(!0),requestAnimationFrame(()=>{var e;return null==(e=p.current)?void 0:e.focus();});},children:"Clear"}),(0,a.jsx)("button",{type:"button",className:"cmp-budget-clear",onClick:function(){o(!1),requestAnimationFrame(()=>{var e;return null==(e=p.current)?void 0:e.focus();});},children:"Cancel"})]}):(0,a.jsx)("button",{type:"button",ref:p,className:"cmp-budget-clear","aria-label":"Clear conversation history for next prompt",onClick:()=>{d(!1),o(!0);},disabled:!0===l,children:r?"Clear":"Clear history"}),c?(0,a.jsx)("span",{role:"status",className:"cmp-budget-cleared",children:"History cleared for the next prompt — messages remain saved."}):null]}),v?(0,a.jsx)("div",{id:lC,role:"alert",className:"cmp-budget-alert gw-error",children:"Context exceeds the selected model's window. Clear history or pick a model with a larger context."}):null]});}function lF(e){var t,n;let{notice:l,className:r="ui-error-notice",id:s,onDismiss:o}=e,c=`${l.title}
|
|
94
|
-
${l.message}
|
|
95
|
-
${null!=(t=l.code)?t:""}
|
|
96
|
-
${null!=(n=l.remediation)?n:""}`,[d,u]=(0,i.useState)();return d===c?null:(0,a.jsxs)("div",{id:s,className:r,role:"alert","aria-live":"assertive",children:[(0,a.jsxs)("div",{className:"ui-error-notice-title-row",children:[(0,a.jsx)("div",{className:"ui-error-notice-title",children:l.title}),(0,a.jsx)("button",{type:"button",className:"ui-error-notice-close","aria-label":"Dismiss error",title:"Dismiss error",onClick:()=>{u(c),null==o||o();},children:(0,a.jsx)(N.F.close,{size:14})})]}),(0,a.jsx)("div",{className:"ui-error-notice-message",children:l.message}),void 0!==l.remediation?(0,a.jsx)("div",{className:"ui-error-notice-remediation",children:l.remediation}):null,void 0!==l.code?(0,a.jsx)("div",{className:"ui-error-notice-code mono",children:l.code}):null]});}function lT(e){let{error:t,fallback:n,className:l,id:i,onDismiss:r}=e;return(0,a.jsx)(lF,{id:i,className:l,notice:function(e,t){var n;let l;if(e instanceof k.hD){let n=nN(nw(e.message.trim()),e.code,t);return{title:nS(n,e.code),message:n,code:e.code,remediation:nC(n,e.code)};}let a=(n=nw(("string"==typeof e?e.trim():e instanceof Error?e.message.trim():"")||t),null===(l=ny.exec(n))?{message:n,code:void 0}:{message:n.slice(0,l.index).trim(),code:l[1]});return{title:nS(a.message,a.code),message:a.message,code:a.code,remediation:nC(a.message,a.code)};}(t,n),onDismiss:r});}var lD=n(65538);function lq(e){return Number.isFinite(e)?String(e):"—";}function lM(e,t){return Number.isFinite(e)?t(e):"—";}function lP(e){return e.toLocaleString("en-US");}function lL(e){return e.replaceAll("-"," ");}function lz(e){let{label:t,value:n}=e;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("dt",{className:"grounded-context-pack-dt",children:t}),(0,a.jsx)("dd",{className:"grounded-context-pack-dd",children:n})]});}function lO(e){let{contextPack:t}=e,{usage:n,budget:l}=t,i=function(e){if("workspace-root"===e.scopeKind)return"workspace root";let t=e.scopeId.slice(-8);return`${lL(e.scopeKind)} (${t})`;}(t),r="files"===t.scopeKind?`Scope: ${String(t.fileCount)} file${1===t.fileCount?"":"s"} in ${i}`:`Scope: ${i}`;return(0,a.jsxs)("section",{className:"grounded-context-pack","aria-label":"Context inspection summary",children:[(0,a.jsx)("div",{className:"grounded-context-pack-headline",children:r}),(0,a.jsxs)("dl",{className:"grounded-context-pack-dl",children:[(0,a.jsx)(lz,{label:"Searched",value:`${String(n.searchCalls)} / ${lq(l.searchCallsMax)} searches`}),(0,a.jsx)(lz,{label:"Read",value:`${String(n.filesRead)} / ${lq(l.filesReadMax)} files`}),(0,a.jsx)(lz,{label:"Bytes",value:`${(0,lD.z3)(n.excerptBytes)} / ${lM(l.excerptBytesMax,lD.z3)}`}),(0,a.jsx)(lz,{label:"Input",value:`${lP(n.modelInputTokens)} / ${lM(l.modelInputTokensMax,lP)} tokens`}),(0,a.jsx)(lz,{label:"Output",value:`${lP(n.modelOutputTokens)} / ${lM(l.modelOutputTokensMax,lP)} tokens`}),(0,a.jsx)(lz,{label:"Rerank",value:`${String(n.rerankCalls)} / ${lq(l.rerankCallsMax)} calls`}),(0,a.jsx)(lz,{label:"Time",value:`${(0,lD._V)(t.elapsedMs)} / ${lM(l.elapsedMsMax,lD._V)}`}),(0,a.jsx)(lz,{label:"Query",value:lL(t.queryKind)})]})]});}function lK(e){let{score:t}=e;return(0,a.jsxs)("span",{className:"grounded-citation-score",children:[(0,a.jsx)("span",{className:"sr-only",children:"relevance "}),t.toFixed(2)]});}function lB(e){var t;let{citation:n}=e,l=null==(t=n.documentFormat)?void 0:t.toUpperCase();return(0,a.jsxs)("span",{className:"grounded-citation",title:function(e){let t=`relevance ${e.score.toFixed(2)}`,n=void 0===e.documentFormat?"Evidence citation":`${e.documentFormat.toUpperCase()} document evidence (extracted text)`;if(void 0===e.lineRange)return`${n} in ${e.scopePath} — ${t}`;let l=void 0===e.documentFormat?`at lines ${String(e.lineRange.startLine)}-${String(e.lineRange.endLine)}`:`at extracted span ${String(e.lineRange.startLine)}-${String(e.lineRange.endLine)}`;return`${n} in ${e.scopePath} ${l} — ${t}`;}(n),children:[void 0===l?null:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("span",{className:"grounded-citation-doc-badge",children:l}),(0,a.jsx)("span",{className:"sr-only",children:" document evidence extracted text "})]}),(0,a.jsx)("span",{className:"grounded-citation-range",children:void 0===n.lineRange?n.scopePath:`${n.scopePath}:${String(n.lineRange.startLine)}-${String(n.lineRange.endLine)}`}),(0,a.jsx)(lK,{score:n.score})]});}function lW(e){let t=new Set(),n=[];for(let l of e)t.has(l.stableId)||(t.add(l.stableId),n.push(l));return n;}function lU(e){let{total:t,expanded:n,onToggle:l}=e;return t<=8?null:(0,a.jsx)("button",{type:"button",className:"grounded-citations-more","aria-expanded":n,onClick:l,children:n?"Show fewer sources":`Show all ${String(t)} sources`});}function l_(e){let{citations:t}=e,[n,l]=(0,i.useState)(!1);if(0===t.length)return null;let r=lW([...t].sort((e,t)=>t.score-e.score)),s=n?r:r.slice(0,8);return(0,a.jsxs)("div",{className:"grounded-citations-wrap",children:[(0,a.jsx)("span",{className:"grounded-citations-label",children:"Evidence"}),(0,a.jsx)("ul",{className:"grounded-citations","aria-label":"Evidence citations",children:s.map(e=>(0,a.jsx)("li",{className:"grounded-citations-item",children:(0,a.jsx)(lB,{citation:e})},e.stableId))}),(0,a.jsx)(lU,{total:r.length,expanded:n,onToggle:()=>{l(e=>!e);}})]});}function lV(e){let{citations:t}=e,[n,l]=(0,i.useState)(!1);if(0===t.length)return null;let r=lW([...t].sort((e,t)=>t.score-e.score)),s=n?r:r.slice(0,8);return(0,a.jsxs)("div",{className:"grounded-citations-wrap",children:[(0,a.jsx)("span",{className:"grounded-citations-label",children:"Knowledge citations"}),(0,a.jsx)("ul",{className:"grounded-citations","aria-label":"Knowledge citations",children:s.map(e=>(0,a.jsx)("li",{className:"grounded-citations-item",children:(0,a.jsxs)("span",{className:"grounded-citation",title:void 0===e.source?`${e.label} — relevance ${e.score.toFixed(2)}`:`${e.source} \xb7 ${e.label} — relevance ${e.score.toFixed(2)}`,children:[(0,a.jsx)("span",{children:void 0===e.source?`${e.marker} ${e.label}`:`${e.marker} ${e.source} \xb7 ${e.label}`}),(0,a.jsx)(lK,{score:e.score})]})},e.stableId))}),(0,a.jsx)(lU,{total:r.length,expanded:n,onToggle:()=>{l(e=>!e);}})]});}function lH(e){let{markers:t}=e;if(0===t.length)return null;let n=Array.from(new Set(t.map(e=>lL(e.kind)))).join(", ");return(0,a.jsxs)("div",{className:"grounded-uncertainty",role:"note",children:[(0,a.jsx)("div",{children:`Uncertainty (${String(t.length)} markers — ${n})`}),(0,a.jsx)("ul",{className:"grounded-uncertainty-list",children:t.map((e,t)=>(0,a.jsx)("li",{children:`${lL(e.kind)}: ${e.claim}`},`${e.kind}-${String(t)}`))})]});}function lJ(e){let{omittedCount:t,omittedCounts:n}=e;if(t<=0)return null;let l=Object.entries(n).filter(e=>{let[,t]=e;return t>0;}).sort((e,t)=>{let[n]=e,[l]=t;return n<l?-1:+(n>l);}).map(e=>{let[t,n]=e;return`${lL(t)}: ${String(n)}`;}).join(", "),i=l.length>0?` (${l})`:"";return(0,a.jsx)("div",{className:"grounded-meta",children:`Not used: ${String(t)} excerpt${1===t?"":"s"}${i}`});}let lY=[{reason:"size-exceeded",label:"larger than 2 MB"},{reason:"binary",label:"binary or an unsupported format"},{reason:"tool-unavailable",label:"unreadable"},{reason:"unsupported-format",label:"an unsupported document format"},{reason:"no-text-layer",label:"a scanned document with no text layer"},{reason:"malformed-document",label:"a malformed document"},{reason:"encrypted-document",label:"a password-protected document"}];function lX(e){let{omittedCounts:t}=e,n=lY.map(e=>{let{reason:n,label:l}=e;return{label:l,count:t[n]};}).filter(e=>e.count>0),l=n.reduce((e,t)=>e+t.count,0);if(l<=0)return null;let i=n.map(e=>`${String(e.count)} ${e.label}`).join(", "),r=t.binary>0||t["unsupported-format"]>0||t["no-text-layer"]>0||t["malformed-document"]>0||t["encrypted-document"]>0;return(0,a.jsxs)("div",{className:"grounded-coverage-notice",role:"note",children:[(0,a.jsx)("span",{className:"grounded-coverage-notice-title",children:"Partial coverage"}),(0,a.jsx)("span",{children:`This answer reflects only the searchable files in the connected scope — ${String(l)} ${1===l?"file":"files"} ${1===l?"was":"were"} not searched (${i}). It does not cover the entire folder.`}),r?(0,a.jsx)("span",{children:"Repository Search reads text, code, and small DOCX, XLSX, and text-layer PDF documents. Larger, scanned, encrypted, or other document formats remain available through Local Knowledge."}):null]});}function lG(e){let{runId:t,runIds:n}=e,l=Array.from(new Set([...(void 0===t?[]:[t]),...(null!=n?n:[])]));return 0===l.length?null:(0,a.jsx)("div",{className:"grounded-meta",children:l.map((e,t)=>(0,a.jsxs)("a",{className:"sm-link",href:`/api/evidence/${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",children:[1===l.length?"View connected-context audit evidence":`View connected-context audit evidence ${String(t+1)}`," ",(0,a.jsx)("span",{className:"sr-only",children:"(opens in new tab)"})]},e))});}function lQ(e){let{contextPack:t}=e;return(0,a.jsxs)("section",{className:"grounded-context-pack","aria-label":"Knowledge scope summary",children:[(0,a.jsx)("div",{className:"grounded-context-pack-headline",children:`Knowledge scope: ${t.scopeLabel}`}),(0,a.jsxs)("dl",{className:"grounded-context-pack-dl",children:[(0,a.jsx)(lz,{label:"Mode",value:lL(t.scopeKind)}),(0,a.jsx)(lz,{label:"Capsules",value:String(t.capsuleCount)}),(0,a.jsx)(lz,{label:"Sources",value:String(t.sourceCount)}),(0,a.jsx)(lz,{label:"Citations",value:String(t.citationCount)}),(0,a.jsx)(lz,{label:"Context budget",value:`${String(t.referencesUsed)} / ${String(t.referenceBudget)} references`})]})]});}function lZ(e){let{contextPack:t}=e;return(0,a.jsxs)("section",{className:"grounded-context-pack","aria-label":"Hybrid source summary",children:[(0,a.jsx)("div",{className:"grounded-context-pack-headline",children:`Hybrid: ${String(t.folderSourceCount)} folder source${1===t.folderSourceCount?"":"s"} + ${String(t.connectorSourceCount)} connector source${1===t.connectorSourceCount?"":"s"}`}),(0,a.jsx)(lO,{contextPack:t.folder}),(0,a.jsx)(lQ,{contextPack:t.knowledge})]});}function l0(e){let{answer:t,busy:n}=e;return void 0===t?n?(0,a.jsx)("div",{className:"grounded-meta",role:"status","aria-live":"polite","aria-busy":"true",children:"Searching connected sources and asking Keiko…"}):null:"local-knowledge"===t.groundingKind?(0,a.jsxs)("div",{className:"grounded-answer",children:[(0,a.jsx)(lV,{citations:t.citations}),(0,a.jsx)(lH,{markers:t.uncertainty}),(0,a.jsx)(lQ,{contextPack:t.contextPack})]}):"hybrid"===t.groundingKind?(0,a.jsxs)("div",{className:"grounded-answer",children:[(0,a.jsx)(lX,{omittedCounts:t.contextPack.folder.omittedCounts}),(0,a.jsx)(l_,{citations:t.citations}),(0,a.jsx)(lV,{citations:t.knowledgeCitations}),(0,a.jsx)(lH,{markers:t.uncertainty}),(0,a.jsx)(lJ,{omittedCount:t.omittedCount,omittedCounts:t.contextPack.folder.omittedCounts}),(0,a.jsx)(lG,{runId:t.evidenceRunId,runIds:t.evidenceRunIds}),(0,a.jsx)(lZ,{contextPack:t.contextPack})]}):(0,a.jsxs)("div",{className:"grounded-answer",children:[(0,a.jsx)(lX,{omittedCounts:t.contextPack.omittedCounts}),(0,a.jsx)(l_,{citations:t.citations}),(0,a.jsx)(lH,{markers:t.uncertainty}),(0,a.jsx)(lJ,{omittedCount:t.omittedCount,omittedCounts:t.contextPack.omittedCounts}),(0,a.jsx)(lG,{runId:t.evidenceRunId,runIds:t.evidenceRunIds}),(0,a.jsx)(lO,{contextPack:t.contextPack})]});}function l1(e){let{label:t,disabled:n=!1,onStepUp:l,onStepDown:i}=e,r=`Increase ${t}`,s=`Decrease ${t}`;return(0,a.jsxs)("span",{className:"number-control-stepper",children:[(0,a.jsx)("button",{type:"button",className:"number-control-stepper-button number-control-stepper-up","aria-label":r,disabled:n,onPointerDown:e=>{e.preventDefault();},onClick:e=>{e.stopPropagation(),l();}}),(0,a.jsx)("button",{type:"button",className:"number-control-stepper-button number-control-stepper-down","aria-label":s,disabled:n,onPointerDown:e=>{e.preventDefault();},onClick:e=>{e.stopPropagation(),i();}})]});}let l2=["<script","</script","<iframe","</iframe","<object","</object","<embed","</embed","<style","</style","<svg","</svg","<form","</form","<meta","<link","<base"],l3=[" ","\n"," ","'",'"'];function l4(e){var t;let n=function(e){let t=e.toLowerCase().replaceAll("\0",""),n="";for(let e=0;e<t.length;e++){var l;let a=null!=(l=t[e])?l:"";if("<"===a){for(n+="<";e+1<t.length&&(" "===t[e+1]||" "===t[e+1]||"\n"===t[e+1]||"\r"===t[e+1]);)e++;continue;}n+=a;}return n;}(e);for(let e of l2)if(n.includes(e))return!0;let l=0;for(;l<n.length-4;){let e=n[l];if(l3.includes(e)&&"o"===n[l+1]&&"n"===n[l+2]){let e=l+3;for(;e<n.length&&/[a-z]/.test(null!=(t=n[e])?t:"");)e++;if(e<n.length&&"="===n[e])return!0;}l++;}return!1;}function l6(e,t,n,l){l>n&&e.push({kind:"text",text:t.slice(n,l)});}function l5(e){return void 0!==e&&/[A-Za-z0-9]/.test(e);}let l8=new Set([" "," ","\n","<",">",'"']),l7=new Set([".",",",")","]","!","?"]);function l9(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(t>=16)return e.length>0?[{kind:"text",text:e}]:[];let n=[],l=0,a=0;for(;l<e.length;){let i=function(e,t,n,l){if("`"!==t[n])return-1;let a=t.indexOf("`",n+1);return-1===a?-1:(l6(e,t,l,n),e.push({kind:"inline-code",text:t.slice(n+1,a)}),a+1);}(n,e,l,a);if(-1!==i||-1!==(i=function(e,t,n,l,a){let i=t[n],r=t[n+1];if(n+1>=t.length||("*"!==i||"*"!==r)&&("_"!==i||"_"!==r))return-1;let s=t.indexOf(i+r,n+2);if(-1===s)return-1;l6(e,t,l,n);let o=t.slice(n+2,s);return e.push({kind:"strong",children:l9(o,a+1)}),s+2;}(n,e,l,a,t))||-1!==(i=function(e,t,n,l,a){let i=t[n];if("*"!==i&&"_"!==i||"_"===i&&l5(t[n-1])&&l5(t[n+1])||t[n+1]===i||n>0&&t[n-1]===i)return-1;let r=function(e,t,n){for(let l=n;l<e.length;l++)if(e[l]===t&&e[l-1]!==t&&(l+1>=e.length||e[l+1]!==t))return l;return-1;}(t,i,n+1);return-1===r||"_"===i&&l5(t[r-1])&&l5(t[r+1])?-1:(l6(e,t,l,n),e.push({kind:"em",children:l9(t.slice(n+1,r),a+1)}),r+1);}(n,e,l,a,t))||-1!==(i=function(e,t,n,l){let a;if("["!==t[n])return-1;let i=t.indexOf("]",n+1);if(-1===i||"("!==t[i+1])return-1;let r=t.indexOf(")",i+2);if(-1===r)return-1;let s=t.slice(n+1,i),o=t.slice(i+2,r);return l6(e,t,l,n),((a=o.trim().toLowerCase()).startsWith("http://")||a.startsWith("https://"))&&!l4(s)&&!l4(o)?e.push({kind:"link",text:s,href:o}):e.push({kind:"text",text:`[${s}](${o})`}),r+1;}(n,e,l,a))||-1!==(i=function(e,t,n,l){if("h"!==t[n])return-1;let a="https://"===t.slice(n,n+8),i="http://"===t.slice(n,n+7);if(!a&&!i)return-1;let r=function(e,t){var n,l;let a=t;for(;a<e.length&&!l8.has(null!=(n=e[a])?n:"");)a++;for(;a>t&&l7.has(null!=(l=e[a-1])?l:"");)a--;return a;}(t,n);if(r-n<=(a?8:7))return-1;let s=t.slice(n,r);return l6(e,t,l,n),e.push({kind:"link",text:s,href:s}),r;}(n,e,l,a))){a=i,l=i;continue;}l++;}return l6(n,e,a,e.length),n;}function ae(e){let t=e.trim(),n=t.startsWith(":"),l=t.endsWith(":");return n&&l?"center":l?"right":n?"left":void 0;}function at(e){let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|");}function an(e){var t,n,l;let a=/^( *)([*+\-]) (.*)$/.exec(e);return a?{match:!0,indent:null!=(t=null==(l=a[1])?void 0:l.length)?t:0,text:null!=(n=a[3])?n:""}:{match:!1};}function al(e){var t,n,l;let a=/^( *)\d+\. (.*)$/.exec(e);return a?{match:!0,indent:null!=(t=null==(l=a[1])?void 0:l.length)?t:0,text:null!=(n=a[2])?n:""}:{match:!1};}function aa(e){return e.includes("|");}function ai(e){let t=e.trim();return /^(-{3,}|\*{3,}|_{3,})$/.test(t);}function ar(e,t){let n=[],l=t?al:an;for(;e.i<e.lines.length;){var a;let t=null!=(a=e.lines[e.i])?a:"",i=l(t);if(i.match)n.push({text:i.text,indent:i.indent}),e.i++;else if(""===t.trim())break;else break;}return function e(t,n,l){let a=n?"ol":"ul",i=[],r=0;for(;r<t.length;){let a=t[r];if(void 0===a){r++;continue;}let s=a.indent,o=[];for(r++;r<t.length;){let e=t[r];if(void 0===e||e.indent<=s)break;o.push(e),r++;}let c=[...l9(a.text)];o.length>0&&l<16?c.push(e(o,n,l+1)):o.length>0&&c.push({kind:"text",text:o.map(e=>e.text).join("\n")}),i.push({kind:"li",children:c});}return{kind:a,children:i};}(n,t,e.depth);}function as(e){let{text:t}=e,[n,l]=(0,i.useState)(!1),[r,s]=(0,i.useState)(""),o=(0,i.useCallback)(()=>{var e;"u"<typeof navigator||(null==(e=navigator.clipboard)?void 0:e.writeText)===void 0?s("Copy unavailable: the clipboard requires a secure (HTTPS) connection."):navigator.clipboard.writeText(t).then(()=>{l(!0),s("Code copied"),setTimeout(()=>{l(!1),s("");},1500);},()=>{});},[t]);return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("button",{type:"button",className:"sm-code-copy","aria-label":n?"Copied":"Copy code block",title:n?"Copied":"Copy code block","data-copied":n?"true":"false",onClick:o,children:n?"Copied":"Copy"}),(0,a.jsx)("span",{role:"status",className:"sr-only",children:r})]});}let ao={1:"h3",2:"h4",3:"h5",4:"h6",5:"h6",6:"h6"},ac={1:"sm-h sm-h1",2:"sm-h sm-h2",3:"sm-h sm-h3",4:"sm-h sm-h4",5:"sm-h sm-h5",6:"sm-h sm-h6"};function ad(e,t){return void 0===e.children?null:e.children.map((e,n)=>au(e,t+"-"+String(n)));}function au(e,t){let n=function(e,t){var n,l;switch(e.kind){case"paragraph":return(0,a.jsx)("p",{className:"sm-p",children:ad(e,t)},t);case"heading":{let l=null!=(n=e.level)?n:1,i=ao[l],r=ac[l];return(0,a.jsx)(i,{className:r,children:ad(e,t)},t);}case"blockquote":return(0,a.jsx)("blockquote",{className:"sm-blockquote",children:ad(e,t)},t);case"hr":return(0,a.jsx)("hr",{className:"sm-hr"},t);case"code-block":{let n=e.language,i=null!=(l=e.text)?l:"",r=void 0!==n?`lang-${n}`:void 0;return(0,a.jsxs)("div",{className:"sm-code-block-frame",children:[(0,a.jsxs)("div",{className:"sm-code-block-header",children:[(0,a.jsx)("span",{className:"sm-code-lang",children:null!=n?n:"text"}),(0,a.jsx)(as,{text:i})]}),(0,a.jsx)("pre",{className:"sm-pre",children:(0,a.jsx)("code",{className:r,children:i})})]},t);}default:return null;}}(e,t);if(null!==n)return n;let l=function(e,t){switch(e.kind){case"ul":return(0,a.jsx)("ul",{className:"sm-ul",children:ad(e,t)},t);case"ol":return(0,a.jsx)("ol",{className:"sm-ol",children:ad(e,t)},t);case"li":return(0,a.jsx)("li",{className:"sm-li",children:ad(e,t)},t);default:return null;}}(e,t);if(null!==l)return l;let i=function(e,t){let n=void 0!==e.align?{textAlign:e.align}:void 0;switch(e.kind){case"table":return(0,a.jsx)("div",{className:"sm-table-wrapper",children:(0,a.jsx)("table",{className:"sm-table",children:ad(e,t)})},t);case"thead":return(0,a.jsx)("thead",{children:ad(e,t)},t);case"tbody":return(0,a.jsx)("tbody",{children:ad(e,t)},t);case"tr":return(0,a.jsx)("tr",{children:ad(e,t)},t);case"th":return(0,a.jsx)("th",{style:n,children:ad(e,t)},t);case"td":return(0,a.jsx)("td",{style:n,children:ad(e,t)},t);default:return null;}}(e,t);if(null!==i)return i;let r=function(e,t){switch(e.kind){case"text":return(0,a.jsx)("span",{children:e.text},t);case"inline-code":return(0,a.jsx)("code",{className:"sm-inline-code",children:e.text},t);case"link":return(0,a.jsxs)("a",{href:e.href,className:"sm-link",rel:"noopener noreferrer",target:"_blank",children:[e.text,(0,a.jsx)("span",{className:"sr-only",children:" (opens in new tab)"})]},t);case"strong":return(0,a.jsx)("strong",{children:ad(e,t)},t);case"em":return(0,a.jsx)("em",{children:ad(e,t)},t);default:return null;}}(e,t);return null!==r?r:null;}function ap(e){let{source:t}=e,n=function e(t,n){let l=[],a={lines:t.split("\n"),i:0,depth:n};for(;a.i<a.lines.length;)!function(t,n){var l,a;let i=null!=(l=t.lines[t.i])?l:"";if(""===i.trim())return t.i++;if(function(e,t,n){var l;let a=/^(`{3,}|~{3,})(\S*)/.exec(t.trim());if(null===a)return!1;let i=null!=(l=a[1])?l:"```",r=a[2],s=void 0!==r&&r.length>0?r:void 0;return n.push(function(e,t,n){let l=[];for(e.i++;e.i<e.lines.length;){var a,i,r;let n=null!=(a=e.lines[e.i])?a:"",s=/^(`{3,}|~{3,})\s*$/.exec(n.trim());if(null!==s){let n=null!=(i=s[1])?i:"";if(n.startsWith(null!=(r=t[0])?r:"")&&n.length>=t.length){e.i++;break;}}l.push(n),e.i++;}let s={kind:"code-block",text:l.join("\n")};return void 0!==n?{...s,language:n}:s;}(e,i,s)),!0;}(t,i,n)||function(e,t,n){var l,a;let i=/^(#{1,6}) (.+)$/.exec(t.trim());if(null===i)return!1;let r=Math.min((null!=(l=i[1])?l:"").length,6),s=null!=(a=i[2])?a:"";return n.push({kind:"heading",level:r,children:l9(s)}),e.i++,!0;}(t,i,n))return;if(ai(i)){n.push({kind:"hr"}),t.i++;return;}if(i.trimStart().startsWith("> ")||">"===i.trim())return n.push(function(t){let n=[];for(;t.i<t.lines.length;){var l;let e=null!=(l=t.lines[t.i])?l:"";if(e.trimStart().startsWith("> ")||">"===e.trim())n.push(e.replace(/^( *)> ?/,"")),t.i++;else break;}let a=n.join("\n");return t.depth>=16?{kind:"blockquote",children:[{kind:"paragraph",children:[{kind:"text",text:a}]}]}:{kind:"blockquote",children:[...e(a,t.depth+1)]};}(t));if(aa(i.trim())&&function(e){if(0===e.length)return!1;for(let t of e){let e=t.trim().replace(/^:/,"").replace(/:$/,"");if(!/^-+$/.test(e))return!1;}return!0;}(at(null!=(a=t.lines[t.i+1])?a:""))&&(n.push(function(e,t){var n,l;let a,i;e.i++;let r=null!=(n=e.lines[e.i])?n:"",s=[];for(e.i++;e.i<e.lines.length;){let t=null!=(l=e.lines[e.i])?l:"";if(""===t.trim()||!aa(t.trim()))break;s.push(t),e.i++;}return a=at(t),i=at(r).map(ae),{kind:"table",children:[{kind:"thead",children:[{kind:"tr",children:a.map((e,t)=>{var n;let l;return n=i[t],l={kind:"th",children:l9(e.trim())},void 0!==n?{...l,align:n}:l;})}]},{kind:"tbody",children:s.map(e=>({kind:"tr",children:at(e).map((e,t)=>{var n;let l;return n=i[t],l={kind:"td",children:l9(e.trim())},void 0!==n?{...l,align:n}:l;})}))}]};}(t,i)),1)||(an(i).match?(n.push(ar(t,!1)),!0):!!al(i).match&&(n.push(ar(t,!0)),!0)))return;let r=function(e){let t=[];for(;e.i<e.lines.length;){var n;let l=null!=(n=e.lines[e.i])?n:"";if(function(e){let t=e.trim();return!!(""===t||/^#{1,6} /.test(t)||e.trimStart().startsWith("> ")||/^(`{3,}|~{3,})/.test(t))||!!an(e).match||!!al(e).match||ai(e);}(l))break;t.push(l),e.i++;}return 0===t.length?null:{kind:"paragraph",children:l9(t.join(" "))};}(t);null!==r&&n.push(r);}(a,l);return l;}(t,0);return(0,a.jsx)("div",{className:"sm-root",children:n.map((e,t)=>au(e,String(t)))});}class am extends i.Component{static getDerivedStateFromError(){return{failed:!0};}render(){return this.state.failed?(0,a.jsx)("div",{className:"sm-root sm-fallback","data-markdown-fallback":"true",children:this.props.source}):(0,a.jsx)(ap,{source:this.props.source});}constructor(...e){super(...e),this.state={failed:!1};}}function ah(e){var t;let{attachment:n,onRemove:l}=e,i=`Remove attachment ${n.name}`,r=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:32;if(e.length<=t)return e;let n=e.lastIndexOf(".");if(n>0&&e.length-n<=8){let l=e.slice(n);return`${e.slice(0,t-l.length-1)}…${l}`;}return`${e.slice(0,t-1)}…`;}(n.name);return(0,a.jsxs)("div",{className:"attach-chip",role:"listitem",children:["image"===n.kind&&void 0!==n.previewDataUrl?(0,a.jsx)("img",{src:n.previewDataUrl,alt:"",className:"attach-chip-thumb",width:40,height:40}):(0,a.jsx)("span",{className:"attach-chip-icon","aria-hidden":"true",children:(0,a.jsx)(N.F.file,{size:16})}),(0,a.jsx)("span",{className:"attach-chip-name",title:n.name,children:r}),(0,a.jsx)("span",{className:"attach-chip-size",children:(t=n.sizeBytes)<1024?`${String(t)} B`:t<1048576?`${(t/1024).toFixed(1)} KB`:`${(t/1048576).toFixed(1)} MiB`}),(0,a.jsx)("button",{type:"button",className:"attach-chip-remove","aria-label":i,onClick:()=>l(n.id),children:(0,a.jsx)(N.F.close,{size:12})})]});}function af(e){let{attachments:t,onRemove:n}=e;return 0===t.length?null:(0,a.jsx)("div",{className:"attach-strip",role:"list","aria-label":"Pending attachments",children:t.map(e=>(0,a.jsx)(ah,{attachment:e,onRemove:n},e.id))});}function ag(e){let{enabled:t,onFiles:n}=e,[l,r]=(0,i.useState)(!1),[s,o]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!t)return;let e=0,n=t=>{var n,l;Array.from(null!=(n=null==(l=t.dataTransfer)?void 0:l.types)?n:[]).includes("Files")&&(e+=1,o(!0));},l=()=>{0===(e=Math.max(0,e-1))&&o(!1);},a=()=>{e=0,o(!1);};return window.addEventListener("dragenter",n),window.addEventListener("dragleave",l),window.addEventListener("drop",a),window.addEventListener("dragend",a),()=>{window.removeEventListener("dragenter",n),window.removeEventListener("dragleave",l),window.removeEventListener("drop",a),window.removeEventListener("dragend",a);};},[t]);let c=(0,i.useCallback)(e=>{t&&(e.preventDefault(),r(!0));},[t]),d=(0,i.useCallback)(()=>{r(!1);},[]),u=(0,i.useCallback)(e=>{if(e.preventDefault(),r(!1),!t)return;let l=Array.from(e.dataTransfer.files);l.length>0&&n(l);},[t,n]);return t?(0,a.jsx)("div",{className:"attach-drop-zone","data-dragover":l?"true":void 0,"data-active":s?"true":"false","aria-hidden":"true",onDragOver:c,onDragLeave:d,onDrop:u,children:(0,a.jsx)("span",{className:"attach-drop-hint",children:"Drop files here to attach"})}):null;}let av="cmp-attach-disabled-hint";function ab(e){let{model:t,onFiles:n,anyModelSupportsAttachments:l=!0}=e,r=(0,i.useRef)(null),s=void 0!==t&&(t.supportsImageInput||t.supportsDocumentInput),o=function(e){if(void 0===e)return"";let t=[];return e.supportsImageInput&&t.push("image/*"),e.supportsDocumentInput&&t.push(".pdf,.txt,.md,.csv,.json,.yaml,.yml"),t.join(",");}(t),c=(0,i.useCallback)(()=>{var e;s&&(null==(e=r.current)||e.click());},[s]),d=(0,i.useCallback)(()=>{var e,t;let l=Array.from(null!=(e=null==(t=r.current)?void 0:t.files)?e:[]);l.length>0&&(n(l),null!==r.current&&(r.current.value=""));},[n]);return(0,a.jsxs)(a.Fragment,{children:[s?null:(0,a.jsx)("span",{id:av,className:"sr-only",children:l?"The selected model does not support image or document input. Choose a different model to attach files.":"The selected model does not support image or document input. No configured model currently supports attachments."}),(0,a.jsx)("input",{ref:r,type:"file",multiple:!0,accept:o,className:"sr-only",tabIndex:-1,"aria-hidden":"true",onChange:d}),(0,a.jsx)("button",{type:"button",className:"cmp-icon cmp-tip-start","aria-label":"Attach file","aria-disabled":s?void 0:"true","aria-describedby":s?void 0:av,"data-tip":s?"Attach file":"Attachments not supported",onClick:c,children:(0,a.jsx)(N.F.files,{size:16})})]});}function ax(e){let{reason:t,mimeType:n}=e;return void 0===t?null:(0,a.jsx)("div",{role:"alert",className:"attach-rejection-alert",children:function(e,t){switch(e){case"text-only-model":return"The selected model can't accept this attachment type. Choose a model that supports images or documents.";case"unsupported-type":return`Unsupported file type${void 0!==t&&t.length>0?`: ${t}`:""}. Supported types: images (image/*), PDF, plain text, markdown, JSON, YAML.`;case"oversized":return"File is larger than the 8 MiB limit. Choose a smaller file or summarize the content as text.";case"empty":return"Empty file. Add a file with content to attach.";}}(t,n)});}function ay(e){let{documents:t}=e;if(0===t.length)return null;let n=t.some(e=>e.truncated);return(0,a.jsxs)("div",{role:"note",className:"sent-docs-note","aria-label":"Documents included as context",children:[(0,a.jsx)("span",{className:"sent-docs-note-label",children:1===t.length?"Document included as context:":"Documents included as context:"}),(0,a.jsx)("ul",{className:"sent-docs-note-list",children:t.map(e=>(0,a.jsxs)("li",{className:"sent-docs-note-item",children:[e.displayName,e.truncated?(0,a.jsx)("span",{className:"sent-docs-note-trunc",children:" (truncated)"}):null]},e.id))}),n?(0,a.jsx)("span",{className:"sent-docs-note-hint",children:"Some document text was truncated to fit the context limit."}):null]});}function aw(e){let{selectedModel:t,compact:n=!1,launch:l}=e,[r,s]=(0,i.useState)(!1),o=(0,i.useRef)(null);return void 0!==t&&t_(t)?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("button",{ref:o,type:"button",className:`cmp-mode${n?" cmp-mode-compact":" cmp-pill-standard"} ui-tip`,"aria-label":"Launch workflow","aria-haspopup":"dialog","data-tip":n?"Launch workflow":void 0,onClick:()=>s(!0),children:[(0,a.jsx)(N.F.spark,{size:n?16:14,style:{color:"var(--accent)"}}),n?(0,a.jsx)("span",{className:"sr-only",children:"Launch workflow"}):"Launch workflow",n?null:(0,a.jsx)(N.F.chevron,{size:12})]}),r?(0,a.jsx)(ak,{modelId:t.id,launch:l,onClose:()=>{var e;s(!1),null==(e=o.current)||e.focus();}}):null]}):null;}function aj(e){return Array.from(e.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'));}function ak(e){let{modelId:t,launch:n,onClose:l}=e,r=(0,i.useId)(),s=(0,i.useId)(),[o,c]=(0,i.useState)(),[d,u]=(0,i.useState)(""),[p,m]=(0,i.useState)(!1),[h,f]=(0,i.useState)(),g=(0,i.useRef)(null),v=void 0===o?void 0:np(o);async function b(){if(void 0===v||0===d.trim().length)return;m(!0),f(void 0);let e=await n({workflowId:v.workflowId,modelId:t,text:d});(m(!1),e.ok)?l():f(function(e){if(void 0!==e.message&&e.message.length>0)return e.message;switch(e.reason){case"not-workflow-eligible":return"The selected model does not support workflow runs. Pick a model with tool calling and structured output.";case"unknown-workflow":return"That workflow is no longer available.";case"missing-chat":return"Open or create a chat first, then launch the workflow.";case"missing-input":return"Provide an input before launching the workflow.";case"request-failed":return"Could not launch the workflow. Try again, or check the gateway logs.";default:return"Could not launch the workflow.";}}(e));}(0,i.useEffect)(()=>{var e;null==(e=g.current)||e.focus();},[o]),(0,i.useEffect)(()=>{function e(e){if("Escape"===e.key)return void l();if("Tab"!==e.key)return;let t=g.current;if(null===t)return;let n=aj(t);if(0===n.length){e.preventDefault(),t.focus();return;}let a=n[0],i=n[n.length-1],r=document.activeElement;e.shiftKey&&(r===a||r===t)?(e.preventDefault(),null==i||i.focus()):e.shiftKey||r!==i||(e.preventDefault(),null==a||a.focus());}return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e);},[l]);let x=(0,a.jsx)("div",{ref:g,role:"dialog","aria-modal":"true","aria-labelledby":r,tabIndex:-1,className:"wf-dialog-overlay",children:(0,a.jsxs)("div",{className:"wf-dialog",children:[(0,a.jsx)("h2",{id:r,className:"wf-dialog-title",children:"Launch workflow"}),void 0===v?(0,a.jsx)("ul",{className:"wf-dialog-list","aria-label":"Available workflows",children:nu.map(e=>(0,a.jsx)("li",{children:(0,a.jsxs)("button",{type:"button",className:"wf-dialog-choice",onClick:()=>c(e.workflowId),children:[(0,a.jsx)("span",{className:"wf-dialog-choice-label",children:e.label}),(0,a.jsx)("span",{className:"wf-dialog-choice-desc",children:e.description})]})},e.workflowId))}):(0,a.jsxs)("div",{className:"wf-dialog-form",children:[(0,a.jsx)("p",{className:"wf-dialog-form-desc",children:v.description}),(0,a.jsx)("label",{className:"wf-dialog-field",htmlFor:s,children:v.prompt}),(0,a.jsx)("textarea",{id:s,className:"wf-dialog-input mono",rows:3,placeholder:v.placeholder,value:d,onChange:e=>u(e.target.value)}),void 0!==h?(0,a.jsx)("div",{role:"alert",className:"wf-dialog-error",children:h}):null,(0,a.jsxs)("div",{className:"wf-dialog-actions",children:[(0,a.jsx)("button",{type:"button",className:"wf-dialog-cancel",onClick:()=>c(void 0),children:"Back"}),(0,a.jsx)("button",{type:"button",className:"wf-dialog-launch",disabled:p||0===d.trim().length,onClick:()=>{b();},children:p?"Launching…":"Launch"})]})]}),(0,a.jsx)("button",{type:"button",className:"wf-dialog-close","aria-label":"Close launch workflow",onClick:l,children:(0,a.jsx)(N.F.close,{size:14})})]})});return"u"<typeof document?x:(0,tM.createPortal)(x,document.body);}let aN=[{workflowKind:"unit-test-generation",label:"Generate unit tests",description:"Use the grounded evidence as read-only context and propose in-scope test changes."},{workflowKind:"bug-investigation",label:"Investigate bug",description:"Investigate a bug against the grounded evidence and keep writes inside approved paths."},{workflowKind:"verification",label:"Run verification",description:"Run verification against the grounded workspace context without granting write access."}],aS=["verify","lint","typecheck","tests","manual"];function aC(e){return e.split(/\r?\n|,/).map(e=>e.trim()).filter(e=>e.length>0);}function aI(e){let{answer:t,modelId:n,busy:l,launch:r}=e,[s,o]=(0,i.useState)(!1),c=(0,i.useRef)(null),d=(0,i.useId)();if(void 0===t||"connected-context"!==t.groundingKind||void 0===n||t.citations.some(e=>void 0!==e.source))return null;let u=!0===l;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("button",{ref:c,type:"button",className:"cmp-mode ui-tip","data-tip":"Launch grounded workflow","aria-haspopup":"dialog","aria-disabled":u||void 0,"aria-describedby":u?d:void 0,onClick:()=>{u||o(!0);},children:[(0,a.jsx)(N.F.spark,{size:14,style:{color:"var(--accent)"}})," Launch grounded workflow",(0,a.jsx)(N.F.chevron,{size:12})]}),u?(0,a.jsx)("span",{className:"sr-only",id:d,children:"A run is in progress. Wait for it to complete before launching another grounded workflow."}):null,s?(0,a.jsx)(aR,{answer:t,modelId:n,launch:r,onClose:()=>{var e;o(!1),null==(e=c.current)||e.focus();}}):null]});}function aR(e){let{answer:t,modelId:n,launch:l,onClose:r}=e,s=(0,i.useId)(),o=(0,i.useRef)(null),[c,d]=(0,i.useState)(),[u,p]=(0,i.useState)("file"),[m,h]=(0,i.useState)(""),[f,g]=(0,i.useState)(""),[v,b]=(0,i.useState)(""),[x,y]=(0,i.useState)(""),[w,j]=(0,i.useState)(""),[k,S]=(0,i.useState)(""),[C,I]=(0,i.useState)([]),[R,E]=(0,i.useState)(!1),[$,A]=(0,i.useState)();async function F(){if(void 0===c)return;let e=function(e,t,n,l,a,i){if("unit-test-generation"===e){if("changedFiles"===t){let e=aC(n);return 0===e.length?{ok:!1,message:"Provide at least one changed file."}:{ok:!0,input:{target:{kind:"changedFiles",filePaths:e}}};}let e=n.trim();return 0===e.length?{ok:!1,message:"module"===t?"Provide a module directory.":"Provide a target file."}:"module"===t?{ok:!0,input:{target:{kind:"module",moduleDir:e}}}:{ok:!0,input:{target:{kind:"file",filePath:e}}};}if("bug-investigation"===e){let e=aC(a),t=l.trim();return 0===t.length&&0===e.length?{ok:!1,message:"Provide at least a bug description or one suspected target file."}:{ok:!0,input:{report:{...(0===t.length?{}:{description:t}),...(0===e.length?{}:{targetFiles:e})}}};}let r=aC(i);return{ok:!0,input:0===r.length?{}:{targetFiles:r}};}(c,u,m,f,v,x);if(!e.ok)return void A(e.message);if(0===C.length)return void A("Select at least one expected check.");E(!0),A(void 0);let a=await l({assistantMessageId:t.assistantMessageId,modelId:n,workflowKind:c,input:e.input,editablePaths:aC(w),expectedChecks:C,unknowns:aC(k)});(E(!1),a.ok)?r():A(function(e){if(e.ok)return"";if(void 0!==e.message&&e.message.length>0)return e.message;switch(e.reason){case"missing-chat":return"Open a chat with the grounded answer you want to hand off.";case"missing-model":return"Pick a model before launching the grounded workflow.";default:return"Could not launch the grounded workflow.";}}(a));}(0,i.useEffect)(()=>{var e;null==(e=o.current)||e.focus();},[c]),(0,i.useEffect)(()=>{void 0!==c&&I("unit-test-generation"===c?["tests"]:["verify"]);},[c]),(0,i.useEffect)(()=>{function e(e){if("Escape"===e.key)return void r();if("Tab"!==e.key)return;let t=o.current;if(null===t)return;let n=aj(t);if(0===n.length){e.preventDefault(),t.focus();return;}let l=n[0],a=n[n.length-1],i=document.activeElement;e.shiftKey&&(i===l||i===t)?(e.preventDefault(),null==a||a.focus()):e.shiftKey||i!==a||(e.preventDefault(),null==l||l.focus());}return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e);},[r]);let T=aN.find(e=>e.workflowKind===c),D=(0,a.jsx)("div",{ref:o,role:"dialog","aria-modal":"true","aria-labelledby":s,tabIndex:-1,className:"wf-dialog-overlay",children:(0,a.jsxs)("div",{className:"wf-dialog",children:[(0,a.jsx)("h2",{id:s,className:"wf-dialog-title",children:"Grounded workflow handoff"}),void 0===T?(0,a.jsx)("ul",{className:"wf-dialog-list","aria-label":"Available grounded workflows",children:aN.map(e=>(0,a.jsx)("li",{children:(0,a.jsxs)("button",{type:"button",className:"wf-dialog-choice",onClick:()=>d(e.workflowKind),children:[(0,a.jsx)("span",{className:"wf-dialog-choice-label",children:e.label}),(0,a.jsx)("span",{className:"wf-dialog-choice-desc",children:e.description})]})},e.workflowKind))}):(0,a.jsxs)("div",{className:"wf-dialog-form",children:[(0,a.jsx)("p",{className:"wf-dialog-form-desc",children:T.description}),"unit-test-generation"===c?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"wf-dialog-field",children:[(0,a.jsx)("span",{children:"Target mode"}),(0,a.jsx)(tB,{triggerClassName:"wf-dialog-input mono",value:u,ariaLabel:"Target mode",menuTitle:"Target mode",mono:!0,sections:[{options:[{value:"file",label:"File"},{value:"module",label:"Module"},{value:"changedFiles",label:"Changed files"}]}],onValueChange:e=>p(e)})]}),(0,a.jsxs)("label",{className:"wf-dialog-field",children:["module"===u?"Module directory":"changedFiles"===u?"Changed files (one per line)":"Target file",(0,a.jsx)("textarea",{className:"wf-dialog-input mono",rows:"changedFiles"===u?3:2,value:m,onChange:e=>h(e.target.value),placeholder:"module"===u?"src/components":"changedFiles"===u?"src/a.ts\nsrc/b.ts":"src/example.ts"})]})]}):null,"bug-investigation"===c?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("label",{className:"wf-dialog-field",children:["Bug description",(0,a.jsx)("textarea",{className:"wf-dialog-input mono",rows:3,value:f,onChange:e=>g(e.target.value),placeholder:"Describe the failing behavior or regression."})]}),(0,a.jsxs)("label",{className:"wf-dialog-field",children:["Suspected target files (one per line)",(0,a.jsx)("textarea",{className:"wf-dialog-input mono",rows:2,value:v,onChange:e=>b(e.target.value),placeholder:"src/app.ts\\nsrc/lib/foo.ts"})]})]}):null,"verification"===c?(0,a.jsxs)("label",{className:"wf-dialog-field",children:["Target files (optional, one per line)",(0,a.jsx)("textarea",{className:"wf-dialog-input mono",rows:2,value:x,onChange:e=>y(e.target.value),placeholder:"src/app.ts\\nsrc/lib/foo.ts"})]}):null,(0,a.jsxs)("label",{className:"wf-dialog-field",children:["Editable paths (explicit, workspace-relative, one per line)",(0,a.jsx)("textarea",{className:"wf-dialog-input mono",rows:3,value:w,onChange:e=>j(e.target.value),placeholder:"src/example.test.ts"})]}),(0,a.jsxs)("fieldset",{className:"wf-dialog-field",style:{border:0,padding:0,margin:0},children:[(0,a.jsx)("legend",{children:"Expected checks"}),(0,a.jsx)("div",{className:"wf-dialog-form",style:{gap:8},children:aS.map(e=>(0,a.jsxs)("label",{className:"c-check",children:[(0,a.jsx)("input",{type:"checkbox",checked:C.includes(e),onChange:()=>{I(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]);}}),(0,a.jsx)("span",{className:"bx","aria-hidden":"true",children:(0,a.jsx)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:3,strokeLinecap:"round",strokeLinejoin:"round",children:(0,a.jsx)("path",{d:"M5 12.5 L10 17.5 L19 6.5"})})}),(0,a.jsx)("span",{children:e})]},e))})]}),(0,a.jsxs)("label",{className:"wf-dialog-field",children:["Unknowns (optional, one per line)",(0,a.jsx)("textarea",{className:"wf-dialog-input mono",rows:2,value:k,onChange:e=>S(e.target.value),placeholder:"Need confirmation on public API behavior"})]}),void 0!==$?(0,a.jsx)("div",{role:"alert",className:"wf-dialog-error",children:$}):null,(0,a.jsxs)("div",{className:"wf-dialog-actions",children:[(0,a.jsx)("button",{type:"button",className:"wf-dialog-cancel",onClick:()=>d(void 0),children:"Back"}),(0,a.jsx)("button",{type:"button",className:"wf-dialog-launch",disabled:R,onClick:()=>{F();},children:R?"Launching…":"Launch"})]})]}),(0,a.jsx)("button",{type:"button",className:"wf-dialog-close","aria-label":"Close grounded workflow handoff",onClick:r,children:(0,a.jsx)(N.F.close,{size:14})})]})});return"u"<typeof document?D:(0,tM.createPortal)(D,document.body);}function aE(e){return"system"===e.role&&"string"==typeof e.runId;}function a$(e){var t,n,l;let{message:r,onOpenResult:s}=e,o=null!=(t=r.workflowStatus)?t:"queued",c=null!=(n=null!=(l=r.workflowId)?l:r.taskType)?n:"workflow",d=void 0===r.runId?"":r.runId.slice(0,8),u=void 0===r.runId?void 0:`/api/evidence/${encodeURIComponent(r.runId)}`,[p,m]=(0,i.useState)(""),h=(0,i.useRef)(o);return(0,i.useEffect)(()=>{h.current!==o&&(h.current=o,m(`Workflow ${c}: ${o}`));},[o,c]),(0,a.jsxs)("article",{className:"run-summary-card","data-testid":"run-summary-card","data-status":o,"aria-label":`Workflow run ${c} — ${o}`,children:[(0,a.jsxs)("header",{className:"run-summary-card-head",children:[(0,a.jsx)(N.F.spark,{size:14,style:{color:"var(--accent)"}}),(0,a.jsx)("span",{className:"run-summary-card-workflow mono",children:c}),(0,a.jsx)("span",{className:"run-summary-card-status","data-status":o,children:o})]}),(0,a.jsxs)("div",{className:"run-summary-card-body",children:[(0,a.jsx)("p",{className:"run-summary-card-line",children:r.content}),void 0!==r.shortResult&&r.shortResult.length>0?(0,a.jsx)("p",{className:"run-summary-card-result",children:r.shortResult}):null,void 0!==r.runId?(0,a.jsxs)("p",{className:"run-summary-card-meta mono",children:["run"," ",(0,a.jsx)("span",{className:"run-summary-card-runshort","data-runid":r.runId,title:r.runId,children:d})]}):null,void 0!==r.runId?(0,a.jsxs)("div",{className:"run-summary-card-actions","aria-label":"Workflow result actions",children:[void 0!==s?(0,a.jsx)("button",{type:"button",className:"run-summary-card-action",onClick:()=>s(r),children:"Open result"}):null,void 0!==u?(0,a.jsx)("a",{className:"run-summary-card-action run-summary-card-action-secondary",href:u,target:"_blank",rel:"noreferrer",children:"Evidence"}):null]}):null]}),(0,a.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","data-testid":"run-summary-card-sr",children:p})]});}function aA(e){let{on:t,onChange:n,label:l}=e;return(0,a.jsx)("button",{type:"button",role:"switch","aria-checked":t,"aria-label":l,className:`auto-toggle${t?" on":""}`,onClick:()=>{n(!t);},children:(0,a.jsx)("span",{})});}var aF=n(29464);let aT="cmp-no-model-alert",aD="cmp-send-hint",aq="cmp-loading-status",aM="Ask Keiko...",aP=/\s*[[【[]\d+[\]】]]/g;function aL(e){let{content:t}=e,[n,l]=(0,i.useState)(!1),[r,s]=(0,i.useState)(""),o=(0,i.useCallback)(()=>{var e;"u"<typeof navigator||(null==(e=navigator.clipboard)?void 0:e.writeText)===void 0?s("Copy unavailable: the clipboard requires a secure (HTTPS) connection."):navigator.clipboard.writeText(t.replace(aP,"")).then(()=>{l(!0),s("Message copied"),setTimeout(()=>{l(!1),s("");},1500);},()=>{});},[t]);return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("button",{type:"button",className:"chat-msg-copy ui-tip","aria-label":n?"Copied":"Copy message","data-tip":n?"Copied":"Copy message","data-copied":n?"true":"false",onClick:o,children:n?"Copied":"Copy"}),(0,a.jsx)("span",{role:"status",className:"sr-only",children:r})]});}function az(e){let t,n,{message:l,onOpenRunResult:i,streaming:r=!1}=e;if(aE(l))return(0,a.jsx)(a$,{message:l,onOpenResult:i});let s="user"===l.role;return(0,a.jsx)("article",{className:"chat-msg","data-role":l.role,children:(0,a.jsxs)("div",{className:"chat-msg-bubble",children:[s?(0,a.jsx)("div",{className:"chat-msg-role",children:"You"}):(0,a.jsx)(aO,{}),s?l.content:(0,a.jsx)(am,{source:l.content}),r&&!s?(0,a.jsx)("span",{className:"ai-stream-cursor","aria-hidden":"true"}):null,(0,a.jsxs)("div",{className:"chat-msg-foot",children:[(0,a.jsx)("div",{className:"chat-msg-time",title:new Date(l.timestamp).toLocaleString(),children:(n=(t=new Date(l.timestamp)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t.toDateString()===new Date().toDateString()?n:`${t.toLocaleDateString([],{month:"short",day:"numeric"})}, ${n}`)}),s?null:(0,a.jsx)(aL,{content:l.content})]})]})});}function aO(e){let{pulsing:t=!1}=e;return(0,a.jsx)("div",{className:"chat-msg-brand","data-pulsing":t?"true":"false",role:"img","aria-label":"Keiko logo",children:(0,a.jsx)(lS.default,{src:"/assets/keiko-logo.svg",width:22,height:22,alt:"","aria-hidden":"true"})});}function aK(){return(0,a.jsx)("article",{className:"chat-msg","data-role":"assistant",children:(0,a.jsxs)("div",{className:"chat-msg-bubble",children:[(0,a.jsx)(aO,{pulsing:!0}),(0,a.jsxs)("span",{className:"chat-typing",role:"img","aria-label":"Keiko is responding",children:[(0,a.jsx)("i",{}),(0,a.jsx)("i",{}),(0,a.jsx)("i",{})]})]})});}function aB(e){let{session:t,ready:n,selectedModelCapability:l,onAttachFiles:i,compact:r=!1,controlsNarrow:s=!1,barCompact:o=!1,workflowCompact:c=!1,budgetExceeded:d}=e,{models:u,selectedModel:p,setSelectedModel:m,draft:h,noEligibleModels:f,loading:g,sending:v,cancelSend:b,launchWorkflowFromConversation:x}=t,y=f||d||!n,w=0===h.trim().length,j=f?aT:void 0,k=f?aT:d?lC:g?aq:w?aD:void 0,S=g||f?"":null!=p?p:"",C=g?"Loading models…":f?"No conversation-eligible model":"Change model";return(0,a.jsxs)("div",{className:`cmp-bar${o?" cmp-bar-compact":""}`,children:[(0,a.jsxs)("div",{className:"cmp-bar-main",children:[(0,a.jsx)(ab,{model:l,onFiles:i,anyModelSupportsAttachments:u.some(e=>e.supportsImageInput||e.supportsDocumentInput)}),(0,a.jsx)(aw,{selectedModel:l,compact:c,launch:x}),(0,a.jsx)("div",{className:`cmp-model mono ui-tip${s?" cmp-model-compact":" cmp-pill-standard"}`,"data-tip":s?C:void 0,children:(0,a.jsx)(tB,{triggerClassName:"cmp-model-select",value:S,ariaLabel:"Models",ariaDescribedBy:j,disabled:g,placeholder:g?"Loading models…":f?"No conversation-eligible model":"Models",leadingVisual:(0,a.jsx)(N.F.cube,{size:s?16:13,style:{color:"var(--accent)"}}),menuTitle:"Models",menuClassName:"cmp-model-menu",menuMinWidth:s?118:280,mono:!0,sections:[{options:g?[{value:"",label:"Loading models…",disabled:!0}]:f?[{value:"",label:"No conversation-eligible model",disabled:!0}]:u.filter(e=>"chat"===e.kind).map(e=>({value:e.id,label:e.id}))}],onValueChange:e=>{f||g||m(e);}})}),null]}),k===aD?(0,a.jsx)("span",{id:aD,className:"sr-only",children:"Type a message to send"}):null,v?(0,a.jsx)("button",{type:"button",className:"cmp-send cmp-send-cancel cmp-tip-end","data-on":!0,"aria-label":"Cancel response","data-tip":"Cancel response",onClick:b,children:(0,a.jsx)(N.F.close,{size:16})}):(0,a.jsx)("button",{type:y?"button":"submit",className:"cmp-send cmp-tip-end","data-on":!y,"data-tip":f?"No model available":d?"Context too large":g?"Connecting to gateway":"Send message","aria-disabled":y,"aria-describedby":k,"aria-label":"Send message",children:(0,a.jsx)(N.F.arrowUp,{size:16})})]});}function aW(){return(0,a.jsx)("div",{id:aT,role:"alert",className:"gw-error cmp-no-model",children:"No conversation-eligible model is configured. Connect a gateway in Settings to enable chat."});}function aU(){return(0,a.jsxs)("div",{id:aq,role:"status",className:"cmp-loading-status",children:[(0,a.jsx)("span",{className:"cmp-loading-dot","aria-hidden":"true"}),"Connecting to your gateway…"]});}function a_(e){let{status:t}=e,n=function(e){switch(e){case"idle":case"completed":case"failed":return"";case"queued":return"Submitting your message…";case"contacting":return"Contacting model…";case"streaming":return"Receiving response…";case"cancelled":return"Response cancelled.";}}(t);return(0,a.jsx)("div",{role:"status","aria-live":"polite","data-send-status":t,className:"cmp-send-status",children:0===n.length?null:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("span",{className:"cmp-loading-dot","aria-hidden":"true"}),n]})});}function aV(e){let{session:t,ready:n,placeholder:l,minimal:r=!1,compact:s=!1,controlsNarrow:o=!1,barCompact:c=!1,workflowCompact:d=!1}=e,{draft:u,loading:p,sending:m,sendStatus:h,setDraft:f,sendMessage:g,models:v,selectedModel:b,pendingAttachments:x,addPendingAttachment:y,removePendingAttachment:w,budget:j,clearHistory:k}=t,N=nX(j),S=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=S.current;null!==e&&(e.style.height="auto",e.style.height=`${String(Math.min(e.scrollHeight,220))}px`);},[u]);let[C,I]=(0,i.useState)(),[R,E]=(0,i.useState)(),$=v.find(e=>e.id===b),A=void 0!==$&&($.supportsImageInput||$.supportsDocumentInput),F=(0,i.useCallback)(async e=>{let t,n;for(let l of e){let e=await y(l);e.ok||void 0!==t||(t=e.reason,n=l.type);}I(t),E(n);},[y]);return(0,a.jsxs)("div",{className:`cmp-box${s?" cmp-box-compact":""}`,children:[(0,a.jsxs)("div",{className:"cmp-input-stack",children:[(0,a.jsx)(ag,{enabled:A,onFiles:F}),(0,a.jsx)("textarea",{className:"cmp-input",ref:S,rows:2,value:u,"aria-label":"Chat message",placeholder:l,onChange:e=>f(e.target.value),onKeyDown:e=>{!e.nativeEvent.isComposing&&("Enter"!==e.key||e.shiftKey||(e.preventDefault(),g()));}}),(0,a.jsx)(af,{attachments:x,onRemove:w}),(0,a.jsx)(ax,{reason:C,mimeType:R}),(0,a.jsx)(a_,{status:h})]}),(0,a.jsxs)("div",{className:"cmp-footer-row",children:[r?null:(0,a.jsx)(lA,{budget:j,onClearHistory:k,disabled:m||p,compact:s}),(0,a.jsx)(aB,{session:t,ready:n,selectedModelCapability:$,onAttachFiles:F,compact:s,controlsNarrow:o,barCompact:c,workflowCompact:d,budgetExceeded:N})]})]});}function aH(e){let{minimal:t=!1}=e;return t?(0,a.jsx)("div",{className:"chatw-empty chatw-empty-minimal",role:"note","aria-label":"Conversation ready",children:(0,a.jsx)("h2",{className:"chatw-empty-headline",children:"How can I help you today?"})}):(0,a.jsx)("div",{className:"chatw-empty",children:(0,a.jsx)("h2",{className:"chatw-empty-headline",children:"How can I help you today?"})});}function aJ(){return(0,a.jsxs)("div",{className:"chatw-empty-no-chat",children:[(0,a.jsx)("div",{className:"chatw-empty-no-chat-icon","aria-hidden":"true",children:(0,a.jsx)(N.F.spark,{size:20})}),(0,a.jsx)("p",{className:"chatw-empty-no-chat-label",children:"Pick or start a chat"}),(0,a.jsx)("p",{className:"chatw-empty-no-chat-hint",children:"Select a conversation from the project sidebar, or create a new one to get started."})]});}function aY(e){return(void 0!==e.connectedScopes?e.connectedScopes.length:+(void 0!==e.connectedScope))+(void 0!==e.localKnowledgeScopes?e.localKnowledgeScopes.length:+(void 0!==e.localKnowledgeScope));}function aX(e){var t,n;if(aY(e)>1)return"multi";let l=null!=(t=null==(n=e.localKnowledgeScopes)?void 0:n[0])?t:e.localKnowledgeScope;return(null==l?void 0:l.kind)==="capsule"?`capsule:${l.capsuleId}`:(null==l?void 0:l.kind)==="capsule-set"?`capsule-set:${l.capsuleSetId}`:aQ(e)?"files":"none";}function aG(e){return void 0!==e.localKnowledgeScopes?e.localKnowledgeScopes:void 0!==e.localKnowledgeScope?[e.localKnowledgeScope]:[];}function aQ(e){return void 0!==e&&(void 0!==e.connectedScope||void 0!==e.connectedScopes&&e.connectedScopes.length>0);}function aZ(e){return aQ(e)||void 0!==e&&(void 0!==e.localKnowledgeScope||void 0!==e.localKnowledgeScopes&&e.localKnowledgeScopes.length>0);}function a0(e){return nI(e,"Unable to update knowledge scope.");}function a1(e){let{chat:t,onChatChanged:n,catalog:l,connected:r}=e,{capsules:s,capsuleSets:o,loadError:c}=l,[d,u]=(0,i.useState)(!1),[p,m]=(0,i.useState)(null);async function h(e){u(!0),m(null);try{if("none"===e){let e=aY(t);if(e>0&&!window.confirm(`This will disconnect ${String(e)} grounding ${1===e?"source":"sources"}. Continue?`))return;let l=await(0,k.wi)(t.id,{connectedScopes:null,localKnowledgeScopes:null});n(l.chat);return;}if("files"===e){let e=await(0,k.wi)(t.id,{localKnowledgeScopes:null});n(e.chat);return;}if(e.startsWith("capsule-set:")){let l={kind:"capsule-set",capsuleSetId:e.slice(12),connectedAtMs:Date.now()},a=aG(t),i=a.some(e=>"capsule-set"===e.kind&&e.capsuleSetId===l.capsuleSetId)?a:[...a,l],r=await(0,k.wi)(t.id,{localKnowledgeScopes:i});n(r.chat);return;}if(e.startsWith("capsule:")){let l={kind:"capsule",capsuleId:e.slice(8),connectedAtMs:Date.now()},a=aG(t),i=a.some(e=>"capsule"===e.kind&&e.capsuleId===l.capsuleId)?a:[...a,l],r=await(0,k.wi)(t.id,{localKnowledgeScopes:i});n(r.chat);}}catch(e){m(a0(e));}finally{u(!1);}}let f=aX(t),g=function(e,t){let n=t.map(e=>({value:`capsule:${e.id}`,label:`Knowledge capsule: ${e.displayName}`})),l=aX(e);if(!l.startsWith("capsule:")||n.some(e=>e.value===l))return n;let a=l.slice(8);return[...n,{value:l,label:`Knowledge capsule: ${a} (unavailable)`}];}(t,s),v=function(e,t){let n=t.map(e=>({value:`capsule-set:${e.id}`,label:`Capsule set: ${e.displayName}`})),l=aX(e);if(!l.startsWith("capsule-set:")||n.some(e=>e.value===l))return n;let a=l.slice(12);return[...n,{value:l,label:`Capsule set: ${a} (unavailable)`}];}(t,o),b=null!=p?p:c;return(0,a.jsxs)("div",{className:"scope-grounding","data-connected":r?"true":"false",children:[(0,a.jsx)("span",{className:"scope-grounding-label mono",children:"Grounding"}),(0,a.jsx)(tB,{triggerClassName:"scope-grounding-select",value:f,disabled:d,ariaLabel:"Grounding mode",menuTitle:"Strategy",sections:[{options:[{value:"none",label:"Model only"},{value:"files",label:"Live Files context",disabled:!aQ(t)},...("multi"===f?[{value:"multi",label:"Multiple sources",disabled:!0}]:[]),...g.map(e=>({value:e.value,label:e.label})),...v.map(e=>({value:e.value,label:e.label}))]}],onValueChange:e=>{h(e);}}),null!==b?(0,a.jsx)("span",{role:"alert",className:"scope-connect-error",children:b}):null]});}function a2(e){let{chat:t,onChatChanged:n}=e,l=function(){let[e,t]=(0,i.useState)([]),[n,l]=(0,i.useState)([]),[a,r]=(0,i.useState)(null);return(0,i.useEffect)(()=>{let e=!1;return async function(){try{let[n,a]=await Promise.allSettled([(0,aF.xr)(),(0,aF.R3)()]);if("fulfilled"!==n.status)throw n.reason;if(e)return;t(n.value.capsules.filter(e=>"ready"===e.lifecycleState)),"fulfilled"===a.status?l(a.value.capsuleSets):(l([]),r(a0(a.reason)));}catch(t){e||r(a0(t));}}(),()=>{e=!0;};},[]),{capsules:e,capsuleSets:n,loadError:a};}(),r=aZ(t);return(0,a.jsx)("div",{className:"chat-scope-header","data-grounded":r?"true":"false",children:(0,a.jsx)(a1,{chat:t,onChatChanged:n,catalog:l,connected:r})});}function a3(e){let{chat:t,answer:n,busy:l,selectedModelId:i,launchGroundedWorkflowHandoff:r}=e;return void 0!==t&&aZ(t)&&(void 0!==n||l)?(0,a.jsxs)("div",{className:"chatw-grounded",children:[(0,a.jsx)(l0,{answer:n,busy:l}),(0,a.jsx)(aI,{answer:n,modelId:i,busy:l,launch:r})]}):null;}function a4(e){let{action:t,acceptCandidate:n,rejectCandidate:l,forgetMemoryAction:r,onActionSettled:s}=e,[o,c]=(0,i.useState)(!1),[d,u]=(0,i.useState)(),[p,m]=(0,i.useState)(!1),h=(0,i.useCallback)((e,t,n)=>{o||(c(!0),u(void 0),e().then(()=>{s(t);}).catch(e=>{u(e instanceof Error?e.message:n);}).finally(()=>c(!1)));},[o,s]);if("candidate"===t.kind)return(0,a.jsxs)("article",{className:"chat-memory-action",children:[(0,a.jsxs)("div",{className:"chat-memory-action-head",children:[(0,a.jsx)("strong",{children:t.scopeLabel}),(0,a.jsx)("span",{children:t.requiresApproval?"Approval required":"Proposed memory"})]}),(0,a.jsx)("p",{children:t.body}),(0,a.jsxs)("div",{className:"chat-memory-action-buttons",children:[(0,a.jsx)("button",{type:"button","aria-disabled":o,"aria-busy":o,onClick:()=>{h(()=>n(t.proposalId),"MemoriaViva proposal accepted.","Unable to accept memory.");},children:"Accept"}),(0,a.jsx)("button",{type:"button","aria-disabled":o,"aria-busy":o,onClick:()=>{h(()=>l(t.proposalId),"MemoriaViva proposal rejected.","Unable to reject memory.");},children:"Reject"})]}),void 0!==d?(0,a.jsx)(lT,{error:d,fallback:"Unable to update memory.",onDismiss:()=>u(void 0)}):null]});if("update"===t.kind)return(0,a.jsxs)("article",{className:"chat-memory-action",children:[(0,a.jsxs)("div",{className:"chat-memory-action-head",children:[(0,a.jsx)("strong",{children:"MemoriaViva update detected"}),(0,a.jsx)("span",{children:t.memoryId})]}),(0,a.jsx)("p",{children:void 0!==t.bodyPatch?`Suggested update: ${t.bodyPatch}`:"Suggested update."})]});if("forget"===t.kind){let e=()=>{h(()=>r(t.memoryId).then(()=>m(!1)),"MemoriaViva forget action completed.","Unable to forget memory.");};return(0,a.jsxs)("article",{className:"chat-memory-action",children:[(0,a.jsxs)("div",{className:"chat-memory-action-head",children:[(0,a.jsx)("strong",{children:"MemoriaViva forget detected"}),(0,a.jsx)("span",{children:t.requiresConfirmation?"Confirmation required":t.memoryId})]}),(0,a.jsx)("p",{children:`Matched memory ${t.memoryId} for a forget operation.`}),(0,a.jsx)("div",{className:"chat-memory-action-buttons",children:t.requiresConfirmation?p?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("button",{type:"button","aria-disabled":o,"aria-busy":o,onClick:e,children:"Forget permanently"}),(0,a.jsx)("button",{type:"button","aria-disabled":o,"aria-busy":o,onClick:()=>{o||(u(void 0),m(!1));},children:"Cancel"})]}):(0,a.jsx)("button",{type:"button","aria-disabled":o,"aria-busy":o,onClick:()=>{o||(u(void 0),m(!0));},children:"Review forget"}):(0,a.jsx)("button",{type:"button","aria-disabled":o,"aria-busy":o,onClick:e,children:"Forget"})}),void 0!==d?(0,a.jsx)(lT,{error:d,fallback:"Unable to update memory.",onDismiss:()=>u(void 0)}):null]});}return"rejected"===t.kind?(0,a.jsxs)("article",{className:"chat-memory-action",children:[(0,a.jsx)("div",{className:"chat-memory-action-head",children:(0,a.jsx)("strong",{children:"Memory proposal declined"})}),(0,a.jsx)("p",{children:""!==t.reason?t.reason:"No reason provided"})]}):(0,a.jsx)("article",{className:"chat-memory-action",children:(0,a.jsx)("div",{className:"chat-memory-action-head",children:(0,a.jsx)("strong",{children:"MemoriaViva action not created"})})});}function a6(e){var t;let{memoryEnabled:n,setMemoryEnabled:l,memoryBudgetTokens:r,setMemoryBudgetTokens:s,latestMemory:o,acceptCandidate:c,rejectCandidate:d,forgetMemoryAction:u,compact:p=!1}=e,[m,h]=(0,i.useState)(!1),[f,g]=(0,i.useState)(""),v=(0,i.useId)(),b=`${v}-chat-memory-disclosure`,x=(0,i.useRef)(null),y=(0,i.useCallback)(e=>{var t;g(e),null==(t=x.current)||t.focus();},[]),w=null!=(t=null==o?void 0:o.context.memories.length)?t:0,j=w>0?`${String(w)} memories included`:"No memories included",k=e=>{s(Math.max(0,r+e));},S=(0,a.jsxs)("label",{className:"chat-memory-budget",children:[(0,a.jsx)("span",{children:"Budget (tokens)"}),(0,a.jsxs)("span",{className:"number-control number-control-pill",children:[(0,a.jsx)("input",{type:"number",className:"number-control-input",min:0,step:100,value:r,onChange:e=>s(Math.max(0,Number(e.target.value)||0)),onWheel:e=>{0===e.deltaY||(e.preventDefault(),k(100*(e.deltaY<0?1:-1)));}}),(0,a.jsx)(l1,{label:"memory budget",onStepUp:()=>k(100),onStepDown:()=>k(-100)})]})]});return(0,a.jsxs)("section",{className:"chat-memory-panel","aria-label":"Conversation memory",children:[(0,a.jsxs)("div",{className:"chat-memory-panel-head",children:[(0,a.jsxs)("div",{className:"chat-memory-toggle",children:[(0,a.jsx)(aA,{on:n,onChange:l,label:"Enable MemoriaViva for the next request"}),(0,a.jsxs)("span",{children:["MemoriaViva ",n?"on":"off"]})]}),p?null:S,(0,a.jsx)("button",{ref:x,type:"button",className:`chip${p?" chip-icon chat-memory-disclosure-toggle ui-tip cmp-tip-end":""}`,"aria-expanded":m,"aria-controls":b,"aria-label":j,"data-tip":p?j:void 0,onClick:()=>h(e=>!e),children:p?(0,a.jsx)(N.F.brainSlash,{size:16,style:{color:"var(--accent)"}}):j})]}),m?(0,a.jsxs)("div",{id:b,className:"chat-memory-disclosure",children:[(0,a.jsx)("p",{className:"chat-memory-summary",children:void 0===o?"MemoriaViva disclosure appears after the next response.":o.context.enabled?`Used ${String(o.context.budget.used)} of ${String(o.context.budget.tokens)} MemoriaViva tokens.`:"MemoriaViva was disabled for the last request."}),null==o?void 0:o.context.memories.map(e=>(0,a.jsxs)("article",{className:"chat-memory-item",children:[(0,a.jsxs)("div",{className:"chat-memory-item-head",children:[(0,a.jsx)("strong",{children:e.memoryId}),(0,a.jsx)("span",{children:e.inclusionReason})]}),(0,a.jsx)("p",{children:e.bodyExcerpt}),(0,a.jsxs)("dl",{className:"chat-memory-meta","aria-label":`Provenance for ${e.memoryId}`,children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Source"}),(0,a.jsx)("dd",{children:e.sourceKind})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Sensitivity"}),(0,a.jsx)("dd",{children:e.sensitivity})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Status"}),(0,a.jsx)("dd",{children:e.status})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Confidence"}),(0,a.jsx)("dd",{children:`${String(Math.round(100*e.confidence))}%`})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Captured"}),(0,a.jsx)("dd",{children:new Date(e.capturedAt).toISOString().slice(0,10)})]})]}),void 0!==e.captureRationale?(0,a.jsx)("p",{className:"chat-memory-rationale",children:e.captureRationale}):null]},e.memoryId)),null==o?void 0:o.actions.map(e=>(0,a.jsx)(a4,{action:e,acceptCandidate:c,rejectCandidate:d,forgetMemoryAction:u,onActionSettled:y},"candidate"===e.kind?e.proposalId:"rejected"===e.kind?e.reason:e.memoryId)),(0,a.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true",children:f})]}):null]});}function a5(e){let{mini:t=!1,minimalChat:n=!1,compact:l=!1,controlsNarrow:r=!1,barCompact:s=!1,workflowCompact:c=!1,onOpenRunResult:d}=e,u=o(),{messages:p,draft:m,loading:h,sending:f,sendStatus:g,error:v,noEligibleModels:b,selectedModel:x,sendMessage:y,cancelGrounded:w,activeChat:j,replaceChat:k,latestGrounded:N,latestMemory:S,lastSentDocuments:C,memoryEnabled:I,setMemoryEnabled:R,memoryBudgetTokens:E,setMemoryBudgetTokens:$,acceptMemoryCandidate:A,rejectMemoryCandidate:F,launchGroundedWorkflowHandoff:T,forgetMemoryAction:D}=u,q=m.trim().length>0&&!f&&!h&&!b,M=p.filter(e=>"user"===e.role||"assistant"===e.role&&e.content.length>0||aE(e)),P=(0,i.useRef)(null),L=(0,i.useRef)(!0),z=(0,i.useRef)(!1),O=M.length>0?M[M.length-1]:void 0,K=void 0===O?"":O.content,B=l||t,W=r||t||n||c,U=s||n,_=c||t||n;return(0,i.useEffect)(()=>{f&&!z.current&&(L.current=!0),z.current=f;let e=P.current;null!==e&&L.current&&(e.scrollTop=e.scrollHeight);},[M.length,f,K]),(0,a.jsxs)("div",{className:`chatw${B?" chatw-compact":""}${n?" chatw-minimal":""}`,children:[void 0!==j?(0,a.jsx)(a2,{chat:j,onChatChanged:k}):null,void 0!==j?(0,a.jsx)(a6,{memoryEnabled:I,setMemoryEnabled:R,memoryBudgetTokens:E,setMemoryBudgetTokens:$,latestMemory:S,acceptCandidate:A,rejectCandidate:F,forgetMemoryAction:D,compact:B||n}):null,b?(0,a.jsx)("div",{className:"chatw-foot",children:(0,a.jsx)(aW,{})}):null,h?(0,a.jsx)("div",{className:"chatw-foot",children:(0,a.jsx)(aU,{})}):null,(0,a.jsx)("div",{className:"chatw-scroll",ref:P,role:"log","aria-label":"Conversation",tabIndex:0,onScroll:e=>{let t=e.currentTarget;L.current=t.scrollHeight-t.scrollTop-t.clientHeight<64;},children:0===M.length?void 0!==j?(0,a.jsx)(aH,{minimal:n}):(0,a.jsx)(aJ,{}):(0,a.jsxs)("div",{className:"chatw-log",children:[M.map((e,t)=>(0,a.jsx)(az,{message:e,onOpenRunResult:d,streaming:"streaming"===g&&t===M.length-1&&"assistant"===e.role},e.id)),f&&"streaming"!==g?(0,a.jsxs)("div",{className:"chatw-typing-row",children:[(0,a.jsx)(aK,{}),aZ(j)?(0,a.jsx)("button",{type:"button",className:"grounded-cancel-btn","aria-label":"Cancel grounded request",onClick:w,children:"Cancel"}):null]}):null,(0,a.jsx)(a3,{chat:j,answer:N,busy:f,selectedModelId:x,launchGroundedWorkflowHandoff:T}),(0,a.jsx)(ay,{documents:C})]})}),M.length>0?(0,a.jsx)("div",{className:"chatw-foot",children:(0,a.jsxs)("form",{className:`composer${B?" composer-chat-compact":""}`,onSubmit:e=>{e.preventDefault(),y();},children:[(0,a.jsx)(aV,{session:u,ready:q,placeholder:aM,minimal:n,compact:B,controlsNarrow:W,barCompact:U,workflowCompact:_}),void 0!==v?(0,a.jsx)(lT,{error:v,fallback:"Could not send message.",onDismiss:u.clearError}):null]})}):null,0===M.length&&void 0!==j?(0,a.jsx)("div",{className:"chatw-foot",children:(0,a.jsxs)("form",{className:`composer${B?" composer-chat-compact":""}`,onSubmit:e=>{e.preventDefault(),y();},children:[(0,a.jsx)(aV,{session:u,ready:q,placeholder:h?"Connecting to your gateway…":aM,minimal:n,compact:B,controlsNarrow:W,barCompact:U,workflowCompact:_}),void 0!==v?(0,a.jsx)(lT,{error:v,fallback:"Could not send message.",onDismiss:u.clearError}):null]})}):null,0===M.length&&void 0!==v&&void 0===j?(0,a.jsx)("div",{className:"chatw-foot",children:(0,a.jsx)(lT,{error:v,fallback:"Could not load chat.",onDismiss:u.clearError})}):null]});}let a8=new Set(["ArrowDown","ArrowUp","ArrowRight","ArrowLeft","Home","End"]);function a7(e){return Array.from(e.querySelectorAll("button[role='treeitem']"));}function a9(e){let{project:t,activeProjectPath:n,chats:l,activeChatId:r,onProject:s,onChat:o,treeRef:c}=e,d=n===t.path,[u,p]=(0,i.useState)(d),m=t.available?"Available":"Unavailable";return(0,i.useEffect)(()=>{d&&p(!0);},[d]),(0,a.jsxs)("div",{className:"proj",children:[(0,a.jsxs)("button",{className:"proj-head",type:"button",role:"treeitem","aria-level":1,"aria-expanded":u,"aria-selected":d,"data-active":d?"true":"false","aria-current":d?"true":void 0,"aria-label":`${t.name} (${m})`,tabIndex:d?0:-1,onClick:()=>{p(e=>!e),s(t),null!==c.current&&a7(c.current).forEach(e=>{e.tabIndex=-1;});},children:[(0,a.jsx)("span",{className:"proj-caret","data-open":u,"aria-hidden":"true",children:(0,a.jsx)(N.F.chevronR,{size:13})}),(0,a.jsx)(N.F.folder,{size:15,"aria-hidden":"true"}),(0,a.jsx)("span",{className:"proj-name",children:t.name}),(0,a.jsx)("span",{className:"chat-time",children:m})]}),u&&(0,a.jsx)("div",{className:"proj-chats",role:"group","aria-label":t.name,children:d?0===l.length?(0,a.jsx)("div",{className:"proj-empty",children:"No chats"}):l.map(e=>(0,a.jsxs)("button",{type:"button",role:"treeitem","aria-level":2,"aria-selected":r===e.id,className:"chat-row","data-active":r===e.id,tabIndex:-1,onClick:()=>{o(e);},children:[(0,a.jsx)("span",{className:"chat-title",children:e.title}),void 0!==e.branchLabel?(0,a.jsx)("span",{className:"chat-meta mono",children:e.branchLabel}):null]},e.id)):(0,a.jsx)("div",{className:"proj-empty",children:"Select project to load chats"})})]});}function ie(){let e=o(),t=(0,i.useRef)(null);return(0,a.jsxs)("div",{className:"tw-scroll",children:[(0,a.jsx)("div",{className:"sb-section",children:(0,a.jsx)("span",{className:"sb-section-label",children:"Projects"})}),0===e.projects.length?(0,a.jsx)("div",{className:"proj-empty",children:"No registered projects"}):(0,a.jsx)("div",{className:"proj-tree",role:"tree","aria-label":"Projects",tabIndex:-1,ref:t,onKeyDown:e=>{a8.has(e.key)&&null!==t.current&&function(e,t){var n,l,a,i,r,s,o,c,d;let u=a7(t),p=e.target;if(!(p instanceof HTMLElement))return;let m=p.closest("button[role='treeitem']");if(null===m)return;let h=u.indexOf(m);if(h<0)return;e.preventDefault();let f=e.key;if("ArrowDown"===f)null==(n=u[h+1])||n.focus();else if("ArrowUp"===f)null==(l=u[h-1])||l.focus();else if("Home"===f)null==(a=u[0])||a.focus();else if("End"===f)null==(i=u[u.length-1])||i.focus();else if("ArrowRight"===f)"false"===m.getAttribute("aria-expanded")?m.click():"true"===m.getAttribute("aria-expanded")&&(null==(r=u[h+1])||r.focus());else if("ArrowLeft"===f)if("true"===m.getAttribute("aria-expanded"))m.click();else{let e=Number(null!=(s=m.getAttribute("aria-level"))?s:"1");for(let t=h-1;t>=0;t-=1)if(Number(null!=(o=null==(c=u[t])?void 0:c.getAttribute("aria-level"))?o:"1")<e){null==(d=u[t])||d.focus();break;}}}(e,t.current);},children:e.projects.map(n=>{var l,i,r;return(0,a.jsx)(a9,{project:n,activeProjectPath:null==(l=e.activeProject)?void 0:l.path,chats:(null==(i=e.activeProject)?void 0:i.path)===n.path?e.chats:[],activeChatId:null==(r=e.activeChat)?void 0:r.id,treeRef:t,onProject:t=>{e.openProject(t);},onChat:t=>{e.openChat(t);}},n.path);})})]});}function it(e){let{openChatWindow:t}=e,n=o(),[l,r]=(0,i.useState)(""),[s,c]=(0,i.useState)("active"),[d,u]=(0,i.useState)(null),[p,m]=(0,i.useState)(""),[h,f]=(0,i.useState)(null),[g,v]=(0,i.useState)(null),[b,x]=(0,i.useState)(null),[y,w]=(0,i.useState)(null),j=(0,i.useRef)(null),S=(0,i.useId)(),C=(0,i.useId)(),I=(0,i.useId)(),R=(0,i.useId)(),E=(0,i.useMemo)(()=>n.chats.filter(e=>"closed"!==e.status).length,[n.chats]),$=n.chats.length-E,A=(0,i.useMemo)(()=>[...n.chats].sort((e,t)=>t.updatedAt-e.updatedAt).filter(e=>"deleted"===s?"closed"===e.status:"closed"!==e.status).filter(e=>{var t,n;let a;return 0===(a=l.trim().toLowerCase()).length||e.title.toLowerCase().includes(a)||e.selectedModel.toLowerCase().includes(a)||null!=(t=null==(n=e.branchLabel)?void 0:n.toLowerCase().includes(a))&&t;}),[l,n.chats,s]);(0,i.useEffect)(()=>{var e;null!==d&&(null==(e=j.current)||e.focus({preventScroll:!0}));},[d]);let F=async()=>{x(null);let e=await n.openNewChat(void 0,"New chat");void 0!==e&&t(e);},T=e=>{u(e.id),m(e.title),f(null),x(null),w(null);},D=async e=>{let t=p.trim();if(0===t.length){var l;w("Title cannot be empty."),null==(l=j.current)||l.focus({preventScroll:!0});return;}if(t===e.title){u(null),w(null);return;}v(e.id),x(null),w(null);try{let l=await(0,k.wi)(e.id,{title:t});n.replaceChat(l.chat),u(null);}catch{x("Rename failed.");}finally{v(null);}},q=async e=>{v(e.id),x(null);try{let t=await(0,k.wi)(e.id,{status:"closed"});n.replaceChat(t.chat),f(null);}catch(t){let e=t instanceof Error?t.message:"Request failed.";x(`Delete failed: ${e}`);}finally{v(null);}},M=async e=>{v(e.id),x(null);try{let t=await(0,k.wi)(e.id,{status:"open"});n.replaceChat(t.chat),f(null);}catch(t){let e=t instanceof Error?t.message:"Request failed.";x(`Restore failed: ${e}`);}finally{v(null);}};return(0,a.jsxs)("div",{className:"chat-history",children:[(0,a.jsxs)("div",{className:"chat-history-head",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("p",{className:"chat-history-kicker",children:"Conversations"}),(0,a.jsx)("h2",{children:"Chat History"})]}),(0,a.jsxs)("button",{type:"button",className:"lk-btn lk-btn-primary",onClick:()=>void F(),children:[(0,a.jsx)(N.F.newChat,{size:15}),"New"]})]}),(0,a.jsxs)("label",{className:"chat-history-search",children:[(0,a.jsx)(N.F.search,{size:15}),(0,a.jsx)("input",{value:l,onChange:e=>r(e.target.value),placeholder:"Search","aria-label":"Search chat history"})]}),(0,a.jsxs)("div",{className:"chat-history-tabs",role:"tablist","aria-label":"Conversation state",children:[(0,a.jsxs)("button",{type:"button",id:S,role:"tab","aria-selected":"active"===s,"aria-controls":I,className:"chat-history-tab",onClick:()=>{c("active"),f(null);},children:["Active ",(0,a.jsx)("span",{children:E})]}),(0,a.jsxs)("button",{type:"button",id:C,role:"tab","aria-selected":"deleted"===s,"aria-controls":I,className:"chat-history-tab",onClick:()=>{c("deleted"),f(null);},children:["Deleted ",(0,a.jsx)("span",{children:$})]})]}),null!==b?(0,a.jsx)("div",{className:"lk-alert",role:"alert",children:b}):null,(0,a.jsx)("div",{id:I,className:"chat-history-list",role:"tabpanel","aria-labelledby":"active"===s?S:C,children:0===A.length?(0,a.jsx)("div",{className:"lk-empty",children:(0,a.jsx)("p",{className:"lk-empty-title",children:"No conversations"})}):A.map(e=>{var n;let l=e5(e).length+e8(e).length,i=d===e.id,r=h===e.id,s=g===e.id,o="closed"===e.status;return(0,a.jsxs)("article",{className:"chat-history-row","data-chat-id":e.id,"data-state":o?"deleted":"active",children:[(0,a.jsx)("div",{className:"chat-history-row-main",children:i?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("input",{ref:j,className:"chat-history-title-input",value:p,"aria-invalid":null!==y,"aria-describedby":null!==y?R:void 0,onChange:e=>{m(e.target.value),null!==y&&w(null);},onKeyDown:t=>{"Enter"===t.key&&D(e),"Escape"===t.key&&(u(null),w(null));}}),null!==y?(0,a.jsx)("span",{id:R,className:"chat-history-rename-error",role:"alert",children:y}):null]}):(0,a.jsxs)("button",{type:"button",className:"chat-history-open",disabled:o,onClick:()=>t(e),children:[(0,a.jsx)("span",{className:"chat-history-title",children:e.title}),(0,a.jsxs)("span",{className:"chat-history-meta",children:[(n=e.updatedAt,new Intl.DateTimeFormat(void 0,{month:"short",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(n)))," / ",e.selectedModel,l>0?` / ${String(l)} sources`:""]})]})}),(0,a.jsx)("div",{className:"chat-history-actions",children:i?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-primary",disabled:s,onClick:()=>void D(e),children:"Save"}),(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",disabled:s,onClick:()=>{u(null),w(null);},children:"Cancel"})]}):r?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-danger",disabled:s,onClick:()=>void q(e),children:"Delete"}),(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",disabled:s,onClick:()=>f(null),children:"Cancel"})]}):o?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("button",{type:"button",className:"lk-btn lk-btn-primary",disabled:s,onClick:()=>void M(e),children:[(0,a.jsx)(N.F.restore,{size:14}),"Restore"]}),(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:()=>T(e),children:"Rename"})]}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:()=>T(e),children:"Rename"}),(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:()=>{f(e.id),u(null);},children:"Delete"})]})})]},e.id);})})]});}function il(){var e,t;let n=c(),l=null!=(e=null==n||null==(t=n.activeProject)?void 0:t.name)?e:"No project selected",r=(0,i.useId)();return(0,a.jsxs)("div",{className:"srch",children:[(0,a.jsxs)("div",{className:"srch-box",children:[(0,a.jsx)(N.F.search,{size:15,"aria-hidden":"true"}),(0,a.jsx)("input",{type:"search","aria-label":"Search files and symbols","aria-describedby":r,placeholder:"Search files & symbols…",disabled:!0})]}),(0,a.jsxs)("div",{className:"tw-label srch-label",children:[l," ",(0,a.jsx)("span",{className:"srch-meta mono",children:"workspace search"})]}),(0,a.jsxs)("div",{className:"tw-pad",children:[(0,a.jsxs)("div",{className:"rb-placeholder",style:{height:150},children:[(0,a.jsx)("div",{className:"ph-stripes"}),(0,a.jsx)("span",{className:"rb-ph-label mono",children:"search"})]}),(0,a.jsx)("div",{id:r,className:"rb-foot mono",style:{marginTop:14},children:"Search across workspace files & symbols — coming soon."})]})]});}let ia=[{value:"auto",label:"Auto (recommended)"},{value:"fast",label:"Fast"},{value:"precise",label:"Precise"},{value:"research",label:"Research"},{value:"creative",label:"Creative"},{value:"technical",label:"Technical"},{value:"safety-critical",label:"Safety-critical"},{value:"agentic",label:"Agentic"}],ii=[{value:"clarify",label:"Ask clarifying questions"},{value:"assume",label:"State explicit assumptions"}],ir="__none__";function is(e){let{items:t,empty:n}=e;return 0===t.length?void 0===n?null:(0,a.jsx)("p",{className:"pe-empty",children:n}):(0,a.jsx)("ul",{className:"pe-list",children:t.map((e,t)=>(0,a.jsx)("li",{children:e},`${String(t)}:${e.slice(0,24)}`))});}function io(e){let{title:t,children:n}=e;return(0,a.jsxs)("section",{className:"pe-section","aria-label":t,children:[(0,a.jsx)("h4",{className:"pe-section-title",children:t}),n]});}function ic(e){var t;let{routing:n}=e,l="available"===n.availability?"ok":"unavailable"===n.availability?"warn":"muted",i="available"===n.availability?`Model ready: ${null!=(t=n.resolvedModelId)?t:""}`:"unavailable"===n.availability?"Selected model unavailable — enhancement still completed deterministically":"No downstream model selected — enhancement is provider-neutral";return(0,a.jsx)("p",{className:`pe-routing pe-routing-${l}`,"data-testid":"pe-model-routing",role:"status","aria-live":"polite",children:i});}function id(e){let{safety:t}=e,n=t.requiresHumanReview;return(0,a.jsxs)(io,{title:"Safety",children:[(0,a.jsxs)("p",{className:"pe-safety-summary","data-testid":"pe-safety-decision",children:["Decision: ",(0,a.jsx)("strong",{children:t.decision})," \xb7 verification: ",t.verificationStatus," \xb7"," ","human review: ",(0,a.jsx)("strong",{children:n?"required":"not required"})]}),n?(0,a.jsx)("p",{className:"pe-safety-warning",role:"alert",children:"This prompt requires human review before any downstream use."}):null,t.findings.length>0?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("h5",{className:"pe-subhead",children:"Safety findings"}),(0,a.jsx)("ul",{className:"pe-list","data-testid":"pe-safety-findings",children:t.findings.map(e=>(0,a.jsxs)("li",{children:[(0,a.jsx)("span",{className:`pe-sev pe-sev-${e.severity}`,children:e.severity})," ",e.detail]},`${e.ruleId}:${e.code}`))})]}):null,t.leastPrivilege.length>0?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("h5",{className:"pe-subhead",children:"Least-privilege constraints"}),(0,a.jsx)(is,{items:[...t.leastPrivilege]})]}):null]});}function iu(e){let{plan:t,readiness:n}=e,l="ready"===n.status?"Grounding readiness: connected context available":"unavailable"===n.status?`Grounding readiness: unavailable${void 0===n.notice?"":` — ${n.notice}`}`:"Grounding readiness: not required";return(0,a.jsxs)(io,{title:"Grounding plan",children:[(0,a.jsx)("p",{className:`pe-grounding-readiness pe-grounding-readiness-${n.status}`,"data-testid":"pe-grounding-readiness",role:"unavailable"===n.status?"alert":"status","aria-live":"polite",children:l}),(0,a.jsxs)("p",{className:"pe-grounding-meta",children:["Strategy: ",(0,a.jsx)("strong",{children:t.strategy})," \xb7 ",t.required?"required":"optional"," \xb7 citations: ",t.citation.discipline," (",t.citation.granularity,")"]}),t.sourcePriority.length>0?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("h5",{className:"pe-subhead",children:"Source priority"}),(0,a.jsx)("ol",{className:"pe-list",children:t.sourcePriority.map(e=>(0,a.jsxs)("li",{children:[e.source,e.required?" (required)":""]},e.source))})]}):null,(0,a.jsx)(is,{items:[...t.directives]})]});}function ip(e){var t;let{evidence:n,fingerprint:l}=e;return(0,a.jsxs)("p",{className:"pe-evidence","data-testid":"pe-evidence",children:["Evidence fingerprint: ",l.slice(0,16),"…","recorded"===n.status&&void 0!==n.runId?(0,a.jsxs)(a.Fragment,{children:[" ","Manifest:"," ",(0,a.jsx)("a",{href:null!=(t=n.manifestUrl)?t:"#",target:"_blank",rel:"noreferrer","aria-label":`Prompt enhancement evidence manifest ${n.runId}`,children:n.runId})]}):" Manifest not recorded."]});}function im(e){let{candidates:t}=e;return(0,a.jsx)(io,{title:"Candidate scorecards",children:(0,a.jsx)("div",{className:"c-tablewrap",children:(0,a.jsx)("div",{className:"c-tablescroll",children:(0,a.jsxs)("table",{className:"c-table pe-scorecards","data-testid":"pe-scorecards",children:[(0,a.jsx)("thead",{children:(0,a.jsxs)("tr",{children:[(0,a.jsx)("th",{scope:"col",children:"Profile"}),(0,a.jsx)("th",{scope:"col",className:"num",children:"Score"}),(0,a.jsx)("th",{scope:"col",className:"num",children:"Tokens"}),(0,a.jsx)("th",{scope:"col",children:"Winner"})]})}),(0,a.jsx)("tbody",{children:t.scorecards.map(e=>{let n=e.candidateId===t.winnerCandidateId;return(0,a.jsxs)("tr",{className:n?"pe-winner":void 0,children:[(0,a.jsx)("th",{scope:"row",children:e.profile}),(0,a.jsx)("td",{className:"num",children:e.aggregateScore.toFixed(3)}),(0,a.jsx)("td",{className:"num",children:e.estimatedTokens}),(0,a.jsx)("td",{children:n?"★":""})]},e.candidateId);})})]})})})});}function ih(e){let{result:t}=e,n=t.enhancedPrompt,l=t.analysis.missingContext.map(e=>"assumption"===e.kind?e.statement:e.question);return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(io,{title:"Role",children:(0,a.jsx)("p",{children:n.role})}),(0,a.jsx)(io,{title:"Objective",children:(0,a.jsx)("p",{children:n.goal})}),(0,a.jsx)(io,{title:"Context",children:(0,a.jsx)(is,{items:[...n.context],empty:"No additional context."})}),(0,a.jsx)(io,{title:t.analysis.missingContext.some(e=>"assumption"===e.kind)?"Assumptions":"Clarification questions",children:(0,a.jsx)(is,{items:l,empty:"No clarifications or assumptions needed."})}),(0,a.jsx)(io,{title:"Steps",children:(0,a.jsx)(is,{items:[...n.taskDecomposition]})}),(0,a.jsx)(io,{title:"Constraints",children:(0,a.jsx)(is,{items:[...n.constraints]})}),(0,a.jsxs)(io,{title:"Output schema",children:[(0,a.jsxs)("p",{children:["Format: ",(0,a.jsx)("strong",{children:n.outputSchema.format}),n.outputSchema.structured?" \xb7 structured":""]}),(0,a.jsx)(is,{items:[...n.outputSchema.hints]})]}),(0,a.jsx)(io,{title:"Quality criteria",children:(0,a.jsx)(is,{items:[...n.qualityCriteria]})}),(0,a.jsx)(io,{title:"Uncertainty handling",children:(0,a.jsx)(is,{items:[...n.uncertaintyHandling]})}),(0,a.jsx)(io,{title:"Safety rules",children:(0,a.jsx)(is,{items:[...n.safetyRules]})})]});}function ig(){let{enhanceImpl:e=k.fG,fetchModelsImpl:t=k.ZC}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},[n,l]=(0,i.useState)(""),[r,s]=(0,i.useState)("auto"),[o,c]=(0,i.useState)("clarify"),[d,u]=(0,i.useState)(ir),[p,m]=(0,i.useState)([]),[h,f]=(0,i.useState)(null),[g,v]=(0,i.useState)(!1),[b,x]=(0,i.useState)(null),[y,w]=(0,i.useState)(!1),[j,N]=(0,i.useState)(null),S=(0,i.useRef)(null),C=(0,i.useId)(),I=(0,i.useId)();(0,i.useEffect)(()=>{let e=!1;return t().then(t=>{e||m(t.models.filter(e=>"chat"===e.kind));}).catch(()=>{}),()=>{e=!0;};},[t]),(0,i.useEffect)(()=>()=>{var e;null==(e=S.current)||e.abort();},[]);let R=(0,i.useCallback)(async()=>{var t;let l=n.trim();if(0===l.length)return void x("Enter a prompt draft to enhance.");null==(t=S.current)||t.abort();let a=new AbortController();S.current=a,v(!0),x(null),w(!1),N(null);let i={text:l,missingInformationStrategy:"assume"===o?"assume":"clarify",...("auto"===r?{}:{profilePreference:r}),...(d===ir?{}:{modelId:d})};try{let t=await e(i,a.signal);a.signal.aborted||f(t);}catch(e){a.signal.aborted||x(e instanceof k.hD?`${e.message} (${e.code})`:e instanceof Error&&"AbortError"===e.name?"Request cancelled.":"Prompt enhancement failed. Please try again.");}finally{a.signal.aborted||v(!1);}},[n,o,r,d,e]),E=(0,i.useCallback)(async()=>{var e;if(null===h)return;let t=null==(e=navigator.clipboard)?void 0:e.writeText;if(void 0===t)return void x("Clipboard is not available in this browser.");try{await t.call(navigator.clipboard,h.renderedPrompt),w(!0),N("Rendered prompt copied to clipboard.");}catch{x("Could not copy to the clipboard.");}},[h]),$=[{options:[{value:ir,label:"Deterministic only (no model)"},...p.map(e=>({value:e.id,label:e.id}))]}];return(0,a.jsxs)("div",{className:"pe-panel","data-testid":"prompt-enhancer-panel",children:[(0,a.jsx)("h3",{className:"pe-title",children:"Prompt Enhancer"}),(0,a.jsx)("p",{className:"pe-intro",children:"Turn a raw prompt into a governed, structured Enhanced Prompt. The result is for review and copy/export — it is never executed from here."}),(0,a.jsxs)("div",{className:"pe-form",children:[(0,a.jsx)("label",{className:"pe-label",htmlFor:C,children:"Raw prompt"}),(0,a.jsx)("textarea",{id:C,className:"pe-draft",value:n,onChange:e=>{l(e.target.value);},rows:5,placeholder:"Describe the task you want a strong prompt for…","aria-describedby":null===b?void 0:I}),(0,a.jsxs)("div",{className:"pe-controls",children:[(0,a.jsxs)("div",{className:"pe-control",children:[(0,a.jsx)("span",{className:"pe-label","aria-hidden":"true",children:"Profile"}),(0,a.jsx)(tB,{value:r,ariaLabel:"Profile",onValueChange:s,sections:[{options:ia.map(e=>({...e}))}]})]}),(0,a.jsxs)("div",{className:"pe-control",children:[(0,a.jsx)("span",{className:"pe-label","aria-hidden":"true",children:"Missing information"}),(0,a.jsx)(tB,{value:o,ariaLabel:"Missing information",onValueChange:c,sections:[{options:ii.map(e=>({...e}))}]})]}),(0,a.jsxs)("div",{className:"pe-control",children:[(0,a.jsx)("span",{className:"pe-label","aria-hidden":"true",children:"Readiness model"}),(0,a.jsx)(tB,{value:d,ariaLabel:"Readiness model",onValueChange:u,sections:$})]})]}),(0,a.jsx)("button",{type:"button",className:"pe-enhance",onClick:()=>{R();},disabled:g||0===n.trim().length,children:g?"Enhancing…":"Enhance prompt"}),g?(0,a.jsx)("p",{className:"pe-status",role:"status","aria-live":"polite",children:"Enhancing prompt…"}):null]}),null!==b?(0,a.jsx)("p",{className:"pe-error",role:"alert",id:I,children:b}):null,null!==h?(0,a.jsxs)("div",{className:"pe-result","data-testid":"pe-result",children:[(0,a.jsx)(ic,{routing:h.modelRouting}),(0,a.jsxs)("p",{className:"pe-analysis",children:["Task: ",(0,a.jsx)("strong",{children:h.analysis.taskClass})," \xb7 domain: ",h.analysis.domain," \xb7 criticality: ",h.analysis.criticality]}),(0,a.jsx)(id,{safety:h.safety}),(0,a.jsx)(ih,{result:h}),(0,a.jsx)(iu,{plan:h.enhancedPrompt.groundingPlan,readiness:h.groundingReadiness}),(0,a.jsx)(im,{candidates:h.candidates}),(0,a.jsxs)(io,{title:"Rendered prompt",children:[(0,a.jsx)("pre",{className:"pe-rendered","aria-label":"Rendered prompt text",children:h.renderedPrompt}),(0,a.jsx)("div",{className:"pe-actions",children:(0,a.jsx)("button",{type:"button",className:"pe-copy",onClick:()=>{E();},children:"Copy rendered prompt"})}),y&&null!==j?(0,a.jsx)("p",{className:"pe-status",role:"status","aria-live":"polite",children:j}):null]}),(0,a.jsx)(ip,{evidence:h.evidence,fingerprint:h.inputFingerprintSha256})]}):null]});}let iv=[{name:"Context7",img:"upstash",desc:"Up-to-date library docs",on:!0},{name:"Sequential Thinking",icon:"layers",desc:"Step-by-step reasoning",on:!0},{name:"Filesystem",icon:"files",desc:"Local file access",on:!0},{name:"GitHub",img:"github",desc:"Repos \xb7 PRs \xb7 issues",on:!0},{name:"Playwright",img:"playwright",desc:"Browser automation",on:!1},{name:"Brave Search",img:"brave",desc:"Web search",on:!1},{name:"MemoriaViva",icon:"cube",desc:"Knowledge graph",on:!0}],ib=[{name:"GitHub",img:"github",on:!0},{name:"Linear",img:"linear",on:!0},{name:"PostgreSQL",img:"postgresql",on:!0},{name:"Sentry",img:"sentry",on:!1},{name:"Slack",img:"slack",on:!1},{name:"Notion",img:"notion",on:!1}];function ix(e){let{img:t,icon:n,glyph:l}=e;if(void 0!==t)return(0,a.jsx)("img",{className:"pl-img",src:`/assets/icons/${t}.svg`,width:"20",height:"20",alt:""});if(void 0!==n){let e=N.F[n];return(0,a.jsx)("span",{className:"pl-line",children:(0,a.jsx)(e,{size:18})});}return(0,a.jsx)("span",{className:"mono pl-glyph",children:l});}function iy(){let[e,t]=(0,i.useState)(iv.map(e=>e.on)),n=e.filter(Boolean).length;return(0,a.jsxs)("div",{className:"plg",children:[(0,a.jsxs)("div",{className:"plg-sec",children:[(0,a.jsx)("span",{className:"plg-sec-t",children:"MCP Servers"}),(0,a.jsxs)("span",{className:"plg-sec-c mono",children:[n,"/",iv.length," active"]})]}),iv.map((n,l)=>{var i;let r=null!=(i=e[l])&&i;return(0,a.jsxs)("div",{className:"plg-row",children:[(0,a.jsx)("span",{className:"plg-ico",children:(0,a.jsx)(ix,{img:n.img,icon:n.icon})}),(0,a.jsxs)("span",{className:"plg-text",children:[(0,a.jsx)("span",{className:"plg-name",children:n.name}),(0,a.jsx)("span",{className:"plg-desc",children:n.desc})]}),(0,a.jsx)("button",{className:`plg-dot${r?" on":""}`,title:r?"Running":"Stopped","aria-label":`${n.name}: ${r?"running":"stopped"}`,onClick:()=>{t(e=>{var t;let n=[...e];return n[l]=!(null!=(t=n[l])&&t),n;});}})]},n.name);}),(0,a.jsx)("div",{className:"plg-sec plg-sec2",children:(0,a.jsx)("span",{className:"plg-sec-t",children:"Connectors"})}),ib.map(e=>(0,a.jsxs)("button",{className:"plg-row plg-conn","data-on":e.on,children:[(0,a.jsx)("span",{className:"plg-ico",children:(0,a.jsx)(ix,{img:e.img})}),(0,a.jsxs)("span",{className:"plg-text",children:[(0,a.jsx)("span",{className:"plg-name",children:e.name}),(0,a.jsx)("span",{className:"plg-desc",children:e.on?"Connected":"Not connected"})]}),e.on?(0,a.jsx)("span",{className:"integ-on",children:(0,a.jsx)(N.F.check,{size:13})}):(0,a.jsx)("span",{className:"integ-add",children:(0,a.jsx)(N.F.plus,{size:14})})]},e.name))]});}let iw=[{id:"nightly-review",name:"Nightly review",when:"02:00 daily",defaultOn:!0},{id:"on-push-lint",name:"On push → lint",when:"git push",defaultOn:!0},{id:"weekly-digest",name:"Weekly digest",when:"Mon 09:00",defaultOn:!1}],ij="keiko.automations.v1",ik=Object.fromEntries(iw.map(e=>[e.id,e.defaultOn]));function iN(){try{let e=localStorage.getItem(ij);if(null===e)return{...ik};let t=JSON.parse(e);if("object"!=typeof t||null===t||Array.isArray(t))return{...ik};let n={...ik};for(let[e,l]of Object.entries(t))e in ik&&"boolean"==typeof l&&(n[e]=l);return n;}catch{return{...ik};}}function iS(){let[e,t]=(0,i.useState)(iN);return(0,a.jsx)("div",{className:"tw-list",children:iw.map(n=>{var l;let i=null!=(l=e[n.id])?l:n.defaultOn;return(0,a.jsxs)("div",{className:"auto-row",children:[(0,a.jsx)("span",{className:"dot",style:{background:i?"var(--accent)":"var(--fg-faint)"}}),(0,a.jsxs)("span",{className:"auto-text",children:[(0,a.jsx)("span",{className:"auto-name",children:n.name}),(0,a.jsx)("span",{className:"auto-when mono",children:n.when})]}),(0,a.jsx)(aA,{on:i,onChange:()=>{var e;e=n.id,t(t=>{var n;let l={...t,[e]:!(null!=(n=t[e])&&n)};try{localStorage.setItem(ij,JSON.stringify(l));}catch{}return l;});},label:n.name})]},n.id);})});}function iC(){return(0,a.jsxs)("div",{className:"tw-pad mob",children:[(0,a.jsxs)("div",{className:"mob-qr",children:[(0,a.jsx)("div",{className:"ph-stripes"}),(0,a.jsx)(N.F.mobile,{size:28,style:{position:"relative",color:"var(--fg-dim)"}})]}),(0,a.jsx)("div",{className:"mob-title",children:"Keiko Mobile"}),(0,a.jsx)("div",{className:"mob-sub",children:"Scan to continue this workspace on your phone."})]});}function iI(){var e;let t,{wins:n,active:l,winCount:r}=(0,i.useContext)(j),s=null!==l?$[l.type]:null,o=null!==l?Object.entries(l.cfg).filter(e=>{let[,t]=e;return""!==t&&null!=t;}):[];return(0,a.jsxs)("div",{className:"tw-pad",children:[(0,a.jsx)("div",{className:"rb-section-label",style:{marginTop:0},children:"Active window"}),null!==l&&null!==s?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"insp-top",children:[(0,a.jsx)("span",{className:"insp-ico",style:{color:!0===s.accent?"var(--accent)":"var(--fg-muted)"},children:(e=s.icon,t=N.F[e],(0,a.jsx)(t,{size:16}))}),(0,a.jsx)("span",{className:"insp-title",children:s.title})]}),(0,a.jsxs)("div",{className:"rb-rows",children:[(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",children:"Size"}),(0,a.jsxs)("span",{className:"rb-row-v mono",children:[Math.round(l.w)," \xd7 ",Math.round(l.h)]})]}),(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",children:"Position"}),(0,a.jsxs)("span",{className:"rb-row-v mono",children:[Math.round(l.x),", ",Math.round(l.y)]})]}),(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",children:"State"}),(0,a.jsx)("span",{className:"rb-row-v mono",children:l.max?"maximized":"floating"})]})]}),o.length>0&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("div",{className:"rb-section-label",children:"Configuration"}),(0,a.jsx)("div",{className:"rb-rows",children:o.map(e=>{let[t,n]=e;return(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",children:t}),(0,a.jsx)("span",{className:"rb-row-v mono",children:String(n).slice(0,20)||"—"})]},t);})})]}),(0,a.jsx)("div",{className:"rb-section-label insp-governance",children:"Governance"}),(0,a.jsxs)("div",{className:"rb-rows insp-governance","data-testid":"insp-governance",children:[(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",children:"Authority"}),(0,a.jsx)("span",{className:"rb-row-v mono",children:eD[l.type].authority})]}),(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",children:"Persistence"}),(0,a.jsx)("span",{className:"rb-row-v mono",children:eD[l.type].persistence})]}),(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",children:"Trust"}),(0,a.jsx)("span",{className:"rb-row-v mono",children:eD[l.type].trustBoundary.join(", ")})]}),(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",children:"Lifecycle"}),(0,a.jsx)("span",{className:"rb-row-v mono",children:eD[l.type].lifecycle.join(" → ")})]})]})]}):(0,a.jsx)("div",{className:"insp-empty",children:"No window focused"}),(0,a.jsx)("div",{className:"rb-section-label",children:"Workspace"}),(0,a.jsx)("div",{className:"rb-rows",children:(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",children:"Open windows"}),(0,a.jsx)("span",{className:"rb-row-v mono",children:r})]})})]});}let iR=[{t:"Agent finished build-board",time:"2m",c:"var(--accent)"},{t:"diff-review ready to merge",time:"9m",c:"var(--info)"},{t:"lint-pass queued",time:"14m",c:"var(--fg-faint)"}];function iE(){return(0,a.jsx)("ul",{className:"tw-list",children:iR.map((e,t)=>(0,a.jsxs)("li",{className:"nt-row",children:[(0,a.jsx)("span",{className:"dot",style:{background:e.c,marginTop:6},"aria-hidden":"true"}),(0,a.jsxs)("span",{className:"nt-text",children:[(0,a.jsx)("span",{className:"nt-title",children:e.t}),(0,a.jsxs)("span",{className:"nt-time mono",children:[e.time," ago"]})]})]},t))});}function i$(){return(0,a.jsxs)("div",{className:"tw-pad",children:[(0,a.jsxs)("div",{className:"rb-placeholder",style:{height:150},children:[(0,a.jsx)("div",{className:"ph-stripes"}),(0,a.jsx)("span",{className:"rb-ph-label mono",children:"resources"})]}),(0,a.jsx)("div",{className:"rb-foot mono",style:{marginTop:14},children:"Shared assets & references — coming soon."})]});}let iA="keiko-activity",iF={step:"var(--fg-dim)",approval:"var(--warn)",approved:"var(--accent)",rejected:"var(--danger)",stopped:"var(--danger)",open:"var(--info)","twin-approved":"var(--accent)","twin-denied":"var(--danger)"};function iT(){let e=function(){var e;let[,t]=(0,i.useState)(0);return(0,i.useEffect)(()=>{let e=()=>{t(e=>e+1);};return window.addEventListener(iA,e),()=>{window.removeEventListener(iA,e);};},[]),null!=(e=window.__keikoActivity)?e:[];}();return(0,a.jsxs)("div",{className:"tl",role:"log","aria-label":"Activity timeline",children:[0===e.length&&(0,a.jsxs)("div",{className:"tl-empty",children:["No activity yet.",(0,a.jsx)("br",{}),"Start an agent to see its actions stream here."]}),e.map((e,t)=>{var n,l;return(0,a.jsxs)("div",{className:"tl-row",children:[(0,a.jsx)("span",{className:"tl-dot","aria-hidden":"true",style:{background:null!=(n=iF[e.type])?n:"var(--fg-faint)"}}),(0,a.jsxs)("div",{className:"tl-body",children:[(0,a.jsx)("span",{className:"visually-hidden",children:e.type}),(0,a.jsx)("span",{className:"tl-text",children:e.text}),(0,a.jsxs)("span",{className:"tl-meta mono",children:[null!=(l=e.agent)?l:"workspace"," \xb7 ",new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})]})]})]},t);})]});}function iD(e){let t,{name:n,icon:l}=e,i=null!=l?l:"dockerfile"===(t=n.toLowerCase())||t.includes("docker-compose")||t.endsWith(".dockerignore")?"docker":t.endsWith(".json")?"json":t.endsWith(".yml")||t.endsWith(".yaml")?"yaml":t.endsWith(".md")?"markdown":t.endsWith(".properties")||t.endsWith(".env")||t.startsWith(".env.")?"properties":t.endsWith(".java")?"java":t.endsWith(".tsx")?"react":t.endsWith(".ts")?"typescript":t.endsWith(".jsx")||t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":t.endsWith(".py")?"python":t.endsWith(".go")?"go":t.endsWith(".rs")?"rust":t.endsWith(".gradle")?"gradle":t.endsWith(".sql")?"postgresql":t.endsWith(".html")?"html5":t.endsWith(".css")?"css3":t.endsWith(".graphql")||t.endsWith(".gql")?"graphql":t.endsWith(".png")||t.endsWith(".jpg")||t.endsWith(".jpeg")||t.endsWith(".gif")||t.endsWith(".webp")||t.endsWith(".svg")?"image":null;return null!==i?(0,a.jsx)("img",{className:"fi-img",src:`/assets/icons/${i}.svg`,width:"15",height:"15",alt:""}):(0,a.jsx)("span",{className:"fi-fallback",children:(0,a.jsx)(N.F.file,{size:14})});}let iq={jsx:"js",js:"js",mjs:"js",ts:"ts",tsx:"ts",java:"java",kt:"kotlin",kts:"kotlin",py:"py",rb:"py",go:"go",rs:"rust",json:"json",yml:"yaml",yaml:"yaml",md:"md",markdown:"md",html:"html",xml:"html",css:"css",sql:"sql",sh:"sh",bash:"sh",cob:"cobol",cbl:"cobol",gradle:"js",graphql:"graphql",gql:"graphql",properties:"props",toml:"props",env:"props",dockerfile:"docker"};function iM(e){var t;let n=e.toLowerCase();if(".env"===n||n.startsWith(".env."))return"props";if("dockerfile"===n||n.startsWith("dockerfile"))return"docker";if(n.includes("docker-compose"))return"yaml";let l=n.split("."),a=l.length>1?l[l.length-1]:void 0;return void 0===a?"code":null!=(t=iq[a])?t:"code";}let iP=new Set("const let var function return if else for while do switch case break continue import from export default class extends implements interface enum new async await yield of in typeof instanceof this super public private protected static final readonly void int long double float boolean char byte short val fun object data override companion package def pass lambda try catch except finally throw throws raise with as not and or is null nil None True False true false undefined struct impl trait pub use mod match where select insert update delete create table from join on group by order limit FROM RUN CMD ENV COPY WORKDIR EXPOSE ENTRYPOINT AS".split(" "));function iL(e){let t=[];return e.split(/(`[^`]+`|\*\*[^*]+\*\*)/).forEach(e=>{""!==e&&(e.startsWith("`")?t.push(["str",e]):e.startsWith("**")?t.push(["type",e]):t.push(["id",e]));}),t.length>0?t:[["id",e]];}function iz(e,t){if("md"===t)return e.split("\n").map(e=>{if(/^#{1,6}\s/.test(e))return[["head",e]];if(/^\s*```/.test(e))return[["com",e]];let t=/^(\s*)([-*+]|\d+\.)(\s)/.exec(e);if(null!==t){var n,l,a;return[["ws",null!=(n=t[1])?n:""],["key",null!=(l=t[2])?l:""],["ws",null!=(a=t[3])?a:""],...iL(e.slice(t[0].length))];}return iL(e);});if("json"===t)return e.split("\n").map(e=>{let t=[],n=0;for(;n<e.length;){let l=e.slice(n),a=/^"(?:[^"\\]|\\.)*"/.exec(l);if(null!==a){let l=e.slice(n+a[0].length),i=/^\s*:/.test(l);t.push([i?"key2":"str",a[0]]),n+=a[0].length;continue;}let i=/^-?\d[\d.eE+\-]*/.exec(l);if(null!==i){t.push(["num",i[0]]),n+=i[0].length;continue;}let r=/^(true|false|null)\b/.exec(l);if(null!==r){t.push(["lit",r[0]]),n+=r[0].length;continue;}let s=/^\s+/.exec(l);if(null!==s){t.push(["ws",s[0]]),n+=s[0].length;continue;}t.push(["punct",l.charAt(0)]),n+=1;}return t;});let n="py"===t||"sh"===t||"yaml"===t||"props"===t||"docker"===t?{line:"#",block:null}:"sql"===t?{line:"--",block:["/*","*/"]}:"cobol"===t?{line:"*>",block:null}:"html"===t?{line:null,block:["\x3c!--","--\x3e"]}:{line:"//",block:["/*","*/"]},l={inBlock:!1},a=[];for(let t of e.split("\n"))a.push(function(e,t,n){let l=[],a=0;if(t.inBlock&&null!==n.block){let i=e.indexOf(n.block[1]);if(-1===i)return l.push(["com",e]),l;l.push(["com",e.slice(0,i+n.block[1].length)]),a=i+n.block[1].length,t.inBlock=!1;}for(;a<e.length;){let r=e.slice(a);if(null!==n.line&&r.startsWith(n.line)){l.push(["com",r]);break;}if(null!==n.block&&r.startsWith(n.block[0])){let i=e.indexOf(n.block[1],a+n.block[0].length);if(-1===i){l.push(["com",r]),t.inBlock=!0;break;}l.push(["com",e.slice(a,i+n.block[1].length)]),a=i+n.block[1].length;continue;}let s=/^(?:"(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?)/.exec(r);if(null!==s&&s[0].length>1){l.push(["str",s[0]]),a+=s[0].length;continue;}if(/^\d/.test(r)){var i;let e=/^\d[\w.]*/.exec(r),t=null!=(i=null==e?void 0:e[0])?i:r.charAt(0);l.push(["num",t]),a+=t.length;continue;}let o=/^[@A-Za-z_$][\w$]*/.exec(r);if(null!==o){let t=o[0],n="id";iP.has(t)||iP.has(t.toLowerCase())?n="key":t.startsWith("@")||/^[A-Z]/.test(t)?n="type":"("===e.charAt(a+t.length)&&(n="fn"),l.push([n,t]),a+=t.length;continue;}let c=/^\s+/.exec(r);if(null!==c){l.push(["ws",c[0]]),a+=c[0].length;continue;}let d=/^[^\w\s$@"']+/.exec(r);if(null!==d){l.push(["punct",d[0]]),a+=d[0].length;continue;}l.push(["id",r.charAt(0)]),a+=1;}return l;}(t,l,n));return a;}let iO={docx:"DOCX",xlsx:"XLSX",pdf:"PDF"};function iK(e){if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=e,l=0;for(;n>=1024&&l<t.length-1;)n/=1024,l+=1;let a=0===l?n.toFixed(0):n.toFixed(n>=10?1:2);return`${a} ${t[l]}`;}function iB(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e));}function iW(e){let{label:t,value:n}=e;return(0,a.jsxs)("div",{className:"fpv-meta-row",children:[(0,a.jsx)("span",{children:t}),(0,a.jsx)("strong",{children:n})]});}function iU(e){var t,n,l,r;let{root:s,path:o,onClose:c,onOpenInEditor:d}=e,[u,p]=(0,i.useState)(null),[m,h]=(0,i.useState)(!0),[f,g]=(0,i.useState)(null),[v,b]=(0,i.useState)(0),x=(0,i.useRef)(null);(0,i.useEffect)(()=>{var e;null==(e=x.current)||e.focus({preventScroll:!0});},[]),(0,i.useEffect)(()=>{let e=!1;return h(!0),g(null),p(null),(0,k.q7)(s,o).then(t=>{e||p(t);}).catch(t=>{e||g(t instanceof k.hD&&"DENIED"===t.code?{message:"This file is excluded from the read surface for safety (matches a deny pattern such as .env, *.pem, node_modules, .git, …).",denied:!0}:t instanceof Error?{message:/^HTTP \d+$/.test(t.message)?"The file could not be loaded. Try again.":t.message,denied:!1}:{message:"Unable to read this file.",denied:!1});}).finally(()=>{e||h(!1);}),()=>{e=!0;};},[o,s,v]);let y=(null==f?void 0:f.denied)===!0,w=null!==u?"text"===u.kind?null!=(l=u.extension)?l:"text":"image"===u.kind?u.mime:null!=(r=u.extension)?r:"binary":y?"denied":null!==f?"error":"loading",j=y?"Hidden file":null!=(t=null==u?void 0:u.name)?t:null!==f?"Preview unavailable":"Loading preview",S=(null==u?void 0:u.kind)==="text"&&u.content.length<=2e5,C=void 0!==d&&(null==u?void 0:u.kind)==="text"&&!u.truncated,I=(null==u?void 0:u.kind)==="text"?S?iz(u.content,iM(u.name)):u.content.split("\n").map(e=>[["id",e]]):[];return(0,a.jsxs)("div",{className:"fpv",onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),c());},children:[(0,a.jsxs)("div",{className:"fpv-bar",children:[(0,a.jsx)("button",{className:"fpv-back",type:"button",ref:x,onClick:c,title:"Back to files","aria-label":"Back to files",children:(0,a.jsx)(N.F.back,{size:15})}),(0,a.jsx)(iD,{name:y||null===u?"":u.name}),(0,a.jsx)("span",{className:"fpv-name",title:j,children:j}),(0,a.jsx)("span",{className:"fpv-lang mono",children:w}),(0,a.jsx)("span",{className:"spacer"}),C?(0,a.jsx)("button",{className:"fpv-back",type:"button",onClick:()=>d(s,o),title:"Open in editor","aria-label":"Open in editor",children:(0,a.jsx)(N.F.editor,{size:15})}):null,(0,a.jsx)("button",{className:"fpv-back",type:"button",onClick:c,title:"Close preview","aria-label":"Close preview",children:(0,a.jsx)(N.F.close,{size:15})})]}),m?(0,a.jsx)("div",{className:"fpv-state",role:"status",children:"Loading preview…"}):null,null!==f?(0,a.jsxs)("div",{className:"fpv-state fpv-error",role:"alert",children:[(0,a.jsx)("span",{children:f.message}),f.denied?null:(0,a.jsx)("button",{type:"button",className:"fpv-retry",onClick:()=>b(e=>e+1),children:"Retry"})]}):null,(null==u?void 0:u.kind)==="text"?(0,a.jsxs)(a.Fragment,{children:[u.truncated?(0,a.jsxs)("div",{className:"fpv-banner",children:["Preview truncated at ",iK(u.maxBytes),". Larger files can't be shown in full here."]}):null,S?null:(0,a.jsx)("div",{className:"fpv-banner",children:"Syntax highlighting disabled for large previews."}),(0,a.jsx)("div",{className:"fpv-code mono",tabIndex:0,role:"region","aria-label":`File preview: ${u.name}`,style:{"--fpv-gutter-w":`max(44px, calc(${String(String(I.length).length)}ch + 16px))`},children:I.map((e,t)=>(0,a.jsxs)("div",{className:"fpv-line",children:[(0,a.jsx)("span",{className:"fpv-num",children:t+1}),(0,a.jsx)("span",{className:"fpv-src",children:e.map((e,t)=>(0,a.jsx)("span",{className:`hl-${e[0]}`,children:e[1]},t))})]},t))})]}):null,(null==u?void 0:u.kind)==="image"?(0,a.jsxs)("div",{className:"fpv-image-pane",children:[(0,a.jsx)("div",{className:"fpv-image-card",children:(0,a.jsx)("img",{className:"fpv-image",src:u.dataUrl,alt:u.name})}),(0,a.jsxs)("div",{className:"fpv-meta",children:[(0,a.jsx)(iW,{label:"Type",value:u.mime}),(0,a.jsx)(iW,{label:"Size",value:iK(u.sizeBytes)}),(0,a.jsx)(iW,{label:"Modified",value:iB(u.modifiedAt)})]})]}):null,(null==u?void 0:u.kind)==="binary"?(0,a.jsx)("div",{className:"fpv-meta-pane",children:(0,a.jsxs)("div",{className:"fpv-meta-card",children:[(0,a.jsx)(iD,{name:u.name}),(0,a.jsx)("h3",{children:u.name}),(0,a.jsx)("p",{children:function(e){var t;if("too_large"===e.reason)return`Preview disabled because this file exceeds ${iK(null!=(t=e.maxBytes)?t:0)}.`;let n=iO[function(e){var t;let n=null==(t=e.extension)?void 0:t.trim().toLowerCase();if(void 0!==n&&n.length>0)return n;let l=e.name.lastIndexOf(".");return l>=0?e.name.slice(l+1).trim().toLowerCase():"";}(e)];return void 0!==n?`${n} files up to 2 MB are searchable in Repository Search via bounded text extraction when explicitly connected to a chat. Encrypted, scanned, or larger documents are not extracted — use Local Knowledge for those. No inline preview is available for this format here.`:"No safe text or image preview is available for this file type.";}(u)}),(0,a.jsxs)("div",{className:"fpv-meta",children:[(0,a.jsx)(iW,{label:"Type",value:u.mime}),(0,a.jsx)(iW,{label:"Extension",value:null!=(n=u.extension)?n:"none"}),(0,a.jsx)(iW,{label:"Size",value:iK(u.sizeBytes)}),(0,a.jsx)(iW,{label:"Modified",value:iB(u.modifiedAt)})]})]})}):null]});}function i_(e){let t=e.replace(/[/\\]+$/,""),n=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return n<0?null:0===n?"/":/^[A-Za-z]:$/.test(t.slice(0,n))?`${t.slice(0,n)}\\`:t.slice(0,n);}function iV(e){return 8+18*e;}let iH=new Set(["ArrowDown","ArrowUp","ArrowRight","ArrowLeft","Home","End"]);function iJ(e){var t;let{root:n,activeFilePath:l,openFilesDirectly:r=!1,onActiveFileChange:s,onRootChange:o,onOpenFile:c}=e,d=null==n?void 0:n.trim(),u=void 0!==d&&d.length>0?d:null,[p,m]=(0,i.useState)(null),h=null!=(t=null!=u?u:p)?t:"",[f,g]=(0,i.useState)(null),[v,b]=(0,i.useState)(""),[x,y]=(0,i.useState)(null),[w,j]=(0,i.useState)(null),[S,C]=(0,i.useState)({}),[I,R]=(0,i.useState)(()=>new Set([""])),[E,$]=(0,i.useState)(0),A=(0,i.useRef)(s);A.current=s;let F=(0,i.useRef)(null),T=(0,i.useRef)(null),D=(0,i.useId)();(0,i.useEffect)(()=>{var e,t;if(null!==x)return;let n=T.current;if(null===n)return;T.current=null;let l=null==(e=F.current)?void 0:e.querySelector(`.tr-file[data-path="${"u">typeof CSS&&"function"==typeof CSS.escape?CSS.escape(n):n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"]`);null==(t=null!=l?l:F.current)||t.focus({preventScroll:!0});},[x]),(0,i.useEffect)(()=>{if(null!==u)return;let e=!1;return(0,k.vj)().then(t=>{var n;if(e)return;let l=null==(n=t.projects.find(e=>e.available))?void 0:n.path;m(null!=l?l:null);}).catch(()=>{e||m(null);}),()=>{e=!0;};},[u]);let q=(0,i.useCallback)(async e=>{if(0===h.length)return void C(t=>({...t,[e]:{entries:[],truncated:!1,loading:!1,error:null,notice:"no-root"}}));C(t=>{var n,l,a,i;return{...t,[e]:{entries:null!=(n=null==(a=t[e])?void 0:a.entries)?n:[],truncated:null!=(l=null==(i=t[e])?void 0:i.truncated)&&l,loading:!0,error:null,notice:null}};});try{let n=await(0,k.KD)(h,e);if(""===e){var t;g(n.root),null==(t=A.current)||t.call(A,null,n.root,null),j(null);}C(t=>({...t,[e]:{entries:n.entries,truncated:n.truncated,loading:!1,error:null,notice:null}}));}catch(t){C(n=>{var l,a,i,r;return{...n,[e]:{entries:null!=(l=null==(i=n[e])?void 0:i.entries)?l:[],truncated:null!=(a=null==(r=n[e])?void 0:r.truncated)&&a,loading:!1,error:t instanceof Error?t.message:"Unable to read this folder.",notice:null}};});}},[h]);(0,i.useEffect)(()=>{var e;y(null),j(null),null==(e=A.current)||e.call(A,null,null,null),g(null),R(new Set([""])),C({}),q("");},[h,q,E]);let M=function(e,t){if(null===t||0===t.length)return e;let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return`${e.replace(/[/\\]+$/u,"")}${n}${t.replace(/\//gu,n)}`;}(null!=f?f:h.length>0?h:"",w);(0,i.useEffect)(()=>{b(M);},[M]);let P=(0,i.useCallback)(e=>{let t=e.trim();void 0===o||0===t.length||t!==M&&o(t);},[o,M]),L=(0,i.useCallback)(e=>{var t;y(null),j(e),null==(t=A.current)||t.call(A,null,null!=f?f:h,e),null!==e&&void 0===S[e]&&q(e);},[h,S,q,f]),z=(0,i.useCallback)(()=>{if(null!==w)return void L(function(e){let t=e.replace(/\/+$/u,""),n=t.lastIndexOf("/");if(n<0)return null;let l=t.slice(0,n);return l.length>0?l:null;}(w));let e=i_(null!=f?f:h);null!==e&&P(e);},[h,w,L,P,f]),O=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:S[e];return(0,a.jsxs)("div",{className:"tr-dir",role:0===t?void 0:"group",children:[(null==n?void 0:n.loading)===!0?(0,a.jsx)("div",{className:"files-note",role:"status",style:{paddingLeft:iV(t)+18},children:"Loading…"}):null,(null==n?void 0:n.notice)==="no-root"?(0,a.jsx)("div",{className:"files-note",role:"status",style:{paddingLeft:iV(t)+18},children:void 0!==o?"No folder is open yet. Enter a folder path above and press Open.":"No registered project is available."}):null,(null==n?void 0:n.error)!==null&&(null==n?void 0:n.error)!==void 0?(0,a.jsxs)("div",{className:"files-error",role:"alert",style:{marginLeft:iV(t)},children:[(0,a.jsx)("span",{children:n.error}),(0,a.jsx)("button",{type:"button",className:"files-retry",onClick:()=>{q(e);},children:"Retry"})]}):null,(null==n?void 0:n.truncated)===!0?(0,a.jsxs)("div",{className:"files-note files-warning",role:"status",style:{paddingLeft:iV(t)+18},children:["Showing only the first ",n.entries.length," entries — this folder contains more."]}):null,null==n?void 0:n.entries.map(e=>((e,t)=>{var n;let i=iV(t),s=I.has(e.path),o="This link can't be opened from this folder.";if("directory"===e.kind){let n=S[e.path];return(0,a.jsxs)("div",{className:"tr-row-wrap",children:[(0,a.jsxs)("div",{className:"tr-dir-line",style:{paddingLeft:i},children:[(0,a.jsx)("button",{className:"tr-caret-btn",type:"button",tabIndex:-1,disabled:!e.readable,"aria-label":`${s?"Collapse":"Expand"} folder: ${e.name}`,onClick:()=>(e=>{if(!e.readable)return;let t=I.has(e.path);R(t=>{let n=new Set(t);return n.has(e.path)?n.delete(e.path):n.add(e.path),n;}),t||void 0!==S[e.path]||q(e.path);})(e),title:e.readable?`${s?"Collapse":"Expand"} ${e.path}`:o,children:(0,a.jsx)("span",{className:"tr-caret","data-open":s,children:(0,a.jsx)(N.F.chevronR,{size:11})})}),(0,a.jsxs)("button",{className:"tr-row tr-dir-enter",role:"treeitem","aria-level":t+1,"aria-selected":w===e.path,"data-active":w===e.path,"data-readable":e.readable,"data-path":e.path,type:"button","aria-disabled":!e.readable||void 0,"aria-describedby":e.readable?void 0:D,"aria-expanded":s,onClick:()=>{e.readable&&L(e.path);},title:e.readable?e.path:o,children:[(0,a.jsx)("span",{className:"fi-fallback",style:{color:"var(--accent)"},children:(0,a.jsx)(N.F.folder,{size:14})}),(0,a.jsx)("span",{className:"tr-name tr-folder",children:e.name}),e.symlink?(0,a.jsx)("span",{className:"tr-badge",children:"link"}):null]})]}),s?O(e.path,t+1,n):null]},e.path);}let d=null!=(n=null!=x?x:l)?n:null;return(0,a.jsxs)("button",{className:"tr-row tr-file",role:"treeitem","aria-level":t+1,"aria-selected":d===e.path,"data-active":d===e.path,"data-readable":e.readable,"data-path":e.path,style:{paddingLeft:i},type:"button","aria-disabled":!e.readable||void 0,"aria-describedby":e.readable?void 0:D,onClick:()=>{var t,n;if(!e.readable)return;let l=null!=f?f:h;if(r&&void 0!==c){null==(n=A.current)||n.call(A,e.path,l),c(l,e.path);return;}y(e.path),null==(t=A.current)||t.call(A,e.path,l);},title:e.readable?e.path:o,children:[(0,a.jsx)("span",{className:"tr-caret tr-caret-ghost","aria-hidden":"true",children:(0,a.jsx)(N.F.chevronR,{size:11})}),(0,a.jsx)(iD,{name:e.name}),(0,a.jsx)("span",{className:"tr-name",children:e.name}),e.symlink?(0,a.jsx)("span",{className:"tr-badge",children:"link"}):null,(0,a.jsx)("span",{className:"tr-meta mono",children:function(e){if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=e,l=0;for(;n>=1024&&l<t.length-1;)n/=1024,l+=1;let a=0===l?n.toFixed(0):n.toFixed(n>=10?1:2);return`${a} ${t[l]}`;}(e.sizeBytes)})]},e.path);})(e,t)),void 0===n||n.loading||null!==n.error||null!==n.notice||0!==n.entries.length?null:(0,a.jsx)("div",{className:"files-note",role:"status",style:{paddingLeft:iV(t)+18},children:"Empty folder."})]});};return null!==x?(0,a.jsx)(iU,{root:null!=f?f:h,path:x,onOpenInEditor:c,onClose:()=>{var e;T.current=x,y(null),null==(e=A.current)||e.call(A,null,null!=f?f:h);}}):(0,a.jsxs)("div",{className:"files",ref:F,tabIndex:-1,children:[void 0!==o?(0,a.jsxs)("form",{className:"files-root-bar",role:"group","aria-label":"Folder root",onSubmit:e=>{e.preventDefault(),P(v);},children:[(0,a.jsx)("button",{type:"button",className:"files-root-up",onClick:z,disabled:null===w&&null===i_(null!=f?f:h),title:"Open parent folder","aria-label":"Open parent folder",children:(0,a.jsx)(N.F.arrowUp,{size:13})}),(0,a.jsx)("input",{type:"text",className:"files-root-input mono","aria-label":"Folder path — open any folder on this machine",placeholder:"/path/to/any/folder",spellCheck:!1,value:v,onChange:e=>b(e.target.value)}),(0,a.jsx)("button",{type:"submit",className:"files-root-open",title:"Open this folder",children:"Open"})]}):null,(0,a.jsx)("button",{className:"files-refresh",type:"button",onClick:()=>$(e=>e+1),title:"Refresh folder","aria-label":"Refresh folder",children:(0,a.jsx)(N.F.reset,{size:13})}),(0,a.jsx)("span",{id:D,className:"visually-hidden",children:"This link can't be opened from this folder."}),(0,a.jsx)("div",{className:"tr files-tree",role:"tree","aria-label":"Files",tabIndex:-1,onKeyDown:e=>{if(!iH.has(e.key))return;let t=e.target,n=t instanceof HTMLElement?t.closest("button.tr-row"):null;if(null===n)return;let l=Array.from(e.currentTarget.querySelectorAll("button.tr-row")),a=l.indexOf(n);a<0||(e.preventDefault(),function(e,t,n){var l,a,i,r,s,o;let c=e[t];if(void 0===c)return;let d=null==(l=c.closest(".tr-row-wrap"))?void 0:l.querySelector("button.tr-caret-btn");if("ArrowDown"===n)null==(a=e[t+1])||a.focus();else if("ArrowUp"===n)null==(i=e[t-1])||i.focus();else if("Home"===n)null==(r=e[0])||r.focus();else if("End"===n)null==(s=e[e.length-1])||s.focus();else if("ArrowRight"===n){let n=c.getAttribute("aria-expanded");"false"===n?null==d||d.click():"true"===n&&(null==(o=e[t+1])||o.focus());}else"ArrowLeft"===n&&("true"===c.getAttribute("aria-expanded")?null==d||d.click():function(e,t){var n,l,a,i,r;let s=Number(null!=(n=null==(l=e[t])?void 0:l.getAttribute("aria-level"))?n:"1");for(let n=t-1;n>=0;n-=1)if(Number(null!=(a=null==(i=e[n])?void 0:i.getAttribute("aria-level"))?a:"1")<s){null==(r=e[n])||r.focus();return;}}(e,t));}(l,a,e.key));},children:O(null!=w?w:"",0)})]});}var iY=n(42925);function iX(e){return"object"==typeof e&&null!==e&&!Array.isArray(e);}function iG(e,t,n){return Math.min(n,Math.max(t,e));}function iQ(e){return iG(Math.round(e),15,85);}function iZ(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)"string"==typeof n&&n.length>0&&!t.includes(n)&&t.push(n);return t;}function i0(e,t,n){let l=[],a=e=>{e.length>0&&!l.includes(e)&&l.push(e);};for(let e of null!=n?n:[])a(e);for(let e of t)a(e);return a(e),l;}function i1(e,t,n){var l;let a=i0(t,n);return{id:e,openFiles:a,activeFile:t.length>0?t:null!=(l=a[0])?l:"",tabOrder:a};}function i2(e,t){if(!iX(e))return null;let n="string"==typeof e.id&&e.id.length>0?e.id:t,l="string"==typeof e.activeFile?e.activeFile:"string"==typeof e.file?e.file:"",a=i1(n,l,i0(l,iZ(e.openFiles),iZ(e.tabOrder)));return a.openFiles.length>0||a.activeFile.length>0?a:null;}function i3(e){return"column"===e?"column":"row";}function i4(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return"pane"===e.type?t.push(e.paneId):(i4(e.first,t),i4(e.second,t)),t;}function i6(e,t){return"number"==typeof e.sidebarWidth&&Number.isFinite(e.sidebarWidth)?iG(e.sidebarWidth,t.minSidebarWidth,t.maxSidebarWidth):t.defaultSidebarWidth;}function i5(e,t,n){return"string"==typeof e.activePaneId&&void 0!==t[e.activePaneId]?e.activePaneId:n;}function i8(e){return JSON.stringify({schemaVersion:2,root:e.root,activePaneId:e.activePaneId,tree:e.tree,panes:e.panes,sidebarWidth:Math.round(e.sidebarWidth),sidebarCollapsed:e.sidebarCollapsed});}function i7(e){return i4(e.tree);}function i9(e){return i7(e).map(t=>e.panes[t]).filter(e=>void 0!==e);}function re(e){var t,n;return null!=(t=null!=(n=e.panes[e.activePaneId])?n:i9(e)[0])?t:i1("pane-1","",[]);}function rt(e,t,n){let l=e.panes[t];return void 0===l?e:{...e,panes:{...e.panes,[t]:n(l)}};}function rn(e,t){return e.filter(e=>e!==t);}function rl(e,t,n){let l=rn(e,t),a=void 0===n?l.length:iG(n,0,l.length);return[...l.slice(0,a),t,...l.slice(a)];}function ra(e,t,n){var l;let a=i0(n,t);return{...e,openFiles:a,tabOrder:a,activeFile:n.length>0?n:null!=(l=a[0])?l:""};}function ri(e,t,n,l,a){let i=e.panes[t];if(void 0===i)return e;let r=null!=l?l:i.activeFile;if(0===r.length)return e;let s=function(e){let t=Object.keys(e.panes).length+1;for(;void 0!==e.panes[`pane-${String(t)}`];)t+=1;return`pane-${String(t)}`;}(e),o=i1(s,r,[r]),c={type:"split",id:function(e){let t=new Set(),n=e=>{"split"===e.type&&(t.add(e.id),n(e.first),n(e.second));};n(e);let l=t.size+1;for(;t.has(`split-${String(l)}`);)l+=1;return`split-${String(l)}`;}(e.tree),direction:n,ratio:50,first:{type:"pane",paneId:a?s:t},second:{type:"pane",paneId:a?t:s}};return{...e,activePaneId:s,tree:function e(t,n,l){return"pane"===t.type?t.paneId===n?l:t:{...t,first:e(t.first,n,l),second:e(t.second,n,l)};}(e.tree,t,c),panes:{...e.panes,[s]:o}};}function rr(e,t){var n;if(void 0===e.panes[t]||i7(e).length<=1)return e;let l=function e(t,n){if("pane"===t.type)return t.paneId===n?null:t;let l=e(t.first,n),a=e(t.second,n);return null===l?a:null===a?l:{...t,first:l,second:a};}(e.tree,t);if(null===l)return e;let a={};for(let[n,l]of Object.entries(e.panes))n!==t&&(a[n]=l);let i=e.activePaneId===t&&null!=(n=i4(l)[0])?n:e.activePaneId;return{...e,tree:l,panes:a,activePaneId:i};}function rs(e,t,n){var l,a,i;let r=e.panes[t];if(!(null==r?void 0:r.openFiles.includes(n)))return e;let s=r.tabOrder.indexOf(n),o=rn(r.openFiles,n);if(0===o.length)return i7(e).length>1?rr(e,t):rt(e,t,e=>ra(e,[],""));let c=r.activeFile===n?null!=(l=null!=(a=null!=(i=o[s])?i:o[s-1])?a:o[0])?l:"":r.activeFile;return rt(e,t,e=>ra(e,o,c));}function ro(e,t,n,l,a){if(t===n)return rt(e,n,e=>ra(e,rl(e.tabOrder,l,a),l));let i=e.panes[t],r=e.panes[n];if(void 0===i||void 0===r||!i.openFiles.includes(l))return e;let s=rs(e,t,l);return void 0===s.panes[n]?s:{...(s=rt(s,n,e=>ra(e,rl(e.tabOrder,l,a),l))),activePaneId:n};}let rc=new Set(["open-file","select-file","close-tab","reorder-tab"]),rd=new Set(["close-pane","move-tab","drop-tab","split-pane"]);function ru(e,t){if(rc.has(t.type)){switch(t.type){case"open-file":return rt(e,t.paneId,e=>ra(e,i0(t.file,e.openFiles),t.file));case"select-file":return rt({...e,activePaneId:t.paneId},t.paneId,e=>e.openFiles.includes(t.file)?ra(e,e.openFiles,t.file):e);case"close-tab":return rs(e,t.paneId,t.file);case"reorder-tab":return rt(e,t.paneId,e=>e.openFiles.includes(t.file)?ra(e,rl(e.tabOrder,t.file,t.targetIndex),t.file):e);}return;}return rd.has(t.type)?function(e,t){switch(t.type){case"close-pane":return rr(e,t.paneId);case"move-tab":return ro(e,t.fromPaneId,t.toPaneId,t.file,t.targetIndex);case"drop-tab":var n;return"center"===(n=t.intent).zone?ro(e,n.fromPaneId,n.toPaneId,n.file,n.targetIndex):ri(ro(e,n.fromPaneId,n.fromPaneId,n.file),n.toPaneId,"top"===n.zone||"bottom"===n.zone?"column":"row",n.file,"top"===n.zone||"left"===n.zone);case"split-pane":return ri(e,t.paneId,t.direction,t.file,!1);}}(e,t):function(e,t){var n,l,a;switch(t.type){case"set-active-pane":return void 0===e.panes[t.paneId]?e:{...e,activePaneId:t.paneId};case"resize-split":return{...e,tree:function e(t,n,l){return"pane"===t.type?t:{...t,ratio:t.id===n?iQ(l):t.ratio,first:e(t.first,n,l),second:e(t.second,n,l)};}(e.tree,t.splitId,t.ratio)};case"set-sidebar":return{...e,sidebarWidth:null!=(n=t.width)?n:e.sidebarWidth,sidebarCollapsed:null!=(l=t.collapsed)?l:e.sidebarCollapsed};case"replace-root":let i;return i=i1("pane-1","",[]),{schemaVersion:2,root:t.root,activePaneId:i.id,tree:{type:"pane",paneId:i.id},panes:{[i.id]:i},sidebarWidth:null!=(a=t.sidebarWidth)?a:e.sidebarWidth,sidebarCollapsed:!1};}}(e,t);}function rp(e){let t=[];for(let n of i9(e))for(let e of n.openFiles)e.length>0&&!t.includes(e)&&t.push(e);return t;}let rm=(0,iY.default)(()=>n.e(9385).then(n.bind(n,19385)),{loadableGenerated:{webpack:()=>[19385]},ssr:!1,loading:()=>(0,a.jsx)("div",{className:"ed-host-loading","aria-hidden":"true"})});function rh(e,t,n){return Math.min(n,Math.max(t,e));}function rf(e){return e.trim().replace(/\\/gu,"/").replace(/\/+$/u,"");}function rg(e,t){var n;let l=null!=(n=null==t?void 0:t.trim())?n:"";if(0===e.trim().length||0===l.length)return l;let a=rf(e),i=rf(l),r=a.toLowerCase(),s=i.toLowerCase();return s===r?"":s.startsWith(`${r}/`)?i.slice(a.length+1).replace(/^\/+/u,""):l;}function rv(e,t,n){let l=[],a=t=>{let n=rg(e,t);0===n.length||l.includes(n)||l.push(n);};for(let e of null!=n?n:[])a(e);return a(t),l;}function rb(e,t){let n={};for(let[l,a]of Object.entries(t.panes))n[l]=function(e,t){let n=rv(e,t.activeFile,t.openFiles),l=rg(e,t.activeFile)||n[0]||"",a=rv(e,l,t.tabOrder);return{...t,openFiles:n,activeFile:l,tabOrder:a.length>0?a:n};}(e,a);return{...t,root:e,panes:n};}function rx(e){return rb(e.root,function(e){var t;let n=function(e){if(void 0!==e.layoutJson&&e.layoutJson.trim().length>0)try{let n=JSON.parse(e.layoutJson);if(iX(n)){var t;let l=null!=(t=n.schemaVersion)?t:n.version,a=2===l||"2"===l?function(e,t,n){var l,a;let i=function(e){if(!iX(e))return{};let t={};for(let[n,l]of Object.entries(e)){let e=i2(l,n);null!==e&&(t[e.id]=e);}return t;}(t.panes),r=Object.keys(i)[0];if(void 0===r)return null;let s=null!=(l=function e(t,n){var l;return iX(t)?null!==(l="pane"===t.type&&"string"==typeof t.paneId&&void 0!==n[t.paneId]?{type:"pane",paneId:t.paneId}:null)&&void 0!==l?l:function(t,n){if("split"!==t.type)return null;let l=e(t.first,n),a=e(t.second,n);if(null===l||null===a)return null;let i="string"==typeof t.id&&t.id.length>0?t.id:"split-1",r="number"==typeof t.ratio&&Number.isFinite(t.ratio)?t.ratio:50;return{type:"split",id:i,direction:i3(t.direction),ratio:iQ(r),first:l,second:a};}(t,n):null;}(t.tree,i))?l:{type:"pane",paneId:r},o=function(e,t){let n={};for(let l of new Set(i4(e))){let e=t[l];void 0!==e&&(n[l]=e);}return n;}(s,i);return{schemaVersion:2,root:e,activePaneId:i5(t,o,null!=(a=i4(s)[0])?a:r),tree:s,panes:o,sidebarWidth:i6(t,n),sidebarCollapsed:!0===t.sidebarCollapsed};}(e.root,n,e):function(e,t,n){var l;let a=Array.isArray(l=t.panes)?l.map((e,t)=>i2(e,`pane-${String(t+1)}`)).filter(e=>null!==e):[];if(0===a.length)return null;let i={};for(let e of a)i[e.id]=e;let r=a[0];if(void 0===r)return null;let s=function(e,t,n){if(void 0===t)return{type:"pane",paneId:e.id};let l="number"==typeof n.splitRatio&&Number.isFinite(n.splitRatio)?iQ(n.splitRatio):50;return{type:"split",id:"split-1",direction:i3(n.direction),ratio:l,first:{type:"pane",paneId:e.id},second:{type:"pane",paneId:t.id}};}(r,a[1],t);return{schemaVersion:2,root:e,activePaneId:i5(t,i,r.id),tree:s,panes:i,sidebarWidth:i6(t,n),sidebarCollapsed:!0===t.sidebarCollapsed};}(e.root,n,e);if(null!==a)return a;}}catch{}return null;}(e);if(null!==n)return n;let l=i1("pane-1",e.file.length>0?e.file:null!=(t=e.openFiles[0])?t:"",e.openFiles);return{schemaVersion:2,root:e.root,activePaneId:l.id,tree:{type:"pane",paneId:l.id},panes:{[l.id]:l},sidebarWidth:e.defaultSidebarWidth,sidebarCollapsed:!1};}({root:e.root,file:e.file,openFiles:e.openFiles,layoutJson:e.layoutJson,defaultSidebarWidth:260,minSidebarWidth:180,maxSidebarWidth:440}));}function ry(e){let t=new Set();for(let n of Object.values(e))for(let e of Object.keys(n))t.add(e);return[...t];}function rw(e){let t="editor-dirty-close-title",n=(0,i.useRef)(null);return(0,i.useEffect)(()=>{var e;null==(e=n.current)||e.focus();},[]),(0,i.useEffect)(()=>{let t=t=>{"Escape"!==t.key||e.pending.saving||e.onCancel();};return document.addEventListener("keydown",t),()=>{document.removeEventListener("keydown",t);};},[e]),(0,a.jsx)("div",{className:"ed-dialog-backdrop",role:"presentation",children:(0,a.jsxs)("div",{className:"ed-dirty-dialog",ref:n,role:"dialog","aria-modal":"true","aria-labelledby":t,tabIndex:-1,children:[(0,a.jsx)("h2",{id:t,children:"Unsaved editor changes"}),(0,a.jsx)("p",{children:"Choose how to handle these files before continuing."}),(0,a.jsx)("ul",{children:e.pending.dirtyFiles.map(e=>(0,a.jsx)("li",{children:e},e))}),void 0!==e.pending.error?(0,a.jsx)("p",{role:"alert",children:e.pending.error}):null,(0,a.jsxs)("div",{className:"ed-dialog-actions",children:[(0,a.jsx)("button",{type:"button",className:"ed-save",onClick:e.onSave,disabled:e.pending.saving,children:e.pending.saving?"Saving...":"Save"}),(0,a.jsx)("button",{type:"button",className:"ed-reload",onClick:e.onDiscard,disabled:e.pending.saving,children:"Discard"}),(0,a.jsx)("button",{type:"button",className:"ed-icon-action",onClick:e.onCancel,disabled:e.pending.saving,children:"Cancel"})]})]})});}function rj(e){var t,n;let{root:l,file:r,openFiles:s,layoutJson:o,onWorkspaceChange:c,...d}=e,u=null!=(t=null==l?void 0:l.trim())?t:"",p=rg(u,r),m=rv(u,p,s),h=rx({root:u,file:p,openFiles:m,layoutJson:o}),[f,g]=(0,i.useState)(u),[v,b]=(0,i.useState)(h),[x,y]=(0,i.useState)({}),[w,j]=(0,i.useState)(null),[k,S]=(0,i.useState)(null),[C,I]=(0,i.useState)(null),R=(0,i.useRef)(0),E=(0,i.useRef)(new Map()),$=(0,i.useRef)(null!=(n=null==l?void 0:l.trim())?n:""),A=(0,i.useRef)(null),F=(0,i.useCallback)((e,t)=>{var n;let l=re(t);return{root:e,file:l.activeFile.length>0?l.activeFile:void 0,openFiles:(n=rp(t)).length>0?n:void 0,layoutJson:i8(t)};},[]),T=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:f,n=rb(t,e);b(n),t.length>0&&(null==c||c(F(t,n)));},[F,c,f]);(0,i.useEffect)(()=>{var e,t;let n=null!=(e=null==l?void 0:l.trim())?e:"",a=rg(n,r),i=rv(n,a,s),d=rx({root:n,file:a,openFiles:i,layoutJson:o}),u=re(d),p=rp(d),m=$.current!==n;if($.current=n,g(n),b(d),m&&y({}),0===n.length||void 0===c)return;let h=(null!=(t=null==r?void 0:r.trim())?t:"")!==u.activeFile,f=void 0===s?0!==p.length:!(s.length===p.length&&s.every((e,t)=>e===p[t])),v=o!==i8(d);(h||f||v)&&c(F(n,d));},[F,s,r,o,c,l]);let D=(0,i.useMemo)(()=>ry(x),[x]),q=re(v),M=q.activeFile;(0,i.useEffect)(()=>{if(0===D.length)return;let e=e=>{e.preventDefault(),e.returnValue="";};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e);};},[D.length]);let P=(0,i.useCallback)((e,t,n)=>{y(l=>{var a;let i=null!=(a=l[e])?a:{};if(n)return!0===i[t]?l:{...l,[e]:{...i,[t]:!0}};if(!0!==i[t])return l;let{[t]:r,...s}=i;return{...l,[e]:s};});},[]),L=(0,i.useCallback)((e,t)=>{R.current+=1;let n=R.current;return T(ru(v,{type:"select-file",paneId:e,file:t})),I({id:n,paneId:e,file:t}),new Promise(e=>{E.current.set(n,e);});},[T,v]),z=(0,i.useCallback)((e,t,n,l)=>{let a=E.current.get(e);E.current.delete(e),(null==C?void 0:C.id)===e&&I(null),l&&P(t,n,!1),null==a||a(l);},[P,null==C?void 0:C.id]),O=(0,i.useCallback)(e=>{var t,n,l;let a,i=new Set(ry(x)),r="root-change"===e.reason||"window-close"===e.reason?e.files.filter(e=>i.has(e)):(t=e.paneId,n=e.files,a=null!=(l=x[t])?l:{},n.filter(e=>!0===a[e]));return 0===r.length?(e.apply(),!0):(j({intent:function(e){let t=[];for(let n of e.files)n.length>0&&!t.includes(n)&&t.push(n);return{paneId:e.paneId,files:t,reason:e.reason};}({paneId:e.paneId,files:r,reason:e.reason}),apply:e.apply,dirtyFiles:r,saving:!1}),!1);},[x]),K=(0,i.useCallback)(()=>{null===w||w.saving||(j({...w,saving:!0,error:void 0}),(async()=>{for(let n of w.dirtyFiles){var e,t;let l=null!=(e=null==(t=Object.entries(x).find(e=>{let[,t]=e;return!0===t[n];}))?void 0:t[0])?e:w.intent.paneId;if(!(await L(l,n)))return void j({...w,saving:!1,error:"Save failed. The close action was not applied."});}w.apply(),j(null);})());},[x,w,L]),B=(0,i.useCallback)(()=>{if(null!==w&&!w.saving){for(let e of w.dirtyFiles)for(let[t,n]of Object.entries(x))!0===n[e]&&P(t,e,!1);w.apply(),j(null);}},[x,P,w]),W=(0,i.useCallback)(()=>{(null==w?void 0:w.saving)!==!0&&j(null);},[null==w?void 0:w.saving]),U=(0,i.useCallback)(e=>{var t;let n=e.trim();0===n.length||O({paneId:null!=(t=i7(v)[0])?t:v.activePaneId,files:D,reason:"root-change",apply:()=>{let e=ru(v,{type:"replace-root",root:n,sidebarWidth:v.sidebarWidth});g(n),y({}),T(e,n);}});},[T,D,v,O]),_=(0,i.useCallback)((e,t)=>{let n=e.trim(),l=rg(n,t);if(0===n.length||0===l.length)return;let a=ru(v,{type:"open-file",paneId:q.id,file:l});g(n),T(a,n);},[T,q.id,v]),V=(0,i.useCallback)((e,t)=>{0!==f.length&&0!==t.length&&T(ru(v,{type:"select-file",paneId:e,file:t}));},[T,v,f]),H=(0,i.useCallback)(async(e,t)=>O({paneId:e,files:[t],reason:"tab-close",apply:()=>{P(e,t,!1),T(ru(v,{type:"close-tab",paneId:e,file:t}));}}),[T,v,P,O]),J=(0,i.useCallback)((e,t)=>{T(ru(v,{type:"split-pane",paneId:e,direction:t}));},[T,v]),Y=(0,i.useCallback)(e=>{let t=v.panes[e];void 0!==t&&O({paneId:e,files:t.openFiles,reason:"pane-close",apply:()=>{y(t=>{let{[e]:n,...l}=t;return l;}),T(ru(v,{type:"close-pane",paneId:e}));}});},[T,v,O]),X=(0,i.useCallback)(()=>{T(ru(v,{type:"set-sidebar",collapsed:!v.sidebarCollapsed}));},[T,v]),G=(0,i.useCallback)(e=>{null===A.current||T(ru(v,{type:"set-sidebar",width:rh(e-A.current.getBoundingClientRect().left,180,440),collapsed:!1}));},[T,v]),Q=(0,i.useCallback)(e=>{1===e.buttons&&G(e.clientX);},[G]),Z=(0,i.useCallback)((e,t,n,l)=>{let a="row"===e.direction?(n-t.left)/t.width*100:(l-t.top)/t.height*100;T(ru(v,{type:"resize-split",splitId:e.id,ratio:rh(a,15,85)}));},[T,v]),ee=(0,i.useCallback)(e=>{e.preventDefault();let t=e=>G(e.clientX),n=()=>{window.removeEventListener("mousemove",t),window.removeEventListener("mouseup",n);};window.addEventListener("mousemove",t),window.addEventListener("mouseup",n,{once:!0});},[G]),et=(0,i.useCallback)((e,t)=>{t.preventDefault();let n=t.currentTarget.parentElement;if(null===n)return;let l=t=>Z(e,n.getBoundingClientRect(),t.clientX,t.clientY),a=()=>{window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",a);};window.addEventListener("mousemove",l),window.addEventListener("mouseup",a,{once:!0});},[Z]),en=(0,i.useCallback)(e=>{e.currentTarget.setPointerCapture(e.pointerId);},[]),el=(0,i.useCallback)(e=>{e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId);},[]),ea=(0,i.useCallback)((e,t,n)=>{if(!n.altKey)return;let l=v.panes[e];if(void 0!==l&&("ArrowLeft"===n.key||"ArrowRight"===n.key)){n.preventDefault();let a=i7(v);if(n.shiftKey){let l=a.indexOf(e),i="ArrowLeft"===n.key?a[l-1]:a[l+1];void 0!==i&&T(ru(v,{type:"move-tab",fromPaneId:e,toPaneId:i,file:t}));return;}let i=l.tabOrder.indexOf(t);T(ru(v,{type:"reorder-tab",paneId:e,file:t,targetIndex:"ArrowLeft"===n.key?i-1:i+1}));}},[T,v]),ei=(0,i.useCallback)((e,t,n)=>{n.preventDefault(),null!==k&&(T(ru(v,{type:"drop-tab",intent:{fromPaneId:k.paneId,toPaneId:e,file:k.file,zone:t}})),S(null));},[T,k,v]);if(0===f.length)return(0,a.jsx)(rm,{...d});let er=e=>{if("pane"===e.type){var t;let n,l,i=v.panes[e.paneId];return void 0===i?null:(n=i9(v).map(e=>({paneId:e.id,activeFile:e.activeFile.length>0?e.activeFile:null,openFiles:e.openFiles})),l={...d,root:f,...(i.activeFile.length>0?{file:i.activeFile}:{}),openFiles:i.openFiles,dirtyFiles:D,windowId:`${null!=(t=d.windowId)?t:"editor"}-${i.id}`,paneId:i.id,layoutPanes:n,activePaneId:v.activePaneId,onSelectOpenFile:e=>V(i.id,e),onCloseOpenFile:e=>H(i.id,e),onDirtyChange:(e,t)=>P(i.id,e,t),toolbarExtras:(0,a.jsxs)("span",{className:"ed-pane-actions","aria-label":"Editor split controls",children:[(0,a.jsx)("button",{type:"button",className:"ed-icon-action","aria-label":`Split ${i.activeFile||"editor"} right`,title:"Split right",onClick:()=>J(i.id,"row"),children:(0,a.jsx)(N.F.split,{size:14})}),(0,a.jsx)("button",{type:"button",className:"ed-icon-action","aria-label":`Split ${i.activeFile||"editor"} down`,title:"Split down",onClick:()=>J(i.id,"column"),children:(0,a.jsx)(N.F.tile,{size:14})}),i7(v).length>1?(0,a.jsx)("button",{type:"button",className:"ed-icon-action","aria-label":`Close split ${i.activeFile||"editor"}`,title:"Close split",onClick:()=>Y(i.id),children:(0,a.jsx)(N.F.close,{size:14})}):null]}),externalSaveRequest:null!==C&&C.paneId===i.id?C:void 0,onExternalSaveComplete:z},(0,a.jsxs)("section",{className:"ed-pane","data-active":i.id===v.activePaneId?"true":"false","data-dragging":null===k?"false":"true",children:[(0,a.jsx)("div",{className:"ed-pane-drop-zones","aria-hidden":"true",children:["left","right","top","bottom","center"].map(e=>(0,a.jsx)("button",{type:"button",className:`ed-pane-drop-zone ${e}`,tabIndex:-1,"aria-label":`Drop tab ${e}`,onDragOver:e=>e.preventDefault(),onDrop:t=>ei(i.id,e,t)},e))}),(0,a.jsx)(rm,{...l,renderTabHandle:(e,t,n)=>({draggable:!0,onDragStart:t=>{t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",e),S({paneId:i.id,file:e});},onDragEnd:()=>S(null),onKeyDown:t=>ea(i.id,e,t),"data-active":t?"true":"false","data-dirty":n?"true":"false"})})]},i.id));}return(0,a.jsxs)("div",{className:`ed-panes ${e.direction}`,"data-split-id":e.id,style:{"--ed-split-ratio":`${String(e.ratio)}%`},children:[er(e.first),(0,a.jsx)("button",{type:"button",className:"ed-pane-resizer","aria-label":"Resize editor split",title:"Resize editor split",onPointerDown:en,onPointerMove:t=>{if(1!==t.buttons)return;let n=t.currentTarget.parentElement;null!==n&&Z(e,n.getBoundingClientRect(),t.clientX,t.clientY);},onPointerUp:el,onPointerCancel:el,onMouseDown:t=>et(e,t)}),er(e.second)]});},es=1===i7(v).length;return(0,a.jsxs)("div",{className:`editor-workspace${v.sidebarCollapsed?" sidebar-collapsed":""}`,ref:A,style:{"--ed-sidebar-width":`${String(v.sidebarWidth)}px`},children:[v.sidebarCollapsed?(0,a.jsx)("button",{type:"button",className:"ed-sidebar-restore","aria-label":"Show project tree",title:"Show project tree",onClick:X,children:(0,a.jsx)(N.F.sidebar,{size:15})}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("aside",{className:"ed-sidebar","aria-label":"Editor files",children:[(0,a.jsx)("div",{className:"ed-sidebar-chrome",children:(0,a.jsx)("button",{type:"button",className:"ed-icon-action","aria-label":"Hide project tree",title:"Hide project tree",onClick:X,children:(0,a.jsx)(N.F.sidebar,{size:14})})}),(0,a.jsx)(iJ,{root:f,activeFilePath:M.length>0?M:void 0,openFilesDirectly:!0,onRootChange:U,onOpenFile:_})]}),(0,a.jsx)("button",{type:"button",className:"ed-sidebar-resizer","aria-label":"Resize project tree",title:"Resize project tree",onPointerDown:en,onPointerMove:Q,onPointerUp:el,onPointerCancel:el,onMouseDown:ee})]}),(0,a.jsx)("div",{className:"ed-main",children:(0,a.jsx)("div",{className:`ed-panes ed-panes-root${es?" single":""}`,children:er(v.tree)})}),null!==w?(0,a.jsx)(rw,{pending:w,onSave:K,onDiscard:B,onCancel:W}):null]});}async function rk(e,t){var n,l;let a=(null!=(n=null==t?void 0:t.method)?n:"GET").toUpperCase(),i="GET"!==a&&"HEAD"!==a,r=await fetch(e,{...t,headers:{Accept:"application/json",...(i?{"Content-Type":"application/json"}:{}),...(i?{"X-Keiko-CSRF":"1"}:{}),...(null!=(l=null==t?void 0:t.headers)?l:{})}});if(!r.ok){let e="INTERNAL",t=`HTTP ${r.status.toString()}`;try{let n=await r.json();e=n.error.code,t=n.error.message;}catch{}throw new k.hD(e,t,r.status);}if(204!==r.status)return r.json();}async function rN(e){return rk(`/api/browser/status?port=${encodeURIComponent(String(e))}`);}async function rS(e){return rk("/api/browser/sessions",{method:"POST",body:JSON.stringify({port:e})});}async function rC(e){await rk(`/api/browser/sessions/${encodeURIComponent(e)}`,{method:"DELETE"});}async function rI(e,t){return rk(`/api/browser/sessions/${encodeURIComponent(e)}/navigate`,{method:"POST",body:JSON.stringify({url:t})});}async function rR(e){return rk(`/api/browser/sessions/${encodeURIComponent(e)}/screenshot`,{method:"POST",body:JSON.stringify({})});}async function rE(e,t){return rk(`/api/browser/sessions/${encodeURIComponent(e)}/apply`,{method:"POST",body:JSON.stringify({captureSeq:t})});}async function r$(e){return rk(`/api/browser/sessions/${encodeURIComponent(e)}/content`,{method:"POST",body:JSON.stringify({})});}function rA(e){return e instanceof k.hD?{code:e.code,message:e.message}:e instanceof Error?{code:"INTERNAL",message:e.message}:{code:"INTERNAL",message:"Unexpected error."};}function rF(e){var t,n;let l=null!=(t=e.cdpPort)?t:9222,r=null!=(n=e.url)?n:"http://localhost:5173",[s,o]=(0,i.useState)(String(l)),[c,d]=(0,i.useState)(r),[u,p]=(0,i.useState)(null),[m,h]=(0,i.useState)(null),[f,g]=(0,i.useState)(!1),[v,b]=(0,i.useState)(null),[x,y]=(0,i.useState)(null),[w,j]=(0,i.useState)([]),[k,N]=(0,i.useState)(null),[S,C]=(0,i.useState)(null),[I,R]=(0,i.useState)(null),E=(0,i.useRef)(null),$=(0,i.useCallback)(()=>{y(null);},[]),A=(0,i.useCallback)(e=>{j(t=>{let n=[...t,e];return n.length>50?n.slice(n.length-50):n;}),"navigated"===e.kind&&"string"==typeof e.payload.originOnly&&R(e.payload.originOnly),"error"===e.kind&&y({code:"string"==typeof e.payload.code?e.payload.code:"INTERNAL",message:"string"==typeof e.payload.message?e.payload.message:"Error."});},[]);(0,i.useEffect)(()=>{var e,t;if(null===u){null==(e=E.current)||e.close(),E.current=null;return;}let n=new EventSource((t=u.sessionId,`/api/browser/sessions/${encodeURIComponent(t)}/events`));for(let e of["session-opened","navigated","screenshot-captured","page-content-captured","session-closed","trust-warning","error"])n.addEventListener(`browser:${e}`,e=>{try{let t=JSON.parse(e.data);A(t);}catch{}});return E.current=n,()=>{n.close(),E.current=null;};},[u,A]);let F=(0,i.useCallback)(async()=>{$(),g(!0);try{let e=Number.parseInt(s,10),t=await rN(e);h(t);}catch(e){y(rA(e));}finally{g(!1);}},[s,$]),T=(0,i.useCallback)(async()=>{$(),g(!0);try{let e=Number.parseInt(s,10),t=await rS(e);p(t),j([]),C(null),R(null);}catch(e){y(rA(e));}finally{g(!1);}},[s,$]),D=(0,i.useCallback)(async()=>{if(null!==u){$(),g(!0);try{await rC(u.sessionId),p(null),N(null),C(null),R(null);}catch(e){y(rA(e));}finally{g(!1);}}},[u,$]),q=(0,i.useCallback)(async()=>{if(null!==u){$(),g(!0);try{let e=await rI(u.sessionId,c);R(e.originOnly);}catch(e){y(rA(e));}finally{g(!1);}}},[u,c,$]),M=(0,i.useCallback)(async()=>{if(null!==u){$(),g(!0);try{let e=await rR(u.sessionId);e.persisted||N({seq:e.seq,dataBase64:e.dataBase64});}catch(e){y(rA(e));}finally{g(!1);}}},[u,$]),P=(0,i.useCallback)(async()=>{if(null!==u&&null!==k){$(),g(!0);try{let e=await rE(u.sessionId,k.seq);e.persisted&&C(e.path),N(null);}catch(e){y(rA(e));}finally{g(!1);}}},[u,k,$]),L=(0,i.useCallback)(async()=>{if(null!==u){$(),g(!0);try{await r$(u.sessionId);}catch(e){y(rA(e));}finally{g(!1);}}},[u,$]),z=(0,i.useMemo)(()=>f||null!==u,[f,u]),O=(0,i.useMemo)(()=>f||null===u,[f,u]),K=f||null!==u,B=f||null===k,W=f&&null!==v?v:null!==k?"Screenshot ready (dry-run) — press Apply to persist.":null!==S?`Persisted as ${S}.`:null!==I?`Current origin: ${I}`:null!==m&&null===u?`Reachable: ${m.reachable?"yes":"no"}`:"";return(0,a.jsxs)("div",{className:"browser",children:[(0,a.jsxs)("div",{className:"bw-bar",children:[(0,a.jsx)("span",{className:"bw-dot",style:{background:null===u?"var(--line-strong)":"var(--ok)"},"aria-hidden":"true"}),(0,a.jsxs)("label",{className:"bw-field",children:[(0,a.jsx)("span",{className:"bw-field-label",children:"Port"}),(0,a.jsx)("input",{type:"text",inputMode:"numeric",className:"bw-input",value:s,onChange:e=>o(e.target.value),disabled:null!==u||f})]}),(0,a.jsxs)("label",{className:"bw-field bw-field-url",children:[(0,a.jsx)("span",{className:"bw-field-label",children:"URL"}),(0,a.jsx)("input",{type:"url",className:"bw-input bw-input-url",value:c,onChange:e=>d(e.target.value),disabled:f})]})]}),(0,a.jsxs)("div",{className:"bw-actions",role:"group","aria-label":"Browser actions",children:[(0,a.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{K||(b("Checking Chrome…"),F());},"aria-disabled":K,children:"Check"}),(0,a.jsx)("button",{type:"button",className:"bw-btn bw-btn-primary",onClick:()=>{z||(b("Opening session…"),T());},"aria-disabled":z,children:"Open session"}),(0,a.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{O||(b("Navigating…"),q());},"aria-disabled":O,children:"Navigate"}),(0,a.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{O||(b("Capturing screenshot…"),M());},"aria-disabled":O,children:"Screenshot"}),(0,a.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{B||(b("Applying screenshot…"),P());},"aria-disabled":B,children:"Apply"}),(0,a.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{O||(b("Capturing HTML…"),L());},"aria-disabled":O,children:"Capture HTML"}),(0,a.jsx)("button",{type:"button",className:"bw-btn bw-btn-danger",onClick:()=>{O||(b("Closing session…"),D());},"aria-disabled":O,children:"Close"})]}),(0,a.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:W}),f&&null!==v?(0,a.jsx)("p",{className:"bw-status",children:v}):null,null!==m&&null===u?(0,a.jsxs)("p",{className:"bw-status",children:["Reachable: ",m.reachable?"yes":"no",null===m.browserVersion?"":` — ${m.browserVersion}`]}):null,null!==I?(0,a.jsxs)("p",{className:"bw-status",children:["Current origin: ",(0,a.jsx)("span",{className:"mono",children:I})]}):null,null!==k?(0,a.jsx)("p",{className:"bw-status",children:"Screenshot ready (dry-run) — press Apply to persist."}):null,null!==S?(0,a.jsxs)("p",{className:"bw-status",children:["Persisted as ",(0,a.jsx)("span",{className:"mono",children:S}),"."]}):null,null!==x?(0,a.jsxs)("div",{className:"bw-error",role:"alert",children:[x.message," ",(0,a.jsxs)("span",{className:"err-code mono",children:["(",x.code,")"]})]}):null,(0,a.jsx)("div",{className:"bw-view",children:null!==k?(0,a.jsx)("img",{className:"bw-screenshot",src:`data:image/png;base64,${k.dataBase64}`,alt:"Pending screenshot preview"}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("div",{className:"ph-stripes","aria-hidden":"true"}),(0,a.jsx)("div",{className:"bw-overlay mono",children:null===u?"No session — choose a port and press Open session":"Session open — use Screenshot to capture a preview"})]})}),(0,a.jsx)("div",{className:"bw-log",role:"log","aria-label":"Browser event log",children:(0,a.jsx)("ul",{className:"bw-log-list",children:w.slice(-10).reverse().map((e,t)=>(0,a.jsxs)("li",{className:"bw-log-item",children:[(0,a.jsx)("span",{className:"bw-log-kind",children:function(e){switch(e){case"session-opened":return"session opened";case"navigated":return"navigated";case"screenshot-captured":return"screenshot captured";case"page-content-captured":return"content captured";case"session-closed":return"session closed";case"trust-warning":return"trust warning";case"error":return"error";}}(e.kind)}),(0,a.jsx)("span",{className:"bw-log-detail mono",children:function(e){let t=e.payload;if("navigated"===e.kind){let e="string"==typeof t.originOnly?t.originOnly:"",n="number"==typeof t.httpStatus?` (${String(t.httpStatus)})`:"";return`${e}${n}`;}return"screenshot-captured"===e.kind?!0===t.persisted?"persisted":"dry-run":"page-content-captured"===e.kind?"number"==typeof t.byteLength?`${String(t.byteLength)} bytes`:"":"error"===e.kind||"trust-warning"===e.kind?"string"==typeof t.message?t.message:"string"==typeof t.warning?t.warning:"":"";}(e)})]},`${String(e.kind)}-${String(t)}`))})})]});}async function rT(e,t){var n,l;let a=(null!=(n=null==t?void 0:t.method)?n:"GET").toUpperCase(),i="GET"!==a&&"HEAD"!==a,r=await fetch(e,{...t,headers:{Accept:"application/json",...(i?{"Content-Type":"application/json"}:{}),...(i?{"X-Keiko-CSRF":"1"}:{}),...(null!=(l=null==t?void 0:t.headers)?l:{})}});if(!r.ok){let e="INTERNAL",t=`HTTP ${r.status.toString()}`;try{let n=await r.json();e=n.error.code,t=n.error.message;}catch{}throw new k.hD(e,t,r.status);}if(204!==r.status)return r.json();}async function rD(){return rT("/api/terminal/policy");}async function rq(e,t){let n=new URLSearchParams();return n.set("projectId",e),void 0!==t&&t.length>0&&n.set("path",t),rT(`/api/terminal/directories?${n.toString()}`);}async function rM(e){return rT("/api/terminal/executions",{method:"POST",body:JSON.stringify(e)});}async function rP(e){await rT(`/api/terminal/executions/${encodeURIComponent(e)}`,{method:"DELETE"});}function rL(e){return e instanceof k.hD?{code:e.code,message:e.message}:e instanceof Error?{code:"INTERNAL",message:e.message}:{code:"INTERNAL",message:"Unexpected error."};}function rz(e){var t,n,l;let[r,s]=(0,i.useState)(null),[o,c]=(0,i.useState)(""),[d,u]=(0,i.useState)(""),[p,m]=(0,i.useState)(null!=(t=e.cwd)?t:""),[h,f]=(0,i.useState)(null!=(n=e.projectPath)?n:""),[g,v]=(0,i.useState)(!1),[b,x]=(0,i.useState)(null),[y,w]=(0,i.useState)(null),[j,k]=(0,i.useState)(null),[N,S]=(0,i.useState)([]),C=(0,i.useRef)(null),I=(0,i.useRef)(!1),R=(0,i.useRef)(null),[E,$]=(0,i.useState)([]);(0,i.useEffect)(()=>{let e=!1;return rD().then(t=>{e||(s(t),c(e=>{var n;return e.length>0?e:null!=(n=t.commands[0])?n:"";}));}).catch(t=>{e||k(rL(t));}),()=>{e=!0;};},[]),(0,i.useEffect)(()=>{if(0===h.length)return void $([]);let e=!1;return rq(h,p.length>0?p:void 0).then(t=>{e||$(t.entries);}).catch(()=>{e||$([]);}),()=>{e=!0;};},[h,p]),(0,i.useEffect)(()=>{let e=new EventSource("/api/terminal/events");C.current=e;let t=e=>{try{let t=JSON.parse(e.data);if("execution-started"===t.kind&&I.current){let e=t.payload;"string"==typeof e.requestId&&e.requestId===R.current&&x(e=>null!==e?e:t.executionId);}if("execution-completed"===t.kind||"execution-failed"===t.kind||"execution-cancelled"===t.kind){let e=t.payload;"string"==typeof e.requestId&&e.requestId===R.current&&x(e=>null===e||e!==t.executionId?e:null);}S(e=>{let n=[t,...e];return n.length>30?n.slice(0,30):n;});}catch{}};for(let n of["execution-started","execution-completed","execution-failed","execution-cancelled"])e.addEventListener(`terminal:${n}`,t);return()=>{e.close(),C.current=null;};},[]);let A=(0,i.useCallback)(async e=>{let t;if(e.preventDefault(),g)return;k(null),w(null),x(null);let n="function"==typeof crypto.randomUUID?crypto.randomUUID():`terminal-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;R.current=n;let l=0===(t=d.trim()).length?[]:t.split(/\s+/);I.current=!0,v(!0);try{let e={projectId:h,command:o,args:l,...(p.length>0?{cwd:p}:{}),requestId:n},t=await rM(e);w(t);}catch(e){k(rL(e));}finally{I.current=!1,v(!1),R.current=null,x(null);}},[d,o,p,h,g]),F=(0,i.useCallback)(async()=>{if(null!==b)try{await rP(b);}catch(e){k(rL(e));}},[b]),T=(0,i.useMemo)(()=>{var e;return null!=(e=null==r?void 0:r.limits)?e:null;},[r]),D=(0,i.useRef)(null),q=(0,i.useRef)(!1);return(0,i.useEffect)(()=>{if(q.current&&!g&&document.activeElement===document.body){var e;null==(e=D.current)||e.focus();}q.current=g;},[g]),(0,a.jsxs)("div",{className:"terminal",children:[(0,a.jsxs)("form",{className:"tm-form",onSubmit:e=>void A(e),children:[(0,a.jsxs)("label",{className:"tm-field",children:[(0,a.jsx)("span",{children:"Project path"}),(0,a.jsx)("input",{type:"text",value:h,onChange:e=>f(e.target.value),placeholder:"/absolute/path/to/project",required:!0})]}),(0,a.jsxs)("div",{className:"tm-field",children:[(0,a.jsx)("span",{children:"Command"}),(0,a.jsx)(tB,{value:o,ariaLabel:"Command",disabled:null===r,menuTitle:"Allowed commands",mono:!0,sections:[{options:null!=(l=null==r?void 0:r.commands.map(e=>({value:e,label:e})))?l:[]}],onValueChange:c})]}),(0,a.jsxs)("label",{className:"tm-field",children:[(0,a.jsx)("span",{children:"Args (space-separated)"}),(0,a.jsx)("input",{type:"text",value:d,onChange:e=>u(e.target.value),placeholder:"e.g. -la src"})]}),(0,a.jsxs)("label",{className:"tm-field",children:[(0,a.jsx)("span",{children:"Working directory (optional)"}),(0,a.jsx)("input",{type:"text",value:p,onChange:e=>m(e.target.value),placeholder:"(project root)",list:"tm-cwd-suggestions"}),(0,a.jsx)("datalist",{id:"tm-cwd-suggestions",children:E.map(e=>(0,a.jsx)("option",{value:e.path},e.path))})]}),(0,a.jsxs)("div",{className:"tm-actions",children:[(0,a.jsx)("button",{type:"submit",className:"tm-action","data-primary":"true",ref:D,disabled:null===r,"aria-disabled":g||null===r,children:g?"Running…":"Run"}),g?(0,a.jsx)("button",{type:"button",className:"tm-action","aria-disabled":null===b,onClick:()=>void F(),children:"Cancel"}):null]}),null!==T?(0,a.jsxs)("p",{className:"tm-limits",children:["Limits: ",(0,lD.z3)(T.maxOutputBytes)," output \xb7"," ",(0,lD._V)(T.defaultTimeoutMs)," timeout"]}):null]}),null!==j?(0,a.jsxs)("div",{className:"tm-error",role:"alert",children:[(0,a.jsxs)("span",{className:"tm-error-text",children:[j.message," ",(0,a.jsxs)("span",{className:"err-code mono",children:["(",j.code,")"]})]}),(0,a.jsx)("button",{type:"button",className:"tm-error-dismiss","aria-label":"Dismiss error",onClick:()=>k(null),children:"✕"})]}):null,(0,a.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:null!==y?`Command finished: exit ${String(y.exitCode)}, ${String(y.durationMs)} ms${y.truncated?", output truncated":""}${y.timedOut?", timed out":""}`:""}),null!==y?(0,a.jsxs)("div",{className:"tm-result",children:[(0,a.jsxs)("div",{className:"tm-badges",children:[(0,a.jsxs)("span",{className:0===y.exitCode?"tm-badge tm-badge-ok":"tm-badge tm-badge-fail",children:["exit ",String(y.exitCode)]}),(0,a.jsxs)("span",{className:"tm-badge",children:[y.durationMs," ms"]}),y.truncated?(0,a.jsx)("span",{className:"tm-badge tm-badge-warn",children:"truncated"}):null,y.timedOut?(0,a.jsx)("span",{className:"tm-badge tm-badge-warn",children:"timed out"}):null]}),y.stdout.length>0?(0,a.jsx)("pre",{className:"tm-stdout",children:y.stdout}):null,y.stderr.length>0?(0,a.jsx)("pre",{className:"tm-stderr",children:y.stderr}):null]}):null,(0,a.jsx)("ul",{className:"tm-events",role:"log","aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false","aria-label":"Recent terminal events",children:N.map((e,t)=>{var n;let l;return(0,a.jsxs)("li",{className:"tm-event",children:[(0,a.jsx)("span",{className:"tm-event-kind",children:function(e){switch(e){case"execution-started":return"started";case"execution-completed":return"completed";case"execution-failed":return"failed";case"execution-cancelled":return"cancelled";}}(e.kind)}),(0,a.jsx)("span",{className:"tm-event-detail",children:(l=(n=e).payload,"execution-completed"===n.kind?["number"==typeof l.exitCode||null===l.exitCode?`exit ${String(l.exitCode)}`:"","number"==typeof l.durationMs?`${String(l.durationMs)}ms`:""].filter(Boolean).join(" \xb7 "):"execution-failed"===n.kind?"string"==typeof l.code?l.code:"":"execution-started"===n.kind&&"string"==typeof l.command?l.command:"")})]},`${e.executionId}-${String(t)}-${e.kind}`);})})]});}function rO(e){return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e;}function rK(e){return e instanceof k.hD?{code:e.code,message:e.message}:e instanceof Error?{code:"INTERNAL",message:e.message}:{code:"INTERNAL",message:"Unexpected error."};}function rB(e){return("dry-run"===e.status||"fix-proposed"===e.status)&&void 0!==e.proposedDiff&&void 0===e.appliedAt;}function rW(e){return void 0!==e.proposedDiff&&""!==e.proposedDiff;}function rU(e){let{href:t,hasManifest:n,error:l}=e;return n?(0,a.jsx)("a",{className:"rv-evidence-link",href:t,target:"_blank",rel:"noopener noreferrer",children:"Evidence"}):null!==l?(0,a.jsxs)("span",{className:"rv-evidence-link rv-evidence-error",role:"alert",children:["Evidence error: ",l.message]}):(0,a.jsx)("button",{type:"button",className:"rv-evidence-link rv-evidence-disabled",disabled:!0,children:"Evidence"});}function r_(e){let{tokens:t}=e;return(0,a.jsx)(a.Fragment,{children:t.map((e,t)=>(0,a.jsx)("span",{className:`hl-${e[0]}`,children:e[1]},t))});}function rV(e){var t,n,l;let i,{line:r,lang:s}=e,o="add"===r.kind?"+":"del"===r.kind?"−":"ctx"===r.kind?"\xb7":"",c="ctx"===r.kind?"":` rv-${r.kind}`;if("meta"!==r.kind&&"code"!==s){let e=null!=(l=iz(r.text,iM(s))[0])?l:[];i=(0,a.jsx)(r_,{tokens:e});}else i=r.text;return(0,a.jsxs)("div",{className:`rv-line${c}`,children:[(0,a.jsx)("span",{className:"rv-sr-only",children:{add:"Added line",del:"Deleted line",ctx:"Context line",meta:"Diff metadata"}[r.kind]}),(0,a.jsx)("span",{className:"rv-num-old rv-num",children:null!=(t=r.oldLine)?t:""}),(0,a.jsx)("span",{className:"rv-num-new rv-num",children:null!=(n=r.newLine)?n:""}),(0,a.jsx)("span",{className:"rv-gutter","aria-hidden":"true",children:o}),(0,a.jsx)("code",{className:"rv-src",children:i})]});}function rH(e){let{hunk:t,lang:n}=e;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"rv-hunk mono","aria-label":`Hunk header ${t.header}`,children:[(0,a.jsx)("span",{className:"rv-sr-only",children:"Hunk header"}),t.header]}),t.lines.map((e,t)=>(0,a.jsx)(rV,{line:e,lang:n},t))]});}function rJ(e){var t;let{file:n,index:l,changedFiles:i,sectionRef:r}=e,s=i.find(e=>e.path===n.path),o=n.path.includes(".")&&null!=(t=n.path.split(".").pop())?t:"code";return(0,a.jsxs)("section",{id:`rv-file-${l}`,"aria-labelledby":`rv-file-${l}-h`,ref:r,children:[(0,a.jsxs)("h3",{id:`rv-file-${l}-h`,className:"rv-file mono",children:[(0,a.jsx)("span",{className:"rv-path",children:n.path}),void 0!==n.oldPath&&(0,a.jsxs)("span",{className:"rv-oldpath",children:[" (was ",n.oldPath,")"]}),(0,a.jsx)("span",{className:"spacer"}),(0,a.jsxs)("span",{className:"rv-stat add",children:["+",n.addedLines]}),(0,a.jsxs)("span",{className:"rv-stat del",children:["−",n.removedLines]}),(null==s?void 0:s.elevatedReview)===!0&&(0,a.jsx)("span",{className:"rv-elevated","aria-label":"Elevated review",children:"!"})]}),(0,a.jsx)("div",{className:"rv-code mono",children:n.hunks.map((e,t)=>(0,a.jsx)(rH,{hunk:e,lang:o},t))})]});}function rY(e){var t,n;let{runId:l,onRunIdSubmit:r}=e,[s,o]=(0,i.useState)(null),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(null),[m,h]=(0,i.useState)(!1),[f,g]=(0,i.useState)(null),[v,b]=(0,i.useState)(!1),[x,y]=(0,i.useState)(null),[w,j]=(0,i.useState)(null),[N,S]=(0,i.useState)(""),[C,I]=(0,i.useState)(!1),R=(0,i.useRef)(null);(0,i.useEffect)(()=>()=>{null!==R.current&&window.clearTimeout(R.current);},[]),(0,i.useEffect)(()=>{if(void 0===l||""===l)return;let e=!1;return h(!0),g(null),o(null),d(!1),p(null),j(null),Promise.allSettled([(0,k.Qe)(l),(0,k.tZ)(l)]).then(t=>{let[n,l]=t;if(!e){if("fulfilled"===l.status)d(!0),p(null);else{let e=rK(l.reason);d(!1),p("NOT_FOUND"===e.code?null:e);}if("fulfilled"===n.status){o(n.value.report),h(!1);return;}g(rK(n.reason)),h(!1);}}),()=>{e=!0;};},[l]);let E=`/api/evidence/${encodeURIComponent(null!=l?l:"")}`,$=(0,i.useMemo)(()=>(null==s?void 0:s.proposedDiff)!==void 0?function(e){let t=new TextEncoder(),n=t.encode(e).byteLength;if(0===e.length)return{files:[],truncated:!1,totalBytes:0};let l=e,a=!1;if(n>524288){a=!0;let n=t.encode(e),i=new TextDecoder().decode(n.slice(0,524288)),r=i.lastIndexOf("\n");l=-1===r?i:i.slice(0,r+1);}let i=l.split("\n"),r=i.length>0&&""===i[i.length-1]?i.slice(0,-1):i,s=[],o=null,c=null,d=0,u=0,p=()=>{null!==o&&null!==c&&o.hunks.push(c),c=null;},m=()=>{p(),null!==o&&(s.length<400?s.push(o):a=!0),o=null;},h=0;for(;h<r.length;){var f,g,v;let e=null!=(f=r[h])?f:"";if(e.startsWith("diff --git ")){m();let t=/^diff --git a\/(.+?) b\/(.+)$/.exec(e);if(null!==t&&void 0!==t[1]&&void 0!==t[2]){let e=t[1],n=t[2],l=rO(`b/${n}`),a=rO(`a/${e}`),i={path:l,hunks:[],addedLines:0,removedLines:0};a!==l&&(i.oldPath=a),o=i;}h++;continue;}if(null!==c){if(e.startsWith("+")){let t={kind:"add",oldLine:null,newLine:u,text:e.slice(1)};c.lines.push(t),null!==o&&o.addedLines++,u++,h++;continue;}if(e.startsWith("-")){let t={kind:"del",oldLine:d,newLine:null,text:e.slice(1)};c.lines.push(t),null!==o&&o.removedLines++,d++,h++;continue;}if(e.startsWith("\\ ")){let t={kind:"meta",oldLine:null,newLine:null,text:e};c.lines.push(t),h++;continue;}if(e.startsWith(" ")||""===e){let t={kind:"ctx",oldLine:d,newLine:u,text:e.startsWith(" ")?e.slice(1):e};c.lines.push(t),d++,u++,h++;continue;}}if(e.startsWith("--- ")){let t=e.slice(4);if("/dev/null"!==t&&null===o)m(),o={path:rO(t),hunks:[],addedLines:0,removedLines:0};else if("/dev/null"!==t&&null!==o){let e=rO(t);e!==o.path&&(o.oldPath=e);}h++;continue;}if(e.startsWith("+++ ")){let t=e.slice(4);"/dev/null"!==t&&null!==o?o.path=rO(t):"/dev/null"!==t&&(m(),o={path:rO(t),hunks:[],addedLines:0,removedLines:0}),h++;continue;}if(e.startsWith("@@ ")){null===o&&(o={path:"(unknown)",hunks:[],addedLines:0,removedLines:0}),p();let t=function(e){let t=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(e);return null===t||void 0===t[1]||void 0===t[2]?null:{oldStart:parseInt(t[1],10),newStart:parseInt(t[2],10)};}(e);d=null!=(g=null==t?void 0:t.oldStart)?g:1,u=null!=(v=null==t?void 0:t.newStart)?v:1,c={header:e,lines:[]},h++;continue;}h++;}return m(),{files:s,truncated:a,totalBytes:n};}(s.proposedDiff):null,[null==s?void 0:s.proposedDiff]),A=null!=(t=null==s?void 0:s.changedFiles)?t:[],F=(0,i.useMemo)(()=>{var e,t;return{added:null!=(e=null==$?void 0:$.files.reduce((e,t)=>e+t.addedLines,0))?e:0,removed:null!=(t=null==$?void 0:$.files.reduce((e,t)=>e+t.removedLines,0))?t:0};},[$]),T=null!==$&&$.files.length>0?Math.min(null!=w?w:0,$.files.length-1):null,D=null!==T?null==$?void 0:$.files[T]:void 0,q=(null==s?void 0:s.status)==="running";return void 0===l||""===l?(0,a.jsxs)("section",{className:"review rv-empty","aria-label":"Diff review",children:[(0,a.jsx)("h2",{className:"rv-empty-h",children:"Review"}),void 0!==r?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("p",{className:"rv-empty-p",children:"Paste a run ID below to load a proposed diff."}),(0,a.jsxs)("form",{className:"rv-empty-form",onSubmit:e=>{e.preventDefault();let t=N.trim();0!==t.length&&r(t);},children:[(0,a.jsx)("label",{className:"rv-empty-label",htmlFor:"rv-runid-input",children:"Run ID"}),(0,a.jsx)("input",{id:"rv-runid-input",className:"rv-runid-input mono",type:"text",value:N,onChange:e=>S(e.target.value),placeholder:"e.g. 7f3a9c12…"}),(0,a.jsx)("button",{type:"submit",className:"arun-btn",children:"Load run"})]})]}):(0,a.jsx)("p",{className:"rv-empty-p",children:"Enter a run ID in the window configuration to load a proposed diff."})]}):(0,a.jsxs)("section",{className:"review","aria-label":"Diff review",children:[m&&(0,a.jsxs)("div",{className:"rv-loading",role:"status","aria-busy":"true","aria-label":"Loading diff",children:[(0,a.jsx)("div",{className:"rv-skel"}),(0,a.jsx)("div",{className:"rv-skel rv-skel-sm"})]}),!m&&null!==f&&(0,a.jsxs)("div",{role:"alert",className:"rv-error",children:["NOT_FOUND"===f.code?"No run with that ID was found.":(0,a.jsxs)(a.Fragment,{children:[f.message," ",(0,a.jsxs)("span",{className:"err-code mono",children:["(",f.code,")"]})]}),(c||null!==u)&&(0,a.jsx)("span",{className:"rv-error-evidence",children:(0,a.jsx)(rU,{href:E,hasManifest:c,error:u})})]}),(0,a.jsx)("p",{role:"status","aria-live":"polite",className:!m&&null===f&&null!==s&&q?"rv-no-diff":"sr-only",children:!m&&null===f&&null!==s&&q?"Run is still running. The proposed diff will appear when the run completes.":""}),!m&&null===f&&null!==s&&!q&&!rW(s)&&(0,a.jsx)("p",{className:"rv-no-diff",children:"This run has no proposed diff to review."}),!m&&null===f&&null!==s&&rW(s)&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"rv-header",children:[(0,a.jsx)("span",{className:"rv-status mono",children:(0,lD.az)(s.status)}),void 0!==s.modelId&&(0,a.jsx)("span",{className:"rv-model mono",children:s.modelId}),(0,a.jsxs)("span",{className:"rv-counts mono",children:[null!==$&&`${$.files.length} file${1!==$.files.length?"s":""}`," ",(0,a.jsxs)("span",{className:"rv-stat add",children:["+",F.added]})," ",(0,a.jsxs)("span",{className:"rv-stat del",children:["−",F.removed]})]}),(0,a.jsx)("span",{className:"spacer"}),(0,a.jsx)(rU,{href:E,hasManifest:c,error:u})]}),null!==$&&$.files.length>0&&null!==T&&void 0!==D&&(0,a.jsxs)("div",{className:"rv-layout",children:[(0,a.jsx)("nav",{className:"rv-filelist","aria-label":"Changed files",children:(0,a.jsx)("ul",{children:$.files.map((e,t)=>{let n=A.find(t=>t.path===e.path),l=T===t;return(0,a.jsx)("li",{children:(0,a.jsxs)("button",{type:"button",className:"rv-filerow",title:e.path,"aria-pressed":l,"aria-controls":l?`rv-file-${t}`:void 0,onClick:()=>{j(t);},children:[(0,a.jsx)("span",{className:"rv-filerow-path mono",children:function(e){if(e.length<=40)return e;let t=e.split("/");return t.length<=2?e:`…/${t.slice(-2).join("/")}`;}(e.path)}),(0,a.jsxs)("span",{className:"rv-stat add",children:["+",e.addedLines]}),(0,a.jsxs)("span",{className:"rv-stat del",children:["−",e.removedLines]}),(null==n?void 0:n.elevatedReview)===!0&&(0,a.jsx)("span",{className:"rv-elevated","aria-label":"Elevated review",children:"!"})]})},e.path);})})}),(0,a.jsxs)("div",{className:"rv-body",children:[(0,a.jsx)(rJ,{file:D,index:T,changedFiles:A,sectionRef:()=>void 0},D.path),$.truncated&&(0,a.jsxs)("p",{role:"note",className:"rv-truncated",children:["Diff truncated at 512 KB. Open the"," ",c?(0,a.jsx)("a",{href:E,target:"_blank",rel:"noopener noreferrer",children:"evidence manifest"}):"evidence manifest"," ","for the full record."]})]})]}),(0,a.jsxs)("div",{className:"rv-controls",children:[(0,a.jsx)("span",{role:"status","aria-live":"polite",className:"rv-apply-status",children:v?"Applying…":void 0!==s.appliedAt?"Applied":""}),null!==x&&(0,a.jsx)("span",{role:"alert",className:"rv-apply-error",children:x.message}),void 0!==s.appliedAt?(0,a.jsx)("span",{className:"rv-final mono",children:"Applied"}):rB(s)?(0,a.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":v,onClick:()=>{if(!v){if(!C){I(!0),null!==R.current&&window.clearTimeout(R.current),R.current=window.setTimeout(()=>{I(!1),R.current=null;},6e3);return;}null!==R.current&&(window.clearTimeout(R.current),R.current=null),I(!1),void 0!==l&&null!==s&&rB(s)&&!v&&(b(!0),y(null),(0,k.qU)(l).then(e=>{o(e.report),b(!1);}).catch(e=>{y(rK(e)),b(!1);}));}},children:v?"Applying…":C?`Confirm apply (${(null!=(n=null==$?void 0:$.files.length)?n:0).toString()} file${(null==$?void 0:$.files.length)===1?"":"s"})`:"Apply"}):null]})]})]});}let rX=new Set(["completed","dry-run","rejected","cancelled","failed","fix-applied","fix-proposed","investigation-only"]),rG={verify:"Verify","explain-plan":"Explain plan","unit-test-generation":"Generate unit tests","bug-investigation":"Investigate bug"};function rQ(e,t){return void 0===t||0===t.length?null:(0,a.jsxs)("div",{className:"arun-result-card",children:[(0,a.jsx)("div",{className:"arun-result-title",children:e}),(0,a.jsx)("pre",{children:t})]});}let rZ={high:"High",medium:"Medium",low:"Low — verify"};function r0(e){let{level:t}=e;return(0,a.jsxs)("div",{className:"arun-kv",children:[(0,a.jsx)("span",{children:"Confidence"}),(0,a.jsxs)("span",{className:"ai-conf","data-level":t,children:[(0,a.jsxs)("span",{className:"track","aria-hidden":"true",children:[(0,a.jsx)("i",{}),(0,a.jsx)("i",{}),(0,a.jsx)("i",{})]}),(0,a.jsx)("span",{className:"lbl",children:rZ[t]})]})]});}function r1(e){var t,n,l,r,s,o,c,d,u,p,m;let h,{cfg:f={},linkedRoot:g=null,linkedFilePath:v}=e,b=null!=(t=f.runId)?t:null,x="verify"===(p=f.workflow)||"explain-plan"===p||"unit-test-generation"===p||"bug-investigation"===p?p:null,y=null!=(n=f.model)?n:"",w=function(e){if(void 0===e||0===e.length)return null;try{let t=JSON.parse(e);return"object"!=typeof t||null===t||Array.isArray(t)?null:t;}catch{return null;}}(f.inputJson),j=function(e){let[t,n]=(0,i.useState)([]),[l,a]=(0,i.useState)("connecting"),[r,s]=(0,i.useState)(null),o=(0,i.useRef)(-1);return(0,i.useEffect)(()=>{if(null===e)return;n([]),a("connecting"),s(null),o.current=-1;let t=null,l=!1,i=`/api/runs/${encodeURIComponent(e)}/events`;(t=new EventSource(o.current>=0?`${i}?lastEventId=${o.current.toString()}`:i)).onopen=()=>{l||(a("live"),s(null));},t.onerror=()=>{l||(a("error"),s("Stream disconnected. Attempting to reconnect…"));};let r=e=>{let i;if(!l){try{i=JSON.parse(e.data);}catch{return;}o.current=i.seq,n(e=>[...e,i]),nb.eQ.has(i.type)&&(a("terminal"),null==t||t.close());}};for(let e of nb.$Q)t.addEventListener(e,r);return()=>{l=!0,null==t||t.close();};},[e]),{events:t,status:l,error:r};}(b),[S,C]=(0,i.useState)(null),[I,R]=(0,i.useState)(null),[E,$]=(0,i.useState)(null),[A,F]=(0,i.useState)(!1),[T,D]=(0,i.useState)(null),[q,M]=(0,i.useState)(null),[P,L]=(0,i.useState)(!1),z=(0,i.useRef)(null),O=(0,i.useRef)(null),K=(0,i.useCallback)(async()=>{if(null!==b){$(null);try{let e=await(0,k.Qe)(b);C(e.report),R(null);}catch(e){if(e instanceof k.hD&&404===e.status){try{let e=await(0,k.tZ)(b);R(e.manifest),C(null);}catch(e){$(e instanceof Error?e.message:"Unable to load evidence.");}return;}$(e instanceof Error?e.message:"Unable to load run report.");}}},[b]);(0,i.useEffect)(()=>{K();},[K]),(0,i.useEffect)(()=>{"terminal"===j.status&&K();},[K,j.status]),(0,i.useEffect)(()=>{let e=!1;if(0!==y.length)return(0,k.ZC)().then(t=>{var n,l;e||M(null!=(n=null==(l=t.models.find(e=>e.id===y))?void 0:l.costClass)?n:null);}).catch(()=>{e||M(null);}),()=>{e=!0;};},[y]);let B=(0,i.useMemo)(()=>function(e,t){var n,l,a,i,r,s;let o=null!=(n=null==t||null==(i=t.usage)?void 0:i.promptTokens)?n:0,c=null!=(l=null==t||null==(r=t.usage)?void 0:r.completionTokens)?l:0,d=null!=(a=null==t||null==(s=t.usage)?void 0:s.latencyMs)?a:0,u=+((null==t?void 0:t.usage)!==void 0);if(u>0)return{promptTokens:o,completionTokens:c,latencyMs:d,requestCount:u};for(let t of e){let e=function(e){if("model:call:completed"===e.type)return{promptTokens:e.usage.promptTokens,completionTokens:e.usage.completionTokens,latencyMs:e.usage.latencyMs,requestCount:1};let t=e.promptTokens,n=e.completionTokens,l=e.latencyMs;return"number"==typeof t&&"number"==typeof n&&"number"==typeof l?{promptTokens:t,completionTokens:n,latencyMs:l,requestCount:1}:null;}(t);null!==e&&(o+=e.promptTokens,c+=e.completionTokens,d+=e.latencyMs,u+=e.requestCount);}return{promptTokens:o,completionTokens:c,latencyMs:d,requestCount:u};}(j.events,S),[j.events,S]),W=null!=(l=null!=(r=null==S?void 0:S.durationMs)?r:null==I?void 0:I.run.durationMs)?l:j.events.length>0?Math.max(0,Date.now()-Number(new Date(null!=(s=null==(d=j.events[0])?void 0:d.ts)?s:Date.now()))):0,U=null!==S?S.status:null!==I?I.run.outcome:"loading",_=null!==S?(0,lD.az)(S.status):null!==I?(0,lD.FR)(I.run.outcome):"Loading…",V=null!==S&&rX.has(S.status),H=null!==S&&void 0!==S.proposedDiff&&void 0===S.appliedAt&&("unit-test-generation"===x&&"dry-run"===S.status||"bug-investigation"===x&&"fix-proposed"===S.status),J=!V&&(null==S?void 0:S.status)==="running",Y=function(e){if(void 0===e||0===e.length)return 0;let t=e.match(/^diff --git /gm);if(null!==t)return t.length;let n=e.match(/^\+\+\+ /gm);return null===n?0:n.length;}(null==S?void 0:S.proposedDiff),X=A||"connecting"===j.status||(null==S?void 0:S.status)==="running"||null===S&&null===I&&null===E,G=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(G.current&&!J&&document.activeElement===document.body){var e;null==(e=O.current)||e.focus();}G.current=J;},[J]),(0,i.useEffect)(()=>()=>{null!==z.current&&window.clearTimeout(z.current);},[]);let Q=async()=>{if(null!==b){$(null);try{await(0,k.Su)(b),await K();}catch(e){$(e instanceof Error?e.message:"Unable to cancel run.");}}},Z=async()=>{if(null!==b&&H&&!A){F(!0),D(null);try{let e=await(0,k.qU)(b);C(e.report);}catch(e){D(e instanceof Error?e.message:"Unable to apply run.");}finally{F(!1);}}};return null===b||null===x?(0,a.jsxs)("div",{className:"arun arun-empty",children:[(0,a.jsx)("div",{className:"arun-result-title",children:"Agent run is not configured."}),(0,a.jsx)("p",{children:"Open a new Agent window from the launcher to start a workflow."})]}):(0,a.jsxs)("div",{className:"arun arun-real","aria-busy":X?"true":void 0,children:[(0,a.jsxs)("div",{className:"arun-head",children:[(0,a.jsx)("span",{className:"arun-role",children:rG[x]}),y.length>0?(0,a.jsx)("span",{className:"ag-model mono",children:y}):null,null!==q?(0,a.jsx)("span",{className:"arun-gov",title:"Model cost class",children:(0,lD.Kb)(q)}):null,(0,a.jsx)("span",{className:"spacer"}),(0,a.jsxs)("span",{className:"arun-status",children:[(0,a.jsx)("span",{className:"dot","data-live":(null==S?void 0:S.status)==="running","data-status":U}),_]})]}),(0,a.jsxs)("div",{className:"arun-summary",role:"status","aria-live":"polite",children:[(0,a.jsx)("strong",{children:function(e,t,n){var l,a;if(null===t&&null===n)return"Loading run state…";let i=null===e?"Agent run":rG[e];return(null==t?void 0:t.status)==="running"?`${i} is running.`:(null==t?void 0:t.status)==="dry-run"?`${i} produced a reviewable dry-run.`:(null==t?void 0:t.status)==="fix-proposed"?`${i} proposed a fix.`:(null==t?void 0:t.status)==="fix-applied"?`${i} applied changes.`:(null==t?void 0:t.status)==="investigation-only"?`${i} completed without a patch.`:(null==t?void 0:t.status)==="failed"||(null==t?void 0:t.status)==="rejected"?`${i} failed.`:(null==t?void 0:t.status)==="cancelled"?`${i} was cancelled.`:null!==t?`${i} completed.`:(null==n||null==(a=n.patch)?void 0:a.redactedDiff)!==void 0?`${i} evidence loaded with a reviewable diff.`:`${i} evidence loaded: ${null!=(l=null==n?void 0:n.run.outcome)?l:"unknown"}.`;}(x,S,I)}),(0,a.jsxs)("span",{className:"mono",title:b,children:["run ",b.slice(0,8)]})]}),(0,a.jsxs)("div",{className:"arun-meters",children:[(0,a.jsxs)("div",{className:"arun-meter",children:[(0,a.jsx)("span",{className:"arun-mk",children:"Elapsed"}),(0,a.jsx)("span",{className:"arun-mv mono",children:(0,lD._V)(W)})]}),(0,a.jsxs)("div",{className:"arun-meter",children:[(0,a.jsx)("span",{className:"arun-mk",children:"Usage"}),(0,a.jsx)("span",{className:"arun-mv mono",children:0===B.requestCount?"No model usage":`${(0,lD._y)(B.promptTokens+B.completionTokens)} tok`})]}),(0,a.jsxs)("div",{className:"arun-meter",children:[(0,a.jsx)("span",{className:"arun-mk",children:"Latency"}),(0,a.jsx)("span",{className:"arun-mv mono",children:0===B.requestCount?"—":(0,lD._V)(B.latencyMs)})]})]}),(0,a.jsxs)("div",{className:"arun-perms",children:[(0,a.jsxs)("span",{className:"arun-perm","data-on":null!==g,title:null!==g?g:null!=(o=f.workspaceRoot)?o:void 0,children:[(0,a.jsx)(N.F.files,{size:11}),(0,a.jsx)("span",{className:"arun-perm-path",children:null!==g?g:null!=(c=f.workspaceRoot)?c:"no workspace"})]}),void 0!==v?(0,a.jsxs)("span",{className:"arun-perm","data-on":!0,title:v,children:[(0,a.jsx)(N.F.files,{size:11}),(0,a.jsx)("span",{className:"arun-perm-path",children:v})]}):null]}),null!==w?(0,a.jsxs)("details",{className:"arun-input",children:[(0,a.jsx)("summary",{children:"Run input"}),(0,a.jsx)("pre",{children:JSON.stringify(w,null,2)})]}):null,(0,a.jsxs)("div",{className:"arun-log",role:"log","aria-live":"polite","aria-label":"Run events","aria-busy":X?"true":void 0,children:["error"===j.status&&null!==j.error?(0,a.jsxs)("div",{className:"arun-log-row",children:[(0,a.jsx)("span",{className:"arun-log-ico",children:(0,a.jsx)(N.F.reset,{size:12})}),(0,a.jsx)("span",{className:"arun-log-text",children:j.error})]}):null,0===j.events.length?"error"===j.status?null:(0,a.jsxs)("div",{className:"arun-log-row",children:[(0,a.jsx)("span",{className:"arun-log-ico",children:(0,a.jsx)(N.F.reset,{size:12})}),(0,a.jsx)("span",{className:"arun-log-text",children:"connecting"===j.status?"Connecting to run events…":"Waiting for run events…"})]}):j.events.slice().reverse().slice(0,50).map(e=>{let t;return(0,a.jsxs)("div",{className:"arun-log-row",children:[(0,a.jsx)("span",{className:"arun-log-ico",children:(0,a.jsx)(N.F.spark,{size:12})}),(0,a.jsx)("span",{className:"arun-log-text",children:function(e){switch(e.type){case"ready":return"SSE stream ready";case"run:started":return`Started ${e.taskType}`;case"run:completed":return"Run completed";case"run:failed":return`Run failed: ${e.failure.message}`;case"run:cancelled":return"Run cancelled";case"state:transition":return`${e.from} -> ${e.to}${void 0===e.reason?"":`: ${e.reason}`}`;case"model:call:started":return`Model call started (${(0,lD.z3)(e.contextBytes)})`;case"model:call:completed":return`Model call completed (${(0,lD._y)(e.usage.promptTokens+e.usage.completionTokens)} tokens)`;case"model:call:failed":return`Model call failed: ${e.message}`;case"patch:proposed":return`Patch proposed (${(0,lD.z3)(e.patchBytes)})`;case"verification:result":return`Verification ${e.passed?"passed":"failed"}: ${e.detail}`;case"workflow:started":return"Unit-test workflow started";case"workflow:model:call:completed":return`Unit-test model call completed (${(0,lD._y)(e.promptTokens+e.completionTokens)} tokens)`;case"workflow:verification:result":return`Unit-test verification ${e.overallStatus}`;case"workflow:completed":return`Unit-test workflow ${e.status}`;case"workflow:failed":return`Unit-test workflow failed: ${e.message}`;case"bug:started":return"Bug investigation started";case"bug:model:call:completed":return`Bug model call completed (${(0,lD._y)(e.promptTokens+e.completionTokens)} tokens)`;case"bug:rootcause:proposed":return`Root cause proposed${e.hasPatch?" with patch":""}`;case"bug:verification:result":return`Bug verification ${e.overallStatus}`;case"bug:completed":return`Bug investigation ${e.status}`;case"bug:failed":return`Bug investigation failed: ${e.message}`;default:return e.type;}}(e)}),(0,a.jsx)("span",{className:"arun-log-t mono",children:Number.isFinite(t="number"==typeof e.ts?e.ts:Date.parse(e.ts))?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):""})]},`${e.runId}:${e.seq}:${e.type}`);})]}),null!==S?(0,a.jsxs)("div",{className:"arun-results",children:[void 0===S.report?null:(0,a.jsxs)("div",{className:"arun-result-card",children:[(0,a.jsx)("div",{className:"arun-result-title",children:"Report"}),(0,a.jsx)("pre",{children:S.report})]}),void 0===S.overallStatus||void 0===S.results?null:(0,a.jsxs)("div",{className:"arun-result-card",children:[(0,a.jsx)("div",{className:"arun-result-title",children:"Verification"}),(0,a.jsxs)("div",{className:"arun-kv",children:[(0,a.jsx)("span",{children:"Status"}),(0,a.jsx)("strong",{children:S.overallStatus})]}),S.results.slice(0,8).map(e=>(0,a.jsxs)("div",{className:"arun-check-row",children:[(0,a.jsx)("span",{children:e.kind}),(0,a.jsx)("span",{className:"mono",children:e.status})]},`${e.kind}:${e.command}`))]}),rQ("Failure",S.failureReason),rQ("Covered behavior",S.coveredBehavior),rQ("Known gaps",S.knownGaps),rQ("Verification note",S.verificationSkipReason),function(e){let t=e.hypothesis;if(void 0===t)return null;let n=[["Root cause",t.rootCause],["Regression test",t.regressionTestStrategy],["Uncertainty",t.uncertainty]].filter(e=>"string"==typeof e[1]&&e[1].length>0),l="string"==typeof t.confidence?t.confidence:"",i="low"===l||"medium"===l||"high"===l?l:void 0,r=l.length>0&&void 0===i?l:void 0;return 0===n.length&&void 0===i&&void 0===r?null:(0,a.jsxs)("div",{className:"arun-result-card",children:[(0,a.jsx)("div",{className:"arun-result-title",children:"Hypothesis"}),n.map(e=>{let[t,n]=e;return(0,a.jsxs)("div",{className:"arun-kv",children:[(0,a.jsx)("span",{children:t}),(0,a.jsx)("strong",{children:n})]},t);}),void 0!==r?(0,a.jsxs)("div",{className:"arun-kv",children:[(0,a.jsx)("span",{children:"Confidence"}),(0,a.jsx)("strong",{children:r})]}):null,void 0!==i?(0,a.jsx)(r0,{level:i}):null]});}(S),void 0===(m=S.nextActions)||0===m.length?null:(0,a.jsxs)("div",{className:"arun-result-card",children:[(0,a.jsx)("div",{className:"arun-result-title",children:"Next actions"}),m.map(e=>(0,a.jsx)("div",{className:"arun-check-row",children:(0,a.jsx)("span",{children:e})},e))]}),void 0!==S.dryRunPreview?(0,a.jsxs)("div",{className:"arun-result-card",children:[(0,a.jsx)("div",{className:"arun-result-title",children:"Dry-run preview"}),(0,a.jsx)("pre",{children:S.dryRunPreview})]}):null,void 0!==S.proposedDiff?(0,a.jsxs)("div",{className:"arun-result-card",children:[(0,a.jsx)("div",{className:"arun-result-title",children:"Proposed diff"}),(0,a.jsx)("pre",{children:S.proposedDiff})]}):null,void 0===(h=S.verificationSummary)?null:(0,a.jsxs)("div",{className:"arun-result-card",children:[(0,a.jsx)("div",{className:"arun-result-title",children:"Verification"}),(0,a.jsxs)("div",{className:"arun-kv",children:[(0,a.jsx)("span",{children:"Status"}),(0,a.jsx)("strong",{children:h.overallStatus})]}),(0,a.jsxs)("div",{className:"arun-kv",children:[(0,a.jsx)("span",{children:"Duration"}),(0,a.jsx)("strong",{children:(0,lD._V)(h.durationMs)})]}),h.results.slice(0,5).map(e=>(0,a.jsxs)("div",{className:"arun-check-row",children:[(0,a.jsx)("span",{children:e.kind}),(0,a.jsx)("span",{className:"mono",children:e.status})]},`${e.kind}:${e.command}`))]}),void 0!==S.applyReport?(0,a.jsxs)("div",{className:"arun-result-card arun-applied",children:[(0,a.jsx)("div",{className:"arun-result-title",children:"Applied"}),(0,a.jsx)("pre",{children:JSON.stringify(S.applyReport,null,2)})]}):null]}):null!==I?(0,a.jsxs)("div",{className:"arun-results",children:[(0,a.jsxs)("div",{className:"arun-result-card",children:[(0,a.jsx)("div",{className:"arun-result-title",children:"Evidence"}),(0,a.jsxs)("div",{className:"arun-kv",children:[(0,a.jsx)("span",{children:"Outcome"}),(0,a.jsx)("strong",{children:I.run.outcome})]}),(0,a.jsxs)("div",{className:"arun-kv",children:[(0,a.jsx)("span",{children:"Duration"}),(0,a.jsx)("strong",{children:(0,lD._V)(I.run.durationMs)})]}),void 0!==I.patch?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"arun-kv",children:[(0,a.jsx)("span",{children:"Changed files"}),(0,a.jsx)("strong",{children:I.patch.changedFiles.toString()})]}),(0,a.jsxs)("div",{className:"arun-kv",children:[(0,a.jsx)("span",{children:"Patch size"}),(0,a.jsx)("strong",{children:(0,lD.z3)(I.patch.patchBytes)})]})]}):null]}),(null==(u=I.patch)?void 0:u.redactedDiff)!==void 0?(0,a.jsxs)("div",{className:"arun-result-card",children:[(0,a.jsx)("div",{className:"arun-result-title",children:"Proposed diff"}),(0,a.jsx)("pre",{children:I.patch.redactedDiff})]}):null]}):null,null!==E?(0,a.jsx)("div",{className:"arun-error",role:"alert",children:E}):null,null!==T?(0,a.jsx)("div",{className:"arun-error",role:"alert",children:T}):null,(0,a.jsxs)("div",{className:"arun-controls",children:[(0,a.jsx)("a",{className:"arun-btn ghost",href:`/api/evidence/${encodeURIComponent(b)}`,target:"_blank",rel:"noreferrer",ref:O,children:"Evidence"}),H?(0,a.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":A,onClick:()=>{if(!A){if(!P){L(!0),null!==z.current&&window.clearTimeout(z.current),z.current=window.setTimeout(()=>{L(!1),z.current=null;},6e3);return;}null!==z.current&&(window.clearTimeout(z.current),z.current=null),L(!1),Z();}},children:A?"Applying…":P?`Confirm apply (${Y.toString()} file${1===Y?"":"s"})`:"Apply"}):(null==S?void 0:S.appliedAt)!==void 0?(0,a.jsx)("span",{className:"arun-final mono",children:"Applied"}):null,J?(0,a.jsx)("button",{type:"button",className:"arun-btn danger",onClick:()=>void Q(),children:"Cancel"}):null]})]});}let r2=[{name:"Messaging",desc:"Catch up on threads",glyph:"#"},{name:"GitHub",desc:"PRs, code & CI",glyph:"{ }"},{name:"Linear",desc:"Track issues",glyph:"⊿"},{name:"Slack",desc:"Team channels",glyph:"≡"},{name:"Sentry",desc:"Error tracking",glyph:"◎"}];function r3(){return(0,a.jsx)("ul",{className:"integ","aria-label":"Integrations",children:r2.map(e=>(0,a.jsxs)("li",{className:"integ-row",children:[(0,a.jsx)("span",{className:"integ-glyph mono",children:e.glyph}),(0,a.jsxs)("span",{className:"integ-text",children:[(0,a.jsx)("span",{className:"integ-name",children:e.name}),(0,a.jsx)("span",{className:"integ-desc",children:e.desc})]}),(0,a.jsx)("span",{className:"integ-status",children:"Not connected — coming soon"})]},e.name))});}let r4={allow:["Allow","var(--accent)"],ask:["Ask","var(--warn)"],deny:["Deny","var(--danger)"]},r6={allow:"ask",ask:"deny",deny:"allow"},r5=[{id:1,label:"Write src/windows.jsx",kind:"write",risk:"low",expect:"allow"},{id:2,label:"Overwrite prod/secrets.env",kind:"write",risk:"high",expect:"deny"},{id:3,label:"Run `npm test`",kind:"command",risk:"low",expect:"allow"},{id:4,label:"Run `kubectl apply` → prod",kind:"command",risk:"high",expect:"ask"},{id:5,label:"Open pull request #142",kind:"git",risk:"low",expect:"allow"},{id:6,label:"Email the customer",kind:"mail",risk:"low",expect:"ask"}],r8=[["Developer","Codes, reviews diffs, runs tests, opens PRs"],["Product Owner","Searches docs, drafts Jira tickets, plans releases"],["Designer","Explores UI options, reviews flows, writes specs"]],r7=[["calendar","Calendar","automations"],["mail","Mail","bell"],["jira","Jira","review"],["docs","Docs","files"]];function r9(e){let{policy:t,setPolicy:n}=e;return(0,a.jsxs)("div",{className:"pol",children:[(0,a.jsx)("div",{className:"pol-hint",children:"Rights an agent inherits when Keiko governs. Tap a decision to cycle through Allow → Ask → Deny."}),t.map(e=>{let t=r4[e.decision];return(0,a.jsxs)("div",{className:"pol-row",children:[(0,a.jsxs)("div",{className:"pol-text",children:[(0,a.jsx)("span",{className:"pol-action",children:e.action}),(0,a.jsx)("span",{className:"pol-scope mono",children:e.scope})]}),(0,a.jsx)("button",{type:"button",className:"pol-dec",style:{color:t[1],borderColor:t[1]},onClick:()=>{let t;return t=e.id,n(e=>e.map(e=>e.id===t?{...e,decision:r6[e.decision]}:e));},children:t[0]})]},e.id);})]});}function se(e){let{decide:t}=e,[n,l]=(0,i.useState)(!1),r=r5.map(e=>{let n=t(e.kind,e.risk);return{...e,actual:n,pass:n===e.expect};}),s=r.filter(e=>e.pass).length;return(0,a.jsxs)("div",{className:"evl",children:[(0,a.jsxs)("div",{className:"evl-head",children:[(0,a.jsxs)("button",{type:"button",className:"evl-run",onClick:()=>l(!0),children:[(0,a.jsx)(N.F.spark,{size:13})," Run evaluation"]}),n&&(0,a.jsxs)("span",{className:"evl-score"+(s===r.length?" ok":""),children:[s,"/",r.length," passed"]})]}),(0,a.jsx)("div",{className:"evl-hint",children:"Mock scenarios against your policy before going autonomous."}),r.map(e=>(0,a.jsxs)("div",{className:"evl-row","data-state":n?e.pass?"pass":"fail":"idle",children:[(0,a.jsx)("span",{className:"evl-ico",children:n?e.pass?(0,a.jsx)(N.F.check,{size:13}):(0,a.jsx)(N.F.close,{size:13}):(0,a.jsx)("span",{className:"evl-dot"})}),(0,a.jsx)("span",{className:"evl-label",children:e.label}),n&&(0,a.jsx)("span",{className:"evl-res mono",style:{color:r4[e.actual][1]},children:r4[e.actual][0]})]},e.id))]});}function st(e){let{bridges:t,setBridges:n}=e;return(0,a.jsxs)("div",{className:"brg",children:[(0,a.jsx)("div",{className:"evl-hint",children:"What your twin can reach on your behalf."}),r7.map(e=>{let[l,i,r]=e,s=N.F[r],o=t[l];return(0,a.jsxs)("button",{type:"button",className:"brg-row","data-on":o,"aria-pressed":o,onClick:()=>n(e=>({...e,[l]:!e[l]})),children:[(0,a.jsx)("span",{className:"brg-ico",children:(0,a.jsx)(s,{size:16})}),(0,a.jsx)("span",{className:"brg-name",children:i}),(0,a.jsx)("span",{className:"brg-tg"+(o?" on":""),children:(0,a.jsx)("span",{})})]},l);})]});}function sn(e){let{persona:t,setPersona:n}=e;return(0,a.jsxs)("div",{className:"prs",children:[(0,a.jsx)("div",{className:"evl-hint",children:"Keiko adapts behaviour & tools to who is at the wheel."}),r8.map(e=>{let[l,i]=e;return(0,a.jsxs)("button",{type:"button",className:"prs-row","data-on":t===l,"aria-pressed":t===l,onClick:()=>n(l),children:[(0,a.jsx)("span",{className:"prs-dot"}),(0,a.jsxs)("span",{className:"prs-text",children:[(0,a.jsx)("span",{className:"prs-name",children:l}),(0,a.jsx)("span",{className:"prs-desc",children:i})]}),t===l&&(0,a.jsx)(N.F.check,{size:14,style:{color:"var(--accent)"}})]},l);})]});}let sl=[["policy","Policy"],["eval","EVAL"],["bridges","Connections"],["persona","Persona"]];function sa(){let e=w(),[t,n]=(0,i.useState)("policy");return(0,a.jsxs)("div",{className:"twin",children:[(0,a.jsxs)("div",{className:"twin-hero",children:[(0,a.jsx)("img",{className:"twin-orca",src:"/assets/keiko-logo.svg",alt:""}),(0,a.jsxs)("div",{className:"twin-id",children:[(0,a.jsx)("span",{className:"twin-name",children:"Keiko — Digital Twin"}),(0,a.jsxs)("span",{className:"twin-sub mono",children:["mirroring \xb7 ",e.persona]})]}),(0,a.jsx)("span",{className:"twin-mode "+("autonomous"===e.mode?"on":""),children:"autonomous"===e.mode?"Autonomous":"Manual"})]}),(0,a.jsx)("div",{className:"twin-tabs",children:sl.map(e=>{let[l,i]=e;return(0,a.jsx)("button",{type:"button",className:"twin-tab","data-on":t===l,onClick:()=>n(l),children:i},l);})}),(0,a.jsxs)("div",{className:"twin-body",children:["policy"===t&&(0,a.jsx)(r9,{policy:e.policy,setPolicy:e.setPolicy}),"eval"===t&&(0,a.jsx)(se,{decide:e.decide}),"bridges"===t&&(0,a.jsx)(st,{bridges:e.bridges,setBridges:e.setBridges}),"persona"===t&&(0,a.jsx)(sn,{persona:e.persona,setPersona:e.setPersona})]})]});}function si(e){return"embedding-only"===e?"Embedding model — not selectable for text conversation":"ocr-vision-only"===e?"OCR/vision-only — not selectable for text conversation":"Not a chat model — not selectable for text conversation";}function sr(){return"Available for embeddings; not shown in the chat model picker";}function ss(e){let{model:t}=e,n=(0,nb.nP)(t);return void 0===n?(0,a.jsx)("span",{className:"ml-elig ml-elig-ok","data-testid":"conv-elig-ok",role:"status","aria-label":"Model eligibility: eligible for conversation",children:"Conversation-eligible"}):"embedding-only"===n?(0,a.jsx)("span",{className:"ml-elig ml-elig-embed","data-testid":"embedding-elig-ok",role:"status","aria-label":"Model eligibility: "+sr(),title:sr(),children:"Embedding-ready"}):(0,a.jsxs)("span",{className:"ml-elig ml-elig-no","data-testid":"conv-elig-no",role:"status","aria-label":"Model eligibility: "+si(n),title:si(n),children:["Not selectable — ","ocr-vision-only"===n?"OCR/vision-only":"not a chat model"]});}function so(e){var t;let{model:n}=e,l=(0,nb.S_)(n),i="embedding"===n.kind;return(0,a.jsxs)("div",{className:"ml-row",children:[(0,a.jsx)("span",{className:"ml-ico",children:(0,a.jsx)(N.F.cube,{size:16})}),(0,a.jsxs)("div",{className:"ml-info",children:[(0,a.jsxs)("div",{className:"ml-top",children:[(0,a.jsx)("span",{className:"ml-name",children:n.id}),(0,a.jsx)("span",{className:"ml-type mono",children:"ocr-vision"===(t=n.kind)?"OCR":t}),(0,a.jsx)(ss,{model:n})]}),(0,a.jsxs)("div",{className:"ml-url mono",children:["tools ",n.toolCalling?"yes":"no"," \xb7 structured"," ",n.structuredOutput?"yes":"no"," \xb7 ",n.costClass,"/",n.latencyClass]})]}),(0,a.jsx)("span",{className:"ml-status "+(l||i?"connected":"ineligible"),title:l?"conversation-eligible":i?"available for embeddings":"not selectable for conversation","aria-hidden":"true"})]});}function sc(){let[e,t]=(0,i.useState)(ed),[n,l]=(0,i.useState)(eu),[r,s]=(0,i.useState)(ep),[o,c]=(0,i.useState)(em),[d,u]=(0,i.useState)(eh),[p,m]=(0,i.useState)(ef);(0,i.useEffect)(()=>{try{window.localStorage.setItem(G,e?"true":"false");}catch{}window.dispatchEvent(new CustomEvent(el,{detail:e}));},[e]),(0,i.useEffect)(()=>{try{window.localStorage.setItem(Q,String(n));}catch{}window.dispatchEvent(new CustomEvent(ea,{detail:n}));},[n]),(0,i.useEffect)(()=>{try{window.localStorage.setItem(Z,String(r));}catch{}eg(r),window.dispatchEvent(new CustomEvent(ei,{detail:r}));},[r]),(0,i.useEffect)(()=>{try{window.localStorage.setItem(ee,String(o));}catch{}ev(o),window.dispatchEvent(new CustomEvent(er,{detail:o}));},[o]),(0,i.useEffect)(()=>{try{window.localStorage.setItem(et,String(d));}catch{}eb(d),window.dispatchEvent(new CustomEvent(es,{detail:d}));},[d]),(0,i.useEffect)(()=>{try{window.localStorage.setItem(en,String(p));}catch{}ex(p),window.dispatchEvent(new CustomEvent(eo,{detail:p}));},[p]);let h={"--p":`${String(n)}%`},f={"--p":`${String(r)}%`},g={"--p":`${String(o)}%`},v={"--p":`${String(d)}%`},b={"--p":`${String(p)}%`};return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("div",{className:"set-sec-h",children:(0,a.jsxs)("div",{children:[(0,a.jsx)("div",{className:"set-sec-t",children:"Workspace wallpaper"}),(0,a.jsx)("div",{className:"set-sec-d",children:"Liquid Chrome — a subtle metallic flow behind the grid that reacts to your cursor and clicks. Turn it off to stop the WebGL animation completely."})]})}),(0,a.jsxs)("div",{className:"gpref",children:[(0,a.jsxs)("div",{className:"gpref-row",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("div",{className:"gpref-label",children:"Liquid wallpaper"}),(0,a.jsx)("div",{className:"gpref-help",children:e?"Running":"Stopped"})]}),(0,a.jsx)(aA,{on:e,onChange:t,label:"Liquid wallpaper"})]}),(0,a.jsxs)("div",{className:"gpref-row",children:[(0,a.jsx)("label",{className:"gpref-label",htmlFor:"wp-op",children:"Wallpaper opacity"}),(0,a.jsxs)("span",{className:"gpref-val mono",children:[n,"%"]})]}),(0,a.jsx)("input",{id:"wp-op",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:n,disabled:!e,onChange:e=>l(Number.parseInt(e.target.value,10)),style:h,"aria-label":"Wallpaper opacity"}),(0,a.jsxs)("div",{className:"gpref-scale",children:[(0,a.jsx)("span",{children:"Off"}),(0,a.jsx)("span",{children:"Full"})]})]}),(0,a.jsxs)("div",{className:"gpref",children:[(0,a.jsxs)("div",{className:"gpref-row",children:[(0,a.jsx)("label",{className:"gpref-label",htmlFor:"ws-bg-bright",children:"Workspace background brightness"}),(0,a.jsxs)("span",{className:"gpref-val mono",children:[r,"%"]})]}),(0,a.jsx)("input",{id:"ws-bg-bright",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:r,onChange:e=>s(Number.parseInt(e.target.value,10)),style:f,"aria-label":"Workspace background brightness"}),(0,a.jsxs)("div",{className:"gpref-scale",children:[(0,a.jsx)("span",{children:"Base"}),(0,a.jsx)("span",{children:"Lighter"})]})]}),(0,a.jsxs)("div",{className:"gpref",children:[(0,a.jsxs)("div",{className:"gpref-row",children:[(0,a.jsx)("label",{className:"gpref-label",htmlFor:"ws-grid-strength",children:"Workspace grid strength"}),(0,a.jsxs)("span",{className:"gpref-val mono",children:[o,"%"]})]}),(0,a.jsx)("input",{id:"ws-grid-strength",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:o,onChange:e=>c(Number.parseInt(e.target.value,10)),style:g,"aria-label":"Workspace grid strength"}),(0,a.jsxs)("div",{className:"gpref-scale",children:[(0,a.jsx)("span",{children:"Subtle"}),(0,a.jsx)("span",{children:"Strong"})]})]}),(0,a.jsxs)("div",{className:"gpref",children:[(0,a.jsxs)("div",{className:"gpref-row",children:[(0,a.jsx)("label",{className:"gpref-label",htmlFor:"frame-border-strength",children:"Workspace border strength"}),(0,a.jsxs)("span",{className:"gpref-val mono",children:[d,"%"]})]}),(0,a.jsx)("input",{id:"frame-border-strength",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:d,onChange:e=>u(Number.parseInt(e.target.value,10)),style:v,"aria-label":"Workspace border strength"}),(0,a.jsxs)("div",{className:"gpref-scale",children:[(0,a.jsx)("span",{children:"Subtle"}),(0,a.jsx)("span",{children:"Strong"})]})]}),(0,a.jsxs)("div",{className:"gpref",children:[(0,a.jsxs)("div",{className:"gpref-row",children:[(0,a.jsx)("label",{className:"gpref-label",htmlFor:"frame-inner-glow-strength",children:"Workspace inner glow"}),(0,a.jsxs)("span",{className:"gpref-val mono",children:[p,"%"]})]}),(0,a.jsx)("input",{id:"frame-inner-glow-strength",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:p,onChange:e=>m(Number.parseInt(e.target.value,10)),style:b,"aria-label":"Workspace inner glow"}),(0,a.jsxs)("div",{className:"gpref-scale",children:[(0,a.jsx)("span",{children:"Off"}),(0,a.jsx)("span",{children:"Strong"})]})]})]});}function sd(){var e;let[t,n]=(0,i.useState)("models"),[l,r]=(0,i.useState)([]),[s,o]=(0,i.useState)(null),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!0),[m,h]=(0,i.useState)(),[f,g]=(0,i.useState)(!1),[v,b]=(0,i.useState)(0);(0,i.useEffect)(()=>{let e=!1;return async function(){p(!0),h(void 0);try{let[t,n]=await Promise.all([(0,k.Dz)(),(0,k.ZC)()]);if(e)return;o(t.config),d(t.configPresent),r(n.models);}catch(t){if(e)return;h(function(e){let t="Could not load gateway settings — the local Keiko backend did not respond.";if(!(e instanceof Error))return t;let n=e.message.trim();return 0===n.length||/^HTTP \d+$/u.test(n)||"Failed to fetch"===n||"Load failed"===n||"NetworkError when attempting to fetch a resource."===n?t:n;}(t));}finally{e||p(!1);}}(),()=>{e=!0;};},[v]);let x=l.filter(nb.S_).length,y=l.length>0,w=c?y?0===x?"Gateway connected, but none of the discovered models can be used for conversation. Add a chat-capable deployment.":"Keiko can use the configured gateway models for chat and agent workflows.":"The gateway is configured, but no conversation-capable models are currently available.":"Enter the gateway base URL and API token before using chat or agent workflows.",j=c?"connected":"untested";return(0,a.jsxs)("div",{className:"set",children:[(0,a.jsxs)("div",{className:"set-hero",children:[(0,a.jsx)(N.F.settings,{size:18}),(0,a.jsx)("span",{className:"set-title",children:"Settings"}),(0,a.jsxs)("span",{className:"set-onprem",title:"Runs inside your network",children:[(0,a.jsx)("span",{className:"dot",style:{background:"var(--accent)"}})," Self-hosted"]})]}),(0,a.jsx)("div",{className:"set-tabs",children:["models","general","security"].map(e=>(0,a.jsx)("button",{type:"button",className:"set-tab","data-on":t===e,"aria-pressed":t===e,onPointerDown:()=>n(e),onClick:()=>n(e),children:"models"===e?"Models":"general"===e?"General":"Security"},e))}),(0,a.jsxs)("div",{className:"set-body",children:["models"===t&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"set-sec-h",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("div",{className:"set-sec-t",children:"Model gateway"}),(0,a.jsx)("div",{className:"set-sec-d",children:"Credentials are stored locally by the Keiko loopback server; secrets are never returned to the browser."})]}),(0,a.jsxs)("button",{type:"button",className:"set-add",onClick:()=>g(!0),children:[(0,a.jsx)(N.F.plus,{size:14}),c?"Update credentials":"Connect gateway"]})]}),(0,a.jsxs)("div",{className:"ml-row",children:[(0,a.jsx)("span",{className:"ml-ico",children:(0,a.jsx)(N.F.cube,{size:16})}),(0,a.jsxs)("div",{className:"ml-info",children:[(0,a.jsxs)("div",{className:"ml-top",children:[(0,a.jsx)("span",{className:"ml-name",children:c?y?"Gateway connected":"Gateway configured":"Gateway setup required"}),(0,a.jsxs)("span",{className:"ml-type mono",children:[l.length.toString()," models"]}),(0,a.jsxs)("span",{className:"ml-type mono",children:[x.toString()," chat"]})]}),(0,a.jsx)("div",{className:"ml-url mono",children:w})]}),(0,a.jsx)("span",{className:"ml-status "+j,title:c?"gateway configured":"setup required","aria-hidden":"true"})]}),void 0!==m?(0,a.jsxs)("div",{className:"gw-error",role:"alert",children:[m,(0,a.jsx)("button",{type:"button",className:"gw-error-retry",onClick:()=>b(e=>e+1),children:"Retry"})]}):null,u?(0,a.jsx)("div",{className:"set-placeholder",role:"status",children:"Loading gateway models…"}):0===l.length?(0,a.jsx)("div",{className:"set-placeholder",role:"status",children:c?"No conversation-capable models are currently available. Review the gateway configuration or discovered model set.":"No models are configured yet. Connect the gateway to load configured model capabilities."}):(0,a.jsx)("div",{className:"set-list",children:l.map(e=>(0,a.jsx)(so,{model:e},e.id))}),f?(0,a.jsx)(tL,{onCancel:()=>g(!1),preserveExisting:c,storedApiKeyHeaderName:null==s||null==(e=s.providers[0])?void 0:e.credentialHeaderName,storedModels:l}):null]}),"general"===t&&(0,a.jsx)(sc,{}),"security"===t&&(0,a.jsx)("div",{className:"set-placeholder",children:"SSO \xb7 audit log \xb7 data residency — coming soon."})]})]});}function su(e){return e instanceof k.hD?`${e.message} (${e.code})`:e instanceof Error?e.message:"Failed to load connectors.";}function sp(){return(0,a.jsx)("div",{className:"connector-picker-status",role:"status","aria-live":"polite",children:"Loading connectors…"});}function sm(e){let{message:t,onRetry:n}=e;return(0,a.jsxs)("div",{className:"connector-picker-error",role:"alert",children:[(0,a.jsx)("p",{children:t}),(0,a.jsx)("button",{type:"button",className:"connector-picker-retry",onClick:n,children:"Try again"})]});}function sh(e){let{onManageConnectors:t}=e;return(0,a.jsx)("div",{className:"connector-picker-empty",children:(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-primary connector-picker-create-link",onClick:t,children:"Create a connector"})});}function sf(e){let{capsules:t,capsuleSets:n,selectedKind:l,selectedId:i}=e,r=function(e,t,n,l){if(void 0===n||void 0===l||0===l.length)return null;if("capsule"===n){let t=e.find(e=>e.id===l);return void 0!==t?t.displayName:`Capsule ${l}`;}if("capsule-set"===n){let e=t.find(e=>e.id===l);return void 0!==e?e.displayName:`Set ${l}`;}return null;}(t,n,l,i);return null===r?null:(0,a.jsxs)("div",{className:"connector-picker-selected",role:"status","aria-live":"polite",children:[(0,a.jsx)("span",{"aria-hidden":"true",children:"●"}),(0,a.jsx)("span",{children:r})]});}function sg(e){let{selectedId:t,selectedLabel:n,selectedState:l,onManageConnectors:i}=e,r=void 0!==n&&n.trim().length>0?n.trim():`Capsule ${t}`;return(0,a.jsxs)("div",{className:"connector-node","data-testid":"knowledge-connector-node",children:[(0,a.jsx)("div",{className:"connector-node-icon","aria-hidden":"true",children:(0,a.jsx)(N.F.server,{size:42})}),(0,a.jsxs)("div",{className:"connector-node-copy",children:[(0,a.jsx)("p",{className:"connector-node-kicker",children:function(e){switch(e){case"ready":return"Indexed";case"draft":return"Draft";case"indexing":return"Indexing";case"stale":return"Stale";case"error":return"Failed";default:return"Local Knowledge";}}(l)}),(0,a.jsx)("h2",{className:"connector-node-title",title:r,children:r}),(0,a.jsx)("p",{className:"connector-node-id mono",title:t,children:t})]}),(0,a.jsx)("button",{type:"button",className:"connector-node-manage",onClick:i,children:"Manage"})]});}function sv(e){let{selectedKind:t,selectedId:n,selectedLabel:l,selectedState:r,presentation:s,onSelect:o,onManageConnectors:c=()=>void 0}=e,[d,u]=(0,i.useState)([]),[p,m]=(0,i.useState)([]),[h,f]=(0,i.useState)(!0),[g,v]=(0,i.useState)(null),[b,x]=(0,i.useState)(!1),[y,w]=(0,i.useState)(0),j="node"===s&&"capsule"===t&&void 0!==n&&n.length>0;if((0,i.useEffect)(()=>{if(j)return;let e=!1;return async function(){f(!0),v(null),x(!1);try{let[t,n]=await Promise.allSettled([(0,aF.xr)(),(0,aF.R3)()]);if(e)return;"fulfilled"===t.status?u(t.value.capsules.filter(e=>"ready"===e.lifecycleState)):v(su(t.reason)),"fulfilled"===n.status?m(n.value.capsuleSets):x(!0);}catch(t){e||v(su(t));}finally{e||f(!1);}}(),()=>{e=!0;};},[j,y]),j)return(0,a.jsx)(sg,{selectedId:n,selectedLabel:l,selectedState:r,onManageConnectors:c});if(h)return(0,a.jsx)(sp,{});if(null!==g)return(0,a.jsx)(sm,{message:g,onRetry:()=>{w(e=>e+1);}});let k=d.length>0,N=p.length>0;if(!k&&!N)return(0,a.jsx)(sh,{onManageConnectors:c});let S=void 0!==t&&void 0!==n&&n.length>0?`${t}:${n}`:"";return(0,a.jsxs)("div",{className:"connector-picker",children:[(0,a.jsx)(sf,{capsules:d,capsuleSets:p,selectedKind:t,selectedId:n}),(0,a.jsx)("div",{className:"connector-picker-label",children:"Select a connector"}),(0,a.jsx)(tB,{triggerClassName:"connector-picker-select",value:S,ariaLabel:"Select a connector",placeholder:"— choose a connector —",menuTitle:"Available connectors",sections:[...(k?[{label:"Capsules",options:d.map(e=>({value:`capsule:${e.id}`,label:`${e.displayName} (${function(e){switch(e){case"ready":return"Ready";case"indexing":return"Indexing…";case"error":return"Failed";default:return e;}}(e.lifecycleState)})`}))}]:[]),...(N?[{label:"Capsule sets",options:p.map(e=>({value:`capsule-set:${e.id}`,label:`${e.displayName} (${String(e.capsuleCount)} capsules)`}))}]:[])],onValueChange:e=>{!function(e){if(""===e)return;let t=e.indexOf(":");if(-1===t)return;let n=e.slice(0,t),l=e.slice(t+1);0!==l.length&&o({selectedKind:n,selectedId:l});}(e);}}),b?(0,a.jsx)("p",{className:"connector-picker-notice",role:"status",children:"Capsule sets could not be loaded."}):null,(0,a.jsx)("div",{className:"connector-picker-footer",children:(0,a.jsx)("button",{type:"button",className:"connector-picker-create-link",onClick:c,children:"Create or manage connectors"})})]});}async function sb(e,t){var n,l;let a=(null!=(n=null==t?void 0:t.method)?n:"GET").toUpperCase(),i="GET"!==a&&"HEAD"!==a,r=await fetch(e,{...t,headers:{Accept:"application/json",...(i?{"Content-Type":"application/json"}:{}),...(i?{"X-Keiko-CSRF":"1"}:{}),...(null!=(l=null==t?void 0:t.headers)?l:{})}});if(!r.ok){let e="INTERNAL",t=`HTTP ${r.status.toString()}`;try{let n=await r.json();e=n.error.code,t=n.error.message;}catch{}throw new k.hD(e,t,r.status);}return r.json();}async function sx(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return sb("/api/figma/snapshots",{method:"POST",...(void 0!==t.signal?{signal:t.signal}:{}),body:JSON.stringify({boardLink:e,...(!0===t.acknowledgeReadOnly?{acknowledgeReadOnly:!0}:{}),...(!0===t.isResnapshot?{isResnapshot:!0}:{}),...(void 0!==t.version?{version:t.version}:{})})});}async function sy(e,t){return sb(`/api/figma/snapshots/${encodeURIComponent(e)}`,{...(void 0!==t?{signal:t}:{})});}async function sw(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=new URLSearchParams();void 0!==e.fileKey&&t.set("fileKey",e.fileKey),void 0!==e.nodeId&&t.set("nodeId",e.nodeId),void 0!==e.limit&&t.set("limit",String(e.limit));let n=t.size>0?`?${t.toString()}`:"";return(await sb(`/api/figma/snapshots${n}`,{...(void 0!==e.signal?{signal:e.signal}:{})})).snapshots;}async function sj(e,t,n){return sb(`/api/figma/snapshots/${encodeURIComponent(e)}`,{method:"PATCH",...(void 0!==n?{signal:n}:{}),body:JSON.stringify({displayName:t})});}async function sk(e,t){return sb(`/api/figma/snapshots/${encodeURIComponent(e)}`,{method:"DELETE",...(void 0!==t?{signal:t}:{})});}function sN(e,t){return`/api/figma/snapshots/${encodeURIComponent(e)}/screens/${encodeURIComponent(String(t))}/image`;}async function sS(e,t,n){return sb(`/api/figma/snapshots/${encodeURIComponent(e)}/screens/${encodeURIComponent(t)}/json`,{...(void 0!==n?{signal:n}:{})});}async function sC(e,t){return sb(`/api/figma/snapshots/${encodeURIComponent(e)}/code`,{method:"POST",...(void 0!==t?{signal:t}:{}),body:JSON.stringify({})});}async function sI(){return sb("/api/figma/token",{method:"DELETE",body:JSON.stringify({})});}let sR=/"(?:\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4})|[^"\\])*"\s*:?|[-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|\b(?:true|false|null)\b|[{}\[\],:]/gu;function sE(e){return 0===e.length?0:"u">typeof TextEncoder?new TextEncoder().encode(e).byteLength:e.length;}function s$(e){let{text:t,className:n}=e,l=function(e){let t=[],n=0;for(let l of e.matchAll(sR)){let a=l[0],i=l.index;i>n&&t.push(e.slice(n,i)),t.push({kind:a.startsWith('"')?a.endsWith(":")?"key":"string":"true"===a||"false"===a?"boolean":"null"===a?"null":/^-?\d/u.test(a)?"number":"punctuation",text:a}),n=i+a.length;}return n<e.length&&t.push(e.slice(n)),t;}(t);return(0,a.jsx)("pre",{className:n,children:(0,a.jsx)("code",{children:l.map((e,t)=>"string"==typeof e?e:(0,a.jsx)("span",{className:`json-token-${e.kind}`,children:e.text},`${e.kind}-${t.toString()}`))})});}let sA=[];function sF(e){try{let t=new URL(e.trim()),n=t.hostname.toLowerCase();if("https:"!==t.protocol||"figma.com"!==n&&"www.figma.com"!==n||!/^\/(design|file)\//u.test(t.pathname))return!1;let l=t.searchParams.get("node-id");return null!==l&&l.length>0;}catch{return!1;}}function sT(e){let t=new URL(`https://www.figma.com/design/${e.fileKey}/board`);return t.searchParams.set("node-id",e.nodeId),void 0!==e.version&&e.version.length>0&&t.searchParams.set("version",e.version),t.toString();}function sD(e){var t;return null!=(t=e.displayName)?t:`Snapshot ${(0,lD.Yq)(e.fetchedAt)}`;}function sq(e){return void 0===e||0===e.length?"Latest":e;}function sM(e){return e.length<=16?e:`${e.slice(0,12)}…`;}function sP(e){var t;return null!=(t=e.management)?t:{};}function sL(e,t){return{runId:e.runId,...(void 0!==t.displayName?{displayName:t.displayName}:{}),management:sP(t),fileKey:e.fileKey,nodeId:e.nodeId,version:e.version,fetchedAt:e.fetchedAt,screenCount:e.screenCount,skippedCount:e.skippedCount,...(void 0!==e.structuralOnlyCount?{structuralOnlyCount:e.structuralOnlyCount}:{}),reductionHint:e.reductionHint,integrityHash:e.integrityHash};}let sz=new Set(["FIGMA_PROXY_EGRESS_FAILED","FIGMA_PROXY_UNREACHABLE","FIGMA_PROXY_AUTH_REQUIRED","FIGMA_PROXY_BLOCKED_BY_POLICY"]),sO=new Set(["FIGMA_TLS_CA_FAILURE"]),sK=new Set(["FIGMA_NETWORK_UNREACHABLE","FIGMA_EGRESS_TIMEOUT","FIGMA_EGRESS_FAILED"]);function sB(e){return e instanceof k.hD?"FIGMA_UPSTREAM_UNAVAILABLE"===e.code?{title:"Figma is currently unavailable",detail:`${e.code}: ${e.message}`,status:`HTTP ${e.status.toString()}`,remediation:"Retry later — no snapshot was stored.",assertive:!0}:sz.has(e.code)?{title:"Figma snapshot blocked by outbound egress",detail:`${e.code}: ${e.message}`,status:`HTTP ${e.status.toString()}`,remediation:"Check the configured proxy, NO_PROXY rules, and CA bundle, then retry. No snapshot was stored.",assertive:!0}:sO.has(e.code)?{title:"Figma snapshot blocked by outbound egress",detail:`${e.code}: ${e.message}`,status:`HTTP ${e.status.toString()}`,remediation:"A TLS certificate verification failure blocked the request. Check the CA bundle configuration, then retry. No snapshot was stored.",assertive:!0}:sK.has(e.code)?{title:"Figma snapshot blocked by outbound egress",detail:`${e.code}: ${e.message}`,status:`HTTP ${e.status.toString()}`,remediation:"The outbound network request to Figma failed. Check DNS resolution and network connectivity, then retry. No snapshot was stored.",assertive:!0}:{title:"Figma snapshot failed",detail:e.message}:e instanceof Error?{title:"Figma snapshot failed",detail:e.message}:{title:"Figma snapshot failed",detail:"An unexpected error occurred."};}function sW(e){let t=sB(e);return void 0===t.status?t.detail:`${t.detail} (${t.status})`;}function sU(e,t){let n=document.elementFromPoint(e,t);return n instanceof Element&&null!==n.closest("main.workspace")&&null===n.closest(".window");}function s_(e,t){let n={payload:e,clientX:t.clientX,clientY:t.clientY};window.dispatchEvent(new CustomEvent(tf,{detail:n}));}function sV(e,t){let n={payload:e,clientX:t.clientX,clientY:t.clientY};window.dispatchEvent(new CustomEvent(tx,{detail:n}));}function sH(e,t){let n={payload:e,clientX:t.clientX,clientY:t.clientY};window.dispatchEvent(new CustomEvent(tk,{detail:n}));}function sJ(e){let{index:t,screenId:n,name:l,irSummary:r,imageSrc:s,imageByteLength:o,structuralReason:c,onAddSource:d,isSourceSelected:u=!1,dragPayload:p}=e,m=(0,i.useRef)(null),h=(0,i.useRef)(!1),f=(0,i.useRef)(!1),g=void 0!==p&&void 0!==d&&!u,v=u?`${l} preview is already the active scoped source`:`Drag screen ${l} to the workspace, or click to add it as a Quality Intelligence source`,b=void 0!==s?(0,a.jsx)(lS.default,{className:"figma-snapshot-screen-image",src:s,alt:`Captured preview for ${l}`,loading:"lazy",width:72,height:54,unoptimized:!0}):(0,a.jsxs)("div",{className:"figma-snapshot-screen-image figma-snapshot-screen-placeholder","aria-label":`Structural data only for ${l}`,role:"img",children:[(0,a.jsx)(N.F.layers,{className:"figma-snapshot-screen-frame-icon","aria-hidden":"true"}),(0,a.jsx)("span",{className:"figma-snapshot-screen-placeholder-label",children:"IR"})]});return(0,a.jsxs)("article",{className:"figma-snapshot-screen-card","aria-label":`Screen ${String(t+1)}: ${l}`,children:[void 0!==d?(0,a.jsx)("button",{type:"button",className:"figma-snapshot-screen-preview-btn",onClick:e=>{if(f.current){f.current=!1,e.preventDefault(),e.stopPropagation();return;}null==d||d();},disabled:u,"aria-disabled":u?"true":void 0,"aria-label":v,draggable:g,onDragStart:e=>{g&&(e.dataTransfer.effectAllowed="copy",e.dataTransfer.setData(th,JSON.stringify(p)),e.dataTransfer.setData("text/plain",l));},onDragEnd:e=>{g&&sU(e.clientX,e.clientY)&&s_(p,e);},onPointerDown:e=>{g&&0===e.button&&(h.current=!1,m.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY},e.currentTarget.setPointerCapture(e.pointerId));},onPointerMove:e=>{let t=m.current;null===t||t.pointerId!==e.pointerId||Math.hypot(e.clientX-t.startX,e.clientY-t.startY)>=6&&e.preventDefault();},onPointerUp:e=>{let t=m.current;if(null===t||t.pointerId!==e.pointerId)return;m.current=null,e.currentTarget.releasePointerCapture(e.pointerId);let n=Math.hypot(e.clientX-t.startX,e.clientY-t.startY);n>=6&&(h.current=!0),n>=6&&void 0!==p&&sU(e.clientX,e.clientY)&&(e.preventDefault(),f.current=!0,s_(p,e));},onPointerCancel:e=>{let t=m.current;null!==t&&t.pointerId===e.pointerId&&(m.current=null,e.currentTarget.releasePointerCapture(e.pointerId));},onMouseDown:e=>{if(!g||0!==e.button||void 0===p)return;let t=e.clientX,n=e.clientY,l=e=>{Math.hypot(e.clientX-t,e.clientY-n)>=6&&e.preventDefault();},a=e=>{if(window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",a),h.current){h.current=!1;return;}Math.hypot(e.clientX-t,e.clientY-n)>=6&&sU(e.clientX,e.clientY)&&(e.preventDefault(),f.current=!0,s_(p,e));};window.addEventListener("mousemove",l),window.addEventListener("mouseup",a);},children:b}):b,(0,a.jsxs)("div",{className:"figma-snapshot-screen-meta",children:[(0,a.jsx)("h3",{className:"figma-snapshot-screen-name",title:l,children:l}),(0,a.jsx)("p",{className:"figma-snapshot-screen-summary",children:r}),(0,a.jsx)("p",{className:"figma-snapshot-screen-size",children:void 0!==o?(0,lD.z3)(o):`Structural IR only${void 0!==c?` (${c})`:""}`}),(0,a.jsx)("p",{className:"figma-snapshot-screen-id",children:n}),void 0!==d?(0,a.jsx)("div",{className:"figma-snapshot-screen-actions",children:(0,a.jsx)("button",{type:"button",className:"figma-snapshot-screen-source-btn",onClick:d,disabled:u,"aria-disabled":u?"true":void 0,"aria-label":u?`${l} is already the active scoped source`:`Add screen ${l} to the workspace as a Quality Intelligence source`,children:u?"Source active":"Add to workspace"})}):null]})]});}function sY(e){let{name:t,screenId:n,irSummary:l,imageSrc:r,imageByteLength:s,structuralReason:o,snapshotRunId:c,capturedAt:d,imageDragPayload:u}=e,p=(0,i.useRef)(null),m=(0,i.useRef)(!1),h=void 0!==r&&void 0!==u,f=void 0!==r?(0,a.jsx)(lS.default,{className:"figma-view-preview-image",src:r,alt:`Captured preview for ${t}`,loading:"eager",width:360,height:240,draggable:!1,unoptimized:!0}):(0,a.jsxs)("div",{className:"figma-view-preview-image figma-view-preview-placeholder","aria-label":`Structural data only for ${t}`,role:"img",children:[(0,a.jsx)(N.F.layers,{className:"figma-view-preview-icon","aria-hidden":"true"}),(0,a.jsx)("span",{children:"Structural IR"})]});return(0,a.jsxs)("article",{className:"figma-view-source-card","aria-label":`Figma view source: ${t}`,children:[h?(0,a.jsx)("button",{type:"button",className:"figma-view-preview figma-view-preview-drag-surface",draggable:!0,onDragStart:e=>{h&&(e.dataTransfer.effectAllowed="copyMove",e.dataTransfer.setData(tj,JSON.stringify(u)),e.dataTransfer.setData("text/plain",`${u.name}.png`));},onDragEnd:e=>{h&&sU(e.clientX,e.clientY)&&sH(u,e);},onKeyDown:e=>{if(!h||"Enter"!==e.key&&" "!==e.key)return;e.preventDefault();let t=e.currentTarget.getBoundingClientRect();sH(u,{clientX:t.right+24,clientY:t.top+t.height/2});},onPointerDown:e=>{h&&0===e.button&&(m.current=!1,p.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY},e.currentTarget.setPointerCapture(e.pointerId));},onPointerMove:e=>{let t=p.current;null===t||t.pointerId!==e.pointerId||Math.hypot(e.clientX-t.startX,e.clientY-t.startY)>=6&&e.preventDefault();},onPointerUp:e=>{let t=p.current;if(null===t||t.pointerId!==e.pointerId)return;p.current=null,e.currentTarget.releasePointerCapture(e.pointerId);let n=Math.hypot(e.clientX-t.startX,e.clientY-t.startY);n>=6&&(m.current=!0),n>=6&&h&&sU(e.clientX,e.clientY)&&(e.preventDefault(),sH(u,e));},onPointerCancel:e=>{let t=p.current;null!==t&&t.pointerId===e.pointerId&&(p.current=null,e.currentTarget.releasePointerCapture(e.pointerId));},onMouseDown:e=>{if(!h||0!==e.button)return;let t=e.clientX,n=e.clientY,l=e=>{Math.hypot(e.clientX-t,e.clientY-n)>=6&&e.preventDefault();},a=e=>{if(window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",a),m.current){m.current=!1;return;}Math.hypot(e.clientX-t,e.clientY-n)>=6&&sU(e.clientX,e.clientY)&&(e.preventDefault(),sH(u,e));};window.addEventListener("mousemove",l),window.addEventListener("mouseup",a);},"aria-label":`Create a standalone image source for ${t}`,title:`Drag image for ${t} to the workspace`,children:f}):(0,a.jsx)("div",{className:"figma-view-preview",children:f}),(0,a.jsxs)("div",{className:"figma-view-source-meta",children:[(0,a.jsx)("p",{className:"figma-view-source-kicker",children:"QI view source"}),(0,a.jsx)("h2",{className:"figma-view-source-title",title:t,children:t}),(0,a.jsx)("p",{className:"figma-view-source-summary",children:l}),(0,a.jsxs)("dl",{className:"figma-view-source-facts",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Screen"}),(0,a.jsx)("dd",{children:n})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Snapshot"}),(0,a.jsx)("dd",{children:c})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Captured"}),(0,a.jsx)("dd",{children:d})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Preview"}),(0,a.jsx)("dd",{children:void 0!==s?(0,lD.z3)(s):`Structural IR${void 0!==o?` (${o})`:""}`})]})]})]})]});}function sX(e){var t,n,l,r,s;let o,c,d,u,{sourceWindowId:p,snapshotRunId:m,selectedScreenIds:h=sA,selectedScreenName:f,openScreenSource:g,updateCfg:v,triggerImpl:b=sx,loadImpl:x=sy,listImpl:y=sw,updateMetadataImpl:w=sj,deleteImpl:j=sk,loadScreenJsonImpl:S=sS,codegenImpl:C=sC,revokeImpl:I=sI}=e,R=(0,i.useId)(),E=(0,i.useId)(),$=(0,i.useId)(),A=(0,i.useId)(),[F,T]=(0,i.useState)(""),[D,q]=(0,i.useState)("idle"),[M,P]=(0,i.useState)(null),[L,z]=(0,i.useState)(null),[O,K]=(0,i.useState)(null),[B,W]=(0,i.useState)(null),[U,_]=(0,i.useState)(0),[V,H]=(0,i.useState)("recent"),[J,Y]=(0,i.useState)([]),[X,G]=(0,i.useState)([]),[Q,Z]=(0,i.useState)(!1),[ee,et]=(0,i.useState)(!1),[en,el]=(0,i.useState)(null),[ea,ei]=(0,i.useState)(null),[er,es]=(0,i.useState)(null),[eo,ec]=(0,i.useState)(""),[ed,eu]=(0,i.useState)(null),[ep,em]=(0,i.useState)(null),[eh,ef]=(0,i.useState)(null),[eg,ev]=(0,i.useState)(null),[eb,ex]=(0,i.useState)(!1),[ey,ew]=(0,i.useState)(!1),ej=(0,i.useRef)(null),ek=(0,i.useRef)(null),eN=(0,i.useRef)(null),eS=(0,i.useRef)(null),eC=(0,i.useRef)(null),eI=(0,i.useRef)(null),eR=(0,i.useRef)(null),eE=(0,i.useRef)(null),e$=(0,i.useRef)(!1),eA=(0,i.useCallback)(()=>{ew(!0);},[]),[eF,eT]=(0,i.useState)("idle"),[eD,eq]=(0,i.useState)(null),[eM,eP]=(0,i.useState)(null),[eL,ez]=(0,i.useState)("idle"),[eO,eK]=(0,i.useState)(null),[eB,eW]=(0,i.useState)(null),[eU,e_]=(0,i.useState)(null),[eV,eH]=(0,i.useState)(!1),[eJ,eY]=(0,i.useState)(null),[eX,eG]=(0,i.useState)(null),eQ=(0,i.useRef)(null),eZ=(0,i.useRef)(null),[e0,e1]=(0,i.useState)(24),e2=h.join("\0"),e3=sF(F),e4=function(e){let t=e.trim();if(0===t.length||sF(t))return null;try{let e=new URL(t),n=e.hostname.toLowerCase();if("https:"===e.protocol&&("figma.com"===n||"www.figma.com"===n)&&/^\/(design|file)\//u.test(e.pathname))return"Add a node-id by selecting a frame or section in Figma and copying its link (Copy link to selection).";}catch{}return"This doesn't look like a Figma board link. Use a figma.com design/file link that includes a node-id parameter.";}(F),e6=(0,i.useMemo)(()=>null!==M?{fileKey:M.fileKey,nodeId:M.nodeId}:function(e){try{let t=new URL(e.trim()),n=t.hostname.toLowerCase();if("https:"!==t.protocol||"figma.com"!==n&&"www.figma.com"!==n)return null;let[,l,a]=t.pathname.split("/");if("design"!==l&&"file"!==l||void 0===a||0===a.length)return null;let i=t.searchParams.get("node-id");if(null===i||0===i.length)return null;return{fileKey:a,nodeId:i};}catch{return null;}}(F),[F,M]),e5=null==e6?void 0:e6.fileKey,e8=null==e6?void 0:e6.nodeId,e7="building"===D,e9="loading"===D,te=e7||e9,tt=e7&&null!==B?(c=Math.floor((o=Math.max(0,Math.floor(U/1e3)))/3600),d=Math.floor(o%3600/60),u=o%60,c>0?`${String(c)}h ${String(d)}m ${String(u)}s`:d>0?`${String(d)}m ${String(u)}s`:`${String(u)}s`):null,tn=(0,i.useMemo)(()=>new Set(h),[h]),tl=h.length>0,ta=tl&&void 0!==m&&m.length>0,ti=(0,i.useMemo)(()=>{var e;if(null===M)return[];let t=new Set(M.screens.map(e=>e.screenId)),n=[...M.screens.map((e,t)=>({kind:"rendered",screen:e,imageIndex:t})),...(null!=(e=M.structuralScreens)?e:[]).filter(e=>!t.has(e.screenId)).map(e=>({kind:"structural",screen:e}))];return tl?n.filter(e=>tn.has(e.screen.screenId)):n;},[tl,tn,M]),tr=1===h.length?h[0]:void 0,ts=(0,i.useMemo)(()=>null===eO?"":JSON.stringify(eO,null,2),[eO]),to=(0,i.useMemo)(()=>sE(ts),[ts]),tc=(null!=(t=null==M?void 0:M.screens.length)?t:0)+(null!=(n=null==M||null==(r=M.structuralScreens)?void 0:r.length)?n:0),td=null===M?{}:sP(M);(0,i.useEffect)(()=>{var e;ey&&"error"===D&&(null==(e=ej.current)||e.focus());},[ey,D]),(0,i.useEffect)(()=>{var e;eV&&(null==(e=eQ.current)||e.focus());},[eV]),(0,i.useEffect)(()=>{if(!e7||null===B)return;_(Date.now()-B);let e=window.setInterval(()=>{_(Date.now()-B);},1e3);return()=>{window.clearInterval(e);};},[e7,B]),(0,i.useEffect)(()=>()=>{var e,t,n,l,a;null==(e=ek.current)||e.abort(),null==(t=eN.current)||t.abort(),null==(n=eS.current)||n.abort(),null==(l=eC.current)||l.abort(),null==(a=eI.current)||a.abort();},[]),(0,i.useEffect)(()=>{null===e6&&"board"===V&&H("recent");},[e6,V]);let tu=(0,i.useCallback)(()=>{var e;null==(e=eC.current)||e.abort();let t=new AbortController();if(eC.current=t,et(!0),ei(null),y({limit:12,signal:t.signal}).then(e=>{G(e);}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||(G([]),ei(sW(e)));}).finally(()=>{eC.current===t&&et(!1);}),void 0===e5||void 0===e8){Y([]),el(null),Z(!1);return;}Z(!0),el(null),y({fileKey:e5,nodeId:e8,limit:12,signal:t.signal}).then(e=>{Y(e);}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||(Y([]),el(sW(e)));}).finally(()=>{eC.current===t&&Z(!1);});},[e5,e8,y]);(0,i.useEffect)(()=>{tu();},[tu,null==M?void 0:M.runId]);let tp=(0,i.useCallback)(e=>{var t;if(0===e.length||te)return;null==(t=ek.current)||t.abort();let n=new AbortController();ek.current=n,q("loading"),z(null),K(null),eT("idle"),eq(null),eP(null),ez("idle"),eK(null),eW(null),e_(null),x(e,n.signal).then(e=>{P(e),T(sT(e)),v({snapshotRunId:e.runId}),q("done");}).catch(t=>{t instanceof DOMException&&"AbortError"===t.name||(t instanceof k.hD&&"FIGMA_SNAPSHOT_NOT_FOUND"===t.code?(m===e&&v({snapshotRunId:void 0}),z({...sB(t),detail:m===e?`${t.message} The stored run ID has been cleared.`:t.message})):z(sB(t)),q("error"));});},[te,x,m,v]);(0,i.useEffect)(()=>{ta&&void 0!==m&&0!==m.length&&null===M&&"idle"===D&&tp(m);},[D,ta,tp,m,M]);let tm=(0,i.useCallback)(async(e,t)=>{var n,l,a;null==(n=ek.current)||n.abort(),null==(l=eN.current)||l.abort(),null==(a=eS.current)||a.abort(),eN.current=null,eS.current=null;let i=new AbortController();ek.current=i,eR.current={link:e,isResnapshot:t},q("building"),z(null),K(null),W(Date.now()),_(0),eT("idle"),eq(null),ez("idle"),eK(null),eW(null),e_(null);try{let n=await b(e,{acknowledgeReadOnly:eb,isResnapshot:t,signal:i.signal});P(n),T(sT(n)),v({snapshotRunId:n.runId}),q("done"),W(null),_(0),eR.current=null;}catch(n){if(n instanceof DOMException&&"AbortError"===n.name)return;if(W(null),_(0),n instanceof k.hD&&"FIGMA_CONSENT_REQUIRED"===n.code){let e=sB(n);z({...e,detail:`${e.detail} Tick the acknowledgement checkbox below, then snapshot again.`}),eA();}else n instanceof k.hD&&"FIGMA_BUILD_TIMEOUT"===n.code?(K({link:e,isResnapshot:t}),z({title:"Figma snapshot is still running",detail:"This window stopped waiting for the snapshot result. The server may still finish the build in the background.",status:`HTTP ${n.status.toString()}`,remediation:"Reconnect to the same board to keep waiting, or close this window and return later."})):z(sB(n));q("error"),eR.current=null;}},[b,v,eb,eA]),th=(0,i.useCallback)(e=>{if(e.preventDefault(),e3&&!te){if(!eb){z({title:"Figma snapshot failed",detail:"Tick the read-only acknowledgement checkbox below, then snapshot again."}),q("error"),eA();return;}tm(F,!1);}},[F,te,eb,e3,tm,eA]),tf=(0,i.useCallback)(()=>{te||null!==M&&tm(sT(M),!0);},[te,tm,M]),tg=(0,i.useCallback)(()=>{var e;null==(e=ek.current)||e.abort(),ek.current=null,W(null),_(0),null!==eR.current&&K(eR.current),eR.current=null,q("idle"),z(null);},[]),tv=(0,i.useCallback)(()=>{te||null===O||tm(O.link,O.isResnapshot);},[te,O,tm]),tx=(0,i.useCallback)(()=>{var e;let t=null!=(e=null==M?void 0:M.runId)?e:m;if(void 0===t||0===t.length||"generating"===eF)return;let n=new AbortController();eN.current=n,eT("generating"),eP(null),C(t,n.signal).then(e=>{eq(e),eT("done");}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name?eT("idle"):(eP(sW(e)),eT("error"));}).finally(()=>{eN.current===n&&(eN.current=null);});},[C,eF,m,M]),ty=(0,i.useCallback)(()=>{var e,t;let n=null!=(e=null==M?void 0:M.runId)?e:m;if(void 0===n||0===n.length||void 0===tr||"loading"===eL)return;null==(t=eS.current)||t.abort();let l=new AbortController();eS.current=l,ez("loading"),eW(null),e_(null),S(n,tr,l.signal).then(e=>{eK(e),ez("done");}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name?ez("idle"):(eK(null),eW(sW(e)),ez("error"));}).finally(()=>{eS.current===l&&(eS.current=null);});},[tr,S,eL,m,null==M?void 0:M.runId]),tw=(0,i.useCallback)(()=>{if(0!==ts.length){if(void 0===navigator.clipboard)return void e_("Clipboard unavailable");navigator.clipboard.writeText(ts).then(()=>{e_("Copied");}).catch(()=>{e_("Copy failed");});}},[ts]),tj=(0,i.useMemo)(()=>{var e,t,n,l,a;let i=null!=(e=null!=(t=null==eO?void 0:eO.runId)?t:null==M?void 0:M.runId)?e:m,r=null!=(n=null==eO?void 0:eO.screen.screenId)?n:tr,s=null!=(l=null!=(a=null==eO?void 0:eO.screen.name)?a:f)?l:r;return void 0===i||0===i.length||void 0===r||0===r.length||void 0===s||0===s.length?null:{snapshotRunId:i,screenId:r,name:s,...(void 0!==p?{sourceWindowId:p}:{})};},[tr,null==eO?void 0:eO.runId,null==eO?void 0:eO.screen.name,null==eO?void 0:eO.screen.screenId,f,m,p,null==M?void 0:M.runId]),tk=(0,i.useCallback)(e=>{null!==tj&&(e.dataTransfer.effectAllowed="copyMove",e.dataTransfer.setData(tb,JSON.stringify(tj)),e.dataTransfer.setData("text/plain",`${tj.name}.json`));},[tj]),tN=(0,i.useCallback)(e=>{null!==tj&&sU(e.clientX,e.clientY)&&sV(tj,e);},[tj]),tS=(0,i.useCallback)(e=>{if(null===tj||"Enter"!==e.key&&" "!==e.key)return;e.preventDefault();let t=e.currentTarget.getBoundingClientRect();sV(tj,{clientX:t.right+24,clientY:t.top+t.height/2});},[tj]),tC=(0,i.useCallback)(e=>{null!==tj&&0===e.button&&(e$.current=!1,eE.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY},e.currentTarget.setPointerCapture(e.pointerId));},[tj]),tI=(0,i.useCallback)(e=>{let t=eE.current;null===t||t.pointerId!==e.pointerId||Math.hypot(e.clientX-t.startX,e.clientY-t.startY)>=6&&e.preventDefault();},[]),tR=(0,i.useCallback)(e=>{let t=eE.current;if(null===t||t.pointerId!==e.pointerId)return;eE.current=null,e.currentTarget.releasePointerCapture(e.pointerId);let n=Math.hypot(e.clientX-t.startX,e.clientY-t.startY);n>=6&&(e$.current=!0),n>=6&&null!==tj&&sU(e.clientX,e.clientY)&&(e.preventDefault(),sV(tj,e));},[tj]),tE=(0,i.useCallback)(e=>{let t=eE.current;null!==t&&t.pointerId===e.pointerId&&(eE.current=null,e.currentTarget.releasePointerCapture(e.pointerId));},[]),t$=(0,i.useCallback)(e=>{if(null===tj||0!==e.button)return;let t=e.clientX,n=e.clientY,l=e=>{Math.hypot(e.clientX-t,e.clientY-n)>=6&&e.preventDefault();},a=e=>{if(window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",a),e$.current){e$.current=!1;return;}Math.hypot(e.clientX-t,e.clientY-n)>=6&&sU(e.clientX,e.clientY)&&(e.preventDefault(),sV(tj,e));};window.addEventListener("mousemove",l),window.addEventListener("mouseup",a);},[tj]),tA=(0,i.useCallback)(()=>{var e;null==(e=eN.current)||e.abort(),eN.current=null,eT("idle"),eP(null);},[]),tF=(0,i.useCallback)(()=>{void 0===m||0===m.length||te||tp(m);},[te,tp,m]);(0,i.useEffect)(()=>{e1(24);},[e2,null==M?void 0:M.runId]),(0,i.useEffect)(()=>{var e;null==(e=eS.current)||e.abort(),eS.current=null,ez("idle"),eK(null),eW(null),e_(null);},[e2,m]);let tT=(0,i.useCallback)(()=>{eH(!1),eG(null),eY(null),I().then(e=>{eY(e.message),requestAnimationFrame(()=>{var e;return null==(e=eZ.current)?void 0:e.focus();});}).catch(e=>{eG(sW(e)),requestAnimationFrame(()=>{var e;return null==(e=eZ.current)?void 0:e.focus();});});},[I]),tD=(0,i.useCallback)(()=>{eH(!1),requestAnimationFrame(()=>{var e;return null==(e=eZ.current)?void 0:e.focus();});},[]),tq=(0,i.useCallback)(e=>{var t;es(e.runId),ec(null!=(t=e.displayName)?t:""),eu(null),em(null),ev(null);},[]),tM=(0,i.useCallback)(()=>{es(null),ec("");},[]),tP=(0,i.useCallback)(e=>{var t;if(null!==eh)return;null==(t=eI.current)||t.abort();let n=new AbortController();eI.current=n,ef(e),ev(null);let l=eo.trim();w(e,0===l.length?null:l,n.signal).then(t=>{(null==M?void 0:M.runId)===e&&P(t),Y(n=>n.map(n=>n.runId===e?sL(n,t):n)),G(n=>n.map(n=>n.runId===e?sL(n,t):n)),es(null),ec("");}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||ev(sW(e));}).finally(()=>{eI.current===n&&(eI.current=null),ef(null);});},[eo,eh,null==M?void 0:M.runId,w]),tL=(0,i.useCallback)(e=>{eu(t=>t===e?null:e),es(null),em(null),ev(null);},[]),tz=(0,i.useCallback)(e=>{em(e),es(null),eu(null),ev(null);},[]),tO=(0,i.useCallback)(e=>{var t;if(null!==eh)return;null==(t=eI.current)||t.abort();let n=new AbortController();eI.current=n,ef(e),ev(null),j(e,n.signal).then(t=>{Y(t=>t.filter(t=>t.runId!==e)),G(t=>t.filter(t=>t.runId!==e)),em(null),es(null),eu(null),(null==M?void 0:M.runId)===e&&(P(null),q("idle"),eT("idle"),eq(null),ez("idle"),eK(null)),((null==M?void 0:M.runId)===e||m===e)&&v({snapshotRunId:void 0});}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||ev(sW(e));}).finally(()=>{eI.current===n&&(eI.current=null),ef(null);});},[j,eh,m,null==M?void 0:M.runId,v]),tK=void 0!==m&&m.length>0&&null===M&&("idle"===D||"loading"===D||"error"===D),tB=(e,t,n,l,i,r)=>t?(0,a.jsx)("p",{className:"figma-snapshot-dashboard-status",children:"Loading snapshots…"}):null!==n?(0,a.jsx)("p",{className:"figma-snapshot-dashboard-status figma-snapshot-dashboard-status-error",children:n}):0===e.length?(0,a.jsxs)("div",{className:"figma-snapshot-dashboard-empty",children:[(0,a.jsx)("p",{className:"figma-snapshot-dashboard-empty-title",children:l}),(0,a.jsx)("p",{className:"figma-snapshot-dashboard-empty-detail",children:i})]}):(0,a.jsx)("div",{className:"figma-snapshot-dashboard-list",role:"list",children:e.map(e=>{var t;let n=(null==M?void 0:M.runId)===e.runId,l=sD(e),i=sP(e),s=eh===e.runId,o=ed===e.runId,c=er===e.runId,d=ep===e.runId;return(0,a.jsxs)("article",{className:"figma-snapshot-dashboard-item",role:"listitem","aria-current":n?"true":void 0,"aria-busy":e9&&m===e.runId?"true":void 0,children:[(0,a.jsxs)("div",{className:"figma-snapshot-dashboard-item-head",children:[(0,a.jsxs)("div",{className:"figma-snapshot-dashboard-item-title-block",children:[(0,a.jsx)("h3",{className:"figma-snapshot-dashboard-item-title",title:l,children:l}),(0,a.jsx)("span",{className:"figma-snapshot-dashboard-item-date",children:(0,lD.Yq)(e.fetchedAt)})]}),n&&(0,a.jsx)("span",{className:"figma-snapshot-dashboard-item-badge",children:"Current"}),(0,a.jsxs)("div",{className:"figma-snapshot-dashboard-item-actions",children:[(0,a.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-load",onClick:()=>{tp(e.runId);},disabled:te,"aria-disabled":te?"true":void 0,"aria-label":`Load snapshot ${l}`,children:"Load"}),(0,a.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-icon-btn",onClick:()=>tq(e),disabled:s,"aria-label":`Rename snapshot ${l}`,title:"Rename",children:(0,a.jsx)(N.F.edit,{"aria-hidden":"true"})}),(0,a.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-icon-btn",onClick:()=>tL(e.runId),"aria-expanded":o,"aria-label":`${o?"Hide":"Show"} metadata for snapshot ${l}`,title:"Metadata",children:(0,a.jsx)(N.F.info,{"aria-hidden":"true"})}),(0,a.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-icon-btn figma-snapshot-dashboard-icon-btn-danger",onClick:()=>tz(e.runId),disabled:s,"aria-label":`Delete snapshot ${l}`,title:"Delete",children:(0,a.jsx)(N.F.trash,{"aria-hidden":"true"})})]})]}),(0,a.jsx)("p",{className:"figma-snapshot-dashboard-item-hint",children:e.reductionHint}),(0,a.jsxs)("p",{className:"figma-snapshot-dashboard-item-meta",children:[e.screenCount.toString()," screen",1!==e.screenCount?"s":"",e.skippedCount>0?`, ${e.skippedCount.toString()} skipped`:", no skipped renders"]}),r&&(0,a.jsxs)("p",{className:"figma-snapshot-dashboard-item-scope",children:[e.fileKey," \xb7 ",e.nodeId]}),c?(0,a.jsxs)("form",{className:"figma-snapshot-dashboard-rename",onSubmit:t=>{t.preventDefault(),tP(e.runId);},children:[(0,a.jsx)("input",{type:"text",className:"figma-snapshot-dashboard-rename-input",value:eo,onChange:e=>ec(e.target.value),maxLength:120,disabled:s,"aria-label":`Snapshot name for ${l}`,placeholder:"Snapshot name"}),(0,a.jsx)("button",{type:"submit",className:"figma-snapshot-dashboard-rename-save",disabled:s,"aria-busy":s,children:"Save"}),(0,a.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-rename-cancel",onClick:tM,disabled:s,children:"Cancel"})]}):null,d?(0,a.jsxs)("div",{className:"figma-snapshot-dashboard-delete-confirm",children:[(0,a.jsx)("span",{children:"Delete this snapshot?"}),(0,a.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-delete-confirm-btn",onClick:()=>tO(e.runId),disabled:s,"aria-busy":s,children:"Delete"}),(0,a.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-delete-cancel-btn",onClick:()=>em(null),disabled:s,children:"Cancel"})]}):null,o?(0,a.jsxs)("dl",{className:"figma-snapshot-dashboard-details",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Run"}),(0,a.jsx)("dd",{children:e.runId})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Version"}),(0,a.jsx)("dd",{children:sq(e.version)})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Integrity"}),(0,a.jsx)("dd",{title:e.integrityHash,children:sM(e.integrityHash)})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Structural"}),(0,a.jsx)("dd",{children:(null!=(t=e.structuralOnlyCount)?t:0).toString()})]}),void 0!==i.updatedAt?(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Name updated"}),(0,a.jsx)("dd",{children:(0,lD.Yq)(i.updatedAt)})]}):null]}):null]},e.runId);})});if(ta){let e=null!=f?f:h.join(", "),t=void 0!==tr&&(null!=(s=null==M?void 0:M.runId)?s:m)!==void 0&&"loading"!==eL;return(0,a.jsxs)("section",{className:"figma-snapshot-window figma-view-window","aria-label":`Figma view source ${e}`,children:[(0,a.jsxs)("div",{className:"figma-view-source-header",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("p",{className:"figma-view-source-eyebrow",children:"Figma view"}),(0,a.jsx)("h1",{className:"figma-view-source-heading",title:e,children:e})]}),(0,a.jsxs)("div",{className:"figma-view-source-actions",children:[(0,a.jsx)("span",{className:"figma-view-source-badge",children:"QI source"}),(0,a.jsx)("button",{type:"button",className:"figma-view-json-btn",onClick:ty,disabled:!t,"aria-disabled":t?void 0:"true","aria-busy":"loading"===eL?"true":void 0,children:"loading"===eL?"Loading JSON…":"Inspect JSON"})]})]}),(0,a.jsxs)("div",{id:E,role:"status","aria-live":"polite","aria-atomic":"true",className:"figma-snapshot-status",children:[e9&&(0,a.jsx)("p",{className:"figma-snapshot-progress",children:"Loading view preview…"}),"error"===D&&null!==L&&(0,a.jsx)("p",{className:"figma-snapshot-error",children:L.detail}),"done"===D&&null!==M&&(0,a.jsxs)("p",{className:"sr-only",children:["Figma view loaded — ",e,"."]})]}),null===M?(0,a.jsxs)("div",{className:"figma-view-source-empty",children:[(0,a.jsx)("p",{className:"figma-view-source-empty-title",children:e9?"Loading the selected view…":"Selected view preview not loaded."}),!e9&&(0,a.jsx)("button",{type:"button",className:"figma-snapshot-load-btn",onClick:tF,children:"Load view"})]}):ti.length>0?ti.map(e=>{let t="rendered"===e.kind?sN(M.runId,e.imageIndex):void 0,n=void 0===t?void 0:{snapshotRunId:M.runId,screenId:e.screen.screenId,name:e.screen.name,imageSrc:t,...(void 0!==p?{sourceWindowId:p}:{})};return(0,a.jsx)(sY,{name:e.screen.name,screenId:e.screen.screenId,irSummary:e.screen.irSummary,imageSrc:t,imageByteLength:"rendered"===e.kind?e.screen.imageByteLength:void 0,structuralReason:"structural"===e.kind?e.screen.reason:void 0,snapshotRunId:M.runId,capturedAt:(0,lD.Yq)(M.fetchedAt),imageDragPayload:n},e.screen.screenId);}):(0,a.jsx)("div",{className:"lk-empty",children:(0,a.jsx)("p",{className:"lk-empty-body",children:"The selected screen is not present in this stored snapshot."})}),"error"===eL&&null!==eB?(0,a.jsx)("p",{className:"figma-snapshot-error",role:"alert",children:eB}):null,"done"===eL&&null!==eO?(0,a.jsxs)("section",{className:"figma-view-json-inspector","aria-label":`Scoped JSON for ${eO.screen.name}`,children:[(0,a.jsxs)("div",{className:"figma-view-json-inspector-header",children:[(0,a.jsxs)("div",{className:"figma-view-json-drag-surface",role:"button",tabIndex:null!==tj?0:-1,draggable:!1,onDragStart:tk,onDragEnd:tN,onKeyDown:tS,onPointerDown:tC,onPointerMove:tI,onPointerUp:tR,onPointerCancel:tE,onMouseDown:t$,"aria-label":`Create a standalone JSON source for ${eO.screen.name}`,"aria-disabled":null===tj?"true":void 0,title:`Drag JSON for ${eO.screen.name} to the workspace`,children:[(0,a.jsx)("p",{className:"figma-view-json-kicker",children:"Stored Screen-IR JSON"}),(0,a.jsx)("h2",{className:"figma-view-json-title",children:eO.screen.screenId}),(0,a.jsxs)("p",{className:"figma-view-json-meta",children:[eO.screen.kind," \xb7 ",(0,lD.z3)(to)," \xb7"," ",eO.relatedLinks.length.toString()," related link",1!==eO.relatedLinks.length?"s":""]})]}),(0,a.jsx)("button",{type:"button",className:"figma-view-json-copy-btn",onClick:tw,children:"Copy JSON"})]}),null!==eU?(0,a.jsx)("p",{className:"figma-view-json-copy-status",role:"status",children:eU}):null,(0,a.jsx)(s$,{text:ts,className:"figma-view-json-code"})]}):null]});}return(0,a.jsxs)("section",{className:"figma-snapshot-window","aria-label":"Figma Snapshot",children:[(0,a.jsxs)("form",{className:"figma-snapshot-form",onSubmit:th,noValidate:!0,children:[(0,a.jsx)("label",{className:"figma-snapshot-label",htmlFor:R,children:"Board link"}),(0,a.jsxs)("div",{className:"figma-snapshot-input-row",children:[(0,a.jsx)("input",{id:R,type:"url",className:"figma-snapshot-input",placeholder:"https://www.figma.com/design/…?node-id=…",value:F,onChange:e=>{T(e.target.value),null!==L&&z(null),"error"===D&&q("idle"),null!==O&&K(null),ey&&ew(!1);},"aria-describedby":null!==e4?`${$} ${E}`:E,"aria-invalid":null!==e4?"true":void 0,readOnly:te,autoComplete:"off",spellCheck:!1}),(0,a.jsx)("button",{type:"submit",className:"figma-snapshot-trigger-btn",disabled:!e3&&!te,"aria-disabled":!e3||te?"true":void 0,"aria-busy":e7,children:e7?"Building…":"Snapshot"})]}),null!==e4&&(0,a.jsx)("p",{id:$,className:"figma-snapshot-link-error",role:"alert",children:e4}),(0,a.jsxs)("label",{className:"figma-snapshot-consent",children:[(0,a.jsx)("input",{type:"checkbox",className:"figma-snapshot-consent-checkbox",ref:ej,checked:eb,"aria-invalid":ey?"true":void 0,onChange:e=>{ex(e.target.checked),null!==L&&z(null),"error"===D&&q("idle"),ew(!1);},disabled:e7}),(0,a.jsxs)("span",{children:["I acknowledge the configured Figma PAT is read-only and least-privilege (",(0,a.jsx)("code",{children:"file_content:read"}),")."," ",(0,a.jsx)("span",{className:"figma-snapshot-consent-required",children:"Required before the first snapshot of a board."})]})]}),(0,a.jsx)("p",{className:"figma-snapshot-hint",children:"Paste a Figma board link with a node-id param (section or frame anchor). The access token is resolved server-side — it never reaches this page."})]}),"error"===D&&null!==L&&!0===L.assertive&&(0,a.jsxs)("div",{className:"figma-snapshot-error-card",role:"alert","aria-labelledby":`${E}-error-title`,children:[(0,a.jsx)("p",{id:`${E}-error-title`,className:"figma-snapshot-error-title",children:L.title}),(0,a.jsx)("p",{className:"figma-snapshot-error-detail",children:L.detail}),void 0!==L.status&&(0,a.jsx)("p",{className:"figma-snapshot-error-status",children:L.status}),void 0!==L.remediation&&(0,a.jsx)("p",{className:"figma-snapshot-error-remediation",children:L.remediation})]}),(0,a.jsxs)("div",{id:E,role:"status","aria-live":"polite","aria-atomic":"true",className:"figma-snapshot-status",children:[e7&&(0,a.jsxs)("p",{className:"figma-snapshot-progress",children:["Building snapshot — fetching screens from Figma…"," ",null!==tt?`${tt} elapsed.`:""," Large boards can take several minutes."]}),e9&&(0,a.jsx)("p",{className:"figma-snapshot-progress",children:"Loading stored snapshot…"}),"done"===D&&null!==M&&(0,a.jsxs)("p",{className:"sr-only",children:["Snapshot complete — ",M.reductionHint,"."]}),"done"===eF&&null!==eD&&(0,a.jsxs)("p",{className:"sr-only",children:["Code generated — ",String(eD.fileCount)," file",1!==eD.fileCount?"s":""," ready for review."]}),"idle"===D&&(0,a.jsx)("p",{className:"sr-only","aria-live":"polite"}),"error"===D&&null!==L&&!0!==L.assertive&&(0,a.jsx)("p",{className:"figma-snapshot-error",children:L.detail})]}),e7&&(0,a.jsxs)("div",{className:"figma-snapshot-cancel-row",children:[(0,a.jsx)("button",{type:"button",className:"figma-snapshot-cancel-btn",onClick:tg,children:"Cancel"}),(0,a.jsx)("p",{className:"figma-snapshot-cancel-note",role:"status","aria-live":"polite",children:"Cancelling stops this window from waiting — the server-side build continues on demand."})]}),null!==O&&!te&&(0,a.jsxs)("div",{className:"figma-snapshot-stored-notice",children:[(0,a.jsx)("p",{className:"figma-snapshot-stored-text",children:"This window is no longer waiting. The server may still be building the snapshot in the background. You can close this window safely."}),(0,a.jsx)("button",{type:"button",className:"figma-snapshot-load-btn",onClick:tv,children:"Reconnect build"})]}),"idle"===D&&null===M&&null===O&&!tK&&(0,a.jsxs)("div",{className:"figma-snapshot-empty",children:[(0,a.jsx)("p",{className:"figma-snapshot-empty-title",children:"Capture screens from a Figma board"}),(0,a.jsxs)("ol",{className:"figma-snapshot-empty-steps",children:[(0,a.jsx)("li",{children:"In Figma, select the frame or section you want to capture."}),(0,a.jsx)("li",{children:"Copy its link (Copy link to selection) — it contains the node-id."}),(0,a.jsx)("li",{children:"Paste it above, acknowledge the read-only scope, then take the snapshot."})]}),(0,a.jsx)("p",{className:"figma-snapshot-empty-note",children:"The snapshot stores the captured screens and their structure as immutable evidence — connect this window to Quality Intelligence to ground generated tests in the design. Requires a Figma access token configured on the server."})]}),tK&&(0,a.jsxs)("div",{className:"figma-snapshot-stored-notice",children:[(0,a.jsx)("p",{className:"figma-snapshot-stored-text",children:"A stored snapshot is available."}),(0,a.jsx)("button",{type:"button",className:"figma-snapshot-load-btn",onClick:tF,"aria-disabled":e9?"true":void 0,"aria-busy":e9,children:e9?"Loading…":"Load snapshot"})]}),(0,a.jsxs)("section",{className:"figma-snapshot-dashboard","aria-label":"Snapshot dashboard",children:[(0,a.jsxs)("div",{className:"figma-snapshot-dashboard-header",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("p",{className:"figma-snapshot-dashboard-eyebrow",children:"Snapshot dashboard"}),(0,a.jsx)("h2",{className:"figma-snapshot-dashboard-title",children:"Stored snapshots"})]}),(0,a.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-refresh",onClick:tu,children:"Refresh"})]}),(0,a.jsxs)("div",{className:"figma-snapshot-dashboard-tabs",role:"tablist","aria-label":"Snapshot views",children:[(0,a.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-tab",role:"tab","aria-selected":"board"===V,"aria-controls":`${A}-board-panel`,id:`${A}-board-tab`,onClick:()=>{null!==e6&&H("board");},disabled:null===e6,children:"This board"}),(0,a.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-tab",role:"tab","aria-selected":"recent"===V,"aria-controls":`${A}-recent-panel`,id:`${A}-recent-tab`,onClick:()=>{H("recent");},children:"Recent"})]}),null!==eg?(0,a.jsx)("p",{className:"figma-snapshot-dashboard-status figma-snapshot-dashboard-status-error",role:"alert",children:eg}):null,"board"===V?(0,a.jsx)("div",{id:`${A}-board-panel`,className:"figma-snapshot-dashboard-panel",role:"tabpanel","aria-labelledby":`${A}-board-tab`,children:null===e6?tB([],!1,null,"No board selected yet","Paste a valid Figma board link or load a stored snapshot to see this board's history.",!1):tB(J,Q,en,"No snapshots stored for this board","Take the first snapshot for this board to make it available here.",!1)}):(0,a.jsx)("div",{id:`${A}-recent-panel`,className:"figma-snapshot-dashboard-panel",role:"tabpanel","aria-labelledby":`${A}-recent-tab`,children:tB(X,ee,ea,"No snapshots stored yet","Stored Figma snapshots will appear here once the first board capture completes.",!0)})]}),null!==M&&(0,a.jsxs)("div",{className:"figma-snapshot-result",children:[(0,a.jsxs)("div",{className:"figma-snapshot-reduction",children:[(0,a.jsxs)("div",{className:"figma-snapshot-result-head",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("h2",{className:"figma-snapshot-result-title",title:sD(M),children:sD(M)}),(0,a.jsx)("p",{className:"figma-snapshot-result-run",children:M.runId})]}),(0,a.jsx)("span",{className:"figma-snapshot-result-hash",title:M.integrityHash,children:sM(M.integrityHash)})]}),(0,a.jsx)("p",{className:"figma-snapshot-reduction-hint",children:M.reductionHint}),(0,a.jsxs)("p",{className:"figma-snapshot-captured-at",children:["Captured ",(0,lD.Yq)(M.fetchedAt)]}),(0,a.jsxs)("dl",{className:"figma-snapshot-result-metadata",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"File"}),(0,a.jsx)("dd",{children:M.fileKey})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Node"}),(0,a.jsx)("dd",{children:M.nodeId})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Version"}),(0,a.jsx)("dd",{children:sq(M.version)})]}),void 0!==td.updatedAt?(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Name updated"}),(0,a.jsx)("dd",{children:(0,lD.Yq)(td.updatedAt)})]}):null]}),tl&&(0,a.jsxs)("p",{className:"figma-snapshot-scope-note",children:["QI source scope: ",null!=f?f:h.join(", ")]}),M.skippedCount>0&&(0,a.jsxs)("p",{className:"figma-snapshot-skipped-notice",children:[String(M.skippedCount)," screen",1!==M.skippedCount?"s":""," could not be rendered and were skipped."]})]}),(0,a.jsx)("button",{type:"button",className:"figma-snapshot-resnapshot-btn",onClick:tf,"aria-disabled":te?"true":void 0,"aria-busy":e7,"aria-label":"Re-snapshot this board",children:e7?"Building…":"Re-snapshot"}),(0,a.jsxs)("div",{className:"figma-snapshot-codegen",children:[(0,a.jsxs)("div",{className:"figma-snapshot-codegen-actions",children:[(0,a.jsx)("button",{type:"button",className:"figma-snapshot-codegen-btn",onClick:tx,"aria-disabled":"generating"===eF?"true":void 0,"aria-busy":"generating"===eF,children:"generating"===eF?"Generating code…":"Generate code"}),"generating"===eF&&(0,a.jsx)("button",{type:"button",className:"figma-snapshot-codegen-cancel-btn",onClick:tA,children:"Cancel"})]}),"error"===eF&&null!==eM&&(0,a.jsx)("p",{className:"figma-snapshot-error",role:"alert",children:eM}),"done"===eF&&null!==eD&&(0,a.jsxs)("div",{className:"figma-snapshot-code-result",children:[(0,a.jsxs)("p",{className:"figma-snapshot-code-summary",children:[String(eD.fileCount)," reviewable file",1!==eD.fileCount?"s":""," (",String(eD.screenCount)," screen",1!==eD.screenCount?"s":"",","," ",eD.adapterName,") — proposal only, never auto-applied."]}),eD.files.map(e=>(0,a.jsxs)("details",{className:"figma-snapshot-code-file",children:[(0,a.jsx)("summary",{className:"figma-snapshot-code-file-path",children:e.path}),(0,a.jsx)("pre",{className:"figma-snapshot-code-file-contents",children:(0,a.jsx)("code",{children:e.contents})})]},e.path))]})]}),(0,a.jsxs)("details",{className:"figma-snapshot-scopes",children:[(0,a.jsx)("summary",{className:"figma-snapshot-scopes-summary",children:"Required Figma PAT scopes"}),(0,a.jsx)("ul",{className:"figma-snapshot-scopes-list",children:(0,a.jsxs)("li",{children:[(0,a.jsx)("code",{children:"file_content:read"})," — read design file structure, node metadata, and rendered images"]})}),(0,a.jsxs)("p",{className:"figma-snapshot-scopes-note",children:["The token is read server-side from the vault, Keiko config, or"," ",(0,a.jsx)("code",{children:"FIGMA_ACCESS_TOKEN"})," environment variable. This window never holds or transmits the token."]}),(0,a.jsxs)("div",{className:"figma-snapshot-revoke-row",children:[eV?(0,a.jsxs)("span",{className:"figma-snapshot-revoke-confirm",children:[(0,a.jsx)("span",{className:"figma-snapshot-revoke-confirm-label",children:"Really revoke the stored token?"}),(0,a.jsx)("button",{ref:eQ,type:"button",className:"figma-snapshot-revoke-confirm-btn",onClick:tT,children:"Yes, revoke"}),(0,a.jsx)("button",{type:"button",className:"figma-snapshot-revoke-cancel-btn",onClick:tD,children:"Cancel"})]}):(0,a.jsx)("button",{ref:eZ,type:"button",className:"figma-snapshot-revoke-btn",onClick:()=>{eH(!0),eY(null),eG(null);},children:"Revoke stored token"}),(0,a.jsx)("p",{className:"figma-snapshot-revoke-status",role:"status","aria-live":"polite","aria-atomic":"true",children:null!=(l=null!=eJ?eJ:eX)?l:""})]})]}),ti.length>0?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("section",{className:"figma-snapshot-gallery","aria-label":tl?`${String(ti.length)} selected screen${1!==ti.length?"s":""}`:`${String(tc)} captured and structural screen${1!==tc?"s":""}`,children:ti.slice(0,e0).map((e,t)=>{let n=void 0===g?void 0:()=>g({snapshotRunId:M.runId,screenId:e.screen.screenId,name:e.screen.name}),l={snapshotRunId:M.runId,screenId:e.screen.screenId,name:e.screen.name};return"rendered"===e.kind?(0,a.jsx)(sJ,{index:t,screenId:e.screen.screenId,name:e.screen.name,irSummary:e.screen.irSummary,imageSrc:sN(M.runId,e.imageIndex),imageByteLength:e.screen.imageByteLength,onAddSource:n,isSourceSelected:tn.has(e.screen.screenId),dragPayload:l},e.screen.screenId):(0,a.jsx)(sJ,{index:t,screenId:e.screen.screenId,name:e.screen.name,irSummary:e.screen.irSummary,structuralReason:e.screen.reason,onAddSource:n,isSourceSelected:tn.has(e.screen.screenId),dragPayload:l},e.screen.screenId);})}),e0<ti.length?(0,a.jsx)("button",{type:"button",className:"figma-snapshot-gallery-more",onClick:()=>e1(e=>Math.min(e+24,ti.length)),children:"Show more screens"}):null]}):(0,a.jsx)("div",{className:"lk-empty",children:(0,a.jsx)("p",{className:"lk-empty-body",children:tl?"The selected screen is not present in this stored snapshot.":"No screens were captured from this board section."})})]})]});}function sG(e){var t;let n,{snapshotRunId:l,screenId:r,screenName:s,loadScreenJsonImpl:o=sS}=e,c=(0,i.useRef)(null),[d,u]=(0,i.useState)("idle"),[p,m]=(0,i.useState)(null),[h,f]=(0,i.useState)(null),[g,v]=(0,i.useState)(null),b=void 0!==(n=null==s?void 0:s.trim())&&n.length>0?n:null!=(t=null==r?void 0:r.trim())?t:"Selected Figma view",x=(0,i.useMemo)(()=>null===p?"":JSON.stringify(p,null,2),[p]),y=(0,i.useMemo)(()=>sE(x),[x]),w=(0,i.useCallback)(()=>{var e;if(void 0===l||0===l.trim().length||void 0===r||0===r.trim().length){m(null),u("error"),f("Missing Figma JSON source reference.");return;}null==(e=c.current)||e.abort();let t=new AbortController();c.current=t,u("loading"),f(null),v(null),o(l,r,t.signal).then(e=>{m(e),u("done");}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||(m(null),f(e instanceof Error?e.message:"Failed to load Figma JSON."),u("error"));}).finally(()=>{c.current===t&&(c.current=null);});},[o,r,l]);(0,i.useEffect)(()=>(w(),()=>{var e;null==(e=c.current)||e.abort(),c.current=null;}),[w]);let j=(0,i.useCallback)(()=>{if(0!==x.length){if(void 0===navigator.clipboard)return void v("Clipboard unavailable");navigator.clipboard.writeText(x).then(()=>v("Copied")).catch(()=>v("Copy failed"));}},[x]);return(0,a.jsxs)("section",{className:"figma-json-window","aria-label":`Figma JSON source ${b}`,children:[(0,a.jsxs)("header",{className:"figma-json-header",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("p",{className:"figma-json-eyebrow",children:"Figma JSON"}),(0,a.jsx)("h1",{className:"figma-json-heading",title:b,children:b}),(0,a.jsx)("p",{className:"figma-json-meta",children:null!==p?`${p.screen.kind} \xb7 ${(0,lD.z3)(y)} \xb7 captured ${(0,lD.Yq)(p.fetchedAt)}`:r})]}),(0,a.jsxs)("div",{className:"figma-json-actions",children:[(0,a.jsx)("span",{className:"figma-view-source-badge",children:"QI source"}),(0,a.jsx)("button",{type:"button",className:"figma-view-json-copy-btn",onClick:j,disabled:0===x.length,"aria-disabled":0===x.length?"true":void 0,children:"Copy JSON"})]})]}),"loading"===d?(0,a.jsx)("p",{className:"figma-json-status",role:"status",children:"Loading JSON…"}):null,"error"===d&&null!==h?(0,a.jsxs)("div",{className:"figma-json-error",role:"alert",children:[(0,a.jsx)("p",{children:h}),(0,a.jsx)("button",{type:"button",className:"figma-snapshot-load-btn",onClick:w,children:"Retry"})]}):null,null!==g?(0,a.jsx)("p",{className:"figma-view-json-copy-status",role:"status",children:g}):null,"done"===d&&x.length>0?(0,a.jsx)(s$,{text:x,className:"figma-json-code"}):null]});}function sQ(e){let t,{imageSrc:n,screenName:l}=e,i=void 0!==(t=null==l?void 0:l.trim())&&t.length>0?t:"Figma image source";return void 0===n||0===n.trim().length?(0,a.jsx)("section",{className:"figma-image-window","aria-label":i,children:(0,a.jsx)("div",{className:"figma-image-missing",role:"alert",children:"Image preview is unavailable."})}):(0,a.jsx)("section",{className:"figma-image-window","aria-label":i,children:(0,a.jsx)(lS.default,{className:"figma-image-preview",src:n,alt:i,width:720,height:480,unoptimized:!0,priority:!0})});}async function sZ(e,t){var n,l;let a=(null!=(n=null==t?void 0:t.method)?n:"GET").toUpperCase(),i="GET"!==a&&"HEAD"!==a,r=await fetch(e,{...t,headers:{Accept:"application/json",...(i?{"Content-Type":"application/json"}:{}),...(i?{"X-Keiko-CSRF":"1"}:{}),...(null!=(l=null==t?void 0:t.headers)?l:{})}});if(!r.ok){let e="INTERNAL",t=`HTTP ${r.status.toString()}`;try{let n=await r.json();e=n.error.code,t=n.error.message;}catch{}throw new k.hD(e,t,r.status);}return r.json();}async function s0(){return sZ("/api/quality-intelligence/runs");}async function s1(e){return sZ(`/api/quality-intelligence/runs/${encodeURIComponent(e)}`);}async function s2(e){let t="QI_RUN_FAILED",n=`HTTP ${e.status.toString()}`;try{var l,a,i,r;let s=await e.json();t=null!=(l=null==(i=s.error)?void 0:i.code)?l:t,n=null!=(a=null==(r=s.error)?void 0:r.message)?a:n;}catch{}return new k.hD(t,n,e.status);}async function s3(e,t,n){var l,a;let i=await fetch("/api/quality-intelligence/runs",{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json","X-Keiko-CSRF":"1"},body:JSON.stringify(e),signal:t}),r=null!=(l=i.headers.get("content-type"))?l:"";if(!i.ok||!r.includes("text/event-stream"))throw await s2(i);let s=i.body;if(null===s)throw new k.hD("QI_NO_STREAM","The server did not return a progress stream.",i.status);let o=s.getReader(),c=new TextDecoder(),d="";try{for(;!t.aborted;){let e=await o.read();if(e.done)break;let t=(d+=c.decode(e.value,{stream:!0})).split("\n");for(let e of(d=null!=(a=t.pop())?a:"",t)){let t=e.trim();if(t.startsWith("data:"))try{n(JSON.parse(t.slice(5).trim()));}catch{}}}}finally{await o.cancel().catch(()=>{}),o.releaseLock();}}async function s4(e){return sZ(`/api/quality-intelligence/runs/${encodeURIComponent(e)}`,{method:"DELETE"});}async function s6(e,t,n,l){return sZ(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/review`,{method:"POST",body:JSON.stringify({action:t,...(void 0!==n?{candidateId:n}:{}),...(void 0!==l?{reviewerLabel:l}:{})})});}async function s5(e,t,n,l){return(await sZ(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/edit`,{method:"POST",body:JSON.stringify({candidateId:t,edited:n,...(void 0!==l?{editorLabel:l}:{})})})).candidate;}async function s8(e,t){return sZ(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/re-check`,{method:"POST",body:JSON.stringify({sources:t})});}async function s7(e,t){return sZ(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/regenerate-stale`,{method:"POST",body:JSON.stringify({sources:t})});}async function s9(e,t,n){var l,a;return sZ(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/export`,{method:"POST",body:JSON.stringify({adapter:t,dryRun:null!=(l=null==n?void 0:n.dryRun)&&l,approvedOnly:null!=(a=null==n?void 0:n.approvedOnly)&&a})});}async function oe(e,t){return sZ(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/traceability`,{method:"POST",body:JSON.stringify({format:t})});}var ot=n(76308);let on={open:"Open",approved:"Approved","changes-requested":"Changes requested",rejected:"Rejected",withdrawn:"Withdrawn"},ol={open:"qi-review-open",approved:"qi-review-approved","changes-requested":"qi-review-changes",rejected:"qi-review-rejected",withdrawn:"qi-review-withdrawn"};function oa(e){let{state:t}=e;return(0,a.jsxs)("span",{className:`qi-review-badge ${ol[t]}`,children:[(0,a.jsx)("span",{className:"sr-only",children:"Review: "}),on[t]]});}function oi(e){if(e instanceof k.hD){var t,n;return t=e.code,n=e.message,`${n} (${t})`;}return e instanceof Error?e.message:"An unexpected error occurred.";}function or(e){try{return new Date(e).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"});}catch{return e;}}let os={running:"Running",succeeded:"Succeeded",failed:"Failed",cancelled:"Cancelled"},oo={running:"qi-badge-running",succeeded:"qi-badge-succeeded",failed:"qi-badge-failed",cancelled:"qi-badge-cancelled"};function oc(e){return"running"===e||"succeeded"===e||"failed"===e||"cancelled"===e;}function od(e){let{status:t}=e,n=oc(t)?os[t]:t,l=oc(t)?oo[t]:"qi-badge-default";return(0,a.jsx)("span",{className:`qi-badge ${l}`,children:n});}let ou={critical:"qi-sev-critical",high:"qi-sev-high",medium:"qi-sev-medium",low:"qi-sev-low"};function op(e){let{severity:t}=e,n="critical"===t||"high"===t||"medium"===t||"low"===t?ou[t]:"qi-sev-low";return(0,a.jsxs)("span",{className:`qi-sev ${n}`,children:[(0,a.jsx)("span",{className:"sr-only",children:"Severity: "}),t]});}function om(e){let{score:t}=e;if(null===t)return(0,a.jsxs)("span",{className:"qi-badge qi-badge-default","data-testid":"qi-quality-badge",children:[(0,a.jsx)("span",{"aria-hidden":"true",children:"—"}),(0,a.jsx)("span",{className:"sr-only",children:"Quality score not available"})]});let n=Math.round(t);return(0,a.jsxs)("span",{className:`qi-badge ${n>=90?"qi-quality-high":n>=70?"qi-quality-mid":"qi-quality-low"}`,"data-testid":"qi-quality-badge",children:[n.toString(),(0,a.jsx)("span",{className:"sr-only",children:" out of 100"})]});}function oh(e){let{flag:t}=e;return(0,a.jsxs)("div",{role:"note","aria-label":`Weak test flagged by the quality judge: ${t.rationale}`,className:"qi-weak-flag","data-testid":"qi-weak-flag",children:[(0,a.jsxs)("span",{className:"qi-weak-flag-badge",children:[(0,a.jsx)("span",{"aria-hidden":"true",className:"qi-weak-flag-icon",children:"⚠"}),"Weak test"]}),(0,a.jsx)("p",{className:"qi-weak-flag-reason",children:t.rationale})]});}let of={verifiability:"Verifiability",atomicity:"Atomicity",determinism:"Determinism","ac-fidelity":"AC fidelity"};function og(e){let{verdict:t}=e,n=Math.round(t.score),l="strong"===t.verdict?"Strong":"Weak";return(0,a.jsxs)("div",{role:"note","aria-label":`Quality judge verdict: ${l}, ${n.toString()} out of 100. ${t.overallRationale}`,className:"qi-cand-block","data-testid":"qi-quality-verdict",children:[(0,a.jsx)("p",{className:"qi-cand-block-label",children:"Quality verdict"}),(0,a.jsxs)("p",{children:[l," - ",n.toString(),"/100"]}),(0,a.jsx)("ul",{className:"qi-cand-list","aria-label":"Quality dimensions",children:t.dimensions.map(e=>{var t;return(0,a.jsxs)("li",{children:[null!=(t=of[e.name])?t:e.name," ",Math.round(e.score).toString(),": ",e.rationale]},e.name);})})]});}function ov(e){let{height:t=20,width:n="100%"}=e;return(0,a.jsx)("div",{"aria-hidden":"true",className:"qi-skeleton",style:{height:t,width:n}});}function ob(){return(0,a.jsx)("div",{"data-testid":"qi-loading-state","aria-busy":"true",style:{display:"flex",flexDirection:"column",gap:8,padding:"12px 0"},children:[1,2,3].map(e=>(0,a.jsxs)("div",{className:"qi-skeleton-row",children:[(0,a.jsx)(ov,{height:14,width:"60%"}),(0,a.jsx)(ov,{height:12,width:"40%"})]},e))});}function ox(e){let{message:t,onRetry:n}=e;return(0,a.jsxs)("div",{role:"alert","aria-live":"assertive",className:"lk-alert","data-testid":"qi-error-state",children:[t,(0,a.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:n,children:"Retry"})]});}let oy="connectedSourcesJson";function ow(e,t){let n=e[t];return"string"==typeof n?n:void 0;}function oj(e,t){return"string"==typeof e[t];}function ok(e){if(!("object"==typeof e&&null!==e&&!Array.isArray(e))||!oj(e,"label"))return!1;switch(e.kind){case"file":case"workspace":return oj(e,"path");case"capsule":return oj(e,"capsuleId");case"capsule-set":return oj(e,"capsuleSetId");case"figma-snapshot":let t;return oj(e,"snapshotRunId")&&(void 0===(t=e.screenIds)||Array.isArray(t)&&t.length>0&&t.every(e=>"string"==typeof e&&e.trim().length>0));case"image":return"figma-snapshot-screen"===e.sourceKind&&oj(e,"snapshotRunId")&&oj(e,"screenId");default:return!1;}}function oN(e){return e.length>0?{[oy]:JSON.stringify(e)}:{};}function oS(e){var t;let n=e.split(/[\\/]/u).filter(e=>e.length>0);return n.length>0&&null!=(t=n[n.length-1])?t:e;}function oC(e){return e.replaceAll("\\","/");}function oI(e){if(/^[A-Za-z]:[/\\]?$/u.test(e))return e.replaceAll("\\","/");if(/^\/\/[^/]+\/[^/]+$/u.test(oC(e)))return oC(e);let t=oC(e).replace(/\/+$/u,"");return 0===t.length&&e.length>0?"/":t;}function oR(e){var t,n,l,a,i,r;let s=null!=(t=e.connectedRoot)?t:null,o=function(e,t){var n,l;let a=null!=(n=null==t?void 0:t.trim())?n:"";if(0===a.length)return null;if(a.startsWith("/")||/^[A-Za-z]:[/\\]/u.test(a)||a.startsWith("\\\\")||a.startsWith("//"))return a;let i=null!=(l=null==e?void 0:e.trim())?l:"";if(0===i.length)return null;let r=oI(i),s=oC(a).replace(/^\/+/u,""),o=r.endsWith("/")?"":"/";return`${r}${o}${s}`;}(s,null!=(n=e.connectedFilePath)?n:null),c=null!==s?oI(s):null,d=(void 0!==e.connectedRoots&&null!==e.connectedRoots&&e.connectedRoots.length>0?e.connectedRoots:null!==s?[s]:[]).map(oI),u=null!==o?d.filter(e=>e!==c):d,p=[];for(let e of(null!==o&&p.push({kind:"file",label:oS(o),path:o}),u))p.push({kind:"workspace",label:oS(e),path:e});for(let t of null!=(l=e.connectedCapsuleIds)?l:[])p.push({kind:"capsule",label:t,capsuleId:t});for(let t of null!=(a=e.connectedCapsuleSetIds)?a:[])p.push({kind:"capsule-set",label:t,capsuleSetId:t});for(let t of void 0!==e.connectedFigmaSnapshotSources?e.connectedFigmaSnapshotSources:(null!=(i=e.connectedFigmaSnapshotRunIds)?i:[]).map(e=>({kind:"figma-snapshot",label:e,snapshotRunId:e})))p.push(t);for(let t of null!=(r=e.connectedImageSources)?r:[])p.push(t);let m=new Set(),h=[];for(let e of p){if(h.length>=16)break;let t=function(e){switch(e.kind){case"file":case"workspace":return`${e.kind}:${e.path}`;case"capsule":return`capsule:${e.capsuleId}`;case"capsule-set":return`capsule-set:${e.capsuleSetId}`;case"figma-snapshot":{let t=e.screenIds,n=void 0===t||0===t.length?"*":[...new Set(t.map(e=>e.trim()).filter(e=>e.length>0))].sort().join(",");return`figma-snapshot:${e.snapshotRunId}:${n}`;}case"image":return`image:${e.sourceKind}:${e.snapshotRunId}:${e.screenId}`;}}(e);m.has(t)||(m.add(t),h.push(e));}return h;}let oE=[{id:"regression-default",label:"Regression (default)"},{id:"banking-default",label:"Banking"},{id:"insurance-default",label:"Insurance"}],o$=[{id:"requirements",label:"Requirements",hint:"Paste text"},{id:"workspace",label:"Folder",hint:"Browse local"},{id:"file",label:"File",hint:"Browse local"},{id:"capsule",label:"Capsule",hint:"Local Knowledge"},{id:"capsule-set",label:"Capsule set",hint:"Local Knowledge"}];function oA(e){let{kind:t}=e;return"requirements"===t?(0,a.jsx)(N.F.review,{size:15}):"workspace"===t?(0,a.jsx)(N.F.folder,{size:15}):"file"===t?(0,a.jsx)(N.F.file,{size:15}):"capsule-set"===t?(0,a.jsx)(N.F.layers,{size:15}):(0,a.jsx)("svg",{"aria-hidden":"true",className:"qi-source-kind-icon-svg",viewBox:"0 0 24 24",children:(0,a.jsx)("path",{d:"M12 3.8 19 7.7v8.6L12 20.2 5 16.3V7.7z"})});}let oF={phase:"Starting…",stageName:null,candidates:0,findings:0,atomCount:null,droppedSourceCount:0,skippedSources:[]},oT="Der Lauf wurde nicht erfolgreich abgeschlossen. Passe die Quelle an und versuche es erneut.";function oD(e){switch(e.code){case"QI_IMAGE_DESCRIPTION_UNAVAILABLE":return`${e.label} (image was readable, but the image model produced no usable description)`;case"QI_IMAGE_UNAVAILABLE":return`${e.label} (stored image could not be found or read)`;case"QI_FIGMA_SNAPSHOT_UNAVAILABLE":return`${e.label} (stored Figma snapshot could not be found or read)`;case"QI_SOURCE_EMPTY":return`${e.label} (source produced no usable evidence)`;case"QI_SOURCE_DENIED":return`${e.label} (source is in a protected location)`;case"QI_SOURCE_TOO_LARGE":return`${e.label} (source is too large for this run)`;case"QI_SOURCE_UNSUPPORTED":return`${e.label} (source format is not supported)`;case"QI_WORKSPACE_NOT_FOUND":return`${e.label} (workspace path could not be read)`;case"QI_CAPSULE_UNAVAILABLE":return`${e.label} (knowledge source is unavailable)`;default:return`${e.label} (could not be read)`;}}function oq(e){switch(e.kind){case"file":return"File";case"workspace":return"Folder";case"capsule":return"Capsule";case"capsule-set":return"Capsule set";case"figma-snapshot":return e.label.startsWith("JSON \xb7")?"Figma JSON":"Figma snapshot";case"image":return"Image";}}function oM(e){switch(e.kind){case"file":case"workspace":return e.path;case"capsule":return e.capsuleId;case"capsule-set":return e.capsuleSetId;case"figma-snapshot":return void 0!==e.screenIds&&e.screenIds.length>0?`${e.snapshotRunId}#${e.screenIds.join(",")}`:e.snapshotRunId;case"image":return`${e.snapshotRunId}#${e.screenId}`;}}function oP(e){let{onRunCompleted:t,startImpl:n=s3,fetchCapsulesImpl:l=aF.xr,fetchCapsuleSetsImpl:r=aF.R3,fetchProjectsImpl:s=k.vj,fetchFilesTreeImpl:o=k.KD,connectedRoot:c=null,connectedFilePath:d=null,connectedRoots:u,connectedCapsuleIds:p,connectedCapsuleSetIds:m,connectedFigmaSnapshotRunIds:h,connectedFigmaSnapshotSources:f,connectedImageSources:g}=e,[v,b]=(0,i.useState)(""),[x,y]=(0,i.useState)("requirements"),[w,j]=(0,i.useState)(""),[N,S]=(0,i.useState)(""),[C,I]=(0,i.useState)(""),[R,E]=(0,i.useState)(""),[$,A]=(0,i.useState)(!1),[F,T]=(0,i.useState)([]),[D,q]=(0,i.useState)([]),[M,P]=(0,i.useState)(!1),[L,z]=(0,i.useState)(null),[O,K]=(0,i.useState)("regression-default"),[B,W]=(0,i.useState)(""),[U,_]=(0,i.useState)(!1),[V,H]=(0,i.useState)(oF),[J,Y]=(0,i.useState)(null),[X,G]=(0,i.useState)(null),Q=(0,i.useRef)(null),Z=(0,i.useRef)(null),ee=(0,i.useRef)(null),et=(0,i.useRef)(!1),en=oR({connectedRoot:c,connectedFilePath:d,connectedRoots:u,connectedCapsuleIds:p,connectedCapsuleSetIds:m,connectedFigmaSnapshotRunIds:h,connectedFigmaSnapshotSources:f,connectedImageSources:g}),el=en.length>0,ea=F.find(e=>e.id===C),ei=D.find(e=>e.id===R),er=N.trim().length>0,es="requirements"===x?w.trim().length>0:"workspace"===x||"file"===x?er:"capsule"===x?C.trim().length>0:R.trim().length>0,eo="requirements"===x?0===w.trim().length:("workspace"===x||"file"===x)&&!er,ec=es||eo&&el,ed=B.trim(),eu=0===ed.length?void 0:/^\d+$/u.test(ed)?Number(ed):NaN,ep=void 0===eu||Number.isSafeInteger(eu)&&Number.isFinite(eu),em=e=>{let t=Number.parseInt(B.trim(),10);W(String(Math.max(0,(Number.isFinite(t)?t:0)+e))),Y(null);},eh=!ec||!ep,ef=(0,i.useId)(),eg=(0,i.useId)(),ev=(0,i.useId)(),eb=(0,i.useId)(),ex=(0,i.useId)(),ey=ec?ep?void 0:eg:ef,ew="workspace"===x||"file"===x?x:null,ej=(0,i.useCallback)(e=>{y(e),A(!1),Y(null),z(null);},[]),ek=(0,i.useCallback)((e,t)=>{U||0!==e.button||ej(t);},[ej,U]),eN=(0,i.useCallback)(e=>{var t,n;if(U)return;let l="ArrowRight"===e.key||"ArrowDown"===e.key?1:"ArrowLeft"===e.key||"ArrowUp"===e.key?-1:0;if(0===l)return;e.preventDefault();let a=o$.length,i=(Math.max(0,o$.findIndex(e=>e.id===x))+l+a)%a,r=o$[i];void 0!==r&&(ej(r.id),null==(n=e.currentTarget.parentElement)||null==(t=n.querySelectorAll('[role="radio"]')[i])||t.focus());},[ej,U,x]),eS=(0,i.useCallback)(e=>{var t,n,l,a,i;"event"===e.type&&("stage:failed"===e.kind||"run:failed"===e.kind)&&"string"==typeof e.reasonSummary&&(ee.current=e.reasonSummary),"done"===e.type&&("succeeded"===e.status?(Z.current=e.runId,!0===e.degraded&&G(function(e){let t="Die Modellgenerierung ist fehlgeschlagen — Keiko hat deterministische Baseline-Testf\xe4lle aus der Evidenz erstellt. Diese sind nicht modellgest\xfctzt; pr\xfcfe das Modell-Gateway und starte den Lauf f\xfcr modellgest\xfctzte Testf\xe4lle erneut.";if(null==e||0===e.trim().length)return t;if("qi-error: UnparseableModelOutputError"===e)return`${t} (Modellausgabe nicht als JSON parsebar)`;if("qi-error: QI_PROMPT_TOO_LARGE"===e)return`${t} (Quellkontext f\xfcr das Modell zu gro\xdf)`;let n=e.startsWith("qi-error: ")?e.slice(10):e.startsWith("qi-safe-error: ")?e.slice(15):e;return`${t} (${n})`;}(null!=(t=e.reasonSummary)?t:null))):"failed"===e.status&&Y(null==(l=null!=(n=e.reasonSummary)?n:ee.current)||0===l.trim().length?oT:"qi-run-error"===l?"Die Modellgenerierung ist fehlgeschlagen, bevor nutzbare Testf\xe4lle zur\xfcckgegeben wurden. Versuche es mit einer kleineren Quelle oder pr\xfcfe das ausgew\xe4hlte Modell-Gateway.":"qi-error: UnparseableModelOutputError"===l?"Das Modell hat eine Ausgabe geliefert, die nicht zu Testf\xe4llen geparst werden konnte. Versuche es erneut oder nutze ein Modell mit strukturierter JSON-Ausgabe.":"qi-error: QI_PROMPT_TOO_LARGE"===l?"Der zusammengestellte Quellkontext ist f\xfcr das Modell zu gro\xdf. Reduziere die Quelle und versuche es erneut.":l.startsWith("qi-error: ")?`${oT} (${l.slice(10)})`:l.startsWith("qi-safe-error: ")?`${oT} (${l.slice(15)})`:`${oT} (${l})`)),"error"===e.type&&Y((a=e.code,i=e.message,`${i} (${a})`)),H(t=>function(e,t){var n,l,a;if("accepted"===t.type)return{...e,phase:"Ingested sources",atomCount:t.atomCount,droppedSourceCount:null!=(n=t.droppedSourceCount)?n:0,skippedSources:null!=(l=t.skippedSources)?l:[]};if("event"===t.type){let n="candidate:proposed"===t.kind?e.candidates+1:e.candidates,l="finding:recorded"===t.kind?e.findings+1:e.findings,i=null!=(a=t.stageName)?a:e.stageName;return{...e,phase:t.kind,stageName:i,candidates:n,findings:l};}return e;}(t,e));},[]),eC="capsule"===x||"capsule-set"===x;(0,i.useEffect)(()=>{if(!eC)return;let e=!1;return async function(){P(!0),z(null);try{let[t,n]=await Promise.allSettled([l(),r()]);if(e)return;"fulfilled"===t.status?T(t.value.capsules.filter(e=>"ready"===e.lifecycleState)):(T([]),"capsule"===x&&z(oi(t.reason))),"fulfilled"===n.status?q(n.value.capsuleSets):(q([]),"capsule-set"===x&&z(oi(n.reason)));}finally{e||P(!1);}}(),()=>{e=!0;};},[l,r,eC,x]),(0,i.useEffect)(()=>{var e,t,n,l;if("capsule"===x){let n=F.some(e=>e.id===C)?C:null!=(e=null==(t=F[0])?void 0:t.id)?e:"";n!==C&&I(n);}if("capsule-set"===x){let e=D.some(e=>e.id===R)?R:null!=(n=null==(l=D[0])?void 0:l.id)?n:"";e!==R&&E(e);}},[C,R,D,F,x]);let eI=(0,i.useCallback)(()=>{let e=v.trim();return"requirements"===x&&w.trim().length>0?[{kind:"requirements",label:e||"Requirements",text:w}]:"workspace"===x&&N.trim().length>0?[{kind:"workspace",label:e||"Folder",path:N.trim()}]:"file"===x&&N.trim().length>0?[{kind:"file",label:e||"File",path:N.trim()}]:"capsule"===x&&C.trim().length>0?[{kind:"capsule",label:e||(null==ea?void 0:ea.displayName)||"Knowledge capsule",capsuleId:C.trim()}]:"capsule-set"===x&&R.trim().length>0?[{kind:"capsule-set",label:e||(null==ei?void 0:ei.displayName)||"Capsule set",capsuleSetId:R.trim()}]:null;},[C,R,v,N,ea,ei,x,w]),eR=(0,i.useCallback)(async()=>{var e;if(!ec||U||!ep||et.current)return;et.current=!0,_(!0),Y(null),G(null),H(oF),Z.current=null,ee.current=null;let l=new AbortController();Q.current=l;let a=null!=(e=eI())?e:en,i={sources:a,profileId:O,...(void 0!==eu?{seed:eu}:{})};try{await n(i,l.signal,eS);let e=Z.current;null!==e&&(null==t||t(e,a.filter(e=>"requirements"!==e.kind)));}catch(e){l.signal.aborted||Y(oi(e));}finally{_(!1),Q.current=null,et.current=!1;}},[ec,O,U,en,eI,eS,t,eu,ep,n]),eE=(0,i.useCallback)(()=>{var e;null==(e=Q.current)||e.abort();},[]),e$=V.droppedSourceCount>0?`${V.droppedSourceCount.toString()} source${1!==V.droppedSourceCount?"s":""} over the 16-source limit ${1!==V.droppedSourceCount?"were":"was"} not included.`:null,eA=function(e){if(0===e.length)return null;let t=e.length.toString(),n=1!==e.length?"sources were":"source was";return`${t} connected ${n} skipped: ${e.map(oD).join(", ")}.`;}(V.skippedSources),eF=[e$,eA].filter(e=>null!==e).join(" ");return(0,a.jsxs)("section",{className:"qi-launcher","aria-label":"Start a Quality Intelligence run",children:[(0,a.jsx)("header",{className:"qi-col-header",children:(0,a.jsx)("h2",{className:"qi-col-title",children:"New run"})}),(0,a.jsxs)("div",{className:"qi-launcher-body",children:[1===en.length&&void 0!==en[0]?(0,a.jsxs)("div",{className:"qi-connected-source","data-testid":"qi-connected-source",children:[(0,a.jsxs)("span",{className:"qi-connected-kind",children:["Connected ",oq(en[0]).toLowerCase()]}),(0,a.jsx)("span",{className:"qi-connected-path qi-monospace",title:oM(en[0]),children:oM(en[0])}),(0,a.jsx)("span",{className:"qi-connected-hint",children:es?"Manual input below overrides the connected source for this run.":`Generate uses the connected ${oq(en[0]).toLowerCase()}.`})]}):en.length>1?(0,a.jsxs)("div",{className:"qi-connected-source","data-testid":"qi-connected-source",children:[(0,a.jsxs)("span",{className:"qi-connected-kind",children:["Connected sources (",en.length.toString(),")"]}),(0,a.jsx)("ul",{className:"qi-connected-roots","aria-label":"Connected sources",children:en.map(e=>(0,a.jsxs)("li",{className:"qi-connected-root-item",children:[(0,a.jsx)("span",{className:"qi-connected-root-name",children:oq(e)}),(0,a.jsx)("span",{className:"qi-connected-path qi-monospace",title:oM(e),children:oM(e)})]},`${e.kind}:${oM(e)}`))}),(0,a.jsx)("span",{className:"qi-connected-hint",children:es?"Manual input below overrides the connected sources for this run.":"Generate uses all connected sources."})]}):null,(0,a.jsxs)("div",{className:"qi-launcher-row",children:[(0,a.jsxs)("label",{className:"qi-field",children:[(0,a.jsx)("span",{className:"qi-field-label",children:"Source label"}),(0,a.jsx)("input",{type:"text",className:"qi-input",value:v,placeholder:"e.g. Funds Transfer — acceptance criteria",disabled:U,"aria-describedby":el&&!es?ev:void 0,onChange:e=>{b(e.target.value);}}),el&&!es?(0,a.jsx)("span",{className:"qi-field-hint",id:ev,children:"Applies to manual input only — connected sources use their own labels."}):null]}),(0,a.jsxs)("div",{className:"qi-field qi-field-kind",children:[(0,a.jsx)("span",{className:"qi-field-label",id:eb,children:"Source type"}),(0,a.jsx)("div",{className:"qi-source-kind-grid",role:"radiogroup","aria-labelledby":eb,"aria-disabled":U||void 0,children:o$.map(e=>(0,a.jsxs)("button",{type:"button",className:"qi-source-kind-option",role:"radio","aria-label":e.label,"data-tip":e.label,"aria-checked":x===e.id,tabIndex:x===e.id?0:-1,disabled:U,onPointerDown:t=>{ek(t,e.id);},onClick:()=>ej(e.id),onKeyDown:eN,children:[(0,a.jsx)("span",{className:"qi-source-kind-label",children:e.label}),(0,a.jsx)("span",{className:"qi-source-kind-icon","aria-hidden":"true",children:(0,a.jsx)(oA,{kind:e.id})})]},e.id))})]})]}),function(){if("requirements"===x)return(0,a.jsxs)("label",{className:"qi-field",children:[(0,a.jsx)("span",{className:"qi-field-label",children:"Requirements"}),(0,a.jsx)("textarea",{className:"qi-textarea",value:w,rows:6,placeholder:"Paste requirements or acceptance criteria, one statement per line.",disabled:U,onChange:e=>{j(e.target.value);}})]});if("workspace"===x||"file"===x){let e="file"===x;return(0,a.jsxs)("div",{className:"qi-field",children:[(0,a.jsx)("span",{className:"qi-field-label",id:ex,children:e?"File path":"Folder path"}),(0,a.jsxs)("div",{className:"qi-path-picker",children:[(0,a.jsx)("div",{className:"qi-path-value qi-monospace",role:"textbox","aria-readonly":"true","aria-labelledby":ex,title:N,"data-empty":0===N.trim().length?"true":void 0,children:N.trim().length>0?N:e?"Choose a local file…":"Choose a local folder…"}),(0,a.jsx)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-browse-btn",disabled:U,onClick:()=>A(!0),children:"Browse"})]})]});}let e="capsule"===x,t=e?F:D;return(0,a.jsxs)("label",{className:"qi-field",children:[(0,a.jsx)("span",{className:"qi-field-label",children:e?"Knowledge capsule":"Capsule set"}),(0,a.jsxs)("select",{className:"qi-select",value:e?C:R,disabled:U||M||null!==L||0===t.length,onChange:t=>{e?I(t.target.value):E(t.target.value);},children:[M?(0,a.jsx)("option",{value:"",children:"Loading connectors..."}):null,M||0!==t.length?null:(0,a.jsx)("option",{value:"",children:e?"No ready capsules":"No capsule sets"}),e?F.map(e=>(0,a.jsx)("option",{value:e.id,children:e.displayName},e.id)):D.map(e=>(0,a.jsx)("option",{value:e.id,children:`${e.displayName} (${String(e.capsuleCount)} capsules)`},e.id))]})]});}(),null!==L?(0,a.jsx)("p",{className:"lk-alert",role:"alert","data-testid":"qi-connector-error",children:L}):null,(0,a.jsxs)("div",{className:"qi-launcher-controls",children:[(0,a.jsxs)("div",{className:"qi-field qi-field-inline qi-policy-profile-field",children:[(0,a.jsx)("span",{className:"qi-field-label",children:"Policy profile"}),(0,a.jsx)(tB,{triggerClassName:"qi-select",value:O,ariaLabel:"Policy profile",disabled:U,menuTitle:"Policy",menuClassName:"qi-policy-profile-menu",sections:[{options:oE.map(e=>({value:e.id,label:e.label}))}],onValueChange:K})]}),(0,a.jsxs)("label",{className:"qi-field qi-field-inline",children:[(0,a.jsx)("span",{className:"qi-field-label",children:"Seed (optional)"}),(0,a.jsxs)("span",{className:"number-control qi-number-control",children:[(0,a.jsx)("input",{type:"number",min:0,step:1,className:"qi-input number-control-input",value:B,placeholder:"e.g. 42",disabled:U,"aria-invalid":!ep||void 0,"aria-describedby":ep?void 0:eg,onChange:e=>{W(e.target.value),Y(null);},onWheel:e=>{U||0===e.deltaY||(e.preventDefault(),em(e.deltaY<0?1:-1));}}),(0,a.jsx)(l1,{label:"seed",disabled:U,onStepUp:()=>em(1),onStepDown:()=>em(-1)})]}),ep?null:(0,a.jsx)("span",{className:"qi-field-error",id:eg,children:"Seed must be a non-negative integer."})]}),(0,a.jsx)("button",{type:"button",className:U?"qi-btn qi-btn-secondary":"qi-btn qi-btn-primary","aria-disabled":!U&&eh||void 0,"aria-describedby":U?void 0:ey,onClick:()=>{U?eE():eh||eR();},children:U?"Cancel":"Generate test cases"}),U||ec?null:(0,a.jsx)("span",{className:"qi-generate-hint",id:ef,children:"Add requirements text, a folder path, a file path, select a capsule, select a capsule set, or connect a source to generate."})]}),U?(0,a.jsxs)("div",{className:"qi-progress","data-testid":"qi-launch-progress","aria-hidden":"true",children:[(0,a.jsx)("span",{className:"qi-progress-spinner","aria-hidden":"true"}),(0,a.jsxs)("span",{className:"qi-progress-text",children:[null!==V.stageName?`Stage: ${V.stageName} \xb7 `:"",V.candidates.toString()," test case",1!==V.candidates?"s":"",V.findings>0?` \xb7 ${V.findings.toString()} finding${1!==V.findings?"s":""}`:""]})]}):null,(0,a.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","data-testid":"qi-launch-progress-sr",children:function(e,t){if(!e)return"";if(null===t.stageName&&0===t.candidates&&0===t.findings)return"Generating test cases…";let n=null!==t.stageName?`Stage: ${t.stageName}. `:"",l=`${t.candidates.toString()} test case${1!==t.candidates?"s":""}`,a=t.findings>0?`, ${t.findings.toString()} finding${1!==t.findings?"s":""}`:"";return`${n}${l}${a}`;}(U,V)}),(0,a.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:eF}),null!==e$||null!==eA?(0,a.jsxs)("div",{className:"qi-coverage-notice","data-testid":"qi-coverage-notice",children:[null!==e$?(0,a.jsx)("p",{className:"qi-coverage-line",children:e$}):null,null!==eA?(0,a.jsx)("p",{className:"qi-coverage-line",children:eA}):null]}):null,null!==X?(0,a.jsx)("p",{className:"qi-degraded-notice",role:"status","data-testid":"qi-launch-degraded",children:X}):null,null!==J?(0,a.jsx)("p",{className:"lk-alert",role:"alert","data-testid":"qi-launch-error",children:J}):null]}),$&&null!==ew?(0,a.jsx)(ot.c2,{mode:"file"===ew?"file":"folder",title:`Choose ${"file"===ew?"file":"folder"} source`,description:"Browse a registered local project or enter an absolute folder root.",initialRootPath:"file"===ew?(0,ot.pD)(N):N,fetchProjectsImpl:s,fetchFilesTreeImpl:o,onCancel:()=>A(!1),onApply:e=>{var t;S("file"===ew?(0,ot.$e)(e.rootPath,null!=(t=e.files[0])?t:null):e.folderPath),A(!1),Y(null);}}):null]});}function oL(e){var t;let{run:n,onOpen:l,onDelete:r,deleting:s}=e,o=n.totals.candidates,[c,d]=(0,i.useState)(!1),u=(0,i.useRef)(null),p=(0,i.useRef)(null),m=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(c){var e;null==(e=p.current)||e.focus();}},[c]);let h=(0,i.useCallback)(()=>{d(!1),requestAnimationFrame(()=>{var e;null==(e=u.current)||e.focus();});},[]),f=(0,i.useCallback)(e=>{"Escape"===e.key&&(e.preventDefault(),h());},[h]),g=(0,i.useCallback)(()=>{s||r(n.id);},[s,r,n.id]);return(0,a.jsxs)("li",{style:{display:"flex",alignItems:"stretch"},children:[(0,a.jsxs)("button",{type:"button",className:"qi-run-item",style:{flex:1},onClick:()=>{l(n.id,[]);},"aria-label":`Open run ${n.id} — ${oc(t=n.status)?os[t]:t}, ${or(n.requestedAt)}, ${o.toString()} test case${1!==o?"s":""}, review ${on[n.reviewState]}`,title:`Open run ${n.id}`,children:[(0,a.jsx)("span",{className:"qi-run-title",children:or(n.requestedAt)}),(0,a.jsx)(od,{status:n.status}),(0,a.jsx)(oa,{state:n.reviewState}),(0,a.jsxs)("span",{className:"qi-run-id",children:[n.id.slice(0,16),"…"]}),(0,a.jsxs)("span",{className:"qi-run-totals",children:[n.totals.candidates.toString()," test case",1!==n.totals.candidates?"s":""]})]}),c?(0,a.jsxs)("div",{className:"qi-cand-actions",role:"group","aria-label":`Confirm deleting run ${or(n.requestedAt)}`,style:{display:"flex",alignItems:"center",gap:4,padding:"0 6px",flexShrink:0},children:[(0,a.jsx)("button",{ref:m,type:"button",className:"qi-btn qi-btn-reject",style:{minWidth:0,padding:"4px 10px",fontSize:12,flexShrink:0},"aria-label":`Confirm delete of run ${or(n.requestedAt)}`,"aria-busy":s||void 0,"aria-disabled":s||void 0,onClick:g,onKeyDown:f,children:s?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("span",{"aria-hidden":"true",children:"Deleting…"}),(0,a.jsx)("span",{className:"sr-only",children:"Deleting run, please wait"})]}):"Confirm delete"}),(0,a.jsx)("button",{ref:p,type:"button",className:"qi-btn qi-btn-secondary",style:{minWidth:0,padding:"4px 10px",fontSize:12,flexShrink:0},"aria-disabled":s||void 0,onClick:()=>{s||h();},onKeyDown:f,children:"Cancel"})]}):(0,a.jsx)("button",{ref:u,type:"button",className:"qi-btn qi-btn-reject",style:{alignSelf:"center",minWidth:0,padding:"4px 10px",fontSize:12,margin:"0 6px 0 0",flexShrink:0},"aria-label":`Delete run ${or(n.requestedAt)}`,onClick:()=>{d(!0);},children:"Delete"})]});}function oz(e){let{openRun:t,connectedRoot:n=null,connectedFilePath:l=null,connectedRoots:r,connectedCapsuleIds:s,connectedCapsuleSetIds:o,connectedFigmaSnapshotRunIds:c,connectedFigmaSnapshotSources:d,connectedImageSources:u,fetchRunsImpl:p=s0,deleteImpl:m=s4}=e,[h,f]=(0,i.useState)([]),[g,v]=(0,i.useState)(0),[b,x]=(0,i.useState)(!1),[y,w]=(0,i.useState)(!0),[j,k]=(0,i.useState)(null),[N,S]=(0,i.useState)(25),[C,I]=(0,i.useState)(null),[R,E]=(0,i.useState)(""),$=(0,i.useCallback)(async()=>{w(!0),k(null);try{let e=await p();f(e.runs),v(e.totalRunIds),x(e.truncated);}catch(e){k(oi(e));}finally{w(!1);}},[p]);(0,i.useEffect)(()=>{$();},[$]);let A=(0,i.useCallback)((e,n)=>{$(),t(e,n);},[$,t]),F=(0,i.useCallback)(async e=>{if(null===C){I(e),k(null);try{await m(e),E("Run deleted."),await $();}catch(e){k(oi(e));}finally{I(null);}}},[C,m,$]);return(0,a.jsxs)("div",{className:"qi-hub",children:[(0,a.jsx)(oP,{onRunCompleted:A,connectedRoot:n,connectedFilePath:l,connectedRoots:r,connectedCapsuleIds:s,connectedCapsuleSetIds:o,connectedFigmaSnapshotRunIds:c,connectedFigmaSnapshotSources:d,connectedImageSources:u}),(0,a.jsxs)("section",{className:"qi-hub-runs","aria-label":"Quality Intelligence runs",children:[(0,a.jsxs)("header",{className:"qi-col-header",children:[(0,a.jsx)("h2",{className:"qi-col-title",children:"Runs"}),y||null!==j?null:(0,a.jsx)("span",{className:"qi-col-count",children:g.toString()})]}),(0,a.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:y?"Loading runs…":null===j?`Run list loaded: ${h.length.toString()} run${1===h.length?"":"s"}${b?` of ${g.toString()}`:""}.`:""}),(0,a.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true",children:R}),(0,a.jsx)("div",{className:"qi-col-body","aria-busy":y,children:y?(0,a.jsx)(ob,{}):null!==j?(0,a.jsx)(ox,{message:j,onRetry:()=>{$();}}):0===h.length?(0,a.jsxs)("div",{className:"lk-empty",children:[(0,a.jsx)("p",{className:"lk-empty-title",children:"No runs yet"}),(0,a.jsx)("p",{className:"lk-empty-body",children:"Start a run above — generated test cases open as cards on your workspace."})]}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("ul",{className:"qi-run-list","aria-label":"Run list",children:h.slice(0,N).map(e=>(0,a.jsx)(oL,{run:e,onOpen:t,onDelete:e=>{F(e);},deleting:C===e.id},e.id))}),N<h.length?(0,a.jsxs)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-show-more",onClick:()=>{S(e=>e+25);},children:["Show more runs (",(h.length-N).toString()," remaining)"]}):null,b?(0,a.jsx)("p",{className:"qi-runs-truncated","data-testid":"qi-runs-truncated",children:`Showing ${h.length.toString()} of ${g.toString()} runs.`}):null]})})]})]});}let oO=["P0","P1","P2","P3"],oK=["safety","compliance","regression","functional","visual"],oB=e=>e.split("\n").map(e=>e.trim()).filter(e=>e.length>0),oW=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]);function oU(e,t){let n=oB(t.preconditions),l=oB(t.steps),a=oB(t.expectedResults),i=t.tags.split(",").map(e=>e.trim()).filter(e=>e.length>0);return{...(t.title!==e.title?{title:t.title}:{}),...(!oW(n,e.preconditions)?{preconditions:n}:{}),...(!oW(l,e.steps)?{steps:l}:{}),...(!oW(a,e.expectedResults)?{expectedResults:a}:{}),...(t.priority!==e.priority?{priority:t.priority}:{}),...(t.riskClass!==e.riskClass?{riskClass:t.riskClass}:{}),...(!oW(i,e.tags)?{tags:i}:{})};}function o_(e){let{id:t,label:n,value:l,disabled:i=!1,onChange:r}=e;return(0,a.jsxs)("label",{className:"qi-edit-field",htmlFor:t,children:[(0,a.jsx)("span",{className:"qi-edit-label",children:n}),(0,a.jsx)("textarea",{id:t,className:"qi-edit-textarea",value:l,rows:3,disabled:i,onChange:e=>{r(e.target.value);}})]});}function oV(e){let{id:t,label:n,value:l,disabled:i=!1,required:r=!1,onChange:s}=e;return(0,a.jsxs)("label",{className:"qi-edit-field",htmlFor:t,children:[(0,a.jsx)("span",{className:"qi-edit-label","data-required":r?"true":void 0,children:n}),(0,a.jsx)("input",{id:t,className:"qi-edit-input",value:l,disabled:i,required:r,"aria-required":r?"true":void 0,onChange:e=>{s(e.target.value);}})]});}function oH(e){let{id:t,label:n,value:l,options:i,disabled:r=!1,onChange:s}=e;return(0,a.jsxs)("label",{className:"qi-edit-field",htmlFor:t,children:[(0,a.jsx)("span",{className:"qi-edit-label",children:n}),(0,a.jsx)("select",{id:t,className:"qi-edit-select",value:l,disabled:r,onChange:e=>{s(e.target.value);},children:i.map(e=>(0,a.jsx)("option",{value:e,children:e},e))})]});}function oJ(e){let{onCancel:t,saving:n}=e;return(0,a.jsxs)("div",{className:"qi-edit-actions",children:[(0,a.jsx)("button",{type:"submit",className:"qi-btn qi-btn-approve qi-edit-save","aria-disabled":n||void 0,children:"Save"}),(0,a.jsx)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-edit-cancel","aria-disabled":n||void 0,onClick:()=>{n||t();},children:"Cancel"})]});}function oY(e){let{candidate:t,onSave:n,onCancel:l}=e,[r,s]=(0,i.useState)(()=>({title:t.title,preconditions:t.preconditions.join("\n"),steps:t.steps.join("\n"),expectedResults:t.expectedResults.join("\n"),priority:t.priority,riskClass:t.riskClass,tags:t.tags.join(", ")})),[o,c]=(0,i.useState)(null),[d,u]=(0,i.useState)(!1),[p,m]=(0,i.useState)(!1),h=(0,i.useRef)(null),f=(e,t)=>{c(null),m(!1),s(n=>({...n,[e]:t}));},g=(0,i.useCallback)(()=>{d||(!(Object.keys(oU(t,r)).length>0)||p?l():m(!0));},[t,p,l,d,r]);(0,i.useEffect)(()=>{let e=e=>{if("Escape"!==e.key||d)return;let t=h.current;null!==t&&t.contains(document.activeElement)&&g();};return document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e);};},[g,d]),(0,i.useEffect)(()=>{var e,t;null==(t=h.current)||null==(e=t.querySelector("input.qi-edit-input"))||e.focus();},[]);let v=`qi-edit-${t.id}`,b=async()=>{if(!d){u(!0),c(null);try{await n(oU(t,r));}catch(e){c(oi(e));}finally{u(!1);}}};return(0,a.jsxs)("form",{ref:h,className:"qi-edit-form","aria-label":`Edit ${t.title}`,"aria-busy":d,onSubmit:e=>{e.preventDefault(),b();},children:[(0,a.jsxs)("div",{className:"qi-edit-head",children:[(0,a.jsxs)("div",{className:"qi-edit-head-copy",children:[(0,a.jsx)("p",{className:"qi-edit-eyebrow",children:"Edit test case"}),(0,a.jsx)("h3",{className:"qi-edit-heading",children:t.title})]}),(0,a.jsx)(oJ,{onCancel:g,saving:d})]}),null!==o?(0,a.jsx)("p",{className:"qi-edit-error",role:"alert","aria-live":"assertive",children:o}):null,(0,a.jsx)("p",{className:"qi-edit-discard-note",role:"status","aria-live":"polite",children:p?"Unsaved changes — press Escape or activate Cancel again to discard them.":""}),(0,a.jsxs)("div",{className:"qi-edit-layout",children:[(0,a.jsxs)("div",{className:"qi-edit-main",children:[(0,a.jsx)(oV,{id:`${v}-title`,label:"Title",value:r.title,disabled:d,required:!0,onChange:e=>{f("title",e);}}),(0,a.jsx)(o_,{id:`${v}-preconditions`,label:"Preconditions (one per line)",value:r.preconditions,disabled:d,onChange:e=>{f("preconditions",e);}}),(0,a.jsx)(o_,{id:`${v}-steps`,label:"Steps (one per line)",value:r.steps,disabled:d,onChange:e=>{f("steps",e);}}),(0,a.jsx)(o_,{id:`${v}-expected`,label:"Expected results (one per line)",value:r.expectedResults,disabled:d,onChange:e=>{f("expectedResults",e);}})]}),(0,a.jsxs)("div",{className:"qi-edit-side",children:[(0,a.jsx)(oH,{id:`${v}-priority`,label:"Priority",value:r.priority,options:oO,disabled:d,onChange:e=>{f("priority",e);}}),(0,a.jsx)(oH,{id:`${v}-risk`,label:"Risk class",value:r.riskClass,options:oK,disabled:d,onChange:e=>{f("riskClass",e);}}),(0,a.jsx)(oV,{id:`${v}-tags`,label:"Tags (comma-separated)",value:r.tags,disabled:d,onChange:e=>{f("tags",e);}})]})]})]});}let oX=new Set(["approved","rejected","withdrawn"]);function oG(e){let{items:t,label:n}=e;return 0===t.length?null:(0,a.jsxs)("div",{className:"qi-cand-block",children:[(0,a.jsx)("p",{className:"qi-cand-block-label",children:n}),(0,a.jsx)("ol",{className:"qi-cand-list","aria-label":n,children:t.map((e,t)=>(0,a.jsx)("li",{children:e},`${n}-${String(t)}`))})]});}function oQ(e){let{candidate:t}=e;return(0,a.jsxs)("dl",{className:"qi-cand-meta","aria-label":"Test case metadata",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Steps"}),(0,a.jsx)("dd",{children:t.steps.length.toString()})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Expected"}),(0,a.jsx)("dd",{children:t.expectedResults.length.toString()})]}),void 0!==t.qualityVerdict?(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{children:"Quality"}),(0,a.jsx)("dd",{children:Math.round(t.qualityVerdict.score).toString()})]}):null]});}function oZ(e){let{title:t,children:n}=e;return(0,a.jsxs)("details",{className:"qi-cand-accordion",children:[(0,a.jsx)("summary",{className:"qi-cand-accordion-summary",children:(0,a.jsx)("span",{children:t})}),(0,a.jsx)("div",{className:"qi-cand-accordion-body",children:n})]});}function o0(e){let{candidate:t}=e;return(0,a.jsxs)(oZ,{title:"Scenario",children:[(0,a.jsx)(oG,{items:t.preconditions,label:"Preconditions"}),(0,a.jsx)(oG,{items:t.steps,label:"Steps"}),(0,a.jsx)(oG,{items:t.expectedResults,label:"Expected results"})]});}function o1(e){let{candidate:t}=e;return 0===t.tags.length&&void 0===t.qualityVerdict&&void 0===t.weakTestFlag?null:(0,a.jsxs)(oZ,{title:"Evidence",children:[void 0!==t.weakTestFlag?(0,a.jsx)(oh,{flag:t.weakTestFlag}):null,void 0!==t.qualityVerdict?(0,a.jsx)(og,{verdict:t.qualityVerdict}):null,t.tags.length>0?(0,a.jsx)("ul",{className:"qi-cand-tags","aria-label":"Tags",children:t.tags.map(e=>(0,a.jsx)("li",{className:"qi-cand-tag",children:e},e))}):null]});}function o2(e){let{className:t,label:n,pressed:l,disabled:i,describedBy:r,onActivate:s}=e;return(0,a.jsx)("button",{type:"button",className:t,...(void 0!==l?{"aria-pressed":l}:{}),"aria-disabled":i||void 0,"aria-describedby":i?r:void 0,onClick:()=>{i||s();},children:n});}function o3(e){let{candidateId:t,state:n,onReview:l,disabled:r=!1,describedBy:s,pendingReview:o}=e,c=null!=o,d=e=>c&&o.candidateId===t&&o.action===e,u=oX.has(n),p=(0,i.useId)(),m=u?p:s;return(0,a.jsxs)("div",{className:"qi-cand-actions",role:"group","aria-label":"Review decision",children:[u?(0,a.jsx)("p",{id:p,className:"qi-cand-governance-note",role:"note",children:"This review decision is final — reopen to change it."}):null,(0,a.jsx)(o2,{className:"qi-btn qi-btn-approve",label:d("approve")?"Saving…":"Approve",pressed:"approved"===n,disabled:r||c||u,describedBy:m,onActivate:()=>{l(t,"approve");}}),(0,a.jsx)(o2,{className:"qi-btn qi-btn-reject",label:d("reject")?"Saving…":"Reject",pressed:"rejected"===n,disabled:r||c||u,describedBy:m,onActivate:()=>{l(t,"reject");}}),(0,a.jsx)(o2,{className:"qi-btn qi-btn-secondary",label:d("request-changes")?"Saving…":"Request changes",pressed:"changes-requested"===n,disabled:r||c||u,describedBy:m,onActivate:()=>{l(t,"request-changes");}}),u?(0,a.jsx)(o2,{className:"qi-btn qi-btn-secondary",label:d("reopen")?"Saving…":"Reopen",disabled:r||c,describedBy:r?s:void 0,onActivate:()=>{l(t,"reopen");}}):null]});}function o4(e){let{candidate:t,onReview:n,onStartEdit:l,actionsDisabled:r=!1,actionsDisabledReason:s,describedBy:o,editButtonRef:c,pendingReview:d}=e,u=(0,i.useId)(),p=r&&void 0!==s?[o,u].filter(Boolean).join(" "):o;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"qi-cand-header",children:[(0,a.jsx)("div",{className:"qi-cand-title-wrap",children:(0,a.jsx)("h3",{className:"qi-cand-title",children:t.title})}),(0,a.jsxs)("div",{className:"qi-cand-status",children:[(0,a.jsxs)("div",{className:"qi-cand-badges",children:[(0,a.jsx)("span",{className:"qi-cand-risk",children:t.riskClass}),"open"!==t.reviewState?(0,a.jsx)(oa,{state:t.reviewState}):null]}),(0,a.jsx)(oQ,{candidate:t})]})]}),(0,a.jsxs)("div",{className:"qi-cand-accordion-stack",children:[(0,a.jsx)(o0,{candidate:t}),(0,a.jsx)(o1,{candidate:t})]}),(0,a.jsxs)("div",{className:"qi-cand-actions-row",children:[r&&void 0!==s?(0,a.jsx)("p",{id:u,className:"qi-cand-action-note",role:"note",children:s}):null,(0,a.jsxs)("div",{className:"qi-cand-action-buttons",children:[void 0!==l?(0,a.jsx)("button",{ref:c,type:"button",className:"qi-btn qi-btn-secondary qi-cand-edit","aria-disabled":r||void 0,"aria-describedby":r?p:void 0,onClick:()=>{r||l();},children:"Edit"}):null,void 0!==n?(0,a.jsx)(o3,{candidateId:t.id,state:t.reviewState,onReview:n,disabled:r,describedBy:p,pendingReview:d}):null]})]})]});}function o6(e){let{candidate:t,onReview:n,onEdit:l,actionsDisabled:r=!1,actionsDisabledReason:s,describedBy:o,pendingReview:c}=e,[d,u]=(0,i.useState)(!1),p=(0,i.useRef)(null),m=(0,i.useRef)(!1);(0,i.useEffect)(()=>{var e;m.current&&!d&&(null==(e=p.current)||e.focus()),m.current=d;},[d]);let h=async e=>{void 0!==l&&(await l(t.id,e)),u(!1);};return(0,a.jsx)("li",{className:d?"qi-cand-card qi-cand-card-editing":"qi-cand-card",children:d&&void 0!==l?(0,a.jsx)(oY,{candidate:t,onSave:h,onCancel:()=>{u(!1);}}):(0,a.jsx)(o4,{candidate:t,onReview:n,actionsDisabled:r,actionsDisabledReason:s,describedBy:o,pendingReview:c,editButtonRef:p,onStartEdit:void 0!==l?()=>{u(!0);}:void 0})});}function o5(e){let{candidates:t,onReview:n,onEdit:l,actionsDisabled:r=!1,actionsDisabledReason:s,pendingReview:o}=e,[c,d]=(0,i.useState)(25),u=(0,i.useId)(),p=r&&void 0!==s;if(0===t.length)return(0,a.jsxs)("div",{className:"lk-empty",children:[(0,a.jsx)("p",{className:"lk-empty-title",children:"No test cases"}),(0,a.jsx)("p",{className:"lk-empty-body",children:"This run produced no generated test cases."})]});let m=[...t].sort((e,t)=>!!e.tags.includes("source:deterministic-baseline")-!!t.tags.includes("source:deterministic-baseline")).slice(0,c);return(0,a.jsxs)("div",{className:"qi-cand-pane",children:[p?(0,a.jsx)("p",{id:u,className:"qi-cand-governance-note",role:"note",children:s}):null,(0,a.jsx)("ul",{className:"qi-cand-cards","aria-label":"Test case list",children:m.map(e=>(0,a.jsx)(o6,{candidate:e,onReview:n,onEdit:l,actionsDisabled:r,actionsDisabledReason:s,describedBy:p?u:void 0,pendingReview:o},e.id))}),c<t.length?(0,a.jsxs)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-cand-more",onClick:()=>{d(e=>e+25);},children:["Show more test cases (",(t.length-c).toString()," remaining)"]}):null]});}function o8(e){return 0===e?"No drift — every test is current.":`${e.toString()} ${1===e?"test is":"tests are"} stale — source changed since this run.`;}function o7(e){let t=e.regeneratedCount,n=e.preservedCount;return`Regenerated ${t.toString()} ${1===t?"test":"tests"} as a new run (${n.toString()} ${1===n?"test":"tests"} preserved).`;}function o9(e){let{staleCount:t}=e;return 0===t?(0,a.jsxs)("p",{className:"qi-drift-fresh","data-testid":"qi-drift-fresh",children:[(0,a.jsx)("span",{"aria-hidden":"true",className:"qi-drift-icon-ok",children:"✓"}),o8(0)]}):(0,a.jsxs)("p",{className:"qi-drift-stale","data-testid":"qi-drift-stale",children:[(0,a.jsx)("span",{"aria-hidden":"true",className:"qi-drift-icon-warn",children:"⚠"}),o8(t)]});}function ce(e){let{runId:t,connectedSources:n,onRegenerated:l,reCheckImpl:r=s8,regenerateImpl:s=s7}=e,[o,c]=(0,i.useState)(null),[d,u]=(0,i.useState)(null),p=null!==d,[m,h]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(null),x=(0,i.useCallback)(()=>{p||(async()=>{u("check"),h(null),g(null);try{c(await r(t,n));}catch(e){h(oi(e));}finally{u(null);}})();},[p,r,t,n]),y=(0,i.useCallback)(()=>{p||(async()=>{u("regenerate"),h(null);try{let a=await s(t,n);if(document.activeElement===b.current){var e;null==(e=v.current)||e.focus();}g(a),c(null),null==l||l(a);}catch(e){h(oi(e));}finally{u(null);}})();},[p,s,t,n,l]);return(0,a.jsxs)("section",{className:"qi-drift-panel","aria-label":"Drift detection",children:[(0,a.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:null!==f?o7(f):null!==o?o8(o.staleCount):""}),(0,a.jsxs)("div",{className:"qi-drift-head",children:[(0,a.jsx)("h3",{className:"qi-col-subtitle",children:"Living tests"}),(0,a.jsx)("button",{type:"button",ref:v,className:"qi-btn qi-btn-secondary",onClick:x,"aria-disabled":p||void 0,"data-testid":"qi-drift-recheck",children:"check"===d?"Checking…":"Re-check drift"})]}),null!==m?(0,a.jsx)("p",{className:"lk-alert",role:"alert",children:m}):null,null!==o?(0,a.jsx)(o9,{staleCount:o.staleCount}):null,null!==o&&o.staleCount>0&&null===f?(0,a.jsx)("button",{type:"button",ref:b,className:"qi-btn qi-btn-approve",onClick:y,"aria-disabled":p||void 0,"data-testid":"qi-drift-regenerate",children:"regenerate"===d?"Regenerating…":`Regenerate ${o.staleCount.toString()} stale ${1===o.staleCount?"test":"tests"}`}):null,null!==f?(0,a.jsx)("p",{className:"qi-drift-regenerated","data-testid":"qi-drift-regenerated",children:o7(f)}):null]});}let ct={"traceability-csv":"csv","traceability-markdown":"markdown"},cn=[{id:"csv",label:"CSV",tms:!1},{id:"json",label:"JSON",tms:!1},{id:"spreadsheet-safe-csv",label:"Spreadsheet-safe CSV",tms:!1},{id:"markdown",label:"Markdown",tms:!1},{id:"plain-text",label:"Plain text",tms:!1},{id:"pdf",label:"PDF",tms:!1},{id:"zip-bundle",label:"ZIP bundle (all formats)",tms:!1},{id:"traceability-csv",label:"Traceability matrix (CSV)",tms:!1},{id:"traceability-markdown",label:"Traceability matrix (Markdown)",tms:!1},{id:"jira-issues",label:"Jira (preview)",tms:!0},{id:"qtest",label:"qTest (preview)",tms:!0},{id:"xray",label:"Xray (preview)",tms:!0},{id:"polarion",label:"Polarion (preview)",tms:!0},{id:"quality-center",label:"Quality Center (preview)",tms:!0}];function cl(e,t,n,l){let a=new Blob(["base64"===l?function(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n;}(n):n],{type:t}),i=URL.createObjectURL(a),r=document.createElement("a");r.href=i,r.download=e,document.body.appendChild(r),r.click(),r.remove(),window.setTimeout(()=>{URL.revokeObjectURL(i);},250);}function ca(e){var t;let{runId:n,exportImpl:l=s9,traceabilityImpl:r=oe}=e,[s,o]=(0,i.useState)("csv"),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(null),[m,h]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),[v,b]=(0,i.useState)(!1),x=cn.find(e=>e.id===s),y=null!=(t=null==x?void 0:x.tms)&&t,w=(0,i.useCallback)(async()=>{let e=ct[s];if(void 0!==e){let t=await r(n,e);cl(t.filename,t.contentType,t.body),g(t.filename);return;}let t=await l(n,s,{dryRun:y,approvedOnly:v});t.dryRun?h(`${t.candidateCount.toString()} test case${1===t.candidateCount?"":"s"} \xb7 ${t.byteLen.toString()} bytes
|
|
97
|
-
|
|
98
|
-
${t.preview}`):(cl(t.filename,t.contentType,t.body,t.encoding),g(t.filename));},[n,s,y,v,l,r]),j=(0,i.useCallback)(async()=>{d(!0),p(null),h(null),g(null);try{await w();}catch(e){p(oi(e));}finally{d(!1);}},[w]);return(0,a.jsxs)("div",{className:"qi-export","data-testid":"qi-export-bar",children:[(0,a.jsxs)("div",{className:"qi-export-head",children:[(0,a.jsxs)("div",{className:"qi-export-copy",children:[(0,a.jsx)("p",{className:"qi-export-title",children:"Export"}),y?null:(0,a.jsx)("p",{className:"qi-export-hint",role:"note","data-testid":"qi-export-scope-notice",children:v?"Exports approved test cases only.":"Exports all test cases, including unapproved."})]}),y?null:(0,a.jsxs)("label",{className:"qi-export-approved-label",children:[(0,a.jsx)("input",{type:"checkbox",className:"qi-checkbox",checked:v,disabled:c,onChange:e=>{b(e.target.checked);},"data-testid":"qi-export-approved-only"}),(0,a.jsx)("span",{children:"Approved only"})]})]}),(0,a.jsxs)("div",{className:"qi-export-controls",children:[(0,a.jsxs)("div",{className:"qi-field qi-export-format",children:[(0,a.jsx)("span",{className:"qi-field-label",children:"Format"}),(0,a.jsx)(tB,{triggerClassName:"qi-select",value:s,ariaLabel:"Export",disabled:c,ariaDescribedBy:y?"qi-export-connector-hint":void 0,menuTitle:"Export",sections:[{options:cn.map(e=>({value:e.id,label:e.label}))}],onValueChange:e=>{o(e),h(null),p(null),g(null);}})]}),(0,a.jsx)("button",{type:"button",className:"qi-btn qi-btn-primary qi-export-action",disabled:c,onClick:()=>{j();},children:c?"Exporting…":y?"Preview":"Download"})]}),(0,a.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:null!==f?`Downloaded ${f}`:null!==m?"Export preview ready below.":""}),y?(0,a.jsx)("p",{id:"qi-export-connector-hint",className:"qi-export-hint",role:"note","data-testid":"qi-export-connector-hint",children:(null==x?void 0:x.id)==="quality-center"?"Quality Center is preview-only. Configure a connector to enable live export.":"External target — preview only. Configure a connector to enable live export."}):null,null!==f?(0,a.jsx)("p",{className:"qi-export-success","data-testid":"qi-export-success",children:`Downloaded ${f}`}):null,null!==m?(0,a.jsx)("pre",{className:"qi-export-preview",role:"region","aria-label":"Export preview",tabIndex:0,"data-testid":"qi-export-preview",children:m}):null,null!==u?(0,a.jsx)("p",{className:"lk-alert",role:"alert","data-testid":"qi-export-error",children:u}):null]});}let ci="keiko.qi.reviewerLabel",cr="Set a reviewer label to review or edit candidates.";function cs(e){let{detail:t}=e;return(0,a.jsxs)("dl",{className:"qi-run-summary","aria-label":"Run summary",children:[(0,a.jsxs)("div",{className:"qi-run-summary-item",children:[(0,a.jsx)("dt",{children:"Status"}),(0,a.jsx)("dd",{children:(0,a.jsx)(od,{status:t.status})})]}),(0,a.jsxs)("div",{className:"qi-run-summary-item",children:[(0,a.jsx)("dt",{children:"Test cases"}),(0,a.jsx)("dd",{children:t.totals.candidates.toString()})]}),(0,a.jsxs)("div",{className:"qi-run-summary-item",children:[(0,a.jsx)("dt",{children:"Findings"}),(0,a.jsx)("dd",{children:t.totals.findings.toString()})]}),(0,a.jsxs)("div",{className:"qi-run-summary-item",children:[(0,a.jsx)("dt",{children:"Quality"}),(0,a.jsx)("dd",{children:(0,a.jsx)(om,{score:t.qualityScore})})]}),(0,a.jsxs)("div",{className:"qi-run-summary-item",children:[(0,a.jsx)("dt",{children:"Review"}),(0,a.jsx)("dd",{className:"qi-run-summary-review",children:on[t.reviewState]})]}),(0,a.jsxs)("div",{className:"qi-run-summary-item",children:[(0,a.jsx)("dt",{children:"Requested"}),(0,a.jsx)("dd",{children:or(t.requestedAt)})]}),null!==t.completedAt?(0,a.jsxs)("div",{className:"qi-run-summary-item",children:[(0,a.jsx)("dt",{children:"Completed"}),(0,a.jsx)("dd",{children:or(t.completedAt)})]}):null]});}let co={"logic-defect":"Logic defect","faithfulness-defect":"Faithfulness defect","semantic-defect":"Semantic defect","mutation-defect":"Mutation defect","policy-violation":"Policy violation","manual-rejection":"Manual rejection","coverage-gap":"Coverage gap","test-quality":"Test quality"};function cc(e){let{detail:t}=e,[n,l]=(0,i.useState)(20),r=t.findingRefs.length;if(0===r)return null;let s=t.findingRefs.slice(0,n);return(0,a.jsxs)("section",{className:"qi-run-findings","aria-label":"Findings",children:[(0,a.jsxs)("h3",{className:"qi-col-subtitle",children:["Findings",(0,a.jsx)("span",{className:"qi-col-count",children:r.toString()})]}),(0,a.jsx)("ul",{className:"qi-finding-list","aria-label":"Findings list",children:s.map(e=>{var t;return(0,a.jsxs)("li",{className:"qi-finding-item",children:[(0,a.jsxs)("div",{className:"qi-finding-header",children:[(0,a.jsx)("span",{className:"qi-finding-kind",children:null!=(t=co[e.kind])?t:e.kind}),(0,a.jsx)(op,{severity:e.severity})]}),(0,a.jsx)("p",{className:"qi-finding-summary",children:e.summaryRedacted})]},e.id);})}),n<r?(0,a.jsxs)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-show-more",onClick:()=>{l(e=>e+20);},children:["Show more findings (",(r-n).toString()," remaining)"]}):null]});}let cd={covered:"Covered","weakly-covered":"Weakly covered",uncovered:"Uncovered"},cu={covered:"qi-cov-covered","weakly-covered":"qi-cov-weak",uncovered:"qi-cov-uncovered"},cp={uncovered:0,"weakly-covered":1,covered:2};function cm(e){let{detail:t}=e,[n,l]=(0,i.useState)(20),{total:r,coveredCount:s,gaps:o}=(0,i.useMemo)(()=>{let e=t.coverageByAtom;return{total:e.length,coveredCount:e.filter(e=>"covered"===e.status).length,gaps:e.filter(e=>"covered"!==e.status).sort((e,t)=>cp[e.status]-cp[t.status])};},[t.coverageByAtom]);if(0===r)return null;let c=o.slice(0,n);return(0,a.jsxs)("section",{className:"qi-coverage-panel","aria-label":"Coverage",children:[(0,a.jsxs)("h3",{className:"qi-col-subtitle",children:["Coverage",(0,a.jsxs)("span",{className:"qi-badge qi-badge-default","aria-label":`Coverage: ${t.coveragePercentage.toFixed(0)} percent, ${s.toString()} of ${r.toString()} requirements covered`,"data-testid":"qi-coverage-pct",children:[t.coveragePercentage.toFixed(0),"%"]})]}),(0,a.jsx)("p",{className:"qi-coverage-summary","data-testid":"qi-coverage-summary",children:`${s.toString()} of ${r.toString()} requirements covered \xb7 ${o.length.toString()} gap${1===o.length?"":"s"}`}),o.length>0?(0,a.jsxs)("section",{className:"qi-coverage-gaps","aria-label":"Gap radar",children:[(0,a.jsx)("h4",{className:"qi-col-subtitle",children:`Gap radar (${o.length.toString()})`}),(0,a.jsx)("ul",{className:"qi-coverage-gap-list","aria-label":"Uncovered and weakly covered atoms",children:c.map(e=>{let t=cd[e.status],n=cu[e.status],l=e.requirementExcerptRedacted;return(0,a.jsxs)("li",{className:"qi-coverage-gap-item","aria-label":void 0===l?`Atom ${e.atomId}: ${t}`:`Requirement "${l}" (atom ${e.atomId}): ${t}`,children:[(0,a.jsxs)("span",{className:"qi-coverage-gap-req",children:[void 0===l?null:(0,a.jsx)("span",{className:"qi-coverage-gap-text","data-testid":"qi-coverage-gap-text",children:l}),(0,a.jsx)("span",{className:"qi-coverage-atom-id qi-monospace",children:e.atomId})]}),(0,a.jsx)("span",{className:`qi-badge ${n}`,"aria-hidden":"true",children:t}),(0,a.jsx)("span",{className:"qi-sr-only",children:t})]},e.atomId);})}),n<o.length?(0,a.jsxs)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-show-more",onClick:()=>{l(e=>e+20);},children:["Show more gaps (",(o.length-n).toString()," remaining)"]}):null]}):null]});}function ch(e){let{detail:t}=e,n=(0,i.useId)();return t.drift.reCheckSupported?(0,a.jsxs)("section",{className:"qi-drift-panel","aria-label":"Drift detection",children:[(0,a.jsxs)("div",{className:"qi-drift-head",children:[(0,a.jsx)("h3",{className:"qi-col-subtitle",children:"Living tests"}),(0,a.jsx)("button",{type:"button",className:"qi-btn qi-btn-secondary","aria-disabled":"true","aria-describedby":n,"data-testid":"qi-drift-recheck-unavailable",onClick:e=>{e.preventDefault();},children:"Re-check drift"})]}),(0,a.jsx)("p",{id:n,className:"qi-drift-note","data-testid":"qi-drift-unavailable",children:"Drift fingerprints are recorded for this run, but this card has no current source handle. Reopen it from the connected source or start a new run from the current source."})]}):null;}function cf(e){let{runId:t,connectedSources:n,onRegenerated:l,fetchDetailImpl:r=s1,reviewImpl:s=s6,editImpl:o=s5,reCheckImpl:c,regenerateImpl:d}=e,[u,p]=(0,i.useState)(null),[m,h]=(0,i.useState)(!0),[f,g]=(0,i.useState)(null),[v,b]=(0,i.useState)(null),[x,y]=(0,i.useState)(null),[w,j]=(0,i.useState)(""),[k,N]=(0,i.useState)(!1),S=(0,i.useId)(),C=(0,i.useId)(),[I,R]=(0,i.useState)(""),E=(0,i.useRef)(0),$=(0,i.useRef)(0),A=(0,i.useCallback)(async()=>{let e=$.current+1;$.current=e,h(!0),g(null);try{let n=await r(t);$.current===e&&p(n);}catch(t){$.current===e&&g(oi(t));}finally{$.current===e&&h(!1);}},[r,t]);(0,i.useEffect)(()=>{A();},[A]),(0,i.useEffect)(()=>{j(function(){try{var e;return null!=(e=window.localStorage.getItem(ci))?e:"";}catch{return"";}}()),N(!0);},[]),(0,i.useEffect)(()=>{if(k)try{window.localStorage.setItem(ci,w);}catch{}},[w,k]);let F=w.trim(),T=F.length>0,D=(0,i.useCallback)((e,n)=>{T&&null===x&&(y({candidateId:e,action:n}),(async()=>{b(null);try{var l,a;await s(t,n,e,F),await A();let i=on["approve"===n?"approved":"reject"===n?"rejected":"request-changes"===n?"changes-requested":"open"],r=null!=(l=null==u||null==(a=u.candidates.find(t=>t.id===e))?void 0:a.title)?l:e;E.current+=1,R(`Candidate "${r}" marked ${i}. (${E.current.toString()})`);}catch(e){b(oi(e));}finally{y(null);}})());},[T,x,s,t,F,A,u]),q=(0,i.useCallback)(async(e,n)=>{if(!T)throw Error(cr);await o(t,e,n,F),await A();},[o,T,t,F,A]);return(0,a.jsxs)("div",{className:"qi-run-card","data-testid":"qi-run-card",children:[(0,a.jsx)("header",{className:"qi-run-card-head",children:(0,a.jsx)("span",{className:"qi-run-id qi-monospace",title:t,role:"heading","aria-level":2,"aria-label":`Quality Intelligence run ${t}`,children:t})}),(0,a.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:m?"Loading run…":null===f&&null!==u?`Run loaded: ${u.totals.candidates.toString()} test case${1===u.totals.candidates?"":"s"}.`:""}),(0,a.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","data-testid":"qi-review-announce",children:I}),(0,a.jsx)("div",{className:"qi-run-card-body","aria-busy":m,children:m&&null===u?(0,a.jsx)(ob,{}):null!==f?(0,a.jsx)(ox,{message:f,onRetry:()=>void A()}):null===u?(0,a.jsx)("div",{className:"lk-empty",children:(0,a.jsx)("p",{className:"lk-empty-body",children:"Run not found."})}):(0,a.jsxs)(a.Fragment,{children:[null!==v?(0,a.jsxs)("div",{className:"lk-alert qi-action-error",role:"alert","data-testid":"qi-action-error",children:[v,(0,a.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>{b(null);},children:"Dismiss"})]}):null,(0,a.jsxs)("section",{className:"qi-run-governance","aria-label":"Review governance",children:[(0,a.jsxs)("label",{className:"qi-field",htmlFor:`qi-reviewer-label-${t}`,children:[(0,a.jsx)("span",{className:"qi-field-label",children:"Reviewer label"}),(0,a.jsx)("input",{id:`qi-reviewer-label-${t}`,className:"qi-input qi-run-governance-input",value:w,placeholder:"Required for review and edit actions","aria-invalid":!T,"aria-describedby":T?S:`${S} ${C}`,onChange:e=>{j(e.target.value);}})]}),(0,a.jsx)("p",{id:S,className:"qi-run-governance-help",children:"Used for QI review and edit audit entries."}),(0,a.jsx)("p",{id:C,className:"qi-run-governance-warning",role:"status","aria-live":"polite",children:T?"":cr})]}),(0,a.jsx)(cs,{detail:u}),(0,a.jsx)(cc,{detail:u}),(0,a.jsx)(cm,{detail:u}),void 0!==n&&n.length>0?(0,a.jsx)(ce,{runId:t,connectedSources:n,onRegenerated:l,reCheckImpl:c,regenerateImpl:d}):(0,a.jsx)(ch,{detail:u}),(0,a.jsxs)("section",{className:"qi-run-cases","aria-label":"Generated test cases",children:[(0,a.jsxs)("div",{className:"qi-run-cases-head",children:[(0,a.jsxs)("h3",{className:"qi-col-subtitle",children:["Test cases",(0,a.jsx)("span",{className:"qi-col-count",children:u.candidates.length.toString()})]}),u.candidates.length>0?(0,a.jsx)(ca,{runId:t}):null]}),(0,a.jsx)(o5,{candidates:u.candidates,onReview:D,pendingReview:x,onEdit:q,actionsDisabled:!T,actionsDisabledReason:cr})]})]})})]});}let cg={inactive:{label:"Inactive",ariaDescription:"No recent activity for this relationship.",iconShape:"hollow-circle",textColor:"var(--fg-muted)",bgColor:"var(--inset)",animated:!1},queued:{label:"Queued",ariaDescription:"A workflow run referencing this relationship is queued.",iconShape:"clock",textColor:"var(--fg-muted)",bgColor:"var(--inset)",animated:!1},active:{label:"Active",ariaDescription:"A model call referencing this relationship is in progress.",iconShape:"filled-circle",textColor:"var(--accent)",bgColor:"var(--accent-dim)",borderColor:"var(--accent-line)",animated:!1},processing:{label:"Processing",ariaDescription:"A tool or command referencing this relationship is executing.",iconShape:"spinning-circle",textColor:"var(--accent)",bgColor:"var(--accent-dim)",borderColor:"var(--accent-line)",animated:!0},completed:{label:"Completed",ariaDescription:"The most recent run referencing this relationship completed successfully.",iconShape:"check",textColor:"var(--accent)",bgColor:"var(--accent-dim)",animated:!1},failed:{label:"Failed",ariaDescription:"The most recent run referencing this relationship failed.",iconShape:"triangle-exclamation",textColor:"var(--danger)",bgColor:"color-mix(in oklch, var(--danger) 12%, var(--card))",animated:!1},blocked:{label:"Blocked",ariaDescription:"The validator denied a recent proposal referencing this relationship; see the inspector for the reason.",iconShape:"filled-square",textColor:"var(--warn)",bgColor:"color-mix(in oklch, var(--warn) 12%, var(--card))",animated:!1},degraded:{label:"Degraded",ariaDescription:"The health check flagged at least one endpoint of this relationship as not currently live.",iconShape:"broken-line",textColor:"var(--warn)",bgColor:"color-mix(in oklch, var(--warn) 8%, var(--card))",animated:!1},"high-throughput":{label:"High throughput",ariaDescription:"More than fifty events referenced this relationship in the last sixty seconds.",iconShape:"stacked-lines",textColor:"var(--accent)",bgColor:"var(--accent-dim)",animated:!1}};function cv(e){let{shape:t,color:n,animated:l,highContrast:i}=e,r=["rb-edge-badge-icon",l?"rb-edge-badge-icon--processing":"",i?"rb-edge-badge-icon--high-contrast":""].filter(e=>e.length>0).join(" "),s=i?2:1.5,o={width:12,height:12,viewBox:"0 0 12 12","aria-hidden":!0,fill:"currentColor",className:r,style:{color:n}};switch(t){case"hollow-circle":return(0,a.jsx)("svg",{...o,children:(0,a.jsx)("circle",{cx:"6",cy:"6",r:"4.5",fill:"none",stroke:"currentColor",strokeWidth:s})});case"clock":return(0,a.jsxs)("svg",{...o,children:[(0,a.jsx)("circle",{cx:"6",cy:"6",r:"4.5",fill:"none",stroke:"currentColor",strokeWidth:s}),(0,a.jsx)("path",{d:"M6 3v3l2 1",stroke:"currentColor",strokeWidth:s,strokeLinecap:"round",fill:"none"})]});case"filled-circle":return(0,a.jsx)("svg",{...o,children:(0,a.jsx)("circle",{cx:"6",cy:"6",r:"5"})});case"spinning-circle":return(0,a.jsx)("svg",{...o,children:(0,a.jsx)("circle",{cx:"6",cy:"6",r:"4.5",fill:"none",stroke:"currentColor",strokeWidth:s,strokeDasharray:"8 4"})});case"check":return(0,a.jsx)("svg",{...o,children:(0,a.jsx)("path",{d:"M2 6l3 3 5-5",stroke:"currentColor",strokeWidth:i?2.2:1.8,strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})});case"triangle-exclamation":return(0,a.jsxs)("svg",{...o,children:[(0,a.jsx)("path",{d:"M6 1 L11 10 L1 10 Z",fill:"currentColor"}),(0,a.jsx)("path",{d:"M6 5v2.5",stroke:"var(--card)",strokeWidth:s,strokeLinecap:"round",fill:"none"}),(0,a.jsx)("circle",{cx:"6",cy:"9",r:"0.7",fill:"var(--card)"})]});case"filled-square":return(0,a.jsx)("svg",{...o,children:(0,a.jsx)("rect",{x:"1.5",y:"1.5",width:"9",height:"9",rx:"1.5"})});case"broken-line":return(0,a.jsx)("svg",{...o,children:(0,a.jsx)("path",{d:"M1 6h2.5l1.5-2 2 4 1.5-2H11",stroke:"currentColor",strokeWidth:s,strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})});case"stacked-lines":return(0,a.jsxs)("svg",{...o,children:[(0,a.jsx)("rect",{x:"2",y:"2.5",width:"8",height:"1.5",rx:"0.75"}),(0,a.jsx)("rect",{x:"2",y:"5.25",width:"8",height:"1.5",rx:"0.75"}),(0,a.jsx)("rect",{x:"2",y:"8",width:"8",height:"1.5",rx:"0.75"})]});}}function cb(e){let{state:t}=e,n={width:10,height:10,viewBox:"0 0 10 10","aria-hidden":!0,fill:"currentColor"};switch(t){case"draft":return(0,a.jsx)("svg",{...n,children:(0,a.jsx)("circle",{cx:"5",cy:"5",r:"4",fill:"none",stroke:"currentColor",strokeWidth:"1.5"})});case"active":return(0,a.jsx)("svg",{...n,children:(0,a.jsx)("circle",{cx:"5",cy:"5",r:"4.5"})});case"archived":return(0,a.jsx)("svg",{...n,children:(0,a.jsx)("rect",{x:"1",y:"1",width:"8",height:"8",rx:"1"})});case"superseded":return(0,a.jsx)("svg",{...n,children:(0,a.jsx)("path",{d:"M2 5h6M6 3l2 2-2 2",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})});case"revoked":return(0,a.jsx)("svg",{...n,children:(0,a.jsx)("path",{d:"M2 2l6 6M8 2L2 8",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",fill:"none"})});case"blocked":return(0,a.jsxs)("svg",{...n,children:[(0,a.jsx)("rect",{x:"1",y:"1",width:"8",height:"8",rx:"1"}),(0,a.jsx)("path",{d:"M5 3v3",stroke:"var(--card)",strokeWidth:"1.5",strokeLinecap:"round",fill:"none"}),(0,a.jsx)("circle",{cx:"5",cy:"7.5",r:"0.6",fill:"var(--card)"})]});case"stale":return(0,a.jsx)("svg",{...n,children:(0,a.jsx)("rect",{x:"1",y:"1",width:"8",height:"8",rx:"1",fill:"none",stroke:"currentColor",strokeWidth:"1.5"})});}}function cx(e){var t;let{type:n,lifecycle:l,activity:r,throughputCount:s,animateOverride:o=!0,highContrast:c,onClick:d,className:u=""}=e,[p,m]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(void 0!==c)return;let e=window.matchMedia("(prefers-contrast: more)"),t=e=>{m(e);};t(e.matches);let n=e=>{t(e.matches);};return e.addEventListener("change",n),()=>{e.removeEventListener("change",n);};},[c]);let h=null!=(t=cg[r])?t:cg.inactive,f=ll[n],g=null!=c?c:p,v="high-throughput"===r&&void 0!==s?`${h.label} (${String(s)})`:h.label,b=`${f.displayName} — ${h.ariaDescription}`,x=h.animated&&o,y=g?{color:h.textColor,background:"var(--card)",border:`1px solid ${h.textColor}`}:{color:h.textColor,background:h.bgColor,border:void 0!==h.borderColor?`1px solid ${h.borderColor}`:void 0};return(0,a.jsx)("span",{role:"status","aria-live":"polite","aria-atomic":"true",className:`rb-edge-badge ${u}`.trim(),"data-activity-state":r,"data-high-contrast":g?"true":void 0,children:void 0!==d?(0,a.jsxs)("button",{type:"button",className:"rb-edge-badge-btn",style:y,"aria-label":b,onClick:d,children:[(0,a.jsx)("span",{"aria-hidden":"true",children:(0,a.jsx)(cv,{shape:h.iconShape,color:h.textColor,animated:x,highContrast:g})}),(0,a.jsx)("span",{className:"visually-hidden",children:h.ariaDescription}),(0,a.jsx)("span",{"aria-hidden":"true",className:"rb-edge-badge-label",children:v}),(0,a.jsx)("span",{className:"rb-edge-badge-type",children:f.displayName}),(0,a.jsx)(cb,{state:l})]}):(0,a.jsxs)("span",{className:"rb-edge-badge-static",style:y,"aria-label":b,children:[(0,a.jsx)("span",{"aria-hidden":"true",children:(0,a.jsx)(cv,{shape:h.iconShape,color:h.textColor,animated:x,highContrast:g})}),(0,a.jsx)("span",{className:"visually-hidden",children:h.ariaDescription}),(0,a.jsx)("span",{"aria-hidden":"true",className:"rb-edge-badge-label",children:v}),(0,a.jsx)("span",{className:"rb-edge-badge-type",children:f.displayName}),(0,a.jsx)(cb,{state:l})]})});}let cy="keiko.relationships.density",cw={minimal:5,standard:25,dense:512};function cj(){try{let e=window.localStorage.getItem(cy);if("minimal"===e||"standard"===e||"dense"===e)return e;}catch{}return"minimal";}function ck(e,t){return void 0===e||0===e.length?[]:e.split(",").map(e=>e.trim()).filter(e=>t.includes(e));}function cN(e){return{types:ck(e.relType,lt),lifecycles:ck(e.relLifecycle,ln),activities:ck(e.relActivity,["inactive","queued","active","processing","completed","failed","blocked","degraded","high-throughput"]),srcKinds:ck(e.relSrcKind,n9),tgtKinds:ck(e.relTgtKind,n9)};}let cS={"high-throughput":0,processing:1,active:2,blocked:3,failed:4,degraded:5,queued:6,completed:7,inactive:8};function cC(e,t,n){var l;return null!=(l=n.get(e))?l:function(e){switch(e){case"blocked":return"blocked";case"stale":return"degraded";default:return"inactive";}}(t);}function cI(e){var t,n,l,r,s,o,c;let{filters:d,selectedId:u,onSelect:p,onFilterChange:m,activityMap:h=new Map(),throughputMap:f=new Map(),animateBadges:g=!0,highContrast:v=!1}=e,[b,x]=(0,i.useState)(()=>{let e=d.relDensity;return"minimal"===e||"standard"===e||"dense"===e?e:cj();}),[y,w]=(0,i.useState)(!1),[j,k]=(0,i.useState)([]),[N,S]=(0,i.useState)(!1),[C,I]=(0,i.useState)(null),[R,E]=(0,i.useState)(!1),$=(0,i.useRef)(null),A=(0,i.useRef)(null),[F,T]=(0,i.useState)(null!=(t=d.relType)?t:""),D=(0,i.useRef)(null),q=(0,i.useCallback)(e=>{x(e),m({relDensity:e});try{window.localStorage.setItem(cy,e);}catch{}},[m]);(0,i.useEffect)(()=>{let e=d.relDensity;"minimal"===e||"standard"===e||"dense"===e?x(e):x(cj());},[d.relDensity]),(0,i.useEffect)(()=>{var e;T(null!=(e=d.relType)?e:"");},[d.relType]);let M=(0,i.useCallback)(async()=>{I(null),S(!0);try{let e=cN(d),t=1===e.lifecycles.length?e.lifecycles[0]:"active",n=1===e.types.length?e.types[0]:void 0,l=1===e.srcKinds.length?e.srcKinds[0]:void 0,a=1===e.tgtKinds.length?e.tgtKinds[0]:void 0,i=await lu({lifecycle:t,type:n,sourceKind:l,targetKind:a,limit:cw[b]});k(i.entries),E(i.truncated);}catch(e){I(e instanceof lr?e.message:li);}finally{S(!1);}},[d,b]);(0,i.useEffect)(()=>{M();},[M]),(0,i.useEffect)(()=>{let e=$.current;if(null!==e)return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t);function t(e){if(!("u"<typeof document)&&null!==document.querySelector('[role="dialog"][aria-modal="true"]'))return;let t=e.target;if(!(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement||t instanceof HTMLElement&&t.isContentEditable)){if("f"===e.key||"F"===e.key)e.preventDefault(),w(e=>!e);else if("Escape"===e.key)w(!1);else if("/"===e.key){var n;e.preventDefault(),null==(n=A.current)||n.focus();}}}},[]);let P=(0,i.useCallback)(e=>{let t=e.target.value;T(t),null!==D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{m({relType:t.length>0?t:void 0});},250);},[m]),L=(0,i.useMemo)(()=>{var e;let t=cN(d),n=(null!=(e=d.relType)?e:"").split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0),l=0===n.length?j:j.filter(e=>n.some(t=>e.type.toLowerCase().includes(t)));return(0===t.activities.length?l:l.filter(e=>t.activities.includes(cC(e.id,e.lifecycle,h)))).slice(0,cw[b]);},[h,b,d,j]),z=L.slice(0,25),O=L.slice(25),K=O.length,B=K>0?function(e,t){let n=new Map();for(let a of e){var l;let e=cC(a.id,a.lifecycle,t);n.set(e,(null!=(l=n.get(e))?l:0)+1);}return Array.from(n.entries()).sort((e,t)=>{var n,l;return t[1]!==e[1]?t[1]-e[1]:(null!=(n=cS[e[0]])?n:Number.MAX_SAFE_INTEGER)-(null!=(l=cS[t[0]])?l:Number.MAX_SAFE_INTEGER);}).map(e=>{let t,[n,l]=e;return t=1===l?"relationship":"relationships","high-throughput"===n?`${l} high-throughput ${t}`:`${l} ${n} ${t}`;}).join(", ");}(O,h):"",W=R?`Showing first ${String(L.length)} relationships — more available.`:`Showing ${String(L.length)} relationship${1!==L.length?"s":""}.`,U=(null!=(n=d.relType)?n:"").trim().length>0||(null!=(l=d.relActivity)?l:"").trim().length>0||(null!=(r=d.relSrcKind)?r:"").trim().length>0||(null!=(s=d.relTgtKind)?s:"").trim().length>0||(null!=(o=d.relLifecycle)?o:"").trim().length>0&&"active"!==d.relLifecycle,_=ck(d.relLifecycle,ln),V=1===_.length&&null!=(c=_[0])?c:"active";return(0,a.jsxs)("div",{ref:$,className:"tw-pad","data-testid":"relationship-list-panel","data-relationship-focus":y?"true":void 0,children:[(0,a.jsxs)("div",{role:"group","aria-label":"Relationship density",style:{display:"flex",flexWrap:"wrap",gap:"var(--space-2)",marginBottom:8},children:[["minimal","standard","dense"].map(e=>(0,a.jsx)("button",{type:"button",className:"arun-btn","aria-pressed":b===e,onClick:()=>q(e),style:{textTransform:"capitalize",minWidth:24,minHeight:24},children:e},e)),(0,a.jsx)("button",{type:"button",className:"arun-btn","aria-pressed":y,onClick:()=>w(e=>!e),title:"Toggle focus mode (F)","aria-label":`Focus mode: ${y?"on":"off"}`,style:{minWidth:24,minHeight:24},children:"Focus"})]}),(0,a.jsxs)("div",{style:{marginBottom:8},children:[(0,a.jsx)("label",{htmlFor:"rel-type-filter",className:"rb-row-k",style:{display:"block",marginBottom:2,fontSize:11,fontWeight:600},children:"Filter by type (press / to focus)"}),(0,a.jsx)("input",{id:"rel-type-filter",ref:A,type:"text",list:"rel-type-filter-options",value:F,onChange:P,placeholder:"e.g. reads-context","aria-label":"Filter relationships by type",style:{width:"100%",background:"var(--inset)",border:"1px solid var(--line)",borderRadius:9,padding:"4px 8px",minHeight:24,color:"var(--fg)",fontSize:13}}),(0,a.jsx)("datalist",{id:"rel-type-filter-options",children:lt.map(e=>(0,a.jsx)("option",{value:e},e))})]}),(0,a.jsxs)("div",{style:{marginBottom:8},children:[(0,a.jsx)("label",{htmlFor:"rel-lifecycle-filter",className:"rb-row-k",style:{display:"block",marginBottom:2,fontSize:11,fontWeight:600},children:"Lifecycle"}),(0,a.jsx)("select",{id:"rel-lifecycle-filter",value:V,onChange:e=>m({relLifecycle:e.target.value}),"aria-label":"Filter relationships by lifecycle",style:{width:"100%",background:"var(--inset)",border:"1px solid var(--line)",borderRadius:9,padding:"4px 8px",minHeight:24,color:"var(--fg)",fontSize:13},children:ln.map(e=>(0,a.jsx)("option",{value:e,children:e},e))})]}),(0,a.jsx)("div",{"aria-live":"polite","aria-atomic":"true",className:"visually-hidden",children:W}),R&&(0,a.jsx)("div",{"data-testid":"list-truncation-note",style:{fontSize:11,color:"var(--fg-muted)",marginBottom:6},children:W}),null!==C&&(0,a.jsxs)("div",{className:"lk-alert",role:"alert","aria-live":"assertive",children:[(0,a.jsx)("span",{children:C}),(0,a.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>void M(),children:"Retry"})]}),N&&0===j.length&&(0,a.jsx)("div",{role:"status",className:"insp-empty",children:"Loading…"}),(!N||j.length>0)&&null===C&&0===L.length&&(0,a.jsx)("div",{className:"insp-empty","data-testid":"list-empty",children:U?"No relationships match the current filter.":'No active relationships yet. Create one with "+ New relationship", or connect a source — connections appear here automatically.'}),L.length>0&&(0,a.jsxs)("div",{role:"list","aria-label":"Relationships","aria-busy":N||void 0,style:{display:"flex",flexDirection:"column",gap:"var(--space-1)",opacity:N?.6:1,transition:"opacity 0.15s ease"},children:[z.map(e=>{var t;let n=e.id===u,l=cC(e.id,e.lifecycle,h),i=y&&n,r=y&&!n;return(0,a.jsx)("div",{role:"listitem",style:{opacity:r?.4:1},children:(0,a.jsxs)("button",{type:"button","aria-pressed":n,"aria-label":`${e.type} relationship from ${e.source.kind} ${e.source.id} to ${e.target.kind} ${e.target.id}, lifecycle: ${e.lifecycle}`,title:`${e.source.id} → ${e.target.id}`,onClick:()=>p(e.id),onKeyDown:t=>{var n;return n=e.id,void(("Enter"===t.key||" "===t.key)&&(t.preventDefault(),p(n)));},"data-incident":i?"true":void 0,className:"rel-row",children:[(0,a.jsx)(cx,{type:e.type,lifecycle:e.lifecycle,activity:l,throughputCount:f.get(e.id),animateOverride:g,highContrast:v}),(0,a.jsxs)("span",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column"},children:[(0,a.jsxs)("span",{style:{fontSize:12,color:"var(--fg)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.source.kind," → ",e.target.kind]}),(0,a.jsx)("span",{style:{fontSize:10.5,color:"var(--fg-muted)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:null!=(t=e.summary)?t:`${e.source.id} → ${e.target.id}`})]}),(0,a.jsx)("span",{style:{fontSize:11,color:"var(--fg-muted)",whiteSpace:"nowrap"},children:e.lifecycle})]})},e.id);}),K>0&&(0,a.jsxs)("div",{role:"listitem","aria-live":"polite",style:{fontSize:12,color:"var(--fg-muted)",padding:"4px 6px"},"data-testid":"animation-cap-aggregate",children:["+",String(K)," more: ",B]})]})]});}function cR(){return(0,a.jsx)("p",{role:"note",style:{margin:"4px 0 0",fontSize:11,color:"var(--fg-muted)",borderLeft:"2px solid var(--warn)",paddingLeft:8},children:"The walk hit a bound before the graph was fully traversed; more objects may be affected than shown."});}function cE(e){let{title:t,help:n,report:l,onSelectRelationship:i}=e;if(null===l)return(0,a.jsxs)("section",{style:{marginBottom:12},children:[(0,a.jsx)("div",{className:"rb-section-label",role:"heading","aria-level":4,children:t}),(0,a.jsx)("p",{style:{fontSize:12,color:"var(--fg-muted)",margin:0},children:"Loading…"})]});let r=l.endpoints.slice(1),s=l.relationships,o=r.slice(0,50),c=s.slice(0,50);return(0,a.jsxs)("section",{style:{marginBottom:12},"aria-label":t,children:[(0,a.jsxs)("div",{className:"rb-section-label",role:"heading","aria-level":4,children:[t,(0,a.jsx)("span",{className:"rb-count","aria-hidden":"true",children:r.length})]}),(0,a.jsx)("p",{style:{margin:"0 0 6px",fontSize:11,color:"var(--fg-muted)"},children:n}),0===r.length?(0,a.jsx)("p",{style:{fontSize:12,color:"var(--fg-muted)",margin:0},children:"No further objects are affected in this direction."}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("ul",{style:{listStyle:"none",margin:0,padding:0},children:o.map(e=>(0,a.jsx)("li",{className:"rb-row",style:{fontSize:12},children:(0,a.jsx)("span",{className:"mono",children:`${e.kind}: ${e.id}`})},`${e.kind}:${e.id}`))}),r.length>o.length&&(0,a.jsxs)("p",{role:"note",style:{margin:"4px 0 0",fontSize:11,color:"var(--fg-muted)"},children:["Showing the first ",String(50)," of ",String(r.length)," ","objects."]}),s.length>0&&(0,a.jsxs)("details",{style:{marginTop:6},children:[(0,a.jsxs)("summary",{style:{fontSize:11,color:"var(--fg-muted)",cursor:"pointer"},children:[String(s.length)," relationship",1===s.length?"":"s"," on the path"]}),(0,a.jsx)("ul",{style:{listStyle:"none",margin:"4px 0 0",padding:0},children:c.map(e=>(0,a.jsx)("li",{style:{marginBottom:2},children:(0,a.jsxs)("button",{type:"button",className:"arun-btn ghost",onClick:()=>i(e.id),"aria-label":`Inspect ${e.type} relationship from ${e.source.kind} ${e.source.id} to ${e.target.kind} ${e.target.id}`,style:{display:"flex",width:"100%",gap:"var(--space-3)",alignItems:"center",textAlign:"left",fontSize:12},children:[(0,a.jsx)("span",{className:"mono",children:e.type}),(0,a.jsxs)("span",{style:{color:"var(--fg-muted)"},children:[e.source.id," → ",e.target.id]})]})},e.id))})]})]}),l.truncated&&(0,a.jsx)(cR,{})]});}function c$(e){let{outgoing:t,incoming:n,onSelectRelationship:l}=e;return(0,a.jsxs)("div",{style:{marginTop:8,padding:"8px 10px",border:"1px solid var(--line)",borderRadius:8,background:"var(--inset)"},"aria-label":"Bounded impact analysis",children:[(0,a.jsx)(cE,{title:"Downstream impact",help:"Objects this relationship's target leads to. Deleting or revoking here may affect them.",report:t,onSelectRelationship:l}),(0,a.jsx)(cE,{title:"Upstream impact",help:"Objects that depend on this relationship's source.",report:n,onSelectRelationship:l})]});}let cA={draft:{bg:"var(--inset)",fg:"var(--fg-muted)"},active:{bg:"var(--accent-dim)",fg:"var(--accent)"},archived:{bg:"var(--inset)",fg:"var(--fg-dim)"},superseded:{bg:"var(--inset)",fg:"var(--fg-dim)"},revoked:{bg:"color-mix(in oklch, var(--danger) 14%, var(--card))",fg:"var(--danger)"},blocked:{bg:"color-mix(in oklch, var(--warn) 12%, var(--card))",fg:"var(--warn)"},stale:{bg:"var(--inset)",fg:"var(--fg-faint)"}},cF={draft:"Proposed but not yet validated or awaiting an upstream gate.",active:"Validated and committed. Both endpoints are currently live.",archived:"Preserved for audit but no longer participates in queries by default.",superseded:"Replaced by a newer relationship of the same type.",revoked:"Rejected after proposal or retracted after acceptance. Terminal state.",blocked:"Cannot transition to active because the validator returned a denial reason.",stale:"At least one endpoint is tombstoned, retired, or unavailable."};function cT(e){let{lines:t=3}=e;return(0,a.jsx)("div",{className:"rb-rows","aria-hidden":"true",children:Array.from({length:t},(e,t)=>(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",style:{background:"var(--inset)",borderRadius:3,width:"40%",display:"block",height:12}}),(0,a.jsx)("span",{className:"rb-row-v",style:{background:"var(--inset)",borderRadius:3,width:"55%",display:"block",height:12}})]},t))});}function cD(e){let{children:t,style:n}=e;return(0,a.jsx)("div",{className:"rb-section-label",role:"heading","aria-level":3,style:n,children:t});}function cq(e){let{rel:t}=e,n=ll[t.type],l=`${t.source.kind} ${t.type} ${t.target.kind}`;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"insp-top",children:[(0,a.jsx)("span",{className:"chip",style:{fontSize:11},children:t.type}),(0,a.jsx)("span",{className:"insp-title",children:l})]}),(0,a.jsxs)("div",{className:"rb-rows",children:[(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",children:"Semantics"}),(0,a.jsx)("span",{className:"rb-row-v",children:n.semantics})]}),(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",children:"Cardinality"}),(0,a.jsx)("span",{className:"rb-row-v mono",children:n.cardinality})]})]})]});}function cM(e){let{label:t,kind:n,id:l}=e;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(cD,{children:[t," endpoint"]}),(0,a.jsxs)("div",{className:"rb-rows",children:[(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",children:"Kind"}),(0,a.jsx)("span",{className:"rb-row-v mono",children:n})]}),(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",children:"Reference"}),(0,a.jsx)("span",{className:"rb-row-v mono","aria-label":`Reference id: ${l}`,children:l})]})]})]});}function cP(e){var t;let{lifecycle:n}=e,l=`lifecycle-desc-${n}`,i=null!=(t=cA[n])?t:cA.draft;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(cD,{children:"Lifecycle status"}),(0,a.jsxs)("div",{className:"rb-rows",children:[(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",children:"State"}),(0,a.jsx)("span",{className:"rb-row-v",children:(0,a.jsx)("span",{className:"chip",style:{background:i.bg,color:i.fg},"aria-describedby":l,children:n})})]}),(0,a.jsx)("div",{className:"rb-row",children:(0,a.jsx)("span",{id:l,className:"rb-row-v",style:{color:"var(--fg-muted)",fontSize:12},children:cF[n]})})]})]});}function cL(e){let{type:t,lifecycle:n,activity:l,throughputCount:i,animateBadges:r,highContrast:s,transitions:o,densityMode:c}=e,d=o.slice(0,"minimal"===c?3:5);return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(cD,{children:"Activity"}),(0,a.jsxs)("div",{className:"rb-rows",children:[(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",children:"Current state"}),(0,a.jsx)("span",{className:"rb-row-v",children:(0,a.jsx)(cx,{type:t,lifecycle:n,activity:l,throughputCount:i,animateOverride:r,highContrast:s})})]}),d.length>0&&(0,a.jsxs)("div",{className:"rb-row",style:{flexDirection:"column",gap:"var(--space-2)",alignItems:"flex-start"},children:[(0,a.jsx)("span",{className:"rb-row-k",style:{marginBottom:4},children:"Recent transitions"}),d.map((e,t)=>(0,a.jsxs)("div",{style:{fontSize:12,color:"var(--fg-muted)",display:"flex",gap:"var(--space-4)"},children:[(0,a.jsxs)("span",{className:"mono",children:[e.from," → ",e.to]}),(0,a.jsx)("time",{dateTime:new Date(e.occurredAt).toISOString(),style:{color:"var(--fg-faint)"},children:new Date(e.occurredAt).toLocaleString()})]},t))]})]})]});}function cz(){return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(cD,{children:"Authority status"}),(0,a.jsx)("div",{className:"rb-rows",children:(0,a.jsx)("div",{className:"rb-row","data-testid":"authority-disclaimer",children:(0,a.jsx)("span",{className:"rb-row-v",style:{color:"var(--fg-muted)",fontStyle:"italic"},children:"Relationship: governance only. No model/tool/file/workflow authority granted."})})})]});}function cO(e){let{auditRows:t,loading:n,error:l,onRetry:i,onLoadMore:r,hasMore:s}=e;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(cD,{children:"Audit history"}),n&&(0,a.jsx)(cT,{lines:3}),null!==l&&(0,a.jsxs)("div",{className:"lk-alert",role:"alert","aria-live":"assertive",children:[(0,a.jsx)("span",{children:l}),(0,a.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:i,children:"Retry"})]}),!n&&null===l&&0===t.length&&(0,a.jsx)("div",{className:"rb-rows",children:(0,a.jsx)("div",{className:"rb-row",children:(0,a.jsx)("span",{className:"rb-row-v",style:{color:"var(--fg-muted)"},children:"No audit events for this relationship yet."})})}),!n&&t.length>0&&(0,a.jsxs)("div",{className:"rb-rows",children:[t.map((e,t)=>(0,a.jsxs)("div",{className:"rb-row",style:{flexDirection:"column",alignItems:"flex-start",gap:"var(--space-1)"},children:[(0,a.jsxs)("span",{className:"rb-row-k mono",style:{fontSize:11},children:[e.from," → ",e.to]}),(0,a.jsx)("time",{dateTime:new Date(e.occurredAt).toISOString(),style:{color:"var(--fg-faint)",fontSize:11},children:new Date(e.occurredAt).toLocaleString()})]},t)),s&&(0,a.jsx)("div",{className:"rb-row",children:(0,a.jsx)("button",{type:"button",className:"rb-row-v",style:{color:"var(--accent)",fontSize:12,background:"none",border:"none",padding:0,cursor:"pointer",minHeight:24,minWidth:24},onClick:r,"aria-label":"Load more audit events",children:"Load more"})})]})]});}function cK(e){let t,{rel:n}=e,l=(t=[],"evidence-run"===n.source.kind&&t.push(n.source.id),"evidence-run"===n.target.kind&&t.push(n.target.id),t);return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(cD,{children:"Evidence references"}),0===l.length?(0,a.jsx)("p",{style:{fontSize:12,color:"var(--fg-muted)",margin:"0 0 4px"},"data-testid":"evidence-empty",children:"No evidence references for this relationship."}):(0,a.jsx)("div",{className:"rb-rows",children:l.map(e=>(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",children:"Evidence run"}),(0,a.jsx)("span",{className:"rb-row-v mono","aria-label":`Evidence run reference ${e}`,title:e,children:e})]},e))})]});}function cB(e){let{relationshipId:t,forwardCount:n,reverseCount:l,outgoing:i,incoming:r,expanded:s,onToggle:o,onSelectRelationship:c}=e;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(cD,{children:"Impact summary"}),(0,a.jsxs)("div",{className:"rb-rows",children:[(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",children:"Forward dependencies"}),(0,a.jsx)("span",{className:"rb-row-v mono",children:null===n?"—":String(n)})]}),(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",children:"Reverse dependencies"}),(0,a.jsx)("span",{className:"rb-row-v mono",children:null===l?"—":String(l)})]}),(0,a.jsx)("div",{className:"rb-row",children:(0,a.jsx)("button",{type:"button",className:"arun-btn",onClick:o,"aria-expanded":s,"aria-controls":"rb-impact-detail","aria-label":s?`Hide impact for relationship ${t}`:`View impact for relationship ${t}`,"data-testid":"view-impact-btn",children:s?"Hide impact":"View impact"})})]}),s&&(0,a.jsx)("div",{id:"rb-impact-detail",children:(0,a.jsx)(c$,{outgoing:i,incoming:r,onSelectRelationship:c})})]});}function cW(e){let{codes:t,messages:n,deniedAt:l}=e;return 0===t.length?null:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(cD,{children:"Denial reason"}),(0,a.jsxs)("div",{className:"lk-alert",role:"status","aria-live":"polite","data-testid":"denial-section",children:[t.map((e,l)=>{var i;return(0,a.jsxs)("div",{style:{marginBottom:8*(l<t.length-1)},children:[(0,a.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--fg-muted)",marginBottom:2},children:e}),(0,a.jsx)("div",{style:{fontSize:13,color:"var(--fg)"},children:null!=(i=n[l])?i:e})]},e);}),void 0!==l&&(0,a.jsxs)("div",{style:{fontSize:11,color:"var(--fg-faint)",marginTop:6},children:["Denied at ",(0,a.jsx)("time",{dateTime:l,children:l})]})]})]});}function cU(e){return null==e||0===e.length?null:{codes:e.map(e=>e.code),messages:e.map(e=>e.message)};}function c_(e){let{rel:t,onReconnect:n,onArchive:l,onRevoke:i,onViewImpact:r,onViewEvidence:s,mutating:o}=e,c=t.lifecycle,d="blocked"===c,u="active"===c,p="active"===c||"blocked"===c||"archived"===c,m="active"===c;return(0,a.jsxs)("div",{style:{display:"flex",gap:"var(--space-3)",flexWrap:"wrap",marginTop:8},children:[(0,a.jsx)("button",{type:"button",className:`arun-btn${d?" primary":""}`,"aria-disabled":!d||o,"aria-label":"Reconnect — only available for blocked relationships",title:d?"Reconnect this relationship":"Only blocked relationships can be reconnected.",disabled:!d||o,onClick:d?n:void 0,children:"Reconnect"}),(0,a.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":!u||o,"aria-label":"Archive — only available for active relationships",title:u?"Archive this relationship":"Only active relationships can be archived.",disabled:!u||o,onClick:u?l:void 0,children:"Archive"}),(0,a.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":!p||o,"aria-label":"Revoke relationship",title:p?"Revoke this relationship":"Already revoked or superseded.",disabled:!p||o,onClick:p?i:void 0,style:{color:p?"var(--danger)":void 0},children:"Revoke"}),(0,a.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":!m,"aria-label":"View impact analysis",title:m?"Toggle the impact analysis card":"Impact analysis is unavailable in this state.",disabled:!m,onClick:m?r:void 0,children:"View impact"}),(0,a.jsx)("button",{type:"button",className:"arun-btn","aria-label":"View evidence references",title:"Jump to the evidence references section",onClick:s,children:"View evidence"})]});}function cV(e){var t,n,l;let{relationshipId:r,densityMode:s="minimal",onClearFocus:o,onViewImpact:c,activityMap:d=new Map(),throughputMap:u=new Map(),animateBadges:p=!0,highContrast:m=!1}=e,[h,f]=(0,i.useState)(null),[g,v]=(0,i.useState)(null),[b,x]=(0,i.useState)(!1),[y,w]=(0,i.useState)(null),[j,k]=(0,i.useState)(!1),[N,S]=(0,i.useState)(null),[C,I]=(0,i.useState)(null),[R,E]=(0,i.useState)(null),[$,A]=(0,i.useState)(null),[F,T]=(0,i.useState)(!1),D=null===R?null:R.relationships.length,q=null===$?null:$.relationships.length,[M,P]=(0,i.useState)(!1),L=(0,i.useRef)(null),z=(0,i.useRef)(0),O=(0,i.useCallback)(async e=>{let t=++z.current;w(null),x(!0),I(null),E(null),A(null),T(!1);let n=setTimeout(()=>{z.current===t&&P(!0);},500);L.current=n;try{let[n,l]=await Promise.all([lp(e),lg(e)]);if(z.current!==t)return;f(n),v(l);try{let[n,l]=await Promise.all([lf(e,{direction:"outgoing",maxDepth:3,maxRelationships:512}),lf(e,{direction:"incoming",maxDepth:3,maxRelationships:512})]);if(z.current!==t)return;E(n),A(l);}catch{}}catch(e){if(z.current!==t)return;w(e instanceof lr?e.message:li);}finally{L.current===n?(clearTimeout(n),L.current=null):clearTimeout(n),z.current===t&&(x(!1),P(!1));}},[]);(0,i.useEffect)(()=>{if(null===r){z.current+=1,null!==L.current&&(clearTimeout(L.current),L.current=null),f(null),v(null),w(null),I(null),P(!1),x(!1);return;}return O(r),()=>{null!==L.current&&(clearTimeout(L.current),L.current=null);};},[r,O]);let K=(0,i.useCallback)(async e=>{if(null!==h){k(!0),S(null),I(null);try{let t=crypto.randomUUID(),{relationship:n}=await lm(h.id,{transition:{to:e}},String(h.etag),t);f(n),v(null),await O(h.id);}catch(e){S(e instanceof lr?e.message:"Mutation failed. Please retry."),I(e instanceof lr?cU(e.reasons):null);}finally{k(!1);}}},[h,O]),B=(0,i.useCallback)(()=>void K("draft"),[K]),W=(0,i.useCallback)(()=>void K("archived"),[K]),U=(0,i.useCallback)(async()=>{if(null!==h&&window.confirm(`Revoke relationship "${h.type}"? This cannot be undone.`)){k(!0),S(null),I(null);try{let e=crypto.randomUUID(),t=await lh(h.id,String(h.etag),e);f(t);}catch(e){S(e instanceof lr?e.message:"Revoke failed. Please retry."),I(e instanceof lr?cU(e.reasons):null);}finally{k(!1);}}},[h]),_=(0,i.useCallback)(()=>{T(e=>!e);},[]),V=(0,i.useCallback)(e=>{null==c||c(e);},[c]),H=(0,i.useRef)(null),J=(0,i.useCallback)(()=>{var e,t;null==(t=H.current)||null==(e=t.scrollIntoView)||e.call(t,{block:"start"});},[]);if(null===r)return(0,a.jsxs)("div",{className:"tw-pad","data-testid":"relationship-inspector-panel",children:[(0,a.jsx)(cD,{style:{marginTop:0},children:"Relationship"}),(0,a.jsx)("div",{className:"insp-empty","data-testid":"inspector-empty",children:"Select a relationship from the list to inspect it."}),(0,a.jsx)("div",{style:{fontSize:12,color:"var(--fg-muted)",marginTop:4},children:"If the list is empty, use “+ New relationship” in the toolbar to create one."})]});let Y=cU(null==g?void 0:g.decision.reasons),X=null!=Y?Y:C,G=null!==X&&((null==h?void 0:h.lifecycle)==="blocked"||(null==h?void 0:h.lifecycle)==="revoked"||null!==C),Q=null!==h?null!=(t=d.get(h.id))?t:function(e){switch(e){case"blocked":return"blocked";case"stale":return"degraded";default:return"inactive";}}(h.lifecycle):"inactive",Z=null!==h?u.get(h.id):void 0;return(0,a.jsxs)("div",{className:"tw-pad","aria-busy":b,"data-testid":"relationship-inspector-panel",children:[null!==y&&(0,a.jsxs)("div",{className:"lk-alert",role:"alert","aria-live":"assertive",children:[(0,a.jsx)("span",{children:y}),(0,a.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>void O(r),children:"Retry"})]}),null!==N&&(0,a.jsxs)("div",{className:"lk-alert",role:"alert","aria-live":"assertive",children:[(0,a.jsx)("span",{children:N}),(0,a.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>S(null),children:"Dismiss"})]}),b&&M&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(cD,{style:{marginTop:0},children:"Relationship"}),(0,a.jsx)(cT,{lines:4}),(0,a.jsx)(cT,{lines:3})]}),!b&&null===y&&null===h&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(cD,{style:{marginTop:0},children:"Relationship"}),(0,a.jsx)("div",{className:"insp-empty","data-testid":"inspector-not-found",children:"This relationship is no longer available."}),(0,a.jsx)("div",{style:{fontSize:12,color:"var(--fg-muted)",marginTop:4},children:"It may have been deleted, retired by retention, or it never existed in this workspace."}),void 0!==o&&(0,a.jsx)("button",{type:"button",className:"arun-btn",style:{marginTop:8},onClick:o,children:"Clear focus"})]}),!b&&null!==h&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(cD,{style:{marginTop:0},children:"Relationship"}),(0,a.jsx)(cq,{rel:h}),(0,a.jsx)(cM,{label:"Source",kind:h.source.kind,id:h.source.id}),(0,a.jsx)(cM,{label:"Target",kind:h.target.kind,id:h.target.id}),(0,a.jsx)(cP,{lifecycle:h.lifecycle}),(0,a.jsx)(cL,{type:h.type,lifecycle:h.lifecycle,activity:Q,throughputCount:Z,animateBadges:p,highContrast:m,transitions:null!=(n=null==g?void 0:g.lifecycle)?n:[],densityMode:s}),(0,a.jsx)(cz,{}),(0,a.jsx)(cO,{auditRows:null!=(l=null==g?void 0:g.lifecycle)?l:[],loading:!1,error:null,onRetry:()=>void O(r),onLoadMore:()=>{},hasMore:!1}),(0,a.jsx)("div",{ref:H,children:(0,a.jsx)(cK,{rel:h})}),(0,a.jsx)(cB,{relationshipId:h.id,forwardCount:D,reverseCount:q,outgoing:R,incoming:$,expanded:F,onToggle:_,onSelectRelationship:V}),G&&null!==X&&(0,a.jsx)(cW,{codes:X.codes,messages:X.messages}),(0,a.jsx)(c_,{rel:h,onReconnect:B,onArchive:W,onRevoke:()=>void U(),onViewImpact:_,onViewEvidence:J,mutating:j})]})]});}let cH=new Set(["kind","id","state","timestamp","count"]);function cJ(e){return`${e.kind}: ${e.id}`;}function cY(e){let{category:t}=e;return(0,a.jsxs)("p",{role:"note",style:{margin:"4px 0 0",fontSize:11,color:"var(--fg-muted)",borderLeft:"2px solid var(--warn)",paddingLeft:8},children:["More ",t," exist than the bounded query returned. Resolve the listed items, then re-run the health check."]});}function cX(e){let{category:t,onSelectRelationship:n}=e;if(0===t.items.length)return null;let l=t.items.slice(0,50),i=t.items.length-l.length;return(0,a.jsxs)("section",{"aria-label":`${t.label} (${String(t.items.length)})`,style:{marginBottom:14},children:[(0,a.jsxs)("div",{className:"rb-section-label",role:"heading","aria-level":3,children:[t.label,(0,a.jsx)("span",{className:"rb-count","aria-hidden":"true",children:t.items.length})]}),(0,a.jsx)("p",{style:{margin:"0 0 6px",fontSize:11,color:"var(--fg-muted)"},children:t.help}),(0,a.jsx)("ul",{style:{listStyle:"none",margin:0,padding:0},children:l.map(e=>(0,a.jsx)("li",{style:{marginBottom:2},children:(0,a.jsxs)("button",{type:"button",className:"arun-btn ghost",onClick:()=>n(e.id),"aria-label":`Inspect ${e.type} relationship from ${cJ(e.source)} to ${cJ(e.target)}, lifecycle ${e.lifecycle}`,style:{display:"flex",width:"100%",gap:6,alignItems:"center",textAlign:"left",fontSize:12},children:[(0,a.jsx)("span",{className:"mono",style:{color:"var(--fg)"},children:e.type}),(0,a.jsxs)("span",{style:{color:"var(--fg-muted)"},children:[cJ(e.source)," → ",cJ(e.target)]}),(0,a.jsx)("span",{className:"mono",style:{marginLeft:"auto",color:"var(--fg-muted)"},children:e.lifecycle})]})},e.id))}),i>0&&(0,a.jsxs)("p",{role:"note",style:{margin:"4px 0 0",fontSize:11,color:"var(--fg-muted)"},children:["Showing the first ",String(50)," of ",String(t.items.length),"."]}),t.truncated&&(0,a.jsx)(cY,{category:t.label.toLowerCase()})]});}function cG(e){let{findings:t}=e;if(0===t.orphanedEndpoints.length)return null;let n=t.orphanedEndpoints.slice(0,50);return(0,a.jsxs)("section",{"aria-label":`Orphaned endpoints (${String(t.orphanedEndpoints.length)})`,style:{marginBottom:14},children:[(0,a.jsxs)("div",{className:"rb-section-label",role:"heading","aria-level":3,children:["Orphaned endpoints",(0,a.jsx)("span",{className:"rb-count","aria-hidden":"true",children:t.orphanedEndpoints.length})]}),(0,a.jsx)("p",{style:{margin:"0 0 6px",fontSize:11,color:"var(--fg-muted)"},children:"Endpoints that participate in no live relationship."}),(0,a.jsx)("ul",{style:{listStyle:"none",margin:0,padding:0},children:n.map(e=>(0,a.jsx)("li",{className:"rb-row",style:{fontSize:12},children:(0,a.jsx)("span",{className:"mono",children:cJ(e)})},`${e.kind}:${e.id}`))}),t.orphanedEndpointsTruncated&&(0,a.jsx)(cY,{category:"orphaned endpoints"})]});}function cQ(e){var t,n;let{onSelectRelationship:l}=e,[r,s]=(0,i.useState)(null),[o,c]=(0,i.useState)(!0),[d,u]=(0,i.useState)(null),p=(0,i.useCallback)(async()=>{c(!0),u(null);try{let e=await lv();s(e);}catch(e){u(e instanceof lr?e.message:"Could not load the graph health check.");}finally{c(!1);}},[]);return(0,i.useEffect)(()=>{p();},[p]),(0,a.jsxs)("div",{style:{padding:12,height:"100%",overflowY:"auto"},"aria-busy":o,children:[(0,a.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[(0,a.jsx)("h2",{style:{margin:0,fontSize:13,fontWeight:600,color:"var(--fg)",flexGrow:1},children:"Graph health"}),(0,a.jsx)("button",{type:"button",className:"arun-btn",onClick:()=>void p(),"aria-label":"Re-run the graph health check",style:{minHeight:24},children:"Refresh"})]}),o&&(0,a.jsx)("p",{style:{fontSize:12,color:"var(--fg-muted)"},"aria-live":"polite",children:"Running health check…"}),null!==d&&(0,a.jsxs)("div",{className:"lk-alert",role:"alert",children:[d,(0,a.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>void p(),children:"Retry"})]}),!o&&null===d&&null!==r&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("p",{style:{fontSize:11,color:"var(--fg-faint)",margin:"0 0 10px"},children:["Checked at"," ",(0,a.jsx)("time",{dateTime:new Date(r.checkedAt).toISOString(),children:new Date(r.checkedAt).toLocaleString()}),"."]}),(0,a.jsx)("div",{className:"rb-rows",style:{marginBottom:14},children:ln.filter(e=>{var t;return(null!=(t=r.totals[e])?t:0)>0;}).map(e=>{var t;return(0,a.jsxs)("div",{className:"rb-row",children:[(0,a.jsx)("span",{className:"rb-row-k",children:e}),(0,a.jsx)("span",{className:"rb-row-v mono",children:String(null!=(t=r.totals[e])?t:0)})]},e);})}),0===(t=r.findings).orphanedEndpoints.length+t.staleRelationships.length+t.blockedRelationships.length+t.failedRelationships.length+t.invalidReferences.length+t.cycleParticipants.length?(0,a.jsxs)("div",{className:"lk-empty",children:[(0,a.jsx)("p",{className:"lk-empty-title",children:"Healthy"}),(0,a.jsx)("p",{className:"lk-empty-body",children:"No relationship-graph defects were found."})]}):(0,a.jsxs)(a.Fragment,{children:[[{key:"invalid",label:"Invalid references",help:"An endpoint no longer resolves to a live workspace object.",items:(n=r.findings).invalidReferences,truncated:n.invalidReferencesTruncated},{key:"blocked",label:"Blocked",help:"A policy or endpoint state is blocking this relationship.",items:n.blockedRelationships,truncated:n.blockedRelationshipsTruncated},{key:"failed",label:"Failed (revoked)",help:"The relationship reached the revoked terminal state.",items:n.failedRelationships,truncated:n.failedRelationshipsTruncated},{key:"cycle",label:"Cycle participants",help:"These relationships take part in a dependency cycle.",items:n.cycleParticipants,truncated:n.cycleScanTruncated},{key:"stale",label:"Stale",help:"A health check flagged at least one endpoint as not currently live.",items:n.staleRelationships,truncated:n.staleRelationshipsTruncated}].map(e=>(0,a.jsx)(cX,{category:e,onSelectRelationship:l},e.key)),(0,a.jsx)(cG,{findings:r.findings})]})]})]});}let cZ={draft:["draft","active","archived","superseded","revoked","blocked","stale"],active:["active","archived","superseded","revoked","stale"],archived:["archived","superseded","revoked","stale"],superseded:["superseded","stale"],revoked:["revoked"],blocked:["blocked","draft","active","archived","revoked","stale"],stale:["stale","active","archived","superseded","revoked"]};function c0(e){return"object"==typeof e&&null!==e&&!Array.isArray(e);}function c1(e){return"string"==typeof e&&e.length>0;}function c2(e,t,n){return void 0===n?{code:e,message:t}:{code:e,field:n,message:t};}function c3(e,t,n){return c0(e)?c1(e.kind)?c1(e.id)?!!c1(e.workspaceId)||(n.push(c2("denied/schema-version-unsupported",`${t}.workspaceId must be a non-empty string`,`${t}.workspaceId`)),!1):(n.push(c2("denied/schema-version-unsupported",`${t}.id must be a non-empty string`,`${t}.id`)),!1):(n.push(c2("denied/schema-version-unsupported",`${t}.kind must be a non-empty string`,`${t}.kind`)),!1):(n.push(c2("denied/schema-version-unsupported",`${t} must be an object`,t)),!1);}function c4(e,t,n){c1(e[t])||n.push(c2("denied/schema-version-unsupported",`${t} must be a non-empty string`,t));}function c6(e,t){let n=e.kind;return n9.includes(n)?null:c2("denied/schema-version-unsupported",`${t}.kind is not a known object kind`,`${t}.kind`);}function c5(e,t,n){"missing"===t?n.push(c2("source"===e?"denied/non-existent-source":"denied/non-existent-target",`${e} endpoint does not exist`,e)):"tombstoned"===t?n.push(c2("denied/endpoint-tombstoned",`${e} endpoint has been tombstoned`,e)):"retired"===t?n.push(c2("denied/endpoint-retired",`${e} endpoint has been retired`,e)):"unavailable"===t&&n.push(c2("denied/endpoint-unavailable",`${e} endpoint is unavailable`,e));}function c8(e,t){let n=e.kind;return le.includes(n)?null:c2("denied/object-kind-not-yet-supported",`${t}.kind "${n}" is reserved for a future release`,`${t}.kind`);}function c7(){return{type:"reads-context",sourceKind:"workflow-run",sourceId:"",targetKind:"memory",targetId:"",summary:""};}let c9=new Set(["denied/path-not-contained","denied/cross-workspace","denied/payload-content-not-permitted"]);function de(e){return(null==e?void 0:e.codes.some(e=>c9.has(e)))===!0;}function dt(e){let{onClose:t}=e,[n,l]=(0,i.useState)(c7),[r,s]=(0,i.useState)([]),[o,c]=(0,i.useState)(null),[d,u]=(0,i.useState)(!1),[p,m]=(0,i.useState)(!1),h=(0,i.useRef)(null),f="rel-create-dialog-title",g="rel-create-dialog-desc",v=(0,i.useCallback)(e=>{let t=h.current;if(null===t)return;let n=Array.from(t.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')).filter(e=>!e.hasAttribute("disabled")),l=n[0],a=n[n.length-1];"Tab"===e.key&&(e.shiftKey?document.activeElement===l&&(e.preventDefault(),null==a||a.focus()):document.activeElement===a&&(e.preventDefault(),null==l||l.focus()));},[]),b=(0,i.useCallback)(e=>{"Escape"===e.key&&t(null);},[t]);(0,i.useEffect)(()=>{let e=h.current;if(null!==e)return e.addEventListener("keydown",v),e.addEventListener("keydown",b),()=>{e.removeEventListener("keydown",v),e.removeEventListener("keydown",b);};},[v,b]),(0,i.useEffect)(()=>{if(0===n.sourceId.length||0===n.targetId.length)return void s([]);let e=function(e){let t=function(e){var t;if(!c0(e))return{errors:[c2("denied/schema-version-unsupported","relationship must be an object")]};let n=[];c4(e,"id",n),c4(e,"workspaceId",n),c4(e,"createdAt",n),c4(e,"updatedAt",n),(!("number"==typeof(t=e.etag)&&Number.isInteger(t)&&Number.isFinite(t))||e.etag<0)&&n.push(c2("denied/schema-version-unsupported","etag must be a non-negative finite integer","etag"));let l=c3(e.source,"source",n),a=c3(e.target,"target",n);return!(n.length>0)&&l&&a?{errors:[],value:{record:e,source:e.source,target:e.target}}:{errors:n};}(e);if(!t.value)return{ok:!1,errors:t.errors};let{record:n,source:l,target:a}=t.value,i=function(e,t,n){let l,a,i="1"!==e.schemaVersion?c2("denied/schema-version-unsupported",'schemaVersion must be the literal "1"',"schemaVersion"):null;if(i)return[i];let r=c1(l=e.type)?lt.includes(l)?null:c2("denied/schema-version-unsupported","type is not a known relationship type","type"):c2("denied/schema-version-unsupported","type must be a non-empty string","type");if(r)return[r];let s=c6(t,"source"),o=c6(n,"target");if(null!==s||null!==o){let e=[];return null!==s&&e.push(s),null!==o&&e.push(o),e;}let c=c1(a=e.lifecycleState)?ln.includes(a)?null:c2("denied/schema-version-unsupported","lifecycleState is not a known lifecycle state","lifecycleState"):c2("denied/schema-version-unsupported","lifecycleState must be a non-empty string","lifecycleState");return c?[c]:null;}(n,l,a);if(i)return{ok:!1,errors:i};let r=function(e){if(!(null==e?void 0:e.endpointResolver))return null;let t=[];return"missing"===e.endpointResolver.source&&c5("source",e.endpointResolver.source,t),"missing"===e.endpointResolver.target&&c5("target",e.endpointResolver.target,t),t;}(void 0);if(null!==r&&r.length>0)return{ok:!1,errors:r};let s=function(e,t,n,l){var a,i,r,s,o;let c,d,u,p,m,h,f=[],g=e.type,v=e.lifecycleState,b=c8(t,"source");b&&f.push(b);let x=c8(n,"target");x&&f.push(x),null===b&&null===x&&(a=t.kind,i=n.kind,"denied/source-kind-not-allowed"===(d=(c=ll[g]).validSourceKinds.includes(a)?c.validTargetKinds.includes(i)?null:"denied/target-kind-not-allowed":"denied/source-kind-not-allowed")?f.push(c2("denied/source-kind-not-allowed",`source.kind "${t.kind}" is not permitted for type "${g}"`,"source.kind")):"denied/target-kind-not-allowed"===d&&f.push(c2("denied/target-kind-not-allowed",`target.kind "${n.kind}" is not permitted for type "${g}"`,"target.kind")));let y=(u=null==l?void 0:l.cardinalityCounts)?"produces-evidence"===g&&"number"==typeof u.producesEvidenceForSource&&u.producesEvidenceForSource>=1?c2("denied/cardinality-exceeded","produces-evidence already exists for this source workflow-run"):"starts-workflow"===g&&"number"==typeof u.startsWorkflowForTarget&&u.startsWorkflowForTarget>=1?c2("denied/cardinality-exceeded","starts-workflow already exists for this target workflow-run"):null:null;y&&f.push(y),(p=t.kind===n.kind&&t.id===n.id?c2("denied/cycle-forbidden","source and target refer to the same endpoint"):null)&&f.push(p),(m="depends-on"===g&&(null==l?void 0:l.dependsOnReverseEdgeExists)===!0?c2("denied/cycle-forbidden","depends-on reverse edge already exists for this endpoint pair"):null)&&f.push(m);let w=(r=e.workspaceId,t.workspaceId!==r||n.workspaceId!==r?c2("denied/cross-workspace","source and target must be in the relationship's workspace"):null);w&&f.push(w);let j=void 0===(h=null==l?void 0:l.previousLifecycleState)||cZ[h].includes(v)?null:c2("denied/lifecycle-illegal-transition",`transition from ${h} to ${v} is not permitted`,"lifecycleState");for(let t of(j&&f.push(j),s=l,o=f,(null==s?void 0:s.endpointResolver)&&("missing"!==s.endpointResolver.source&&c5("source",s.endpointResolver.source,o),"missing"!==s.endpointResolver.target&&c5("target",s.endpointResolver.target,o)),function(e){let t=[];if(void 0===e.metadata||null===e.metadata)return t;if(!c0(e.metadata))return t.push(c2("denied/payload-content-not-permitted","metadata must be an object when set","metadata")),t;for(let n of Object.keys(e.metadata)){let e=n.toLowerCase().replace(/[^a-z0-9]/g,"");for(let l of la)if(e.includes(l)){t.push(c2("denied/payload-content-not-permitted","metadata may not carry endpoint content",`metadata.${n}`));break;}}return t;}(e)))f.push(t);return f;}(n,l,a,void 0);return s.length>0?{ok:!1,errors:s}:{ok:!0,value:n};}({id:"candidate",schemaVersion:"1",workspaceId:"preview",source:{kind:n.sourceKind,id:n.sourceId,workspaceId:"preview"},target:{kind:n.targetKind,id:n.targetId,workspaceId:"preview"},type:n.type,lifecycleState:"active",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),etag:0});e.ok?s([]):s(e.errors.map(e=>e.message));},[n]);let x=(0,i.useRef)(null),y=(0,i.useRef)(0);(0,i.useEffect)(()=>{y.current+=1;let e=y.current;return(null!==x.current&&clearTimeout(x.current),0===n.sourceId.length||0===n.targetId.length||r.length>0)?void m(!1):(x.current=setTimeout(async()=>{m(!0);try{if(await lc({type:n.type,source:{kind:n.sourceKind,id:n.sourceId},target:{kind:n.targetKind,id:n.targetId},summary:n.summary.length>0?n.summary:void 0}),e!==y.current)return;c(e=>de(e)?e:null);}catch(t){if(e!==y.current)return;t instanceof lr&&t.reasons.length>0?c({source:"preview",codes:t.reasons.map(e=>e.code),messages:t.reasons.map(e=>e.message)}):c(null);}finally{e===y.current&&m(!1);}},250),()=>{null!==x.current&&clearTimeout(x.current);});},[n,r]),(0,i.useEffect)(()=>{c(e=>(null==e?void 0:e.source)!=="submit"||de(e)?e:null);},[n]);let w=n.sourceId.trim().length>0&&n.targetId.trim().length>0&&0===r.length&&null===o&&!d,j=(0,i.useCallback)(async()=>{if(w){u(!0),c(null);try{let e=crypto.randomUUID(),{relationship:l}=await ld({type:n.type,source:{kind:n.sourceKind,id:n.sourceId},target:{kind:n.targetKind,id:n.targetId},summary:n.summary.length>0?n.summary:void 0},e);t(l);}catch(e){e instanceof lr?e.reasons.length>0?c({source:"submit",codes:e.reasons.map(e=>e.code),messages:e.reasons.map(e=>e.message)}):c({source:"submit",codes:[e.code],messages:[e.message]}):c({source:"submit",codes:["relationship/network-error"],messages:[li]});}finally{u(!1);}}},[w,n,t]),k=(0,i.useCallback)(e=>{"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&j();},[j]),S=ll[n.type],C=de(o),I=[r.length>0?"rel-create-client-hints":null,null!==o?"rel-create-server-denial":null].filter(e=>null!==e),R=(0,a.jsx)("div",{className:"cmdk-overlay",onPointerDown:()=>t(null),"data-testid":"rel-create-overlay",children:(0,a.jsxs)("div",{ref:h,role:"dialog","aria-modal":"true","aria-labelledby":f,"aria-describedby":g,className:"cmdk",style:{maxWidth:480,width:"100%"},onPointerDown:e=>e.stopPropagation(),onKeyDown:k,"data-testid":"rel-create-dialog",children:[(0,a.jsxs)("div",{className:"cmdk-input",style:{borderBottom:"1px solid var(--line)"},children:[(0,a.jsx)("span",{id:f,style:{fontWeight:600,fontSize:14,color:"var(--fg)"},children:"Create relationship"}),(0,a.jsx)("span",{id:g,className:"visually-hidden",children:"Create a new relationship between two workspace endpoints."}),(0,a.jsx)("button",{type:"button",className:"palette-x",onClick:()=>t(null),"aria-label":"Close",title:"Close",style:{marginLeft:"auto"},children:(0,a.jsx)(N.F.close,{size:16})})]}),(0,a.jsxs)("div",{style:{padding:"12px 16px",display:"flex",flexDirection:"column",gap:10},children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("label",{htmlFor:"rel-type",style:{fontSize:12,color:"var(--fg-muted)",display:"block",marginBottom:3},children:"Type"}),(0,a.jsx)(tB,{value:n.type,ariaLabel:"Relationship type",autoFocus:!0,menuTitle:"Relationship type",triggerStyle:{width:"100%",background:"var(--inset)",border:"1px solid var(--line)",borderRadius:4,padding:"4px 8px",minHeight:24,color:"var(--fg)",fontSize:13},sections:[{options:lt.map(e=>({value:e,label:ll[e].displayName}))}],onValueChange:e=>l(t=>({...t,type:e}))}),(0,a.jsx)("div",{style:{fontSize:11,color:"var(--fg-muted)",marginTop:3},children:S.semantics})]}),(0,a.jsxs)("div",{style:{display:"flex",gap:"var(--space-3)"},children:[(0,a.jsxs)("div",{style:{flex:"0 0 140px"},children:[(0,a.jsx)("label",{htmlFor:"rel-src-kind",style:{fontSize:12,color:"var(--fg-muted)",display:"block",marginBottom:3},children:"Source kind"}),(0,a.jsx)("select",{id:"rel-src-kind",value:n.sourceKind,onChange:e=>l(t=>({...t,sourceKind:e.target.value})),style:{width:"100%",background:"var(--inset)",border:"1px solid var(--line)",borderRadius:4,padding:"4px 8px",minHeight:24,color:"var(--fg)",fontSize:12},"aria-label":"Source endpoint kind",children:le.map(e=>(0,a.jsx)("option",{value:e,children:e},e))})]}),(0,a.jsxs)("div",{style:{flex:1},children:[(0,a.jsx)("label",{htmlFor:"rel-src-id",style:{fontSize:12,color:"var(--fg-muted)",display:"block",marginBottom:3},children:"Source ID"}),(0,a.jsx)("input",{id:"rel-src-id",type:"text",value:n.sourceId,onChange:e=>l(t=>({...t,sourceId:e.target.value})),placeholder:"endpoint id",style:{width:"100%",background:"var(--inset)",border:"1px solid var(--line)",borderRadius:4,padding:"4px 8px",minHeight:24,color:"var(--fg)",fontSize:12},"aria-label":"Source endpoint ID","aria-describedby":"rel-src-kind"})]})]}),(0,a.jsxs)("div",{style:{display:"flex",gap:"var(--space-3)"},children:[(0,a.jsxs)("div",{style:{flex:"0 0 140px"},children:[(0,a.jsx)("label",{htmlFor:"rel-tgt-kind",style:{fontSize:12,color:"var(--fg-muted)",display:"block",marginBottom:3},children:"Target kind"}),(0,a.jsx)("select",{id:"rel-tgt-kind",value:n.targetKind,onChange:e=>l(t=>({...t,targetKind:e.target.value})),style:{width:"100%",background:"var(--inset)",border:"1px solid var(--line)",borderRadius:4,padding:"4px 8px",minHeight:24,color:"var(--fg)",fontSize:12},"aria-label":"Target endpoint kind",children:le.map(e=>(0,a.jsx)("option",{value:e,children:e},e))})]}),(0,a.jsxs)("div",{style:{flex:1},children:[(0,a.jsx)("label",{htmlFor:"rel-tgt-id",style:{fontSize:12,color:"var(--fg-muted)",display:"block",marginBottom:3},children:"Target ID"}),(0,a.jsx)("input",{id:"rel-tgt-id",type:"text",value:n.targetId,onChange:e=>l(t=>({...t,targetId:e.target.value})),placeholder:"endpoint id",style:{width:"100%",background:"var(--inset)",border:"1px solid var(--line)",borderRadius:4,padding:"4px 8px",minHeight:24,color:"var(--fg)",fontSize:12},"aria-label":"Target endpoint ID","aria-describedby":"rel-tgt-kind"})]})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("label",{htmlFor:"rel-summary",style:{fontSize:12,color:"var(--fg-muted)",display:"block",marginBottom:3},children:"Summary (optional, ≤240 chars)"}),(0,a.jsx)("textarea",{id:"rel-summary",value:n.summary,maxLength:240,rows:2,onChange:e=>l(t=>({...t,summary:e.target.value})),style:{width:"100%",background:"var(--inset)",border:"1px solid var(--line)",borderRadius:4,padding:"4px 8px",minHeight:24,color:"var(--fg)",fontSize:12,resize:"vertical"},"aria-label":"Relationship summary"})]}),r.length>0&&(0,a.jsx)("div",{id:"rel-create-client-hints",className:"lk-alert",role:"status","aria-live":"polite","data-testid":"client-validation-hints",children:r.map((e,t)=>(0,a.jsx)("div",{style:{fontSize:12},children:e},t))}),p&&(0,a.jsx)("div",{style:{fontSize:12,color:"var(--fg-muted)"},"aria-live":"polite",children:"Validating…"}),null!==o&&(0,a.jsxs)("div",{id:"rel-create-server-denial",className:"lk-alert",role:"alert","aria-live":"assertive","data-testid":"server-denial-banner",children:[o.codes.map((e,t)=>{var n;return(0,a.jsxs)("div",{style:{marginBottom:6*(t<o.codes.length-1)},children:[(0,a.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--fg-muted)",marginBottom:2},children:e}),(0,a.jsx)("div",{style:{fontSize:13,color:"var(--fg)"},children:null!=(n=o.messages[t])?n:e})]},e);}),C&&(0,a.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>c(null),style:{marginTop:6},children:"Dismiss"})]}),(0,a.jsxs)("div",{style:{display:"flex",gap:"var(--space-4)",justifyContent:"flex-end",marginTop:4},children:[(0,a.jsx)("button",{type:"button",className:"arun-btn",onClick:()=>t(null),style:{minWidth:24,minHeight:24},children:"Cancel"}),(0,a.jsx)("button",{type:"button",className:`arun-btn${w?" primary":""}`,"aria-disabled":!w,"aria-describedby":I.length>0?I.join(" "):void 0,onClick:()=>void j(),"aria-busy":d,style:{minWidth:24,minHeight:24},children:d?"Creating…":"Create"})]})]})]})});return"u"<typeof document?R:(0,tM.createPortal)(R,document.body);}let dn={};function dl(){var e;let{activityMap:t,throughputMap:n,animate:l}=function(){let e=(0,i.useRef)(new Map()),t=(0,i.useRef)("u"<typeof document||"visible"===document.visibilityState),[n,l]=(0,i.useState)(new Map()),[a,r]=(0,i.useState)(new Map()),s=(0,i.useRef)(new Map()),o=(0,i.useRef)(new Map()),[c,d]=(0,i.useState)(()=>window.matchMedia("(prefers-reduced-motion: reduce)").matches),[u,p]=(0,i.useState)(!1),m=(0,i.useCallback)(()=>{p(!0);},[]),h=(0,i.useCallback)((t,n)=>{let a=new Map(s.current),i=new Set(),c=new Set(),d=!1;for(let[l,r]of a){var u;let s=t-(null!=(u=e.current.get(l))?u:0);s>=6e4&&"inactive"!==r&&(a.set(l,"inactive"),c.add(l),d=!0),!n&&s>=12e4&&(a.delete(l),i.add(l),c.add(l),d=!0);}if(a.size>512)for(let t of Array.from(a.keys()).sort((t,n)=>{var l,i;let r=a.get(t),s=a.get(n);return"inactive"===r&&"inactive"!==s?-1:"inactive"!==r&&"inactive"===s?1:(null!=(l=e.current.get(t))?l:0)-(null!=(i=e.current.get(n))?i:0);}).slice(0,a.size-512))a.delete(t),i.add(t),c.add(t),d=!0;if(d&&(s.current=a,l(a)),i.size>0)for(let t of i)e.current.delete(t);if(c.size>0){let e=!1,t=new Map(o.current);for(let n of c)t.delete(n)&&(e=!0);e&&(o.current=t,r(t));}},[]);(0,i.useEffect)(()=>{let e=window.matchMedia("(prefers-reduced-motion: reduce)"),t=e=>{d(e.matches);};return e.addEventListener("change",t),()=>{e.removeEventListener("change",t);};},[]);let f=(0,i.useCallback)(n=>{var a;if(!t.current)return;let i=Date.now();i-(null!=(a=e.current.get(n.id))?a:0)<2e3||(e.current.set(n.id,i),l(e=>{let t=new Map(e);return t.set(n.id,n.state),s.current=t,t;}),"high-throughput"===n.state&&void 0!==n.count?r(e=>{let t=new Map(e);return t.set(n.id,n.count),o.current=t,t;}):r(e=>{if(!e.has(n.id))return e;let t=new Map(e);return t.delete(n.id),o.current=t,t;}));},[]);return(0,i.useEffect)(()=>{let e=setInterval(()=>{t.current&&h(Date.now(),!1);},15e3);return()=>{clearInterval(e);};},[h]),(0,i.useEffect)(()=>{if("u"<typeof document)return;let e=()=>{t.current="visible"===document.visibilityState,t.current&&h(Date.now(),!0);};return t.current="visible"===document.visibilityState,document.addEventListener("visibilitychange",e),()=>{document.removeEventListener("visibilitychange",e);};},[h]),(0,i.useEffect)(()=>{let e=!1,n=null,l=null;function a(e){let t;try{t=JSON.parse(e);}catch{return;}let n=function(e){var t;if(null===e||"object"!=typeof e||function e(t){if(null===t||"object"!=typeof t)return!1;for(let n of Object.keys(t))if(function(e){let t=e.toLowerCase();return la.some(e=>t.includes(e));}(n)||e(t[n]))return!0;return!1;}(e))return null;let n={};for(let t of cH)Object.prototype.hasOwnProperty.call(e,t)&&(n[t]=e[t]);return"string"!=typeof n.id||0===n.id.length?null:"inactive"!==(t=n.state)&&"queued"!==t&&"active"!==t&&"processing"!==t&&"completed"!==t&&"failed"!==t&&"blocked"!==t&&"degraded"!==t&&"high-throughput"!==t||"number"!=typeof n.timestamp?null:{kind:"string"==typeof n.kind?n.kind:"relationship:activity",id:n.id,state:n.state,timestamp:n.timestamp,count:"number"==typeof n.count?n.count:void 0};}(t);null!==n&&f(n);}function i(){null!==l&&(clearTimeout(l),l=null);}function r(){null==n||n.close(),n=null;}function s(){!e&&null===l&&t.current&&(l=setTimeout(()=>{l=null,o();},5e3));}function o(){if(!e&&t.current){try{n=new EventSource("/api/relationships/events");}catch{s();return;}n.addEventListener("relationship:activity",e=>{a(e.data);}),n.onmessage=e=>{a(e.data);},n.onerror=()=>{e||(r(),s());};}}o();let c=()=>{if(t.current="visible"===document.visibilityState,!t.current){i(),r();return;}h(Date.now(),!0),null===n&&o();};return document.addEventListener("visibilitychange",c),()=>{e=!0,document.removeEventListener("visibilitychange",c),i(),r();};},[void 0,f,h]),{activityMap:n,throughputMap:a,animate:!c&&!u,disable:m};}(),[r,s]=(0,i.useState)(!1),[o,c]=(0,i.useState)(dn),d=o.relFocus,u=null!=(e=o.relDensity)?e:"minimal",[p,m]=(0,i.useState)(!1),h=(0,i.useRef)(null),f=(0,i.useRef)(!1),g=(0,i.useRef)(null),[v,b]=(0,i.useState)(!1),x=(0,i.useCallback)(e=>{c(t=>{let n={...t,...e},l={};for(let[e,t]of Object.entries(n))void 0!==t&&""!==t&&(l[e]=t);return l;});},[]),y=(0,i.useCallback)(e=>{x({relFocus:e});},[x]),w=(0,i.useCallback)(()=>{x({relFocus:void 0});},[x]),j=(0,i.useCallback)(e=>{x({relFocus:e});},[x]),k=(0,i.useCallback)(e=>{f.current=!0,m(!1),null!==e&&x({relFocus:e.id});},[x]);return(0,i.useEffect)(()=>{var e;!p&&f.current&&(f.current=!1,null==(e=h.current)||e.focus());},[p]),(0,i.useEffect)(()=>{let e=window.matchMedia("(prefers-contrast: more)"),t=e=>{s(e);};t(e.matches);let n=e=>{t(e.matches);};return e.addEventListener("change",n),()=>e.removeEventListener("change",n);},[]),(0,i.useEffect)(()=>{let e=g.current;if(null===e)return;let t=e=>{let t=e.target;if(!("INPUT"===t.tagName||"TEXTAREA"===t.tagName||"SELECT"===t.tagName||t.isContentEditable)&&"Escape"===e.key){if(p||null!==document.querySelector('[role="dialog"][aria-modal="true"]'))return;w();}};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t);},[p,w]),(0,a.jsxs)(a.Fragment,{children:[p&&(0,a.jsx)(dt,{onClose:k}),(0,a.jsxs)("div",{ref:g,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",background:"var(--bg)"},children:[(0,a.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid var(--line)",flexShrink:0},children:[(0,a.jsx)("button",{type:"button",className:"arun-btn",onClick:()=>b(e=>!e),"aria-pressed":v,"aria-label":"Toggle the graph health view",style:{flex:"0 0 auto",minHeight:24,marginRight:"auto"},children:v?"Hide health":"Graph health"}),(0,a.jsx)("button",{ref:h,type:"button",className:"arun-btn primary",onClick:()=>m(!0),"aria-label":"Create new relationship",style:{flex:"0 0 auto",minWidth:24,minHeight:24},children:"+ New relationship"})]}),(0,a.jsxs)("div",{style:{display:"flex",flex:1,overflow:"hidden"},children:[(0,a.jsx)("div",{style:{flex:"0 0 280px",borderRight:"1px solid var(--line)",overflowY:"auto"},children:(0,a.jsx)(cI,{filters:o,selectedId:d,onSelect:y,onFilterChange:x,activityMap:t,throughputMap:n,animateBadges:l,highContrast:r})}),(0,a.jsx)("div",{style:{flex:1,overflowY:"auto"},children:v?(0,a.jsx)(cQ,{onSelectRelationship:e=>{b(!1),y(e);}}):(0,a.jsx)(cV,{relationshipId:null!=d?d:null,densityMode:u,onClearFocus:w,onViewImpact:j,activityMap:t,throughputMap:n,animateBadges:l,highContrast:r})})]})]})]});}var da=n(65587),di=n.n(da);let dr={NOT_FOUND:"The memory could not be found. It may have been deleted.",BAD_REQUEST:"The request was rejected as invalid. Adjust the input and try again.",CONFLICT:"The memory changed in the meantime. Reload the page and try again.",GOVERNANCE_ERROR:"Governance rules blocked this action.",MEMORY_ERROR:"The memory store reported an error. Retry, or check the server log.",MEMORY_UNAVAILABLE:"The memory store is currently unavailable. Retry in a moment.",PAYLOAD_TOO_LARGE:"The submitted content is too large. Shorten it and try again.",INTERNAL:"Something went wrong on the server. Retry, or check the server log."};function ds(e){if(e instanceof k.hD){let t=dr[e.code];return void 0!==t?`${t} (${e.code})`:e.message.trim().length>0?`${e.message} (${e.code})`:`Something went wrong. Retry, or check the server log. (${e.code})`;}return e instanceof Error&&e.message.trim().length>0?e.message:"An unexpected error occurred.";}let dc={jaccardThreshold:.85,staleConfidenceThreshold:.3,maxAgeMs:7776e6,maxClustersPerRun:100,maxRecordsPerRun:1e3};function dd(e,t){return`${e.toString()} ${1===e?t:`${t}s`}`;}function du(e){return"completed"===e||"failed"===e||"canceled"===e||"skipped"===e;}function dp(e){return void 0===e?"—":new Date(e).toLocaleString();}function dm(e){let{id:t,onOpenDetail:n}=e;return void 0!==n?(0,a.jsx)("button",{type:"button",className:"mc-id-link mc-link-button",title:t,onClick:()=>n(t),children:t}):(0,a.jsx)(di(),{href:`/memoriaviva/detail?id=${encodeURIComponent(t)}`,className:"mc-id-link",title:t,children:t});}function dh(e){let{ids:t,onOpenDetail:n}=e;return(0,a.jsx)(a.Fragment,{children:t.map((e,t)=>(0,a.jsxs)(i.Fragment,{children:[t>0?", ":null,(0,a.jsx)(dm,{id:e,onOpenDetail:n})]},`${t.toString()}:${e}`))});}function df(e){let{item:t,onOpenDetail:n}=e;return void 0===t.proposedAction?(0,a.jsx)(a.Fragment,{children:"No automatic action proposed."}):"merge"===t.proposedAction.kind?(0,a.jsxs)(a.Fragment,{children:["Merge into ",(0,a.jsx)(dm,{id:t.proposedAction.winner,onOpenDetail:n}),"; replace ",(0,a.jsx)(dh,{ids:t.proposedAction.losers,onOpenDetail:n}),"."]}):(0,a.jsxs)(a.Fragment,{children:["Supersede ",(0,a.jsx)(dm,{id:t.proposedAction.older,onOpenDetail:n})," with"," ",(0,a.jsx)(dm,{id:t.proposedAction.newer,onOpenDetail:n}),"."]});}function dg(e){let{flag:t,onOpenDetail:n}=e;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(dm,{id:t.memoryId,onOpenDetail:n})," — ",t.reason]});}function dv(e){let{label:t,name:n,value:l,min:r,max:s,step:o,help:c,disabled:d=!1,onChange:u}=e,p=(0,i.useId)(),m=e=>{var t;let a=null!=o?o:1,i=Number.isFinite(l)?l:null!=r?r:0,c=Math.min(function(e){let[,t=""]=e.toString().split(".");return t.length;}(a)+2,8);u(n,(t=Number((i+e*a).toFixed(c)),void 0!==r&&t<r?r:void 0!==s&&t>s?s:t));};return(0,a.jsxs)("div",{style:{display:"grid",gap:"var(--space-3)"},children:[(0,a.jsxs)("label",{style:{display:"grid",gap:"var(--space-3)"},children:[(0,a.jsx)("span",{className:"mc-dialog-label",children:t}),(0,a.jsxs)("span",{className:"number-control",children:[(0,a.jsx)("input",{type:"number",inputMode:"decimal",className:"mc-dialog-input number-control-input",name:n,value:Number.isFinite(l)?l:"",min:r,max:s,step:o,disabled:d,"aria-describedby":p,onChange:e=>{u(n,Number(e.target.value));},onWheel:e=>{d||0===e.deltaY||(e.preventDefault(),m(e.deltaY<0?1:-1));}}),(0,a.jsx)(l1,{label:t.toLowerCase(),disabled:d,onStepUp:()=>m(1),onStepDown:()=>m(-1)})]})]}),(0,a.jsx)("span",{id:p,style:{color:"var(--fg-muted)",fontSize:12},children:c})]});}function db(e){var t,n,l,r,s,o,c,d,u,p;let{startJobImpl:m=t7,fetchJobImpl:h=t9,cancelJobImpl:f=ne,pollIntervalMs:g=2e3,onBack:v,onOpenDetail:b}=e,[x,y]=(0,i.useState)(dc),[w,j]=(0,i.useState)(null),[k,N]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),[I,R]=(0,i.useState)(!1),[E,$]=(0,i.useState)(null),[A,F]=(0,i.useState)(null),T=null!=(t=null==w?void 0:w.job)?t:null,D=null!==T&&!du(T.state),q=(0,i.useMemo)(()=>{var e,t,n;if(null===T)return null;let l=T.result;return{reviewCount:null!=(e=null==l?void 0:l.reviewItems.length)?e:0,staleCount:null!=(t=null==l?void 0:l.staleFlags.length)?t:0,edgeCount:null!=(n=null==l?void 0:l.edgesProposed.length)?n:0};},[T]),M=(0,i.useCallback)((e,t)=>{y(n=>({...n,[e]:t}));},[]),P=(0,i.useCallback)(async e=>{C(!0);try{let t=await h(e);j(t.job),F(null);}catch(e){F(ds(e));}finally{C(!1);}},[h]);(0,i.useEffect)(()=>{if(null===T||du(T.state))return;let e=window.setInterval(()=>{P(T.id);},g);return()=>{window.clearInterval(e);};},[T,g,P]);let L=(0,i.useCallback)(async e=>{if(e.preventDefault(),!k&&!D){N(!0),$(null),F(null);try{let e=await m(x);j(e.job);}catch(e){$(ds(e));}finally{N(!1);}}},[x,m,k,D]),z=(0,i.useCallback)(async()=>{if(null!==T&&!I){R(!0),F(null);try{let e=await f(T.id);j(e.job);}catch(e){F(ds(e));}finally{R(!1);}}},[T,f,I]);return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("header",{className:"lk-header mc-consolidation-header",children:[(0,a.jsxs)("div",{className:"mc-consolidation-heading",style:{display:"grid",gap:"var(--space-2)"},children:[(0,a.jsx)("h1",{className:"lk-title",children:"MemoriaViva Consolidation"}),(0,a.jsx)("p",{style:{margin:0,color:"var(--fg-muted)"},children:"Start a bounded consolidation job, inspect its output, and cancel it while it is still queued or running."})]}),void 0!==v?(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost lk-btn-lg","aria-label":"Back to MemoriaViva",onClick:v,children:"Back"}):(0,a.jsx)(di(),{href:"/memoriaviva",className:"lk-btn lk-btn-ghost lk-btn-lg","aria-label":"Back to MemoriaViva",children:"Back"})]}),(0,a.jsxs)("div",{className:"mc-consolidation-scroll",children:[(0,a.jsx)("section",{"aria-label":"Consolidation settings",style:{display:"grid",gap:16,padding:16,border:"1px solid var(--line)",borderRadius:14,background:"var(--card)"},children:(0,a.jsxs)("form",{onSubmit:L,style:{display:"grid",gap:16},children:[(0,a.jsxs)("div",{style:{display:"grid",gap:"var(--space-5)",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))"},children:[(0,a.jsx)(dv,{label:"Jaccard threshold",name:"jaccardThreshold",value:x.jaccardThreshold,min:0,max:1,step:.01,disabled:k||D,help:"Similarity floor for near-duplicate detection.",onChange:M}),(0,a.jsx)(dv,{label:"Stale confidence threshold",name:"staleConfidenceThreshold",value:x.staleConfidenceThreshold,min:0,max:1,step:.01,disabled:k||D,help:"Memories at or below this confidence are flagged stale.",onChange:M}),(0,a.jsx)(dv,{label:"Max age (days)",name:"maxAgeMs",value:x.maxAgeMs/864e5,min:0,step:1,disabled:k||D,help:"Memories older than this are checked for staleness.",onChange:(e,t)=>{M(e,864e5*t);}}),(0,a.jsx)(dv,{label:"Max clusters per run",name:"maxClustersPerRun",value:x.maxClustersPerRun,min:0,max:1e3,step:1,disabled:k||D,help:"Hard bound on duplicate clusters inspected in one run.",onChange:M}),(0,a.jsx)(dv,{label:"Max records per run",name:"maxRecordsPerRun",value:x.maxRecordsPerRun,min:0,max:1e3,step:1,disabled:k||D,help:"Hard bound on accepted records admitted to one scan.",onChange:M})]}),null!==E?(0,a.jsx)("div",{role:"alert",className:"lk-alert",children:E}):null,(0,a.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"var(--space-5)"},children:[(0,a.jsx)("button",{type:"submit",className:"lk-btn lk-btn-primary","aria-disabled":k||D,"aria-busy":k,children:k?"Starting…":"Start consolidation"}),(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null===T||S,"aria-busy":S,onClick:()=>{null===T||S||P(T.id);},children:S?"Refreshing…":"Refresh status"}),D?(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":I,"aria-busy":I,onClick:()=>{z();},children:I?"Canceling…":"Cancel job"}):null]})]})}),(0,a.jsx)("section",{"aria-label":"Consolidation job status",style:{display:"grid",gap:16,padding:16,border:"1px solid var(--line)",borderRadius:14,background:"var(--card)"},children:null===T?(0,a.jsx)("p",{style:{margin:0,color:"var(--fg-muted)"},children:"No consolidation job started yet."}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{style:{display:"grid",gap:"var(--space-5)",gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))"},children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"State"}),(0,a.jsx)("div",{role:"status","aria-live":"polite","aria-atomic":"true",style:{fontWeight:700,textTransform:"capitalize"},children:T.state})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Job ID"}),(0,a.jsx)("div",{style:{wordBreak:"break-all"},children:T.id})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Started"}),(0,a.jsx)("div",{children:dp(T.startedAt)})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Completed"}),(0,a.jsx)("div",{children:dp(T.completedAt)})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Clusters inspected"}),(0,a.jsx)("div",{style:{fontVariantNumeric:"tabular-nums"},children:null!=(n=null==(o=T.result)?void 0:o.clustersInspected)?n:0})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Elapsed"}),(0,a.jsx)("div",{style:{fontVariantNumeric:"tabular-nums"},children:(p=null!=(l=null==(c=T.result)?void 0:c.elapsedMs)?l:0)<1e3?`${p.toString()} ms`:`${(p/1e3).toFixed(1)} s`})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Records inspected"}),(0,a.jsxs)("div",{style:{fontVariantNumeric:"tabular-nums"},children:[null!=(r=null==(d=T.result)?void 0:d.recordsInspected)?r:0,(null==(u=T.result)?void 0:u.truncated)===!0?" (truncated)":""]})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Memories loaded"}),(0,a.jsx)("div",{style:{fontVariantNumeric:"tabular-nums"},children:null!=(s=null==w?void 0:w.memoryCount)?s:0})]})]}),null!==A?(0,a.jsx)("div",{role:"alert",className:"lk-alert",children:A}):null,void 0!==T.error&&T.error.length>0?(0,a.jsx)("div",{role:"alert",className:"lk-alert",children:T.error}):null,null!==q?(0,a.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"var(--space-5)"},children:[(0,a.jsx)("span",{className:"mc-badge mc-badge-default",children:dd(q.reviewCount,"review item")}),(0,a.jsx)("span",{className:"mc-badge mc-badge-default",children:dd(q.staleCount,"stale flag")}),(0,a.jsx)("span",{className:"mc-badge mc-badge-default",children:dd(q.edgeCount,"proposed edge")})]}):null]})}),(null==T?void 0:T.result)!==void 0?(0,a.jsxs)("section",{"aria-label":"Consolidation results","aria-live":"polite","aria-atomic":"false",style:{display:"grid",gap:16,gridTemplateColumns:"repeat(auto-fit, minmax(280px, 1fr))"},children:[(0,a.jsxs)("article",{style:{display:"grid",gap:"var(--space-5)",padding:16,border:"1px solid var(--line)",borderRadius:14,background:"var(--card)"},children:[(0,a.jsx)("h2",{className:"lk-section-head",style:{margin:0},children:"Review items"}),0===T.result.reviewItems.length?(0,a.jsx)("p",{style:{margin:0,color:"var(--fg-muted)"},children:"No review items returned."}):(0,a.jsx)("ul",{style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:"var(--space-5)"},children:T.result.reviewItems.map(e=>(0,a.jsxs)("li",{style:{display:"grid",gap:"var(--space-2)"},children:[(0,a.jsx)("strong",{style:{textTransform:"capitalize"},children:e.reason.replaceAll("-"," ")}),(0,a.jsx)("span",{children:(0,a.jsx)(dh,{ids:e.relatedMemoryIds,onOpenDetail:b})}),(0,a.jsx)("span",{style:{color:"var(--fg-muted)"},children:(0,a.jsx)(df,{item:e,onOpenDetail:b})})]},e.id))})]}),(0,a.jsxs)("article",{style:{display:"grid",gap:"var(--space-5)",padding:16,border:"1px solid var(--line)",borderRadius:14,background:"var(--card)"},children:[(0,a.jsx)("h2",{className:"lk-section-head",style:{margin:0},children:"Stale flags"}),0===T.result.staleFlags.length?(0,a.jsx)("p",{style:{margin:0,color:"var(--fg-muted)"},children:"No stale flags returned."}):(0,a.jsx)("ul",{style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:"var(--space-5)"},children:T.result.staleFlags.map(e=>(0,a.jsx)("li",{children:(0,a.jsx)(dg,{flag:e,onOpenDetail:b})},`${e.memoryId}:${e.reason}`))})]}),(0,a.jsxs)("article",{style:{display:"grid",gap:"var(--space-5)",padding:16,border:"1px solid var(--line)",borderRadius:14,background:"var(--card)"},children:[(0,a.jsx)("h2",{className:"lk-section-head",style:{margin:0},children:"Proposed edges"}),0===T.result.edgesProposed.length?(0,a.jsx)("p",{style:{margin:0,color:"var(--fg-muted)"},children:"No edges proposed."}):(0,a.jsx)("ul",{style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:"var(--space-5)"},children:T.result.edgesProposed.map(e=>(0,a.jsxs)("li",{style:{display:"grid",gap:"var(--space-2)"},children:[(0,a.jsx)("strong",{children:e.kind}),(0,a.jsxs)("span",{children:[(0,a.jsx)(dm,{id:e.fromMemoryId,onOpenDetail:b})," →"," ",(0,a.jsx)(dm,{id:e.toMemoryId,onOpenDetail:b})]}),void 0!==e.provenanceSummary?(0,a.jsx)("span",{style:{color:"var(--fg-muted)"},children:e.provenanceSummary}):null]},e.id))})]})]}):null]})]});}let dx=["user","workspace","project","workflow","global"],dy=["episodic","semantic-fact","procedural","preference","correction","decision","negative","pinned"],dw=["public","confidential","restricted"],dj=["proposed","accepted","rejected","superseded","archived","forgotten","conflicted","expired"],dk={user:"User",workspace:"Workspace",project:"Project",workflow:"Workflow",global:"Global"},dN={episodic:"Episodic","semantic-fact":"Fact",procedural:"Procedural",preference:"Preference",correction:"Correction",decision:"Decision",negative:"Negative",pinned:"Pinned"},dS={proposed:"Proposed",accepted:"Accepted",rejected:"Rejected",superseded:"Superseded",archived:"Archived",forgotten:"Forgotten",conflicted:"Conflicted",expired:"Expired"},dC={public:"Public",confidential:"Confidential",restricted:"Restricted"};function dI(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t];}function dR(e){let{label:t,items:n,labels:l,active:i,onToggle:r}=e;return(0,a.jsxs)("div",{className:"mc-filter-row",role:"group","aria-label":`Filter by ${t}`,children:[(0,a.jsx)("span",{className:"mc-filter-label",children:t}),(0,a.jsx)("div",{className:"mc-filter-chips",children:n.map(e=>{let t=i.includes(e);return(0,a.jsx)("button",{type:"button",className:"mc-chip","data-active":String(t),"aria-pressed":t,onClick:()=>{r(e);},children:l[e]},e);})})]});}function dE(e){let{filters:t,onChange:n}=e;return(0,a.jsxs)("section",{className:"mc-filters","aria-label":"Memory filters",children:[(0,a.jsx)(dR,{label:"Scope",items:dx,labels:dk,active:t.scope,onToggle:e=>{n({...t,scope:dI(t.scope,e)});}}),(0,a.jsx)(dR,{label:"Type",items:dy,labels:dN,active:t.type,onToggle:e=>{n({...t,type:dI(t.type,e)});}}),(0,a.jsx)(dR,{label:"Status",items:dj,labels:dS,active:t.status,onToggle:e=>{n({...t,status:dI(t.status,e)});}}),(0,a.jsx)(dR,{label:"Sensitivity",items:dw,labels:dC,active:t.sensitivity,onToggle:e=>{n({...t,sensitivity:dI(t.sensitivity,e)});}})]});}let d$={public:"Public",confidential:"Confidential",restricted:"Restricted"};function dA(e){let{record:t,mode:n="edit",onSave:l,onClose:r,editMemoryImpl:s=nn,correctMemoryImpl:o=no}=e,[c,d]=(0,i.useState)(t.body),[u,p]=(0,i.useState)(t.tags.join(", ")),[m,h]=(0,i.useState)(t.provenance.sensitivity),[f,g]=(0,i.useState)(!1),[v,b]=(0,i.useState)(null),[x,y]=(0,i.useState)(!1),w=(0,i.useRef)(null),j=(0,i.useRef)(null),k=(0,i.useRef)(null),N=(0,i.useRef)(null),S=(0,i.useId)(),C=(0,i.useId)(),I="correct"===n;(0,i.useEffect)(()=>{var e;return N.current=document.activeElement instanceof HTMLElement?document.activeElement:null,null==(e=w.current)||e.focus(),()=>{var e;null==(e=N.current)||e.focus();};},[]);let R=(0,i.useCallback)(e=>{var t,n,l;if("Escape"===e.key)return void r();if("Tab"!==e.key)return;let a=null==(t=k.current)?void 0:t.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled])');if(void 0===a||0===a.length){e.preventDefault(),null==(n=k.current)||n.focus();return;}let i=a[0],s=a[a.length-1];if(void 0===i||void 0===s){e.preventDefault(),null==(l=k.current)||l.focus();return;}let o=document.activeElement;e.shiftKey||o!==s?e.shiftKey&&o===i&&(e.preventDefault(),s.focus()):(e.preventDefault(),i.focus());},[r]),E=(0,i.useCallback)(e=>{e.target===j.current&&r();},[r]),$=(0,i.useCallback)(async()=>{let e=c.trim();if(0===e.length){var n;b("Body cannot be empty."),y(!0),null==(n=w.current)||n.focus();return;}let a=u.split(",").map(e=>e.trim()).filter(e=>e.length>0);g(!0),b(null);try{if(I){let n=await o(t.id,e);l(n.correction);}else{let n=await s(t.id,{body:e,tags:a,sensitivity:m});l(n.memory);}}catch(e){b(ds(e));}finally{g(!1);}},[c,u,m,t.id,I,o,s,l]);return(0,a.jsx)("div",{ref:j,className:"mc-dialog-backdrop",role:"presentation",onClick:E,children:(0,a.jsxs)("div",{ref:k,role:"dialog","aria-modal":"true","aria-labelledby":S,tabIndex:-1,className:"mc-dialog",onKeyDown:R,children:[(0,a.jsx)("h2",{id:S,className:"mc-dialog-title",children:I?"Correct memory":"Edit memory"}),(0,a.jsxs)("div",{className:"mc-dialog-field",children:[(0,a.jsx)("label",{htmlFor:"edit-body",className:"mc-dialog-label",children:I?"Corrected body":"Body"}),(0,a.jsx)("textarea",{id:"edit-body",ref:w,className:"mc-dialog-textarea",value:c,rows:5,onChange:e=>{d(e.target.value),x&&(y(!1),b(null));},disabled:f,"aria-required":"true","aria-invalid":x?"true":void 0,"aria-describedby":x?C:void 0})]}),I?null:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"mc-dialog-field",children:[(0,a.jsxs)("label",{htmlFor:"edit-tags",className:"mc-dialog-label",children:["Tags ",(0,a.jsx)("span",{className:"mc-dialog-hint",children:"(comma-separated)"})]}),(0,a.jsx)("input",{id:"edit-tags",type:"text",className:"mc-dialog-input",value:u,onChange:e=>{p(e.target.value);},disabled:f})]}),(0,a.jsxs)("div",{className:"mc-dialog-field",children:[(0,a.jsx)("label",{htmlFor:"edit-sensitivity",className:"mc-dialog-label",children:"Sensitivity"}),(0,a.jsx)("select",{id:"edit-sensitivity",className:"mc-dialog-select",value:m,onChange:e=>{h(e.target.value);},disabled:f,children:dw.map(e=>(0,a.jsx)("option",{value:e,children:d$[e]},e))})]})]}),null!==v?(0,a.jsx)("p",{id:C,role:"alert",className:"mc-dialog-error",children:v}):null,(0,a.jsxs)("div",{className:"mc-dialog-actions",children:[(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:r,disabled:f,children:"Cancel"}),(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-primary",onClick:()=>{$();},disabled:f,"aria-busy":f,children:f?I?"Submitting…":"Saving…":I?"Submit correction":"Save"})]})]})});}function dF(e){let{record:t,mode:n="forget",onComplete:l,onClose:r,forgetMemoryImpl:s=nr,deleteMemoryImpl:o=ns}=e,[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(null),m=(0,i.useRef)(null),h=(0,i.useRef)(null),f=(0,i.useRef)(null),g=(0,i.useRef)(null),v="delete"===n;(0,i.useEffect)(()=>{var e;return g.current=document.activeElement instanceof HTMLElement?document.activeElement:null,null==(e=m.current)||e.focus(),()=>{var e;null==(e=g.current)||e.focus();};},[]);let b=(0,i.useCallback)(e=>{var t,n,l;if("Escape"===e.key)return void r();if("Tab"!==e.key)return;let a=null==(t=f.current)?void 0:t.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled])');if(void 0===a||0===a.length){e.preventDefault(),null==(n=f.current)||n.focus();return;}let i=a[0],s=a[a.length-1];if(void 0===i||void 0===s){e.preventDefault(),null==(l=f.current)||l.focus();return;}let o=document.activeElement;e.shiftKey||o!==s?e.shiftKey&&o===i&&(e.preventDefault(),s.focus()):(e.preventDefault(),i.focus());},[r]),x=(0,i.useCallback)(e=>{e.target===h.current&&r();},[r]),y=(0,i.useCallback)(async()=>{d(!0),p(null);try{v?await o(t.id,"user-initiated delete from MemoriaViva"):await s(t.id,"user-initiated forget from MemoriaViva"),l();}catch(e){p(ds(e)),d(!1);}},[o,s,v,l,t.id]);return(0,a.jsx)("div",{ref:h,className:"mc-dialog-backdrop",role:"presentation",onClick:x,children:(0,a.jsxs)("div",{ref:f,role:"dialog","aria-modal":"true","aria-labelledby":"forget-dialog-title","aria-describedby":"forget-dialog-desc",tabIndex:-1,className:"mc-dialog",onKeyDown:b,children:[(0,a.jsx)("h2",{id:"forget-dialog-title",className:"mc-dialog-title",children:v?"Delete this memory?":"Forget this memory?"}),(0,a.jsx)("p",{id:"forget-dialog-desc",className:"mc-dialog-body",children:(0,a.jsxs)(a.Fragment,{children:["This action is ",(0,a.jsx)("strong",{children:"permanent"}),". The memory will be removed and a tombstone audit record will be created. You cannot undo this."]})}),(0,a.jsx)("blockquote",{className:"mc-dialog-quote","aria-label":"Memory content to be removed",children:t.body.length>120?`${t.body.slice(0,120)}…`:t.body}),null!==u?(0,a.jsx)("p",{role:"alert",className:"mc-dialog-error",children:u}):null,(0,a.jsxs)("div",{className:"mc-dialog-actions",children:[(0,a.jsx)("button",{ref:m,type:"button",className:"lk-btn lk-btn-ghost",onClick:r,disabled:c,children:"Cancel"}),(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-danger",onClick:()=>{y();},disabled:c,"aria-busy":c,children:c?v?"Deleting…":"Forgetting…":v?"Delete permanently":"Forget permanently"})]})]})});}function dT(e){let{record:t,onRecordChange:n,acceptImpl:l=nc,rejectImpl:r=nd,pinImpl:s=nl,unpinImpl:o=na,archiveImpl:c=ni,deleteImpl:d=ns,correctImpl:u=no}=e,[p,m]=(0,i.useState)(null),[h,f]=(0,i.useState)(null),[g,v]=(0,i.useState)(null),[b,x]=(0,i.useState)(!1),[y,w]=(0,i.useState)(!1),[j,k]=(0,i.useState)(!1),[N,S]=(0,i.useState)(!1),C=(0,i.useCallback)(async(e,t)=>{if(null===p){m(e),f(null),v(null);try{await t();}catch(e){f(ds(e));}finally{m(null);}}},[p]),I=(0,i.useCallback)(()=>{C("accept",async()=>{n((await l(t.id)).memory);});},[l,n,t.id,C]),R=(0,i.useCallback)(()=>{C("reject",async()=>{n((await r(t.id,"rejected by user in MemoriaViva")).memory);});},[n,t.id,r,C]),E=(0,i.useCallback)(()=>{C("pin",async()=>{n((await s(t.id)).memory);});},[n,s,t.id,C]),$=(0,i.useCallback)(()=>{C("unpin",async()=>{n((await o(t.id)).memory);});},[n,t.id,C,o]),A=(0,i.useCallback)(()=>{C("archive",async()=>{n((await c(t.id,"archived by user in MemoriaViva")).memory);});},[c,n,t.id,C]),F=(0,i.useCallback)(e=>{w(!1),v(`Correction submitted for review: ${e.body}`);},[]),T="proposed"===t.status,D="accepted"===t.status||"superseded"===t.status||"conflicted"===t.status||"expired"===t.status,q="forgotten"===t.status;return(0,a.jsxs)("div",{className:"mc-actions",role:"group","aria-label":"Memory actions",children:[T?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-primary","aria-disabled":null!==p,"aria-busy":"accept"===p,onClick:I,"aria-label":"Approve this memory proposal",children:"accept"===p?"Approving…":"Approve"}),(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==p,"aria-busy":"reject"===p,onClick:R,"aria-label":"Reject this memory proposal",children:"reject"===p?"Rejecting…":"Reject"})]}):null,q?null:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==p,onClick:()=>{null===p&&(f(null),v(null),x(!0));},"aria-label":"Edit memory body, tags, or sensitivity",children:"Edit"}),(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==p,onClick:()=>{null===p&&(f(null),v(null),w(!0));},"aria-label":"Create a correction proposal for this memory",children:"Correct"})]}),q?null:t.pinned?(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==p,"aria-busy":"unpin"===p,onClick:$,"aria-label":"Unpin this memory",children:"unpin"===p?"Unpinning…":"Unpin"}):(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==p,"aria-busy":"pin"===p,onClick:E,"aria-label":"Pin this memory for priority retrieval",children:"pin"===p?"Pinning…":"Pin"}),D?(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==p,"aria-busy":"archive"===p,onClick:A,"aria-label":"Archive this memory",children:"archive"===p?"Archiving…":"Archive"}):null,q?null:(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-danger","aria-disabled":null!==p,onClick:()=>{null===p&&(f(null),v(null),k(!0));},"aria-label":"Forget this memory permanently",children:"Forget"}),(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-danger","aria-disabled":null!==p,onClick:()=>{null===p&&(f(null),v(null),S(!0));},"aria-label":"Delete this memory record",children:"Delete"}),null!==h?(0,a.jsx)("p",{role:"alert","aria-live":"assertive",className:"mc-action-error",children:h}):null,null!==g?(0,a.jsx)("p",{role:"status","aria-live":"polite",className:"mc-action-notice",children:g}):null,b?(0,a.jsx)(dA,{record:t,onSave:e=>{x(!1),n(e);},onClose:()=>{x(!1);}}):null,y?(0,a.jsx)(dA,{mode:"correct",record:t,correctMemoryImpl:u,onSave:F,onClose:()=>{w(!1);}}):null,j?(0,a.jsx)(dF,{record:t,onComplete:()=>{k(!1),n(null);},onClose:()=>{k(!1);}}):null,N?(0,a.jsx)(dF,{mode:"delete",record:t,deleteMemoryImpl:d,onComplete:()=>{S(!1),n(null);},onClose:()=>{S(!1);}}):null]});}function dD(e){return new Date(e).toLocaleString();}function dq(e){let{label:t,value:n}=e;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("dt",{className:"mc-meta-label",children:t}),(0,a.jsx)("dd",{className:"mc-meta-value",children:n})]});}function dM(e){let{provenance:t}=e;return(0,a.jsxs)("section",{"aria-label":"Provenance",className:"mc-section",children:[(0,a.jsx)("h2",{className:"lk-section-head",children:"Provenance"}),(0,a.jsxs)("dl",{className:"mc-meta",children:[(0,a.jsx)(dq,{label:"Source kind",value:t.sourceKind}),(0,a.jsx)(dq,{label:"Captured at",value:dD(t.capturedAt)}),(0,a.jsx)(dq,{label:"Confidence",value:`${(100*t.confidence).toFixed(0)}%`}),(0,a.jsx)(dq,{label:"Sensitivity",value:t.sensitivity}),void 0!==t.captureRationale?(0,a.jsx)(dq,{label:"Rationale",value:t.captureRationale}):null,void 0!==t.modelIdentity?(0,a.jsx)(dq,{label:"Model",value:`${t.modelIdentity.provider} / ${t.modelIdentity.modelId}`}):null]})]});}function dP(e){let{validity:t}=e;return(0,a.jsxs)("section",{"aria-label":"Validity",className:"mc-section",children:[(0,a.jsx)("h2",{className:"lk-section-head",children:"Validity"}),(0,a.jsxs)("dl",{className:"mc-meta",children:[(0,a.jsx)(dq,{label:"Valid from",value:dD(t.validFrom)}),(0,a.jsx)(dq,{label:"Valid until",value:void 0!==t.validUntil?dD(t.validUntil):"No expiry"})]})]});}function dL(e){let{tags:t}=e;return 0===t.length?(0,a.jsx)("span",{className:"mc-meta-empty",children:"No tags"}):(0,a.jsx)("ul",{className:"mc-tags","aria-label":"Tags",children:t.map(e=>(0,a.jsx)("li",{className:"mc-tag",children:e},e))});}function dz(e){let{onBack:t,controlRef:n,children:l="Back to MemoriaViva"}=e;return void 0!==t?(0,a.jsx)("button",{ref:n,type:"button",className:"mc-back-link lk-btn lk-btn-ghost",onClick:t,children:l}):(0,a.jsx)(di(),{ref:n,href:"/memoriaviva",className:"mc-back-link lk-btn lk-btn-ghost","aria-label":"Back to MemoriaViva",children:l});}function dO(e){let{record:t,onBack:n}=e;return(0,a.jsxs)("header",{className:"mc-detail-header",children:[(0,a.jsxs)("div",{className:"mc-detail-title-row",children:[(0,a.jsxs)("h1",{className:"lk-title",style:{flex:1},children:[dN[t.type]," memory"]}),(0,a.jsx)("span",{className:`mc-badge mc-badge-${t.status}`,children:t.status}),t.pinned?(0,a.jsx)("span",{"aria-label":"Pinned",className:"mc-badge mc-badge-pinned",children:"Pinned"}):null]}),(0,a.jsx)(dz,{onBack:n,children:"Back"})]});}function dK(e){let{id:t,fetchMemoryImpl:n=nt,onBack:l}=e,[r,s]=(0,i.useState)(null),[o,c]=(0,i.useState)(!0),[d,u]=(0,i.useState)(null),[p,m]=(0,i.useState)(!1),h=(0,i.useRef)(null),f=(0,i.useCallback)(e=>{h.current=e;},[]),g=(0,i.useCallback)(e=>{null===e&&m(!0),s(e);},[]);(0,i.useEffect)(()=>{var e;p&&null===r&&(null==(e=h.current)||e.focus());},[p,r]);let v=(0,i.useCallback)(async()=>{c(!0),u(null);try{let e=await n(t);s(e.memory);}catch(e){u(ds(e));}finally{c(!1);}},[t,n]);return((0,i.useEffect)(()=>{v();},[v]),o)?(0,a.jsx)("p",{role:"status","aria-live":"polite",className:"lk-loading",children:"Loading memory…"}):null!==d?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{role:"alert","aria-live":"assertive",className:"lk-alert",children:[d,(0,a.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>{v();},children:"Retry"})]}),(0,a.jsx)("p",{children:(0,a.jsx)(dz,{onBack:l})})]}):null===r?(0,a.jsx)("div",{className:"lk-empty",children:(0,a.jsxs)("div",{children:[(0,a.jsx)("p",{className:"lk-empty-title",children:p?"Memory removed":"Memory not found"}),(0,a.jsx)("p",{role:"status","aria-live":"polite",className:"lk-empty-body",children:p?"The memory was forgotten or deleted and is no longer available.":"This memory may have been deleted. Open a memory from the list instead."}),(0,a.jsx)("p",{children:(0,a.jsx)(dz,{onBack:l,controlRef:f})})]})}):(0,a.jsxs)("article",{"aria-label":`Memory record: ${r.body.slice(0,60)}`,className:"mc-detail",children:[(0,a.jsx)(dO,{record:r,onBack:l}),(0,a.jsxs)("section",{"aria-label":"Memory body",className:"mc-section",children:[(0,a.jsx)("h2",{className:"lk-section-head",children:"Content"}),(0,a.jsx)("p",{className:"mc-body-text",children:r.body})]}),(0,a.jsxs)("section",{"aria-label":"Details",className:"mc-section",children:[(0,a.jsx)("h2",{className:"lk-section-head",children:"Details"}),(0,a.jsxs)("dl",{className:"mc-meta",children:[(0,a.jsx)(dq,{label:"ID",value:(0,a.jsx)("code",{className:"mc-code",children:r.id})}),(0,a.jsx)(dq,{label:"Scope",value:function(e){switch(e.kind){case"user":return`user:${e.userId}`;case"workspace":return`workspace:${e.workspaceId}`;case"project":return`project:${e.projectId}`;case"workflow":return`workflow:${e.workflowDefinitionId}`;case"global":return"global";default:return"unknown";}}(r.scope)}),(0,a.jsx)(dq,{label:"Type",value:dN[r.type]}),(0,a.jsx)(dq,{label:"Created",value:dD(r.createdAt)}),(0,a.jsx)(dq,{label:"Updated",value:dD(r.updatedAt)}),void 0!==r.staleReason?(0,a.jsx)(dq,{label:"Stale reason",value:(0,a.jsx)("em",{children:r.staleReason})}):null]})]}),(0,a.jsx)(dM,{provenance:r.provenance}),(0,a.jsx)(dP,{validity:r.validity}),(0,a.jsxs)("section",{"aria-label":"Tags",className:"mc-section",children:[(0,a.jsx)("h2",{className:"lk-section-head",children:"Tags"}),(0,a.jsx)(dL,{tags:r.tags})]}),(0,a.jsxs)("section",{"aria-label":"Actions",className:"mc-section",children:[(0,a.jsx)("h2",{className:"lk-section-head",children:"Actions"}),(0,a.jsx)(dT,{record:r,onRecordChange:g})]})]});}var dB=n(79748);let dW={proposed:"mc-badge-proposed",accepted:"mc-badge-accepted",conflicted:"mc-badge-conflicted",rejected:"mc-badge-rejected",archived:"mc-badge-archived",forgotten:"mc-badge-forgotten",superseded:"mc-badge-superseded",expired:"mc-badge-expired"};function dU(e){var t;let{status:n}=e,l=null!=(t=dW[n])?t:"mc-badge-default";return(0,a.jsx)("span",{className:`mc-badge ${l}`,children:n});}function d_(e){var t;let{record:n,onOpenDetail:l}=e,i=(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"mc-row-main",children:[(0,a.jsx)("span",{className:"mc-row-body",title:n.body,children:n.body}),(0,a.jsxs)("div",{className:"mc-row-meta",children:[(0,a.jsx)("span",{className:"mc-row-type",children:dN[n.type]}),(0,a.jsx)("span",{className:"mc-row-scope",children:dk[n.scope.kind]}),(0,a.jsxs)("span",{className:"mc-row-source",children:["Source ",n.provenance.sourceKind]}),(0,a.jsx)("span",{className:"mc-row-confidence",children:(t=n.provenance.confidence,`${(100*t).toFixed(0)}% confidence`)}),(0,a.jsxs)("span",{className:"mc-row-sensitivity",children:["Sensitivity ",n.provenance.sensitivity]}),n.pinned?(0,a.jsx)("span",{className:"mc-badge mc-badge-pinned",children:"Pinned"}):null]})]}),(0,a.jsx)(dU,{status:n.status})]});return(0,a.jsx)("li",{children:void 0!==l?(0,a.jsx)("button",{type:"button",className:"mc-row mc-row-button",onClick:()=>l(n.id),children:i}):(0,a.jsx)(di(),{href:`/memoriaviva/detail?id=${encodeURIComponent(n.id)}`,className:"mc-row",children:i})});}function dV(e){let{hasFilters:t}=e;return(0,a.jsx)("div",{"data-testid":"memory-empty-state",className:"lk-empty",children:(0,a.jsxs)("div",{children:[(0,a.jsx)("p",{className:"lk-empty-title",children:"No memories found"}),(0,a.jsx)("p",{className:"lk-empty-body",children:t?"Try removing some filters to see more memories.":"Memories will appear here once the system captures them from your conversations and workflows."})]})});}function dH(e){let{filters:t,onFilterChange:n,fetchMemoriesImpl:l=t5,onOpenDetail:r,onOpenConsolidation:s,onOpenReviewQueue:o,policyEnabled:c,onPolicyEnabledChange:d,showWorkspaceBackLink:u=!0}=e,[p,m]=(0,i.useState)([]),[h,f]=(0,i.useState)(!0),[g,v]=(0,i.useState)(null),[b,x]=(0,i.useState)(!0),y=null!=c?c:b,w=t.scope.length>0||t.type.length>0||t.status.length>0||t.sensitivity.length>0,j=(0,i.useCallback)(async e=>{f(!0),v(null);try{let t=await l(e);m(t.memories);}catch(e){v(ds(e));}finally{f(!1);}},[l]);return(0,i.useEffect)(()=>{j(t);},[t,j]),(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("header",{className:"lk-header",children:[(0,a.jsx)("h1",{className:"lk-title",children:"MemoriaViva"}),(0,a.jsxs)("div",{className:"mc-view-actions",children:[(0,a.jsxs)("div",{className:"mc-policy-switch",children:[(0,a.jsx)(aA,{on:y,onChange:null!=d?d:x,label:"Enable MemoriaViva policy"}),(0,a.jsxs)("span",{children:["Policy ",y?"on":"off"]})]}),u?(0,a.jsx)(di(),{href:"/",className:"lk-btn lk-btn-ghost lk-btn-lg",children:"Back to Workspace"}):null,void 0!==s?(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost lk-btn-lg",onClick:s,children:"Consolidation"}):(0,a.jsx)(di(),{href:"/memoriaviva/consolidation",className:"lk-btn lk-btn-ghost lk-btn-lg",children:"Consolidation"}),void 0!==o?(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost lk-btn-lg mc-queue-link",onClick:o,children:"Review queue"}):(0,a.jsx)(di(),{href:"/memoriaviva/review-queue",className:"lk-btn lk-btn-ghost lk-btn-lg mc-queue-link",children:"Review queue"})]})]}),(0,a.jsx)(dE,{filters:t,onChange:n}),(0,a.jsx)("p",{role:"status",className:"visually-hidden",children:h||null!==g?null:`${p.length.toString()} ${1===p.length?"memory":"memories"} found`}),(0,a.jsx)("section",{"aria-label":"Memory records","aria-busy":h,style:{flex:1,minHeight:0,overflowY:"auto"},children:h&&0===p.length?(0,a.jsx)("p",{role:"status","aria-live":"polite",className:"lk-loading",children:"Loading memories…"}):null!==g?(0,a.jsxs)("div",{role:"alert","aria-live":"assertive",className:"lk-alert",children:[g,(0,a.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>{j(t);},children:"Retry"})]}):0===p.length?(0,a.jsx)(dV,{hasFilters:w}):(0,a.jsx)("ul",{"aria-label":"Memory list",style:{listStyle:"none",padding:0,margin:0,display:"flex",flexDirection:"column",gap:4,opacity:h?.6:1,transition:"opacity 0.15s ease"},children:p.map(e=>(0,a.jsx)(d_,{record:e,onOpenDetail:r},e.id))})})]});}function dJ(e){let{record:t,busyAction:n,rowError:l,onAccept:i,onReject:r,onArchive:s,onOpenDetail:o}=e,c=`memory-review-body-${t.id}`,d=`View details for memory ${t.id}: ${t.body.slice(0,80)}`,u=void 0!==t.staleReason||"expired"===t.status;return(0,a.jsx)("li",{"data-review-row-id":t.id,children:(0,a.jsxs)("article",{className:"mc-review-row",children:[(0,a.jsxs)("div",{className:"mc-review-body",children:[(0,a.jsx)("p",{id:c,className:"mc-row-body",children:t.body}),(0,a.jsxs)("div",{className:"mc-row-meta",children:[(0,a.jsx)("span",{className:"mc-row-type",children:dN[t.type]}),(0,a.jsx)("span",{className:"mc-row-scope",children:dk[t.scope.kind]}),(0,a.jsx)("span",{className:`mc-badge mc-badge-${t.status}`,children:t.status}),u?(0,a.jsxs)("span",{className:"mc-row-stale",children:["Stale",void 0!==t.staleReason?`: ${t.staleReason}`:""]}):null,void 0!==o?(0,a.jsx)("button",{type:"button",className:"mc-row-detail-link mc-link-button","aria-label":d,onClick:()=>o(t.id),children:"View details"}):(0,a.jsx)(di(),{href:`/memoriaviva/detail?id=${encodeURIComponent(t.id)}`,className:"mc-row-detail-link","aria-label":d,children:"View details"})]}),null!==l?(0,a.jsx)("p",{role:"alert",className:"mc-action-error",children:l}):null]}),(0,a.jsx)("div",{className:"mc-review-actions",role:"group","aria-labelledby":c,children:"proposed"===t.status?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-primary","aria-disabled":null!==n,"aria-busy":"accept"===n,onClick:()=>{null===n&&i(t);},children:"accept"===n?"Approving…":"Approve"}),(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==n,"aria-busy":"reject"===n,onClick:()=>{null===n&&r(t);},children:"reject"===n?"Rejecting…":"Reject"})]}):"conflicted"===t.status?(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==n,"aria-busy":"reject"===n,onClick:()=>{null===n&&r(t);},children:"reject"===n?"Rejecting…":"Reject conflict"}):(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==n,"aria-busy":"archive"===n,onClick:()=>{null===n&&s(t);},children:"archive"===n?"Archiving…":"Archive stale"})})]})});}function dY(e){let{fetchQueueImpl:t=t8,acceptImpl:n=nc,rejectImpl:l=nd,archiveImpl:r=ni,onBack:s,onOpenDetail:o}=e,[c,d]=(0,i.useState)([]),[u,p]=(0,i.useState)(!0),[m,h]=(0,i.useState)(null),[f,g]=(0,i.useState)({}),[v,b]=(0,i.useState)({}),[x,y]=(0,i.useState)(""),w=(0,i.useRef)(null),j=(0,i.useRef)(null),k=(0,i.useRef)(null),N=(0,i.useCallback)(async()=>{p(!0),h(null);try{let e=await t();d(e.memories),g({}),b({});}catch(e){h(ds(e));}finally{p(!1);}},[t]);(0,i.useEffect)(()=>{N();},[N]);let S=(0,i.useCallback)(e=>{g(t=>{let n={...t};return delete n[e],n;}),b(t=>{let n={...t};return delete n[e],n;});},[]),C=(0,i.useCallback)(e=>{var t;let n=c.findIndex(t=>t.id===e),l=null!=(t=c[n+1])?t:c[n-1];k.current=void 0!==l?l.id:"",d(t=>t.filter(t=>t.id!==e)),S(e);},[c,S]);(0,i.useEffect)(()=>{var e,t,n;let l=k.current;if(null===l)return;k.current=null;let a=""===l?null:null!=(e=null==(t=w.current)?void 0:t.querySelector(`[data-review-row-id="${CSS.escape(l)}"]`))?e:null,i=null===a?null:a.querySelector("button");null!==i?i.focus():null==(n=j.current)||n.focus();},[c]);let I=(0,i.useCallback)(async(e,t)=>{let a=e.id;g(e=>({...e,[a]:t})),b(e=>{let t={...e};return delete t[a],t;});try{"accept"===t?await n(a):"archive"===t?await r(a,"archived stale memory from review queue"):await l(a,"conflicted"===e.status?"rejected conflict from review queue":"rejected from review queue"),C(a),y("accept"===t?"Memory approved":"archive"===t?"Memory archived":"Memory rejected");}catch(e){b(t=>({...t,[a]:ds(e)})),g(e=>{let t={...e};return delete t[a],t;});}},[n,r,l,C]);return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("header",{className:"lk-header mc-review-header",children:[(0,a.jsx)("h1",{className:"lk-title",tabIndex:-1,ref:j,children:"Review queue"}),(0,a.jsxs)("span",{role:"status","aria-live":"polite",className:"mc-badge-count",children:[c.length.toString()," awaiting review"]}),void 0!==s?(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost lk-btn-lg","aria-label":"Back to MemoriaViva",onClick:s,children:"Back"}):(0,a.jsx)(di(),{href:"/memoriaviva",className:"lk-btn lk-btn-ghost lk-btn-lg","aria-label":"Back to MemoriaViva",children:"Back"})]}),(0,a.jsx)("p",{role:"status",className:"visually-hidden",children:x}),(0,a.jsx)("section",{"aria-label":"Memories awaiting review","aria-busy":u,style:{flex:1,minHeight:0,overflowY:"auto"},children:u?(0,a.jsx)("p",{role:"status","aria-live":"polite",className:"lk-loading",children:"Loading review queue…"}):null!==m?(0,a.jsxs)("div",{role:"alert","aria-live":"assertive",className:"lk-alert",children:[m,(0,a.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>{N();},children:"Retry"})]}):0===c.length?(0,a.jsx)("div",{"data-testid":"review-queue-empty",className:"lk-empty",children:(0,a.jsxs)("div",{children:[(0,a.jsx)("p",{className:"lk-empty-title",children:"Queue is clear"}),(0,a.jsx)("p",{className:"lk-empty-body",children:"No memories are waiting for review. Proposed, conflicted, and stale memories appear here."})]})}):(0,a.jsx)("ul",{ref:w,"aria-label":"Review queue",style:{listStyle:"none",padding:0,margin:0,display:"flex",flexDirection:"column",gap:8},children:c.map(e=>{var t,n;return(0,a.jsx)(dJ,{record:e,busyAction:null!=(t=f[e.id])?t:null,rowError:null!=(n=v[e.id])?n:null,onAccept:e=>{I(e,"accept");},onReject:e=>{I(e,"reject");},onArchive:e=>{I(e,"archive");},onOpenDetail:o},e.id);})})})]});}let dX={scope:[],type:[],status:[],sensitivity:[]};function dG(){let[e,t]=(0,i.useState)({kind:"list"}),[n,l]=(0,i.useState)(dX),[r,s]=(0,i.useState)(!0),o=(0,i.useCallback)(()=>{t({kind:"list"});},[]),c=(0,i.useCallback)(e=>{t({kind:"detail",id:e});},[]);return(0,a.jsx)("div",{className:"memoria-window",children:"list"===e.kind?(0,a.jsx)(dH,{filters:n,onFilterChange:l,onOpenDetail:c,onOpenConsolidation:()=>t({kind:"consolidation"}),onOpenReviewQueue:()=>t({kind:"reviewQueue"}),policyEnabled:r,onPolicyEnabledChange:s,showWorkspaceBackLink:!1}):"detail"===e.kind?(0,a.jsx)(dK,{id:e.id,onBack:o}):"consolidation"===e.kind?(0,a.jsx)(db,{onBack:o,onOpenDetail:c}):(0,a.jsx)(dY,{onBack:o,onOpenDetail:c})});}var dQ=n(19217),dZ=n(25780),d0=n(23934);function d1(e){return Array.from(e.querySelectorAll("button:not([disabled]),input:not([disabled]),[tabindex]:not([tabindex='-1'])"));}function d2(e){let{capsule:t,checked:n,disabled:l,onToggle:i}=e;return(0,a.jsx)("li",{className:"lk-compose-member",children:(0,a.jsxs)("label",{className:"lk-compose-member-label",children:[(0,a.jsx)("input",{type:"checkbox",checked:n,disabled:l,onChange:()=>i(t.id)}),(0,a.jsx)("span",{className:"lk-compose-member-name",title:t.displayName,children:t.displayName}),(0,a.jsx)("span",{className:"lk-badge","data-state":t.lifecycleState,children:dZ.Z[t.lifecycleState]})]})});}function d3(e){let t,{capsules:n,onCancel:l,onCreated:r,createImpl:s=aF.WM}=e,o=(0,i.useId)(),c=(0,i.useId)(),d=(0,i.useId)(),u=(0,i.useRef)(null),[p,m]=(0,i.useState)(""),[h,f]=(0,i.useState)(new Set()),[g,v]=(0,i.useState)(!1),[b,x]=(0,i.useState)(null);function y(e){f(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n;}),null!==b&&x(null);}async function w(e){var t;e.preventDefault();let n=(t=h.size,0===p.trim().length?"Set name is required.":0===t?"Select at least one capsule to combine.":t>16?"A set can hold at most 16 capsules.":null);if(null!==n)return void x(n);v(!0),x(null);try{await s({displayName:p.trim(),capsuleIds:[...h]}),r();}catch(e){x((0,d0.W)(e));}finally{v(!1);}}(0,dQ.i)(),(0,i.useEffect)(()=>{var e;let t=document.activeElement,n=u.current;return null!==n&&(null==(e=d1(n)[0])||e.focus()),()=>{var e;return null==t||null==(e=t.focus)?void 0:e.call(t);};},[u]),(0,i.useEffect)(()=>{let e=u.current;if(null!==e)return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t);function t(t){if("Escape"===t.key&&!g){t.preventDefault(),l();return;}if("Tab"!==t.key)return;let n=d1(e);if(0===n.length)return void t.preventDefault();let a=n[0],i=n[n.length-1];t.shiftKey&&document.activeElement===a?(t.preventDefault(),null==i||i.focus()):t.shiftKey||document.activeElement!==i||(t.preventDefault(),null==a||a.focus());}},[u,g,l]),t=(0,i.useRef)(!1),(0,i.useEffect)(()=>{let e=u.current;if(null!==e){if(g)t.current=!0,e.focus();else if(t.current){var n;t.current=!1,null==(n=d1(e)[0])||n.focus();}}},[u,g]);let j="Set name is required."===b,k="Select at least one capsule to combine."===b;return(0,tM.createPortal)((0,a.jsx)("div",{className:"mc-dialog-backdrop",role:"presentation",children:(0,a.jsxs)("div",{ref:u,className:"mc-dialog",role:"dialog","aria-modal":"true","aria-labelledby":o,tabIndex:-1,children:[(0,a.jsx)("h2",{id:o,className:"mc-dialog-title",children:"Combine capsules into a set"}),(0,a.jsxs)("form",{onSubmit:e=>void w(e),children:[(0,a.jsxs)("label",{className:"mc-dialog-field",htmlFor:c,children:[(0,a.jsx)("span",{className:"mc-dialog-label",children:"Set name"}),(0,a.jsx)("input",{id:c,className:"mc-dialog-input",value:p,disabled:g,autoComplete:"off","aria-invalid":j,"aria-describedby":j?d:void 0,onChange:e=>{m(e.target.value),null!==b&&x(null);}})]}),(0,a.jsxs)("fieldset",{className:"lk-compose-fieldset",disabled:g,"aria-invalid":k,"aria-describedby":k?d:void 0,children:[(0,a.jsxs)("legend",{className:"mc-dialog-label",children:["Capsules (",h.size.toString(),"/","16",")"]}),0===n.length?(0,a.jsx)("p",{className:"lkd-empty-note",children:"No capsules available to combine."}):(0,a.jsx)("ul",{className:"lk-compose-member-list","aria-label":"Selectable capsules",children:n.map(e=>(0,a.jsx)(d2,{capsule:e,checked:h.has(e.id),disabled:g,onToggle:y},e.id))})]}),null!==b?(0,a.jsx)("div",{id:d,role:"alert","aria-live":"assertive",className:"mc-dialog-error",children:b}):null,(0,a.jsxs)("div",{className:"mc-dialog-actions",children:[(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",disabled:g,onClick:l,children:"Cancel"}),(0,a.jsx)("button",{type:"submit",className:"lk-btn lk-btn-primary",disabled:g,"aria-busy":g,children:g?"Combining…":"Combine"})]})]})]})}),document.body);}var d4=n(68835);function d6(e){let{message:t,onRetry:n,onDismiss:l}=e;return(0,a.jsxs)("div",{role:"alert","aria-live":"assertive",className:"lk-alert",children:[t,void 0!==n?(0,a.jsx)("button",{type:"button",onClick:n,"aria-label":"Retry loading capsules",className:"lk-alert-retry",children:"Retry"}):null,void 0!==l?(0,a.jsx)("button",{type:"button",onClick:l,"aria-label":"Dismiss error message",className:"lk-alert-retry",children:"Dismiss"}):null]});}function d5(e){return Array.from(e.querySelectorAll("button:not([disabled]),input:not([disabled]),textarea:not([disabled]),select:not([disabled]),[tabindex]:not([tabindex='-1'])"));}function d8(e){let{busy:t,error:n,onCancel:l,onSubmit:r}=e,s=(0,i.useId)(),o=(0,i.useId)(),c=(0,i.useId)(),d=(0,i.useId)(),u=(0,i.useRef)(null),p=(0,i.useRef)(null),m=(0,i.useRef)(null),[h,f]=(0,i.useState)(""),[g,v]=(0,i.useState)(null);(0,dQ.i)(),(0,i.useEffect)(()=>{var e;return m.current=document.activeElement,null==(e=p.current)||e.focus(),()=>{var e,t;null==(t=m.current)||null==(e=t.focus)||e.call(t);};},[]),(0,i.useEffect)(()=>{let e=u.current;if(null===e)return;let n=n=>{if("Escape"===n.key&&!t){n.preventDefault(),l();return;}if("Tab"!==n.key)return;let a=d5(e);if(0===a.length)return void n.preventDefault();let i=a[0],r=a[a.length-1];n.shiftKey&&document.activeElement===i?(n.preventDefault(),null==r||r.focus()):n.shiftKey||document.activeElement!==r||(n.preventDefault(),null==i||i.focus());};return e.addEventListener("keydown",n),()=>e.removeEventListener("keydown",n);},[t,l]);let b=(0,i.useRef)(!1);async function x(e){e.preventDefault();let t=h.trim();0===t.length?v("Capsule display name is required."):(v(null),await r(t));}(0,i.useEffect)(()=>{let e=u.current;if(null!==e){if(t)b.current=!0,e.focus();else if(b.current){var n;b.current=!1,null==(n=d5(e)[0])||n.focus();}}},[t]);let y=null!=g?g:n;return(0,tM.createPortal)((0,a.jsx)("div",{className:"mc-dialog-backdrop",role:"presentation",children:(0,a.jsxs)("div",{ref:u,className:"mc-dialog",role:"dialog","aria-modal":"true","aria-labelledby":s,"aria-describedby":o,tabIndex:-1,children:[(0,a.jsx)("h2",{id:s,className:"mc-dialog-title",children:"Create capsule"}),(0,a.jsx)("p",{id:o,className:"mc-dialog-body",children:"Name the capsule. After creating it, connect a source and start indexing from the capsule page."}),(0,a.jsxs)("form",{onSubmit:e=>void x(e),children:[(0,a.jsxs)("label",{className:"mc-dialog-field",htmlFor:c,children:[(0,a.jsx)("span",{className:"mc-dialog-label",children:"Capsule display name"}),(0,a.jsx)("input",{id:c,ref:p,className:"mc-dialog-input",value:h,disabled:t,autoComplete:"off","aria-invalid":null!==y,"aria-describedby":null!==y?d:void 0,onChange:e=>{f(e.target.value),null!==g&&v(null);}})]}),null!==y?(0,a.jsx)("div",{id:d,role:"alert","aria-live":"assertive",className:"mc-dialog-error",children:y}):null,(0,a.jsxs)("div",{className:"mc-dialog-actions",children:[(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",disabled:t,onClick:l,children:"Cancel"}),(0,a.jsx)("button",{type:"submit",className:"lk-btn lk-btn-primary",disabled:t,children:t?"Creating…":"Create capsule"})]})]})]})}),document.body);}function d7(e){let{capsuleName:t,onCancel:n,onConfirm:l}=e,r=(0,i.useId)(),s=(0,i.useId)(),o=(0,i.useRef)(null);return(0,dQ.i)(),(0,i.useEffect)(()=>{var e;let t=document.activeElement,n=o.current;return null!==n&&(null==(e=d5(n)[0])||e.focus()),()=>{var e;return null==t||null==(e=t.focus)?void 0:e.call(t);};},[]),(0,i.useEffect)(()=>{let e=o.current;if(null===e)return;let t=t=>{if("Escape"===t.key){t.preventDefault(),n();return;}if("Tab"!==t.key)return;let l=d5(e);if(0===l.length)return void t.preventDefault();let a=l[0],i=l[l.length-1];t.shiftKey&&document.activeElement===a?(t.preventDefault(),null==i||i.focus()):t.shiftKey||document.activeElement!==i||(t.preventDefault(),null==a||a.focus());};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t);},[n]),(0,tM.createPortal)((0,a.jsx)("div",{className:"mc-dialog-backdrop",role:"presentation",children:(0,a.jsxs)("div",{ref:o,className:"mc-dialog",role:"dialog","aria-modal":"true","aria-labelledby":r,"aria-describedby":s,tabIndex:-1,children:[(0,a.jsx)("h2",{id:r,className:"mc-dialog-title",children:"Disconnect capsule"}),(0,a.jsxs)("p",{id:s,className:"mc-dialog-body",children:['Disconnect "',t,'"? The capsule keeps its index, but the source link is removed.']}),(0,a.jsxs)("div",{className:"mc-dialog-actions",children:[(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:n,children:"Cancel"}),(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-danger",onClick:l,children:"Disconnect"})]})]})}),document.body);}function d9(e){let{state:t}=e;return(0,a.jsx)("span",{className:"lk-badge","data-state":t,children:dZ.Z[t]});}function ue(e){let{capsule:t,busy:n,busyKind:l,onStart:r,onCancel:s}=e,{id:o,displayName:c,lifecycleState:d,sourceCount:u}=t,p=(0,i.useId)();if("indexing"===d)return(0,a.jsx)("button",{type:"button",disabled:n,"aria-busy":"cancel"===l,"aria-label":`Cancel indexing for capsule ${c}`,onClick:()=>{s(o);},className:"lk-btn lk-btn-ghost",children:"cancel"===l?"Cancelling…":"Cancel"});let m=u>0;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("button",{type:"button",disabled:n,"aria-disabled":!m||void 0,"aria-busy":"index"===l,"aria-label":`Start indexing capsule ${c}`,"aria-describedby":m?void 0:p,title:m?void 0:"Attach a source before indexing this capsule.",onClick:()=>{m&&r(o);},className:"lk-btn lk-btn-primary",children:"index"===l?"Indexing…":"Index"}),m?null:(0,a.jsx)("span",{id:p,className:"visually-hidden",children:"Attach a source before indexing."})]});}function ut(e){let{capsule:t,busy:n,busyKind:l,onStart:i,onCancel:r,onDisconnect:s,onHealth:o,onAddToWorkspace:c}=e,{id:d,displayName:u}=t;return(0,a.jsxs)("div",{role:"group","aria-label":`Actions for capsule ${u}`,className:"lk-capsule-actions",children:[(0,a.jsx)(ue,{capsule:t,busy:n,busyKind:l,onStart:i,onCancel:r}),(0,a.jsx)("button",{type:"button",disabled:n,"aria-label":`Add capsule ${u} to workspace`,onClick:()=>{c(d);},className:"lk-btn lk-btn-ghost",children:"Add to workspace"}),(0,a.jsx)("button",{type:"button",disabled:n,"aria-label":`Open details for capsule ${u}`,onClick:()=>{o(d);},className:"lk-btn lk-btn-ghost",children:"Details"}),(0,a.jsx)("button",{type:"button",disabled:n,"aria-busy":"disconnect"===l,"aria-label":`Disconnect capsule ${u}`,onClick:()=>{s(d);},className:"lk-btn lk-btn-danger",children:"disconnect"===l?"Disconnecting…":"Disconnect"})]});}function un(e){return e instanceof Element&&null!==e.closest(".lk-capsule-actions,a,input,select,textarea");}function ul(e,t){let n=document.elementFromPoint(e,t);return n instanceof Element&&null!==n.closest("main.workspace")&&null===n.closest(".window");}function ua(e,t){let n={payload:e,clientX:t.clientX,clientY:t.clientY};window.dispatchEvent(new CustomEvent(tp,{detail:n}));}function ui(e){let{capsule:t,busy:n,busyKind:l,onStart:r,onCancel:s,onDisconnect:o,onHealth:c,onAddToWorkspace:d}=e,[u,p]=(0,i.useState)(null),m=(0,i.useRef)(!1),h=(0,i.useRef)(!1),f={kind:"capsule",id:t.id,label:t.displayName,lifecycleState:t.lifecycleState},g=e=>{h.current||(h.current=!0,ua(f,e),window.setTimeout(()=>{h.current=!1;},250));},v=(e,n)=>{m.current=!0;let l=!1,a=a=>{let i=a.clientX-e,r=a.clientY-n;!l&&6>Math.hypot(i,r)||(l=!0,document.body.style.cursor="grabbing",p({x:a.clientX,y:a.clientY,label:t.displayName,state:t.lifecycleState}));},i=e=>{window.removeEventListener("pointermove",a),window.removeEventListener("pointerup",i),window.removeEventListener("mousemove",a),window.removeEventListener("mouseup",i),m.current=!1,document.body.style.cursor="",p(null),l&&ul(e.clientX,e.clientY)&&g(e);};window.addEventListener("pointermove",a),window.addEventListener("pointerup",i),window.addEventListener("mousemove",a),window.addEventListener("mouseup",i);};return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("article",{"aria-label":`Capsule: ${t.displayName}`,className:"lk-capsule-row",children:[(0,a.jsxs)("button",{type:"button",className:"lk-capsule-drag-handle","aria-label":`Drag capsule ${t.displayName} to workspace`,title:"Drag to the workspace to create a connector card",onPointerDown:e=>{un(e.target)||U(e)&&(e.preventDefault(),e.stopPropagation(),v(e.clientX,e.clientY));},onMouseDown:e=>{m.current||un(e.target)||U(e)&&(e.preventDefault(),e.stopPropagation(),v(e.clientX,e.clientY));},onDragStart:e=>{un(e.target)?e.preventDefault():(e.dataTransfer.effectAllowed="copy",e.dataTransfer.setData(tu,JSON.stringify(f)),e.dataTransfer.setData("text/plain",t.displayName));},onDragEnd:e=>{ul(e.clientX,e.clientY)&&g(e);},draggable:!0,children:[(0,a.jsx)("span",{"aria-hidden":"true",className:"lk-capsule-icon",children:"⬡"}),(0,a.jsxs)("span",{className:"lk-capsule-info",children:[(0,a.jsx)("span",{className:"lk-capsule-name",title:t.displayName,children:t.displayName}),(0,a.jsx)(d9,{state:t.lifecycleState})]})]}),(0,a.jsx)(ut,{capsule:t,busy:n,busyKind:l,onStart:r,onCancel:s,onDisconnect:o,onHealth:c,onAddToWorkspace:d})]}),null!==u?(0,tM.createPortal)((0,a.jsxs)("div",{className:"lk-connector-drag-ghost",style:{left:u.x+14,top:u.y+14},"aria-hidden":"true",children:[(0,a.jsx)("span",{className:"lk-connector-drag-ghost-icon",children:"▣"}),(0,a.jsxs)("span",{className:"lk-connector-drag-ghost-copy",children:[(0,a.jsx)("span",{children:u.label}),(0,a.jsx)("small",{children:dZ.Z[u.state]})]})]}),document.body):null]});}function ur(e){let{creating:t,onCreateCapsule:n}=e;return(0,a.jsxs)("div",{"data-testid":"empty-state",className:"lk-empty",children:[(0,a.jsx)("span",{"aria-hidden":"true",className:"lk-empty-icon",children:"⬡"}),(0,a.jsxs)("div",{children:[(0,a.jsx)("p",{className:"lk-empty-title",children:"No capsules yet"}),(0,a.jsx)("p",{className:"lk-empty-body",children:"Create a capsule to start indexing your local knowledge sources."})]}),(0,a.jsx)("button",{type:"button",disabled:t,"aria-label":"Create your first knowledge capsule",onClick:n,className:"lk-btn lk-btn-primary lk-btn-xl",children:t?"Creating…":"Create your first capsule"})]});}function us(e){let{capsules:t,isLoading:n,creating:l,actionBusy:i,actionKind:r,onCreateCapsule:s,onStartIndexing:o,onCancelIndexing:c,onDisconnect:d,onOpenHealth:u}=e;return n?(0,a.jsx)("p",{role:"status","aria-live":"polite",className:"lk-loading",children:"Loading capsules…"}):0===t.length?(0,a.jsx)(ur,{creating:l,onCreateCapsule:s}):(0,a.jsx)("ul",{"aria-label":"Knowledge capsule list",style:{display:"flex",flexDirection:"column",gap:8,listStyle:"none",padding:0,margin:0},children:t.map(e=>(0,a.jsx)("li",{style:{display:"block"},children:(0,a.jsx)(ui,{capsule:e,busy:i===e.id,busyKind:i===e.id?r:null,onStart:o,onCancel:c,onDisconnect:d,onHealth:u,onAddToWorkspace:()=>{let t=function(){let e=document.querySelector("main.workspace");if(!(e instanceof HTMLElement))return null;let t=e.getBoundingClientRect();return 0===t.width||0===t.height?null:{clientX:Math.round(t.left+t.width/2),clientY:Math.round(t.top+t.height/2)};}();null!==t&&ua({kind:"capsule",id:e.id,label:e.displayName,lifecycleState:e.lifecycleState},t);}})},e.id))});}function uo(e){let{creating:t,createDialogOpen:n,combineDialogOpen:l,combineDisabled:r,showBackToWorkspace:s,loadStatus:o,loadError:c,actionError:d,createError:u,reload:p,onCreateCapsule:m,onCombineCapsules:h,onDismissCreateError:f,onDismissActionError:g}=e,v=(0,i.useId)();return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("header",{className:"lk-header",children:[(0,a.jsx)("h1",{className:"lk-title",children:"Local Knowledge Connector"}),(0,a.jsxs)("div",{className:"lk-header-actions",children:[s?(0,a.jsx)(di(),{href:"/",className:"lk-btn lk-btn-ghost lk-btn-lg",children:"Back to Workspace"}):null,(0,a.jsx)("button",{type:"button","aria-disabled":r,"aria-describedby":r?v:void 0,"aria-label":"Combine capsules into a set","aria-haspopup":"dialog","aria-expanded":l,title:r?"Create capsules first, then combine them into a set.":void 0,onClick:()=>{r||h();},className:"lk-btn lk-btn-ghost lk-btn-lg",children:"Combine capsules"}),r?(0,a.jsx)("span",{id:v,className:"visually-hidden",children:"Create capsules first, then combine them into a set."}):null,(0,a.jsx)("button",{type:"button",disabled:t,"aria-label":"Create a new knowledge capsule","aria-haspopup":"dialog","aria-expanded":n,onClick:m,className:"lk-btn lk-btn-primary lk-btn-lg",children:t?"Creating…":"Create capsule"})]})]}),"error"===o&&null!==c?(0,a.jsx)(d6,{message:c,onRetry:p}):null,null===u||n?null:(0,a.jsx)(d6,{message:u,onDismiss:f}),null!==d?(0,a.jsx)(d6,{message:d,onDismiss:g}):null]});}function uc(e){let t,n,{onOpenCapsule:l,showBackToWorkspace:r=!0}=e,[s,o]=(0,i.useState)(null),c=(0,i.useCallback)(e=>{void 0!==l?l(e):o(e);},[l]),{capsules:d,loadStatus:u,loadError:p,actionBusy:m,actionKind:h,actionError:f,creating:g,createError:v,reload:b,clearCreateError:x,clearActionError:y,handleStartIndexing:w,handleCancelIndexing:j,handleDisconnect:k,handleOpenHealth:N,handleCreateCapsule:S}=function(e){let{fetchCapsulesImpl:t=aF.xr,createCapsuleImpl:n=aF.qY,startIndexingImpl:l=aF.r,cancelIndexingImpl:a=aF.Tq,disconnectCapsuleImpl:r=aF.Qi,onOpenCapsule:s}=e,{capsules:o,loadStatus:c,loadError:d,reload:u}=function(e){let[t,n]=(0,i.useState)([]),[l,a]=(0,i.useState)("loading"),[r,s]=(0,i.useState)(null),o=(0,i.useCallback)(async()=>{a("loading"),s(null);try{let t=await e();n(t.capsules),a("ready");}catch(e){s((0,d0.W)(e)),a("error");}},[e]);return(0,i.useEffect)(()=>{o();},[o]),{capsules:t,loadStatus:l,loadError:r,reload:function(){o();}};}(t),{actionBusy:p,actionKind:m,actionError:h,clearActionError:f,handleStartIndexing:g,handleCancelIndexing:v,handleDisconnect:b,handleOpenHealth:x}=function(e,t,n,l,a){let r=(0,dB.useRouter)(),[s,o]=(0,i.useState)(null),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(null);async function m(t,n,l){o(t),d(n),p(null);try{await l(),e();}catch(e){p((0,d0.W)(e));}finally{o(null),d(null);}}return{actionBusy:s,actionKind:c,actionError:u,clearActionError:function(){p(null);},handleStartIndexing:function(e){m(e,"index",()=>t(e));},handleCancelIndexing:function(e){m(e,"cancel",()=>n(e));},handleDisconnect:function(e){m(e,"disconnect",()=>l(e));},handleOpenHealth:function(e){void 0!==a?a(e):r.push(`/local-knowledge/capsule?capsuleId=${encodeURIComponent(e)}`);}};}(u,l,a,r,s),{creating:y,createError:w,clearCreateError:j,handleCreateCapsule:k}=function(e,t){let[n,l]=(0,i.useState)(!1),[a,r]=(0,i.useState)(null);return{creating:n,createError:a,clearCreateError:function(){r(null);},handleCreateCapsule:async function n(n){l(!0),r(null);try{await e({displayName:n}),t();}catch(e){r((0,d0.W)(e));}finally{l(!1);}}};}(n,u);return{capsules:o,loadStatus:c,loadError:d,actionBusy:p,actionKind:m,actionError:h,creating:y,createError:w,reload:u,clearCreateError:j,clearActionError:f,handleStartIndexing:g,handleCancelIndexing:v,handleDisconnect:b,handleOpenHealth:x,handleCreateCapsule:k};}({...e,onOpenCapsule:c}),C="loading"===u,[I,R]=(0,i.useState)(!1),[E,$]=(0,i.useState)(!1),[A,F]=(0,i.useState)(null);async function T(e){try{await S(e),R(!1);}catch{}}return null!==s&&void 0===l?(0,a.jsxs)("div",{className:"lk-page",children:[(0,a.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost lk-btn-lg lk-back-inline",onClick:()=>{o(null),b();},children:"Back to capsules"}),(0,a.jsx)(d4.CapsuleDetail,{capsuleId:s,onDeleted:()=>{o(null),b();}})]}):(0,a.jsxs)("div",{className:"lk-page",children:[(0,a.jsx)(uo,{creating:g,createDialogOpen:I,combineDialogOpen:E,combineDisabled:C||0===d.length,showBackToWorkspace:r,loadStatus:u,loadError:p,actionError:f,createError:v,reload:b,onCreateCapsule:()=>R(!0),onCombineCapsules:()=>$(!0),onDismissCreateError:x,onDismissActionError:y}),(0,a.jsx)("p",{role:"status",className:"visually-hidden",children:C||null!==p?null:(t=d.filter(e=>"indexing"===e.lifecycleState).length,n=`${d.length.toString()} capsule${1===d.length?"":"s"}`,t>0?`${n}, ${t.toString()} indexing`:n)}),(0,a.jsxs)("section",{"aria-label":"Knowledge capsules","aria-busy":C,style:{flex:1,minHeight:0,overflowY:"auto"},children:[(0,a.jsx)("h2",{className:"lk-section-head",children:"Knowledge Capsules"}),(0,a.jsx)(us,{capsules:d,isLoading:C,creating:g,actionBusy:m,actionKind:h,onCreateCapsule:()=>R(!0),onStartIndexing:w,onCancelIndexing:j,onDisconnect:e=>{var t;return F(null!=(t=d.find(t=>t.id===e))?t:null);},onOpenHealth:N})]}),I?(0,a.jsx)(d8,{busy:g,error:v,onCancel:()=>{R(!1),x();},onSubmit:T}):null,E?(0,a.jsx)(d3,{capsules:d,onCancel:()=>$(!1),onCreated:function(){$(!1),b();}}):null,null!==A?(0,a.jsx)(d7,{capsuleName:A.displayName,onCancel:()=>F(null),onConfirm:()=>{k(A.id),F(null);}}):null]});}function ud(e,t){let n=e[t];return"string"==typeof n?n:void 0;}function uu(e,t){let n=ud(e,t);if(void 0===n||0===n.trim().length)return[];try{let e=JSON.parse(n);if(!Array.isArray(e))return[];return e.filter(e=>"string"==typeof e&&e.trim().length>0).map(e=>e.trim());}catch{return[];}}function up(e){let{cfg:t,ctx:n}=e,l=n5({autoCreate:!1}),r=(0,i.useRef)(!1),o=ud(t,"chatId"),c=ud(t,"title"),{updateCfg:d}=n,{activeChat:u,activeProject:p,chats:m,loading:h,openChat:f,openNewChat:g}=l,v=void 0!==u&&"closed"!==u.status?u:void 0;(0,i.useEffect)(()=>{if(!h){if(void 0!==o){if((null==v?void 0:v.id)===o)return;let e=m.find(e=>e.id===o&&"closed"!==e.status);void 0!==e&&f(e);return;}r.current||(r.current=!0,g(void 0,c).then(e=>{void 0!==e&&d({chatId:e.id,title:e.title});}).finally(()=>{r.current=!1;}));}},[o,null==v?void 0:v.id,m,h,f,g,c,d]),(0,i.useEffect)(()=>{h||void 0===o||(null==v?void 0:v.id)!==o||v.title!==c&&d({title:v.title});},[null==v?void 0:v.id,null==v?void 0:v.title,o,h,c,d]);let b=void 0!==o&&!l.loading&&(null==v?void 0:v.id)!==o&&!l.chats.some(e=>e.id===o&&"closed"!==e.status),x=l.loading||void 0!==o&&(null==v?void 0:v.id)!==o,y=(0,i.useCallback)(e=>{var t;if(void 0===e.runId)return;let l={runId:e.runId},a=null!=(t=e.workflowId)?t:e.taskType;void 0!==a&&(l.workflow=a),(null==p?void 0:p.path)!==void 0&&(l.workspaceRoot=p.path),n.openWindow("agents",l);},[null==p?void 0:p.path,n]);return(0,a.jsx)(s,{value:l,children:b?(0,a.jsxs)("div",{className:"lk-empty",children:[(0,a.jsx)("p",{className:"lk-empty-title",children:"Chat not found"}),(0,a.jsx)("p",{className:"lk-empty-body",children:"This conversation was deleted or is no longer available."})]}):x?(0,a.jsx)("div",{className:"lk-loading",children:"Opening chat..."}):(0,a.jsx)(a5,{mini:!0===n.mini,minimalChat:!0===n.minimalChat,compact:!0===n.compact,controlsNarrow:!0===n.controlsNarrow,barCompact:!0===n.barCompact,workflowCompact:!0===n.workflowCompact,linkedRoot:n.linkedRoot,onOpenRunResult:y})});}E("chat",(e,t)=>(0,a.jsx)(up,{cfg:e,ctx:t})),E("chatHistory",(e,t)=>(0,a.jsx)(it,{openChatWindow:e=>{t.openWindow("chat",{chatId:e.id,title:e.title});}})),E("project",()=>(0,a.jsx)(ie,{})),E("promptEnhancer",()=>(0,a.jsx)(ig,{})),E("search",()=>(0,a.jsx)(il,{})),E("plugins",()=>(0,a.jsx)(iy,{})),E("automations",()=>(0,a.jsx)(iS,{})),E("mobile",()=>(0,a.jsx)(iC,{})),E("inspector",()=>(0,a.jsx)(iI,{})),E("notifications",()=>(0,a.jsx)(iE,{})),E("resources",()=>(0,a.jsx)(i$,{})),E("activity",()=>(0,a.jsx)(iT,{})),E("keiko",()=>(0,a.jsx)(sa,{})),E("settings",()=>(0,a.jsx)(sd,{})),E("localKnowledge",()=>(0,a.jsx)(uc,{showBackToWorkspace:!1})),E("quality",(e,t)=>{var n;return(0,a.jsx)(oz,{openRun:(e,n)=>{var l;let a=void 0!==n?{[oy]:JSON.stringify(n.filter(ok))}:oN(oR({connectedFilePath:null!=(l=t.linkedFilePath)?l:null,connectedRoot:t.linkedRoot,connectedRoots:t.linkedRoots,connectedCapsuleIds:t.linkedCapsuleIds,connectedCapsuleSetIds:t.linkedCapsuleSetIds,connectedFigmaSnapshotRunIds:t.linkedFigmaSnapshotRunIds,connectedFigmaSnapshotSources:t.linkedFigmaSnapshotSources,connectedImageSources:t.linkedImageSources}));t.openWindow("qiRun",{runId:e,...a});},connectedRoot:t.linkedRoot,connectedFilePath:null!=(n=t.linkedFilePath)?n:null,connectedRoots:t.linkedRoots,connectedCapsuleIds:t.linkedCapsuleIds,connectedCapsuleSetIds:t.linkedCapsuleSetIds,connectedFigmaSnapshotRunIds:t.linkedFigmaSnapshotRunIds,connectedFigmaSnapshotSources:t.linkedFigmaSnapshotSources,connectedImageSources:t.linkedImageSources});}),E("qiRun",(e,t)=>{let n=ud(e,"runId");if(void 0===n||""===n)return(0,a.jsx)("div",{className:"lk-empty",children:(0,a.jsx)("p",{className:"lk-empty-body",children:"Open a run from the Quality Intelligence hub."})});let l=function(e){var t,n;let l=ow(e,oy);if(void 0!==l&&l.length>0){let e=function(e){try{let t=JSON.parse(e);if(!Array.isArray(t)||!t.every(ok))return null;return t;}catch{return null;}}(l);if(null!==e)return e;}return oR({connectedFilePath:null!=(t=ow(e,"connectedFilePath"))?t:null,connectedRoot:null!=(n=ow(e,"connectedRoot"))?n:null});}(e),i=oN(l);return(0,a.jsx)(cf,{runId:n,connectedSources:l,onRegenerated:e=>{t.openWindow("qiRun",{runId:e.runId,...i});}});}),E("relationships",()=>(0,a.jsx)(dl,{})),E("files",(e,t)=>{let n=ud(e,"root"),l=(e,n,l)=>{let a={activeFilePath:null!=e?e:void 0,resolvedRoot:null!=n?n:void 0};void 0!==l&&(a.activeDirectoryPath=null!=l?l:void 0),t.updateCfg(a);},i=e=>{t.updateCfg({root:e,activeFilePath:void 0,activeDirectoryPath:void 0,resolvedRoot:void 0});},r=(e,n)=>{t.openWindow("editor",{root:e,file:n,openFiles:[n]});};return void 0!==n?(0,a.jsx)(iJ,{root:n,onActiveFileChange:l,onRootChange:i,onOpenFile:r}):(0,a.jsx)(iJ,{onActiveFileChange:l,onRootChange:i,onOpenFile:r});}),E("editor",(e,t)=>{let n=ud(e,"root"),l=ud(e,"file"),i=function(e,t){let n=e[t];if(!Array.isArray(n))return;let l=n.filter(e=>"string"==typeof e&&e.trim().length>0).map(e=>e.trim());return l.length>0?l:void 0;}(e,"openFiles"),r=ud(e,"layoutJson"),s={};return void 0!==n&&(s.root=n),void 0!==l&&(s.file=l),void 0!==i&&(s.openFiles=i),void 0!==r&&(s.layoutJson=r),s.linkedRoot=t.linkedRoot,s.linkedFilePath=t.linkedFilePath,s.linkedCapsuleIds=t.linkedCapsuleIds,s.linkedCapsuleSetIds=t.linkedCapsuleSetIds,s.windowId=t.windowId,s.onWorkspaceChange=e=>{t.updateCfg(e);},(0,a.jsx)(rj,{...s});}),E("browser",e=>{let t=ud(e,"url");return void 0!==t&&""!==t?(0,a.jsx)(rF,{url:t}):(0,a.jsx)(rF,{});}),E("terminal",e=>{let t=ud(e,"cwd"),n=ud(e,"projectPath"),l={};return void 0!==t&&(l.cwd=t),void 0!==n&&(l.projectPath=n),(0,a.jsx)(rz,{...l});}),E("review",(e,t)=>{let n=ud(e,"runId"),l=e=>{t.updateCfg({runId:e});};return void 0!==n&&""!==n?(0,a.jsx)(rY,{runId:n,onRunIdSubmit:l}):(0,a.jsx)(rY,{onRunIdSubmit:l});}),E("agents",(e,t)=>{var n;let l,i,r,s,o,c,d,u,p,m,h;return(0,a.jsx)(r1,{cfg:(r={},void 0!==(s=ud(n=e,"workflow"))&&(r.workflow=s),void 0!==(o=ud(n,"model"))&&(r.model=o),void 0!==(c=ud(n,"runId"))&&(r.runId=c),void 0!==(d=ud(n,"fingerprint"))&&(r.fingerprint=d),void 0!==(u=ud(n,"workspaceRoot"))&&(r.workspaceRoot=u),void 0!==(p=ud(n,"inputJson"))&&(r.inputJson=p),void 0!==(m="boolean"==typeof(l=n.keikoMode)?l:void 0)&&(r.keikoMode=m),void 0!==(h="ask"===(i=n.access)||"full"===i?i:void 0)&&(r.access=h),r),linkedRoot:t.linkedRoot,linkedFilePath:t.linkedFilePath});}),E("memoria",()=>(0,a.jsx)(dG,{})),E("integ",()=>(0,a.jsx)(r3,{})),E("figma",(e,t)=>{let n=ud(e,"snapshotRunId"),l=uu(e,"selectedScreenIdsJson"),i=ud(e,"selectedScreenName");return(0,a.jsx)(sX,{sourceWindowId:t.windowId,snapshotRunId:n,selectedScreenIds:l,selectedScreenName:i,openScreenSource:e=>{let{snapshotRunId:n,screenId:l,name:a}=e;t.openWindow("figmaView",{snapshotRunId:n,selectedScreenIdsJson:JSON.stringify([l]),selectedScreenName:a});},updateCfg:e=>{t.updateCfg(e);}});}),E("figmaView",(e,t)=>{let n=ud(e,"snapshotRunId"),l=uu(e,"selectedScreenIdsJson"),i=ud(e,"selectedScreenName");return(0,a.jsx)(sX,{sourceWindowId:t.windowId,snapshotRunId:n,selectedScreenIds:l,selectedScreenName:i,updateCfg:e=>{t.updateCfg(e);}});}),E("figmaJson",e=>{let t=ud(e,"snapshotRunId"),n=ud(e,"screenId"),l=ud(e,"selectedScreenName");return(0,a.jsx)(sG,{snapshotRunId:t,screenId:n,screenName:l});}),E("figmaImage",e=>{let t=ud(e,"imageSrc"),n=ud(e,"selectedScreenName");return(0,a.jsx)(sQ,{imageSrc:t,screenName:n});}),E("connector",(e,t)=>{let n=ud(e,"presentation"),l=ud(e,"selectedKind"),i=ud(e,"selectedId"),r=ud(e,"selectedLabel"),s=ud(e,"selectedState");return(0,a.jsx)(sv,{presentation:n,selectedKind:l,selectedId:i,selectedLabel:r,selectedState:s,onSelect:e=>{t.updateCfg(e);},onManageConnectors:()=>{t.openWindow("localKnowledge");}});});let um={supported:{heading:"Install Keiko",body:"Keep Keiko in your app shelf for fast access.",install:"Install Keiko"},"ios-add-to-home":{heading:"Install Keiko",body:'On iOS Safari, tap Share, then "Add to Home Screen".',install:null}};function uh(){let{available:e,triggerInstall:t}=function(){let[e,t]=(0,i.useState)(!1),n=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=e=>{e.preventDefault(),function(e){if("function"!=typeof e.prompt)return!1;let t=e.userChoice;return"object"==typeof t&&null!==t&&"function"==typeof t.then;}(e)&&(n.current=e,t(!0));},l=()=>{localStorage.setItem("keiko.pwa.installed","true"),n.current=null,t(!1);};return window.addEventListener("beforeinstallprompt",e,{passive:!1}),window.addEventListener("appinstalled",l),()=>{window.removeEventListener("beforeinstallprompt",e),window.removeEventListener("appinstalled",l);};},[]),{available:e,triggerInstall:(0,i.useCallback)(async()=>{let e=n.current;if(null===e)return;await e.prompt();let{outcome:l}=await e.userChoice;"accepted"===l&&localStorage.setItem("keiko.pwa.installed","true"),n.current=null,t(!1);},[])};}(),[n,l]=(0,i.useState)(!1),[r]=(0,i.useState)(()=>{let e;return"u">typeof navigator?(e=navigator.userAgent.toLowerCase()).includes("crios/")?"manual":e.includes("chrome/")&&!e.includes("mobile")||e.includes("edg/")||e.includes("chromium/")?"supported":e.includes("firefox/")?"manual":e.includes("safari/")&&(e.includes("iphone")||e.includes("ipad")||e.includes("ipod"))?"ios-add-to-home":(e.includes("safari/")&&e.includes("macintosh"),"manual"):"manual";}),s=(0,i.useRef)(null),o=(0,i.useCallback)(()=>{localStorage.setItem("keiko.pwa.dismissed",new Date().toISOString()),l(!0);},[]),c=(0,i.useCallback)(async()=>{await t();},[t]),d=(0,i.useCallback)(e=>{"Escape"!==e.key||e.defaultPrevented||o();},[o]);if(n||window.matchMedia("(display-mode: standalone)").matches||"true"===localStorage.getItem("keiko.pwa.installed")||function(){let e=localStorage.getItem("keiko.pwa.dismissed");if(null===e)return!1;let t=Date.parse(e);return!!Number.isNaN(t)||Date.now()-t<2592e6;}()||"supported"===r&&!e||"supported"!==r&&"ios-add-to-home"!==r)return null;let u=um[r];return(0,a.jsx)("aside",{className:"install-banner",role:"region","aria-label":"Install Keiko",onKeyDown:d,children:(0,a.jsxs)("div",{className:"install-banner-body",children:[(0,a.jsxs)("div",{className:"install-banner-text",children:[(0,a.jsx)("span",{className:"install-banner-heading",children:u.heading}),(0,a.jsx)("span",{className:"install-banner-desc",children:u.body})]}),(0,a.jsxs)("div",{className:"install-banner-actions",children:[null!==u.install&&(0,a.jsx)("button",{ref:s,type:"button",className:"install-banner-btn-install",onClick:()=>void c(),children:u.install}),(0,a.jsx)("button",{type:"button",className:"install-banner-btn-dismiss",onClick:o,children:"Not now"})]})]})});}let uf="keiko.service-worker-update-reload-pending",ug=!1;function uv(){ug||function(){try{if("true"!==window.sessionStorage.getItem(uf))return!1;return window.sessionStorage.removeItem(uf),!0;}catch{return!0;}}()&&(ug=!0,window.location.reload());}function ub(e){let t=e.waiting;if(null!==t){try{window.sessionStorage.setItem(uf,"true");}catch{}try{t.postMessage({type:"KEIKO_ACTIVATE_WAITING_SERVICE_WORKER"});}catch{try{window.sessionStorage.removeItem(uf);}catch{}}}}function ux(e){return null===e||void 0===e.root?null:[e.root.replace(/\\/gu,"/").replace(/\/+$/u,""),e.kind,...e.relativePaths.map(e=>e.replace(/\\/gu,"/").replace(/^\/+|\/+$/gu,""))].join("\0");}function uy(e){return e.trim().replace(/\\/gu,"/").replace(/\/+$/u,"");}function uw(e,t){let n=uy(e),l=uy(t);if(0===l.length)return"";if(0===n.length)return /^\/+$/u.test(e.trim().replace(/\\/gu,"/"))?l.replace(/^\/+/u,""):"";let a=n.toLowerCase(),i=l.toLowerCase();return i===a?"":i.startsWith(`${a}/`)?l.slice(n.length+1).replace(/^\/+/u,""):null;}let uj=["chat","connector","files","editor","agents"],uk=["chatHistory","memoria","settings","automations","mobile","inspector","activity","notifications","resources","localKnowledge","figma","quality","promptEnhancer","relationships"];function uN(){var e,t,n,l,r,o,c,d,u,p;let m,{theme:h,toggle:f}=function(){let[e,t]=(0,i.useState)(n7),[n,l]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{t(function(){try{let e=window.localStorage.getItem(n8);return"light"===e||"dark"===e?e:n7;}catch{return n7;}}()),l(!0);},[]),(0,i.useEffect)(()=>{if(n){"u">typeof document&&(document.documentElement.dataset.theme=e);try{window.localStorage.setItem(n8,e);}catch{}}},[e,n]),{theme:e,toggle:(0,i.useCallback)(()=>{t(e=>"light"===e?"dark":"light");},[])};}(),g=w(),v=n5({autoCreate:!1}),b=(0,i.useRef)(null),x=(0,i.useRef)(null),[y,N]=(0,i.useState)(nb.ty);(0,i.useEffect)(()=>{(0,k.Dz)().then(e=>N(e.effectiveGroundingLimits)).catch(()=>void 0);},[]);let[S,C]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(null===S)return;let e=window.setTimeout(()=>C(null),1e4);return()=>window.clearTimeout(e);},[S]);let I=(0,i.useCallback)((e,t)=>(C(`Source limit reached — this chat already has ${String(e)} of ${String(t)} connected sources. Disconnect a source before connecting another.`),!1),[]),R=(0,i.useCallback)(e=>(C(e),!1),[]),E=(0,i.useCallback)(e=>{var t,n,l;let a=function(e){if((null==e?void 0:e.type)!=="chat")return;let t=e.cfg.chatId;return"string"==typeof t&&t.length>0?t:void 0;}(null==(n=x.current)?void 0:n.find(t=>t.id===e));if(void 0===a)return;let i=null!=(t=v.chats.find(e=>e.id===a))?t:(null==(l=v.activeChat)?void 0:l.id)===a?v.activeChat:void 0;return(null==i?void 0:i.status)==="closed"?void 0:i;},[v.activeChat,v.chats]),A=(0,i.useCallback)(async function(e,t){var n;let l=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,a=E(e);if(void 0===a)return R("Open a ready chat window before connecting a source.");let i=null===l?e5(a):e6(e5(a),l),r=e8(a);if(i.some(e=>e1(e,t))){if(null!==l){let e=await(0,k.Mr)(a.id,i.length>0?i:null);v.replaceChat(e.chat);}return!0;}let s=e4(y);if(i.length+r.length>=s)return I(i.length+r.length,s);let o={...t,connectedAtMs:Date.now()},c=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16;if(void 0===t.root)return null;let l=eQ(t.root);if(!eG(l))return null;let a=t.relativePaths.map(e0),i={kind:t.kind,relativePaths:a,root:l,connectedAtMs:t.connectedAtMs};return e.some(e=>e1(e,i))||e.length>=n?e:[...e,i];}(i,o,y.maxConnectedSources);if(null===c)return R("Choose a local folder before connecting it to chat.");if(c===i)return I(i.length+r.length,s);try{let e=await(0,k.Mr)(a.id,c);v.replaceChat(e.chat),C(null);let t=function(e){var t;if(void 0===e.root)return null;let n=null==(t=e.relativePaths[0])?void 0:t.replace(/\\/gu,"/").replace(/^\/+/u,"");if(void 0===n||0===n.length)return e.root;let l=e.root.replace(/\\/gu,"/").replace(/\/+$/u,"");return`${l}/${n}`;}(o);return null!==t&&(n=a.id,0!==n.length&&0!==t.length&&ld({type:"reads-context",source:{kind:"chat",id:n},target:{kind:"workspace-path",id:t}},function(e,t){let n=0x811c9dc5,l=`${e}|${t}`;for(let e=0;e<l.length;e+=1)n=Math.imul(n^l.charCodeAt(e),0x1000193);return`rc-${(n>>>0).toString(36)}-${(65535&l.length).toString(36)}`;}(n,t)).catch(e=>{})),!0;}catch{return R("Keiko could not connect that source. Check that it is still available and try again.");}},[E,v,y,I,R]),T=function(e){var t,n,l,a,r,s,o,c,d;let u=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},[p,m]=(0,i.useState)(null),[h,f]=(0,i.useState)(null),[g,v]=(0,i.useState)(!1),[b,x]=(0,i.useState)([]),[y,w]=(0,i.useState)(null),[j,k]=(0,i.useState)(ta),N=(0,i.useRef)(3),S=(0,i.useRef)(null),C=(0,i.useRef)([]);C.current=null!=p?p:[];let I=(0,i.useRef)([]);I.current=b;let R=(0,i.useRef)(null);R.current=y;let E=(0,i.useRef)(null),A=(0,i.useRef)(()=>void 0),{viewRef:T,worldVP:q,zoomTo:M,fitView:P,resetView:L,panBy:z,rect:O}=function(e){let{wsRef:t,view:n,winsRef:l,setView:a,setWins:r}=e,s=(0,i.useRef)(n);s.current=n;let o=(0,i.useRef)(null),c=(0,i.useRef)(null);(0,i.useEffect)(()=>{to(tl,n);},[n]),(0,i.useEffect)(()=>()=>{null!==c.current&&"function"==typeof window.cancelAnimationFrame&&window.cancelAnimationFrame(c.current);},[]);let d=(0,i.useCallback)(e=>{var t;let n=null!=(t=o.current)?t:s.current,l="function"==typeof e?e(n):e;if(s.current=l,o.current=l,"function"!=typeof window.requestAnimationFrame||"function"!=typeof window.cancelAnimationFrame){o.current=null,a(l);return;}null===c.current&&(c.current=window.requestAnimationFrame(()=>{c.current=null;let e=o.current;o.current=null,null!==e&&a(e);}));},[a]);(0,i.useEffect)(()=>{let e=t.current;if(null===e)return;let n=t=>{if(t.metaKey||t.ctrlKey){var n,l,a;t.preventDefault();let i=(n=t.target)instanceof Element&&null!=(l=null==(a=n.closest(".window[data-window-id]"))?void 0:a.dataset.windowId)?l:null;if(null!==i)return void r(e=>null===e?e:e.map(e=>{var n,l,a;let r,s;return e.id===i?(n=e,l=t.deltaY,(s=tr((r=null!=(a=n.zoom)?a:1)*Math.exp(-(.0015*l))))===r?n:{...n,zoom:s}):e;}));let o=e.getBoundingClientRect(),c=s.current,u=tc(t),p=ti(c.zoom*Math.exp(-(.0015*u.y))),m=(t.clientX-o.left-c.x)/c.zoom,h=(t.clientY-o.top-c.y)/c.zoom;return void d({zoom:p,x:t.clientX-o.left-m*p,y:t.clientY-o.top-h*p});}let i=t.target;if(i instanceof Element&&null!==i.closest(".window"))return;t.preventDefault();let o=tc(t);d(e=>({...e,x:e.x-o.x,y:e.y-o.y}));};return e.addEventListener("wheel",n,{passive:!1}),()=>{e.removeEventListener("wheel",n);};},[t,r,d]);let u=(0,i.useCallback)(()=>null===t.current?null:t.current.getBoundingClientRect(),[t]),p=(0,i.useCallback)(()=>{let e=u();if(null===e)return null;let t=s.current;return{x:-t.x/t.zoom,y:-t.y/t.zoom,w:e.width/t.zoom,h:e.height/t.zoom};},[u]),m=(0,i.useCallback)(e=>{let t=u();if(null===t)return;let n=s.current,l=t.width/2,a=t.height/2,i=(l-n.x)/n.zoom,r=(a-n.y)/n.zoom,o=ti(e);d({zoom:o,x:l-i*o,y:a-r*o});},[u,d]),h=(0,i.useCallback)(()=>{let e=u();null!==e&&d(function(e,t){let n=e.filter(e=>!0!==e.minimized);if(0===n.length)return{zoom:1,x:0,y:0};let l=1/0,a=1/0,i=-1/0,r=-1/0;for(let e of n)l=Math.min(l,e.x),a=Math.min(a,e.y),i=Math.max(i,e.x+e.w),r=Math.max(r,e.y+e.h);let s=Math.max(1,i-l),o=Math.max(1,r-a),c=ti(Math.min(1,Math.max(1,t.width-144)/s,Math.max(1,t.height-144)/o)),d=l+s/2,u=a+o/2;return{zoom:c,x:Math.round(t.width/2-d*c),y:Math.round(t.height/2-u*c)};}(l.current,e));},[u,l,d]);return{viewRef:s,worldVP:p,zoomTo:m,fitView:h,resetView:(0,i.useCallback)(()=>d({zoom:1,x:0,y:0}),[d]),panBy:(0,i.useCallback)((e,t)=>d(n=>({...n,x:n.x+e,y:n.y+t})),[d]),rect:u};}({wsRef:e,view:j,winsRef:C,setView:k,setWins:m});!function(e){let{wsRef:t,setWins:n,setConns:l,zc:a}=e;(0,i.useLayoutEffect)(()=>{let e=t.current;if(null===e)return;e.getBoundingClientRect();let i=null;try{i=function(e){if(null===e)return null;try{let t=JSON.parse(e);if(!Array.isArray(t)||0===t.length)return null;let n=e_(t);return n.length>0?n:null;}catch{return null;}}(window.localStorage.getItem(tt));}catch{i=null;}null===i&&(i=[]),a.current=0===i.length?1:Math.max(1,...i.map(e=>e.z)),n(i);try{l(function(e,t){if(null===e)return[];try{let n=JSON.parse(e);if(!Array.isArray(n))return[];return eV(n,t);}catch{return[];}}(window.localStorage.getItem(tn),i));}catch{}},[t,n,l,a]);}({wsRef:e,setWins:m,setConns:x,zc:N}),(0,i.useEffect)(()=>{null!==p&&to(tn,eV(b,p));},[b,p]),(0,i.useEffect)(()=>{null!==p&&x(e=>{let t=e.filter(e=>void 0!==p.find(t=>t.id===e.a)&&void 0!==p.find(t=>t.id===e.b));return t.length===e.length?e:t;});},[p,x]),(0,i.useEffect)(()=>{null!==p&&to(tt,e_(p));},[p]),function(e){let{setWins:t,rect:n,cancelConnectRef:l}=e;(0,i.useEffect)(()=>{let e=e=>{var a,i;if("Escape"===e.key)return void l.current();if(null!==(a=document.activeElement)&&("INPUT"===a.tagName||"TEXTAREA"===a.tagName||"SELECT"===a.tagName))return;let r=td[e.code];if((e.metaKey||e.ctrlKey)&&e.altKey&&void 0!==r){e.preventDefault(),t(e=>{var t,n;if(null===e||0===e.length)return e;let l=ts(e);if(null===l)return e;let a=(n=null!=(t=l.zoom)?t:1,"0"===r?1:"-"===r||"_"===r?tr(n-.1):tr(n+.1));return e.map(e=>e.id===l.id?{...e,zoom:a}:e);});return;}if(!/^Arrow/.test(e.key))return;let s=e.metaKey||e.ctrlKey,o=e.altKey;if(!s&&!o)return;e.preventDefault();let c=n();null!==c&&(i={key:e.key,shift:e.shiftKey},t(e=>{let t,n,l,a,r,s,d;if(null===e||0===e.length)return e;let u=ts(e);if(null===u)return e;let p=o?(t=i.shift?1:16,n=u.w,l=u.h,"ArrowRight"===i.key?n+=t:"ArrowLeft"===i.key?n-=t:"ArrowDown"===i.key?l+=t:"ArrowUp"===i.key&&(l-=t),n=Math.max((a=$[u.type].min).w,Math.min(c.width,n)),l=Math.max(a.h,Math.min(c.height,l)),{x:u.x,y:u.y,w:n,h:l}):(r=i.shift?1:16,s=u.x,d=u.y,"ArrowRight"===i.key?s+=r:"ArrowLeft"===i.key?s-=r:"ArrowDown"===i.key?d+=r:"ArrowUp"===i.key&&(d-=r),{x:s=Math.max(-(u.w-120),Math.min(c.width-120,s)),y:d=Math.max(0,Math.min(c.height-38,d)),w:u.w,h:u.h});return e.map(e=>e.id===u.id?{...e,...p,max:!1}:e);}));};return window.addEventListener("keydown",e),()=>{window.removeEventListener("keydown",e);};},[t,n,l]);}({setWins:m,rect:O,cancelConnectRef:A}),function(e){let{wsRef:t,viewRef:n,setWins:l}=e;(0,i.useEffect)(()=>{let e=t.current;if(null===e||"u"<typeof ResizeObserver)return;let a=new ResizeObserver(()=>{let t=e.getBoundingClientRect(),a=n.current,i={x:-a.x/a.zoom,y:-a.y/a.zoom,w:t.width/a.zoom,h:t.height/a.zoom};l(e=>null===e?e:e.map(e=>function(e,t){if(e.max)return{...e,x:t.x,y:t.y,w:t.w,h:t.h};if(t.w<520||t.h<420){let n=t.x+8,l=t.y+8;return n===e.x&&l===e.y?e:{...e,x:n,y:l};}let n=Math.max(t.x-(e.w-120),Math.min(t.x+t.w-120,e.x)),l=Math.max(t.y,Math.min(t.y+t.h-38,e.y));return n===e.x&&l===e.y?e:{...e,x:n,y:l};}(e,i)));});return a.observe(e),()=>{a.disconnect();};},[t,n,l]);}({wsRef:e,viewRef:T,setWins:m});let{update:K,focus:B,close:W,minimize:U,restore:_,maximize:V,add:H,toggleTool:J}={update:(n=(t={setWins:m,zc:N,worldVP:q}).setWins,(e,t)=>n(n=>{if(null===n)return n;let l=!1,a=n.map(n=>{if(n.id!==e)return n;for(let[e,a]of Object.entries(t))if(n[e]!==a)return l=!0,{...n,...t};return n;});return l?a:n;})),focus:(l=t.setWins,a=t.zc,e=>l(t=>null===t?t:t.map(t=>t.id===e?{...t,z:++a.current}:t))),close:(r=t.setWins,e=>r(t=>null===t?t:t.filter(t=>t.id!==e))),minimize:(s=t.setWins,e=>s(t=>null===t?t:t.map(t=>t.id===e?{...t,minimized:!0}:t))),restore:(o=t.setWins,c=t.zc,e=>o(t=>null===t?t:t.map(t=>t.id===e?{...t,minimized:!1,z:++c.current}:t))),maximize:function(e){let{setWins:t,zc:n,worldVP:l}=e;return e=>t(t=>{if(null===t)return t;let a=l();return null===a?t:t.map(t=>{if(t.id!==e)return t;if(t.max){var l,i;let e,r,s,o=null!=(l=t.prev)?l:(i=t.type,r=Math.min((e=$[i]).w,Math.max(e.min.w,a.w-32)),s=Math.min(e.h,Math.max(e.min.h,a.h-32)),{x:a.x+Math.max(16,Math.round((a.w-r)/2)),y:a.y+Math.max(16,Math.round((a.h-s)/2)),w:r,h:s}),{prev:c,...d}=t;return{...d,x:o.x,y:o.y,w:o.w,h:o.h,max:!1,z:++n.current};}return{...t,max:!0,prev:{x:t.x,y:t.y,w:t.w,h:t.h},x:a.x,y:a.y,w:a.w,h:a.h,z:++n.current};});});}(t),add:function(e){let{setWins:t,zc:n,worldVP:l}=e;return(e,a)=>{let i=$[e],r="figma"===e&&"string"==typeof(null==a?void 0:a.selectedScreenIdsJson)&&a.selectedScreenIdsJson.length>0,s=r?360:i.w,o=r?360:i.h,c=r?Math.max(i.min.w,300):i.min.w,d=r?Math.max(i.min.h,260):i.min.h,u=null;return t(t=>{let r=l();if(null===r)return t;let p=null!=t?t:[];if(!0===i.singleton){let t=p.find(t=>t.type===e);if(void 0!==t)return u=t.id,p.map(e=>e.id===t.id?{...e,minimized:!1,z:++n.current}:e);}let m="qiRun"===e?null==a?void 0:a.runId:void 0;if("string"==typeof m&&m.length>0){let e=p.find(e=>"qiRun"===e.type&&e.cfg.runId===m);if(void 0!==e)return u=e.id,p.map(t=>t.id===e.id?{...t,cfg:void 0===a?t.cfg:{...t.cfg,...a},minimized:!1,z:++n.current}:t);}let h="chat"===e?null==a?void 0:a.chatId:void 0;if("string"==typeof h&&h.length>0){let e=p.find(e=>"chat"===e.type&&e.cfg.chatId===h);if(void 0!==e)return u=e.id,p.map(t=>t.id===e.id?{...t,minimized:!1,z:++n.current}:t);}let{x:f,y:g}=eH(r,s,o,p.length,40),v=!0===i.singleton?e:`${e}-${Date.now().toString(36)}`;return u=v,[...p,{id:v,type:e,x:f,y:g,w:Math.max(s,c),h:Math.max(o,d),z:++n.current,cfg:null!=a?a:{},max:!1,zoom:1}];}),u;};}(t),toggleTool:function(e){let{setWins:t,zc:n,worldVP:l}=e;return e=>{let a=$[e];t(t=>{let i=l();if(null===i)return t;let r=null!=t?t:[],s=r.find(t=>t.type===e);if(void 0!==s&&!0===s.minimized)return r.map(e=>e.id===s.id?{...e,minimized:!1,z:++n.current}:e);if(void 0!==s)return r.filter(t=>t.type!==e);let{x:o,y:c}=eH(i,a.w,a.h,r.length,28);return[...r,{id:e,type:e,x:o,y:c,w:a.w,h:a.h,z:++n.current,cfg:{},max:!1,zoom:1}];});};}(t)},{tileAll:Y,splitFront:X,cascade:G}={tileAll:function(e){let{setWins:t,worldVP:n}=e;return()=>t(e=>{if(null===e||0===e.length)return e;let t=n();if(null===t)return e;let l=e.length,a=Math.ceil(Math.sqrt(l)),i=Math.ceil(l/a),r=(t.w-12*(a+1))/a,s=(t.h-12*(i+1))/i;return e.map((e,n)=>{let l=Math.floor(n/a);return{...eJ(e),max:!1,minimized:!1,x:t.x+12+n%a*(r+12),y:t.y+12+l*(s+12),w:r,h:s};});});}(d={setWins:m,worldVP:q}),splitFront:function(e){let{setWins:t,worldVP:n}=e;return()=>t(e=>{if(null===e||0===e.length)return e;let t=n();if(null===t)return e;let l=[...e].filter(e=>!0!==e.minimized).sort((e,t)=>t.z-e.z).slice(0,2).map(e=>e.id);return e.map(e=>{let n=l.indexOf(e.id);return 0===n?{...eJ(e),max:!1,minimized:!1,x:t.x,y:t.y,w:t.w/2,h:t.h}:1===n?{...eJ(e),max:!1,minimized:!1,x:t.x+t.w/2,y:t.y,w:t.w/2,h:t.h}:e;});});}(d),cascade:function(e){let{setWins:t,worldVP:n}=e;return()=>t(e=>{if(null===e)return e;let t=n();return null===t?e:e.map((e,n)=>({...eJ(e),max:!1,minimized:!1,x:t.x+24+30*n,y:t.y+24+30*n,w:Math.min(560,t.w-80),h:Math.min(420,t.h-80),z:n+1}));});}(d)},{setSnap:Q,commitSnap:Z}=function(e){let{setSnapPrev:t,snapZone:n,worldVP:l,update:a}=e;return{setSnap:e=>{if(n.current=e,null===e)return void t(null);let a=l();null!==a&&t(D(a)[e]);},commitSnap:e=>{let i=n.current;if(n.current=null,t(null),null===i)return;let r=l();if(null===r)return;let s={...D(r)[i],max:"maxi"===i};"maxi"===i&&(s.prev={x:r.x+40,y:r.y+40,w:480,h:360}),a(e,s);}};}({setSnapPrev:f,snapZone:S,worldVP:q,update:K}),{startConnect:ee,confirmConnect:et,cancelConnect:en,removeConn:el,connect:ea,linkedFilesRoot:ei,linkedFilesContext:er,linkedAllFilesRoots:es,linkedConnectorCapsuleIds:eo,linkedConnectorCapsuleSetIds:ec,linkedFigmaSnapshotRunIds:ed,linkedFigmaSnapshotSources:eu,linkedImageSources:ep,currentFilesContext:em}=function(e){let{wsRef:t,viewRef:n,winsRef:l,connsRef:a,connectingRef:i,connectCleanupRef:r,focus:s,setConns:o,setConnecting:c,onScopeBind:d,onScopeUnbind:u,onConnectorBind:p,onConnectorUnbind:m}=e,h=()=>{null!==r.current&&(r.current(),r.current=null),i.current=null,c(null);},f=e=>{if("files"!==e.type)return null;let t=e.cfg.resolvedRoot,n=e.cfg.root,l="string"==typeof t&&t.length>0?t:"string"==typeof n&&n.length>0?n:null;if(null===l||!eG(l))return null;let a=e.cfg.activeFilePath;return{id:e.id,root:l,...("string"==typeof a&&a.length>0?{activeFilePath:a}:{})};},g=e=>{let t=[];for(let n of a.current){let a=n.a===e?n.b:n.b===e?n.a:null;if(null===a)continue;let i=l.current.find(e=>e.id===a);void 0!==i&&"files"===i.type&&t.push(i);}if(0===t.length)return null;let n=[...t].sort((e,t)=>t.z-e.z),i=n.find(e=>{let t=e.cfg.activeFilePath;return"string"==typeof t&&t.length>0;}),r=null!=i?i:n[0];return void 0===r?null:f(r);},v=(e,t)=>{let n=new Set(),i=[];for(let r of a.current){if(i.length>=16)break;let a=r.a===e?r.b:r.b===e?r.a:null;if(null===a)continue;let s=l.current.find(e=>e.id===a);if(void 0===s||"connector"!==s.type||s.cfg.selectedKind!==t)continue;let o=s.cfg.selectedId;"string"==typeof o&&0!==o.trim().length&&(n.has(o)||(n.add(o),i.push(o)));}return i;},b=e=>{let t=(e=>{if("string"!=typeof e||0===e.trim().length)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let n=t.filter(e=>"string"==typeof e&&""!==e.trim()).map(e=>e.trim());return[...new Set(n)].sort();}catch{return[];}})(e.cfg.selectedScreenIdsJson);if(t.length>0)return t;let n=e.cfg.screenId;return"string"==typeof n&&n.trim().length>0?[n.trim()]:[];};return{startConnect:(e,l)=>{if(l.preventDefault(),l.stopPropagation(),null!==i.current&&i.current.from===e)return void h();let a=t.current;if(null===a)return;let s=a.getBoundingClientRect(),o=n.current,d=e=>(e-s.left-o.x)/o.zoom,u=e=>(e-s.top-o.y)/o.zoom;null!==r.current&&(r.current(),r.current=null);let p={from:e,x:d(l.clientX),y:u(l.clientY)};i.current=p,c(p);let m=t=>{let n={from:e,x:d(t.clientX),y:u(t.clientY)};i.current=n,c(n);};window.addEventListener("pointermove",m),r.current=()=>{window.removeEventListener("pointermove",m);};},confirmConnect:(e,t)=>{t.preventDefault(),t.stopPropagation();let n=i.current;if(null===n)return;let a=l.current,r=a.find(e=>e.id===n.from),c=a.find(t=>t.id===e);if(void 0!==r&&void 0!==c&&F(r.type,c.type)){let t,a=e2(r,c,Date.now()),i=null===a?te(r,c):null,h=null!==a||null!==i?eX(r,c):null;try{var u,m;t=null!==a&&null!==h?null==(u=null==d?void 0:d(h,a))||u:null===i||null!==h&&(null==(m=null==p?void 0:p(h,i))||m);}catch{t=!1;}Promise.resolve(t).then(t=>{!t||l.current.some(e=>e.id===n.from)&&l.current.some(t=>t.id===e)&&(o(t=>eY(t,n.from,e)?t:[...t,{id:`${n.from}~${e}`,a:n.from,b:e,...(null!==h?{boundChatWindowId:h}:{}),...(null!==a?{boundRoot:a.root,boundScopeKind:a.kind,boundRelativePath:a.relativePaths[0]}:{}),...(null!==i?"capsule"===i.kind?{boundConnectorKind:"capsule",boundConnectorId:i.capsuleId}:{boundConnectorKind:"capsule-set",boundConnectorId:i.capsuleSetId}:{})}]),s(e));}).catch(()=>void 0);}h();},cancelConnect:h,removeConn:e=>{var t,n,i;let r=a.current.find(t=>t.id===e);if(o(t=>t.filter(t=>t.id!==e)),void 0===r)return;let s=l.current,c=s.find(e=>e.id===r.a),d=s.find(e=>e.id===r.b),p=void 0!==c&&void 0!==d,h=null!=(t=r.boundChatWindowId)?t:p?eX(c,d):null,f=null!=(n=e3(r))?n:p?e2(c,d,Date.now()):null;null!==f&&null!==h&&(null==u||u(h,f));let g=null!=(i=e9(r))?i:p?te(c,d):null;null!==g&&null!==h&&(null==m||m(h,g));},connect:(e,t)=>{let n=l.current,a=n.find(t=>t.id===e),i=n.find(e=>e.id===t);void 0!==a&&void 0!==i&&F(a.type,i.type)&&o(n=>eY(n,e,t)?n:[...n,{id:`${e}~${t}`,a:e,b:t}]);},linkedFilesRoot:e=>{var t,n;return null!=(t=null==(n=g(e))?void 0:n.root)?t:null;},linkedFilesContext:g,linkedAllFilesRoots:e=>{let t=new Set(),n=[];for(let i of a.current){if(n.length>=16)break;let a=i.a===e?i.b:i.b===e?i.a:null;if(null===a)continue;let r=l.current.find(e=>e.id===a);if(void 0===r)continue;let s=eZ(r);null===s||t.has(s)||(t.add(s),n.push(s));}return n;},linkedConnectorCapsuleIds:e=>v(e,"capsule"),linkedConnectorCapsuleSetIds:e=>v(e,"capsule-set"),linkedFigmaSnapshotRunIds:e=>{let t=new Set(),n=[];for(let i of a.current){if(n.length>=16)break;let a=i.a===e?i.b:i.b===e?i.a:null;if(null===a)continue;let r=l.current.find(e=>e.id===a);if(void 0===r||"figma"!==r.type)continue;let s=r.cfg.snapshotRunId;"string"==typeof s&&0!==s.trim().length&&(t.has(s)||(t.add(s),n.push(s)));}return n;},linkedFigmaSnapshotSources:e=>{let t=new Set(),n=[];for(let i of a.current){if(n.length>=16)break;let a=i.a===e?i.b:i.b===e?i.a:null;if(null===a)continue;let r=l.current.find(e=>e.id===a);if(void 0===r||"figma"!==r.type&&"figmaView"!==r.type&&"figmaJson"!==r.type)continue;let s=r.cfg.snapshotRunId;if("string"!=typeof s||0===s.trim().length)continue;let o=r.cfg.selectedScreenIdsJson,c=r.cfg.selectedScreenName,d=b(r);if(("figmaJson"===r.type||"figmaView"===r.type||void 0!==o||"string"==typeof c&&c.trim().length>0)&&0===d.length)continue;let u=`${s}:${d.join(",")||"*"}`;if(t.has(u))continue;t.add(u);let p=d.length>0&&"string"==typeof c&&c.trim().length>0?"figmaJson"===r.type?`JSON \xb7 ${c}`:c:s;n.push({kind:"figma-snapshot",label:p,snapshotRunId:s,...(d.length>0?{screenIds:d}:{})});}return n;},linkedImageSources:e=>{let t=new Set(),n=[];for(let i of a.current){if(n.length>=16)break;let a=i.a===e?i.b:i.b===e?i.a:null;if(null===a)continue;let r=l.current.find(e=>e.id===a);if(void 0===r||"figmaImage"!==r.type)continue;let s=r.cfg.snapshotRunId,o=r.cfg.screenId;if("string"!=typeof s||0===s.trim().length||"string"!=typeof o||0===o.trim().length)continue;let c=`${s}:${o}`;if(t.has(c))continue;t.add(c);let d=r.cfg.selectedScreenName,u="string"==typeof d&&d.trim().length>0?`Image \xb7 ${d}`:`Image \xb7 ${o}`;n.push({kind:"image",label:u,sourceKind:"figma-snapshot-screen",snapshotRunId:s,screenId:o});}return n;},currentFilesContext:()=>{var e;let t=l.current.map(e=>f(e)).filter(e=>null!==e);if(1===t.length)return null!=(e=t[0])?e:null;let n=[...l.current].filter(e=>"files"===e.type).sort((e,t)=>t.z-e.z)[0];return void 0===n?null:f(n);}};}({wsRef:e,viewRef:T,winsRef:C,connsRef:I,connectingRef:R,connectCleanupRef:E,focus:B,setConns:x,setConnecting:w,onScopeBind:u.onScopeBind,onScopeUnbind:u.onScopeUnbind,onConnectorBind:u.onConnectorBind,onConnectorUnbind:u.onConnectorUnbind});return A.current=en,(0,i.useEffect)(()=>()=>{null!==E.current&&(E.current(),E.current=null);},[]),{wins:p,snapPrev:h,palOpen:g,setPalOpen:v,conns:b,connecting:y,view:j,api:{add:H,toggleTool:J,focus:B,close:e=>{let t=C.current.find(t=>t.id===e);if(void 0!==t)for(let s of I.current){var n,l,a,i,r;let o=s.a===e?s.b:s.b===e?s.a:null;if(null===o)continue;let c=C.current.find(e=>e.id===o);if(void 0===c)continue;let d=null!=(n=s.boundChatWindowId)?n:"chat"===t.type?t.id:"chat"===c.type?c.id:null,p=null!=(l=e3(s))?l:e2(t,c,Date.now());null!==p&&null!==d&&(null==(i=u.onScopeUnbind)||i.call(u,d,p));let m=null!=(a=e9(s))?a:te(t,c);null!==m&&null!==d&&(null==(r=u.onConnectorUnbind)||r.call(u,d,m));}W(e);},minimize:U,restore:_,maximize:V,update:K,setSnap:Q,commitSnap:Z,tileAll:Y,splitFront:X,cascade:G,startConnect:ee,confirmConnect:et,cancelConnect:en,removeConn:el,updateConnBoundScope:(e,t)=>{x(n=>n.map(n=>n.id===e?{...n,boundScopeKind:t.kind,...(void 0!==t.root?{boundRoot:t.root}:{}),...(void 0!==t.relativePaths[0]?{boundRelativePath:t.relativePaths[0]}:{})}:n));},connect:ea,linkedFilesRoot:ei,linkedFilesContext:er,linkedAllFilesRoots:es,linkedConnectorCapsuleIds:eo,linkedConnectorCapsuleSetIds:ec,linkedFigmaSnapshotRunIds:ed,linkedFigmaSnapshotSources:eu,linkedImageSources:ep,currentFilesContext:em,zoomTo:M,fitView:P,resetView:L,panBy:z,rect:O}};}(b,{onScopeBind:(0,i.useCallback)(async(e,t)=>A(e,t),[A]),onScopeUnbind:(0,i.useCallback)((e,t)=>{let n=E(e);if(void 0===n)return;let l=e6(e5(n),t);(0,k.Mr)(n.id,l.length>0?l:null).then(e=>{v.replaceChat(e.chat);}).catch(e=>{console.warn("[keiko] connected-scope unbind failed",e);});},[E,v]),onConnectorBind:(0,i.useCallback)(async(e,t)=>{var n;let l,a,i=E(e);if(void 0===i)return R("Open a ready chat window before connecting a source.");let r=e8(i),s=e5(i);if(l=e7(t),r.some(e=>e7(e)===l))return!0;let o=e4(y);if(s.length+r.length>=o)return I(s.length+r.length,o);let c=(n=y.maxLocalKnowledgeSources,a=e7(t),r.some(e=>e7(e)===a)||r.length>=n?r:[...r,t]);if(c===r)return I(s.length+r.length,o);try{let e=await(0,k.Cp)(i.id,c);return v.replaceChat(e.chat),C(null),!0;}catch{return R("Keiko could not connect that knowledge source. Check that it is still available and try again.");}},[E,v,y,I,R]),onConnectorUnbind:(0,i.useCallback)((e,t)=>{var n;let l=E(e);if(void 0===l)return;let a="capsule"===t.kind?`capsule:${t.capsuleId}`:`set:${t.capsuleSetId}`,i=(n=e8(l),n.filter(e=>e7(e)!==a));(0,k.Cp)(l.id,i.length>0?i:null).then(e=>{v.replaceChat(e.chat);}).catch(()=>void 0);},[E,v])});x.current=T.wins,(0,i.useEffect)(()=>{if(null!==T.wins)for(let t of T.conns){var e;let n=T.wins.find(e=>e.id===t.a),l=T.wins.find(e=>e.id===t.b);if(void 0===n||void 0===l)continue;let a=null!=(e=t.boundChatWindowId)?e:"chat"===n.type?n.id:"chat"===l.type?l.id:null;if(null===a)continue;let i=e2(n,l,Date.now());if(null===i)continue;let r=e3(t);ux(r)!==ux(i)&&A(a,i,r).then(e=>{e&&T.api.updateConnBoundScope(t.id,i);});}},[A,T.api,T.conns,T.wins]);let[q,L]=(0,i.useState)(!1),[z,B]=(0,i.useState)(null),[W,U]=(0,i.useState)(!1),[_,V]=(0,i.useState)(!1),H=null!=(e=null==(n=T.wins)?void 0:n.length)?e:0,J=function(e){if(null===e||0===e.length)return null;let t=null;for(let n=0;n<e.length;n++){let l=e[n];if(!0!==l.minimized){if(null===t){t=l;continue;}l.z>t.z&&(t=l);}}return t;}(T.wins),Y=(0,i.useMemo)(()=>function(e){if(null===e)return new Set();let t=new Set();for(let n of e)!0===$[n.type].tool&&t.add(n.type);return t;}(T.wins),[T.wins]),X=(0,i.useMemo)(()=>{var e;return{wins:null!=(e=T.wins)?e:[],active:J,winCount:H};},[T.wins,J,H]),G=(0,i.useCallback)(()=>L(!0),[]),Q=(0,i.useCallback)(()=>L(!1),[]),Z=(0,i.useCallback)(()=>V(e=>!e),[]),ee=(0,i.useCallback)(()=>V(!1),[]),et=(0,i.useCallback)(e=>{T.api.restore(e),V(!1);},[T.api]),en=(0,i.useCallback)(e=>{L(!1),B(e);},[]),el=(0,i.useCallback)(e=>{if(B(null),null===z)return;let{__connectFilesId:t,...n}="editor"===z?function(e){let t="string"==typeof e.root?e.root.trim():"",n="string"==typeof e.file?e.file.trim():"";if(0===t.length)return e;let l=uw(t,n),a={...e,root:t},i=function(e,t,n){let l=[],a=t=>{let n=function(e,t){let n=t.trim();if(0===n.length)return"";let l=uw(e,n);return null!==l?l:n.startsWith("/")||n.startsWith("\\")||/^[A-Za-z]:[\\/]/u.test(n)?null:n.replace(/\\/gu,"/").replace(/^\/+/u,"");}(e,t);null===n||0===n.length||l.includes(n)||l.push(n);};if(Array.isArray(t))for(let e of t)"string"==typeof e&&a(e);return n.length>0&&a(n),l;}(t,e.openFiles,null!==l?l:n);return null===l?n.length>0&&(a.file=n):l.length>0?a.file=l:delete a.file,i.length>0?a.openFiles=i:delete a.openFiles,a;}(e):e,l=T.api.add(z,n);"agents"===z&&null!==l&&"string"==typeof t&&t.length>0&&T.api.connect(l,t),null!==l&&requestAnimationFrame(()=>{var e;let t=document.querySelector(`[data-window-id="${l}"]`);null===t||(null!=(e=t.querySelector("textarea, input, select, button, [tabindex]"))?e:t).focus();});},[z,T.api]),ea=(0,i.useCallback)(()=>B(null),[]),ei=(0,i.useCallback)(()=>U(!1),[]),er=(0,i.useCallback)(()=>U(!0),[]),es=(0,i.useRef)(null),eo=(0,i.useCallback)(e=>{es.current=e;},[]),ec=function(e){var t;let{apply:n}=e,l=null!=(t=e.limit)?t:100,[a,r]=(0,i.useState)(lw),s=(0,i.useRef)(n);s.current=n;let o=(0,i.useRef)(a);o.current=a;let c=(0,i.useCallback)(e=>{r(t=>{let n=[...t.undoStack,e];return{undoStack:n.length>l?n.slice(n.length-l):n,redoStack:[]};});},[l]),d=(0,i.useCallback)(()=>{let e=o.current;if(0===e.undoStack.length)return;let t=e.undoStack[e.undoStack.length-1],n=function(e){switch(e.kind){case"ui.window.move":case"ui.window.resize":case"ui.window.zorder":case"ui.workspace.pan":case"ui.workspace.zoom":case"ui.workspace.fit":case"ui.panel.toggle":case"ui.selection.change":case"ui.tab.switch":return{...e,before:e.after,after:e.before};case"ui.window.close":return{...e,kind:"ui.window.open"};case"ui.window.open":return{...e,kind:"ui.window.close"};}}(t);r({undoStack:e.undoStack.slice(0,-1),redoStack:[...e.redoStack,t]}),s.current(n);},[]),u=(0,i.useCallback)(()=>{let e=o.current;if(0===e.redoStack.length)return;let t=e.redoStack[e.redoStack.length-1];r({undoStack:[...e.undoStack,t],redoStack:e.redoStack.slice(0,-1)}),s.current(t);},[]),p=(0,i.useCallback)(()=>{r(lw);},[]);return(0,i.useMemo)(()=>{let e=a.undoStack[a.undoStack.length-1],t=a.redoStack[a.redoStack.length-1];return{canUndo:a.undoStack.length>0,canRedo:a.redoStack.length>0,undoLabel:void 0!==e?lx(e):null,redoLabel:void 0!==t?lx(t):null,push:c,undo:d,redo:u,clear:p};},[a,c,d,u,p]);}({apply:(0,i.useCallback)(e=>{var t;return t=T.api,void("ui.panel.toggle"===e.kind&&e.panel in $&&t.toggleTool(e.panel));},[T.api])}),ed=(0,i.useCallback)(e=>{if(!(e in $))return;let t=Y.has(e);T.api.toggleTool(e),ec.push({kind:"ui.panel.toggle",panel:e,before:t,after:!t});},[T.api,Y,ec]),eu=(0,i.useCallback)(()=>en("chat"),[en]),ep=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(ep.current||null===T.wins)return;ep.current=!0;let e=window.location.pathname.replace(/\/+$/u,""),t="/relationships"===e?"relationships":"/local-knowledge"===e?"localKnowledge":null;null!==t&&(T.wins.some(e=>e.type===t)||ed(t),window.history.replaceState(null,"","/"));},[T.wins,ed]),function(e){var t;let{bindings:n,dispatch:l}=e,a=null!=(t=e.platform)?t:function(){if("u"<typeof navigator)return"other";let e=navigator.platform||"";return /Mac|iPhone|iPad|iPod/i.test(e)?"mac":"other";}(),r=(0,i.useRef)(l);r.current=l;let s=(0,i.useMemo)(()=>function(e){let t=new Map();for(let n of e){let e=ly(n.chord),l=t.get(e);void 0!==l?l.push(n.commandId):t.set(e,[n.commandId]);}let n=[];for(let[,l]of t)if(l.length>1){let t=e.find(e=>l.includes(e.commandId));void 0!==t&&n.push({chord:t.chord,commandIds:l});}return n;}(n),[n]),o=(0,i.useMemo)(()=>n.filter(e=>function(e){for(let t of lb)if(ly(e)===ly(t))return!0;return!1;}(e.chord)),[n]);if(s.length>0)throw new lj(s);if(o.length>0)throw new lk(o);(0,i.useEffect)(()=>{function e(e){if(!function(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;let t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t;}(e.target)){for(let t of n)if(function(e,t,n){if(!(e.key.toLowerCase()===t.key.toLowerCase()||t.mod.includes("alt")&&/^[a-z]$/i.test(t.key)&&e.code===`Key${t.key.toUpperCase()}`))return!1;let l=function(e,t){let n=new Set();for(let l of e)"cmd"===l?n.add("mac"===t?"meta":"ctrl"):"ctrl"===l?n.add("ctrl"):"alt"===l?n.add("alt"):"shift"===l&&n.add("shift");return n;}(t.mod,n);return e.metaKey===l.has("meta")&&e.ctrlKey===l.has("ctrl")&&e.altKey===l.has("alt")&&e.shiftKey===l.has("shift");}(e,t.chord,a)){e.preventDefault(),r.current(t.commandId);return;}}}return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e);},[n,a]),(0,i.useMemo)(()=>({bindings:n,conflicts:s,reserved:o}),[n,s,o]);}({bindings:lN,dispatch:(0,i.useCallback)(e=>{var t;"undo"===e?ec.undo():"redo"===e?ec.redo():"focus-status"===e&&(null==(t=es.current)||t.focus());},[ec])}),(0,i.useEffect)(()=>{let e=document.documentElement,t=()=>{e.setAttribute("data-input-modality","pointer");},n=t=>{t.metaKey||t.ctrlKey||t.altKey||"Tab"===t.key&&e.setAttribute("data-input-modality","keyboard");};return e.setAttribute("data-input-modality","pointer"),window.addEventListener("pointerdown",t,!0),window.addEventListener("mousedown",t,!0),window.addEventListener("keydown",n,!0),()=>{window.removeEventListener("pointerdown",t,!0),window.removeEventListener("mousedown",t,!0),window.removeEventListener("keydown",n,!0),e.removeAttribute("data-input-modality");};},[]);let em=(0,i.useMemo)(()=>function(e,t,n,l,a,i){let r=[];for(let e of uj){let t=$[e];r.push({id:`new-${e}`,label:`New ${t.title}`,group:"Create",icon:t.icon,run:()=>n(e)});}for(let e of uk){let n=$[e];r.push({id:`open-${e}`,label:`Open ${n.title}`,group:"Tools",icon:n.icon,run:()=>t(e)});}return r.push({id:"tile",label:"Tile all windows",group:"Layout",icon:"tile",run:e.tileAll}),r.push({id:"split",label:"Split front windows",group:"Layout",icon:"split",run:e.splitFront}),r.push({id:"cascade",label:"Cascade windows",group:"Layout",icon:"cascade",run:e.cascade}),r.push({id:"theme",label:"Toggle light / dark theme",group:"View",icon:"light"===l?"moon":"sun",run:a}),r.push({id:"undo",label:null!==i.undoLabel?`Undo: ${i.undoLabel}`:"Undo (window and panel changes only)",group:"Edit",icon:"back",shortcut:"⌘Z",run:i.undo}),r.push({id:"redo",label:null!==i.redoLabel?`Redo: ${i.redoLabel}`:"Redo (window and panel changes only)",group:"Edit",icon:"fwd",shortcut:"⇧⌘Z",run:i.redo}),r;}(T.api,ed,en,h,f,ec),[T.api,ed,en,h,f,ec]),eh=!v.loading&&void 0===v.error&&0===v.models.length,ef=(c=null==(l=v.activeProject)?void 0:l.name,v.loading?"Loading project…":void 0!==c&&c.trim().length>0?c:"No project selected"),eg=void 0!==v.activeProject,ev=(null==(r=v.activeProject)?void 0:r.available)===!0,eb=(d={loading:v.loading,error:v.error,hasProject:eg,projectAvailable:ev,noEligibleModels:v.noEligibleModels}).loading?"Loading shell…":void 0!==d.error?"Shell error":d.hasProject?d.projectAvailable?d.noEligibleModels?"Gateway setup required":"Ready":"Project unavailable":"No project selected",ex=0===(m=(null!=(u=T.wins)?u:[]).filter(e=>"review"===e.type)).length?"No review open":m.some(e=>"string"==typeof e.cfg.runId&&e.cfg.runId.length>0)?"Evidence ready":"Review window open",ey=void 0!==(p=null==(o=v.activeChat)?void 0:o.branchLabel)&&p.trim().length>0?p:"No branch selected",ew=q?(0,a.jsx)(t3,{types:$,order:uj,onAdd:en,onClose:Q}):null;return(0,a.jsx)(s,{value:v,children:(0,a.jsx)(j.Provider,{value:X,children:(0,a.jsxs)("div",{className:"app",children:[(0,a.jsx)("a",{className:"skip-link",href:"#main",children:"Skip to content"}),(0,a.jsx)("h1",{className:"visually-hidden",children:"Keiko workspace"}),(0,a.jsx)(P,{openPalette:G,openCommandPalette:er,onTileAll:T.api.tileAll,onSplitFront:T.api.splitFront,onCascade:T.api.cascade}),(0,a.jsxs)("div",{className:"mid",children:[eh?null:(0,a.jsx)(O,{openTools:Y,onTool:ed,onNewChat:eu,theme:h,onToggleTheme:f}),(0,a.jsxs)("div",{className:"stage",id:"main",tabIndex:-1,children:[(0,a.jsx)(tD,{ws:T,wsRef:b,openPalette:G,palette:ew}),null!==S&&(0,a.jsxs)("div",{className:"source-limit-alert",role:"alert",children:[(0,a.jsx)("span",{children:S}),(0,a.jsx)("button",{type:"button",className:"source-limit-alert-dismiss","aria-label":"Dismiss source connection notice",onClick:()=>C(null),children:"\xd7"})]})]}),eh?null:(0,a.jsx)(K,{openTools:Y,onTool:ed})]}),(0,a.jsx)(M,{winCount:H,windows:null!=(t=T.wins)?t:[],windowPaletteOpen:_,onToggleWindowPalette:Z,onSelectWindow:et,onCloseWindowPalette:ee,mode:g.mode,selectedModel:v.selectedModel,projectName:ef,branchLabel:ey,shellStatusLabel:eb,evidenceStatusLabel:ex,statusRef:eo}),null!==z&&(0,a.jsx)(t2,{type:z,types:$,filesContext:T.api.currentFilesContext(),onConfirm:el,onClose:ea}),W&&(0,a.jsx)(tq,{commands:em,onClose:ei}),eh?(0,a.jsx)(tL,{}):null,(0,a.jsx)(uh,{})]})})});}function uS(){let[e,t]=(0,i.useState)(!1);return((0,i.useEffect)(()=>{try{window.sessionStorage.removeItem("keiko.app-boot-recovery-reload-count");}catch{}t(!0);},[]),(0,i.useEffect)(()=>{!function(){if(!("u">typeof navigator&&"serviceWorker"in navigator))return;let e=navigator.serviceWorker;try{e.register("/sw.js",{scope:"/"}).then(t=>{e.addEventListener("controllerchange",uv),null!==e.controller&&ub(t),t.addEventListener("updatefound",()=>{let n;n=t.installing,null!==n&&n.addEventListener("statechange",()=>{"installed"!==n.state||null!==e.controller&&ub(t);});});}).catch(e=>{});}catch{}}();},[]),e)?(0,a.jsx)(y,{children:(0,a.jsx)(uN,{})}):(0,a.jsx)("div",{className:"app","aria-hidden":"true",children:(0,a.jsx)("div",{className:"app-boot",children:(0,a.jsx)("img",{className:"app-boot-logo",src:"/assets/keiko-logo.svg",alt:""})})});}function uC(){return(0,a.jsx)(uS,{});}}}]);
|