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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) 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/0i3jzgrj42so8.css +1 -0
  9. package/dist/ui/static/_next/static/chunks/1ru_021szp0u7.js +1 -0
  10. package/dist/ui/static/_next/static/chunks/1t7vb5d9ed2e7.js +1 -0
  11. package/dist/ui/static/_next/static/chunks/23o2c6pyjq92z.js +109 -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/fonts/OFL.txt +93 -0
  21. package/dist/ui/static/fonts/jetbrains-mono-latin-wght-normal.woff2 +0 -0
  22. package/dist/ui/static/index.html +1 -1
  23. package/dist/ui/static/index.txt +3 -3
  24. package/dist/ui/static/launch/__next._full.txt +3 -3
  25. package/dist/ui/static/launch/__next._head.txt +1 -1
  26. package/dist/ui/static/launch/__next._index.txt +2 -2
  27. package/dist/ui/static/launch/__next._tree.txt +2 -2
  28. package/dist/ui/static/launch/__next.launch.__PAGE__.txt +2 -2
  29. package/dist/ui/static/launch/__next.launch.txt +1 -1
  30. package/dist/ui/static/launch.html +1 -1
  31. package/dist/ui/static/launch.txt +3 -3
  32. package/dist/ui/static/local-knowledge/__next._full.txt +3 -3
  33. package/dist/ui/static/local-knowledge/__next._head.txt +1 -1
  34. package/dist/ui/static/local-knowledge/__next._index.txt +2 -2
  35. package/dist/ui/static/local-knowledge/__next._tree.txt +2 -2
  36. package/dist/ui/static/local-knowledge/__next.local-knowledge.__PAGE__.txt +2 -2
  37. package/dist/ui/static/local-knowledge/__next.local-knowledge.txt +1 -1
  38. package/dist/ui/static/local-knowledge/capsule/__next._full.txt +3 -3
  39. package/dist/ui/static/local-knowledge/capsule/__next._head.txt +1 -1
  40. package/dist/ui/static/local-knowledge/capsule/__next._index.txt +2 -2
  41. package/dist/ui/static/local-knowledge/capsule/__next._tree.txt +2 -2
  42. package/dist/ui/static/local-knowledge/capsule/__next.local-knowledge.capsule.__PAGE__.txt +2 -2
  43. package/dist/ui/static/local-knowledge/capsule/__next.local-knowledge.capsule.txt +1 -1
  44. package/dist/ui/static/local-knowledge/capsule/__next.local-knowledge.txt +1 -1
  45. package/dist/ui/static/local-knowledge/capsule.html +1 -1
  46. package/dist/ui/static/local-knowledge/capsule.txt +3 -3
  47. package/dist/ui/static/local-knowledge.html +1 -1
  48. package/dist/ui/static/local-knowledge.txt +3 -3
  49. package/dist/ui/static/memoriaviva/__next._full.txt +2 -2
  50. package/dist/ui/static/memoriaviva/__next._head.txt +1 -1
  51. package/dist/ui/static/memoriaviva/__next._index.txt +2 -2
  52. package/dist/ui/static/memoriaviva/__next._tree.txt +2 -2
  53. package/dist/ui/static/memoriaviva/__next.memoriaviva.__PAGE__.txt +1 -1
  54. package/dist/ui/static/memoriaviva/__next.memoriaviva.txt +1 -1
  55. package/dist/ui/static/memoriaviva/consolidation/__next._full.txt +2 -2
  56. package/dist/ui/static/memoriaviva/consolidation/__next._head.txt +1 -1
  57. package/dist/ui/static/memoriaviva/consolidation/__next._index.txt +2 -2
  58. package/dist/ui/static/memoriaviva/consolidation/__next._tree.txt +2 -2
  59. package/dist/ui/static/memoriaviva/consolidation/__next.memoriaviva.consolidation.__PAGE__.txt +1 -1
  60. package/dist/ui/static/memoriaviva/consolidation/__next.memoriaviva.consolidation.txt +1 -1
  61. package/dist/ui/static/memoriaviva/consolidation/__next.memoriaviva.txt +1 -1
  62. package/dist/ui/static/memoriaviva/consolidation.html +1 -1
  63. package/dist/ui/static/memoriaviva/consolidation.txt +2 -2
  64. package/dist/ui/static/memoriaviva/detail/__next._full.txt +2 -2
  65. package/dist/ui/static/memoriaviva/detail/__next._head.txt +1 -1
  66. package/dist/ui/static/memoriaviva/detail/__next._index.txt +2 -2
  67. package/dist/ui/static/memoriaviva/detail/__next._tree.txt +2 -2
  68. package/dist/ui/static/memoriaviva/detail/__next.memoriaviva.detail.__PAGE__.txt +1 -1
  69. package/dist/ui/static/memoriaviva/detail/__next.memoriaviva.detail.txt +1 -1
  70. package/dist/ui/static/memoriaviva/detail/__next.memoriaviva.txt +1 -1
  71. package/dist/ui/static/memoriaviva/detail.html +1 -1
  72. package/dist/ui/static/memoriaviva/detail.txt +2 -2
  73. package/dist/ui/static/memoriaviva/review-queue/__next._full.txt +2 -2
  74. package/dist/ui/static/memoriaviva/review-queue/__next._head.txt +1 -1
  75. package/dist/ui/static/memoriaviva/review-queue/__next._index.txt +2 -2
  76. package/dist/ui/static/memoriaviva/review-queue/__next._tree.txt +2 -2
  77. package/dist/ui/static/memoriaviva/review-queue/__next.memoriaviva.review-queue.__PAGE__.txt +1 -1
  78. package/dist/ui/static/memoriaviva/review-queue/__next.memoriaviva.review-queue.txt +1 -1
  79. package/dist/ui/static/memoriaviva/review-queue/__next.memoriaviva.txt +1 -1
  80. package/dist/ui/static/memoriaviva/review-queue.html +1 -1
  81. package/dist/ui/static/memoriaviva/review-queue.txt +2 -2
  82. package/dist/ui/static/memoriaviva.html +1 -1
  83. package/dist/ui/static/memoriaviva.txt +2 -2
  84. package/dist/ui/static/sw.js +7 -3
  85. package/node_modules/@oscharko-dev/keiko-cli/dist/.tsbuildinfo +1 -1
  86. package/node_modules/@oscharko-dev/keiko-cli/dist/memory.d.ts.map +1 -1
  87. package/node_modules/@oscharko-dev/keiko-cli/dist/memory.js +4 -5
  88. package/node_modules/@oscharko-dev/keiko-cli/package.json +1 -1
  89. package/node_modules/@oscharko-dev/keiko-contracts/dist/.tsbuildinfo +1 -1
  90. package/node_modules/@oscharko-dev/keiko-contracts/dist/index.d.ts +1 -1
  91. package/node_modules/@oscharko-dev/keiko-contracts/dist/index.js +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/qualityIntelligence/figmaSnapshot/store.d.ts +5 -0
  97. package/node_modules/@oscharko-dev/keiko-evidence/dist/qualityIntelligence/figmaSnapshot/store.d.ts.map +1 -1
  98. package/node_modules/@oscharko-dev/keiko-evidence/dist/qualityIntelligence/figmaSnapshot/store.js +16 -0
  99. package/node_modules/@oscharko-dev/keiko-evidence/package.json +1 -1
  100. package/node_modules/@oscharko-dev/keiko-harness/dist/.tsbuildinfo +1 -1
  101. package/node_modules/@oscharko-dev/keiko-harness/package.json +1 -1
  102. package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/.tsbuildinfo +1 -1
  103. package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/parsers/pdf-parser.d.ts.map +1 -1
  104. package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/parsers/pdf-parser.js +0 -10
  105. package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/parsers/types.d.ts +2 -2
  106. package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/parsers/types.d.ts.map +1 -1
  107. package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/parsers/types.js +3 -3
  108. package/node_modules/@oscharko-dev/keiko-local-knowledge/package.json +1 -1
  109. package/node_modules/@oscharko-dev/keiko-memory-capture/package.json +1 -1
  110. package/node_modules/@oscharko-dev/keiko-memory-consolidation/package.json +1 -1
  111. package/node_modules/@oscharko-dev/keiko-memory-governance/dist/.tsbuildinfo +1 -1
  112. package/node_modules/@oscharko-dev/keiko-memory-governance/dist/index.d.ts +1 -1
  113. package/node_modules/@oscharko-dev/keiko-memory-governance/dist/index.d.ts.map +1 -1
  114. package/node_modules/@oscharko-dev/keiko-memory-governance/dist/index.js +1 -1
  115. package/node_modules/@oscharko-dev/keiko-memory-governance/dist/maintenance.d.ts +2 -16
  116. package/node_modules/@oscharko-dev/keiko-memory-governance/dist/maintenance.d.ts.map +1 -1
  117. package/node_modules/@oscharko-dev/keiko-memory-governance/dist/maintenance.js +49 -48
  118. package/node_modules/@oscharko-dev/keiko-memory-governance/dist/retention.d.ts +2 -1
  119. package/node_modules/@oscharko-dev/keiko-memory-governance/dist/retention.d.ts.map +1 -1
  120. package/node_modules/@oscharko-dev/keiko-memory-governance/dist/retention.js +15 -0
  121. package/node_modules/@oscharko-dev/keiko-memory-governance/package.json +1 -1
  122. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/.tsbuildinfo +1 -1
  123. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/decay.d.ts +2 -0
  124. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/decay.d.ts.map +1 -0
  125. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/decay.js +22 -0
  126. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/diversity.d.ts +8 -0
  127. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/diversity.d.ts.map +1 -0
  128. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/diversity.js +87 -0
  129. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/index.d.ts +4 -2
  130. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/index.d.ts.map +1 -1
  131. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/index.js +4 -1
  132. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/ranking.d.ts +5 -1
  133. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/ranking.d.ts.map +1 -1
  134. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/ranking.js +140 -21
  135. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/recency.d.ts.map +1 -1
  136. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/recency.js +4 -10
  137. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/retrieve.d.ts.map +1 -1
  138. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/retrieve.js +11 -1
  139. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/strength.d.ts +9 -0
  140. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/strength.d.ts.map +1 -0
  141. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/strength.js +51 -0
  142. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/types.d.ts +11 -0
  143. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/types.d.ts.map +1 -1
  144. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/types.js +7 -0
  145. package/node_modules/@oscharko-dev/keiko-memory-retrieval/package.json +1 -1
  146. package/node_modules/@oscharko-dev/keiko-memory-vault/dist/.tsbuildinfo +1 -1
  147. package/node_modules/@oscharko-dev/keiko-memory-vault/dist/access.d.ts +3 -0
  148. package/node_modules/@oscharko-dev/keiko-memory-vault/dist/access.d.ts.map +1 -1
  149. package/node_modules/@oscharko-dev/keiko-memory-vault/dist/access.js +31 -1
  150. package/node_modules/@oscharko-dev/keiko-memory-vault/dist/schema.d.ts +1 -1
  151. package/node_modules/@oscharko-dev/keiko-memory-vault/dist/schema.d.ts.map +1 -1
  152. package/node_modules/@oscharko-dev/keiko-memory-vault/dist/schema.js +16 -1
  153. package/node_modules/@oscharko-dev/keiko-memory-vault/dist/types.d.ts +1 -0
  154. package/node_modules/@oscharko-dev/keiko-memory-vault/dist/types.d.ts.map +1 -1
  155. package/node_modules/@oscharko-dev/keiko-memory-vault/dist/vault.d.ts.map +1 -1
  156. package/node_modules/@oscharko-dev/keiko-memory-vault/dist/vault.js +4 -1
  157. package/node_modules/@oscharko-dev/keiko-memory-vault/package.json +1 -1
  158. package/node_modules/@oscharko-dev/keiko-model-gateway/dist/.tsbuildinfo +1 -1
  159. package/node_modules/@oscharko-dev/keiko-model-gateway/package.json +1 -1
  160. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/.tsbuildinfo +1 -1
  161. package/node_modules/@oscharko-dev/keiko-quality-intelligence/package.json +1 -1
  162. package/node_modules/@oscharko-dev/keiko-sdk/dist/.tsbuildinfo +1 -1
  163. package/node_modules/@oscharko-dev/keiko-sdk/package.json +1 -1
  164. package/node_modules/@oscharko-dev/keiko-security/dist/.tsbuildinfo +1 -1
  165. package/node_modules/@oscharko-dev/keiko-security/package.json +1 -1
  166. package/node_modules/@oscharko-dev/keiko-server/dist/.tsbuildinfo +1 -1
  167. package/node_modules/@oscharko-dev/keiko-server/dist/chat-handlers.d.ts.map +1 -1
  168. package/node_modules/@oscharko-dev/keiko-server/dist/chat-handlers.js +44 -65
  169. package/node_modules/@oscharko-dev/keiko-server/dist/deps.d.ts +2 -0
  170. package/node_modules/@oscharko-dev/keiko-server/dist/deps.d.ts.map +1 -1
  171. package/node_modules/@oscharko-dev/keiko-server/dist/deps.js +1 -0
  172. package/node_modules/@oscharko-dev/keiko-server/dist/gateway-setup.d.ts.map +1 -1
  173. package/node_modules/@oscharko-dev/keiko-server/dist/gateway-setup.js +305 -66
  174. package/node_modules/@oscharko-dev/keiko-server/dist/memory-conv-handlers.d.ts.map +1 -1
  175. package/node_modules/@oscharko-dev/keiko-server/dist/memory-conv-handlers.js +34 -5
  176. package/node_modules/@oscharko-dev/keiko-server/dist/memory-embedding.d.ts +12 -2
  177. package/node_modules/@oscharko-dev/keiko-server/dist/memory-embedding.d.ts.map +1 -1
  178. package/node_modules/@oscharko-dev/keiko-server/dist/memory-embedding.js +127 -0
  179. package/node_modules/@oscharko-dev/keiko-server/dist/memory-handlers.d.ts.map +1 -1
  180. package/node_modules/@oscharko-dev/keiko-server/dist/memory-handlers.js +40 -11
  181. package/node_modules/@oscharko-dev/keiko-server/dist/memory-maintenance-handlers.d.ts +16 -3
  182. package/node_modules/@oscharko-dev/keiko-server/dist/memory-maintenance-handlers.d.ts.map +1 -1
  183. package/node_modules/@oscharko-dev/keiko-server/dist/memory-maintenance-handlers.js +72 -50
  184. package/node_modules/@oscharko-dev/keiko-server/dist/memory-retrieval-signals.d.ts +12 -0
  185. package/node_modules/@oscharko-dev/keiko-server/dist/memory-retrieval-signals.d.ts.map +1 -0
  186. package/node_modules/@oscharko-dev/keiko-server/dist/memory-retrieval-signals.js +84 -0
  187. package/node_modules/@oscharko-dev/keiko-server/dist/memory-salience.d.ts.map +1 -1
  188. package/node_modules/@oscharko-dev/keiko-server/dist/memory-salience.js +11 -6
  189. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figmaSnapshotRoutes.d.ts +15 -0
  190. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figmaSnapshotRoutes.d.ts.map +1 -1
  191. package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figmaSnapshotRoutes.js +105 -0
  192. package/node_modules/@oscharko-dev/keiko-server/dist/routes.d.ts.map +1 -1
  193. package/node_modules/@oscharko-dev/keiko-server/dist/routes.js +2 -1
  194. package/node_modules/@oscharko-dev/keiko-server/package.json +1 -1
  195. package/node_modules/@oscharko-dev/keiko-tools/dist/.tsbuildinfo +1 -1
  196. package/node_modules/@oscharko-dev/keiko-tools/package.json +1 -1
  197. package/node_modules/@oscharko-dev/keiko-verification/dist/.tsbuildinfo +1 -1
  198. package/node_modules/@oscharko-dev/keiko-verification/package.json +1 -1
  199. package/node_modules/@oscharko-dev/keiko-workflows/dist/.tsbuildinfo +1 -1
  200. package/node_modules/@oscharko-dev/keiko-workflows/package.json +1 -1
  201. package/node_modules/@oscharko-dev/keiko-workspace/dist/.tsbuildinfo +1 -1
  202. package/node_modules/@oscharko-dev/keiko-workspace/package.json +1 -1
  203. package/package.json +2 -1
  204. package/dist/ui/static/_next/static/chunks/0-qhhdvxg2j_y.js +0 -1
  205. package/dist/ui/static/_next/static/chunks/0ke4ratkgvcxo.css +0 -1
  206. package/dist/ui/static/_next/static/chunks/3vf3oh2-sl2nc.js +0 -1
  207. package/dist/ui/static/_next/static/chunks/3wmd4-2vznp2g.js +0 -106
  208. /package/dist/ui/static/_next/static/{frhs0YcUqCPLHal-wHjDP → Ppze_8n_i3yc1FS_Qdj0I}/_buildManifest.js +0 -0
  209. /package/dist/ui/static/_next/static/{frhs0YcUqCPLHal-wHjDP → Ppze_8n_i3yc1FS_Qdj0I}/_clientMiddlewareManifest.js +0 -0
  210. /package/dist/ui/static/_next/static/{frhs0YcUqCPLHal-wHjDP → Ppze_8n_i3yc1FS_Qdj0I}/_ssgManifest.js +0 -0
@@ -1,106 +0,0 @@
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:h,className:m,quality:p,width:f,height:g,fill:v=!1,style:x,overrideSrc:b,onLoad:y,onLoadingComplete:j,placeholder:w="empty",blurDataURL:k,fetchPriority:N,decoding:S="async",layout:C,objectFit:I,objectPosition:E,lazyBoundary:R,lazyRoot:$,...T},A){var q;let M,P,L,{imgConf:D,showAltText:F,blurComplete:z,defaultLoader:O}=A,K=D||s.imageConfigDefault;if("allSizes"in K)M=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);M={...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"===M.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&&(x={...x,...e});let n={responsive:"100vw",fill:"100vw"}[C];n&&!t&&(t=n)}let U="",W=o(f),H=o(g);if((q=e)&&"object"==typeof q&&(r(q)||void 0!==q.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(P=t.blurWidth,L=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 G=!d&&!u&&("lazy"===h||void 0===h);(!(e="string"==typeof e?e:U)||e.startsWith("data:")||e.startsWith("blob:"))&&(n=!0,G=!1),M.unoptimized&&(n=!0),_&&!M.dangerouslyAllowSVG&&e.split("?",1)[0].endsWith(".svg")&&(n=!0);let V=o(p),Y=Object.assign(v?{position:"absolute",height:"100%",width:"100%",left:0,top:0,right:0,bottom:0,objectFit:I,objectPosition:E}:{},F?{}:{color:"transparent"},x),Q=z||"empty"===w?null:"blur"===w?`url("data:image/svg+xml;charset=utf-8,${(0,l.getImageBlurSvg)({widthInt:W,heightInt:H,blurWidth:P,blurHeight:L,blurDataURL:k||"",objectFit:Y.objectFit})}")`:`url("${w}")`,J=i.includes(Y.objectFit)?"fill"===Y.objectFit?"100% 100%":"cover":Y.objectFit,X=Q?{backgroundSize:J,backgroundPosition:Y.objectPosition||"50% 50%",backgroundRepeat:"no-repeat",backgroundImage:Q}:{},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:M,src:e,unoptimized:n,width:W,quality:V,sizes:t,loader:B}),ee=G?"lazy":h;return{props:{...T,loading:ee,fetchPriority:N,width:W,height:H,decoding:S,className:m,style:{...Y,...X},sizes:Z.sizes,srcSet:Z.srcSet,src:b||Z.src},meta:{unoptimized:n,preload:u||d,placeholder:w,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 h(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 m=["name","httpEquiv","charSet","itemProp"];function p(e){let t,n,a,l;return e.reduce(h,[]).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=m.length;t<n;t++){let n=m[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 h=e.r(65856),m=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 x=(0,i.forwardRef)(({src:e,srcSet:t,sizes:n,height:a,width:l,decoding:r,className:o,style:c,fetchPriority:d,placeholder:u,loading:h,unoptimized:m,fill:f,onLoadRef:x,onLoadingCompleteRef:b,setBlurComplete:y,setShowAltText:j,sizesInput:w,onLoad:k,onError:N,...S},C)=>{let I=(0,i.useCallback)(e=>{e&&(N&&(e.src=e.src),e.complete&&g(e,u,x,b,y,m,w))},[e,u,x,b,y,N,m,w]),E=(0,p.useMergedRef)(C,I);return(0,s.jsx)("img",{...S,...v(d),loading:h,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,x,b,y,m,w)},onError:e=>{j(!0),"empty"!==u&&y(!0),N&&N(e)}})});function b({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)(h.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),[j,w]=(0,i.useState)(!1),{props:k,meta:N}=(0,c.getImgProps)(e,{defaultLoader:m.default,imgConf:l,blurComplete:v,showAltText:j});return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(x,{...k,unoptimized:N.unoptimized,placeholder:N.placeholder,fill:N.fill,onLoadRef:p,onLoadingCompleteRef:g,setBlurComplete:y,setShowAltText:w,sizesInput:e.sizes,ref:t}),N.preload?(0,s.jsx)(b,{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",h="keiko.twin.policy",m="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 x({children:e}){let[t,l]=(0,a.useState)("manual"),[s,i]=(0,a.useState)("Developer"),[r,b]=(0,a.useState)(o),[y,j]=(0,a.useState)(c),[w,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"}}()),b(f(h,o)),j(f(m,c));try{window.localStorage.removeItem("keiko.twin.memory")}catch{}k(!0)},[]),(0,a.useEffect)(()=>{w&&g(d,t)},[t,w]),(0,a.useEffect)(()=>{w&&g(u,s)},[s,w]),(0,a.useEffect)(()=>{w&&v(h,r)},[r,w]),(0,a.useEffect)(()=>{w&&v(m,y)},[y,w]);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:b,bridges:y,setBridges:j,decide:N}),[t,s,r,y,N]);return(0,n.jsx)(p.Provider,{value:S,children:e})}function b(){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 j=e.i(76055),w=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}}},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"],figma:["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];return l.includes("connector")?"uses knowledge":l.includes("figma")?"uses snapshot":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 q(e,t){if(void 0===t)return null;let n=e=>{let n=t[e];return"string"==typeof n&&n.length>0?n:null};switch(e){case"files":return n("root");case"browser":return n("url");case"editor":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}default:return null}}function M({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"),h=`${String(e)} ${1===e?"window":"windows"}`,m=[...t].sort((e,t)=>t.z-e.z);return(0,a.useEffect)(()=>{let e=!1;return async function(){try{let t=await (0,j.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)(w.Icons.tile,{size:13})," ",h]}),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:m.map(e=>{let t=E[e.type],a=w.Icons[t.icon],l=q(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 P({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)(w.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)(w.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)(w.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)(w.Icons.cascade,{size:16})})]})]})}let L=[{id:"chatHistory",icon:"archive",label:"Chat History"}];function D({tool:e,active:t,onClick:a}){let l=w.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)(w.Icons.newChat,{size:18})}),(0,n.jsx)("div",{className:"rail-div"}),(0,n.jsx)("div",{className:"rail-group",children:L.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)(w.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)(w.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)(w.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)(w.Icons.moon,{size:19}):(0,n.jsx)(w.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)(w.Icons.settings,{size:19})})]})}function z(e){return(0,n.jsx)("aside",{className:"rail rail-right","aria-label":"Workspace utilities"})}let O=`
4
- attribute vec2 aPos;
5
- void main(){ gl_Position = vec4(aPos, 0.0, 1.0); }
6
- `,K=`
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 B(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 _(){let e=window.localStorage.getItem("keiko.wallpaper.opacity");if(null===e)return 1;let t=Number.parseInt(e,10);return Number.isFinite(t)?Math.max(0,Math.min(100,t))/100:1}function U(){let e=(0,a.useRef)(null);return(0,a.useEffect)(()=>{let t,n=e.current;if(null===n)return;let a=n.parentElement;if(null===a)return;let l=window.matchMedia("(prefers-reduced-motion: reduce)"),s=()=>{l.matches?(t?.(),t=void 0):void 0===t&&(t=function(e,t){t.style.opacity=String(_());let n=e=>{let n=e.detail,a="number"==typeof n?n:100*_();t.style.opacity=String(Math.max(0,Math.min(100,a))/100)};window.addEventListener("keiko:wallpaper-opacity",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("keiko:wallpaper-opacity",n)};let l=B(a,a.VERTEX_SHADER,O),s=B(a,a.FRAGMENT_SHADER,K);if(null===l||null===s)return()=>{window.removeEventListener("keiko:wallpaper-opacity",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("keiko:wallpaper-opacity",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"),h=a.getUniformLocation(i,"uLight"),m=a.getUniformLocation(i,"uRip"),p=a.getUniformLocation(i,"uRipT"),f=1,g=1,v=Math.min(window.devicePixelRatio??1,1.5),x={tx:.5,ty:.5,x:.5,y:.5},b=new Float32Array(8),y=[,,,,].fill(-1/0),j=0;function w(){let n=e.getBoundingClientRect();f=Math.max(1,Math.round(n.width)),g=Math.max(1,Math.round(n.height)),t.width=Math.round(f*v),t.height=Math.round(g*v),t.style.width=`${String(f)}px`,t.style.height=`${String(g)}px`,null!==a&&a.viewport(0,0,t.width,t.height)}w();let k="u">typeof ResizeObserver?new ResizeObserver(w):null;null!==k?k.observe(e):window.addEventListener("resize",w);let N=t=>{let n=e.getBoundingClientRect();x.tx=(t.clientX-n.left)/Math.max(1,n.width),x.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||(b[2*j]=a,b[2*j+1]=l,y[j]=performance.now(),j=(j+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();x.x+=(x.tx-x.x)*.06,x.y+=(x.ty-x.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,x.x,x.y),a.uniform1f(h,n),a.uniform2fv(m,b),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("keiko:wallpaper-opacity",n),e.removeEventListener("pointermove",N),e.removeEventListener("pointerdown",S),null!==k?k.disconnect():window.removeEventListener("resize",w),null!==a&&(a.deleteBuffer(r),a.deleteProgram(i),a.deleteShader(l),a.deleteShader(s))}}(a,n))};return s(),l.addEventListener("change",s),()=>{l.removeEventListener("change",s),t?.()}},[]),(0,n.jsx)("canvas",{ref:e,className:"ws-shader","aria-hidden":"true"})}let W=new Set(["files","connector","browser","plugins","agents","quality"]);function H(e,t){return e>=4||t>=8192}function G({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 V({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:h,intensity:m}=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 H(e.contextPack.usage.filesRead,e.contextPack.usage.excerptBytes)?"heavy":"light";case"hybrid":return H(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?W.has(t.type):W.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=h&&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?m:void 0,"data-reduced-motion":t&&o?"true":void 0}),t&&!o?(0,n.jsx)(G,{pathId:a,intensity:m}):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=h&&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?m: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} — ${m} data exchange in progress. Activate to remove connection.`:`Remove connection: ${e.label}`,children:[(0,n.jsx)(w.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"===m?"⇶":"→"}):null]},e.c.id)})})]})}let Y=["n","s","e","w","ne","nw","se","sw"],Q=["t","r","b","l"];function J({icon:e,label:t}){let a=w.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 X({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=w.Icons[c.icon],h=e.zoom??1,m="chat"===e.type||"agents"===e.type||"quality"===e.type?i.linkedFilesRoot(e.id):null,p="agents"===e.type||"quality"===e.type?i.linkedFilesContext(e.id)?.activeFilePath:void 0,f="quality"===e.type?i.linkedAllFilesRoots(e.id):null!==m?[m]:[],g="quality"===e.type?i.linkedConnectorCapsuleIds(e.id):[],v="quality"===e.type?i.linkedConnectorCapsuleSetIds(e.id):[],x="quality"===e.type?i.linkedFigmaSnapshotRunIds(e.id):[],b=e.w/h,y=e.h/h,j=(0,a.useCallback)(t=>{i.update(e.id,{cfg:{...e.cfg,...t}})},[i,e.cfg,e.id]),k=(0,a.useCallback)((e,t)=>i.add(e,t),[i]),{mode:N,node:S}=function(e,t,a,l,s,i,r,o,c,d,u,h){let m=E[e];if("chat"===e){let e=t<430||a<430;return{mode:e?"mini":"full",node:m.render(l,{mini:e,linkedRoot:s,linkedFilePath:i,linkedRoots:r,linkedCapsuleIds:o,linkedCapsuleSetIds:c,linkedFigmaSnapshotRunIds:d,updateCfg:u,openWindow:h})}}return t<m.tiny.w||a<m.tiny.h?{mode:"tiny",node:(0,n.jsx)(J,{icon:m.icon,label:m.title})}:{mode:"full",node:m.render(l,{linkedRoot:s,linkedFilePath:i,linkedRoots:r,linkedCapsuleIds:o,linkedCapsuleSetIds:c,linkedFigmaSnapshotRunIds:d,updateCfg:u,openWindow:h})}}(e.type,b,y,e.cfg,m,p,f,g,v,x,j,k),C=(0,a.useCallback)(t=>i.update(e.id,{zoom:Math.max(.5,Math.min(2,Math.round(10*t)/10))}),[i,e.id]),I=(0,a.useCallback)(t=>{var n,a;let o,c,d,u;if(0!==t.button||"valid"===l)return;t.preventDefault(),i.focus(e.id);let h=r.current;if(null===h)return;let m=(n=h.getBoundingClientRect(),{z:o=s.zoom,vpx0:-s.x/o,vpy0:-s.y/o,vpw:n.width/o,vph:n.height/o,toWX:e=>(e-n.left-s.x)/o,toWY:e=>(e-n.top-s.y)/o}),p=e.max,f=p?e.prev?.w??480:e.w,g=p?e.prev?.h??360:e.h,v=p?f/2:m.toWX(t.clientX)-e.x,x=p?18:m.toWY(t.clientY)-e.y;p&&i.update(e.id,{max:!1,w:f,h:g}),a={winId:e.id,offX:v,offY:x,W:f},c=30/m.z,d=e=>{let t,n,l,s,r=m.toWX(e.clientX),o=m.toWY(e.clientY),d=r-a.offX,u=o-a.offY;d=Math.max(m.vpx0-(a.W-120),Math.min(m.vpx0+m.vpw-120,d)),u=Math.max(m.vpy0,Math.min(m.vpy0+m.vph-38,u)),i.setSnap((t=r-m.vpx0<c,n=m.vpx0+m.vpw-r<c,l=o-m.vpy0<c,s=m.vpy0+m.vph-o<c,l&&t?"tl":l&&n?"tr":s&&t?"bl":s&&n?"br":t?"left":n?"right":l?"maxi":null)),i.update(a.winId,{x:d,y:u})},u=()=>{window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",u),i.commitSnap(a.winId),document.body.style.cursor=""},document.body.style.cursor="grabbing",window.addEventListener("pointermove",d),window.addEventListener("pointerup",u)},[i,e.id,e.x,e.y,e.w,e.h,e.max,e.prev,s,r,l]),$=(0,a.useCallback)(t=>n=>{n.preventDefault(),n.stopPropagation(),i.focus(e.id);let a={x:e.x,y:e.y,w:e.w,h:e.h},l=n.clientX,r=n.clientY,o=s.zoom,c=n=>{let s=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-l)/o,(n.clientY-r)/o,e.type);i.update(e.id,{...s,max:!1})},d=()=>{window.removeEventListener("pointermove",c),window.removeEventListener("pointerup",d),document.body.style.cursor=""};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",c),window.addEventListener("pointerup",d)},[i,e.id,e.x,e.y,e.w,e.h,e.type,s.zoom]),T=(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]),A=(0,a.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),T(e.currentTarget,e)},[T]),M=(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(),T(t.currentTarget,t)}},[T,l,i,e.id]),P=(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]),L=(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]),D="full"===N?q(e.type,e.cfg):null,F={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!==D?`${c.title} — ${D}`:c.title,"aria-roledescription":"window","data-top":t?"true":"false","data-max":e.max?"true":"false","data-conn":l??void 0,"data-window-id":e.id,style:F,tabIndex:-1,onPointerDown:t=>{"valid"===l&&i.confirmConnect(e.id,t),i.focus(e.id)},onFocusCapture:()=>{t||i.focus(e.id)},children:[(0,n.jsxs)("header",{className:"win-head",onPointerDown:I,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!==D?(0,n.jsx)("span",{className:"win-sub mono",title:D,children:D}):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:h<=.5,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>C(h-.1),children:(0,n.jsx)(w.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*h))}% — reset ${c.title} content zoom`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>i.update(e.id,{zoom:1}),children:[Math.round(100*h),"%"]}),(0,n.jsx)("button",{type:"button",className:"win-zbtn",title:"Zoom content in","aria-label":`Zoom ${c.title} content in`,disabled:h>=2,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>C(h+.1),children:(0,n.jsx)(w.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:L}),(0,n.jsx)("button",{type:"button",className:"win-traffic-btn win-traffic-maximize",title:e.max?"Restore":"Maximize","aria-label":e.max?`Restore ${c.title} window`:`Maximize ${c.title} window`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>i.maximize(e.id)}),(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:P})]})]}),(0,n.jsx)("div",{className:"win-body","data-mode":N,style:"tiny"===N?{}:{zoom:h},children:S}),e.max?null:Y.map(e=>(0,n.jsx)("div",{className:`wz wz-${e}`,onPointerDown:$(e)},e)),!e.max&&d?Q.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:A,onKeyDown:M},`p${e}`)):null]})}let Z=[/\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 et={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"}},en=["apikey","accesskey","clientsecret","credential","password","privatekey","secret","token"],ea=["api_key=","apikey=","client_secret=","clientsecret=","credential=","authorization:","password=","secret=","token="],el=[".env",".env.local",".env.development",".env.test",".env.production"],es={chat:["chatId"],files:["activeFilePath","activeDirectoryPath","resolvedRoot"]};function ei(e){return"number"==typeof e&&Number.isFinite(e)}function er(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function eo(e){let t=e.trim();if(0===t.length)return!1;let n=t.toLowerCase();return function(e){for(let t of Z)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)||ea.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(el.includes(n)||".npmrc"===n||"credentials.json"===n||".aws"===n&&"credentials"===a||".ssh"===n&&a.startsWith("id_"))return!0}return!1}(t)}function ec(e){let t=[];for(let n of e){let e=function(e){var t;if(!er(e)||!("string"==typeof(t=e.type)&&t in E))return null;let n=e.type;if("transient"===et[n].persistence||"string"!=typeof e.id||!ei(e.x)||!ei(e.y)||!ei(e.w)||!ei(e.h)||!ei(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(!er(t)||"durable.config"===et[e].persistence)return{};let n=new Set([...(E[e].config??[]).map(e=>e.key),...es[e]??[]]),a={};for(let[l,s]of Object.entries(t)){if(!n.has(l))continue;let t=function(e,t,n){let a;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),en.some(e=>a.includes(e))))return;if("string"!=typeof n)return n;let l=et[e].persistence;return"evidence-reference"===l?!function(e){if(0===e.length||e.length>256||e.startsWith(".")||e.trim()!==e||eo(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}(n)?void 0:n:eo(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(er(e)&&ei(e.x)&&ei(e.y)&&ei(e.w)&&ei(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}:{},...ei(e.zoom)?{zoom:e.zoom}:{}}}(n);null!==e&&t.push(e)}return t}function ed(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 eu(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 eh(e){let{prev:t,...n}=e;return n}function em(e,t,n){return e.some(e=>e.a===t&&e.b===n||e.a===n&&e.b===t)}function ep(e,t){return e?.type==="chat"?e.id:t?.type==="chat"?t.id:null}function ef(e){return e.length>0&&(e.startsWith("/")||/^[A-Za-z]:[/\\]/u.test(e))}function eg(e){return/^[A-Za-z]:[/\\]?$/u.test(e)?e.replace(/\\/gu,"/"):e.replace(/\\/gu,"/").replace(/\/+$/u,"")}function ev(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&&ef(a)?a:null}function ex(e){return e.replace(/\\/gu,"/").replace(/^\/+/u,"").replace(/\/+$/u,"")}function eb(e,t){return void 0!==e.root&&void 0!==t.root&&eg(e.root)===eg(t.root)&&e.kind===t.kind&&e.relativePaths.length===t.relativePaths.length&&e.relativePaths.every((e,n)=>ex(e)===ex(t.relativePaths[n]??""))}function ey(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=ev(a);if(null===s)return null;let i=a.cfg.activeFilePath;if("string"==typeof i&&i.length>0)return{kind:"files",relativePaths:[ex(i)],root:eg(s),connectedAtMs:n};let r=a.cfg.activeDirectoryPath;return"string"==typeof r&&r.length>0?{kind:"directory",relativePaths:[ex(r)],root:eg(s),connectedAtMs:n}:{kind:"workspace-root",relativePaths:[],root:eg(s),connectedAtMs:n}}function ej(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:[ex(e.boundRelativePath)],root:eg(e.boundRoot),connectedAtMs:t}:"files"===e.boundScopeKind?"string"!=typeof e.boundRelativePath||0===e.boundRelativePath.length?null:{kind:"files",relativePaths:[ex(e.boundRelativePath)],root:eg(e.boundRoot),connectedAtMs:t}:{kind:"workspace-root",relativePaths:[],root:eg(e.boundRoot),connectedAtMs:t}}function ew(e){return Math.max(e.maxConnectedSources,e.maxLocalKnowledgeSources)}function ek(e,t){return e.filter(e=>!eb(e,t))}function eN(e){return e.connectedScopes??(void 0!==e.connectedScope?[e.connectedScope]:[])}function eS(e){return e.localKnowledgeScopes??(void 0!==e.localKnowledgeScope?[e.localKnowledgeScope]:[])}function eC(e){return"capsule"===e.kind?`capsule:${e.capsuleId}`:`set:${e.capsuleSetId}`}function eI(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 eE(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 eR="keiko.workspace.v4",e$="keiko.conns.v1",eT="keiko.view";function eA(){try{let e=window.localStorage.getItem(eT);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 eq(e){return Math.max(.3,Math.min(2.5,e))}function eM(e){return Math.max(.5,Math.min(2,Math.round(10*e)/10))}function eP(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 eL(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}let eD={Equal:"=",NumpadAdd:"+",Minus:"-",NumpadSubtract:"-",Digit0:"0",Numpad0:"0"},eF="application/x-keiko-local-knowledge-connector",ez="keiko:local-knowledge-connector-drop";function eO(e){if(!Array.from(e.types).includes(eF))return null;try{let t=JSON.parse(e.getData(eF));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 eK={w:260,h:220};function eB(e,t){let n=e+t;return e<1&&n>1||e>1&&n<1?1:n}function e_({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 eU(e){let t=E[e.type].title,n=q(e.type,e.cfg);return null!==n?`${t}: ${n}`:t}function eW({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:`${eU(n)} ${T(n,a)} ${eU(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=eU(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}`:`Maximize ${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 ",eU(t.source)," and"," ",eU(t.target)]})]},e.id))})]})]})})}function eH({ws:e,wsRef:t,openPalette:l,palette:s}){let{wins:i,view:r,snapPrev:o,conns:c,connecting:d,api:u}=e,h=(0,a.useMemo)(()=>null===i?null:i.filter(e=>!0!==e.minimized),[i]),m=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}(h),p=null!==d&&null!==h?h.find(e=>e.id===d.from)??null:null,f=(0,a.useMemo)(()=>({backgroundSize:`${String(22*r.zoom)}px ${String(22*r.zoom)}px`,backgroundPosition:`${String(r.x)}px ${String(r.y)}px`}),[r]),g=(0,a.useMemo)(()=>({transform:`translate(${String(r.x/r.zoom)}px, ${String(r.y/r.zoom)}px)`,transformOrigin:"0 0",zoom:r.zoom}),[r]),v=(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,{...function({clientX:e,clientY:t,rect:n,view:a}){return{x:Math.round((e-n.left-a.x)/a.zoom-eK.w/2),y:Math.round((t-n.top-a.y)/a.zoom-28)}}({clientX:t,clientY:n,rect:a,view:r}),...eK})},[u,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||v(s,a,l,n)};return window.addEventListener(ez,e),()=>{window.removeEventListener(ez,e)}},[v,t]);let x=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,onPointerDownCapture:e=>{if(0!==e.button||null===d||null===p||null===h)return;let t=function(e){if(!(e instanceof Element))return;let t=e.closest(".window[data-window-id]");return t?.dataset.windowId}(e.target);if(void 0===t||t===p.id)return;let n=h.find(e=>e.id===t);void 0!==n&&$(p.type,n.type)&&u.confirmConnect(n.id,e)},onPointerDown:e=>{var t,n;if(0===e.button&&!((t=e.target)instanceof Element&&(null!==t.closest(".window")||null!==t.closest(".ws-zoom")||null!==t.closest(".ws-fab")||null!==t.closest(".ws-empty-btn")||null!==t.closest(".ws-outline")||null!==t.closest(".conn-badge")))){let t,a,l,s;if(null!==d)return void u.cancelConnect();n=u.panBy,t=e.clientX,a=e.clientY,document.body.style.cursor="grabbing",l=e=>{n(e.clientX-t,e.clientY-a),t=e.clientX,a=e.clientY},s=()=>{window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",s),document.body.style.cursor=""},window.addEventListener("pointermove",l),window.addEventListener("pointerup",s)}},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!==eO(e.dataTransfer)&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},onDrop:e=>{let t=eO(e.dataTransfer);if(null===t)return;e.preventDefault(),e.stopPropagation();let n=e.currentTarget.getBoundingClientRect();v(t,e.clientX,e.clientY,n)},children:[(0,n.jsx)(U,{}),(0,n.jsx)("div",{className:"ws-grid",style:f,"aria-hidden":"true"}),(0,n.jsx)(eW,{wins:i,conns:c,top:m,api:u,openPalette:l}),(0,n.jsx)(e_,{wins:h,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,x?(0,n.jsxs)("div",{className:"ws-empty",children:[(0,n.jsx)("img",{className:"ws-empty-logo",src:"/assets/keiko-logo.svg",alt:""}),(0,n.jsx)("div",{className:"ws-empty-title",children:"Empty workspace"}),(0,n.jsx)("div",{className:"ws-empty-sub",children:"Open a window to start working"}),(0,n.jsxs)("button",{type:"button",className:"ws-empty-btn",onClick:l,children:[(0,n.jsx)(w.Icons.add,{size:15})," New window"]})]}):null,(0,n.jsxs)("div",{className:"ws-scene",style:g,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!==h?(0,n.jsx)(V,{wins:h,conns:c,connecting:d,api:u}):null,null!==h?h.map(e=>(0,n.jsx)(X,{win:e,top:null!==m&&e.id===m.id,connState:null===p?null:e.id===p.id?"source":$(p.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(eB(r.zoom,-.2)),disabled:r.zoom<=.3,"aria-label":"Zoom out",title:"Zoom out",children:(0,n.jsx)(w.Icons.zoomOut,{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(eB(r.zoom,.2)),disabled:r.zoom>=2.5,"aria-label":"Zoom in",title:"Zoom in",children:(0,n.jsx)(w.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)(w.Icons.add,{size:20})}),s??null]})}function eG({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 h=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(),h(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)(w.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:()=>h(e),children:[(0,n.jsx)("span",{className:"cmdk-ico",children:(a=e.icon,l=w.Icons[a]??w.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 eV=e.i(74080);function eY(e){return Array.from(new Set(e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e.length>0)))}function eQ({onCancel:e}){let t=(0,a.useRef)(null),l=(0,a.useRef)(null),s=(0,a.useRef)(null),i=(0,a.useRef)(void 0),[r,o]=(0,a.useState)(""),[c,d]=(0,a.useState)(""),[u,h]=(0,a.useState)(""),[m,p]=(0,a.useState)(""),[f,g]=(0,a.useState)(""),[v,x]=(0,a.useState)(!1),[b,y]=(0,a.useState)(),[k,N]=(0,a.useState)(),[S,C]=(0,a.useState)();async function I(e){if(e.preventDefault(),!v){x(!0),y(void 0),N(void 0),C(void 0),t.current?.focus();try{let e=eY(m);if(function(e){try{return new URL(e.trim()).hostname.endsWith(".services.ai.azure.com")}catch{return!1}}(r)&&0===e.length){y("Azure AI Foundry requires deployment names. Paste the names from the Deployments tab."),x(!1);return}let t=eY(f),n=(await (0,j.setupGateway)({baseUrl:r,apiKey:c,apiKeyHeaderName:""===u.trim()?void 0:u.trim(),deploymentNames:e,...0===t.length?{}:{imageInputModelIds:t}})).testedModelIds.length;C(`Verified ${String(n)} workflow chat model${1===n?"":"s"}. Reloading Keiko…`),i.current=window.setTimeout(()=>window.location.reload(),800)}catch(t){let e=t instanceof j.ApiError?{message:t.message,code:t.code}:t instanceof Error?{message:t.message}:{message:"The gateway could not be configured."};y(e.message),N(e.code),x(!1)}}}(0,a.useEffect)(()=>(s.current=document.activeElement,l.current?.focus(),()=>{void 0!==i.current&&window.clearTimeout(i.current),s.current?.focus?.()}),[]),(0,a.useEffect)(()=>{let n=t.current;if(null===n)return;let a=t=>{if("Escape"===t.key){if(v||void 0!==S||void 0===e)return;t.preventDefault(),e();return}if("Tab"!==t.key)return;let a=Array.from(n.querySelectorAll("button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex='-1'])"));if(0===a.length)return;let l=a[0],s=a[a.length-1];t.shiftKey&&document.activeElement===l?(t.preventDefault(),s.focus()):t.shiftKey||document.activeElement!==s||(t.preventDefault(),l.focus())};return n.addEventListener("keydown",a),()=>n.removeEventListener("keydown",a)},[v,e,S]),(0,a.useEffect)(()=>{void 0===b||v||l.current?.focus()},[b,v]);let E=(0,n.jsx)("div",{className:"gw-setup-backdrop",role:"presentation",children:(0,n.jsx)("div",{ref:t,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",{onSubmit:e=>void I(e),children:[(0,n.jsxs)("div",{className:"gw-setup-badge",children:[(0,n.jsx)(w.Icons.cube,{size:18}),"Model gateway setup"]}),(0,n.jsx)("h1",{id:"gw-setup-title",children:"Connect Keiko to your internal LLMs"}),(0,n.jsx)("p",{id:"gw-setup-desc",children:"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)("label",{className:"gw-field",children:[(0,n.jsx)("span",{children:"Base URL"}),(0,n.jsx)("input",{className:"gw-input mono",value:r,placeholder:"https://llm-gateway.example.com/v1",autoComplete:"off",disabled:v||void 0!==S,ref:l,onChange:e=>o(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsx)("span",{children:"API token"}),(0,n.jsx)("input",{className:"gw-input mono",type:"password",value:c,placeholder:"Paste your API token",autoComplete:"off",disabled:v||void 0!==S,onChange:e=>d(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:u,placeholder:"Authorization",autoComplete:"off",disabled:v||void 0!==S,onChange:e=>h(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:m,placeholder:"Paste deployment names, one per line",autoComplete:"off",disabled:v||void 0!==S,onChange:e=>p(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:f,placeholder:"Paste image-capable model names, one per line",autoComplete:"off",disabled:v||void 0!==S,onChange:e=>g(e.target.value)})]}),(0,n.jsx)("div",{className:"gw-note",children:"Leave the header field empty unless your gateway admin gave you a custom API-key header, for example X-Litellm-Key. Supported headers are Authorization, X-Litellm-Key, X-Api-Key, and api-key. Leave deployment names empty only for OpenAI-compatible gateways with model discovery. For Azure AI Foundry, paste deployment names exactly as shown in the Deployments tab. Image-input model names must match tested gateway models exactly. Testing several deployments can take up to 30 seconds."}),void 0!==b?(0,n.jsxs)("div",{className:"gw-error",role:"alert",children:[b,void 0!==k?(0,n.jsx)("div",{className:"gw-error-code mono",children:k}):null]}):null,void 0!==S?(0,n.jsx)("div",{className:"gw-success",role:"status",children:S}):null,(0,n.jsx)("span",{id:"gw-submit-requirements",className:"visually-hidden",children:"Base URL and API token are required."}),(0,n.jsxs)("div",{className:"gw-actions",children:[void 0!==e?(0,n.jsx)("button",{className:"gw-cancel",type:"button",disabled:v||void 0!==S,onClick:e,children:"Cancel"}):null,(0,n.jsx)("button",{className:"gw-submit",type:"submit",disabled:v||void 0!==S||""===r.trim()||""===c.trim(),"aria-busy":v,"aria-describedby":"gw-submit-requirements",children:v?"Testing connection…":"Test & save"})]})]})})});return"u"<typeof document?E:(0,eV.createPortal)(E,document.body)}let eJ=[["ask","Ask every action"],["full","Full access"]];function eX({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:eJ.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 eZ(e){return"chat"===e.kind&&e.toolCalling&&e.structuredOutput}function e0(e){if(e instanceof j.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 e1({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,h]=(0,a.useState)(!1),[m,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}h(!0),p(null);try{let t=await (0,j.fetchFilesDirectories)(f,e);o(t),d(t.path)}catch(e){p(e0(e))}finally{h(!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)(w.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)(w.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!==m?(0,n.jsx)("div",{className:"dir-error",role:"alert",children:m}):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 e2=[{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 e4(e){return e.filter(e=>e.available).map(e=>e.path)}function e3(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e.length>0)}function e6(e){return e.replaceAll("\\","/")}function e5(e,t){let n=e6(t.trim());if(0===n.length)return"";let a=e6(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 e8(e,t){return e3(t).map(t=>e5(e,t)).join(", ")}function e9({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??""),[h,m]=(0,a.useState)(""),[p,f]=(0,a.useState)([]),[g,v]=(0,a.useState)([]),[x,b]=(0,a.useState)(()=>{var t,n;let a;return t=e?.root??"",{verifyTargetFiles:a=null===(n=e?.activeFilePath??null)?"":e5(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===e3(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||e3(a.bugTargetFiles).length>0?null:"Bug investigation requires description, output, stack trace, or target files."}(o,E,h,x),A=null===T&&$&&!C&&!y;(0,a.useEffect)(()=>{let e=!1;return k(!0),i(null),Promise.all([(0,j.fetchModels)(),(0,j.fetchProjects)()]).then(([t,n])=>{if(e)return;let a=t.models.filter(eZ);f(a),m(e=>e||(a[0]?.id??"")),v(e4(n.projects))}).catch(t=>{e||i(e0(t))}).finally(()=>{e||k(!1)}),()=>{e=!0}},[i]);let q=e=>{b(t=>({...t,...e}))};(0,a.useEffect)(()=>{if(null===R)return;let e=e5(E,R);b(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 M=async()=>{v(e4((await (0,j.fetchProjects)()).projects))},P=async()=>{if(0!==E.length){S(!0),i(null);try{await (0,j.createProject)({path:E}),await M()}catch(e){i(e0(e))}finally{S(!1)}}},L=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=e3(a.verifyTargetFiles).map(e=>e5(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:e5(t,a.explainFilePath),...a.explainQuestion.trim().length>0?{question:a.explainQuestion.trim()}:{}}};if("unit-test-generation"===e){let e=e3(a.unitFilePaths).map(e=>e5(t,e)),l="module"===a.unitTargetKind?{kind:"module",moduleDir:e5(t,a.unitModuleDir)}:"changedFiles"===a.unitTargetKind?{kind:"changedFiles",filePaths:e}:{kind:"file",filePath:e5(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()}:{},...e3(a.bugTargetFiles).length>0?{targetFiles:e3(a.bugTargetFiles).map(e=>e5(t,e))}:{}}}}}(o,E,h,x);try{let n=await (0,j.startRun)(t);r({workflow:o,model:h,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 j.ApiError&&"WORKSPACE_NOT_REGISTERED"===e.code?(await M().catch(()=>void 0),i("Workspace is not registered.")):i(e0(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:e2.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)(w.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)(e1,{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 P(),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:h,onChange:e=>m(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)(w.Icons.chevron,{size:15})})]})]}),null!==R?(0,n.jsxs)("button",{type:"button",className:"dlg-current-file",onClick:()=>{if(null===R)return;let e=e5(E,R);"verify"===o?q({verifyTargetFiles:e}):"explain-plan"===o?q({explainFilePath:e}):"unit-test-generation"===o?"changedFiles"===x.unitTargetKind?q({unitFilePaths:e}):q({unitTargetKind:"file",unitFilePath:e}):q({bugTargetFiles:e})},title:R,children:[(0,n.jsx)(w.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:x.verifyTargetFiles,onChange:e=>q({verifyTargetFiles:e.target.value}),onBlur:e=>q({verifyTargetFiles:e8(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:x.explainFilePath,onChange:e=>q({explainFilePath:e.target.value}),onBlur:e=>q({explainFilePath:e5(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:x.explainQuestion,onChange:e=>q({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:x.unitTargetKind,onChange:e=>q({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)(w.Icons.chevron,{size:15})})]})]}),"module"===x.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:x.unitModuleDir,onChange:e=>q({unitModuleDir:e.target.value}),onBlur:e=>q({unitModuleDir:e5(E,e.target.value)})})]}):"changedFiles"===x.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:x.unitFilePaths,onChange:e=>q({unitFilePaths:e.target.value}),onBlur:e=>q({unitFilePaths:e8(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:x.unitFilePath,onChange:e=>q({unitFilePath:e.target.value}),onBlur:e=>q({unitFilePath:e5(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:x.bugDescription,onChange:e=>q({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:x.bugFailingOutput,onChange:e=>q({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:x.bugStackTrace,onChange:e=>q({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:x.bugTargetFiles,onChange:e=>q({bugTargetFiles:e.target.value}),onBlur:e=>q({bugTargetFiles:e8(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 L(),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 e7({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,h]=(0,a.useState)(!1),[m,p]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),v=(0,a.useRef)(null),x=(0,a.useRef)(null),b=(0,a.useRef)(null);(0,a.useEffect)(()=>(b.current=document.activeElement,()=>{let e=b.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(()=>{h(!0),(v.current??x.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,j.fetchProjects)().then(e=>{let n=e4(e.projects)[0];t||void 0===n||d(e=>({...e,root:n}))}).catch(e=>{t||p(e0(e))}),()=>{t=!0}},[c.root,e]);let y=(e,t)=>d(n=>({...n,[e]:t})),k=()=>{"agents"!==e&&s(c)},N=w.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:x,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)(w.Icons.close,{size:16})})]}),(0,n.jsxs)("div",{className:"dlg-body",children:["agents"===e?(0,n.jsx)(e9,{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)(eX,{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)(w.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)(e1,{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!==m?(0,n.jsx)("div",{className:"dlg-error",role:"alert",children:m}):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]})]})})}let te=new Map([["ArrowRight",1],["ArrowLeft",-1],["ArrowDown",2],["ArrowUp",-2]]);function tt({types:e,order:t,onAdd:l,onClose:s}){let i=(0,a.useRef)(null),r=(0,a.useRef)(null),[o,c]=(0,a.useState)(0);return(0,a.useEffect)(()=>{r.current=document.activeElement;let e=i.current?.querySelector(".pal-card");return e?.focus(),()=>{let e=document.activeElement;(null===e||e===document.body)&&r.current?.focus?.()}},[]),(0,a.useEffect)(()=>{let e=e=>{null!==i.current&&e.target instanceof Node&&!i.current.contains(e.target)&&s()};return document.addEventListener("pointerdown",e),()=>{document.removeEventListener("pointerdown",e)}},[s]),(0,n.jsxs)("div",{ref:i,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(i.current?.querySelectorAll(".pal-card")??[]),n=function(e,t,n){if(0===n)return null;if("Home"===e)return 0;if("End"===e)return n-1;let a=te.get(e);return void 0===a?null:Math.max(0,Math.min(n-1,t+a))}(e.key,t.indexOf(e.target),t.length);null!==n&&(e.preventDefault(),c(n),t[n]?.focus())},onBlur:e=>{e.relatedTarget instanceof Node&&i.current?.contains(e.relatedTarget)!==!0&&s()},children:[(0,n.jsxs)("div",{className:"palette-head",children:[(0,n.jsx)("span",{className:"palette-badge",children:(0,n.jsx)(w.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)(w.Icons.close,{size:16})})]}),(0,n.jsx)("div",{className:"palette-grid",children:t.map((t,a)=>{let s=e[t],i=w.Icons[s.icon];return(0,n.jsxs)("button",{type:"button",className:"pal-card pal-main",tabIndex:a===o?0:-1,onFocus:()=>c(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",children:(0,n.jsx)(w.Icons.plus,{size:15})})]},t)})})]})}async function tn(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 ta(e,t){let n,a=(t?.method??"GET").toUpperCase(),l=t?.body,s=await fetch(e,{...t,headers:(n={Accept:"application/json"},null!=l&&(n["Content-Type"]="application/json"),"GET"!==a&&"HEAD"!==a&&(n["X-Keiko-CSRF"]="1"),n)});if(!s.ok){let{code:e,message:t}=await tn(s);throw new j.ApiError(e,t,s.status)}return s.json()}async function tl(e={},t=ta){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 ts(e=ta){return e("/api/memory/review-queue")}async function ti(e,t=ta){return t("/api/memory/consolidation/jobs",{method:"POST",body:JSON.stringify({settings:e})})}async function tr(e,t=ta){return t(`/api/memory/consolidation/jobs/${encodeURIComponent(e)}`)}async function to(e,t=ta){return t(`/api/memory/consolidation/jobs/${encodeURIComponent(e)}/cancel`,{method:"POST",body:"{}"})}async function tc(e,t=ta){return t(`/api/memory/${encodeURIComponent(e)}`)}async function td(e,t,n=ta){return n(`/api/memory/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})}async function tu(e,t=ta){return t(`/api/memory/${encodeURIComponent(e)}/pin`,{method:"POST",body:"{}"})}async function th(e,t=ta){return t(`/api/memory/${encodeURIComponent(e)}/unpin`,{method:"POST",body:"{}"})}async function tm(e,t,n=ta){return n(`/api/memory/${encodeURIComponent(e)}/archive`,{method:"POST",body:JSON.stringify({...void 0!==t?{reason:t}:{}})})}async function tp(e,t,n=ta){return n(`/api/memory/${encodeURIComponent(e)}/forget`,{method:"POST",body:JSON.stringify({acknowledged:!0,...void 0!==t?{reason:t}:{}})})}async function tf(e,t,n=ta){return n(`/api/memory/${encodeURIComponent(e)}`,{method:"DELETE",body:JSON.stringify({acknowledged:!0,...void 0!==t?{reason:t}:{}})})}async function tg(e,t,n=ta){return n(`/api/memory/${encodeURIComponent(e)}/correct`,{method:"POST",body:JSON.stringify({body:t})})}async function tv(e,t=ta){return t(`/api/memory/proposals/${encodeURIComponent(e)}/accept`,{method:"POST",body:"{}"})}async function tx(e,t,n=ta){return n(`/api/memory/proposals/${encodeURIComponent(e)}/reject`,{method:"POST",body:JSON.stringify({...void 0!==t?{reason:t}:{}})})}let tb=[{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 ty(e){return tb.find(t=>t.workflowId===e)}function tj(e){return void 0===e||!Number.isFinite(e)||e<=0?0:Math.floor(e)}function tw(e){return"u">typeof TextEncoder?new TextEncoder().encode(e).length:e.length}function tk(e){let t=tj(e.modelContextWindow),n=tj(e.modelMaxOutputTokens),a=Math.max(0,t-n),l=tw(e.userDraftText),s=function(e){let t=0;for(let n of e)t+=tw(n.role),t+=tw(n.content);return t}(e.conversationHistory),i=function(e){if(void 0===e)return 0;let t=0;for(let n of e)t+=tj(n.extractedBytes);return t}(e.documentContext),r=tj(e.repoContextPackBytes),o=tj(e.knowledgeCapsuleBytes),c=tj(e.memoryContextBytes),d=l+s+i+r+o+c,u=Math.ceil(d/4),h=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:h,breakdown:{draftBytes:l,historyBytes:s,documentBytes:i,repoContextBytes:r,knowledgeBytes:o,memoryBytes:c}}}function tN(e){return"chat"===e.kind}let tS={embedding:"embedding-only","ocr-vision":"ocr-vision-only"};function tC(e,t){return e instanceof j.ApiError?e.message.trim().length>0?`${e.message} (${e.code})`:`${t} (${e.code})`:e instanceof Error&&e.message.trim().length>0?e.message:t}let tI="\n…[truncated]",tE=["text/"],tR=new Set(["application/json","application/x-yaml","application/yaml"]),t$=new TextEncoder;function tT(e){return t$.encode(e).length}function tA(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t>=0?e.slice(t+1):e}let tq=`${String(256)} KB`;function tM(e){return`"${e}" won't be sent — the ${tq} attachment limit was already used by earlier files.`}async function tP(e,t){var n,a;let l,s,i,r,o;if(e.remainingAggregate<=0)return tM(tA(t.name));try{l=await t.file.text()}catch{return n=tA(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-tT(tI),0));if(c<=0)return tM(tA(t.name));let{entry:d,consumed:u}=(i=(s=tT(a=l)>c)?function(e,t){if(t<=0)return"";if(tT(e)<=t)return e;let n=0,a="";for(let l of e){let e=n+tT(l);if(e>t)break;n=e,a+=l}return a}(a,c):a,r=tT(i),o=s?tT(tI):0,{entry:{id:t.id,displayName:tA(t.name),mimeType:t.mimeType,sizeBytes:t.sizeBytes,extractedBytes:r,truncated:s,truncationMarker:s?tI:void 0,text:i},consumed:r+o});if(0===d.text.length)return 0===l.length?void 0:tM(tA(t.name));e.entries.push(d),e.remainingAggregate-=u}async function tL(e){let t=e.filter(e=>{var t;return t=e.mimeType,!!tE.some(e=>t.startsWith(e))||tR.has(t)}),n=t.slice(0,16),a={entries:[],remainingAggregate:262144},l=[];for(let e of n){let t=await tP(a,e);void 0!==t&&l.push(t)}for(let e of t.slice(16)){var s;l.push((s=tA(e.name),`"${s}" won't be sent — only the first ${String(16)} documents are included.`))}return{entries:a.entries,failures:l}}let tD=["text/"],tF=new Set(["application/pdf","application/json","application/x-yaml","application/yaml"]),tz="New chat",tO="keiko:chat-upsert",tK="keiko:chat-delete",tB=["completed","failed","cancelled"];function t_(e){return"idle"!==e&&!tB.includes(e)}let tU="The conversation context exceeded the model's window. Clear history or pick a larger-context model.",tW="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.",tH=new Set(["CONVERSATION_OVERSIZED_CONTEXT","GATEWAY_CONTEXT_OVERFLOW"]),tG=["context length","context_length_exceeded","max_tokens","too many tokens"],tV=["empty assistant response","empty grounded answer","without assistant content"];function tY(e){return void 0!==e&&e.contextWindowTokens>0&&"exceeded"===e.pressure}function tQ(e){let t;return function(e){if(e instanceof j.ApiError&&tH.has(e.code))return!0;let t=e instanceof Error?e.message.toLowerCase():"";return 0!==t.length&&tG.some(e=>t.includes(e))}(e)?tU:0!==(t=e instanceof Error?e.message.toLowerCase():"").length&&tV.some(e=>t.includes(e))?e instanceof j.ApiError?`${tW} (${e.code})`:tW:tC(e,"Something went wrong. Try again.")}function tJ(e){return[...e].sort((e,t)=>t.updatedAt-e.updatedAt)}function tX(e){window.dispatchEvent(new CustomEvent(tO,{detail:e}))}function tZ(e){return e.find(tN)?.id}function t0(e,t){return void 0!==e&&t.some(t=>t.id===e&&tN(t))?e:tZ(t)}function t1(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 t2={projects:[],chats:[],messages:[],models:[],activeProject:void 0,activeChat:void 0,selectedModel:void 0};async function t4(e){let t=(await (0,j.fetchModels)()).models.filter(tN),n=tZ(t),a=[...(await (0,j.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=tJ((await (0,j.fetchChats)(l.path).catch(()=>({chats:[]}))).chats),n=e[0];if(void 0!==n){let s=await (0,j.fetchChatMessages)(n.id,l.path),i=t0(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:tz};l?.available===!0&&(s.projectPath=l.path);let i=await (0,j.createDesktopChat)(s);return tX(i.chat),{models:t,selectedModel:i.chat.selectedModel,projects:Array.from(i.projects),activeProject:i.project,chats:tJ(i.chats),activeChat:i.chat,messages:Array.from(i.messages)}}function t3(e={}){let t=e.autoCreate??!0,[n,l]=(0,a.useState)(t2),[s,i]=(0,a.useState)(""),[r,o]=(0,a.useState)(!0),[c,d]=(0,a.useState)("idle"),u=t_(c),h=(0,a.useRef)("idle"),m=(0,a.useRef)(null),[p,f]=(0,a.useState)(),[g,v]=(0,a.useState)(),[x,b]=(0,a.useState)(),[y,w]=(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":tD.some(e=>t.startsWith(e))||tF.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]),q=(0,a.useCallback)(e=>{R(t=>t.filter(t=>t.id!==e))},[]),M=(0,a.useCallback)(()=>{R([])},[]),P=(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 tL(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]),L=(0,a.useCallback)(()=>{b(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 tv(e),b(t=>void 0===t?t:{...t,actions:t.actions.filter(t=>"candidate"!==t.kind||t.proposalId!==e)})},[]),z=(0,a.useCallback)(async e=>{await tx(e),b(t=>void 0===t?t:{...t,actions:t.actions.filter(t=>"candidate"!==t.kind||t.proposalId!==e)})},[]),O=(0,a.useCallback)(async e=>{await tp(e,"user-initiated forget from Conversation Center"),b(t=>void 0===t?t:{...t,actions:t.actions.filter(t=>"forget"!==t.kind||t.memoryId!==e)})},[]),K=(0,a.useCallback)(e=>{h.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 t4(t);e||l(e=>({...e,...n}))}catch(t){e||f(tQ(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:tJ([t,...e.chats.filter(e=>e.id!==t.id)]),activeChat:e.activeChat?.id===t.id?t:e.activeChat,selectedModel:e.activeChat?.id===t.id?t0(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(tO,e),window.addEventListener(tK,t),()=>{window.removeEventListener(tO,e),window.removeEventListener(tK,t)}},[]),(0,a.useEffect)(()=>()=>{m.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,j.updateChat)(n,{selectedModel:e}).then(e=>{C.current!==a||S.current===e.chat.id&&(tX(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(tQ(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=t0(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:tz},r=e?.path??n.activeProject?.path;void 0!==r&&(i.projectPath=r);let o=await (0,j.createDesktopChat)(i);return S.current=o.chat.id,tX(o.chat),l({projects:Array.from(o.projects),chats:tJ(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(tQ(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,j.fetchChats)(e.path),a=tJ(t.chats),s=a[0];if(void 0===s)return void await _(e);let i=await (0,j.fetchChatMessages)(s.id,e.path);S.current=s.id;let r=t0(s.selectedModel,n.models);l(e=>({...e,chats:a,activeChat:s,selectedModel:r,messages:Array.from(i.messages)})),b(void 0)}catch(e){f(tQ(e))}},[_,n.models]),W=(0,a.useCallback)(async e=>{f(void 0),m.current?.abort(),m.current=null,S.current=e.id,v(void 0),b(void 0),T([]);try{let t=await (0,j.fetchChatMessages)(e.id,e.projectPath),a=t0(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(tQ(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,j.createProject)({path:t}),n=await (0,j.fetchProjects)();l(e=>({...e,projects:Array.from(n.projects)})),await _(e.project)}catch(e){f(tQ(e))}}},[_]),G=(0,a.useCallback)(e=>{l(t=>({...t,messages:t.messages.filter(t=>t.id!==e)}))},[]),V=(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:tJ([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)]})),tX(a.chat),void 0!==a.memory&&b(a.memory),n("completed")},onError:({code:t,message:a})=>{f(tQ(new j.ApiError(t,a,0))),G(e),n("failed")},onCancelled:()=>{G(e),n("cancelled")}}},[G,K]),Y=(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=V(o,a,e);(0,j.sendDesktopChatStream)(c,i,n).catch(n=>{G(o),n instanceof j.StreamingUnavailableError?t(n):n instanceof DOMException&&"AbortError"===n.name?e("cancelled"):(f(tQ(n)),l(e=>({...e,messages:e.messages.filter(e=>e.id!==a)})),e("failed"))})})},[D,V,G]),Q=(0,a.useCallback)(async(e,t,n,a,s,i,r)=>{try{K("contacting");let o=await (0,j.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:tJ([o.chat,...e.chats.filter(e=>e.id!==o.chat.id)]),messages:[...e.messages.filter(e=>e.id!==a),...Array.from(o.messages)]})),tX(o.chat),b(o.memory),"completed"}catch(n){if(n instanceof DOMException&&"AbortError"===n.name)return"cancelled";f(tQ(n));try{let n=await (0,j.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]),J=(0,a.useCallback)(async(e,t,a,l,s,i,r)=>{if(n.models.find(e=>e.id===s)?.streaming!==!0)return Q(e,t,a,l,s,i,r);K("contacting");try{return await Y(e,t,a,l,s,i,r)}catch(e){if(!(e instanceof j.StreamingUnavailableError))throw e}return Q(e,t,a,l,s,i,r)},[n.models,Q,Y,K]),X=(0,a.useCallback)(async(e,t,n,a,s,i)=>{v(void 0);try{K("contacting");let t=await (0,j.askGrounded)({chatId:e.id,content:n,modelId:s},i);if(S.current!==e.id)return"completed";if(i.aborted)return"cancelled";v(t),b(void 0);let[a,r]=await Promise.all([(0,j.fetchChatMessages)(e.id,e.projectPath),(0,j.fetchChats)(e.projectPath)]),o=r.chats.find(t=>t.id===e.id);return l(e=>({...e,messages:Array.from(a.messages),chats:tJ(r.chats),activeChat:o??e.activeChat})),void 0!==o&&tX(o),"completed"}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return"cancelled";return f(tQ(e)),l(e=>({...e,messages:e.messages.filter(e=>e.id!==a)})),"failed"}},[K]),Z=(0,a.useCallback)(()=>{t_(h.current)&&(m.current?.abort(),m.current=null,K("cancelled"))},[K]),ee=(0,a.useCallback)(async()=>{if(t_(h.current))return;let e=s.trim(),t=n.activeChat,a=n.activeProject,r=t0(n.selectedModel,n.models);if(0===e.length||void 0===t||void 0===a||void 0===r)return;if(tY(tk({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(tU);if(t1(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;m.current=c,b(void 0);try{let n=t1(t),{entries:l,disclosures:s}=n?{entries:[],disclosures:[]}:await P(),i=n?await X(t,a,e,o.id,r,c.signal):await J(t,a,e,o.id,r,c.signal,l);"cancelled"===h.current||K(i),"completed"===i&&(M(),T(s))}finally{m.current=null}},[s,n.activeChat,n.activeProject,n.selectedModel,n.models,n.messages,E,X,J,P,M,K]),et=(0,a.useCallback)(()=>{v(void 0),b(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!==x&&x.context.enabled?x.context.text.length:0;return tk({modelContextWindow:e.contextWindow,modelMaxOutputTokens:e.maxOutputTokens,userDraftText:s,conversationHistory:t,repoContextPackBytes:a,knowledgeCapsuleBytes:l,memoryContextBytes:i})},[n.models,n.selectedModel,n.messages,s,g,x,y]),ea=(0,a.useCallback)(async e=>{if(t_(h.current))return{ok:!1,reason:"request-failed",message:"A request is already in flight."};let t=e.text.trim();if(0===t.length)return{ok:!1,reason:"missing-input"};let 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||!eZ(i))return{ok:!1,reason:"not-workflow-eligible"};let r=ty(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,j.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=tQ(t);return f(e),{ok:!1,reason:"request-failed",message:e}}},[n.activeChat,n.activeProject,n.models]),el=(0,a.useCallback)(async e=>{if(t_(h.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,j.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=tQ(t);return f(e),{ok:!1,reason:"request-failed",message:e}}},[n.activeChat]),es=(0,a.useCallback)(e=>{tX(e),l(t=>({...t,chats:t.chats.map(t=>t.id===e.id?e:t),activeChat:t.activeChat?.id===e.id?e:t.activeChat}))},[]);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===t0(n.selectedModel,n.models),draft:s,loading:r,sending:u,sendStatus:c,error:p,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:q,clearPendingAttachments:M,lastSentDocuments:$,budget:en,memoryEnabled:y,setMemoryEnabled:w,memoryBudgetTokens:k,setMemoryBudgetTokens:N,latestMemory:x,clearLatestMemory:L,acceptMemoryCandidate:F,rejectMemoryCandidate:z,forgetMemoryAction:O,clearHistory:et,launchWorkflowFromConversation:ea,launchGroundedWorkflowHandoff:el}}let t6="keiko.theme",t5="dark";var t8=e.i(66702);let t9=["agent","capsule","capsule-set","chat","connector","data-source","evidence-run","mcp-tool","memory","patch-proposal","skill","tool","workflow-run","workspace-path"],t7=["capsule","capsule-set","chat","evidence-run","memory","patch-proposal","tool","workflow-run","workspace-path"],ne=["reads-context","proposes-patch","uses-tool","starts-workflow","produces-evidence","references-document","depends-on"],nt=["draft","active","archived","superseded","revoked","blocked","stale"],nn={"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"}},na=["prompt","documentcontent","filecontent","toolstdout","toolstderr","secret","credential","apikey","password","token"],nl="Unable to reach the local backend. Check that the Keiko server is running (keiko ui).";class ns 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 ni(e){let t;try{t=await e.json()}catch{throw new ns("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 ns(l,s,e.status,i)}return t}function nr(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 no(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:nr({}),body:JSON.stringify(t)});return{decision:(await ni(n)).decision}}async function nc(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:nr({idempotencyKey:t}),body:JSON.stringify(n)}),l=await ni(a);return{relationship:l.relationship,etag:l.etag}}async function nd(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 ni(n);return{entries:a.entries,truncated:a.truncated,nextCursor:a.nextCursor}}async function nu(e){let t=await fetch(`/api/relationships/${encodeURIComponent(e)}`);return(await ni(t)).relationship}async function nh(e,t,n,a){let l=await fetch(`/api/relationships/${encodeURIComponent(e)}`,{method:"PATCH",headers:nr({idempotencyKey:a,ifMatch:n}),body:JSON.stringify({schemaVersion:"1",...t})}),s=await ni(l);return{relationship:s.relationship,etag:s.etag}}async function nm(e,t,n){let a=await fetch(`/api/relationships/${encodeURIComponent(e)}`,{method:"DELETE",headers:nr({idempotencyKey:n,ifMatch:t})});return(await ni(a)).relationship}async function np(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 ni(a)).report}async function nf(e){return ni(await fetch(`/api/relationships/${encodeURIComponent(e)}/explain`))}async function ng(){return ni(await fetch("/api/relationships/health"))}let nv=[{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 nx(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 nb(e){let t=[...e.mod].sort();return`${t.join("+")}|${e.key.toLowerCase()}`}let ny={undoStack:[],redoStack:[]};class nj extends Error{conflicts;constructor(e){super(`Workspace keyboard shortcut conflicts detected: ${e.map(e=>`${nb(e.chord)} (${e.commandIds.join(", ")})`).join("; ")}`),this.name="WorkspaceShortcutConflictError",this.conflicts=e}}class nw extends Error{reserved;constructor(e){super(`Workspace keyboard shortcut bindings refused: ${e.map(e=>`${e.commandId} → ${nb(e.chord)}`).join("; ")} are browser-reserved`),this.name="WorkspaceShortcutReservedError",this.reserved=e}}let nk=[{commandId:"undo",chord:{key:"z",mod:["cmd"]}},{commandId:"redo",chord:{key:"z",mod:["cmd","shift"]}},{commandId:"focus-status",chord:{key:"s",mod:["alt"]}}];var nN=e.i(57688);let nS="cmp-budget-exceeded-alert",nC={low:"Low",moderate:"Moderate",high:"High",exceeded:"Exceeded"},nI={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"},nE="Token counts are approximate. Actual model usage may vary.";function nR(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toString()}function n$({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,h=nR(e.approximateTokens),m=nR(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: ${h} / ${m} tokens`:`Approximate context: ${h} tokens`}),u?(0,n.jsx)("span",{className:nI[p],"aria-label":`Context pressure: ${nC[p]}`,children:nC[p]}):null,(0,n.jsx)("span",{className:"cmp-budget-info",role:"img",tabIndex:0,"aria-label":nE,"data-tip":nE,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:nS,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 nT(e){return e<1024?`${e.toString()} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function nA(e){if(e<1e3)return`${e.toString()} ms`;if(e<6e4)return`${(e/1e3).toFixed(1)} s`;let t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${t.toString()}m ${n.toString()}s`}function nq(e){return({running:"Running",completed:"Completed","dry-run":"Dry run",rejected:"Rejected",cancelled:"Cancelled",failed:"Failed","fix-applied":"Fix applied","fix-proposed":"Fix proposed","investigation-only":"Investigation only"})[e]??e}function nM(e){return e<1e3?e.toString():`${(e/1e3).toFixed(1)}k`}function nP(e){return Number.isFinite(e)?String(e):"—"}function nL(e,t){return Number.isFinite(e)?t(e):"—"}function nD(e){return e.toLocaleString("en-US")}function nF(e){return e.replaceAll("-"," ")}function nz({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 nO({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`${nF(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)(nz,{label:"Searched",value:`${String(t.searchCalls)} / ${nP(a.searchCallsMax)} searches`}),(0,n.jsx)(nz,{label:"Read",value:`${String(t.filesRead)} / ${nP(a.filesReadMax)} files`}),(0,n.jsx)(nz,{label:"Bytes",value:`${nT(t.excerptBytes)} / ${nL(a.excerptBytesMax,nT)}`}),(0,n.jsx)(nz,{label:"Input",value:`${nD(t.modelInputTokens)} / ${nL(a.modelInputTokensMax,nD)} tokens`}),(0,n.jsx)(nz,{label:"Output",value:`${nD(t.modelOutputTokens)} / ${nL(a.modelOutputTokensMax,nD)} tokens`}),(0,n.jsx)(nz,{label:"Rerank",value:`${String(t.rerankCalls)} / ${nP(a.rerankCallsMax)} calls`}),(0,n.jsx)(nz,{label:"Time",value:`${nA(e.elapsedMs)} / ${nL(a.elapsedMsMax,nA)}`}),(0,n.jsx)(nz,{label:"Query",value:nF(e.queryKind)})]})]})}function nK({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 nB({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)(nK,{score:e.score})]})}function n_({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 nU({citations:e}){let[t,l]=(0,a.useState)(!1);if(0===e.length)return null;let s=[...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)(nB,{citation:e})},e.stableId))}),(0,n.jsx)(n_,{total:s.length,expanded:t,onToggle:()=>{l(e=>!e)}})]})}function nW({citations:e}){let[t,l]=(0,a.useState)(!1);if(0===e.length)return null;let s=[...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)(nK,{score:e.score})]})},e.stableId))}),(0,n.jsx)(n_,{total:s.length,expanded:t,onToggle:()=>{l(e=>!e)}})]})}function nH({markers:e}){if(0===e.length)return null;let t=Array.from(new Set(e.map(e=>nF(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:`${nF(e.kind)}: ${e.claim}`},`${e.kind}-${String(t)}`))})]})}function nG({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])=>`${nF(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 nV=[{reason:"size-exceeded",label:"larger than 2 MB"},{reason:"binary",label:"binary or an unsupported format"},{reason:"tool-unavailable",label:"unreadable"}];function nY({omittedCounts:e}){let t=nV.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.`})]})}function nQ({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 nJ({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)(nz,{label:"Mode",value:nF(e.scopeKind)}),(0,n.jsx)(nz,{label:"Capsules",value:String(e.capsuleCount)}),(0,n.jsx)(nz,{label:"Sources",value:String(e.sourceCount)}),(0,n.jsx)(nz,{label:"Citations",value:String(e.citationCount)}),(0,n.jsx)(nz,{label:"Context budget",value:`${String(e.referencesUsed)} / ${String(e.referenceBudget)} references`})]})]})}function nX({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)(nO,{contextPack:e.folder}),(0,n.jsx)(nJ,{contextPack:e.knowledge})]})}function nZ({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)(nW,{citations:e.citations}),(0,n.jsx)(nH,{markers:e.uncertainty}),(0,n.jsx)(nJ,{contextPack:e.contextPack})]}):"hybrid"===e.groundingKind?(0,n.jsxs)("div",{className:"grounded-answer",children:[(0,n.jsx)(nY,{omittedCounts:e.contextPack.folder.omittedCounts}),(0,n.jsx)(nU,{citations:e.citations}),(0,n.jsx)(nW,{citations:e.knowledgeCitations}),(0,n.jsx)(nH,{markers:e.uncertainty}),(0,n.jsx)(nG,{omittedCount:e.omittedCount,omittedCounts:e.contextPack.folder.omittedCounts}),(0,n.jsx)(nQ,{runId:e.evidenceRunId,runIds:e.evidenceRunIds}),(0,n.jsx)(nX,{contextPack:e.contextPack})]}):(0,n.jsxs)("div",{className:"grounded-answer",children:[(0,n.jsx)(nY,{omittedCounts:e.contextPack.omittedCounts}),(0,n.jsx)(nU,{citations:e.citations}),(0,n.jsx)(nH,{markers:e.uncertainty}),(0,n.jsx)(nG,{omittedCount:e.omittedCount,omittedCounts:e.contextPack.omittedCounts}),(0,n.jsx)(nQ,{runId:e.evidenceRunId,runIds:e.evidenceRunIds}),(0,n.jsx)(nO,{contextPack:e.contextPack})]})}var n0=a;let n1=["<script","</script","<iframe","</iframe","<object","</object","<embed","</embed","<style","</style","<svg","</svg","<form","</form","<meta","<link","<base"],n2=[" ","\n"," ","'",'"'];function n4(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 n1)if(t.includes(e))return!0;let n=0;for(;n<t.length-4;){let e=t[n];if(n2.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 n3(e,t,n,a){a>n&&e.push({kind:"text",text:t.slice(n,a)})}function n6(e){return void 0!==e&&/[A-Za-z0-9]/.test(e)}let n5=new Set([" "," ","\n","<",">",'"']),n8=new Set([".",",",")","]","!","?"]);function n9(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:(n3(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;n3(e,t,a,n);let o=t.slice(n+2,r);return e.push({kind:"strong",children:n9(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&&n6(t[n-1])&&n6(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&&n6(t[i-1])&&n6(t[i+1])?-1:(n3(e,t,a,n),e.push({kind:"em",children:n9(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 n3(e,t,a,n),((l=o.trim().toLowerCase()).startsWith("http://")||l.startsWith("https://"))&&!n4(r)&&!n4(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&&!n5.has(e[n]??"");)n++;for(;n>t&&n8.has(e[n-1]??"");)n--;return n}(t,n);if(i-n<=(l?8:7))return -1;let r=t.slice(n,i);return n3(e,t,a,n),e.push({kind:"link",text:r,href:r}),i}(n,e,a,l))){l=s,a=s;continue}a++}return n3(n,e,l,e.length),n}function n7(e){let t=e.trim(),n=t.startsWith(":"),a=t.endsWith(":");return n&&a?"center":a?"right":n?"left":void 0}function ae(e){let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|")}function at(e){let t=/^( *)([*+\-]) (.*)$/.exec(e);return t?{match:!0,indent:t[1]?.length??0,text:t[3]??""}:{match:!1}}function an(e){let t=/^( *)\d+\. (.*)$/.exec(e);return t?{match:!0,indent:t[1]?.length??0,text:t[2]??""}:{match:!1}}function aa(e){return e.includes("|")}function al(e){let t=e.trim();return/^(-{3,}|\*{3,}|_{3,})$/.test(t)}function as(e,t){let n=[],a=t?an:at;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=[...n9(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 ai({text:e}){let[t,a]=(0,n0.useState)(!1),[l,s]=(0,n0.useState)(""),i=(0,n0.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 ar={1:"h3",2:"h4",3:"h5",4:"h6",5:"h6",6:"h6"},ao={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 ac(e,t){return void 0===e.children?null:e.children.map((e,n)=>ad(e,t+"-"+String(n)))}function ad(e,t){let a=function(e,t){switch(e.kind){case"paragraph":return(0,n.jsx)("p",{className:"sm-p",children:ac(e,t)},t);case"heading":{let a=e.level??1,l=ar[a],s=ao[a];return(0,n.jsx)(l,{className:s,children:ac(e,t)},t)}case"blockquote":return(0,n.jsx)("blockquote",{className:"sm-blockquote",children:ac(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)(ai,{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:ac(e,t)},t);case"ol":return(0,n.jsx)("ol",{className:"sm-ol",children:ac(e,t)},t);case"li":return(0,n.jsx)("li",{className:"sm-li",children:ac(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:ac(e,t)})},t);case"thead":return(0,n.jsx)("thead",{children:ac(e,t)},t);case"tbody":return(0,n.jsx)("tbody",{children:ac(e,t)},t);case"tr":return(0,n.jsx)("tr",{children:ac(e,t)},t);case"th":return(0,n.jsx)("th",{style:a,children:ac(e,t)},t);case"td":return(0,n.jsx)("td",{style:a,children:ac(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:ac(e,t)},t);case"em":return(0,n.jsx)("em",{children:ac(e,t)},t);default:return null}}(e,t);return null!==i?i:null}function au({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:n9(s)}),e.i++,!0}(t,a,n))return;if(al(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(aa(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}(ae(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()||!aa(t.trim()))break;s.push(t),e.i++}return n=ae(t),a=ae(l).map(n7),{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:n9(e.trim())},void 0!==n?{...l,align:n}:l})}]},{kind:"tbody",children:s.map(e=>({kind:"tr",children:ae(e).map((e,t)=>{var n;let l;return n=a[t],l={kind:"td",children:n9(e.trim())},void 0!==n?{...l,align:n}:l})}))}]}}(t,a)),1)||(at(a).match?(n.push(as(t,!1)),!0):!!an(a).match&&(n.push(as(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))||!!at(e).match||!!an(e).match||al(e)}(n))break;t.push(n),e.i++}return 0===t.length?null:{kind:"paragraph",children:n9(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)=>ad(e,String(t)))})}class ah extends n0.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)(au,{source:this.props.source})}}function am({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)(w.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)(w.Icons.close,{size:12})})]})}function ap({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)(am,{attachment:e,onRemove:t},e.id))})}function af({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 ag="cmp-attach-disabled-hint";function av({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:ag,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:ag,title:i?"Attach file":"Attachments not supported by this model",onClick:o,children:(0,n.jsx)(w.Icons.files,{size:16})})]})}function ax({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 ab({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 ay({selectedModel:e,launch:t}){let[l,s]=(0,a.useState)(!1),i=(0,a.useRef)(null);return void 0!==e&&eZ(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)(w.Icons.spark,{size:14,style:{color:"var(--accent)"}})," Launch workflow",(0,n.jsx)(w.Icons.chevron,{size:12})]}),l?(0,n.jsx)(aw,{modelId:e.id,launch:t,onClose:()=>{s(!1),i.current?.focus()}}):null]}):null}function aj(e){return Array.from(e.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'))}function aw({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,h]=(0,a.useState)(!1),[m,p]=(0,a.useState)(),f=(0,a.useRef)(null),g=void 0===r?void 0:ty(r);async function v(){if(void 0===g||0===c.trim().length)return;h(!0),p(void 0);let n=await t({workflowId:g.workflowId,modelId:e,text:c});(h(!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=aj(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 x=(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:tb.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!==m?(0,n.jsx)("div",{role:"alert",className:"wf-dialog-error",children:m}):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)(w.Icons.close,{size:14})})]})});return"u"<typeof document?x:(0,eV.createPortal)(x,document.body)}let ak=[{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."}],aN=["verify","lint","typecheck","tests","manual"];function aS(e){return e.split(/\r?\n|,/).map(e=>e.trim()).filter(e=>e.length>0)}function aC({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)(w.Icons.spark,{size:14,style:{color:"var(--accent)"}})," Launch grounded workflow",(0,n.jsx)(w.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)(aI,{answer:e,modelId:t,launch:s,onClose:()=>{r(!1),o.current?.focus()}}):null]})}function aI({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"),[h,m]=(0,a.useState)(""),[p,f]=(0,a.useState)(""),[g,v]=(0,a.useState)(""),[x,b]=(0,a.useState)(""),[y,j]=(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=aS(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=aS(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=aS(s);return{ok:!0,input:0===i.length?{}:{targetFiles:i}}}(o,d,h,p,g,x);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:aS(y),expectedChecks:S,unknowns:aS(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=aj(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=ak.find(e=>e.workflowKind===o),q=(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:ak.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:h,onChange:e=>m(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:x,onChange:e=>b(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=>j(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:aN.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)(w.Icons.close,{size:14})})]})});return"u"<typeof document?q:(0,eV.createPortal)(q,document.body)}function aE(e){return"system"===e.role&&"string"==typeof e.runId}function aR({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)(w.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 a$({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 aT=e.i(61593);let aA="cmp-no-model-alert",aq="cmp-send-hint",aM="cmp-loading-status",aP="Ask Keiko about your code…",aL="Send message — Enter to send, Shift+Enter for a new line";function aD(e){return t=>{!t.nativeEvent.isComposing&&("Enter"!==t.key||t.shiftKey||(t.preventDefault(),e()))}}let aF=/\s*[[【[]\d+[\]】]]/g;function az({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(aF,"")).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 aO({message:e}){let t,a;if(aE(e))return(0,n.jsx)(aR,{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)(aK,{}),l?e.content:(0,n.jsx)(ah,{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)(az,{content:e.content})]})]})})}function aK({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)(nN.default,{src:"/assets/keiko-logo.svg",width:22,height:22,alt:"","aria-hidden":"true"})})}function aB(){return(0,n.jsx)("article",{className:"chat-msg","data-role":"assistant",children:(0,n.jsxs)("div",{className:"chat-msg-bubble",children:[(0,n.jsx)(aK,{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 a_({session:e,ready:t,selectedModelCapability:a,onAttachFiles:l,budgetExceeded:s}){let{models:i,selectedModel:r,setSelectedModel:o,draft:c,noEligibleModels:d,loading:u,sending:h,cancelSend:m,launchWorkflowFromConversation:p}=e,f=d||s||!t,g=0===c.trim().length,v=d?aA:void 0,x=d?aA:s?nS:u?aM:g?aq:void 0,b=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)(av,{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:b,children:[(0,n.jsx)(w.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:b,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)(w.Icons.chevron,{size:12})]}),(0,n.jsx)(ay,{selectedModel:a,launch:p}),null,x===aq?(0,n.jsx)("span",{id:aq,className:"sr-only",children:"Type a message to send"}):null,h?(0,n.jsx)("button",{type:"button",className:"cmp-send cmp-send-cancel","data-on":!0,"aria-label":"Cancel response",title:"Cancel response",onClick:m,children:(0,n.jsx)(w.Icons.close,{size:16})}):(0,n.jsx)("button",{type:f?"button":"submit",className:"cmp-send","data-on":!f,"aria-disabled":f,"aria-describedby":x,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":aL,"aria-label":"Send message",children:(0,n.jsx)(w.Icons.arrowUp,{size:16})})]})}function aU(){return(0,n.jsx)("div",{id:aA,role:"alert",className:"gw-error cmp-no-model",children:"No conversation-eligible model is configured. Connect a gateway in Settings to enable chat."})}function aW(){return(0,n.jsxs)("div",{id:aM,role:"status",className:"cmp-loading-status",children:[(0,n.jsx)("span",{className:"cmp-loading-dot","aria-hidden":"true"}),"Connecting to your gateway…"]})}function aH({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 aG({session:e,ready:t,placeholder:l}){let{draft:s,loading:i,sending:r,sendStatus:o,setDraft:c,sendMessage:d,models:u,selectedModel:h,pendingAttachments:m,addPendingAttachment:p,removePendingAttachment:f,budget:g,clearHistory:v}=e,x=tY(g),b=(0,a.useRef)(null);(0,a.useEffect)(()=>{let e=b.current;null!==e&&(e.style.height="auto",e.style.height=`${String(Math.min(e.scrollHeight,220))}px`)},[s]);let[y,j]=(0,a.useState)(),[w,k]=(0,a.useState)(),N=u.find(e=>e.id===h),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)}j(t),k(n)},[p]);return(0,n.jsxs)("div",{className:"cmp-box",children:[(0,n.jsx)(af,{enabled:S,onFiles:C}),(0,n.jsx)(ap,{attachments:m,onRemove:f}),(0,n.jsx)("textarea",{className:"cmp-input",ref:b,rows:2,value:s,"aria-label":"Chat message",placeholder:l,onChange:e=>c(e.target.value),onKeyDown:aD(d)}),(0,n.jsx)(ax,{reason:y,mimeType:w}),(0,n.jsx)(aH,{status:o}),(0,n.jsx)(n$,{budget:g,onClearHistory:v,disabled:r||i}),(0,n.jsx)(a_,{session:e,ready:t,selectedModelCapability:N,onAttachFiles:C,budgetExceeded:x})]})}function aV({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)(w.Icons.spark,{size:12,style:{color:"var(--accent)"}}),e]},e))})]})}function aY(){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)(w.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 aQ({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:aD(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)(w.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:aL,children:(0,n.jsx)(w.Icons.arrowUp,{size:16})})]}),(0,n.jsx)(aH,{status:i})]})}function aJ(e){return(void 0!==e.connectedScopes?e.connectedScopes.length:+(void 0!==e.connectedScope))+(void 0!==e.localKnowledgeScopes?e.localKnowledgeScopes.length:+(void 0!==e.localKnowledgeScope))}function aX(e){if(aJ(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}`:a0(e)?"files":"none"}function aZ(e){return void 0!==e.localKnowledgeScopes?e.localKnowledgeScopes:void 0!==e.localKnowledgeScope?[e.localKnowledgeScope]:[]}function a0(e){return void 0!==e&&(void 0!==e.connectedScope||void 0!==e.connectedScopes&&e.connectedScopes.length>0)}function a1(e){return a0(e)||void 0!==e&&(void 0!==e.localKnowledgeScope||void 0!==e.localKnowledgeScopes&&e.localKnowledgeScopes.length>0)}function a2(e){return tC(e,"Unable to update knowledge scope.")}function a4({chat:e,onChatChanged:t,catalog:l,connected:s}){let{capsules:i,capsuleSets:r,loadError:o}=l,[c,d]=(0,a.useState)(!1),[u,h]=(0,a.useState)(null),m=(0,a.useRef)(null);async function p(n){d(!0),h(null);try{if("none"===n){let n=aJ(e);if(n>0&&!window.confirm(`This will disconnect ${String(n)} grounding ${1===n?"source":"sources"}. Continue?`)){null!==m.current&&(m.current.value=aX(e));return}let a=await (0,j.updateChat)(e.id,{connectedScopes:null,localKnowledgeScopes:null});t(a.chat);return}if("files"===n){let n=await (0,j.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=aZ(e),s=l.some(e=>"capsule-set"===e.kind&&e.capsuleSetId===a.capsuleSetId)?l:[...l,a],i=await (0,j.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=aZ(e),s=l.some(e=>"capsule"===e.kind&&e.capsuleId===a.capsuleId)?l:[...l,a],i=await (0,j.updateChat)(e.id,{localKnowledgeScopes:s});t(i.chat)}}catch(e){h(a2(e))}finally{d(!1)}}let f=aX(e),g=function(e,t){let n=t.map(e=>({value:`capsule:${e.id}`,label:`Knowledge capsule: ${e.displayName}`})),a=aX(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=aX(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),x=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:m,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:!a0(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!==x?(0,n.jsx)("span",{role:"alert",className:"scope-connect-error",children:x}):null]})}function a3({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,aT.fetchCapsules)(),(0,aT.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(a2(a.reason)))}catch(t){e||i(a2(t))}}(),()=>{e=!0}},[]),{capsules:e,capsuleSets:n,loadError:s}}(),s=a1(e);return(0,n.jsx)("div",{className:"chat-scope-header","data-grounded":s?"true":"false",children:(0,n.jsx)(a4,{chat:e,onChatChanged:t,catalog:l,connected:s})})}function a6({chat:e,answer:t,busy:a,selectedModelId:l,launchGroundedWorkflowHandoff:s}){return void 0!==e&&a1(e)&&(void 0!==t||a)?(0,n.jsxs)("div",{className:"chatw-grounded",children:[(0,n.jsx)(nZ,{answer:t,busy:a}),(0,n.jsx)(aC,{answer:t,modelId:l,busy:a,launch:s})]}):null}function a5({action:e,acceptCandidate:t,rejectCandidate:l,forgetMemoryAction:s,onActionSettled:i}){let[r,o]=(0,a.useState)(!1),[c,d]=(0,a.useState)(),[u,h]=(0,a.useState)(!1),m=(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:()=>{m(()=>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:()=>{m(()=>l(e.proposalId),"MemoriaViva proposal rejected.","Unable to reject memory.")},children:"Reject"})]}),void 0!==c?(0,n.jsx)("div",{role:"alert",className:"cmp-err",children:c}):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=()=>{m(()=>s(e.memoryId).then(()=>h(!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),h(!1))},children:"Cancel"})]}):(0,n.jsx)("button",{type:"button","aria-disabled":r,"aria-busy":r,onClick:()=>{r||(d(void 0),h(!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)("div",{role:"alert",className:"cmp-err",children:c}):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 a8({memoryEnabled:e,setMemoryEnabled:t,memoryBudgetTokens:l,setMemoryBudgetTokens:s,latestMemory:i,acceptCandidate:r,rejectCandidate:o,forgetMemoryAction:c}){let[d,u]=(0,a.useState)(!1),[h,m]=(0,a.useState)(""),p=(0,a.useId)(),f=`${p}-chat-memory-disclosure`,g=(0,a.useRef)(null),v=(0,a.useCallback)(e=>{m(e),g.current?.focus()},[]),x=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)(a$,{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:x>0?`${String(x)} 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)(a5,{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:h})]}):null]})}function a9({mini:e=!1}){let t=i(),{messages:l,draft:s,loading:r,sending:o,sendStatus:c,error:d,noEligibleModels:u,selectedModel:h,sendMessage:m,cancelGrounded:p,activeChat:f,replaceChat:g,latestGrounded:v,latestMemory:x,lastSentDocuments:b,memoryEnabled:y,setMemoryEnabled:j,memoryBudgetTokens:w,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||aE(e)),$=(0,a.useRef)(null),T=(0,a.useRef)(!0),A=(0,a.useRef)(!1),q=R.length>0?R[R.length-1]:void 0,M=void 0===q?"":q.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,M]),e)?(0,n.jsxs)("div",{className:"chatw chatw-mini",children:[void 0!==f?(0,n.jsx)(a3,{chat:f,onChatChanged:g}):null,u?(0,n.jsx)(aU,{}):null,(0,n.jsx)(aQ,{session:t,ready:E}),void 0!==d?(0,n.jsx)("div",{role:"alert",className:"cmp-err",children:d}):null]}):(0,n.jsxs)("div",{className:"chatw",children:[void 0!==f?(0,n.jsx)(a3,{chat:f,onChatChanged:g}):null,void 0!==f?(0,n.jsx)(a8,{memoryEnabled:y,setMemoryEnabled:j,memoryBudgetTokens:w,setMemoryBudgetTokens:k,latestMemory:x,acceptCandidate:N,rejectCandidate:S,forgetMemoryAction:I}):null,u?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsx)(aU,{})}):null,r?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsx)(aW,{})}):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)(aV,{session:t,noEligibleModels:u}):(0,n.jsx)(aY,{}):(0,n.jsxs)("div",{className:"chatw-log",children:[R.map(e=>(0,n.jsx)(aO,{message:e},e.id)),o&&"streaming"!==c?(0,n.jsxs)("div",{className:"chatw-typing-row",children:[(0,n.jsx)(aB,{}),a1(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)(a6,{chat:f,answer:v,busy:o,selectedModelId:h,launchGroundedWorkflowHandoff:C}),(0,n.jsx)(ab,{documents:b})]})}),R.length>0?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsxs)("form",{className:"composer",onSubmit:e=>{e.preventDefault(),m()},children:[(0,n.jsx)(aG,{session:t,ready:E,placeholder:aP}),void 0!==d?(0,n.jsx)("div",{role:"alert",className:"cmp-err",children:d}):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(),m()},children:[(0,n.jsx)(aG,{session:t,ready:E,placeholder:r?"Connecting to your gateway…":aP}),void 0!==d?(0,n.jsx)("div",{role:"alert",className:"cmp-err",children:d}):null]})}):null,0===R.length&&void 0!==d&&void 0===f?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsx)("div",{role:"alert",className:"cmp-err",children:d})}):null]})}let a7=new Set(["ArrowDown","ArrowUp","ArrowRight","ArrowLeft","Home","End"]);function le(e){return Array.from(e.querySelectorAll("button[role='treeitem']"))}function lt({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),h=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} (${h})`,tabIndex:c?0:-1,onClick:()=>{u(e=>!e),i(e),null!==o.current&&le(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)(w.Icons.chevronR,{size:13})}),(0,n.jsx)(w.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:h})]}),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 ln(){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=>{a7.has(e.key)&&null!==t.current&&function(e,t){let n=le(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)(lt,{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 la({openChatWindow:e}){let t=i(),[l,s]=(0,a.useState)(""),[r,o]=(0,a.useState)("active"),[c,d]=(0,a.useState)(null),[u,h]=(0,a.useState)(""),[m,p]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),[v,x]=(0,a.useState)(null),[b,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()=>{x(null);let n=await t.openNewChat(void 0,"New chat");void 0!==n&&e(n)},A=e=>{d(e.id),h(e.title),p(null),x(null),y(null)},q=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),x(null),y(null);try{let a=await (0,j.updateChat)(e.id,{title:n});t.replaceChat(a.chat),d(null)}catch{x("Rename failed.")}finally{g(null)}},M=async e=>{g(e.id),x(null);try{let n=await (0,j.updateChat)(e.id,{status:"closed"});t.replaceChat(n.chat),p(null),o("deleted")}catch(t){let e=t instanceof Error?t.message:"Request failed.";x(`Delete failed: ${e}`)}finally{g(null)}},P=async e=>{g(e.id),x(null);try{let n=await (0,j.updateChat)(e.id,{status:"open"});t.replaceChat(n.chat),p(null),o("active")}catch(t){let e=t instanceof Error?t.message:"Request failed.";x(`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)(w.Icons.newChat,{size:15}),"New"]})]}),(0,n.jsxs)("label",{className:"chat-history-search",children:[(0,n.jsx)(w.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=eN(t).length+eS(t).length,s=c===t.id,i=m===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!==b,"aria-describedby":null!==b?I:void 0,onChange:e=>{h(e.target.value),null!==b&&y(null)},onKeyDown:e=>{"Enter"===e.key&&q(t),"Escape"===e.key&&(d(null),y(null))}}),null!==b?(0,n.jsx)("span",{id:I,className:"chat-history-rename-error",role:"alert",children:b}):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 q(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 M(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 P(t),children:[(0,n.jsx)(w.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 ll(){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)(w.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 ls=[{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}],li=[{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 lr({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=w.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 lo(){let[e,t]=(0,a.useState)(ls.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,"/",ls.length," active"]})]}),ls.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)(lr,{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"})}),li.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)(lr,{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)(w.Icons.check,{size:13})}):(0,n.jsx)("span",{className:"integ-add",children:(0,n.jsx)(w.Icons.plus,{size:14})})]},e.name))]})}let lc=[{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}],ld="keiko.automations.v1",lu=Object.fromEntries(lc.map(e=>[e.id,e.defaultOn]));function lh(){try{let e=localStorage.getItem(ld);if(null===e)return{...lu};let t=JSON.parse(e);if("object"!=typeof t||null===t||Array.isArray(t))return{...lu};let n={...lu};for(let[e,a]of Object.entries(t))e in lu&&"boolean"==typeof a&&(n[e]=a);return n}catch{return{...lu}}}function lm(){let[e,t]=(0,a.useState)(lh);return(0,n.jsx)("div",{className:"tw-list",children:lc.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)(a$,{on:l,onChange:()=>{var e;e=a.id,t(t=>{let n={...t,[e]:!t[e]};try{localStorage.setItem(ld,JSON.stringify(n))}catch{}return n})},label:a.name})]},a.id)})})}function lp(){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)(w.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 lf(){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=w.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:et[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:et[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:et[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:et[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 lg=[{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 lv(){return(0,n.jsx)("ul",{className:"tw-list",children:lg.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 lx(){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 lb="keiko-activity",ly={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 lj(){let e=function(){let[,e]=(0,a.useState)(0);return(0,a.useEffect)(()=>{let t=()=>{e(e=>e+1)};return window.addEventListener(lb,t),()=>{window.removeEventListener(lb,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:ly[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 lw({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)(w.Icons.file,{size:14})})}let lk={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 lN(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":lk[a]??"code"}let lS=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 lC(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 lI(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]??""],...lC(e.slice(t[0].length))]:lC(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";lS.has(t)||lS.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 lE(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 lR(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e))}function l$({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 lT({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),[h,m]=(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,j.fetchFilesPreview)(e,t).then(e=>{n||r(e)}).catch(e=>{n||u(e instanceof j.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,h]);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"),x=i?.kind==="text"&&i.content.length<=2e5,b=void 0!==s&&i?.kind==="text"&&!i.truncated,y=i?.kind==="text"?x?lI(i.content,lN(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)(w.Icons.back,{size:15})}),(0,n.jsx)(lw,{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"}),b?(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)(w.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)(w.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:()=>m(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 ",lE(i.maxBytes),". Larger files can't be shown in full here."]}):null,x?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)(l$,{label:"Type",value:i.mime}),(0,n.jsx)(l$,{label:"Size",value:lE(i.sizeBytes)}),(0,n.jsx)(l$,{label:"Modified",value:lR(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)(lw,{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 ${lE(i.maxBytes??0)}.`:"No safe text or image preview is available for this file type."}),(0,n.jsxs)("div",{className:"fpv-meta",children:[(0,n.jsx)(l$,{label:"Type",value:i.mime}),(0,n.jsx)(l$,{label:"Extension",value:i.extension??"none"}),(0,n.jsx)(l$,{label:"Size",value:lE(i.sizeBytes)}),(0,n.jsx)(l$,{label:"Modified",value:lR(i.modifiedAt)})]})]})}):null]})}function lA(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 lq(e){return 8+18*e}let lM=new Set(["ArrowDown","ArrowUp","ArrowRight","ArrowLeft","Home","End"]);function lP({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,h]=(0,a.useState)(null),[m,p]=(0,a.useState)(""),[f,g]=(0,a.useState)(null),[v,x]=(0,a.useState)(null),[b,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,j.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,j.fetchFilesTree)(d,e);""===e&&(h(t.root),I.current?.(null,t.root,null),x(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),x(null),I.current?.(null,null,null),h(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 q=(0,a.useCallback)(e=>{let t=e.trim();void 0===l||0===t.length||t!==A&&l(t)},[l,A]),M=(0,a.useCallback)(e=>{g(null),x(e),I.current?.(null,u??d,e),null!==e&&void 0===b[e]&&T(e)},[d,b,T,u]),P=(0,a.useCallback)(()=>{if(null!==v)return void M(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=lA(u??d);null!==e&&q(e)},[d,v,M,q,u]),L=(e,t,a=b[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:lq(t)+18},children:"Loading…"}):null,a?.notice==="no-root"?(0,n.jsx)("div",{className:"files-note",role:"status",style:{paddingLeft:lq(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:lq(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:lq(t)+18},children:["Showing only the first ",a.entries.length," entries — this folder contains more."]}):null,a?.entries.map(e=>((e,t)=>{let a=lq(t),l=k.has(e.path),s="This link can't be opened from this folder.";if("directory"===e.kind){let i=b[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!==b[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)(w.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&&M(e.path)},title:e.readable?e.path:s,children:[(0,n.jsx)("span",{className:"fi-fallback",style:{color:"var(--accent)"},children:(0,n.jsx)(w.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?L(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)(w.Icons.chevronR,{size:11})}),(0,n.jsx)(lw,{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:lq(t)+18},children:"Empty folder."})]});return null!==f?(0,n.jsx)(lT,{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(),q(m)},children:[(0,n.jsx)("button",{type:"button",className:"files-root-up",onClick:P,disabled:null===v&&null===lA(u??d),title:"Open parent folder","aria-label":"Open parent folder",children:(0,n.jsx)(w.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:m,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)(w.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(!lM.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:L(v??"",0)})]})}function lL(e){return e instanceof j.ApiError||e instanceof Error?e.message:"The file could not be loaded."}function lD(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e))}function lF({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),[h,m]=(0,a.useState)(void 0!==e&&void 0!==t),[p,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(null),[x,b]=(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),m(!1),f(!1),v(null),b(null);return}let n=!1;return m(!0),v(null),b(null),(0,j.fetchFilesContent)(e,t).then(e=>{n||(s(e.content),r(e.content),c(e.modifiedAt),u(e.maxBytes))}).catch(e=>{n||v(lL(e))}).finally(()=>{n||m(!1)}),()=>{n=!0}},[y,e,t]);let N=async()=>{if(y&&k&&!p){f(!0),v(null),b(null);try{let n=await (0,j.saveFilesContent)({root:e,path:t,content:l,expectedModifiedAt:o??void 0});s(n.content),r(n.content),c(n.modifiedAt),u(n.maxBytes),b(`Saved ${lD(n.modifiedAt)}`)}catch(e){v(lL(e))}finally{f(!1)}}},S=(0,a.useMemo)(()=>y?h?"Loading file…":p?"Saving…":null!==g?g:null!==x?x:k?"Unsaved changes":null!==o?`Saved ${lD(o)}`:"Ready":"Open a file from the Files window to start editing.",[k,g,y,h,o,x,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)(w.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||h||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!==x&&b(null)},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"s"===e.key.toLowerCase()&&(e.preventDefault(),N())},disabled:h||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 lz(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 j.ApiError(e,t,l.status)}if(204!==l.status)return l.json()}async function lO(e){return lz(`/api/browser/status?port=${encodeURIComponent(String(e))}`)}async function lK(e){return lz("/api/browser/sessions",{method:"POST",body:JSON.stringify({port:e})})}async function lB(e){await lz(`/api/browser/sessions/${encodeURIComponent(e)}`,{method:"DELETE"})}async function l_(e,t){return lz(`/api/browser/sessions/${encodeURIComponent(e)}/navigate`,{method:"POST",body:JSON.stringify({url:t})})}async function lU(e){return lz(`/api/browser/sessions/${encodeURIComponent(e)}/screenshot`,{method:"POST",body:JSON.stringify({})})}async function lW(e,t){return lz(`/api/browser/sessions/${encodeURIComponent(e)}/apply`,{method:"POST",body:JSON.stringify({captureSeq:t})})}async function lH(e){return lz(`/api/browser/sessions/${encodeURIComponent(e)}/content`,{method:"POST",body:JSON.stringify({})})}function lG(e){return e instanceof j.ApiError?{code:e.code,message:e.message}:e instanceof Error?{code:"INTERNAL",message:e.message}:{code:"INTERNAL",message:"Unexpected error."}}function lV(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,h]=(0,a.useState)(null),[m,p]=(0,a.useState)(!1),[f,g]=(0,a.useState)(null),[v,x]=(0,a.useState)(null),[b,y]=(0,a.useState)([]),[j,w]=(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)(()=>{x(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&&x({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 lO(e);h(t)}catch(e){x(lG(e))}finally{p(!1)}},[s,E]),T=(0,a.useCallback)(async()=>{E(),p(!0);try{let e=Number.parseInt(s,10),t=await lK(e);d(t),y([]),N(null),C(null)}catch(e){x(lG(e))}finally{p(!1)}},[s,E]),A=(0,a.useCallback)(async()=>{if(null!==c){E(),p(!0);try{await lB(c.sessionId),d(null),w(null),N(null),C(null)}catch(e){x(lG(e))}finally{p(!1)}}},[c,E]),q=(0,a.useCallback)(async()=>{if(null!==c){E(),p(!0);try{let e=await l_(c.sessionId,r);C(e.originOnly)}catch(e){x(lG(e))}finally{p(!1)}}},[c,r,E]),M=(0,a.useCallback)(async()=>{if(null!==c){E(),p(!0);try{let e=await lU(c.sessionId);e.persisted||w({seq:e.seq,dataBase64:e.dataBase64})}catch(e){x(lG(e))}finally{p(!1)}}},[c,E]),P=(0,a.useCallback)(async()=>{if(null!==c&&null!==j){E(),p(!0);try{let e=await lW(c.sessionId,j.seq);e.persisted&&N(e.path),w(null)}catch(e){x(lG(e))}finally{p(!1)}}},[c,j,E]),L=(0,a.useCallback)(async()=>{if(null!==c){E(),p(!0);try{await lH(c.sessionId)}catch(e){x(lG(e))}finally{p(!1)}}},[c,E]),D=(0,a.useMemo)(()=>m||null!==c,[m,c]),F=(0,a.useMemo)(()=>m||null===c,[m,c]),z=m||null!==c,O=m||null===j,K=m&&null!==f?f:null!==j?"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||m})]}),(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:m})]})]}),(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…"),q())},"aria-disabled":F,children:"Navigate"}),(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{F||(g("Capturing screenshot…"),M())},"aria-disabled":F,children:"Screenshot"}),(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{O||(g("Applying screenshot…"),P())},"aria-disabled":O,children:"Apply"}),(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{F||(g("Capturing HTML…"),L())},"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}),m&&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!==j?(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!==j?(0,n.jsx)("img",{className:"bw-screenshot",src:`data:image/png;base64,${j.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:b.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 lY(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 j.ApiError(e,t,l.status)}if(204!==l.status)return l.json()}async function lQ(){return lY("/api/terminal/policy")}async function lJ(e,t){let n=new URLSearchParams;return n.set("projectId",e),void 0!==t&&t.length>0&&n.set("path",t),lY(`/api/terminal/directories?${n.toString()}`)}async function lX(e){return lY("/api/terminal/executions",{method:"POST",body:JSON.stringify(e)})}async function lZ(e){await lY(`/api/terminal/executions/${encodeURIComponent(e)}`,{method:"DELETE"})}function l0(e){return e instanceof j.ApiError?{code:e.code,message:e.message}:e instanceof Error?{code:"INTERNAL",message:e.message}:{code:"INTERNAL",message:"Unexpected error."}}function l1(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,h]=(0,a.useState)(e.projectPath??""),[m,p]=(0,a.useState)(!1),[f,g]=(0,a.useState)(null),[v,x]=(0,a.useState)(null),[b,y]=(0,a.useState)(null),[j,w]=(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 lQ().then(t=>{e||(l(t),i(e=>e.length>0?e:t.commands[0]??""))}).catch(t=>{e||y(l0(t))}),()=>{e=!0}},[]),(0,a.useEffect)(()=>{if(0===u.length)return void I([]);let e=!1;return lJ(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)}w(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(),m)return;y(null),x(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 lX(e);x(t)}catch(e){y(l0(e))}finally{N.current=!1,p(!1),S.current=null,g(null)}},[r,s,c,u,m]),R=(0,a.useCallback)(async()=>{if(null!==f)try{await lZ(f)}catch(e){y(l0(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&&!m&&document.activeElement===document.body&&T.current?.focus(),A.current=m},[m]),(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=>h(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":m||null===t,children:m?"Running…":"Run"}),m?(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: ",nT($.maxOutputBytes)," output ·"," ",nA($.defaultTimeoutMs)," timeout"]}):null]}),null!==b?(0,n.jsxs)("div",{className:"tm-error",role:"alert",children:[(0,n.jsxs)("span",{className:"tm-error-text",children:[b.message," ",(0,n.jsxs)("span",{className:"err-code mono",children:["(",b.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:j.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 l2(e){return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function l4(e){return e instanceof j.ApiError?{code:e.code,message:e.message}:e instanceof Error?{code:"INTERNAL",message:e.message}:{code:"INTERNAL",message:"Unexpected error."}}function l3(e){return("dry-run"===e.status||"fix-proposed"===e.status)&&void 0!==e.proposedDiff&&void 0===e.appliedAt}function l6(e){return void 0!==e.proposedDiff&&""!==e.proposedDiff}function l5({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 l8({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 l9({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=lI(e.text,lN(t))[0]??[];a=(0,n.jsx)(l8,{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 l7({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)(l9,{line:e,lang:t},a))]})}function se({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)(l7,{hunk:e,lang:i},t))})]})}function st({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),[h,m]=(0,a.useState)(null),[p,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(null),[x,b]=(0,a.useState)(null),[y,w]=(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),m(null),s(null),r(!1),c(null),b(null),Promise.allSettled([(0,j.fetchRunReport)(e),(0,j.fetchEvidenceManifest)(e)]).then(([e,n])=>{if(!t){if("fulfilled"===n.status)r(!0),c(null);else{let e=l4(n.reason);r(!1),c("NOT_FOUND"===e.code?null:e)}if("fulfilled"===e.status){s(e.value.report),u(!1);return}m(l4(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,h=()=>{null!==o&&null!==c&&o.hunks.push(c),c=null},m=()=>{h(),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 ")){m();let t=/^diff --git a\/(.+?) b\/(.+)$/.exec(e);if(null!==t&&void 0!==t[1]&&void 0!==t[2]){let e=t[1],n=t[2],a=l2(`b/${n}`),l=l2(`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)m(),o={path:l2(t),hunks:[],addedLines:0,removedLines:0};else if("/dev/null"!==t&&null!==o){let e=l2(t);e!==o.path&&(o.oldPath=e)}p++;continue}if(e.startsWith("+++ ")){let t=e.slice(4);"/dev/null"!==t&&null!==o?o.path=l2(t):"/dev/null"!==t&&(m(),o={path:l2(t),hunks:[],addedLines:0,removedLines:0}),p++;continue}if(e.startsWith("@@ ")){null===o&&(o={path:"(unknown)",hunks:[],addedLines:0,removedLines:0}),h();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 m(),{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(x??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=>w(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!==h&&(0,n.jsxs)("div",{role:"alert",className:"rv-error",children:["NOT_FOUND"===h.code?"No run with that ID was found.":(0,n.jsxs)(n.Fragment,{children:[h.message," ",(0,n.jsxs)("span",{className:"err-code mono",children:["(",h.code,")"]})]}),(i||null!==o)&&(0,n.jsx)("span",{className:"rv-error-evidence",children:(0,n.jsx)(l5,{href:C,hasManifest:i,error:o})})]}),(0,n.jsx)("p",{role:"status","aria-live":"polite",className:!d&&null===h&&null!==l&&A?"rv-no-diff":"sr-only",children:!d&&null===h&&null!==l&&A?"Run is still running. The proposed diff will appear when the run completes.":""}),!d&&null===h&&null!==l&&!A&&!l6(l)&&(0,n.jsx)("p",{className:"rv-no-diff",children:"This run has no proposed diff to review."}),!d&&null===h&&null!==l&&l6(l)&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"rv-header",children:[(0,n.jsx)("span",{className:"rv-status mono",children:nq(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)(l5,{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:()=>{b(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)(se,{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"}):l3(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&&l3(l)&&!p&&(f(!0),v(null),(0,j.applyRun)(e).then(e=>{s(e.report),f(!1)}).catch(e=>{v(l4(e)),f(!1)}))}},children:p?"Applying…":k?`Confirm apply (${(I?.files.length??0).toString()} file${I?.files.length===1?"":"s"})`:"Apply"}):null]})]})]})}let sn=["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"],sa=new Set(["run:completed","run:cancelled","run:failed","workflow:completed","workflow:failed","bug:completed","bug:failed"]),sl=new Set(["completed","dry-run","rejected","cancelled","failed","fix-applied","fix-proposed","investigation-only"]),ss={verify:"Verify","explain-plan":"Explain plan","unit-test-generation":"Generate unit tests","bug-investigation":"Investigate bug"};function si(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 sr({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),h=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]),sa.has(l.type)&&(s("terminal"),t?.close())}};for(let e of sn)t.addEventListener(e,i);return()=>{a=!0,t?.close()}},[e]),{events:t,status:l,error:i}}(o),[m,p]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),[v,x]=(0,a.useState)(null),[b,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){x(null);try{let e=await (0,j.fetchRunReport)(o);p(e.report),g(null)}catch(e){if(e instanceof j.ApiError&&404===e.status){try{let e=await (0,j.fetchEvidenceManifest)(o);g(e.manifest),p(null)}catch(e){x(e instanceof Error?e.message:"Unable to load evidence.")}return}x(e instanceof Error?e.message:"Unable to load run report.")}}},[o]);(0,a.useEffect)(()=>{T()},[T]),(0,a.useEffect)(()=>{"terminal"===h.status&&T()},[T,h.status]),(0,a.useEffect)(()=>{let e=!1;if(0!==d.length)return(0,j.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}})(h.events,m),[h.events,m]),q=m?.durationMs??f?.run.durationMs??(h.events.length>0?Math.max(0,Date.now()-Number(new Date(h.events[0]?.ts??Date.now()))):0),M=null!==m?m.status:null!==f?f.run.outcome:"loading",P=function(e,t){if(null!==e)return nq(e.status);if(null!==t){var n=t.run.outcome;switch(n){case"fix-applied":return"Fix applied";case"fix-proposed":return"Fix proposed (dry-run)";case"investigation-only":return"Investigation only";case"limit-exceeded":return"Limit exceeded";case"dry-run":return"Dry-run";default:return n.charAt(0).toUpperCase()+n.slice(1)}}return"Loading…"}(m,f),L=null!==m&&sl.has(m.status),D=null!==m&&void 0!==m.proposedDiff&&void 0===m.appliedAt&&("unit-test-generation"===c&&"dry-run"===m.status||"bug-investigation"===c&&"fix-proposed"===m.status),F=!L&&m?.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}(m?.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){x(null);try{await (0,j.cancelRun)(o),await T()}catch(e){x(e instanceof Error?e.message:"Unable to cancel run.")}}},B=async()=>{if(null!==o&&D&&!b){y(!0),N(null);try{let e=await (0,j.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:ss[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:function(e){switch(e){case"low":return"Low cost";case"medium":return"Medium cost";case"high":return"High cost";case"unknown":return"Unknown cost"}}(S)}):null,(0,n.jsx)("span",{className:"spacer"}),(0,n.jsxs)("span",{className:"arun-status",children:[(0,n.jsx)("span",{className:"dot","data-live":m?.status==="running","data-status":M}),P]})]}),(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":ss[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,m,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:nA(q)})]}),(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":`${nM(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?"—":nA(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)(w.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)(w.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"===h.status&&null!==h.error?(0,n.jsxs)("div",{className:"arun-log-row",children:[(0,n.jsx)("span",{className:"arun-log-ico",children:(0,n.jsx)(w.Icons.reset,{size:12})}),(0,n.jsx)("span",{className:"arun-log-text",children:h.error})]}):null,0===h.events.length?"error"===h.status?null:(0,n.jsxs)("div",{className:"arun-log-row",children:[(0,n.jsx)("span",{className:"arun-log-ico",children:(0,n.jsx)(w.Icons.reset,{size:12})}),(0,n.jsx)("span",{className:"arun-log-text",children:"connecting"===h.status?"Connecting to run events…":"Waiting for run events…"})]}):h.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)(w.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 (${nT(e.contextBytes)})`;case"model:call:completed":return`Model call completed (${nM(e.usage.promptTokens+e.usage.completionTokens)} tokens)`;case"model:call:failed":return`Model call failed: ${e.message}`;case"patch:proposed":return`Patch proposed (${nT(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 (${nM(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 (${nM(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!==m?(0,n.jsxs)("div",{className:"arun-results",children:[void 0===m.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:m.report})]}),void 0===m.overallStatus||void 0===m.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:m.overallStatus})]}),m.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}`))]}),si("Failure",m.failureReason),si("Covered behavior",m.coveredBehavior),si("Known gaps",m.knownGaps),si("Verification note",m.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))]})}(m),void 0===(i=m.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!==m.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:m.dryRunPreview})]}):null,void 0!==m.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:m.proposedDiff})]}):null,void 0===(r=m.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:nA(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!==m.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(m.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:nA(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":b,onClick:()=>{if(!b){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:b?"Applying…":I?`Confirm apply (${z.toString()} file${1===z?"":"s"})`:"Apply"}):m?.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 so=[{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 sc(){return(0,n.jsx)("ul",{className:"integ","aria-label":"Integrations",children:so.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 sd={allow:["Allow","var(--accent)"],ask:["Ask","var(--warn)"],deny:["Deny","var(--danger)"]},su={allow:"ask",ask:"deny",deny:"allow"},sh=[{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"}],sm=[["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"]],sp=[["calendar","Calendar","automations"],["mail","Mail","bell"],["jira","Jira","review"],["docs","Docs","files"]];function sf({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=sd[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:su[e.decision]}:e))},children:a[0]})]},e.id)})]})}function sg({decide:e}){let[t,l]=(0,a.useState)(!1),s=sh.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)(w.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)(w.Icons.check,{size:13}):(0,n.jsx)(w.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:sd[e.actual][1]},children:sd[e.actual][0]})]},e.id))]})}function sv({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."}),sp.map(([a,l,s])=>{let i=w.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 sx({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."}),sm.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)(w.Icons.check,{size:14,style:{color:"var(--accent)"}})]},a))]})}let sb=[["policy","Policy"],["eval","EVAL"],["bridges","Connections"],["persona","Persona"]];function sy(){let e=b(),[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:sb.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)(sf,{policy:e.policy,setPolicy:e.setPolicy}),"eval"===t&&(0,n.jsx)(sg,{decide:e.decide}),"bridges"===t&&(0,n.jsx)(sv,{bridges:e.bridges,setBridges:e.setBridges}),"persona"===t&&(0,n.jsx)(sx,{persona:e.persona,setPersona:e.setPersona})]})]})}function sj(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 sw(){return"Available for embeddings; not shown in the chat model picker"}function sk({model:e}){let t=function(e){if("chat"!==e.kind)return tS[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: "+sw(),title:sw(),children:"Embedding-ready"}):(0,n.jsxs)("span",{className:"ml-elig ml-elig-no","data-testid":"conv-elig-no",role:"status","aria-label":"Model eligibility: "+sj(t),title:sj(t),children:["Not selectable — ","ocr-vision-only"===t?"OCR/vision-only":"not a chat model"]})}function sN({model:e}){var t;let a=tN(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)(w.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)(sk,{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"})]})}let sS="keiko.wallpaper.opacity";function sC(){let e=window.localStorage.getItem(sS);if(null===e)return 100;let t=Number.parseInt(e,10);return Number.isFinite(t)?Math.max(0,Math.min(100,t)):100}function sI(){let[e,t]=(0,a.useState)(sC);(0,a.useEffect)(()=>{try{window.localStorage.setItem(sS,String(e))}catch{}window.dispatchEvent(new CustomEvent("keiko:wallpaper-opacity",{detail:e}))},[e]);let l={"--p":`${String(e)}%`};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. Set to 0% for the plain workspace background."})]})}),(0,n.jsxs)("div",{className:"gpref",children:[(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:[e,"%"]})]}),(0,n.jsx)("input",{id:"wp-op",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:e,onChange:e=>t(Number.parseInt(e.target.value,10)),style:l,"aria-label":"Wallpaper opacity"}),(0,n.jsxs)("div",{className:"gpref-scale",children:[(0,n.jsx)("span",{children:"Off"}),(0,n.jsx)("span",{children:"Full"})]})]})]})}function sE(){let[e,t]=(0,a.useState)("models"),[l,s]=(0,a.useState)([]),[i,r]=(0,a.useState)(!1),[o,c]=(0,a.useState)(!0),[d,u]=(0,a.useState)(),[h,m]=(0,a.useState)(!1),[p,f]=(0,a.useState)(0);(0,a.useEffect)(()=>{let e=!1;return async function(){c(!0),u(void 0);try{let[t,n]=await Promise.all([(0,j.fetchConfig)(),(0,j.fetchModels)()]);if(e)return;r(t.configPresent),s(n.models)}catch(t){if(e)return;u(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||c(!1)}}(),()=>{e=!0}},[p]);let g=l.filter(tN).length,v=l.length>0,x=i?v?0===g?"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.";return(0,n.jsxs)("div",{className:"set",children:[(0,n.jsxs)("div",{className:"set-hero",children:[(0,n.jsx)(w.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:()=>m(!0),children:[(0,n.jsx)(w.Icons.plus,{size:14}),i?"Update credentials":"Connect gateway"]})]}),(0,n.jsxs)("div",{className:"ml-row",children:[(0,n.jsx)("span",{className:"ml-ico",children:(0,n.jsx)(w.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:i?v?"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:[g.toString()," chat"]})]}),(0,n.jsx)("div",{className:"ml-url mono",children:x})]}),(0,n.jsx)("span",{className:"ml-status "+(i?"connected":"untested"),title:i?"gateway configured":"setup required","aria-hidden":"true"})]}),void 0!==d?(0,n.jsxs)("div",{className:"gw-error",role:"alert",children:[d,(0,n.jsx)("button",{type:"button",className:"gw-error-retry",onClick:()=>f(e=>e+1),children:"Retry"})]}):null,o?(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:i?"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)(sN,{model:e},e.id))}),h?(0,n.jsx)(eQ,{onCancel:()=>m(!1)}):null]}),"general"===e&&(0,n.jsx)(sI,{}),"security"===e&&(0,n.jsx)("div",{className:"set-placeholder",children:"SSO · audit log · data residency — coming soon."})]})]})}function sR(e){return e instanceof j.ApiError?`${e.message} (${e.code})`:e instanceof Error?e.message:"Failed to load connectors."}function s$(){return(0,n.jsx)("div",{className:"connector-picker-status",role:"status","aria-live":"polite",children:"Loading connectors…"})}function sT({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 sA({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 sq({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 sM({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)(w.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 sP({selectedKind:e,selectedId:t,selectedLabel:l,selectedState:s,presentation:i,onSelect:r,onManageConnectors:o=()=>void 0}){let[c,d]=(0,a.useState)([]),[u,h]=(0,a.useState)([]),[m,p]=(0,a.useState)(!0),[f,g]=(0,a.useState)(null),[v,x]=(0,a.useState)(!1),[b,y]=(0,a.useState)(0),j="node"===i&&"capsule"===e&&void 0!==t&&t.length>0;if((0,a.useEffect)(()=>{if(j)return;let e=!1;return async function(){p(!0),g(null),x(!1);try{let[t,n]=await Promise.allSettled([(0,aT.fetchCapsules)(),(0,aT.fetchCapsuleSets)()]);if(e)return;"fulfilled"===t.status?d(t.value.capsules.filter(e=>"ready"===e.lifecycleState)):g(sR(t.reason)),"fulfilled"===n.status?h(n.value.capsuleSets):x(!0)}catch(t){e||g(sR(t))}finally{e||p(!1)}}(),()=>{e=!0}},[j,b]),j)return(0,n.jsx)(sM,{selectedId:t,selectedLabel:l,selectedState:s,onManageConnectors:o});if(m)return(0,n.jsx)(s$,{});if(null!==f)return(0,n.jsx)(sT,{message:f,onRetry:()=>{y(e=>e+1)}});let w=c.length>0,k=u.length>0;if(!w&&!k)return(0,n.jsx)(sA,{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)(sq,{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 —"}),w&&(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 sL(e,t){let n=(t?.method??"GET").toUpperCase(),a=await fetch(e,{...t,headers:{Accept:"application/json",...t?.body!==void 0?{"Content-Type":"application/json"}:{},..."GET"===n||"HEAD"===n?{}:{"X-Keiko-CSRF":"1"},...t?.headers??{}}});if(!a.ok){let e="INTERNAL",t=`HTTP ${a.status.toString()}`;try{let n=await a.json();e=n.error.code,t=n.error.message}catch{}throw new j.ApiError(e,t,a.status)}return a.json()}async function sD(e,t={}){return sL("/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 sF(e,t){return sL(`/api/figma/snapshots/${encodeURIComponent(e)}`,{...void 0!==t?{signal:t}:{}})}async function sz(e,t){return sL(`/api/figma/snapshots/${encodeURIComponent(e)}/code`,{method:"POST",...void 0!==t?{signal:t}:{},body:JSON.stringify({})})}async function sO(){return sL("/api/figma/token",{method:"DELETE",body:JSON.stringify({})})}function sK(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}}let sB=new Set(["FIGMA_PROXY_EGRESS_FAILED","FIGMA_PROXY_UNREACHABLE","FIGMA_PROXY_AUTH_REQUIRED","FIGMA_PROXY_BLOCKED_BY_POLICY"]),s_=new Set(["FIGMA_TLS_CA_FAILURE"]),sU=new Set(["FIGMA_NETWORK_UNREACHABLE","FIGMA_EGRESS_TIMEOUT","FIGMA_EGRESS_FAILED"]);function sW(e){return e instanceof j.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}:sB.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}:s_.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}:sU.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 sH(e){let t=sW(e);return void 0===t.status?t.detail:`${t.detail} (${t.status})`}function sG({index:e,screenId:t,name:a,irSummary:l,imageSrc:s,imageByteLength:i}){return(0,n.jsxs)("article",{className:"figma-snapshot-screen-card","aria-label":`Screen ${String(e+1)}: ${a}`,children:[(0,n.jsx)(nN.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-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:nT(i)}),(0,n.jsx)("p",{className:"figma-snapshot-screen-id",children:t})]})]})}function sV({snapshotRunId:e,updateCfg:t,triggerImpl:l=sD,loadImpl:s=sF,codegenImpl:i=sz,revokeImpl:r=sO}){let o=(0,a.useId)(),c=(0,a.useId)(),d=(0,a.useId)(),[u,h]=(0,a.useState)(""),[m,p]=(0,a.useState)("idle"),[f,g]=(0,a.useState)(null),[v,x]=(0,a.useState)(null),[b,y]=(0,a.useState)(!1),[w,k]=(0,a.useState)(!1),N=(0,a.useRef)(null),S=(0,a.useRef)(null),C=(0,a.useRef)(null),I=(0,a.useCallback)(()=>{k(!0)},[]),[E,R]=(0,a.useState)("idle"),[$,T]=(0,a.useState)(null),[A,q]=(0,a.useState)(null),[M,P]=(0,a.useState)(!1),[L,D]=(0,a.useState)(null),[F,z]=(0,a.useState)(null),O=(0,a.useRef)(null),K=(0,a.useRef)(null),[B,_]=(0,a.useState)(24),U=sK(u),W=function(e){let t=e.trim();if(0===t.length||sK(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."}(u),H="building"===m,G="loading"===m,V=H||G;(0,a.useEffect)(()=>{w&&"error"===m&&N.current?.focus()},[w,m]),(0,a.useEffect)(()=>{M&&O.current?.focus()},[M]),(0,a.useEffect)(()=>()=>{S.current?.abort(),C.current?.abort()},[]);let Y=(0,a.useCallback)(async(e,n)=>{S.current?.abort(),C.current?.abort(),C.current=null;let a=new AbortController;S.current=a,p("building"),x(null),R("idle"),T(null);try{let s=await l(e,{acknowledgeReadOnly:b,isResnapshot:n,signal:a.signal});g(s),t({snapshotRunId:s.runId}),p("done")}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return;if(e instanceof j.ApiError&&"FIGMA_CONSENT_REQUIRED"===e.code){let t=sW(e);x({...t,detail:`${t.detail} Tick the acknowledgement checkbox below, then snapshot again.`}),I()}else x(sW(e));p("error")}},[l,t,b,I]),Q=(0,a.useCallback)(e=>{if(e.preventDefault(),U&&!V){if(!b){x({title:"Figma snapshot failed",detail:"Tick the read-only acknowledgement checkbox below, then snapshot again."}),p("error"),I();return}Y(u,!1)}},[u,V,b,U,Y,I]),J=(0,a.useCallback)(()=>{V||null===f||Y(`https://www.figma.com/design/${f.fileKey}/board?node-id=${f.nodeId}`,!0)},[V,Y,f]),X=(0,a.useCallback)(()=>{S.current?.abort(),S.current=null,p("idle"),x(null)},[]),Z=(0,a.useCallback)(()=>{let t=f?.runId??e;if(void 0===t||0===t.length||"generating"===E)return;let n=new AbortController;C.current=n,R("generating"),q(null),i(t,n.signal).then(e=>{T(e),R("done")}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name?R("idle"):(q(sH(e)),R("error"))}).finally(()=>{C.current===n&&(C.current=null)})},[i,E,e,f]),ee=(0,a.useCallback)(()=>{C.current?.abort(),C.current=null,R("idle"),q(null)},[]),et=(0,a.useCallback)(()=>{if(void 0===e||0===e.length||V)return;S.current?.abort();let n=new AbortController;S.current=n,p("loading"),x(null),s(e,n.signal).then(e=>{g(e),p("done")}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||(e instanceof j.ApiError&&"FIGMA_SNAPSHOT_NOT_FOUND"===e.code?(t({snapshotRunId:void 0}),x({...sW(e),detail:`${e.message} The stored run ID has been cleared.`})):x(sW(e)),p("error"))})},[V,s,e,t]);(0,a.useEffect)(()=>{_(24)},[f?.runId]);let en=(0,a.useCallback)(()=>{P(!1),z(null),D(null),r().then(e=>{D(e.message),requestAnimationFrame(()=>K.current?.focus())}).catch(e=>{z(sH(e)),requestAnimationFrame(()=>K.current?.focus())})},[r]),ea=(0,a.useCallback)(()=>{P(!1),requestAnimationFrame(()=>K.current?.focus())},[]),el=void 0!==e&&e.length>0&&null===f&&("idle"===m||"loading"===m||"error"===m);return(0,n.jsxs)("section",{className:"figma-snapshot-window","aria-label":"Figma Snapshot",children:[(0,n.jsxs)("form",{className:"figma-snapshot-form",onSubmit:Q,noValidate:!0,children:[(0,n.jsx)("label",{className:"figma-snapshot-label",htmlFor:o,children:"Board link"}),(0,n.jsxs)("div",{className:"figma-snapshot-input-row",children:[(0,n.jsx)("input",{id:o,type:"url",className:"figma-snapshot-input",placeholder:"https://www.figma.com/design/…?node-id=…",value:u,onChange:e=>{h(e.target.value),null!==v&&x(null),"error"===m&&p("idle"),w&&k(!1)},"aria-describedby":null!==W?`${d} ${c}`:c,"aria-invalid":null!==W?"true":void 0,readOnly:V,autoComplete:"off",spellCheck:!1}),(0,n.jsx)("button",{type:"submit",className:"figma-snapshot-trigger-btn",disabled:!U&&!V,"aria-disabled":!U||V?"true":void 0,"aria-busy":H,children:H?"Building…":"Snapshot"})]}),null!==W&&(0,n.jsx)("p",{id:d,className:"figma-snapshot-link-error",role:"alert",children:W}),(0,n.jsxs)("label",{className:"figma-snapshot-consent",children:[(0,n.jsx)("input",{type:"checkbox",className:"figma-snapshot-consent-checkbox",ref:N,checked:b,"aria-invalid":w?"true":void 0,onChange:e=>{y(e.target.checked),null!==v&&x(null),"error"===m&&p("idle"),k(!1)},disabled:H}),(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"===m&&null!==v&&!0===v.assertive&&(0,n.jsxs)("div",{className:"figma-snapshot-error-card",role:"alert","aria-labelledby":`${c}-error-title`,children:[(0,n.jsx)("p",{id:`${c}-error-title`,className:"figma-snapshot-error-title",children:v.title}),(0,n.jsx)("p",{className:"figma-snapshot-error-detail",children:v.detail}),void 0!==v.status&&(0,n.jsx)("p",{className:"figma-snapshot-error-status",children:v.status}),void 0!==v.remediation&&(0,n.jsx)("p",{className:"figma-snapshot-error-remediation",children:v.remediation})]}),(0,n.jsxs)("div",{id:c,role:"status","aria-live":"polite","aria-atomic":"true",className:"figma-snapshot-status",children:[H&&(0,n.jsx)("p",{className:"figma-snapshot-progress",children:"Building snapshot — fetching screens from Figma…"}),G&&(0,n.jsx)("p",{className:"figma-snapshot-progress",children:"Loading stored snapshot…"}),"done"===m&&null!==f&&(0,n.jsxs)("p",{className:"sr-only",children:["Snapshot complete — ",f.reductionHint,"."]}),"done"===E&&null!==$&&(0,n.jsxs)("p",{className:"sr-only",children:["Code generated — ",String($.fileCount)," file",1!==$.fileCount?"s":""," ready for review."]}),"idle"===m&&(0,n.jsx)("p",{className:"sr-only","aria-live":"polite"}),"error"===m&&null!==v&&!0!==v.assertive&&(0,n.jsx)("p",{className:"figma-snapshot-error",children:v.detail})]}),H&&(0,n.jsxs)("div",{className:"figma-snapshot-cancel-row",children:[(0,n.jsx)("button",{type:"button",className:"figma-snapshot-cancel-btn",onClick:X,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."})]}),"idle"===m&&null===f&&!el&&(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."})]}),el&&(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:et,"aria-disabled":G?"true":void 0,"aria-busy":G,children:G?"Loading…":"Load snapshot"})]}),null!==f&&(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:f.reductionHint}),(0,n.jsxs)("p",{className:"figma-snapshot-captured-at",children:["Captured ",function(e){try{return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return"string"==typeof e?e:e.toString()}}(f.fetchedAt)]}),f.skippedCount>0&&(0,n.jsxs)("p",{className:"figma-snapshot-skipped-notice",children:[String(f.skippedCount)," screen",1!==f.skippedCount?"s":""," could not be rendered and were skipped."]})]}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-resnapshot-btn",onClick:J,"aria-disabled":V?"true":void 0,"aria-busy":H,"aria-label":"Re-snapshot this board",children:H?"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:Z,"aria-disabled":"generating"===E?"true":void 0,"aria-busy":"generating"===E,children:"generating"===E?"Generating code…":"Generate code"}),"generating"===E&&(0,n.jsx)("button",{type:"button",className:"figma-snapshot-codegen-cancel-btn",onClick:ee,children:"Cancel"})]}),"error"===E&&null!==A&&(0,n.jsx)("p",{className:"figma-snapshot-error",role:"alert",children:A}),"done"===E&&null!==$&&(0,n.jsxs)("div",{className:"figma-snapshot-code-result",children:[(0,n.jsxs)("p",{className:"figma-snapshot-code-summary",children:[String($.fileCount)," reviewable file",1!==$.fileCount?"s":""," (",String($.screenCount)," screen",1!==$.screenCount?"s":"",","," ",$.adapterName,") — proposal only, never auto-applied."]}),$.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:[M?(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:O,type:"button",className:"figma-snapshot-revoke-confirm-btn",onClick:en,children:"Yes, revoke"}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-revoke-cancel-btn",onClick:ea,children:"Cancel"})]}):(0,n.jsx)("button",{ref:K,type:"button",className:"figma-snapshot-revoke-btn",onClick:()=>{P(!0),D(null),z(null)},children:"Revoke stored token"}),(0,n.jsx)("p",{className:"figma-snapshot-revoke-status",role:"status","aria-live":"polite","aria-atomic":"true",children:L??F??""})]})]}),f.screens.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("section",{className:"figma-snapshot-gallery","aria-label":`${String(f.screenCount)} captured screen${1!==f.screenCount?"s":""}`,children:f.screens.slice(0,B).map((e,t)=>{var a;return(0,n.jsx)(sG,{index:t,screenId:e.screenId,name:e.name,irSummary:e.irSummary,imageSrc:(a=f.runId,`/api/figma/snapshots/${encodeURIComponent(a)}/screens/${encodeURIComponent(String(t))}/image`),imageByteLength:e.imageByteLength},e.screenId)})}),B<f.screens.length?(0,n.jsx)("button",{type:"button",className:"figma-snapshot-gallery-more",onClick:()=>_(e=>Math.min(e+24,f.screens.length)),children:"Show more screens"}):null]}):(0,n.jsx)("div",{className:"lk-empty",children:(0,n.jsx)("p",{className:"lk-empty-body",children:"No screens were captured from this board section."})})]})]})}async function sY(e,t){let n=(t?.method??"GET").toUpperCase(),a=await fetch(e,{...t,headers:{Accept:"application/json",...t?.body!==void 0?{"Content-Type":"application/json"}:{},..."GET"===n||"HEAD"===n?{}:{"X-Keiko-CSRF":"1"},...t?.headers??{}}});if(!a.ok){let e="INTERNAL",t=`HTTP ${a.status.toString()}`;try{let n=await a.json();e=n.error.code,t=n.error.message}catch{}throw new j.ApiError(e,t,a.status)}return a.json()}async function sQ(){return sY("/api/quality-intelligence/runs")}async function sJ(e){return sY(`/api/quality-intelligence/runs/${encodeURIComponent(e)}`)}async function sX(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 j.ApiError(t,n,e.status)}async function sZ(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 sX(a);let s=a.body;if(null===s)throw new j.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 s0(e){return sY(`/api/quality-intelligence/runs/${encodeURIComponent(e)}`,{method:"DELETE"})}async function s1(e,t,n,a){return sY(`/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 s2(e,t,n,a){return(await sY(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/edit`,{method:"POST",body:JSON.stringify({candidateId:t,edited:n,...void 0!==a?{editorLabel:a}:{}})})).candidate}async function s4(e,t){return sY(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/re-check`,{method:"POST",body:JSON.stringify({sources:t})})}async function s3(e,t){return sY(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/regenerate-stale`,{method:"POST",body:JSON.stringify({sources:t})})}async function s6(e,t,n){return sY(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/export`,{method:"POST",body:JSON.stringify({adapter:t,dryRun:n?.dryRun??!1,approvedOnly:n?.approvedOnly??!1})})}async function s5(e,t){return sY(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/traceability`,{method:"POST",body:JSON.stringify({format:t})})}let s8={open:"Open",approved:"Approved","changes-requested":"Changes requested",rejected:"Rejected",withdrawn:"Withdrawn"},s9={open:"qi-review-open",approved:"qi-review-approved","changes-requested":"qi-review-changes",rejected:"qi-review-rejected",withdrawn:"qi-review-withdrawn"};function s7({state:e}){return(0,n.jsxs)("span",{className:`qi-review-badge ${s9[e]}`,children:[(0,n.jsx)("span",{className:"sr-only",children:"Review: "}),s8[e]]})}function ie(e){if(e instanceof j.ApiError){var t,n;return t=e.code,n=e.message,`${n} (${t})`}return e instanceof Error?e.message:"An unexpected error occurred."}function it(e){try{return new Date(e).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"})}catch{return e}}let ia={running:"Running",succeeded:"Succeeded",failed:"Failed",cancelled:"Cancelled"},il={running:"qi-badge-running",succeeded:"qi-badge-succeeded",failed:"qi-badge-failed",cancelled:"qi-badge-cancelled"};function is(e){return"running"===e||"succeeded"===e||"failed"===e||"cancelled"===e}function ii({status:e}){let t=is(e)?ia[e]:e,a=is(e)?il[e]:"qi-badge-default";return(0,n.jsx)("span",{className:`qi-badge ${a}`,children:t})}let ir={critical:"qi-sev-critical",high:"qi-sev-high",medium:"qi-sev-medium",low:"qi-sev-low"};function io({severity:e}){let t="critical"===e||"high"===e||"medium"===e||"low"===e?ir[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 ic({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 id({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 iu={verifiability:"Verifiability",atomicity:"Atomicity",determinism:"Determinism","ac-fidelity":"AC fidelity"};function ih({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:[iu[e.name]??e.name," ",Math.round(e.score).toString(),": ",e.rationale]},e.name))})]})}function im({height:e=20,width:t="100%"}){return(0,n.jsx)("div",{"aria-hidden":"true",className:"qi-skeleton",style:{height:e,width:t}})}function ip(){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)(im,{height:14,width:"60%"}),(0,n.jsx)(im,{height:12,width:"40%"})]},e))})}function ig({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 iv="connectedSourcesJson";function ix(e,t){let n=e[t];return"string"==typeof n?n:void 0}function ib(e,t){return"string"==typeof e[t]}function iy(e){if(!("object"==typeof e&&null!==e&&!Array.isArray(e))||!ib(e,"label"))return!1;switch(e.kind){case"file":case"workspace":return ib(e,"path");case"capsule":return ib(e,"capsuleId");case"capsule-set":return ib(e,"capsuleSetId");case"figma-snapshot":return ib(e,"snapshotRunId");default:return!1}}function ij(e){return e.length>0?{[iv]:JSON.stringify(e)}:{}}function iw(e){let t=e.split(/[\\/]/u).filter(e=>e.length>0);return t.length>0?t[t.length-1]??e:e}function ik(e){return e.replaceAll("\\","/")}function iN(e){if(/^[A-Za-z]:[/\\]?$/u.test(e))return e.replaceAll("\\","/");if(/^\/\/[^/]+\/[^/]+$/u.test(ik(e)))return ik(e);let t=ik(e).replace(/\/+$/u,"");return 0===t.length&&e.length>0?"/":t}function iS(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=iN(a),s=ik(n).replace(/^\/+/u,""),i=l.endsWith("/")?"":"/";return`${l}${i}${s}`}(t,e.connectedFilePath??null),a=null!==t?iN(t):null,l=(void 0!==e.connectedRoots&&null!==e.connectedRoots&&e.connectedRoots.length>0?e.connectedRoots:null!==t?[t]:[]).map(iN),s=null!==n?l.filter(e=>e!==a):l,i=[];for(let e of(null!==n&&i.push({kind:"file",label:iw(n),path:n}),s))i.push({kind:"workspace",label:iw(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 e.connectedFigmaSnapshotRunIds??[])i.push({kind:"figma-snapshot",label:t,snapshotRunId: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":return`figma-snapshot:${e.snapshotRunId}`}}(e);r.has(t)||(r.add(t),o.push(e))}return o}let iC=[{id:"regression-default",label:"Regression (default)"},{id:"banking-default",label:"Banking"},{id:"insurance-default",label:"Insurance"}],iI={phase:"Starting…",stageName:null,candidates:0,findings:0,atomCount:null,droppedSourceCount:0,skippedSources:[]};function iE(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"Figma snapshot"}}function iR(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 e.snapshotRunId}}function i$({onRunCompleted:e,startImpl:t=sZ,fetchCapsulesImpl:l=aT.fetchCapsules,fetchCapsuleSetsImpl:s=aT.fetchCapsuleSets,connectedRoot:i=null,connectedFilePath:r=null,connectedRoots:o,connectedCapsuleIds:c,connectedCapsuleSetIds:d,connectedFigmaSnapshotRunIds:u}){let[h,m]=(0,a.useState)(""),[p,f]=(0,a.useState)("requirements"),[g,v]=(0,a.useState)(""),[x,b]=(0,a.useState)(""),[y,j]=(0,a.useState)(""),[w,k]=(0,a.useState)(""),[N,S]=(0,a.useState)([]),[C,I]=(0,a.useState)([]),[E,R]=(0,a.useState)(!1),[$,T]=(0,a.useState)(null),[A,q]=(0,a.useState)("regression-default"),[M,P]=(0,a.useState)(""),[L,D]=(0,a.useState)(!1),[F,z]=(0,a.useState)(iI),[O,K]=(0,a.useState)(null),B=(0,a.useRef)(null),_=(0,a.useRef)(null),U=(0,a.useRef)(!1),W=iS({connectedRoot:i,connectedFilePath:r,connectedRoots:o,connectedCapsuleIds:c,connectedCapsuleSetIds:d,connectedFigmaSnapshotRunIds:u}),H=W.length>0,G=N.find(e=>e.id===y),V=C.find(e=>e.id===w),Y=x.trim().length>0,Q="requirements"===p?g.trim().length>0:"workspace"===p||"file"===p?Y:"capsule"===p?y.trim().length>0:w.trim().length>0,J="requirements"===p?0===g.trim().length:("workspace"===p||"file"===p)&&!Y,X=Q||J&&H,Z=M.trim(),ee=0===Z.length?void 0:/^\d+$/u.test(Z)?Number(Z):NaN,et=void 0===ee||Number.isSafeInteger(ee)&&Number.isFinite(ee),en=!X||!et,ea=(0,a.useId)(),el=(0,a.useId)(),es=(0,a.useId)(),ei=X?et?void 0:el:ea,er=(0,a.useCallback)(e=>{var t,n;"done"===e.type&&("succeeded"===e.status?_.current=e.runId:"failed"===e.status&&K("The run did not complete successfully. Adjust the source and retry.")),"error"===e.type&&K((t=e.code,n=e.message,`${n} (${t})`)),z(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="stage:started"===t.kind?t.stageName??null:e.stageName;return{...e,phase:t.kind,stageName:l,candidates:n,findings:a}}return e})(t,e))},[]),eo="capsule"===p||"capsule-set"===p;(0,a.useEffect)(()=>{if(!eo)return;let e=!1;return async function(){R(!0),T(null);try{let[t,n]=await Promise.allSettled([l(),s()]);if(e)return;"fulfilled"===t.status?S(t.value.capsules.filter(e=>"ready"===e.lifecycleState)):(S([]),"capsule"===p&&T(ie(t.reason))),"fulfilled"===n.status?I(n.value.capsuleSets):(I([]),"capsule-set"===p&&T(ie(n.reason)))}finally{e||R(!1)}}(),()=>{e=!0}},[l,s,eo,p]),(0,a.useEffect)(()=>{if("capsule"===p){let e=N.some(e=>e.id===y)?y:N[0]?.id??"";e!==y&&j(e)}if("capsule-set"===p){let e=C.some(e=>e.id===w)?w:C[0]?.id??"";e!==w&&k(e)}},[y,w,C,N,p]);let ec=(0,a.useCallback)(()=>{let e=h.trim();return"requirements"===p&&g.trim().length>0?[{kind:"requirements",label:e||"Requirements",text:g}]:"workspace"===p&&x.trim().length>0?[{kind:"workspace",label:e||"Folder",path:x.trim()}]:"file"===p&&x.trim().length>0?[{kind:"file",label:e||"File",path:x.trim()}]:"capsule"===p&&y.trim().length>0?[{kind:"capsule",label:e||G?.displayName||"Knowledge capsule",capsuleId:y.trim()}]:"capsule-set"===p&&w.trim().length>0?[{kind:"capsule-set",label:e||V?.displayName||"Capsule set",capsuleSetId:w.trim()}]:null},[y,w,h,x,G,V,p,g]),ed=(0,a.useCallback)(async()=>{if(!X||L||!et||U.current)return;U.current=!0,D(!0),K(null),z(iI),_.current=null;let n=new AbortController;B.current=n;let a=ec()??W,l={sources:a,profileId:A,...void 0!==ee?{seed:ee}:{}};try{await t(l,n.signal,er);let s=_.current;null!==s&&e?.(s,a.filter(e=>"requirements"!==e.kind))}catch(e){n.signal.aborted||K(ie(e))}finally{D(!1),B.current=null,U.current=!1}},[X,A,L,W,ec,er,e,ee,et,t]),eu=(0,a.useCallback)(()=>{B.current?.abort()},[]),eh=F.droppedSourceCount>0?`${F.droppedSourceCount.toString()} source${1!==F.droppedSourceCount?"s":""} over the 16-source limit ${1!==F.droppedSourceCount?"were":"was"} not included.`:null,em=F.skippedSources.length>0?`${F.skippedSources.length.toString()} connected source${1!==F.skippedSources.length?"s":""} could not be read and ${1!==F.skippedSources.length?"were":"was"} skipped: ${F.skippedSources.map(e=>e.label).join(", ")}.`:null,ep=[eh,em].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===W.length&&void 0!==W[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 ",iE(W[0]).toLowerCase()]}),(0,n.jsx)("span",{className:"qi-connected-path qi-monospace",title:iR(W[0]),children:iR(W[0])}),(0,n.jsx)("span",{className:"qi-connected-hint",children:Q?"Manual input below overrides the connected source for this run.":`Generate uses the connected ${iE(W[0]).toLowerCase()}.`})]}):W.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 (",W.length.toString(),")"]}),(0,n.jsx)("ul",{className:"qi-connected-roots","aria-label":"Connected sources",children:W.map(e=>(0,n.jsxs)("li",{className:"qi-connected-root-item",children:[(0,n.jsx)("span",{className:"qi-connected-root-name",children:iE(e)}),(0,n.jsx)("span",{className:"qi-connected-path qi-monospace",title:iR(e),children:iR(e)})]},`${e.kind}:${iR(e)}`))}),(0,n.jsx)("span",{className:"qi-connected-hint",children:Q?"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:h,placeholder:"e.g. Funds Transfer — acceptance criteria",disabled:L,"aria-describedby":H&&!Q?es:void 0,onChange:e=>{m(e.target.value)}}),H&&!Q?(0,n.jsx)("span",{className:"qi-field-hint",id:es,children:"Applies to manual input only — connected sources use their own labels."}):null]}),(0,n.jsxs)("label",{className:"qi-field qi-field-kind",children:[(0,n.jsx)("span",{className:"qi-field-label",children:"Source type"}),(0,n.jsxs)("select",{className:"qi-select",value:p,disabled:L,onChange:e=>{let t=e.target.value;f("workspace"===t||"file"===t||"capsule"===t||"capsule-set"===t?t:"requirements"),K(null),T(null)},children:[(0,n.jsx)("option",{value:"requirements",children:"Requirements text"}),(0,n.jsx)("option",{value:"workspace",children:"Local folder"}),(0,n.jsx)("option",{value:"file",children:"Single file"}),(0,n.jsx)("option",{value:"capsule",children:"Knowledge capsule"}),(0,n.jsx)("option",{value:"capsule-set",children:"Capsule set"})]})]})]}),function(){if("requirements"===p)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:g,rows:6,placeholder:"Paste requirements or acceptance criteria, one statement per line.",disabled:L,onChange:e=>{v(e.target.value)}})]});if("workspace"===p||"file"===p){let e="file"===p;return(0,n.jsxs)("label",{className:"qi-field",children:[(0,n.jsx)("span",{className:"qi-field-label",children:e?"File path":"Folder path"}),(0,n.jsx)("input",{type:"text",className:"qi-input",value:x,placeholder:e?"/absolute/path/to/requirements.md":"/absolute/path/to/folder",disabled:L,onChange:e=>{b(e.target.value)}})]})}let e="capsule"===p,t=e?N:C;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?y:w,disabled:L||E||null!==$||0===t.length,onChange:t=>{e?j(t.target.value):k(t.target.value)},children:[E?(0,n.jsx)("option",{value:"",children:"Loading connectors..."}):null,E||0!==t.length?null:(0,n.jsx)("option",{value:"",children:e?"No ready capsules":"No capsule sets"}),e?N.map(e=>(0,n.jsx)("option",{value:e.id,children:e.displayName},e.id)):C.map(e=>(0,n.jsx)("option",{value:e.id,children:`${e.displayName} (${String(e.capsuleCount)} capsules)`},e.id))]})]})}(),null!==$?(0,n.jsx)("p",{className:"lk-alert",role:"alert","data-testid":"qi-connector-error",children:$}):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:A,disabled:L,onChange:e=>{q(e.target.value)},children:iC.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:M,placeholder:"e.g. 42",disabled:L,"aria-invalid":!et||void 0,"aria-describedby":et?void 0:el,onChange:e=>{P(e.target.value),K(null)}}),et?null:(0,n.jsx)("span",{className:"qi-field-error",id:el,children:"Seed must be a non-negative integer."})]}),(0,n.jsx)("button",{type:"button",className:L?"qi-btn qi-btn-secondary":"qi-btn qi-btn-primary","aria-disabled":!L&&en||void 0,"aria-describedby":L?void 0:ei,onClick:()=>{L?eu():en||ed()},children:L?"Cancel":"Generate test cases"}),L||X?null:(0,n.jsx)("span",{className:"qi-generate-hint",id:ea,children:"Add requirements text, a folder path, a file path, select a capsule, select a capsule set, or connect a source to generate."})]}),L?(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!==F.stageName?`Stage: ${F.stageName} \xb7 `:"",F.candidates.toString()," test case",1!==F.candidates?"s":"",F.findings>0?` \xb7 ${F.findings.toString()} finding${1!==F.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}`}(L,F)}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:ep}),null!==eh||null!==em?(0,n.jsxs)("div",{className:"qi-coverage-notice","data-testid":"qi-coverage-notice",children:[null!==eh?(0,n.jsx)("p",{className:"qi-coverage-line",children:eh}):null,null!==em?(0,n.jsx)("p",{className:"qi-coverage-line",children:em}):null]}):null,null!==O?(0,n.jsx)("p",{className:"lk-alert",role:"alert","data-testid":"qi-launch-error",children:O}):null]})]})}function iT({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),h=(0,a.useRef)(null);(0,a.useEffect)(()=>{o&&u.current?.focus()},[o]);let m=(0,a.useCallback)(()=>{c(!1),requestAnimationFrame(()=>{d.current?.focus()})},[]),p=(0,a.useCallback)(e=>{"Escape"===e.key&&(e.preventDefault(),m())},[m]),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} — ${is(i=e.status)?ia[i]:i}, ${it(e.requestedAt)}, ${r.toString()} test case${1!==r?"s":""}, review ${s8[e.reviewState]}`,title:`Open run ${e.id}`,children:[(0,n.jsx)("span",{className:"qi-run-title",children:it(e.requestedAt)}),(0,n.jsx)(ii,{status:e.status}),(0,n.jsx)(s7,{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 ${it(e.requestedAt)}`,style:{display:"flex",alignItems:"center",gap:4,padding:"0 6px",flexShrink:0},children:[(0,n.jsx)("button",{ref:h,type:"button",className:"qi-btn qi-btn-reject",style:{minWidth:0,padding:"4px 10px",fontSize:12,flexShrink:0},"aria-label":`Confirm delete of run ${it(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||m()},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 ${it(e.requestedAt)}`,onClick:()=>{c(!0)},children:"Delete"})]})}function iA({openRun:e,connectedRoot:t=null,connectedFilePath:l=null,connectedRoots:s,connectedCapsuleIds:i,connectedCapsuleSetIds:r,connectedFigmaSnapshotRunIds:o,fetchRunsImpl:c=sQ,deleteImpl:d=s0}){let[u,h]=(0,a.useState)([]),[m,p]=(0,a.useState)(0),[f,g]=(0,a.useState)(!1),[v,x]=(0,a.useState)(!0),[b,y]=(0,a.useState)(null),[j,w]=(0,a.useState)(25),[k,N]=(0,a.useState)(null),[S,C]=(0,a.useState)(""),I=(0,a.useCallback)(async()=>{x(!0),y(null);try{let e=await c();h(e.runs),p(e.totalRunIds),g(e.truncated)}catch(e){y(ie(e))}finally{x(!1)}},[c]);(0,a.useEffect)(()=>{I()},[I]);let E=(0,a.useCallback)((t,n)=>{I(),e(t,n)},[I,e]),R=(0,a.useCallback)(async e=>{if(null===k){N(e),y(null);try{await d(e),C("Run deleted."),await I()}catch(e){y(ie(e))}finally{N(null)}}},[k,d,I]);return(0,n.jsxs)("div",{className:"qi-hub",children:[(0,n.jsx)(i$,{onRunCompleted:E,connectedRoot:t,connectedFilePath:l,connectedRoots:s,connectedCapsuleIds:i,connectedCapsuleSetIds:r,connectedFigmaSnapshotRunIds:o}),(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"}),v||null!==b?null:(0,n.jsx)("span",{className:"qi-col-count",children:m.toString()})]}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:v?"Loading runs…":null===b?`Run list loaded: ${u.length.toString()} run${1===u.length?"":"s"}${f?` of ${m.toString()}`:""}.`:""}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true",children:S}),(0,n.jsx)("div",{className:"qi-col-body","aria-busy":v,children:v?(0,n.jsx)(ip,{}):null!==b?(0,n.jsx)(ig,{message:b,onRetry:()=>{I()}}):0===u.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:u.slice(0,j).map(t=>(0,n.jsx)(iT,{run:t,onOpen:e,onDelete:e=>{R(e)},deleting:k===t.id},t.id))}),j<u.length?(0,n.jsxs)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-show-more",onClick:()=>{w(e=>e+25)},children:["Show more runs (",(u.length-j).toString()," remaining)"]}):null,f?(0,n.jsx)("p",{className:"qi-runs-truncated","data-testid":"qi-runs-truncated",children:`Showing ${u.length.toString()} of ${m.toString()} runs.`}):null]})})]})]})}e.s(["QUALITY_INTELLIGENCE_SCHEMA_VERSION",0,"1"],73859),e.i(73859);let iq=["..","/","\\"],iM=(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`}:iq.some(t=>e.includes(t))?{ok:!1,reason:`${t} contains forbidden path fragment`}:{ok:!0},iP=(e,t)=>{let n=iM(e,t);if(!n.ok)throw TypeError(`Invalid ${t}: ${n.reason}`);return e},iL=e=>1564===e||e>=8203&&e<=8207||e>=8234&&e<=8238||e>=8294&&e<=8297||65279===e,iD=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(iL(t.codePointAt(0)??0))return!0;return!1})(e)),iF=e=>Number.isFinite(e)&&e>=0&&e<=1,iz=Object.freeze({critical:0,high:1,medium:2,low:3}),iO=new Set(["jira-issues","qtest","xray","polarion","alm","quality-center"]),iK=["verifiability","atomicity","determinism","ac-fidelity"],iB=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:[...iK]},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,iz,"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,iO,"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,iB,"TEST_QUALITY_RUBRIC_DIMENSIONS",0,iK,"asQualityIntelligenceAuditSummaryId",0,e=>iP(e,"QualityIntelligenceAuditSummaryId"),"asQualityIntelligenceCoverageMapId",0,e=>iP(e,"QualityIntelligenceCoverageMapId"),"asQualityIntelligenceEvidenceAtomId",0,e=>iP(e,"QualityIntelligenceEvidenceAtomId"),"asQualityIntelligenceExportBundleId",0,e=>iP(e,"QualityIntelligenceExportBundleId"),"asQualityIntelligenceReviewRecordId",0,e=>iP(e,"QualityIntelligenceReviewRecordId"),"asQualityIntelligenceRunId",0,e=>iP(e,"QualityIntelligenceRunId"),"asQualityIntelligenceSourceEnvelopeId",0,e=>iP(e,"QualityIntelligenceSourceEnvelopeId"),"asQualityIntelligenceTestCaseId",0,e=>iP(e,"QualityIntelligenceTestCaseId"),"asQualityIntelligenceValidationFindingId",0,e=>iP(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(!iF(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(iO.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)||iD(t)||iD(a)||iD(n.origin)||"connector-document"===e.kind&&iD(e.adapterId))},"validateQualityIntelligenceIdString",0,iM],47425);var i_=e.i(47425),i_=i_;let iU=i_.QUALITY_INTELLIGENCE_PRIORITIES,iW=i_.QUALITY_INTELLIGENCE_RISK_CLASSES,iH=e=>e.split("\n").map(e=>e.trim()).filter(e=>e.length>0),iG=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]);function iV(e,t){let n=iH(t.preconditions),a=iH(t.steps),l=iH(t.expectedResults),s=t.tags.split(",").map(e=>e.trim()).filter(e=>e.length>0);return{...t.title!==e.title?{title:t.title}:{},...!iG(n,e.preconditions)?{preconditions:n}:{},...!iG(a,e.steps)?{steps:a}:{},...!iG(l,e.expectedResults)?{expectedResults:l}:{},...t.priority!==e.priority?{priority:t.priority}:{},...t.riskClass!==e.riskClass?{riskClass:t.riskClass}:{},...!iG(s,e.tags)?{tags:s}:{}}}function iY({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 iQ({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 iJ({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 iX({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 iZ({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,h]=(0,a.useState)(!1),m=(0,a.useRef)(null),p=(e,t)=>{o(null),h(!1),i(n=>({...n,[e]:t}))},f=(0,a.useCallback)(()=>{c||(!(Object.keys(iV(e,s)).length>0)||u?l():h(!0))},[e,u,l,c,s]);(0,a.useEffect)(()=>{let e=e=>{if("Escape"!==e.key||c)return;let t=m.current;null!==t&&t.contains(document.activeElement)&&f()};return document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e)}},[f,c]),(0,a.useEffect)(()=>{m.current?.querySelector("input.qi-edit-input")?.focus()},[]);let g=`qi-edit-${e.id}`,v=async()=>{if(!c){d(!0),o(null);try{await t(iV(e,s))}catch(e){o(ie(e))}finally{d(!1)}}};return(0,n.jsxs)("form",{ref:m,className:"qi-edit-form","aria-label":`Edit ${e.title}`,"aria-busy":c,onSubmit:e=>{e.preventDefault(),v()},children:[(0,n.jsx)(iQ,{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)(iX,{onCancel:f,saving:c}),(0,n.jsx)(iY,{id:`${g}-preconditions`,label:"Preconditions (one per line)",value:s.preconditions,disabled:c,onChange:e=>{p("preconditions",e)}}),(0,n.jsx)(iY,{id:`${g}-steps`,label:"Steps (one per line)",value:s.steps,disabled:c,onChange:e=>{p("steps",e)}}),(0,n.jsx)(iY,{id:`${g}-expected`,label:"Expected results (one per line)",value:s.expectedResults,disabled:c,onChange:e=>{p("expectedResults",e)}}),(0,n.jsx)(iJ,{id:`${g}-priority`,label:"Priority",value:s.priority,options:iU,disabled:c,onChange:e=>{p("priority",e)}}),(0,n.jsx)(iJ,{id:`${g}-risk`,label:"Risk class",value:s.riskClass,options:iW,disabled:c,onChange:e=>{p("riskClass",e)}}),(0,n.jsx)(iQ,{id:`${g}-tags`,label:"Tags (comma-separated)",value:s.tags,disabled:c,onChange:e=>{p("tags",e)}})]})}let i0=new Set(["approved","rejected","withdrawn"]);function i1({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 i2({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 i4({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=i0.has(t),u=(0,a.useId)(),h=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)(i2,{className:"qi-btn qi-btn-approve",label:c("approve")?"Saving…":"Approve",pressed:"approved"===t,disabled:s||o||d,describedBy:h,onActivate:()=>{l(e,"approve")}}),(0,n.jsx)(i2,{className:"qi-btn qi-btn-reject",label:c("reject")?"Saving…":"Reject",pressed:"rejected"===t,disabled:s||o||d,describedBy:h,onActivate:()=>{l(e,"reject")}}),(0,n.jsx)(i2,{className:"qi-btn qi-btn-secondary",label:c("request-changes")?"Saving…":"Request changes",pressed:"changes-requested"===t,disabled:s||o||d,describedBy:h,onActivate:()=>{l(e,"request-changes")}}),d?(0,n.jsx)(i2,{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 i3({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)(s7,{state:e.reviewState})]})]}),void 0!==e.weakTestFlag?(0,n.jsx)(id,{flag:e.weakTestFlag}):null,void 0!==e.qualityVerdict?(0,n.jsx)(ih,{verdict:e.qualityVerdict}):null,(0,n.jsx)(i1,{items:e.preconditions,label:"Preconditions"}),(0,n.jsx)(i1,{items:e.steps,label:"Steps"}),(0,n.jsx)(i1,{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)(i4,{candidateId:e.id,state:e.reviewState,onReview:t,disabled:l,describedBy:s,pendingReview:r}):null]})]})}function i6({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 h=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)(iZ,{candidate:e,onSave:h,onCancel:()=>{c(!1)}}):(0,n.jsx)(i3,{candidate:e,onReview:t,actionsDisabled:s,describedBy:i,pendingReview:r,editButtonRef:d,onStartEdit:void 0!==l?()=>{c(!0)}:void 0})})}function i5({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 h=[...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:h.map(e=>(0,n.jsx)(i6,{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 i8(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 i9(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 i7({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:"✓"}),i8(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:"⚠"}),i8(e)]})}function re({runId:e,connectedSources:t,onRegenerated:l,reCheckImpl:s=s4,regenerateImpl:i=s3}){let[r,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(null),u=null!==c,[h,m]=(0,a.useState)(null),[p,f]=(0,a.useState)(null),g=(0,a.useRef)(null),v=(0,a.useRef)(null),x=(0,a.useCallback)(()=>{u||(async()=>{d("check"),m(null),f(null);try{o(await s(e,t))}catch(e){m(ie(e))}finally{d(null)}})()},[u,s,e,t]),b=(0,a.useCallback)(()=>{u||(async()=>{d("regenerate"),m(null);try{let n=await i(e,t);document.activeElement===v.current&&g.current?.focus(),f(n),o(null),l?.(n)}catch(e){m(ie(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?i9(p):null!==r?i8(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:x,"aria-disabled":u||void 0,"data-testid":"qi-drift-recheck",children:"check"===c?"Checking…":"Re-check drift"})]}),null!==h?(0,n.jsx)("p",{className:"lk-alert",role:"alert",children:h}):null,null!==r?(0,n.jsx)(i7,{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:b,"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:i9(p)}):null]})}let rt={"traceability-csv":"csv","traceability-markdown":"markdown"},rn=[{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 ra(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 rl({runId:e,exportImpl:t=s6,traceabilityImpl:l=s5}){let[s,i]=(0,a.useState)("csv"),[r,o]=(0,a.useState)(!1),[c,d]=(0,a.useState)(null),[u,h]=(0,a.useState)(null),[m,p]=(0,a.useState)(null),[f,g]=(0,a.useState)(!1),v=rn.find(e=>e.id===s),x=v?.tms??!1,b=(0,a.useCallback)(async()=>{let n=rt[s];if(void 0!==n){let t=await l(e,n);ra(t.filename,t.contentType,t.body),p(t.filename);return}let a=await t(e,s,{dryRun:x,approvedOnly:f});a.dryRun?h(`${a.candidateCount.toString()} test case${1===a.candidateCount?"":"s"} \xb7 ${a.byteLen.toString()} bytes
105
-
106
- ${a.preview}`):(ra(a.filename,a.contentType,a.body,a.encoding),p(a.filename))},[e,s,x,f,t,l]),y=(0,a.useCallback)(async()=>{o(!0),d(null),h(null),p(null);try{await b()}catch(e){d(ie(e))}finally{o(!1)}},[b]);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":x?"qi-export-connector-hint":void 0,onChange:e=>{i(e.target.value),h(null),d(null),p(null)},children:rn.map(e=>(0,n.jsx)("option",{value:e.id,children:e.label},e.id))})]}),x?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"})]}),x?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…":x?"Preview":"Download"}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:null!==m?`Downloaded ${m}`:null!==u?"Export preview ready below.":""}),x?(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!==m?(0,n.jsx)("p",{className:"qi-export-success","data-testid":"qi-export-success",children:`Downloaded ${m}`}):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 rs="keiko.qi.reviewerLabel",ri="Set a reviewer label to review or edit candidates.";function rr({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)(ii,{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)(ic,{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:s8[e.reviewState]})]}),(0,n.jsxs)("div",{className:"qi-run-summary-item",children:[(0,n.jsx)("dt",{children:"Requested"}),(0,n.jsx)("dd",{children:it(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:it(e.completedAt)})]}):null]})}let ro={"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 rc({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:ro[e.kind]??e.kind}),(0,n.jsx)(io,{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 rd={covered:"Covered","weakly-covered":"Weakly covered",uncovered:"Uncovered"},ru={covered:"qi-cov-covered","weakly-covered":"qi-cov-weak",uncovered:"qi-cov-uncovered"},rh={uncovered:0,"weakly-covered":1,covered:2};function rm({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)=>rh[e.status]-rh[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=rd[e.status],a=ru[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 rp({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 rf({runId:e,connectedSources:t,onRegenerated:l,fetchDetailImpl:s=sJ,reviewImpl:i=s1,editImpl:r=s2,reCheckImpl:o,regenerateImpl:c}){let[d,u]=(0,a.useState)(null),[h,m]=(0,a.useState)(!0),[p,f]=(0,a.useState)(null),[g,v]=(0,a.useState)(null),[x,b]=(0,a.useState)(null),[y,j]=(0,a.useState)(""),[w,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,m(!0),f(null);try{let n=await s(e);R.current===t&&u(n)}catch(e){R.current===t&&f(ie(e))}finally{R.current===t&&m(!1)}},[s,e]);(0,a.useEffect)(()=>{$()},[$]),(0,a.useEffect)(()=>{j(function(){try{return window.localStorage.getItem(rs)??""}catch{return""}}()),k(!0)},[]),(0,a.useEffect)(()=>{if(w)try{window.localStorage.setItem(rs,y)}catch{}},[y,w]);let T=y.trim(),A=T.length>0,q=(0,a.useCallback)((t,n)=>{A&&null===x&&(b({candidateId:t,action:n}),(async()=>{v(null);try{await i(e,n,t,T),await $();let a=s8["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(ie(e))}finally{b(null)}})())},[A,x,i,e,T,$,d]),M=(0,a.useCallback)(async(t,n)=>{if(!A)throw Error(ri);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:h?"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":h,children:h&&null===d?(0,n.jsx)(ip,{}):null!==p?(0,n.jsx)(ig,{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=>{j(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?"":ri})]}),(0,n.jsx)(rr,{detail:d}),(0,n.jsx)(rc,{detail:d}),(0,n.jsx)(rm,{detail:d}),void 0!==t&&t.length>0?(0,n.jsx)(re,{runId:e,connectedSources:t,onRegenerated:l,reCheckImpl:o,regenerateImpl:c}):(0,n.jsx)(rp,{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)(rl,{runId:e}):null]}),(0,n.jsx)(i5,{candidates:d.candidates,onReview:q,pendingReview:x,onEdit:M,actionsDisabled:!A,actionsDisabledReason:ri})]})]})})]})}let rg={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 rv({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 rx({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 rb({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 h=rg[l]??rg.inactive,m=nn[e],p=r??d,f="high-throughput"===l&&void 0!==s?`${h.label} (${String(s)})`:h.label,g=`${m.displayName} — ${h.ariaDescription}`,v=h.animated&&i,x=p?{color:h.textColor,background:"var(--card)",border:`1px solid ${h.textColor}`}:{color:h.textColor,background:h.bgColor,border:void 0!==h.borderColor?`1px solid ${h.borderColor}`:void 0};return(0,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:x,"aria-label":g,onClick:o,children:[(0,n.jsx)("span",{"aria-hidden":"true",children:(0,n.jsx)(rv,{shape:h.iconShape,color:h.textColor,animated:v,highContrast:p})}),(0,n.jsx)("span",{className:"visually-hidden",children:h.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:m.displayName}),(0,n.jsx)(rx,{state:t})]}):(0,n.jsxs)("span",{className:"rb-edge-badge-static",style:x,"aria-label":g,children:[(0,n.jsx)("span",{"aria-hidden":"true",children:(0,n.jsx)(rv,{shape:h.iconShape,color:h.textColor,animated:v,highContrast:p})}),(0,n.jsx)("span",{className:"visually-hidden",children:h.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:m.displayName}),(0,n.jsx)(rx,{state:t})]})})}let ry="keiko.relationships.density",rj={minimal:5,standard:25,dense:512};function rw(){try{let e=window.localStorage.getItem(ry);if("minimal"===e||"standard"===e||"dense"===e)return e}catch{}return"minimal"}function rk(e,t){return void 0===e||0===e.length?[]:e.split(",").map(e=>e.trim()).filter(e=>t.includes(e))}function rN(e){return{types:rk(e.relType,ne),lifecycles:rk(e.relLifecycle,nt),activities:rk(e.relActivity,["inactive","queued","active","processing","completed","failed","blocked","degraded","high-throughput"]),srcKinds:rk(e.relSrcKind,t9),tgtKinds:rk(e.relTgtKind,t9)}}let rS={"high-throughput":0,processing:1,active:2,blocked:3,failed:4,degraded:5,queued:6,completed:7,inactive:8};function rC(e,t,n){return n.get(e)??function(e){switch(e){case"blocked":return"blocked";case"stale":return"degraded";default:return"inactive"}}(t)}function rI({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:rw()}),[h,m]=(0,a.useState)(!1),[p,f]=(0,a.useState)([]),[g,v]=(0,a.useState)(!1),[x,b]=(0,a.useState)(null),[y,j]=(0,a.useState)(!1),w=(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(ry,e)}catch{}},[s]);(0,a.useEffect)(()=>{let t=e.relDensity;"minimal"===t||"standard"===t||"dense"===t?u(t):u(rw())},[e.relDensity]),(0,a.useEffect)(()=>{S(e.relType??"")},[e.relType]);let E=(0,a.useCallback)(async()=>{b(null),v(!0);try{let t=rN(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 nd({lifecycle:n,type:a,sourceKind:l,targetKind:s,limit:rj[d]});f(i.entries),j(i.truncated)}catch(e){b(e instanceof ns?e.message:nl)}finally{v(!1)}},[e,d]);(0,a.useEffect)(()=>{E()},[E]),(0,a.useEffect)(()=>{let e=w.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(),m(e=>!e)):"Escape"===e.key?m(!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=rN(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(rC(e.id,e.lifecycle,i)))).slice(0,rj[d])},[i,d,e,p]),T=$.slice(0,25),A=$.slice(25),q=A.length,M=q>0?function(e,t){let n=new Map;for(let a of e){let e=rC(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]:(rS[e[0]]??Number.MAX_SAFE_INTEGER)-(rS[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):"",P=y?`Showing first ${String($.length)} relationships — more available.`:`Showing ${String($.length)} relationship${1!==$.length?"s":""}.`,L=(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=rk(e.relLifecycle,nt),F=1===D.length?D[0]??"active":"active";return(0,n.jsxs)("div",{ref:w,className:"tw-pad","data-testid":"relationship-list-panel","data-relationship-focus":h?"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":h,onClick:()=>m(e=>!e),title:"Toggle focus mode (F)","aria-label":`Focus mode: ${h?"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:ne.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:nt.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:P}),y&&(0,n.jsx)("div",{"data-testid":"list-truncation-note",style:{fontSize:11,color:"var(--fg-muted)",marginBottom:6},children:P}),null!==x&&(0,n.jsxs)("div",{className:"lk-alert",role:"alert","aria-live":"assertive",children:[(0,n.jsx)("span",{children:x}),(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===x&&0===$.length&&(0,n.jsx)("div",{className:"insp-empty","data-testid":"list-empty",children:L?"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=rC(e.id,e.lifecycle,i),d=h&&a,u=h&&!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)(rb,{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)}),q>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(q)," more: ",M]})]})]})}function rE(){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 rR({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)(rE,{})]})}function r$({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)(rR,{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)(rR,{title:"Upstream impact",help:"Objects that depend on this relationship's source.",report:t,onSelectRelationship:a})]})}let rT={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)"}},rA={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 rq({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 rM({children:e,style:t}){return(0,n.jsx)("div",{className:"rb-section-label",role:"heading","aria-level":3,style:t,children:e})}function rP({rel:e}){let t=nn[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 rL({label:e,kind:t,id:a}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)(rM,{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 rD({lifecycle:e}){let t=`lifecycle-desc-${e}`,a=rT[e]??rT.draft;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(rM,{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:rA[e]})})]})]})}function rF({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)(rM,{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)(rb,{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 rz(){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(rM,{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 rO({auditRows:e,loading:t,error:a,onRetry:l,onLoadMore:s,hasMore:i}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(rM,{children:"Audit history"}),t&&(0,n.jsx)(rq,{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 rK({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)(rM,{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 rB({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)(rM,{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)(r$,{outgoing:l,incoming:s,onSelectRelationship:o})})]})}function r_({codes:e,messages:t,deniedAt:a}){return 0===e.length?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(rM,{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 rU(e){return null==e||0===e.length?null:{codes:e.map(e=>e.code),messages:e.map(e=>e.message)}}function rW({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,h="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":!h,"aria-label":"View impact analysis",title:h?"Toggle the impact analysis card":"Impact analysis is unavailable in this state.",disabled:!h,onClick:h?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 rH({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),[h,m]=(0,a.useState)(null),[p,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(null),[x,b]=(0,a.useState)(!1),[y,j]=(0,a.useState)(null),[w,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,q]=(0,a.useState)(!1),M=(0,a.useRef)(null),P=(0,a.useRef)(0),L=(0,a.useCallback)(async e=>{let t=++P.current;v(null),f(!0),k(null),S(null),I(null),R(!1);let n=setTimeout(()=>{P.current===t&&q(!0)},500);M.current=n;try{let[n,a]=await Promise.all([nu(e),nf(e)]);if(P.current!==t)return;u(n),m(a);try{let[n,a]=await Promise.all([np(e,{direction:"outgoing",maxDepth:3,maxRelationships:512}),np(e,{direction:"incoming",maxDepth:3,maxRelationships:512})]);if(P.current!==t)return;S(n),I(a)}catch{}}catch(e){if(P.current!==t)return;v(e instanceof ns?e.message:nl)}finally{M.current===n?(clearTimeout(n),M.current=null):clearTimeout(n),P.current===t&&(f(!1),q(!1))}},[]);(0,a.useEffect)(()=>{if(null===e){P.current+=1,null!==M.current&&(clearTimeout(M.current),M.current=null),u(null),m(null),v(null),k(null),q(!1),f(!1);return}return L(e),()=>{null!==M.current&&(clearTimeout(M.current),M.current=null)}},[e,L]);let D=(0,a.useCallback)(async e=>{if(null!==d){b(!0),j(null),k(null);try{let t=crypto.randomUUID(),{relationship:n}=await nh(d.id,{transition:{to:e}},String(d.etag),t);u(n),m(null),await L(d.id)}catch(e){j(e instanceof ns?e.message:"Mutation failed. Please retry."),k(e instanceof ns?rU(e.reasons):null)}finally{b(!1)}}},[d,L]),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.`)){b(!0),j(null),k(null);try{let e=crypto.randomUUID(),t=await nm(d.id,String(d.etag),e);u(t)}catch(e){j(e instanceof ns?e.message:"Revoke failed. Please retry."),k(e instanceof ns?rU(e.reasons):null)}finally{b(!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)(rM,{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=rU(h?.decision.reasons)??w,H=null!==W&&(d?.lifecycle==="blocked"||d?.lifecycle==="revoked"||null!==w),G=null!==d?i.get(d.id)??function(e){switch(e){case"blocked":return"blocked";case"stale":return"degraded";default:return"inactive"}}(d.lifecycle):"inactive",V=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 L(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:()=>j(null),children:"Dismiss"})]}),p&&A&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(rM,{style:{marginTop:0},children:"Relationship"}),(0,n.jsx)(rq,{lines:4}),(0,n.jsx)(rq,{lines:3})]}),!p&&null===g&&null===d&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(rM,{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)(rM,{style:{marginTop:0},children:"Relationship"}),(0,n.jsx)(rP,{rel:d}),(0,n.jsx)(rL,{label:"Source",kind:d.source.kind,id:d.source.id}),(0,n.jsx)(rL,{label:"Target",kind:d.target.kind,id:d.target.id}),(0,n.jsx)(rD,{lifecycle:d.lifecycle}),(0,n.jsx)(rF,{type:d.type,lifecycle:d.lifecycle,activity:G,throughputCount:V,animateBadges:o,highContrast:c,transitions:h?.lifecycle??[],densityMode:t}),(0,n.jsx)(rz,{}),(0,n.jsx)(rO,{auditRows:h?.lifecycle??[],loading:!1,error:null,onRetry:()=>void L(e),onLoadMore:()=>{},hasMore:!1}),(0,n.jsx)("div",{ref:_,children:(0,n.jsx)(rK,{rel:d})}),(0,n.jsx)(rB,{relationshipId:d.id,forwardCount:$,reverseCount:T,outgoing:N,incoming:C,expanded:E,onToggle:K,onSelectRelationship:B}),H&&null!==W&&(0,n.jsx)(r_,{codes:W.codes,messages:W.messages}),(0,n.jsx)(rW,{rel:d,onReconnect:F,onArchive:z,onRevoke:()=>void O(),onViewImpact:K,onViewEvidence:U,mutating:x})]})]})}let rG=new Set(["kind","id","state","timestamp","count"]);function rV(e){return`${e.kind}: ${e.id}`}function rY({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 rQ({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 ${rV(e.source)} to ${rV(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:[rV(e.source)," → ",rV(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)(rY,{category:e.label.toLowerCase()})]})}function rJ({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:rV(e)})},`${e.kind}:${e.id}`))}),e.orphanedEndpointsTruncated&&(0,n.jsx)(rY,{category:"orphaned endpoints"})]})}function rX({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 ng();i(e)}catch(e){d(e instanceof ns?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:nt.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)(rQ,{category:t,onSelectRelationship:e},t.key)),(0,n.jsx)(rJ,{findings:s.findings})]})]})]})}let rZ={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 r0(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function r1(e){return"string"==typeof e&&e.length>0}function r2(e,t,n){return void 0===n?{code:e,message:t}:{code:e,field:n,message:t}}function r4(e,t,n){return r0(e)?r1(e.kind)?r1(e.id)?!!r1(e.workspaceId)||(n.push(r2("denied/schema-version-unsupported",`${t}.workspaceId must be a non-empty string`,`${t}.workspaceId`)),!1):(n.push(r2("denied/schema-version-unsupported",`${t}.id must be a non-empty string`,`${t}.id`)),!1):(n.push(r2("denied/schema-version-unsupported",`${t}.kind must be a non-empty string`,`${t}.kind`)),!1):(n.push(r2("denied/schema-version-unsupported",`${t} must be an object`,t)),!1)}function r3(e,t,n){r1(e[t])||n.push(r2("denied/schema-version-unsupported",`${t} must be a non-empty string`,t))}function r6(e,t){let n=e.kind;return t9.includes(n)?null:r2("denied/schema-version-unsupported",`${t}.kind is not a known object kind`,`${t}.kind`)}function r5(e,t,n){"missing"===t?n.push(r2("source"===e?"denied/non-existent-source":"denied/non-existent-target",`${e} endpoint does not exist`,e)):"tombstoned"===t?n.push(r2("denied/endpoint-tombstoned",`${e} endpoint has been tombstoned`,e)):"retired"===t?n.push(r2("denied/endpoint-retired",`${e} endpoint has been retired`,e)):"unavailable"===t&&n.push(r2("denied/endpoint-unavailable",`${e} endpoint is unavailable`,e))}function r8(e,t){let n=e.kind;return t7.includes(n)?null:r2("denied/object-kind-not-yet-supported",`${t}.kind "${n}" is reserved for a future release`,`${t}.kind`)}function r9(){return{type:"reads-context",sourceKind:"workflow-run",sourceId:"",targetKind:"memory",targetId:"",summary:""}}let r7=new Set(["denied/path-not-contained","denied/cross-workspace","denied/payload-content-not-permitted"]);function oe(e){return e?.codes.some(e=>r7.has(e))===!0}function ot({onClose:e}){let[t,l]=(0,a.useState)(r9),[s,i]=(0,a.useState)([]),[r,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(!1),[u,h]=(0,a.useState)(!1),m=(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=m.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()))},[]),x=(0,a.useCallback)(t=>{"Escape"===t.key&&e(null)},[e]);(0,a.useEffect)(()=>{let e=m.current;if(null!==e)return e.addEventListener("keydown",v),e.addEventListener("keydown",x),()=>{e.removeEventListener("keydown",v),e.removeEventListener("keydown",x)}},[v,x]),(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(!r0(e))return{errors:[r2("denied/schema-version-unsupported","relationship must be an object")]};let n=[];r3(e,"id",n),r3(e,"workspaceId",n),r3(e,"createdAt",n),r3(e,"updatedAt",n),(!("number"==typeof(t=e.etag)&&Number.isInteger(t)&&Number.isFinite(t))||e.etag<0)&&n.push(r2("denied/schema-version-unsupported","etag must be a non-negative finite integer","etag"));let a=r4(e.source,"source",n),l=r4(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?r2("denied/schema-version-unsupported",'schemaVersion must be the literal "1"',"schemaVersion"):null;if(s)return[s];let i=r1(a=e.type)?ne.includes(a)?null:r2("denied/schema-version-unsupported","type is not a known relationship type","type"):r2("denied/schema-version-unsupported","type must be a non-empty string","type");if(i)return[i];let r=r6(t,"source"),o=r6(n,"target");if(null!==r||null!==o){let e=[];return null!==r&&e.push(r),null!==o&&e.push(o),e}let c=r1(l=e.lifecycleState)?nt.includes(l)?null:r2("denied/schema-version-unsupported","lifecycleState is not a known lifecycle state","lifecycleState"):r2("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&&r5("source",e.endpointResolver.source,t),"missing"===e.endpointResolver.target&&r5("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,h,m,p,f=[],g=e.type,v=e.lifecycleState,x=r8(t,"source");x&&f.push(x);let b=r8(n,"target");b&&f.push(b),null===x&&null===b&&(l=t.kind,s=n.kind,"denied/source-kind-not-allowed"===(d=(c=nn[g]).validSourceKinds.includes(l)?c.validTargetKinds.includes(s)?null:"denied/target-kind-not-allowed":"denied/source-kind-not-allowed")?f.push(r2("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(r2("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?r2("denied/cardinality-exceeded","produces-evidence already exists for this source workflow-run"):"starts-workflow"===g&&"number"==typeof u.startsWorkflowForTarget&&u.startsWorkflowForTarget>=1?r2("denied/cardinality-exceeded","starts-workflow already exists for this target workflow-run"):null:null;y&&f.push(y),(h=t.kind===n.kind&&t.id===n.id?r2("denied/cycle-forbidden","source and target refer to the same endpoint"):null)&&f.push(h),(m="depends-on"===g&&a?.dependsOnReverseEdgeExists===!0?r2("denied/cycle-forbidden","depends-on reverse edge already exists for this endpoint pair"):null)&&f.push(m);let j=(i=e.workspaceId,t.workspaceId!==i||n.workspaceId!==i?r2("denied/cross-workspace","source and target must be in the relationship's workspace"):null);j&&f.push(j);let w=void 0===(p=a?.previousLifecycleState)||rZ[p].includes(v)?null:r2("denied/lifecycle-illegal-transition",`transition from ${p} to ${v} is not permitted`,"lifecycleState");for(let t of(w&&f.push(w),r=a,o=f,r?.endpointResolver&&("missing"!==r.endpointResolver.source&&r5("source",r.endpointResolver.source,o),"missing"!==r.endpointResolver.target&&r5("target",r.endpointResolver.target,o)),function(e){let t=[];if(void 0===e.metadata||null===e.metadata)return t;if(!r0(e.metadata))return t.push(r2("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 na)if(e.includes(a)){t.push(r2("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 b=(0,a.useRef)(null),y=(0,a.useRef)(0);(0,a.useEffect)(()=>{y.current+=1;let e=y.current;return(null!==b.current&&clearTimeout(b.current),0===t.sourceId.length||0===t.targetId.length||s.length>0)?void h(!1):(b.current=setTimeout(async()=>{h(!0);try{if(await no({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=>oe(e)?e:null)}catch(t){if(e!==y.current)return;t instanceof ns&&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&&h(!1)}},250),()=>{null!==b.current&&clearTimeout(b.current)})},[t,s]),(0,a.useEffect)(()=>{o(e=>e?.source!=="submit"||oe(e)?e:null)},[t]);let j=t.sourceId.trim().length>0&&t.targetId.trim().length>0&&0===s.length&&null===r&&!c,k=(0,a.useCallback)(async()=>{if(j){d(!0),o(null);try{let n=crypto.randomUUID(),{relationship:a}=await nc({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 ns?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:[nl]})}finally{d(!1)}}},[j,t,e]),N=(0,a.useCallback)(e=>{"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&k()},[k]),S=nn[t.type],C=oe(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:m,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)(w.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:ne.map(e=>(0,n.jsx)("option",{value:e,children:nn[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:t7.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:t7.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${j?" primary":""}`,"aria-disabled":!j,"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,eV.createPortal)(E,document.body)}let on={};function oa(){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,h]=(0,a.useState)(!1),m=(0,a.useCallback)(()=>{h(!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 na.some(e=>t.includes(e))}(n)||e(t[n]))return!0;return!1}(e))return null;let n={};for(let t of rG)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:m}}(),[s,i]=(0,a.useState)(!1),[r,o]=(0,a.useState)(on),c=r.relFocus,d=r.relDensity??"minimal",[u,h]=(0,a.useState)(!1),m=(0,a.useRef)(null),p=(0,a.useRef)(!1),f=(0,a.useRef)(null),[g,v]=(0,a.useState)(!1),x=(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})},[]),b=(0,a.useCallback)(e=>{x({relFocus:e})},[x]),y=(0,a.useCallback)(()=>{x({relFocus:void 0})},[x]),j=(0,a.useCallback)(e=>{x({relFocus:e})},[x]),w=(0,a.useCallback)(e=>{p.current=!0,h(!1),null!==e&&x({relFocus:e.id})},[x]);return(0,a.useEffect)(()=>{!u&&p.current&&(p.current=!1,m.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)(ot,{onClose:w}),(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:m,type:"button",className:"arun-btn primary",onClick:()=>h(!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)(rI,{filters:r,selectedId:c,onSelect:b,onFilterChange:x,activityMap:e,throughputMap:t,animateBadges:l,highContrast:s})}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto"},children:g?(0,n.jsx)(rX,{onSelectRelationship:e=>{v(!1),b(e)}}):(0,n.jsx)(rH,{relationshipId:c??null,densityMode:d,onClearFocus:y,onViewImpact:j,activityMap:e,throughputMap:t,animateBadges:l,highContrast:s})})]})]})]})}var ol=e.i(22016);let os={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 oi(e){if(e instanceof j.ApiError){let t=os[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 or={jaccardThreshold:.85,staleConfidenceThreshold:.3,maxAgeMs:7776e6,maxClustersPerRun:100,maxRecordsPerRun:1e3};function oo(e,t){return`${e.toString()} ${1===e?t:`${t}s`}`}function oc(e){return"completed"===e||"failed"===e||"canceled"===e||"skipped"===e}function od(e){return void 0===e?"—":new Date(e).toLocaleString()}function ou({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)(ol.default,{href:`/memoriaviva/detail?id=${encodeURIComponent(e)}`,className:"mc-id-link",title:e,children:e})}function oh({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)(ou,{id:e,onOpenDetail:t})]},`${l.toString()}:${e}`))})}function om({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)(ou,{id:e.proposedAction.winner,onOpenDetail:t}),"; replace ",(0,n.jsx)(oh,{ids:e.proposedAction.losers,onOpenDetail:t}),"."]}):(0,n.jsxs)(n.Fragment,{children:["Supersede ",(0,n.jsx)(ou,{id:e.proposedAction.older,onOpenDetail:t})," with"," ",(0,n.jsx)(ou,{id:e.proposedAction.newer,onOpenDetail:t}),"."]})}function op({flag:e,onOpenDetail:t}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ou,{id:e.memoryId,onOpenDetail:t})," — ",e.reason]})}function of({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 og({startJobImpl:e=ti,fetchJobImpl:t=tr,cancelJobImpl:l=to,pollIntervalMs:s=2e3,onBack:i,onOpenDetail:r}){var o;let[c,d]=(0,a.useState)(or),[u,h]=(0,a.useState)(null),[m,p]=(0,a.useState)(!1),[f,g]=(0,a.useState)(!1),[v,x]=(0,a.useState)(!1),[b,y]=(0,a.useState)(null),[j,w]=(0,a.useState)(null),k=u?.job??null,N=null!==k&&!oc(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);h(n.job),w(null)}catch(e){w(oi(e))}finally{g(!1)}},[t]);(0,a.useEffect)(()=>{if(null===k||oc(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(),!m&&!N){p(!0),y(null),w(null);try{let t=await e(c);h(t.job)}catch(e){y(oi(e))}finally{p(!1)}}},[c,e,m,N]),R=(0,a.useCallback)(async()=>{if(null!==k&&!v){x(!0),w(null);try{let e=await l(k.id);h(e.job)}catch(e){w(oi(e))}finally{x(!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)(ol.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)(of,{label:"Jaccard threshold",name:"jaccardThreshold",value:c.jaccardThreshold,min:0,max:1,step:.01,disabled:m||N,help:"Similarity floor for near-duplicate detection.",onChange:C}),(0,n.jsx)(of,{label:"Stale confidence threshold",name:"staleConfidenceThreshold",value:c.staleConfidenceThreshold,min:0,max:1,step:.01,disabled:m||N,help:"Memories at or below this confidence are flagged stale.",onChange:C}),(0,n.jsx)(of,{label:"Max age (days)",name:"maxAgeMs",value:c.maxAgeMs/864e5,min:0,step:1,disabled:m||N,help:"Memories older than this are checked for staleness.",onChange:(e,t)=>{C(e,864e5*t)}}),(0,n.jsx)(of,{label:"Max clusters per run",name:"maxClustersPerRun",value:c.maxClustersPerRun,min:0,max:1e3,step:1,disabled:m||N,help:"Hard bound on duplicate clusters inspected in one run.",onChange:C}),(0,n.jsx)(of,{label:"Max records per run",name:"maxRecordsPerRun",value:c.maxRecordsPerRun,min:0,max:1e3,step:1,disabled:m||N,help:"Hard bound on accepted records admitted to one scan.",onChange:C})]}),null!==b?(0,n.jsx)("div",{role:"alert",className:"lk-alert",children:b}):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":m||N,"aria-busy":m,children:m?"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:od(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:od(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!==j?(0,n.jsx)("div",{role:"alert",className:"lk-alert",children:j}):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:oo(S.reviewCount,"review item")}),(0,n.jsx)("span",{className:"mc-badge mc-badge-default",children:oo(S.staleCount,"stale flag")}),(0,n.jsx)("span",{className:"mc-badge mc-badge-default",children:oo(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)(oh,{ids:e.relatedMemoryIds,onOpenDetail:r})}),(0,n.jsx)("span",{style:{color:"var(--fg-muted)"},children:(0,n.jsx)(om,{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)(op,{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)(ou,{id:e.fromMemoryId,onOpenDetail:r})," →"," ",(0,n.jsx)(ou,{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 ov=["user","workspace","project","workflow","global"],ox=["episodic","semantic-fact","procedural","preference","correction","decision","negative","pinned"],ob=["public","confidential","restricted"],oy=["proposed","accepted","rejected","superseded","archived","forgotten","conflicted","expired"],oj={user:"User",workspace:"Workspace",project:"Project",workflow:"Workflow",global:"Global"},ow={episodic:"Episodic","semantic-fact":"Fact",procedural:"Procedural",preference:"Preference",correction:"Correction",decision:"Decision",negative:"Negative",pinned:"Pinned"},ok={proposed:"Proposed",accepted:"Accepted",rejected:"Rejected",superseded:"Superseded",archived:"Archived",forgotten:"Forgotten",conflicted:"Conflicted",expired:"Expired"},oN={public:"Public",confidential:"Confidential",restricted:"Restricted"};function oS(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function oC({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 oI({filters:e,onChange:t}){return(0,n.jsxs)("section",{className:"mc-filters","aria-label":"Memory filters",children:[(0,n.jsx)(oC,{label:"Scope",items:ov,labels:oj,active:e.scope,onToggle:n=>{t({...e,scope:oS(e.scope,n)})}}),(0,n.jsx)(oC,{label:"Type",items:ox,labels:ow,active:e.type,onToggle:n=>{t({...e,type:oS(e.type,n)})}}),(0,n.jsx)(oC,{label:"Status",items:oy,labels:ok,active:e.status,onToggle:n=>{t({...e,status:oS(e.status,n)})}}),(0,n.jsx)(oC,{label:"Sensitivity",items:ob,labels:oN,active:e.sensitivity,onToggle:n=>{t({...e,sensitivity:oS(e.sensitivity,n)})}})]})}let oE={public:"Public",confidential:"Confidential",restricted:"Restricted"};function oR({record:e,mode:t="edit",onSave:l,onClose:s,editMemoryImpl:i=td,correctMemoryImpl:r=tg}){let[o,c]=(0,a.useState)(e.body),[d,u]=(0,a.useState)(e.tags.join(", ")),[h,m]=(0,a.useState)(e.provenance.sensitivity),[p,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(null),[x,b]=(0,a.useState)(!1),y=(0,a.useRef)(null),j=(0,a.useRef)(null),w=(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=w.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(),w.current?.focus();return}let n=t[0],a=t[t.length-1];if(void 0===n||void 0===a){e.preventDefault(),w.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===j.current&&s()},[s]),R=(0,a.useCallback)(async()=>{let t=o.trim();if(0===t.length){v("Body cannot be empty."),b(!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:h});l(a.memory)}}catch(e){v(oi(e))}finally{f(!1)}},[o,d,h,e.id,C,r,i,l]);return(0,n.jsx)("div",{ref:j,className:"mc-dialog-backdrop",role:"presentation",onClick:E,children:(0,n.jsxs)("div",{ref:w,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),x&&(b(!1),v(null))},disabled:p,"aria-required":"true","aria-invalid":x?"true":void 0,"aria-describedby":x?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:h,onChange:e=>{m(e.target.value)},disabled:p,children:ob.map(e=>(0,n.jsx)("option",{value:e,children:oE[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 o$({record:e,mode:t="forget",onComplete:l,onClose:s,forgetMemoryImpl:i=tp,deleteMemoryImpl:r=tf}){let[o,c]=(0,a.useState)(!1),[d,u]=(0,a.useState)(null),h=(0,a.useRef)(null),m=(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,h.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]),x=(0,a.useCallback)(e=>{e.target===m.current&&s()},[s]),b=(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(oi(e)),c(!1)}},[r,i,g,l,e.id]);return(0,n.jsx)("div",{ref:m,className:"mc-dialog-backdrop",role:"presentation",onClick:x,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:h,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:()=>{b()},disabled:o,"aria-busy":o,children:o?g?"Deleting…":"Forgetting…":g?"Delete permanently":"Forget permanently"})]})]})})}function oT({record:e,onRecordChange:t,acceptImpl:l=tv,rejectImpl:s=tx,pinImpl:i=tu,unpinImpl:r=th,archiveImpl:o=tm,deleteImpl:c=tf,correctImpl:d=tg}){let[u,h]=(0,a.useState)(null),[m,p]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),[v,x]=(0,a.useState)(!1),[b,y]=(0,a.useState)(!1),[j,w]=(0,a.useState)(!1),[k,N]=(0,a.useState)(!1),S=(0,a.useCallback)(async(e,t)=>{if(null===u){h(e),p(null),g(null);try{await t()}catch(e){p(oi(e))}finally{h(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,q="accepted"===e.status||"superseded"===e.status||"conflicted"===e.status||"expired"===e.status,M="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,M?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),x(!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"})]}),M?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"}),q?(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,M?null:(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-danger","aria-disabled":null!==u,onClick:()=>{null===u&&(p(null),g(null),w(!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!==m?(0,n.jsx)("p",{role:"alert","aria-live":"assertive",className:"mc-action-error",children:m}):null,null!==f?(0,n.jsx)("p",{role:"status","aria-live":"polite",className:"mc-action-notice",children:f}):null,v?(0,n.jsx)(oR,{record:e,onSave:e=>{x(!1),t(e)},onClose:()=>{x(!1)}}):null,b?(0,n.jsx)(oR,{mode:"correct",record:e,correctMemoryImpl:d,onSave:T,onClose:()=>{y(!1)}}):null,j?(0,n.jsx)(o$,{record:e,onComplete:()=>{w(!1),t(null)},onClose:()=>{w(!1)}}):null,k?(0,n.jsx)(o$,{mode:"delete",record:e,deleteMemoryImpl:c,onComplete:()=>{N(!1),t(null)},onClose:()=>{N(!1)}}):null]})}function oA(e){return new Date(e).toLocaleString()}function oq({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 oM({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)(oq,{label:"Source kind",value:e.sourceKind}),(0,n.jsx)(oq,{label:"Captured at",value:oA(e.capturedAt)}),(0,n.jsx)(oq,{label:"Confidence",value:`${(100*e.confidence).toFixed(0)}%`}),(0,n.jsx)(oq,{label:"Sensitivity",value:e.sensitivity}),void 0!==e.captureRationale?(0,n.jsx)(oq,{label:"Rationale",value:e.captureRationale}):null,void 0!==e.modelIdentity?(0,n.jsx)(oq,{label:"Model",value:`${e.modelIdentity.provider} / ${e.modelIdentity.modelId}`}):null]})]})}function oP({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)(oq,{label:"Valid from",value:oA(e.validFrom)}),(0,n.jsx)(oq,{label:"Valid until",value:void 0!==e.validUntil?oA(e.validUntil):"No expiry"})]})]})}function oL({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 oD({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)(ol.default,{ref:t,href:"/memoriaviva",className:"mc-back-link lk-btn lk-btn-ghost","aria-label":"Back to MemoriaViva",children:a})}function oF({record:e,onBack:t}){return(0,n.jsxs)("header",{className:"mc-detail-header",children:[(0,n.jsx)(oD,{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:[ow[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 oz({id:e,fetchMemoryImpl:t=tc,onBack:l}){let[s,i]=(0,a.useState)(null),[r,o]=(0,a.useState)(!0),[c,d]=(0,a.useState)(null),[u,h]=(0,a.useState)(!1),m=(0,a.useRef)(null),p=(0,a.useCallback)(e=>{m.current=e},[]),f=(0,a.useCallback)(e=>{null===e&&h(!0),i(e)},[]);(0,a.useEffect)(()=>{u&&null===s&&m.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(oi(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)(oD,{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)(oD,{onBack:l,controlRef:p})})]})}):(0,n.jsxs)("article",{"aria-label":`Memory record: ${s.body.slice(0,60)}`,className:"mc-detail",children:[(0,n.jsx)(oF,{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)(oq,{label:"ID",value:(0,n.jsx)("code",{className:"mc-code",children:s.id})}),(0,n.jsx)(oq,{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)(oq,{label:"Type",value:ow[s.type]}),(0,n.jsx)(oq,{label:"Created",value:oA(s.createdAt)}),(0,n.jsx)(oq,{label:"Updated",value:oA(s.updatedAt)}),void 0!==s.staleReason?(0,n.jsx)(oq,{label:"Stale reason",value:(0,n.jsx)("em",{children:s.staleReason})}):null]})]}),(0,n.jsx)(oM,{provenance:s.provenance}),(0,n.jsx)(oP,{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)(oL,{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)(oT,{record:s,onRecordChange:f})]})]})}var oO=e.i(18566);let oK={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 oB({status:e}){let t=oK[e]??"mc-badge-default";return(0,n.jsx)("span",{className:`mc-badge ${t}`,children:e})}function o_({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:ow[e.type]}),(0,n.jsx)("span",{className:"mc-row-scope",children:oj[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)(oB,{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)(ol.default,{href:`/memoriaviva/detail?id=${encodeURIComponent(e.id)}`,className:"mc-row",children:l})})}function oU({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 oW({filters:e,onFilterChange:t,fetchMemoriesImpl:l=tl,onOpenDetail:s,onOpenConsolidation:i,onOpenReviewQueue:r,policyEnabled:o,onPolicyEnabledChange:c,showWorkspaceBackLink:d=!0}){let[u,h]=(0,a.useState)([]),[m,p]=(0,a.useState)(!0),[f,g]=(0,a.useState)(null),[v,x]=(0,a.useState)(!0),b=o??v,y=e.scope.length>0||e.type.length>0||e.status.length>0||e.sensitivity.length>0,j=(0,a.useCallback)(async e=>{p(!0),g(null);try{let t=await l(e);h(t.memories)}catch(e){g(oi(e))}finally{p(!1)}},[l]);return(0,a.useEffect)(()=>{j(e)},[e,j]),(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)(a$,{on:b,onChange:c??x,label:"Enable MemoriaViva policy"}),(0,n.jsxs)("span",{children:["Policy ",b?"on":"off"]})]}),d?(0,n.jsx)(ol.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)(ol.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)(ol.default,{href:"/memoriaviva/review-queue",className:"lk-btn lk-btn-ghost lk-btn-lg mc-queue-link",children:"Review queue"})]})]}),(0,n.jsx)(oI,{filters:e,onChange:t}),(0,n.jsx)("p",{role:"status",className:"visually-hidden",children:m||null!==f?null:`${u.length.toString()} ${1===u.length?"memory":"memories"} found`}),(0,n.jsx)("section",{"aria-label":"Memory records","aria-busy":m,style:{flex:1,minHeight:0,overflowY:"auto"},children:m&&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:()=>{j(e)},children:"Retry"})]}):0===u.length?(0,n.jsx)(oU,{hasFilters:y}):(0,n.jsx)("ul",{"aria-label":"Memory list",style:{listStyle:"none",padding:0,margin:0,display:"flex",flexDirection:"column",gap:4,opacity:m?.6:1,transition:"opacity 0.15s ease"},children:u.map(e=>(0,n.jsx)(o_,{record:e,onOpenDetail:s},e.id))})})]})}function oH({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:ow[e.type]}),(0,n.jsx)("span",{className:"mc-row-scope",children:oj[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)(ol.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 oG({fetchQueueImpl:e=ts,acceptImpl:t=tv,rejectImpl:l=tx,archiveImpl:s=tm,onBack:i,onOpenDetail:r}){let[o,c]=(0,a.useState)([]),[d,u]=(0,a.useState)(!0),[h,m]=(0,a.useState)(null),[p,f]=(0,a.useState)({}),[g,v]=(0,a.useState)({}),[x,b]=(0,a.useState)(""),y=(0,a.useRef)(null),j=(0,a.useRef)(null),w=(0,a.useRef)(null),k=(0,a.useCallback)(async()=>{u(!0),m(null);try{let t=await e();c(t.memories),f({}),v({})}catch(e){m(oi(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];w.current=void 0!==n?n.id:"",c(t=>t.filter(t=>t.id!==e)),N(e)},[o,N]);(0,a.useEffect)(()=>{let e=w.current;if(null===e)return;w.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():j.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),b("accept"===n?"Memory approved":"archive"===n?"Memory archived":"Memory rejected")}catch(e){v(t=>({...t,[a]:oi(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:j,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)(ol.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:x}),(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!==h?(0,n.jsxs)("div",{role:"alert","aria-live":"assertive",className:"lk-alert",children:[h,(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)(oH,{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 oV={scope:[],type:[],status:[],sensitivity:[]};function oY(){let[e,t]=(0,a.useState)({kind:"list"}),[l,s]=(0,a.useState)(oV),[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)(oW,{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)(oz,{id:e.id,onBack:o}):"consolidation"===e.kind?(0,n.jsx)(og,{onBack:o,onOpenDetail:c}):(0,n.jsx)(oG,{onBack:o,onOpenDetail:c})})}var oQ=e.i(96688),oJ=e.i(61774);function oX(e){return Array.from(e.querySelectorAll("button:not([disabled]),input:not([disabled]),[tabindex]:not([tabindex='-1'])"))}function oZ({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:oQ.STATUS_LABELS[e.lifecycleState]})]})})}function o0({capsules:e,onCancel:t,onCreated:l,createImpl:s=aT.createCapsuleSet}){let i,r=(0,a.useId)(),o=(0,a.useId)(),c=(0,a.useId)(),d=(0,a.useRef)(null),[u,h]=(0,a.useState)(""),[m,p]=(0,a.useState)(new Set),[f,g]=(0,a.useState)(!1),[v,x]=(0,a.useState)(null);function b(e){p(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),null!==v&&x(null)}async function y(e){var t;e.preventDefault();let n=(t=m.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 x(n);g(!0),x(null);try{await s({displayName:u.trim(),capsuleIds:[...m]}),l()}catch(e){x((0,oJ.formatError)(e))}finally{g(!1)}}(0,a.useEffect)(()=>{let e=document.activeElement,t=d.current;return null!==t&&oX(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=oX(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,oX(e)[0]?.focus()))},[d,f]);let j="Set name is required."===v,w="Select at least one capsule to combine."===v;return(0,eV.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":j,"aria-describedby":j?c:void 0,onChange:e=>{h(e.target.value),null!==v&&x(null)}})]}),(0,n.jsxs)("fieldset",{className:"lk-compose-fieldset",disabled:f,"aria-invalid":w,"aria-describedby":w?c:void 0,children:[(0,n.jsxs)("legend",{className:"mc-dialog-label",children:["Capsules (",m.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)(oZ,{capsule:e,checked:m.has(e.id),disabled:f,onToggle:b},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 o1=e.i(80010);function o2({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 o4(e){return Array.from(e.querySelectorAll("button:not([disabled]),input:not([disabled]),textarea:not([disabled]),select:not([disabled]),[tabindex]:not([tabindex='-1'])"))}function o3({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),h=(0,a.useRef)(null),[m,p]=(0,a.useState)(""),[f,g]=(0,a.useState)(null);(0,a.useEffect)(()=>(h.current=document.activeElement,u.current?.focus(),()=>{h.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=o4(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 x(e){e.preventDefault();let t=m.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,o4(t)[0]?.focus()))},[e]);let b=f??t;return(0,eV.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 x(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:m,disabled:e,autoComplete:"off","aria-invalid":null!==b,"aria-describedby":null!==b?c:void 0,onChange:e=>{p(e.target.value),null!==f&&g(null)}})]}),null!==b?(0,n.jsx)("div",{id:c,role:"alert","aria-live":"assertive",className:"mc-dialog-error",children:b}):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 o6({capsuleName:e,onCancel:t,onConfirm:l}){let s=(0,a.useId)(),i=(0,a.useId)(),r=(0,a.useRef)(null);return(0,a.useEffect)(()=>{let e=document.activeElement,t=r.current;return null!==t&&o4(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=o4(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,eV.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 o5(){return(0,n.jsx)("svg",{"aria-hidden":"true",focusable:"false",width:"40",height:"24",viewBox:"0 0 40 24",style:{flexShrink:0,alignSelf:"center"},children:(0,n.jsx)("path",{d:"M2 12 H32 M28 6 L38 12 L28 18",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none",opacity:"0.7"})})}let o8={"files-window":"📂","local-knowledge":"🧠","capsule-pool":"⬡","conversation-center":"💬"};function o9({kind:e,label:t,sublabel:a,connected:l=!1}){return(0,n.jsxs)("div",{className:"lk-node","data-connected":String(l),children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"lk-node-icon",children:o8[e]}),(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{className:"lk-node-label",children:[t,l?(0,n.jsx)("span",{"aria-hidden":"true",className:"lk-node-tick",children:"✓"}):null]}),void 0!==a?(0,n.jsx)("div",{className:"lk-node-sub",children:a}):null,(0,n.jsx)("span",{className:"visually-hidden",children:l?"Connected":"Not connected"})]})]})}function o7({children:e}){return(0,n.jsx)("div",{role:"listitem",style:{display:"flex",alignItems:"center",gap:8,flexShrink:0},children:e})}function ce({capsules:e,isLoading:t}){var a;let l=e.some(e=>"ready"===e.lifecycleState),s=e.length>0;return(0,n.jsx)("section",{"aria-label":"Connector pipeline diagram",style:{flexShrink:0},children:(0,n.jsxs)("div",{role:"list","aria-label":"Pipeline nodes",className:"lk-pipeline",children:[(0,n.jsxs)(o7,{children:[(0,n.jsx)(o9,{kind:"files-window",label:"Files Window",sublabel:"Source",connected:s}),(0,n.jsx)(o5,{})]}),(0,n.jsxs)(o7,{children:[(0,n.jsx)(o9,{kind:"local-knowledge",label:"Local Knowledge",sublabel:"Connector",connected:s}),(0,n.jsx)(o5,{})]}),(0,n.jsxs)(o7,{children:[(0,n.jsx)(o9,{kind:"capsule-pool",label:"Capsules",sublabel:(a=e.length,t?"Loading…":0===a?"No capsules":`${a.toString()} capsule${1===a?"":"s"}`),connected:s}),(0,n.jsx)(o5,{})]}),(0,n.jsx)(o7,{children:(0,n.jsx)(o9,{kind:"conversation-center",label:"Conversation Center",sublabel:"Consumer",connected:l})})]})})}function ct({state:e}){return(0,n.jsx)("span",{className:"lk-badge","data-state":e,children:oQ.STATUS_LABELS[e]})}function cn({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 h=d>0;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",disabled:t,"aria-disabled":!h||void 0,"aria-busy":"index"===l,"aria-label":`Start indexing capsule ${o}`,"aria-describedby":h?void 0:u,title:h?void 0:"Attach a source before indexing this capsule.",onClick:()=>{h&&s(r)},className:"lk-btn lk-btn-primary",children:"index"===l?"Indexing…":"Index"}),h?null:(0,n.jsx)("span",{id:u,className:"visually-hidden",children:"Attach a source before indexing."})]})}function ca({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)(cn,{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 cl(e){return e instanceof Element&&null!==e.closest(".lk-capsule-actions,a,input,select,textarea")}function cs(e,t){let n=document.elementFromPoint(e,t);return n instanceof Element&&null!==n.closest("main.workspace")&&null===n.closest(".window")}function ci(e,t){let n={payload:e,clientX:t.clientX,clientY:t.clientY};window.dispatchEvent(new CustomEvent(ez,{detail:n}))}function cr({capsule:e,busy:t,busyKind:l,onStart:s,onCancel:i,onDisconnect:r,onHealth:o,onAddToWorkspace:c}){let[d,u]=(0,a.useState)(null),h=(0,a.useRef)(!1),m=(0,a.useRef)(!1),p={kind:"capsule",id:e.id,label:e.displayName,lifecycleState:e.lifecycleState},f=e=>{m.current||(m.current=!0,ci(p,e),window.setTimeout(()=>{m.current=!1},250))},g=(t,n)=>{h.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),h.current=!1,document.body.style.cursor="",u(null),a&&cs(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=>{cl(e.target)||(e.stopPropagation(),0===e.button&&(e.preventDefault(),g(e.clientX,e.clientY)))},onMouseDown:e=>{h.current||cl(e.target)||(e.stopPropagation(),0===e.button&&(e.preventDefault(),g(e.clientX,e.clientY)))},onDragStart:t=>{cl(t.target)?t.preventDefault():(t.dataTransfer.effectAllowed="copy",t.dataTransfer.setData(eF,JSON.stringify(p)),t.dataTransfer.setData("text/plain",e.displayName))},onDragEnd:e=>{cs(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)(ct,{state:e.lifecycleState})]})]}),(0,n.jsx)(ca,{capsule:e,busy:t,busyKind:l,onStart:s,onCancel:i,onDisconnect:r,onHealth:o,onAddToWorkspace:c})]}),null!==d?(0,eV.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:oQ.STATUS_LABELS[d.state]})]})]}),document.body):null]})}function co({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 cc({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)(co,{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)(cr,{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&&ci({kind:"capsule",id:e.id,label:e.displayName,lifecycleState:e.lifecycleState},t)}})},e.id))})}function cd({creating:e,createDialogOpen:t,combineDialogOpen:l,combineDisabled:s,showBackToWorkspace:i,loadStatus:r,loadError:o,actionError:c,createError:d,reload:u,onCreateCapsule:h,onCombineCapsules:m,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)(ol.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||m()},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:h,className:"lk-btn lk-btn-primary lk-btn-lg",children:e?"Creating…":"Create capsule"})]})]}),"error"===r&&null!==o?(0,n.jsx)(o2,{message:o,onRetry:u}):null,null===d||t?null:(0,n.jsx)(o2,{message:d,onDismiss:p}),null!==c?(0,n.jsx)(o2,{message:c,onDismiss:f}):null]})}function cu(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:h,actionBusy:m,actionKind:p,actionError:f,creating:g,createError:v,reload:x,clearCreateError:b,clearActionError:y,handleStartIndexing:j,handleCancelIndexing:w,handleDisconnect:k,handleOpenHealth:N,handleCreateCapsule:S}=function(e){let{fetchCapsulesImpl:t=aT.fetchCapsules,createCapsuleImpl:n=aT.createCapsule,startIndexingImpl:l=aT.startIndexing,cancelIndexingImpl:s=aT.cancelIndexing,disconnectCapsuleImpl:i=aT.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,oJ.formatError)(e)),s("error")}},[e]);return(0,a.useEffect)(()=>{o()},[o]),{capsules:t,loadStatus:l,loadError:i,reload:function(){o()}}}(t),{actionBusy:h,actionKind:m,actionError:p,clearActionError:f,handleStartIndexing:g,handleCancelIndexing:v,handleDisconnect:x,handleOpenHealth:b}=function(e,t,n,l,s){let i=(0,oO.useRouter)(),[r,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(null),[u,h]=(0,a.useState)(null);async function m(t,n,a){o(t),d(n),h(null);try{await a(),e()}catch(e){h((0,oJ.formatError)(e))}finally{o(null),d(null)}}return{actionBusy:r,actionKind:c,actionError:u,clearActionError:function(){h(null)},handleStartIndexing:function(e){m(e,"index",()=>t(e))},handleCancelIndexing:function(e){m(e,"cancel",()=>n(e))},handleDisconnect:function(e){m(e,"disconnect",()=>l(e))},handleOpenHealth:function(e){void 0!==s?s(e):i.push(`/local-knowledge/capsule?capsuleId=${encodeURIComponent(e)}`)}}}(u,l,s,i,r),{creating:y,createError:j,clearCreateError:w,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,oJ.formatError)(e))}finally{l(!1)}}}}(n,u);return{capsules:o,loadStatus:c,loadError:d,actionBusy:h,actionKind:m,actionError:p,creating:y,createError:j,reload:u,clearCreateError:w,clearActionError:f,handleStartIndexing:g,handleCancelIndexing:v,handleDisconnect:x,handleOpenHealth:b,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 q(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),x()},children:"Back to capsules"}),(0,n.jsx)(o1.CapsuleDetail,{capsuleId:r,onDeleted:()=>{o(null),x()}})]}):(0,n.jsxs)("div",{className:"lk-page",children:[(0,n.jsx)(cd,{creating:g,createDialogOpen:I,combineDialogOpen:R,combineDisabled:C||0===d.length,showBackToWorkspace:i,loadStatus:u,loadError:h,actionError:f,createError:v,reload:x,onCreateCapsule:()=>E(!0),onCombineCapsules:()=>$(!0),onDismissCreateError:b,onDismissActionError:y}),(0,n.jsx)(ce,{capsules:d,isLoading:C}),(0,n.jsx)("p",{role:"status",className:"visually-hidden",children:C||null!==h?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)(cc,{capsules:d,isLoading:C,creating:g,actionBusy:m,actionKind:p,onCreateCapsule:()=>E(!0),onStartIndexing:j,onCancelIndexing:w,onDisconnect:e=>A(d.find(t=>t.id===e)??null),onOpenHealth:N})]}),I?(0,n.jsx)(o3,{busy:g,error:v,onCancel:()=>{E(!1),b()},onSubmit:q}):null,R?(0,n.jsx)(o0,{capsules:d,onCancel:()=>$(!1),onCreated:function(){$(!1),x()}}):null,null!==T?(0,n.jsx)(o6,{capsuleName:T.displayName,onCancel:()=>A(null),onConfirm:()=>{k(T.id),A(null)}}):null]})}function ch(e,t){let n=e[t];return"string"==typeof n?n:void 0}function cm({cfg:e,ctx:t}){let l=t3({autoCreate:!1}),i=(0,a.useRef)(!1),r=ch(e,"chatId"),o=ch(e,"title"),{updateCfg:c}=t,{activeChat:d,chats:u,loading:h,openChat:m,openNewChat:p}=l,f=void 0!==d&&"closed"!==d.status?d:void 0;(0,a.useEffect)(()=>{if(!h){if(void 0!==r){if(f?.id===r)return;let e=u.find(e=>e.id===r&&"closed"!==e.status);void 0!==e&&m(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,h,m,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)(a9,{mini:!0===t.mini,linkedRoot:t.linkedRoot})})}I("chat",(e,t)=>(0,n.jsx)(cm,{cfg:e,ctx:t})),I("chatHistory",(e,t)=>(0,n.jsx)(la,{openChatWindow:e=>{t.openWindow("chat",{chatId:e.id,title:e.title})}})),I("project",()=>(0,n.jsx)(ln,{})),I("search",()=>(0,n.jsx)(ll,{})),I("plugins",()=>(0,n.jsx)(lo,{})),I("automations",()=>(0,n.jsx)(lm,{})),I("mobile",()=>(0,n.jsx)(lp,{})),I("inspector",()=>(0,n.jsx)(lf,{})),I("notifications",()=>(0,n.jsx)(lv,{})),I("resources",()=>(0,n.jsx)(lx,{})),I("activity",()=>(0,n.jsx)(lj,{})),I("keiko",()=>(0,n.jsx)(sy,{})),I("settings",()=>(0,n.jsx)(sE,{})),I("localKnowledge",()=>(0,n.jsx)(cu,{showBackToWorkspace:!1})),I("quality",(e,t)=>(0,n.jsx)(iA,{openRun:(e,n)=>{let a=void 0!==n?{[iv]:JSON.stringify(n.filter(iy))}:ij(iS({connectedFilePath:t.linkedFilePath??null,connectedRoot:t.linkedRoot,connectedRoots:t.linkedRoots,connectedCapsuleIds:t.linkedCapsuleIds,connectedCapsuleSetIds:t.linkedCapsuleSetIds,connectedFigmaSnapshotRunIds:t.linkedFigmaSnapshotRunIds}));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})),I("qiRun",(e,t)=>{let a=ch(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=ix(e,iv);if(void 0!==t&&t.length>0){let e=function(e){try{let t=JSON.parse(e);if(!Array.isArray(t)||!t.every(iy))return null;return t}catch{return null}}(t);if(null!==e)return e}return iS({connectedFilePath:ix(e,"connectedFilePath")??null,connectedRoot:ix(e,"connectedRoot")??null})}(e),s=ij(l);return(0,n.jsx)(rf,{runId:a,connectedSources:l,onRegenerated:e=>{t.openWindow("qiRun",{runId:e.runId,...s})}})}),I("relationships",()=>(0,n.jsx)(oa,{})),I("files",(e,t)=>{let a=ch(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)(lP,{root:a,onActiveFileChange:l,onRootChange:s,onOpenFile:i}):(0,n.jsx)(lP,{onActiveFileChange:l,onRootChange:s,onOpenFile:i})}),I("editor",e=>{let t=ch(e,"root"),a=ch(e,"file"),l={};return void 0!==t&&(l.root=t),void 0!==a&&(l.file=a),(0,n.jsx)(lF,{...l})}),I("browser",e=>{let t=ch(e,"url");return void 0!==t&&""!==t?(0,n.jsx)(lV,{url:t}):(0,n.jsx)(lV,{})}),I("terminal",e=>{let t=ch(e,"cwd"),a=ch(e,"projectPath"),l={};return void 0!==t&&(l.cwd=t),void 0!==a&&(l.projectPath=a),(0,n.jsx)(l1,{...l})}),I("review",(e,t)=>{let a=ch(e,"runId"),l=e=>{t.updateCfg({runId:e})};return void 0!==a&&""!==a?(0,n.jsx)(st,{runId:a,onRunIdSubmit:l}):(0,n.jsx)(st,{onRunIdSubmit:l})}),I("agents",(e,t)=>{var a;let l,s,i,r,o,c,d,u,h,m,p;return(0,n.jsx)(sr,{cfg:(i={},void 0!==(r=ch(a=e,"workflow"))&&(i.workflow=r),void 0!==(o=ch(a,"model"))&&(i.model=o),void 0!==(c=ch(a,"runId"))&&(i.runId=c),void 0!==(d=ch(a,"fingerprint"))&&(i.fingerprint=d),void 0!==(u=ch(a,"workspaceRoot"))&&(i.workspaceRoot=u),void 0!==(h=ch(a,"inputJson"))&&(i.inputJson=h),void 0!==(m="boolean"==typeof(l=a.keikoMode)?l:void 0)&&(i.keikoMode=m),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)(oY,{})),I("integ",()=>(0,n.jsx)(sc,{})),I("figma",(e,t)=>{let a=ch(e,"snapshotRunId");return(0,n.jsx)(sV,{snapshotRunId:a,updateCfg:e=>{t.updateCfg(e)}})}),I("connector",(e,t)=>{let a=ch(e,"presentation"),l=ch(e,"selectedKind"),s=ch(e,"selectedId"),i=ch(e,"selectedLabel"),r=ch(e,"selectedState");return(0,n.jsx)(sP,{presentation:a,selectedKind:l,selectedId:s,selectedLabel:i,selectedState:r,onSelect:e=>{t.updateCfg(e)},onManageConnectors:()=>{t.openWindow("localKnowledge")}})});let cp={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 cf(){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=cp[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 cg(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 cv=["chat","connector","figma","files","terminal","review"],cx=["chatHistory","memoria","settings","automations","mobile","inspector","activity","notifications","resources","localKnowledge","quality","relationships"];function cb(){var e,t,l;let i,{theme:r,toggle:o}=function(){let[e,t]=(0,a.useState)(t5),[n,l]=(0,a.useState)(!1);return(0,a.useEffect)(()=>{t(function(){try{let e=window.localStorage.getItem(t6);return"light"===e||"dark"===e?e:t5}catch{return t5}}()),l(!0)},[]),(0,a.useEffect)(()=>{if(n){"u">typeof document&&(document.documentElement.dataset.theme=e);try{window.localStorage.setItem(t6,e)}catch{}}},[e,n]),{theme:e,toggle:(0,a.useCallback)(()=>{t(e=>"light"===e?"dark":"light")},[])}}(),c=b(),d=t3({autoCreate:!1}),u=(0,a.useRef)(null),h=(0,a.useRef)(null),[m,p]=(0,a.useState)(t8.DEFAULT_GROUNDING_LIMITS);(0,a.useEffect)(()=>{(0,j.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),[]),x=(0,a.useCallback)(e=>(g(e),!1),[]),w=(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}(h.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=w(e);if(void 0===l)return x("Open a ready chat window before connecting a source.");let s=null===n?eN(l):ek(eN(l),n),i=eS(l);if(s.some(e=>eb(e,t))){if(null!==n){let e=await (0,j.updateChatConnectedScopes)(l.id,s.length>0?s:null);d.replaceChat(e.chat)}return!0}let r=ew(m);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=eg(t.root);if(!ef(a))return null;let l=t.relativePaths.map(ex),s={kind:t.kind,relativePaths:l,root:a,connectedAtMs:t.connectedAtMs};return e.some(e=>eb(e,s))||e.length>=n?e:[...e,s]}(s,o,m.maxConnectedSources);if(null===c)return x("Choose a local folder before connecting it to chat.");if(c===s)return v(s.length+i.length,r);try{let e=await (0,j.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&&nc({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 x("Keiko could not connect that source. Check that it is still available and try again.")}},[w,d,m,v,x]),N=function(e,t={}){var n,l,s,i,r,o,c,d,u;let[h,m]=(0,a.useState)(null),[p,f]=(0,a.useState)(null),[g,v]=(0,a.useState)(!1),[x,b]=(0,a.useState)([]),[y,j]=(0,a.useState)(null),[w,k]=(0,a.useState)(eA),N=(0,a.useRef)(3),S=(0,a.useRef)(null),C=(0,a.useRef)([]);C.current=h??[];let I=(0,a.useRef)([]);I.current=x;let R=(0,a.useRef)(null);R.current=y;let T=(0,a.useRef)(null),q=(0,a.useRef)(()=>void 0),{viewRef:M,worldVP:P,zoomTo:L,resetView:D,panBy:F,rect:z}=function({wsRef:e,view:t,setView:n,setWins:l}){let s=(0,a.useRef)(t);s.current=t,(0,a.useEffect)(()=>{eL(eT,t)},[t]),(0,a.useEffect)(()=>{let t=e.current;if(null===t)return;let a=e=>{if(e.metaKey||e.ctrlKey){var a;e.preventDefault();let i=(a=e.target)instanceof Element?a.closest(".window[data-window-id]")?.dataset.windowId??null:null;if(null!==i)return void l(t=>null===t?t:t.map(t=>{var n,a;let l,s;return t.id===i?(n=t,a=e.deltaY,(s=eM((l=n.zoom??1)*Math.exp(-(.0015*a))))===l?n:{...n,zoom:s}):t}));let r=t.getBoundingClientRect(),o=s.current,c=eq(o.zoom*Math.exp(-(.0015*e.deltaY))),d=(e.clientX-r.left-o.x)/o.zoom,u=(e.clientY-r.top-o.y)/o.zoom;return void n({zoom:c,x:e.clientX-r.left-d*c,y:e.clientY-r.top-u*c})}let i=e.target;i instanceof Element&&null!==i.closest(".window")||(e.preventDefault(),n(t=>({...t,x:t.x-e.deltaX,y:t.y-e.deltaY})))};return t.addEventListener("wheel",a,{passive:!1}),()=>{t.removeEventListener("wheel",a)}},[e,n,l]);let i=(0,a.useCallback)(()=>null===e.current?null:e.current.getBoundingClientRect(),[e]),r=(0,a.useCallback)(()=>{let e=i();if(null===e)return null;let t=s.current;return{x:-t.x/t.zoom,y:-t.y/t.zoom,w:e.width/t.zoom,h:e.height/t.zoom}},[i]),o=(0,a.useCallback)(e=>{let t=i();if(null===t)return;let a=s.current,l=t.width/2,r=t.height/2,o=(l-a.x)/a.zoom,c=(r-a.y)/a.zoom,d=eq(e);n({zoom:d,x:l-o*d,y:r-c*d})},[i,n]);return{viewRef:s,worldVP:r,zoomTo:o,resetView:(0,a.useCallback)(()=>n({zoom:1,x:0,y:0}),[n]),panBy:(0,a.useCallback)((e,t)=>n(n=>({...n,x:n.x+e,y:n.y+t})),[n]),rect:i}}({wsRef:e,view:w,setView:k,setWins:m});!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=ec(t);return n.length>0?n:null}catch{return null}}(window.localStorage.getItem(eR))}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 ed(n,t)}catch{return[]}}(window.localStorage.getItem(e$),s))}catch{}},[e,t,n,l])}({wsRef:e,setWins:m,setConns:b,zc:N}),(0,a.useEffect)(()=>{null!==h&&eL(e$,ed(x,h))},[x,h]),(0,a.useEffect)(()=>{null!==h&&b(e=>{let t=e.filter(e=>void 0!==h.find(t=>t.id===e.a)&&void 0!==h.find(t=>t.id===e.b));return t.length===e.length?e:t})},[h,b]),(0,a.useEffect)(()=>{null!==h&&eL(eR,ec(h))},[h]),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=eD[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=eP(e);if(null===n)return e;let a=(t=n.zoom??1,"0"===i?1:"-"===i||"_"===i?eM(t-.1):eM(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=eP(e);if(null===u)return e;let h=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,...h,max:!1}:e)}))};return window.addEventListener("keydown",a),()=>{window.removeEventListener("keydown",a)}},[e,t,n])}({setWins:m,rect:z,cancelConnectRef:q}),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:M,setWins:m});let{update:O,focus:K,close:B,minimize:_,restore:U,maximize:W,add:H,toggleTool:G}={update:(l=(n={setWins:m,zc:N,worldVP:P}).setWins,(e,t)=>l(n=>null===n?n:n.map(n=>n.id===e?{...n,...t}: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=null;return t(t=>{let r=a();if(null===r)return t;let o=t??[];if(!0===s.singleton){let t=o.find(t=>t.type===e);if(void 0!==t)return i=t.id,o.map(e=>e.id===t.id?{...e,minimized:!1,z:++n.current}:e)}let c="qiRun"===e?l?.runId:void 0;if("string"==typeof c&&c.length>0){let e=o.find(e=>"qiRun"===e.type&&e.cfg.runId===c);if(void 0!==e)return i=e.id,o.map(t=>t.id===e.id?{...t,cfg:void 0===l?t.cfg:{...t.cfg,...l},minimized:!1,z:++n.current}:t)}let d="chat"===e?l?.chatId:void 0;if("string"==typeof d&&d.length>0){let e=o.find(e=>"chat"===e.type&&e.cfg.chatId===d);if(void 0!==e)return i=e.id,o.map(t=>t.id===e.id?{...t,minimized:!1,z:++n.current}:t)}let{x:u,y:h}=eu(r,s.w,s.h,o.length,40),m=!0===s.singleton?e:`${e}-${Date.now().toString(36)}`;return i=m,[...o,{id:m,type:e,x:u,y:h,w:s.w,h:s.h,z:++n.current,cfg:l??{},max:!1,zoom:1}]}),i}}(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}=eu(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:V,splitFront:Y,cascade:Q}={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{...eh(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:m,worldVP:P}),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?{...eh(e),max:!1,minimized:!1,x:n.x,y:n.y,w:n.w/2,h:n.h}:1===t?{...eh(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)=>({...eh(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:J,commitSnap:X}=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:P,update:O}),{startConnect:Z,confirmConnect:ee,cancelConnect:et,removeConn:en,connect:ea,linkedFilesRoot:el,linkedFilesContext:es,linkedAllFilesRoots:ei,linkedConnectorCapsuleIds:er,linkedConnectorCapsuleSetIds:eo,linkedFigmaSnapshotRunIds:eg,currentFilesContext:ex}=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:h,onConnectorUnbind:m}=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||!ef(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};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 h={from:e,x:d(a.clientX),y:u(a.clientY)};s.current=h,c(h);let m=t=>{let n={from:e,x:d(t.clientX),y:u(t.clientY)};s.current=n,c(n)};window.addEventListener("pointermove",m),i.current=()=>{window.removeEventListener("pointermove",m)}},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=ey(i,c,Date.now()),s=null===l?eE(i,c):null,u=null!==l||null!==s?ep(i,c):null;try{t=null!==l&&null!==u?d?.(u,l)??!0:null===s||null!==u&&(h?.(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=>em(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?ep(s,i):null),d=ej(t)??(r?ey(s,i,Date.now()):null);null!==d&&null!==c&&u?.(c,d);let h=eI(t)??(r?eE(s,i):null);null!==h&&null!==c&&m?.(c,h)},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=>em(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=ev(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)continue;let r=i.cfg.snapshotRunId;"string"==typeof r&&0!==r.trim().length&&(t.has(r)||(t.add(r),n.push(r)))}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:M,winsRef:C,connsRef:I,connectingRef:R,connectCleanupRef:T,focus:K,setConns:b,setConnecting:j,onScopeBind:t.onScopeBind,onScopeUnbind:t.onScopeUnbind,onConnectorBind:t.onConnectorBind,onConnectorUnbind:t.onConnectorUnbind});return q.current=et,(0,a.useEffect)(()=>()=>{null!==T.current&&(T.current(),T.current=null)},[]),{wins:h,snapPrev:p,palOpen:g,setPalOpen:v,conns:x,connecting:y,view:w,api:{add:H,toggleTool:G,focus:K,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=ej(a)??ey(n,s,Date.now());null!==r&&null!==i&&t.onScopeUnbind?.(i,r);let o=eI(a)??eE(n,s);null!==o&&null!==i&&t.onConnectorUnbind?.(i,o)}B(e)},minimize:_,restore:U,maximize:W,update:O,setSnap:J,commitSnap:X,tileAll:V,splitFront:Y,cascade:Q,startConnect:Z,confirmConnect:ee,cancelConnect:et,removeConn:en,updateConnBoundScope:(e,t)=>{b(n=>n.map(n=>n.id===e?{...n,boundScopeKind:t.kind,...void 0!==t.root?{boundRoot:t.root}:{},...void 0!==t.relativePaths[0]?{boundRelativePath:t.relativePaths[0]}:{}}:n))},connect:ea,linkedFilesRoot:el,linkedFilesContext:es,linkedAllFilesRoots:ei,linkedConnectorCapsuleIds:er,linkedConnectorCapsuleSetIds:eo,linkedFigmaSnapshotRunIds:eg,currentFilesContext:ex,zoomTo:L,resetView:D,panBy:F,rect:z}}}(u,{onScopeBind:(0,a.useCallback)(async(e,t)=>k(e,t),[k]),onScopeUnbind:(0,a.useCallback)((e,t)=>{let n=w(e);if(void 0===n)return;let a=ek(eN(n),t);(0,j.updateChatConnectedScopes)(n.id,a.length>0?a:null).then(e=>{d.replaceChat(e.chat)}).catch(e=>{console.warn("[keiko] connected-scope unbind failed",e)})},[w,d]),onConnectorBind:(0,a.useCallback)(async(e,t)=>{var n;let a,l,s=w(e);if(void 0===s)return x("Open a ready chat window before connecting a source.");let i=eS(s),r=eN(s);if(a=eC(t),i.some(e=>eC(e)===a))return!0;let o=ew(m);if(r.length+i.length>=o)return v(r.length+i.length,o);let c=(n=m.maxLocalKnowledgeSources,l=eC(t),i.some(e=>eC(e)===l)||i.length>=n?i:[...i,t]);if(c===i)return v(r.length+i.length,o);try{let e=await (0,j.updateChatLocalKnowledgeScopes)(s.id,c);return d.replaceChat(e.chat),g(null),!0}catch{return x("Keiko could not connect that knowledge source. Check that it is still available and try again.")}},[w,d,m,v,x]),onConnectorUnbind:(0,a.useCallback)((e,t)=>{var n;let a=w(e);if(void 0===a)return;let l="capsule"===t.kind?`capsule:${t.capsuleId}`:`set:${t.capsuleSetId}`,s=(n=eS(a),n.filter(e=>eC(e)!==l));(0,j.updateChatLocalKnowledgeScopes)(a.id,s.length>0?s:null).then(e=>{d.replaceChat(e.chat)}).catch(()=>void 0)},[w,d])});h.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=ey(t,n,Date.now());if(null===l)continue;let s=ej(e);cg(s)!==cg(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,q]=(0,a.useState)(!1),[L,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),[]),G=(0,a.useCallback)(()=>D(!1),[]),V=(0,a.useCallback)(e=>{N.api.restore(e),D(!1)},[N.api]),Y=(0,a.useCallback)(e=>{C(!1),R(e)},[]),Q=(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]),J=(0,a.useCallback)(()=>R(null),[]),X=(0,a.useCallback)(()=>q(!1),[]),Z=(0,a.useCallback)(()=>q(!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)(ny),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(ny)},[]);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?nx(e):null,redoLabel:void 0!==t?nx(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)(()=>Y("chat"),[Y]),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=nb(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 nv)if(nb(e)===nb(t))return!0;return!1})(e.chord)),[t]);if(i.length>0)throw new nj(i);if(r.length>0)throw new nw(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:nk,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(),q(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 cv){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 cx){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,Y,r,o,en),[N.api,ea,Y,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"),eF=void 0!==d.activeProject,ez=d.activeProject?.available===!0,eO=(t={loading:d.loading,error:d.error,hasProject:eF,projectAvailable:ez,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",eK=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",eB=void 0!==(l=d.activeChat?.branchLabel)&&l.trim().length>0?l:"No branch selected",e_=S?(0,n.jsx)(tt,{types:E,order:cv,onAdd:Y,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)("h1",{className:"visually-hidden",children:"Keiko workspace"}),(0,n.jsx)(P,{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",children:[(0,n.jsx)(eH,{ws:N,wsRef:u,openPalette:U,palette:e_}),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)(M,{winCount:O,windows:N.wins??[],windowPaletteOpen:L,onToggleWindowPalette:H,onSelectWindow:V,onCloseWindowPalette:G,mode:c.mode,selectedModel:d.selectedModel,projectName:eo,branchLabel:eB,shellStatusLabel:eO,evidenceStatusLabel:eK,statusRef:et}),null!==I&&(0,n.jsx)(e7,{type:I,types:E,filesContext:N.api.currentFilesContext(),onConfirm:Q,onClose:J}),T&&(0,n.jsx)(eG,{commands:ei,onClose:X}),er?(0,n.jsx)(eQ,{}):null,(0,n.jsx)(cf,{})]})})})}function cy(){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)(x,{children:(0,n.jsx)(cb,{})}):(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)(cy,{})}],89199)}]);