dsh-ppt 0.34.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.en.md +14 -17
  3. package/README.md +14 -17
  4. package/docs/USAGE.en.md +44 -35
  5. package/docs/USAGE.md +45 -36
  6. package/docs/VALIDATION.md +4 -0
  7. package/docs/assets/intro/screen-en.webp +0 -0
  8. package/docs/assets/intro/screen-zh.webp +0 -0
  9. package/docs/assets/intro/workflow-en-dark.svg +1 -1
  10. package/docs/assets/intro/workflow-en-light.svg +1 -1
  11. package/docs/assets/intro/workflow-en-mobile-dark.svg +1 -1
  12. package/docs/assets/intro/workflow-en-mobile-light.svg +1 -1
  13. package/docs/assets/intro/workflow-zh-dark.svg +1 -1
  14. package/docs/assets/intro/workflow-zh-light.svg +1 -1
  15. package/docs/assets/intro/workflow-zh-mobile-dark.svg +1 -1
  16. package/docs/assets/intro/workflow-zh-mobile-light.svg +1 -1
  17. package/lib/client.js +333 -45
  18. package/lib/execution.js +20 -2
  19. package/lib/tools.js +64 -2
  20. package/lib/types.d.ts +58 -1
  21. package/lib/workbench.js +18 -2
  22. package/package.json +2 -2
  23. package/skills/dsh-ppt/SKILL.md +34 -32
  24. package/skills/dsh-ppt/package.json +1 -1
  25. package/skills/dsh-ppt/references/office-pack.md +124 -0
  26. package/skills/dsh-ppt/references/research-plan.md +93 -62
  27. package/skills/dsh-ppt/scripts/build-deck.mjs +60 -2
  28. package/skills/dsh-ppt/scripts/deck-absorb.mjs +2 -0
  29. package/skills/dsh-ppt/scripts/deck-advanced.mjs +198 -29
  30. package/skills/dsh-ppt/scripts/deck-brand-kit.mjs +13 -0
  31. package/skills/dsh-ppt/scripts/deck-charts-exec.mjs +805 -0
  32. package/skills/dsh-ppt/scripts/deck-chrome.mjs +10 -1
  33. package/skills/dsh-ppt/scripts/deck-compose.mjs +386 -0
  34. package/skills/dsh-ppt/scripts/deck-core.mjs +128 -14
  35. package/skills/dsh-ppt/scripts/deck-delivery.mjs +141 -3
  36. package/skills/dsh-ppt/scripts/deck-evidence.mjs +811 -118
  37. package/skills/dsh-ppt/scripts/deck-export.mjs +652 -0
  38. package/skills/dsh-ppt/scripts/deck-i18n.mjs +170 -0
  39. package/skills/dsh-ppt/scripts/deck-layouts.mjs +72 -8
  40. package/skills/dsh-ppt/scripts/deck-office.mjs +833 -38
@@ -17,11 +17,13 @@
17
17
  * 经智能导演 + smartLayout 生成 5–20 页高品味演示文稿。
18
18
  */
19
19
 
20
- import { lstatSync, readdirSync, readFileSync } from 'node:fs'
20
+ import { lstatSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
21
21
  import { createRequire } from 'node:module'
22
22
  import { basename, extname, join, posix, resolve } from 'node:path'
23
23
  import { inflateRawSync, inflateSync } from 'node:zlib'
24
24
  import { promoteMarkdownSlides, inferThemeFromContent } from './deck-director.mjs'
25
+ import { buildHybridEnrichmentPlan, mergeHybridEvidence } from './deck-evidence.mjs'
26
+ import { loadWorkspaceBrandKit } from './deck-brand-kit.mjs'
25
27
 
26
28
  const MAX_OFFICE_BYTES = 32 * 1024 * 1024
27
29
  const MAX_ENTRY_BYTES = 32 * 1024 * 1024
@@ -1030,6 +1032,7 @@ function profileTabularWorkbook(sheets, fileName, en) {
1030
1032
  title: baseTitle,
1031
1033
  language: en ? 'en' : 'zh',
1032
1034
  slides,
1035
+ _sheets: sheets,
1033
1036
  stats: {
1034
1037
  sourceFormat: extname(fileName).slice(1).toLowerCase() || 'xlsx',
1035
1038
  sheetCount: sheets.length,
@@ -1432,6 +1435,8 @@ function parseDocxArchive(bytes, fileName) {
1432
1435
  title,
1433
1436
  language: en ? 'en' : 'zh',
1434
1437
  slides: promoted,
1438
+ _rawSections: sections,
1439
+ _embeddedMedia: [...mediaDataUris.values()],
1435
1440
  stats: {
1436
1441
  sourceFormat: 'docx',
1437
1442
  sectionCount: sections.length,
@@ -1839,6 +1844,7 @@ function parsePdfDocument(bytes, fileName, langHint) {
1839
1844
  title,
1840
1845
  language: en ? 'en' : 'zh',
1841
1846
  slides: promoted,
1847
+ _rawSections: sections,
1842
1848
  stats: {
1843
1849
  sourceFormat: 'pdf',
1844
1850
  lineCount: lines.length,
@@ -1848,6 +1854,315 @@ function parsePdfDocument(bytes, fileName, langHint) {
1848
1854
  }
1849
1855
  }
1850
1856
 
1857
+ // ---------------------------------------------------------------------------
1858
+ // Zero-dep Local Image Inspector (PNG / JPEG / WebP header parser + Smart Photo Role)
1859
+ // ---------------------------------------------------------------------------
1860
+
1861
+ const PORTRAIT_HINT_RE = /(?:team|founder|ceo|cto|people|person|portrait|avatar|staff|speaker|headshot|团队|合影|人像|人物|头像|嘉宾|讲师|员工|领导)/i
1862
+ const COVER_HINT_RE = /(?:cover|hero|banner|keynote|title|overview|封面|主图|全景|头图|开场)/i
1863
+ const MOBILE_HINT_RE = /(?:mobile|phone|ios|android|app|wechat|miniapp|手机|移动端|小程序|竖屏)/i
1864
+ const BROWSER_HINT_RE = /(?:ui|screen|screenshot|dashboard|web|browser|demo|console|admin|portal|界面|截图|看板|系统|后台|工作台|网页|演示)/i
1865
+
1866
+ function parseImageDimensions(bytes) {
1867
+ if (!bytes || bytes.length < 16) return null
1868
+ // PNG: IHDR width/height at offsets 16..23
1869
+ if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47 && bytes.length >= 24) {
1870
+ return { mime: 'image/png', width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) }
1871
+ }
1872
+ // JPEG: scan SOF0/1/2/3/5/6/7/9/10/11/13/14/15 markers
1873
+ if (bytes[0] === 0xff && bytes[1] === 0xd8) {
1874
+ let offset = 2
1875
+ while (offset + 4 < bytes.length) {
1876
+ if (bytes[offset] !== 0xff) break
1877
+ while (offset < bytes.length && bytes[offset] === 0xff) offset += 1
1878
+ const marker = bytes[offset]
1879
+ offset += 1
1880
+ if (marker === 0xd9 || marker === 0xda) break
1881
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) continue
1882
+ if (offset + 2 > bytes.length) break
1883
+ const len = bytes.readUInt16BE(offset)
1884
+ if (len < 2 || offset + len > bytes.length) break
1885
+ if ([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf].includes(marker) && len >= 7) {
1886
+ return { mime: 'image/jpeg', height: bytes.readUInt16BE(offset + 3), width: bytes.readUInt16BE(offset + 5) }
1887
+ }
1888
+ offset += len
1889
+ }
1890
+ return { mime: 'image/jpeg', width: 0, height: 0 }
1891
+ }
1892
+ // WebP: VP8 / VP8L / VP8X
1893
+ if (bytes.length >= 30 && bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP') {
1894
+ const chunk = bytes.toString('ascii', 12, 16)
1895
+ if (chunk === 'VP8 ') {
1896
+ return { mime: 'image/webp', width: bytes.readUInt16LE(26) & 0x3fff, height: bytes.readUInt16LE(28) & 0x3fff }
1897
+ }
1898
+ if (chunk === 'VP8L') {
1899
+ const bits = bytes.readUInt32LE(21)
1900
+ return { mime: 'image/webp', width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 }
1901
+ }
1902
+ if (chunk === 'VP8X') {
1903
+ const w = 1 + (bytes[24] | (bytes[25] << 8) | (bytes[26] << 16))
1904
+ const h = 1 + (bytes[27] | (bytes[28] << 8) | (bytes[29] << 16))
1905
+ return { mime: 'image/webp', width: w, height: h }
1906
+ }
1907
+ }
1908
+ return null
1909
+ }
1910
+
1911
+ export function inspectImageBytes(bytes, fileName = 'image.png') {
1912
+ const buf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes)
1913
+ const dims = parseImageDimensions(buf)
1914
+ const width = dims?.width || 0
1915
+ const height = dims?.height || 0
1916
+ const aspectRatio = width > 0 && height > 0 ? Math.round((width / height) * 100) / 100 : 1
1917
+ const orientation = width > 0 && height > 0
1918
+ ? (aspectRatio >= 1.15 ? 'landscape' : (aspectRatio <= 0.85 ? 'portrait' : 'square'))
1919
+ : 'unknown'
1920
+ const baseName = cleanLine(fileName.replace(/\.[^.]+$/, ''))
1921
+ const isPortraitSubject = orientation === 'portrait' || PORTRAIT_HINT_RE.test(baseName)
1922
+ const recommendedFocalPoint = isPortraitSubject ? 'top' : 'center'
1923
+
1924
+ let recommendedRole = 'section'
1925
+ let recommendedLayout = 'image-right'
1926
+ if (COVER_HINT_RE.test(baseName) && orientation !== 'portrait') {
1927
+ recommendedRole = 'cover'
1928
+ recommendedLayout = 'cover'
1929
+ } else if (MOBILE_HINT_RE.test(baseName) || (orientation === 'portrait' && aspectRatio <= 0.68)) {
1930
+ recommendedRole = 'mockup-mobile'
1931
+ recommendedLayout = 'mockup[mobile]'
1932
+ } else if (BROWSER_HINT_RE.test(baseName)) {
1933
+ recommendedRole = 'mockup-browser'
1934
+ recommendedLayout = 'mockup[browser]'
1935
+ } else if (orientation === 'landscape' && width >= 1200 && height >= 650) {
1936
+ recommendedRole = 'section'
1937
+ recommendedLayout = 'image-right'
1938
+ }
1939
+
1940
+ return {
1941
+ fileName,
1942
+ label: baseName || fileName,
1943
+ mime: dims?.mime || detectImageMime(buf) || 'image/png',
1944
+ sizeBytes: buf.length,
1945
+ width,
1946
+ height,
1947
+ aspectRatio,
1948
+ orientation,
1949
+ recommendedRole,
1950
+ recommendedLayout,
1951
+ recommendedFocalPoint,
1952
+ }
1953
+ }
1954
+
1955
+ export function inspectLocalImage(filePath, cwd = '.') {
1956
+ const full = resolve(String(cwd || '.'), String(filePath || '').trim())
1957
+ const stat = lstatSync(full)
1958
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_IMAGE_BYTES) {
1959
+ fail('图片需为 5 MiB 内的普通文件:' + full)
1960
+ }
1961
+ const bytes = readFileSync(full)
1962
+ return {
1963
+ path: full,
1964
+ ...inspectImageBytes(bytes, basename(full)),
1965
+ }
1966
+ }
1967
+
1968
+ // ---------------------------------------------------------------------------
1969
+ // Natural-Language Instructions Parser & Smart Filter Helpers
1970
+ // ---------------------------------------------------------------------------
1971
+
1972
+ function parseUserInstructions(rawInstructions = '') {
1973
+ const text = cleanLine(rawInstructions)
1974
+ if (!text) return { raw: '', targetSlides: null, skipAgenda: false, focusTerms: [], coverHints: [], mockupHints: [] }
1975
+
1976
+ const slideMatch = /(?:约|大概|控制[在为]?|一共|总共|做|生成)?\s*(\d{1,2})\s*(?:页|张|slides?|pages?)/i.exec(text)
1977
+ const parsedCount = slideMatch ? Number(slideMatch[1]) : null
1978
+ const targetSlides = Number.isInteger(parsedCount) && parsedCount >= 3 && parsedCount <= 40 ? parsedCount : null
1979
+ const skipAgenda = /不要目录|跳过目录|无需目录|no\s+agenda|skip\s+agenda/i.test(text)
1980
+
1981
+ const coverHints = []
1982
+ const mockupHints = []
1983
+ for (const m of text.matchAll(/([A-Za-z0-9_\u4e00-\u9fa5-]+\.(?:png|jpe?g|webp))\s*(?:放|做|当|作为|用于|in|as|on)?\s*(封面|cover|主图|hero|样机|mockup|手机|浏览器|截图)/gi)) {
1984
+ const fn = m[1].toLowerCase()
1985
+ if (/封面|cover|主图|hero/i.test(m[2])) coverHints.push(fn)
1986
+ else mockupHints.push(fn)
1987
+ }
1988
+
1989
+ const focusTerms = text
1990
+ .replace(/[,。;:、,.!!??()()【】[\]「」"'`]/g, ' ')
1991
+ .split(/\s+/)
1992
+ .map(t => t.trim())
1993
+ .filter(t => t.length >= 2 && !/^(?:帮我|请把|生成|制作|一个|一份|按照|要求|控制|左右|不要|跳过|封面|目录|ppt|deck|slides?|pages?|with|from|the|and|for)$/i.test(t))
1994
+ .slice(0, 14)
1995
+
1996
+ return { raw: text, targetSlides, skipAgenda, focusTerms, coverHints, mockupHints }
1997
+ }
1998
+
1999
+ function filterSheetsByInclude(sheets, includeSheets) {
2000
+ if (!Array.isArray(includeSheets) || includeSheets.length === 0) return sheets
2001
+ const needles = includeSheets.map(s => String(s ?? '').trim().toLowerCase()).filter(Boolean)
2002
+ if (needles.length === 0) return sheets
2003
+ const filtered = sheets.filter(sh => {
2004
+ const name = String(sh.name || '').toLowerCase()
2005
+ return needles.some(n => name === n || name.includes(n))
2006
+ })
2007
+ return filtered.length > 0 ? filtered : sheets
2008
+ }
2009
+
2010
+ function applyMaxSlidesBudget(slides, maxSlides, focusTerms = []) {
2011
+ if (!Number.isInteger(maxSlides) || maxSlides < 3 || slides.length <= maxSlides) return slides
2012
+ const first = slides[0]
2013
+ const last = slides[slides.length - 1]
2014
+ const hasCover = first?.layout === 'cover'
2015
+ const hasClosing = last?.layout === 'closing'
2016
+ const middle = slides.slice(hasCover ? 1 : 0, hasClosing ? -1 : undefined)
2017
+ const keepBudget = Math.max(1, maxSlides - (hasCover ? 1 : 0) - (hasClosing ? 1 : 0))
2018
+ if (middle.length <= keepBudget) return slides
2019
+
2020
+ const scored = middle.map((slide, origIdx) => {
2021
+ const hay = [slide.kicker, slide.title, slide.subtitle, slide.takeaway, ...(slide.bullets || [])].filter(Boolean).join(' ').toLowerCase()
2022
+ let score = 0
2023
+ if (slide.layout === 'kpi') score += 5
2024
+ if (slide.layout === 'chart-split' || slide.layout === 'sankey' || slide.layout === 'gantt' || slide.layout === 'marimekko') score += 4
2025
+ if (slide.layout === 'mockup' || slide.layout === 'image-right' || slide.layout === 'image-left') score += 3.5
2026
+ if (slide.layout === 'table' && /附录|Appendix|明细/i.test(`${slide.kicker || ''} ${slide.title || ''}`)) score -= 2.5
2027
+ if (slide.layout === 'agenda') score -= 1.5
2028
+ for (const term of focusTerms) {
2029
+ if (hay.includes(term.toLowerCase())) score += 3
2030
+ }
2031
+ return { slide, origIdx, score }
2032
+ })
2033
+
2034
+ const chosen = [...scored]
2035
+ .sort((a, b) => b.score - a.score || a.origIdx - b.origIdx)
2036
+ .slice(0, keepBudget)
2037
+ .sort((a, b) => a.origIdx - b.origIdx)
2038
+ .map(x => x.slide)
2039
+
2040
+ return [
2041
+ ...(hasCover ? [first] : []),
2042
+ ...chosen,
2043
+ ...(hasClosing ? [last] : []),
2044
+ ]
2045
+ }
2046
+
2047
+ // ---------------------------------------------------------------------------
2048
+ // Live Excel-to-dataModel Binder (bindDataModel: true)
2049
+ // ---------------------------------------------------------------------------
2050
+
2051
+ function buildAutoDataModelFromSheets(sheetEntries = []) {
2052
+ if (!Array.isArray(sheetEntries) || sheetEntries.length === 0) return null
2053
+ const sources = []
2054
+ const metrics = []
2055
+ const bindingsBySheet = new Map()
2056
+
2057
+ for (let sIdx = 0; sIdx < sheetEntries.length && sources.length < 6; sIdx += 1) {
2058
+ const entry = sheetEntries[sIdx]
2059
+ const rows = entry?.rows
2060
+ if (!Array.isArray(rows) || rows.length < 2) continue
2061
+ const headers = rows[0].slice(0, 12)
2062
+ const dataRows = rows.slice(1, 30)
2063
+ const cols = profileColumns([headers, ...dataRows])
2064
+ const numCols = cols.filter(c => c.isNumeric)
2065
+ if (numCols.length === 0) continue
2066
+
2067
+ const sourceId = `sheet${sources.length + 1}`
2068
+ const cleanRows = [
2069
+ headers.map(h => cleanLine(h) || 'Col'),
2070
+ ...dataRows.map(r => headers.map((_, ci) => {
2071
+ const p = parseCellNumber(r[ci])
2072
+ if (cols[ci]?.isNumeric && p.ok) {
2073
+ return p.isPercent ? `${p.num}%` : p.num
2074
+ }
2075
+ return cleanLine(r[ci] ?? '')
2076
+ })),
2077
+ ]
2078
+ sources.push({
2079
+ id: sourceId,
2080
+ name: cleanLine(entry.name || sourceId).slice(0, 100),
2081
+ kind: 'table',
2082
+ rows: cleanRows,
2083
+ })
2084
+
2085
+ const primaryCol = numCols[0]
2086
+ const colLetter = String.fromCharCode(65 + primaryCol.index)
2087
+ const catCol = cols.find(c => !c.isNumeric) || cols[0]
2088
+ const boundCells = []
2089
+ for (let rIdx = 0; rIdx < dataRows.length && metrics.length < 48; rIdx += 1) {
2090
+ const p = primaryCol.parsed[rIdx]
2091
+ if (!p?.ok) continue
2092
+ const cellAddr = `${colLetter}${rIdx + 2}`
2093
+ const metricId = `${sourceId}r${rIdx + 2}c${primaryCol.index + 1}`
2094
+ const rowLabel = cleanLine(dataRows[rIdx][catCol.index] || `Row${rIdx + 1}`)
2095
+ metrics.push({
2096
+ id: metricId,
2097
+ label: `${entry.name} · ${rowLabel} (${primaryCol.header})`.slice(0, 110),
2098
+ kind: 'source',
2099
+ source: { sourceId, cell: cellAddr },
2100
+ format: {
2101
+ style: primaryCol.isPercentCol ? 'percent' : 'number',
2102
+ digits: primaryCol.isPercentCol ? 1 : (Number.isInteger(p.num) ? 0 : 1),
2103
+ ...(!primaryCol.isPercentCol && primaryCol.unit ? { unit: primaryCol.unit.slice(0, 20) } : {}),
2104
+ },
2105
+ })
2106
+ boundCells.push({ rowIndex: rIdx, metricId, value: p.num, label: rowLabel })
2107
+ }
2108
+ if (boundCells.length > 0) {
2109
+ bindingsBySheet.set(entry.name, { sourceId, primaryCol, boundCells })
2110
+ }
2111
+ }
2112
+
2113
+ if (sources.length === 0 || metrics.length === 0) return null
2114
+ return {
2115
+ dataModel: { schemaVersion: 1, sources, metrics },
2116
+ bindingsBySheet,
2117
+ }
2118
+ }
2119
+
2120
+ function bindSlidesWithAutoDataModel(slides, autoBound) {
2121
+ if (!autoBound || !autoBound.bindingsBySheet?.size) return slides
2122
+ const usedMetrics = new Set()
2123
+ return slides.map((slide) => {
2124
+ // Bind first matching chart-split single-series primary values to {{metricId}}
2125
+ if ((slide.layout === 'chart-split' || slide.layout === 'chart') && slide.chart && Array.isArray(slide.chart.series) && slide.chart.series.length > 0) {
2126
+ const binding = autoBound.bindingsBySheet.get(slide.kicker)
2127
+ if (binding && slide.chart.kind !== 'waterfall') {
2128
+ const s0 = slide.chart.series[0]
2129
+ if (Array.isArray(s0.values) && s0.values.length === binding.boundCells.length) {
2130
+ const nextSeries = slide.chart.series.map((ser, idx) => {
2131
+ if (idx !== 0) return ser
2132
+ return {
2133
+ ...ser,
2134
+ values: binding.boundCells.map((bc) => {
2135
+ usedMetrics.add(bc.metricId)
2136
+ return `{{${bc.metricId}}}`
2137
+ }),
2138
+ }
2139
+ })
2140
+ return { ...slide, chart: { ...slide.chart, series: nextSeries } }
2141
+ }
2142
+ }
2143
+ }
2144
+ // Bind peak KPI item on Executive Summary KPI slide when available
2145
+ if (slide.layout === 'kpi' && Array.isArray(slide.items) && slide.items.length > 0) {
2146
+ const nextItems = slide.items.map((it) => {
2147
+ for (const [sheetName, binding] of autoBound.bindingsBySheet.entries()) {
2148
+ if (String(it.title || it.tag || '').includes(sheetName) && binding.boundCells.length > 0) {
2149
+ const peak = binding.boundCells.reduce((b, c) => (c.value > b.value ? c : b), binding.boundCells[0])
2150
+ usedMetrics.add(peak.metricId)
2151
+ const { unit: _dropUnit, ...restItem } = it
2152
+ return {
2153
+ ...restItem,
2154
+ value: `{{${peak.metricId}}}`,
2155
+ }
2156
+ }
2157
+ }
2158
+ return it
2159
+ })
2160
+ return { ...slide, items: nextItems }
2161
+ }
2162
+ return slide
2163
+ })
2164
+ }
2165
+
1851
2166
  // ---------------------------------------------------------------------------
1852
2167
  // Multi-Source Pack Ingestion (Directory or Mixed filePaths[] -> 1 Deck + Evidence Ledger)
1853
2168
  // ---------------------------------------------------------------------------
@@ -1874,11 +2189,10 @@ function readImageAsDataUri(resolvedFile) {
1874
2189
  return `data:${mime};base64,${buf.toString('base64')}`
1875
2190
  }
1876
2191
 
1877
- async function extractMultiSourcePack(rawFilePaths, options = {}) {
1878
- const cwd = resolve(String(options.cwd ?? '.'))
2192
+ function collectPackFiles(rawFilePaths, cwd, signal) {
1879
2193
  const resolvedFiles = []
1880
2194
  for (const fp of rawFilePaths) {
1881
- abort(options.signal)
2195
+ abort(signal)
1882
2196
  const full = resolve(cwd, String(fp ?? '').trim())
1883
2197
  let st
1884
2198
  try { st = lstatSync(full) } catch { fail('找不到素材路径:' + full, 'Source path not found: ' + full) }
@@ -1905,19 +2219,258 @@ async function extractMultiSourcePack(rawFilePaths, options = {}) {
1905
2219
  }
1906
2220
  }
1907
2221
  }
1908
-
1909
2222
  const uniqueFiles = [...new Set(resolvedFiles)]
1910
2223
  .sort((a, b) => packFilePriority(a) - packFilePriority(b) || basename(a).localeCompare(basename(b)))
1911
2224
  .slice(0, MAX_PACK_FILES)
1912
-
1913
2225
  if (uniqueFiles.length === 0) {
1914
2226
  fail('目录中未找到可导入的素材文件(支持 .xlsx / .csv / .tsv / .docx / .pdf / .png / .jpg / .webp)', 'No supported source files found')
1915
2227
  }
2228
+ return uniqueFiles
2229
+ }
2230
+
2231
+ function resolvePhotoRole(photoMeta, explicitRoles = {}, parsedInstr = null) {
2232
+ const fnameLower = photoMeta.fileName.toLowerCase()
2233
+ const stemLower = photoMeta.label.toLowerCase()
2234
+ for (const [k, v] of Object.entries(explicitRoles || {})) {
2235
+ const kl = String(k).toLowerCase()
2236
+ if (kl === fnameLower || kl === stemLower || fnameLower.includes(kl)) {
2237
+ const role = String(v || '').trim().toLowerCase()
2238
+ if (['cover', 'mockup', 'mockup-mobile', 'mockup-browser', 'gallery', 'full-bleed', 'section'].includes(role)) {
2239
+ return role
2240
+ }
2241
+ }
2242
+ }
2243
+ if (parsedInstr?.coverHints?.some(h => h === fnameLower || fnameLower.includes(h))) return 'cover'
2244
+ if (parsedInstr?.mockupHints?.some(h => h === fnameLower || fnameLower.includes(h))) {
2245
+ return photoMeta.orientation === 'portrait' ? 'mockup-mobile' : 'mockup-browser'
2246
+ }
2247
+ return photoMeta.recommendedRole
2248
+ }
2249
+
2250
+ /**
2251
+ * 精炼素材包体检模式(`inspectOnly: true`):
2252
+ * 零耗 Token 防爆:只输出结构化摘要(Excel 统计极值+推荐图型+前5行预览、Word/PDF 章节摘要+表格维度+内嵌图尺寸、
2253
+ * 照片像素/比例/防裁歪建议、本地 `[E1..Ek]` 证据台账,以及 Mode C 外部权威检索补充计划),供 AI 按用户要求精准编排 PPT。
2254
+ */
2255
+ export async function inspectOfficePack(options = {}) {
2256
+ abort(options.signal)
2257
+ const cwd = resolve(String(options.cwd ?? '.'))
2258
+ const rawList = Array.isArray(options.filePaths) && options.filePaths.length > 0
2259
+ ? options.filePaths
2260
+ : [options.filePath ?? options.path].filter(Boolean)
2261
+ if (rawList.length === 0) {
2262
+ fail('inspectOfficePack 需提供 filePath 或 filePaths')
2263
+ }
2264
+
2265
+ const uniqueFiles = collectPackFiles(rawList, cwd, options.signal)
2266
+ const todayYm = new Date().toISOString().slice(0, 7)
2267
+ const sources = []
2268
+ const excelSheets = []
2269
+ const docSections = []
2270
+ const photos = []
2271
+ const localEvidence = []
2272
+ let cjkHits = 0
2273
+ let primaryTopic = cleanLine(options.title || '')
2274
+
2275
+ for (let idx = 0; idx < uniqueFiles.length; idx += 1) {
2276
+ abort(options.signal)
2277
+ const file = uniqueFiles[idx]
2278
+ const fname = basename(file)
2279
+ const ext = extname(file).toLowerCase()
2280
+ const stat = lstatSync(file)
2281
+ const evId = `E${idx + 1}`
2282
+
2283
+ sources.push({ fileName: fname, path: file, format: ext.slice(1), sizeBytes: stat.size })
2284
+
2285
+ if (PACK_IMG_EXTS.has(ext)) {
2286
+ const meta = inspectLocalImage(file, cwd)
2287
+ cjkHits += (meta.label.match(/[\u3400-\u9fff]/g) || []).length
2288
+ photos.push({ ...meta, evidenceId: evId })
2289
+ localEvidence.push({
2290
+ id: evId,
2291
+ origin: 'local-file',
2292
+ claim: `本地视觉素材「${meta.label}」(${meta.width}×${meta.height}, ${meta.orientation})`,
2293
+ source: fname,
2294
+ date: todayYm,
2295
+ confidence: 'verified',
2296
+ })
2297
+ continue
2298
+ }
2299
+
2300
+ const single = await extractSingleOfficeFile({ ...options, filePath: file, filePaths: undefined })
2301
+ if (!primaryTopic && single.title) primaryTopic = single.title
2302
+ const sample = [single.title, ...(single.slides || []).slice(0, 4).map(s => s.title || '')].join(' ')
2303
+ cjkHits += (sample.match(/[\u3400-\u9fff]/g) || []).length
2304
+
2305
+ if (PACK_DATA_EXTS.has(ext)) {
2306
+ const rawSheets = single._sheets || []
2307
+ for (const sh of rawSheets) {
2308
+ const headers = sh.rows[0] || []
2309
+ const dataRows = sh.rows.slice(1)
2310
+ const cols = profileColumns(sh.rows)
2311
+ const numCols = cols.filter(c => c.isNumeric)
2312
+ const catCol = cols.find(c => !c.isNumeric) || cols[0]
2313
+ const profiled = buildNumericSheetSlides(sh, options.lang === 'en')
2314
+ const firstSlide = profiled.slides[0]
2315
+ const topMetrics = numCols.slice(0, 3).map(nc => {
2316
+ const vals = nc.parsed.filter(p => p.ok).map(p => p.num)
2317
+ const sum = vals.reduce((a, b) => a + b, 0)
2318
+ const max = vals.length ? Math.max(...vals) : 0
2319
+ const min = vals.length ? Math.min(...vals) : 0
2320
+ const avg = vals.length ? sum / vals.length : 0
2321
+ const maxRowIdx = nc.parsed.findIndex(p => p.ok && p.num === max)
2322
+ return {
2323
+ column: nc.header,
2324
+ unit: nc.unit,
2325
+ isPercent: nc.isPercentCol,
2326
+ sum: Number(sum.toFixed(2)),
2327
+ avg: Number(avg.toFixed(2)),
2328
+ min: Number(min.toFixed(2)),
2329
+ max: Number(max.toFixed(2)),
2330
+ peakCategory: maxRowIdx >= 0 ? (dataRows[maxRowIdx]?.[catCol.index] || '') : '',
2331
+ }
2332
+ })
2333
+ excelSheets.push({
2334
+ sourceFile: fname,
2335
+ evidenceId: evId,
2336
+ sheetName: sh.name,
2337
+ bannerTitle: sh.bannerTitle || '',
2338
+ rowCount: dataRows.length,
2339
+ colCount: headers.length,
2340
+ headers,
2341
+ topMetrics,
2342
+ recommendedLayout: firstSlide?.layout || 'table',
2343
+ recommendedChartKind: firstSlide?.chart?.kind || firstSlide?.layout || 'table',
2344
+ ...(firstSlide?.chart ? { chartSpec: firstSlide.chart } : {}),
2345
+ rowsPreview: sh.rows.slice(0, 6),
2346
+ })
2347
+ }
2348
+ localEvidence.push({
2349
+ id: evId,
2350
+ origin: 'local-file',
2351
+ claim: `${fname} 数据工作簿(${rawSheets.length} 张表,${single.stats?.totalRows ?? 0} 条记录)`,
2352
+ source: fname,
2353
+ date: todayYm,
2354
+ confidence: 'verified',
2355
+ })
2356
+ } else {
2357
+ // .docx or .pdf
2358
+ const rawSecs = single._rawSections || []
2359
+ const embeddedMedia = Array.isArray(single._embeddedMedia) ? single._embeddedMedia : []
2360
+ let cachedImgMap = new Map()
2361
+ if (embeddedMedia.length > 0) {
2362
+ try {
2363
+ const cacheDir = join(cwd, '.dsh-ppt', 'office-media-cache')
2364
+ mkdirSync(cacheDir, { recursive: true })
2365
+ for (let mIdx = 0; mIdx < embeddedMedia.length; mIdx += 1) {
2366
+ const em = embeddedMedia[mIdx]
2367
+ const b64 = String(em.dataUri || '').split(',')[1]
2368
+ if (!b64) continue
2369
+ const buf = Buffer.from(b64, 'base64')
2370
+ const meta = inspectImageBytes(buf, em.name || `docx-img-${mIdx + 1}.png`)
2371
+ const safeName = `${basename(fname, extname(fname)).replace(/[^A-Za-z0-9_-]/g, '_')}-${mIdx + 1}-${basename(em.name || 'img.png').replace(/[^A-Za-z0-9._-]/g, '_')}`
2372
+ const outPath = join(cacheDir, safeName)
2373
+ writeFileSync(outPath, buf)
2374
+ cachedImgMap.set(em.dataUri, { ...meta, path: outPath })
2375
+ }
2376
+ } catch { /* read-only cwd: fall back to metadata only */ }
2377
+ }
2378
+ for (const sec of rawSecs.slice(0, 20)) {
2379
+ const secImages = (sec.images || []).map((im) => {
2380
+ const cached = cachedImgMap.get(im.src)
2381
+ return cached
2382
+ ? { fileName: cached.fileName, path: cached.path, width: cached.width, height: cached.height, orientation: cached.orientation, recommendedFocalPoint: cached.recommendedFocalPoint }
2383
+ : { fileName: im.alt || 'embedded.png' }
2384
+ })
2385
+ docSections.push({
2386
+ sourceFile: fname,
2387
+ evidenceId: evId,
2388
+ heading: sec.title,
2389
+ level: sec.level || 2,
2390
+ bulletCount: sec.bullets?.length || 0,
2391
+ summaryBullets: (sec.bullets || []).slice(0, 4).map(b => cleanLine(b).slice(0, 110)),
2392
+ tableCount: sec.tables?.length || 0,
2393
+ tableDims: (sec.tables || []).map(t => `${t.length}x${t[0]?.length || 0}`),
2394
+ hasMermaid: (sec.mermaids?.length || 0) > 0,
2395
+ hasFormula: (sec.formulas?.length || 0) > 0,
2396
+ ...(secImages.length > 0 ? { embeddedImages: secImages } : {}),
2397
+ })
2398
+ }
2399
+ localEvidence.push({
2400
+ id: evId,
2401
+ origin: 'local-file',
2402
+ claim: cleanLine(`${single.title}(${rawSecs.length} 组章节)`).slice(0, 120),
2403
+ source: fname,
2404
+ date: todayYm,
2405
+ confidence: 'verified',
2406
+ })
2407
+ }
2408
+ }
2409
+
2410
+ const en = options.lang ? options.lang === 'en' : cjkHits < 4
2411
+ const topic = primaryTopic || (en ? 'Material Pack Presentation' : '多源素材汇报')
2412
+ const brandKit = loadWorkspaceBrandKit(cwd)
2413
+
2414
+ const enrichmentPlan = buildHybridEnrichmentPlan({
2415
+ topic,
2416
+ instructions: options.instructions || '',
2417
+ localAssets: { excelSheets, docSections, photos },
2418
+ localEvidence,
2419
+ lang: en ? 'en' : 'zh',
2420
+ preferredSources: brandKit?.preferredSources,
2421
+ blockedDomains: brandKit?.blockedDomains,
2422
+ })
2423
+
2424
+ const mdLines = [
2425
+ `# ${en ? 'Material Pack Dossier' : '本地素材包精炼档案'}:${topic}`,
2426
+ '',
2427
+ `- **${en ? 'Files' : '文件清单'}**:${sources.map(s => `${s.fileName} (${s.format})`).join(' · ')}`,
2428
+ ...(excelSheets.length ? [
2429
+ '',
2430
+ `## ${en ? 'Excel / Tabular Sheets' : '数据表画像'} (${excelSheets.length})`,
2431
+ ...excelSheets.map(sh => `- **${sh.sheetName}** (${sh.rowCount}×${sh.colCount}, [${sh.evidenceId}]) → 推荐 \`${sh.recommendedLayout}\` / \`${sh.recommendedChartKind}\`;核心指标:${sh.topMetrics.map(m => `${m.column} 峰值 ${m.peakCategory}=${m.max}${m.unit}`).join(',') || sh.headers.join('/')}`),
2432
+ ] : []),
2433
+ ...(docSections.length ? [
2434
+ '',
2435
+ `## ${en ? 'Word / PDF Sections' : '文档核心章节'} (${docSections.length})`,
2436
+ ...docSections.slice(0, 12).map(d => `- **${d.heading}** ([${d.evidenceId}], ${d.bulletCount} 条要点${d.tableCount ? `, ${d.tableCount} 表格` : ''}${d.embeddedImages?.length ? `, ${d.embeddedImages.length} 内嵌图` : ''}):${d.summaryBullets[0] || ''}`),
2437
+ ] : []),
2438
+ ...(photos.length ? [
2439
+ '',
2440
+ `## ${en ? 'Photos & Visual Assets' : '本地图片与配图体检'} (${photos.length})`,
2441
+ ...photos.map(p => `- **${p.fileName}** (${p.width}×${p.height} · ${p.orientation}, [${p.evidenceId}]) → 建议角色 \`${p.recommendedRole}\` / 版式 \`${p.recommendedLayout}\` / 焦点 \`focalPoint: "${p.recommendedFocalPoint}"\``),
2442
+ ] : []),
2443
+ '',
2444
+ enrichmentPlan.planMarkdown,
2445
+ ]
2446
+
2447
+ return {
2448
+ ok: true,
2449
+ inspectOnly: true,
2450
+ topic,
2451
+ language: en ? 'en' : 'zh',
2452
+ sources,
2453
+ excelSheets,
2454
+ docSections,
2455
+ photos,
2456
+ localEvidence,
2457
+ enrichmentPlan,
2458
+ dossierMarkdown: mdLines.join('\n'),
2459
+ }
2460
+ }
2461
+
2462
+ async function extractMultiSourcePack(rawFilePaths, options = {}) {
2463
+ const cwd = resolve(String(options.cwd ?? '.'))
2464
+ const uniqueFiles = collectPackFiles(rawFilePaths, cwd, options.signal)
2465
+ const parsedInstr = parseUserInstructions(options.instructions || '')
2466
+ const explicitPhotoRoles = options.photoRoles && typeof options.photoRoles === 'object' ? options.photoRoles : {}
1916
2467
 
1917
2468
  const todayYm = new Date().toISOString().slice(0, 7)
1918
2469
  const evidence = []
1919
2470
  const bodySlides = []
1920
2471
  const sourceSummaries = []
2472
+ const collectedSheets = []
2473
+ const pendingPhotos = []
1921
2474
  const formatCounts = { docs: 0, tables: 0, images: 0 }
1922
2475
  let detectedEn = options.lang === 'en'
1923
2476
  let cjkHits = 0
@@ -1932,32 +2485,34 @@ async function extractMultiSourcePack(rawFilePaths, options = {}) {
1932
2485
  if (PACK_IMG_EXTS.has(ext)) {
1933
2486
  const dataUri = readImageAsDataUri(file)
1934
2487
  if (!dataUri) continue
2488
+ const meta = inspectLocalImage(file, cwd)
2489
+ const role = resolvePhotoRole(meta, explicitPhotoRoles, parsedInstr)
1935
2490
  formatCounts.images += 1
1936
- const label = cleanLine(fname.replace(/\.[^.]+$/, '')) || fname
1937
- cjkHits += (label.match(/[\u3400-\u9fff]/g) || []).length
2491
+ cjkHits += (meta.label.match(/[\u3400-\u9fff]/g) || []).length
1938
2492
  evidence.push({
1939
2493
  id: evId,
1940
- claim: `视觉素材「${label}」来自本地图片文件`,
2494
+ origin: 'local-file',
2495
+ claim: `视觉素材「${meta.label}」来自本地图片文件`,
1941
2496
  source: fname,
1942
2497
  date: todayYm,
1943
2498
  confidence: 'verified',
1944
2499
  })
1945
- bodySlides.push({
1946
- layout: 'image',
1947
- variant: 'framed',
1948
- kicker: `VISUAL · ${evId}`,
1949
- title: label,
1950
- image: { src: dataUri, alt: label, fit: 'contain', caption: fname },
1951
- source: fname,
1952
- evidenceIds: [evId],
2500
+ pendingPhotos.push({
2501
+ ...meta,
2502
+ role,
2503
+ dataUri,
2504
+ evId,
1953
2505
  })
1954
- sourceSummaries.push({ file: fname, title: label, evId })
2506
+ sourceSummaries.push({ file: fname, title: meta.label, evId })
1955
2507
  continue
1956
2508
  }
1957
2509
 
1958
2510
  const single = await extractSingleOfficeFile({ ...options, filePath: file, filePaths: undefined })
1959
2511
  if (PACK_DOC_EXTS.has(ext)) formatCounts.docs += 1
1960
- else formatCounts.tables += 1
2512
+ else {
2513
+ formatCounts.tables += 1
2514
+ if (Array.isArray(single._sheets)) collectedSheets.push(...single._sheets)
2515
+ }
1961
2516
 
1962
2517
  const innerBody = (single.slides || []).filter(s => !['cover', 'closing', 'agenda'].includes(s.layout))
1963
2518
  const sampleText = [single.title, ...innerBody.slice(0, 3).map(s => s.title || '')].join(' ')
@@ -1968,6 +2523,7 @@ async function extractMultiSourcePack(rawFilePaths, options = {}) {
1968
2523
  ).slice(0, 96)
1969
2524
  evidence.push({
1970
2525
  id: evId,
2526
+ origin: 'local-file',
1971
2527
  claim: summaryClaim || `来自 ${fname} 的业务资料`,
1972
2528
  source: fname,
1973
2529
  date: todayYm,
@@ -1987,6 +2543,124 @@ async function extractMultiSourcePack(rawFilePaths, options = {}) {
1987
2543
 
1988
2544
  if (!options.lang) detectedEn = cjkHits < 4
1989
2545
  const en = detectedEn
2546
+
2547
+ // Smart Photo Choreography: Cover Hero / Device Mockup / Section Pair / Multi-Photo Gallery
2548
+ let coverPhoto = null
2549
+ const remainingGallery = []
2550
+
2551
+ for (const ph of pendingPhotos) {
2552
+ if (ph.role === 'cover' && !coverPhoto) {
2553
+ coverPhoto = ph
2554
+ continue
2555
+ }
2556
+ if (ph.role === 'mockup' || ph.role === 'mockup-mobile' || ph.role === 'mockup-browser') {
2557
+ const variant = ph.role === 'mockup-mobile' || (ph.role === 'mockup' && ph.orientation === 'portrait') ? 'mobile' : 'browser'
2558
+ bodySlides.push({
2559
+ layout: 'mockup',
2560
+ variant,
2561
+ kicker: `PRODUCT · ${ph.evId}`,
2562
+ title: en ? `${ph.label}: Live interface showcase` : `${ph.label}:核心产品界面展示`,
2563
+ image: { src: ph.dataUri, alt: ph.label, fit: 'cover', focalPoint: ph.recommendedFocalPoint },
2564
+ bullets: [
2565
+ en ? `Captured from ${ph.fileName} (${ph.width}×${ph.height})` : `原始界面素材:${ph.fileName}(${ph.width}×${ph.height})`,
2566
+ en ? 'Embedded in crisp device frame with focal crop preserved' : '自动匹配设备画框与焦点裁切,确保界面清晰呈现',
2567
+ ],
2568
+ source: ph.fileName,
2569
+ evidenceIds: [ph.evId],
2570
+ })
2571
+ continue
2572
+ }
2573
+ if (ph.role === 'full-bleed') {
2574
+ bodySlides.push({
2575
+ layout: 'image',
2576
+ variant: 'full-bleed',
2577
+ kicker: `VISUAL · ${ph.evId}`,
2578
+ title: ph.label,
2579
+ image: { src: ph.dataUri, alt: ph.label, fit: 'cover', focalPoint: ph.recommendedFocalPoint },
2580
+ source: ph.fileName,
2581
+ evidenceIds: [ph.evId],
2582
+ })
2583
+ continue
2584
+ }
2585
+ if (ph.role === 'gallery') {
2586
+ remainingGallery.push(ph)
2587
+ continue
2588
+ }
2589
+
2590
+ // Try keyword-matching photo to an existing text/bullets slide without chart/image
2591
+ const tokens = ph.label.toLowerCase().split(/[\s_-]+/).filter(t => t.length >= 2)
2592
+ const matchIdx = tokens.length > 0
2593
+ ? bodySlides.findIndex(s =>
2594
+ !s.image && !s.images && !s.chart && ['bullets', 'cards', 'callout'].includes(s.layout) &&
2595
+ tokens.some(tk => `${s.title || ''} ${s.kicker || ''}`.toLowerCase().includes(tk))
2596
+ )
2597
+ : -1
2598
+
2599
+ if (matchIdx >= 0) {
2600
+ const target = bodySlides[matchIdx]
2601
+ const pairedBullets = Array.isArray(target.bullets) && target.bullets.length > 0
2602
+ ? target.bullets.slice(0, 4)
2603
+ : (Array.isArray(target.items) ? target.items.slice(0, 4).map(it => `**${it.title || it.tag || ''}**:${it.text || ''}`) : [])
2604
+ bodySlides[matchIdx] = {
2605
+ ...target,
2606
+ layout: 'image-right',
2607
+ variant: 'framed',
2608
+ bullets: pairedBullets,
2609
+ items: undefined,
2610
+ image: { src: ph.dataUri, alt: ph.label, fit: 'cover', focalPoint: ph.recommendedFocalPoint },
2611
+ evidenceIds: [...new Set([...(target.evidenceIds || []), ph.evId])],
2612
+ }
2613
+ } else {
2614
+ remainingGallery.push(ph)
2615
+ }
2616
+ }
2617
+
2618
+ // Group remaining photos into crisp 2-4 photo gallery slides, or single framed image slide
2619
+ if (remainingGallery.length >= 2) {
2620
+ for (let g = 0; g < remainingGallery.length; g += 4) {
2621
+ const chunk = remainingGallery.slice(g, g + 4)
2622
+ if (chunk.length === 1) {
2623
+ const ph = chunk[0]
2624
+ bodySlides.push({
2625
+ layout: 'image',
2626
+ variant: 'framed',
2627
+ kicker: `VISUAL · ${ph.evId}`,
2628
+ title: ph.label,
2629
+ image: { src: ph.dataUri, alt: ph.label, fit: 'contain', caption: ph.fileName },
2630
+ source: ph.fileName,
2631
+ evidenceIds: [ph.evId],
2632
+ })
2633
+ } else {
2634
+ bodySlides.push({
2635
+ layout: 'image',
2636
+ variant: 'gallery',
2637
+ kicker: en ? 'VISUAL GALLERY' : '现场与视觉图集',
2638
+ title: en ? `Visual Evidence Showcase (${chunk.length} Assets)` : `核心视觉实景图集(共 ${chunk.length} 组素材)`,
2639
+ images: chunk.map(ph => ({
2640
+ src: ph.dataUri,
2641
+ alt: ph.label,
2642
+ fit: 'cover',
2643
+ focalPoint: ph.recommendedFocalPoint,
2644
+ caption: ph.label,
2645
+ })),
2646
+ source: chunk.map(ph => ph.fileName).join(' · '),
2647
+ evidenceIds: chunk.map(ph => ph.evId),
2648
+ })
2649
+ }
2650
+ }
2651
+ } else if (remainingGallery.length === 1) {
2652
+ const ph = remainingGallery[0]
2653
+ bodySlides.push({
2654
+ layout: 'image',
2655
+ variant: 'framed',
2656
+ kicker: `VISUAL · ${ph.evId}`,
2657
+ title: ph.label,
2658
+ image: { src: ph.dataUri, alt: ph.label, fit: 'contain', caption: ph.fileName },
2659
+ source: ph.fileName,
2660
+ evidenceIds: [ph.evId],
2661
+ })
2662
+ }
2663
+
1990
2664
  const defaultPackTitle = cleanLine(options.title || '')
1991
2665
  || (options.filePath && lstatSync(resolve(cwd, String(options.filePath))).isDirectory()
1992
2666
  ? basename(resolve(cwd, String(options.filePath)))
@@ -1997,18 +2671,29 @@ async function extractMultiSourcePack(rawFilePaths, options = {}) {
1997
2671
  if (formatCounts.tables > 0) partsDesc.push(en ? `${formatCounts.tables} table(s)` : `${formatCounts.tables} 份数据表`)
1998
2672
  if (formatCounts.images > 0) partsDesc.push(en ? `${formatCounts.images} visual(s)` : `${formatCounts.images} 张视觉素材`)
1999
2673
 
2000
- const mergedSlides = [
2001
- {
2002
- layout: 'cover',
2003
- kicker: en ? 'MULTI-SOURCE BRIEFING' : '多源素材融合汇报',
2004
- title: defaultPackTitle,
2005
- subtitle: en
2006
- ? `Synthesized from ${uniqueFiles.length} local files (${partsDesc.join(' · ')}) with [E1–E${evidence.length}] provenance`
2007
- : `融合 ${uniqueFiles.length} 份本地资料(${partsDesc.join(' · ')}),全篇自动绑定 [E1–E${evidence.length}] 溯源台账`,
2008
- },
2009
- ]
2674
+ const coverSlide = {
2675
+ layout: 'cover',
2676
+ kicker: en ? 'MULTI-SOURCE BRIEFING' : '多源素材融合汇报',
2677
+ title: defaultPackTitle,
2678
+ subtitle: en
2679
+ ? `Synthesized from ${uniqueFiles.length} local files (${partsDesc.join(' · ')}) with [E1–E${evidence.length}] provenance`
2680
+ : `融合 ${uniqueFiles.length} 份本地资料(${partsDesc.join(' · ')}),全篇自动绑定 [E1–E${evidence.length}] 溯源台账`,
2681
+ ...(coverPhoto
2682
+ ? {
2683
+ image: {
2684
+ src: coverPhoto.dataUri,
2685
+ alt: coverPhoto.label,
2686
+ fit: 'cover',
2687
+ focalPoint: coverPhoto.recommendedFocalPoint,
2688
+ },
2689
+ evidenceIds: [coverPhoto.evId],
2690
+ }
2691
+ : {}),
2692
+ }
2693
+
2694
+ const mergedSlides = [coverSlide]
2010
2695
 
2011
- if (sourceSummaries.length >= 2) {
2696
+ if (sourceSummaries.length >= 2 && !parsedInstr.skipAgenda) {
2012
2697
  mergedSlides.push({
2013
2698
  layout: 'agenda',
2014
2699
  kicker: en ? 'SOURCE PACK' : '资料目录',
@@ -2035,14 +2720,18 @@ async function extractMultiSourcePack(rawFilePaths, options = {}) {
2035
2720
  })),
2036
2721
  })
2037
2722
 
2723
+ const effectiveMaxSlides = Number.isInteger(options.maxSlides) ? options.maxSlides : parsedInstr.targetSlides
2724
+ const budgetedSlides = applyMaxSlidesBudget(mergedSlides, effectiveMaxSlides, parsedInstr.focusTerms)
2725
+
2038
2726
  return {
2039
2727
  ok: true,
2040
2728
  importedFrom: uniqueFiles.join(', '),
2041
2729
  importedFiles: uniqueFiles,
2042
2730
  title: defaultPackTitle,
2043
2731
  language: en ? 'en' : 'zh',
2044
- slides: mergedSlides,
2732
+ slides: budgetedSlides,
2045
2733
  evidence,
2734
+ _sheets: collectedSheets,
2046
2735
  stats: {
2047
2736
  sourceFormat: 'multi-source-pack',
2048
2737
  fileCount: uniqueFiles.length,
@@ -2050,7 +2739,7 @@ async function extractMultiSourcePack(rawFilePaths, options = {}) {
2050
2739
  tableCount: formatCounts.tables,
2051
2740
  imageCount: formatCounts.images,
2052
2741
  evidenceCount: evidence.length,
2053
- slideCount: mergedSlides.length,
2742
+ slideCount: budgetedSlides.length,
2054
2743
  },
2055
2744
  }
2056
2745
  }
@@ -2059,16 +2748,22 @@ async function extractSingleOfficeFile(options = {}) {
2059
2748
  abort(options.signal)
2060
2749
  const input = readOfficeInput(options)
2061
2750
  const enHint = options.lang === 'en'
2751
+ const parsedInstr = parseUserInstructions(options.instructions || '')
2062
2752
 
2063
2753
  if (input.format === 'xlsx') {
2064
- const { sheets } = parseXlsxArchive(input.bytes)
2754
+ const parsed = parseXlsxArchive(input.bytes)
2755
+ const sheets = filterSheetsByInclude(parsed.sheets, options.includeSheets)
2065
2756
  const sample = sheets.flatMap(s => s.rows.slice(0, 5).flat()).join(' ')
2066
2757
  const en = options.lang ? enHint : (sample.match(/[\u3400-\u9fff]/g) || []).length < 4
2067
2758
  const profiled = profileTabularWorkbook(sheets, input.fileName, en)
2759
+ const maxBudget = Number.isInteger(options.maxSlides) ? options.maxSlides : parsedInstr.targetSlides
2760
+ const finalSlides = applyMaxSlidesBudget(profiled.slides, maxBudget, parsedInstr.focusTerms)
2068
2761
  return {
2069
2762
  ok: true,
2070
2763
  importedFrom: input.resolvedPath,
2071
2764
  ...profiled,
2765
+ slides: finalSlides,
2766
+ stats: { ...profiled.stats, slideCount: finalSlides.length },
2072
2767
  }
2073
2768
  }
2074
2769
 
@@ -2078,27 +2773,43 @@ async function extractSingleOfficeFile(options = {}) {
2078
2773
  const en = options.lang ? enHint : (sample.match(/[\u3400-\u9fff]/g) || []).length < 4
2079
2774
  const sheetTitle = cleanLine(input.fileName.replace(/\.[^.]+$/, '')) || (en ? 'Dataset' : '数据表')
2080
2775
  const profiled = profileTabularWorkbook([{ name: sheetTitle, bannerTitle: '', rows }], input.fileName, en)
2776
+ const maxBudget = Number.isInteger(options.maxSlides) ? options.maxSlides : parsedInstr.targetSlides
2777
+ const finalSlides = applyMaxSlidesBudget(profiled.slides, maxBudget, parsedInstr.focusTerms)
2081
2778
  return {
2082
2779
  ok: true,
2083
2780
  importedFrom: input.resolvedPath,
2084
2781
  ...profiled,
2782
+ slides: finalSlides,
2783
+ stats: { ...profiled.stats, slideCount: finalSlides.length },
2085
2784
  }
2086
2785
  }
2087
2786
 
2088
2787
  if (input.format === 'pdf') {
2089
2788
  const parsedPdf = parsePdfDocument(input.bytes, input.fileName, options.lang)
2789
+ let slides = parsedPdf.slides
2790
+ if (parsedInstr.skipAgenda) slides = slides.filter(s => s.layout !== 'agenda')
2791
+ const maxBudget = Number.isInteger(options.maxSlides) ? options.maxSlides : parsedInstr.targetSlides
2792
+ slides = applyMaxSlidesBudget(slides, maxBudget, parsedInstr.focusTerms)
2090
2793
  return {
2091
2794
  ok: true,
2092
2795
  importedFrom: input.resolvedPath,
2093
2796
  ...parsedPdf,
2797
+ slides,
2798
+ stats: { ...parsedPdf.stats, slideCount: slides.length },
2094
2799
  }
2095
2800
  }
2096
2801
 
2097
2802
  const parsedDocx = parseDocxArchive(input.bytes, input.fileName)
2803
+ let slides = parsedDocx.slides
2804
+ if (parsedInstr.skipAgenda) slides = slides.filter(s => s.layout !== 'agenda')
2805
+ const maxBudget = Number.isInteger(options.maxSlides) ? options.maxSlides : parsedInstr.targetSlides
2806
+ slides = applyMaxSlidesBudget(slides, maxBudget, parsedInstr.focusTerms)
2098
2807
  return {
2099
2808
  ok: true,
2100
2809
  importedFrom: input.resolvedPath,
2101
2810
  ...parsedDocx,
2811
+ slides,
2812
+ stats: { ...parsedDocx.stats, slideCount: slides.length },
2102
2813
  }
2103
2814
  }
2104
2815
 
@@ -2109,10 +2820,13 @@ async function extractSingleOfficeFile(options = {}) {
2109
2820
  /**
2110
2821
  * Extract structured slides & metadata from `.xlsx`, `.csv`, `.tsv`, `.docx`, `.pdf`,
2111
2822
  * OR a multi-source pack (directory path or `filePaths[]` combining docs + tables + PDF + images).
2112
- * Zero external new dependencies (uses Node zlib inflateSync/inflateRawSync + lazy csv-parse).
2823
+ * Pass `inspectOnly: true` to return a compact Material Dossier + Hybrid Authoritative Enrichment Plan without building slides.
2113
2824
  */
2114
2825
  export async function extractOfficeSource(options = {}) {
2115
2826
  abort(options.signal)
2827
+ if (options.inspectOnly === true) {
2828
+ return inspectOfficePack(options)
2829
+ }
2116
2830
  if (Array.isArray(options.filePaths) && options.filePaths.length > 0) {
2117
2831
  return extractMultiSourcePack(options.filePaths, options)
2118
2832
  }
@@ -2124,6 +2838,9 @@ export async function extractOfficeSource(options = {}) {
2124
2838
  if (st.isDirectory()) {
2125
2839
  return extractMultiSourcePack([resolved], options)
2126
2840
  }
2841
+ if (st.isFile() && PACK_IMG_EXTS.has(extname(resolved).toLowerCase())) {
2842
+ return extractMultiSourcePack([resolved], options)
2843
+ }
2127
2844
  } catch { /* fall through to readOfficeInput error */ }
2128
2845
  }
2129
2846
  return extractSingleOfficeFile(options)
@@ -2131,10 +2848,15 @@ export async function extractOfficeSource(options = {}) {
2131
2848
 
2132
2849
  /**
2133
2850
  * Import an Office/PDF document or multi-source folder pack directly into a full dsh-ppt deck
2134
- * (HTML slideshow + 100% native editable PPTX + JSON project + optional evidence ledger & handout/one-pager).
2851
+ * (HTML slideshow + 100% native editable PPTX + JSON project + optional live dataModel binding,
2852
+ * hybrid external authoritative evidence merge, and reverse exports).
2853
+ * When `inspectOnly: true`, returns the compact Material Dossier + Mode C Enrichment Plan without writing files.
2135
2854
  */
2136
2855
  export async function importOfficeDeck(options = {}) {
2137
2856
  abort(options.signal)
2857
+ if (options.inspectOnly === true) {
2858
+ return inspectOfficePack(options)
2859
+ }
2138
2860
  const extracted = await extractOfficeSource(options)
2139
2861
  const { buildDeckAsync } = await import('./deck-advanced.mjs')
2140
2862
 
@@ -2156,16 +2878,86 @@ export async function importOfficeDeck(options = {}) {
2156
2878
  ? { ...(options.brand && typeof options.brand === 'object' ? options.brand : {}), chromeStyle: options.chromeStyle }
2157
2879
  : options.brand
2158
2880
 
2881
+ let finalSlides = extracted.slides
2882
+ let autoDataModel
2883
+ if (options.bindDataModel === true && Array.isArray(extracted._sheets) && extracted._sheets.length > 0) {
2884
+ const bound = buildAutoDataModelFromSheets(extracted._sheets)
2885
+ if (bound) {
2886
+ autoDataModel = bound.dataModel
2887
+ finalSlides = bindSlidesWithAutoDataModel(finalSlides, bound)
2888
+ }
2889
+ }
2890
+
2891
+ // Merge local evidence + optional external authoritative web-research evidence with zero ID collisions
2892
+ const localEv = Array.isArray(extracted.evidence) && extracted.evidence.length > 0
2893
+ ? extracted.evidence
2894
+ : (Array.isArray(options.evidence) && options.evidence.length > 0
2895
+ ? [{
2896
+ id: 'E1',
2897
+ origin: 'local-file',
2898
+ claim: cleanLine(`${title} 本地原始资料`),
2899
+ source: basename(extracted.importedFrom || title),
2900
+ date: new Date().toISOString().slice(0, 7),
2901
+ confidence: 'verified',
2902
+ }]
2903
+ : [])
2904
+ let mergedEvidence = localEv
2905
+ let hybridMergeInfo
2906
+ if (Array.isArray(options.evidence) && options.evidence.length > 0) {
2907
+ const cwd = resolve(String(options.cwd ?? '.'))
2908
+ const kit = loadWorkspaceBrandKit(cwd)
2909
+ const merged = mergeHybridEvidence(localEv, options.evidence, {
2910
+ preferredSources: kit?.preferredSources,
2911
+ blockedDomains: kit?.blockedDomains,
2912
+ })
2913
+ mergedEvidence = merged.evidence
2914
+ hybridMergeInfo = {
2915
+ localCount: merged.localCount,
2916
+ externalCount: merged.externalCount,
2917
+ remappedIds: merged.remappedIds,
2918
+ }
2919
+ // Add an authoritative external benchmark synthesis slide if external evidence wasn't already referenced
2920
+ const extOnly = merged.evidence.filter(e => e.origin === 'web-research')
2921
+ if (extOnly.length > 0) {
2922
+ const en = lang === 'en'
2923
+ const closingIdx = finalSlides.findIndex(s => s.layout === 'closing')
2924
+ const extSlide = {
2925
+ layout: 'cards',
2926
+ variant: 'pillars',
2927
+ kicker: en ? 'EXTERNAL BENCHMARKS' : '权威外部基准对标',
2928
+ title: en
2929
+ ? `Authoritative External Context Anchors ${extOnly.length} Key Benchmarks`
2930
+ : `外部权威基准校准核心判断(共引入 ${extOnly.length} 项权威外源)`,
2931
+ items: extOnly.slice(0, 4).map((e) => ({
2932
+ tag: `${e.id}${e.tier ? ` · T${e.tier}` : ''}`,
2933
+ title: cleanLine(e.source).slice(0, 28),
2934
+ text: cleanLine(e.claim).slice(0, 72) + (e.claimType === 'forecast' ? (en ? ' (Forecast)' : '(预计)') : ''),
2935
+ })),
2936
+ evidenceIds: extOnly.map(e => e.id),
2937
+ takeaway: en
2938
+ ? 'Internal metrics are benchmarked against verified external Tier 1/2 sources; full provenance is recorded in the Evidence Appendix.'
2939
+ : '内部数据已与外部权威基准完成双轨对标,完整出处、年份与原文链接详见附录溯源清单。',
2940
+ }
2941
+ if (closingIdx >= 0) {
2942
+ finalSlides = [...finalSlides.slice(0, closingIdx), extSlide, ...finalSlides.slice(closingIdx)]
2943
+ } else {
2944
+ finalSlides = [...finalSlides, extSlide]
2945
+ }
2946
+ }
2947
+ }
2948
+
2159
2949
  const built = await buildDeckAsync({
2160
2950
  title,
2161
- slides: extracted.slides,
2951
+ slides: finalSlides,
2162
2952
  theme: inferred,
2163
2953
  persona,
2164
2954
  lang,
2165
2955
  motion: options.motion,
2956
+ motionProfile: options.motionProfile,
2166
2957
  brand,
2167
- ...(Array.isArray(extracted.evidence) && extracted.evidence.length > 0
2168
- ? { evidence: extracted.evidence, evidenceAppendix: options.evidenceAppendix !== false }
2958
+ ...(autoDataModel ? { dataModel: autoDataModel } : {}),
2959
+ ...(Array.isArray(mergedEvidence) && mergedEvidence.length > 0
2960
+ ? { evidence: mergedEvidence, evidenceAppendix: options.evidenceAppendix !== false }
2169
2961
  : {}),
2170
2962
  outputDir: options.outputDir || options.outDir || '.',
2171
2963
  fileName: baseFileName,
@@ -2173,6 +2965,7 @@ export async function importOfficeDeck(options = {}) {
2173
2965
  smartLayout: false,
2174
2966
  handout: options.handout === true,
2175
2967
  onePager: options.onePager === true,
2968
+ ...(Array.isArray(options.exports) && options.exports.length > 0 ? { exports: options.exports } : {}),
2176
2969
  ...(options.targetMinutes !== undefined ? { targetMinutes: options.targetMinutes } : {}),
2177
2970
  cwd: options.cwd,
2178
2971
  signal: options.signal,
@@ -2182,6 +2975,8 @@ export async function importOfficeDeck(options = {}) {
2182
2975
  ...built,
2183
2976
  importedFrom: extracted.importedFrom,
2184
2977
  ...(extracted.importedFiles ? { importedFiles: extracted.importedFiles } : {}),
2978
+ ...(autoDataModel ? { dataModelBound: true, boundMetricCount: autoDataModel.metrics.length } : {}),
2979
+ ...(hybridMergeInfo ? { hybridEvidence: hybridMergeInfo } : {}),
2185
2980
  officeStats: extracted.stats,
2186
2981
  }
2187
2982
  }