@yejiming/dsh-data-agent 0.0.11 → 0.0.13

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 (49) hide show
  1. package/README.en.md +70 -15
  2. package/README.md +70 -15
  3. package/conformance/dsh-ecosystem/baseline.json +59 -0
  4. package/conformance/dsh-ecosystem/dependencies.json +41 -0
  5. package/conformance/dsh-ecosystem/fixtures/host-degraded.fixture.json +12 -0
  6. package/conformance/dsh-ecosystem/fixtures/host-eligible.fixture.json +13 -0
  7. package/conformance/dsh-ecosystem/fixtures/host-rejected.fixture.json +12 -0
  8. package/conformance/dsh-ecosystem/fixtures/profiles/native-only/package.json +8 -0
  9. package/conformance/dsh-ecosystem/fixtures/profiles/native-plus-adapter/package.json +9 -0
  10. package/conformance/dsh-ecosystem/inventory.json +77 -0
  11. package/conformance/dsh-ecosystem/restrictions.json +20 -0
  12. package/dsh-plugin.json +67 -0
  13. package/lib/client.js +1352 -130
  14. package/lib/client.js.map +1 -1
  15. package/lib/{command-DuCpwVbl.js → command-utC5MHd9.js} +101 -60
  16. package/lib/command.js +1 -1
  17. package/lib/{connections-5sfdEDsG.js → connections-CHY4uB6z.js} +747 -65
  18. package/lib/defaults-Cngd8Tf8.js +131 -0
  19. package/lib/ecosystem.js +19 -0
  20. package/lib/index.js +40 -33
  21. package/lib/routes.js +5 -6
  22. package/lib/{tool-DVh61An-.js → tool-ZTOS4B33.js} +161 -177
  23. package/lib/tool.js +1 -1
  24. package/lib/types/analysis-html.d.ts +27 -0
  25. package/lib/types/analysis.d.ts +13 -1
  26. package/lib/types/client/DataAgentWorkbench.d.ts +1 -2
  27. package/lib/types/client/QueryResultTable.d.ts +13 -0
  28. package/lib/types/client/locales.d.ts +48 -0
  29. package/lib/types/client/persistence.d.ts +3 -1
  30. package/lib/types/client/query-export.d.ts +11 -0
  31. package/lib/types/client-discovery.d.ts +3 -4
  32. package/lib/types/clients.d.ts +14 -8
  33. package/lib/types/command.d.ts +2 -2
  34. package/lib/types/connections.d.ts +33 -4
  35. package/lib/types/database-types.d.ts +23 -0
  36. package/lib/types/defaults.d.ts +4 -0
  37. package/lib/types/ecosystem.d.ts +13 -0
  38. package/lib/types/index.d.ts +21 -16
  39. package/lib/types/presentation-text.d.ts +3 -0
  40. package/lib/types/query.d.ts +13 -11
  41. package/lib/types/sql.d.ts +9 -1
  42. package/lib/types/storage.d.ts +11 -1
  43. package/lib/types/structured-read.d.ts +2 -2
  44. package/lib/types/structured.d.ts +1 -1
  45. package/lib/types/tool.d.ts +5 -5
  46. package/lib/types/tui-connection-form.d.ts +10 -7
  47. package/package.json +66 -42
  48. package/preset/data-agent/agent.cordis.yml +9 -4
  49. package/lib/defaults-DP4RyRh1.js +0 -21
@@ -1,5 +1,8 @@
1
- import { a as classifyStatement, c as assertSingleStatement, i as runClientQuery, n as redactQueryResult, o as clientsSchema, r as redactSecretText, s as enforceReadRowLimit } from "./connections-5sfdEDsG.js";
2
- import { i as DEFAULT_MAX_RESULT_CHARS, o as DEFAULT_QUERY_TIMEOUT_MS, r as DEFAULT_MAX_QUERY_CHARS } from "./defaults-DP4RyRh1.js";
1
+ import { i as DEFAULT_MAX_RESULT_CHARS, o as DEFAULT_QUERY_TIMEOUT_MS, r as DEFAULT_MAX_QUERY_CHARS } from "./defaults-Cngd8Tf8.js";
2
+ import { a as parseStructuredQueryOutput, c as clientsSchema, l as enforceReadRowLimit, n as redactQueryResult, o as runClientQuery, r as redactSecretText, s as classifyStatement, u as assertSingleStatement } from "./connections-CHY4uB6z.js";
3
+ import { randomUUID } from "node:crypto";
4
+ import { link, mkdir, unlink, writeFile } from "node:fs/promises";
5
+ import { resolve } from "node:path";
3
6
  import z from "schemastery";
4
7
  import { defineTool } from "@deepseek-ai/dsh-tools";
5
8
  const VIEW_KINDS = [
@@ -203,11 +206,14 @@ function parseAnalysisRequest(input, prefix = "render-analysis") {
203
206
  if (!isRecord(input)) fail(prefix + ": 请求必须是对象");
204
207
  assertOnlyKeys(input, [
205
208
  "title",
209
+ "outputName",
206
210
  "summary",
207
211
  "datasets",
208
212
  "views"
209
213
  ], prefix);
210
214
  const title = requireNonEmptyString(input["title"], prefix + ".title");
215
+ const outputName = optionalString(input, "outputName", prefix);
216
+ if (outputName !== void 0 && outputName.trim().length === 0) fail(prefix + ".outputName: 必须是非空字符串");
211
217
  const summary = optionalString(input, "summary", prefix);
212
218
  const datasets = input["datasets"];
213
219
  if (!Array.isArray(datasets) || datasets.length < 1 || datasets.length > 6) fail(prefix + ": datasets 必须是 1-6 个");
@@ -242,6 +248,7 @@ function parseAnalysisRequest(input, prefix = "render-analysis") {
242
248
  datasets: parsedDatasets,
243
249
  views: parsedViews
244
250
  };
251
+ if (outputName !== void 0) request.outputName = outputName;
245
252
  if (summary !== void 0) request.summary = summary;
246
253
  return request;
247
254
  }
@@ -312,13 +319,15 @@ function rowsToArrays(columns, rows) {
312
319
  }
313
320
  /** JSON-encoded UTF-8 size of the normalized report (the 512 KiB bound). */
314
321
  function reportJsonBytes(report) {
315
- return new TextEncoder().encode(JSON.stringify(report)).length;
322
+ const { htmlPath: _htmlPath, ...dataReport } = report;
323
+ return new TextEncoder().encode(JSON.stringify(dataReport)).length;
316
324
  }
317
325
  /** One-line model-facing summary; never re-injects rows into model context (D5). */
318
326
  function formatAnalysisSummary(report) {
319
327
  const emptyIds = report.datasets.filter((dataset) => dataset.rows.length === 0).map((dataset) => dataset.id);
320
328
  let text = "已生成分析报告《" + report.title + "》:" + report.datasets.length + " 个数据集、" + report.views.length + " 个视图(version 1)。";
321
329
  if (emptyIds.length > 0) text += "其中 " + emptyIds.length + " 个数据集无数据:" + emptyIds.join("、") + "。";
330
+ if (report.htmlPath !== void 0) text += "Dashboard HTML已保存:" + report.htmlPath;
322
331
  return text;
323
332
  }
324
333
  const BASE_VIEW_PROPERTIES = {
@@ -508,6 +517,10 @@ const RENDER_ANALYSIS_PARAMETERS = {
508
517
  required: true,
509
518
  description: "报告标题,如「月度经营分析」"
510
519
  },
520
+ outputName: {
521
+ type: "string",
522
+ description: "可选语义化HTML文件名(仅basename,可省略.html),如「电商经营全景分析-2023-09至2026-08」;缺省时使用title,不要使用随机ID"
523
+ },
511
524
  summary: {
512
525
  type: "string",
513
526
  description: "可选一句话结论/摘要,显示在报告头部"
@@ -554,6 +567,10 @@ const ANALYSIS_REPORT_OUTPUT_SCHEMA = {
554
567
  required: true
555
568
  },
556
569
  summary: { type: "string" },
570
+ htmlPath: {
571
+ type: "string",
572
+ required: true
573
+ },
557
574
  datasets: {
558
575
  type: "array",
559
576
  required: true,
@@ -590,168 +607,6 @@ const ANALYSIS_REPORT_OUTPUT_SCHEMA = {
590
607
  additionalProperties: false
591
608
  };
592
609
  //#endregion
593
- //#region src/structured.ts
594
- function normalizeNewlines(text) {
595
- return text.replace(/\r\n?/g, "\n");
596
- }
597
- function splitLine(line, delimiter) {
598
- return line.split(delimiter);
599
- }
600
- /** Make column names valid unique JSON object keys. */
601
- function uniqueColumns(columns) {
602
- const used = /* @__PURE__ */ new Set();
603
- return columns.map((raw, index) => {
604
- let name = raw.trim();
605
- if (name.length === 0) name = `column_${index + 1}`;
606
- if (used.has(name)) {
607
- let suffix = 2;
608
- while (used.has(`${name}_${suffix}`)) suffix += 1;
609
- name = `${name}_${suffix}`;
610
- }
611
- used.add(name);
612
- return name;
613
- });
614
- }
615
- function rowObject(columns, fields) {
616
- const row = {};
617
- for (let index = 0; index < columns.length; index += 1) row[columns[index]] = fields[index] ?? null;
618
- return row;
619
- }
620
- function emptyOutput() {
621
- return {
622
- columns: [],
623
- rows: [],
624
- rowLimitExceeded: false
625
- };
626
- }
627
- function skipLeadingBlank(lines) {
628
- let index = 0;
629
- while (index < lines.length && lines[index].trim().length === 0) index += 1;
630
- return index;
631
- }
632
- /** PostgreSQL `-A` appends a `(N rows)` / `(N row)` footer after SELECT output. */
633
- function isPostgresFooter(line) {
634
- return /^\(\d+ rows?\)$/.test(line.trim());
635
- }
636
- function parseDelimited(stdout, delimiter, maxRows, skipFooter = false) {
637
- const lines = normalizeNewlines(stdout).split("\n");
638
- if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
639
- const headerIndex = skipLeadingBlank(lines);
640
- if (headerIndex >= lines.length) return emptyOutput();
641
- const columns = uniqueColumns(splitLine(lines[headerIndex], delimiter));
642
- const rows = [];
643
- let rowLimitExceeded = false;
644
- for (let index = headerIndex + 1; index < lines.length; index += 1) {
645
- const line = lines[index];
646
- if (skipFooter && isPostgresFooter(line)) continue;
647
- if (rows.length >= maxRows) {
648
- rowLimitExceeded = true;
649
- break;
650
- }
651
- rows.push(rowObject(columns, splitLine(line, delimiter)));
652
- }
653
- return {
654
- columns,
655
- rows,
656
- rowLimitExceeded
657
- };
658
- }
659
- /** Minimal RFC-4180-style parser for sqlite3 `-csv` output. */
660
- function parseCsv(text) {
661
- const records = [];
662
- let record = [];
663
- let field = "";
664
- let quoted = false;
665
- let index = 0;
666
- const pushField = () => {
667
- record.push(field);
668
- field = "";
669
- };
670
- const pushRecord = () => {
671
- pushField();
672
- records.push(record);
673
- record = [];
674
- };
675
- while (index < text.length) {
676
- const char = text[index];
677
- if (quoted) {
678
- if (char === "\"") {
679
- if (text[index + 1] === "\"") {
680
- field += "\"";
681
- index += 2;
682
- continue;
683
- }
684
- quoted = false;
685
- index += 1;
686
- continue;
687
- }
688
- field += char;
689
- index += 1;
690
- continue;
691
- }
692
- if (char === "\"" && field.length === 0) {
693
- quoted = true;
694
- index += 1;
695
- continue;
696
- }
697
- if (char === ",") {
698
- pushField();
699
- index += 1;
700
- continue;
701
- }
702
- if (char === "\n") {
703
- pushRecord();
704
- index += 1;
705
- continue;
706
- }
707
- if (char === "\r") {
708
- if (text[index + 1] === "\n") index += 1;
709
- pushRecord();
710
- index += 1;
711
- continue;
712
- }
713
- field += char;
714
- index += 1;
715
- }
716
- if (field.length > 0 || record.length > 0) pushRecord();
717
- return records;
718
- }
719
- function parseCsvOutput(stdout, maxRows) {
720
- const records = parseCsv(normalizeNewlines(stdout)).filter((record) => !(record.length === 1 && record[0] === ""));
721
- if (records.length === 0) return emptyOutput();
722
- const columns = uniqueColumns(records[0]);
723
- const rows = [];
724
- let rowLimitExceeded = false;
725
- for (let index = 1; index < records.length; index += 1) {
726
- if (rows.length >= maxRows) {
727
- rowLimitExceeded = true;
728
- break;
729
- }
730
- rows.push(rowObject(columns, records[index]));
731
- }
732
- return {
733
- columns,
734
- rows,
735
- rowLimitExceeded
736
- };
737
- }
738
- /**
739
- * Parse one database type's structured-query stdout. The matching template is
740
- * `buildStructuredQueryTemplate`: mysql tab-separated with a header, postgres
741
- * pipe-separated with a header and row-count footer, sqlite CSV with a header,
742
- * oracle pipe-separated with heading on, hive/impala tsv with a header.
743
- */
744
- function parseStructuredQueryOutput(type, stdout, maxRows) {
745
- switch (type) {
746
- case "mysql": return parseDelimited(stdout, " ", maxRows);
747
- case "postgres": return parseDelimited(stdout, "|", maxRows, true);
748
- case "sqlite": return parseCsvOutput(stdout, maxRows);
749
- case "oracle": return parseDelimited(stdout, "|", maxRows);
750
- case "hive":
751
- case "impala": return parseDelimited(stdout, " ", maxRows);
752
- }
753
- }
754
- //#endregion
755
610
  //#region src/structured-read.ts
756
611
  /** Look up the session connection, failing with the same message for every tool. */
757
612
  async function requireToolConnection(ctx, exec, toolName) {
@@ -786,7 +641,7 @@ function runnerOptions(resolved, mode) {
786
641
  /**
787
642
  * Execute one read-only SQL through the structured client template and parse
788
643
  * it into the canonical { columns, rows } shape, with maxRows enforced at both
789
- * the SQL level (LIMIT injection) and the parse level.
644
+ * the SQL level (dialect rewrite) and the parse level.
790
645
  */
791
646
  async function runStructuredReadQuery(ctx, connection, sql, resolved, toolName, signal) {
792
647
  if (sql.trim().length === 0) throw new Error(toolName + ": sql 不能为空");
@@ -810,6 +665,127 @@ async function runStructuredReadQuery(ctx, connection, sql, resolved, toolName,
810
665
  };
811
666
  }
812
667
  //#endregion
668
+ //#region src/analysis-html.ts
669
+ /**
670
+ * Offline HTML artifact for one validated AnalysisReportV1.
671
+ *
672
+ * The generated page has no network/runtime dependencies. Untrusted report
673
+ * strings stay inside escaped JSON and are projected with textContent only;
674
+ * chart geometry is derived from already-validated finite numeric fields.
675
+ * @module @yejiming/dsh-data-agent/analysis-html
676
+ */
677
+ const ANALYSIS_REPORT_DIRECTORY = "analysis-reports";
678
+ /** Convert a report title/output name into a bounded, readable filename segment. */
679
+ function analysisFileSegment(value, fallback) {
680
+ const sanitize = (candidate) => candidate.normalize("NFKC").replace(/\.html$/i, "").replace(/[\u0000-\u001f\u007f-\u009f]/g, "").replace(/[^\p{Letter}\p{Number}]+/gu, "-").replace(/^-+|-+$/g, "").slice(0, 96);
681
+ return sanitize(value) || sanitize(fallback) || "analysis-report";
682
+ }
683
+ /** Relative path shared by the writer and DSH's mutation presentation. */
684
+ function analysisArtifactRelativePath(title, outputName) {
685
+ const basename = analysisFileSegment(outputName ?? title, "分析报告");
686
+ return `${ANALYSIS_REPORT_DIRECTORY}/${basename}.html`;
687
+ }
688
+ /** Escape JSON so data cannot close its application/json script element. */
689
+ function escapeJsonForHtmlScript(value) {
690
+ return JSON.stringify(value).replace(/&/g, "\\u0026").replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
691
+ }
692
+ /** Render one complete, offline Dashboard document. */
693
+ function renderAnalysisHtml(report, generatedAt = (/* @__PURE__ */ new Date()).toISOString()) {
694
+ return `<!doctype html>
695
+ <html lang="zh-CN">
696
+ <head>
697
+ <meta charset="utf-8">
698
+ <meta name="viewport" content="width=device-width, initial-scale=1">
699
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'none'; font-src 'none'; object-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'">
700
+ <title>DSH Data Agent Analysis</title>
701
+ <style>
702
+ :root{color-scheme:light dark;--bg:oklch(97.4% .006 255);--panel:oklch(99.2% .003 255);--text:oklch(27% .035 255);--muted:oklch(52% .025 255);--line:oklch(88% .012 255);--grid:oklch(92% .008 255);--accent:oklch(58% .16 255);--palette:#4e79a7,#f28e2b,#59a14f,#e15759,#76b7b2,#edc948,#b07aa1,#9c755f}
703
+ @media(prefers-color-scheme:dark){:root{--bg:oklch(19% .018 255);--panel:oklch(23% .02 255);--text:oklch(93% .012 255);--muted:oklch(72% .018 255);--line:oklch(35% .022 255);--grid:oklch(31% .018 255);--accent:oklch(72% .13 255)}}
704
+ *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:14px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif}main{width:min(1440px,calc(100% - 32px));margin:0 auto;padding:24px 0 48px}header{padding-bottom:16px;margin-bottom:16px;border-bottom:1px solid var(--line)}h1{margin:0;font-size:24px;line-height:1.25;font-weight:650;letter-spacing:-.015em}header p{max-width:1120px;margin:7px 0 0;color:var(--muted)}.report-count{font-size:13px;color:var(--text)}.metric-band{display:flex;flex-wrap:wrap;gap:8px;padding-bottom:12px;margin-bottom:12px;border-bottom:1px solid var(--line)}.metric{flex:1 1 180px;min-width:150px;padding:9px 12px;background:var(--panel);border:1px solid var(--line);border-radius:8px;break-inside:avoid}.metric-label{margin:0;color:var(--muted);font-size:12px}.metric-value{margin:2px 0 0;font-size:18px;line-height:1.35;font-weight:650;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.dashboard{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.view{min-width:0;padding:11px 12px;background:var(--panel);border:1px solid var(--line);border-radius:8px;break-inside:avoid}.view.full,.view.table{grid-column:1/-1}.view h2{font-size:13px;line-height:1.4;font-weight:650;margin:0 0 8px}.empty{padding:28px 12px;text-align:center;color:var(--muted);border:1px dashed var(--line);border-radius:7px}.chart{width:100%;height:auto;min-height:260px;display:block}.axis{stroke:var(--line);stroke-width:1}.grid{stroke:var(--grid);stroke-width:1}.axis-label,.legend{fill:var(--muted);font-size:11px}.legend-row{display:flex;gap:12px;flex-wrap:wrap;color:var(--muted);font-size:12px;margin-top:6px}.dot{display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:5px}details{margin-top:10px;border-top:1px solid var(--line);padding-top:8px}summary{cursor:pointer;color:var(--accent);font-size:12px}.table-wrap{overflow:auto;max-height:460px;border:1px solid var(--line);border-radius:6px}table{width:100%;border-collapse:collapse;white-space:nowrap;font-size:12px}th,td{text-align:left;padding:7px 10px;border-bottom:1px solid var(--line);vertical-align:top}th{position:sticky;top:0;background:var(--bg);font-weight:600}td{max-width:420px;white-space:pre-wrap;overflow-wrap:anywhere}.null{color:var(--muted);font-style:italic}footer{margin-top:18px;color:var(--muted);font-size:12px}
705
+ @media(max-width:880px){main{width:min(100% - 20px,1440px);padding-top:18px}h1{font-size:21px}.dashboard{grid-template-columns:1fr}.view{grid-column:1!important}.metric{flex-basis:100%}}
706
+ @media print{:root{color-scheme:light;--bg:oklch(98.5% .003 255);--panel:oklch(99.5% .002 255);--text:oklch(24% .025 255);--muted:oklch(48% .02 255);--line:oklch(84% .01 255);--grid:oklch(90% .008 255)}.dashboard{display:block}.view{margin:0 0 12px}.table-wrap{max-height:none;overflow:visible}details{display:block}details>summary{display:none}details>*{display:block!important}main{width:100%;padding:0}}
707
+ </style>
708
+ </head>
709
+ <body>
710
+ <main>
711
+ <header id="report-header"></header>
712
+ <section id="metric-band" class="metric-band" aria-label="关键指标"></section>
713
+ <section id="dashboard" class="dashboard" aria-label="分析视图"></section>
714
+ <footer id="report-footer"></footer>
715
+ </main>
716
+ <script type="application/json" id="report-data">${escapeJsonForHtmlScript(report)}<\/script>
717
+ <script>
718
+ (()=>{'use strict';
719
+ const report=JSON.parse(document.getElementById('report-data').textContent||'{}');
720
+ const palette=['#4e79a7','#f28e2b','#59a14f','#e15759','#76b7b2','#edc948','#b07aa1','#9c755f'];
721
+ const ns='http://www.w3.org/2000/svg';
722
+ const el=(tag,className,text)=>{const node=document.createElement(tag);if(className)node.className=className;if(text!==undefined)node.textContent=String(text);return node};
723
+ const svgEl=(tag,attrs={})=>{const node=document.createElementNS(ns,tag);for(const [key,value] of Object.entries(attrs))node.setAttribute(key,String(value));return node};
724
+ const datasetFor=id=>report.datasets.find(item=>item.id===id);
725
+ const indexOf=(dataset,field)=>dataset.columns.indexOf(field);
726
+ const number=value=>value===null||value===undefined||value===''?null:(Number.isFinite(Number(value))?Number(value):null);
727
+ const extent=(values,includeZero=false)=>{const finite=values.filter(Number.isFinite);let min=finite.length?Math.min(...finite):0,max=finite.length?Math.max(...finite):1;if(includeZero){min=Math.min(0,min);max=Math.max(0,max)}if(min===max){min-=1;max+=1}return[min,max]};
728
+ const scale=(value,min,max,start,end)=>start+(value-min)/(max-min)*(end-start);
729
+ const titleFor=view=>view.label||({metric:'指标',line:'趋势',bar:'对比',pie:'构成',scatter:'分布',table:'明细'}[view.kind]||view.id);
730
+ const empty=()=>el('div','empty','暂无数据');
731
+ function tableFor(dataset,columns){const selected=(columns&&columns.length?columns:dataset.columns).map(name=>[name,indexOf(dataset,name)]);const wrap=el('div','table-wrap');const table=el('table');const head=el('thead');const hr=el('tr');selected.forEach(([name])=>hr.append(el('th','',name)));head.append(hr);table.append(head);const body=el('tbody');dataset.rows.forEach(row=>{const tr=el('tr');selected.forEach(([,index])=>{const value=row[index];const td=el('td',value===null?'null':'',value===null?'NULL':value);tr.append(td)});body.append(tr)});table.append(body);wrap.append(table);return wrap}
732
+ function detailsFor(dataset,columns){const details=el('details');details.append(el('summary','','查看原始数据('+dataset.rows.length+'行)'));details.append(tableFor(dataset,columns));return details}
733
+ function baseSvg(){const svg=svgEl('svg',{viewBox:'0 0 760 300',role:'img',class:'chart','aria-label':'数据图表'});for(let i=0;i<5;i++){const y=30+i*55;svg.append(svgEl('line',{x1:58,y1:y,x2:738,y2:y,class:'grid'}))}svg.append(svgEl('line',{x1:58,y1:250,x2:738,y2:250,class:'axis'}));svg.append(svgEl('line',{x1:58,y1:20,x2:58,y2:250,class:'axis'}));return svg}
734
+ function axisText(svg,text,x,y,anchor='start'){const node=svgEl('text',{x,y,'text-anchor':anchor,class:'axis-label'});node.textContent=String(text);svg.append(node)}
735
+ function legend(card,names){if(names.length<2)return;const row=el('div','legend-row');names.forEach((name,index)=>{const item=el('span');const dot=el('i','dot');dot.style.background=palette[index%palette.length];item.append(dot,document.createTextNode(String(name)));row.append(item)});card.append(row)}
736
+ function lineChart(card,view,dataset){const xIndex=indexOf(dataset,view.x.field);const grouped=new Map();if(view.seriesField){const groupIndex=indexOf(dataset,view.seriesField),yIndex=indexOf(dataset,view.y[0]);dataset.rows.forEach((row,index)=>{const name=row[groupIndex]??'';if(!grouped.has(name))grouped.set(name,[]);grouped.get(name).push({index,x:row[xIndex],y:number(row[yIndex])})})}else view.y.forEach(field=>{const yIndex=indexOf(dataset,field);grouped.set(field,dataset.rows.map((row,index)=>({index,x:row[xIndex],y:number(row[yIndex])}))) });const all=[...grouped.values()].flat().map(point=>point.y).filter(value=>value!==null);if(!all.length){card.append(empty());return}const [min,max]=extent(all);const svg=baseSvg();axisText(svg,max.toLocaleString(),52,27,'end');axisText(svg,min.toLocaleString(),52,250,'end');axisText(svg,view.x.label||view.x.field,398,286,'middle');const count=Math.max(2,dataset.rows.length);[...grouped.entries()].forEach(([name,points],seriesIndex)=>{let segment=[];const flush=()=>{if(segment.length){svg.append(svgEl('polyline',{points:segment.join(' '),fill:'none',stroke:palette[seriesIndex%palette.length],'stroke-width':3,'stroke-linejoin':'round','stroke-linecap':'round'}));segment=[]}};points.forEach(point=>{if(point.y===null){flush();return}const x=scale(point.index,0,count-1,62,734),y=scale(point.y,min,max,246,24);segment.push(x+','+y);svg.append(svgEl('circle',{cx:x,cy:y,r:3,fill:palette[seriesIndex%palette.length]}))});flush()});card.append(svg);legend(card,[...grouped.keys()])}
737
+ function barChart(card,view,dataset){const xIndex=indexOf(dataset,view.x.field);const series=view.seriesField?[view.seriesField]:view.y;const values=[];const entries=[];if(view.seriesField){const groupIndex=indexOf(dataset,view.seriesField),yIndex=indexOf(dataset,view.y[0]);dataset.rows.forEach((row,index)=>{const value=number(row[yIndex]);if(value!==null){values.push(value);entries.push({index,value,name:row[groupIndex]??'',x:row[xIndex]??''})}})}else dataset.rows.forEach((row,index)=>view.y.forEach((field,seriesIndex)=>{const value=number(row[indexOf(dataset,field)]);if(value!==null){values.push(value);entries.push({index,value,name:field,seriesIndex,x:row[xIndex]??''})}}));if(!values.length){card.append(empty());return}const [min,max]=extent(values,true),svg=baseSvg(),zero=scale(0,min,max,246,24),groups=Math.max(1,dataset.rows.length),barWidth=Math.max(2,Math.min(36,620/(groups*Math.max(1,series.length))));svg.append(svgEl('line',{x1:58,y1:zero,x2:738,y2:zero,stroke:'var(--muted)','stroke-width':1.5}));entries.forEach((entry,entryIndex)=>{const seriesIndex=entry.seriesIndex??Math.max(0,series.indexOf(entry.name));const center=scale(entry.index+.5,0,groups,62,734);const offset=(seriesIndex-(series.length-1)/2)*barWidth;const y=scale(entry.value,min,max,246,24);svg.append(svgEl('rect',{x:center+offset-barWidth*.42,y:Math.min(y,zero),width:barWidth*.84,height:Math.max(1,Math.abs(zero-y)),rx:2,fill:palette[(seriesIndex<0?entryIndex:seriesIndex)%palette.length]}))});axisText(svg,max.toLocaleString(),52,27,'end');axisText(svg,min.toLocaleString(),52,250,'end');axisText(svg,view.x.label||view.x.field,398,286,'middle');card.append(svg);legend(card,series)}
738
+ function pieChart(card,view,dataset){const cIndex=indexOf(dataset,view.categoryField),vIndex=indexOf(dataset,view.valueField);const entries=dataset.rows.map(row=>({name:row[cIndex]??'',value:number(row[vIndex])??0})),total=entries.reduce((sum,item)=>sum+item.value,0);if(total<=0){card.append(empty());return}const svg=svgEl('svg',{viewBox:'0 0 760 300',role:'img',class:'chart','aria-label':'构成图'}),cx=235,cy=150,r=105;let angle=-Math.PI/2;entries.forEach((entry,index)=>{const next=angle+entry.value/total*Math.PI*2,x1=cx+Math.cos(angle)*r,y1=cy+Math.sin(angle)*r,x2=cx+Math.cos(next)*r,y2=cy+Math.sin(next)*r,large=next-angle>Math.PI?1:0;const path=svgEl('path',{d:'M '+cx+' '+cy+' L '+x1+' '+y1+' A '+r+' '+r+' 0 '+large+' 1 '+x2+' '+y2+' Z',fill:palette[index%palette.length]});svg.append(path);angle=next});entries.forEach((entry,index)=>{const y=46+index*25;svg.append(svgEl('circle',{cx:490,cy:y-4,r:5,fill:palette[index%palette.length]}));axisText(svg,entry.name+' '+(entry.value/total*100).toFixed(1)+'%',505,y)});card.append(svg)}
739
+ function scatterChart(card,view,dataset){const xi=indexOf(dataset,view.xField),yi=indexOf(dataset,view.yField),points=dataset.rows.map(row=>[number(row[xi]),number(row[yi])]).filter(point=>point[0]!==null&&point[1]!==null);if(!points.length){card.append(empty());return}const [xmin,xmax]=extent(points.map(point=>point[0])),[ymin,ymax]=extent(points.map(point=>point[1])),svg=baseSvg();points.forEach(point=>svg.append(svgEl('circle',{cx:scale(point[0],xmin,xmax,62,734),cy:scale(point[1],ymin,ymax,246,24),r:4,fill:palette[0],opacity:.82})));axisText(svg,ymax.toLocaleString(),52,27,'end');axisText(svg,ymin.toLocaleString(),52,250,'end');axisText(svg,xmin.toLocaleString(),62,270);axisText(svg,xmax.toLocaleString(),734,270,'end');axisText(svg,view.xField,398,288,'middle');card.append(svg)}
740
+ const header=document.getElementById('report-header');header.append(el('h1','',report.title));if(report.summary)header.append(el('p','',report.summary));header.append(el('p','report-count',report.datasets.length+'个数据集 · '+report.views.length+'个视图'));
741
+ const widths=new Map();let firstChartPlaced=false;report.views.forEach(view=>{if(view.kind==='metric')return;if(view.width){widths.set(view.id,view.width);if(['line','bar','pie','scatter'].includes(view.kind))firstChartPlaced=true;return}const width=view.kind==='table'||!firstChartPlaced?'full':'half';widths.set(view.id,width);if(['line','bar','pie','scatter'].includes(view.kind))firstChartPlaced=true});
742
+ const metricBand=document.getElementById('metric-band');const metrics=report.views.filter(view=>view.kind==='metric');if(metrics.length===0)metricBand.remove();else metrics.forEach(view=>{const dataset=datasetFor(view.datasetId),metric=el('article','metric');metric.append(el('p','metric-label',titleFor(view)));if(!dataset||dataset.rows.length===0)metric.append(el('p','metric-value','—'));else{const value=number(dataset.rows[0][indexOf(dataset,view.field)]);metric.append(el('p','metric-value',value===null?'—':(view.format==='percent'?(value*100).toLocaleString()+'%':value.toLocaleString())))}metricBand.append(metric)});
743
+ const dashboard=document.getElementById('dashboard');report.views.filter(view=>view.kind!=='metric').forEach(view=>{const dataset=datasetFor(view.datasetId),card=el('article','view '+(widths.get(view.id)==='full'?'full ':'')+view.kind);card.append(el('h2','',titleFor(view)));if(!dataset||dataset.rows.length===0)card.append(empty());else if(view.kind==='table')card.append(tableFor(dataset,view.columns));else{if(view.kind==='line')lineChart(card,view,dataset);if(view.kind==='bar')barChart(card,view,dataset);if(view.kind==='pie')pieChart(card,view,dataset);if(view.kind==='scatter')scatterChart(card,view,dataset);card.append(detailsFor(dataset))}dashboard.append(card)});
744
+ document.getElementById('report-footer').textContent='由 DSH Data Agent 生成 · '+${escapeJsonForHtmlScript(generatedAt)}+' · 离线HTML';
745
+ })();
746
+ <\/script>
747
+ </body>
748
+ </html>`;
749
+ }
750
+ /** Atomically persist one report and return the report enriched with htmlPath. */
751
+ async function writeAnalysisHtml(report, options) {
752
+ const directory = resolve(options.cwd, ANALYSIS_REPORT_DIRECTORY);
753
+ const relativePath = analysisArtifactRelativePath(report.title, options.outputName);
754
+ const htmlPath = resolve(options.cwd, relativePath);
755
+ const complete = {
756
+ ...report,
757
+ htmlPath
758
+ };
759
+ const basename = analysisFileSegment(options.outputName ?? report.title, "分析报告");
760
+ const temporaryPath = resolve(directory, `.${basename}.${randomUUID()}.tmp`);
761
+ try {
762
+ await mkdir(directory, { recursive: true });
763
+ await writeFile(temporaryPath, renderAnalysisHtml(complete, options.generatedAt), {
764
+ encoding: "utf8",
765
+ flag: "wx"
766
+ });
767
+ await link(temporaryPath, htmlPath);
768
+ await unlink(temporaryPath).catch(() => void 0);
769
+ } catch (error) {
770
+ await unlink(temporaryPath).catch(() => void 0);
771
+ const message = error instanceof Error ? error.message : String(error);
772
+ const detail = error?.code === "EEXIST" ? "目标文件已存在,请使用更具体的outputName" : message;
773
+ throw new Error(`render-analysis: 保存Dashboard HTML失败(${htmlPath}):${detail}`, { cause: error });
774
+ }
775
+ return complete;
776
+ }
777
+ //#endregion
778
+ //#region src/presentation-text.ts
779
+ /** Surface-neutral control-sequence sanitization for generic tool cards. */
780
+ const CONTROL_ESCAPE = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/gu;
781
+ const OSC_SEQUENCE = /\u001b\][\s\S]*?(?:\u0007|\u001b\\)/gu;
782
+ const CSI_SEQUENCE = /\u001b\[[0-?]*[ -/]*[@-~]/gu;
783
+ const ESC_SEQUENCE = /\u001b(?:[@-_]|[ -/]+[@-~]?)/gu;
784
+ /** Remove control effects while keeping their presence visible to the user. */
785
+ function sanitizePresentationText(value) {
786
+ return String(value ?? "").replace(OSC_SEQUENCE, "⟦OSC⟧").replace(CSI_SEQUENCE, "⟦ESC⟧").replace(ESC_SEQUENCE, "⟦ESC⟧").replace(/\r\n?/gu, "\\n").replace(/\n/gu, "\\n").replace(/\t/gu, "\\t").replace(CONTROL_ESCAPE, (character) => `\\x${character.codePointAt(0).toString(16).padStart(2, "0")}`);
787
+ }
788
+ //#endregion
813
789
  //#region src/tool.ts
814
790
  /** Cordis plugin name (diagnostics only). */
815
791
  const name = "data-agent-tool";
@@ -852,7 +828,7 @@ function validateSingleSql(sql, toolName) {
852
828
  assertSingleStatement(sql, toolName);
853
829
  }
854
830
  /**
855
- * The Web-only render-analysis tool (D1-D5): one call builds one versioned
831
+ * The surface-neutral render-analysis tool (D1-D5): one call builds one versioned
856
832
  * analysis report from 1-6 read-only datasets and 1-8 views. The full report
857
833
  * is persisted as presentationMeta; the model only receives a short summary
858
834
  * (output.render), never the rows themselves.
@@ -860,7 +836,7 @@ function validateSingleSql(sql, toolName) {
860
836
  function defineRenderAnalysisTool(ctx, resolved) {
861
837
  return defineTool({
862
838
  name: "render-analysis",
863
- description: "Web only: render one versioned analysis report (v1) from 1-6 read-only datasets and 1-8 metric, line, bar, pie, scatter, or table views. First use sql-query to inspect and verify data, then call this tool only when visualization adds value. Use one primary chart for a simple relationship or 3-6 complementary views for multi-metric, time-series, or segmented analysis. Put aggregation, Top N, and sorting in SQL, and add ORDER BY for line or time datasets. Reuse a dataset across views via datasetId; each dataset runs once. Arbitrary chart options, scripts, HTML, CSS, and URLs are not accepted. Empty datasets are valid and render as no-data states.",
839
+ description: "Render one versioned analysis report (v1) from 1-6 read-only datasets using 1-8 metric, line, bar, pie, scatter, or table views, then save an offline Dashboard HTML file under analysis-reports/ in the current session workspace. First use sql-query to inspect and verify data, then call this tool only when visualization adds value. Use one primary chart for a simple relationship or 3-6 complementary views for multi-metric, time-series, or segmented analysis. Put aggregation, Top N, and sorting in SQL, and add ORDER BY for line or time datasets. Reuse a dataset across views via datasetId; each dataset runs once. Arbitrary chart options, scripts, HTML, CSS, and URLs are not accepted. Empty datasets are valid and render as no-data states.",
864
840
  parameters: RENDER_ANALYSIS_PARAMETERS,
865
841
  output: {
866
842
  schema: ANALYSIS_REPORT_OUTPUT_SCHEMA,
@@ -872,14 +848,18 @@ function defineRenderAnalysisTool(ctx, resolved) {
872
848
  },
873
849
  presentCall: (args) => ({
874
850
  card: "generic",
875
- kind: "read",
876
- title: "render-analysis《" + args.title + "》",
877
- rawInput: args.title
851
+ kind: "edit",
852
+ title: "render-analysis《" + sanitizePresentationText(args.title) + "》",
853
+ rawInput: sanitizePresentationText(args.title),
854
+ locations: [{ path: analysisArtifactRelativePath(args.title, args.outputName) }]
878
855
  }),
879
856
  presentResult: (args, result) => ({
880
857
  card: "generic",
881
- title: "render-analysis《" + args.title + "》",
882
- content: result.content
858
+ title: "render-analysis《" + sanitizePresentationText(args.title) + "》",
859
+ content: result.content.map((item) => item.type === "text" ? {
860
+ ...item,
861
+ text: sanitizePresentationText(item.text)
862
+ } : item)
883
863
  }),
884
864
  async execute(args, exec) {
885
865
  const request = parseAnalysisRequest(args);
@@ -928,7 +908,11 @@ function defineRenderAnalysisTool(ctx, resolved) {
928
908
  };
929
909
  const bytes = reportJsonBytes(report);
930
910
  if (bytes > 524288) throw new Error("render-analysis: 报告 JSON 超过 524288 字节上限(当前 " + bytes + " 字节);请聚合、筛选或拆分报告,不得静默删减数据");
931
- return report;
911
+ const sessionCwd = exec.agent?.session?.header?.cwd;
912
+ return await writeAnalysisHtml(report, {
913
+ cwd: typeof sessionCwd === "string" && sessionCwd.length > 0 ? sessionCwd : process.cwd(),
914
+ outputName: request.outputName
915
+ });
932
916
  }
933
917
  });
934
918
  }
@@ -953,7 +937,7 @@ function apply(ctx, config) {
953
937
  parameters: { sql: {
954
938
  type: "string",
955
939
  required: true,
956
- description: "一条只读 SQL,如 \"SELECT * FROM orders LIMIT 5;\"、\"SHOW TABLES;\"、\"DESCRIBE users;\""
940
+ description: "一条符合当前数据库方言的只读 SQL,如 \"SELECT * FROM orders;\"、\"SHOW TABLES;\"、\"DESCRIBE users;\""
957
941
  } },
958
942
  output: {
959
943
  schema: {
@@ -1075,7 +1059,7 @@ function apply(ctx, config) {
1075
1059
  parameters: { sql: {
1076
1060
  type: "string",
1077
1061
  required: true,
1078
- description: "一条 SQL 文本(或客户端命令),如 \"SHOW TABLES;\"、\"DESCRIBE users;\"、\"SELECT * FROM orders LIMIT 5;\""
1062
+ description: "一条符合当前数据库方言的 SQL 文本(或数据库命令),如 \"SHOW TABLES;\"、\"DESCRIBE users;\"、\"SELECT * FROM orders;\""
1079
1063
  } },
1080
1064
  output: {
1081
1065
  schema: {
@@ -1122,7 +1106,7 @@ function apply(ctx, config) {
1122
1106
  return runRedactedClientQuery(ctx, connection, classifyStatement(args.sql, connection.type) === "read" ? enforceReadRowLimit(args.sql, connection.type, resolved.maxRows) : args.sql, runnerOptions(resolved), exec.signal);
1123
1107
  }
1124
1108
  }));
1125
- if (ctx.get("webServer") !== void 0) ctx.tools.register(defineRenderAnalysisTool(ctx, resolved));
1109
+ ctx.tools.register(defineRenderAnalysisTool(ctx, resolved));
1126
1110
  }
1127
1111
  //#endregion
1128
1112
  export { name as i, apply as n, inject as r, Config as t };
package/lib/tool.js CHANGED
@@ -1,2 +1,2 @@
1
- import { i as name, n as apply, r as inject, t as Config } from "./tool-DVh61An-.js";
1
+ import { i as name, n as apply, r as inject, t as Config } from "./tool-ZTOS4B33.js";
2
2
  export { Config, apply, inject, name };
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Offline HTML artifact for one validated AnalysisReportV1.
3
+ *
4
+ * The generated page has no network/runtime dependencies. Untrusted report
5
+ * strings stay inside escaped JSON and are projected with textContent only;
6
+ * chart geometry is derived from already-validated finite numeric fields.
7
+ * @module @yejiming/dsh-data-agent/analysis-html
8
+ */
9
+ import type { AnalysisReportV1 } from './analysis.ts';
10
+ export declare const ANALYSIS_REPORT_DIRECTORY = "analysis-reports";
11
+ /** Convert a report title/output name into a bounded, readable filename segment. */
12
+ export declare function analysisFileSegment(value: string, fallback: string): string;
13
+ /** Relative path shared by the writer and DSH's mutation presentation. */
14
+ export declare function analysisArtifactRelativePath(title: string, outputName?: string): string;
15
+ /** Escape JSON so data cannot close its application/json script element. */
16
+ export declare function escapeJsonForHtmlScript(value: unknown): string;
17
+ /** Render one complete, offline Dashboard document. */
18
+ export declare function renderAnalysisHtml(report: AnalysisReportV1, generatedAt?: string): string;
19
+ export interface WriteAnalysisHtmlOptions {
20
+ cwd: string;
21
+ outputName?: string;
22
+ generatedAt?: string;
23
+ }
24
+ /** Atomically persist one report and return the report enriched with htmlPath. */
25
+ export declare function writeAnalysisHtml(report: AnalysisReportV1, options: WriteAnalysisHtmlOptions): Promise<AnalysisReportV1 & {
26
+ htmlPath: string;
27
+ }>;
@@ -87,6 +87,8 @@ export interface AnalysisDatasetRequestV1 {
87
87
  /** The wire request accepted by the render-analysis tool. */
88
88
  export interface AnalysisRequestV1 {
89
89
  title: string;
90
+ /** Semantic output basename; directory is always analysis-reports/. */
91
+ outputName?: string;
90
92
  summary?: string;
91
93
  datasets: AnalysisDatasetRequestV1[];
92
94
  views: AnalysisViewV1[];
@@ -102,6 +104,8 @@ export interface AnalysisReportV1 {
102
104
  version: typeof ANALYSIS_REPORT_VERSION;
103
105
  title: string;
104
106
  summary?: string;
107
+ /** Absolute path of the generated HTML artifact (absent on legacy v1 meta). */
108
+ htmlPath?: string;
105
109
  datasets: AnalysisDatasetResultV1[];
106
110
  views: AnalysisViewV1[];
107
111
  }
@@ -136,7 +140,7 @@ export declare function rowsToArrays(columns: string[], rows: readonly Record<st
136
140
  /** JSON-encoded UTF-8 size of the normalized report (the 512 KiB bound). */
137
141
  export declare function reportJsonBytes(report: AnalysisReportV1): number;
138
142
  /** One-line model-facing summary; never re-injects rows into model context (D5). */
139
- export declare function formatAnalysisSummary(report: Pick<AnalysisReportV1, 'title' | 'datasets' | 'views'>): string;
143
+ export declare function formatAnalysisSummary(report: Pick<AnalysisReportV1, 'title' | 'datasets' | 'views' | 'htmlPath'>): string;
140
144
  /** The view union: exactly the six supported kinds, nothing else. */
141
145
  export declare const ANALYSIS_VIEWS_SCHEMA: {
142
146
  readonly oneOf: readonly [{
@@ -423,6 +427,10 @@ export declare const RENDER_ANALYSIS_PARAMETERS: {
423
427
  readonly required: true;
424
428
  readonly description: "报告标题,如「月度经营分析」";
425
429
  };
430
+ readonly outputName: {
431
+ readonly type: "string";
432
+ readonly description: "可选语义化HTML文件名(仅basename,可省略.html),如「电商经营全景分析-2023-09至2026-08」;缺省时使用title,不要使用随机ID";
433
+ };
426
434
  readonly summary: {
427
435
  readonly type: "string";
428
436
  readonly description: "可选一句话结论/摘要,显示在报告头部";
@@ -748,6 +756,10 @@ export declare const ANALYSIS_REPORT_OUTPUT_SCHEMA: {
748
756
  readonly summary: {
749
757
  readonly type: "string";
750
758
  };
759
+ readonly htmlPath: {
760
+ readonly type: "string";
761
+ readonly required: true;
762
+ };
751
763
  readonly datasets: {
752
764
  readonly type: "array";
753
765
  readonly required: true;
@@ -1,6 +1,5 @@
1
1
  import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots';
2
- /** Database kinds offered by the connection form. */
3
- export type DatabaseType = 'mysql' | 'postgres' | 'sqlite' | 'oracle' | 'hive' | 'impala';
2
+ export type { DatabaseType } from '../database-types.ts';
4
3
  /** The sessions-list slice the workbench needs (structural; avoids a runtime import). */
5
4
  export interface SessionListLike {
6
5
  byId: Record<string, {
@@ -0,0 +1,13 @@
1
+ import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots';
2
+ export interface StructuredWorkbenchResult {
3
+ kind: 'table';
4
+ columns: string[];
5
+ rows: Record<string, string | null>[];
6
+ elapsedMs: number;
7
+ truncated: boolean;
8
+ maxRows: number;
9
+ }
10
+ export declare function QueryResultTable({ result, t, }: {
11
+ result: StructuredWorkbenchResult;
12
+ t: TranslateNS<'data-agent'>;
13
+ }): import("react").JSX.Element;