@hmharness/evolution 0.14.22 → 0.14.24

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.
@@ -0,0 +1,132 @@
1
+ import type { DpoPair } from './reward-model.ts';
2
+ /** A fine-tunable model + how its jobs are priced. Prices change - the
3
+ * caller renders the estimate, the catalog only carries what we verified. */
4
+ export interface FineTuneModelInfo {
5
+ id: string;
6
+ dpo: boolean;
7
+ note: string;
8
+ }
9
+ /** Models verified as fine-tunable (guide + live probe 2026-09-25: bare
10
+ * glm-4-air 404s "微调模型不存在", glm-4-flash passes model validation). */
11
+ export declare const FINE_TUNE_CATALOG: FineTuneModelInfo[];
12
+ export declare const DEFAULT_FINE_TUNE_MODEL = "glm-4-flash";
13
+ /**
14
+ * Model auto-selection (user direction 2026-09-25: novices must never pick
15
+ * a fine-tune base). Candidates: the user's MAIN model first - if the API
16
+ * rejects it (live probe 2026-09-25: glm-5.3 answers "微调功能未开放") the
17
+ * ladder silently falls to the next documented fine-tunable base. The probe
18
+ * POSTs {model, training_file:"file-probe-invalid"} - model validation runs
19
+ * BEFORE file binding, so the request always fails without creating
20
+ * anything, and the error text tells us whether the model is usable.
21
+ */
22
+ export declare function fineTuneModelLadder(mainModel: string): string[];
23
+ /** Zero-side-effect model probe (the request can never create a job - the
24
+ * training_file id is invalid on purpose). "model rejected" vs "reached
25
+ * file validation" is distinguishable in the error text. */
26
+ export declare function probeFineTuneModel(opts: {
27
+ apiKey: string;
28
+ baseUrl: string;
29
+ model: string;
30
+ fetchImpl?: typeof fetch;
31
+ }): Promise<{
32
+ usable: boolean;
33
+ reason?: string;
34
+ }>;
35
+ /** Walk the ladder, return the first usable model plus why earlier ones
36
+ * were skipped (surfaced as one Chinese line - the backend adapts, the
37
+ * user reads, never chooses). */
38
+ export declare function pickFineTuneModel(opts: {
39
+ apiKey: string;
40
+ baseUrl: string;
41
+ mainModel: string;
42
+ log?: (line: string) => void;
43
+ fetchImpl?: typeof fetch;
44
+ }): Promise<string>;
45
+ /**
46
+ * Fine-tuning does not live on the coding endpoint: config.json points the
47
+ * chat route at /api/coding/paas/v4, but the fine_tuning/file APIs sit on
48
+ * /api/paas/v4. Strip the coding segment so the user's existing glm provider
49
+ * entry works unchanged (zero new configuration).
50
+ */
51
+ export declare function normalizeFineTuneBase(baseUrl: string): string;
52
+ /** Serialize pairs into the provider DPO JSONL row format (pure). Accepts
53
+ * the slim {prompt,chosen,rejected} rows the CLI persists - provenance
54
+ * fields never leave the machine.
55
+ * Format verified live 2026-09-25: the documented {"input":{"messages":...}}
56
+ * nesting is REJECTED by the upload validator ("缺少messages字段"); the
57
+ * accepted shape is top-level messages (MUST contain an assistant turn -
58
+ * "缺少assistant角色" otherwise) plus preferred_output/non_preferred_output.
59
+ * The assistant turn carries the chosen answer, so the row is a complete
60
+ * good trajectory and the preference pair trains the separation. */
61
+ export declare function toDpoJsonl(pairs: Array<Pick<DpoPair, 'prompt' | 'chosen' | 'rejected'>>): string;
62
+ /** Rough token estimate for a cost preview before upload (chars/4 heuristic;
63
+ * the upload response returns exact per-tokenizer stats which the UI shows
64
+ * alongside - this is only the pre-flight number). */
65
+ export declare function estimateTokens(jsonl: string): number;
66
+ /** Training cost = tokens × epochs × unit price. Pure math, price supplied
67
+ * by the caller (it changes; we never bake it in as truth). */
68
+ export declare function estimateTrainingCost(tokens: number, epochs: number, pricePerKTokens: number): number;
69
+ export interface UploadedFile {
70
+ id: string;
71
+ bytes: number;
72
+ samples: number;
73
+ /** tokens counted by the provider tokenizer (max of the reported stats). */
74
+ tokens: number;
75
+ }
76
+ /** Upload a training/validation JSONL (free operation, verified live). */
77
+ export declare function uploadFineTuneFile(opts: {
78
+ apiKey: string;
79
+ baseUrl: string;
80
+ filename: string;
81
+ jsonl: string;
82
+ fetchImpl?: typeof fetch;
83
+ }): Promise<UploadedFile>;
84
+ export interface FineTuneJob {
85
+ id: string;
86
+ model?: string;
87
+ status?: string;
88
+ fine_tuned_model?: string;
89
+ training_file?: string;
90
+ created_at?: number;
91
+ [k: string]: unknown;
92
+ }
93
+ /** Create a fine-tuning job (PAID - callers must gate behind explicit
94
+ * submit consent; uploads alone are free). */
95
+ export declare function createFineTuneJob(opts: {
96
+ apiKey: string;
97
+ baseUrl: string;
98
+ model: string;
99
+ trainingFile: string;
100
+ validationFile?: string;
101
+ suffix?: string;
102
+ hyperparameters?: {
103
+ batch_size?: number | 'auto';
104
+ learning_rate_multiplier?: number | 'auto';
105
+ n_epochs?: number | 'auto';
106
+ };
107
+ fetchImpl?: typeof fetch;
108
+ }): Promise<FineTuneJob>;
109
+ export declare function listFineTuneJobs(opts: {
110
+ apiKey: string;
111
+ baseUrl: string;
112
+ limit?: number;
113
+ fetchImpl?: typeof fetch;
114
+ }): Promise<FineTuneJob[]>;
115
+ export declare function retrieveFineTuneJob(opts: {
116
+ apiKey: string;
117
+ baseUrl: string;
118
+ jobId: string;
119
+ fetchImpl?: typeof fetch;
120
+ }): Promise<FineTuneJob>;
121
+ export declare function cancelFineTuneJob(opts: {
122
+ apiKey: string;
123
+ baseUrl: string;
124
+ jobId: string;
125
+ fetchImpl?: typeof fetch;
126
+ }): Promise<FineTuneJob>;
127
+ /** Append-only record of jobs this machine submitted (audit trail: what was
128
+ * trained, on which file, when - survives provider console churn). */
129
+ export declare function recordFineTuneJob(home: string, job: FineTuneJob, extra?: Record<string, unknown>): Promise<void>;
130
+ export declare function readLocalFineTuneJobs(home: string): Promise<Array<FineTuneJob & {
131
+ time: string;
132
+ }>>;
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Cloud fine-tuning client (2026-09-25, closes the auto-finetune loop).
3
+ *
4
+ * Direction (user, 2026-09-24): users configure ONE api key, the backend
5
+ * adapts everything else; local-GPU training was a developer experiment.
6
+ * This module submits the accumulated DPO preference pairs to the provider's
7
+ * fine-tuning API so "gets smarter as you use it" needs no local stack.
8
+ *
9
+ * Endpoint surface verified live 2026-09-25 against open.bigmodel.cn with a
10
+ * real key (read-only probes + one 85-byte purpose=fine-tune upload):
11
+ * POST /api/paas/v4/files multipart file + purpose=fine-tune
12
+ * POST /api/paas/v4/fine_tuning/jobs {model, training_file, ...}
13
+ * GET /api/paas/v4/fine_tuning/jobs list
14
+ * GET /api/paas/v4/fine_tuning/jobs/{id} retrieve
15
+ * POST /api/paas/v4/fine_tuning/jobs/{id}/cancel
16
+ * GET /api/paas/v4/fine_tuning/jobs/{id}/events
17
+ * Cross-checked field names against zhipuai SDK 2.1.5 source
18
+ * (api_resource/fine_tuning/jobs/jobs.py). The DPO row format follows the
19
+ * official guide: {"input":{messages,tools,parallel_tool_calls},
20
+ * "preferred_output":[...],"non_preferred_output":[...]}.
21
+ */
22
+ import { appendFile, mkdir, readFile } from 'node:fs/promises';
23
+ import { join } from 'node:path';
24
+ /** Models verified as fine-tunable (guide + live probe 2026-09-25: bare
25
+ * glm-4-air 404s "微调模型不存在", glm-4-flash passes model validation). */
26
+ export const FINE_TUNE_CATALOG = [
27
+ { id: 'glm-4-flash', dpo: true, note: '最便宜,LoRA 需开发者 Pro 权益' },
28
+ { id: 'glm-4.5-air', dpo: false, note: '全参微调,对所有用户开放(SFT)' },
29
+ { id: 'glm-4-air-250414', dpo: true, note: '全参微调' },
30
+ { id: 'glm-4-air-x', dpo: true, note: '全参微调' },
31
+ ];
32
+ export const DEFAULT_FINE_TUNE_MODEL = 'glm-4-flash';
33
+ /**
34
+ * Model auto-selection (user direction 2026-09-25: novices must never pick
35
+ * a fine-tune base). Candidates: the user's MAIN model first - if the API
36
+ * rejects it (live probe 2026-09-25: glm-5.3 answers "微调功能未开放") the
37
+ * ladder silently falls to the next documented fine-tunable base. The probe
38
+ * POSTs {model, training_file:"file-probe-invalid"} - model validation runs
39
+ * BEFORE file binding, so the request always fails without creating
40
+ * anything, and the error text tells us whether the model is usable.
41
+ */
42
+ export function fineTuneModelLadder(mainModel) {
43
+ const ladder = [mainModel, DEFAULT_FINE_TUNE_MODEL, 'glm-4.5-air'];
44
+ return [...new Set(ladder.filter(Boolean))];
45
+ }
46
+ /** Zero-side-effect model probe (the request can never create a job - the
47
+ * training_file id is invalid on purpose). "model rejected" vs "reached
48
+ * file validation" is distinguishable in the error text. */
49
+ export async function probeFineTuneModel(opts) {
50
+ const url = normalizeFineTuneBase(opts.baseUrl) + '/fine_tuning/jobs';
51
+ const res = await (opts.fetchImpl ?? fetch)(url, {
52
+ method: 'POST',
53
+ headers: { Authorization: `Bearer ${opts.apiKey}`, 'Content-Type': 'application/json' },
54
+ body: JSON.stringify({ model: opts.model, training_file: 'file-probe-invalid' }),
55
+ });
56
+ const text = await res.text();
57
+ if (res.ok)
58
+ return { usable: true }; // unreachable in practice; harmless
59
+ const rejected = /微调模型不存在|微调功能未开放|无权限|not found/i.test(text);
60
+ return { usable: !rejected, reason: rejected ? text.slice(0, 160) : undefined };
61
+ }
62
+ /** Walk the ladder, return the first usable model plus why earlier ones
63
+ * were skipped (surfaced as one Chinese line - the backend adapts, the
64
+ * user reads, never chooses). */
65
+ export async function pickFineTuneModel(opts) {
66
+ for (const m of fineTuneModelLadder(opts.mainModel)) {
67
+ const r = await probeFineTuneModel({ apiKey: opts.apiKey, baseUrl: opts.baseUrl, model: m, fetchImpl: opts.fetchImpl });
68
+ if (r.usable)
69
+ return m;
70
+ opts.log?.(`微调候选 ${m} 不可用(${(r.reason ?? '').replace(/^.*"message":"([^"]*)".*$/, '$1').slice(0, 60) || 'API 拒绝'}),自动改试下一个`);
71
+ }
72
+ throw new Error('所有微调候选模型均不可用——请在智谱控制台确认微调权限(可能需联系客服开放),或用 --model= 指定其他可微调模型');
73
+ }
74
+ /**
75
+ * Fine-tuning does not live on the coding endpoint: config.json points the
76
+ * chat route at /api/coding/paas/v4, but the fine_tuning/file APIs sit on
77
+ * /api/paas/v4. Strip the coding segment so the user's existing glm provider
78
+ * entry works unchanged (zero new configuration).
79
+ */
80
+ export function normalizeFineTuneBase(baseUrl) {
81
+ let u = baseUrl.trim().replace(/\/+$/, '');
82
+ u = u.replace(/\/coding\/paas\/v4$/, '/paas/v4');
83
+ if (!/\/api\/paas\/v4$/.test(u)) {
84
+ const m = u.match(/^(https?:\/\/[^/]+)/);
85
+ if (!m)
86
+ throw new Error('baseUrl 需以 http(s):// 开头: ' + baseUrl);
87
+ u = m[1] + '/api/paas/v4';
88
+ }
89
+ return u;
90
+ }
91
+ /** Serialize pairs into the provider DPO JSONL row format (pure). Accepts
92
+ * the slim {prompt,chosen,rejected} rows the CLI persists - provenance
93
+ * fields never leave the machine.
94
+ * Format verified live 2026-09-25: the documented {"input":{"messages":...}}
95
+ * nesting is REJECTED by the upload validator ("缺少messages字段"); the
96
+ * accepted shape is top-level messages (MUST contain an assistant turn -
97
+ * "缺少assistant角色" otherwise) plus preferred_output/non_preferred_output.
98
+ * The assistant turn carries the chosen answer, so the row is a complete
99
+ * good trajectory and the preference pair trains the separation. */
100
+ export function toDpoJsonl(pairs) {
101
+ const lines = [];
102
+ for (const p of pairs) {
103
+ if (!p.prompt.trim() || !p.chosen.trim() || !p.rejected.trim())
104
+ continue; // quality gate mirrors rl-governance
105
+ const row = {
106
+ messages: [
107
+ { role: 'user', content: p.prompt },
108
+ { role: 'assistant', content: p.chosen },
109
+ ],
110
+ preferred_output: [{ role: 'assistant', content: p.chosen }],
111
+ non_preferred_output: [{ role: 'assistant', content: p.rejected }],
112
+ };
113
+ lines.push(JSON.stringify(row));
114
+ }
115
+ return lines.join('\n') + (lines.length ? '\n' : '');
116
+ }
117
+ /** Rough token estimate for a cost preview before upload (chars/4 heuristic;
118
+ * the upload response returns exact per-tokenizer stats which the UI shows
119
+ * alongside - this is only the pre-flight number). */
120
+ export function estimateTokens(jsonl) {
121
+ return Math.ceil(jsonl.length / 4);
122
+ }
123
+ /** Training cost = tokens × epochs × unit price. Pure math, price supplied
124
+ * by the caller (it changes; we never bake it in as truth). */
125
+ export function estimateTrainingCost(tokens, epochs, pricePerKTokens) {
126
+ return Math.round(((tokens / 1000) * epochs * pricePerKTokens) * 100) / 100;
127
+ }
128
+ async function zhipuFetch(url, apiKey, init, fetchImpl) {
129
+ const res = await fetchImpl(url, {
130
+ ...init,
131
+ headers: { Authorization: `Bearer ${apiKey}`, ...init.headers },
132
+ });
133
+ const text = await res.text();
134
+ let body;
135
+ try {
136
+ body = JSON.parse(text);
137
+ }
138
+ catch {
139
+ body = text;
140
+ }
141
+ if (!res.ok) {
142
+ const err = body;
143
+ throw new Error(`HTTP ${res.status}: ${err?.error?.message ?? String(body).slice(0, 200)}`);
144
+ }
145
+ return body;
146
+ }
147
+ /** Upload a training/validation JSONL (free operation, verified live). */
148
+ export async function uploadFineTuneFile(opts) {
149
+ const url = normalizeFineTuneBase(opts.baseUrl) + '/files';
150
+ const form = new FormData();
151
+ form.append('purpose', 'fine-tune');
152
+ form.append('file', new Blob([opts.jsonl], { type: 'application/jsonl' }), opts.filename);
153
+ const body = await zhipuFetch(url, opts.apiKey, { method: 'POST', body: form }, opts.fetchImpl ?? fetch);
154
+ const o = body;
155
+ const tokens = Math.max(0, ...(o.text_stats ?? []).map((t) => t.tokens ?? 0));
156
+ return { id: o.id, bytes: o.bytes, samples: o.samples ?? 0, tokens };
157
+ }
158
+ /** Create a fine-tuning job (PAID - callers must gate behind explicit
159
+ * submit consent; uploads alone are free). */
160
+ export async function createFineTuneJob(opts) {
161
+ const url = normalizeFineTuneBase(opts.baseUrl) + '/fine_tuning/jobs';
162
+ const payload = { model: opts.model, training_file: opts.trainingFile };
163
+ if (opts.validationFile)
164
+ payload.validation_file = opts.validationFile;
165
+ if (opts.suffix)
166
+ payload.suffix = opts.suffix;
167
+ if (opts.hyperparameters)
168
+ payload.hyperparameters = opts.hyperparameters;
169
+ return (await zhipuFetch(url, opts.apiKey, {
170
+ method: 'POST',
171
+ headers: { 'Content-Type': 'application/json' },
172
+ body: JSON.stringify(payload),
173
+ }, opts.fetchImpl ?? fetch));
174
+ }
175
+ export async function listFineTuneJobs(opts) {
176
+ const url = normalizeFineTuneBase(opts.baseUrl) + `/fine_tuning/jobs?limit=${opts.limit ?? 10}`;
177
+ const body = await zhipuFetch(url, opts.apiKey, { method: 'GET' }, opts.fetchImpl ?? fetch);
178
+ return (body.data ?? []);
179
+ }
180
+ export async function retrieveFineTuneJob(opts) {
181
+ const url = normalizeFineTuneBase(opts.baseUrl) + `/fine_tuning/jobs/${opts.jobId}`;
182
+ return (await zhipuFetch(url, opts.apiKey, { method: 'GET' }, opts.fetchImpl ?? fetch));
183
+ }
184
+ export async function cancelFineTuneJob(opts) {
185
+ const url = normalizeFineTuneBase(opts.baseUrl) + `/fine_tuning/jobs/${opts.jobId}/cancel`;
186
+ return (await zhipuFetch(url, opts.apiKey, { method: 'POST' }, opts.fetchImpl ?? fetch));
187
+ }
188
+ /* ---------------- local job ledger ---------------- */
189
+ /** Append-only record of jobs this machine submitted (audit trail: what was
190
+ * trained, on which file, when - survives provider console churn). */
191
+ export async function recordFineTuneJob(home, job, extra = {}) {
192
+ const dir = join(home, 'evolution');
193
+ await mkdir(dir, { recursive: true });
194
+ const row = { time: new Date().toISOString(), ...job, ...extra };
195
+ await appendFile(join(dir, 'finetune-jobs.jsonl'), JSON.stringify(row) + '\n', 'utf8');
196
+ }
197
+ export async function readLocalFineTuneJobs(home) {
198
+ try {
199
+ const text = await readFile(join(home, 'evolution', 'finetune-jobs.jsonl'), 'utf8');
200
+ return text.split('\n').filter(Boolean).map((l) => JSON.parse(l));
201
+ }
202
+ catch {
203
+ return [];
204
+ }
205
+ }
package/dist/index.d.ts CHANGED
@@ -23,3 +23,4 @@ export * from './router-evolution.ts';
23
23
  export * from './context-evolution.ts';
24
24
  export * from './rl-governance.ts';
25
25
  export * from './policy-optimizer.ts';
26
+ export * from './cloud-finetune.ts';
package/dist/index.js CHANGED
@@ -23,3 +23,4 @@ export * from "./router-evolution.js";
23
23
  export * from "./context-evolution.js";
24
24
  export * from "./rl-governance.js";
25
25
  export * from "./policy-optimizer.js";
26
+ export * from "./cloud-finetune.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/evolution",
3
- "version": "0.14.22",
3
+ "version": "0.14.24",
4
4
  "description": "hmharness evolution subsystem: persistent memory, insight capture, skill library, and the bench that gives evolution its fitness signal. First-class kernel citizen, not a plugin.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",