@oscharko-dev/keiko 0.2.0-beta.6 → 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.
- package/dist/ui/csp-hashes.json +14 -14
- package/dist/ui/static/404.html +1 -1
- package/dist/ui/static/__next.__PAGE__.txt +2 -2
- package/dist/ui/static/__next._full.txt +3 -3
- package/dist/ui/static/__next._head.txt +1 -1
- package/dist/ui/static/__next._index.txt +2 -2
- package/dist/ui/static/__next._tree.txt +2 -2
- package/dist/ui/static/_next/static/chunks/0i3jzgrj42so8.css +1 -0
- package/dist/ui/static/_next/static/chunks/1ru_021szp0u7.js +1 -0
- package/dist/ui/static/_next/static/chunks/1t7vb5d9ed2e7.js +1 -0
- package/dist/ui/static/_next/static/chunks/23o2c6pyjq92z.js +109 -0
- package/dist/ui/static/_not-found/__next._full.txt +2 -2
- package/dist/ui/static/_not-found/__next._head.txt +1 -1
- package/dist/ui/static/_not-found/__next._index.txt +2 -2
- package/dist/ui/static/_not-found/__next._not-found.__PAGE__.txt +1 -1
- package/dist/ui/static/_not-found/__next._not-found.txt +1 -1
- package/dist/ui/static/_not-found/__next._tree.txt +2 -2
- package/dist/ui/static/_not-found.html +1 -1
- package/dist/ui/static/_not-found.txt +2 -2
- package/dist/ui/static/fonts/OFL.txt +93 -0
- package/dist/ui/static/fonts/jetbrains-mono-latin-wght-normal.woff2 +0 -0
- package/dist/ui/static/index.html +1 -1
- package/dist/ui/static/index.txt +3 -3
- package/dist/ui/static/launch/__next._full.txt +3 -3
- package/dist/ui/static/launch/__next._head.txt +1 -1
- package/dist/ui/static/launch/__next._index.txt +2 -2
- package/dist/ui/static/launch/__next._tree.txt +2 -2
- package/dist/ui/static/launch/__next.launch.__PAGE__.txt +2 -2
- package/dist/ui/static/launch/__next.launch.txt +1 -1
- package/dist/ui/static/launch.html +1 -1
- package/dist/ui/static/launch.txt +3 -3
- package/dist/ui/static/local-knowledge/__next._full.txt +3 -3
- package/dist/ui/static/local-knowledge/__next._head.txt +1 -1
- package/dist/ui/static/local-knowledge/__next._index.txt +2 -2
- package/dist/ui/static/local-knowledge/__next._tree.txt +2 -2
- package/dist/ui/static/local-knowledge/__next.local-knowledge.__PAGE__.txt +2 -2
- package/dist/ui/static/local-knowledge/__next.local-knowledge.txt +1 -1
- package/dist/ui/static/local-knowledge/capsule/__next._full.txt +3 -3
- package/dist/ui/static/local-knowledge/capsule/__next._head.txt +1 -1
- package/dist/ui/static/local-knowledge/capsule/__next._index.txt +2 -2
- package/dist/ui/static/local-knowledge/capsule/__next._tree.txt +2 -2
- package/dist/ui/static/local-knowledge/capsule/__next.local-knowledge.capsule.__PAGE__.txt +2 -2
- package/dist/ui/static/local-knowledge/capsule/__next.local-knowledge.capsule.txt +1 -1
- package/dist/ui/static/local-knowledge/capsule/__next.local-knowledge.txt +1 -1
- package/dist/ui/static/local-knowledge/capsule.html +1 -1
- package/dist/ui/static/local-knowledge/capsule.txt +3 -3
- package/dist/ui/static/local-knowledge.html +1 -1
- package/dist/ui/static/local-knowledge.txt +3 -3
- package/dist/ui/static/memoriaviva/__next._full.txt +2 -2
- package/dist/ui/static/memoriaviva/__next._head.txt +1 -1
- package/dist/ui/static/memoriaviva/__next._index.txt +2 -2
- package/dist/ui/static/memoriaviva/__next._tree.txt +2 -2
- package/dist/ui/static/memoriaviva/__next.memoriaviva.__PAGE__.txt +1 -1
- package/dist/ui/static/memoriaviva/__next.memoriaviva.txt +1 -1
- package/dist/ui/static/memoriaviva/consolidation/__next._full.txt +2 -2
- package/dist/ui/static/memoriaviva/consolidation/__next._head.txt +1 -1
- package/dist/ui/static/memoriaviva/consolidation/__next._index.txt +2 -2
- package/dist/ui/static/memoriaviva/consolidation/__next._tree.txt +2 -2
- package/dist/ui/static/memoriaviva/consolidation/__next.memoriaviva.consolidation.__PAGE__.txt +1 -1
- package/dist/ui/static/memoriaviva/consolidation/__next.memoriaviva.consolidation.txt +1 -1
- package/dist/ui/static/memoriaviva/consolidation/__next.memoriaviva.txt +1 -1
- package/dist/ui/static/memoriaviva/consolidation.html +1 -1
- package/dist/ui/static/memoriaviva/consolidation.txt +2 -2
- package/dist/ui/static/memoriaviva/detail/__next._full.txt +2 -2
- package/dist/ui/static/memoriaviva/detail/__next._head.txt +1 -1
- package/dist/ui/static/memoriaviva/detail/__next._index.txt +2 -2
- package/dist/ui/static/memoriaviva/detail/__next._tree.txt +2 -2
- package/dist/ui/static/memoriaviva/detail/__next.memoriaviva.detail.__PAGE__.txt +1 -1
- package/dist/ui/static/memoriaviva/detail/__next.memoriaviva.detail.txt +1 -1
- package/dist/ui/static/memoriaviva/detail/__next.memoriaviva.txt +1 -1
- package/dist/ui/static/memoriaviva/detail.html +1 -1
- package/dist/ui/static/memoriaviva/detail.txt +2 -2
- package/dist/ui/static/memoriaviva/review-queue/__next._full.txt +2 -2
- package/dist/ui/static/memoriaviva/review-queue/__next._head.txt +1 -1
- package/dist/ui/static/memoriaviva/review-queue/__next._index.txt +2 -2
- package/dist/ui/static/memoriaviva/review-queue/__next._tree.txt +2 -2
- package/dist/ui/static/memoriaviva/review-queue/__next.memoriaviva.review-queue.__PAGE__.txt +1 -1
- package/dist/ui/static/memoriaviva/review-queue/__next.memoriaviva.review-queue.txt +1 -1
- package/dist/ui/static/memoriaviva/review-queue/__next.memoriaviva.txt +1 -1
- package/dist/ui/static/memoriaviva/review-queue.html +1 -1
- package/dist/ui/static/memoriaviva/review-queue.txt +2 -2
- package/dist/ui/static/memoriaviva.html +1 -1
- package/dist/ui/static/memoriaviva.txt +2 -2
- package/dist/ui/static/sw.js +7 -3
- package/node_modules/@oscharko-dev/keiko-cli/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-cli/dist/memory.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-cli/dist/memory.js +4 -5
- package/node_modules/@oscharko-dev/keiko-cli/package.json +1 -1
- package/node_modules/@oscharko-dev/keiko-contracts/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-contracts/dist/index.d.ts +1 -1
- package/node_modules/@oscharko-dev/keiko-contracts/dist/index.js +1 -1
- package/node_modules/@oscharko-dev/keiko-contracts/package.json +1 -1
- package/node_modules/@oscharko-dev/keiko-evaluations/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-evaluations/package.json +1 -1
- package/node_modules/@oscharko-dev/keiko-evidence/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-evidence/dist/qualityIntelligence/figmaSnapshot/store.d.ts +5 -0
- package/node_modules/@oscharko-dev/keiko-evidence/dist/qualityIntelligence/figmaSnapshot/store.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-evidence/dist/qualityIntelligence/figmaSnapshot/store.js +16 -0
- package/node_modules/@oscharko-dev/keiko-evidence/package.json +1 -1
- package/node_modules/@oscharko-dev/keiko-harness/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-harness/package.json +1 -1
- package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/parsers/pdf-parser.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/parsers/pdf-parser.js +0 -10
- package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/parsers/types.d.ts +2 -2
- package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/parsers/types.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/parsers/types.js +3 -3
- package/node_modules/@oscharko-dev/keiko-local-knowledge/package.json +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-capture/package.json +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-consolidation/package.json +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-governance/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-governance/dist/index.d.ts +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-governance/dist/index.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-governance/dist/index.js +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-governance/dist/maintenance.d.ts +2 -16
- package/node_modules/@oscharko-dev/keiko-memory-governance/dist/maintenance.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-governance/dist/maintenance.js +49 -48
- package/node_modules/@oscharko-dev/keiko-memory-governance/dist/retention.d.ts +2 -1
- package/node_modules/@oscharko-dev/keiko-memory-governance/dist/retention.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-governance/dist/retention.js +15 -0
- package/node_modules/@oscharko-dev/keiko-memory-governance/package.json +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/decay.d.ts +2 -0
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/decay.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/decay.js +22 -0
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/diversity.d.ts +8 -0
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/diversity.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/diversity.js +87 -0
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/index.d.ts +4 -2
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/index.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/index.js +4 -1
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/ranking.d.ts +5 -1
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/ranking.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/ranking.js +140 -21
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/recency.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/recency.js +4 -10
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/retrieve.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/retrieve.js +11 -1
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/strength.d.ts +9 -0
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/strength.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/strength.js +51 -0
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/types.d.ts +11 -0
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/types.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/types.js +7 -0
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/package.json +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-vault/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-vault/dist/access.d.ts +3 -0
- package/node_modules/@oscharko-dev/keiko-memory-vault/dist/access.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-vault/dist/access.js +31 -1
- package/node_modules/@oscharko-dev/keiko-memory-vault/dist/schema.d.ts +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-vault/dist/schema.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-vault/dist/schema.js +16 -1
- package/node_modules/@oscharko-dev/keiko-memory-vault/dist/types.d.ts +1 -0
- package/node_modules/@oscharko-dev/keiko-memory-vault/dist/types.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-vault/dist/vault.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-vault/dist/vault.js +4 -1
- package/node_modules/@oscharko-dev/keiko-memory-vault/package.json +1 -1
- package/node_modules/@oscharko-dev/keiko-model-gateway/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-model-gateway/package.json +1 -1
- package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-quality-intelligence/package.json +1 -1
- package/node_modules/@oscharko-dev/keiko-sdk/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-sdk/package.json +1 -1
- package/node_modules/@oscharko-dev/keiko-security/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-security/package.json +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/chat-handlers.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/chat-handlers.js +44 -65
- package/node_modules/@oscharko-dev/keiko-server/dist/deps.d.ts +2 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/deps.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/deps.js +1 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/gateway-setup.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/gateway-setup.js +348 -64
- package/node_modules/@oscharko-dev/keiko-server/dist/memory-conv-handlers.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/memory-conv-handlers.js +34 -5
- package/node_modules/@oscharko-dev/keiko-server/dist/memory-embedding.d.ts +12 -2
- package/node_modules/@oscharko-dev/keiko-server/dist/memory-embedding.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/memory-embedding.js +127 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/memory-handlers.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/memory-handlers.js +40 -11
- package/node_modules/@oscharko-dev/keiko-server/dist/memory-maintenance-handlers.d.ts +16 -3
- package/node_modules/@oscharko-dev/keiko-server/dist/memory-maintenance-handlers.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/memory-maintenance-handlers.js +72 -50
- package/node_modules/@oscharko-dev/keiko-server/dist/memory-retrieval-signals.d.ts +12 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/memory-retrieval-signals.d.ts.map +1 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/memory-retrieval-signals.js +84 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/memory-salience.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/memory-salience.js +11 -6
- package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figmaSnapshotRoutes.d.ts +15 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figmaSnapshotRoutes.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/qualityIntelligence/figmaSnapshotRoutes.js +105 -0
- package/node_modules/@oscharko-dev/keiko-server/dist/routes.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/routes.js +2 -1
- package/node_modules/@oscharko-dev/keiko-server/package.json +1 -1
- package/node_modules/@oscharko-dev/keiko-tools/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-tools/package.json +1 -1
- package/node_modules/@oscharko-dev/keiko-verification/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-verification/package.json +1 -1
- package/node_modules/@oscharko-dev/keiko-workflows/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-workflows/package.json +1 -1
- package/node_modules/@oscharko-dev/keiko-workspace/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-workspace/package.json +1 -1
- package/package.json +2 -1
- package/dist/ui/static/_next/static/chunks/0-qhhdvxg2j_y.js +0 -1
- package/dist/ui/static/_next/static/chunks/0ke4ratkgvcxo.css +0 -1
- package/dist/ui/static/_next/static/chunks/3vf3oh2-sl2nc.js +0 -1
- package/dist/ui/static/_next/static/chunks/3wmd4-2vznp2g.js +0 -106
- /package/dist/ui/static/_next/static/{fQMXe8UmV01bh25WOoIt3 → Ppze_8n_i3yc1FS_Qdj0I}/_buildManifest.js +0 -0
- /package/dist/ui/static/_next/static/{fQMXe8UmV01bh25WOoIt3 → Ppze_8n_i3yc1FS_Qdj0I}/_clientMiddlewareManifest.js +0 -0
- /package/dist/ui/static/_next/static/{fQMXe8UmV01bh25WOoIt3 → Ppze_8n_i3yc1FS_Qdj0I}/_ssgManifest.js +0 -0
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,88143,(e,t,n)=>{"use strict";function a({widthInt:e,heightInt:t,blurWidth:n,blurHeight:l,blurDataURL:s,objectFit:i}){let r=n?40*n:e,o=l?40*l:t,c=r&&o?`viewBox='0 0 ${r} ${o}'`:"";return`%3Csvg xmlns='http://www.w3.org/2000/svg' ${c}%3E%3Cfilter id='b' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3CfeColorMatrix values='1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 100 -1' result='s'/%3E%3CfeFlood x='0' y='0' width='100%25' height='100%25'/%3E%3CfeComposite operator='out' in='s'/%3E%3CfeComposite in2='SourceGraphic'/%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3C/filter%3E%3Cimage width='100%25' height='100%25' x='0' y='0' preserveAspectRatio='${c?"none":"contain"===i?"xMidYMid":"cover"===i?"xMidYMid slice":"none"}' style='filter: url(%23b);' href='${s}'/%3E%3C/svg%3E`}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"getImageBlurSvg",{enumerable:!0,get:function(){return a}})},87690,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0});var a={VALID_LOADERS:function(){return s},imageConfigDefault:function(){return i}};for(var l in a)Object.defineProperty(n,l,{enumerable:!0,get:a[l]});let s=["default","imgix","cloudinary","akamai","custom"],i={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[32,48,64,96,128,256,384],path:"/_next/image",loader:"default",loaderFile:"",domains:[],disableStaticImages:!1,minimumCacheTTL:14400,formats:["image/webp"],maximumDiskCacheSize:void 0,maximumRedirects:3,maximumResponseBody:5e7,dangerouslyAllowLocalIP:!1,dangerouslyAllowSVG:!1,contentSecurityPolicy:"script-src 'none'; frame-src 'none'; sandbox;",contentDispositionType:"attachment",localPatterns:void 0,remotePatterns:[],qualities:[75],unoptimized:!1,customCacheHandler:!1}},8927,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"getImgProps",{enumerable:!0,get:function(){return c}}),e.r(33525);let a=e.r(43369),l=e.r(88143),s=e.r(87690),i=["-moz-initial","fill","none","scale-down",void 0];function r(e){return void 0!==e.default}function o(e){return void 0===e?e:"number"==typeof e?Number.isFinite(e)?e:NaN:"string"==typeof e&&/^[0-9]+$/.test(e)?parseInt(e,10):NaN}function c({src:e,sizes:t,unoptimized:n=!1,priority:d=!1,preload:u=!1,loading:m,className:h,quality:p,width:f,height:g,fill:v=!1,style: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:$,...A},T){var M;let q,L,P,{imgConf:D,showAltText:F,blurComplete:z,defaultLoader:O}=T,K=D||s.imageConfigDefault;if("allSizes"in K)q=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);q={...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 _=A.loader||O;delete A.loader,delete A.srcSet;let B="__next_img_default"in _;if(B){if("custom"===q.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=_;_=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((M=e)&&"object"==typeof M&&(r(M)||void 0!==M.src)){let t=r(e)?e.default:e;if(!t.src)throw Object.defineProperty(Error(`An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received ${JSON.stringify(t)}`),"__NEXT_ERROR_CODE",{value:"E460",enumerable:!1,configurable:!0});if(!t.height||!t.width)throw Object.defineProperty(Error(`An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received ${JSON.stringify(t)}`),"__NEXT_ERROR_CODE",{value:"E48",enumerable:!1,configurable:!0});if(L=t.blurWidth,P=t.blurHeight,k=k||t.blurDataURL,U=t.src,!v)if(W||H){if(W&&!H){let e=W/t.width;H=Math.round(t.height*e)}else if(!W&&H){let e=H/t.height;W=Math.round(t.width*e)}}else W=t.width,H=t.height}let G=!d&&!u&&("lazy"===m||void 0===m);(!(e="string"==typeof e?e:U)||e.startsWith("data:")||e.startsWith("blob:"))&&(n=!0,G=!1),q.unoptimized&&(n=!0),B&&!q.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:L,blurHeight:P,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:q,src:e,unoptimized:n,width:W,quality:V,sizes:t,loader:_}),ee=G?"lazy":m;return{props:{...A,loading:ee,fetchPriority:N,width:W,height:H,decoding:S,className:h,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 m(e,t){return"string"==typeof t||"number"==typeof t?e:t.type===o.default.Fragment?e.concat(o.default.Children.toArray(t.props.children).reduce((e,t)=>"string"==typeof t||"number"==typeof t?e:e.concat(t),[])):e.concat(t)}e.r(33525);let h=["name","httpEquiv","charSet","itemProp"];function p(e){let t,n,a,l;return e.reduce(m,[]).reverse().concat(u().reverse()).filter((t=new Set,n=new Set,a=new Set,l={},e=>{let s=!0,i=!1;if(e.key&&"number"!=typeof e.key&&e.key.indexOf("$")>0){i=!0;let n=e.key.slice(e.key.indexOf("$")+1);t.has(n)?s=!1:t.add(n)}switch(e.type){case"title":case"base":n.has(e.type)?s=!1:n.add(e.type);break;case"meta":for(let t=0,n=h.length;t<n;t++){let n=h[t];if(e.props.hasOwnProperty(n))if("charSet"===n)a.has(n)?s=!1:a.add(n);else{let t=e.props[n],a=l[n]||new Set;("name"!==n||!i)&&a.has(t)?s=!1:(a.add(t),l[n]=a)}}}return s})).reverse().map((e,t)=>{let n=e.key||t;return o.default.cloneElement(e,{key:n})})}let f=function({children:e}){let t=(0,o.useContext)(d.HeadManagerContext);return(0,r.jsx)(c.default,{reduceComponentsToState:p,headManager:t,children:e})};("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),t.exports=n.default)},18556,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"ImageConfigContext",{enumerable:!0,get:function(){return s}});let a=e.r(55682)._(e.r(71645)),l=e.r(87690),s=a.default.createContext(l.imageConfigDefault)},65856,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"RouterContext",{enumerable:!0,get:function(){return a}});let a=e.r(55682)._(e.r(71645)).default.createContext(null)},70965,(e,t,n)=>{"use strict";function a(e,t){let n=e||75;return t?.qualities?.length?t.qualities.reduce((e,t)=>Math.abs(t-n)<Math.abs(e-n)?t:e,t.qualities[0]):n}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"findClosestQuality",{enumerable:!0,get:function(){return a}})},1948,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"default",{enumerable:!0,get:function(){return i}});let a=e.r(70965),l=e.r(43369);function s({config:e,src:t,width:n,quality:i}){let r=(0,l.getDeploymentId)();if(t.startsWith("/")&&!t.startsWith("//")){let e=t.indexOf("?");if(-1!==e){let n=new URLSearchParams(t.slice(e+1)),a=n.get("dpl");if(a){r=a,n.delete("dpl");let l=n.toString();t=t.slice(0,e)+(l?"?"+l:"")}}}if(t.startsWith("/")&&t.includes("?")&&e.localPatterns?.length===1&&"**"===e.localPatterns[0].pathname&&""===e.localPatterns[0].search)throw Object.defineProperty(Error(`Image with src "${t}" is using a query string which is not configured in images.localPatterns.
|
|
3
|
+
Read more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns`),"__NEXT_ERROR_CODE",{value:"E871",enumerable:!1,configurable:!0});let o=(0,a.findClosestQuality)(i,e);return`${e.path}?url=${encodeURIComponent(t)}&w=${n}&q=${o}${t.startsWith("/")&&r?`&dpl=${r}`:""}`}s.__next_img_default=!0;let i=s},5500,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"Image",{enumerable:!0,get:function(){return y}});let a=e.r(55682),l=e.r(90809),s=e.r(43476),i=l._(e.r(71645)),r=a._(e.r(74080)),o=a._(e.r(25633)),c=e.r(8927),d=e.r(87690),u=e.r(18556);e.r(33525);let m=e.r(65856),h=a._(e.r(1948)),p=e.r(18581),f={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[32,48,64,96,128,256,384],qualities:[75],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!0};function g(e,t,n,a,l,s,i){let r=e?.src;e&&e["data-loaded-src"]!==r&&(e["data-loaded-src"]=r,("decode"in e?e.decode():Promise.resolve()).catch(()=>{}).then(()=>{if(e.parentElement&&e.isConnected){if("empty"!==t&&l(!0),n?.current){let t=new Event("load");Object.defineProperty(t,"target",{writable:!1,value:e});let a=!1,l=!1;n.current({...t,nativeEvent:t,currentTarget:e,target:e,isDefaultPrevented:()=>a,isPropagationStopped:()=>l,persist:()=>{},preventDefault:()=>{a=!0,t.preventDefault()},stopPropagation:()=>{l=!0,t.stopPropagation()}})}a?.current&&a.current(e)}}))}function v(e){return i.use?{fetchPriority:e}:{fetchpriority:e}}"u"<typeof window&&(globalThis.__NEXT_IMAGE_IMPORTED=!0);let 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:m,unoptimized:h,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,h,w))},[e,u,x,b,y,N,h,w]),E=(0,p.useMergedRef)(C,I);return(0,s.jsx)("img",{...S,...v(d),loading:m,width:l,height:a,decoding:r,"data-nimg":f?"fill":"1",className:o,style:c,sizes:n,srcSet:t,src:e,ref:E,onLoad:e=>{g(e.currentTarget,u,x,b,y,h,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)(m.RouterContext),a=(0,i.useContext)(u.ImageConfigContext),l=(0,i.useMemo)(()=>{let e=f||a||d.imageConfigDefault,t=[...e.deviceSizes,...e.imageSizes].sort((e,t)=>e-t),n=e.deviceSizes.sort((e,t)=>e-t),l=e.qualities?.sort((e,t)=>e-t);return{...e,allSizes:t,deviceSizes:n,qualities:l,localPatterns:"u"<typeof window?a?.localPatterns:e.localPatterns}},[a]),{onLoad:r,onLoadingComplete:o}=e,p=(0,i.useRef)(r);(0,i.useEffect)(()=>{p.current=r},[r]);let g=(0,i.useRef)(o);(0,i.useEffect)(()=>{g.current=o},[o]);let[v,y]=(0,i.useState)(!1),[j,w]=(0,i.useState)(!1),{props:k,meta:N}=(0,c.getImgProps)(e,{defaultLoader:h.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",m="keiko.twin.policy",h="keiko.twin.bridges",p=(0,a.createContext)(null);function f(e,t){try{let n=window.localStorage.getItem(e);if(null===n)return t;let a=JSON.parse(n);return null==a?t:a}catch{return t}}function g(e,t){try{window.localStorage.setItem(e,t)}catch{}}function v(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function 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(m,o)),j(f(h,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(m,r)},[r,w]),(0,a.useEffect)(()=>{w&&v(h,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 A(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 T(e){return{left:{x:e.x,y:e.y,w:e.w/2,h:e.h},right:{x:e.x+e.w/2,y:e.y,w:e.w/2,h:e.h},maxi:{x:e.x,y:e.y,w:e.w,h:e.h},tl:{x:e.x,y:e.y,w:e.w/2,h:e.h/2},tr:{x:e.x+e.w/2,y:e.y,w:e.w/2,h:e.h/2},bl:{x:e.x,y:e.y+e.h/2,w:e.w/2,h:e.h/2},br:{x:e.x+e.w/2,y:e.y+e.h/2,w:e.w/2,h:e.h/2}}}function M(e,t){if(void 0===t)return null;let n=e=>{let n=t[e];return"string"==typeof n&&n.length>0?n:null};switch(e){case"files":return n("root");case"browser":return n("url");case"editor":return n("file");case"terminal":return n("cwd");case"review":{let e=n("base"),t=n("head");return null!==e&&null!==t?`${e} → ${t}`:null}case"agents":return n("role");case"chat":{let e=n("title");return null!==e&&"New chat"!==e?e:null}default:return null}}function q({winCount:e,windows:t,windowPaletteOpen:l,onToggleWindowPalette:s,onSelectWindow:i,onCloseWindowPalette:r,statusRef:o}){let c=(0,a.useRef)(null),[d,u]=(0,a.useState)("version loading"),m=`${String(e)} ${1===e?"window":"windows"}`,h=[...t].sort((e,t)=>t.z-e.z);return(0,a.useEffect)(()=>{let e=!1;return async function(){try{let t=await (0,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})," ",m]}),l&&e>0?(0,n.jsxs)("div",{id:"footer-window-palette",className:"ft-window-palette",role:"menu","aria-label":"Open windows",children:[(0,n.jsx)("div",{className:"ft-window-palette-head",children:"Open windows"}),(0,n.jsx)("div",{className:"ft-window-list",children:h.map(e=>{let t=E[e.type],a=w.Icons[t.icon],l=M(e.type,e.cfg),s=!0===e.minimized?"Minimized":e.max?"Fullscreen":"Visible",r=!0===e.minimized?"Restore":"Focus";return(0,n.jsxs)("button",{type:"button",className:"ft-window-card",role:"menuitem","data-minimized":!0===e.minimized?"true":"false","aria-label":`${r} ${t.title} window${null!==l?` - ${l}`:""}`,onClick:()=>i(e.id),children:[(0,n.jsx)("span",{className:"ft-window-icon",style:{color:!0===t.accent?"var(--accent)":void 0},children:(0,n.jsx)(a,{size:14})}),(0,n.jsxs)("span",{className:"ft-window-copy",children:[(0,n.jsx)("span",{className:"ft-window-title",children:t.title}),(0,n.jsx)("span",{className:"ft-window-sub",title:l??s,children:l??s})]}),(0,n.jsx)("span",{className:"ft-window-state",children:s})]},e.id)})})]}):null]})]})}function L({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 P=[{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:P.map(a=>(0,n.jsx)(D,{tool:a,active:e.has(a.id),onClick:()=>t(a.id)},a.id))}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsxs)("div",{className:"rail-group",children:[(0,n.jsx)("button",{type:"button",className:"rail-btn","data-active":e.has("memoria")?"true":"false","data-side":"left","aria-label":"MemoriaViva","aria-pressed":e.has("memoria"),"data-tip":"MemoriaViva",onClick:()=>t("memoria"),children:(0,n.jsx)(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"})}function O(e){return e.toFixed(2)}function K({onNewWindow:e}){let t=(0,a.useId)(),l=`ewb-${t.replace(/:/gu,"")}`,s=(0,a.useRef)(null),i=(0,a.useRef)(null);(0,a.useEffect)(()=>{let e=e=>{s.current?.setAttribute("d",function(e){let t=[];for(let n=0;n<150;n++){let a=n/150*Math.PI*2,l=1+.07*(.55*Math.sin(3*a+e)+.32*Math.sin(5*a-.8*e+1.7)+.22*Math.sin(2*a+.5*e+.4));t.push([140+127.44000000000001*l*Math.cos(a),140+118*l*Math.sin(a)])}let n=`M${O(t[0]?.[0]??140)} ${O(t[0]?.[1]??140)} `;for(let e=0;e<t.length;e++){let a=t[(e-1+t.length)%t.length],l=t[e],s=t[(e+1)%t.length],i=t[(e+2)%t.length],r=l[0]+(s[0]-a[0])/6,o=l[1]+(s[1]-a[1])/6,c=s[0]-(i[0]-l[0])/6,d=s[1]-(i[1]-l[1])/6;n+=`C${O(r)} ${O(o)} ${O(c)} ${O(d)} ${O(s[0])} ${O(s[1])} `}return`${n}Z`}(e))};if(e(.7),"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches||"function"!=typeof window.requestAnimationFrame)return;let t=0,n=()=>{0!==t&&(window.cancelAnimationFrame(t),t=0)},a=n=>{e(85e-5*n),t=window.requestAnimationFrame(a)},l=()=>{0===t&&!0!==document.hidden&&(t=window.requestAnimationFrame(a))},i=()=>{!0===document.hidden?n():l()};return l(),document.addEventListener("visibilitychange",i),window.addEventListener("blur",n),window.addEventListener("focus",l),()=>{n(),document.removeEventListener("visibilitychange",i),window.removeEventListener("blur",n),window.removeEventListener("focus",l)}},[]);let r=(0,a.useCallback)(()=>{let t=i.current;null!==t&&(t.classList.remove("is-pulse"),t.getBoundingClientRect(),t.classList.add("is-pulse")),e()},[e]);return(0,n.jsx)("button",{type:"button",className:"empty-workspace-blob","aria-label":"Open a new window",onClick:r,children:(0,n.jsxs)("svg",{width:"320",height:"320",viewBox:"0 0 280 280","aria-hidden":"true",children:[(0,n.jsx)("defs",{children:(0,n.jsxs)("mask",{id:l,maskUnits:"userSpaceOnUse",x:"0",y:"0",width:"280",height:"280",children:[(0,n.jsx)("rect",{x:"0",y:"0",width:"280",height:"280",fill:"#fff"}),(0,n.jsx)("g",{transform:"translate(107,64) scale(0.080625)",children:(0,n.jsx)("g",{transform:"translate(1024 0) scale(-1 1)",children:(0,n.jsx)("g",{transform:"translate(1024,1024) scale(-0.1,-0.1)",fill:"#000",children:(0,n.jsx)("path",{d:"M3465 8223 c-144 -8 -314 -52 -408 -105 -69 -39 -146 -99 -146 -113 0 -5 30 -24 68 -42 146 -70 323 -229 377 -340 25 -49 29 -70 29 -138 -1 -72 -5 -88 -39 -160 -36 -75 -54 -95 -265 -305 -134 -132 -270 -279 -331 -355 -339 -425 -552 -896 -626 -1390 -25 -165 -25 -549 0 -720 92 -645 368 -1196 826 -1655 322 -324 710 -562 1145 -704 389 -126 793 -172 1155 -130 235 27 377 63 579 149 205 87 268 86 423 -7 102 -62 231 -115 335 -138 247 -56 562 -26 794 74 92 40 244 136 232 146 -4 3 -26 12 -48 19 -86 28 -246 116 -385 211 -162 112 -284 182 -357 207 l-48 17 40 15 c185 70 436 223 595 363 438 386 695 1014 678 1663 l-3 120 -50 -70 c-64 -90 -248 -280 -350 -362 -171 -136 -366 -255 -645 -391 -288 -140 -442 -243 -590 -391 -136 -137 -247 -316 -325 -526 -47 -127 -114 -262 -160 -326 -79 -107 -237 -224 -384 -283 -136 -55 -355 -96 -514 -96 -274 0 -548 71 -832 215 -242 123 -375 216 -553 389 -175 171 -287 332 -361 517 -44 114 -63 216 -63 359 0 152 17 233 74 350 35 70 59 102 136 179 l95 94 21 -29 c55 -75 219 -277 277 -338 171 -183 337 -256 582 -256 56 0 126 -3 155 -7 53 -6 54 -7 76 -57 30 -66 97 -128 172 -156 151 -57 318 11 395 160 33 62 34 193 3 261 -30 64 -88 125 -148 157 -44 23 -63 27 -141 27 -78 0 -97 -4 -140 -27 -58 -30 -131 -105 -141 -142 -6 -25 -8 -26 -93 -26 -47 0 -131 5 -186 10 -87 8 -111 15 -182 51 -45 22 -109 66 -143 96 -59 53 -326 361 -319 367 14 11 179 47 241 52 102 9 177 -7 318 -66 158 -66 243 -89 357 -99 157 -12 413 5 582 40 l93 19 44 -39 c59 -52 135 -75 228 -69 117 8 212 72 262 176 23 47 28 71 28 138 0 70 -4 89 -29 138 -55 110 -145 167 -270 174 -65 3 -91 0 -137 -18 -107 -40 -183 -140 -195 -257 l-6 -52 -51 -11 c-104 -23 -285 -41 -411 -42 -149 -1 -211 12 -402 88 -186 74 -256 88 -403 81 -193 -8 -377 -70 -546 -182 -342 -228 -485 -611 -399 -1064 30 -157 119 -388 209 -541 20 -35 35 -64 33 -66 -8 -8 -111 108 -190 214 -154 206 -278 489 -324 737 -28 154 -25 492 6 635 46 216 133 391 256 514 82 82 161 128 271 156 152 39 300 23 529 -57 217 -76 308 -101 410 -114 137 -17 284 -7 426 30 272 70 414 145 809 425 217 153 399 238 610 283 64 14 129 18 265 18 197 0 269 -9 615 -76 461 -89 843 -149 952 -149 41 0 41 0 23 -20 -28 -31 -169 -119 -254 -158 -167 -77 -388 -145 -716 -222 -399 -93 -508 -128 -608 -194 -102 -68 -160 -160 -217 -346 -35 -115 -102 -286 -149 -378 -85 -168 -227 -341 -377 -458 -105 -82 -115 -107 -69 -162 29 -34 65 -44 109 -29 86 29 261 181 371 322 126 162 201 309 295 581 61 176 90 232 145 283 62 57 163 93 470 165 439 104 640 169 863 278 206 100 368 240 434 375 32 67 33 71 33 198 -1 120 -3 138 -34 229 -98 294 -319 655 -573 936 -381 421 -968 723 -1618 834 -448 76 -767 83 -1169 25 -80 -12 -165 -19 -190 -17 -26 3 -90 26 -146 53 -343 162 -576 233 -842 255 -114 9 -141 10 -248 3z m2926 -1227 c164 -27 346 -102 485 -202 181 -129 354 -348 354 -448 0 -64 -75 -126 -154 -126 -60 0 -63 4 -52 70 8 50 7 65 -9 100 -29 64 -74 93 -151 98 -54 4 -70 1 -107 -21 -42 -25 -61 -52 -91 -129 -25 -64 -55 -73 -246 -73 -121 0 -187 5 -248 18 -318 70 -556 242 -556 402 0 218 388 374 775 311z m-2249 -611 c119 -21 208 -50 321 -106 114 -56 177 -100 266 -184 67 -63 157 -173 148 -181 -2 -3 -61 18 -130 45 -131 52 -298 100 -427 122 -113 20 -367 17 -470 -4 -502 -106 -885 -433 -1160 -992 -70 -142 -160 -379 -160 -424 0 -9 -5 -23 -11 -31 -13 -19 -5 316 10 410 80 482 295 846 661 1117 145 107 350 197 522 228 100 18 326 18 430 0z m1485 -1456 c95 -36 119 -159 42 -223 -78 -66 -209 -1 -209 104 0 60 33 100 99 121 36 10 36 10 68 -2z m-591 -822 c29 -26 37 -42 40 -77 6 -54 -9 -86 -55 -117 -41 -28 -70 -29 -119 -4 -44 22 -62 55 -62 112 0 51 13 75 53 99 50 31 101 26 143 -13z"})})})}),(0,n.jsx)("text",{x:"140",y:"172",textAnchor:"middle",fill:"#000",fontFamily:"var(--font-ui)",fontSize:"16",fontWeight:"700",children:"Empty workspace"}),(0,n.jsx)("text",{x:"140",y:"191",textAnchor:"middle",fill:"#000",fontFamily:"var(--font-ui)",fontSize:"11",fontWeight:"400",children:"Open a window to start working"})]})}),(0,n.jsx)("g",{ref:i,className:"empty-workspace-blob__group",children:(0,n.jsx)("path",{ref:s,className:"empty-workspace-blob__fill",mask:`url(#${l})`})})]})})}let _="keiko.wallpaper.enabled",B="keiko.wallpaper.opacity",U="keiko.workspace.background.brightness",W="keiko.workspace.grid.strength",H="keiko.frame.border.strength",G="keiko:wallpaper-enabled",V="keiko:wallpaper-opacity",Y="keiko:workspace-background-brightness",Q="keiko:workspace-grid-strength",J="keiko:frame-border-strength";function X(e){return Number.isFinite(e)?Math.max(0,Math.min(100,e)):0}function Z(){return"true"===window.localStorage.getItem(_)}function ee(){let e=window.localStorage.getItem(B);return null===e?100:X(Number.parseInt(e,10))}function et(){let e=window.localStorage.getItem(U);return null===e?0:X(Number.parseInt(e,10))}function en(){let e=window.localStorage.getItem(W);return null===e?28:X(Number.parseInt(e,10))}function ea(){let e=window.localStorage.getItem(H);return null===e?42:X(Number.parseInt(e,10))}function el(e){"u">typeof document&&document.documentElement.style.setProperty("--workspace-bg-brightness",`${X(e)}%`)}function es(e){"u">typeof document&&document.documentElement.style.setProperty("--workspace-grid-strength",`${X(e)}%`)}function ei(e){"u">typeof document&&document.documentElement.style.setProperty("--frame-border-strength",`${X(e)}%`)}let er=`
|
|
4
|
+
attribute vec2 aPos;
|
|
5
|
+
void main(){ gl_Position = vec4(aPos, 0.0, 1.0); }
|
|
6
|
+
`,eo=`
|
|
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 ec(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 ed(){let e=(0,a.useRef)(null),[t,l]=(0,a.useState)(Z);return(0,a.useEffect)(()=>{el(et()),es(en()),ei(ea());let e=e=>{let t=e.detail;el("number"==typeof t?t:et())},t=e=>{let t=e.detail;es("number"==typeof t?t:en())},n=e=>{let t=e.detail;ei("number"==typeof t?t:ea())};return window.addEventListener(Y,e),window.addEventListener(Q,t),window.addEventListener(J,n),()=>{window.removeEventListener(Y,e),window.removeEventListener(Q,t),window.removeEventListener(J,n)}},[]),(0,a.useEffect)(()=>{let e=e=>{let t=e.detail;l("boolean"==typeof t?t:Z())},t=e=>{(null===e.key||e.key===_)&&l(Z())};return window.addEventListener(G,e),window.addEventListener("storage",t),()=>{window.removeEventListener(G,e),window.removeEventListener("storage",t)}},[]),(0,a.useEffect)(()=>{let n;if(!t)return;let a=e.current;if(null===a)return;let l=a.parentElement;if(null===l)return;let s=window.matchMedia("(prefers-reduced-motion: reduce)"),i=()=>{s.matches?(n?.(),n=void 0):void 0===n&&(n=function(e,t){t.style.opacity=String(ee()/100);let n=e=>{let n=e.detail,a="number"==typeof n?n:ee();t.style.opacity=String(X(a)/100)};window.addEventListener(V,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(V,n)};let l=ec(a,a.VERTEX_SHADER,er),s=ec(a,a.FRAGMENT_SHADER,eo);if(null===l||null===s)return()=>{window.removeEventListener(V,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(V,n)};a.useProgram(i);let r=a.createBuffer();a.bindBuffer(a.ARRAY_BUFFER,r),a.bufferData(a.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),a.STATIC_DRAW);let o=a.getAttribLocation(i,"aPos");a.enableVertexAttribArray(o),a.vertexAttribPointer(o,2,a.FLOAT,!1,0,0);let c=a.getUniformLocation(i,"uRes"),d=a.getUniformLocation(i,"uTime"),u=a.getUniformLocation(i,"uMouse"),m=a.getUniformLocation(i,"uLight"),h=a.getUniformLocation(i,"uRip"),p=a.getUniformLocation(i,"uRipT"),f=1,g=1,v=Math.min(window.devicePixelRatio??1,1.5),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(m,n),a.uniform2fv(h,b),a.uniform1fv(p,R),a.drawArrays(a.TRIANGLES,0,3)),I=requestAnimationFrame($)}I=requestAnimationFrame($);let A=()=>{document.hidden?(E=!1,cancelAnimationFrame(I)):E||(E=!0,I=requestAnimationFrame($))};return document.addEventListener("visibilitychange",A),()=>{E=!1,cancelAnimationFrame(I),document.removeEventListener("visibilitychange",A),window.removeEventListener(V,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))}}(l,a))};return i(),s.addEventListener("change",i),()=>{s.removeEventListener("change",i),n?.()}},[t]),t?(0,n.jsx)("canvas",{ref:e,className:"ws-shader","aria-hidden":"true"}):null}let eu=new Set(["files","connector","browser","plugins","agents","quality"]);function em(e,t){return e>=4||t>=8192}function eh({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 ep({wins:e,conns:t,connecting:l,api:s}){let i=r(),o=function(){let[e,t]=(0,a.useState)(!1);return(0,a.useEffect)(()=>{let e=window.matchMedia("(prefers-reduced-motion: reduce)");t(e.matches);let n=e=>t(e.matches);return e.addEventListener("change",n),()=>e.removeEventListener("change",n)},[]),e}(),{armedId:c,arm:d,disarm:u}=function(){let[e,t]=(0,a.useState)(null);return(0,a.useEffect)(()=>{if(null===e)return;let n=setTimeout(()=>t(null),3e3);return()=>clearTimeout(n)},[e]),{armedId:e,arm:e=>t(e),disarm:()=>t(null)}}(),{flowing:m,intensity:h}=function(e,t){let[n,l]=(0,a.useState)("light"),[s,i]=(0,a.useState)(!1);return(0,a.useEffect)(()=>{if(void 0===t)return;l(function(e){switch(e.groundingKind){case"connected-context":return em(e.contextPack.usage.filesRead,e.contextPack.usage.excerptBytes)?"heavy":"light";case"hybrid":return em(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:A(t,l),dataChannel:function(e,t){let n=[e.type,t.type].includes("chat"),a="chat"===e.type?eu.has(t.type):eu.has(e.type);return n&&a}(t,l)})}return a}(e,t),f=null!==l?function(e,t){let n=t.find(t=>t.id===e.from);if(void 0===n)return null;let a={x:n.x+n.w/2,y:n.y+n.h/2},l=e.x-a.x,s=e.y-a.y,i=Math.abs(l)>=Math.abs(s),r=i?{x:l>=0?n.x+n.w:n.x,y:a.y}:{x:a.x,y:s>=0?n.y+n.h:n.y},o=Math.max(40,Math.abs(i?l:s)/2),c=i?{x:r.x+(l>=0?o:-o),y:r.y}:{x:r.x,y:r.y+(s>=0?o:-o)},d=e.x,u=e.y;return{d:`M${String(r.x)},${String(r.y)} C${String(c.x)},${String(c.y)} ${String(d)},${String(u)} ${String(d)},${String(u)}`,ex:d,ey:u}}(l,e):null;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"conn-layer",children:(0,n.jsxs)("svg",{className:"conn-svg",viewBox:"-10000 -10000 20000 20000",preserveAspectRatio:"xMidYMid meet",children:[p.map(e=>{let t=m&&e.dataChannel,a=`conn-path-${e.c.id}`;return(0,n.jsxs)("g",{children:[(0,n.jsx)("path",{id:a,className:"conn-path",d:e.d,"data-active":t?"true":void 0,"data-intensity":t?h:void 0,"data-reduced-motion":t&&o?"true":void 0}),t&&!o?(0,n.jsx)(eh,{pathId:a,intensity:h}):null]},e.c.id)}),null!==f?(0,n.jsx)("path",{className:"conn-path conn-temp",d:f.d}):null,null!==f?(0,n.jsx)("circle",{className:"conn-dot",cx:f.ex,cy:f.ey,r:"5"}):null]})}),(0,n.jsx)("div",{className:"conn-badge-layer",children:p.map(e=>{let t,a=m&&e.dataChannel,l=c===e.c.id,i=(t=[`Connection: ${e.label}`],void 0!==e.c.boundRoot&&t.push(`Root: ${e.c.boundRoot}`),void 0!==e.c.boundScopeKind&&t.push(`Scope: ${e.c.boundScopeKind}`),void 0!==e.c.boundRelativePath&&e.c.boundRelativePath.length>0&&t.push(`Path: ${e.c.boundRelativePath}`),void 0!==e.c.boundConnectorKind&&void 0!==e.c.boundConnectorId&&t.push(`Knowledge: ${e.c.boundConnectorKind} ${e.c.boundConnectorId}`),t.join("\n"));return(0,n.jsxs)("button",{type:"button",className:"conn-badge","data-active":a?"true":void 0,"data-intensity":a?h:void 0,"data-armed":l?"true":void 0,style:{left:e.mid.x,top:e.mid.y},onClick:()=>{l?(u(),s.removeConn(e.c.id)):d(e.c.id)},onBlur:()=>{l&&u()},title:l?`Click again to remove: ${e.label}
|
|
101
|
+
|
|
102
|
+
${i}`:`${i}
|
|
103
|
+
|
|
104
|
+
Click once to arm removal.`,"aria-label":l?`Confirm removal of connection: ${e.label}. Activate again to remove.`:a?`${e.label} — ${h} data exchange in progress. Activate to remove connection.`:`Remove connection: ${e.label}`,children:[(0,n.jsx)(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"===h?"⇶":"→"}):null]},e.c.id)})})]})}let ef=["n","s","e","w","ne","nw","se","sw"],eg=["t","r","b","l"];function ev({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 ex({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],[m,h]=(0,a.useState)(!1),p=e.zoom??1,f="chat"===e.type||"agents"===e.type||"quality"===e.type?i.linkedFilesRoot(e.id):null,g="agents"===e.type||"quality"===e.type?i.linkedFilesContext(e.id)?.activeFilePath:void 0,v="quality"===e.type?i.linkedAllFilesRoots(e.id):null!==f?[f]:[],x="quality"===e.type?i.linkedConnectorCapsuleIds(e.id):[],b="quality"===e.type?i.linkedConnectorCapsuleSetIds(e.id):[],y="quality"===e.type?i.linkedFigmaSnapshotRunIds(e.id):[],j=e.w/p,k=e.h/p,N=(0,a.useCallback)(t=>{i.update(e.id,{cfg:{...e.cfg,...t}})},[i,e.cfg,e.id]),S=(0,a.useCallback)((e,t)=>i.add(e,t),[i]),{mode:C,node:I}=function(e,t,a,l,s,i,r,o,c,d,u,m){let h=E[e];if("chat"===e){let e=t<430||a<430;return{mode:e?"mini":"full",node:h.render(l,{mini:e,linkedRoot:s,linkedFilePath:i,linkedRoots:r,linkedCapsuleIds:o,linkedCapsuleSetIds:c,linkedFigmaSnapshotRunIds:d,updateCfg:u,openWindow:m})}}return t<h.tiny.w||a<h.tiny.h?{mode:"tiny",node:(0,n.jsx)(ev,{icon:h.icon,label:h.title})}:{mode:"full",node:h.render(l,{linkedRoot:s,linkedFilePath:i,linkedRoots:r,linkedCapsuleIds:o,linkedCapsuleSetIds:c,linkedFigmaSnapshotRunIds:d,updateCfg:u,openWindow:m})}}(e.type,j,k,e.cfg,f,g,v,x,b,y,N,S),$=(0,a.useCallback)(t=>i.update(e.id,{zoom:Math.max(.5,Math.min(2,Math.round(10*t)/10))}),[i,e.id]),A=(0,a.useCallback)(t=>{var n,a,o;let c,d,u,m;if(1!==t.button||"valid"===l)return;t.preventDefault(),i.focus(e.id);let p=r.current;if(null===p)return;let f=(n=p.getBoundingClientRect(),{z:c=s.zoom,vpx0:-s.x/c,vpy0:-s.y/c,vpw:n.width/c,vph:n.height/c,toWX:e=>(e-n.left-s.x)/c,toWY:e=>(e-n.top-s.y)/c}),g=e.max,v=g?e.prev?.w??480:e.w,x=g?e.prev?.h??360:e.h,b=g?v/2:f.toWX(t.clientX)-e.x,y=g?18:f.toWY(t.clientY)-e.y;g&&i.update(e.id,{max:!1,w:v,h:x}),h(!0),a={winId:e.id,offX:b,offY:y,W:v},o=()=>h(!1),d=30/f.z,u=e=>{let t,n,l,s,r=f.toWX(e.clientX),o=f.toWY(e.clientY),c=r-a.offX,u=o-a.offY;c=Math.max(f.vpx0-(a.W-120),Math.min(f.vpx0+f.vpw-120,c)),u=Math.max(f.vpy0,Math.min(f.vpy0+f.vph-38,u)),i.setSnap((t=r-f.vpx0<d,n=f.vpx0+f.vpw-r<d,l=o-f.vpy0<d,s=f.vpy0+f.vph-o<d,l&&t?"tl":l&&n?"tr":s&&t?"bl":s&&n?"br":t?"left":n?"right":l?"maxi":null)),i.update(a.winId,{x:c,y:u})},m=()=>{window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",m),i.commitSnap(a.winId),document.body.style.cursor="",o?.()},document.body.style.cursor="grabbing",window.addEventListener("pointermove",u),window.addEventListener("pointerup",m)},[i,e.id,e.x,e.y,e.w,e.h,e.max,e.prev,s,r,l]),T=(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]),q=(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]),L=(0,a.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),q(e.currentTarget,e)},[q]),P=(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(),q(t.currentTarget,t)}},[q,l,i,e.id]),D=(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]),F=(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]),z="full"===C?M(e.type,e.cfg):null,O={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!==z?`${c.title} — ${z}`:c.title,"aria-roledescription":"window","data-top":t?"true":"false","data-max":e.max?"true":"false","data-conn":l??void 0,"data-dragging":m?"true":void 0,"data-window-id":e.id,style:O,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:A,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!==z?(0,n.jsx)("span",{className:"win-sub mono",title:z,children:z}):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:p<=.5,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>$(p-.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*p))}% — reset ${c.title} content zoom`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>i.update(e.id,{zoom:1}),children:[Math.round(100*p),"%"]}),(0,n.jsx)("button",{type:"button",className:"win-zbtn",title:"Zoom content in","aria-label":`Zoom ${c.title} content in`,disabled:p>=2,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>$(p+.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:F,children:(0,n.jsx)(w.Icons.minimize,{size:17})}),(0,n.jsx)("button",{type:"button",className:"win-traffic-btn win-traffic-maximize",title:e.max?"Restore":"Full screen","aria-label":e.max?`Restore ${c.title} window`:`Full screen ${c.title} window`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>i.maximize(e.id),children:e.max?(0,n.jsx)(w.Icons.restore,{size:17}):(0,n.jsx)(w.Icons.maximize,{size:17})}),(0,n.jsx)("button",{type:"button",className:"win-traffic-btn win-traffic-close",title:"Close","aria-label":`Close ${c.title} window`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:D,children:(0,n.jsx)(w.Icons.close,{size:17})})]})]}),(0,n.jsx)("div",{className:"win-body","data-mode":C,style:"tiny"===C?{}:{zoom:p},children:I}),e.max?null:ef.map(e=>(0,n.jsx)("div",{className:`wz wz-${e}`,onPointerDown:T(e)},e)),!e.max&&d?eg.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:L,onKeyDown:P},`p${e}`)):null]})}let eb=[/\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-----/],ey=/\b(?:\d[ -]?){13,19}\b/g;e.i(47167);let ej={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"}},ew=["apikey","accesskey","clientsecret","credential","password","privatekey","secret","token"],ek=["api_key=","apikey=","client_secret=","clientsecret=","credential=","authorization:","password=","secret=","token="],eN=[".env",".env.local",".env.development",".env.test",".env.production"],eS={chat:["chatId"],files:["activeFilePath","activeDirectoryPath","resolvedRoot"]};function eC(e){return"number"==typeof e&&Number.isFinite(e)}function eI(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function eE(e){let t=e.trim();if(0===t.length)return!1;let n=t.toLowerCase();return function(e){for(let t of eb)if(t.test(e))return!0;for(let t of e.matchAll(ey)){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)||ek.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(eN.includes(n)||".npmrc"===n||"credentials.json"===n||".aws"===n&&"credentials"===a||".ssh"===n&&a.startsWith("id_"))return!0}return!1}(t)}function eR(e){let t=[];for(let n of e){let e=function(e){var t;if(!eI(e)||!("string"==typeof(t=e.type)&&t in E))return null;let n=e.type;if("transient"===ej[n].persistence||"string"!=typeof e.id||!eC(e.x)||!eC(e.y)||!eC(e.w)||!eC(e.h)||!eC(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(!eI(t)||"durable.config"===ej[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),ew.some(e=>a.includes(e))))return;if("string"!=typeof n)return n;let l=ej[e].persistence;return"evidence-reference"===l?!function(e){if(0===e.length||e.length>256||e.startsWith(".")||e.trim()!==e||eE(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:eE(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(eI(e)&&eC(e.x)&&eC(e.y)&&eC(e.w)&&eC(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}:{},...eC(e.zoom)?{zoom:e.zoom}:{}}}(n);null!==e&&t.push(e)}return t}function e$(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 eA(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 eT(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 eq(e,t){return e?.type==="chat"?e.id:t?.type==="chat"?t.id:null}function eL(e){return e.length>0&&(e.startsWith("/")||/^[A-Za-z]:[/\\]/u.test(e))}function eP(e){return/^[A-Za-z]:[/\\]?$/u.test(e)?e.replace(/\\/gu,"/"):e.replace(/\\/gu,"/").replace(/\/+$/u,"")}function eD(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&&eL(a)?a:null}function eF(e){return e.replace(/\\/gu,"/").replace(/^\/+/u,"").replace(/\/+$/u,"")}function ez(e,t){return void 0!==e.root&&void 0!==t.root&&eP(e.root)===eP(t.root)&&e.kind===t.kind&&e.relativePaths.length===t.relativePaths.length&&e.relativePaths.every((e,n)=>eF(e)===eF(t.relativePaths[n]??""))}function eO(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=eD(a);if(null===s)return null;let i=a.cfg.activeFilePath;if("string"==typeof i&&i.length>0)return{kind:"files",relativePaths:[eF(i)],root:eP(s),connectedAtMs:n};let r=a.cfg.activeDirectoryPath;return"string"==typeof r&&r.length>0?{kind:"directory",relativePaths:[eF(r)],root:eP(s),connectedAtMs:n}:{kind:"workspace-root",relativePaths:[],root:eP(s),connectedAtMs:n}}function eK(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:[eF(e.boundRelativePath)],root:eP(e.boundRoot),connectedAtMs:t}:"files"===e.boundScopeKind?"string"!=typeof e.boundRelativePath||0===e.boundRelativePath.length?null:{kind:"files",relativePaths:[eF(e.boundRelativePath)],root:eP(e.boundRoot),connectedAtMs:t}:{kind:"workspace-root",relativePaths:[],root:eP(e.boundRoot),connectedAtMs:t}}function e_(e){return Math.max(e.maxConnectedSources,e.maxLocalKnowledgeSources)}function eB(e,t){return e.filter(e=>!ez(e,t))}function eU(e){return e.connectedScopes??(void 0!==e.connectedScope?[e.connectedScope]:[])}function eW(e){return e.localKnowledgeScopes??(void 0!==e.localKnowledgeScope?[e.localKnowledgeScope]:[])}function eH(e){return"capsule"===e.kind?`capsule:${e.capsuleId}`:`set:${e.capsuleSetId}`}function eG(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 eV(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 eY="keiko.workspace.v4",eQ="keiko.conns.v1",eJ="keiko.view";function eX(){try{let e=window.localStorage.getItem(eJ);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 eZ(e){return Math.max(.3,Math.min(2.5,e))}function e0(e){return Math.max(.5,Math.min(2,Math.round(10*e)/10))}function e1(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 e2(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function e3(e){let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?16:2===e.deltaMode?800:1;return{x:e.deltaX*t,y:e.deltaY*t}}let e4={Equal:"=",NumpadAdd:"+",Minus:"-",NumpadSubtract:"-",Digit0:"0",Numpad0:"0"},e6="application/x-keiko-local-knowledge-connector",e5="keiko:local-knowledge-connector-drop";function e8(e){if(!Array.from(e.types).includes(e6))return null;try{let t=JSON.parse(e.getData(e6));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 e7={w:260,h:220};function e9(){return!("u"<typeof document)&&"true"===document.documentElement.getAttribute("data-keiko-modal-open")}function te(e,t){let n=e+t;return e<1&&n>1||e>1&&n<1?1:n}function tt({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: ${A(n,a)}`:"Connected")}else i("Connection cancelled")},[t,l,e]),(0,n.jsx)("div",{className:"sr-only","aria-live":"polite",children:s})}function tn(e){let t=E[e.type].title,n=M(e.type,e.cfg);return null!==n?`${t}: ${n}`:t}function ta({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:`${tn(n)} ${A(n,a)} ${tn(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=tn(e),r=E[e.type];return(0,n.jsx)("li",{children:(0,n.jsxs)("article",{"aria-labelledby":`ws-outline-window-${e.id}`,children:[(0,n.jsx)("h4",{id:`ws-outline-window-${e.id}`,children:i}),(0,n.jsxs)("p",{children:["Type: ",r.title,". Status: ",((t=[]).push(null!==l&&l.id===e.id?"active":"background"),t.push(!0===e.minimized?"minimized":"open"),e.max&&t.push("maximized"),1!==(a=e.zoom??1)&&t.push(`${String(Math.round(100*a))}% content zoom`),t.join(", ")),"."]}),(0,n.jsx)("p",{children:r.desc}),(0,n.jsxs)("div",{className:"ws-outline-actions","aria-label":`${i} actions`,children:[(0,n.jsx)("button",{type:"button",onClick:()=>s.restore(e.id),children:!0===e.minimized?`Restore ${i}`:`Open ${i}`}),(0,n.jsxs)("button",{type:"button",onClick:()=>s.minimize(e.id),children:["Minimize ",i]}),(0,n.jsx)("button",{type:"button",onClick:()=>s.maximize(e.id),children:e.max?`Restore size of ${i}`:`Full screen ${i}`}),(0,n.jsxs)("button",{type:"button",onClick:()=>s.close(e.id),children:["Close ",i]})]})]})},e.id)})})]}),(0,n.jsxs)("section",{"aria-labelledby":"ws-outline-relationships-title",children:[(0,n.jsx)("h3",{id:"ws-outline-relationships-title",children:"Relationships"}),0===r.length?(0,n.jsx)("p",{children:"No relationships are connected."}):(0,n.jsx)("ul",{className:"ws-outline-list",children:r.map(({conn:e,label:t})=>(0,n.jsxs)("li",{children:[(0,n.jsxs)("p",{children:[t.text,"."]}),(0,n.jsxs)("button",{type:"button",onClick:()=>s.removeConn(e.id),children:["Remove relationship between ",tn(t.source)," and"," ",tn(t.target)]})]},e.id))})]})]})})}function tl({ws:e,wsRef:t,openPalette:l,palette:s}){let{wins:i,view:r,snapPrev:o,conns:c,connecting:d,api:u}=e,[m,h]=(0,a.useState)(!1),p=(0,a.useMemo)(()=>null===i?null:i.filter(e=>!0!==e.minimized),[i]),f=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}(p),g=null!==d&&null!==p?p.find(e=>e.id===d.from)??null:null,v=(0,a.useMemo)(()=>({backgroundSize:`${String(22*r.zoom)}px ${String(22*r.zoom)}px`,backgroundPosition:`${String(r.x)}px ${String(r.y)}px`}),[r]),x=(0,a.useMemo)(()=>({transform:`translate(${String(r.x/r.zoom)}px, ${String(r.y/r.zoom)}px)`,transformOrigin:"0 0",zoom:r.zoom}),[r]),b=(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-e7.w/2),y:Math.round((t-n.top-a.y)/a.zoom-28)}}({clientX:t,clientY:n,rect:a,view:r}),...e7})},[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||b(s,a,l,n)};return window.addEventListener(e5,e),()=>{window.removeEventListener(e5,e)}},[b,t]);let y=null!==i&&0===i.length;return(0,n.jsxs)("main",{className:"workspace",ref:t,"aria-label":"Workspace surface",tabIndex:0,"data-connecting":null!==d?"true":void 0,"data-panning":m?"true":void 0,onPointerDownCapture:e=>{if(e9()||0!==e.button||null===d||null===g||null===p)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===g.id)return;let n=p.find(e=>e.id===t);void 0!==n&&$(g.type,n.type)&&u.confirmConnect(n.id,e)},onPointerDown:e=>{var t,n;if(!e9()){if(!((t=e.target)instanceof Element)||null===t.closest(".window")&&null===t.closest(".ws-zoom")&&null===t.closest(".ws-fab")&&null===t.closest(".empty-workspace-blob")&&null===t.closest(".ws-outline")&&null===t.closest(".conn-badge")){if(null!==d){0===e.button&&u.cancelConnect();return}if(1===e.button){let t,a,l,s,i,r,o;n=u.panBy,e.preventDefault(),t=e.currentTarget,t.setPointerCapture?.(e.pointerId),a=e.clientX,l=e.clientY,s=document.body.style.cursor,i=document.body.style.userSelect,h(!0),document.body.style.cursor="grabbing",document.body.style.userSelect="none",r=e=>{n(e.clientX-a,e.clientY-l),a=e.clientX,l=e.clientY},o=()=>{window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",o),window.removeEventListener("pointercancel",o),h(!1),t.hasPointerCapture?.(e.pointerId)===!0&&t.releasePointerCapture?.(e.pointerId),document.body.style.cursor=s,document.body.style.userSelect=i},window.addEventListener("pointermove",r),window.addEventListener("pointerup",o),window.addEventListener("pointercancel",o)}}}},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!==e8(e.dataTransfer)&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},onDrop:e=>{let t=e8(e.dataTransfer);if(null===t)return;e.preventDefault(),e.stopPropagation();let n=e.currentTarget.getBoundingClientRect();b(t,e.clientX,e.clientY,n)},children:[(0,n.jsx)(ed,{}),(0,n.jsx)("div",{className:"ws-grid",style:v,"aria-hidden":"true"}),(0,n.jsx)(ta,{wins:i,conns:c,top:f,api:u,openPalette:l}),(0,n.jsx)(tt,{wins:p,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,y?(0,n.jsx)("div",{className:"ws-empty",children:(0,n.jsx)(K,{onNewWindow:l})}):null,(0,n.jsxs)("div",{className:"ws-scene",style:x,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!==p?(0,n.jsx)(ep,{wins:p,conns:c,connecting:d,api:u}):null,null!==p?p.map(e=>(0,n.jsx)(ex,{win:e,top:null!==f&&e.id===f.id,connState:null===g?null:e.id===g.id?"source":$(g.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(te(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.jsx)("button",{type:"button",className:"ws-zoom-btn",onClick:u.fitView,disabled:null===p||0===p.length,"aria-label":"Fit workspace to windows",title:"Fit workspace to windows",children:(0,n.jsx)(w.Icons.expand,{size:15})}),(0,n.jsxs)("button",{type:"button",className:"ws-zoom-pct mono",onClick:u.resetView,"aria-label":`${String(Math.round(100*r.zoom))}% — reset view`,title:"Reset view to 100%",children:[Math.round(100*r.zoom),"%"]}),(0,n.jsx)("button",{type:"button",className:"ws-zoom-btn",onClick:()=>u.zoomTo(te(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 ts({commands:e,onClose:t}){let[l,s]=(0,a.useState)(""),[i,r]=(0,a.useState)(0),o=(0,a.useRef)(null),c=(0,a.useRef)(null),d=(0,a.useRef)(null);(0,a.useEffect)(()=>(c.current=document.activeElement,()=>{c.current?.focus?.()}),[]),(0,a.useEffect)(()=>{o.current?.focus()},[]);let u=(0,a.useMemo)(()=>{let t=l.toLowerCase();return e.filter(e=>`${e.label} ${e.group??""}`.toLowerCase().includes(t))},[e,l]);(0,a.useEffect)(()=>{r(0)},[l]),(0,a.useEffect)(()=>{document.getElementById(`cmdk-row-${String(i)}`)?.scrollIntoView?.({block:"nearest"})},[i,u]);let m=e=>{void 0!==e&&(e.run(),t())};return(0,n.jsx)("div",{className:"cmdk-overlay",onPointerDown:t,children:(0,n.jsxs)("div",{ref:d,className:"cmdk",role:"dialog","aria-modal":"true","aria-labelledby":"cmdk-title","aria-describedby":"cmdk-desc",tabIndex:-1,onPointerDown:e=>e.stopPropagation(),onKeyDown:e=>{if("Tab"===e.key){let t=Array.from(d.current?.querySelectorAll("button:not([disabled]),input:not([disabled]),[tabindex]:not([tabindex='-1'])")??[]);if(t.length>0){let n=t[0],a=t[t.length-1];if(e.shiftKey&&document.activeElement===n){e.preventDefault(),a.focus();return}if(!e.shiftKey&&document.activeElement===a){e.preventDefault(),n.focus();return}}}if("ArrowDown"===e.key){e.preventDefault(),r(e=>Math.min(u.length-1,e+1));return}if("ArrowUp"===e.key){e.preventDefault(),r(e=>Math.max(0,e-1));return}if("Enter"===e.key){e.preventDefault(),m(u[i]);return}"Escape"===e.key&&t()},children:[(0,n.jsx)("h2",{id:"cmdk-title",className:"sr-only",children:"Command palette"}),(0,n.jsx)("p",{id:"cmdk-desc",className:"sr-only",children:"Search commands and press Enter to run the selected action."}),(0,n.jsxs)("div",{className:"cmdk-input",children:[(0,n.jsx)(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:()=>m(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 ti=e.i(74080);function tr(e){return Array.from(new Set(e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e.length>0)))}function to({onCancel:e,preserveExisting:t=!1,storedApiKeyHeaderName:l,storedModels:s=[]}){let i=(0,a.useRef)(null),r=(0,a.useRef)(null),o=(0,a.useRef)(null),c=(0,a.useRef)(null),d=(0,a.useRef)(void 0),[u,m]=(0,a.useState)(""),[h,p]=(0,a.useState)(""),[f,g]=(0,a.useState)(""),[v,x]=(0,a.useState)(""),[b,y]=(0,a.useState)(""),[k,N]=(0,a.useState)(""),[S,C]=(0,a.useState)(!1),[I,E]=(0,a.useState)(),[R,$]=(0,a.useState)(),[A,T]=(0,a.useState)();async function M(e){if(e.preventDefault(),!S){C(!0),E(void 0),$(void 0),T(void 0),i.current?.focus();try{let e=tr(v);if(function(e){try{return new URL(e.trim()).hostname.endsWith(".services.ai.azure.com")}catch{return!1}}(u)&&0===e.length){E("Azure AI Foundry requires deployment names. Paste the names from the Deployments tab."),C(!1);return}let n=tr(b),a=!t||""!==u.trim()||""!==h.trim()||""!==f.trim()||e.length>0||n.length>0,l=""!==k.trim(),s=(await (0,j.setupGateway)({baseUrl:""===u.trim()?void 0:u.trim(),apiKey:""===h.trim()?void 0:h.trim(),apiKeyHeaderName:""===f.trim()?void 0:f.trim(),deploymentNames:e,preserveExisting:t,...0===n.length?{}:{imageInputModelIds:n},...""===k.trim()?{}:{figmaAccessToken:k.trim()}})).testedModelIds.length;C(!1),l&&!a?T("Verified Figma access token. Reloading Keiko…"):l?T(`Verified ${String(s)} workflow chat model${1===s?"":"s"} and Figma access token. Reloading Keiko…`):T(`Verified ${String(s)} workflow chat model${1===s?"":"s"}. Reloading Keiko…`),d.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."};E(e.message),$(e.code),C(!1)}}}(0,a.useEffect)(()=>{let e=document.documentElement,n=Number(e.dataset.keikoModalOpenCount??"0");return e.dataset.keikoModalOpenCount=String(n+1),e.setAttribute("data-keiko-modal-open","true"),c.current=document.activeElement,t?o.current?.focus():r.current?.focus(),()=>{void 0!==d.current&&window.clearTimeout(d.current);let t=Math.max(0,Number(e.dataset.keikoModalOpenCount??"1")-1);0===t?(delete e.dataset.keikoModalOpenCount,e.removeAttribute("data-keiko-modal-open")):e.dataset.keikoModalOpenCount=String(t),c.current?.focus?.()}},[t]),(0,a.useEffect)(()=>{let t=i.current;if(null===t)return;let n=n=>{if("Escape"===n.key){if(S||void 0!==A||void 0===e)return;n.preventDefault(),e();return}if("Tab"!==n.key)return;let a=Array.from(t.querySelectorAll("button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),summary,[tabindex]:not([tabindex='-1'])"));if(0===a.length)return;let l=a[0],s=a[a.length-1];n.shiftKey&&document.activeElement===l?(n.preventDefault(),s.focus()):n.shiftKey||document.activeElement!==s||(n.preventDefault(),l.focus())};return t.addEventListener("keydown",n),()=>t.removeEventListener("keydown",n)},[S,e,A]),(0,a.useEffect)(()=>{void 0===I||S||(t&&""===u.trim()&&""===h.trim()?o.current?.focus():r.current?.focus())},[h,u,S,I,t]);let q=tr(v),L=tr(b),P=!t,D=""!==u.trim()||""!==h.trim()||""!==f.trim()||q.length>0||L.length>0,F=""!==k.trim(),z=!S&&void 0===A&&(P?""!==u.trim()&&""!==h.trim():D||F),O=s.map(e=>e.id),K=O.slice(0,6),_=Math.max(0,O.length-K.length),B=(0,n.jsxs)("div",{className:"gw-grid",children:[(0,n.jsxs)("label",{className:"gw-field gw-span-2",children:[(0,n.jsxs)("span",{children:["Base URL"," ",t?(0,n.jsx)("span",{className:"dlg-opt",children:"leave blank to keep"}):null]}),(0,n.jsx)("input",{className:"gw-input mono",value:u,placeholder:t?"Only enter a value to replace the stored gateway URL":"https://llm-gateway.example.com/v1",autoComplete:"off",disabled:S||void 0!==A,ref:r,onChange:e=>m(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["API token"," ",t?(0,n.jsx)("span",{className:"dlg-opt",children:"leave blank to keep"}):null]}),(0,n.jsx)("input",{className:"gw-input mono",type:"password",value:h,placeholder:t?"Only enter a value to replace the stored token":"Paste your API token",autoComplete:"off",disabled:S||void 0!==A,onChange:e=>p(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["API key header ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("input",{className:"gw-input mono",value:f,placeholder:t?"Leave blank to keep stored header":"Authorization",autoComplete:"off",disabled:S||void 0!==A,onChange:e=>g(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsx)("span",{children:"Deployment names for Azure"}),(0,n.jsx)("textarea",{className:"gw-input gw-textarea mono",value:v,placeholder:"Paste deployment names, one per line",autoComplete:"off",disabled:S||void 0!==A,onChange:e=>x(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:b,placeholder:"Paste image-capable model names, one per line",autoComplete:"off",disabled:S||void 0!==A,onChange:e=>y(e.target.value)})]})]}),U=(0,n.jsx)("div",{className:"gw-setup-backdrop",role:"presentation",children:(0,n.jsx)("div",{ref:i,className:"gw-setup",role:"dialog","aria-modal":"true","aria-labelledby":"gw-setup-title","aria-describedby":"gw-setup-desc",tabIndex:-1,children:(0,n.jsxs)("form",{className:"gw-form",onSubmit:e=>void M(e),children:[(0,n.jsxs)("div",{className:"gw-head",children:[(0,n.jsxs)("div",{className:"gw-setup-badge",children:[(0,n.jsx)(w.Icons.cube,{size:18}),t?"Credential update":"Model gateway setup"]}),(0,n.jsx)("h1",{id:"gw-setup-title",children:t?"Update Keiko credentials":"Connect Keiko to your internal LLMs"}),(0,n.jsx)("p",{id:"gw-setup-desc",children:t?"Leave stored gateway fields blank to keep the current value. Keiko never returns existing secrets to the browser.":"Keiko needs the internal gateway URL and API token before chat and agent workflows can run. The token is tested once and stored only on this machine."})]}),(0,n.jsxs)("section",{className:"gw-section","aria-labelledby":"gw-model-section-title",children:[(0,n.jsx)("div",{className:"gw-section-head",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{id:"gw-model-section-title",children:"Model gateway"}),(0,n.jsx)("p",{children:t?"Blank gateway fields keep the stored value.":"Base URL and API token are required."})]})}),t?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"gw-current","aria-label":"Stored model gateway credentials",children:[(0,n.jsxs)("div",{className:"gw-current-row",children:[(0,n.jsx)("span",{children:"Gateway URL"}),(0,n.jsx)("strong",{children:"Stored"})]}),(0,n.jsxs)("div",{className:"gw-current-row",children:[(0,n.jsx)("span",{children:"API token"}),(0,n.jsx)("strong",{className:"mono",children:"••••••••••••"})]}),(0,n.jsxs)("div",{className:"gw-current-row",children:[(0,n.jsx)("span",{children:"API key header"}),(0,n.jsx)("strong",{className:"mono",children:l??"authorization"})]}),(0,n.jsxs)("div",{className:"gw-current-models",children:[(0,n.jsx)("span",{children:"Configured models"}),(0,n.jsxs)("div",{className:"gw-model-chips",children:[0===K.length?(0,n.jsx)("strong",{children:"Stored"}):K.map(e=>(0,n.jsx)("strong",{className:"mono",children:e},e)),_>0?(0,n.jsxs)("strong",{children:["+",_.toString()]}):null]})]})]}),(0,n.jsxs)("details",{className:"gw-replace",children:[(0,n.jsx)("summary",{children:"Replace model gateway settings"}),B]})]}):B]}),(0,n.jsxs)("section",{className:"gw-section","aria-labelledby":"gw-figma-section-title",children:[(0,n.jsx)("div",{className:"gw-section-head",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{id:"gw-figma-section-title",children:"Figma Snapshot"}),(0,n.jsx)("p",{children:"Optional connector credential."})]})}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["Figma access token ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("input",{className:"gw-input mono",type:"password",value:k,placeholder:t?"Stored Figma token is kept when blank":"Paste a read-only Figma PAT when needed",autoComplete:"off",disabled:S||void 0!==A,ref:o,onChange:e=>N(e.target.value)})]})]}),(0,n.jsx)("div",{className:"gw-note",children:"Stored secrets stay local and are never returned to the browser. Supported API-key headers: Authorization, X-Litellm-Key, X-Api-Key, api-key."}),void 0!==I?(0,n.jsxs)("div",{className:"gw-error",role:"alert",children:[I,void 0!==R?(0,n.jsx)("div",{className:"gw-error-code mono",children:R}):null]}):null,void 0!==A?(0,n.jsx)("div",{className:"gw-success",role:"status",children:A}):null,S?(0,n.jsx)("div",{className:"gw-pending",role:"status",children:"Testing credentials…"}):null,(0,n.jsx)("span",{id:"gw-submit-requirements",className:"visually-hidden",children:t?"Enter at least one field to update. Blank stored gateway fields keep their current value.":"Base URL and API token are required. The Figma access token is optional."}),(0,n.jsxs)("div",{className:"gw-actions",children:[void 0!==e?(0,n.jsx)("button",{className:"gw-cancel",type:"button",disabled:S||void 0!==A,onClick:e,children:"Cancel"}):null,(0,n.jsx)("button",{className:"gw-submit",type:"submit",disabled:!z,"aria-busy":S,"aria-describedby":"gw-submit-requirements",children:S?"Testing credentials…":"Test & save"})]})]})})});return"u"<typeof document?U:(0,ti.createPortal)(U,document.body)}let tc=[["ask","Ask every action"],["full","Full access"]];function td({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:tc.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 tu(e){return"chat"===e.kind&&e.toolCalling&&e.structuredOutput}function tm(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 th({value:e,projectId:t,selectProjectRoot:l=!1,onSelect:s,onClose:i}){let[r,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(e),[u,m]=(0,a.useState)(!1),[h,p]=(0,a.useState)(null),f=t??e.trim(),g=(0,a.useCallback)(async e=>{if(0===f.length){o(null),p("Enter an absolute folder path.");return}m(!0),p(null);try{let t=await (0,j.fetchFilesDirectories)(f,e);o(t),d(t.path)}catch(e){p(tm(e))}finally{m(!1)}},[f]);return(0,a.useEffect)(()=>{g(e.length>0?e:void 0)},[]),(0,n.jsxs)("div",{className:"dir-picker",role:"group","aria-label":"Directory picker",children:[(0,n.jsxs)("div",{className:"dir-top",children:[(0,n.jsx)("input",{className:"dlg-input mono dir-path",value:c,"aria-label":"Folder path",placeholder:"/absolute/folder/path",onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),g(c))}}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dir-go",onClick:()=>void g(c),children:"Go"})]}),null!==r?(0,n.jsx)("div",{className:"dir-roots",children:r.roots.map(e=>(0,n.jsx)("button",{type:"button",className:"dir-chip",onClick:()=>void g(e.path),children:e.label},`${e.label}:${e.path}`))}):null,(0,n.jsxs)("div",{className:"dir-list",children:[r?.parent!==null&&r?.parent!==void 0?(0,n.jsxs)("button",{type:"button",className:"dir-row",onClick:()=>void g(r.parent??void 0),children:[(0,n.jsx)(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!==h?(0,n.jsx)("div",{className:"dir-error",role:"alert",children:h}):null]}),(0,n.jsxs)("div",{className:"dir-actions",children:[(0,n.jsx)("button",{type:"button",className:"dlg-btn",onClick:i,children:"Close"}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",onClick:()=>{null!==r&&(s(l?r.roots[0]?.path??r.path:r.path),i())},disabled:null===r,children:"Use directory"})]})]})}let tp=[{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 tf(e){return e.filter(e=>e.available).map(e=>e.path)}function tg(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e.length>0)}function tv(e){return e.replaceAll("\\","/")}function tx(e,t){let n=tv(t.trim());if(0===n.length)return"";let a=tv(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 tb(e,t){return tg(t).map(t=>tx(e,t)).join(", ")}function ty({filesContext:e,firstRef:t,directoryField:l,setDirectoryField:s,setDialogError:i,onConfirm:r}){let[o,c]=(0,a.useState)("verify"),[d,u]=(0,a.useState)(e?.root??""),[m,h]=(0,a.useState)(""),[p,f]=(0,a.useState)([]),[g,v]=(0,a.useState)([]),[x,b]=(0,a.useState)(()=>{var t,n;let a;return t=e?.root??"",{verifyTargetFiles:a=null===(n=e?.activeFilePath??null)?"":tx(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),A=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===tg(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||tg(a.bugTargetFiles).length>0?null:"Bug investigation requires description, output, stack trace, or target files."}(o,E,m,x),T=null===A&&$&&!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(tu);f(a),h(e=>e||(a[0]?.id??"")),v(tf(n.projects))}).catch(t=>{e||i(tm(t))}).finally(()=>{e||k(!1)}),()=>{e=!0}},[i]);let M=e=>{b(t=>({...t,...e}))};(0,a.useEffect)(()=>{if(null===R)return;let e=tx(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 q=async()=>{v(tf((await (0,j.fetchProjects)()).projects))},L=async()=>{if(0!==E.length){S(!0),i(null);try{await (0,j.createProject)({path:E}),await q()}catch(e){i(tm(e))}finally{S(!1)}}},P=async()=>{if(!T)return void i(A??"Workspace is not registered.");I(!0),i(null);let t=function(e,t,n,a){if("verify"===e){let e=tg(a.verifyTargetFiles).map(e=>tx(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:tx(t,a.explainFilePath),...a.explainQuestion.trim().length>0?{question:a.explainQuestion.trim()}:{}}};if("unit-test-generation"===e){let e=tg(a.unitFilePaths).map(e=>tx(t,e)),l="module"===a.unitTargetKind?{kind:"module",moduleDir:tx(t,a.unitModuleDir)}:"changedFiles"===a.unitTargetKind?{kind:"changedFiles",filePaths:e}:{kind:"file",filePath:tx(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()}:{},...tg(a.bugTargetFiles).length>0?{targetFiles:tg(a.bugTargetFiles).map(e=>tx(t,e))}:{}}}}}(o,E,m,x);try{let n=await (0,j.startRun)(t);r({workflow:o,model:m,runId:n.runId,fingerprint:n.fingerprint,workspaceRoot:E,inputJson:JSON.stringify(t.input),...null!==e&&e.root===E?{__connectFilesId:e.id}:{}})}catch(e){e instanceof j.ApiError&&"WORKSPACE_NOT_REGISTERED"===e.code?(await q().catch(()=>void 0),i("Workspace is not registered.")):i(tm(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:tp.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)(th,{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 L(),children:N?"Registering…":"Register workspace"})]}):null,(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Model"}),(0,n.jsxs)("span",{className:"dlg-selwrap",children:[(0,n.jsx)("select",{className:"dlg-input mono",value:m,onChange:e=>h(e.target.value),disabled:0===p.length,children:p.map(e=>(0,n.jsx)("option",{value:e.id,children:e.id},e.id))}),(0,n.jsx)("span",{className:"dlg-selchev",children:(0,n.jsx)(w.Icons.chevron,{size:15})})]})]}),null!==R?(0,n.jsxs)("button",{type:"button",className:"dlg-current-file",onClick:()=>{if(null===R)return;let e=tx(E,R);"verify"===o?M({verifyTargetFiles:e}):"explain-plan"===o?M({explainFilePath:e}):"unit-test-generation"===o?"changedFiles"===x.unitTargetKind?M({unitFilePaths:e}):M({unitTargetKind:"file",unitFilePath:e}):M({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=>M({verifyTargetFiles:e.target.value}),onBlur:e=>M({verifyTargetFiles:tb(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=>M({explainFilePath:e.target.value}),onBlur:e=>M({explainFilePath:tx(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=>M({explainQuestion:e.target.value})})]})]}):"unit-test-generation"===o?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Target"}),(0,n.jsxs)("span",{className:"dlg-selwrap",children:[(0,n.jsxs)("select",{className:"dlg-input mono",value:x.unitTargetKind,onChange:e=>M({unitTargetKind:e.target.value}),children:[(0,n.jsx)("option",{value:"file",children:"Single file"}),(0,n.jsx)("option",{value:"module",children:"Module"}),(0,n.jsx)("option",{value:"changedFiles",children:"Changed files"})]}),(0,n.jsx)("span",{className:"dlg-selchev",children:(0,n.jsx)(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=>M({unitModuleDir:e.target.value}),onBlur:e=>M({unitModuleDir:tx(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=>M({unitFilePaths:e.target.value}),onBlur:e=>M({unitFilePaths:tb(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=>M({unitFilePath:e.target.value}),onBlur:e=>M({unitFilePath:tx(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=>M({bugDescription:e.target.value})})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:["Failing output ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,value:x.bugFailingOutput,onChange:e=>M({bugFailingOutput:e.target.value})})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:["Stack trace ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,value:x.bugStackTrace,onChange:e=>M({bugStackTrace:e.target.value})})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:["Target files ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,placeholder:"src/file.ts, src/other.ts",value:x.bugTargetFiles,onChange:e=>M({bugTargetFiles:e.target.value}),onBlur:e=>M({bugTargetFiles:tb(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:!T,"aria-busy":C,"aria-describedby":T||C?void 0:"agent-start-validation",onClick:()=>void P(),children:C?"Starting…":"Start agent"}),y?(0,n.jsx)("span",{id:"agent-start-validation",className:"dlg-note",role:"status",children:"Loading models and projects…"}):null,y||null===A?null:(0,n.jsx)("span",{id:"agent-start-validation",className:"dlg-note",role:"status",children:A})]})]})}function tj({type:e,types:t,filesContext:l=null,onConfirm:s,onClose:i}){let r=t[e],o=r.config??[],[c,d]=(0,a.useState)(()=>(function(e){let t={};for(let n of e)t[n.key]=n.def??"";return t})(o)),[u,m]=(0,a.useState)(!1),[h,p]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),v=(0,a.useRef)(null),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(()=>{m(!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=tf(e.projects)[0];t||void 0===n||d(e=>({...e,root:n}))}).catch(e=>{t||p(tm(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)(ty,{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)(td,{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)(th,{value:"string"==typeof c[e.key]?c[e.key]:"",selectProjectRoot:"root"===e.key,onSelect:t=>y(e.key,t),onClose:()=>g(null)}):null]},e.key)),null!==h?(0,n.jsx)("div",{className:"dlg-error",role:"alert",children:h}):null]}),(0,n.jsxs)("div",{className:"dlg-foot",children:[(0,n.jsx)("button",{type:"button",className:"dlg-btn",onClick:i,children:"Cancel"}),"agents"!==e?(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",onClick:k,children:S}):null]})]})})}let tw=new Map([["ArrowRight",1],["ArrowLeft",-1],["ArrowDown",3],["ArrowUp",-3]]);function tk({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=tw.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","aria-hidden":"true",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 tS(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 tC(e={},t=tS){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 tI(e=tS){return e("/api/memory/review-queue")}async function tE(e,t=tS){return t("/api/memory/consolidation/jobs",{method:"POST",body:JSON.stringify({settings:e})})}async function tR(e,t=tS){return t(`/api/memory/consolidation/jobs/${encodeURIComponent(e)}`)}async function t$(e,t=tS){return t(`/api/memory/consolidation/jobs/${encodeURIComponent(e)}/cancel`,{method:"POST",body:"{}"})}async function tA(e,t=tS){return t(`/api/memory/${encodeURIComponent(e)}`)}async function tT(e,t,n=tS){return n(`/api/memory/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})}async function tM(e,t=tS){return t(`/api/memory/${encodeURIComponent(e)}/pin`,{method:"POST",body:"{}"})}async function tq(e,t=tS){return t(`/api/memory/${encodeURIComponent(e)}/unpin`,{method:"POST",body:"{}"})}async function tL(e,t,n=tS){return n(`/api/memory/${encodeURIComponent(e)}/archive`,{method:"POST",body:JSON.stringify({...void 0!==t?{reason:t}:{}})})}async function tP(e,t,n=tS){return n(`/api/memory/${encodeURIComponent(e)}/forget`,{method:"POST",body:JSON.stringify({acknowledged:!0,...void 0!==t?{reason:t}:{}})})}async function tD(e,t,n=tS){return n(`/api/memory/${encodeURIComponent(e)}`,{method:"DELETE",body:JSON.stringify({acknowledged:!0,...void 0!==t?{reason:t}:{}})})}async function tF(e,t,n=tS){return n(`/api/memory/${encodeURIComponent(e)}/correct`,{method:"POST",body:JSON.stringify({body:t})})}async function tz(e,t=tS){return t(`/api/memory/proposals/${encodeURIComponent(e)}/accept`,{method:"POST",body:"{}"})}async function tO(e,t,n=tS){return n(`/api/memory/proposals/${encodeURIComponent(e)}/reject`,{method:"POST",body:JSON.stringify({...void 0!==t?{reason:t}:{}})})}let tK=[{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 t_(e){return tK.find(t=>t.workflowId===e)}function tB(e){return void 0===e||!Number.isFinite(e)||e<=0?0:Math.floor(e)}function tU(e){return"u">typeof TextEncoder?new TextEncoder().encode(e).length:e.length}function tW(e){let t=tB(e.modelContextWindow),n=tB(e.modelMaxOutputTokens),a=Math.max(0,t-n),l=tU(e.userDraftText),s=function(e){let t=0;for(let n of e)t+=tU(n.role),t+=tU(n.content);return t}(e.conversationHistory),i=function(e){if(void 0===e)return 0;let t=0;for(let n of e)t+=tB(n.extractedBytes);return t}(e.documentContext),r=tB(e.repoContextPackBytes),o=tB(e.knowledgeCapsuleBytes),c=tB(e.memoryContextBytes),d=l+s+i+r+o+c,u=Math.ceil(d/4),m=function(e,t){if(t<=0)return"exceeded";let n=e/t;return n>.95?"exceeded":n>.75?"high":n>.5?"moderate":"low"}(u,a);return{approximateBytes:d,approximateTokens:u,contextWindowTokens:t,reservedOutputTokens:n,availableInputTokens:a,pressure:m,breakdown:{draftBytes:l,historyBytes:s,documentBytes:i,repoContextBytes:r,knowledgeBytes:o,memoryBytes:c}}}function tH(e){return"chat"===e.kind}let tG={embedding:"embedding-only","ocr-vision":"ocr-vision-only"},tV=[/\bsk-[A-Za-z0-9_-]{12,}\b/g,/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}\b/gi,/\bgho_[A-Za-z0-9_]{12,}\b/g,/\bghp_[A-Za-z0-9_]{12,}\b/g],tY=/\s+\(([A-Z][A-Z0-9_/-]{2,})\)\s*$/;function tQ(e){let t=e;for(let e of tV)t=t.replace(e,"[REDACTED]");return t.replace(/\bBearer\s+\[REDACTED\]/gi,"[REDACTED]")}function tJ(e,t){return"BAD_REQUEST"===t&&e.toLowerCase().includes("too broad")&&e.toLowerCase().includes("connected")}function tX(e,t){return tJ(e,t)?"Narrow the connected-source question":"PAYLOAD_TOO_LARGE"===t?"Request is too large":"NO_MODEL"===t?"No model is available":void 0!==t?"Request failed":"Something went wrong"}function tZ(e,t){return tJ(e,t)?"Ask about a specific file, folder, symbol, identifier, or exact phrase. For broad questions over large project folders, narrow the Files scope first.":"PAYLOAD_TOO_LARGE"===t?"Reduce the selected scope or remove large attachments before retrying.":void 0}function t0(e,t){if(e instanceof j.ApiError){let n=tQ(e.message.trim());return n.length>0?`${n} (${e.code})`:`${t} (${e.code})`}return e instanceof Error&&e.message.trim().length>0?tQ(e.message.trim()):t}let t1="\n…[truncated]",t2=["text/"],t3=new Set(["application/json","application/x-yaml","application/yaml"]),t4=new TextEncoder;function t6(e){return t4.encode(e).length}function t5(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t>=0?e.slice(t+1):e}let t8=`${String(256)} KB`;function t7(e){return`"${e}" won't be sent — the ${t8} attachment limit was already used by earlier files.`}async function t9(e,t){var n,a;let l,s,i,r,o;if(e.remainingAggregate<=0)return t7(t5(t.name));try{l=await t.file.text()}catch{return n=t5(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-t6(t1),0));if(c<=0)return t7(t5(t.name));let{entry:d,consumed:u}=(i=(s=t6(a=l)>c)?function(e,t){if(t<=0)return"";if(t6(e)<=t)return e;let n=0,a="";for(let l of e){let e=n+t6(l);if(e>t)break;n=e,a+=l}return a}(a,c):a,r=t6(i),o=s?t6(t1):0,{entry:{id:t.id,displayName:t5(t.name),mimeType:t.mimeType,sizeBytes:t.sizeBytes,extractedBytes:r,truncated:s,truncationMarker:s?t1:void 0,text:i},consumed:r+o});if(0===d.text.length)return 0===l.length?void 0:t7(t5(t.name));e.entries.push(d),e.remainingAggregate-=u}async function ne(e){let t=e.filter(e=>{var t;return t=e.mimeType,!!t2.some(e=>t.startsWith(e))||t3.has(t)}),n=t.slice(0,16),a={entries:[],remainingAggregate:262144},l=[];for(let e of n){let t=await t9(a,e);void 0!==t&&l.push(t)}for(let e of t.slice(16)){var s;l.push((s=t5(e.name),`"${s}" won't be sent — only the first ${String(16)} documents are included.`))}return{entries:a.entries,failures:l}}let nt=["text/"],nn=new Set(["application/pdf","application/json","application/x-yaml","application/yaml"]),na="New chat",nl="keiko:chat-upsert",ns="keiko:chat-delete",ni=["completed","failed","cancelled"];function nr(e){return"idle"!==e&&!ni.includes(e)}let no="The conversation context exceeded the model's window. Clear history or pick a larger-context model.",nc="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.",nd=new Set(["CONVERSATION_OVERSIZED_CONTEXT","GATEWAY_CONTEXT_OVERFLOW"]),nu=["context length","context_length_exceeded","max_tokens","too many tokens"],nm=["empty assistant response","empty grounded answer","without assistant content"];function nh(e){return void 0!==e&&e.contextWindowTokens>0&&"exceeded"===e.pressure}function np(e){let t;return function(e){if(e instanceof j.ApiError&&nd.has(e.code))return!0;let t=e instanceof Error?e.message.toLowerCase():"";return 0!==t.length&&nu.some(e=>t.includes(e))}(e)?no:0!==(t=e instanceof Error?e.message.toLowerCase():"").length&&nm.some(e=>t.includes(e))?e instanceof j.ApiError?`${nc} (${e.code})`:nc:t0(e,"Something went wrong. Try again.")}function nf(e){return[...e].sort((e,t)=>t.updatedAt-e.updatedAt)}function ng(e){window.dispatchEvent(new CustomEvent(nl,{detail:e}))}function nv(e){return e.find(tH)?.id}function nx(e,t){return void 0!==e&&t.some(t=>t.id===e&&tH(t))?e:nv(t)}function nb(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 ny={projects:[],chats:[],messages:[],models:[],activeProject:void 0,activeChat:void 0,selectedModel:void 0};async function nj(e){let t=(await (0,j.fetchModels)()).models.filter(tH),n=nv(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=nf((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=nx(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:na};l?.available===!0&&(s.projectPath=l.path);let i=await (0,j.createDesktopChat)(s);return ng(i.chat),{models:t,selectedModel:i.chat.selectedModel,projects:Array.from(i.projects),activeProject:i.project,chats:nf(i.chats),activeChat:i.chat,messages:Array.from(i.messages)}}function nw(e={}){let t=e.autoCreate??!0,[n,l]=(0,a.useState)(ny),[s,i]=(0,a.useState)(""),[r,o]=(0,a.useState)(!0),[c,d]=(0,a.useState)("idle"),u=nr(c),m=(0,a.useRef)("idle"),h=(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)([]),[$,A]=(0,a.useState)([]),T=(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":nt.some(e=>t.startsWith(e))||nn.has(t)?"document":"unsupported-type";if("unsupported-type"===l)return{ok:!1,reason:"unsupported-type"};let s=n.models.find(e=>e.id===n.selectedModel);if(void 0!==s&&("image"===l&&!s.supportsImageInput||"document"===l&&!s.supportsDocumentInput))return{ok:!1,reason:"text-only-model"};if("image"===l)try{a=await new Promise((t,n)=>{let a=new FileReader;a.onload=()=>t(a.result),a.onerror=()=>n(Error("FileReader error")),a.readAsDataURL(e)})}catch{return{ok:!1,reason:"unsupported-type"}}let i={id:crypto.randomUUID(),kind:l,name:e.name,mimeType:e.type,sizeBytes:e.size,previewDataUrl:a,file:e};return R(e=>[...e,i]),{ok:!0}},[n.models,n.selectedModel]),M=(0,a.useCallback)(e=>{R(t=>t.filter(t=>t.id!==e))},[]),q=(0,a.useCallback)(()=>{R([])},[]),L=(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 ne(e);n.length>0&&f(n.join(" "));let a=t.map(e=>({id:e.id,displayName:e.displayName,truncated:e.truncated}));return{entries:t,disclosures:a}},[E]),P=(0,a.useCallback)(()=>{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 tz(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 tO(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=>{m.current=e,d(e)},[]);(0,a.useEffect)(()=>{S.current=n.activeChat?.id},[n.activeChat?.id]),(0,a.useEffect)(()=>{I.current=n.models},[n.models]),(0,a.useEffect)(()=>{let e=!1;return async function(){o(!0),f(void 0);try{let n=await nj(t);e||l(e=>({...e,...n}))}catch(t){e||f(np(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:nf([t,...e.chats.filter(e=>e.id!==t.id)]),activeChat:e.activeChat?.id===t.id?t:e.activeChat,selectedModel:e.activeChat?.id===t.id?nx(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(nl,e),window.addEventListener(ns,t),()=>{window.removeEventListener(nl,e),window.removeEventListener(ns,t)}},[]),(0,a.useEffect)(()=>()=>{h.current?.abort()},[]);let _=(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&&(ng(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(np(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})}))}})},[]),B=(0,a.useCallback)(async(e,t)=>{let a=nx(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:na},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,ng(o.chat),l({projects:Array.from(o.projects),chats:nf(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(np(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=nf(t.chats),s=a[0];if(void 0===s)return void await B(e);let i=await (0,j.fetchChatMessages)(s.id,e.path);S.current=s.id;let r=nx(s.selectedModel,n.models);l(e=>({...e,chats:a,activeChat:s,selectedModel:r,messages:Array.from(i.messages)})),b(void 0)}catch(e){f(np(e))}},[B,n.models]),W=(0,a.useCallback)(async e=>{f(void 0),h.current?.abort(),h.current=null,S.current=e.id,v(void 0),b(void 0),A([]);try{let t=await (0,j.fetchChatMessages)(e.id,e.projectPath),a=nx(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(np(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 B(e.project)}catch(e){f(np(e))}}},[B]),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:nf([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)]})),ng(a.chat),void 0!==a.memory&&b(a.memory),n("completed")},onError:({code:t,message:a})=>{f(np(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(np(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:nf([o.chat,...e.chats.filter(e=>e.id!==o.chat.id)]),messages:[...e.messages.filter(e=>e.id!==a),...Array.from(o.messages)]})),ng(o.chat),b(o.memory),"completed"}catch(n){if(n instanceof DOMException&&"AbortError"===n.name)return"cancelled";f(np(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:nf(r.chats),activeChat:o??e.activeChat})),void 0!==o&&ng(o),"completed"}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return"cancelled";return f(np(e)),l(e=>({...e,messages:e.messages.filter(e=>e.id!==a)})),"failed"}},[K]),Z=(0,a.useCallback)(()=>{nr(m.current)&&(h.current?.abort(),h.current=null,K("cancelled"))},[K]),ee=(0,a.useCallback)(async()=>{if(nr(m.current))return;let e=s.trim(),t=n.activeChat,a=n.activeProject,r=nx(n.selectedModel,n.models);if(0===e.length||void 0===t||void 0===a||void 0===r)return;if(nh(tW({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(no);if(nb(t)&&E.length>0)return void f("Attachments are not supported for grounded chats. Remove the attachment or switch to a non-grounded chat.");let o={id:`local-${String(Date.now())}`,chatId:t.id,role:"user",content:e,timestamp:Date.now(),runId:void 0,workflowId:void 0,workflowStatus:void 0,shortResult:void 0,taskType:void 0};K("queued"),i(""),f(void 0),l(e=>({...e,messages:[...e.messages,o]}));let c=new AbortController;h.current=c,b(void 0);try{let n=nb(t),{entries:l,disclosures:s}=n?{entries:[],disclosures:[]}:await L(),i=n?await X(t,a,e,o.id,r,c.signal):await J(t,a,e,o.id,r,c.signal,l);"cancelled"===m.current||K(i),"completed"===i&&(q(),A(s))}finally{h.current=null}},[s,n.activeChat,n.activeProject,n.selectedModel,n.models,n.messages,E,X,J,L,q,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 tW({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(nr(m.current))return{ok:!1,reason:"request-failed",message:"A request is already in flight."};let t=e.text.trim();if(0===t.length)return{ok:!1,reason:"missing-input"};let a=n.activeChat,s=n.activeProject;if(void 0===a||void 0===s)return{ok:!1,reason:"missing-chat"};let i=n.models.find(t=>t.id===e.modelId);if(void 0===i||!tu(i))return{ok:!1,reason:"not-workflow-eligible"};let r=t_(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=np(t);return f(e),{ok:!1,reason:"request-failed",message:e}}},[n.activeChat,n.activeProject,n.models]),el=(0,a.useCallback)(async e=>{if(nr(m.current))return{ok:!1,reason:"request-failed",message:"A request is already in flight."};if(void 0===n.activeChat)return{ok:!1,reason:"missing-chat"};if(0===e.modelId.trim().length)return{ok:!1,reason:"missing-model"};try{let t=await (0,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=np(t);return f(e),{ok:!1,reason:"request-failed",message:e}}},[n.activeChat]),es=(0,a.useCallback)(e=>{ng(e),l(t=>({...t,chats:t.chats.map(t=>t.id===e.id?e:t),activeChat:t.activeChat?.id===e.id?e:t.activeChat}))},[]),ei=(0,a.useCallback)(()=>{f(void 0)},[]);return{projects:n.projects,chats:n.chats,messages:n.messages,models:n.models,activeProject:n.activeProject,activeChat:n.activeChat,selectedModel:n.selectedModel,noEligibleModels:!r&&void 0===nx(n.selectedModel,n.models),draft:s,loading:r,sending:u,sendStatus:c,error:p,clearError:ei,setDraft:i,setSelectedModel:_,openNewChat:B,openProject:U,openChat:W,addProject:H,sendMessage:ee,cancelSend:Z,replaceChat:es,latestGrounded:g,cancelGrounded:Z,pendingAttachments:E,addPendingAttachment:T,removePendingAttachment:M,clearPendingAttachments:q,lastSentDocuments:$,budget:en,memoryEnabled:y,setMemoryEnabled:w,memoryBudgetTokens:k,setMemoryBudgetTokens:N,latestMemory:x,clearLatestMemory:P,acceptMemoryCandidate:F,rejectMemoryCandidate:z,forgetMemoryAction:O,clearHistory:et,launchWorkflowFromConversation:ea,launchGroundedWorkflowHandoff:el}}let nk="keiko.theme",nN="dark";var nS=e.i(66702);let nC=["agent","capsule","capsule-set","chat","connector","data-source","evidence-run","mcp-tool","memory","patch-proposal","skill","tool","workflow-run","workspace-path"],nI=["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"],nR=["draft","active","archived","superseded","revoked","blocked","stale"],n$={"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"],nT="Unable to reach the local backend. Check that the Keiko server is running (keiko ui).";class nM 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 nq(e){let t;try{t=await e.json()}catch{throw new nM("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 nM(l,s,e.status,i)}return t}function nL(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 nP(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:nL({}),body:JSON.stringify(t)});return{decision:(await nq(n)).decision}}async function nD(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:nL({idempotencyKey:t}),body:JSON.stringify(n)}),l=await nq(a);return{relationship:l.relationship,etag:l.etag}}async function nF(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 nq(n);return{entries:a.entries,truncated:a.truncated,nextCursor:a.nextCursor}}async function nz(e){let t=await fetch(`/api/relationships/${encodeURIComponent(e)}`);return(await nq(t)).relationship}async function nO(e,t,n,a){let l=await fetch(`/api/relationships/${encodeURIComponent(e)}`,{method:"PATCH",headers:nL({idempotencyKey:a,ifMatch:n}),body:JSON.stringify({schemaVersion:"1",...t})}),s=await nq(l);return{relationship:s.relationship,etag:s.etag}}async function nK(e,t,n){let a=await fetch(`/api/relationships/${encodeURIComponent(e)}`,{method:"DELETE",headers:nL({idempotencyKey:n,ifMatch:t})});return(await nq(a)).relationship}async function n_(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 nq(a)).report}async function nB(e){return nq(await fetch(`/api/relationships/${encodeURIComponent(e)}/explain`))}async function nU(){return nq(await fetch("/api/relationships/health"))}let nW=[{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 nH(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 nG(e){let t=[...e.mod].sort();return`${t.join("+")}|${e.key.toLowerCase()}`}let nV={undoStack:[],redoStack:[]};class nY extends Error{conflicts;constructor(e){super(`Workspace keyboard shortcut conflicts detected: ${e.map(e=>`${nG(e.chord)} (${e.commandIds.join(", ")})`).join("; ")}`),this.name="WorkspaceShortcutConflictError",this.conflicts=e}}class nQ extends Error{reserved;constructor(e){super(`Workspace keyboard shortcut bindings refused: ${e.map(e=>`${e.commandId} → ${nG(e.chord)}`).join("; ")} are browser-reserved`),this.name="WorkspaceShortcutReservedError",this.reserved=e}}let nJ=[{commandId:"undo",chord:{key:"z",mod:["cmd"]}},{commandId:"redo",chord:{key:"z",mod:["cmd","shift"]}},{commandId:"focus-status",chord:{key:"s",mod:["alt"]}}];var nX=e.i(57688);let nZ="cmp-budget-exceeded-alert",n0={low:"Low",moderate:"Moderate",high:"High",exceeded:"Exceeded"},n1={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"},n2="Token counts are approximate. Actual model usage may vary.";function n3(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toString()}function n4({budget:e,onClearHistory:t,disabled:l}){let[s,i]=(0,a.useState)(!1),[r,o]=(0,a.useState)(!1),c=(0,a.useRef)(null),d=(0,a.useRef)(null);if((0,a.useEffect)(()=>{s&&c.current?.focus()},[s]),void 0===e)return null;let u=e.contextWindowTokens>0,m=n3(e.approximateTokens),h=n3(e.contextWindowTokens),p=e.pressure,f=u&&"exceeded"===p;return(0,n.jsxs)("div",{className:"cmp-budget","data-pressure":u?p:"unknown",children:[(0,n.jsxs)("div",{className:"cmp-budget-row",children:[(0,n.jsx)("span",{className:"cmp-budget-count",children:u?`Approximate context: ${m} / ${h} tokens`:`Approximate context: ${m} tokens`}),u?(0,n.jsx)("span",{className:n1[p],"aria-label":`Context pressure: ${n0[p]}`,children:n0[p]}):null,(0,n.jsx)("span",{className:"cmp-budget-info",role:"img",tabIndex:0,"aria-label":n2,"data-tip":n2,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:nZ,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 n6({notice:e,className:t="ui-error-notice",id:l,onDismiss:s}){let i=`${e.title}
|
|
105
|
+
${e.message}
|
|
106
|
+
${e.code??""}
|
|
107
|
+
${e.remediation??""}`,[r,o]=(0,a.useState)();return r===i?null:(0,n.jsxs)("div",{id:l,className:t,role:"alert","aria-live":"assertive",children:[(0,n.jsxs)("div",{className:"ui-error-notice-title-row",children:[(0,n.jsx)("div",{className:"ui-error-notice-title",children:e.title}),(0,n.jsx)("button",{type:"button",className:"ui-error-notice-close","aria-label":"Dismiss error",title:"Dismiss error",onClick:()=>{o(i),s?.()},children:(0,n.jsx)(w.Icons.close,{size:14})})]}),(0,n.jsx)("div",{className:"ui-error-notice-message",children:e.message}),void 0!==e.remediation?(0,n.jsx)("div",{className:"ui-error-notice-remediation",children:e.remediation}):null,void 0!==e.code?(0,n.jsx)("div",{className:"ui-error-notice-code mono",children:e.code}):null]})}function n5({error:e,fallback:t,className:a,id:l,onDismiss:s}){return(0,n.jsx)(n6,{id:l,className:a,notice:function(e,t){var n;let a;if(e instanceof j.ApiError){let n=tQ(e.message.trim())||t;return{title:tX(n,e.code),message:n,code:e.code,remediation:tZ(n,e.code)}}let l=(n=tQ(("string"==typeof e?e.trim():e instanceof Error?e.message.trim():"")||t),null===(a=tY.exec(n))?{message:n,code:void 0}:{message:n.slice(0,a.index).trim(),code:a[1]});return{title:tX(l.message,l.code),message:l.message,code:l.code,remediation:tZ(l.message,l.code)}}(e,t),onDismiss:s})}var n8=e.i(83449);function n7(e){return Number.isFinite(e)?String(e):"—"}function n9(e,t){return Number.isFinite(e)?t(e):"—"}function ae(e){return e.toLocaleString("en-US")}function at(e){return e.replaceAll("-"," ")}function an({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 aa({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`${at(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)(an,{label:"Searched",value:`${String(t.searchCalls)} / ${n7(a.searchCallsMax)} searches`}),(0,n.jsx)(an,{label:"Read",value:`${String(t.filesRead)} / ${n7(a.filesReadMax)} files`}),(0,n.jsx)(an,{label:"Bytes",value:`${(0,n8.formatBytes)(t.excerptBytes)} / ${n9(a.excerptBytesMax,n8.formatBytes)}`}),(0,n.jsx)(an,{label:"Input",value:`${ae(t.modelInputTokens)} / ${n9(a.modelInputTokensMax,ae)} tokens`}),(0,n.jsx)(an,{label:"Output",value:`${ae(t.modelOutputTokens)} / ${n9(a.modelOutputTokensMax,ae)} tokens`}),(0,n.jsx)(an,{label:"Rerank",value:`${String(t.rerankCalls)} / ${n7(a.rerankCallsMax)} calls`}),(0,n.jsx)(an,{label:"Time",value:`${(0,n8.formatMs)(e.elapsedMs)} / ${n9(a.elapsedMsMax,n8.formatMs)}`}),(0,n.jsx)(an,{label:"Query",value:at(e.queryKind)})]})]})}function al({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 as({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)(al,{score:e.score})]})}function ai({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 ar({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)(as,{citation:e})},e.stableId))}),(0,n.jsx)(ai,{total:s.length,expanded:t,onToggle:()=>{l(e=>!e)}})]})}function ao({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)(al,{score:e.score})]})},e.stableId))}),(0,n.jsx)(ai,{total:s.length,expanded:t,onToggle:()=>{l(e=>!e)}})]})}function ac({markers:e}){if(0===e.length)return null;let t=Array.from(new Set(e.map(e=>at(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:`${at(e.kind)}: ${e.claim}`},`${e.kind}-${String(t)}`))})]})}function ad({omittedCount:e,omittedCounts:t}){if(e<=0)return null;let a=Object.entries(t).filter(([,e])=>e>0).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>`${at(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 au=[{reason:"size-exceeded",label:"larger than 2 MB"},{reason:"binary",label:"binary or an unsupported format"},{reason:"tool-unavailable",label:"unreadable"}];function am({omittedCounts:e}){let t=au.map(({reason:t,label:n})=>({label:n,count:e[t]})).filter(e=>e.count>0),a=t.reduce((e,t)=>e+t.count,0);if(a<=0)return null;let l=t.map(e=>`${String(e.count)} ${e.label}`).join(", ");return(0,n.jsxs)("div",{className:"grounded-coverage-notice",role:"note",children:[(0,n.jsx)("span",{className:"grounded-coverage-notice-title",children:"Partial coverage"}),(0,n.jsx)("span",{children:`This answer reflects only the searchable files in the connected scope — ${String(a)} ${1===a?"file":"files"} ${1===a?"was":"were"} not searched (${l}). It does not cover the entire folder.`}),e.binary>0?(0,n.jsx)("span",{children:"Some connected files were skipped because Repository Search currently reads text/code files only."}):null]})}function ah({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 ap({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)(an,{label:"Mode",value:at(e.scopeKind)}),(0,n.jsx)(an,{label:"Capsules",value:String(e.capsuleCount)}),(0,n.jsx)(an,{label:"Sources",value:String(e.sourceCount)}),(0,n.jsx)(an,{label:"Citations",value:String(e.citationCount)}),(0,n.jsx)(an,{label:"Context budget",value:`${String(e.referencesUsed)} / ${String(e.referenceBudget)} references`})]})]})}function af({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)(aa,{contextPack:e.folder}),(0,n.jsx)(ap,{contextPack:e.knowledge})]})}function ag({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)(ao,{citations:e.citations}),(0,n.jsx)(ac,{markers:e.uncertainty}),(0,n.jsx)(ap,{contextPack:e.contextPack})]}):"hybrid"===e.groundingKind?(0,n.jsxs)("div",{className:"grounded-answer",children:[(0,n.jsx)(am,{omittedCounts:e.contextPack.folder.omittedCounts}),(0,n.jsx)(ar,{citations:e.citations}),(0,n.jsx)(ao,{citations:e.knowledgeCitations}),(0,n.jsx)(ac,{markers:e.uncertainty}),(0,n.jsx)(ad,{omittedCount:e.omittedCount,omittedCounts:e.contextPack.folder.omittedCounts}),(0,n.jsx)(ah,{runId:e.evidenceRunId,runIds:e.evidenceRunIds}),(0,n.jsx)(af,{contextPack:e.contextPack})]}):(0,n.jsxs)("div",{className:"grounded-answer",children:[(0,n.jsx)(am,{omittedCounts:e.contextPack.omittedCounts}),(0,n.jsx)(ar,{citations:e.citations}),(0,n.jsx)(ac,{markers:e.uncertainty}),(0,n.jsx)(ad,{omittedCount:e.omittedCount,omittedCounts:e.contextPack.omittedCounts}),(0,n.jsx)(ah,{runId:e.evidenceRunId,runIds:e.evidenceRunIds}),(0,n.jsx)(aa,{contextPack:e.contextPack})]})}var av=a;let ax=["<script","</script","<iframe","</iframe","<object","</object","<embed","</embed","<style","</style","<svg","</svg","<form","</form","<meta","<link","<base"],ab=[" ","\n"," ","'",'"'];function ay(e){let t=function(e){let t=e.toLowerCase().replaceAll("\0",""),n="";for(let e=0;e<t.length;e++){let a=t[e]??"";if("<"===a){for(n+="<";e+1<t.length&&(" "===t[e+1]||" "===t[e+1]||"\n"===t[e+1]||"\r"===t[e+1]);)e++;continue}n+=a}return n}(e);for(let e of ax)if(t.includes(e))return!0;let n=0;for(;n<t.length-4;){let e=t[n];if(ab.includes(e)&&"o"===t[n+1]&&"n"===t[n+2]){let e=n+3;for(;e<t.length&&/[a-z]/.test(t[e]??"");)e++;if(e<t.length&&"="===t[e])return!0}n++}return!1}function aj(e,t,n,a){a>n&&e.push({kind:"text",text:t.slice(n,a)})}function aw(e){return void 0!==e&&/[A-Za-z0-9]/.test(e)}let ak=new Set([" "," ","\n","<",">",'"']),aN=new Set([".",",",")","]","!","?"]);function aS(e,t=0){if(t>=16)return e.length>0?[{kind:"text",text:e}]:[];let n=[],a=0,l=0;for(;a<e.length;){let s=function(e,t,n,a){if("`"!==t[n])return -1;let l=t.indexOf("`",n+1);return -1===l?-1:(aj(e,t,a,n),e.push({kind:"inline-code",text:t.slice(n+1,l)}),l+1)}(n,e,a,l);if(-1!==s||-1!==(s=function(e,t,n,a,l){let s=t[n],i=t[n+1];if(n+1>=t.length||("*"!==s||"*"!==i)&&("_"!==s||"_"!==i))return -1;let r=t.indexOf(s+i,n+2);if(-1===r)return -1;aj(e,t,a,n);let o=t.slice(n+2,r);return e.push({kind:"strong",children:aS(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&&aw(t[n-1])&&aw(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&&aw(t[i-1])&&aw(t[i+1])?-1:(aj(e,t,a,n),e.push({kind:"em",children:aS(t.slice(n+1,i),l+1)}),i+1)}(n,e,a,l,t))||-1!==(s=function(e,t,n,a){let l;if("["!==t[n])return -1;let s=t.indexOf("]",n+1);if(-1===s||"("!==t[s+1])return -1;let i=t.indexOf(")",s+2);if(-1===i)return -1;let r=t.slice(n+1,s),o=t.slice(s+2,i);return aj(e,t,a,n),((l=o.trim().toLowerCase()).startsWith("http://")||l.startsWith("https://"))&&!ay(r)&&!ay(o)?e.push({kind:"link",text:r,href:o}):e.push({kind:"text",text:`[${r}](${o})`}),i+1}(n,e,a,l))||-1!==(s=function(e,t,n,a){if("h"!==t[n])return -1;let l="https://"===t.slice(n,n+8),s="http://"===t.slice(n,n+7);if(!l&&!s)return -1;let i=function(e,t){let n=t;for(;n<e.length&&!ak.has(e[n]??"");)n++;for(;n>t&&aN.has(e[n-1]??"");)n--;return n}(t,n);if(i-n<=(l?8:7))return -1;let r=t.slice(n,i);return aj(e,t,a,n),e.push({kind:"link",text:r,href:r}),i}(n,e,a,l))){l=s,a=s;continue}a++}return aj(n,e,l,e.length),n}function aC(e){let t=e.trim(),n=t.startsWith(":"),a=t.endsWith(":");return n&&a?"center":a?"right":n?"left":void 0}function aI(e){let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|")}function aE(e){let t=/^( *)([*+\-]) (.*)$/.exec(e);return t?{match:!0,indent:t[1]?.length??0,text:t[3]??""}:{match:!1}}function aR(e){let t=/^( *)\d+\. (.*)$/.exec(e);return t?{match:!0,indent:t[1]?.length??0,text:t[2]??""}:{match:!1}}function a$(e){return e.includes("|")}function aA(e){let t=e.trim();return/^(-{3,}|\*{3,}|_{3,})$/.test(t)}function aT(e,t){let n=[],a=t?aR:aE;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=[...aS(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 aM({text:e}){let[t,a]=(0,av.useState)(!1),[l,s]=(0,av.useState)(""),i=(0,av.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 aq={1:"h3",2:"h4",3:"h5",4:"h6",5:"h6",6:"h6"},aL={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 aP(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:aP(e,t)},t);case"heading":{let a=e.level??1,l=aq[a],s=aL[a];return(0,n.jsx)(l,{className:s,children:aP(e,t)},t)}case"blockquote":return(0,n.jsx)("blockquote",{className:"sm-blockquote",children:aP(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)(aM,{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:aP(e,t)},t);case"ol":return(0,n.jsx)("ol",{className:"sm-ol",children:aP(e,t)},t);case"li":return(0,n.jsx)("li",{className:"sm-li",children:aP(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:aP(e,t)})},t);case"thead":return(0,n.jsx)("thead",{children:aP(e,t)},t);case"tbody":return(0,n.jsx)("tbody",{children:aP(e,t)},t);case"tr":return(0,n.jsx)("tr",{children:aP(e,t)},t);case"th":return(0,n.jsx)("th",{style:a,children:aP(e,t)},t);case"td":return(0,n.jsx)("td",{style:a,children:aP(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:aP(e,t)},t);case"em":return(0,n.jsx)("em",{children:aP(e,t)},t);default:return null}}(e,t);return null!==i?i:null}function aF({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:aS(s)}),e.i++,!0}(t,a,n))return;if(aA(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(a$(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}(aI(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()||!a$(t.trim()))break;s.push(t),e.i++}return n=aI(t),a=aI(l).map(aC),{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:aS(e.trim())},void 0!==n?{...l,align:n}:l})}]},{kind:"tbody",children:s.map(e=>({kind:"tr",children:aI(e).map((e,t)=>{var n;let l;return n=a[t],l={kind:"td",children:aS(e.trim())},void 0!==n?{...l,align:n}:l})}))}]}}(t,a)),1)||(aE(a).match?(n.push(aT(t,!1)),!0):!!aR(a).match&&(n.push(aT(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))||!!aE(e).match||!!aR(e).match||aA(e)}(n))break;t.push(n),e.i++}return 0===t.length?null:{kind:"paragraph",children:aS(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 az extends av.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)(aF,{source:this.props.source})}}function aO({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 aK({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)(aO,{attachment:e,onRemove:t},e.id))})}function a_({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 aB="cmp-attach-disabled-hint";function aU({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:aB,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:aB,title:i?"Attach file":"Attachments not supported by this model",onClick:o,children:(0,n.jsx)(w.Icons.files,{size:16})})]})}function aW({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 aH({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 aG({selectedModel:e,launch:t}){let[l,s]=(0,a.useState)(!1),i=(0,a.useRef)(null);return void 0!==e&&tu(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)(aY,{modelId:e.id,launch:t,onClose:()=>{s(!1),i.current?.focus()}}):null]}):null}function aV(e){return Array.from(e.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'))}function aY({modelId:e,launch:t,onClose:l}){let s=(0,a.useId)(),i=(0,a.useId)(),[r,o]=(0,a.useState)(),[c,d]=(0,a.useState)(""),[u,m]=(0,a.useState)(!1),[h,p]=(0,a.useState)(),f=(0,a.useRef)(null),g=void 0===r?void 0:t_(r);async function v(){if(void 0===g||0===c.trim().length)return;m(!0),p(void 0);let n=await t({workflowId:g.workflowId,modelId:e,text:c});(m(!1),n.ok)?l():p(function(e){if(void 0!==e.message&&e.message.length>0)return e.message;switch(e.reason){case"not-workflow-eligible":return"The selected model does not support workflow runs. Pick a model with tool calling and structured output.";case"unknown-workflow":return"That workflow is no longer available.";case"missing-chat":return"Open or create a chat first, then launch the workflow.";case"missing-input":return"Provide an input before launching the workflow.";case"request-failed":return"Could not launch the workflow. Try again, or check the gateway logs.";default:return"Could not launch the workflow."}}(n))}(0,a.useEffect)(()=>{f.current?.focus()},[r]),(0,a.useEffect)(()=>{function e(e){if("Escape"===e.key)return void l();if("Tab"!==e.key)return;let t=f.current;if(null===t)return;let n=aV(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:tK.map(e=>(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button",className:"wf-dialog-choice",onClick:()=>o(e.workflowId),children:[(0,n.jsx)("span",{className:"wf-dialog-choice-label",children:e.label}),(0,n.jsx)("span",{className:"wf-dialog-choice-desc",children:e.description})]})},e.workflowId))}):(0,n.jsxs)("div",{className:"wf-dialog-form",children:[(0,n.jsx)("p",{className:"wf-dialog-form-desc",children:g.description}),(0,n.jsx)("label",{className:"wf-dialog-field",htmlFor:i,children:g.prompt}),(0,n.jsx)("textarea",{id:i,className:"wf-dialog-input mono",rows:3,placeholder:g.placeholder,value:c,onChange:e=>d(e.target.value)}),void 0!==h?(0,n.jsx)("div",{role:"alert",className:"wf-dialog-error",children:h}):null,(0,n.jsxs)("div",{className:"wf-dialog-actions",children:[(0,n.jsx)("button",{type:"button",className:"wf-dialog-cancel",onClick:()=>o(void 0),children:"Back"}),(0,n.jsx)("button",{type:"button",className:"wf-dialog-launch",disabled:u||0===c.trim().length,onClick:()=>{v()},children:u?"Launching…":"Launch"})]})]}),(0,n.jsx)("button",{type:"button",className:"wf-dialog-close","aria-label":"Close launch workflow",onClick:l,children:(0,n.jsx)(w.Icons.close,{size:14})})]})});return"u"<typeof document?x:(0,ti.createPortal)(x,document.body)}let aQ=[{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."}],aJ=["verify","lint","typecheck","tests","manual"];function aX(e){return e.split(/\r?\n|,/).map(e=>e.trim()).filter(e=>e.length>0)}function aZ({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)(a0,{answer:e,modelId:t,launch:s,onClose:()=>{r(!1),o.current?.focus()}}):null]})}function a0({answer:e,modelId:t,launch:l,onClose:s}){let i=(0,a.useId)(),r=(0,a.useRef)(null),[o,c]=(0,a.useState)(),[d,u]=(0,a.useState)("file"),[m,h]=(0,a.useState)(""),[p,f]=(0,a.useState)(""),[g,v]=(0,a.useState)(""),[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 A(){if(void 0===o)return;let n=function(e,t,n,a,l,s){if("unit-test-generation"===e){if("changedFiles"===t){let e=aX(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=aX(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=aX(s);return{ok:!0,input:0===i.length?{}:{targetFiles:i}}}(o,d,m,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:aX(y),expectedChecks:S,unknowns:aX(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=aV(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 T=aQ.find(e=>e.workflowKind===o),M=(0,n.jsx)("div",{ref:r,role:"dialog","aria-modal":"true","aria-labelledby":i,tabIndex:-1,className:"wf-dialog-overlay",children:(0,n.jsxs)("div",{className:"wf-dialog",children:[(0,n.jsx)("h2",{id:i,className:"wf-dialog-title",children:"Grounded workflow handoff"}),void 0===T?(0,n.jsx)("ul",{className:"wf-dialog-list","aria-label":"Available grounded workflows",children:aQ.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:T.description}),"unit-test-generation"===o?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Target mode",(0,n.jsxs)("select",{className:"wf-dialog-input mono",value:d,onChange:e=>u(e.target.value),children:[(0,n.jsx)("option",{value:"file",children:"File"}),(0,n.jsx)("option",{value:"module",children:"Module"}),(0,n.jsx)("option",{value:"changedFiles",children:"Changed files"})]})]}),(0,n.jsxs)("label",{className:"wf-dialog-field",children:["module"===d?"Module directory":"changedFiles"===d?"Changed files (one per line)":"Target file",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:"changedFiles"===d?3:2,value:m,onChange:e=>h(e.target.value),placeholder:"module"===d?"src/components":"changedFiles"===d?"src/a.ts\nsrc/b.ts":"src/example.ts"})]})]}):null,"bug-investigation"===o?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Bug description",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:3,value:p,onChange:e=>f(e.target.value),placeholder:"Describe the failing behavior or regression."})]}),(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Suspected target files (one per line)",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:2,value:g,onChange:e=>v(e.target.value),placeholder:"src/app.ts\\nsrc/lib/foo.ts"})]})]}):null,"verification"===o?(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Target files (optional, one per line)",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:2,value: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:aJ.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:()=>{A()},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?M:(0,ti.createPortal)(M,document.body)}function a1(e){return"system"===e.role&&"string"==typeof e.runId}function a2({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 a3({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 a4=e.i(61593);let a6="cmp-no-model-alert",a5="cmp-send-hint",a8="cmp-loading-status",a7="Ask Keiko about your code…",a9="Send message — Enter to send, Shift+Enter for a new line";function le(e){return t=>{!t.nativeEvent.isComposing&&("Enter"!==t.key||t.shiftKey||(t.preventDefault(),e()))}}let lt=/\s*[[【[]\d+[\]】]]/g;function ln({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(lt,"")).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 la({message:e}){let t,a;if(a1(e))return(0,n.jsx)(a2,{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)(ll,{}),l?e.content:(0,n.jsx)(az,{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)(ln,{content:e.content})]})]})})}function ll({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)(nX.default,{src:"/assets/keiko-logo.svg",width:22,height:22,alt:"","aria-hidden":"true"})})}function ls(){return(0,n.jsx)("article",{className:"chat-msg","data-role":"assistant",children:(0,n.jsxs)("div",{className:"chat-msg-bubble",children:[(0,n.jsx)(ll,{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 li({session:e,ready:t,selectedModelCapability:a,onAttachFiles:l,budgetExceeded:s}){let{models:i,selectedModel:r,setSelectedModel:o,draft:c,noEligibleModels:d,loading:u,sending:m,cancelSend:h,launchWorkflowFromConversation:p}=e,f=d||s||!t,g=0===c.trim().length,v=d?a6:void 0,x=d?a6:s?nZ:u?a8:g?a5: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)(aU,{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)(aG,{selectedModel:a,launch:p}),null,x===a5?(0,n.jsx)("span",{id:a5,className:"sr-only",children:"Type a message to send"}):null,m?(0,n.jsx)("button",{type:"button",className:"cmp-send cmp-send-cancel","data-on":!0,"aria-label":"Cancel response",title:"Cancel response",onClick:h,children:(0,n.jsx)(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":a9,"aria-label":"Send message",children:(0,n.jsx)(w.Icons.arrowUp,{size:16})})]})}function lr(){return(0,n.jsx)("div",{id:a6,role:"alert",className:"gw-error cmp-no-model",children:"No conversation-eligible model is configured. Connect a gateway in Settings to enable chat."})}function lo(){return(0,n.jsxs)("div",{id:a8,role:"status",className:"cmp-loading-status",children:[(0,n.jsx)("span",{className:"cmp-loading-dot","aria-hidden":"true"}),"Connecting to your gateway…"]})}function lc({status:e}){let t=function(e){switch(e){case"idle":case"completed":case"failed":return"";case"queued":return"Submitting your message…";case"contacting":return"Contacting model…";case"streaming":return"Receiving response…";case"cancelled":return"Response cancelled."}}(e);return(0,n.jsx)("div",{role:"status","aria-live":"polite","data-send-status":e,className:"cmp-send-status",children:0===t.length?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"cmp-loading-dot","aria-hidden":"true"}),t]})})}function ld({session:e,ready:t,placeholder:l}){let{draft:s,loading:i,sending:r,sendStatus:o,setDraft:c,sendMessage:d,models:u,selectedModel:m,pendingAttachments:h,addPendingAttachment:p,removePendingAttachment:f,budget:g,clearHistory:v}=e,x=nh(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===m),S=void 0!==N&&(N.supportsImageInput||N.supportsDocumentInput),C=(0,a.useCallback)(async e=>{let t,n;for(let a of e){let e=await p(a);e.ok||void 0!==t||(t=e.reason,n=a.type)}j(t),k(n)},[p]);return(0,n.jsxs)("div",{className:"cmp-box",children:[(0,n.jsx)(a_,{enabled:S,onFiles:C}),(0,n.jsx)(aK,{attachments:h,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:le(d)}),(0,n.jsx)(aW,{reason:y,mimeType:w}),(0,n.jsx)(lc,{status:o}),(0,n.jsx)(n4,{budget:g,onClearHistory:v,disabled:r||i}),(0,n.jsx)(li,{session:e,ready:t,selectedModelCapability:N,onAttachFiles:C,budgetExceeded:x})]})}function lu({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 lm(){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 lh({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:le(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:a9,children:(0,n.jsx)(w.Icons.arrowUp,{size:16})})]}),(0,n.jsx)(lc,{status:i})]})}function lp(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 lf(e){if(lp(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}`:lv(e)?"files":"none"}function lg(e){return void 0!==e.localKnowledgeScopes?e.localKnowledgeScopes:void 0!==e.localKnowledgeScope?[e.localKnowledgeScope]:[]}function lv(e){return void 0!==e&&(void 0!==e.connectedScope||void 0!==e.connectedScopes&&e.connectedScopes.length>0)}function lx(e){return lv(e)||void 0!==e&&(void 0!==e.localKnowledgeScope||void 0!==e.localKnowledgeScopes&&e.localKnowledgeScopes.length>0)}function lb(e){return t0(e,"Unable to update knowledge scope.")}function ly({chat:e,onChatChanged:t,catalog:l,connected:s}){let{capsules:i,capsuleSets:r,loadError:o}=l,[c,d]=(0,a.useState)(!1),[u,m]=(0,a.useState)(null),h=(0,a.useRef)(null);async function p(n){d(!0),m(null);try{if("none"===n){let n=lp(e);if(n>0&&!window.confirm(`This will disconnect ${String(n)} grounding ${1===n?"source":"sources"}. Continue?`)){null!==h.current&&(h.current.value=lf(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=lg(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=lg(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){m(lb(e))}finally{d(!1)}}let f=lf(e),g=function(e,t){let n=t.map(e=>({value:`capsule:${e.id}`,label:`Knowledge capsule: ${e.displayName}`})),a=lf(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=lf(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:h,className:"scope-grounding-select",value:f,disabled:c,"aria-label":"Grounding mode",onChange:e=>{p(e.target.value)},children:[(0,n.jsx)("option",{value:"none",children:"Model only"}),(0,n.jsx)("option",{value:"files",disabled:!lv(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 lj({chat:e,onChatChanged:t}){let l=function(){let[e,t]=(0,a.useState)([]),[n,l]=(0,a.useState)([]),[s,i]=(0,a.useState)(null);return(0,a.useEffect)(()=>{let e=!1;return async function(){try{let[n,a]=await Promise.allSettled([(0,a4.fetchCapsules)(),(0,a4.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(lb(a.reason)))}catch(t){e||i(lb(t))}}(),()=>{e=!0}},[]),{capsules:e,capsuleSets:n,loadError:s}}(),s=lx(e);return(0,n.jsx)("div",{className:"chat-scope-header","data-grounded":s?"true":"false",children:(0,n.jsx)(ly,{chat:e,onChatChanged:t,catalog:l,connected:s})})}function lw({chat:e,answer:t,busy:a,selectedModelId:l,launchGroundedWorkflowHandoff:s}){return void 0!==e&&lx(e)&&(void 0!==t||a)?(0,n.jsxs)("div",{className:"chatw-grounded",children:[(0,n.jsx)(ag,{answer:t,busy:a}),(0,n.jsx)(aZ,{answer:t,modelId:l,busy:a,launch:s})]}):null}function lk({action:e,acceptCandidate:t,rejectCandidate:l,forgetMemoryAction:s,onActionSettled:i}){let[r,o]=(0,a.useState)(!1),[c,d]=(0,a.useState)(),[u,m]=(0,a.useState)(!1),h=(0,a.useCallback)((e,t,n)=>{r||(o(!0),d(void 0),e().then(()=>{i(t)}).catch(e=>{d(e instanceof Error?e.message:n)}).finally(()=>o(!1)))},[r,i]);if("candidate"===e.kind)return(0,n.jsxs)("article",{className:"chat-memory-action",children:[(0,n.jsxs)("div",{className:"chat-memory-action-head",children:[(0,n.jsx)("strong",{children:e.scopeLabel}),(0,n.jsx)("span",{children:e.requiresApproval?"Approval required":"Proposed memory"})]}),(0,n.jsx)("p",{children:e.body}),(0,n.jsxs)("div",{className:"chat-memory-action-buttons",children:[(0,n.jsx)("button",{type:"button","aria-disabled":r,"aria-busy":r,onClick:()=>{h(()=>t(e.proposalId),"MemoriaViva proposal accepted.","Unable to accept memory.")},children:"Accept"}),(0,n.jsx)("button",{type:"button","aria-disabled":r,"aria-busy":r,onClick:()=>{h(()=>l(e.proposalId),"MemoriaViva proposal rejected.","Unable to reject memory.")},children:"Reject"})]}),void 0!==c?(0,n.jsx)(n5,{error:c,fallback:"Unable to update memory.",onDismiss:()=>d(void 0)}):null]});if("update"===e.kind)return(0,n.jsxs)("article",{className:"chat-memory-action",children:[(0,n.jsxs)("div",{className:"chat-memory-action-head",children:[(0,n.jsx)("strong",{children:"MemoriaViva update detected"}),(0,n.jsx)("span",{children:e.memoryId})]}),(0,n.jsx)("p",{children:void 0!==e.bodyPatch?`Suggested update: ${e.bodyPatch}`:"Suggested update."})]});if("forget"===e.kind){let t=()=>{h(()=>s(e.memoryId).then(()=>m(!1)),"MemoriaViva forget action completed.","Unable to forget memory.")};return(0,n.jsxs)("article",{className:"chat-memory-action",children:[(0,n.jsxs)("div",{className:"chat-memory-action-head",children:[(0,n.jsx)("strong",{children:"MemoriaViva forget detected"}),(0,n.jsx)("span",{children:e.requiresConfirmation?"Confirmation required":e.memoryId})]}),(0,n.jsx)("p",{children:`Matched memory ${e.memoryId} for a forget operation.`}),(0,n.jsx)("div",{className:"chat-memory-action-buttons",children:e.requiresConfirmation?u?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button","aria-disabled":r,"aria-busy":r,onClick:t,children:"Forget permanently"}),(0,n.jsx)("button",{type:"button","aria-disabled":r,"aria-busy":r,onClick:()=>{r||(d(void 0),m(!1))},children:"Cancel"})]}):(0,n.jsx)("button",{type:"button","aria-disabled":r,"aria-busy":r,onClick:()=>{r||(d(void 0),m(!0))},children:"Review forget"}):(0,n.jsx)("button",{type:"button","aria-disabled":r,"aria-busy":r,onClick:t,children:"Forget"})}),void 0!==c?(0,n.jsx)(n5,{error:c,fallback:"Unable to update memory.",onDismiss:()=>d(void 0)}):null]})}return"rejected"===e.kind?(0,n.jsxs)("article",{className:"chat-memory-action",children:[(0,n.jsx)("div",{className:"chat-memory-action-head",children:(0,n.jsx)("strong",{children:"Memory proposal declined"})}),(0,n.jsx)("p",{children:""!==e.reason?e.reason:"No reason provided"})]}):(0,n.jsx)("article",{className:"chat-memory-action",children:(0,n.jsx)("div",{className:"chat-memory-action-head",children:(0,n.jsx)("strong",{children:"MemoriaViva action not created"})})})}function lN({memoryEnabled:e,setMemoryEnabled:t,memoryBudgetTokens:l,setMemoryBudgetTokens:s,latestMemory:i,acceptCandidate:r,rejectCandidate:o,forgetMemoryAction:c}){let[d,u]=(0,a.useState)(!1),[m,h]=(0,a.useState)(""),p=(0,a.useId)(),f=`${p}-chat-memory-disclosure`,g=(0,a.useRef)(null),v=(0,a.useCallback)(e=>{h(e),g.current?.focus()},[]),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)(a3,{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)(lk,{action:e,acceptCandidate:r,rejectCandidate:o,forgetMemoryAction:c,onActionSettled:v},"candidate"===e.kind?e.proposalId:"rejected"===e.kind?e.reason:e.memoryId)),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true",children:m})]}):null]})}function lS({mini:e=!1}){let t=i(),{messages:l,draft:s,loading:r,sending:o,sendStatus:c,error:d,noEligibleModels:u,selectedModel:m,sendMessage:h,cancelGrounded:p,activeChat:f,replaceChat:g,latestGrounded:v,latestMemory: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||a1(e)),$=(0,a.useRef)(null),A=(0,a.useRef)(!0),T=(0,a.useRef)(!1),M=R.length>0?R[R.length-1]:void 0,q=void 0===M?"":M.content;return((0,a.useEffect)(()=>{o&&!T.current&&(A.current=!0),T.current=o;let e=$.current;null!==e&&A.current&&(e.scrollTop=e.scrollHeight)},[R.length,o,q]),e)?(0,n.jsxs)("div",{className:"chatw chatw-mini",children:[void 0!==f?(0,n.jsx)(lj,{chat:f,onChatChanged:g}):null,u?(0,n.jsx)(lr,{}):null,(0,n.jsx)(lh,{session:t,ready:E}),void 0!==d?(0,n.jsx)(n5,{error:d,fallback:"Could not send message.",onDismiss:t.clearError}):null]}):(0,n.jsxs)("div",{className:"chatw",children:[void 0!==f?(0,n.jsx)(lj,{chat:f,onChatChanged:g}):null,void 0!==f?(0,n.jsx)(lN,{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)(lr,{})}):null,r?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsx)(lo,{})}):null,(0,n.jsx)("div",{className:"chatw-scroll",ref:$,role:"log","aria-label":"Conversation",tabIndex:0,onScroll:e=>{let t=e.currentTarget;A.current=t.scrollHeight-t.scrollTop-t.clientHeight<64},children:0===R.length?void 0!==f?(0,n.jsx)(lu,{session:t,noEligibleModels:u}):(0,n.jsx)(lm,{}):(0,n.jsxs)("div",{className:"chatw-log",children:[R.map(e=>(0,n.jsx)(la,{message:e},e.id)),o&&"streaming"!==c?(0,n.jsxs)("div",{className:"chatw-typing-row",children:[(0,n.jsx)(ls,{}),lx(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)(lw,{chat:f,answer:v,busy:o,selectedModelId:m,launchGroundedWorkflowHandoff:C}),(0,n.jsx)(aH,{documents:b})]})}),R.length>0?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsxs)("form",{className:"composer",onSubmit:e=>{e.preventDefault(),h()},children:[(0,n.jsx)(ld,{session:t,ready:E,placeholder:a7}),void 0!==d?(0,n.jsx)(n5,{error:d,fallback:"Could not send message.",onDismiss:t.clearError}):null]})}):null,0===R.length&&void 0!==f?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsxs)("form",{className:"composer",onSubmit:e=>{e.preventDefault(),h()},children:[(0,n.jsx)(ld,{session:t,ready:E,placeholder:r?"Connecting to your gateway…":a7}),void 0!==d?(0,n.jsx)(n5,{error:d,fallback:"Could not send message.",onDismiss:t.clearError}):null]})}):null,0===R.length&&void 0!==d&&void 0===f?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsx)(n5,{error:d,fallback:"Could not load chat.",onDismiss:t.clearError})}):null]})}let lC=new Set(["ArrowDown","ArrowUp","ArrowRight","ArrowLeft","Home","End"]);function lI(e){return Array.from(e.querySelectorAll("button[role='treeitem']"))}function lE({project:e,activeProjectPath:t,chats:l,activeChatId:s,onProject:i,onChat:r,treeRef:o}){let c=t===e.path,[d,u]=(0,a.useState)(c),m=e.available?"Available":"Unavailable";return(0,a.useEffect)(()=>{c&&u(!0)},[c]),(0,n.jsxs)("div",{className:"proj",children:[(0,n.jsxs)("button",{className:"proj-head",type:"button",role:"treeitem","aria-level":1,"aria-expanded":d,"aria-selected":c,"data-active":c?"true":"false","aria-current":c?"true":void 0,"aria-label":`${e.name} (${m})`,tabIndex:c?0:-1,onClick:()=>{u(e=>!e),i(e),null!==o.current&&lI(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:m})]}),d&&(0,n.jsx)("div",{className:"proj-chats",role:"group","aria-label":e.name,children:c?0===l.length?(0,n.jsx)("div",{className:"proj-empty",children:"No chats"}):l.map(e=>(0,n.jsxs)("button",{type:"button",role:"treeitem","aria-level":2,"aria-selected":s===e.id,className:"chat-row","data-active":s===e.id,tabIndex:-1,onClick:()=>{r(e)},children:[(0,n.jsx)("span",{className:"chat-title",children:e.title}),void 0!==e.branchLabel?(0,n.jsx)("span",{className:"chat-meta mono",children:e.branchLabel}):null]},e.id)):(0,n.jsx)("div",{className:"proj-empty",children:"Select project to load chats"})})]})}function lR(){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=>{lC.has(e.key)&&null!==t.current&&function(e,t){let n=lI(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)(lE,{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 l$({openChatWindow:e}){let t=i(),[l,s]=(0,a.useState)(""),[r,o]=(0,a.useState)("active"),[c,d]=(0,a.useState)(null),[u,m]=(0,a.useState)(""),[h,p]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),[v,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 A=async()=>{x(null);let n=await t.openNewChat(void 0,"New chat");void 0!==n&&e(n)},T=e=>{d(e.id),m(e.title),p(null),x(null),y(null)},M=async e=>{let n=u.trim();if(0===n.length){y("Title cannot be empty."),k.current?.focus({preventScroll:!0});return}if(n===e.title){d(null),y(null);return}g(e.id),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)}},q=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)}},L=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 A(),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=eU(t).length+eW(t).length,s=c===t.id,i=h===t.id,r=f===t.id,o="closed"===t.status;return(0,n.jsxs)("article",{className:"chat-history-row","data-chat-id":t.id,"data-state":o?"deleted":"active",children:[(0,n.jsx)("div",{className:"chat-history-row-main",children:s?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("input",{ref:k,className:"chat-history-title-input",value:u,"aria-invalid":null!==b,"aria-describedby":null!==b?I:void 0,onChange:e=>{m(e.target.value),null!==b&&y(null)},onKeyDown:e=>{"Enter"===e.key&&M(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 M(t),children:"Save"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",disabled:r,onClick:()=>{d(null),y(null)},children:"Cancel"})]}):i?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-danger",disabled:r,onClick:()=>void q(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 L(t),children:[(0,n.jsx)(w.Icons.restore,{size:14}),"Restore"]}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:()=>T(t),children:"Rename"})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:()=>T(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 lA(){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 lT=[{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}],lM=[{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 lq({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 lL(){let[e,t]=(0,a.useState)(lT.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,"/",lT.length," active"]})]}),lT.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)(lq,{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"})}),lM.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)(lq,{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 lP=[{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",lF=Object.fromEntries(lP.map(e=>[e.id,e.defaultOn]));function lz(){try{let e=localStorage.getItem(lD);if(null===e)return{...lF};let t=JSON.parse(e);if("object"!=typeof t||null===t||Array.isArray(t))return{...lF};let n={...lF};for(let[e,a]of Object.entries(t))e in lF&&"boolean"==typeof a&&(n[e]=a);return n}catch{return{...lF}}}function lO(){let[e,t]=(0,a.useState)(lz);return(0,n.jsx)("div",{className:"tw-list",children:lP.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)(a3,{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 lK(){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 l_(){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:ej[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:ej[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:ej[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:ej[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 lB=[{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 lU(){return(0,n.jsx)("ul",{className:"tw-list",children:lB.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 lW(){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 lH="keiko-activity",lG={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 lV(){let e=function(){let[,e]=(0,a.useState)(0);return(0,a.useEffect)(()=>{let t=()=>{e(e=>e+1)};return window.addEventListener(lH,t),()=>{window.removeEventListener(lH,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:lG[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 lY({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 lQ={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 lJ(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":lQ[a]??"code"}let lX=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 lZ(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 l0(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]??""],...lZ(e.slice(t[0].length))]:lZ(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";lX.has(t)||lX.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 l1(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 l2(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e))}function l3({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 l4({root:e,path:t,onClose:l,onOpenInEditor:s}){let[i,r]=(0,a.useState)(null),[o,c]=(0,a.useState)(!0),[d,u]=(0,a.useState)(null),[m,h]=(0,a.useState)(0),p=(0,a.useRef)(null);(0,a.useEffect)(()=>{p.current?.focus({preventScroll:!0})},[]),(0,a.useEffect)(()=>{let n=!1;return c(!0),u(null),r(null),(0,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,m]);let f=d?.denied===!0,g=null!==i?"text"===i.kind?i.extension??"text":"image"===i.kind?i.mime:i.extension??"binary":f?"denied":null!==d?"error":"loading",v=f?"Hidden file":i?.name??(null!==d?"Preview unavailable":"Loading preview"),x=i?.kind==="text"&&i.content.length<=2e5,b=void 0!==s&&i?.kind==="text"&&!i.truncated,y=i?.kind==="text"?x?l0(i.content,lJ(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)(lY,{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:()=>h(e=>e+1),children:"Retry"})]}):null,i?.kind==="text"?(0,n.jsxs)(n.Fragment,{children:[i.truncated?(0,n.jsxs)("div",{className:"fpv-banner",children:["Preview truncated at ",l1(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)(l3,{label:"Type",value:i.mime}),(0,n.jsx)(l3,{label:"Size",value:l1(i.sizeBytes)}),(0,n.jsx)(l3,{label:"Modified",value:l2(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)(lY,{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 ${l1(i.maxBytes??0)}.`:"docx"===function(e){let t=e.extension?.trim().toLowerCase();if(void 0!==t&&t.length>0)return t;let n=e.name.lastIndexOf(".");return n>=0?e.name.slice(n+1).trim().toLowerCase():""}(i)?"DOCX is not searchable in Repository Search yet. Add it to Local Knowledge, or enable small-document repository extraction when available.":"No safe text or image preview is available for this file type."}),(0,n.jsxs)("div",{className:"fpv-meta",children:[(0,n.jsx)(l3,{label:"Type",value:i.mime}),(0,n.jsx)(l3,{label:"Extension",value:i.extension??"none"}),(0,n.jsx)(l3,{label:"Size",value:l1(i.sizeBytes)}),(0,n.jsx)(l3,{label:"Modified",value:l2(i.modifiedAt)})]})]})}):null]})}function l6(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 l5(e){return 8+18*e}let l8=new Set(["ArrowDown","ArrowUp","ArrowRight","ArrowLeft","Home","End"]);function l7({root:e,onActiveFileChange:t,onRootChange:l,onOpenFile:s}){let i=e?.trim(),r=void 0!==i&&i.length>0?i:null,[o,c]=(0,a.useState)(null),d=r??o??"",[u,m]=(0,a.useState)(null),[h,p]=(0,a.useState)(""),[f,g]=(0,a.useState)(null),[v,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 A=(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&&(m(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),m(null),N(new Set([""])),y({}),A("")},[d,A,S]);let T=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(T)},[T]);let M=(0,a.useCallback)(e=>{let t=e.trim();void 0===l||0===t.length||t!==T&&l(t)},[l,T]),q=(0,a.useCallback)(e=>{g(null),x(e),I.current?.(null,u??d,e),null!==e&&void 0===b[e]&&A(e)},[d,b,A,u]),L=(0,a.useCallback)(()=>{if(null!==v)return void q(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=l6(u??d);null!==e&&M(e)},[d,v,q,M,u]),P=(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:l5(t)+18},children:"Loading…"}):null,a?.notice==="no-root"?(0,n.jsx)("div",{className:"files-note",role:"status",style:{paddingLeft:l5(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:l5(t)},children:[(0,n.jsx)("span",{children:a.error}),(0,n.jsx)("button",{type:"button",className:"files-retry",onClick:()=>{A(e)},children:"Retry"})]}):null,a?.truncated===!0?(0,n.jsxs)("div",{className:"files-note files-warning",role:"status",style:{paddingLeft:l5(t)+18},children:["Showing only the first ",a.entries.length," entries — this folder contains more."]}):null,a?.entries.map(e=>((e,t)=>{let a=l5(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]||A(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&&q(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?P(e.path,t+1,i):null]},e.path)}return(0,n.jsxs)("button",{className:"tr-row tr-file",role:"treeitem","aria-level":t+1,"aria-selected":f===e.path,"data-active":f===e.path,"data-readable":e.readable,"data-path":e.path,style:{paddingLeft:a},type:"button","aria-disabled":!e.readable||void 0,"aria-describedby":e.readable?void 0:$,onClick:()=>{e.readable&&(g(e.path),I.current?.(e.path,u??d))},title:e.readable?e.path:s,children:[(0,n.jsx)("span",{className:"tr-caret tr-caret-ghost","aria-hidden":"true",children:(0,n.jsx)(w.Icons.chevronR,{size:11})}),(0,n.jsx)(lY,{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:l5(t)+18},children:"Empty folder."})]});return null!==f?(0,n.jsx)(l4,{root:u??d,path:f,onOpenInEditor:s,onClose:()=>{R.current=f,g(null),I.current?.(null,u??d)}}):(0,n.jsxs)("div",{className:"files",ref:E,tabIndex:-1,children:[void 0!==l?(0,n.jsxs)("form",{className:"files-root-bar",role:"group","aria-label":"Folder root",onSubmit:e=>{e.preventDefault(),M(h)},children:[(0,n.jsx)("button",{type:"button",className:"files-root-up",onClick:L,disabled:null===v&&null===l6(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:h,onChange:e=>p(e.target.value)}),(0,n.jsx)("button",{type:"submit",className:"files-root-open",title:"Open this folder",children:"Open"})]}):null,(0,n.jsx)("button",{className:"files-refresh",type:"button",onClick:()=>C(e=>e+1),title:"Refresh folder","aria-label":"Refresh folder",children:(0,n.jsx)(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(!l8.has(e.key))return;let t=e.target,n=t instanceof HTMLElement?t.closest("button.tr-row"):null;if(null===n)return;let a=Array.from(e.currentTarget.querySelectorAll("button.tr-row")),l=a.indexOf(n);l<0||(e.preventDefault(),function(e,t,n){let a=e[t];if(void 0===a)return;let l=a.closest(".tr-row-wrap")?.querySelector("button.tr-caret-btn");if("ArrowDown"===n)e[t+1]?.focus();else if("ArrowUp"===n)e[t-1]?.focus();else if("Home"===n)e[0]?.focus();else if("End"===n)e[e.length-1]?.focus();else if("ArrowRight"===n){let n=a.getAttribute("aria-expanded");"false"===n?l?.click():"true"===n&&e[t+1]?.focus()}else"ArrowLeft"===n&&("true"===a.getAttribute("aria-expanded")?l?.click():function(e,t){let n=Number(e[t]?.getAttribute("aria-level")??"1");for(let a=t-1;a>=0;a-=1)if(Number(e[a]?.getAttribute("aria-level")??"1")<n)return void e[a]?.focus()}(e,t))}(a,l,e.key))},children:P(v??"",0)})]})}function l9(e){return e instanceof j.ApiError||e instanceof Error?e.message:"The file could not be loaded."}function se(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e))}function st({root:e,file:t}){let[l,s]=(0,a.useState)(""),[i,r]=(0,a.useState)(""),[o,c]=(0,a.useState)(null),[d,u]=(0,a.useState)(null),[m,h]=(0,a.useState)(void 0!==e&&void 0!==t),[p,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(null),[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),h(!1),f(!1),v(null),b(null);return}let n=!1;return h(!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(l9(e))}).finally(()=>{n||h(!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 ${se(n.modifiedAt)}`)}catch(e){v(l9(e))}finally{f(!1)}}},S=(0,a.useMemo)(()=>y?m?"Loading file…":p?"Saving…":null!==g?g:null!==x?x:k?"Unsaved changes":null!==o?`Saved ${se(o)}`:"Ready":"Open a file from the Files window to start editing.",[k,g,y,m,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||m||p,children:"Save"}):null]}),(0,n.jsxs)("div",{className:"ed-meta",children:[(0,n.jsx)("span",{className:"ed-status",role:null!==g?"alert":"status",children:S}),null!==d?(0,n.jsxs)("span",{className:"ed-limit mono",children:["Limit ",d.toLocaleString()," B"]}):null]}),y?(0,n.jsx)("textarea",{className:"ed-textarea mono","aria-label":void 0!==t?`Editor: ${t}`:"Editor",value:l,onChange:e=>{s(e.target.value),null!==x&&b(null)},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"s"===e.key.toLowerCase()&&(e.preventDefault(),N())},disabled:m||p||null!==g,spellCheck:!1}):(0,n.jsxs)("div",{className:"ed-empty",role:"note",children:["Choose a file from the Files window and use ",(0,n.jsx)("strong",{children:"Open in editor"}),"."]})]})}async function sn(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 sa(e){return sn(`/api/browser/status?port=${encodeURIComponent(String(e))}`)}async function sl(e){return sn("/api/browser/sessions",{method:"POST",body:JSON.stringify({port:e})})}async function ss(e){await sn(`/api/browser/sessions/${encodeURIComponent(e)}`,{method:"DELETE"})}async function si(e,t){return sn(`/api/browser/sessions/${encodeURIComponent(e)}/navigate`,{method:"POST",body:JSON.stringify({url:t})})}async function sr(e){return sn(`/api/browser/sessions/${encodeURIComponent(e)}/screenshot`,{method:"POST",body:JSON.stringify({})})}async function so(e,t){return sn(`/api/browser/sessions/${encodeURIComponent(e)}/apply`,{method:"POST",body:JSON.stringify({captureSeq:t})})}async function sc(e){return sn(`/api/browser/sessions/${encodeURIComponent(e)}/content`,{method:"POST",body:JSON.stringify({})})}function sd(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 su(e){let t=e.cdpPort??9222,l=e.url??"http://localhost:5173",[s,i]=(0,a.useState)(String(t)),[r,o]=(0,a.useState)(l),[c,d]=(0,a.useState)(null),[u,m]=(0,a.useState)(null),[h,p]=(0,a.useState)(!1),[f,g]=(0,a.useState)(null),[v,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 sa(e);m(t)}catch(e){x(sd(e))}finally{p(!1)}},[s,E]),A=(0,a.useCallback)(async()=>{E(),p(!0);try{let e=Number.parseInt(s,10),t=await sl(e);d(t),y([]),N(null),C(null)}catch(e){x(sd(e))}finally{p(!1)}},[s,E]),T=(0,a.useCallback)(async()=>{if(null!==c){E(),p(!0);try{await ss(c.sessionId),d(null),w(null),N(null),C(null)}catch(e){x(sd(e))}finally{p(!1)}}},[c,E]),M=(0,a.useCallback)(async()=>{if(null!==c){E(),p(!0);try{let e=await si(c.sessionId,r);C(e.originOnly)}catch(e){x(sd(e))}finally{p(!1)}}},[c,r,E]),q=(0,a.useCallback)(async()=>{if(null!==c){E(),p(!0);try{let e=await sr(c.sessionId);e.persisted||w({seq:e.seq,dataBase64:e.dataBase64})}catch(e){x(sd(e))}finally{p(!1)}}},[c,E]),L=(0,a.useCallback)(async()=>{if(null!==c&&null!==j){E(),p(!0);try{let e=await so(c.sessionId,j.seq);e.persisted&&N(e.path),w(null)}catch(e){x(sd(e))}finally{p(!1)}}},[c,j,E]),P=(0,a.useCallback)(async()=>{if(null!==c){E(),p(!0);try{await sc(c.sessionId)}catch(e){x(sd(e))}finally{p(!1)}}},[c,E]),D=(0,a.useMemo)(()=>h||null!==c,[h,c]),F=(0,a.useMemo)(()=>h||null===c,[h,c]),z=h||null!==c,O=h||null===j,K=h&&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||h})]}),(0,n.jsxs)("label",{className:"bw-field bw-field-url",children:[(0,n.jsx)("span",{className:"bw-field-label",children:"URL"}),(0,n.jsx)("input",{type:"url",className:"bw-input bw-input-url",value:r,onChange:e=>o(e.target.value),disabled:h})]})]}),(0,n.jsxs)("div",{className:"bw-actions",role:"group","aria-label":"Browser actions",children:[(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{z||(g("Checking Chrome…"),$())},"aria-disabled":z,children:"Check"}),(0,n.jsx)("button",{type:"button",className:"bw-btn bw-btn-primary",onClick:()=>{D||(g("Opening session…"),A())},"aria-disabled":D,children:"Open session"}),(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{F||(g("Navigating…"),M())},"aria-disabled":F,children:"Navigate"}),(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{F||(g("Capturing screenshot…"),q())},"aria-disabled":F,children:"Screenshot"}),(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{O||(g("Applying screenshot…"),L())},"aria-disabled":O,children:"Apply"}),(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{F||(g("Capturing HTML…"),P())},"aria-disabled":F,children:"Capture HTML"}),(0,n.jsx)("button",{type:"button",className:"bw-btn bw-btn-danger",onClick:()=>{F||(g("Closing session…"),T())},"aria-disabled":F,children:"Close"})]}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:K}),h&&null!==f?(0,n.jsx)("p",{className:"bw-status",children:f}):null,null!==u&&null===c?(0,n.jsxs)("p",{className:"bw-status",children:["Reachable: ",u.reachable?"yes":"no",null===u.browserVersion?"":` — ${u.browserVersion}`]}):null,null!==S?(0,n.jsxs)("p",{className:"bw-status",children:["Current origin: ",(0,n.jsx)("span",{className:"mono",children:S})]}):null,null!==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 sm(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 sh(){return sm("/api/terminal/policy")}async function sp(e,t){let n=new URLSearchParams;return n.set("projectId",e),void 0!==t&&t.length>0&&n.set("path",t),sm(`/api/terminal/directories?${n.toString()}`)}async function sf(e){return sm("/api/terminal/executions",{method:"POST",body:JSON.stringify(e)})}async function sg(e){await sm(`/api/terminal/executions/${encodeURIComponent(e)}`,{method:"DELETE"})}function sv(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 sx(e){let[t,l]=(0,a.useState)(null),[s,i]=(0,a.useState)(""),[r,o]=(0,a.useState)(""),[c,d]=(0,a.useState)(e.cwd??""),[u,m]=(0,a.useState)(e.projectPath??""),[h,p]=(0,a.useState)(!1),[f,g]=(0,a.useState)(null),[v,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 sh().then(t=>{e||(l(t),i(e=>e.length>0?e:t.commands[0]??""))}).catch(t=>{e||y(sv(t))}),()=>{e=!0}},[]),(0,a.useEffect)(()=>{if(0===u.length)return void I([]);let e=!1;return sp(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(),h)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 sf(e);x(t)}catch(e){y(sv(e))}finally{N.current=!1,p(!1),S.current=null,g(null)}},[r,s,c,u,h]),R=(0,a.useCallback)(async()=>{if(null!==f)try{await sg(f)}catch(e){y(sv(e))}},[f]),$=(0,a.useMemo)(()=>t?.limits??null,[t]),A=(0,a.useRef)(null),T=(0,a.useRef)(!1);return(0,a.useEffect)(()=>{T.current&&!h&&document.activeElement===document.body&&A.current?.focus(),T.current=h},[h]),(0,n.jsxs)("div",{className:"terminal",children:[(0,n.jsxs)("form",{className:"tm-form",onSubmit:e=>void E(e),children:[(0,n.jsxs)("label",{className:"tm-field",children:[(0,n.jsx)("span",{children:"Project path"}),(0,n.jsx)("input",{type:"text",value:u,onChange:e=>m(e.target.value),placeholder:"/absolute/path/to/project",required:!0})]}),(0,n.jsxs)("label",{className:"tm-field",children:[(0,n.jsx)("span",{children:"Command"}),(0,n.jsx)("select",{value:s,onChange:e=>i(e.target.value),disabled:null===t,required:!0,children:t?.commands.map(e=>(0,n.jsx)("option",{value:e,children:e},e))})]}),(0,n.jsxs)("label",{className:"tm-field",children:[(0,n.jsx)("span",{children:"Args (space-separated)"}),(0,n.jsx)("input",{type:"text",value:r,onChange:e=>o(e.target.value),placeholder:"e.g. -la src"})]}),(0,n.jsxs)("label",{className:"tm-field",children:[(0,n.jsx)("span",{children:"Working directory (optional)"}),(0,n.jsx)("input",{type:"text",value:c,onChange:e=>d(e.target.value),placeholder:"(project root)",list:"tm-cwd-suggestions"}),(0,n.jsx)("datalist",{id:"tm-cwd-suggestions",children:C.map(e=>(0,n.jsx)("option",{value:e.path},e.path))})]}),(0,n.jsxs)("div",{className:"tm-actions",children:[(0,n.jsx)("button",{type:"submit",className:"tm-action","data-primary":"true",ref:A,disabled:null===t,"aria-disabled":h||null===t,children:h?"Running…":"Run"}),h?(0,n.jsx)("button",{type:"button",className:"tm-action","aria-disabled":null===f,onClick:()=>void R(),children:"Cancel"}):null]}),null!==$?(0,n.jsxs)("p",{className:"tm-limits",children:["Limits: ",(0,n8.formatBytes)($.maxOutputBytes)," output ·"," ",(0,n8.formatMs)($.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 sb(e){return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function sy(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 sj(e){return("dry-run"===e.status||"fix-proposed"===e.status)&&void 0!==e.proposedDiff&&void 0===e.appliedAt}function sw(e){return void 0!==e.proposedDiff&&""!==e.proposedDiff}function sk({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 sN({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 sS({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=l0(e.text,lJ(t))[0]??[];a=(0,n.jsx)(sN,{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 sC({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)(sS,{line:e,lang:t},a))]})}function sI({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)(sC,{hunk:e,lang:i},t))})]})}function sE({runId:e,onRunIdSubmit:t}){let[l,s]=(0,a.useState)(null),[i,r]=(0,a.useState)(!1),[o,c]=(0,a.useState)(null),[d,u]=(0,a.useState)(!1),[m,h]=(0,a.useState)(null),[p,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(null),[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),h(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=sy(n.reason);r(!1),c("NOT_FOUND"===e.code?null:e)}if("fulfilled"===e.status){s(e.value.report),u(!1);return}h(sy(e.reason)),u(!1)}}),()=>{t=!0}},[e]);let C=`/api/evidence/${encodeURIComponent(e??"")}`,I=(0,a.useMemo)(()=>l?.proposedDiff!==void 0?function(e){let t=new TextEncoder,n=t.encode(e).byteLength;if(0===e.length)return{files:[],truncated:!1,totalBytes:0};let a=e,l=!1;if(n>524288){l=!0;let n=t.encode(e),s=new TextDecoder().decode(n.slice(0,524288)),i=s.lastIndexOf("\n");a=-1===i?s:s.slice(0,i+1)}let s=a.split("\n"),i=s.length>0&&""===s[s.length-1]?s.slice(0,-1):s,r=[],o=null,c=null,d=0,u=0,m=()=>{null!==o&&null!==c&&o.hunks.push(c),c=null},h=()=>{m(),null!==o&&(r.length<400?r.push(o):l=!0),o=null},p=0;for(;p<i.length;){let e=i[p]??"";if(e.startsWith("diff --git ")){h();let t=/^diff --git a\/(.+?) b\/(.+)$/.exec(e);if(null!==t&&void 0!==t[1]&&void 0!==t[2]){let e=t[1],n=t[2],a=sb(`b/${n}`),l=sb(`a/${e}`),s={path:a,hunks:[],addedLines:0,removedLines:0};l!==a&&(s.oldPath=l),o=s}p++;continue}if(null!==c){if(e.startsWith("+")){let t={kind:"add",oldLine:null,newLine:u,text:e.slice(1)};c.lines.push(t),null!==o&&o.addedLines++,u++,p++;continue}if(e.startsWith("-")){let t={kind:"del",oldLine:d,newLine:null,text:e.slice(1)};c.lines.push(t),null!==o&&o.removedLines++,d++,p++;continue}if(e.startsWith("\\ ")){let t={kind:"meta",oldLine:null,newLine:null,text:e};c.lines.push(t),p++;continue}if(e.startsWith(" ")||""===e){let t={kind:"ctx",oldLine:d,newLine:u,text:e.startsWith(" ")?e.slice(1):e};c.lines.push(t),d++,u++,p++;continue}}if(e.startsWith("--- ")){let t=e.slice(4);if("/dev/null"!==t&&null===o)h(),o={path:sb(t),hunks:[],addedLines:0,removedLines:0};else if("/dev/null"!==t&&null!==o){let e=sb(t);e!==o.path&&(o.oldPath=e)}p++;continue}if(e.startsWith("+++ ")){let t=e.slice(4);"/dev/null"!==t&&null!==o?o.path=sb(t):"/dev/null"!==t&&(h(),o={path:sb(t),hunks:[],addedLines:0,removedLines:0}),p++;continue}if(e.startsWith("@@ ")){null===o&&(o={path:"(unknown)",hunks:[],addedLines:0,removedLines:0}),m();let t=function(e){let t=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(e);return null===t||void 0===t[1]||void 0===t[2]?null:{oldStart:parseInt(t[1],10),newStart:parseInt(t[2],10)}}(e);d=t?.oldStart??1,u=t?.newStart??1,c={header:e,lines:[]},p++;continue}p++}return h(),{files:r,truncated:l,totalBytes:n}}(l.proposedDiff):null,[l?.proposedDiff]),E=l?.changedFiles??[],R=(0,a.useMemo)(()=>({added:I?.files.reduce((e,t)=>e+t.addedLines,0)??0,removed:I?.files.reduce((e,t)=>e+t.removedLines,0)??0}),[I]),$=null!==I&&I.files.length>0?Math.min(x??0,I.files.length-1):null,A=null!==$?I?.files[$]:void 0,T=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!==m&&(0,n.jsxs)("div",{role:"alert",className:"rv-error",children:["NOT_FOUND"===m.code?"No run with that ID was found.":(0,n.jsxs)(n.Fragment,{children:[m.message," ",(0,n.jsxs)("span",{className:"err-code mono",children:["(",m.code,")"]})]}),(i||null!==o)&&(0,n.jsx)("span",{className:"rv-error-evidence",children:(0,n.jsx)(sk,{href:C,hasManifest:i,error:o})})]}),(0,n.jsx)("p",{role:"status","aria-live":"polite",className:!d&&null===m&&null!==l&&T?"rv-no-diff":"sr-only",children:!d&&null===m&&null!==l&&T?"Run is still running. The proposed diff will appear when the run completes.":""}),!d&&null===m&&null!==l&&!T&&!sw(l)&&(0,n.jsx)("p",{className:"rv-no-diff",children:"This run has no proposed diff to review."}),!d&&null===m&&null!==l&&sw(l)&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"rv-header",children:[(0,n.jsx)("span",{className:"rv-status mono",children:(0,n8.runStatusLabel)(l.status)}),void 0!==l.modelId&&(0,n.jsx)("span",{className:"rv-model mono",children:l.modelId}),(0,n.jsxs)("span",{className:"rv-counts mono",children:[null!==I&&`${I.files.length} file${1!==I.files.length?"s":""}`," ",(0,n.jsxs)("span",{className:"rv-stat add",children:["+",R.added]})," ",(0,n.jsxs)("span",{className:"rv-stat del",children:["−",R.removed]})]}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsx)(sk,{href:C,hasManifest:i,error:o})]}),null!==I&&I.files.length>0&&null!==$&&void 0!==A&&(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)(sI,{file:A,index:$,changedFiles:E,sectionRef:()=>void 0},A.path),I.truncated&&(0,n.jsxs)("p",{role:"note",className:"rv-truncated",children:["Diff truncated at 512 KB. Open the"," ",i?(0,n.jsx)("a",{href:C,target:"_blank",rel:"noopener noreferrer",children:"evidence manifest"}):"evidence manifest"," ","for the full record."]})]})]}),(0,n.jsxs)("div",{className:"rv-controls",children:[(0,n.jsx)("span",{role:"status","aria-live":"polite",className:"rv-apply-status",children:p?"Applying…":void 0!==l.appliedAt?"Applied":""}),null!==g&&(0,n.jsx)("span",{role:"alert",className:"rv-apply-error",children:g.message}),void 0!==l.appliedAt?(0,n.jsx)("span",{className:"rv-final mono",children:"Applied"}):sj(l)?(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":p,onClick:()=>{if(!p){if(!k){N(!0),null!==S.current&&window.clearTimeout(S.current),S.current=window.setTimeout(()=>{N(!1),S.current=null},6e3);return}null!==S.current&&(window.clearTimeout(S.current),S.current=null),N(!1),void 0!==e&&null!==l&&sj(l)&&!p&&(f(!0),v(null),(0,j.applyRun)(e).then(e=>{s(e.report),f(!1)}).catch(e=>{v(sy(e)),f(!1)}))}},children:p?"Applying…":k?`Confirm apply (${(I?.files.length??0).toString()} file${I?.files.length===1?"":"s"})`:"Apply"}):null]})]})]})}let sR=["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"],s$=new Set(["run:completed","run:cancelled","run:failed","workflow:completed","workflow:failed","bug:completed","bug:failed"]),sA=new Set(["completed","dry-run","rejected","cancelled","failed","fix-applied","fix-proposed","investigation-only"]),sT={verify:"Verify","explain-plan":"Explain plan","unit-test-generation":"Generate unit tests","bug-investigation":"Investigate bug"};function sM(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 sq({cfg:e={},linkedRoot:t=null,linkedFilePath:l}){var s,i;let r,o=e.runId??null,c="verify"===(s=e.workflow)||"explain-plan"===s||"unit-test-generation"===s||"bug-investigation"===s?s:null,d=e.model??"",u=function(e){if(void 0===e||0===e.length)return null;try{let t=JSON.parse(e);return"object"!=typeof t||null===t||Array.isArray(t)?null:t}catch{return null}}(e.inputJson),m=function(e){let[t,n]=(0,a.useState)([]),[l,s]=(0,a.useState)("connecting"),[i,r]=(0,a.useState)(null),o=(0,a.useRef)(-1);return(0,a.useEffect)(()=>{if(null===e)return;n([]),s("connecting"),r(null),o.current=-1;let t=null,a=!1,l=`/api/runs/${encodeURIComponent(e)}/events`;(t=new EventSource(o.current>=0?`${l}?lastEventId=${o.current.toString()}`:l)).onopen=()=>{a||(s("live"),r(null))},t.onerror=()=>{a||(s("error"),r("Stream disconnected. Attempting to reconnect…"))};let i=e=>{let l;if(!a){try{l=JSON.parse(e.data)}catch{return}o.current=l.seq,n(e=>[...e,l]),s$.has(l.type)&&(s("terminal"),t?.close())}};for(let e of sR)t.addEventListener(e,i);return()=>{a=!0,t?.close()}},[e]),{events:t,status:l,error:i}}(o),[h,p]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),[v,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),A=(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)(()=>{A()},[A]),(0,a.useEffect)(()=>{"terminal"===m.status&&A()},[A,m.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 T=(0,a.useMemo)(()=>(function(e,t){let n=t?.usage?.promptTokens??0,a=t?.usage?.completionTokens??0,l=t?.usage?.latencyMs??0,s=+(t?.usage!==void 0);if(s>0)return{promptTokens:n,completionTokens:a,latencyMs:l,requestCount:s};for(let t of e){let e=function(e){if("model:call:completed"===e.type)return{promptTokens:e.usage.promptTokens,completionTokens:e.usage.completionTokens,latencyMs:e.usage.latencyMs,requestCount:1};let t=e.promptTokens,n=e.completionTokens,a=e.latencyMs;return"number"==typeof t&&"number"==typeof n&&"number"==typeof a?{promptTokens:t,completionTokens:n,latencyMs:a,requestCount:1}:null}(t);null!==e&&(n+=e.promptTokens,a+=e.completionTokens,l+=e.latencyMs,s+=e.requestCount)}return{promptTokens:n,completionTokens:a,latencyMs:l,requestCount:s}})(m.events,h),[m.events,h]),M=h?.durationMs??f?.run.durationMs??(m.events.length>0?Math.max(0,Date.now()-Number(new Date(m.events[0]?.ts??Date.now()))):0),q=null!==h?h.status:null!==f?f.run.outcome:"loading",L=null!==h?(0,n8.runStatusLabel)(h.status):null!==f?(0,n8.outcomeLabel)(f.run.outcome):"Loading…",P=null!==h&&sA.has(h.status),D=null!==h&&void 0!==h.proposedDiff&&void 0===h.appliedAt&&("unit-test-generation"===c&&"dry-run"===h.status||"bug-investigation"===c&&"fix-proposed"===h.status),F=!P&&h?.status==="running",z=function(e){if(void 0===e||0===e.length)return 0;let t=e.match(/^diff --git /gm);if(null!==t)return t.length;let n=e.match(/^\+\+\+ /gm);return null===n?0:n.length}(h?.proposedDiff),O=(0,a.useRef)(!1);(0,a.useEffect)(()=>{O.current&&!F&&document.activeElement===document.body&&$.current?.focus(),O.current=F},[F]),(0,a.useEffect)(()=>()=>{null!==R.current&&window.clearTimeout(R.current)},[]);let K=async()=>{if(null!==o){x(null);try{await (0,j.cancelRun)(o),await A()}catch(e){x(e instanceof Error?e.message:"Unable to cancel run.")}}},_=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:sT[c]}),d.length>0?(0,n.jsx)("span",{className:"ag-model mono",children:d}):null,null!==S?(0,n.jsx)("span",{className:"arun-gov",title:"Model cost class",children:(0,n8.costClassLabel)(S)}):null,(0,n.jsx)("span",{className:"spacer"}),(0,n.jsxs)("span",{className:"arun-status",children:[(0,n.jsx)("span",{className:"dot","data-live":h?.status==="running","data-status":q}),L]})]}),(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":sT[e];return t?.status==="running"?`${a} is running.`:t?.status==="dry-run"?`${a} produced a reviewable dry-run.`:t?.status==="fix-proposed"?`${a} proposed a fix.`:t?.status==="fix-applied"?`${a} applied changes.`:t?.status==="investigation-only"?`${a} completed without a patch.`:t?.status==="failed"||t?.status==="rejected"?`${a} failed.`:t?.status==="cancelled"?`${a} was cancelled.`:null!==t?`${a} completed.`:`${a} evidence loaded: ${n?.run.outcome??"unknown"}.`}(c,h,f)}),(0,n.jsxs)("span",{className:"mono",title:o,children:["run ",o.slice(0,8)]})]}),(0,n.jsxs)("div",{className:"arun-meters",children:[(0,n.jsxs)("div",{className:"arun-meter",children:[(0,n.jsx)("span",{className:"arun-mk",children:"Elapsed"}),(0,n.jsx)("span",{className:"arun-mv mono",children:(0,n8.formatMs)(M)})]}),(0,n.jsxs)("div",{className:"arun-meter",children:[(0,n.jsx)("span",{className:"arun-mk",children:"Usage"}),(0,n.jsx)("span",{className:"arun-mv mono",children:0===T.requestCount?"No model usage":`${(0,n8.formatTokens)(T.promptTokens+T.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===T.requestCount?"—":(0,n8.formatMs)(T.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"===m.status&&null!==m.error?(0,n.jsxs)("div",{className:"arun-log-row",children:[(0,n.jsx)("span",{className:"arun-log-ico",children:(0,n.jsx)(w.Icons.reset,{size:12})}),(0,n.jsx)("span",{className:"arun-log-text",children:m.error})]}):null,0===m.events.length?"error"===m.status?null:(0,n.jsxs)("div",{className:"arun-log-row",children:[(0,n.jsx)("span",{className:"arun-log-ico",children:(0,n.jsx)(w.Icons.reset,{size:12})}),(0,n.jsx)("span",{className:"arun-log-text",children:"connecting"===m.status?"Connecting to run events…":"Waiting for run events…"})]}):m.events.slice().reverse().slice(0,50).map(e=>{let t;return(0,n.jsxs)("div",{className:"arun-log-row",children:[(0,n.jsx)("span",{className:"arun-log-ico",children:(0,n.jsx)(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 (${(0,n8.formatBytes)(e.contextBytes)})`;case"model:call:completed":return`Model call completed (${(0,n8.formatTokens)(e.usage.promptTokens+e.usage.completionTokens)} tokens)`;case"model:call:failed":return`Model call failed: ${e.message}`;case"patch:proposed":return`Patch proposed (${(0,n8.formatBytes)(e.patchBytes)})`;case"verification:result":return`Verification ${e.passed?"passed":"failed"}: ${e.detail}`;case"workflow:started":return"Unit-test workflow started";case"workflow:model:call:completed":return`Unit-test model call completed (${(0,n8.formatTokens)(e.promptTokens+e.completionTokens)} tokens)`;case"workflow:verification:result":return`Unit-test verification ${e.overallStatus}`;case"workflow:completed":return`Unit-test workflow ${e.status}`;case"workflow:failed":return`Unit-test workflow failed: ${e.message}`;case"bug:started":return"Bug investigation started";case"bug:model:call:completed":return`Bug model call completed (${(0,n8.formatTokens)(e.promptTokens+e.completionTokens)} tokens)`;case"bug:rootcause:proposed":return`Root cause proposed${e.hasPatch?" with patch":""}`;case"bug:verification:result":return`Bug verification ${e.overallStatus}`;case"bug:completed":return`Bug investigation ${e.status}`;case"bug:failed":return`Bug investigation failed: ${e.message}`;default:return e.type}}(e)}),(0,n.jsx)("span",{className:"arun-log-t mono",children:Number.isFinite(t="number"==typeof e.ts?e.ts:Date.parse(e.ts))?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):""})]},`${e.runId}:${e.seq}:${e.type}`)})]}),null!==h?(0,n.jsxs)("div",{className:"arun-results",children:[void 0===h.report?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Report"}),(0,n.jsx)("pre",{children:h.report})]}),void 0===h.overallStatus||void 0===h.results?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Verification"}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Status"}),(0,n.jsx)("strong",{children:h.overallStatus})]}),h.results.slice(0,8).map(e=>(0,n.jsxs)("div",{className:"arun-check-row",children:[(0,n.jsx)("span",{children:e.kind}),(0,n.jsx)("span",{className:"mono",children:e.status})]},`${e.kind}:${e.command}`))]}),sM("Failure",h.failureReason),sM("Covered behavior",h.coveredBehavior),sM("Known gaps",h.knownGaps),sM("Verification note",h.verificationSkipReason),function(e){let t=e.hypothesis;if(void 0===t)return null;let a=[["Root cause",t.rootCause],["Regression test",t.regressionTestStrategy],["Uncertainty",t.uncertainty],["Confidence",t.confidence]].filter(e=>"string"==typeof e[1]&&e[1].length>0);return 0===a.length?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Hypothesis"}),a.map(([e,t])=>(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:e}),(0,n.jsx)("strong",{children:t})]},e))]})}(h),void 0===(i=h.nextActions)||0===i.length?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Next actions"}),i.map(e=>(0,n.jsx)("div",{className:"arun-check-row",children:(0,n.jsx)("span",{children:e})},e))]}),void 0!==h.dryRunPreview?(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Dry-run preview"}),(0,n.jsx)("pre",{children:h.dryRunPreview})]}):null,void 0!==h.proposedDiff?(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Proposed diff"}),(0,n.jsx)("pre",{children:h.proposedDiff})]}):null,void 0===(r=h.verificationSummary)?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Verification"}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Status"}),(0,n.jsx)("strong",{children:r.overallStatus})]}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Duration"}),(0,n.jsx)("strong",{children:(0,n8.formatMs)(r.durationMs)})]}),r.results.slice(0,5).map(e=>(0,n.jsxs)("div",{className:"arun-check-row",children:[(0,n.jsx)("span",{children:e.kind}),(0,n.jsx)("span",{className:"mono",children:e.status})]},`${e.kind}:${e.command}`))]}),void 0!==h.applyReport?(0,n.jsxs)("div",{className:"arun-result-card arun-applied",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Applied"}),(0,n.jsx)("pre",{children:JSON.stringify(h.applyReport,null,2)})]}):null]}):null!==f?(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Evidence"}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Outcome"}),(0,n.jsx)("strong",{children:f.run.outcome})]}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Duration"}),(0,n.jsx)("strong",{children:(0,n8.formatMs)(f.run.durationMs)})]})]}):null,null!==v?(0,n.jsx)("div",{className:"arun-error",role:"alert",children:v}):null,null!==k?(0,n.jsx)("div",{className:"arun-error",role:"alert",children:k}):null,(0,n.jsxs)("div",{className:"arun-controls",children:[(0,n.jsx)("a",{className:"arun-btn ghost",href:`/api/evidence/${encodeURIComponent(o)}`,target:"_blank",rel:"noreferrer",ref:$,children:"Evidence"}),D?(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":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),_()}},children:b?"Applying…":I?`Confirm apply (${z.toString()} file${1===z?"":"s"})`:"Apply"}):h?.appliedAt!==void 0?(0,n.jsx)("span",{className:"arun-final mono",children:"Applied"}):null,F?(0,n.jsx)("button",{type:"button",className:"arun-btn danger",onClick:()=>void K(),children:"Cancel"}):null]})]})}let sL=[{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 sP(){return(0,n.jsx)("ul",{className:"integ","aria-label":"Integrations",children:sL.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)"]},sF={allow:"ask",ask:"deny",deny:"allow"},sz=[{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"}],sO=[["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"]],sK=[["calendar","Calendar","automations"],["mail","Mail","bell"],["jira","Jira","review"],["docs","Docs","files"]];function s_({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:sF[e.decision]}:e))},children:a[0]})]},e.id)})]})}function sB({decide:e}){let[t,l]=(0,a.useState)(!1),s=sz.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 sU({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."}),sK.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 sW({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."}),sO.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 sH=[["policy","Policy"],["eval","EVAL"],["bridges","Connections"],["persona","Persona"]];function sG(){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:sH.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)(s_,{policy:e.policy,setPolicy:e.setPolicy}),"eval"===t&&(0,n.jsx)(sB,{decide:e.decide}),"bridges"===t&&(0,n.jsx)(sU,{bridges:e.bridges,setBridges:e.setBridges}),"persona"===t&&(0,n.jsx)(sW,{persona:e.persona,setPersona:e.setPersona})]})]})}function sV(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 sY(){return"Available for embeddings; not shown in the chat model picker"}function sQ({model:e}){let t=function(e){if("chat"!==e.kind)return tG[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: "+sY(),title:sY(),children:"Embedding-ready"}):(0,n.jsxs)("span",{className:"ml-elig ml-elig-no","data-testid":"conv-elig-no",role:"status","aria-label":"Model eligibility: "+sV(t),title:sV(t),children:["Not selectable — ","ocr-vision-only"===t?"OCR/vision-only":"not a chat model"]})}function sJ({model:e}){var t;let a=tH(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)(sQ,{model:e})]}),(0,n.jsxs)("div",{className:"ml-url mono",children:["tools ",e.toolCalling?"yes":"no"," · structured"," ",e.structuredOutput?"yes":"no"," · ",e.costClass,"/",e.latencyClass]})]}),(0,n.jsx)("span",{className:"ml-status "+(a||l?"connected":"ineligible"),title:a?"conversation-eligible":l?"available for embeddings":"not selectable for conversation","aria-hidden":"true"})]})}function sX(){let[e,t]=(0,a.useState)(Z),[l,s]=(0,a.useState)(ee),[i,r]=(0,a.useState)(et),[o,c]=(0,a.useState)(en),[d,u]=(0,a.useState)(ea);(0,a.useEffect)(()=>{try{window.localStorage.setItem(_,e?"true":"false")}catch{}window.dispatchEvent(new CustomEvent(G,{detail:e}))},[e]),(0,a.useEffect)(()=>{try{window.localStorage.setItem(B,String(l))}catch{}window.dispatchEvent(new CustomEvent(V,{detail:l}))},[l]),(0,a.useEffect)(()=>{try{window.localStorage.setItem(U,String(i))}catch{}el(i),window.dispatchEvent(new CustomEvent(Y,{detail:i}))},[i]),(0,a.useEffect)(()=>{try{window.localStorage.setItem(W,String(o))}catch{}es(o),window.dispatchEvent(new CustomEvent(Q,{detail:o}))},[o]),(0,a.useEffect)(()=>{try{window.localStorage.setItem(H,String(d))}catch{}ei(d),window.dispatchEvent(new CustomEvent(J,{detail:d}))},[d]);let m={"--p":`${String(l)}%`},h={"--p":`${String(i)}%`},p={"--p":`${String(o)}%`},f={"--p":`${String(d)}%`};return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"set-sec-h",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"set-sec-t",children:"Workspace wallpaper"}),(0,n.jsx)("div",{className:"set-sec-d",children:"Liquid Chrome — a subtle metallic flow behind the grid that reacts to your cursor and clicks. Turn it off to stop the WebGL animation completely."})]})}),(0,n.jsxs)("div",{className:"gpref",children:[(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"gpref-label",children:"Liquid wallpaper"}),(0,n.jsx)("div",{className:"gpref-help",children:e?"Running":"Stopped"})]}),(0,n.jsx)(a3,{on:e,onChange:t,label:"Liquid wallpaper"})]}),(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsx)("label",{className:"gpref-label",htmlFor:"wp-op",children:"Wallpaper opacity"}),(0,n.jsxs)("span",{className:"gpref-val mono",children:[l,"%"]})]}),(0,n.jsx)("input",{id:"wp-op",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:l,disabled:!e,onChange:e=>s(Number.parseInt(e.target.value,10)),style:m,"aria-label":"Wallpaper opacity"}),(0,n.jsxs)("div",{className:"gpref-scale",children:[(0,n.jsx)("span",{children:"Off"}),(0,n.jsx)("span",{children:"Full"})]})]}),(0,n.jsxs)("div",{className:"gpref",children:[(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsx)("label",{className:"gpref-label",htmlFor:"ws-bg-bright",children:"Workspace background brightness"}),(0,n.jsxs)("span",{className:"gpref-val mono",children:[i,"%"]})]}),(0,n.jsx)("input",{id:"ws-bg-bright",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:i,onChange:e=>r(Number.parseInt(e.target.value,10)),style:h,"aria-label":"Workspace background brightness"}),(0,n.jsxs)("div",{className:"gpref-scale",children:[(0,n.jsx)("span",{children:"Base"}),(0,n.jsx)("span",{children:"Lighter"})]})]}),(0,n.jsxs)("div",{className:"gpref",children:[(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsx)("label",{className:"gpref-label",htmlFor:"ws-grid-strength",children:"Workspace grid strength"}),(0,n.jsxs)("span",{className:"gpref-val mono",children:[o,"%"]})]}),(0,n.jsx)("input",{id:"ws-grid-strength",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:o,onChange:e=>c(Number.parseInt(e.target.value,10)),style:p,"aria-label":"Workspace grid strength"}),(0,n.jsxs)("div",{className:"gpref-scale",children:[(0,n.jsx)("span",{children:"Subtle"}),(0,n.jsx)("span",{children:"Strong"})]})]}),(0,n.jsxs)("div",{className:"gpref",children:[(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsx)("label",{className:"gpref-label",htmlFor:"frame-border-strength",children:"Workspace border strength"}),(0,n.jsxs)("span",{className:"gpref-val mono",children:[d,"%"]})]}),(0,n.jsx)("input",{id:"frame-border-strength",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:d,onChange:e=>u(Number.parseInt(e.target.value,10)),style:f,"aria-label":"Workspace border strength"}),(0,n.jsxs)("div",{className:"gpref-scale",children:[(0,n.jsx)("span",{children:"Subtle"}),(0,n.jsx)("span",{children:"Strong"})]})]})]})}function sZ(){let[e,t]=(0,a.useState)("models"),[l,s]=(0,a.useState)([]),[i,r]=(0,a.useState)(null),[o,c]=(0,a.useState)(!1),[d,u]=(0,a.useState)(!0),[m,h]=(0,a.useState)(),[p,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(0);(0,a.useEffect)(()=>{let e=!1;return async function(){u(!0),h(void 0);try{let[t,n]=await Promise.all([(0,j.fetchConfig)(),(0,j.fetchModels)()]);if(e)return;r(t.config),c(t.configPresent),s(n.models)}catch(t){if(e)return;h(function(e){let t="Could not load gateway settings — the local Keiko backend did not respond.";if(!(e instanceof Error))return t;let n=e.message.trim();return 0===n.length||/^HTTP \d+$/u.test(n)||"Failed to fetch"===n||"Load failed"===n||"NetworkError when attempting to fetch a resource."===n?t:n}(t))}finally{e||u(!1)}}(),()=>{e=!0}},[g]);let x=l.filter(tH).length,b=l.length>0,y=o?b?0===x?"Gateway connected, but none of the discovered models can be used for conversation. Add a chat-capable deployment.":"Keiko can use the configured gateway models for chat and agent workflows.":"The gateway is configured, but no conversation-capable models are currently available.":"Enter the gateway base URL and API token before using chat or agent workflows.",k=o?"connected":"untested";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:()=>f(!0),children:[(0,n.jsx)(w.Icons.plus,{size:14}),o?"Update credentials":"Connect gateway"]})]}),(0,n.jsxs)("div",{className:"ml-row",children:[(0,n.jsx)("span",{className:"ml-ico",children:(0,n.jsx)(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:o?b?"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:[x.toString()," chat"]})]}),(0,n.jsx)("div",{className:"ml-url mono",children:y})]}),(0,n.jsx)("span",{className:"ml-status "+k,title:o?"gateway configured":"setup required","aria-hidden":"true"})]}),void 0!==m?(0,n.jsxs)("div",{className:"gw-error",role:"alert",children:[m,(0,n.jsx)("button",{type:"button",className:"gw-error-retry",onClick:()=>v(e=>e+1),children:"Retry"})]}):null,d?(0,n.jsx)("div",{className:"set-placeholder",role:"status",children:"Loading gateway models…"}):0===l.length?(0,n.jsx)("div",{className:"set-placeholder",role:"status",children:o?"No conversation-capable models are currently available. Review the gateway configuration or discovered model set.":"No models are configured yet. Connect the gateway to load configured model capabilities."}):(0,n.jsx)("div",{className:"set-list",children:l.map(e=>(0,n.jsx)(sJ,{model:e},e.id))}),p?(0,n.jsx)(to,{onCancel:()=>f(!1),preserveExisting:o,storedApiKeyHeaderName:i?.providers[0]?.credentialHeaderName,storedModels:l}):null]}),"general"===e&&(0,n.jsx)(sX,{}),"security"===e&&(0,n.jsx)("div",{className:"set-placeholder",children:"SSO · audit log · data residency — coming soon."})]})]})}function s0(e){return e instanceof j.ApiError?`${e.message} (${e.code})`:e instanceof Error?e.message:"Failed to load connectors."}function s1(){return(0,n.jsx)("div",{className:"connector-picker-status",role:"status","aria-live":"polite",children:"Loading connectors…"})}function s2({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 s3({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 s4({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 s6({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 s5({selectedKind:e,selectedId:t,selectedLabel:l,selectedState:s,presentation:i,onSelect:r,onManageConnectors:o=()=>void 0}){let[c,d]=(0,a.useState)([]),[u,m]=(0,a.useState)([]),[h,p]=(0,a.useState)(!0),[f,g]=(0,a.useState)(null),[v,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,a4.fetchCapsules)(),(0,a4.fetchCapsuleSets)()]);if(e)return;"fulfilled"===t.status?d(t.value.capsules.filter(e=>"ready"===e.lifecycleState)):g(s0(t.reason)),"fulfilled"===n.status?m(n.value.capsuleSets):x(!0)}catch(t){e||g(s0(t))}finally{e||p(!1)}}(),()=>{e=!0}},[j,b]),j)return(0,n.jsx)(s6,{selectedId:t,selectedLabel:l,selectedState:s,onManageConnectors:o});if(h)return(0,n.jsx)(s1,{});if(null!==f)return(0,n.jsx)(s2,{message:f,onRetry:()=>{y(e=>e+1)}});let w=c.length>0,k=u.length>0;if(!w&&!k)return(0,n.jsx)(s3,{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)(s4,{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 s8(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 s7(e,t={}){return s8("/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 s9(e,t){return s8(`/api/figma/snapshots/${encodeURIComponent(e)}`,{...void 0!==t?{signal:t}:{}})}async function ie(e={}){let t=new URLSearchParams;void 0!==e.fileKey&&t.set("fileKey",e.fileKey),void 0!==e.nodeId&&t.set("nodeId",e.nodeId),void 0!==e.limit&&t.set("limit",String(e.limit));let n=t.size>0?`?${t.toString()}`:"";return(await s8(`/api/figma/snapshots${n}`,{...void 0!==e.signal?{signal:e.signal}:{}})).snapshots}async function it(e,t){return s8(`/api/figma/snapshots/${encodeURIComponent(e)}/code`,{method:"POST",...void 0!==t?{signal:t}:{},body:JSON.stringify({})})}async function ia(){return s8("/api/figma/token",{method:"DELETE",body:JSON.stringify({})})}function il(e){try{let t=new URL(e.trim()),n=t.hostname.toLowerCase();if("https:"!==t.protocol||"figma.com"!==n&&"www.figma.com"!==n||!/^\/(design|file)\//u.test(t.pathname))return!1;let a=t.searchParams.get("node-id");return null!==a&&a.length>0}catch{return!1}}function is(e){let t=new URL(`https://www.figma.com/design/${e.fileKey}/board`);return t.searchParams.set("node-id",e.nodeId),void 0!==e.version&&e.version.length>0&&t.searchParams.set("version",e.version),t.toString()}let ii=new Set(["FIGMA_PROXY_EGRESS_FAILED","FIGMA_PROXY_UNREACHABLE","FIGMA_PROXY_AUTH_REQUIRED","FIGMA_PROXY_BLOCKED_BY_POLICY"]),ir=new Set(["FIGMA_TLS_CA_FAILURE"]),io=new Set(["FIGMA_NETWORK_UNREACHABLE","FIGMA_EGRESS_TIMEOUT","FIGMA_EGRESS_FAILED"]);function ic(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}:ii.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}:ir.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}:io.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 id(e){let t=ic(e);return void 0===t.status?t.detail:`${t.detail} (${t.status})`}function iu({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)(nX.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:(0,n8.formatBytes)(i)}),(0,n.jsx)("p",{className:"figma-snapshot-screen-id",children:t})]})]})}function im({snapshotRunId:e,updateCfg:t,triggerImpl:l=s7,loadImpl:s=s9,listImpl:i=ie,codegenImpl:r=it,revokeImpl:o=ia}){let c,d,u,m,h=(0,a.useId)(),p=(0,a.useId)(),f=(0,a.useId)(),g=(0,a.useId)(),[v,x]=(0,a.useState)(""),[b,y]=(0,a.useState)("idle"),[w,k]=(0,a.useState)(null),[N,S]=(0,a.useState)(null),[C,I]=(0,a.useState)(null),[E,R]=(0,a.useState)(null),[$,A]=(0,a.useState)(0),[T,M]=(0,a.useState)("recent"),[q,L]=(0,a.useState)([]),[P,D]=(0,a.useState)([]),[F,z]=(0,a.useState)(!1),[O,K]=(0,a.useState)(!1),[_,B]=(0,a.useState)(null),[U,W]=(0,a.useState)(null),[H,G]=(0,a.useState)(!1),[V,Y]=(0,a.useState)(!1),Q=(0,a.useRef)(null),J=(0,a.useRef)(null),X=(0,a.useRef)(null),Z=(0,a.useRef)(null),ee=(0,a.useRef)(null),et=(0,a.useCallback)(()=>{Y(!0)},[]),[en,ea]=(0,a.useState)("idle"),[el,es]=(0,a.useState)(null),[ei,er]=(0,a.useState)(null),[eo,ec]=(0,a.useState)(!1),[ed,eu]=(0,a.useState)(null),[em,eh]=(0,a.useState)(null),ep=(0,a.useRef)(null),ef=(0,a.useRef)(null),[eg,ev]=(0,a.useState)(24),ex=il(v),eb=function(e){let t=e.trim();if(0===t.length||il(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."}(v),ey=(0,a.useMemo)(()=>null!==w?{fileKey:w.fileKey,nodeId:w.nodeId}:function(e){try{let t=new URL(e.trim()),n=t.hostname.toLowerCase();if("https:"!==t.protocol||"figma.com"!==n&&"www.figma.com"!==n)return null;let[,a,l]=t.pathname.split("/");if("design"!==a&&"file"!==a||void 0===l||0===l.length)return null;let s=t.searchParams.get("node-id");if(null===s||0===s.length)return null;return{fileKey:l,nodeId:s}}catch{return null}}(v),[v,w]),ej=ey?.fileKey,ew=ey?.nodeId,ek="building"===b,eN="loading"===b,eS=ek||eN,eC=ek&&null!==E?(d=Math.floor((c=Math.max(0,Math.floor($/1e3)))/3600),u=Math.floor(c%3600/60),m=c%60,d>0?`${String(d)}h ${String(u)}m ${String(m)}s`:u>0?`${String(u)}m ${String(m)}s`:`${String(m)}s`):null;(0,a.useEffect)(()=>{V&&"error"===b&&Q.current?.focus()},[V,b]),(0,a.useEffect)(()=>{eo&&ep.current?.focus()},[eo]),(0,a.useEffect)(()=>{if(!ek||null===E)return;A(Date.now()-E);let e=window.setInterval(()=>{A(Date.now()-E)},1e3);return()=>{window.clearInterval(e)}},[ek,E]),(0,a.useEffect)(()=>()=>{J.current?.abort(),X.current?.abort(),Z.current?.abort()},[]),(0,a.useEffect)(()=>{null===ey&&"board"===T&&M("recent")},[ey,T]);let eI=(0,a.useCallback)(()=>{Z.current?.abort();let e=new AbortController;if(Z.current=e,K(!0),W(null),i({limit:12,signal:e.signal}).then(e=>{D(e)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||(D([]),W(id(e)))}).finally(()=>{Z.current===e&&K(!1)}),void 0===ej||void 0===ew){L([]),B(null),z(!1);return}z(!0),B(null),i({fileKey:ej,nodeId:ew,limit:12,signal:e.signal}).then(e=>{L(e)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||(L([]),B(id(e)))}).finally(()=>{Z.current===e&&z(!1)})},[ej,ew,i]);(0,a.useEffect)(()=>{eI()},[eI,w?.runId]);let eE=(0,a.useCallback)(n=>{if(0===n.length||eS)return;J.current?.abort();let a=new AbortController;J.current=a,y("loading"),S(null),I(null),ea("idle"),es(null),er(null),s(n,a.signal).then(e=>{k(e),x(is(e)),t({snapshotRunId:e.runId}),y("done")}).catch(a=>{a instanceof DOMException&&"AbortError"===a.name||(a instanceof j.ApiError&&"FIGMA_SNAPSHOT_NOT_FOUND"===a.code?(e===n&&t({snapshotRunId:void 0}),S({...ic(a),detail:e===n?`${a.message} The stored run ID has been cleared.`:a.message})):S(ic(a)),y("error"))})},[eS,s,e,t]),eR=(0,a.useCallback)(async(e,n)=>{J.current?.abort(),X.current?.abort(),X.current=null;let a=new AbortController;J.current=a,ee.current={link:e,isResnapshot:n},y("building"),S(null),I(null),R(Date.now()),A(0),ea("idle"),es(null);try{let s=await l(e,{acknowledgeReadOnly:H,isResnapshot:n,signal:a.signal});k(s),x(is(s)),t({snapshotRunId:s.runId}),y("done"),R(null),A(0),ee.current=null}catch(t){if(t instanceof DOMException&&"AbortError"===t.name)return;if(R(null),A(0),t instanceof j.ApiError&&"FIGMA_CONSENT_REQUIRED"===t.code){let e=ic(t);S({...e,detail:`${e.detail} Tick the acknowledgement checkbox below, then snapshot again.`}),et()}else t instanceof j.ApiError&&"FIGMA_BUILD_TIMEOUT"===t.code?(I({link:e,isResnapshot:n}),S({title:"Figma snapshot is still running",detail:"This window stopped waiting for the snapshot result. The server may still finish the build in the background.",status:`HTTP ${t.status.toString()}`,remediation:"Reconnect to the same board to keep waiting, or close this window and return later."})):S(ic(t));y("error"),ee.current=null}},[l,t,H,et]),e$=(0,a.useCallback)(e=>{if(e.preventDefault(),ex&&!eS){if(!H){S({title:"Figma snapshot failed",detail:"Tick the read-only acknowledgement checkbox below, then snapshot again."}),y("error"),et();return}eR(v,!1)}},[v,eS,H,ex,eR,et]),eA=(0,a.useCallback)(()=>{eS||null!==w&&eR(is(w),!0)},[eS,eR,w]),eT=(0,a.useCallback)(()=>{J.current?.abort(),J.current=null,R(null),A(0),null!==ee.current&&I(ee.current),ee.current=null,y("idle"),S(null)},[]),eM=(0,a.useCallback)(()=>{eS||null===C||eR(C.link,C.isResnapshot)},[eS,C,eR]),eq=(0,a.useCallback)(()=>{let t=w?.runId??e;if(void 0===t||0===t.length||"generating"===en)return;let n=new AbortController;X.current=n,ea("generating"),er(null),r(t,n.signal).then(e=>{es(e),ea("done")}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name?ea("idle"):(er(id(e)),ea("error"))}).finally(()=>{X.current===n&&(X.current=null)})},[r,en,e,w]),eL=(0,a.useCallback)(()=>{X.current?.abort(),X.current=null,ea("idle"),er(null)},[]),eP=(0,a.useCallback)(()=>{void 0===e||0===e.length||eS||eE(e)},[eS,eE,e]);(0,a.useEffect)(()=>{ev(24)},[w?.runId]);let eD=(0,a.useCallback)(()=>{ec(!1),eh(null),eu(null),o().then(e=>{eu(e.message),requestAnimationFrame(()=>ef.current?.focus())}).catch(e=>{eh(id(e)),requestAnimationFrame(()=>ef.current?.focus())})},[o]),eF=(0,a.useCallback)(()=>{ec(!1),requestAnimationFrame(()=>ef.current?.focus())},[]),ez=void 0!==e&&e.length>0&&null===w&&("idle"===b||"loading"===b||"error"===b),eO=(t,a,l,s,i,r)=>a?(0,n.jsx)("p",{className:"figma-snapshot-dashboard-status",children:"Loading snapshots…"}):null!==l?(0,n.jsx)("p",{className:"figma-snapshot-dashboard-status figma-snapshot-dashboard-status-error",children:l}):0===t.length?(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-empty",children:[(0,n.jsx)("p",{className:"figma-snapshot-dashboard-empty-title",children:s}),(0,n.jsx)("p",{className:"figma-snapshot-dashboard-empty-detail",children:i})]}):(0,n.jsx)("div",{className:"figma-snapshot-dashboard-list",role:"list",children:t.map(t=>{let a=w?.runId===t.runId;return(0,n.jsxs)("button",{type:"button",className:"figma-snapshot-dashboard-item",onClick:()=>{eE(t.runId)},"aria-current":a?"true":void 0,"aria-busy":eN&&e===t.runId?"true":void 0,children:[(0,n.jsxs)("span",{className:"figma-snapshot-dashboard-item-head",children:[(0,n.jsx)("span",{className:"figma-snapshot-dashboard-item-date",children:(0,n8.formatDate)(t.fetchedAt)}),a&&(0,n.jsx)("span",{className:"figma-snapshot-dashboard-item-badge",children:"Current"})]}),(0,n.jsx)("span",{className:"figma-snapshot-dashboard-item-hint",children:t.reductionHint}),(0,n.jsxs)("span",{className:"figma-snapshot-dashboard-item-meta",children:[t.screenCount.toString()," screen",1!==t.screenCount?"s":"",t.skippedCount>0?`, ${t.skippedCount.toString()} skipped`:", no skipped renders"]}),r&&(0,n.jsxs)("span",{className:"figma-snapshot-dashboard-item-scope",children:[t.fileKey," · ",t.nodeId]})]},t.runId)})});return(0,n.jsxs)("section",{className:"figma-snapshot-window","aria-label":"Figma Snapshot",children:[(0,n.jsxs)("form",{className:"figma-snapshot-form",onSubmit:e$,noValidate:!0,children:[(0,n.jsx)("label",{className:"figma-snapshot-label",htmlFor:h,children:"Board link"}),(0,n.jsxs)("div",{className:"figma-snapshot-input-row",children:[(0,n.jsx)("input",{id:h,type:"url",className:"figma-snapshot-input",placeholder:"https://www.figma.com/design/…?node-id=…",value:v,onChange:e=>{x(e.target.value),null!==N&&S(null),"error"===b&&y("idle"),null!==C&&I(null),V&&Y(!1)},"aria-describedby":null!==eb?`${f} ${p}`:p,"aria-invalid":null!==eb?"true":void 0,readOnly:eS,autoComplete:"off",spellCheck:!1}),(0,n.jsx)("button",{type:"submit",className:"figma-snapshot-trigger-btn",disabled:!ex&&!eS,"aria-disabled":!ex||eS?"true":void 0,"aria-busy":ek,children:ek?"Building…":"Snapshot"})]}),null!==eb&&(0,n.jsx)("p",{id:f,className:"figma-snapshot-link-error",role:"alert",children:eb}),(0,n.jsxs)("label",{className:"figma-snapshot-consent",children:[(0,n.jsx)("input",{type:"checkbox",className:"figma-snapshot-consent-checkbox",ref:Q,checked:H,"aria-invalid":V?"true":void 0,onChange:e=>{G(e.target.checked),null!==N&&S(null),"error"===b&&y("idle"),Y(!1)},disabled:ek}),(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"===b&&null!==N&&!0===N.assertive&&(0,n.jsxs)("div",{className:"figma-snapshot-error-card",role:"alert","aria-labelledby":`${p}-error-title`,children:[(0,n.jsx)("p",{id:`${p}-error-title`,className:"figma-snapshot-error-title",children:N.title}),(0,n.jsx)("p",{className:"figma-snapshot-error-detail",children:N.detail}),void 0!==N.status&&(0,n.jsx)("p",{className:"figma-snapshot-error-status",children:N.status}),void 0!==N.remediation&&(0,n.jsx)("p",{className:"figma-snapshot-error-remediation",children:N.remediation})]}),(0,n.jsxs)("div",{id:p,role:"status","aria-live":"polite","aria-atomic":"true",className:"figma-snapshot-status",children:[ek&&(0,n.jsxs)("p",{className:"figma-snapshot-progress",children:["Building snapshot — fetching screens from Figma…"," ",null!==eC?`${eC} elapsed.`:""," Large boards can take several minutes."]}),eN&&(0,n.jsx)("p",{className:"figma-snapshot-progress",children:"Loading stored snapshot…"}),"done"===b&&null!==w&&(0,n.jsxs)("p",{className:"sr-only",children:["Snapshot complete — ",w.reductionHint,"."]}),"done"===en&&null!==el&&(0,n.jsxs)("p",{className:"sr-only",children:["Code generated — ",String(el.fileCount)," file",1!==el.fileCount?"s":""," ready for review."]}),"idle"===b&&(0,n.jsx)("p",{className:"sr-only","aria-live":"polite"}),"error"===b&&null!==N&&!0!==N.assertive&&(0,n.jsx)("p",{className:"figma-snapshot-error",children:N.detail})]}),ek&&(0,n.jsxs)("div",{className:"figma-snapshot-cancel-row",children:[(0,n.jsx)("button",{type:"button",className:"figma-snapshot-cancel-btn",onClick:eT,children:"Cancel"}),(0,n.jsx)("p",{className:"figma-snapshot-cancel-note",role:"status","aria-live":"polite",children:"Cancelling stops this window from waiting — the server-side build continues on demand."})]}),null!==C&&!eS&&(0,n.jsxs)("div",{className:"figma-snapshot-stored-notice",children:[(0,n.jsx)("p",{className:"figma-snapshot-stored-text",children:"This window is no longer waiting. The server may still be building the snapshot in the background. You can close this window safely."}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-load-btn",onClick:eM,children:"Reconnect build"})]}),"idle"===b&&null===w&&null===C&&!ez&&(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."})]}),ez&&(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:eP,"aria-disabled":eN?"true":void 0,"aria-busy":eN,children:eN?"Loading…":"Load snapshot"})]}),(0,n.jsxs)("section",{className:"figma-snapshot-dashboard","aria-label":"Snapshot dashboard",children:[(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-header",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"figma-snapshot-dashboard-eyebrow",children:"Snapshot dashboard"}),(0,n.jsx)("h2",{className:"figma-snapshot-dashboard-title",children:"Stored snapshots"})]}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-refresh",onClick:eI,children:"Refresh"})]}),(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-tabs",role:"tablist","aria-label":"Snapshot views",children:[(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-tab",role:"tab","aria-selected":"board"===T,"aria-controls":`${g}-board-panel`,id:`${g}-board-tab`,onClick:()=>{null!==ey&&M("board")},disabled:null===ey,children:"This board"}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-tab",role:"tab","aria-selected":"recent"===T,"aria-controls":`${g}-recent-panel`,id:`${g}-recent-tab`,onClick:()=>{M("recent")},children:"Recent"})]}),"board"===T?(0,n.jsx)("div",{id:`${g}-board-panel`,className:"figma-snapshot-dashboard-panel",role:"tabpanel","aria-labelledby":`${g}-board-tab`,children:null===ey?eO([],!1,null,"No board selected yet","Paste a valid Figma board link or load a stored snapshot to see this board's history.",!1):eO(q,F,_,"No snapshots stored for this board","Take the first snapshot for this board to make it available here.",!1)}):(0,n.jsx)("div",{id:`${g}-recent-panel`,className:"figma-snapshot-dashboard-panel",role:"tabpanel","aria-labelledby":`${g}-recent-tab`,children:eO(P,O,U,"No snapshots stored yet","Stored Figma snapshots will appear here once the first board capture completes.",!0)})]}),null!==w&&(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:w.reductionHint}),(0,n.jsxs)("p",{className:"figma-snapshot-captured-at",children:["Captured ",(0,n8.formatDate)(w.fetchedAt)]}),w.skippedCount>0&&(0,n.jsxs)("p",{className:"figma-snapshot-skipped-notice",children:[String(w.skippedCount)," screen",1!==w.skippedCount?"s":""," could not be rendered and were skipped."]})]}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-resnapshot-btn",onClick:eA,"aria-disabled":eS?"true":void 0,"aria-busy":ek,"aria-label":"Re-snapshot this board",children:ek?"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:eq,"aria-disabled":"generating"===en?"true":void 0,"aria-busy":"generating"===en,children:"generating"===en?"Generating code…":"Generate code"}),"generating"===en&&(0,n.jsx)("button",{type:"button",className:"figma-snapshot-codegen-cancel-btn",onClick:eL,children:"Cancel"})]}),"error"===en&&null!==ei&&(0,n.jsx)("p",{className:"figma-snapshot-error",role:"alert",children:ei}),"done"===en&&null!==el&&(0,n.jsxs)("div",{className:"figma-snapshot-code-result",children:[(0,n.jsxs)("p",{className:"figma-snapshot-code-summary",children:[String(el.fileCount)," reviewable file",1!==el.fileCount?"s":""," (",String(el.screenCount)," screen",1!==el.screenCount?"s":"",","," ",el.adapterName,") — proposal only, never auto-applied."]}),el.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:[eo?(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:ep,type:"button",className:"figma-snapshot-revoke-confirm-btn",onClick:eD,children:"Yes, revoke"}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-revoke-cancel-btn",onClick:eF,children:"Cancel"})]}):(0,n.jsx)("button",{ref:ef,type:"button",className:"figma-snapshot-revoke-btn",onClick:()=>{ec(!0),eu(null),eh(null)},children:"Revoke stored token"}),(0,n.jsx)("p",{className:"figma-snapshot-revoke-status",role:"status","aria-live":"polite","aria-atomic":"true",children:ed??em??""})]})]}),w.screens.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("section",{className:"figma-snapshot-gallery","aria-label":`${String(w.screenCount)} captured screen${1!==w.screenCount?"s":""}`,children:w.screens.slice(0,eg).map((e,t)=>{var a;return(0,n.jsx)(iu,{index:t,screenId:e.screenId,name:e.name,irSummary:e.irSummary,imageSrc:(a=w.runId,`/api/figma/snapshots/${encodeURIComponent(a)}/screens/${encodeURIComponent(String(t))}/image`),imageByteLength:e.imageByteLength},e.screenId)})}),eg<w.screens.length?(0,n.jsx)("button",{type:"button",className:"figma-snapshot-gallery-more",onClick:()=>ev(e=>Math.min(e+24,w.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 ih(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 ip(){return ih("/api/quality-intelligence/runs")}async function ig(e){return ih(`/api/quality-intelligence/runs/${encodeURIComponent(e)}`)}async function iv(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 ix(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 iv(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 ib(e){return ih(`/api/quality-intelligence/runs/${encodeURIComponent(e)}`,{method:"DELETE"})}async function iy(e,t,n,a){return ih(`/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 ij(e,t,n,a){return(await ih(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/edit`,{method:"POST",body:JSON.stringify({candidateId:t,edited:n,...void 0!==a?{editorLabel:a}:{}})})).candidate}async function iw(e,t){return ih(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/re-check`,{method:"POST",body:JSON.stringify({sources:t})})}async function ik(e,t){return ih(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/regenerate-stale`,{method:"POST",body:JSON.stringify({sources:t})})}async function iN(e,t,n){return ih(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/export`,{method:"POST",body:JSON.stringify({adapter:t,dryRun:n?.dryRun??!1,approvedOnly:n?.approvedOnly??!1})})}async function iS(e,t){return ih(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/traceability`,{method:"POST",body:JSON.stringify({format:t})})}let iC={open:"Open",approved:"Approved","changes-requested":"Changes requested",rejected:"Rejected",withdrawn:"Withdrawn"},iI={open:"qi-review-open",approved:"qi-review-approved","changes-requested":"qi-review-changes",rejected:"qi-review-rejected",withdrawn:"qi-review-withdrawn"};function iE({state:e}){return(0,n.jsxs)("span",{className:`qi-review-badge ${iI[e]}`,children:[(0,n.jsx)("span",{className:"sr-only",children:"Review: "}),iC[e]]})}function iR(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 i$(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"},iT={running:"qi-badge-running",succeeded:"qi-badge-succeeded",failed:"qi-badge-failed",cancelled:"qi-badge-cancelled"};function iM(e){return"running"===e||"succeeded"===e||"failed"===e||"cancelled"===e}function iq({status:e}){let t=iM(e)?iA[e]:e,a=iM(e)?iT[e]:"qi-badge-default";return(0,n.jsx)("span",{className:`qi-badge ${a}`,children:t})}let iL={critical:"qi-sev-critical",high:"qi-sev-high",medium:"qi-sev-medium",low:"qi-sev-low"};function iP({severity:e}){let t="critical"===e||"high"===e||"medium"===e||"low"===e?iL[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 iD({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 iF({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 iz={verifiability:"Verifiability",atomicity:"Atomicity",determinism:"Determinism","ac-fidelity":"AC fidelity"};function iO({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:[iz[e.name]??e.name," ",Math.round(e.score).toString(),": ",e.rationale]},e.name))})]})}function iK({height:e=20,width:t="100%"}){return(0,n.jsx)("div",{"aria-hidden":"true",className:"qi-skeleton",style:{height:e,width:t}})}function i_(){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)(iK,{height:14,width:"60%"}),(0,n.jsx)(iK,{height:12,width:"40%"})]},e))})}function iB({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 iU="connectedSourcesJson";function iW(e,t){let n=e[t];return"string"==typeof n?n:void 0}function iH(e,t){return"string"==typeof e[t]}function iG(e){if(!("object"==typeof e&&null!==e&&!Array.isArray(e))||!iH(e,"label"))return!1;switch(e.kind){case"file":case"workspace":return iH(e,"path");case"capsule":return iH(e,"capsuleId");case"capsule-set":return iH(e,"capsuleSetId");case"figma-snapshot":return iH(e,"snapshotRunId");default:return!1}}function iV(e){return e.length>0?{[iU]:JSON.stringify(e)}:{}}function iY(e){let t=e.split(/[\\/]/u).filter(e=>e.length>0);return t.length>0?t[t.length-1]??e:e}function iQ(e){return e.replaceAll("\\","/")}function iJ(e){if(/^[A-Za-z]:[/\\]?$/u.test(e))return e.replaceAll("\\","/");if(/^\/\/[^/]+\/[^/]+$/u.test(iQ(e)))return iQ(e);let t=iQ(e).replace(/\/+$/u,"");return 0===t.length&&e.length>0?"/":t}function iX(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=iJ(a),s=iQ(n).replace(/^\/+/u,""),i=l.endsWith("/")?"":"/";return`${l}${i}${s}`}(t,e.connectedFilePath??null),a=null!==t?iJ(t):null,l=(void 0!==e.connectedRoots&&null!==e.connectedRoots&&e.connectedRoots.length>0?e.connectedRoots:null!==t?[t]:[]).map(iJ),s=null!==n?l.filter(e=>e!==a):l,i=[];for(let e of(null!==n&&i.push({kind:"file",label:iY(n),path:n}),s))i.push({kind:"workspace",label:iY(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 iZ=[{id:"regression-default",label:"Regression (default)"},{id:"banking-default",label:"Banking"},{id:"insurance-default",label:"Insurance"}],i0={phase:"Starting…",stageName:null,candidates:0,findings:0,atomCount:null,droppedSourceCount:0,skippedSources:[]};function i1(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 i2(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 i3({onRunCompleted:e,startImpl:t=ix,fetchCapsulesImpl:l=a4.fetchCapsules,fetchCapsuleSetsImpl:s=a4.fetchCapsuleSets,connectedRoot:i=null,connectedFilePath:r=null,connectedRoots:o,connectedCapsuleIds:c,connectedCapsuleSetIds:d,connectedFigmaSnapshotRunIds:u}){let[m,h]=(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),[$,A]=(0,a.useState)(null),[T,M]=(0,a.useState)("regression-default"),[q,L]=(0,a.useState)(""),[P,D]=(0,a.useState)(!1),[F,z]=(0,a.useState)(i0),[O,K]=(0,a.useState)(null),_=(0,a.useRef)(null),B=(0,a.useRef)(null),U=(0,a.useRef)(!1),W=iX({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=q.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?B.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),A(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&&A(iR(t.reason))),"fulfilled"===n.status?I(n.value.capsuleSets):(I([]),"capsule-set"===p&&A(iR(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=m.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,m,x,G,V,p,g]),ed=(0,a.useCallback)(async()=>{if(!X||P||!et||U.current)return;U.current=!0,D(!0),K(null),z(i0),B.current=null;let n=new AbortController;_.current=n;let a=ec()??W,l={sources:a,profileId:T,...void 0!==ee?{seed:ee}:{}};try{await t(l,n.signal,er);let s=B.current;null!==s&&e?.(s,a.filter(e=>"requirements"!==e.kind))}catch(e){n.signal.aborted||K(iR(e))}finally{D(!1),_.current=null,U.current=!1}},[X,T,P,W,ec,er,e,ee,et,t]),eu=(0,a.useCallback)(()=>{_.current?.abort()},[]),em=F.droppedSourceCount>0?`${F.droppedSourceCount.toString()} source${1!==F.droppedSourceCount?"s":""} over the 16-source limit ${1!==F.droppedSourceCount?"were":"was"} not included.`:null,eh=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=[em,eh].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 ",i1(W[0]).toLowerCase()]}),(0,n.jsx)("span",{className:"qi-connected-path qi-monospace",title:i2(W[0]),children:i2(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 ${i1(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:i1(e)}),(0,n.jsx)("span",{className:"qi-connected-path qi-monospace",title:i2(e),children:i2(e)})]},`${e.kind}:${i2(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:m,placeholder:"e.g. Funds Transfer — acceptance criteria",disabled:P,"aria-describedby":H&&!Q?es:void 0,onChange:e=>{h(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:P,onChange:e=>{let t=e.target.value;f("workspace"===t||"file"===t||"capsule"===t||"capsule-set"===t?t:"requirements"),K(null),A(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:P,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:P,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:P||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:T,disabled:P,onChange:e=>{M(e.target.value)},children:iZ.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:q,placeholder:"e.g. 42",disabled:P,"aria-invalid":!et||void 0,"aria-describedby":et?void 0:el,onChange:e=>{L(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:P?"qi-btn qi-btn-secondary":"qi-btn qi-btn-primary","aria-disabled":!P&&en||void 0,"aria-describedby":P?void 0:ei,onClick:()=>{P?eu():en||ed()},children:P?"Cancel":"Generate test cases"}),P||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."})]}),P?(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}`}(P,F)}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:ep}),null!==em||null!==eh?(0,n.jsxs)("div",{className:"qi-coverage-notice","data-testid":"qi-coverage-notice",children:[null!==em?(0,n.jsx)("p",{className:"qi-coverage-line",children:em}):null,null!==eh?(0,n.jsx)("p",{className:"qi-coverage-line",children:eh}):null]}):null,null!==O?(0,n.jsx)("p",{className:"lk-alert",role:"alert","data-testid":"qi-launch-error",children:O}):null]})]})}function i4({run:e,onOpen:t,onDelete:l,deleting:s}){var i;let r=e.totals.candidates,[o,c]=(0,a.useState)(!1),d=(0,a.useRef)(null),u=(0,a.useRef)(null),m=(0,a.useRef)(null);(0,a.useEffect)(()=>{o&&u.current?.focus()},[o]);let h=(0,a.useCallback)(()=>{c(!1),requestAnimationFrame(()=>{d.current?.focus()})},[]),p=(0,a.useCallback)(e=>{"Escape"===e.key&&(e.preventDefault(),h())},[h]),f=(0,a.useCallback)(()=>{s||l(e.id)},[s,l,e.id]);return(0,n.jsxs)("li",{style:{display:"flex",alignItems:"stretch"},children:[(0,n.jsxs)("button",{type:"button",className:"qi-run-item",style:{flex:1},onClick:()=>{t(e.id,[])},"aria-label":`Open run ${e.id} — ${iM(i=e.status)?iA[i]:i}, ${i$(e.requestedAt)}, ${r.toString()} test case${1!==r?"s":""}, review ${iC[e.reviewState]}`,title:`Open run ${e.id}`,children:[(0,n.jsx)("span",{className:"qi-run-title",children:i$(e.requestedAt)}),(0,n.jsx)(iq,{status:e.status}),(0,n.jsx)(iE,{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 ${i$(e.requestedAt)}`,style:{display:"flex",alignItems:"center",gap:4,padding:"0 6px",flexShrink:0},children:[(0,n.jsx)("button",{ref:m,type:"button",className:"qi-btn qi-btn-reject",style:{minWidth:0,padding:"4px 10px",fontSize:12,flexShrink:0},"aria-label":`Confirm delete of run ${i$(e.requestedAt)}`,"aria-busy":s||void 0,"aria-disabled":s||void 0,onClick:f,onKeyDown:p,children:s?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{"aria-hidden":"true",children:"Deleting…"}),(0,n.jsx)("span",{className:"sr-only",children:"Deleting run, please wait"})]}):"Confirm delete"}),(0,n.jsx)("button",{ref:u,type:"button",className:"qi-btn qi-btn-secondary",style:{minWidth:0,padding:"4px 10px",fontSize:12,flexShrink:0},"aria-disabled":s||void 0,onClick:()=>{s||h()},onKeyDown:p,children:"Cancel"})]}):(0,n.jsx)("button",{ref:d,type:"button",className:"qi-btn qi-btn-reject",style:{alignSelf:"center",minWidth:0,padding:"4px 10px",fontSize:12,margin:"0 6px 0 0",flexShrink:0},"aria-label":`Delete run ${i$(e.requestedAt)}`,onClick:()=>{c(!0)},children:"Delete"})]})}function i6({openRun:e,connectedRoot:t=null,connectedFilePath:l=null,connectedRoots:s,connectedCapsuleIds:i,connectedCapsuleSetIds:r,connectedFigmaSnapshotRunIds:o,fetchRunsImpl:c=ip,deleteImpl:d=ib}){let[u,m]=(0,a.useState)([]),[h,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();m(e.runs),p(e.totalRunIds),g(e.truncated)}catch(e){y(iR(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(iR(e))}finally{N(null)}}},[k,d,I]);return(0,n.jsxs)("div",{className:"qi-hub",children:[(0,n.jsx)(i3,{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:h.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 ${h.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)(i_,{}):null!==b?(0,n.jsx)(iB,{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)(i4,{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 ${h.toString()} runs.`}):null]})})]})]})}e.s(["QUALITY_INTELLIGENCE_SCHEMA_VERSION",0,"1"],73859),e.i(73859);let i5=["..","/","\\"],i8=(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`}:i5.some(t=>e.includes(t))?{ok:!1,reason:`${t} contains forbidden path fragment`}:{ok:!0},i7=(e,t)=>{let n=i8(e,t);if(!n.ok)throw TypeError(`Invalid ${t}: ${n.reason}`);return e},i9=e=>1564===e||e>=8203&&e<=8207||e>=8234&&e<=8238||e>=8294&&e<=8297||65279===e,re=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(i9(t.codePointAt(0)??0))return!0;return!1})(e)),rt=e=>Number.isFinite(e)&&e>=0&&e<=1,rn=Object.freeze({critical:0,high:1,medium:2,low:3}),ra=new Set(["jira-issues","qtest","xray","polarion","alm","quality-center"]),rl=["verifiability","atomicity","determinism","ac-fidelity"],rs=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:[...rl]},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,rn,"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,ra,"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,rs,"TEST_QUALITY_RUBRIC_DIMENSIONS",0,rl,"asQualityIntelligenceAuditSummaryId",0,e=>i7(e,"QualityIntelligenceAuditSummaryId"),"asQualityIntelligenceCoverageMapId",0,e=>i7(e,"QualityIntelligenceCoverageMapId"),"asQualityIntelligenceEvidenceAtomId",0,e=>i7(e,"QualityIntelligenceEvidenceAtomId"),"asQualityIntelligenceExportBundleId",0,e=>i7(e,"QualityIntelligenceExportBundleId"),"asQualityIntelligenceReviewRecordId",0,e=>i7(e,"QualityIntelligenceReviewRecordId"),"asQualityIntelligenceRunId",0,e=>i7(e,"QualityIntelligenceRunId"),"asQualityIntelligenceSourceEnvelopeId",0,e=>i7(e,"QualityIntelligenceSourceEnvelopeId"),"asQualityIntelligenceTestCaseId",0,e=>i7(e,"QualityIntelligenceTestCaseId"),"asQualityIntelligenceValidationFindingId",0,e=>i7(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(!rt(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(ra.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)||re(t)||re(a)||re(n.origin)||"connector-document"===e.kind&&re(e.adapterId))},"validateQualityIntelligenceIdString",0,i8],47425);var ri=e.i(47425),ri=ri;let rr=ri.QUALITY_INTELLIGENCE_PRIORITIES,ro=ri.QUALITY_INTELLIGENCE_RISK_CLASSES,rc=e=>e.split("\n").map(e=>e.trim()).filter(e=>e.length>0),rd=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]);function ru(e,t){let n=rc(t.preconditions),a=rc(t.steps),l=rc(t.expectedResults),s=t.tags.split(",").map(e=>e.trim()).filter(e=>e.length>0);return{...t.title!==e.title?{title:t.title}:{},...!rd(n,e.preconditions)?{preconditions:n}:{},...!rd(a,e.steps)?{steps:a}:{},...!rd(l,e.expectedResults)?{expectedResults:l}:{},...t.priority!==e.priority?{priority:t.priority}:{},...t.riskClass!==e.riskClass?{riskClass:t.riskClass}:{},...!rd(s,e.tags)?{tags:s}:{}}}function rm({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 rh({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 rp({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 rf({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 rg({candidate:e,onSave:t,onCancel:l}){let[s,i]=(0,a.useState)(()=>({title:e.title,preconditions:e.preconditions.join("\n"),steps:e.steps.join("\n"),expectedResults:e.expectedResults.join("\n"),priority:e.priority,riskClass:e.riskClass,tags:e.tags.join(", ")})),[r,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(!1),[u,m]=(0,a.useState)(!1),h=(0,a.useRef)(null),p=(e,t)=>{o(null),m(!1),i(n=>({...n,[e]:t}))},f=(0,a.useCallback)(()=>{c||(!(Object.keys(ru(e,s)).length>0)||u?l():m(!0))},[e,u,l,c,s]);(0,a.useEffect)(()=>{let e=e=>{if("Escape"!==e.key||c)return;let t=h.current;null!==t&&t.contains(document.activeElement)&&f()};return document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e)}},[f,c]),(0,a.useEffect)(()=>{h.current?.querySelector("input.qi-edit-input")?.focus()},[]);let g=`qi-edit-${e.id}`,v=async()=>{if(!c){d(!0),o(null);try{await t(ru(e,s))}catch(e){o(iR(e))}finally{d(!1)}}};return(0,n.jsxs)("form",{ref:h,className:"qi-edit-form","aria-label":`Edit ${e.title}`,"aria-busy":c,onSubmit:e=>{e.preventDefault(),v()},children:[(0,n.jsx)(rh,{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)(rf,{onCancel:f,saving:c}),(0,n.jsx)(rm,{id:`${g}-preconditions`,label:"Preconditions (one per line)",value:s.preconditions,disabled:c,onChange:e=>{p("preconditions",e)}}),(0,n.jsx)(rm,{id:`${g}-steps`,label:"Steps (one per line)",value:s.steps,disabled:c,onChange:e=>{p("steps",e)}}),(0,n.jsx)(rm,{id:`${g}-expected`,label:"Expected results (one per line)",value:s.expectedResults,disabled:c,onChange:e=>{p("expectedResults",e)}}),(0,n.jsx)(rp,{id:`${g}-priority`,label:"Priority",value:s.priority,options:rr,disabled:c,onChange:e=>{p("priority",e)}}),(0,n.jsx)(rp,{id:`${g}-risk`,label:"Risk class",value:s.riskClass,options:ro,disabled:c,onChange:e=>{p("riskClass",e)}}),(0,n.jsx)(rh,{id:`${g}-tags`,label:"Tags (comma-separated)",value:s.tags,disabled:c,onChange:e=>{p("tags",e)}})]})}let rv=new Set(["approved","rejected","withdrawn"]);function rx({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 rb({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 ry({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=rv.has(t),u=(0,a.useId)(),m=d?u:i;return(0,n.jsxs)("div",{className:"qi-cand-actions",role:"group","aria-label":"Review decision",children:[d?(0,n.jsx)("p",{id:u,className:"qi-cand-governance-note",role:"note",children:"This review decision is final — reopen to change it."}):null,(0,n.jsx)(rb,{className:"qi-btn qi-btn-approve",label:c("approve")?"Saving…":"Approve",pressed:"approved"===t,disabled:s||o||d,describedBy:m,onActivate:()=>{l(e,"approve")}}),(0,n.jsx)(rb,{className:"qi-btn qi-btn-reject",label:c("reject")?"Saving…":"Reject",pressed:"rejected"===t,disabled:s||o||d,describedBy:m,onActivate:()=>{l(e,"reject")}}),(0,n.jsx)(rb,{className:"qi-btn qi-btn-secondary",label:c("request-changes")?"Saving…":"Request changes",pressed:"changes-requested"===t,disabled:s||o||d,describedBy:m,onActivate:()=>{l(e,"request-changes")}}),d?(0,n.jsx)(rb,{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 rj({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)(iE,{state:e.reviewState})]})]}),void 0!==e.weakTestFlag?(0,n.jsx)(iF,{flag:e.weakTestFlag}):null,void 0!==e.qualityVerdict?(0,n.jsx)(iO,{verdict:e.qualityVerdict}):null,(0,n.jsx)(rx,{items:e.preconditions,label:"Preconditions"}),(0,n.jsx)(rx,{items:e.steps,label:"Steps"}),(0,n.jsx)(rx,{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)(ry,{candidateId:e.id,state:e.reviewState,onReview:t,disabled:l,describedBy:s,pendingReview:r}):null]})]})}function rw({candidate:e,onReview:t,onEdit:l,actionsDisabled:s=!1,describedBy:i,pendingReview:r}){let[o,c]=(0,a.useState)(!1),d=(0,a.useRef)(null),u=(0,a.useRef)(!1);(0,a.useEffect)(()=>{u.current&&!o&&d.current?.focus(),u.current=o},[o]);let m=async t=>{void 0!==l&&await l(e.id,t),c(!1)};return(0,n.jsx)("li",{className:o?"qi-cand-card qi-cand-card-editing":"qi-cand-card",children:o&&void 0!==l?(0,n.jsx)(rg,{candidate:e,onSave:m,onCancel:()=>{c(!1)}}):(0,n.jsx)(rj,{candidate:e,onReview:t,actionsDisabled:s,describedBy:i,pendingReview:r,editButtonRef:d,onStartEdit:void 0!==l?()=>{c(!0)}:void 0})})}function rk({candidates:e,onReview:t,onEdit:l,actionsDisabled:s=!1,actionsDisabledReason:i,pendingReview:r}){let[o,c]=(0,a.useState)(25),d=(0,a.useId)(),u=s&&void 0!==i;if(0===e.length)return(0,n.jsxs)("div",{className:"lk-empty",children:[(0,n.jsx)("p",{className:"lk-empty-title",children:"No test cases"}),(0,n.jsx)("p",{className:"lk-empty-body",children:"This run produced no generated test cases."})]});let m=[...e].sort((e,t)=>!!e.tags.includes("source:deterministic-baseline")-!!t.tags.includes("source:deterministic-baseline")).slice(0,o);return(0,n.jsxs)("div",{className:"qi-cand-pane",children:[u?(0,n.jsx)("p",{id:d,className:"qi-cand-governance-note",role:"note",children:i}):null,(0,n.jsx)("ul",{className:"qi-cand-cards","aria-label":"Test case list",children:m.map(e=>(0,n.jsx)(rw,{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 rN(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 rS(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 rC({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:"✓"}),rN(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:"⚠"}),rN(e)]})}function rI({runId:e,connectedSources:t,onRegenerated:l,reCheckImpl:s=iw,regenerateImpl:i=ik}){let[r,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(null),u=null!==c,[m,h]=(0,a.useState)(null),[p,f]=(0,a.useState)(null),g=(0,a.useRef)(null),v=(0,a.useRef)(null),x=(0,a.useCallback)(()=>{u||(async()=>{d("check"),h(null),f(null);try{o(await s(e,t))}catch(e){h(iR(e))}finally{d(null)}})()},[u,s,e,t]),b=(0,a.useCallback)(()=>{u||(async()=>{d("regenerate"),h(null);try{let n=await i(e,t);document.activeElement===v.current&&g.current?.focus(),f(n),o(null),l?.(n)}catch(e){h(iR(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?rS(p):null!==r?rN(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!==m?(0,n.jsx)("p",{className:"lk-alert",role:"alert",children:m}):null,null!==r?(0,n.jsx)(rC,{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:rS(p)}):null]})}let rE={"traceability-csv":"csv","traceability-markdown":"markdown"},rR=[{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 r$(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 rA({runId:e,exportImpl:t=iN,traceabilityImpl:l=iS}){let[s,i]=(0,a.useState)("csv"),[r,o]=(0,a.useState)(!1),[c,d]=(0,a.useState)(null),[u,m]=(0,a.useState)(null),[h,p]=(0,a.useState)(null),[f,g]=(0,a.useState)(!1),v=rR.find(e=>e.id===s),x=v?.tms??!1,b=(0,a.useCallback)(async()=>{let n=rE[s];if(void 0!==n){let t=await l(e,n);r$(t.filename,t.contentType,t.body),p(t.filename);return}let a=await t(e,s,{dryRun:x,approvedOnly:f});a.dryRun?m(`${a.candidateCount.toString()} test case${1===a.candidateCount?"":"s"} \xb7 ${a.byteLen.toString()} bytes
|
|
108
|
+
|
|
109
|
+
${a.preview}`):(r$(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),m(null),p(null);try{await b()}catch(e){d(iR(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),m(null),d(null),p(null)},children:rR.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!==h?`Downloaded ${h}`: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!==h?(0,n.jsx)("p",{className:"qi-export-success","data-testid":"qi-export-success",children:`Downloaded ${h}`}):null,null!==u?(0,n.jsx)("pre",{className:"qi-export-preview",role:"region","aria-label":"Export preview",tabIndex:0,"data-testid":"qi-export-preview",children:u}):null,null!==c?(0,n.jsx)("p",{className:"lk-alert",role:"alert","data-testid":"qi-export-error",children:c}):null]})}let rT="keiko.qi.reviewerLabel",rM="Set a reviewer label to review or edit candidates.";function rq({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)(iq,{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)(iD,{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:iC[e.reviewState]})]}),(0,n.jsxs)("div",{className:"qi-run-summary-item",children:[(0,n.jsx)("dt",{children:"Requested"}),(0,n.jsx)("dd",{children:i$(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:i$(e.completedAt)})]}):null]})}let rL={"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 rP({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:rL[e.kind]??e.kind}),(0,n.jsx)(iP,{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"},rF={covered:"qi-cov-covered","weakly-covered":"qi-cov-weak",uncovered:"qi-cov-uncovered"},rz={uncovered:0,"weakly-covered":1,covered:2};function rO({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)=>rz[e.status]-rz[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=rF[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 rK({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 r_({runId:e,connectedSources:t,onRegenerated:l,fetchDetailImpl:s=ig,reviewImpl:i=iy,editImpl:r=ij,reCheckImpl:o,regenerateImpl:c}){let[d,u]=(0,a.useState)(null),[m,h]=(0,a.useState)(!0),[p,f]=(0,a.useState)(null),[g,v]=(0,a.useState)(null),[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,h(!0),f(null);try{let n=await s(e);R.current===t&&u(n)}catch(e){R.current===t&&f(iR(e))}finally{R.current===t&&h(!1)}},[s,e]);(0,a.useEffect)(()=>{$()},[$]),(0,a.useEffect)(()=>{j(function(){try{return window.localStorage.getItem(rT)??""}catch{return""}}()),k(!0)},[]),(0,a.useEffect)(()=>{if(w)try{window.localStorage.setItem(rT,y)}catch{}},[y,w]);let A=y.trim(),T=A.length>0,M=(0,a.useCallback)((t,n)=>{T&&null===x&&(b({candidateId:t,action:n}),(async()=>{v(null);try{await i(e,n,t,A),await $();let a=iC["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(iR(e))}finally{b(null)}})())},[T,x,i,e,A,$,d]),q=(0,a.useCallback)(async(t,n)=>{if(!T)throw Error(rM);await r(e,t,n,A),await $()},[r,T,e,A,$]);return(0,n.jsxs)("div",{className:"qi-run-card","data-testid":"qi-run-card",children:[(0,n.jsx)("header",{className:"qi-run-card-head",children:(0,n.jsx)("span",{className:"qi-run-id qi-monospace",title:e,role:"heading","aria-level":2,"aria-label":`Quality Intelligence run ${e}`,children:e})}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:m?"Loading run…":null===p&&null!==d?`Run loaded: ${d.totals.candidates.toString()} test case${1===d.totals.candidates?"":"s"}.`:""}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","data-testid":"qi-review-announce",children:C}),(0,n.jsx)("div",{className:"qi-run-card-body","aria-busy":m,children:m&&null===d?(0,n.jsx)(i_,{}):null!==p?(0,n.jsx)(iB,{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":!T,"aria-describedby":T?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:T?"":rM})]}),(0,n.jsx)(rq,{detail:d}),(0,n.jsx)(rP,{detail:d}),(0,n.jsx)(rO,{detail:d}),void 0!==t&&t.length>0?(0,n.jsx)(rI,{runId:e,connectedSources:t,onRegenerated:l,reCheckImpl:o,regenerateImpl:c}):(0,n.jsx)(rK,{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)(rA,{runId:e}):null]}),(0,n.jsx)(rk,{candidates:d.candidates,onReview:M,pendingReview:x,onEdit:q,actionsDisabled:!T,actionsDisabledReason:rM})]})]})})]})}let rB={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 rU({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 rW({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 rH({type:e,lifecycle:t,activity:l,throughputCount:s,animateOverride:i=!0,highContrast:r,onClick:o,className:c=""}){let[d,u]=(0,a.useState)(!1);(0,a.useEffect)(()=>{if(void 0!==r)return;let e=window.matchMedia("(prefers-contrast: more)"),t=e=>{u(e)};t(e.matches);let n=e=>{t(e.matches)};return e.addEventListener("change",n),()=>{e.removeEventListener("change",n)}},[r]);let m=rB[l]??rB.inactive,h=n$[e],p=r??d,f="high-throughput"===l&&void 0!==s?`${m.label} (${String(s)})`:m.label,g=`${h.displayName} — ${m.ariaDescription}`,v=m.animated&&i,x=p?{color:m.textColor,background:"var(--card)",border:`1px solid ${m.textColor}`}:{color:m.textColor,background:m.bgColor,border:void 0!==m.borderColor?`1px solid ${m.borderColor}`:void 0};return(0,n.jsx)("span",{role:"status","aria-live":"polite","aria-atomic":"true",className:`rb-edge-badge ${c}`.trim(),"data-activity-state":l,"data-high-contrast":p?"true":void 0,children:void 0!==o?(0,n.jsxs)("button",{type:"button",className:"rb-edge-badge-btn",style:x,"aria-label":g,onClick:o,children:[(0,n.jsx)("span",{"aria-hidden":"true",children:(0,n.jsx)(rU,{shape:m.iconShape,color:m.textColor,animated:v,highContrast:p})}),(0,n.jsx)("span",{className:"visually-hidden",children:m.ariaDescription}),(0,n.jsx)("span",{"aria-hidden":"true",className:"rb-edge-badge-label",children:f}),(0,n.jsx)("span",{className:"rb-edge-badge-type",children:h.displayName}),(0,n.jsx)(rW,{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)(rU,{shape:m.iconShape,color:m.textColor,animated:v,highContrast:p})}),(0,n.jsx)("span",{className:"visually-hidden",children:m.ariaDescription}),(0,n.jsx)("span",{"aria-hidden":"true",className:"rb-edge-badge-label",children:f}),(0,n.jsx)("span",{className:"rb-edge-badge-type",children:h.displayName}),(0,n.jsx)(rW,{state:t})]})})}let rG="keiko.relationships.density",rV={minimal:5,standard:25,dense:512};function rY(){try{let e=window.localStorage.getItem(rG);if("minimal"===e||"standard"===e||"dense"===e)return e}catch{}return"minimal"}function rQ(e,t){return void 0===e||0===e.length?[]:e.split(",").map(e=>e.trim()).filter(e=>t.includes(e))}function rJ(e){return{types:rQ(e.relType,nE),lifecycles:rQ(e.relLifecycle,nR),activities:rQ(e.relActivity,["inactive","queued","active","processing","completed","failed","blocked","degraded","high-throughput"]),srcKinds:rQ(e.relSrcKind,nC),tgtKinds:rQ(e.relTgtKind,nC)}}let rX={"high-throughput":0,processing:1,active:2,blocked:3,failed:4,degraded:5,queued:6,completed:7,inactive:8};function rZ(e,t,n){return n.get(e)??function(e){switch(e){case"blocked":return"blocked";case"stale":return"degraded";default:return"inactive"}}(t)}function r0({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:rY()}),[m,h]=(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(rG,e)}catch{}},[s]);(0,a.useEffect)(()=>{let t=e.relDensity;"minimal"===t||"standard"===t||"dense"===t?u(t):u(rY())},[e.relDensity]),(0,a.useEffect)(()=>{S(e.relType??"")},[e.relType]);let E=(0,a.useCallback)(async()=>{b(null),v(!0);try{let t=rJ(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 nF({lifecycle:n,type:a,sourceKind:l,targetKind:s,limit:rV[d]});f(i.entries),j(i.truncated)}catch(e){b(e instanceof nM?e.message:nT)}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(),h(e=>!e)):"Escape"===e.key?h(!1):"/"===e.key&&(e.preventDefault(),k.current?.focus()))}},[]);let R=(0,a.useCallback)(e=>{let t=e.target.value;S(t),null!==C.current&&clearTimeout(C.current),C.current=setTimeout(()=>{s({relType:t.length>0?t:void 0})},250)},[s]),$=(0,a.useMemo)(()=>{let t=rJ(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(rZ(e.id,e.lifecycle,i)))).slice(0,rV[d])},[i,d,e,p]),A=$.slice(0,25),T=$.slice(25),M=T.length,q=M>0?function(e,t){let n=new Map;for(let a of e){let e=rZ(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]:(rX[e[0]]??Number.MAX_SAFE_INTEGER)-(rX[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(", ")}(T,i):"",L=y?`Showing first ${String($.length)} relationships — more available.`:`Showing ${String($.length)} relationship${1!==$.length?"s":""}.`,P=(e.relType??"").trim().length>0||(e.relActivity??"").trim().length>0||(e.relSrcKind??"").trim().length>0||(e.relTgtKind??"").trim().length>0||(e.relLifecycle??"").trim().length>0&&"active"!==e.relLifecycle,D=rQ(e.relLifecycle,nR),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":m?"true":void 0,children:[(0,n.jsxs)("div",{role:"group","aria-label":"Relationship density",style:{display:"flex",flexWrap:"wrap",gap:4,marginBottom:8},children:[["minimal","standard","dense"].map(e=>(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-pressed":d===e,onClick:()=>I(e),style:{textTransform:"capitalize",minWidth:24,minHeight:24},children:e},e)),(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-pressed":m,onClick:()=>h(e=>!e),title:"Toggle focus mode (F)","aria-label":`Focus mode: ${m?"on":"off"}`,style:{minWidth:24,minHeight:24},children:"Focus"})]}),(0,n.jsxs)("div",{style:{marginBottom:8},children:[(0,n.jsx)("label",{htmlFor:"rel-type-filter",className:"rb-row-k",style:{display:"block",marginBottom:2,fontSize:11,fontWeight:600},children:"Filter by type (press / to focus)"}),(0,n.jsx)("input",{id:"rel-type-filter",ref:k,type:"text",list:"rel-type-filter-options",value:N,onChange:R,placeholder:"e.g. reads-context","aria-label":"Filter relationships by type",style:{width:"100%",background:"var(--inset)",border:"1px solid var(--line)",borderRadius:9,padding:"4px 8px",minHeight:24,color:"var(--fg)",fontSize:13}}),(0,n.jsx)("datalist",{id:"rel-type-filter-options",children: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:nR.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:L}),y&&(0,n.jsx)("div",{"data-testid":"list-truncation-note",style:{fontSize:11,color:"var(--fg-muted)",marginBottom:6},children:L}),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:P?"No relationships match the current filter.":'No active relationships yet. Create one with "+ New relationship", or connect a source — connections appear here automatically.'}),$.length>0&&(0,n.jsxs)("div",{role:"list","aria-label":"Relationships","aria-busy":g||void 0,style:{display:"flex",flexDirection:"column",gap:2,opacity:g?.6:1,transition:"opacity 0.15s ease"},children:[A.map(e=>{let a=e.id===t,s=rZ(e.id,e.lifecycle,i),d=m&&a,u=m&&!a;return(0,n.jsx)("div",{role:"listitem",style:{opacity:u?.4:1},children:(0,n.jsxs)("button",{type:"button","aria-pressed":a,"aria-label":`${e.type} relationship from ${e.source.kind} ${e.source.id} to ${e.target.kind} ${e.target.id}, lifecycle: ${e.lifecycle}`,title:`${e.source.id} → ${e.target.id}`,onClick:()=>l(e.id),onKeyDown:t=>{var n;return n=e.id,void(("Enter"===t.key||" "===t.key)&&(t.preventDefault(),l(n)))},"data-incident":d?"true":void 0,className:"rel-row",children:[(0,n.jsx)(rH,{type:e.type,lifecycle:e.lifecycle,activity:s,throughputCount:r.get(e.id),animateOverride:o,highContrast:c}),(0,n.jsxs)("span",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column"},children:[(0,n.jsxs)("span",{style:{fontSize:12,color:"var(--fg)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.source.kind," → ",e.target.kind]}),(0,n.jsx)("span",{style:{fontSize:10.5,color:"var(--fg-muted)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.summary??`${e.source.id} → ${e.target.id}`})]}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--fg-muted)",whiteSpace:"nowrap"},children:e.lifecycle})]})},e.id)}),M>0&&(0,n.jsxs)("div",{role:"listitem","aria-live":"polite",style:{fontSize:12,color:"var(--fg-muted)",padding:"4px 6px"},"data-testid":"animation-cap-aggregate",children:["+",String(M)," more: ",q]})]})]})}function r1(){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 r2({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)(r1,{})]})}function r3({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)(r2,{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)(r2,{title:"Upstream impact",help:"Objects that depend on this relationship's source.",report:t,onSelectRelationship:a})]})}let r4={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)"}},r6={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 r5({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 r8({children:e,style:t}){return(0,n.jsx)("div",{className:"rb-section-label",role:"heading","aria-level":3,style:t,children:e})}function r7({rel:e}){let t=n$[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 r9({label:e,kind:t,id:a}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)(r8,{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 oe({lifecycle:e}){let t=`lifecycle-desc-${e}`,a=r4[e]??r4.draft;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(r8,{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:r6[e]})})]})]})}function ot({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)(r8,{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)(rH,{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 on(){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(r8,{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 oa({auditRows:e,loading:t,error:a,onRetry:l,onLoadMore:s,hasMore:i}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(r8,{children:"Audit history"}),t&&(0,n.jsx)(r5,{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 ol({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)(r8,{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 os({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)(r8,{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)(r3,{outgoing:l,incoming:s,onSelectRelationship:o})})]})}function oi({codes:e,messages:t,deniedAt:a}){return 0===e.length?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(r8,{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 or(e){return null==e||0===e.length?null:{codes:e.map(e=>e.code),messages:e.map(e=>e.message)}}function oo({rel:e,onReconnect:t,onArchive:a,onRevoke:l,onViewImpact:s,onViewEvidence:i,mutating:r}){let o=e.lifecycle,c="blocked"===o,d="active"===o,u="active"===o||"blocked"===o||"archived"===o,m="active"===o;return(0,n.jsxs)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginTop:8},children:[(0,n.jsx)("button",{type:"button",className:`arun-btn${c?" primary":""}`,"aria-disabled":!c||r,"aria-label":"Reconnect — only available for blocked relationships",title:c?"Reconnect this relationship":"Only blocked relationships can be reconnected.",disabled:!c||r,onClick:c?t:void 0,children:"Reconnect"}),(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":!d||r,"aria-label":"Archive — only available for active relationships",title:d?"Archive this relationship":"Only active relationships can be archived.",disabled:!d||r,onClick:d?a:void 0,children:"Archive"}),(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":!u||r,"aria-label":"Revoke relationship",title:u?"Revoke this relationship":"Already revoked or superseded.",disabled:!u||r,onClick:u?l:void 0,style:{color:u?"var(--danger)":void 0},children:"Revoke"}),(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":!m,"aria-label":"View impact analysis",title:m?"Toggle the impact analysis card":"Impact analysis is unavailable in this state.",disabled:!m,onClick:m?s:void 0,children:"View impact"}),(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-label":"View evidence references",title:"Jump to the evidence references section",onClick:i,children:"View evidence"})]})}function oc({relationshipId:e,densityMode:t="minimal",onClearFocus:l,onViewImpact:s,activityMap:i=new Map,throughputMap:r=new Map,animateBadges:o=!0,highContrast:c=!1}){let[d,u]=(0,a.useState)(null),[m,h]=(0,a.useState)(null),[p,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(null),[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,A=null===C?null:C.relationships.length,[T,M]=(0,a.useState)(!1),q=(0,a.useRef)(null),L=(0,a.useRef)(0),P=(0,a.useCallback)(async e=>{let t=++L.current;v(null),f(!0),k(null),S(null),I(null),R(!1);let n=setTimeout(()=>{L.current===t&&M(!0)},500);q.current=n;try{let[n,a]=await Promise.all([nz(e),nB(e)]);if(L.current!==t)return;u(n),h(a);try{let[n,a]=await Promise.all([n_(e,{direction:"outgoing",maxDepth:3,maxRelationships:512}),n_(e,{direction:"incoming",maxDepth:3,maxRelationships:512})]);if(L.current!==t)return;S(n),I(a)}catch{}}catch(e){if(L.current!==t)return;v(e instanceof nM?e.message:nT)}finally{q.current===n?(clearTimeout(n),q.current=null):clearTimeout(n),L.current===t&&(f(!1),M(!1))}},[]);(0,a.useEffect)(()=>{if(null===e){L.current+=1,null!==q.current&&(clearTimeout(q.current),q.current=null),u(null),h(null),v(null),k(null),M(!1),f(!1);return}return P(e),()=>{null!==q.current&&(clearTimeout(q.current),q.current=null)}},[e,P]);let D=(0,a.useCallback)(async e=>{if(null!==d){b(!0),j(null),k(null);try{let t=crypto.randomUUID(),{relationship:n}=await nO(d.id,{transition:{to:e}},String(d.etag),t);u(n),h(null),await P(d.id)}catch(e){j(e instanceof nM?e.message:"Mutation failed. Please retry."),k(e instanceof nM?or(e.reasons):null)}finally{b(!1)}}},[d,P]),F=(0,a.useCallback)(()=>void D("draft"),[D]),z=(0,a.useCallback)(()=>void D("archived"),[D]),O=(0,a.useCallback)(async()=>{if(null!==d&&window.confirm(`Revoke relationship "${d.type}"? This cannot be undone.`)){b(!0),j(null),k(null);try{let e=crypto.randomUUID(),t=await nK(d.id,String(d.etag),e);u(t)}catch(e){j(e instanceof nM?e.message:"Revoke failed. Please retry."),k(e instanceof nM?or(e.reasons):null)}finally{b(!1)}}},[d]),K=(0,a.useCallback)(()=>{R(e=>!e)},[]),_=(0,a.useCallback)(e=>{s?.(e)},[s]),B=(0,a.useRef)(null),U=(0,a.useCallback)(()=>{B.current?.scrollIntoView?.({block:"start"})},[]);if(null===e)return(0,n.jsxs)("div",{className:"tw-pad","data-testid":"relationship-inspector-panel",children:[(0,n.jsx)(r8,{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=or(m?.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 P(e),children:"Retry"})]}),null!==y&&(0,n.jsxs)("div",{className:"lk-alert",role:"alert","aria-live":"assertive",children:[(0,n.jsx)("span",{children:y}),(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>j(null),children:"Dismiss"})]}),p&&T&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(r8,{style:{marginTop:0},children:"Relationship"}),(0,n.jsx)(r5,{lines:4}),(0,n.jsx)(r5,{lines:3})]}),!p&&null===g&&null===d&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(r8,{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)(r8,{style:{marginTop:0},children:"Relationship"}),(0,n.jsx)(r7,{rel:d}),(0,n.jsx)(r9,{label:"Source",kind:d.source.kind,id:d.source.id}),(0,n.jsx)(r9,{label:"Target",kind:d.target.kind,id:d.target.id}),(0,n.jsx)(oe,{lifecycle:d.lifecycle}),(0,n.jsx)(ot,{type:d.type,lifecycle:d.lifecycle,activity:G,throughputCount:V,animateBadges:o,highContrast:c,transitions:m?.lifecycle??[],densityMode:t}),(0,n.jsx)(on,{}),(0,n.jsx)(oa,{auditRows:m?.lifecycle??[],loading:!1,error:null,onRetry:()=>void P(e),onLoadMore:()=>{},hasMore:!1}),(0,n.jsx)("div",{ref:B,children:(0,n.jsx)(ol,{rel:d})}),(0,n.jsx)(os,{relationshipId:d.id,forwardCount:$,reverseCount:A,outgoing:N,incoming:C,expanded:E,onToggle:K,onSelectRelationship:_}),H&&null!==W&&(0,n.jsx)(oi,{codes:W.codes,messages:W.messages}),(0,n.jsx)(oo,{rel:d,onReconnect:F,onArchive:z,onRevoke:()=>void O(),onViewImpact:K,onViewEvidence:U,mutating:x})]})]})}let od=new Set(["kind","id","state","timestamp","count"]);function ou(e){return`${e.kind}: ${e.id}`}function om({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 oh({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 ${ou(e.source)} to ${ou(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:[ou(e.source)," → ",ou(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)(om,{category:e.label.toLowerCase()})]})}function op({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:ou(e)})},`${e.kind}:${e.id}`))}),e.orphanedEndpointsTruncated&&(0,n.jsx)(om,{category:"orphaned endpoints"})]})}function of({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 nU();i(e)}catch(e){d(e instanceof nM?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:nR.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)(oh,{category:t,onSelectRelationship:e},t.key)),(0,n.jsx)(op,{findings:s.findings})]})]})]})}let og={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 ov(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ox(e){return"string"==typeof e&&e.length>0}function ob(e,t,n){return void 0===n?{code:e,message:t}:{code:e,field:n,message:t}}function oy(e,t,n){return ov(e)?ox(e.kind)?ox(e.id)?!!ox(e.workspaceId)||(n.push(ob("denied/schema-version-unsupported",`${t}.workspaceId must be a non-empty string`,`${t}.workspaceId`)),!1):(n.push(ob("denied/schema-version-unsupported",`${t}.id must be a non-empty string`,`${t}.id`)),!1):(n.push(ob("denied/schema-version-unsupported",`${t}.kind must be a non-empty string`,`${t}.kind`)),!1):(n.push(ob("denied/schema-version-unsupported",`${t} must be an object`,t)),!1)}function oj(e,t,n){ox(e[t])||n.push(ob("denied/schema-version-unsupported",`${t} must be a non-empty string`,t))}function ow(e,t){let n=e.kind;return nC.includes(n)?null:ob("denied/schema-version-unsupported",`${t}.kind is not a known object kind`,`${t}.kind`)}function ok(e,t,n){"missing"===t?n.push(ob("source"===e?"denied/non-existent-source":"denied/non-existent-target",`${e} endpoint does not exist`,e)):"tombstoned"===t?n.push(ob("denied/endpoint-tombstoned",`${e} endpoint has been tombstoned`,e)):"retired"===t?n.push(ob("denied/endpoint-retired",`${e} endpoint has been retired`,e)):"unavailable"===t&&n.push(ob("denied/endpoint-unavailable",`${e} endpoint is unavailable`,e))}function oN(e,t){let n=e.kind;return nI.includes(n)?null:ob("denied/object-kind-not-yet-supported",`${t}.kind "${n}" is reserved for a future release`,`${t}.kind`)}function oS(){return{type:"reads-context",sourceKind:"workflow-run",sourceId:"",targetKind:"memory",targetId:"",summary:""}}let oC=new Set(["denied/path-not-contained","denied/cross-workspace","denied/payload-content-not-permitted"]);function oI(e){return e?.codes.some(e=>oC.has(e))===!0}function oE({onClose:e}){let[t,l]=(0,a.useState)(oS),[s,i]=(0,a.useState)([]),[r,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(!1),[u,m]=(0,a.useState)(!1),h=(0,a.useRef)(null),p=(0,a.useRef)(null),f="rel-create-dialog-title",g="rel-create-dialog-desc";(0,a.useEffect)(()=>{p.current?.focus()},[]);let v=(0,a.useCallback)(e=>{let t=h.current;if(null===t)return;let n=Array.from(t.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')).filter(e=>!e.hasAttribute("disabled")),a=n[0],l=n[n.length-1];"Tab"===e.key&&(e.shiftKey?document.activeElement===a&&(e.preventDefault(),l?.focus()):document.activeElement===l&&(e.preventDefault(),a?.focus()))},[]),x=(0,a.useCallback)(t=>{"Escape"===t.key&&e(null)},[e]);(0,a.useEffect)(()=>{let e=h.current;if(null!==e)return e.addEventListener("keydown",v),e.addEventListener("keydown",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(!ov(e))return{errors:[ob("denied/schema-version-unsupported","relationship must be an object")]};let n=[];oj(e,"id",n),oj(e,"workspaceId",n),oj(e,"createdAt",n),oj(e,"updatedAt",n),(!("number"==typeof(t=e.etag)&&Number.isInteger(t)&&Number.isFinite(t))||e.etag<0)&&n.push(ob("denied/schema-version-unsupported","etag must be a non-negative finite integer","etag"));let a=oy(e.source,"source",n),l=oy(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?ob("denied/schema-version-unsupported",'schemaVersion must be the literal "1"',"schemaVersion"):null;if(s)return[s];let i=ox(a=e.type)?nE.includes(a)?null:ob("denied/schema-version-unsupported","type is not a known relationship type","type"):ob("denied/schema-version-unsupported","type must be a non-empty string","type");if(i)return[i];let r=ow(t,"source"),o=ow(n,"target");if(null!==r||null!==o){let e=[];return null!==r&&e.push(r),null!==o&&e.push(o),e}let c=ox(l=e.lifecycleState)?nR.includes(l)?null:ob("denied/schema-version-unsupported","lifecycleState is not a known lifecycle state","lifecycleState"):ob("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&&ok("source",e.endpointResolver.source,t),"missing"===e.endpointResolver.target&&ok("target",e.endpointResolver.target,t),t}(void 0);if(null!==i&&i.length>0)return{ok:!1,errors:i};let r=function(e,t,n,a){var l,s,i,r,o;let c,d,u,m,h,p,f=[],g=e.type,v=e.lifecycleState,x=oN(t,"source");x&&f.push(x);let b=oN(n,"target");b&&f.push(b),null===x&&null===b&&(l=t.kind,s=n.kind,"denied/source-kind-not-allowed"===(d=(c=n$[g]).validSourceKinds.includes(l)?c.validTargetKinds.includes(s)?null:"denied/target-kind-not-allowed":"denied/source-kind-not-allowed")?f.push(ob("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(ob("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?ob("denied/cardinality-exceeded","produces-evidence already exists for this source workflow-run"):"starts-workflow"===g&&"number"==typeof u.startsWorkflowForTarget&&u.startsWorkflowForTarget>=1?ob("denied/cardinality-exceeded","starts-workflow already exists for this target workflow-run"):null:null;y&&f.push(y),(m=t.kind===n.kind&&t.id===n.id?ob("denied/cycle-forbidden","source and target refer to the same endpoint"):null)&&f.push(m),(h="depends-on"===g&&a?.dependsOnReverseEdgeExists===!0?ob("denied/cycle-forbidden","depends-on reverse edge already exists for this endpoint pair"):null)&&f.push(h);let j=(i=e.workspaceId,t.workspaceId!==i||n.workspaceId!==i?ob("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)||og[p].includes(v)?null:ob("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&&ok("source",r.endpointResolver.source,o),"missing"!==r.endpointResolver.target&&ok("target",r.endpointResolver.target,o)),function(e){let t=[];if(void 0===e.metadata||null===e.metadata)return t;if(!ov(e.metadata))return t.push(ob("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(ob("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 m(!1):(b.current=setTimeout(async()=>{m(!0);try{if(await nP({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=>oI(e)?e:null)}catch(t){if(e!==y.current)return;t instanceof nM&&t.reasons.length>0?o({source:"preview",codes:t.reasons.map(e=>e.code),messages:t.reasons.map(e=>e.message)}):o(null)}finally{e===y.current&&m(!1)}},250),()=>{null!==b.current&&clearTimeout(b.current)})},[t,s]),(0,a.useEffect)(()=>{o(e=>e?.source!=="submit"||oI(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 nD({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 nM?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:[nT]})}finally{d(!1)}}},[j,t,e]),N=(0,a.useCallback)(e=>{"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&k()},[k]),S=n$[t.type],C=oI(r),I=[s.length>0?"rel-create-client-hints":null,null!==r?"rel-create-server-denial":null].filter(e=>null!==e),E=(0,n.jsx)("div",{className:"cmdk-overlay",onPointerDown:()=>e(null),"data-testid":"rel-create-overlay",children:(0,n.jsxs)("div",{ref:h,role:"dialog","aria-modal":"true","aria-labelledby":f,"aria-describedby":g,className:"cmdk",style:{maxWidth:480,width:"100%"},onPointerDown:e=>e.stopPropagation(),onKeyDown:N,"data-testid":"rel-create-dialog",children:[(0,n.jsxs)("div",{className:"cmdk-input",style:{borderBottom:"1px solid var(--line)"},children:[(0,n.jsx)("span",{id:f,style:{fontWeight:600,fontSize:14,color:"var(--fg)"},children:"Create relationship"}),(0,n.jsx)("span",{id:g,className:"visually-hidden",children:"Create a new relationship between two workspace endpoints."}),(0,n.jsx)("button",{type:"button",className:"palette-x",onClick:()=>e(null),"aria-label":"Close",title:"Close",style:{marginLeft:"auto"},children:(0,n.jsx)(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:n$[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:nI.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:nI.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,ti.createPortal)(E,document.body)}let oR={};function o$(){let{activityMap:e,throughputMap:t,animate:l}=function(){let e=(0,a.useRef)(new Map),t=(0,a.useRef)("u"<typeof document||"visible"===document.visibilityState),[n,l]=(0,a.useState)(new Map),[s,i]=(0,a.useState)(new Map),r=(0,a.useRef)(new Map),o=(0,a.useRef)(new Map),[c,d]=(0,a.useState)(()=>window.matchMedia("(prefers-reduced-motion: reduce)").matches),[u,m]=(0,a.useState)(!1),h=(0,a.useCallback)(()=>{m(!0)},[]),p=(0,a.useCallback)((t,n)=>{let a=new Map(r.current),s=new Set,c=new Set,d=!1;for(let[l,i]of a){let r=t-(e.current.get(l)??0);r>=6e4&&"inactive"!==i&&(a.set(l,"inactive"),c.add(l),d=!0),!n&&r>=12e4&&(a.delete(l),s.add(l),c.add(l),d=!0)}if(a.size>512)for(let t of Array.from(a.keys()).sort((t,n)=>{let l=a.get(t),s=a.get(n);return"inactive"===l&&"inactive"!==s?-1:"inactive"!==l&&"inactive"===s?1:(e.current.get(t)??0)-(e.current.get(n)??0)}).slice(0,a.size-512))a.delete(t),s.add(t),c.add(t),d=!0;if(d&&(r.current=a,l(a)),s.size>0)for(let t of s)e.current.delete(t);if(c.size>0){let e=!1,t=new Map(o.current);for(let n of c)t.delete(n)&&(e=!0);e&&(o.current=t,i(t))}},[]);(0,a.useEffect)(()=>{let e=window.matchMedia("(prefers-reduced-motion: reduce)"),t=e=>{d(e.matches)};return e.addEventListener("change",t),()=>{e.removeEventListener("change",t)}},[]);let f=(0,a.useCallback)(n=>{if(!t.current)return;let a=Date.now();a-(e.current.get(n.id)??0)<2e3||(e.current.set(n.id,a),l(e=>{let t=new Map(e);return t.set(n.id,n.state),r.current=t,t}),"high-throughput"===n.state&&void 0!==n.count?i(e=>{let t=new Map(e);return t.set(n.id,n.count),o.current=t,t}):i(e=>{if(!e.has(n.id))return e;let t=new Map(e);return t.delete(n.id),o.current=t,t}))},[]);return(0,a.useEffect)(()=>{let e=setInterval(()=>{t.current&&p(Date.now(),!1)},15e3);return()=>{clearInterval(e)}},[p]),(0,a.useEffect)(()=>{if("u"<typeof document)return;let e=()=>{t.current="visible"===document.visibilityState,t.current&&p(Date.now(),!0)};return t.current="visible"===document.visibilityState,document.addEventListener("visibilitychange",e),()=>{document.removeEventListener("visibilitychange",e)}},[p]),(0,a.useEffect)(()=>{let e=!1,n=null,a=null;function l(e){let t;try{t=JSON.parse(e)}catch{return}let n=function(e){var t;if(null===e||"object"!=typeof e||function e(t){if(null===t||"object"!=typeof t)return!1;for(let n of Object.keys(t))if(function(e){let t=e.toLowerCase();return nA.some(e=>t.includes(e))}(n)||e(t[n]))return!0;return!1}(e))return null;let n={};for(let t of od)Object.prototype.hasOwnProperty.call(e,t)&&(n[t]=e[t]);return"string"!=typeof n.id||0===n.id.length?null:"inactive"!==(t=n.state)&&"queued"!==t&&"active"!==t&&"processing"!==t&&"completed"!==t&&"failed"!==t&&"blocked"!==t&&"degraded"!==t&&"high-throughput"!==t||"number"!=typeof n.timestamp?null:{kind:"string"==typeof n.kind?n.kind:"relationship:activity",id:n.id,state:n.state,timestamp:n.timestamp,count:"number"==typeof n.count?n.count:void 0}}(t);null!==n&&f(n)}function s(){null!==a&&(clearTimeout(a),a=null)}function i(){n?.close(),n=null}function r(){!e&&null===a&&t.current&&(a=setTimeout(()=>{a=null,o()},5e3))}function o(){if(!e&&t.current){try{n=new EventSource("/api/relationships/events")}catch{r();return}n.addEventListener("relationship:activity",e=>{l(e.data)}),n.onmessage=e=>{l(e.data)},n.onerror=()=>{e||(i(),r())}}}o();let c=()=>{if(t.current="visible"===document.visibilityState,!t.current){s(),i();return}p(Date.now(),!0),null===n&&o()};return document.addEventListener("visibilitychange",c),()=>{e=!0,document.removeEventListener("visibilitychange",c),s(),i()}},[void 0,f,p]),{activityMap:n,throughputMap:s,animate:!c&&!u,disable:h}}(),[s,i]=(0,a.useState)(!1),[r,o]=(0,a.useState)(oR),c=r.relFocus,d=r.relDensity??"minimal",[u,m]=(0,a.useState)(!1),h=(0,a.useRef)(null),p=(0,a.useRef)(!1),f=(0,a.useRef)(null),[g,v]=(0,a.useState)(!1),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,m(!1),null!==e&&x({relFocus:e.id})},[x]);return(0,a.useEffect)(()=>{!u&&p.current&&(p.current=!1,h.current?.focus())},[u]),(0,a.useEffect)(()=>{let e=window.matchMedia("(prefers-contrast: more)"),t=e=>{i(e)};t(e.matches);let n=e=>{t(e.matches)};return e.addEventListener("change",n),()=>e.removeEventListener("change",n)},[]),(0,a.useEffect)(()=>{let e=f.current;if(null===e)return;let t=e=>{let t=e.target;if(!("INPUT"===t.tagName||"TEXTAREA"===t.tagName||"SELECT"===t.tagName||t.isContentEditable)&&"Escape"===e.key){if(u||null!==document.querySelector('[role="dialog"][aria-modal="true"]'))return;y()}};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)},[u,y]),(0,n.jsxs)(n.Fragment,{children:[u&&(0,n.jsx)(oE,{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:h,type:"button",className:"arun-btn primary",onClick:()=>m(!0),"aria-label":"Create new relationship",style:{flex:"0 0 auto",minWidth:24,minHeight:24},children:"+ New relationship"})]}),(0,n.jsxs)("div",{style:{display:"flex",flex:1,overflow:"hidden"},children:[(0,n.jsx)("div",{style:{flex:"0 0 280px",borderRight:"1px solid var(--line)",overflowY:"auto"},children:(0,n.jsx)(r0,{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)(of,{onSelectRelationship:e=>{v(!1),b(e)}}):(0,n.jsx)(oc,{relationshipId:c??null,densityMode:d,onClearFocus:y,onViewImpact:j,activityMap:e,throughputMap:t,animateBadges:l,highContrast:s})})]})]})]})}var oA=e.i(22016);let oT={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 oM(e){if(e instanceof j.ApiError){let t=oT[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 oq={jaccardThreshold:.85,staleConfidenceThreshold:.3,maxAgeMs:7776e6,maxClustersPerRun:100,maxRecordsPerRun:1e3};function oL(e,t){return`${e.toString()} ${1===e?t:`${t}s`}`}function oP(e){return"completed"===e||"failed"===e||"canceled"===e||"skipped"===e}function oD(e){return void 0===e?"—":new Date(e).toLocaleString()}function oF({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)(oA.default,{href:`/memoriaviva/detail?id=${encodeURIComponent(e)}`,className:"mc-id-link",title:e,children:e})}function oz({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)(oF,{id:e,onOpenDetail:t})]},`${l.toString()}:${e}`))})}function oO({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)(oF,{id:e.proposedAction.winner,onOpenDetail:t}),"; replace ",(0,n.jsx)(oz,{ids:e.proposedAction.losers,onOpenDetail:t}),"."]}):(0,n.jsxs)(n.Fragment,{children:["Supersede ",(0,n.jsx)(oF,{id:e.proposedAction.older,onOpenDetail:t})," with"," ",(0,n.jsx)(oF,{id:e.proposedAction.newer,onOpenDetail:t}),"."]})}function oK({flag:e,onOpenDetail:t}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oF,{id:e.memoryId,onOpenDetail:t})," — ",e.reason]})}function o_({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 oB({startJobImpl:e=tE,fetchJobImpl:t=tR,cancelJobImpl:l=t$,pollIntervalMs:s=2e3,onBack:i,onOpenDetail:r}){var o;let[c,d]=(0,a.useState)(oq),[u,m]=(0,a.useState)(null),[h,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&&!oP(k.state),S=(0,a.useMemo)(()=>{if(null===k)return null;let e=k.result;return{reviewCount:e?.reviewItems.length??0,staleCount:e?.staleFlags.length??0,edgeCount:e?.edgesProposed.length??0}},[k]),C=(0,a.useCallback)((e,t)=>{d(n=>({...n,[e]:t}))},[]),I=(0,a.useCallback)(async e=>{g(!0);try{let n=await t(e);m(n.job),w(null)}catch(e){w(oM(e))}finally{g(!1)}},[t]);(0,a.useEffect)(()=>{if(null===k||oP(k.state))return;let e=window.setInterval(()=>{I(k.id)},s);return()=>{window.clearInterval(e)}},[k,s,I]);let E=(0,a.useCallback)(async t=>{if(t.preventDefault(),!h&&!N){p(!0),y(null),w(null);try{let t=await e(c);m(t.job)}catch(e){y(oM(e))}finally{p(!1)}}},[c,e,h,N]),R=(0,a.useCallback)(async()=>{if(null!==k&&!v){x(!0),w(null);try{let e=await l(k.id);m(e.job)}catch(e){w(oM(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)(oA.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)(o_,{label:"Jaccard threshold",name:"jaccardThreshold",value:c.jaccardThreshold,min:0,max:1,step:.01,disabled:h||N,help:"Similarity floor for near-duplicate detection.",onChange:C}),(0,n.jsx)(o_,{label:"Stale confidence threshold",name:"staleConfidenceThreshold",value:c.staleConfidenceThreshold,min:0,max:1,step:.01,disabled:h||N,help:"Memories at or below this confidence are flagged stale.",onChange:C}),(0,n.jsx)(o_,{label:"Max age (days)",name:"maxAgeMs",value:c.maxAgeMs/864e5,min:0,step:1,disabled:h||N,help:"Memories older than this are checked for staleness.",onChange:(e,t)=>{C(e,864e5*t)}}),(0,n.jsx)(o_,{label:"Max clusters per run",name:"maxClustersPerRun",value:c.maxClustersPerRun,min:0,max:1e3,step:1,disabled:h||N,help:"Hard bound on duplicate clusters inspected in one run.",onChange:C}),(0,n.jsx)(o_,{label:"Max records per run",name:"maxRecordsPerRun",value:c.maxRecordsPerRun,min:0,max:1e3,step:1,disabled:h||N,help:"Hard bound on accepted records admitted to one scan.",onChange:C})]}),null!==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":h||N,"aria-busy":h,children:h?"Starting…":"Start consolidation"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null===k||f,"aria-busy":f,onClick:()=>{null===k||f||I(k.id)},children:f?"Refreshing…":"Refresh status"}),N?(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":v,"aria-busy":v,onClick:()=>{R()},children:v?"Canceling…":"Cancel job"}):null]})]})}),(0,n.jsx)("section",{"aria-label":"Consolidation job status",style:{display:"grid",gap:16,padding:16,border:"1px solid var(--line)",borderRadius:14,background:"var(--card)"},children:null===k?(0,n.jsx)("p",{style:{margin:0,color:"var(--fg-muted)"},children:"No consolidation job started yet."}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{style:{display:"grid",gap:12,gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))"},children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"State"}),(0,n.jsx)("div",{role:"status","aria-live":"polite","aria-atomic":"true",style:{fontWeight:700,textTransform:"capitalize"},children:k.state})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Job ID"}),(0,n.jsx)("div",{style:{wordBreak:"break-all"},children:k.id})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Started"}),(0,n.jsx)("div",{children: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:oL(S.reviewCount,"review item")}),(0,n.jsx)("span",{className:"mc-badge mc-badge-default",children:oL(S.staleCount,"stale flag")}),(0,n.jsx)("span",{className:"mc-badge mc-badge-default",children:oL(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)(oz,{ids:e.relatedMemoryIds,onOpenDetail:r})}),(0,n.jsx)("span",{style:{color:"var(--fg-muted)"},children:(0,n.jsx)(oO,{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)(oK,{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)(oF,{id:e.fromMemoryId,onOpenDetail:r})," →"," ",(0,n.jsx)(oF,{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 oU=["user","workspace","project","workflow","global"],oW=["episodic","semantic-fact","procedural","preference","correction","decision","negative","pinned"],oH=["public","confidential","restricted"],oG=["proposed","accepted","rejected","superseded","archived","forgotten","conflicted","expired"],oV={user:"User",workspace:"Workspace",project:"Project",workflow:"Workflow",global:"Global"},oY={episodic:"Episodic","semantic-fact":"Fact",procedural:"Procedural",preference:"Preference",correction:"Correction",decision:"Decision",negative:"Negative",pinned:"Pinned"},oQ={proposed:"Proposed",accepted:"Accepted",rejected:"Rejected",superseded:"Superseded",archived:"Archived",forgotten:"Forgotten",conflicted:"Conflicted",expired:"Expired"},oJ={public:"Public",confidential:"Confidential",restricted:"Restricted"};function oX(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function oZ({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 o0({filters:e,onChange:t}){return(0,n.jsxs)("section",{className:"mc-filters","aria-label":"Memory filters",children:[(0,n.jsx)(oZ,{label:"Scope",items:oU,labels:oV,active:e.scope,onToggle:n=>{t({...e,scope:oX(e.scope,n)})}}),(0,n.jsx)(oZ,{label:"Type",items:oW,labels:oY,active:e.type,onToggle:n=>{t({...e,type:oX(e.type,n)})}}),(0,n.jsx)(oZ,{label:"Status",items:oG,labels:oQ,active:e.status,onToggle:n=>{t({...e,status:oX(e.status,n)})}}),(0,n.jsx)(oZ,{label:"Sensitivity",items:oH,labels:oJ,active:e.sensitivity,onToggle:n=>{t({...e,sensitivity:oX(e.sensitivity,n)})}})]})}let o1={public:"Public",confidential:"Confidential",restricted:"Restricted"};function o2({record:e,mode:t="edit",onSave:l,onClose:s,editMemoryImpl:i=tT,correctMemoryImpl:r=tF}){let[o,c]=(0,a.useState)(e.body),[d,u]=(0,a.useState)(e.tags.join(", ")),[m,h]=(0,a.useState)(e.provenance.sensitivity),[p,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(null),[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:m});l(a.memory)}}catch(e){v(oM(e))}finally{f(!1)}},[o,d,m,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:m,onChange:e=>{h(e.target.value)},disabled:p,children:oH.map(e=>(0,n.jsx)("option",{value:e,children:o1[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 o3({record:e,mode:t="forget",onComplete:l,onClose:s,forgetMemoryImpl:i=tP,deleteMemoryImpl:r=tD}){let[o,c]=(0,a.useState)(!1),[d,u]=(0,a.useState)(null),m=(0,a.useRef)(null),h=(0,a.useRef)(null),p=(0,a.useRef)(null),f=(0,a.useRef)(null),g="delete"===t;(0,a.useEffect)(()=>(f.current=document.activeElement instanceof HTMLElement?document.activeElement:null,m.current?.focus(),()=>{f.current?.focus()}),[]);let v=(0,a.useCallback)(e=>{if("Escape"===e.key)return void s();if("Tab"!==e.key)return;let t=p.current?.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled])');if(void 0===t||0===t.length){e.preventDefault(),p.current?.focus();return}let n=t[0],a=t[t.length-1];if(void 0===n||void 0===a){e.preventDefault(),p.current?.focus();return}let l=document.activeElement;e.shiftKey||l!==a?e.shiftKey&&l===n&&(e.preventDefault(),a.focus()):(e.preventDefault(),n.focus())},[s]),x=(0,a.useCallback)(e=>{e.target===h.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(oM(e)),c(!1)}},[r,i,g,l,e.id]);return(0,n.jsx)("div",{ref:h,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:m,type:"button",className:"lk-btn lk-btn-ghost",onClick:s,disabled:o,children:"Cancel"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-danger",onClick:()=>{b()},disabled:o,"aria-busy":o,children:o?g?"Deleting…":"Forgetting…":g?"Delete permanently":"Forget permanently"})]})]})})}function o4({record:e,onRecordChange:t,acceptImpl:l=tz,rejectImpl:s=tO,pinImpl:i=tM,unpinImpl:r=tq,archiveImpl:o=tL,deleteImpl:c=tD,correctImpl:d=tF}){let[u,m]=(0,a.useState)(null),[h,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){m(e),p(null),g(null);try{await t()}catch(e){p(oM(e))}finally{m(null)}}},[u]),C=(0,a.useCallback)(()=>{S("accept",async()=>{t((await l(e.id)).memory)})},[l,t,e.id,S]),I=(0,a.useCallback)(()=>{S("reject",async()=>{t((await s(e.id,"rejected by user in MemoriaViva")).memory)})},[t,e.id,s,S]),E=(0,a.useCallback)(()=>{S("pin",async()=>{t((await i(e.id)).memory)})},[t,i,e.id,S]),R=(0,a.useCallback)(()=>{S("unpin",async()=>{t((await r(e.id)).memory)})},[t,e.id,S,r]),$=(0,a.useCallback)(()=>{S("archive",async()=>{t((await o(e.id,"archived by user in MemoriaViva")).memory)})},[o,t,e.id,S]),A=(0,a.useCallback)(e=>{y(!1),g(`Correction submitted for review: ${e.body}`)},[]),T="proposed"===e.status,M="accepted"===e.status||"superseded"===e.status||"conflicted"===e.status||"expired"===e.status,q="forgotten"===e.status;return(0,n.jsxs)("div",{className:"mc-actions",role:"group","aria-label":"Memory actions",children:[T?(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,q?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"})]}),q?null:e.pinned?(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==u,"aria-busy":"unpin"===u,onClick:R,"aria-label":"Unpin this memory",children:"unpin"===u?"Unpinning…":"Unpin"}):(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==u,"aria-busy":"pin"===u,onClick:E,"aria-label":"Pin this memory for priority retrieval",children:"pin"===u?"Pinning…":"Pin"}),M?(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==u,"aria-busy":"archive"===u,onClick:$,"aria-label":"Archive this memory",children:"archive"===u?"Archiving…":"Archive"}):null,q?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!==h?(0,n.jsx)("p",{role:"alert","aria-live":"assertive",className:"mc-action-error",children:h}):null,null!==f?(0,n.jsx)("p",{role:"status","aria-live":"polite",className:"mc-action-notice",children:f}):null,v?(0,n.jsx)(o2,{record:e,onSave:e=>{x(!1),t(e)},onClose:()=>{x(!1)}}):null,b?(0,n.jsx)(o2,{mode:"correct",record:e,correctMemoryImpl:d,onSave:A,onClose:()=>{y(!1)}}):null,j?(0,n.jsx)(o3,{record:e,onComplete:()=>{w(!1),t(null)},onClose:()=>{w(!1)}}):null,k?(0,n.jsx)(o3,{mode:"delete",record:e,deleteMemoryImpl:c,onComplete:()=>{N(!1),t(null)},onClose:()=>{N(!1)}}):null]})}function o6(e){return new Date(e).toLocaleString()}function o5({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 o8({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)(o5,{label:"Source kind",value:e.sourceKind}),(0,n.jsx)(o5,{label:"Captured at",value:o6(e.capturedAt)}),(0,n.jsx)(o5,{label:"Confidence",value:`${(100*e.confidence).toFixed(0)}%`}),(0,n.jsx)(o5,{label:"Sensitivity",value:e.sensitivity}),void 0!==e.captureRationale?(0,n.jsx)(o5,{label:"Rationale",value:e.captureRationale}):null,void 0!==e.modelIdentity?(0,n.jsx)(o5,{label:"Model",value:`${e.modelIdentity.provider} / ${e.modelIdentity.modelId}`}):null]})]})}function o7({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)(o5,{label:"Valid from",value:o6(e.validFrom)}),(0,n.jsx)(o5,{label:"Valid until",value:void 0!==e.validUntil?o6(e.validUntil):"No expiry"})]})]})}function o9({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 ce({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)(oA.default,{ref:t,href:"/memoriaviva",className:"mc-back-link lk-btn lk-btn-ghost","aria-label":"Back to MemoriaViva",children:a})}function ct({record:e,onBack:t}){return(0,n.jsxs)("header",{className:"mc-detail-header",children:[(0,n.jsx)(ce,{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:[oY[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 cn({id:e,fetchMemoryImpl:t=tA,onBack:l}){let[s,i]=(0,a.useState)(null),[r,o]=(0,a.useState)(!0),[c,d]=(0,a.useState)(null),[u,m]=(0,a.useState)(!1),h=(0,a.useRef)(null),p=(0,a.useCallback)(e=>{h.current=e},[]),f=(0,a.useCallback)(e=>{null===e&&m(!0),i(e)},[]);(0,a.useEffect)(()=>{u&&null===s&&h.current?.focus()},[u,s]);let g=(0,a.useCallback)(async()=>{o(!0),d(null);try{let n=await t(e);i(n.memory)}catch(e){d(oM(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)(ce,{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)(ce,{onBack:l,controlRef:p})})]})}):(0,n.jsxs)("article",{"aria-label":`Memory record: ${s.body.slice(0,60)}`,className:"mc-detail",children:[(0,n.jsx)(ct,{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)(o5,{label:"ID",value:(0,n.jsx)("code",{className:"mc-code",children:s.id})}),(0,n.jsx)(o5,{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)(o5,{label:"Type",value:oY[s.type]}),(0,n.jsx)(o5,{label:"Created",value:o6(s.createdAt)}),(0,n.jsx)(o5,{label:"Updated",value:o6(s.updatedAt)}),void 0!==s.staleReason?(0,n.jsx)(o5,{label:"Stale reason",value:(0,n.jsx)("em",{children:s.staleReason})}):null]})]}),(0,n.jsx)(o8,{provenance:s.provenance}),(0,n.jsx)(o7,{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)(o9,{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)(o4,{record:s,onRecordChange:f})]})]})}var ca=e.i(18566);let cl={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 cs({status:e}){let t=cl[e]??"mc-badge-default";return(0,n.jsx)("span",{className:`mc-badge ${t}`,children:e})}function ci({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:oY[e.type]}),(0,n.jsx)("span",{className:"mc-row-scope",children:oV[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)(cs,{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)(oA.default,{href:`/memoriaviva/detail?id=${encodeURIComponent(e.id)}`,className:"mc-row",children:l})})}function cr({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 co({filters:e,onFilterChange:t,fetchMemoriesImpl:l=tC,onOpenDetail:s,onOpenConsolidation:i,onOpenReviewQueue:r,policyEnabled:o,onPolicyEnabledChange:c,showWorkspaceBackLink:d=!0}){let[u,m]=(0,a.useState)([]),[h,p]=(0,a.useState)(!0),[f,g]=(0,a.useState)(null),[v,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);m(t.memories)}catch(e){g(oM(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)(a3,{on:b,onChange:c??x,label:"Enable MemoriaViva policy"}),(0,n.jsxs)("span",{children:["Policy ",b?"on":"off"]})]}),d?(0,n.jsx)(oA.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)(oA.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)(oA.default,{href:"/memoriaviva/review-queue",className:"lk-btn lk-btn-ghost lk-btn-lg mc-queue-link",children:"Review queue"})]})]}),(0,n.jsx)(o0,{filters:e,onChange:t}),(0,n.jsx)("p",{role:"status",className:"visually-hidden",children:h||null!==f?null:`${u.length.toString()} ${1===u.length?"memory":"memories"} found`}),(0,n.jsx)("section",{"aria-label":"Memory records","aria-busy":h,style:{flex:1,minHeight:0,overflowY:"auto"},children:h&&0===u.length?(0,n.jsx)("p",{role:"status","aria-live":"polite",className:"lk-loading",children:"Loading memories…"}):null!==f?(0,n.jsxs)("div",{role:"alert","aria-live":"assertive",className:"lk-alert",children:[f,(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>{j(e)},children:"Retry"})]}):0===u.length?(0,n.jsx)(cr,{hasFilters:y}):(0,n.jsx)("ul",{"aria-label":"Memory list",style:{listStyle:"none",padding:0,margin:0,display:"flex",flexDirection:"column",gap:4,opacity:h?.6:1,transition:"opacity 0.15s ease"},children:u.map(e=>(0,n.jsx)(ci,{record:e,onOpenDetail:s},e.id))})})]})}function cc({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:oY[e.type]}),(0,n.jsx)("span",{className:"mc-row-scope",children:oV[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)(oA.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 cd({fetchQueueImpl:e=tI,acceptImpl:t=tz,rejectImpl:l=tO,archiveImpl:s=tL,onBack:i,onOpenDetail:r}){let[o,c]=(0,a.useState)([]),[d,u]=(0,a.useState)(!0),[m,h]=(0,a.useState)(null),[p,f]=(0,a.useState)({}),[g,v]=(0,a.useState)({}),[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),h(null);try{let t=await e();c(t.memories),f({}),v({})}catch(e){h(oM(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]:oM(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)(oA.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!==m?(0,n.jsxs)("div",{role:"alert","aria-live":"assertive",className:"lk-alert",children:[m,(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>{k()},children:"Retry"})]}):0===o.length?(0,n.jsx)("div",{"data-testid":"review-queue-empty",className:"lk-empty",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"lk-empty-title",children:"Queue is clear"}),(0,n.jsx)("p",{className:"lk-empty-body",children:"No memories are waiting for review. Proposed, conflicted, and stale memories appear here."})]})}):(0,n.jsx)("ul",{ref:y,"aria-label":"Review queue",style:{listStyle:"none",padding:0,margin:0,display:"flex",flexDirection:"column",gap:8},children:o.map(e=>(0,n.jsx)(cc,{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 cu={scope:[],type:[],status:[],sensitivity:[]};function cm(){let[e,t]=(0,a.useState)({kind:"list"}),[l,s]=(0,a.useState)(cu),[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)(co,{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)(cn,{id:e.id,onBack:o}):"consolidation"===e.kind?(0,n.jsx)(oB,{onBack:o,onOpenDetail:c}):(0,n.jsx)(cd,{onBack:o,onOpenDetail:c})})}var ch=e.i(96688),cp=e.i(61774);function cf(e){return Array.from(e.querySelectorAll("button:not([disabled]),input:not([disabled]),[tabindex]:not([tabindex='-1'])"))}function cg({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:ch.STATUS_LABELS[e.lifecycleState]})]})})}function cv({capsules:e,onCancel:t,onCreated:l,createImpl:s=a4.createCapsuleSet}){let i,r=(0,a.useId)(),o=(0,a.useId)(),c=(0,a.useId)(),d=(0,a.useRef)(null),[u,m]=(0,a.useState)(""),[h,p]=(0,a.useState)(new Set),[f,g]=(0,a.useState)(!1),[v,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=h.size,0===u.trim().length?"Set name is required.":0===t?"Select at least one capsule to combine.":t>16?"A set can hold at most 16 capsules.":null);if(null!==n)return void x(n);g(!0),x(null);try{await s({displayName:u.trim(),capsuleIds:[...h]}),l()}catch(e){x((0,cp.formatError)(e))}finally{g(!1)}}(0,a.useEffect)(()=>{let e=document.activeElement,t=d.current;return null!==t&&cf(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=cf(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,cf(e)[0]?.focus()))},[d,f]);let j="Set name is required."===v,w="Select at least one capsule to combine."===v;return(0,ti.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=>{m(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 (",h.size.toString(),"/","16",")"]}),0===e.length?(0,n.jsx)("p",{className:"lkd-empty-note",children:"No capsules available to combine."}):(0,n.jsx)("ul",{className:"lk-compose-member-list","aria-label":"Selectable capsules",children:e.map(e=>(0,n.jsx)(cg,{capsule:e,checked:h.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 cx=e.i(80010);function cb({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 cy(e){return Array.from(e.querySelectorAll("button:not([disabled]),input:not([disabled]),textarea:not([disabled]),select:not([disabled]),[tabindex]:not([tabindex='-1'])"))}function cj({busy:e,error:t,onCancel:l,onSubmit:s}){let i=(0,a.useId)(),r=(0,a.useId)(),o=(0,a.useId)(),c=(0,a.useId)(),d=(0,a.useRef)(null),u=(0,a.useRef)(null),m=(0,a.useRef)(null),[h,p]=(0,a.useState)(""),[f,g]=(0,a.useState)(null);(0,a.useEffect)(()=>(m.current=document.activeElement,u.current?.focus(),()=>{m.current?.focus?.()}),[]),(0,a.useEffect)(()=>{let t=d.current;if(null===t)return;let n=n=>{if("Escape"===n.key&&!e){n.preventDefault(),l();return}if("Tab"!==n.key)return;let a=cy(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=h.trim();0===t.length?g("Capsule display name is required."):(g(null),await s(t))}(0,a.useEffect)(()=>{let t=d.current;null!==t&&(e?(v.current=!0,t.focus()):v.current&&(v.current=!1,cy(t)[0]?.focus()))},[e]);let b=f??t;return(0,ti.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:h,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 cw({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&&cy(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=cy(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,ti.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 ck({state:e}){return(0,n.jsx)("span",{className:"lk-badge","data-state":e,children:ch.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 m=d>0;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",disabled:t,"aria-disabled":!m||void 0,"aria-busy":"index"===l,"aria-label":`Start indexing capsule ${o}`,"aria-describedby":m?void 0:u,title:m?void 0:"Attach a source before indexing this capsule.",onClick:()=>{m&&s(r)},className:"lk-btn lk-btn-primary",children:"index"===l?"Indexing…":"Index"}),m?null:(0,n.jsx)("span",{id:u,className:"visually-hidden",children:"Attach a source before indexing."})]})}function cS({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 cC(e){return e instanceof Element&&null!==e.closest(".lk-capsule-actions,a,input,select,textarea")}function cI(e,t){let n=document.elementFromPoint(e,t);return n instanceof Element&&null!==n.closest("main.workspace")&&null===n.closest(".window")}function cE(e,t){let n={payload:e,clientX:t.clientX,clientY:t.clientY};window.dispatchEvent(new CustomEvent(e5,{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),m=(0,a.useRef)(!1),h=(0,a.useRef)(!1),p={kind:"capsule",id:e.id,label:e.displayName,lifecycleState:e.lifecycleState},f=e=>{h.current||(h.current=!0,cE(p,e),window.setTimeout(()=>{h.current=!1},250))},g=(t,n)=>{m.current=!0;let a=!1,l=l=>{let s=l.clientX-t,i=l.clientY-n;!a&&6>Math.hypot(s,i)||(a=!0,document.body.style.cursor="grabbing",u({x:l.clientX,y:l.clientY,label:e.displayName,state:e.lifecycleState}))},s=e=>{window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",s),window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",s),m.current=!1,document.body.style.cursor="",u(null),a&&cI(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=>{cC(e.target)||(e.stopPropagation(),0===e.button&&(e.preventDefault(),g(e.clientX,e.clientY)))},onMouseDown:e=>{m.current||cC(e.target)||(e.stopPropagation(),0===e.button&&(e.preventDefault(),g(e.clientX,e.clientY)))},onDragStart:t=>{cC(t.target)?t.preventDefault():(t.dataTransfer.effectAllowed="copy",t.dataTransfer.setData(e6,JSON.stringify(p)),t.dataTransfer.setData("text/plain",e.displayName))},onDragEnd:e=>{cI(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)(ck,{state:e.lifecycleState})]})]}),(0,n.jsx)(cS,{capsule:e,busy:t,busyKind:l,onStart:s,onCancel:i,onDisconnect:r,onHealth:o,onAddToWorkspace:c})]}),null!==d?(0,ti.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:ch.STATUS_LABELS[d.state]})]})]}),document.body):null]})}function c$({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 cA({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)(c$,{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&&cE({kind:"capsule",id:e.id,label:e.displayName,lifecycleState:e.lifecycleState},t)}})},e.id))})}function cT({creating:e,createDialogOpen:t,combineDialogOpen:l,combineDisabled:s,showBackToWorkspace:i,loadStatus:r,loadError:o,actionError:c,createError:d,reload:u,onCreateCapsule:m,onCombineCapsules:h,onDismissCreateError:p,onDismissActionError:f}){let g=(0,a.useId)();return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("header",{className:"lk-header",children:[(0,n.jsx)("h1",{className:"lk-title",children:"Local Knowledge Connector"}),(0,n.jsxs)("div",{className:"lk-header-actions",children:[i?(0,n.jsx)(oA.default,{href:"/",className:"lk-btn lk-btn-ghost lk-btn-lg",children:"Back to Workspace"}):null,(0,n.jsx)("button",{type:"button","aria-disabled":s,"aria-describedby":s?g:void 0,"aria-label":"Combine capsules into a set","aria-haspopup":"dialog","aria-expanded":l,title:s?"Create capsules first, then combine them into a set.":void 0,onClick:()=>{s||h()},className:"lk-btn lk-btn-ghost lk-btn-lg",children:"Combine capsules"}),s?(0,n.jsx)("span",{id:g,className:"visually-hidden",children:"Create capsules first, then combine them into a set."}):null,(0,n.jsx)("button",{type:"button",disabled:e,"aria-label":"Create a new knowledge capsule","aria-haspopup":"dialog","aria-expanded":t,onClick:m,className:"lk-btn lk-btn-primary lk-btn-lg",children:e?"Creating…":"Create capsule"})]})]}),"error"===r&&null!==o?(0,n.jsx)(cb,{message:o,onRetry:u}):null,null===d||t?null:(0,n.jsx)(cb,{message:d,onDismiss:p}),null!==c?(0,n.jsx)(cb,{message:c,onDismiss:f}):null]})}function cM(e){let t,l,{onOpenCapsule:s,showBackToWorkspace:i=!0}=e,[r,o]=(0,a.useState)(null),c=(0,a.useCallback)(e=>{void 0!==s?s(e):o(e)},[s]),{capsules:d,loadStatus:u,loadError:m,actionBusy:h,actionKind:p,actionError:f,creating:g,createError:v,reload:x,clearCreateError:b,clearActionError:y,handleStartIndexing:j,handleCancelIndexing:w,handleDisconnect:k,handleOpenHealth:N,handleCreateCapsule:S}=function(e){let{fetchCapsulesImpl:t=a4.fetchCapsules,createCapsuleImpl:n=a4.createCapsule,startIndexingImpl:l=a4.startIndexing,cancelIndexingImpl:s=a4.cancelIndexing,disconnectCapsuleImpl:i=a4.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,cp.formatError)(e)),s("error")}},[e]);return(0,a.useEffect)(()=>{o()},[o]),{capsules:t,loadStatus:l,loadError:i,reload:function(){o()}}}(t),{actionBusy:m,actionKind:h,actionError:p,clearActionError:f,handleStartIndexing:g,handleCancelIndexing:v,handleDisconnect:x,handleOpenHealth:b}=function(e,t,n,l,s){let i=(0,ca.useRouter)(),[r,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(null),[u,m]=(0,a.useState)(null);async function h(t,n,a){o(t),d(n),m(null);try{await a(),e()}catch(e){m((0,cp.formatError)(e))}finally{o(null),d(null)}}return{actionBusy:r,actionKind:c,actionError:u,clearActionError:function(){m(null)},handleStartIndexing:function(e){h(e,"index",()=>t(e))},handleCancelIndexing:function(e){h(e,"cancel",()=>n(e))},handleDisconnect:function(e){h(e,"disconnect",()=>l(e))},handleOpenHealth:function(e){void 0!==s?s(e):i.push(`/local-knowledge/capsule?capsuleId=${encodeURIComponent(e)}`)}}}(u,l,s,i,r),{creating:y,createError: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,cp.formatError)(e))}finally{l(!1)}}}}(n,u);return{capsules:o,loadStatus:c,loadError:d,actionBusy:m,actionKind:h,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),[A,T]=(0,a.useState)(null);async function M(e){try{await S(e),E(!1)}catch{}}return null!==r&&void 0===s?(0,n.jsxs)("div",{className:"lk-page",children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost lk-btn-lg lk-back-inline",onClick:()=>{o(null),x()},children:"Back to capsules"}),(0,n.jsx)(cx.CapsuleDetail,{capsuleId:r,onDeleted:()=>{o(null),x()}})]}):(0,n.jsxs)("div",{className:"lk-page",children:[(0,n.jsx)(cT,{creating:g,createDialogOpen:I,combineDialogOpen:R,combineDisabled:C||0===d.length,showBackToWorkspace:i,loadStatus:u,loadError:m,actionError:f,createError:v,reload:x,onCreateCapsule:()=>E(!0),onCombineCapsules:()=>$(!0),onDismissCreateError:b,onDismissActionError:y}),(0,n.jsx)("p",{role:"status",className:"visually-hidden",children:C||null!==m?null:(t=d.filter(e=>"indexing"===e.lifecycleState).length,l=`${d.length.toString()} capsule${1===d.length?"":"s"}`,t>0?`${l}, ${t.toString()} indexing`:l)}),(0,n.jsxs)("section",{"aria-label":"Knowledge capsules","aria-busy":C,style:{flex:1,minHeight:0,overflowY:"auto"},children:[(0,n.jsx)("h2",{className:"lk-section-head",children:"Knowledge Capsules"}),(0,n.jsx)(cA,{capsules:d,isLoading:C,creating:g,actionBusy:h,actionKind:p,onCreateCapsule:()=>E(!0),onStartIndexing:j,onCancelIndexing:w,onDisconnect:e=>T(d.find(t=>t.id===e)??null),onOpenHealth:N})]}),I?(0,n.jsx)(cj,{busy:g,error:v,onCancel:()=>{E(!1),b()},onSubmit:M}):null,R?(0,n.jsx)(cv,{capsules:d,onCancel:()=>$(!1),onCreated:function(){$(!1),x()}}):null,null!==A?(0,n.jsx)(cw,{capsuleName:A.displayName,onCancel:()=>T(null),onConfirm:()=>{k(A.id),T(null)}}):null]})}function cq(e,t){let n=e[t];return"string"==typeof n?n:void 0}function cL({cfg:e,ctx:t}){let l=nw({autoCreate:!1}),i=(0,a.useRef)(!1),r=cq(e,"chatId"),o=cq(e,"title"),{updateCfg:c}=t,{activeChat:d,chats:u,loading:m,openChat:h,openNewChat:p}=l,f=void 0!==d&&"closed"!==d.status?d:void 0;(0,a.useEffect)(()=>{if(!m){if(void 0!==r){if(f?.id===r)return;let e=u.find(e=>e.id===r&&"closed"!==e.status);void 0!==e&&h(e);return}i.current||(i.current=!0,p(void 0,o).then(e=>{void 0!==e&&c({chatId:e.id,title:e.title})}).finally(()=>{i.current=!1}))}},[r,f?.id,u,m,h,p,o,c]);let g=void 0!==r&&!l.loading&&f?.id!==r&&!l.chats.some(e=>e.id===r&&"closed"!==e.status),v=l.loading||void 0!==r&&f?.id!==r;return(0,n.jsx)(s,{value:l,children:g?(0,n.jsxs)("div",{className:"lk-empty",children:[(0,n.jsx)("p",{className:"lk-empty-title",children:"Chat not found"}),(0,n.jsx)("p",{className:"lk-empty-body",children:"This conversation was deleted or is no longer available."})]}):v?(0,n.jsx)("div",{className:"lk-loading",children:"Opening chat..."}):(0,n.jsx)(lS,{mini:!0===t.mini,linkedRoot:t.linkedRoot})})}I("chat",(e,t)=>(0,n.jsx)(cL,{cfg:e,ctx:t})),I("chatHistory",(e,t)=>(0,n.jsx)(l$,{openChatWindow:e=>{t.openWindow("chat",{chatId:e.id,title:e.title})}})),I("project",()=>(0,n.jsx)(lR,{})),I("search",()=>(0,n.jsx)(lA,{})),I("plugins",()=>(0,n.jsx)(lL,{})),I("automations",()=>(0,n.jsx)(lO,{})),I("mobile",()=>(0,n.jsx)(lK,{})),I("inspector",()=>(0,n.jsx)(l_,{})),I("notifications",()=>(0,n.jsx)(lU,{})),I("resources",()=>(0,n.jsx)(lW,{})),I("activity",()=>(0,n.jsx)(lV,{})),I("keiko",()=>(0,n.jsx)(sG,{})),I("settings",()=>(0,n.jsx)(sZ,{})),I("localKnowledge",()=>(0,n.jsx)(cM,{showBackToWorkspace:!1})),I("quality",(e,t)=>(0,n.jsx)(i6,{openRun:(e,n)=>{let a=void 0!==n?{[iU]:JSON.stringify(n.filter(iG))}:iV(iX({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=cq(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=iW(e,iU);if(void 0!==t&&t.length>0){let e=function(e){try{let t=JSON.parse(e);if(!Array.isArray(t)||!t.every(iG))return null;return t}catch{return null}}(t);if(null!==e)return e}return iX({connectedFilePath:iW(e,"connectedFilePath")??null,connectedRoot:iW(e,"connectedRoot")??null})}(e),s=iV(l);return(0,n.jsx)(r_,{runId:a,connectedSources:l,onRegenerated:e=>{t.openWindow("qiRun",{runId:e.runId,...s})}})}),I("relationships",()=>(0,n.jsx)(o$,{})),I("files",(e,t)=>{let a=cq(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)(l7,{root:a,onActiveFileChange:l,onRootChange:s,onOpenFile:i}):(0,n.jsx)(l7,{onActiveFileChange:l,onRootChange:s,onOpenFile:i})}),I("editor",e=>{let t=cq(e,"root"),a=cq(e,"file"),l={};return void 0!==t&&(l.root=t),void 0!==a&&(l.file=a),(0,n.jsx)(st,{...l})}),I("browser",e=>{let t=cq(e,"url");return void 0!==t&&""!==t?(0,n.jsx)(su,{url:t}):(0,n.jsx)(su,{})}),I("terminal",e=>{let t=cq(e,"cwd"),a=cq(e,"projectPath"),l={};return void 0!==t&&(l.cwd=t),void 0!==a&&(l.projectPath=a),(0,n.jsx)(sx,{...l})}),I("review",(e,t)=>{let a=cq(e,"runId"),l=e=>{t.updateCfg({runId:e})};return void 0!==a&&""!==a?(0,n.jsx)(sE,{runId:a,onRunIdSubmit:l}):(0,n.jsx)(sE,{onRunIdSubmit:l})}),I("agents",(e,t)=>{var a;let l,s,i,r,o,c,d,u,m,h,p;return(0,n.jsx)(sq,{cfg:(i={},void 0!==(r=cq(a=e,"workflow"))&&(i.workflow=r),void 0!==(o=cq(a,"model"))&&(i.model=o),void 0!==(c=cq(a,"runId"))&&(i.runId=c),void 0!==(d=cq(a,"fingerprint"))&&(i.fingerprint=d),void 0!==(u=cq(a,"workspaceRoot"))&&(i.workspaceRoot=u),void 0!==(m=cq(a,"inputJson"))&&(i.inputJson=m),void 0!==(h="boolean"==typeof(l=a.keikoMode)?l:void 0)&&(i.keikoMode=h),void 0!==(p="ask"===(s=a.access)||"full"===s?s:void 0)&&(i.access=p),i),linkedRoot:t.linkedRoot,linkedFilePath:t.linkedFilePath})}),I("memoria",()=>(0,n.jsx)(cm,{})),I("integ",()=>(0,n.jsx)(sP,{})),I("figma",(e,t)=>{let a=cq(e,"snapshotRunId");return(0,n.jsx)(im,{snapshotRunId:a,updateCfg:e=>{t.updateCfg(e)}})}),I("connector",(e,t)=>{let a=cq(e,"presentation"),l=cq(e,"selectedKind"),s=cq(e,"selectedId"),i=cq(e,"selectedLabel"),r=cq(e,"selectedState");return(0,n.jsx)(s5,{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 cD(){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 cF(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 cz=["chat","connector","figma","files","terminal","review"],cO=["chatHistory","memoria","settings","automations","mobile","inspector","activity","notifications","resources","localKnowledge","quality","relationships"];function cK(){var e,t,l;let i,{theme:r,toggle:o}=function(){let[e,t]=(0,a.useState)(nN),[n,l]=(0,a.useState)(!1);return(0,a.useEffect)(()=>{t(function(){try{let e=window.localStorage.getItem(nk);return"light"===e||"dark"===e?e:nN}catch{return nN}}()),l(!0)},[]),(0,a.useEffect)(()=>{if(n){"u">typeof document&&(document.documentElement.dataset.theme=e);try{window.localStorage.setItem(nk,e)}catch{}}},[e,n]),{theme:e,toggle:(0,a.useCallback)(()=>{t(e=>"light"===e?"dark":"light")},[])}}(),c=b(),d=nw({autoCreate:!1}),u=(0,a.useRef)(null),m=(0,a.useRef)(null),[h,p]=(0,a.useState)(nS.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}(m.current?.find(t=>t.id===e));if(void 0===t)return;let n=d.chats.find(e=>e.id===t)??(d.activeChat?.id===t?d.activeChat:void 0);return n?.status==="closed"?void 0:n},[d.activeChat,d.chats]),k=(0,a.useCallback)(async(e,t,n=null)=>{var a;let l=w(e);if(void 0===l)return x("Open a ready chat window before connecting a source.");let s=null===n?eU(l):eB(eU(l),n),i=eW(l);if(s.some(e=>ez(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=e_(h);if(s.length+i.length>=r)return v(s.length+i.length,r);let o={...t,connectedAtMs:Date.now()},c=function(e,t,n=16){if(void 0===t.root)return null;let a=eP(t.root);if(!eL(a))return null;let l=t.relativePaths.map(eF),s={kind:t.kind,relativePaths:l,root:a,connectedAtMs:t.connectedAtMs};return e.some(e=>ez(e,s))||e.length>=n?e:[...e,s]}(s,o,h.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&&nD({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,h,v,x]),N=function(e,t={}){var n,l,s,i,r,o,c,d,u;let[m,h]=(0,a.useState)(null),[p,f]=(0,a.useState)(null),[g,v]=(0,a.useState)(!1),[x,b]=(0,a.useState)([]),[y,j]=(0,a.useState)(null),[w,k]=(0,a.useState)(eX),N=(0,a.useRef)(3),S=(0,a.useRef)(null),C=(0,a.useRef)([]);C.current=m??[];let I=(0,a.useRef)([]);I.current=x;let R=(0,a.useRef)(null);R.current=y;let A=(0,a.useRef)(null),M=(0,a.useRef)(()=>void 0),{viewRef:q,worldVP:L,zoomTo:P,fitView:D,resetView:F,panBy:z,rect:O}=function({wsRef:e,view:t,winsRef:n,setView:l,setWins:s}){let i=(0,a.useRef)(t);i.current=t;let r=(0,a.useRef)(null),o=(0,a.useRef)(null);(0,a.useEffect)(()=>{e2(eJ,t)},[t]),(0,a.useEffect)(()=>()=>{null!==o.current&&"function"==typeof window.cancelAnimationFrame&&window.cancelAnimationFrame(o.current)},[]);let c=(0,a.useCallback)(e=>{let t=r.current??i.current,n="function"==typeof e?e(t):e;if(i.current=n,r.current=n,"function"!=typeof window.requestAnimationFrame||"function"!=typeof window.cancelAnimationFrame){r.current=null,l(n);return}null===o.current&&(o.current=window.requestAnimationFrame(()=>{o.current=null;let e=r.current;r.current=null,null!==e&&l(e)}))},[l]);(0,a.useEffect)(()=>{let t=e.current;if(null===t)return;let n=e=>{if(e.metaKey||e.ctrlKey){var n;e.preventDefault();let a=(n=e.target)instanceof Element?n.closest(".window[data-window-id]")?.dataset.windowId??null:null;if(null!==a)return void s(t=>null===t?t:t.map(t=>{var n,l;let s,i;return t.id===a?(n=t,l=e.deltaY,(i=e0((s=n.zoom??1)*Math.exp(-(.0015*l))))===s?n:{...n,zoom:i}):t}));let l=t.getBoundingClientRect(),r=i.current,o=e3(e),d=eZ(r.zoom*Math.exp(-(.0015*o.y))),u=(e.clientX-l.left-r.x)/r.zoom,m=(e.clientY-l.top-r.y)/r.zoom;return void c({zoom:d,x:e.clientX-l.left-u*d,y:e.clientY-l.top-m*d})}let a=e.target;if(a instanceof Element&&null!==a.closest(".window"))return;e.preventDefault();let l=e3(e);c(e=>({...e,x:e.x-l.x,y:e.y-l.y}))};return t.addEventListener("wheel",n,{passive:!1}),()=>{t.removeEventListener("wheel",n)}},[e,s,c]);let d=(0,a.useCallback)(()=>null===e.current?null:e.current.getBoundingClientRect(),[e]),u=(0,a.useCallback)(()=>{let e=d();if(null===e)return null;let t=i.current;return{x:-t.x/t.zoom,y:-t.y/t.zoom,w:e.width/t.zoom,h:e.height/t.zoom}},[d]),m=(0,a.useCallback)(e=>{let t=d();if(null===t)return;let n=i.current,a=t.width/2,l=t.height/2,s=(a-n.x)/n.zoom,r=(l-n.y)/n.zoom,o=eZ(e);c({zoom:o,x:a-s*o,y:l-r*o})},[d,c]),h=(0,a.useCallback)(()=>{let e=d();null!==e&&c(function(e,t){let n=e.filter(e=>!0!==e.minimized);if(0===n.length)return{zoom:1,x:0,y:0};let a=1/0,l=1/0,s=-1/0,i=-1/0;for(let e of n)a=Math.min(a,e.x),l=Math.min(l,e.y),s=Math.max(s,e.x+e.w),i=Math.max(i,e.y+e.h);let r=Math.max(1,s-a),o=Math.max(1,i-l),c=eZ(Math.min(1,Math.max(1,t.width-144)/r,Math.max(1,t.height-144)/o)),d=a+r/2,u=l+o/2;return{zoom:c,x:Math.round(t.width/2-d*c),y:Math.round(t.height/2-u*c)}}(n.current,e))},[d,n,c]);return{viewRef:i,worldVP:u,zoomTo:m,fitView:h,resetView:(0,a.useCallback)(()=>c({zoom:1,x:0,y:0}),[c]),panBy:(0,a.useCallback)((e,t)=>c(n=>({...n,x:n.x+e,y:n.y+t})),[c]),rect:d}}({wsRef:e,view:w,winsRef:C,setView:k,setWins:h});!function({wsRef:e,setWins:t,setConns:n,zc:l}){(0,a.useLayoutEffect)(()=>{let a=e.current;if(null===a)return;a.getBoundingClientRect();let s=null;try{s=function(e){if(null===e)return null;try{let t=JSON.parse(e);if(!Array.isArray(t)||0===t.length)return null;let n=eR(t);return n.length>0?n:null}catch{return null}}(window.localStorage.getItem(eY))}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 e$(n,t)}catch{return[]}}(window.localStorage.getItem(eQ),s))}catch{}},[e,t,n,l])}({wsRef:e,setWins:h,setConns:b,zc:N}),(0,a.useEffect)(()=>{null!==m&&e2(eQ,e$(x,m))},[x,m]),(0,a.useEffect)(()=>{null!==m&&b(e=>{let t=e.filter(e=>void 0!==m.find(t=>t.id===e.a)&&void 0!==m.find(t=>t.id===e.b));return t.length===e.length?e:t})},[m,b]),(0,a.useEffect)(()=>{null!==m&&e2(eY,eR(m))},[m]),function({setWins:e,rect:t,cancelConnectRef:n}){(0,a.useEffect)(()=>{let a=a=>{var l,s;if("Escape"===a.key)return void n.current();if(null!==(l=document.activeElement)&&("INPUT"===l.tagName||"TEXTAREA"===l.tagName||"SELECT"===l.tagName))return;let i=e4[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=e1(e);if(null===n)return e;let a=(t=n.zoom??1,"0"===i?1:"-"===i||"_"===i?e0(t-.1):e0(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=e1(e);if(null===u)return e;let m=o?(t=s.shift?1:16,n=u.w,a=u.h,"ArrowRight"===s.key?n+=t:"ArrowLeft"===s.key?n-=t:"ArrowDown"===s.key?a+=t:"ArrowUp"===s.key&&(a-=t),n=Math.max((l=E[u.type].min).w,Math.min(c.width,n)),a=Math.max(l.h,Math.min(c.height,a)),{x:u.x,y:u.y,w:n,h:a}):(i=s.shift?1:16,r=u.x,d=u.y,"ArrowRight"===s.key?r+=i:"ArrowLeft"===s.key?r-=i:"ArrowDown"===s.key?d+=i:"ArrowUp"===s.key&&(d-=i),{x:r=Math.max(-(u.w-120),Math.min(c.width-120,r)),y:d=Math.max(0,Math.min(c.height-38,d)),w:u.w,h:u.h});return e.map(e=>e.id===u.id?{...e,...m,max:!1}:e)}))};return window.addEventListener("keydown",a),()=>{window.removeEventListener("keydown",a)}},[e,t,n])}({setWins:h,rect:O,cancelConnectRef:M}),function({wsRef:e,viewRef:t,setWins:n}){(0,a.useEffect)(()=>{let a=e.current;if(null===a||"u"<typeof ResizeObserver)return;let l=new ResizeObserver(()=>{let e=a.getBoundingClientRect(),l=t.current,s={x:-l.x/l.zoom,y:-l.y/l.zoom,w:e.width/l.zoom,h:e.height/l.zoom};n(e=>null===e?e:e.map(e=>(function(e,t){if(e.max)return{...e,x:t.x,y:t.y,w:t.w,h:t.h};let n=Math.max(t.x-(e.w-120),Math.min(t.x+t.w-120,e.x)),a=Math.max(t.y,Math.min(t.y+t.h-38,e.y));return n===e.x&&a===e.y?e:{...e,x:n,y:a}})(e,s)))});return l.observe(a),()=>{l.disconnect()}},[e,t,n])}({wsRef:e,viewRef:q,setWins:h});let{update:K,focus:_,close:B,minimize:U,restore:W,maximize:H,add:G,toggleTool:V}={update:(l=(n={setWins:h,zc:N,worldVP:L}).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:m}=eA(r,s.w,s.h,o.length,40),h=!0===s.singleton?e:`${e}-${Date.now().toString(36)}`;return i=h,[...o,{id:h,type:e,x:u,y:m,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}=eA(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:Y,splitFront:Q,cascade:J}={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{...eT(e),max:!1,minimized:!1,x:n.x+12+t%l*(i+12),y:n.y+12+a*(r+12),w:i,h:r}})})}(u={setWins:h,worldVP:L}),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?{...eT(e),max:!1,minimized:!1,x:n.x,y:n.y,w:n.w/2,h:n.h}:1===t?{...eT(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)=>({...eT(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:X,commitSnap:Z}=function({setSnapPrev:e,snapZone:t,worldVP:n,update:a}){return{setSnap:a=>{if(t.current=a,null===a)return void e(null);let l=n();null!==l&&e(T(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={...T(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:L,update:K}),{startConnect:ee,confirmConnect:et,cancelConnect:en,removeConn:ea,connect:el,linkedFilesRoot:es,linkedFilesContext:ei,linkedAllFilesRoots:er,linkedConnectorCapsuleIds:eo,linkedConnectorCapsuleSetIds:ec,linkedFigmaSnapshotRunIds:ed,currentFilesContext:eu}=function(e){let{wsRef:t,viewRef:n,winsRef:a,connsRef:l,connectingRef:s,connectCleanupRef:i,focus:r,setConns:o,setConnecting:c,onScopeBind:d,onScopeUnbind:u,onConnectorBind:m,onConnectorUnbind:h}=e,p=()=>{null!==i.current&&(i.current(),i.current=null),s.current=null,c(null)},f=e=>{if("files"!==e.type)return null;let t=e.cfg.resolvedRoot,n=e.cfg.root,a="string"==typeof t&&t.length>0?t:"string"==typeof n&&n.length>0?n:null;if(null===a||!eL(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 m={from:e,x:d(a.clientX),y:u(a.clientY)};s.current=m,c(m);let h=t=>{let n={from:e,x:d(t.clientX),y:u(t.clientY)};s.current=n,c(n)};window.addEventListener("pointermove",h),i.current=()=>{window.removeEventListener("pointermove",h)}},confirmConnect:(e,t)=>{t.preventDefault(),t.stopPropagation();let n=s.current;if(null===n)return;let l=a.current,i=l.find(e=>e.id===n.from),c=l.find(t=>t.id===e);if(void 0!==i&&void 0!==c&&$(i.type,c.type)){let t,l=eO(i,c,Date.now()),s=null===l?eV(i,c):null,u=null!==l||null!==s?eq(i,c):null;try{t=null!==l&&null!==u?d?.(u,l)??!0:null===s||null!==u&&(m?.(u,s)??!0)}catch{t=!1}Promise.resolve(t).then(t=>{!t||a.current.some(e=>e.id===n.from)&&a.current.some(t=>t.id===e)&&(o(t=>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?eq(s,i):null),d=eK(t)??(r?eO(s,i,Date.now()):null);null!==d&&null!==c&&u?.(c,d);let m=eG(t)??(r?eV(s,i):null);null!==m&&null!==c&&h?.(c,m)},connect:(e,t)=>{let n=a.current,l=n.find(t=>t.id===e),s=n.find(e=>e.id===t);void 0!==l&&void 0!==s&&$(l.type,s.type)&&o(n=>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=eD(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:q,winsRef:C,connsRef:I,connectingRef:R,connectCleanupRef:A,focus:_,setConns:b,setConnecting:j,onScopeBind:t.onScopeBind,onScopeUnbind:t.onScopeUnbind,onConnectorBind:t.onConnectorBind,onConnectorUnbind:t.onConnectorUnbind});return M.current=en,(0,a.useEffect)(()=>()=>{null!==A.current&&(A.current(),A.current=null)},[]),{wins:m,snapPrev:p,palOpen:g,setPalOpen:v,conns:x,connecting:y,view:w,api:{add:G,toggleTool:V,focus:_,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=eK(a)??eO(n,s,Date.now());null!==r&&null!==i&&t.onScopeUnbind?.(i,r);let o=eG(a)??eV(n,s);null!==o&&null!==i&&t.onConnectorUnbind?.(i,o)}B(e)},minimize:U,restore:W,maximize:H,update:K,setSnap:X,commitSnap:Z,tileAll:Y,splitFront:Q,cascade:J,startConnect:ee,confirmConnect:et,cancelConnect:en,removeConn:ea,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:el,linkedFilesRoot:es,linkedFilesContext:ei,linkedAllFilesRoots:er,linkedConnectorCapsuleIds:eo,linkedConnectorCapsuleSetIds:ec,linkedFigmaSnapshotRunIds:ed,currentFilesContext:eu,zoomTo:P,fitView:D,resetView:F,panBy:z,rect:O}}}(u,{onScopeBind:(0,a.useCallback)(async(e,t)=>k(e,t),[k]),onScopeUnbind:(0,a.useCallback)((e,t)=>{let n=w(e);if(void 0===n)return;let a=eB(eU(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=eW(s),r=eU(s);if(a=eH(t),i.some(e=>eH(e)===a))return!0;let o=e_(h);if(r.length+i.length>=o)return v(r.length+i.length,o);let c=(n=h.maxLocalKnowledgeSources,l=eH(t),i.some(e=>eH(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,h,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=eW(a),n.filter(e=>eH(e)!==l));(0,j.updateChatLocalKnowledgeScopes)(a.id,s.length>0?s:null).then(e=>{d.replaceChat(e.chat)}).catch(()=>void 0)},[w,d])});m.current=N.wins,(0,a.useEffect)(()=>{if(null!==N.wins)for(let e of N.conns){let t=N.wins.find(t=>t.id===e.a),n=N.wins.find(t=>t.id===e.b);if(void 0===t||void 0===n)continue;let a=e.boundChatWindowId??("chat"===t.type?t.id:"chat"===n.type?n.id:null);if(null===a)continue;let l=eO(t,n,Date.now());if(null===l)continue;let s=eK(e);cF(s)!==cF(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),[A,M]=(0,a.useState)(!1),[P,D]=(0,a.useState)(!1),O=N.wins?.length??0,K=function(e){if(null===e||0===e.length)return null;let t=null;for(let n=0;n<e.length;n++){let a=e[n];if(!0!==a.minimized){if(null===t){t=a;continue}a.z>t.z&&(t=a)}}return t}(N.wins),_=(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]),B=(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)(()=>M(!1),[]),Z=(0,a.useCallback)(()=>M(!0),[]),ee=(0,a.useRef)(null),et=(0,a.useCallback)(e=>{ee.current=e},[]),en=function(e){let{apply:t}=e,n=e.limit??100,[l,s]=(0,a.useState)(nV),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(nV)},[]);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?nH(e):null,redoLabel:void 0!==t?nH(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=_.has(e);N.api.toggleTool(e),en.push({kind:"ui.panel.toggle",panel:e,before:t,after:!t})},[N.api,_,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=nG(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 nW)if(nG(e)===nG(t))return!0;return!1})(e.chord)),[t]);if(i.length>0)throw new nY(i);if(r.length>0)throw new nQ(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:nJ,dispatch:(0,a.useCallback)(e=>{"undo"===e?en.undo():"redo"===e?en.redo():"focus-status"===e&&ee.current?.focus()},[en])}),(0,a.useEffect)(()=>{let e=e=>{(e.metaKey||e.ctrlKey)&&("k"===e.key||"K"===e.key)&&(e.preventDefault(),M(e=>!e))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]);let ei=(0,a.useMemo)(()=>(function(e,t,n,a,l,s){let i=[];for(let e of cz){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 cO){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"),ec=void 0!==d.activeProject,ed=d.activeProject?.available===!0,eu=(t={loading:d.loading,error:d.error,hasProject:ec,projectAvailable:ed,noEligibleModels:d.noEligibleModels}).loading?"Loading shell…":void 0!==t.error?"Shell error":t.hasProject?t.projectAvailable?t.noEligibleModels?"Gateway setup required":"Ready":"Project unavailable":"No project selected",em=0===(i=(N.wins??[]).filter(e=>"review"===e.type)).length?"No review open":i.some(e=>"string"==typeof e.cfg.runId&&e.cfg.runId.length>0)?"Evidence ready":"Review window open",eh=void 0!==(l=d.activeChat?.branchLabel)&&l.trim().length>0?l:"No branch selected",ep=S?(0,n.jsx)(tk,{types:E,order:cz,onAdd:Y,onClose:W}):null;return(0,n.jsx)(s,{value:d,children:(0,n.jsx)(y.Provider,{value:B,children:(0,n.jsxs)("div",{className:"app",children:[(0,n.jsx)("a",{className:"skip-link",href:"#main",children:"Skip to content"}),(0,n.jsx)("h1",{className:"visually-hidden",children:"Keiko workspace"}),(0,n.jsx)(L,{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:_,onTool:ea,onNewChat:el,theme:r,onToggleTheme:o}),(0,n.jsxs)("div",{className:"stage",id:"main",tabIndex:-1,children:[(0,n.jsx)(tl,{ws:N,wsRef:u,openPalette:U,palette:ep}),null!==f&&(0,n.jsxs)("div",{className:"source-limit-alert",role:"alert",children:[(0,n.jsx)("span",{children:f}),(0,n.jsx)("button",{type:"button",className:"source-limit-alert-dismiss","aria-label":"Dismiss source connection notice",onClick:()=>g(null),children:"×"})]})]}),(0,n.jsx)(z,{openTools:_,onTool:ea})]}),(0,n.jsx)(q,{winCount:O,windows:N.wins??[],windowPaletteOpen:P,onToggleWindowPalette:H,onSelectWindow:V,onCloseWindowPalette:G,mode:c.mode,selectedModel:d.selectedModel,projectName:eo,branchLabel:eh,shellStatusLabel:eu,evidenceStatusLabel:em,statusRef:et}),null!==I&&(0,n.jsx)(tj,{type:I,types:E,filesContext:N.api.currentFilesContext(),onConfirm:Q,onClose:J}),A&&(0,n.jsx)(ts,{commands:ei,onClose:X}),er?(0,n.jsx)(to,{}):null,(0,n.jsx)(cD,{})]})})})}function c_(){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)(cK,{})}):(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)(c_,{})}],89199)}]);
|