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

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 +692 -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,142 @@
1
+ // Tool registration layer.
2
+ //
3
+ // Every tool goes through one choke point, so the whole plugin has exactly one
4
+ // place that decides what a model-visible result looks like and how calls are
5
+ // counted. DSH itself validates arguments before execute(), enforces timeoutMs
6
+ // (dsh-tool-call-timeout-policy), snapshots the result as lossless JSON and then
7
+ // renders it with output.render — this module makes sure we never trip those
8
+ // checks and keeps the per-tool declarations honest.
9
+ //
10
+ // Notes from dsh-tools that shaped this file:
11
+ // * `presentCall` is host-local: the Web client derives cards from the call
12
+ // arguments itself, so the plugin does not emit presentation metadata.
13
+ // * only an exact `isConcurrencySafe(args) === true` is scheduled in parallel;
14
+ // an absent classifier is exclusive (fail-closed), but declaring it makes the
15
+ // intent explicit.
16
+ import { textOut } from './runtime.js'
17
+
18
+ /** Every tool result is an object with a boolean `ok`; those are the only fields DSH relies on. */
19
+ const RESULT_SCHEMA = {
20
+ type: 'object',
21
+ properties: { ok: { type: 'boolean' } },
22
+ required: ['ok'],
23
+ }
24
+
25
+ const NAME_RE = /^openfoam_[a-z0-9_]+$/
26
+
27
+ /**
28
+ * Rebuild a value as plain JSON: drop `undefined` (JSON.stringify does the same,
29
+ * but DSH's lossless snapshot rejects it), keep nulls, reject what JSON cannot
30
+ * carry (functions, symbols, bigint, non-finite numbers).
31
+ */
32
+ export function toLosslessJson(value, path = 'result') {
33
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return value
34
+ if (typeof value === 'number') {
35
+ if (!Number.isFinite(value)) throw new TypeError(`${path}: non-finite number cannot be a tool result`)
36
+ return value
37
+ }
38
+ // JSON.stringify turns a hole/undefined array item into null; keep that contract.
39
+ if (Array.isArray(value)) return value.map((v, i) => (v === undefined ? null : toLosslessJson(v, `${path}[${i}]`)))
40
+ if (typeof value === 'object') {
41
+ const out = {}
42
+ for (const [k, v] of Object.entries(value)) {
43
+ if (v === undefined) continue
44
+ out[k] = toLosslessJson(v, `${path}.${k}`)
45
+ }
46
+ return out
47
+ }
48
+ throw new TypeError(`${path}: ${typeof value} cannot be a tool result`)
49
+ }
50
+
51
+ function validateDefinition(tool) {
52
+ if (!tool || typeof tool !== 'object') throw new Error('[openfoam-workbench] tool definition must be an object')
53
+ if (!NAME_RE.test(String(tool.name || ''))) throw new Error(`[openfoam-workbench] bad tool name: ${tool.name}`)
54
+ if (typeof tool.description !== 'string' || !tool.description.trim()) throw new Error(`[openfoam-workbench] ${tool.name}: description is required`)
55
+ if (!tool.parameters || typeof tool.parameters !== 'object') throw new Error(`[openfoam-workbench] ${tool.name}: parameters schema is required`)
56
+ if (typeof tool.execute !== 'function') throw new Error(`[openfoam-workbench] ${tool.name}: execute() is required`)
57
+ }
58
+
59
+ export function makeRegistry(ctx, { RENDERS = {} } = {}) {
60
+ const usage = []
61
+ const registered = new Map()
62
+
63
+ function register(tool) {
64
+ validateDefinition(tool)
65
+ if (registered.has(tool.name)) throw new Error(`[openfoam-workbench] duplicate tool: ${tool.name}`)
66
+
67
+ const output = { ...(tool.output || {}) }
68
+ if (RENDERS[tool.name]) output.render = RENDERS[tool.name]
69
+ if (typeof output.render !== 'function') output.render = (_args, value) => textOut(value)
70
+ // A tool that needs a human decision says so explicitly: the question is
71
+ // rendered before the payload, so the model cannot miss it.
72
+ const baseRender = output.render
73
+ output.render = (args, value) => {
74
+ const blocks = baseRender(args, value)
75
+ const q = value && value.needs_input
76
+ if (!q) return blocks
77
+ const label = (o) => (o && typeof o === 'object' ? `${o.id ?? '?'}: ${o.label ?? ''}` : `${o}`)
78
+ const ask = typeof q.ask === 'string' ? q.ask : typeof q.question === 'string' ? q.question : ''
79
+ if (!ask) return blocks
80
+ const head = q.kind ? `[${q.kind}] ` : ''
81
+ const options = Array.isArray(q.options) && q.options.length ? '\noptions: ' + q.options.map(label).join('; ') : ''
82
+ return [{ type: 'text', text: 'QUESTION — ask the user with ask_user_question before proceeding, in the language the user writes in:\n' + head + ask + options }, ...blocks]
83
+ }
84
+ // Keep the tool's own fields (e.g. a stricter schema) but always require `ok`.
85
+ output.schema = { ...RESULT_SCHEMA, ...(output.schema || {}) }
86
+ tool.output = output
87
+
88
+ // Declare the scheduling intent: only read-only tools say `true`.
89
+ if (typeof tool.isConcurrencySafe !== 'function') tool.isConcurrencySafe = () => false
90
+
91
+ const execute = tool.execute
92
+ tool.execute = async (args, exec) => {
93
+ const rec = { name: tool.name, at: Date.now(), ok: null }
94
+ usage.push(rec)
95
+ if (usage.length > 1000) usage.shift()
96
+ try {
97
+ const value = toLosslessJson(await execute(args, exec))
98
+ rec.ok = value.ok !== false
99
+ return value
100
+ } catch (e) {
101
+ rec.ok = false
102
+ rec.error = String((e && e.message) || e)
103
+ throw e
104
+ }
105
+ }
106
+
107
+ registered.set(tool.name, tool)
108
+ ctx.tools.register(tool)
109
+ }
110
+
111
+ function report() {
112
+ const counts = new Map()
113
+ const failures = new Map()
114
+ for (const r of usage) {
115
+ counts.set(r.name, (counts.get(r.name) || 0) + 1)
116
+ if (r.ok === false) failures.set(r.name, (failures.get(r.name) || 0) + 1)
117
+ }
118
+ const called = [...counts.keys()].sort().map((name) => ({ name, count: counts.get(name), failed: failures.get(name) || 0 }))
119
+ const unused = [...registered.keys()].filter((n) => !counts.has(n)).sort()
120
+ return {
121
+ calls: usage.length,
122
+ called,
123
+ unused,
124
+ lastCall: usage.length ? new Date(usage[usage.length - 1].at).toISOString() : null,
125
+ }
126
+ }
127
+
128
+ /** Recent call records, optionally limited to the last `ms` milliseconds. */
129
+ function history({ ms = 0, name = '' } = {}) {
130
+ const since = ms > 0 ? Date.now() - ms : 0
131
+ return usage.filter((r) => (!since || r.at >= since) && (!name || r.name === name)).map((r) => ({ ...r }))
132
+ }
133
+
134
+ return {
135
+ register,
136
+ report,
137
+ history,
138
+ reset: () => { usage.length = 0 },
139
+ registered,
140
+ usage,
141
+ }
142
+ }
@@ -0,0 +1,126 @@
1
+ // Tool-routing guard.
2
+ //
3
+ // The write policy only covers this plugin's tools. An agent that also has
4
+ // generic shell/file tools can change a case around them, so the plugin watches
5
+ // `tools/pre-execute` and reports (or refuses, depending on the configuration)
6
+ // direct edits of case dictionaries.
7
+ //
8
+ // Text matching on shell commands is evadable on purpose (printf, python -c,
9
+ // variable indirection): the guard is a strong deterrent plus a signal, not a
10
+ // proof. The real boundary stays the DSH sandbox and the approval answerer.
11
+ import { basename } from 'node:path'
12
+
13
+ /** Case-relative dictionaries the plugin owns. */
14
+ const CASE_DIRS = /(^|\/)(system|constant|0|0\.orig|0_orig)\//
15
+ const DICT_FILE = /\.(dict|Dict|properties|Properties|Transport|Schemes|Solution|Dict)$|^(controlDict|fvSchemes|fvSolution|blockMeshDict|snappyHexMeshDict|decomposeParDict|createZonesDict|topoSetDict|regionProperties|regionSolvers|transportProperties|turbulenceProperties|momentumTransport|thermophysicalProperties|thermophysicalTransport|physicalProperties|g|pRef|initialConditions|postProcessDict)$/
16
+ const WRITE_HINTS = /(>>?|\bsed\s+-i|\bperl\s+-[a-z]*i\b|\btee\b|\bcp\b|\bmv\b|\btruncate\b|\binstall\b|\bdd\b|open\([^)]*['"]w|foamDictionary\b[^\n]*-set|writeFileSync|>\/)/
17
+
18
+ const TOOL_FOR = [
19
+ [/(^|\/)(system|constant)\//, 'openfoam_read_dict / openfoam_dict_set'],
20
+ [/(^|\/)0(\/|$)/, 'openfoam_dict_set'],
21
+ ]
22
+
23
+ function looksLikeCaseDictionary(path) {
24
+ const p = String(path || '').replace(/\\/g, '/')
25
+ if (!p) return false
26
+ if (CASE_DIRS.test(p)) return true
27
+ return DICT_FILE.test(basename(p))
28
+ }
29
+
30
+ function redirectFor(path) {
31
+ for (const [re, tool] of TOOL_FOR) if (re.test(String(path || '').replace(/\\/g, '/'))) return tool
32
+ return 'openfoam_dict_set'
33
+ }
34
+
35
+ /**
36
+ * Decide whether one tool call bypasses the plugin's write path.
37
+ * Returns { hit, toolName, target, reason, redirect } or { hit: false }.
38
+ */
39
+ export function classifyToolCall(toolName, args = {}) {
40
+ const name = String(toolName || '')
41
+ // file tools: a direct write to a case dictionary
42
+ if (name === 'write' || name === 'edit' || name === 'apply_patch' || name === 'multi_edit') {
43
+ const path = args.file_path || args.filePath || args.path || ''
44
+ if (looksLikeCaseDictionary(path)) {
45
+ return {
46
+ hit: true,
47
+ toolName: name,
48
+ target: String(path),
49
+ reason: `${name} writes ${path} directly`,
50
+ redirect: redirectFor(path),
51
+ }
52
+ }
53
+ return { hit: false }
54
+ }
55
+ // shell: a command that writes into a case dictionary
56
+ if (name === 'bash' || name === 'bash_sandbox' || name === 'shell') {
57
+ const cmd = String(args.command || args.cmd || '')
58
+ if (!cmd) return { hit: false }
59
+ const hasWrite = WRITE_HINTS.test(cmd)
60
+ const touchesCase = /(^|[\s'"=])(\.{0,2}\/)?([\w.\-/]*\/)?(system|constant|0|0\.orig)\//.test(cmd) || DICT_FILE.test(cmd)
61
+ if (hasWrite && touchesCase) {
62
+ const m = /([\w.\-/]*\/)?(system|constant|0|0\.orig)\/[\w.\-]+/.exec(cmd)
63
+ const target = m ? m[0] : cmd.slice(0, 80)
64
+ return {
65
+ hit: true,
66
+ toolName: name,
67
+ target,
68
+ reason: `bash writes ${target}`,
69
+ redirect: redirectFor(target),
70
+ }
71
+ }
72
+ }
73
+ return { hit: false }
74
+ }
75
+
76
+ const events = []
77
+
78
+ /** Recorded bypass attempts (warn and deny alike). */
79
+ export function routingReport() {
80
+ return {
81
+ count: events.length,
82
+ events: events.slice(-20),
83
+ }
84
+ }
85
+
86
+ export function resetRoutingReport() {
87
+ events.length = 0
88
+ }
89
+
90
+ /**
91
+ * Evaluate one call against the configured mode.
92
+ * off → allow silently
93
+ * warn → allow, record the event (visible in openfoam_usage_report)
94
+ * deny → refuse with a message that names the plugin tool
95
+ */
96
+ export function evaluateToolCall({ toolName, args, mode = 'warn', consume = null, now = () => new Date().toISOString() }) {
97
+ if (mode === 'off') return { decision: 'allow', hit: false }
98
+ const hit = classifyToolCall(toolName, args)
99
+ if (!hit.hit) return { decision: 'allow', hit: false }
100
+
101
+ // strict: a covered write needs a live escalation token for this target
102
+ if (mode === 'strict') {
103
+ const token = typeof consume === 'function' ? consume(hit.target) : null
104
+ if (token && token.ok) {
105
+ events.push({ at: now(), tool: hit.toolName, target: hit.target, decision: 'escalated', escalation: token.id })
106
+ return { decision: 'allow', hit: true, escalation: token.id }
107
+ }
108
+ events.push({ at: now(), tool: hit.toolName, target: hit.target, decision: 'deny' })
109
+ return {
110
+ decision: 'deny',
111
+ hit: true,
112
+ reason: `${hit.reason}; use ${hit.redirect} instead. If no tool can express it, call openfoam_escalate({ target: "${hit.target}", operation: "…", toolsTried: ["<tool that failed>"], why: "…" }) first — it is audited and grants one write`,
113
+ redirect: hit.redirect,
114
+ }
115
+ }
116
+
117
+ events.push({ at: now(), tool: hit.toolName, target: hit.target, decision: mode })
118
+ if (mode === 'deny') {
119
+ return {
120
+ decision: 'deny',
121
+ hit: true,
122
+ reason: `${hit.reason}; use ${hit.redirect} instead so the change is classified, journaled and reversible (openfoam_dict_undo)`,
123
+ }
124
+ }
125
+ return { decision: 'warn', hit: true, reason: hit.reason, redirect: hit.redirect }
126
+ }