@v587d/capital-generation 2.24.0 → 2.26.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/CHANGELOG.md +49 -0
- package/README.md +9 -4
- package/THIRD_PARTY_NOTICES.md +20 -0
- package/automation/brief.js +21 -24
- package/automation/builtins.js +55 -54
- package/automation/client.js +11 -3
- package/automation/client.src.cjs +70 -8
- package/automation/package.json +1 -1
- package/chart-ui/package.json +1 -1
- package/config/client.js +21 -5
- package/config/client.src.cjs +264 -0
- package/config/package.json +1 -1
- package/cordis.patch.yml +9 -2
- package/lib/agents/role-tool-policy.d.ts +1 -1
- package/lib/agents/root-tool-policy.d.ts +3 -3
- package/lib/agents/root-tool-policy.js +2 -2
- package/lib/data-collector/catalog-taxonomy.js +4 -0
- package/lib/python-runtime/child-env.d.ts +11 -0
- package/lib/python-runtime/child-env.js +39 -0
- package/lib/python-runtime/errors.d.ts +8 -0
- package/lib/python-runtime/errors.js +34 -0
- package/lib/python-runtime/lock.d.ts +11 -0
- package/lib/python-runtime/lock.js +68 -0
- package/lib/python-runtime/manager.d.ts +61 -0
- package/lib/python-runtime/manager.js +517 -0
- package/lib/python-runtime/manifest.d.ts +5 -0
- package/lib/python-runtime/manifest.js +160 -0
- package/lib/python-runtime/paths.d.ts +20 -0
- package/lib/python-runtime/paths.js +156 -0
- package/lib/python-runtime/platform.d.ts +32 -0
- package/lib/python-runtime/platform.js +145 -0
- package/lib/python-runtime/pnpm.d.ts +24 -0
- package/lib/python-runtime/pnpm.js +115 -0
- package/lib/python-runtime/probe.d.ts +13 -0
- package/lib/python-runtime/probe.js +101 -0
- package/lib/python-runtime/routes.d.ts +6 -0
- package/lib/python-runtime/routes.js +152 -0
- package/lib/python-runtime/types.d.ts +105 -0
- package/lib/python-runtime/types.js +3 -0
- package/lib/python-runtime-entry.d.ts +10 -0
- package/lib/python-runtime-entry.js +60 -0
- package/lib/sources/eastmoney-http.js +346 -1
- package/lib/sources/tencent-http.js +248 -2
- package/lib/sources/tencent-public-core.js +1 -1
- package/lib/sources-entry.d.ts +1 -1
- package/lib/time/tools.js +2 -0
- package/lib/web-retriever/local-fetch.d.ts +1 -1
- package/lib/web-retriever/local-fetch.js +1 -1
- package/lib/web-retriever/sources.d.ts +16 -1
- package/lib/web-retriever/sources.js +133 -1
- package/lib/web-retriever/tools.js +41 -1
- package/lib/web-retriever/wind-client.d.ts +1 -1
- package/lib/web-retriever/wind-client.js +1 -1
- package/package.json +13 -1
- package/plugin-page/README.en.md +1 -7
- package/plugin-page/README.zh.md +1 -8
- package/preset/capital-generation/agent.patch.yml +12 -13
- package/preset/capital-generation/skills/capital-web-protocol/SKILL.md +10 -4
- package/python/worker.py +154 -0
- package/runtime/manifest.json +75 -0
- package/scripts/python-runtime.mjs +139 -0
- package/watchlist/client.js +83 -3
- package/watchlist/client.src.cjs +565 -1
- package/watchlist/package.json +1 -1
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { PythonRuntimeError } from './errors.js';
|
|
3
|
+
import { PACK_NAMES, TARGET_IDS } from './types.js';
|
|
4
|
+
const VERSION = /^\d+(?:\.\d+)+(?:[.\-+][A-Za-z0-9._-]+)*$/u;
|
|
5
|
+
const PYTHON_VERSION = /^\d+\.\d+\.\d+(?:[.\-+][A-Za-z0-9._-]+)*$/u;
|
|
6
|
+
const PACKAGE = /^@?[a-z0-9][a-z0-9._-]*(?:\/[a-z0-9][a-z0-9._-]*)?$/u;
|
|
7
|
+
function record(value, label) {
|
|
8
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
9
|
+
throw new PythonRuntimeError('manifest-invalid', `${label} 必须是对象。`);
|
|
10
|
+
}
|
|
11
|
+
return value;
|
|
12
|
+
}
|
|
13
|
+
function string(value, label) {
|
|
14
|
+
if (typeof value !== 'string' || value === '') {
|
|
15
|
+
throw new PythonRuntimeError('manifest-invalid', `${label} 必须是非空字符串。`);
|
|
16
|
+
}
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
function positiveInteger(value, label) {
|
|
20
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
|
|
21
|
+
throw new PythonRuntimeError('manifest-invalid', `${label} 必须是正整数。`);
|
|
22
|
+
}
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
function version(value, label) {
|
|
26
|
+
const text = string(value, label);
|
|
27
|
+
if (!VERSION.test(text))
|
|
28
|
+
throw new PythonRuntimeError('manifest-invalid', `${label} 不是合法版本:${text}`);
|
|
29
|
+
return text;
|
|
30
|
+
}
|
|
31
|
+
function packageName(value, label) {
|
|
32
|
+
const text = string(value, label);
|
|
33
|
+
if (!PACKAGE.test(text))
|
|
34
|
+
throw new PythonRuntimeError('manifest-invalid', `${label} 不是合法包名:${text}`);
|
|
35
|
+
return text;
|
|
36
|
+
}
|
|
37
|
+
function targetId(value) {
|
|
38
|
+
if (!TARGET_IDS.includes(value)) {
|
|
39
|
+
throw new PythonRuntimeError('manifest-invalid', `未知 target:${value}`);
|
|
40
|
+
}
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
function packName(value) {
|
|
44
|
+
if (!PACK_NAMES.includes(value)) {
|
|
45
|
+
throw new PythonRuntimeError('manifest-invalid', `未知 pack:${value}`);
|
|
46
|
+
}
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
function parsePack(name, value) {
|
|
50
|
+
const raw = record(value, `packs.${name}`);
|
|
51
|
+
const kind = raw.kind;
|
|
52
|
+
if (kind !== 'base' && kind !== 'lib')
|
|
53
|
+
throw new PythonRuntimeError('manifest-invalid', `packs.${name}.kind 必须是 base 或 lib。`);
|
|
54
|
+
if (name === 'base' && kind !== 'base')
|
|
55
|
+
throw new PythonRuntimeError('manifest-invalid', 'base pack 的 kind 必须是 base。');
|
|
56
|
+
if (name !== 'base' && kind !== 'lib')
|
|
57
|
+
throw new PythonRuntimeError('manifest-invalid', `${name} pack 的 kind 必须是 lib。`);
|
|
58
|
+
const packagesRaw = record(raw.packages, `packs.${name}.packages`);
|
|
59
|
+
const packages = {};
|
|
60
|
+
for (const [packageKey, packageVersion] of Object.entries(packagesRaw)) {
|
|
61
|
+
packages[packageKey] = version(packageVersion, `packs.${name}.packages.${packageKey}`);
|
|
62
|
+
}
|
|
63
|
+
if (Object.keys(packages).length === 0)
|
|
64
|
+
throw new PythonRuntimeError('manifest-invalid', `packs.${name}.packages 不能为空。`);
|
|
65
|
+
const targetsRaw = record(raw.targets, `packs.${name}.targets`);
|
|
66
|
+
const targets = {};
|
|
67
|
+
for (const [key, targetValue] of Object.entries(targetsRaw)) {
|
|
68
|
+
const id = targetId(key);
|
|
69
|
+
const target = record(targetValue, `packs.${name}.targets.${key}`);
|
|
70
|
+
targets[id] = {
|
|
71
|
+
package: packageName(target.package, `packs.${name}.targets.${key}.package`),
|
|
72
|
+
version: version(target.version, `packs.${name}.targets.${key}.version`),
|
|
73
|
+
bytes: positiveInteger(target.bytes, `packs.${name}.targets.${key}.bytes`),
|
|
74
|
+
...(target.sha256 === undefined ? {} : { sha256: string(target.sha256, `packs.${name}.targets.${key}.sha256`) }),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
if (Object.keys(targets).length === 0)
|
|
78
|
+
throw new PythonRuntimeError('manifest-invalid', `packs.${name}.targets 不能为空。`);
|
|
79
|
+
let requires;
|
|
80
|
+
if (raw.requires !== undefined) {
|
|
81
|
+
const required = record(raw.requires, `packs.${name}.requires`);
|
|
82
|
+
requires = {};
|
|
83
|
+
for (const [key, requiredVersion] of Object.entries(required)) {
|
|
84
|
+
requires[packName(key)] = version(requiredVersion, `packs.${name}.requires.${key}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return { kind, packages, targets, ...(requires === undefined ? {} : { requires }) };
|
|
88
|
+
}
|
|
89
|
+
export function parseManifest(value) {
|
|
90
|
+
const raw = record(value, 'manifest');
|
|
91
|
+
if (raw.schemaVersion !== 1)
|
|
92
|
+
throw new PythonRuntimeError('manifest-invalid', 'manifest.schemaVersion 必须是 1。');
|
|
93
|
+
const python = version(raw.python, 'python');
|
|
94
|
+
if (!PYTHON_VERSION.test(python))
|
|
95
|
+
throw new PythonRuntimeError('manifest-invalid', `python 必须是三段式版本:${python}`);
|
|
96
|
+
const cacheRoot = string(raw.cacheRoot, 'cacheRoot');
|
|
97
|
+
if (cacheRoot.startsWith('/') || cacheRoot.includes('..') || cacheRoot.includes('\\')) {
|
|
98
|
+
throw new PythonRuntimeError('manifest-invalid', 'cacheRoot 必须是 DSH home 下的相对 POSIX 路径。');
|
|
99
|
+
}
|
|
100
|
+
const packsRaw = record(raw.packs, 'packs');
|
|
101
|
+
const packs = {
|
|
102
|
+
base: parsePack('base', packsRaw.base),
|
|
103
|
+
parquet: parsePack('parquet', packsRaw.parquet),
|
|
104
|
+
};
|
|
105
|
+
const limitsRaw = record(raw.limits, 'limits');
|
|
106
|
+
return {
|
|
107
|
+
schemaVersion: 1,
|
|
108
|
+
python,
|
|
109
|
+
cacheRoot,
|
|
110
|
+
packs,
|
|
111
|
+
limits: {
|
|
112
|
+
minFreeBytes: positiveInteger(limitsRaw.minFreeBytes, 'limits.minFreeBytes'),
|
|
113
|
+
installTimeoutMs: positiveInteger(limitsRaw.installTimeoutMs, 'limits.installTimeoutMs'),
|
|
114
|
+
probeTimeoutMs: positiveInteger(limitsRaw.probeTimeoutMs, 'limits.probeTimeoutMs'),
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
export function readManifest(path) {
|
|
119
|
+
let text;
|
|
120
|
+
try {
|
|
121
|
+
text = readFileSync(path, 'utf8');
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
throw new PythonRuntimeError('manifest-invalid', `读不到 runtime manifest:${path}`, String(error));
|
|
125
|
+
}
|
|
126
|
+
try {
|
|
127
|
+
return parseManifest(JSON.parse(text));
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
if (error instanceof PythonRuntimeError)
|
|
131
|
+
throw error;
|
|
132
|
+
throw new PythonRuntimeError('manifest-invalid', `runtime manifest 不是合法 JSON:${path}`, String(error));
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
export function packTarget(manifest, pack, target) {
|
|
136
|
+
const found = manifest.packs[pack].targets[target];
|
|
137
|
+
if (found === undefined) {
|
|
138
|
+
throw new PythonRuntimeError('unsupported-platform', `${pack} 没有 ${target} 的运行时包。`);
|
|
139
|
+
}
|
|
140
|
+
return found;
|
|
141
|
+
}
|
|
142
|
+
export function normalizePackNames(value) {
|
|
143
|
+
if (value === undefined)
|
|
144
|
+
return ['base'];
|
|
145
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
146
|
+
throw new PythonRuntimeError('invalid-request', 'packs 必须是非空数组。');
|
|
147
|
+
}
|
|
148
|
+
const names = [];
|
|
149
|
+
for (const item of value) {
|
|
150
|
+
if (typeof item !== 'string' || !PACK_NAMES.includes(item)) {
|
|
151
|
+
throw new PythonRuntimeError('invalid-request', `未知 pack:${String(item)}(只能是 ${PACK_NAMES.join(' 或 ')})。`);
|
|
152
|
+
}
|
|
153
|
+
const name = item;
|
|
154
|
+
if (!names.includes(name))
|
|
155
|
+
names.push(name);
|
|
156
|
+
}
|
|
157
|
+
if (names.includes('parquet'))
|
|
158
|
+
return ['base', ...names.filter((name) => name !== 'base')];
|
|
159
|
+
return names;
|
|
160
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { PackName, ReadyFile, TargetId } from './types.js';
|
|
2
|
+
export declare function resolveDshHome(profileHome?: string): string;
|
|
3
|
+
export declare function runtimeRoot(dshHome: string, cacheRoot: string): string;
|
|
4
|
+
export declare function packRoot(cacheRoot: string, pack: PackName, version: string, target: TargetId): string;
|
|
5
|
+
export declare function readyPath(root: string): string;
|
|
6
|
+
export declare function payloadPath(root: string): string;
|
|
7
|
+
export declare function stagingRoot(cacheRoot: string): string;
|
|
8
|
+
export declare function lockRoot(cacheRoot: string): string;
|
|
9
|
+
export declare function storeRoot(cacheRoot: string): string;
|
|
10
|
+
export declare function safeChild(root: string, ...parts: string[]): string;
|
|
11
|
+
export declare function safeRelative(root: string, relativePath: string): string;
|
|
12
|
+
export declare function isInside(root: string, candidate: string): boolean;
|
|
13
|
+
export declare function readJson<T>(path: string): Promise<T | undefined>;
|
|
14
|
+
export declare function writeJsonAtomic(path: string, value: unknown): Promise<void>;
|
|
15
|
+
export declare function exists(path: string): Promise<boolean>;
|
|
16
|
+
export declare function directoryBytes(path: string): Promise<number>;
|
|
17
|
+
export declare function availableBytes(path: string): Promise<number | undefined>;
|
|
18
|
+
export declare function removeStaleStaging(staging: string, maxAgeMs?: number): Promise<void>;
|
|
19
|
+
export declare function readyFileShape(value: unknown): value is ReadyFile;
|
|
20
|
+
export declare function assertStablePath(path: string, label: string): void;
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { mkdir, readFile, readdir, rename, rm, stat, statfs, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
5
|
+
import { PythonRuntimeError } from './errors.js';
|
|
6
|
+
export function resolveDshHome(profileHome) {
|
|
7
|
+
const env = process.env.DSH_HOME;
|
|
8
|
+
if (env !== undefined && env !== '')
|
|
9
|
+
return resolve(env);
|
|
10
|
+
if (profileHome !== undefined && profileHome !== '')
|
|
11
|
+
return resolve(profileHome);
|
|
12
|
+
return join(homedir(), '.dsh');
|
|
13
|
+
}
|
|
14
|
+
export function runtimeRoot(dshHome, cacheRoot) {
|
|
15
|
+
return join(dshHome, ...cacheRoot.split('/'));
|
|
16
|
+
}
|
|
17
|
+
export function packRoot(cacheRoot, pack, version, target) {
|
|
18
|
+
return join(cacheRoot, pack, version, target);
|
|
19
|
+
}
|
|
20
|
+
export function readyPath(root) {
|
|
21
|
+
return join(root, 'ready.json');
|
|
22
|
+
}
|
|
23
|
+
export function payloadPath(root) {
|
|
24
|
+
return join(root, 'payload');
|
|
25
|
+
}
|
|
26
|
+
export function stagingRoot(cacheRoot) {
|
|
27
|
+
return join(cacheRoot, 'staging');
|
|
28
|
+
}
|
|
29
|
+
export function lockRoot(cacheRoot) {
|
|
30
|
+
return join(cacheRoot, 'locks');
|
|
31
|
+
}
|
|
32
|
+
export function storeRoot(cacheRoot) {
|
|
33
|
+
return join(cacheRoot, 'pnpm-store');
|
|
34
|
+
}
|
|
35
|
+
export function safeChild(root, ...parts) {
|
|
36
|
+
const target = resolve(root, ...parts);
|
|
37
|
+
const rel = relative(root, target);
|
|
38
|
+
if (rel.startsWith('..') || isAbsolute(rel)) {
|
|
39
|
+
throw new PythonRuntimeError('pack-invalid', `路径逃出运行时目录:${parts.join('/')}`);
|
|
40
|
+
}
|
|
41
|
+
return target;
|
|
42
|
+
}
|
|
43
|
+
export function safeRelative(root, relativePath) {
|
|
44
|
+
if (relativePath === '' || isAbsolute(relativePath)) {
|
|
45
|
+
throw new PythonRuntimeError('pack-invalid', `运行时报文里的相对路径不合法:${relativePath}`);
|
|
46
|
+
}
|
|
47
|
+
const target = resolve(root, relativePath);
|
|
48
|
+
const rel = relative(root, target);
|
|
49
|
+
if (rel.startsWith('..') || isAbsolute(rel)) {
|
|
50
|
+
throw new PythonRuntimeError('pack-invalid', `运行时报文里的路径逃出 payload:${relativePath}`);
|
|
51
|
+
}
|
|
52
|
+
return target;
|
|
53
|
+
}
|
|
54
|
+
export function isInside(root, candidate) {
|
|
55
|
+
const rel = relative(resolve(root), resolve(candidate));
|
|
56
|
+
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
|
|
57
|
+
}
|
|
58
|
+
export async function readJson(path) {
|
|
59
|
+
try {
|
|
60
|
+
return JSON.parse(await readFile(path, 'utf8'));
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
export async function writeJsonAtomic(path, value) {
|
|
67
|
+
await mkdir(dirname(path), { recursive: true });
|
|
68
|
+
const temporary = `${path}.tmp-${process.pid}-${Date.now()}`;
|
|
69
|
+
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
|
|
70
|
+
await rename(temporary, path);
|
|
71
|
+
}
|
|
72
|
+
export async function exists(path) {
|
|
73
|
+
try {
|
|
74
|
+
await stat(path);
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
export async function directoryBytes(path) {
|
|
82
|
+
let total = 0;
|
|
83
|
+
let entries;
|
|
84
|
+
try {
|
|
85
|
+
entries = await readdir(path, { withFileTypes: true });
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return 0;
|
|
89
|
+
}
|
|
90
|
+
for (const entry of entries) {
|
|
91
|
+
const child = join(path, entry.name);
|
|
92
|
+
if (entry.isDirectory())
|
|
93
|
+
total += await directoryBytes(child);
|
|
94
|
+
else if (entry.isFile()) {
|
|
95
|
+
try {
|
|
96
|
+
total += (await stat(child)).size;
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
// A file removed during the scan contributes nothing.
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return total;
|
|
104
|
+
}
|
|
105
|
+
export async function availableBytes(path) {
|
|
106
|
+
try {
|
|
107
|
+
const stats = await statfs(path);
|
|
108
|
+
return stats.bavail * stats.bsize;
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
export async function removeStaleStaging(staging, maxAgeMs = 24 * 60 * 60 * 1000) {
|
|
115
|
+
let entries;
|
|
116
|
+
try {
|
|
117
|
+
entries = await readdir(staging, { withFileTypes: true });
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const now = Date.now();
|
|
123
|
+
for (const entry of entries) {
|
|
124
|
+
if (!entry.isDirectory())
|
|
125
|
+
continue;
|
|
126
|
+
const target = join(staging, entry.name);
|
|
127
|
+
try {
|
|
128
|
+
const info = await stat(target);
|
|
129
|
+
if (now - info.mtimeMs > maxAgeMs)
|
|
130
|
+
await rm(target, { recursive: true, force: true });
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
// Best-effort cleanup only.
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
export function readyFileShape(value) {
|
|
138
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
139
|
+
return false;
|
|
140
|
+
const raw = value;
|
|
141
|
+
return raw.schemaVersion === 1
|
|
142
|
+
&& typeof raw.pack === 'string'
|
|
143
|
+
&& typeof raw.packVersion === 'string'
|
|
144
|
+
&& typeof raw.target === 'string'
|
|
145
|
+
&& typeof raw.package === 'string'
|
|
146
|
+
&& typeof raw.pythonVersion === 'string'
|
|
147
|
+
&& (raw.python === null || typeof raw.python === 'string')
|
|
148
|
+
&& Array.isArray(raw.sitePackages)
|
|
149
|
+
&& raw.sitePackages.every((item) => typeof item === 'string')
|
|
150
|
+
&& raw.packages !== null
|
|
151
|
+
&& typeof raw.packages === 'object';
|
|
152
|
+
}
|
|
153
|
+
export function assertStablePath(path, label) {
|
|
154
|
+
if (!existsSync(path))
|
|
155
|
+
throw new PythonRuntimeError('pack-invalid', `${label} 不存在:${path}`);
|
|
156
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { TargetId } from './types.js';
|
|
2
|
+
export interface PlatformFacts {
|
|
3
|
+
platform: string;
|
|
4
|
+
arch: string;
|
|
5
|
+
target: TargetId | null;
|
|
6
|
+
supported: boolean;
|
|
7
|
+
reason?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface PlatformProbeInput {
|
|
10
|
+
platform?: string;
|
|
11
|
+
arch?: string;
|
|
12
|
+
release?: string;
|
|
13
|
+
glibc?: string;
|
|
14
|
+
}
|
|
15
|
+
type EnvLike = Record<string, string | undefined>;
|
|
16
|
+
/** The only place that turns process.platform/arch into a supported target. */
|
|
17
|
+
export declare function detectPlatform(input?: PlatformProbeInput): PlatformFacts;
|
|
18
|
+
/** PATH directories. Always split on node:path delimiter; ':' breaks Windows paths. */
|
|
19
|
+
export declare function pathDirs(env?: EnvLike): string[];
|
|
20
|
+
/** Resolve pnpm to `node <pnpm.cjs>`; bare pnpm.cmd cannot be spawned without a shell. */
|
|
21
|
+
export declare function findPnpmCli(env?: EnvLike): {
|
|
22
|
+
command: string;
|
|
23
|
+
args: string[];
|
|
24
|
+
};
|
|
25
|
+
export declare function minimalSystemPath(env?: EnvLike): string;
|
|
26
|
+
export declare const pythonFlags: readonly string[];
|
|
27
|
+
export declare const detachedChild: boolean;
|
|
28
|
+
/** Kill a child's process tree. POSIX children are spawned detached (own process group). */
|
|
29
|
+
export declare function killTree(pid: number | undefined, child: {
|
|
30
|
+
kill(signal?: NodeJS.Signals): boolean;
|
|
31
|
+
} | undefined, signal?: NodeJS.Signals): Promise<void>;
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { existsSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { basename, delimiter, dirname, join, resolve } from 'node:path';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import { PythonRuntimeError } from './errors.js';
|
|
6
|
+
function normalizeArch(arch) {
|
|
7
|
+
if (arch === 'amd64')
|
|
8
|
+
return 'x64';
|
|
9
|
+
return arch;
|
|
10
|
+
}
|
|
11
|
+
function windowsBuild(release) {
|
|
12
|
+
const parts = release.split('.');
|
|
13
|
+
const build = Number(parts[2]);
|
|
14
|
+
return Number.isFinite(build) ? build : undefined;
|
|
15
|
+
}
|
|
16
|
+
function macosMajor(release) {
|
|
17
|
+
const major = Number(release.split('.')[0]);
|
|
18
|
+
return Number.isFinite(major) ? major : undefined;
|
|
19
|
+
}
|
|
20
|
+
function glibcAtLeast(version, requiredMajor, requiredMinor) {
|
|
21
|
+
const [major, minor] = version.split('.').map(Number);
|
|
22
|
+
if (!Number.isFinite(major) || !Number.isFinite(minor))
|
|
23
|
+
return false;
|
|
24
|
+
return major > requiredMajor || (major === requiredMajor && minor >= requiredMinor);
|
|
25
|
+
}
|
|
26
|
+
/** The only place that turns process.platform/arch into a supported target. */
|
|
27
|
+
export function detectPlatform(input = {}) {
|
|
28
|
+
const platform = input.platform ?? process.platform;
|
|
29
|
+
const arch = normalizeArch(input.arch ?? process.arch);
|
|
30
|
+
const release = input.release ?? os.release();
|
|
31
|
+
const glibc = input.glibc ?? process.report?.getReport()?.header?.glibcVersionRuntime;
|
|
32
|
+
if (platform === 'win32') {
|
|
33
|
+
if (arch !== 'x64') {
|
|
34
|
+
return { platform, arch, target: null, supported: false, reason: 'Windows 暂只支持 x64;ARM64 运行时包尚未提供。' };
|
|
35
|
+
}
|
|
36
|
+
const build = windowsBuild(release);
|
|
37
|
+
if (build !== undefined && build < 17763) {
|
|
38
|
+
return { platform, arch, target: null, supported: false, reason: '需要 Windows 10 1809(build 17763)或更高版本。' };
|
|
39
|
+
}
|
|
40
|
+
return { platform, arch, target: 'win32-x64', supported: true };
|
|
41
|
+
}
|
|
42
|
+
if (platform === 'darwin') {
|
|
43
|
+
if (arch !== 'arm64' && arch !== 'x64') {
|
|
44
|
+
return { platform, arch, target: null, supported: false, reason: 'macOS 只支持 arm64 或 x64。' };
|
|
45
|
+
}
|
|
46
|
+
// Darwin 21 == macOS 12 (Monterey). pyarrow 25 wheels start at macOS 12.
|
|
47
|
+
if ((macosMajor(release) ?? 0) < 21) {
|
|
48
|
+
return { platform, arch, target: null, supported: false, reason: '需要 macOS 12(Monterey)或更高版本。' };
|
|
49
|
+
}
|
|
50
|
+
return { platform, arch, target: arch === 'arm64' ? 'darwin-arm64' : 'darwin-x64', supported: true };
|
|
51
|
+
}
|
|
52
|
+
if (platform === 'linux') {
|
|
53
|
+
if (arch !== 'x64') {
|
|
54
|
+
return { platform, arch, target: null, supported: false, reason: 'Linux 首期只支持 x64;ARM64 运行时包尚未提供。' };
|
|
55
|
+
}
|
|
56
|
+
if (glibc === undefined || !glibcAtLeast(glibc, 2, 28)) {
|
|
57
|
+
return {
|
|
58
|
+
platform,
|
|
59
|
+
arch,
|
|
60
|
+
target: null,
|
|
61
|
+
supported: false,
|
|
62
|
+
reason: `需要 glibc 2.28+(当前 ${glibc ?? '未知,可能是 musl/Alpine'})。`,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
return { platform, arch, target: 'linux-x64', supported: true };
|
|
66
|
+
}
|
|
67
|
+
return { platform, arch, target: null, supported: false, reason: `不支持的操作系统:${platform}。` };
|
|
68
|
+
}
|
|
69
|
+
/** PATH directories. Always split on node:path delimiter; ':' breaks Windows paths. */
|
|
70
|
+
export function pathDirs(env = process.env) {
|
|
71
|
+
return (env.PATH ?? '').split(delimiter).filter((dir) => dir.length > 0);
|
|
72
|
+
}
|
|
73
|
+
function realpath(file) {
|
|
74
|
+
try {
|
|
75
|
+
return realpathSync(file);
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function isPnpmCli(file) {
|
|
82
|
+
const name = basename(file);
|
|
83
|
+
return name === 'pnpm.cjs' || name === 'pnpm.mjs';
|
|
84
|
+
}
|
|
85
|
+
/** Resolve pnpm to `node <pnpm.cjs>`; bare pnpm.cmd cannot be spawned without a shell. */
|
|
86
|
+
export function findPnpmCli(env = process.env) {
|
|
87
|
+
const override = env.CG_PNPM_CLI;
|
|
88
|
+
if (override !== undefined && override !== '') {
|
|
89
|
+
if (!existsSync(override))
|
|
90
|
+
throw new PythonRuntimeError('pnpm-missing', `CG_PNPM_CLI 指向的文件不存在:${override}`);
|
|
91
|
+
return { command: process.execPath, args: [override] };
|
|
92
|
+
}
|
|
93
|
+
const candidates = [];
|
|
94
|
+
for (const dir of pathDirs(env)) {
|
|
95
|
+
candidates.push(join(dir, 'pnpm'));
|
|
96
|
+
candidates.push(join(dir, 'pnpm.cjs'));
|
|
97
|
+
candidates.push(join(dir, 'node_modules', 'pnpm', 'bin', 'pnpm.cjs'));
|
|
98
|
+
candidates.push(resolve(dir, '..', 'lib', 'node_modules', 'pnpm', 'bin', 'pnpm.cjs'));
|
|
99
|
+
candidates.push(resolve(dir, '..', 'pnpm', 'bin', 'pnpm.cjs'));
|
|
100
|
+
}
|
|
101
|
+
const nodeDir = dirname(process.execPath);
|
|
102
|
+
candidates.push(join(nodeDir, 'node_modules', 'pnpm', 'bin', 'pnpm.cjs'));
|
|
103
|
+
for (const candidate of candidates) {
|
|
104
|
+
const real = realpath(candidate);
|
|
105
|
+
if (real !== undefined && isPnpmCli(real))
|
|
106
|
+
return { command: process.execPath, args: [real] };
|
|
107
|
+
}
|
|
108
|
+
throw new PythonRuntimeError('pnpm-missing', '找不到 pnpm CLI。请确认 DSH 的插件管理器可用,或通过 CG_PNPM_CLI 指定 pnpm.cjs 的绝对路径。');
|
|
109
|
+
}
|
|
110
|
+
export function minimalSystemPath(env = process.env) {
|
|
111
|
+
if ((env.SystemRoot ?? '') !== '') {
|
|
112
|
+
return [join(env.SystemRoot, 'System32'), env.SystemRoot].join(delimiter);
|
|
113
|
+
}
|
|
114
|
+
return ['/usr/bin', '/bin', '/usr/sbin', '/sbin'].join(delimiter);
|
|
115
|
+
}
|
|
116
|
+
export const pythonFlags = Object.freeze(['-I', '-B', '-u']);
|
|
117
|
+
export const detachedChild = process.platform !== 'win32';
|
|
118
|
+
/** Kill a child's process tree. POSIX children are spawned detached (own process group). */
|
|
119
|
+
export function killTree(pid, child, signal = 'SIGTERM') {
|
|
120
|
+
if (pid === undefined) {
|
|
121
|
+
child?.kill(signal);
|
|
122
|
+
return Promise.resolve();
|
|
123
|
+
}
|
|
124
|
+
if (process.platform !== 'win32') {
|
|
125
|
+
try {
|
|
126
|
+
process.kill(-pid, signal);
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
// ESRCH means it already exited; fall back to the direct child handle.
|
|
130
|
+
try {
|
|
131
|
+
child?.kill(signal);
|
|
132
|
+
}
|
|
133
|
+
catch { /* already gone */ }
|
|
134
|
+
}
|
|
135
|
+
return Promise.resolve();
|
|
136
|
+
}
|
|
137
|
+
return new Promise((resolvePromise) => {
|
|
138
|
+
const killer = spawn('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
|
|
139
|
+
killer.once('error', () => { try {
|
|
140
|
+
child?.kill(signal);
|
|
141
|
+
}
|
|
142
|
+
catch { /* already gone */ } resolvePromise(); });
|
|
143
|
+
killer.once('close', () => resolvePromise());
|
|
144
|
+
});
|
|
145
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { PythonRuntimeError } from './errors.js';
|
|
2
|
+
export interface PnpmInvocation {
|
|
3
|
+
command: string;
|
|
4
|
+
args: string[];
|
|
5
|
+
env?: Record<string, string>;
|
|
6
|
+
}
|
|
7
|
+
export interface PnpmRunResult {
|
|
8
|
+
code: number | null;
|
|
9
|
+
output: string;
|
|
10
|
+
timedOut: boolean;
|
|
11
|
+
aborted: boolean;
|
|
12
|
+
}
|
|
13
|
+
export interface PnpmRunOptions {
|
|
14
|
+
cwd: string;
|
|
15
|
+
timeoutMs: number;
|
|
16
|
+
signal?: AbortSignal;
|
|
17
|
+
env?: Record<string, string>;
|
|
18
|
+
maxOutputBytes?: number;
|
|
19
|
+
}
|
|
20
|
+
/** Run pnpm without a shell. The caller owns the exact package spec (never model input). */
|
|
21
|
+
export declare function runPnpm(invocation: PnpmInvocation, args: string[], options: PnpmRunOptions): Promise<PnpmRunResult>;
|
|
22
|
+
export declare function classifyPnpmFailure(result: PnpmRunResult): PythonRuntimeError;
|
|
23
|
+
export declare function writeInstallProject(payloadDir: string, packageName: string, spec: string, registry?: string): Promise<void>;
|
|
24
|
+
export declare function installArgs(payloadDir: string, storeDir: string, registry?: string): string[];
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { PythonRuntimeError } from './errors.js';
|
|
5
|
+
import { killTree } from './platform.js';
|
|
6
|
+
const MAX_OUTPUT = 64 * 1024;
|
|
7
|
+
function appendBounded(previous, chunk, cap) {
|
|
8
|
+
const next = previous + chunk.toString('utf8');
|
|
9
|
+
return next.length > cap ? next.slice(next.length - cap) : next;
|
|
10
|
+
}
|
|
11
|
+
/** Run pnpm without a shell. The caller owns the exact package spec (never model input). */
|
|
12
|
+
export async function runPnpm(invocation, args, options) {
|
|
13
|
+
const cap = options.maxOutputBytes ?? MAX_OUTPUT;
|
|
14
|
+
return await new Promise((resolvePromise, reject) => {
|
|
15
|
+
let output = '';
|
|
16
|
+
let timedOut = false;
|
|
17
|
+
let aborted = false;
|
|
18
|
+
let settled = false;
|
|
19
|
+
const child = spawn(invocation.command, [...invocation.args, ...args], {
|
|
20
|
+
cwd: options.cwd,
|
|
21
|
+
env: { ...process.env, ...invocation.env, ...options.env },
|
|
22
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
23
|
+
windowsHide: true,
|
|
24
|
+
});
|
|
25
|
+
const timer = setTimeout(() => {
|
|
26
|
+
timedOut = true;
|
|
27
|
+
void killTree(child.pid, child, 'SIGTERM');
|
|
28
|
+
setTimeout(() => { void killTree(child.pid, child, 'SIGKILL'); }, 2_000).unref?.();
|
|
29
|
+
}, options.timeoutMs);
|
|
30
|
+
timer.unref?.();
|
|
31
|
+
const abort = () => {
|
|
32
|
+
aborted = true;
|
|
33
|
+
void killTree(child.pid, child, 'SIGTERM');
|
|
34
|
+
setTimeout(() => { void killTree(child.pid, child, 'SIGKILL'); }, 2_000).unref?.();
|
|
35
|
+
};
|
|
36
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
37
|
+
const finish = (code) => {
|
|
38
|
+
if (settled)
|
|
39
|
+
return;
|
|
40
|
+
settled = true;
|
|
41
|
+
clearTimeout(timer);
|
|
42
|
+
options.signal?.removeEventListener('abort', abort);
|
|
43
|
+
resolvePromise({ code, output, timedOut, aborted });
|
|
44
|
+
};
|
|
45
|
+
child.stdout?.on('data', (chunk) => { output = appendBounded(output, chunk, cap); });
|
|
46
|
+
child.stderr?.on('data', (chunk) => { output = appendBounded(output, chunk, cap); });
|
|
47
|
+
child.once('error', (error) => {
|
|
48
|
+
if (settled)
|
|
49
|
+
return;
|
|
50
|
+
settled = true;
|
|
51
|
+
clearTimeout(timer);
|
|
52
|
+
options.signal?.removeEventListener('abort', abort);
|
|
53
|
+
const code = error.code;
|
|
54
|
+
if (code === 'ENOENT')
|
|
55
|
+
reject(new PythonRuntimeError('pnpm-missing', 'pnpm 可执行文件不存在。', String(error)));
|
|
56
|
+
else
|
|
57
|
+
reject(new PythonRuntimeError('unknown', `启动 pnpm 失败:${String(error)}`));
|
|
58
|
+
});
|
|
59
|
+
child.once('close', (code) => finish(code));
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
export function classifyPnpmFailure(result) {
|
|
63
|
+
if (result.aborted)
|
|
64
|
+
return new PythonRuntimeError('cancelled', undefined, result.output);
|
|
65
|
+
if (result.timedOut)
|
|
66
|
+
return new PythonRuntimeError('timeout', 'pnpm 安装运行时包超时。', result.output);
|
|
67
|
+
const text = result.output;
|
|
68
|
+
if (/ERR_PNPM_FETCH_404|E404|404 Not Found/i.test(text)) {
|
|
69
|
+
return new PythonRuntimeError('not-found', '运行时包版本在 registry 中不存在,或镜像尚未同步。', text);
|
|
70
|
+
}
|
|
71
|
+
if (/ERR_PNPM_META_FETCH_FAIL|ECONN|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ERR_SOCKET|proxy|TLS|certificate/i.test(text)) {
|
|
72
|
+
return new PythonRuntimeError('network', '无法连接 npm registry 或代理/TLS 失败。', text);
|
|
73
|
+
}
|
|
74
|
+
if (/ENOSPC|no space left/i.test(text))
|
|
75
|
+
return new PythonRuntimeError('disk-space', undefined, text);
|
|
76
|
+
if (/EACCES|EPERM|permission denied/i.test(text))
|
|
77
|
+
return new PythonRuntimeError('permission', undefined, text);
|
|
78
|
+
return new PythonRuntimeError('unknown', `pnpm 安装失败(exit ${String(result.code)})。`, text);
|
|
79
|
+
}
|
|
80
|
+
export async function writeInstallProject(payloadDir, packageName, spec, registry) {
|
|
81
|
+
await mkdir(payloadDir, { recursive: true });
|
|
82
|
+
const manifest = {
|
|
83
|
+
name: 'capital-python-runtime-install',
|
|
84
|
+
private: true,
|
|
85
|
+
version: '1.0.0',
|
|
86
|
+
dependencies: { [packageName]: spec },
|
|
87
|
+
};
|
|
88
|
+
const npmrc = [
|
|
89
|
+
'node-linker=hoisted',
|
|
90
|
+
'package-import-method=auto',
|
|
91
|
+
'ignore-scripts=true',
|
|
92
|
+
'strict-peer-dependencies=false',
|
|
93
|
+
'auto-install-peers=false',
|
|
94
|
+
...(registry === undefined || registry === '' ? [] : [`registry=${registry}`]),
|
|
95
|
+
'',
|
|
96
|
+
].join('\n');
|
|
97
|
+
await writeFile(join(payloadDir, 'package.json'), `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
|
|
98
|
+
await writeFile(join(payloadDir, '.npmrc'), npmrc, 'utf8');
|
|
99
|
+
}
|
|
100
|
+
export function installArgs(payloadDir, storeDir, registry) {
|
|
101
|
+
return [
|
|
102
|
+
'install',
|
|
103
|
+
'--dir', payloadDir,
|
|
104
|
+
'--ignore-workspace',
|
|
105
|
+
'--no-lockfile',
|
|
106
|
+
'--prod',
|
|
107
|
+
'--ignore-scripts',
|
|
108
|
+
'--store-dir', storeDir,
|
|
109
|
+
'--reporter=append-only',
|
|
110
|
+
// pnpm 11 may ignore node-linker from a project .npmrc when --dir names another project.
|
|
111
|
+
'--config.node-linker=hoisted',
|
|
112
|
+
'--config.package-import-method=auto',
|
|
113
|
+
...(registry === undefined || registry === '' ? [] : ['--registry', registry]),
|
|
114
|
+
];
|
|
115
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ProbeReport } from './types.js';
|
|
2
|
+
export interface ProbeOptions {
|
|
3
|
+
python: string;
|
|
4
|
+
workerPath: string;
|
|
5
|
+
sitePackages: string[];
|
|
6
|
+
homeDir: string;
|
|
7
|
+
tempDir: string;
|
|
8
|
+
timeoutMs: number;
|
|
9
|
+
signal?: AbortSignal;
|
|
10
|
+
env?: Record<string, string | undefined>;
|
|
11
|
+
}
|
|
12
|
+
/** Run the private interpreter once and require its self-check JSON. */
|
|
13
|
+
export declare function probePython(options: ProbeOptions): Promise<ProbeReport>;
|