@yakovlev-i-a/dsh-openfoam-workbench 0.0.0-stage → 0.9.26

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 (56) hide show
  1. package/CHANGELOG.md +683 -0
  2. package/CORE.md +50 -0
  3. package/LICENSE +202 -0
  4. package/NOTICE +29 -0
  5. package/README.md +373 -2
  6. package/client.js +48 -0
  7. package/cordis.patch.yml +18 -0
  8. package/icon.png +0 -0
  9. package/lib/buildlib.js +42 -0
  10. package/lib/caselib.js +212 -0
  11. package/lib/core.js +47 -0
  12. package/lib/discover.js +139 -0
  13. package/lib/escalations.js +92 -0
  14. package/lib/explib.js +149 -0
  15. package/lib/impact.js +55 -0
  16. package/lib/index.js +109 -0
  17. package/lib/knowledge.js +108 -0
  18. package/lib/meshlib.js +375 -0
  19. package/lib/needs-input.js +32 -0
  20. package/lib/of-case.js +485 -0
  21. package/lib/of-engine.js +1061 -0
  22. package/lib/paperlib.js +200 -0
  23. package/lib/presentation.js +365 -0
  24. package/lib/registry.js +142 -0
  25. package/lib/routing-guard.js +126 -0
  26. package/lib/runtime.js +580 -0
  27. package/lib/scaffold-cht.js +318 -0
  28. package/lib/scaffold-compressible.js +171 -0
  29. package/lib/scaffold.js +355 -0
  30. package/lib/settings-schema.js +86 -0
  31. package/lib/skills.js +53 -0
  32. package/lib/tools/build.js +90 -0
  33. package/lib/tools/case.js +1082 -0
  34. package/lib/tools/env.js +592 -0
  35. package/lib/tools/experience.js +165 -0
  36. package/lib/tools/mesh.js +408 -0
  37. package/lib/tools/meta.js +95 -0
  38. package/lib/tools/papers.js +105 -0
  39. package/lib/tools/render.js +94 -0
  40. package/lib/tools/run.js +331 -0
  41. package/lib/versions.js +133 -0
  42. package/licenses/dsh-openfoam-doctor-MIT.txt +21 -0
  43. package/locale/en.json +6 -0
  44. package/locale/ru.json +6 -0
  45. package/package.json +44 -4
  46. package/skills/openfoam-analyze/SKILL.md +27 -0
  47. package/skills/openfoam-case-builder/SKILL.md +61 -0
  48. package/skills/openfoam-cht/SKILL.md +83 -0
  49. package/skills/openfoam-code-modify/SKILL.md +32 -0
  50. package/skills/openfoam-mesh-independence/SKILL.md +55 -0
  51. package/skills/openfoam-meshing/SKILL.md +30 -0
  52. package/skills/openfoam-paper-reproduction/SKILL.md +36 -0
  53. package/skills/openfoam-self-evolution/SKILL.md +21 -0
  54. package/skills/openfoam-solver-development/SKILL.md +61 -0
  55. package/skills/openfoam-stats/SKILL.md +46 -0
  56. package/skills/openfoam-viz/SKILL.md +35 -0
@@ -0,0 +1,200 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
+
3
+ const UA = (() => {
4
+ try { return 'openfoam-workbench/' + JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version } catch { return 'openfoam-workbench' }
5
+ })()
6
+ const MAX_PDF_BYTES = 50 * 1024 * 1024
7
+ import { extname, join } from 'node:path'
8
+ import { readText, resolveCase, run } from './runtime.js'
9
+
10
+ export async function pdfText(cfg, file) {
11
+ const bin = cfg.pdftotext || 'pdftotext'
12
+ const r = await run(bin, ['-layout', file, '-'], { timeoutMs: 120000 })
13
+ if (r.ok && r.stdout.trim()) return { ok: true, text: r.stdout, tool: 'pdftotext' }
14
+ const py = cfg.pythonPath || 'python3'
15
+ const script = 'import sys, fitz\nd = fitz.open(sys.argv[1])\nprint("\\n".join(p.get_text() for p in d))'
16
+ const r2 = await run(py, ['-c', script, file], { timeoutMs: 120000 })
17
+ if (r2.ok && r2.stdout.trim()) return { ok: true, text: r2.stdout, tool: 'pymupdf' }
18
+ return { ok: false, error: 'PDF text extraction failed', log: ((r.stderr || '') + (r2.stderr || '')).slice(-1000) }
19
+ }
20
+
21
+ export function splitSections(text) {
22
+ const out = { body: [] }
23
+ let cur = 'body'
24
+ const slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48)
25
+ for (const line of String(text).split('\n')) {
26
+ const t = line.trim()
27
+ let key = null
28
+ if (/^\d+\.?\s+[A-Z][^\n]{0,80}$/.test(t) && t.length < 90) {
29
+ key = slug(t)
30
+ } else if (/^(Abstract|References)\b/i.test(t) && t.length < 60) {
31
+ key = t.toLowerCase().split(/\s/)[0]
32
+ }
33
+ if (key) cur = key
34
+ if (!out[cur]) out[cur] = []
35
+ out[cur].push(line)
36
+ }
37
+ const res = {}
38
+ for (const [k, v] of Object.entries(out)) res[k] = v.join('\n').trim().slice(0, 20000)
39
+ return res
40
+ }
41
+
42
+ export async function paperSearch(cfg, args) {
43
+ const q = String(args.query || '')
44
+ if (!q) return { ok: false, error: 'empty query' }
45
+ const limit = Math.min(Number(args.top_k) || 10, 50)
46
+ const merge = []
47
+ const errors = []
48
+ try {
49
+ const url = `https://api.semanticscholar.org/graph/v1/paper/search?query=${encodeURIComponent(q)}&limit=${limit}&fields=title,authors,year,venue,citationCount,abstract,externalIds,openAccessPdf`
50
+ const r = await fetch(url, { headers: { 'User-Agent': UA }, signal: AbortSignal.timeout(20000) })
51
+ if (r.ok) {
52
+ const j = await r.json()
53
+ for (const p of j.data || []) {
54
+ merge.push({ source: 's2', title: p.title, authors: (p.authors || []).map((a) => a.name), year: p.year, venue: p.venue, citations: p.citationCount, doi: p.externalIds && p.externalIds.DOI, arxiv: p.externalIds && p.externalIds.ArXiv, abstract: p.abstract, pdf: p.openAccessPdf && p.openAccessPdf.url })
55
+ }
56
+ } else {
57
+ errors.push('semantic-scholar: HTTP ' + r.status)
58
+ }
59
+ } catch (e) {
60
+ errors.push('semantic-scholar: ' + ((e && e.message) || e))
61
+ }
62
+ try {
63
+ const url = `https://export.arxiv.org/api/query?search_query=all:${encodeURIComponent(q)}&max_results=${limit}`
64
+ const r = await fetch(url, { headers: { 'User-Agent': UA }, signal: AbortSignal.timeout(25000) })
65
+ if (r.ok) {
66
+ const xml = await r.text()
67
+ if (!/<entry>/.test(xml)) errors.push('arxiv: ' + xml.slice(0, 120))
68
+ for (const m of xml.matchAll(/<entry>([\s\S]*?)<\/entry>/g)) {
69
+ const e = m[1]
70
+ const title = ((e.match(/<title>([\s\S]*?)<\/title>/) || [])[1] || '').trim().replace(/\s+/g, ' ')
71
+ const id = (e.match(/<id>([\s\S]*?)<\/id>/) || [])[1]
72
+ const published = (e.match(/<published>([\s\S]*?)<\/published>/) || [])[1]
73
+ merge.push({ source: 'arxiv', title, arxiv: id ? id.split('/abs/').pop() : null, year: published ? new Date(published).getFullYear() : null, pdf: id ? id.trim() : null })
74
+ }
75
+ } else {
76
+ errors.push('arxiv: HTTP ' + r.status)
77
+ }
78
+ } catch (e) {
79
+ errors.push('arxiv: ' + ((e && e.message) || e))
80
+ }
81
+ const seen = new Set()
82
+ const out = []
83
+ for (const p of merge) {
84
+ const k = String(p.title || '').toLowerCase().replace(/\s+/g, ' ').trim()
85
+ if (!k || seen.has(k)) continue
86
+ seen.add(k)
87
+ out.push(p)
88
+ }
89
+ return { ok: true, count: Math.min(out.length, limit), papers: out.slice(0, limit), errors: errors.length ? errors : null, degraded: errors.length > 0 }
90
+ }
91
+
92
+ export async function paperFetch(cfg, args) {
93
+ const id = String(args.id || '').trim()
94
+ if (!id) return { ok: false, error: 'empty id' }
95
+ const url = `https://api.semanticscholar.org/graph/v1/paper/${encodeURIComponent(id)}?fields=title,authors,year,venue,abstract,tldr,externalIds,openAccessPdf,references.title,references.year`
96
+ try {
97
+ const r = await fetch(url, { headers: { 'User-Agent': UA }, signal: AbortSignal.timeout(20000) })
98
+ if (!r.ok) return { ok: false, error: 'Semantic Scholar returned ' + r.status }
99
+ const p = await r.json()
100
+ const out = { ok: true, title: p.title, authors: (p.authors || []).map((a) => a.name), year: p.year, venue: p.venue, abstract: p.abstract, tldr: p.tldr && p.tldr.text, doi: p.externalIds && p.externalIds.DOI, arxiv: p.externalIds && p.externalIds.ArXiv, pdf: p.openAccessPdf && p.openAccessPdf.url, references: (p.references || []).slice(0, Number(args.max_refs) || 10) }
101
+ if (args.download && p.openAccessPdf && p.openAccessPdf.url) {
102
+ const dir = join((Array.isArray(cfg.caseRoots) && cfg.caseRoots.length ? cfg.caseRoots[0] : process.cwd()), 'downloads/papers')
103
+ mkdirSync(dir, { recursive: true })
104
+ const base = (p.externalIds && p.externalIds.ArXiv ? 'arxiv_' + p.externalIds.ArXiv : String(p.title || 'paper').replace(/[^A-Za-z0-9]+/g, '_').slice(0, 60)) + '.pdf'
105
+ const file = join(dir, base)
106
+ try {
107
+ const pr = await fetch(p.openAccessPdf.url, { signal: AbortSignal.timeout(60000) })
108
+ if (pr.ok) {
109
+ const declared = Number(pr.headers.get('content-length') || 0)
110
+ if (declared > MAX_PDF_BYTES) {
111
+ out.downloadError = `PDF is ${(declared / 1048576).toFixed(1)} MB, above the ${MAX_PDF_BYTES / 1048576} MB limit`
112
+ } else {
113
+ const buf = Buffer.from(await pr.arrayBuffer())
114
+ if (buf.length > MAX_PDF_BYTES) out.downloadError = 'PDF exceeded the size limit while downloading'
115
+ else { writeFileSync(file, buf); out.downloaded = file }
116
+ }
117
+ }
118
+ } catch {}
119
+ }
120
+ return out
121
+ } catch (e) {
122
+ return { ok: false, error: String((e && e.message) || e) }
123
+ }
124
+ }
125
+
126
+ export async function pdfTextBlocks(cfg, file) {
127
+ const py = cfg.pythonPath || 'python3'
128
+ const script = [
129
+ 'import sys, fitz',
130
+ 'doc = fitz.open(sys.argv[1])',
131
+ 'out = []',
132
+ 'for page in doc:',
133
+ ' blocks = [b for b in page.get_text("blocks") if b[6] == 0]',
134
+ ' if not blocks:',
135
+ ' continue',
136
+ ' mid = page.rect.width * 0.5',
137
+ ' left = [b for b in blocks if b[2] <= mid + 5]',
138
+ ' right = [b for b in blocks if b[0] >= mid - 5]',
139
+ ' if left and right and len(left) + len(right) >= len(blocks) - 2:',
140
+ ' left.sort(key=lambda b: (b[1], b[0]))',
141
+ ' right.sort(key=lambda b: (b[1], b[0]))',
142
+ ' ordered = left + right',
143
+ ' else:',
144
+ ' ordered = sorted(blocks, key=lambda b: (b[1], b[0]))',
145
+ ' out.append("\\n".join(b[4].strip() for b in ordered))',
146
+ 'print("\\n\\n".join(out))',
147
+ ].join('\n')
148
+ const r = await run(py, ['-c', script, file], { timeoutMs: 120000 })
149
+ if (r.ok && r.stdout.trim()) return { ok: true, text: r.stdout, tool: 'pymupdf-blocks' }
150
+ return pdfText(cfg, file)
151
+ }
152
+
153
+ export async function readPaper(cfg, args) {
154
+ const p = resolveCase(cfg, args.path)
155
+ if (!p || !existsSync(p)) return { ok: false, error: 'file not found: ' + p }
156
+ const t = await pdfTextBlocks(cfg, p)
157
+ if (!t.ok) return t
158
+ const sections = splitSections(t.text)
159
+ let focusHits = null
160
+ if (args.focus) {
161
+ const f = String(args.focus).toLowerCase()
162
+ focusHits = t.text.split('\n').filter((line) => line.toLowerCase().includes(f)).slice(0, 20)
163
+ }
164
+ return { ok: true, path: p, tool: t.tool, chars: t.text.length, sections, focusHits }
165
+ }
166
+
167
+ export async function paperExtract(cfg, args) {
168
+ const p = resolveCase(cfg, args.path)
169
+ if (!p || !existsSync(p)) return { ok: false, error: 'file not found: ' + p }
170
+ const t = await pdfText(cfg, p)
171
+ if (!t.ok) return t
172
+ const text = t.text
173
+ const equations = []
174
+ for (const m of text.matchAll(/^\s*([^\n]{3,200})\s*\((\d+)\)\s*$/gm)) {
175
+ equations.push({ eq: m[2], text: m[1].trim() })
176
+ if (equations.length >= 60) break
177
+ }
178
+ const tables = []
179
+ for (const m of text.matchAll(/\bTable\s+(\d+)[^\n]{0,120}/g)) {
180
+ tables.push({ table: m[1], caption: m[0].trim() })
181
+ if (tables.length >= 40) break
182
+ }
183
+ const params = []
184
+ for (const m of text.matchAll(/\b([A-Za-z_][A-Za-z0-9_]{1,20})\s*=\s*([0-9.+\-eE]+)\s*([A-Za-z/%^0-9]+)?/g)) {
185
+ params.push({ name: m[1], value: m[2], unit: m[3] || '' })
186
+ if (params.length >= 200) break
187
+ }
188
+ return { ok: true, path: p, equations, tables, params }
189
+ }
190
+
191
+ export async function readDocument(cfg, args) {
192
+ const p = resolveCase(cfg, args.path)
193
+ if (!p || !existsSync(p)) return { ok: false, error: 'file not found: ' + p }
194
+ const ext = extname(p).toLowerCase()
195
+ if (ext === '.pdf') return pdfText(cfg, p)
196
+ if (['.txt', '.md', '.csv', '.log', '.dat', '.json', '.yaml', '.yml'].includes(ext)) {
197
+ return { ok: true, text: (readText(p) || '').slice(0, 200000), tool: 'raw' }
198
+ }
199
+ return { ok: false, error: `unsupported format ${ext}; supported: pdf, txt, md, csv, log, dat, json, yaml` }
200
+ }
@@ -0,0 +1,365 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { basename, dirname, join } from 'node:path'
3
+ import { tmpdir } from 'node:os'
4
+ import { resolveCase, run, textOut } from './runtime.js'
5
+ import { ensureFoamFile, findFoamFile } from './of-case.js'
6
+
7
+ export const PV_RENDER_SCRIPT = `import sys, os, json
8
+ from paraview.simple import *
9
+
10
+ def main():
11
+ def num(s, d):
12
+ try:
13
+ return float(s[1:]) if s.startswith('n') else float(s)
14
+ except Exception:
15
+ return d
16
+
17
+ case = sys.argv[1]
18
+ field = sys.argv[2] if len(sys.argv) > 2 and sys.argv[2] != 'none' else ''
19
+ step = int(num(sys.argv[3] if len(sys.argv) > 3 else 'n-1', -1))
20
+ az = num(sys.argv[4] if len(sys.argv) > 4 else 'n0', 0.0)
21
+ el = num(sys.argv[5] if len(sys.argv) > 5 else 'n0', 0.0)
22
+ zoom = num(sys.argv[6] if len(sys.argv) > 6 else 'n1', 1.0)
23
+ out = sys.argv[7] if len(sys.argv) > 7 else 'render.png'
24
+ region = sys.argv[8] if len(sys.argv) > 8 and sys.argv[8] != 'none' else ''
25
+ foam_name = sys.argv[9] if len(sys.argv) > 9 and sys.argv[9] != 'none' else 'case.foam'
26
+ foam = os.path.join(case, foam_name)
27
+ if not os.path.exists(foam):
28
+ open(foam, 'w').close()
29
+ reader = OpenFOAMReader(FileName=foam)
30
+ avail = []
31
+ try:
32
+ avail = [str(x) for x in list(reader.MeshRegions.Available or [])]
33
+ except Exception:
34
+ pass
35
+ if region:
36
+ want = [x for x in avail if x == region or x.endswith('/' + region + '/internalMesh')]
37
+ if not want:
38
+ print('META ' + json.dumps({'ok': False, 'reason': 'region not available', 'region': region, 'regions': avail}))
39
+ sys.exit(3)
40
+ else:
41
+ want = [x for x in avail if x.endswith('/internalMesh')]
42
+ if not want:
43
+ want = ['internalMesh']
44
+ try:
45
+ reader.MeshRegions = want
46
+ except Exception:
47
+ pass
48
+ cells = []
49
+ points = []
50
+ try:
51
+ cells = [str(x) for x in list(reader.CellArrays.Available or [])]
52
+ except Exception:
53
+ pass
54
+ try:
55
+ points = [str(x) for x in list(reader.PointArrays.Available or [])]
56
+ except Exception:
57
+ pass
58
+ if field and (cells or points) and field not in cells and field not in points:
59
+ print('META ' + json.dumps({'ok': False, 'reason': 'field not available', 'field': field, 'regions': avail, 'cellArrays': cells[:40], 'pointArrays': points[:20]}))
60
+ sys.exit(4)
61
+ if field:
62
+ try:
63
+ reader.CellArrays = [field]
64
+ except Exception:
65
+ try:
66
+ reader.PointArrays = [field]
67
+ except Exception:
68
+ pass
69
+ UpdatePipeline()
70
+ view = GetActiveViewOrCreate('RenderView')
71
+ display = Show(reader, view)
72
+ ncells = 0
73
+ try:
74
+ ncells = int(reader.GetDataInformation().GetNumberOfCells())
75
+ except Exception:
76
+ ncells = 0
77
+ if ncells <= 0:
78
+ # Reader builds that do not honour the MeshRegions list fall back to
79
+ # their default selection; only a second zero is a real empty scene.
80
+ try:
81
+ reader.MeshRegions = ['internalMesh']
82
+ UpdatePipeline()
83
+ ncells = int(reader.GetDataInformation().GetNumberOfCells())
84
+ except Exception:
85
+ pass
86
+ if ncells <= 0:
87
+ print('META ' + json.dumps({'ok': False, 'reason': 'empty scene', 'regions': want, 'available': avail}))
88
+ sys.exit(5)
89
+ if field:
90
+ for loc in ('CELLS', 'POINTS'):
91
+ try:
92
+ ColorBy(display, (loc, field))
93
+ break
94
+ except Exception:
95
+ continue
96
+ if step >= 0:
97
+ try:
98
+ view.ViewTime = reader.TimestepValues[step]
99
+ except Exception:
100
+ pass
101
+ # A domain that is much longer in z than in x/y looks like a tiny square
102
+ # from the default -z view (e.g. a 3.5 x 3.5 x 49 m channel): turn the camera
103
+ # so the long axis spans the frame.
104
+ try:
105
+ b = reader.GetDataInformation().GetBounds()
106
+ ex, ey, ez = b[1] - b[0], b[3] - b[2], b[5] - b[4]
107
+ if ez > 2 * max(ex, ey):
108
+ view.GetActiveCamera().Azimuth(90)
109
+ except Exception:
110
+ pass
111
+ ResetCamera(view)
112
+ cam = view.GetActiveCamera()
113
+ cam.Azimuth(az)
114
+ cam.Elevation(el)
115
+ cam.Zoom(zoom)
116
+ Render()
117
+ SaveScreenshot(out, view, ImageResolution=[1200, 800])
118
+ print('META ' + json.dumps({'ok': True, 'regions': want, 'cells': ncells, 'field': field}))
119
+
120
+ main()
121
+ `
122
+
123
+ export function parseRenderMeta(stdout) {
124
+ const line = String(stdout || '').split('\n').find((l) => l.trim().startsWith('META '))
125
+ if (!line) return null
126
+ try { return JSON.parse(line.trim().slice(5)) } catch { return null }
127
+ }
128
+
129
+ export async function doRender(cfg, args) {
130
+ const dir = resolveCase(cfg, args.case_path || args.casePath)
131
+ if (!dir || !existsSync(dir)) return { ok: false, error: 'case not found: ' + dir }
132
+ const pv = cfg.paraviewPython || 'pvpython'
133
+ // Script and PNG live in a temp dir: rendering must not write into the case
134
+ // (a production case may sit on a read-only mount, and stray .png files end
135
+ // up in the time directories).
136
+ const work = join(tmpdir(), 'ofwb-render-' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6))
137
+ try { mkdirSync(work, { recursive: true }) } catch (e) { return { ok: false, error: 'cannot create render dir: ' + (e.message || e) } }
138
+ const script = join(work, 'render.py')
139
+ try { writeFileSync(script, PV_RENDER_SCRIPT) } catch (e) { return { ok: false, error: 'cannot write render script: ' + (e.message || e) } }
140
+ const field = String(args.field || 'none')
141
+ const step = args.time_step != null ? Number(args.time_step) : -1
142
+ const az = Number(args.azimuth) || 0
143
+ const el = Number(args.elevation) || 0
144
+ const zoom = Number(args.zoom) || 1
145
+ const region = String(args.region || '')
146
+ const foam = findFoamFile(dir) || ensureFoamFile(dir).path
147
+ const out = join(work, 'render.png')
148
+ const runArgs = [script, dir, field, 'n' + step, 'n' + az, 'n' + el, 'n' + zoom, out, region || 'none', foam ? basename(foam) : 'none']
149
+ let r = await run('/usr/bin/env', ['-u', 'DISPLAY', pv, ...runArgs], { timeoutMs: 300000 })
150
+ let log = (r.stdout || '') + (r.stderr ? '\n[stderr]\n' + r.stderr : '')
151
+ let meta = parseRenderMeta(r.stdout)
152
+ if ((!r.ok || !existsSync(out)) && /GLX|BadValue|X Error|X_GLX/i.test(log) && existsSync('/usr/bin/xvfb-run')) {
153
+ r = await run('/usr/bin/xvfb-run', ['-a', pv, ...runArgs], { timeoutMs: 300000 })
154
+ log = (r.stdout || '') + (r.stderr ? '\n[stderr]\n' + r.stderr : '')
155
+ meta = parseRenderMeta(r.stdout) || meta
156
+ }
157
+ if (meta && meta.ok === false) {
158
+ if (meta.reason === 'field not available') {
159
+ return {
160
+ ok: false,
161
+ error: `field '${field}' is not in this case`,
162
+ available: { regions: meta.regions, cellArrays: meta.cellArrays, pointArrays: meta.pointArrays },
163
+ hint: 'cellArrays lists the fields ParaView exposes (multi-region readers expose the union); regions look like /fluid/internalMesh',
164
+ }
165
+ }
166
+ if (meta.reason === 'region not available') {
167
+ return {
168
+ ok: false,
169
+ error: `no such mesh region: ${meta.region}`,
170
+ regions: meta.regions,
171
+ hint: 'pass region="fluid" (or "solid"); the available regions are listed in regions',
172
+ }
173
+ }
174
+ if (meta.reason === 'empty scene') {
175
+ return {
176
+ ok: false,
177
+ error: 'empty scene: the selected mesh regions contain no cells',
178
+ regions: meta.regions,
179
+ available: meta.available,
180
+ hint: 'multi-region cases need MeshRegions like /fluid/internalMesh; pass region="<name>" or check that the case actually has a mesh',
181
+ }
182
+ }
183
+ return { ok: false, error: meta.reason || 'render failed', meta }
184
+ }
185
+ if (r.ok && existsSync(out)) {
186
+ return { ok: true, path: out, case: dir, field, time_step: step, region: region || null, regions: meta && meta.regions, cells: meta && meta.cells }
187
+ }
188
+ if (/GLX|BadValue|X Error|X_GLX|SIGSEGV|Segmentation fault|core dumped/i.test(log)) {
189
+ return { ok: false, error: 'headless rendering unavailable: this ParaView build needs a GLX display (no OSMesa/EGL) and cannot create an offscreen GL context.', hint: 'Use a machine with a display, or an OSMesa/EGL ParaView build. xvfb alone is not enough for this build.', log: log.slice(-1200) }
190
+ }
191
+ return { ok: false, error: 'render failed', log: log.slice(-1200) }
192
+ }
193
+
194
+ export const PV_STL_SCRIPT = `import sys
195
+ from paraview.simple import *
196
+
197
+ stl, out = sys.argv[1], sys.argv[2]
198
+ def num(s, d):
199
+ try:
200
+ return float(s[1:]) if s.startswith('n') else float(s)
201
+ except Exception:
202
+ return d
203
+ az = num(sys.argv[3] if len(sys.argv) > 3 else 'n0', 0.0)
204
+ el = num(sys.argv[4] if len(sys.argv) > 4 else 'n0', 0.0)
205
+ zoom = num(sys.argv[5] if len(sys.argv) > 5 else 'n1', 1.0)
206
+ r = OpenDataFile(stl)
207
+ r.UpdatePipeline()
208
+ view = GetActiveViewOrCreate('RenderView')
209
+ Show(r, view)
210
+ view.ViewSize = [1200, 900]
211
+ ResetCamera(view)
212
+ cam = view.GetActiveCamera()
213
+ cam.Azimuth(az)
214
+ cam.Elevation(el)
215
+ cam.Zoom(zoom)
216
+ Render()
217
+ SaveScreenshot(out, view, ImageResolution=[1200, 900])
218
+ print('DONE', out)
219
+ `
220
+
221
+ export async function doRenderStl(cfg, args) {
222
+ const stl = resolveCase(cfg, args.stl_path || args.stlPath)
223
+ if (!stl || !existsSync(stl)) return { ok: false, error: 'stl not found: ' + stl }
224
+ const pv = cfg.paraviewPython || 'pvpython'
225
+ const base = join(tmpdir(), 'ofwb-stl-' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5))
226
+ const script = base + '.py'
227
+ const out = join(dirname(stl), '.stl_render_' + Date.now().toString(36) + '.png')
228
+ try { writeFileSync(script, PV_STL_SCRIPT) } catch (e) { return { ok: false, error: 'cannot write render script: ' + (e.message || e) } }
229
+ const runArgs = [script, stl, out, 'n' + (Number(args.azimuth) || 0), 'n' + (Number(args.elevation) || 0), 'n' + (Number(args.zoom) || 1)]
230
+ let r = await run('/usr/bin/env', ['-u', 'DISPLAY', pv, ...runArgs], { timeoutMs: 300000 })
231
+ let log = (r.stdout || '') + (r.stderr ? '\n[stderr]\n' + r.stderr : '')
232
+ if (!r.ok || !existsSync(out)) {
233
+ r = await run('/usr/bin/env', ['-u', 'DISPLAY', '/usr/bin/xvfb-run', '-a', pv, ...runArgs], { timeoutMs: 300000 })
234
+ log = (r.stdout || '') + (r.stderr ? '\n[stderr]\n' + r.stderr : '')
235
+ }
236
+ if (r.ok && existsSync(out)) return { ok: true, path: out, stl }
237
+ return { ok: false, error: 'stl render failed', log: log.slice(-1200) }
238
+ }
239
+
240
+ // --- paper / document helpers ---
241
+
242
+ export const renderBlocks = (v) => (v && v.image ? [...textOut(v), { type: 'image', attachment: v.image }] : textOut(v))
243
+ export const renderCompare = (v) => {
244
+ const out = textOut(v)
245
+ for (const r of [v && v.a, v && v.b]) if (r && r.image) out.push({ type: 'image', attachment: r.image })
246
+ return out
247
+ }
248
+
249
+ export function makePresentation(ctx) {
250
+ // --- presentation helpers: inline images + tool-call cards ---
251
+ async function attachImage(result) {
252
+ if (!result || !result.ok || !result.path || !existsSync(result.path)) return result
253
+ try {
254
+ const att = ctx.get('attachments')
255
+ if (!att || typeof att.saveImage !== 'function') return result
256
+ const ref = await att.saveImage({ data: readFileSync(result.path), mediaType: 'image/png', name: 'render.png' })
257
+ return { ...result, image: ref }
258
+ } catch (e) {
259
+ return result
260
+ }
261
+ }
262
+
263
+ const fmtDuration = (ms) => {
264
+ if (ms == null) return ''
265
+ const s = Math.round(ms / 1000)
266
+ if (s < 60) return s + 's'
267
+ const m = Math.floor(s / 60)
268
+ if (m < 60) return m + 'm' + (s % 60) + 's'
269
+ return Math.floor(m / 60) + 'h' + (m % 60) + 'm'
270
+ }
271
+ function fmtTable(headers, rows) {
272
+ const all = [headers, ...rows]
273
+ const widths = headers.map((_, i) => Math.max(1, ...all.map((r) => String(r[i] == null ? '' : r[i]).length)))
274
+ const fmt = (r) => r.map((c, i) => String(c == null ? '' : c).padEnd(widths[i])).join(' ')
275
+ return [fmt(headers), widths.map((w) => '-'.repeat(w)).join(' '), ...rows.map(fmt)].join('\n')
276
+ }
277
+
278
+ const RENDERS = {
279
+ openfoam_check: (_args, v) => {
280
+ if (!v || v.ok === false) return textOut(v)
281
+ const f = v.findings || []
282
+ if (!f.length) return [{ type: 'text', text: `check: ${v.path || ''} — no findings` }]
283
+ const multi = f.some((x) => x.region)
284
+ const body = multi
285
+ ? fmtTable(['REGION', 'SEVERITY', 'RULE', 'TITLE'], f.map((x) => [x.region || '(case)', x.severity || '', x.rule || '', x.title || '']))
286
+ : fmtTable(['SEVERITY', 'RULE', 'TITLE'], f.map((x) => [x.severity || '', x.rule || '', x.title || '']))
287
+ const fixes = f.map((x, i) => ` ${i + 1}. ${x.fix || ''}`).join('\n')
288
+ return [{ type: 'text', text: `check: ${v.path || ''} — ${f.length} finding(s)\n\n${body}\n\nfixes:\n${fixes}` }]
289
+ },
290
+ openfoam_run_list: (_args, v) => {
291
+ if (!v || v.ok === false) return textOut(v)
292
+ const runs = v.runs || []
293
+ if (!runs.length) return [{ type: 'text', text: 'runs: none' }]
294
+ const rows = runs.map((r) => [r.runId || '', r.status || (r.running ? 'running' : ''), fmtDuration(r.durationMs), r.lastTime == null ? '' : r.lastTime, r.command || ''])
295
+ return [{ type: 'text', text: `runs: ${runs.length}\n\n${fmtTable(['ID', 'STATUS', 'TIME', 'LAST TIME', 'COMMAND'], rows)}` }]
296
+ },
297
+ openfoam_mesh_verify: (_args, v) => {
298
+ if (!v || v.ok === false) return textOut(v)
299
+ const m = v.metrics || {}
300
+ const rows = Object.entries(m).map(([k, val]) => [k, typeof val === 'object' ? JSON.stringify(val) : String(val)])
301
+ const head = `mesh verify: ${v.pass === true ? 'PASS' : v.pass === false ? 'FAIL' : '?'}`
302
+ const regions = Array.isArray(v.regions) && v.regions.length > 1
303
+ ? '\n\n' + fmtTable(['REGION', 'VERDICT', 'CHECKS'], v.regions.map((r) => [r.region, r.pass ? 'Mesh OK' : r.failedChecks ? `${r.failedChecks} failed` : 'no Mesh OK', r.command]))
304
+ : ''
305
+ const warn = v.warnings && v.warnings.length ? '\n\nwarnings:\n' + v.warnings.map((w) => ' - ' + w).join('\n') : ''
306
+ const sug = v.suggestions && v.suggestions.length ? '\n\nsuggestions:\n' + v.suggestions.map((s, i) => ` ${i + 1}. ${s}`).join('\n') : ''
307
+ return [{ type: 'text', text: `${head}${regions}\n\n${fmtTable(['METRIC', 'VALUE'], rows)}${warn}${sug}` }]
308
+ },
309
+ openfoam_env_check: (_args, v) => {
310
+ if (!v || v.ok === false) return textOut(v)
311
+ const dists = Array.isArray(v.distributions) ? v.distributions : [v]
312
+ const rows = dists.map((d) => [d.distribution || 'default', d.version || '?', d.distributionKind || '', d.ok ? 'ok' : 'FAIL', d.foamRoot || ''])
313
+ const head = `plugin ${v.plugin ? v.plugin.version : '?'}`
314
+ return [{ type: 'text', text: `${head}\n\n${fmtTable(['DIST', 'VERSION', 'KIND', 'STATUS', 'ROOT'], rows)}` }]
315
+ },
316
+ openfoam_list_cases: (_args, v) => {
317
+ if (!v || v.ok === false) return textOut(v)
318
+ const cases = Array.isArray(v.cases) ? v.cases : []
319
+ if (!cases.length) return [{ type: 'text', text: `cases: none under ${v.root || ''}` }]
320
+ const shown = cases.slice(0, 25)
321
+ const rows = shown.map((c) => [c.name || c.path || '', c.solver || '?', c.steady === true ? 'steady' : c.steady === false ? 'transient' : '?', c.endTime == null ? '' : String(c.endTime), (c.strayTimes || []).length ? `stray:${c.strayTimes.length}` : ''])
322
+ const more = cases.length > shown.length ? `\n... ${cases.length - shown.length} more` : ''
323
+ return [{ type: 'text', text: `cases: ${v.count ?? cases.length}\n\n${fmtTable(['CASE', 'SOLVER', 'KIND', 'END', 'NOTE'], rows)}${more}` }]
324
+ },
325
+ openfoam_run_progress: (_args, v) => {
326
+ if (!v || v.ok === false) return textOut(v)
327
+ const rows = [
328
+ ['state', v.state || '?'],
329
+ ['time', v.time == null ? '?' : `${v.time}${v.endTime ? ' / ' + v.endTime : ''}`],
330
+ ['steps', v.steps == null ? '?' : String(v.steps)],
331
+ ['s/step', v.secondsPerStep == null ? '?' : v.secondsPerStep.toFixed(3)],
332
+ ['ETA', v.eta || '-'],
333
+ ['residual floor', v.residualFloor == null ? '?' : String(v.residualFloor)],
334
+ ]
335
+ return [{ type: 'text', text: `progress: ${v.state || '?'} (${v.decision || '?'})\n\n${fmtTable(['FIELD', 'VALUE'], rows)}` }]
336
+ },
337
+ openfoam_solve_verify: (_args, v) => {
338
+ if (!v || v.ok === false) return textOut(v)
339
+ const m = v.metrics || {}
340
+ const rows = [
341
+ ['state', v.state || (m.finished ? 'finished' : '?')],
342
+ ['decision', v.decision || '?'],
343
+ ['time', m.lastTime == null ? '?' : String(m.lastTime)],
344
+ ['steps', m.timeSteps == null ? '?' : String(m.timeSteps)],
345
+ ['residual floor', m.residualFloor == null ? '?' : String(m.residualFloor)],
346
+ ['diverged', m.diverged ? 'yes' : 'no'],
347
+ ['seconds/step', m.secondsPerStep == null ? '?' : Number(m.secondsPerStep).toFixed(3)],
348
+ ['ETA', m.eta || '-'],
349
+ ]
350
+ const reasons = (v.reasons || []).length ? '\n\nreasons:\n' + v.reasons.map((r) => ' - ' + r).join('\n') : ''
351
+ const errors = (m.errors || []).length ? '\n\nerrors:\n' + m.errors.map((e) => ' - ' + e).join('\n') : ''
352
+ return [{ type: 'text', text: `${fmtTable(['FIELD', 'VALUE'], rows)}${reasons}${errors}` }]
353
+ },
354
+ openfoam_usage_report: (_args, v) => {
355
+ if (!v || v.ok === false) return textOut(v)
356
+ const called = Array.isArray(v.called) ? v.called : []
357
+ const rows = called.slice(0, 30).map((c) => [c.name, String(c.count), c.failed ? String(c.failed) : ''])
358
+ const head = `calls: ${v.calls ?? 0} | used: ${called.length} | unused: ${(v.unused || []).length}`
359
+ if (!rows.length) return [{ type: 'text', text: head + '\n\n(nothing called yet)' }]
360
+ return [{ type: 'text', text: `${head}\n\n${fmtTable(['TOOL', 'CALLS', 'FAILED'], rows)}` }]
361
+ },
362
+ }
363
+
364
+ return { attachImage, renderBlocks, renderCompare, RENDERS, fmtTable, fmtDuration }
365
+ }