taskforce-model-foundry 0.0.0-stage → 0.2.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/2026-11-22-hf-peft-public-pilot.md +75 -0
- package/docs/acceptance/evidence/cp62-eval-report.json +279 -0
- package/docs/acceptance/r1-r7-reconciliation.md +185 -0
- package/docs/integration.md +228 -0
- package/docs/releases/v0.2.0.md +24 -0
- package/docs/tutorial.md +340 -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 +73 -0
- package/openclaw.plugin.json +25 -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 +137 -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/async-evaluate-worker.mjs +39 -0
- package/src/integrations/async-evaluate.mjs +125 -0
- package/src/integrations/hermes.mjs +177 -0
- package/src/integrations/openclaw.mjs +164 -0
- package/src/jobs/evaluate.mjs +172 -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 +597 -0
- package/src/train/backends/hf_peft_runner.py +397 -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,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 };
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// OpenClaw adapter.
|
|
2
|
+
//
|
|
3
|
+
// OpenClaw hosts load foundry capability as an in-process tool provider: the
|
|
4
|
+
// host passes an action name plus a JSON params object and expects a
|
|
5
|
+
// JSON-serializable envelope back, never a thrown exception and never a shell
|
|
6
|
+
// out. Everything here therefore goes through src/api.mjs, so the adapter and
|
|
7
|
+
// the `tmf` CLI cannot drift apart.
|
|
8
|
+
//
|
|
9
|
+
// The contract this module promises to an OpenClaw host:
|
|
10
|
+
// * `manifest()` is static, side-effect free, and declares every action with
|
|
11
|
+
// its accepted params and whether invoking it consumes compute.
|
|
12
|
+
// * `invoke(action, params)` always resolves to
|
|
13
|
+
// `{ ok, contractVersion, action, result }` or
|
|
14
|
+
// `{ ok: false, contractVersion, action, error: { code, message } }`.
|
|
15
|
+
// * Unknown actions, unknown params and unauthorized compute are errors with
|
|
16
|
+
// stable codes, not crashes.
|
|
17
|
+
// * No config value is echoed back verbatim; results are the API records.
|
|
18
|
+
|
|
19
|
+
import * as api from '../api.mjs';
|
|
20
|
+
import { startBackgroundEvaluation, backgroundEvaluationStatus } from './async-evaluate.mjs';
|
|
21
|
+
import { VERSION } from '../version.mjs';
|
|
22
|
+
|
|
23
|
+
/** Bumped only on a breaking change to the action set or envelope shape. */
|
|
24
|
+
export const CONTRACT_VERSION = 1;
|
|
25
|
+
export const HOST = 'openclaw';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Action table. `compute: true` marks actions that spend real CPU/GPU time and
|
|
29
|
+
* write run artifacts, which a host may gate behind its own authority check.
|
|
30
|
+
*/
|
|
31
|
+
const ACTIONS = {
|
|
32
|
+
doctor: {
|
|
33
|
+
summary: 'Environment and configuration self-check; reports every check.',
|
|
34
|
+
params: ['configFile', 'requireConfig'],
|
|
35
|
+
compute: false,
|
|
36
|
+
handler: (ctx, p) => api.doctor({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, requireConfig: p.requireConfig ?? false }),
|
|
37
|
+
},
|
|
38
|
+
status: {
|
|
39
|
+
summary: 'Durable job state plus a tail of its audit log.',
|
|
40
|
+
params: ['jobId', 'configFile', 'auditTail'],
|
|
41
|
+
compute: false,
|
|
42
|
+
required: ['jobId'],
|
|
43
|
+
handler: (ctx, p) => api.status({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId, auditTail: p.auditTail ?? 10 }),
|
|
44
|
+
},
|
|
45
|
+
synthesize: {
|
|
46
|
+
summary: 'Write a synthetic training corpus (no private data involved).',
|
|
47
|
+
params: ['outDir', 'seed', 'count', 'profile'],
|
|
48
|
+
compute: true,
|
|
49
|
+
handler: (ctx, p) => api.synthesize({ baseDir: ctx.baseDir, ...p }),
|
|
50
|
+
},
|
|
51
|
+
train: {
|
|
52
|
+
summary: 'Run a post-training job that updates real weights or an adapter.',
|
|
53
|
+
params: ['configFile', 'jobId', 'resume', 'resumeCancelled', 'auditEveryStep'],
|
|
54
|
+
compute: true,
|
|
55
|
+
handler: (ctx, p) => api.train({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId ?? null, resume: p.resume ?? true, resumeCancelled: p.resumeCancelled ?? false, auditEveryStep: p.auditEveryStep ?? 10 }),
|
|
56
|
+
},
|
|
57
|
+
evaluate: {
|
|
58
|
+
summary: 'Score base vs trained model on the independent holdout and apply gates.',
|
|
59
|
+
params: ['configFile', 'jobId', 'gates', 'reportFile', 'maxNewTokens', 'background', 'retry'],
|
|
60
|
+
compute: true,
|
|
61
|
+
handler: (ctx, p) => p.background
|
|
62
|
+
? startBackgroundEvaluation({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId, gates: p.gates ?? null, reportFile: p.reportFile ?? null, maxNewTokens: p.maxNewTokens ?? 48, retry: p.retry ?? false })
|
|
63
|
+
: api.evaluate({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId ?? null, gates: p.gates ?? null, reportFile: p.reportFile ?? null, maxNewTokens: p.maxNewTokens ?? 48 }),
|
|
64
|
+
},
|
|
65
|
+
evaluate_status: {
|
|
66
|
+
summary: 'Read a durable background evaluation receipt without consuming compute.',
|
|
67
|
+
params: ['configFile', 'jobId', 'requestId'],
|
|
68
|
+
required: ['jobId', 'requestId'],
|
|
69
|
+
compute: false,
|
|
70
|
+
handler: (ctx, p) => backgroundEvaluationStatus({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId, requestId: p.requestId }),
|
|
71
|
+
},
|
|
72
|
+
export: {
|
|
73
|
+
summary: 'Package weights/adapter with lineage, model card and checksums.',
|
|
74
|
+
params: ['configFile', 'jobId', 'evalReport', 'outDir', 'version', 'evaluateIfMissing'],
|
|
75
|
+
compute: true,
|
|
76
|
+
handler: (ctx, p) => api.exportModel({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId ?? null, evalReport: p.evalReport ?? null, outDir: p.outDir ?? null, version: p.version ?? null, evaluateIfMissing: p.evaluateIfMissing ?? true }),
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
export const ACTION_NAMES = Object.freeze(Object.keys(ACTIONS));
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The action table itself, shared with the other host adapters (see
|
|
84
|
+
* src/integrations/hermes.mjs) so a second host cannot drift from this one:
|
|
85
|
+
* one action set, one set of handlers, one place to add an action.
|
|
86
|
+
*/
|
|
87
|
+
export const ACTION_SPECS = Object.freeze(ACTIONS);
|
|
88
|
+
|
|
89
|
+
/** Static, side-effect-free description of what this adapter offers a host. */
|
|
90
|
+
export function manifest() {
|
|
91
|
+
return {
|
|
92
|
+
host: HOST,
|
|
93
|
+
product: api.PRODUCT,
|
|
94
|
+
toolkitVersion: VERSION,
|
|
95
|
+
contractVersion: CONTRACT_VERSION,
|
|
96
|
+
transport: 'in-process',
|
|
97
|
+
actions: ACTION_NAMES.map((name) => ({
|
|
98
|
+
name,
|
|
99
|
+
summary: ACTIONS[name].summary,
|
|
100
|
+
params: [...ACTIONS[name].params],
|
|
101
|
+
required: [...(ACTIONS[name].required ?? [])],
|
|
102
|
+
compute: ACTIONS[name].compute,
|
|
103
|
+
})),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function fail(action, code, message) {
|
|
108
|
+
return { ok: false, contractVersion: CONTRACT_VERSION, action, error: { code, message } };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Build an adapter bound to one workspace.
|
|
113
|
+
*
|
|
114
|
+
* `allowCompute: false` lets a host mount the adapter for inspection only —
|
|
115
|
+
* doctor and status still answer, while anything that would burn compute or
|
|
116
|
+
* write artifacts is refused with `compute-not-authorized` instead of running.
|
|
117
|
+
*/
|
|
118
|
+
export function createOpenClawAdapter({ baseDir = process.cwd(), configFile = null, allowCompute = true } = {}) {
|
|
119
|
+
const ctx = { baseDir, configFile };
|
|
120
|
+
|
|
121
|
+
async function invoke(action, params = {}) {
|
|
122
|
+
if (typeof action !== 'string' || !action) {
|
|
123
|
+
return fail(String(action), 'invalid-action', 'action must be a non-empty string');
|
|
124
|
+
}
|
|
125
|
+
const spec = ACTIONS[action];
|
|
126
|
+
if (!spec) {
|
|
127
|
+
return fail(action, 'unknown-action', `unknown action "${action}"; known actions: ${ACTION_NAMES.join(', ')}`);
|
|
128
|
+
}
|
|
129
|
+
if (params === null || typeof params !== 'object' || Array.isArray(params)) {
|
|
130
|
+
return fail(action, 'invalid-params', 'params must be a plain object');
|
|
131
|
+
}
|
|
132
|
+
const unknown = Object.keys(params).filter((k) => !spec.params.includes(k));
|
|
133
|
+
if (unknown.length) {
|
|
134
|
+
return fail(action, 'unknown-params', `unknown params for "${action}": ${unknown.join(', ')}`);
|
|
135
|
+
}
|
|
136
|
+
const missing = (spec.required ?? []).filter((k) => params[k] === undefined || params[k] === null);
|
|
137
|
+
if (missing.length) {
|
|
138
|
+
return fail(action, 'missing-params', `action "${action}" requires: ${missing.join(', ')}`);
|
|
139
|
+
}
|
|
140
|
+
if (spec.compute && !allowCompute) {
|
|
141
|
+
return fail(action, 'compute-not-authorized', `action "${action}" consumes compute and this adapter was mounted read-only`);
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
const result = await spec.handler(ctx, params);
|
|
145
|
+
return { ok: true, contractVersion: CONTRACT_VERSION, action, result };
|
|
146
|
+
} catch (err) {
|
|
147
|
+
const code = err?.code && typeof err.code === 'string' ? err.code : err?.name === 'ConfigError' ? 'config-error' : 'action-failed';
|
|
148
|
+
return fail(action, code, err?.message ?? String(err));
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return { host: HOST, baseDir, allowCompute, manifest, actions: ACTION_NAMES, invoke };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Registration entry point for an OpenClaw plugin host. */
|
|
156
|
+
export function register(host, options = {}) {
|
|
157
|
+
const adapter = createOpenClawAdapter(options);
|
|
158
|
+
if (host && typeof host.registerToolProvider === 'function') {
|
|
159
|
+
host.registerToolProvider({ name: api.PRODUCT, manifest: manifest(), invoke: adapter.invoke });
|
|
160
|
+
}
|
|
161
|
+
return adapter;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export default { CONTRACT_VERSION, HOST, manifest, createOpenClawAdapter, register, ACTION_NAMES };
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// The evaluation job.
|
|
2
|
+
//
|
|
3
|
+
// A re-runnable unit of work that turns a checkpoint pair plus held-out data
|
|
4
|
+
// into a gate verdict and a lineage-bearing report. It is deliberately the
|
|
5
|
+
// only place allowed to decide whether a run may be described as an
|
|
6
|
+
// improvement: `verdict.improvementClaimAllowed` is false unless the gates
|
|
7
|
+
// actually passed, and `assertDeliverable` is what export paths call so a
|
|
8
|
+
// failed gate is terminal rather than advisory.
|
|
9
|
+
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { evaluateGates, DEFAULT_GATES } from '../eval/gates.mjs';
|
|
12
|
+
import {
|
|
13
|
+
EVAL_REPORT_FORMAT, assertHoldoutIndependence, evaluateSplitSet, assembleMetrics,
|
|
14
|
+
} from '../eval/evaluator.mjs';
|
|
15
|
+
import { sha256File, sha256Json } from '../core/hash.mjs';
|
|
16
|
+
import { writeJson, exists } from '../core/fsx.mjs';
|
|
17
|
+
|
|
18
|
+
// A report handed in from outside (`tmf export --report`) is only usable as a
|
|
19
|
+
// gate record if it still hashes to its own `reportDigest`: otherwise the
|
|
20
|
+
// bundle would claim lineage for numbers nobody evaluated.
|
|
21
|
+
export function assertReportIntegrity(report, { jobId = null } = {}) {
|
|
22
|
+
if (!report || typeof report !== 'object') throw new Error('eval report must be an object');
|
|
23
|
+
if (report.format !== EVAL_REPORT_FORMAT) {
|
|
24
|
+
throw new Error(`eval report format mismatch: expected ${EVAL_REPORT_FORMAT}, got ${report.format ?? 'none'}`);
|
|
25
|
+
}
|
|
26
|
+
if (!report.reportDigest) throw new Error('eval report is missing reportDigest');
|
|
27
|
+
// Mirror how the digest was produced: `reportDigest` stays as an undefined
|
|
28
|
+
// key (which canonicalizes to null), while `reportFile` — attached only
|
|
29
|
+
// in-memory after the write — must be absent, not undefined.
|
|
30
|
+
const canonical = { ...report, reportDigest: undefined };
|
|
31
|
+
delete canonical.reportFile;
|
|
32
|
+
const recomputed = sha256Json(canonical);
|
|
33
|
+
if (recomputed !== report.reportDigest) {
|
|
34
|
+
throw new Error(`eval report digest mismatch: file claims ${report.reportDigest}, contents hash to ${recomputed}`);
|
|
35
|
+
}
|
|
36
|
+
const reportJob = report.lineage?.jobId ?? null;
|
|
37
|
+
if (jobId && reportJob && reportJob !== jobId) {
|
|
38
|
+
throw new Error(`eval report belongs to job ${reportJob}, not ${jobId}`);
|
|
39
|
+
}
|
|
40
|
+
return report;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function checkpointRef(file) {
|
|
44
|
+
if (!file) return null;
|
|
45
|
+
if (!(await exists(file))) throw new Error(`checkpoint not found: ${file}`);
|
|
46
|
+
return { file, sha256: await sha256File(file) };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function runEvaluationJob({
|
|
50
|
+
backend,
|
|
51
|
+
baseCheckpoint,
|
|
52
|
+
adapterCheckpoint = null,
|
|
53
|
+
tunedCheckpoint = null,
|
|
54
|
+
encoded,
|
|
55
|
+
records = {},
|
|
56
|
+
gates = DEFAULT_GATES,
|
|
57
|
+
lineage = {},
|
|
58
|
+
reportFile = null,
|
|
59
|
+
maxNewTokens = 48,
|
|
60
|
+
jobId = null,
|
|
61
|
+
clock = () => new Date().toISOString(),
|
|
62
|
+
} = {}) {
|
|
63
|
+
if (!backend) throw new Error('runEvaluationJob needs a backend');
|
|
64
|
+
if (!baseCheckpoint) throw new Error('runEvaluationJob needs a base checkpoint');
|
|
65
|
+
const startedAt = clock();
|
|
66
|
+
|
|
67
|
+
const independence = assertHoldoutIndependence({
|
|
68
|
+
holdout: records.holdout ?? [],
|
|
69
|
+
train: records.train ?? [],
|
|
70
|
+
validation: records.validation ?? [],
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
const baseRef = await checkpointRef(baseCheckpoint);
|
|
74
|
+
const adapterRef = await checkpointRef(adapterCheckpoint);
|
|
75
|
+
const tunedRef = await checkpointRef(tunedCheckpoint);
|
|
76
|
+
|
|
77
|
+
// Baseline is the base checkpoint with no adapter attached. For a LoRA run
|
|
78
|
+
// the tuned side is that same base with the adapter layered on; for a
|
|
79
|
+
// full-parameter run (pretrain / full-finetune) the trainer writes a whole
|
|
80
|
+
// tuned checkpoint instead, and that file is the tuned side. Either way both
|
|
81
|
+
// sides are loaded from disk, which is what makes the comparison independent
|
|
82
|
+
// of trainer state -- and without the full-checkpoint path those modes could
|
|
83
|
+
// never produce gates, so export stayed permanently blocked for them.
|
|
84
|
+
const baselineHandle = await backend.loadModel({ file: baseCheckpoint });
|
|
85
|
+
const baselineFingerprint = backend.fingerprint(baselineHandle);
|
|
86
|
+
const baseline = await evaluateSplitSet(backend, baselineHandle, { encoded, records, maxNewTokens });
|
|
87
|
+
|
|
88
|
+
let tuned = null;
|
|
89
|
+
let tunedFingerprint = null;
|
|
90
|
+
let adapterBaseFingerprint = null;
|
|
91
|
+
if (adapterCheckpoint || tunedCheckpoint) {
|
|
92
|
+
const tunedHandle = adapterCheckpoint
|
|
93
|
+
? await backend.loadModel({ file: baseCheckpoint, attachAdapter: adapterCheckpoint })
|
|
94
|
+
: await backend.loadModel({ file: tunedCheckpoint });
|
|
95
|
+
tunedFingerprint = backend.fingerprint(tunedHandle);
|
|
96
|
+
adapterBaseFingerprint = tunedHandle.meta?.baseFingerprint ?? null;
|
|
97
|
+
tuned = await evaluateSplitSet(backend, tunedHandle, { encoded, records, maxNewTokens });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const metrics = assembleMetrics({ baseline, tuned });
|
|
101
|
+
const verdictGates = tuned ? evaluateGates(metrics, gates) : null;
|
|
102
|
+
const status = !tuned ? 'baseline_only' : (verdictGates.passed ? 'passed' : 'failed');
|
|
103
|
+
|
|
104
|
+
const report = {
|
|
105
|
+
format: EVAL_REPORT_FORMAT,
|
|
106
|
+
jobId: jobId ?? `eval-${startedAt}`,
|
|
107
|
+
startedAt,
|
|
108
|
+
finishedAt: clock(),
|
|
109
|
+
backend: { id: backend.id, label: backend.label ?? null },
|
|
110
|
+
execution: {
|
|
111
|
+
device: baseline.holdout.device ?? null,
|
|
112
|
+
tunedDevice: tuned?.holdout.device ?? null,
|
|
113
|
+
},
|
|
114
|
+
inputs: {
|
|
115
|
+
baseCheckpoint: baseRef,
|
|
116
|
+
adapterCheckpoint: adapterRef,
|
|
117
|
+
tunedCheckpoint: tunedRef,
|
|
118
|
+
splits: {
|
|
119
|
+
holdout: encoded.holdout?.length ?? 0,
|
|
120
|
+
validation: encoded.validation?.length ?? 0,
|
|
121
|
+
trainWithheld: records.train?.length ?? 0,
|
|
122
|
+
},
|
|
123
|
+
},
|
|
124
|
+
independence,
|
|
125
|
+
metrics,
|
|
126
|
+
gates: verdictGates ?? { passed: false, results: [], failed: [], summary: 'no tuned model to gate' },
|
|
127
|
+
verdict: {
|
|
128
|
+
status,
|
|
129
|
+
improvementClaimAllowed: status === 'passed',
|
|
130
|
+
deliveryEligible: status === 'passed',
|
|
131
|
+
summary: status === 'passed'
|
|
132
|
+
? `improvement confirmed on an independent holdout (${verdictGates.summary})`
|
|
133
|
+
: status === 'failed'
|
|
134
|
+
? `gates failed, no improvement may be claimed (${verdictGates.summary}): ${verdictGates.failed.map((f) => f.reason).join('; ')}`
|
|
135
|
+
: 'baseline-only evaluation: no tuned checkpoint was supplied, so no improvement may be claimed',
|
|
136
|
+
},
|
|
137
|
+
lineage: {
|
|
138
|
+
...lineage,
|
|
139
|
+
// Some backends fingerprint the composed base+adapter handle, so its
|
|
140
|
+
// digest must differ from the base. Prefer the base fingerprint recorded
|
|
141
|
+
// in the adapter checkpoint; older backends with no recorded base digest
|
|
142
|
+
// retain the original shared-fingerprint comparison.
|
|
143
|
+
baseFingerprint: baselineFingerprint,
|
|
144
|
+
tunedFingerprint,
|
|
145
|
+
// Only an adapter run can be "bound to base". A full-parameter tuned
|
|
146
|
+
// checkpoint has no adapter, so reporting false there would read as a
|
|
147
|
+
// broken binding instead of "not applicable".
|
|
148
|
+
adapterBoundToBase: adapterCheckpoint
|
|
149
|
+
? (adapterBaseFingerprint ?? tunedFingerprint) === baselineFingerprint
|
|
150
|
+
: null,
|
|
151
|
+
gateDefinitions: gates.map((g) => ({ id: g.id, metric: g.metric, comparator: g.comparator, threshold: g.threshold })),
|
|
152
|
+
gateDefinitionsDigest: sha256Json(gates),
|
|
153
|
+
},
|
|
154
|
+
};
|
|
155
|
+
report.reportDigest = sha256Json({ ...report, reportDigest: undefined });
|
|
156
|
+
|
|
157
|
+
if (reportFile) {
|
|
158
|
+
await writeJson(reportFile, report);
|
|
159
|
+
report.reportFile = path.resolve(reportFile);
|
|
160
|
+
}
|
|
161
|
+
return report;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// Delivery/export gate. Callers that want the non-throwing form read
|
|
165
|
+
// `report.verdict.deliveryEligible` instead.
|
|
166
|
+
export function assertDeliverable(report) {
|
|
167
|
+
if (report?.verdict?.deliveryEligible) return report;
|
|
168
|
+
const err = new Error(`evaluation report is not deliverable: ${report?.verdict?.summary ?? 'missing verdict'}`);
|
|
169
|
+
err.code = 'EVAL_NOT_DELIVERABLE';
|
|
170
|
+
err.report = report;
|
|
171
|
+
throw err;
|
|
172
|
+
}
|