@duckcodeailabs/dql-cli 1.12.3 → 1.12.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.
Files changed (79) hide show
  1. package/dist/assets/dql-notebook/assets/AgentAnswerCard-BJAnjaLA.js +5 -0
  2. package/dist/assets/dql-notebook/assets/{AgentLogPage-CsSC2tOR.js → AgentLogPage-J72WR6hk.js} +1 -1
  3. package/dist/assets/dql-notebook/assets/{AiBuildDialog-CjJ-9bQW.js → AiBuildDialog-CHJZfDmp.js} +1 -1
  4. package/dist/assets/dql-notebook/assets/{AiBuildResult-BvTcW9oE.js → AiBuildResult-Da7_Cn12.js} +1 -1
  5. package/dist/assets/dql-notebook/assets/{AiSidePanel-CxFrOfCE.js → AiSidePanel-BY6W_5aC.js} +1 -1
  6. package/dist/assets/dql-notebook/assets/{AnalyticsHome-BtXEdJNR.js → AnalyticsHome-u-buXgdv.js} +1 -1
  7. package/dist/assets/dql-notebook/assets/{AppsView-HjQkbbE6.js → AppsView-3k7ftDpd.js} +3 -3
  8. package/dist/assets/dql-notebook/assets/{BlockStudio-oQHTJsXC.js → BlockStudio-CLX4EUyO.js} +14 -14
  9. package/dist/assets/dql-notebook/assets/{BusinessArtifactView-Dpsftjs7.js → BusinessArtifactView-3THMNeyO.js} +1 -1
  10. package/dist/assets/dql-notebook/assets/{DbtFirstModelingPage-c6ZteaI6.js → DbtFirstModelingPage-BwBPwtdA.js} +1 -1
  11. package/dist/assets/dql-notebook/assets/{GitPage-Cj6mc-Yv.js → GitPage-CvEki0pe.js} +1 -1
  12. package/dist/assets/dql-notebook/assets/{GlobalAiRail-8G_rEyhK.js → GlobalAiRail-NXdk9kNy.js} +1 -1
  13. package/dist/assets/dql-notebook/assets/{GovernedContextPage-BTtzt0Za.js → GovernedContextPage-DILbw-Vr.js} +1 -1
  14. package/dist/assets/dql-notebook/assets/{HelpDocsPage-e2CesE73.js → HelpDocsPage-DgCu4bvY.js} +1 -1
  15. package/dist/assets/dql-notebook/assets/{HomePage-U3ryMLEF.js → HomePage-CK3fXTQo.js} +1 -1
  16. package/dist/assets/dql-notebook/assets/{LineageDAG-CEmgJzm3.js → LineageDAG-DW_NO3P2.js} +1 -1
  17. package/dist/assets/dql-notebook/assets/{LineageDetailView-CeV5QMXS.js → LineageDetailView-VT7DLJOB.js} +1 -1
  18. package/dist/assets/dql-notebook/assets/{LineageDrawer-B1oAn-N_.js → LineageDrawer-DSTm8aXw.js} +1 -1
  19. package/dist/assets/dql-notebook/assets/{LineagePathBreadcrumb-fP6RTXut.js → LineagePathBreadcrumb-DRlAYasJ.js} +1 -1
  20. package/dist/assets/dql-notebook/assets/{MiniLineageGraph-CBYSTmRC.js → MiniLineageGraph-CR_nhwhZ.js} +1 -1
  21. package/dist/assets/dql-notebook/assets/{NewBlockModal-ksEwimjl.js → NewBlockModal-CJvjYiBF.js} +1 -1
  22. package/dist/assets/dql-notebook/assets/{NewNotebookModal-CUx0WmXb.js → NewNotebookModal-BEpPH93n.js} +1 -1
  23. package/dist/assets/dql-notebook/assets/{NotebookEditor-BdxJL3LX.js → NotebookEditor-C7GDFwhF.js} +1 -1
  24. package/dist/assets/dql-notebook/assets/{ReadinessPage-DZ9wDW76.js → ReadinessPage-rZiOp2xr.js} +1 -1
  25. package/dist/assets/dql-notebook/assets/{SetupOnboarding-Bt0AAe0h.js → SetupOnboarding-BWjhTjPB.js} +1 -1
  26. package/dist/assets/dql-notebook/assets/{TrustBadge-DNVJK_mP.js → TrustBadge-RvZ9s6OQ.js} +1 -1
  27. package/dist/assets/dql-notebook/assets/{UnifiedAgentRunPanel-BNqE169i.js → UnifiedAgentRunPanel-CGPcpY1B.js} +18 -18
  28. package/dist/assets/dql-notebook/assets/{answer-to-notebook-B_gE6rsY.js → answer-to-notebook-Di227Cd4.js} +1 -1
  29. package/dist/assets/dql-notebook/assets/{arrow-left-DnKGhzOR.js → arrow-left-BZHDcWHR.js} +1 -1
  30. package/dist/assets/dql-notebook/assets/{arrow-right-CQ73DG7_.js → arrow-right-DlM1pC3_.js} +1 -1
  31. package/dist/assets/dql-notebook/assets/{book-open-text-CyBV5Nhw.js → book-open-text-DBcXFQAu.js} +1 -1
  32. package/dist/assets/dql-notebook/assets/{bot-UOPtBzCj.js → bot-BAywbvPm.js} +1 -1
  33. package/dist/assets/dql-notebook/assets/{chevron-up-CDHDU3N3.js → chevron-up-B_GfKE_F.js} +1 -1
  34. package/dist/assets/dql-notebook/assets/{circle-x-DC5nkL_u.js → circle-x-BcxtZ-ym.js} +1 -1
  35. package/dist/assets/dql-notebook/assets/{dagre.esm-C7ujXipB.js → dagre.esm-Bqs0lsEz.js} +1 -1
  36. package/dist/assets/dql-notebook/assets/{external-link-BiJ_dtTM.js → external-link-B24Dk9_t.js} +1 -1
  37. package/dist/assets/dql-notebook/assets/{grip-vertical-eXvkUerq.js → grip-vertical-D9g31N3j.js} +1 -1
  38. package/dist/assets/dql-notebook/assets/index-DU7j3Sqk.js +644 -0
  39. package/dist/assets/dql-notebook/assets/{link-2-DkHVJTuH.js → link-2-B36oR5Bj.js} +1 -1
  40. package/dist/assets/dql-notebook/assets/{list-tree-8lYW2Itb.js → list-tree-B9ZzGc4U.js} +1 -1
  41. package/dist/assets/dql-notebook/assets/{maximize-2-DjSovOdP.js → maximize-2-BrvQLPoj.js} +1 -1
  42. package/dist/assets/dql-notebook/assets/{minimize-2-DGlmQLES.js → minimize-2-BrpFmsxS.js} +1 -1
  43. package/dist/assets/dql-notebook/assets/{panel-right-open-DPc4gShM.js → panel-right-open-B1g1qhh5.js} +1 -1
  44. package/dist/assets/dql-notebook/assets/{pencil-nwaGtOdL.js → pencil-DwywbTqQ.js} +1 -1
  45. package/dist/assets/dql-notebook/assets/{rotate-ccw-ByjLhAu7.js → rotate-ccw-Db_KVs3J.js} +1 -1
  46. package/dist/assets/dql-notebook/assets/{semantic-fields-eEhwnQhG.js → semantic-fields-BIVuvP2l.js} +1 -1
  47. package/dist/assets/dql-notebook/assets/{triangle-alert-zws0cKhp.js → triangle-alert-Cne6C2aG.js} +1 -1
  48. package/dist/assets/dql-notebook/assets/usePersistedAgentThreadId-D6mtrJ-_.js +18 -0
  49. package/dist/assets/dql-notebook/assets/{user-round-CM8xNakq.js → user-round-DkzxN1xD.js} +1 -1
  50. package/dist/assets/dql-notebook/assets/{wand-sparkles-CIKc8r-4.js → wand-sparkles-CJUvFtur.js} +1 -1
  51. package/dist/assets/dql-notebook/assets/{workflow-6C0ZLbTi.js → workflow-BOvVTg7R.js} +1 -1
  52. package/dist/assets/dql-notebook/assets/{wrench-CeU7hF12.js → wrench-YeSpzZRt.js} +1 -1
  53. package/dist/assets/dql-notebook/assets/{x-DLWEzvri.js → x-C6tsHUR7.js} +1 -1
  54. package/dist/assets/dql-notebook/index.html +1 -1
  55. package/dist/block-invocation.js +4 -0
  56. package/dist/block-invocation.js.map +1 -1
  57. package/dist/llm/answer-loop-tools.d.ts +8 -2
  58. package/dist/llm/answer-loop-tools.d.ts.map +1 -1
  59. package/dist/llm/answer-loop-tools.js +29 -2
  60. package/dist/llm/answer-loop-tools.js.map +1 -1
  61. package/dist/llm/providers/dql-agent-provider.d.ts +27 -1
  62. package/dist/llm/providers/dql-agent-provider.d.ts.map +1 -1
  63. package/dist/llm/providers/dql-agent-provider.js +79 -15
  64. package/dist/llm/providers/dql-agent-provider.js.map +1 -1
  65. package/dist/llm/types.d.ts +8 -1
  66. package/dist/llm/types.d.ts.map +1 -1
  67. package/dist/local-runtime.d.ts +46 -0
  68. package/dist/local-runtime.d.ts.map +1 -1
  69. package/dist/local-runtime.js +606 -66
  70. package/dist/local-runtime.js.map +1 -1
  71. package/dist/package.json +10 -10
  72. package/dist/sql-result-filter.d.ts +39 -0
  73. package/dist/sql-result-filter.d.ts.map +1 -0
  74. package/dist/sql-result-filter.js +256 -0
  75. package/dist/sql-result-filter.js.map +1 -0
  76. package/package.json +10 -10
  77. package/dist/assets/dql-notebook/assets/AgentAnswerCard-BEIwKGm4.js +0 -5
  78. package/dist/assets/dql-notebook/assets/index-BMVfPaXr.js +0 -644
  79. package/dist/assets/dql-notebook/assets/usePersistedAgentThreadId-hxi1RZDm.js +0 -18
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@duckcodeailabs/dql-cli",
3
- "version": "1.12.3",
3
+ "version": "1.12.4",
4
4
  "description": "Public CLI for parsing, formatting, testing, and certifying DQL blocks",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -25,15 +25,15 @@
25
25
  },
26
26
  "dependencies": {
27
27
  "@anthropic-ai/sdk": "^0.104.2",
28
- "@duckcodeailabs/dql-agent": "^1.12.3",
29
- "@duckcodeailabs/dql-compiler": "^1.12.3",
30
- "@duckcodeailabs/dql-connectors": "^1.12.3",
31
- "@duckcodeailabs/dql-core": "^1.12.3",
32
- "@duckcodeailabs/dql-governance": "^1.12.3",
33
- "@duckcodeailabs/dql-mcp": "^1.12.3",
34
- "@duckcodeailabs/dql-notebook": "^1.12.3",
35
- "@duckcodeailabs/dql-project": "^1.12.3",
36
- "@duckcodeailabs/dql-slack": "^1.12.3",
28
+ "@duckcodeailabs/dql-agent": "^1.12.4",
29
+ "@duckcodeailabs/dql-compiler": "^1.12.4",
30
+ "@duckcodeailabs/dql-connectors": "^1.12.4",
31
+ "@duckcodeailabs/dql-core": "^1.12.4",
32
+ "@duckcodeailabs/dql-governance": "^1.12.4",
33
+ "@duckcodeailabs/dql-mcp": "^1.12.4",
34
+ "@duckcodeailabs/dql-notebook": "^1.12.4",
35
+ "@duckcodeailabs/dql-project": "^1.12.4",
36
+ "@duckcodeailabs/dql-slack": "^1.12.4",
37
37
  "isomorphic-git": "^1.27.0",
38
38
  "js-yaml": "^4.1.0",
39
39
  "node-cron": "^3.0.3",
@@ -0,0 +1,39 @@
1
+ export interface SqlFilterableColumn {
2
+ /** Column name as it appears in the result set. */
3
+ column: string;
4
+ /** The predicate target, alias-qualified when the statement joins more than one relation. */
5
+ predicateTarget: string;
6
+ }
7
+ /**
8
+ * A generated block's SQL carries `${param}` placeholders, which no dialect
9
+ * parser accepts. Replace each with a string literal of the SAME LENGTH so the
10
+ * statement parses and every offset still maps onto the original text.
11
+ */
12
+ export declare function placeholderSafeSql(sql: string): string;
13
+ /**
14
+ * Which result columns may safely become a filter input on this SQL.
15
+ * Returns [] whenever anything is uncertain.
16
+ */
17
+ export declare function filterableResultColumns(sql: string, resultColumns: string[], dialect?: string): SqlFilterableColumn[];
18
+ /**
19
+ * Write the new SQL back into a generated block, and declare the new parameter
20
+ * in `params`, `parameterPolicy`, `allowedFilters`, and `filterBindings`.
21
+ *
22
+ * Targeted edits rather than regenerating the block: the source carries curated
23
+ * metadata (terms, grain, outputs, lineage context) that a rebuild would either
24
+ * lose or re-infer differently.
25
+ */
26
+ export declare function replaceBlockStudioSql(source: string, sql: string, parameterName: string, value: unknown): string;
27
+ export interface AddSqlResultFilterResult {
28
+ sql: string;
29
+ parameterName: string;
30
+ predicateTarget: string;
31
+ }
32
+ /**
33
+ * Inject `<column> = ${param}` into the statement's top-level WHERE, adding the
34
+ * clause when there is none. Throws when the column is not offerable — callers
35
+ * should have used {@link filterableResultColumns} first, so a throw here means
36
+ * the artifact and the result disagree.
37
+ */
38
+ export declare function addSqlResultFilter(sql: string, resultColumns: string[], column: string, existingParameterNames?: string[], dialect?: string): AddSqlResultFilterResult;
39
+ //# sourceMappingURL=sql-result-filter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sql-result-filter.d.ts","sourceRoot":"","sources":["../src/sql-result-filter.ts"],"names":[],"mappings":"AAkCA,MAAM,WAAW,mBAAmB;IAClC,mDAAmD;IACnD,MAAM,EAAE,MAAM,CAAC;IACf,6FAA6F;IAC7F,eAAe,EAAE,MAAM,CAAC;CACzB;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAMtD;AA0ED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,EAAE,OAAO,SAAW,GAAG,mBAAmB,EAAE,CAgDvH;AASD;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,EACX,aAAa,EAAE,MAAM,EACrB,KAAK,EAAE,OAAO,GACb,MAAM,CAoBR;AAED,MAAM,WAAW,wBAAwB;IACvC,GAAG,EAAE,MAAM,CAAC;IACZ,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,MAAM,CAAC;CACzB;AAYD;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,GAAG,EAAE,MAAM,EACX,aAAa,EAAE,MAAM,EAAE,EACvB,MAAM,EAAE,MAAM,EACd,sBAAsB,GAAE,MAAM,EAAO,EACrC,OAAO,SAAW,GACjB,wBAAwB,CAyB1B"}
@@ -0,0 +1,256 @@
1
+ /**
2
+ * Add a user-chosen result column as a runtime filter input on a GENERATED SQL
3
+ * answer.
4
+ *
5
+ * Ask already lets you change an input it inferred (`WHERE region = 'EMEA'`
6
+ * becomes `${region}`). This is the other half: promoting a column that appears
7
+ * in the RESULT but was never filtered — "I can see `channel` in the output, let
8
+ * me filter by it" — into a real, reusable block parameter.
9
+ *
10
+ * The whole module is deliberately conservative, because injecting a predicate
11
+ * into model-written SQL is the same class of rewrite that used to detach CTEs
12
+ * and return unfiltered totals under a passing trust label. So:
13
+ *
14
+ * - only a single top-level SELECT that the dialect parser can actually read;
15
+ * - only columns that trace to a REAL SOURCE COLUMN. An aggregate output such
16
+ * as `SUM(amount) AS revenue` never appears in `analysis.columns`, so
17
+ * intersecting with the result columns excludes it for free — and a filter
18
+ * on an aggregate would need HAVING, whose post-aggregation semantics are
19
+ * not what someone picking a column off a table expects;
20
+ * - only columns that resolve to exactly one relation, so the predicate cannot
21
+ * be ambiguous;
22
+ * - insertion positions are found with paren-depth tracking over a
23
+ * string/comment-masked copy, so a `GROUP BY` inside a subquery is never
24
+ * mistaken for the outer one.
25
+ *
26
+ * Anything that fails a check is simply not offered.
27
+ */
28
+ import { analyzeSqlReferences } from '@duckcodeailabs/dql-core';
29
+ /** Clauses that must come AFTER the WHERE clause we are extending or adding. */
30
+ const TRAILING_CLAUSES = [
31
+ 'group by', 'having', 'qualify', 'window', 'order by', 'limit', 'offset', 'fetch',
32
+ ];
33
+ /**
34
+ * A generated block's SQL carries `${param}` placeholders, which no dialect
35
+ * parser accepts. Replace each with a string literal of the SAME LENGTH so the
36
+ * statement parses and every offset still maps onto the original text.
37
+ */
38
+ export function placeholderSafeSql(sql) {
39
+ // A NUMERIC filler, not a quoted string: `LIMIT ${top_n}` must stay valid, and
40
+ // `LIMIT 'xxxx'` is a parse error. A number is accepted both there and in a
41
+ // comparison, and type correctness is irrelevant — this copy is only ever
42
+ // parsed, never executed.
43
+ return sql.replace(/\$\{[^}]*\}/g, (match) => '9'.repeat(match.length));
44
+ }
45
+ /**
46
+ * Mask string literals and comments with spaces, preserving offsets so index
47
+ * arithmetic on the masked copy applies to the original text.
48
+ */
49
+ function maskLiteralsPreservingOffsets(sql) {
50
+ let out = '';
51
+ let index = 0;
52
+ while (index < sql.length) {
53
+ const char = sql[index];
54
+ if (char === "'" || char === '"' || char === '`') {
55
+ const quote = char;
56
+ let cursor = index + 1;
57
+ while (cursor < sql.length) {
58
+ if (sql[cursor] === quote) {
59
+ if (sql[cursor + 1] === quote) {
60
+ cursor += 2;
61
+ continue;
62
+ }
63
+ break;
64
+ }
65
+ cursor += 1;
66
+ }
67
+ const end = Math.min(cursor + 1, sql.length);
68
+ out += ' '.repeat(end - index);
69
+ index = end;
70
+ continue;
71
+ }
72
+ if (char === '-' && sql[index + 1] === '-') {
73
+ const end = sql.indexOf('\n', index);
74
+ const stop = end === -1 ? sql.length : end;
75
+ out += ' '.repeat(stop - index);
76
+ index = stop;
77
+ continue;
78
+ }
79
+ if (char === '/' && sql[index + 1] === '*') {
80
+ const end = sql.indexOf('*/', index + 2);
81
+ const stop = end === -1 ? sql.length : end + 2;
82
+ out += ' '.repeat(stop - index);
83
+ index = stop;
84
+ continue;
85
+ }
86
+ out += char;
87
+ index += 1;
88
+ }
89
+ return out;
90
+ }
91
+ /** Index of `keyword` at paren depth 0, or -1. */
92
+ function topLevelKeywordIndex(masked, keyword) {
93
+ const pattern = new RegExp(`\\b${keyword.replace(/\s+/g, '\\s+')}\\b`, 'gi');
94
+ let depth = 0;
95
+ const depths = new Array(masked.length).fill(0);
96
+ for (let index = 0; index < masked.length; index += 1) {
97
+ const char = masked[index];
98
+ if (char === '(')
99
+ depth += 1;
100
+ else if (char === ')')
101
+ depth = Math.max(0, depth - 1);
102
+ depths[index] = depth;
103
+ }
104
+ let match;
105
+ while ((match = pattern.exec(masked)) !== null) {
106
+ if (depths[match.index] === 0)
107
+ return match.index;
108
+ }
109
+ return -1;
110
+ }
111
+ /** Earliest top-level trailing clause, or the end of the statement. */
112
+ function insertionBoundary(masked) {
113
+ let boundary = masked.length;
114
+ for (const clause of TRAILING_CLAUSES) {
115
+ const index = topLevelKeywordIndex(masked, clause);
116
+ if (index >= 0 && index < boundary)
117
+ boundary = index;
118
+ }
119
+ return boundary;
120
+ }
121
+ /**
122
+ * Which result columns may safely become a filter input on this SQL.
123
+ * Returns [] whenever anything is uncertain.
124
+ */
125
+ export function filterableResultColumns(sql, resultColumns, dialect = 'duckdb') {
126
+ const trimmed = sql.trim().replace(/;\s*$/, '');
127
+ if (!trimmed || resultColumns.length === 0)
128
+ return [];
129
+ const analysis = analyzeSqlReferences(placeholderSafeSql(trimmed), dialect);
130
+ if (!analysis.parsed)
131
+ return [];
132
+ const statements = analysis.statementTypes ?? [];
133
+ if (statements.length !== 1 || statements[0]?.toLowerCase() !== 'select')
134
+ return [];
135
+ // A CTE-bearing statement can still be filtered, but only where the outer
136
+ // query is the one being extended; keep that out of scope rather than guess.
137
+ if ((analysis.ctes ?? []).length > 0)
138
+ return [];
139
+ // column name -> the relations it was referenced against
140
+ const relationsByColumn = new Map();
141
+ for (const reference of analysis.columns ?? []) {
142
+ const name = reference.column?.toLowerCase();
143
+ if (!name)
144
+ continue;
145
+ if (!relationsByColumn.has(name))
146
+ relationsByColumn.set(name, new Set());
147
+ if (reference.relation)
148
+ relationsByColumn.get(name).add(reference.relation);
149
+ }
150
+ // Every column consumed by an aggregate is an input to a measure, not a
151
+ // dimension of the output — filtering it in WHERE changes the aggregate.
152
+ const aggregateInputs = new Set((analysis.aggregates ?? []).map((aggregate) => aggregate.column?.toLowerCase()).filter(Boolean));
153
+ const relationToAlias = new Map();
154
+ for (const [alias, relation] of Object.entries(analysis.aliasToRelation ?? {})) {
155
+ if (!relationToAlias.has(relation))
156
+ relationToAlias.set(relation, alias);
157
+ }
158
+ const multiRelation = (analysis.tables ?? []).length > 1;
159
+ const out = [];
160
+ for (const column of resultColumns) {
161
+ const key = column.toLowerCase();
162
+ const relations = relationsByColumn.get(key);
163
+ // Not a source column (so: an aggregate alias or a computed expression).
164
+ if (!relations)
165
+ continue;
166
+ if (aggregateInputs.has(key))
167
+ continue;
168
+ // Ambiguous across joined relations — a bare predicate could mean either.
169
+ if (relations.size > 1)
170
+ continue;
171
+ const relation = [...relations][0];
172
+ const alias = relation ? relationToAlias.get(relation) : undefined;
173
+ if (multiRelation && !alias)
174
+ continue;
175
+ out.push({
176
+ column,
177
+ predicateTarget: multiRelation && alias ? `${alias}.${column}` : column,
178
+ });
179
+ }
180
+ return out;
181
+ }
182
+ /** Render a DQL parameter default for a value of unknown type. */
183
+ function dqlParameterDefault(value) {
184
+ if (typeof value === 'number' && Number.isFinite(value))
185
+ return String(value);
186
+ if (typeof value === 'boolean')
187
+ return String(value);
188
+ return `"${String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
189
+ }
190
+ /**
191
+ * Write the new SQL back into a generated block, and declare the new parameter
192
+ * in `params`, `parameterPolicy`, `allowedFilters`, and `filterBindings`.
193
+ *
194
+ * Targeted edits rather than regenerating the block: the source carries curated
195
+ * metadata (terms, grain, outputs, lineage context) that a rebuild would either
196
+ * lose or re-infer differently.
197
+ */
198
+ export function replaceBlockStudioSql(source, sql, parameterName, value) {
199
+ const escaped = sql.replace(/"""/g, '\\"\\"\\"');
200
+ let out = source.replace(/(query\s*=\s*""")([\s\S]*?)(""")/i, (_match, open, _body, close) => `${open}\n${escaped}\n ${close}`);
201
+ if (out === source)
202
+ throw new Error('This answer has no editable SQL block to update.');
203
+ const declaration = ` ${parameterName} = ${dqlParameterDefault(value)}`;
204
+ out = /\bparams\s*\{/.test(out)
205
+ ? out.replace(/(\bparams\s*\{)/, `$1\n${declaration}`)
206
+ : out.replace(/(\n\s*query\s*=)/, `\n params {\n${declaration}\n }\n$1`);
207
+ out = /\bparameterPolicy\s*\{/.test(out)
208
+ ? out.replace(/(\bparameterPolicy\s*\{)/, `$1\n ${parameterName} = "dynamic"`)
209
+ : out.replace(/(\n\s*params\s*\{)/, `\n parameterPolicy {\n ${parameterName} = "dynamic"\n }$1`);
210
+ out = /\ballowedFilters\s*=\s*\[/.test(out)
211
+ ? out.replace(/(\ballowedFilters\s*=\s*\[)/, `$1"${parameterName}", `)
212
+ : out.replace(/(\n\s*parameterPolicy\s*\{)/, `\n allowedFilters = ["${parameterName}"]$1`);
213
+ return out;
214
+ }
215
+ /** Parameter names must be safe DQL identifiers and must not collide. */
216
+ function uniqueParameterName(column, taken) {
217
+ const base = column.toLowerCase().replace(/[^a-z0-9_]/g, '_').replace(/^_+|_+$/g, '') || 'filter';
218
+ const seeded = /^[a-z]/.test(base) ? base : `f_${base}`;
219
+ if (!taken.has(seeded))
220
+ return seeded;
221
+ let suffix = 2;
222
+ while (taken.has(`${seeded}_${suffix}`))
223
+ suffix += 1;
224
+ return `${seeded}_${suffix}`;
225
+ }
226
+ /**
227
+ * Inject `<column> = ${param}` into the statement's top-level WHERE, adding the
228
+ * clause when there is none. Throws when the column is not offerable — callers
229
+ * should have used {@link filterableResultColumns} first, so a throw here means
230
+ * the artifact and the result disagree.
231
+ */
232
+ export function addSqlResultFilter(sql, resultColumns, column, existingParameterNames = [], dialect = 'duckdb') {
233
+ const candidate = filterableResultColumns(sql, resultColumns, dialect)
234
+ .find((item) => item.column.toLowerCase() === column.toLowerCase());
235
+ if (!candidate) {
236
+ throw new Error(`"${column}" cannot be turned into a filter input on this query.`);
237
+ }
238
+ const trimmed = sql.trim().replace(/;\s*$/, '');
239
+ // Offsets are preserved by both transforms, so positions found here apply
240
+ // directly to `trimmed`.
241
+ const masked = maskLiteralsPreservingOffsets(placeholderSafeSql(trimmed));
242
+ const parameterName = uniqueParameterName(candidate.column, new Set(existingParameterNames));
243
+ const predicate = `${candidate.predicateTarget} = \${${parameterName}}`;
244
+ const whereIndex = topLevelKeywordIndex(masked, 'where');
245
+ const boundary = insertionBoundary(masked);
246
+ const insertAt = whereIndex >= 0 && whereIndex < boundary ? boundary : boundary;
247
+ const clause = whereIndex >= 0 && whereIndex < boundary ? ` AND ${predicate}` : ` WHERE ${predicate}`;
248
+ const head = trimmed.slice(0, insertAt).replace(/\s+$/, '');
249
+ const tail = trimmed.slice(insertAt);
250
+ return {
251
+ sql: `${head}${clause}${tail ? ` ${tail.replace(/^\s+/, '')}` : ''}`,
252
+ parameterName,
253
+ predicateTarget: candidate.predicateTarget,
254
+ };
255
+ }
256
+ //# sourceMappingURL=sql-result-filter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sql-result-filter.js","sourceRoot":"","sources":["../src/sql-result-filter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAEhE,gFAAgF;AAChF,MAAM,gBAAgB,GAAG;IACvB,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,UAAU,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO;CAClF,CAAC;AASF;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,GAAW;IAC5C,+EAA+E;IAC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O;QACL,GAAG,EAAE,GAAG,IAAI,GAAG,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE;QACpE,aAAa;QACb,eAAe,EAAE,SAAS,CAAC,eAAe;KAC3C,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@duckcodeailabs/dql-cli",
3
- "version": "1.12.3",
3
+ "version": "1.12.4",
4
4
  "description": "Public CLI for parsing, formatting, testing, and certifying DQL blocks",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -20,15 +20,15 @@
20
20
  },
21
21
  "dependencies": {
22
22
  "@anthropic-ai/sdk": "^0.104.2",
23
- "@duckcodeailabs/dql-agent": "^1.12.3",
24
- "@duckcodeailabs/dql-compiler": "^1.12.3",
25
- "@duckcodeailabs/dql-connectors": "^1.12.3",
26
- "@duckcodeailabs/dql-core": "^1.12.3",
27
- "@duckcodeailabs/dql-governance": "^1.12.3",
28
- "@duckcodeailabs/dql-mcp": "^1.12.3",
29
- "@duckcodeailabs/dql-notebook": "^1.12.3",
30
- "@duckcodeailabs/dql-project": "^1.12.3",
31
- "@duckcodeailabs/dql-slack": "^1.12.3",
23
+ "@duckcodeailabs/dql-agent": "^1.12.4",
24
+ "@duckcodeailabs/dql-compiler": "^1.12.4",
25
+ "@duckcodeailabs/dql-connectors": "^1.12.4",
26
+ "@duckcodeailabs/dql-core": "^1.12.4",
27
+ "@duckcodeailabs/dql-governance": "^1.12.4",
28
+ "@duckcodeailabs/dql-mcp": "^1.12.4",
29
+ "@duckcodeailabs/dql-notebook": "^1.12.4",
30
+ "@duckcodeailabs/dql-project": "^1.12.4",
31
+ "@duckcodeailabs/dql-slack": "^1.12.4",
32
32
  "isomorphic-git": "^1.27.0",
33
33
  "js-yaml": "^4.1.0",
34
34
  "node-cron": "^3.0.3",
@@ -1,5 +0,0 @@
1
- import{R as O,j as i,aN as We,r as $,u as $t,t as Ct,a as E}from"./index-BMVfPaXr.js";import{C as ce,b as Ke,T as Ze,a as Bt}from"./usePersistedAgentThreadId-hxi1RZDm.js";import{T as At}from"./TrustBadge-DNVJK_mP.js";import{R as zt,G as Tt}from"./AiBuildResult-BvTcW9oE.js";const Lt={value:"Value",block:"Certified block",term:"Business term",metric:"Metric",dimension:"Dimension",model:"dbt model",source:"Source table",consumer:"Used by"};function Oe(e){const t=(e??"").toLowerCase();return t==="certified"?"success":t==="deprecated"?"neutral":t.includes("review")||t==="draft"||t==="pending"?"warning":"neutral"}function Rt({walk:e,defaultOpen:t=!1,triggerLabel:r}){const[n,s]=O.useState(t),o=Math.min(e.steps.length,2),[a,d]=O.useState(o),u=()=>d(o),l=e.steps.slice(0,a),p=e.steps.length-a;return i.jsxs("div",{style:{border:"1px solid var(--border-subtle, rgba(127,127,127,0.25))",borderRadius:8,background:"var(--bg-1, transparent)",overflow:"hidden"},children:[i.jsxs("button",{type:"button","aria-expanded":n,onClick:()=>{s(c=>!c),n&&u()},style:{width:"100%",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,border:0,background:"transparent",color:"var(--text-secondary, inherit)",cursor:"pointer",padding:"8px 11px",font:"inherit",fontSize:12,fontWeight:700},children:[i.jsxs("span",{style:{display:"flex",alignItems:"center",gap:7},children:[i.jsx("span",{"aria-hidden":!0,style:{transform:n?"rotate(90deg)":"none",transition:"transform 120ms",display:"inline-block"},children:"▸"}),r??"Why?"]}),i.jsx("span",{style:{fontSize:11,color:"var(--text-tertiary, inherit)",fontWeight:600},children:n?"Hide derivation":"Show how this was derived"})]}),n&&i.jsxs("div",{style:{padding:"2px 11px 11px",display:"flex",flexDirection:"column",gap:10},children:[i.jsx("div",{style:{fontSize:12.5,lineHeight:1.5,color:"var(--text-primary, inherit)"},children:e.summary}),(e.trustLabel||e.freshness)&&i.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",alignItems:"center"},children:[e.trustLabel&&i.jsx(We,{tone:Oe(e.trustLabel),children:Pe(e.trustLabel)}),e.freshness&&i.jsxs("span",{style:{fontSize:11,color:"var(--text-tertiary, inherit)"},children:["Fresh as of ",Mt(e.freshness)]})]}),i.jsx("ol",{style:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:7},children:l.map((c,f)=>i.jsxs("li",{style:{display:"flex",gap:9,alignItems:"flex-start",paddingLeft:2},children:[i.jsx("span",{"aria-hidden":!0,style:{marginTop:3,width:7,height:7,borderRadius:999,flexShrink:0,background:"var(--accent, currentColor)",opacity:.7}}),i.jsxs("div",{style:{minWidth:0,display:"flex",flexDirection:"column",gap:2},children:[i.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center",flexWrap:"wrap"},children:[i.jsx("span",{style:{fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.04em",color:"var(--text-tertiary, inherit)"},children:Lt[c.kind]}),i.jsx("span",{style:{fontSize:12.5,fontWeight:700,color:"var(--text-primary, inherit)",overflowWrap:"anywhere"},children:c.name}),c.status&&i.jsx(We,{tone:Oe(c.status),children:Pe(c.status)})]}),(c.owner||c.detail)&&i.jsxs("div",{style:{fontSize:11.5,color:"var(--text-secondary, inherit)",lineHeight:1.45},children:[c.owner&&i.jsxs("span",{children:["Owner: ",c.owner,". "]}),c.detail]})]})]},`${c.kind}-${c.name}-${f}`))}),p>0&&i.jsxs("button",{type:"button",onClick:()=>d(c=>Math.min(e.steps.length,c+1)),style:{alignSelf:"flex-start",border:"1px solid var(--border-default, rgba(127,127,127,0.3))",borderRadius:6,background:"transparent",color:"var(--accent, inherit)",cursor:"pointer",padding:"4px 9px",fontSize:11,fontWeight:700},children:["Show next step (",p," more)"]}),e.caveats&&e.caveats.length>0&&i.jsxs("div",{style:{borderLeft:"3px solid var(--status-warning, #d29922)",background:"var(--status-warning-bg, rgba(210,153,34,0.08))",borderRadius:6,padding:"8px 10px",display:"flex",flexDirection:"column",gap:4},children:[i.jsx("span",{style:{fontSize:10,fontWeight:800,textTransform:"uppercase",letterSpacing:"0.04em",color:"var(--status-warning, inherit)"},children:"Caveats"}),e.caveats.map((c,f)=>i.jsx("span",{style:{fontSize:11.5,color:"var(--text-secondary, inherit)",lineHeight:1.45},children:c},f))]})]})]})}function Pe(e){return e.replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function Mt(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleDateString()}const ue=/date|time|day|month|year|week|quarter|period|_at$|^at$/i,fe=/(?:^|_)(?:id|uuid|key|code)$/i,he=/(?:name|title|label|display|description|customer|account|product|region|segment|category|channel)$/i,_t=new Set(["bar","grouped-bar","stacked-bar","line","area","scatter","pie","donut","heatmap","histogram","funnel","sankey","waterfall","gauge","kpi","table"]);function qe(e){return typeof e=="number"?Number.isFinite(e):typeof e=="string"?e.trim()!==""&&Number.isFinite(Number(e)):!1}function et(e){const t=e.rows.slice(0,20);return t.length===0?[]:e.columns.filter(r=>t.some(n=>qe(n[r]))&&t.every(n=>{const s=n[r];return s==null||s===""||qe(s)}))}function Dt(e,t){const r=e.columns.filter(n=>!t.includes(n));return r.find(n=>he.test(n)&&!fe.test(n))??r.find(n=>!fe.test(n))??r[0]??e.columns[0]}function It(e){return e.columns.filter(t=>{if(!fe.test(t))return!1;const r=t.replace(/(?:_)?(?:id|uuid|key|code)$/i,"").replace(/_+$/,"");return e.columns.some(n=>n!==t&&(r.length>0&&n.toLowerCase().startsWith(r.toLowerCase())&&he.test(n)||r.length===0&&he.test(n)))})}function Wt(e,t){if(t.length===0)return e;const r=new Set(t);return{...e,columns:e.columns.filter(n=>!r.has(n)),rows:e.rows.map(n=>Object.fromEntries(Object.entries(n).filter(([s])=>!r.has(s))))}}function tt(e,t){const r=et(e),n=e.rows.length>0,s=e.columns.filter(g=>!r.includes(g));if(!(n&&r.length>=1))return{config:{...t??{},chart:"table",decisionSource:"data",rationale:"The returned rows do not contain a numeric measure to plot."},chartable:!1,reason:"No numeric measure"};const a=Dt(e,r),d=t!=null&&t.x&&e.columns.includes(t.x)?t.x:a,u=t!=null&&t.y&&e.columns.includes(t.y)?t.y:r.find(g=>g!==d)??r[0],l=Pt(e,r,s,d),p=Ot(t==null?void 0:t.chart),c=t==null?void 0:t.decisionSource,f=c==="authored"||c==="user",h=f&&p||p&&qt(p,e,r,s,d,u)?p:l.chart,x=!!(p&&p!==h&&!f),b=t!=null&&t.color&&e.columns.includes(t.color)?t.color:h==="sankey"?s.find(g=>g!==d):t==null?void 0:t.color,S=x?`${l.reason}; replaced the agent suggestion because the returned data is not compatible.`:p&&!f?"Agent-selected visualization validated against the returned data.":l.reason;return{config:{...t??{},chart:h,x:d,y:u,...b?{color:b}:{},decisionSource:f?c:p&&!x?"agent":"data",rationale:S},chartable:h!=="table",reason:S}}function Ot(e){if(typeof e!="string")return;const t=e.toLowerCase().replace(/_/g,"-").replace("single-value","kpi");return _t.has(t)?t:void 0}function Pt(e,t,r,n){return e.rows.length===1&&t.length>=1?{chart:"kpi",reason:"Single returned value"}:ue.test(n)&&t.length>=1?{chart:"line",reason:`Time-like field ${n}`}:r.length>0&&t.length>=2?{chart:"grouped-bar",reason:"One category with multiple numeric measures"}:r.length>0&&t.length===1?{chart:"bar",reason:"Categorical comparison with one numeric measure"}:t.length>=2?{chart:"scatter",reason:"Two continuous numeric measures"}:{chart:"table",reason:"No comparable category or time axis was returned"}}function qt(e,t,r,n,s,o){return e==="table"?!0:e==="kpi"||e==="gauge"?r.length>=1&&t.rows.length===1:e==="line"||e==="area"?r.includes(o)&&ue.test(s):e==="scatter"?r.length>=2:e==="sankey"?n.length>=2&&r.length>=1:e==="histogram"?r.length>=1:e==="grouped-bar"||e==="stacked-bar"?n.length>=1&&r.length>=2:e==="pie"||e==="donut"?n.length>=1&&r.length>=1&&t.rows.length>=2&&t.rows.length<=8:e==="heatmap"?t.columns.length>=3&&r.length>=1:e==="funnel"||e==="waterfall"?n.length>=1&&r.length>=1:e==="bar"?n.length>=1&&r.length>=1&&!ue.test(s):!1}function En({result:e,themeMode:t,t:r,chartConfig:n,embedded:s=!1,tabLabels:o}){const a=e.rows.length===0,[d,u]=$.useState(),[l,p]=$.useState(!1),c=$.useMemo(()=>({...n??{},...d??{}}),[n,d]),{config:f,chartable:h}=tt(e,c),x=$.useMemo(()=>et(e),[e]),b=$.useMemo(()=>It(e),[e]),S=$.useMemo(()=>l?e:Wt(e,b),[b,e,l]),[g,v]=$.useState(h?"chart":"table"),w=m=>({border:"none",background:"transparent",cursor:"pointer",fontFamily:r.font,fontSize:11,fontWeight:700,padding:"2px 4px",color:m?r.accent:r.textMuted,borderBottom:`2px solid ${m?r.accent:"transparent"}`}),L=ce.some(m=>m.value===f.chart)?f.chart:"bar";return i.jsxs("div",{style:{border:s?"none":`1px solid ${r.headerBorder}`,background:r.cellBg,borderRadius:s?0:8,overflow:"hidden"},children:[i.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",padding:s?"9px 14px":"5px 9px",borderBottom:`1px solid ${r.headerBorder}`},children:[s&&h&&i.jsx("button",{type:"button",onClick:()=>v("table"),style:w(g==="table"),children:(o==null?void 0:o.table)??"Table"}),h&&i.jsx("button",{type:"button",onClick:()=>v("chart"),style:w(g==="chart"),children:(o==null?void 0:o.chart)??"Chart"}),!s&&h&&i.jsx("button",{type:"button",onClick:()=>v("table"),style:w(g==="table"),children:(o==null?void 0:o.table)??"Table"}),!h&&!a&&i.jsx("span",{style:{fontSize:11,fontWeight:700,color:r.textMuted},children:(o==null?void 0:o.table)??"Table"}),h&&g==="chart"?i.jsx("select",{value:L,onChange:m=>u(A=>({...A??{},chart:m.target.value,decisionSource:"user",rationale:"Selected manually."})),title:"Chart type",style:{fontFamily:r.font,fontSize:10.5,fontWeight:600,color:r.textSecondary,background:r.cellBg,border:`1px solid ${r.headerBorder}`,borderRadius:5,padding:"1px 4px",cursor:"pointer"},children:ce.map(m=>i.jsx("option",{value:m.value,children:m.label},m.value))}):null,h&&g==="chart"?i.jsxs(i.Fragment,{children:[i.jsxs("label",{style:{display:"inline-flex",alignItems:"center",gap:3,color:r.textMuted,fontSize:10.5},children:["X",i.jsx("select",{"aria-label":"X-axis field",value:f.x??"",onChange:m=>u(A=>({...A??{},x:m.target.value,decisionSource:"user",rationale:"Axis selected manually."})),style:{fontFamily:r.font,fontSize:10.5,color:r.textSecondary,background:r.cellBg,border:`1px solid ${r.headerBorder}`,borderRadius:5,padding:"1px 3px",cursor:"pointer",maxWidth:120},children:e.columns.map(m=>i.jsx("option",{value:m,children:m},m))})]}),x.length>0?i.jsxs("label",{style:{display:"inline-flex",alignItems:"center",gap:3,color:r.textMuted,fontSize:10.5},children:["Y",i.jsx("select",{"aria-label":"Y-axis field",value:f.y??"",onChange:m=>u(A=>({...A??{},y:m.target.value,decisionSource:"user",rationale:"Axis selected manually."})),style:{fontFamily:r.font,fontSize:10.5,color:r.textSecondary,background:r.cellBg,border:`1px solid ${r.headerBorder}`,borderRadius:5,padding:"1px 3px",cursor:"pointer",maxWidth:120},children:x.map(m=>i.jsx("option",{value:m,children:m},m))})]}):null,f.chart==="sankey"?i.jsxs("label",{style:{display:"inline-flex",alignItems:"center",gap:3,color:r.textMuted,fontSize:10.5},children:["Target",i.jsx("select",{"aria-label":"Sankey target field",value:f.color??"",onChange:m=>u(A=>({...A??{},color:m.target.value,decisionSource:"user",rationale:"Sankey target selected manually."})),style:{fontFamily:r.font,fontSize:10.5,color:r.textSecondary,background:r.cellBg,border:`1px solid ${r.headerBorder}`,borderRadius:5,padding:"1px 3px",cursor:"pointer",maxWidth:120},children:e.columns.filter(m=>!x.includes(m)&&m!==f.x).map(m=>i.jsx("option",{value:m,children:m},m))})]}):null]}):null,h&&f.rationale?i.jsxs("span",{title:f.rationale,style:{fontSize:10.5,color:r.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:230},children:["Smart chart · ",f.chart]}):null,i.jsxs("span",{style:{marginLeft:"auto",fontSize:10.5,color:r.textMuted,alignSelf:"center"},children:[e.rowCount??e.rows.length," rows"]})]}),i.jsx("div",{style:{padding:s?12:8,minHeight:h&&g==="chart"?200:void 0,maxHeight:s?380:320,overflow:"auto"},children:a?i.jsxs("div",{style:{padding:"18px 8px",textAlign:"center",color:r.textMuted,fontSize:12},children:["The query ran successfully and matched 0 rows",e.columns.length>0?` (columns: ${e.columns.join(", ")})`:"","."]}):h&&g==="chart"?i.jsx(Ke,{result:e,themeMode:t,chartConfig:f,onConfigChange:m=>u(A=>({...A??{},...m,decisionSource:"user",rationale:"Adjusted manually."}))}):i.jsxs(i.Fragment,{children:[b.length>0?i.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:6},children:i.jsx("button",{type:"button",onClick:()=>p(m=>!m),style:{border:"none",background:"transparent",color:r.accent,cursor:"pointer",fontSize:10.5,padding:0},children:l?"Hide technical fields":"Show IDs"})}):null,i.jsx(Ze,{result:S,themeMode:t})]})})]})}const Ft=3;function Et(e){const{business360:t,block:r,value:n,generated:s=!1}=e,o=e.maxPerKind??Ft,a=t.focus,d=[];n&&d.push({kind:"value",name:n,detail:a.name?`Reported by ${a.name}.`:void 0});const u=(r==null?void 0:r.owner)??a.owner,l=(r==null?void 0:r.status)??a.status,p=(r==null?void 0:r.reviewCadence)??oe(a.metadata,"reviewCadence");d.push({kind:"block",name:a.name,owner:u,status:l,detail:Ht({reviewCadence:p,businessOutcome:(r==null?void 0:r.businessOutcome)??oe(a.metadata,"businessOutcome"),decisionUse:r==null?void 0:r.decisionUse})});const c=Fe([...t.businessDefinition.terms,...t.businessDefinition.definedByTerms]);for(const x of c.slice(0,o))x.id!==a.id&&d.push({kind:"term",name:x.name,owner:x.owner,detail:"Business term this answer is defined in."});for(const x of se(r==null?void 0:r.metricRefs).slice(0,o))d.push({kind:"metric",name:x,detail:"Governed metric used in the calculation."});for(const x of se(r==null?void 0:r.dimensionRefs).slice(0,o))d.push({kind:"dimension",name:x,detail:"Dimension used to slice the value."});for(const x of t.technicalSources.dbtModels.slice(0,o))d.push({kind:"model",name:x.name,detail:"dbt model the certified SQL builds on."});const f=Fe([...t.technicalSources.dbtSources,...t.technicalSources.sourceTables]);for(const x of f.slice(0,o))d.push({kind:"source",name:x.name,detail:"Raw source table the data originates from."});const h=se((r==null?void 0:r.caveats)??Ut(a.metadata,"caveats"));return{value:n,summary:Nt({focus:a,blockOwner:u,reviewCadence:p,generated:s,sourceAssets:f}),steps:d,trustLabel:e.trustLabel??(s?"review_required":void 0),freshness:e.freshness??Qt(r==null?void 0:r.dataState,r==null?void 0:r.dataStateDetail)??oe(a.metadata,"freshness"),caveats:h.length>0?h:void 0}}function Qt(e,t){switch(e){case"failed":return t?`upstream failed — ${t}`:"upstream failed";case"stale":return t?`stale data — ${t}`:"stale data";default:return}}function Ht(e){const t=[];return e.businessOutcome?t.push(e.businessOutcome):e.decisionUse&&t.push(`Supports: ${e.decisionUse}.`),e.reviewCadence&&t.push(`Reviewed ${e.reviewCadence}.`),t.length>0?t.join(" "):void 0}function Nt(e){const t=e.blockOwner?` owned by ${e.blockOwner}`:"",r=e.sourceAssets.length>0?` It traces back to ${e.sourceAssets[0].name}.`:"";if(e.generated)return`This value was generated from ${e.focus.name}${t} and still needs analyst review before it can be certified.${r}`;const n=e.reviewCadence?`, reviewed ${e.reviewCadence}`:"";return`This value comes from the certified ${e.focus.name}${t}${n}.${r}`}function oe(e,t){const r=e==null?void 0:e[t];return typeof r=="string"&&r.trim().length>0?r:void 0}function Ut(e,t){const r=e==null?void 0:e[t];return Array.isArray(r)?r.filter(n=>typeof n=="string"&&n.trim().length>0):[]}function se(e){if(!e)return[];const t=new Set,r=[];for(const n of e){const s=typeof n=="string"?n.trim():"";!s||t.has(s.toLowerCase())||(t.add(s.toLowerCase()),r.push(s))}return r}function Fe(e){const t=new Set,r=[];for(const n of e)t.has(n.id)||(t.add(n.id),r.push(n));return r}function nt(e){var n,s;const t=e.dqlArtifact,r=(n=t==null?void 0:t.source)==null?void 0:n.trim();return r?{source:r,kind:t==null?void 0:t.kind,name:t==null?void 0:t.name,sourcePath:t==null?void 0:t.sourcePath,metrics:le(t==null?void 0:t.metrics),dimensions:le(t==null?void 0:t.dimensions),filters:((t==null?void 0:t.filters)??[]).map(o=>{var l,p;const a=(l=o.dimension)==null?void 0:l.trim(),d=((p=o.operator)==null?void 0:p.trim())||"equals",u=le(o.values);return!a||u.length===0?"":`${a} ${d} ${u.join(", ")}`}).filter(Boolean),timeDimension:(s=t==null?void 0:t.timeDimension)!=null&&s.name?[t.timeDimension.name,t.timeDimension.granularity].filter(Boolean).join(" / "):void 0,orderBy:((t==null?void 0:t.orderBy)??[]).map(o=>{var u,l;const a=(u=o.name)==null?void 0:u.trim(),d=(l=o.direction)==null?void 0:l.trim();return a&&d?`${a} ${d}`:""}).filter(Boolean),limit:typeof(t==null?void 0:t.limit)=="number"&&Number.isFinite(t.limit)?t.limit:void 0}:null}function Vt(e){for(let t=e.length-1;t>=0;t--){const r=e[t];if(r.kind!=="tool_result"||r.id!=="governed_answer")continue;const n=r.output;if(n&&typeof n=="object"&&"kind"in n)return n}return null}function le(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):[]}function Jt(e){const t=e.result;if(!t||!Array.isArray(t.rows))return null;const n=(Array.isArray(t.columns)?t.columns:[]).map(o=>typeof o=="string"?o:o&&typeof o=="object"&&typeof o.name=="string"?String(o.name):String(o)),s=t.rows.filter(o=>!!(o&&typeof o=="object"&&!Array.isArray(o))).map(o=>o);return{columns:n,rows:s,rowCount:typeof t.rowCount=="number"?t.rowCount:s.length,executionTime:t.executionTime}}function Gt(e,t){const r=e&&typeof e=="object"?e:{},n=typeof r.chart=="string"?r.chart:void 0,s=r.decisionSource==="authored"||r.decisionSource==="agent"||r.decisionSource==="data"||r.decisionSource==="user"?r.decisionSource:void 0,o=n||(typeof t.suggestedViz=="string"?t.suggestedViz:void 0),a=o?o.toLowerCase().replace(/_/g,"-")==="single-value"?"kpi":o:void 0;return{...a?{chart:a}:{},...a?{decisionSource:s??(n?"authored":"agent")}:{},...typeof r.rationale=="string"?{rationale:r.rationale}:{},...typeof r.x=="string"?{x:r.x}:{},...typeof r.y=="string"?{y:r.y}:{},...typeof r.color=="string"?{color:r.color}:{},...typeof r.title=="string"?{title:r.title}:{}}}function Xt(e,t){return!t||t.columns.length===0?e:tt(t,e).config}function ae(e){if(typeof e!="string")return;const t=e.replace(/\s+/g," ").trim();if(t)return t.length>180?`${t.slice(0,177)}...`:t}function rt(e){const t=Yt(e,["Answer","Business summary","Summary"]);if(t)return Ee(t,340);const r=/^(?:reuse evidence|certified result preview|result preview|result summary|trust status|next action|recommended action|sql used by block|reusable block sql|proposed sql|sql generated|sql draft|evidence|parameters|lineage|technical lineage)\s*:/i,n=/^(?:SELECT|WITH|FROM|WHERE|GROUP BY|ORDER BY|LIMIT)\b/i,s=[];for(const a of e.split(/\r?\n/)){const d=a.trim();if(!(!d||/^#{1,6}\s*/.test(d)||/^```/.test(d)||/^\|/.test(d))&&!/^outcome\s*:/i.test(d)){if(r.test(d)||n.test(d)){if(s.length>0)break;continue}if(s.push(d),s.length>=5)break}}const o=s.join(" ").replace(/[*_`]+/g,"").replace(/\s+/g," ").trim();return Ee(o,340)}function Yt(e,t){var p,c,f;const r=e.split(/\r?\n/),n=t.map(h=>h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),s=new RegExp(`^\\s*(?:#{1,6}\\s*)?(?:[-*]\\s*)?(?:\\*\\*)?(${n})(?:\\*\\*)?\\s*:\\s*(.*)$`,"i"),o=/^\s*(?:#{1,6}\s*)?(?:[-*]\s*)?(?:\*\*)?[A-Z][A-Za-z /-]{2,42}(?:\*\*)?\s*:/,a=r.findIndex(h=>s.test(h));if(a<0)return;const d=((f=(c=(p=r[a])==null?void 0:p.match(s))==null?void 0:c[2])==null?void 0:f.trim())??"",u=d?[d]:[];for(let h=a+1;h<r.length;h+=1){const x=r[h]??"";if(o.test(x)||/^\s*```/.test(x))break;x.trim()&&u.push(x.trim())}return u.join(" ").replace(/[*_`]+/g,"").replace(/\s+/g," ").trim()||void 0}function Ee(e,t){const r=e.replace(/\s+/g," ").trim();if(r.length<=t)return r;const n=r.slice(0,t-1),s=Math.max(n.lastIndexOf(". "),n.lastIndexOf("; "));if(s>100)return n.slice(0,s+1).trim();const o=n.lastIndexOf(" ");return`${n.slice(0,o>80?o:n.length).trim()}...`}function Kt({answer:e,themeMode:t,showSql:r=!0,compact:n=!1,addToAppTarget:s,sourceQuestion:o,onInvestigate:a,onInsertSql:d,onCreateBlock:u}){var we,ke,$e,Ce,Be,Ae,ze,Te,Le,Re,Me,_e,De;const l=Ct[t],{dispatch:p}=$t(),c=Jt(e),f=Gt((we=e.result)==null?void 0:we.chartConfig,e),[h,x]=$.useState(),b=Xt({...f??{},...h??{}},c),S=!!(c&&Bt(c,b)!=="table"),g=e.analysisPlan??((ke=e.evidence)==null?void 0:ke.analysisPlan),v=r?e.sql??(($e=e.result)==null?void 0:$e.sql)??e.proposedSql??(g==null?void 0:g.sql):void 0,w=nt(e),L=e.executionError??(((Be=(Ce=e.evidence)==null?void 0:Ce.execution)==null?void 0:Be.status)==="failed"?e.evidence.execution.message:void 0),m=((Ae=e.result)==null?void 0:Ae.blockPath)??((ze=e.block)==null?void 0:ze.sourcePath),A=!!(v||L||r&&m),ee=!!e.evidence,[U,pe]=$.useState("answer"),[ct,xe]=$.useState(!1),[ge,ut]=$.useState(!1),me=dt(e),ye=An(me,l),be=(e.answer??e.text??"").replace(/\n\n_Question:_[\s\S]*$/m,"").trim(),M=n?rt(be):be,k=((Te=e.result)==null?void 0:Te.blockName)??((Le=e.block)==null?void 0:Le.name)??((Me=(Re=e.citations)==null?void 0:Re.find(y=>y.kind==="block"))==null?void 0:Me.name),te=Rn(e,k),ft=zn(e,c,k,m),[ht,ve]=$.useState(!1),[V,J]=$.useState(null),[je,pt]=$.useState(null),xt=!!(s&&(c||v||M||k)),gt=!!(d&&v),mt=!!(u&&v),P=ae(g==null?void 0:g.question)??ae(o)??ae(M)??"Investigate this answer",yt=!!(a&&P),bt=it(e,{sql:v,executionError:L,blockName:k,result:c}),vt=()=>{!d||!v||(d(v,k??(g==null?void 0:g.question)??"AI SQL preview",{question:o??(g==null?void 0:g.question)}),pt("Inserted SQL preview cell for review."))},jt=()=>{!u||!v||u(v,{title:(w==null?void 0:w.name)??k??(g==null?void 0:g.question)??"AI DQL draft",description:M||(g==null?void 0:g.routeReason)||"AI generated DQL draft.",tags:["ai-generated","review-required"]})},St=async(y="auto")=>{if(!s)return;const W=y==="both"?["chart","data"]:y==="data"?["data"]:y==="chart"?["chart"]:c?[S?"chart":"data"]:[];ve(!0),xe(!1),J(null);try{if(e.certification==="certified"&&k){const B=await E.getDashboard(s.appId,s.dashboardId);if(!B)throw new Error("Dashboard could not be loaded.");const _=[...B.dashboard.layout.items],R=W.length>0?W:["chart"];for(const F of R){const X=R.length>1?`${k}_${F}`:k,Ie={...B.dashboard,layout:{...B.dashboard.layout,items:_}},kt=Dn(Ie,X);_.push({i:kt,..._n(Ie),block:{blockId:k},viz:{type:F==="data"?"table":In(b==null?void 0:b.chart)},title:R.length>1?`${k} ${F==="data"?"data":"chart"}`:k})}const q={...B.dashboard.layout,items:_},T=await E.patchDashboardLayout(s.appId,s.dashboardId,q);if(!T.ok)throw new Error(T.error);J(R.length>1?"Added certified chart and data tiles.":"Added certified block tile.")}else{const B=!!(v&&window.confirm("Keep this AI result refreshed daily?")),_=k??(M.slice(0,60)||"AI result"),R=W.length>0?W:["data"];let q=c??void 0;if(!q&&v){const T=await E.previewGeneratedSql(v);if(!T.ok)throw new Error(`SQL preview failed: ${T.error}`);q=T.result}for(const T of R){const F=T==="data"?{...b??{},chart:"table",title:`${_} data`}:b,X=await E.createAiPin(s.appId,{dashboardId:s.dashboardId,title:R.length>1?`${_} ${T==="data"?"data":"chart"}`:_,answer:M||e.answer||e.text||"AI generated answer",question:g==null?void 0:g.question,sql:v,sourceTier:e.sourceTier,certification:e.certification==="certified"?"certified":"ai_generated",reviewStatus:"needs_review",refreshCadence:B?"daily":"none",chartConfig:F,result:q,citations:e.citations,analysisPlan:g,evidence:e.evidence,followUps:g==null?void 0:g.followUps});if(!X.ok)throw new Error(X.error)}J(R.length>1?"Pinned chart and data tiles for review.":"Pinned AI result for review.")}window.dispatchEvent(new CustomEvent("dql-app-dashboard-updated",{detail:s}))}catch(B){J(B instanceof Error?B.message:String(B))}finally{ve(!1)}},wt=()=>{!a||!P||a({question:P,title:te?`${te}: ${P}`:P,answerSummary:M,blockName:te,sql:v,evidence:e.evidence})},ne=[{id:"answer",label:n?"Summary":"Answer",visible:!0},{id:"dql",label:"DQL",visible:!!w},{id:"visual",label:n?"Chart":"Visualization",visible:S},{id:"data",label:"Data",visible:!!c},{id:"sql",label:"SQL / Block",visible:r&&A},{id:"lineage",label:n?"Trace":"Lineage",visible:ee},{id:"context",label:n?"Context":"Business Context",visible:ee},{id:"review",label:n?"Trust":"Review",visible:ee||!!((_e=e.citations)!=null&&_e.length)}].filter(y=>y.visible),Se=ne.some(y=>y.id===U)?U:"answer",G=ne.filter(y=>y.id!=="answer"),re=G.some(y=>y.id===U)?U:(De=G[0])==null?void 0:De.id,ie=y=>y==="answer"?i.jsx(rn,{summary:M,answer:e,blockName:k,evidence:e.evidence,analysisPlan:g,result:c,sourceTier:e.sourceTier,compact:n,t:l}):y==="dql"&&w?i.jsx(jn,{artifact:w,t:l}):y==="visual"&&c&&S?i.jsxs("div",{style:{padding:n?"8px 10px":"10px 12px",minHeight:n?180:220,display:"grid",gap:10},children:[i.jsx(kn,{result:c,chartConfig:b,t:l,onChange:W=>x(B=>({...B??{},...W,decisionSource:"user",rationale:"Adjusted manually."}))}),i.jsx(Ke,{result:c,themeMode:t,chartConfig:b})]}):y==="data"&&c?i.jsx("div",{style:{maxHeight:n?320:420,overflow:"auto"},children:i.jsx(Ze,{result:c,themeMode:t})}):y==="lineage"?i.jsx(yn,{evidence:e.evidence,t:l}):y==="context"?i.jsx(bn,{evidence:e.evidence,t:l}):y==="sql"&&r&&A?i.jsx(Sn,{sql:v,blockPath:m,executionError:L,t:l}):y==="review"?i.jsx(vn,{answer:e,t:l}):null;return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:n?8:10,whiteSpace:"normal"},children:[i.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[i.jsx(At,{state:me}),i.jsx(zt,{t:l,route:e.route}),I(e.cascade)&&i.jsx("span",{style:{border:`1px solid ${l.cellBorder}`,borderRadius:999,padding:"3px 8px",fontSize:11,fontWeight:700,color:l.textSecondary,background:l.tableHeaderBg},children:I(e.cascade)}),!n&&k&&i.jsxs("span",{style:{fontSize:12,fontFamily:l.fontMono,color:l.textSecondary},children:["block: ",k]}),c&&i.jsxs("span",{style:{fontSize:12,color:l.textMuted},children:[(c.rowCount??c.rows.length).toLocaleString()," rows",c.executionTime!==void 0&&i.jsxs(i.Fragment,{children:[" - ",Math.round(c.executionTime),"ms"]})]}),xt&&i.jsx($n,{t:l,adding:ht,hasResult:!!c,hasChart:S,fallbackLabel:e.certification==="certified"&&k?n?"Add":"Add block":"Pin answer",open:ct,onToggle:()=>xe(y=>!y),onAdd:y=>void St(y)}),yt&&i.jsx("button",{type:"button",onClick:wt,style:{border:`1px solid ${l.accent}`,borderRadius:6,background:`${l.accent}12`,color:l.accent,cursor:"pointer",padding:n?"4px 8px":"5px 10px",fontSize:11,fontFamily:l.font,fontWeight:800},children:n?"Investigate":"Investigate deeper"}),mt&&i.jsx("button",{type:"button",onClick:jt,style:{border:`1px solid ${l.accent}`,borderRadius:6,background:l.cellBg,color:l.accent,cursor:"pointer",padding:n?"4px 8px":"5px 10px",fontSize:11,fontFamily:l.font,fontWeight:700},children:n?"DQL draft":w?"Review DQL draft":"Create DQL draft"}),gt&&i.jsx("button",{type:"button",onClick:vt,style:{border:`1px solid ${l.accent}`,borderRadius:6,background:`${l.accent}18`,color:l.accent,cursor:"pointer",padding:n?"4px 8px":"5px 10px",fontSize:11,fontFamily:l.font,fontWeight:700},children:n?"SQL preview":"Insert SQL preview"})]}),V&&i.jsx("div",{style:{fontSize:11,color:V.toLowerCase().includes("added")||V.toLowerCase().includes("pinned")?"#3fb950":"#ff7b72"},children:V}),je&&i.jsx("div",{style:{fontSize:11,color:"#3fb950"},children:je}),i.jsx(Zt,{outcome:bt,t:l,compact:n}),i.jsxs("div",{style:{border:`1px solid ${l.cellBorder}`,borderTop:`2px solid ${ye}`,borderRadius:n?10:6,overflow:"hidden",background:l.cellBg},children:[!n&&i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"4px 10px",borderBottom:`1px solid ${l.cellBorder}`,background:`${l.tableHeaderBg}70`,flexWrap:"wrap"},children:[ne.map(y=>i.jsx(Xe,{active:Se===y.id,label:y.label,onClick:()=>pe(y.id),t:l},y.id)),!r&&m&&i.jsx("span",{style:{marginLeft:"auto",minWidth:0,fontSize:11,fontFamily:l.fontMono,color:l.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m})]}),ie(n?"answer":Se),n&&G.length>0&&i.jsxs("div",{style:{borderTop:`1px solid ${l.cellBorder}`,background:`${l.tableHeaderBg}45`},children:[i.jsxs("button",{type:"button",onClick:()=>ut(y=>!y),style:{width:"100%",border:0,background:"transparent",color:l.textSecondary,padding:"8px 12px",display:"flex",justifyContent:"space-between",alignItems:"center",cursor:"pointer",fontSize:11,fontWeight:800},children:[i.jsx("span",{children:"Details"}),i.jsx("span",{style:{color:l.textMuted,fontFamily:l.fontMono},children:ge?"hide":"show evidence"})]}),ge&&i.jsxs("div",{style:{borderTop:`1px solid ${l.cellBorder}`},children:[i.jsx("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"4px 12px",flexWrap:"wrap"},children:G.map(y=>i.jsx(Xe,{active:re===y.id,label:y.label,onClick:()=>pe(y.id),t:l},y.id))}),re?ie(re):null]})]}),i.jsx(wn,{items:ft,t:l,accent:ye}),i.jsx(Tt,{t:l,skills:e.appliedSkills,onOpenSkills:()=>p({type:"SET_MAIN_VIEW",view:"skills"})})]})]})}function it(e,t){var r,n,s,o,a;if(e.kind==="no_answer")return{kind:"cannot_answer",label:"Cannot answer yet",detail:"The assistant did not find enough trusted context to safely answer or generate SQL.",nextAction:"Clarify the business object, metric, grain, or source table.",tone:"error"};if(e.certification==="certified"||e.kind==="certified"){const d=t.blockName??e.sourceCertifiedBlock??((r=e.block)==null?void 0:r.name);return{kind:"reuse_certified_block",label:"Reuse certified block",detail:d?`Existing DQL block ${d} answers this request.`:"A certified DQL artifact answers this request.",nextAction:"Use the certified block instead of creating duplicate SQL.",tone:"success"}}return t.executionError||e.executionError?{kind:"fix_sql",label:"Fix SQL",detail:"The generated or selected SQL needs correction before it can become reusable DQL.",nextAction:"Ask AI to repair, edit manually, then rerun preview.",tone:"error"}:(n=e.draftBlock)!=null&&n.path||e.draftBlockId?{kind:"use_existing_draft",label:"Use existing draft",detail:`A review-required DQL draft is available at ${((s=e.draftBlock)==null?void 0:s.path)??e.draftBlockId}.`,nextAction:"Open the draft, review metadata/tests/lineage, then certify manually.",tone:"accent"}:(a=(o=e.dqlArtifact)==null?void 0:o.source)!=null&&a.trim()?{kind:"create_dql_draft",label:"Review DQL draft",detail:"A review-required DQL artifact is available for analyst review.",nextAction:"Review DQL metadata, query logic, lineage, and result preview before certification.",tone:"warning"}:t.sql?{kind:t.result?"generate_sql_cell":"create_dql_draft",label:t.result?"Review SQL preview":"Create DQL draft",detail:t.result?`Review-required SQL preview returned ${(t.result.rowCount??t.result.rows.length).toLocaleString()} row${(t.result.rowCount??t.result.rows.length)===1?"":"s"}.`:"Review-required SQL is available but still needs preview and DQL metadata review.",nextAction:t.result?"Create a DQL draft after reviewing parameters and lineage; insert SQL only as a notebook preview.":"Run preview, inspect parameters, then create a draft block.",tone:"warning"}:{kind:"needs_review",label:"Needs review",detail:"The assistant returned business context but no executable certified answer or SQL draft.",nextAction:"Review evidence and ask for a specific SQL, reuse, or DQL draft action.",tone:"muted"}}function Zt({outcome:e,t,compact:r}){const n=en(e.tone,t);return i.jsxs("div",{style:{border:`1px solid ${n}45`,borderLeft:`3px solid ${n}`,borderRadius:r?10:7,background:`${n}10`,padding:r?"9px 10px":"10px 12px",display:"grid",gap:r?4:5},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,minWidth:0},children:[i.jsx("span",{style:{border:`1px solid ${n}55`,background:`${n}14`,color:n,borderRadius:999,padding:"2px 7px",fontSize:10,fontWeight:850,lineHeight:1.1,textTransform:"uppercase",letterSpacing:0,flexShrink:0},children:e.label}),i.jsx("span",{style:{fontSize:r?12:12.5,color:t.textPrimary,fontWeight:750,overflow:"hidden",textOverflow:"ellipsis"},children:e.detail})]}),i.jsxs("div",{style:{fontSize:r?11.5:12,color:t.textSecondary,lineHeight:1.45},children:["Next: ",e.nextAction]})]})}function en(e,t){switch(e){case"success":return t.success;case"accent":return t.accent;case"warning":return t.warning;case"error":return t.error;case"muted":default:return t.textMuted}}function tn({answer:e,blockName:t}){const[r,n]=$.useState(null),[s,o]=$.useState(!1),[a,d]=$.useState(!1),u=O.useCallback(async()=>{var l,p;if(!a){d(!0),o(!0);try{const c=await E.fetchBusiness360(t);if(!c){n(null);return}const f=(l=e.evidence)==null?void 0:l.outcome,h=Qe(e,"metric"),x=Qe(e,"dimension"),b=e.certification!=="certified"&&e.kind!=="certified",S=Et({business360:c,block:{name:t,owner:f==null?void 0:f.owner,status:((p=e.block)==null?void 0:p.status)??e.certification,reviewCadence:f==null?void 0:f.reviewCadence,caveats:f==null?void 0:f.caveats,decisionUse:f==null?void 0:f.decisionUse,metricRefs:h,dimensionRefs:x},value:nn(e),generated:b,trustLabel:e.trustLabel});n(S)}catch{n(null)}finally{o(!1)}}},[e,t,a]);return a?s?i.jsx("div",{style:{fontSize:11.5,color:"var(--text-tertiary, inherit)"},children:"Assembling derivation…"}):r?i.jsx(Rt,{walk:r,defaultOpen:!0}):null:i.jsx("button",{type:"button",onClick:()=>void u(),"aria-expanded":!1,style:{alignSelf:"flex-start",border:0,background:"transparent",color:"var(--accent, inherit)",cursor:"pointer",padding:"4px 0",fontSize:12,fontWeight:700,textDecoration:"underline",textUnderlineOffset:3},children:"Why? Show how this was derived"})}function Qe(e,t){var s,o;const r=(((s=e.evidence)==null?void 0:s.semanticObjects)??[]).filter(a=>a.kind===t).map(a=>a.name).filter(a=>!!a);if(r.length>0)return r;const n=e.analysisPlan??((o=e.evidence)==null?void 0:o.analysisPlan);return(t==="metric"?n==null?void 0:n.measures:n==null?void 0:n.dimensions)??[]}function nn(e){const t=e.result;if(t&&Array.isArray(t.rows)&&t.rows.length===1){const r=t.rows[0];if(r&&typeof r=="object"&&!Array.isArray(r)){const n=Object.values(r);if(n.length===1&&(typeof n[0]=="number"||typeof n[0]=="string"))return String(n[0])}}}function rn({summary:e,answer:t,blockName:r,evidence:n,analysisPlan:s,result:o,sourceTier:a,compact:d,t:u}){var p,c,f,h,x,b,S,g,v;const l=(p=s==null?void 0:s.followUps)==null?void 0:p[0];return i.jsxs("div",{style:{padding:d?14:12,display:"flex",flexDirection:"column",gap:d?10:12},children:[e?i.jsx(ot,{text:e,t:u,compact:d,summaryOnly:d}):i.jsx("div",{style:{fontSize:12,color:u.textMuted},children:"No summary text was returned."}),t&&r&&i.jsx(tn,{answer:t,blockName:r}),d?i.jsx("div",{style:{fontSize:11.5,color:u.textMuted,display:"flex",flexWrap:"wrap",gap:6,alignItems:"center"},children:[a?Bn(a):null,o?`${(o.rowCount??o.rows.length).toLocaleString()} rows`:null,((c=n==null?void 0:n.validation)==null?void 0:c.status)==="failed"?"needs review":null,((f=n==null?void 0:n.execution)==null?void 0:f.status)==="failed"?"data check failed":null].filter(Boolean).map((w,L)=>i.jsxs(O.Fragment,{children:[L>0&&i.jsx("span",{style:{color:u.cellBorder},children:"·"}),i.jsx("span",{children:w})]},`${w}-${L}`))}):i.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[a&&i.jsx(z,{label:C(a),t:u}),o&&i.jsx(z,{label:`${(o.rowCount??o.rows.length).toLocaleString()} rows`,t:u}),((h=n==null?void 0:n.validation)==null?void 0:h.status)&&i.jsx(z,{label:`validation: ${n.validation.status}`,t:u}),((x=n==null?void 0:n.execution)==null?void 0:x.status)&&i.jsx(z,{label:`execution: ${n.execution.status}`,t:u})]}),o&&!d&&i.jsx(mn,{result:o,t:u,compact:d}),s&&!d&&i.jsxs("div",{style:{display:"grid",gap:7,padding:d?"9px 10px":10,border:`1px solid ${u.cellBorder}`,borderRadius:8,background:`${u.tableHeaderBg}45`},children:[s.routeReason&&i.jsx("div",{style:{fontSize:d?12.5:12,lineHeight:1.45,color:u.textSecondary},children:s.routeReason}),(s.grain||((b=s.measures)==null?void 0:b.length)||((S=s.dimensions)==null?void 0:S.length))&&i.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[s.grain&&i.jsx(z,{label:`grain: ${s.grain}`,t:u}),(g=s.measures)==null?void 0:g.slice(0,2).map(w=>i.jsx(z,{label:w,t:u},`measure-${w}`)),(v=s.dimensions)==null?void 0:v.slice(0,2).map(w=>i.jsx(z,{label:w,t:u},`dimension-${w}`))]}),s.candidateJoins&&s.candidateJoins.length>0&&i.jsxs("div",{style:{fontSize:12,color:u.textMuted},children:["Join: ",i.jsx("span",{style:{color:u.textSecondary},children:at(s.candidateJoins[0])})]}),l&&i.jsxs("div",{style:{fontSize:12,color:u.textMuted},children:["Next: ",i.jsx("span",{style:{color:u.textSecondary},children:l})]})]})]})}function ot({text:e,t,compact:r=!1,summaryOnly:n=!1}){const s=n?rt(e):e,o=on(s,t,r);return i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:r?7:8,color:t.textPrimary,fontFamily:t.font,overflowWrap:"anywhere"},children:o})}function on(e,t,r){var d;const n=sn(e).split(`
2
- `),s=[];let o=0,a=0;for(;o<n.length;){const l=n[o].trim();if(!l){o+=1;continue}if(l.startsWith("```")){const h=l.replace(/^```/,"").trim(),x=[];for(o+=1;o<n.length&&!n[o].trim().startsWith("```");)x.push(n[o]),o+=1;o<n.length&&(o+=1),s.push(i.jsx("pre",{style:gn(t,r),"aria-label":h?`${h} code`:"code",children:x.join(`
3
- `)},`code-${a++}`));continue}const p=l.match(/^(#{1,4})\s+(.+)$/);if(p){const h=p[1].length;s.push(i.jsx("div",{style:fn(t,r,h),children:D(p[2],t)},`heading-${a++}`)),o+=1;continue}if(/^[-*_]{3,}$/.test(l)){s.push(i.jsx("hr",{style:{width:"100%",border:0,borderTop:`1px solid ${t.cellBorder}`,margin:r?"2px 0":"4px 0"}},`hr-${a++}`)),o+=1;continue}if(ln(n,o)){const h=[];for(;o<n.length&&Z(n[o].trim());)h.push(n[o].trim()),o+=1;s.push(i.jsx(dn,{lines:h,t,compact:r},`table-${a++}`));continue}if(l.startsWith(">")){const h=[];for(;o<n.length&&n[o].trim().startsWith(">");)h.push(n[o].trim().replace(/^>\s?/,"")),o+=1;s.push(i.jsx("div",{style:Ne(t,r),children:D(h.join(" "),t)},`quote-${a++}`));continue}if(/^[-*+]\s+/.test(l)){const h=[];for(;o<n.length&&/^[-*+]\s+/.test(n[o].trim());)h.push(n[o].trim().replace(/^[-*+]\s+/,"")),o+=1;s.push(i.jsx("ul",{style:Ue(t,r),children:h.map((x,b)=>i.jsx("li",{style:Ve(t,r),children:D(x,t)},`${x}-${b}`))},`ul-${a++}`));continue}if(/^\d+\.\s+/.test(l)){const h=[];for(;o<n.length&&/^\d+\.\s+/.test(n[o].trim());)h.push(n[o].trim().replace(/^\d+\.\s+/,"")),o+=1;s.push(i.jsx("ol",{style:Ue(t,r),children:h.map((x,b)=>i.jsx("li",{style:Ve(t,r),children:D(x,t)},`${x}-${b}`))},`ol-${a++}`));continue}const c=[];for(;o<n.length;){const h=n[o].trim();if(!h||He(h)&&c.length>0||(c.push(h),o+=1,He(((d=n[o])==null?void 0:d.trim())??"")))break}const f=c.join(" ");s.push(i.jsx("div",{style:s.length===0&&cn(f)?Ne(t,r):un(t,r),children:D(f,t)},`p-${a++}`))}return s}function sn(e){return e.replace(/\r\n/g,`
4
- `).replace(/\|\s+\|(?=[^\n]*\|)/g,`|
5
- |`)}function He(e){return!!(e.startsWith("```")||/^(#{1,4})\s+/.test(e)||/^[-*_]{3,}$/.test(e)||Z(e)||e.startsWith(">")||/^[-*+]\s+/.test(e)||/^\d+\.\s+/.test(e))}function ln(e,t){var s,o;const r=((s=e[t])==null?void 0:s.trim())??"",n=((o=e[t+1])==null?void 0:o.trim())??"";return Z(r)&&an(n)}function Z(e){return e.startsWith("|")&&e.endsWith("|")&&H(e).length>=2}function an(e){if(!Z(e))return!1;const t=H(e);return t.length>=2&&t.every(r=>/^:?-{3,}:?$/.test(r.replace(/\s+/g,"")))}function H(e){return e.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(t=>t.trim())}function dn({lines:e,t,compact:r}){const n=H(e[0]??""),s=H(e[1]??""),o=e.slice(2).map(H).filter(l=>l.length>0),a=Math.max(n.length,...o.map(l=>l.length),0);if(a===0)return null;const d=Array.from({length:a},(l,p)=>{var f;const c=((f=s[p])==null?void 0:f.replace(/\s+/g,""))??"";return c.startsWith(":")&&c.endsWith(":")?"center":c.endsWith(":")?"right":"left"}),u=Array.from({length:a},(l,p)=>n[p]??"");return i.jsx("div",{style:hn(t),children:i.jsxs("table",{style:pn(t,r),children:[i.jsx("thead",{children:i.jsx("tr",{children:u.map((l,p)=>i.jsx("th",{style:Je(t,r,!0,d[p]),children:D(l,t)},`h-${p}`))})}),i.jsx("tbody",{children:o.map((l,p)=>i.jsx("tr",{children:Array.from({length:a},(c,f)=>i.jsx("td",{style:Je(t,r,!1,d[f]),children:D(l[f]??"",t)},`c-${p}-${f}`))},`r-${p}`))})]})})}function cn(e){return/\b(certified|uncertified|review[- ]required|draft|trusted|trust)\b/i.test(e)}function D(e,t){const r=[];let n=e,s=0;for(;n.length>0;){const o=n.match(/\*{3}(.+?)\*{3}/),a=n.match(/\*{2}(.+?)\*{2}/),d=n.match(/`([^`]+?)`/),u=n.match(/\[([^\]]+?)\]\((https?:\/\/[^)\s]+|\/[^)\s]+|#[^)\s]+)\)/),l=n.match(/\*([^\s*](?:.*?[^\s*])?)\*/),p=[o?{match:o,type:"boldItalic"}:null,a?{match:a,type:"bold"}:null,d?{match:d,type:"code"}:null,u?{match:u,type:"link"}:null,l?{match:l,type:"italic"}:null].filter(Boolean);if(p.length===0){r.push(i.jsx(O.Fragment,{children:n},`plain-${s++}`));break}const c=p.reduce((h,x)=>(h.match.index??0)<=(x.match.index??0)?h:x),f=c.match.index??0;f>0&&r.push(i.jsx(O.Fragment,{children:n.slice(0,f)},`plain-${s++}`)),c.type==="boldItalic"?r.push(i.jsx("strong",{style:{fontStyle:"italic",color:t.textPrimary},children:c.match[1]},`bi-${s++}`)):c.type==="bold"?r.push(i.jsx("strong",{style:{color:t.textPrimary},children:c.match[1]},`b-${s++}`)):c.type==="italic"?r.push(i.jsx("em",{children:c.match[1]},`i-${s++}`)):c.type==="code"?r.push(i.jsx("code",{style:xn(t),children:c.match[1]},`code-${s++}`)):c.type==="link"&&r.push(i.jsx("a",{href:c.match[2],target:"_blank",rel:"noopener noreferrer",style:{color:t.accent,textDecoration:"underline"},children:c.match[1]},`link-${s++}`)),n=n.slice(f+c.match[0].length)}return i.jsx(i.Fragment,{children:r})}function un(e,t){return{color:e.textPrimary,fontSize:13,lineHeight:t?1.55:1.6}}function fn(e,t,r){return{color:e.textPrimary,fontSize:t?13:Math.max(13,15-r),fontWeight:800,lineHeight:1.35,marginTop:r<=2?2:0}}function Ne(e,t){return{color:e.textPrimary,fontSize:12.5,lineHeight:1.5,padding:t?"8px 9px":"9px 10px",border:`1px solid ${e.cellBorder}`,borderLeft:`3px solid ${e.accent}`,borderRadius:6,background:`${e.tableHeaderBg}55`}}function Ue(e,t){return{margin:0,paddingLeft:t?18:20,color:e.textPrimary,display:"grid",gap:t?4:5}}function Ve(e,t){return{color:e.textPrimary,fontSize:13,lineHeight:1.5,paddingLeft:2}}function hn(e){return{width:"100%",maxWidth:"100%",overflowX:"auto",border:`1px solid ${e.cellBorder}`,borderRadius:8,background:e.editorBg}}function pn(e,t){return{width:"100%",minWidth:t?360:420,borderCollapse:"collapse",color:e.textPrimary,fontSize:t?12:12.5,lineHeight:1.45}}function Je(e,t,r,n){return{padding:t?"6px 8px":"7px 9px",borderBottom:`1px solid ${e.cellBorder}`,color:r?e.textMuted:e.textPrimary,background:r?`${e.tableHeaderBg}75`:void 0,fontFamily:r?e.fontMono:e.font,fontSize:r?t?10.5:11:void 0,fontWeight:r?800:500,textAlign:n,whiteSpace:"nowrap",verticalAlign:"top"}}function xn(e){return{background:e.editorBg,border:`1px solid ${e.cellBorder}`,borderRadius:4,color:e.accent,fontFamily:e.fontMono,fontSize:"0.92em",padding:"1px 4px"}}function gn(e,t){return{margin:0,padding:t?9:10,overflow:"auto",maxHeight:t?220:280,borderRadius:6,background:e.editorBg,color:e.textPrimary,border:`1px solid ${e.cellBorder}`,fontSize:t?11.5:12,fontFamily:e.fontMono,lineHeight:1.5,whiteSpace:"pre"}}function mn({result:e,t,compact:r}){const n=(e.columns.length>0?e.columns:Object.keys(e.rows[0]??{})).slice(0,r?3:4),s=e.rows.slice(0,r?4:5);return n.length===0||s.length===0?null:i.jsxs("div",{style:{border:`1px solid ${t.cellBorder}`,borderRadius:8,overflow:"hidden",background:t.editorBg},children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:10,padding:"7px 9px",borderBottom:`1px solid ${t.cellBorder}`,color:t.textMuted,fontSize:11,fontFamily:t.fontMono,textTransform:"uppercase",letterSpacing:"0.06em"},children:[i.jsx("span",{children:"Preview"}),i.jsxs("span",{children:[s.length," of ",(e.rowCount??e.rows.length).toLocaleString()," rows"]})]}),i.jsx("div",{style:{overflowX:"auto"},children:i.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",tableLayout:"fixed"},children:[i.jsx("thead",{children:i.jsx("tr",{children:n.map(o=>i.jsx("th",{style:{textAlign:"left",padding:"7px 9px",color:t.textMuted,fontSize:11,fontFamily:t.fontMono,borderBottom:`1px solid ${t.cellBorder}`,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:C(o)},o))})}),i.jsx("tbody",{children:s.map((o,a)=>i.jsx("tr",{children:n.map(d=>i.jsx("td",{style:{padding:"7px 9px",color:t.textPrimary,fontSize:r?12:12.5,borderBottom:a<s.length-1?`1px solid ${t.cellBorder}`:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:Cn(o[d])},`${a}-${d}`))},a))})]})})]})}function yn({evidence:e,t}){const r=(e==null?void 0:e.lineage)??[];return r.length===0?i.jsx(lt,{t,children:"No lineage evidence was returned for this answer."}):i.jsx("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:10},children:r.map((n,s)=>i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"20px 1fr",gap:8},children:[i.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center"},children:[i.jsx("div",{style:{width:8,height:8,borderRadius:8,marginTop:5,background:n.role==="question"?t.accent:t.textMuted}}),s<r.length-1&&i.jsx("div",{style:{width:1,flex:1,minHeight:18,background:t.cellBorder}})]}),i.jsxs("div",{style:{minWidth:0},children:[i.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center",flexWrap:"wrap"},children:[i.jsx("span",{style:{fontSize:12,fontWeight:700,color:t.textPrimary},children:n.name??n.nodeId}),n.role&&i.jsx(z,{label:C(n.role),t}),n.kind&&i.jsx(z,{label:C(n.kind),t})]}),n.description&&i.jsx("div",{style:{fontSize:12,color:t.textSecondary,marginTop:3},children:n.description}),(n.sourcePath||n.provenance)&&i.jsxs("div",{style:{fontSize:11,color:t.textMuted,fontFamily:t.fontMono,marginTop:3,overflow:"hidden",textOverflow:"ellipsis"},children:[n.provenance??n.sourcePath,n.sourcePath&&n.provenance?` - ${n.sourcePath}`:""]})]})]},`${n.nodeId??n.name}-${s}`))})}function bn({evidence:e,t}){var s;const r=(e==null?void 0:e.businessContext)??[],n=e==null?void 0:e.outcome;return!n&&r.length===0?i.jsx(lt,{t,children:"No business context was returned for this answer."}):i.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:12},children:[n&&i.jsxs("div",{style:{display:"grid",gap:6},children:[i.jsx(N,{t,children:"Outcome"}),n.name&&i.jsx(j,{label:"Outcome",value:n.name,t}),n.owner&&i.jsx(j,{label:"Owner",value:n.owner,t}),n.decisionUse&&i.jsx(j,{label:"Decision Use",value:n.decisionUse,t}),n.reviewCadence&&i.jsx(j,{label:"Review Cadence",value:n.reviewCadence,t}),(s=n.caveats)==null?void 0:s.map((o,a)=>i.jsx(j,{label:"Caveat",value:o,t},`caveat-${a}`))]}),r.length>0&&i.jsxs("div",{style:{display:"grid",gap:6},children:[i.jsx(N,{t,children:"Context"}),r.map((o,a)=>i.jsx(j,{label:o.label??"Context",value:o.value??"",source:o.source,t},`${o.label}-${a}`))]}),(e==null?void 0:e.semanticObjects)&&e.semanticObjects.length>0&&i.jsx(Ge,{title:"Semantic Objects",assets:e.semanticObjects,t}),(e==null?void 0:e.sourceTables)&&e.sourceTables.length>0&&i.jsx(Ge,{title:"Source Tables",assets:e.sourceTables,t})]})}function vn({answer:e,t}){var o,a;const r=e.evidence,n=e.analysisPlan??(r==null?void 0:r.analysisPlan),s=(r==null?void 0:r.citations)??e.citations??[];return i.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:12},children:[i.jsxs("div",{style:{display:"grid",gap:6},children:[i.jsx(j,{label:"Certification",value:C(e.certification??e.kind),t}),I(e.cascade)&&i.jsx(j,{label:"Cascade",value:I(e.cascade)??"",t}),e.reviewStatus&&i.jsx(j,{label:"Review Status",value:C(e.reviewStatus),t}),typeof e.confidence=="number"&&i.jsx(j,{label:"Confidence",value:`${Math.round(e.confidence*100)}%`,t}),((o=r==null?void 0:r.validation)==null?void 0:o.message)&&i.jsx(j,{label:`Validation ${r.validation.status??""}`.trim(),value:r.validation.message,t}),((a=r==null?void 0:r.execution)==null?void 0:a.message)&&i.jsx(j,{label:`Execution ${r.execution.status??""}`.trim(),value:r.execution.message,t}),e.executionError&&i.jsx(j,{label:"Execution Error",value:e.executionError,t}),e.kind!=="certified"&&i.jsx(j,{label:"Promotion Path",value:"Create draft block, edit SQL, attach tests, then certify after analyst approval.",t})]}),n&&i.jsxs("div",{style:{display:"grid",gap:6},children:[i.jsx(N,{t,children:"Analysis Plan"}),n.question&&i.jsx(j,{label:"Question",value:n.question,t}),n.intent&&i.jsx(j,{label:"Intent",value:C(n.intent),t}),n.grain&&i.jsx(j,{label:"Grain",value:n.grain,t}),n.candidateTables&&n.candidateTables.length>0&&i.jsx(j,{label:"Tables",value:n.candidateTables.slice(0,5).map(d=>d.relation).filter(Boolean).join(", "),t}),n.candidateJoins&&n.candidateJoins.length>0&&i.jsx(j,{label:"Join Paths",value:n.candidateJoins.slice(0,3).map(at).join("; "),t}),n.assumptions&&n.assumptions.length>0&&i.jsx(j,{label:"Assumptions",value:n.assumptions.join(" "),t}),typeof n.repairAttempts=="number"&&n.repairAttempts>0&&i.jsx(j,{label:"SQL Repair",value:`${n.repairAttempts} retry`,t})]}),s.length>0&&i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx(N,{t,children:"Citations"}),s.slice(0,8).map((d,u)=>i.jsxs("div",{style:{fontSize:12,color:t.textSecondary,fontFamily:t.fontMono},children:[d.kind??"source",": ",d.name??"unknown",d.provenance&&i.jsxs("span",{style:{color:t.textMuted},children:[" (",d.provenance,")"]})]},`${d.kind}-${d.name}-${u}`))]})]})}function Ge({title:e,assets:t,t:r}){return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx(N,{t:r,children:e}),t.map((n,s)=>i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,paddingBottom:4},children:[i.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center",flexWrap:"wrap"},children:[i.jsx("span",{style:{fontSize:12,fontWeight:700,color:r.textPrimary},children:n.name??n.nodeId}),n.kind&&i.jsx(z,{label:C(n.kind),t:r}),n.certification&&i.jsx(z,{label:C(n.certification),t:r})]}),n.description&&i.jsx("div",{style:{fontSize:12,color:r.textSecondary},children:n.description}),(n.sourcePath||n.owner||n.domain)&&i.jsx("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.fontMono},children:[n.domain,n.owner,n.sourcePath].filter(Boolean).join(" - ")})]},`${n.nodeId??n.name}-${s}`))]})}function jn({artifact:e,t}){const r=[e.kind?{label:"Kind",value:C(e.kind)}:null,e.name?{label:"Name",value:e.name}:null,e.sourcePath?{label:"Source Path",value:e.sourcePath}:null,e.metrics.length>0?{label:"Metrics",value:e.metrics.join(", ")}:null,e.dimensions.length>0?{label:"Dimensions",value:e.dimensions.join(", ")}:null,e.timeDimension?{label:"Time",value:e.timeDimension}:null,e.filters.length>0?{label:"Filters",value:e.filters.join("; ")}:null].filter(n=>!!n);return i.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:10},children:[r.length>0&&i.jsx("div",{style:{display:"grid",gap:6},children:r.map(n=>i.jsx(j,{label:n.label,value:n.value,t},n.label))}),i.jsx("pre",{style:st(t,340),children:e.source})]})}function Sn({sql:e,blockPath:t,executionError:r,t:n}){return i.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:8},children:[t&&i.jsxs("div",{style:{fontSize:12,color:n.textSecondary},children:["Source block: ",i.jsx("span",{style:{fontFamily:n.fontMono,color:n.textPrimary},children:t})]}),r&&i.jsx("div",{style:{padding:10,border:"1px solid rgba(248, 81, 73, 0.35)",borderRadius:6,background:"rgba(248, 81, 73, 0.10)",color:"#ff7b72",fontSize:12,lineHeight:1.45,whiteSpace:"pre-wrap"},children:r}),e?i.jsx("pre",{style:st(n,260),children:e}):i.jsx("div",{style:{fontSize:12,color:n.textMuted},children:"No SQL text was returned for this answer."})]})}function st(e,t){return{margin:0,padding:10,overflow:"auto",maxHeight:t,borderRadius:4,background:e.editorBg,color:e.textPrimary,border:`1px solid ${e.cellBorder}`,fontSize:12,fontFamily:e.fontMono,whiteSpace:"pre"}}function j({label:e,value:t,source:r,t:n}){return t?i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"130px 1fr",gap:10,fontSize:12,alignItems:"baseline"},children:[i.jsx("span",{style:{color:n.textMuted},children:e}),i.jsxs("span",{style:{color:n.textSecondary},children:[t,r&&i.jsxs("span",{style:{color:n.textMuted},children:[" (",r,")"]})]})]}):null}function N({children:e,t}){return i.jsx("div",{style:{fontSize:11,fontWeight:700,fontFamily:t.fontMono,color:t.textMuted,textTransform:"uppercase",letterSpacing:"0.08em"},children:e})}function lt({children:e,t}){return i.jsx("div",{style:{padding:12,fontSize:12,color:t.textMuted},children:e})}function z({label:e,t}){return i.jsx("span",{style:{fontSize:11,fontFamily:t.fontMono,color:t.textSecondary,padding:"2px 6px",borderRadius:4,background:t.editorBg,border:`1px solid ${t.cellBorder}`},children:e})}function wn({items:e,t,accent:r}){return e.length===0?null:i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px 16px",alignItems:"center",padding:"7px 10px",borderTop:`1px solid ${t.cellBorder}`,boxShadow:`inset 0 2px 0 ${r}`,background:t.editorBg,color:t.textMuted,fontFamily:t.fontMono,fontSize:10.5},children:e.map(n=>i.jsxs("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[i.jsx("span",{style:{color:t.textMuted},children:n.label})," ",i.jsx("strong",{style:{color:t.textSecondary,fontWeight:600},children:n.value})]},`${n.label}-${n.value}`))})}function Xe({active:e,label:t,onClick:r,t:n}){return i.jsx("button",{onClick:r,style:{padding:"4px 2px",fontSize:11.5,border:0,borderBottom:`2px solid ${e?n.accent:"transparent"}`,borderRadius:0,background:"transparent",color:e?n.accent:n.textSecondary,fontWeight:e?700:500,cursor:"pointer"},children:t})}function kn({result:e,chartConfig:t,t:r,onChange:n}){const s=e.columns;if(s.length===0)return null;const o=ce.filter(l=>l.value!=="table"),a=t!=null&&t.x&&s.includes(t.x)?t.x:s[0]??"",d=t!=null&&t.y&&s.includes(t.y)?t.y:s.find(l=>l!==a)??s[0]??"",u=t!=null&&t.color&&s.includes(t.color)?t.color:"";return i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(130px, 1fr))",gap:8,alignItems:"end",border:`1px solid ${r.cellBorder}`,borderRadius:7,background:`${r.tableHeaderBg}55`,padding:10},children:[i.jsx(Y,{label:"Chart type",t:r,children:i.jsx("select",{value:(t==null?void 0:t.chart)??"bar",onChange:l=>n({chart:l.target.value}),style:K(r),children:o.map(l=>i.jsx("option",{value:l.value,children:l.label},l.value))})}),i.jsx(Y,{label:"X axis",t:r,children:i.jsx("select",{value:a,onChange:l=>n({x:l.target.value}),style:K(r),children:s.map(l=>i.jsx("option",{value:l,children:l},l))})}),i.jsx(Y,{label:"Y axis",t:r,children:i.jsx("select",{value:d,onChange:l=>n({y:l.target.value}),style:K(r),children:s.map(l=>i.jsx("option",{value:l,children:l},l))})}),i.jsx(Y,{label:"Color",t:r,children:i.jsxs("select",{value:u,onChange:l=>n({color:l.target.value||void 0}),style:K(r),children:[i.jsx("option",{value:"",children:"None"}),s.map(l=>i.jsx("option",{value:l,children:l},l))]})})]})}function Y({label:e,t,children:r}){return i.jsxs("label",{style:{display:"grid",gap:4,minWidth:0},children:[i.jsx("span",{style:{fontSize:10.5,color:t.textMuted,fontWeight:800,textTransform:"uppercase",letterSpacing:0},children:e}),r]})}function K(e){return{width:"100%",minWidth:0,height:30,border:`1px solid ${e.inputBorder}`,borderRadius:6,background:e.editorBg,color:e.textPrimary,fontFamily:e.font,fontSize:12,padding:"0 8px"}}function $n({t:e,adding:t,hasResult:r,hasChart:n,fallbackLabel:s,open:o,onToggle:a,onAdd:d}){if(!r)return i.jsx("button",{type:"button",onClick:()=>d("auto"),disabled:t,style:{...Ye(e,t),marginLeft:"auto"},children:t?"Adding...":s});const u=n?[{mode:"both",label:"Chart + data",description:"Add chart and table tiles"},{mode:"chart",label:"Chart only",description:"Add the visualization tile"},{mode:"data",label:"Data table",description:"Add the rows as a table tile"}]:[{mode:"data",label:"Data table",description:"Add the rows as a table tile"}];return i.jsxs("div",{style:{marginLeft:"auto",position:"relative"},children:[i.jsxs("button",{type:"button",onClick:a,disabled:t,style:Ye(e,t),children:[t?"Adding...":"Add to App",!t&&i.jsx("span",{style:{marginLeft:6,fontSize:10},children:"v"})]}),o&&!t&&i.jsx("div",{style:{position:"absolute",right:0,top:"calc(100% + 6px)",zIndex:30,width:190,border:`1px solid ${e.cellBorder}`,borderRadius:8,background:e.cellBg,boxShadow:"0 14px 34px rgba(0, 0, 0, 0.18)",padding:6},children:u.map(l=>i.jsxs("button",{type:"button",onClick:()=>d(l.mode),style:{width:"100%",border:0,borderRadius:6,background:"transparent",color:e.textPrimary,textAlign:"left",padding:"8px 9px",cursor:"pointer"},children:[i.jsx("div",{style:{fontSize:12,fontWeight:700},children:l.label}),i.jsx("div",{style:{fontSize:11,color:e.textMuted,marginTop:2},children:l.description})]},l.mode))})]})}function Ye(e,t){return{border:`1px solid ${e.btnBorder}`,borderRadius:5,background:t?e.editorBg:`${e.accent}18`,color:t?e.textMuted:e.accent,padding:"4px 8px",fontSize:11,cursor:t?"default":"pointer"}}function C(e){return e.replace(/_/g," ")}function at(e){const t=[e.leftRelation,e.leftColumn].filter(Boolean).join("."),r=[e.rightRelation,e.rightColumn].filter(Boolean).join("."),n=[t,r].filter(Boolean).join(" to ");return e.reason?`${n} (${e.reason})`:n}function Cn(e){return e==null?"-":typeof e=="number"?Number.isFinite(e)?Math.abs(e)>=1e3||!Number.isInteger(e)?e.toLocaleString(void 0,{maximumFractionDigits:2}):e.toLocaleString():String(e):typeof e=="boolean"?e?"true":"false":typeof e=="string"?e:JSON.stringify(e)}function Bn(e){const t=e.toLowerCase();return t.includes("certified")?"trusted business context":t.includes("ai")||t.includes("generated")?"AI draft":t.includes("no_answer")?"needs more context":C(e)}function dt(e){var t;switch((t=e.trustLabelInfo)==null?void 0:t.id){case"certified":return"certified";case"reviewed":return"review";case"ai_generated":return"ai_generated";case"conflict":return"review";case"insufficient_context":return e.kind==="no_answer"?"no_answer":"uncertified"}return e.kind==="no_answer"?"no_answer":e.certification==="certified"||e.reviewStatus==="certified"?"certified":e.reviewStatus==="draft_ready"||e.reviewStatus==="analyst_review_required"?"review":e.certification==="ai_generated"?"ai_generated":e.certification==="analyst_review_required"||e.certification==="uncertified"?"uncertified":e.kind==="certified"?"certified":"draft"}function An(e,t){return e==="certified"?t.success:e==="no_answer"?t.error:e==="deprecated"?t.textMuted:t.warning}function zn(e,t,r,n){var u,l,p,c,f,h,x,b;const s=[],o=((l=(u=e.evidence)==null?void 0:u.selectedAssets)==null?void 0:l[0])??((c=(p=e.evidence)==null?void 0:p.lineage)==null?void 0:c.find(S=>S.owner||S.domain||S.sourcePath)),a=r??(o==null?void 0:o.name),d=n??(o==null?void 0:o.sourcePath)??(o==null?void 0:o.provenance);if(a&&s.push({label:e.kind==="certified"?"source":"draft source",value:a}),((o==null?void 0:o.owner)??((h=(f=e.evidence)==null?void 0:f.outcome)==null?void 0:h.owner))&&s.push({label:"owner",value:(o==null?void 0:o.owner)??((b=(x=e.evidence)==null?void 0:x.outcome)==null?void 0:b.owner)??""}),d&&s.push({label:"path",value:d}),e.sourceTier&&s.push({label:"tier",value:C(e.sourceTier)}),I(e.cascade)&&s.push({label:"cascade",value:I(e.cascade)??""}),t){const S=t.rowCount??t.rows.length,g=t.executionTime!==void 0?` - ${Math.round(t.executionTime)}ms`:"";s.push({label:"run",value:`${S.toLocaleString()} rows${g}`})}return e.reviewStatus&&e.reviewStatus!=="certified"&&s.push({label:"next",value:C(e.reviewStatus)}),Mn(s).slice(0,5)}function I(e){if(!(e!=null&&e.terminalLane)&&!(e!=null&&e.routeTier))return;const t=Tn(e.terminalLane),r=Ln(e.routeTier);return[t,r].filter(Boolean).join(" · ")||void 0}function Tn(e){switch(e){case"certified":return"Lane 1 certified";case"semantic":return"Lane 2 semantic";case"generated":return"Lane 3 generated";case"refusal":return"Lane 4 refusal";default:return e?C(e):void 0}}function Ln(e){switch(e){case"certified_block":return"Certified block";case"semantic_metric":return"Semantic metric";case"generated_sql":return"Generated SQL";case"business_context":return"Business context";case"no_answer":return"No answer";default:return e?C(e):void 0}}function Rn(e,t){var r,n,s,o;return Q(e.sourceCertifiedBlock)??de((r=e.evidence)==null?void 0:r.selectedAssets)??de((n=e.evidence)==null?void 0:n.lineage)??de(e.citations)??Q((s=e.block)==null?void 0:s.name)??Q((o=e.result)==null?void 0:o.blockName)??Q(t)}function de(e){return e==null?void 0:e.map(t=>t.kind==="block"?Q(t.name):void 0).find(t=>!!t)}function Q(e){return typeof e!="string"?void 0:e.replace(/\s+/g," ").trim()||void 0}function Mn(e){const t=new Set;return e.filter(r=>{const n=r.value.trim();if(!n)return!1;const s=`${r.label}:${n}`;return t.has(s)?!1:(t.add(s),!0)})}function _n(e){return{x:0,y:e.layout.items.reduce((r,n)=>Math.max(r,n.y+n.h),0),w:6,h:3}}function Dn(e,t){const r=t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"tile",n=new Set(e.layout.items.map(s=>s.i));if(!n.has(r))return r;for(let s=2;s<1e3;s++){const o=`${r}-${s}`;if(!n.has(o))return o}return`${r}-${Date.now()}`}function In(e){const t=String(e??"table").toLowerCase().replace(/-/g,"_");return t==="single_value"||t==="kpi"||t==="line"||t==="bar"||t==="area"||t==="pie"||t==="donut"||t==="grouped_bar"||t==="stacked_bar"||t==="scatter"||t==="heatmap"||t==="histogram"||t==="waterfall"||t==="pivot"||t==="map"||t==="funnel"||t==="sankey"?t:"table"}const Qn=Object.freeze(Object.defineProperty({__proto__:null,AgentAnswerCard:Kt,StructuredAnswerText:ot,extractGovernedAnswer:Vt,formatCascadeOutcome:I,resolveAgentOutcome:it,resolveAnswerTrustState:dt,resolveDqlArtifactMeta:nt},Symbol.toStringTag,{value:"Module"}));export{Qn as A,En as R,ot as S,tt as d};