taskforce-model-foundry 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +133 -2
- package/bin/tmf.mjs +353 -0
- package/docs/acceptance/evidence/cp62-eval-report.json +279 -0
- package/docs/acceptance/r1-r7-reconciliation.md +185 -0
- package/docs/integration.md +227 -0
- package/docs/tutorial.md +336 -0
- package/integrations/hermes-plugin/taskforce_model_foundry/__init__.py +193 -0
- package/integrations/hermes-plugin/taskforce_model_foundry/bridge.mjs +46 -0
- package/integrations/hermes-plugin/taskforce_model_foundry/plugin.yaml +7 -0
- package/integrations/hermes-plugin/tests/test_register.py +230 -0
- package/integrations/openclaw-plugin/index.mjs +27 -0
- package/integrations/openclaw-plugin/tools.mjs +70 -0
- package/openclaw.plugin.json +24 -0
- package/package.json +70 -4
- package/scripts/e2e-demo.sh +56 -0
- package/src/api.mjs +341 -0
- package/src/config.mjs +342 -0
- package/src/core/autograd.mjs +451 -0
- package/src/core/fsx.mjs +65 -0
- package/src/core/hash.mjs +47 -0
- package/src/core/rng.mjs +70 -0
- package/src/data/clean.mjs +115 -0
- package/src/data/dedupe.mjs +125 -0
- package/src/data/ingest.mjs +184 -0
- package/src/data/pii.mjs +142 -0
- package/src/data/pipeline.mjs +183 -0
- package/src/data/provenance.mjs +88 -0
- package/src/data/split.mjs +193 -0
- package/src/data/synth.mjs +198 -0
- package/src/eval/evaluator.mjs +124 -0
- package/src/eval/gates.mjs +114 -0
- package/src/eval/metrics.mjs +90 -0
- package/src/export/package.mjs +365 -0
- package/src/index.mjs +26 -0
- package/src/integrations/hermes.mjs +177 -0
- package/src/integrations/openclaw.mjs +154 -0
- package/src/jobs/evaluate.mjs +164 -0
- package/src/jobs/runner.mjs +323 -0
- package/src/jobs/train.mjs +303 -0
- package/src/model/lora.mjs +53 -0
- package/src/model/tokenizer.mjs +73 -0
- package/src/model/transformer.mjs +276 -0
- package/src/train/backends/builtin-js.mjs +367 -0
- package/src/train/backends/hf-peft.mjs +549 -0
- package/src/train/backends/hf_peft_runner.py +326 -0
- package/src/train/backends/index.mjs +92 -0
- package/src/train/dataset.mjs +56 -0
- package/src/train/optimizer.mjs +99 -0
- package/src/version.mjs +5 -0
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
// Export packaging: turn a succeeded training job plus an independent
|
|
2
|
+
// evaluation report into a single, self-describing, checksummed bundle.
|
|
3
|
+
//
|
|
4
|
+
// The gate is enforced here and not by the caller: `assertDeliverable` is the
|
|
5
|
+
// only door into `exportModel`, so a failed or baseline-only evaluation cannot
|
|
6
|
+
// be packaged at all. That is deliberate -- an export directory is the thing
|
|
7
|
+
// people copy around, and a bundle on disk is a claim of improvement.
|
|
8
|
+
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { copyFile, readFile, readdir } from 'node:fs/promises';
|
|
11
|
+
import { ensureDir, writeJson, writeFileAtomic, exists } from '../core/fsx.mjs';
|
|
12
|
+
import { sha256File, sha256Json, stableStringify } from '../core/hash.mjs';
|
|
13
|
+
|
|
14
|
+
export const EXPORT_FORMAT = 'tmf.export/v1';
|
|
15
|
+
|
|
16
|
+
export class ExportBlockedError extends Error {
|
|
17
|
+
constructor(message, { status = null, failed = [] } = {}) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.name = 'ExportBlockedError';
|
|
20
|
+
this.code = 'EXPORT_BLOCKED';
|
|
21
|
+
this.status = status;
|
|
22
|
+
this.failed = failed;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Terminal check that an evaluation report authorises delivery.
|
|
28
|
+
*
|
|
29
|
+
* Throws `ExportBlockedError` for anything that is not an explicitly passed
|
|
30
|
+
* gated evaluation -- missing report, baseline-only run, failed gates, or a
|
|
31
|
+
* report whose verdict and gate block disagree.
|
|
32
|
+
*/
|
|
33
|
+
export function assertDeliverable(report) {
|
|
34
|
+
if (!report || typeof report !== 'object') {
|
|
35
|
+
throw new ExportBlockedError('export requires an evaluation report', { status: 'missing' });
|
|
36
|
+
}
|
|
37
|
+
const status = report.verdict?.status ?? null;
|
|
38
|
+
const gatesPassed = report.gates?.passed === true;
|
|
39
|
+
const eligible = report.verdict?.deliveryEligible === true;
|
|
40
|
+
if (status !== 'passed' || !gatesPassed || !eligible) {
|
|
41
|
+
const failed = (report.gates?.failed ?? []).map((f) => f.id ?? f.metric ?? 'gate');
|
|
42
|
+
throw new ExportBlockedError(
|
|
43
|
+
`export blocked: evaluation status is ${status ?? 'unknown'}${failed.length ? ` (failed gates: ${failed.join(', ')})` : ''}`,
|
|
44
|
+
{ status, failed },
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
return report;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function metricSummary(report) {
|
|
51
|
+
const m = report.metrics ?? {};
|
|
52
|
+
return {
|
|
53
|
+
holdoutLoss: m.tuned?.holdout?.loss ?? null,
|
|
54
|
+
baselineHoldoutLoss: m.baseline?.holdout?.loss ?? null,
|
|
55
|
+
holdoutLossRelativeImprovement: m.improvement?.holdoutLossRelative ?? null,
|
|
56
|
+
exactMatch: m.tuned?.holdout?.exactMatch?.accuracy ?? null,
|
|
57
|
+
exactMatchAbsoluteImprovement: m.improvement?.exactMatchAbsolute ?? null,
|
|
58
|
+
validationLossRelativeImprovement: m.improvement?.validationLossRelative ?? null,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function renderModelCard({ name, version, createdAt, report, artifacts, config, files }) {
|
|
63
|
+
const s = metricSummary(report);
|
|
64
|
+
const num = (v) => (typeof v === 'number' ? v.toFixed(6) : 'n/a');
|
|
65
|
+
const pct = (v) => (typeof v === 'number' ? `${(v * 100).toFixed(2)}%` : 'n/a');
|
|
66
|
+
const gateRows = (report.gates?.results ?? [])
|
|
67
|
+
.map((r) => `| ${r.id} | ${r.metric} | ${r.comparator ?? ''} ${r.threshold} | ${num(r.value)} | ${r.passed ? 'pass' : 'FAIL'} |`)
|
|
68
|
+
.join('\n');
|
|
69
|
+
return `# Model card: ${name} ${version}
|
|
70
|
+
|
|
71
|
+
Exported ${createdAt} by taskforce-model-foundry.
|
|
72
|
+
|
|
73
|
+
## What this is
|
|
74
|
+
|
|
75
|
+
A small post-trained model produced from **synthetic data generated by this
|
|
76
|
+
toolkit**. It is a demonstration-scale artifact: it is not trained on real
|
|
77
|
+
enterprise data, and it carries no claim of fitness for production use.
|
|
78
|
+
|
|
79
|
+
- Mode: \`${config?.mode ?? artifacts?.metrics?.mode ?? 'unknown'}\`
|
|
80
|
+
- Backend: \`${report.backend?.id ?? 'unknown'}\`
|
|
81
|
+
- Base checkpoint: \`${path.basename(artifacts?.baseCheckpoint ?? 'n/a')}\`
|
|
82
|
+
- Delivered weights: \`${path.basename(artifacts?.adapterCheckpoint ?? artifacts?.tunedCheckpoint ?? 'n/a')}\`${artifacts?.adapterCheckpoint ? ' (adapter; requires the base checkpoint)' : ''}
|
|
83
|
+
|
|
84
|
+
## Measured results
|
|
85
|
+
|
|
86
|
+
Measured on an independent holdout split that training never saw
|
|
87
|
+
(independence: \`${report.independence?.verdict ?? report.independence?.status ?? 'see eval-report.json'}\`).
|
|
88
|
+
|
|
89
|
+
| metric | value |
|
|
90
|
+
| --- | --- |
|
|
91
|
+
| holdout loss (tuned) | ${num(s.holdoutLoss)} |
|
|
92
|
+
| holdout loss (baseline) | ${num(s.baselineHoldoutLoss)} |
|
|
93
|
+
| holdout loss improvement | ${pct(s.holdoutLossRelativeImprovement)} |
|
|
94
|
+
| exact match (tuned) | ${pct(s.exactMatch)} |
|
|
95
|
+
| exact match improvement | ${pct(s.exactMatchAbsoluteImprovement)} |
|
|
96
|
+
|
|
97
|
+
## Gates
|
|
98
|
+
|
|
99
|
+
| gate | metric | threshold | value | verdict |
|
|
100
|
+
| --- | --- | --- | --- | --- |
|
|
101
|
+
${gateRows || '| (none recorded) | | | | |'}
|
|
102
|
+
|
|
103
|
+
Verdict: **${report.verdict?.status}** — ${report.verdict?.summary ?? ''}
|
|
104
|
+
|
|
105
|
+
## Training data
|
|
106
|
+
|
|
107
|
+
Synthetic, generated locally. See \`data-report.json\` for the record counts,
|
|
108
|
+
dedupe and PII-scan results, and split digests.
|
|
109
|
+
|
|
110
|
+
## Limitations and intended use
|
|
111
|
+
|
|
112
|
+
- Demonstration and integration testing only.
|
|
113
|
+
- Synthetic task distribution; behaviour outside it is unmeasured.
|
|
114
|
+
- No safety tuning, no real-world evaluation, no production authorisation.
|
|
115
|
+
|
|
116
|
+
## Reproduce and roll back
|
|
117
|
+
|
|
118
|
+
See \`inference.md\`.
|
|
119
|
+
|
|
120
|
+
## Files
|
|
121
|
+
|
|
122
|
+
${files.map((f) => `- \`${f.path}\` (sha256 \`${f.sha256.slice(0, 16)}…\`)`).join('\n')}
|
|
123
|
+
`;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function renderInferenceDoc({ name, version, artifacts, config }) {
|
|
127
|
+
const adapter = artifacts?.adapterCheckpoint;
|
|
128
|
+
return `# Reproducible inference and rollback — ${name} ${version}
|
|
129
|
+
|
|
130
|
+
## Verify the bundle first
|
|
131
|
+
|
|
132
|
+
\`\`\`bash
|
|
133
|
+
sha256sum -c checksums.txt
|
|
134
|
+
\`\`\`
|
|
135
|
+
|
|
136
|
+
Every file listed in \`manifest.json\` is covered. A checksum mismatch means the
|
|
137
|
+
bundle was modified after export: do not load it.
|
|
138
|
+
|
|
139
|
+
## Load and run
|
|
140
|
+
|
|
141
|
+
\`\`\`js
|
|
142
|
+
import { backends } from 'taskforce-model-foundry';
|
|
143
|
+
|
|
144
|
+
const backend = await backends.resolveBackend('${config?.backend ?? 'builtin-js'}');
|
|
145
|
+
const handle = await backend.loadModel({
|
|
146
|
+
file: 'weights/base.json',${adapter ? "\n attachAdapter: 'weights/adapter.json'," : ''}
|
|
147
|
+
});
|
|
148
|
+
const out = await backend.generate({ handle, prompt: '<your prompt>', maxNewTokens: 34 });
|
|
149
|
+
\`\`\`
|
|
150
|
+
|
|
151
|
+
Generation defaults to temperature 0 (greedy) and is deterministic, so the same prompt and the
|
|
152
|
+
same checkpoint files reproduce the same completion. The metrics in
|
|
153
|
+
\`model-card.md\` were produced by exactly this path; re-running the evaluation
|
|
154
|
+
against \`eval-report.json\`'s lineage digests should reproduce them.
|
|
155
|
+
|
|
156
|
+
## Roll back
|
|
157
|
+
|
|
158
|
+
${adapter
|
|
159
|
+
? `This export is an **adapter**. To roll back, stop loading
|
|
160
|
+
\`weights/adapter.json\` and serve \`weights/base.json\` alone — the base weights
|
|
161
|
+
are byte-identical to the pre-training checkpoint (see \`lineage.baseCheckpoint\`
|
|
162
|
+
in \`manifest.json\`), so rollback needs no retraining and no other artifact.`
|
|
163
|
+
: `This export is a **full tuned checkpoint**. To roll back, serve
|
|
164
|
+
\`weights/base.json\`, which is the pre-training checkpoint shipped in this same
|
|
165
|
+
bundle for exactly that purpose.`}
|
|
166
|
+
|
|
167
|
+
Rollback is complete when the served checksum matches \`weights/base.json\` in
|
|
168
|
+
\`checksums.txt\`.
|
|
169
|
+
`;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Package a succeeded training job into `outDir`.
|
|
174
|
+
*
|
|
175
|
+
* Requires an evaluation report that passed its gates; see `assertDeliverable`.
|
|
176
|
+
* Returns the manifest, the per-file checksums, and a bundle digest.
|
|
177
|
+
*/
|
|
178
|
+
|
|
179
|
+
// Depth-bounded, extension-filtered copy of a weight directory into the bundle.
|
|
180
|
+
// The same filter the `hf-peft` fingerprint uses, so what gets embedded is what
|
|
181
|
+
// identifies the checkpoint.
|
|
182
|
+
const EMBED_EXTENSIONS = ['.safetensors', '.bin', '.pt', '.json', '.model', '.txt'];
|
|
183
|
+
const EMBED_MAX_DEPTH = 3;
|
|
184
|
+
const EMBED_MAX_BYTES = 512 * 1024 * 1024;
|
|
185
|
+
|
|
186
|
+
async function copyWeightTree(from, to, { depth = 0, budget } = {}) {
|
|
187
|
+
const copied = [];
|
|
188
|
+
let entries;
|
|
189
|
+
try {
|
|
190
|
+
entries = await readdir(from, { withFileTypes: true });
|
|
191
|
+
} catch {
|
|
192
|
+
return copied;
|
|
193
|
+
}
|
|
194
|
+
for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
195
|
+
const src = path.join(from, entry.name);
|
|
196
|
+
if (entry.isDirectory()) {
|
|
197
|
+
if (depth >= EMBED_MAX_DEPTH) continue;
|
|
198
|
+
const nested = await copyWeightTree(src, path.join(to, entry.name), { depth: depth + 1, budget });
|
|
199
|
+
for (const rel of nested) copied.push(path.join(entry.name, rel));
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
if (!entry.isFile()) continue;
|
|
203
|
+
if (!EMBED_EXTENSIONS.includes(path.extname(entry.name))) continue;
|
|
204
|
+
const buf = await readFile(src);
|
|
205
|
+
budget.bytes += buf.length;
|
|
206
|
+
if (budget.bytes > EMBED_MAX_BYTES) {
|
|
207
|
+
throw new Error(`exportModel: embedded weights exceed the ${EMBED_MAX_BYTES} byte bundle limit`);
|
|
208
|
+
}
|
|
209
|
+
await ensureDir(to);
|
|
210
|
+
await writeFileAtomic(path.join(to, entry.name), buf);
|
|
211
|
+
copied.push(entry.name);
|
|
212
|
+
}
|
|
213
|
+
return copied;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async function embedExternalWeights({ pointerFile, root, role }) {
|
|
217
|
+
let payload;
|
|
218
|
+
try {
|
|
219
|
+
payload = JSON.parse(await readFile(pointerFile, 'utf8'));
|
|
220
|
+
} catch {
|
|
221
|
+
// Not a JSON pointer (or not readable as one): nothing to embed.
|
|
222
|
+
return [];
|
|
223
|
+
}
|
|
224
|
+
if (payload?.format !== 'tmf-checkpoint-v1') return [];
|
|
225
|
+
const dir = payload.adapterDir ?? payload.dir ?? null;
|
|
226
|
+
if (!dir || !(await exists(dir))) return [];
|
|
227
|
+
const rel = `weights/${role}-weights`;
|
|
228
|
+
const budget = { bytes: 0 };
|
|
229
|
+
const copied = await copyWeightTree(dir, path.join(root, rel), { budget });
|
|
230
|
+
const files = [];
|
|
231
|
+
for (const name of copied) {
|
|
232
|
+
const to = `${rel}/${name.split(path.sep).join('/')}`;
|
|
233
|
+
files.push({
|
|
234
|
+
path: to,
|
|
235
|
+
role: `${role}-weights`,
|
|
236
|
+
sha256: await sha256File(path.join(root, to)),
|
|
237
|
+
source: path.join(dir, name),
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
return files;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export async function exportModel({
|
|
244
|
+
outDir,
|
|
245
|
+
artifacts,
|
|
246
|
+
evalReport,
|
|
247
|
+
config = null,
|
|
248
|
+
name = config?.project ?? 'taskforce-model',
|
|
249
|
+
version = '0.1.0',
|
|
250
|
+
toolkitVersion = null,
|
|
251
|
+
clock = () => new Date().toISOString(),
|
|
252
|
+
}) {
|
|
253
|
+
if (!outDir) throw new Error('exportModel requires outDir');
|
|
254
|
+
if (!artifacts?.baseCheckpoint) throw new Error('exportModel requires training artifacts with a baseCheckpoint');
|
|
255
|
+
assertDeliverable(evalReport);
|
|
256
|
+
|
|
257
|
+
const createdAt = clock();
|
|
258
|
+
const root = path.resolve(outDir);
|
|
259
|
+
await ensureDir(path.join(root, 'weights'));
|
|
260
|
+
|
|
261
|
+
const copies = [
|
|
262
|
+
{ from: artifacts.baseCheckpoint, to: 'weights/base.json', role: 'base' },
|
|
263
|
+
artifacts.adapterCheckpoint ? { from: artifacts.adapterCheckpoint, to: 'weights/adapter.json', role: 'adapter' } : null,
|
|
264
|
+
artifacts.tunedCheckpoint ? { from: artifacts.tunedCheckpoint, to: 'weights/tuned.json', role: 'tuned' } : null,
|
|
265
|
+
artifacts.dataReportFile ? { from: artifacts.dataReportFile, to: 'data-report.json', role: 'data-report' } : null,
|
|
266
|
+
evalReport.reportFile ? { from: evalReport.reportFile, to: 'eval-report.json', role: 'eval-report' } : null,
|
|
267
|
+
].filter(Boolean);
|
|
268
|
+
|
|
269
|
+
const files = [];
|
|
270
|
+
for (const copy of copies) {
|
|
271
|
+
if (!(await exists(copy.from))) throw new Error(`exportModel: missing input ${copy.role}: ${copy.from}`);
|
|
272
|
+
const dest = path.join(root, copy.to);
|
|
273
|
+
await copyFile(copy.from, dest);
|
|
274
|
+
files.push({ path: copy.to, role: copy.role, sha256: await sha256File(dest), source: copy.from });
|
|
275
|
+
}
|
|
276
|
+
// A `hf-peft` checkpoint file is a *pointer*: it names a local model dir and
|
|
277
|
+
// an adapter dir rather than carrying weights. Copying only the pointer would
|
|
278
|
+
// produce a package that cannot be reloaded anywhere else, so the referenced
|
|
279
|
+
// weight directory is embedded next to it and every embedded file is hashed
|
|
280
|
+
// into the manifest. Builtin-js checkpoints carry their own weights and are
|
|
281
|
+
// untouched by this.
|
|
282
|
+
for (const copy of copies) {
|
|
283
|
+
if (!copy.to.startsWith('weights/')) continue;
|
|
284
|
+
const embedded = await embedExternalWeights({ pointerFile: copy.from, root, role: copy.role });
|
|
285
|
+
for (const entry of embedded) files.push(entry);
|
|
286
|
+
}
|
|
287
|
+
if (!evalReport.reportFile) {
|
|
288
|
+
const dest = path.join(root, 'eval-report.json');
|
|
289
|
+
await writeJson(dest, evalReport);
|
|
290
|
+
files.push({ path: 'eval-report.json', role: 'eval-report', sha256: await sha256File(dest), source: 'inline' });
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const lineage = {
|
|
294
|
+
data: {
|
|
295
|
+
dataDir: artifacts.dataDir ?? null,
|
|
296
|
+
reportFile: artifacts.dataReportFile ?? null,
|
|
297
|
+
splits: evalReport.inputs?.splits ?? null,
|
|
298
|
+
datasets: config?.data?.datasets ?? null,
|
|
299
|
+
synthetic: true,
|
|
300
|
+
},
|
|
301
|
+
parameters: {
|
|
302
|
+
mode: config?.mode ?? null,
|
|
303
|
+
seed: config?.seed ?? null,
|
|
304
|
+
model: config?.model ?? null,
|
|
305
|
+
hyper: config?.hyper ?? null,
|
|
306
|
+
trainBudget: config?.trainBudget ?? null,
|
|
307
|
+
},
|
|
308
|
+
training: {
|
|
309
|
+
jobId: artifacts.jobId ?? null,
|
|
310
|
+
metrics: artifacts.metrics ?? null,
|
|
311
|
+
},
|
|
312
|
+
evaluation: {
|
|
313
|
+
jobId: evalReport.jobId ?? null,
|
|
314
|
+
reportDigest: evalReport.reportDigest ?? null,
|
|
315
|
+
independence: evalReport.independence ?? null,
|
|
316
|
+
gates: evalReport.gates?.results ?? [],
|
|
317
|
+
lineage: evalReport.lineage ?? null,
|
|
318
|
+
},
|
|
319
|
+
baseCheckpoint: files.find((f) => f.role === 'base')?.sha256 ?? null,
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
const manifest = {
|
|
323
|
+
format: EXPORT_FORMAT,
|
|
324
|
+
name,
|
|
325
|
+
version,
|
|
326
|
+
createdAt,
|
|
327
|
+
toolkit: { name: 'taskforce-model-foundry', version: toolkitVersion },
|
|
328
|
+
kind: artifacts.adapterCheckpoint ? 'adapter' : 'full',
|
|
329
|
+
backend: evalReport.backend ?? null,
|
|
330
|
+
metrics: metricSummary(evalReport),
|
|
331
|
+
verdict: evalReport.verdict ?? null,
|
|
332
|
+
lineage,
|
|
333
|
+
files,
|
|
334
|
+
rollback: artifacts.adapterCheckpoint
|
|
335
|
+
? 'serve weights/base.json alone; the adapter is additive and removing it restores pre-training behaviour'
|
|
336
|
+
: 'serve weights/base.json, the pre-training checkpoint shipped in this bundle',
|
|
337
|
+
docs: ['model-card.md', 'inference.md'],
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
const card = renderModelCard({ name, version, createdAt, report: evalReport, artifacts, config, files });
|
|
341
|
+
await writeFileAtomic(path.join(root, 'model-card.md'), card);
|
|
342
|
+
const inference = renderInferenceDoc({ name, version, artifacts, config });
|
|
343
|
+
await writeFileAtomic(path.join(root, 'inference.md'), inference);
|
|
344
|
+
|
|
345
|
+
for (const doc of ['model-card.md', 'inference.md']) {
|
|
346
|
+
files.push({ path: doc, role: 'doc', sha256: await sha256File(path.join(root, doc)), source: 'generated' });
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
manifest.bundleDigest = sha256Json(files.map((f) => [f.path, f.sha256]));
|
|
350
|
+
const manifestFile = path.join(root, 'manifest.json');
|
|
351
|
+
await writeJson(manifestFile, manifest);
|
|
352
|
+
|
|
353
|
+
const checksums = `${files.map((f) => `${f.sha256} ${f.path}`).join('\n')}\n${await sha256File(manifestFile)} manifest.json\n`;
|
|
354
|
+
await writeFileAtomic(path.join(root, 'checksums.txt'), checksums);
|
|
355
|
+
|
|
356
|
+
return {
|
|
357
|
+
outDir: root,
|
|
358
|
+
manifestFile,
|
|
359
|
+
manifest,
|
|
360
|
+
files,
|
|
361
|
+
bundleDigest: manifest.bundleDigest,
|
|
362
|
+
checksumsFile: path.join(root, 'checksums.txt'),
|
|
363
|
+
stable: stableStringify({ digest: manifest.bundleDigest }),
|
|
364
|
+
};
|
|
365
|
+
}
|
package/src/index.mjs
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Package entry point: the stable public surface.
|
|
2
|
+
//
|
|
3
|
+
// High-level operations come from ./api.mjs; the lower-level building blocks
|
|
4
|
+
// are re-exported under namespaces so embedders can compose their own jobs
|
|
5
|
+
// without reaching into file paths that may move.
|
|
6
|
+
|
|
7
|
+
export { PRODUCT, doctor, synthesize, train, status, evaluate } from './api.mjs';
|
|
8
|
+
export { exportModel as exportBundle } from './api.mjs';
|
|
9
|
+
export {
|
|
10
|
+
CONFIG_FORMAT, CONFIG_DEFAULTS, validateConfig, loadConfig, findConfigFile,
|
|
11
|
+
exampleConfig, formatConfigErrors, ConfigError,
|
|
12
|
+
} from './config.mjs';
|
|
13
|
+
|
|
14
|
+
export * as data from './data/pipeline.mjs';
|
|
15
|
+
export * as synth from './data/synth.mjs';
|
|
16
|
+
export * as jobs from './jobs/runner.mjs';
|
|
17
|
+
export * as trainJob from './jobs/train.mjs';
|
|
18
|
+
export * as evalJob from './jobs/evaluate.mjs';
|
|
19
|
+
export * as gates from './eval/gates.mjs';
|
|
20
|
+
export * as backends from './train/backends/index.mjs';
|
|
21
|
+
export * as exporter from './export/package.mjs';
|
|
22
|
+
export { exportModel, assertDeliverable, ExportBlockedError, EXPORT_FORMAT } from './export/package.mjs';
|
|
23
|
+
|
|
24
|
+
export { VERSION } from './version.mjs';
|
|
25
|
+
export * as openclaw from './integrations/openclaw.mjs';
|
|
26
|
+
export * as hermes from './integrations/hermes.mjs';
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// Hermes adapter.
|
|
2
|
+
//
|
|
3
|
+
// Hermes is a messaging agent: a model picks a flat, prefixed tool name and
|
|
4
|
+
// hands the gateway a JSON *string* of arguments, and whatever comes back has
|
|
5
|
+
// to be text the model can read in the next turn. That is a different shape
|
|
6
|
+
// from the OpenClaw tool provider, but it must not be a different product, so
|
|
7
|
+
// this adapter reuses the action table in src/integrations/openclaw.mjs rather
|
|
8
|
+
// than restating it. Adding an action there surfaces it on both hosts.
|
|
9
|
+
//
|
|
10
|
+
// The contract this module promises a Hermes gateway:
|
|
11
|
+
// * `toolSpecs()` is static and side-effect free, and returns OpenAI-style
|
|
12
|
+
// function specs (`tmf_<action>`) with a closed JSON Schema per tool.
|
|
13
|
+
// * `callTool(name, args)` always resolves to an envelope with `ok`, `tool`
|
|
14
|
+
// and a string `content` the model can be shown — including on failure.
|
|
15
|
+
// * `args` may be an object or the JSON string Hermes receives from the
|
|
16
|
+
// model; unparsable JSON is `invalid-json`, not a crash.
|
|
17
|
+
// * Unknown tools, unknown params and unauthorized compute are errors with
|
|
18
|
+
// stable codes, mirroring the OpenClaw codes.
|
|
19
|
+
|
|
20
|
+
import { ACTION_SPECS, ACTION_NAMES, CONTRACT_VERSION } from './openclaw.mjs';
|
|
21
|
+
import * as api from '../api.mjs';
|
|
22
|
+
import { VERSION } from '../version.mjs';
|
|
23
|
+
|
|
24
|
+
export { CONTRACT_VERSION };
|
|
25
|
+
export const HOST = 'hermes';
|
|
26
|
+
|
|
27
|
+
/** Flat tool-name prefix; Hermes tool names are global to a gateway. */
|
|
28
|
+
export const TOOL_PREFIX = 'tmf_';
|
|
29
|
+
|
|
30
|
+
/** JSON Schema fragment per accepted param name, for the tool specs. */
|
|
31
|
+
const PARAM_SCHEMA = {
|
|
32
|
+
configFile: { type: 'string', description: 'Path to a foundry config file; defaults to the adapter config.' },
|
|
33
|
+
requireConfig: { type: 'boolean', description: 'Fail the check when no config file can be loaded.' },
|
|
34
|
+
jobId: { type: 'string', description: 'Job id; omit to use the latest job in the workspace.' },
|
|
35
|
+
auditTail: { type: 'integer', description: 'How many trailing audit-log lines to include.' },
|
|
36
|
+
outDir: { type: 'string', description: 'Output directory.' },
|
|
37
|
+
seed: { type: 'integer', description: 'Deterministic seed for synthesis.' },
|
|
38
|
+
count: { type: 'integer', description: 'Number of synthetic examples to write.' },
|
|
39
|
+
profile: { type: 'string', description: 'Synthetic corpus profile name.' },
|
|
40
|
+
resume: { type: 'boolean', description: 'Resume an interrupted job instead of starting over.' },
|
|
41
|
+
resumeCancelled: { type: 'boolean', description: 'Also resume a job that was cancelled.' },
|
|
42
|
+
auditEveryStep: { type: 'integer', description: 'Audit-log cadence in training steps.' },
|
|
43
|
+
gates: { type: 'object', description: 'Acceptance gate thresholds to apply to the eval report.' },
|
|
44
|
+
reportFile: { type: 'string', description: 'Path to write the evaluation report to.' },
|
|
45
|
+
maxNewTokens: { type: 'integer', description: 'Generation budget per eval sample.' },
|
|
46
|
+
evalReport: { type: 'string', description: 'Path to an existing evaluation report to pin into the export.' },
|
|
47
|
+
version: { type: 'string', description: 'Version label for the exported package.' },
|
|
48
|
+
evaluateIfMissing: { type: 'boolean', description: 'Run evaluation first when no report is pinned.' },
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export const TOOL_NAMES = Object.freeze(ACTION_NAMES.map((a) => `${TOOL_PREFIX}${a}`));
|
|
52
|
+
|
|
53
|
+
function actionOf(tool) {
|
|
54
|
+
if (typeof tool !== 'string' || !tool.startsWith(TOOL_PREFIX)) return null;
|
|
55
|
+
const action = tool.slice(TOOL_PREFIX.length);
|
|
56
|
+
return Object.prototype.hasOwnProperty.call(ACTION_SPECS, action) ? action : null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Static, side-effect-free function specs for a Hermes gateway. */
|
|
60
|
+
export function toolSpecs() {
|
|
61
|
+
return ACTION_NAMES.map((action) => {
|
|
62
|
+
const spec = ACTION_SPECS[action];
|
|
63
|
+
const properties = {};
|
|
64
|
+
for (const p of spec.params) properties[p] = PARAM_SCHEMA[p] ?? { description: `Parameter "${p}".` };
|
|
65
|
+
return {
|
|
66
|
+
type: 'function',
|
|
67
|
+
function: {
|
|
68
|
+
name: `${TOOL_PREFIX}${action}`,
|
|
69
|
+
description: `${spec.summary}${spec.compute ? ' Consumes compute.' : ''}`,
|
|
70
|
+
parameters: {
|
|
71
|
+
type: 'object',
|
|
72
|
+
properties,
|
|
73
|
+
required: [...(spec.required ?? [])],
|
|
74
|
+
additionalProperties: false,
|
|
75
|
+
},
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Static description of the adapter, for `hermes`-side diagnostics. */
|
|
82
|
+
export function manifest() {
|
|
83
|
+
return {
|
|
84
|
+
host: HOST,
|
|
85
|
+
product: api.PRODUCT,
|
|
86
|
+
toolkitVersion: VERSION,
|
|
87
|
+
contractVersion: CONTRACT_VERSION,
|
|
88
|
+
transport: 'tool-call',
|
|
89
|
+
toolPrefix: TOOL_PREFIX,
|
|
90
|
+
tools: TOOL_NAMES.map((name) => ({
|
|
91
|
+
name,
|
|
92
|
+
action: name.slice(TOOL_PREFIX.length),
|
|
93
|
+
compute: ACTION_SPECS[name.slice(TOOL_PREFIX.length)].compute,
|
|
94
|
+
})),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function textOf(value) {
|
|
99
|
+
try {
|
|
100
|
+
return JSON.stringify(value, null, 2) ?? String(value);
|
|
101
|
+
} catch {
|
|
102
|
+
return String(value);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function fail(tool, code, message) {
|
|
107
|
+
return { ok: false, contractVersion: CONTRACT_VERSION, host: HOST, tool, error: { code, message }, content: `ERROR ${code}: ${message}` };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Build an adapter bound to one workspace.
|
|
112
|
+
*
|
|
113
|
+
* `allowCompute: false` mounts the gateway read-only: the diagnostic tools
|
|
114
|
+
* still answer, while anything that would burn compute or write artifacts is
|
|
115
|
+
* refused with `compute-not-authorized` instead of running.
|
|
116
|
+
*/
|
|
117
|
+
export function createHermesAdapter({ baseDir = process.cwd(), configFile = null, allowCompute = true } = {}) {
|
|
118
|
+
const ctx = { baseDir, configFile };
|
|
119
|
+
|
|
120
|
+
async function callTool(tool, args = {}) {
|
|
121
|
+
const action = actionOf(tool);
|
|
122
|
+
if (!action) {
|
|
123
|
+
return fail(typeof tool === 'string' ? tool : String(tool), 'unknown-tool', `unknown tool "${tool}"; known tools: ${TOOL_NAMES.join(', ')}`);
|
|
124
|
+
}
|
|
125
|
+
let params = args;
|
|
126
|
+
if (typeof params === 'string') {
|
|
127
|
+
const trimmed = params.trim();
|
|
128
|
+
if (!trimmed) params = {};
|
|
129
|
+
else {
|
|
130
|
+
try {
|
|
131
|
+
params = JSON.parse(trimmed);
|
|
132
|
+
} catch (err) {
|
|
133
|
+
return fail(tool, 'invalid-json', `arguments were not valid JSON: ${err?.message ?? String(err)}`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (params === null || params === undefined) params = {};
|
|
138
|
+
if (typeof params !== 'object' || Array.isArray(params)) {
|
|
139
|
+
return fail(tool, 'invalid-params', 'arguments must decode to a plain object');
|
|
140
|
+
}
|
|
141
|
+
const spec = ACTION_SPECS[action];
|
|
142
|
+
const unknown = Object.keys(params).filter((k) => !spec.params.includes(k));
|
|
143
|
+
if (unknown.length) {
|
|
144
|
+
return fail(tool, 'unknown-params', `unknown params for "${tool}": ${unknown.join(', ')}`);
|
|
145
|
+
}
|
|
146
|
+
const missing = (spec.required ?? []).filter((k) => params[k] === undefined || params[k] === null);
|
|
147
|
+
if (missing.length) {
|
|
148
|
+
return fail(tool, 'missing-params', `tool "${tool}" requires: ${missing.join(', ')}`);
|
|
149
|
+
}
|
|
150
|
+
if (spec.compute && !allowCompute) {
|
|
151
|
+
return fail(tool, 'compute-not-authorized', `tool "${tool}" consumes compute and this adapter was mounted read-only`);
|
|
152
|
+
}
|
|
153
|
+
try {
|
|
154
|
+
const result = await spec.handler(ctx, params);
|
|
155
|
+
return { ok: true, contractVersion: CONTRACT_VERSION, host: HOST, tool, action, result, content: textOf(result) };
|
|
156
|
+
} catch (err) {
|
|
157
|
+
const code = err?.code && typeof err.code === 'string' ? err.code : err?.name === 'ConfigError' ? 'config-error' : 'action-failed';
|
|
158
|
+
return fail(tool, code, err?.message ?? String(err));
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return { host: HOST, baseDir, allowCompute, manifest, toolSpecs, tools: TOOL_NAMES, callTool };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Registration entry point for a Hermes gateway. */
|
|
166
|
+
export function register(host, options = {}) {
|
|
167
|
+
const adapter = createHermesAdapter(options);
|
|
168
|
+
const specs = toolSpecs();
|
|
169
|
+
if (host && typeof host.registerTool === 'function') {
|
|
170
|
+
for (const spec of specs) host.registerTool({ spec, handler: (args) => adapter.callTool(spec.function.name, args) });
|
|
171
|
+
} else if (host && typeof host.registerTools === 'function') {
|
|
172
|
+
host.registerTools({ tools: specs, handler: adapter.callTool });
|
|
173
|
+
}
|
|
174
|
+
return adapter;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export default { CONTRACT_VERSION, HOST, TOOL_PREFIX, TOOL_NAMES, manifest, toolSpecs, createHermesAdapter, register };
|