@duckcodeailabs/dql-cli 1.13.4 → 1.13.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/assets/dql-notebook/assets/{AgentLogPage-DYmHO6_i.js → AgentLogPage-BzQOKjyV.js} +1 -1
  2. package/dist/assets/dql-notebook/assets/{AiBuildDialog-BfhaOd1h.js → AiBuildDialog-CTxha499.js} +1 -1
  3. package/dist/assets/dql-notebook/assets/{AiBuildResult-DLKFAe6R.js → AiBuildResult--MuD_I6g.js} +1 -1
  4. package/dist/assets/dql-notebook/assets/{AiSidePanel-C6Z3URGr.js → AiSidePanel-DcI4PMJ1.js} +1 -1
  5. package/dist/assets/dql-notebook/assets/{AnalyticsHome-uG3xCP_s.js → AnalyticsHome-Dq54vjNz.js} +1 -1
  6. package/dist/assets/dql-notebook/assets/{AppsView-DfieNjkh.js → AppsView-0SlwWYex.js} +4 -4
  7. package/dist/assets/dql-notebook/assets/{BlockStudio-90J_wvWL.js → BlockStudio-CxxXZD3M.js} +1 -1
  8. package/dist/assets/dql-notebook/assets/{BusinessArtifactView-_zSMae5q.js → BusinessArtifactView-DxdAmeUN.js} +1 -1
  9. package/dist/assets/dql-notebook/assets/{DbtFirstModelingPage-DoXiPssu.js → DbtFirstModelingPage-y81gFg_b.js} +1 -1
  10. package/dist/assets/dql-notebook/assets/{GitPage-CUfAhS67.js → GitPage-GQtcwncb.js} +1 -1
  11. package/dist/assets/dql-notebook/assets/{GlobalAiRail-ovtL7nQu.js → GlobalAiRail-DM4wkxR_.js} +1 -1
  12. package/dist/assets/dql-notebook/assets/{GovernedContextPage-CaMiKAzA.js → GovernedContextPage-B8Ft6JES.js} +1 -1
  13. package/dist/assets/dql-notebook/assets/{HelpDocsPage-CEGUx28b.js → HelpDocsPage-DnD4nMuF.js} +1 -1
  14. package/dist/assets/dql-notebook/assets/{HomePage-2v3SRf8V.js → HomePage-Ehb0ITj-.js} +1 -1
  15. package/dist/assets/dql-notebook/assets/{LineageDAG-AaqLEiBN.js → LineageDAG-Lvjc2AQX.js} +1 -1
  16. package/dist/assets/dql-notebook/assets/{LineageDetailView-CFc8pm91.js → LineageDetailView-DX32pfbp.js} +1 -1
  17. package/dist/assets/dql-notebook/assets/{LineageDrawer-DOkFjPq-.js → LineageDrawer-CFq3jPfk.js} +1 -1
  18. package/dist/assets/dql-notebook/assets/{LineagePathBreadcrumb-BrDwCuMs.js → LineagePathBreadcrumb-CVHXuHls.js} +1 -1
  19. package/dist/assets/dql-notebook/assets/{MiniLineageGraph-CiHtQs3y.js → MiniLineageGraph-BKaeT5Kt.js} +1 -1
  20. package/dist/assets/dql-notebook/assets/{NewBlockModal-DAgJZbws.js → NewBlockModal-DI-JDzFH.js} +1 -1
  21. package/dist/assets/dql-notebook/assets/{NewNotebookModal-xjG7nZ3O.js → NewNotebookModal-Csw6eF74.js} +1 -1
  22. package/dist/assets/dql-notebook/assets/{NotebookEditor-CXZaKfYT.js → NotebookEditor-FEqs3789.js} +1 -1
  23. package/dist/assets/dql-notebook/assets/{ReadinessPage-MuJBFwwg.js → ReadinessPage-Bk0S_MEA.js} +1 -1
  24. package/dist/assets/dql-notebook/assets/{SetupOnboarding-vKFtKtjh.js → SetupOnboarding-DyLaPFGn.js} +1 -1
  25. package/dist/assets/dql-notebook/assets/{SkillsPage-DCFVOV5f.js → SkillsPage-DLHyvhci.js} +1 -1
  26. package/dist/assets/dql-notebook/assets/{TrustBadge-TcwXFFHK.js → TrustBadge-CIDLj2A6.js} +1 -1
  27. package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel-C0oKTU6G.js +88 -0
  28. package/dist/assets/dql-notebook/assets/{answer-to-notebook-DCFWlHB7.js → answer-to-notebook-CFEJHLvs.js} +1 -1
  29. package/dist/assets/dql-notebook/assets/{arrow-left-BLnlJAtp.js → arrow-left-B-Zdcyvm.js} +1 -1
  30. package/dist/assets/dql-notebook/assets/{arrow-right-BmUAb1aW.js → arrow-right-Cn8TM7cp.js} +1 -1
  31. package/dist/assets/dql-notebook/assets/{book-open-text-bdSChSag.js → book-open-text-Bko2NNUs.js} +1 -1
  32. package/dist/assets/dql-notebook/assets/{circle-x-Cc6dEaf4.js → circle-x-AWJAmUBB.js} +1 -1
  33. package/dist/assets/dql-notebook/assets/{dagre.esm-CPebQKQ9.js → dagre.esm-Cl_ucrRh.js} +1 -1
  34. package/dist/assets/dql-notebook/assets/{external-link-rmXvubf3.js → external-link-DN57tb5f.js} +1 -1
  35. package/dist/assets/dql-notebook/assets/{grip-vertical-Sg4zd5-Q.js → grip-vertical-BOWwFFva.js} +1 -1
  36. package/dist/assets/dql-notebook/assets/{index-mQd_pC-P.js → index-Ck-wqvV2.js} +127 -127
  37. package/dist/assets/dql-notebook/assets/{link-2-BLaPoFxW.js → link-2-xUhbfBs8.js} +1 -1
  38. package/dist/assets/dql-notebook/assets/{list-tree-j0s4asFK.js → list-tree-BDWcBr67.js} +1 -1
  39. package/dist/assets/dql-notebook/assets/{minimize-2-Cl4pef4s.js → minimize-2-CEeNoMTS.js} +1 -1
  40. package/dist/assets/dql-notebook/assets/{panel-right-open-Clz-FtWi.js → panel-right-open-DnSeUvOY.js} +1 -1
  41. package/dist/assets/dql-notebook/assets/{play-DFdazMg7.js → play-EoDj8-fa.js} +1 -1
  42. package/dist/assets/dql-notebook/assets/{rotate-ccw-C3tTaR7s.js → rotate-ccw-BAMxWT9A.js} +1 -1
  43. package/dist/assets/dql-notebook/assets/{semantic-fields-DIAhTlfy.js → semantic-fields-BwLOs1kl.js} +1 -1
  44. package/dist/assets/dql-notebook/assets/{sliders-horizontal-BUiu2tfY.js → sliders-horizontal-BYkm8SWW.js} +1 -1
  45. package/dist/assets/dql-notebook/assets/{star--Yq77aH4.js → star-sVexqNCs.js} +1 -1
  46. package/dist/assets/dql-notebook/assets/{triangle-alert-D5Ng-xZO.js → triangle-alert-D2njv4o4.js} +1 -1
  47. package/dist/assets/dql-notebook/assets/{upload-L8BKQAxP.js → upload-CXTMxIA8.js} +1 -1
  48. package/dist/assets/dql-notebook/assets/{usePersistedAgentThreadId-DBu97YaM.js → usePersistedAgentThreadId-CPDeaAgL.js} +1 -1
  49. package/dist/assets/dql-notebook/assets/{user-round-BK5N1cJW.js → user-round-zVsI_uud.js} +1 -1
  50. package/dist/assets/dql-notebook/assets/{wand-sparkles-D8XDQD9z.js → wand-sparkles-BMIwIzXT.js} +1 -1
  51. package/dist/assets/dql-notebook/assets/{workflow-Bl9zwG0q.js → workflow-Dj9y1sNk.js} +1 -1
  52. package/dist/assets/dql-notebook/assets/{wrench-C-zLCMbW.js → wrench-DPQi6zrs.js} +1 -1
  53. package/dist/assets/dql-notebook/assets/{x-stiJ-sP7.js → x-XhhbtinL.js} +1 -1
  54. package/dist/assets/dql-notebook/index.html +1 -1
  55. package/dist/llm/answer-loop-tools.d.ts +3 -1
  56. package/dist/llm/answer-loop-tools.d.ts.map +1 -1
  57. package/dist/llm/answer-loop-tools.js +31 -23
  58. package/dist/llm/answer-loop-tools.js.map +1 -1
  59. package/dist/llm/providers/dql-agent-provider.d.ts +3 -1
  60. package/dist/llm/providers/dql-agent-provider.d.ts.map +1 -1
  61. package/dist/llm/providers/dql-agent-provider.js +278 -19
  62. package/dist/llm/providers/dql-agent-provider.js.map +1 -1
  63. package/dist/llm/types.d.ts +29 -2
  64. package/dist/llm/types.d.ts.map +1 -1
  65. package/dist/local-runtime.d.ts +176 -4
  66. package/dist/local-runtime.d.ts.map +1 -1
  67. package/dist/local-runtime.js +1775 -372
  68. package/dist/local-runtime.js.map +1 -1
  69. package/dist/package.json +10 -10
  70. package/dist/providers/oauth/claude-oauth.d.ts +1 -1
  71. package/dist/providers/oauth/claude-oauth.d.ts.map +1 -1
  72. package/dist/providers/oauth/claude-oauth.js +18 -11
  73. package/dist/providers/oauth/claude-oauth.js.map +1 -1
  74. package/dist/providers/oauth/codex-oauth.d.ts +1 -1
  75. package/dist/providers/oauth/codex-oauth.d.ts.map +1 -1
  76. package/dist/providers/oauth/codex-oauth.js +9 -1
  77. package/dist/providers/oauth/codex-oauth.js.map +1 -1
  78. package/dist/providers/subscription-cli.d.ts +1 -1
  79. package/dist/providers/subscription-cli.d.ts.map +1 -1
  80. package/dist/providers/subscription-cli.js +33 -4
  81. package/dist/providers/subscription-cli.js.map +1 -1
  82. package/package.json +10 -10
  83. package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel-Cu-YgIe4.js +0 -88
@@ -0,0 +1,88 @@
1
+ import{c as Ie,r as f,a as re,j as t,d as Lt,g as dt,l as ye,b7 as li,f as ct,L as Ve,aK as di,ba as pr,B as gt,e as fr,u as Dt,t as gr,a5 as ci,bb as Ue,E as ui,H as pi,bc as fi,w as gi,S as Ge,aH as hr,b as Nt,b9 as Ze,P as ot,D as hi,G as xr,bd as xi,b0 as rn,a0 as Ut,ar as yi}from"./index-Ck-wqvV2.js";import{S as _t,P as mi,F as ut,E as bi,M as vi,R as gn,d as hn,e as ji,A as wi,g as Si,u as ki}from"./usePersistedAgentThreadId-CPDeaAgL.js";import{C as Ai}from"./AiBuildResult--MuD_I6g.js";import{T as Kt}from"./triangle-alert-D2njv4o4.js";import{U as Ci}from"./user-round-zVsI_uud.js";import{X as zt}from"./x-XhhbtinL.js";import{L as pt}from"./list-tree-BDWcBr67.js";import{W as Pt}from"./wrench-DPQi6zrs.js";import{M as qi}from"./minimize-2-CEeNoMTS.js";import{A as Ri}from"./arrow-right-Cn8TM7cp.js";/**
2
+ * @license lucide-react v0.563.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const Ii=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],_i=Ie("archive",Ii);/**
7
+ * @license lucide-react v0.563.0 - ISC
8
+ *
9
+ * This source code is licensed under the ISC license.
10
+ * See the LICENSE file in the root directory of this source tree.
11
+ */const zi=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],yr=Ie("chevron-up",zi);/**
12
+ * @license lucide-react v0.563.0 - ISC
13
+ *
14
+ * This source code is licensed under the ISC license.
15
+ * See the LICENSE file in the root directory of this source tree.
16
+ */const Ti=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Ei=Ie("circle",Ti);/**
17
+ * @license lucide-react v0.563.0 - ISC
18
+ *
19
+ * This source code is licensed under the ISC license.
20
+ * See the LICENSE file in the root directory of this source tree.
21
+ */const Mi=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],mr=Ie("copy",Mi);/**
22
+ * @license lucide-react v0.563.0 - ISC
23
+ *
24
+ * This source code is licensed under the ISC license.
25
+ * See the LICENSE file in the root directory of this source tree.
26
+ */const Bi=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],Tt=Ie("lightbulb",Bi);/**
27
+ * @license lucide-react v0.563.0 - ISC
28
+ *
29
+ * This source code is licensed under the ISC license.
30
+ * See the LICENSE file in the root directory of this source tree.
31
+ */const $i=[["circle",{cx:"6",cy:"19",r:"3",key:"1kj8tv"}],["path",{d:"M9 19h8.5a3.5 3.5 0 0 0 0-7h-11a3.5 3.5 0 0 1 0-7H15",key:"1d8sl"}],["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}]],sn=Ie("route",$i);/**
32
+ * @license lucide-react v0.563.0 - ISC
33
+ *
34
+ * This source code is licensed under the ISC license.
35
+ * See the LICENSE file in the root directory of this source tree.
36
+ */const Li=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],xn=Ie("save",Li);/**
37
+ * @license lucide-react v0.563.0 - ISC
38
+ *
39
+ * This source code is licensed under the ISC license.
40
+ * See the LICENSE file in the root directory of this source tree.
41
+ */const Di=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],Ni=Ie("send",Di);/**
42
+ * @license lucide-react v0.563.0 - ISC
43
+ *
44
+ * This source code is licensed under the ISC license.
45
+ * See the LICENSE file in the root directory of this source tree.
46
+ */const Pi=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Dn=Ie("square",Pi);/**
47
+ * @license lucide-react v0.563.0 - ISC
48
+ *
49
+ * This source code is licensed under the ISC license.
50
+ * See the LICENSE file in the root directory of this source tree.
51
+ */const Fi=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],Wi=Ie("zap",Fi),Yt=[{mode:"auto",label:"Auto",hint:"Adapts per question — fast for lookups, thorough for hard ones"},{mode:"low",label:"Low · fast",hint:"Fewer thinking tokens, skips extra verification"},{mode:"medium",label:"Medium · balanced",hint:"More thinking, still skips the heavy verification"},{mode:"high",label:"High · thorough",hint:"Most thinking, cross-checks the number — slower"}];function Nn({t:e,value:n,onChange:r}){const[i,s]=f.useState(null),[o,l]=f.useState(!1),d=f.useRef(null);f.useEffect(()=>{let g=!1;return re.getProviderSettings().then(({providers:a})=>{g||s(a.find(u=>u.active)??null)}).catch(()=>{}),()=>{g=!0}},[]),f.useEffect(()=>{if(!o)return;const g=a=>{d.current&&!d.current.contains(a.target)&&l(!1)};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[o]);const c=Yt.find(g=>g.mode===n)??Yt[0],p=i?[i.label,i.model].filter(Boolean).join(" · "):null;return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[p?t.jsxs("span",{title:"Connected model",style:Pn(e),children:[t.jsx(Ei,{size:7,fill:e.success,color:e.success}),t.jsx("span",{style:{color:e.textSecondary},children:p})]}):null,t.jsxs("div",{ref:d,style:{position:"relative"},children:[t.jsxs("button",{type:"button",onClick:()=>l(g=>!g),title:"How hard the model thinks for this thread",style:{...Pn(e),cursor:"pointer"},children:[t.jsx(Wi,{size:12,color:e.textMuted}),t.jsxs("span",{style:{color:e.textSecondary},children:["Thinking: ",c.label]}),t.jsx(Lt,{size:12,color:e.textMuted})]}),o?t.jsx("div",{role:"menu",style:Oi(e),children:Yt.map(g=>{const a=g.mode===n;return t.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":a,onClick:()=>{r(g.mode),l(!1)},style:Hi(e,a),children:[t.jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontWeight:a?600:500,color:e.textPrimary},children:g.label}),a?t.jsx(dt,{size:13,color:e.accent}):null]}),t.jsx("span",{style:{display:"block",fontSize:11,color:e.textMuted,marginTop:2},children:g.hint})]},g.mode)})}):null]})]})}function Pn(e){return{display:"inline-flex",alignItems:"center",gap:6,padding:"4px 9px",borderRadius:8,border:`1px solid ${e.btnBorder}`,background:e.btnBg,fontSize:12,lineHeight:1.2,whiteSpace:"nowrap"}}function Oi(e){return{position:"absolute",bottom:"calc(100% + 6px)",left:0,zIndex:30,width:264,background:e.cellBg,border:`1px solid ${e.cellBorder}`,borderRadius:10,padding:4,boxShadow:"0 8px 24px rgba(0,0,0,0.18)"}}function Hi(e,n){return{display:"block",width:"100%",textAlign:"left",padding:"8px 10px",borderRadius:7,border:"none",background:n?e.pillBg:"transparent",cursor:"pointer"}}const Qi={draft:"#8b949e",review:"#d29922",certified:"#3fb950",deprecated:"#f85149",pending_recertification:"#db6d28"},Vi={queued:"#8b949e",generating:"#4c8dff",running:"#4c8dff",saving:"#4c8dff",saved:"#2ea043",ready:"#2ea043",blocked:"#f85149",needs_attention:"#d29922"},Gi={queued:"Queued",generating:"Generating",running:"Running",saving:"Saving",saved:"Saved",ready:"Ready",blocked:"Blocked",needs_attention:"Needs review",draft:"Draft",review:"In review",certified:"Certified",deprecated:"Deprecated",pending_recertification:"Recertify"},Ui={draft:pr,queued:di,generating:Ve,running:Ve,saving:Ve,ready:ct,saved:ct,blocked:Kt,needs_attention:Kt,review:li,certified:ye,deprecated:_i,pending_recertification:Kt},Ki=new Set(["generating","running","saving"]);function Yi(e){return Qi[e]??Vi[e]??"#8b949e"}function Xi(e){return Gi[e]??e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g," ")}function Ji({status:e,t:n,label:r}){const i=Yi(e),s=Ui[e]??pr,o=r??Xi(e);return t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:10,fontWeight:800,color:i,background:`${i}18`,border:`1px solid ${i}33`,borderRadius:999,padding:"2px 8px",fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.03em",whiteSpace:"nowrap"},children:[t.jsx(s,{size:11,strokeWidth:2.2,className:Ki.has(e)?"spin":void 0}),o]})}function Zi(e){const{t:n,name:r,status:i="draft",description:s,dql:o,sqlPreview:l,grain:d,outputs:c=[],dimensions:p=[],entities:g=[],examples:a=[],sourceTables:u=[],evidence:y=[],certifierVerdict:h,owner:b,actions:m}=e,[C,F]=f.useState(!1),[$,D]=f.useState(!1);return t.jsxs("section",{style:{border:`1px solid ${n.cellBorder}`,borderRadius:10,background:n.cellBg,padding:14,display:"grid",gap:10,fontFamily:n.font},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[t.jsx(gt,{size:14,strokeWidth:2,color:n.accent}),t.jsx("div",{style:{fontSize:13,fontWeight:850,color:n.textPrimary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r}),t.jsx(Ji,{status:i,t:n}),d?t.jsxs("span",{style:on(n),children:["grain ",d]}):null]}),s?t.jsx("div",{style:{fontSize:12,color:n.textSecondary,lineHeight:1.5},children:s}):null,o?t.jsx(Fn,{open:C,onToggle:()=>F(R=>!R),label:"Governed DQL",t:n,lead:!0,children:t.jsx("pre",{style:Wn(n),children:o})}):null,l?t.jsx(Fn,{open:$,onToggle:()=>D(R=>!R),label:o?"Compiled SQL preview":"SQL this block will run",t:n,children:t.jsx("pre",{style:Wn(n),children:l})}):null,t.jsx(Xt,{label:"Outputs",items:c,t:n}),t.jsx(Xt,{label:"Dimensions",items:p,t:n}),t.jsx(Xt,{label:"Entities",items:g,t:n}),a.length>0?t.jsxs("div",{style:{display:"grid",gap:5},children:[t.jsx(br,{t:n,children:"Answers questions like"}),t.jsx("ul",{style:{margin:0,padding:"0 0 0 16px",display:"grid",gap:3},children:a.slice(0,3).map(R=>t.jsx("li",{style:{fontSize:11.5,color:n.textSecondary,lineHeight:1.45},children:R},R))})]}):null,u.length>0||y.length>0?t.jsxs("div",{style:{display:"grid",gap:6,border:`1px solid ${n.headerBorder}`,borderRadius:8,background:n.appBg,padding:10},children:[t.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:10.5,fontWeight:800,color:n.textSecondary,textTransform:"uppercase"},children:[t.jsx(ye,{size:12,color:n.accent})," Grounded on"]}),u.length>0?t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:u.map(R=>t.jsx("span",{style:on(n),children:R},R))}):null,y.slice(0,5).map((R,L)=>t.jsxs("div",{style:{border:`1px solid ${n.headerBorder}`,borderRadius:7,padding:8,background:n.cellBg},children:[t.jsx("div",{style:{fontSize:11,fontWeight:800,color:n.textSecondary,overflowWrap:"anywhere"},children:R.name}),t.jsxs("div",{style:{fontSize:10,color:n.textMuted,marginTop:3},children:[R.kind,R.reason?` · ${R.reason}`:""]}),R.description?t.jsx("div",{style:{fontSize:11,color:n.textMuted,lineHeight:1.35,marginTop:5},children:R.description}):null]},`${R.objectKey??R.name}-${L}`))]}):null,t.jsx(Ai,{t:n,verdict:h}),b?t.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11,color:n.textMuted},children:[t.jsx(Ci,{size:12,strokeWidth:2})," drafting as ",b]}):null,m?t.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:m}):null]})}function Fn({open:e,onToggle:n,label:r,t:i,lead:s,children:o}){return t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:n,style:{display:"inline-flex",alignItems:"center",gap:5,border:"none",background:"transparent",cursor:"pointer",color:s?i.accent:i.textSecondary,fontSize:11.5,fontWeight:s?800:700,fontFamily:i.font,padding:0},children:[e?t.jsx(Lt,{size:13,strokeWidth:2}):t.jsx(fr,{size:13,strokeWidth:2}),e?`Hide ${r.toLowerCase()}`:r]}),e?t.jsx("div",{style:{marginTop:7},children:o}):null]})}function Xt({label:e,items:n,t:r}){return n.length===0?null:t.jsxs("div",{style:{display:"grid",gap:5},children:[t.jsx(br,{t:r,children:e}),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:n.map(i=>t.jsx("span",{style:on(r),children:i},i))})]})}function br({t:e,children:n}){return t.jsx("div",{style:{fontSize:10,fontWeight:800,letterSpacing:"0.05em",textTransform:"uppercase",color:e.textMuted},children:n})}function on(e){return{fontSize:10.5,fontWeight:700,color:e.textSecondary,background:e.pillBg,borderRadius:999,padding:"2px 8px",fontFamily:e.fontMono}}function Wn(e){return{margin:0,fontFamily:e.fontMono,fontSize:11.5,whiteSpace:"pre-wrap",color:e.textSecondary,background:e.appBg,border:`1px solid ${e.headerBorder}`,borderRadius:7,padding:10,maxHeight:240,overflow:"auto"}}function On(){return t.jsx("span",{style:{color:"#ff7b72",marginLeft:2},children:"*"})}function Jt(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function es(e){const n=new Set,r=/@(metric|dim)\(([^)]+)\)/gi;let i;for(;i=r.exec(e);)n.add(i[2].trim());return Array.from(n)}function Hn({cell:e,onClose:n,onSaved:r,initialContent:i,initialName:s,initialDescription:o,initialTags:l,initialDomain:d,initialOwner:c}){var U;const{state:p,dispatch:g}=Dt(),a=gr[p.themeMode],u=f.useRef(null),[y,h]=f.useState(s||e.name||"new_block"),[b,m]=f.useState(d??""),[C,F]=f.useState(c??""),[$,D]=f.useState(o??p.notebookMetadata.description??""),[R,L]=f.useState((l??p.notebookMetadata.categories??[]).join(", ")),[V,M]=f.useState(i??e.content),[W,O]=f.useState(""),[se,k]=f.useState(""),[Z,_]=f.useState([]),[j,Y]=f.useState(!1),[X,ee]=f.useState(null),E=f.useMemo(()=>es(V),[V]),B=f.useMemo(()=>R.split(",").map(w=>w.trim()).filter(Boolean),[R]),te=[{id:"has-name",label:"Block has name",severity:"error",passed:!!y.trim()},{id:"has-owner",label:"Block has owner",severity:"error",passed:!!C.trim()},{id:"has-description",label:"Description",severity:"warning",passed:!!$.trim()},{id:"has-domain",label:"Domain",severity:"warning",passed:!!b.trim()},{id:"has-tags",label:"Has at least one tag",severity:"warning",passed:B.length>0},{id:"has-llm-context",label:"Has LLM context (for agents)",severity:"warning",passed:!!W.trim()}],G=te.some(w=>w.severity==="error"&&!w.passed);f.useEffect(()=>{var w;(w=u.current)==null||w.focus()},[]),f.useEffect(()=>{const w=S=>{S.key==="Escape"&&n()};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[n]);const xe=ci(b,p.authoredDomains),ue=`${b.trim()?`blocks/${Jt(b)}/`:"blocks/"}${Jt(y)||"new-block"}.dql`,H=async()=>{var w,S,K;if(G){ee("Enter the block name and owner before saving.");return}if(!V.trim()){ee("Block content is required.");return}Y(!0),ee(null);try{const ne=se.split(`
52
+ `).map(pe=>pe.trim()).filter(Boolean),we=Z.map(pe=>({question:pe.question.trim(),sql:pe.sql.trim()||void 0})).filter(pe=>pe.question),me=await re.saveAsBlock({cellId:e.id,notebookPath:((w=p.activeFile)==null?void 0:w.path)??null,name:y.trim(),domain:b.trim()||void 0,owner:C.trim()||void 0,content:V,description:$.trim()||void 0,tags:B,metricRefs:E,llmContext:W.trim()||void 0,examples:we.length>0?we:void 0,invariants:ne.length>0?ne:void 0,reviewRequired:!!((S=e.datasetRefs)!=null&&S.length),datasetRefs:e.datasetRefs,lineage:(K=e.dqlArtifact)==null?void 0:K.lineage}),We={name:`${Jt(y)||"new-block"}.dql`,path:me.path,type:"block",folder:"blocks"};p.files.some(pe=>pe.path===me.path)||g({type:"FILE_ADDED",file:We});const $e=await re.openBlockStudio(me.path);g({type:"OPEN_BLOCK_STUDIO",file:We,payload:$e}),r==null||r({...me,name:y.trim()}),n()}catch(ne){ee(ne instanceof Error?ne.message:String(ne))}finally{Y(!1)}},A={width:"100%",background:a.inputBg,border:`1px solid ${X?a.error:a.inputBorder}`,borderRadius:6,color:a.textPrimary,fontSize:13,fontFamily:a.font,padding:"8px 12px",outline:"none",boxSizing:"border-box"};return t.jsx("div",{onClick:w=>{w.target===w.currentTarget&&n()},style:{position:"fixed",inset:0,background:a.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1100,backdropFilter:"blur(4px)"},children:t.jsxs("div",{style:{width:760,maxWidth:"calc(100vw - 48px)",maxHeight:"calc(100vh - 48px)",overflow:"auto",background:a.modalBg,border:`1px solid ${a.cellBorder}`,borderRadius:12,boxShadow:"0 20px 60px rgba(0,0,0,0.5)"},children:[t.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsx("h2",{style:{margin:0,fontSize:16,fontWeight:600,color:a.textPrimary,fontFamily:a.font},children:"Save as Block"}),t.jsx("button",{onClick:n,style:{background:"transparent",border:"none",color:a.textMuted,cursor:"pointer",fontSize:18},children:"×"})]}),t.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsxs("label",{style:{fontSize:12,color:a.textSecondary,fontFamily:a.font},children:["Block Name ",t.jsx(On,{})]}),t.jsx("input",{ref:u,value:y,onChange:w=>h(w.target.value),style:A})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("label",{style:{fontSize:12,color:a.textSecondary,fontFamily:a.font},children:"Domain"}),t.jsxs("select",{value:b,onChange:w=>m(w.target.value),style:A,children:[t.jsx("option",{value:"",children:"Global / cross-domain"}),xe.map(w=>t.jsx("option",{value:w.value,disabled:w.disabled,children:w.label},w.value))]})]})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsxs("label",{style:{fontSize:12,color:a.textSecondary,fontFamily:a.font},children:["Owner ",t.jsx(On,{})]}),t.jsx("input",{value:C,onChange:w=>F(w.target.value),style:A,placeholder:"data-platform@company.com"})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("label",{style:{fontSize:12,color:a.textSecondary,fontFamily:a.font},children:"Tags"}),t.jsx("input",{value:R,onChange:w=>L(w.target.value),style:A,placeholder:"revenue, dashboard"})]})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("label",{style:{fontSize:12,color:a.textSecondary,fontFamily:a.font},children:"Description"}),t.jsx("input",{value:$,onChange:w=>D(w.target.value),style:A})]}),t.jsxs("details",{style:{border:`1px solid ${a.cellBorder}`,borderRadius:6,padding:"8px 12px"},children:[t.jsx("summary",{style:{fontSize:12,fontWeight:600,color:a.textSecondary,fontFamily:a.font,cursor:"pointer"},children:"Agent-facing metadata (optional — helps AI tools ground answers on this block)"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10,paddingTop:10},children:[t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("label",{style:{fontSize:12,color:a.textSecondary,fontFamily:a.font},children:"How should an AI describe this block?"}),t.jsx("textarea",{value:W,onChange:w=>O(w.target.value),rows:3,placeholder:'One paragraph. E.g. "Monthly revenue recognized from closed-won deals, grouped by billing month. Excludes refunds."',style:{...A,fontFamily:a.font,lineHeight:1.5,resize:"vertical"}})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("label",{style:{fontSize:12,color:a.textSecondary,fontFamily:a.font},children:"Invariants (one per line)"}),t.jsx("textarea",{value:se,onChange:w=>k(w.target.value),rows:2,placeholder:`Revenue is never negative
53
+ Each row is a unique month`,style:{...A,fontFamily:a.fontMono,lineHeight:1.5,resize:"vertical"}})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("label",{style:{fontSize:12,color:a.textSecondary,fontFamily:a.font},children:"Example questions (grounding for chat cells)"}),Z.map((w,S)=>t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr auto",gap:6},children:[t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[t.jsx("input",{value:w.question,onChange:K=>{const ne=[...Z];ne[S]={...ne[S],question:K.target.value},_(ne)},placeholder:"What was revenue last month?",style:A}),t.jsx("input",{value:w.sql,onChange:K=>{const ne=[...Z];ne[S]={...ne[S],sql:K.target.value},_(ne)},placeholder:"Optional SQL snippet",style:{...A,fontFamily:a.fontMono,fontSize:12}})]}),t.jsx("button",{type:"button",onClick:()=>_(Z.filter((K,ne)=>ne!==S)),style:{background:"transparent",border:`1px solid ${a.cellBorder}`,borderRadius:6,color:a.textMuted,cursor:"pointer",fontSize:12,padding:"0 10px"},children:"×"})]},S)),t.jsx("button",{type:"button",onClick:()=>_([...Z,{question:"",sql:""}]),style:{alignSelf:"flex-start",background:a.btnBg,border:`1px solid ${a.btnBorder}`,borderRadius:6,color:a.textSecondary,cursor:"pointer",fontSize:12,fontFamily:a.font,padding:"4px 10px"},children:"+ Add example"})]})]})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,padding:"10px 12px",background:a.pillBg,borderRadius:6,border:`1px solid ${a.cellBorder}`},children:[t.jsx("div",{style:{fontSize:11,fontWeight:700,color:a.textSecondary,fontFamily:a.font,letterSpacing:"0.06em",textTransform:"uppercase"},children:"Governance checks"}),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:te.map(w=>{const S=w.passed?"#3fb950":w.severity==="error"?"#ff7b72":"#e3b341",K=w.passed?"✓":w.severity==="error"?"✕":"!";return t.jsxs("span",{title:w.passed?`${w.label} — passed`:`${w.label} — ${w.severity}`,style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11,fontFamily:a.font,color:S,background:`${S}18`,border:`1px solid ${S}55`,borderRadius:999,padding:"2px 10px"},children:[t.jsx("span",{style:{fontWeight:700},children:K}),w.label]},w.id)})})]}),t.jsx("div",{style:{fontSize:12,color:a.textMuted,fontFamily:a.fontMono,padding:"8px 12px",background:a.pillBg,borderRadius:6},children:ue}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("label",{style:{fontSize:12,color:a.textSecondary,fontFamily:a.font},children:"Content Preview"}),t.jsx("textarea",{value:V,onChange:w=>M(w.target.value),style:{...A,minHeight:220,resize:"vertical",fontFamily:a.fontMono,lineHeight:1.5}})]}),E.length>0&&t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,padding:"10px 12px",background:a.pillBg,borderRadius:6},children:[t.jsx("span",{style:{fontSize:11,color:a.textMuted,fontFamily:a.font},children:"Detected semantic refs:"}),E.map(w=>t.jsx("span",{style:{fontSize:11,color:a.accent,fontFamily:a.fontMono,background:`${a.accent}18`,borderRadius:999,padding:"2px 8px"},children:w},w))]}),X&&t.jsx("div",{style:{fontSize:12,color:a.error,fontFamily:a.font},children:X})]}),t.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${a.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[t.jsx("span",{style:{fontSize:11.5,color:a.textMuted,marginRight:"auto",alignSelf:"center"},children:(U=e.datasetRefs)!=null&&U.length?"This analysis uses imported or staged data, so it will be saved as a review-required draft. Certification requires project-controlled, contracted, tested, reproducible sources.":"DQL will certify this block now when its local checks pass; otherwise it is saved as a draft."}),t.jsx("button",{onClick:n,style:{background:a.btnBg,border:`1px solid ${a.btnBorder}`,borderRadius:6,color:a.textSecondary,cursor:"pointer",fontSize:13,fontFamily:a.font,padding:"7px 16px"},children:"Cancel"}),t.jsx("button",{onClick:H,disabled:j||G,title:G?"Fix governance errors to enable Save":void 0,style:{background:a.accent,border:`1px solid ${a.accent}`,borderRadius:6,color:"#fff",cursor:j||G?"not-allowed":"pointer",fontSize:13,fontFamily:a.font,padding:"7px 20px",opacity:j||G?.5:1},children:j?"Saving & checking…":"Save block"})]})]})})}function vr(e){return e.policy==="dynamic"||e.policy==="optional"}function ts({parameters:e,values:n,onChange:r,onReset:i,t:s,includeNonRuntime:o=!1,card:l=!1}){const d=e.filter(c=>o||vr(c));return d.length===0?null:t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:8},children:d.map(c=>{const p=Object.prototype.hasOwnProperty.call(n,c.name),g=p?n[c.name]:c.default,a=y=>r(c.name,y),u=c.type==="boolean"?t.jsxs("select",{"aria-label":c.name,value:String(g??""),onChange:y=>a(y.target.value),style:Qn(s),children:[t.jsx("option",{value:"",children:"Select…"}),t.jsx("option",{value:"true",children:"True"}),t.jsx("option",{value:"false",children:"False"})]}):t.jsx("input",{"aria-label":c.name,type:c.type==="number"?"number":c.type==="date"?"date":"text",value:Array.isArray(g)?g.join(", "):g==null?"":String(g),placeholder:c.type.endsWith("[]")?"Comma-separated values":c.required?"Required value":"Use default",onChange:y=>a(y.target.value),style:Qn(s)});return t.jsxs("label",{style:{display:"grid",gap:4,minWidth:0,...l?{padding:9,border:`1px solid ${s.cellBorder}`,borderRadius:7,background:s.appBg}:{}},children:[t.jsxs("span",{style:{display:"flex",gap:5,alignItems:"center",fontSize:10.5,fontWeight:750,color:s.textSecondary},children:[ns(c.name),c.required?t.jsx("span",{style:{color:s.error},children:"*"}):null]}),u,t.jsxs("span",{style:{display:"flex",alignItems:"center",gap:5,minHeight:14,fontSize:9.5,color:s.textMuted},children:[t.jsxs("span",{children:[c.type,o?` · ${c.policy}`:""]}),p&&i?t.jsx("button",{type:"button",onClick:()=>i(c.name),style:{marginLeft:"auto",border:0,padding:0,background:"transparent",color:s.accent,fontSize:9.5,cursor:"pointer"},children:"Reset"}):null]})]},c.name)})})}function ns(e){return e.replace(/[_-]+/g," ").replace(/\b\w/g,n=>n.toUpperCase())}function Qn(e){return{width:"100%",minWidth:0,boxSizing:"border-box",background:e.inputBg,border:`1px solid ${e.inputBorder}`,borderRadius:5,color:e.textPrimary,padding:"5px 7px",fontSize:11,fontFamily:e.font}}function rs(e){const n=e.filter(o=>o.kind==="run").map(is).filter(o=>!!o).slice(-6);if(n.length===0)return;const r=[...n].reverse().find(o=>{var l;return(l=o.result)==null?void 0:l.columns.length})??n[n.length-1],i=r.result,s=jr(Vn(r));return an({activeSurface:"notebook",conversationStateVersion:1,activeTurnId:r.id,activeTopic:r.question,conversationSummary:cs(n),turns:n,sourceAnswerId:r.id,sourceCertifiedBlock:r.sourceCertifiedBlock,sourceQuestion:r.question,sourceAnswerSummary:r.answerSummary,answerContract:Vn(r),dqlArtifact:r.dqlArtifact,cascade:r.cascade,resultColumns:i==null?void 0:i.columns,resultRowsSample:i==null?void 0:i.rowsSample,resultDimensionValues:i==null?void 0:i.dimensionValues,outputColumns:i==null?void 0:i.columns,requestedFilters:r.requestedFilters??Xe(s==null?void 0:s.filters),requestedDimensions:r.requestedDimensions??Xe(s==null?void 0:s.dimensions),priorLimit:r.topN??wr(s),priorMeasures:r.requestedMeasures??(i==null?void 0:i.measureColumns),contextPackId:r.contextPackId,trustLabel:r.trustLabel,reviewStatus:r.reviewStatus,certification:r.certification,route:r.route,sourceSql:r.sourceSql,updatedAt:r.completedAt})}function is(e){var a,u,y,h;const n=e.run.artifacts.find(b=>b.kind==="answer")??e.run.artifacts.find(b=>b.kind==="research_run")??e.run.artifacts[0],r=ce(n==null?void 0:n.payload),i=ss(r),s=ps(i),o=Array.isArray(i==null?void 0:i.rows)?i.rows.filter(b=>!!(b&&typeof b=="object"&&!Array.isArray(b))).slice(0,24):[],l=((a=ce(r==null?void 0:r.contextPack))==null?void 0:a.questionPlan)??(r==null?void 0:r.analysisPlan),d=jr(l),c=gs(s,o),p=us(d,s),g=oe(r==null?void 0:r.sourceCertifiedBlock)??((n==null?void 0:n.kind)==="answer"?oe(n.ref):void 0)??oe((u=ce(r==null?void 0:r.block))==null?void 0:u.name);return an({id:e.run.id,question:e.run.question,answerSummary:e.run.answer??e.run.summary,completedAt:e.run.completedAt,artifactKind:n==null?void 0:n.kind,sourceCertifiedBlock:g,route:oe((y=ce(r==null?void 0:r.route))==null?void 0:y.label)??oe((h=ce(r==null?void 0:r.route))==null?void 0:h.tier),trustLabel:oe(r==null?void 0:r.trustLabel),reviewStatus:oe(r==null?void 0:r.reviewStatus),certification:oe(r==null?void 0:r.certification),contextPackId:oe(r==null?void 0:r.contextPackId),requestedFilters:Xe(d==null?void 0:d.filters),requestedDimensions:Xe(d==null?void 0:d.dimensions),requestedMeasures:Xe(d==null?void 0:d.measures),answerContract:l,dqlArtifact:ls(r),cascade:ds(r),topN:wr(d),result:s.length>0||o.length>0?an({columns:s,rowsSample:o,dimensionValues:c,measureColumns:p,rowCount:os(i)}):void 0,sourceSql:as(r,i)})}function Vn(e){return e.answerContract}function jr(e){const n=ce(e);return ce(n==null?void 0:n.requestedShape)}function ss(e){const n=ce(e==null?void 0:e.researchRun),r=ce(e==null?void 0:e.result);return[e==null?void 0:e.result,e==null?void 0:e.resultPreview,n==null?void 0:n.resultPreview,n==null?void 0:n.result,r==null?void 0:r.result].map(ce).filter(s=>!!(s&&(Array.isArray(s.rows)||Array.isArray(s.columns)))).sort((s,o)=>Gn(o)-Gn(s))[0]}function Gn(e){const n=Array.isArray(e.rows)?e.rows.length:0,r=typeof e.rowCount=="number"&&Number.isFinite(e.rowCount)?e.rowCount:0;return n*1e5+r}function os(e){const n=e==null?void 0:e.rowCount;return typeof n=="number"&&Number.isFinite(n)?n:Array.isArray(e==null?void 0:e.rows)?e.rows.length:void 0}function as(e,n){var r,i;return oe(e==null?void 0:e.proposedSql)??oe(e==null?void 0:e.sql)??oe(n==null?void 0:n.sql)??oe((r=ce(e==null?void 0:e.query))==null?void 0:r.sql)??oe((i=ce(e==null?void 0:e.plan))==null?void 0:i.sql)}function ls(e){var r,i;const n=Ue(e==null?void 0:e.dqlArtifact);return n?{...n,source:n.source.slice(0,3e3),filters:(r=n.filters)==null?void 0:r.filter(s=>s.values.length>0).slice(0,12).map(s=>({...s,values:s.values.slice(0,12)})),orderBy:(i=n.orderBy)==null?void 0:i.slice(0,8)}:void 0}function ds(e){const n=ce(e==null?void 0:e.cascade);if(!n)return;const r=oe(n.terminalLane),i=oe(n.routeTier);if(!(!r&&!i))return{terminalLane:r,routeTier:i,label:oe(n.label),ref:oe(n.ref),artifactKind:oe(n.artifactKind),refusalCode:oe(n.refusalCode),outcome:ce(n.outcome)}}function cs(e){const n=e.slice(-3).map(r=>{var o,l;const i=(o=r.result)==null?void 0:o.columns.slice(0,5).join(", "),s=(l=r.result)!=null&&l.dimensionValues?Object.entries(r.result.dimensionValues).slice(0,3).map(([d,c])=>`${d}: ${c.slice(0,3).join(", ")}`).join("; "):"";return[`Q: ${r.question}`,r.answerSummary?`A: ${r.answerSummary}`:"",i?`Columns: ${i}`:"",s?`Values: ${s}`:""].filter(Boolean).join(" | ")}).filter(Boolean);return n.length>0?n.join(`
54
+ `):void 0}function wr(e){const n=ce(e==null?void 0:e.topN),r=n==null?void 0:n.n;return typeof r=="number"&&Number.isFinite(r)&&r>0?r:void 0}function us(e,n){const r=[...Xe(e==null?void 0:e.measures)??[],...n.filter(s=>/\b(revenue|sales|amount|total|count|average|avg|sum|spend|cost|margin|profit|value|points?|score|quantity|units?|rate|volume)\b/i.test(s.replace(/_/g," ")))],i=Array.from(new Set(r.map(s=>s.trim()).filter(Boolean))).slice(0,12);return i.length>0?i:void 0}function ce(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function ps(e){const r=(Array.isArray(e==null?void 0:e.columns)?e.columns:[]).map(fs).filter(o=>!!o),i=Array.isArray(e==null?void 0:e.rows)?e.rows.find(o=>o&&typeof o=="object"&&!Array.isArray(o)):void 0,s=i?Object.keys(i):[];return Array.from(new Set([...r,...s])).slice(0,32)}function Xe(e){if(!Array.isArray(e))return;const n=e.map(i=>typeof i=="string"?i.trim():"").filter(Boolean),r=Array.from(new Set(n)).slice(0,24);return r.length>0?r:void 0}function fs(e){if(typeof e=="string"&&e.trim())return e.trim();if(e&&typeof e=="object"){const n=e;return oe(n.name)??oe(n.field)??oe(n.key)}}function gs(e,n){const r=e.filter(s=>/\b(category|product|customer|account|user|segment|region|channel|type|name)\b/i.test(s.replace(/_/g," "))).slice(0,12),i={};for(const s of r){const o=[];for(const l of n){const d=ce(l),c=d==null?void 0:d[s],p=typeof c=="string"||typeof c=="number"?String(c).trim():"";if(!(!p||o.includes(p))&&(o.push(p),o.length>=24))break}o.length>0&&(i[hs(s)]=o)}return Object.keys(i).length>0?i:void 0}function hs(e){const n=e.toLowerCase();return n.includes("category")?"category":n.includes("product")?n.includes("name")?"product_name":"product":n.includes("customer")?n.includes("name")?"customer_name":"customer":n.includes("segment")?"segment":n.includes("region")?"region":n.includes("channel")?"channel":n.replace(/[^a-z0-9_]+/g,"_")}function oe(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function an(e){const n={};for(const[r,i]of Object.entries(e))i!=null&&(Array.isArray(i)&&i.length===0||typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0||(n[r]=i));return Object.keys(n).length>0?n:void 0}function xs(e){return JSON.stringify([e.kind,e.name??null,e.source,e.persistence??null,e.parameters??[],Object.entries(e.parameterValues??{}).sort(([n],[r])=>n.localeCompare(r)),e.executionReceipt??null])}function Sr(e,n){if(e.kind==="sql_block"){const s=new Map(n.columns.map(o=>[o.toLowerCase(),o]));return(e.filterableColumns??[]).flatMap(o=>{const l=s.get(o.column.toLowerCase());return l?[{column:l,field:o.predicateTarget,values:Un(n.rows.map(d=>d[l]))}]:[]})}if(e.kind!=="semantic_block"||e.persistence!=="transient")return[];const r=new Map(n.columns.map(s=>[s.toLowerCase(),s])),i=new Set((e.parameters??[]).flatMap(s=>{var o;return((o=s.binding)==null?void 0:o.kind)==="semantic_filter"?[s.binding.field.toLowerCase()]:[]}));return(e.dimensions??[]).flatMap(s=>{if(i.has(s.toLowerCase()))return[];const o=s.split(".").at(-1)??s,l=r.get(s.toLowerCase())??r.get(o.toLowerCase())??r.get(s.split(".").join("_").toLowerCase());if(!l)return[];const d=Un(n.rows.map(c=>c[l]));return[{column:l,field:s,values:d}]})}function ys(e,n,r,i){const s=Sr(e,n).find(m=>m.column===r);if(!s)throw new Error(`"${r}" is not an available semantic result filter.`);if(i==null||String(i).trim()==="")throw new Error("Choose a default filter value before adding the input.");const o=new Set((e.parameters??[]).map(m=>m.name)),l=ms(s.field.split(".").at(-1)??s.column);let d=l,c=2;for(;o.has(d);)d=`${l}_${c++}`;const p=Array.isArray(i)?i.map(String).join(", "):String(i),g=ui(p,d);let a=pi(e.source,{name:d,type:g,required:!1,defaultText:p,policy:"dynamic"});a=fi(a,d,s.field);const u=gi(a).map(m=>{var C,F,$;return{...m,...((C=m.binding)==null?void 0:C.kind)==="semantic_filter"&&m.binding.field?{binding:{kind:"semantic_filter",field:m.binding.field,operator:m.binding.operator??"equals"}}:((F=m.binding)==null?void 0:F.kind)==="limit"?{binding:{kind:"limit"}}:(($=m.binding)==null?void 0:$.kind)==="sql_value"?{binding:{kind:"sql_value"}}:{binding:void 0}}}),{executionReceipt:y,compiledSql:h,...b}=e;return{artifact:{...b,source:a,parameters:u,parameterValues:{...e.parameterValues??{},[d]:i}},parameterName:d}}function Un(e){const n=new Set,r=[];for(const i of e){if(typeof i!="string"&&typeof i!="number"&&typeof i!="boolean")continue;const s=`${typeof i}:${String(i)}`;if(!n.has(s)&&(n.add(s),r.push(i),r.length>=50))break}return r}function ms(e){const n=e.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return/^[a-z_][a-z0-9_]*$/.test(n)?n:"result_filter"}function kr(e,n,r){return e.map(i=>i.kind==="run"&&i.run.id===n?{kind:"run",id:r.id,run:r}:i)}function Ar(e){var r,i,s;const n=[];for(const o of e){if(o.kind==="user"){n.push({role:"user",text:o.text});continue}if(o.run.status==="blocked"||((r=o.run.artifacts)==null?void 0:r.some(d=>{const c=ie(d);return!!(c.executionError||c.warehouseFailure||c.analyticalFailure)}))){((i=n.at(-1))==null?void 0:i.role)==="user"&&n.pop();continue}n.push({role:"assistant",text:((s=o.run.answer)==null?void 0:s.trim())||o.run.summary})}return n.slice(-12)}const yn="dql.agent.active-runs.v1",Cr={conversation:"Chat",certified_answer:"Certified answer",semantic_answer:"Governed semantic answer",generated_answer:"Generated answer",research:"Research plan",sql_cell:"SQL cell",dql_block_draft:"DQL block draft",modeling_draft:"Modeling proposal",skill_draft:"Skill proposal",app_build:"App plan",clarify:"Clarify",blocked:"Blocked"};function bs({themeMode:e,title:n="AI Copilot",scopeHint:r="Auto routes to answer, research, SQL, block, or app",composerPlaceholder:i="Ask anything about your data…",onClearScope:s,examplePrompts:o,emptyHint:l,notebookPath:d,selectedObject:c,workspaceContext:p,initialMode:g="auto",initialInput:a="",initialItems:u,onItemsChange:y,threadId:h,onThreadIdChange:b,audience:m="analyst",autoRun:C,onInsertSql:F,onInsertDql:$,onReplaceDql:D,onArtifactReady:R,onReviewAuthoringProposal:L,onOpenBlock:V,onOpenResearch:M,onOpenApp:W,onRunningChange:O,answerFirstCards:se=!1,insertDqlActionLabel:k,replaceDqlActionLabel:Z,askLayout:_=!1}){const j=gr[e],Y=f.useRef(void 0),[X,ee]=f.useState(a),[E,B]=f.useState(u??[]),[te,G]=f.useState([]),[xe,ue]=f.useState(""),[H,A]=f.useState(!1),[U,w]=f.useState(null),[S,K]=f.useState(null),[ne,we]=f.useState(null),[me,We]=f.useState(()=>vs()),[$e,pe]=f.useState(!1),[q,ae]=f.useState([]),[ze,Ht]=f.useState(),kn=f.useCallback(x=>{We(x);try{window.localStorage.setItem(qr,x)}catch{}},[]),tt=f.useRef(null),An=f.useRef(a),Cn=f.useRef(null),Ke=f.useRef(null),Se=f.useRef(null),Oe=f.useRef(null),fe=f.useRef(null),Le=f.useRef(0),yt=f.useRef(""),De=f.useRef(null),nt=f.useCallback(()=>{yt.current="",De.current!==null&&(window.cancelAnimationFrame(De.current),De.current=null),ue("")},[]),ei=f.useCallback(x=>{yt.current+=x,De.current===null&&(De.current=window.requestAnimationFrame(()=>{De.current=null;const v=yt.current;yt.current="",v&&ue(z=>z+v)}))},[]);f.useEffect(()=>()=>{De.current!==null&&window.cancelAnimationFrame(De.current)},[]);const Ce=p==null?void 0:p.executionTarget,qn=Ce&&typeof Ce=="object"&&!Array.isArray(Ce)&&Ce.target==="connection"&&typeof Ce.connectionName=="string"?String(Ce.connectionName):void 0,ti=Ce&&typeof Ce=="object"&&!Array.isArray(Ce)&&Ce.target==="local";f.useEffect(()=>{let x=!1;return re.getConnections().then(v=>{if(x)return;const z=Object.keys(v.connections??{}).sort((N,P)=>N.localeCompare(P));ae(z),Ht(Rr(z,v.default,qn))}).catch(()=>{x||(ae([]),Ht(void 0))}),()=>{x=!0}},[qn]);const Rn=f.useCallback(x=>{Ht(x)},[]),[Ne,mt]=f.useState(null),[Te,Ye]=f.useState(null),[ni,Qt]=f.useState(""),In=f.useRef(null),bt=f.useRef(null);f.useEffect(()=>{!a||H||a!==An.current&&(An.current=a,ee(a))},[a,H]);const ri=f.useMemo(()=>Ar(E),[E]),vt=f.useRef(y);vt.current=y;const He=f.useRef(R);He.current=R,f.useEffect(()=>{var x;(x=vt.current)==null||x.call(vt,E)},[E]);const ge=f.useRef(h),jt=f.useRef(b);jt.current=b;const Vt=f.useCallback((x,v)=>{var z;if(fe.current!==null&&(window.clearTimeout(fe.current),fe.current=null),Zt(x.id),Se.current===x.id&&(Se.current=null),Oe.current=null,w(null),G(x.events.slice(-8)),nt(),B(N=>{if(N.some(Q=>Q.kind==="run"&&Q.run.id===x.id))return N.map(Q=>Q.kind==="run"&&Q.run.id===x.id?{...Q,id:x.id,run:x}:Q);const P=N.some(Q=>Q.kind==="user"&&Q.text===v.question);return[...N,...P?[]:[{kind:"user",id:`${x.id}-question`,text:v.question}],{kind:"run",id:x.id,run:x}]}),x.route!=="certified_answer"){const N=Mt(x);N&&((z=He.current)==null||z.call(He,N,x))}},[nt]),_n=f.useCallback((x,v)=>{var N;B(P=>kr(P,x,v)),mt(P=>{if(!P||P.runId!==x)return P;const Q=v.artifacts[0];return Q?{runId:v.id,artifactId:Q.id,tab:P.tab}:null}),we(null);const z=Mt(v);z&&((N=He.current)==null||N.call(He,z,v))},[]),rt=f.useCallback(x=>{fe.current!==null&&window.clearTimeout(fe.current);const v=++Le.current;Se.current=x.id,Oe.current=x,w(x),A(!0),nt(),G([]);const z=async()=>{if(!(v!==Le.current||Se.current!==x.id))try{const N=await re.getAgentRunState(x.id);if(v!==Le.current||Se.current!==x.id)return;if(N.lifecycleState==="terminal"){Vt(N.run,x),A(!1);return}G(N.progress.events.slice(-8)),fe.current=window.setTimeout(()=>{z()},600)}catch{if(v!==Le.current||Se.current!==x.id)return;fe.current=window.setTimeout(()=>{z()},1200)}};return z(),()=>{v===Le.current&&(Le.current+=1),fe.current!==null&&(window.clearTimeout(fe.current),fe.current=null)}},[Vt]),zn=f.useRef(!1);f.useEffect(()=>{if(!h||zn.current)return;zn.current=!0,ge.current??(ge.current=h);let x=!1;return re.getAgentThread(h).then(({turns:v,runs:z})=>{x||v.length===0||B(N=>{const P=N.filter(le=>le.kind==="run").length,Q=Ir(v,z);if(v.length>=P)return Q;const de=new Map(Q.flatMap(le=>le.kind==="run"?[[le.run.id,le.run]]:[]));return N.map(le=>le.kind==="run"&&de.has(le.run.id)?{...le,run:de.get(le.run.id)}:le)})}).catch(()=>{!x&&ge.current===h&&(ge.current=void 0)}),()=>{x=!0}},[h]),f.useEffect(()=>{const x=Jn(h??ge.current);if(!(!x||Ke.current))return rt(x)},[rt,h]),f.useEffect(()=>{const x=()=>{if(document.visibilityState!=="visible"||Ke.current)return;const v=Oe.current??Jn(h??ge.current);v&&rt(v)};return document.addEventListener("visibilitychange",x),()=>document.removeEventListener("visibilitychange",x)},[rt,h]);const Ee=async(x,v,z,N,P)=>{var Mn,Bn,$n;const Q=(x??X).trim();if(!Q||H)return;const de=v??Y.current??g,le=de==="research"&&$e;pe(!1),Y.current=void 0;const Ct={kind:"user",id:sr("user"),text:Q};B(ve=>[...ve,Ct]),ee(""),we(null),A(!0),G([]),nt();const Me=new AbortController;Ke.current=Me;const Qe=sr("run");let be={id:Qe,question:Q,threadId:ge.current,startedAt:new Date().toISOString()};Se.current=Qe,Oe.current=be,w(be),Xn(be);let ke=!1,En=!1;try{if(!ge.current)try{const he=await re.createAgentThread({surface:_?"ask":typeof(p==null?void 0:p.surface)=="string"?p.surface:d?"notebook":"agent",title:Q,...d?{notebookPath:d}:{}});ge.current=he.id,(Mn=jt.current)==null||Mn.call(jt,he.id),be={...be,threadId:he.id},Oe.current=be,w(be),Xn(be)}catch{}const ve=de==="modeling"||de==="skill"?(Bn=[...E].reverse().find(he=>he.kind==="run"&&he.run.artifacts.some(Gt=>Gt.kind===(de==="modeling"?"modeling_change_proposal":"skill_change_proposal"))))==null?void 0:Bn.run:void 0,Ln=ve==null?void 0:ve.artifacts.find(he=>he.kind===(de==="modeling"?"modeling_change_proposal":"skill_change_proposal")),oi={question:Q,...z?{selectedEvidenceId:z}:{},...N?{clarificationSourceQuestion:N}:{},requestedMode:de,audience:m,selectedObject:c??(d?{kind:"notebook",path:d}:void 0),...P!=null&&P.executionTarget?{executionTarget:P.executionTarget}:ti?{executionTarget:{target:"local"}}:ze?{executionTarget:{target:"connection",connectionName:ze}}:{},workspaceContext:{...p??{},...d?{notebookPath:d}:{},...P?{researchSource:Nr(P)}:{},...ve&&Ln?{sourceRunId:ve.id,sourceArtifactId:Ln.id,revision:((($n=ve.derivation)==null?void 0:$n.revision)??1)+1}:{}},conversationContext:rs(E),history:ri,thinkingMode:me,researchResultRowsOptIn:le,runId:Qe,...ge.current?{threadId:ge.current}:{}},ai=await re.createAgentRunStream(oi,he=>{ke=!0,he.kind==="event"?G(Gt=>[...Gt,he.event].slice(-8)):he.kind==="answer-delta"?ei(he.delta):G(he.run.events.slice(-8))},Me.signal);Vt(ai,be)}catch(ve){Me.signal.aborted||(we(ve instanceof Error?ve.message:String(ve)),ee(Q),ke?(En=!0,rt(be)):(Zt(Qe),Se.current===Qe&&(Se.current=null),Oe.current=null,w(null)))}finally{Ke.current===Me&&(Ke.current=null),En||A(!1)}},wt=()=>{Ee()},Tn=()=>{var v;const x=Se.current;x&&re.cancelAgentRun(x).catch(()=>{}),(v=Ke.current)==null||v.abort(),Le.current+=1,fe.current!==null&&window.clearTimeout(fe.current),Zt(x??""),Se.current=null,Oe.current=null,w(null),nt(),G([]),A(!1),we("Stopped. No answer or draft was saved.")},St=f.useRef(O);St.current=O,f.useEffect(()=>{var x;(x=St.current)==null||x.call(St,H)},[H]),f.useEffect(()=>{!(C!=null&&C.text)||H||Cn.current!==C.nonce&&(Cn.current=C.nonce,Ee(C.text,C.mode??g))},[C==null?void 0:C.nonce,C==null?void 0:C.text,C==null?void 0:C.mode,g,H]),f.useEffect(()=>()=>{Le.current+=1,fe.current!==null&&window.clearTimeout(fe.current)},[]);const kt={appId:typeof(p==null?void 0:p.appId)=="string"?p.appId:void 0,dashboardId:typeof(p==null?void 0:p.dashboardId)=="string"?p.dashboardId:void 0,dashboardTitle:typeof(p==null?void 0:p.dashboardTitle)=="string"?p.dashboardTitle:void 0},At=(x,v)=>{var z,N;if(v.id==="review-modeling-proposal"||v.id==="review-skill-proposal"){const P=v.id==="review-modeling-proposal"?"modeling_change_proposal":"skill_change_proposal",Q=x.artifacts.find(de=>de.kind===P);if(!Q){we("This authoring run does not include a reviewable proposal.");return}if(L)L(Q,x);else if(Q.ref){try{window.sessionStorage.setItem("dql-context-proposal-handoff",Q.ref)}catch{}window.dispatchEvent(new CustomEvent("dql:open-context-proposal",{detail:{proposalId:Q.ref,kind:Q.kind}}))}return}if(v.id==="save-dql-block"){const P=_e(x),Q=((z=P==null?void 0:P.source)==null?void 0:z.trim())??((N=Re(x))==null?void 0:N.trim());if(!Q){we("This answer does not include a reusable DQL or SQL artifact yet.");return}K({runId:x.id,source:Q,name:(P==null?void 0:P.name)??`${x.question.slice(0,48).trim()||"saved_answer"}`,dqlArtifact:P});return}if(v.id==="research-deeper"){Ee(x.question,"research",void 0,void 0,x);return}if(v.id.startsWith("suggest-question")){Ee(v.label,"auto");return}Y.current=Os(v.route),ee(Hs(x,v.route)),requestAnimationFrame(()=>{var P;return(P=tt.current)==null?void 0:P.focus()})},ii=f.useCallback((x,v,z="trust")=>{mt({runId:x,artifactId:v,tab:z})},[]),si=f.useCallback(x=>{var N,P;const v=x.trim();if(!v)return;const z=(N=Te==null?void 0:Te.text)==null?void 0:N.trim();Ye(null),Qt("");try{(P=window.getSelection())==null||P.removeAllRanges()}catch{}Ee(z?`${v}
55
+
56
+ Regarding: "${z}"`:v),requestAnimationFrame(()=>{bt.current&&(bt.current.scrollTop=bt.current.scrollHeight)})},[Te,Ee]);if(f.useEffect(()=>{if(!_)return;const x=z=>{const N=z.target;N&&N.closest("[data-selpop]")||window.setTimeout(()=>{const P=window.getSelection(),Q=P&&P.rangeCount?P.toString().trim():"";if(!Q||Q.length<3){Ye(ke=>ke&&null);return}const de=P.anchorNode,le=de&&(de.nodeType===1?de:de.parentElement),Ct=le==null?void 0:le.closest("[data-followup]");if(!Ct){Ye(ke=>ke&&null);return}const Me=P.getRangeAt(0).getBoundingClientRect(),Qe=Math.max(12,Math.min(Me.left,window.innerWidth-340)),be=Me.bottom+176>window.innerHeight?Math.max(12,Me.top-176):Me.bottom+8;Ye({text:Q.slice(0,220),source:Ct.getAttribute("data-followup")||"answer",left:Qe,top:be}),Qt(""),requestAnimationFrame(()=>{var ke;return(ke=In.current)==null?void 0:ke.focus()})},0)},v=z=>{z.key==="Escape"&&Ye(null)};return document.addEventListener("mouseup",x),document.addEventListener("keydown",v),()=>{document.removeEventListener("mouseup",x),document.removeEventListener("keydown",v)}},[_]),_){const x=Ne?(()=>{const v=E.find(N=>N.kind==="run"&&N.run.id===Ne.runId);if(!v||v.kind!=="run")return null;const z=v.run.artifacts.find(N=>N.id===Ne.artifactId);return z?{run:v.run,artifact:z}:null})():null;return t.jsxs("div",{style:{display:"flex",height:"100%",minHeight:0,flex:1,minWidth:0,width:"100%",background:"var(--bg-canvas)"},children:[S?t.jsx(Hn,{cell:{id:`agent-${S.runId}`,type:S.dqlArtifact?"dql":"sql",content:S.source,name:S.name,status:"success",...S.dqlArtifact?{dqlArtifact:S.dqlArtifact}:{}},initialContent:S.source,initialName:S.name,onClose:()=>K(null),onSaved:()=>K(null)}):null,t.jsx("style",{children:Is}),t.jsxs("div",{style:{flex:1,minWidth:360,display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg-canvas)"},children:[t.jsxs("div",{style:{height:46,flexShrink:0,borderBottom:"1px solid var(--border-subtle)",display:"flex",alignItems:"center",gap:9,padding:"0 24px"},children:[t.jsx("div",{style:{width:24,height:24,borderRadius:7,background:"var(--accent-dim)",border:"1px solid var(--status-info-border)",color:"var(--accent)",display:"inline-flex",alignItems:"center",justifyContent:"center"},children:t.jsx(Ge,{size:13})}),t.jsx("span",{style:{fontSize:13.5,fontWeight:650,color:j.textPrimary,whiteSpace:"nowrap"},children:n==="AI Copilot"?"Ask your data":n}),t.jsx("div",{style:{flex:1}}),t.jsx("span",{style:{fontSize:11,color:j.textMuted,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:"Certified first · semantic next · generated SQL last"})]}),t.jsxs("div",{ref:bt,style:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden",display:"flex",flexDirection:"column"},children:[t.jsxs("div",{style:{width:"min(720px, 100% - 48px)",margin:"0 auto",padding:"26px 0 12px",display:"flex",flexDirection:"column",gap:26},children:[E.length===0&&!H?t.jsxs("div",{style:{margin:"auto 0",display:"grid",gap:14,justifyItems:"center",textAlign:"center",color:j.textSecondary,paddingTop:40},children:[t.jsx("div",{style:or(j),children:t.jsx(Ge,{size:20})}),t.jsx("div",{style:{fontSize:13.5,lineHeight:1.5,maxWidth:400,color:j.textSecondary},children:l??Kn}),t.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap",justifyContent:"center",maxWidth:520},children:(o??Yn).map(v=>t.jsx("button",{type:"button",className:"dql-hover dql-lift",onClick:()=>{ee(v.prompt),requestAnimationFrame(()=>{var z;return(z=tt.current)==null?void 0:z.focus()})},style:Bt(j),children:v.label},v.label))})]}):null,E.map(v=>v.kind==="user"?t.jsx("div",{style:_s(j),children:v.text},v.id):t.jsx(ir,{run:v.run,t:j,themeMode:e,threadId:ge.current,appContext:kt,selectedArtifactId:(Ne==null?void 0:Ne.runId)===v.run.id?Ne.artifactId:void 0,onOpenArtifact:(z,N)=>ii(v.run.id,z,N),onOpenApp:W,onInsertSql:F,onInsertDql:$,onOpenBlock:V,onOpenResearch:M,onSelectClarification:z=>{const N=It(z,v.run.question);Ee(N.question,void 0,N.selectedEvidenceId,v.run.question)},onNextAction:z=>At(v.run,z),onRepairedRun:_n},v.id)),H&&t.jsx(tr,{events:te,t:j,streamingAnswer:xe,thinkingMode:me,backgroundRun:U})]}),t.jsxs("div",{style:{width:"min(720px, 100% - 48px)",margin:"auto auto 0",padding:"10px 0 16px",position:"sticky",bottom:0,background:"linear-gradient(to top, var(--bg-canvas) 82%, transparent)"},children:[ne?t.jsx("div",{style:{color:j.error,fontSize:12,marginBottom:8},children:ne}):null,s?t.jsxs("div",{style:{width:"fit-content",maxWidth:"100%",marginBottom:7,padding:"4px 7px 4px 9px",border:"1px solid var(--border-default)",borderRadius:999,background:"var(--bg-2)",color:j.textMuted,fontSize:10.5,display:"flex",alignItems:"center",gap:5},children:[t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r}),t.jsx("button",{type:"button",onClick:s,"aria-label":"Clear modeling scope",title:"Clear modeling scope",style:{border:0,background:"transparent",color:j.textMuted,cursor:"pointer",display:"grid",placeItems:"center",padding:1},children:t.jsx(zt,{size:12})})]}):null,t.jsxs("div",{style:{background:"var(--bg-2)",border:"1px solid var(--border-default)",borderRadius:14,boxShadow:"0 1px 2px rgba(26,26,26,0.03), 0 6px 22px rgba(26,26,26,0.05)",display:"flex",flexDirection:"column"},children:[t.jsx("textarea",{ref:tt,value:X,onChange:v=>{ee(v.target.value),Y.current=void 0},rows:2,placeholder:i,onKeyDown:v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),wt())},style:{border:"none",background:"transparent",resize:"none",outline:"none",boxShadow:"none",padding:"13px 15px 4px",fontSize:13.5,lineHeight:1.5,color:j.textPrimary,fontFamily:j.font}}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 10px 10px 12px"},children:[t.jsx(Nn,{t:j,value:me,onChange:kn}),t.jsx(Zn,{checked:$e,onChange:pe,t:j}),t.jsx(er,{names:q,value:ze,onChange:Rn,t:j}),t.jsx("div",{style:{flex:1}}),H?t.jsxs("button",{type:"button",className:"dql-hover",onClick:Tn,title:"Stop the active agent run",style:{height:34,padding:"0 12px",borderRadius:10,border:`1px solid ${j.error}`,background:j.btnBg,color:j.error,display:"inline-flex",alignItems:"center",gap:6,cursor:"pointer",fontFamily:j.font,fontSize:12.5,fontWeight:600},children:[t.jsx(Dn,{size:13,fill:"currentColor"})," Stop"]}):null,t.jsx("button",{type:"button",className:"dql-hover dql-lift",title:"Ask",onClick:wt,disabled:!X.trim()||H,style:{width:34,height:34,borderRadius:10,border:"none",background:X.trim()&&!H?"var(--accent)":"var(--bg-4)",color:"#fff",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:X.trim()&&!H?"pointer":"default",boxShadow:X.trim()&&!H?"0 1px 5px rgba(107,93,211,0.3)":"none"},children:H?t.jsx(Ve,{size:15,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}}):t.jsx(hr,{size:15})})]})]}),t.jsx("div",{style:{textAlign:"center",fontSize:10.5,color:j.textMuted,marginTop:8},children:"Every answer is grounded in your certified metrics and dbt lineage."})]})]})]}),x?t.jsx(Bs,{run:x.run,artifact:x.artifact,tab:Ne.tab,t:j,appContext:kt,onOpenApp:W,onChangeTab:v=>mt(z=>z&&{...z,tab:v}),onClose:()=>mt(null),onSaveBlock:()=>At(x.run,{id:"save-dql-block",label:"Save as block",route:"dql_block_draft"}),onInsertSql:F,onInsertDql:$}):null,Te?t.jsx($s,{t:j,text:Te.text,source:Te.source,left:Te.left,top:Te.top,draft:ni,inputRef:In,onDraftChange:Qt,onClose:()=>Ye(null),onSend:si}):null]})}return t.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,flex:1,minWidth:0,width:"100%",background:j.cellBg},children:[S?t.jsx(Hn,{cell:{id:`agent-${S.runId}`,type:S.dqlArtifact?"dql":"sql",content:S.source,name:S.name,status:"success",...S.dqlArtifact?{dqlArtifact:S.dqlArtifact}:{}},initialContent:S.source,initialName:S.name,onClose:()=>K(null),onSaved:()=>K(null)}):null,t.jsx("style",{children:`
57
+ @keyframes dql-agent-run-spin { to { transform: rotate(360deg); } }
58
+ @keyframes dql-agent-fadein { from { opacity: 0; transform: translateY(3px); } to { opacity: 1; transform: none; } }
59
+ @keyframes dql-agent-thinking-dot { 0%, 65%, 100% { opacity: .28; transform: translateY(0); } 32% { opacity: 1; transform: translateY(-2px); } }
60
+ @keyframes dql-agent-activity-in { from { opacity: 0; transform: translateY(2px); } to { opacity: 1; transform: none; } }
61
+ .dql-agent-thinking-dot { animation: dql-agent-thinking-dot 1.05s ease-in-out infinite; }
62
+ .dql-agent-activity { animation: dql-agent-activity-in .22s ease-out; }
63
+ .dql-hover { transition: filter .15s ease, transform .12s ease, box-shadow .15s ease, background .15s ease, color .15s ease, border-color .15s ease; }
64
+ .dql-hover:hover { filter: brightness(1.07); }
65
+ .dql-hover:active { transform: translateY(0.5px); }
66
+ .dql-lift:hover { transform: translateY(-1px); }
67
+ details > summary::-webkit-details-marker { display: none; }
68
+ @media (prefers-reduced-motion: reduce) { .dql-agent-thinking-dot, .dql-agent-activity { animation: none !important; } }
69
+ `}),t.jsxs("div",{style:{flex:1,minHeight:0,overflow:"auto",padding:"14px 16px",display:"flex",flexDirection:"column",gap:12},children:[E.length===0&&!H?t.jsxs("div",{style:{margin:"auto 0",display:"grid",gap:14,justifyItems:"center",textAlign:"center",color:j.textSecondary},children:[t.jsx("div",{style:or(j),children:t.jsx(Ge,{size:20})}),t.jsx("div",{style:{fontSize:13,lineHeight:1.5,maxWidth:380,color:j.textSecondary},children:l??Kn}),t.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap",justifyContent:"center",maxWidth:520},children:(o??Yn).map(x=>t.jsx("button",{type:"button",className:"dql-hover dql-lift",onClick:()=>{ee(x.prompt),requestAnimationFrame(()=>{var v;return(v=tt.current)==null?void 0:v.focus()})},style:Bt(j),children:x.label},x.label))})]}):null,E.map(x=>x.kind==="user"?t.jsx("div",{style:no(j),children:x.text},x.id):se?t.jsx(ir,{run:x.run,t:j,themeMode:e,threadId:ge.current,appContext:kt,onOpenApp:W,onInsertSql:F,onInsertDql:$,onReplaceDql:D,insertDqlActionLabel:k,replaceDqlActionLabel:Z,onOpenBlock:V,onOpenResearch:M,onSelectClarification:v=>{const z=It(v,x.run.question);Ee(z.question,void 0,z.selectedEvidenceId,x.run.question)},onNextAction:v=>At(x.run,v),onRepairedRun:_n},x.id):t.jsx(Rs,{run:x.run,t:j,themeMode:e,appContext:kt,onOpenApp:W,onInsertSql:F,onInsertDql:$,onOpenBlock:V,onOpenResearch:M,onSelectClarification:v=>{const z=It(v,x.run.question);Ee(z.question,void 0,z.selectedEvidenceId,x.run.question)},onNextAction:v=>At(x.run,v)},x.id)),H&&t.jsx(tr,{events:te,t:j,streamingAnswer:xe,thinkingMode:me,backgroundRun:U})]}),ne?t.jsx("div",{style:{margin:"0 16px 8px",color:j.error,fontSize:12},children:ne}):null,t.jsxs("div",{style:{padding:"10px 16px 14px",borderTop:`1px solid ${j.headerBorder}`,display:"grid",gap:8},children:[t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",justifyContent:"space-between",flexWrap:"wrap"},children:[t.jsxs("div",{style:{fontSize:11,color:j.textMuted,flex:1,minWidth:180,display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{children:r}),s?t.jsx("button",{type:"button",onClick:s,"aria-label":"Clear modeling scope",title:"Clear modeling scope",style:{border:0,background:"transparent",color:j.textMuted,cursor:"pointer",display:"grid",placeItems:"center",padding:2},children:t.jsx(zt,{size:12})}):null]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx(er,{names:q,value:ze,onChange:Rn,t:j}),t.jsx(Nn,{t:j,value:me,onChange:kn}),t.jsx(Zn,{checked:$e,onChange:pe,t:j})]})]}),t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-end"},children:[t.jsx("textarea",{ref:tt,value:X,onChange:x=>{ee(x.target.value),Y.current=void 0},rows:2,placeholder:i,onKeyDown:x=>{x.key==="Enter"&&!x.shiftKey&&(x.preventDefault(),wt())},style:Zs(j)}),t.jsxs("button",{type:"button",className:"dql-hover dql-lift",onClick:wt,disabled:!X.trim()||H,style:ar(j,!!X.trim()&&!H),children:[H?t.jsx(Ve,{size:15,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}}):t.jsx(Ni,{size:15}),t.jsx("span",{children:H?"Working":"Ask"})]}),H?t.jsxs("button",{type:"button",className:"dql-hover",onClick:Tn,style:{...ar(j,!0),background:j.btnBg,borderColor:j.error,color:j.error},title:"Stop the active agent run",children:[t.jsx(Dn,{size:13,fill:"currentColor"}),t.jsx("span",{children:"Stop"})]}):null]})]})]})}const Kn="Ask a question — every answer is grounded in your certified metrics and dbt lineage. Use Research deeper on any answer for a slower investigation.",Yn=[{label:"What is total revenue?",prompt:"What is total revenue?"},{label:"Why is revenue down by region?",prompt:"Why is revenue down by region?"},{label:"Top customers by revenue this quarter",prompt:"Top customers by revenue this quarter"},{label:"How have orders trended over the last 6 months?",prompt:"How have orders trended over the last 6 months?"}];function mn(){try{const e=JSON.parse(window.localStorage.getItem(yn)??"[]");return Array.isArray(e)?e.filter(n=>{if(!n||typeof n!="object")return!1;const r=n;return typeof r.id=="string"&&typeof r.question=="string"&&typeof r.startedAt=="string"&&(r.threadId===void 0||typeof r.threadId=="string")}):[]}catch{return[]}}function Xn(e){try{const n=mn().filter(r=>r.id!==e.id);window.localStorage.setItem(yn,JSON.stringify([...n,e].slice(-12)))}catch{}}function Zt(e){try{const n=mn().filter(r=>r.id!==e);window.localStorage.setItem(yn,JSON.stringify(n))}catch{}}function Jn(e){const n=mn().sort((r,i)=>i.startedAt.localeCompare(r.startedAt));return e?n.find(r=>r.threadId===e):n.find(r=>!r.threadId)}const qr="dql.agent.thinkingMode";function Rr(e,n,r){return r&&e.includes(r)?r:n&&e.includes(n)?n:e[0]}function Zn({checked:e,onChange:n,t:r}){return t.jsxs("label",{title:"One-run consent: Research may send at most 20 redacted narration rows and 200 redacted local-analysis rows. Ask and repair always send zero rows.",style:{minHeight:30,display:"inline-flex",alignItems:"center",gap:5,padding:"0 7px",border:"1px solid var(--border-default)",borderRadius:8,background:"var(--bg-2)",color:r.textMuted,fontSize:10.5,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox","aria-label":"Allow redacted result rows for this Research run",checked:e,onChange:i=>n(i.target.checked)}),"Research rows (this run)"]})}function er({names:e,value:n,onChange:r,t:i}){return e.length===0||!n?null:t.jsxs("label",{title:"Database connection used for metadata, compilation, and execution in this conversation",style:{height:30,display:"inline-flex",alignItems:"center",gap:5,padding:"0 7px",border:"1px solid var(--border-default)",borderRadius:8,background:"var(--bg-2)",color:i.textMuted,fontSize:11},children:[t.jsx(hi,{size:12}),t.jsx("select",{"aria-label":"Ask AI database connection",value:n,onChange:s=>r(s.target.value),style:{maxWidth:150,border:0,outline:0,background:"transparent",color:i.textSecondary,font:"inherit",cursor:e.length>1?"pointer":"default"},children:e.map(s=>t.jsx("option",{value:s,children:s},s))})]})}function vs(){try{const e=window.localStorage.getItem(qr);return e==="low"||e==="medium"||e==="high"||e==="auto"?e:"auto"}catch{return"auto"}}const js=new Set(["conversation","certified_answer","semantic_answer","generated_answer","research","sql_cell","dql_block_draft","modeling_draft","skill_draft","app_build","clarify","blocked"]),ws=new Set(["certified","governed","grounded","review_required","blocked","not_applicable"]),Ss=new Set(["completed","needs_review","needs_clarification","blocked"]),ks=new Set(["conversational_reply","certified_answer_found","governed_semantic_answer","generated_review_required","artifact_created","needs_clarification","human_review_required","blocked"]);function Ir(e,n=[]){const r=new Map(n.map(o=>[o.id,o])),i=new Set(e.flatMap(o=>o.agentRunId?[o.agentRunId]:[])),s=new Set(n.flatMap(o=>{const l=o.derivation;return(l==null?void 0:l.kind)==="analytical_repair"&&i.has(o.id)&&typeof l.sourceRunId=="string"?[l.sourceRunId]:[]}));return e.filter(o=>!o.agentRunId||!s.has(o.agentRunId)).flatMap(o=>{const l=o.agentRunId?r.get(o.agentRunId):void 0;return[{kind:"user",id:`${o.id}-q`,text:o.question},{kind:"run",id:(l==null?void 0:l.id)??o.id,run:l??As(o)}]})}function As(e){var p,g,a;const n=js.has(e.route)?e.route:"generated_answer",r=ws.has(e.trustLabel)?e.trustLabel:e.certification==="certified"?"certified":"not_applicable",i=Ss.has(e.runStatus)?e.runStatus:"completed",s=ks.has(e.stopReason)?e.stopReason:i==="blocked"?"blocked":i==="needs_clarification"?"needs_clarification":i==="needs_review"?"human_review_required":n==="conversation"?"conversational_reply":r==="certified"?"certified_answer_found":"artifact_created",o=(((p=e.result)==null?void 0:p.columns)??[]).filter(u=>typeof u=="string"),l=(((g=e.result)==null?void 0:g.rowsSample)??[]).filter(u=>Array.isArray(u)).map(u=>Object.fromEntries(o.map((y,h)=>[y,u[h]]))),d=o.length>0?{columns:o,rows:l,rowCount:((a=e.result)==null?void 0:a.rowCount)??l.length}:void 0,c=d||e.sql||e.dqlArtifact||e.sourceCertifiedBlock?{id:`${e.id}-artifact`,kind:"answer",title:e.sourceCertifiedBlock??e.question,trustState:r,ref:e.sourceCertifiedBlock,payload:{...e.sourceCertifiedBlock?{sourceCertifiedBlock:e.sourceCertifiedBlock}:{},...e.certification?{certification:e.certification}:{},...e.contextPackId?{contextPackId:e.contextPackId}:{},...e.sql?{sql:e.sql}:{},...e.dqlArtifact?{dqlArtifact:e.dqlArtifact}:{},...e.cascade?{cascade:e.cascade}:{},...d?{result:d}:{},...e.contract&&Object.keys(e.contract).length>0?{contextPack:{questionPlan:{requestedShape:e.contract}}}:{}}}:void 0;return{id:e.id,question:e.question,requestedMode:"auto",route:n,status:i,trustState:r,stopReason:s,startedAt:e.createdAt,completedAt:e.createdAt,summary:e.answerSummary??e.question,answer:e.answerText??e.answerSummary,answerKind:n==="conversation"?"conversational":void 0,steps:[],artifacts:c?[c]:[],evaluations:[],events:[],nextActions:[],repairAttempts:0}}function Cs(e){switch(e){case"certified_answer":return"Found a compatible certified block";case"semantic_answer":return"Found a compatible semantic metric";case"generated_answer":return"Identified the relevant tables and columns";case"research":return"Identified evidence for deeper analysis";case"app_build":return"Found governed assets for the app";case"sql_cell":return"Identified the query context";case"dql_block_draft":return"Identified reusable governed logic";case"modeling_draft":return"Resolved current models and relationship evidence";case"skill_draft":return"Resolved current domain guidance and governed references";case"clarify":return"Identified a missing business detail";default:return"Identified the best answer path"}}function qs(e,n){if(n.some(r=>r.type==="repair.attempted"))return"Refining the query and trying again";if(n.some(r=>r.type==="escalated"))return"Expanding the evidence search";switch(e){case"certified_answer":case"semantic_answer":return"Running the governed query";case"generated_answer":return"Building and running a grounded query";case"research":return"Researching the strongest evidence";case"app_build":return"Assembling the app from governed assets";case"sql_cell":return"Building and checking the SQL";case"dql_block_draft":return"Drafting the governed logic";case"modeling_draft":return"Building a reviewable modeling proposal";case"skill_draft":return"Building a reviewable Skill proposal";case"clarify":return"Preparing a focused clarification";default:return"Preparing the answer"}}function ln(e){for(let n=e.length-1;n>=0;n-=1)if(e[n].route)return e[n].route}function _r(e,n,r=!1){return e<12?null:!n&&e<24&&!r?{title:"Still resolving the governed evidence",detail:"The bounded request is still selecting its answer path. DQL will stop at the normal deadline instead of silently switching to a longer workflow."}:n==="research"?{title:"Deep research is validating the analysis",detail:"This can use several AI and SQL steps. Reusable relationships and semantic metrics make future investigations faster; reviewed repeat answers can be saved as blocks and certified."}:{title:r?"Applying one bounded query repair":"Finishing the bounded query path",detail:"DQL is compiling or running the selected governed path. An ordinary lookup stops at its deadline instead of silently restarting as Research."}}function zr(e,n,r,i){return r==="certified"||e<20&&i===0||n!=="research"&&n!=="generated_answer"?null:{title:n==="research"?"Make future research faster":"Make this question faster next time",detail:"If this analysis is reusable, save it as a block, review it, then certify it. Add repeated joins to Domain Modeling and reusable measures to the semantic layer to reduce future AI work and token usage."}}function Tr(e,n=!1){if(e.length===0&&n)return[{id:"background",label:"Continuing this request in the background",state:"active"}];const r=ln(e);if(r==="conversation")return[];const i=e.some(d=>d.type==="route.decided"),s=e.some(d=>d.type==="executor.started"||d.type==="step.started"||d.type==="repair.attempted"||d.type==="escalated"),o=e.some(d=>d.type==="evaluation.recorded"),l=[{id:"search",label:"Resolving governed evidence and business meaning",state:i?"complete":"active"}];return i&&l.push({id:"match",label:Cs(r),state:s||o?"complete":"active"}),(s||o)&&l.push({id:"execute",label:qs(r,e),state:o?"complete":"active"}),o&&l.push({id:"verify",label:"Checking the result against governed evidence",state:"active"}),l}function tr({events:e,t:n,streamingAnswer:r,thinkingMode:i,backgroundRun:s}){var h;const[o,l]=f.useState(()=>Date.now());f.useEffect(()=>{const b=window.setInterval(()=>l(Date.now()),1e3);return()=>window.clearInterval(b)},[]);const d=(s==null?void 0:s.startedAt)??((h=e.find(b=>b.type==="run.started"))==null?void 0:h.at),c=d?Date.parse(d):o,p=Number.isFinite(c)?Math.max(0,Math.floor((o-c)/1e3)):0,g=_r(p,ln(e),e.some(b=>b.type==="repair.attempted"));if(r)return t.jsx("div",{style:{alignSelf:"stretch",padding:"4px 2px 8px",fontSize:13.5,lineHeight:1.55,color:n.textPrimary,whiteSpace:"pre-wrap",animation:"dql-agent-fadein 0.22s ease-out"},children:r});if(ln(e)==="conversation")return t.jsxs("div",{role:"status","aria-live":"polite",style:{alignSelf:"stretch",display:"flex",alignItems:"center",gap:9,padding:"5px 2px 9px",color:n.textSecondary,animation:"dql-agent-fadein 0.22s ease-out"},children:[t.jsx(nr,{}),t.jsx("span",{style:{fontSize:13,lineHeight:1.4},children:"Replying…"})]});const u=Tr(e,!!s),y=p>=12?g==null?void 0:g.title:i==="high"?"Thorough mode is cross-checking the result.":null;return t.jsxs("div",{role:"status","aria-live":"polite","aria-label":"Agent activity",style:{alignSelf:"stretch",display:"grid",gap:7,padding:"5px 2px 10px",animation:"dql-agent-fadein 0.22s ease-out"},children:[u.map(b=>t.jsxs("div",{className:"dql-agent-activity",style:{display:"flex",alignItems:"center",gap:9,minHeight:18,color:b.state==="active"?n.textPrimary:n.textMuted},children:[t.jsx("span",{"aria-hidden":"true",style:{width:16,height:16,display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"0 0 auto",color:b.state==="active"?n.accent:n.textMuted},children:b.state==="active"?t.jsx(nr,{}):t.jsx(dt,{size:13,strokeWidth:2.2})}),t.jsxs("span",{style:{fontSize:12.5,lineHeight:1.4,fontWeight:b.state==="active"?620:450},children:[b.label,b.state==="active"?"…":""]})]},b.id)),y?t.jsx("span",{style:{paddingLeft:25,fontSize:10.5,lineHeight:1.4,color:n.textMuted},children:y}):null]})}function nr(){return t.jsx("span",{"aria-hidden":"true",style:{width:16,height:10,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:2},children:[0,1,2].map(e=>t.jsx("span",{className:"dql-agent-thinking-dot",style:{width:3,height:3,borderRadius:999,background:"var(--accent)",animationDelay:`${e*120}ms`}},e))})}function rr({items:e,t:n,renderItem:r,cap:i=4}){const[s,o]=f.useState(!1),l=s?e:e.slice(0,i);return t.jsxs(t.Fragment,{children:[l.map((d,c)=>r(d,c)),e.length>i?t.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>o(d=>!d),style:{alignSelf:"flex-start",background:"none",border:"none",cursor:"pointer",color:n.accent,fontSize:11,padding:"2px 0",display:"inline-flex",alignItems:"center",gap:4},children:[s?t.jsx(yr,{size:11}):t.jsx(Lt,{size:11}),s?"Show less":`Show all (${e.length})`]}):null]})}function Rs({run:e,t:n,themeMode:r,appContext:i,onOpenApp:s,onInsertSql:o,onInsertDql:l,onOpenBlock:d,onOpenResearch:c,onSelectClarification:p,onNextAction:g}){var se;const{dispatch:a}=Dt();if(e.route==="conversation"){const k=e.answerKind==="general_knowledge";return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8,animation:"dql-agent-fadein 0.3s ease-out"},children:[t.jsxs("div",{style:ro(n),children:[k?t.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:10.5,color:n.textMuted,marginBottom:6,fontWeight:650},children:[t.jsx(Tt,{size:11})," General knowledge — not from your data"]}):null,t.jsx("div",{style:{fontSize:13.5,lineHeight:1.55,color:n.textPrimary},children:e.answer?t.jsx(_t,{text:Je(e.answer),t:n}):e.summary})]}),e.nextActions.length>0?t.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:e.nextActions.map(Z=>t.jsx("button",{type:"button",className:"dql-hover dql-lift",onClick:()=>g(Z),style:Bt(n),children:Z.label},Z.id))}):null]})}const u=e.steps??[],y=u.length>1,h=((se=e.plan)==null?void 0:se.source)==="llm",b=Sn(e),m=jn(e),C=ht(e),F=e.route==="certified_answer"||e.route==="generated_answer",$=e.nextActions.some(k=>k.route==="research"),D=F&&C&&!$,R=_e(e),L=C&&!(R!=null&&R.sourcePath)&&!!((R==null?void 0:R.source)??Re(e)),V=Date.parse(e.startedAt),M=Date.parse(e.completedAt),W=Number.isFinite(V)&&Number.isFinite(M)?Math.max(0,Math.round((M-V)/1e3)):0,O=zr(W,e.route,e.trustState,e.repairAttempts);return t.jsxs("div",{style:io(n),children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx(Ps,{run:e}),t.jsx("div",{style:{minWidth:0,flex:1},children:t.jsx("div",{style:{fontSize:12.5,fontWeight:850,color:n.textPrimary},children:Ls(e)})}),t.jsx(Fs,{run:e,t:n})]}),m?t.jsxs("div",{style:{display:"flex",gap:6,alignItems:"flex-start",fontSize:11,color:n.textMuted,lineHeight:1.4},children:[e.trustState==="certified"?t.jsx(ye,{size:12,color:n.success,style:{flex:"0 0 auto",marginTop:1}}):e.trustState==="governed"||e.trustState==="grounded"?t.jsx(ye,{size:12,color:n.accent,style:{flex:"0 0 auto",marginTop:1}}):t.jsx(Ze,{size:12,color:n.warning,style:{flex:"0 0 auto",marginTop:1}}),t.jsx("span",{children:m})]}):null,h||y||e.repairAttempts>0?t.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[h?t.jsx(tn,{t:n,icon:t.jsx(pt,{size:11}),label:"AI plan",tone:"accent"}):null,y?t.jsx(tn,{t:n,icon:t.jsx(sn,{size:11}),label:`${u.length} steps`,tone:"muted"}):null,e.repairAttempts>0?t.jsx(tn,{t:n,icon:t.jsx(Pt,{size:11}),label:`${e.repairAttempts} repair${e.repairAttempts>1?"s":""}`,tone:"warning"}):null]}):null,e.summary&&!(e.answer&&Qs(qe(e.summary),Je(e.answer)))?t.jsx("div",{style:{fontSize:12.5,lineHeight:1.45,color:n.textSecondary},children:qe(e.summary)}):null,e.answer?t.jsx("div",{style:so(n),children:t.jsx(_t,{text:Je(e.answer),t:n})}):null,t.jsx(Br,{run:e,t:n,onSelect:p}),b.length>0?t.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",alignItems:"center"},children:[t.jsx("span",{style:{fontSize:11,color:n.textMuted},children:"Evidence:"}),b.map(k=>t.jsxs("span",{style:Kr(n,k.certified),children:[k.certified?t.jsx(ye,{size:11}):t.jsx(ut,{size:11}),t.jsx("span",{children:k.label})]},k.label))]}):null,t.jsx(Ur,{run:e,t:n}),e.artifacts.length>0?t.jsx("div",{style:{display:"grid",gap:8,gridTemplateColumns:"minmax(0, 1fr)",minWidth:0},children:e.artifacts.map(k=>t.jsx(Or,{artifact:k,t:n,themeMode:r,onInsertSql:o,onInsertDql:l,sourceRunId:e.id,sourceQuestion:e.question,onOpenBlock:d,onOpenResearch:c,onOpenApp:s,onNextAction:g},k.id))}):null,y?t.jsx(Qr,{steps:u,t:n}):t.jsx(Hr,{evaluations:e.evaluations,t:n}),e.events.length>0?t.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>a({type:"OPEN_AGENT_LOG",run:e}),style:{display:"inline-flex",alignItems:"center",gap:5,alignSelf:"flex-start",background:"transparent",border:"none",cursor:"pointer",padding:0,color:n.textMuted,fontSize:11.5,fontFamily:n.font},title:"See what the agent did and where the time went",children:[t.jsx(pt,{size:12})," View steps · where the time went"]}):null,O?t.jsxs("div",{style:{display:"grid",gap:3,padding:"8px 9px",border:`1px solid ${n.accent}33`,borderRadius:7,background:`${n.accent}0a`},children:[t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,color:n.textSecondary,fontSize:11,fontWeight:800},children:[t.jsx(Tt,{size:11,color:n.accent})," ",O.title]}),t.jsx("span",{style:{fontSize:10.5,color:n.textMuted,lineHeight:1.45},children:O.detail})]}):null,C||D||e.nextActions.length>0?t.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",alignItems:"center"},children:[C?t.jsx(vn,{run:e,t:n,appContext:i,onOpenApp:s}):null,L?t.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>g({id:"save-dql-block",label:"Save as block",route:"dql_block_draft"}),style:J(n),children:[t.jsx(xn,{size:11})," Save as block"]}):null,D?t.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>g({id:"research-deeper",label:"Research this deeper",route:"research"}),style:J(n),title:"Run a slower, multi-step investigation on this question",children:[t.jsx(ut,{size:11}),"Research this deeper"]}):null,e.nextActions.filter(k=>k.id!=="pin-to-app"&&k.id!=="research-deeper"&&k.id!=="confirm-app-build"&&k.id!=="request-certification").map(k=>t.jsx("button",{type:"button",className:"dql-hover",onClick:()=>g(k),style:J(n),children:k.label},k.id))]}):null]})}function Er(e){const n=[];return e.analytical&&n.push({id:"how",label:"How it answered"}),(e.hasDql||e.analytical&&e.blocked)&&n.push({id:"dql",label:"DQL"}),(e.hasSql||e.analytical&&e.blocked)&&n.push({id:"sql",label:"SQL"}),e.hasLineage&&n.push({id:"lineage",label:"Lineage"}),n.push({id:"trust",label:"Trust & steps"}),n}const Is=`
70
+ @keyframes dql-agent-run-spin { to { transform: rotate(360deg); } }
71
+ @keyframes dql-agent-fadein { from { opacity: 0; transform: translateY(3px); } to { opacity: 1; transform: none; } }
72
+ @keyframes dql-agent-thinking-dot { 0%, 65%, 100% { opacity: .28; transform: translateY(0); } 32% { opacity: 1; transform: translateY(-2px); } }
73
+ @keyframes dql-agent-activity-in { from { opacity: 0; transform: translateY(2px); } to { opacity: 1; transform: none; } }
74
+ .dql-agent-thinking-dot { animation: dql-agent-thinking-dot 1.05s ease-in-out infinite; }
75
+ .dql-agent-activity { animation: dql-agent-activity-in .22s ease-out; }
76
+ .dql-hover { transition: filter .15s ease, transform .12s ease, box-shadow .15s ease, background .15s ease, color .15s ease, border-color .15s ease; }
77
+ .dql-hover:hover { filter: brightness(1.03); }
78
+ .dql-hover:active { transform: translateY(0.5px); }
79
+ .dql-lift:hover { transform: translateY(-1px); }
80
+ .dql-ask-ghost:hover { background: var(--bg-0); color: var(--text-primary) !important; }
81
+ .dql-ask-chip:hover { border-color: var(--accent) !important; box-shadow: 0 1px 6px rgba(107,93,211,0.12); }
82
+ details > summary::-webkit-details-marker { display: none; }
83
+ @media (prefers-reduced-motion: reduce) { .dql-agent-thinking-dot, .dql-agent-activity { animation: none !important; } }
84
+ `;function _s(e){return{alignSelf:"flex-end",maxWidth:"82%",background:"var(--bg-0)",color:e.textPrimary,borderRadius:"16px 16px 4px 16px",padding:"10px 14px",fontSize:13.5,lineHeight:1.5,whiteSpace:"pre-wrap",animation:"dql-agent-fadein 0.25s ease-out"}}function Pe(e){return Nt(e,{variant:"ghost",size:"sm"})}function en(e,n){return e.kind==="app_proposal"||e.kind==="dql_block_draft"||e.kind==="research_run"||!!Ot(n)}function Ft(e,n){var l,d;const r=[],i=Be(n),s=e.kind==="answer"?(l=i==null?void 0:i.rows)!=null&&l.length?"Table":"Answer":e.kind==="sql_cell"?"SQL":e.kind==="dql_block_draft"?"DQL block":e.kind==="research_run"?"Research":"Result";r.push(s);const o=(i==null?void 0:i.rowCount)??((d=i==null?void 0:i.rows)==null?void 0:d.length);return typeof o=="number"&&r.push(`${o} row${o===1?"":"s"}`),typeof(i==null?void 0:i.executionTime)=="number"&&r.push(i.executionTime>=1e3?`${(i.executionTime/1e3).toFixed(1)}s`:`${i.executionTime.toFixed(i.executionTime<10?1:0)}ms`),r.push(e.trustState==="certified"?"certified block":e.trustState==="governed"||e.trustState==="grounded"?"governed":"AI-generated"),r.join(" · ")}function at(e,n){const i=/^(?:certified|governed semantic|review-required|exploratory dbt-grounded) answer$/i.test(n.title.trim())?e.question:n.title,s=qe(i).replace(/[?.!]+$/,"").trim();if(!s)return"Answer result";const o=s.charAt(0).toUpperCase()+s.slice(1);return o.length>88?`${o.slice(0,85).trimEnd()}…`:o}function T(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Mr(e){const n=[],r=new Set,i=(s,o)=>{const l=T(s);if(!l)return;const d=[l.name,l.label,l.relation,l.objectName].find(a=>typeof a=="string"&&a.trim().length>0);if(!d)return;const c=typeof l.kind=="string"?l.kind:o,p=`${c??""}:${d}`;if(r.has(p))return;r.add(p);const g=[l.description,l.provenance,l.sourceTier,l.source].find(a=>typeof a=="string"&&a.trim().length>0);n.push({name:d,kind:c,detail:g})};for(const s of e.artifacts){const o=ie(s),l=T(o.evidence);for(const p of["lineage","sourceTables","semanticObjects","selectedAssets"]){const g=l==null?void 0:l[p];Array.isArray(g)&&g.forEach(a=>i(a,p==="sourceTables"?"source":void 0))}const d=T(o.analysisPlan)??T(l==null?void 0:l.analysisPlan),c=d==null?void 0:d.candidateTables;Array.isArray(c)&&c.forEach(p=>i(p,"relation"))}return n.slice(0,24)}function bn(e,n){var i;const r=ie(n);return Wt(r)?"how":(i=_e(e)??xt(r))!=null&&i.source?"dql":Re(e)??(typeof r.sql=="string"?r.sql:void 0)?"sql":Mr(e).length>0?"lineage":"trust"}function zs({run:e,artifact:n,selected:r,t:i,themeMode:s,onInspect:o}){const l=ie(n),d=Be(l),[c,p]=f.useState(!1);if(f.useEffect(()=>{if(!c)return;const b=m=>{m.key==="Escape"&&p(!1)};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[c]),!d)return null;const g=Vr(l,d),a=bn(e,n),u=_e(e)??xt(l),y=n.trustState==="certified"?Wr(n,l):void 0,h=t.jsxs("section",{"data-followup":"table","aria-label":`${at(e,n)} result`,style:{border:`1px solid ${r?"var(--accent)":"var(--border-default)"}`,borderRadius:12,background:"var(--bg-2)",overflow:"hidden",boxShadow:c?"0 24px 80px rgba(15,23,42,0.28)":r?"0 2px 10px rgba(107,93,211,0.12)":"0 1px 3px rgba(26,26,26,0.04)",...c?{width:"min(1440px, calc(100vw - 48px))",maxHeight:"calc(100vh - 48px)"}:{}},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"11px 13px",borderBottom:"1px solid var(--border-subtle)"},children:[t.jsx("span",{style:{width:30,height:30,borderRadius:8,background:n.trustState==="certified"?"var(--status-success-bg)":"var(--accent-dim)",color:n.trustState==="certified"?"var(--status-success)":"var(--accent)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t.jsx(et,{kind:n.kind})}),t.jsxs("div",{style:{minWidth:0,flex:1},children:[t.jsx("div",{style:{fontSize:12.5,fontWeight:700,color:i.textPrimary,lineHeight:1.35},children:at(e,n)}),t.jsx("div",{style:{fontSize:11,color:i.textMuted,marginTop:2},children:Ft(n,l)})]}),t.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:()=>o(a),style:Pe(i),children:[t.jsx(pt,{size:12})," Inspect"]}),t.jsxs("button",{type:"button",className:"dql-ask-ghost","aria-label":c?"Return result to Copilot":"Expand result",title:c?"Return result to Copilot":"Expand this result for wide tables",onClick:()=>p(b=>!b),style:Pe(i),children:[c?t.jsx(qi,{size:12}):t.jsx(vi,{size:12}),c?"Restore":"Expand result"]})]}),u?t.jsx(Fr,{artifact:u,certifiedBlockName:y,initialResult:d,initialChartConfig:g,payload:l,executionTarget:e.executionTarget,t:i,themeMode:s,embedded:!0,expanded:c}):t.jsx(gn,{result:d,themeMode:s,t:i,chartConfig:g,embedded:!0,tabLabels:{table:"Results",chart:"Visualization"},contentMaxHeight:c?"calc(100vh - 172px)":void 0,tableMaxHeight:c?"calc(100vh - 250px)":void 0})]});return!c||typeof document>"u"?h:t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{minHeight:96,border:"1px dashed var(--border-default)",borderRadius:12,display:"grid",placeItems:"center",color:i.textMuted,fontSize:11.5},children:"Result is open in the expanded viewer."}),xi.createPortal(t.jsx("div",{role:"dialog","aria-modal":"true","aria-label":`${at(e,n)} expanded result`,onClick:()=>p(!1),style:{position:"fixed",inset:0,zIndex:120,display:"grid",placeItems:"center",padding:24,background:"rgba(15,23,42,0.48)",backdropFilter:"blur(3px)"},children:t.jsx("div",{onClick:b=>b.stopPropagation(),style:{minWidth:0,maxWidth:"100%"},children:h})}),document.body)]})}function ir(e){const{run:n,t:r,themeMode:i,threadId:s,appContext:o,selectedArtifactId:l,onOpenArtifact:d,onOpenApp:c,onInsertSql:p,onInsertDql:g,onReplaceDql:a,insertDqlActionLabel:u,replaceDqlActionLabel:y,onOpenBlock:h,onOpenResearch:b,onSelectClarification:m,onNextAction:C,onRepairedRun:F}=e,{dispatch:$}=Dt(),[D,R]=f.useState(!1),L=d??(()=>$({type:"OPEN_AGENT_LOG",run:n}));if(n.route==="conversation"){const S=n.answerKind==="general_knowledge";return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8,animation:"dql-agent-fadein 0.3s ease-out",maxWidth:"100%"},children:[S?t.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:10.5,color:r.textMuted,fontWeight:650},children:[t.jsx(Tt,{size:11})," General knowledge — not from your data"]}):null,t.jsx("div",{"data-followup":"answer",style:{fontSize:14.5,lineHeight:1.65,color:r.textPrimary},children:n.answer?t.jsx(_t,{text:Je(n.answer),t:r}):n.summary}),n.nextActions.length>0?t.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:n.nextActions.map(K=>t.jsx("button",{type:"button",className:"dql-hover dql-lift",onClick:()=>C(K),style:Bt(r),children:K.label},K.id))}):null]})}const V=n.trustState==="certified",M=n.status==="blocked",W=n.status==="needs_clarification",O=n.answer,se=M?"Couldn’t run this query":W?"Needs clarification":V?"Certified answer":"AI-generated answer",k=M?Zr(n):void 0,Z=Xr(n),_=n.evaluations.filter(S=>S.severity==="info").length,j=Sn(n),Y=n.artifacts.filter(S=>{const K=ie(S);return!en(S,K)&&!!Be(K)}),X=new Set(Y.map(S=>S.id)),ee=n.artifacts.filter(S=>!en(S,ie(S))&&!X.has(S.id)),E=n.artifacts.filter(S=>en(S,ie(S))),B=Y[0]??ee[0]??n.artifacts[0],te=ht(n),G=n.route==="certified_answer"||n.route==="semantic_answer"||n.route==="generated_answer",xe=n.nextActions.some(S=>S.route==="research"),ue=G&&te&&!xe,H=_e(n),A=te&&!(H!=null&&H.sourcePath)&&!!((H==null?void 0:H.source)??Re(n)),U=u&&g||y&&a?Mt(n):void 0,w=()=>{var K;const S=O?Je(O):k??n.summary;S&&((K=navigator.clipboard)==null||K.writeText(S).catch(()=>{}),R(!0),window.setTimeout(()=>R(!1),1400))};return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10,maxWidth:"100%",animation:"dql-agent-fadein 0.3s ease-out"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,flexWrap:"wrap"},children:[M?t.jsx(Ze,{size:14,color:r.error}):V?t.jsx(ye,{size:14,color:r.success}):t.jsx(Ge,{size:14,color:r.accent}),t.jsx("span",{style:{fontSize:12,fontWeight:650,color:M?r.error:r.textSecondary},children:se}),V&&j[0]?t.jsxs("span",{style:{fontSize:11,color:r.textMuted},children:["from ",t.jsx("span",{style:{color:r.accent,fontWeight:600},children:j[0].label})]}):!M&&B&&_>0?t.jsxs("button",{type:"button",onClick:()=>L(B.id,"trust"),style:{fontSize:11,color:r.textMuted,background:"none",border:"none",cursor:"pointer",padding:0,fontFamily:r.font,display:"inline-flex",alignItems:"center",gap:4},children:[t.jsx(dt,{size:11,color:r.success})," ",_," check",_===1?"":"s"," passed"]}):null]}),O?t.jsx("div",{"data-followup":"answer",style:{fontSize:14.5,lineHeight:1.65,color:r.textPrimary},children:t.jsx(_t,{text:Je(O),t:r})}):k?t.jsx(oo,{run:n,detail:k,threadId:s,onRepaired:S=>F(n.id,S),t:r}):n.summary?t.jsx("div",{"data-followup":"answer",style:{fontSize:14,lineHeight:1.6,color:r.textSecondary},children:qe(n.summary)}):null,Z?t.jsxs("div",{role:"status",style:{fontSize:11.5,lineHeight:1.5,color:r.warning,borderLeft:`2px solid ${r.warning}`,paddingLeft:8},children:["Capture warning: ",qe(Z)," The query result is still valid."]}):null,t.jsx(Br,{run:n,t:r,onSelect:m}),Y.map(S=>t.jsx(zs,{run:n,artifact:S,selected:S.id===l,t:r,themeMode:i,onInspect:K=>L(S.id,K)},S.id)),ee.map(S=>{const K=ie(S),ne=S.id===l;return t.jsxs("button",{type:"button",className:"dql-ask-chip",onClick:()=>L(S.id,bn(n,S)),style:{display:"flex",alignItems:"center",gap:10,width:"fit-content",maxWidth:"100%",padding:"9px 12px",borderRadius:10,border:`1px solid ${ne?"var(--accent)":"var(--border-default)"}`,background:"var(--bg-2)",boxShadow:ne?"0 1px 6px rgba(107,93,211,0.12)":"none",cursor:"pointer",textAlign:"left",fontFamily:r.font},children:[t.jsx("span",{style:{width:30,height:30,borderRadius:7,background:S.trustState==="certified"?"var(--status-success-bg)":"var(--accent-dim)",color:S.trustState==="certified"?"var(--status-success)":"var(--accent)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t.jsx(et,{kind:S.kind})}),t.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:1,minWidth:0},children:[t.jsx("span",{style:{fontSize:12.5,fontWeight:650,color:r.textPrimary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:qe(S.title)}),t.jsx("span",{style:{fontSize:11,color:r.textMuted},children:Ft(S,K)})]}),t.jsx(fr,{size:14,color:r.textMuted,style:{flexShrink:0,marginLeft:6}})]},S.id)}),E.length>0?t.jsx("div",{style:{display:"grid",gap:8,gridTemplateColumns:"minmax(0, 1fr)",minWidth:0},children:E.map(S=>t.jsx(Or,{artifact:S,t:r,themeMode:i,onInsertSql:p,onInsertDql:g,insertDqlActionLabel:u,sourceRunId:n.id,sourceQuestion:n.question,onOpenBlock:h,onOpenResearch:b,onOpenApp:c,onNextAction:C},S.id))}):null,O||k||U||te||A||ue||B?t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexWrap:"wrap",marginTop:-2},children:[U&&g?t.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:()=>g(U),style:Pe(r),children:[t.jsx(ot,{size:12})," ",u]}):null,U&&a&&y?t.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:()=>a(U),style:Pe(r),children:[t.jsx(mi,{size:12})," ",y]}):null,O||k?t.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:w,style:Pe(r),children:[D?t.jsx(dt,{size:12}):t.jsx(mr,{size:12})," ",D?"Copied":"Copy"]}):null,te?t.jsx(vn,{run:n,t:r,appContext:o,onOpenApp:c}):null,A?t.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:()=>C({id:"save-dql-block",label:"Save as block",route:"dql_block_draft"}),style:Pe(r),children:[t.jsx(gt,{size:12})," Save as block"]}):null,ue?t.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:()=>C({id:"research-deeper",label:"Research this deeper",route:"research"}),style:Pe(r),children:[t.jsx(ut,{size:12})," Research deeper"]}):null,B?t.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:()=>L(B.id,Wt(ie(B))?"how":"trust"),style:Pe(r),children:[t.jsx(pt,{size:12})," How it was answered"]}):null]}):null]})}function Br({run:e,t:n,onSelect:r}){var i;return e.status!=="needs_clarification"||!((i=e.clarificationOptions)!=null&&i.length)||!r?null:t.jsx("div",{"aria-label":"Choose a governed meaning",style:{display:"grid",gap:7,maxWidth:620},children:e.clarificationOptions.map(s=>t.jsxs("button",{type:"button",className:"dql-hover dql-lift",onClick:()=>r(s),title:`Use governed evidence ${s.id}`,style:{display:"grid",gap:3,width:"100%",padding:"10px 12px",borderRadius:10,border:"1px solid var(--border-default)",background:"var(--bg-2)",color:n.textPrimary,cursor:"pointer",textAlign:"left",fontFamily:n.font},children:[t.jsx("span",{style:{fontSize:12.5,fontWeight:700},children:s.label}),s.description?t.jsx("span",{style:{fontSize:11,lineHeight:1.4,color:n.textMuted},children:s.description}):null]},s.id))})}function $r(e){const n=e.executionError;if(typeof n=="string"&&n.trim())return{stage:"execution",message:n};const r=T(n);if(r)return{stage:"execution",...r};const i=typeof e.refusalCode=="string"?e.refusalCode:void 0;if(i){const s=T(e.refusalDetails),o=typeof(s==null?void 0:s.message)=="string"&&s.message.trim()?s.message:typeof e.answer=="string"&&e.answer.trim()?e.answer:"No answer was accepted for this question.";return{stage:"answer",code:i,message:o}}}function Wt(e){return!!(T(e.resolvedAnalyticalPlan)||T(e.analyticalExecutionGraph)||T(e.analyticalExecutionReceipt)||T(e.analyticalFailure)||T(e.semanticExecutionTrace)||T(e.diagnosticReceipt)||$r(e))}function Lr(e){if(!Wt(e))return;const n=T(e.diagnosticReceipt),r=T(e.resolvedAnalyticalPlan)??T(n==null?void 0:n.resolvedAnalyticalPlan);return{plan:r,frame:T(r==null?void 0:r.analyticalFrame),graph:T(e.analyticalExecutionGraph),receipt:T(e.analyticalExecutionReceipt),facts:T(e.analyticalFacts),narrative:T(e.analyticalNarrative),freshness:T(e.analyticalFreshnessObservation),failure:T(e.analyticalFailure)??T(n==null?void 0:n.failure)??$r(e),semantic:T(e.semanticExecutionTrace),diagnostic:n}}function Ts(){return["Performance & provider egress","Plan","DQL","Compiled SQL","Lineage","Trust & evidence","Actual steps","Failure & repair"]}function Es(e){return[e.includes("retry_same_plan")?"Retry same plan":void 0,e.includes("refresh_snapshot")?"Refresh snapshot and prepare retry":void 0,e.includes("request_access")||e.includes("change_authorized_connection")?"Change connection or request access":void 0,e.includes("edit_dql")?"Open DQL to repair":void 0,e.includes("open_sql_notebook")?"Open SQL in Notebook":void 0,e.includes("reapply_semantic_runtime")?"Reapply semantic runtime settings":void 0].filter(n=>!!n)}function Dr(e){const n=e.telemetry;if(!n)return;const r=(e.providerEgressReceipts??[]).reduce((c,p)=>c+p.resultRowCount,0),i=n.stageDurationsMs.total,s=n.warehouseDurationMs,o=i===void 0||s===void 0?void 0:Math.max(0,i-s),l=Array.from(new Set((e.artifacts??[]).flatMap(c=>{var u;const p=ie(c),g=T(p.resolvedAnalyticalPlan)??T((u=T(p.diagnosticReceipt))==null?void 0:u.resolvedAnalyticalPlan),a=T(p.analyticalExecutionReceipt);return[g==null?void 0:g.planId,a==null?void 0:a.planId].filter(y=>typeof y=="string"&&y.length>0)}))),d=Array.from(new Set((e.artifacts??[]).map(c=>c.id).filter(c=>typeof c=="string"&&c.length>0)));return[["Total",Rt(n.stageDurationsMs.total)],["Warehouse",n.warehouseDurationMs===void 0?"Not recorded":Rt(n.warehouseDurationMs)],["Orchestration",o===void 0?"Not recorded":Rt(o)],["Stages",Object.entries(n.stageDurationsMs).filter(([c])=>c!=="total").map(([c,p])=>`${c}: ${Rt(p)}`).join(" · ")],["Calls",`${n.providerRoundTrips} provider · ${n.toolCalls} tool · ${n.sqlExecutions} SQL · ${n.repairs} repair`],["Provider rows",r===0?`0 result rows sent to providers (${n.egressReceipts} content-free receipt${n.egressReceipts===1?"":"s"})`:`${r} bounded, redacted Research result row${r===1?"":"s"} sent with explicit run consent`],["Plan ID",l.length>0?l.join(", "):"Not recorded"],["Artifact IDs",d.length>0?d.join(", "):"None"],["Fallback",n.fallbackReason??"None"]]}function Ms({run:e,contract:n,dqlArtifact:r,sql:i,lineage:s,t:o,onInsertSql:l,onInsertDql:d,onSaveBlock:c}){var We,$e,pe;const{dispatch:p}=Dt(),g=n.plan,a=n.frame,u=n.graph,y=n.receipt,h=n.semantic,b=T(h==null?void 0:h.failure),m=n.failure??b,C=T(h==null?void 0:h.authoringRequest),F=T(h==null?void 0:h.runtimeRequest),$=je(h==null?void 0:h.bindings),D=je(h==null?void 0:h.steps),R=T(h==null?void 0:h.targetBinding),L=T(R==null?void 0:R.semanticSnapshot),V=T(R==null?void 0:R.executionTarget),M=T(V==null?void 0:V.redactedContext),W=T(R==null?void 0:R.compileTarget),O=T(h==null?void 0:h.executionReceipt),se=je(b==null?void 0:b.candidates),k=T(a==null?void 0:a.timeContext),Z=T(a==null?void 0:a.comparison),_=T(a==null?void 0:a.ranking),j=je(a==null?void 0:a.dimensions),Y=je(a==null?void 0:a.memberBindings),X=je(k==null?void 0:k.periods),ee=je(a==null?void 0:a.requestedOutputs),E=je(u==null?void 0:u.nodes),B=Array.from(new Set([...Ae(m==null?void 0:m.safeActions),...Ae(b==null?void 0:b.safeActions)])),te=je(m==null?void 0:m.failedBindings),G=T(b==null?void 0:b.sqlExcerpt),xe=e.artifacts.map(q=>Be(ie(q))).find(Boolean),ue=Dr(e),H=(r==null?void 0:r.name)??e.question,[A,U]=f.useState(null),w=(q,ae)=>{const ze=ae.derivation.trustTransition;return`${q} as immutable derivation ${ae.derivation.derivationId}. Trust: ${ze.previous} → ${ze.next}${ze.requiresReview?" (review required)":""}.`},S=async()=>{if(!(!(r!=null&&r.source)||!d))try{const q=await re.deriveAnalyticalRepair(e.id,{version:1,action:"edit_dql",dqlSource:r.source});d({sql:i,dqlArtifact:r,result:xe,title:H,sourceRunId:e.id,question:e.question}),U(w("Opened DQL in Notebook",q))}catch(q){U(q instanceof Error?q.message:String(q))}},K=async()=>{if(!(!i||!l))try{const q=await re.deriveAnalyticalRepair(e.id,{version:1,action:"open_sql_notebook",sqlText:i});l(i,`${H} repair`,{question:e.question,sourceRunId:e.id}),U(w("Opened SQL in Notebook",q))}catch(q){U(q instanceof Error?q.message:String(q))}},ne=async q=>{try{const ae=await re.deriveAnalyticalRepair(e.id,{version:1,action:q});U(w(q==="retry_same_plan"?"Prepared the same bounded plan for retry":"Refreshed the governed snapshot and prepared the same plan for retry",ae))}catch(ae){U(ae instanceof Error?ae.message:String(ae))}},we=async()=>{try{const q=await re.deriveAnalyticalRepair(e.id,{version:1,action:"request_access"});U(w("Recorded the access/connection repair and opened Database settings",q)),p({type:"SET_SETTINGS_TAB",tab:"database"}),p({type:"SET_MAIN_VIEW",view:"settings"})}catch(q){U(q instanceof Error?q.message:String(q))}},me=()=>{p({type:"SET_SETTINGS_TAB",tab:"project"}),p({type:"SET_MAIN_VIEW",view:"settings"}),U("Opened Project & dbt settings. Test and apply the intended dbt Cloud Semantic Layer environment to refresh its verified metric inventory.")};return t.jsxs("div",{style:{display:"grid",gap:9},"aria-label":"How it answered",children:[t.jsxs("div",{role:"status",style:{display:"flex",gap:8,alignItems:"flex-start",padding:"10px 12px",borderRadius:8,border:`1px solid ${m?"var(--status-error-border)":"var(--status-success-border)"}`,background:m?"var(--status-error-bg)":"var(--status-success-bg)"},children:[m?t.jsx(Ze,{size:13,color:"var(--status-error)",style:{flexShrink:0,marginTop:2}}):t.jsx(ye,{size:13,color:"var(--status-success)",style:{flexShrink:0,marginTop:2}}),t.jsxs("div",{style:{fontSize:12,color:o.textSecondary,lineHeight:1.5,minWidth:0},children:[t.jsx("div",{style:{fontWeight:700,color:m?"var(--status-error)":"var(--status-success)"},children:m?"Execution failed":"Answered successfully"}),m?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{marginTop:3,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:o.fontMono,fontSize:11},children:typeof m.message=="string"&&m.message.trim()?m.message:"The engine did not report a message. Open the DQL and SQL tabs to inspect what ran."}),t.jsx("div",{style:{marginTop:4,fontSize:10.5,color:o.textMuted},children:[m.code,m.phase?`during ${m.phase}`:""].filter(Boolean).map(I).join(" · ")})]}):t.jsx("div",{style:{marginTop:2},children:typeof(y==null?void 0:y.rowCount)=="number"?`Returned ${y.rowCount} row${y.rowCount===1?"":"s"}.`:"The query ran and returned a result."})]})]}),t.jsx(it,{index:1,label:"Performance & provider egress",t:o,open:!0,children:ue?t.jsx(qt,{rows:ue,t:o}):t.jsx(lt,{t:o,children:"Performance details were not recorded for this legacy run."})}),t.jsx(it,{index:2,label:"Plan",t:o,open:!m,children:t.jsx(qt,{rows:[["Question type",I((a==null?void 0:a.questionType)??(g==null?void 0:g.questionType))],["Selected route",I((u==null?void 0:u.route)??(g==null?void 0:g.recommendedRoute))],["Metric",Ae(a==null?void 0:a.metricConceptIds).join(", ")],["Entity grain",Ae(a==null?void 0:a.entityGrainIds).join(", ")],["Dimensions",j.map(q=>`${I(q.dimensionId)} (${I(q.role)})`).join(", ")],["Member filters",Y.map(q=>`${I(q.dimensionId)}: ${Array.isArray(q.canonicalValues)?q.canonicalValues.length:0} bound value(s)`).join(", ")],["Time policy",[k==null?void 0:k.timeRole,k==null?void 0:k.grain,k==null?void 0:k.timezone,k==null?void 0:k.completenessPolicy].map(I).filter(Boolean).join(" · ")],["Periods",X.map(q=>`${I(q.id)}: ${I(q.start)} → ${I(q.end)}`).join(`
85
+ `)],["Comparison",Z?`${I(Z.basePeriodId)} vs ${Ae(Z.comparisonPeriodIds).join(", ")} · ${I(Z.alignment)}`:a?"Not requested":"Not available — analytical planning did not complete"],["Ranking",_?`${I(_.direction)} · top ${I(_.limit)} · ${I(_.tiePolicy)}`:a?"Not requested":"Not available — analytical planning did not complete"],["Outputs",ee.map(q=>`${I(q.id)} (${I(q.kind)})`).join(", ")],["Semantic metrics",Ae(C==null?void 0:C.metrics).join(", ")],["Semantic dimensions",Ae(C==null?void 0:C.dimensions).join(", ")]],t:o})}),t.jsx(it,{index:3,label:"Trust & evidence",t:o,children:t.jsx(qt,{rows:[["Trust state",e.trustState],["Snapshot",I((g==null?void 0:g.snapshotId)??(u==null?void 0:u.snapshotId))],["Plan fingerprint",I((g==null?void 0:g.fingerprint)??(u==null?void 0:u.planFingerprint))],["Graph fingerprint",I(u==null?void 0:u.fingerprint)],["Receipt",I(y==null?void 0:y.receiptId)],["Result fingerprint",I(y==null?void 0:y.resultFingerprint)],["Freshness observed through",I((We=n.freshness)==null?void 0:We.observedThrough)],["Fact set",I(($e=n.facts)==null?void 0:$e.fingerprint)],["Semantic adapter",I(h==null?void 0:h.adapter)],["Semantic compile status",I(h==null?void 0:h.status)],["Target proof",I((pe=T(R==null?void 0:R.proof))==null?void 0:pe.status)],["Target binding",I(R==null?void 0:R.bindingFingerprint)],["Compile target",I(W==null?void 0:W.kind)],["Local semantic snapshot",I((L==null?void 0:L.semanticCatalogFingerprint)??(L==null?void 0:L.sourceFingerprint))],["Runtime metric inventory proof",I(W==null?void 0:W.semanticCatalogFingerprint)],["Execution target",[V==null?void 0:V.driver,M==null?void 0:M.account,M==null?void 0:M.database,M==null?void 0:M.schema,M==null?void 0:M.role,M==null?void 0:M.warehouse].map(I).filter(Boolean).join(" · ")],["Semantic receipt",I(O==null?void 0:O.receiptId)],["Warehouse query ID",I(O==null?void 0:O.queryId)],["Executed SQL proof",I(O==null?void 0:O.executedSqlFingerprint)],["Runtime metrics",Ae(F==null?void 0:F.metrics).join(", ")],["Runtime dimensions",Ae(F==null?void 0:F.dimensions).join(", ")],["Member bindings",$.map(q=>`${I(q.authoringReference)} → ${I(q.runtimeReference)}${Ae(q.entityPath).length?` via ${Ae(q.entityPath).join(" → ")}`:""} (${I(q.status)})`).join(`
86
+ `)]],t:o,mono:!0})}),t.jsx(it,{index:4,label:"Actual steps",t:o,children:t.jsxs("div",{style:{display:"grid",gap:6},children:[D.map((q,ae)=>t.jsxs("div",{style:{fontSize:11.5,color:o.textSecondary},children:[t.jsxs("strong",{style:{color:I(q.status)==="failed"?"var(--status-error)":o.textPrimary},children:[ae+1,". ",I(q.label)]})," ","— ",I(q.status)," · ",I(q.detail)]},`semantic:${I(q.id)||ae}`)),e.steps.map(q=>t.jsxs("div",{style:{fontSize:11.5,color:o.textSecondary},children:[t.jsxs("strong",{style:{color:o.textPrimary},children:[q.index+1,". ",q.goal]})," — ",q.status,", ",q.attempts," attempt",q.attempts===1?"":"s"]},q.id)),E.map((q,ae)=>t.jsxs("div",{style:{fontSize:11.5,color:o.textSecondary},children:[t.jsxs("span",{style:{color:o.accent,fontFamily:o.fontMono},children:[ae+1,". ",I(q.kind)]})," ","· ",I(q.id)]},I(q.id)||ae)),D.length===0&&e.steps.length===0&&E.length===0?t.jsx(lt,{t:o,children:"No executable steps were recorded."}):null]})}),t.jsx(it,{index:5,label:"Failure & repair",t:o,open:!!m,children:m?t.jsxs("div",{style:{display:"grid",gap:9},children:[t.jsx(qt,{rows:[["Failure ID",I(m.failureId)],["Recoverability",I(m.recoverability)],["Failed bindings",te.map(q=>`${I(q.qualifiedId??q.role)} (${I(q.reasonCode)})`).join(", ")],["Safe actions",B.join(", ")],["DQL fingerprint",I(m.dqlFingerprint)],["SQL fingerprint",I(m.sqlFingerprint)],["Semantic failure code",I(b==null?void 0:b.code)],["Failing identifier",I(b==null?void 0:b.identifier)],["Compiled SQL proof",I(b==null?void 0:b.compiledSqlFingerprint)],["Path candidates",se.map(q=>`${I(q.label)}
87
+ ${I(q.runtimeReference)}`).join(`
88
+ `)]],t:o,mono:!0}),I(G==null?void 0:G.text)?t.jsxs("div",{children:[t.jsxs("div",{style:{fontSize:10.5,fontWeight:700,color:o.textSecondary,marginBottom:5},children:["Failing SQL context · lines ",I(G==null?void 0:G.startLine),"–",I(G==null?void 0:G.endLine)]}),t.jsx("pre",{style:ft(o),children:I(G==null?void 0:G.text)})]}):null,t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6},"aria-label":"Safe repair actions",children:[B.includes("edit_dql")&&d?t.jsxs("button",{type:"button",onClick:()=>void S(),style:J(o),children:[t.jsx(Pt,{size:12})," Open DQL to repair"]}):null,B.includes("open_sql_notebook")&&l?t.jsxs("button",{type:"button",onClick:()=>void K(),style:J(o),children:[t.jsx(hn,{size:12})," Open SQL in Notebook"]}):null,B.includes("retry_same_plan")?t.jsxs("button",{type:"button",onClick:()=>void ne("retry_same_plan"),style:J(o),children:[t.jsx(Ut,{size:12})," Retry same plan"]}):null,B.includes("refresh_snapshot")?t.jsxs("button",{type:"button",onClick:()=>void ne("refresh_snapshot"),style:J(o),children:[t.jsx(Ut,{size:12})," Refresh snapshot and prepare retry"]}):null,B.includes("request_access")||B.includes("change_authorized_connection")?t.jsxs("button",{type:"button",onClick:()=>void we(),style:J(o),children:[t.jsx(Ze,{size:12})," Change connection or request access"]}):null,B.includes("reapply_semantic_runtime")?t.jsxs("button",{type:"button",onClick:me,style:J(o),children:[t.jsx(Ut,{size:12})," Reapply semantic runtime settings"]}):null]})]}):t.jsxs("div",{style:{display:"grid",gap:8},children:[t.jsx(lt,{t:o,children:"No failure was recorded for this run."}),r!=null&&r.sourcePath?null:r!=null&&r.source?t.jsxs("button",{type:"button",onClick:c,style:J(o),children:[t.jsx(xn,{size:12})," Save as draft block"]}):null]})}),A?t.jsx("div",{role:"status",style:{fontSize:10.5,color:A.toLowerCase().includes("created")?"var(--status-success)":"var(--status-error)"},children:A}):null]})}function it({index:e,label:n,t:r,open:i=!1,children:s}){return t.jsxs("details",{open:i,style:{border:"1px solid var(--border-subtle)",borderRadius:8,background:"var(--bg-1)",overflow:"hidden"},children:[t.jsxs("summary",{style:{cursor:"pointer",listStyle:"none",padding:"8px 10px",display:"flex",gap:7,alignItems:"center",fontSize:11.5,fontWeight:700,color:r.textPrimary},children:[t.jsx("span",{style:{width:18,height:18,borderRadius:999,display:"inline-flex",alignItems:"center",justifyContent:"center",background:"var(--accent-dim)",color:"var(--accent)",fontSize:10},children:e}),n]}),t.jsx("div",{style:{display:"grid",gap:8,padding:"0 10px 10px"},children:s})]})}function qt({rows:e,t:n,mono:r=!1}){return t.jsx("div",{style:{display:"grid",gap:6},children:e.filter(([,i])=>i).map(([i,s])=>t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"112px minmax(0, 1fr)",gap:8,alignItems:"start"},children:[t.jsx("span",{style:{fontSize:10.5,color:n.textMuted},children:i}),t.jsx("span",{style:{fontSize:10.5,color:n.textSecondary,fontFamily:r?n.fontMono:n.font,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:s})]},i))})}function lt({t:e,children:n}){return t.jsx("div",{style:{fontSize:11,color:e.textMuted},children:n})}function je(e){return Array.isArray(e)?e.flatMap(n=>T(n)?[T(n)]:[]):[]}function Ae(e){return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}function I(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function Rt(e){return typeof e!="number"||!Number.isFinite(e)||e<0?"Not recorded":e>=1e3?`${(e/1e3).toFixed(e>=1e4?0:1)}s`:`${Math.round(e)}ms`}function It(e,n){var i;const r=n==null?void 0:n.trim();return{question:((i=e.question)==null?void 0:i.trim())||r||e.label,selectedEvidenceId:e.id}}function Nr(e){var i;const n=e.artifacts.map(s=>Be(ie(s))).find(s=>!!s),r=(i=e.artifacts.find(s=>s.ref))==null?void 0:i.ref;return{runId:e.id,question:e.question,trustState:e.trustState,executionTarget:e.executionTarget,sourceCertifiedBlock:r,sql:Re(e),dqlArtifact:_e(e),...n?{result:{columns:n.columns,rows:n.rows.slice(0,24),rowCount:n.rowCount}}:{}}}function ht(e){return!e.artifacts.some(r=>!!Ot(ie(r)))&&e.status!=="blocked"&&e.status!=="needs_clarification"&&(e.artifacts.some(r=>r.kind==="answer"||r.kind==="research_run")||!!(_e(e)??Re(e)))}function Bs({run:e,artifact:n,tab:r,t:i,appContext:s,onOpenApp:o,onChangeTab:l,onClose:d,onSaveBlock:c,onInsertSql:p,onInsertDql:g}){const a=ie(n),u=_e(e)??xt(a),y=Re(e)??(typeof a.sql=="string"?a.sql:void 0),h=Be(a),b=at(e,n),m=Sn(e),C=Mr(e),F=jn(e),$=n.trustState==="certified",D=e.status==="blocked"||n.trustState==="blocked",R=ht(e),L=Lr(a),V=Er({analytical:!!L,blocked:D,hasDql:!!(u!=null&&u.source),hasSql:!!y,hasLineage:C.length>0}),M=V.some(k=>k.id===r)?r:V[0].id,W=D?"Blocked":$?"Certified":n.trustState==="governed"||n.trustState==="grounded"?"Governed":"AI-generated",O=D?"var(--status-error)":$?"var(--status-success)":n.trustState==="governed"||n.trustState==="grounded"?"var(--accent)":"var(--status-warning)",se=D?"var(--status-error-bg)":$?"var(--status-success-bg)":n.trustState==="governed"||n.trustState==="grounded"?"var(--accent-dim)":"var(--status-warning-bg)";return t.jsxs("div",{style:{width:"clamp(300px, 34vw, 440px)",flexShrink:0,background:"var(--bg-2)",borderLeft:"1px solid var(--border-default)",display:"flex",flexDirection:"column",minHeight:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:10,padding:"14px 16px 12px",borderBottom:"1px solid var(--border-subtle)"},children:[t.jsx("span",{style:{width:32,height:32,borderRadius:8,background:se,color:O,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border-subtle)"},children:t.jsx(et,{kind:n.kind})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:13,fontWeight:650,color:i.textPrimary,lineHeight:1.35},children:at(e,n)}),t.jsx("div",{style:{fontSize:11,color:i.textMuted,marginTop:2},children:Ft(n,a)})]}),t.jsx("span",{style:{border:`1px solid ${O}`,color:O,background:se,borderRadius:999,padding:"2px 8px",fontSize:10,fontWeight:700,flexShrink:0,marginTop:2},children:W}),t.jsx("button",{type:"button",onClick:d,title:"Close",className:"dql-ask-ghost",style:{width:24,height:24,borderRadius:6,border:"none",background:"none",color:i.textMuted,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",flexShrink:0},children:t.jsx(zt,{size:14})})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"10px 16px",borderBottom:"1px solid var(--border-subtle)"},children:[R?t.jsx(vn,{run:e,t:i,appContext:s,onOpenApp:o}):null,R?t.jsxs("button",{type:"button",className:"dql-hover",onClick:c,style:{display:"inline-flex",alignItems:"center",gap:6,padding:"7px 13px",borderRadius:8,border:"1px solid var(--border-default)",background:"var(--bg-2)",color:i.textSecondary,fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:i.font},children:[t.jsx(gt,{size:13})," Save as block"]}):null,t.jsx("div",{style:{flex:1}}),t.jsx("button",{type:"button",title:"More",className:"dql-hover",style:{width:28,height:28,borderRadius:7,border:"1px solid var(--border-default)",background:"var(--bg-2)",color:i.textMuted,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},children:t.jsx(bi,{size:14})})]}),t.jsx("div",{style:{display:"flex",alignItems:"center",gap:16,padding:"0 16px",borderBottom:"1px solid var(--border-subtle)",flexShrink:0},children:V.map(k=>t.jsx("button",{type:"button",onClick:()=>l(k.id),style:{padding:"10px 1px",fontSize:12,fontWeight:600,cursor:"pointer",border:"none",background:"none",fontFamily:i.font,whiteSpace:"nowrap",color:M===k.id?i.textPrimary:i.textMuted,boxShadow:M===k.id?`inset 0 -2px 0 0 ${i.accent}`:"none"},children:k.label},k.id))}),t.jsxs("div",{style:{flex:1,minHeight:0,overflow:"auto",padding:"14px 16px 20px"},children:[M==="how"&&L?t.jsx(Ms,{run:e,contract:L,dqlArtifact:u,sql:y,lineage:C,t:i,onInsertSql:p,onInsertDql:g,onSaveBlock:c}):null,M==="dql"?u!=null&&u.source?t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[t.jsx("span",{style:{fontSize:11,color:i.textMuted},children:"Reusable governed artifact — save it as a block to certify."}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[g?t.jsx("button",{type:"button",onClick:()=>g({sql:y,dqlArtifact:u,result:h,chartConfig:h?Fe(a,h):void 0,title:b,sourceRunId:e.id,question:e.question}),style:J(i),children:"Open DQL in notebook"}):null,t.jsx(Et,{text:u.source,t:i,title:"Copy DQL"})]})]}),t.jsx("pre",{style:ft(i),children:u.source})]}):t.jsx(lt,{t:i,children:"The selected plan failed before a DQL source could be materialized. Review the Plan and Failure & repair sections."}):null,M==="sql"?y?t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[t.jsx("span",{style:{fontSize:11,color:i.textMuted},children:"Attempted compiled SQL — open it in Notebook to inspect or repair."}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[p?t.jsx("button",{type:"button",onClick:()=>p(y,b,{question:e.question,sourceRunId:e.id}),style:J(i),children:"Open SQL in notebook"}):null,t.jsx(Et,{text:y,t:i,title:"Copy SQL"})]})]}),t.jsx("pre",{style:ft(i),children:y})]}):t.jsx(lt,{t:i,children:"Compilation stopped before SQL was produced. The DQL, plan, trust evidence, and failure steps are still retained."}):null,M==="lineage"?t.jsxs("div",{style:{display:"grid",gap:8},children:[t.jsx("div",{style:{fontSize:11,color:i.textMuted,lineHeight:1.5},children:"Governed semantic objects and physical sources used to produce this result."}),C.map(k=>t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:9,padding:"9px 10px",border:"1px solid var(--border-subtle)",borderRadius:8,background:"var(--bg-1)"},children:[t.jsx(xr,{size:13,color:i.accent,style:{flexShrink:0,marginTop:2}}),t.jsxs("div",{style:{minWidth:0},children:[t.jsx("div",{style:{fontSize:12,fontWeight:650,color:i.textPrimary},children:k.name}),t.jsx("div",{style:{fontSize:10.5,color:i.textMuted,marginTop:2},children:[k.kind,k.detail].filter(Boolean).join(" · ")})]})]},`${k.kind??"asset"}:${k.name}`))]}):null,M==="trust"?t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[F?t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-start",padding:"10px 12px",borderRadius:8,background:$?"var(--status-success-bg)":"var(--status-warning-bg)",border:`1px solid ${$?"var(--status-success-border)":"var(--status-warning-border)"}`},children:[$?t.jsx(ye,{size:13,color:"var(--status-success)",style:{flexShrink:0,marginTop:1}}):t.jsx(Ze,{size:13,color:"var(--status-warning)",style:{flexShrink:0,marginTop:1}}),t.jsx("span",{style:{fontSize:12,color:i.textSecondary,lineHeight:1.5},children:F})]}):null,m.length>0?t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,fontWeight:700,color:i.textMuted,textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:8},children:"Evidence"}),t.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:m.map(k=>t.jsxs("span",{style:Kr(i,k.certified),children:[k.certified?t.jsx(ye,{size:11}):t.jsx(ut,{size:11}),t.jsx("span",{children:k.label})]},k.label))})]}):null,e.evaluations.length>0?t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,fontWeight:700,color:i.textMuted,textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:8},children:"Verification checks"}),t.jsx(Hr,{evaluations:e.evaluations,t:i})]}):null,e.steps.length>0?t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,fontWeight:700,color:i.textMuted,textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:8},children:"Steps"}),t.jsx(Qr,{steps:e.steps,t:i})]}):null,t.jsx(Ur,{run:e,t:i})]}):null]})]})}function $s({t:e,text:n,source:r,left:i,top:s,draft:o,inputRef:l,onDraftChange:d,onClose:c,onSend:p}){const g=(a,u)=>t.jsx("button",{type:"button",onClick:()=>p(u),style:{border:"1px solid var(--border-subtle)",background:"var(--bg-1)",color:e.textSecondary,borderRadius:999,padding:"3px 10px",fontSize:11,fontWeight:550,cursor:"pointer",fontFamily:e.font},children:a});return t.jsxs("div",{"data-selpop":"true",style:{position:"fixed",left:i,top:s,zIndex:90,width:324,background:"var(--bg-2)",border:"1px solid var(--border-default)",borderRadius:12,boxShadow:"0 10px 32px rgba(26,26,26,0.16)",padding:10,display:"flex",flexDirection:"column",gap:8,animation:"dql-agent-fadein 0.14s ease-out",fontFamily:e.font},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx(Ge,{size:12,color:e.accent}),t.jsx("span",{style:{fontSize:11,fontWeight:700,color:e.textSecondary},children:"Follow up on this"}),t.jsx("span",{style:{fontSize:10,color:e.textMuted},children:r==="table"?"from the result":"from the answer"}),t.jsx("div",{style:{flex:1}}),t.jsx("button",{type:"button",onClick:c,style:{width:20,height:20,borderRadius:5,border:"none",background:"none",color:e.textMuted,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0},children:t.jsx(zt,{size:12})})]}),t.jsxs("div",{style:{borderLeft:`2px solid ${e.accent}`,background:"var(--accent-dim)",borderRadius:"0 6px 6px 0",padding:"5px 9px",fontSize:11.5,color:e.textSecondary,lineHeight:1.45,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:["“",n,"”"]}),t.jsxs("div",{style:{display:"flex",gap:6},children:[t.jsx("input",{ref:l,value:o,onChange:a=>d(a.target.value),onKeyDown:a=>{a.key==="Enter"&&(a.preventDefault(),p(o))},placeholder:"Ask about this…",style:{flex:1,minWidth:0,border:"1px solid var(--border-default)",borderRadius:8,padding:"7px 10px",fontSize:12.5,fontFamily:e.font,color:e.textPrimary,background:"var(--bg-1)",outline:"none"}}),t.jsx("button",{type:"button",onClick:()=>p(o),title:"Send follow-up",style:{width:30,height:30,flexShrink:0,borderRadius:8,border:"none",background:"var(--accent)",color:"#fff",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},children:t.jsx(hr,{size:13})})]}),t.jsxs("div",{style:{display:"flex",gap:5,flexWrap:"wrap"},children:[g("Why is this?","Why is this happening?"),g("Root cause","What is the root cause?"),g("Break it down","Break this down further")]})]})}function st(e){const n=e.replace(/^\/\w+\s+/,"").trim().replace(/[?.!]+$/,"");return(n?n.charAt(0).toUpperCase()+n.slice(1):"New app").slice(0,60)}function dn(e,n){const r=e instanceof Error?e.message.trim():"";return e instanceof yi&&e.status===405||/method not allowed/i.test(r)?"This Notebook server is older than the App Studio shown in your browser. Restart dql notebook, reload this page, and try again. No Project files were published.":r||n}function cn(e,n){return n!=null&&n.trim()?`${e} › ${n.trim()}`:e}function Pr(e,n){const r=n.filter(s=>s.state!=="project_published"),i=new Set(r.flatMap(s=>{var o;return(o=s.baseApp)!=null&&o.appId?[s.baseApp.appId]:[]}));return[...r.map(s=>{var o,l;return{id:`draft:${s.id}`,kind:"draft",appId:s.appId,name:s.name,draft:s,pageId:(o=s.pages[0])==null?void 0:o.id,pageTitle:(l=s.pages[0])==null?void 0:l.metadata.title}}),...e.filter(s=>!i.has(s.id)).map(s=>{var l,d,c;const o=((l=s.homepage)==null?void 0:l.type)==="dashboard"?s.homepage.id:(d=s.dashboards[0])==null?void 0:d.id;return{id:`project:${s.id}`,kind:"project",appId:s.id,name:s.name,pageId:o,pageTitle:(c=s.dashboards.find(p=>p.id===o))==null?void 0:c.title}})]}function vn({run:e,t:n,appContext:r,onOpenApp:i}){const[s,o]=f.useState(!1),[l,d]=f.useState(null),[c,p]=f.useState(!1),[g,a]=f.useState("list"),[u,y]=f.useState(""),[h,b]=f.useState(!1),[m,C]=f.useState(null),[F,$]=f.useState(""),[D,R]=f.useState(null),L=f.useRef(null),V=async()=>{d(null),p(!1);const[_,j]=await Promise.allSettled([re.listAppsStrict(),re.listAppBuilds()]);if(_.status==="rejected"&&j.status==="rejected"){d([]),p(!0);return}const Y=Pr(_.status==="fulfilled"?_.value:[],j.status==="fulfilled"?j.value.drafts:[]);d(Y),Y.length===0&&a("new")},M=()=>{o(!0),C(null),a("list"),L.current=null,y(st(e.question)),$(st(e.question)),V()},W=()=>{h||(o(!1),C(null))},O=async(_,j,Y,X)=>{var G,xe;const ee=F.trim()||st(e.question),E=_e(e),B=nn(e),te=await re.addAskResultToAppBuild(_.id,{expectedRevision:_.revision,expectedProposalHash:_.proposalHash,pageId:Y,title:ee,question:e.question,answer:e.answer??e.summary,certifiedBlockId:B,dqlSource:E==null?void 0:E.source,sql:Re(e),visualization:(G=Gs(e))==null?void 0:G.chart});R({appId:te.draft.appId,draftId:te.draft.id,pageId:te.pageId,name:j,pageTitle:((xe=te.draft.pages.find(ue=>ue.id===te.pageId))==null?void 0:xe.metadata.title)??X,tileTitle:ee,kind:te.deduped?"existing":B?"certified":E!=null&&E.source||Re(e)?"review":"narrative"}),window.dispatchEvent(new CustomEvent("dql-app-build-updated",{detail:{draft:te.draft,pageId:te.pageId,tileId:te.tileId}})),o(!1)},se=async _=>{if(_.draft)return _.draft;const Y=(await re.listAppBuilds()).drafts.find(X=>{var ee;return X.state!=="project_published"&&((ee=X.baseApp)==null?void 0:ee.appId)===_.appId});return Y||(await re.createAppBuild({baseAppId:_.appId,goal:`Edit ${_.name} with an Ask result`,authoringMode:"ai",sourcePolicy:nn(e)?"governed_only":"include_review_required",template:"blank",entrypoint:"ask"})).draft},k=async _=>{if(!h){b(!0),C(null);try{const j=await se(_),Y=(r==null?void 0:r.appId)===_.appId?r.dashboardId:_.pageId;await O(j,_.name,Y,_.pageTitle)}catch(j){C(dn(j,"Could not add to app."))}finally{b(!1)}}},Z=async()=>{var j,Y;if(h)return;const _=u.trim()||st(e.question);b(!0),C(null);try{L.current||(L.current=(await re.createAppBuild({name:_,goal:e.question,authoringMode:"ai",sourcePolicy:nn(e)?"governed_only":"include_review_required",template:"blank",entrypoint:"ask"})).draft),await O(L.current,_,(j=L.current.pages[0])==null?void 0:j.id,(Y=L.current.pages[0])==null?void 0:Y.metadata.title),L.current=null}catch(X){C(dn(X,"Could not create the app."))}finally{b(!1)}};return t.jsxs("div",{style:{position:"relative",display:"inline-flex",alignItems:"center",gap:6},children:[D?t.jsxs("div",{role:"status","aria-live":"polite",style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",alignItems:"center",gap:8,minWidth:260,maxWidth:440,padding:"8px 9px",borderRadius:9,background:`${n.success}12`,color:n.success,border:`1px solid ${n.success}55`},children:[t.jsx("span",{style:{width:26,height:26,borderRadius:999,display:"grid",placeItems:"center",background:`${n.success}20`},children:t.jsx(ct,{size:15})}),t.jsxs("span",{style:{display:"grid",gap:1,minWidth:0},children:[t.jsx("b",{style:{fontSize:11.5},children:D.kind==="existing"?"Already on this page":D.kind==="certified"?"Saved as a certified tile":D.kind==="review"?"Saved — review required":"Saved as editable narrative"}),t.jsxs("span",{title:cn(D.name,D.pageTitle),style:{fontSize:10.5,color:n.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[cn(D.name,D.pageTitle)," · editable draft"]}),t.jsxs("span",{title:D.tileTitle,style:{fontSize:10,color:n.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["Tile: ",D.tileTitle]}),D.kind==="review"||D.kind==="narrative"?t.jsx("span",{style:{fontSize:10,color:n.textMuted,lineHeight:1.35},children:"Stays local and cannot publish until reviewed, promoted, or removed."}):null]}),i?t.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>i(D.appId,D.pageId,D.draftId),style:{...J(n),color:n.success,whiteSpace:"nowrap"},title:"Open the App page containing this tile",children:["Open App ",t.jsx(Ri,{size:12})]}):null]}):null,t.jsxs("button",{type:"button",className:"dql-hover dql-lift",onClick:M,style:D?J(n):lr(n),children:[t.jsx(rn,{size:13}),D?"Add to another":"Add to app"]}),s?t.jsxs(t.Fragment,{children:[t.jsx("div",{onClick:W,style:{position:"fixed",inset:0,zIndex:40}}),t.jsxs("div",{style:eo(n),children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[t.jsx("span",{style:{fontSize:12,fontWeight:700,color:n.textPrimary},children:g==="new"?"Name the new App draft":"Save to an editable App"}),t.jsx("button",{type:"button",onClick:W,style:{border:"none",background:"transparent",color:n.textMuted,cursor:"pointer",fontSize:15,lineHeight:1},children:"×"})]}),m?t.jsx("div",{style:{fontSize:11,color:n.error,marginBottom:7,lineHeight:1.4},children:m}):null,g==="new"?t.jsxs("div",{style:{display:"grid",gap:8},children:[t.jsx("input",{autoFocus:!0,value:u,onChange:_=>y(_.target.value),onKeyDown:_=>{_.key==="Enter"&&Z()},placeholder:"App name",style:cr(n)}),t.jsxs("div",{style:{display:"flex",gap:6},children:[l&&l.length>0?t.jsx("button",{type:"button",className:"dql-hover",onClick:()=>a("list"),style:J(n),children:"Back"}):null,t.jsxs("button",{type:"button",className:"dql-hover",disabled:h||!u.trim(),onClick:()=>void Z(),style:{...lr(n),flex:1,justifyContent:"center"},children:[h?t.jsx(Ve,{size:13,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}}):t.jsx(ot,{size:13}),"Create draft & add"]})]})]}):l===null?t.jsx("div",{style:{fontSize:11.5,color:n.textMuted,padding:"8px 2px"},children:"Loading apps…"}):c?t.jsxs("div",{style:{display:"grid",gap:8},children:[t.jsx("div",{style:{fontSize:11.5,color:n.error,lineHeight:1.4},children:"Couldn't load your apps."}),t.jsxs("div",{style:{display:"flex",gap:6},children:[t.jsx("button",{type:"button",className:"dql-hover",onClick:()=>void V(),style:J(n),children:"Retry"}),t.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>a("new"),style:{...dr(n),width:"auto",flex:1,marginBottom:0,justifyContent:"center"},children:[t.jsx(ot,{size:13})," New app…"]})]})]}):t.jsxs("div",{style:{display:"grid",gap:3,maxHeight:244,overflow:"auto"},children:[t.jsxs("label",{style:{display:"grid",gap:3,marginBottom:5},children:[t.jsx("span",{style:{fontSize:10.5,color:n.textMuted},children:"Tile name"}),t.jsx("input",{value:F,onChange:_=>$(_.target.value),placeholder:st(e.question),maxLength:120,style:cr(n)})]}),t.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>a("new"),style:dr(n),children:[t.jsx(ot,{size:13})," New app…"]}),l.map(_=>t.jsxs("button",{type:"button",className:"dql-hover",disabled:h,onClick:()=>void k(_),style:to(n),children:[t.jsx(rn,{size:13,style:{flex:"0 0 auto",opacity:.7}}),t.jsxs("span",{style:{flex:1,minWidth:0,display:"grid",gap:1,overflow:"hidden",textAlign:"left"},children:[t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:_.name}),t.jsx("small",{style:{color:n.textMuted},children:_.kind==="draft"?"Local editable draft":"Project App · creates a safe edit draft"})]})]},_.id))]})]})]}):null]})}function jn(e){var n;if(e.trustState==="certified")return"Answered from a certified block.";if(e.route==="dql_block_draft")return"Prepared an ownerless review draft. Add it to Block Studio when you are ready to save it.";if(e.trustState==="governed")return"Built from governed metrics and dimensions.";if(e.trustState==="grounded")return"Ran cleanly against your data. Save it as a block when it is reusable.";if(wn(e)){const r=e.artifacts.map(o=>o.payload).filter(o=>!!(o&&typeof o=="object"&&!Array.isArray(o)));if(r.some(o=>{const l=o.result;return!!(l&&typeof l=="object"&&!Array.isArray(l))}))return"Exploratory · DBT-grounded. The query and bounded join probes ran, but no certified relationship path covers it yet.";const s=(n=r.find(o=>typeof o.executionError=="string"))==null?void 0:n.executionError;return typeof s=="string"&&s.trim()?"Exploratory · DBT-grounded. DQL prepared a review-required query, but its bounded execution failed. Inspect the error and DQL artifact before reuse.":"Exploratory · DBT-grounded. DQL prepared a review-required query, but it has not executed yet."}return e.route==="modeling_draft"?"AI-drafted modeling proposal. Review the exact source diff, then save it as a draft — nothing is written or joinable yet.":e.route==="skill_draft"?"AI-drafted Skill proposal. Review it, then save it as a draft — it will not guide any agent until you activate it.":e.trustState==="review_required"?"AI-generated answer. Save it as a block when you want to keep it.":(e.trustState==="blocked",null)}function wn(e){return e.artifacts.some(n=>{const r=n.payload;return!!(r&&typeof r=="object"&&!Array.isArray(r)&&r.exploratoryCandidate)})}function Ls(e){return e.trustState==="certified"?"Certified answer":e.route==="dql_block_draft"?"Draft block":wn(e)?"Exploratory DBT-grounded answer":e.route==="semantic_answer"?"Semantic answer":e.route==="generated_answer"?"AI-generated answer":Cr[e.route]}function Ds({artifact:e,payload:n,t:r,onOpenApp:i}){const s=typeof n.sessionId=="string"?n.sessionId:void 0,o=n.proposal&&typeof n.proposal=="object"?n.proposal:void 0,l=typeof n.proposalHash=="string"?n.proposalHash:void 0,[d,c]=f.useState(()=>o?ji(o):new Set),[p,g]=f.useState(!1),[a,u]=f.useState(null),[y,h]=f.useState(null);if(!o||!s)return t.jsxs("div",{style:fn(r),children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx(et,{kind:e.kind}),t.jsx("div",{style:{fontSize:12,fontWeight:800,color:r.textPrimary},children:e.title})]}),t.jsx("div",{style:{fontSize:11.5,color:r.textMuted},children:"This proposal is no longer available. Ask again to rebuild it."})]});const b=async m=>{var F,$;g(!0),u(null);const C=await re.commitAppAiBuild(s,{selectedTileIds:Array.from(d),expectedProposalHash:l,...m.appName?{appName:m.appName}:{},...m.pageTitle?{pageTitle:m.pageTitle}:{},...m.audience?{audience:m.audience}:{},...Object.keys(m.tileOverrides).length>0?{tileOverrides:m.tileOverrides}:{}});if(g(!1),!C.ok){u(C.error);return}h({appId:((F=C.app)==null?void 0:F.id)??C.session.appId??"",dashboardId:C.dashboardId??void 0,name:(($=C.app)==null?void 0:$.name)??e.title})};return t.jsxs("div",{style:fn(r),children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx(et,{kind:e.kind}),t.jsx("div",{style:{fontSize:12,fontWeight:800,color:r.textPrimary,flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:qe(e.title)})]}),y?t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,color:r.success,fontSize:12,fontWeight:750},children:[t.jsx(ct,{size:13})," Created ",y.name]}),y.appId&&i?t.jsx("button",{type:"button",className:"dql-hover",onClick:()=>i(y.appId,y.dashboardId),style:J(r),children:"Open app"}):null]}):t.jsx(wi,{proposal:o,t:r,selected:d,onToggle:m=>{c(C=>{const F=new Set(C);return F.has(m)?F.delete(m):F.add(m),F})},onCreate:m=>void b(m),defaultName:e.title,busy:p,error:a,compact:!0})]})}function Fr({artifact:e,certifiedBlockName:n,initialResult:r,initialChartConfig:i,payload:s,executionTarget:o,t:l,themeMode:d,embedded:c=!1,expanded:p=!1}){var H;const[g,a]=f.useState(e),[u,y]=f.useState(()=>e.parameters??[]),[h,b]=f.useState(()=>({...e.parameterValues??{},...un(s)})),[m,C]=f.useState(r),[F,$]=f.useState(i),[D,R]=f.useState(!!n),[L,V]=f.useState(!1),[M,W]=f.useState(null),[O,se]=f.useState(!1),[k,Z]=f.useState(""),[_,j]=f.useState(""),Y=f.useRef(!1),X=f.useRef(e);X.current=e;const ee=xs(e);f.useEffect(()=>{const A=X.current;if(a(A),se(!1),!n){y(A.parameters??[]),b({...A.parameterValues??{},...un(s)}),R(!1);return}let U=!1;return R(!0),re.getCertifiedBlockParameters(n).then(w=>{U||(y(w.parameters),b(S=>({...Object.fromEntries(w.parameters.flatMap(K=>K.default===void 0?[]:[[K.name,K.default]])),...S})))}).catch(w=>{U||W(w instanceof Error?w.message:String(w))}).finally(()=>{U||R(!1)}),()=>{U=!0}},[ee,n]);const E=async()=>{if(!Y.current){Y.current=!0,V(!0),W(null);try{const A=await re.invokeDqlArtifact(g,h,void 0,n,o);C(A.result),a(A.artifact),A.result.chartConfig&&typeof A.result.chartConfig=="object"&&$(A.result.chartConfig),A.parameters.length>0&&y(A.parameters)}catch(A){W(A instanceof Error?A.message:String(A))}finally{Y.current=!1,V(!1)}}},B=f.useMemo(()=>Sr(g,m),[g,m]),te=()=>{const A=B[0];A&&(Z(A.column),j(A.values[0]==null?"":String(A.values[0])),se(!0),W(null))},G=async()=>{try{const A=g.kind==="sql_block"?await re.addDqlArtifactResultFilter(g,m.columns,k,_,o):ys(g,m,k,_);a(A.artifact),y(A.artifact.parameters??[]),b(U=>({...U,...A.artifact.parameterValues??{}})),se(!1),W(null)}catch(A){W(A instanceof Error?A.message:String(A))}},xe=u.some(vr),ue=Object.entries(h).filter(([,A])=>A!=null&&A!=="");return t.jsxs("div",{style:{display:"grid",gap:9},children:[ue.length>0?t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap",padding:c?"8px 12px 0":0},children:[t.jsx("span",{style:{fontSize:10.5,fontWeight:750,color:l.textMuted},children:"Applied inputs"}),ue.map(([A,U])=>t.jsxs("span",{style:{fontSize:10.5,color:l.textSecondary,border:`1px solid ${l.cellBorder}`,background:l.appBg,borderRadius:999,padding:"2px 7px"},children:[A.replace(/_/g," ")," = ",Ns(U)]},A))]}):null,D?t.jsx("div",{style:{fontSize:10.5,color:l.textMuted},children:"Loading reusable inputs…"}):xe||B.length>0?t.jsxs("div",{style:{display:"grid",gap:8,padding:9,margin:c?"0 12px":0,border:`1px solid ${l.cellBorder}`,borderRadius:7,background:l.appBg},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:11,fontWeight:800,color:l.textPrimary},children:"Change DQL inputs"}),t.jsx("div",{style:{fontSize:10,color:l.textMuted},children:"Reruns this DQL artifact directly. It does not start another AI search."})]}),B.length>0?t.jsxs("button",{type:"button",onClick:te,style:J(l),children:[t.jsx(ot,{size:11})," Add result filter"]}):null,t.jsxs("button",{type:"button",disabled:L,onClick:()=>void E(),style:{...J(l),color:l.accent,opacity:L?.65:1},children:[L?t.jsx(Ve,{size:11,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}}):t.jsx(Ge,{size:11}),L?"Running…":"Apply"]})]}),O?t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(150px, 1fr) minmax(150px, 1fr) auto auto",gap:7,alignItems:"end",padding:8,border:`1px solid ${l.cellBorder}`,borderRadius:7,background:l.cellBg},children:[t.jsxs("label",{style:{display:"grid",gap:4,fontSize:10,fontWeight:750,color:l.textSecondary},children:["Result column",t.jsx("select",{"aria-label":"Result column for new DQL input",value:k,onChange:A=>{const U=A.target.value,w=B.find(S=>S.column===U);Z(U),j((w==null?void 0:w.values[0])==null?"":String(w.values[0]))},style:ur(l),children:B.map(A=>t.jsx("option",{value:A.column,children:A.column.split("_").join(" ")},A.column))})]}),t.jsxs("label",{style:{display:"grid",gap:4,fontSize:10,fontWeight:750,color:l.textSecondary},children:["Default value",t.jsx("input",{"aria-label":"Default value for new DQL input",value:_,list:`ask-filter-${k}`,onChange:A=>j(A.target.value),style:ur(l)}),t.jsx("datalist",{id:`ask-filter-${k}`,children:(((H=B.find(A=>A.column===k))==null?void 0:H.values)??[]).map(A=>t.jsx("option",{value:String(A)},`${typeof A}:${String(A)}`))})]}),t.jsx("button",{type:"button",onClick:()=>{G()},style:{...J(l),color:l.accent},children:"Add input"}),t.jsx("button",{type:"button",onClick:()=>se(!1),style:J(l),children:"Cancel"})]}):null,u.length>0?t.jsx(ts,{parameters:u,values:h,onChange:(A,U)=>b(w=>({...w,[A]:U})),t:l}):null,B.length>0?t.jsx("div",{style:{fontSize:9.5,color:l.textMuted},children:"Extra filters are available only for semantic dimensions in this result. They stay transient until you explicitly save a block."}):null]}):null,M?t.jsx("div",{style:{fontSize:10.5,color:l.error},children:M}):null,t.jsx(gn,{result:m,themeMode:d,t:l,chartConfig:F,embedded:c,tabLabels:c?{table:"Results",chart:"Visualization"}:void 0,contentMaxHeight:p?"calc(100vh - 172px)":void 0,tableMaxHeight:p?"calc(100vh - 250px)":void 0})]})}function un(e){const n=e.result&&typeof e.result=="object"&&!Array.isArray(e.result)?e.result:void 0,r=Array.isArray(n==null?void 0:n.parameters)?n.parameters:Array.isArray(e.parameters)?e.parameters:[];return Object.fromEntries(r.flatMap(i=>{if(!i||typeof i!="object")return[];const s=i;return typeof s.name=="string"?[[s.name,s.value]]:[]}))}function Ns(e){return Array.isArray(e)?e.map(n=>String(n)).join(", "):typeof e=="boolean"?e?"true":"false":String(e)}function Wr(e,n){const r=n.result&&typeof n.result=="object"&&!Array.isArray(n.result)?n.result:void 0,i=n.block&&typeof n.block=="object"&&!Array.isArray(n.block)?n.block:void 0;return[r==null?void 0:r.blockName,n.sourceCertifiedBlock,i==null?void 0:i.name,e.ref].find(o=>typeof o=="string"&&o.trim().length>0)}function Or({artifact:e,t:n,themeMode:r,onInsertSql:i,onInsertDql:s,insertDqlActionLabel:o,sourceRunId:l,sourceQuestion:d,onOpenBlock:c,onOpenResearch:p,onOpenApp:g,onNextAction:a}){const u=e.payload&&typeof e.payload=="object"?e.payload:{};if(e.kind==="app_proposal")return t.jsx(Ds,{artifact:e,payload:u,t:n,onOpenApp:g});const y=Be(u),h=xt(u),b=Ot(u),m=typeof u.sql=="string"?u.sql:typeof u.sqlPreview=="string"?u.sqlPreview:typeof u.proposedSql=="string"?u.proposedSql:void 0,C=typeof u.name=="string"?u.name:e.title,F=typeof u.path=="string"?u.path:e.ref,$=u.draftBlock&&typeof u.draftBlock=="object"&&!Array.isArray(u.draftBlock)?u.draftBlock:void 0,D=typeof($==null?void 0:$.path)=="string"?$.path:void 0,R=typeof($==null?void 0:$.name)=="string"?$.name:void 0,L=(h==null?void 0:h.sourcePath)??D??(e.kind==="dql_block_draft"?F:void 0),V=(h==null?void 0:h.name)??R??C,M=(h==null?void 0:h.kind)==="sql_block"||e.kind==="dql_block_draft"?"Open DQL draft":"Open DQL artifact",W=u.plan&&typeof u.plan=="object"?u.plan:void 0,O=Array.isArray(W==null?void 0:W.steps)?W.steps:[],se=Array.isArray(W==null?void 0:W.gaps)?W.gaps.map(String):[],k=typeof u.researchRunId=="string"?u.researchRunId:e.kind==="research_run"&&typeof e.ref=="string"?e.ref:void 0,Z=typeof u.notebookPath=="string"?u.notebookPath:void 0,_=Array.isArray(u.generatedPaths)?u.generatedPaths.filter(E=>typeof E=="string"):[],j=u.narration&&typeof u.narration=="object"?u.narration:void 0,Y=Array.isArray(j==null?void 0:j.keyFindings)?j.keyFindings.filter(E=>typeof E=="string"):[],X=typeof(j==null?void 0:j.recommendation)=="string"?j.recommendation:void 0,ee=e.trustState==="certified"?Wr(e,u):void 0;if(e.kind==="dql_block_draft"){const E=te=>Array.isArray(te)?te.filter(G=>typeof G=="string"):void 0,B=u.certifierVerdict&&typeof u.certifierVerdict=="object"?u.certifierVerdict:void 0;return t.jsx(Zi,{t:n,name:typeof u.name=="string"?u.name:C,status:"draft",description:typeof u.description=="string"?u.description:void 0,dql:(h==null?void 0:h.source)??(typeof u.dqlSource=="string"?u.dqlSource:void 0),sqlPreview:m,grain:typeof u.grain=="string"?u.grain:void 0,outputs:E(u.outputs),dimensions:E(u.dimensions)??(h==null?void 0:h.dimensions),entities:E(u.entities),certifierVerdict:B?{blocking:E(B.blocking)??[],warnings:E(B.warnings)??[],ready:!!B.ready}:void 0,actions:t.jsxs(t.Fragment,{children:[m&&s?t.jsx("button",{type:"button",onClick:()=>s({sql:m,dqlArtifact:h,result:y,chartConfig:y?Fe(u,y):void 0,title:C,sourceRunId:l,question:d}),style:J(n),children:o??"Insert as DQL cell"}):m&&i?t.jsx("button",{type:"button",onClick:()=>i(m,C,{question:d,sourceRunId:l}),style:J(n),children:"Insert SQL preview"}):null,L&&c?t.jsx("button",{type:"button",onClick:()=>c(L,V),style:J(n),children:M}):null]})})}return t.jsxs("div",{style:fn(n),children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx(et,{kind:e.kind}),t.jsx("div",{style:{fontSize:12,fontWeight:800,color:n.textPrimary,flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:qe(e.title)})]}),Y.length>0?t.jsxs("div",{style:{display:"grid",gap:4},children:[t.jsx("div",{style:{fontSize:11,fontWeight:800,color:n.textSecondary},children:"Key findings"}),t.jsx(rr,{items:Y,t:n,renderItem:(E,B)=>t.jsxs("div",{style:{fontSize:11.5,color:n.textSecondary,lineHeight:1.4,display:"flex",gap:6},children:[t.jsx("span",{style:{color:n.accent},children:"•"}),t.jsx("span",{children:E})]},B)})]}):O.length>0?t.jsx("div",{style:{display:"grid",gap:5},children:t.jsx(rr,{items:O,t:n,renderItem:(E,B)=>t.jsxs("div",{style:{fontSize:11.5,color:n.textSecondary,lineHeight:1.35},children:[B+1,". ",String(E.thought??E.expectation??"Research step")]},B)})}):null,X?t.jsxs("div",{style:{fontSize:11.5,color:n.textPrimary,lineHeight:1.4,display:"flex",gap:6},children:[t.jsx("span",{style:{color:n.accent},children:"→"}),t.jsx("span",{children:X})]}):null,y?h?t.jsx(Fr,{artifact:h,certifiedBlockName:ee,initialResult:y,initialChartConfig:Fe(u,y),payload:u,t:n,themeMode:r}):t.jsx(gn,{result:y,themeMode:r,t:n,chartConfig:Fe(u,y)}):null,h?t.jsxs("details",{children:[t.jsxs("summary",{style:{cursor:"pointer",fontSize:11,color:n.textSecondary,listStyle:"none",display:"flex",alignItems:"center",gap:5},children:[t.jsx(gt,{size:12}),t.jsx("span",{children:"View DQL artifact"}),t.jsxs("span",{style:{marginLeft:"auto",display:"inline-flex",alignItems:"center",gap:4},children:[h.source?t.jsx(Et,{text:h.source,t:n,title:"Copy DQL"}):null,!L&&a?t.jsxs("button",{type:"button",className:"dql-hover",title:"Save this DQL as a reusable block",onClick:E=>{E.preventDefault(),E.stopPropagation(),a({id:"save-dql-block",label:"Save as DQL block",route:"dql_block_draft"})},style:{border:"none",background:"transparent",cursor:"pointer",color:n.accent,display:"inline-flex",alignItems:"center",gap:3,fontSize:10.5,fontWeight:700,padding:"2px 4px"},children:[t.jsx(xn,{size:12})," Save as block"]}):null]})]}),h.sourcePath?t.jsx("div",{style:{marginTop:6,fontSize:10.5,color:n.textMuted},children:h.sourcePath}):null,t.jsx("pre",{style:{...ft(n),marginTop:6},children:h.source})]}):null,m?t.jsxs("details",{children:[t.jsxs("summary",{style:{cursor:"pointer",fontSize:11,color:n.textSecondary,listStyle:"none",display:"flex",alignItems:"center",gap:5},children:[t.jsx(hn,{size:12}),t.jsx("span",{children:Gr(!!h)}),t.jsx("span",{style:{marginLeft:"auto",display:"inline-flex",alignItems:"center",gap:4},children:t.jsx(Et,{text:m,t:n,title:"Copy SQL"})})]}),t.jsx("pre",{style:{...ft(n),marginTop:6},children:m})]}):null,se.length>0?t.jsxs("div",{style:{fontSize:11.5,color:n.textSecondary,lineHeight:1.4},children:["Gaps: ",se.join(", ")]}):null,_.length>0?t.jsxs("div",{style:{fontSize:11.5,color:n.textSecondary,lineHeight:1.4},children:["Files: ",_.join(", ")]}):null,t.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[k&&p?t.jsx("button",{type:"button",onClick:()=>p(k,Z),style:J(n),children:"Open research"}):null,m&&s?t.jsx("button",{type:"button",onClick:()=>s({sql:m,dqlArtifact:h,result:y,chartConfig:y?Fe(u,y):void 0,title:C,mixedSourcePlan:b,sourceRunId:l,question:d}),style:b?{...J(n),background:n.accent,borderColor:n.accent,color:"#fff",fontWeight:850,padding:"7px 11px"}:J(n),children:b?"Add workflow to notebook":h?"Insert as DQL cell":"Add SQL to notebook"}):m&&i?t.jsx("button",{type:"button",onClick:()=>i(m,C,{question:d,sourceRunId:l}),style:J(n),children:"Insert SQL preview"}):null,L&&c?t.jsx("button",{type:"button",onClick:()=>c(L,V),style:J(n),children:M}):null]})]})}function Ps({run:e}){return e.trustState==="certified"?t.jsx(ye,{size:16,color:"#16a34a"}):e.trustState==="governed"?t.jsx(ye,{size:16,color:"#2563eb"}):e.trustState==="grounded"?t.jsx(ye,{size:16,color:"#2563eb"}):e.status==="completed"?t.jsx(ct,{size:16,color:"#16a34a"}):e.status==="blocked"?t.jsx(sn,{size:16,color:"#ef4444"}):t.jsx(sn,{size:16,color:"#d97706"})}function et({kind:e}){return e==="sql_cell"?t.jsx(hn,{size:14}):e==="dql_block_draft"?t.jsx(gt,{size:14}):e==="app_draft"||e==="app_proposal"?t.jsx(rn,{size:14}):e==="research_run"?t.jsx(ut,{size:14}):t.jsx(Ge,{size:14})}function Fs({run:e,t:n}){const r=e.trustState==="certified"?n.success:e.trustState==="governed"||e.trustState==="grounded"?n.accent:e.trustState==="blocked"?n.error:e.trustState==="not_applicable"?n.textMuted:n.warning,i=e.trustState==="certified"?"Certified":e.route==="dql_block_draft"?"Draft":wn(e)?"Exploratory":e.status==="needs_clarification"?"Needs input":e.trustState==="blocked"?"Refused":"AI-generated";return t.jsx("span",{style:{border:`1px solid ${r}55`,color:r,background:`${r}12`,borderRadius:999,padding:"3px 7px",fontSize:10,fontWeight:850},children:i})}function Hr({evaluations:e,t:n}){if(e.length===0)return null;const r=e.filter(s=>!s.passed),i=e.filter(s=>s.passed);return t.jsxs("div",{style:{display:"grid",gap:6,gridTemplateColumns:"minmax(0, 1fr)",minWidth:0},children:[r.map(s=>t.jsx(pn,{evaluation:s,t:n},s.id)),i.length>0?t.jsxs("details",{children:[t.jsxs("summary",{className:"dql-hover",style:{cursor:"pointer",listStyle:"none",display:"inline-flex",alignItems:"center",gap:6,fontSize:11,fontWeight:700,color:n.textMuted,width:"fit-content"},children:[t.jsx(ye,{size:12,color:n.success}),t.jsxs("span",{children:[i.length," check",i.length>1?"s":""," verified"]})]}),t.jsx("div",{style:{display:"grid",gap:5,marginTop:7},children:i.map(s=>t.jsx(pn,{evaluation:s,t:n},s.id))})]}):null]})}function pn({evaluation:e,t:n}){const r=e.passed?n.success:e.severity==="blocking"?n.error:n.warning;return t.jsxs("div",{style:{display:"flex",gap:7,alignItems:"flex-start",fontSize:11.5,color:n.textSecondary,minWidth:0},children:[t.jsx("span",{style:{color:r,lineHeight:"16px",flex:"0 0 auto",fontWeight:800},children:e.passed?"OK":e.severity==="blocking"?"Stop":"Review"}),t.jsxs("span",{style:{lineHeight:1.4,minWidth:0,flex:1,overflowWrap:"anywhere"},children:[e.message,!e.passed&&e.suggestedRepair?t.jsxs("span",{style:{display:"block",color:n.textMuted,marginTop:1},children:["↳ ",e.suggestedRepair]}):null]})]})}function tn({t:e,icon:n,label:r,tone:i}){const s=i==="accent"?e.accent:i==="warning"?e.warning:e.textMuted;return t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,border:`1px solid ${s}44`,color:s,background:`${s}10`,borderRadius:999,padding:"2px 7px",fontSize:10,fontWeight:800},children:[n,t.jsx("span",{children:r})]})}function Ws(e,n){switch(e){case"passed":return n.success;case"repaired":return n.accent;case"escalated":return n.accent;case"blocked":return n.error;default:return n.warning}}function Qr({steps:e,t:n}){return t.jsxs("details",{style:{border:`1px solid ${n.headerBorder}`,background:n.cellBg,borderRadius:8,padding:"6px 9px"},children:[t.jsxs("summary",{style:{cursor:"pointer",fontSize:11.5,fontWeight:800,color:n.textSecondary,listStyle:"none",display:"flex",alignItems:"center",gap:6},children:[t.jsx(pt,{size:13}),t.jsxs("span",{children:["Plan trace · ",e.length," steps"]})]}),t.jsx("div",{style:{display:"grid",gap:10,marginTop:8},children:e.map(r=>{const i=Ws(r.status,n);return t.jsxs("div",{style:{display:"grid",gap:4,paddingLeft:8,borderLeft:`2px solid ${i}55`},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[t.jsxs("span",{style:{fontSize:11.5,fontWeight:850,color:n.textPrimary},children:[r.index,". ",Cr[r.route]]}),t.jsxs("span",{style:{border:`1px solid ${i}55`,color:i,background:`${i}12`,borderRadius:999,padding:"1px 6px",fontSize:9.5,fontWeight:850,display:"inline-flex",alignItems:"center",gap:3},children:[r.status==="escalated"?t.jsx(xr,{size:10}):r.status==="repaired"?t.jsx(Pt,{size:10}):null,r.status.split("_").join(" ")]}),r.attempts>1?t.jsxs("span",{style:{fontSize:10,color:n.textMuted},children:[r.attempts," attempts"]}):null]}),r.goal?t.jsx("div",{style:{fontSize:11,color:n.textMuted,lineHeight:1.35},children:r.goal}):null,r.evaluations.length>0?t.jsx("div",{style:{display:"grid",gap:4},children:r.evaluations.map(s=>t.jsx(pn,{evaluation:s,t:n},s.id))}):null]},r.id)})})]})}function Os(e){if(e==="research")return"research";if(e==="sql_cell")return"sql";if(e==="dql_block_draft")return"block";if(e==="modeling_draft")return"modeling";if(e==="skill_draft")return"skill";if(e==="app_build")return"app";if(e==="certified_answer"||e==="semantic_answer"||e==="generated_answer")return"ask"}function Hs(e,n){return n==="sql_cell"?`Create a SQL cell for: ${e.question}`:n==="dql_block_draft"?`Create a DQL block draft for: ${e.question}`:n==="modeling_draft"?`Revise the modeling proposal for: ${e.question}`:n==="skill_draft"?`Revise the Skill proposal for: ${e.question}`:n==="app_build"?`Build an app for: ${e.question}`:n==="research"?`Research deeper: ${e.question}`:e.question}function sr(e){return`${e}_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Je(e){return e.replace(/^\s*Outcome\s*:\s*[^\n]*\n+/i,"").replace(/^\s*Review required:\s*/gim,"").replace(/\breview-required\b/gi,"AI-generated").replace(/\*\*(.+?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/^_(.+?)_$/gm,"$1").trim()}function qe(e){return e.replace(/^\s*Review required:\s*/gim,"").replace(/\breview-required\b/gi,"AI-generated").replace(/\bqueued for review\b/gi,"saved as a draft").trim()}function Qs(e,n){const r=i=>i.toLowerCase().replace(/[\s.,!?'"()`*_-]+/g," ").trim();return r(e)===r(n)}function Be(e){var r,i;const n=[e.result,e.resultPreview,(r=e.researchRun)==null?void 0:r.resultPreview,(i=e.result)==null?void 0:i.result];for(const s of n){if(!s||typeof s!="object")continue;const o=s;if(!Array.isArray(o.rows)&&!Array.isArray(o.columns))continue;const l=Array.isArray(o.rows)?o.rows.filter(c=>!!(c&&typeof c=="object")):[],d=Array.isArray(o.columns)&&o.columns.length>0?o.columns.map(c=>typeof c=="string"?c:(c==null?void 0:c.name)??String(c)):l.length>0?Object.keys(l[0]):[];if(!(l.length===0&&d.length===0&&typeof o.rowCount!="number"))return{columns:d,rows:l,rowCount:typeof o.rowCount=="number"?o.rowCount:l.length,...typeof o.executionTime=="number"?{executionTime:o.executionTime}:{}}}}function Fe(e,n){const r=e.result&&typeof e.result=="object"?e.result:void 0,i=r!=null&&r.chartConfig&&typeof r.chartConfig=="object"?r.chartConfig:e.chartConfig&&typeof e.chartConfig=="object"?e.chartConfig:{},s=typeof e.suggestedViz=="string"?e.suggestedViz:typeof(r==null?void 0:r.suggestedViz)=="string"?r.suggestedViz:void 0,o=i.decisionSource==="authored"||i.decisionSource==="agent"||i.decisionSource==="data"||i.decisionSource==="user"?i.decisionSource:void 0,l=typeof i.chart=="string"?i.chart:s,d=l?l.toLowerCase().replace(/_/g,"-")==="single-value"?"kpi":l:void 0,c=n.columns,p=u=>typeof i[u]=="string"&&c.includes(i[u])?i[u]:void 0,g=Array.isArray(i.metrics)?i.metrics.filter(u=>typeof u=="string"&&c.includes(u)):[],a={...d?{chart:d}:{},...d?{decisionSource:o??"agent"}:{},...typeof i.rationale=="string"?{rationale:i.rationale}:{},...p("x")?{x:p("x")}:{},...p("y")?{y:p("y")}:{},...g.length>0?{metrics:g}:{},...p("color")?{color:p("color")}:{},...typeof i.title=="string"?{title:i.title}:{},...typeof i.colorPalette=="string"?{colorPalette:i.colorPalette}:{},...typeof i.maxItems=="number"?{maxItems:i.maxItems}:{}};return Object.keys(a).length>0?a:void 0}function Vr(e,n){var i;const r=Fe(e,n);return(r==null?void 0:r.chart)==="table"&&(((i=r.metrics)==null?void 0:i.length)??0)<=1&&r.decisionSource!=="authored"&&r.decisionSource!=="user"?{...r,chart:void 0}:r}function xt(e){const n=Ue(e.dqlArtifact);if(n)return n;const r=e.researchRun&&typeof e.researchRun=="object"&&!Array.isArray(e.researchRun)?e.researchRun:void 0;return Ue(r==null?void 0:r.dqlArtifact)}function Gr(e){return e?"View compiled SQL preview":"View SQL preview"}function Et({text:e,t:n,title:r="Copy"}){const[i,s]=f.useState(!1),o=async l=>{l.preventDefault(),l.stopPropagation();try{await navigator.clipboard.writeText(e),s(!0),setTimeout(()=>s(!1),1500)}catch{}};return t.jsxs("button",{type:"button",onClick:o,title:r,className:"dql-hover",style:{border:"none",background:"transparent",cursor:"pointer",color:i?n.success:n.textMuted,display:"inline-flex",alignItems:"center",gap:3,fontSize:10.5,fontWeight:650,padding:"2px 4px"},children:[i?t.jsx(dt,{size:12}):t.jsx(mr,{size:12}),i?"Copied":null]})}function ie(e){return e.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{}}function Vs(e){var i,s,o;const n=[],r=new Set;for(const l of e.artifacts){const d=ie(l),c=Array.isArray(d.memoryContext)?d.memoryContext:[];for(const g of c){if(!g||typeof g!="object")continue;const a=g,u=typeof a.title=="string"?a.title.trim():"";!u||r.has(`m:${u}`)||(r.add(`m:${u}`),n.push({kind:"memory",id:typeof a.id=="string"?a.id:void 0,label:u,detail:typeof a.content=="string"?a.content:void 0}))}const p=Array.isArray(d.appliedHints)?d.appliedHints:[];for(const g of p){if(!g||typeof g!="object")continue;const a=g,u=typeof a.title=="string"?a.title.trim():"";if(!u||r.has(`h:${u}`))continue;r.add(`h:${u}`);const y=typeof((i=a.lesson)==null?void 0:i.rule)=="string"?a.lesson.rule:typeof a.guidance=="string"?a.guidance:void 0,h=[typeof a.scopeReason=="string"?a.scopeReason:void 0,typeof a.graphReason=="string"?a.graphReason:void 0].filter(Boolean).join("; "),b=typeof((s=a.matchSignals)==null?void 0:s.lexicalScore)=="number"?a.matchSignals.lexicalScore:void 0,m=typeof((o=a.matchSignals)==null?void 0:o.graphScore)=="number"?a.matchSignals.graphScore:void 0,C=b!==void 0||m!==void 0?`Signals: lexical ${(b??0).toFixed(2)}, graph ${(m??0).toFixed(2)}`:void 0;n.push({kind:"hint",id:typeof a.hintId=="string"?a.hintId:void 0,label:u,detail:[y,h?`Matched: ${h}`:void 0,C].filter(Boolean).join(" · ")||void 0})}}return n.slice(0,6)}function Ur({run:e,t:n}){const[r,i]=f.useState(!1),[s,o]=f.useState(new Set),l=f.useMemo(()=>Vs(e).filter(c=>!c.id||!s.has(c.id)),[e,s]);if(l.length===0)return null;const d=async c=>{try{await re.deleteAgentMemory(c),o(p=>new Set(p).add(c))}catch{}};return t.jsxs("div",{style:{display:"grid",gap:6,gridTemplateColumns:"minmax(0, 1fr)",minWidth:0},children:[t.jsxs("button",{type:"button",onClick:()=>i(c=>!c),style:Us(n),children:[t.jsx(Tt,{size:11}),t.jsxs("span",{children:["Applied ",l.length," learning",l.length>1?"s":""]}),r?t.jsx(yr,{size:11}):t.jsx(Lt,{size:11})]}),r?t.jsxs("div",{style:Ks(n),children:[l.map(c=>t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-start"},children:[t.jsx("span",{style:Ys(n,c.kind),children:c.kind==="hint"?"governed lesson":"memory"}),t.jsxs("div",{style:{minWidth:0,flex:1},children:[t.jsx("div",{style:{fontSize:11.5,fontWeight:650,color:n.textPrimary},children:c.label}),c.detail?t.jsx("div",{style:{fontSize:11,color:n.textMuted,lineHeight:1.4,marginTop:1},children:c.detail}):null]}),c.kind==="memory"&&c.id?t.jsx("button",{type:"button",onClick:()=>void d(c.id),style:Xs(n),children:"Stop using"}):null]},`${c.kind}:${c.label}`)),t.jsx("div",{style:{fontSize:10.5,color:n.textMuted},children:"Advisory only — learnings never override a certified answer. Manage them under Settings → Agent learning."})]}):null]})}function Sn(e){const n=[],r=new Set,i=e.trustState==="certified",s=(o,l)=>{typeof o!="string"||!o.trim()||r.has(o)||(r.add(o),n.push({label:o,certified:l}))};for(const o of e.artifacts){const l=ie(o);o.ref&&s(o.ref,i);const d=l.plan&&typeof l.plan=="object"?l.plan:void 0;Array.isArray(d==null?void 0:d.sources)&&d.sources.forEach(c=>s(c,i)),s(l.sourceCertifiedBlock,!0)}return n.slice(0,4)}function Re(e){for(const n of e.artifacts){const r=ie(n),i=r.researchRun&&typeof r.researchRun=="object"?r.researchRun:void 0,s=r.result&&typeof r.result=="object"&&!Array.isArray(r.result)?r.result:void 0,o=Ue(r.dqlArtifact),l=r.proposedSql??r.sql??r.sqlPreview??(s==null?void 0:s.sql)??(i==null?void 0:i.generatedSql)??(i==null?void 0:i.reviewedSql)??(o==null?void 0:o.compiledSql);if(typeof l=="string"&&l.trim())return l}}function nn(e){var n;if(e.trustState==="certified")for(const r of e.artifacts){const i=ie(r),s=i.blockName??i.blockId??((n=Ue(i.dqlArtifact))==null?void 0:n.name);if(typeof s=="string"&&s.trim())return s.trim()}}function Gs(e){for(const n of e.artifacts){const r=ie(n),i=Be(r);if(!i)continue;const s=Fe(r,i);if(s)return s}}function _e(e){for(const n of e.artifacts){const r=ie(n),i=Ue(r.dqlArtifact);if(i)return i;const s=r.researchRun&&typeof r.researchRun=="object"&&!Array.isArray(r.researchRun)?r.researchRun:void 0,o=Ue(s==null?void 0:s.dqlArtifact);if(o)return o}}function Mt(e){const n=e.route==="dql_block_draft"&&e.status!=="blocked"&&e.status!=="needs_clarification";if(e.route==="certified_answer"||!ht(e)&&!n)return;const r=_e(e),i=Re(e);if(!((!(r!=null&&r.source)||r.sourcePath)&&!i)){for(const s of e.artifacts){const o=ie(s),l=Be(o),d=Ot(o);if(l)return{sql:i,dqlArtifact:r,result:l,chartConfig:Fe(o,l),title:(r==null?void 0:r.name)??s.title??e.question,mixedSourcePlan:d,sourceRunId:e.id,question:e.question,executionTarget:e.executionTarget};if(d)return{sql:i,dqlArtifact:r,title:(r==null?void 0:r.name)??s.title??e.question,mixedSourcePlan:d,sourceRunId:e.id,question:e.question,executionTarget:e.executionTarget}}return{sql:i,dqlArtifact:r,title:(r==null?void 0:r.name)??e.question,sourceRunId:e.id,question:e.question,executionTarget:e.executionTarget}}}function Ot(e){const n=e.mixedSourcePlan;if(!n||typeof n!="object"||Array.isArray(n))return;const r=n;if(["localDataset","localAlias","localKey","warehouseKey","warehouseExpression","warehouseSql"].every(s=>typeof r[s]=="string"&&String(r[s]).trim()))return{datasetId:typeof r.datasetId=="string"?r.datasetId:void 0,datasetName:typeof r.datasetName=="string"?r.datasetName:void 0,localDataset:String(r.localDataset),localAlias:String(r.localAlias),localKey:String(r.localKey),warehouseKey:String(r.warehouseKey),warehouseExpression:String(r.warehouseExpression),warehouseSql:String(r.warehouseSql),warehouseRelations:Array.isArray(r.warehouseRelations)?r.warehouseRelations.filter(s=>typeof s=="string"):void 0}}function Kr(e,n){return{display:"inline-flex",alignItems:"center",gap:4,fontSize:10.5,padding:"2px 7px",borderRadius:999,background:n?`${e.success}14`:e.cellBg,color:n?e.success:e.textMuted,border:`1px solid ${n?`${e.success}44`:e.headerBorder}`}}function Us(e){return{display:"inline-flex",alignItems:"center",gap:5,alignSelf:"flex-start",fontSize:10.5,fontWeight:600,padding:"2px 8px",borderRadius:999,background:`${e.accent}14`,color:e.accent,border:`1px solid ${e.accent}33`,cursor:"pointer"}}function Ks(e){return{display:"grid",gap:8,padding:10,borderRadius:8,background:e.cellBg,border:`1px solid ${e.headerBorder}`}}function Ys(e,n){const r=n==="hint";return{flex:"0 0 auto",fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.04em",padding:"2px 6px",borderRadius:4,marginTop:1,background:r?`${e.accent}1f`:`${e.textMuted}1f`,color:r?e.accent:e.textMuted}}function Xs(e){return{flex:"0 0 auto",fontSize:10.5,border:`1px solid ${e.headerBorder}`,background:"transparent",color:e.textMuted,borderRadius:6,padding:"2px 7px",cursor:"pointer"}}function Js(e){return{width:30,height:30,borderRadius:8,background:`${e.accent}14`,border:`1px solid ${e.accent}36`,color:e.accent,display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"0 0 auto"}}function or(e){return{...Js(e),width:40,height:40}}function Bt(e){return{...Nt(e,{variant:"secondary",size:"md",pill:!0}),fontWeight:550}}function Zs(e){return{flex:1,minHeight:54,maxHeight:140,resize:"none",border:`1px solid ${e.btnBorder}`,background:e.inputBg,color:e.textPrimary,borderRadius:12,padding:"11px 13px",fontSize:13,lineHeight:1.45,fontFamily:e.font,outline:"none",boxShadow:"none"}}function ar(e,n){return{...Nt(e,{variant:n?"primary":"secondary",size:"lg"}),...n?{}:{color:e.textMuted}}}function lr(e){return{border:"none",background:e.accent,color:"#fff",borderRadius:8,padding:"7px 13px",display:"inline-flex",alignItems:"center",gap:6,fontSize:12,fontWeight:700,fontFamily:e.font,cursor:"pointer",boxShadow:`0 1px 5px ${e.accent}4d`}}function eo(e){return{position:"absolute",bottom:"calc(100% + 6px)",left:0,zIndex:41,width:264,background:e.cellBg,border:`1px solid ${e.headerBorder}`,borderRadius:10,boxShadow:"0 12px 32px rgba(0,0,0,0.2)",padding:10}}function to(e){return{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"8px 9px",borderRadius:7,border:"none",background:"transparent",color:e.textSecondary,fontSize:12.5,fontWeight:550,fontFamily:e.font,cursor:"pointer"}}function dr(e){return{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"8px 9px",borderRadius:7,border:`1px dashed ${e.accent}66`,background:`${e.accent}0d`,color:e.accent,fontSize:12.5,fontWeight:650,fontFamily:e.font,cursor:"pointer",marginBottom:2}}function cr(e){return{width:"100%",boxSizing:"border-box",border:`1px solid ${e.btnBorder}`,background:e.inputBg,color:e.textPrimary,borderRadius:8,padding:"8px 10px",fontSize:12.5,fontFamily:e.font,outline:"none"}}function no(e){return{alignSelf:"flex-end",maxWidth:"88%",background:`${e.accent}16`,color:e.textPrimary,border:`1px solid ${e.accent}32`,borderRadius:8,padding:"8px 10px",fontSize:12.5,lineHeight:1.45}}function ro(e){return{alignSelf:"flex-start",maxWidth:"92%",color:e.textPrimary,border:`1px solid ${e.cellBorder}`,background:e.appBg,borderRadius:10,padding:"10px 12px"}}function io(e){return{border:`1px solid ${e.cellBorder}`,background:e.appBg,borderRadius:8,padding:10,display:"grid",gap:10,gridTemplateColumns:"minmax(0, 1fr)",minWidth:0,maxWidth:"100%"}}function fn(e){return{border:`1px solid ${e.headerBorder}`,background:e.cellBg,borderRadius:8,padding:9,display:"grid",gap:8,gridTemplateColumns:"minmax(0, 1fr)",minWidth:0,maxWidth:"100%"}}function so(e){return{border:`1px solid ${e.headerBorder}`,background:e.cellBg,borderRadius:8,padding:9,fontSize:12.5,color:e.textPrimary,lineHeight:1.45}}function ft(e){return{margin:0,maxHeight:180,overflow:"auto",border:`1px solid ${e.headerBorder}`,background:e.editorBg,color:e.textPrimary,borderRadius:7,padding:9,fontSize:11,lineHeight:1.45,fontFamily:e.fontMono,whiteSpace:"pre-wrap"}}function ur(e){return{width:"100%",minWidth:0,boxSizing:"border-box",background:e.inputBg,border:`1px solid ${e.inputBorder}`,borderRadius:5,color:e.textPrimary,padding:"5px 7px",fontSize:11,fontFamily:e.font}}function J(e){return Nt(e,{variant:"secondary",size:"sm"})}const $t={warehouse:{title:"The warehouse rejected the query",hint:"The SQL reached your warehouse and it refused. The message below is the driver’s own."},dql_compilation:{title:"DQL could not build a reusable block",hint:"The query itself is fine — only saving this answer as a block is affected."},governance_gate:{title:"DQL stopped this before running it",hint:"A governance check refused the query, so it never reached the warehouse."},retrieval_gap:{title:"DQL could not confirm this data exists",hint:"The relation was not in the inspected metadata. Refreshing the connection scope usually resolves it."},ambiguity:{title:"One detail is missing",hint:"Answer the question above and DQL will continue."},provider:{title:"The AI provider failed",hint:"Nothing was run. Retry, or check the provider in Settings."},orchestration_budget:{title:"Ask could not freeze one executable plan",hint:"Nothing was run. Ask stopped its own planning loop before another provider call; narrow the metric or dimension and retry."},host:{title:"DQL hit an internal error",hint:"This is a defect in DQL. The detail below is what to report."},modeling_gap:{title:"The governed model does not cover this question",hint:"No query ran. Add or review the missing metric, dimension, relationship, or allocation rule."},proof_integrity:{title:"Not executed: exact semantic proof was not established",hint:"DQL could not establish the exact metric, requested grain, join keys, and fanout proof. Warehouse success cannot create that authority."},identity_integrity:{title:"DQL found an internal identity or target-binding defect",hint:"No query ran. This is an orchestration integrity defect, not missing business modeling."},policy:{title:"Policy or permissions blocked this query",hint:"No AI repair was attempted. Use only the server-provided access or connection actions."},result_contract:{title:"The warehouse result did not match the frozen plan",hint:"The query ran, but DQL rejected the returned columns, types, grain, or row bound."},compile:{title:"DQL could not compile the frozen plan",hint:"The query did not reach the warehouse. Review the exact plan binding and compiler diagnostic."},timeout:{title:"This run reached its hard deadline",hint:"DQL stopped the run at its request-owned deadline and did not accept a later result."},cancel:{title:"This run was cancelled",hint:"Cancellation is terminal and no later provider or warehouse result was accepted."},unknown:{title:"The query could not be completed",hint:"Inspect the details or use the bounded repair when it is available."}};function Yr(e){var n,r,i,s,o,l,d,c,p;for(const g of e.artifacts??[]){const a=ie(g),u=(n=a==null?void 0:a.warehouseFailure)==null?void 0:n.origin,y=typeof((r=a==null?void 0:a.analyticalFailure)==null?void 0:r.code)=="string"?a.analyticalFailure.code:"";if((a==null?void 0:a.refusalCode)==="modeling_gap")return"modeling_gap";if(((i=a==null?void 0:a.aggregationSafetyProof)==null?void 0:i.status)==="blocked")return"proof_integrity";if(["IDENTIFIER_SCOPE_INVALID","EXECUTION_TARGET_MISMATCH","SEMANTIC_TARGET_BINDING_MISSING","SEMANTIC_SOURCE_DRIFT"].includes(y))return"identity_integrity";if(["POLICY_DENIED","PERMISSION_DENIED"].includes(y))return"policy";if(y==="RESULT_CONTRACT_MISMATCH")return"result_contract";if(["TIMEOUT","SEMANTIC_COMPILATION_TIMEOUT"].includes(y))return"timeout";if(y==="EXECUTION_CANCELLED")return"cancel";if(["COMPILATION_FAILED","DIALECT_ERROR","SEMANTIC_ADAPTER_NOT_READY"].includes(y))return"compile";if(typeof u=="string"&&u in $t)return u;if(((s=a==null?void 0:a.providerFailure)==null?void 0:s.code)==="orchestration_budget_exhausted"||((o=a==null?void 0:a.providerFailure)==null?void 0:o.code)==="PROVIDER_DISPATCH_BUDGET_EXHAUSTED")return"orchestration_budget";if(a!=null&&a.providerFailure||(a==null?void 0:a.refusalCode)==="provider_error")return"provider";if((a==null?void 0:a.refusalCode)==="ambiguous")return"ambiguity";if((a==null?void 0:a.refusalCode)==="grounding_gap")return"retrieval_gap"}return((d=(l=e.diagnosticReceipt)==null?void 0:l.failure)==null?void 0:d.code)==="orchestration_budget_exhausted"?"orchestration_budget":((p=(c=e.diagnosticReceipt)==null?void 0:c.failure)==null?void 0:p.code)==="AI_PROVIDER_FAILURE"?"provider":"unknown"}function Xr(e){for(const n of e.artifacts??[]){const r=ie(n),s=(Array.isArray(r.validationWarnings)?r.validationWarnings.filter(o=>typeof o=="string"):[]).find(o=>/captur|reusable DQL block|save as (?:a )?block/i.test(o));if(s)return s}}function Jr(e){const n=e.repairCapability;return(n==null?void 0:n.version)===1&&n.automatic.eligible===!0&&n.automatic.action==="repair_embedded_sql"&&n.automatic.correctionCode==="SQL_EXECUTION_REPAIR"&&n.automatic.attemptsRemaining>0&&n.routeLocked===!0&&n.targetLocked===!0&&n.sourceImmutable===!0}function oo({run:e,detail:n,threadId:r,onRepaired:i,t:s}){const o=Yr(e),l=$t[o]??$t.unknown,[d,c]=f.useState(!1),[p,g]=f.useState(null),a=Jr(e),u=async()=>{if(!d){c(!0),g(null);try{const y=await re.repairAgentRunExecution(e.id,r);i(y.run)}catch(y){g(y instanceof Error?y.message:String(y))}finally{c(!1)}}};return t.jsxs("div",{"data-followup":"answer",style:{display:"flex",flexDirection:"column",gap:6,padding:"11px 13px",borderRadius:9,border:`1px solid ${s.error}33`,background:`${s.error}0d`},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7},children:[t.jsx(Ze,{size:13,color:s.error,style:{flexShrink:0}}),t.jsx("span",{style:{fontSize:12.5,fontWeight:700,color:s.textPrimary},children:l.title})]}),t.jsx("div",{style:{fontSize:12.5,lineHeight:1.6,color:s.textSecondary,wordBreak:"break-word"},children:qe(n)}),t.jsx("div",{style:{fontSize:11.5,lineHeight:1.5,color:s.textMuted},children:l.hint}),a?t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",marginTop:2},children:[t.jsxs("button",{type:"button",className:"dql-hover",disabled:d,onClick:()=>void u(),style:{...J(s),opacity:d?.7:1},children:[t.jsx(Pt,{size:12})," ",d?"Fixing and retrying…":"Fix and retry"]}),t.jsx("span",{style:{fontSize:10.5,color:s.textMuted},children:"One bounded repair attempt on the same data target."})]}):null,p?t.jsx("div",{role:"alert",style:{fontSize:11.5,lineHeight:1.45,color:s.error},children:qe(p)}):null]})}function Zr(e){var r,i,s;for(const o of e.artifacts??[]){const l=ie(o),d=l==null?void 0:l.warehouseFailure,c=[d==null?void 0:d.redactedMessage,d==null?void 0:d.diagnostic,l==null?void 0:l.executionError,(r=l==null?void 0:l.refusalDetails)==null?void 0:r.message].find(p=>typeof p=="string"&&p.trim().length>0);if(c)return c}const n=ao(e);return n||e.summary||((s=(i=e.diagnosticReceipt)==null?void 0:i.failure)==null?void 0:s.message)}function ao(e){var r;const n=[T((r=T(e.diagnosticReceipt))==null?void 0:r.resolvedAnalyticalPlan),...(e.artifacts??[]).flatMap(i=>{var o;const s=ie(i);return[T(s.resolvedAnalyticalPlan),T((o=T(s.diagnosticReceipt))==null?void 0:o.resolvedAnalyticalPlan)]})].filter(i=>!!i);for(const i of n){const s=T(i.query),l=[...je(s==null?void 0:s.measures).map(p=>({kind:"metric",binding:p})),...je(s==null?void 0:s.dimensions).map(p=>({kind:"dimension",binding:p})),...je(s==null?void 0:s.filters).flatMap(p=>{const g=T(p.binding);return g?[{kind:"filter",binding:g}]:[]})].find(({binding:p})=>p.status==="ambiguous"||p.status==="unresolved");if(!l)continue;const d=I(l.binding.requested)||`requested ${l.kind}`,c=Array.isArray(l.binding.candidateIds)?l.binding.candidateIds.filter(p=>typeof p=="string").map(lo):[];return l.binding.status==="ambiguous"&&c.length>1?`I found more than one governed ${l.kind} for “${d}”: ${c.join(" or ")}. Choose one before I run the query.`:`I couldn’t identify one governed ${l.kind} for “${d}”. Review that model binding before retrying.`}}function lo(e){return(e.split(/[:./]/).filter(Boolean).at(-1)??e).replace(/[_-]+/g," ").replace(/\b\w/g,r=>r.toUpperCase())}const vo=Object.freeze(Object.defineProperty({__proto__:null,ASK_FAILURE_PRESENTATION:$t,UnifiedAgentRunPanel:bs,agentRunHistoryFromItems:Ar,agentRunPerformanceRows:Dr,analyticalInspectorContract:Lr,analyticalInspectorSections:Ts,analyticalRepairActionLabels:Es,appPinDestinationLabel:cn,artifactReadyPayloadFromRun:Mt,artifactSqlDisclosureLabel:Gr,askAppDestinations:Pr,askAppWriteErrorMessage:dn,askArtifactMeta:Ft,askFailureDetail:Zr,askFailureOrigin:Yr,askInspectorTabsForState:Er,askRunAllowsExecutionRepair:Jr,askRunCaptureWarning:Xr,clarificationSelectionInput:It,completedRunGuidanceFor:zr,deriveResultChartConfig:Si,hasAnalyticalInspectorContract:Wt,inlineAskChartConfig:Vr,isAgentRunPinnable:ht,liveAgentActivityFor:Tr,longRunGuidanceFor:_r,preferredAskInspectorTab:bn,replacePresentedAgentRun:kr,researchSourceFromRun:Nr,resolveArtifactDqlView:xt,resolvedParameterValues:un,selectAgentExecutionConnection:Rr,threadItemsFromTurns:Ir,trustExplainer:jn,usePersistedAgentThreadId:ki},Symbol.toStringTag,{value:"Module"}));export{ts as B,yr as C,Hn as S,bs as U,Qi as a,Ji as b,vo as c};
@@ -1,2 +1,2 @@
1
- import{u as x,r as w,a as k,m}from"./index-mQd_pC-P.js";const C="dql:focus-notebook-cell";function h(e){window.setTimeout(()=>{window.dispatchEvent(new CustomEvent(C,{detail:{cellId:e}}))},0)}function S(e){var t,a,c;const i=(t=e.question)==null?void 0:t.trim(),n=(a=e.generatedSql)==null?void 0:a.trim(),s=(c=e.generatedDql)==null?void 0:c.trim();if(!(!i||!n&&!s))return{version:1,source:"agent_run",question:i,...n?{generatedSql:n}:{},...s?{generatedDql:s}:{},...e.sourceRunId?{sourceRunId:e.sourceRunId}:{}}}function g(e){return e.replace(/[^a-zA-Z0-9_ -]+/g," ").replace(/\s+/g,"_").replace(/^_+|_+$/g,"").slice(0,48)||"ai_analysis"}function E(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function I(e,i){var c,o,u,f,l,q;const n=(o=(c=e.dqlArtifact)==null?void 0:c.source)==null?void 0:o.trim(),s=(e.sql??n??"").trim();if(!s&&!n)return[];if(e.mixedSourcePlan){const r=e.mixedSourcePlan,A=m("markdown",[`### ${e.title??"Mixed-source analysis"}`,"",`This analysis combines a bounded warehouse extraction with the local dataset \`${r.localDataset}\`.`,"",...(u=r.warehouseRelations)!=null&&u.length?[`- Warehouse sources: ${r.warehouseRelations.map(b=>`\`${b}\``).join(", ")}`]:[],`- Join: \`${r.warehouseKey}\` = \`${r.localKey}\``,"- Trust: local mixed-source analysis · review required"].join(`
1
+ import{u as x,r as w,a as k,m}from"./index-Ck-wqvV2.js";const C="dql:focus-notebook-cell";function h(e){window.setTimeout(()=>{window.dispatchEvent(new CustomEvent(C,{detail:{cellId:e}}))},0)}function S(e){var t,a,c;const i=(t=e.question)==null?void 0:t.trim(),n=(a=e.generatedSql)==null?void 0:a.trim(),s=(c=e.generatedDql)==null?void 0:c.trim();if(!(!i||!n&&!s))return{version:1,source:"agent_run",question:i,...n?{generatedSql:n}:{},...s?{generatedDql:s}:{},...e.sourceRunId?{sourceRunId:e.sourceRunId}:{}}}function g(e){return e.replace(/[^a-zA-Z0-9_ -]+/g," ").replace(/\s+/g,"_").replace(/^_+|_+$/g,"").slice(0,48)||"ai_analysis"}function E(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function I(e,i){var c,o,u,f,l,q;const n=(o=(c=e.dqlArtifact)==null?void 0:c.source)==null?void 0:o.trim(),s=(e.sql??n??"").trim();if(!s&&!n)return[];if(e.mixedSourcePlan){const r=e.mixedSourcePlan,A=m("markdown",[`### ${e.title??"Mixed-source analysis"}`,"",`This analysis combines a bounded warehouse extraction with the local dataset \`${r.localDataset}\`.`,"",...(u=r.warehouseRelations)!=null&&u.length?[`- Warehouse sources: ${r.warehouseRelations.map(b=>`\`${b}\``).join(", ")}`]:[],`- Join: \`${r.warehouseKey}\` = \`${r.localKey}\``,"- Trust: local mixed-source analysis · review required"].join(`
2
2
  `));A.name=g("Analysis context");const d=m("sql",s);return d.name=g(e.title??"Warehouse extraction"),d.mixedSourcePlan=r,d.executionTarget=((f=e.executionTarget)==null?void 0:f.target)==="connection"?e.executionTarget:{target:"connection"},d.datasetRefs=[{id:r.datasetId??r.localDataset,alias:r.localDataset,role:"source"}],[A,d]}const t=m(n?"dql":"sql",n||s);t.name=g(e.title??((l=e.dqlArtifact)==null?void 0:l.name)??"AI analysis"),e.result&&(t.result=e.result,t.status="success",t.executionCount=1),e.chartConfig&&(t.chartConfig=e.chartConfig),e.executionTarget&&(t.executionTarget=e.executionTarget),t.correctionProvenance=S({question:e.question,generatedSql:e.sql??((q=e.dqlArtifact)==null?void 0:q.compiledSql),generatedDql:n,sourceRunId:e.sourceRunId}),e.dqlArtifact&&(t.dqlArtifact={source:e.dqlArtifact.source,sql:e.sql,name:e.dqlArtifact.name,sourcePath:e.dqlArtifact.sourcePath,kind:e.dqlArtifact.kind,metrics:e.dqlArtifact.metrics,dimensions:e.dqlArtifact.dimensions,parameters:e.dqlArtifact.parameters,parameterValues:e.dqlArtifact.parameterValues,persistence:e.dqlArtifact.persistence,trustState:e.dqlArtifact.trustState,compiledSql:e.dqlArtifact.compiledSql??e.sql,...e.question?{question:e.question}:{}},t.dqlParameterValues=e.dqlArtifact.parameterValues);const a=i.filter(r=>new RegExp(`\\b${E(r.alias)}\\b`,"i").test(s)).map(r=>({id:r.id,alias:r.alias,role:r.storageMode==="staged"?"staged":"source",fingerprint:r.fileFingerprint}));return a.length>0&&(t.executionTarget={target:"local"},t.datasetRefs=a,t.dqlArtifact&&(t.dqlArtifact.reviewState="review_required")),[t]}function _(e){return(e??"ai analysis").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"ai-analysis"}function v(){const{state:e,dispatch:i}=x();return w.useCallback(async(n,s)=>{var f;const t=I(n,(s==null?void 0:s.datasets)??[]);if(t.length===0)return;if(e.activeFile&&e.activeFile.type!=="block"){let l=s==null?void 0:s.afterId;for(const q of t)i({type:"ADD_CELL",cell:q,...l?{afterId:l}:{}}),l=q.id;h(t[t.length-1].id);return}const a=n.title??((f=n.dqlArtifact)==null?void 0:f.name)??"AI analysis",c=_(a);let o=`notebooks/${c}.dqlnb`;try{o=(await k.createNotebook(c,"blank")).path}catch{}const u={name:o.split("/").pop()??`${c}.dqlnb`,path:o,type:"notebook",folder:"notebooks",isNew:!0};i({type:"FILE_ADDED",file:u}),i({type:"OPEN_FILE",file:u,cells:t,title:a}),h(t[t.length-1].id)},[i,e.activeFile])}export{C as N,S as c,h as f,v as u};
@@ -1,4 +1,4 @@
1
- import{c as o}from"./index-mQd_pC-P.js";/**
1
+ import{c as o}from"./index-Ck-wqvV2.js";/**
2
2
  * @license lucide-react v0.563.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -1,4 +1,4 @@
1
- import{c as o}from"./index-mQd_pC-P.js";/**
1
+ import{c as o}from"./index-Ck-wqvV2.js";/**
2
2
  * @license lucide-react v0.563.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -1,4 +1,4 @@
1
- import{c as a}from"./index-mQd_pC-P.js";/**
1
+ import{c as a}from"./index-Ck-wqvV2.js";/**
2
2
  * @license lucide-react v0.563.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -1,4 +1,4 @@
1
- import{c}from"./index-mQd_pC-P.js";/**
1
+ import{c}from"./index-Ck-wqvV2.js";/**
2
2
  * @license lucide-react v0.563.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.