@v587d/capital-generation 2.24.0 → 2.25.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.
Files changed (58) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +9 -4
  3. package/THIRD_PARTY_NOTICES.md +20 -0
  4. package/automation/package.json +1 -1
  5. package/chart-ui/package.json +1 -1
  6. package/config/client.js +21 -5
  7. package/config/client.src.cjs +264 -0
  8. package/config/package.json +1 -1
  9. package/cordis.patch.yml +9 -2
  10. package/lib/agents/role-tool-policy.d.ts +1 -1
  11. package/lib/agents/root-tool-policy.d.ts +3 -3
  12. package/lib/agents/root-tool-policy.js +2 -2
  13. package/lib/data-collector/catalog-taxonomy.js +4 -0
  14. package/lib/python-runtime/child-env.d.ts +11 -0
  15. package/lib/python-runtime/child-env.js +39 -0
  16. package/lib/python-runtime/errors.d.ts +8 -0
  17. package/lib/python-runtime/errors.js +34 -0
  18. package/lib/python-runtime/lock.d.ts +11 -0
  19. package/lib/python-runtime/lock.js +68 -0
  20. package/lib/python-runtime/manager.d.ts +61 -0
  21. package/lib/python-runtime/manager.js +517 -0
  22. package/lib/python-runtime/manifest.d.ts +5 -0
  23. package/lib/python-runtime/manifest.js +160 -0
  24. package/lib/python-runtime/paths.d.ts +20 -0
  25. package/lib/python-runtime/paths.js +156 -0
  26. package/lib/python-runtime/platform.d.ts +32 -0
  27. package/lib/python-runtime/platform.js +145 -0
  28. package/lib/python-runtime/pnpm.d.ts +24 -0
  29. package/lib/python-runtime/pnpm.js +115 -0
  30. package/lib/python-runtime/probe.d.ts +13 -0
  31. package/lib/python-runtime/probe.js +101 -0
  32. package/lib/python-runtime/routes.d.ts +6 -0
  33. package/lib/python-runtime/routes.js +152 -0
  34. package/lib/python-runtime/types.d.ts +105 -0
  35. package/lib/python-runtime/types.js +3 -0
  36. package/lib/python-runtime-entry.d.ts +10 -0
  37. package/lib/python-runtime-entry.js +60 -0
  38. package/lib/sources/eastmoney-http.js +346 -1
  39. package/lib/sources/tencent-http.js +248 -2
  40. package/lib/sources/tencent-public-core.js +1 -1
  41. package/lib/sources-entry.d.ts +1 -1
  42. package/lib/time/tools.js +2 -0
  43. package/lib/web-retriever/local-fetch.d.ts +1 -1
  44. package/lib/web-retriever/local-fetch.js +1 -1
  45. package/lib/web-retriever/sources.d.ts +16 -1
  46. package/lib/web-retriever/sources.js +133 -1
  47. package/lib/web-retriever/tools.js +41 -1
  48. package/lib/web-retriever/wind-client.d.ts +1 -1
  49. package/lib/web-retriever/wind-client.js +1 -1
  50. package/package.json +13 -1
  51. package/plugin-page/README.en.md +1 -7
  52. package/plugin-page/README.zh.md +1 -8
  53. package/preset/capital-generation/agent.patch.yml +12 -13
  54. package/preset/capital-generation/skills/capital-web-protocol/SKILL.md +10 -4
  55. package/python/worker.py +154 -0
  56. package/runtime/manifest.json +75 -0
  57. package/scripts/python-runtime.mjs +139 -0
  58. package/watchlist/package.json +1 -1
@@ -0,0 +1,61 @@
1
+ import { type PlatformFacts } from './platform.js';
2
+ import { runPnpm, type PnpmInvocation } from './pnpm.js';
3
+ import { probePython } from './probe.js';
4
+ import type { PackName, PrepareJob, ProbeReport, RuntimeHandle, RuntimeManifest, RuntimeStatus } from './types.js';
5
+ interface LoggerLike {
6
+ info?(message: string): void;
7
+ warn?(message: string): void;
8
+ error?(message: string): void;
9
+ }
10
+ export interface PythonRuntimeManagerOptions {
11
+ manifest: RuntimeManifest;
12
+ dshHome?: string;
13
+ workerPath: string;
14
+ target: PlatformFacts;
15
+ profileDir?: string;
16
+ packageManager?: PnpmInvocation;
17
+ packSources?: Partial<Record<PackName, string>>;
18
+ registry?: string;
19
+ logger?: LoggerLike;
20
+ now?: () => Date;
21
+ runPnpm?: typeof runPnpm;
22
+ probePython?: typeof probePython;
23
+ }
24
+ export declare class PythonRuntimeManager {
25
+ readonly manifest: RuntimeManifest;
26
+ readonly dshHome: string;
27
+ readonly cacheRoot: string;
28
+ readonly workerPath: string;
29
+ readonly target: PlatformFacts;
30
+ private readonly profileDir?;
31
+ private readonly packageManager?;
32
+ private readonly packSources;
33
+ private readonly registry?;
34
+ private readonly logger?;
35
+ private readonly now;
36
+ private readonly runPnpm;
37
+ private readonly probePython;
38
+ private readonly jobs;
39
+ private activeJobId?;
40
+ private pnpmInvocation?;
41
+ constructor(options: PythonRuntimeManagerOptions);
42
+ private targetId;
43
+ private readReady;
44
+ private packStatus;
45
+ status(): Promise<RuntimeStatus>;
46
+ prepare(packs?: unknown): PrepareJob;
47
+ getJob(id: string): PrepareJob | undefined;
48
+ waitForJob(id: string): Promise<PrepareJob>;
49
+ cancel(id: string): boolean;
50
+ private runJob;
51
+ private getPnpm;
52
+ private ensurePack;
53
+ private readPackMetadata;
54
+ private validateProbe;
55
+ /** Re-run the self-check against the installed packs; `parquet` also verifies pyarrow. */
56
+ verify(packs?: unknown): Promise<ProbeReport>;
57
+ resolve(packs?: unknown): Promise<RuntimeHandle>;
58
+ remove(pack: PackName): Promise<void>;
59
+ dispose(): Promise<void>;
60
+ }
61
+ export {};
@@ -0,0 +1,517 @@
1
+ import { chmod, mkdir, rename, rm, stat } from 'node:fs/promises';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { join, resolve } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { PythonRuntimeError, isPythonRuntimeError, messageOf } from './errors.js';
6
+ import { withInstallLock } from './lock.js';
7
+ import { normalizePackNames, packTarget } from './manifest.js';
8
+ import { availableBytes, directoryBytes, exists, isInside, lockRoot, packRoot, readJson, readyFileShape, readyPath, removeStaleStaging, resolveDshHome, runtimeRoot, safeRelative, stagingRoot, storeRoot, writeJsonAtomic, } from './paths.js';
9
+ import { findPnpmCli } from './platform.js';
10
+ import { classifyPnpmFailure, installArgs, runPnpm, writeInstallProject } from './pnpm.js';
11
+ import { probePython } from './probe.js';
12
+ const PACK_ORDER = ['base', 'parquet'];
13
+ function nowIso(now) {
14
+ return now().toISOString();
15
+ }
16
+ function copyJob(job) {
17
+ return {
18
+ ...job,
19
+ packs: [...job.packs],
20
+ ...(job.error === undefined ? {} : { error: { ...job.error } }),
21
+ };
22
+ }
23
+ function targetParts(target) {
24
+ const index = target.lastIndexOf('-');
25
+ return { platform: target.slice(0, index), arch: target.slice(index + 1) };
26
+ }
27
+ function normalizeMachine(value) {
28
+ const machine = value.toLowerCase();
29
+ if (machine === 'amd64' || machine === 'x86_64' || machine === 'x64')
30
+ return 'x64';
31
+ if (machine === 'aarch64' || machine === 'arm64')
32
+ return 'arm64';
33
+ return machine;
34
+ }
35
+ function packagesMatch(actual, expected) {
36
+ return Object.entries(expected).every(([name, version]) => actual[name] === version);
37
+ }
38
+ export class PythonRuntimeManager {
39
+ manifest;
40
+ dshHome;
41
+ cacheRoot;
42
+ workerPath;
43
+ target;
44
+ profileDir;
45
+ packageManager;
46
+ packSources;
47
+ registry;
48
+ logger;
49
+ now;
50
+ runPnpm;
51
+ probePython;
52
+ jobs = new Map();
53
+ activeJobId;
54
+ pnpmInvocation;
55
+ constructor(options) {
56
+ this.manifest = options.manifest;
57
+ this.dshHome = resolveDshHome(options.dshHome);
58
+ this.cacheRoot = runtimeRoot(this.dshHome, options.manifest.cacheRoot);
59
+ this.workerPath = options.workerPath;
60
+ this.target = options.target;
61
+ this.profileDir = options.profileDir;
62
+ this.packageManager = options.packageManager;
63
+ this.packSources = options.packSources ?? {};
64
+ this.registry = options.registry;
65
+ this.logger = options.logger;
66
+ this.now = options.now ?? (() => new Date());
67
+ this.runPnpm = options.runPnpm ?? runPnpm;
68
+ this.probePython = options.probePython ?? probePython;
69
+ }
70
+ targetId() {
71
+ if (this.target.target === null || !this.target.supported) {
72
+ throw new PythonRuntimeError('unsupported-platform', this.target.reason);
73
+ }
74
+ return this.target.target;
75
+ }
76
+ async readReady(pack, version, target) {
77
+ const root = packRoot(this.cacheRoot, pack, version, target);
78
+ const value = await readJson(readyPath(root));
79
+ return readyFileShape(value) ? value : undefined;
80
+ }
81
+ async packStatus(pack) {
82
+ const target = this.target.target;
83
+ const spec = target === null ? undefined : this.manifest.packs[pack].targets[target];
84
+ const version = spec?.version ?? '';
85
+ const packageName = spec?.package ?? '';
86
+ const base = {
87
+ name: pack,
88
+ state: 'not-installed',
89
+ kind: this.manifest.packs[pack].kind,
90
+ version,
91
+ package: packageName,
92
+ target,
93
+ pythonVersion: this.manifest.python,
94
+ packages: { ...this.manifest.packs[pack].packages },
95
+ bytes: 0,
96
+ path: target === null ? '' : packRoot(this.cacheRoot, pack, version, target),
97
+ };
98
+ if (target === null || spec === undefined)
99
+ return base;
100
+ const root = packRoot(this.cacheRoot, pack, version, target);
101
+ if (!await exists(root))
102
+ return base;
103
+ const ready = await this.readReady(pack, version, target);
104
+ if (ready === undefined) {
105
+ return { ...base, state: 'broken', error: 'ready.json 缺失或不可读。' };
106
+ }
107
+ if (ready.pack !== pack
108
+ || ready.packVersion !== version
109
+ || ready.target !== target
110
+ || ready.package !== packageName
111
+ || ready.pythonVersion !== this.manifest.python
112
+ || !packagesMatch(ready.packages, this.manifest.packs[pack].packages)) {
113
+ return { ...base, state: 'broken', error: 'ready.json 与当前 manifest 不一致。' };
114
+ }
115
+ try {
116
+ if (pack === 'base' && ready.python === null) {
117
+ return { ...base, state: 'broken', error: 'base ready.json 缺少 Python 可执行文件。' };
118
+ }
119
+ if (ready.python !== null)
120
+ await stat(safeRelative(root, ready.python));
121
+ for (const item of ready.sitePackages)
122
+ await stat(safeRelative(root, item));
123
+ }
124
+ catch (error) {
125
+ return { ...base, state: 'broken', error: `运行时文件缺失:${messageOf(error)}` };
126
+ }
127
+ return {
128
+ ...base,
129
+ state: 'ready',
130
+ installedAt: ready.installedAt,
131
+ bytes: ready.bytes ?? await directoryBytes(root),
132
+ };
133
+ }
134
+ async status() {
135
+ const base = await this.packStatus('base');
136
+ const parquet = await this.packStatus('parquet');
137
+ const active = this.activeJobId === undefined ? undefined : this.jobs.get(this.activeJobId)?.job;
138
+ return {
139
+ supported: this.target.supported,
140
+ ...(this.target.reason === undefined ? {} : { reason: this.target.reason }),
141
+ target: this.target.target,
142
+ platform: this.target.platform,
143
+ arch: this.target.arch,
144
+ python: this.manifest.python,
145
+ cacheRoot: this.cacheRoot,
146
+ base,
147
+ parquet,
148
+ ready: base.state === 'ready',
149
+ ...(active === undefined ? {} : { activeJob: copyJob(active) }),
150
+ };
151
+ }
152
+ prepare(packs = ['base']) {
153
+ const names = normalizePackNames(packs);
154
+ const target = this.targetId();
155
+ for (const name of names)
156
+ packTarget(this.manifest, name, target);
157
+ if (this.activeJobId !== undefined) {
158
+ const active = this.jobs.get(this.activeJobId);
159
+ if (active !== undefined && active.job.state === 'running') {
160
+ if (active.job.packs.length === names.length && active.job.packs.every((name, index) => name === names[index])) {
161
+ return copyJob(active.job);
162
+ }
163
+ throw new PythonRuntimeError('busy', '已有另一个运行时准备任务在进行。');
164
+ }
165
+ }
166
+ const id = randomUUID();
167
+ const job = {
168
+ id,
169
+ packs: names,
170
+ state: 'running',
171
+ stage: 'checking',
172
+ message: '检查平台与缓存…',
173
+ startedAt: nowIso(this.now),
174
+ };
175
+ const controller = new AbortController();
176
+ const active = { job, controller, promise: Promise.resolve() };
177
+ this.jobs.set(id, active);
178
+ this.activeJobId = id;
179
+ active.promise = this.runJob(active).catch((error) => {
180
+ this.logger?.error?.(`python-runtime prepare failed: ${messageOf(error)}`);
181
+ }).finally(() => {
182
+ if (this.activeJobId === id)
183
+ this.activeJobId = undefined;
184
+ });
185
+ return copyJob(job);
186
+ }
187
+ getJob(id) {
188
+ const active = this.jobs.get(id);
189
+ return active === undefined ? undefined : copyJob(active.job);
190
+ }
191
+ async waitForJob(id) {
192
+ const active = this.jobs.get(id);
193
+ if (active === undefined)
194
+ throw new PythonRuntimeError('invalid-request', `没有这个运行时任务:${id}`);
195
+ await active.promise;
196
+ return copyJob(active.job);
197
+ }
198
+ cancel(id) {
199
+ const active = this.jobs.get(id);
200
+ if (active === undefined || active.job.state !== 'running')
201
+ return false;
202
+ active.controller.abort();
203
+ active.job.message = '正在取消…';
204
+ return true;
205
+ }
206
+ async runJob(active) {
207
+ const { job, controller } = active;
208
+ try {
209
+ await mkdir(this.cacheRoot, { recursive: true, mode: 0o700 });
210
+ await removeStaleStaging(stagingRoot(this.cacheRoot));
211
+ for (const pack of job.packs) {
212
+ if (controller.signal.aborted)
213
+ throw new PythonRuntimeError('cancelled');
214
+ job.current = pack;
215
+ job.stage = 'checking';
216
+ job.message = `检查 ${pack}…`;
217
+ const status = await this.packStatus(pack);
218
+ if (status.state === 'ready')
219
+ continue;
220
+ job.stage = 'installing';
221
+ job.message = `安装 ${pack}…`;
222
+ await this.ensurePack(active, pack);
223
+ }
224
+ job.stage = 'done';
225
+ job.state = 'done';
226
+ job.message = '分析环境已就绪。';
227
+ job.endedAt = nowIso(this.now);
228
+ delete job.current;
229
+ }
230
+ catch (error) {
231
+ const runtimeError = isPythonRuntimeError(error)
232
+ ? error
233
+ : new PythonRuntimeError('unknown', messageOf(error));
234
+ job.state = runtimeError.code === 'cancelled' ? 'cancelled' : 'failed';
235
+ job.stage = 'done';
236
+ job.message = runtimeError.message;
237
+ job.error = { code: runtimeError.code, message: runtimeError.message };
238
+ job.endedAt = nowIso(this.now);
239
+ this.logger?.error?.(`python-runtime: ${runtimeError.code}: ${runtimeError.message}`);
240
+ if (runtimeError.diagnostics !== undefined)
241
+ this.logger?.warn?.(runtimeError.diagnostics);
242
+ }
243
+ }
244
+ getPnpm() {
245
+ if (this.pnpmInvocation !== undefined)
246
+ return this.pnpmInvocation;
247
+ this.pnpmInvocation = this.packageManager ?? findPnpmCli();
248
+ return this.pnpmInvocation;
249
+ }
250
+ async ensurePack(active, pack) {
251
+ const target = this.targetId();
252
+ const spec = packTarget(this.manifest, pack, target);
253
+ const root = packRoot(this.cacheRoot, pack, spec.version, target);
254
+ const lock = join(lockRoot(this.cacheRoot), `${pack}-${spec.version}-${target}`);
255
+ const { job, controller } = active;
256
+ await mkdir(lockRoot(this.cacheRoot), { recursive: true, mode: 0o700 });
257
+ await withInstallLock(lock, async () => {
258
+ const current = await this.packStatus(pack);
259
+ if (current.state === 'ready')
260
+ return;
261
+ job.stage = 'checking';
262
+ job.message = `检查磁盘空间…`;
263
+ const free = await availableBytes(this.cacheRoot);
264
+ if (free !== undefined && free < this.manifest.limits.minFreeBytes) {
265
+ throw new PythonRuntimeError('disk-space', `磁盘空间不足:需要约 ${Math.ceil(this.manifest.limits.minFreeBytes / 1048576)} MB,当前约 ${Math.floor(free / 1048576)} MB。`);
266
+ }
267
+ const staging = join(stagingRoot(this.cacheRoot), `${pack}-${spec.version}-${target}-${randomUUID()}`);
268
+ const installDir = join(staging, 'install');
269
+ const payload = join(staging, 'payload');
270
+ const probeHome = join(staging, 'probe-home');
271
+ const probeTemp = join(staging, 'probe-tmp');
272
+ try {
273
+ await mkdir(staging, { recursive: true, mode: 0o700 });
274
+ const source = this.packSources[pack];
275
+ // A package.json dependency value is a range or a file URL, never `name@version`:
276
+ // pnpm treats the latter as a relative directory and installs nothing.
277
+ const dependency = source === undefined ? spec.version : pathToFileURL(resolve(source)).href;
278
+ await writeInstallProject(installDir, spec.package, dependency, this.registry);
279
+ job.stage = 'installing';
280
+ job.message = source === undefined ? `下载并安装 ${pack}(约 ${Math.ceil(spec.bytes / 1048576)} MB)…` : `安装本地 ${pack} 包…`;
281
+ const result = await this.runPnpm(this.getPnpm(), installArgs(installDir, storeRoot(this.cacheRoot), this.registry), {
282
+ cwd: this.profileDir ?? staging,
283
+ timeoutMs: this.manifest.limits.installTimeoutMs,
284
+ signal: controller.signal,
285
+ });
286
+ if (result.code !== 0 || result.timedOut || result.aborted)
287
+ throw classifyPnpmFailure(result);
288
+ const installed = join(installDir, 'node_modules', ...spec.package.split('/'));
289
+ if (!await exists(installed)) {
290
+ throw new PythonRuntimeError('pack-invalid', `pnpm 安装完成但找不到 ${spec.package}。`);
291
+ }
292
+ await rename(installed, payload);
293
+ await rm(installDir, { recursive: true, force: true });
294
+ const metadata = await this.readPackMetadata(payload, pack, target);
295
+ const executable = metadata.executable === null ? undefined : safeRelative(payload, metadata.executable);
296
+ if (metadata.kind === 'base') {
297
+ if (executable === undefined)
298
+ throw new PythonRuntimeError('pack-invalid', 'base pack 缺少 executable。');
299
+ if (this.target.platform !== 'win32')
300
+ await chmod(executable, 0o755);
301
+ }
302
+ const sitePackages = metadata.sitePackages.map((item) => safeRelative(payload, item));
303
+ const baseReady = pack === 'base' ? undefined : await this.readReady('base', this.manifest.packs.base.targets[target]?.version ?? '', target);
304
+ const baseRoot = pack === 'base' ? undefined : packRoot(this.cacheRoot, 'base', this.manifest.packs.base.targets[target]?.version ?? '', target);
305
+ const python = pack === 'base'
306
+ ? executable
307
+ : (baseReady?.python === null || baseReady?.python === undefined || baseRoot === undefined ? undefined : safeRelative(baseRoot, baseReady.python));
308
+ if (python === undefined)
309
+ throw new PythonRuntimeError('pack-invalid', `${pack} pack 找不到可用的 Python 解释器;请先安装 base。`);
310
+ const probeSites = pack === 'base'
311
+ ? sitePackages
312
+ : [
313
+ ...(baseReady?.sitePackages ?? []).map((item) => safeRelative(baseRoot, item)),
314
+ ...sitePackages,
315
+ ];
316
+ job.stage = 'verifying';
317
+ job.message = `自检 ${pack}…`;
318
+ const report = await this.probePython({
319
+ python,
320
+ workerPath: this.workerPath,
321
+ sitePackages: probeSites,
322
+ homeDir: probeHome,
323
+ tempDir: probeTemp,
324
+ timeoutMs: this.manifest.limits.probeTimeoutMs,
325
+ signal: controller.signal,
326
+ });
327
+ this.validateProbe(report, pack, target, python, probeSites, payload, baseRoot);
328
+ const ready = {
329
+ schemaVersion: 1,
330
+ pack,
331
+ packVersion: spec.version,
332
+ target,
333
+ package: spec.package,
334
+ pythonVersion: this.manifest.python,
335
+ packages: { ...this.manifest.packs[pack].packages },
336
+ python: metadata.executable === null ? null : `payload/${metadata.executable}`,
337
+ sitePackages: metadata.sitePackages.map((item) => `payload/${item}`),
338
+ installedAt: nowIso(this.now),
339
+ probe: { ok: true, at: nowIso(this.now) },
340
+ bytes: await directoryBytes(payload),
341
+ };
342
+ await writeJsonAtomic(readyPath(staging), ready);
343
+ await mkdir(join(root, '..'), { recursive: true });
344
+ if (await exists(root)) {
345
+ const previous = `${root}.broken-${Date.now()}`;
346
+ await rename(root, previous);
347
+ await rm(previous, { recursive: true, force: true }).catch(() => undefined);
348
+ }
349
+ await rename(staging, root);
350
+ }
351
+ finally {
352
+ await rm(staging, { recursive: true, force: true }).catch(() => undefined);
353
+ }
354
+ }, { timeoutMs: 30_000, staleMs: 120_000 });
355
+ }
356
+ async readPackMetadata(payload, pack, target) {
357
+ const value = await readJson(join(payload, 'runtime-pack.json'));
358
+ if (value === undefined)
359
+ throw new PythonRuntimeError('pack-invalid', '运行时包缺少 runtime-pack.json。');
360
+ const parts = targetParts(target);
361
+ const expected = this.manifest.packs[pack];
362
+ if (value.schemaVersion !== 1
363
+ || value.kind !== expected.kind
364
+ || value.platform !== parts.platform
365
+ || value.arch !== parts.arch
366
+ || value.pythonVersion !== this.manifest.python
367
+ || value.packages === null
368
+ || typeof value.packages !== 'object'
369
+ || Array.isArray(value.packages)) {
370
+ throw new PythonRuntimeError('pack-invalid', 'runtime-pack.json 与 manifest/当前平台不一致。');
371
+ }
372
+ if (!packagesMatch(value.packages, expected.packages)) {
373
+ throw new PythonRuntimeError('pack-invalid', 'runtime-pack.json 的三方库版本与 manifest 不一致。');
374
+ }
375
+ if (value.executable !== null && typeof value.executable !== 'string') {
376
+ throw new PythonRuntimeError('pack-invalid', 'runtime-pack.json.executable 必须是字符串或 null。');
377
+ }
378
+ if (!Array.isArray(value.sitePackages) || value.sitePackages.length === 0 || value.sitePackages.some((item) => typeof item !== 'string')) {
379
+ throw new PythonRuntimeError('pack-invalid', 'runtime-pack.json.sitePackages 必须是非空字符串数组。');
380
+ }
381
+ const metadata = value;
382
+ for (const item of metadata.sitePackages) {
383
+ const path = safeRelative(payload, item);
384
+ if (!await exists(path))
385
+ throw new PythonRuntimeError('pack-invalid', `site-packages 不存在:${item}`);
386
+ }
387
+ if (metadata.executable !== null) {
388
+ const path = safeRelative(payload, metadata.executable);
389
+ if (!await exists(path))
390
+ throw new PythonRuntimeError('pack-invalid', `Python 可执行文件不存在:${metadata.executable}`);
391
+ }
392
+ return metadata;
393
+ }
394
+ validateProbe(report, pack, target, python, sitePackages, payload, baseRoot) {
395
+ const parts = targetParts(target);
396
+ if (report.pythonVersion !== this.manifest.python) {
397
+ throw new PythonRuntimeError('probe-failed', `Python 版本不匹配:期望 ${this.manifest.python},实际 ${report.pythonVersion}。`);
398
+ }
399
+ if (report.platform !== parts.platform) {
400
+ throw new PythonRuntimeError('probe-failed', `Python 平台不匹配:期望 ${parts.platform},实际 ${report.platform}。`);
401
+ }
402
+ if (normalizeMachine(report.arch) !== parts.arch) {
403
+ throw new PythonRuntimeError('probe-failed', `Python 架构不匹配:期望 ${parts.arch},实际 ${report.arch}。`);
404
+ }
405
+ if (!packagesMatch(report.packages, this.manifest.packs[pack].packages)) {
406
+ throw new PythonRuntimeError('probe-failed', `Python 三方库版本不匹配:${JSON.stringify(report.packages)}。`);
407
+ }
408
+ const reportPython = resolve(report.executable);
409
+ const expectedPython = resolve(python);
410
+ const root = pack === 'base' ? payload : baseRoot;
411
+ if (root === undefined || reportPython !== expectedPython || !isInside(root, reportPython)) {
412
+ throw new PythonRuntimeError('probe-failed', 'probe 使用了 payload 之外的解释器。');
413
+ }
414
+ for (const item of report.sitePackages) {
415
+ const allowed = sitePackages.some((candidate) => resolve(candidate) === resolve(item))
416
+ || (baseRoot !== undefined && isInside(baseRoot, item));
417
+ if (!allowed)
418
+ throw new PythonRuntimeError('probe-failed', `probe 使用了未授权的 site-packages:${item}`);
419
+ }
420
+ }
421
+ /** Re-run the self-check against the installed packs; `parquet` also verifies pyarrow. */
422
+ async verify(packs = ['base']) {
423
+ const names = normalizePackNames(packs);
424
+ const handle = await this.resolve(names);
425
+ const target = this.targetId();
426
+ const baseSpec = packTarget(this.manifest, 'base', target);
427
+ const baseRoot = packRoot(this.cacheRoot, 'base', baseSpec.version, target);
428
+ const probeHome = join(this.cacheRoot, 'verify-home');
429
+ const probeTemp = join(this.cacheRoot, 'verify-tmp');
430
+ const report = await this.probePython({
431
+ python: handle.python,
432
+ workerPath: this.workerPath,
433
+ sitePackages: handle.sitePackages,
434
+ homeDir: probeHome,
435
+ tempDir: probeTemp,
436
+ timeoutMs: this.manifest.limits.probeTimeoutMs,
437
+ });
438
+ const parts = targetParts(target);
439
+ if (report.pythonVersion !== this.manifest.python
440
+ || report.platform !== parts.platform
441
+ || normalizeMachine(report.arch) !== parts.arch) {
442
+ throw new PythonRuntimeError('probe-failed', `Python 运行时与当前平台不一致:${report.pythonVersion}/${report.platform}/${report.arch}。`);
443
+ }
444
+ if (!packagesMatch(report.packages, handle.packages)) {
445
+ throw new PythonRuntimeError('probe-failed', `Python 三方库版本不匹配:${JSON.stringify(report.packages)}。`);
446
+ }
447
+ const reportPython = resolve(report.executable);
448
+ if (reportPython !== resolve(handle.python) || !isInside(baseRoot, reportPython)) {
449
+ throw new PythonRuntimeError('probe-failed', 'probe 使用了 payload 之外的解释器。');
450
+ }
451
+ for (const item of report.sitePackages) {
452
+ const allowed = handle.sitePackages.some((candidate) => resolve(candidate) === resolve(item))
453
+ || isInside(baseRoot, item);
454
+ if (!allowed)
455
+ throw new PythonRuntimeError('probe-failed', `probe 使用了未授权的 site-packages:${item}`);
456
+ }
457
+ return report;
458
+ }
459
+ async resolve(packs = ['base']) {
460
+ const names = normalizePackNames(packs);
461
+ const target = this.targetId();
462
+ const baseSpec = packTarget(this.manifest, 'base', target);
463
+ const base = await this.packStatus('base');
464
+ if (base.state !== 'ready')
465
+ throw new PythonRuntimeError('runtime-not-ready');
466
+ const baseRoot = packRoot(this.cacheRoot, 'base', baseSpec.version, target);
467
+ const baseReady = await this.readReady('base', baseSpec.version, target);
468
+ if (baseReady === undefined || baseReady.python === null)
469
+ throw new PythonRuntimeError('runtime-not-ready');
470
+ const sitePackages = baseReady.sitePackages.map((item) => safeRelative(baseRoot, item));
471
+ const packages = { ...baseReady.packages };
472
+ const packVersions = { base: baseSpec.version };
473
+ for (const pack of names.filter((name) => name !== 'base')) {
474
+ const spec = packTarget(this.manifest, pack, target);
475
+ const status = await this.packStatus(pack);
476
+ if (status.state !== 'ready')
477
+ throw new PythonRuntimeError('runtime-not-ready', `${pack} 运行时尚未准备。`);
478
+ const requires = this.manifest.packs[pack].requires?.base;
479
+ if (requires !== undefined && requires !== baseReady.packVersion) {
480
+ throw new PythonRuntimeError('pack-invalid', `${pack} 需要 base ${requires},当前是 ${baseReady.packVersion}。`);
481
+ }
482
+ const root = packRoot(this.cacheRoot, pack, spec.version, target);
483
+ const ready = await this.readReady(pack, spec.version, target);
484
+ if (ready === undefined)
485
+ throw new PythonRuntimeError('runtime-not-ready', `${pack} 运行时尚未准备。`);
486
+ sitePackages.push(...ready.sitePackages.map((item) => safeRelative(root, item)));
487
+ Object.assign(packages, ready.packages);
488
+ packVersions[pack] = spec.version;
489
+ }
490
+ return {
491
+ python: safeRelative(baseRoot, baseReady.python),
492
+ pythonVersion: this.manifest.python,
493
+ sitePackages,
494
+ packages,
495
+ packs: packVersions,
496
+ };
497
+ }
498
+ async remove(pack) {
499
+ if (this.activeJobId !== undefined)
500
+ throw new PythonRuntimeError('busy', '运行时任务进行中,不能移除。');
501
+ if (!PACK_ORDER.includes(pack))
502
+ throw new PythonRuntimeError('invalid-request', `未知 pack:${String(pack)}`);
503
+ if (pack === 'base' && (await this.packStatus('parquet')).state === 'ready') {
504
+ throw new PythonRuntimeError('busy', '请先移除 parquet 运行时,再移除 base。');
505
+ }
506
+ await rm(join(this.cacheRoot, pack), { recursive: true, force: true });
507
+ }
508
+ async dispose() {
509
+ for (const active of this.jobs.values()) {
510
+ if (active.job.state === 'running')
511
+ active.controller.abort();
512
+ }
513
+ await Promise.allSettled([...this.jobs.values()].map((active) => active.promise));
514
+ this.jobs.clear();
515
+ this.activeJobId = undefined;
516
+ }
517
+ }
@@ -0,0 +1,5 @@
1
+ import { type PackName, type PackTarget, type RuntimeManifest, type TargetId } from './types.js';
2
+ export declare function parseManifest(value: unknown): RuntimeManifest;
3
+ export declare function readManifest(path: string): RuntimeManifest;
4
+ export declare function packTarget(manifest: RuntimeManifest, pack: PackName, target: TargetId): PackTarget;
5
+ export declare function normalizePackNames(value: unknown): PackName[];