@duckcodeailabs/dql-cli 1.13.4 → 1.14.0

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 (92) hide show
  1. package/dist/args.d.ts +2 -0
  2. package/dist/args.d.ts.map +1 -1
  3. package/dist/args.js +5 -0
  4. package/dist/args.js.map +1 -1
  5. package/dist/assets/dql-notebook/assets/{AgentLogPage-DYmHO6_i.js → AgentLogPage-Ch7VK20X.js} +1 -1
  6. package/dist/assets/dql-notebook/assets/{AiBuildDialog-BfhaOd1h.js → AiBuildDialog-DBr5TmyM.js} +1 -1
  7. package/dist/assets/dql-notebook/assets/{AiBuildResult-DLKFAe6R.js → AiBuildResult-jLPzQO7O.js} +1 -1
  8. package/dist/assets/dql-notebook/assets/{AiSidePanel-C6Z3URGr.js → AiSidePanel-CdlGsiVC.js} +1 -1
  9. package/dist/assets/dql-notebook/assets/{AnalyticsHome-uG3xCP_s.js → AnalyticsHome-C0DXbOwY.js} +1 -1
  10. package/dist/assets/dql-notebook/assets/{AppsView-DfieNjkh.js → AppsView-CcpwjApv.js} +4 -4
  11. package/dist/assets/dql-notebook/assets/{BlockStudio-90J_wvWL.js → BlockStudio-CFYxafw-.js} +1 -1
  12. package/dist/assets/dql-notebook/assets/{BusinessArtifactView-_zSMae5q.js → BusinessArtifactView-C0kLYg2p.js} +1 -1
  13. package/dist/assets/dql-notebook/assets/{DbtFirstModelingPage-DoXiPssu.js → DbtFirstModelingPage-CMwElXD_.js} +1 -1
  14. package/dist/assets/dql-notebook/assets/{GitPage-CUfAhS67.js → GitPage-JjhRDeWY.js} +1 -1
  15. package/dist/assets/dql-notebook/assets/{GlobalAiRail-ovtL7nQu.js → GlobalAiRail-DakE4NdR.js} +1 -1
  16. package/dist/assets/dql-notebook/assets/{GovernedContextPage-CaMiKAzA.js → GovernedContextPage-BokDqG6a.js} +1 -1
  17. package/dist/assets/dql-notebook/assets/{HelpDocsPage-CEGUx28b.js → HelpDocsPage-CjOv6_gz.js} +1 -1
  18. package/dist/assets/dql-notebook/assets/{HomePage-2v3SRf8V.js → HomePage-nGaNcwdw.js} +1 -1
  19. package/dist/assets/dql-notebook/assets/{LineageDAG-AaqLEiBN.js → LineageDAG-CO6CFJRg.js} +1 -1
  20. package/dist/assets/dql-notebook/assets/{LineageDetailView-CFc8pm91.js → LineageDetailView-BnGb7OF7.js} +1 -1
  21. package/dist/assets/dql-notebook/assets/{LineageDrawer-DOkFjPq-.js → LineageDrawer-C5Y0Ht0b.js} +1 -1
  22. package/dist/assets/dql-notebook/assets/{LineagePathBreadcrumb-BrDwCuMs.js → LineagePathBreadcrumb-Cgh3GR3F.js} +1 -1
  23. package/dist/assets/dql-notebook/assets/{MiniLineageGraph-CiHtQs3y.js → MiniLineageGraph-Kla9PYuj.js} +1 -1
  24. package/dist/assets/dql-notebook/assets/{NewBlockModal-DAgJZbws.js → NewBlockModal-BR2SnmPT.js} +1 -1
  25. package/dist/assets/dql-notebook/assets/{NewNotebookModal-xjG7nZ3O.js → NewNotebookModal-BaCHMYeB.js} +1 -1
  26. package/dist/assets/dql-notebook/assets/{NotebookEditor-CXZaKfYT.js → NotebookEditor-CBLqY8cE.js} +1 -1
  27. package/dist/assets/dql-notebook/assets/{ReadinessPage-MuJBFwwg.js → ReadinessPage-CiN0IWSS.js} +1 -1
  28. package/dist/assets/dql-notebook/assets/{SetupOnboarding-vKFtKtjh.js → SetupOnboarding-BhiCsYF-.js} +1 -1
  29. package/dist/assets/dql-notebook/assets/{SkillsPage-DCFVOV5f.js → SkillsPage-CCSf8VMm.js} +1 -1
  30. package/dist/assets/dql-notebook/assets/{TrustBadge-TcwXFFHK.js → TrustBadge-BgQmFe_x.js} +1 -1
  31. package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel-Bw5AXNDB.js +88 -0
  32. package/dist/assets/dql-notebook/assets/{answer-to-notebook-DCFWlHB7.js → answer-to-notebook-AeDYUDla.js} +1 -1
  33. package/dist/assets/dql-notebook/assets/{arrow-left-BLnlJAtp.js → arrow-left-C55x2hq_.js} +1 -1
  34. package/dist/assets/dql-notebook/assets/{arrow-right-BmUAb1aW.js → arrow-right-C1cJrhOm.js} +1 -1
  35. package/dist/assets/dql-notebook/assets/{book-open-text-bdSChSag.js → book-open-text-CQf_sdv2.js} +1 -1
  36. package/dist/assets/dql-notebook/assets/{circle-x-Cc6dEaf4.js → circle-x-X8-Z2yLY.js} +1 -1
  37. package/dist/assets/dql-notebook/assets/{dagre.esm-CPebQKQ9.js → dagre.esm-BjjNYKyY.js} +1 -1
  38. package/dist/assets/dql-notebook/assets/{external-link-rmXvubf3.js → external-link-C2zrz5DH.js} +1 -1
  39. package/dist/assets/dql-notebook/assets/{grip-vertical-Sg4zd5-Q.js → grip-vertical-qGV_PYGU.js} +1 -1
  40. package/dist/assets/dql-notebook/assets/{index-mQd_pC-P.js → index-ByTDPDaH.js} +127 -127
  41. package/dist/assets/dql-notebook/assets/{link-2-BLaPoFxW.js → link-2-VpyOxQXG.js} +1 -1
  42. package/dist/assets/dql-notebook/assets/{list-tree-j0s4asFK.js → list-tree-CH2Jhwms.js} +1 -1
  43. package/dist/assets/dql-notebook/assets/{minimize-2-Cl4pef4s.js → minimize-2-B2TZJ8BT.js} +1 -1
  44. package/dist/assets/dql-notebook/assets/{panel-right-open-Clz-FtWi.js → panel-right-open-BunF88lt.js} +1 -1
  45. package/dist/assets/dql-notebook/assets/{play-DFdazMg7.js → play-DAFVF4_G.js} +1 -1
  46. package/dist/assets/dql-notebook/assets/{rotate-ccw-C3tTaR7s.js → rotate-ccw-DGCrrqtY.js} +1 -1
  47. package/dist/assets/dql-notebook/assets/{semantic-fields-DIAhTlfy.js → semantic-fields-Ci-9QL9F.js} +1 -1
  48. package/dist/assets/dql-notebook/assets/{sliders-horizontal-BUiu2tfY.js → sliders-horizontal-BOAlXXbn.js} +1 -1
  49. package/dist/assets/dql-notebook/assets/{star--Yq77aH4.js → star-CkksZXHt.js} +1 -1
  50. package/dist/assets/dql-notebook/assets/{triangle-alert-D5Ng-xZO.js → triangle-alert-D3mjyJZE.js} +1 -1
  51. package/dist/assets/dql-notebook/assets/{upload-L8BKQAxP.js → upload-CTNOAVEO.js} +1 -1
  52. package/dist/assets/dql-notebook/assets/{usePersistedAgentThreadId-DBu97YaM.js → usePersistedAgentThreadId-DiQjc7x-.js} +4 -4
  53. package/dist/assets/dql-notebook/assets/{user-round-BK5N1cJW.js → user-round-BWd5tQRg.js} +1 -1
  54. package/dist/assets/dql-notebook/assets/{wand-sparkles-D8XDQD9z.js → wand-sparkles-CqsAv8P-.js} +1 -1
  55. package/dist/assets/dql-notebook/assets/{workflow-Bl9zwG0q.js → workflow-CSqsj-sC.js} +1 -1
  56. package/dist/assets/dql-notebook/assets/{wrench-C-zLCMbW.js → wrench-DWqzqlX8.js} +1 -1
  57. package/dist/assets/dql-notebook/assets/{x-stiJ-sP7.js → x-65M5rLCE.js} +1 -1
  58. package/dist/assets/dql-notebook/index.html +1 -1
  59. package/dist/commands/eval.d.ts +15 -1
  60. package/dist/commands/eval.d.ts.map +1 -1
  61. package/dist/commands/eval.js +32 -3
  62. package/dist/commands/eval.js.map +1 -1
  63. package/dist/index.js +1 -1
  64. package/dist/llm/answer-loop-tools.d.ts +3 -1
  65. package/dist/llm/answer-loop-tools.d.ts.map +1 -1
  66. package/dist/llm/answer-loop-tools.js +31 -23
  67. package/dist/llm/answer-loop-tools.js.map +1 -1
  68. package/dist/llm/providers/dql-agent-provider.d.ts +3 -1
  69. package/dist/llm/providers/dql-agent-provider.d.ts.map +1 -1
  70. package/dist/llm/providers/dql-agent-provider.js +315 -22
  71. package/dist/llm/providers/dql-agent-provider.js.map +1 -1
  72. package/dist/llm/types.d.ts +29 -2
  73. package/dist/llm/types.d.ts.map +1 -1
  74. package/dist/local-runtime.d.ts +200 -5
  75. package/dist/local-runtime.d.ts.map +1 -1
  76. package/dist/local-runtime.js +2280 -457
  77. package/dist/local-runtime.js.map +1 -1
  78. package/dist/package.json +10 -10
  79. package/dist/providers/oauth/claude-oauth.d.ts +1 -1
  80. package/dist/providers/oauth/claude-oauth.d.ts.map +1 -1
  81. package/dist/providers/oauth/claude-oauth.js +18 -11
  82. package/dist/providers/oauth/claude-oauth.js.map +1 -1
  83. package/dist/providers/oauth/codex-oauth.d.ts +1 -1
  84. package/dist/providers/oauth/codex-oauth.d.ts.map +1 -1
  85. package/dist/providers/oauth/codex-oauth.js +9 -1
  86. package/dist/providers/oauth/codex-oauth.js.map +1 -1
  87. package/dist/providers/subscription-cli.d.ts +1 -1
  88. package/dist/providers/subscription-cli.d.ts.map +1 -1
  89. package/dist/providers/subscription-cli.js +33 -4
  90. package/dist/providers/subscription-cli.js.map +1 -1
  91. package/package.json +10 -10
  92. package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel-Cu-YgIe4.js +0 -88
@@ -0,0 +1,88 @@
1
+ import{c as Ie,r as h,a as ie,j as t,d as Dt,g as dt,l as be,b7 as li,f as ut,L as Ve,aK as ci,ba as pr,B as ht,e as fr,u as Nt,t as gr,a5 as di,bb as Ge,E as ui,H as pi,bc as fi,w as gi,S as Ue,aH as hr,b as Pt,b9 as Ze,P as ot,D as hi,G as xr,bd as xi,be as yi,b0 as sn,a0 as Kt,ar as mi}from"./index-ByTDPDaH.js";import{S as _t,P as bi,F as pt,E as vi,M as ji,R as gn,d as hn,e as Si,A as wi,g as ki,u as Ai}from"./usePersistedAgentThreadId-DiQjc7x-.js";import{C as Ci}from"./AiBuildResult-jLPzQO7O.js";import{T as Yt}from"./triangle-alert-D3mjyJZE.js";import{U as Ri}from"./user-round-BWd5tQRg.js";import{X as Tt}from"./x-65M5rLCE.js";import{L as ft}from"./list-tree-CH2Jhwms.js";import{W as Ft}from"./wrench-DWqzqlX8.js";import{M as qi}from"./minimize-2-B2TZJ8BT.js";import{A as Ii}from"./arrow-right-C1cJrhOm.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 zi=[["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",zi);/**
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 Ti=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],yr=Ie("chevron-up",Ti);/**
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 Ei=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Mi=Ie("circle",Ei);/**
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 Bi=[["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",Bi);/**
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 $i=[["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"}]],Et=Ie("lightbulb",$i);/**
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 Li=[["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"}]],at=Ie("route",Li);/**
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 Di=[["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",Di);/**
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 Ni=[["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"}]],Pi=Ie("send",Ni);/**
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 Fi=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Dn=Ie("square",Fi);/**
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 Wi=[["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"}]],Oi=Ie("zap",Wi),Xt=[{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]=h.useState(null),[o,a]=h.useState(!1),c=h.useRef(null);h.useEffect(()=>{let g=!1;return ie.getProviderSettings().then(({providers:l})=>{g||s(l.find(u=>u.active)??null)}).catch(()=>{}),()=>{g=!0}},[]),h.useEffect(()=>{if(!o)return;const g=l=>{c.current&&!c.current.contains(l.target)&&a(!1)};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[o]);const d=Xt.find(g=>g.mode===n)??Xt[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(Mi,{size:7,fill:e.success,color:e.success}),t.jsx("span",{style:{color:e.textSecondary},children:p})]}):null,t.jsxs("div",{ref:c,style:{position:"relative"},children:[t.jsxs("button",{type:"button",onClick:()=>a(g=>!g),title:"How hard the model thinks for this thread",style:{...Pn(e),cursor:"pointer"},children:[t.jsx(Oi,{size:12,color:e.textMuted}),t.jsxs("span",{style:{color:e.textSecondary},children:["Thinking: ",d.label]}),t.jsx(Dt,{size:12,color:e.textMuted})]}),o?t.jsx("div",{role:"menu",style:Hi(e),children:Xt.map(g=>{const l=g.mode===n;return t.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":l,onClick:()=>{r(g.mode),a(!1)},style:Qi(e,l),children:[t.jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontWeight:l?600:500,color:e.textPrimary},children:g.label}),l?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 Hi(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 Qi(e,n){return{display:"block",width:"100%",textAlign:"left",padding:"8px 10px",borderRadius:7,border:"none",background:n?e.pillBg:"transparent",cursor:"pointer"}}const Vi={draft:"#8b949e",review:"#d29922",certified:"#3fb950",deprecated:"#f85149",pending_recertification:"#db6d28"},Ui={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"},Ki={draft:pr,queued:ci,generating:Ve,running:Ve,saving:Ve,ready:ut,saved:ut,blocked:Yt,needs_attention:Yt,review:li,certified:be,deprecated:_i,pending_recertification:Yt},Yi=new Set(["generating","running","saving"]);function Xi(e){return Vi[e]??Ui[e]??"#8b949e"}function Ji(e){return Gi[e]??e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g," ")}function Zi({status:e,t:n,label:r}){const i=Xi(e),s=Ki[e]??pr,o=r??Ji(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:Yi.has(e)?"spin":void 0}),o]})}function es(e){const{t:n,name:r,status:i="draft",description:s,dql:o,sqlPreview:a,grain:c,outputs:d=[],dimensions:p=[],entities:g=[],examples:l=[],sourceTables:u=[],evidence:f=[],certifierVerdict:x,owner:m,actions:b}=e,[k,O]=h.useState(!1),[L,P]=h.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(ht,{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(Zi,{status:i,t:n}),c?t.jsxs("span",{style:on(n),children:["grain ",c]}):null]}),s?t.jsx("div",{style:{fontSize:12,color:n.textSecondary,lineHeight:1.5},children:s}):null,o?t.jsx(Fn,{open:k,onToggle:()=>O(q=>!q),label:"Governed DQL",t:n,lead:!0,children:t.jsx("pre",{style:Wn(n),children:o})}):null,a?t.jsx(Fn,{open:L,onToggle:()=>P(q=>!q),label:o?"Compiled SQL preview":"SQL this block will run",t:n,children:t.jsx("pre",{style:Wn(n),children:a})}):null,t.jsx(Jt,{label:"Outputs",items:d,t:n}),t.jsx(Jt,{label:"Dimensions",items:p,t:n}),t.jsx(Jt,{label:"Entities",items:g,t:n}),l.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:l.slice(0,3).map(q=>t.jsx("li",{style:{fontSize:11.5,color:n.textSecondary,lineHeight:1.45},children:q},q))})]}):null,u.length>0||f.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(be,{size:12,color:n.accent})," Grounded on"]}),u.length>0?t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:u.map(q=>t.jsx("span",{style:on(n),children:q},q))}):null,f.slice(0,5).map((q,D)=>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:q.name}),t.jsxs("div",{style:{fontSize:10,color:n.textMuted,marginTop:3},children:[q.kind,q.reason?` · ${q.reason}`:""]}),q.description?t.jsx("div",{style:{fontSize:11,color:n.textMuted,lineHeight:1.35,marginTop:5},children:q.description}):null]},`${q.objectKey??q.name}-${D}`))]}):null,t.jsx(Ci,{t:n,verdict:x}),m?t.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11,color:n.textMuted},children:[t.jsx(Ri,{size:12,strokeWidth:2})," drafting as ",m]}):null,b?t.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:b}):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(Dt,{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 Jt({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 Zt(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ts(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:a,initialDomain:c,initialOwner:d}){var G;const{state:p,dispatch:g}=Nt(),l=gr[p.themeMode],u=h.useRef(null),[f,x]=h.useState(s||e.name||"new_block"),[m,b]=h.useState(c??""),[k,O]=h.useState(d??""),[L,P]=h.useState(o??p.notebookMetadata.description??""),[q,D]=h.useState((a??p.notebookMetadata.categories??[]).join(", ")),[U,N]=h.useState(i??e.content),[E,J]=h.useState(""),[Z,C]=h.useState(""),[_,z]=h.useState([]),[j,K]=h.useState(!1),[Y,te]=h.useState(null),B=h.useMemo(()=>ts(U),[U]),H=h.useMemo(()=>q.split(",").map(S=>S.trim()).filter(Boolean),[q]),ne=[{id:"has-name",label:"Block has name",severity:"error",passed:!!f.trim()},{id:"has-owner",label:"Block has owner",severity:"error",passed:!!k.trim()},{id:"has-description",label:"Description",severity:"warning",passed:!!L.trim()},{id:"has-domain",label:"Domain",severity:"warning",passed:!!m.trim()},{id:"has-tags",label:"Has at least one tag",severity:"warning",passed:H.length>0},{id:"has-llm-context",label:"Has LLM context (for agents)",severity:"warning",passed:!!E.trim()}],Q=ne.some(S=>S.severity==="error"&&!S.passed);h.useEffect(()=>{var S;(S=u.current)==null||S.focus()},[]),h.useEffect(()=>{const S=$=>{$.key==="Escape"&&n()};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[n]);const de=di(m,p.authoredDomains),he=`${m.trim()?`blocks/${Zt(m)}/`:"blocks/"}${Zt(f)||"new-block"}.dql`,X=async()=>{var S,$,oe;if(Q){te("Enter the block name and owner before saving.");return}if(!U.trim()){te("Block content is required.");return}K(!0),te(null);try{const R=Z.split(`
52
+ `).map(ge=>ge.trim()).filter(Boolean),re=_.map(ge=>({question:ge.question.trim(),sql:ge.sql.trim()||void 0})).filter(ge=>ge.question),fe=await ie.saveAsBlock({cellId:e.id,notebookPath:((S=p.activeFile)==null?void 0:S.path)??null,name:f.trim(),domain:m.trim()||void 0,owner:k.trim()||void 0,content:U,description:L.trim()||void 0,tags:H,metricRefs:B,llmContext:E.trim()||void 0,examples:re.length>0?re:void 0,invariants:R.length>0?R:void 0,reviewRequired:!!(($=e.datasetRefs)!=null&&$.length),datasetRefs:e.datasetRefs,lineage:(oe=e.dqlArtifact)==null?void 0:oe.lineage}),We={name:`${Zt(f)||"new-block"}.dql`,path:fe.path,type:"block",folder:"blocks"};p.files.some(ge=>ge.path===fe.path)||g({type:"FILE_ADDED",file:We});const $e=await ie.openBlockStudio(fe.path);g({type:"OPEN_BLOCK_STUDIO",file:We,payload:$e}),r==null||r({...fe,name:f.trim()}),n()}catch(R){te(R instanceof Error?R.message:String(R))}finally{K(!1)}},w={width:"100%",background:l.inputBg,border:`1px solid ${Y?l.error:l.inputBorder}`,borderRadius:6,color:l.textPrimary,fontSize:13,fontFamily:l.font,padding:"8px 12px",outline:"none",boxSizing:"border-box"};return t.jsx("div",{onClick:S=>{S.target===S.currentTarget&&n()},style:{position:"fixed",inset:0,background:l.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:l.modalBg,border:`1px solid ${l.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:l.textPrimary,fontFamily:l.font},children:"Save as Block"}),t.jsx("button",{onClick:n,style:{background:"transparent",border:"none",color:l.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:l.textSecondary,fontFamily:l.font},children:["Block Name ",t.jsx(On,{})]}),t.jsx("input",{ref:u,value:f,onChange:S=>x(S.target.value),style:w})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("label",{style:{fontSize:12,color:l.textSecondary,fontFamily:l.font},children:"Domain"}),t.jsxs("select",{value:m,onChange:S=>b(S.target.value),style:w,children:[t.jsx("option",{value:"",children:"Global / cross-domain"}),de.map(S=>t.jsx("option",{value:S.value,disabled:S.disabled,children:S.label},S.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:l.textSecondary,fontFamily:l.font},children:["Owner ",t.jsx(On,{})]}),t.jsx("input",{value:k,onChange:S=>O(S.target.value),style:w,placeholder:"data-platform@company.com"})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("label",{style:{fontSize:12,color:l.textSecondary,fontFamily:l.font},children:"Tags"}),t.jsx("input",{value:q,onChange:S=>D(S.target.value),style:w,placeholder:"revenue, dashboard"})]})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("label",{style:{fontSize:12,color:l.textSecondary,fontFamily:l.font},children:"Description"}),t.jsx("input",{value:L,onChange:S=>P(S.target.value),style:w})]}),t.jsxs("details",{style:{border:`1px solid ${l.cellBorder}`,borderRadius:6,padding:"8px 12px"},children:[t.jsx("summary",{style:{fontSize:12,fontWeight:600,color:l.textSecondary,fontFamily:l.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:l.textSecondary,fontFamily:l.font},children:"How should an AI describe this block?"}),t.jsx("textarea",{value:E,onChange:S=>J(S.target.value),rows:3,placeholder:'One paragraph. E.g. "Monthly revenue recognized from closed-won deals, grouped by billing month. Excludes refunds."',style:{...w,fontFamily:l.font,lineHeight:1.5,resize:"vertical"}})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("label",{style:{fontSize:12,color:l.textSecondary,fontFamily:l.font},children:"Invariants (one per line)"}),t.jsx("textarea",{value:Z,onChange:S=>C(S.target.value),rows:2,placeholder:`Revenue is never negative
53
+ Each row is a unique month`,style:{...w,fontFamily:l.fontMono,lineHeight:1.5,resize:"vertical"}})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("label",{style:{fontSize:12,color:l.textSecondary,fontFamily:l.font},children:"Example questions (grounding for chat cells)"}),_.map((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:S.question,onChange:oe=>{const R=[..._];R[$]={...R[$],question:oe.target.value},z(R)},placeholder:"What was revenue last month?",style:w}),t.jsx("input",{value:S.sql,onChange:oe=>{const R=[..._];R[$]={...R[$],sql:oe.target.value},z(R)},placeholder:"Optional SQL snippet",style:{...w,fontFamily:l.fontMono,fontSize:12}})]}),t.jsx("button",{type:"button",onClick:()=>z(_.filter((oe,R)=>R!==$)),style:{background:"transparent",border:`1px solid ${l.cellBorder}`,borderRadius:6,color:l.textMuted,cursor:"pointer",fontSize:12,padding:"0 10px"},children:"×"})]},$)),t.jsx("button",{type:"button",onClick:()=>z([..._,{question:"",sql:""}]),style:{alignSelf:"flex-start",background:l.btnBg,border:`1px solid ${l.btnBorder}`,borderRadius:6,color:l.textSecondary,cursor:"pointer",fontSize:12,fontFamily:l.font,padding:"4px 10px"},children:"+ Add example"})]})]})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,padding:"10px 12px",background:l.pillBg,borderRadius:6,border:`1px solid ${l.cellBorder}`},children:[t.jsx("div",{style:{fontSize:11,fontWeight:700,color:l.textSecondary,fontFamily:l.font,letterSpacing:"0.06em",textTransform:"uppercase"},children:"Governance checks"}),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:ne.map(S=>{const $=S.passed?"#3fb950":S.severity==="error"?"#ff7b72":"#e3b341",oe=S.passed?"✓":S.severity==="error"?"✕":"!";return t.jsxs("span",{title:S.passed?`${S.label} — passed`:`${S.label} — ${S.severity}`,style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11,fontFamily:l.font,color:$,background:`${$}18`,border:`1px solid ${$}55`,borderRadius:999,padding:"2px 10px"},children:[t.jsx("span",{style:{fontWeight:700},children:oe}),S.label]},S.id)})})]}),t.jsx("div",{style:{fontSize:12,color:l.textMuted,fontFamily:l.fontMono,padding:"8px 12px",background:l.pillBg,borderRadius:6},children:he}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("label",{style:{fontSize:12,color:l.textSecondary,fontFamily:l.font},children:"Content Preview"}),t.jsx("textarea",{value:U,onChange:S=>N(S.target.value),style:{...w,minHeight:220,resize:"vertical",fontFamily:l.fontMono,lineHeight:1.5}})]}),B.length>0&&t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,padding:"10px 12px",background:l.pillBg,borderRadius:6},children:[t.jsx("span",{style:{fontSize:11,color:l.textMuted,fontFamily:l.font},children:"Detected semantic refs:"}),B.map(S=>t.jsx("span",{style:{fontSize:11,color:l.accent,fontFamily:l.fontMono,background:`${l.accent}18`,borderRadius:999,padding:"2px 8px"},children:S},S))]}),Y&&t.jsx("div",{style:{fontSize:12,color:l.error,fontFamily:l.font},children:Y})]}),t.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${l.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[t.jsx("span",{style:{fontSize:11.5,color:l.textMuted,marginRight:"auto",alignSelf:"center"},children:(G=e.datasetRefs)!=null&&G.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:l.btnBg,border:`1px solid ${l.btnBorder}`,borderRadius:6,color:l.textSecondary,cursor:"pointer",fontSize:13,fontFamily:l.font,padding:"7px 16px"},children:"Cancel"}),t.jsx("button",{onClick:X,disabled:j||Q,title:Q?"Fix governance errors to enable Save":void 0,style:{background:l.accent,border:`1px solid ${l.accent}`,borderRadius:6,color:"#fff",cursor:j||Q?"not-allowed":"pointer",fontSize:13,fontFamily:l.font,padding:"7px 20px",opacity:j||Q?.5:1},children:j?"Saving & checking…":"Save block"})]})]})})}function vr(e){return e.policy==="dynamic"||e.policy==="optional"}function ns({parameters:e,values:n,onChange:r,onReset:i,t:s,includeNonRuntime:o=!1,card:a=!1}){const c=e.filter(d=>o||vr(d));return c.length===0?null:t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:8},children:c.map(d=>{const p=Object.prototype.hasOwnProperty.call(n,d.name),g=p?n[d.name]:d.default,l=f=>r(d.name,f),u=d.type==="boolean"?t.jsxs("select",{"aria-label":d.name,value:String(g??""),onChange:f=>l(f.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":d.name,type:d.type==="number"?"number":d.type==="date"?"date":"text",value:Array.isArray(g)?g.join(", "):g==null?"":String(g),placeholder:d.type.endsWith("[]")?"Comma-separated values":d.required?"Required value":"Use default",onChange:f=>l(f.target.value),style:Qn(s)});return t.jsxs("label",{style:{display:"grid",gap:4,minWidth:0,...a?{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:[rs(d.name),d.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:[d.type,o?` · ${d.policy}`:""]}),p&&i?t.jsx("button",{type:"button",onClick:()=>i(d.name),style:{marginLeft:"auto",border:0,padding:0,background:"transparent",color:s.accent,fontSize:9.5,cursor:"pointer"},children:"Reset"}):null]})]},d.name)})})}function rs(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 is(e){const n=e.filter(o=>o.kind==="run").map(ss).filter(o=>!!o).slice(-6);if(n.length===0)return;const r=[...n].reverse().find(o=>{var a;return(a=o.result)==null?void 0:a.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:us(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??Sr(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 ss(e){var l,u,f,x;const n=e.run.artifacts.find(m=>m.kind==="answer")??e.run.artifacts.find(m=>m.kind==="research_run")??e.run.artifacts[0],r=pe(n==null?void 0:n.payload),i=os(r),s=fs(i),o=Array.isArray(i==null?void 0:i.rows)?i.rows.filter(m=>!!(m&&typeof m=="object"&&!Array.isArray(m))).slice(0,24):[],a=((l=pe(r==null?void 0:r.contextPack))==null?void 0:l.questionPlan)??(r==null?void 0:r.analysisPlan),c=jr(a),d=hs(s,o),p=ps(c,s),g=ae(r==null?void 0:r.sourceCertifiedBlock)??((n==null?void 0:n.kind)==="answer"?ae(n.ref):void 0)??ae((u=pe(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:ae((f=pe(r==null?void 0:r.route))==null?void 0:f.label)??ae((x=pe(r==null?void 0:r.route))==null?void 0:x.tier),trustLabel:ae(r==null?void 0:r.trustLabel),reviewStatus:ae(r==null?void 0:r.reviewStatus),certification:ae(r==null?void 0:r.certification),contextPackId:ae(r==null?void 0:r.contextPackId),requestedFilters:Xe(c==null?void 0:c.filters),requestedDimensions:Xe(c==null?void 0:c.dimensions),requestedMeasures:Xe(c==null?void 0:c.measures),answerContract:a,dqlArtifact:cs(r),cascade:ds(r),topN:Sr(c),result:s.length>0||o.length>0?an({columns:s,rowsSample:o,dimensionValues:d,measureColumns:p,rowCount:as(i)}):void 0,sourceSql:ls(r,i)})}function Vn(e){return e.answerContract}function jr(e){const n=pe(e);return pe(n==null?void 0:n.requestedShape)}function os(e){const n=pe(e==null?void 0:e.researchRun),r=pe(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(pe).filter(s=>!!(s&&(Array.isArray(s.rows)||Array.isArray(s.columns)))).sort((s,o)=>Un(o)-Un(s))[0]}function Un(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 as(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 ls(e,n){var r,i;return ae(e==null?void 0:e.proposedSql)??ae(e==null?void 0:e.sql)??ae(n==null?void 0:n.sql)??ae((r=pe(e==null?void 0:e.query))==null?void 0:r.sql)??ae((i=pe(e==null?void 0:e.plan))==null?void 0:i.sql)}function cs(e){var r,i;const n=Ge(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=pe(e==null?void 0:e.cascade);if(!n)return;const r=ae(n.terminalLane),i=ae(n.routeTier);if(!(!r&&!i))return{terminalLane:r,routeTier:i,label:ae(n.label),ref:ae(n.ref),artifactKind:ae(n.artifactKind),refusalCode:ae(n.refusalCode),outcome:pe(n.outcome)}}function us(e){const n=e.slice(-3).map(r=>{var o,a;const i=(o=r.result)==null?void 0:o.columns.slice(0,5).join(", "),s=(a=r.result)!=null&&a.dimensionValues?Object.entries(r.result.dimensionValues).slice(0,3).map(([c,d])=>`${c}: ${d.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 Sr(e){const n=pe(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 ps(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 pe(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function fs(e){const r=(Array.isArray(e==null?void 0:e.columns)?e.columns:[]).map(gs).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 gs(e){if(typeof e=="string"&&e.trim())return e.trim();if(e&&typeof e=="object"){const n=e;return ae(n.name)??ae(n.field)??ae(n.key)}}function hs(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 a of n){const c=pe(a),d=c==null?void 0:c[s],p=typeof d=="string"||typeof d=="number"?String(d).trim():"";if(!(!p||o.includes(p))&&(o.push(p),o.length>=24))break}o.length>0&&(i[xs(s)]=o)}return Object.keys(i).length>0?i:void 0}function xs(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 ae(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 ys(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 wr(e,n){if(e.kind==="sql_block"){const s=new Map(n.columns.map(o=>[o.toLowerCase(),o]));return(e.filterableColumns??[]).flatMap(o=>{const a=s.get(o.column.toLowerCase());return a?[{column:a,field:o.predicateTarget,values:Gn(n.rows.map(c=>c[a]))}]:[]})}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,a=r.get(s.toLowerCase())??r.get(o.toLowerCase())??r.get(s.split(".").join("_").toLowerCase());if(!a)return[];const c=Gn(n.rows.map(d=>d[a]));return[{column:a,field:s,values:c}]})}function ms(e,n,r,i){const s=wr(e,n).find(b=>b.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(b=>b.name)),a=bs(s.field.split(".").at(-1)??s.column);let c=a,d=2;for(;o.has(c);)c=`${a}_${d++}`;const p=Array.isArray(i)?i.map(String).join(", "):String(i),g=ui(p,c);let l=pi(e.source,{name:c,type:g,required:!1,defaultText:p,policy:"dynamic"});l=fi(l,c,s.field);const u=gi(l).map(b=>{var k,O,L;return{...b,...((k=b.binding)==null?void 0:k.kind)==="semantic_filter"&&b.binding.field?{binding:{kind:"semantic_filter",field:b.binding.field,operator:b.binding.operator??"equals"}}:((O=b.binding)==null?void 0:O.kind)==="limit"?{binding:{kind:"limit"}}:((L=b.binding)==null?void 0:L.kind)==="sql_value"?{binding:{kind:"sql_value"}}:{binding:void 0}}}),{executionReceipt:f,compiledSql:x,...m}=e;return{artifact:{...m,source:l,parameters:u,parameterValues:{...e.parameterValues??{},[c]:i}},parameterName:c}}function Gn(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 bs(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"||o.run.status==="cancelled"||o.run.stopReason==="cancelled"||((r=o.run.artifacts)==null?void 0:r.some(c=>{const d=se(c);return!!(d.executionError||d.warehouseFailure||d.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",cancelled:"Stopped by user",blocked:"Blocked"};function vs({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:a,notebookPath:c,selectedObject:d,workspaceContext:p,initialMode:g="auto",initialInput:l="",initialItems:u,onItemsChange:f,threadId:x,onThreadIdChange:m,audience:b="analyst",autoRun:k,onInsertSql:O,onInsertDql:L,onReplaceDql:P,onArtifactReady:q,onReviewAuthoringProposal:D,onOpenBlock:U,onOpenResearch:N,onOpenApp:E,onRunningChange:J,answerFirstCards:Z=!1,insertDqlActionLabel:C,replaceDqlActionLabel:_,askLayout:z=!1}){const j=gr[e],K=h.useRef(void 0),[Y,te]=h.useState(l),[B,H]=h.useState(u??[]),[ne,Q]=h.useState([]),[de,he]=h.useState(""),[X,w]=h.useState(!1),[G,S]=h.useState(null),[$,oe]=h.useState(null),[R,re]=h.useState(null),[fe,We]=h.useState(()=>js()),[$e,ge]=h.useState(!1),[A,le]=h.useState([]),[Te,Qt]=h.useState(),kn=h.useCallback(y=>{We(y);try{window.localStorage.setItem(Rr,y)}catch{}},[]),tt=h.useRef(null),An=h.useRef(l),Cn=h.useRef(null),Ke=h.useRef(null),we=h.useRef(null),Oe=h.useRef(null),xe=h.useRef(null),Le=h.useRef(0),mt=h.useRef(""),De=h.useRef(null),nt=h.useCallback(()=>{mt.current="",De.current!==null&&(window.cancelAnimationFrame(De.current),De.current=null),he("")},[]),ei=h.useCallback(y=>{mt.current+=y,De.current===null&&(De.current=window.requestAnimationFrame(()=>{De.current=null;const v=mt.current;mt.current="",v&&he(T=>T+v)}))},[]);h.useEffect(()=>()=>{De.current!==null&&window.cancelAnimationFrame(De.current)},[]);const Re=p==null?void 0:p.executionTarget,Rn=Re&&typeof Re=="object"&&!Array.isArray(Re)&&Re.target==="connection"&&typeof Re.connectionName=="string"?String(Re.connectionName):void 0,ti=Re&&typeof Re=="object"&&!Array.isArray(Re)&&Re.target==="local";h.useEffect(()=>{let y=!1;return ie.getConnections().then(v=>{if(y)return;const T=Object.keys(v.connections??{}).sort((F,W)=>F.localeCompare(W));le(T),Qt(qr(T,v.default,Rn))}).catch(()=>{y||(le([]),Qt(void 0))}),()=>{y=!0}},[Rn]);const qn=h.useCallback(y=>{Qt(y)},[]),[Ne,bt]=h.useState(null),[Ee,Ye]=h.useState(null),[ni,Vt]=h.useState(""),In=h.useRef(null),vt=h.useRef(null);h.useEffect(()=>{!l||X||l!==An.current&&(An.current=l,te(l))},[l,X]);const ri=h.useMemo(()=>Ar(B),[B]),jt=h.useRef(f);jt.current=f;const He=h.useRef(q);He.current=q,h.useEffect(()=>{var y;(y=jt.current)==null||y.call(jt,B)},[B]);const ye=h.useRef(x),St=h.useRef(m);St.current=m;const Ut=h.useCallback((y,v)=>{var T;if(xe.current!==null&&(window.clearTimeout(xe.current),xe.current=null),en(y.id),we.current===y.id&&(we.current=null),Oe.current=null,S(null),Q(y.events.slice(-8)),nt(),H(F=>{if(F.some(V=>V.kind==="run"&&V.run.id===y.id))return F.map(V=>V.kind==="run"&&V.run.id===y.id?{...V,id:y.id,run:y}:V);const W=F.some(V=>V.kind==="user"&&V.text===v.question);return[...F,...W?[]:[{kind:"user",id:`${y.id}-question`,text:v.question}],{kind:"run",id:y.id,run:y}]}),y.route!=="certified_answer"){const F=Bt(y);F&&((T=He.current)==null||T.call(He,F,y))}},[nt]),zn=h.useCallback((y,v)=>{var F;H(W=>kr(W,y,v)),bt(W=>{if(!W||W.runId!==y)return W;const V=v.artifacts[0];return V?{runId:v.id,artifactId:V.id,tab:W.tab}:null}),re(null);const T=Bt(v);T&&((F=He.current)==null||F.call(He,T,v))},[]),rt=h.useCallback(y=>{xe.current!==null&&window.clearTimeout(xe.current);const v=++Le.current;we.current=y.id,Oe.current=y,S(y),w(!0),nt(),Q([]);const T=async()=>{if(!(v!==Le.current||we.current!==y.id))try{const F=await ie.getAgentRunState(y.id);if(v!==Le.current||we.current!==y.id)return;if(F.lifecycleState==="terminal"){Ut(F.run,y),w(!1);return}Q(F.progress.events.slice(-8)),xe.current=window.setTimeout(()=>{T()},600)}catch{if(v!==Le.current||we.current!==y.id)return;xe.current=window.setTimeout(()=>{T()},1200)}};return T(),()=>{v===Le.current&&(Le.current+=1),xe.current!==null&&(window.clearTimeout(xe.current),xe.current=null)}},[Ut]),_n=h.useRef(!1);h.useEffect(()=>{if(!x||_n.current)return;_n.current=!0,ye.current??(ye.current=x);let y=!1;return ie.getAgentThread(x).then(({turns:v,runs:T})=>{y||v.length===0||H(F=>{const W=F.filter(ce=>ce.kind==="run").length,V=Ir(v,T);if(v.length>=W)return V;const ue=new Map(V.flatMap(ce=>ce.kind==="run"?[[ce.run.id,ce.run]]:[]));return F.map(ce=>ce.kind==="run"&&ue.has(ce.run.id)?{...ce,run:ue.get(ce.run.id)}:ce)})}).catch(()=>{!y&&ye.current===x&&(ye.current=void 0)}),()=>{y=!0}},[x]),h.useEffect(()=>{const y=Jn(x??ye.current);if(!(!y||Ke.current))return rt(y)},[rt,x]),h.useEffect(()=>{const y=()=>{if(document.visibilityState!=="visible"||Ke.current)return;const v=Oe.current??Jn(x??ye.current);v&&rt(v)};return document.addEventListener("visibilitychange",y),()=>document.removeEventListener("visibilitychange",y)},[rt,x]);const Me=async(y,v,T,F,W)=>{var Mn,Bn,$n;const V=(y??Y).trim();if(!V||X)return;const ue=v??K.current??g,ce=ue==="research"&&$e;ge(!1),K.current=void 0;const Rt={kind:"user",id:sr("user"),text:V};H(je=>[...je,Rt]),te(""),re(null),w(!0),Q([]),nt();const Be=new AbortController;Ke.current=Be;const Qe=sr("run");let ve={id:Qe,question:V,threadId:ye.current,startedAt:new Date().toISOString()};we.current=Qe,Oe.current=ve,S(ve),Xn(ve);let ke=!1,En=!1;try{if(!ye.current)try{const me=await ie.createAgentThread({surface:z?"ask":typeof(p==null?void 0:p.surface)=="string"?p.surface:c?"notebook":"agent",title:V,...c?{notebookPath:c}:{}});ye.current=me.id,(Mn=St.current)==null||Mn.call(St,me.id),ve={...ve,threadId:me.id},Oe.current=ve,S(ve),Xn(ve)}catch{}const je=ue==="modeling"||ue==="skill"?(Bn=[...B].reverse().find(me=>me.kind==="run"&&me.run.artifacts.some(Gt=>Gt.kind===(ue==="modeling"?"modeling_change_proposal":"skill_change_proposal"))))==null?void 0:Bn.run:void 0,Ln=je==null?void 0:je.artifacts.find(me=>me.kind===(ue==="modeling"?"modeling_change_proposal":"skill_change_proposal")),oi={question:V,...T?{selectedEvidenceId:T}:{},...F?{clarificationSourceQuestion:F}:{},requestedMode:ue,audience:b,selectedObject:d??(c?{kind:"notebook",path:c}:void 0),...W!=null&&W.executionTarget?{executionTarget:W.executionTarget}:ti?{executionTarget:{target:"local"}}:Te?{executionTarget:{target:"connection",connectionName:Te}}:{},workspaceContext:{...p??{},...c?{notebookPath:c}:{},...W?{researchSource:Nr(W)}:{},...je&&Ln?{sourceRunId:je.id,sourceArtifactId:Ln.id,revision:((($n=je.derivation)==null?void 0:$n.revision)??1)+1}:{}},conversationContext:is(B),history:ri,thinkingMode:fe,researchResultRowsOptIn:ce,runId:Qe,...ye.current?{threadId:ye.current}:{}},ai=await ie.createAgentRunStream(oi,me=>{ke=!0,me.kind==="event"?Q(Gt=>[...Gt,me.event].slice(-8)):me.kind==="answer-delta"?ei(me.delta):Q(me.run.events.slice(-8))},Be.signal);Ut(ai,ve)}catch(je){Be.signal.aborted||(re(je instanceof Error?je.message:String(je)),te(V),ke?(En=!0,rt(ve)):(en(Qe),we.current===Qe&&(we.current=null),Oe.current=null,S(null)))}finally{Ke.current===Be&&(Ke.current=null),En||w(!1)}},wt=()=>{Me()},Tn=()=>{var v;const y=we.current;y&&ie.cancelAgentRun(y).catch(()=>{}),(v=Ke.current)==null||v.abort(),Le.current+=1,xe.current!==null&&window.clearTimeout(xe.current),en(y??""),we.current=null,Oe.current=null,S(null),nt(),Q([]),w(!1),re("Stopped. No answer or draft was saved.")},kt=h.useRef(J);kt.current=J,h.useEffect(()=>{var y;(y=kt.current)==null||y.call(kt,X)},[X]),h.useEffect(()=>{!(k!=null&&k.text)||X||Cn.current!==k.nonce&&(Cn.current=k.nonce,Me(k.text,k.mode??g))},[k==null?void 0:k.nonce,k==null?void 0:k.text,k==null?void 0:k.mode,g,X]),h.useEffect(()=>()=>{Le.current+=1,xe.current!==null&&window.clearTimeout(xe.current)},[]);const At={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},Ct=(y,v)=>{var T,F;if(v.id==="review-modeling-proposal"||v.id==="review-skill-proposal"){const W=v.id==="review-modeling-proposal"?"modeling_change_proposal":"skill_change_proposal",V=y.artifacts.find(ue=>ue.kind===W);if(!V){re("This authoring run does not include a reviewable proposal.");return}if(D)D(V,y);else if(V.ref){try{window.sessionStorage.setItem("dql-context-proposal-handoff",V.ref)}catch{}window.dispatchEvent(new CustomEvent("dql:open-context-proposal",{detail:{proposalId:V.ref,kind:V.kind}}))}return}if(v.id==="save-dql-block"){const W=_e(y),V=((T=W==null?void 0:W.source)==null?void 0:T.trim())??((F=qe(y))==null?void 0:F.trim());if(!V){re("This answer does not include a reusable DQL or SQL artifact yet.");return}oe({runId:y.id,source:V,name:(W==null?void 0:W.name)??`${y.question.slice(0,48).trim()||"saved_answer"}`,dqlArtifact:W});return}if(v.id==="research-deeper"){Me(y.question,"research",void 0,void 0,y);return}if(v.id.startsWith("suggest-question")){Me(v.label,"auto");return}K.current=Hs(v.route),te(Qs(y,v.route)),requestAnimationFrame(()=>{var W;return(W=tt.current)==null?void 0:W.focus()})},ii=h.useCallback((y,v,T="trust")=>{bt({runId:y,artifactId:v,tab:T})},[]),si=h.useCallback(y=>{var F,W;const v=y.trim();if(!v)return;const T=(F=Ee==null?void 0:Ee.text)==null?void 0:F.trim();Ye(null),Vt("");try{(W=window.getSelection())==null||W.removeAllRanges()}catch{}Me(T?`${v}
55
+
56
+ Regarding: "${T}"`:v),requestAnimationFrame(()=>{vt.current&&(vt.current.scrollTop=vt.current.scrollHeight)})},[Ee,Me]);if(h.useEffect(()=>{if(!z)return;const y=T=>{const F=T.target;F&&F.closest("[data-selpop]")||window.setTimeout(()=>{const W=window.getSelection(),V=W&&W.rangeCount?W.toString().trim():"";if(!V||V.length<3){Ye(ke=>ke&&null);return}const ue=W.anchorNode,ce=ue&&(ue.nodeType===1?ue:ue.parentElement),Rt=ce==null?void 0:ce.closest("[data-followup]");if(!Rt){Ye(ke=>ke&&null);return}const Be=W.getRangeAt(0).getBoundingClientRect(),Qe=Math.max(12,Math.min(Be.left,window.innerWidth-340)),ve=Be.bottom+176>window.innerHeight?Math.max(12,Be.top-176):Be.bottom+8;Ye({text:V.slice(0,220),source:Rt.getAttribute("data-followup")||"answer",left:Qe,top:ve}),Vt(""),requestAnimationFrame(()=>{var ke;return(ke=In.current)==null?void 0:ke.focus()})},0)},v=T=>{T.key==="Escape"&&Ye(null)};return document.addEventListener("mouseup",y),document.addEventListener("keydown",v),()=>{document.removeEventListener("mouseup",y),document.removeEventListener("keydown",v)}},[z]),z){const y=Ne?(()=>{const v=B.find(F=>F.kind==="run"&&F.run.id===Ne.runId);if(!v||v.kind!=="run")return null;const T=v.run.artifacts.find(F=>F.id===Ne.artifactId);return T?{run:v.run,artifact:T}:null})():null;return t.jsxs("div",{style:{display:"flex",height:"100%",minHeight:0,flex:1,minWidth:0,width:"100%",background:"var(--bg-canvas)"},children:[$?t.jsx(Hn,{cell:{id:`agent-${$.runId}`,type:$.dqlArtifact?"dql":"sql",content:$.source,name:$.name,status:"success",...$.dqlArtifact?{dqlArtifact:$.dqlArtifact}:{}},initialContent:$.source,initialName:$.name,onClose:()=>oe(null),onSaved:()=>oe(null)}):null,t.jsx("style",{children:zs}),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(Ue,{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:vt,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:[B.length===0&&!X?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(Ue,{size:20})}),t.jsx("div",{style:{fontSize:13.5,lineHeight:1.5,maxWidth:400,color:j.textSecondary},children:a??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:()=>{te(v.prompt),requestAnimationFrame(()=>{var T;return(T=tt.current)==null?void 0:T.focus()})},style:$t(j),children:v.label},v.label))})]}):null,B.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:ye.current,appContext:At,selectedArtifactId:(Ne==null?void 0:Ne.runId)===v.run.id?Ne.artifactId:void 0,onOpenArtifact:(T,F)=>ii(v.run.id,T,F),onOpenApp:E,onInsertSql:O,onInsertDql:L,onOpenBlock:U,onOpenResearch:N,onSelectClarification:T=>{const F=zt(T,v.run.question);Me(F.question,void 0,F.selectedEvidenceId,v.run.question)},onNextAction:T=>Ct(v.run,T),onRepairedRun:zn},v.id)),X&&t.jsx(tr,{events:ne,t:j,streamingAnswer:de,thinkingMode:fe,backgroundRun:G})]}),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:[R?t.jsx("div",{style:{color:j.error,fontSize:12,marginBottom:8},children:R}):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(Tt,{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:Y,onChange:v=>{te(v.target.value),K.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:fe,onChange:kn}),t.jsx(Zn,{checked:$e,onChange:ge,t:j}),t.jsx(er,{names:A,value:Te,onChange:qn,t:j}),t.jsx("div",{style:{flex:1}}),X?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:!Y.trim()||X,style:{width:34,height:34,borderRadius:10,border:"none",background:Y.trim()&&!X?"var(--accent)":"var(--bg-4)",color:"#fff",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:Y.trim()&&!X?"pointer":"default",boxShadow:Y.trim()&&!X?"0 1px 5px rgba(107,93,211,0.3)":"none"},children:X?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."})]})]})]}),y?t.jsx($s,{run:y.run,artifact:y.artifact,tab:Ne.tab,t:j,appContext:At,onOpenApp:E,onChangeTab:v=>bt(T=>T&&{...T,tab:v}),onClose:()=>bt(null),onSaveBlock:()=>Ct(y.run,{id:"save-dql-block",label:"Save as block",route:"dql_block_draft"}),onInsertSql:O,onInsertDql:L}):null,Ee?t.jsx(Ls,{t:j,text:Ee.text,source:Ee.source,left:Ee.left,top:Ee.top,draft:ni,inputRef:In,onDraftChange:Vt,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:[$?t.jsx(Hn,{cell:{id:`agent-${$.runId}`,type:$.dqlArtifact?"dql":"sql",content:$.source,name:$.name,status:"success",...$.dqlArtifact?{dqlArtifact:$.dqlArtifact}:{}},initialContent:$.source,initialName:$.name,onClose:()=>oe(null),onSaved:()=>oe(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:[B.length===0&&!X?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(Ue,{size:20})}),t.jsx("div",{style:{fontSize:13,lineHeight:1.5,maxWidth:380,color:j.textSecondary},children:a??Kn}),t.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap",justifyContent:"center",maxWidth:520},children:(o??Yn).map(y=>t.jsx("button",{type:"button",className:"dql-hover dql-lift",onClick:()=>{te(y.prompt),requestAnimationFrame(()=>{var v;return(v=tt.current)==null?void 0:v.focus()})},style:$t(j),children:y.label},y.label))})]}):null,B.map(y=>y.kind==="user"?t.jsx("div",{style:ro(j),children:y.text},y.id):Z?t.jsx(ir,{run:y.run,t:j,themeMode:e,threadId:ye.current,appContext:At,onOpenApp:E,onInsertSql:O,onInsertDql:L,onReplaceDql:P,insertDqlActionLabel:C,replaceDqlActionLabel:_,onOpenBlock:U,onOpenResearch:N,onSelectClarification:v=>{const T=zt(v,y.run.question);Me(T.question,void 0,T.selectedEvidenceId,y.run.question)},onNextAction:v=>Ct(y.run,v),onRepairedRun:zn},y.id):t.jsx(Is,{run:y.run,t:j,themeMode:e,appContext:At,onOpenApp:E,onInsertSql:O,onInsertDql:L,onOpenBlock:U,onOpenResearch:N,onSelectClarification:v=>{const T=zt(v,y.run.question);Me(T.question,void 0,T.selectedEvidenceId,y.run.question)},onNextAction:v=>Ct(y.run,v)},y.id)),X&&t.jsx(tr,{events:ne,t:j,streamingAnswer:de,thinkingMode:fe,backgroundRun:G})]}),R?t.jsx("div",{style:{margin:"0 16px 8px",color:j.error,fontSize:12},children:R}):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(Tt,{size:12})}):null]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx(er,{names:A,value:Te,onChange:qn,t:j}),t.jsx(Nn,{t:j,value:fe,onChange:kn}),t.jsx(Zn,{checked:$e,onChange:ge,t:j})]})]}),t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-end"},children:[t.jsx("textarea",{ref:tt,value:Y,onChange:y=>{te(y.target.value),K.current=void 0},rows:2,placeholder:i,onKeyDown:y=>{y.key==="Enter"&&!y.shiftKey&&(y.preventDefault(),wt())},style:eo(j)}),t.jsxs("button",{type:"button",className:"dql-hover dql-lift",onClick:wt,disabled:!Y.trim()||X,style:ar(j,!!Y.trim()&&!X),children:[X?t.jsx(Ve,{size:15,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}}):t.jsx(Pi,{size:15}),t.jsx("span",{children:X?"Working":"Ask"})]}),X?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 en(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 Rr="dql.agent.thinkingMode";function qr(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 js(){try{const e=window.localStorage.getItem(Rr);return e==="low"||e==="medium"||e==="high"||e==="auto"?e:"auto"}catch{return"auto"}}const Ss=new Set(["conversation","certified_answer","semantic_answer","generated_answer","research","sql_cell","dql_block_draft","modeling_draft","skill_draft","app_build","clarify","cancelled","blocked"]),ws=new Set(["certified","governed","grounded","review_required","blocked","not_applicable"]),ks=new Set(["completed","needs_review","needs_clarification","cancelled","blocked"]),As=new Set(["conversational_reply","certified_answer_found","governed_semantic_answer","generated_review_required","artifact_created","needs_clarification","human_review_required","cancelled","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 a=o.derivation;return(a==null?void 0:a.kind)==="analytical_repair"&&i.has(o.id)&&typeof a.sourceRunId=="string"?[a.sourceRunId]:[]}));return e.filter(o=>!o.agentRunId||!s.has(o.agentRunId)).flatMap(o=>{const a=o.agentRunId?r.get(o.agentRunId):void 0;return[{kind:"user",id:`${o.id}-q`,text:o.question},{kind:"run",id:(a==null?void 0:a.id)??o.id,run:a??Cs(o)}]})}function Cs(e){var p,g,l;const n=Ss.has(e.route)?e.route:"generated_answer",r=ws.has(e.trustLabel)?e.trustLabel:e.certification==="certified"?"certified":"not_applicable",i=ks.has(e.runStatus)?e.runStatus:"completed",s=As.has(e.stopReason)?e.stopReason:i==="cancelled"?"cancelled":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"),a=(((g=e.result)==null?void 0:g.rowsSample)??[]).filter(u=>Array.isArray(u)).map(u=>Object.fromEntries(o.map((f,x)=>[f,u[x]]))),c=o.length>0?{columns:o,rows:a,rowCount:((l=e.result)==null?void 0:l.rowCount)??a.length}:void 0,d=c||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}:{},...c?{result:c}:{},...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:d?[d]:[],evaluations:[],events:[],nextActions:[],repairAttempts:0}}function Rs(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";case"cancelled":return"Stopped by user";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 zr(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 _r(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(c=>c.type==="route.decided"),s=e.some(c=>c.type==="executor.started"||c.type==="step.started"||c.type==="repair.attempted"||c.type==="escalated"),o=e.some(c=>c.type==="evaluation.recorded"),a=[{id:"search",label:"Resolving governed evidence and business meaning",state:i?"complete":"active"}];return i&&a.push({id:"match",label:Rs(r),state:s||o?"complete":"active"}),(s||o)&&a.push({id:"execute",label:qs(r,e),state:o?"complete":"active"}),o&&a.push({id:"verify",label:"Checking the result against governed evidence",state:"active"}),a}function tr({events:e,t:n,streamingAnswer:r,thinkingMode:i,backgroundRun:s}){var x;const[o,a]=h.useState(()=>Date.now());h.useEffect(()=>{const m=window.setInterval(()=>a(Date.now()),1e3);return()=>window.clearInterval(m)},[]);const c=(s==null?void 0:s.startedAt)??((x=e.find(m=>m.type==="run.started"))==null?void 0:x.at),d=c?Date.parse(c):o,p=Number.isFinite(d)?Math.max(0,Math.floor((o-d)/1e3)):0,g=zr(p,ln(e),e.some(m=>m.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),f=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(m=>t.jsxs("div",{className:"dql-agent-activity",style:{display:"flex",alignItems:"center",gap:9,minHeight:18,color:m.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:m.state==="active"?n.accent:n.textMuted},children:m.state==="active"?t.jsx(nr,{}):t.jsx(dt,{size:13,strokeWidth:2.2})}),t.jsxs("span",{style:{fontSize:12.5,lineHeight:1.4,fontWeight:m.state==="active"?620:450},children:[m.label,m.state==="active"?"…":""]})]},m.id)),f?t.jsx("span",{style:{paddingLeft:25,fontSize:10.5,lineHeight:1.4,color:n.textMuted},children:f}):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]=h.useState(!1),a=s?e:e.slice(0,i);return t.jsxs(t.Fragment,{children:[a.map((c,d)=>r(c,d)),e.length>i?t.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>o(c=>!c),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(Dt,{size:11}),s?"Show less":`Show all (${e.length})`]}):null]})}function Is({run:e,t:n,themeMode:r,appContext:i,onOpenApp:s,onInsertSql:o,onInsertDql:a,onOpenBlock:c,onOpenResearch:d,onSelectClarification:p,onNextAction:g}){var Z;const{dispatch:l}=Nt();if(e.route==="conversation"){const C=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:io(n),children:[C?t.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:10.5,color:n.textMuted,marginBottom:6,fontWeight:650},children:[t.jsx(Et,{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(_=>t.jsx("button",{type:"button",className:"dql-hover dql-lift",onClick:()=>g(_),style:$t(n),children:_.label},_.id))}):null]})}const u=e.steps??[],f=u.length>1,x=((Z=e.plan)==null?void 0:Z.source)==="llm",m=wn(e),b=jn(e),k=xt(e),O=e.route==="certified_answer"||e.route==="generated_answer",L=e.nextActions.some(C=>C.route==="research"),P=O&&k&&!L,q=_e(e),D=k&&!(q!=null&&q.sourcePath)&&!!((q==null?void 0:q.source)??qe(e)),U=Date.parse(e.startedAt),N=Date.parse(e.completedAt),E=Number.isFinite(U)&&Number.isFinite(N)?Math.max(0,Math.round((N-U)/1e3)):0,J=_r(E,e.route,e.trustState,e.repairAttempts);return t.jsxs("div",{style:so(n),children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx(Fs,{run:e}),t.jsx("div",{style:{minWidth:0,flex:1},children:t.jsx("div",{style:{fontSize:12.5,fontWeight:850,color:n.textPrimary},children:Ds(e)})}),t.jsx(Ws,{run:e,t:n})]}),b?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(be,{size:12,color:n.success,style:{flex:"0 0 auto",marginTop:1}}):e.trustState==="governed"||e.trustState==="grounded"?t.jsx(be,{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:b})]}):null,x||f||e.repairAttempts>0?t.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[x?t.jsx(nn,{t:n,icon:t.jsx(ft,{size:11}),label:"AI plan",tone:"accent"}):null,f?t.jsx(nn,{t:n,icon:t.jsx(at,{size:11}),label:`${u.length} steps`,tone:"muted"}):null,e.repairAttempts>0?t.jsx(nn,{t:n,icon:t.jsx(Ft,{size:11}),label:`${e.repairAttempts} repair${e.repairAttempts>1?"s":""}`,tone:"warning"}):null]}):null,e.summary&&!(e.answer&&Vs(Ce(e.summary),Je(e.answer)))?t.jsx("div",{style:{fontSize:12.5,lineHeight:1.45,color:n.textSecondary},children:Ce(e.summary)}):null,e.answer?t.jsx("div",{style:oo(n),children:t.jsx(_t,{text:Je(e.answer),t:n})}):null,e.analyticalTaskOutcomes&&e.analyticalTaskOutcomes.length>1?t.jsxs("div",{style:{display:"grid",gap:5,padding:"8px 10px",border:`1px solid ${n.cellBorder}`,borderRadius:8,background:n.cellBg},children:[t.jsx("div",{style:{fontSize:10.5,fontWeight:800,color:n.textMuted,textTransform:"uppercase",letterSpacing:.4},children:"Analytical tasks"}),e.analyticalTaskOutcomes.map(C=>{var j;const _=typeof C.status=="string"?C.status:"gap",z=typeof C.summary=="string"?C.summary:typeof((j=C.gap)==null?void 0:j.message)=="string"?String(C.gap.message):"Task outcome recorded.";return t.jsxs("div",{style:{display:"flex",gap:7,alignItems:"flex-start",fontSize:11.5,color:n.textSecondary},children:[t.jsx("span",{style:{color:_==="completed"?n.success:n.warning,fontWeight:800},children:_==="completed"?"✓":"!"}),t.jsxs("span",{children:[t.jsx("strong",{children:String(C.taskId)})," · ",z]})]},String(C.taskId))})]}):null,t.jsx(Br,{run:e,t:n,onSelect:p}),m.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:"}),m.map(C=>t.jsxs("span",{style:Kr(n,C.certified),children:[C.certified?t.jsx(be,{size:11}):t.jsx(pt,{size:11}),t.jsx("span",{children:C.label})]},C.label))]}):null,t.jsx(Gr,{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(C=>t.jsx(Or,{artifact:C,t:n,themeMode:r,onInsertSql:o,onInsertDql:a,sourceRunId:e.id,sourceQuestion:e.question,onOpenBlock:c,onOpenResearch:d,onOpenApp:s,onNextAction:g},C.id))}):null,f?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:()=>l({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(ft,{size:12})," View steps · where the time went"]}):null,J?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(Et,{size:11,color:n.accent})," ",J.title]}),t.jsx("span",{style:{fontSize:10.5,color:n.textMuted,lineHeight:1.45},children:J.detail})]}):null,k||P||e.nextActions.length>0?t.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",alignItems:"center"},children:[k?t.jsx(vn,{run:e,t:n,appContext:i,onOpenApp:s}):null,D?t.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>g({id:"save-dql-block",label:"Save as block",route:"dql_block_draft"}),style:ee(n),children:[t.jsx(xn,{size:11})," Save as block"]}):null,P?t.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>g({id:"research-deeper",label:"Research this deeper",route:"research"}),style:ee(n),title:"Run a slower, multi-step investigation on this question",children:[t.jsx(pt,{size:11}),"Research this deeper"]}):null,e.nextActions.filter(C=>C.id!=="pin-to-app"&&C.id!=="research-deeper"&&C.id!=="confirm-app-build"&&C.id!=="request-certification").map(C=>t.jsx("button",{type:"button",className:"dql-hover",onClick:()=>g(C),style:ee(n),children:C.label},C.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 zs=`
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 Pt(e,{variant:"ghost",size:"sm"})}function tn(e,n){return e.kind==="app_proposal"||e.kind==="dql_block_draft"||e.kind==="research_run"||!!Ht(n)}function Wt(e,n){var a,c;const r=[],i=ze(n),s=e.kind==="answer"?(a=i==null?void 0:i.rows)!=null&&a.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)??((c=i==null?void 0:i.rows)==null?void 0:c.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 lt(e,n){const i=/^(?:certified|governed semantic|review-required|exploratory dbt-grounded) answer$/i.test(n.title.trim())?e.question:n.title,s=Ce(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 M(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Mr(e){const n=[],r=new Set,i=(s,o)=>{const a=M(s);if(!a)return;const c=[a.name,a.label,a.relation,a.objectName].find(l=>typeof l=="string"&&l.trim().length>0);if(!c)return;const d=typeof a.kind=="string"?a.kind:o,p=`${d??""}:${c}`;if(r.has(p))return;r.add(p);const g=[a.description,a.provenance,a.sourceTier,a.source].find(l=>typeof l=="string"&&l.trim().length>0);n.push({name:c,kind:d,detail:g})};for(const s of e.artifacts){const o=se(s),a=M(o.evidence);for(const p of["lineage","sourceTables","semanticObjects","selectedAssets"]){const g=a==null?void 0:a[p];Array.isArray(g)&&g.forEach(l=>i(l,p==="sourceTables"?"source":void 0))}const c=M(o.analysisPlan)??M(a==null?void 0:a.analysisPlan),d=c==null?void 0:c.candidateTables;Array.isArray(d)&&d.forEach(p=>i(p,"relation"))}return n.slice(0,24)}function bn(e,n){var i;const r=se(n);return Ot(r)?"how":(i=_e(e)??yt(r))!=null&&i.source?"dql":qe(e)??(typeof r.sql=="string"?r.sql:void 0)?"sql":Mr(e).length>0?"lineage":"trust"}function Ts({run:e,artifact:n,selected:r,t:i,themeMode:s,onInspect:o}){const a=se(n),c=ze(a),[d,p]=h.useState(!1);if(h.useEffect(()=>{if(!d)return;const m=b=>{b.key==="Escape"&&p(!1)};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[d]),!c)return null;const g=Vr(a,c),l=bn(e,n),u=_e(e)??yt(a),f=n.trustState==="certified"?Wr(n,a):void 0,x=t.jsxs("section",{"data-followup":"table","aria-label":`${lt(e,n)} result`,style:{border:`1px solid ${r?"var(--accent)":"var(--border-default)"}`,borderRadius:12,background:"var(--bg-2)",overflow:"hidden",boxShadow:d?"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)",...d?{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:lt(e,n)}),t.jsx("div",{style:{fontSize:11,color:i.textMuted,marginTop:2},children:Wt(n,a)})]}),t.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:()=>o(l),style:Pe(i),children:[t.jsx(ft,{size:12})," Inspect"]}),t.jsxs("button",{type:"button",className:"dql-ask-ghost","aria-label":d?"Return result to Copilot":"Expand result",title:d?"Return result to Copilot":"Expand this result for wide tables",onClick:()=>p(m=>!m),style:Pe(i),children:[d?t.jsx(qi,{size:12}):t.jsx(ji,{size:12}),d?"Restore":"Expand result"]})]}),u?t.jsx(Fr,{artifact:u,certifiedBlockName:f,initialResult:c,initialChartConfig:g,payload:a,executionTarget:e.executionTarget,t:i,themeMode:s,embedded:!0,expanded:d}):t.jsx(gn,{result:c,themeMode:s,t:i,chartConfig:g,embedded:!0,tabLabels:{table:"Results",chart:"Visualization"},contentMaxHeight:d?"calc(100vh - 172px)":void 0,tableMaxHeight:d?"calc(100vh - 250px)":void 0})]});return!d||typeof document>"u"?x: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."}),yi.createPortal(t.jsx("div",{role:"dialog","aria-modal":"true","aria-label":`${lt(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:m=>m.stopPropagation(),style:{minWidth:0,maxWidth:"100%"},children:x})}),document.body)]})}function ir(e){const{run:n,t:r,themeMode:i,threadId:s,appContext:o,selectedArtifactId:a,onOpenArtifact:c,onOpenApp:d,onInsertSql:p,onInsertDql:g,onReplaceDql:l,insertDqlActionLabel:u,replaceDqlActionLabel:f,onOpenBlock:x,onOpenResearch:m,onSelectClarification:b,onNextAction:k,onRepairedRun:O}=e,{dispatch:L}=Nt(),[P,q]=h.useState(!1),D=c??(()=>L({type:"OPEN_AGENT_LOG",run:n}));if(n.route==="conversation"){const R=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:[R?t.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:10.5,color:r.textMuted,fontWeight:650},children:[t.jsx(Et,{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(re=>t.jsx("button",{type:"button",className:"dql-hover dql-lift",onClick:()=>k(re),style:$t(r),children:re.label},re.id))}):null]})}const U=n.trustState==="certified",N=n.status==="blocked",E=n.status==="cancelled"||n.stopReason==="cancelled"||n.route==="cancelled",J=n.status==="needs_clarification",Z=n.answer,C=E?"Stopped by user":N?"Couldn’t run this query":J?"Needs clarification":U?"Certified answer":"AI-generated answer",_=E?n.summary||"Stopped by user.":N?Zr(n):void 0,z=Xr(n),j=n.evaluations.filter(R=>R.severity==="info").length,K=wn(n),Y=E?[]:n.artifacts,te=Y.filter(R=>{const re=se(R);return!tn(R,re)&&!!ze(re)}),B=new Set(te.map(R=>R.id)),H=Y.filter(R=>!tn(R,se(R))&&!B.has(R.id)),ne=Y.filter(R=>tn(R,se(R))),Q=te[0]??H[0]??Y[0],de=xt(n),he=n.route==="certified_answer"||n.route==="semantic_answer"||n.route==="generated_answer",X=n.nextActions.some(R=>R.route==="research"),w=he&&de&&!X,G=_e(n),S=de&&!(G!=null&&G.sourcePath)&&!!((G==null?void 0:G.source)??qe(n)),$=u&&g||f&&l?Bt(n):void 0,oe=()=>{var re;const R=Z?Je(Z):_??n.summary;R&&((re=navigator.clipboard)==null||re.writeText(R).catch(()=>{}),q(!0),window.setTimeout(()=>q(!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:[E?t.jsx(at,{size:14,color:r.textMuted}):N?t.jsx(Ze,{size:14,color:r.error}):U?t.jsx(be,{size:14,color:r.success}):t.jsx(Ue,{size:14,color:r.accent}),t.jsx("span",{style:{fontSize:12,fontWeight:650,color:E?r.textMuted:N?r.error:r.textSecondary},children:C}),U&&K[0]?t.jsxs("span",{style:{fontSize:11,color:r.textMuted},children:["from ",t.jsx("span",{style:{color:r.accent,fontWeight:600},children:K[0].label})]}):!N&&!E&&Q&&j>0?t.jsxs("button",{type:"button",onClick:()=>D(Q.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})," ",j," check",j===1?"":"s"," passed"]}):null]}),Z?t.jsx("div",{"data-followup":"answer",style:{fontSize:14.5,lineHeight:1.65,color:r.textPrimary},children:t.jsx(_t,{text:Je(Z),t:r})}):E?t.jsx("div",{"data-followup":"answer",style:{fontSize:14,lineHeight:1.6,color:r.textMuted},children:Ce(n.summary||"Stopped by user.")}):_?t.jsx(ao,{run:n,detail:_,threadId:s,onRepaired:R=>O(n.id,R),t:r}):n.summary?t.jsx("div",{"data-followup":"answer",style:{fontSize:14,lineHeight:1.6,color:r.textSecondary},children:Ce(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: ",Ce(z)," The query result is still valid."]}):null,t.jsx(Br,{run:n,t:r,onSelect:b}),te.map(R=>t.jsx(Ts,{run:n,artifact:R,selected:R.id===a,t:r,themeMode:i,onInspect:re=>D(R.id,re)},R.id)),H.map(R=>{const re=se(R),fe=R.id===a;return t.jsxs("button",{type:"button",className:"dql-ask-chip",onClick:()=>D(R.id,bn(n,R)),style:{display:"flex",alignItems:"center",gap:10,width:"fit-content",maxWidth:"100%",padding:"9px 12px",borderRadius:10,border:`1px solid ${fe?"var(--accent)":"var(--border-default)"}`,background:"var(--bg-2)",boxShadow:fe?"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:R.trustState==="certified"?"var(--status-success-bg)":"var(--accent-dim)",color:R.trustState==="certified"?"var(--status-success)":"var(--accent)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t.jsx(et,{kind:R.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:Ce(R.title)}),t.jsx("span",{style:{fontSize:11,color:r.textMuted},children:Wt(R,re)})]}),t.jsx(fr,{size:14,color:r.textMuted,style:{flexShrink:0,marginLeft:6}})]},R.id)}),ne.length>0?t.jsx("div",{style:{display:"grid",gap:8,gridTemplateColumns:"minmax(0, 1fr)",minWidth:0},children:ne.map(R=>t.jsx(Or,{artifact:R,t:r,themeMode:i,onInsertSql:p,onInsertDql:g,insertDqlActionLabel:u,sourceRunId:n.id,sourceQuestion:n.question,onOpenBlock:x,onOpenResearch:m,onOpenApp:d,onNextAction:k},R.id))}):null,Z||_||$||de||S||w||Q?t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexWrap:"wrap",marginTop:-2},children:[$&&g?t.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:()=>g($),style:Pe(r),children:[t.jsx(ot,{size:12})," ",u]}):null,$&&l&&f?t.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:()=>l($),style:Pe(r),children:[t.jsx(bi,{size:12})," ",f]}):null,Z||_?t.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:oe,style:Pe(r),children:[P?t.jsx(dt,{size:12}):t.jsx(mr,{size:12})," ",P?"Copied":"Copy"]}):null,de?t.jsx(vn,{run:n,t:r,appContext:o,onOpenApp:d}):null,S?t.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:()=>k({id:"save-dql-block",label:"Save as block",route:"dql_block_draft"}),style:Pe(r),children:[t.jsx(ht,{size:12})," Save as block"]}):null,w?t.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:()=>k({id:"research-deeper",label:"Research this deeper",route:"research"}),style:Pe(r),children:[t.jsx(pt,{size:12})," Research deeper"]}):null,Q?t.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:()=>D(Q.id,Ot(se(Q))?"how":"trust"),style:Pe(r),children:[t.jsx(ft,{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=M(n);if(r)return{stage:"execution",...r};const i=typeof e.refusalCode=="string"?e.refusalCode:void 0;if(i){const s=M(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 Ot(e){return!!(M(e.resolvedAnalyticalPlan)||M(e.analyticalExecutionGraph)||M(e.analyticalExecutionReceipt)||M(e.analyticalFailure)||M(e.semanticExecutionTrace)||M(e.diagnosticReceipt)||$r(e))}function Lr(e){if(!Ot(e))return;const n=M(e.diagnosticReceipt),r=M(e.resolvedAnalyticalPlan)??M(n==null?void 0:n.resolvedAnalyticalPlan);return{plan:r,frame:M(r==null?void 0:r.analyticalFrame),graph:M(e.analyticalExecutionGraph),receipt:M(e.analyticalExecutionReceipt),facts:M(e.analyticalFacts),narrative:M(e.analyticalNarrative),freshness:M(e.analyticalFreshnessObservation),failure:M(e.analyticalFailure)??M(n==null?void 0:n.failure)??$r(e),semantic:M(e.semanticExecutionTrace),diagnostic:n}}function Es(){return["Performance & provider egress","Plan","DQL","Compiled SQL","Lineage","Trust & evidence","Actual steps","Failure & repair"]}function Ms(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((d,p)=>d+p.resultRowCount,0),i=n.stageDurationsMs.total,s=n.warehouseDurationMs,o=i===void 0||s===void 0?void 0:Math.max(0,i-s),a=Array.from(new Set((e.artifacts??[]).flatMap(d=>{var u;const p=se(d),g=M(p.resolvedAnalyticalPlan)??M((u=M(p.diagnosticReceipt))==null?void 0:u.resolvedAnalyticalPlan),l=M(p.analyticalExecutionReceipt);return[g==null?void 0:g.planId,l==null?void 0:l.planId].filter(f=>typeof f=="string"&&f.length>0)}))),c=Array.from(new Set((e.artifacts??[]).map(d=>d.id).filter(d=>typeof d=="string"&&d.length>0)));return[["Total",It(n.stageDurationsMs.total)],["Warehouse",n.warehouseDurationMs===void 0?"Not recorded":It(n.warehouseDurationMs)],["Orchestration",o===void 0?"Not recorded":It(o)],["Stages",Object.entries(n.stageDurationsMs).filter(([d])=>d!=="total").map(([d,p])=>`${d}: ${It(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",a.length>0?a.join(", "):"Not recorded"],["Artifact IDs",c.length>0?c.join(", "):"None"],["Fallback",n.fallbackReason??"None"]]}function Bs({run:e,contract:n,dqlArtifact:r,sql:i,lineage:s,t:o,onInsertSql:a,onInsertDql:c,onSaveBlock:d}){var We,$e,ge;const{dispatch:p}=Nt(),g=n.plan,l=n.frame,u=n.graph,f=n.receipt,x=n.semantic,m=M(x==null?void 0:x.failure),b=n.failure??m,k=M(x==null?void 0:x.authoringRequest),O=M(x==null?void 0:x.runtimeRequest),L=Se(x==null?void 0:x.bindings),P=Se(x==null?void 0:x.steps),q=M(x==null?void 0:x.targetBinding),D=M(q==null?void 0:q.semanticSnapshot),U=M(q==null?void 0:q.executionTarget),N=M(U==null?void 0:U.redactedContext),E=M(q==null?void 0:q.compileTarget),J=M(x==null?void 0:x.executionReceipt),Z=Se(m==null?void 0:m.candidates),C=M(l==null?void 0:l.timeContext),_=M(l==null?void 0:l.comparison),z=M(l==null?void 0:l.ranking),j=Se(l==null?void 0:l.dimensions),K=Se(l==null?void 0:l.memberBindings),Y=Se(C==null?void 0:C.periods),te=Se(l==null?void 0:l.requestedOutputs),B=Se(u==null?void 0:u.nodes),H=Array.from(new Set([...Ae(b==null?void 0:b.safeActions),...Ae(m==null?void 0:m.safeActions)])),ne=Se(b==null?void 0:b.failedBindings),Q=M(m==null?void 0:m.sqlExcerpt),de=e.artifacts.map(A=>ze(se(A))).find(Boolean),he=Dr(e),X=(r==null?void 0:r.name)??e.question,[w,G]=h.useState(null),S=(A,le)=>{const Te=le.derivation.trustTransition;return`${A} as immutable derivation ${le.derivation.derivationId}. Trust: ${Te.previous} → ${Te.next}${Te.requiresReview?" (review required)":""}.`},$=async()=>{if(!(!(r!=null&&r.source)||!c))try{const A=await ie.deriveAnalyticalRepair(e.id,{version:1,action:"edit_dql",dqlSource:r.source});c({sql:i,dqlArtifact:r,result:de,title:X,sourceRunId:e.id,question:e.question}),G(S("Opened DQL in Notebook",A))}catch(A){G(A instanceof Error?A.message:String(A))}},oe=async()=>{if(!(!i||!a))try{const A=await ie.deriveAnalyticalRepair(e.id,{version:1,action:"open_sql_notebook",sqlText:i});a(i,`${X} repair`,{question:e.question,sourceRunId:e.id}),G(S("Opened SQL in Notebook",A))}catch(A){G(A instanceof Error?A.message:String(A))}},R=async A=>{try{const le=await ie.deriveAnalyticalRepair(e.id,{version:1,action:A});G(S(A==="retry_same_plan"?"Prepared the same bounded plan for retry":"Refreshed the governed snapshot and prepared the same plan for retry",le))}catch(le){G(le instanceof Error?le.message:String(le))}},re=async()=>{try{const A=await ie.deriveAnalyticalRepair(e.id,{version:1,action:"request_access"});G(S("Recorded the access/connection repair and opened Database settings",A)),p({type:"SET_SETTINGS_TAB",tab:"database"}),p({type:"SET_MAIN_VIEW",view:"settings"})}catch(A){G(A instanceof Error?A.message:String(A))}},fe=()=>{p({type:"SET_SETTINGS_TAB",tab:"project"}),p({type:"SET_MAIN_VIEW",view:"settings"}),G("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 ${b?"var(--status-error-border)":"var(--status-success-border)"}`,background:b?"var(--status-error-bg)":"var(--status-success-bg)"},children:[b?t.jsx(Ze,{size:13,color:"var(--status-error)",style:{flexShrink:0,marginTop:2}}):t.jsx(be,{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:b?"var(--status-error)":"var(--status-success)"},children:b?"Execution failed":"Answered successfully"}),b?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{marginTop:3,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:o.fontMono,fontSize:11},children:typeof b.message=="string"&&b.message.trim()?b.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:[b.code,b.phase?`during ${b.phase}`:""].filter(Boolean).map(I).join(" · ")})]}):t.jsx("div",{style:{marginTop:2},children:typeof(f==null?void 0:f.rowCount)=="number"?`Returned ${f.rowCount} row${f.rowCount===1?"":"s"}.`:"The query ran and returned a result."})]})]}),t.jsx(it,{index:1,label:"Performance & provider egress",t:o,open:!0,children:he?t.jsx(qt,{rows:he,t:o}):t.jsx(ct,{t:o,children:"Performance details were not recorded for this legacy run."})}),t.jsx(it,{index:2,label:"Plan",t:o,open:!b,children:t.jsx(qt,{rows:[["Question type",I((l==null?void 0:l.questionType)??(g==null?void 0:g.questionType))],["Selected route",I((u==null?void 0:u.route)??(g==null?void 0:g.recommendedRoute))],["Metric",Ae(l==null?void 0:l.metricConceptIds).join(", ")],["Entity grain",Ae(l==null?void 0:l.entityGrainIds).join(", ")],["Dimensions",j.map(A=>`${I(A.dimensionId)} (${I(A.role)})`).join(", ")],["Member filters",K.map(A=>`${I(A.dimensionId)}: ${Array.isArray(A.canonicalValues)?A.canonicalValues.length:0} bound value(s)`).join(", ")],["Time policy",[C==null?void 0:C.timeRole,C==null?void 0:C.grain,C==null?void 0:C.timezone,C==null?void 0:C.completenessPolicy].map(I).filter(Boolean).join(" · ")],["Periods",Y.map(A=>`${I(A.id)}: ${I(A.start)} → ${I(A.end)}`).join(`
85
+ `)],["Comparison",_?`${I(_.basePeriodId)} vs ${Ae(_.comparisonPeriodIds).join(", ")} · ${I(_.alignment)}`:l?"Not requested":"Not available — analytical planning did not complete"],["Ranking",z?`${I(z.direction)} · top ${I(z.limit)} · ${I(z.tiePolicy)}`:l?"Not requested":"Not available — analytical planning did not complete"],["Outputs",te.map(A=>`${I(A.id)} (${I(A.kind)})`).join(", ")],["Semantic metrics",Ae(k==null?void 0:k.metrics).join(", ")],["Semantic dimensions",Ae(k==null?void 0:k.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(f==null?void 0:f.receiptId)],["Result fingerprint",I(f==null?void 0:f.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(x==null?void 0:x.adapter)],["Semantic compile status",I(x==null?void 0:x.status)],["Target proof",I((ge=M(q==null?void 0:q.proof))==null?void 0:ge.status)],["Target binding",I(q==null?void 0:q.bindingFingerprint)],["Compile target",I(E==null?void 0:E.kind)],["Local semantic snapshot",I((D==null?void 0:D.semanticCatalogFingerprint)??(D==null?void 0:D.sourceFingerprint))],["Runtime metric inventory proof",I(E==null?void 0:E.semanticCatalogFingerprint)],["Execution target",[U==null?void 0:U.driver,N==null?void 0:N.account,N==null?void 0:N.database,N==null?void 0:N.schema,N==null?void 0:N.role,N==null?void 0:N.warehouse].map(I).filter(Boolean).join(" · ")],["Semantic receipt",I(J==null?void 0:J.receiptId)],["Warehouse query ID",I(J==null?void 0:J.queryId)],["Executed SQL proof",I(J==null?void 0:J.executedSqlFingerprint)],["Runtime metrics",Ae(O==null?void 0:O.metrics).join(", ")],["Runtime dimensions",Ae(O==null?void 0:O.dimensions).join(", ")],["Member bindings",L.map(A=>`${I(A.authoringReference)} → ${I(A.runtimeReference)}${Ae(A.entityPath).length?` via ${Ae(A.entityPath).join(" → ")}`:""} (${I(A.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:[P.map((A,le)=>t.jsxs("div",{style:{fontSize:11.5,color:o.textSecondary},children:[t.jsxs("strong",{style:{color:I(A.status)==="failed"?"var(--status-error)":o.textPrimary},children:[le+1,". ",I(A.label)]})," ","— ",I(A.status)," · ",I(A.detail)]},`semantic:${I(A.id)||le}`)),e.steps.map(A=>t.jsxs("div",{style:{fontSize:11.5,color:o.textSecondary},children:[t.jsxs("strong",{style:{color:o.textPrimary},children:[A.index+1,". ",A.goal]})," — ",A.status,", ",A.attempts," attempt",A.attempts===1?"":"s"]},A.id)),B.map((A,le)=>t.jsxs("div",{style:{fontSize:11.5,color:o.textSecondary},children:[t.jsxs("span",{style:{color:o.accent,fontFamily:o.fontMono},children:[le+1,". ",I(A.kind)]})," ","· ",I(A.id)]},I(A.id)||le)),P.length===0&&e.steps.length===0&&B.length===0?t.jsx(ct,{t:o,children:"No executable steps were recorded."}):null]})}),t.jsx(it,{index:5,label:"Failure & repair",t:o,open:!!b,children:b?t.jsxs("div",{style:{display:"grid",gap:9},children:[t.jsx(qt,{rows:[["Failure ID",I(b.failureId)],["Recoverability",I(b.recoverability)],["Failed bindings",ne.map(A=>`${I(A.qualifiedId??A.role)} (${I(A.reasonCode)})`).join(", ")],["Safe actions",H.join(", ")],["DQL fingerprint",I(b.dqlFingerprint)],["SQL fingerprint",I(b.sqlFingerprint)],["Semantic failure code",I(m==null?void 0:m.code)],["Failing identifier",I(m==null?void 0:m.identifier)],["Compiled SQL proof",I(m==null?void 0:m.compiledSqlFingerprint)],["Path candidates",Z.map(A=>`${I(A.label)}
87
+ ${I(A.runtimeReference)}`).join(`
88
+ `)]],t:o,mono:!0}),I(Q==null?void 0:Q.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(Q==null?void 0:Q.startLine),"–",I(Q==null?void 0:Q.endLine)]}),t.jsx("pre",{style:gt(o),children:I(Q==null?void 0:Q.text)})]}):null,t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6},"aria-label":"Safe repair actions",children:[H.includes("edit_dql")&&c?t.jsxs("button",{type:"button",onClick:()=>void $(),style:ee(o),children:[t.jsx(Ft,{size:12})," Open DQL to repair"]}):null,H.includes("open_sql_notebook")&&a?t.jsxs("button",{type:"button",onClick:()=>void oe(),style:ee(o),children:[t.jsx(hn,{size:12})," Open SQL in Notebook"]}):null,H.includes("retry_same_plan")?t.jsxs("button",{type:"button",onClick:()=>void R("retry_same_plan"),style:ee(o),children:[t.jsx(Kt,{size:12})," Retry same plan"]}):null,H.includes("refresh_snapshot")?t.jsxs("button",{type:"button",onClick:()=>void R("refresh_snapshot"),style:ee(o),children:[t.jsx(Kt,{size:12})," Refresh snapshot and prepare retry"]}):null,H.includes("request_access")||H.includes("change_authorized_connection")?t.jsxs("button",{type:"button",onClick:()=>void re(),style:ee(o),children:[t.jsx(Ze,{size:12})," Change connection or request access"]}):null,H.includes("reapply_semantic_runtime")?t.jsxs("button",{type:"button",onClick:fe,style:ee(o),children:[t.jsx(Kt,{size:12})," Reapply semantic runtime settings"]}):null]})]}):t.jsxs("div",{style:{display:"grid",gap:8},children:[t.jsx(ct,{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:d,style:ee(o),children:[t.jsx(xn,{size:12})," Save as draft block"]}):null]})}),w?t.jsx("div",{role:"status",style:{fontSize:10.5,color:w.toLowerCase().includes("created")?"var(--status-success)":"var(--status-error)"},children:w}):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 ct({t:e,children:n}){return t.jsx("div",{style:{fontSize:11,color:e.textMuted},children:n})}function Se(e){return Array.isArray(e)?e.flatMap(n=>M(n)?[M(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 It(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 zt(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=>ze(se(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:qe(e),dqlArtifact:_e(e),...n?{result:{columns:n.columns,rows:n.rows.slice(0,24),rowCount:n.rowCount}}:{}}}function xt(e){return!e.artifacts.some(r=>!!Ht(se(r)))&&e.status!=="blocked"&&e.status!=="cancelled"&&e.stopReason!=="cancelled"&&e.status!=="needs_clarification"&&(e.artifacts.some(r=>r.kind==="answer"||r.kind==="research_run")||!!(_e(e)??qe(e)))}function $s({run:e,artifact:n,tab:r,t:i,appContext:s,onOpenApp:o,onChangeTab:a,onClose:c,onSaveBlock:d,onInsertSql:p,onInsertDql:g}){const l=se(n),u=_e(e)??yt(l),f=qe(e)??(typeof l.sql=="string"?l.sql:void 0),x=ze(l),m=lt(e,n),b=wn(e),k=Mr(e),O=jn(e),L=n.trustState==="certified",P=e.status==="cancelled"||e.stopReason==="cancelled"||e.route==="cancelled",q=!P&&(e.status==="blocked"||n.trustState==="blocked"),D=xt(e),U=Lr(l),N=Er({analytical:!!U,blocked:q,hasDql:!!(u!=null&&u.source),hasSql:!!f,hasLineage:k.length>0}),E=N.some(_=>_.id===r)?r:N[0].id,J=P?"Cancelled":q?"Blocked":L?"Certified":n.trustState==="governed"||n.trustState==="grounded"?"Governed":"AI-generated",Z=P?"var(--text-tertiary)":q?"var(--status-error)":L?"var(--status-success)":n.trustState==="governed"||n.trustState==="grounded"?"var(--accent)":"var(--status-warning)",C=P?"var(--bg-3)":q?"var(--status-error-bg)":L?"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:C,color:Z,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:lt(e,n)}),t.jsx("div",{style:{fontSize:11,color:i.textMuted,marginTop:2},children:Wt(n,l)})]}),t.jsx("span",{style:{border:`1px solid ${Z}`,color:Z,background:C,borderRadius:999,padding:"2px 8px",fontSize:10,fontWeight:700,flexShrink:0,marginTop:2},children:J}),t.jsx("button",{type:"button",onClick:c,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(Tt,{size:14})})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"10px 16px",borderBottom:"1px solid var(--border-subtle)"},children:[D?t.jsx(vn,{run:e,t:i,appContext:s,onOpenApp:o}):null,D?t.jsxs("button",{type:"button",className:"dql-hover",onClick:d,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(ht,{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(vi,{size:14})})]}),t.jsx("div",{style:{display:"flex",alignItems:"center",gap:16,padding:"0 16px",borderBottom:"1px solid var(--border-subtle)",flexShrink:0},children:N.map(_=>t.jsx("button",{type:"button",onClick:()=>a(_.id),style:{padding:"10px 1px",fontSize:12,fontWeight:600,cursor:"pointer",border:"none",background:"none",fontFamily:i.font,whiteSpace:"nowrap",color:E===_.id?i.textPrimary:i.textMuted,boxShadow:E===_.id?`inset 0 -2px 0 0 ${i.accent}`:"none"},children:_.label},_.id))}),t.jsxs("div",{style:{flex:1,minHeight:0,overflow:"auto",padding:"14px 16px 20px"},children:[E==="how"&&U?t.jsx(Bs,{run:e,contract:U,dqlArtifact:u,sql:f,lineage:k,t:i,onInsertSql:p,onInsertDql:g,onSaveBlock:d}):null,E==="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:f,dqlArtifact:u,result:x,chartConfig:x?Fe(l,x):void 0,title:m,sourceRunId:e.id,question:e.question}),style:ee(i),children:"Open DQL in notebook"}):null,t.jsx(Mt,{text:u.source,t:i,title:"Copy DQL"})]})]}),t.jsx("pre",{style:gt(i),children:u.source})]}):t.jsx(ct,{t:i,children:"The selected plan failed before a DQL source could be materialized. Review the Plan and Failure & repair sections."}):null,E==="sql"?f?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(f,m,{question:e.question,sourceRunId:e.id}),style:ee(i),children:"Open SQL in notebook"}):null,t.jsx(Mt,{text:f,t:i,title:"Copy SQL"})]})]}),t.jsx("pre",{style:gt(i),children:f})]}):t.jsx(ct,{t:i,children:"Compilation stopped before SQL was produced. The DQL, plan, trust evidence, and failure steps are still retained."}):null,E==="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."}),k.map(_=>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:_.name}),t.jsx("div",{style:{fontSize:10.5,color:i.textMuted,marginTop:2},children:[_.kind,_.detail].filter(Boolean).join(" · ")})]})]},`${_.kind??"asset"}:${_.name}`))]}):null,E==="trust"?t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[O?t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-start",padding:"10px 12px",borderRadius:8,background:L?"var(--status-success-bg)":"var(--status-warning-bg)",border:`1px solid ${L?"var(--status-success-border)":"var(--status-warning-border)"}`},children:[L?t.jsx(be,{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:O})]}):null,b.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:b.map(_=>t.jsxs("span",{style:Kr(i,_.certified),children:[_.certified?t.jsx(be,{size:11}):t.jsx(pt,{size:11}),t.jsx("span",{children:_.label})]},_.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(Gr,{run:e,t:i})]}):null]})]})}function Ls({t:e,text:n,source:r,left:i,top:s,draft:o,inputRef:a,onDraftChange:c,onClose:d,onSend:p}){const g=(l,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:l});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(Ue,{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:d,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(Tt,{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:a,value:o,onChange:l=>c(l.target.value),onKeyDown:l=>{l.key==="Enter"&&(l.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 cn(e,n){const r=e instanceof Error?e.message.trim():"";return e instanceof mi&&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 dn(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,a;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:(a=s.pages[0])==null?void 0:a.metadata.title}}),...e.filter(s=>!i.has(s.id)).map(s=>{var a,c,d;const o=((a=s.homepage)==null?void 0:a.type)==="dashboard"?s.homepage.id:(c=s.dashboards[0])==null?void 0:c.id;return{id:`project:${s.id}`,kind:"project",appId:s.id,name:s.name,pageId:o,pageTitle:(d=s.dashboards.find(p=>p.id===o))==null?void 0:d.title}})]}function vn({run:e,t:n,appContext:r,onOpenApp:i}){const[s,o]=h.useState(!1),[a,c]=h.useState(null),[d,p]=h.useState(!1),[g,l]=h.useState("list"),[u,f]=h.useState(""),[x,m]=h.useState(!1),[b,k]=h.useState(null),[O,L]=h.useState(""),[P,q]=h.useState(null),D=h.useRef(null),U=async()=>{c(null),p(!1);const[z,j]=await Promise.allSettled([ie.listAppsStrict(),ie.listAppBuilds()]);if(z.status==="rejected"&&j.status==="rejected"){c([]),p(!0);return}const K=Pr(z.status==="fulfilled"?z.value:[],j.status==="fulfilled"?j.value.drafts:[]);c(K),K.length===0&&l("new")},N=()=>{o(!0),k(null),l("list"),D.current=null,f(st(e.question)),L(st(e.question)),U()},E=()=>{x||(o(!1),k(null))},J=async(z,j,K,Y)=>{var Q,de;const te=O.trim()||st(e.question),B=_e(e),H=rn(e),ne=await ie.addAskResultToAppBuild(z.id,{expectedRevision:z.revision,expectedProposalHash:z.proposalHash,pageId:K,title:te,question:e.question,answer:e.answer??e.summary,certifiedBlockId:H,dqlSource:B==null?void 0:B.source,sql:qe(e),visualization:(Q=Gs(e))==null?void 0:Q.chart});q({appId:ne.draft.appId,draftId:ne.draft.id,pageId:ne.pageId,name:j,pageTitle:((de=ne.draft.pages.find(he=>he.id===ne.pageId))==null?void 0:de.metadata.title)??Y,tileTitle:te,kind:ne.deduped?"existing":H?"certified":B!=null&&B.source||qe(e)?"review":"narrative"}),window.dispatchEvent(new CustomEvent("dql-app-build-updated",{detail:{draft:ne.draft,pageId:ne.pageId,tileId:ne.tileId}})),o(!1)},Z=async z=>{if(z.draft)return z.draft;const K=(await ie.listAppBuilds()).drafts.find(Y=>{var te;return Y.state!=="project_published"&&((te=Y.baseApp)==null?void 0:te.appId)===z.appId});return K||(await ie.createAppBuild({baseAppId:z.appId,goal:`Edit ${z.name} with an Ask result`,authoringMode:"ai",sourcePolicy:rn(e)?"governed_only":"include_review_required",template:"blank",entrypoint:"ask"})).draft},C=async z=>{if(!x){m(!0),k(null);try{const j=await Z(z),K=(r==null?void 0:r.appId)===z.appId?r.dashboardId:z.pageId;await J(j,z.name,K,z.pageTitle)}catch(j){k(cn(j,"Could not add to app."))}finally{m(!1)}}},_=async()=>{var j,K;if(x)return;const z=u.trim()||st(e.question);m(!0),k(null);try{D.current||(D.current=(await ie.createAppBuild({name:z,goal:e.question,authoringMode:"ai",sourcePolicy:rn(e)?"governed_only":"include_review_required",template:"blank",entrypoint:"ask"})).draft),await J(D.current,z,(j=D.current.pages[0])==null?void 0:j.id,(K=D.current.pages[0])==null?void 0:K.metadata.title),D.current=null}catch(Y){k(cn(Y,"Could not create the app."))}finally{m(!1)}};return t.jsxs("div",{style:{position:"relative",display:"inline-flex",alignItems:"center",gap:6},children:[P?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(ut,{size:15})}),t.jsxs("span",{style:{display:"grid",gap:1,minWidth:0},children:[t.jsx("b",{style:{fontSize:11.5},children:P.kind==="existing"?"Already on this page":P.kind==="certified"?"Saved as a certified tile":P.kind==="review"?"Saved — review required":"Saved as editable narrative"}),t.jsxs("span",{title:dn(P.name,P.pageTitle),style:{fontSize:10.5,color:n.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[dn(P.name,P.pageTitle)," · editable draft"]}),t.jsxs("span",{title:P.tileTitle,style:{fontSize:10,color:n.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["Tile: ",P.tileTitle]}),P.kind==="review"||P.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(P.appId,P.pageId,P.draftId),style:{...ee(n),color:n.success,whiteSpace:"nowrap"},title:"Open the App page containing this tile",children:["Open App ",t.jsx(Ii,{size:12})]}):null]}):null,t.jsxs("button",{type:"button",className:"dql-hover dql-lift",onClick:N,style:P?ee(n):lr(n),children:[t.jsx(sn,{size:13}),P?"Add to another":"Add to app"]}),s?t.jsxs(t.Fragment,{children:[t.jsx("div",{onClick:E,style:{position:"fixed",inset:0,zIndex:40}}),t.jsxs("div",{style:to(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:E,style:{border:"none",background:"transparent",color:n.textMuted,cursor:"pointer",fontSize:15,lineHeight:1},children:"×"})]}),b?t.jsx("div",{style:{fontSize:11,color:n.error,marginBottom:7,lineHeight:1.4},children:b}):null,g==="new"?t.jsxs("div",{style:{display:"grid",gap:8},children:[t.jsx("input",{autoFocus:!0,value:u,onChange:z=>f(z.target.value),onKeyDown:z=>{z.key==="Enter"&&_()},placeholder:"App name",style:dr(n)}),t.jsxs("div",{style:{display:"flex",gap:6},children:[a&&a.length>0?t.jsx("button",{type:"button",className:"dql-hover",onClick:()=>l("list"),style:ee(n),children:"Back"}):null,t.jsxs("button",{type:"button",className:"dql-hover",disabled:x||!u.trim(),onClick:()=>void _(),style:{...lr(n),flex:1,justifyContent:"center"},children:[x?t.jsx(Ve,{size:13,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}}):t.jsx(ot,{size:13}),"Create draft & add"]})]})]}):a===null?t.jsx("div",{style:{fontSize:11.5,color:n.textMuted,padding:"8px 2px"},children:"Loading apps…"}):d?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 U(),style:ee(n),children:"Retry"}),t.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>l("new"),style:{...cr(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:O,onChange:z=>L(z.target.value),placeholder:st(e.question),maxLength:120,style:dr(n)})]}),t.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>l("new"),style:cr(n),children:[t.jsx(ot,{size:13})," New app…"]}),a.map(z=>t.jsxs("button",{type:"button",className:"dql-hover",disabled:x,onClick:()=>void C(z),style:no(n),children:[t.jsx(sn,{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:z.name}),t.jsx("small",{style:{color:n.textMuted},children:z.kind==="draft"?"Local editable draft":"Project App · creates a safe edit draft"})]})]},z.id))]})]})]}):null]})}function jn(e){var n;if(e.status==="cancelled"||e.stopReason==="cancelled"||e.route==="cancelled")return"Stopped by user. No result was accepted.";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(Sn(e)){const r=e.artifacts.map(o=>o.payload).filter(o=>!!(o&&typeof o=="object"&&!Array.isArray(o)));if(r.some(o=>{const a=o.result;return!!(a&&typeof a=="object"&&!Array.isArray(a))}))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 Sn(e){return e.artifacts.some(n=>{const r=n.payload;return!!(r&&typeof r=="object"&&!Array.isArray(r)&&r.exploratoryCandidate)})}function Ds(e){return e.status==="cancelled"||e.stopReason==="cancelled"||e.route==="cancelled"?"Stopped by user":e.trustState==="certified"?"Certified answer":e.route==="dql_block_draft"?"Draft block":Sn(e)?"Exploratory DBT-grounded answer":e.route==="semantic_answer"?"Semantic answer":e.route==="generated_answer"?"AI-generated answer":Cr[e.route]}function Ns({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,a=typeof n.proposalHash=="string"?n.proposalHash:void 0,[c,d]=h.useState(()=>o?Si(o):new Set),[p,g]=h.useState(!1),[l,u]=h.useState(null),[f,x]=h.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 m=async b=>{var O,L;g(!0),u(null);const k=await ie.commitAppAiBuild(s,{selectedTileIds:Array.from(c),expectedProposalHash:a,...b.appName?{appName:b.appName}:{},...b.pageTitle?{pageTitle:b.pageTitle}:{},...b.audience?{audience:b.audience}:{},...Object.keys(b.tileOverrides).length>0?{tileOverrides:b.tileOverrides}:{}});if(g(!1),!k.ok){u(k.error);return}x({appId:((O=k.app)==null?void 0:O.id)??k.session.appId??"",dashboardId:k.dashboardId??void 0,name:((L=k.app)==null?void 0:L.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:Ce(e.title)})]}),f?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(ut,{size:13})," Created ",f.name]}),f.appId&&i?t.jsx("button",{type:"button",className:"dql-hover",onClick:()=>i(f.appId,f.dashboardId),style:ee(r),children:"Open app"}):null]}):t.jsx(wi,{proposal:o,t:r,selected:c,onToggle:b=>{d(k=>{const O=new Set(k);return O.has(b)?O.delete(b):O.add(b),O})},onCreate:b=>void m(b),defaultName:e.title,busy:p,error:l,compact:!0})]})}function Fr({artifact:e,certifiedBlockName:n,initialResult:r,initialChartConfig:i,payload:s,executionTarget:o,t:a,themeMode:c,embedded:d=!1,expanded:p=!1}){var X;const[g,l]=h.useState(e),[u,f]=h.useState(()=>e.parameters??[]),[x,m]=h.useState(()=>({...e.parameterValues??{},...un(s)})),[b,k]=h.useState(r),[O,L]=h.useState(i),[P,q]=h.useState(!!n),[D,U]=h.useState(!1),[N,E]=h.useState(null),[J,Z]=h.useState(!1),[C,_]=h.useState(""),[z,j]=h.useState(""),K=h.useRef(!1),Y=h.useRef(e);Y.current=e;const te=ys(e);h.useEffect(()=>{const w=Y.current;if(l(w),Z(!1),!n){f(w.parameters??[]),m({...w.parameterValues??{},...un(s)}),q(!1);return}let G=!1;return q(!0),ie.getCertifiedBlockParameters(n).then(S=>{G||(f(S.parameters),m($=>({...Object.fromEntries(S.parameters.flatMap(oe=>oe.default===void 0?[]:[[oe.name,oe.default]])),...$})))}).catch(S=>{G||E(S instanceof Error?S.message:String(S))}).finally(()=>{G||q(!1)}),()=>{G=!0}},[te,n]);const B=async()=>{if(!K.current){K.current=!0,U(!0),E(null);try{const w=await ie.invokeDqlArtifact(g,x,void 0,n,o);k(w.result),l(w.artifact),w.result.chartConfig&&typeof w.result.chartConfig=="object"&&L(w.result.chartConfig),w.parameters.length>0&&f(w.parameters)}catch(w){E(w instanceof Error?w.message:String(w))}finally{K.current=!1,U(!1)}}},H=h.useMemo(()=>wr(g,b),[g,b]),ne=()=>{const w=H[0];w&&(_(w.column),j(w.values[0]==null?"":String(w.values[0])),Z(!0),E(null))},Q=async()=>{try{const w=g.kind==="sql_block"?await ie.addDqlArtifactResultFilter(g,b.columns,C,z,o):ms(g,b,C,z);l(w.artifact),f(w.artifact.parameters??[]),m(G=>({...G,...w.artifact.parameterValues??{}})),Z(!1),E(null)}catch(w){E(w instanceof Error?w.message:String(w))}},de=u.some(vr),he=Object.entries(x).filter(([,w])=>w!=null&&w!=="");return t.jsxs("div",{style:{display:"grid",gap:9},children:[he.length>0?t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap",padding:d?"8px 12px 0":0},children:[t.jsx("span",{style:{fontSize:10.5,fontWeight:750,color:a.textMuted},children:"Applied inputs"}),he.map(([w,G])=>t.jsxs("span",{style:{fontSize:10.5,color:a.textSecondary,border:`1px solid ${a.cellBorder}`,background:a.appBg,borderRadius:999,padding:"2px 7px"},children:[w.replace(/_/g," ")," = ",Ps(G)]},w))]}):null,P?t.jsx("div",{style:{fontSize:10.5,color:a.textMuted},children:"Loading reusable inputs…"}):de||H.length>0?t.jsxs("div",{style:{display:"grid",gap:8,padding:9,margin:d?"0 12px":0,border:`1px solid ${a.cellBorder}`,borderRadius:7,background:a.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:a.textPrimary},children:"Change DQL inputs"}),t.jsx("div",{style:{fontSize:10,color:a.textMuted},children:"Reruns this DQL artifact directly. It does not start another AI search."})]}),H.length>0?t.jsxs("button",{type:"button",onClick:ne,style:ee(a),children:[t.jsx(ot,{size:11})," Add result filter"]}):null,t.jsxs("button",{type:"button",disabled:D,onClick:()=>void B(),style:{...ee(a),color:a.accent,opacity:D?.65:1},children:[D?t.jsx(Ve,{size:11,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}}):t.jsx(Ue,{size:11}),D?"Running…":"Apply"]})]}),J?t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(150px, 1fr) minmax(150px, 1fr) auto auto",gap:7,alignItems:"end",padding:8,border:`1px solid ${a.cellBorder}`,borderRadius:7,background:a.cellBg},children:[t.jsxs("label",{style:{display:"grid",gap:4,fontSize:10,fontWeight:750,color:a.textSecondary},children:["Result column",t.jsx("select",{"aria-label":"Result column for new DQL input",value:C,onChange:w=>{const G=w.target.value,S=H.find($=>$.column===G);_(G),j((S==null?void 0:S.values[0])==null?"":String(S.values[0]))},style:ur(a),children:H.map(w=>t.jsx("option",{value:w.column,children:w.column.split("_").join(" ")},w.column))})]}),t.jsxs("label",{style:{display:"grid",gap:4,fontSize:10,fontWeight:750,color:a.textSecondary},children:["Default value",t.jsx("input",{"aria-label":"Default value for new DQL input",value:z,list:`ask-filter-${C}`,onChange:w=>j(w.target.value),style:ur(a)}),t.jsx("datalist",{id:`ask-filter-${C}`,children:(((X=H.find(w=>w.column===C))==null?void 0:X.values)??[]).map(w=>t.jsx("option",{value:String(w)},`${typeof w}:${String(w)}`))})]}),t.jsx("button",{type:"button",onClick:()=>{Q()},style:{...ee(a),color:a.accent},children:"Add input"}),t.jsx("button",{type:"button",onClick:()=>Z(!1),style:ee(a),children:"Cancel"})]}):null,u.length>0?t.jsx(ns,{parameters:u,values:x,onChange:(w,G)=>m(S=>({...S,[w]:G})),t:a}):null,H.length>0?t.jsx("div",{style:{fontSize:9.5,color:a.textMuted},children:"Extra filters are available only for semantic dimensions in this result. They stay transient until you explicitly save a block."}):null]}):null,N?t.jsx("div",{style:{fontSize:10.5,color:a.error},children:N}):null,t.jsx(gn,{result:b,themeMode:c,t:a,chartConfig:O,embedded:d,tabLabels:d?{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 Ps(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:a,sourceQuestion:c,onOpenBlock:d,onOpenResearch:p,onOpenApp:g,onNextAction:l}){const u=e.payload&&typeof e.payload=="object"?e.payload:{};if(e.kind==="app_proposal")return t.jsx(Ns,{artifact:e,payload:u,t:n,onOpenApp:g});const f=ze(u),x=yt(u),m=Ht(u),b=typeof u.sql=="string"?u.sql:typeof u.sqlPreview=="string"?u.sqlPreview:typeof u.proposedSql=="string"?u.proposedSql:void 0,k=typeof u.name=="string"?u.name:e.title,O=typeof u.path=="string"?u.path:e.ref,L=u.draftBlock&&typeof u.draftBlock=="object"&&!Array.isArray(u.draftBlock)?u.draftBlock:void 0,P=typeof(L==null?void 0:L.path)=="string"?L.path:void 0,q=typeof(L==null?void 0:L.name)=="string"?L.name:void 0,D=(x==null?void 0:x.sourcePath)??P??(e.kind==="dql_block_draft"?O:void 0),U=(x==null?void 0:x.name)??q??k,N=(x==null?void 0:x.kind)==="sql_block"||e.kind==="dql_block_draft"?"Open DQL draft":"Open DQL artifact",E=u.plan&&typeof u.plan=="object"?u.plan:void 0,J=Array.isArray(E==null?void 0:E.steps)?E.steps:[],Z=Array.isArray(E==null?void 0:E.gaps)?E.gaps.map(String):[],C=typeof u.researchRunId=="string"?u.researchRunId:e.kind==="research_run"&&typeof e.ref=="string"?e.ref:void 0,_=typeof u.notebookPath=="string"?u.notebookPath:void 0,z=Array.isArray(u.generatedPaths)?u.generatedPaths.filter(B=>typeof B=="string"):[],j=u.narration&&typeof u.narration=="object"?u.narration:void 0,K=Array.isArray(j==null?void 0:j.keyFindings)?j.keyFindings.filter(B=>typeof B=="string"):[],Y=typeof(j==null?void 0:j.recommendation)=="string"?j.recommendation:void 0,te=e.trustState==="certified"?Wr(e,u):void 0;if(e.kind==="dql_block_draft"){const B=ne=>Array.isArray(ne)?ne.filter(Q=>typeof Q=="string"):void 0,H=u.certifierVerdict&&typeof u.certifierVerdict=="object"?u.certifierVerdict:void 0;return t.jsx(es,{t:n,name:typeof u.name=="string"?u.name:k,status:"draft",description:typeof u.description=="string"?u.description:void 0,dql:(x==null?void 0:x.source)??(typeof u.dqlSource=="string"?u.dqlSource:void 0),sqlPreview:b,grain:typeof u.grain=="string"?u.grain:void 0,outputs:B(u.outputs),dimensions:B(u.dimensions)??(x==null?void 0:x.dimensions),entities:B(u.entities),certifierVerdict:H?{blocking:B(H.blocking)??[],warnings:B(H.warnings)??[],ready:!!H.ready}:void 0,actions:t.jsxs(t.Fragment,{children:[b&&s?t.jsx("button",{type:"button",onClick:()=>s({sql:b,dqlArtifact:x,result:f,chartConfig:f?Fe(u,f):void 0,title:k,sourceRunId:a,question:c}),style:ee(n),children:o??"Insert as DQL cell"}):b&&i?t.jsx("button",{type:"button",onClick:()=>i(b,k,{question:c,sourceRunId:a}),style:ee(n),children:"Insert SQL preview"}):null,D&&d?t.jsx("button",{type:"button",onClick:()=>d(D,U),style:ee(n),children:N}):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:Ce(e.title)})]}),K.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:K,t:n,renderItem:(B,H)=>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:B})]},H)})]}):J.length>0?t.jsx("div",{style:{display:"grid",gap:5},children:t.jsx(rr,{items:J,t:n,renderItem:(B,H)=>t.jsxs("div",{style:{fontSize:11.5,color:n.textSecondary,lineHeight:1.35},children:[H+1,". ",String(B.thought??B.expectation??"Research step")]},H)})}):null,Y?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:Y})]}):null,f?x?t.jsx(Fr,{artifact:x,certifiedBlockName:te,initialResult:f,initialChartConfig:Fe(u,f),payload:u,t:n,themeMode:r}):t.jsx(gn,{result:f,themeMode:r,t:n,chartConfig:Fe(u,f)}):null,x?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(ht,{size:12}),t.jsx("span",{children:"View DQL artifact"}),t.jsxs("span",{style:{marginLeft:"auto",display:"inline-flex",alignItems:"center",gap:4},children:[x.source?t.jsx(Mt,{text:x.source,t:n,title:"Copy DQL"}):null,!D&&l?t.jsxs("button",{type:"button",className:"dql-hover",title:"Save this DQL as a reusable block",onClick:B=>{B.preventDefault(),B.stopPropagation(),l({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]})]}),x.sourcePath?t.jsx("div",{style:{marginTop:6,fontSize:10.5,color:n.textMuted},children:x.sourcePath}):null,t.jsx("pre",{style:{...gt(n),marginTop:6},children:x.source})]}):null,b?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:Ur(!!x)}),t.jsx("span",{style:{marginLeft:"auto",display:"inline-flex",alignItems:"center",gap:4},children:t.jsx(Mt,{text:b,t:n,title:"Copy SQL"})})]}),t.jsx("pre",{style:{...gt(n),marginTop:6},children:b})]}):null,Z.length>0?t.jsxs("div",{style:{fontSize:11.5,color:n.textSecondary,lineHeight:1.4},children:["Gaps: ",Z.join(", ")]}):null,z.length>0?t.jsxs("div",{style:{fontSize:11.5,color:n.textSecondary,lineHeight:1.4},children:["Files: ",z.join(", ")]}):null,t.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[C&&p?t.jsx("button",{type:"button",onClick:()=>p(C,_),style:ee(n),children:"Open research"}):null,b&&s?t.jsx("button",{type:"button",onClick:()=>s({sql:b,dqlArtifact:x,result:f,chartConfig:f?Fe(u,f):void 0,title:k,mixedSourcePlan:m,sourceRunId:a,question:c}),style:m?{...ee(n),background:n.accent,borderColor:n.accent,color:"#fff",fontWeight:850,padding:"7px 11px"}:ee(n),children:m?"Add workflow to notebook":x?"Insert as DQL cell":"Add SQL to notebook"}):b&&i?t.jsx("button",{type:"button",onClick:()=>i(b,k,{question:c,sourceRunId:a}),style:ee(n),children:"Insert SQL preview"}):null,D&&d?t.jsx("button",{type:"button",onClick:()=>d(D,U),style:ee(n),children:N}):null]})]})}function Fs({run:e}){return e.trustState==="certified"?t.jsx(be,{size:16,color:"#16a34a"}):e.trustState==="governed"?t.jsx(be,{size:16,color:"#2563eb"}):e.trustState==="grounded"?t.jsx(be,{size:16,color:"#2563eb"}):e.status==="completed"?t.jsx(ut,{size:16,color:"#16a34a"}):e.status==="cancelled"||e.stopReason==="cancelled"?t.jsx(at,{size:16,color:"#737373"}):e.status==="blocked"?t.jsx(at,{size:16,color:"#ef4444"}):t.jsx(at,{size:16,color:"#d97706"})}function et({kind:e}){return e==="sql_cell"?t.jsx(hn,{size:14}):e==="dql_block_draft"?t.jsx(ht,{size:14}):e==="app_draft"||e==="app_proposal"?t.jsx(sn,{size:14}):e==="research_run"?t.jsx(pt,{size:14}):t.jsx(Ue,{size:14})}function Ws({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.status==="cancelled"||e.stopReason==="cancelled"?"Cancelled":e.trustState==="certified"?"Certified":e.route==="dql_block_draft"?"Draft":Sn(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(be,{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 nn({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 Os(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(ft,{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=Os(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(Ft,{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 Hs(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 Qs(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 Ce(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 Vs(e,n){const r=i=>i.toLowerCase().replace(/[\s.,!?'"()`*_-]+/g," ").trim();return r(e)===r(n)}function ze(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 a=xi(o),c=a.rows,d=a.columns;if(!(c.length===0&&d.length===0&&typeof o.rowCount!="number"))return{columns:d,rows:c,rowCount:a.rowCount,...a.resultFingerprint?{resultFingerprint:a.resultFingerprint}:{},...a.executionReceipt?{executionReceipt:a.executionReceipt}:{},...a.trustState?{trustState:a.trustState}:{},...a.answerTier?{answerTier:a.answerTier}:{},...a.executionTime!==void 0?{executionTime:a.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,a=typeof i.chart=="string"?i.chart:s,c=a?a.toLowerCase().replace(/_/g,"-")==="single-value"?"kpi":a:void 0,d=n.columns,p=u=>typeof i[u]=="string"&&d.includes(i[u])?i[u]:void 0,g=Array.isArray(i.metrics)?i.metrics.filter(u=>typeof u=="string"&&d.includes(u)):[],l={...c?{chart:c}:{},...c?{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(l).length>0?l: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 yt(e){const n=Ge(e.dqlArtifact);if(n)return n;const r=e.researchRun&&typeof e.researchRun=="object"&&!Array.isArray(e.researchRun)?e.researchRun:void 0;return Ge(r==null?void 0:r.dqlArtifact)}function Ur(e){return e?"View compiled SQL preview":"View SQL preview"}function Mt({text:e,t:n,title:r="Copy"}){const[i,s]=h.useState(!1),o=async a=>{a.preventDefault(),a.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 se(e){return e.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{}}function Us(e){var i,s,o;const n=[],r=new Set;for(const a of e.artifacts){const c=se(a),d=Array.isArray(c.memoryContext)?c.memoryContext:[];for(const g of d){if(!g||typeof g!="object")continue;const l=g,u=typeof l.title=="string"?l.title.trim():"";!u||r.has(`m:${u}`)||(r.add(`m:${u}`),n.push({kind:"memory",id:typeof l.id=="string"?l.id:void 0,label:u,detail:typeof l.content=="string"?l.content:void 0}))}const p=Array.isArray(c.appliedHints)?c.appliedHints:[];for(const g of p){if(!g||typeof g!="object")continue;const l=g,u=typeof l.title=="string"?l.title.trim():"";if(!u||r.has(`h:${u}`))continue;r.add(`h:${u}`);const f=typeof((i=l.lesson)==null?void 0:i.rule)=="string"?l.lesson.rule:typeof l.guidance=="string"?l.guidance:void 0,x=[typeof l.scopeReason=="string"?l.scopeReason:void 0,typeof l.graphReason=="string"?l.graphReason:void 0].filter(Boolean).join("; "),m=typeof((s=l.matchSignals)==null?void 0:s.lexicalScore)=="number"?l.matchSignals.lexicalScore:void 0,b=typeof((o=l.matchSignals)==null?void 0:o.graphScore)=="number"?l.matchSignals.graphScore:void 0,k=m!==void 0||b!==void 0?`Signals: lexical ${(m??0).toFixed(2)}, graph ${(b??0).toFixed(2)}`:void 0;n.push({kind:"hint",id:typeof l.hintId=="string"?l.hintId:void 0,label:u,detail:[f,x?`Matched: ${x}`:void 0,k].filter(Boolean).join(" · ")||void 0})}}return n.slice(0,6)}function Gr({run:e,t:n}){const[r,i]=h.useState(!1),[s,o]=h.useState(new Set),a=h.useMemo(()=>Us(e).filter(d=>!d.id||!s.has(d.id)),[e,s]);if(a.length===0)return null;const c=async d=>{try{await ie.deleteAgentMemory(d),o(p=>new Set(p).add(d))}catch{}};return t.jsxs("div",{style:{display:"grid",gap:6,gridTemplateColumns:"minmax(0, 1fr)",minWidth:0},children:[t.jsxs("button",{type:"button",onClick:()=>i(d=>!d),style:Ks(n),children:[t.jsx(Et,{size:11}),t.jsxs("span",{children:["Applied ",a.length," learning",a.length>1?"s":""]}),r?t.jsx(yr,{size:11}):t.jsx(Dt,{size:11})]}),r?t.jsxs("div",{style:Ys(n),children:[a.map(d=>t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-start"},children:[t.jsx("span",{style:Xs(n,d.kind),children:d.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:d.label}),d.detail?t.jsx("div",{style:{fontSize:11,color:n.textMuted,lineHeight:1.4,marginTop:1},children:d.detail}):null]}),d.kind==="memory"&&d.id?t.jsx("button",{type:"button",onClick:()=>void c(d.id),style:Js(n),children:"Stop using"}):null]},`${d.kind}:${d.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 wn(e){const n=[],r=new Set,i=e.trustState==="certified",s=(o,a)=>{typeof o!="string"||!o.trim()||r.has(o)||(r.add(o),n.push({label:o,certified:a}))};for(const o of e.artifacts){const a=se(o);o.ref&&s(o.ref,i);const c=a.plan&&typeof a.plan=="object"?a.plan:void 0;Array.isArray(c==null?void 0:c.sources)&&c.sources.forEach(d=>s(d,i)),s(a.sourceCertifiedBlock,!0)}return n.slice(0,4)}function qe(e){for(const n of e.artifacts){const r=se(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=Ge(r.dqlArtifact),a=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 a=="string"&&a.trim())return a}}function rn(e){var n;if(e.trustState==="certified")for(const r of e.artifacts){const i=se(r),s=i.blockName??i.blockId??((n=Ge(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=se(n),i=ze(r);if(!i)continue;const s=Fe(r,i);if(s)return s}}function _e(e){for(const n of e.artifacts){const r=se(n),i=Ge(r.dqlArtifact);if(i)return i;const s=r.researchRun&&typeof r.researchRun=="object"&&!Array.isArray(r.researchRun)?r.researchRun:void 0,o=Ge(s==null?void 0:s.dqlArtifact);if(o)return o}}function Bt(e){const n=e.route==="dql_block_draft"&&e.status!=="blocked"&&e.status!=="cancelled"&&e.stopReason!=="cancelled"&&e.status!=="needs_clarification";if(e.route==="certified_answer"||!xt(e)&&!n)return;const r=_e(e),i=qe(e);if(!((!(r!=null&&r.source)||r.sourcePath)&&!i)){for(const s of e.artifacts){const o=se(s),a=ze(o),c=Ht(o);if(a)return{sql:i,dqlArtifact:r,result:a,chartConfig:Fe(o,a),title:(r==null?void 0:r.name)??s.title??e.question,mixedSourcePlan:c,sourceRunId:e.id,question:e.question,executionTarget:e.executionTarget};if(c)return{sql:i,dqlArtifact:r,title:(r==null?void 0:r.name)??s.title??e.question,mixedSourcePlan:c,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 Ht(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 Ks(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 Ys(e){return{display:"grid",gap:8,padding:10,borderRadius:8,background:e.cellBg,border:`1px solid ${e.headerBorder}`}}function Xs(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 Js(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 Zs(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{...Zs(e),width:40,height:40}}function $t(e){return{...Pt(e,{variant:"secondary",size:"md",pill:!0}),fontWeight:550}}function eo(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{...Pt(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 to(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 no(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 cr(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 dr(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 ro(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 io(e){return{alignSelf:"flex-start",maxWidth:"92%",color:e.textPrimary,border:`1px solid ${e.cellBorder}`,background:e.appBg,borderRadius:10,padding:"10px 12px"}}function so(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 oo(e){return{border:`1px solid ${e.headerBorder}`,background:e.cellBg,borderRadius:8,padding:9,fontSize:12.5,color:e.textPrimary,lineHeight:1.45}}function gt(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 ee(e){return Pt(e,{variant:"secondary",size:"sm"})}const Lt={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,a,c,d,p,g,l;if(e.status==="cancelled"||e.stopReason==="cancelled"||e.route==="cancelled"||((r=(n=e.diagnosticReceipt)==null?void 0:n.failure)==null?void 0:r.code)==="RUN_CANCELLED")return"cancel";for(const u of e.artifacts??[]){const f=se(u),x=(i=f==null?void 0:f.warehouseFailure)==null?void 0:i.origin,m=typeof((s=f==null?void 0:f.analyticalFailure)==null?void 0:s.code)=="string"?f.analyticalFailure.code:"";if((f==null?void 0:f.refusalCode)==="modeling_gap")return"modeling_gap";if(((o=f==null?void 0:f.aggregationSafetyProof)==null?void 0:o.status)==="blocked")return"proof_integrity";if(["IDENTIFIER_SCOPE_INVALID","EXECUTION_TARGET_MISMATCH","SEMANTIC_TARGET_BINDING_MISSING","SEMANTIC_SOURCE_DRIFT"].includes(m))return"identity_integrity";if(["POLICY_DENIED","PERMISSION_DENIED"].includes(m))return"policy";if(m==="RESULT_CONTRACT_MISMATCH")return"result_contract";if(["TIMEOUT","SEMANTIC_COMPILATION_TIMEOUT"].includes(m))return"timeout";if(m==="EXECUTION_CANCELLED")return"cancel";if(["COMPILATION_FAILED","DIALECT_ERROR","SEMANTIC_ADAPTER_NOT_READY"].includes(m))return"compile";if(typeof x=="string"&&x in Lt)return x;if(((a=f==null?void 0:f.providerFailure)==null?void 0:a.code)==="orchestration_budget_exhausted"||((c=f==null?void 0:f.providerFailure)==null?void 0:c.code)==="PROVIDER_DISPATCH_BUDGET_EXHAUSTED")return"orchestration_budget";if(f!=null&&f.providerFailure||(f==null?void 0:f.refusalCode)==="provider_error")return"provider";if((f==null?void 0:f.refusalCode)==="ambiguous")return"ambiguity";if((f==null?void 0:f.refusalCode)==="grounding_gap")return"retrieval_gap"}return((p=(d=e.diagnosticReceipt)==null?void 0:d.failure)==null?void 0:p.code)==="orchestration_budget_exhausted"?"orchestration_budget":((l=(g=e.diagnosticReceipt)==null?void 0:g.failure)==null?void 0:l.code)==="AI_PROVIDER_FAILURE"?"provider":"unknown"}function Xr(e){for(const n of e.artifacts??[]){const r=se(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 ao({run:e,detail:n,threadId:r,onRepaired:i,t:s}){const o=Yr(e),a=Lt[o]??Lt.unknown,[c,d]=h.useState(!1),[p,g]=h.useState(null),l=Jr(e),u=async()=>{if(!c){d(!0),g(null);try{const f=await ie.repairAgentRunExecution(e.id,r);i(f.run)}catch(f){g(f instanceof Error?f.message:String(f))}finally{d(!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:a.title})]}),t.jsx("div",{style:{fontSize:12.5,lineHeight:1.6,color:s.textSecondary,wordBreak:"break-word"},children:Ce(n)}),t.jsx("div",{style:{fontSize:11.5,lineHeight:1.5,color:s.textMuted},children:a.hint}),l?t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",marginTop:2},children:[t.jsxs("button",{type:"button",className:"dql-hover",disabled:c,onClick:()=>void u(),style:{...ee(s),opacity:c?.7:1},children:[t.jsx(Ft,{size:12})," ",c?"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:Ce(p)}):null]})}function Zr(e){var r,i,s;for(const o of e.artifacts??[]){const a=se(o),c=a==null?void 0:a.warehouseFailure,d=[c==null?void 0:c.redactedMessage,c==null?void 0:c.diagnostic,a==null?void 0:a.executionError,(r=a==null?void 0:a.refusalDetails)==null?void 0:r.message].find(p=>typeof p=="string"&&p.trim().length>0);if(d)return d}const n=lo(e);return n||e.summary||((s=(i=e.diagnosticReceipt)==null?void 0:i.failure)==null?void 0:s.message)}function lo(e){var r;const n=[M((r=M(e.diagnosticReceipt))==null?void 0:r.resolvedAnalyticalPlan),...(e.artifacts??[]).flatMap(i=>{var o;const s=se(i);return[M(s.resolvedAnalyticalPlan),M((o=M(s.diagnosticReceipt))==null?void 0:o.resolvedAnalyticalPlan)]})].filter(i=>!!i);for(const i of n){const s=M(i.query),a=[...Se(s==null?void 0:s.measures).map(p=>({kind:"metric",binding:p})),...Se(s==null?void 0:s.dimensions).map(p=>({kind:"dimension",binding:p})),...Se(s==null?void 0:s.filters).flatMap(p=>{const g=M(p.binding);return g?[{kind:"filter",binding:g}]:[]})].find(({binding:p})=>p.status==="ambiguous"||p.status==="unresolved");if(!a)continue;const c=I(a.binding.requested)||`requested ${a.kind}`,d=Array.isArray(a.binding.candidateIds)?a.binding.candidateIds.filter(p=>typeof p=="string").map(co):[];return a.binding.status==="ambiguous"&&d.length>1?`I found more than one governed ${a.kind} for “${c}”: ${d.join(" or ")}. Choose one before I run the query.`:`I couldn’t identify one governed ${a.kind} for “${c}”. Review that model binding before retrying.`}}function co(e){return(e.split(/[:./]/).filter(Boolean).at(-1)??e).replace(/[_-]+/g," ").replace(/\b\w/g,r=>r.toUpperCase())}const jo=Object.freeze(Object.defineProperty({__proto__:null,ASK_FAILURE_PRESENTATION:Lt,UnifiedAgentRunPanel:vs,agentRunHistoryFromItems:Ar,agentRunPerformanceRows:Dr,analyticalInspectorContract:Lr,analyticalInspectorSections:Es,analyticalRepairActionLabels:Ms,appPinDestinationLabel:dn,artifactReadyPayloadFromRun:Bt,artifactSqlDisclosureLabel:Ur,askAppDestinations:Pr,askAppWriteErrorMessage:cn,askArtifactMeta:Wt,askFailureDetail:Zr,askFailureOrigin:Yr,askInspectorTabsForState:Er,askRunAllowsExecutionRepair:Jr,askRunCaptureWarning:Xr,clarificationSelectionInput:zt,completedRunGuidanceFor:_r,deriveResultChartConfig:ki,extractResult:ze,hasAnalyticalInspectorContract:Ot,inlineAskChartConfig:Vr,isAgentRunPinnable:xt,liveAgentActivityFor:Tr,longRunGuidanceFor:zr,preferredAskInspectorTab:bn,replacePresentedAgentRun:kr,researchSourceFromRun:Nr,resolveArtifactDqlView:yt,resolvedParameterValues:un,selectAgentExecutionConnection:qr,threadItemsFromTurns:Ir,trustExplainer:jn,usePersistedAgentThreadId:Ai},Symbol.toStringTag,{value:"Module"}));export{ns as B,yr as C,Hn as S,vs as U,Vi as a,Zi as b,jo 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-ByTDPDaH.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-ByTDPDaH.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-ByTDPDaH.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-ByTDPDaH.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-ByTDPDaH.js";/**
2
2
  * @license lucide-react v0.563.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.