@oscharko-dev/keiko 0.2.0-beta.8 → 0.2.0-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (241) hide show
  1. package/dist/ui/csp-hashes.json +14 -14
  2. package/dist/ui/static/404.html +1 -1
  3. package/dist/ui/static/__next.__PAGE__.txt +2 -2
  4. package/dist/ui/static/__next._full.txt +3 -3
  5. package/dist/ui/static/__next._head.txt +1 -1
  6. package/dist/ui/static/__next._index.txt +2 -2
  7. package/dist/ui/static/__next._tree.txt +2 -2
  8. package/dist/ui/static/_next/static/chunks/06-q1ntr51v8r.js +1 -0
  9. package/dist/ui/static/_next/static/chunks/0y9qlvrxsyign.js +109 -0
  10. package/dist/ui/static/_next/static/chunks/1h0v66-p9cx19.css +1 -0
  11. package/dist/ui/static/_next/static/chunks/3ewv4mguqzooj.js +1 -0
  12. package/dist/ui/static/_not-found/__next._full.txt +2 -2
  13. package/dist/ui/static/_not-found/__next._head.txt +1 -1
  14. package/dist/ui/static/_not-found/__next._index.txt +2 -2
  15. package/dist/ui/static/_not-found/__next._not-found.__PAGE__.txt +1 -1
  16. package/dist/ui/static/_not-found/__next._not-found.txt +1 -1
  17. package/dist/ui/static/_not-found/__next._tree.txt +2 -2
  18. package/dist/ui/static/_not-found.html +1 -1
  19. package/dist/ui/static/_not-found.txt +2 -2
  20. package/dist/ui/static/index.html +1 -1
  21. package/dist/ui/static/index.txt +3 -3
  22. package/dist/ui/static/launch/__next._full.txt +3 -3
  23. package/dist/ui/static/launch/__next._head.txt +1 -1
  24. package/dist/ui/static/launch/__next._index.txt +2 -2
  25. package/dist/ui/static/launch/__next._tree.txt +2 -2
  26. package/dist/ui/static/launch/__next.launch.__PAGE__.txt +2 -2
  27. package/dist/ui/static/launch/__next.launch.txt +1 -1
  28. package/dist/ui/static/launch.html +1 -1
  29. package/dist/ui/static/launch.txt +3 -3
  30. package/dist/ui/static/local-knowledge/__next._full.txt +3 -3
  31. package/dist/ui/static/local-knowledge/__next._head.txt +1 -1
  32. package/dist/ui/static/local-knowledge/__next._index.txt +2 -2
  33. package/dist/ui/static/local-knowledge/__next._tree.txt +2 -2
  34. package/dist/ui/static/local-knowledge/__next.local-knowledge.__PAGE__.txt +2 -2
  35. package/dist/ui/static/local-knowledge/__next.local-knowledge.txt +1 -1
  36. package/dist/ui/static/local-knowledge/capsule/__next._full.txt +3 -3
  37. package/dist/ui/static/local-knowledge/capsule/__next._head.txt +1 -1
  38. package/dist/ui/static/local-knowledge/capsule/__next._index.txt +2 -2
  39. package/dist/ui/static/local-knowledge/capsule/__next._tree.txt +2 -2
  40. package/dist/ui/static/local-knowledge/capsule/__next.local-knowledge.capsule.__PAGE__.txt +2 -2
  41. package/dist/ui/static/local-knowledge/capsule/__next.local-knowledge.capsule.txt +1 -1
  42. package/dist/ui/static/local-knowledge/capsule/__next.local-knowledge.txt +1 -1
  43. package/dist/ui/static/local-knowledge/capsule.html +1 -1
  44. package/dist/ui/static/local-knowledge/capsule.txt +3 -3
  45. package/dist/ui/static/local-knowledge.html +1 -1
  46. package/dist/ui/static/local-knowledge.txt +3 -3
  47. package/dist/ui/static/memoriaviva/__next._full.txt +2 -2
  48. package/dist/ui/static/memoriaviva/__next._head.txt +1 -1
  49. package/dist/ui/static/memoriaviva/__next._index.txt +2 -2
  50. package/dist/ui/static/memoriaviva/__next._tree.txt +2 -2
  51. package/dist/ui/static/memoriaviva/__next.memoriaviva.__PAGE__.txt +1 -1
  52. package/dist/ui/static/memoriaviva/__next.memoriaviva.txt +1 -1
  53. package/dist/ui/static/memoriaviva/consolidation/__next._full.txt +2 -2
  54. package/dist/ui/static/memoriaviva/consolidation/__next._head.txt +1 -1
  55. package/dist/ui/static/memoriaviva/consolidation/__next._index.txt +2 -2
  56. package/dist/ui/static/memoriaviva/consolidation/__next._tree.txt +2 -2
  57. package/dist/ui/static/memoriaviva/consolidation/__next.memoriaviva.consolidation.__PAGE__.txt +1 -1
  58. package/dist/ui/static/memoriaviva/consolidation/__next.memoriaviva.consolidation.txt +1 -1
  59. package/dist/ui/static/memoriaviva/consolidation/__next.memoriaviva.txt +1 -1
  60. package/dist/ui/static/memoriaviva/consolidation.html +1 -1
  61. package/dist/ui/static/memoriaviva/consolidation.txt +2 -2
  62. package/dist/ui/static/memoriaviva/detail/__next._full.txt +2 -2
  63. package/dist/ui/static/memoriaviva/detail/__next._head.txt +1 -1
  64. package/dist/ui/static/memoriaviva/detail/__next._index.txt +2 -2
  65. package/dist/ui/static/memoriaviva/detail/__next._tree.txt +2 -2
  66. package/dist/ui/static/memoriaviva/detail/__next.memoriaviva.detail.__PAGE__.txt +1 -1
  67. package/dist/ui/static/memoriaviva/detail/__next.memoriaviva.detail.txt +1 -1
  68. package/dist/ui/static/memoriaviva/detail/__next.memoriaviva.txt +1 -1
  69. package/dist/ui/static/memoriaviva/detail.html +1 -1
  70. package/dist/ui/static/memoriaviva/detail.txt +2 -2
  71. package/dist/ui/static/memoriaviva/review-queue/__next._full.txt +2 -2
  72. package/dist/ui/static/memoriaviva/review-queue/__next._head.txt +1 -1
  73. package/dist/ui/static/memoriaviva/review-queue/__next._index.txt +2 -2
  74. package/dist/ui/static/memoriaviva/review-queue/__next._tree.txt +2 -2
  75. package/dist/ui/static/memoriaviva/review-queue/__next.memoriaviva.review-queue.__PAGE__.txt +1 -1
  76. package/dist/ui/static/memoriaviva/review-queue/__next.memoriaviva.review-queue.txt +1 -1
  77. package/dist/ui/static/memoriaviva/review-queue/__next.memoriaviva.txt +1 -1
  78. package/dist/ui/static/memoriaviva/review-queue.html +1 -1
  79. package/dist/ui/static/memoriaviva/review-queue.txt +2 -2
  80. package/dist/ui/static/memoriaviva.html +1 -1
  81. package/dist/ui/static/memoriaviva.txt +2 -2
  82. package/node_modules/@oscharko-dev/keiko-cli/dist/.tsbuildinfo +1 -1
  83. package/node_modules/@oscharko-dev/keiko-cli/package.json +1 -1
  84. package/node_modules/@oscharko-dev/keiko-contracts/dist/.tsbuildinfo +1 -1
  85. package/node_modules/@oscharko-dev/keiko-contracts/dist/index.d.ts +2 -2
  86. package/node_modules/@oscharko-dev/keiko-contracts/dist/index.d.ts.map +1 -1
  87. package/node_modules/@oscharko-dev/keiko-contracts/dist/index.js +1 -1
  88. package/node_modules/@oscharko-dev/keiko-contracts/dist/qualityIntelligence/bffWire.d.ts +36 -4
  89. package/node_modules/@oscharko-dev/keiko-contracts/dist/qualityIntelligence/bffWire.d.ts.map +1 -1
  90. package/node_modules/@oscharko-dev/keiko-contracts/dist/qualityIntelligence/index.d.ts +1 -1
  91. package/node_modules/@oscharko-dev/keiko-contracts/dist/qualityIntelligence/index.d.ts.map +1 -1
  92. package/node_modules/@oscharko-dev/keiko-contracts/package.json +1 -1
  93. package/node_modules/@oscharko-dev/keiko-evaluations/dist/.tsbuildinfo +1 -1
  94. package/node_modules/@oscharko-dev/keiko-evaluations/package.json +1 -1
  95. package/node_modules/@oscharko-dev/keiko-evidence/dist/.tsbuildinfo +1 -1
  96. package/node_modules/@oscharko-dev/keiko-evidence/dist/index.d.ts +1 -1
  97. package/node_modules/@oscharko-dev/keiko-evidence/dist/index.d.ts.map +1 -1
  98. package/node_modules/@oscharko-dev/keiko-evidence/dist/qualityIntelligence/figmaSnapshot/schema.d.ts +15 -0
  99. package/node_modules/@oscharko-dev/keiko-evidence/dist/qualityIntelligence/figmaSnapshot/schema.d.ts.map +1 -1
  100. package/node_modules/@oscharko-dev/keiko-evidence/dist/qualityIntelligence/figmaSnapshot/schema.js +13 -3
  101. package/node_modules/@oscharko-dev/keiko-evidence/dist/qualityIntelligence/figmaSnapshot/store.d.ts +8 -0
  102. package/node_modules/@oscharko-dev/keiko-evidence/dist/qualityIntelligence/figmaSnapshot/store.d.ts.map +1 -1
  103. package/node_modules/@oscharko-dev/keiko-evidence/dist/qualityIntelligence/figmaSnapshot/store.js +30 -2
  104. package/node_modules/@oscharko-dev/keiko-evidence/dist/qualityIntelligence/index.d.ts +2 -2
  105. package/node_modules/@oscharko-dev/keiko-evidence/dist/qualityIntelligence/index.d.ts.map +1 -1
  106. package/node_modules/@oscharko-dev/keiko-evidence/package.json +1 -1
  107. package/node_modules/@oscharko-dev/keiko-harness/dist/.tsbuildinfo +1 -1
  108. package/node_modules/@oscharko-dev/keiko-harness/package.json +1 -1
  109. package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/.tsbuildinfo +1 -1
  110. package/node_modules/@oscharko-dev/keiko-local-knowledge/package.json +1 -1
  111. package/node_modules/@oscharko-dev/keiko-memory-capture/package.json +1 -1
  112. package/node_modules/@oscharko-dev/keiko-memory-consolidation/package.json +1 -1
  113. package/node_modules/@oscharko-dev/keiko-memory-governance/package.json +1 -1
  114. package/node_modules/@oscharko-dev/keiko-memory-retrieval/package.json +1 -1
  115. package/node_modules/@oscharko-dev/keiko-memory-vault/dist/.tsbuildinfo +1 -1
  116. package/node_modules/@oscharko-dev/keiko-memory-vault/package.json +1 -1
  117. package/node_modules/@oscharko-dev/keiko-model-gateway/dist/.tsbuildinfo +1 -1
  118. package/node_modules/@oscharko-dev/keiko-model-gateway/package.json +1 -1
  119. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/.tsbuildinfo +1 -1
  120. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/domain/figma/screenIrTestBaseline.d.ts +8 -0
  121. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/domain/figma/screenIrTestBaseline.d.ts.map +1 -1
  122. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/domain/figma/screenIrTestBaseline.js +9 -5
  123. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/domain/testDesignModel.d.ts +6 -0
  124. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/domain/testDesignModel.d.ts.map +1 -1
  125. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/domain/testDesignModel.js +116 -21
  126. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/domain/testQualityRubric.d.ts +6 -0
  127. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/domain/testQualityRubric.d.ts.map +1 -1
  128. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/domain/testQualityRubric.js +12 -0
  129. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/domain/validation.d.ts.map +1 -1
  130. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/domain/validation.js +8 -7
  131. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/generation/parseGeneratedCandidates.d.ts.map +1 -1
  132. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/generation/parseGeneratedCandidates.js +29 -7
  133. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/generation/prompt.d.ts.map +1 -1
  134. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/generation/prompt.js +61 -24
  135. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/index.d.ts +1 -1
  136. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/index.d.ts.map +1 -1
  137. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/index.js +1 -1
  138. package/node_modules/@oscharko-dev/keiko-quality-intelligence/package.json +1 -1
  139. package/node_modules/@oscharko-dev/keiko-sdk/dist/.tsbuildinfo +1 -1
  140. package/node_modules/@oscharko-dev/keiko-sdk/package.json +1 -1
  141. package/node_modules/@oscharko-dev/keiko-security/dist/.tsbuildinfo +1 -1
  142. package/node_modules/@oscharko-dev/keiko-security/package.json +1 -1
  143. package/node_modules/@oscharko-dev/keiko-server/dist/.tsbuildinfo +1 -1
  144. package/node_modules/@oscharko-dev/keiko-server/dist/conversation-prompt.d.ts.map +1 -1
  145. package/node_modules/@oscharko-dev/keiko-server/dist/conversation-prompt.js +2 -0
  146. package/node_modules/@oscharko-dev/keiko-server/dist/gateway-setup.d.ts.map +1 -1
  147. package/node_modules/@oscharko-dev/keiko-server/dist/gateway-setup.js +30 -6
  148. package/node_modules/@oscharko-dev/keiko-server/dist/grounded-orchestrator.d.ts +1 -0
  149. package/node_modules/@oscharko-dev/keiko-server/dist/grounded-orchestrator.d.ts.map +1 -1
  150. package/node_modules/@oscharko-dev/keiko-server/dist/grounded-orchestrator.js +410 -18
  151. package/node_modules/@oscharko-dev/keiko-server/dist/grounded-prompt.d.ts.map +1 -1
  152. package/node_modules/@oscharko-dev/keiko-server/dist/grounded-prompt.js +1 -0
  153. package/node_modules/@oscharko-dev/keiko-server/dist/grounded-qa-hybrid.d.ts.map +1 -1
  154. package/node_modules/@oscharko-dev/keiko-server/dist/grounded-qa-hybrid.js +7 -5
  155. package/node_modules/@oscharko-dev/keiko-server/dist/grounded-qa-multi-source.js +4 -3
  156. package/node_modules/@oscharko-dev/keiko-server/dist/grounded-qa.d.ts +1 -0
  157. package/node_modules/@oscharko-dev/keiko-server/dist/grounded-qa.d.ts.map +1 -1
  158. package/node_modules/@oscharko-dev/keiko-server/dist/grounded-qa.js +4 -1
  159. package/node_modules/@oscharko-dev/keiko-server/dist/local-knowledge-grounded-qa.d.ts +1 -0
  160. package/node_modules/@oscharko-dev/keiko-server/dist/local-knowledge-grounded-qa.d.ts.map +1 -1
  161. package/node_modules/@oscharko-dev/keiko-server/dist/local-knowledge-grounded-qa.js +8 -3
  162. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figma/figmaConnector.d.ts.map +1 -1
  163. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figma/figmaConnector.js +9 -4
  164. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figma/figmaScopedPagination.d.ts +6 -5
  165. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figma/figmaScopedPagination.d.ts.map +1 -1
  166. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figma/figmaScopedPagination.js +10 -9
  167. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figma/figmaSnapshotBuilder.d.ts +2 -1
  168. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figma/figmaSnapshotBuilder.d.ts.map +1 -1
  169. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figma/figmaSnapshotBuilder.js +62 -26
  170. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figma/figmaSnapshotHash.d.ts +2 -0
  171. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figma/figmaSnapshotHash.d.ts.map +1 -1
  172. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figma/figmaSnapshotHash.js +6 -3
  173. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figma/figmaSnapshotTypes.d.ts +14 -0
  174. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figma/figmaSnapshotTypes.d.ts.map +1 -1
  175. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figmaSnapshotRoutes.d.ts +18 -0
  176. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figmaSnapshotRoutes.d.ts.map +1 -1
  177. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figmaSnapshotRoutes.js +159 -6
  178. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figmaSnapshotScreenIds.d.ts +19 -0
  179. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figmaSnapshotScreenIds.d.ts.map +1 -0
  180. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figmaSnapshotScreenIds.js +75 -0
  181. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/judgePort.d.ts.map +1 -1
  182. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/judgePort.js +13 -12
  183. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/modelSelection.d.ts +6 -6
  184. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/modelSelection.d.ts.map +1 -1
  185. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/modelSelection.js +12 -7
  186. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/reCheckRoutes.d.ts.map +1 -1
  187. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/reCheckRoutes.js +34 -3
  188. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/runIngestion.d.ts +4 -2
  189. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/runIngestion.d.ts.map +1 -1
  190. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/runIngestion.js +222 -35
  191. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/runRoutes.d.ts +7 -0
  192. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/runRoutes.d.ts.map +1 -1
  193. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/runRoutes.js +68 -16
  194. package/node_modules/@oscharko-dev/keiko-server/dist/routes.d.ts.map +1 -1
  195. package/node_modules/@oscharko-dev/keiko-server/dist/routes.js +6 -1
  196. package/node_modules/@oscharko-dev/keiko-server/package.json +1 -1
  197. package/node_modules/@oscharko-dev/keiko-tools/dist/.tsbuildinfo +1 -1
  198. package/node_modules/@oscharko-dev/keiko-tools/package.json +1 -1
  199. package/node_modules/@oscharko-dev/keiko-verification/dist/.tsbuildinfo +1 -1
  200. package/node_modules/@oscharko-dev/keiko-verification/package.json +1 -1
  201. package/node_modules/@oscharko-dev/keiko-workflows/dist/.tsbuildinfo +1 -1
  202. package/node_modules/@oscharko-dev/keiko-workflows/dist/planner/anchors.d.ts.map +1 -1
  203. package/node_modules/@oscharko-dev/keiko-workflows/dist/planner/anchors.js +45 -0
  204. package/node_modules/@oscharko-dev/keiko-workflows/dist/planner/index.d.ts +2 -0
  205. package/node_modules/@oscharko-dev/keiko-workflows/dist/planner/index.d.ts.map +1 -1
  206. package/node_modules/@oscharko-dev/keiko-workflows/dist/planner/index.js +1 -0
  207. package/node_modules/@oscharko-dev/keiko-workflows/dist/planner/intent.d.ts +8 -0
  208. package/node_modules/@oscharko-dev/keiko-workflows/dist/planner/intent.d.ts.map +1 -0
  209. package/node_modules/@oscharko-dev/keiko-workflows/dist/planner/intent.js +140 -0
  210. package/node_modules/@oscharko-dev/keiko-workflows/dist/planner/plan.d.ts +2 -0
  211. package/node_modules/@oscharko-dev/keiko-workflows/dist/planner/plan.d.ts.map +1 -1
  212. package/node_modules/@oscharko-dev/keiko-workflows/dist/planner/plan.js +21 -5
  213. package/node_modules/@oscharko-dev/keiko-workflows/dist/qualityIntelligence/modelRoutedTestDesign.d.ts.map +1 -1
  214. package/node_modules/@oscharko-dev/keiko-workflows/dist/qualityIntelligence/modelRoutedTestDesign.js +86 -40
  215. package/node_modules/@oscharko-dev/keiko-workflows/dist/ranking/rank.d.ts.map +1 -1
  216. package/node_modules/@oscharko-dev/keiko-workflows/dist/ranking/rank.js +9 -0
  217. package/node_modules/@oscharko-dev/keiko-workflows/package.json +1 -1
  218. package/node_modules/@oscharko-dev/keiko-workspace/dist/.tsbuildinfo +1 -1
  219. package/node_modules/@oscharko-dev/keiko-workspace/dist/index.d.ts +1 -0
  220. package/node_modules/@oscharko-dev/keiko-workspace/dist/index.d.ts.map +1 -1
  221. package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearch.d.ts +3 -0
  222. package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearch.d.ts.map +1 -1
  223. package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearch.js +23 -6
  224. package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearchMatchers.d.ts +1 -1
  225. package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearchMatchers.d.ts.map +1 -1
  226. package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearchMatchers.js +24 -3
  227. package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearchPolicy.d.ts +34 -0
  228. package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearchPolicy.d.ts.map +1 -0
  229. package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearchPolicy.js +342 -0
  230. package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearchScan.d.ts +6 -1
  231. package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearchScan.d.ts.map +1 -1
  232. package/node_modules/@oscharko-dev/keiko-workspace/dist/repoSearchScan.js +57 -9
  233. package/node_modules/@oscharko-dev/keiko-workspace/package.json +1 -1
  234. package/package.json +1 -1
  235. package/dist/ui/static/_next/static/chunks/0i3jzgrj42so8.css +0 -1
  236. package/dist/ui/static/_next/static/chunks/1ru_021szp0u7.js +0 -1
  237. package/dist/ui/static/_next/static/chunks/1t7vb5d9ed2e7.js +0 -1
  238. package/dist/ui/static/_next/static/chunks/23o2c6pyjq92z.js +0 -109
  239. /package/dist/ui/static/_next/static/{Ppze_8n_i3yc1FS_Qdj0I → a5sUbXeTgQ9A2LRTMu_Q_}/_buildManifest.js +0 -0
  240. /package/dist/ui/static/_next/static/{Ppze_8n_i3yc1FS_Qdj0I → a5sUbXeTgQ9A2LRTMu_Q_}/_clientMiddlewareManifest.js +0 -0
  241. /package/dist/ui/static/_next/static/{Ppze_8n_i3yc1FS_Qdj0I → a5sUbXeTgQ9A2LRTMu_Q_}/_ssgManifest.js +0 -0
@@ -0,0 +1,109 @@
1
+ (globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,88143,(e,t,n)=>{"use strict";function a({widthInt:e,heightInt:t,blurWidth:n,blurHeight:l,blurDataURL:s,objectFit:i}){let r=n?40*n:e,o=l?40*l:t,c=r&&o?`viewBox='0 0 ${r} ${o}'`:"";return`%3Csvg xmlns='http://www.w3.org/2000/svg' ${c}%3E%3Cfilter id='b' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3CfeColorMatrix values='1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 100 -1' result='s'/%3E%3CfeFlood x='0' y='0' width='100%25' height='100%25'/%3E%3CfeComposite operator='out' in='s'/%3E%3CfeComposite in2='SourceGraphic'/%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3C/filter%3E%3Cimage width='100%25' height='100%25' x='0' y='0' preserveAspectRatio='${c?"none":"contain"===i?"xMidYMid":"cover"===i?"xMidYMid slice":"none"}' style='filter: url(%23b);' href='${s}'/%3E%3C/svg%3E`}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"getImageBlurSvg",{enumerable:!0,get:function(){return a}})},87690,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0});var a={VALID_LOADERS:function(){return s},imageConfigDefault:function(){return i}};for(var l in a)Object.defineProperty(n,l,{enumerable:!0,get:a[l]});let s=["default","imgix","cloudinary","akamai","custom"],i={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[32,48,64,96,128,256,384],path:"/_next/image",loader:"default",loaderFile:"",domains:[],disableStaticImages:!1,minimumCacheTTL:14400,formats:["image/webp"],maximumDiskCacheSize:void 0,maximumRedirects:3,maximumResponseBody:5e7,dangerouslyAllowLocalIP:!1,dangerouslyAllowSVG:!1,contentSecurityPolicy:"script-src 'none'; frame-src 'none'; sandbox;",contentDispositionType:"attachment",localPatterns:void 0,remotePatterns:[],qualities:[75],unoptimized:!1,customCacheHandler:!1}},8927,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"getImgProps",{enumerable:!0,get:function(){return c}}),e.r(33525);let a=e.r(43369),l=e.r(88143),s=e.r(87690),i=["-moz-initial","fill","none","scale-down",void 0];function r(e){return void 0!==e.default}function o(e){return void 0===e?e:"number"==typeof e?Number.isFinite(e)?e:NaN:"string"==typeof e&&/^[0-9]+$/.test(e)?parseInt(e,10):NaN}function c({src:e,sizes:t,unoptimized:n=!1,priority:d=!1,preload:u=!1,loading:m,className:h,quality:p,width:f,height:g,fill:v=!1,style:b,overrideSrc:x,onLoad:y,onLoadingComplete:w,placeholder:j="empty",blurDataURL:k,fetchPriority:N,decoding:S="async",layout:C,objectFit:I,objectPosition:E,lazyBoundary:R,lazyRoot:$,...T},A){var M;let L,q,P,{imgConf:D,showAltText:F,blurComplete:z,defaultLoader:O}=A,K=D||s.imageConfigDefault;if("allSizes"in K)L=K;else{let e=[...K.deviceSizes,...K.imageSizes].sort((e,t)=>e-t),t=K.deviceSizes.sort((e,t)=>e-t),n=K.qualities?.sort((e,t)=>e-t);L={...K,allSizes:e,deviceSizes:t,qualities:n}}if(void 0===O)throw Object.defineProperty(Error("images.loaderFile detected but the file is missing default export.\nRead more: https://nextjs.org/docs/messages/invalid-images-config"),"__NEXT_ERROR_CODE",{value:"E163",enumerable:!1,configurable:!0});let B=T.loader||O;delete T.loader,delete T.srcSet;let _="__next_img_default"in B;if(_){if("custom"===L.loader)throw Object.defineProperty(Error(`Image with src "${e}" is missing "loader" prop.
2
+ Read more: https://nextjs.org/docs/messages/next-image-missing-loader`),"__NEXT_ERROR_CODE",{value:"E252",enumerable:!1,configurable:!0})}else{let e=B;B=t=>{let{config:n,...a}=t;return e(a)}}if(C){"fill"===C&&(v=!0);let e={intrinsic:{maxWidth:"100%",height:"auto"},responsive:{width:"100%",height:"auto"}}[C];e&&(b={...b,...e});let n={responsive:"100vw",fill:"100vw"}[C];n&&!t&&(t=n)}let U="",W=o(f),H=o(g);if((M=e)&&"object"==typeof M&&(r(M)||void 0!==M.src)){let t=r(e)?e.default:e;if(!t.src)throw Object.defineProperty(Error(`An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received ${JSON.stringify(t)}`),"__NEXT_ERROR_CODE",{value:"E460",enumerable:!1,configurable:!0});if(!t.height||!t.width)throw Object.defineProperty(Error(`An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received ${JSON.stringify(t)}`),"__NEXT_ERROR_CODE",{value:"E48",enumerable:!1,configurable:!0});if(q=t.blurWidth,P=t.blurHeight,k=k||t.blurDataURL,U=t.src,!v)if(W||H){if(W&&!H){let e=W/t.width;H=Math.round(t.height*e)}else if(!W&&H){let e=H/t.height;W=Math.round(t.width*e)}}else W=t.width,H=t.height}let Y=!d&&!u&&("lazy"===m||void 0===m);(!(e="string"==typeof e?e:U)||e.startsWith("data:")||e.startsWith("blob:"))&&(n=!0,Y=!1),L.unoptimized&&(n=!0),_&&!L.dangerouslyAllowSVG&&e.split("?",1)[0].endsWith(".svg")&&(n=!0);let J=o(p),G=Object.assign(v?{position:"absolute",height:"100%",width:"100%",left:0,top:0,right:0,bottom:0,objectFit:I,objectPosition:E}:{},F?{}:{color:"transparent"},b),V=z||"empty"===j?null:"blur"===j?`url("data:image/svg+xml;charset=utf-8,${(0,l.getImageBlurSvg)({widthInt:W,heightInt:H,blurWidth:q,blurHeight:P,blurDataURL:k||"",objectFit:G.objectFit})}")`:`url("${j}")`,X=i.includes(G.objectFit)?"fill"===G.objectFit?"100% 100%":"cover":G.objectFit,Q=V?{backgroundSize:X,backgroundPosition:G.objectPosition||"50% 50%",backgroundRepeat:"no-repeat",backgroundImage:V}:{},Z=function({config:e,src:t,unoptimized:n,width:l,quality:s,sizes:i,loader:r}){if(n){if(t.startsWith("/")&&!t.startsWith("//")){let e=(0,a.getDeploymentId)();if(e){let n=t.indexOf("?");if(-1!==n){let a=new URLSearchParams(t.slice(n+1));a.get("dpl")||(a.append("dpl",e),t=t.slice(0,n)+"?"+a.toString())}else t+=`?dpl=${e}`}}return{src:t,srcSet:void 0,sizes:void 0}}let{widths:o,kind:c}=function({deviceSizes:e,allSizes:t},n,a){if(a){let n=/(^|\s)(1?\d?\d)vw/g,l=[];for(let e;e=n.exec(a);)l.push(parseInt(e[2]));if(l.length){let n=.01*Math.min(...l);return{widths:t.filter(t=>t>=e[0]*n),kind:"w"}}return{widths:t,kind:"w"}}return"number"!=typeof n?{widths:e,kind:"w"}:{widths:[...new Set([n,2*n].map(e=>t.find(t=>t>=e)||t[t.length-1]))],kind:"x"}}(e,l,i),d=o.length-1;return{sizes:i||"w"!==c?i:"100vw",srcSet:o.map((n,a)=>`${r({config:e,src:t,quality:s,width:n})} ${"w"===c?n:a+1}${c}`).join(", "),src:r({config:e,src:t,quality:s,width:o[d]})}}({config:L,src:e,unoptimized:n,width:W,quality:J,sizes:t,loader:B}),ee=Y?"lazy":m;return{props:{...T,loading:ee,fetchPriority:N,width:W,height:H,decoding:S,className:h,style:{...G,...Q},sizes:Z.sizes,srcSet:Z.srcSet,src:x||Z.src},meta:{unoptimized:n,preload:u||d,placeholder:j,fill:v}}}},98879,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"default",{enumerable:!0,get:function(){return r}});let a=e.r(71645),l="u"<typeof window,s=l?()=>{}:a.useLayoutEffect,i=l?()=>{}:a.useEffect;function r(e){let{headManager:t,reduceComponentsToState:n}=e;function r(){if(t&&t.mountedInstances){let e=a.Children.toArray(Array.from(t.mountedInstances).filter(Boolean));t.updateHead(n(e))}}return l&&(t?.mountedInstances?.add(e.children),r()),s(()=>(t?.mountedInstances?.add(e.children),()=>{t?.mountedInstances?.delete(e.children)})),s(()=>(t&&(t._pendingUpdate=r),()=>{t&&(t._pendingUpdate=r)})),i(()=>(t&&t._pendingUpdate&&(t._pendingUpdate(),t._pendingUpdate=null),()=>{t&&t._pendingUpdate&&(t._pendingUpdate(),t._pendingUpdate=null)})),null}},25633,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0});var a={default:function(){return f},defaultHead:function(){return u}};for(var l in a)Object.defineProperty(n,l,{enumerable:!0,get:a[l]});let s=e.r(55682),i=e.r(90809),r=e.r(43476),o=i._(e.r(71645)),c=s._(e.r(98879)),d=e.r(42732);function u(){return[(0,r.jsx)("meta",{charSet:"utf-8"},"charset"),(0,r.jsx)("meta",{name:"viewport",content:"width=device-width"},"viewport")]}function m(e,t){return"string"==typeof t||"number"==typeof t?e:t.type===o.default.Fragment?e.concat(o.default.Children.toArray(t.props.children).reduce((e,t)=>"string"==typeof t||"number"==typeof t?e:e.concat(t),[])):e.concat(t)}e.r(33525);let h=["name","httpEquiv","charSet","itemProp"];function p(e){let t,n,a,l;return e.reduce(m,[]).reverse().concat(u().reverse()).filter((t=new Set,n=new Set,a=new Set,l={},e=>{let s=!0,i=!1;if(e.key&&"number"!=typeof e.key&&e.key.indexOf("$")>0){i=!0;let n=e.key.slice(e.key.indexOf("$")+1);t.has(n)?s=!1:t.add(n)}switch(e.type){case"title":case"base":n.has(e.type)?s=!1:n.add(e.type);break;case"meta":for(let t=0,n=h.length;t<n;t++){let n=h[t];if(e.props.hasOwnProperty(n))if("charSet"===n)a.has(n)?s=!1:a.add(n);else{let t=e.props[n],a=l[n]||new Set;("name"!==n||!i)&&a.has(t)?s=!1:(a.add(t),l[n]=a)}}}return s})).reverse().map((e,t)=>{let n=e.key||t;return o.default.cloneElement(e,{key:n})})}let f=function({children:e}){let t=(0,o.useContext)(d.HeadManagerContext);return(0,r.jsx)(c.default,{reduceComponentsToState:p,headManager:t,children:e})};("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),t.exports=n.default)},18556,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"ImageConfigContext",{enumerable:!0,get:function(){return s}});let a=e.r(55682)._(e.r(71645)),l=e.r(87690),s=a.default.createContext(l.imageConfigDefault)},65856,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"RouterContext",{enumerable:!0,get:function(){return a}});let a=e.r(55682)._(e.r(71645)).default.createContext(null)},70965,(e,t,n)=>{"use strict";function a(e,t){let n=e||75;return t?.qualities?.length?t.qualities.reduce((e,t)=>Math.abs(t-n)<Math.abs(e-n)?t:e,t.qualities[0]):n}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"findClosestQuality",{enumerable:!0,get:function(){return a}})},1948,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"default",{enumerable:!0,get:function(){return i}});let a=e.r(70965),l=e.r(43369);function s({config:e,src:t,width:n,quality:i}){let r=(0,l.getDeploymentId)();if(t.startsWith("/")&&!t.startsWith("//")){let e=t.indexOf("?");if(-1!==e){let n=new URLSearchParams(t.slice(e+1)),a=n.get("dpl");if(a){r=a,n.delete("dpl");let l=n.toString();t=t.slice(0,e)+(l?"?"+l:"")}}}if(t.startsWith("/")&&t.includes("?")&&e.localPatterns?.length===1&&"**"===e.localPatterns[0].pathname&&""===e.localPatterns[0].search)throw Object.defineProperty(Error(`Image with src "${t}" is using a query string which is not configured in images.localPatterns.
3
+ Read more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns`),"__NEXT_ERROR_CODE",{value:"E871",enumerable:!1,configurable:!0});let o=(0,a.findClosestQuality)(i,e);return`${e.path}?url=${encodeURIComponent(t)}&w=${n}&q=${o}${t.startsWith("/")&&r?`&dpl=${r}`:""}`}s.__next_img_default=!0;let i=s},5500,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"Image",{enumerable:!0,get:function(){return y}});let a=e.r(55682),l=e.r(90809),s=e.r(43476),i=l._(e.r(71645)),r=a._(e.r(74080)),o=a._(e.r(25633)),c=e.r(8927),d=e.r(87690),u=e.r(18556);e.r(33525);let m=e.r(65856),h=a._(e.r(1948)),p=e.r(18581),f={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[32,48,64,96,128,256,384],qualities:[75],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!0};function g(e,t,n,a,l,s,i){let r=e?.src;e&&e["data-loaded-src"]!==r&&(e["data-loaded-src"]=r,("decode"in e?e.decode():Promise.resolve()).catch(()=>{}).then(()=>{if(e.parentElement&&e.isConnected){if("empty"!==t&&l(!0),n?.current){let t=new Event("load");Object.defineProperty(t,"target",{writable:!1,value:e});let a=!1,l=!1;n.current({...t,nativeEvent:t,currentTarget:e,target:e,isDefaultPrevented:()=>a,isPropagationStopped:()=>l,persist:()=>{},preventDefault:()=>{a=!0,t.preventDefault()},stopPropagation:()=>{l=!0,t.stopPropagation()}})}a?.current&&a.current(e)}}))}function v(e){return i.use?{fetchPriority:e}:{fetchpriority:e}}"u"<typeof window&&(globalThis.__NEXT_IMAGE_IMPORTED=!0);let b=(0,i.forwardRef)(({src:e,srcSet:t,sizes:n,height:a,width:l,decoding:r,className:o,style:c,fetchPriority:d,placeholder:u,loading:m,unoptimized:h,fill:f,onLoadRef:b,onLoadingCompleteRef:x,setBlurComplete:y,setShowAltText:w,sizesInput:j,onLoad:k,onError:N,...S},C)=>{let I=(0,i.useCallback)(e=>{e&&(N&&(e.src=e.src),e.complete&&g(e,u,b,x,y,h,j))},[e,u,b,x,y,N,h,j]),E=(0,p.useMergedRef)(C,I);return(0,s.jsx)("img",{...S,...v(d),loading:m,width:l,height:a,decoding:r,"data-nimg":f?"fill":"1",className:o,style:c,sizes:n,srcSet:t,src:e,ref:E,onLoad:e=>{g(e.currentTarget,u,b,x,y,h,j)},onError:e=>{w(!0),"empty"!==u&&y(!0),N&&N(e)}})});function x({isAppRouter:e,imgAttributes:t}){let n={as:"image",imageSrcSet:t.srcSet,imageSizes:t.sizes,crossOrigin:t.crossOrigin,referrerPolicy:t.referrerPolicy,...v(t.fetchPriority)};return e&&r.default.preload?(r.default.preload(t.src,n),null):(0,s.jsx)(o.default,{children:(0,s.jsx)("link",{rel:"preload",href:t.srcSet?void 0:t.src,...n},"__nimg-"+t.src+t.srcSet+t.sizes)})}let y=(0,i.forwardRef)((e,t)=>{let n=(0,i.useContext)(m.RouterContext),a=(0,i.useContext)(u.ImageConfigContext),l=(0,i.useMemo)(()=>{let e=f||a||d.imageConfigDefault,t=[...e.deviceSizes,...e.imageSizes].sort((e,t)=>e-t),n=e.deviceSizes.sort((e,t)=>e-t),l=e.qualities?.sort((e,t)=>e-t);return{...e,allSizes:t,deviceSizes:n,qualities:l,localPatterns:"u"<typeof window?a?.localPatterns:e.localPatterns}},[a]),{onLoad:r,onLoadingComplete:o}=e,p=(0,i.useRef)(r);(0,i.useEffect)(()=>{p.current=r},[r]);let g=(0,i.useRef)(o);(0,i.useEffect)(()=>{g.current=o},[o]);let[v,y]=(0,i.useState)(!1),[w,j]=(0,i.useState)(!1),{props:k,meta:N}=(0,c.getImgProps)(e,{defaultLoader:h.default,imgConf:l,blurComplete:v,showAltText:w});return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(b,{...k,unoptimized:N.unoptimized,placeholder:N.placeholder,fill:N.fill,onLoadRef:p,onLoadingCompleteRef:g,setBlurComplete:y,setShowAltText:j,sizesInput:e.sizes,ref:t}),N.preload?(0,s.jsx)(x,{isAppRouter:!n,imgAttributes:k}):null]})});("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),t.exports=n.default)},94909,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0});var a={default:function(){return d},getImageProps:function(){return c}};for(var l in a)Object.defineProperty(n,l,{enumerable:!0,get:a[l]});let s=e.r(55682),i=e.r(8927),r=e.r(5500),o=s._(e.r(1948));function c(e){let{props:t}=(0,i.getImgProps)(e,{defaultLoader:o.default,imgConf:{deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[32,48,64,96,128,256,384],qualities:[75],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!0}});for(let[e,n]of Object.entries(t))void 0===n&&delete t[e];return{props:t}}let d=r.Image},57688,(e,t,n)=>{t.exports=e.r(94909)},89199,e=>{"use strict";let t;var n=e.i(43476),a=e.i(71645);let l=(0,a.createContext)(null);function s({value:e,children:t}){return(0,n.jsx)(l.Provider,{value:e,children:t})}function i(){let e=(0,a.useContext)(l);if(null===e)throw Error("useChatSessionContext must be used inside ChatSessionProvider");return e}function r(){return(0,a.useContext)(l)}let o=[{id:"read",action:"Read files",scope:"workspace",decision:"allow"},{id:"write",action:"Write files",scope:"src/** · docs/**",decision:"allow"},{id:"write-prod",action:"Write files",scope:"prod/** · infra/**",decision:"deny"},{id:"command",action:"Run commands",scope:"test · build · lint",decision:"allow"},{id:"command-danger",action:"Run commands",scope:"deploy · rm · 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"}],c={calendar:!0,mail:!1,jira:!0,docs:!0},d="keiko.twin.mode",u="keiko.twin.persona",m="keiko.twin.policy",h="keiko.twin.bridges",p=(0,a.createContext)(null);function f(e,t){try{let n=window.localStorage.getItem(e);if(null===n)return t;let a=JSON.parse(n);return null==a?t:a}catch{return t}}function g(e,t){try{window.localStorage.setItem(e,t)}catch{}}function v(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function b({children:e}){let[t,l]=(0,a.useState)("manual"),[s,i]=(0,a.useState)("Developer"),[r,x]=(0,a.useState)(o),[y,w]=(0,a.useState)(c),[j,k]=(0,a.useState)(!1);(0,a.useEffect)(()=>{l(function(){try{let e=window.localStorage.getItem(d);return"manual"===e||"autonomous"===e?e:"manual"}catch{return"manual"}}()),i(function(){try{let e=window.localStorage.getItem(u);if("Developer"===e||"Product Owner"===e||"Designer"===e)return e;return"Developer"}catch{return"Developer"}}()),x(f(m,o)),w(f(h,c));try{window.localStorage.removeItem("keiko.twin.memory")}catch{}k(!0)},[]),(0,a.useEffect)(()=>{j&&g(d,t)},[t,j]),(0,a.useEffect)(()=>{j&&g(u,s)},[s,j]),(0,a.useEffect)(()=>{j&&v(m,r)},[r,j]),(0,a.useEffect)(()=>{j&&v(h,y)},[y,j]);let N=(0,a.useCallback)((e,t)=>{let n;return n=e=>r.find(t=>t.id===e)?.decision??null,"write"===e?"high"===t?n("write-prod")??"deny":n("write")??"allow":"command"===e?"high"===t?n("command-danger")??"ask":n("command")??"allow":"git"===e?n("pr")??"allow":"mail"===e?n("mail")??"ask":"network"===e?n("network")??"ask":"ask"},[r]),S=(0,a.useMemo)(()=>({mode:t,setMode:l,persona:s,setPersona:i,policy:r,setPolicy:x,bridges:y,setBridges:w,decide:N}),[t,s,r,y,N]);return(0,n.jsx)(p.Provider,{value:S,children:e})}function x(){let e=(0,a.useContext)(p);if(null===e)throw Error("useTwin must be used inside <TwinProvider>");return e}let y=(0,a.createContext)({wins:[],active:null,winCount:0});var w=e.i(76055),j=e.i(17161);let k={w:150,h:110},N={w:290,h:190},S={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:"Edit a text file",w:480,h:360,config:[{key:"file",label:"File path",type:"text",def:"",optional:!0,placeholder:"src/app.ts"},{key:"root",label:"Root",type:"directory",def:"",optional:!0}]},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:"Run a BFF workflow",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},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:"Capture a Figma board snapshot",w:420,h:540,min:{w:320,h:360},tiny:{w:280,h:240}},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}}},C=new Map;function I(e,t){C.set(e,t)}let E=(t={},Object.keys(S).forEach(e=>{var n;let a,l;t[e]=(a={title:(n=S[e]).title,icon:n.icon,desc:n.desc,w:n.w,h:n.h,min:n.min??k,tiny:n.tiny??N,render:(t,n)=>{let a=C.get(e);return void 0!==a?a(t,n):null}},l={},!0===n.accent&&(l.accent=!0),!0===n.tool&&(l.tool=!0),!0===n.singleton&&(l.singleton=!0),void 0!==n.config&&(l.config=n.config),void 0!==n.cta&&(l.cta=n.cta),{...a,...l})}),t),R={agents:["files","terminal","plugins","review","browser","agents","keiko"],chat:["files","browser","plugins","keiko","connector"],files:["agents","chat","quality"],terminal:["agents"],plugins:["agents","chat"],review:["agents"],browser:["agents","chat"],keiko:["agents","chat"],connector:["chat","quality"],quality:["files","connector","figma","figmaJson","figmaImage"],figma:["quality"],figmaJson:["quality"],figmaImage:["quality"]};function $(e,t){return void 0!==e&&void 0!==t&&e!==t&&((R[e]??[]).includes(t)||(R[t]??[]).includes(e))}function T(e,t){let n="files"===e.type?e:"files"===t.type?t:null,a=null===n?null:n===e?t:e;if(null!==n&&null!==a&&("chat"===a.type||"agents"===a.type||"quality"===a.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){let n=e?.activeFilePath;if("string"==typeof n&&n.length>0)return n.split(/[/\\]/u).filter(Boolean).pop()??n;let a=e?.activeDirectoryPath;return"string"==typeof a&&a.length>0?`${a.split(/[/\\]/u).filter(Boolean).pop()??a}/`:`${t.split(/[/\\]/u).filter(Boolean).pop()??t}/`}(n.cfg,e)}`}let l=[e.type,t.type];if(l.includes("connector"))return"uses knowledge";if(l.includes("figmaJson"))return"uses JSON";if(l.includes("figmaImage"))return"uses image";if(l.includes("figma")){let n="figma"===e.type?e:"figma"===t.type?t:null,a=n?.cfg?.selectedScreenName;return"string"==typeof a&&a.trim().length>0?"uses view":"uses snapshot"}return l.includes("keiko")?"governed by":"agents"===l[0]&&"agents"===l[1]?"delegates":l.includes("terminal")?"runs in":l.includes("plugins")?"uses tools":l.includes("review")?"reviews":l.includes("browser")?"browses":"connected"}function A(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 M(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":return n("file");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":return n("selectedScreenName")??n("snapshotRunId");case"figmaJson":return n("selectedScreenName")??n("screenId")??n("snapshotRunId");default:return null}}function L({winCount:e,windows:t,windowPaletteOpen:l,onToggleWindowPalette:s,onSelectWindow:i,onCloseWindowPalette:r,statusRef:o}){let c=(0,a.useRef)(null),[d,u]=(0,a.useState)("version loading"),m=`${String(e)} ${1===e?"window":"windows"}`,h=[...t].sort((e,t)=>t.z-e.z);return(0,a.useEffect)(()=>{let e=!1;return async function(){try{let t=await (0,w.fetchHealth)();e||u(t.version)}catch{e||u("version unavailable")}}(),()=>{e=!0}},[]),(0,a.useEffect)(()=>{if(!l)return;if(0===e)return void r();let t=e=>{let t=e.target;t instanceof Node&&null!==c.current&&!c.current.contains(t)&&r()},n=e=>{"Escape"===e.key&&r()};return document.addEventListener("pointerdown",t),document.addEventListener("keydown",n),()=>{document.removeEventListener("pointerdown",t),document.removeEventListener("keydown",n)}},[r,e,l]),(0,n.jsxs)("footer",{ref:o,className:"footer mono",tabIndex:-1,"aria-label":"Workspace status","aria-live":"polite",children:[(0,n.jsx)("span",{className:"spacer"}),(0,n.jsxs)("span",{className:"ft-brand","aria-label":`Keiko version ${d}`,children:["Keiko | ",d]}),(0,n.jsxs)("span",{className:"ft-window-wrap",ref:c,children:[(0,n.jsxs)("button",{type:"button",className:"ft-seg ft-accent ft-window-trigger","aria-atomic":"true","aria-expanded":l,"aria-controls":"footer-window-palette",disabled:0===e,title:"Open windows in the workspace",onClick:s,children:[(0,n.jsx)(j.Icons.tile,{size:13})," ",m]}),l&&e>0?(0,n.jsxs)("div",{id:"footer-window-palette",className:"ft-window-palette",role:"menu","aria-label":"Open windows",children:[(0,n.jsx)("div",{className:"ft-window-palette-head",children:"Open windows"}),(0,n.jsx)("div",{className:"ft-window-list",children:h.map(e=>{let t=E[e.type],a=j.Icons[t.icon],l=M(e.type,e.cfg),s=!0===e.minimized?"Minimized":e.max?"Fullscreen":"Visible",r=!0===e.minimized?"Restore":"Focus";return(0,n.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:()=>i(e.id),children:[(0,n.jsx)("span",{className:"ft-window-icon",style:{color:!0===t.accent?"var(--accent)":void 0},children:(0,n.jsx)(a,{size:14})}),(0,n.jsxs)("span",{className:"ft-window-copy",children:[(0,n.jsx)("span",{className:"ft-window-title",children:t.title}),(0,n.jsx)("span",{className:"ft-window-sub",title:l??s,children:l??s})]}),(0,n.jsx)("span",{className:"ft-window-state",children:s})]},e.id)})})]}):null]})]})}function q({openPalette:e,openCommandPalette:t,onTileAll:a,onSplitFront:l,onCascade:s}){return(0,n.jsxs)("header",{className:"header",children:[(0,n.jsxs)("div",{className:"hd-brand",children:[(0,n.jsx)("img",{className:"hd-logo",src:"/assets/keiko-logo.svg",alt:""}),(0,n.jsx)("span",{className:"hd-wordmark",children:"Keiko"})]}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsxs)("div",{className:"hd-tools",children:[(0,n.jsxs)("button",{type:"button",className:"hd-tool hd-tool-cta",onClick:e,title:"New window — press Ctrl/⌘K for all commands",children:[(0,n.jsx)(j.Icons.add,{size:16}),(0,n.jsx)("span",{children:"New"})]}),(0,n.jsx)("button",{type:"button",className:"hd-tool hd-tool-kbd",onClick:t,title:"Open the command palette (Ctrl/⌘K)","aria-label":"Open the command palette (Ctrl/⌘K)",children:(0,n.jsx)("span",{className:"kbd","aria-hidden":"true",children:"⌘K"})}),(0,n.jsx)("span",{className:"hd-div"}),(0,n.jsx)("button",{type:"button",className:"hd-tool",onClick:a,title:"Tile all windows","aria-label":"Tile all windows",children:(0,n.jsx)(j.Icons.tile,{size:16})}),(0,n.jsx)("button",{type:"button",className:"hd-tool",onClick:l,title:"Split front windows","aria-label":"Split front windows",children:(0,n.jsx)(j.Icons.split,{size:16})}),(0,n.jsx)("button",{type:"button",className:"hd-tool",onClick:s,title:"Cascade windows","aria-label":"Cascade windows",children:(0,n.jsx)(j.Icons.cascade,{size:16})})]})]})}let P=[{id:"chatHistory",icon:"archive",label:"Chat History"}];function D({tool:e,active:t,onClick:a}){let l=j.Icons[e.icon];return(0,n.jsx)("button",{type:"button",className:"rail-btn","data-active":t?"true":"false","data-side":"left","aria-label":e.label,"aria-pressed":t,"data-tip":e.label,onClick:a,children:void 0!==e.img?(0,n.jsx)("img",{className:"rail-img",src:e.img,alt:""}):(0,n.jsx)(l,{size:19})})}function F({openTools:e,onTool:t,onNewChat:a,theme:l,onToggleTheme:s}){return(0,n.jsxs)("nav",{className:"rail rail-left","aria-label":"Primary workspace navigation",children:[(0,n.jsx)("button",{type:"button",className:"rail-new",onClick:a,"data-side":"left","aria-label":"New chat","data-tip":"New chat",children:(0,n.jsx)(j.Icons.newChat,{size:18})}),(0,n.jsx)("div",{className:"rail-div"}),(0,n.jsx)("div",{className:"rail-group",children:P.map(a=>(0,n.jsx)(D,{tool:a,active:e.has(a.id),onClick:()=>t(a.id)},a.id))}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsxs)("div",{className:"rail-group",children:[(0,n.jsx)("button",{type:"button",className:"rail-btn","data-active":e.has("memoria")?"true":"false","data-side":"left","aria-label":"MemoriaViva","aria-pressed":e.has("memoria"),"data-tip":"MemoriaViva",onClick:()=>t("memoria"),children:(0,n.jsx)(j.Icons.brain,{size:19})}),(0,n.jsx)("button",{type:"button",className:"rail-btn","data-side":"left","data-active":e.has("quality")?"true":"false","aria-label":"Quality Intelligence","aria-pressed":e.has("quality"),"data-tip":"Quality Intelligence",onClick:()=>t("quality"),children:(0,n.jsx)(j.Icons.check,{size:19})}),(0,n.jsx)("button",{type:"button",className:"rail-btn","data-side":"left","data-active":e.has("localKnowledge")?"true":"false","aria-label":"Local Knowledge","aria-pressed":e.has("localKnowledge"),"data-tip":"Local Knowledge",onClick:()=>t("localKnowledge"),children:(0,n.jsx)(j.Icons.localKnowledge,{size:19})})]}),(0,n.jsx)("div",{className:"rail-div"}),(0,n.jsx)("button",{type:"button",className:"rail-btn","data-side":"left","aria-label":"light"===l?"Dark mode":"Light mode","aria-pressed":"light"===l,"data-tip":"light"===l?"Dark mode":"Light mode",onClick:s,children:"light"===l?(0,n.jsx)(j.Icons.moon,{size:19}):(0,n.jsx)(j.Icons.sun,{size:19})}),(0,n.jsx)("button",{type:"button",className:"rail-btn","data-side":"left","data-active":e.has("settings")?"true":"false","aria-label":"Settings","aria-pressed":e.has("settings"),"data-tip":"Settings",onClick:()=>t("settings"),children:(0,n.jsx)(j.Icons.settings,{size:19})})]})}function z(e){return(0,n.jsx)("aside",{className:"rail rail-right","aria-label":"Workspace utilities"})}function O(e){return e.toFixed(2)}function K({onNewWindow:e}){let t=(0,a.useId)(),l=`ewb-${t.replace(/:/gu,"")}`,s=(0,a.useRef)(null),i=(0,a.useRef)(null);(0,a.useEffect)(()=>{let e=e=>{s.current?.setAttribute("d",function(e){let t=[];for(let n=0;n<150;n++){let a=n/150*Math.PI*2,l=1+.07*(.55*Math.sin(3*a+e)+.32*Math.sin(5*a-.8*e+1.7)+.22*Math.sin(2*a+.5*e+.4));t.push([140+127.44000000000001*l*Math.cos(a),140+118*l*Math.sin(a)])}let n=`M${O(t[0]?.[0]??140)} ${O(t[0]?.[1]??140)} `;for(let e=0;e<t.length;e++){let a=t[(e-1+t.length)%t.length],l=t[e],s=t[(e+1)%t.length],i=t[(e+2)%t.length],r=l[0]+(s[0]-a[0])/6,o=l[1]+(s[1]-a[1])/6,c=s[0]-(i[0]-l[0])/6,d=s[1]-(i[1]-l[1])/6;n+=`C${O(r)} ${O(o)} ${O(c)} ${O(d)} ${O(s[0])} ${O(s[1])} `}return`${n}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)},a=n=>{e(85e-5*n),t=window.requestAnimationFrame(a)},l=()=>{0===t&&!0!==document.hidden&&(t=window.requestAnimationFrame(a))},i=()=>{!0===document.hidden?n():l()};return l(),document.addEventListener("visibilitychange",i),window.addEventListener("blur",n),window.addEventListener("focus",l),()=>{n(),document.removeEventListener("visibilitychange",i),window.removeEventListener("blur",n),window.removeEventListener("focus",l)}},[]);let r=(0,a.useCallback)(()=>{let t=i.current;null!==t&&(t.classList.remove("is-pulse"),t.getBoundingClientRect(),t.classList.add("is-pulse")),e()},[e]);return(0,n.jsx)("button",{type:"button",className:"empty-workspace-blob","aria-label":"Open a new window",onClick:r,children:(0,n.jsxs)("svg",{width:"320",height:"320",viewBox:"0 0 280 280","aria-hidden":"true",children:[(0,n.jsx)("defs",{children:(0,n.jsxs)("mask",{id:l,maskUnits:"userSpaceOnUse",x:"0",y:"0",width:"280",height:"280",children:[(0,n.jsx)("rect",{x:"0",y:"0",width:"280",height:"280",fill:"#fff"}),(0,n.jsx)("g",{transform:"translate(107,64) scale(0.080625)",children:(0,n.jsx)("g",{transform:"translate(1024 0) scale(-1 1)",children:(0,n.jsx)("g",{transform:"translate(1024,1024) scale(-0.1,-0.1)",fill:"#000",children:(0,n.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,n.jsx)("text",{x:"140",y:"172",textAnchor:"middle",fill:"#000",fontFamily:"var(--font-ui)",fontSize:"16",fontWeight:"700",children:"Empty workspace"}),(0,n.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,n.jsx)("g",{ref:i,className:"empty-workspace-blob__group",children:(0,n.jsx)("path",{ref:s,className:"empty-workspace-blob__fill",mask:`url(#${l})`})})]})})}function B(e){return 0===e.button&&!(0===e.button&&e.ctrlKey)}function _(e){return B(e)||1===e.button}function U(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,.ws-outline,.conn-badge")}function W(){return!("u"<typeof document)&&"true"===document.documentElement.getAttribute("data-keiko-modal-open")}let H=0,Y="",J="";function G(){if("u"<typeof document)return()=>void 0;let e=document.body;0===H&&(Y=e.style.cursor,J=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=Y,e.style.userSelect=J))}}let V="keiko.wallpaper.enabled",X="keiko.wallpaper.opacity",Q="keiko.workspace.background.brightness",Z="keiko.workspace.grid.strength",ee="keiko.frame.border.strength",et="keiko:wallpaper-enabled",en="keiko:wallpaper-opacity",ea="keiko:workspace-background-brightness",el="keiko:workspace-grid-strength",es="keiko:frame-border-strength";function ei(e){return Number.isFinite(e)?Math.max(0,Math.min(100,e)):0}function er(){return"true"===window.localStorage.getItem(V)}function eo(){let e=window.localStorage.getItem(X);return null===e?100:ei(Number.parseInt(e,10))}function ec(){let e=window.localStorage.getItem(Q);return null===e?0:ei(Number.parseInt(e,10))}function ed(){let e=window.localStorage.getItem(Z);return null===e?28:ei(Number.parseInt(e,10))}function eu(){let e=window.localStorage.getItem(ee);return null===e?42:ei(Number.parseInt(e,10))}function em(e){"u">typeof document&&document.documentElement.style.setProperty("--workspace-bg-brightness",`${ei(e)}%`)}function eh(e){"u">typeof document&&document.documentElement.style.setProperty("--workspace-grid-strength",`${ei(e)}%`)}function ep(e){"u">typeof document&&document.documentElement.style.setProperty("--frame-border-strength",`${ei(e)}%`)}let ef=`
4
+ attribute vec2 aPos;
5
+ void main(){ gl_Position = vec4(aPos, 0.0, 1.0); }
6
+ `,eg=`
7
+ precision highp float;
8
+ uniform vec2 uRes;
9
+ uniform float uTime;
10
+ uniform vec2 uMouse; // 0..1, y up
11
+ uniform float uLight; // 1 = light theme, 0 = dark; WebGL default 0 keeps failure mode dark
12
+ uniform vec2 uRip[4]; // ripple origins (0..1, y up)
13
+ uniform float uRipT[4]; // seconds since each ripple fired (large = inactive)
14
+
15
+ float hash(vec2 p){
16
+ p = fract(p * vec2(123.34, 456.21));
17
+ p += dot(p, p + 45.32);
18
+ return fract(p.x * p.y);
19
+ }
20
+ float vnoise(vec2 p){
21
+ vec2 i = floor(p), f = fract(p);
22
+ vec2 u = f * f * (3.0 - 2.0 * f);
23
+ float a = hash(i), b = hash(i + vec2(1.,0.));
24
+ float c = hash(i + vec2(0.,1.)), d = hash(i + vec2(1.,1.));
25
+ return mix(mix(a,b,u.x), mix(c,d,u.x), u.y);
26
+ }
27
+ float fbm(vec2 p){
28
+ float v = 0.0, a = 0.5;
29
+ mat2 m = mat2(1.6, 1.2, -1.2, 1.6);
30
+ for(int i = 0; i < 5; i++){ v += a * vnoise(p); p = m * p; a *= 0.5; }
31
+ return v;
32
+ }
33
+
34
+ void main(){
35
+ vec2 uv = gl_FragCoord.xy / uRes.xy;
36
+ float aspect = uRes.x / uRes.y;
37
+ vec2 p = vec2(uv.x * aspect, uv.y);
38
+ vec2 m = vec2(uMouse.x * aspect, uMouse.y);
39
+
40
+ float t = uTime * 0.06;
41
+
42
+ // --- click ripples ---------------------------------------------------
43
+ float rip = 0.0;
44
+ for(int i = 0; i < 4; i++){
45
+ float age = uRipT[i];
46
+ if(age < 2.4){
47
+ vec2 rc = vec2(uRip[i].x * aspect, uRip[i].y);
48
+ float d = distance(p, rc);
49
+ float ring = sin(d * 15.0 - age * 9.0);
50
+ float env = exp(-d * 3.6) * exp(-age * 2.1);
51
+ rip += ring * env;
52
+ }
53
+ }
54
+
55
+ // --- liquid domain warp ---------------------------------------------
56
+ vec2 warp = vec2(
57
+ fbm(p * 2.1 + vec2(0.0, t)),
58
+ fbm(p * 2.1 + vec2(t, 4.7))
59
+ );
60
+ // mouse bends the flow toward the cursor
61
+ vec2 toM = m - p;
62
+ float md = exp(-length(toM) * 2.2);
63
+ warp += toM * md * 0.28;
64
+ warp += rip * 0.07;
65
+
66
+ float f = fbm(p * 2.4 + warp * 1.7 + vec2(t * 0.6, 0.0));
67
+
68
+ // --- chrome banding (sharp metallic streaks) ------------------------
69
+ float bands = abs(sin((f * 4.0 + warp.x * 2.0) * 3.14159 + t * 1.4));
70
+ float chrome = pow(bands, 2.6);
71
+
72
+ // --- palette (brand) -------------------------------------------------
73
+ vec3 baseD = vec3(0.072, 0.085, 0.079); // warm near-black ~ --bg
74
+ vec3 metalD = vec3(0.205, 0.230, 0.216); // chrome mid grey
75
+ vec3 baseL = vec3(0.930, 0.942, 0.935); // near-white
76
+ vec3 metalL = vec3(0.795, 0.835, 0.812); // soft grey
77
+ vec3 green = vec3(0.306, 0.729, 0.529); // #4EBA87
78
+
79
+ vec3 base = mix(baseD, baseL, uLight);
80
+ vec3 metal = mix(metalD, metalL, uLight);
81
+
82
+ vec3 col = mix(base, metal, chrome * 0.85);
83
+
84
+ // orca-green sheen on the brightest specular ridges
85
+ float spec = smoothstep(0.80, 1.0, bands);
86
+ col += green * spec * mix(0.16, 0.085, uLight);
87
+
88
+ // soft green glow trailing the cursor — fun to fidget with
89
+ col += green * md * 0.085;
90
+
91
+ // ripple highlight
92
+ vec3 ripCol = mix(vec3(1.0), green, uLight);
93
+ col += ripCol * max(rip, 0.0) * 0.032;
94
+
95
+ // keep it dezent — pull back toward base
96
+ col = mix(base, col, 0.84);
97
+
98
+ gl_FragColor = vec4(col, 1.0);
99
+ }
100
+ `;function ev(e,t,n){let a=e.createShader(t);return null===a?null:(e.shaderSource(a,n),e.compileShader(a),e.getShaderParameter(a,e.COMPILE_STATUS))?a:(e.deleteShader(a),null)}function eb(){let e=(0,a.useRef)(null),[t,l]=(0,a.useState)(er);return(0,a.useEffect)(()=>{em(ec()),eh(ed()),ep(eu());let e=e=>{let t=e.detail;em("number"==typeof t?t:ec())},t=e=>{let t=e.detail;eh("number"==typeof t?t:ed())},n=e=>{let t=e.detail;ep("number"==typeof t?t:eu())};return window.addEventListener(ea,e),window.addEventListener(el,t),window.addEventListener(es,n),()=>{window.removeEventListener(ea,e),window.removeEventListener(el,t),window.removeEventListener(es,n)}},[]),(0,a.useEffect)(()=>{let e=e=>{let t=e.detail;l("boolean"==typeof t?t:er())},t=e=>{(null===e.key||e.key===V)&&l(er())};return window.addEventListener(et,e),window.addEventListener("storage",t),()=>{window.removeEventListener(et,e),window.removeEventListener("storage",t)}},[]),(0,a.useEffect)(()=>{let n;if(!t)return;let a=e.current;if(null===a)return;let l=a.parentElement;if(null===l)return;let s=window.matchMedia("(prefers-reduced-motion: reduce)"),i=()=>{s.matches?(n?.(),n=void 0):void 0===n&&(n=function(e,t){t.style.opacity=String(eo()/100);let n=e=>{let n=e.detail,a="number"==typeof n?n:eo();t.style.opacity=String(ei(a)/100)};window.addEventListener(en,n);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(en,n)};let l=ev(a,a.VERTEX_SHADER,ef),s=ev(a,a.FRAGMENT_SHADER,eg);if(null===l||null===s)return()=>{window.removeEventListener(en,n)};let i=a.createProgram();if(null===i||(a.attachShader(i,l),a.attachShader(i,s),a.linkProgram(i),!a.getProgramParameter(i,a.LINK_STATUS)))return()=>{window.removeEventListener(en,n)};a.useProgram(i);let r=a.createBuffer();a.bindBuffer(a.ARRAY_BUFFER,r),a.bufferData(a.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),a.STATIC_DRAW);let o=a.getAttribLocation(i,"aPos");a.enableVertexAttribArray(o),a.vertexAttribPointer(o,2,a.FLOAT,!1,0,0);let c=a.getUniformLocation(i,"uRes"),d=a.getUniformLocation(i,"uTime"),u=a.getUniformLocation(i,"uMouse"),m=a.getUniformLocation(i,"uLight"),h=a.getUniformLocation(i,"uRip"),p=a.getUniformLocation(i,"uRipT"),f=1,g=1,v=Math.min(window.devicePixelRatio??1,1.5),b={tx:.5,ty:.5,x:.5,y:.5},x=new Float32Array(8),y=[,,,,].fill(-1/0),w=0;function j(){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)}j();let k="u">typeof ResizeObserver?new ResizeObserver(j):null;null!==k?k.observe(e):window.addEventListener("resize",j);let N=t=>{let n=e.getBoundingClientRect();b.tx=(t.clientX-n.left)/Math.max(1,n.width),b.ty=1-(t.clientY-n.top)/Math.max(1,n.height)},S=t=>{let n=e.getBoundingClientRect(),a=(t.clientX-n.left)/Math.max(1,n.width),l=1-(t.clientY-n.top)/Math.max(1,n.height);a<0||a>1||l<0||l>1||(x[2*w]=a,x[2*w+1]=l,y[w]=performance.now(),w=(w+1)%4)};e.addEventListener("pointermove",N),e.addEventListener("pointerdown",S);let C=performance.now(),I=0,E=!0,R=new Float32Array(4);function $(){if(!E)return;let e=performance.now();b.x+=(b.tx-b.x)*.06,b.y+=(b.ty-b.y)*.06;for(let t=0;t<4;t++)R[t]=(e-(y[t]??-1/0))/1e3;let n=+("light"===document.documentElement.dataset.theme);null!==a&&(a.uniform2f(c,t.width,t.height),a.uniform1f(d,(e-C)/1e3),a.uniform2f(u,b.x,b.y),a.uniform1f(m,n),a.uniform2fv(h,x),a.uniform1fv(p,R),a.drawArrays(a.TRIANGLES,0,3)),I=requestAnimationFrame($)}I=requestAnimationFrame($);let T=()=>{document.hidden?(E=!1,cancelAnimationFrame(I)):E||(E=!0,I=requestAnimationFrame($))};return document.addEventListener("visibilitychange",T),()=>{E=!1,cancelAnimationFrame(I),document.removeEventListener("visibilitychange",T),window.removeEventListener(en,n),e.removeEventListener("pointermove",N),e.removeEventListener("pointerdown",S),null!==k?k.disconnect():window.removeEventListener("resize",j),null!==a&&(a.deleteBuffer(r),a.deleteProgram(i),a.deleteShader(l),a.deleteShader(s))}}(l,a))};return i(),s.addEventListener("change",i),()=>{s.removeEventListener("change",i),n?.()}},[t]),t?(0,n.jsx)("canvas",{ref:e,className:"ws-shader","aria-hidden":"true"}):null}let ex=new Set(["files","connector","browser","plugins","agents","quality"]);function ey(e,t){return e>=4||t>=8192}function ew({pathId:e,intensity:t}){let a="heavy"===t?3:1,l="heavy"===t?1.1:2.2;return(0,n.jsx)(n.Fragment,{children:Array.from({length:a},(s,i)=>(0,n.jsx)("circle",{className:"conn-particle",r:"heavy"===t?3:2.4,"aria-hidden":"true",children:(0,n.jsx)("animateMotion",{dur:`${String(l)}s`,repeatCount:"indefinite",begin:`${String(l/a*i)}s`,rotate:"auto",keyPoints:"0;1",keyTimes:"0;1",calcMode:"linear",children:(0,n.jsx)("mpath",{href:`#${e}`})})},i))})}function ej({wins:e,conns:t,connecting:l,api:s}){let i=r(),o=function(){let[e,t]=(0,a.useState)(!1);return(0,a.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:c,arm:d,disarm:u}=function(){let[e,t]=(0,a.useState)(null);return(0,a.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,a.useState)("light"),[s,i]=(0,a.useState)(!1);return(0,a.useEffect)(()=>{if(void 0===t)return;l(function(e){switch(e.groundingKind){case"connected-context":return ey(e.contextPack.usage.filesRead,e.contextPack.usage.excerptBytes)?"heavy":"light";case"hybrid":return ey(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)),i(!0);let e=setTimeout(()=>i(!1),2500);return()=>clearTimeout(e)},[t]),{flowing:e||s,intensity:n}}(i?.sending===!0,i?.latestGrounded),p=function(e,t){let n=new Map(e.map(e=>[e.id,e])),a=[];for(let e of t){let t=n.get(e.a),l=n.get(e.b);if(void 0===t||void 0===l)continue;let s=function(e,t){let n,a,l,s,i={x:e.x+e.w/2,y:e.y+e.h/2},r={x:t.x+t.w/2,y:t.y+t.h/2},o=r.x-i.x,c=r.y-i.y;if(Math.abs(o)>=Math.abs(c)){n=o>=0?{x:e.x+e.w,y:i.y}:{x:e.x,y:i.y};let c=Math.max(40,Math.abs((a=o>=0?{x:t.x,y:r.y}:{x:t.x+t.w,y:r.y}).x-n.x)/2),d=o>=0?1:-1;l={x:n.x+d*c,y:n.y},s={x:a.x-d*c,y:a.y}}else{n=c>=0?{x:i.x,y:e.y+e.h}:{x:i.x,y:e.y};let o=Math.max(40,Math.abs((a=c>=0?{x:r.x,y:t.y}:{x:r.x,y:t.y+t.h}).y-n.y)/2),d=c>=0?1:-1;l={x:n.x,y:n.y+d*o},s={x:a.x,y:a.y-d*o}}let d={x:(n.x+3*l.x+3*s.x+a.x)/8,y:(n.y+3*l.y+3*s.y+a.y)/8};return{d:`M${String(n.x)},${String(n.y)} C${String(l.x)},${String(l.y)} ${String(s.x)},${String(s.y)} ${String(a.x)},${String(a.y)}`,mid:d}}(t,l);a.push({c:e,d:s.d,mid:s.mid,label:T(t,l),dataChannel:function(e,t){let n=[e.type,t.type].includes("chat"),a="chat"===e.type?ex.has(t.type):ex.has(e.type);return n&&a}(t,l)})}return a}(e,t),f=null!==l?function(e,t){let n=t.find(t=>t.id===e.from);if(void 0===n)return null;let a={x:n.x+n.w/2,y:n.y+n.h/2},l=e.x-a.x,s=e.y-a.y,i=Math.abs(l)>=Math.abs(s),r=i?{x:l>=0?n.x+n.w:n.x,y:a.y}:{x:a.x,y:s>=0?n.y+n.h:n.y},o=Math.max(40,Math.abs(i?l:s)/2),c=i?{x:r.x+(l>=0?o:-o),y:r.y}:{x:r.x,y:r.y+(s>=0?o:-o)},d=e.x,u=e.y;return{d:`M${String(r.x)},${String(r.y)} C${String(c.x)},${String(c.y)} ${String(d)},${String(u)} ${String(d)},${String(u)}`,ex:d,ey:u}}(l,e):null;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"conn-layer",children:(0,n.jsxs)("svg",{className:"conn-svg",viewBox:"-10000 -10000 20000 20000",preserveAspectRatio:"xMidYMid meet",children:[p.map(e=>{let t=m&&e.dataChannel,a=`conn-path-${e.c.id}`;return(0,n.jsxs)("g",{children:[(0,n.jsx)("path",{id:a,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,n.jsx)(ew,{pathId:a,intensity:h}):null]},e.c.id)}),null!==f?(0,n.jsx)("path",{className:"conn-path conn-temp",d:f.d}):null,null!==f?(0,n.jsx)("circle",{className:"conn-dot",cx:f.ex,cy:f.ey,r:"5"}):null]})}),(0,n.jsx)("div",{className:"conn-badge-layer",children:p.map(e=>{let t,a=m&&e.dataChannel,l=c===e.c.id,i=(t=[`Connection: ${e.label}`],void 0!==e.c.boundRoot&&t.push(`Root: ${e.c.boundRoot}`),void 0!==e.c.boundScopeKind&&t.push(`Scope: ${e.c.boundScopeKind}`),void 0!==e.c.boundRelativePath&&e.c.boundRelativePath.length>0&&t.push(`Path: ${e.c.boundRelativePath}`),void 0!==e.c.boundConnectorKind&&void 0!==e.c.boundConnectorId&&t.push(`Knowledge: ${e.c.boundConnectorKind} ${e.c.boundConnectorId}`),t.join("\n"));return(0,n.jsxs)("button",{type:"button",className:"conn-badge","data-active":a?"true":void 0,"data-intensity":a?h:void 0,"data-armed":l?"true":void 0,style:{left:e.mid.x,top:e.mid.y},onClick:()=>{l?(u(),s.removeConn(e.c.id)):d(e.c.id)},onBlur:()=>{l&&u()},title:l?`Click again to remove: ${e.label}
101
+
102
+ ${i}`:`${i}
103
+
104
+ Click once to arm removal.`,"aria-label":l?`Confirm removal of connection: ${e.label}. Activate again to remove.`:a?`${e.label} — ${h} data exchange in progress. Activate to remove connection.`:`Remove connection: ${e.label}`,children:[(0,n.jsx)(j.Icons.git,{size:11})," ",(0,n.jsx)("span",{children:l?"Remove?":e.label}),a&&!l?(0,n.jsx)("span",{className:"conn-flow-tag","aria-hidden":"true",children:"heavy"===h?"⇶":"→"}):null]},e.c.id)})})]})}let ek=["n","s","e","w","ne","nw","se","sw"],eN=["t","r","b","l"];function eS({icon:e,label:t}){let a=j.Icons[e];return(0,n.jsxs)("div",{className:"too-small",children:[(0,n.jsx)("div",{className:"ts-ico",children:(0,n.jsx)(a,{size:28})}),(0,n.jsxs)("div",{className:"ts-title",children:["Too small to show ",t]}),(0,n.jsx)("div",{className:"ts-sub",children:"Enlarge the window or zoom its content out"}),(0,n.jsx)("div",{className:"ts-arrow","aria-hidden":"true",children:(0,n.jsx)("svg",{width:"22",height:"22",viewBox:"0 0 22 22",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M8 8l8 8M16 11v5h-5"})})})]})}function eC({win:e,top:t,connState:l,view:s,api:i,wsRef:r}){var o;let c=E[e.type],d=void 0!==(o=e.type)&&((R[o]??[]).length>0||Object.values(R).some(e=>e.includes(o))),u=j.Icons[c.icon],[m,h]=(0,a.useState)(!1),p=(0,a.useRef)(null),f=(0,a.useRef)(null),g=e.zoom??1,v="chat"===e.type||"agents"===e.type||"quality"===e.type?i.linkedFilesRoot(e.id):null,b="agents"===e.type||"quality"===e.type?i.linkedFilesContext(e.id)?.activeFilePath:void 0,x="quality"===e.type?i.linkedAllFilesRoots(e.id):null!==v?[v]:[],y="quality"===e.type?i.linkedConnectorCapsuleIds(e.id):[],w="quality"===e.type?i.linkedConnectorCapsuleSetIds(e.id):[],k="quality"===e.type?i.linkedFigmaSnapshotRunIds(e.id):[],N="quality"===e.type?i.linkedFigmaSnapshotSources?.(e.id):void 0,S="quality"===e.type?i.linkedImageSources?.(e.id):void 0,C=e.w/g,I=e.h/g,$=(0,a.useCallback)(t=>{i.update(e.id,{cfg:{...e.cfg,...t}})},[i,e.cfg,e.id]),T=(0,a.useCallback)((e,t)=>i.add(e,t),[i]),{mode:A,node:L}=function(e,t,a,l,s,i,r,o,c,d,u,m,h,p,f){let g=E[t];if("chat"===t){let t=a<430||l<430;return{mode:t?"mini":"full",node:g.render(s,{windowId:e,mini:t,linkedRoot:i,linkedFilePath:r,linkedRoots:o,linkedCapsuleIds:c,linkedCapsuleSetIds:d,linkedFigmaSnapshotRunIds:u,linkedFigmaSnapshotSources:m,linkedImageSources:h,updateCfg:p,openWindow:f})}}return a<g.tiny.w||l<g.tiny.h?{mode:"tiny",node:(0,n.jsx)(eS,{icon:g.icon,label:g.title})}:{mode:"full",node:g.render(s,{windowId:e,linkedRoot:i,linkedFilePath:r,linkedRoots:o,linkedCapsuleIds:c,linkedCapsuleSetIds:d,linkedFigmaSnapshotRunIds:u,linkedFigmaSnapshotSources:m,linkedImageSources:h,updateCfg:p,openWindow:f})}}(e.id,e.type,C,I,e.cfg,v,b,x,y,w,k,N,S,$,T),q=(0,a.useCallback)(t=>i.update(e.id,{zoom:Math.max(.5,Math.min(2,Math.round(10*t)/10))}),[i,e.id]);(0,a.useEffect)(()=>{var t,n;if(t=e.type,n=e.cfg,"figma"!==t||"string"!=typeof n.selectedScreenIdsJson||!(n.selectedScreenIdsJson.length>0)||e.max||"full"!==A)return;let a=p.current;if(null===a)return;let l=null,s=()=>{l=null;let t=a.scrollHeight-a.clientHeight;if(t<=8)return;let n=Math.ceil(e.h+t);n<=e.h+8||i.update(e.id,{h:n})},r=()=>{null===l&&(l="function"==typeof window.requestAnimationFrame?window.requestAnimationFrame(s):window.setTimeout(s,0))};r();let o="u">typeof ResizeObserver?new ResizeObserver(r):null;o?.observe(a);let c=a.firstElementChild;return null!==c&&o?.observe(c),()=>{null!==l&&("function"==typeof window.cancelAnimationFrame?window.cancelAnimationFrame(l):window.clearTimeout(l)),o?.disconnect()}},[i,A,e.cfg,e.h,e.id,e.max,e.type]),(0,a.useEffect)(()=>()=>{f.current?.(),f.current=null},[]);let P=(0,a.useCallback)(t=>{t instanceof Element&&null!==t.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(()=>i.focus(e.id),0):i.focus(e.id)},[i,e.id]),D=(0,a.useCallback)(t=>{var n,a,o;let c,d,u,m,p;if(!_(t)||"valid"===l)return;t.preventDefault(),P(t.target);let f=r.current;if(null===f)return;let g=(n=f.getBoundingClientRect(),{z:c=s.zoom,vpx0:-s.x/c,vpy0:-s.y/c,vpw:n.width/c,vph:n.height/c,toWX:e=>(e-n.left-s.x)/c,toWY:e=>(e-n.top-s.y)/c}),v=e.max,b=v?e.prev?.w??480:e.w,x=v?e.prev?.h??360:e.h,y=v?b/2:g.toWX(t.clientX)-e.x,w=v?18:g.toWY(t.clientY)-e.y;v&&i.update(e.id,{max:!1,w:b,h:x}),h(!0),a={winId:e.id,offX:y,offY:w,W:b},o=()=>h(!1),d=30/g.z,u=e=>{let t,n,l,s,r=g.toWX(e.clientX),o=g.toWY(e.clientY),c=r-a.offX,u=o-a.offY;c=Math.max(g.vpx0-(a.W-120),Math.min(g.vpx0+g.vpw-120,c)),u=Math.max(g.vpy0,Math.min(g.vpy0+g.vph-38,u)),i.setSnap((t=r-g.vpx0<d,n=g.vpx0+g.vpw-r<d,l=o-g.vpy0<d,s=g.vpy0+g.vph-o<d,l&&t?"tl":l&&n?"tr":s&&t?"bl":s&&n?"br":t?"left":n?"right":l?"maxi":null)),i.update(a.winId,{x:c,y:u})},m=()=>{window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",m),window.removeEventListener("pointercancel",m),i.commitSnap(a.winId),p(),o?.()},p=G(),window.addEventListener("pointermove",u),window.addEventListener("pointerup",m),window.addEventListener("pointercancel",m)},[i,e.id,e.x,e.y,e.w,e.h,e.max,e.prev,s,r,l,P]),F=(0,a.useCallback)(t=>n=>{if(!B(n))return;n.preventDefault(),n.stopPropagation(),f.current?.(),f.current=null,i.focus(e.id);let a={x:e.x,y:e.y,w:e.w,h:e.h},l=a,r=n.clientX,o=n.clientY,c=s.zoom,d=document.body.style.cursor,u=!0,m=()=>{u&&(u=!1,window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",h),window.removeEventListener("blur",h),document.body.style.cursor=d,f.current===m&&(f.current=null))},h=()=>{m()},p=n=>{var s;if(!u)return;if(0===n.buttons)return void m();let d=function(e,t,n,a,l){let{x:s,y:i,w:r,h:o}=e;t.includes("e")&&(r=e.w+n),t.includes("s")&&(o=e.h+a),t.includes("w")&&(r=e.w-n,s=e.x+n),t.includes("n")&&(o=e.h-a,i=e.y+a);let c=E[l].min,d=c.w>0?c.w:240,u=c.h>0?c.h:150;return r<d&&(t.includes("w")&&(s-=d-r),r=d),o<u&&(t.includes("n")&&(i-=u-o),o=u),{x:s,y:i,w:r,h:o}}(a,t,(n.clientX-r)/c,(n.clientY-o)/c,e.type);((s=l).x!==d.x||s.y!==d.y||s.w!==d.w||s.h!==d.h)&&(l=d,i.update(e.id,{...d,max:!1}))};document.body.style.cursor="n"===t||"s"===t?"ns-resize":"e"===t||"w"===t?"ew-resize":"ne"===t||"sw"===t?"nesw-resize":"nwse-resize",window.addEventListener("pointermove",p),window.addEventListener("pointerup",h),window.addEventListener("pointercancel",h),window.addEventListener("blur",h),f.current=m},[i,e.id,e.x,e.y,e.w,e.h,e.type,s.zoom]),z=(0,a.useCallback)((t,n)=>{let a=t.getBoundingClientRect();i.startConnect(e.id,{clientX:"clientX"in n?n.clientX:a.left+a.width/2,clientY:"clientY"in n?n.clientY:a.top+a.height/2,preventDefault:()=>n.preventDefault(),stopPropagation:()=>n.stopPropagation()})},[i,e.id]),O=(0,a.useCallback)(e=>{B(e)&&(e.preventDefault(),e.stopPropagation(),z(e.currentTarget,e))},[z]),K=(0,a.useCallback)(t=>{if("Enter"===t.key||" "===t.key||"Spacebar"===t.key){if("valid"===l)return void i.confirmConnect(e.id,{preventDefault:()=>t.preventDefault(),stopPropagation:()=>t.stopPropagation()});t.preventDefault(),t.stopPropagation(),z(t.currentTarget,t)}},[z,l,i,e.id]),U=(0,a.useCallback)(()=>{i.close(e.id),requestAnimationFrame(()=>{let e=document.querySelector('.window[data-top="true"]')??document.querySelector(".ws-fab");e?.focus({preventScroll:!0})})},[i,e.id]),W=(0,a.useCallback)(()=>{i.minimize(e.id),requestAnimationFrame(()=>{let e=document.querySelector('.window[data-top="true"]')??document.querySelector(".ws-fab");e?.focus({preventScroll:!0})})},[i,e.id]),H="full"===A?M(e.type,e.cfg):null,Y="tiny"===A?{}:{zoom:g},J={left:e.x,top:e.y,width:e.w,height:e.h,zIndex:e.z};return(0,n.jsxs)("section",{className:"window","aria-label":null!==H?`${c.title} — ${H}`:c.title,"aria-roledescription":"window","data-top":t?"true":"false","data-max":e.max?"true":"false","data-conn":l??void 0,"data-dragging":m?"true":void 0,"data-window-id":e.id,style:J,tabIndex:-1,onPointerDown:t=>{"valid"===l&&i.confirmConnect(e.id,t),P(t.target)},onFocusCapture:()=>{t||window.setTimeout(()=>i.focus(e.id),0)},children:[(0,n.jsxs)("header",{className:"win-head",onPointerDown:D,onDoubleClick:t=>{(function(e){let t=e.target;if(t instanceof Element&&null!==t.closest("button,[role='button']"))return!1;let n=e.currentTarget.getBoundingClientRect(),a=Math.min(210,n.width/2);return e.clientX<n.right-a})(t)&&i.maximize(e.id)},children:[(0,n.jsx)("span",{className:"win-ico",style:{color:!0===c.accent?"var(--accent)":"var(--fg-muted)"},children:(0,n.jsx)(u,{size:14})}),(0,n.jsx)("span",{className:"win-title",children:c.title}),null!==H?(0,n.jsx)("span",{className:"win-sub mono",title:H,children:H}):null,(0,n.jsx)("span",{className:"spacer"}),(0,n.jsxs)("div",{className:"win-zoom",children:[(0,n.jsx)("button",{type:"button",className:"win-zbtn",title:"Zoom content out","aria-label":`Zoom ${c.title} content out`,disabled:g<=.5,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>q(g-.1),children:(0,n.jsx)(j.Icons.zoomOut,{size:13})}),(0,n.jsxs)("button",{type:"button",className:"win-zpct",title:"Reset content zoom to 100%","aria-label":`${String(Math.round(100*g))}% — reset ${c.title} content zoom`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>i.update(e.id,{zoom:1}),children:[Math.round(100*g),"%"]}),(0,n.jsx)("button",{type:"button",className:"win-zbtn",title:"Zoom content in","aria-label":`Zoom ${c.title} content in`,disabled:g>=2,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>q(g+.1),children:(0,n.jsx)(j.Icons.zoomIn,{size:13})})]}),(0,n.jsxs)("div",{className:"win-traffic",role:"group","aria-label":`${c.title} window controls`,children:[(0,n.jsx)("button",{type:"button",className:"win-traffic-btn win-traffic-minimize",title:"Minimize","aria-label":`Minimize ${c.title} window`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:W,children:(0,n.jsx)(j.Icons.minimize,{size:17})}),(0,n.jsx)("button",{type:"button",className:"win-traffic-btn win-traffic-maximize",title:e.max?"Restore":"Full screen","aria-label":e.max?`Restore ${c.title} window`:`Full screen ${c.title} window`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>i.maximize(e.id),children:e.max?(0,n.jsx)(j.Icons.restore,{size:17}):(0,n.jsx)(j.Icons.maximize,{size:17})}),(0,n.jsx)("button",{type:"button",className:"win-traffic-btn win-traffic-close",title:"Close","aria-label":`Close ${c.title} window`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:U,children:(0,n.jsx)(j.Icons.close,{size:17})})]})]}),(0,n.jsx)("div",{ref:p,className:"win-body","data-mode":A,style:Y,children:L}),e.max?null:ek.map(e=>(0,n.jsx)("div",{className:`wz wz-${e}`,onPointerDown:F(e)},e)),!e.max&&d?eN.map(e=>(0,n.jsx)("button",{type:"button",className:`win-port wp-${e}`,title:"Click to connect to another window","aria-label":`Connect ${c.title} from ${"t"===e?"top":"r"===e?"right":"b"===e?"bottom":"left"} edge`,onPointerDown:O,onKeyDown:K},`p${e}`)):null]})}let eI=[/\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-----/],eE=/\b(?:\d[ -]?){13,19}\b/g;e.i(47167);let eR={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"},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"},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"}},e$=["apikey","accesskey","clientsecret","credential","password","privatekey","secret","token"],eT=["api_key=","apikey=","client_secret=","clientsecret=","credential=","authorization:","password=","secret=","token="],eA=[".env",".env.local",".env.development",".env.test",".env.production"],eM={chat:["chatId"],files:["activeFilePath","activeDirectoryPath","resolvedRoot"],figma:["snapshotRunId","selectedScreenIdsJson","selectedScreenName"],figmaJson:["snapshotRunId","screenId","selectedScreenIdsJson","selectedScreenName"],figmaImage:["snapshotRunId","screenId","selectedScreenName","imageSrc"]};function eL(e){return"number"==typeof e&&Number.isFinite(e)}function eq(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function eP(e){let t=e.trim();if(0===t.length)return!1;let n=t.toLowerCase();return function(e){for(let t of eI)if(t.test(e))return!0;for(let t of e.matchAll(eE)){let e=t[0].replaceAll(/[ -]/g,"");if(e.length>=13&&e.length<=19&&function(e){let t=0,n=!1;for(let a=e.length-1;a>=0;a-=1){let l=Number(e[a]);n&&(l*=2)>9&&(l-=9),t+=l,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 a=0;for(let l=n+t.length;l<e.length&&0!==(e[l]??"").trim().length;l+=1)a+=1;return a>=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)||eT.some(e=>n.includes(e))||function(e){let t=e.toLowerCase().replaceAll("\\","/").split("/");for(let e=0;e<t.length;e+=1){let n=t[e]??"",a=t[e+1]??"";if(eA.includes(n)||".npmrc"===n||"credentials.json"===n||".aws"===n&&"credentials"===a||".ssh"===n&&a.startsWith("id_"))return!0}return!1}(t)}function eD(e){if(0===e.length||e.length>256||e.startsWith(".")||e.trim()!==e||eP(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 eF(e){if(0===e.length||e.length>256||e.trim()!==e||eP(e))return!1;for(let t of e){let e=t.charCodeAt(0),n=e>=48&&e<=57,a=e>=65&&e<=90,l=e>=97&&e<=122,s=46===e||58===e||95===e||45===e;if(!n&&!a&&!l&&!s)return!1}return!0}function ez(e){let t=[];for(let n of e){let e=function(e){var t;if(!eq(e)||!("string"==typeof(t=e.type)&&t in E))return null;let n=e.type;if("transient"===eR[n].persistence||"string"!=typeof e.id||!eL(e.x)||!eL(e.y)||!eL(e.w)||!eL(e.h)||!eL(e.z)||"boolean"!=typeof e.max)return null;let a={id:e.id,type:n,x:e.x,y:e.y,w:e.w,h:e.h,z:e.z,cfg:function(e,t){if(!eq(t)||"durable.config"===eR[e].persistence)return{};let n=new Set([...(E[e].config??[]).map(e=>e.key),...eM[e]??[]]),a={};for(let[l,s]of Object.entries(t)){if(!n.has(l))continue;let t=function(e,t,n){let a;if("figma"===e||"figmaJson"===e||"figmaImage"===e)return function(e,t){if("string"==typeof t){if("snapshotRunId"===e)return eD(t)?t:void 0;if("screenId"===e)return eF(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(!eF(e))return;n.push(e)}return JSON.stringify(n)}if("selectedScreenName"===e){if(t.length>256||eP(t))return;return t}}}(t,n);if("string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||(a=function(e){let t="";for(let n of e.toLowerCase())(n>="a"&&n<="z"||n>="0"&&n<="9")&&(t+=n);return t}(t),e$.some(e=>a.includes(e))))return;if("string"!=typeof n)return n;let l=eR[e].persistence;return"evidence-reference"===l?eD(n)?n:void 0:eP(n)?"durable.ui"===l?"[REDACTED]":void 0:n}(e,l,s);void 0!==t&&(a[l]=t)}return a}(n,e.cfg),max:e.max},l=function(e){if(eq(e)&&eL(e.x)&&eL(e.y)&&eL(e.w)&&eL(e.h))return{x:e.x,y:e.y,w:e.w,h:e.h}}(e.prev);return{...a,...!0===e.minimized?{minimized:!0}:{},...void 0!==l?{prev:l}:{},...eL(e.zoom)?{zoom:e.zoom}:{}}}(n);null!==e&&t.push(e)}return t}function eO(e,t){let n=new Set(t.map(e=>e.id)),a=[];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,l="workspace-root"===t.boundScopeKind||"directory"===t.boundScopeKind||"files"===t.boundScopeKind,s="string"==typeof t.boundRelativePath&&t.boundRelativePath.length>0,i="string"==typeof t.boundChatWindowId&&t.boundChatWindowId.length>0&&n.has(t.boundChatWindowId),r=("capsule"===t.boundConnectorKind||"capsule-set"===t.boundConnectorKind)&&"string"==typeof t.boundConnectorId&&t.boundConnectorId.length>0;a.push({id:t.id,a:t.a,b:t.b,...i?{boundChatWindowId:t.boundChatWindowId}:{},...e?{boundRoot:t.boundRoot}:{},...l?{boundScopeKind:t.boundScopeKind}:{},...s?{boundRelativePath:t.boundRelativePath}:{},...r?{boundConnectorKind:t.boundConnectorKind,boundConnectorId:t.boundConnectorId}:{}})}return a}function eK(e,t,n,a,l){return{x:e.x+Math.max(16,Math.min(l+26*a,e.w-t-16)),y:e.y+Math.max(16,Math.min(l+26*a,e.h-n-16))}}function eB(e){let{prev:t,...n}=e;return n}function e_(e,t,n){return e.some(e=>e.a===t&&e.b===n||e.a===n&&e.b===t)}function eU(e,t){return e?.type==="chat"?e.id:t?.type==="chat"?t.id:null}function eW(e){return e.length>0&&(e.startsWith("/")||/^[A-Za-z]:[/\\]/u.test(e))}function eH(e){return/^[A-Za-z]:[/\\]?$/u.test(e)?e.replace(/\\/gu,"/"):e.replace(/\\/gu,"/").replace(/\/+$/u,"")}function eY(e){if("files"!==e.type)return null;let t=e.cfg.resolvedRoot,n=e.cfg.root,a="string"==typeof t&&t.length>0?t:"string"==typeof n&&n.length>0?n:null;return null!==a&&eW(a)?a:null}function eJ(e){return e.replace(/\\/gu,"/").replace(/^\/+/u,"").replace(/\/+$/u,"")}function eG(e,t){return void 0!==e.root&&void 0!==t.root&&eH(e.root)===eH(t.root)&&e.kind===t.kind&&e.relativePaths.length===t.relativePaths.length&&e.relativePaths.every((e,n)=>eJ(e)===eJ(t.relativePaths[n]??""))}function eV(e,t,n){let a="files"===e.type?e:"files"===t.type?t:null,l="chat"===e.type?e:"chat"===t.type?t:null;if(null===a||null===l)return null;let s=eY(a);if(null===s)return null;let i=a.cfg.activeFilePath;if("string"==typeof i&&i.length>0)return{kind:"files",relativePaths:[eJ(i)],root:eH(s),connectedAtMs:n};let r=a.cfg.activeDirectoryPath;return"string"==typeof r&&r.length>0?{kind:"directory",relativePaths:[eJ(r)],root:eH(s),connectedAtMs:n}:{kind:"workspace-root",relativePaths:[],root:eH(s),connectedAtMs:n}}function eX(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:[eJ(e.boundRelativePath)],root:eH(e.boundRoot),connectedAtMs:t}:"files"===e.boundScopeKind?"string"!=typeof e.boundRelativePath||0===e.boundRelativePath.length?null:{kind:"files",relativePaths:[eJ(e.boundRelativePath)],root:eH(e.boundRoot),connectedAtMs:t}:{kind:"workspace-root",relativePaths:[],root:eH(e.boundRoot),connectedAtMs:t}}function eQ(e){return Math.max(e.maxConnectedSources,e.maxLocalKnowledgeSources)}function eZ(e,t){return e.filter(e=>!eG(e,t))}function e0(e){return e.connectedScopes??(void 0!==e.connectedScope?[e.connectedScope]:[])}function e1(e){return e.localKnowledgeScopes??(void 0!==e.localKnowledgeScope?[e.localKnowledgeScope]:[])}function e2(e){return"capsule"===e.kind?`capsule:${e.capsuleId}`:`set:${e.capsuleSetId}`}function e4(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 e3(e,t){let n="connector"===e.type?e:"connector"===t.type?t:null,a="chat"===e.type?e:"chat"===t.type?t:null;if(null===n||null===a)return null;let l=n.cfg.selectedKind,s=n.cfg.selectedId;if("string"!=typeof l||"string"!=typeof s)return null;let i=s.trim();return 0===i.length?null:"capsule"===l?{kind:"capsule",capsuleId:i,connectedAtMs:Date.now()}:"capsule-set"===l?{kind:"capsule-set",capsuleSetId:i,connectedAtMs:Date.now()}:null}let e6="keiko.workspace.v4",e5="keiko.conns.v1",e8="keiko.view";function e7(){try{let e=window.localStorage.getItem(e8);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 e9(e){return Math.max(.3,Math.min(2.5,e))}function te(e){return Math.max(.5,Math.min(2,Math.round(10*e)/10))}function tt(e){let t=null;for(let n=0;n<e.length;n++){let a=e[n];if(!0!==a.minimized){if(null===t){t=a;continue}a.z>t.z&&(t=a)}}return t}function tn(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function ta(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 tl={Equal:"=",NumpadAdd:"+",Minus:"-",NumpadSubtract:"-",Digit0:"0",Numpad0:"0"},ts="application/x-keiko-local-knowledge-connector",ti="keiko:local-knowledge-connector-drop";function tr(e){if(!Array.from(e.types).includes(ts))return null;try{let t=JSON.parse(e.getData(ts));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():"",a="string"==typeof t.lifecycleState?t.lifecycleState.trim():"";return{kind:"capsule",id:t.id.trim(),...n.length>0?{label:n}:{},...a.length>0?{lifecycleState:a}:{}}}catch{return null}}let to="application/x-keiko-figma-view",tc="keiko:figma-view-drop";function td(e){return"string"==typeof e&&e.trim().length>0?e.trim():null}function tu(e){if(!Array.from(e.types).includes(to))return null;try{let t=JSON.parse(e.getData(to));if("object"!=typeof t||null===t)return null;let n=td(t.snapshotRunId),a=td(t.screenId),l=td(t.name);if(null===n||null===a||null===l)return null;return{snapshotRunId:n,screenId:a,name:l}}catch{return null}}let tm="application/x-keiko-figma-json",th="keiko:figma-json-drop";function tp(e){return"string"==typeof e&&e.trim().length>0?e.trim():null}function tf(e){if(!Array.from(e.types).includes(tm))return null;try{let t=JSON.parse(e.getData(tm));if("object"!=typeof t||null===t)return null;let n=tp(t.snapshotRunId),a=tp(t.screenId),l=tp(t.name);if(null===n||null===a||null===l)return null;let s=tp(t.sourceWindowId);return{snapshotRunId:n,screenId:a,name:l,...null!==s?{sourceWindowId:s}:{}}}catch{return null}}let tg="application/x-keiko-figma-image",tv="keiko:figma-image-drop";function tb(e){return"string"==typeof e&&e.trim().length>0?e.trim():null}function tx(e){if(!Array.from(e.types).includes(tg))return null;try{let t=JSON.parse(e.getData(tg));if("object"!=typeof t||null===t)return null;let n=tb(t.snapshotRunId),a=tb(t.screenId),l=tb(t.name),s=tb(t.imageSrc);if(null===n||null===a||null===l||null===s||!/^\/api\/figma\/snapshots\/[^/?#]+\/screens\/\d+\/image$/u.test(s))return null;let i=tb(t.sourceWindowId);return{snapshotRunId:n,screenId:a,name:l,imageSrc:s,...null!==i?{sourceWindowId:i}:{}}}catch{return null}}let ty={w:260,h:220},tw={w:360,h:360},tj={w:520,h:540},tk={w:560,h:420};function tN({clientX:e,clientY:t,rect:n,view:a,size:l=ty}){return{x:Math.round((e-n.left-a.x)/a.zoom-l.w/2),y:Math.round((t-n.top-a.y)/a.zoom-28)}}function tS(e,t){let n=e+t;return e<1&&n>1||e>1&&n<1?1:n}function tC(e,t,n){t.preventDefault();let a=t.currentTarget;a.setPointerCapture?.(t.pointerId);let l=t.clientX,s=t.clientY,i=G();n(!0);let r=t=>{e(t.clientX-l,t.clientY-s),l=t.clientX,s=t.clientY},o=()=>{window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",o),window.removeEventListener("pointercancel",o),n(!1),a.hasPointerCapture?.(t.pointerId)===!0&&a.releasePointerCapture?.(t.pointerId),i()};window.addEventListener("pointermove",r),window.addEventListener("pointerup",o),window.addEventListener("pointercancel",o)}function tI({wins:e,connecting:t,conns:l}){let[s,i]=(0,a.useState)(""),r=(0,a.useRef)(null),o=(0,a.useRef)(l.length);return(0,a.useEffect)(()=>{let n=r.current;r.current=t;let a=o.current;if(o.current=l.length,null===n&&null!==t){let n=e?.find(e=>e.id===t.from),a=void 0!==n?E[n.type].title:"window";i(`Connecting from ${a} — select a highlighted window, press Escape to cancel`);return}if(null!==n&&null===t)if(l.length>a){let t=l[l.length-1],n=void 0!==t?e?.find(e=>e.id===t.a):void 0,a=void 0!==t?e?.find(e=>e.id===t.b):void 0;i(void 0!==n&&void 0!==a?`Connected: ${T(n,a)}`:"Connected")}else i("Connection cancelled")},[t,l,e]),(0,n.jsx)("div",{className:"sr-only","aria-live":"polite",children:s})}function tE(e){let t=E[e.type].title,n=M(e.type,e.cfg);return null!==n?`${t}: ${n}`:t}function tR({wins:e,conns:t,top:l,api:s,openPalette:i}){let r=(0,a.useMemo)(()=>null===e?[]:t.map(t=>{let n,a;return{conn:t,label:(n=e.find(e=>e.id===t.a),a=e.find(e=>e.id===t.b),void 0===n||void 0===a?null:{source:n,target:a,text:`${tE(n)} ${T(n,a)} ${tE(a)}`})}}).filter(e=>null!==e.label),[t,e]),o=null!==e&&e.length>0;return(0,n.jsx)("section",{className:"ws-outline","aria-labelledby":"ws-outline-title",children:(0,n.jsxs)("div",{className:"ws-outline-inner",children:[(0,n.jsx)("h2",{id:"ws-outline-title",children:"Workspace outline"}),(0,n.jsx)("p",{className:"ws-outline-summary",children:null===e?"Workspace is loading.":`${String(e.length)} workspace window${1===e.length?"":"s"}, ${String(r.length)} relationship${1===r.length?"":"s"}.`}),(0,n.jsxs)("div",{className:"ws-outline-actions",children:[(0,n.jsx)("button",{type:"button",onClick:i,children:"New window"}),(0,n.jsx)("button",{type:"button",onClick:s.tileAll,disabled:!o,children:"Tile all windows"}),(0,n.jsx)("button",{type:"button",onClick:s.cascade,disabled:!o,children:"Cascade windows"})]}),(0,n.jsxs)("section",{"aria-labelledby":"ws-outline-windows-title",children:[(0,n.jsx)("h3",{id:"ws-outline-windows-title",children:"Windows"}),null===e?(0,n.jsx)("p",{children:"Loading windows."}):0===e.length?(0,n.jsx)("p",{children:"No workspace windows are open."}):(0,n.jsx)("ul",{className:"ws-outline-list",children:e.map(e=>{let t,a,i=tE(e),r=E[e.type];return(0,n.jsx)("li",{children:(0,n.jsxs)("article",{"aria-labelledby":`ws-outline-window-${e.id}`,children:[(0,n.jsx)("h4",{id:`ws-outline-window-${e.id}`,children:i}),(0,n.jsxs)("p",{children:["Type: ",r.title,". Status: ",((t=[]).push(null!==l&&l.id===e.id?"active":"background"),t.push(!0===e.minimized?"minimized":"open"),e.max&&t.push("maximized"),1!==(a=e.zoom??1)&&t.push(`${String(Math.round(100*a))}% content zoom`),t.join(", ")),"."]}),(0,n.jsx)("p",{children:r.desc}),(0,n.jsxs)("div",{className:"ws-outline-actions","aria-label":`${i} actions`,children:[(0,n.jsx)("button",{type:"button",onClick:()=>s.restore(e.id),children:!0===e.minimized?`Restore ${i}`:`Open ${i}`}),(0,n.jsxs)("button",{type:"button",onClick:()=>s.minimize(e.id),children:["Minimize ",i]}),(0,n.jsx)("button",{type:"button",onClick:()=>s.maximize(e.id),children:e.max?`Restore size of ${i}`:`Full screen ${i}`}),(0,n.jsxs)("button",{type:"button",onClick:()=>s.close(e.id),children:["Close ",i]})]})]})},e.id)})})]}),(0,n.jsxs)("section",{"aria-labelledby":"ws-outline-relationships-title",children:[(0,n.jsx)("h3",{id:"ws-outline-relationships-title",children:"Relationships"}),0===r.length?(0,n.jsx)("p",{children:"No relationships are connected."}):(0,n.jsx)("ul",{className:"ws-outline-list",children:r.map(({conn:e,label:t})=>(0,n.jsxs)("li",{children:[(0,n.jsxs)("p",{children:[t.text,"."]}),(0,n.jsxs)("button",{type:"button",onClick:()=>s.removeConn(e.id),children:["Remove relationship between ",tE(t.source)," and"," ",tE(t.target)]})]},e.id))})]})]})})}function t$({ws:e,wsRef:t,openPalette:l,palette:s}){let{wins:i,view:r,snapPrev:o,conns:c,connecting:d,api:u}=e,[m,h]=(0,a.useState)(!1),[p,f]=(0,a.useState)(!1),g=(0,a.useRef)(!1),v=(0,a.useMemo)(()=>null===i?null:i.filter(e=>!0!==e.minimized),[i]),b=function(e){if(null===e||0===e.length)return null;let t=null;for(let n=0;n<e.length;n++){let a=e[n];if(!0!==a.minimized){if(null===t){t=a;continue}a.z>t.z&&(t=a)}}return t}(v),x=null!==d&&null!==v?v.find(e=>e.id===d.from)??null:null;(0,a.useEffect)(()=>{let e=e=>{g.current=e,f(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(),g.current||e(!0))},n=t=>{"Space"===t.code&&e(!1)},a=()=>{e(!1)};return window.addEventListener("keydown",t),window.addEventListener("keyup",n),window.addEventListener("blur",a),()=>{window.removeEventListener("keydown",t),window.removeEventListener("keyup",n),window.removeEventListener("blur",a)}},[]);let y=(0,a.useMemo)(()=>({backgroundSize:`${String(22*r.zoom)}px ${String(22*r.zoom)}px`,backgroundPosition:`${String(r.x)}px ${String(r.y)}px`}),[r]),w=(0,a.useMemo)(()=>({transform:`translate(${String(r.x/r.zoom)}px, ${String(r.y/r.zoom)}px)`,transformOrigin:"0 0",zoom:r.zoom}),[r]),k=(0,a.useCallback)((e,t,n,a)=>{let l=u.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!==l&&u.update(l,{...tN({clientX:t,clientY:n,rect:a,view:r}),...ty})},[u,r]),N=(0,a.useCallback)((e,t,n,a)=>{let l=u.add("figma",{snapshotRunId:e.snapshotRunId,selectedScreenIdsJson:JSON.stringify([e.screenId]),selectedScreenName:e.name});null!==l&&u.update(l,{...tN({clientX:t,clientY:n,rect:a,view:r,size:tw}),...tw})},[u,r]),S=(0,a.useCallback)(e=>{if(null===i)return[];let t=new Map(i.map(e=>[e.id,e])),n=[];for(let a of c){let l=a.a===e?a.b:a.b===e?a.a:null;if(null===l)continue;let s=t.get(l);s?.type==="quality"&&n.push({connId:a.id,qualityId:s.id})}return n},[c,i]),C=(0,a.useCallback)((e,t,n,a)=>{let l=u.add("figmaJson",{snapshotRunId:e.snapshotRunId,screenId:e.screenId,selectedScreenIdsJson:JSON.stringify([e.screenId]),selectedScreenName:e.name});if(null===l||(u.update(l,{...tN({clientX:t,clientY:n,rect:a,view:r,size:tj}),...tj}),void 0===e.sourceWindowId))return;let s=S(e.sourceWindowId);if(0!==s.length){for(let e of s)u.removeConn(e.connId);window.setTimeout(()=>{for(let e of s)u.connect(l,e.qualityId)},0)}},[u,S,r]),I=(0,a.useCallback)((e,t,n,a)=>{let l=u.add("figmaImage",{snapshotRunId:e.snapshotRunId,screenId:e.screenId,selectedScreenName:e.name,imageSrc:e.imageSrc});if(null===l||(u.update(l,{...tN({clientX:t,clientY:n,rect:a,view:r,size:tk}),...tk}),void 0===e.sourceWindowId))return;let s=S(e.sourceWindowId);if(0!==s.length){for(let e of s)u.removeConn(e.connId);window.setTimeout(()=>{for(let e of s)u.connect(l,e.qualityId)},0)}},[u,S,r]);(0,a.useEffect)(()=>{let e=e=>{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=t.current?.getBoundingClientRect();if(void 0===n)return;let{clientX:a,clientY:l,payload:s}=e.detail;a<n.left||a>n.right||l<n.top||l>n.bottom||k(s,a,l,n)};return window.addEventListener(ti,e),()=>{window.removeEventListener(ti,e)}},[k,t]),(0,a.useEffect)(()=>{let e=e=>{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=t.current?.getBoundingClientRect();if(void 0===n)return;let{clientX:a,clientY:l,payload:s}=e.detail;a<n.left||a>n.right||l<n.top||l>n.bottom||N(s,a,l,n)};return window.addEventListener(tc,e),()=>{window.removeEventListener(tc,e)}},[N,t]),(0,a.useEffect)(()=>{let e=e=>{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=t.current?.getBoundingClientRect();if(void 0===n)return;let{clientX:a,clientY:l,payload:s}=e.detail;a<n.left||a>n.right||l<n.top||l>n.bottom||C(s,a,l,n)};return window.addEventListener(th,e),()=>{window.removeEventListener(th,e)}},[C,t]),(0,a.useEffect)(()=>{let e=e=>{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=t.current?.getBoundingClientRect();if(void 0===n)return;let{clientX:a,clientY:l,payload:s}=e.detail;a<n.left||a>n.right||l<n.top||l>n.bottom||I(s,a,l,n)};return window.addEventListener(tv,e),()=>{window.removeEventListener(tv,e)}},[I,t]);let E=null!==i&&0===i.length;return(0,n.jsxs)("main",{className:"workspace",ref:t,"aria-label":"Workspace surface",tabIndex:0,"data-connecting":null!==d?"true":void 0,"data-panning":m?"true":void 0,"data-hand-tool":p?"true":void 0,onPointerDownCapture:e=>{var t;if(W())return;if(g.current&&B(e)&&null===d&&!((t=e.target)instanceof Element&&null!==t.closest("input, textarea, select, [contenteditable='true'], [contenteditable='']"))&&!U(e.target)){tC(u.panBy,e,h),e.stopPropagation();return}if(0!==e.button||null===d||null===x||null===v)return;let n=function(e){if(!(e instanceof Element))return;let t=e.closest(".window[data-window-id]");return t?.dataset.windowId}(e.target);if(void 0===n||n===x.id)return;let a=v.find(e=>e.id===n);void 0!==a&&$(x.type,a.type)&&u.confirmConnect(a.id,e)},onPointerDown:e=>{if(!(W()||U(e.target))){if(null!==d){B(e)&&u.cancelConnect();return}_(e)&&tC(u.panBy,e,h)}},onKeyDown:e=>{if(e.target!==e.currentTarget)return;let t=e.shiftKey?192:48;switch(e.key){case"ArrowLeft":u.panBy(t,0);break;case"ArrowRight":u.panBy(-t,0);break;case"ArrowUp":u.panBy(0,t);break;case"ArrowDown":u.panBy(0,-t);break;default:return}e.preventDefault()},onDragOver:e=>{(null!==tr(e.dataTransfer)||null!==tu(e.dataTransfer)||null!==tf(e.dataTransfer)||null!==tx(e.dataTransfer))&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},onDrop:e=>{let t=tr(e.dataTransfer),n=tu(e.dataTransfer),a=tf(e.dataTransfer),l=tx(e.dataTransfer);if(null===t&&null===n&&null===a&&null===l)return;e.preventDefault(),e.stopPropagation();let s=e.currentTarget.getBoundingClientRect();null!==t?k(t,e.clientX,e.clientY,s):null!==n?N(n,e.clientX,e.clientY,s):null!==a?C(a,e.clientX,e.clientY,s):null!==l&&I(l,e.clientX,e.clientY,s)},children:[(0,n.jsx)(eb,{}),(0,n.jsx)("div",{className:"ws-grid",style:y,"aria-hidden":"true"}),(0,n.jsx)(tR,{wins:i,conns:c,top:b,api:u,openPalette:l}),(0,n.jsx)(tI,{wins:v,connecting:d,conns:c}),null!==d?(0,n.jsx)("div",{className:"ws-connect-hint","aria-hidden":"true",children:"Click a highlighted window to connect — Esc to cancel"}):null,E?(0,n.jsx)("div",{className:"ws-empty",children:(0,n.jsx)(K,{onNewWindow:l})}):null,(0,n.jsxs)("div",{className:"ws-scene",style:w,children:[null!==o?(0,n.jsx)("div",{className:"snap-ghost",style:{left:o.x,top:o.y,width:o.w,height:o.h}}):null,null!==v?(0,n.jsx)(ej,{wins:v,conns:c,connecting:d,api:u}):null,null!==v?v.map(e=>(0,n.jsx)(eC,{win:e,top:null!==b&&e.id===b.id,connState:null===x?null:e.id===x.id?"source":$(x.type,e.type)?"valid":"invalid",view:r,api:u,wsRef:t},e.id)):null]}),(0,n.jsxs)("div",{className:"ws-zoom",children:[(0,n.jsx)("button",{type:"button",className:"ws-zoom-btn",onClick:()=>u.zoomTo(tS(r.zoom,-.2)),disabled:r.zoom<=.3,"aria-label":"Zoom out",title:"Zoom out",children:(0,n.jsx)(j.Icons.zoomOut,{size:15})}),(0,n.jsx)("button",{type:"button",className:"ws-zoom-btn",onClick:u.fitView,disabled:null===v||0===v.length,"aria-label":"Fit workspace to windows",title:"Fit workspace to windows",children:(0,n.jsx)(j.Icons.expand,{size:15})}),(0,n.jsxs)("button",{type:"button",className:"ws-zoom-pct mono",onClick:u.resetView,"aria-label":`${String(Math.round(100*r.zoom))}% — reset view`,title:"Reset view to 100%",children:[Math.round(100*r.zoom),"%"]}),(0,n.jsx)("button",{type:"button",className:"ws-zoom-btn",onClick:()=>u.zoomTo(tS(r.zoom,.2)),disabled:r.zoom>=2.5,"aria-label":"Zoom in",title:"Zoom in",children:(0,n.jsx)(j.Icons.zoomIn,{size:15})})]}),(0,n.jsx)("button",{type:"button",className:"ws-fab",onPointerDown:e=>e.stopPropagation(),onClick:l,"aria-label":"New window",title:"New window",children:(0,n.jsx)(j.Icons.add,{size:20})}),s??null]})}function tT({commands:e,onClose:t}){let[l,s]=(0,a.useState)(""),[i,r]=(0,a.useState)(0),o=(0,a.useRef)(null),c=(0,a.useRef)(null),d=(0,a.useRef)(null);(0,a.useEffect)(()=>(c.current=document.activeElement,()=>{c.current?.focus?.()}),[]),(0,a.useEffect)(()=>{o.current?.focus()},[]);let u=(0,a.useMemo)(()=>{let t=l.toLowerCase();return e.filter(e=>`${e.label} ${e.group??""}`.toLowerCase().includes(t))},[e,l]);(0,a.useEffect)(()=>{r(0)},[l]),(0,a.useEffect)(()=>{document.getElementById(`cmdk-row-${String(i)}`)?.scrollIntoView?.({block:"nearest"})},[i,u]);let m=e=>{void 0!==e&&(e.run(),t())};return(0,n.jsx)("div",{className:"cmdk-overlay",onPointerDown:t,children:(0,n.jsxs)("div",{ref:d,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){let t=Array.from(d.current?.querySelectorAll("button:not([disabled]),input:not([disabled]),[tabindex]:not([tabindex='-1'])")??[]);if(t.length>0){let n=t[0],a=t[t.length-1];if(e.shiftKey&&document.activeElement===n){e.preventDefault(),a.focus();return}if(!e.shiftKey&&document.activeElement===a){e.preventDefault(),n.focus();return}}}if("ArrowDown"===e.key){e.preventDefault(),r(e=>Math.min(u.length-1,e+1));return}if("ArrowUp"===e.key){e.preventDefault(),r(e=>Math.max(0,e-1));return}if("Enter"===e.key){e.preventDefault(),m(u[i]);return}"Escape"===e.key&&t()},children:[(0,n.jsx)("h2",{id:"cmdk-title",className:"sr-only",children:"Command palette"}),(0,n.jsx)("p",{id:"cmdk-desc",className:"sr-only",children:"Search commands and press Enter to run the selected action."}),(0,n.jsxs)("div",{className:"cmdk-input",children:[(0,n.jsx)(j.Icons.search,{size:16}),(0,n.jsx)("input",{ref:o,role:"combobox","aria-expanded":"true","aria-controls":"cmdk-list","aria-activedescendant":u.length>0?`cmdk-row-${String(i)}`:void 0,"aria-label":"Command query",placeholder:"Type a command…",value:l,onChange:e=>s(e.target.value)}),(0,n.jsx)("span",{className:"kbd",children:"esc"})]}),(0,n.jsx)("div",{className:"sr-only",role:"status",children:0===u.length?"No matching commands":`${String(u.length)} command${1===u.length?"":"s"}`}),(0,n.jsxs)("div",{id:"cmdk-list",role:"listbox",className:"cmdk-list",children:[0===u.length&&(0,n.jsx)("div",{className:"cmdk-empty",children:"No matching commands"}),u.map((e,t)=>{var a;let l;return(0,n.jsxs)("div",{role:"option",id:`cmdk-row-${String(t)}`,"aria-selected":t===i,className:"cmdk-row","data-sel":t===i,tabIndex:-1,onMouseEnter:()=>r(t),onClick:()=>m(e),children:[(0,n.jsx)("span",{className:"cmdk-ico",children:(a=e.icon,l=j.Icons[a]??j.Icons.spark,(0,n.jsx)(l,{size:16}))}),(0,n.jsx)("span",{className:"cmdk-label",children:e.label}),(0,n.jsx)("span",{className:"spacer"}),void 0!==e.shortcut&&(0,n.jsx)("span",{className:"kbd",children:e.shortcut}),void 0!==e.group&&(0,n.jsx)("span",{className:"cmdk-group mono",children:e.group})]},e.id)})]})]})})}var tA=e.i(74080);function tM(e){return Array.from(new Set(e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e.length>0)))}function tL({onCancel:e,preserveExisting:t=!1,storedApiKeyHeaderName:l,storedModels:s=[]}){let i=(0,a.useRef)(null),r=(0,a.useRef)(null),o=(0,a.useRef)(null),c=(0,a.useRef)(null),d=(0,a.useRef)(void 0),[u,m]=(0,a.useState)(""),[h,p]=(0,a.useState)(""),[f,g]=(0,a.useState)(""),[v,b]=(0,a.useState)(""),[x,y]=(0,a.useState)(""),[k,N]=(0,a.useState)(""),[S,C]=(0,a.useState)(!1),[I,E]=(0,a.useState)(),[R,$]=(0,a.useState)(),[T,A]=(0,a.useState)();async function M(e){if(e.preventDefault(),!S){var n;C(!0),E(void 0),$(void 0),A(void 0),i.current?.focus();try{let e=tM(v);if(function(e){try{return new URL(e.trim()).hostname.endsWith(".services.ai.azure.com")}catch{return!1}}(u)&&0===e.length){E("Azure AI Foundry requires deployment names. Paste the names from the Deployments tab."),C(!1);return}let a=tM(x),l=!t||""!==u.trim()||""!==h.trim()||""!==f.trim()||e.length>0||a.length>0,s=""!==k.trim(),i=await (0,w.setupGateway)({baseUrl:""===u.trim()?void 0:u.trim(),apiKey:""===h.trim()?void 0:h.trim(),apiKeyHeaderName:""===f.trim()?void 0:f.trim(),deploymentNames:e,preserveExisting:t,...0===a.length?{}:{imageInputModelIds:a},...""===k.trim()?{}:{figmaAccessToken:k.trim()}}),r=i.testedModelIds.length,o=(n=i.skippedModelIds??[],0===n.length?"":` Could not verify deployment${1===n.length?"":"s"}: ${n.join(", ")}.`);C(!1),s&&!l?A("Verified Figma access token. Reloading Keiko…"):s?A(`Verified ${String(r)} workflow chat model${1===r?"":"s"} and Figma access token. Reloading Keiko…${o}`):A(`Verified ${String(r)} workflow chat model${1===r?"":"s"}. Reloading Keiko…${o}`),d.current=window.setTimeout(()=>window.location.reload(),0===(i.skippedModelIds??[]).length?800:1800)}catch(t){let e=t instanceof w.ApiError?{message:t.message,code:t.code}:t instanceof Error?{message:t.message}:{message:"The gateway could not be configured."};E(e.message),$(e.code),C(!1)}}}(0,a.useEffect)(()=>{let e=document.documentElement,n=Number(e.dataset.keikoModalOpenCount??"0");return e.dataset.keikoModalOpenCount=String(n+1),e.setAttribute("data-keiko-modal-open","true"),c.current=document.activeElement,t?o.current?.focus():r.current?.focus(),()=>{void 0!==d.current&&window.clearTimeout(d.current);let t=Math.max(0,Number(e.dataset.keikoModalOpenCount??"1")-1);0===t?(delete e.dataset.keikoModalOpenCount,e.removeAttribute("data-keiko-modal-open")):e.dataset.keikoModalOpenCount=String(t),c.current?.focus?.()}},[t]),(0,a.useEffect)(()=>{let t=i.current;if(null===t)return;let n=n=>{if("Escape"===n.key){if(S||void 0!==T||void 0===e)return;n.preventDefault(),e();return}if("Tab"!==n.key)return;let a=Array.from(t.querySelectorAll("button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),summary,[tabindex]:not([tabindex='-1'])"));if(0===a.length)return;let l=a[0],s=a[a.length-1];n.shiftKey&&document.activeElement===l?(n.preventDefault(),s.focus()):n.shiftKey||document.activeElement!==s||(n.preventDefault(),l.focus())};return t.addEventListener("keydown",n),()=>t.removeEventListener("keydown",n)},[S,e,T]),(0,a.useEffect)(()=>{void 0===I||S||(t&&""===u.trim()&&""===h.trim()?o.current?.focus():r.current?.focus())},[h,u,S,I,t]);let L=tM(v),q=tM(x),P=!t,D=""!==u.trim()||""!==h.trim()||""!==f.trim()||L.length>0||q.length>0,F=""!==k.trim(),z=!S&&void 0===T&&(P?""!==u.trim()&&""!==h.trim():D||F),O=s.map(e=>e.id),K=O.slice(0,6),B=Math.max(0,O.length-K.length),_=(0,n.jsxs)("div",{className:"gw-grid",children:[(0,n.jsxs)("label",{className:"gw-field gw-span-2",children:[(0,n.jsxs)("span",{children:["Base URL ",t?(0,n.jsx)("span",{className:"dlg-opt",children:"leave blank to keep"}):null]}),(0,n.jsx)("input",{className:"gw-input mono",value:u,placeholder:t?"Only enter a value to replace the stored gateway URL":"https://llm-gateway.example.com/v1",autoComplete:"off",disabled:S||void 0!==T,ref:r,onChange:e=>m(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["API token ",t?(0,n.jsx)("span",{className:"dlg-opt",children:"leave blank to keep"}):null]}),(0,n.jsx)("input",{className:"gw-input mono",type:"password",value:h,placeholder:t?"Only enter a value to replace the stored token":"Paste your API token",autoComplete:"off",disabled:S||void 0!==T,onChange:e=>p(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["API key header ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("input",{className:"gw-input mono",value:f,placeholder:t?"Leave blank to keep stored header":"Authorization",autoComplete:"off",disabled:S||void 0!==T,onChange:e=>g(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsx)("span",{children:"Deployment names for Azure"}),(0,n.jsx)("textarea",{className:"gw-input gw-textarea mono",value:v,placeholder:"Paste deployment names, one per line",autoComplete:"off",disabled:S||void 0!==T,onChange:e=>b(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["Image-input models ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"gw-input gw-textarea mono",value:x,placeholder:"Paste image-capable model names, one per line",autoComplete:"off",disabled:S||void 0!==T,onChange:e=>y(e.target.value)})]})]}),U=(0,n.jsx)("div",{className:"gw-setup-backdrop",role:"presentation",children:(0,n.jsx)("div",{ref:i,className:"gw-setup",role:"dialog","aria-modal":"true","aria-labelledby":"gw-setup-title","aria-describedby":"gw-setup-desc",tabIndex:-1,children:(0,n.jsxs)("form",{className:"gw-form",onSubmit:e=>void M(e),children:[(0,n.jsxs)("div",{className:"gw-head",children:[(0,n.jsxs)("div",{className:"gw-setup-badge",children:[(0,n.jsx)(j.Icons.cube,{size:18}),t?"Credential update":"Model gateway setup"]}),(0,n.jsx)("h1",{id:"gw-setup-title",children:t?"Update Keiko credentials":"Connect Keiko to your internal LLMs"}),(0,n.jsx)("p",{id:"gw-setup-desc",children:t?"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,n.jsxs)("section",{className:"gw-section","aria-labelledby":"gw-model-section-title",children:[(0,n.jsx)("div",{className:"gw-section-head",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{id:"gw-model-section-title",children:"Model gateway"}),(0,n.jsx)("p",{children:t?"Blank gateway fields keep the stored value.":"Base URL and API token are required."})]})}),t?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"gw-current","aria-label":"Stored model gateway credentials",children:[(0,n.jsxs)("div",{className:"gw-current-row",children:[(0,n.jsx)("span",{children:"Gateway URL"}),(0,n.jsx)("strong",{children:"Stored"})]}),(0,n.jsxs)("div",{className:"gw-current-row",children:[(0,n.jsx)("span",{children:"API token"}),(0,n.jsx)("strong",{className:"mono",children:"••••••••••••"})]}),(0,n.jsxs)("div",{className:"gw-current-row",children:[(0,n.jsx)("span",{children:"API key header"}),(0,n.jsx)("strong",{className:"mono",children:l??"authorization"})]}),(0,n.jsxs)("div",{className:"gw-current-models",children:[(0,n.jsx)("span",{children:"Configured models"}),(0,n.jsxs)("div",{className:"gw-model-chips",children:[0===K.length?(0,n.jsx)("strong",{children:"Stored"}):K.map(e=>(0,n.jsx)("strong",{className:"mono",children:e},e)),B>0?(0,n.jsxs)("strong",{children:["+",B.toString()]}):null]})]})]}),(0,n.jsxs)("details",{className:"gw-replace",children:[(0,n.jsx)("summary",{children:"Replace model gateway settings"}),_]})]}):_]}),(0,n.jsxs)("section",{className:"gw-section","aria-labelledby":"gw-figma-section-title",children:[(0,n.jsx)("div",{className:"gw-section-head",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{id:"gw-figma-section-title",children:"Figma Snapshot"}),(0,n.jsx)("p",{children:"Optional connector credential."})]})}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["Figma access token ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("input",{className:"gw-input mono",type:"password",value:k,placeholder:t?"Stored Figma token is kept when blank":"Paste a read-only Figma PAT when needed",autoComplete:"off",disabled:S||void 0!==T,ref:o,onChange:e=>N(e.target.value)})]})]}),(0,n.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!==I?(0,n.jsxs)("div",{className:"gw-error",role:"alert",children:[I,void 0!==R?(0,n.jsx)("div",{className:"gw-error-code mono",children:R}):null]}):null,void 0!==T?(0,n.jsx)("div",{className:"gw-success",role:"status",children:T}):null,S?(0,n.jsx)("div",{className:"gw-pending",role:"status",children:"Testing credentials…"}):null,(0,n.jsx)("span",{id:"gw-submit-requirements",className:"visually-hidden",children:t?"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,n.jsxs)("div",{className:"gw-actions",children:[void 0!==e?(0,n.jsx)("button",{className:"gw-cancel",type:"button",disabled:S||void 0!==T,onClick:e,children:"Cancel"}):null,(0,n.jsx)("button",{className:"gw-submit",type:"submit",disabled:!z,"aria-busy":S,"aria-describedby":"gw-submit-requirements",children:S?"Testing credentials…":"Test & save"})]})]})})});return"u"<typeof document?U:(0,tA.createPortal)(U,document.body)}let tq=[["ask","Ask every action"],["full","Full access"]];function tP({cfg:e,set:t}){let a=!1!==e.keikoMode,l="full"===e.access?"full":"ask",s=a?"No rights by default. You approve while manual; Keiko governs per policy when autonomous.":"full"===l?"Legacy: agent acts without prompts.":"Legacy: you approve each privileged action.";return(0,n.jsxs)("div",{className:"permctl",children:[(0,n.jsxs)("button",{type:"button",className:"perm-toggle","data-on":a,"aria-pressed":a,onClick:()=>t("keikoMode",!a),children:[(0,n.jsx)("img",{className:"perm-orca",src:"/assets/keiko-logo.svg",alt:""}),(0,n.jsxs)("span",{className:"perm-tt",children:[(0,n.jsx)("span",{className:"perm-name",children:"Keiko-Mode"}),(0,n.jsx)("span",{className:"perm-desc",children:"Zero standing rights · Keiko governs"})]}),(0,n.jsx)("span",{className:"perm-sw"+(a?" on":""),children:(0,n.jsx)("span",{})})]}),!a&&(0,n.jsx)("div",{className:"perm-legacy",children:tq.map(([e,a])=>(0,n.jsx)("button",{type:"button",className:"perm-opt","data-on":l===e,"aria-pressed":l===e,onClick:()=>t("access",e),children:a},e))}),(0,n.jsx)("div",{className:"perm-note",children:s})]})}function tD(e){return"chat"===e.kind&&e.toolCalling&&e.structuredOutput}function tF(e){if(e instanceof w.ApiError){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 tz({value:e,projectId:t,selectProjectRoot:l=!1,onSelect:s,onClose:i}){let[r,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(e),[u,m]=(0,a.useState)(!1),[h,p]=(0,a.useState)(null),f=t??e.trim(),g=(0,a.useCallback)(async e=>{if(0===f.length){o(null),p("Enter an absolute folder path.");return}m(!0),p(null);try{let t=await (0,w.fetchFilesDirectories)(f,e);o(t),d(t.path)}catch(e){p(tF(e))}finally{m(!1)}},[f]);return(0,a.useEffect)(()=>{g(e.length>0?e:void 0)},[]),(0,n.jsxs)("div",{className:"dir-picker",role:"group","aria-label":"Directory picker",children:[(0,n.jsxs)("div",{className:"dir-top",children:[(0,n.jsx)("input",{className:"dlg-input mono dir-path",value:c,"aria-label":"Folder path",placeholder:"/absolute/folder/path",onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),g(c))}}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dir-go",onClick:()=>void g(c),children:"Go"})]}),null!==r?(0,n.jsx)("div",{className:"dir-roots",children:r.roots.map(e=>(0,n.jsx)("button",{type:"button",className:"dir-chip",onClick:()=>void g(e.path),children:e.label},`${e.label}:${e.path}`))}):null,(0,n.jsxs)("div",{className:"dir-list",children:[r?.parent!==null&&r?.parent!==void 0?(0,n.jsxs)("button",{type:"button",className:"dir-row",onClick:()=>void g(r.parent??void 0),children:[(0,n.jsx)(j.Icons.back,{size:14}),(0,n.jsx)("span",{children:"Parent directory"})]}):null,r?.entries.map(e=>(0,n.jsxs)("button",{type:"button",className:"dir-row",onClick:()=>void g(e.path),children:[(0,n.jsx)(j.Icons.folder,{size:14}),(0,n.jsx)("span",{children:e.name})]},e.path)),u?(0,n.jsx)("div",{className:"dir-note",role:"status",children:"Loading directories…"}):null,u||null===r||0!==r.entries.length?null:(0,n.jsx)("div",{className:"dir-note",children:"No child directories."}),null!==h?(0,n.jsx)("div",{className:"dir-error",role:"alert",children:h}):null]}),(0,n.jsxs)("div",{className:"dir-actions",children:[(0,n.jsx)("button",{type:"button",className:"dlg-btn",onClick:i,children:"Close"}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",onClick:()=>{null!==r&&(s(l?r.roots[0]?.path??r.path:r.path),i())},disabled:null===r,children:"Use directory"})]})]})}let tO=[{id:"verify",label:"Verify"},{id:"explain-plan",label:"Explain plan"},{id:"unit-test-generation",label:"Generate unit tests"},{id:"bug-investigation",label:"Investigate bug"}];function tK(e){return e.filter(e=>e.available).map(e=>e.path)}function tB(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e.length>0)}function t_(e){return e.replaceAll("\\","/")}function tU(e,t){let n=t_(t.trim());if(0===n.length)return"";let a=t_(e.trim()).replace(/\/+$/u,"");if(0===a.length)return n;if(n===a)return".";let l=`${a}/`;return n.startsWith(l)?n.slice(l.length):n}function tW(e,t){return tB(t).map(t=>tU(e,t)).join(", ")}function tH({filesContext:e,firstRef:t,directoryField:l,setDirectoryField:s,setDialogError:i,onConfirm:r}){let[o,c]=(0,a.useState)("verify"),[d,u]=(0,a.useState)(e?.root??""),[m,h]=(0,a.useState)(""),[p,f]=(0,a.useState)([]),[g,v]=(0,a.useState)([]),[b,x]=(0,a.useState)(()=>{var t,n;let a;return t=e?.root??"",{verifyTargetFiles:a=null===(n=e?.activeFilePath??null)?"":tU(t,n),explainFilePath:a,explainQuestion:"",unitTargetKind:"file",unitFilePath:a,unitModuleDir:"",unitFilePaths:a,bugDescription:"",bugFailingOutput:"",bugStackTrace:"",bugTargetFiles:a}}),[y,k]=(0,a.useState)(!0),[N,S]=(0,a.useState)(!1),[C,I]=(0,a.useState)(!1),E=d.trim(),R=null!==e&&e.root===E&&void 0!==e.activeFilePath?e.activeFilePath:null,$=E.length>0&&g.includes(E),T=function(e,t,n,a){if(0===t.length)return"Workspace is required.";if(0===n.length)return"No model is available.";if("explain-plan"===e&&0===a.explainFilePath.trim().length)return"Explain plan requires a file path.";if("unit-test-generation"===e){if("file"===a.unitTargetKind&&0===a.unitFilePath.trim().length)return"Unit test generation requires a file path.";if("module"===a.unitTargetKind&&0===a.unitModuleDir.trim().length)return"Unit test generation requires a module folder.";if("changedFiles"===a.unitTargetKind&&0===tB(a.unitFilePaths).length)return"Unit test generation requires at least one file path."}return"bug-investigation"!==e||a.bugDescription.trim().length>0||a.bugFailingOutput.trim().length>0||a.bugStackTrace.trim().length>0||tB(a.bugTargetFiles).length>0?null:"Bug investigation requires description, output, stack trace, or target files."}(o,E,m,b),A=null===T&&$&&!C&&!y;(0,a.useEffect)(()=>{let e=!1;return k(!0),i(null),Promise.all([(0,w.fetchModels)(),(0,w.fetchProjects)()]).then(([t,n])=>{if(e)return;let a=t.models.filter(tD);f(a),h(e=>e||(a[0]?.id??"")),v(tK(n.projects))}).catch(t=>{e||i(tF(t))}).finally(()=>{e||k(!1)}),()=>{e=!0}},[i]);let M=e=>{x(t=>({...t,...e}))};(0,a.useEffect)(()=>{if(null===R)return;let e=tU(E,R);x(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.unitFilePaths.trim().length&&(n.unitFilePaths=e),0===t.bugTargetFiles.trim().length&&(n.bugTargetFiles=e),0===Object.keys(n).length?t:{...t,...n}})},[R,E]);let L=async()=>{v(tK((await (0,w.fetchProjects)()).projects))},q=async()=>{if(0!==E.length){S(!0),i(null);try{await (0,w.createProject)({path:E}),await L()}catch(e){i(tF(e))}finally{S(!1)}}},P=async()=>{if(!A)return void i(T??"Workspace is not registered.");I(!0),i(null);let t=function(e,t,n,a){if("verify"===e){let e=tB(a.verifyTargetFiles).map(e=>tU(t,e));return{taskType:"verify",modelId:n,input:{workspaceRoot:t,...e.length>0?{targetFiles:e}:{}}}}if("explain-plan"===e)return{taskType:"explain-plan",modelId:n,input:{workspaceRoot:t,filePath:tU(t,a.explainFilePath),...a.explainQuestion.trim().length>0?{question:a.explainQuestion.trim()}:{}}};if("unit-test-generation"===e){let e=tB(a.unitFilePaths).map(e=>tU(t,e)),l="module"===a.unitTargetKind?{kind:"module",moduleDir:tU(t,a.unitModuleDir)}:"changedFiles"===a.unitTargetKind?{kind:"changedFiles",filePaths:e}:{kind:"file",filePath:tU(t,a.unitFilePath)};return{workflowId:"unit-test-generation",modelId:n,input:{workspaceRoot:t,target:l}}}return{workflowId:"bug-investigation",modelId:n,input:{workspaceRoot:t,report:{...a.bugDescription.trim().length>0?{description:a.bugDescription.trim()}:{},...a.bugFailingOutput.trim().length>0?{failingOutput:a.bugFailingOutput.trim()}:{},...a.bugStackTrace.trim().length>0?{stackTrace:a.bugStackTrace.trim()}:{},...tB(a.bugTargetFiles).length>0?{targetFiles:tB(a.bugTargetFiles).map(e=>tU(t,e))}:{}}}}}(o,E,m,b);try{let n=await (0,w.startRun)(t);r({workflow:o,model:m,runId:n.runId,fingerprint:n.fingerprint,workspaceRoot:E,inputJson:JSON.stringify(t.input),...null!==e&&e.root===E?{__connectFilesId:e.id}:{}})}catch(e){e instanceof w.ApiError&&"WORKSPACE_NOT_REGISTERED"===e.code?(await L().catch(()=>void 0),i("Workspace is not registered.")):i(tF(e))}finally{I(!1)}};return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Workflow"}),(0,n.jsxs)("span",{className:"dlg-selwrap",children:[(0,n.jsx)("select",{ref:t,className:"dlg-input mono",value:o,onChange:e=>c(e.target.value),children:tO.map(e=>(0,n.jsx)("option",{value:e.id,children:e.label},e.id))}),(0,n.jsx)("span",{className:"dlg-selchev",children:(0,n.jsx)(j.Icons.chevron,{size:15})})]})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Workspace"}),(0,n.jsxs)("span",{className:"dlg-dirwrap",children:[(0,n.jsx)("input",{className:"dlg-input mono",value:d,placeholder:"/absolute/project/path",onClick:()=>s("agentWorkspace"),onChange:e=>u(e.target.value)}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-dirbtn",onClick:()=>s("agentWorkspace"),children:"Browse"})]}),"agentWorkspace"===l?(0,n.jsx)(tz,{value:d,projectId:$?E:void 0,onSelect:u,onClose:()=>s(null)}):null]}),E.length>0&&!$?(0,n.jsxs)("div",{className:"dlg-agent-warning",children:[(0,n.jsx)("span",{children:"Workspace is not registered."}),(0,n.jsx)("button",{type:"button",className:"dlg-btn",disabled:N,onClick:()=>void q(),children:N?"Registering…":"Register workspace"})]}):null,(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Model"}),(0,n.jsxs)("span",{className:"dlg-selwrap",children:[(0,n.jsx)("select",{className:"dlg-input mono",value:m,onChange:e=>h(e.target.value),disabled:0===p.length,children:p.map(e=>(0,n.jsx)("option",{value:e.id,children:e.id},e.id))}),(0,n.jsx)("span",{className:"dlg-selchev",children:(0,n.jsx)(j.Icons.chevron,{size:15})})]})]}),null!==R?(0,n.jsxs)("button",{type:"button",className:"dlg-current-file",onClick:()=>{if(null===R)return;let e=tU(E,R);"verify"===o?M({verifyTargetFiles:e}):"explain-plan"===o?M({explainFilePath:e}):"unit-test-generation"===o?"changedFiles"===b.unitTargetKind?M({unitFilePaths:e}):M({unitTargetKind:"file",unitFilePath:e}):M({bugTargetFiles:e})},title:R,children:[(0,n.jsx)(j.Icons.files,{size:13})," Use current file ",(0,n.jsx)("span",{className:"mono",children:R})]}):null,"verify"===o?(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:["Target files ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,placeholder:"src/file.ts, src/other.ts",value:b.verifyTargetFiles,onChange:e=>M({verifyTargetFiles:e.target.value}),onBlur:e=>M({verifyTargetFiles:tW(E,e.target.value)})})]}):"explain-plan"===o?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"File path"}),(0,n.jsx)("input",{className:"dlg-input mono",placeholder:"src/file.ts",value:b.explainFilePath,onChange:e=>M({explainFilePath:e.target.value}),onBlur:e=>M({explainFilePath:tU(E,e.target.value)})})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:["Question ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea",rows:2,placeholder:"What should the plan focus on?",value:b.explainQuestion,onChange:e=>M({explainQuestion:e.target.value})})]})]}):"unit-test-generation"===o?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Target"}),(0,n.jsxs)("span",{className:"dlg-selwrap",children:[(0,n.jsxs)("select",{className:"dlg-input mono",value:b.unitTargetKind,onChange:e=>M({unitTargetKind:e.target.value}),children:[(0,n.jsx)("option",{value:"file",children:"Single file"}),(0,n.jsx)("option",{value:"module",children:"Module"}),(0,n.jsx)("option",{value:"changedFiles",children:"Changed files"})]}),(0,n.jsx)("span",{className:"dlg-selchev",children:(0,n.jsx)(j.Icons.chevron,{size:15})})]})]}),"module"===b.unitTargetKind?(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Module folder"}),(0,n.jsx)("input",{className:"dlg-input mono",placeholder:"src/module",value:b.unitModuleDir,onChange:e=>M({unitModuleDir:e.target.value}),onBlur:e=>M({unitModuleDir:tU(E,e.target.value)})})]}):"changedFiles"===b.unitTargetKind?(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"File paths"}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,placeholder:"src/file.ts, src/other.ts",value:b.unitFilePaths,onChange:e=>M({unitFilePaths:e.target.value}),onBlur:e=>M({unitFilePaths:tW(E,e.target.value)})})]}):(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"File path"}),(0,n.jsx)("input",{className:"dlg-input mono",placeholder:"src/file.ts",value:b.unitFilePath,onChange:e=>M({unitFilePath:e.target.value}),onBlur:e=>M({unitFilePath:tU(E,e.target.value)})})]})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:["Description ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea",rows:2,placeholder:"Describe the observed bug.",value:b.bugDescription,onChange:e=>M({bugDescription:e.target.value})})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:["Failing output ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,value:b.bugFailingOutput,onChange:e=>M({bugFailingOutput:e.target.value})})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:["Stack trace ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,value:b.bugStackTrace,onChange:e=>M({bugStackTrace:e.target.value})})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:["Target files ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,placeholder:"src/file.ts, src/other.ts",value:b.bugTargetFiles,onChange:e=>M({bugTargetFiles:e.target.value}),onBlur:e=>M({bugTargetFiles:tW(E,e.target.value)})})]})]}),(0,n.jsxs)("div",{className:"dlg-agent-actions",children:[(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",disabled:!A,"aria-busy":C,"aria-describedby":A||C?void 0:"agent-start-validation",onClick:()=>void P(),children:C?"Starting…":"Start agent"}),y?(0,n.jsx)("span",{id:"agent-start-validation",className:"dlg-note",role:"status",children:"Loading models and projects…"}):null,y||null===T?null:(0,n.jsx)("span",{id:"agent-start-validation",className:"dlg-note",role:"status",children:T})]})]})}function tY({type:e,types:t,filesContext:l=null,onConfirm:s,onClose:i}){let r=t[e],o=r.config??[],[c,d]=(0,a.useState)(()=>(function(e){let t={};for(let n of e)t[n.key]=n.def??"";return t})(o)),[u,m]=(0,a.useState)(!1),[h,p]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),v=(0,a.useRef)(null),b=(0,a.useRef)(null),x=(0,a.useRef)(null);(0,a.useEffect)(()=>(x.current=document.activeElement,()=>{let e=x.current;null!==e&&e.isConnected?e.focus():requestAnimationFrame(()=>{(document.querySelector('.window[data-top="true"]')??document.querySelector(".ws-fab")??document.body).focus({preventScroll:!0})})}),[]),(0,a.useEffect)(()=>{let e=requestAnimationFrame(()=>{m(!0),(v.current??b.current)?.focus()});return()=>cancelAnimationFrame(e)},[]),(0,a.useEffect)(()=>{let e=e=>{"Escape"===e.key&&i()};return window.addEventListener("keydown",e),()=>{window.removeEventListener("keydown",e)}},[i]),(0,a.useEffect)(()=>{if("files"!==e)return;let t=!1,n=c.root;if("string"!=typeof n||!(n.length>0))return p(null),(0,w.fetchProjects)().then(e=>{let n=tK(e.projects)[0];t||void 0===n||d(e=>({...e,root:n}))}).catch(e=>{t||p(tF(e))}),()=>{t=!0}},[c.root,e]);let y=(e,t)=>d(n=>({...n,[e]:t})),k=()=>{"agents"!==e&&s(c)},N=j.Icons[r.icon],S=r.cta??`Open ${r.title}`;return(0,n.jsx)("div",{className:"dlg-overlay"+(u?" in":""),onPointerDown:i,children:(0,n.jsxs)("div",{ref:b,className:"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 i();if("Enter"===e.key&&(e.metaKey||e.ctrlKey))return void k();if("Enter"===e.key){let t=e.target instanceof HTMLElement?e.target.tagName:"";("INPUT"===t||"SELECT"===t)&&(e.preventDefault(),k());return}if("Tab"!==e.key)return;let a=(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===a.length)return;let l=a[0],s=a[a.length-1];e.shiftKey&&document.activeElement===l?(e.preventDefault(),s.focus()):e.shiftKey||document.activeElement!==s||(e.preventDefault(),l.focus())},children:[(0,n.jsxs)("div",{className:"dlg-head",children:[(0,n.jsx)("span",{className:"dlg-ico",children:(0,n.jsx)(N,{size:20})}),(0,n.jsxs)("div",{className:"dlg-htext",children:[(0,n.jsxs)("span",{id:"new-window-title",className:"dlg-title",children:["New ",r.title," window"]}),(0,n.jsx)("span",{id:"new-window-desc",className:"dlg-sub",children:r.desc})]}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsx)("button",{type:"button",className:"palette-x",onClick:i,"aria-label":"Cancel",title:"Cancel",children:(0,n.jsx)(j.Icons.close,{size:16})})]}),(0,n.jsxs)("div",{className:"dlg-body",children:["agents"===e?(0,n.jsx)(tH,{filesContext:l,firstRef:e=>{v.current=e},directoryField:f,setDirectoryField:g,setDialogError:p,onConfirm:s}):0===o.length&&(0,n.jsxs)("div",{className:"dlg-empty",children:["Add a new ",r.title," window to your workspace."]}),"agents"!==e&&o.map((e,t)=>(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:[e.label,!0===e.optional&&(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),function(e,t,a,l,s){if("perm"===e.type)return(0,n.jsx)(tP,{cfg:t,set:a});let i=t[e.key],r="string"==typeof i?i:void 0===i?"":String(i);if("select"===e.type){let t=e.options??[];return(0,n.jsxs)("span",{className:"dlg-selwrap",children:[(0,n.jsx)("select",{ref:l??void 0,className:"dlg-input mono",value:r,onChange:t=>a(e.key,t.target.value),disabled:0===t.length,children:t.map(t=>(0,n.jsx)("option",{value:t,children:(e.prefix??"")+t},t))}),(0,n.jsx)("span",{className:"dlg-selchev",children:(0,n.jsx)(j.Icons.chevron,{size:15})})]})}return"textarea"===e.type?(0,n.jsx)("textarea",{ref:l??void 0,className:"dlg-input dlg-textarea",rows:3,placeholder:e.placeholder??"",value:r,onChange:t=>a(e.key,t.target.value)}):"directory"===e.type?(0,n.jsxs)("span",{className:"dlg-dirwrap",children:[(0,n.jsx)("input",{ref:l??void 0,className:"dlg-input mono",placeholder:e.placeholder??e.label,value:r,onClick:()=>s(e.key),onChange:t=>a(e.key,t.target.value)}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-dirbtn",onClick:()=>s(e.key),children:"Browse"})]}):(0,n.jsx)("input",{ref:l??void 0,className:"dlg-input mono",placeholder:e.placeholder??e.label,value:r,onChange:t=>a(e.key,t.target.value)})}(e,c,y,0===t?e=>{v.current=e}:null,g),"directory"===e.type&&f===e.key?(0,n.jsx)(tz,{value:"string"==typeof c[e.key]?c[e.key]:"",selectProjectRoot:"root"===e.key,onSelect:t=>y(e.key,t),onClose:()=>g(null)}):null]},e.key)),null!==h?(0,n.jsx)("div",{className:"dlg-error",role:"alert",children:h}):null]}),(0,n.jsxs)("div",{className:"dlg-foot",children:[(0,n.jsx)("button",{type:"button",className:"dlg-btn",onClick:i,children:"Cancel"}),"agents"!==e?(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",onClick:k,children:S}):null]})]})})}function tJ({types:e,order:t,onAdd:l,onClose:s}){let i=t.length<=4?2:3,r=(0,a.useRef)(null),o=(0,a.useRef)(null),[c,d]=(0,a.useState)(0);return(0,a.useEffect)(()=>{o.current=document.activeElement;let e=r.current?.querySelector(".pal-card");return e?.focus(),()=>{let e=document.activeElement;(null===e||e===document.body)&&o.current?.focus?.()}},[]),(0,a.useEffect)(()=>{let e=e=>{null!==r.current&&e.target instanceof Node&&!r.current.contains(e.target)&&s()};return document.addEventListener("pointerdown",e),()=>{document.removeEventListener("pointerdown",e)}},[s]),(0,n.jsxs)("div",{ref:r,className:"palette",role:"dialog","aria-labelledby":"palette-title","aria-describedby":"palette-desc",tabIndex:-1,onPointerDown:e=>e.stopPropagation(),onKeyDown:e=>{if("Escape"===e.key){e.preventDefault(),s();return}if(!(e.target instanceof HTMLElement)||!e.target.classList.contains("pal-card"))return;let t=Array.from(r.current?.querySelectorAll(".pal-card")??[]),n=function(e,t,n,a){let l;if(0===n)return null;if("Home"===e)return 0;if("End"===e)return n-1;if("ArrowRight"===e)l=1;else if("ArrowLeft"===e)l=-1;else if("ArrowDown"===e)l=a;else{if("ArrowUp"!==e)return null;l=-a}return Math.max(0,Math.min(n-1,t+l))}(e.key,t.indexOf(e.target),t.length,i);null!==n&&(e.preventDefault(),d(n),t[n]?.focus())},onBlur:e=>{e.relatedTarget instanceof Node&&r.current?.contains(e.relatedTarget)!==!0&&s()},"data-columns":i,children:[(0,n.jsxs)("div",{className:"palette-head",children:[(0,n.jsx)("span",{className:"palette-badge",children:(0,n.jsx)(j.Icons.add,{size:17})}),(0,n.jsxs)("div",{className:"palette-htext",children:[(0,n.jsx)("span",{id:"palette-title",className:"palette-title",children:"New window"}),(0,n.jsx)("span",{id:"palette-desc",className:"palette-sub",children:"Pick a card to add to your workspace"})]}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsx)("button",{type:"button",className:"palette-x",onClick:s,"aria-label":"Close",title:"Close",children:(0,n.jsx)(j.Icons.close,{size:16})})]}),(0,n.jsx)("div",{className:"palette-grid",children:t.map((t,a)=>{let s=e[t],i=j.Icons[s.icon];return(0,n.jsxs)("button",{type:"button",className:"pal-card pal-main",tabIndex:a===c?0:-1,onFocus:()=>d(a),onClick:()=>l(t),children:[(0,n.jsx)("span",{className:"pal-ico",children:(0,n.jsx)(i,{size:18})}),(0,n.jsx)("span",{className:"pal-name",children:s.title}),(0,n.jsx)("span",{className:"pal-desc",children:s.desc}),(0,n.jsx)("span",{className:"pal-add","aria-hidden":"true",children:(0,n.jsx)(j.Icons.plus,{size:15})})]},t)})})]})}async function tG(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 tV(e,t){let n,a,l=(t?.method??"GET").toUpperCase(),s=t?.body,i=await fetch(e,{...t,headers:(n={Accept:"application/json"},((a="GET"!==l&&"HEAD"!==l)||null!=s)&&(n["Content-Type"]="application/json"),a&&(n["X-Keiko-CSRF"]="1"),n)});if(!i.ok){let{code:e,message:t}=await tG(i);throw new w.ApiError(e,t,i.status)}return i.json()}async function tX(e={},t=tV){let 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 a=n.toString();return t(`/api/memory${a.length>0?`?${a}`:""}`)}async function tQ(e=tV){return e("/api/memory/review-queue")}async function tZ(e,t=tV){return t("/api/memory/consolidation/jobs",{method:"POST",body:JSON.stringify({settings:e})})}async function t0(e,t=tV){return t(`/api/memory/consolidation/jobs/${encodeURIComponent(e)}`)}async function t1(e,t=tV){return t(`/api/memory/consolidation/jobs/${encodeURIComponent(e)}/cancel`,{method:"POST",body:"{}"})}async function t2(e,t=tV){return t(`/api/memory/${encodeURIComponent(e)}`)}async function t4(e,t,n=tV){return n(`/api/memory/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})}async function t3(e,t=tV){return t(`/api/memory/${encodeURIComponent(e)}/pin`,{method:"POST",body:"{}"})}async function t6(e,t=tV){return t(`/api/memory/${encodeURIComponent(e)}/unpin`,{method:"POST",body:"{}"})}async function t5(e,t,n=tV){return n(`/api/memory/${encodeURIComponent(e)}/archive`,{method:"POST",body:JSON.stringify({...void 0!==t?{reason:t}:{}})})}async function t8(e,t,n=tV){return n(`/api/memory/${encodeURIComponent(e)}/forget`,{method:"POST",body:JSON.stringify({acknowledged:!0,...void 0!==t?{reason:t}:{}})})}async function t7(e,t,n=tV){return n(`/api/memory/${encodeURIComponent(e)}`,{method:"DELETE",body:JSON.stringify({acknowledged:!0,...void 0!==t?{reason:t}:{}})})}async function t9(e,t,n=tV){return n(`/api/memory/${encodeURIComponent(e)}/correct`,{method:"POST",body:JSON.stringify({body:t})})}async function ne(e,t=tV){return t(`/api/memory/proposals/${encodeURIComponent(e)}/accept`,{method:"POST",body:"{}"})}async function nt(e,t,n=tV){return n(`/api/memory/proposals/${encodeURIComponent(e)}/reject`,{method:"POST",body:JSON.stringify({...void 0!==t?{reason:t}:{}})})}let nn=[{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 na(e){return nn.find(t=>t.workflowId===e)}function nl(e){return void 0===e||!Number.isFinite(e)||e<=0?0:Math.floor(e)}function ns(e){return"u">typeof TextEncoder?new TextEncoder().encode(e).length:e.length}function ni(e){let t=nl(e.modelContextWindow),n=nl(e.modelMaxOutputTokens),a=Math.max(0,t-n),l=ns(e.userDraftText),s=function(e){let t=0;for(let n of e)t+=ns(n.role),t+=ns(n.content);return t}(e.conversationHistory),i=function(e){if(void 0===e)return 0;let t=0;for(let n of e)t+=nl(n.extractedBytes);return t}(e.documentContext),r=nl(e.repoContextPackBytes),o=nl(e.knowledgeCapsuleBytes),c=nl(e.memoryContextBytes),d=l+s+i+r+o+c,u=Math.ceil(d/4),m=function(e,t){if(t<=0)return"exceeded";let n=e/t;return n>.95?"exceeded":n>.75?"high":n>.5?"moderate":"low"}(u,a);return{approximateBytes:d,approximateTokens:u,contextWindowTokens:t,reservedOutputTokens:n,availableInputTokens:a,pressure:m,breakdown:{draftBytes:l,historyBytes:s,documentBytes:i,repoContextBytes:r,knowledgeBytes:o,memoryBytes:c}}}function nr(e){return"chat"===e.kind}let no={embedding:"embedding-only","ocr-vision":"ocr-vision-only"},nc=[/\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],nd=/\s+\(([A-Z][A-Z0-9_/-]{2,})\)\s*$/;function nu(e){let t=e;for(let e of nc)t=t.replace(e,"[REDACTED]");return t.replace(/\bBearer\s+\[REDACTED\]/gi,"[REDACTED]")}function nm(e,t){return"BAD_REQUEST"===t&&e.toLowerCase().includes("too broad")&&e.toLowerCase().includes("connected")}function nh(e){return"CLARIFICATION_NEEDED"===e}function np(e,t){return nh(t)?"Keiko braucht mehr Kontext":nm(e,t)?"Narrow the connected-source question":"PAYLOAD_TOO_LARGE"===t?"Request is too large":"NO_MODEL"===t?"No model is available":void 0!==t?"Request failed":"Something went wrong"}function nf(e,t){return nh(t)?"Nenne eine konkrete Datei, einen Identifier, eine Fehlermeldung oder eine exakte Phrase.":nm(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.":"PAYLOAD_TOO_LARGE"===t?"Reduce the selected scope or remove large attachments before retrying.":void 0}function ng(e,t){if(e instanceof w.ApiError){let n=nu(e.message.trim());return n.length>0?`${n} (${e.code})`:`${t} (${e.code})`}return e instanceof Error&&e.message.trim().length>0?nu(e.message.trim()):t}let nv="\n…[truncated]",nb=["text/"],nx=new Set(["application/json","application/x-yaml","application/yaml"]),ny=new TextEncoder;function nw(e){return ny.encode(e).length}function nj(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t>=0?e.slice(t+1):e}let nk=`${String(256)} KB`;function nN(e){return`"${e}" won't be sent — the ${nk} attachment limit was already used by earlier files.`}async function nS(e,t){var n,a;let l,s,i,r,o;if(e.remainingAggregate<=0)return nN(nj(t.name));try{l=await t.file.text()}catch{return n=nj(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-nw(nv),0));if(c<=0)return nN(nj(t.name));let{entry:d,consumed:u}=(i=(s=nw(a=l)>c)?function(e,t){if(t<=0)return"";if(nw(e)<=t)return e;let n=0,a="";for(let l of e){let e=n+nw(l);if(e>t)break;n=e,a+=l}return a}(a,c):a,r=nw(i),o=s?nw(nv):0,{entry:{id:t.id,displayName:nj(t.name),mimeType:t.mimeType,sizeBytes:t.sizeBytes,extractedBytes:r,truncated:s,truncationMarker:s?nv:void 0,text:i},consumed:r+o});if(0===d.text.length)return 0===l.length?void 0:nN(nj(t.name));e.entries.push(d),e.remainingAggregate-=u}async function nC(e){let t=e.filter(e=>{var t;return t=e.mimeType,!!nb.some(e=>t.startsWith(e))||nx.has(t)}),n=t.slice(0,16),a={entries:[],remainingAggregate:262144},l=[];for(let e of n){let t=await nS(a,e);void 0!==t&&l.push(t)}for(let e of t.slice(16)){var s;l.push((s=nj(e.name),`"${s}" won't be sent — only the first ${String(16)} documents are included.`))}return{entries:a.entries,failures:l}}let nI=["text/"],nE=new Set(["application/pdf","application/json","application/x-yaml","application/yaml"]),nR="New chat",n$="keiko:chat-upsert",nT="keiko:chat-delete",nA=["completed","failed","cancelled"];function nM(e){return"idle"!==e&&!nA.includes(e)}let nL="The conversation context exceeded the model's window. Clear history or pick a larger-context model.",nq="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.",nP=new Set(["CONVERSATION_OVERSIZED_CONTEXT","GATEWAY_CONTEXT_OVERFLOW"]),nD=["context length","context_length_exceeded","max_tokens","too many tokens"],nF=["empty assistant response","empty grounded answer","without assistant content"];function nz(e){return void 0!==e&&e.contextWindowTokens>0&&"exceeded"===e.pressure}function nO(e){let t;return function(e){if(e instanceof w.ApiError&&nP.has(e.code))return!0;let t=e instanceof Error?e.message.toLowerCase():"";return 0!==t.length&&nD.some(e=>t.includes(e))}(e)?nL:0!==(t=e instanceof Error?e.message.toLowerCase():"").length&&nF.some(e=>t.includes(e))?e instanceof w.ApiError?`${nq} (${e.code})`:nq:ng(e,"Something went wrong. Try again.")}function nK(e){return[...e].sort((e,t)=>t.updatedAt-e.updatedAt)}function nB(e){window.dispatchEvent(new CustomEvent(n$,{detail:e}))}function n_(e){return e.find(nr)?.id}function nU(e,t){return void 0!==e&&t.some(t=>t.id===e&&nr(t))?e:n_(t)}function nW(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 nH={projects:[],chats:[],messages:[],models:[],activeProject:void 0,activeChat:void 0,selectedModel:void 0};async function nY(e){let t=(await (0,w.fetchModels)()).models.filter(nr),n=n_(t),a=[...(await (0,w.fetchProjects)().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)),l=a.find(e=>e.available)??a[0];if(void 0!==l){let e=nK((await (0,w.fetchChats)(l.path).catch(()=>({chats:[]}))).chats),n=e[0];if(void 0!==n){let s=await (0,w.fetchChatMessages)(n.id,l.path),i=nU(n.selectedModel,t);return{models:t,selectedModel:i,projects:Array.from(a),activeProject:l,chats:e,activeChat:n,messages:Array.from(s.messages)}}}if(void 0===n||!e)return{models:t,selectedModel:n,projects:Array.from(a),activeProject:l,chats:[],activeChat:void 0,messages:[]};let s={modelId:n,title:nR};l?.available===!0&&(s.projectPath=l.path);let i=await (0,w.createDesktopChat)(s);return nB(i.chat),{models:t,selectedModel:i.chat.selectedModel,projects:Array.from(i.projects),activeProject:i.project,chats:nK(i.chats),activeChat:i.chat,messages:Array.from(i.messages)}}function nJ(e={}){let t=e.autoCreate??!0,[n,l]=(0,a.useState)(nH),[s,i]=(0,a.useState)(""),[r,o]=(0,a.useState)(!0),[c,d]=(0,a.useState)("idle"),u=nM(c),m=(0,a.useRef)("idle"),h=(0,a.useRef)(null),[p,f]=(0,a.useState)(),[g,v]=(0,a.useState)(),[b,x]=(0,a.useState)(),[y,j]=(0,a.useState)(!0),[k,N]=(0,a.useState)(1200),S=(0,a.useRef)(void 0),C=(0,a.useRef)(0),I=(0,a.useRef)([]),[E,R]=(0,a.useState)([]),[$,T]=(0,a.useState)([]),A=(0,a.useCallback)(async e=>{var t;let a;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":nI.some(e=>t.startsWith(e))||nE.has(t)?"document":"unsupported-type";if("unsupported-type"===l)return{ok:!1,reason:"unsupported-type"};let s=n.models.find(e=>e.id===n.selectedModel);if(void 0!==s&&("image"===l&&!s.supportsImageInput||"document"===l&&!s.supportsDocumentInput))return{ok:!1,reason:"text-only-model"};if("image"===l)try{a=await new Promise((t,n)=>{let a=new FileReader;a.onload=()=>t(a.result),a.onerror=()=>n(Error("FileReader error")),a.readAsDataURL(e)})}catch{return{ok:!1,reason:"unsupported-type"}}let i={id:crypto.randomUUID(),kind:l,name:e.name,mimeType:e.type,sizeBytes:e.size,previewDataUrl:a,file:e};return R(e=>[...e,i]),{ok:!0}},[n.models,n.selectedModel]),M=(0,a.useCallback)(e=>{R(t=>t.filter(t=>t.id!==e))},[]),L=(0,a.useCallback)(()=>{R([])},[]),q=(0,a.useCallback)(async()=>{let e=E.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 nC(e);n.length>0&&f(n.join(" "));let a=t.map(e=>({id:e.id,displayName:e.displayName,truncated:e.truncated}));return{entries:t,disclosures:a}},[E]),P=(0,a.useCallback)(()=>{x(void 0)},[]),D=(0,a.useCallback)((e,t)=>({enabled:y,budgetTokens:k,context:{userId:"local-operator",workspaceId:t.path,projectId:t.path,conversationId:e.id}}),[k,y]),F=(0,a.useCallback)(async e=>{await ne(e),x(t=>void 0===t?t:{...t,actions:t.actions.filter(t=>"candidate"!==t.kind||t.proposalId!==e)})},[]),z=(0,a.useCallback)(async e=>{await nt(e),x(t=>void 0===t?t:{...t,actions:t.actions.filter(t=>"candidate"!==t.kind||t.proposalId!==e)})},[]),O=(0,a.useCallback)(async e=>{await t8(e,"user-initiated forget from Conversation Center"),x(t=>void 0===t?t:{...t,actions:t.actions.filter(t=>"forget"!==t.kind||t.memoryId!==e)})},[]),K=(0,a.useCallback)(e=>{m.current=e,d(e)},[]);(0,a.useEffect)(()=>{S.current=n.activeChat?.id},[n.activeChat?.id]),(0,a.useEffect)(()=>{I.current=n.models},[n.models]),(0,a.useEffect)(()=>{let e=!1;return async function(){o(!0),f(void 0);try{let n=await nY(t);e||l(e=>({...e,...n}))}catch(t){e||f(nO(t))}finally{e||o(!1)}}(),()=>{e=!0}},[t]),(0,a.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&&l(e=>({...e,chats:nK([t,...e.chats.filter(e=>e.id!==t.id)]),activeChat:e.activeChat?.id===t.id?t:e.activeChat,selectedModel:e.activeChat?.id===t.id?nU(t.selectedModel,e.models):e.selectedModel}))},t=e=>{let t=e.detail;"object"==typeof t&&null!==t&&"string"==typeof t.chatId&&l(e=>({...e,chats:e.chats.filter(e=>e.id!==t.chatId),activeChat:e.activeChat?.id===t.chatId?void 0:e.activeChat,messages:e.activeChat?.id===t.chatId?[]:e.messages}))};return window.addEventListener(n$,e),window.addEventListener(nT,t),()=>{window.removeEventListener(n$,e),window.removeEventListener(nT,t)}},[]),(0,a.useEffect)(()=>()=>{h.current?.abort()},[]);let B=(0,a.useCallback)(e=>{let t;f(void 0),l(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)})),R(t=>t.filter(t=>{let n;return void 0===(n=I.current.find(t=>t.id===e))||("image"===t.kind?n.supportsImageInput:n.supportsDocumentInput)}));let n=S.current;if(void 0===n)return;let a=C.current+1;C.current=a,(0,w.updateChat)(n,{selectedModel:e}).then(e=>{C.current!==a||S.current===e.chat.id&&(nB(e.chat),l(t=>({...t,selectedModel:e.chat.selectedModel,activeChat:t.activeChat?.id===e.chat.id?e.chat:t.activeChat,chats:t.chats.map(t=>t.id===e.chat.id?e.chat:t)})))}).catch(e=>{if(C.current===a&&S.current===n&&(f(nO(e)),void 0!==t)){let e=t;l(t=>({...t,selectedModel:t.activeChat?.id===n?e.selectedModel:t.selectedModel,activeChat:t.activeChat?.id===n?e.activeChat:t.activeChat,chats:t.chats.map(t=>{if(t.id!==n)return t;let a=e.chats.find(e=>e.id===n);return void 0!==a?{...t,selectedModel:a.selectedModel}:t})}))}})},[]),_=(0,a.useCallback)(async(e,t)=>{let a=nU(n.selectedModel,n.models);if(void 0===a)return void f("No conversation-eligible model is configured. Connect a gateway in Settings.");f(void 0);try{let s=t?.trim(),i={modelId:a,title:void 0!==s&&s.length>0?s:nR},r=e?.path??n.activeProject?.path;void 0!==r&&(i.projectPath=r);let o=await (0,w.createDesktopChat)(i);return S.current=o.chat.id,nB(o.chat),l({projects:Array.from(o.projects),chats:nK(o.chats),messages:Array.from(o.messages),models:n.models,activeProject:o.project,activeChat:o.chat,selectedModel:o.chat.selectedModel}),o.chat}catch(e){f(nO(e));return}},[n.selectedModel,n.activeProject,n.models]),U=(0,a.useCallback)(async e=>{f(void 0),l(t=>({...t,activeProject:e}));try{let t=await (0,w.fetchChats)(e.path),a=nK(t.chats),s=a[0];if(void 0===s)return void await _(e);let i=await (0,w.fetchChatMessages)(s.id,e.path);S.current=s.id;let r=nU(s.selectedModel,n.models);l(e=>({...e,chats:a,activeChat:s,selectedModel:r,messages:Array.from(i.messages)})),x(void 0)}catch(e){f(nO(e))}},[_,n.models]),W=(0,a.useCallback)(async e=>{f(void 0),h.current?.abort(),h.current=null,S.current=e.id,v(void 0),x(void 0),T([]);try{let t=await (0,w.fetchChatMessages)(e.id,e.projectPath),a=nU(e.selectedModel,n.models);l(n=>{let l=n.projects.find(t=>t.path===e.projectPath);return{...n,activeProject:l,activeChat:e,selectedModel:a,messages:Array.from(t.messages)}})}catch(e){f(nO(e))}},[n.models]),H=(0,a.useCallback)(async e=>{let t=e.trim();if(0!==t.length){f(void 0);try{let e=await (0,w.createProject)({path:t}),n=await (0,w.fetchProjects)();l(e=>({...e,projects:Array.from(n.projects)})),await _(e.project)}catch(e){f(nO(e))}}},[_]),Y=(0,a.useCallback)(e=>{l(t=>({...t,messages:t.messages.filter(t=>t.id!==e)}))},[]),J=(0,a.useCallback)((e,t,n)=>{let a=!1;return{onToken:t=>{a||(K("streaming"),a=!0),l(n=>({...n,messages:n.messages.map(n=>n.id===e?{...n,content:n.content+t}:n)}))},onDone:a=>{l(n=>({...n,activeChat:a.chat,chats:nK([a.chat,...n.chats.filter(e=>e.id!==a.chat.id)]),messages:[...n.messages.filter(n=>n.id!==t&&n.id!==e),...Array.from(a.messages)]})),nB(a.chat),void 0!==a.memory&&x(a.memory),n("completed")},onError:({code:t,message:a})=>{f(nO(new w.ApiError(t,a,0))),Y(e),n("failed")},onCancelled:()=>{Y(e),n("cancelled")}}},[Y,K]),G=(0,a.useCallback)((e,t,n,a,s,i,r)=>{let o=`stream-${String(Date.now())}`;l(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:s,memory:D(e,t),...r.length>0?{documentContext:r}:{}};return new Promise((e,t)=>{let n=J(o,a,e);(0,w.sendDesktopChatStream)(c,i,n).catch(n=>{Y(o),n instanceof w.StreamingUnavailableError?t(n):n instanceof DOMException&&"AbortError"===n.name?e("cancelled"):(f(nO(n)),l(e=>({...e,messages:e.messages.filter(e=>e.id!==a)})),e("failed"))})})},[D,J,Y]),V=(0,a.useCallback)(async(e,t,n,a,s,i,r)=>{try{K("contacting");let o=await (0,w.sendDesktopChat)({chatId:e.id,projectPath:t.path,content:n,modelId:s,memory:D(e,t),...r.length>0?{documentContext:r}:{}},i);if(i.aborted)return"cancelled";return l(e=>({...e,activeChat:o.chat,chats:nK([o.chat,...e.chats.filter(e=>e.id!==o.chat.id)]),messages:[...e.messages.filter(e=>e.id!==a),...Array.from(o.messages)]})),nB(o.chat),x(o.memory),"completed"}catch(n){if(n instanceof DOMException&&"AbortError"===n.name)return"cancelled";f(nO(n));try{let n=await (0,w.fetchChatMessages)(e.id,t.path);l(e=>({...e,messages:Array.from(n.messages)}))}catch{l(e=>({...e,messages:e.messages.filter(e=>e.id!==a)}))}return"failed"}},[D,K]),X=(0,a.useCallback)(async(e,t,a,l,s,i,r)=>{if(n.models.find(e=>e.id===s)?.streaming!==!0)return V(e,t,a,l,s,i,r);K("contacting");try{return await G(e,t,a,l,s,i,r)}catch(e){if(!(e instanceof w.StreamingUnavailableError))throw e}return V(e,t,a,l,s,i,r)},[n.models,V,G,K]),Q=(0,a.useCallback)(async(e,t,n,a,s,i)=>{v(void 0);try{K("contacting");let t=await (0,w.askGrounded)({chatId:e.id,content:n,modelId:s},i);if(S.current!==e.id)return"completed";if(i.aborted)return"cancelled";v(t),x(void 0);let[a,r]=await Promise.all([(0,w.fetchChatMessages)(e.id,e.projectPath),(0,w.fetchChats)(e.projectPath)]),o=r.chats.find(t=>t.id===e.id);return l(e=>({...e,messages:Array.from(a.messages),chats:nK(r.chats),activeChat:o??e.activeChat})),void 0!==o&&nB(o),"completed"}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return"cancelled";return f(nO(e)),l(e=>({...e,messages:e.messages.filter(e=>e.id!==a)})),"failed"}},[K]),Z=(0,a.useCallback)(()=>{nM(m.current)&&(h.current?.abort(),h.current=null,K("cancelled"))},[K]),ee=(0,a.useCallback)(async()=>{if(nM(m.current))return;let e=s.trim(),t=n.activeChat,a=n.activeProject,r=nU(n.selectedModel,n.models);if(0===e.length||void 0===t||void 0===a||void 0===r)return;if(nz(ni({modelContextWindow:n.models.find(e=>e.id===r)?.contextWindow??0,modelMaxOutputTokens:n.models.find(e=>e.id===r)?.maxOutputTokens??0,userDraftText:e,conversationHistory:n.messages.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.content}))})))return void f(nL);if(nW(t)&&E.length>0)return void f("Attachments are not supported for grounded chats. Remove the attachment or switch to a non-grounded chat.");let o={id:`local-${String(Date.now())}`,chatId:t.id,role:"user",content:e,timestamp:Date.now(),runId:void 0,workflowId:void 0,workflowStatus:void 0,shortResult:void 0,taskType:void 0};K("queued"),i(""),f(void 0),l(e=>({...e,messages:[...e.messages,o]}));let c=new AbortController;h.current=c,x(void 0);try{let n=nW(t),{entries:l,disclosures:s}=n?{entries:[],disclosures:[]}:await q(),i=n?await Q(t,a,e,o.id,r,c.signal):await X(t,a,e,o.id,r,c.signal,l);"cancelled"===m.current||K(i),"completed"===i&&(L(),T(s))}finally{h.current=null}},[s,n.activeChat,n.activeProject,n.selectedModel,n.models,n.messages,E,Q,X,q,L,K]),et=(0,a.useCallback)(()=>{v(void 0),x(void 0),l(e=>({...e,messages:[]}))},[]),en=(0,a.useMemo)(()=>{let e=n.models.find(e=>e.id===n.selectedModel);if(void 0===e)return;let t=n.messages.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.content})),a=0,l=0;void 0!==g&&(("connected-context"===g.groundingKind||"hybrid"===g.groundingKind)&&(a=("hybrid"===g.groundingKind?g.contextPack.folder:g.contextPack).usage.excerptBytes),("local-knowledge"===g.groundingKind||"hybrid"===g.groundingKind)&&(l=4*("hybrid"===g.groundingKind?g.contextPack.knowledge:g.contextPack).referenceBudget));let i=y&&void 0!==b&&b.context.enabled?b.context.text.length:0;return ni({modelContextWindow:e.contextWindow,modelMaxOutputTokens:e.maxOutputTokens,userDraftText:s,conversationHistory:t,repoContextPackBytes:a,knowledgeCapsuleBytes:l,memoryContextBytes:i})},[n.models,n.selectedModel,n.messages,s,g,b,y]),ea=(0,a.useCallback)(async e=>{if(nM(m.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 a=n.activeChat,s=n.activeProject;if(void 0===a||void 0===s)return{ok:!1,reason:"missing-chat"};let i=n.models.find(t=>t.id===e.modelId);if(void 0===i||!tD(i))return{ok:!1,reason:"not-workflow-eligible"};let r=na(e.workflowId);if(void 0===r)return{ok:!1,reason:"unknown-workflow"};let o=Date.now(),c=r.buildInput(s.path,t);try{let n=await (0,w.startChatRun)({chatId:a.id,projectPath:s.path,run:{workflowId:e.workflowId,input:c,modelId:e.modelId},user:{content:t,timestamp:o},summary:{content:`Launched: ${r.label}`,timestamp:o+1}});return l(e=>({...e,messages:Array.from(n.messages)})),{ok:!0,runId:n.run.runId}}catch(t){let e=nO(t);return f(e),{ok:!1,reason:"request-failed",message:e}}},[n.activeChat,n.activeProject,n.models]),el=(0,a.useCallback)(async e=>{if(nM(m.current))return{ok:!1,reason:"request-failed",message:"A request is already in flight."};if(void 0===n.activeChat)return{ok:!1,reason:"missing-chat"};if(0===e.modelId.trim().length)return{ok:!1,reason:"missing-model"};try{let t=await (0,w.startGroundedWorkflowHandoff)({assistantMessageId:e.assistantMessageId,chatId:n.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 l(e=>({...e,messages:Array.from(t.messages)})),{ok:!0,runId:t.run.runId}}catch(t){let e=nO(t);return f(e),{ok:!1,reason:"request-failed",message:e}}},[n.activeChat]),es=(0,a.useCallback)(e=>{nB(e),l(t=>({...t,chats:t.chats.map(t=>t.id===e.id?e:t),activeChat:t.activeChat?.id===e.id?e:t.activeChat}))},[]),ei=(0,a.useCallback)(()=>{f(void 0)},[]);return{projects:n.projects,chats:n.chats,messages:n.messages,models:n.models,activeProject:n.activeProject,activeChat:n.activeChat,selectedModel:n.selectedModel,noEligibleModels:!r&&void 0===nU(n.selectedModel,n.models),draft:s,loading:r,sending:u,sendStatus:c,error:p,clearError:ei,setDraft:i,setSelectedModel:B,openNewChat:_,openProject:U,openChat:W,addProject:H,sendMessage:ee,cancelSend:Z,replaceChat:es,latestGrounded:g,cancelGrounded:Z,pendingAttachments:E,addPendingAttachment:A,removePendingAttachment:M,clearPendingAttachments:L,lastSentDocuments:$,budget:en,memoryEnabled:y,setMemoryEnabled:j,memoryBudgetTokens:k,setMemoryBudgetTokens:N,latestMemory:b,clearLatestMemory:P,acceptMemoryCandidate:F,rejectMemoryCandidate:z,forgetMemoryAction:O,clearHistory:et,launchWorkflowFromConversation:ea,launchGroundedWorkflowHandoff:el}}let nG="keiko.theme",nV="dark";var nX=e.i(66702);let nQ=["agent","capsule","capsule-set","chat","connector","data-source","evidence-run","mcp-tool","memory","patch-proposal","skill","tool","workflow-run","workspace-path"],nZ=["capsule","capsule-set","chat","evidence-run","memory","patch-proposal","tool","workflow-run","workspace-path"],n0=["reads-context","proposes-patch","uses-tool","starts-workflow","produces-evidence","references-document","depends-on"],n1=["draft","active","archived","superseded","revoked","blocked","stale"],n2={"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"}},n4=["prompt","documentcontent","filecontent","toolstdout","toolstderr","secret","credential","apikey","password","token"],n3="Unable to reach the local backend. Check that the Keiko server is running (keiko ui).";class n6 extends Error{code;status;reasons;constructor(e,t,n,a=[]){super(t),this.name="RelationshipApiError",this.code=e,this.status=n,this.reasons=a}}async function n5(e){let t;try{t=await e.json()}catch{throw new n6("relationship/parse-error","Response is not valid JSON.",e.status)}if(!e.ok){let n=t,a=n.error??n,l="string"==typeof a.code?a.code:"relationship/unknown-error",s="string"==typeof a.message?a.message:"An unknown error occurred.",i=Array.isArray(n.reasons)?n.reasons:[];throw new n6(l,s,e.status,i)}return t}function n8(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 n7(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:n8({}),body:JSON.stringify(t)});return{decision:(await n5(n)).decision}}async function n9(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}:{}}},a=await fetch("/api/relationships",{method:"POST",headers:n8({idempotencyKey:t}),body:JSON.stringify(n)}),l=await n5(a);return{relationship:l.relationship,etag:l.etag}}async function ae(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()}`),a=await n5(n);return{entries:a.entries,truncated:a.truncated,nextCursor:a.nextCursor}}async function at(e){let t=await fetch(`/api/relationships/${encodeURIComponent(e)}`);return(await n5(t)).relationship}async function an(e,t,n,a){let l=await fetch(`/api/relationships/${encodeURIComponent(e)}`,{method:"PATCH",headers:n8({idempotencyKey:a,ifMatch:n}),body:JSON.stringify({schemaVersion:"1",...t})}),s=await n5(l);return{relationship:s.relationship,etag:s.etag}}async function aa(e,t,n){let a=await fetch(`/api/relationships/${encodeURIComponent(e)}`,{method:"DELETE",headers:n8({idempotencyKey:n,ifMatch:t})});return(await n5(a)).relationship}async function al(e,t={}){let 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 a=await fetch(`/api/relationships/${encodeURIComponent(e)}/dependencies?${n.toString()}`);return(await n5(a)).report}async function as(e){return n5(await fetch(`/api/relationships/${encodeURIComponent(e)}/explain`))}async function ai(){return n5(await fetch("/api/relationships/health"))}let ar=[{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 ao(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 ac(e){let t=[...e.mod].sort();return`${t.join("+")}|${e.key.toLowerCase()}`}let ad={undoStack:[],redoStack:[]};class au extends Error{conflicts;constructor(e){super(`Workspace keyboard shortcut conflicts detected: ${e.map(e=>`${ac(e.chord)} (${e.commandIds.join(", ")})`).join("; ")}`),this.name="WorkspaceShortcutConflictError",this.conflicts=e}}class am extends Error{reserved;constructor(e){super(`Workspace keyboard shortcut bindings refused: ${e.map(e=>`${e.commandId} → ${ac(e.chord)}`).join("; ")} are browser-reserved`),this.name="WorkspaceShortcutReservedError",this.reserved=e}}let ah=[{commandId:"undo",chord:{key:"z",mod:["cmd"]}},{commandId:"redo",chord:{key:"z",mod:["cmd","shift"]}},{commandId:"focus-status",chord:{key:"s",mod:["alt"]}}];var ap=e.i(57688);let af="cmp-budget-exceeded-alert",ag={low:"Low",moderate:"Moderate",high:"High",exceeded:"Exceeded"},av={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"},ab="Token counts are approximate. Actual model usage may vary.";function ax(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toString()}function ay({budget:e,onClearHistory:t,disabled:l}){let[s,i]=(0,a.useState)(!1),[r,o]=(0,a.useState)(!1),c=(0,a.useRef)(null),d=(0,a.useRef)(null);if((0,a.useEffect)(()=>{s&&c.current?.focus()},[s]),void 0===e)return null;let u=e.contextWindowTokens>0,m=ax(e.approximateTokens),h=ax(e.contextWindowTokens),p=e.pressure,f=u&&"exceeded"===p;return(0,n.jsxs)("div",{className:"cmp-budget","data-pressure":u?p:"unknown",children:[(0,n.jsxs)("div",{className:"cmp-budget-row",children:[(0,n.jsx)("span",{className:"cmp-budget-count",children:u?`Approximate context: ${m} / ${h} tokens`:`Approximate context: ${m} tokens`}),u?(0,n.jsx)("span",{className:av[p],"aria-label":`Context pressure: ${ag[p]}`,children:ag[p]}):null,(0,n.jsx)("span",{className:"cmp-budget-info",role:"img",tabIndex:0,"aria-label":ab,"data-tip":ab,children:"i"}),s?(0,n.jsxs)("span",{className:"cmp-budget-confirm",children:[(0,n.jsx)("span",{className:"cmp-budget-confirm-label",id:"cmp-budget-confirm-label",children:"Clear history?"}),(0,n.jsx)("button",{type:"button",ref:c,className:"cmp-budget-clear","aria-describedby":"cmp-budget-confirm-label",onClick:function(){t(),i(!1),o(!0),requestAnimationFrame(()=>d.current?.focus())},children:"Clear"}),(0,n.jsx)("button",{type:"button",className:"cmp-budget-clear",onClick:function(){i(!1),requestAnimationFrame(()=>d.current?.focus())},children:"Cancel"})]}):(0,n.jsx)("button",{type:"button",ref:d,className:"cmp-budget-clear","aria-label":"Clear conversation history for next prompt",onClick:()=>{o(!1),i(!0)},disabled:!0===l,children:"Clear history"}),r?(0,n.jsx)("span",{role:"status",className:"cmp-budget-cleared",children:"History cleared for the next prompt — messages remain saved."}):null]}),f?(0,n.jsx)("div",{id:af,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 aw({notice:e,className:t="ui-error-notice",id:l,onDismiss:s}){let i=`${e.title}
105
+ ${e.message}
106
+ ${e.code??""}
107
+ ${e.remediation??""}`,[r,o]=(0,a.useState)();return r===i?null:(0,n.jsxs)("div",{id:l,className:t,role:"alert","aria-live":"assertive",children:[(0,n.jsxs)("div",{className:"ui-error-notice-title-row",children:[(0,n.jsx)("div",{className:"ui-error-notice-title",children:e.title}),(0,n.jsx)("button",{type:"button",className:"ui-error-notice-close","aria-label":"Dismiss error",title:"Dismiss error",onClick:()=>{o(i),s?.()},children:(0,n.jsx)(j.Icons.close,{size:14})})]}),(0,n.jsx)("div",{className:"ui-error-notice-message",children:e.message}),void 0!==e.remediation?(0,n.jsx)("div",{className:"ui-error-notice-remediation",children:e.remediation}):null,void 0!==e.code?(0,n.jsx)("div",{className:"ui-error-notice-code mono",children:e.code}):null]})}function aj({error:e,fallback:t,className:a,id:l,onDismiss:s}){return(0,n.jsx)(aw,{id:l,className:a,notice:function(e,t){var n;let a;if(e instanceof w.ApiError){let n=nu(e.message.trim())||t;return{title:np(n,e.code),message:n,code:e.code,remediation:nf(n,e.code)}}let l=(n=nu(("string"==typeof e?e.trim():e instanceof Error?e.message.trim():"")||t),null===(a=nd.exec(n))?{message:n,code:void 0}:{message:n.slice(0,a.index).trim(),code:a[1]});return{title:np(l.message,l.code),message:l.message,code:l.code,remediation:nf(l.message,l.code)}}(e,t),onDismiss:s})}var ak=e.i(83449);function aN(e){return Number.isFinite(e)?String(e):"—"}function aS(e,t){return Number.isFinite(e)?t(e):"—"}function aC(e){return e.toLocaleString("en-US")}function aI(e){return e.replaceAll("-"," ")}function aE({label:e,value:t}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("dt",{className:"grounded-context-pack-dt",children:e}),(0,n.jsx)("dd",{className:"grounded-context-pack-dd",children:t})]})}function aR({contextPack:e}){let{usage:t,budget:a}=e,l=function(e){if("workspace-root"===e.scopeKind)return"workspace root";let t=e.scopeId.slice(-8);return`${aI(e.scopeKind)} (${t})`}(e),s="files"===e.scopeKind?`Scope: ${String(e.fileCount)} file${1===e.fileCount?"":"s"} in ${l}`:`Scope: ${l}`;return(0,n.jsxs)("section",{className:"grounded-context-pack","aria-label":"Context inspection summary",children:[(0,n.jsx)("div",{className:"grounded-context-pack-headline",children:s}),(0,n.jsxs)("dl",{className:"grounded-context-pack-dl",children:[(0,n.jsx)(aE,{label:"Searched",value:`${String(t.searchCalls)} / ${aN(a.searchCallsMax)} searches`}),(0,n.jsx)(aE,{label:"Read",value:`${String(t.filesRead)} / ${aN(a.filesReadMax)} files`}),(0,n.jsx)(aE,{label:"Bytes",value:`${(0,ak.formatBytes)(t.excerptBytes)} / ${aS(a.excerptBytesMax,ak.formatBytes)}`}),(0,n.jsx)(aE,{label:"Input",value:`${aC(t.modelInputTokens)} / ${aS(a.modelInputTokensMax,aC)} tokens`}),(0,n.jsx)(aE,{label:"Output",value:`${aC(t.modelOutputTokens)} / ${aS(a.modelOutputTokensMax,aC)} tokens`}),(0,n.jsx)(aE,{label:"Rerank",value:`${String(t.rerankCalls)} / ${aN(a.rerankCallsMax)} calls`}),(0,n.jsx)(aE,{label:"Time",value:`${(0,ak.formatMs)(e.elapsedMs)} / ${aS(a.elapsedMsMax,ak.formatMs)}`}),(0,n.jsx)(aE,{label:"Query",value:aI(e.queryKind)})]})]})}function a$({score:e}){return(0,n.jsxs)("span",{className:"grounded-citation-score",children:[(0,n.jsx)("span",{className:"sr-only",children:"relevance "}),e.toFixed(2)]})}function aT({citation:e}){let t;return(0,n.jsxs)("span",{className:"grounded-citation",title:(t=`relevance ${e.score.toFixed(2)}`,void 0===e.lineRange?`Evidence citation in ${e.scopePath} — ${t}`:`Evidence citation in ${e.scopePath} at lines ${String(e.lineRange.startLine)}-${String(e.lineRange.endLine)} — ${t}`),children:[(0,n.jsx)("span",{children:void 0===e.lineRange?e.scopePath:`${e.scopePath}:${String(e.lineRange.startLine)}-${String(e.lineRange.endLine)}`}),(0,n.jsx)(a$,{score:e.score})]})}function aA(e){let t=new Set,n=[];for(let a of e)t.has(a.stableId)||(t.add(a.stableId),n.push(a));return n}function aM({total:e,expanded:t,onToggle:a}){return e<=8?null:(0,n.jsx)("button",{type:"button",className:"grounded-citations-more","aria-expanded":t,onClick:a,children:t?"Show fewer sources":`Show all ${String(e)} sources`})}function aL({citations:e}){let[t,l]=(0,a.useState)(!1);if(0===e.length)return null;let s=aA([...e].sort((e,t)=>t.score-e.score)),i=t?s:s.slice(0,8);return(0,n.jsxs)("div",{className:"grounded-citations-wrap",children:[(0,n.jsx)("span",{className:"grounded-citations-label",children:"Evidence"}),(0,n.jsx)("ul",{className:"grounded-citations","aria-label":"Evidence citations",children:i.map(e=>(0,n.jsx)("li",{className:"grounded-citations-item",children:(0,n.jsx)(aT,{citation:e})},e.stableId))}),(0,n.jsx)(aM,{total:s.length,expanded:t,onToggle:()=>{l(e=>!e)}})]})}function aq({citations:e}){let[t,l]=(0,a.useState)(!1);if(0===e.length)return null;let s=aA([...e].sort((e,t)=>t.score-e.score)),i=t?s:s.slice(0,8);return(0,n.jsxs)("div",{className:"grounded-citations-wrap",children:[(0,n.jsx)("span",{className:"grounded-citations-label",children:"Knowledge citations"}),(0,n.jsx)("ul",{className:"grounded-citations","aria-label":"Knowledge citations",children:i.map(e=>(0,n.jsx)("li",{className:"grounded-citations-item",children:(0,n.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,n.jsx)("span",{children:void 0===e.source?`${e.marker} ${e.label}`:`${e.marker} ${e.source} \xb7 ${e.label}`}),(0,n.jsx)(a$,{score:e.score})]})},e.stableId))}),(0,n.jsx)(aM,{total:s.length,expanded:t,onToggle:()=>{l(e=>!e)}})]})}function aP({markers:e}){if(0===e.length)return null;let t=Array.from(new Set(e.map(e=>aI(e.kind)))).join(", ");return(0,n.jsxs)("div",{className:"grounded-uncertainty",role:"note",children:[(0,n.jsx)("div",{children:`Uncertainty (${String(e.length)} markers — ${t})`}),(0,n.jsx)("ul",{className:"grounded-uncertainty-list",children:e.map((e,t)=>(0,n.jsx)("li",{children:`${aI(e.kind)}: ${e.claim}`},`${e.kind}-${String(t)}`))})]})}function aD({omittedCount:e,omittedCounts:t}){if(e<=0)return null;let a=Object.entries(t).filter(([,e])=>e>0).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>`${aI(e)}: ${String(t)}`).join(", "),l=a.length>0?` (${a})`:"";return(0,n.jsx)("div",{className:"grounded-meta",children:`Not used: ${String(e)} excerpt${1===e?"":"s"}${l}`})}let aF=[{reason:"size-exceeded",label:"larger than 2 MB"},{reason:"binary",label:"binary or an unsupported format"},{reason:"tool-unavailable",label:"unreadable"}];function az({omittedCounts:e}){let t=aF.map(({reason:t,label:n})=>({label:n,count:e[t]})).filter(e=>e.count>0),a=t.reduce((e,t)=>e+t.count,0);if(a<=0)return null;let l=t.map(e=>`${String(e.count)} ${e.label}`).join(", ");return(0,n.jsxs)("div",{className:"grounded-coverage-notice",role:"note",children:[(0,n.jsx)("span",{className:"grounded-coverage-notice-title",children:"Partial coverage"}),(0,n.jsx)("span",{children:`This answer reflects only the searchable files in the connected scope — ${String(a)} ${1===a?"file":"files"} ${1===a?"was":"were"} not searched (${l}). It does not cover the entire folder.`}),e.binary>0?(0,n.jsx)("span",{children:"Some connected files were skipped because Repository Search currently reads text/code files only."}):null]})}function aO({runId:e,runIds:t}){let a=Array.from(new Set([...void 0===e?[]:[e],...t??[]]));return 0===a.length?null:(0,n.jsx)("div",{className:"grounded-meta",children:a.map((e,t)=>(0,n.jsxs)("a",{className:"sm-link",href:`/api/evidence/${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",children:[1===a.length?"View connected-context audit evidence":`View connected-context audit evidence ${String(t+1)}`," ",(0,n.jsx)("span",{className:"sr-only",children:"(opens in new tab)"})]},e))})}function aK({contextPack:e}){return(0,n.jsxs)("section",{className:"grounded-context-pack","aria-label":"Knowledge scope summary",children:[(0,n.jsx)("div",{className:"grounded-context-pack-headline",children:`Knowledge scope: ${e.scopeLabel}`}),(0,n.jsxs)("dl",{className:"grounded-context-pack-dl",children:[(0,n.jsx)(aE,{label:"Mode",value:aI(e.scopeKind)}),(0,n.jsx)(aE,{label:"Capsules",value:String(e.capsuleCount)}),(0,n.jsx)(aE,{label:"Sources",value:String(e.sourceCount)}),(0,n.jsx)(aE,{label:"Citations",value:String(e.citationCount)}),(0,n.jsx)(aE,{label:"Context budget",value:`${String(e.referencesUsed)} / ${String(e.referenceBudget)} references`})]})]})}function aB({contextPack:e}){return(0,n.jsxs)("section",{className:"grounded-context-pack","aria-label":"Hybrid source summary",children:[(0,n.jsx)("div",{className:"grounded-context-pack-headline",children:`Hybrid: ${String(e.folderSourceCount)} folder source${1===e.folderSourceCount?"":"s"} + ${String(e.connectorSourceCount)} connector source${1===e.connectorSourceCount?"":"s"}`}),(0,n.jsx)(aR,{contextPack:e.folder}),(0,n.jsx)(aK,{contextPack:e.knowledge})]})}function a_({answer:e,busy:t}){return void 0===e?t?(0,n.jsx)("div",{className:"grounded-meta",children:"Searching connected sources and asking Keiko…"}):null:"local-knowledge"===e.groundingKind?(0,n.jsxs)("div",{className:"grounded-answer",children:[(0,n.jsx)(aq,{citations:e.citations}),(0,n.jsx)(aP,{markers:e.uncertainty}),(0,n.jsx)(aK,{contextPack:e.contextPack})]}):"hybrid"===e.groundingKind?(0,n.jsxs)("div",{className:"grounded-answer",children:[(0,n.jsx)(az,{omittedCounts:e.contextPack.folder.omittedCounts}),(0,n.jsx)(aL,{citations:e.citations}),(0,n.jsx)(aq,{citations:e.knowledgeCitations}),(0,n.jsx)(aP,{markers:e.uncertainty}),(0,n.jsx)(aD,{omittedCount:e.omittedCount,omittedCounts:e.contextPack.folder.omittedCounts}),(0,n.jsx)(aO,{runId:e.evidenceRunId,runIds:e.evidenceRunIds}),(0,n.jsx)(aB,{contextPack:e.contextPack})]}):(0,n.jsxs)("div",{className:"grounded-answer",children:[(0,n.jsx)(az,{omittedCounts:e.contextPack.omittedCounts}),(0,n.jsx)(aL,{citations:e.citations}),(0,n.jsx)(aP,{markers:e.uncertainty}),(0,n.jsx)(aD,{omittedCount:e.omittedCount,omittedCounts:e.contextPack.omittedCounts}),(0,n.jsx)(aO,{runId:e.evidenceRunId,runIds:e.evidenceRunIds}),(0,n.jsx)(aR,{contextPack:e.contextPack})]})}var aU=a;let aW=["<script","</script","<iframe","</iframe","<object","</object","<embed","</embed","<style","</style","<svg","</svg","<form","</form","<meta","<link","<base"],aH=[" ","\n"," ","'",'"'];function aY(e){let t=function(e){let t=e.toLowerCase().replaceAll("\0",""),n="";for(let e=0;e<t.length;e++){let a=t[e]??"";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 aW)if(t.includes(e))return!0;let n=0;for(;n<t.length-4;){let e=t[n];if(aH.includes(e)&&"o"===t[n+1]&&"n"===t[n+2]){let e=n+3;for(;e<t.length&&/[a-z]/.test(t[e]??"");)e++;if(e<t.length&&"="===t[e])return!0}n++}return!1}function aJ(e,t,n,a){a>n&&e.push({kind:"text",text:t.slice(n,a)})}function aG(e){return void 0!==e&&/[A-Za-z0-9]/.test(e)}let aV=new Set([" "," ","\n","<",">",'"']),aX=new Set([".",",",")","]","!","?"]);function aQ(e,t=0){if(t>=16)return e.length>0?[{kind:"text",text:e}]:[];let n=[],a=0,l=0;for(;a<e.length;){let s=function(e,t,n,a){if("`"!==t[n])return -1;let l=t.indexOf("`",n+1);return -1===l?-1:(aJ(e,t,a,n),e.push({kind:"inline-code",text:t.slice(n+1,l)}),l+1)}(n,e,a,l);if(-1!==s||-1!==(s=function(e,t,n,a,l){let s=t[n],i=t[n+1];if(n+1>=t.length||("*"!==s||"*"!==i)&&("_"!==s||"_"!==i))return -1;let r=t.indexOf(s+i,n+2);if(-1===r)return -1;aJ(e,t,a,n);let o=t.slice(n+2,r);return e.push({kind:"strong",children:aQ(o,l+1)}),r+2}(n,e,a,l,t))||-1!==(s=function(e,t,n,a,l){let s=t[n];if("*"!==s&&"_"!==s||"_"===s&&aG(t[n-1])&&aG(t[n+1])||t[n+1]===s||n>0&&t[n-1]===s)return -1;let i=function(e,t,n){for(let a=n;a<e.length;a++)if(e[a]===t&&e[a-1]!==t&&(a+1>=e.length||e[a+1]!==t))return a;return -1}(t,s,n+1);return -1===i||"_"===s&&aG(t[i-1])&&aG(t[i+1])?-1:(aJ(e,t,a,n),e.push({kind:"em",children:aQ(t.slice(n+1,i),l+1)}),i+1)}(n,e,a,l,t))||-1!==(s=function(e,t,n,a){let l;if("["!==t[n])return -1;let s=t.indexOf("]",n+1);if(-1===s||"("!==t[s+1])return -1;let i=t.indexOf(")",s+2);if(-1===i)return -1;let r=t.slice(n+1,s),o=t.slice(s+2,i);return aJ(e,t,a,n),((l=o.trim().toLowerCase()).startsWith("http://")||l.startsWith("https://"))&&!aY(r)&&!aY(o)?e.push({kind:"link",text:r,href:o}):e.push({kind:"text",text:`[${r}](${o})`}),i+1}(n,e,a,l))||-1!==(s=function(e,t,n,a){if("h"!==t[n])return -1;let l="https://"===t.slice(n,n+8),s="http://"===t.slice(n,n+7);if(!l&&!s)return -1;let i=function(e,t){let n=t;for(;n<e.length&&!aV.has(e[n]??"");)n++;for(;n>t&&aX.has(e[n-1]??"");)n--;return n}(t,n);if(i-n<=(l?8:7))return -1;let r=t.slice(n,i);return aJ(e,t,a,n),e.push({kind:"link",text:r,href:r}),i}(n,e,a,l))){l=s,a=s;continue}a++}return aJ(n,e,l,e.length),n}function aZ(e){let t=e.trim(),n=t.startsWith(":"),a=t.endsWith(":");return n&&a?"center":a?"right":n?"left":void 0}function a0(e){let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|")}function a1(e){let t=/^( *)([*+\-]) (.*)$/.exec(e);return t?{match:!0,indent:t[1]?.length??0,text:t[3]??""}:{match:!1}}function a2(e){let t=/^( *)\d+\. (.*)$/.exec(e);return t?{match:!0,indent:t[1]?.length??0,text:t[2]??""}:{match:!1}}function a4(e){return e.includes("|")}function a3(e){let t=e.trim();return/^(-{3,}|\*{3,}|_{3,})$/.test(t)}function a6(e,t){let n=[],a=t?a2:a1;for(;e.i<e.lines.length;){let t=e.lines[e.i]??"",l=a(t);if(l.match)n.push({text:l.text,indent:l.indent}),e.i++;else if(""===t.trim())break;else break}return function e(t,n,a){let l=n?"ol":"ul",s=[],i=0;for(;i<t.length;){let l=t[i];if(void 0===l){i++;continue}let r=l.indent,o=[];for(i++;i<t.length;){let e=t[i];if(void 0===e||e.indent<=r)break;o.push(e),i++}let c=[...aQ(l.text)];o.length>0&&a<16?c.push(e(o,n,a+1)):o.length>0&&c.push({kind:"text",text:o.map(e=>e.text).join("\n")}),s.push({kind:"li",children:c})}return{kind:l,children:s}}(n,t,e.depth)}function a5({text:e}){let[t,a]=(0,aU.useState)(!1),[l,s]=(0,aU.useState)(""),i=(0,aU.useCallback)(()=>{"u"<typeof navigator||navigator.clipboard?.writeText===void 0?s("Copy unavailable: the clipboard requires a secure (HTTPS) connection."):navigator.clipboard.writeText(e).then(()=>{a(!0),s("Code copied"),setTimeout(()=>{a(!1),s("")},1500)},()=>{})},[e]);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"sm-code-copy","aria-label":t?"Copied":"Copy code block",title:t?"Copied":"Copy code block","data-copied":t?"true":"false",onClick:i,children:t?"Copied":"Copy"}),(0,n.jsx)("span",{role:"status",className:"sr-only",children:l})]})}let a8={1:"h3",2:"h4",3:"h5",4:"h6",5:"h6",6:"h6"},a7={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 a9(e,t){return void 0===e.children?null:e.children.map((e,n)=>le(e,t+"-"+String(n)))}function le(e,t){let a=function(e,t){switch(e.kind){case"paragraph":return(0,n.jsx)("p",{className:"sm-p",children:a9(e,t)},t);case"heading":{let a=e.level??1,l=a8[a],s=a7[a];return(0,n.jsx)(l,{className:s,children:a9(e,t)},t)}case"blockquote":return(0,n.jsx)("blockquote",{className:"sm-blockquote",children:a9(e,t)},t);case"hr":return(0,n.jsx)("hr",{className:"sm-hr"},t);case"code-block":{let a=e.language,l=e.text??"",s=void 0!==a?`lang-${a}`:void 0;return(0,n.jsxs)("div",{className:"sm-code-block-frame",children:[(0,n.jsxs)("div",{className:"sm-code-block-header",children:[(0,n.jsx)("span",{className:"sm-code-lang",children:a??"text"}),(0,n.jsx)(a5,{text:l})]}),(0,n.jsx)("pre",{className:"sm-pre",children:(0,n.jsx)("code",{className:s,children:l})})]},t)}default:return null}}(e,t);if(null!==a)return a;let l=function(e,t){switch(e.kind){case"ul":return(0,n.jsx)("ul",{className:"sm-ul",children:a9(e,t)},t);case"ol":return(0,n.jsx)("ol",{className:"sm-ol",children:a9(e,t)},t);case"li":return(0,n.jsx)("li",{className:"sm-li",children:a9(e,t)},t);default:return null}}(e,t);if(null!==l)return l;let s=function(e,t){let a=void 0!==e.align?{textAlign:e.align}:void 0;switch(e.kind){case"table":return(0,n.jsx)("div",{className:"sm-table-wrapper",children:(0,n.jsx)("table",{className:"sm-table",children:a9(e,t)})},t);case"thead":return(0,n.jsx)("thead",{children:a9(e,t)},t);case"tbody":return(0,n.jsx)("tbody",{children:a9(e,t)},t);case"tr":return(0,n.jsx)("tr",{children:a9(e,t)},t);case"th":return(0,n.jsx)("th",{style:a,children:a9(e,t)},t);case"td":return(0,n.jsx)("td",{style:a,children:a9(e,t)},t);default:return null}}(e,t);if(null!==s)return s;let i=function(e,t){switch(e.kind){case"text":return(0,n.jsx)("span",{children:e.text},t);case"inline-code":return(0,n.jsx)("code",{className:"sm-inline-code",children:e.text},t);case"link":return(0,n.jsxs)("a",{href:e.href,className:"sm-link",rel:"noopener noreferrer",target:"_blank",children:[e.text,(0,n.jsx)("span",{className:"sr-only",children:" (opens in new tab)"})]},t);case"strong":return(0,n.jsx)("strong",{children:a9(e,t)},t);case"em":return(0,n.jsx)("em",{children:a9(e,t)},t);default:return null}}(e,t);return null!==i?i:null}function lt({source:e}){let t=function e(t,n){let a=[],l={lines:t.split("\n"),i:0,depth:n};for(;l.i<l.lines.length;)!function(t,n){let a=t.lines[t.i]??"";if(""===a.trim())return t.i++;if(function(e,t,n){let a=/^(`{3,}|~{3,})(\S*)/.exec(t.trim());if(null===a)return!1;let l=a[1]??"```",s=a[2],i=void 0!==s&&s.length>0?s:void 0;return n.push(function(e,t,n){let a=[];for(e.i++;e.i<e.lines.length;){let n=e.lines[e.i]??"",l=/^(`{3,}|~{3,})\s*$/.exec(n.trim());if(null!==l){let n=l[1]??"";if(n.startsWith(t[0]??"")&&n.length>=t.length){e.i++;break}}a.push(n),e.i++}let l={kind:"code-block",text:a.join("\n")};return void 0!==n?{...l,language:n}:l}(e,l,i)),!0}(t,a,n)||function(e,t,n){let a=/^(#{1,6}) (.+)$/.exec(t.trim());if(null===a)return!1;let l=Math.min((a[1]??"").length,6),s=a[2]??"";return n.push({kind:"heading",level:l,children:aQ(s)}),e.i++,!0}(t,a,n))return;if(a3(a)){n.push({kind:"hr"}),t.i++;return}if(a.trimStart().startsWith("> ")||">"===a.trim())return n.push(function(t){let n=[];for(;t.i<t.lines.length;){let e=t.lines[t.i]??"";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(a4(a.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}(a0(t.lines[t.i+1]??""))&&(n.push(function(e,t){let n,a;e.i++;let l=e.lines[e.i]??"",s=[];for(e.i++;e.i<e.lines.length;){let t=e.lines[e.i]??"";if(""===t.trim()||!a4(t.trim()))break;s.push(t),e.i++}return n=a0(t),a=a0(l).map(aZ),{kind:"table",children:[{kind:"thead",children:[{kind:"tr",children:n.map((e,t)=>{var n;let l;return n=a[t],l={kind:"th",children:aQ(e.trim())},void 0!==n?{...l,align:n}:l})}]},{kind:"tbody",children:s.map(e=>({kind:"tr",children:a0(e).map((e,t)=>{var n;let l;return n=a[t],l={kind:"td",children:aQ(e.trim())},void 0!==n?{...l,align:n}:l})}))}]}}(t,a)),1)||(a1(a).match?(n.push(a6(t,!1)),!0):!!a2(a).match&&(n.push(a6(t,!0)),!0)))return;let l=function(e){let t=[];for(;e.i<e.lines.length;){let n=e.lines[e.i]??"";if(function(e){let t=e.trim();return!!(""===t||/^#{1,6} /.test(t)||e.trimStart().startsWith("> ")||/^(`{3,}|~{3,})/.test(t))||!!a1(e).match||!!a2(e).match||a3(e)}(n))break;t.push(n),e.i++}return 0===t.length?null:{kind:"paragraph",children:aQ(t.join(" "))}}(t);null!==l&&n.push(l)}(l,a);return a}(e,0);return(0,n.jsx)("div",{className:"sm-root",children:t.map((e,t)=>le(e,String(t)))})}class ln extends aU.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}render(){return this.state.failed?(0,n.jsx)("div",{className:"sm-root sm-fallback","data-markdown-fallback":"true",children:this.props.source}):(0,n.jsx)(lt,{source:this.props.source})}}function la({attachment:e,onRemove:t}){var a;let l=`Remove attachment ${e.name}`,s=function(e,t=32){if(e.length<=t)return e;let n=e.lastIndexOf(".");if(n>0&&e.length-n<=8){let a=e.slice(n);return`${e.slice(0,t-a.length-1)}…${a}`}return`${e.slice(0,t-1)}…`}(e.name);return(0,n.jsxs)("div",{className:"attach-chip",role:"listitem",children:["image"===e.kind&&void 0!==e.previewDataUrl?(0,n.jsx)("img",{src:e.previewDataUrl,alt:"",className:"attach-chip-thumb",width:40,height:40}):(0,n.jsx)("span",{className:"attach-chip-icon","aria-hidden":"true",children:(0,n.jsx)(j.Icons.file,{size:16})}),(0,n.jsx)("span",{className:"attach-chip-name",title:e.name,children:s}),(0,n.jsx)("span",{className:"attach-chip-size",children:(a=e.sizeBytes)<1024?`${String(a)} B`:a<1048576?`${(a/1024).toFixed(1)} KB`:`${(a/1048576).toFixed(1)} MiB`}),(0,n.jsx)("button",{type:"button",className:"attach-chip-remove","aria-label":l,onClick:()=>t(e.id),children:(0,n.jsx)(j.Icons.close,{size:12})})]})}function ll({attachments:e,onRemove:t}){return 0===e.length?null:(0,n.jsx)("div",{className:"attach-strip",role:"list","aria-label":"Pending attachments",children:e.map(e=>(0,n.jsx)(la,{attachment:e,onRemove:t},e.id))})}function ls({enabled:e,onFiles:t}){let[l,s]=(0,a.useState)(!1),[i,r]=(0,a.useState)(!1);(0,a.useEffect)(()=>{if(!e)return;let t=0,n=e=>{Array.from(e.dataTransfer?.types??[]).includes("Files")&&(t+=1,r(!0))},a=()=>{0===(t=Math.max(0,t-1))&&r(!1)},l=()=>{t=0,r(!1)};return window.addEventListener("dragenter",n),window.addEventListener("dragleave",a),window.addEventListener("drop",l),window.addEventListener("dragend",l),()=>{window.removeEventListener("dragenter",n),window.removeEventListener("dragleave",a),window.removeEventListener("drop",l),window.removeEventListener("dragend",l)}},[e]);let o=(0,a.useCallback)(t=>{e&&(t.preventDefault(),s(!0))},[e]),c=(0,a.useCallback)(()=>{s(!1)},[]),d=(0,a.useCallback)(n=>{if(n.preventDefault(),s(!1),!e)return;let a=Array.from(n.dataTransfer.files);a.length>0&&t(a)},[e,t]);return e?(0,n.jsx)("div",{className:"attach-drop-zone","data-dragover":l?"true":void 0,"data-active":i?"true":"false","aria-hidden":"true",onDragOver:o,onDragLeave:c,onDrop:d,children:(0,n.jsx)("span",{className:"attach-drop-hint",children:"Drop files here to attach"})}):null}let li="cmp-attach-disabled-hint";function lr({model:e,onFiles:t,anyModelSupportsAttachments:l=!0}){let s=(0,a.useRef)(null),i=void 0!==e&&(e.supportsImageInput||e.supportsDocumentInput),r=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(",")}(e),o=(0,a.useCallback)(()=>{i&&s.current?.click()},[i]),c=(0,a.useCallback)(()=>{let e=Array.from(s.current?.files??[]);e.length>0&&(t(e),null!==s.current&&(s.current.value=""))},[t]);return(0,n.jsxs)(n.Fragment,{children:[i?null:(0,n.jsx)("span",{id:li,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,n.jsx)("input",{ref:s,type:"file",multiple:!0,accept:r,className:"sr-only",tabIndex:-1,"aria-hidden":"true",onChange:c}),(0,n.jsx)("button",{type:"button",className:"cmp-icon","aria-label":"Attach file","aria-disabled":i?void 0:"true","aria-describedby":i?void 0:li,title:i?"Attach file":"Attachments not supported by this model",onClick:o,children:(0,n.jsx)(j.Icons.files,{size:16})})]})}function lo({reason:e,mimeType:t}){return void 0===e?null:(0,n.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."}}(e,t)})}function lc({documents:e}){if(0===e.length)return null;let t=e.some(e=>e.truncated);return(0,n.jsxs)("div",{role:"note",className:"sent-docs-note","aria-label":"Documents included as context",children:[(0,n.jsx)("span",{className:"sent-docs-note-label",children:1===e.length?"Document included as context:":"Documents included as context:"}),(0,n.jsx)("ul",{className:"sent-docs-note-list",children:e.map(e=>(0,n.jsxs)("li",{className:"sent-docs-note-item",children:[e.displayName,e.truncated?(0,n.jsx)("span",{className:"sent-docs-note-trunc",children:" (truncated)"}):null]},e.id))}),t?(0,n.jsx)("span",{className:"sent-docs-note-hint",children:"Some document text was truncated to fit the context limit."}):null]})}function ld({selectedModel:e,launch:t}){let[l,s]=(0,a.useState)(!1),i=(0,a.useRef)(null);return void 0!==e&&tD(e)?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{ref:i,type:"button",className:"cmp-mode",title:"Launch a governed workflow with the current model","aria-haspopup":"dialog",onClick:()=>s(!0),children:[(0,n.jsx)(j.Icons.spark,{size:14,style:{color:"var(--accent)"}})," Launch workflow",(0,n.jsx)(j.Icons.chevron,{size:12})]}),l?(0,n.jsx)(lm,{modelId:e.id,launch:t,onClose:()=>{s(!1),i.current?.focus()}}):null]}):null}function lu(e){return Array.from(e.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'))}function lm({modelId:e,launch:t,onClose:l}){let s=(0,a.useId)(),i=(0,a.useId)(),[r,o]=(0,a.useState)(),[c,d]=(0,a.useState)(""),[u,m]=(0,a.useState)(!1),[h,p]=(0,a.useState)(),f=(0,a.useRef)(null),g=void 0===r?void 0:na(r);async function v(){if(void 0===g||0===c.trim().length)return;m(!0),p(void 0);let n=await t({workflowId:g.workflowId,modelId:e,text:c});(m(!1),n.ok)?l():p(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."}}(n))}(0,a.useEffect)(()=>{f.current?.focus()},[r]),(0,a.useEffect)(()=>{function e(e){if("Escape"===e.key)return void l();if("Tab"!==e.key)return;let t=f.current;if(null===t)return;let n=lu(t);if(0===n.length){e.preventDefault(),t.focus();return}let a=n[0],s=n[n.length-1],i=document.activeElement;e.shiftKey&&(i===a||i===t)?(e.preventDefault(),s?.focus()):e.shiftKey||i!==s||(e.preventDefault(),a?.focus())}return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[l]);let b=(0,n.jsx)("div",{ref:f,role:"dialog","aria-modal":"true","aria-labelledby":s,tabIndex:-1,className:"wf-dialog-overlay",children:(0,n.jsxs)("div",{className:"wf-dialog",children:[(0,n.jsx)("h2",{id:s,className:"wf-dialog-title",children:"Launch workflow"}),void 0===g?(0,n.jsx)("ul",{className:"wf-dialog-list","aria-label":"Available workflows",children:nn.map(e=>(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button",className:"wf-dialog-choice",onClick:()=>o(e.workflowId),children:[(0,n.jsx)("span",{className:"wf-dialog-choice-label",children:e.label}),(0,n.jsx)("span",{className:"wf-dialog-choice-desc",children:e.description})]})},e.workflowId))}):(0,n.jsxs)("div",{className:"wf-dialog-form",children:[(0,n.jsx)("p",{className:"wf-dialog-form-desc",children:g.description}),(0,n.jsx)("label",{className:"wf-dialog-field",htmlFor:i,children:g.prompt}),(0,n.jsx)("textarea",{id:i,className:"wf-dialog-input mono",rows:3,placeholder:g.placeholder,value:c,onChange:e=>d(e.target.value)}),void 0!==h?(0,n.jsx)("div",{role:"alert",className:"wf-dialog-error",children:h}):null,(0,n.jsxs)("div",{className:"wf-dialog-actions",children:[(0,n.jsx)("button",{type:"button",className:"wf-dialog-cancel",onClick:()=>o(void 0),children:"Back"}),(0,n.jsx)("button",{type:"button",className:"wf-dialog-launch",disabled:u||0===c.trim().length,onClick:()=>{v()},children:u?"Launching…":"Launch"})]})]}),(0,n.jsx)("button",{type:"button",className:"wf-dialog-close","aria-label":"Close launch workflow",onClick:l,children:(0,n.jsx)(j.Icons.close,{size:14})})]})});return"u"<typeof document?b:(0,tA.createPortal)(b,document.body)}let lh=[{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."}],lp=["verify","lint","typecheck","tests","manual"];function lf(e){return e.split(/\r?\n|,/).map(e=>e.trim()).filter(e=>e.length>0)}function lg({answer:e,modelId:t,busy:l,launch:s}){let[i,r]=(0,a.useState)(!1),o=(0,a.useRef)(null),c=(0,a.useId)();if(void 0===e||"connected-context"!==e.groundingKind||void 0===t||e.citations.some(e=>void 0!==e.source))return null;let d=!0===l;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{ref:o,type:"button",className:"cmp-mode",title:"Launch a governed workflow from this grounded answer","aria-haspopup":"dialog","aria-disabled":d||void 0,"aria-describedby":d?c:void 0,onClick:()=>{d||r(!0)},children:[(0,n.jsx)(j.Icons.spark,{size:14,style:{color:"var(--accent)"}})," Launch grounded workflow",(0,n.jsx)(j.Icons.chevron,{size:12})]}),d?(0,n.jsx)("span",{className:"sr-only",id:c,children:"A run is in progress. Wait for it to complete before launching another grounded workflow."}):null,i?(0,n.jsx)(lv,{answer:e,modelId:t,launch:s,onClose:()=>{r(!1),o.current?.focus()}}):null]})}function lv({answer:e,modelId:t,launch:l,onClose:s}){let i=(0,a.useId)(),r=(0,a.useRef)(null),[o,c]=(0,a.useState)(),[d,u]=(0,a.useState)("file"),[m,h]=(0,a.useState)(""),[p,f]=(0,a.useState)(""),[g,v]=(0,a.useState)(""),[b,x]=(0,a.useState)(""),[y,w]=(0,a.useState)(""),[k,N]=(0,a.useState)(""),[S,C]=(0,a.useState)([]),[I,E]=(0,a.useState)(!1),[R,$]=(0,a.useState)();async function T(){if(void 0===o)return;let n=function(e,t,n,a,l,s){if("unit-test-generation"===e){if("changedFiles"===t){let e=lf(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=lf(l),t=a.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 i=lf(s);return{ok:!0,input:0===i.length?{}:{targetFiles:i}}}(o,d,m,p,g,b);if(!n.ok)return void $(n.message);if(0===S.length)return void $("Select at least one expected check.");E(!0),$(void 0);let a=await l({assistantMessageId:e.assistantMessageId,modelId:t,workflowKind:o,input:n.input,editablePaths:lf(y),expectedChecks:S,unknowns:lf(k)});(E(!1),a.ok)?s():$(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,a.useEffect)(()=>{r.current?.focus()},[o]),(0,a.useEffect)(()=>{void 0!==o&&C("unit-test-generation"===o?["tests"]:["verify"])},[o]),(0,a.useEffect)(()=>{function e(e){if("Escape"===e.key)return void s();if("Tab"!==e.key)return;let t=r.current;if(null===t)return;let n=lu(t);if(0===n.length){e.preventDefault(),t.focus();return}let a=n[0],l=n[n.length-1],i=document.activeElement;e.shiftKey&&(i===a||i===t)?(e.preventDefault(),l?.focus()):e.shiftKey||i!==l||(e.preventDefault(),a?.focus())}return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[s]);let A=lh.find(e=>e.workflowKind===o),M=(0,n.jsx)("div",{ref:r,role:"dialog","aria-modal":"true","aria-labelledby":i,tabIndex:-1,className:"wf-dialog-overlay",children:(0,n.jsxs)("div",{className:"wf-dialog",children:[(0,n.jsx)("h2",{id:i,className:"wf-dialog-title",children:"Grounded workflow handoff"}),void 0===A?(0,n.jsx)("ul",{className:"wf-dialog-list","aria-label":"Available grounded workflows",children:lh.map(e=>(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button",className:"wf-dialog-choice",onClick:()=>c(e.workflowKind),children:[(0,n.jsx)("span",{className:"wf-dialog-choice-label",children:e.label}),(0,n.jsx)("span",{className:"wf-dialog-choice-desc",children:e.description})]})},e.workflowKind))}):(0,n.jsxs)("div",{className:"wf-dialog-form",children:[(0,n.jsx)("p",{className:"wf-dialog-form-desc",children:A.description}),"unit-test-generation"===o?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Target mode",(0,n.jsxs)("select",{className:"wf-dialog-input mono",value:d,onChange:e=>u(e.target.value),children:[(0,n.jsx)("option",{value:"file",children:"File"}),(0,n.jsx)("option",{value:"module",children:"Module"}),(0,n.jsx)("option",{value:"changedFiles",children:"Changed files"})]})]}),(0,n.jsxs)("label",{className:"wf-dialog-field",children:["module"===d?"Module directory":"changedFiles"===d?"Changed files (one per line)":"Target file",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:"changedFiles"===d?3:2,value:m,onChange:e=>h(e.target.value),placeholder:"module"===d?"src/components":"changedFiles"===d?"src/a.ts\nsrc/b.ts":"src/example.ts"})]})]}):null,"bug-investigation"===o?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Bug description",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:3,value:p,onChange:e=>f(e.target.value),placeholder:"Describe the failing behavior or regression."})]}),(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Suspected target files (one per line)",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:2,value:g,onChange:e=>v(e.target.value),placeholder:"src/app.ts\\nsrc/lib/foo.ts"})]})]}):null,"verification"===o?(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Target files (optional, one per line)",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:2,value:b,onChange:e=>x(e.target.value),placeholder:"src/app.ts\\nsrc/lib/foo.ts"})]}):null,(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Editable paths (explicit, workspace-relative, one per line)",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:3,value:y,onChange:e=>w(e.target.value),placeholder:"src/example.test.ts"})]}),(0,n.jsxs)("fieldset",{className:"wf-dialog-field",style:{border:0,padding:0,margin:0},children:[(0,n.jsx)("legend",{children:"Expected checks"}),(0,n.jsx)("div",{className:"wf-dialog-form",style:{gap:8},children:lp.map(e=>(0,n.jsxs)("label",{className:"wf-dialog-choice-desc",style:{display:"flex",gap:8},children:[(0,n.jsx)("input",{type:"checkbox",checked:S.includes(e),onChange:()=>{C(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])}}),(0,n.jsx)("span",{children:e})]},e))})]}),(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Unknowns (optional, one per line)",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:2,value:k,onChange:e=>N(e.target.value),placeholder:"Need confirmation on public API behavior"})]}),void 0!==R?(0,n.jsx)("div",{role:"alert",className:"wf-dialog-error",children:R}):null,(0,n.jsxs)("div",{className:"wf-dialog-actions",children:[(0,n.jsx)("button",{type:"button",className:"wf-dialog-cancel",onClick:()=>c(void 0),children:"Back"}),(0,n.jsx)("button",{type:"button",className:"wf-dialog-launch",disabled:I,onClick:()=>{T()},children:I?"Launching…":"Launch"})]})]}),(0,n.jsx)("button",{type:"button",className:"wf-dialog-close","aria-label":"Close grounded workflow handoff",onClick:s,children:(0,n.jsx)(j.Icons.close,{size:14})})]})});return"u"<typeof document?M:(0,tA.createPortal)(M,document.body)}function lb(e){return"system"===e.role&&"string"==typeof e.runId}function lx({message:e}){let t=e.workflowStatus??"queued",l=e.workflowId??e.taskType??"workflow",s=void 0===e.runId?"":e.runId.slice(0,8),[i,r]=(0,a.useState)(""),o=(0,a.useRef)(t);return(0,a.useEffect)(()=>{o.current!==t&&(o.current=t,r(`Workflow ${l}: ${t}`))},[t,l]),(0,n.jsxs)("article",{className:"run-summary-card","data-testid":"run-summary-card","data-status":t,"aria-label":`Workflow run ${l} — ${t}`,children:[(0,n.jsxs)("header",{className:"run-summary-card-head",children:[(0,n.jsx)(j.Icons.spark,{size:14,style:{color:"var(--accent)"}}),(0,n.jsx)("span",{className:"run-summary-card-workflow mono",children:l}),(0,n.jsx)("span",{className:"run-summary-card-status","data-status":t,children:t})]}),(0,n.jsxs)("div",{className:"run-summary-card-body",children:[(0,n.jsx)("p",{className:"run-summary-card-line",children:e.content}),void 0!==e.shortResult&&e.shortResult.length>0?(0,n.jsx)("p",{className:"run-summary-card-result",children:e.shortResult}):null,void 0!==e.runId?(0,n.jsxs)("p",{className:"run-summary-card-meta mono",children:["run"," ",(0,n.jsx)("span",{className:"run-summary-card-runshort","data-runid":e.runId,title:e.runId,children:s})]}):null]}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","data-testid":"run-summary-card-sr",children:i})]})}function ly({on:e,onChange:t,label:a}){return(0,n.jsx)("button",{type:"button",role:"switch","aria-checked":e,"aria-label":a,className:`auto-toggle${e?" on":""}`,onClick:()=>{t(!e)},children:(0,n.jsx)("span",{})})}var lw=e.i(61593);let lj="cmp-no-model-alert",lk="cmp-send-hint",lN="cmp-loading-status",lS="Ask Keiko about your code…",lC="Send message — Enter to send, Shift+Enter for a new line";function lI(e){return t=>{!t.nativeEvent.isComposing&&("Enter"!==t.key||t.shiftKey||(t.preventDefault(),e()))}}let lE=/\s*[[【[]\d+[\]】]]/g;function lR({content:e}){let[t,l]=(0,a.useState)(!1),[s,i]=(0,a.useState)(""),r=(0,a.useCallback)(()=>{"u"<typeof navigator||navigator.clipboard?.writeText===void 0?i("Copy unavailable: the clipboard requires a secure (HTTPS) connection."):navigator.clipboard.writeText(e.replace(lE,"")).then(()=>{l(!0),i("Message copied"),setTimeout(()=>{l(!1),i("")},1500)},()=>{})},[e]);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"chat-msg-copy","aria-label":t?"Copied":"Copy message",title:t?"Copied":"Copy message","data-copied":t?"true":"false",onClick:r,children:t?"Copied":"Copy"}),(0,n.jsx)("span",{role:"status",className:"sr-only",children:s})]})}function l$({message:e}){let t,a;if(lb(e))return(0,n.jsx)(lx,{message:e});let l="user"===e.role;return(0,n.jsx)("article",{className:"chat-msg","data-role":e.role,children:(0,n.jsxs)("div",{className:"chat-msg-bubble",children:[l?(0,n.jsx)("div",{className:"chat-msg-role",children:"You"}):(0,n.jsx)(lT,{}),l?e.content:(0,n.jsx)(ln,{source:e.content}),(0,n.jsxs)("div",{className:"chat-msg-foot",children:[(0,n.jsx)("div",{className:"chat-msg-time",title:new Date(e.timestamp).toLocaleString(),children:(a=(t=new Date(e.timestamp)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t.toDateString()===new Date().toDateString()?a:`${t.toLocaleDateString([],{month:"short",day:"numeric"})}, ${a}`)}),l?null:(0,n.jsx)(lR,{content:e.content})]})]})})}function lT({pulsing:e=!1}){return(0,n.jsx)("div",{className:"chat-msg-brand","data-pulsing":e?"true":"false",role:"img","aria-label":"Keiko logo",children:(0,n.jsx)(ap.default,{src:"/assets/keiko-logo.svg",width:22,height:22,alt:"","aria-hidden":"true"})})}function lA(){return(0,n.jsx)("article",{className:"chat-msg","data-role":"assistant",children:(0,n.jsxs)("div",{className:"chat-msg-bubble",children:[(0,n.jsx)(lT,{pulsing:!0}),(0,n.jsxs)("span",{className:"chat-typing",role:"img","aria-label":"Keiko is responding",children:[(0,n.jsx)("i",{}),(0,n.jsx)("i",{}),(0,n.jsx)("i",{})]})]})})}function lM({session:e,ready:t,selectedModelCapability:a,onAttachFiles:l,budgetExceeded:s}){let{models:i,selectedModel:r,setSelectedModel:o,draft:c,noEligibleModels:d,loading:u,sending:m,cancelSend:h,launchWorkflowFromConversation:p}=e,f=d||s||!t,g=0===c.trim().length,v=d?lj:void 0,b=d?lj:s?af:u?lN:g?lk:void 0,x=d?"No conversation-eligible model is configured — connect a gateway in Settings":"Model",y=u||d?"":r??"";return(0,n.jsxs)("div",{className:"cmp-bar",children:[(0,n.jsx)(lr,{model:a,onFiles:l,anyModelSupportsAttachments:i.some(e=>e.supportsImageInput||e.supportsDocumentInput)}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsxs)("label",{className:"cmp-model mono",title:x,children:[(0,n.jsx)(j.Icons.cube,{size:13,style:{color:"var(--accent)"}}),(0,n.jsx)("select",{className:"cmp-model-select",value:y,"aria-label":"Model","aria-disabled":d||u?"true":void 0,"aria-describedby":v,title:x,disabled:u,onChange:e=>{d||u||o(e.target.value)},children:u?(0,n.jsx)("option",{value:"",disabled:!0,children:"Loading models…"}):d?(0,n.jsx)("option",{value:"",children:"No conversation-eligible model"}):i.filter(e=>"chat"===e.kind).map(e=>(0,n.jsx)("option",{value:e.id,children:e.id},e.id))}),(0,n.jsx)(j.Icons.chevron,{size:12})]}),(0,n.jsx)(ld,{selectedModel:a,launch:p}),null,b===lk?(0,n.jsx)("span",{id:lk,className:"sr-only",children:"Type a message to send"}):null,m?(0,n.jsx)("button",{type:"button",className:"cmp-send cmp-send-cancel","data-on":!0,"aria-label":"Cancel response",title:"Cancel response",onClick:h,children:(0,n.jsx)(j.Icons.close,{size:16})}):(0,n.jsx)("button",{type:f?"button":"submit",className:"cmp-send","data-on":!f,"aria-disabled":f,"aria-describedby":b,title:d?"No conversation-eligible model is configured — connect a gateway in Settings":s?"Context exceeds the model's window — clear history or pick a larger-context model":u?"Connecting to your gateway":g?"Type a message to send":lC,"aria-label":"Send message",children:(0,n.jsx)(j.Icons.arrowUp,{size:16})})]})}function lL(){return(0,n.jsx)("div",{id:lj,role:"alert",className:"gw-error cmp-no-model",children:"No conversation-eligible model is configured. Connect a gateway in Settings to enable chat."})}function lq(){return(0,n.jsxs)("div",{id:lN,role:"status",className:"cmp-loading-status",children:[(0,n.jsx)("span",{className:"cmp-loading-dot","aria-hidden":"true"}),"Connecting to your gateway…"]})}function lP({status:e}){let t=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."}}(e);return(0,n.jsx)("div",{role:"status","aria-live":"polite","data-send-status":e,className:"cmp-send-status",children:0===t.length?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"cmp-loading-dot","aria-hidden":"true"}),t]})})}function lD({session:e,ready:t,placeholder:l}){let{draft:s,loading:i,sending:r,sendStatus:o,setDraft:c,sendMessage:d,models:u,selectedModel:m,pendingAttachments:h,addPendingAttachment:p,removePendingAttachment:f,budget:g,clearHistory:v}=e,b=nz(g),x=(0,a.useRef)(null);(0,a.useEffect)(()=>{let e=x.current;null!==e&&(e.style.height="auto",e.style.height=`${String(Math.min(e.scrollHeight,220))}px`)},[s]);let[y,w]=(0,a.useState)(),[j,k]=(0,a.useState)(),N=u.find(e=>e.id===m),S=void 0!==N&&(N.supportsImageInput||N.supportsDocumentInput),C=(0,a.useCallback)(async e=>{let t,n;for(let a of e){let e=await p(a);e.ok||void 0!==t||(t=e.reason,n=a.type)}w(t),k(n)},[p]);return(0,n.jsxs)("div",{className:"cmp-box",children:[(0,n.jsx)(ls,{enabled:S,onFiles:C}),(0,n.jsx)(ll,{attachments:h,onRemove:f}),(0,n.jsx)("textarea",{className:"cmp-input",ref:x,rows:2,value:s,"aria-label":"Chat message",placeholder:l,onChange:e=>c(e.target.value),onKeyDown:lI(d)}),(0,n.jsx)(lo,{reason:y,mimeType:j}),(0,n.jsx)(lP,{status:o}),(0,n.jsx)(ay,{budget:g,onClearHistory:v,disabled:r||i}),(0,n.jsx)(lM,{session:e,ready:t,selectedModelCapability:N,onAttachFiles:C,budgetExceeded:b})]})}function lF({session:e,noEligibleModels:t}){let{activeProject:a,setDraft:l}=e,s=void 0!==a?[`Explain the architecture of ${a.name}`,`Find a bug in ${a.name}`,`Write tests for ${a.name}`]:["Explain the architecture of this codebase","Find and fix a bug in the workspace store","Write tests for the window manager"];return(0,n.jsxs)("div",{className:"chatw-empty",children:[(0,n.jsx)("h2",{className:"chatw-empty-headline",children:"Start a Keiko conversation"}),(0,n.jsx)("p",{className:"chatw-empty-sub",children:void 0!==a?`Working in ${a.name}. What would you like to explore?`:"Pick a project from the sidebar to scope your workspace, or ask anything below."}),t?null:(0,n.jsx)("div",{className:"chatw-empty-prompts",role:"group","aria-label":"Starter prompts",children:s.map(e=>(0,n.jsxs)("button",{type:"button",className:"suggest",onClick:()=>l(e),children:[(0,n.jsx)(j.Icons.spark,{size:12,style:{color:"var(--accent)"}}),e]},e))})]})}function lz(){return(0,n.jsxs)("div",{className:"chatw-empty-no-chat",children:[(0,n.jsx)("div",{className:"chatw-empty-no-chat-icon","aria-hidden":"true",children:(0,n.jsx)(j.Icons.spark,{size:20})}),(0,n.jsx)("p",{className:"chatw-empty-no-chat-label",children:"Pick or start a chat"}),(0,n.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 lO({session:e,ready:t}){let{draft:a,loading:l,sending:s,sendStatus:i,cancelSend:r,setDraft:o,sendMessage:c}=e;return(0,n.jsxs)("form",{className:"composer composer-fill",onSubmit:e=>{e.preventDefault(),c()},children:[(0,n.jsxs)("div",{className:"cmp-box cmp-box-fill",children:[(0,n.jsx)("textarea",{className:"cmp-input cmp-input-mini",value:a,"aria-label":"Chat message",placeholder:l?"Loading…":"Ask Keiko…",onChange:e=>o(e.target.value),onKeyDown:lI(c)}),s?(0,n.jsx)("button",{type:"button",className:"cmp-send cmp-send-float cmp-send-cancel","data-on":!0,"aria-label":"Cancel response",title:"Cancel response",onClick:r,children:(0,n.jsx)(j.Icons.close,{size:16})}):(0,n.jsx)("button",{type:t?"submit":"button",className:"cmp-send cmp-send-float","data-on":t,"aria-disabled":!t,"aria-label":"Send message",title:lC,children:(0,n.jsx)(j.Icons.arrowUp,{size:16})})]}),(0,n.jsx)(lP,{status:i})]})}function lK(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 lB(e){if(lK(e)>1)return"multi";let t=e.localKnowledgeScopes?.[0]??e.localKnowledgeScope;return t?.kind==="capsule"?`capsule:${t.capsuleId}`:t?.kind==="capsule-set"?`capsule-set:${t.capsuleSetId}`:lU(e)?"files":"none"}function l_(e){return void 0!==e.localKnowledgeScopes?e.localKnowledgeScopes:void 0!==e.localKnowledgeScope?[e.localKnowledgeScope]:[]}function lU(e){return void 0!==e&&(void 0!==e.connectedScope||void 0!==e.connectedScopes&&e.connectedScopes.length>0)}function lW(e){return lU(e)||void 0!==e&&(void 0!==e.localKnowledgeScope||void 0!==e.localKnowledgeScopes&&e.localKnowledgeScopes.length>0)}function lH(e){return ng(e,"Unable to update knowledge scope.")}function lY({chat:e,onChatChanged:t,catalog:l,connected:s}){let{capsules:i,capsuleSets:r,loadError:o}=l,[c,d]=(0,a.useState)(!1),[u,m]=(0,a.useState)(null),h=(0,a.useRef)(null);async function p(n){d(!0),m(null);try{if("none"===n){let n=lK(e);if(n>0&&!window.confirm(`This will disconnect ${String(n)} grounding ${1===n?"source":"sources"}. Continue?`)){null!==h.current&&(h.current.value=lB(e));return}let a=await (0,w.updateChat)(e.id,{connectedScopes:null,localKnowledgeScopes:null});t(a.chat);return}if("files"===n){let n=await (0,w.updateChat)(e.id,{localKnowledgeScopes:null});t(n.chat);return}if(n.startsWith("capsule-set:")){let a={kind:"capsule-set",capsuleSetId:n.slice(12),connectedAtMs:Date.now()},l=l_(e),s=l.some(e=>"capsule-set"===e.kind&&e.capsuleSetId===a.capsuleSetId)?l:[...l,a],i=await (0,w.updateChat)(e.id,{localKnowledgeScopes:s});t(i.chat);return}if(n.startsWith("capsule:")){let a={kind:"capsule",capsuleId:n.slice(8),connectedAtMs:Date.now()},l=l_(e),s=l.some(e=>"capsule"===e.kind&&e.capsuleId===a.capsuleId)?l:[...l,a],i=await (0,w.updateChat)(e.id,{localKnowledgeScopes:s});t(i.chat)}}catch(e){m(lH(e))}finally{d(!1)}}let f=lB(e),g=function(e,t){let n=t.map(e=>({value:`capsule:${e.id}`,label:`Knowledge capsule: ${e.displayName}`})),a=lB(e);if(!a.startsWith("capsule:")||n.some(e=>e.value===a))return n;let l=a.slice(8);return[...n,{value:a,label:`Knowledge capsule: ${l} (unavailable)`}]}(e,i),v=function(e,t){let n=t.map(e=>({value:`capsule-set:${e.id}`,label:`Capsule set: ${e.displayName}`})),a=lB(e);if(!a.startsWith("capsule-set:")||n.some(e=>e.value===a))return n;let l=a.slice(12);return[...n,{value:a,label:`Capsule set: ${l} (unavailable)`}]}(e,r),b=u??o;return(0,n.jsxs)("label",{className:"scope-grounding","data-connected":s?"true":"false",children:[(0,n.jsx)("span",{className:"scope-grounding-label mono",children:"Grounding"}),(0,n.jsxs)("select",{ref:h,className:"scope-grounding-select",value:f,disabled:c,"aria-label":"Grounding mode",onChange:e=>{p(e.target.value)},children:[(0,n.jsx)("option",{value:"none",children:"Model only"}),(0,n.jsx)("option",{value:"files",disabled:!lU(e),children:"Live Files context"}),"multi"===f?(0,n.jsx)("option",{value:"multi",disabled:!0,children:"Multiple sources"}):null,g.map(e=>(0,n.jsx)("option",{value:e.value,children:e.label},e.value)),v.map(e=>(0,n.jsx)("option",{value:e.value,children:e.label},e.value))]}),null!==b?(0,n.jsx)("span",{role:"alert",className:"scope-connect-error",children:b}):null]})}function lJ({chat:e,onChatChanged:t}){let l=function(){let[e,t]=(0,a.useState)([]),[n,l]=(0,a.useState)([]),[s,i]=(0,a.useState)(null);return(0,a.useEffect)(()=>{let e=!1;return async function(){try{let[n,a]=await Promise.allSettled([(0,lw.fetchCapsules)(),(0,lw.fetchCapsuleSets)()]);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([]),i(lH(a.reason)))}catch(t){e||i(lH(t))}}(),()=>{e=!0}},[]),{capsules:e,capsuleSets:n,loadError:s}}(),s=lW(e);return(0,n.jsx)("div",{className:"chat-scope-header","data-grounded":s?"true":"false",children:(0,n.jsx)(lY,{chat:e,onChatChanged:t,catalog:l,connected:s})})}function lG({chat:e,answer:t,busy:a,selectedModelId:l,launchGroundedWorkflowHandoff:s}){return void 0!==e&&lW(e)&&(void 0!==t||a)?(0,n.jsxs)("div",{className:"chatw-grounded",children:[(0,n.jsx)(a_,{answer:t,busy:a}),(0,n.jsx)(lg,{answer:t,modelId:l,busy:a,launch:s})]}):null}function lV({action:e,acceptCandidate:t,rejectCandidate:l,forgetMemoryAction:s,onActionSettled:i}){let[r,o]=(0,a.useState)(!1),[c,d]=(0,a.useState)(),[u,m]=(0,a.useState)(!1),h=(0,a.useCallback)((e,t,n)=>{r||(o(!0),d(void 0),e().then(()=>{i(t)}).catch(e=>{d(e instanceof Error?e.message:n)}).finally(()=>o(!1)))},[r,i]);if("candidate"===e.kind)return(0,n.jsxs)("article",{className:"chat-memory-action",children:[(0,n.jsxs)("div",{className:"chat-memory-action-head",children:[(0,n.jsx)("strong",{children:e.scopeLabel}),(0,n.jsx)("span",{children:e.requiresApproval?"Approval required":"Proposed memory"})]}),(0,n.jsx)("p",{children:e.body}),(0,n.jsxs)("div",{className:"chat-memory-action-buttons",children:[(0,n.jsx)("button",{type:"button","aria-disabled":r,"aria-busy":r,onClick:()=>{h(()=>t(e.proposalId),"MemoriaViva proposal accepted.","Unable to accept memory.")},children:"Accept"}),(0,n.jsx)("button",{type:"button","aria-disabled":r,"aria-busy":r,onClick:()=>{h(()=>l(e.proposalId),"MemoriaViva proposal rejected.","Unable to reject memory.")},children:"Reject"})]}),void 0!==c?(0,n.jsx)(aj,{error:c,fallback:"Unable to update memory.",onDismiss:()=>d(void 0)}):null]});if("update"===e.kind)return(0,n.jsxs)("article",{className:"chat-memory-action",children:[(0,n.jsxs)("div",{className:"chat-memory-action-head",children:[(0,n.jsx)("strong",{children:"MemoriaViva update detected"}),(0,n.jsx)("span",{children:e.memoryId})]}),(0,n.jsx)("p",{children:void 0!==e.bodyPatch?`Suggested update: ${e.bodyPatch}`:"Suggested update."})]});if("forget"===e.kind){let t=()=>{h(()=>s(e.memoryId).then(()=>m(!1)),"MemoriaViva forget action completed.","Unable to forget memory.")};return(0,n.jsxs)("article",{className:"chat-memory-action",children:[(0,n.jsxs)("div",{className:"chat-memory-action-head",children:[(0,n.jsx)("strong",{children:"MemoriaViva forget detected"}),(0,n.jsx)("span",{children:e.requiresConfirmation?"Confirmation required":e.memoryId})]}),(0,n.jsx)("p",{children:`Matched memory ${e.memoryId} for a forget operation.`}),(0,n.jsx)("div",{className:"chat-memory-action-buttons",children:e.requiresConfirmation?u?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button","aria-disabled":r,"aria-busy":r,onClick:t,children:"Forget permanently"}),(0,n.jsx)("button",{type:"button","aria-disabled":r,"aria-busy":r,onClick:()=>{r||(d(void 0),m(!1))},children:"Cancel"})]}):(0,n.jsx)("button",{type:"button","aria-disabled":r,"aria-busy":r,onClick:()=>{r||(d(void 0),m(!0))},children:"Review forget"}):(0,n.jsx)("button",{type:"button","aria-disabled":r,"aria-busy":r,onClick:t,children:"Forget"})}),void 0!==c?(0,n.jsx)(aj,{error:c,fallback:"Unable to update memory.",onDismiss:()=>d(void 0)}):null]})}return"rejected"===e.kind?(0,n.jsxs)("article",{className:"chat-memory-action",children:[(0,n.jsx)("div",{className:"chat-memory-action-head",children:(0,n.jsx)("strong",{children:"Memory proposal declined"})}),(0,n.jsx)("p",{children:""!==e.reason?e.reason:"No reason provided"})]}):(0,n.jsx)("article",{className:"chat-memory-action",children:(0,n.jsx)("div",{className:"chat-memory-action-head",children:(0,n.jsx)("strong",{children:"MemoriaViva action not created"})})})}function lX({memoryEnabled:e,setMemoryEnabled:t,memoryBudgetTokens:l,setMemoryBudgetTokens:s,latestMemory:i,acceptCandidate:r,rejectCandidate:o,forgetMemoryAction:c}){let[d,u]=(0,a.useState)(!1),[m,h]=(0,a.useState)(""),p=(0,a.useId)(),f=`${p}-chat-memory-disclosure`,g=(0,a.useRef)(null),v=(0,a.useCallback)(e=>{h(e),g.current?.focus()},[]),b=i?.context.memories.length??0;return(0,n.jsxs)("section",{className:"chat-memory-panel","aria-label":"Conversation memory",children:[(0,n.jsxs)("div",{className:"chat-memory-panel-head",children:[(0,n.jsxs)("div",{className:"chat-memory-toggle",children:[(0,n.jsx)(ly,{on:e,onChange:t,label:"Enable MemoriaViva for the next request"}),(0,n.jsxs)("span",{children:["MemoriaViva ",e?"on":"off"]})]}),(0,n.jsxs)("label",{className:"chat-memory-budget",children:[(0,n.jsx)("span",{children:"Budget (tokens)"}),(0,n.jsx)("input",{type:"number",min:0,step:100,value:l,onChange:e=>s(Math.max(0,Number(e.target.value)||0))})]}),(0,n.jsx)("button",{ref:g,type:"button",className:"chip","aria-expanded":d,"aria-controls":f,onClick:()=>u(e=>!e),children:b>0?`${String(b)} memories included`:"No memories included"})]}),d?(0,n.jsxs)("div",{id:f,className:"chat-memory-disclosure",children:[(0,n.jsx)("p",{className:"chat-memory-summary",children:void 0===i?"MemoriaViva disclosure appears after the next response.":i.context.enabled?`Used ${String(i.context.budget.used)} of ${String(i.context.budget.tokens)} MemoriaViva tokens.`:"MemoriaViva was disabled for the last request."}),i?.context.memories.map(e=>(0,n.jsxs)("article",{className:"chat-memory-item",children:[(0,n.jsxs)("div",{className:"chat-memory-item-head",children:[(0,n.jsx)("strong",{children:e.memoryId}),(0,n.jsx)("span",{children:e.inclusionReason})]}),(0,n.jsx)("p",{children:e.bodyExcerpt}),(0,n.jsxs)("dl",{className:"chat-memory-meta","aria-label":`Provenance for ${e.memoryId}`,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Source"}),(0,n.jsx)("dd",{children:e.sourceKind})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Sensitivity"}),(0,n.jsx)("dd",{children:e.sensitivity})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Status"}),(0,n.jsx)("dd",{children:e.status})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Confidence"}),(0,n.jsx)("dd",{children:`${String(Math.round(100*e.confidence))}%`})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Captured"}),(0,n.jsx)("dd",{children:new Date(e.capturedAt).toISOString().slice(0,10)})]})]}),void 0!==e.captureRationale?(0,n.jsx)("p",{className:"chat-memory-rationale",children:e.captureRationale}):null]},e.memoryId)),i?.actions.map(e=>(0,n.jsx)(lV,{action:e,acceptCandidate:r,rejectCandidate:o,forgetMemoryAction:c,onActionSettled:v},"candidate"===e.kind?e.proposalId:"rejected"===e.kind?e.reason:e.memoryId)),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true",children:m})]}):null]})}function lQ({mini:e=!1}){let t=i(),{messages:l,draft:s,loading:r,sending:o,sendStatus:c,error:d,noEligibleModels:u,selectedModel:m,sendMessage:h,cancelGrounded:p,activeChat:f,replaceChat:g,latestGrounded:v,latestMemory:b,lastSentDocuments:x,memoryEnabled:y,setMemoryEnabled:w,memoryBudgetTokens:j,setMemoryBudgetTokens:k,acceptMemoryCandidate:N,rejectMemoryCandidate:S,launchGroundedWorkflowHandoff:C,forgetMemoryAction:I}=t,E=s.trim().length>0&&!o&&!r&&!u,R=l.filter(e=>"user"===e.role||"assistant"===e.role&&e.content.length>0||lb(e)),$=(0,a.useRef)(null),T=(0,a.useRef)(!0),A=(0,a.useRef)(!1),M=R.length>0?R[R.length-1]:void 0,L=void 0===M?"":M.content;return((0,a.useEffect)(()=>{o&&!A.current&&(T.current=!0),A.current=o;let e=$.current;null!==e&&T.current&&(e.scrollTop=e.scrollHeight)},[R.length,o,L]),e)?(0,n.jsxs)("div",{className:"chatw chatw-mini",children:[void 0!==f?(0,n.jsx)(lJ,{chat:f,onChatChanged:g}):null,u?(0,n.jsx)(lL,{}):null,(0,n.jsx)(lO,{session:t,ready:E}),void 0!==d?(0,n.jsx)(aj,{error:d,fallback:"Could not send message.",onDismiss:t.clearError}):null]}):(0,n.jsxs)("div",{className:"chatw",children:[void 0!==f?(0,n.jsx)(lJ,{chat:f,onChatChanged:g}):null,void 0!==f?(0,n.jsx)(lX,{memoryEnabled:y,setMemoryEnabled:w,memoryBudgetTokens:j,setMemoryBudgetTokens:k,latestMemory:b,acceptCandidate:N,rejectCandidate:S,forgetMemoryAction:I}):null,u?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsx)(lL,{})}):null,r?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsx)(lq,{})}):null,(0,n.jsx)("div",{className:"chatw-scroll",ref:$,role:"log","aria-label":"Conversation",tabIndex:0,onScroll:e=>{let t=e.currentTarget;T.current=t.scrollHeight-t.scrollTop-t.clientHeight<64},children:0===R.length?void 0!==f?(0,n.jsx)(lF,{session:t,noEligibleModels:u}):(0,n.jsx)(lz,{}):(0,n.jsxs)("div",{className:"chatw-log",children:[R.map(e=>(0,n.jsx)(l$,{message:e},e.id)),o&&"streaming"!==c?(0,n.jsxs)("div",{className:"chatw-typing-row",children:[(0,n.jsx)(lA,{}),lW(f)?(0,n.jsx)("button",{type:"button",className:"grounded-cancel-btn","aria-label":"Cancel grounded request",onClick:p,children:"Cancel"}):null]}):null,(0,n.jsx)(lG,{chat:f,answer:v,busy:o,selectedModelId:m,launchGroundedWorkflowHandoff:C}),(0,n.jsx)(lc,{documents:x})]})}),R.length>0?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsxs)("form",{className:"composer",onSubmit:e=>{e.preventDefault(),h()},children:[(0,n.jsx)(lD,{session:t,ready:E,placeholder:lS}),void 0!==d?(0,n.jsx)(aj,{error:d,fallback:"Could not send message.",onDismiss:t.clearError}):null]})}):null,0===R.length&&void 0!==f?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsxs)("form",{className:"composer",onSubmit:e=>{e.preventDefault(),h()},children:[(0,n.jsx)(lD,{session:t,ready:E,placeholder:r?"Connecting to your gateway…":lS}),void 0!==d?(0,n.jsx)(aj,{error:d,fallback:"Could not send message.",onDismiss:t.clearError}):null]})}):null,0===R.length&&void 0!==d&&void 0===f?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsx)(aj,{error:d,fallback:"Could not load chat.",onDismiss:t.clearError})}):null]})}let lZ=new Set(["ArrowDown","ArrowUp","ArrowRight","ArrowLeft","Home","End"]);function l0(e){return Array.from(e.querySelectorAll("button[role='treeitem']"))}function l1({project:e,activeProjectPath:t,chats:l,activeChatId:s,onProject:i,onChat:r,treeRef:o}){let c=t===e.path,[d,u]=(0,a.useState)(c),m=e.available?"Available":"Unavailable";return(0,a.useEffect)(()=>{c&&u(!0)},[c]),(0,n.jsxs)("div",{className:"proj",children:[(0,n.jsxs)("button",{className:"proj-head",type:"button",role:"treeitem","aria-level":1,"aria-expanded":d,"aria-selected":c,"data-active":c?"true":"false","aria-current":c?"true":void 0,"aria-label":`${e.name} (${m})`,tabIndex:c?0:-1,onClick:()=>{u(e=>!e),i(e),null!==o.current&&l0(o.current).forEach(e=>{e.tabIndex=-1})},children:[(0,n.jsx)("span",{className:"proj-caret","data-open":d,"aria-hidden":"true",children:(0,n.jsx)(j.Icons.chevronR,{size:13})}),(0,n.jsx)(j.Icons.folder,{size:15,"aria-hidden":"true"}),(0,n.jsx)("span",{className:"proj-name",children:e.name}),(0,n.jsx)("span",{className:"chat-time",children:m})]}),d&&(0,n.jsx)("div",{className:"proj-chats",role:"group","aria-label":e.name,children:c?0===l.length?(0,n.jsx)("div",{className:"proj-empty",children:"No chats"}):l.map(e=>(0,n.jsxs)("button",{type:"button",role:"treeitem","aria-level":2,"aria-selected":s===e.id,className:"chat-row","data-active":s===e.id,tabIndex:-1,onClick:()=>{r(e)},children:[(0,n.jsx)("span",{className:"chat-title",children:e.title}),void 0!==e.branchLabel?(0,n.jsx)("span",{className:"chat-meta mono",children:e.branchLabel}):null]},e.id)):(0,n.jsx)("div",{className:"proj-empty",children:"Select project to load chats"})})]})}function l2(){let e=i(),t=(0,a.useRef)(null);return(0,n.jsxs)("div",{className:"tw-scroll",children:[(0,n.jsx)("div",{className:"sb-section",children:(0,n.jsx)("span",{className:"sb-section-label",children:"Projects"})}),0===e.projects.length?(0,n.jsx)("div",{className:"proj-empty",children:"No registered projects"}):(0,n.jsx)("div",{className:"proj-tree",role:"tree","aria-label":"Projects",tabIndex:-1,ref:t,onKeyDown:e=>{lZ.has(e.key)&&null!==t.current&&function(e,t){let n=l0(t),a=e.target;if(!(a instanceof HTMLElement))return;let l=a.closest("button[role='treeitem']");if(null===l)return;let s=n.indexOf(l);if(s<0)return;e.preventDefault();let i=e.key;if("ArrowDown"===i)n[s+1]?.focus();else if("ArrowUp"===i)n[s-1]?.focus();else if("Home"===i)n[0]?.focus();else if("End"===i)n[n.length-1]?.focus();else if("ArrowRight"===i)"false"===l.getAttribute("aria-expanded")?l.click():"true"===l.getAttribute("aria-expanded")&&n[s+1]?.focus();else if("ArrowLeft"===i)if("true"===l.getAttribute("aria-expanded"))l.click();else{let e=Number(l.getAttribute("aria-level")??"1");for(let t=s-1;t>=0;t-=1)if(Number(n[t]?.getAttribute("aria-level")??"1")<e){n[t]?.focus();break}}}(e,t.current)},children:e.projects.map(a=>(0,n.jsx)(l1,{project:a,activeProjectPath:e.activeProject?.path,chats:e.activeProject?.path===a.path?e.chats:[],activeChatId:e.activeChat?.id,treeRef:t,onProject:t=>{e.openProject(t)},onChat:t=>{e.openChat(t)}},a.path))})]})}function l4({openChatWindow:e}){let t=i(),[l,s]=(0,a.useState)(""),[r,o]=(0,a.useState)("active"),[c,d]=(0,a.useState)(null),[u,m]=(0,a.useState)(""),[h,p]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(null),[x,y]=(0,a.useState)(null),k=(0,a.useRef)(null),N=(0,a.useId)(),S=(0,a.useId)(),C=(0,a.useId)(),I=(0,a.useId)(),E=(0,a.useMemo)(()=>t.chats.filter(e=>"closed"!==e.status).length,[t.chats]),R=t.chats.length-E,$=(0,a.useMemo)(()=>[...t.chats].sort((e,t)=>t.updatedAt-e.updatedAt).filter(e=>"deleted"===r?"closed"===e.status:"closed"!==e.status).filter(e=>{let t;return 0===(t=l.trim().toLowerCase()).length||e.title.toLowerCase().includes(t)||e.selectedModel.toLowerCase().includes(t)||(e.branchLabel?.toLowerCase().includes(t)??!1)}),[l,t.chats,r]);(0,a.useEffect)(()=>{null!==c&&k.current?.focus({preventScroll:!0})},[c]);let T=async()=>{b(null);let n=await t.openNewChat(void 0,"New chat");void 0!==n&&e(n)},A=e=>{d(e.id),m(e.title),p(null),b(null),y(null)},M=async e=>{let n=u.trim();if(0===n.length){y("Title cannot be empty."),k.current?.focus({preventScroll:!0});return}if(n===e.title){d(null),y(null);return}g(e.id),b(null),y(null);try{let a=await (0,w.updateChat)(e.id,{title:n});t.replaceChat(a.chat),d(null)}catch{b("Rename failed.")}finally{g(null)}},L=async e=>{g(e.id),b(null);try{let n=await (0,w.updateChat)(e.id,{status:"closed"});t.replaceChat(n.chat),p(null),o("deleted")}catch(t){let e=t instanceof Error?t.message:"Request failed.";b(`Delete failed: ${e}`)}finally{g(null)}},q=async e=>{g(e.id),b(null);try{let n=await (0,w.updateChat)(e.id,{status:"open"});t.replaceChat(n.chat),p(null),o("active")}catch(t){let e=t instanceof Error?t.message:"Request failed.";b(`Restore failed: ${e}`)}finally{g(null)}};return(0,n.jsxs)("div",{className:"chat-history",children:[(0,n.jsxs)("div",{className:"chat-history-head",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"chat-history-kicker",children:"Conversations"}),(0,n.jsx)("h2",{children:"Chat History"})]}),(0,n.jsxs)("button",{type:"button",className:"lk-btn lk-btn-primary",onClick:()=>void T(),children:[(0,n.jsx)(j.Icons.newChat,{size:15}),"New"]})]}),(0,n.jsxs)("label",{className:"chat-history-search",children:[(0,n.jsx)(j.Icons.search,{size:15}),(0,n.jsx)("input",{value:l,onChange:e=>s(e.target.value),placeholder:"Search","aria-label":"Search chat history"})]}),(0,n.jsxs)("div",{className:"chat-history-tabs",role:"tablist","aria-label":"Conversation state",children:[(0,n.jsxs)("button",{type:"button",id:N,role:"tab","aria-selected":"active"===r,"aria-controls":C,className:"chat-history-tab",onClick:()=>{o("active"),p(null)},children:["Active ",(0,n.jsx)("span",{children:E})]}),(0,n.jsxs)("button",{type:"button",id:S,role:"tab","aria-selected":"deleted"===r,"aria-controls":C,className:"chat-history-tab",onClick:()=>{o("deleted"),p(null)},children:["Deleted ",(0,n.jsx)("span",{children:R})]})]}),null!==v?(0,n.jsx)("div",{className:"lk-alert",role:"alert",children:v}):null,(0,n.jsx)("div",{id:C,className:"chat-history-list",role:"tabpanel","aria-labelledby":"active"===r?N:S,children:0===$.length?(0,n.jsx)("div",{className:"lk-empty",children:(0,n.jsx)("p",{className:"lk-empty-title",children:"No conversations"})}):$.map(t=>{var a;let l=e0(t).length+e1(t).length,s=c===t.id,i=h===t.id,r=f===t.id,o="closed"===t.status;return(0,n.jsxs)("article",{className:"chat-history-row","data-chat-id":t.id,"data-state":o?"deleted":"active",children:[(0,n.jsx)("div",{className:"chat-history-row-main",children:s?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("input",{ref:k,className:"chat-history-title-input",value:u,"aria-invalid":null!==x,"aria-describedby":null!==x?I:void 0,onChange:e=>{m(e.target.value),null!==x&&y(null)},onKeyDown:e=>{"Enter"===e.key&&M(t),"Escape"===e.key&&(d(null),y(null))}}),null!==x?(0,n.jsx)("span",{id:I,className:"chat-history-rename-error",role:"alert",children:x}):null]}):(0,n.jsxs)("button",{type:"button",className:"chat-history-open",disabled:o,onClick:()=>e(t),children:[(0,n.jsx)("span",{className:"chat-history-title",children:t.title}),(0,n.jsxs)("span",{className:"chat-history-meta",children:[(a=t.updatedAt,new Intl.DateTimeFormat(void 0,{month:"short",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(a)))," / ",t.selectedModel,l>0?` / ${String(l)} sources`:""]})]})}),(0,n.jsx)("div",{className:"chat-history-actions",children:s?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-primary",disabled:r,onClick:()=>void M(t),children:"Save"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",disabled:r,onClick:()=>{d(null),y(null)},children:"Cancel"})]}):i?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-danger",disabled:r,onClick:()=>void L(t),children:"Delete"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",disabled:r,onClick:()=>p(null),children:"Cancel"})]}):o?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{type:"button",className:"lk-btn lk-btn-primary",disabled:r,onClick:()=>void q(t),children:[(0,n.jsx)(j.Icons.restore,{size:14}),"Restore"]}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:()=>A(t),children:"Rename"})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:()=>A(t),children:"Rename"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:()=>{p(t.id),d(null)},children:"Delete"})]})})]},t.id)})})]})}function l3(){let e=r(),t=e?.activeProject?.name??"No project selected",l=(0,a.useId)();return(0,n.jsxs)("div",{className:"srch",children:[(0,n.jsxs)("div",{className:"srch-box",children:[(0,n.jsx)(j.Icons.search,{size:15,"aria-hidden":"true"}),(0,n.jsx)("input",{type:"search","aria-label":"Search files and symbols","aria-describedby":l,placeholder:"Search files & symbols…",disabled:!0})]}),(0,n.jsxs)("div",{className:"tw-label srch-label",children:[t," ",(0,n.jsx)("span",{className:"srch-meta mono",children:"workspace search"})]}),(0,n.jsxs)("div",{className:"tw-pad",children:[(0,n.jsxs)("div",{className:"rb-placeholder",style:{height:150},children:[(0,n.jsx)("div",{className:"ph-stripes"}),(0,n.jsx)("span",{className:"rb-ph-label mono",children:"search"})]}),(0,n.jsx)("div",{id:l,className:"rb-foot mono",style:{marginTop:14},children:"Search across workspace files & symbols — coming soon."})]})]})}let l6=[{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 · PRs · 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}],l5=[{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 l8({img:e,icon:t,glyph:a}){if(void 0!==e)return(0,n.jsx)("img",{className:"pl-img",src:`/assets/icons/${e}.svg`,width:"20",height:"20",alt:""});if(void 0!==t){let e=j.Icons[t];return(0,n.jsx)("span",{className:"pl-line",children:(0,n.jsx)(e,{size:18})})}return(0,n.jsx)("span",{className:"mono pl-glyph",children:a})}function l7(){let[e,t]=(0,a.useState)(l6.map(e=>e.on)),l=e.filter(Boolean).length;return(0,n.jsxs)("div",{className:"plg",children:[(0,n.jsxs)("div",{className:"plg-sec",children:[(0,n.jsx)("span",{className:"plg-sec-t",children:"MCP Servers"}),(0,n.jsxs)("span",{className:"plg-sec-c mono",children:[l,"/",l6.length," active"]})]}),l6.map((a,l)=>{let s=e[l]??!1;return(0,n.jsxs)("div",{className:"plg-row",children:[(0,n.jsx)("span",{className:"plg-ico",children:(0,n.jsx)(l8,{img:a.img,icon:a.icon})}),(0,n.jsxs)("span",{className:"plg-text",children:[(0,n.jsx)("span",{className:"plg-name",children:a.name}),(0,n.jsx)("span",{className:"plg-desc",children:a.desc})]}),(0,n.jsx)("button",{className:`plg-dot${s?" on":""}`,title:s?"Running":"Stopped","aria-label":`${a.name}: ${s?"running":"stopped"}`,onClick:()=>{t(e=>{let t=[...e];return t[l]=!t[l],t})}})]},a.name)}),(0,n.jsx)("div",{className:"plg-sec plg-sec2",children:(0,n.jsx)("span",{className:"plg-sec-t",children:"Connectors"})}),l5.map(e=>(0,n.jsxs)("button",{className:"plg-row plg-conn","data-on":e.on,children:[(0,n.jsx)("span",{className:"plg-ico",children:(0,n.jsx)(l8,{img:e.img})}),(0,n.jsxs)("span",{className:"plg-text",children:[(0,n.jsx)("span",{className:"plg-name",children:e.name}),(0,n.jsx)("span",{className:"plg-desc",children:e.on?"Connected":"Not connected"})]}),e.on?(0,n.jsx)("span",{className:"integ-on",children:(0,n.jsx)(j.Icons.check,{size:13})}):(0,n.jsx)("span",{className:"integ-add",children:(0,n.jsx)(j.Icons.plus,{size:14})})]},e.name))]})}let l9=[{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}],se="keiko.automations.v1",st=Object.fromEntries(l9.map(e=>[e.id,e.defaultOn]));function sn(){try{let e=localStorage.getItem(se);if(null===e)return{...st};let t=JSON.parse(e);if("object"!=typeof t||null===t||Array.isArray(t))return{...st};let n={...st};for(let[e,a]of Object.entries(t))e in st&&"boolean"==typeof a&&(n[e]=a);return n}catch{return{...st}}}function sa(){let[e,t]=(0,a.useState)(sn);return(0,n.jsx)("div",{className:"tw-list",children:l9.map(a=>{let l=e[a.id]??a.defaultOn;return(0,n.jsxs)("div",{className:"auto-row",children:[(0,n.jsx)("span",{className:"dot",style:{background:l?"var(--accent)":"var(--fg-faint)"}}),(0,n.jsxs)("span",{className:"auto-text",children:[(0,n.jsx)("span",{className:"auto-name",children:a.name}),(0,n.jsx)("span",{className:"auto-when mono",children:a.when})]}),(0,n.jsx)(ly,{on:l,onChange:()=>{var e;e=a.id,t(t=>{let n={...t,[e]:!t[e]};try{localStorage.setItem(se,JSON.stringify(n))}catch{}return n})},label:a.name})]},a.id)})})}function sl(){return(0,n.jsxs)("div",{className:"tw-pad mob",children:[(0,n.jsxs)("div",{className:"mob-qr",children:[(0,n.jsx)("div",{className:"ph-stripes"}),(0,n.jsx)(j.Icons.mobile,{size:28,style:{position:"relative",color:"var(--fg-dim)"}})]}),(0,n.jsx)("div",{className:"mob-title",children:"Keiko Mobile"}),(0,n.jsx)("div",{className:"mob-sub",children:"Scan to continue this workspace on your phone."})]})}function ss(){var e;let t,{wins:l,active:s,winCount:i}=(0,a.useContext)(y),r=null!==s?E[s.type]:null,o=null!==s?Object.entries(s.cfg).filter(([,e])=>""!==e&&null!=e):[];return(0,n.jsxs)("div",{className:"tw-pad",children:[(0,n.jsx)("div",{className:"rb-section-label",style:{marginTop:0},children:"Active window"}),null!==s&&null!==r?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"insp-top",children:[(0,n.jsx)("span",{className:"insp-ico",style:{color:!0===r.accent?"var(--accent)":"var(--fg-muted)"},children:(e=r.icon,t=j.Icons[e],(0,n.jsx)(t,{size:16}))}),(0,n.jsx)("span",{className:"insp-title",children:r.title})]}),(0,n.jsxs)("div",{className:"rb-rows",children:[(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Size"}),(0,n.jsxs)("span",{className:"rb-row-v mono",children:[Math.round(s.w)," × ",Math.round(s.h)]})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Position"}),(0,n.jsxs)("span",{className:"rb-row-v mono",children:[Math.round(s.x),", ",Math.round(s.y)]})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"State"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:s.max?"maximized":"floating"})]})]}),o.length>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"rb-section-label",children:"Configuration"}),(0,n.jsx)("div",{className:"rb-rows",children:o.map(([e,t])=>(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:e}),(0,n.jsx)("span",{className:"rb-row-v mono",children:String(t).slice(0,20)||"—"})]},e))})]}),(0,n.jsx)("div",{className:"rb-section-label insp-governance",children:"Governance"}),(0,n.jsxs)("div",{className:"rb-rows insp-governance","data-testid":"insp-governance",children:[(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Authority"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:eR[s.type].authority})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Persistence"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:eR[s.type].persistence})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Trust"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:eR[s.type].trustBoundary.join(", ")})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Lifecycle"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:eR[s.type].lifecycle.join(" → ")})]})]})]}):(0,n.jsx)("div",{className:"insp-empty",children:"No window focused"}),(0,n.jsx)("div",{className:"rb-section-label",children:"Workspace"}),(0,n.jsx)("div",{className:"rb-rows",children:(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Open windows"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:i})]})})]})}let si=[{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 sr(){return(0,n.jsx)("ul",{className:"tw-list",children:si.map((e,t)=>(0,n.jsxs)("li",{className:"nt-row",children:[(0,n.jsx)("span",{className:"dot",style:{background:e.c,marginTop:6},"aria-hidden":"true"}),(0,n.jsxs)("span",{className:"nt-text",children:[(0,n.jsx)("span",{className:"nt-title",children:e.t}),(0,n.jsxs)("span",{className:"nt-time mono",children:[e.time," ago"]})]})]},t))})}function so(){return(0,n.jsxs)("div",{className:"tw-pad",children:[(0,n.jsxs)("div",{className:"rb-placeholder",style:{height:150},children:[(0,n.jsx)("div",{className:"ph-stripes"}),(0,n.jsx)("span",{className:"rb-ph-label mono",children:"resources"})]}),(0,n.jsx)("div",{className:"rb-foot mono",style:{marginTop:14},children:"Shared assets & references — coming soon."})]})}let sc="keiko-activity",sd={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 su(){let e=function(){let[,e]=(0,a.useState)(0);return(0,a.useEffect)(()=>{let t=()=>{e(e=>e+1)};return window.addEventListener(sc,t),()=>{window.removeEventListener(sc,t)}},[]),window.__keikoActivity??[]}();return(0,n.jsxs)("div",{className:"tl",role:"log","aria-label":"Activity timeline",children:[0===e.length&&(0,n.jsxs)("div",{className:"tl-empty",children:["No activity yet.",(0,n.jsx)("br",{}),"Start an agent to see its actions stream here."]}),e.map((e,t)=>(0,n.jsxs)("div",{className:"tl-row",children:[(0,n.jsx)("span",{className:"tl-dot","aria-hidden":"true",style:{background:sd[e.type]??"var(--fg-faint)"}}),(0,n.jsxs)("div",{className:"tl-body",children:[(0,n.jsx)("span",{className:"visually-hidden",children:e.type}),(0,n.jsx)("span",{className:"tl-text",children:e.text}),(0,n.jsxs)("span",{className:"tl-meta mono",children:[e.agent??"workspace"," · ",new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})]})]})]},t))]})}function sm({name:e,icon:t}){let a,l=t??("dockerfile"===(a=e.toLowerCase())||a.includes("docker-compose")||a.endsWith(".dockerignore")?"docker":a.endsWith(".json")?"json":a.endsWith(".yml")||a.endsWith(".yaml")?"yaml":a.endsWith(".md")?"markdown":a.endsWith(".properties")||a.endsWith(".env")||a.startsWith(".env.")?"properties":a.endsWith(".java")?"java":a.endsWith(".tsx")?"react":a.endsWith(".ts")?"typescript":a.endsWith(".jsx")||a.endsWith(".js")||a.endsWith(".mjs")||a.endsWith(".cjs")?"javascript":a.endsWith(".py")?"python":a.endsWith(".go")?"go":a.endsWith(".rs")?"rust":a.endsWith(".gradle")?"gradle":a.endsWith(".sql")?"postgresql":a.endsWith(".html")?"html5":a.endsWith(".css")?"css3":a.endsWith(".graphql")||a.endsWith(".gql")?"graphql":a.endsWith(".png")||a.endsWith(".jpg")||a.endsWith(".jpeg")||a.endsWith(".gif")||a.endsWith(".webp")||a.endsWith(".svg")?"image":null);return null!==l?(0,n.jsx)("img",{className:"fi-img",src:`/assets/icons/${l}.svg`,width:"15",height:"15",alt:""}):(0,n.jsx)("span",{className:"fi-fallback",children:(0,n.jsx)(j.Icons.file,{size:14})})}let sh={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 sp(e){let t=e.toLowerCase();if(".env"===t||t.startsWith(".env."))return"props";if("dockerfile"===t||t.startsWith("dockerfile"))return"docker";if(t.includes("docker-compose"))return"yaml";let n=t.split("."),a=n.length>1?n[n.length-1]:void 0;return void 0===a?"code":sh[a]??"code"}let sf=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 sg(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 sv(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);return null!==t?[["ws",t[1]??""],["key",t[2]??""],["ws",t[3]??""],...sg(e.slice(t[0].length))]:sg(e)});if("json"===t)return e.split("\n").map(e=>{let t=[],n=0;for(;n<e.length;){let a=e.slice(n),l=/^"(?:[^"\\]|\\.)*"/.exec(a);if(null!==l){let a=e.slice(n+l[0].length),s=/^\s*:/.test(a);t.push([s?"key2":"str",l[0]]),n+=l[0].length;continue}let s=/^-?\d[\d.eE+\-]*/.exec(a);if(null!==s){t.push(["num",s[0]]),n+=s[0].length;continue}let i=/^(true|false|null)\b/.exec(a);if(null!==i){t.push(["lit",i[0]]),n+=i[0].length;continue}let r=/^\s+/.exec(a);if(null!==r){t.push(["ws",r[0]]),n+=r[0].length;continue}t.push(["punct",a.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:["<!--","-->"]}:{line:"//",block:["/*","*/"]},a={inBlock:!1},l=[];for(let t of e.split("\n"))l.push(function(e,t,n){let a=[],l=0;if(t.inBlock&&null!==n.block){let s=e.indexOf(n.block[1]);if(-1===s)return a.push(["com",e]),a;a.push(["com",e.slice(0,s+n.block[1].length)]),l=s+n.block[1].length,t.inBlock=!1}for(;l<e.length;){let s=e.slice(l);if(null!==n.line&&s.startsWith(n.line)){a.push(["com",s]);break}if(null!==n.block&&s.startsWith(n.block[0])){let i=e.indexOf(n.block[1],l+n.block[0].length);if(-1===i){a.push(["com",s]),t.inBlock=!0;break}a.push(["com",e.slice(l,i+n.block[1].length)]),l=i+n.block[1].length;continue}let i=/^(?:"(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?)/.exec(s);if(null!==i&&i[0].length>1){a.push(["str",i[0]]),l+=i[0].length;continue}if(/^\d/.test(s)){let e=/^\d[\w.]*/.exec(s),t=e?.[0]??s.charAt(0);a.push(["num",t]),l+=t.length;continue}let r=/^[@A-Za-z_$][\w$]*/.exec(s);if(null!==r){let t=r[0],n="id";sf.has(t)||sf.has(t.toLowerCase())?n="key":t.startsWith("@")||/^[A-Z]/.test(t)?n="type":"("===e.charAt(l+t.length)&&(n="fn"),a.push([n,t]),l+=t.length;continue}let o=/^\s+/.exec(s);if(null!==o){a.push(["ws",o[0]]),l+=o[0].length;continue}let c=/^[^\w\s$@"']+/.exec(s);if(null!==c){a.push(["punct",c[0]]),l+=c[0].length;continue}a.push(["id",s.charAt(0)]),l+=1}return a}(t,a,n));return l}function sb(e){if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=e,a=0;for(;n>=1024&&a<t.length-1;)n/=1024,a+=1;let l=0===a?n.toFixed(0):n.toFixed(n>=10?1:2);return`${l} ${t[a]}`}function sx(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e))}function sy({label:e,value:t}){return(0,n.jsxs)("div",{className:"fpv-meta-row",children:[(0,n.jsx)("span",{children:e}),(0,n.jsx)("strong",{children:t})]})}function sw({root:e,path:t,onClose:l,onOpenInEditor:s}){let[i,r]=(0,a.useState)(null),[o,c]=(0,a.useState)(!0),[d,u]=(0,a.useState)(null),[m,h]=(0,a.useState)(0),p=(0,a.useRef)(null);(0,a.useEffect)(()=>{p.current?.focus({preventScroll:!0})},[]),(0,a.useEffect)(()=>{let n=!1;return c(!0),u(null),r(null),(0,w.fetchFilesPreview)(e,t).then(e=>{n||r(e)}).catch(e=>{n||u(e instanceof w.ApiError&&"DENIED"===e.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}:e instanceof Error?{message:/^HTTP \d+$/.test(e.message)?"The file could not be loaded. Try again.":e.message,denied:!1}:{message:"Unable to read this file.",denied:!1})}).finally(()=>{n||c(!1)}),()=>{n=!0}},[t,e,m]);let f=d?.denied===!0,g=null!==i?"text"===i.kind?i.extension??"text":"image"===i.kind?i.mime:i.extension??"binary":f?"denied":null!==d?"error":"loading",v=f?"Hidden file":i?.name??(null!==d?"Preview unavailable":"Loading preview"),b=i?.kind==="text"&&i.content.length<=2e5,x=void 0!==s&&i?.kind==="text"&&!i.truncated,y=i?.kind==="text"?b?sv(i.content,sp(i.name)):i.content.split("\n").map(e=>[["id",e]]):[];return(0,n.jsxs)("div",{className:"fpv",onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),l())},children:[(0,n.jsxs)("div",{className:"fpv-bar",children:[(0,n.jsx)("button",{className:"fpv-back",type:"button",ref:p,onClick:l,title:"Back to files","aria-label":"Back to files",children:(0,n.jsx)(j.Icons.back,{size:15})}),(0,n.jsx)(sm,{name:f||null===i?"":i.name}),(0,n.jsx)("span",{className:"fpv-name",title:v,children:v}),(0,n.jsx)("span",{className:"fpv-lang mono",children:g}),(0,n.jsx)("span",{className:"spacer"}),x?(0,n.jsx)("button",{className:"fpv-back",type:"button",onClick:()=>s(e,t),title:"Open in editor","aria-label":"Open in editor",children:(0,n.jsx)(j.Icons.editor,{size:15})}):null,(0,n.jsx)("button",{className:"fpv-back",type:"button",onClick:l,title:"Close preview","aria-label":"Close preview",children:(0,n.jsx)(j.Icons.close,{size:15})})]}),o?(0,n.jsx)("div",{className:"fpv-state",role:"status",children:"Loading preview…"}):null,null!==d?(0,n.jsxs)("div",{className:"fpv-state fpv-error",role:"alert",children:[(0,n.jsx)("span",{children:d.message}),d.denied?null:(0,n.jsx)("button",{type:"button",className:"fpv-retry",onClick:()=>h(e=>e+1),children:"Retry"})]}):null,i?.kind==="text"?(0,n.jsxs)(n.Fragment,{children:[i.truncated?(0,n.jsxs)("div",{className:"fpv-banner",children:["Preview truncated at ",sb(i.maxBytes),". Larger files can't be shown in full here."]}):null,b?null:(0,n.jsx)("div",{className:"fpv-banner",children:"Syntax highlighting disabled for large previews."}),(0,n.jsx)("div",{className:"fpv-code mono",tabIndex:0,role:"region","aria-label":`File preview: ${i.name}`,style:{"--fpv-gutter-w":`max(44px, calc(${String(String(y.length).length)}ch + 16px))`},children:y.map((e,t)=>(0,n.jsxs)("div",{className:"fpv-line",children:[(0,n.jsx)("span",{className:"fpv-num",children:t+1}),(0,n.jsx)("span",{className:"fpv-src",children:e.map((e,t)=>(0,n.jsx)("span",{className:`hl-${e[0]}`,children:e[1]},t))})]},t))})]}):null,i?.kind==="image"?(0,n.jsxs)("div",{className:"fpv-image-pane",children:[(0,n.jsx)("div",{className:"fpv-image-card",children:(0,n.jsx)("img",{className:"fpv-image",src:i.dataUrl,alt:i.name})}),(0,n.jsxs)("div",{className:"fpv-meta",children:[(0,n.jsx)(sy,{label:"Type",value:i.mime}),(0,n.jsx)(sy,{label:"Size",value:sb(i.sizeBytes)}),(0,n.jsx)(sy,{label:"Modified",value:sx(i.modifiedAt)})]})]}):null,i?.kind==="binary"?(0,n.jsx)("div",{className:"fpv-meta-pane",children:(0,n.jsxs)("div",{className:"fpv-meta-card",children:[(0,n.jsx)(sm,{name:i.name}),(0,n.jsx)("h3",{children:i.name}),(0,n.jsx)("p",{children:"too_large"===i.reason?`Preview disabled because this file exceeds ${sb(i.maxBytes??0)}.`:"docx"===function(e){let t=e.extension?.trim().toLowerCase();if(void 0!==t&&t.length>0)return t;let n=e.name.lastIndexOf(".");return n>=0?e.name.slice(n+1).trim().toLowerCase():""}(i)?"DOCX is not searchable in Repository Search yet. Add it to Local Knowledge, or enable small-document repository extraction when available.":"No safe text or image preview is available for this file type."}),(0,n.jsxs)("div",{className:"fpv-meta",children:[(0,n.jsx)(sy,{label:"Type",value:i.mime}),(0,n.jsx)(sy,{label:"Extension",value:i.extension??"none"}),(0,n.jsx)(sy,{label:"Size",value:sb(i.sizeBytes)}),(0,n.jsx)(sy,{label:"Modified",value:sx(i.modifiedAt)})]})]})}):null]})}function sj(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 sk(e){return 8+18*e}let sN=new Set(["ArrowDown","ArrowUp","ArrowRight","ArrowLeft","Home","End"]);function sS({root:e,onActiveFileChange:t,onRootChange:l,onOpenFile:s}){let i=e?.trim(),r=void 0!==i&&i.length>0?i:null,[o,c]=(0,a.useState)(null),d=r??o??"",[u,m]=(0,a.useState)(null),[h,p]=(0,a.useState)(""),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(null),[x,y]=(0,a.useState)({}),[k,N]=(0,a.useState)(()=>new Set([""])),[S,C]=(0,a.useState)(0),I=(0,a.useRef)(t);I.current=t;let E=(0,a.useRef)(null),R=(0,a.useRef)(null),$=(0,a.useId)();(0,a.useEffect)(()=>{if(null!==f)return;let e=R.current;if(null===e)return;R.current=null;let t=E.current?.querySelector(`.tr-file[data-path="${"u">typeof CSS&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"]`);(t??E.current)?.focus({preventScroll:!0})},[f]),(0,a.useEffect)(()=>{if(null!==r)return;let e=!1;return(0,w.fetchProjects)().then(t=>{e||c(t.projects.find(e=>e.available)?.path??null)}).catch(()=>{e||c(null)}),()=>{e=!0}},[r]);let T=(0,a.useCallback)(async e=>{if(0===d.length)return void y(t=>({...t,[e]:{entries:[],truncated:!1,loading:!1,error:null,notice:"no-root"}}));y(t=>({...t,[e]:{entries:t[e]?.entries??[],truncated:t[e]?.truncated??!1,loading:!0,error:null,notice:null}}));try{let t=await (0,w.fetchFilesTree)(d,e);""===e&&(m(t.root),I.current?.(null,t.root,null),b(null)),y(n=>({...n,[e]:{entries:t.entries,truncated:t.truncated,loading:!1,error:null,notice:null}}))}catch(t){y(n=>({...n,[e]:{entries:n[e]?.entries??[],truncated:n[e]?.truncated??!1,loading:!1,error:t instanceof Error?t.message:"Unable to read this folder.",notice:null}}))}},[d]);(0,a.useEffect)(()=>{g(null),b(null),I.current?.(null,null,null),m(null),N(new Set([""])),y({}),T("")},[d,T,S]);let A=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)}`}(u??(d.length>0?d:""),v);(0,a.useEffect)(()=>{p(A)},[A]);let M=(0,a.useCallback)(e=>{let t=e.trim();void 0===l||0===t.length||t!==A&&l(t)},[l,A]),L=(0,a.useCallback)(e=>{g(null),b(e),I.current?.(null,u??d,e),null!==e&&void 0===x[e]&&T(e)},[d,x,T,u]),q=(0,a.useCallback)(()=>{if(null!==v)return void L(function(e){let t=e.replace(/\/+$/u,""),n=t.lastIndexOf("/");if(n<0)return null;let a=t.slice(0,n);return a.length>0?a:null}(v));let e=sj(u??d);null!==e&&M(e)},[d,v,L,M,u]),P=(e,t,a=x[e])=>(0,n.jsxs)("div",{className:"tr-dir",role:0===t?void 0:"group",children:[a?.loading===!0?(0,n.jsx)("div",{className:"files-note",role:"status",style:{paddingLeft:sk(t)+18},children:"Loading…"}):null,a?.notice==="no-root"?(0,n.jsx)("div",{className:"files-note",role:"status",style:{paddingLeft:sk(t)+18},children:void 0!==l?"No folder is open yet. Enter a folder path above and press Open.":"No registered project is available."}):null,a?.error!==null&&a?.error!==void 0?(0,n.jsxs)("div",{className:"files-error",role:"alert",style:{marginLeft:sk(t)},children:[(0,n.jsx)("span",{children:a.error}),(0,n.jsx)("button",{type:"button",className:"files-retry",onClick:()=>{T(e)},children:"Retry"})]}):null,a?.truncated===!0?(0,n.jsxs)("div",{className:"files-note files-warning",role:"status",style:{paddingLeft:sk(t)+18},children:["Showing only the first ",a.entries.length," entries — this folder contains more."]}):null,a?.entries.map(e=>((e,t)=>{let a=sk(t),l=k.has(e.path),s="This link can't be opened from this folder.";if("directory"===e.kind){let i=x[e.path];return(0,n.jsxs)("div",{className:"tr-row-wrap",children:[(0,n.jsxs)("div",{className:"tr-dir-line",style:{paddingLeft:a},children:[(0,n.jsx)("button",{className:"tr-caret-btn",type:"button",tabIndex:-1,disabled:!e.readable,"aria-label":`${l?"Collapse":"Expand"} folder: ${e.name}`,onClick:()=>(e=>{if(!e.readable)return;let t=k.has(e.path);N(t=>{let n=new Set(t);return n.has(e.path)?n.delete(e.path):n.add(e.path),n}),t||void 0!==x[e.path]||T(e.path)})(e),title:e.readable?`${l?"Collapse":"Expand"} ${e.path}`:s,children:(0,n.jsx)("span",{className:"tr-caret","data-open":l,children:(0,n.jsx)(j.Icons.chevronR,{size:11})})}),(0,n.jsxs)("button",{className:"tr-row tr-dir-enter",role:"treeitem","aria-level":t+1,"aria-selected":v===e.path,"data-active":v===e.path,"data-readable":e.readable,"data-path":e.path,type:"button","aria-disabled":!e.readable||void 0,"aria-describedby":e.readable?void 0:$,"aria-expanded":l,onClick:()=>{e.readable&&L(e.path)},title:e.readable?e.path:s,children:[(0,n.jsx)("span",{className:"fi-fallback",style:{color:"var(--accent)"},children:(0,n.jsx)(j.Icons.folder,{size:14})}),(0,n.jsx)("span",{className:"tr-name tr-folder",children:e.name}),e.symlink?(0,n.jsx)("span",{className:"tr-badge",children:"link"}):null]})]}),l?P(e.path,t+1,i):null]},e.path)}return(0,n.jsxs)("button",{className:"tr-row tr-file",role:"treeitem","aria-level":t+1,"aria-selected":f===e.path,"data-active":f===e.path,"data-readable":e.readable,"data-path":e.path,style:{paddingLeft:a},type:"button","aria-disabled":!e.readable||void 0,"aria-describedby":e.readable?void 0:$,onClick:()=>{e.readable&&(g(e.path),I.current?.(e.path,u??d))},title:e.readable?e.path:s,children:[(0,n.jsx)("span",{className:"tr-caret tr-caret-ghost","aria-hidden":"true",children:(0,n.jsx)(j.Icons.chevronR,{size:11})}),(0,n.jsx)(sm,{name:e.name}),(0,n.jsx)("span",{className:"tr-name",children:e.name}),e.symlink?(0,n.jsx)("span",{className:"tr-badge",children:"link"}):null,(0,n.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,a=0;for(;n>=1024&&a<t.length-1;)n/=1024,a+=1;let l=0===a?n.toFixed(0):n.toFixed(n>=10?1:2);return`${l} ${t[a]}`}(e.sizeBytes)})]},e.path)})(e,t)),void 0===a||a.loading||null!==a.error||null!==a.notice||0!==a.entries.length?null:(0,n.jsx)("div",{className:"files-note",role:"status",style:{paddingLeft:sk(t)+18},children:"Empty folder."})]});return null!==f?(0,n.jsx)(sw,{root:u??d,path:f,onOpenInEditor:s,onClose:()=>{R.current=f,g(null),I.current?.(null,u??d)}}):(0,n.jsxs)("div",{className:"files",ref:E,tabIndex:-1,children:[void 0!==l?(0,n.jsxs)("form",{className:"files-root-bar",role:"group","aria-label":"Folder root",onSubmit:e=>{e.preventDefault(),M(h)},children:[(0,n.jsx)("button",{type:"button",className:"files-root-up",onClick:q,disabled:null===v&&null===sj(u??d),title:"Open parent folder","aria-label":"Open parent folder",children:(0,n.jsx)(j.Icons.arrowUp,{size:13})}),(0,n.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:h,onChange:e=>p(e.target.value)}),(0,n.jsx)("button",{type:"submit",className:"files-root-open",title:"Open this folder",children:"Open"})]}):null,(0,n.jsx)("button",{className:"files-refresh",type:"button",onClick:()=>C(e=>e+1),title:"Refresh folder","aria-label":"Refresh folder",children:(0,n.jsx)(j.Icons.reset,{size:13})}),(0,n.jsx)("span",{id:$,className:"visually-hidden",children:"This link can't be opened from this folder."}),(0,n.jsx)("div",{className:"tr files-tree",role:"tree","aria-label":"Files",tabIndex:-1,onKeyDown:e=>{if(!sN.has(e.key))return;let t=e.target,n=t instanceof HTMLElement?t.closest("button.tr-row"):null;if(null===n)return;let a=Array.from(e.currentTarget.querySelectorAll("button.tr-row")),l=a.indexOf(n);l<0||(e.preventDefault(),function(e,t,n){let a=e[t];if(void 0===a)return;let l=a.closest(".tr-row-wrap")?.querySelector("button.tr-caret-btn");if("ArrowDown"===n)e[t+1]?.focus();else if("ArrowUp"===n)e[t-1]?.focus();else if("Home"===n)e[0]?.focus();else if("End"===n)e[e.length-1]?.focus();else if("ArrowRight"===n){let n=a.getAttribute("aria-expanded");"false"===n?l?.click():"true"===n&&e[t+1]?.focus()}else"ArrowLeft"===n&&("true"===a.getAttribute("aria-expanded")?l?.click():function(e,t){let n=Number(e[t]?.getAttribute("aria-level")??"1");for(let a=t-1;a>=0;a-=1)if(Number(e[a]?.getAttribute("aria-level")??"1")<n)return void e[a]?.focus()}(e,t))}(a,l,e.key))},children:P(v??"",0)})]})}function sC(e){return e instanceof w.ApiError||e instanceof Error?e.message:"The file could not be loaded."}function sI(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e))}function sE({root:e,file:t}){let[l,s]=(0,a.useState)(""),[i,r]=(0,a.useState)(""),[o,c]=(0,a.useState)(null),[d,u]=(0,a.useState)(null),[m,h]=(0,a.useState)(void 0!==e&&void 0!==t),[p,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(null),[b,x]=(0,a.useState)(null),y=void 0!==e&&e.length>0&&void 0!==t&&t.length>0,k=y&&l!==i;(0,a.useEffect)(()=>{if(!y){s(""),r(""),c(null),u(null),h(!1),f(!1),v(null),x(null);return}let n=!1;return h(!0),v(null),x(null),(0,w.fetchFilesContent)(e,t).then(e=>{n||(s(e.content),r(e.content),c(e.modifiedAt),u(e.maxBytes))}).catch(e=>{n||v(sC(e))}).finally(()=>{n||h(!1)}),()=>{n=!0}},[y,e,t]);let N=async()=>{if(y&&k&&!p){f(!0),v(null),x(null);try{let n=await (0,w.saveFilesContent)({root:e,path:t,content:l,expectedModifiedAt:o??void 0});s(n.content),r(n.content),c(n.modifiedAt),u(n.maxBytes),x(`Saved ${sI(n.modifiedAt)}`)}catch(e){v(sC(e))}finally{f(!1)}}},S=(0,a.useMemo)(()=>y?m?"Loading file…":p?"Saving…":null!==g?g:null!==b?b:k?"Unsaved changes":null!==o?`Saved ${sI(o)}`:"Ready":"Open a file from the Files window to start editing.",[k,g,y,m,o,b,p]);return(0,n.jsxs)("div",{className:"editor",children:[(0,n.jsxs)("div",{className:"ed-tabs mono",children:[(0,n.jsxs)("span",{className:"ed-tab active",children:[(0,n.jsx)(j.Icons.editor,{size:12})," ",t??"Editor"]}),(0,n.jsx)("span",{className:"spacer"}),y?(0,n.jsx)("button",{type:"button",className:"ed-save",onClick:()=>void N(),disabled:!k||m||p,children:"Save"}):null]}),(0,n.jsxs)("div",{className:"ed-meta",children:[(0,n.jsx)("span",{className:"ed-status",role:null!==g?"alert":"status",children:S}),null!==d?(0,n.jsxs)("span",{className:"ed-limit mono",children:["Limit ",d.toLocaleString()," B"]}):null]}),y?(0,n.jsx)("textarea",{className:"ed-textarea mono","aria-label":void 0!==t?`Editor: ${t}`:"Editor",value:l,onChange:e=>{s(e.target.value),null!==b&&x(null)},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"s"===e.key.toLowerCase()&&(e.preventDefault(),N())},disabled:m||p||null!==g,spellCheck:!1}):(0,n.jsxs)("div",{className:"ed-empty",role:"note",children:["Choose a file from the Files window and use ",(0,n.jsx)("strong",{children:"Open in editor"}),"."]})]})}async function sR(e,t){let n=(t?.method??"GET").toUpperCase(),a="GET"!==n&&"HEAD"!==n,l=await fetch(e,{...t,headers:{Accept:"application/json",...a?{"Content-Type":"application/json"}:{},...a?{"X-Keiko-CSRF":"1"}:{},...t?.headers??{}}});if(!l.ok){let e="INTERNAL",t=`HTTP ${l.status.toString()}`;try{let n=await l.json();e=n.error.code,t=n.error.message}catch{}throw new w.ApiError(e,t,l.status)}if(204!==l.status)return l.json()}async function s$(e){return sR(`/api/browser/status?port=${encodeURIComponent(String(e))}`)}async function sT(e){return sR("/api/browser/sessions",{method:"POST",body:JSON.stringify({port:e})})}async function sA(e){await sR(`/api/browser/sessions/${encodeURIComponent(e)}`,{method:"DELETE"})}async function sM(e,t){return sR(`/api/browser/sessions/${encodeURIComponent(e)}/navigate`,{method:"POST",body:JSON.stringify({url:t})})}async function sL(e){return sR(`/api/browser/sessions/${encodeURIComponent(e)}/screenshot`,{method:"POST",body:JSON.stringify({})})}async function sq(e,t){return sR(`/api/browser/sessions/${encodeURIComponent(e)}/apply`,{method:"POST",body:JSON.stringify({captureSeq:t})})}async function sP(e){return sR(`/api/browser/sessions/${encodeURIComponent(e)}/content`,{method:"POST",body:JSON.stringify({})})}function sD(e){return e instanceof w.ApiError?{code:e.code,message:e.message}:e instanceof Error?{code:"INTERNAL",message:e.message}:{code:"INTERNAL",message:"Unexpected error."}}function sF(e){let t=e.cdpPort??9222,l=e.url??"http://localhost:5173",[s,i]=(0,a.useState)(String(t)),[r,o]=(0,a.useState)(l),[c,d]=(0,a.useState)(null),[u,m]=(0,a.useState)(null),[h,p]=(0,a.useState)(!1),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(null),[x,y]=(0,a.useState)([]),[w,j]=(0,a.useState)(null),[k,N]=(0,a.useState)(null),[S,C]=(0,a.useState)(null),I=(0,a.useRef)(null),E=(0,a.useCallback)(()=>{b(null)},[]),R=(0,a.useCallback)(e=>{y(t=>{let n=[...t,e];return n.length>50?n.slice(n.length-50):n}),"navigated"===e.kind&&"string"==typeof e.payload.originOnly&&C(e.payload.originOnly),"error"===e.kind&&b({code:"string"==typeof e.payload.code?e.payload.code:"INTERNAL",message:"string"==typeof e.payload.message?e.payload.message:"Error."})},[]);(0,a.useEffect)(()=>{var e;if(null===c){I.current?.close(),I.current=null;return}let t=new EventSource((e=c.sessionId,`/api/browser/sessions/${encodeURIComponent(e)}/events`));for(let e of["session-opened","navigated","screenshot-captured","page-content-captured","session-closed","trust-warning","error"])t.addEventListener(`browser:${e}`,e=>{try{let t=JSON.parse(e.data);R(t)}catch{}});return I.current=t,()=>{t.close(),I.current=null}},[c,R]);let $=(0,a.useCallback)(async()=>{E(),p(!0);try{let e=Number.parseInt(s,10),t=await s$(e);m(t)}catch(e){b(sD(e))}finally{p(!1)}},[s,E]),T=(0,a.useCallback)(async()=>{E(),p(!0);try{let e=Number.parseInt(s,10),t=await sT(e);d(t),y([]),N(null),C(null)}catch(e){b(sD(e))}finally{p(!1)}},[s,E]),A=(0,a.useCallback)(async()=>{if(null!==c){E(),p(!0);try{await sA(c.sessionId),d(null),j(null),N(null),C(null)}catch(e){b(sD(e))}finally{p(!1)}}},[c,E]),M=(0,a.useCallback)(async()=>{if(null!==c){E(),p(!0);try{let e=await sM(c.sessionId,r);C(e.originOnly)}catch(e){b(sD(e))}finally{p(!1)}}},[c,r,E]),L=(0,a.useCallback)(async()=>{if(null!==c){E(),p(!0);try{let e=await sL(c.sessionId);e.persisted||j({seq:e.seq,dataBase64:e.dataBase64})}catch(e){b(sD(e))}finally{p(!1)}}},[c,E]),q=(0,a.useCallback)(async()=>{if(null!==c&&null!==w){E(),p(!0);try{let e=await sq(c.sessionId,w.seq);e.persisted&&N(e.path),j(null)}catch(e){b(sD(e))}finally{p(!1)}}},[c,w,E]),P=(0,a.useCallback)(async()=>{if(null!==c){E(),p(!0);try{await sP(c.sessionId)}catch(e){b(sD(e))}finally{p(!1)}}},[c,E]),D=(0,a.useMemo)(()=>h||null!==c,[h,c]),F=(0,a.useMemo)(()=>h||null===c,[h,c]),z=h||null!==c,O=h||null===w,K=h&&null!==f?f:null!==w?"Screenshot ready (dry-run) — press Apply to persist.":null!==k?`Persisted as ${k}.`:null!==S?`Current origin: ${S}`:null!==u&&null===c?`Reachable: ${u.reachable?"yes":"no"}`:"";return(0,n.jsxs)("div",{className:"browser",children:[(0,n.jsxs)("div",{className:"bw-bar",children:[(0,n.jsx)("span",{className:"bw-dot",style:{background:null===c?"var(--line-strong)":"var(--ok)"},"aria-hidden":"true"}),(0,n.jsxs)("label",{className:"bw-field",children:[(0,n.jsx)("span",{className:"bw-field-label",children:"Port"}),(0,n.jsx)("input",{type:"text",inputMode:"numeric",className:"bw-input",value:s,onChange:e=>i(e.target.value),disabled:null!==c||h})]}),(0,n.jsxs)("label",{className:"bw-field bw-field-url",children:[(0,n.jsx)("span",{className:"bw-field-label",children:"URL"}),(0,n.jsx)("input",{type:"url",className:"bw-input bw-input-url",value:r,onChange:e=>o(e.target.value),disabled:h})]})]}),(0,n.jsxs)("div",{className:"bw-actions",role:"group","aria-label":"Browser actions",children:[(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{z||(g("Checking Chrome…"),$())},"aria-disabled":z,children:"Check"}),(0,n.jsx)("button",{type:"button",className:"bw-btn bw-btn-primary",onClick:()=>{D||(g("Opening session…"),T())},"aria-disabled":D,children:"Open session"}),(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{F||(g("Navigating…"),M())},"aria-disabled":F,children:"Navigate"}),(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{F||(g("Capturing screenshot…"),L())},"aria-disabled":F,children:"Screenshot"}),(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{O||(g("Applying screenshot…"),q())},"aria-disabled":O,children:"Apply"}),(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{F||(g("Capturing HTML…"),P())},"aria-disabled":F,children:"Capture HTML"}),(0,n.jsx)("button",{type:"button",className:"bw-btn bw-btn-danger",onClick:()=>{F||(g("Closing session…"),A())},"aria-disabled":F,children:"Close"})]}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:K}),h&&null!==f?(0,n.jsx)("p",{className:"bw-status",children:f}):null,null!==u&&null===c?(0,n.jsxs)("p",{className:"bw-status",children:["Reachable: ",u.reachable?"yes":"no",null===u.browserVersion?"":` — ${u.browserVersion}`]}):null,null!==S?(0,n.jsxs)("p",{className:"bw-status",children:["Current origin: ",(0,n.jsx)("span",{className:"mono",children:S})]}):null,null!==w?(0,n.jsx)("p",{className:"bw-status",children:"Screenshot ready (dry-run) — press Apply to persist."}):null,null!==k?(0,n.jsxs)("p",{className:"bw-status",children:["Persisted as ",(0,n.jsx)("span",{className:"mono",children:k}),"."]}):null,null!==v?(0,n.jsxs)("div",{className:"bw-error",role:"alert",children:[v.message," ",(0,n.jsxs)("span",{className:"err-code mono",children:["(",v.code,")"]})]}):null,(0,n.jsx)("div",{className:"bw-view",children:null!==w?(0,n.jsx)("img",{className:"bw-screenshot",src:`data:image/png;base64,${w.dataBase64}`,alt:"Pending screenshot preview"}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"ph-stripes","aria-hidden":"true"}),(0,n.jsx)("div",{className:"bw-overlay mono",children:null===c?"No session — choose a port and press Open session":"Session open — use Screenshot to capture a preview"})]})}),(0,n.jsx)("div",{className:"bw-log",role:"log","aria-label":"Browser event log",children:(0,n.jsx)("ul",{className:"bw-log-list",children:x.slice(-10).reverse().map((e,t)=>(0,n.jsxs)("li",{className:"bw-log-item",children:[(0,n.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,n.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 sz(e,t){let n=(t?.method??"GET").toUpperCase(),a="GET"!==n&&"HEAD"!==n,l=await fetch(e,{...t,headers:{Accept:"application/json",...a?{"Content-Type":"application/json"}:{},...a?{"X-Keiko-CSRF":"1"}:{},...t?.headers??{}}});if(!l.ok){let e="INTERNAL",t=`HTTP ${l.status.toString()}`;try{let n=await l.json();e=n.error.code,t=n.error.message}catch{}throw new w.ApiError(e,t,l.status)}if(204!==l.status)return l.json()}async function sO(){return sz("/api/terminal/policy")}async function sK(e,t){let n=new URLSearchParams;return n.set("projectId",e),void 0!==t&&t.length>0&&n.set("path",t),sz(`/api/terminal/directories?${n.toString()}`)}async function sB(e){return sz("/api/terminal/executions",{method:"POST",body:JSON.stringify(e)})}async function s_(e){await sz(`/api/terminal/executions/${encodeURIComponent(e)}`,{method:"DELETE"})}function sU(e){return e instanceof w.ApiError?{code:e.code,message:e.message}:e instanceof Error?{code:"INTERNAL",message:e.message}:{code:"INTERNAL",message:"Unexpected error."}}function sW(e){let[t,l]=(0,a.useState)(null),[s,i]=(0,a.useState)(""),[r,o]=(0,a.useState)(""),[c,d]=(0,a.useState)(e.cwd??""),[u,m]=(0,a.useState)(e.projectPath??""),[h,p]=(0,a.useState)(!1),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(null),[x,y]=(0,a.useState)(null),[w,j]=(0,a.useState)([]),k=(0,a.useRef)(null),N=(0,a.useRef)(!1),S=(0,a.useRef)(null),[C,I]=(0,a.useState)([]);(0,a.useEffect)(()=>{let e=!1;return sO().then(t=>{e||(l(t),i(e=>e.length>0?e:t.commands[0]??""))}).catch(t=>{e||y(sU(t))}),()=>{e=!0}},[]),(0,a.useEffect)(()=>{if(0===u.length)return void I([]);let e=!1;return sK(u,c.length>0?c:void 0).then(t=>{e||I(t.entries)}).catch(()=>{e||I([])}),()=>{e=!0}},[u,c]),(0,a.useEffect)(()=>{let e=new EventSource("/api/terminal/events");k.current=e;let t=e=>{try{let t=JSON.parse(e.data);if("execution-started"===t.kind&&N.current){let e=t.payload;"string"==typeof e.requestId&&e.requestId===S.current&&g(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===S.current&&g(e=>null===e||e!==t.executionId?e:null)}j(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(),k.current=null}},[]);let E=(0,a.useCallback)(async e=>{let t;if(e.preventDefault(),h)return;y(null),b(null),g(null);let n="function"==typeof crypto.randomUUID?crypto.randomUUID():`terminal-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;S.current=n;let a=0===(t=r.trim()).length?[]:t.split(/\s+/);N.current=!0,p(!0);try{let e={projectId:u,command:s,args:a,...c.length>0?{cwd:c}:{},requestId:n},t=await sB(e);b(t)}catch(e){y(sU(e))}finally{N.current=!1,p(!1),S.current=null,g(null)}},[r,s,c,u,h]),R=(0,a.useCallback)(async()=>{if(null!==f)try{await s_(f)}catch(e){y(sU(e))}},[f]),$=(0,a.useMemo)(()=>t?.limits??null,[t]),T=(0,a.useRef)(null),A=(0,a.useRef)(!1);return(0,a.useEffect)(()=>{A.current&&!h&&document.activeElement===document.body&&T.current?.focus(),A.current=h},[h]),(0,n.jsxs)("div",{className:"terminal",children:[(0,n.jsxs)("form",{className:"tm-form",onSubmit:e=>void E(e),children:[(0,n.jsxs)("label",{className:"tm-field",children:[(0,n.jsx)("span",{children:"Project path"}),(0,n.jsx)("input",{type:"text",value:u,onChange:e=>m(e.target.value),placeholder:"/absolute/path/to/project",required:!0})]}),(0,n.jsxs)("label",{className:"tm-field",children:[(0,n.jsx)("span",{children:"Command"}),(0,n.jsx)("select",{value:s,onChange:e=>i(e.target.value),disabled:null===t,required:!0,children:t?.commands.map(e=>(0,n.jsx)("option",{value:e,children:e},e))})]}),(0,n.jsxs)("label",{className:"tm-field",children:[(0,n.jsx)("span",{children:"Args (space-separated)"}),(0,n.jsx)("input",{type:"text",value:r,onChange:e=>o(e.target.value),placeholder:"e.g. -la src"})]}),(0,n.jsxs)("label",{className:"tm-field",children:[(0,n.jsx)("span",{children:"Working directory (optional)"}),(0,n.jsx)("input",{type:"text",value:c,onChange:e=>d(e.target.value),placeholder:"(project root)",list:"tm-cwd-suggestions"}),(0,n.jsx)("datalist",{id:"tm-cwd-suggestions",children:C.map(e=>(0,n.jsx)("option",{value:e.path},e.path))})]}),(0,n.jsxs)("div",{className:"tm-actions",children:[(0,n.jsx)("button",{type:"submit",className:"tm-action","data-primary":"true",ref:T,disabled:null===t,"aria-disabled":h||null===t,children:h?"Running…":"Run"}),h?(0,n.jsx)("button",{type:"button",className:"tm-action","aria-disabled":null===f,onClick:()=>void R(),children:"Cancel"}):null]}),null!==$?(0,n.jsxs)("p",{className:"tm-limits",children:["Limits: ",(0,ak.formatBytes)($.maxOutputBytes)," output ·"," ",(0,ak.formatMs)($.defaultTimeoutMs)," timeout"]}):null]}),null!==x?(0,n.jsxs)("div",{className:"tm-error",role:"alert",children:[(0,n.jsxs)("span",{className:"tm-error-text",children:[x.message," ",(0,n.jsxs)("span",{className:"err-code mono",children:["(",x.code,")"]})]}),(0,n.jsx)("button",{type:"button",className:"tm-error-dismiss","aria-label":"Dismiss error",onClick:()=>y(null),children:"✕"})]}):null,(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:null!==v?`Command finished: exit ${String(v.exitCode)}, ${String(v.durationMs)} ms${v.truncated?", output truncated":""}${v.timedOut?", timed out":""}`:""}),null!==v?(0,n.jsxs)("div",{className:"tm-result",children:[(0,n.jsxs)("div",{className:"tm-badges",children:[(0,n.jsxs)("span",{className:0===v.exitCode?"tm-badge tm-badge-ok":"tm-badge tm-badge-fail",children:["exit ",String(v.exitCode)]}),(0,n.jsxs)("span",{className:"tm-badge",children:[v.durationMs," ms"]}),v.truncated?(0,n.jsx)("span",{className:"tm-badge tm-badge-warn",children:"truncated"}):null,v.timedOut?(0,n.jsx)("span",{className:"tm-badge tm-badge-warn",children:"timed out"}):null]}),v.stdout.length>0?(0,n.jsx)("pre",{className:"tm-stdout",children:v.stdout}):null,v.stderr.length>0?(0,n.jsx)("pre",{className:"tm-stderr",children:v.stderr}):null]}):null,(0,n.jsx)("ul",{className:"tm-events",role:"log","aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false","aria-label":"Recent terminal events",children:w.map((e,t)=>{var a;let l;return(0,n.jsxs)("li",{className:"tm-event",children:[(0,n.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,n.jsx)("span",{className:"tm-event-detail",children:(l=(a=e).payload,"execution-completed"===a.kind?["number"==typeof l.exitCode||null===l.exitCode?`exit ${String(l.exitCode)}`:"","number"==typeof l.durationMs?`${String(l.durationMs)}ms`:""].filter(Boolean).join(" · "):"execution-failed"===a.kind?"string"==typeof l.code?l.code:"":"execution-started"===a.kind&&"string"==typeof l.command?l.command:"")})]},`${e.executionId}-${String(t)}-${e.kind}`)})})]})}function sH(e){return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function sY(e){return e instanceof w.ApiError?{code:e.code,message:e.message}:e instanceof Error?{code:"INTERNAL",message:e.message}:{code:"INTERNAL",message:"Unexpected error."}}function sJ(e){return("dry-run"===e.status||"fix-proposed"===e.status)&&void 0!==e.proposedDiff&&void 0===e.appliedAt}function sG(e){return void 0!==e.proposedDiff&&""!==e.proposedDiff}function sV({href:e,hasManifest:t,error:a}){return t?(0,n.jsx)("a",{className:"rv-evidence-link",href:e,target:"_blank",rel:"noopener noreferrer",children:"Evidence"}):null!==a?(0,n.jsxs)("span",{className:"rv-evidence-link rv-evidence-error",role:"alert",children:["Evidence error: ",a.message]}):(0,n.jsx)("button",{type:"button",className:"rv-evidence-link rv-evidence-disabled",disabled:!0,children:"Evidence"})}function sX({tokens:e}){return(0,n.jsx)(n.Fragment,{children:e.map((e,t)=>(0,n.jsx)("span",{className:`hl-${e[0]}`,children:e[1]},t))})}function sQ({line:e,lang:t}){let a,l="add"===e.kind?"+":"del"===e.kind?"−":"ctx"===e.kind?"·":"",s="ctx"===e.kind?"":` rv-${e.kind}`;if("meta"!==e.kind&&"code"!==t){let l=sv(e.text,sp(t))[0]??[];a=(0,n.jsx)(sX,{tokens:l})}else a=e.text;return(0,n.jsxs)("div",{className:`rv-line${s}`,children:[(0,n.jsx)("span",{className:"rv-sr-only",children:{add:"Added line",del:"Deleted line",ctx:"Context line",meta:"Diff metadata"}[e.kind]}),(0,n.jsx)("span",{className:"rv-num-old rv-num",children:e.oldLine??""}),(0,n.jsx)("span",{className:"rv-num-new rv-num",children:e.newLine??""}),(0,n.jsx)("span",{className:"rv-gutter","aria-hidden":"true",children:l}),(0,n.jsx)("code",{className:"rv-src",children:a})]})}function sZ({hunk:e,lang:t}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"rv-hunk mono","aria-label":`Hunk header ${e.header}`,children:[(0,n.jsx)("span",{className:"rv-sr-only",children:"Hunk header"}),e.header]}),e.lines.map((e,a)=>(0,n.jsx)(sQ,{line:e,lang:t},a))]})}function s0({file:e,index:t,changedFiles:a,sectionRef:l}){let s=a.find(t=>t.path===e.path),i=e.path.includes(".")?e.path.split(".").pop()??"code":"code";return(0,n.jsxs)("section",{id:`rv-file-${t}`,"aria-labelledby":`rv-file-${t}-h`,ref:l,children:[(0,n.jsxs)("h3",{id:`rv-file-${t}-h`,className:"rv-file mono",children:[(0,n.jsx)("span",{className:"rv-path",children:e.path}),void 0!==e.oldPath&&(0,n.jsxs)("span",{className:"rv-oldpath",children:[" (was ",e.oldPath,")"]}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsxs)("span",{className:"rv-stat add",children:["+",e.addedLines]}),(0,n.jsxs)("span",{className:"rv-stat del",children:["−",e.removedLines]}),s?.elevatedReview===!0&&(0,n.jsx)("span",{className:"rv-elevated","aria-label":"Elevated review",children:"!"})]}),(0,n.jsx)("div",{className:"rv-code mono",children:e.hunks.map((e,t)=>(0,n.jsx)(sZ,{hunk:e,lang:i},t))})]})}function s1({runId:e,onRunIdSubmit:t}){let[l,s]=(0,a.useState)(null),[i,r]=(0,a.useState)(!1),[o,c]=(0,a.useState)(null),[d,u]=(0,a.useState)(!1),[m,h]=(0,a.useState)(null),[p,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(null),[b,x]=(0,a.useState)(null),[y,j]=(0,a.useState)(""),[k,N]=(0,a.useState)(!1),S=(0,a.useRef)(null);(0,a.useEffect)(()=>()=>{null!==S.current&&window.clearTimeout(S.current)},[]),(0,a.useEffect)(()=>{if(void 0===e||""===e)return;let t=!1;return u(!0),h(null),s(null),r(!1),c(null),x(null),Promise.allSettled([(0,w.fetchRunReport)(e),(0,w.fetchEvidenceManifest)(e)]).then(([e,n])=>{if(!t){if("fulfilled"===n.status)r(!0),c(null);else{let e=sY(n.reason);r(!1),c("NOT_FOUND"===e.code?null:e)}if("fulfilled"===e.status){s(e.value.report),u(!1);return}h(sY(e.reason)),u(!1)}}),()=>{t=!0}},[e]);let C=`/api/evidence/${encodeURIComponent(e??"")}`,I=(0,a.useMemo)(()=>l?.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 a=e,l=!1;if(n>524288){l=!0;let n=t.encode(e),s=new TextDecoder().decode(n.slice(0,524288)),i=s.lastIndexOf("\n");a=-1===i?s:s.slice(0,i+1)}let s=a.split("\n"),i=s.length>0&&""===s[s.length-1]?s.slice(0,-1):s,r=[],o=null,c=null,d=0,u=0,m=()=>{null!==o&&null!==c&&o.hunks.push(c),c=null},h=()=>{m(),null!==o&&(r.length<400?r.push(o):l=!0),o=null},p=0;for(;p<i.length;){let e=i[p]??"";if(e.startsWith("diff --git ")){h();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],a=sH(`b/${n}`),l=sH(`a/${e}`),s={path:a,hunks:[],addedLines:0,removedLines:0};l!==a&&(s.oldPath=l),o=s}p++;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++,p++;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++,p++;continue}if(e.startsWith("\\ ")){let t={kind:"meta",oldLine:null,newLine:null,text:e};c.lines.push(t),p++;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++,p++;continue}}if(e.startsWith("--- ")){let t=e.slice(4);if("/dev/null"!==t&&null===o)h(),o={path:sH(t),hunks:[],addedLines:0,removedLines:0};else if("/dev/null"!==t&&null!==o){let e=sH(t);e!==o.path&&(o.oldPath=e)}p++;continue}if(e.startsWith("+++ ")){let t=e.slice(4);"/dev/null"!==t&&null!==o?o.path=sH(t):"/dev/null"!==t&&(h(),o={path:sH(t),hunks:[],addedLines:0,removedLines:0}),p++;continue}if(e.startsWith("@@ ")){null===o&&(o={path:"(unknown)",hunks:[],addedLines:0,removedLines:0}),m();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=t?.oldStart??1,u=t?.newStart??1,c={header:e,lines:[]},p++;continue}p++}return h(),{files:r,truncated:l,totalBytes:n}}(l.proposedDiff):null,[l?.proposedDiff]),E=l?.changedFiles??[],R=(0,a.useMemo)(()=>({added:I?.files.reduce((e,t)=>e+t.addedLines,0)??0,removed:I?.files.reduce((e,t)=>e+t.removedLines,0)??0}),[I]),$=null!==I&&I.files.length>0?Math.min(b??0,I.files.length-1):null,T=null!==$?I?.files[$]:void 0,A=l?.status==="running";return void 0===e||""===e?(0,n.jsxs)("section",{className:"review rv-empty","aria-label":"Diff review",children:[(0,n.jsx)("h2",{className:"rv-empty-h",children:"Review"}),void 0!==t?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{className:"rv-empty-p",children:"Paste a run ID below to load a proposed diff."}),(0,n.jsxs)("form",{className:"rv-empty-form",onSubmit:e=>{e.preventDefault();let n=y.trim();0!==n.length&&t(n)},children:[(0,n.jsx)("label",{className:"rv-empty-label",htmlFor:"rv-runid-input",children:"Run ID"}),(0,n.jsx)("input",{id:"rv-runid-input",className:"rv-runid-input mono",type:"text",value:y,onChange:e=>j(e.target.value),placeholder:"e.g. 7f3a9c12…"}),(0,n.jsx)("button",{type:"submit",className:"arun-btn",children:"Load run"})]})]}):(0,n.jsx)("p",{className:"rv-empty-p",children:"Enter a run ID in the window configuration to load a proposed diff."})]}):(0,n.jsxs)("section",{className:"review","aria-label":"Diff review",children:[d&&(0,n.jsxs)("div",{className:"rv-loading",role:"status","aria-busy":"true","aria-label":"Loading diff",children:[(0,n.jsx)("div",{className:"rv-skel"}),(0,n.jsx)("div",{className:"rv-skel rv-skel-sm"})]}),!d&&null!==m&&(0,n.jsxs)("div",{role:"alert",className:"rv-error",children:["NOT_FOUND"===m.code?"No run with that ID was found.":(0,n.jsxs)(n.Fragment,{children:[m.message," ",(0,n.jsxs)("span",{className:"err-code mono",children:["(",m.code,")"]})]}),(i||null!==o)&&(0,n.jsx)("span",{className:"rv-error-evidence",children:(0,n.jsx)(sV,{href:C,hasManifest:i,error:o})})]}),(0,n.jsx)("p",{role:"status","aria-live":"polite",className:!d&&null===m&&null!==l&&A?"rv-no-diff":"sr-only",children:!d&&null===m&&null!==l&&A?"Run is still running. The proposed diff will appear when the run completes.":""}),!d&&null===m&&null!==l&&!A&&!sG(l)&&(0,n.jsx)("p",{className:"rv-no-diff",children:"This run has no proposed diff to review."}),!d&&null===m&&null!==l&&sG(l)&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"rv-header",children:[(0,n.jsx)("span",{className:"rv-status mono",children:(0,ak.runStatusLabel)(l.status)}),void 0!==l.modelId&&(0,n.jsx)("span",{className:"rv-model mono",children:l.modelId}),(0,n.jsxs)("span",{className:"rv-counts mono",children:[null!==I&&`${I.files.length} file${1!==I.files.length?"s":""}`," ",(0,n.jsxs)("span",{className:"rv-stat add",children:["+",R.added]})," ",(0,n.jsxs)("span",{className:"rv-stat del",children:["−",R.removed]})]}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsx)(sV,{href:C,hasManifest:i,error:o})]}),null!==I&&I.files.length>0&&null!==$&&void 0!==T&&(0,n.jsxs)("div",{className:"rv-layout",children:[(0,n.jsx)("nav",{className:"rv-filelist","aria-label":"Changed files",children:(0,n.jsx)("ul",{children:I.files.map((e,t)=>{let a=E.find(t=>t.path===e.path),l=$===t;return(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button",className:"rv-filerow",title:e.path,"aria-pressed":l,"aria-controls":l?`rv-file-${t}`:void 0,onClick:()=>{x(t)},children:[(0,n.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,n.jsxs)("span",{className:"rv-stat add",children:["+",e.addedLines]}),(0,n.jsxs)("span",{className:"rv-stat del",children:["−",e.removedLines]}),a?.elevatedReview===!0&&(0,n.jsx)("span",{className:"rv-elevated","aria-label":"Elevated review",children:"!"})]})},e.path)})})}),(0,n.jsxs)("div",{className:"rv-body",children:[(0,n.jsx)(s0,{file:T,index:$,changedFiles:E,sectionRef:()=>void 0},T.path),I.truncated&&(0,n.jsxs)("p",{role:"note",className:"rv-truncated",children:["Diff truncated at 512 KB. Open the"," ",i?(0,n.jsx)("a",{href:C,target:"_blank",rel:"noopener noreferrer",children:"evidence manifest"}):"evidence manifest"," ","for the full record."]})]})]}),(0,n.jsxs)("div",{className:"rv-controls",children:[(0,n.jsx)("span",{role:"status","aria-live":"polite",className:"rv-apply-status",children:p?"Applying…":void 0!==l.appliedAt?"Applied":""}),null!==g&&(0,n.jsx)("span",{role:"alert",className:"rv-apply-error",children:g.message}),void 0!==l.appliedAt?(0,n.jsx)("span",{className:"rv-final mono",children:"Applied"}):sJ(l)?(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":p,onClick:()=>{if(!p){if(!k){N(!0),null!==S.current&&window.clearTimeout(S.current),S.current=window.setTimeout(()=>{N(!1),S.current=null},6e3);return}null!==S.current&&(window.clearTimeout(S.current),S.current=null),N(!1),void 0!==e&&null!==l&&sJ(l)&&!p&&(f(!0),v(null),(0,w.applyRun)(e).then(e=>{s(e.report),f(!1)}).catch(e=>{v(sY(e)),f(!1)}))}},children:p?"Applying…":k?`Confirm apply (${(I?.files.length??0).toString()} file${I?.files.length===1?"":"s"})`:"Apply"}):null]})]})]})}let s2=["run:started","state:transition","model:call:started","model:call:completed","model:call:failed","tool:call:started","tool:call:completed","tool:call:failed","reasoning:trace","patch:proposed","verification:result","run:completed","run:cancelled","run:failed","command:executed","sandbox:configured","patch:applied","browser:session-opened","browser:navigated","browser:screenshot-captured","browser:page-content-captured","browser:session-closed","browser:trust-warning","browser:error","workflow:started","conventions:detected","context:selected","workflow:model:call:started","workflow:model:call:completed","patch:validated","workflow:patch:applied","workflow:verification:result","workflow:completed","workflow:failed","bug:started","bug:failure:parsed","bug:context:selected","bug:model:call:started","bug:model:call:completed","bug:rootcause:proposed","bug:patch:validated","bug:patch:applied","bug:verification:result","bug:completed","bug:failed","ready"],s4=new Set(["run:completed","run:cancelled","run:failed","workflow:completed","workflow:failed","bug:completed","bug:failed"]),s3=new Set(["completed","dry-run","rejected","cancelled","failed","fix-applied","fix-proposed","investigation-only"]),s6={verify:"Verify","explain-plan":"Explain plan","unit-test-generation":"Generate unit tests","bug-investigation":"Investigate bug"};function s5(e,t){return void 0===t||0===t.length?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:e}),(0,n.jsx)("pre",{children:t})]})}function s8({cfg:e={},linkedRoot:t=null,linkedFilePath:l}){var s,i;let r,o=e.runId??null,c="verify"===(s=e.workflow)||"explain-plan"===s||"unit-test-generation"===s||"bug-investigation"===s?s:null,d=e.model??"",u=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}}(e.inputJson),m=function(e){let[t,n]=(0,a.useState)([]),[l,s]=(0,a.useState)("connecting"),[i,r]=(0,a.useState)(null),o=(0,a.useRef)(-1);return(0,a.useEffect)(()=>{if(null===e)return;n([]),s("connecting"),r(null),o.current=-1;let t=null,a=!1,l=`/api/runs/${encodeURIComponent(e)}/events`;(t=new EventSource(o.current>=0?`${l}?lastEventId=${o.current.toString()}`:l)).onopen=()=>{a||(s("live"),r(null))},t.onerror=()=>{a||(s("error"),r("Stream disconnected. Attempting to reconnect…"))};let i=e=>{let l;if(!a){try{l=JSON.parse(e.data)}catch{return}o.current=l.seq,n(e=>[...e,l]),s4.has(l.type)&&(s("terminal"),t?.close())}};for(let e of s2)t.addEventListener(e,i);return()=>{a=!0,t?.close()}},[e]),{events:t,status:l,error:i}}(o),[h,p]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(null),[x,y]=(0,a.useState)(!1),[k,N]=(0,a.useState)(null),[S,C]=(0,a.useState)(null),[I,E]=(0,a.useState)(!1),R=(0,a.useRef)(null),$=(0,a.useRef)(null),T=(0,a.useCallback)(async()=>{if(null!==o){b(null);try{let e=await (0,w.fetchRunReport)(o);p(e.report),g(null)}catch(e){if(e instanceof w.ApiError&&404===e.status){try{let e=await (0,w.fetchEvidenceManifest)(o);g(e.manifest),p(null)}catch(e){b(e instanceof Error?e.message:"Unable to load evidence.")}return}b(e instanceof Error?e.message:"Unable to load run report.")}}},[o]);(0,a.useEffect)(()=>{T()},[T]),(0,a.useEffect)(()=>{"terminal"===m.status&&T()},[T,m.status]),(0,a.useEffect)(()=>{let e=!1;if(0!==d.length)return(0,w.fetchModels)().then(t=>{e||C(t.models.find(e=>e.id===d)?.costClass??null)}).catch(()=>{e||C(null)}),()=>{e=!0}},[d]);let A=(0,a.useMemo)(()=>(function(e,t){let n=t?.usage?.promptTokens??0,a=t?.usage?.completionTokens??0,l=t?.usage?.latencyMs??0,s=+(t?.usage!==void 0);if(s>0)return{promptTokens:n,completionTokens:a,latencyMs:l,requestCount:s};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,a=e.latencyMs;return"number"==typeof t&&"number"==typeof n&&"number"==typeof a?{promptTokens:t,completionTokens:n,latencyMs:a,requestCount:1}:null}(t);null!==e&&(n+=e.promptTokens,a+=e.completionTokens,l+=e.latencyMs,s+=e.requestCount)}return{promptTokens:n,completionTokens:a,latencyMs:l,requestCount:s}})(m.events,h),[m.events,h]),M=h?.durationMs??f?.run.durationMs??(m.events.length>0?Math.max(0,Date.now()-Number(new Date(m.events[0]?.ts??Date.now()))):0),L=null!==h?h.status:null!==f?f.run.outcome:"loading",q=null!==h?(0,ak.runStatusLabel)(h.status):null!==f?(0,ak.outcomeLabel)(f.run.outcome):"Loading…",P=null!==h&&s3.has(h.status),D=null!==h&&void 0!==h.proposedDiff&&void 0===h.appliedAt&&("unit-test-generation"===c&&"dry-run"===h.status||"bug-investigation"===c&&"fix-proposed"===h.status),F=!P&&h?.status==="running",z=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}(h?.proposedDiff),O=(0,a.useRef)(!1);(0,a.useEffect)(()=>{O.current&&!F&&document.activeElement===document.body&&$.current?.focus(),O.current=F},[F]),(0,a.useEffect)(()=>()=>{null!==R.current&&window.clearTimeout(R.current)},[]);let K=async()=>{if(null!==o){b(null);try{await (0,w.cancelRun)(o),await T()}catch(e){b(e instanceof Error?e.message:"Unable to cancel run.")}}},B=async()=>{if(null!==o&&D&&!x){y(!0),N(null);try{let e=await (0,w.applyRun)(o);p(e.report)}catch(e){N(e instanceof Error?e.message:"Unable to apply run.")}finally{y(!1)}}};return null===o||null===c?(0,n.jsxs)("div",{className:"arun arun-empty",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Agent run is not configured."}),(0,n.jsx)("p",{children:"Open a new Agent window from the launcher to start a workflow."})]}):(0,n.jsxs)("div",{className:"arun arun-real",children:[(0,n.jsxs)("div",{className:"arun-head",children:[(0,n.jsx)("span",{className:"arun-role",children:s6[c]}),d.length>0?(0,n.jsx)("span",{className:"ag-model mono",children:d}):null,null!==S?(0,n.jsx)("span",{className:"arun-gov",title:"Model cost class",children:(0,ak.costClassLabel)(S)}):null,(0,n.jsx)("span",{className:"spacer"}),(0,n.jsxs)("span",{className:"arun-status",children:[(0,n.jsx)("span",{className:"dot","data-live":h?.status==="running","data-status":L}),q]})]}),(0,n.jsxs)("div",{className:"arun-summary",role:"status","aria-live":"polite",children:[(0,n.jsx)("strong",{children:function(e,t,n){if(null===t&&null===n)return"Loading run state…";let a=null===e?"Agent run":s6[e];return t?.status==="running"?`${a} is running.`:t?.status==="dry-run"?`${a} produced a reviewable dry-run.`:t?.status==="fix-proposed"?`${a} proposed a fix.`:t?.status==="fix-applied"?`${a} applied changes.`:t?.status==="investigation-only"?`${a} completed without a patch.`:t?.status==="failed"||t?.status==="rejected"?`${a} failed.`:t?.status==="cancelled"?`${a} was cancelled.`:null!==t?`${a} completed.`:`${a} evidence loaded: ${n?.run.outcome??"unknown"}.`}(c,h,f)}),(0,n.jsxs)("span",{className:"mono",title:o,children:["run ",o.slice(0,8)]})]}),(0,n.jsxs)("div",{className:"arun-meters",children:[(0,n.jsxs)("div",{className:"arun-meter",children:[(0,n.jsx)("span",{className:"arun-mk",children:"Elapsed"}),(0,n.jsx)("span",{className:"arun-mv mono",children:(0,ak.formatMs)(M)})]}),(0,n.jsxs)("div",{className:"arun-meter",children:[(0,n.jsx)("span",{className:"arun-mk",children:"Usage"}),(0,n.jsx)("span",{className:"arun-mv mono",children:0===A.requestCount?"No model usage":`${(0,ak.formatTokens)(A.promptTokens+A.completionTokens)} tok`})]}),(0,n.jsxs)("div",{className:"arun-meter",children:[(0,n.jsx)("span",{className:"arun-mk",children:"Latency"}),(0,n.jsx)("span",{className:"arun-mv mono",children:0===A.requestCount?"—":(0,ak.formatMs)(A.latencyMs)})]})]}),(0,n.jsxs)("div",{className:"arun-perms",children:[(0,n.jsxs)("span",{className:"arun-perm","data-on":null!==t,title:null!==t?t:e.workspaceRoot??void 0,children:[(0,n.jsx)(j.Icons.files,{size:11}),(0,n.jsx)("span",{className:"arun-perm-path",children:null!==t?t:e.workspaceRoot??"no workspace"})]}),void 0!==l?(0,n.jsxs)("span",{className:"arun-perm","data-on":!0,title:l,children:[(0,n.jsx)(j.Icons.files,{size:11}),(0,n.jsx)("span",{className:"arun-perm-path",children:l})]}):null]}),null!==u?(0,n.jsxs)("details",{className:"arun-input",children:[(0,n.jsx)("summary",{children:"Run input"}),(0,n.jsx)("pre",{children:JSON.stringify(u,null,2)})]}):null,(0,n.jsxs)("div",{className:"arun-log",role:"log","aria-live":"polite","aria-label":"Run events",children:["error"===m.status&&null!==m.error?(0,n.jsxs)("div",{className:"arun-log-row",children:[(0,n.jsx)("span",{className:"arun-log-ico",children:(0,n.jsx)(j.Icons.reset,{size:12})}),(0,n.jsx)("span",{className:"arun-log-text",children:m.error})]}):null,0===m.events.length?"error"===m.status?null:(0,n.jsxs)("div",{className:"arun-log-row",children:[(0,n.jsx)("span",{className:"arun-log-ico",children:(0,n.jsx)(j.Icons.reset,{size:12})}),(0,n.jsx)("span",{className:"arun-log-text",children:"connecting"===m.status?"Connecting to run events…":"Waiting for run events…"})]}):m.events.slice().reverse().slice(0,50).map(e=>{let t;return(0,n.jsxs)("div",{className:"arun-log-row",children:[(0,n.jsx)("span",{className:"arun-log-ico",children:(0,n.jsx)(j.Icons.spark,{size:12})}),(0,n.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,ak.formatBytes)(e.contextBytes)})`;case"model:call:completed":return`Model call completed (${(0,ak.formatTokens)(e.usage.promptTokens+e.usage.completionTokens)} tokens)`;case"model:call:failed":return`Model call failed: ${e.message}`;case"patch:proposed":return`Patch proposed (${(0,ak.formatBytes)(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,ak.formatTokens)(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,ak.formatTokens)(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,n.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!==h?(0,n.jsxs)("div",{className:"arun-results",children:[void 0===h.report?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Report"}),(0,n.jsx)("pre",{children:h.report})]}),void 0===h.overallStatus||void 0===h.results?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Verification"}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Status"}),(0,n.jsx)("strong",{children:h.overallStatus})]}),h.results.slice(0,8).map(e=>(0,n.jsxs)("div",{className:"arun-check-row",children:[(0,n.jsx)("span",{children:e.kind}),(0,n.jsx)("span",{className:"mono",children:e.status})]},`${e.kind}:${e.command}`))]}),s5("Failure",h.failureReason),s5("Covered behavior",h.coveredBehavior),s5("Known gaps",h.knownGaps),s5("Verification note",h.verificationSkipReason),function(e){let t=e.hypothesis;if(void 0===t)return null;let a=[["Root cause",t.rootCause],["Regression test",t.regressionTestStrategy],["Uncertainty",t.uncertainty],["Confidence",t.confidence]].filter(e=>"string"==typeof e[1]&&e[1].length>0);return 0===a.length?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Hypothesis"}),a.map(([e,t])=>(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:e}),(0,n.jsx)("strong",{children:t})]},e))]})}(h),void 0===(i=h.nextActions)||0===i.length?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Next actions"}),i.map(e=>(0,n.jsx)("div",{className:"arun-check-row",children:(0,n.jsx)("span",{children:e})},e))]}),void 0!==h.dryRunPreview?(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Dry-run preview"}),(0,n.jsx)("pre",{children:h.dryRunPreview})]}):null,void 0!==h.proposedDiff?(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Proposed diff"}),(0,n.jsx)("pre",{children:h.proposedDiff})]}):null,void 0===(r=h.verificationSummary)?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Verification"}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Status"}),(0,n.jsx)("strong",{children:r.overallStatus})]}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Duration"}),(0,n.jsx)("strong",{children:(0,ak.formatMs)(r.durationMs)})]}),r.results.slice(0,5).map(e=>(0,n.jsxs)("div",{className:"arun-check-row",children:[(0,n.jsx)("span",{children:e.kind}),(0,n.jsx)("span",{className:"mono",children:e.status})]},`${e.kind}:${e.command}`))]}),void 0!==h.applyReport?(0,n.jsxs)("div",{className:"arun-result-card arun-applied",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Applied"}),(0,n.jsx)("pre",{children:JSON.stringify(h.applyReport,null,2)})]}):null]}):null!==f?(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Evidence"}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Outcome"}),(0,n.jsx)("strong",{children:f.run.outcome})]}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Duration"}),(0,n.jsx)("strong",{children:(0,ak.formatMs)(f.run.durationMs)})]})]}):null,null!==v?(0,n.jsx)("div",{className:"arun-error",role:"alert",children:v}):null,null!==k?(0,n.jsx)("div",{className:"arun-error",role:"alert",children:k}):null,(0,n.jsxs)("div",{className:"arun-controls",children:[(0,n.jsx)("a",{className:"arun-btn ghost",href:`/api/evidence/${encodeURIComponent(o)}`,target:"_blank",rel:"noreferrer",ref:$,children:"Evidence"}),D?(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":x,onClick:()=>{if(!x){if(!I){E(!0),null!==R.current&&window.clearTimeout(R.current),R.current=window.setTimeout(()=>{E(!1),R.current=null},6e3);return}null!==R.current&&(window.clearTimeout(R.current),R.current=null),E(!1),B()}},children:x?"Applying…":I?`Confirm apply (${z.toString()} file${1===z?"":"s"})`:"Apply"}):h?.appliedAt!==void 0?(0,n.jsx)("span",{className:"arun-final mono",children:"Applied"}):null,F?(0,n.jsx)("button",{type:"button",className:"arun-btn danger",onClick:()=>void K(),children:"Cancel"}):null]})]})}let s7=[{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 s9(){return(0,n.jsx)("ul",{className:"integ","aria-label":"Integrations",children:s7.map(e=>(0,n.jsxs)("li",{className:"integ-row",children:[(0,n.jsx)("span",{className:"integ-glyph mono",children:e.glyph}),(0,n.jsxs)("span",{className:"integ-text",children:[(0,n.jsx)("span",{className:"integ-name",children:e.name}),(0,n.jsx)("span",{className:"integ-desc",children:e.desc})]}),(0,n.jsx)("span",{className:"integ-status",children:"Not connected — coming soon"})]},e.name))})}let ie={allow:["Allow","var(--accent)"],ask:["Ask","var(--warn)"],deny:["Deny","var(--danger)"]},it={allow:"ask",ask:"deny",deny:"allow"},ia=[{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"}],il=[["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"]],is=[["calendar","Calendar","automations"],["mail","Mail","bell"],["jira","Jira","review"],["docs","Docs","files"]];function ii({policy:e,setPolicy:t}){return(0,n.jsxs)("div",{className:"pol",children:[(0,n.jsx)("div",{className:"pol-hint",children:"Rights an agent inherits when Keiko governs. Tap a decision to cycle through Allow → Ask → Deny."}),e.map(e=>{let a=ie[e.decision];return(0,n.jsxs)("div",{className:"pol-row",children:[(0,n.jsxs)("div",{className:"pol-text",children:[(0,n.jsx)("span",{className:"pol-action",children:e.action}),(0,n.jsx)("span",{className:"pol-scope mono",children:e.scope})]}),(0,n.jsx)("button",{type:"button",className:"pol-dec",style:{color:a[1],borderColor:a[1]},onClick:()=>{let n;return n=e.id,t(e=>e.map(e=>e.id===n?{...e,decision:it[e.decision]}:e))},children:a[0]})]},e.id)})]})}function ir({decide:e}){let[t,l]=(0,a.useState)(!1),s=ia.map(t=>{let n=e(t.kind,t.risk);return{...t,actual:n,pass:n===t.expect}}),i=s.filter(e=>e.pass).length;return(0,n.jsxs)("div",{className:"evl",children:[(0,n.jsxs)("div",{className:"evl-head",children:[(0,n.jsxs)("button",{type:"button",className:"evl-run",onClick:()=>l(!0),children:[(0,n.jsx)(j.Icons.spark,{size:13})," Run evaluation"]}),t&&(0,n.jsxs)("span",{className:"evl-score"+(i===s.length?" ok":""),children:[i,"/",s.length," passed"]})]}),(0,n.jsx)("div",{className:"evl-hint",children:"Mock scenarios against your policy before going autonomous."}),s.map(e=>(0,n.jsxs)("div",{className:"evl-row","data-state":t?e.pass?"pass":"fail":"idle",children:[(0,n.jsx)("span",{className:"evl-ico",children:t?e.pass?(0,n.jsx)(j.Icons.check,{size:13}):(0,n.jsx)(j.Icons.close,{size:13}):(0,n.jsx)("span",{className:"evl-dot"})}),(0,n.jsx)("span",{className:"evl-label",children:e.label}),t&&(0,n.jsx)("span",{className:"evl-res mono",style:{color:ie[e.actual][1]},children:ie[e.actual][0]})]},e.id))]})}function io({bridges:e,setBridges:t}){return(0,n.jsxs)("div",{className:"brg",children:[(0,n.jsx)("div",{className:"evl-hint",children:"What your twin can reach on your behalf."}),is.map(([a,l,s])=>{let i=j.Icons[s],r=e[a];return(0,n.jsxs)("button",{type:"button",className:"brg-row","data-on":r,"aria-pressed":r,onClick:()=>t(e=>({...e,[a]:!e[a]})),children:[(0,n.jsx)("span",{className:"brg-ico",children:(0,n.jsx)(i,{size:16})}),(0,n.jsx)("span",{className:"brg-name",children:l}),(0,n.jsx)("span",{className:"brg-tg"+(r?" on":""),children:(0,n.jsx)("span",{})})]},a)})]})}function ic({persona:e,setPersona:t}){return(0,n.jsxs)("div",{className:"prs",children:[(0,n.jsx)("div",{className:"evl-hint",children:"Keiko adapts behaviour & tools to who is at the wheel."}),il.map(([a,l])=>(0,n.jsxs)("button",{type:"button",className:"prs-row","data-on":e===a,"aria-pressed":e===a,onClick:()=>t(a),children:[(0,n.jsx)("span",{className:"prs-dot"}),(0,n.jsxs)("span",{className:"prs-text",children:[(0,n.jsx)("span",{className:"prs-name",children:a}),(0,n.jsx)("span",{className:"prs-desc",children:l})]}),e===a&&(0,n.jsx)(j.Icons.check,{size:14,style:{color:"var(--accent)"}})]},a))]})}let id=[["policy","Policy"],["eval","EVAL"],["bridges","Connections"],["persona","Persona"]];function iu(){let e=x(),[t,l]=(0,a.useState)("policy");return(0,n.jsxs)("div",{className:"twin",children:[(0,n.jsxs)("div",{className:"twin-hero",children:[(0,n.jsx)("img",{className:"twin-orca",src:"/assets/keiko-logo.svg",alt:""}),(0,n.jsxs)("div",{className:"twin-id",children:[(0,n.jsx)("span",{className:"twin-name",children:"Keiko — Digital Twin"}),(0,n.jsxs)("span",{className:"twin-sub mono",children:["mirroring · ",e.persona]})]}),(0,n.jsx)("span",{className:"twin-mode "+("autonomous"===e.mode?"on":""),children:"autonomous"===e.mode?"Autonomous":"Manual"})]}),(0,n.jsx)("div",{className:"twin-tabs",children:id.map(([e,a])=>(0,n.jsx)("button",{type:"button",className:"twin-tab","data-on":t===e,onClick:()=>l(e),children:a},e))}),(0,n.jsxs)("div",{className:"twin-body",children:["policy"===t&&(0,n.jsx)(ii,{policy:e.policy,setPolicy:e.setPolicy}),"eval"===t&&(0,n.jsx)(ir,{decide:e.decide}),"bridges"===t&&(0,n.jsx)(io,{bridges:e.bridges,setBridges:e.setBridges}),"persona"===t&&(0,n.jsx)(ic,{persona:e.persona,setPersona:e.setPersona})]})]})}function im(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 ih(){return"Available for embeddings; not shown in the chat model picker"}function ip({model:e}){let t=function(e){if("chat"!==e.kind)return no[e.kind]}(e);return void 0===t?(0,n.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"===t?(0,n.jsx)("span",{className:"ml-elig ml-elig-embed","data-testid":"embedding-elig-ok",role:"status","aria-label":"Model eligibility: "+ih(),title:ih(),children:"Embedding-ready"}):(0,n.jsxs)("span",{className:"ml-elig ml-elig-no","data-testid":"conv-elig-no",role:"status","aria-label":"Model eligibility: "+im(t),title:im(t),children:["Not selectable — ","ocr-vision-only"===t?"OCR/vision-only":"not a chat model"]})}function ig({model:e}){var t;let a=nr(e),l="embedding"===e.kind;return(0,n.jsxs)("div",{className:"ml-row",children:[(0,n.jsx)("span",{className:"ml-ico",children:(0,n.jsx)(j.Icons.cube,{size:16})}),(0,n.jsxs)("div",{className:"ml-info",children:[(0,n.jsxs)("div",{className:"ml-top",children:[(0,n.jsx)("span",{className:"ml-name",children:e.id}),(0,n.jsx)("span",{className:"ml-type mono",children:"ocr-vision"===(t=e.kind)?"OCR":t}),(0,n.jsx)(ip,{model:e})]}),(0,n.jsxs)("div",{className:"ml-url mono",children:["tools ",e.toolCalling?"yes":"no"," · structured"," ",e.structuredOutput?"yes":"no"," · ",e.costClass,"/",e.latencyClass]})]}),(0,n.jsx)("span",{className:"ml-status "+(a||l?"connected":"ineligible"),title:a?"conversation-eligible":l?"available for embeddings":"not selectable for conversation","aria-hidden":"true"})]})}function iv(){let[e,t]=(0,a.useState)(er),[l,s]=(0,a.useState)(eo),[i,r]=(0,a.useState)(ec),[o,c]=(0,a.useState)(ed),[d,u]=(0,a.useState)(eu);(0,a.useEffect)(()=>{try{window.localStorage.setItem(V,e?"true":"false")}catch{}window.dispatchEvent(new CustomEvent(et,{detail:e}))},[e]),(0,a.useEffect)(()=>{try{window.localStorage.setItem(X,String(l))}catch{}window.dispatchEvent(new CustomEvent(en,{detail:l}))},[l]),(0,a.useEffect)(()=>{try{window.localStorage.setItem(Q,String(i))}catch{}em(i),window.dispatchEvent(new CustomEvent(ea,{detail:i}))},[i]),(0,a.useEffect)(()=>{try{window.localStorage.setItem(Z,String(o))}catch{}eh(o),window.dispatchEvent(new CustomEvent(el,{detail:o}))},[o]),(0,a.useEffect)(()=>{try{window.localStorage.setItem(ee,String(d))}catch{}ep(d),window.dispatchEvent(new CustomEvent(es,{detail:d}))},[d]);let m={"--p":`${String(l)}%`},h={"--p":`${String(i)}%`},p={"--p":`${String(o)}%`},f={"--p":`${String(d)}%`};return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"set-sec-h",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"set-sec-t",children:"Workspace wallpaper"}),(0,n.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,n.jsxs)("div",{className:"gpref",children:[(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"gpref-label",children:"Liquid wallpaper"}),(0,n.jsx)("div",{className:"gpref-help",children:e?"Running":"Stopped"})]}),(0,n.jsx)(ly,{on:e,onChange:t,label:"Liquid wallpaper"})]}),(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsx)("label",{className:"gpref-label",htmlFor:"wp-op",children:"Wallpaper opacity"}),(0,n.jsxs)("span",{className:"gpref-val mono",children:[l,"%"]})]}),(0,n.jsx)("input",{id:"wp-op",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:l,disabled:!e,onChange:e=>s(Number.parseInt(e.target.value,10)),style:m,"aria-label":"Wallpaper opacity"}),(0,n.jsxs)("div",{className:"gpref-scale",children:[(0,n.jsx)("span",{children:"Off"}),(0,n.jsx)("span",{children:"Full"})]})]}),(0,n.jsxs)("div",{className:"gpref",children:[(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsx)("label",{className:"gpref-label",htmlFor:"ws-bg-bright",children:"Workspace background brightness"}),(0,n.jsxs)("span",{className:"gpref-val mono",children:[i,"%"]})]}),(0,n.jsx)("input",{id:"ws-bg-bright",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:i,onChange:e=>r(Number.parseInt(e.target.value,10)),style:h,"aria-label":"Workspace background brightness"}),(0,n.jsxs)("div",{className:"gpref-scale",children:[(0,n.jsx)("span",{children:"Base"}),(0,n.jsx)("span",{children:"Lighter"})]})]}),(0,n.jsxs)("div",{className:"gpref",children:[(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsx)("label",{className:"gpref-label",htmlFor:"ws-grid-strength",children:"Workspace grid strength"}),(0,n.jsxs)("span",{className:"gpref-val mono",children:[o,"%"]})]}),(0,n.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:p,"aria-label":"Workspace grid strength"}),(0,n.jsxs)("div",{className:"gpref-scale",children:[(0,n.jsx)("span",{children:"Subtle"}),(0,n.jsx)("span",{children:"Strong"})]})]}),(0,n.jsxs)("div",{className:"gpref",children:[(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsx)("label",{className:"gpref-label",htmlFor:"frame-border-strength",children:"Workspace border strength"}),(0,n.jsxs)("span",{className:"gpref-val mono",children:[d,"%"]})]}),(0,n.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:f,"aria-label":"Workspace border strength"}),(0,n.jsxs)("div",{className:"gpref-scale",children:[(0,n.jsx)("span",{children:"Subtle"}),(0,n.jsx)("span",{children:"Strong"})]})]})]})}function ib(){let[e,t]=(0,a.useState)("models"),[l,s]=(0,a.useState)([]),[i,r]=(0,a.useState)(null),[o,c]=(0,a.useState)(!1),[d,u]=(0,a.useState)(!0),[m,h]=(0,a.useState)(),[p,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(0);(0,a.useEffect)(()=>{let e=!1;return async function(){u(!0),h(void 0);try{let[t,n]=await Promise.all([(0,w.fetchConfig)(),(0,w.fetchModels)()]);if(e)return;r(t.config),c(t.configPresent),s(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||u(!1)}}(),()=>{e=!0}},[g]);let b=l.filter(nr).length,x=l.length>0,y=o?x?0===b?"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.",k=o?"connected":"untested";return(0,n.jsxs)("div",{className:"set",children:[(0,n.jsxs)("div",{className:"set-hero",children:[(0,n.jsx)(j.Icons.settings,{size:18}),(0,n.jsx)("span",{className:"set-title",children:"Settings"}),(0,n.jsxs)("span",{className:"set-onprem",title:"Runs inside your network",children:[(0,n.jsx)("span",{className:"dot",style:{background:"var(--accent)"}})," Self-hosted"]})]}),(0,n.jsx)("div",{className:"set-tabs",children:["models","general","security"].map(a=>(0,n.jsx)("button",{type:"button",className:"set-tab","data-on":e===a,"aria-pressed":e===a,onClick:()=>t(a),children:"models"===a?"Models":"general"===a?"General":"Security"},a))}),(0,n.jsxs)("div",{className:"set-body",children:["models"===e&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"set-sec-h",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"set-sec-t",children:"Model gateway"}),(0,n.jsx)("div",{className:"set-sec-d",children:"Credentials are stored locally by the Keiko loopback server; secrets are never returned to the browser."})]}),(0,n.jsxs)("button",{type:"button",className:"set-add",onClick:()=>f(!0),children:[(0,n.jsx)(j.Icons.plus,{size:14}),o?"Update credentials":"Connect gateway"]})]}),(0,n.jsxs)("div",{className:"ml-row",children:[(0,n.jsx)("span",{className:"ml-ico",children:(0,n.jsx)(j.Icons.cube,{size:16})}),(0,n.jsxs)("div",{className:"ml-info",children:[(0,n.jsxs)("div",{className:"ml-top",children:[(0,n.jsx)("span",{className:"ml-name",children:o?x?"Gateway connected":"Gateway configured":"Gateway setup required"}),(0,n.jsxs)("span",{className:"ml-type mono",children:[l.length.toString()," models"]}),(0,n.jsxs)("span",{className:"ml-type mono",children:[b.toString()," chat"]})]}),(0,n.jsx)("div",{className:"ml-url mono",children:y})]}),(0,n.jsx)("span",{className:"ml-status "+k,title:o?"gateway configured":"setup required","aria-hidden":"true"})]}),void 0!==m?(0,n.jsxs)("div",{className:"gw-error",role:"alert",children:[m,(0,n.jsx)("button",{type:"button",className:"gw-error-retry",onClick:()=>v(e=>e+1),children:"Retry"})]}):null,d?(0,n.jsx)("div",{className:"set-placeholder",role:"status",children:"Loading gateway models…"}):0===l.length?(0,n.jsx)("div",{className:"set-placeholder",role:"status",children:o?"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,n.jsx)("div",{className:"set-list",children:l.map(e=>(0,n.jsx)(ig,{model:e},e.id))}),p?(0,n.jsx)(tL,{onCancel:()=>f(!1),preserveExisting:o,storedApiKeyHeaderName:i?.providers[0]?.credentialHeaderName,storedModels:l}):null]}),"general"===e&&(0,n.jsx)(iv,{}),"security"===e&&(0,n.jsx)("div",{className:"set-placeholder",children:"SSO · audit log · data residency — coming soon."})]})]})}function ix(e){return e instanceof w.ApiError?`${e.message} (${e.code})`:e instanceof Error?e.message:"Failed to load connectors."}function iy(){return(0,n.jsx)("div",{className:"connector-picker-status",role:"status","aria-live":"polite",children:"Loading connectors…"})}function iw({message:e,onRetry:t}){return(0,n.jsxs)("div",{className:"connector-picker-error",role:"alert",children:[(0,n.jsx)("p",{children:e}),(0,n.jsx)("button",{type:"button",className:"connector-picker-retry",onClick:t,children:"Try again"})]})}function ij({onManageConnectors:e}){return(0,n.jsxs)("div",{className:"connector-picker-empty",children:[(0,n.jsx)("p",{children:"No ready connectors found."}),(0,n.jsx)("button",{type:"button",className:"connector-picker-create-link",onClick:e,children:"Create a connector"})]})}function ik({capsules:e,capsuleSets:t,selectedKind:a,selectedId:l}){let s=function(e,t,n,a){if(void 0===n||void 0===a||0===a.length)return null;if("capsule"===n){let t=e.find(e=>e.id===a);return void 0!==t?t.displayName:`Capsule ${a}`}if("capsule-set"===n){let e=t.find(e=>e.id===a);return void 0!==e?e.displayName:`Set ${a}`}return null}(e,t,a,l);return null===s?null:(0,n.jsxs)("div",{className:"connector-picker-selected",role:"status","aria-live":"polite",children:[(0,n.jsx)("span",{"aria-hidden":"true",children:"●"}),(0,n.jsx)("span",{children:s})]})}function iN({selectedId:e,selectedLabel:t,selectedState:a,onManageConnectors:l}){let s=void 0!==t&&t.trim().length>0?t.trim():`Capsule ${e}`;return(0,n.jsxs)("div",{className:"connector-node","data-testid":"knowledge-connector-node",children:[(0,n.jsx)("div",{className:"connector-node-icon","aria-hidden":"true",children:(0,n.jsx)(j.Icons.server,{size:42})}),(0,n.jsxs)("div",{className:"connector-node-copy",children:[(0,n.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"}}(a)}),(0,n.jsx)("h2",{className:"connector-node-title",title:s,children:s}),(0,n.jsx)("p",{className:"connector-node-id mono",title:e,children:e})]}),(0,n.jsx)("button",{type:"button",className:"connector-node-manage",onClick:l,children:"Manage"})]})}function iS({selectedKind:e,selectedId:t,selectedLabel:l,selectedState:s,presentation:i,onSelect:r,onManageConnectors:o=()=>void 0}){let[c,d]=(0,a.useState)([]),[u,m]=(0,a.useState)([]),[h,p]=(0,a.useState)(!0),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(!1),[x,y]=(0,a.useState)(0),w="node"===i&&"capsule"===e&&void 0!==t&&t.length>0;if((0,a.useEffect)(()=>{if(w)return;let e=!1;return async function(){p(!0),g(null),b(!1);try{let[t,n]=await Promise.allSettled([(0,lw.fetchCapsules)(),(0,lw.fetchCapsuleSets)()]);if(e)return;"fulfilled"===t.status?d(t.value.capsules.filter(e=>"ready"===e.lifecycleState)):g(ix(t.reason)),"fulfilled"===n.status?m(n.value.capsuleSets):b(!0)}catch(t){e||g(ix(t))}finally{e||p(!1)}}(),()=>{e=!0}},[w,x]),w)return(0,n.jsx)(iN,{selectedId:t,selectedLabel:l,selectedState:s,onManageConnectors:o});if(h)return(0,n.jsx)(iy,{});if(null!==f)return(0,n.jsx)(iw,{message:f,onRetry:()=>{y(e=>e+1)}});let j=c.length>0,k=u.length>0;if(!j&&!k)return(0,n.jsx)(ij,{onManageConnectors:o});let N=void 0!==e&&void 0!==t&&t.length>0?`${e}:${t}`:"";return(0,n.jsxs)("div",{className:"connector-picker",children:[(0,n.jsx)(ik,{capsules:c,capsuleSets:u,selectedKind:e,selectedId:t}),(0,n.jsx)("label",{className:"connector-picker-label",htmlFor:"connector-picker-select",children:"Select a connector"}),(0,n.jsxs)("select",{id:"connector-picker-select",className:"connector-picker-select",value:N,onChange:e=>{!function(e){if(""===e)return;let t=e.indexOf(":");if(-1===t)return;let n=e.slice(0,t),a=e.slice(t+1);0!==a.length&&r({selectedKind:n,selectedId:a})}(e.target.value)},children:[(0,n.jsx)("option",{value:"",disabled:!0,children:"— choose a connector —"}),j&&(0,n.jsx)("optgroup",{label:"Capsules",children:c.map(e=>(0,n.jsx)("option",{value:`capsule:${e.id}`,children:`${e.displayName} (${function(e){switch(e){case"ready":return"Ready";case"indexing":return"Indexing…";case"error":return"Failed";default:return e}}(e.lifecycleState)})`},`capsule:${e.id}`))}),k&&(0,n.jsx)("optgroup",{label:"Capsule sets",children:u.map(e=>(0,n.jsx)("option",{value:`capsule-set:${e.id}`,children:`${e.displayName} (${String(e.capsuleCount)} capsules)`},`capsule-set:${e.id}`))})]}),v?(0,n.jsx)("p",{className:"connector-picker-notice",role:"status",children:"Capsule sets could not be loaded."}):null,(0,n.jsx)("div",{className:"connector-picker-footer",children:(0,n.jsx)("button",{type:"button",className:"connector-picker-create-link",onClick:o,children:"Create or manage connectors"})})]})}async function iC(e,t){let n=(t?.method??"GET").toUpperCase(),a="GET"!==n&&"HEAD"!==n,l=await fetch(e,{...t,headers:{Accept:"application/json",...a?{"Content-Type":"application/json"}:{},...a?{"X-Keiko-CSRF":"1"}:{},...t?.headers??{}}});if(!l.ok){let e="INTERNAL",t=`HTTP ${l.status.toString()}`;try{let n=await l.json();e=n.error.code,t=n.error.message}catch{}throw new w.ApiError(e,t,l.status)}return l.json()}async function iI(e,t={}){return iC("/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 iE(e,t){return iC(`/api/figma/snapshots/${encodeURIComponent(e)}`,{...void 0!==t?{signal:t}:{}})}async function iR(e={}){let 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 iC(`/api/figma/snapshots${n}`,{...void 0!==e.signal?{signal:e.signal}:{}})).snapshots}function i$(e,t){return`/api/figma/snapshots/${encodeURIComponent(e)}/screens/${encodeURIComponent(String(t))}/image`}async function iT(e,t,n){return iC(`/api/figma/snapshots/${encodeURIComponent(e)}/screens/${encodeURIComponent(t)}/json`,{...void 0!==n?{signal:n}:{}})}async function iA(e,t){return iC(`/api/figma/snapshots/${encodeURIComponent(e)}/code`,{method:"POST",...void 0!==t?{signal:t}:{},body:JSON.stringify({})})}async function iM(){return iC("/api/figma/token",{method:"DELETE",body:JSON.stringify({})})}let iL=/"(?:\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4})|[^"\\])*"\s*:?|[-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|\b(?:true|false|null)\b|[{}\[\],:]/gu;function iq(e){return 0===e.length?0:"u">typeof TextEncoder?new TextEncoder().encode(e).byteLength:e.length}function iP({text:e,className:t}){let a=function(e){let t=[],n=0;for(let a of e.matchAll(iL)){let l=a[0],s=a.index;s>n&&t.push(e.slice(n,s)),t.push({kind:l.startsWith('"')?l.endsWith(":")?"key":"string":"true"===l||"false"===l?"boolean":"null"===l?"null":/^-?\d/u.test(l)?"number":"punctuation",text:l}),n=s+l.length}return n<e.length&&t.push(e.slice(n)),t}(e);return(0,n.jsx)("pre",{className:t,children:(0,n.jsx)("code",{children:a.map((e,t)=>"string"==typeof e?e:(0,n.jsx)("span",{className:`json-token-${e.kind}`,children:e.text},`${e.kind}-${t.toString()}`))})})}let iD=[];function iF(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 a=t.searchParams.get("node-id");return null!==a&&a.length>0}catch{return!1}}function iz(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()}let iO=new Set(["FIGMA_PROXY_EGRESS_FAILED","FIGMA_PROXY_UNREACHABLE","FIGMA_PROXY_AUTH_REQUIRED","FIGMA_PROXY_BLOCKED_BY_POLICY"]),iK=new Set(["FIGMA_TLS_CA_FAILURE"]),iB=new Set(["FIGMA_NETWORK_UNREACHABLE","FIGMA_EGRESS_TIMEOUT","FIGMA_EGRESS_FAILED"]);function i_(e){return e instanceof w.ApiError?"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}:iO.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}:iK.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}:iB.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 iU(e){let t=i_(e);return void 0===t.status?t.detail:`${t.detail} (${t.status})`}function iW(e,t){let n=document.elementFromPoint(e,t);return n instanceof Element&&null!==n.closest("main.workspace")&&null===n.closest(".window")}function iH(e,t){let n={payload:e,clientX:t.clientX,clientY:t.clientY};window.dispatchEvent(new CustomEvent(th,{detail:n}))}function iY(e,t){let n={payload:e,clientX:t.clientX,clientY:t.clientY};window.dispatchEvent(new CustomEvent(tv,{detail:n}))}function iJ({index:e,screenId:t,name:a,irSummary:l,imageSrc:s,imageByteLength:i,structuralReason:r,onAddSource:o,isSourceSelected:c=!1,dragPayload:d}){let u=void 0!==d&&void 0!==o&&!c,m=c?`${a} preview is already the active scoped source`:`Drag screen ${a} to the workspace, or click to add it as a Quality Intelligence source`,h=void 0!==s?(0,n.jsx)(ap.default,{className:"figma-snapshot-screen-image",src:s,alt:`Captured preview for ${a}`,loading:"lazy",width:72,height:54,unoptimized:!0}):(0,n.jsxs)("div",{className:"figma-snapshot-screen-image figma-snapshot-screen-placeholder","aria-label":`Structural data only for ${a}`,role:"img",children:[(0,n.jsx)(j.Icons.layers,{className:"figma-snapshot-screen-frame-icon","aria-hidden":"true"}),(0,n.jsx)("span",{className:"figma-snapshot-screen-placeholder-label",children:"IR"})]});return(0,n.jsxs)("article",{className:"figma-snapshot-screen-card","aria-label":`Screen ${String(e+1)}: ${a}`,children:[void 0!==o?(0,n.jsx)("button",{type:"button",className:"figma-snapshot-screen-preview-btn",onClick:o,disabled:c,"aria-disabled":c?"true":void 0,"aria-label":m,draggable:u,onDragStart:e=>{u&&(e.dataTransfer.effectAllowed="copy",e.dataTransfer.setData(to,JSON.stringify(d)),e.dataTransfer.setData("text/plain",a))},onDragEnd:e=>{if(u){let t;iW(e.clientX,e.clientY)&&(t={payload:d,clientX:e.clientX,clientY:e.clientY},window.dispatchEvent(new CustomEvent(tc,{detail:t})))}},children:h}):h,(0,n.jsxs)("div",{className:"figma-snapshot-screen-meta",children:[(0,n.jsx)("h3",{className:"figma-snapshot-screen-name",title:a,children:a}),(0,n.jsx)("p",{className:"figma-snapshot-screen-summary",children:l}),(0,n.jsx)("p",{className:"figma-snapshot-screen-size",children:void 0!==i?(0,ak.formatBytes)(i):`Structural IR only${void 0!==r?` (${r})`:""}`}),(0,n.jsx)("p",{className:"figma-snapshot-screen-id",children:t}),void 0!==o?(0,n.jsx)("div",{className:"figma-snapshot-screen-actions",children:(0,n.jsx)("button",{type:"button",className:"figma-snapshot-screen-source-btn",onClick:o,disabled:c,"aria-disabled":c?"true":void 0,"aria-label":c?`${a} is already the active scoped source`:`Add screen ${a} to the workspace as a Quality Intelligence source`,children:c?"Source active":"Add to workspace"})}):null]})]})}function iG({name:e,screenId:t,irSummary:l,imageSrc:s,imageByteLength:i,structuralReason:r,snapshotRunId:o,capturedAt:c,imageDragPayload:d}){let u=(0,a.useRef)(null),m=(0,a.useRef)(!1),h=void 0!==s&&void 0!==d,p=void 0!==s?(0,n.jsx)(ap.default,{className:"figma-view-preview-image",src:s,alt:`Captured preview for ${e}`,loading:"eager",width:360,height:240,draggable:!1,unoptimized:!0}):(0,n.jsxs)("div",{className:"figma-view-preview-image figma-view-preview-placeholder","aria-label":`Structural data only for ${e}`,role:"img",children:[(0,n.jsx)(j.Icons.layers,{className:"figma-view-preview-icon","aria-hidden":"true"}),(0,n.jsx)("span",{children:"Structural IR"})]});return(0,n.jsxs)("article",{className:"figma-view-source-card","aria-label":`Figma view source: ${e}`,children:[h?(0,n.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(tg,JSON.stringify(d)),e.dataTransfer.setData("text/plain",`${d.name}.png`))},onDragEnd:e=>{h&&iW(e.clientX,e.clientY)&&iY(d,e)},onKeyDown:e=>{if(!h||"Enter"!==e.key&&" "!==e.key)return;e.preventDefault();let t=e.currentTarget.getBoundingClientRect();iY(d,{clientX:t.right+24,clientY:t.top+t.height/2})},onPointerDown:e=>{h&&0===e.button&&(m.current=!1,u.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY},e.currentTarget.setPointerCapture(e.pointerId))},onPointerMove:e=>{let t=u.current;null===t||t.pointerId!==e.pointerId||Math.hypot(e.clientX-t.startX,e.clientY-t.startY)>=6&&e.preventDefault()},onPointerUp:e=>{let t=u.current;if(null===t||t.pointerId!==e.pointerId)return;u.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&&iW(e.clientX,e.clientY)&&(e.preventDefault(),iY(d,e))},onPointerCancel:e=>{let t=u.current;null!==t&&t.pointerId===e.pointerId&&(u.current=null,e.currentTarget.releasePointerCapture(e.pointerId))},onMouseDown:e=>{if(!h||0!==e.button)return;let t=e.clientX,n=e.clientY,a=e=>{Math.hypot(e.clientX-t,e.clientY-n)>=6&&e.preventDefault()},l=e=>{if(window.removeEventListener("mousemove",a),window.removeEventListener("mouseup",l),m.current){m.current=!1;return}Math.hypot(e.clientX-t,e.clientY-n)>=6&&iW(e.clientX,e.clientY)&&(e.preventDefault(),iY(d,e))};window.addEventListener("mousemove",a),window.addEventListener("mouseup",l)},"aria-label":`Create a standalone image source for ${e}`,title:`Drag image for ${e} to the workspace`,children:p}):(0,n.jsx)("div",{className:"figma-view-preview",children:p}),(0,n.jsxs)("div",{className:"figma-view-source-meta",children:[(0,n.jsx)("p",{className:"figma-view-source-kicker",children:"QI view source"}),(0,n.jsx)("h2",{className:"figma-view-source-title",title:e,children:e}),(0,n.jsx)("p",{className:"figma-view-source-summary",children:l}),(0,n.jsxs)("dl",{className:"figma-view-source-facts",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Screen"}),(0,n.jsx)("dd",{children:t})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Snapshot"}),(0,n.jsx)("dd",{children:o})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Captured"}),(0,n.jsx)("dd",{children:c})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Preview"}),(0,n.jsx)("dd",{children:void 0!==i?(0,ak.formatBytes)(i):`Structural IR${void 0!==r?` (${r})`:""}`})]})]})]})]})}function iV({sourceWindowId:e,snapshotRunId:t,selectedScreenIds:l=iD,selectedScreenName:s,openScreenSource:i,updateCfg:r,triggerImpl:o=iI,loadImpl:c=iE,listImpl:d=iR,loadScreenJsonImpl:u=iT,codegenImpl:m=iA,revokeImpl:h=iM}){let p,f,g,v,b=(0,a.useId)(),x=(0,a.useId)(),y=(0,a.useId)(),j=(0,a.useId)(),[k,N]=(0,a.useState)(""),[S,C]=(0,a.useState)("idle"),[I,E]=(0,a.useState)(null),[R,$]=(0,a.useState)(null),[T,A]=(0,a.useState)(null),[M,L]=(0,a.useState)(null),[q,P]=(0,a.useState)(0),[D,F]=(0,a.useState)("recent"),[z,O]=(0,a.useState)([]),[K,B]=(0,a.useState)([]),[_,U]=(0,a.useState)(!1),[W,H]=(0,a.useState)(!1),[Y,J]=(0,a.useState)(null),[G,V]=(0,a.useState)(null),[X,Q]=(0,a.useState)(!1),[Z,ee]=(0,a.useState)(!1),et=(0,a.useRef)(null),en=(0,a.useRef)(null),ea=(0,a.useRef)(null),el=(0,a.useRef)(null),es=(0,a.useRef)(null),ei=(0,a.useRef)(null),er=(0,a.useRef)(null),eo=(0,a.useRef)(!1),ec=(0,a.useCallback)(()=>{ee(!0)},[]),[ed,eu]=(0,a.useState)("idle"),[em,eh]=(0,a.useState)(null),[ep,ef]=(0,a.useState)(null),[eg,ev]=(0,a.useState)("idle"),[eb,ex]=(0,a.useState)(null),[ey,ew]=(0,a.useState)(null),[ej,ek]=(0,a.useState)(null),[eN,eS]=(0,a.useState)(!1),[eC,eI]=(0,a.useState)(null),[eE,eR]=(0,a.useState)(null),e$=(0,a.useRef)(null),eT=(0,a.useRef)(null),[eA,eM]=(0,a.useState)(24),eL=l.join("\0"),eq=iF(k),eP=function(e){let t=e.trim();if(0===t.length||iF(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."}(k),eD=(0,a.useMemo)(()=>null!==I?{fileKey:I.fileKey,nodeId:I.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[,a,l]=t.pathname.split("/");if("design"!==a&&"file"!==a||void 0===l||0===l.length)return null;let s=t.searchParams.get("node-id");if(null===s||0===s.length)return null;return{fileKey:l,nodeId:s}}catch{return null}}(k),[k,I]),eF=eD?.fileKey,ez=eD?.nodeId,eO="building"===S,eK="loading"===S,eB=eO||eK,e_=eO&&null!==M?(f=Math.floor((p=Math.max(0,Math.floor(q/1e3)))/3600),g=Math.floor(p%3600/60),v=p%60,f>0?`${String(f)}h ${String(g)}m ${String(v)}s`:g>0?`${String(g)}m ${String(v)}s`:`${String(v)}s`):null,eU=(0,a.useMemo)(()=>new Set(l),[l]),eW=l.length>0,eH=eW&&void 0!==t&&t.length>0,eY=(0,a.useMemo)(()=>{if(null===I)return[];let e=new Set(I.screens.map(e=>e.screenId)),t=[...I.screens.map((e,t)=>({kind:"rendered",screen:e,imageIndex:t})),...(I.structuralScreens??[]).filter(t=>!e.has(t.screenId)).map(e=>({kind:"structural",screen:e}))];return eW?t.filter(e=>eU.has(e.screen.screenId)):t},[eW,eU,I]),eJ=1===l.length?l[0]:void 0,eG=(0,a.useMemo)(()=>null===eb?"":JSON.stringify(eb,null,2),[eb]),eV=(0,a.useMemo)(()=>iq(eG),[eG]),eX=(I?.screens.length??0)+(I?.structuralScreens?.length??0);(0,a.useEffect)(()=>{Z&&"error"===S&&et.current?.focus()},[Z,S]),(0,a.useEffect)(()=>{eN&&e$.current?.focus()},[eN]),(0,a.useEffect)(()=>{if(!eO||null===M)return;P(Date.now()-M);let e=window.setInterval(()=>{P(Date.now()-M)},1e3);return()=>{window.clearInterval(e)}},[eO,M]),(0,a.useEffect)(()=>()=>{en.current?.abort(),ea.current?.abort(),el.current?.abort(),es.current?.abort()},[]),(0,a.useEffect)(()=>{null===eD&&"board"===D&&F("recent")},[eD,D]);let eQ=(0,a.useCallback)(()=>{es.current?.abort();let e=new AbortController;if(es.current=e,H(!0),V(null),d({limit:12,signal:e.signal}).then(e=>{B(e)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||(B([]),V(iU(e)))}).finally(()=>{es.current===e&&H(!1)}),void 0===eF||void 0===ez){O([]),J(null),U(!1);return}U(!0),J(null),d({fileKey:eF,nodeId:ez,limit:12,signal:e.signal}).then(e=>{O(e)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||(O([]),J(iU(e)))}).finally(()=>{es.current===e&&U(!1)})},[eF,ez,d]);(0,a.useEffect)(()=>{eQ()},[eQ,I?.runId]);let eZ=(0,a.useCallback)(e=>{if(0===e.length||eB)return;en.current?.abort();let n=new AbortController;en.current=n,C("loading"),$(null),A(null),eu("idle"),eh(null),ef(null),ev("idle"),ex(null),ew(null),ek(null),c(e,n.signal).then(e=>{E(e),N(iz(e)),r({snapshotRunId:e.runId}),C("done")}).catch(n=>{n instanceof DOMException&&"AbortError"===n.name||(n instanceof w.ApiError&&"FIGMA_SNAPSHOT_NOT_FOUND"===n.code?(t===e&&r({snapshotRunId:void 0}),$({...i_(n),detail:t===e?`${n.message} The stored run ID has been cleared.`:n.message})):$(i_(n)),C("error"))})},[eB,c,t,r]);(0,a.useEffect)(()=>{eH&&void 0!==t&&0!==t.length&&null===I&&"idle"===S&&eZ(t)},[S,eH,eZ,t,I]);let e0=(0,a.useCallback)(async(e,t)=>{en.current?.abort(),ea.current?.abort(),el.current?.abort(),ea.current=null,el.current=null;let n=new AbortController;en.current=n,ei.current={link:e,isResnapshot:t},C("building"),$(null),A(null),L(Date.now()),P(0),eu("idle"),eh(null),ev("idle"),ex(null),ew(null),ek(null);try{let a=await o(e,{acknowledgeReadOnly:X,isResnapshot:t,signal:n.signal});E(a),N(iz(a)),r({snapshotRunId:a.runId}),C("done"),L(null),P(0),ei.current=null}catch(n){if(n instanceof DOMException&&"AbortError"===n.name)return;if(L(null),P(0),n instanceof w.ApiError&&"FIGMA_CONSENT_REQUIRED"===n.code){let e=i_(n);$({...e,detail:`${e.detail} Tick the acknowledgement checkbox below, then snapshot again.`}),ec()}else n instanceof w.ApiError&&"FIGMA_BUILD_TIMEOUT"===n.code?(A({link:e,isResnapshot:t}),$({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."})):$(i_(n));C("error"),ei.current=null}},[o,r,X,ec]),e1=(0,a.useCallback)(e=>{if(e.preventDefault(),eq&&!eB){if(!X){$({title:"Figma snapshot failed",detail:"Tick the read-only acknowledgement checkbox below, then snapshot again."}),C("error"),ec();return}e0(k,!1)}},[k,eB,X,eq,e0,ec]),e2=(0,a.useCallback)(()=>{eB||null!==I&&e0(iz(I),!0)},[eB,e0,I]),e4=(0,a.useCallback)(()=>{en.current?.abort(),en.current=null,L(null),P(0),null!==ei.current&&A(ei.current),ei.current=null,C("idle"),$(null)},[]),e3=(0,a.useCallback)(()=>{eB||null===T||e0(T.link,T.isResnapshot)},[eB,T,e0]),e6=(0,a.useCallback)(()=>{let e=I?.runId??t;if(void 0===e||0===e.length||"generating"===ed)return;let n=new AbortController;ea.current=n,eu("generating"),ef(null),m(e,n.signal).then(e=>{eh(e),eu("done")}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name?eu("idle"):(ef(iU(e)),eu("error"))}).finally(()=>{ea.current===n&&(ea.current=null)})},[m,ed,t,I]),e5=(0,a.useCallback)(()=>{let e=I?.runId??t;if(void 0===e||0===e.length||void 0===eJ||"loading"===eg)return;el.current?.abort();let n=new AbortController;el.current=n,ev("loading"),ew(null),ek(null),u(e,eJ,n.signal).then(e=>{ex(e),ev("done")}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name?ev("idle"):(ex(null),ew(iU(e)),ev("error"))}).finally(()=>{el.current===n&&(el.current=null)})},[eJ,u,eg,t,I?.runId]),e8=(0,a.useCallback)(()=>{if(0!==eG.length){if(void 0===navigator.clipboard)return void ek("Clipboard unavailable");navigator.clipboard.writeText(eG).then(()=>{ek("Copied")}).catch(()=>{ek("Copy failed")})}},[eG]),e7=(0,a.useMemo)(()=>{let n=eb?.runId??I?.runId??t,a=eb?.screen.screenId??eJ,l=eb?.screen.name??s??a;return void 0===n||0===n.length||void 0===a||0===a.length||void 0===l||0===l.length?null:{snapshotRunId:n,screenId:a,name:l,...void 0!==e?{sourceWindowId:e}:{}}},[eJ,eb?.runId,eb?.screen.name,eb?.screen.screenId,s,t,e,I?.runId]),e9=(0,a.useCallback)(e=>{null!==e7&&(e.dataTransfer.effectAllowed="copyMove",e.dataTransfer.setData(tm,JSON.stringify(e7)),e.dataTransfer.setData("text/plain",`${e7.name}.json`))},[e7]),te=(0,a.useCallback)(e=>{null!==e7&&iW(e.clientX,e.clientY)&&iH(e7,e)},[e7]),tt=(0,a.useCallback)(e=>{if(null===e7||"Enter"!==e.key&&" "!==e.key)return;e.preventDefault();let t=e.currentTarget.getBoundingClientRect();iH(e7,{clientX:t.right+24,clientY:t.top+t.height/2})},[e7]),tn=(0,a.useCallback)(e=>{null!==e7&&0===e.button&&(eo.current=!1,er.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY},e.currentTarget.setPointerCapture(e.pointerId))},[e7]),ta=(0,a.useCallback)(e=>{let t=er.current;null===t||t.pointerId!==e.pointerId||Math.hypot(e.clientX-t.startX,e.clientY-t.startY)>=6&&e.preventDefault()},[]),tl=(0,a.useCallback)(e=>{let t=er.current;if(null===t||t.pointerId!==e.pointerId)return;er.current=null,e.currentTarget.releasePointerCapture(e.pointerId);let n=Math.hypot(e.clientX-t.startX,e.clientY-t.startY);n>=6&&(eo.current=!0),n>=6&&null!==e7&&iW(e.clientX,e.clientY)&&(e.preventDefault(),iH(e7,e))},[e7]),ts=(0,a.useCallback)(e=>{let t=er.current;null!==t&&t.pointerId===e.pointerId&&(er.current=null,e.currentTarget.releasePointerCapture(e.pointerId))},[]),ti=(0,a.useCallback)(e=>{if(null===e7||0!==e.button)return;let t=e.clientX,n=e.clientY,a=e=>{Math.hypot(e.clientX-t,e.clientY-n)>=6&&e.preventDefault()},l=e=>{if(window.removeEventListener("mousemove",a),window.removeEventListener("mouseup",l),eo.current){eo.current=!1;return}Math.hypot(e.clientX-t,e.clientY-n)>=6&&iW(e.clientX,e.clientY)&&(e.preventDefault(),iH(e7,e))};window.addEventListener("mousemove",a),window.addEventListener("mouseup",l)},[e7]),tr=(0,a.useCallback)(()=>{ea.current?.abort(),ea.current=null,eu("idle"),ef(null)},[]),to=(0,a.useCallback)(()=>{void 0===t||0===t.length||eB||eZ(t)},[eB,eZ,t]);(0,a.useEffect)(()=>{eM(24)},[eL,I?.runId]),(0,a.useEffect)(()=>{el.current?.abort(),el.current=null,ev("idle"),ex(null),ew(null),ek(null)},[eL,t]);let tc=(0,a.useCallback)(()=>{eS(!1),eR(null),eI(null),h().then(e=>{eI(e.message),requestAnimationFrame(()=>eT.current?.focus())}).catch(e=>{eR(iU(e)),requestAnimationFrame(()=>eT.current?.focus())})},[h]),td=(0,a.useCallback)(()=>{eS(!1),requestAnimationFrame(()=>eT.current?.focus())},[]),tu=void 0!==t&&t.length>0&&null===I&&("idle"===S||"loading"===S||"error"===S),th=(e,a,l,s,i,r)=>a?(0,n.jsx)("p",{className:"figma-snapshot-dashboard-status",children:"Loading snapshots…"}):null!==l?(0,n.jsx)("p",{className:"figma-snapshot-dashboard-status figma-snapshot-dashboard-status-error",children:l}):0===e.length?(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-empty",children:[(0,n.jsx)("p",{className:"figma-snapshot-dashboard-empty-title",children:s}),(0,n.jsx)("p",{className:"figma-snapshot-dashboard-empty-detail",children:i})]}):(0,n.jsx)("div",{className:"figma-snapshot-dashboard-list",role:"list",children:e.map(e=>{let a=I?.runId===e.runId;return(0,n.jsxs)("button",{type:"button",className:"figma-snapshot-dashboard-item",onClick:()=>{eZ(e.runId)},"aria-current":a?"true":void 0,"aria-busy":eK&&t===e.runId?"true":void 0,children:[(0,n.jsxs)("span",{className:"figma-snapshot-dashboard-item-head",children:[(0,n.jsx)("span",{className:"figma-snapshot-dashboard-item-date",children:(0,ak.formatDate)(e.fetchedAt)}),a&&(0,n.jsx)("span",{className:"figma-snapshot-dashboard-item-badge",children:"Current"})]}),(0,n.jsx)("span",{className:"figma-snapshot-dashboard-item-hint",children:e.reductionHint}),(0,n.jsxs)("span",{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,n.jsxs)("span",{className:"figma-snapshot-dashboard-item-scope",children:[e.fileKey," · ",e.nodeId]})]},e.runId)})});if(eH){let a=s??l.join(", "),i=void 0!==eJ&&(I?.runId??t)!==void 0&&"loading"!==eg;return(0,n.jsxs)("section",{className:"figma-snapshot-window figma-view-window","aria-label":`Figma view source ${a}`,children:[(0,n.jsxs)("div",{className:"figma-view-source-header",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"figma-view-source-eyebrow",children:"Figma view"}),(0,n.jsx)("h1",{className:"figma-view-source-heading",title:a,children:a})]}),(0,n.jsxs)("div",{className:"figma-view-source-actions",children:[(0,n.jsx)("span",{className:"figma-view-source-badge",children:"QI source"}),(0,n.jsx)("button",{type:"button",className:"figma-view-json-btn",onClick:e5,disabled:!i,"aria-disabled":i?void 0:"true","aria-busy":"loading"===eg?"true":void 0,children:"loading"===eg?"Loading JSON…":"Inspect JSON"})]})]}),(0,n.jsxs)("div",{id:x,role:"status","aria-live":"polite","aria-atomic":"true",className:"figma-snapshot-status",children:[eK&&(0,n.jsx)("p",{className:"figma-snapshot-progress",children:"Loading view preview…"}),"error"===S&&null!==R&&(0,n.jsx)("p",{className:"figma-snapshot-error",children:R.detail}),"done"===S&&null!==I&&(0,n.jsxs)("p",{className:"sr-only",children:["Figma view loaded — ",a,"."]})]}),null===I?(0,n.jsxs)("div",{className:"figma-view-source-empty",children:[(0,n.jsx)("p",{className:"figma-view-source-empty-title",children:eK?"Loading the selected view…":"Selected view preview not loaded."}),!eK&&(0,n.jsx)("button",{type:"button",className:"figma-snapshot-load-btn",onClick:to,children:"Load view"})]}):eY.length>0?eY.map(t=>{let a="rendered"===t.kind?i$(I.runId,t.imageIndex):void 0,l=void 0===a?void 0:{snapshotRunId:I.runId,screenId:t.screen.screenId,name:t.screen.name,imageSrc:a,...void 0!==e?{sourceWindowId:e}:{}};return(0,n.jsx)(iG,{name:t.screen.name,screenId:t.screen.screenId,irSummary:t.screen.irSummary,imageSrc:a,imageByteLength:"rendered"===t.kind?t.screen.imageByteLength:void 0,structuralReason:"structural"===t.kind?t.screen.reason:void 0,snapshotRunId:I.runId,capturedAt:(0,ak.formatDate)(I.fetchedAt),imageDragPayload:l},t.screen.screenId)}):(0,n.jsx)("div",{className:"lk-empty",children:(0,n.jsx)("p",{className:"lk-empty-body",children:"The selected screen is not present in this stored snapshot."})}),"error"===eg&&null!==ey?(0,n.jsx)("p",{className:"figma-snapshot-error",role:"alert",children:ey}):null,"done"===eg&&null!==eb?(0,n.jsxs)("section",{className:"figma-view-json-inspector","aria-label":`Scoped JSON for ${eb.screen.name}`,children:[(0,n.jsxs)("div",{className:"figma-view-json-inspector-header",children:[(0,n.jsxs)("div",{className:"figma-view-json-drag-surface",role:"button",tabIndex:null!==e7?0:-1,draggable:!1,onDragStart:e9,onDragEnd:te,onKeyDown:tt,onPointerDown:tn,onPointerMove:ta,onPointerUp:tl,onPointerCancel:ts,onMouseDown:ti,"aria-label":`Create a standalone JSON source for ${eb.screen.name}`,"aria-disabled":null===e7?"true":void 0,title:`Drag JSON for ${eb.screen.name} to the workspace`,children:[(0,n.jsx)("p",{className:"figma-view-json-kicker",children:"Stored Screen-IR JSON"}),(0,n.jsx)("h2",{className:"figma-view-json-title",children:eb.screen.screenId}),(0,n.jsxs)("p",{className:"figma-view-json-meta",children:[eb.screen.kind," · ",(0,ak.formatBytes)(eV)," ·"," ",eb.relatedLinks.length.toString()," related link",1!==eb.relatedLinks.length?"s":""]})]}),(0,n.jsx)("button",{type:"button",className:"figma-view-json-copy-btn",onClick:e8,children:"Copy JSON"})]}),null!==ej?(0,n.jsx)("p",{className:"figma-view-json-copy-status",role:"status",children:ej}):null,(0,n.jsx)(iP,{text:eG,className:"figma-view-json-code"})]}):null]})}return(0,n.jsxs)("section",{className:"figma-snapshot-window","aria-label":"Figma Snapshot",children:[(0,n.jsxs)("form",{className:"figma-snapshot-form",onSubmit:e1,noValidate:!0,children:[(0,n.jsx)("label",{className:"figma-snapshot-label",htmlFor:b,children:"Board link"}),(0,n.jsxs)("div",{className:"figma-snapshot-input-row",children:[(0,n.jsx)("input",{id:b,type:"url",className:"figma-snapshot-input",placeholder:"https://www.figma.com/design/…?node-id=…",value:k,onChange:e=>{N(e.target.value),null!==R&&$(null),"error"===S&&C("idle"),null!==T&&A(null),Z&&ee(!1)},"aria-describedby":null!==eP?`${y} ${x}`:x,"aria-invalid":null!==eP?"true":void 0,readOnly:eB,autoComplete:"off",spellCheck:!1}),(0,n.jsx)("button",{type:"submit",className:"figma-snapshot-trigger-btn",disabled:!eq&&!eB,"aria-disabled":!eq||eB?"true":void 0,"aria-busy":eO,children:eO?"Building…":"Snapshot"})]}),null!==eP&&(0,n.jsx)("p",{id:y,className:"figma-snapshot-link-error",role:"alert",children:eP}),(0,n.jsxs)("label",{className:"figma-snapshot-consent",children:[(0,n.jsx)("input",{type:"checkbox",className:"figma-snapshot-consent-checkbox",ref:et,checked:X,"aria-invalid":Z?"true":void 0,onChange:e=>{Q(e.target.checked),null!==R&&$(null),"error"===S&&C("idle"),ee(!1)},disabled:eO}),(0,n.jsxs)("span",{children:["I acknowledge the configured Figma PAT is read-only and least-privilege (",(0,n.jsx)("code",{children:"file_content:read"}),")."," ",(0,n.jsx)("span",{className:"figma-snapshot-consent-required",children:"Required before the first snapshot of a board."})]})]}),(0,n.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"===S&&null!==R&&!0===R.assertive&&(0,n.jsxs)("div",{className:"figma-snapshot-error-card",role:"alert","aria-labelledby":`${x}-error-title`,children:[(0,n.jsx)("p",{id:`${x}-error-title`,className:"figma-snapshot-error-title",children:R.title}),(0,n.jsx)("p",{className:"figma-snapshot-error-detail",children:R.detail}),void 0!==R.status&&(0,n.jsx)("p",{className:"figma-snapshot-error-status",children:R.status}),void 0!==R.remediation&&(0,n.jsx)("p",{className:"figma-snapshot-error-remediation",children:R.remediation})]}),(0,n.jsxs)("div",{id:x,role:"status","aria-live":"polite","aria-atomic":"true",className:"figma-snapshot-status",children:[eO&&(0,n.jsxs)("p",{className:"figma-snapshot-progress",children:["Building snapshot — fetching screens from Figma…"," ",null!==e_?`${e_} elapsed.`:""," Large boards can take several minutes."]}),eK&&(0,n.jsx)("p",{className:"figma-snapshot-progress",children:"Loading stored snapshot…"}),"done"===S&&null!==I&&(0,n.jsxs)("p",{className:"sr-only",children:["Snapshot complete — ",I.reductionHint,"."]}),"done"===ed&&null!==em&&(0,n.jsxs)("p",{className:"sr-only",children:["Code generated — ",String(em.fileCount)," file",1!==em.fileCount?"s":""," ready for review."]}),"idle"===S&&(0,n.jsx)("p",{className:"sr-only","aria-live":"polite"}),"error"===S&&null!==R&&!0!==R.assertive&&(0,n.jsx)("p",{className:"figma-snapshot-error",children:R.detail})]}),eO&&(0,n.jsxs)("div",{className:"figma-snapshot-cancel-row",children:[(0,n.jsx)("button",{type:"button",className:"figma-snapshot-cancel-btn",onClick:e4,children:"Cancel"}),(0,n.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!==T&&!eB&&(0,n.jsxs)("div",{className:"figma-snapshot-stored-notice",children:[(0,n.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,n.jsx)("button",{type:"button",className:"figma-snapshot-load-btn",onClick:e3,children:"Reconnect build"})]}),"idle"===S&&null===I&&null===T&&!tu&&(0,n.jsxs)("div",{className:"figma-snapshot-empty",children:[(0,n.jsx)("p",{className:"figma-snapshot-empty-title",children:"Capture screens from a Figma board"}),(0,n.jsxs)("ol",{className:"figma-snapshot-empty-steps",children:[(0,n.jsx)("li",{children:"In Figma, select the frame or section you want to capture."}),(0,n.jsx)("li",{children:"Copy its link (Copy link to selection) — it contains the node-id."}),(0,n.jsx)("li",{children:"Paste it above, acknowledge the read-only scope, then take the snapshot."})]}),(0,n.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."})]}),tu&&(0,n.jsxs)("div",{className:"figma-snapshot-stored-notice",children:[(0,n.jsx)("p",{className:"figma-snapshot-stored-text",children:"A stored snapshot is available."}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-load-btn",onClick:to,"aria-disabled":eK?"true":void 0,"aria-busy":eK,children:eK?"Loading…":"Load snapshot"})]}),(0,n.jsxs)("section",{className:"figma-snapshot-dashboard","aria-label":"Snapshot dashboard",children:[(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-header",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"figma-snapshot-dashboard-eyebrow",children:"Snapshot dashboard"}),(0,n.jsx)("h2",{className:"figma-snapshot-dashboard-title",children:"Stored snapshots"})]}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-refresh",onClick:eQ,children:"Refresh"})]}),(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-tabs",role:"tablist","aria-label":"Snapshot views",children:[(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-tab",role:"tab","aria-selected":"board"===D,"aria-controls":`${j}-board-panel`,id:`${j}-board-tab`,onClick:()=>{null!==eD&&F("board")},disabled:null===eD,children:"This board"}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-tab",role:"tab","aria-selected":"recent"===D,"aria-controls":`${j}-recent-panel`,id:`${j}-recent-tab`,onClick:()=>{F("recent")},children:"Recent"})]}),"board"===D?(0,n.jsx)("div",{id:`${j}-board-panel`,className:"figma-snapshot-dashboard-panel",role:"tabpanel","aria-labelledby":`${j}-board-tab`,children:null===eD?th([],!1,null,"No board selected yet","Paste a valid Figma board link or load a stored snapshot to see this board's history.",!1):th(z,_,Y,"No snapshots stored for this board","Take the first snapshot for this board to make it available here.",!1)}):(0,n.jsx)("div",{id:`${j}-recent-panel`,className:"figma-snapshot-dashboard-panel",role:"tabpanel","aria-labelledby":`${j}-recent-tab`,children:th(K,W,G,"No snapshots stored yet","Stored Figma snapshots will appear here once the first board capture completes.",!0)})]}),null!==I&&(0,n.jsxs)("div",{className:"figma-snapshot-result",children:[(0,n.jsxs)("div",{className:"figma-snapshot-reduction",children:[(0,n.jsx)("p",{className:"figma-snapshot-reduction-hint",children:I.reductionHint}),(0,n.jsxs)("p",{className:"figma-snapshot-captured-at",children:["Captured ",(0,ak.formatDate)(I.fetchedAt)]}),eW&&(0,n.jsxs)("p",{className:"figma-snapshot-scope-note",children:["QI source scope: ",s??l.join(", ")]}),I.skippedCount>0&&(0,n.jsxs)("p",{className:"figma-snapshot-skipped-notice",children:[String(I.skippedCount)," screen",1!==I.skippedCount?"s":""," could not be rendered and were skipped."]})]}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-resnapshot-btn",onClick:e2,"aria-disabled":eB?"true":void 0,"aria-busy":eO,"aria-label":"Re-snapshot this board",children:eO?"Building…":"Re-snapshot"}),(0,n.jsxs)("div",{className:"figma-snapshot-codegen",children:[(0,n.jsxs)("div",{className:"figma-snapshot-codegen-actions",children:[(0,n.jsx)("button",{type:"button",className:"figma-snapshot-codegen-btn",onClick:e6,"aria-disabled":"generating"===ed?"true":void 0,"aria-busy":"generating"===ed,children:"generating"===ed?"Generating code…":"Generate code"}),"generating"===ed&&(0,n.jsx)("button",{type:"button",className:"figma-snapshot-codegen-cancel-btn",onClick:tr,children:"Cancel"})]}),"error"===ed&&null!==ep&&(0,n.jsx)("p",{className:"figma-snapshot-error",role:"alert",children:ep}),"done"===ed&&null!==em&&(0,n.jsxs)("div",{className:"figma-snapshot-code-result",children:[(0,n.jsxs)("p",{className:"figma-snapshot-code-summary",children:[String(em.fileCount)," reviewable file",1!==em.fileCount?"s":""," (",String(em.screenCount)," screen",1!==em.screenCount?"s":"",","," ",em.adapterName,") — proposal only, never auto-applied."]}),em.files.map(e=>(0,n.jsxs)("details",{className:"figma-snapshot-code-file",children:[(0,n.jsx)("summary",{className:"figma-snapshot-code-file-path",children:e.path}),(0,n.jsx)("pre",{className:"figma-snapshot-code-file-contents",children:(0,n.jsx)("code",{children:e.contents})})]},e.path))]})]}),(0,n.jsxs)("details",{className:"figma-snapshot-scopes",children:[(0,n.jsx)("summary",{className:"figma-snapshot-scopes-summary",children:"Required Figma PAT scopes"}),(0,n.jsx)("ul",{className:"figma-snapshot-scopes-list",children:(0,n.jsxs)("li",{children:[(0,n.jsx)("code",{children:"file_content:read"})," — read design file structure, node metadata, and rendered images"]})}),(0,n.jsxs)("p",{className:"figma-snapshot-scopes-note",children:["The token is read server-side from the vault, Keiko config, or"," ",(0,n.jsx)("code",{children:"FIGMA_ACCESS_TOKEN"})," environment variable. This window never holds or transmits the token."]}),(0,n.jsxs)("div",{className:"figma-snapshot-revoke-row",children:[eN?(0,n.jsxs)("span",{className:"figma-snapshot-revoke-confirm",children:[(0,n.jsx)("span",{className:"figma-snapshot-revoke-confirm-label",children:"Really revoke the stored token?"}),(0,n.jsx)("button",{ref:e$,type:"button",className:"figma-snapshot-revoke-confirm-btn",onClick:tc,children:"Yes, revoke"}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-revoke-cancel-btn",onClick:td,children:"Cancel"})]}):(0,n.jsx)("button",{ref:eT,type:"button",className:"figma-snapshot-revoke-btn",onClick:()=>{eS(!0),eI(null),eR(null)},children:"Revoke stored token"}),(0,n.jsx)("p",{className:"figma-snapshot-revoke-status",role:"status","aria-live":"polite","aria-atomic":"true",children:eC??eE??""})]})]}),eY.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("section",{className:"figma-snapshot-gallery","aria-label":eW?`${String(eY.length)} selected screen${1!==eY.length?"s":""}`:`${String(eX)} captured and structural screen${1!==eX?"s":""}`,children:eY.slice(0,eA).map((e,t)=>{let a=void 0===i?void 0:()=>i({snapshotRunId:I.runId,screenId:e.screen.screenId,name:e.screen.name}),l={snapshotRunId:I.runId,screenId:e.screen.screenId,name:e.screen.name};return"rendered"===e.kind?(0,n.jsx)(iJ,{index:t,screenId:e.screen.screenId,name:e.screen.name,irSummary:e.screen.irSummary,imageSrc:i$(I.runId,e.imageIndex),imageByteLength:e.screen.imageByteLength,onAddSource:a,isSourceSelected:eU.has(e.screen.screenId),dragPayload:l},e.screen.screenId):(0,n.jsx)(iJ,{index:t,screenId:e.screen.screenId,name:e.screen.name,irSummary:e.screen.irSummary,structuralReason:e.screen.reason,onAddSource:a,isSourceSelected:eU.has(e.screen.screenId),dragPayload:l},e.screen.screenId)})}),eA<eY.length?(0,n.jsx)("button",{type:"button",className:"figma-snapshot-gallery-more",onClick:()=>eM(e=>Math.min(e+24,eY.length)),children:"Show more screens"}):null]}):(0,n.jsx)("div",{className:"lk-empty",children:(0,n.jsx)("p",{className:"lk-empty-body",children:eW?"The selected screen is not present in this stored snapshot.":"No screens were captured from this board section."})})]})]})}function iX({snapshotRunId:e,screenId:t,screenName:l,loadScreenJsonImpl:s=iT}){let i,r=(0,a.useRef)(null),[o,c]=(0,a.useState)("idle"),[d,u]=(0,a.useState)(null),[m,h]=(0,a.useState)(null),[p,f]=(0,a.useState)(null),g=void 0!==(i=l?.trim())&&i.length>0?i:t?.trim()??"Selected Figma view",v=(0,a.useMemo)(()=>null===d?"":JSON.stringify(d,null,2),[d]),b=(0,a.useMemo)(()=>iq(v),[v]),x=(0,a.useCallback)(()=>{if(void 0===e||0===e.trim().length||void 0===t||0===t.trim().length){u(null),c("error"),h("Missing Figma JSON source reference.");return}r.current?.abort();let n=new AbortController;r.current=n,c("loading"),h(null),f(null),s(e,t,n.signal).then(e=>{u(e),c("done")}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||(u(null),h(e instanceof Error?e.message:"Failed to load Figma JSON."),c("error"))}).finally(()=>{r.current===n&&(r.current=null)})},[s,t,e]);(0,a.useEffect)(()=>(x(),()=>{r.current?.abort(),r.current=null}),[x]);let y=(0,a.useCallback)(()=>{if(0!==v.length){if(void 0===navigator.clipboard)return void f("Clipboard unavailable");navigator.clipboard.writeText(v).then(()=>f("Copied")).catch(()=>f("Copy failed"))}},[v]);return(0,n.jsxs)("section",{className:"figma-json-window","aria-label":`Figma JSON source ${g}`,children:[(0,n.jsxs)("header",{className:"figma-json-header",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"figma-json-eyebrow",children:"Figma JSON"}),(0,n.jsx)("h1",{className:"figma-json-heading",title:g,children:g}),(0,n.jsx)("p",{className:"figma-json-meta",children:null!==d?`${d.screen.kind} \xb7 ${(0,ak.formatBytes)(b)} \xb7 captured ${(0,ak.formatDate)(d.fetchedAt)}`:t})]}),(0,n.jsxs)("div",{className:"figma-json-actions",children:[(0,n.jsx)("span",{className:"figma-view-source-badge",children:"QI source"}),(0,n.jsx)("button",{type:"button",className:"figma-view-json-copy-btn",onClick:y,disabled:0===v.length,"aria-disabled":0===v.length?"true":void 0,children:"Copy JSON"})]})]}),"loading"===o?(0,n.jsx)("p",{className:"figma-json-status",role:"status",children:"Loading JSON…"}):null,"error"===o&&null!==m?(0,n.jsxs)("div",{className:"figma-json-error",role:"alert",children:[(0,n.jsx)("p",{children:m}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-load-btn",onClick:x,children:"Retry"})]}):null,null!==p?(0,n.jsx)("p",{className:"figma-view-json-copy-status",role:"status",children:p}):null,"done"===o&&v.length>0?(0,n.jsx)(iP,{text:v,className:"figma-json-code"}):null]})}function iQ({imageSrc:e,screenName:t}){let a,l=void 0!==(a=t?.trim())&&a.length>0?a:"Figma image source";return void 0===e||0===e.trim().length?(0,n.jsx)("section",{className:"figma-image-window","aria-label":l,children:(0,n.jsx)("div",{className:"figma-image-missing",role:"alert",children:"Image preview is unavailable."})}):(0,n.jsx)("section",{className:"figma-image-window","aria-label":l,children:(0,n.jsx)(ap.default,{className:"figma-image-preview",src:e,alt:l,width:720,height:480,unoptimized:!0,priority:!0})})}async function iZ(e,t){let n=(t?.method??"GET").toUpperCase(),a="GET"!==n&&"HEAD"!==n,l=await fetch(e,{...t,headers:{Accept:"application/json",...a?{"Content-Type":"application/json"}:{},...a?{"X-Keiko-CSRF":"1"}:{},...t?.headers??{}}});if(!l.ok){let e="INTERNAL",t=`HTTP ${l.status.toString()}`;try{let n=await l.json();e=n.error.code,t=n.error.message}catch{}throw new w.ApiError(e,t,l.status)}return l.json()}async function i0(){return iZ("/api/quality-intelligence/runs")}async function i1(e){return iZ(`/api/quality-intelligence/runs/${encodeURIComponent(e)}`)}async function i2(e){let t="QI_RUN_FAILED",n=`HTTP ${e.status.toString()}`;try{let a=await e.json();t=a.error?.code??t,n=a.error?.message??n}catch{}return new w.ApiError(t,n,e.status)}async function i4(e,t,n){let a=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}),l=a.headers.get("content-type")??"";if(!a.ok||!l.includes("text/event-stream"))throw await i2(a);let s=a.body;if(null===s)throw new w.ApiError("QI_NO_STREAM","The server did not return a progress stream.",a.status);let i=s.getReader(),r=new TextDecoder,o="";try{for(;!t.aborted;){let e=await i.read();if(e.done)break;let t=(o+=r.decode(e.value,{stream:!0})).split("\n");for(let e of(o=t.pop()??"",t)){let t=e.trim();if(t.startsWith("data:"))try{n(JSON.parse(t.slice(5).trim()))}catch{}}}}finally{await i.cancel().catch(()=>{}),i.releaseLock()}}async function i3(e){return iZ(`/api/quality-intelligence/runs/${encodeURIComponent(e)}`,{method:"DELETE"})}async function i6(e,t,n,a){return iZ(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/review`,{method:"POST",body:JSON.stringify({action:t,...void 0!==n?{candidateId:n}:{},...void 0!==a?{reviewerLabel:a}:{}})})}async function i5(e,t,n,a){return(await iZ(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/edit`,{method:"POST",body:JSON.stringify({candidateId:t,edited:n,...void 0!==a?{editorLabel:a}:{}})})).candidate}async function i8(e,t){return iZ(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/re-check`,{method:"POST",body:JSON.stringify({sources:t})})}async function i7(e,t){return iZ(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/regenerate-stale`,{method:"POST",body:JSON.stringify({sources:t})})}async function i9(e,t,n){return iZ(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/export`,{method:"POST",body:JSON.stringify({adapter:t,dryRun:n?.dryRun??!1,approvedOnly:n?.approvedOnly??!1})})}async function re(e,t){return iZ(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/traceability`,{method:"POST",body:JSON.stringify({format:t})})}var rt=e.i(68336);let rn={open:"Open",approved:"Approved","changes-requested":"Changes requested",rejected:"Rejected",withdrawn:"Withdrawn"},ra={open:"qi-review-open",approved:"qi-review-approved","changes-requested":"qi-review-changes",rejected:"qi-review-rejected",withdrawn:"qi-review-withdrawn"};function rl({state:e}){return(0,n.jsxs)("span",{className:`qi-review-badge ${ra[e]}`,children:[(0,n.jsx)("span",{className:"sr-only",children:"Review: "}),rn[e]]})}function rs(e){if(e instanceof w.ApiError){var t,n;return t=e.code,n=e.message,`${n} (${t})`}return e instanceof Error?e.message:"An unexpected error occurred."}function ri(e){try{return new Date(e).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"})}catch{return e}}let rr={running:"Running",succeeded:"Succeeded",failed:"Failed",cancelled:"Cancelled"},ro={running:"qi-badge-running",succeeded:"qi-badge-succeeded",failed:"qi-badge-failed",cancelled:"qi-badge-cancelled"};function rc(e){return"running"===e||"succeeded"===e||"failed"===e||"cancelled"===e}function rd({status:e}){let t=rc(e)?rr[e]:e,a=rc(e)?ro[e]:"qi-badge-default";return(0,n.jsx)("span",{className:`qi-badge ${a}`,children:t})}let ru={critical:"qi-sev-critical",high:"qi-sev-high",medium:"qi-sev-medium",low:"qi-sev-low"};function rm({severity:e}){let t="critical"===e||"high"===e||"medium"===e||"low"===e?ru[e]:"qi-sev-low";return(0,n.jsxs)("span",{className:`qi-sev ${t}`,children:[(0,n.jsx)("span",{className:"sr-only",children:"Severity: "}),e]})}function rh({score:e}){if(null===e)return(0,n.jsxs)("span",{className:"qi-badge qi-badge-default","data-testid":"qi-quality-badge",children:[(0,n.jsx)("span",{"aria-hidden":"true",children:"—"}),(0,n.jsx)("span",{className:"sr-only",children:"Quality score not available"})]});let t=Math.round(e);return(0,n.jsxs)("span",{className:`qi-badge ${t>=90?"qi-quality-high":t>=70?"qi-quality-mid":"qi-quality-low"}`,"data-testid":"qi-quality-badge",children:[t.toString(),(0,n.jsx)("span",{className:"sr-only",children:" out of 100"})]})}function rp({flag:e}){return(0,n.jsxs)("div",{role:"note","aria-label":`Weak test flagged by the quality judge: ${e.rationale}`,className:"qi-weak-flag","data-testid":"qi-weak-flag",children:[(0,n.jsxs)("span",{className:"qi-weak-flag-badge",children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"qi-weak-flag-icon",children:"⚠"}),"Weak test"]}),(0,n.jsx)("p",{className:"qi-weak-flag-reason",children:e.rationale})]})}let rf={verifiability:"Verifiability",atomicity:"Atomicity",determinism:"Determinism","ac-fidelity":"AC fidelity"};function rg({verdict:e}){let t=Math.round(e.score),a="strong"===e.verdict?"Strong":"Weak";return(0,n.jsxs)("div",{role:"note","aria-label":`Quality judge verdict: ${a}, ${t.toString()} out of 100. ${e.overallRationale}`,className:"qi-cand-block","data-testid":"qi-quality-verdict",children:[(0,n.jsx)("p",{className:"qi-cand-block-label",children:"Quality verdict"}),(0,n.jsxs)("p",{children:[a," - ",t.toString(),"/100"]}),(0,n.jsx)("ul",{className:"qi-cand-list","aria-label":"Quality dimensions",children:e.dimensions.map(e=>(0,n.jsxs)("li",{children:[rf[e.name]??e.name," ",Math.round(e.score).toString(),": ",e.rationale]},e.name))})]})}function rv({height:e=20,width:t="100%"}){return(0,n.jsx)("div",{"aria-hidden":"true",className:"qi-skeleton",style:{height:e,width:t}})}function rb(){return(0,n.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,n.jsxs)("div",{className:"qi-skeleton-row",children:[(0,n.jsx)(rv,{height:14,width:"60%"}),(0,n.jsx)(rv,{height:12,width:"40%"})]},e))})}function rx({message:e,onRetry:t}){return(0,n.jsxs)("div",{role:"alert","aria-live":"assertive",className:"lk-alert","data-testid":"qi-error-state",children:[e,(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:t,children:"Retry"})]})}let ry="connectedSourcesJson";function rw(e,t){let n=e[t];return"string"==typeof n?n:void 0}function rj(e,t){return"string"==typeof e[t]}function rk(e){if(!("object"==typeof e&&null!==e&&!Array.isArray(e))||!rj(e,"label"))return!1;switch(e.kind){case"file":case"workspace":return rj(e,"path");case"capsule":return rj(e,"capsuleId");case"capsule-set":return rj(e,"capsuleSetId");case"figma-snapshot":let t;return rj(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&&rj(e,"snapshotRunId")&&rj(e,"screenId");default:return!1}}function rN(e){return e.length>0?{[ry]:JSON.stringify(e)}:{}}function rS(e){let t=e.split(/[\\/]/u).filter(e=>e.length>0);return t.length>0?t[t.length-1]??e:e}function rC(e){return e.replaceAll("\\","/")}function rI(e){if(/^[A-Za-z]:[/\\]?$/u.test(e))return e.replaceAll("\\","/");if(/^\/\/[^/]+\/[^/]+$/u.test(rC(e)))return rC(e);let t=rC(e).replace(/\/+$/u,"");return 0===t.length&&e.length>0?"/":t}function rE(e){let t=e.connectedRoot??null,n=function(e,t){let n=t?.trim()??"";if(0===n.length)return null;if(n.startsWith("/")||/^[A-Za-z]:[/\\]/u.test(n)||n.startsWith("\\\\")||n.startsWith("//"))return n;let a=e?.trim()??"";if(0===a.length)return null;let l=rI(a),s=rC(n).replace(/^\/+/u,""),i=l.endsWith("/")?"":"/";return`${l}${i}${s}`}(t,e.connectedFilePath??null),a=null!==t?rI(t):null,l=(void 0!==e.connectedRoots&&null!==e.connectedRoots&&e.connectedRoots.length>0?e.connectedRoots:null!==t?[t]:[]).map(rI),s=null!==n?l.filter(e=>e!==a):l,i=[];for(let e of(null!==n&&i.push({kind:"file",label:rS(n),path:n}),s))i.push({kind:"workspace",label:rS(e),path:e});for(let t of e.connectedCapsuleIds??[])i.push({kind:"capsule",label:t,capsuleId:t});for(let t of e.connectedCapsuleSetIds??[])i.push({kind:"capsule-set",label:t,capsuleSetId:t});for(let t of void 0!==e.connectedFigmaSnapshotSources?e.connectedFigmaSnapshotSources:(e.connectedFigmaSnapshotRunIds??[]).map(e=>({kind:"figma-snapshot",label:e,snapshotRunId:e})))i.push(t);for(let t of e.connectedImageSources??[])i.push(t);let r=new Set,o=[];for(let e of i){if(o.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);r.has(t)||(r.add(t),o.push(e))}return o}let rR=[{id:"regression-default",label:"Regression (default)"},{id:"banking-default",label:"Banking"},{id:"insurance-default",label:"Insurance"}],r$=[{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"}],rT={phase:"Starting…",stageName:null,candidates:0,findings:0,atomCount:null,droppedSourceCount:0,skippedSources:[]},rA="Der Lauf wurde nicht erfolgreich abgeschlossen. Passe die Quelle an und versuche es erneut.";function rM(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 ·")?"Figma JSON":"Figma snapshot";case"image":return"Image"}}function rL(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 rq({onRunCompleted:e,startImpl:t=i4,fetchCapsulesImpl:l=lw.fetchCapsules,fetchCapsuleSetsImpl:s=lw.fetchCapsuleSets,fetchProjectsImpl:i=w.fetchProjects,fetchFilesTreeImpl:r=w.fetchFilesTree,connectedRoot:o=null,connectedFilePath:c=null,connectedRoots:d,connectedCapsuleIds:u,connectedCapsuleSetIds:m,connectedFigmaSnapshotRunIds:h,connectedFigmaSnapshotSources:p,connectedImageSources:f}){let[g,v]=(0,a.useState)(""),[b,x]=(0,a.useState)("requirements"),[y,j]=(0,a.useState)(""),[k,N]=(0,a.useState)(""),[S,C]=(0,a.useState)(""),[I,E]=(0,a.useState)(""),[R,$]=(0,a.useState)(!1),[T,A]=(0,a.useState)([]),[M,L]=(0,a.useState)([]),[q,P]=(0,a.useState)(!1),[D,F]=(0,a.useState)(null),[z,O]=(0,a.useState)("regression-default"),[K,B]=(0,a.useState)(""),[_,U]=(0,a.useState)(!1),[W,H]=(0,a.useState)(rT),[Y,J]=(0,a.useState)(null),[G,V]=(0,a.useState)(null),X=(0,a.useRef)(null),Q=(0,a.useRef)(null),Z=(0,a.useRef)(null),ee=(0,a.useRef)(!1),et=rE({connectedRoot:o,connectedFilePath:c,connectedRoots:d,connectedCapsuleIds:u,connectedCapsuleSetIds:m,connectedFigmaSnapshotRunIds:h,connectedFigmaSnapshotSources:p,connectedImageSources:f}),en=et.length>0,ea=T.find(e=>e.id===S),el=M.find(e=>e.id===I),es=k.trim().length>0,ei="requirements"===b?y.trim().length>0:"workspace"===b||"file"===b?es:"capsule"===b?S.trim().length>0:I.trim().length>0,er="requirements"===b?0===y.trim().length:("workspace"===b||"file"===b)&&!es,eo=ei||er&&en,ec=K.trim(),ed=0===ec.length?void 0:/^\d+$/u.test(ec)?Number(ec):NaN,eu=void 0===ed||Number.isSafeInteger(ed)&&Number.isFinite(ed),em=!eo||!eu,eh=(0,a.useId)(),ep=(0,a.useId)(),ef=(0,a.useId)(),eg=(0,a.useId)(),ev=(0,a.useId)(),eb=eo?eu?void 0:ep:eh,ex="workspace"===b||"file"===b?b:null,ey=(0,a.useCallback)(e=>{x(e),$(!1),J(null),F(null)},[]),ew=(0,a.useCallback)(e=>{if(_)return;let t="ArrowRight"===e.key||"ArrowDown"===e.key?1:"ArrowLeft"===e.key||"ArrowUp"===e.key?-1:0;if(0===t)return;e.preventDefault();let n=r$.length,a=(Math.max(0,r$.findIndex(e=>e.id===b))+t+n)%n,l=r$[a];void 0!==l&&(ey(l.id),e.currentTarget.parentElement?.querySelectorAll('[role="radio"]')[a]?.focus())},[ey,_,b]),ej=(0,a.useCallback)(e=>{var t,n,a;"event"===e.type&&("stage:failed"===e.kind||"run:failed"===e.kind)&&"string"==typeof e.reasonSummary&&(Z.current=e.reasonSummary),"done"===e.type&&("succeeded"===e.status?(Q.current=e.runId,!0===e.degraded&&V(function(e){let t="Die Modellgenerierung ist fehlgeschlagen — Keiko hat deterministische Baseline-Testfälle aus der Evidenz erstellt. Diese sind nicht modellgestützt; prüfe das Modell-Gateway und starte den Lauf für modellgestützte Testfälle 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})`}(e.reasonSummary??null))):"failed"===e.status&&J(null==(t=e.reasonSummary??Z.current)||0===t.trim().length?rA:"qi-run-error"===t?"Die Modellgenerierung ist fehlgeschlagen, bevor nutzbare Testfälle zurückgegeben wurden. Versuche es mit einer kleineren Quelle oder prüfe das ausgewählte Modell-Gateway.":"qi-error: UnparseableModelOutputError"===t?"Das Modell hat eine Ausgabe geliefert, die nicht zu Testfällen geparst werden konnte. Versuche es erneut oder nutze ein Modell mit strukturierter JSON-Ausgabe.":"qi-error: QI_PROMPT_TOO_LARGE"===t?"Der zusammengestellte Quellkontext ist für das Modell zu groß. Reduziere die Quelle und versuche es erneut.":t.startsWith("qi-error: ")?`${rA} (${t.slice(10)})`:t.startsWith("qi-safe-error: ")?`${rA} (${t.slice(15)})`:`${rA} (${t})`)),"error"===e.type&&J((n=e.code,a=e.message,`${a} (${n})`)),H(t=>(function(e,t){if("accepted"===t.type)return{...e,phase:"Ingested sources",atomCount:t.atomCount,droppedSourceCount:t.droppedSourceCount??0,skippedSources:t.skippedSources??[]};if("event"===t.type){let n="candidate:proposed"===t.kind?e.candidates+1:e.candidates,a="finding:recorded"===t.kind?e.findings+1:e.findings,l=t.stageName??e.stageName;return{...e,phase:t.kind,stageName:l,candidates:n,findings:a}}return e})(t,e))},[]),ek="capsule"===b||"capsule-set"===b;(0,a.useEffect)(()=>{if(!ek)return;let e=!1;return async function(){P(!0),F(null);try{let[t,n]=await Promise.allSettled([l(),s()]);if(e)return;"fulfilled"===t.status?A(t.value.capsules.filter(e=>"ready"===e.lifecycleState)):(A([]),"capsule"===b&&F(rs(t.reason))),"fulfilled"===n.status?L(n.value.capsuleSets):(L([]),"capsule-set"===b&&F(rs(n.reason)))}finally{e||P(!1)}}(),()=>{e=!0}},[l,s,ek,b]),(0,a.useEffect)(()=>{if("capsule"===b){let e=T.some(e=>e.id===S)?S:T[0]?.id??"";e!==S&&C(e)}if("capsule-set"===b){let e=M.some(e=>e.id===I)?I:M[0]?.id??"";e!==I&&E(e)}},[S,I,M,T,b]);let eN=(0,a.useCallback)(()=>{let e=g.trim();return"requirements"===b&&y.trim().length>0?[{kind:"requirements",label:e||"Requirements",text:y}]:"workspace"===b&&k.trim().length>0?[{kind:"workspace",label:e||"Folder",path:k.trim()}]:"file"===b&&k.trim().length>0?[{kind:"file",label:e||"File",path:k.trim()}]:"capsule"===b&&S.trim().length>0?[{kind:"capsule",label:e||ea?.displayName||"Knowledge capsule",capsuleId:S.trim()}]:"capsule-set"===b&&I.trim().length>0?[{kind:"capsule-set",label:e||el?.displayName||"Capsule set",capsuleSetId:I.trim()}]:null},[S,I,g,k,ea,el,b,y]),eS=(0,a.useCallback)(async()=>{if(!eo||_||!eu||ee.current)return;ee.current=!0,U(!0),J(null),V(null),H(rT),Q.current=null,Z.current=null;let n=new AbortController;X.current=n;let a=eN()??et,l={sources:a,profileId:z,...void 0!==ed?{seed:ed}:{}};try{await t(l,n.signal,ej);let s=Q.current;null!==s&&e?.(s,a.filter(e=>"requirements"!==e.kind))}catch(e){n.signal.aborted||J(rs(e))}finally{U(!1),X.current=null,ee.current=!1}},[eo,z,_,et,eN,ej,e,ed,eu,t]),eC=(0,a.useCallback)(()=>{X.current?.abort()},[]),eI=W.droppedSourceCount>0?`${W.droppedSourceCount.toString()} source${1!==W.droppedSourceCount?"s":""} over the 16-source limit ${1!==W.droppedSourceCount?"were":"was"} not included.`:null,eE=W.skippedSources.length>0?`${W.skippedSources.length.toString()} connected source${1!==W.skippedSources.length?"s":""} could not be read and ${1!==W.skippedSources.length?"were":"was"} skipped: ${W.skippedSources.map(e=>e.label).join(", ")}.`:null,eR=[eI,eE].filter(e=>null!==e).join(" ");return(0,n.jsxs)("section",{className:"qi-launcher","aria-label":"Start a Quality Intelligence run",children:[(0,n.jsx)("header",{className:"qi-col-header",children:(0,n.jsx)("h2",{className:"qi-col-title",children:"New run"})}),(0,n.jsxs)("div",{className:"qi-launcher-body",children:[1===et.length&&void 0!==et[0]?(0,n.jsxs)("div",{className:"qi-connected-source","data-testid":"qi-connected-source",children:[(0,n.jsxs)("span",{className:"qi-connected-kind",children:["Connected ",rM(et[0]).toLowerCase()]}),(0,n.jsx)("span",{className:"qi-connected-path qi-monospace",title:rL(et[0]),children:rL(et[0])}),(0,n.jsx)("span",{className:"qi-connected-hint",children:ei?"Manual input below overrides the connected source for this run.":`Generate uses the connected ${rM(et[0]).toLowerCase()}.`})]}):et.length>1?(0,n.jsxs)("div",{className:"qi-connected-source","data-testid":"qi-connected-source",children:[(0,n.jsxs)("span",{className:"qi-connected-kind",children:["Connected sources (",et.length.toString(),")"]}),(0,n.jsx)("ul",{className:"qi-connected-roots","aria-label":"Connected sources",children:et.map(e=>(0,n.jsxs)("li",{className:"qi-connected-root-item",children:[(0,n.jsx)("span",{className:"qi-connected-root-name",children:rM(e)}),(0,n.jsx)("span",{className:"qi-connected-path qi-monospace",title:rL(e),children:rL(e)})]},`${e.kind}:${rL(e)}`))}),(0,n.jsx)("span",{className:"qi-connected-hint",children:ei?"Manual input below overrides the connected sources for this run.":"Generate uses all connected sources."})]}):null,(0,n.jsxs)("div",{className:"qi-launcher-row",children:[(0,n.jsxs)("label",{className:"qi-field",children:[(0,n.jsx)("span",{className:"qi-field-label",children:"Source label"}),(0,n.jsx)("input",{type:"text",className:"qi-input",value:g,placeholder:"e.g. Funds Transfer — acceptance criteria",disabled:_,"aria-describedby":en&&!ei?ef:void 0,onChange:e=>{v(e.target.value)}}),en&&!ei?(0,n.jsx)("span",{className:"qi-field-hint",id:ef,children:"Applies to manual input only — connected sources use their own labels."}):null]}),(0,n.jsxs)("div",{className:"qi-field qi-field-kind",children:[(0,n.jsx)("span",{className:"qi-field-label",id:eg,children:"Source type"}),(0,n.jsx)("div",{className:"qi-source-kind-grid",role:"radiogroup","aria-labelledby":eg,"aria-disabled":_||void 0,children:r$.map(e=>(0,n.jsxs)("button",{type:"button",className:"qi-source-kind-option",role:"radio","aria-checked":b===e.id,tabIndex:b===e.id?0:-1,disabled:_,onClick:()=>ey(e.id),onKeyDown:ew,children:[(0,n.jsx)("span",{children:e.label}),(0,n.jsx)("span",{children:e.hint})]},e.id))})]})]}),function(){if("requirements"===b)return(0,n.jsxs)("label",{className:"qi-field",children:[(0,n.jsx)("span",{className:"qi-field-label",children:"Requirements"}),(0,n.jsx)("textarea",{className:"qi-textarea",value:y,rows:6,placeholder:"Paste requirements or acceptance criteria, one statement per line.",disabled:_,onChange:e=>{j(e.target.value)}})]});if("workspace"===b||"file"===b){let e="file"===b;return(0,n.jsxs)("div",{className:"qi-field",children:[(0,n.jsx)("span",{className:"qi-field-label",id:ev,children:e?"File path":"Folder path"}),(0,n.jsxs)("div",{className:"qi-path-picker",children:[(0,n.jsx)("div",{className:"qi-path-value qi-monospace",role:"textbox","aria-readonly":"true","aria-labelledby":ev,title:k,"data-empty":0===k.trim().length?"true":void 0,children:k.trim().length>0?k:e?"Choose a local file…":"Choose a local folder…"}),(0,n.jsx)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-browse-btn",disabled:_,onClick:()=>$(!0),children:"Browse"})]})]})}let e="capsule"===b,t=e?T:M;return(0,n.jsxs)("label",{className:"qi-field",children:[(0,n.jsx)("span",{className:"qi-field-label",children:e?"Knowledge capsule":"Capsule set"}),(0,n.jsxs)("select",{className:"qi-select",value:e?S:I,disabled:_||q||null!==D||0===t.length,onChange:t=>{e?C(t.target.value):E(t.target.value)},children:[q?(0,n.jsx)("option",{value:"",children:"Loading connectors..."}):null,q||0!==t.length?null:(0,n.jsx)("option",{value:"",children:e?"No ready capsules":"No capsule sets"}),e?T.map(e=>(0,n.jsx)("option",{value:e.id,children:e.displayName},e.id)):M.map(e=>(0,n.jsx)("option",{value:e.id,children:`${e.displayName} (${String(e.capsuleCount)} capsules)`},e.id))]})]})}(),null!==D?(0,n.jsx)("p",{className:"lk-alert",role:"alert","data-testid":"qi-connector-error",children:D}):null,(0,n.jsxs)("div",{className:"qi-launcher-controls",children:[(0,n.jsxs)("label",{className:"qi-field qi-field-inline",children:[(0,n.jsx)("span",{className:"qi-field-label",children:"Policy profile"}),(0,n.jsx)("select",{className:"qi-select",value:z,disabled:_,onChange:e=>{O(e.target.value)},children:rR.map(e=>(0,n.jsx)("option",{value:e.id,children:e.label},e.id))})]}),(0,n.jsxs)("label",{className:"qi-field qi-field-inline",children:[(0,n.jsx)("span",{className:"qi-field-label",children:"Seed (optional)"}),(0,n.jsx)("input",{type:"number",min:0,step:1,className:"qi-input",value:K,placeholder:"e.g. 42",disabled:_,"aria-invalid":!eu||void 0,"aria-describedby":eu?void 0:ep,onChange:e=>{B(e.target.value),J(null)}}),eu?null:(0,n.jsx)("span",{className:"qi-field-error",id:ep,children:"Seed must be a non-negative integer."})]}),(0,n.jsx)("button",{type:"button",className:_?"qi-btn qi-btn-secondary":"qi-btn qi-btn-primary","aria-disabled":!_&&em||void 0,"aria-describedby":_?void 0:eb,onClick:()=>{_?eC():em||eS()},children:_?"Cancel":"Generate test cases"}),_||eo?null:(0,n.jsx)("span",{className:"qi-generate-hint",id:eh,children:"Add requirements text, a folder path, a file path, select a capsule, select a capsule set, or connect a source to generate."})]}),_?(0,n.jsxs)("div",{className:"qi-progress","data-testid":"qi-launch-progress","aria-hidden":"true",children:[(0,n.jsx)("span",{className:"qi-progress-spinner","aria-hidden":"true"}),(0,n.jsxs)("span",{className:"qi-progress-text",children:[null!==W.stageName?`Stage: ${W.stageName} \xb7 `:"",W.candidates.toString()," test case",1!==W.candidates?"s":"",W.findings>0?` \xb7 ${W.findings.toString()} finding${1!==W.findings?"s":""}`:""]})]}):null,(0,n.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}. `:"",a=`${t.candidates.toString()} test case${1!==t.candidates?"s":""}`,l=t.findings>0?`, ${t.findings.toString()} finding${1!==t.findings?"s":""}`:"";return`${n}${a}${l}`}(_,W)}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:eR}),null!==eI||null!==eE?(0,n.jsxs)("div",{className:"qi-coverage-notice","data-testid":"qi-coverage-notice",children:[null!==eI?(0,n.jsx)("p",{className:"qi-coverage-line",children:eI}):null,null!==eE?(0,n.jsx)("p",{className:"qi-coverage-line",children:eE}):null]}):null,null!==G?(0,n.jsx)("p",{className:"qi-degraded-notice",role:"status","data-testid":"qi-launch-degraded",children:G}):null,null!==Y?(0,n.jsx)("p",{className:"lk-alert",role:"alert","data-testid":"qi-launch-error",children:Y}):null]}),R&&null!==ex?(0,n.jsx)(rt.LocalFileBrowserDialog,{mode:"file"===ex?"file":"folder",title:`Choose ${"file"===ex?"file":"folder"} source`,description:"Browse a registered local project or enter an absolute folder root.",initialRootPath:"file"===ex?(0,rt.dirname)(k):k,fetchProjectsImpl:i,fetchFilesTreeImpl:r,onCancel:()=>$(!1),onApply:e=>{N("file"===ex?(0,rt.displayLocalPath)(e.rootPath,e.files[0]??null):e.folderPath),$(!1),J(null)}}):null]})}function rP({run:e,onOpen:t,onDelete:l,deleting:s}){var i;let r=e.totals.candidates,[o,c]=(0,a.useState)(!1),d=(0,a.useRef)(null),u=(0,a.useRef)(null),m=(0,a.useRef)(null);(0,a.useEffect)(()=>{o&&u.current?.focus()},[o]);let h=(0,a.useCallback)(()=>{c(!1),requestAnimationFrame(()=>{d.current?.focus()})},[]),p=(0,a.useCallback)(e=>{"Escape"===e.key&&(e.preventDefault(),h())},[h]),f=(0,a.useCallback)(()=>{s||l(e.id)},[s,l,e.id]);return(0,n.jsxs)("li",{style:{display:"flex",alignItems:"stretch"},children:[(0,n.jsxs)("button",{type:"button",className:"qi-run-item",style:{flex:1},onClick:()=>{t(e.id,[])},"aria-label":`Open run ${e.id} — ${rc(i=e.status)?rr[i]:i}, ${ri(e.requestedAt)}, ${r.toString()} test case${1!==r?"s":""}, review ${rn[e.reviewState]}`,title:`Open run ${e.id}`,children:[(0,n.jsx)("span",{className:"qi-run-title",children:ri(e.requestedAt)}),(0,n.jsx)(rd,{status:e.status}),(0,n.jsx)(rl,{state:e.reviewState}),(0,n.jsxs)("span",{className:"qi-run-id",children:[e.id.slice(0,16),"…"]}),(0,n.jsxs)("span",{className:"qi-run-totals",children:[e.totals.candidates.toString()," test case",1!==e.totals.candidates?"s":""]})]}),o?(0,n.jsxs)("div",{className:"qi-cand-actions",role:"group","aria-label":`Confirm deleting run ${ri(e.requestedAt)}`,style:{display:"flex",alignItems:"center",gap:4,padding:"0 6px",flexShrink:0},children:[(0,n.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 ${ri(e.requestedAt)}`,"aria-busy":s||void 0,"aria-disabled":s||void 0,onClick:f,onKeyDown:p,children:s?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{"aria-hidden":"true",children:"Deleting…"}),(0,n.jsx)("span",{className:"sr-only",children:"Deleting run, please wait"})]}):"Confirm delete"}),(0,n.jsx)("button",{ref:u,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:p,children:"Cancel"})]}):(0,n.jsx)("button",{ref:d,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 ${ri(e.requestedAt)}`,onClick:()=>{c(!0)},children:"Delete"})]})}function rD({openRun:e,connectedRoot:t=null,connectedFilePath:l=null,connectedRoots:s,connectedCapsuleIds:i,connectedCapsuleSetIds:r,connectedFigmaSnapshotRunIds:o,connectedFigmaSnapshotSources:c,connectedImageSources:d,fetchRunsImpl:u=i0,deleteImpl:m=i3}){let[h,p]=(0,a.useState)([]),[f,g]=(0,a.useState)(0),[v,b]=(0,a.useState)(!1),[x,y]=(0,a.useState)(!0),[w,j]=(0,a.useState)(null),[k,N]=(0,a.useState)(25),[S,C]=(0,a.useState)(null),[I,E]=(0,a.useState)(""),R=(0,a.useCallback)(async()=>{y(!0),j(null);try{let e=await u();p(e.runs),g(e.totalRunIds),b(e.truncated)}catch(e){j(rs(e))}finally{y(!1)}},[u]);(0,a.useEffect)(()=>{R()},[R]);let $=(0,a.useCallback)((t,n)=>{R(),e(t,n)},[R,e]),T=(0,a.useCallback)(async e=>{if(null===S){C(e),j(null);try{await m(e),E("Run deleted."),await R()}catch(e){j(rs(e))}finally{C(null)}}},[S,m,R]);return(0,n.jsxs)("div",{className:"qi-hub",children:[(0,n.jsx)(rq,{onRunCompleted:$,connectedRoot:t,connectedFilePath:l,connectedRoots:s,connectedCapsuleIds:i,connectedCapsuleSetIds:r,connectedFigmaSnapshotRunIds:o,connectedFigmaSnapshotSources:c,connectedImageSources:d}),(0,n.jsxs)("section",{className:"qi-hub-runs","aria-label":"Quality Intelligence runs",children:[(0,n.jsxs)("header",{className:"qi-col-header",children:[(0,n.jsx)("h2",{className:"qi-col-title",children:"Runs"}),x||null!==w?null:(0,n.jsx)("span",{className:"qi-col-count",children:f.toString()})]}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:x?"Loading runs…":null===w?`Run list loaded: ${h.length.toString()} run${1===h.length?"":"s"}${v?` of ${f.toString()}`:""}.`:""}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true",children:I}),(0,n.jsx)("div",{className:"qi-col-body","aria-busy":x,children:x?(0,n.jsx)(rb,{}):null!==w?(0,n.jsx)(rx,{message:w,onRetry:()=>{R()}}):0===h.length?(0,n.jsxs)("div",{className:"lk-empty",children:[(0,n.jsx)("p",{className:"lk-empty-title",children:"No runs yet"}),(0,n.jsx)("p",{className:"lk-empty-body",children:"Start a run above — generated test cases open as cards on your workspace."})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("ul",{className:"qi-run-list","aria-label":"Run list",children:h.slice(0,k).map(t=>(0,n.jsx)(rP,{run:t,onOpen:e,onDelete:e=>{T(e)},deleting:S===t.id},t.id))}),k<h.length?(0,n.jsxs)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-show-more",onClick:()=>{N(e=>e+25)},children:["Show more runs (",(h.length-k).toString()," remaining)"]}):null,v?(0,n.jsx)("p",{className:"qi-runs-truncated","data-testid":"qi-runs-truncated",children:`Showing ${h.length.toString()} of ${f.toString()} runs.`}):null]})})]})]})}e.s(["QUALITY_INTELLIGENCE_SCHEMA_VERSION",0,"1"],73859),e.i(73859);let rF=["..","/","\\"],rz=(e,t)=>"string"!=typeof e?{ok:!1,reason:`${t} must be a string`}:0===e.length?{ok:!1,reason:`${t} must not be empty`}:0===e.trim().length?{ok:!1,reason:`${t} must not be whitespace-only`}:e!==e.trim()?{ok:!1,reason:`${t} must not have leading or trailing whitespace`}:e.length>256?{ok:!1,reason:`${t} exceeds max length ${String(256)}`}:e.normalize("NFKC")!==e?{ok:!1,reason:`${t} must be NFKC-normalised`}:(e=>{for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n<=31||127===n||n>=128&&n<=159)return!0}return!1})(e)?{ok:!1,reason:`${t} contains control characters`}:rF.some(t=>e.includes(t))?{ok:!1,reason:`${t} contains forbidden path fragment`}:{ok:!0},rO=(e,t)=>{let n=rz(e,t);if(!n.ok)throw TypeError(`Invalid ${t}: ${n.reason}`);return e},rK=e=>1564===e||e>=8203&&e<=8207||e>=8234&&e<=8238||e>=8294&&e<=8297||65279===e,rB=e=>!!(/[a-z][a-z0-9+.-]*:\/\//iu.test(e)||/AKIA[0-9A-Z]{12,}/u.test(e)||/(?:ghp_|gho_|github_pat_)[A-Za-z0-9_]{20,}/u.test(e)||/xox[baprs]-[A-Za-z0-9-]{10,}/u.test(e)||/sk-[A-Za-z0-9]{16,}/u.test(e)||/\bBearer\s+\S/u.test(e)||/-----BEGIN [A-Z ]*PRIVATE KEY-----/u.test(e)||/^(?:\/|[A-Za-z]:[\\/]|\\\\)/u.test(e)||(e=>{for(let t of e)if(rK(t.codePointAt(0)??0))return!0;return!1})(e)),r_=e=>Number.isFinite(e)&&e>=0&&e<=1,rU=Object.freeze({critical:0,high:1,medium:2,low:3}),rW=new Set(["jira-issues","qtest","xray","polarion","alm","quality-center"]),rH=["verifiability","atomicity","determinism","ac-fidelity"],rY=Object.freeze({type:"object",additionalProperties:!1,required:["dimensions","overallRationale"],properties:{dimensions:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","score","rationale"],properties:{name:{type:"string",enum:[...rH]},score:{type:"integer",minimum:0,maximum:100},rationale:{type:"string"}}}},overallRationale:{type:"string"}}});e.s(["QUALITY_INTELLIGENCE_AUDIT_MANIFEST_SCHEMA_VERSION",0,1,"QUALITY_INTELLIGENCE_COVERAGE_KINDS",0,["derived","asserted","manual"],"QUALITY_INTELLIGENCE_EVENT_SCHEMA_VERSION",0,1,"QUALITY_INTELLIGENCE_EVIDENCE_ATOM_KINDS",0,["requirement","design-fragment","code-fragment","document-excerpt","human-statement"],"QUALITY_INTELLIGENCE_EXPORT_ADAPTERS",0,["jira-issues","qtest","xray","polarion","alm","csv","json","spreadsheet-safe-csv","markdown","plain-text","quality-center"],"QUALITY_INTELLIGENCE_HANDOFF_PROMPTED_ACTIONS",0,["design-tests","validate-tests","review-coverage","request-export"],"QUALITY_INTELLIGENCE_LIFECYCLE_STATUSES",0,["draft","finalised","archived"],"QUALITY_INTELLIGENCE_PLANNER_KINDS",0,["scripted","model-routed"],"QUALITY_INTELLIGENCE_PRIORITIES",0,["P0","P1","P2","P3"],"QUALITY_INTELLIGENCE_REDACTION_STATUSES",0,["redacted","not-required"],"QUALITY_INTELLIGENCE_REVIEWER_KINDS",0,["human-author","human-reviewer","judge"],"QUALITY_INTELLIGENCE_REVIEW_STATES",0,["open","approved","changes-requested","rejected","withdrawn"],"QUALITY_INTELLIGENCE_RISK_CLASSES",0,["safety","compliance","regression","functional","visual"],"QUALITY_INTELLIGENCE_RUN_EVENT_KINDS",0,["run:queued","run:started","stage:started","stage:completed","stage:failed","candidate:proposed","finding:recorded","review:requested","review:completed","run:succeeded","run:failed","run:cancelled"],"QUALITY_INTELLIGENCE_SCHEMA_VERSION",0,"1","QUALITY_INTELLIGENCE_SEVERITIES",0,["critical","high","medium","low"],"QUALITY_INTELLIGENCE_SEVERITY_RANK",0,rU,"QUALITY_INTELLIGENCE_SOURCE_KINDS",0,["repository-context","local-knowledge-capsule","figma-evidence","human-context","connector-document"],"QUALITY_INTELLIGENCE_TEST_CASE_STATUSES",0,["proposed","accepted","rejected","needs-review"],"QUALITY_INTELLIGENCE_TMS_ADAPTERS",0,rW,"QUALITY_INTELLIGENCE_VALIDATION_FINDING_KINDS",0,["logic-defect","faithfulness-defect","semantic-defect","mutation-defect","policy-violation","manual-rejection","coverage-gap","test-quality"],"TEST_QUALITY_JUDGE_RESPONSE_SCHEMA",0,rY,"TEST_QUALITY_RUBRIC_DIMENSIONS",0,rH,"asQualityIntelligenceAuditSummaryId",0,e=>rO(e,"QualityIntelligenceAuditSummaryId"),"asQualityIntelligenceCoverageMapId",0,e=>rO(e,"QualityIntelligenceCoverageMapId"),"asQualityIntelligenceEvidenceAtomId",0,e=>rO(e,"QualityIntelligenceEvidenceAtomId"),"asQualityIntelligenceExportBundleId",0,e=>rO(e,"QualityIntelligenceExportBundleId"),"asQualityIntelligenceReviewRecordId",0,e=>rO(e,"QualityIntelligenceReviewRecordId"),"asQualityIntelligenceRunId",0,e=>rO(e,"QualityIntelligenceRunId"),"asQualityIntelligenceSourceEnvelopeId",0,e=>rO(e,"QualityIntelligenceSourceEnvelopeId"),"asQualityIntelligenceTestCaseId",0,e=>rO(e,"QualityIntelligenceTestCaseId"),"asQualityIntelligenceValidationFindingId",0,e=>rO(e,"QualityIntelligenceValidationFindingId"),"assertCoverageMapInvariant",0,e=>{for(let t=0;t<e.mappings.length;t+=1){let n=e.mappings[t];if(void 0===n)throw RangeError(`Coverage map mapping[${String(t)}] is missing`);if(!r_(n.confidence))throw RangeError(`Coverage map mapping[${String(t)}] has out-of-range confidence ${String(n.confidence)}`);if(0===n.candidateIds.length)throw RangeError(`Coverage map mapping[${String(t)}] must reference at least one candidate`)}},"assertExportBundleInvariant",0,e=>{if(!/^[0-9a-f]{64}$/u.test(e.integrityHashSha256Hex))throw Error(`Export bundle integrity hash must be a lowercase sha256 hex string (id=${e.id})`);if(rW.has(e.targetAdapter)&&!e.redactionAttested)throw Error(`Export bundle targeting TMS adapter "${e.targetAdapter}" requires redactionAttested === true (id=${e.id})`)},"assertQualityIntelligenceNever",0,e=>{throw TypeError(`Unexpected Quality Intelligence discriminant: ${JSON.stringify(e)}`)},"assertRunEventSequenceMonotonic",0,e=>{let t=-1;for(let n=0;n<e.length;n+=1){let a=e[n];if(void 0===a)throw RangeError(`Run event[${String(n)}] is missing`);if(!Number.isInteger(a.sequence)||a.sequence<0)throw RangeError(`Run event[${String(n)}] has invalid sequence ${String(a.sequence)}`);if(a.sequence<=t)throw RangeError(`Run event[${String(n)}] sequence ${String(a.sequence)} is not strictly greater than previous ${String(t)}`);t=a.sequence}},"hasCanonicalSha256Hash",0,e=>/^[0-9a-f]{64}$/u.test(e.canonicalHashSha256Hex),"looksLikeBrowserSafeSourceEnvelope",0,e=>{let{displayLabel:t,provenance:n,localRef:a}=e;return!(0===t.length||t.length>256||/^[A-Za-z0-9+/]{40,}={0,2}$/u.test(t)||!/^[0-9a-f]{64}$/u.test(n.integrityHashSha256Hex)||rB(t)||rB(a)||rB(n.origin)||"connector-document"===e.kind&&rB(e.adapterId))},"validateQualityIntelligenceIdString",0,rz],47425);var rJ=e.i(47425),rJ=rJ;let rG=rJ.QUALITY_INTELLIGENCE_PRIORITIES,rV=rJ.QUALITY_INTELLIGENCE_RISK_CLASSES,rX=e=>e.split("\n").map(e=>e.trim()).filter(e=>e.length>0),rQ=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]);function rZ(e,t){let n=rX(t.preconditions),a=rX(t.steps),l=rX(t.expectedResults),s=t.tags.split(",").map(e=>e.trim()).filter(e=>e.length>0);return{...t.title!==e.title?{title:t.title}:{},...!rQ(n,e.preconditions)?{preconditions:n}:{},...!rQ(a,e.steps)?{steps:a}:{},...!rQ(l,e.expectedResults)?{expectedResults:l}:{},...t.priority!==e.priority?{priority:t.priority}:{},...t.riskClass!==e.riskClass?{riskClass:t.riskClass}:{},...!rQ(s,e.tags)?{tags:s}:{}}}function r0({id:e,label:t,value:a,disabled:l=!1,onChange:s}){return(0,n.jsxs)("label",{className:"qi-edit-field",htmlFor:e,children:[(0,n.jsx)("span",{className:"qi-edit-label",children:t}),(0,n.jsx)("textarea",{id:e,className:"qi-edit-textarea",value:a,rows:3,disabled:l,onChange:e=>{s(e.target.value)}})]})}function r1({id:e,label:t,value:a,disabled:l=!1,required:s=!1,onChange:i}){return(0,n.jsxs)("label",{className:"qi-edit-field",htmlFor:e,children:[(0,n.jsx)("span",{className:"qi-edit-label","data-required":s?"true":void 0,children:t}),(0,n.jsx)("input",{id:e,className:"qi-edit-input",value:a,disabled:l,required:s,"aria-required":s?"true":void 0,onChange:e=>{i(e.target.value)}})]})}function r2({id:e,label:t,value:a,options:l,disabled:s=!1,onChange:i}){return(0,n.jsxs)("label",{className:"qi-edit-field",htmlFor:e,children:[(0,n.jsx)("span",{className:"qi-edit-label",children:t}),(0,n.jsx)("select",{id:e,className:"qi-edit-select",value:a,disabled:s,onChange:e=>{i(e.target.value)},children:l.map(e=>(0,n.jsx)("option",{value:e,children:e},e))})]})}function r4({onCancel:e,saving:t}){return(0,n.jsxs)("div",{className:"qi-edit-actions",children:[(0,n.jsx)("button",{type:"submit",className:"qi-btn qi-btn-approve qi-edit-save","aria-disabled":t||void 0,children:"Save"}),(0,n.jsx)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-edit-cancel","aria-disabled":t||void 0,onClick:()=>{t||e()},children:"Cancel"})]})}function r3({candidate:e,onSave:t,onCancel:l}){let[s,i]=(0,a.useState)(()=>({title:e.title,preconditions:e.preconditions.join("\n"),steps:e.steps.join("\n"),expectedResults:e.expectedResults.join("\n"),priority:e.priority,riskClass:e.riskClass,tags:e.tags.join(", ")})),[r,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(!1),[u,m]=(0,a.useState)(!1),h=(0,a.useRef)(null),p=(e,t)=>{o(null),m(!1),i(n=>({...n,[e]:t}))},f=(0,a.useCallback)(()=>{c||(!(Object.keys(rZ(e,s)).length>0)||u?l():m(!0))},[e,u,l,c,s]);(0,a.useEffect)(()=>{let e=e=>{if("Escape"!==e.key||c)return;let t=h.current;null!==t&&t.contains(document.activeElement)&&f()};return document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e)}},[f,c]),(0,a.useEffect)(()=>{h.current?.querySelector("input.qi-edit-input")?.focus()},[]);let g=`qi-edit-${e.id}`,v=async()=>{if(!c){d(!0),o(null);try{await t(rZ(e,s))}catch(e){o(rs(e))}finally{d(!1)}}};return(0,n.jsxs)("form",{ref:h,className:"qi-edit-form","aria-label":`Edit ${e.title}`,"aria-busy":c,onSubmit:e=>{e.preventDefault(),v()},children:[(0,n.jsx)(r1,{id:`${g}-title`,label:"Title",value:s.title,disabled:c,required:!0,onChange:e=>{p("title",e)}}),null!==r?(0,n.jsx)("p",{className:"qi-edit-error",role:"alert","aria-live":"assertive",children:r}):null,(0,n.jsx)("p",{className:"qi-edit-discard-note",role:"status","aria-live":"polite",children:u?"Unsaved changes — press Escape or activate Cancel again to discard them.":""}),(0,n.jsx)(r4,{onCancel:f,saving:c}),(0,n.jsx)(r0,{id:`${g}-preconditions`,label:"Preconditions (one per line)",value:s.preconditions,disabled:c,onChange:e=>{p("preconditions",e)}}),(0,n.jsx)(r0,{id:`${g}-steps`,label:"Steps (one per line)",value:s.steps,disabled:c,onChange:e=>{p("steps",e)}}),(0,n.jsx)(r0,{id:`${g}-expected`,label:"Expected results (one per line)",value:s.expectedResults,disabled:c,onChange:e=>{p("expectedResults",e)}}),(0,n.jsx)(r2,{id:`${g}-priority`,label:"Priority",value:s.priority,options:rG,disabled:c,onChange:e=>{p("priority",e)}}),(0,n.jsx)(r2,{id:`${g}-risk`,label:"Risk class",value:s.riskClass,options:rV,disabled:c,onChange:e=>{p("riskClass",e)}}),(0,n.jsx)(r1,{id:`${g}-tags`,label:"Tags (comma-separated)",value:s.tags,disabled:c,onChange:e=>{p("tags",e)}})]})}let r6=new Set(["approved","rejected","withdrawn"]);function r5({items:e,label:t}){return 0===e.length?null:(0,n.jsxs)("div",{className:"qi-cand-block",children:[(0,n.jsx)("p",{className:"qi-cand-block-label",children:t}),(0,n.jsx)("ol",{className:"qi-cand-list","aria-label":t,children:e.map((e,a)=>(0,n.jsx)("li",{children:e},`${t}-${String(a)}`))})]})}function r8({className:e,label:t,pressed:a,disabled:l,describedBy:s,onActivate:i}){return(0,n.jsx)("button",{type:"button",className:e,...void 0!==a?{"aria-pressed":a}:{},"aria-disabled":l||void 0,"aria-describedby":l?s:void 0,onClick:()=>{l||i()},children:t})}function r7({candidateId:e,state:t,onReview:l,disabled:s=!1,describedBy:i,pendingReview:r}){let o=null!=r,c=t=>o&&r.candidateId===e&&r.action===t,d=r6.has(t),u=(0,a.useId)(),m=d?u:i;return(0,n.jsxs)("div",{className:"qi-cand-actions",role:"group","aria-label":"Review decision",children:[d?(0,n.jsx)("p",{id:u,className:"qi-cand-governance-note",role:"note",children:"This review decision is final — reopen to change it."}):null,(0,n.jsx)(r8,{className:"qi-btn qi-btn-approve",label:c("approve")?"Saving…":"Approve",pressed:"approved"===t,disabled:s||o||d,describedBy:m,onActivate:()=>{l(e,"approve")}}),(0,n.jsx)(r8,{className:"qi-btn qi-btn-reject",label:c("reject")?"Saving…":"Reject",pressed:"rejected"===t,disabled:s||o||d,describedBy:m,onActivate:()=>{l(e,"reject")}}),(0,n.jsx)(r8,{className:"qi-btn qi-btn-secondary",label:c("request-changes")?"Saving…":"Request changes",pressed:"changes-requested"===t,disabled:s||o||d,describedBy:m,onActivate:()=>{l(e,"request-changes")}}),d?(0,n.jsx)(r8,{className:"qi-btn qi-btn-secondary",label:c("reopen")?"Saving…":"Reopen",disabled:s||o,describedBy:s?i:void 0,onActivate:()=>{l(e,"reopen")}}):null]})}function r9({candidate:e,onReview:t,onStartEdit:a,actionsDisabled:l=!1,describedBy:s,editButtonRef:i,pendingReview:r}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"qi-cand-header",children:[(0,n.jsx)("h3",{className:"qi-cand-title",children:e.title}),(0,n.jsxs)("div",{className:"qi-cand-badges",children:[(0,n.jsx)("span",{className:"qi-cand-pri",children:e.priority}),(0,n.jsx)("span",{className:"qi-cand-risk",children:e.riskClass}),(0,n.jsx)(rl,{state:e.reviewState})]})]}),void 0!==e.weakTestFlag?(0,n.jsx)(rp,{flag:e.weakTestFlag}):null,void 0!==e.qualityVerdict?(0,n.jsx)(rg,{verdict:e.qualityVerdict}):null,(0,n.jsx)(r5,{items:e.preconditions,label:"Preconditions"}),(0,n.jsx)(r5,{items:e.steps,label:"Steps"}),(0,n.jsx)(r5,{items:e.expectedResults,label:"Expected results"}),e.tags.length>0?(0,n.jsx)("ul",{className:"qi-cand-tags","aria-label":"Tags",children:e.tags.map(e=>(0,n.jsx)("li",{className:"qi-cand-tag",children:e},e))}):null,(0,n.jsxs)("div",{className:"qi-cand-actions-row",children:[void 0!==a?(0,n.jsx)("button",{ref:i,type:"button",className:"qi-btn qi-btn-secondary qi-cand-edit","aria-disabled":l||void 0,"aria-describedby":l?s:void 0,onClick:()=>{l||a()},children:"Edit"}):null,void 0!==t?(0,n.jsx)(r7,{candidateId:e.id,state:e.reviewState,onReview:t,disabled:l,describedBy:s,pendingReview:r}):null]})]})}function oe({candidate:e,onReview:t,onEdit:l,actionsDisabled:s=!1,describedBy:i,pendingReview:r}){let[o,c]=(0,a.useState)(!1),d=(0,a.useRef)(null),u=(0,a.useRef)(!1);(0,a.useEffect)(()=>{u.current&&!o&&d.current?.focus(),u.current=o},[o]);let m=async t=>{void 0!==l&&await l(e.id,t),c(!1)};return(0,n.jsx)("li",{className:o?"qi-cand-card qi-cand-card-editing":"qi-cand-card",children:o&&void 0!==l?(0,n.jsx)(r3,{candidate:e,onSave:m,onCancel:()=>{c(!1)}}):(0,n.jsx)(r9,{candidate:e,onReview:t,actionsDisabled:s,describedBy:i,pendingReview:r,editButtonRef:d,onStartEdit:void 0!==l?()=>{c(!0)}:void 0})})}function ot({candidates:e,onReview:t,onEdit:l,actionsDisabled:s=!1,actionsDisabledReason:i,pendingReview:r}){let[o,c]=(0,a.useState)(25),d=(0,a.useId)(),u=s&&void 0!==i;if(0===e.length)return(0,n.jsxs)("div",{className:"lk-empty",children:[(0,n.jsx)("p",{className:"lk-empty-title",children:"No test cases"}),(0,n.jsx)("p",{className:"lk-empty-body",children:"This run produced no generated test cases."})]});let m=[...e].sort((e,t)=>!!e.tags.includes("source:deterministic-baseline")-!!t.tags.includes("source:deterministic-baseline")).slice(0,o);return(0,n.jsxs)("div",{className:"qi-cand-pane",children:[u?(0,n.jsx)("p",{id:d,className:"qi-cand-governance-note",role:"note",children:i}):null,(0,n.jsx)("ul",{className:"qi-cand-cards","aria-label":"Test case list",children:m.map(e=>(0,n.jsx)(oe,{candidate:e,onReview:t,onEdit:l,actionsDisabled:s,describedBy:u?d:void 0,pendingReview:r},e.id))}),o<e.length?(0,n.jsxs)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-cand-more",onClick:()=>{c(e=>e+25)},children:["Show more test cases (",(e.length-o).toString()," remaining)"]}):null]})}function on(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 oa(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 ol({staleCount:e}){return 0===e?(0,n.jsxs)("p",{className:"qi-drift-fresh","data-testid":"qi-drift-fresh",children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"qi-drift-icon-ok",children:"✓"}),on(0)]}):(0,n.jsxs)("p",{className:"qi-drift-stale","data-testid":"qi-drift-stale",children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"qi-drift-icon-warn",children:"⚠"}),on(e)]})}function os({runId:e,connectedSources:t,onRegenerated:l,reCheckImpl:s=i8,regenerateImpl:i=i7}){let[r,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(null),u=null!==c,[m,h]=(0,a.useState)(null),[p,f]=(0,a.useState)(null),g=(0,a.useRef)(null),v=(0,a.useRef)(null),b=(0,a.useCallback)(()=>{u||(async()=>{d("check"),h(null),f(null);try{o(await s(e,t))}catch(e){h(rs(e))}finally{d(null)}})()},[u,s,e,t]),x=(0,a.useCallback)(()=>{u||(async()=>{d("regenerate"),h(null);try{let n=await i(e,t);document.activeElement===v.current&&g.current?.focus(),f(n),o(null),l?.(n)}catch(e){h(rs(e))}finally{d(null)}})()},[u,i,e,t,l]);return(0,n.jsxs)("section",{className:"qi-drift-panel","aria-label":"Drift detection",children:[(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:null!==p?oa(p):null!==r?on(r.staleCount):""}),(0,n.jsxs)("div",{className:"qi-drift-head",children:[(0,n.jsx)("h3",{className:"qi-col-subtitle",children:"Living tests"}),(0,n.jsx)("button",{type:"button",ref:g,className:"qi-btn qi-btn-secondary",onClick:b,"aria-disabled":u||void 0,"data-testid":"qi-drift-recheck",children:"check"===c?"Checking…":"Re-check drift"})]}),null!==m?(0,n.jsx)("p",{className:"lk-alert",role:"alert",children:m}):null,null!==r?(0,n.jsx)(ol,{staleCount:r.staleCount}):null,null!==r&&r.staleCount>0&&null===p?(0,n.jsx)("button",{type:"button",ref:v,className:"qi-btn qi-btn-approve",onClick:x,"aria-disabled":u||void 0,"data-testid":"qi-drift-regenerate",children:"regenerate"===c?"Regenerating…":`Regenerate ${r.staleCount.toString()} stale ${1===r.staleCount?"test":"tests"}`}):null,null!==p?(0,n.jsx)("p",{className:"qi-drift-regenerated","data-testid":"qi-drift-regenerated",children:oa(p)}):null]})}let oi={"traceability-csv":"csv","traceability-markdown":"markdown"},or=[{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 oo(e,t,n,a){let l=new Blob(["base64"===a?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}),s=URL.createObjectURL(l),i=document.createElement("a");i.href=s,i.download=e,document.body.appendChild(i),i.click(),i.remove(),window.setTimeout(()=>{URL.revokeObjectURL(s)},250)}function oc({runId:e,exportImpl:t=i9,traceabilityImpl:l=re}){let[s,i]=(0,a.useState)("csv"),[r,o]=(0,a.useState)(!1),[c,d]=(0,a.useState)(null),[u,m]=(0,a.useState)(null),[h,p]=(0,a.useState)(null),[f,g]=(0,a.useState)(!1),v=or.find(e=>e.id===s),b=v?.tms??!1,x=(0,a.useCallback)(async()=>{let n=oi[s];if(void 0!==n){let t=await l(e,n);oo(t.filename,t.contentType,t.body),p(t.filename);return}let a=await t(e,s,{dryRun:b,approvedOnly:f});a.dryRun?m(`${a.candidateCount.toString()} test case${1===a.candidateCount?"":"s"} \xb7 ${a.byteLen.toString()} bytes
108
+
109
+ ${a.preview}`):(oo(a.filename,a.contentType,a.body,a.encoding),p(a.filename))},[e,s,b,f,t,l]),y=(0,a.useCallback)(async()=>{o(!0),d(null),m(null),p(null);try{await x()}catch(e){d(rs(e))}finally{o(!1)}},[x]);return(0,n.jsxs)("div",{className:"qi-export","data-testid":"qi-export-bar",children:[(0,n.jsxs)("label",{className:"qi-field qi-field-inline",children:[(0,n.jsx)("span",{className:"qi-field-label",children:"Export"}),(0,n.jsx)("select",{className:"qi-select",value:s,disabled:r,"aria-describedby":b?"qi-export-connector-hint":void 0,onChange:e=>{i(e.target.value),m(null),d(null),p(null)},children:or.map(e=>(0,n.jsx)("option",{value:e.id,children:e.label},e.id))})]}),b?null:(0,n.jsxs)("label",{className:"qi-field qi-field-inline qi-export-approved-label",children:[(0,n.jsx)("input",{type:"checkbox",className:"qi-checkbox",checked:f,disabled:r,onChange:e=>{g(e.target.checked)},"data-testid":"qi-export-approved-only"}),(0,n.jsx)("span",{children:"Approved only"})]}),b?null:(0,n.jsx)("p",{className:"qi-export-hint",role:"note","data-testid":"qi-export-scope-notice",children:f?"Exports approved test cases only.":"Exports all test cases, including unapproved."}),(0,n.jsx)("button",{type:"button",className:"qi-btn qi-btn-secondary",disabled:r,onClick:()=>{y()},children:r?"Exporting…":b?"Preview":"Download"}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:null!==h?`Downloaded ${h}`:null!==u?"Export preview ready below.":""}),b?(0,n.jsx)("p",{id:"qi-export-connector-hint",className:"qi-export-hint",role:"note","data-testid":"qi-export-connector-hint",children:v?.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!==h?(0,n.jsx)("p",{className:"qi-export-success","data-testid":"qi-export-success",children:`Downloaded ${h}`}):null,null!==u?(0,n.jsx)("pre",{className:"qi-export-preview",role:"region","aria-label":"Export preview",tabIndex:0,"data-testid":"qi-export-preview",children:u}):null,null!==c?(0,n.jsx)("p",{className:"lk-alert",role:"alert","data-testid":"qi-export-error",children:c}):null]})}let od="keiko.qi.reviewerLabel",ou="Set a reviewer label to review or edit candidates.";function om({detail:e}){return(0,n.jsxs)("dl",{className:"qi-run-summary","aria-label":"Run summary",children:[(0,n.jsxs)("div",{className:"qi-run-summary-item",children:[(0,n.jsx)("dt",{children:"Status"}),(0,n.jsx)("dd",{children:(0,n.jsx)(rd,{status:e.status})})]}),(0,n.jsxs)("div",{className:"qi-run-summary-item",children:[(0,n.jsx)("dt",{children:"Test cases"}),(0,n.jsx)("dd",{children:e.totals.candidates.toString()})]}),(0,n.jsxs)("div",{className:"qi-run-summary-item",children:[(0,n.jsx)("dt",{children:"Findings"}),(0,n.jsx)("dd",{children:e.totals.findings.toString()})]}),(0,n.jsxs)("div",{className:"qi-run-summary-item",children:[(0,n.jsx)("dt",{children:"Quality"}),(0,n.jsx)("dd",{children:(0,n.jsx)(rh,{score:e.qualityScore})})]}),(0,n.jsxs)("div",{className:"qi-run-summary-item",children:[(0,n.jsx)("dt",{children:"Review"}),(0,n.jsx)("dd",{className:"qi-run-summary-review",children:rn[e.reviewState]})]}),(0,n.jsxs)("div",{className:"qi-run-summary-item",children:[(0,n.jsx)("dt",{children:"Requested"}),(0,n.jsx)("dd",{children:ri(e.requestedAt)})]}),null!==e.completedAt?(0,n.jsxs)("div",{className:"qi-run-summary-item",children:[(0,n.jsx)("dt",{children:"Completed"}),(0,n.jsx)("dd",{children:ri(e.completedAt)})]}):null]})}let oh={"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 op({detail:e}){let[t,l]=(0,a.useState)(20),s=e.findingRefs.length;if(0===s)return null;let i=e.findingRefs.slice(0,t);return(0,n.jsxs)("section",{className:"qi-run-findings","aria-label":"Findings",children:[(0,n.jsxs)("h3",{className:"qi-col-subtitle",children:["Findings",(0,n.jsx)("span",{className:"qi-col-count",children:s.toString()})]}),(0,n.jsx)("ul",{className:"qi-finding-list","aria-label":"Findings list",children:i.map(e=>(0,n.jsxs)("li",{className:"qi-finding-item",children:[(0,n.jsxs)("div",{className:"qi-finding-header",children:[(0,n.jsx)("span",{className:"qi-finding-kind",children:oh[e.kind]??e.kind}),(0,n.jsx)(rm,{severity:e.severity})]}),(0,n.jsx)("p",{className:"qi-finding-summary",children:e.summaryRedacted})]},e.id))}),t<s?(0,n.jsxs)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-show-more",onClick:()=>{l(e=>e+20)},children:["Show more findings (",(s-t).toString()," remaining)"]}):null]})}let of={covered:"Covered","weakly-covered":"Weakly covered",uncovered:"Uncovered"},og={covered:"qi-cov-covered","weakly-covered":"qi-cov-weak",uncovered:"qi-cov-uncovered"},ov={uncovered:0,"weakly-covered":1,covered:2};function ob({detail:e}){let[t,l]=(0,a.useState)(20),{total:s,coveredCount:i,gaps:r}=(0,a.useMemo)(()=>{let t=e.coverageByAtom;return{total:t.length,coveredCount:t.filter(e=>"covered"===e.status).length,gaps:t.filter(e=>"covered"!==e.status).sort((e,t)=>ov[e.status]-ov[t.status])}},[e.coverageByAtom]);if(0===s)return null;let o=r.slice(0,t);return(0,n.jsxs)("section",{className:"qi-coverage-panel","aria-label":"Coverage",children:[(0,n.jsxs)("h3",{className:"qi-col-subtitle",children:["Coverage",(0,n.jsxs)("span",{className:"qi-badge qi-badge-default","aria-label":`Coverage: ${e.coveragePercentage.toFixed(0)} percent, ${i.toString()} of ${s.toString()} requirements covered`,"data-testid":"qi-coverage-pct",children:[e.coveragePercentage.toFixed(0),"%"]})]}),(0,n.jsx)("p",{className:"qi-coverage-summary","data-testid":"qi-coverage-summary",children:`${i.toString()} of ${s.toString()} requirements covered \xb7 ${r.length.toString()} gap${1===r.length?"":"s"}`}),r.length>0?(0,n.jsxs)("section",{className:"qi-coverage-gaps","aria-label":"Gap radar",children:[(0,n.jsx)("h4",{className:"qi-col-subtitle",children:`Gap radar (${r.length.toString()})`}),(0,n.jsx)("ul",{className:"qi-coverage-gap-list","aria-label":"Uncovered and weakly covered atoms",children:o.map(e=>{let t=of[e.status],a=og[e.status],l=e.requirementExcerptRedacted;return(0,n.jsxs)("li",{className:"qi-coverage-gap-item","aria-label":void 0===l?`Atom ${e.atomId}: ${t}`:`Requirement "${l}" (atom ${e.atomId}): ${t}`,children:[(0,n.jsxs)("span",{className:"qi-coverage-gap-req",children:[void 0===l?null:(0,n.jsx)("span",{className:"qi-coverage-gap-text","data-testid":"qi-coverage-gap-text",children:l}),(0,n.jsx)("span",{className:"qi-coverage-atom-id qi-monospace",children:e.atomId})]}),(0,n.jsx)("span",{className:`qi-badge ${a}`,"aria-hidden":"true",children:t}),(0,n.jsx)("span",{className:"qi-sr-only",children:t})]},e.atomId)})}),t<r.length?(0,n.jsxs)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-show-more",onClick:()=>{l(e=>e+20)},children:["Show more gaps (",(r.length-t).toString()," remaining)"]}):null]}):null]})}function ox({detail:e}){let t=(0,a.useId)();return e.drift.reCheckSupported?(0,n.jsxs)("section",{className:"qi-drift-panel","aria-label":"Drift detection",children:[(0,n.jsxs)("div",{className:"qi-drift-head",children:[(0,n.jsx)("h3",{className:"qi-col-subtitle",children:"Living tests"}),(0,n.jsx)("button",{type:"button",className:"qi-btn qi-btn-secondary","aria-disabled":"true","aria-describedby":t,"data-testid":"qi-drift-recheck-unavailable",onClick:e=>{e.preventDefault()},children:"Re-check drift"})]}),(0,n.jsx)("p",{id:t,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 oy({runId:e,connectedSources:t,onRegenerated:l,fetchDetailImpl:s=i1,reviewImpl:i=i6,editImpl:r=i5,reCheckImpl:o,regenerateImpl:c}){let[d,u]=(0,a.useState)(null),[m,h]=(0,a.useState)(!0),[p,f]=(0,a.useState)(null),[g,v]=(0,a.useState)(null),[b,x]=(0,a.useState)(null),[y,w]=(0,a.useState)(""),[j,k]=(0,a.useState)(!1),N=(0,a.useId)(),S=(0,a.useId)(),[C,I]=(0,a.useState)(""),E=(0,a.useRef)(0),R=(0,a.useRef)(0),$=(0,a.useCallback)(async()=>{let t=R.current+1;R.current=t,h(!0),f(null);try{let n=await s(e);R.current===t&&u(n)}catch(e){R.current===t&&f(rs(e))}finally{R.current===t&&h(!1)}},[s,e]);(0,a.useEffect)(()=>{$()},[$]),(0,a.useEffect)(()=>{w(function(){try{return window.localStorage.getItem(od)??""}catch{return""}}()),k(!0)},[]),(0,a.useEffect)(()=>{if(j)try{window.localStorage.setItem(od,y)}catch{}},[y,j]);let T=y.trim(),A=T.length>0,M=(0,a.useCallback)((t,n)=>{A&&null===b&&(x({candidateId:t,action:n}),(async()=>{v(null);try{await i(e,n,t,T),await $();let a=rn["approve"===n?"approved":"reject"===n?"rejected":"request-changes"===n?"changes-requested":"open"],l=d?.candidates.find(e=>e.id===t)?.title??t;E.current+=1,I(`Candidate "${l}" marked ${a}. (${E.current.toString()})`)}catch(e){v(rs(e))}finally{x(null)}})())},[A,b,i,e,T,$,d]),L=(0,a.useCallback)(async(t,n)=>{if(!A)throw Error(ou);await r(e,t,n,T),await $()},[r,A,e,T,$]);return(0,n.jsxs)("div",{className:"qi-run-card","data-testid":"qi-run-card",children:[(0,n.jsx)("header",{className:"qi-run-card-head",children:(0,n.jsx)("span",{className:"qi-run-id qi-monospace",title:e,role:"heading","aria-level":2,"aria-label":`Quality Intelligence run ${e}`,children:e})}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:m?"Loading run…":null===p&&null!==d?`Run loaded: ${d.totals.candidates.toString()} test case${1===d.totals.candidates?"":"s"}.`:""}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","data-testid":"qi-review-announce",children:C}),(0,n.jsx)("div",{className:"qi-run-card-body","aria-busy":m,children:m&&null===d?(0,n.jsx)(rb,{}):null!==p?(0,n.jsx)(rx,{message:p,onRetry:()=>void $()}):null===d?(0,n.jsx)("div",{className:"lk-empty",children:(0,n.jsx)("p",{className:"lk-empty-body",children:"Run not found."})}):(0,n.jsxs)(n.Fragment,{children:[null!==g?(0,n.jsxs)("div",{className:"lk-alert qi-action-error",role:"alert","data-testid":"qi-action-error",children:[g,(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>{v(null)},children:"Dismiss"})]}):null,(0,n.jsxs)("section",{className:"qi-run-governance","aria-label":"Review governance",children:[(0,n.jsxs)("label",{className:"qi-field",htmlFor:`qi-reviewer-label-${e}`,children:[(0,n.jsx)("span",{className:"qi-field-label",children:"Reviewer label"}),(0,n.jsx)("input",{id:`qi-reviewer-label-${e}`,className:"qi-input qi-run-governance-input",value:y,placeholder:"Required for review and edit actions","aria-invalid":!A,"aria-describedby":A?N:`${N} ${S}`,onChange:e=>{w(e.target.value)}})]}),(0,n.jsx)("p",{id:N,className:"qi-run-governance-help",children:"Used for QI review and edit audit entries."}),(0,n.jsx)("p",{id:S,className:"qi-run-governance-warning",role:"status","aria-live":"polite",children:A?"":ou})]}),(0,n.jsx)(om,{detail:d}),(0,n.jsx)(op,{detail:d}),(0,n.jsx)(ob,{detail:d}),void 0!==t&&t.length>0?(0,n.jsx)(os,{runId:e,connectedSources:t,onRegenerated:l,reCheckImpl:o,regenerateImpl:c}):(0,n.jsx)(ox,{detail:d}),(0,n.jsxs)("section",{className:"qi-run-cases","aria-label":"Generated test cases",children:[(0,n.jsxs)("div",{className:"qi-run-cases-head",children:[(0,n.jsxs)("h3",{className:"qi-col-subtitle",children:["Test cases",(0,n.jsx)("span",{className:"qi-col-count",children:d.candidates.length.toString()})]}),d.candidates.length>0?(0,n.jsx)(oc,{runId:e}):null]}),(0,n.jsx)(ot,{candidates:d.candidates,onReview:M,pendingReview:b,onEdit:L,actionsDisabled:!A,actionsDisabledReason:ou})]})]})})]})}let ow={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 oj({shape:e,color:t,animated:a,highContrast:l}){let s=["rb-edge-badge-icon",a?"rb-edge-badge-icon--processing":"",l?"rb-edge-badge-icon--high-contrast":""].filter(e=>e.length>0).join(" "),i=l?2:1.5,r={width:12,height:12,viewBox:"0 0 12 12","aria-hidden":!0,fill:"currentColor",className:s,style:{color:t}};switch(e){case"hollow-circle":return(0,n.jsx)("svg",{...r,children:(0,n.jsx)("circle",{cx:"6",cy:"6",r:"4.5",fill:"none",stroke:"currentColor",strokeWidth:i})});case"clock":return(0,n.jsxs)("svg",{...r,children:[(0,n.jsx)("circle",{cx:"6",cy:"6",r:"4.5",fill:"none",stroke:"currentColor",strokeWidth:i}),(0,n.jsx)("path",{d:"M6 3v3l2 1",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",fill:"none"})]});case"filled-circle":return(0,n.jsx)("svg",{...r,children:(0,n.jsx)("circle",{cx:"6",cy:"6",r:"5"})});case"spinning-circle":return(0,n.jsx)("svg",{...r,children:(0,n.jsx)("circle",{cx:"6",cy:"6",r:"4.5",fill:"none",stroke:"currentColor",strokeWidth:i,strokeDasharray:"8 4"})});case"check":return(0,n.jsx)("svg",{...r,children:(0,n.jsx)("path",{d:"M2 6l3 3 5-5",stroke:"currentColor",strokeWidth:l?2.2:1.8,strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})});case"triangle-exclamation":return(0,n.jsxs)("svg",{...r,children:[(0,n.jsx)("path",{d:"M6 1 L11 10 L1 10 Z",fill:"currentColor"}),(0,n.jsx)("path",{d:"M6 5v2.5",stroke:"var(--card)",strokeWidth:i,strokeLinecap:"round",fill:"none"}),(0,n.jsx)("circle",{cx:"6",cy:"9",r:"0.7",fill:"var(--card)"})]});case"filled-square":return(0,n.jsx)("svg",{...r,children:(0,n.jsx)("rect",{x:"1.5",y:"1.5",width:"9",height:"9",rx:"1.5"})});case"broken-line":return(0,n.jsx)("svg",{...r,children:(0,n.jsx)("path",{d:"M1 6h2.5l1.5-2 2 4 1.5-2H11",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})});case"stacked-lines":return(0,n.jsxs)("svg",{...r,children:[(0,n.jsx)("rect",{x:"2",y:"2.5",width:"8",height:"1.5",rx:"0.75"}),(0,n.jsx)("rect",{x:"2",y:"5.25",width:"8",height:"1.5",rx:"0.75"}),(0,n.jsx)("rect",{x:"2",y:"8",width:"8",height:"1.5",rx:"0.75"})]})}}function ok({state:e}){let t={width:10,height:10,viewBox:"0 0 10 10","aria-hidden":!0,fill:"currentColor"};switch(e){case"draft":return(0,n.jsx)("svg",{...t,children:(0,n.jsx)("circle",{cx:"5",cy:"5",r:"4",fill:"none",stroke:"currentColor",strokeWidth:"1.5"})});case"active":return(0,n.jsx)("svg",{...t,children:(0,n.jsx)("circle",{cx:"5",cy:"5",r:"4.5"})});case"archived":return(0,n.jsx)("svg",{...t,children:(0,n.jsx)("rect",{x:"1",y:"1",width:"8",height:"8",rx:"1"})});case"superseded":return(0,n.jsx)("svg",{...t,children:(0,n.jsx)("path",{d:"M2 5h6M6 3l2 2-2 2",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})});case"revoked":return(0,n.jsx)("svg",{...t,children:(0,n.jsx)("path",{d:"M2 2l6 6M8 2L2 8",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",fill:"none"})});case"blocked":return(0,n.jsxs)("svg",{...t,children:[(0,n.jsx)("rect",{x:"1",y:"1",width:"8",height:"8",rx:"1"}),(0,n.jsx)("path",{d:"M5 3v3",stroke:"var(--card)",strokeWidth:"1.5",strokeLinecap:"round",fill:"none"}),(0,n.jsx)("circle",{cx:"5",cy:"7.5",r:"0.6",fill:"var(--card)"})]});case"stale":return(0,n.jsx)("svg",{...t,children:(0,n.jsx)("rect",{x:"1",y:"1",width:"8",height:"8",rx:"1",fill:"none",stroke:"currentColor",strokeWidth:"1.5"})})}}function oN({type:e,lifecycle:t,activity:l,throughputCount:s,animateOverride:i=!0,highContrast:r,onClick:o,className:c=""}){let[d,u]=(0,a.useState)(!1);(0,a.useEffect)(()=>{if(void 0!==r)return;let e=window.matchMedia("(prefers-contrast: more)"),t=e=>{u(e)};t(e.matches);let n=e=>{t(e.matches)};return e.addEventListener("change",n),()=>{e.removeEventListener("change",n)}},[r]);let m=ow[l]??ow.inactive,h=n2[e],p=r??d,f="high-throughput"===l&&void 0!==s?`${m.label} (${String(s)})`:m.label,g=`${h.displayName} — ${m.ariaDescription}`,v=m.animated&&i,b=p?{color:m.textColor,background:"var(--card)",border:`1px solid ${m.textColor}`}:{color:m.textColor,background:m.bgColor,border:void 0!==m.borderColor?`1px solid ${m.borderColor}`:void 0};return(0,n.jsx)("span",{role:"status","aria-live":"polite","aria-atomic":"true",className:`rb-edge-badge ${c}`.trim(),"data-activity-state":l,"data-high-contrast":p?"true":void 0,children:void 0!==o?(0,n.jsxs)("button",{type:"button",className:"rb-edge-badge-btn",style:b,"aria-label":g,onClick:o,children:[(0,n.jsx)("span",{"aria-hidden":"true",children:(0,n.jsx)(oj,{shape:m.iconShape,color:m.textColor,animated:v,highContrast:p})}),(0,n.jsx)("span",{className:"visually-hidden",children:m.ariaDescription}),(0,n.jsx)("span",{"aria-hidden":"true",className:"rb-edge-badge-label",children:f}),(0,n.jsx)("span",{className:"rb-edge-badge-type",children:h.displayName}),(0,n.jsx)(ok,{state:t})]}):(0,n.jsxs)("span",{className:"rb-edge-badge-static",style:b,"aria-label":g,children:[(0,n.jsx)("span",{"aria-hidden":"true",children:(0,n.jsx)(oj,{shape:m.iconShape,color:m.textColor,animated:v,highContrast:p})}),(0,n.jsx)("span",{className:"visually-hidden",children:m.ariaDescription}),(0,n.jsx)("span",{"aria-hidden":"true",className:"rb-edge-badge-label",children:f}),(0,n.jsx)("span",{className:"rb-edge-badge-type",children:h.displayName}),(0,n.jsx)(ok,{state:t})]})})}let oS="keiko.relationships.density",oC={minimal:5,standard:25,dense:512};function oI(){try{let e=window.localStorage.getItem(oS);if("minimal"===e||"standard"===e||"dense"===e)return e}catch{}return"minimal"}function oE(e,t){return void 0===e||0===e.length?[]:e.split(",").map(e=>e.trim()).filter(e=>t.includes(e))}function oR(e){return{types:oE(e.relType,n0),lifecycles:oE(e.relLifecycle,n1),activities:oE(e.relActivity,["inactive","queued","active","processing","completed","failed","blocked","degraded","high-throughput"]),srcKinds:oE(e.relSrcKind,nQ),tgtKinds:oE(e.relTgtKind,nQ)}}let o$={"high-throughput":0,processing:1,active:2,blocked:3,failed:4,degraded:5,queued:6,completed:7,inactive:8};function oT(e,t,n){return n.get(e)??function(e){switch(e){case"blocked":return"blocked";case"stale":return"degraded";default:return"inactive"}}(t)}function oA({filters:e,selectedId:t,onSelect:l,onFilterChange:s,activityMap:i=new Map,throughputMap:r=new Map,animateBadges:o=!0,highContrast:c=!1}){let[d,u]=(0,a.useState)(()=>{let t=e.relDensity;return"minimal"===t||"standard"===t||"dense"===t?t:oI()}),[m,h]=(0,a.useState)(!1),[p,f]=(0,a.useState)([]),[g,v]=(0,a.useState)(!1),[b,x]=(0,a.useState)(null),[y,w]=(0,a.useState)(!1),j=(0,a.useRef)(null),k=(0,a.useRef)(null),[N,S]=(0,a.useState)(e.relType??""),C=(0,a.useRef)(null),I=(0,a.useCallback)(e=>{u(e),s({relDensity:e});try{window.localStorage.setItem(oS,e)}catch{}},[s]);(0,a.useEffect)(()=>{let t=e.relDensity;"minimal"===t||"standard"===t||"dense"===t?u(t):u(oI())},[e.relDensity]),(0,a.useEffect)(()=>{S(e.relType??"")},[e.relType]);let E=(0,a.useCallback)(async()=>{x(null),v(!0);try{let t=oR(e),n=1===t.lifecycles.length?t.lifecycles[0]:"active",a=1===t.types.length?t.types[0]:void 0,l=1===t.srcKinds.length?t.srcKinds[0]:void 0,s=1===t.tgtKinds.length?t.tgtKinds[0]:void 0,i=await ae({lifecycle:n,type:a,sourceKind:l,targetKind:s,limit:oC[d]});f(i.entries),w(i.truncated)}catch(e){x(e instanceof n6?e.message:n3)}finally{v(!1)}},[e,d]);(0,a.useEffect)(()=>{E()},[E]),(0,a.useEffect)(()=>{let e=j.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;t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement||t instanceof HTMLElement&&t.isContentEditable||("f"===e.key||"F"===e.key?(e.preventDefault(),h(e=>!e)):"Escape"===e.key?h(!1):"/"===e.key&&(e.preventDefault(),k.current?.focus()))}},[]);let R=(0,a.useCallback)(e=>{let t=e.target.value;S(t),null!==C.current&&clearTimeout(C.current),C.current=setTimeout(()=>{s({relType:t.length>0?t:void 0})},250)},[s]),$=(0,a.useMemo)(()=>{let t=oR(e),n=(e.relType??"").split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0),a=0===n.length?p:p.filter(e=>n.some(t=>e.type.toLowerCase().includes(t)));return(0===t.activities.length?a:a.filter(e=>t.activities.includes(oT(e.id,e.lifecycle,i)))).slice(0,oC[d])},[i,d,e,p]),T=$.slice(0,25),A=$.slice(25),M=A.length,L=M>0?function(e,t){let n=new Map;for(let a of e){let e=oT(a.id,a.lifecycle,t);n.set(e,(n.get(e)??0)+1)}return Array.from(n.entries()).sort((e,t)=>t[1]!==e[1]?t[1]-e[1]:(o$[e[0]]??Number.MAX_SAFE_INTEGER)-(o$[t[0]]??Number.MAX_SAFE_INTEGER)).map(([e,t])=>{let n;return n=1===t?"relationship":"relationships","high-throughput"===e?`${t} high-throughput ${n}`:`${t} ${e} ${n}`}).join(", ")}(A,i):"",q=y?`Showing first ${String($.length)} relationships — more available.`:`Showing ${String($.length)} relationship${1!==$.length?"s":""}.`,P=(e.relType??"").trim().length>0||(e.relActivity??"").trim().length>0||(e.relSrcKind??"").trim().length>0||(e.relTgtKind??"").trim().length>0||(e.relLifecycle??"").trim().length>0&&"active"!==e.relLifecycle,D=oE(e.relLifecycle,n1),F=1===D.length?D[0]??"active":"active";return(0,n.jsxs)("div",{ref:j,className:"tw-pad","data-testid":"relationship-list-panel","data-relationship-focus":m?"true":void 0,children:[(0,n.jsxs)("div",{role:"group","aria-label":"Relationship density",style:{display:"flex",flexWrap:"wrap",gap:4,marginBottom:8},children:[["minimal","standard","dense"].map(e=>(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-pressed":d===e,onClick:()=>I(e),style:{textTransform:"capitalize",minWidth:24,minHeight:24},children:e},e)),(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-pressed":m,onClick:()=>h(e=>!e),title:"Toggle focus mode (F)","aria-label":`Focus mode: ${m?"on":"off"}`,style:{minWidth:24,minHeight:24},children:"Focus"})]}),(0,n.jsxs)("div",{style:{marginBottom:8},children:[(0,n.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,n.jsx)("input",{id:"rel-type-filter",ref:k,type:"text",list:"rel-type-filter-options",value:N,onChange:R,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,n.jsx)("datalist",{id:"rel-type-filter-options",children:n0.map(e=>(0,n.jsx)("option",{value:e},e))})]}),(0,n.jsxs)("div",{style:{marginBottom:8},children:[(0,n.jsx)("label",{htmlFor:"rel-lifecycle-filter",className:"rb-row-k",style:{display:"block",marginBottom:2,fontSize:11,fontWeight:600},children:"Lifecycle"}),(0,n.jsx)("select",{id:"rel-lifecycle-filter",value:F,onChange:e=>s({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:n1.map(e=>(0,n.jsx)("option",{value:e,children:e},e))})]}),(0,n.jsx)("div",{"aria-live":"polite","aria-atomic":"true",className:"visually-hidden",children:q}),y&&(0,n.jsx)("div",{"data-testid":"list-truncation-note",style:{fontSize:11,color:"var(--fg-muted)",marginBottom:6},children:q}),null!==b&&(0,n.jsxs)("div",{className:"lk-alert",role:"alert","aria-live":"assertive",children:[(0,n.jsx)("span",{children:b}),(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>void E(),children:"Retry"})]}),g&&0===p.length&&(0,n.jsx)("div",{role:"status",className:"insp-empty",children:"Loading…"}),(!g||p.length>0)&&null===b&&0===$.length&&(0,n.jsx)("div",{className:"insp-empty","data-testid":"list-empty",children:P?"No relationships match the current filter.":'No active relationships yet. Create one with "+ New relationship", or connect a source — connections appear here automatically.'}),$.length>0&&(0,n.jsxs)("div",{role:"list","aria-label":"Relationships","aria-busy":g||void 0,style:{display:"flex",flexDirection:"column",gap:2,opacity:g?.6:1,transition:"opacity 0.15s ease"},children:[T.map(e=>{let a=e.id===t,s=oT(e.id,e.lifecycle,i),d=m&&a,u=m&&!a;return(0,n.jsx)("div",{role:"listitem",style:{opacity:u?.4:1},children:(0,n.jsxs)("button",{type:"button","aria-pressed":a,"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:()=>l(e.id),onKeyDown:t=>{var n;return n=e.id,void(("Enter"===t.key||" "===t.key)&&(t.preventDefault(),l(n)))},"data-incident":d?"true":void 0,className:"rel-row",children:[(0,n.jsx)(oN,{type:e.type,lifecycle:e.lifecycle,activity:s,throughputCount:r.get(e.id),animateOverride:o,highContrast:c}),(0,n.jsxs)("span",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column"},children:[(0,n.jsxs)("span",{style:{fontSize:12,color:"var(--fg)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.source.kind," → ",e.target.kind]}),(0,n.jsx)("span",{style:{fontSize:10.5,color:"var(--fg-muted)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.summary??`${e.source.id} → ${e.target.id}`})]}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--fg-muted)",whiteSpace:"nowrap"},children:e.lifecycle})]})},e.id)}),M>0&&(0,n.jsxs)("div",{role:"listitem","aria-live":"polite",style:{fontSize:12,color:"var(--fg-muted)",padding:"4px 6px"},"data-testid":"animation-cap-aggregate",children:["+",String(M)," more: ",L]})]})]})}function oM(){return(0,n.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 oL({title:e,help:t,report:a,onSelectRelationship:l}){if(null===a)return(0,n.jsxs)("section",{style:{marginBottom:12},children:[(0,n.jsx)("div",{className:"rb-section-label",role:"heading","aria-level":4,children:e}),(0,n.jsx)("p",{style:{fontSize:12,color:"var(--fg-muted)",margin:0},children:"Loading…"})]});let s=a.endpoints.slice(1),i=a.relationships,r=s.slice(0,50),o=i.slice(0,50);return(0,n.jsxs)("section",{style:{marginBottom:12},"aria-label":e,children:[(0,n.jsxs)("div",{className:"rb-section-label",role:"heading","aria-level":4,children:[e,(0,n.jsx)("span",{className:"rb-count","aria-hidden":"true",children:s.length})]}),(0,n.jsx)("p",{style:{margin:"0 0 6px",fontSize:11,color:"var(--fg-muted)"},children:t}),0===s.length?(0,n.jsx)("p",{style:{fontSize:12,color:"var(--fg-muted)",margin:0},children:"No further objects are affected in this direction."}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("ul",{style:{listStyle:"none",margin:0,padding:0},children:r.map(e=>(0,n.jsx)("li",{className:"rb-row",style:{fontSize:12},children:(0,n.jsx)("span",{className:"mono",children:`${e.kind}: ${e.id}`})},`${e.kind}:${e.id}`))}),s.length>r.length&&(0,n.jsxs)("p",{role:"note",style:{margin:"4px 0 0",fontSize:11,color:"var(--fg-muted)"},children:["Showing the first ",String(50)," of ",String(s.length)," ","objects."]}),i.length>0&&(0,n.jsxs)("details",{style:{marginTop:6},children:[(0,n.jsxs)("summary",{style:{fontSize:11,color:"var(--fg-muted)",cursor:"pointer"},children:[String(i.length)," relationship",1===i.length?"":"s"," on the path"]}),(0,n.jsx)("ul",{style:{listStyle:"none",margin:"4px 0 0",padding:0},children:o.map(e=>(0,n.jsx)("li",{style:{marginBottom:2},children:(0,n.jsxs)("button",{type:"button",className:"arun-btn ghost",onClick:()=>l(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:6,alignItems:"center",textAlign:"left",fontSize:12},children:[(0,n.jsx)("span",{className:"mono",children:e.type}),(0,n.jsxs)("span",{style:{color:"var(--fg-muted)"},children:[e.source.id," → ",e.target.id]})]})},e.id))})]})]}),a.truncated&&(0,n.jsx)(oM,{})]})}function oq({outgoing:e,incoming:t,onSelectRelationship:a}){return(0,n.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,n.jsx)(oL,{title:"Downstream impact",help:"Objects this relationship's target leads to. Deleting or revoking here may affect them.",report:e,onSelectRelationship:a}),(0,n.jsx)(oL,{title:"Upstream impact",help:"Objects that depend on this relationship's source.",report:t,onSelectRelationship:a})]})}let oP={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)"}},oD={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 oF({lines:e=3}){return(0,n.jsx)("div",{className:"rb-rows","aria-hidden":"true",children:Array.from({length:e},(e,t)=>(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",style:{background:"var(--inset)",borderRadius:3,width:"40%",display:"block",height:12}}),(0,n.jsx)("span",{className:"rb-row-v",style:{background:"var(--inset)",borderRadius:3,width:"55%",display:"block",height:12}})]},t))})}function oz({children:e,style:t}){return(0,n.jsx)("div",{className:"rb-section-label",role:"heading","aria-level":3,style:t,children:e})}function oO({rel:e}){let t=n2[e.type],a=`${e.source.kind} ${e.type} ${e.target.kind}`;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"insp-top",children:[(0,n.jsx)("span",{className:"chip",style:{fontSize:11},children:e.type}),(0,n.jsx)("span",{className:"insp-title",children:a})]}),(0,n.jsxs)("div",{className:"rb-rows",children:[(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Semantics"}),(0,n.jsx)("span",{className:"rb-row-v",children:t.semantics})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Cardinality"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:t.cardinality})]})]})]})}function oK({label:e,kind:t,id:a}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)(oz,{children:[e," endpoint"]}),(0,n.jsxs)("div",{className:"rb-rows",children:[(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Kind"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:t})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Reference"}),(0,n.jsx)("span",{className:"rb-row-v mono","aria-label":`Reference id: ${a}`,children:a})]})]})]})}function oB({lifecycle:e}){let t=`lifecycle-desc-${e}`,a=oP[e]??oP.draft;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oz,{children:"Lifecycle status"}),(0,n.jsxs)("div",{className:"rb-rows",children:[(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"State"}),(0,n.jsx)("span",{className:"rb-row-v",children:(0,n.jsx)("span",{className:"chip",style:{background:a.bg,color:a.fg},"aria-describedby":t,children:e})})]}),(0,n.jsx)("div",{className:"rb-row",children:(0,n.jsx)("span",{id:t,className:"rb-row-v",style:{color:"var(--fg-muted)",fontSize:12},children:oD[e]})})]})]})}function o_({type:e,lifecycle:t,activity:a,throughputCount:l,animateBadges:s,highContrast:i,transitions:r,densityMode:o}){let c=r.slice(0,"minimal"===o?3:5);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oz,{children:"Activity"}),(0,n.jsxs)("div",{className:"rb-rows",children:[(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Current state"}),(0,n.jsx)("span",{className:"rb-row-v",children:(0,n.jsx)(oN,{type:e,lifecycle:t,activity:a,throughputCount:l,animateOverride:s,highContrast:i})})]}),c.length>0&&(0,n.jsxs)("div",{className:"rb-row",style:{flexDirection:"column",gap:4,alignItems:"flex-start"},children:[(0,n.jsx)("span",{className:"rb-row-k",style:{marginBottom:4},children:"Recent transitions"}),c.map((e,t)=>(0,n.jsxs)("div",{style:{fontSize:12,color:"var(--fg-muted)",display:"flex",gap:8},children:[(0,n.jsxs)("span",{className:"mono",children:[e.from," → ",e.to]}),(0,n.jsx)("time",{dateTime:new Date(e.occurredAt).toISOString(),style:{color:"var(--fg-faint)"},children:new Date(e.occurredAt).toLocaleString()})]},t))]})]})]})}function oU(){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oz,{children:"Authority status"}),(0,n.jsx)("div",{className:"rb-rows",children:(0,n.jsx)("div",{className:"rb-row","data-testid":"authority-disclaimer",children:(0,n.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 oW({auditRows:e,loading:t,error:a,onRetry:l,onLoadMore:s,hasMore:i}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oz,{children:"Audit history"}),t&&(0,n.jsx)(oF,{lines:3}),null!==a&&(0,n.jsxs)("div",{className:"lk-alert",role:"alert","aria-live":"assertive",children:[(0,n.jsx)("span",{children:a}),(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:l,children:"Retry"})]}),!t&&null===a&&0===e.length&&(0,n.jsx)("div",{className:"rb-rows",children:(0,n.jsx)("div",{className:"rb-row",children:(0,n.jsx)("span",{className:"rb-row-v",style:{color:"var(--fg-muted)"},children:"No audit events for this relationship yet."})})}),!t&&e.length>0&&(0,n.jsxs)("div",{className:"rb-rows",children:[e.map((e,t)=>(0,n.jsxs)("div",{className:"rb-row",style:{flexDirection:"column",alignItems:"flex-start",gap:2},children:[(0,n.jsxs)("span",{className:"rb-row-k mono",style:{fontSize:11},children:[e.from," → ",e.to]}),(0,n.jsx)("time",{dateTime:new Date(e.occurredAt).toISOString(),style:{color:"var(--fg-faint)",fontSize:11},children:new Date(e.occurredAt).toLocaleString()})]},t)),i&&(0,n.jsx)("div",{className:"rb-row",children:(0,n.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:s,"aria-label":"Load more audit events",children:"Load more"})})]})]})}function oH({rel:e}){let t,a=(t=[],"evidence-run"===e.source.kind&&t.push(e.source.id),"evidence-run"===e.target.kind&&t.push(e.target.id),t);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oz,{children:"Evidence references"}),0===a.length?(0,n.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,n.jsx)("div",{className:"rb-rows",children:a.map(e=>(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Evidence run"}),(0,n.jsx)("span",{className:"rb-row-v mono","aria-label":`Evidence run reference ${e}`,title:e,children:e})]},e))})]})}function oY({relationshipId:e,forwardCount:t,reverseCount:a,outgoing:l,incoming:s,expanded:i,onToggle:r,onSelectRelationship:o}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oz,{children:"Impact summary"}),(0,n.jsxs)("div",{className:"rb-rows",children:[(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Forward dependencies"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:null===t?"—":String(t)})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Reverse dependencies"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:null===a?"—":String(a)})]}),(0,n.jsx)("div",{className:"rb-row",children:(0,n.jsx)("button",{type:"button",className:"arun-btn",onClick:r,"aria-expanded":i,"aria-controls":"rb-impact-detail","aria-label":i?`Hide impact for relationship ${e}`:`View impact for relationship ${e}`,"data-testid":"view-impact-btn",children:i?"Hide impact":"View impact"})})]}),i&&(0,n.jsx)("div",{id:"rb-impact-detail",children:(0,n.jsx)(oq,{outgoing:l,incoming:s,onSelectRelationship:o})})]})}function oJ({codes:e,messages:t,deniedAt:a}){return 0===e.length?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oz,{children:"Denial reason"}),(0,n.jsxs)("div",{className:"lk-alert",role:"status","aria-live":"polite","data-testid":"denial-section",children:[e.map((a,l)=>(0,n.jsxs)("div",{style:{marginBottom:8*(l<e.length-1)},children:[(0,n.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--fg-muted)",marginBottom:2},children:a}),(0,n.jsx)("div",{style:{fontSize:13,color:"var(--fg)"},children:t[l]??a})]},a)),void 0!==a&&(0,n.jsxs)("div",{style:{fontSize:11,color:"var(--fg-faint)",marginTop:6},children:["Denied at ",(0,n.jsx)("time",{dateTime:a,children:a})]})]})]})}function oG(e){return null==e||0===e.length?null:{codes:e.map(e=>e.code),messages:e.map(e=>e.message)}}function oV({rel:e,onReconnect:t,onArchive:a,onRevoke:l,onViewImpact:s,onViewEvidence:i,mutating:r}){let o=e.lifecycle,c="blocked"===o,d="active"===o,u="active"===o||"blocked"===o||"archived"===o,m="active"===o;return(0,n.jsxs)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginTop:8},children:[(0,n.jsx)("button",{type:"button",className:`arun-btn${c?" primary":""}`,"aria-disabled":!c||r,"aria-label":"Reconnect — only available for blocked relationships",title:c?"Reconnect this relationship":"Only blocked relationships can be reconnected.",disabled:!c||r,onClick:c?t:void 0,children:"Reconnect"}),(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":!d||r,"aria-label":"Archive — only available for active relationships",title:d?"Archive this relationship":"Only active relationships can be archived.",disabled:!d||r,onClick:d?a:void 0,children:"Archive"}),(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":!u||r,"aria-label":"Revoke relationship",title:u?"Revoke this relationship":"Already revoked or superseded.",disabled:!u||r,onClick:u?l:void 0,style:{color:u?"var(--danger)":void 0},children:"Revoke"}),(0,n.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?s:void 0,children:"View impact"}),(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-label":"View evidence references",title:"Jump to the evidence references section",onClick:i,children:"View evidence"})]})}function oX({relationshipId:e,densityMode:t="minimal",onClearFocus:l,onViewImpact:s,activityMap:i=new Map,throughputMap:r=new Map,animateBadges:o=!0,highContrast:c=!1}){let[d,u]=(0,a.useState)(null),[m,h]=(0,a.useState)(null),[p,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(null),[b,x]=(0,a.useState)(!1),[y,w]=(0,a.useState)(null),[j,k]=(0,a.useState)(null),[N,S]=(0,a.useState)(null),[C,I]=(0,a.useState)(null),[E,R]=(0,a.useState)(!1),$=null===N?null:N.relationships.length,T=null===C?null:C.relationships.length,[A,M]=(0,a.useState)(!1),L=(0,a.useRef)(null),q=(0,a.useRef)(0),P=(0,a.useCallback)(async e=>{let t=++q.current;v(null),f(!0),k(null),S(null),I(null),R(!1);let n=setTimeout(()=>{q.current===t&&M(!0)},500);L.current=n;try{let[n,a]=await Promise.all([at(e),as(e)]);if(q.current!==t)return;u(n),h(a);try{let[n,a]=await Promise.all([al(e,{direction:"outgoing",maxDepth:3,maxRelationships:512}),al(e,{direction:"incoming",maxDepth:3,maxRelationships:512})]);if(q.current!==t)return;S(n),I(a)}catch{}}catch(e){if(q.current!==t)return;v(e instanceof n6?e.message:n3)}finally{L.current===n?(clearTimeout(n),L.current=null):clearTimeout(n),q.current===t&&(f(!1),M(!1))}},[]);(0,a.useEffect)(()=>{if(null===e){q.current+=1,null!==L.current&&(clearTimeout(L.current),L.current=null),u(null),h(null),v(null),k(null),M(!1),f(!1);return}return P(e),()=>{null!==L.current&&(clearTimeout(L.current),L.current=null)}},[e,P]);let D=(0,a.useCallback)(async e=>{if(null!==d){x(!0),w(null),k(null);try{let t=crypto.randomUUID(),{relationship:n}=await an(d.id,{transition:{to:e}},String(d.etag),t);u(n),h(null),await P(d.id)}catch(e){w(e instanceof n6?e.message:"Mutation failed. Please retry."),k(e instanceof n6?oG(e.reasons):null)}finally{x(!1)}}},[d,P]),F=(0,a.useCallback)(()=>void D("draft"),[D]),z=(0,a.useCallback)(()=>void D("archived"),[D]),O=(0,a.useCallback)(async()=>{if(null!==d&&window.confirm(`Revoke relationship "${d.type}"? This cannot be undone.`)){x(!0),w(null),k(null);try{let e=crypto.randomUUID(),t=await aa(d.id,String(d.etag),e);u(t)}catch(e){w(e instanceof n6?e.message:"Revoke failed. Please retry."),k(e instanceof n6?oG(e.reasons):null)}finally{x(!1)}}},[d]),K=(0,a.useCallback)(()=>{R(e=>!e)},[]),B=(0,a.useCallback)(e=>{s?.(e)},[s]),_=(0,a.useRef)(null),U=(0,a.useCallback)(()=>{_.current?.scrollIntoView?.({block:"start"})},[]);if(null===e)return(0,n.jsxs)("div",{className:"tw-pad","data-testid":"relationship-inspector-panel",children:[(0,n.jsx)(oz,{style:{marginTop:0},children:"Relationship"}),(0,n.jsx)("div",{className:"insp-empty","data-testid":"inspector-empty",children:"Select a relationship from the list to inspect it."}),(0,n.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 W=oG(m?.decision.reasons)??j,H=null!==W&&(d?.lifecycle==="blocked"||d?.lifecycle==="revoked"||null!==j),Y=null!==d?i.get(d.id)??function(e){switch(e){case"blocked":return"blocked";case"stale":return"degraded";default:return"inactive"}}(d.lifecycle):"inactive",J=null!==d?r.get(d.id):void 0;return(0,n.jsxs)("div",{className:"tw-pad","aria-busy":p,"data-testid":"relationship-inspector-panel",children:[null!==g&&(0,n.jsxs)("div",{className:"lk-alert",role:"alert","aria-live":"assertive",children:[(0,n.jsx)("span",{children:g}),(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>void P(e),children:"Retry"})]}),null!==y&&(0,n.jsxs)("div",{className:"lk-alert",role:"alert","aria-live":"assertive",children:[(0,n.jsx)("span",{children:y}),(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>w(null),children:"Dismiss"})]}),p&&A&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oz,{style:{marginTop:0},children:"Relationship"}),(0,n.jsx)(oF,{lines:4}),(0,n.jsx)(oF,{lines:3})]}),!p&&null===g&&null===d&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oz,{style:{marginTop:0},children:"Relationship"}),(0,n.jsx)("div",{className:"insp-empty","data-testid":"inspector-not-found",children:"This relationship is no longer available."}),(0,n.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!==l&&(0,n.jsx)("button",{type:"button",className:"arun-btn",style:{marginTop:8},onClick:l,children:"Clear focus"})]}),!p&&null!==d&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oz,{style:{marginTop:0},children:"Relationship"}),(0,n.jsx)(oO,{rel:d}),(0,n.jsx)(oK,{label:"Source",kind:d.source.kind,id:d.source.id}),(0,n.jsx)(oK,{label:"Target",kind:d.target.kind,id:d.target.id}),(0,n.jsx)(oB,{lifecycle:d.lifecycle}),(0,n.jsx)(o_,{type:d.type,lifecycle:d.lifecycle,activity:Y,throughputCount:J,animateBadges:o,highContrast:c,transitions:m?.lifecycle??[],densityMode:t}),(0,n.jsx)(oU,{}),(0,n.jsx)(oW,{auditRows:m?.lifecycle??[],loading:!1,error:null,onRetry:()=>void P(e),onLoadMore:()=>{},hasMore:!1}),(0,n.jsx)("div",{ref:_,children:(0,n.jsx)(oH,{rel:d})}),(0,n.jsx)(oY,{relationshipId:d.id,forwardCount:$,reverseCount:T,outgoing:N,incoming:C,expanded:E,onToggle:K,onSelectRelationship:B}),H&&null!==W&&(0,n.jsx)(oJ,{codes:W.codes,messages:W.messages}),(0,n.jsx)(oV,{rel:d,onReconnect:F,onArchive:z,onRevoke:()=>void O(),onViewImpact:K,onViewEvidence:U,mutating:b})]})]})}let oQ=new Set(["kind","id","state","timestamp","count"]);function oZ(e){return`${e.kind}: ${e.id}`}function o0({category:e}){return(0,n.jsxs)("p",{role:"note",style:{margin:"4px 0 0",fontSize:11,color:"var(--fg-muted)",borderLeft:"2px solid var(--warn)",paddingLeft:8},children:["More ",e," exist than the bounded query returned. Resolve the listed items, then re-run the health check."]})}function o1({category:e,onSelectRelationship:t}){if(0===e.items.length)return null;let a=e.items.slice(0,50),l=e.items.length-a.length;return(0,n.jsxs)("section",{"aria-label":`${e.label} (${String(e.items.length)})`,style:{marginBottom:14},children:[(0,n.jsxs)("div",{className:"rb-section-label",role:"heading","aria-level":3,children:[e.label,(0,n.jsx)("span",{className:"rb-count","aria-hidden":"true",children:e.items.length})]}),(0,n.jsx)("p",{style:{margin:"0 0 6px",fontSize:11,color:"var(--fg-muted)"},children:e.help}),(0,n.jsx)("ul",{style:{listStyle:"none",margin:0,padding:0},children:a.map(e=>(0,n.jsx)("li",{style:{marginBottom:2},children:(0,n.jsxs)("button",{type:"button",className:"arun-btn ghost",onClick:()=>t(e.id),"aria-label":`Inspect ${e.type} relationship from ${oZ(e.source)} to ${oZ(e.target)}, lifecycle ${e.lifecycle}`,style:{display:"flex",width:"100%",gap:6,alignItems:"center",textAlign:"left",fontSize:12},children:[(0,n.jsx)("span",{className:"mono",style:{color:"var(--fg)"},children:e.type}),(0,n.jsxs)("span",{style:{color:"var(--fg-muted)"},children:[oZ(e.source)," → ",oZ(e.target)]}),(0,n.jsx)("span",{className:"mono",style:{marginLeft:"auto",color:"var(--fg-muted)"},children:e.lifecycle})]})},e.id))}),l>0&&(0,n.jsxs)("p",{role:"note",style:{margin:"4px 0 0",fontSize:11,color:"var(--fg-muted)"},children:["Showing the first ",String(50)," of ",String(e.items.length),"."]}),e.truncated&&(0,n.jsx)(o0,{category:e.label.toLowerCase()})]})}function o2({findings:e}){if(0===e.orphanedEndpoints.length)return null;let t=e.orphanedEndpoints.slice(0,50);return(0,n.jsxs)("section",{"aria-label":`Orphaned endpoints (${String(e.orphanedEndpoints.length)})`,style:{marginBottom:14},children:[(0,n.jsxs)("div",{className:"rb-section-label",role:"heading","aria-level":3,children:["Orphaned endpoints",(0,n.jsx)("span",{className:"rb-count","aria-hidden":"true",children:e.orphanedEndpoints.length})]}),(0,n.jsx)("p",{style:{margin:"0 0 6px",fontSize:11,color:"var(--fg-muted)"},children:"Endpoints that participate in no live relationship."}),(0,n.jsx)("ul",{style:{listStyle:"none",margin:0,padding:0},children:t.map(e=>(0,n.jsx)("li",{className:"rb-row",style:{fontSize:12},children:(0,n.jsx)("span",{className:"mono",children:oZ(e)})},`${e.kind}:${e.id}`))}),e.orphanedEndpointsTruncated&&(0,n.jsx)(o0,{category:"orphaned endpoints"})]})}function o4({onSelectRelationship:e}){var t,l;let[s,i]=(0,a.useState)(null),[r,o]=(0,a.useState)(!0),[c,d]=(0,a.useState)(null),u=(0,a.useCallback)(async()=>{o(!0),d(null);try{let e=await ai();i(e)}catch(e){d(e instanceof n6?e.message:"Could not load the graph health check.")}finally{o(!1)}},[]);return(0,a.useEffect)(()=>{u()},[u]),(0,n.jsxs)("div",{style:{padding:12,height:"100%",overflowY:"auto"},"aria-busy":r,children:[(0,n.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[(0,n.jsx)("h2",{style:{margin:0,fontSize:13,fontWeight:600,color:"var(--fg)",flexGrow:1},children:"Graph health"}),(0,n.jsx)("button",{type:"button",className:"arun-btn",onClick:()=>void u(),"aria-label":"Re-run the graph health check",style:{minHeight:24},children:"Refresh"})]}),r&&(0,n.jsx)("p",{style:{fontSize:12,color:"var(--fg-muted)"},"aria-live":"polite",children:"Running health check…"}),null!==c&&(0,n.jsxs)("div",{className:"lk-alert",role:"alert",children:[c,(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>void u(),children:"Retry"})]}),!r&&null===c&&null!==s&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("p",{style:{fontSize:11,color:"var(--fg-faint)",margin:"0 0 10px"},children:["Checked at"," ",(0,n.jsx)("time",{dateTime:new Date(s.checkedAt).toISOString(),children:new Date(s.checkedAt).toLocaleString()}),"."]}),(0,n.jsx)("div",{className:"rb-rows",style:{marginBottom:14},children:n1.filter(e=>(s.totals[e]??0)>0).map(e=>(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:e}),(0,n.jsx)("span",{className:"rb-row-v mono",children:String(s.totals[e]??0)})]},e))}),0===(t=s.findings).orphanedEndpoints.length+t.staleRelationships.length+t.blockedRelationships.length+t.failedRelationships.length+t.invalidReferences.length+t.cycleParticipants.length?(0,n.jsxs)("div",{className:"lk-empty",children:[(0,n.jsx)("p",{className:"lk-empty-title",children:"Healthy"}),(0,n.jsx)("p",{className:"lk-empty-body",children:"No relationship-graph defects were found."})]}):(0,n.jsxs)(n.Fragment,{children:[[{key:"invalid",label:"Invalid references",help:"An endpoint no longer resolves to a live workspace object.",items:(l=s.findings).invalidReferences,truncated:l.invalidReferencesTruncated},{key:"blocked",label:"Blocked",help:"A policy or endpoint state is blocking this relationship.",items:l.blockedRelationships,truncated:l.blockedRelationshipsTruncated},{key:"failed",label:"Failed (revoked)",help:"The relationship reached the revoked terminal state.",items:l.failedRelationships,truncated:l.failedRelationshipsTruncated},{key:"cycle",label:"Cycle participants",help:"These relationships take part in a dependency cycle.",items:l.cycleParticipants,truncated:l.cycleScanTruncated},{key:"stale",label:"Stale",help:"A health check flagged at least one endpoint as not currently live.",items:l.staleRelationships,truncated:l.staleRelationshipsTruncated}].map(t=>(0,n.jsx)(o1,{category:t,onSelectRelationship:e},t.key)),(0,n.jsx)(o2,{findings:s.findings})]})]})]})}let o3={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 o6(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function o5(e){return"string"==typeof e&&e.length>0}function o8(e,t,n){return void 0===n?{code:e,message:t}:{code:e,field:n,message:t}}function o7(e,t,n){return o6(e)?o5(e.kind)?o5(e.id)?!!o5(e.workspaceId)||(n.push(o8("denied/schema-version-unsupported",`${t}.workspaceId must be a non-empty string`,`${t}.workspaceId`)),!1):(n.push(o8("denied/schema-version-unsupported",`${t}.id must be a non-empty string`,`${t}.id`)),!1):(n.push(o8("denied/schema-version-unsupported",`${t}.kind must be a non-empty string`,`${t}.kind`)),!1):(n.push(o8("denied/schema-version-unsupported",`${t} must be an object`,t)),!1)}function o9(e,t,n){o5(e[t])||n.push(o8("denied/schema-version-unsupported",`${t} must be a non-empty string`,t))}function ce(e,t){let n=e.kind;return nQ.includes(n)?null:o8("denied/schema-version-unsupported",`${t}.kind is not a known object kind`,`${t}.kind`)}function ct(e,t,n){"missing"===t?n.push(o8("source"===e?"denied/non-existent-source":"denied/non-existent-target",`${e} endpoint does not exist`,e)):"tombstoned"===t?n.push(o8("denied/endpoint-tombstoned",`${e} endpoint has been tombstoned`,e)):"retired"===t?n.push(o8("denied/endpoint-retired",`${e} endpoint has been retired`,e)):"unavailable"===t&&n.push(o8("denied/endpoint-unavailable",`${e} endpoint is unavailable`,e))}function cn(e,t){let n=e.kind;return nZ.includes(n)?null:o8("denied/object-kind-not-yet-supported",`${t}.kind "${n}" is reserved for a future release`,`${t}.kind`)}function ca(){return{type:"reads-context",sourceKind:"workflow-run",sourceId:"",targetKind:"memory",targetId:"",summary:""}}let cl=new Set(["denied/path-not-contained","denied/cross-workspace","denied/payload-content-not-permitted"]);function cs(e){return e?.codes.some(e=>cl.has(e))===!0}function ci({onClose:e}){let[t,l]=(0,a.useState)(ca),[s,i]=(0,a.useState)([]),[r,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(!1),[u,m]=(0,a.useState)(!1),h=(0,a.useRef)(null),p=(0,a.useRef)(null),f="rel-create-dialog-title",g="rel-create-dialog-desc";(0,a.useEffect)(()=>{p.current?.focus()},[]);let v=(0,a.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")),a=n[0],l=n[n.length-1];"Tab"===e.key&&(e.shiftKey?document.activeElement===a&&(e.preventDefault(),l?.focus()):document.activeElement===l&&(e.preventDefault(),a?.focus()))},[]),b=(0,a.useCallback)(t=>{"Escape"===t.key&&e(null)},[e]);(0,a.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,a.useEffect)(()=>{if(0===t.sourceId.length||0===t.targetId.length)return void i([]);let e=function(e){let t=function(e){var t;if(!o6(e))return{errors:[o8("denied/schema-version-unsupported","relationship must be an object")]};let n=[];o9(e,"id",n),o9(e,"workspaceId",n),o9(e,"createdAt",n),o9(e,"updatedAt",n),(!("number"==typeof(t=e.etag)&&Number.isInteger(t)&&Number.isFinite(t))||e.etag<0)&&n.push(o8("denied/schema-version-unsupported","etag must be a non-negative finite integer","etag"));let a=o7(e.source,"source",n),l=o7(e.target,"target",n);return!(n.length>0)&&a&&l?{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:a,target:l}=t.value,s=function(e,t,n){let a,l,s="1"!==e.schemaVersion?o8("denied/schema-version-unsupported",'schemaVersion must be the literal "1"',"schemaVersion"):null;if(s)return[s];let i=o5(a=e.type)?n0.includes(a)?null:o8("denied/schema-version-unsupported","type is not a known relationship type","type"):o8("denied/schema-version-unsupported","type must be a non-empty string","type");if(i)return[i];let r=ce(t,"source"),o=ce(n,"target");if(null!==r||null!==o){let e=[];return null!==r&&e.push(r),null!==o&&e.push(o),e}let c=o5(l=e.lifecycleState)?n1.includes(l)?null:o8("denied/schema-version-unsupported","lifecycleState is not a known lifecycle state","lifecycleState"):o8("denied/schema-version-unsupported","lifecycleState must be a non-empty string","lifecycleState");return c?[c]:null}(n,a,l);if(s)return{ok:!1,errors:s};let i=function(e){if(!e?.endpointResolver)return null;let t=[];return"missing"===e.endpointResolver.source&&ct("source",e.endpointResolver.source,t),"missing"===e.endpointResolver.target&&ct("target",e.endpointResolver.target,t),t}(void 0);if(null!==i&&i.length>0)return{ok:!1,errors:i};let r=function(e,t,n,a){var l,s,i,r,o;let c,d,u,m,h,p,f=[],g=e.type,v=e.lifecycleState,b=cn(t,"source");b&&f.push(b);let x=cn(n,"target");x&&f.push(x),null===b&&null===x&&(l=t.kind,s=n.kind,"denied/source-kind-not-allowed"===(d=(c=n2[g]).validSourceKinds.includes(l)?c.validTargetKinds.includes(s)?null:"denied/target-kind-not-allowed":"denied/source-kind-not-allowed")?f.push(o8("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(o8("denied/target-kind-not-allowed",`target.kind "${n.kind}" is not permitted for type "${g}"`,"target.kind")));let y=(u=a?.cardinalityCounts)?"produces-evidence"===g&&"number"==typeof u.producesEvidenceForSource&&u.producesEvidenceForSource>=1?o8("denied/cardinality-exceeded","produces-evidence already exists for this source workflow-run"):"starts-workflow"===g&&"number"==typeof u.startsWorkflowForTarget&&u.startsWorkflowForTarget>=1?o8("denied/cardinality-exceeded","starts-workflow already exists for this target workflow-run"):null:null;y&&f.push(y),(m=t.kind===n.kind&&t.id===n.id?o8("denied/cycle-forbidden","source and target refer to the same endpoint"):null)&&f.push(m),(h="depends-on"===g&&a?.dependsOnReverseEdgeExists===!0?o8("denied/cycle-forbidden","depends-on reverse edge already exists for this endpoint pair"):null)&&f.push(h);let w=(i=e.workspaceId,t.workspaceId!==i||n.workspaceId!==i?o8("denied/cross-workspace","source and target must be in the relationship's workspace"):null);w&&f.push(w);let j=void 0===(p=a?.previousLifecycleState)||o3[p].includes(v)?null:o8("denied/lifecycle-illegal-transition",`transition from ${p} to ${v} is not permitted`,"lifecycleState");for(let t of(j&&f.push(j),r=a,o=f,r?.endpointResolver&&("missing"!==r.endpointResolver.source&&ct("source",r.endpointResolver.source,o),"missing"!==r.endpointResolver.target&&ct("target",r.endpointResolver.target,o)),function(e){let t=[];if(void 0===e.metadata||null===e.metadata)return t;if(!o6(e.metadata))return t.push(o8("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 a of n4)if(e.includes(a)){t.push(o8("denied/payload-content-not-permitted","metadata may not carry endpoint content",`metadata.${n}`));break}}return t}(e)))f.push(t);return f}(n,a,l,void 0);return r.length>0?{ok:!1,errors:r}:{ok:!0,value:n}}({id:"candidate",schemaVersion:"1",workspaceId:"preview",source:{kind:t.sourceKind,id:t.sourceId,workspaceId:"preview"},target:{kind:t.targetKind,id:t.targetId,workspaceId:"preview"},type:t.type,lifecycleState:"active",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),etag:0});e.ok?i([]):i(e.errors.map(e=>e.message))},[t]);let x=(0,a.useRef)(null),y=(0,a.useRef)(0);(0,a.useEffect)(()=>{y.current+=1;let e=y.current;return(null!==x.current&&clearTimeout(x.current),0===t.sourceId.length||0===t.targetId.length||s.length>0)?void m(!1):(x.current=setTimeout(async()=>{m(!0);try{if(await n7({type:t.type,source:{kind:t.sourceKind,id:t.sourceId},target:{kind:t.targetKind,id:t.targetId},summary:t.summary.length>0?t.summary:void 0}),e!==y.current)return;o(e=>cs(e)?e:null)}catch(t){if(e!==y.current)return;t instanceof n6&&t.reasons.length>0?o({source:"preview",codes:t.reasons.map(e=>e.code),messages:t.reasons.map(e=>e.message)}):o(null)}finally{e===y.current&&m(!1)}},250),()=>{null!==x.current&&clearTimeout(x.current)})},[t,s]),(0,a.useEffect)(()=>{o(e=>e?.source!=="submit"||cs(e)?e:null)},[t]);let w=t.sourceId.trim().length>0&&t.targetId.trim().length>0&&0===s.length&&null===r&&!c,k=(0,a.useCallback)(async()=>{if(w){d(!0),o(null);try{let n=crypto.randomUUID(),{relationship:a}=await n9({type:t.type,source:{kind:t.sourceKind,id:t.sourceId},target:{kind:t.targetKind,id:t.targetId},summary:t.summary.length>0?t.summary:void 0},n);e(a)}catch(e){e instanceof n6?e.reasons.length>0?o({source:"submit",codes:e.reasons.map(e=>e.code),messages:e.reasons.map(e=>e.message)}):o({source:"submit",codes:[e.code],messages:[e.message]}):o({source:"submit",codes:["relationship/network-error"],messages:[n3]})}finally{d(!1)}}},[w,t,e]),N=(0,a.useCallback)(e=>{"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&k()},[k]),S=n2[t.type],C=cs(r),I=[s.length>0?"rel-create-client-hints":null,null!==r?"rel-create-server-denial":null].filter(e=>null!==e),E=(0,n.jsx)("div",{className:"cmdk-overlay",onPointerDown:()=>e(null),"data-testid":"rel-create-overlay",children:(0,n.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:N,"data-testid":"rel-create-dialog",children:[(0,n.jsxs)("div",{className:"cmdk-input",style:{borderBottom:"1px solid var(--line)"},children:[(0,n.jsx)("span",{id:f,style:{fontWeight:600,fontSize:14,color:"var(--fg)"},children:"Create relationship"}),(0,n.jsx)("span",{id:g,className:"visually-hidden",children:"Create a new relationship between two workspace endpoints."}),(0,n.jsx)("button",{type:"button",className:"palette-x",onClick:()=>e(null),"aria-label":"Close",title:"Close",style:{marginLeft:"auto"},children:(0,n.jsx)(j.Icons.close,{size:16})})]}),(0,n.jsxs)("div",{style:{padding:"12px 16px",display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{htmlFor:"rel-type",style:{fontSize:12,color:"var(--fg-muted)",display:"block",marginBottom:3},children:"Type"}),(0,n.jsx)("select",{id:"rel-type",ref:p,value:t.type,onChange:e=>l(t=>({...t,type: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:13},"aria-label":"Relationship type",children:n0.map(e=>(0,n.jsx)("option",{value:e,children:n2[e].displayName},e))}),(0,n.jsx)("div",{style:{fontSize:11,color:"var(--fg-muted)",marginTop:3},children:S.semantics})]}),(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsxs)("div",{style:{flex:"0 0 140px"},children:[(0,n.jsx)("label",{htmlFor:"rel-src-kind",style:{fontSize:12,color:"var(--fg-muted)",display:"block",marginBottom:3},children:"Source kind"}),(0,n.jsx)("select",{id:"rel-src-kind",value:t.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:nZ.map(e=>(0,n.jsx)("option",{value:e,children:e},e))})]}),(0,n.jsxs)("div",{style:{flex:1},children:[(0,n.jsx)("label",{htmlFor:"rel-src-id",style:{fontSize:12,color:"var(--fg-muted)",display:"block",marginBottom:3},children:"Source ID"}),(0,n.jsx)("input",{id:"rel-src-id",type:"text",value:t.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,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsxs)("div",{style:{flex:"0 0 140px"},children:[(0,n.jsx)("label",{htmlFor:"rel-tgt-kind",style:{fontSize:12,color:"var(--fg-muted)",display:"block",marginBottom:3},children:"Target kind"}),(0,n.jsx)("select",{id:"rel-tgt-kind",value:t.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:nZ.map(e=>(0,n.jsx)("option",{value:e,children:e},e))})]}),(0,n.jsxs)("div",{style:{flex:1},children:[(0,n.jsx)("label",{htmlFor:"rel-tgt-id",style:{fontSize:12,color:"var(--fg-muted)",display:"block",marginBottom:3},children:"Target ID"}),(0,n.jsx)("input",{id:"rel-tgt-id",type:"text",value:t.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,n.jsxs)("div",{children:[(0,n.jsx)("label",{htmlFor:"rel-summary",style:{fontSize:12,color:"var(--fg-muted)",display:"block",marginBottom:3},children:"Summary (optional, ≤240 chars)"}),(0,n.jsx)("textarea",{id:"rel-summary",value:t.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"})]}),s.length>0&&(0,n.jsx)("div",{id:"rel-create-client-hints",className:"lk-alert",role:"status","aria-live":"polite","data-testid":"client-validation-hints",children:s.map((e,t)=>(0,n.jsx)("div",{style:{fontSize:12},children:e},t))}),u&&(0,n.jsx)("div",{style:{fontSize:12,color:"var(--fg-muted)"},"aria-live":"polite",children:"Validating…"}),null!==r&&(0,n.jsxs)("div",{id:"rel-create-server-denial",className:"lk-alert",role:"alert","aria-live":"assertive","data-testid":"server-denial-banner",children:[r.codes.map((e,t)=>(0,n.jsxs)("div",{style:{marginBottom:6*(t<r.codes.length-1)},children:[(0,n.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--fg-muted)",marginBottom:2},children:e}),(0,n.jsx)("div",{style:{fontSize:13,color:"var(--fg)"},children:r.messages[t]??e})]},e)),C&&(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>o(null),style:{marginTop:6},children:"Dismiss"})]}),(0,n.jsxs)("div",{style:{display:"flex",gap:8,justifyContent:"flex-end",marginTop:4},children:[(0,n.jsx)("button",{type:"button",className:"arun-btn",onClick:()=>e(null),style:{minWidth:24,minHeight:24},children:"Cancel"}),(0,n.jsx)("button",{type:"button",className:`arun-btn${w?" primary":""}`,"aria-disabled":!w,"aria-describedby":I.length>0?I.join(" "):void 0,onClick:()=>void k(),"aria-busy":c,style:{minWidth:24,minHeight:24},children:c?"Creating…":"Create"})]})]})]})});return"u"<typeof document?E:(0,tA.createPortal)(E,document.body)}let cr={};function co(){let{activityMap:e,throughputMap:t,animate:l}=function(){let e=(0,a.useRef)(new Map),t=(0,a.useRef)("u"<typeof document||"visible"===document.visibilityState),[n,l]=(0,a.useState)(new Map),[s,i]=(0,a.useState)(new Map),r=(0,a.useRef)(new Map),o=(0,a.useRef)(new Map),[c,d]=(0,a.useState)(()=>window.matchMedia("(prefers-reduced-motion: reduce)").matches),[u,m]=(0,a.useState)(!1),h=(0,a.useCallback)(()=>{m(!0)},[]),p=(0,a.useCallback)((t,n)=>{let a=new Map(r.current),s=new Set,c=new Set,d=!1;for(let[l,i]of a){let r=t-(e.current.get(l)??0);r>=6e4&&"inactive"!==i&&(a.set(l,"inactive"),c.add(l),d=!0),!n&&r>=12e4&&(a.delete(l),s.add(l),c.add(l),d=!0)}if(a.size>512)for(let t of Array.from(a.keys()).sort((t,n)=>{let l=a.get(t),s=a.get(n);return"inactive"===l&&"inactive"!==s?-1:"inactive"!==l&&"inactive"===s?1:(e.current.get(t)??0)-(e.current.get(n)??0)}).slice(0,a.size-512))a.delete(t),s.add(t),c.add(t),d=!0;if(d&&(r.current=a,l(a)),s.size>0)for(let t of s)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,i(t))}},[]);(0,a.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,a.useCallback)(n=>{if(!t.current)return;let a=Date.now();a-(e.current.get(n.id)??0)<2e3||(e.current.set(n.id,a),l(e=>{let t=new Map(e);return t.set(n.id,n.state),r.current=t,t}),"high-throughput"===n.state&&void 0!==n.count?i(e=>{let t=new Map(e);return t.set(n.id,n.count),o.current=t,t}):i(e=>{if(!e.has(n.id))return e;let t=new Map(e);return t.delete(n.id),o.current=t,t}))},[]);return(0,a.useEffect)(()=>{let e=setInterval(()=>{t.current&&p(Date.now(),!1)},15e3);return()=>{clearInterval(e)}},[p]),(0,a.useEffect)(()=>{if("u"<typeof document)return;let e=()=>{t.current="visible"===document.visibilityState,t.current&&p(Date.now(),!0)};return t.current="visible"===document.visibilityState,document.addEventListener("visibilitychange",e),()=>{document.removeEventListener("visibilitychange",e)}},[p]),(0,a.useEffect)(()=>{let e=!1,n=null,a=null;function l(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 n4.some(e=>t.includes(e))}(n)||e(t[n]))return!0;return!1}(e))return null;let n={};for(let t of oQ)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 s(){null!==a&&(clearTimeout(a),a=null)}function i(){n?.close(),n=null}function r(){!e&&null===a&&t.current&&(a=setTimeout(()=>{a=null,o()},5e3))}function o(){if(!e&&t.current){try{n=new EventSource("/api/relationships/events")}catch{r();return}n.addEventListener("relationship:activity",e=>{l(e.data)}),n.onmessage=e=>{l(e.data)},n.onerror=()=>{e||(i(),r())}}}o();let c=()=>{if(t.current="visible"===document.visibilityState,!t.current){s(),i();return}p(Date.now(),!0),null===n&&o()};return document.addEventListener("visibilitychange",c),()=>{e=!0,document.removeEventListener("visibilitychange",c),s(),i()}},[void 0,f,p]),{activityMap:n,throughputMap:s,animate:!c&&!u,disable:h}}(),[s,i]=(0,a.useState)(!1),[r,o]=(0,a.useState)(cr),c=r.relFocus,d=r.relDensity??"minimal",[u,m]=(0,a.useState)(!1),h=(0,a.useRef)(null),p=(0,a.useRef)(!1),f=(0,a.useRef)(null),[g,v]=(0,a.useState)(!1),b=(0,a.useCallback)(e=>{o(t=>{let n={...t,...e},a={};for(let[e,t]of Object.entries(n))void 0!==t&&""!==t&&(a[e]=t);return a})},[]),x=(0,a.useCallback)(e=>{b({relFocus:e})},[b]),y=(0,a.useCallback)(()=>{b({relFocus:void 0})},[b]),w=(0,a.useCallback)(e=>{b({relFocus:e})},[b]),j=(0,a.useCallback)(e=>{p.current=!0,m(!1),null!==e&&b({relFocus:e.id})},[b]);return(0,a.useEffect)(()=>{!u&&p.current&&(p.current=!1,h.current?.focus())},[u]),(0,a.useEffect)(()=>{let e=window.matchMedia("(prefers-contrast: more)"),t=e=>{i(e)};t(e.matches);let n=e=>{t(e.matches)};return e.addEventListener("change",n),()=>e.removeEventListener("change",n)},[]),(0,a.useEffect)(()=>{let e=f.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(u||null!==document.querySelector('[role="dialog"][aria-modal="true"]'))return;y()}};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)},[u,y]),(0,n.jsxs)(n.Fragment,{children:[u&&(0,n.jsx)(ci,{onClose:j}),(0,n.jsxs)("div",{ref:f,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",background:"var(--bg)"},children:[(0,n.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid var(--line)",flexShrink:0},children:[(0,n.jsx)("button",{type:"button",className:"arun-btn",onClick:()=>v(e=>!e),"aria-pressed":g,"aria-label":"Toggle the graph health view",style:{flex:"0 0 auto",minHeight:24,marginRight:"auto"},children:g?"Hide health":"Graph health"}),(0,n.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,n.jsxs)("div",{style:{display:"flex",flex:1,overflow:"hidden"},children:[(0,n.jsx)("div",{style:{flex:"0 0 280px",borderRight:"1px solid var(--line)",overflowY:"auto"},children:(0,n.jsx)(oA,{filters:r,selectedId:c,onSelect:x,onFilterChange:b,activityMap:e,throughputMap:t,animateBadges:l,highContrast:s})}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto"},children:g?(0,n.jsx)(o4,{onSelectRelationship:e=>{v(!1),x(e)}}):(0,n.jsx)(oX,{relationshipId:c??null,densityMode:d,onClearFocus:y,onViewImpact:w,activityMap:e,throughputMap:t,animateBadges:l,highContrast:s})})]})]})]})}var cc=e.i(22016);let cd={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 cu(e){if(e instanceof w.ApiError){let t=cd[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 cm={jaccardThreshold:.85,staleConfidenceThreshold:.3,maxAgeMs:7776e6,maxClustersPerRun:100,maxRecordsPerRun:1e3};function ch(e,t){return`${e.toString()} ${1===e?t:`${t}s`}`}function cp(e){return"completed"===e||"failed"===e||"canceled"===e||"skipped"===e}function cf(e){return void 0===e?"—":new Date(e).toLocaleString()}function cg({id:e,onOpenDetail:t}){return void 0!==t?(0,n.jsx)("button",{type:"button",className:"mc-id-link mc-link-button",title:e,onClick:()=>t(e),children:e}):(0,n.jsx)(cc.default,{href:`/memoriaviva/detail?id=${encodeURIComponent(e)}`,className:"mc-id-link",title:e,children:e})}function cv({ids:e,onOpenDetail:t}){return(0,n.jsx)(n.Fragment,{children:e.map((e,l)=>(0,n.jsxs)(a.Fragment,{children:[l>0?", ":null,(0,n.jsx)(cg,{id:e,onOpenDetail:t})]},`${l.toString()}:${e}`))})}function cb({item:e,onOpenDetail:t}){return void 0===e.proposedAction?(0,n.jsx)(n.Fragment,{children:"No automatic action proposed."}):"merge"===e.proposedAction.kind?(0,n.jsxs)(n.Fragment,{children:["Merge into ",(0,n.jsx)(cg,{id:e.proposedAction.winner,onOpenDetail:t}),"; replace ",(0,n.jsx)(cv,{ids:e.proposedAction.losers,onOpenDetail:t}),"."]}):(0,n.jsxs)(n.Fragment,{children:["Supersede ",(0,n.jsx)(cg,{id:e.proposedAction.older,onOpenDetail:t})," with"," ",(0,n.jsx)(cg,{id:e.proposedAction.newer,onOpenDetail:t}),"."]})}function cx({flag:e,onOpenDetail:t}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(cg,{id:e.memoryId,onOpenDetail:t})," — ",e.reason]})}function cy({label:e,name:t,value:l,min:s,max:i,step:r,help:o,disabled:c=!1,onChange:d}){let u=(0,a.useId)();return(0,n.jsxs)("div",{style:{display:"grid",gap:6},children:[(0,n.jsxs)("label",{style:{display:"grid",gap:6},children:[(0,n.jsx)("span",{className:"mc-dialog-label",children:e}),(0,n.jsx)("input",{type:"number",inputMode:"decimal",className:"mc-dialog-input",name:t,value:Number.isFinite(l)?l:"",min:s,max:i,step:r,disabled:c,"aria-describedby":u,onChange:e=>{d(t,Number(e.target.value))}})]}),(0,n.jsx)("span",{id:u,style:{color:"var(--fg-muted)",fontSize:12},children:o})]})}function cw({startJobImpl:e=tZ,fetchJobImpl:t=t0,cancelJobImpl:l=t1,pollIntervalMs:s=2e3,onBack:i,onOpenDetail:r}){var o;let[c,d]=(0,a.useState)(cm),[u,m]=(0,a.useState)(null),[h,p]=(0,a.useState)(!1),[f,g]=(0,a.useState)(!1),[v,b]=(0,a.useState)(!1),[x,y]=(0,a.useState)(null),[w,j]=(0,a.useState)(null),k=u?.job??null,N=null!==k&&!cp(k.state),S=(0,a.useMemo)(()=>{if(null===k)return null;let e=k.result;return{reviewCount:e?.reviewItems.length??0,staleCount:e?.staleFlags.length??0,edgeCount:e?.edgesProposed.length??0}},[k]),C=(0,a.useCallback)((e,t)=>{d(n=>({...n,[e]:t}))},[]),I=(0,a.useCallback)(async e=>{g(!0);try{let n=await t(e);m(n.job),j(null)}catch(e){j(cu(e))}finally{g(!1)}},[t]);(0,a.useEffect)(()=>{if(null===k||cp(k.state))return;let e=window.setInterval(()=>{I(k.id)},s);return()=>{window.clearInterval(e)}},[k,s,I]);let E=(0,a.useCallback)(async t=>{if(t.preventDefault(),!h&&!N){p(!0),y(null),j(null);try{let t=await e(c);m(t.job)}catch(e){y(cu(e))}finally{p(!1)}}},[c,e,h,N]),R=(0,a.useCallback)(async()=>{if(null!==k&&!v){b(!0),j(null);try{let e=await l(k.id);m(e.job)}catch(e){j(cu(e))}finally{b(!1)}}},[k,l,v]);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("header",{className:"lk-header",children:[(0,n.jsxs)("div",{style:{display:"grid",gap:4},children:[(0,n.jsx)("h1",{className:"lk-title",children:"MemoriaViva Consolidation"}),(0,n.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!==i?(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost lk-btn-lg",onClick:i,children:"Back to MemoriaViva"}):(0,n.jsx)(cc.default,{href:"/memoriaviva",className:"lk-btn lk-btn-ghost lk-btn-lg",children:"Back to MemoriaViva"})]}),(0,n.jsxs)("div",{className:"mc-consolidation-scroll",children:[(0,n.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,n.jsxs)("form",{onSubmit:E,style:{display:"grid",gap:16},children:[(0,n.jsxs)("div",{style:{display:"grid",gap:12,gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))"},children:[(0,n.jsx)(cy,{label:"Jaccard threshold",name:"jaccardThreshold",value:c.jaccardThreshold,min:0,max:1,step:.01,disabled:h||N,help:"Similarity floor for near-duplicate detection.",onChange:C}),(0,n.jsx)(cy,{label:"Stale confidence threshold",name:"staleConfidenceThreshold",value:c.staleConfidenceThreshold,min:0,max:1,step:.01,disabled:h||N,help:"Memories at or below this confidence are flagged stale.",onChange:C}),(0,n.jsx)(cy,{label:"Max age (days)",name:"maxAgeMs",value:c.maxAgeMs/864e5,min:0,step:1,disabled:h||N,help:"Memories older than this are checked for staleness.",onChange:(e,t)=>{C(e,864e5*t)}}),(0,n.jsx)(cy,{label:"Max clusters per run",name:"maxClustersPerRun",value:c.maxClustersPerRun,min:0,max:1e3,step:1,disabled:h||N,help:"Hard bound on duplicate clusters inspected in one run.",onChange:C}),(0,n.jsx)(cy,{label:"Max records per run",name:"maxRecordsPerRun",value:c.maxRecordsPerRun,min:0,max:1e3,step:1,disabled:h||N,help:"Hard bound on accepted records admitted to one scan.",onChange:C})]}),null!==x?(0,n.jsx)("div",{role:"alert",className:"lk-alert",children:x}):null,(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:12},children:[(0,n.jsx)("button",{type:"submit",className:"lk-btn lk-btn-primary","aria-disabled":h||N,"aria-busy":h,children:h?"Starting…":"Start consolidation"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null===k||f,"aria-busy":f,onClick:()=>{null===k||f||I(k.id)},children:f?"Refreshing…":"Refresh status"}),N?(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":v,"aria-busy":v,onClick:()=>{R()},children:v?"Canceling…":"Cancel job"}):null]})]})}),(0,n.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===k?(0,n.jsx)("p",{style:{margin:0,color:"var(--fg-muted)"},children:"No consolidation job started yet."}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{style:{display:"grid",gap:12,gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))"},children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"State"}),(0,n.jsx)("div",{role:"status","aria-live":"polite","aria-atomic":"true",style:{fontWeight:700,textTransform:"capitalize"},children:k.state})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Job ID"}),(0,n.jsx)("div",{style:{wordBreak:"break-all"},children:k.id})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Started"}),(0,n.jsx)("div",{children:cf(k.startedAt)})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Completed"}),(0,n.jsx)("div",{children:cf(k.completedAt)})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Clusters inspected"}),(0,n.jsx)("div",{style:{fontVariantNumeric:"tabular-nums"},children:k.result?.clustersInspected??0})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Elapsed"}),(0,n.jsx)("div",{style:{fontVariantNumeric:"tabular-nums"},children:(o=k.result?.elapsedMs??0)<1e3?`${o.toString()} ms`:`${(o/1e3).toFixed(1)} s`})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Records inspected"}),(0,n.jsxs)("div",{style:{fontVariantNumeric:"tabular-nums"},children:[k.result?.recordsInspected??0,k.result?.truncated===!0?" (truncated)":""]})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Memories loaded"}),(0,n.jsx)("div",{style:{fontVariantNumeric:"tabular-nums"},children:u?.memoryCount??0})]})]}),null!==w?(0,n.jsx)("div",{role:"alert",className:"lk-alert",children:w}):null,void 0!==k.error&&k.error.length>0?(0,n.jsx)("div",{role:"alert",className:"lk-alert",children:k.error}):null,null!==S?(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:12},children:[(0,n.jsx)("span",{className:"mc-badge mc-badge-default",children:ch(S.reviewCount,"review item")}),(0,n.jsx)("span",{className:"mc-badge mc-badge-default",children:ch(S.staleCount,"stale flag")}),(0,n.jsx)("span",{className:"mc-badge mc-badge-default",children:ch(S.edgeCount,"proposed edge")})]}):null]})}),k?.result!==void 0?(0,n.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,n.jsxs)("article",{style:{display:"grid",gap:12,padding:16,border:"1px solid var(--line)",borderRadius:14,background:"var(--card)"},children:[(0,n.jsx)("h2",{className:"lk-section-head",style:{margin:0},children:"Review items"}),0===k.result.reviewItems.length?(0,n.jsx)("p",{style:{margin:0,color:"var(--fg-muted)"},children:"No review items returned."}):(0,n.jsx)("ul",{style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:12},children:k.result.reviewItems.map(e=>(0,n.jsxs)("li",{style:{display:"grid",gap:4},children:[(0,n.jsx)("strong",{style:{textTransform:"capitalize"},children:e.reason.replaceAll("-"," ")}),(0,n.jsx)("span",{children:(0,n.jsx)(cv,{ids:e.relatedMemoryIds,onOpenDetail:r})}),(0,n.jsx)("span",{style:{color:"var(--fg-muted)"},children:(0,n.jsx)(cb,{item:e,onOpenDetail:r})})]},e.id))})]}),(0,n.jsxs)("article",{style:{display:"grid",gap:12,padding:16,border:"1px solid var(--line)",borderRadius:14,background:"var(--card)"},children:[(0,n.jsx)("h2",{className:"lk-section-head",style:{margin:0},children:"Stale flags"}),0===k.result.staleFlags.length?(0,n.jsx)("p",{style:{margin:0,color:"var(--fg-muted)"},children:"No stale flags returned."}):(0,n.jsx)("ul",{style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:12},children:k.result.staleFlags.map(e=>(0,n.jsx)("li",{children:(0,n.jsx)(cx,{flag:e,onOpenDetail:r})},`${e.memoryId}:${e.reason}`))})]}),(0,n.jsxs)("article",{style:{display:"grid",gap:12,padding:16,border:"1px solid var(--line)",borderRadius:14,background:"var(--card)"},children:[(0,n.jsx)("h2",{className:"lk-section-head",style:{margin:0},children:"Proposed edges"}),0===k.result.edgesProposed.length?(0,n.jsx)("p",{style:{margin:0,color:"var(--fg-muted)"},children:"No edges proposed."}):(0,n.jsx)("ul",{style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:12},children:k.result.edgesProposed.map(e=>(0,n.jsxs)("li",{style:{display:"grid",gap:4},children:[(0,n.jsx)("strong",{children:e.kind}),(0,n.jsxs)("span",{children:[(0,n.jsx)(cg,{id:e.fromMemoryId,onOpenDetail:r})," →"," ",(0,n.jsx)(cg,{id:e.toMemoryId,onOpenDetail:r})]}),void 0!==e.provenanceSummary?(0,n.jsx)("span",{style:{color:"var(--fg-muted)"},children:e.provenanceSummary}):null]},e.id))})]})]}):null]})]})}let cj=["user","workspace","project","workflow","global"],ck=["episodic","semantic-fact","procedural","preference","correction","decision","negative","pinned"],cN=["public","confidential","restricted"],cS=["proposed","accepted","rejected","superseded","archived","forgotten","conflicted","expired"],cC={user:"User",workspace:"Workspace",project:"Project",workflow:"Workflow",global:"Global"},cI={episodic:"Episodic","semantic-fact":"Fact",procedural:"Procedural",preference:"Preference",correction:"Correction",decision:"Decision",negative:"Negative",pinned:"Pinned"},cE={proposed:"Proposed",accepted:"Accepted",rejected:"Rejected",superseded:"Superseded",archived:"Archived",forgotten:"Forgotten",conflicted:"Conflicted",expired:"Expired"},cR={public:"Public",confidential:"Confidential",restricted:"Restricted"};function c$(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function cT({label:e,items:t,labels:a,active:l,onToggle:s}){return(0,n.jsxs)("div",{className:"mc-filter-row",role:"group","aria-label":`Filter by ${e}`,children:[(0,n.jsx)("span",{className:"mc-filter-label",children:e}),(0,n.jsx)("div",{className:"mc-filter-chips",children:t.map(e=>{let t=l.includes(e);return(0,n.jsx)("button",{type:"button",className:"mc-chip","data-active":String(t),"aria-pressed":t,onClick:()=>{s(e)},children:a[e]},e)})})]})}function cA({filters:e,onChange:t}){return(0,n.jsxs)("section",{className:"mc-filters","aria-label":"Memory filters",children:[(0,n.jsx)(cT,{label:"Scope",items:cj,labels:cC,active:e.scope,onToggle:n=>{t({...e,scope:c$(e.scope,n)})}}),(0,n.jsx)(cT,{label:"Type",items:ck,labels:cI,active:e.type,onToggle:n=>{t({...e,type:c$(e.type,n)})}}),(0,n.jsx)(cT,{label:"Status",items:cS,labels:cE,active:e.status,onToggle:n=>{t({...e,status:c$(e.status,n)})}}),(0,n.jsx)(cT,{label:"Sensitivity",items:cN,labels:cR,active:e.sensitivity,onToggle:n=>{t({...e,sensitivity:c$(e.sensitivity,n)})}})]})}let cM={public:"Public",confidential:"Confidential",restricted:"Restricted"};function cL({record:e,mode:t="edit",onSave:l,onClose:s,editMemoryImpl:i=t4,correctMemoryImpl:r=t9}){let[o,c]=(0,a.useState)(e.body),[d,u]=(0,a.useState)(e.tags.join(", ")),[m,h]=(0,a.useState)(e.provenance.sensitivity),[p,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(null),[b,x]=(0,a.useState)(!1),y=(0,a.useRef)(null),w=(0,a.useRef)(null),j=(0,a.useRef)(null),k=(0,a.useRef)(null),N=(0,a.useId)(),S=(0,a.useId)(),C="correct"===t;(0,a.useEffect)(()=>(k.current=document.activeElement instanceof HTMLElement?document.activeElement:null,y.current?.focus(),()=>{k.current?.focus()}),[]);let I=(0,a.useCallback)(e=>{if("Escape"===e.key)return void s();if("Tab"!==e.key)return;let t=j.current?.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled])');if(void 0===t||0===t.length){e.preventDefault(),j.current?.focus();return}let n=t[0],a=t[t.length-1];if(void 0===n||void 0===a){e.preventDefault(),j.current?.focus();return}let l=document.activeElement;e.shiftKey||l!==a?e.shiftKey&&l===n&&(e.preventDefault(),a.focus()):(e.preventDefault(),n.focus())},[s]),E=(0,a.useCallback)(e=>{e.target===w.current&&s()},[s]),R=(0,a.useCallback)(async()=>{let t=o.trim();if(0===t.length){v("Body cannot be empty."),x(!0),y.current?.focus();return}let n=d.split(",").map(e=>e.trim()).filter(e=>e.length>0);f(!0),v(null);try{if(C){let n=await r(e.id,t);l(n.correction)}else{let a=await i(e.id,{body:t,tags:n,sensitivity:m});l(a.memory)}}catch(e){v(cu(e))}finally{f(!1)}},[o,d,m,e.id,C,r,i,l]);return(0,n.jsx)("div",{ref:w,className:"mc-dialog-backdrop",role:"presentation",onClick:E,children:(0,n.jsxs)("div",{ref:j,role:"dialog","aria-modal":"true","aria-labelledby":N,tabIndex:-1,className:"mc-dialog",onKeyDown:I,children:[(0,n.jsx)("h2",{id:N,className:"mc-dialog-title",children:C?"Correct memory":"Edit memory"}),(0,n.jsxs)("div",{className:"mc-dialog-field",children:[(0,n.jsx)("label",{htmlFor:"edit-body",className:"mc-dialog-label",children:C?"Corrected body":"Body"}),(0,n.jsx)("textarea",{id:"edit-body",ref:y,className:"mc-dialog-textarea",value:o,rows:5,onChange:e=>{c(e.target.value),b&&(x(!1),v(null))},disabled:p,"aria-required":"true","aria-invalid":b?"true":void 0,"aria-describedby":b?S:void 0})]}),C?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"mc-dialog-field",children:[(0,n.jsxs)("label",{htmlFor:"edit-tags",className:"mc-dialog-label",children:["Tags ",(0,n.jsx)("span",{className:"mc-dialog-hint",children:"(comma-separated)"})]}),(0,n.jsx)("input",{id:"edit-tags",type:"text",className:"mc-dialog-input",value:d,onChange:e=>{u(e.target.value)},disabled:p})]}),(0,n.jsxs)("div",{className:"mc-dialog-field",children:[(0,n.jsx)("label",{htmlFor:"edit-sensitivity",className:"mc-dialog-label",children:"Sensitivity"}),(0,n.jsx)("select",{id:"edit-sensitivity",className:"mc-dialog-select",value:m,onChange:e=>{h(e.target.value)},disabled:p,children:cN.map(e=>(0,n.jsx)("option",{value:e,children:cM[e]},e))})]})]}),null!==g?(0,n.jsx)("p",{id:S,role:"alert",className:"mc-dialog-error",children:g}):null,(0,n.jsxs)("div",{className:"mc-dialog-actions",children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:s,disabled:p,children:"Cancel"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-primary",onClick:()=>{R()},disabled:p,"aria-busy":p,children:p?C?"Submitting…":"Saving…":C?"Submit correction":"Save"})]})]})})}function cq({record:e,mode:t="forget",onComplete:l,onClose:s,forgetMemoryImpl:i=t8,deleteMemoryImpl:r=t7}){let[o,c]=(0,a.useState)(!1),[d,u]=(0,a.useState)(null),m=(0,a.useRef)(null),h=(0,a.useRef)(null),p=(0,a.useRef)(null),f=(0,a.useRef)(null),g="delete"===t;(0,a.useEffect)(()=>(f.current=document.activeElement instanceof HTMLElement?document.activeElement:null,m.current?.focus(),()=>{f.current?.focus()}),[]);let v=(0,a.useCallback)(e=>{if("Escape"===e.key)return void s();if("Tab"!==e.key)return;let t=p.current?.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled])');if(void 0===t||0===t.length){e.preventDefault(),p.current?.focus();return}let n=t[0],a=t[t.length-1];if(void 0===n||void 0===a){e.preventDefault(),p.current?.focus();return}let l=document.activeElement;e.shiftKey||l!==a?e.shiftKey&&l===n&&(e.preventDefault(),a.focus()):(e.preventDefault(),n.focus())},[s]),b=(0,a.useCallback)(e=>{e.target===h.current&&s()},[s]),x=(0,a.useCallback)(async()=>{c(!0),u(null);try{g?await r(e.id,"user-initiated delete from MemoriaViva"):await i(e.id,"user-initiated forget from MemoriaViva"),l()}catch(e){u(cu(e)),c(!1)}},[r,i,g,l,e.id]);return(0,n.jsx)("div",{ref:h,className:"mc-dialog-backdrop",role:"presentation",onClick:b,children:(0,n.jsxs)("div",{ref:p,role:"dialog","aria-modal":"true","aria-labelledby":"forget-dialog-title","aria-describedby":"forget-dialog-desc",tabIndex:-1,className:"mc-dialog",onKeyDown:v,children:[(0,n.jsx)("h2",{id:"forget-dialog-title",className:"mc-dialog-title",children:g?"Delete this memory?":"Forget this memory?"}),(0,n.jsx)("p",{id:"forget-dialog-desc",className:"mc-dialog-body",children:(0,n.jsxs)(n.Fragment,{children:["This action is ",(0,n.jsx)("strong",{children:"permanent"}),". The memory will be removed and a tombstone audit record will be created. You cannot undo this."]})}),(0,n.jsx)("blockquote",{className:"mc-dialog-quote","aria-label":"Memory content to be removed",children:e.body.length>120?`${e.body.slice(0,120)}…`:e.body}),null!==d?(0,n.jsx)("p",{role:"alert",className:"mc-dialog-error",children:d}):null,(0,n.jsxs)("div",{className:"mc-dialog-actions",children:[(0,n.jsx)("button",{ref:m,type:"button",className:"lk-btn lk-btn-ghost",onClick:s,disabled:o,children:"Cancel"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-danger",onClick:()=>{x()},disabled:o,"aria-busy":o,children:o?g?"Deleting…":"Forgetting…":g?"Delete permanently":"Forget permanently"})]})]})})}function cP({record:e,onRecordChange:t,acceptImpl:l=ne,rejectImpl:s=nt,pinImpl:i=t3,unpinImpl:r=t6,archiveImpl:o=t5,deleteImpl:c=t7,correctImpl:d=t9}){let[u,m]=(0,a.useState)(null),[h,p]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(!1),[x,y]=(0,a.useState)(!1),[w,j]=(0,a.useState)(!1),[k,N]=(0,a.useState)(!1),S=(0,a.useCallback)(async(e,t)=>{if(null===u){m(e),p(null),g(null);try{await t()}catch(e){p(cu(e))}finally{m(null)}}},[u]),C=(0,a.useCallback)(()=>{S("accept",async()=>{t((await l(e.id)).memory)})},[l,t,e.id,S]),I=(0,a.useCallback)(()=>{S("reject",async()=>{t((await s(e.id,"rejected by user in MemoriaViva")).memory)})},[t,e.id,s,S]),E=(0,a.useCallback)(()=>{S("pin",async()=>{t((await i(e.id)).memory)})},[t,i,e.id,S]),R=(0,a.useCallback)(()=>{S("unpin",async()=>{t((await r(e.id)).memory)})},[t,e.id,S,r]),$=(0,a.useCallback)(()=>{S("archive",async()=>{t((await o(e.id,"archived by user in MemoriaViva")).memory)})},[o,t,e.id,S]),T=(0,a.useCallback)(e=>{y(!1),g(`Correction submitted for review: ${e.body}`)},[]),A="proposed"===e.status,M="accepted"===e.status||"superseded"===e.status||"conflicted"===e.status||"expired"===e.status,L="forgotten"===e.status;return(0,n.jsxs)("div",{className:"mc-actions",role:"group","aria-label":"Memory actions",children:[A?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-primary","aria-disabled":null!==u,"aria-busy":"accept"===u,onClick:C,"aria-label":"Approve this memory proposal",children:"accept"===u?"Approving…":"Approve"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==u,"aria-busy":"reject"===u,onClick:I,"aria-label":"Reject this memory proposal",children:"reject"===u?"Rejecting…":"Reject"})]}):null,L?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==u,onClick:()=>{null===u&&(p(null),g(null),b(!0))},"aria-label":"Edit memory body, tags, or sensitivity",children:"Edit"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==u,onClick:()=>{null===u&&(p(null),g(null),y(!0))},"aria-label":"Create a correction proposal for this memory",children:"Correct"})]}),L?null:e.pinned?(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==u,"aria-busy":"unpin"===u,onClick:R,"aria-label":"Unpin this memory",children:"unpin"===u?"Unpinning…":"Unpin"}):(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==u,"aria-busy":"pin"===u,onClick:E,"aria-label":"Pin this memory for priority retrieval",children:"pin"===u?"Pinning…":"Pin"}),M?(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==u,"aria-busy":"archive"===u,onClick:$,"aria-label":"Archive this memory",children:"archive"===u?"Archiving…":"Archive"}):null,L?null:(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-danger","aria-disabled":null!==u,onClick:()=>{null===u&&(p(null),g(null),j(!0))},"aria-label":"Forget this memory permanently",children:"Forget"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-danger","aria-disabled":null!==u,onClick:()=>{null===u&&(p(null),g(null),N(!0))},"aria-label":"Delete this memory record",children:"Delete"}),null!==h?(0,n.jsx)("p",{role:"alert","aria-live":"assertive",className:"mc-action-error",children:h}):null,null!==f?(0,n.jsx)("p",{role:"status","aria-live":"polite",className:"mc-action-notice",children:f}):null,v?(0,n.jsx)(cL,{record:e,onSave:e=>{b(!1),t(e)},onClose:()=>{b(!1)}}):null,x?(0,n.jsx)(cL,{mode:"correct",record:e,correctMemoryImpl:d,onSave:T,onClose:()=>{y(!1)}}):null,w?(0,n.jsx)(cq,{record:e,onComplete:()=>{j(!1),t(null)},onClose:()=>{j(!1)}}):null,k?(0,n.jsx)(cq,{mode:"delete",record:e,deleteMemoryImpl:c,onComplete:()=>{N(!1),t(null)},onClose:()=>{N(!1)}}):null]})}function cD(e){return new Date(e).toLocaleString()}function cF({label:e,value:t}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("dt",{className:"mc-meta-label",children:e}),(0,n.jsx)("dd",{className:"mc-meta-value",children:t})]})}function cz({provenance:e}){return(0,n.jsxs)("section",{"aria-label":"Provenance",className:"mc-section",children:[(0,n.jsx)("h2",{className:"lk-section-head",children:"Provenance"}),(0,n.jsxs)("dl",{className:"mc-meta",children:[(0,n.jsx)(cF,{label:"Source kind",value:e.sourceKind}),(0,n.jsx)(cF,{label:"Captured at",value:cD(e.capturedAt)}),(0,n.jsx)(cF,{label:"Confidence",value:`${(100*e.confidence).toFixed(0)}%`}),(0,n.jsx)(cF,{label:"Sensitivity",value:e.sensitivity}),void 0!==e.captureRationale?(0,n.jsx)(cF,{label:"Rationale",value:e.captureRationale}):null,void 0!==e.modelIdentity?(0,n.jsx)(cF,{label:"Model",value:`${e.modelIdentity.provider} / ${e.modelIdentity.modelId}`}):null]})]})}function cO({validity:e}){return(0,n.jsxs)("section",{"aria-label":"Validity",className:"mc-section",children:[(0,n.jsx)("h2",{className:"lk-section-head",children:"Validity"}),(0,n.jsxs)("dl",{className:"mc-meta",children:[(0,n.jsx)(cF,{label:"Valid from",value:cD(e.validFrom)}),(0,n.jsx)(cF,{label:"Valid until",value:void 0!==e.validUntil?cD(e.validUntil):"No expiry"})]})]})}function cK({tags:e}){return 0===e.length?(0,n.jsx)("span",{className:"mc-meta-empty",children:"No tags"}):(0,n.jsx)("ul",{className:"mc-tags","aria-label":"Tags",children:e.map(e=>(0,n.jsx)("li",{className:"mc-tag",children:e},e))})}function cB({onBack:e,controlRef:t,children:a="Back to MemoriaViva"}){return void 0!==e?(0,n.jsx)("button",{ref:t,type:"button",className:"mc-back-link lk-btn lk-btn-ghost",onClick:e,children:a}):(0,n.jsx)(cc.default,{ref:t,href:"/memoriaviva",className:"mc-back-link lk-btn lk-btn-ghost","aria-label":"Back to MemoriaViva",children:a})}function c_({record:e,onBack:t}){return(0,n.jsxs)("header",{className:"mc-detail-header",children:[(0,n.jsx)(cB,{onBack:t,children:"← Back"}),(0,n.jsxs)("div",{className:"mc-detail-title-row",children:[(0,n.jsxs)("h1",{className:"lk-title",style:{flex:1},children:[cI[e.type]," memory"]}),(0,n.jsx)("span",{className:`mc-badge mc-badge-${e.status}`,children:e.status}),e.pinned?(0,n.jsx)("span",{"aria-label":"Pinned",className:"mc-badge mc-badge-pinned",children:"Pinned"}):null]})]})}function cU({id:e,fetchMemoryImpl:t=t2,onBack:l}){let[s,i]=(0,a.useState)(null),[r,o]=(0,a.useState)(!0),[c,d]=(0,a.useState)(null),[u,m]=(0,a.useState)(!1),h=(0,a.useRef)(null),p=(0,a.useCallback)(e=>{h.current=e},[]),f=(0,a.useCallback)(e=>{null===e&&m(!0),i(e)},[]);(0,a.useEffect)(()=>{u&&null===s&&h.current?.focus()},[u,s]);let g=(0,a.useCallback)(async()=>{o(!0),d(null);try{let n=await t(e);i(n.memory)}catch(e){d(cu(e))}finally{o(!1)}},[e,t]);return((0,a.useEffect)(()=>{g()},[g]),r)?(0,n.jsx)("p",{role:"status","aria-live":"polite",className:"lk-loading",children:"Loading memory…"}):null!==c?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{role:"alert","aria-live":"assertive",className:"lk-alert",children:[c,(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>{g()},children:"Retry"})]}),(0,n.jsx)("p",{children:(0,n.jsx)(cB,{onBack:l})})]}):null===s?(0,n.jsx)("div",{className:"lk-empty",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"lk-empty-title",children:u?"Memory removed":"Memory not found"}),(0,n.jsx)("p",{role:"status","aria-live":"polite",className:"lk-empty-body",children:u?"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,n.jsx)("p",{children:(0,n.jsx)(cB,{onBack:l,controlRef:p})})]})}):(0,n.jsxs)("article",{"aria-label":`Memory record: ${s.body.slice(0,60)}`,className:"mc-detail",children:[(0,n.jsx)(c_,{record:s,onBack:l}),(0,n.jsxs)("section",{"aria-label":"Memory body",className:"mc-section",children:[(0,n.jsx)("h2",{className:"lk-section-head",children:"Content"}),(0,n.jsx)("p",{className:"mc-body-text",children:s.body})]}),(0,n.jsxs)("section",{"aria-label":"Details",className:"mc-section",children:[(0,n.jsx)("h2",{className:"lk-section-head",children:"Details"}),(0,n.jsxs)("dl",{className:"mc-meta",children:[(0,n.jsx)(cF,{label:"ID",value:(0,n.jsx)("code",{className:"mc-code",children:s.id})}),(0,n.jsx)(cF,{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"}}(s.scope)}),(0,n.jsx)(cF,{label:"Type",value:cI[s.type]}),(0,n.jsx)(cF,{label:"Created",value:cD(s.createdAt)}),(0,n.jsx)(cF,{label:"Updated",value:cD(s.updatedAt)}),void 0!==s.staleReason?(0,n.jsx)(cF,{label:"Stale reason",value:(0,n.jsx)("em",{children:s.staleReason})}):null]})]}),(0,n.jsx)(cz,{provenance:s.provenance}),(0,n.jsx)(cO,{validity:s.validity}),(0,n.jsxs)("section",{"aria-label":"Tags",className:"mc-section",children:[(0,n.jsx)("h2",{className:"lk-section-head",children:"Tags"}),(0,n.jsx)(cK,{tags:s.tags})]}),(0,n.jsxs)("section",{"aria-label":"Actions",className:"mc-section",children:[(0,n.jsx)("h2",{className:"lk-section-head",children:"Actions"}),(0,n.jsx)(cP,{record:s,onRecordChange:f})]})]})}var cW=e.i(18566);let cH={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 cY({status:e}){let t=cH[e]??"mc-badge-default";return(0,n.jsx)("span",{className:`mc-badge ${t}`,children:e})}function cJ({record:e,onOpenDetail:t}){var a;let l=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"mc-row-main",children:[(0,n.jsx)("span",{className:"mc-row-body",title:e.body,children:e.body}),(0,n.jsxs)("div",{className:"mc-row-meta",children:[(0,n.jsx)("span",{className:"mc-row-type",children:cI[e.type]}),(0,n.jsx)("span",{className:"mc-row-scope",children:cC[e.scope.kind]}),(0,n.jsxs)("span",{className:"mc-row-source",children:["Source ",e.provenance.sourceKind]}),(0,n.jsx)("span",{className:"mc-row-confidence",children:(a=e.provenance.confidence,`${(100*a).toFixed(0)}% confidence`)}),(0,n.jsxs)("span",{className:"mc-row-sensitivity",children:["Sensitivity ",e.provenance.sensitivity]}),e.pinned?(0,n.jsx)("span",{className:"mc-badge mc-badge-pinned",children:"Pinned"}):null]})]}),(0,n.jsx)(cY,{status:e.status})]});return(0,n.jsx)("li",{children:void 0!==t?(0,n.jsx)("button",{type:"button",className:"mc-row mc-row-button",onClick:()=>t(e.id),children:l}):(0,n.jsx)(cc.default,{href:`/memoriaviva/detail?id=${encodeURIComponent(e.id)}`,className:"mc-row",children:l})})}function cG({hasFilters:e}){return(0,n.jsx)("div",{"data-testid":"memory-empty-state",className:"lk-empty",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"lk-empty-title",children:"No memories found"}),(0,n.jsx)("p",{className:"lk-empty-body",children:e?"Try removing some filters to see more memories.":"Memories will appear here once the system captures them from your conversations and workflows."})]})})}function cV({filters:e,onFilterChange:t,fetchMemoriesImpl:l=tX,onOpenDetail:s,onOpenConsolidation:i,onOpenReviewQueue:r,policyEnabled:o,onPolicyEnabledChange:c,showWorkspaceBackLink:d=!0}){let[u,m]=(0,a.useState)([]),[h,p]=(0,a.useState)(!0),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(!0),x=o??v,y=e.scope.length>0||e.type.length>0||e.status.length>0||e.sensitivity.length>0,w=(0,a.useCallback)(async e=>{p(!0),g(null);try{let t=await l(e);m(t.memories)}catch(e){g(cu(e))}finally{p(!1)}},[l]);return(0,a.useEffect)(()=>{w(e)},[e,w]),(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("header",{className:"lk-header",children:[(0,n.jsx)("h1",{className:"lk-title",children:"MemoriaViva"}),(0,n.jsxs)("div",{className:"mc-view-actions",children:[(0,n.jsxs)("div",{className:"mc-policy-switch",children:[(0,n.jsx)(ly,{on:x,onChange:c??b,label:"Enable MemoriaViva policy"}),(0,n.jsxs)("span",{children:["Policy ",x?"on":"off"]})]}),d?(0,n.jsx)(cc.default,{href:"/",className:"lk-btn lk-btn-ghost lk-btn-lg",children:"Back to Workspace"}):null,void 0!==i?(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost lk-btn-lg",onClick:i,children:"Consolidation"}):(0,n.jsx)(cc.default,{href:"/memoriaviva/consolidation",className:"lk-btn lk-btn-ghost lk-btn-lg",children:"Consolidation"}),void 0!==r?(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost lk-btn-lg mc-queue-link",onClick:r,children:"Review queue"}):(0,n.jsx)(cc.default,{href:"/memoriaviva/review-queue",className:"lk-btn lk-btn-ghost lk-btn-lg mc-queue-link",children:"Review queue"})]})]}),(0,n.jsx)(cA,{filters:e,onChange:t}),(0,n.jsx)("p",{role:"status",className:"visually-hidden",children:h||null!==f?null:`${u.length.toString()} ${1===u.length?"memory":"memories"} found`}),(0,n.jsx)("section",{"aria-label":"Memory records","aria-busy":h,style:{flex:1,minHeight:0,overflowY:"auto"},children:h&&0===u.length?(0,n.jsx)("p",{role:"status","aria-live":"polite",className:"lk-loading",children:"Loading memories…"}):null!==f?(0,n.jsxs)("div",{role:"alert","aria-live":"assertive",className:"lk-alert",children:[f,(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>{w(e)},children:"Retry"})]}):0===u.length?(0,n.jsx)(cG,{hasFilters:y}):(0,n.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:u.map(e=>(0,n.jsx)(cJ,{record:e,onOpenDetail:s},e.id))})})]})}function cX({record:e,busyAction:t,rowError:a,onAccept:l,onReject:s,onArchive:i,onOpenDetail:r}){let o=`memory-review-body-${e.id}`,c=`View details for memory ${e.id}: ${e.body.slice(0,80)}`,d=void 0!==e.staleReason||"expired"===e.status;return(0,n.jsx)("li",{"data-review-row-id":e.id,children:(0,n.jsxs)("article",{className:"mc-review-row",children:[(0,n.jsxs)("div",{className:"mc-review-body",children:[(0,n.jsx)("p",{id:o,className:"mc-row-body",children:e.body}),(0,n.jsxs)("div",{className:"mc-row-meta",children:[(0,n.jsx)("span",{className:"mc-row-type",children:cI[e.type]}),(0,n.jsx)("span",{className:"mc-row-scope",children:cC[e.scope.kind]}),(0,n.jsx)("span",{className:`mc-badge mc-badge-${e.status}`,children:e.status}),d?(0,n.jsxs)("span",{className:"mc-row-stale",children:["Stale",void 0!==e.staleReason?`: ${e.staleReason}`:""]}):null,void 0!==r?(0,n.jsx)("button",{type:"button",className:"mc-row-detail-link mc-link-button","aria-label":c,onClick:()=>r(e.id),children:"View details"}):(0,n.jsx)(cc.default,{href:`/memoriaviva/detail?id=${encodeURIComponent(e.id)}`,className:"mc-row-detail-link","aria-label":c,children:"View details"})]}),null!==a?(0,n.jsx)("p",{role:"alert",className:"mc-action-error",children:a}):null]}),(0,n.jsx)("div",{className:"mc-review-actions",role:"group","aria-labelledby":o,children:"proposed"===e.status?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-primary","aria-disabled":null!==t,"aria-busy":"accept"===t,onClick:()=>{null===t&&l(e)},children:"accept"===t?"Approving…":"Approve"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==t,"aria-busy":"reject"===t,onClick:()=>{null===t&&s(e)},children:"reject"===t?"Rejecting…":"Reject"})]}):"conflicted"===e.status?(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==t,"aria-busy":"reject"===t,onClick:()=>{null===t&&s(e)},children:"reject"===t?"Rejecting…":"Reject conflict"}):(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==t,"aria-busy":"archive"===t,onClick:()=>{null===t&&i(e)},children:"archive"===t?"Archiving…":"Archive stale"})})]})})}function cQ({fetchQueueImpl:e=tQ,acceptImpl:t=ne,rejectImpl:l=nt,archiveImpl:s=t5,onBack:i,onOpenDetail:r}){let[o,c]=(0,a.useState)([]),[d,u]=(0,a.useState)(!0),[m,h]=(0,a.useState)(null),[p,f]=(0,a.useState)({}),[g,v]=(0,a.useState)({}),[b,x]=(0,a.useState)(""),y=(0,a.useRef)(null),w=(0,a.useRef)(null),j=(0,a.useRef)(null),k=(0,a.useCallback)(async()=>{u(!0),h(null);try{let t=await e();c(t.memories),f({}),v({})}catch(e){h(cu(e))}finally{u(!1)}},[e]);(0,a.useEffect)(()=>{k()},[k]);let N=(0,a.useCallback)(e=>{f(t=>{let n={...t};return delete n[e],n}),v(t=>{let n={...t};return delete n[e],n})},[]),S=(0,a.useCallback)(e=>{let t=o.findIndex(t=>t.id===e),n=o[t+1]??o[t-1];j.current=void 0!==n?n.id:"",c(t=>t.filter(t=>t.id!==e)),N(e)},[o,N]);(0,a.useEffect)(()=>{let e=j.current;if(null===e)return;j.current=null;let t=""===e?null:y.current?.querySelector(`[data-review-row-id="${CSS.escape(e)}"]`)??null,n=null===t?null:t.querySelector("button");null!==n?n.focus():w.current?.focus()},[o]);let C=(0,a.useCallback)(async(e,n)=>{let a=e.id;f(e=>({...e,[a]:n})),v(e=>{let t={...e};return delete t[a],t});try{"accept"===n?await t(a):"archive"===n?await s(a,"archived stale memory from review queue"):await l(a,"conflicted"===e.status?"rejected conflict from review queue":"rejected from review queue"),S(a),x("accept"===n?"Memory approved":"archive"===n?"Memory archived":"Memory rejected")}catch(e){v(t=>({...t,[a]:cu(e)})),f(e=>{let t={...e};return delete t[a],t})}},[t,s,l,S]);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("header",{className:"lk-header",children:[(0,n.jsx)("h1",{className:"lk-title",tabIndex:-1,ref:w,children:"Review queue"}),(0,n.jsxs)("span",{role:"status","aria-live":"polite",className:"mc-badge-count",children:[o.length.toString()," awaiting review"]}),void 0!==i?(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost lk-btn-lg",onClick:i,children:"Back to MemoriaViva"}):(0,n.jsx)(cc.default,{href:"/memoriaviva",className:"lk-btn lk-btn-ghost lk-btn-lg",children:"Back to MemoriaViva"})]}),(0,n.jsx)("p",{role:"status",className:"visually-hidden",children:b}),(0,n.jsx)("section",{"aria-label":"Memories awaiting review","aria-busy":d,style:{flex:1,minHeight:0,overflowY:"auto"},children:d?(0,n.jsx)("p",{role:"status","aria-live":"polite",className:"lk-loading",children:"Loading review queue…"}):null!==m?(0,n.jsxs)("div",{role:"alert","aria-live":"assertive",className:"lk-alert",children:[m,(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>{k()},children:"Retry"})]}):0===o.length?(0,n.jsx)("div",{"data-testid":"review-queue-empty",className:"lk-empty",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"lk-empty-title",children:"Queue is clear"}),(0,n.jsx)("p",{className:"lk-empty-body",children:"No memories are waiting for review. Proposed, conflicted, and stale memories appear here."})]})}):(0,n.jsx)("ul",{ref:y,"aria-label":"Review queue",style:{listStyle:"none",padding:0,margin:0,display:"flex",flexDirection:"column",gap:8},children:o.map(e=>(0,n.jsx)(cX,{record:e,busyAction:p[e.id]??null,rowError:g[e.id]??null,onAccept:e=>{C(e,"accept")},onReject:e=>{C(e,"reject")},onArchive:e=>{C(e,"archive")},onOpenDetail:r},e.id))})})]})}let cZ={scope:[],type:[],status:[],sensitivity:[]};function c0(){let[e,t]=(0,a.useState)({kind:"list"}),[l,s]=(0,a.useState)(cZ),[i,r]=(0,a.useState)(!0),o=(0,a.useCallback)(()=>{t({kind:"list"})},[]),c=(0,a.useCallback)(e=>{t({kind:"detail",id:e})},[]);return(0,n.jsx)("div",{className:"memoria-window",children:"list"===e.kind?(0,n.jsx)(cV,{filters:l,onFilterChange:s,onOpenDetail:c,onOpenConsolidation:()=>t({kind:"consolidation"}),onOpenReviewQueue:()=>t({kind:"reviewQueue"}),policyEnabled:i,onPolicyEnabledChange:r,showWorkspaceBackLink:!1}):"detail"===e.kind?(0,n.jsx)(cU,{id:e.id,onBack:o}):"consolidation"===e.kind?(0,n.jsx)(cw,{onBack:o,onOpenDetail:c}):(0,n.jsx)(cQ,{onBack:o,onOpenDetail:c})})}var c1=e.i(8245),c2=e.i(96688),c4=e.i(61774);function c3(e){return Array.from(e.querySelectorAll("button:not([disabled]),input:not([disabled]),[tabindex]:not([tabindex='-1'])"))}function c6({capsule:e,checked:t,disabled:a,onToggle:l}){return(0,n.jsx)("li",{className:"lk-compose-member",children:(0,n.jsxs)("label",{className:"lk-compose-member-label",children:[(0,n.jsx)("input",{type:"checkbox",checked:t,disabled:a,onChange:()=>l(e.id)}),(0,n.jsx)("span",{className:"lk-compose-member-name",title:e.displayName,children:e.displayName}),(0,n.jsx)("span",{className:"lk-badge","data-state":e.lifecycleState,children:c2.STATUS_LABELS[e.lifecycleState]})]})})}function c5({capsules:e,onCancel:t,onCreated:l,createImpl:s=lw.createCapsuleSet}){let i,r=(0,a.useId)(),o=(0,a.useId)(),c=(0,a.useId)(),d=(0,a.useRef)(null),[u,m]=(0,a.useState)(""),[h,p]=(0,a.useState)(new Set),[f,g]=(0,a.useState)(!1),[v,b]=(0,a.useState)(null);function x(e){p(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),null!==v&&b(null)}async function y(e){var t;e.preventDefault();let n=(t=h.size,0===u.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 b(n);g(!0),b(null);try{await s({displayName:u.trim(),capsuleIds:[...h]}),l()}catch(e){b((0,c4.formatError)(e))}finally{g(!1)}}(0,c1.useModalInteractionLock)(),(0,a.useEffect)(()=>{let e=document.activeElement,t=d.current;return null!==t&&c3(t)[0]?.focus(),()=>e?.focus?.()},[d]),(0,a.useEffect)(()=>{let e=d.current;if(null!==e)return e.addEventListener("keydown",n),()=>e.removeEventListener("keydown",n);function n(n){if("Escape"===n.key&&!f){n.preventDefault(),t();return}if("Tab"!==n.key)return;let a=c3(e);if(0===a.length)return void n.preventDefault();let l=a[0],s=a[a.length-1];n.shiftKey&&document.activeElement===l?(n.preventDefault(),s?.focus()):n.shiftKey||document.activeElement!==s||(n.preventDefault(),l?.focus())}},[d,f,t]),i=(0,a.useRef)(!1),(0,a.useEffect)(()=>{let e=d.current;null!==e&&(f?(i.current=!0,e.focus()):i.current&&(i.current=!1,c3(e)[0]?.focus()))},[d,f]);let w="Set name is required."===v,j="Select at least one capsule to combine."===v;return(0,tA.createPortal)((0,n.jsx)("div",{className:"mc-dialog-backdrop",role:"presentation",children:(0,n.jsxs)("div",{ref:d,className:"mc-dialog",role:"dialog","aria-modal":"true","aria-labelledby":r,tabIndex:-1,children:[(0,n.jsx)("h2",{id:r,className:"mc-dialog-title",children:"Combine capsules into a set"}),(0,n.jsxs)("form",{onSubmit:e=>void y(e),children:[(0,n.jsxs)("label",{className:"mc-dialog-field",htmlFor:o,children:[(0,n.jsx)("span",{className:"mc-dialog-label",children:"Set name"}),(0,n.jsx)("input",{id:o,className:"mc-dialog-input",value:u,disabled:f,autoComplete:"off","aria-invalid":w,"aria-describedby":w?c:void 0,onChange:e=>{m(e.target.value),null!==v&&b(null)}})]}),(0,n.jsxs)("fieldset",{className:"lk-compose-fieldset",disabled:f,"aria-invalid":j,"aria-describedby":j?c:void 0,children:[(0,n.jsxs)("legend",{className:"mc-dialog-label",children:["Capsules (",h.size.toString(),"/","16",")"]}),0===e.length?(0,n.jsx)("p",{className:"lkd-empty-note",children:"No capsules available to combine."}):(0,n.jsx)("ul",{className:"lk-compose-member-list","aria-label":"Selectable capsules",children:e.map(e=>(0,n.jsx)(c6,{capsule:e,checked:h.has(e.id),disabled:f,onToggle:x},e.id))})]}),null!==v?(0,n.jsx)("div",{id:c,role:"alert","aria-live":"assertive",className:"mc-dialog-error",children:v}):null,(0,n.jsxs)("div",{className:"mc-dialog-actions",children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",disabled:f,onClick:t,children:"Cancel"}),(0,n.jsx)("button",{type:"submit",className:"lk-btn lk-btn-primary",disabled:f,"aria-busy":f,children:f?"Combining…":"Combine"})]})]})]})}),document.body)}var c8=e.i(80010);function c7({message:e,onRetry:t,onDismiss:a}){return(0,n.jsxs)("div",{role:"alert","aria-live":"assertive",className:"lk-alert",children:[e,void 0!==t?(0,n.jsx)("button",{type:"button",onClick:t,"aria-label":"Retry loading capsules",className:"lk-alert-retry",children:"Retry"}):null,void 0!==a?(0,n.jsx)("button",{type:"button",onClick:a,"aria-label":"Dismiss error message",className:"lk-alert-retry",children:"Dismiss"}):null]})}function c9(e){return Array.from(e.querySelectorAll("button:not([disabled]),input:not([disabled]),textarea:not([disabled]),select:not([disabled]),[tabindex]:not([tabindex='-1'])"))}function de({busy:e,error:t,onCancel:l,onSubmit:s}){let i=(0,a.useId)(),r=(0,a.useId)(),o=(0,a.useId)(),c=(0,a.useId)(),d=(0,a.useRef)(null),u=(0,a.useRef)(null),m=(0,a.useRef)(null),[h,p]=(0,a.useState)(""),[f,g]=(0,a.useState)(null);(0,c1.useModalInteractionLock)(),(0,a.useEffect)(()=>(m.current=document.activeElement,u.current?.focus(),()=>{m.current?.focus?.()}),[]),(0,a.useEffect)(()=>{let t=d.current;if(null===t)return;let n=n=>{if("Escape"===n.key&&!e){n.preventDefault(),l();return}if("Tab"!==n.key)return;let a=c9(t);if(0===a.length)return void n.preventDefault();let s=a[0],i=a[a.length-1];n.shiftKey&&document.activeElement===s?(n.preventDefault(),i?.focus()):n.shiftKey||document.activeElement!==i||(n.preventDefault(),s?.focus())};return t.addEventListener("keydown",n),()=>t.removeEventListener("keydown",n)},[e,l]);let v=(0,a.useRef)(!1);async function b(e){e.preventDefault();let t=h.trim();0===t.length?g("Capsule display name is required."):(g(null),await s(t))}(0,a.useEffect)(()=>{let t=d.current;null!==t&&(e?(v.current=!0,t.focus()):v.current&&(v.current=!1,c9(t)[0]?.focus()))},[e]);let x=f??t;return(0,tA.createPortal)((0,n.jsx)("div",{className:"mc-dialog-backdrop",role:"presentation",children:(0,n.jsxs)("div",{ref:d,className:"mc-dialog",role:"dialog","aria-modal":"true","aria-labelledby":i,"aria-describedby":r,tabIndex:-1,children:[(0,n.jsx)("h2",{id:i,className:"mc-dialog-title",children:"Create capsule"}),(0,n.jsx)("p",{id:r,className:"mc-dialog-body",children:"Name the capsule. After creating it, connect a source and start indexing from the capsule page."}),(0,n.jsxs)("form",{onSubmit:e=>void b(e),children:[(0,n.jsxs)("label",{className:"mc-dialog-field",htmlFor:o,children:[(0,n.jsx)("span",{className:"mc-dialog-label",children:"Capsule display name"}),(0,n.jsx)("input",{id:o,ref:u,className:"mc-dialog-input",value:h,disabled:e,autoComplete:"off","aria-invalid":null!==x,"aria-describedby":null!==x?c:void 0,onChange:e=>{p(e.target.value),null!==f&&g(null)}})]}),null!==x?(0,n.jsx)("div",{id:c,role:"alert","aria-live":"assertive",className:"mc-dialog-error",children:x}):null,(0,n.jsxs)("div",{className:"mc-dialog-actions",children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",disabled:e,onClick:l,children:"Cancel"}),(0,n.jsx)("button",{type:"submit",className:"lk-btn lk-btn-primary",disabled:e,children:e?"Creating…":"Create capsule"})]})]})]})}),document.body)}function dt({capsuleName:e,onCancel:t,onConfirm:l}){let s=(0,a.useId)(),i=(0,a.useId)(),r=(0,a.useRef)(null);return(0,c1.useModalInteractionLock)(),(0,a.useEffect)(()=>{let e=document.activeElement,t=r.current;return null!==t&&c9(t)[0]?.focus(),()=>e?.focus?.()},[]),(0,a.useEffect)(()=>{let e=r.current;if(null===e)return;let n=n=>{if("Escape"===n.key){n.preventDefault(),t();return}if("Tab"!==n.key)return;let a=c9(e);if(0===a.length)return void n.preventDefault();let l=a[0],s=a[a.length-1];n.shiftKey&&document.activeElement===l?(n.preventDefault(),s?.focus()):n.shiftKey||document.activeElement!==s||(n.preventDefault(),l?.focus())};return e.addEventListener("keydown",n),()=>e.removeEventListener("keydown",n)},[t]),(0,tA.createPortal)((0,n.jsx)("div",{className:"mc-dialog-backdrop",role:"presentation",children:(0,n.jsxs)("div",{ref:r,className:"mc-dialog",role:"dialog","aria-modal":"true","aria-labelledby":s,"aria-describedby":i,tabIndex:-1,children:[(0,n.jsx)("h2",{id:s,className:"mc-dialog-title",children:"Disconnect capsule"}),(0,n.jsxs)("p",{id:i,className:"mc-dialog-body",children:['Disconnect "',e,'"? The capsule keeps its index, but the source link is removed.']}),(0,n.jsxs)("div",{className:"mc-dialog-actions",children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:t,children:"Cancel"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-danger",onClick:l,children:"Disconnect"})]})]})}),document.body)}function dn({state:e}){return(0,n.jsx)("span",{className:"lk-badge","data-state":e,children:c2.STATUS_LABELS[e]})}function da({capsule:e,busy:t,busyKind:l,onStart:s,onCancel:i}){let{id:r,displayName:o,lifecycleState:c,sourceCount:d}=e,u=(0,a.useId)();if("indexing"===c)return(0,n.jsx)("button",{type:"button",disabled:t,"aria-busy":"cancel"===l,"aria-label":`Cancel indexing for capsule ${o}`,onClick:()=>{i(r)},className:"lk-btn lk-btn-ghost",children:"cancel"===l?"Cancelling…":"Cancel"});let m=d>0;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",disabled:t,"aria-disabled":!m||void 0,"aria-busy":"index"===l,"aria-label":`Start indexing capsule ${o}`,"aria-describedby":m?void 0:u,title:m?void 0:"Attach a source before indexing this capsule.",onClick:()=>{m&&s(r)},className:"lk-btn lk-btn-primary",children:"index"===l?"Indexing…":"Index"}),m?null:(0,n.jsx)("span",{id:u,className:"visually-hidden",children:"Attach a source before indexing."})]})}function dl({capsule:e,busy:t,busyKind:a,onStart:l,onCancel:s,onDisconnect:i,onHealth:r,onAddToWorkspace:o}){let{id:c,displayName:d}=e;return(0,n.jsxs)("div",{role:"group","aria-label":`Actions for capsule ${d}`,className:"lk-capsule-actions",children:[(0,n.jsx)(da,{capsule:e,busy:t,busyKind:a,onStart:l,onCancel:s}),(0,n.jsx)("button",{type:"button",disabled:t,"aria-label":`Add capsule ${d} to workspace`,onClick:()=>{o(c)},className:"lk-btn lk-btn-ghost",children:"Add to workspace"}),(0,n.jsx)("button",{type:"button",disabled:t,"aria-label":`Open details for capsule ${d}`,onClick:()=>{r(c)},className:"lk-btn lk-btn-ghost",children:"Details"}),(0,n.jsx)("button",{type:"button",disabled:t,"aria-busy":"disconnect"===a,"aria-label":`Disconnect capsule ${d}`,onClick:()=>{i(c)},className:"lk-btn lk-btn-danger",children:"disconnect"===a?"Disconnecting…":"Disconnect"})]})}function ds(e){return e instanceof Element&&null!==e.closest(".lk-capsule-actions,a,input,select,textarea")}function di(e,t){let n=document.elementFromPoint(e,t);return n instanceof Element&&null!==n.closest("main.workspace")&&null===n.closest(".window")}function dr(e,t){let n={payload:e,clientX:t.clientX,clientY:t.clientY};window.dispatchEvent(new CustomEvent(ti,{detail:n}))}function dc({capsule:e,busy:t,busyKind:l,onStart:s,onCancel:i,onDisconnect:r,onHealth:o,onAddToWorkspace:c}){let[d,u]=(0,a.useState)(null),m=(0,a.useRef)(!1),h=(0,a.useRef)(!1),p={kind:"capsule",id:e.id,label:e.displayName,lifecycleState:e.lifecycleState},f=e=>{h.current||(h.current=!0,dr(p,e),window.setTimeout(()=>{h.current=!1},250))},g=(t,n)=>{m.current=!0;let a=!1,l=l=>{let s=l.clientX-t,i=l.clientY-n;!a&&6>Math.hypot(s,i)||(a=!0,document.body.style.cursor="grabbing",u({x:l.clientX,y:l.clientY,label:e.displayName,state:e.lifecycleState}))},s=e=>{window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",s),window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",s),m.current=!1,document.body.style.cursor="",u(null),a&&di(e.clientX,e.clientY)&&f(e)};window.addEventListener("pointermove",l),window.addEventListener("pointerup",s),window.addEventListener("mousemove",l),window.addEventListener("mouseup",s)};return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("article",{"aria-label":`Capsule: ${e.displayName}`,className:"lk-capsule-row",children:[(0,n.jsxs)("button",{type:"button",className:"lk-capsule-drag-handle","aria-label":`Drag capsule ${e.displayName} to workspace`,title:"Drag to the workspace to create a connector card",onPointerDown:e=>{ds(e.target)||B(e)&&(e.preventDefault(),e.stopPropagation(),g(e.clientX,e.clientY))},onMouseDown:e=>{m.current||ds(e.target)||B(e)&&(e.preventDefault(),e.stopPropagation(),g(e.clientX,e.clientY))},onDragStart:t=>{ds(t.target)?t.preventDefault():(t.dataTransfer.effectAllowed="copy",t.dataTransfer.setData(ts,JSON.stringify(p)),t.dataTransfer.setData("text/plain",e.displayName))},onDragEnd:e=>{di(e.clientX,e.clientY)&&f(e)},draggable:!0,children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"lk-capsule-icon",children:"⬡"}),(0,n.jsxs)("span",{className:"lk-capsule-info",children:[(0,n.jsx)("span",{className:"lk-capsule-name",title:e.displayName,children:e.displayName}),(0,n.jsx)(dn,{state:e.lifecycleState})]})]}),(0,n.jsx)(dl,{capsule:e,busy:t,busyKind:l,onStart:s,onCancel:i,onDisconnect:r,onHealth:o,onAddToWorkspace:c})]}),null!==d?(0,tA.createPortal)((0,n.jsxs)("div",{className:"lk-connector-drag-ghost",style:{left:d.x+14,top:d.y+14},"aria-hidden":"true",children:[(0,n.jsx)("span",{className:"lk-connector-drag-ghost-icon",children:"▣"}),(0,n.jsxs)("span",{className:"lk-connector-drag-ghost-copy",children:[(0,n.jsx)("span",{children:d.label}),(0,n.jsx)("small",{children:c2.STATUS_LABELS[d.state]})]})]}),document.body):null]})}function dd({creating:e,onCreateCapsule:t}){return(0,n.jsxs)("div",{"data-testid":"empty-state",className:"lk-empty",children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"lk-empty-icon",children:"⬡"}),(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"lk-empty-title",children:"No capsules yet"}),(0,n.jsx)("p",{className:"lk-empty-body",children:"Create a capsule to start indexing your local knowledge sources."})]}),(0,n.jsx)("button",{type:"button",disabled:e,"aria-label":"Create your first knowledge capsule",onClick:t,className:"lk-btn lk-btn-primary lk-btn-xl",children:e?"Creating…":"Create your first capsule"})]})}function du({capsules:e,isLoading:t,creating:a,actionBusy:l,actionKind:s,onCreateCapsule:i,onStartIndexing:r,onCancelIndexing:o,onDisconnect:c,onOpenHealth:d}){return t?(0,n.jsx)("p",{role:"status","aria-live":"polite",className:"lk-loading",children:"Loading capsules…"}):0===e.length?(0,n.jsx)(dd,{creating:a,onCreateCapsule:i}):(0,n.jsx)("ul",{"aria-label":"Knowledge capsule list",style:{display:"flex",flexDirection:"column",gap:8,listStyle:"none",padding:0,margin:0},children:e.map(e=>(0,n.jsx)("li",{style:{display:"block"},children:(0,n.jsx)(dc,{capsule:e,busy:l===e.id,busyKind:l===e.id?s:null,onStart:r,onCancel:o,onDisconnect:c,onHealth:d,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&&dr({kind:"capsule",id:e.id,label:e.displayName,lifecycleState:e.lifecycleState},t)}})},e.id))})}function dm({creating:e,createDialogOpen:t,combineDialogOpen:l,combineDisabled:s,showBackToWorkspace:i,loadStatus:r,loadError:o,actionError:c,createError:d,reload:u,onCreateCapsule:m,onCombineCapsules:h,onDismissCreateError:p,onDismissActionError:f}){let g=(0,a.useId)();return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("header",{className:"lk-header",children:[(0,n.jsx)("h1",{className:"lk-title",children:"Local Knowledge Connector"}),(0,n.jsxs)("div",{className:"lk-header-actions",children:[i?(0,n.jsx)(cc.default,{href:"/",className:"lk-btn lk-btn-ghost lk-btn-lg",children:"Back to Workspace"}):null,(0,n.jsx)("button",{type:"button","aria-disabled":s,"aria-describedby":s?g:void 0,"aria-label":"Combine capsules into a set","aria-haspopup":"dialog","aria-expanded":l,title:s?"Create capsules first, then combine them into a set.":void 0,onClick:()=>{s||h()},className:"lk-btn lk-btn-ghost lk-btn-lg",children:"Combine capsules"}),s?(0,n.jsx)("span",{id:g,className:"visually-hidden",children:"Create capsules first, then combine them into a set."}):null,(0,n.jsx)("button",{type:"button",disabled:e,"aria-label":"Create a new knowledge capsule","aria-haspopup":"dialog","aria-expanded":t,onClick:m,className:"lk-btn lk-btn-primary lk-btn-lg",children:e?"Creating…":"Create capsule"})]})]}),"error"===r&&null!==o?(0,n.jsx)(c7,{message:o,onRetry:u}):null,null===d||t?null:(0,n.jsx)(c7,{message:d,onDismiss:p}),null!==c?(0,n.jsx)(c7,{message:c,onDismiss:f}):null]})}function dh(e){let t,l,{onOpenCapsule:s,showBackToWorkspace:i=!0}=e,[r,o]=(0,a.useState)(null),c=(0,a.useCallback)(e=>{void 0!==s?s(e):o(e)},[s]),{capsules:d,loadStatus:u,loadError:m,actionBusy:h,actionKind:p,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=lw.fetchCapsules,createCapsuleImpl:n=lw.createCapsule,startIndexingImpl:l=lw.startIndexing,cancelIndexingImpl:s=lw.cancelIndexing,disconnectCapsuleImpl:i=lw.disconnectCapsule,onOpenCapsule:r}=e,{capsules:o,loadStatus:c,loadError:d,reload:u}=function(e){let[t,n]=(0,a.useState)([]),[l,s]=(0,a.useState)("loading"),[i,r]=(0,a.useState)(null),o=(0,a.useCallback)(async()=>{s("loading"),r(null);try{let t=await e();n(t.capsules),s("ready")}catch(e){r((0,c4.formatError)(e)),s("error")}},[e]);return(0,a.useEffect)(()=>{o()},[o]),{capsules:t,loadStatus:l,loadError:i,reload:function(){o()}}}(t),{actionBusy:m,actionKind:h,actionError:p,clearActionError:f,handleStartIndexing:g,handleCancelIndexing:v,handleDisconnect:b,handleOpenHealth:x}=function(e,t,n,l,s){let i=(0,cW.useRouter)(),[r,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(null),[u,m]=(0,a.useState)(null);async function h(t,n,a){o(t),d(n),m(null);try{await a(),e()}catch(e){m((0,c4.formatError)(e))}finally{o(null),d(null)}}return{actionBusy:r,actionKind:c,actionError:u,clearActionError:function(){m(null)},handleStartIndexing:function(e){h(e,"index",()=>t(e))},handleCancelIndexing:function(e){h(e,"cancel",()=>n(e))},handleDisconnect:function(e){h(e,"disconnect",()=>l(e))},handleOpenHealth:function(e){void 0!==s?s(e):i.push(`/local-knowledge/capsule?capsuleId=${encodeURIComponent(e)}`)}}}(u,l,s,i,r),{creating:y,createError:w,clearCreateError:j,handleCreateCapsule:k}=function(e,t){let[n,l]=(0,a.useState)(!1),[s,i]=(0,a.useState)(null);return{creating:n,createError:s,clearCreateError:function(){i(null)},handleCreateCapsule:async function n(n){l(!0),i(null);try{await e({displayName:n}),t()}catch(e){i((0,c4.formatError)(e))}finally{l(!1)}}}}(n,u);return{capsules:o,loadStatus:c,loadError:d,actionBusy:m,actionKind:h,actionError:p,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,E]=(0,a.useState)(!1),[R,$]=(0,a.useState)(!1),[T,A]=(0,a.useState)(null);async function M(e){try{await S(e),E(!1)}catch{}}return null!==r&&void 0===s?(0,n.jsxs)("div",{className:"lk-page",children:[(0,n.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,n.jsx)(c8.CapsuleDetail,{capsuleId:r,onDeleted:()=>{o(null),b()}})]}):(0,n.jsxs)("div",{className:"lk-page",children:[(0,n.jsx)(dm,{creating:g,createDialogOpen:I,combineDialogOpen:R,combineDisabled:C||0===d.length,showBackToWorkspace:i,loadStatus:u,loadError:m,actionError:f,createError:v,reload:b,onCreateCapsule:()=>E(!0),onCombineCapsules:()=>$(!0),onDismissCreateError:x,onDismissActionError:y}),(0,n.jsx)("p",{role:"status",className:"visually-hidden",children:C||null!==m?null:(t=d.filter(e=>"indexing"===e.lifecycleState).length,l=`${d.length.toString()} capsule${1===d.length?"":"s"}`,t>0?`${l}, ${t.toString()} indexing`:l)}),(0,n.jsxs)("section",{"aria-label":"Knowledge capsules","aria-busy":C,style:{flex:1,minHeight:0,overflowY:"auto"},children:[(0,n.jsx)("h2",{className:"lk-section-head",children:"Knowledge Capsules"}),(0,n.jsx)(du,{capsules:d,isLoading:C,creating:g,actionBusy:h,actionKind:p,onCreateCapsule:()=>E(!0),onStartIndexing:w,onCancelIndexing:j,onDisconnect:e=>A(d.find(t=>t.id===e)??null),onOpenHealth:N})]}),I?(0,n.jsx)(de,{busy:g,error:v,onCancel:()=>{E(!1),x()},onSubmit:M}):null,R?(0,n.jsx)(c5,{capsules:d,onCancel:()=>$(!1),onCreated:function(){$(!1),b()}}):null,null!==T?(0,n.jsx)(dt,{capsuleName:T.displayName,onCancel:()=>A(null),onConfirm:()=>{k(T.id),A(null)}}):null]})}function dp(e,t){let n=e[t];return"string"==typeof n?n:void 0}function df({cfg:e,ctx:t}){let l=nJ({autoCreate:!1}),i=(0,a.useRef)(!1),r=dp(e,"chatId"),o=dp(e,"title"),{updateCfg:c}=t,{activeChat:d,chats:u,loading:m,openChat:h,openNewChat:p}=l,f=void 0!==d&&"closed"!==d.status?d:void 0;(0,a.useEffect)(()=>{if(!m){if(void 0!==r){if(f?.id===r)return;let e=u.find(e=>e.id===r&&"closed"!==e.status);void 0!==e&&h(e);return}i.current||(i.current=!0,p(void 0,o).then(e=>{void 0!==e&&c({chatId:e.id,title:e.title})}).finally(()=>{i.current=!1}))}},[r,f?.id,u,m,h,p,o,c]);let g=void 0!==r&&!l.loading&&f?.id!==r&&!l.chats.some(e=>e.id===r&&"closed"!==e.status),v=l.loading||void 0!==r&&f?.id!==r;return(0,n.jsx)(s,{value:l,children:g?(0,n.jsxs)("div",{className:"lk-empty",children:[(0,n.jsx)("p",{className:"lk-empty-title",children:"Chat not found"}),(0,n.jsx)("p",{className:"lk-empty-body",children:"This conversation was deleted or is no longer available."})]}):v?(0,n.jsx)("div",{className:"lk-loading",children:"Opening chat..."}):(0,n.jsx)(lQ,{mini:!0===t.mini,linkedRoot:t.linkedRoot})})}I("chat",(e,t)=>(0,n.jsx)(df,{cfg:e,ctx:t})),I("chatHistory",(e,t)=>(0,n.jsx)(l4,{openChatWindow:e=>{t.openWindow("chat",{chatId:e.id,title:e.title})}})),I("project",()=>(0,n.jsx)(l2,{})),I("search",()=>(0,n.jsx)(l3,{})),I("plugins",()=>(0,n.jsx)(l7,{})),I("automations",()=>(0,n.jsx)(sa,{})),I("mobile",()=>(0,n.jsx)(sl,{})),I("inspector",()=>(0,n.jsx)(ss,{})),I("notifications",()=>(0,n.jsx)(sr,{})),I("resources",()=>(0,n.jsx)(so,{})),I("activity",()=>(0,n.jsx)(su,{})),I("keiko",()=>(0,n.jsx)(iu,{})),I("settings",()=>(0,n.jsx)(ib,{})),I("localKnowledge",()=>(0,n.jsx)(dh,{showBackToWorkspace:!1})),I("quality",(e,t)=>(0,n.jsx)(rD,{openRun:(e,n)=>{let a=void 0!==n?{[ry]:JSON.stringify(n.filter(rk))}:rN(rE({connectedFilePath:t.linkedFilePath??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:t.linkedFilePath??null,connectedRoots:t.linkedRoots,connectedCapsuleIds:t.linkedCapsuleIds,connectedCapsuleSetIds:t.linkedCapsuleSetIds,connectedFigmaSnapshotRunIds:t.linkedFigmaSnapshotRunIds,connectedFigmaSnapshotSources:t.linkedFigmaSnapshotSources,connectedImageSources:t.linkedImageSources})),I("qiRun",(e,t)=>{let a=dp(e,"runId");if(void 0===a||""===a)return(0,n.jsx)("div",{className:"lk-empty",children:(0,n.jsx)("p",{className:"lk-empty-body",children:"Open a run from the Quality Intelligence hub."})});let l=function(e){let t=rw(e,ry);if(void 0!==t&&t.length>0){let e=function(e){try{let t=JSON.parse(e);if(!Array.isArray(t)||!t.every(rk))return null;return t}catch{return null}}(t);if(null!==e)return e}return rE({connectedFilePath:rw(e,"connectedFilePath")??null,connectedRoot:rw(e,"connectedRoot")??null})}(e),s=rN(l);return(0,n.jsx)(oy,{runId:a,connectedSources:l,onRegenerated:e=>{t.openWindow("qiRun",{runId:e.runId,...s})}})}),I("relationships",()=>(0,n.jsx)(co,{})),I("files",(e,t)=>{let a=dp(e,"root"),l=(e,n,a)=>{let l={activeFilePath:e??void 0,resolvedRoot:n??void 0};void 0!==a&&(l.activeDirectoryPath=a??void 0),t.updateCfg(l)},s=e=>{t.updateCfg({root:e,activeFilePath:void 0,activeDirectoryPath:void 0,resolvedRoot:void 0})},i=(e,n)=>{t.openWindow("editor",{root:e,file:n})};return void 0!==a?(0,n.jsx)(sS,{root:a,onActiveFileChange:l,onRootChange:s,onOpenFile:i}):(0,n.jsx)(sS,{onActiveFileChange:l,onRootChange:s,onOpenFile:i})}),I("editor",e=>{let t=dp(e,"root"),a=dp(e,"file"),l={};return void 0!==t&&(l.root=t),void 0!==a&&(l.file=a),(0,n.jsx)(sE,{...l})}),I("browser",e=>{let t=dp(e,"url");return void 0!==t&&""!==t?(0,n.jsx)(sF,{url:t}):(0,n.jsx)(sF,{})}),I("terminal",e=>{let t=dp(e,"cwd"),a=dp(e,"projectPath"),l={};return void 0!==t&&(l.cwd=t),void 0!==a&&(l.projectPath=a),(0,n.jsx)(sW,{...l})}),I("review",(e,t)=>{let a=dp(e,"runId"),l=e=>{t.updateCfg({runId:e})};return void 0!==a&&""!==a?(0,n.jsx)(s1,{runId:a,onRunIdSubmit:l}):(0,n.jsx)(s1,{onRunIdSubmit:l})}),I("agents",(e,t)=>{var a;let l,s,i,r,o,c,d,u,m,h,p;return(0,n.jsx)(s8,{cfg:(i={},void 0!==(r=dp(a=e,"workflow"))&&(i.workflow=r),void 0!==(o=dp(a,"model"))&&(i.model=o),void 0!==(c=dp(a,"runId"))&&(i.runId=c),void 0!==(d=dp(a,"fingerprint"))&&(i.fingerprint=d),void 0!==(u=dp(a,"workspaceRoot"))&&(i.workspaceRoot=u),void 0!==(m=dp(a,"inputJson"))&&(i.inputJson=m),void 0!==(h="boolean"==typeof(l=a.keikoMode)?l:void 0)&&(i.keikoMode=h),void 0!==(p="ask"===(s=a.access)||"full"===s?s:void 0)&&(i.access=p),i),linkedRoot:t.linkedRoot,linkedFilePath:t.linkedFilePath})}),I("memoria",()=>(0,n.jsx)(c0,{})),I("integ",()=>(0,n.jsx)(s9,{})),I("figma",(e,t)=>{let a=dp(e,"snapshotRunId"),l=function(e,t){let n=dp(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[]}}(e,"selectedScreenIdsJson"),s=dp(e,"selectedScreenName");return(0,n.jsx)(iV,{sourceWindowId:t.windowId,snapshotRunId:a,selectedScreenIds:l,selectedScreenName:s,openScreenSource:({snapshotRunId:e,screenId:n,name:a})=>{t.openWindow("figma",{snapshotRunId:e,selectedScreenIdsJson:JSON.stringify([n]),selectedScreenName:a})},updateCfg:e=>{t.updateCfg(e)}})}),I("figmaJson",e=>{let t=dp(e,"snapshotRunId"),a=dp(e,"screenId"),l=dp(e,"selectedScreenName");return(0,n.jsx)(iX,{snapshotRunId:t,screenId:a,screenName:l})}),I("figmaImage",e=>{let t=dp(e,"imageSrc"),a=dp(e,"selectedScreenName");return(0,n.jsx)(iQ,{imageSrc:t,screenName:a})}),I("connector",(e,t)=>{let a=dp(e,"presentation"),l=dp(e,"selectedKind"),s=dp(e,"selectedId"),i=dp(e,"selectedLabel"),r=dp(e,"selectedState");return(0,n.jsx)(iS,{presentation:a,selectedKind:l,selectedId:s,selectedLabel:i,selectedState:r,onSelect:e=>{t.updateCfg(e)},onManageConnectors:()=>{t.openWindow("localKnowledge")}})});let dg={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 dv(){let{available:e,triggerInstall:t}=function(){let[e,t]=(0,a.useState)(!1),n=(0,a.useRef)(null);return(0,a.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))},a=()=>{localStorage.setItem("keiko.pwa.installed","true"),n.current=null,t(!1)};return window.addEventListener("beforeinstallprompt",e,{passive:!1}),window.addEventListener("appinstalled",a),()=>{window.removeEventListener("beforeinstallprompt",e),window.removeEventListener("appinstalled",a)}},[]),{available:e,triggerInstall:(0,a.useCallback)(async()=>{let e=n.current;if(null===e)return;await e.prompt();let{outcome:a}=await e.userChoice;"accepted"===a&&localStorage.setItem("keiko.pwa.installed","true"),n.current=null,t(!1)},[])}}(),[l,s]=(0,a.useState)(!1),[i]=(0,a.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"}),r=(0,a.useRef)(null),o=(0,a.useCallback)(()=>{localStorage.setItem("keiko.pwa.dismissed",new Date().toISOString()),s(!0)},[]),c=(0,a.useCallback)(async()=>{await t()},[t]),d=(0,a.useCallback)(e=>{"Escape"!==e.key||e.defaultPrevented||o()},[o]);if(l||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"===i&&!e||"supported"!==i&&"ios-add-to-home"!==i)return null;let u=dg[i];return(0,n.jsx)("aside",{className:"install-banner",role:"region","aria-label":"Install Keiko",onKeyDown:d,children:(0,n.jsxs)("div",{className:"install-banner-body",children:[(0,n.jsxs)("div",{className:"install-banner-text",children:[(0,n.jsx)("span",{className:"install-banner-heading",children:u.heading}),(0,n.jsx)("span",{className:"install-banner-desc",children:u.body})]}),(0,n.jsxs)("div",{className:"install-banner-actions",children:[null!==u.install&&(0,n.jsx)("button",{ref:r,type:"button",className:"install-banner-btn-install",onClick:()=>void c(),children:u.install}),(0,n.jsx)("button",{type:"button",className:"install-banner-btn-dismiss",onClick:o,children:"Not now"})]})]})})}function db(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")}let dx=["chat","connector","figma","files"],dy=["chatHistory","memoria","settings","automations","mobile","inspector","activity","notifications","resources","localKnowledge","quality","relationships"];function dw(){var e,t,l;let i,{theme:r,toggle:o}=function(){let[e,t]=(0,a.useState)(nV),[n,l]=(0,a.useState)(!1);return(0,a.useEffect)(()=>{t(function(){try{let e=window.localStorage.getItem(nG);return"light"===e||"dark"===e?e:nV}catch{return nV}}()),l(!0)},[]),(0,a.useEffect)(()=>{if(n){"u">typeof document&&(document.documentElement.dataset.theme=e);try{window.localStorage.setItem(nG,e)}catch{}}},[e,n]),{theme:e,toggle:(0,a.useCallback)(()=>{t(e=>"light"===e?"dark":"light")},[])}}(),c=x(),d=nJ({autoCreate:!1}),u=(0,a.useRef)(null),m=(0,a.useRef)(null),[h,p]=(0,a.useState)(nX.DEFAULT_GROUNDING_LIMITS);(0,a.useEffect)(()=>{(0,w.fetchConfig)().then(e=>p(e.effectiveGroundingLimits)).catch(()=>void 0)},[]);let[f,g]=(0,a.useState)(null);(0,a.useEffect)(()=>{if(null===f)return;let e=window.setTimeout(()=>g(null),1e4);return()=>window.clearTimeout(e)},[f]);let v=(0,a.useCallback)((e,t)=>(g(`Source limit reached — this chat already has ${String(e)} of ${String(t)} connected sources. Disconnect a source before connecting another.`),!1),[]),b=(0,a.useCallback)(e=>(g(e),!1),[]),j=(0,a.useCallback)(e=>{let t=function(e){if(e?.type!=="chat")return;let t=e.cfg.chatId;return"string"==typeof t&&t.length>0?t:void 0}(m.current?.find(t=>t.id===e));if(void 0===t)return;let n=d.chats.find(e=>e.id===t)??(d.activeChat?.id===t?d.activeChat:void 0);return n?.status==="closed"?void 0:n},[d.activeChat,d.chats]),k=(0,a.useCallback)(async(e,t,n=null)=>{var a;let l=j(e);if(void 0===l)return b("Open a ready chat window before connecting a source.");let s=null===n?e0(l):eZ(e0(l),n),i=e1(l);if(s.some(e=>eG(e,t))){if(null!==n){let e=await (0,w.updateChatConnectedScopes)(l.id,s.length>0?s:null);d.replaceChat(e.chat)}return!0}let r=eQ(h);if(s.length+i.length>=r)return v(s.length+i.length,r);let o={...t,connectedAtMs:Date.now()},c=function(e,t,n=16){if(void 0===t.root)return null;let a=eH(t.root);if(!eW(a))return null;let l=t.relativePaths.map(eJ),s={kind:t.kind,relativePaths:l,root:a,connectedAtMs:t.connectedAtMs};return e.some(e=>eG(e,s))||e.length>=n?e:[...e,s]}(s,o,h.maxConnectedSources);if(null===c)return b("Choose a local folder before connecting it to chat.");if(c===s)return v(s.length+i.length,r);try{let e=await (0,w.updateChatConnectedScopes)(l.id,c);d.replaceChat(e.chat),g(null);let t=function(e){if(void 0===e.root)return null;let t=e.relativePaths[0]?.replace(/\\/gu,"/").replace(/^\/+/u,"");if(void 0===t||0===t.length)return e.root;let n=e.root.replace(/\\/gu,"/").replace(/\/+$/u,"");return`${n}/${t}`}(o);return null!==t&&(a=l.id,0!==a.length&&0!==t.length&&n9({type:"reads-context",source:{kind:"chat",id:a},target:{kind:"workspace-path",id:t}},function(e,t){let n=0x811c9dc5,a=`${e}|${t}`;for(let e=0;e<a.length;e+=1)n=Math.imul(n^a.charCodeAt(e),0x1000193);return`rc-${(n>>>0).toString(36)}-${(65535&a.length).toString(36)}`}(a,t)).catch(e=>{})),!0}catch{return b("Keiko could not connect that source. Check that it is still available and try again.")}},[j,d,h,v,b]),N=function(e,t={}){var n,l,s,i,r,o,c,d,u;let[m,h]=(0,a.useState)(null),[p,f]=(0,a.useState)(null),[g,v]=(0,a.useState)(!1),[b,x]=(0,a.useState)([]),[y,w]=(0,a.useState)(null),[j,k]=(0,a.useState)(e7),N=(0,a.useRef)(3),S=(0,a.useRef)(null),C=(0,a.useRef)([]);C.current=m??[];let I=(0,a.useRef)([]);I.current=b;let R=(0,a.useRef)(null);R.current=y;let T=(0,a.useRef)(null),M=(0,a.useRef)(()=>void 0),{viewRef:L,worldVP:q,zoomTo:P,fitView:D,resetView:F,panBy:z,rect:O}=function({wsRef:e,view:t,winsRef:n,setView:l,setWins:s}){let i=(0,a.useRef)(t);i.current=t;let r=(0,a.useRef)(null),o=(0,a.useRef)(null);(0,a.useEffect)(()=>{tn(e8,t)},[t]),(0,a.useEffect)(()=>()=>{null!==o.current&&"function"==typeof window.cancelAnimationFrame&&window.cancelAnimationFrame(o.current)},[]);let c=(0,a.useCallback)(e=>{let t=r.current??i.current,n="function"==typeof e?e(t):e;if(i.current=n,r.current=n,"function"!=typeof window.requestAnimationFrame||"function"!=typeof window.cancelAnimationFrame){r.current=null,l(n);return}null===o.current&&(o.current=window.requestAnimationFrame(()=>{o.current=null;let e=r.current;r.current=null,null!==e&&l(e)}))},[l]);(0,a.useEffect)(()=>{let t=e.current;if(null===t)return;let n=e=>{if(e.metaKey||e.ctrlKey){var n;e.preventDefault();let a=(n=e.target)instanceof Element?n.closest(".window[data-window-id]")?.dataset.windowId??null:null;if(null!==a)return void s(t=>null===t?t:t.map(t=>{var n,l;let s,i;return t.id===a?(n=t,l=e.deltaY,(i=te((s=n.zoom??1)*Math.exp(-(.0015*l))))===s?n:{...n,zoom:i}):t}));let l=t.getBoundingClientRect(),r=i.current,o=ta(e),d=e9(r.zoom*Math.exp(-(.0015*o.y))),u=(e.clientX-l.left-r.x)/r.zoom,m=(e.clientY-l.top-r.y)/r.zoom;return void c({zoom:d,x:e.clientX-l.left-u*d,y:e.clientY-l.top-m*d})}let a=e.target;if(a instanceof Element&&null!==a.closest(".window"))return;e.preventDefault();let l=ta(e);c(e=>({...e,x:e.x-l.x,y:e.y-l.y}))};return t.addEventListener("wheel",n,{passive:!1}),()=>{t.removeEventListener("wheel",n)}},[e,s,c]);let d=(0,a.useCallback)(()=>null===e.current?null:e.current.getBoundingClientRect(),[e]),u=(0,a.useCallback)(()=>{let e=d();if(null===e)return null;let t=i.current;return{x:-t.x/t.zoom,y:-t.y/t.zoom,w:e.width/t.zoom,h:e.height/t.zoom}},[d]),m=(0,a.useCallback)(e=>{let t=d();if(null===t)return;let n=i.current,a=t.width/2,l=t.height/2,s=(a-n.x)/n.zoom,r=(l-n.y)/n.zoom,o=e9(e);c({zoom:o,x:a-s*o,y:l-r*o})},[d,c]),h=(0,a.useCallback)(()=>{let e=d();null!==e&&c(function(e,t){let n=e.filter(e=>!0!==e.minimized);if(0===n.length)return{zoom:1,x:0,y:0};let a=1/0,l=1/0,s=-1/0,i=-1/0;for(let e of n)a=Math.min(a,e.x),l=Math.min(l,e.y),s=Math.max(s,e.x+e.w),i=Math.max(i,e.y+e.h);let r=Math.max(1,s-a),o=Math.max(1,i-l),c=e9(Math.min(1,Math.max(1,t.width-144)/r,Math.max(1,t.height-144)/o)),d=a+r/2,u=l+o/2;return{zoom:c,x:Math.round(t.width/2-d*c),y:Math.round(t.height/2-u*c)}}(n.current,e))},[d,n,c]);return{viewRef:i,worldVP:u,zoomTo:m,fitView:h,resetView:(0,a.useCallback)(()=>c({zoom:1,x:0,y:0}),[c]),panBy:(0,a.useCallback)((e,t)=>c(n=>({...n,x:n.x+e,y:n.y+t})),[c]),rect:d}}({wsRef:e,view:j,winsRef:C,setView:k,setWins:h});!function({wsRef:e,setWins:t,setConns:n,zc:l}){(0,a.useLayoutEffect)(()=>{let a=e.current;if(null===a)return;a.getBoundingClientRect();let s=null;try{s=function(e){if(null===e)return null;try{let t=JSON.parse(e);if(!Array.isArray(t)||0===t.length)return null;let n=ez(t);return n.length>0?n:null}catch{return null}}(window.localStorage.getItem(e6))}catch{s=null}null===s&&(s=[]),l.current=0===s.length?1:Math.max(1,...s.map(e=>e.z)),t(s);try{n(function(e,t){if(null===e)return[];try{let n=JSON.parse(e);if(!Array.isArray(n))return[];return eO(n,t)}catch{return[]}}(window.localStorage.getItem(e5),s))}catch{}},[e,t,n,l])}({wsRef:e,setWins:h,setConns:x,zc:N}),(0,a.useEffect)(()=>{null!==m&&tn(e5,eO(b,m))},[b,m]),(0,a.useEffect)(()=>{null!==m&&x(e=>{let t=e.filter(e=>void 0!==m.find(t=>t.id===e.a)&&void 0!==m.find(t=>t.id===e.b));return t.length===e.length?e:t})},[m,x]),(0,a.useEffect)(()=>{null!==m&&tn(e6,ez(m))},[m]),function({setWins:e,rect:t,cancelConnectRef:n}){(0,a.useEffect)(()=>{let a=a=>{var l,s;if("Escape"===a.key)return void n.current();if(null!==(l=document.activeElement)&&("INPUT"===l.tagName||"TEXTAREA"===l.tagName||"SELECT"===l.tagName))return;let i=tl[a.code];if((a.metaKey||a.ctrlKey)&&a.altKey&&void 0!==i){a.preventDefault(),e(e=>{var t;if(null===e||0===e.length)return e;let n=tt(e);if(null===n)return e;let a=(t=n.zoom??1,"0"===i?1:"-"===i||"_"===i?te(t-.1):te(t+.1));return e.map(e=>e.id===n.id?{...e,zoom:a}:e)});return}if(!/^Arrow/.test(a.key))return;let r=a.metaKey||a.ctrlKey,o=a.altKey;if(!r&&!o)return;a.preventDefault();let c=t();null!==c&&(s={key:a.key,shift:a.shiftKey},e(e=>{let t,n,a,l,i,r,d;if(null===e||0===e.length)return e;let u=tt(e);if(null===u)return e;let m=o?(t=s.shift?1:16,n=u.w,a=u.h,"ArrowRight"===s.key?n+=t:"ArrowLeft"===s.key?n-=t:"ArrowDown"===s.key?a+=t:"ArrowUp"===s.key&&(a-=t),n=Math.max((l=E[u.type].min).w,Math.min(c.width,n)),a=Math.max(l.h,Math.min(c.height,a)),{x:u.x,y:u.y,w:n,h:a}):(i=s.shift?1:16,r=u.x,d=u.y,"ArrowRight"===s.key?r+=i:"ArrowLeft"===s.key?r-=i:"ArrowDown"===s.key?d+=i:"ArrowUp"===s.key&&(d-=i),{x:r=Math.max(-(u.w-120),Math.min(c.width-120,r)),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,...m,max:!1}:e)}))};return window.addEventListener("keydown",a),()=>{window.removeEventListener("keydown",a)}},[e,t,n])}({setWins:h,rect:O,cancelConnectRef:M}),function({wsRef:e,viewRef:t,setWins:n}){(0,a.useEffect)(()=>{let a=e.current;if(null===a||"u"<typeof ResizeObserver)return;let l=new ResizeObserver(()=>{let e=a.getBoundingClientRect(),l=t.current,s={x:-l.x/l.zoom,y:-l.y/l.zoom,w:e.width/l.zoom,h:e.height/l.zoom};n(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};let n=Math.max(t.x-(e.w-120),Math.min(t.x+t.w-120,e.x)),a=Math.max(t.y,Math.min(t.y+t.h-38,e.y));return n===e.x&&a===e.y?e:{...e,x:n,y:a}})(e,s)))});return l.observe(a),()=>{l.disconnect()}},[e,t,n])}({wsRef:e,viewRef:L,setWins:h});let{update:K,focus:B,close:_,minimize:U,restore:W,maximize:H,add:Y,toggleTool:J}={update:(l=(n={setWins:h,zc:N,worldVP:q}).setWins,(e,t)=>l(n=>{if(null===n)return n;let a=!1,l=n.map(n=>{if(n.id!==e)return n;for(let[e,l]of Object.entries(t))if(n[e]!==l)return a=!0,{...n,...t};return n});return a?l:n})),focus:(s=n.setWins,i=n.zc,e=>s(t=>null===t?t:t.map(t=>t.id===e?{...t,z:++i.current}:t))),close:(r=n.setWins,e=>r(t=>null===t?t:t.filter(t=>t.id!==e))),minimize:(o=n.setWins,e=>o(t=>null===t?t:t.map(t=>t.id===e?{...t,minimized:!0}:t))),restore:(c=n.setWins,d=n.zc,e=>c(t=>null===t?t:t.map(t=>t.id===e?{...t,minimized:!1,z:++d.current}:t))),maximize:function(e){let{setWins:t,zc:n,worldVP:a}=e;return e=>t(t=>{if(null===t)return t;let l=a();return null===l?t:t.map(t=>{if(t.id!==e)return t;if(t.max){var a;let e,s,i,r=t.prev??(a=t.type,s=Math.min((e=E[a]).w,Math.max(e.min.w,l.w-32)),i=Math.min(e.h,Math.max(e.min.h,l.h-32)),{x:l.x+Math.max(16,Math.round((l.w-s)/2)),y:l.y+Math.max(16,Math.round((l.h-i)/2)),w:s,h:i}),{prev:o,...c}=t;return{...c,x:r.x,y:r.y,w:r.w,h:r.h,max:!1,z:++n.current}}return{...t,max:!0,prev:{x:t.x,y:t.y,w:t.w,h:t.h},x:l.x,y:l.y,w:l.w,h:l.h,z:++n.current}})})}(n),add:function(e){let{setWins:t,zc:n,worldVP:a}=e;return(e,l)=>{let s=E[e],i="figma"===e&&"string"==typeof l?.selectedScreenIdsJson&&l.selectedScreenIdsJson.length>0,r=i?360:s.w,o=i?360:s.h,c=i?Math.max(s.min.w,300):s.min.w,d=i?Math.max(s.min.h,260):s.min.h,u=null;return t(t=>{let i=a();if(null===i)return t;let m=t??[];if(!0===s.singleton){let t=m.find(t=>t.type===e);if(void 0!==t)return u=t.id,m.map(e=>e.id===t.id?{...e,minimized:!1,z:++n.current}:e)}let h="qiRun"===e?l?.runId:void 0;if("string"==typeof h&&h.length>0){let e=m.find(e=>"qiRun"===e.type&&e.cfg.runId===h);if(void 0!==e)return u=e.id,m.map(t=>t.id===e.id?{...t,cfg:void 0===l?t.cfg:{...t.cfg,...l},minimized:!1,z:++n.current}:t)}let p="chat"===e?l?.chatId:void 0;if("string"==typeof p&&p.length>0){let e=m.find(e=>"chat"===e.type&&e.cfg.chatId===p);if(void 0!==e)return u=e.id,m.map(t=>t.id===e.id?{...t,minimized:!1,z:++n.current}:t)}let{x:f,y:g}=eK(i,r,o,m.length,40),v=!0===s.singleton?e:`${e}-${Date.now().toString(36)}`;return u=v,[...m,{id:v,type:e,x:f,y:g,w:Math.max(r,c),h:Math.max(o,d),z:++n.current,cfg:l??{},max:!1,zoom:1}]}),u}}(n),toggleTool:function(e){let{setWins:t,zc:n,worldVP:a}=e;return e=>{let l=E[e];t(t=>{let s=a();if(null===s)return t;let i=t??[],r=i.find(t=>t.type===e);if(void 0!==r&&!0===r.minimized)return i.map(e=>e.id===r.id?{...e,minimized:!1,z:++n.current}:e);if(void 0!==r)return i.filter(t=>t.type!==e);let{x:o,y:c}=eK(s,l.w,l.h,i.length,28);return[...i,{id:e,type:e,x:o,y:c,w:l.w,h:l.h,z:++n.current,cfg:{},max:!1,zoom:1}]})}}(n)},{tileAll:G,splitFront:V,cascade:X}={tileAll:function({setWins:e,worldVP:t}){return()=>e(e=>{if(null===e||0===e.length)return e;let n=t();if(null===n)return e;let a=e.length,l=Math.ceil(Math.sqrt(a)),s=Math.ceil(a/l),i=(n.w-12*(l+1))/l,r=(n.h-12*(s+1))/s;return e.map((e,t)=>{let a=Math.floor(t/l);return{...eB(e),max:!1,minimized:!1,x:n.x+12+t%l*(i+12),y:n.y+12+a*(r+12),w:i,h:r}})})}(u={setWins:h,worldVP:q}),splitFront:function({setWins:e,worldVP:t}){return()=>e(e=>{if(null===e||0===e.length)return e;let n=t();if(null===n)return e;let a=[...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 t=a.indexOf(e.id);return 0===t?{...eB(e),max:!1,minimized:!1,x:n.x,y:n.y,w:n.w/2,h:n.h}:1===t?{...eB(e),max:!1,minimized:!1,x:n.x+n.w/2,y:n.y,w:n.w/2,h:n.h}:e})})}(u),cascade:function({setWins:e,worldVP:t}){return()=>e(e=>{if(null===e)return e;let n=t();return null===n?e:e.map((e,t)=>({...eB(e),max:!1,minimized:!1,x:n.x+24+30*t,y:n.y+24+30*t,w:Math.min(560,n.w-80),h:Math.min(420,n.h-80),z:t+1}))})}(u)},{setSnap:Q,commitSnap:Z}=function({setSnapPrev:e,snapZone:t,worldVP:n,update:a}){return{setSnap:a=>{if(t.current=a,null===a)return void e(null);let l=n();null!==l&&e(A(l)[a])},commitSnap:l=>{let s=t.current;if(t.current=null,e(null),null===s)return;let i=n();if(null===i)return;let r={...A(i)[s],max:"maxi"===s};"maxi"===s&&(r.prev={x:i.x+40,y:i.y+40,w:480,h:360}),a(l,r)}}}({setSnapPrev:f,snapZone:S,worldVP:q,update:K}),{startConnect:ee,confirmConnect:et,cancelConnect:en,removeConn:ea,connect:el,linkedFilesRoot:es,linkedFilesContext:ei,linkedAllFilesRoots:er,linkedConnectorCapsuleIds:eo,linkedConnectorCapsuleSetIds:ec,linkedFigmaSnapshotRunIds:ed,linkedFigmaSnapshotSources:eu,linkedImageSources:em,currentFilesContext:eh}=function(e){let{wsRef:t,viewRef:n,winsRef:a,connsRef:l,connectingRef:s,connectCleanupRef:i,focus:r,setConns:o,setConnecting:c,onScopeBind:d,onScopeUnbind:u,onConnectorBind:m,onConnectorUnbind:h}=e,p=()=>{null!==i.current&&(i.current(),i.current=null),s.current=null,c(null)},f=e=>{if("files"!==e.type)return null;let t=e.cfg.resolvedRoot,n=e.cfg.root,a="string"==typeof t&&t.length>0?t:"string"==typeof n&&n.length>0?n:null;if(null===a||!eW(a))return null;let l=e.cfg.activeFilePath;return{id:e.id,root:a,..."string"==typeof l&&l.length>0?{activeFilePath:l}:{}}},g=e=>{let t=[];for(let n of l.current){let l=n.a===e?n.b:n.b===e?n.a:null;if(null===l)continue;let s=a.current.find(e=>e.id===l);void 0!==s&&"files"===s.type&&t.push(s)}if(0===t.length)return null;let n=[...t].sort((e,t)=>t.z-e.z),s=n.find(e=>{let t=e.cfg.activeFilePath;return"string"==typeof t&&t.length>0})??n[0];return void 0===s?null:f(s)},v=(e,t)=>{let n=new Set,s=[];for(let i of l.current){if(s.length>=16)break;let l=i.a===e?i.b:i.b===e?i.a:null;if(null===l)continue;let r=a.current.find(e=>e.id===l);if(void 0===r||"connector"!==r.type||r.cfg.selectedKind!==t)continue;let o=r.cfg.selectedId;"string"==typeof o&&0!==o.trim().length&&(n.has(o)||(n.add(o),s.push(o)))}return s},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,a)=>{if(a.preventDefault(),a.stopPropagation(),null!==s.current&&s.current.from===e)return void p();let l=t.current;if(null===l)return;let r=l.getBoundingClientRect(),o=n.current,d=e=>(e-r.left-o.x)/o.zoom,u=e=>(e-r.top-o.y)/o.zoom;null!==i.current&&(i.current(),i.current=null);let m={from:e,x:d(a.clientX),y:u(a.clientY)};s.current=m,c(m);let h=t=>{let n={from:e,x:d(t.clientX),y:u(t.clientY)};s.current=n,c(n)};window.addEventListener("pointermove",h),i.current=()=>{window.removeEventListener("pointermove",h)}},confirmConnect:(e,t)=>{t.preventDefault(),t.stopPropagation();let n=s.current;if(null===n)return;let l=a.current,i=l.find(e=>e.id===n.from),c=l.find(t=>t.id===e);if(void 0!==i&&void 0!==c&&$(i.type,c.type)){let t,l=eV(i,c,Date.now()),s=null===l?e3(i,c):null,u=null!==l||null!==s?eU(i,c):null;try{t=null!==l&&null!==u?d?.(u,l)??!0:null===s||null!==u&&(m?.(u,s)??!0)}catch{t=!1}Promise.resolve(t).then(t=>{!t||a.current.some(e=>e.id===n.from)&&a.current.some(t=>t.id===e)&&(o(t=>e_(t,n.from,e)?t:[...t,{id:`${n.from}~${e}`,a:n.from,b:e,...null!==u?{boundChatWindowId:u}:{},...null!==l?{boundRoot:l.root,boundScopeKind:l.kind,boundRelativePath:l.relativePaths[0]}:{},...null!==s?"capsule"===s.kind?{boundConnectorKind:"capsule",boundConnectorId:s.capsuleId}:{boundConnectorKind:"capsule-set",boundConnectorId:s.capsuleSetId}:{}}]),r(e))}).catch(()=>void 0)}p()},cancelConnect:p,removeConn:e=>{let t=l.current.find(t=>t.id===e);if(o(t=>t.filter(t=>t.id!==e)),void 0===t)return;let n=a.current,s=n.find(e=>e.id===t.a),i=n.find(e=>e.id===t.b),r=void 0!==s&&void 0!==i,c=t.boundChatWindowId??(r?eU(s,i):null),d=eX(t)??(r?eV(s,i,Date.now()):null);null!==d&&null!==c&&u?.(c,d);let m=e4(t)??(r?e3(s,i):null);null!==m&&null!==c&&h?.(c,m)},connect:(e,t)=>{let n=a.current,l=n.find(t=>t.id===e),s=n.find(e=>e.id===t);void 0!==l&&void 0!==s&&$(l.type,s.type)&&o(n=>e_(n,e,t)?n:[...n,{id:`${e}~${t}`,a:e,b:t}])},linkedFilesRoot:e=>g(e)?.root??null,linkedFilesContext:g,linkedAllFilesRoots:e=>{let t=new Set,n=[];for(let s of l.current){if(n.length>=16)break;let l=s.a===e?s.b:s.b===e?s.a:null;if(null===l)continue;let i=a.current.find(e=>e.id===l);if(void 0===i)continue;let r=eY(i);null===r||t.has(r)||(t.add(r),n.push(r))}return n},linkedConnectorCapsuleIds:e=>v(e,"capsule"),linkedConnectorCapsuleSetIds:e=>v(e,"capsule-set"),linkedFigmaSnapshotRunIds:e=>{let t=new Set,n=[];for(let s of l.current){if(n.length>=16)break;let l=s.a===e?s.b:s.b===e?s.a:null;if(null===l)continue;let i=a.current.find(e=>e.id===l);if(void 0===i||"figma"!==i.type&&"figmaJson"!==i.type)continue;let r=i.cfg.snapshotRunId;"string"==typeof r&&0!==r.trim().length&&(t.has(r)||(t.add(r),n.push(r)))}return n},linkedFigmaSnapshotSources:e=>{let t=new Set,n=[];for(let s of l.current){if(n.length>=16)break;let l=s.a===e?s.b:s.b===e?s.a:null;if(null===l)continue;let i=a.current.find(e=>e.id===l);if(void 0===i||"figma"!==i.type&&"figmaJson"!==i.type)continue;let r=i.cfg.snapshotRunId;if("string"!=typeof r||0===r.trim().length)continue;let o=i.cfg.selectedScreenIdsJson,c=i.cfg.selectedScreenName,d=b(i);if(("figmaJson"===i.type||void 0!==o||"string"==typeof c&&c.trim().length>0)&&0===d.length)continue;let u=`${r}:${d.join(",")||"*"}`;if(t.has(u))continue;t.add(u);let m=d.length>0&&"string"==typeof c&&c.trim().length>0?"figmaJson"===i.type?`JSON \xb7 ${c}`:c:r;n.push({kind:"figma-snapshot",label:m,snapshotRunId:r,...d.length>0?{screenIds:d}:{}})}return n},linkedImageSources:e=>{let t=new Set,n=[];for(let s of l.current){if(n.length>=16)break;let l=s.a===e?s.b:s.b===e?s.a:null;if(null===l)continue;let i=a.current.find(e=>e.id===l);if(void 0===i||"figmaImage"!==i.type)continue;let r=i.cfg.snapshotRunId,o=i.cfg.screenId;if("string"!=typeof r||0===r.trim().length||"string"!=typeof o||0===o.trim().length)continue;let c=`${r}:${o}`;if(t.has(c))continue;t.add(c);let d=i.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:r,screenId:o})}return n},currentFilesContext:()=>{let e=a.current.map(e=>f(e)).filter(e=>null!==e);if(1===e.length)return e[0]??null;let t=[...a.current].filter(e=>"files"===e.type).sort((e,t)=>t.z-e.z)[0];return void 0===t?null:f(t)}}}({wsRef:e,viewRef:L,winsRef:C,connsRef:I,connectingRef:R,connectCleanupRef:T,focus:B,setConns:x,setConnecting:w,onScopeBind:t.onScopeBind,onScopeUnbind:t.onScopeUnbind,onConnectorBind:t.onConnectorBind,onConnectorUnbind:t.onConnectorUnbind});return M.current=en,(0,a.useEffect)(()=>()=>{null!==T.current&&(T.current(),T.current=null)},[]),{wins:m,snapPrev:p,palOpen:g,setPalOpen:v,conns:b,connecting:y,view:j,api:{add:Y,toggleTool:J,focus:B,close:e=>{let n=C.current.find(t=>t.id===e);if(void 0!==n)for(let a of I.current){let l=a.a===e?a.b:a.b===e?a.a:null;if(null===l)continue;let s=C.current.find(e=>e.id===l);if(void 0===s)continue;let i=a.boundChatWindowId??("chat"===n.type?n.id:"chat"===s.type?s.id:null),r=eX(a)??eV(n,s,Date.now());null!==r&&null!==i&&t.onScopeUnbind?.(i,r);let o=e4(a)??e3(n,s);null!==o&&null!==i&&t.onConnectorUnbind?.(i,o)}_(e)},minimize:U,restore:W,maximize:H,update:K,setSnap:Q,commitSnap:Z,tileAll:G,splitFront:V,cascade:X,startConnect:ee,confirmConnect:et,cancelConnect:en,removeConn:ea,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:el,linkedFilesRoot:es,linkedFilesContext:ei,linkedAllFilesRoots:er,linkedConnectorCapsuleIds:eo,linkedConnectorCapsuleSetIds:ec,linkedFigmaSnapshotRunIds:ed,linkedFigmaSnapshotSources:eu,linkedImageSources:em,currentFilesContext:eh,zoomTo:P,fitView:D,resetView:F,panBy:z,rect:O}}}(u,{onScopeBind:(0,a.useCallback)(async(e,t)=>k(e,t),[k]),onScopeUnbind:(0,a.useCallback)((e,t)=>{let n=j(e);if(void 0===n)return;let a=eZ(e0(n),t);(0,w.updateChatConnectedScopes)(n.id,a.length>0?a:null).then(e=>{d.replaceChat(e.chat)}).catch(e=>{console.warn("[keiko] connected-scope unbind failed",e)})},[j,d]),onConnectorBind:(0,a.useCallback)(async(e,t)=>{var n;let a,l,s=j(e);if(void 0===s)return b("Open a ready chat window before connecting a source.");let i=e1(s),r=e0(s);if(a=e2(t),i.some(e=>e2(e)===a))return!0;let o=eQ(h);if(r.length+i.length>=o)return v(r.length+i.length,o);let c=(n=h.maxLocalKnowledgeSources,l=e2(t),i.some(e=>e2(e)===l)||i.length>=n?i:[...i,t]);if(c===i)return v(r.length+i.length,o);try{let e=await (0,w.updateChatLocalKnowledgeScopes)(s.id,c);return d.replaceChat(e.chat),g(null),!0}catch{return b("Keiko could not connect that knowledge source. Check that it is still available and try again.")}},[j,d,h,v,b]),onConnectorUnbind:(0,a.useCallback)((e,t)=>{var n;let a=j(e);if(void 0===a)return;let l="capsule"===t.kind?`capsule:${t.capsuleId}`:`set:${t.capsuleSetId}`,s=(n=e1(a),n.filter(e=>e2(e)!==l));(0,w.updateChatLocalKnowledgeScopes)(a.id,s.length>0?s:null).then(e=>{d.replaceChat(e.chat)}).catch(()=>void 0)},[j,d])});m.current=N.wins,(0,a.useEffect)(()=>{if(null!==N.wins)for(let e of N.conns){let t=N.wins.find(t=>t.id===e.a),n=N.wins.find(t=>t.id===e.b);if(void 0===t||void 0===n)continue;let a=e.boundChatWindowId??("chat"===t.type?t.id:"chat"===n.type?n.id:null);if(null===a)continue;let l=eV(t,n,Date.now());if(null===l)continue;let s=eX(e);db(s)!==db(l)&&k(a,l,s).then(t=>{t&&N.api.updateConnBoundScope(e.id,l)})}},[k,N.api,N.conns,N.wins]);let[S,C]=(0,a.useState)(!1),[I,R]=(0,a.useState)(null),[T,M]=(0,a.useState)(!1),[P,D]=(0,a.useState)(!1),O=N.wins?.length??0,K=function(e){if(null===e||0===e.length)return null;let t=null;for(let n=0;n<e.length;n++){let a=e[n];if(!0!==a.minimized){if(null===t){t=a;continue}a.z>t.z&&(t=a)}}return t}(N.wins),B=(0,a.useMemo)(()=>(function(e){if(null===e)return new Set;let t=new Set;for(let n of e)!0===E[n.type].tool&&t.add(n.type);return t})(N.wins),[N.wins]),_=(0,a.useMemo)(()=>({wins:N.wins??[],active:K,winCount:O}),[N.wins,K,O]),U=(0,a.useCallback)(()=>C(!0),[]),W=(0,a.useCallback)(()=>C(!1),[]),H=(0,a.useCallback)(()=>D(e=>!e),[]),Y=(0,a.useCallback)(()=>D(!1),[]),J=(0,a.useCallback)(e=>{N.api.restore(e),D(!1)},[N.api]),G=(0,a.useCallback)(e=>{C(!1),R(e)},[]),V=(0,a.useCallback)(e=>{if(R(null),null===I)return;let{__connectFilesId:t,...n}=e,a=N.api.add(I,n);"agents"===I&&null!==a&&"string"==typeof t&&t.length>0&&N.api.connect(a,t),null!==a&&requestAnimationFrame(()=>{let e=document.querySelector(`[data-window-id="${a}"]`);null===e||(e.querySelector("textarea, input, select, button, [tabindex]")??e).focus()})},[I,N.api]),X=(0,a.useCallback)(()=>R(null),[]),Q=(0,a.useCallback)(()=>M(!1),[]),Z=(0,a.useCallback)(()=>M(!0),[]),ee=(0,a.useRef)(null),et=(0,a.useCallback)(e=>{ee.current=e},[]),en=function(e){let{apply:t}=e,n=e.limit??100,[l,s]=(0,a.useState)(ad),i=(0,a.useRef)(t);i.current=t;let r=(0,a.useRef)(l);r.current=l;let o=(0,a.useCallback)(e=>{s(t=>{let a=[...t.undoStack,e];return{undoStack:a.length>n?a.slice(a.length-n):a,redoStack:[]}})},[n]),c=(0,a.useCallback)(()=>{let e=r.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);s({undoStack:e.undoStack.slice(0,-1),redoStack:[...e.redoStack,t]}),i.current(n)},[]),d=(0,a.useCallback)(()=>{let e=r.current;if(0===e.redoStack.length)return;let t=e.redoStack[e.redoStack.length-1];s({undoStack:[...e.undoStack,t],redoStack:e.redoStack.slice(0,-1)}),i.current(t)},[]),u=(0,a.useCallback)(()=>{s(ad)},[]);return(0,a.useMemo)(()=>{let e=l.undoStack[l.undoStack.length-1],t=l.redoStack[l.redoStack.length-1];return{canUndo:l.undoStack.length>0,canRedo:l.redoStack.length>0,undoLabel:void 0!==e?ao(e):null,redoLabel:void 0!==t?ao(t):null,push:o,undo:c,redo:d,clear:u}},[l,o,c,d,u])}({apply:(0,a.useCallback)(e=>{var t;return t=N.api,void("ui.panel.toggle"===e.kind&&e.panel in E&&t.toggleTool(e.panel))},[N.api])}),ea=(0,a.useCallback)(e=>{if(!(e in E))return;let t=B.has(e);N.api.toggleTool(e),en.push({kind:"ui.panel.toggle",panel:e,before:t,after:!t})},[N.api,B,en]),el=(0,a.useCallback)(()=>G("chat"),[G]),es=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(es.current||null===N.wins)return;es.current=!0;let e=window.location.pathname.replace(/\/+$/u,""),t="/relationships"===e?"relationships":"/local-knowledge"===e?"localKnowledge":null;null!==t&&(N.wins.some(e=>e.type===t)||ea(t),window.history.replaceState(null,"","/"))},[N.wins,ea]),function(e){let{bindings:t,dispatch:n}=e,l=e.platform??function(){if("u"<typeof navigator)return"other";let e=navigator.platform||"";return/Mac|iPhone|iPad|iPod/i.test(e)?"mac":"other"}(),s=(0,a.useRef)(n);s.current=n;let i=(0,a.useMemo)(()=>(function(e){let t=new Map;for(let n of e){let e=ac(n.chord),a=t.get(e);void 0!==a?a.push(n.commandId):t.set(e,[n.commandId])}let n=[];for(let[,a]of t)if(a.length>1){let t=e.find(e=>a.includes(e.commandId));void 0!==t&&n.push({chord:t.chord,commandIds:a})}return n})(t),[t]),r=(0,a.useMemo)(()=>t.filter(e=>(function(e){for(let t of ar)if(ac(e)===ac(t))return!0;return!1})(e.chord)),[t]);if(i.length>0)throw new au(i);if(r.length>0)throw new am(r);(0,a.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 n of t)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 a=function(e,t){let n=new Set;for(let a of e)"cmd"===a?n.add("mac"===t?"meta":"ctrl"):"ctrl"===a?n.add("ctrl"):"alt"===a?n.add("alt"):"shift"===a&&n.add("shift");return n}(t.mod,n);return e.metaKey===a.has("meta")&&e.ctrlKey===a.has("ctrl")&&e.altKey===a.has("alt")&&e.shiftKey===a.has("shift")}(e,n.chord,l)){e.preventDefault(),s.current(n.commandId);return}}}return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[t,l]),(0,a.useMemo)(()=>({bindings:t,conflicts:i,reserved:r}),[t,i,r])}({bindings:ah,dispatch:(0,a.useCallback)(e=>{"undo"===e?en.undo():"redo"===e?en.redo():"focus-status"===e&&ee.current?.focus()},[en])}),(0,a.useEffect)(()=>{let e=e=>{(e.metaKey||e.ctrlKey)&&("k"===e.key||"K"===e.key)&&(e.preventDefault(),M(e=>!e))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]);let ei=(0,a.useMemo)(()=>(function(e,t,n,a,l,s){let i=[];for(let e of dx){let t=E[e];i.push({id:`new-${e}`,label:`New ${t.title}`,group:"Create",icon:t.icon,run:()=>n(e)})}for(let e of dy){let n=E[e];i.push({id:`open-${e}`,label:`Open ${n.title}`,group:"Tools",icon:n.icon,run:()=>t(e)})}return i.push({id:"tile",label:"Tile all windows",group:"Layout",icon:"tile",run:e.tileAll}),i.push({id:"split",label:"Split front windows",group:"Layout",icon:"split",run:e.splitFront}),i.push({id:"cascade",label:"Cascade windows",group:"Layout",icon:"cascade",run:e.cascade}),i.push({id:"theme",label:"Toggle light / dark theme",group:"View",icon:"light"===a?"moon":"sun",run:l}),i.push({id:"undo",label:null!==s.undoLabel?`Undo: ${s.undoLabel}`:"Undo (window and panel changes only)",group:"Edit",icon:"back",shortcut:"⌘Z",run:s.undo}),i.push({id:"redo",label:null!==s.redoLabel?`Redo: ${s.redoLabel}`:"Redo (window and panel changes only)",group:"Edit",icon:"fwd",shortcut:"⇧⌘Z",run:s.redo}),i})(N.api,ea,G,r,o,en),[N.api,ea,G,r,o,en]),er=!d.loading&&void 0===d.error&&0===d.models.length,eo=(e=d.activeProject?.name,d.loading?"Loading project…":void 0!==e&&e.trim().length>0?e:"No project selected"),ec=void 0!==d.activeProject,ed=d.activeProject?.available===!0,eu=(t={loading:d.loading,error:d.error,hasProject:ec,projectAvailable:ed,noEligibleModels:d.noEligibleModels}).loading?"Loading shell…":void 0!==t.error?"Shell error":t.hasProject?t.projectAvailable?t.noEligibleModels?"Gateway setup required":"Ready":"Project unavailable":"No project selected",em=0===(i=(N.wins??[]).filter(e=>"review"===e.type)).length?"No review open":i.some(e=>"string"==typeof e.cfg.runId&&e.cfg.runId.length>0)?"Evidence ready":"Review window open",eh=void 0!==(l=d.activeChat?.branchLabel)&&l.trim().length>0?l:"No branch selected",ep=S?(0,n.jsx)(tJ,{types:E,order:dx,onAdd:G,onClose:W}):null;return(0,n.jsx)(s,{value:d,children:(0,n.jsx)(y.Provider,{value:_,children:(0,n.jsxs)("div",{className:"app",children:[(0,n.jsx)("a",{className:"skip-link",href:"#main",children:"Skip to content"}),(0,n.jsx)("h1",{className:"visually-hidden",children:"Keiko workspace"}),(0,n.jsx)(q,{openPalette:U,openCommandPalette:Z,onTileAll:N.api.tileAll,onSplitFront:N.api.splitFront,onCascade:N.api.cascade}),(0,n.jsxs)("div",{className:"mid",children:[(0,n.jsx)(F,{openTools:B,onTool:ea,onNewChat:el,theme:r,onToggleTheme:o}),(0,n.jsxs)("div",{className:"stage",id:"main",tabIndex:-1,children:[(0,n.jsx)(t$,{ws:N,wsRef:u,openPalette:U,palette:ep}),null!==f&&(0,n.jsxs)("div",{className:"source-limit-alert",role:"alert",children:[(0,n.jsx)("span",{children:f}),(0,n.jsx)("button",{type:"button",className:"source-limit-alert-dismiss","aria-label":"Dismiss source connection notice",onClick:()=>g(null),children:"×"})]})]}),(0,n.jsx)(z,{openTools:B,onTool:ea})]}),(0,n.jsx)(L,{winCount:O,windows:N.wins??[],windowPaletteOpen:P,onToggleWindowPalette:H,onSelectWindow:J,onCloseWindowPalette:Y,mode:c.mode,selectedModel:d.selectedModel,projectName:eo,branchLabel:eh,shellStatusLabel:eu,evidenceStatusLabel:em,statusRef:et}),null!==I&&(0,n.jsx)(tY,{type:I,types:E,filesContext:N.api.currentFilesContext(),onConfirm:V,onClose:X}),T&&(0,n.jsx)(tT,{commands:ei,onClose:Q}),er?(0,n.jsx)(tL,{}):null,(0,n.jsx)(dv,{})]})})})}function dj(){let[e,t]=(0,a.useState)(!1);return((0,a.useEffect)(()=>{t(!0)},[]),(0,a.useEffect)(()=>{!function(){if(!("u">typeof navigator&&"serviceWorker"in navigator))return;let e=navigator.serviceWorker;try{e.register("/sw.js",{scope:"/"}).catch(e=>{})}catch{}}()},[]),e)?(0,n.jsx)(b,{children:(0,n.jsx)(dw,{})}):(0,n.jsx)("div",{className:"app","aria-hidden":"true",children:(0,n.jsx)("div",{className:"app-boot",children:(0,n.jsx)("img",{className:"app-boot-logo",src:"/assets/keiko-logo.svg",alt:""})})})}e.s(["KeikoDesktop",0,function(){return(0,n.jsx)(dj,{})}],89199)}]);