@duckcodeailabs/dql-cli 1.14.3-rc.1 → 1.14.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/args.d.ts +2 -0
- package/dist/args.d.ts.map +1 -1
- package/dist/args.js +12 -0
- package/dist/args.js.map +1 -1
- package/dist/ask-runtime/analytical-planner.d.ts +14 -0
- package/dist/ask-runtime/analytical-planner.d.ts.map +1 -0
- package/dist/ask-runtime/analytical-planner.js +197 -0
- package/dist/ask-runtime/analytical-planner.js.map +1 -0
- package/dist/ask-runtime/readiness.d.ts +36 -0
- package/dist/ask-runtime/readiness.d.ts.map +1 -0
- package/dist/ask-runtime/readiness.js +65 -0
- package/dist/ask-runtime/readiness.js.map +1 -0
- package/dist/assets/dql-notebook/assets/{AgentLogPage-Jbyb4so-.js → AgentLogPage-XonDlOVv.js} +1 -1
- package/dist/assets/dql-notebook/assets/{AiBuildDialog-Du07X1qO.js → AiBuildDialog-DwHVVFIS.js} +1 -1
- package/dist/assets/dql-notebook/assets/{AiBuildResult-xKtGthWv.js → AiBuildResult-BImB4Wej.js} +1 -1
- package/dist/assets/dql-notebook/assets/{AiSidePanel-CE_L04dK.js → AiSidePanel-D7fFBhgc.js} +1 -1
- package/dist/assets/dql-notebook/assets/{AnalyticsHome-CiUE10uF.js → AnalyticsHome-CHvGWG92.js} +1 -1
- package/dist/assets/dql-notebook/assets/{AppsView-DlNaTuwD.js → AppsView-DNhs0MyO.js} +4 -4
- package/dist/assets/dql-notebook/assets/{AskObservabilityPage-DracZPI9.js → AskObservabilityPage-1WYjAf8-.js} +1 -1
- package/dist/assets/dql-notebook/assets/AskTracePage-D6_RunIf.js +8 -0
- package/dist/assets/dql-notebook/assets/{BlockStudio-DQS5Hcq9.js → BlockStudio-DWMOCHy5.js} +1 -1
- package/dist/assets/dql-notebook/assets/{BusinessArtifactView-CqV4i9l_.js → BusinessArtifactView-guqlfQ0j.js} +1 -1
- package/dist/assets/dql-notebook/assets/{DbtFirstModelingPage-JKhB_Y2H.js → DbtFirstModelingPage-DE7ewjMK.js} +1 -1
- package/dist/assets/dql-notebook/assets/{GitPage-DjaNp0o3.js → GitPage-CM3cgHtf.js} +1 -1
- package/dist/assets/dql-notebook/assets/{GlobalAiRail-CsV3zlc8.js → GlobalAiRail-BWfeK8lb.js} +1 -1
- package/dist/assets/dql-notebook/assets/{GovernedContextPage-uXUHUOIJ.js → GovernedContextPage-2Ld4yIgE.js} +1 -1
- package/dist/assets/dql-notebook/assets/{HelpDocsPage-Hbh9IeYB.js → HelpDocsPage-BxBzoxBO.js} +1 -1
- package/dist/assets/dql-notebook/assets/{HomePage-CRRl-R_v.js → HomePage-D4ZjCFfB.js} +1 -1
- package/dist/assets/dql-notebook/assets/{LineageDAG-OMUP2sbl.js → LineageDAG-DLdogZMo.js} +1 -1
- package/dist/assets/dql-notebook/assets/{LineageDetailView-C964BLuV.js → LineageDetailView-CqPB_tFP.js} +1 -1
- package/dist/assets/dql-notebook/assets/{LineageDrawer-CzY0nfpD.js → LineageDrawer-LZyR3zHf.js} +1 -1
- package/dist/assets/dql-notebook/assets/{LineagePathBreadcrumb-0Gi-Fm1B.js → LineagePathBreadcrumb-BZ7EcIxp.js} +1 -1
- package/dist/assets/dql-notebook/assets/{MiniLineageGraph-wn0wLc9m.js → MiniLineageGraph-Be_kqIq2.js} +1 -1
- package/dist/assets/dql-notebook/assets/{NewBlockModal-kMAzk91d.js → NewBlockModal-C9MKCa6R.js} +1 -1
- package/dist/assets/dql-notebook/assets/{NewNotebookModal-D_cWd_6M.js → NewNotebookModal-ZxHbTU9u.js} +1 -1
- package/dist/assets/dql-notebook/assets/{NotebookEditor-Bax0lxaz.js → NotebookEditor-Bh39Vsg0.js} +1 -1
- package/dist/assets/dql-notebook/assets/{ReadinessPage-DEUIXQQY.js → ReadinessPage-jKOBKkED.js} +1 -1
- package/dist/assets/dql-notebook/assets/{SetupOnboarding-CyE-Ex41.js → SetupOnboarding-BRut9nLO.js} +1 -1
- package/dist/assets/dql-notebook/assets/{SkillsPage-QgvKGPxE.js → SkillsPage-D9msUOxY.js} +1 -1
- package/dist/assets/dql-notebook/assets/{TrustBadge-D5CGp0cu.js → TrustBadge-D1CGSj0Y.js} +1 -1
- package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel-BexNjqJd.js +88 -0
- package/dist/assets/dql-notebook/assets/{answer-to-notebook-tACdCsTV.js → answer-to-notebook-zHFOdR6E.js} +1 -1
- package/dist/assets/dql-notebook/assets/{arrow-left-CF6wxXU5.js → arrow-left-C1tZBhgf.js} +1 -1
- package/dist/assets/dql-notebook/assets/{arrow-right-C7G3M_S8.js → arrow-right-BP5vPPNo.js} +1 -1
- package/dist/assets/dql-notebook/assets/{book-open-text-DDBO8G7L.js → book-open-text-BD3-ATYI.js} +1 -1
- package/dist/assets/dql-notebook/assets/{chevron-left-DxajrX2v.js → chevron-left-3opVgscY.js} +1 -1
- package/dist/assets/dql-notebook/assets/{circle-x-HBvXjnT6.js → circle-x-Bg9-70KN.js} +1 -1
- package/dist/assets/dql-notebook/assets/{clock-3-CJIdsPLt.js → clock-3-DLV5puGW.js} +1 -1
- package/dist/assets/dql-notebook/assets/{external-link-WciAU8Bu.js → external-link-BjD8w9QU.js} +1 -1
- package/dist/assets/dql-notebook/assets/{grip-vertical-DVu7ok6x.js → grip-vertical-DqIc09oX.js} +1 -1
- package/dist/assets/dql-notebook/assets/{index-D3wnucQC.js → index-C9KfoqCR.js} +2 -2
- package/dist/assets/dql-notebook/assets/{link-2-C6uQx50X.js → link-2-5s0hUu6w.js} +1 -1
- package/dist/assets/dql-notebook/assets/{list-tree-DapsIuQB.js → list-tree-67yz_uCY.js} +1 -1
- package/dist/assets/dql-notebook/assets/{minimize-2-BlVoipnT.js → minimize-2-BJw5tlPC.js} +1 -1
- package/dist/assets/dql-notebook/assets/{panel-right-open-DcnKWxfx.js → panel-right-open-CyhTG-tw.js} +1 -1
- package/dist/assets/dql-notebook/assets/{play-CNuRuaAs.js → play-CsY8D5M2.js} +1 -1
- package/dist/assets/dql-notebook/assets/{rotate-ccw-B2p953Zh.js → rotate-ccw-RvwtBcw9.js} +1 -1
- package/dist/assets/dql-notebook/assets/{semantic-fields-2fWgkTJc.js → semantic-fields-EorgHwAj.js} +1 -1
- package/dist/assets/dql-notebook/assets/{sliders-horizontal-DwRTu1w4.js → sliders-horizontal-jQ_fUiYf.js} +1 -1
- package/dist/assets/dql-notebook/assets/{star-Cbaj4F3i.js → star-N_C8YvbB.js} +1 -1
- package/dist/assets/dql-notebook/assets/{style-NlN9F6JE.js → style-D6AlWDHX.js} +1 -1
- package/dist/assets/dql-notebook/assets/{triangle-alert-BPHvH1wA.js → triangle-alert-D1WefIrN.js} +1 -1
- package/dist/assets/dql-notebook/assets/{upload-DIqK0KE1.js → upload-CFJjpPL4.js} +1 -1
- package/dist/assets/dql-notebook/assets/{usePersistedAgentThreadId-DpQXOEDw.js → usePersistedAgentThreadId-B5pTglEr.js} +1 -1
- package/dist/assets/dql-notebook/assets/{user-round-DukNupB_.js → user-round-DL6DLw0m.js} +1 -1
- package/dist/assets/dql-notebook/assets/{wand-sparkles-CAwLX0b9.js → wand-sparkles-CNUjLDqT.js} +1 -1
- package/dist/assets/dql-notebook/assets/{workflow-bOT-NqdO.js → workflow-0NUwpoQ4.js} +1 -1
- package/dist/assets/dql-notebook/assets/{wrench-1m0_kcza.js → wrench-QNiznShi.js} +1 -1
- package/dist/assets/dql-notebook/assets/{x-fp82BETM.js → x-BhTl5gZs.js} +1 -1
- package/dist/assets/dql-notebook/index.html +1 -1
- package/dist/commands/agent-eval-cassette.d.ts.map +1 -1
- package/dist/commands/agent-eval-cassette.js +15 -0
- package/dist/commands/agent-eval-cassette.js.map +1 -1
- package/dist/commands/agent-shadow-report.d.ts +17 -0
- package/dist/commands/agent-shadow-report.d.ts.map +1 -0
- package/dist/commands/agent-shadow-report.js +149 -0
- package/dist/commands/agent-shadow-report.js.map +1 -0
- package/dist/commands/agent.d.ts.map +1 -1
- package/dist/commands/agent.js +6 -2
- package/dist/commands/agent.js.map +1 -1
- package/dist/commands/notebook.d.ts +2 -1
- package/dist/commands/notebook.d.ts.map +1 -1
- package/dist/commands/notebook.js +8 -1
- package/dist/commands/notebook.js.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/llm/providers/ask-v2-analyst-prompt.d.ts +32 -0
- package/dist/llm/providers/ask-v2-analyst-prompt.d.ts.map +1 -0
- package/dist/llm/providers/ask-v2-analyst-prompt.js +136 -0
- package/dist/llm/providers/ask-v2-analyst-prompt.js.map +1 -0
- package/dist/llm/providers/dql-agent-provider.d.ts +77 -1
- package/dist/llm/providers/dql-agent-provider.d.ts.map +1 -1
- package/dist/llm/providers/dql-agent-provider.js +4848 -354
- package/dist/llm/providers/dql-agent-provider.js.map +1 -1
- package/dist/llm/types.d.ts +124 -2
- package/dist/llm/types.d.ts.map +1 -1
- package/dist/local-runtime.d.ts +352 -3
- package/dist/local-runtime.d.ts.map +1 -1
- package/dist/local-runtime.js +4916 -238
- package/dist/local-runtime.js.map +1 -1
- package/dist/metricflow.d.ts.map +1 -1
- package/dist/metricflow.js +80 -11
- package/dist/metricflow.js.map +1 -1
- package/dist/package.json +10 -10
- package/dist/providers/oauth/claude-oauth.d.ts +14 -0
- package/dist/providers/oauth/claude-oauth.d.ts.map +1 -1
- package/dist/providers/oauth/claude-oauth.js +32 -5
- package/dist/providers/oauth/claude-oauth.js.map +1 -1
- package/dist/research-lineage-program.d.ts +29 -0
- package/dist/research-lineage-program.d.ts.map +1 -0
- package/dist/research-lineage-program.js +389 -0
- package/dist/research-lineage-program.js.map +1 -0
- package/dist/retrieval-health.d.ts.map +1 -1
- package/dist/retrieval-health.js +5 -2
- package/dist/retrieval-health.js.map +1 -1
- package/dist/semantic-runtime.d.ts.map +1 -1
- package/dist/semantic-runtime.js +73 -2
- package/dist/semantic-runtime.js.map +1 -1
- package/package.json +10 -10
- package/dist/assets/dql-notebook/assets/AskTracePage-CSMoMw9a.js +0 -8
- package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel-BjsTE6yf.js +0 -89
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import{c as Ne,r as h,a as se,j as n,d as an,g as It,l as Se,b9 as Hi,f as _t,L as et,aK as Qi,bb as Br,B as $t,e as Lr,u as ln,t as Nr,a5 as Ui,bc as nt,E as Gi,H as Ki,bd as Yi,w as Xi,S as tt,aH as Fr,b as cn,aL as Be,P as At,D as Ji,G as dn,be as Zi,bf as es,b1 as Cn,a0 as mn,ar as ts}from"./index-C9KfoqCR.js";import{S as Jt,F as rt,P as ns,E as rs,M as is,R as Dn,d as Pn,e as ss,A as os,g as as,u as ls}from"./usePersistedAgentThreadId-B5pTglEr.js";import{C as cs}from"./AiBuildResult-BImB4Wej.js";import{T as bn}from"./triangle-alert-D1WefIrN.js";import{U as ds}from"./user-round-DL6DLw0m.js";import{X as Zt}from"./x-BhTl5gZs.js";import{L as qt}from"./list-tree-67yz_uCY.js";import{W as un}from"./wrench-QNiznShi.js";import{M as us}from"./minimize-2-BJw5tlPC.js";import{A as ps}from"./arrow-right-BP5vPPNo.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 fs=[["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"}]],gs=Ne("archive",fs);/**
|
|
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 hs=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Dr=Ne("chevron-up",hs);/**
|
|
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 xs=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],ys=Ne("circle",xs);/**
|
|
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 ms=[["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"}]],Pr=Ne("copy",ms);/**
|
|
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 bs=[["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"}]],en=Ne("lightbulb",bs);/**
|
|
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 vs=[["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"}]],Ct=Ne("route",vs);/**
|
|
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 js=[["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"}]],Wn=Ne("save",js);/**
|
|
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 Ss=[["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"}]],ws=Ne("send",Ss);/**
|
|
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 ks=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],rr=Ne("square",ks);/**
|
|
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 As=[["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"}]],Cs=Ne("zap",As),vn=[{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 ir({t:e,value:t,onChange:r}){const[i,s]=h.useState(null),[o,a]=h.useState(!1),c=h.useRef(null);h.useEffect(()=>{let f=!1;return se.getProviderSettings().then(({providers:l})=>{f||s(l.find(d=>d.active)??null)}).catch(()=>{}),()=>{f=!0}},[]),h.useEffect(()=>{if(!o)return;const f=l=>{c.current&&!c.current.contains(l.target)&&a(!1)};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[o]);const u=vn.find(f=>f.mode===t)??vn[0],p=i?[i.label,i.model].filter(Boolean).join(" · "):null;return n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[p?n.jsxs("span",{title:"Connected model",style:sr(e),children:[n.jsx(ys,{size:7,fill:e.success,color:e.success}),n.jsx("span",{style:{color:e.textSecondary},children:p})]}):null,n.jsxs("div",{ref:c,style:{position:"relative"},children:[n.jsxs("button",{type:"button",onClick:()=>a(f=>!f),title:"How hard the model thinks for this thread",style:{...sr(e),cursor:"pointer"},children:[n.jsx(Cs,{size:12,color:e.textMuted}),n.jsxs("span",{style:{color:e.textSecondary},children:["Thinking: ",u.label]}),n.jsx(an,{size:12,color:e.textMuted})]}),o?n.jsx("div",{role:"menu",style:Rs(e),children:vn.map(f=>{const l=f.mode===t;return n.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":l,onClick:()=>{r(f.mode),a(!1)},style:Is(e,l),children:[n.jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[n.jsx("span",{style:{fontWeight:l?600:500,color:e.textPrimary},children:f.label}),l?n.jsx(It,{size:13,color:e.accent}):null]}),n.jsx("span",{style:{display:"block",fontSize:11,color:e.textMuted,marginTop:2},children:f.hint})]},f.mode)})}):null]})]})}function sr(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 Rs(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 Is(e,t){return{display:"block",width:"100%",textAlign:"left",padding:"8px 10px",borderRadius:7,border:"none",background:t?e.pillBg:"transparent",cursor:"pointer"}}const _s={draft:"#8b949e",review:"#d29922",certified:"#3fb950",deprecated:"#f85149",pending_recertification:"#db6d28"},qs={queued:"#8b949e",generating:"#4c8dff",running:"#4c8dff",saving:"#4c8dff",saved:"#2ea043",ready:"#2ea043",blocked:"#f85149",needs_attention:"#d29922"},zs={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"},$s={draft:Br,queued:Qi,generating:et,running:et,saving:et,ready:_t,saved:_t,blocked:bn,needs_attention:bn,review:Hi,certified:Se,deprecated:gs,pending_recertification:bn},Ts=new Set(["generating","running","saving"]);function Ms(e){return _s[e]??qs[e]??"#8b949e"}function Es(e){return zs[e]??e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g," ")}function Bs({status:e,t,label:r}){const i=Ms(e),s=$s[e]??Br,o=r??Es(e);return n.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:t.font,textTransform:"uppercase",letterSpacing:"0.03em",whiteSpace:"nowrap"},children:[n.jsx(s,{size:11,strokeWidth:2.2,className:Ts.has(e)?"spin":void 0}),o]})}function Ls(e){const{t,name:r,status:i="draft",description:s,dql:o,sqlPreview:a,grain:c,outputs:u=[],dimensions:p=[],entities:f=[],examples:l=[],sourceTables:d=[],evidence:m=[],certifierVerdict:g,owner:b,actions:y}=e,[x,_]=h.useState(!1),[z,N]=h.useState(!1);return n.jsxs("section",{style:{border:`1px solid ${t.cellBorder}`,borderRadius:10,background:t.cellBg,padding:14,display:"grid",gap:10,fontFamily:t.font},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[n.jsx($t,{size:14,strokeWidth:2,color:t.accent}),n.jsx("div",{style:{fontSize:13,fontWeight:850,color:t.textPrimary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r}),n.jsx(Bs,{status:i,t}),c?n.jsxs("span",{style:Rn(t),children:["grain ",c]}):null]}),s?n.jsx("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.5},children:s}):null,o?n.jsx(or,{open:x,onToggle:()=>_(q=>!q),label:"Governed DQL",t,lead:!0,children:n.jsx("pre",{style:ar(t),children:o})}):null,a?n.jsx(or,{open:z,onToggle:()=>N(q=>!q),label:o?"Compiled SQL preview":"SQL this block will run",t,children:n.jsx("pre",{style:ar(t),children:a})}):null,n.jsx(jn,{label:"Outputs",items:u,t}),n.jsx(jn,{label:"Dimensions",items:p,t}),n.jsx(jn,{label:"Entities",items:f,t}),l.length>0?n.jsxs("div",{style:{display:"grid",gap:5},children:[n.jsx(Wr,{t,children:"Answers questions like"}),n.jsx("ul",{style:{margin:0,padding:"0 0 0 16px",display:"grid",gap:3},children:l.slice(0,3).map(q=>n.jsx("li",{style:{fontSize:11.5,color:t.textSecondary,lineHeight:1.45},children:q},q))})]}):null,d.length>0||m.length>0?n.jsxs("div",{style:{display:"grid",gap:6,border:`1px solid ${t.headerBorder}`,borderRadius:8,background:t.appBg,padding:10},children:[n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:10.5,fontWeight:800,color:t.textSecondary,textTransform:"uppercase"},children:[n.jsx(Se,{size:12,color:t.accent})," Grounded on"]}),d.length>0?n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:d.map(q=>n.jsx("span",{style:Rn(t),children:q},q))}):null,m.slice(0,5).map((q,E)=>n.jsxs("div",{style:{border:`1px solid ${t.headerBorder}`,borderRadius:7,padding:8,background:t.cellBg},children:[n.jsx("div",{style:{fontSize:11,fontWeight:800,color:t.textSecondary,overflowWrap:"anywhere"},children:q.name}),n.jsxs("div",{style:{fontSize:10,color:t.textMuted,marginTop:3},children:[q.kind,q.reason?` · ${q.reason}`:""]}),q.description?n.jsx("div",{style:{fontSize:11,color:t.textMuted,lineHeight:1.35,marginTop:5},children:q.description}):null]},`${q.objectKey??q.name}-${E}`))]}):null,n.jsx(cs,{t,verdict:g}),b?n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11,color:t.textMuted},children:[n.jsx(ds,{size:12,strokeWidth:2})," drafting as ",b]}):null,y?n.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:y}):null]})}function or({open:e,onToggle:t,label:r,t:i,lead:s,children:o}){return n.jsxs("div",{children:[n.jsxs("button",{type:"button",onClick:t,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?n.jsx(an,{size:13,strokeWidth:2}):n.jsx(Lr,{size:13,strokeWidth:2}),e?`Hide ${r.toLowerCase()}`:r]}),e?n.jsx("div",{style:{marginTop:7},children:o}):null]})}function jn({label:e,items:t,t:r}){return t.length===0?null:n.jsxs("div",{style:{display:"grid",gap:5},children:[n.jsx(Wr,{t:r,children:e}),n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:t.map(i=>n.jsx("span",{style:Rn(r),children:i},i))})]})}function Wr({t:e,children:t}){return n.jsx("div",{style:{fontSize:10,fontWeight:800,letterSpacing:"0.05em",textTransform:"uppercase",color:e.textMuted},children:t})}function Rn(e){return{fontSize:10.5,fontWeight:700,color:e.textSecondary,background:e.pillBg,borderRadius:999,padding:"2px 8px",fontFamily:e.fontMono}}function ar(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 lr(){return n.jsx("span",{style:{color:"#ff7b72",marginLeft:2},children:"*"})}function Sn(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ns(e){const t=new Set,r=/@(metric|dim)\(([^)]+)\)/gi;let i;for(;i=r.exec(e);)t.add(i[2].trim());return Array.from(t)}function cr({cell:e,onClose:t,onSaved:r,initialContent:i,initialName:s,initialDescription:o,initialTags:a,initialDomain:c,initialOwner:u}){var ce;const{state:p,dispatch:f}=ln(),l=Nr[p.themeMode],d=h.useRef(null),[m,g]=h.useState(s||e.name||"new_block"),[b,y]=h.useState(c??""),[x,_]=h.useState(u??""),[z,N]=h.useState(o??p.notebookMetadata.description??""),[q,E]=h.useState((a??p.notebookMetadata.categories??[]).join(", ")),[V,U]=h.useState(i??e.content),[T,ie]=h.useState(""),[F,B]=h.useState(""),[K,w]=h.useState([]),[j,D]=h.useState(!1),[Z,Y]=h.useState(null),Q=h.useMemo(()=>Ns(V),[V]),W=h.useMemo(()=>q.split(",").map(A=>A.trim()).filter(Boolean),[q]),P=[{id:"has-name",label:"Block has name",severity:"error",passed:!!m.trim()},{id:"has-owner",label:"Block has owner",severity:"error",passed:!!x.trim()},{id:"has-description",label:"Description",severity:"warning",passed:!!z.trim()},{id:"has-domain",label:"Domain",severity:"warning",passed:!!b.trim()},{id:"has-tags",label:"Has at least one tag",severity:"warning",passed:W.length>0},{id:"has-llm-context",label:"Has LLM context (for agents)",severity:"warning",passed:!!T.trim()}],H=P.some(A=>A.severity==="error"&&!A.passed);h.useEffect(()=>{var A;(A=d.current)==null||A.focus()},[]),h.useEffect(()=>{const A=L=>{L.key==="Escape"&&t()};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[t]);const ue=Ui(b,p.authoredDomains),he=`${b.trim()?`blocks/${Sn(b)}/`:"blocks/"}${Sn(m)||"new-block"}.dql`,X=async()=>{var A,L,ee;if(H){Y("Enter the block name and owner before saving.");return}if(!V.trim()){Y("Block content is required.");return}D(!0),Y(null);try{const ne=F.split(`
|
|
52
|
+
`).map(Ie=>Ie.trim()).filter(Boolean),ae=K.map(Ie=>({question:Ie.question.trim(),sql:Ie.sql.trim()||void 0})).filter(Ie=>Ie.question),$=await se.saveAsBlock({cellId:e.id,notebookPath:((A=p.activeFile)==null?void 0:A.path)??null,name:m.trim(),domain:b.trim()||void 0,owner:x.trim()||void 0,content:V,description:z.trim()||void 0,tags:W,metricRefs:Q,llmContext:T.trim()||void 0,examples:ae.length>0?ae:void 0,invariants:ne.length>0?ne:void 0,reviewRequired:!!((L=e.datasetRefs)!=null&&L.length),datasetRefs:e.datasetRefs,lineage:(ee=e.dqlArtifact)==null?void 0:ee.lineage}),oe={name:`${Sn(m)||"new-block"}.dql`,path:$.path,type:"block",folder:"blocks"};p.files.some(Ie=>Ie.path===$.path)||f({type:"FILE_ADDED",file:oe});const Re=await se.openBlockStudio($.path);f({type:"OPEN_BLOCK_STUDIO",file:oe,payload:Re}),r==null||r({...$,name:m.trim()}),t()}catch(ne){Y(ne instanceof Error?ne.message:String(ne))}finally{D(!1)}},I={width:"100%",background:l.inputBg,border:`1px solid ${Z?l.error:l.inputBorder}`,borderRadius:6,color:l.textPrimary,fontSize:13,fontFamily:l.font,padding:"8px 12px",outline:"none",boxSizing:"border-box"};return n.jsx("div",{onClick:A=>{A.target===A.currentTarget&&t()},style:{position:"fixed",inset:0,background:l.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1100,backdropFilter:"blur(4px)"},children:n.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:[n.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsx("h2",{style:{margin:0,fontSize:16,fontWeight:600,color:l.textPrimary,fontFamily:l.font},children:"Save as Block"}),n.jsx("button",{onClick:t,style:{background:"transparent",border:"none",color:l.textMuted,cursor:"pointer",fontSize:18},children:"×"})]}),n.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:16},children:[n.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[n.jsxs("label",{style:{fontSize:12,color:l.textSecondary,fontFamily:l.font},children:["Block Name ",n.jsx(lr,{})]}),n.jsx("input",{ref:d,value:m,onChange:A=>g(A.target.value),style:I})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[n.jsx("label",{style:{fontSize:12,color:l.textSecondary,fontFamily:l.font},children:"Domain"}),n.jsxs("select",{value:b,onChange:A=>y(A.target.value),style:I,children:[n.jsx("option",{value:"",children:"Global / cross-domain"}),ue.map(A=>n.jsx("option",{value:A.value,disabled:A.disabled,children:A.label},A.value))]})]})]}),n.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[n.jsxs("label",{style:{fontSize:12,color:l.textSecondary,fontFamily:l.font},children:["Owner ",n.jsx(lr,{})]}),n.jsx("input",{value:x,onChange:A=>_(A.target.value),style:I,placeholder:"data-platform@company.com"})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[n.jsx("label",{style:{fontSize:12,color:l.textSecondary,fontFamily:l.font},children:"Tags"}),n.jsx("input",{value:q,onChange:A=>E(A.target.value),style:I,placeholder:"revenue, dashboard"})]})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[n.jsx("label",{style:{fontSize:12,color:l.textSecondary,fontFamily:l.font},children:"Description"}),n.jsx("input",{value:z,onChange:A=>N(A.target.value),style:I})]}),n.jsxs("details",{style:{border:`1px solid ${l.cellBorder}`,borderRadius:6,padding:"8px 12px"},children:[n.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)"}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10,paddingTop:10},children:[n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[n.jsx("label",{style:{fontSize:12,color:l.textSecondary,fontFamily:l.font},children:"How should an AI describe this block?"}),n.jsx("textarea",{value:T,onChange:A=>ie(A.target.value),rows:3,placeholder:'One paragraph. E.g. "Monthly revenue recognized from closed-won deals, grouped by billing month. Excludes refunds."',style:{...I,fontFamily:l.font,lineHeight:1.5,resize:"vertical"}})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[n.jsx("label",{style:{fontSize:12,color:l.textSecondary,fontFamily:l.font},children:"Invariants (one per line)"}),n.jsx("textarea",{value:F,onChange:A=>B(A.target.value),rows:2,placeholder:`Revenue is never negative
|
|
53
|
+
Each row is a unique month`,style:{...I,fontFamily:l.fontMono,lineHeight:1.5,resize:"vertical"}})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[n.jsx("label",{style:{fontSize:12,color:l.textSecondary,fontFamily:l.font},children:"Example questions (grounding for chat cells)"}),K.map((A,L)=>n.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr auto",gap:6},children:[n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[n.jsx("input",{value:A.question,onChange:ee=>{const ne=[...K];ne[L]={...ne[L],question:ee.target.value},w(ne)},placeholder:"What was revenue last month?",style:I}),n.jsx("input",{value:A.sql,onChange:ee=>{const ne=[...K];ne[L]={...ne[L],sql:ee.target.value},w(ne)},placeholder:"Optional SQL snippet",style:{...I,fontFamily:l.fontMono,fontSize:12}})]}),n.jsx("button",{type:"button",onClick:()=>w(K.filter((ee,ne)=>ne!==L)),style:{background:"transparent",border:`1px solid ${l.cellBorder}`,borderRadius:6,color:l.textMuted,cursor:"pointer",fontSize:12,padding:"0 10px"},children:"×"})]},L)),n.jsx("button",{type:"button",onClick:()=>w([...K,{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"})]})]})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,padding:"10px 12px",background:l.pillBg,borderRadius:6,border:`1px solid ${l.cellBorder}`},children:[n.jsx("div",{style:{fontSize:11,fontWeight:700,color:l.textSecondary,fontFamily:l.font,letterSpacing:"0.06em",textTransform:"uppercase"},children:"Governance checks"}),n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:P.map(A=>{const L=A.passed?"#3fb950":A.severity==="error"?"#ff7b72":"#e3b341",ee=A.passed?"✓":A.severity==="error"?"✕":"!";return n.jsxs("span",{title:A.passed?`${A.label} — passed`:`${A.label} — ${A.severity}`,style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11,fontFamily:l.font,color:L,background:`${L}18`,border:`1px solid ${L}55`,borderRadius:999,padding:"2px 10px"},children:[n.jsx("span",{style:{fontWeight:700},children:ee}),A.label]},A.id)})})]}),n.jsx("div",{style:{fontSize:12,color:l.textMuted,fontFamily:l.fontMono,padding:"8px 12px",background:l.pillBg,borderRadius:6},children:he}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[n.jsx("label",{style:{fontSize:12,color:l.textSecondary,fontFamily:l.font},children:"Content Preview"}),n.jsx("textarea",{value:V,onChange:A=>U(A.target.value),style:{...I,minHeight:220,resize:"vertical",fontFamily:l.fontMono,lineHeight:1.5}})]}),Q.length>0&&n.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,padding:"10px 12px",background:l.pillBg,borderRadius:6},children:[n.jsx("span",{style:{fontSize:11,color:l.textMuted,fontFamily:l.font},children:"Detected semantic refs:"}),Q.map(A=>n.jsx("span",{style:{fontSize:11,color:l.accent,fontFamily:l.fontMono,background:`${l.accent}18`,borderRadius:999,padding:"2px 8px"},children:A},A))]}),Z&&n.jsx("div",{style:{fontSize:12,color:l.error,fontFamily:l.font},children:Z})]}),n.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${l.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[n.jsx("span",{style:{fontSize:11.5,color:l.textMuted,marginRight:"auto",alignSelf:"center"},children:(ce=e.datasetRefs)!=null&&ce.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."}),n.jsx("button",{onClick:t,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"}),n.jsx("button",{onClick:X,disabled:j||H,title:H?"Fix governance errors to enable Save":void 0,style:{background:l.accent,border:`1px solid ${l.accent}`,borderRadius:6,color:"#fff",cursor:j||H?"not-allowed":"pointer",fontSize:13,fontFamily:l.font,padding:"7px 20px",opacity:j||H?.5:1},children:j?"Saving & checking…":"Save block"})]})]})})}function Or(e){return e.policy==="dynamic"||e.policy==="optional"}function Fs({parameters:e,values:t,onChange:r,onReset:i,t:s,includeNonRuntime:o=!1,card:a=!1}){const c=e.filter(u=>o||Or(u));return c.length===0?null:n.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:8},children:c.map(u=>{const p=Object.prototype.hasOwnProperty.call(t,u.name),f=p?t[u.name]:u.default,l=m=>r(u.name,m),d=u.type==="boolean"?n.jsxs("select",{"aria-label":u.name,value:String(f??""),onChange:m=>l(m.target.value),style:dr(s),children:[n.jsx("option",{value:"",children:"Select…"}),n.jsx("option",{value:"true",children:"True"}),n.jsx("option",{value:"false",children:"False"})]}):n.jsx("input",{"aria-label":u.name,type:u.type==="number"?"number":u.type==="date"?"date":"text",value:Array.isArray(f)?f.join(", "):f==null?"":String(f),placeholder:u.type.endsWith("[]")?"Comma-separated values":u.required?"Required value":"Use default",onChange:m=>l(m.target.value),style:dr(s)});return n.jsxs("label",{style:{display:"grid",gap:4,minWidth:0,...a?{padding:9,border:`1px solid ${s.cellBorder}`,borderRadius:7,background:s.appBg}:{}},children:[n.jsxs("span",{style:{display:"flex",gap:5,alignItems:"center",fontSize:10.5,fontWeight:750,color:s.textSecondary},children:[Ds(u.name),u.required?n.jsx("span",{style:{color:s.error},children:"*"}):null]}),d,n.jsxs("span",{style:{display:"flex",alignItems:"center",gap:5,minHeight:14,fontSize:9.5,color:s.textMuted},children:[n.jsxs("span",{children:[u.type,o?` · ${u.policy}`:""]}),p&&i?n.jsx("button",{type:"button",onClick:()=>i(u.name),style:{marginLeft:"auto",border:0,padding:0,background:"transparent",color:s.accent,fontSize:9.5,cursor:"pointer"},children:"Reset"}):null]})]},u.name)})})}function Ds(e){return e.replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function dr(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 Ps(e){const t=e.filter(o=>o.kind==="run").map(Ws).filter(o=>!!o).slice(-6);if(t.length===0)return;const r=[...t].reverse().find(o=>{var a;return(a=o.result)==null?void 0:a.columns.length})??t[t.length-1],i=r.result,s=Vr(ur(r));return In({activeSurface:"notebook",conversationStateVersion:1,activeTurnId:r.id,activeTopic:r.question,conversationSummary:Gs(t),turns:t,sourceAnswerId:r.id,sourceCertifiedBlock:r.sourceCertifiedBlock,sourceQuestion:r.question,sourceAnswerSummary:r.answerSummary,answerContract:ur(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??pt(s==null?void 0:s.filters),requestedDimensions:r.requestedDimensions??pt(s==null?void 0:s.dimensions),priorLimit:r.topN??Hr(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 Ws(e){var l,d,m,g;const t=e.run.artifacts.find(b=>b.kind==="answer")??e.run.artifacts.find(b=>b.kind==="research_run")??e.run.artifacts[0],r=je(t==null?void 0:t.payload),i=Os(r),s=Ys(i),o=Array.isArray(i==null?void 0:i.rows)?i.rows.filter(b=>!!(b&&typeof b=="object"&&!Array.isArray(b))).slice(0,24):[],a=((l=je(r==null?void 0:r.contextPack))==null?void 0:l.questionPlan)??(r==null?void 0:r.analysisPlan),c=Vr(a),u=Js(s,o),p=Ks(c,s),f=de(r==null?void 0:r.sourceCertifiedBlock)??((t==null?void 0:t.kind)==="answer"?de(t.ref):void 0)??de((d=je(r==null?void 0:r.block))==null?void 0:d.name);return In({id:e.run.id,question:e.run.question,answerSummary:e.run.answer??e.run.summary,completedAt:e.run.completedAt,artifactKind:t==null?void 0:t.kind,sourceCertifiedBlock:f,route:de((m=je(r==null?void 0:r.route))==null?void 0:m.label)??de((g=je(r==null?void 0:r.route))==null?void 0:g.tier),trustLabel:de(r==null?void 0:r.trustLabel),reviewStatus:de(r==null?void 0:r.reviewStatus),certification:de(r==null?void 0:r.certification),contextPackId:de(r==null?void 0:r.contextPackId),requestedFilters:pt(c==null?void 0:c.filters),requestedDimensions:pt(c==null?void 0:c.dimensions),requestedMeasures:pt(c==null?void 0:c.measures),answerContract:a,dqlArtifact:Qs(r),cascade:Us(r),topN:Hr(c),result:s.length>0||o.length>0?In({columns:s,rowsSample:o,dimensionValues:u,measureColumns:p,rowCount:Vs(i)}):void 0,sourceSql:Hs(r,i)})}function ur(e){return e.answerContract}function Vr(e){const t=je(e);return je(t==null?void 0:t.requestedShape)}function Os(e){const t=je(e==null?void 0:e.researchRun),r=je(e==null?void 0:e.result);return[e==null?void 0:e.result,e==null?void 0:e.resultPreview,t==null?void 0:t.resultPreview,t==null?void 0:t.result,r==null?void 0:r.result].map(je).filter(s=>!!(s&&(Array.isArray(s.rows)||Array.isArray(s.columns)))).sort((s,o)=>pr(o)-pr(s))[0]}function pr(e){const t=Array.isArray(e.rows)?e.rows.length:0,r=typeof e.rowCount=="number"&&Number.isFinite(e.rowCount)?e.rowCount:0;return t*1e5+r}function Vs(e){const t=e==null?void 0:e.rowCount;return typeof t=="number"&&Number.isFinite(t)?t:Array.isArray(e==null?void 0:e.rows)?e.rows.length:void 0}function Hs(e,t){var r,i;return de(e==null?void 0:e.proposedSql)??de(e==null?void 0:e.sql)??de(t==null?void 0:t.sql)??de((r=je(e==null?void 0:e.query))==null?void 0:r.sql)??de((i=je(e==null?void 0:e.plan))==null?void 0:i.sql)}function Qs(e){var r,i;const t=nt(e==null?void 0:e.dqlArtifact);return t?{...t,source:t.source.slice(0,3e3),filters:(r=t.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=t.orderBy)==null?void 0:i.slice(0,8)}:void 0}function Us(e){const t=je(e==null?void 0:e.cascade);if(!t)return;const r=de(t.terminalLane),i=de(t.routeTier);if(!(!r&&!i))return{terminalLane:r,routeTier:i,label:de(t.label),ref:de(t.ref),artifactKind:de(t.artifactKind),refusalCode:de(t.refusalCode),outcome:je(t.outcome)}}function Gs(e){const t=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,u])=>`${c}: ${u.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 t.length>0?t.join(`
|
|
54
|
+
`):void 0}function Hr(e){const t=je(e==null?void 0:e.topN),r=t==null?void 0:t.n;return typeof r=="number"&&Number.isFinite(r)&&r>0?r:void 0}function Ks(e,t){const r=[...pt(e==null?void 0:e.measures)??[],...t.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 je(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Ys(e){const r=(Array.isArray(e==null?void 0:e.columns)?e.columns:[]).map(Xs).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 pt(e){if(!Array.isArray(e))return;const t=e.map(i=>typeof i=="string"?i.trim():"").filter(Boolean),r=Array.from(new Set(t)).slice(0,24);return r.length>0?r:void 0}function Xs(e){if(typeof e=="string"&&e.trim())return e.trim();if(e&&typeof e=="object"){const t=e;return de(t.name)??de(t.field)??de(t.key)}}function Js(e,t){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 t){const c=je(a),u=c==null?void 0:c[s],p=typeof u=="string"||typeof u=="number"?String(u).trim():"";if(!(!p||o.includes(p))&&(o.push(p),o.length>=24))break}o.length>0&&(i[Zs(s)]=o)}return Object.keys(i).length>0?i:void 0}function Zs(e){const t=e.toLowerCase();return t.includes("category")?"category":t.includes("product")?t.includes("name")?"product_name":"product":t.includes("customer")?t.includes("name")?"customer_name":"customer":t.includes("segment")?"segment":t.includes("region")?"region":t.includes("channel")?"channel":t.replace(/[^a-z0-9_]+/g,"_")}function de(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function In(e){const t={};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||(t[r]=i));return Object.keys(t).length>0?t:void 0}function eo(e){return JSON.stringify([e.kind,e.name??null,e.source,e.persistence??null,e.parameters??[],Object.entries(e.parameterValues??{}).sort(([t],[r])=>t.localeCompare(r)),e.executionReceipt??null])}function Qr(e,t){if(e.kind==="sql_block"){const s=new Map(t.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:fr(t.rows.map(c=>c[a]))}]:[]})}if(e.kind!=="semantic_block"||e.persistence!=="transient")return[];const r=new Map(t.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=fr(t.rows.map(u=>u[a]));return[{column:a,field:s,values:c}]})}function to(e,t,r,i){const s=Qr(e,t).find(y=>y.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(y=>y.name)),a=no(s.field.split(".").at(-1)??s.column);let c=a,u=2;for(;o.has(c);)c=`${a}_${u++}`;const p=Array.isArray(i)?i.map(String).join(", "):String(i),f=Gi(p,c);let l=Ki(e.source,{name:c,type:f,required:!1,defaultText:p,policy:"dynamic"});l=Yi(l,c,s.field);const d=Xi(l).map(y=>{var x,_,z;return{...y,...((x=y.binding)==null?void 0:x.kind)==="semantic_filter"&&y.binding.field?{binding:{kind:"semantic_filter",field:y.binding.field,operator:y.binding.operator??"equals"}}:((_=y.binding)==null?void 0:_.kind)==="limit"?{binding:{kind:"limit"}}:((z=y.binding)==null?void 0:z.kind)==="sql_value"?{binding:{kind:"sql_value"}}:{binding:void 0}}}),{executionReceipt:m,compiledSql:g,...b}=e;return{artifact:{...b,source:l,parameters:d,parameterValues:{...e.parameterValues??{},[c]:i}},parameterName:c}}function fr(e){const t=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(!t.has(s)&&(t.add(s),r.push(i),r.length>=50))break}return r}function no(e){const t=e.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return/^[a-z_][a-z0-9_]*$/.test(t)?t:"result_filter"}const Ur="Canonical decision summary unavailable for this older run";function Gr(e){return e.modeOverride?e.modeOverride:e.pendingMode?e.pendingMode:e.researchMode?"research":e.initialMode==="research"?"ask":e.initialMode}function Kr(e,t,r){return e.map(i=>i.kind==="run"&&i.run.id===t?{kind:"run",id:r.id,run:r}:i)}function Yr(e){var r,i,s;const t=[];for(const o of e){if(o.kind==="user"){t.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 u=re(c);return!!(u.executionError||u.warehouseFailure||u.analyticalFailure)}))){((i=t.at(-1))==null?void 0:i.role)==="user"&&t.pop();continue}t.push({role:"assistant",text:((s=Ke(o.run))==null?void 0:s.trim())||o.run.summary})}return t.slice(-12)}function Ke(e){var t,r,i;return((t=e.askAnalystState)==null?void 0:t.mode)==="authoritative"||(r=e.diagnosticReceiptV5)!=null&&r.state?(i=e.businessAnswer)==null?void 0:i.answer:e.answer}const On="dql.agent.active-runs.v1",Xr={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 ro({themeMode:e,title:t="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:u,workspaceContext:p,initialMode:f="auto",initialInput:l="",initialItems:d,onItemsChange:m,threadId:g,onThreadIdChange:b,audience:y="analyst",autoRun:x,onInsertSql:_,onInsertDql:z,onReplaceDql:N,onArtifactReady:q,onReviewAuthoringProposal:E,onOpenBlock:V,onOpenResearch:U,onOpenApp:T,onRunningChange:ie,answerFirstCards:F=!1,insertDqlActionLabel:B,replaceDqlActionLabel:K,askLayout:w=!1}){const j=Nr[e],D=h.useRef(void 0),[Z,Y]=h.useState(l),[Q,W]=h.useState(d??[]),[P,H]=h.useState([]),[ue,he]=h.useState(""),[X,I]=h.useState(!1),[ce,A]=h.useState(null),[L,ee]=h.useState(null),[ne,ae]=h.useState(null),[$,oe]=h.useState(()=>io()),[Re,Ie]=h.useState(f==="research"),[ht,it]=h.useState(!1),[st,ot]=h.useState([]),[ke,Oe]=h.useState(),Et=h.useCallback(v=>{oe(v);try{window.localStorage.setItem(Jr,v)}catch{}},[]),Bt=h.useCallback(v=>{Ie(v),v||it(!1)},[]),Ve=h.useRef(null),Lt=h.useRef(l),Nt=h.useRef(null),De=h.useRef(null),ye=h.useRef(null),qe=h.useRef(null),xe=h.useRef(null),ze=h.useRef(0),Je=h.useRef(""),$e=h.useRef(null),He=h.useCallback(()=>{Je.current="",$e.current!==null&&(window.cancelAnimationFrame($e.current),$e.current=null),he("")},[]),Ft=h.useCallback(v=>{Je.current+=v,$e.current===null&&($e.current=window.requestAnimationFrame(()=>{$e.current=null;const k=Je.current;Je.current="",k&&he(M=>M+k)}))},[]);h.useEffect(()=>()=>{$e.current!==null&&window.cancelAnimationFrame($e.current)},[]);const _e=p==null?void 0:p.executionTarget,xt=_e&&typeof _e=="object"&&!Array.isArray(_e)&&_e.target==="connection"&&typeof _e.connectionName=="string"?String(_e.connectionName):void 0,C=_e&&typeof _e=="object"&&!Array.isArray(_e)&&_e.target==="local";h.useEffect(()=>{let v=!1;return se.getConnections().then(k=>{if(v)return;const M=Object.keys(k.connections??{}).sort((O,G)=>O.localeCompare(G));ot(M),Oe(ti(M,k.default,xt))}).catch(()=>{v||(ot([]),Oe(void 0))}),()=>{v=!0}},[xt]);const fe=h.useCallback(v=>{Oe(v)},[]),[me,Dt]=h.useState(null),[Pe,at]=h.useState(null),[Di,xn]=h.useState(""),Xn=h.useRef(null),Pt=h.useRef(null);h.useEffect(()=>{!l||X||l!==Lt.current&&(Lt.current=l,Y(l))},[l,X]);const Pi=h.useMemo(()=>Yr(Q),[Q]),Wt=h.useRef(m);Wt.current=m;const Ze=h.useRef(q);Ze.current=q,h.useEffect(()=>{var v;(v=Wt.current)==null||v.call(Wt,Q)},[Q]);const Ae=h.useRef(g),Ot=h.useRef(b);Ot.current=b;const yn=h.useCallback((v,k)=>{var M;if(xe.current!==null&&(window.clearTimeout(xe.current),xe.current=null),St(v.id),ye.current===v.id&&(ye.current=null),qe.current=null,A(null),H(v.events.slice(-8)),He(),W(O=>{if(O.some(J=>J.kind==="run"&&J.run.id===v.id))return O.map(J=>J.kind==="run"&&J.run.id===v.id?{...J,id:v.id,run:v}:J);const G=O.some(J=>J.kind==="user"&&J.text===k.question);return[...O,...G?[]:[{kind:"user",id:`${v.id}-question`,text:k.question}],{kind:"run",id:v.id,run:v}]}),v.route!=="certified_answer"){const O=rn(v);O&&((M=Ze.current)==null||M.call(Ze,O,v))}},[He]),Jn=h.useCallback((v,k)=>{var O;W(G=>Kr(G,v,k)),Dt(G=>{if(!G||G.runId!==v)return G;const J=k.artifacts[0];return J?{runId:k.id,artifactId:J.id,tab:G.tab}:null}),ae(null);const M=rn(k);M&&((O=Ze.current)==null||O.call(Ze,M,k))},[]),yt=h.useCallback(v=>{xe.current!==null&&window.clearTimeout(xe.current);const k=++ze.current;ye.current=v.id,qe.current=v,A(v),I(!0),He(),H([]);const M=async()=>{if(!(k!==ze.current||ye.current!==v.id))try{const O=await se.getAgentRunState(v.id);if(k!==ze.current||ye.current!==v.id)return;if(O.lifecycleState==="terminal"){yn(O.run,v),I(!1);return}H(O.progress.events.slice(-8)),xe.current=window.setTimeout(()=>{M()},600)}catch{if(k!==ze.current||ye.current!==v.id)return;xe.current=window.setTimeout(()=>{M()},1200)}};return M(),()=>{k===ze.current&&(ze.current+=1),xe.current!==null&&(window.clearTimeout(xe.current),xe.current=null)}},[yn]),Zn=h.useRef(!1);h.useEffect(()=>{if(!g||Zn.current)return;Zn.current=!0,Ae.current??(Ae.current=g);let v=!1;return se.getAgentThread(g).then(({turns:k,runs:M})=>{v||k.length===0||W(O=>{const G=O.filter(pe=>pe.kind==="run").length,J=ni(k,M);if(k.length>=G)return J;const be=new Map(J.flatMap(pe=>pe.kind==="run"?[[pe.run.id,pe.run]]:[]));return O.map(pe=>pe.kind==="run"&&be.has(pe.run.id)?{...pe,run:be.get(pe.run.id)}:pe)})}).catch(()=>{!v&&Ae.current===g&&(Ae.current=void 0)}),()=>{v=!0}},[g]),h.useEffect(()=>{const v=yr(g??Ae.current);if(!(!v||De.current))return yt(v)},[yt,g]),h.useEffect(()=>{const v=()=>{if(document.visibilityState!=="visible"||De.current)return;const k=qe.current??yr(g??Ae.current);k&&yt(k)};return document.addEventListener("visibilitychange",v),()=>document.removeEventListener("visibilitychange",v)},[yt,g]);const We=async(v,k,M,O,G,J)=>{var Gt,vt,ve;const be=(v??Z).trim();if(!be||X)return;const pe=Gr({initialMode:f,researchMode:Re,modeOverride:k,pendingMode:D.current}),lt=ei(pe,ht);it(!1),D.current=void 0;const ct={kind:"user",id:_r("user"),text:be};W(we=>[...we,ct]),Y(""),ae(null),I(!0),H([]),He();const dt=new AbortController;De.current=dt;let le={id:_r("pending"),question:be,threadId:Ae.current,startedAt:new Date().toISOString()};ye.current=null,qe.current=le,A(le);let mt=!1,bt=!1,ut=!1;try{if(!Ae.current)try{const ge=await se.createAgentThread({surface:w?"ask":typeof(p==null?void 0:p.surface)=="string"?p.surface:c?"notebook":"agent",title:be,...c?{notebookPath:c}:{}});Ae.current=ge.id,(Gt=Ot.current)==null||Gt.call(Ot,ge.id),le={...le,threadId:ge.id},qe.current=le,A(le)}catch{}const we=pe==="modeling"||pe==="skill"?(vt=[...Q].reverse().find(ge=>ge.kind==="run"&&ge.run.artifacts.some(jt=>jt.kind===(pe==="modeling"?"modeling_change_proposal":"skill_change_proposal"))))==null?void 0:vt.run:void 0,nr=we==null?void 0:we.artifacts.find(ge=>ge.kind===(pe==="modeling"?"modeling_change_proposal":"skill_change_proposal")),Vi={question:be,...M?{selectedEvidenceId:M}:{},...O?{clarificationSourceQuestion:O}:{},...J?{selectedResultBinding:J}:{},requestedMode:pe,audience:y,selectedObject:u??(c?{kind:"notebook",path:c}:void 0),...G!=null&&G.executionTarget?{executionTarget:G.executionTarget}:C?{executionTarget:{target:"local"}}:ke?{executionTarget:{target:"connection",connectionName:ke}}:{},workspaceContext:{...p??{},...c?{notebookPath:c}:{},...G?{researchSource:ki(G)}:{},...we&&nr?{sourceRunId:we.id,sourceArtifactId:nr.id,revision:(((ve=we.derivation)==null?void 0:ve.revision)??1)+1}:{}},conversationContext:Ps(Q),history:Pi,thinkingMode:$,researchResultRowsOptIn:lt,...Ae.current?{threadId:Ae.current}:{}},Kt=await se.createAgentRunStream(Vi,ge=>{if(mt=!0,ge.kind==="accepted"){const jt=le.id;le={...le,id:ge.runId},ye.current=ge.runId,qe.current=le,A(le),St(jt),xr(le),bt=!0}else ge.kind==="event"?H(jt=>[...jt,ge.event].slice(-8)):ge.kind==="answer-delta"?Ft(ge.delta):H(ge.run.events.slice(-8))},dt.signal);if(le.id!==Kt.id){const ge=le.id;le={...le,id:Kt.id},ye.current=Kt.id,qe.current=le,St(ge),xr(le)}yn(Kt,le)}catch(we){dt.signal.aborted||(ae(we instanceof Error?we.message:String(we)),Y(be),mt&&bt?(ut=!0,yt(le)):(St(le.id),ye.current===le.id&&(ye.current=null),qe.current=null,A(null)))}finally{De.current===dt&&(De.current=null),ut||I(!1)}},Vt=()=>{We()},er=()=>{var k;const v=ye.current;v&&se.cancelAgentRun(v).catch(()=>{}),(k=De.current)==null||k.abort(),ze.current+=1,xe.current!==null&&window.clearTimeout(xe.current),St(v??""),ye.current=null,qe.current=null,A(null),He(),H([]),I(!1),ae("Stopped. No answer or draft was saved.")},Ht=h.useRef(ie);Ht.current=ie,h.useEffect(()=>{var v;(v=Ht.current)==null||v.call(Ht,X)},[X]),h.useEffect(()=>{!(x!=null&&x.text)||X||Nt.current!==x.nonce&&(Nt.current=x.nonce,We(x.text,x.mode??f))},[x==null?void 0:x.nonce,x==null?void 0:x.text,x==null?void 0:x.mode,f,X]),h.useEffect(()=>()=>{ze.current+=1,xe.current!==null&&window.clearTimeout(xe.current)},[]);const Qt={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},Ut=(v,k)=>{var M,O;if(k.id==="review-modeling-proposal"||k.id==="review-skill-proposal"){const G=k.id==="review-modeling-proposal"?"modeling_change_proposal":"skill_change_proposal",J=v.artifacts.find(be=>be.kind===G);if(!J){ae("This authoring run does not include a reviewable proposal.");return}if(E)E(J,v);else if(J.ref){try{window.sessionStorage.setItem("dql-context-proposal-handoff",J.ref)}catch{}window.dispatchEvent(new CustomEvent("dql:open-context-proposal",{detail:{proposalId:J.ref,kind:J.kind}}))}return}if(k.id==="save-dql-block"){const G=Fe(v),J=((M=G==null?void 0:G.source)==null?void 0:M.trim())??((O=Le(v))==null?void 0:O.trim());if(!J){ae("This answer does not include a reusable DQL or SQL artifact yet.");return}ee({runId:v.id,source:J,name:(G==null?void 0:G.name)??`${v.question.slice(0,48).trim()||"saved_answer"}`,dqlArtifact:G});return}if(k.id==="research-deeper"){We(v.question,"research",void 0,void 0,v);return}if(k.id.startsWith("suggest-question")){We(k.label,"auto");return}D.current=Eo(k.route),Y(Bo(v,k.route)),requestAnimationFrame(()=>{var G;return(G=Ve.current)==null?void 0:G.focus()})},Wi=h.useCallback((v,k,M="trust")=>{Dt({runId:v,artifactId:k,tab:M})},[]),Oi=h.useCallback(v=>{var O;const k=v.trim();if(!k)return;const M=Pe==null?void 0:Pe.selectedResultBinding;at(null),xn("");try{(O=window.getSelection())==null||O.removeAllRanges()}catch{}We(k,void 0,void 0,void 0,void 0,M),requestAnimationFrame(()=>{Pt.current&&(Pt.current.scrollTop=Pt.current.scrollHeight)})},[Pe,We]);if(h.useEffect(()=>{if(!w)return;const v=M=>{const O=M.target;O&&O.closest("[data-selpop]")||window.setTimeout(()=>{var vt;const G=window.getSelection(),J=G&&G.rangeCount?G.toString().trim():"";if(!J||J.length<3){at(ve=>ve&&null);return}const be=G.anchorNode,pe=be&&(be.nodeType===1?be:be.parentElement),lt=pe==null?void 0:pe.closest("[data-followup]");if(!lt){at(ve=>ve&&null);return}const ct=G.getRangeAt(0).getBoundingClientRect(),dt=Math.max(12,Math.min(ct.left,window.innerWidth-340)),tr=ct.bottom+176>window.innerHeight?Math.max(12,ct.top-176):ct.bottom+8,le=lt.getAttribute("data-followup")||"answer",mt=lt.getAttribute("data-followup-run-id"),bt=lt.getAttribute("data-followup-artifact-id"),ut=mt?(vt=Q.find(ve=>ve.kind==="run"&&ve.run.id===mt))==null?void 0:vt.run:void 0,Gt=ut&&bt?ut.artifacts.find(ve=>ve.id===bt):void 0;zi({selectedText:J,run:ut,artifact:Gt}).then(ve=>{at({text:J.slice(0,220),source:le,left:dt,top:tr,...ve?{selectedResultBinding:ve}:{}}),xn(""),requestAnimationFrame(()=>{var we;return(we=Xn.current)==null?void 0:we.focus()})})},0)},k=M=>{M.key==="Escape"&&at(null)};return document.addEventListener("mouseup",v),document.addEventListener("keydown",k),()=>{document.removeEventListener("mouseup",v),document.removeEventListener("keydown",k)}},[w,Q]),w){const v=me?(()=>{const k=Q.find(O=>O.kind==="run"&&O.run.id===me.runId);if(!k||k.kind!=="run")return null;const M=k.run.artifacts.find(O=>O.id===me.artifactId);return M?{run:k.run,artifact:M}:null})():null;return n.jsxs("div",{style:{display:"flex",height:"100%",minHeight:0,flex:1,minWidth:0,width:"100%",background:"var(--bg-canvas)"},children:[L?n.jsx(cr,{cell:{id:`agent-${L.runId}`,type:L.dqlArtifact?"dql":"sql",content:L.source,name:L.name,status:"success",...L.dqlArtifact?{dqlArtifact:L.dqlArtifact}:{}},initialContent:L.source,initialName:L.name,onClose:()=>ee(null),onSaved:()=>ee(null)}):null,n.jsx("style",{children:xo}),n.jsxs("div",{style:{flex:1,minWidth:360,display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg-canvas)"},children:[n.jsxs("div",{style:{height:46,flexShrink:0,borderBottom:"1px solid var(--border-subtle)",display:"flex",alignItems:"center",gap:9,padding:"0 24px"},children:[n.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:n.jsx(tt,{size:13})}),n.jsx("span",{style:{fontSize:13.5,fontWeight:650,color:j.textPrimary,whiteSpace:"nowrap"},children:t==="AI Copilot"?"Ask your data":t}),n.jsx("div",{style:{flex:1}}),n.jsx("span",{style:{fontSize:11,color:j.textMuted,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:"Certified first · semantic next · generated SQL last"})]}),n.jsxs("div",{ref:Pt,style:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden",display:"flex",flexDirection:"column"},children:[n.jsxs("div",{style:{width:"min(720px, 100% - 48px)",margin:"0 auto",padding:"26px 0 12px",display:"flex",flexDirection:"column",gap:26},children:[Q.length===0&&!X?n.jsxs("div",{style:{margin:"auto 0",display:"grid",gap:14,justifyItems:"center",textAlign:"center",color:j.textSecondary,paddingTop:40},children:[n.jsx("div",{style:qr(j),children:n.jsx(tt,{size:20})}),n.jsx("div",{style:{fontSize:13.5,lineHeight:1.5,maxWidth:400,color:j.textSecondary},children:a??gr}),n.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap",justifyContent:"center",maxWidth:520},children:(o??hr).map(k=>n.jsx("button",{type:"button",className:"dql-hover dql-lift",onClick:()=>{Y(k.prompt),requestAnimationFrame(()=>{var M;return(M=Ve.current)==null?void 0:M.focus()})},style:sn(j),children:k.label},k.label))})]}):null,Q.map(k=>k.kind==="user"?n.jsx("div",{style:yo(j),children:k.text},k.id):n.jsx(Ar,{run:k.run,t:j,themeMode:e,threadId:Ae.current,appContext:Qt,selectedArtifactId:(me==null?void 0:me.runId)===k.run.id?me.artifactId:void 0,onOpenArtifact:(M,O)=>Wi(k.run.id,M,O),onOpenApp:T,onInsertSql:_,onInsertDql:z,onOpenBlock:V,onOpenResearch:U,onSelectClarification:M=>{const O=Xt(M,k.run.question);We(O.question,void 0,O.selectedEvidenceId,k.run.question)},onNextAction:M=>Ut(k.run,M),onRepairedRun:Jn},k.id)),X&&n.jsx(jr,{events:P,t:j,streamingAnswer:ue,thinkingMode:$,backgroundRun:ce})]}),n.jsxs("div",{style:{width:"min(720px, 100% - 48px)",margin:"auto auto 0",padding:"10px 0 16px",position:"sticky",bottom:0,background:"linear-gradient(to top, var(--bg-canvas) 82%, transparent)"},children:[ne?n.jsx("div",{style:{color:j.error,fontSize:12,marginBottom:8},children:ne}):null,s?n.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:[n.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r}),n.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:n.jsx(Zt,{size:12})})]}):null,n.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:[n.jsx("textarea",{ref:Ve,value:Z,onChange:k=>{Y(k.target.value),D.current=void 0},rows:2,placeholder:i,onKeyDown:k=>{k.key==="Enter"&&!k.shiftKey&&(k.preventDefault(),Vt())},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}}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 10px 10px 12px"},children:[n.jsx(ir,{t:j,value:$,onChange:Et}),n.jsx(mr,{checked:Re,onChange:Bt,t:j}),Re?n.jsx(br,{checked:ht,onChange:it,t:j}):null,n.jsx(vr,{names:st,value:ke,onChange:fe,t:j}),n.jsx("div",{style:{flex:1}}),X?n.jsxs("button",{type:"button",className:"dql-hover",onClick:er,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:[n.jsx(rr,{size:13,fill:"currentColor"})," Stop"]}):null,n.jsx("button",{type:"button",className:"dql-hover dql-lift",title:"Ask",onClick:Vt,disabled:!Z.trim()||X,style:{width:34,height:34,borderRadius:10,border:"none",background:Z.trim()&&!X?"var(--accent)":"var(--bg-4)",color:"#fff",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:Z.trim()&&!X?"pointer":"default",boxShadow:Z.trim()&&!X?"0 1px 5px rgba(107,93,211,0.3)":"none"},children:X?n.jsx(et,{size:15,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}}):n.jsx(Fr,{size:15})})]})]}),n.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."})]})]})]}),v?n.jsx(Ro,{run:v.run,artifact:v.artifact,tab:me.tab,t:j,appContext:Qt,onOpenApp:T,onChangeTab:k=>Dt(M=>M&&{...M,tab:k}),onClose:()=>Dt(null),onSaveBlock:()=>Ut(v.run,{id:"save-dql-block",label:"Save as block",route:"dql_block_draft"}),onInsertSql:_,onInsertDql:z}):null,Pe?n.jsx(Io,{t:j,text:Pe.text,source:Pe.source,left:Pe.left,top:Pe.top,draft:Di,inputRef:Xn,onDraftChange:xn,onClose:()=>at(null),onSend:Oi}):null]})}return n.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,flex:1,minWidth:0,width:"100%",background:j.cellBg},children:[L?n.jsx(cr,{cell:{id:`agent-${L.runId}`,type:L.dqlArtifact?"dql":"sql",content:L.source,name:L.name,status:"success",...L.dqlArtifact?{dqlArtifact:L.dqlArtifact}:{}},initialContent:L.source,initialName:L.name,onClose:()=>ee(null),onSaved:()=>ee(null)}):null,n.jsx("style",{children:`
|
|
55
|
+
@keyframes dql-agent-run-spin { to { transform: rotate(360deg); } }
|
|
56
|
+
@keyframes dql-agent-fadein { from { opacity: 0; transform: translateY(3px); } to { opacity: 1; transform: none; } }
|
|
57
|
+
@keyframes dql-agent-thinking-dot { 0%, 65%, 100% { opacity: .28; transform: translateY(0); } 32% { opacity: 1; transform: translateY(-2px); } }
|
|
58
|
+
@keyframes dql-agent-activity-in { from { opacity: 0; transform: translateY(2px); } to { opacity: 1; transform: none; } }
|
|
59
|
+
.dql-agent-thinking-dot { animation: dql-agent-thinking-dot 1.05s ease-in-out infinite; }
|
|
60
|
+
.dql-agent-activity { animation: dql-agent-activity-in .22s ease-out; }
|
|
61
|
+
.dql-hover { transition: filter .15s ease, transform .12s ease, box-shadow .15s ease, background .15s ease, color .15s ease, border-color .15s ease; }
|
|
62
|
+
.dql-hover:hover { filter: brightness(1.07); }
|
|
63
|
+
.dql-hover:active { transform: translateY(0.5px); }
|
|
64
|
+
.dql-lift:hover { transform: translateY(-1px); }
|
|
65
|
+
details > summary::-webkit-details-marker { display: none; }
|
|
66
|
+
@media (prefers-reduced-motion: reduce) { .dql-agent-thinking-dot, .dql-agent-activity { animation: none !important; } }
|
|
67
|
+
`}),n.jsxs("div",{style:{flex:1,minHeight:0,overflow:"auto",padding:"14px 16px",display:"flex",flexDirection:"column",gap:12},children:[Q.length===0&&!X?n.jsxs("div",{style:{margin:"auto 0",display:"grid",gap:14,justifyItems:"center",textAlign:"center",color:j.textSecondary},children:[n.jsx("div",{style:qr(j),children:n.jsx(tt,{size:20})}),n.jsx("div",{style:{fontSize:13,lineHeight:1.5,maxWidth:380,color:j.textSecondary},children:a??gr}),n.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap",justifyContent:"center",maxWidth:520},children:(o??hr).map(v=>n.jsx("button",{type:"button",className:"dql-hover dql-lift",onClick:()=>{Y(v.prompt),requestAnimationFrame(()=>{var k;return(k=Ve.current)==null?void 0:k.focus()})},style:sn(j),children:v.label},v.label))})]}):null,Q.map(v=>v.kind==="user"?n.jsx("div",{style:Yo(j),children:v.text},v.id):F?n.jsx(Ar,{run:v.run,t:j,themeMode:e,threadId:Ae.current,appContext:Qt,onOpenApp:T,onInsertSql:_,onInsertDql:z,onReplaceDql:N,insertDqlActionLabel:B,replaceDqlActionLabel:K,onOpenBlock:V,onOpenResearch:U,onSelectClarification:k=>{const M=Xt(k,v.run.question);We(M.question,void 0,M.selectedEvidenceId,v.run.question)},onNextAction:k=>Ut(v.run,k),onRepairedRun:Jn},v.id):n.jsx(ho,{run:v.run,t:j,themeMode:e,appContext:Qt,onOpenApp:T,onInsertSql:_,onInsertDql:z,onOpenBlock:V,onOpenResearch:U,onSelectClarification:k=>{const M=Xt(k,v.run.question);We(M.question,void 0,M.selectedEvidenceId,v.run.question)},onNextAction:k=>Ut(v.run,k)},v.id)),X&&n.jsx(jr,{events:P,t:j,streamingAnswer:ue,thinkingMode:$,backgroundRun:ce})]}),ne?n.jsx("div",{style:{margin:"0 16px 8px",color:j.error,fontSize:12},children:ne}):null,n.jsxs("div",{style:{padding:"10px 16px 14px",borderTop:`1px solid ${j.headerBorder}`,display:"grid",gap:8},children:[n.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",justifyContent:"space-between",flexWrap:"wrap"},children:[n.jsxs("div",{style:{fontSize:11,color:j.textMuted,flex:1,minWidth:180,display:"flex",alignItems:"center",gap:6},children:[n.jsx("span",{children:r}),s?n.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:n.jsx(Zt,{size:12})}):null]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsx(vr,{names:st,value:ke,onChange:fe,t:j}),n.jsx(ir,{t:j,value:$,onChange:Et}),n.jsx(mr,{checked:Re,onChange:Bt,t:j}),Re?n.jsx(br,{checked:ht,onChange:it,t:j}):null]})]}),n.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-end"},children:[n.jsx("textarea",{ref:Ve,value:Z,onChange:v=>{Y(v.target.value),D.current=void 0},rows:2,placeholder:i,onKeyDown:v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),Vt())},style:Uo(j)}),n.jsxs("button",{type:"button",className:"dql-hover dql-lift",onClick:Vt,disabled:!Z.trim()||X,style:zr(j,!!Z.trim()&&!X),children:[X?n.jsx(et,{size:15,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}}):n.jsx(ws,{size:15}),n.jsx("span",{children:X?"Working":"Ask"})]}),X?n.jsxs("button",{type:"button",className:"dql-hover",onClick:er,style:{...zr(j,!0),background:j.btnBg,borderColor:j.error,color:j.error},title:"Stop the active agent run",children:[n.jsx(rr,{size:13,fill:"currentColor"}),n.jsx("span",{children:"Stop"})]}):null]})]})]})}const gr="Ask a question — every answer is grounded in your certified metrics and dbt lineage. Use Research deeper on any answer for a slower investigation.",hr=[{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 Vn(){try{const e=JSON.parse(window.localStorage.getItem(On)??"[]");return Array.isArray(e)?e.filter(t=>{if(!t||typeof t!="object")return!1;const r=t;return typeof r.id=="string"&&typeof r.question=="string"&&typeof r.startedAt=="string"&&(r.threadId===void 0||typeof r.threadId=="string")}):[]}catch{return[]}}function xr(e){try{const t=Vn().filter(r=>r.id!==e.id);window.localStorage.setItem(On,JSON.stringify([...t,e].slice(-12)))}catch{}}function St(e){try{const t=Vn().filter(r=>r.id!==e);window.localStorage.setItem(On,JSON.stringify(t))}catch{}}function yr(e){const t=Vn().sort((r,i)=>i.startedAt.localeCompare(r.startedAt));return e?t.find(r=>r.threadId===e):t.find(r=>!r.threadId)}const Jr="dql.agent.thinkingMode",Zr="One-run consent: during explicit Research, enables up to 20 redacted result rows for Research narration and up to 200 redacted local-analysis tool rows. Ordinary Ask—and Research without this selection—keeps result rows local.";function ei(e,t){return e==="research"&&t}function ti(e,t,r){return r&&e.includes(r)?r:t&&e.includes(t)?t:e[0]}function mr({checked:e,onChange:t,t:r}){return n.jsxs("button",{type:"button","aria-pressed":e,"aria-label":"Research mode",title:"Research mode plans a bounded investigation and synthesizes the surrounding business context. Thinking effort is separate.",onClick:()=>t(!e),style:{minHeight:30,display:"inline-flex",alignItems:"center",gap:5,padding:"0 8px",border:e?"1px solid var(--accent)":"1px solid var(--border-default)",borderRadius:8,background:e?"var(--accent-dim)":"var(--bg-2)",color:e?"var(--accent-fg)":r.textMuted,fontSize:10.5,cursor:"pointer"},children:[n.jsx(rt,{size:13})," Research"]})}function br({checked:e,onChange:t,t:r}){return n.jsxs("label",{title:Zr,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:[n.jsx("input",{type:"checkbox","aria-label":"Allow redacted local-analysis tool rows for this Research run",checked:e,onChange:i=>t(i.target.checked)}),"Research tool rows (this run)"]})}function vr({names:e,value:t,onChange:r,t:i}){return e.length===0||!t?null:n.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:[n.jsx(Ji,{size:12}),n.jsx("select",{"aria-label":"Ask AI database connection",value:t,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=>n.jsx("option",{value:s,children:s},s))})]})}function io(){try{const e=window.localStorage.getItem(Jr);return e==="low"||e==="medium"||e==="high"||e==="auto"?e:"auto"}catch{return"auto"}}const so=new Set(["conversation","certified_answer","semantic_answer","generated_answer","research","sql_cell","dql_block_draft","modeling_draft","skill_draft","app_build","clarify","cancelled","blocked"]),oo=new Set(["certified","governed","grounded","review_required","blocked","not_applicable"]),ao=new Set(["completed","needs_review","needs_clarification","cancelled","blocked"]),lo=new Set(["conversational_reply","certified_answer_found","governed_semantic_answer","governed_compound_answer","generated_review_required","artifact_created","needs_clarification","human_review_required","cancelled","blocked"]);function ni(e,t=[]){const r=new Map(t.map(o=>[o.id,o])),i=new Set(e.flatMap(o=>o.agentRunId?[o.agentRunId]:[])),s=new Set(t.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??co(o)}]})}function co(e){var p,f,l;const t=so.has(e.route)?e.route:"generated_answer",r=oo.has(e.trustLabel)?e.trustLabel:e.certification==="certified"?"certified":"not_applicable",i=ao.has(e.runStatus)?e.runStatus:"completed",s=lo.has(e.stopReason)?e.stopReason:i==="cancelled"?"cancelled":i==="blocked"?"blocked":i==="needs_clarification"?"needs_clarification":i==="needs_review"?"human_review_required":t==="conversation"?"conversational_reply":r==="certified"?"certified_answer_found":"artifact_created",o=(((p=e.result)==null?void 0:p.columns)??[]).filter(d=>typeof d=="string"),a=(((f=e.result)==null?void 0:f.rowsSample)??[]).filter(d=>Array.isArray(d)).map(d=>Object.fromEntries(o.map((m,g)=>[m,d[g]]))),c=o.length>0?{columns:o,rows:a,rowCount:((l=e.result)==null?void 0:l.rowCount)??a.length}:void 0,u=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:t,status:i,trustState:r,stopReason:s,startedAt:e.createdAt,completedAt:e.createdAt,summary:e.answerSummary??e.question,answer:e.answerText??e.answerSummary,answerKind:t==="conversation"?"conversational":void 0,narrationIntegrityReceipt:e.narrationIntegrityReceipt,steps:[],artifacts:u?[u]:[],evaluations:[],events:[],nextActions:[],repairAttempts:0}}function uo(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 po(e,t){if(t.some(r=>r.type==="repair.attempted"))return"Refining the query and trying again";if(t.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 _n(e){for(let t=e.length-1;t>=0;t-=1)if(e[t].route)return e[t].route}function ri(e,t,r=!1){return e<12?null:!t&&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."}:t==="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 ii(e,t,r,i){return r==="certified"||e<20&&i===0||t!=="research"&&t!=="generated_answer"?null:{title:t==="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 si(e,t=!1){if(e.length===0&&t)return[{id:"background",label:"Continuing this request in the background",state:"active"}];const r=_n(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:uo(r),state:s||o?"complete":"active"}),(s||o)&&a.push({id:"execute",label:po(r,e),state:o?"complete":"active"}),o&&a.push({id:"verify",label:"Checking the result against governed evidence",state:"active"}),a}function jr({events:e,t,streamingAnswer:r,thinkingMode:i,backgroundRun:s}){var g;const[o,a]=h.useState(()=>Date.now());h.useEffect(()=>{const b=window.setInterval(()=>a(Date.now()),1e3);return()=>window.clearInterval(b)},[]);const c=(s==null?void 0:s.startedAt)??((g=e.find(b=>b.type==="run.started"))==null?void 0:g.at),u=c?Date.parse(c):o,p=Number.isFinite(u)?Math.max(0,Math.floor((o-u)/1e3)):0,f=ri(p,_n(e),e.some(b=>b.type==="repair.attempted"));if(r)return n.jsx("div",{style:{alignSelf:"stretch",padding:"4px 2px 8px",fontSize:13.5,lineHeight:1.55,color:t.textPrimary,whiteSpace:"pre-wrap",animation:"dql-agent-fadein 0.22s ease-out"},children:r});if(_n(e)==="conversation")return n.jsxs("div",{role:"status","aria-live":"polite",style:{alignSelf:"stretch",display:"flex",alignItems:"center",gap:9,padding:"5px 2px 9px",color:t.textSecondary,animation:"dql-agent-fadein 0.22s ease-out"},children:[n.jsx(Sr,{}),n.jsx("span",{style:{fontSize:13,lineHeight:1.4},children:"Replying…"})]});const d=si(e,!!s),m=p>=12?f==null?void 0:f.title:i==="high"?"Thorough mode is cross-checking the result.":null;return n.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:[d.map(b=>n.jsxs("div",{className:"dql-agent-activity",style:{display:"flex",alignItems:"center",gap:9,minHeight:18,color:b.state==="active"?t.textPrimary:t.textMuted},children:[n.jsx("span",{"aria-hidden":"true",style:{width:16,height:16,display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"0 0 auto",color:b.state==="active"?t.accent:t.textMuted},children:b.state==="active"?n.jsx(Sr,{}):n.jsx(It,{size:13,strokeWidth:2.2})}),n.jsxs("span",{style:{fontSize:12.5,lineHeight:1.4,fontWeight:b.state==="active"?620:450},children:[b.label,b.state==="active"?"…":""]})]},b.id)),m?n.jsx("span",{style:{paddingLeft:25,fontSize:10.5,lineHeight:1.4,color:t.textMuted},children:m}):null]})}function Sr(){return n.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=>n.jsx("span",{className:"dql-agent-thinking-dot",style:{width:3,height:3,borderRadius:999,background:"var(--accent)",animationDelay:`${e*120}ms`}},e))})}function wr({items:e,t,renderItem:r,cap:i=4}){const[s,o]=h.useState(!1),a=s?e:e.slice(0,i);return n.jsxs(n.Fragment,{children:[a.map((c,u)=>r(c,u)),e.length>i?n.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>o(c=>!c),style:{alignSelf:"flex-start",background:"none",border:"none",cursor:"pointer",color:t.accent,fontSize:11,padding:"2px 0",display:"inline-flex",alignItems:"center",gap:4},children:[s?n.jsx(Dr,{size:11}):n.jsx(an,{size:11}),s?"Show less":`Show all (${e.length})`]}):null]})}function oi(e){var i,s,o;const t=e.summary??(typeof((i=e.gap)==null?void 0:i.message)=="string"?e.gap.message:void 0)??"Task outcome recorded.";if(e.status==="completed"||e.status==="partial")return{glyph:"✓",label:e.status==="partial"?"Partial result":"Completed",detail:t,tone:"success"};if(e.status==="dependency_blocked"){const a=(s=e.dependencyTaskIds)!=null&&s.length?` Waiting for ${e.dependencyTaskIds.join(", ")}.`:"";return{glyph:"↳",label:"Dependency blocked",detail:`${t}${a}`,tone:"muted"}}const r=(o=e.failure)!=null&&o.code?` (${e.failure.code})`:"";return{glyph:"!",label:e.status==="gap"?"Needs coverage":"Blocked",detail:`${t}${r}`,tone:"warning"}}function ai({outcomes:e,summary:t,t:r}){const i=Array.isArray(e)?e.filter(fo):[],s=go(t)?t:void 0;if(i.length<2)return null;const o=s?s.status==="completed"?`Analytical tasks · ${s.taskCount} completed`:s.status==="partial"?`Analytical tasks · ${s.successfulTaskIds.length} of ${s.taskCount} completed`:"Analytical tasks · no completed task":"Analytical tasks";return n.jsxs("div",{style:{display:"grid",gap:5,padding:"8px 10px",border:`1px solid ${r.cellBorder}`,borderRadius:8,background:r.cellBg},children:[n.jsx("div",{style:{fontSize:10.5,fontWeight:800,color:r.textMuted,textTransform:"uppercase",letterSpacing:.4},children:o}),i.map(a=>{const c=oi(a),u=c.tone==="success"?r.success:c.tone==="muted"?r.textMuted:r.warning;return n.jsxs("div",{style:{display:"flex",gap:7,alignItems:"flex-start",fontSize:11.5,color:r.textSecondary},children:[n.jsx("span",{style:{color:u,fontWeight:800},children:c.glyph}),n.jsxs("span",{children:[n.jsx("strong",{children:a.taskId})," · ",n.jsx("strong",{children:c.label})," · ",c.detail]})]},a.taskId)})]})}function fo(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return typeof t.taskId=="string"&&(t.status==="completed"||t.status==="partial"||t.status==="gap"||t.status==="blocked"||t.status==="dependency_blocked")}function go(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return(t.status==="completed"||t.status==="partial"||t.status==="blocked")&&typeof t.taskCount=="number"&&Array.isArray(t.successfulTaskIds)&&Array.isArray(t.failedTaskIds)&&Array.isArray(t.dependencyBlockedTaskIds)}function ho({run:e,t,themeMode:r,appContext:i,onOpenApp:s,onInsertSql:o,onInsertDql:a,onOpenBlock:c,onOpenResearch:u,onSelectClarification:p,onNextAction:f}){var F;const{dispatch:l}=ln();if(e.route==="conversation"){const B=e.answerKind==="general_knowledge";return n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8,animation:"dql-agent-fadein 0.3s ease-out"},children:[n.jsxs("div",{style:Xo(t),children:[B?n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:10.5,color:t.textMuted,marginBottom:6,fontWeight:650},children:[n.jsx(en,{size:11})," General knowledge — not from your data"]}):null,n.jsx("div",{style:{fontSize:13.5,lineHeight:1.55,color:t.textPrimary},children:e.answer?n.jsx(Jt,{text:ft(e.answer),t}):e.summary})]}),e.nextActions.length>0?n.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:e.nextActions.map(K=>n.jsx("button",{type:"button",className:"dql-hover dql-lift",onClick:()=>f(K),style:sn(t),children:K.label},K.id))}):null]})}const d=e.steps??[],m=d.length>1,g=((F=e.plan)==null?void 0:F.source)==="llm",b=Yn(e),y=Gn(e),x=Tt(e),_=e.route==="certified_answer"||e.route==="generated_answer",z=e.nextActions.some(B=>B.route==="research"),N=_&&x&&!z,q=Fe(e),E=x&&!(q!=null&&q.sourcePath)&&!!((q==null?void 0:q.source)??Le(e)),V=Date.parse(e.startedAt),U=Date.parse(e.completedAt),T=Number.isFinite(V)&&Number.isFinite(U)?Math.max(0,Math.round((U-V)/1e3)):0,ie=ii(T,e.route,e.trustState,e.repairAttempts);return n.jsxs("div",{style:Jo(t),children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsx($o,{run:e}),n.jsx("div",{style:{minWidth:0,flex:1},children:n.jsx("div",{style:{fontSize:12.5,fontWeight:850,color:t.textPrimary},children:_o(e)})}),n.jsx(To,{run:e,t})]}),y?n.jsxs("div",{style:{display:"flex",gap:6,alignItems:"flex-start",fontSize:11,color:t.textMuted,lineHeight:1.4},children:[e.trustState==="certified"?n.jsx(Se,{size:12,color:t.success,style:{flex:"0 0 auto",marginTop:1}}):e.trustState==="governed"||e.trustState==="grounded"?n.jsx(Se,{size:12,color:t.accent,style:{flex:"0 0 auto",marginTop:1}}):n.jsx(Be,{size:12,color:t.warning,style:{flex:"0 0 auto",marginTop:1}}),n.jsx("span",{children:y})]}):null,g||m||e.repairAttempts>0?n.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[g?n.jsx(kn,{t,icon:n.jsx(qt,{size:11}),label:"AI plan",tone:"accent"}):null,m?n.jsx(kn,{t,icon:n.jsx(Ct,{size:11}),label:`${d.length} steps`,tone:"muted"}):null,e.repairAttempts>0?n.jsx(kn,{t,icon:n.jsx(un,{size:11}),label:`${e.repairAttempts} repair${e.repairAttempts>1?"s":""}`,tone:"warning"}):null]}):null,e.summary&&!(Ke(e)&&Lo(Me(e.summary),ft(Ke(e))))?n.jsx("div",{style:{fontSize:12.5,lineHeight:1.45,color:t.textSecondary},children:Me(e.summary)}):null,Ke(e)?n.jsx("div",{style:Zo(t),children:n.jsx(Jt,{text:ft(Ke(e)),t})}):null,n.jsx(ai,{outcomes:e.analyticalTaskOutcomes,summary:e.analyticalTaskOutcomeSummary,t}),n.jsx(pi,{run:e,t,onSelect:p}),b.length>0?n.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",alignItems:"center"},children:[n.jsx("span",{style:{fontSize:11,color:t.textMuted},children:"Evidence:"}),b.map(B=>n.jsxs("span",{style:Ei(t,B.certified),children:[B.certified?n.jsx(Se,{size:11}):n.jsx(rt,{size:11}),n.jsx("span",{children:B.label})]},B.label))]}):null,n.jsx(Mi,{run:e,t}),e.artifacts.length>0?n.jsx("div",{style:{display:"grid",gap:8,gridTemplateColumns:"minmax(0, 1fr)",minWidth:0},children:e.artifacts.map(B=>n.jsx(Ii,{artifact:B,t,themeMode:r,onInsertSql:o,onInsertDql:a,sourceRunId:e.id,sourceQuestion:e.question,onOpenBlock:c,onOpenResearch:u,onOpenApp:s,onNextAction:f},B.id))}):null,m?n.jsx(qi,{steps:d,t}):n.jsx(_i,{evaluations:e.evaluations,t}),e.events.length>0||e.traceReference?n.jsxs("div",{style:{display:"flex",gap:12,flexWrap:"wrap",alignItems:"center"},children:[e.events.length>0?n.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:t.textMuted,fontSize:11.5,fontFamily:t.font},title:"See what the agent did and where the time went",children:[n.jsx(qt,{size:12})," View steps · where the time went"]}):null,e.traceReference?n.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>l({type:"OPEN_ASK_TRACE",runId:e.id}),style:{display:"inline-flex",alignItems:"center",gap:5,alignSelf:"flex-start",background:"transparent",border:"none",cursor:"pointer",padding:0,color:t.accent,fontSize:11.5,fontFamily:t.font,fontWeight:650},title:"Open the local, redacted Ask trace",children:[n.jsx(dn,{size:12})," Open full trace"]}):null]}):null,ie?n.jsxs("div",{style:{display:"grid",gap:3,padding:"8px 9px",border:`1px solid ${t.accent}33`,borderRadius:7,background:`${t.accent}0a`},children:[n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,color:t.textSecondary,fontSize:11,fontWeight:800},children:[n.jsx(en,{size:11,color:t.accent})," ",ie.title]}),n.jsx("span",{style:{fontSize:10.5,color:t.textMuted,lineHeight:1.45},children:ie.detail})]}):null,x||N||e.nextActions.length>0?n.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",alignItems:"center"},children:[x?n.jsx(Un,{run:e,t,appContext:i,onOpenApp:s}):null,E?n.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>f({id:"save-dql-block",label:"Save as block",route:"dql_block_draft"}),style:te(t),children:[n.jsx(Wn,{size:11})," Save as block"]}):null,N?n.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>f({id:"research-deeper",label:"Research this deeper",route:"research"}),style:te(t),title:"Run a slower, multi-step investigation on this question",children:[n.jsx(rt,{size:11}),"Research this deeper"]}):null,e.nextActions.filter(B=>B.id!=="pin-to-app"&&B.id!=="research-deeper"&&B.id!=="confirm-app-build"&&B.id!=="request-certification").map(B=>n.jsx("button",{type:"button",className:"dql-hover",onClick:()=>f(B),style:te(t),children:B.label},B.id))]}):null]})}function li(e){const t=[];return e.analytical&&t.push({id:"how",label:"How it answered"}),(e.hasDql||e.analytical&&e.blocked)&&t.push({id:"dql",label:"DQL"}),(e.hasSql||e.analytical&&e.blocked)&&t.push({id:"sql",label:"SQL"}),e.hasLineage&&t.push({id:"lineage",label:"Lineage"}),t.push({id:"trust",label:"Trust & steps"}),t}const xo=`
|
|
68
|
+
@keyframes dql-agent-run-spin { to { transform: rotate(360deg); } }
|
|
69
|
+
@keyframes dql-agent-fadein { from { opacity: 0; transform: translateY(3px); } to { opacity: 1; transform: none; } }
|
|
70
|
+
@keyframes dql-agent-thinking-dot { 0%, 65%, 100% { opacity: .28; transform: translateY(0); } 32% { opacity: 1; transform: translateY(-2px); } }
|
|
71
|
+
@keyframes dql-agent-activity-in { from { opacity: 0; transform: translateY(2px); } to { opacity: 1; transform: none; } }
|
|
72
|
+
.dql-agent-thinking-dot { animation: dql-agent-thinking-dot 1.05s ease-in-out infinite; }
|
|
73
|
+
.dql-agent-activity { animation: dql-agent-activity-in .22s ease-out; }
|
|
74
|
+
.dql-hover { transition: filter .15s ease, transform .12s ease, box-shadow .15s ease, background .15s ease, color .15s ease, border-color .15s ease; }
|
|
75
|
+
.dql-hover:hover { filter: brightness(1.03); }
|
|
76
|
+
.dql-hover:active { transform: translateY(0.5px); }
|
|
77
|
+
.dql-lift:hover { transform: translateY(-1px); }
|
|
78
|
+
.dql-ask-ghost:hover { background: var(--bg-0); color: var(--text-primary) !important; }
|
|
79
|
+
.dql-ask-chip:hover { border-color: var(--accent) !important; box-shadow: 0 1px 6px rgba(107,93,211,0.12); }
|
|
80
|
+
details > summary::-webkit-details-marker { display: none; }
|
|
81
|
+
@media (prefers-reduced-motion: reduce) { .dql-agent-thinking-dot, .dql-agent-activity { animation: none !important; } }
|
|
82
|
+
`;function yo(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 Ue(e){return cn(e,{variant:"ghost",size:"sm"})}function wn(e,t){return e.kind==="app_proposal"||e.kind==="dql_block_draft"||e.kind==="research_run"||!!hn(t)}function pn(e,t){var u,p;const r=[],i=Ee(t),s=e.kind==="answer"?(u=i==null?void 0:i.rows)!=null&&u.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)??((p=i==null?void 0:i.rows)==null?void 0:p.length);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`);const a=di(t),c=e.trustState==="certified"?"certified block":e.trustState==="governed"||e.trustState==="grounded"?"governed":e.trustState==="blocked"?a==="semantic"?"semantic compilation failed":a==="generic"?"compilation failed":"blocked":"AI-generated";return r.push(c),r.join(" · ")}const kr=["supported","contradicted","inconclusive","failed","skipped"];function Hn(e){var m;const t=S(e.researchLedgerV3)??S(e.researchLedgerV2);if(!t)return;const r=Array.isArray(t.entries)?t.entries:[],i={supported:0,contradicted:0,inconclusive:0,failed:0,skipped:0};for(const g of r){const b=(m=S(g))==null?void 0:m.verdict;typeof b=="string"&&kr.includes(b)&&(i[b]+=1)}const s=r.length,o=r.filter(g=>{var b;return((b=S(g))==null?void 0:b.evidenceKind)==="lineage_graph"}).length,a=typeof t.groundableBranchCount=="number"&&Number.isFinite(t.groundableBranchCount)&&t.groundableBranchCount>=0?Math.trunc(t.groundableBranchCount):s,c=t.limitedScope===!0||a<3,u=kr.flatMap(g=>{const b=i[g];return b?[`${b} ${g}`]:[]}),p=s===0?"no branch verdicts recorded":u.join(" · "),f=c?`Limited research scope · ${p}`:`Research branches · ${p}`,l=o>0?` ${o} structural lineage ${o===1?"check was":"checks were"} local-only and non-causal.`:"",d=c?`Limited research scope: ${a} of at least 3 evidence-supported branches were available. Verdicts: ${p}.${l}`:`${a} evidence-supported branches were available. Verdicts: ${p}.${l}`;return{branchCount:s,groundableBranchCount:a,limitedScope:c,lineageBranchCount:o,verdicts:i,compactLabel:f,detail:d}}function ci(e){const t=e.artifacts.find(r=>r.kind==="research_run");return t?Hn(re(t)):void 0}function Rt(e,t){const i=/^(?:certified|governed semantic|review-required|exploratory dbt-grounded) answer$/i.test(t.title.trim())?e.question:t.title,s=Me(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 S(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function di(e){var u;const t=S(e.semanticExecutionTrace),r=S(t==null?void 0:t.failure);if((r==null?void 0:r.phase)==="compilation"&&(r.code==="SEMANTIC_COMPILATION_FAILED"||r.code==="COMPILATION_FAILED"))return"semantic";const i=S(e.diagnosticReceiptV4),s=S(i==null?void 0:i.terminalIncident)??S((u=S(i==null?void 0:i.summary))==null?void 0:u.terminalIncident);if((s==null?void 0:s.code)==="COMPILATION_FAILED")return s.boundary==="semantic.compile"?"semantic":"generic";const o=S(e.analyticalFailure),a=typeof(o==null?void 0:o.code)=="string"?o.code:typeof e.failureCode=="string"?e.failureCode:void 0,c=typeof(o==null?void 0:o.phase)=="string"?o.phase:void 0;if(a==="COMPILATION_FAILED"&&(c===void 0||c==="compilation"))return t?"semantic":"generic"}function ui(e){const t=[],r=new Set,i=(s,o)=>{const a=S(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 u=typeof a.kind=="string"?a.kind:o,p=`${u??""}:${c}`;if(r.has(p))return;r.add(p);const f=[a.description,a.provenance,a.sourceTier,a.source].find(l=>typeof l=="string"&&l.trim().length>0);t.push({name:c,kind:u,detail:f})};for(const s of e.artifacts){const o=re(s),a=S(o.evidence);for(const p of["lineage","sourceTables","semanticObjects","selectedAssets"]){const f=a==null?void 0:a[p];Array.isArray(f)&&f.forEach(l=>i(l,p==="sourceTables"?"source":void 0))}const c=S(o.analysisPlan)??S(a==null?void 0:a.analysisPlan),u=c==null?void 0:c.candidateTables;Array.isArray(u)&&u.forEach(p=>i(p,"relation"))}return t.slice(0,24)}function Qn(e,t){var i,s;const r=re(t);return((i=e.diagnosticReceiptV8)==null?void 0:i.mode)==="authoritative_v2"||fn(r)?"how":(s=Fe(e)??Mt(r))!=null&&s.source?"dql":Le(e)??(typeof r.sql=="string"?r.sql:void 0)?"sql":ui(e).length>0?"lineage":"trust"}function mo({run:e,artifact:t,selected:r,t:i,themeMode:s,onInspect:o}){const a=re(t),c=Ee(a),[u,p]=h.useState(!1);if(h.useEffect(()=>{if(!u)return;const b=y=>{y.key==="Escape"&&p(!1)};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[u]),!c)return null;const f=$i(a,c),l=Qn(e,t),d=Fe(e)??Mt(a),m=t.trustState==="certified"?Ri(t,a):void 0,g=n.jsxs("section",{"data-followup":"table","data-followup-run-id":e.id,"data-followup-artifact-id":t.id,"aria-label":`${Rt(e,t)} result`,style:{border:`1px solid ${r?"var(--accent)":"var(--border-default)"}`,borderRadius:12,background:"var(--bg-2)",overflow:"hidden",boxShadow:u?"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)",...u?{width:"min(1440px, calc(100vw - 48px))",maxHeight:"calc(100vh - 48px)"}:{}},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"11px 13px",borderBottom:"1px solid var(--border-subtle)"},children:[n.jsx("span",{style:{width:30,height:30,borderRadius:8,background:t.trustState==="certified"?"var(--status-success-bg)":"var(--accent-dim)",color:t.trustState==="certified"?"var(--status-success)":"var(--accent)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:n.jsx(gt,{kind:t.kind})}),n.jsxs("div",{style:{minWidth:0,flex:1},children:[n.jsx("div",{style:{fontSize:12.5,fontWeight:700,color:i.textPrimary,lineHeight:1.35},children:Rt(e,t)}),n.jsx("div",{style:{fontSize:11,color:i.textMuted,marginTop:2},children:pn(t,a)})]}),n.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:()=>o(l),style:Ue(i),children:[n.jsx(qt,{size:12})," Inspect"]}),n.jsxs("button",{type:"button",className:"dql-ask-ghost","aria-label":u?"Return result to Copilot":"Expand result",title:u?"Return result to Copilot":"Expand this result for wide tables",onClick:()=>p(b=>!b),style:Ue(i),children:[u?n.jsx(us,{size:12}):n.jsx(is,{size:12}),u?"Restore":"Expand result"]})]}),d?n.jsx(Ci,{artifact:d,certifiedBlockName:m,initialResult:c,initialChartConfig:f,payload:a,executionTarget:e.executionTarget,t:i,themeMode:s,embedded:!0,expanded:u}):n.jsx(Dn,{result:c,themeMode:s,t:i,chartConfig:f,embedded:!0,tabLabels:{table:"Results",chart:"Visualization"},contentMaxHeight:u?"calc(100vh - 172px)":void 0,tableMaxHeight:u?"calc(100vh - 250px)":void 0})]});return!u||typeof document>"u"?g:n.jsxs(n.Fragment,{children:[n.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."}),es.createPortal(n.jsx("div",{role:"dialog","aria-modal":"true","aria-label":`${Rt(e,t)} 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:n.jsx("div",{onClick:b=>b.stopPropagation(),style:{minWidth:0,maxWidth:"100%"},children:g})}),document.body)]})}function Ar(e){const{run:t,t:r,themeMode:i,threadId:s,appContext:o,selectedArtifactId:a,onOpenArtifact:c,onOpenApp:u,onInsertSql:p,onInsertDql:f,onReplaceDql:l,insertDqlActionLabel:d,replaceDqlActionLabel:m,onOpenBlock:g,onOpenResearch:b,onSelectClarification:y,onNextAction:x,onRepairedRun:_}=e,{dispatch:z}=ln(),[N,q]=h.useState(!1),E=c??(()=>z({type:"OPEN_AGENT_LOG",run:t}));if(t.route==="conversation"){const $=t.answerKind==="general_knowledge";return n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8,animation:"dql-agent-fadein 0.3s ease-out",maxWidth:"100%"},children:[$?n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:10.5,color:r.textMuted,fontWeight:650},children:[n.jsx(en,{size:11})," General knowledge — not from your data"]}):null,n.jsx("div",{"data-followup":"answer",style:{fontSize:14.5,lineHeight:1.65,color:r.textPrimary},children:t.answer?n.jsx(Jt,{text:ft(t.answer),t:r}):t.summary}),t.nextActions.length>0?n.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:t.nextActions.map(oe=>n.jsx("button",{type:"button",className:"dql-hover dql-lift",onClick:()=>x(oe),style:sn(r),children:oe.label},oe.id))}):null]})}const V=t.trustState==="certified",U=t.status==="blocked",T=t.status==="cancelled"||t.stopReason==="cancelled"||t.route==="cancelled",ie=t.status==="needs_clarification",F=Ke(t),B=T?"Stopped by user":U?"Couldn’t run this query":ie?"Needs clarification":V?"Certified answer":"AI-generated answer",K=T?t.summary||"Stopped by user.":U?Fi(t):void 0,w=Li(t),j=Yn(t),D=T?[]:t.artifacts,Z=D.filter($=>{const oe=re($);return!wn($,oe)&&!!Ee(oe)}),Y=new Set(Z.map($=>$.id)),Q=D.filter($=>!wn($,re($))&&!Y.has($.id)),W=D.filter($=>wn($,re($))),P=Z[0]??Q[0]??D[0],H=D.find($=>$.kind==="research_run"),ue=ci(t),he=ue?0:t.evaluations.filter($=>$.severity==="info").length,X=Tt(t),I=t.route==="certified_answer"||t.route==="semantic_answer"||t.route==="generated_answer",ce=t.nextActions.some($=>$.route==="research"),A=I&&X&&!ce,L=Fe(t),ee=X&&!(L!=null&&L.sourcePath)&&!!((L==null?void 0:L.source)??Le(t)),ne=d&&f||m&&l?rn(t):void 0,ae=()=>{var oe;const $=F?ft(F):K??t.summary;$&&((oe=navigator.clipboard)==null||oe.writeText($).catch(()=>{}),q(!0),window.setTimeout(()=>q(!1),1400))};return n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10,maxWidth:"100%",animation:"dql-agent-fadein 0.3s ease-out"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,flexWrap:"wrap"},children:[T?n.jsx(Ct,{size:14,color:r.textMuted}):U?n.jsx(Be,{size:14,color:r.error}):V?n.jsx(Se,{size:14,color:r.success}):n.jsx(tt,{size:14,color:r.accent}),n.jsx("span",{style:{fontSize:12,fontWeight:650,color:T?r.textMuted:U?r.error:r.textSecondary},children:B}),V&&j[0]?n.jsxs("span",{style:{fontSize:11,color:r.textMuted},children:["from ",n.jsx("span",{style:{color:r.accent,fontWeight:600},children:j[0].label})]}):!U&&!T&&ue&&H?n.jsxs("button",{type:"button","aria-label":"Open Research branch evidence",onClick:()=>E(H.id,"trust"),style:{fontSize:11,color:ue.limitedScope?r.warning:r.textMuted,background:"none",border:"none",cursor:"pointer",padding:0,fontFamily:r.font,display:"inline-flex",alignItems:"center",gap:4,textAlign:"left"},children:[n.jsx(rt,{size:11,color:ue.limitedScope?r.warning:r.accent})," ",ue.compactLabel]}):!U&&!T&&P&&he>0?n.jsxs("button",{type:"button",onClick:()=>E(P.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:[n.jsx(It,{size:11,color:r.success})," ",he," check",he===1?"":"s"," passed"]}):null]}),F?n.jsx("div",{"data-followup":"answer",style:{fontSize:14.5,lineHeight:1.65,color:r.textPrimary},children:n.jsx(Jt,{text:ft(F),t:r})}):T?n.jsx("div",{"data-followup":"answer",style:{fontSize:14,lineHeight:1.6,color:r.textMuted},children:Me(t.summary||"Stopped by user.")}):K?n.jsx(ea,{run:t,detail:K,threadId:s,onRepaired:$=>_(t.id,$),t:r}):t.summary?n.jsx("div",{"data-followup":"answer",style:{fontSize:14,lineHeight:1.6,color:r.textSecondary},children:Me(t.summary)}):null,w?n.jsxs("div",{role:"status",style:{fontSize:11.5,lineHeight:1.5,color:r.warning,borderLeft:`2px solid ${r.warning}`,paddingLeft:8},children:["Capture warning: ",Me(w)," The query result is still valid."]}):null,n.jsx(pi,{run:t,t:r,onSelect:y}),Z.map($=>n.jsx(mo,{run:t,artifact:$,selected:$.id===a,t:r,themeMode:i,onInspect:oe=>E($.id,oe)},$.id)),Q.map($=>{const oe=re($),Re=$.id===a;return n.jsxs("button",{type:"button",className:"dql-ask-chip",onClick:()=>E($.id,Qn(t,$)),style:{display:"flex",alignItems:"center",gap:10,width:"fit-content",maxWidth:"100%",padding:"9px 12px",borderRadius:10,border:`1px solid ${Re?"var(--accent)":"var(--border-default)"}`,background:"var(--bg-2)",boxShadow:Re?"0 1px 6px rgba(107,93,211,0.12)":"none",cursor:"pointer",textAlign:"left",fontFamily:r.font},children:[n.jsx("span",{style:{width:30,height:30,borderRadius:7,background:$.trustState==="certified"?"var(--status-success-bg)":"var(--accent-dim)",color:$.trustState==="certified"?"var(--status-success)":"var(--accent)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:n.jsx(gt,{kind:$.kind})}),n.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:1,minWidth:0},children:[n.jsx("span",{style:{fontSize:12.5,fontWeight:650,color:r.textPrimary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Me($.title)}),n.jsx("span",{style:{fontSize:11,color:r.textMuted},children:pn($,oe)})]}),n.jsx(Lr,{size:14,color:r.textMuted,style:{flexShrink:0,marginLeft:6}})]},$.id)}),W.length>0?n.jsx("div",{style:{display:"grid",gap:8,gridTemplateColumns:"minmax(0, 1fr)",minWidth:0},children:W.map($=>n.jsx(Ii,{artifact:$,t:r,themeMode:i,onInsertSql:p,onInsertDql:f,insertDqlActionLabel:d,sourceRunId:t.id,sourceQuestion:t.question,onOpenBlock:g,onOpenResearch:b,onOpenApp:u,onNextAction:x},$.id))}):null,F||K||ne||X||ee||A||P?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexWrap:"wrap",marginTop:-2},children:[ne&&f?n.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:()=>f(ne),style:Ue(r),children:[n.jsx(At,{size:12})," ",d]}):null,ne&&l&&m?n.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:()=>l(ne),style:Ue(r),children:[n.jsx(ns,{size:12})," ",m]}):null,F||K?n.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:ae,style:Ue(r),children:[N?n.jsx(It,{size:12}):n.jsx(Pr,{size:12})," ",N?"Copied":"Copy"]}):null,X?n.jsx(Un,{run:t,t:r,appContext:o,onOpenApp:u}):null,ee?n.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:()=>x({id:"save-dql-block",label:"Save as block",route:"dql_block_draft"}),style:Ue(r),children:[n.jsx($t,{size:12})," Save as block"]}):null,A?n.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:()=>x({id:"research-deeper",label:"Research this deeper",route:"research"}),style:Ue(r),children:[n.jsx(rt,{size:12})," Research deeper"]}):null,P?n.jsxs("button",{type:"button",className:"dql-ask-ghost",onClick:()=>E(P.id,fn(re(P))?"how":"trust"),style:Ue(r),children:[n.jsx(qt,{size:12})," How it was answered"]}):null]}):null]})}function pi({run:e,t,onSelect:r}){var i;return e.status!=="needs_clarification"||!((i=e.clarificationOptions)!=null&&i.length)||!r?null:n.jsx("div",{"aria-label":"Choose a governed meaning",style:{display:"grid",gap:7,maxWidth:620},children:e.clarificationOptions.map(s=>n.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:t.textPrimary,cursor:"pointer",textAlign:"left",fontFamily:t.font},children:[n.jsx("span",{style:{fontSize:12.5,fontWeight:700},children:s.label}),s.description?n.jsx("span",{style:{fontSize:11,lineHeight:1.4,color:t.textMuted},children:s.description}):null]},s.id))})}function fi(e){const t=S(e);return(t==null?void 0:t.version)===8&&(t.mode==="legacy_v1"||t.mode==="shadow_v2"||t.mode==="authoritative_v2")&&Array.isArray(t.contextCoverage)&&Array.isArray(t.observations)&&Array.isArray(t.tierAttempts)&&S(t.outcome)!==void 0}function gi(e){const t=e.executionError;if(typeof t=="string"&&t.trim())return{stage:"execution",message:t};const r=S(t);if(r)return{stage:"execution",...r};const i=typeof e.refusalCode=="string"?e.refusalCode:void 0;if(i){const s=S(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 fn(e){return!!(S(e.resolvedAnalyticalPlan)||S(e.analyticalExecutionGraph)||S(e.analyticalExecutionReceipt)||S(e.analyticalFailure)||S(e.semanticExecutionTrace)||S(e.diagnosticReceipt)||S(e.diagnosticReceiptV3)||S(e.diagnosticReceiptV4)||S(e.diagnosticReceiptV5)||fi(e.diagnosticReceiptV8)||gi(e))}function hi(e){if(!fn(e))return;const t=S(e.diagnosticReceipt),r=S(e.diagnosticReceiptV3),i=S(e.diagnosticReceiptV4),s=S(e.diagnosticReceiptV5),o=fi(e.diagnosticReceiptV8)?e.diagnosticReceiptV8:void 0,a=s||i||r?{...t,...r,...i,...s,failure:(r==null?void 0:r.failure)??(t==null?void 0:t.failure)}:t,c=S(e.resolvedAnalyticalPlan)??S(a==null?void 0:a.resolvedAnalyticalPlan);return{plan:c,frame:S(c==null?void 0:c.analyticalFrame),graph:S(e.analyticalExecutionGraph),receipt:S(e.analyticalExecutionReceipt),facts:S(e.analyticalFacts),narrative:S(e.analyticalNarrative),freshness:S(e.analyticalFreshnessObservation),failure:S(e.analyticalFailure)??S(a==null?void 0:a.failure)??gi(e),semantic:S(e.semanticExecutionTrace),diagnostic:a,...bo(i==null?void 0:i.summary)?{decisionSummary:i.summary}:{},...vo(s==null?void 0:s.summary)?{runtimeDecisionSummary:s.summary}:{},...o?{runtimeReceiptV8:o}:{}}}function bo(e){const t=S(e);return(t==null?void 0:t.version)===1&&typeof t.summaryFingerprint=="string"&&S(t.understoodRequest)!==void 0&&Array.isArray(t.evidenceByRole)&&Array.isArray(t.tierDecisions)&&typeof t.safeNextAction=="string"}function vo(e){const t=S(e);return(t==null?void 0:t.version)===2&&typeof t.summaryFingerprint=="string"&&typeof t.runtimeMode=="string"&&typeof t.whatHappened=="string"&&typeof t.why=="string"&&typeof t.impact=="string"}function jo(){return["Performance & provider egress","Plan","DQL","Compiled SQL","Lineage","Trust & evidence","Actual steps","Failure & repair"]}function So(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(t=>!!t)}function wo(e){var p,f;const t=new Map;let r=0,i=0,s=0,o=0;for(const l of e.spans){let d;l.name==="provider.attempt"?((f=S((p=S(l.payload))==null?void 0:p.attempt))==null?void 0:f.admission)!=="denied"&&(r+=1,d="provider"):l.name==="tool.call"?(i+=1,d="tool"):l.name==="sql.execute"?(s+=1,d="sql"):l.name==="sql.repair"&&(o+=1,d="repair");const m=Rr(l.durationMs);if(m===void 0)continue;const g=d??(l.stage==="provider"||l.stage==="tool"||l.stage==="sql"||l.stage==="request"?void 0:l.stage);g&&t.set(g,(t.get(g)??0)+m)}const c=["conversation","snapshot","retrieval","meaning","cascade","plan","provider","tool","sql","repair","result","narration","research","persistence"].flatMap(l=>t.has(l)?[`${l}: ${Qe(t.get(l))}`]:[]).join(" · "),u=t.get("sql");return{totalDurationMs:Rr(e.envelope.durationMs),sqlExecutionDurationMs:u,stages:c||"No completed physical provider, tool, SQL, or repair stage was recorded.",providerAttempts:r,toolCalls:i,sqlExecutions:s,repairs:o}}function tn(e){var c,u;if((e==null?void 0:e.mode)!=="authoritative_v2")return;const t=[...e.observations],r=t.slice().reverse().find(p=>p.frozen===!0&&(typeof p.planId=="string"||typeof p.inputFingerprint=="string"))??t.slice().reverse().find(p=>p.frozen===!0),i=t.slice().reverse().find(p=>p.outcome==="executed"),s=e.tierAttempts.slice().reverse().find(p=>p.frozen)??e.tierAttempts.slice().reverse().find(p=>p.outcome==="executed")??void 0,o=(r==null?void 0:r.tier)??(i==null?void 0:i.tier)??(s==null?void 0:s.tier)??e.controllerTier,a=(c=r==null?void 0:r.candidateIds)!=null&&c.length?r.candidateIds:(u=i==null?void 0:i.candidateIds)!=null&&u.length?i.candidateIds:(s==null?void 0:s.candidateIds)??[];return{receipt:e,selectedTier:o,...typeof(r==null?void 0:r.planId)=="string"?{planId:r.planId}:{},...typeof(r==null?void 0:r.inputFingerprint)=="string"?{frozenPlanFingerprint:r.inputFingerprint}:{},candidateIds:a,candidateAdmissionCount:e.initialCandidateCount,retainedCandidateCount:e.retainedCandidateCount,tierAttempts:e.tierAttempts}}function qn(e){return e.planId?`${e.planId}${e.receipt.planFrozen?" · frozen":""}`:e.receipt.planFrozen?"Frozen plan ID not retained":"No plan frozen"}function zn(e){return e.tierAttempts.length===0?"No V2 tier attempt was retained.":e.tierAttempts.map(t=>`${t.tier}: ${t.outcome}${t.frozen?" (frozen)":""}`).join(" · ")}function ko(e){return e.receipt.contextCoverage.length===0?"No source coverage was retained.":e.receipt.contextCoverage.map(t=>`${t.source}: ${t.status} (${t.admittedCandidateCount} admitted${t.excludedCandidateCount?`, ${t.excludedCandidateCount} excluded`:""})`).join(`
|
|
83
|
+
`)}function xi(e){const t=e.receipt.outcome;return`${t.connectionAttempted?"Connection attempted":"No connection attempted"} · ${t.executionAttempts} execution attempt${t.executionAttempts===1?"":"s"}`}function yi(e){const t=e.receipt.outcome;return`${t.factCount} validated fact${t.factCount===1?"":"s"} · ${t.narration.replace(/_/g," ")}`}function Cr(e,t){const r=(t==null?void 0:t.runtimeReceiptV8)??e.diagnosticReceiptV8;return(r==null?void 0:r.mode)==="authoritative_v2"?r.activity:void 0}function Yt(e){if(e==="authoritative_v2")return"Authoritative V2 receipt";if(e==="shadow_v2")return"Shadow V2 observation only — legacy V1 served this answer.";if(e==="legacy_v1")return"Legacy V1 runtime"}function Rr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function $n(e,t){var f;if(t){const l=wo(t),d=Cr(e,t),m=tn(t.runtimeReceiptV8??e.diagnosticReceiptV8),g=(d==null?void 0:d.providerDispatches)??l.providerAttempts,b=(d==null?void 0:d.toolCalls)??l.toolCalls,y=(d==null?void 0:d.executionAttempts)??l.sqlExecutions,x=(d==null?void 0:d.repairs)??l.repairs,_=Tn(e,g),z=l.totalDurationMs===void 0?void 0:Math.max(0,l.totalDurationMs-(l.sqlExecutionDurationMs??0)),N=Array.from(new Set([...m!=null&&m.planId?[m.planId]:[],...(e.artifacts??[]).flatMap(E=>{var ie;const V=re(E),U=S(V.resolvedAnalyticalPlan)??S((ie=S(V.diagnosticReceipt))==null?void 0:ie.resolvedAnalyticalPlan),T=S(V.analyticalExecutionReceipt);return[U==null?void 0:U.planId,T==null?void 0:T.planId].filter(F=>typeof F=="string"&&F.length>0)})])),q=Array.from(new Set((e.artifacts??[]).map(E=>E.id).filter(E=>typeof E=="string"&&E.length>0)));return[["Total",l.totalDurationMs===void 0?"Not recorded":Qe(l.totalDurationMs)],["Warehouse",l.sqlExecutionDurationMs===void 0?"Not recorded":Qe(l.sqlExecutionDurationMs)],["Orchestration",z===void 0?"Not recorded":Qe(z)],["Stages",l.stages],["Calls",`${g} provider · ${b} tool · ${y} SQL · ${x} repair`],["Provider rows",_],["Trace evidence",d?"Authoritative V2 receipt (canonical physical egress and execution counts)":"Canonical local physical trace"],...Yt(t.runtimeMode??e.askAgentRuntimeMode)?[["Ask runtime",Yt(t.runtimeMode??e.askAgentRuntimeMode)]]:[],...e.narrationIntegrityReceipt?[["Narration",Ir(e.narrationIntegrityReceipt)]]:[],["Plan ID",N.length>0?N.join(", "):"Not recorded"],["Artifact IDs",q.length>0?q.join(", "):"None"],["Fallback",((f=e.telemetry)==null?void 0:f.fallbackReason)??"None"]]}const r=e.telemetry;if(!r)return;const i=Cr(e),s=tn(e.diagnosticReceiptV8),o=r.stageDurationsMs.total,a=r.warehouseDurationMs,c=o===void 0||a===void 0?void 0:Math.max(0,o-a),u=Array.from(new Set([...s!=null&&s.planId?[s.planId]:[],...(e.artifacts??[]).flatMap(l=>{var b;const d=re(l),m=S(d.resolvedAnalyticalPlan)??S((b=S(d.diagnosticReceipt))==null?void 0:b.resolvedAnalyticalPlan),g=S(d.analyticalExecutionReceipt);return[m==null?void 0:m.planId,g==null?void 0:g.planId].filter(y=>typeof y=="string"&&y.length>0)})])),p=Array.from(new Set((e.artifacts??[]).map(l=>l.id).filter(l=>typeof l=="string"&&l.length>0)));return[["Total",Qe(r.stageDurationsMs.total)],["Warehouse",r.warehouseDurationMs===void 0?"Not recorded":Qe(r.warehouseDurationMs)],["Orchestration",c===void 0?"Not recorded":Qe(c)],["Stages",Object.entries(r.stageDurationsMs).filter(([l])=>l!=="total").map(([l,d])=>`${l}: ${Qe(d)}`).join(" · ")],["Calls",`${(i==null?void 0:i.providerDispatches)??r.providerRoundTrips} provider · ${(i==null?void 0:i.toolCalls)??r.toolCalls} tool · ${(i==null?void 0:i.executionAttempts)??r.sqlExecutions} SQL · ${(i==null?void 0:i.repairs)??r.repairs} repair`],["Provider rows",Tn(e,(i==null?void 0:i.providerDispatches)??r.providerRoundTrips)],...i?[["Trace evidence","Authoritative V2 receipt (canonical physical egress and execution counts)"]]:[],...Yt(e.askAgentRuntimeMode)?[["Ask runtime",Yt(e.askAgentRuntimeMode)]]:[],...e.narrationIntegrityReceipt?[["Narration",Ir(e.narrationIntegrityReceipt)]]:[],["Plan ID",u.length>0?u.join(", "):"Not recorded"],["Artifact IDs",p.length>0?p.join(", "):"None"],["Fallback",r.fallbackReason??"None"]]}function Tn(e,t){if(t===0)return"0 result rows sent to providers (0 content-free receipts)";const r=e.providerEgressReceipts??[];if(r.length===0)return`No retained egress receipt for ${t} recorded provider attempt${t===1?"":"s"}`;const i=r.filter(f=>f.resultRowCount>0),s=i.reduce((f,l)=>f+l.resultRowCount,0),o=f=>{const l=typeof f.dispatchPhase=="string"?f.dispatchPhase:typeof f.purpose=="string"?f.purpose:void 0;return l==null?void 0:l.replace(/_/g," ")},a=[...new Set(r.filter(f=>f.resultRowCount===0).map(o).filter(f=>!!f))];if(s===0){const f=a.length>0?` ${a.join(", ")}`:"";return`0 result rows sent to providers (${r.length} content-free${f} receipt${r.length===1?"":"s"})`}const c=[...new Set(i.map(o).filter(f=>!!f))];return i.every(f=>f.legacyReadOnly===!0)?`${s} bounded, redacted legacy non-Research result row${s===1?"":"s"} retained as read-only evidence; not a current egress authority`:e.requestedMode==="research"&&i.every(f=>f.purpose==="research_narration"||f.purpose==="research_tool")?`${s} bounded, redacted Research result row${s===1?"":"s"} sent with explicit run consent${c.length?` during ${c.join(", ")}`:""}`:`${s} bounded, redacted Ask result row${s===1?"":"s"} sent during ${c.join(", ")||"an unrecorded provider phase"}`}function Ao(e){var o,a;const t=(o=e.traceReference)==null?void 0:o.traceId,r=(a=e.traceReference)==null?void 0:a.recordingStatus,[i,s]=h.useState(()=>t?{state:"loading"}:{state:"legacy"});return h.useEffect(()=>{let c=!0;return t?r==="unavailable"||r==="detail_expired"?(s({state:"unavailable"}),()=>{c=!1}):(s({state:"loading"}),se.getAskTraceByRun(e.id).then(u=>{c&&s(u.envelope.runId===e.id?{state:"loaded",trace:u}:{state:"unavailable"})}).catch(()=>{c&&s({state:"unavailable"})}),()=>{c=!1}):(s({state:"legacy"}),()=>{c=!1})},[e.id,t,r]),i.state==="loaded"&&i.trace.envelope.runId!==e.id?{state:"loading"}:i}function Ir(e){return e.outcome==="skipped"?`Skipped${e.skipReason?` (${e.skipReason.replace(/_/g," ")})`:""}`:e.outcome==="success"?e.mode==="verified_facts"?`Fact-verified (${e.factCount} facts)`:"Preview-grounded":e.outcome==="deterministic_fallback"?`Deterministic fallback${e.validationFailures.length>0?` (${e.validationFailures.join(", ")})`:""}`:"Narration unavailable; the retained answer was not replaced."}function Co({run:e,contract:t,dqlArtifact:r,sql:i,lineage:s,t:o,onInsertSql:a,onInsertDql:c,onSaveBlock:u}){var De,ye,qe,xe,ze,Je,$e,He,Ft,_e,xt;const{dispatch:p}=ln(),f=t.plan,l=t.frame,d=t.graph,m=t.receipt,g=t.semantic,b=S(g==null?void 0:g.failure),y=tn(e.diagnosticReceiptV8??t.runtimeReceiptV8),_=((De=y==null?void 0:y.receipt.terminalOutcome)==null?void 0:De.kind)==="finish_answer"?void 0:t.failure??b,z=((ye=e.diagnosticReceiptV4)==null?void 0:ye.summary)??t.decisionSummary,N=((qe=e.diagnosticReceiptV5)==null?void 0:qe.summary)??t.runtimeDecisionSummary,q=z==null?void 0:z.researchBranchSummary,E=(q==null?void 0:q.partialSuccess)===!0?q:void 0,V=S(g==null?void 0:g.authoringRequest),U=S(g==null?void 0:g.runtimeRequest),T=Ce(g==null?void 0:g.bindings),ie=Ce(g==null?void 0:g.steps),F=S(g==null?void 0:g.targetBinding),B=S(F==null?void 0:F.semanticSnapshot),K=S(F==null?void 0:F.executionTarget),w=S(K==null?void 0:K.redactedContext),j=S(F==null?void 0:F.compileTarget),D=S(g==null?void 0:g.executionReceipt),Z=Ce(b==null?void 0:b.candidates),Y=S((xe=t.diagnostic)==null?void 0:xe.cascade),Q=Ce((ze=t.diagnostic)==null?void 0:ze.sourceCoverage),W=Ce(Y==null?void 0:Y.attempts),P=S((Je=t.diagnostic)==null?void 0:Je.provider),H=S(l==null?void 0:l.timeContext),ue=S(l==null?void 0:l.comparison),he=S(l==null?void 0:l.ranking),X=Ce(l==null?void 0:l.dimensions),I=Ce(l==null?void 0:l.memberBindings),ce=Ce(H==null?void 0:H.periods),A=Ce(l==null?void 0:l.requestedOutputs),L=Ce(d==null?void 0:d.nodes),ee=Array.from(new Set([...Te(_==null?void 0:_.safeActions),...Te(b==null?void 0:b.safeActions)])),ne=Ce(_==null?void 0:_.failedBindings),ae=S(b==null?void 0:b.sqlExcerpt),$=e.artifacts.map(C=>Ee(re(C))).find(Boolean),oe=Ao(e),Re=oe.state==="loaded"?$n(e,oe.trace):oe.state==="legacy"?$n(e):void 0,Ie=(r==null?void 0:r.name)??e.question,ht=y?[["Objective",y.receipt.objective.replace(/_/g," ")],["Selected tier",y.selectedTier??"No executable tier selected"],["Frozen plan",qn(y)],["Frozen plan fingerprint",y.frozenPlanFingerprint??"Not retained"],["Candidate admissions",`${y.candidateAdmissionCount} initial · ${y.retainedCandidateCount} retained`],["Context expansions",String(y.receipt.expansionCount)],["Tier attempts",zn(y)]]:[["Question type",R((l==null?void 0:l.questionType)??(f==null?void 0:f.questionType))],["Selected route",R((d==null?void 0:d.route)??(f==null?void 0:f.recommendedRoute))],["Metric",Te(l==null?void 0:l.metricConceptIds).join(", ")],["Entity grain",Te(l==null?void 0:l.entityGrainIds).join(", ")],["Dimensions",X.map(C=>`${R(C.dimensionId)} (${R(C.role)})`).join(", ")],["Member filters",I.map(C=>`${R(C.dimensionId)}: ${Array.isArray(C.canonicalValues)?C.canonicalValues.length:0} bound value(s)`).join(", ")],["Time policy",[H==null?void 0:H.timeRole,H==null?void 0:H.grain,H==null?void 0:H.timezone,H==null?void 0:H.completenessPolicy].map(R).filter(Boolean).join(" · ")],["Periods",ce.map(C=>`${R(C.id)}: ${R(C.start)} → ${R(C.end)}`).join(`
|
|
84
|
+
`)],["Comparison",ue?`${R(ue.basePeriodId)} vs ${Te(ue.comparisonPeriodIds).join(", ")} · ${R(ue.alignment)}`:l?"Not requested":"Not available — analytical planning did not complete"],["Ranking",he?`${R(he.direction)} · top ${R(he.limit)} · ${R(he.tiePolicy)}`:l?"Not requested":"Not available — analytical planning did not complete"],["Outputs",A.map(C=>`${R(C.id)} (${R(C.kind)})`).join(", ")],["Semantic metrics",Te(V==null?void 0:V.metrics).join(", ")],["Semantic dimensions",Te(V==null?void 0:V.dimensions).join(", ")],["Review assumption",($e=e.diagnosticReceiptV7)!=null&&$e.inspector.route.reviewRequired&&e.diagnosticReceiptV7.inspector.route.selectedTier==="semantic"?"Sole declared MetricFlow grouping was inferred for the requested dimension; verify before reuse.":"None"]],it=y?[["Trust state",e.trustState],["Snapshot",y.receipt.snapshotId??"Not retained"],["Frozen plan",qn(y)],["Frozen plan fingerprint",y.frozenPlanFingerprint??"Not retained"],["Candidate admissions",`${y.candidateAdmissionCount} initial · ${y.retainedCandidateCount} retained`],["Selected candidates",y.candidateIds.join(", ")||"Not retained"],["Cascade",y.selectedTier??"No executable tier selected"],["Plan frozen",y.receipt.planFrozen?"true":"false"],["Tier attempts",zn(y)],["Connection & execution",xi(y)],["Validated facts",yi(y)],["Source coverage",ko(y)],["Final stop",y.receipt.finalStopReason.replace(/_/g," ")]]:[["Trust state",e.trustState],["Snapshot",R((f==null?void 0:f.snapshotId)??(d==null?void 0:d.snapshotId))],["Plan fingerprint",R((f==null?void 0:f.fingerprint)??(d==null?void 0:d.planFingerprint))],["Graph fingerprint",R(d==null?void 0:d.fingerprint)],["Receipt",R(m==null?void 0:m.receiptId)],["Result fingerprint",R(m==null?void 0:m.resultFingerprint)],["Freshness observed through",R((He=t.freshness)==null?void 0:He.observedThrough)],["Fact set",R((Ft=t.facts)==null?void 0:Ft.fingerprint)],["Semantic adapter",R(g==null?void 0:g.adapter)],["Semantic compile status",R(g==null?void 0:g.status)],["Target proof",R((_e=S(F==null?void 0:F.proof))==null?void 0:_e.status)],["Target binding",R(F==null?void 0:F.bindingFingerprint)],["Compile target",R(j==null?void 0:j.kind)],["Local semantic snapshot",R((B==null?void 0:B.semanticCatalogFingerprint)??(B==null?void 0:B.sourceFingerprint))],["Runtime metric inventory proof",R(j==null?void 0:j.semanticCatalogFingerprint)],["Execution target",[K==null?void 0:K.driver,w==null?void 0:w.account,w==null?void 0:w.database,w==null?void 0:w.schema,w==null?void 0:w.role,w==null?void 0:w.warehouse].map(R).filter(Boolean).join(" · ")],["Semantic receipt",R(D==null?void 0:D.receiptId)],["Warehouse query ID",R(D==null?void 0:D.queryId)],["Executed SQL proof",R(D==null?void 0:D.executedSqlFingerprint)],["Runtime metrics",Te(U==null?void 0:U.metrics).join(", ")],["Runtime dimensions",Te(U==null?void 0:U.dimensions).join(", ")],["Member bindings",T.map(C=>`${R(C.authoringReference)} → ${R(C.runtimeReference)}${Te(C.entityPath).length?` via ${Te(C.entityPath).join(" → ")}`:""} (${R(C.status)})`).join(`
|
|
85
|
+
`)],["Cascade",R(Y==null?void 0:Y.selectedTier)||R(Y==null?void 0:Y.stopReason)],["Plan frozen",R((xt=t.diagnostic)==null?void 0:xt.planFrozen)],["Provider phase/cause",[R(P==null?void 0:P.phase),R(P==null?void 0:P.cause)].filter(Boolean).join(" · ")],["Provider recovery",R(P==null?void 0:P.safeAction)],["Source coverage",Q.map(C=>`${R(C.source)}: ${R(C.status)}`).join(`
|
|
86
|
+
`)]],st=(y==null?void 0:y.tierAttempts)??W,[ot,ke]=h.useState(null),Oe=(C,fe)=>{const me=fe.derivation.trustTransition;return`${C} as immutable derivation ${fe.derivation.derivationId}. Trust: ${me.previous} → ${me.next}${me.requiresReview?" (review required)":""}.`},Et=async()=>{if(!(!(r!=null&&r.source)||!c))try{const C=await se.deriveAnalyticalRepair(e.id,{version:1,action:"edit_dql",dqlSource:r.source});c({sql:i,dqlArtifact:r,result:$,title:Ie,sourceRunId:e.id,question:e.question}),ke(Oe("Opened DQL in Notebook",C))}catch(C){ke(C instanceof Error?C.message:String(C))}},Bt=async()=>{if(!(!i||!a))try{const C=await se.deriveAnalyticalRepair(e.id,{version:1,action:"open_sql_notebook",sqlText:i});a(i,`${Ie} repair`,{question:e.question,sourceRunId:e.id}),ke(Oe("Opened SQL in Notebook",C))}catch(C){ke(C instanceof Error?C.message:String(C))}},Ve=async C=>{try{const fe=await se.deriveAnalyticalRepair(e.id,{version:1,action:C});ke(Oe(C==="retry_same_plan"?"Prepared the same bounded plan for retry":"Refreshed the governed snapshot and prepared the same plan for retry",fe))}catch(fe){ke(fe instanceof Error?fe.message:String(fe))}},Lt=async()=>{try{const C=await se.deriveAnalyticalRepair(e.id,{version:1,action:"request_access"});ke(Oe("Recorded the access/connection repair and opened Database settings",C)),p({type:"SET_SETTINGS_TAB",tab:"database"}),p({type:"SET_MAIN_VIEW",view:"settings"})}catch(C){ke(C instanceof Error?C.message:String(C))}},Nt=()=>{p({type:"SET_SETTINGS_TAB",tab:"project"}),p({type:"SET_MAIN_VIEW",view:"settings"}),ke("Opened Project & dbt settings. Test and apply the intended dbt Cloud Semantic Layer environment to refresh its verified metric inventory.")};return n.jsxs("div",{style:{display:"grid",gap:9},"aria-label":"How it answered",children:[n.jsxs("div",{role:"status",style:{display:"flex",gap:8,alignItems:"flex-start",padding:"10px 12px",borderRadius:8,border:`1px solid ${_?"var(--status-error-border)":"var(--status-success-border)"}`,background:_?"var(--status-error-bg)":"var(--status-success-bg)"},children:[_?n.jsx(Be,{size:13,color:"var(--status-error)",style:{flexShrink:0,marginTop:2}}):n.jsx(Se,{size:13,color:"var(--status-success)",style:{flexShrink:0,marginTop:2}}),n.jsxs("div",{style:{fontSize:12,color:o.textSecondary,lineHeight:1.5,minWidth:0},children:[n.jsx("div",{style:{fontWeight:700,color:_?"var(--status-error)":"var(--status-success)"},children:_?"Execution failed":"Answered successfully"}),_?n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{marginTop:3,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:o.fontMono,fontSize:11},children:typeof _.message=="string"&&_.message.trim()?_.message:"The engine did not report a message. Open the DQL and SQL tabs to inspect what ran."}),n.jsx("div",{style:{marginTop:4,fontSize:10.5,color:o.textMuted},children:[_.code,_.phase?`during ${_.phase}`:""].filter(Boolean).map(R).join(" · ")})]}):n.jsx("div",{style:{marginTop:2},children:typeof(m==null?void 0:m.rowCount)=="number"?`Returned ${m.rowCount} row${m.rowCount===1?"":"s"}.`:"The query ran and returned a result."})]})]}),e.traceReference?n.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>p({type:"OPEN_ASK_TRACE",runId:e.id}),style:{display:"inline-flex",alignItems:"center",justifySelf:"start",gap:5,background:"transparent",border:"none",cursor:"pointer",padding:"1px 0",color:o.accent,fontSize:11.5,fontFamily:o.font,fontWeight:700},title:"Open the local, redacted Ask trace",children:[n.jsx(dn,{size:12})," Open full trace"]}):null,y?n.jsx(mi,{projection:y,t:o}):N?n.jsx(bi,{summary:N,t:o}):z?n.jsx(vi,{summary:z,t:o}):n.jsx(wi,{t:o}),n.jsxs(wt,{index:1,label:"Performance & provider egress",t:o,open:!0,children:[oe.state==="loading"?n.jsx(Ge,{t:o,children:"Loading the local physical trace. Legacy counters are withheld until its recorded attempts are available."}):Re?n.jsx(Ye,{rows:Re,t:o}):oe.state==="unavailable"?n.jsx(Ge,{t:o,children:"Canonical physical performance evidence is unavailable for this trace-backed run."}):n.jsx(Ge,{t:o,children:"Performance details were not recorded for this legacy run."}),oe.state==="unavailable"&&e.traceReference?n.jsx("p",{style:{margin:0,color:o.textMuted,fontSize:10.5,lineHeight:1.45},children:"The local trace detail is unavailable, so physical provider and SQL counters are not shown for this trace-backed run."}):null]}),n.jsx(wt,{index:2,label:"Plan",t:o,open:!_,children:n.jsx(Ye,{rows:ht,t:o})}),n.jsx(wt,{index:3,label:"Trust & evidence",t:o,children:n.jsx(Ye,{rows:it,t:o,mono:!0})}),n.jsx(wt,{index:4,label:"Actual steps",t:o,children:n.jsxs("div",{style:{display:"grid",gap:6},children:[!y&&ie.map((C,fe)=>n.jsxs("div",{style:{fontSize:11.5,color:o.textSecondary},children:[n.jsxs("strong",{style:{color:R(C.status)==="failed"?"var(--status-error)":o.textPrimary},children:[fe+1,". ",R(C.label)]})," ","— ",R(C.status)," · ",R(C.detail)]},`semantic:${R(C.id)||fe}`)),!y&&e.steps.map(C=>n.jsxs("div",{style:{fontSize:11.5,color:o.textSecondary},children:[n.jsxs("strong",{style:{color:o.textPrimary},children:[C.index+1,". ",C.goal]})," — ",C.status,", ",C.attempts," attempt",C.attempts===1?"":"s"]},C.id)),!y&&L.map((C,fe)=>n.jsxs("div",{style:{fontSize:11.5,color:o.textSecondary},children:[n.jsxs("span",{style:{color:o.accent,fontFamily:o.fontMono},children:[fe+1,". ",R(C.kind)]})," ","· ",R(C.id)]},R(C.id)||fe)),st.map((C,fe)=>{var me;return n.jsxs("div",{style:{fontSize:11.5,color:o.textSecondary},children:[n.jsxs("span",{style:{color:o.accent,fontFamily:o.fontMono},children:[fe+1,". ",R(C.tier)]})," ","— ",R(C.outcome)," · ",R(C.reasonCode)||R((me=S(C))==null?void 0:me.reason),C.frozen===!0?" · frozen":""]},`cascade:${R(C.tier)}:${fe}`)}),y&&st.length===0?n.jsx(Ge,{t:o,children:"No authoritative V2 tier attempt was retained."}):null,!y&&ie.length===0&&e.steps.length===0&&L.length===0&&st.length===0?n.jsx(Ge,{t:o,children:"No executable steps were recorded."}):null]})}),n.jsx(wt,{index:5,label:"Failure & repair",t:o,open:!!(_||E),children:_?n.jsxs("div",{style:{display:"grid",gap:9},children:[n.jsx(Ye,{rows:[["Failure ID",R(_.failureId)],["Recoverability",R(_.recoverability)],["Failed bindings",ne.map(C=>`${R(C.qualifiedId??C.role)} (${R(C.reasonCode)})`).join(", ")],["Safe actions",ee.join(", ")],["DQL fingerprint",R(_.dqlFingerprint)],["SQL fingerprint",R(_.sqlFingerprint)],["Semantic failure code",R(b==null?void 0:b.code)],["Failing identifier",R(b==null?void 0:b.identifier)],["Compiled SQL proof",R(b==null?void 0:b.compiledSqlFingerprint)],["Path candidates",Z.map(C=>`${R(C.label)}
|
|
87
|
+
${R(C.runtimeReference)}`).join(`
|
|
88
|
+
`)]],t:o,mono:!0}),R(ae==null?void 0:ae.text)?n.jsxs("div",{children:[n.jsxs("div",{style:{fontSize:10.5,fontWeight:700,color:o.textSecondary,marginBottom:5},children:["Failing SQL context · lines ",R(ae==null?void 0:ae.startLine),"–",R(ae==null?void 0:ae.endLine)]}),n.jsx("pre",{style:zt(o),children:R(ae==null?void 0:ae.text)})]}):null,n.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6},"aria-label":"Safe repair actions",children:[ee.includes("edit_dql")&&c?n.jsxs("button",{type:"button",onClick:()=>void Et(),style:te(o),children:[n.jsx(un,{size:12})," Open DQL to repair"]}):null,ee.includes("open_sql_notebook")&&a?n.jsxs("button",{type:"button",onClick:()=>void Bt(),style:te(o),children:[n.jsx(Pn,{size:12})," Open SQL in Notebook"]}):null,ee.includes("retry_same_plan")?n.jsxs("button",{type:"button",onClick:()=>void Ve("retry_same_plan"),style:te(o),children:[n.jsx(mn,{size:12})," Retry same plan"]}):null,ee.includes("refresh_snapshot")?n.jsxs("button",{type:"button",onClick:()=>void Ve("refresh_snapshot"),style:te(o),children:[n.jsx(mn,{size:12})," Refresh snapshot and prepare retry"]}):null,ee.includes("request_access")||ee.includes("change_authorized_connection")?n.jsxs("button",{type:"button",onClick:()=>void Lt(),style:te(o),children:[n.jsx(Be,{size:12})," Change connection or request access"]}):null,ee.includes("reapply_semantic_runtime")?n.jsxs("button",{type:"button",onClick:Nt,style:te(o),children:[n.jsx(mn,{size:12})," Reapply semantic runtime settings"]}):null]})]}):E?n.jsx(ji,{summary:E,t:o}):n.jsxs("div",{style:{display:"grid",gap:8},children:[n.jsx(Ge,{t:o,children:"No failure was recorded for this run."}),r!=null&&r.sourcePath?null:r!=null&&r.source?n.jsxs("button",{type:"button",onClick:u,style:te(o),children:[n.jsx(Wn,{size:12})," Save as draft block"]}):null]})}),ot?n.jsx("div",{role:"status",style:{fontSize:10.5,color:ot.toLowerCase().includes("created")?"var(--status-success)":"var(--status-error)"},children:ot}):null]})}function mi({projection:e,t}){const r=e.receipt.terminalOutcome,i=(r==null?void 0:r.kind)==="finish_answer",s=[["Objective",e.receipt.objective.replace(/_/g," ")],["Candidate admissions",`${e.candidateAdmissionCount} initial · ${e.retainedCandidateCount} retained`],["Selected tier",e.selectedTier??"No executable tier selected"],["Frozen plan",qn(e)],["Frozen plan fingerprint",e.frozenPlanFingerprint??"Not retained"],["Tier attempts",zn(e)],["Connection & execution",xi(e)],["Validated facts",yi(e)],["Final outcome",r?`${r.kind.replace(/_/g," ")} · ${r.reasonCode.replace(/_/g," ")}`:e.receipt.finalStopReason.replace(/_/g," ")],["Safe next action",r!=null&&r.safeAction?gn(r.safeAction):"None"]];return n.jsxs("section",{"aria-label":"Authoritative Ask decision story",style:{padding:"10px 12px",borderRadius:8,border:`1px solid ${i?"var(--status-success-border)":"var(--status-warning-border)"}`,background:i?"var(--status-success-bg)":"var(--status-warning-bg)"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,color:i?"var(--status-success)":"var(--status-warning)",fontSize:12,fontWeight:750,marginBottom:8},children:[i?n.jsx(Se,{size:13}):n.jsx(Be,{size:13}),"Authoritative Ask decision story"]}),n.jsx(Ye,{rows:s,t,mono:!0})]})}function bi({summary:e,t}){const r=/did not complete|paused/i.test(e.whatHappened),i=[["What happened",e.whatHappened],["Why",e.why],["Impact on answer",e.impact],["How to proceed",gn(e.nextAction)],["Program",`${e.programTaskCount} task${e.programTaskCount===1?"":"s"} · ${e.admittedCandidateCount} admitted candidates · ${e.toolCallCount} tool calls · ${e.executionAttempts} execution attempt${e.executionAttempts===1?"":"s"}${e.selectedCompiler?` · ${e.selectedCompiler.replace(/_/g," ")}`:""}.`],["Runtime receipt",e.summaryFingerprint]];return n.jsxs("section",{"aria-label":"Ask runtime story",style:{padding:"10px 12px",borderRadius:8,border:`1px solid ${r?"var(--status-error-border)":"var(--status-success-border)"}`,background:r?"var(--status-error-bg)":"var(--status-success-bg)"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,color:r?"var(--status-error)":"var(--status-success)",fontSize:12,fontWeight:750,marginBottom:8},children:[r?n.jsx(Be,{size:13}):n.jsx(Se,{size:13}),"Ask runtime story"]}),n.jsx(Ye,{rows:i,t,mono:!0})]})}function vi({summary:e,t}){const r=e.understoodRequest,i=e.researchBranchSummary,s=(i==null?void 0:i.partialSuccess)===!0,o=[["Understood request",`${r.measures} measure${r.measures===1?"":"s"}, ${r.dimensions} dimension${r.dimensions===1?"":"s"}${r.entityRequested?", an entity output":""}${r.ranking?`, ${r.ranking.direction} ${r.ranking.limit}${r.ranking.defaultedLimit?" (default)":""}`:""}. Conversation binding: ${r.conversationBinding.replace(/_/g," ")}.`],["Evidence by role",e.evidenceByRole.length>0?e.evidenceByRole.map(c=>`${c.role.replace(/_/g," ")}: ${c.candidateCount}`).join(" · "):"No role evidence was retained for this legacy-compatible run."],["Tier decisions",e.tierDecisions.length>0?e.tierDecisions.map(c=>`${c.tier}: ${c.outcome}${c.planFrozen?" (frozen)":""}`).join(" · "):"No cascade tier receipt was recorded."],["Selected plan",e.selectedPlan?`${e.selectedPlan.tier.replace(/_/g," ")}${e.selectedPlan.planFrozen?" frozen":""}${e.selectedPlan.reviewRequired?"; review required":""}.`:"No executable plan was selected."],...i?[["Research branch evidence",Si(i)]]:[],["Failure or repair",e.terminalIncident?`${e.terminalIncident.code.replace(/_/g," ")} at ${e.terminalIncident.boundary}; ${e.terminalIncident.impact.replace(/_/g," ")}.`:s?`Research limitations: ${i.failedBranches+i.timedOutBranches+i.skippedBranches} child branches did not complete; completed receipt-backed findings remain available.`:"No terminal incident was recorded."],["Safe next action",gn(e.safeNextAction)],["Summary fingerprint",e.summaryFingerprint]],a=!!(e.terminalIncident||s);return n.jsxs("section",{"aria-label":"Ask decision story",style:{padding:"10px 12px",borderRadius:8,border:`1px solid ${a?"var(--status-error-border)":"var(--status-success-border)"}`,background:a?"var(--status-error-bg)":"var(--status-success-bg)"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,color:a?"var(--status-error)":"var(--status-success)",fontSize:12,fontWeight:750,marginBottom:8},children:[a?n.jsx(Be,{size:13}):n.jsx(Se,{size:13}),"Ask decision story"]}),n.jsx(Ye,{rows:o,t,mono:!0})]})}function ji({summary:e,t}){const r=e.failedBranches+e.timedOutBranches+e.skippedBranches;return n.jsx("div",{"aria-label":"Research branch limitations",style:{display:"grid",gap:8},children:n.jsx(Ye,{rows:[["Root outcome","The root Research answer remains successful; these child limitations are not a terminal incident."],["Research branch evidence",Si(e)],["Limitations",`${r} child ${r===1?"branch did":"branches did"} not complete. Receipt-backed findings remain available.`],["Safe next action",gn(e.safeAction)]],t})})}function gn(e){return e==="inspect_research_failures"?"Inspect failed or timed-out branches; retry narrower Research if the missing evidence matters.":e.replace(/_/g," ")}function Si(e){const t=e.failureReasons.length>0?e.failureReasons.map(i=>`${i.code.replace(/_/g," ")}: ${i.branchCount}`).join(" · "):"no displayable reason code",r=e.availableChildPlans.length>0?` Persisted child plans: ${e.availableChildPlans.map(i=>`${i.tier.replace(/_/g," ")} frozen ×${i.frozenPlanCount} for ${i.branchCount} ${i.branchCount===1?"branch":"branches"}${i.reviewRequired?" (review required)":""}`).join(" · ")}.`:" No frozen child plan evidence was retained.";return`${e.receiptBackedBranches} receipt-backed ${e.receiptBackedBranches===1?"finding":"findings"} · ${e.failedBranches} failed · ${e.timedOutBranches} timed out · ${e.skippedBranches} skipped. Reasons: ${t}.${r} ${e.linkedChildRunCount} linked child ${e.linkedChildRunCount===1?"run":"runs"}.`}function wi({t:e}){return n.jsxs("section",{"aria-label":"Ask decision story unavailable",style:{padding:"10px 12px",borderRadius:8,border:"1px solid var(--status-warning-border)",background:"var(--status-warning-bg)",color:e.textSecondary,fontSize:12,lineHeight:1.45},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,color:"var(--status-warning)",fontSize:12,fontWeight:750,marginBottom:4},children:[n.jsx(Be,{size:13})," Ask decision story"]}),n.jsxs("div",{children:[Ur,"."]}),n.jsx("div",{style:{marginTop:3,color:e.textMuted,fontSize:11.5},children:"Open the full trace to inspect its raw advanced evidence."})]})}function wt({index:e,label:t,t:r,open:i=!1,children:s}){return n.jsxs("details",{open:i,style:{border:"1px solid var(--border-subtle)",borderRadius:8,background:"var(--bg-1)",overflow:"hidden"},children:[n.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:[n.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}),t]}),n.jsx("div",{style:{display:"grid",gap:8,padding:"0 10px 10px"},children:s})]})}function Ye({rows:e,t,mono:r=!1}){return n.jsx("div",{style:{display:"grid",gap:6},children:e.filter(([,i])=>i).map(([i,s])=>n.jsxs("div",{style:{display:"grid",gridTemplateColumns:"112px minmax(0, 1fr)",gap:8,alignItems:"start"},children:[n.jsx("span",{style:{fontSize:10.5,color:t.textMuted},children:i}),n.jsx("span",{style:{fontSize:10.5,color:t.textSecondary,fontFamily:r?t.fontMono:t.font,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:s})]},i))})}function Ge({t:e,children:t}){return n.jsx("div",{style:{fontSize:11,color:e.textMuted},children:t})}function Ce(e){return Array.isArray(e)?e.flatMap(t=>S(t)?[S(t)]:[]):[]}function Te(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function R(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function Qe(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 Xt(e,t){var i;const r=t==null?void 0:t.trim();return{question:((i=e.question)==null?void 0:i.trim())||r||e.label,selectedEvidenceId:e.id}}function ki(e){var i;const t=e.artifacts.map(s=>Ee(re(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:Le(e),dqlArtifact:Fe(e),...t?{result:{columns:t.columns,rows:t.rows.slice(0,24),rowCount:t.rowCount}}:{}}}function Tt(e){return!e.artifacts.some(r=>!!hn(re(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")||!!(Fe(e)??Le(e)))}function Ro({run:e,artifact:t,tab:r,t:i,appContext:s,onOpenApp:o,onChangeTab:a,onClose:c,onSaveBlock:u,onInsertSql:p,onInsertDql:f}){var K;const l=re(t),d=Fe(e)??Mt(l),m=Le(e)??(typeof l.sql=="string"?l.sql:void 0),g=Ee(l),b=Rt(e,t),y=Yn(e),x=ui(e),_=Gn(e),z=t.trustState==="certified",N=e.status==="cancelled"||e.stopReason==="cancelled"||e.route==="cancelled",q=!N&&(e.status==="blocked"||t.trustState==="blocked"),E=Tt(e),V=hi(l)??(((K=e.diagnosticReceiptV8)==null?void 0:K.mode)==="authoritative_v2"?{}:void 0),U=li({analytical:!!V,blocked:q,hasDql:!!(d!=null&&d.source),hasSql:!!m,hasLineage:x.length>0}),T=U.some(w=>w.id===r)?r:U[0].id,ie=N?"Cancelled":q?"Blocked":z?"Certified":t.trustState==="governed"||t.trustState==="grounded"?"Governed":"AI-generated",F=N?"var(--text-tertiary)":q?"var(--status-error)":z?"var(--status-success)":t.trustState==="governed"||t.trustState==="grounded"?"var(--accent)":"var(--status-warning)",B=N?"var(--bg-3)":q?"var(--status-error-bg)":z?"var(--status-success-bg)":t.trustState==="governed"||t.trustState==="grounded"?"var(--accent-dim)":"var(--status-warning-bg)";return n.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:[n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:10,padding:"14px 16px 12px",borderBottom:"1px solid var(--border-subtle)"},children:[n.jsx("span",{style:{width:32,height:32,borderRadius:8,background:B,color:F,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border-subtle)"},children:n.jsx(gt,{kind:t.kind})}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{fontSize:13,fontWeight:650,color:i.textPrimary,lineHeight:1.35},children:Rt(e,t)}),n.jsx("div",{style:{fontSize:11,color:i.textMuted,marginTop:2},children:pn(t,l)})]}),n.jsx("span",{style:{border:`1px solid ${F}`,color:F,background:B,borderRadius:999,padding:"2px 8px",fontSize:10,fontWeight:700,flexShrink:0,marginTop:2},children:ie}),n.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:n.jsx(Zt,{size:14})})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"10px 16px",borderBottom:"1px solid var(--border-subtle)"},children:[E?n.jsx(Un,{run:e,t:i,appContext:s,onOpenApp:o}):null,E?n.jsxs("button",{type:"button",className:"dql-hover",onClick:u,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:[n.jsx($t,{size:13})," Save as block"]}):null,n.jsx("div",{style:{flex:1}}),n.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:n.jsx(rs,{size:14})})]}),n.jsx("div",{style:{display:"flex",alignItems:"center",gap:16,padding:"0 16px",borderBottom:"1px solid var(--border-subtle)",flexShrink:0},children:U.map(w=>n.jsx("button",{type:"button",onClick:()=>a(w.id),style:{padding:"10px 1px",fontSize:12,fontWeight:600,cursor:"pointer",border:"none",background:"none",fontFamily:i.font,whiteSpace:"nowrap",color:T===w.id?i.textPrimary:i.textMuted,boxShadow:T===w.id?`inset 0 -2px 0 0 ${i.accent}`:"none"},children:w.label},w.id))}),n.jsxs("div",{style:{flex:1,minHeight:0,overflow:"auto",padding:"14px 16px 20px"},children:[T==="how"&&V?n.jsx(Co,{run:e,contract:V,dqlArtifact:d,sql:m,lineage:x,t:i,onInsertSql:p,onInsertDql:f,onSaveBlock:u}):null,T==="dql"?d!=null&&d.source?n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[n.jsx("span",{style:{fontSize:11,color:i.textMuted},children:"Reusable governed artifact — save it as a block to certify."}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[f?n.jsx("button",{type:"button",onClick:()=>f({sql:m,dqlArtifact:d,result:g,chartConfig:g?Xe(l,g):void 0,title:b,sourceRunId:e.id,question:e.question}),style:te(i),children:"Open DQL in notebook"}):null,n.jsx(nn,{text:d.source,t:i,title:"Copy DQL"})]})]}),n.jsx("pre",{style:zt(i),children:d.source})]}):n.jsx(Ge,{t:i,children:"The selected plan failed before a DQL source could be materialized. Review the Plan and Failure & repair sections."}):null,T==="sql"?m?n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[n.jsx("span",{style:{fontSize:11,color:i.textMuted},children:"Attempted compiled SQL — open it in Notebook to inspect or repair."}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[p?n.jsx("button",{type:"button",onClick:()=>p(m,b,{question:e.question,sourceRunId:e.id}),style:te(i),children:"Open SQL in notebook"}):null,n.jsx(nn,{text:m,t:i,title:"Copy SQL"})]})]}),n.jsx("pre",{style:zt(i),children:m})]}):n.jsx(Ge,{t:i,children:"Compilation stopped before SQL was produced. The DQL, plan, trust evidence, and failure steps are still retained."}):null,T==="lineage"?n.jsxs("div",{style:{display:"grid",gap:8},children:[n.jsx("div",{style:{fontSize:11,color:i.textMuted,lineHeight:1.5},children:"Governed semantic objects and physical sources used to produce this result."}),x.map(w=>n.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:[n.jsx(dn,{size:13,color:i.accent,style:{flexShrink:0,marginTop:2}}),n.jsxs("div",{style:{minWidth:0},children:[n.jsx("div",{style:{fontSize:12,fontWeight:650,color:i.textPrimary},children:w.name}),n.jsx("div",{style:{fontSize:10.5,color:i.textMuted,marginTop:2},children:[w.kind,w.detail].filter(Boolean).join(" · ")})]})]},`${w.kind??"asset"}:${w.name}`))]}):null,T==="trust"?n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[_?n.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-start",padding:"10px 12px",borderRadius:8,background:z?"var(--status-success-bg)":"var(--status-warning-bg)",border:`1px solid ${z?"var(--status-success-border)":"var(--status-warning-border)"}`},children:[z?n.jsx(Se,{size:13,color:"var(--status-success)",style:{flexShrink:0,marginTop:1}}):n.jsx(Be,{size:13,color:"var(--status-warning)",style:{flexShrink:0,marginTop:1}}),n.jsx("span",{style:{fontSize:12,color:i.textSecondary,lineHeight:1.5},children:_})]}):null,y.length>0?n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:11,fontWeight:700,color:i.textMuted,textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:8},children:"Evidence"}),n.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:y.map(w=>n.jsxs("span",{style:Ei(i,w.certified),children:[w.certified?n.jsx(Se,{size:11}):n.jsx(rt,{size:11}),n.jsx("span",{children:w.label})]},w.label))})]}):null,e.evaluations.length>0?n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:11,fontWeight:700,color:i.textMuted,textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:8},children:"Verification checks"}),n.jsx(_i,{evaluations:e.evaluations,t:i})]}):null,e.steps.length>0?n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:11,fontWeight:700,color:i.textMuted,textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:8},children:"Steps"}),n.jsx(qi,{steps:e.steps,t:i})]}):null,n.jsx(Mi,{run:e,t:i})]}):null]})]})}function Io({t:e,text:t,source:r,left:i,top:s,draft:o,inputRef:a,onDraftChange:c,onClose:u,onSend:p}){const f=(l,d)=>n.jsx("button",{type:"button",onClick:()=>p(d),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 n.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:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[n.jsx(tt,{size:12,color:e.accent}),n.jsx("span",{style:{fontSize:11,fontWeight:700,color:e.textSecondary},children:"Follow up on this"}),n.jsx("span",{style:{fontSize:10,color:e.textMuted},children:r==="table"?"from the result":"from the answer"}),n.jsx("div",{style:{flex:1}}),n.jsx("button",{type:"button",onClick:u,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:n.jsx(Zt,{size:12})})]}),n.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:["“",t,"”"]}),n.jsxs("div",{style:{display:"flex",gap:6},children:[n.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"}}),n.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:n.jsx(Fr,{size:13})})]}),n.jsxs("div",{style:{display:"flex",gap:5,flexWrap:"wrap"},children:[f("Why is this?","Why is this happening?"),f("Root cause","What is the root cause?"),f("Break it down","Break this down further")]})]})}function kt(e){const t=e.replace(/^\/\w+\s+/,"").trim().replace(/[?.!]+$/,"");return(t?t.charAt(0).toUpperCase()+t.slice(1):"New app").slice(0,60)}function Mn(e,t){const r=e instanceof Error?e.message.trim():"";return e instanceof ts&&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||t}function En(e,t){return t!=null&&t.trim()?`${e} › ${t.trim()}`:e}function Ai(e,t){const r=t.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,u;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:(u=s.dashboards.find(p=>p.id===o))==null?void 0:u.title}})]}function Un({run:e,t,appContext:r,onOpenApp:i}){const[s,o]=h.useState(!1),[a,c]=h.useState(null),[u,p]=h.useState(!1),[f,l]=h.useState("list"),[d,m]=h.useState(""),[g,b]=h.useState(!1),[y,x]=h.useState(null),[_,z]=h.useState(""),[N,q]=h.useState(null),E=h.useRef(null),V=async()=>{c(null),p(!1);const[w,j]=await Promise.allSettled([se.listAppsStrict(),se.listAppBuilds()]);if(w.status==="rejected"&&j.status==="rejected"){c([]),p(!0);return}const D=Ai(w.status==="fulfilled"?w.value:[],j.status==="fulfilled"?j.value.drafts:[]);c(D),D.length===0&&l("new")},U=()=>{o(!0),x(null),l("list"),E.current=null,m(kt(e.question)),z(kt(e.question)),V()},T=()=>{g||(o(!1),x(null))},ie=async(w,j,D,Z)=>{var H,ue;const Y=_.trim()||kt(e.question),Q=Fe(e),W=An(e),P=await se.addAskResultToAppBuild(w.id,{expectedRevision:w.revision,expectedProposalHash:w.proposalHash,pageId:D,title:Y,question:e.question,answer:Ke(e)??e.summary,certifiedBlockId:W,dqlSource:Q==null?void 0:Q.source,sql:Le(e),visualization:(H=Po(e))==null?void 0:H.chart});q({appId:P.draft.appId,draftId:P.draft.id,pageId:P.pageId,name:j,pageTitle:((ue=P.draft.pages.find(he=>he.id===P.pageId))==null?void 0:ue.metadata.title)??Z,tileTitle:Y,kind:P.deduped?"existing":W?"certified":Q!=null&&Q.source||Le(e)?"review":"narrative"}),window.dispatchEvent(new CustomEvent("dql-app-build-updated",{detail:{draft:P.draft,pageId:P.pageId,tileId:P.tileId}})),o(!1)},F=async w=>{if(w.draft)return w.draft;const D=(await se.listAppBuilds()).drafts.find(Z=>{var Y;return Z.state!=="project_published"&&((Y=Z.baseApp)==null?void 0:Y.appId)===w.appId});return D||(await se.createAppBuild({baseAppId:w.appId,goal:`Edit ${w.name} with an Ask result`,authoringMode:"ai",sourcePolicy:An(e)?"governed_only":"include_review_required",template:"blank",entrypoint:"ask"})).draft},B=async w=>{if(!g){b(!0),x(null);try{const j=await F(w),D=(r==null?void 0:r.appId)===w.appId?r.dashboardId:w.pageId;await ie(j,w.name,D,w.pageTitle)}catch(j){x(Mn(j,"Could not add to app."))}finally{b(!1)}}},K=async()=>{var j,D;if(g)return;const w=d.trim()||kt(e.question);b(!0),x(null);try{E.current||(E.current=(await se.createAppBuild({name:w,goal:e.question,authoringMode:"ai",sourcePolicy:An(e)?"governed_only":"include_review_required",template:"blank",entrypoint:"ask"})).draft),await ie(E.current,w,(j=E.current.pages[0])==null?void 0:j.id,(D=E.current.pages[0])==null?void 0:D.metadata.title),E.current=null}catch(Z){x(Mn(Z,"Could not create the app."))}finally{b(!1)}};return n.jsxs("div",{style:{position:"relative",display:"inline-flex",alignItems:"center",gap:6},children:[N?n.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:`${t.success}12`,color:t.success,border:`1px solid ${t.success}55`},children:[n.jsx("span",{style:{width:26,height:26,borderRadius:999,display:"grid",placeItems:"center",background:`${t.success}20`},children:n.jsx(_t,{size:15})}),n.jsxs("span",{style:{display:"grid",gap:1,minWidth:0},children:[n.jsx("b",{style:{fontSize:11.5},children:N.kind==="existing"?"Already on this page":N.kind==="certified"?"Saved as a certified tile":N.kind==="review"?"Saved — review required":"Saved as editable narrative"}),n.jsxs("span",{title:En(N.name,N.pageTitle),style:{fontSize:10.5,color:t.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[En(N.name,N.pageTitle)," · editable draft"]}),n.jsxs("span",{title:N.tileTitle,style:{fontSize:10,color:t.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["Tile: ",N.tileTitle]}),N.kind==="review"||N.kind==="narrative"?n.jsx("span",{style:{fontSize:10,color:t.textMuted,lineHeight:1.35},children:"Stays local and cannot publish until reviewed, promoted, or removed."}):null]}),i?n.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>i(N.appId,N.pageId,N.draftId),style:{...te(t),color:t.success,whiteSpace:"nowrap"},title:"Open the App page containing this tile",children:["Open App ",n.jsx(ps,{size:12})]}):null]}):null,n.jsxs("button",{type:"button",className:"dql-hover dql-lift",onClick:U,style:N?te(t):$r(t),children:[n.jsx(Cn,{size:13}),N?"Add to another":"Add to app"]}),s?n.jsxs(n.Fragment,{children:[n.jsx("div",{onClick:T,style:{position:"fixed",inset:0,zIndex:40}}),n.jsxs("div",{style:Go(t),children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[n.jsx("span",{style:{fontSize:12,fontWeight:700,color:t.textPrimary},children:f==="new"?"Name the new App draft":"Save to an editable App"}),n.jsx("button",{type:"button",onClick:T,style:{border:"none",background:"transparent",color:t.textMuted,cursor:"pointer",fontSize:15,lineHeight:1},children:"×"})]}),y?n.jsx("div",{style:{fontSize:11,color:t.error,marginBottom:7,lineHeight:1.4},children:y}):null,f==="new"?n.jsxs("div",{style:{display:"grid",gap:8},children:[n.jsx("input",{autoFocus:!0,value:d,onChange:w=>m(w.target.value),onKeyDown:w=>{w.key==="Enter"&&K()},placeholder:"App name",style:Mr(t)}),n.jsxs("div",{style:{display:"flex",gap:6},children:[a&&a.length>0?n.jsx("button",{type:"button",className:"dql-hover",onClick:()=>l("list"),style:te(t),children:"Back"}):null,n.jsxs("button",{type:"button",className:"dql-hover",disabled:g||!d.trim(),onClick:()=>void K(),style:{...$r(t),flex:1,justifyContent:"center"},children:[g?n.jsx(et,{size:13,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}}):n.jsx(At,{size:13}),"Create draft & add"]})]})]}):a===null?n.jsx("div",{style:{fontSize:11.5,color:t.textMuted,padding:"8px 2px"},children:"Loading apps…"}):u?n.jsxs("div",{style:{display:"grid",gap:8},children:[n.jsx("div",{style:{fontSize:11.5,color:t.error,lineHeight:1.4},children:"Couldn't load your apps."}),n.jsxs("div",{style:{display:"flex",gap:6},children:[n.jsx("button",{type:"button",className:"dql-hover",onClick:()=>void V(),style:te(t),children:"Retry"}),n.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>l("new"),style:{...Tr(t),width:"auto",flex:1,marginBottom:0,justifyContent:"center"},children:[n.jsx(At,{size:13})," New app…"]})]})]}):n.jsxs("div",{style:{display:"grid",gap:3,maxHeight:244,overflow:"auto"},children:[n.jsxs("label",{style:{display:"grid",gap:3,marginBottom:5},children:[n.jsx("span",{style:{fontSize:10.5,color:t.textMuted},children:"Tile name"}),n.jsx("input",{value:_,onChange:w=>z(w.target.value),placeholder:kt(e.question),maxLength:120,style:Mr(t)})]}),n.jsxs("button",{type:"button",className:"dql-hover",onClick:()=>l("new"),style:Tr(t),children:[n.jsx(At,{size:13})," New app…"]}),a.map(w=>n.jsxs("button",{type:"button",className:"dql-hover",disabled:g,onClick:()=>void B(w),style:Ko(t),children:[n.jsx(Cn,{size:13,style:{flex:"0 0 auto",opacity:.7}}),n.jsxs("span",{style:{flex:1,minWidth:0,display:"grid",gap:1,overflow:"hidden",textAlign:"left"},children:[n.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:w.name}),n.jsx("small",{style:{color:t.textMuted},children:w.kind==="draft"?"Local editable draft":"Project App · creates a safe edit draft"})]})]},w.id))]})]})]}):null]})}function Gn(e){var t,r;if(e.status==="cancelled"||e.stopReason==="cancelled"||e.route==="cancelled")return"Stopped by user. No result was accepted.";if((t=e.diagnosticReceiptV7)!=null&&t.inspector.route.reviewRequired&&e.diagnosticReceiptV7.inspector.route.selectedTier==="semantic")return"Review required: DQL used the sole declared MetricFlow grouping for the requested dimension. Verify this inferred business mapping before reuse.";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(Kn(e)){const i=e.artifacts.map(a=>a.payload).filter(a=>!!(a&&typeof a=="object"&&!Array.isArray(a)));if(i.some(a=>{const c=a.result;return!!(c&&typeof c=="object"&&!Array.isArray(c))}))return"Exploratory · DBT-grounded. The query and bounded join probes ran, but no certified relationship path covers it yet.";const o=(r=i.find(a=>typeof a.executionError=="string"))==null?void 0:r.executionError;return typeof o=="string"&&o.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 Kn(e){return e.artifacts.some(t=>{const r=t.payload;return!!(r&&typeof r=="object"&&!Array.isArray(r)&&r.exploratoryCandidate)})}function _o(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":Kn(e)?"Exploratory DBT-grounded answer":e.route==="semantic_answer"?"Semantic answer":e.route==="generated_answer"?"AI-generated answer":Xr[e.route]}function qo({artifact:e,payload:t,t:r,onOpenApp:i}){const s=typeof t.sessionId=="string"?t.sessionId:void 0,o=t.proposal&&typeof t.proposal=="object"?t.proposal:void 0,a=typeof t.proposalHash=="string"?t.proposalHash:void 0,[c,u]=h.useState(()=>o?ss(o):new Set),[p,f]=h.useState(!1),[l,d]=h.useState(null),[m,g]=h.useState(null);if(!o||!s)return n.jsxs("div",{style:Fn(r),children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsx(gt,{kind:e.kind}),n.jsx("div",{style:{fontSize:12,fontWeight:800,color:r.textPrimary},children:e.title})]}),n.jsx("div",{style:{fontSize:11.5,color:r.textMuted},children:"This proposal is no longer available. Ask again to rebuild it."})]});const b=async y=>{var _,z;f(!0),d(null);const x=await se.commitAppAiBuild(s,{selectedTileIds:Array.from(c),expectedProposalHash:a,...y.appName?{appName:y.appName}:{},...y.pageTitle?{pageTitle:y.pageTitle}:{},...y.audience?{audience:y.audience}:{},...Object.keys(y.tileOverrides).length>0?{tileOverrides:y.tileOverrides}:{}});if(f(!1),!x.ok){d(x.error);return}g({appId:((_=x.app)==null?void 0:_.id)??x.session.appId??"",dashboardId:x.dashboardId??void 0,name:((z=x.app)==null?void 0:z.name)??e.title})};return n.jsxs("div",{style:Fn(r),children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsx(gt,{kind:e.kind}),n.jsx("div",{style:{fontSize:12,fontWeight:800,color:r.textPrimary,flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Me(e.title)})]}),m?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,color:r.success,fontSize:12,fontWeight:750},children:[n.jsx(_t,{size:13})," Created ",m.name]}),m.appId&&i?n.jsx("button",{type:"button",className:"dql-hover",onClick:()=>i(m.appId,m.dashboardId),style:te(r),children:"Open app"}):null]}):n.jsx(os,{proposal:o,t:r,selected:c,onToggle:y=>{u(x=>{const _=new Set(x);return _.has(y)?_.delete(y):_.add(y),_})},onCreate:y=>void b(y),defaultName:e.title,busy:p,error:l,compact:!0})]})}function Ci({artifact:e,certifiedBlockName:t,initialResult:r,initialChartConfig:i,payload:s,executionTarget:o,t:a,themeMode:c,embedded:u=!1,expanded:p=!1}){var X;const[f,l]=h.useState(e),[d,m]=h.useState(()=>e.parameters??[]),[g,b]=h.useState(()=>({...e.parameterValues??{},...Bn(s)})),[y,x]=h.useState(r),[_,z]=h.useState(i),[N,q]=h.useState(!!t),[E,V]=h.useState(!1),[U,T]=h.useState(null),[ie,F]=h.useState(!1),[B,K]=h.useState(""),[w,j]=h.useState(""),D=h.useRef(!1),Z=h.useRef(e);Z.current=e;const Y=eo(e);h.useEffect(()=>{const I=Z.current;if(l(I),F(!1),!t){m(I.parameters??[]),b({...I.parameterValues??{},...Bn(s)}),q(!1);return}let ce=!1;return q(!0),se.getCertifiedBlockParameters(t).then(A=>{ce||(m(A.parameters),b(L=>({...Object.fromEntries(A.parameters.flatMap(ee=>ee.default===void 0?[]:[[ee.name,ee.default]])),...L})))}).catch(A=>{ce||T(A instanceof Error?A.message:String(A))}).finally(()=>{ce||q(!1)}),()=>{ce=!0}},[Y,t]);const Q=async()=>{if(!D.current){D.current=!0,V(!0),T(null);try{const I=await se.invokeDqlArtifact(f,g,void 0,t,o);x(I.result),l(I.artifact),I.result.chartConfig&&typeof I.result.chartConfig=="object"&&z(I.result.chartConfig),I.parameters.length>0&&m(I.parameters)}catch(I){T(I instanceof Error?I.message:String(I))}finally{D.current=!1,V(!1)}}},W=h.useMemo(()=>Qr(f,y),[f,y]),P=()=>{const I=W[0];I&&(K(I.column),j(I.values[0]==null?"":String(I.values[0])),F(!0),T(null))},H=async()=>{try{const I=f.kind==="sql_block"?await se.addDqlArtifactResultFilter(f,y.columns,B,w,o):to(f,y,B,w);l(I.artifact),m(I.artifact.parameters??[]),b(ce=>({...ce,...I.artifact.parameterValues??{}})),F(!1),T(null)}catch(I){T(I instanceof Error?I.message:String(I))}},ue=d.some(Or),he=Object.entries(g).filter(([,I])=>I!=null&&I!=="");return n.jsxs("div",{style:{display:"grid",gap:9},children:[he.length>0?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap",padding:u?"8px 12px 0":0},children:[n.jsx("span",{style:{fontSize:10.5,fontWeight:750,color:a.textMuted},children:"Applied inputs"}),he.map(([I,ce])=>n.jsxs("span",{style:{fontSize:10.5,color:a.textSecondary,border:`1px solid ${a.cellBorder}`,background:a.appBg,borderRadius:999,padding:"2px 7px"},children:[I.replace(/_/g," ")," = ",zo(ce)]},I))]}):null,N?n.jsx("div",{style:{fontSize:10.5,color:a.textMuted},children:"Loading reusable inputs…"}):ue||W.length>0?n.jsxs("div",{style:{display:"grid",gap:8,padding:9,margin:u?"0 12px":0,border:`1px solid ${a.cellBorder}`,borderRadius:7,background:a.appBg},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{fontSize:11,fontWeight:800,color:a.textPrimary},children:"Change DQL inputs"}),n.jsx("div",{style:{fontSize:10,color:a.textMuted},children:"Reruns this DQL artifact directly. It does not start another AI search."})]}),W.length>0?n.jsxs("button",{type:"button",onClick:P,style:te(a),children:[n.jsx(At,{size:11})," Add result filter"]}):null,n.jsxs("button",{type:"button",disabled:E,onClick:()=>void Q(),style:{...te(a),color:a.accent,opacity:E?.65:1},children:[E?n.jsx(et,{size:11,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}}):n.jsx(tt,{size:11}),E?"Running…":"Apply"]})]}),ie?n.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:[n.jsxs("label",{style:{display:"grid",gap:4,fontSize:10,fontWeight:750,color:a.textSecondary},children:["Result column",n.jsx("select",{"aria-label":"Result column for new DQL input",value:B,onChange:I=>{const ce=I.target.value,A=W.find(L=>L.column===ce);K(ce),j((A==null?void 0:A.values[0])==null?"":String(A.values[0]))},style:Er(a),children:W.map(I=>n.jsx("option",{value:I.column,children:I.column.split("_").join(" ")},I.column))})]}),n.jsxs("label",{style:{display:"grid",gap:4,fontSize:10,fontWeight:750,color:a.textSecondary},children:["Default value",n.jsx("input",{"aria-label":"Default value for new DQL input",value:w,list:`ask-filter-${B}`,onChange:I=>j(I.target.value),style:Er(a)}),n.jsx("datalist",{id:`ask-filter-${B}`,children:(((X=W.find(I=>I.column===B))==null?void 0:X.values)??[]).map(I=>n.jsx("option",{value:String(I)},`${typeof I}:${String(I)}`))})]}),n.jsx("button",{type:"button",onClick:()=>{H()},style:{...te(a),color:a.accent},children:"Add input"}),n.jsx("button",{type:"button",onClick:()=>F(!1),style:te(a),children:"Cancel"})]}):null,d.length>0?n.jsx(Fs,{parameters:d,values:g,onChange:(I,ce)=>b(A=>({...A,[I]:ce})),t:a}):null,W.length>0?n.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,U?n.jsx("div",{style:{fontSize:10.5,color:a.error},children:U}):null,n.jsx(Dn,{result:y,themeMode:c,t:a,chartConfig:_,embedded:u,tabLabels:u?{table:"Results",chart:"Visualization"}:void 0,contentMaxHeight:p?"calc(100vh - 172px)":void 0,tableMaxHeight:p?"calc(100vh - 250px)":void 0})]})}function Bn(e){const t=e.result&&typeof e.result=="object"&&!Array.isArray(e.result)?e.result:void 0,r=Array.isArray(t==null?void 0:t.parameters)?t.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 zo(e){return Array.isArray(e)?e.map(t=>String(t)).join(", "):typeof e=="boolean"?e?"true":"false":String(e)}function Ri(e,t){const r=t.result&&typeof t.result=="object"&&!Array.isArray(t.result)?t.result:void 0,i=t.block&&typeof t.block=="object"&&!Array.isArray(t.block)?t.block:void 0;return[r==null?void 0:r.blockName,t.sourceCertifiedBlock,i==null?void 0:i.name,e.ref].find(o=>typeof o=="string"&&o.trim().length>0)}function Ii({artifact:e,t,themeMode:r,onInsertSql:i,onInsertDql:s,insertDqlActionLabel:o,sourceRunId:a,sourceQuestion:c,onOpenBlock:u,onOpenResearch:p,onOpenApp:f,onNextAction:l}){const d=e.payload&&typeof e.payload=="object"?e.payload:{};if(e.kind==="app_proposal")return n.jsx(qo,{artifact:e,payload:d,t,onOpenApp:f});const m=Ee(d),g=Mt(d),b=hn(d),y=typeof d.sql=="string"?d.sql:typeof d.sqlPreview=="string"?d.sqlPreview:typeof d.proposedSql=="string"?d.proposedSql:void 0,x=typeof d.name=="string"?d.name:e.title,_=typeof d.path=="string"?d.path:e.ref,z=d.draftBlock&&typeof d.draftBlock=="object"&&!Array.isArray(d.draftBlock)?d.draftBlock:void 0,N=typeof(z==null?void 0:z.path)=="string"?z.path:void 0,q=typeof(z==null?void 0:z.name)=="string"?z.name:void 0,E=(g==null?void 0:g.sourcePath)??N??(e.kind==="dql_block_draft"?_:void 0),V=(g==null?void 0:g.name)??q??x,U=(g==null?void 0:g.kind)==="sql_block"||e.kind==="dql_block_draft"?"Open DQL draft":"Open DQL artifact",T=d.plan&&typeof d.plan=="object"?d.plan:void 0,ie=Array.isArray(T==null?void 0:T.steps)?T.steps:[],F=Array.isArray(T==null?void 0:T.gaps)?T.gaps.map(String):[],B=typeof d.researchRunId=="string"?d.researchRunId:e.kind==="research_run"&&typeof e.ref=="string"?e.ref:void 0,K=typeof d.notebookPath=="string"?d.notebookPath:void 0,w=Array.isArray(d.generatedPaths)?d.generatedPaths.filter(W=>typeof W=="string"):[],j=d.narration&&typeof d.narration=="object"?d.narration:void 0,D=Array.isArray(j==null?void 0:j.keyFindings)?j.keyFindings.filter(W=>typeof W=="string"):[],Z=typeof(j==null?void 0:j.recommendation)=="string"?j.recommendation:void 0,Y=e.trustState==="certified"?Ri(e,d):void 0,Q=e.kind==="research_run"?Hn(d):void 0;if(e.kind==="dql_block_draft"){const W=H=>Array.isArray(H)?H.filter(ue=>typeof ue=="string"):void 0,P=d.certifierVerdict&&typeof d.certifierVerdict=="object"?d.certifierVerdict:void 0;return n.jsx(Ls,{t,name:typeof d.name=="string"?d.name:x,status:"draft",description:typeof d.description=="string"?d.description:void 0,dql:(g==null?void 0:g.source)??(typeof d.dqlSource=="string"?d.dqlSource:void 0),sqlPreview:y,grain:typeof d.grain=="string"?d.grain:void 0,outputs:W(d.outputs),dimensions:W(d.dimensions)??(g==null?void 0:g.dimensions),entities:W(d.entities),certifierVerdict:P?{blocking:W(P.blocking)??[],warnings:W(P.warnings)??[],ready:!!P.ready}:void 0,actions:n.jsxs(n.Fragment,{children:[y&&s?n.jsx("button",{type:"button",onClick:()=>s({sql:y,dqlArtifact:g,result:m,chartConfig:m?Xe(d,m):void 0,title:x,sourceRunId:a,question:c}),style:te(t),children:o??"Insert as DQL cell"}):y&&i?n.jsx("button",{type:"button",onClick:()=>i(y,x,{question:c,sourceRunId:a}),style:te(t),children:"Insert SQL preview"}):null,E&&u?n.jsx("button",{type:"button",onClick:()=>u(E,V),style:te(t),children:U}):null]})})}return n.jsxs("div",{style:Fn(t),children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsx(gt,{kind:e.kind}),n.jsx("div",{style:{fontSize:12,fontWeight:800,color:t.textPrimary,flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Me(e.title)})]}),Q?n.jsxs("div",{role:"status","aria-label":Q.detail,style:{borderLeft:`3px solid ${Q.limitedScope?t.warning:t.accent}`,padding:"7px 9px",borderRadius:6,background:Q.limitedScope?`${t.warning}10`:`${t.accent}0d`,display:"grid",gap:2},children:[n.jsx("strong",{style:{fontSize:11.5,color:Q.limitedScope?t.warning:t.textPrimary},children:Q.limitedScope?"Limited research scope":"Research branch verdicts"}),n.jsx("span",{style:{fontSize:11,color:t.textSecondary,lineHeight:1.4},children:Q.detail})]}):null,D.length>0?n.jsxs("div",{style:{display:"grid",gap:4},children:[n.jsx("div",{style:{fontSize:11,fontWeight:800,color:t.textSecondary},children:"Key findings"}),n.jsx(wr,{items:D,t,renderItem:(W,P)=>n.jsxs("div",{style:{fontSize:11.5,color:t.textSecondary,lineHeight:1.4,display:"flex",gap:6},children:[n.jsx("span",{style:{color:t.accent},children:"•"}),n.jsx("span",{children:W})]},P)})]}):ie.length>0?n.jsx("div",{style:{display:"grid",gap:5},children:n.jsx(wr,{items:ie,t,renderItem:(W,P)=>n.jsxs("div",{style:{fontSize:11.5,color:t.textSecondary,lineHeight:1.35},children:[P+1,". ",String(W.thought??W.expectation??"Research step")]},P)})}):null,Z?n.jsxs("div",{style:{fontSize:11.5,color:t.textPrimary,lineHeight:1.4,display:"flex",gap:6},children:[n.jsx("span",{style:{color:t.accent},children:"→"}),n.jsx("span",{children:Z})]}):null,m?g?n.jsx(Ci,{artifact:g,certifiedBlockName:Y,initialResult:m,initialChartConfig:Xe(d,m),payload:d,t,themeMode:r}):n.jsx(Dn,{result:m,themeMode:r,t,chartConfig:Xe(d,m)}):null,g?n.jsxs("details",{children:[n.jsxs("summary",{style:{cursor:"pointer",fontSize:11,color:t.textSecondary,listStyle:"none",display:"flex",alignItems:"center",gap:5},children:[n.jsx($t,{size:12}),n.jsx("span",{children:"View DQL artifact"}),n.jsxs("span",{style:{marginLeft:"auto",display:"inline-flex",alignItems:"center",gap:4},children:[g.source?n.jsx(nn,{text:g.source,t,title:"Copy DQL"}):null,!E&&l?n.jsxs("button",{type:"button",className:"dql-hover",title:"Save this DQL as a reusable block",onClick:W=>{W.preventDefault(),W.stopPropagation(),l({id:"save-dql-block",label:"Save as DQL block",route:"dql_block_draft"})},style:{border:"none",background:"transparent",cursor:"pointer",color:t.accent,display:"inline-flex",alignItems:"center",gap:3,fontSize:10.5,fontWeight:700,padding:"2px 4px"},children:[n.jsx(Wn,{size:12})," Save as block"]}):null]})]}),g.sourcePath?n.jsx("div",{style:{marginTop:6,fontSize:10.5,color:t.textMuted},children:g.sourcePath}):null,n.jsx("pre",{style:{...zt(t),marginTop:6},children:g.source})]}):null,y?n.jsxs("details",{children:[n.jsxs("summary",{style:{cursor:"pointer",fontSize:11,color:t.textSecondary,listStyle:"none",display:"flex",alignItems:"center",gap:5},children:[n.jsx(Pn,{size:12}),n.jsx("span",{children:Ti(!!g)}),n.jsx("span",{style:{marginLeft:"auto",display:"inline-flex",alignItems:"center",gap:4},children:n.jsx(nn,{text:y,t,title:"Copy SQL"})})]}),n.jsx("pre",{style:{...zt(t),marginTop:6},children:y})]}):null,F.length>0?n.jsxs("div",{style:{fontSize:11.5,color:t.textSecondary,lineHeight:1.4},children:["Gaps: ",F.join(", ")]}):null,w.length>0?n.jsxs("div",{style:{fontSize:11.5,color:t.textSecondary,lineHeight:1.4},children:["Files: ",w.join(", ")]}):null,n.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[B&&p?n.jsx("button",{type:"button","aria-label":"Open research evidence",onClick:()=>p(B,K,a),style:te(t),children:"Open research"}):null,y&&s?n.jsx("button",{type:"button",onClick:()=>s({sql:y,dqlArtifact:g,result:m,chartConfig:m?Xe(d,m):void 0,title:x,mixedSourcePlan:b,sourceRunId:a,question:c}),style:b?{...te(t),background:t.accent,borderColor:t.accent,color:"#fff",fontWeight:850,padding:"7px 11px"}:te(t),children:b?"Add workflow to notebook":g?"Insert as DQL cell":"Add SQL to notebook"}):y&&i?n.jsx("button",{type:"button",onClick:()=>i(y,x,{question:c,sourceRunId:a}),style:te(t),children:"Insert SQL preview"}):null,E&&u?n.jsx("button",{type:"button",onClick:()=>u(E,V),style:te(t),children:U}):null]})]})}function $o({run:e}){return e.trustState==="certified"?n.jsx(Se,{size:16,color:"#16a34a"}):e.trustState==="governed"?n.jsx(Se,{size:16,color:"#2563eb"}):e.trustState==="grounded"?n.jsx(Se,{size:16,color:"#2563eb"}):e.status==="completed"?n.jsx(_t,{size:16,color:"#16a34a"}):e.status==="cancelled"||e.stopReason==="cancelled"?n.jsx(Ct,{size:16,color:"#737373"}):e.status==="blocked"?n.jsx(Ct,{size:16,color:"#ef4444"}):n.jsx(Ct,{size:16,color:"#d97706"})}function gt({kind:e}){return e==="sql_cell"?n.jsx(Pn,{size:14}):e==="dql_block_draft"?n.jsx($t,{size:14}):e==="app_draft"||e==="app_proposal"?n.jsx(Cn,{size:14}):e==="research_run"?n.jsx(rt,{size:14}):n.jsx(tt,{size:14})}function To({run:e,t}){const r=e.trustState==="certified"?t.success:e.trustState==="governed"||e.trustState==="grounded"?t.accent:e.trustState==="blocked"?t.error:e.trustState==="not_applicable"?t.textMuted:t.warning,i=e.status==="cancelled"||e.stopReason==="cancelled"?"Cancelled":e.trustState==="certified"?"Certified":e.route==="dql_block_draft"?"Draft":Kn(e)?"Exploratory":e.status==="needs_clarification"?"Needs input":e.trustState==="blocked"?"Refused":"AI-generated";return n.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 _i({evaluations:e,t}){if(e.length===0)return null;const r=e.filter(s=>!s.passed),i=e.filter(s=>s.passed);return n.jsxs("div",{style:{display:"grid",gap:6,gridTemplateColumns:"minmax(0, 1fr)",minWidth:0},children:[r.map(s=>n.jsx(Ln,{evaluation:s,t},s.id)),i.length>0?n.jsxs("details",{children:[n.jsxs("summary",{className:"dql-hover",style:{cursor:"pointer",listStyle:"none",display:"inline-flex",alignItems:"center",gap:6,fontSize:11,fontWeight:700,color:t.textMuted,width:"fit-content"},children:[n.jsx(Se,{size:12,color:t.success}),n.jsxs("span",{children:[i.length," check",i.length>1?"s":""," verified"]})]}),n.jsx("div",{style:{display:"grid",gap:5,marginTop:7},children:i.map(s=>n.jsx(Ln,{evaluation:s,t},s.id))})]}):null]})}function Ln({evaluation:e,t}){const r=e.passed?t.success:e.severity==="blocking"?t.error:t.warning;return n.jsxs("div",{style:{display:"flex",gap:7,alignItems:"flex-start",fontSize:11.5,color:t.textSecondary,minWidth:0},children:[n.jsx("span",{style:{color:r,lineHeight:"16px",flex:"0 0 auto",fontWeight:800},children:e.passed?"OK":e.severity==="blocking"?"Stop":"Review"}),n.jsxs("span",{style:{lineHeight:1.4,minWidth:0,flex:1,overflowWrap:"anywhere"},children:[e.message,!e.passed&&e.suggestedRepair?n.jsxs("span",{style:{display:"block",color:t.textMuted,marginTop:1},children:["↳ ",e.suggestedRepair]}):null]})]})}function kn({t:e,icon:t,label:r,tone:i}){const s=i==="accent"?e.accent:i==="warning"?e.warning:e.textMuted;return n.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:[t,n.jsx("span",{children:r})]})}function Mo(e,t){switch(e){case"passed":return t.success;case"repaired":return t.accent;case"escalated":return t.accent;case"blocked":return t.error;default:return t.warning}}function qi({steps:e,t}){return n.jsxs("details",{style:{border:`1px solid ${t.headerBorder}`,background:t.cellBg,borderRadius:8,padding:"6px 9px"},children:[n.jsxs("summary",{style:{cursor:"pointer",fontSize:11.5,fontWeight:800,color:t.textSecondary,listStyle:"none",display:"flex",alignItems:"center",gap:6},children:[n.jsx(qt,{size:13}),n.jsxs("span",{children:["Plan trace · ",e.length," steps"]})]}),n.jsx("div",{style:{display:"grid",gap:10,marginTop:8},children:e.map(r=>{const i=Mo(r.status,t);return n.jsxs("div",{style:{display:"grid",gap:4,paddingLeft:8,borderLeft:`2px solid ${i}55`},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[n.jsxs("span",{style:{fontSize:11.5,fontWeight:850,color:t.textPrimary},children:[r.index,". ",Xr[r.route]]}),n.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"?n.jsx(dn,{size:10}):r.status==="repaired"?n.jsx(un,{size:10}):null,r.status.split("_").join(" ")]}),r.attempts>1?n.jsxs("span",{style:{fontSize:10,color:t.textMuted},children:[r.attempts," attempts"]}):null]}),r.goal?n.jsx("div",{style:{fontSize:11,color:t.textMuted,lineHeight:1.35},children:r.goal}):null,r.evaluations.length>0?n.jsx("div",{style:{display:"grid",gap:4},children:r.evaluations.map(s=>n.jsx(Ln,{evaluation:s,t},s.id))}):null]},r.id)})})]})}function Eo(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 Bo(e,t){return t==="sql_cell"?`Create a SQL cell for: ${e.question}`:t==="dql_block_draft"?`Create a DQL block draft for: ${e.question}`:t==="modeling_draft"?`Revise the modeling proposal for: ${e.question}`:t==="skill_draft"?`Revise the Skill proposal for: ${e.question}`:t==="app_build"?`Build an app for: ${e.question}`:t==="research"?`Research deeper: ${e.question}`:e.question}function _r(e){return`${e}_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function ft(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 Me(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 Lo(e,t){const r=i=>i.toLowerCase().replace(/[\s.,!?'"()`*_-]+/g," ").trim();return r(e)===r(t)}function Ee(e){var r,i;const t=[e.result,e.resultPreview,(r=e.researchRun)==null?void 0:r.resultPreview,(i=e.result)==null?void 0:i.result];for(const s of t){if(!s||typeof s!="object")continue;const o=s;if(!Array.isArray(o.rows)&&!Array.isArray(o.columns))continue;const a=Zi(o),c=a.rows,u=a.columns;if(!(c.length===0&&u.length===0&&typeof o.rowCount!="number"))return{columns:u,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}:{}}}}async function zi(e){const t=e.selectedText.trim();if(!t||!e.run||!e.artifact)return;const r=Ee(re(e.artifact));if(!(r!=null&&r.resultFingerprint)||!r.columns.length)return;const i=r.rows.flatMap(a=>r.columns.flatMap(c=>{const u=No(a[c]);return u===t?[{column:c,value:u,row:a}]:[]}));if(i.length!==1)return;const s=i[0],o=await Fo({columns:r.columns,row:Object.fromEntries(r.columns.map(a=>[a,s.row[a]]))});if(o)return{version:1,sourceRunId:e.run.id,sourceArtifactId:e.artifact.id,canonicalColumn:s.column,value:s.value,rowFingerprint:o,resultFingerprint:r.resultFingerprint}}function No(e){if(typeof e=="string")return e;if(typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean")return String(e)}function Nn(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Nn).join(",")}]`;const t=e;return`{${Object.keys(t).sort().map(r=>`${JSON.stringify(r)}:${Nn(t[r])}`).join(",")}}`}async function Fo(e){var i;const t=(i=globalThis.crypto)==null?void 0:i.subtle;if(!t)return;const r=await t.digest("SHA-256",new TextEncoder().encode(Nn(e)));return[...new Uint8Array(r)].map(s=>s.toString(16).padStart(2,"0")).join("")}function Xe(e,t){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,u=t.columns,p=d=>typeof i[d]=="string"&&u.includes(i[d])?i[d]:void 0,f=Array.isArray(i.metrics)?i.metrics.filter(d=>typeof d=="string"&&u.includes(d)):[],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")}:{},...f.length>0?{metrics:f}:{},...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 $i(e,t){var i;const r=Xe(e,t);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 Mt(e){const t=nt(e.dqlArtifact);if(t)return t;const r=e.researchRun&&typeof e.researchRun=="object"&&!Array.isArray(e.researchRun)?e.researchRun:void 0;return nt(r==null?void 0:r.dqlArtifact)}function Ti(e){return e?"View compiled SQL preview":"View SQL preview"}function nn({text:e,t,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 n.jsxs("button",{type:"button",onClick:o,title:r,className:"dql-hover",style:{border:"none",background:"transparent",cursor:"pointer",color:i?t.success:t.textMuted,display:"inline-flex",alignItems:"center",gap:3,fontSize:10.5,fontWeight:650,padding:"2px 4px"},children:[i?n.jsx(It,{size:12}):n.jsx(Pr,{size:12}),i?"Copied":null]})}function re(e){return e.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{}}function Do(e){var i,s,o;const t=[],r=new Set;for(const a of e.artifacts){const c=re(a),u=Array.isArray(c.memoryContext)?c.memoryContext:[];for(const f of u){if(!f||typeof f!="object")continue;const l=f,d=typeof l.title=="string"?l.title.trim():"";!d||r.has(`m:${d}`)||(r.add(`m:${d}`),t.push({kind:"memory",id:typeof l.id=="string"?l.id:void 0,label:d,detail:typeof l.content=="string"?l.content:void 0}))}const p=Array.isArray(c.appliedHints)?c.appliedHints:[];for(const f of p){if(!f||typeof f!="object")continue;const l=f,d=typeof l.title=="string"?l.title.trim():"";if(!d||r.has(`h:${d}`))continue;r.add(`h:${d}`);const m=typeof((i=l.lesson)==null?void 0:i.rule)=="string"?l.lesson.rule:typeof l.guidance=="string"?l.guidance:void 0,g=[typeof l.scopeReason=="string"?l.scopeReason:void 0,typeof l.graphReason=="string"?l.graphReason:void 0].filter(Boolean).join("; "),b=typeof((s=l.matchSignals)==null?void 0:s.lexicalScore)=="number"?l.matchSignals.lexicalScore:void 0,y=typeof((o=l.matchSignals)==null?void 0:o.graphScore)=="number"?l.matchSignals.graphScore:void 0,x=b!==void 0||y!==void 0?`Signals: lexical ${(b??0).toFixed(2)}, graph ${(y??0).toFixed(2)}`:void 0;t.push({kind:"hint",id:typeof l.hintId=="string"?l.hintId:void 0,label:d,detail:[m,g?`Matched: ${g}`:void 0,x].filter(Boolean).join(" · ")||void 0})}}return t.slice(0,6)}function Mi({run:e,t}){const[r,i]=h.useState(!1),[s,o]=h.useState(new Set),a=h.useMemo(()=>Do(e).filter(u=>!u.id||!s.has(u.id)),[e,s]);if(a.length===0)return null;const c=async u=>{try{await se.deleteAgentMemory(u),o(p=>new Set(p).add(u))}catch{}};return n.jsxs("div",{style:{display:"grid",gap:6,gridTemplateColumns:"minmax(0, 1fr)",minWidth:0},children:[n.jsxs("button",{type:"button",onClick:()=>i(u=>!u),style:Wo(t),children:[n.jsx(en,{size:11}),n.jsxs("span",{children:["Applied ",a.length," learning",a.length>1?"s":""]}),r?n.jsx(Dr,{size:11}):n.jsx(an,{size:11})]}),r?n.jsxs("div",{style:Oo(t),children:[a.map(u=>n.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-start"},children:[n.jsx("span",{style:Vo(t,u.kind),children:u.kind==="hint"?"governed lesson":"memory"}),n.jsxs("div",{style:{minWidth:0,flex:1},children:[n.jsx("div",{style:{fontSize:11.5,fontWeight:650,color:t.textPrimary},children:u.label}),u.detail?n.jsx("div",{style:{fontSize:11,color:t.textMuted,lineHeight:1.4,marginTop:1},children:u.detail}):null]}),u.kind==="memory"&&u.id?n.jsx("button",{type:"button",onClick:()=>void c(u.id),style:Ho(t),children:"Stop using"}):null]},`${u.kind}:${u.label}`)),n.jsx("div",{style:{fontSize:10.5,color:t.textMuted},children:"Advisory only — learnings never override a certified answer. Manage them under Settings → Agent learning."})]}):null]})}function Yn(e){const t=[],r=new Set,i=e.trustState==="certified",s=(o,a)=>{typeof o!="string"||!o.trim()||r.has(o)||(r.add(o),t.push({label:o,certified:a}))};for(const o of e.artifacts){const a=re(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(u=>s(u,i)),s(a.sourceCertifiedBlock,!0)}return t.slice(0,4)}function Le(e){for(const t of e.artifacts){const r=re(t),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=nt(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 An(e){var t;if(e.trustState==="certified")for(const r of e.artifacts){const i=re(r),s=i.blockName??i.blockId??((t=nt(i.dqlArtifact))==null?void 0:t.name);if(typeof s=="string"&&s.trim())return s.trim()}}function Po(e){for(const t of e.artifacts){const r=re(t),i=Ee(r);if(!i)continue;const s=Xe(r,i);if(s)return s}}function Fe(e){for(const t of e.artifacts){const r=re(t),i=nt(r.dqlArtifact);if(i)return i;const s=r.researchRun&&typeof r.researchRun=="object"&&!Array.isArray(r.researchRun)?r.researchRun:void 0,o=nt(s==null?void 0:s.dqlArtifact);if(o)return o}}function rn(e){const t=e.route==="dql_block_draft"&&e.status!=="blocked"&&e.status!=="cancelled"&&e.stopReason!=="cancelled"&&e.status!=="needs_clarification";if(e.route==="certified_answer"||!Tt(e)&&!t)return;const r=Fe(e),i=Le(e);if(!((!(r!=null&&r.source)||r.sourcePath)&&!i)){for(const s of e.artifacts){const o=re(s),a=Ee(o),c=hn(o);if(a)return{sql:i,dqlArtifact:r,result:a,chartConfig:Xe(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 hn(e){const t=e.mixedSourcePlan;if(!t||typeof t!="object"||Array.isArray(t))return;const r=t;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 Ei(e,t){return{display:"inline-flex",alignItems:"center",gap:4,fontSize:10.5,padding:"2px 7px",borderRadius:999,background:t?`${e.success}14`:e.cellBg,color:t?e.success:e.textMuted,border:`1px solid ${t?`${e.success}44`:e.headerBorder}`}}function Wo(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 Oo(e){return{display:"grid",gap:8,padding:10,borderRadius:8,background:e.cellBg,border:`1px solid ${e.headerBorder}`}}function Vo(e,t){const r=t==="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 Ho(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 Qo(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 qr(e){return{...Qo(e),width:40,height:40}}function sn(e){return{...cn(e,{variant:"secondary",size:"md",pill:!0}),fontWeight:550}}function Uo(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 zr(e,t){return{...cn(e,{variant:t?"primary":"secondary",size:"lg"}),...t?{}:{color:e.textMuted}}}function $r(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 Go(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 Ko(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 Tr(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 Mr(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 Yo(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 Xo(e){return{alignSelf:"flex-start",maxWidth:"92%",color:e.textPrimary,border:`1px solid ${e.cellBorder}`,background:e.appBg,borderRadius:10,padding:"10px 12px"}}function Jo(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 Zo(e){return{border:`1px solid ${e.headerBorder}`,background:e.cellBg,borderRadius:8,padding:9,fontSize:12.5,color:e.textPrimary,lineHeight:1.45}}function zt(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 Er(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 te(e){return cn(e,{variant:"secondary",size:"sm"})}const on={warehouse:{title:"The warehouse rejected the query",hint:"The SQL reached your warehouse and it refused. The message below is the driver’s own."},execution:{title:"The selected query did not complete",hint:"DQL froze the selected plan and began execution, but the current connection could not complete it. Review the connection or warehouse state, then retry."},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 Bi(e){var r,i,s,o,a,c,u,p,f,l,d,m,g;if(e.status==="cancelled"||e.stopReason==="cancelled"||e.route==="cancelled"||((i=(r=e.diagnosticReceipt)==null?void 0:r.failure)==null?void 0:i.code)==="RUN_CANCELLED")return"cancel";const t=(s=e.diagnosticReceiptV4)==null?void 0:s.terminalIncident;if((t==null?void 0:t.code)==="ANALYTICAL_EXECUTION_FAILED"&&t.boundary==="sql.execute")return"execution";if((t==null?void 0:t.code)==="RESULT_CONTRACT_MISMATCH"&&t.boundary==="result.validate")return"result_contract";for(const b of e.artifacts??[]){const y=re(b),x=y,_=(o=x==null?void 0:x.warehouseFailure)==null?void 0:o.origin,z=typeof((a=x==null?void 0:x.analyticalFailure)==null?void 0:a.code)=="string"?x.analyticalFailure.code:"";if(di(y))return"compile";if((x==null?void 0:x.refusalCode)==="modeling_gap")return"modeling_gap";if(((c=x==null?void 0:x.aggregationSafetyProof)==null?void 0:c.status)==="blocked")return"proof_integrity";if(["IDENTIFIER_SCOPE_INVALID","EXECUTION_TARGET_MISMATCH","SEMANTIC_TARGET_BINDING_MISSING","SEMANTIC_SOURCE_DRIFT"].includes(z))return"identity_integrity";if(["POLICY_DENIED","PERMISSION_DENIED"].includes(z))return"policy";if(z==="RESULT_CONTRACT_MISMATCH")return"result_contract";if(["TIMEOUT","SEMANTIC_COMPILATION_TIMEOUT"].includes(z))return"timeout";if(z==="EXECUTION_CANCELLED")return"cancel";if(["COMPILATION_FAILED","DIALECT_ERROR","SEMANTIC_ADAPTER_NOT_READY"].includes(z))return"compile";if(typeof _=="string"&&_ in on)return _;const N=(x==null?void 0:x.analyticalFailure)!==void 0,q=N&&((u=x==null?void 0:x.analyticalFailure)==null?void 0:u.phase)==="execution",E=!N&&((x==null?void 0:x.refusalCode)==="execution_error"||typeof(x==null?void 0:x.executionError)=="string"&&x.executionError.trim().length>0);if(q||E)return"execution";if(((p=x==null?void 0:x.providerFailure)==null?void 0:p.code)==="orchestration_budget_exhausted"||((f=x==null?void 0:x.providerFailure)==null?void 0:f.code)==="PROVIDER_DISPATCH_BUDGET_EXHAUSTED"||(x==null?void 0:x.refusalCode)==="orchestration_budget_exhausted")return"orchestration_budget";if(x!=null&&x.providerFailure||(x==null?void 0:x.refusalCode)==="provider_error")return"provider";if((x==null?void 0:x.refusalCode)==="ambiguous")return"ambiguity";if((x==null?void 0:x.refusalCode)==="grounding_gap")return"retrieval_gap"}return((d=(l=e.diagnosticReceipt)==null?void 0:l.failure)==null?void 0:d.code)==="orchestration_budget_exhausted"?"orchestration_budget":((g=(m=e.diagnosticReceipt)==null?void 0:m.failure)==null?void 0:g.code)==="AI_PROVIDER_FAILURE"?"provider":"unknown"}function Li(e){for(const t of e.artifacts??[]){const r=re(t),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 Ni(e){const t=e.repairCapability;return(t==null?void 0:t.version)===1&&t.automatic.eligible===!0&&t.automatic.action==="repair_embedded_sql"&&t.automatic.correctionCode==="SQL_EXECUTION_REPAIR"&&t.automatic.attemptsRemaining>0&&t.routeLocked===!0&&t.targetLocked===!0&&t.sourceImmutable===!0}function ea({run:e,detail:t,threadId:r,onRepaired:i,t:s}){const o=Bi(e),a=on[o]??on.unknown,[c,u]=h.useState(!1),[p,f]=h.useState(null),l=Ni(e),d=async()=>{if(!c){u(!0),f(null);try{const m=await se.repairAgentRunExecution(e.id,r);i(m.run)}catch(m){f(m instanceof Error?m.message:String(m))}finally{u(!1)}}};return n.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:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7},children:[n.jsx(Be,{size:13,color:s.error,style:{flexShrink:0}}),n.jsx("span",{style:{fontSize:12.5,fontWeight:700,color:s.textPrimary},children:a.title})]}),n.jsx("div",{style:{fontSize:12.5,lineHeight:1.6,color:s.textSecondary,wordBreak:"break-word"},children:Me(t)}),n.jsx("div",{style:{fontSize:11.5,lineHeight:1.5,color:s.textMuted},children:a.hint}),l?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",marginTop:2},children:[n.jsxs("button",{type:"button",className:"dql-hover",disabled:c,onClick:()=>void d(),style:{...te(s),opacity:c?.7:1},children:[n.jsx(un,{size:12})," ",c?"Fixing and retrying…":"Fix and retry"]}),n.jsx("span",{style:{fontSize:10.5,color:s.textMuted},children:"One bounded repair attempt on the same data target."})]}):null,p?n.jsx("div",{role:"alert",style:{fontSize:11.5,lineHeight:1.45,color:s.error},children:Me(p)}):null]})}function Fi(e){var i,s,o;const t=ta(e);if(t)return t;for(const a of e.artifacts??[]){const c=re(a),u=c==null?void 0:c.warehouseFailure,p=[u==null?void 0:u.redactedMessage,u==null?void 0:u.diagnostic,c==null?void 0:c.executionError,(i=c==null?void 0:c.refusalDetails)==null?void 0:i.message].find(f=>typeof f=="string"&&f.trim().length>0);if(p)return p}const r=na(e);return r||e.summary||((o=(s=e.diagnosticReceipt)==null?void 0:s.failure)==null?void 0:o.message)}function ta(e){const t=[S(e.diagnosticReceiptV3),...e.artifacts.map(a=>S(re(a).diagnosticReceiptV3))],r=S(e.routeDecision),i=S(r==null?void 0:r.terminalOutcome),s=S(i==null?void 0:i.gap);if([...t.flatMap(a=>{var c;return[S(a==null?void 0:a.terminalGap),S((c=S(a==null?void 0:a.cascade))==null?void 0:c.terminalGap)]}),s].some(a=>(a==null?void 0:a.code)==="MISSING_RELATIONSHIP"))return"This Ask needs a certified relationship or approved allocation proof before it can run. DQL did not infer a relationship or execute a query."}function na(e){var r;const t=[S((r=S(e.diagnosticReceipt))==null?void 0:r.resolvedAnalyticalPlan),...(e.artifacts??[]).flatMap(i=>{var o;const s=re(i);return[S(s.resolvedAnalyticalPlan),S((o=S(s.diagnosticReceipt))==null?void 0:o.resolvedAnalyticalPlan)]})].filter(i=>!!i);for(const i of t){const s=S(i.query),a=[...Ce(s==null?void 0:s.measures).map(p=>({kind:"metric",binding:p})),...Ce(s==null?void 0:s.dimensions).map(p=>({kind:"dimension",binding:p})),...Ce(s==null?void 0:s.filters).flatMap(p=>{const f=S(p.binding);return f?[{kind:"filter",binding:f}]:[]})].find(({binding:p})=>p.status==="ambiguous"||p.status==="unresolved");if(!a)continue;const c=R(a.binding.requested)||`requested ${a.kind}`,u=Array.isArray(a.binding.candidateIds)?a.binding.candidateIds.filter(p=>typeof p=="string").map(ra):[];return a.binding.status==="ambiguous"&&u.length>1?`I found more than one governed ${a.kind} for “${c}”: ${u.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 ra(e){return(e.split(/[:./]/).filter(Boolean).at(-1)??e).replace(/[_-]+/g," ").replace(/\b\w/g,r=>r.toUpperCase())}const ga=Object.freeze(Object.defineProperty({__proto__:null,ASK_FAILURE_PRESENTATION:on,AnalyticalTaskOutcomeList:ai,CANONICAL_DECISION_SUMMARY_UNAVAILABLE:Ur,InspectorAuthoritativeV8DecisionStory:mi,InspectorDecisionStory:vi,InspectorDecisionSummaryUnavailable:wi,InspectorRuntimeDecisionStory:bi,RESEARCH_TOOL_ROWS_CONSENT_TITLE:Zr,ResearchPartialFailureRepair:ji,UnifiedAgentRunPanel:ro,acceptedAskAnswer:Ke,agentRunHistoryFromItems:Yr,agentRunPerformanceRows:$n,analyticalInspectorContract:hi,analyticalInspectorSections:jo,analyticalRepairActionLabels:So,analyticalTaskOutcomePresentation:oi,appPinDestinationLabel:En,artifactReadyPayloadFromRun:rn,artifactSqlDisclosureLabel:Ti,askAppDestinations:Ai,askAppWriteErrorMessage:Mn,askArtifactMeta:pn,askFailureDetail:Fi,askFailureOrigin:Bi,askInspectorTabsForState:li,askRunAllowsExecutionRepair:Ni,askRunCaptureWarning:Li,authoritativeV8CompactInspectorProjection:tn,clarificationSelectionInput:Xt,completedRunGuidanceFor:ii,deriveResultChartConfig:as,extractResult:Ee,hasAnalyticalInspectorContract:fn,inlineAskChartConfig:$i,isAgentRunPinnable:Tt,liveAgentActivityFor:si,longRunGuidanceFor:ri,preferredAskInspectorTab:Qn,providerEgressSummary:Tn,replacePresentedAgentRun:Kr,researchResultRowsOptInForRun:ei,researchSourceFromRun:ki,researchVerdictSummary:Hn,researchVerdictSummaryForRun:ci,resolveArtifactDqlView:Mt,resolveComposerRequestedMode:Gr,resolvedParameterValues:Bn,selectAgentExecutionConnection:ti,selectedResultBindingForSelection:zi,threadItemsFromTurns:ni,trustExplainer:Gn,usePersistedAgentThreadId:ls},Symbol.toStringTag,{value:"Module"}));export{Fs as B,Dr as C,cr as S,ro as U,_s as a,Bs as b,ga as c};
|