@v587d/capital-generation 2.23.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 (63) hide show
  1. package/CHANGELOG.md +49 -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.d.ts +16 -0
  14. package/lib/data-collector/catalog-taxonomy.js +179 -0
  15. package/lib/data-collector/hub.d.ts +16 -3
  16. package/lib/data-collector/hub.js +40 -6
  17. package/lib/data-collector/tools.js +46 -8
  18. package/lib/python-runtime/child-env.d.ts +11 -0
  19. package/lib/python-runtime/child-env.js +39 -0
  20. package/lib/python-runtime/errors.d.ts +8 -0
  21. package/lib/python-runtime/errors.js +34 -0
  22. package/lib/python-runtime/lock.d.ts +11 -0
  23. package/lib/python-runtime/lock.js +68 -0
  24. package/lib/python-runtime/manager.d.ts +61 -0
  25. package/lib/python-runtime/manager.js +517 -0
  26. package/lib/python-runtime/manifest.d.ts +5 -0
  27. package/lib/python-runtime/manifest.js +160 -0
  28. package/lib/python-runtime/paths.d.ts +20 -0
  29. package/lib/python-runtime/paths.js +156 -0
  30. package/lib/python-runtime/platform.d.ts +32 -0
  31. package/lib/python-runtime/platform.js +145 -0
  32. package/lib/python-runtime/pnpm.d.ts +24 -0
  33. package/lib/python-runtime/pnpm.js +115 -0
  34. package/lib/python-runtime/probe.d.ts +13 -0
  35. package/lib/python-runtime/probe.js +101 -0
  36. package/lib/python-runtime/routes.d.ts +6 -0
  37. package/lib/python-runtime/routes.js +152 -0
  38. package/lib/python-runtime/types.d.ts +105 -0
  39. package/lib/python-runtime/types.js +3 -0
  40. package/lib/python-runtime-entry.d.ts +10 -0
  41. package/lib/python-runtime-entry.js +60 -0
  42. package/lib/sources/eastmoney-http.js +346 -1
  43. package/lib/sources/tencent-http.js +248 -2
  44. package/lib/sources/tencent-public-core.js +1 -1
  45. package/lib/sources-entry.d.ts +1 -1
  46. package/lib/time/tools.js +2 -0
  47. package/lib/web-retriever/local-fetch.d.ts +1 -1
  48. package/lib/web-retriever/local-fetch.js +1 -1
  49. package/lib/web-retriever/sources.d.ts +16 -1
  50. package/lib/web-retriever/sources.js +133 -1
  51. package/lib/web-retriever/tools.js +41 -1
  52. package/lib/web-retriever/wind-client.d.ts +1 -1
  53. package/lib/web-retriever/wind-client.js +1 -1
  54. package/package.json +13 -1
  55. package/plugin-page/README.en.md +1 -7
  56. package/plugin-page/README.zh.md +1 -8
  57. package/preset/capital-generation/agent.patch.yml +12 -13
  58. package/preset/capital-generation/skills/capital-data-protocol/SKILL.md +21 -22
  59. package/preset/capital-generation/skills/capital-web-protocol/SKILL.md +10 -4
  60. package/python/worker.py +154 -0
  61. package/runtime/manifest.json +75 -0
  62. package/scripts/python-runtime.mjs +139 -0
  63. package/watchlist/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  import { summarizeTimeCoverage } from './time-axis.js';
2
+ import { CATALOG_TOPICS, CATALOG_TOPIC_LABELS, topicOf } from './catalog-taxonomy.js';
2
3
  /** Normalize an internal data_key token; data_key is host-only and never model-visible. */
3
4
  export function normalizeKeyToken(value) {
4
5
  return value.replace(/[\\/:]+/g, '.')
@@ -27,6 +28,14 @@ function encodeDirectoryField(value) {
27
28
  .replace(/\n/g, '\\n')
28
29
  .replace(/\t/g, '\\t');
29
30
  }
31
+ /** One model-visible catalog line; keep this the only encoder so index and shard lines cannot drift. */
32
+ function formatCapabilityLine(entry) {
33
+ return `${encodeDirectoryField(entry.capability)}|${encodeDirectoryField(entry.summary)}|${entry.paginated ? 1 : 0}`;
34
+ }
35
+ /** Host pruner measures Unicode code points, not UTF-16 units; shard sizes use the same denominator. */
36
+ function codePointLength(value) {
37
+ return Array.from(value).length;
38
+ }
30
39
  function isPlainRecord(value) {
31
40
  return typeof value === 'object' && value !== null && !Array.isArray(value);
32
41
  }
@@ -258,22 +267,47 @@ export class DataCollectorHub {
258
267
  waiter.reject(outcome.error);
259
268
  }
260
269
  /** Catalog: capability, one-line summary, paginated only. Full schemas would be pruned; details come from describeCapability. */
261
- listCapabilities() {
262
- return [...this.sources.values()].map((source) => ({
270
+ listCapabilities(topic) {
271
+ const entries = [...this.sources.values()].map((source) => ({
263
272
  capability: source.schema.capability,
264
273
  summary: summarize(source.schema),
265
274
  paginated: source.schema.paginated === true,
266
275
  }));
276
+ return topic === undefined ? entries : entries.filter((entry) => topicOf(entry.capability) === topic);
267
277
  }
268
278
  capabilityNames() {
269
279
  return [...this.sources.keys()];
270
280
  }
271
- /** Model-visible catalog: one `capability|summary|paginated` line each; JSON costs about twice the tokens. */
272
- capabilityDirectory() {
273
- return this.listCapabilities()
274
- .map((entry) => `${encodeDirectoryField(entry.capability)}|${encodeDirectoryField(entry.summary)}|${entry.paginated ? 1 : 0}`)
281
+ /** One row per non-empty topic; chars is the exact size of the shard text the model will receive. */
282
+ catalogTopicEntries() {
283
+ const result = [];
284
+ for (const topic of CATALOG_TOPICS) {
285
+ const entries = this.listCapabilities(topic);
286
+ if (entries.length === 0)
287
+ continue;
288
+ const chars = codePointLength(entries.map(formatCapabilityLine).join('\n'));
289
+ result.push({
290
+ topic,
291
+ label: CATALOG_TOPIC_LABELS[topic],
292
+ count: entries.length,
293
+ chars,
294
+ examples: entries.slice(0, 2).map((entry) => entry.capability),
295
+ });
296
+ }
297
+ return result;
298
+ }
299
+ /** Discovery index: `topic|label|count|chars|examples`, one row per non-empty shard. */
300
+ catalogIndex() {
301
+ return this.catalogTopicEntries()
302
+ .map((entry) => [entry.topic, entry.label, String(entry.count), String(entry.chars), entry.examples.join(',')]
303
+ .map(encodeDirectoryField)
304
+ .join('|'))
275
305
  .join('\n');
276
306
  }
307
+ /** Full catalog is internal aggregation only; the model receives catalogIndex() or one topic shard. */
308
+ capabilityDirectory(topic) {
309
+ return this.listCapabilities(topic).map(formatCapabilityLine).join('\n');
310
+ }
277
311
  /** Single capability contract; undefined for unknown names (the tool layer classifies it). */
278
312
  describeCapability(capability) {
279
313
  const source = this.sources.get(capability);
@@ -2,6 +2,7 @@ import { UpstreamRetryBudget, classifyUpstreamFailure, retryBudgetKey, upstreamF
2
2
  // Session reading and authorization have one implementation (src/tool-exec.ts); do not re-implement here.
3
3
  import { authorizedSession, sessionIdentityDecisions } from '../tool-exec.js';
4
4
  import { DATA_COLLECTION_PRESET_IDS } from '../preset-ids.js';
5
+ import { CATALOG_TOPICS } from './catalog-taxonomy.js';
5
6
  const jsonObject = (properties = {}, required = []) => ({ type: 'object', properties, required, additionalProperties: false });
6
7
  const freeObject = { type: 'object', additionalProperties: true };
7
8
  const MAX_ID_LENGTH = 256;
@@ -114,12 +115,30 @@ function resolveCapability(hub, value) {
114
115
  if (!hub.describeCapability(name)) {
115
116
  const available = hub.capabilityNames();
116
117
  if (available.length === 0) {
117
- throw capabilityError('capability_catalog_empty', '当前没有任何已注册的数据能力(数据源注册没有生效)。注意:缺凭据**不会**让目录变空——同花顺能力始终在目录里,只在取数那一刻点名 FUYAO_API_KEY 失败。本工具此刻对任何名字都会失败——不要反复重试,也不要编造能力名;请把该状态回告主 Agent,必要时用 dc_status 核对 registered_capabilities 与 api_key。');
118
+ throw capabilityError('capability_catalog_empty', '当前没有任何已注册的数据能力(数据源注册没有生效)。注意:缺凭据**不会**让目录变空——同花顺能力始终在目录里,只在取数那一刻点名 FUYAO_API_KEY 失败。本工具此刻对任何名字都会失败——不要反复重试,也不要编造能力名;请把该状态回告主 Agent,必要时用 dc_status 核对 registered_capability_count / registered_topics 与 api_key。');
118
119
  }
119
- throw capabilityError('capability_unknown', `未注册的能力 "${name}"。当前可用能力:${available.join(', ')}。请从 list_capabilities() 返回的目录里原样复制一个名字,再调用 describe_capability;不要自行编造、缩写或改写。`);
120
+ throw capabilityError('capability_unknown', `未注册的能力 "${name}"。目录按九个主题分片,下面是索引;先按 topic 取分片,再原样复制名字:\n${hub.catalogIndex()}\n不要自行编造、缩写或改写。`);
120
121
  }
121
122
  return name;
122
123
  }
124
+ /** `topic` is optional; blank means "index", an unknown value gets the full topic list instead of an empty shard. */
125
+ function resolveCatalogTopic(hub, value) {
126
+ if (value === undefined || value === null)
127
+ return undefined;
128
+ if (typeof value !== 'string') {
129
+ throw capabilityError('capability_scope_invalid', `topic 必须是字符串(收到 ${Array.isArray(value) ? 'array' : typeof value})。省略 topic 取九行索引,或从索引里选一个 topic 原样传入。`);
130
+ }
131
+ const topic = value.trim();
132
+ if (topic.length === 0)
133
+ return undefined;
134
+ const entries = hub.catalogTopicEntries();
135
+ const match = entries.find((entry) => entry.topic === topic);
136
+ if (!match) {
137
+ const available = entries.map((entry) => `${entry.topic}(${entry.label},${entry.count}条)`).join('、');
138
+ throw capabilityError('capability_scope_invalid', `未知 topic "${topic}"。可用 topic:${available || '(当前目录为空)'}。请从 list_capabilities() 的索引里原样选一个 topic,再调用 list_capabilities({ "topic": "<topic>" });不要编造。需要全量就九片分别取,不要用 all。`);
139
+ }
140
+ return match.topic;
141
+ }
123
142
  export function registerDataCollectorTools(ctx, hub, diagnostics) {
124
143
  const tools = ctx.get('tools');
125
144
  if (!tools)
@@ -177,8 +196,21 @@ export function registerDataCollectorTools(ctx, hub, diagnostics) {
177
196
  throw requestParamsError(error, requestedCapability) ?? error;
178
197
  }
179
198
  }),
180
- tool('list_capabilities', '列出当前已注册的数据能力目录:**纯文本,一行一条** `capability|summary|paginated`,paginated 为 1(分页)/ 0(不分页)。名字或摘要里的 `|`、换行会转义成 `\\|`、`\\n`,所以一行就是一条能力,不要按冒号或空格拆分。目录是发现入口,**一个任务只需调用一次**:同一 session 的历史里已经保有这份目录,重复调用只会白占上下文。目录刻意不含参数与输出结构(完整 schema 约 23KB,会被剪枝截断);确定要用的能力后,用 describe_capability 单独取那一个能力的 input_schema 后即可 request_data。request_data 的 capability 必须以本目录为准,不要自行编造。', jsonObject(), { type: 'string' }, async (_args, exec) => { authorizedSession(ctx, exec, 'list_capabilities', DATA_COLLECTION_PRESET_IDS); return hub.capabilityDirectory(); }, { concurrencySafe: true }),
181
- tool('describe_capability', '读取**一个**能力的完整契约:description(单位、null 语义、时间与分页口径)、input_schema(params 的取值与约束)、output_fields(返回字段的逐行字典 `路径:类型[:说明]`,类型后缀 `?` 为可为 null、`[].` 为数组元素的字段)与 paginated。request_data 的 params 必须按这里返回的 input_schema 填写;request_data 若返回 request_params_invalid,应回到这里重新读取后再重试。一个能力描述一次即可:结果已在本 session 历史里,重复描述同一个能力只会白占上下文;需要几个能力就**在同一条消息里一次发出多个调用**(本工具是纯读、可并发执行,框架会把它们放进并发池、在同一个下一步一起返回),但一次仍只传**一个**名字,不要用逗号把多个名字塞进一条调用。错误按 code 引导:capability_required(没给名字,先 list_capabilities())、capability_invalid(不是字符串/超长/含逗号,改为目录中的单个名字)、capability_catalog_empty(数据源未注册,别重试,回告主 Agent)、capability_unknown(名字不存在,错误里会列出全部可用能力名并要求原样复制)。', jsonObject({ capability: { type: 'string' } }, ['capability']), jsonObject({
199
+ tool('list_capabilities', '发现数据能力目录。不传 topic:返回九行主题索引 `topic|中文|条数|码点|例子`,先看哪个主题包含所需能力;传 topic:返回该主题的 `capability|summary|paginated` 行。按问题需要取片,不设片数上限:复杂/跨资产问题建议第一步九片全取,单一资产按需取;同一 session 已有结果不要重复调用,多个 topic 在同一条消息里并发调用(本工具纯读、可并发)。片数是结果,不是配额;单片 <2048 是体积预算。目录刻意不含 schema;选定能力后用 describe_capability 取完整契约。request_data 的 capability 必须以目录为准,不要编造。未知 topic 返回 capability_scope_invalid 并列出可用主题。', jsonObject({
200
+ topic: {
201
+ type: 'string',
202
+ enum: [...CATALOG_TOPICS],
203
+ description: '可选。省略返回九行主题索引;给出 topic 返回该主题的能力目录。一次只取需要的主题,不要拉全部。',
204
+ },
205
+ }), { type: 'string' }, async (args, exec) => {
206
+ authorizedSession(ctx, exec, 'list_capabilities', DATA_COLLECTION_PRESET_IDS);
207
+ if (hub.capabilityNames().length === 0) {
208
+ throw capabilityError('capability_catalog_empty', '当前没有任何已注册的数据能力(数据源注册没有生效)。注意:缺凭据**不会**让目录变空;不要反复重试,也不要编造能力名;请用 dc_status 核对 registered_capability_count / registered_topics 与 api_key,并回告主 Agent。');
209
+ }
210
+ const topic = resolveCatalogTopic(hub, args.topic);
211
+ return topic === undefined ? hub.catalogIndex() : hub.capabilityDirectory(topic);
212
+ }, { concurrencySafe: true }),
213
+ tool('describe_capability', '读取**一个**能力的完整契约:description(单位、null 语义、时间与分页口径)、input_schema(params 的取值与约束)、output_fields(返回字段的逐行字典 `路径:类型[:说明]`,类型后缀 `?` 为可为 null、`[].` 为数组元素的字段)与 paginated。request_data 的 params 必须按这里返回的 input_schema 填写;request_data 若返回 request_params_invalid,应回到这里重新读取后再重试。一个能力描述一次即可:结果已在本 session 历史里,重复描述同一个能力只会白占上下文;需要几个能力就**在同一条消息里一次发出多个调用**(本工具是纯读、可并发执行,框架会把它们放进并发池、在同一个下一步一起返回),但一次仍只传**一个**名字,不要用逗号把多个名字塞进一条调用。错误按 code 引导:capability_required(没给名字,先 list_capabilities())、capability_invalid(不是字符串/超长/含逗号,改为目录中的单个名字)、capability_catalog_empty(数据源未注册,别重试,回告主 Agent)、capability_unknown(名字不存在,错误里回九行索引,按 topic 取分片后原样复制)。', jsonObject({ capability: { type: 'string' } }, ['capability']), jsonObject({
182
214
  capability: { type: 'string' },
183
215
  summary: { type: 'string' },
184
216
  paginated: { type: 'boolean' },
@@ -194,11 +226,16 @@ export function registerDataCollectorTools(ctx, hub, diagnostics) {
194
226
  return detail;
195
227
  }, { concurrencySafe: true }),
196
228
  ...(diagnostics ? [
197
- tool('dc_status', '诊断工具:返回数据管道运行状态 —— at/call 为本次真实执行的时间戳与计数(防伪)、api_key 为**本次调用现取**的凭据解析结果(present/source,不含密钥值)、registered_capabilities 为当前已注册 capability 列表、agent_tool_policy 为工具面收敛的现场记录(preset_id / root / outcome / allowed / denied / failed:`outcome=restricted` 是组合期那次减名字的账,`guard-denied` 是一次调用真的被调用级闸门拦下(`ocr` 的 url 形态、`write` / `edit`、角色的 `interrupt_agent`),`not-capital` / `skipped` / `unavailable` / `pending` 是四种没生效的原因;`root=true` 是用户手开出来的会话。工具面本身由该 preset 挂的工具行决定,allowed 恒为空。排查"某个 Agent 为什么看得见、或为什么用不了某颗工具"用)、session_identity 为最近的工具授权判据现场(tool / via=preset|topology / preset_id / allowed;`via:"topology"` 表示 registry 读不到身份、回落到"必须是被委派的子会话"这一旧判据)。数据源注册不依赖 key:api_key.present=false 时同花顺能力仍在目录里,但每次取数会点名 FUYAO_API_KEY 失败。排障时优先调用。', jsonObject(), jsonObject({
229
+ tool('dc_status', '诊断工具:返回数据管道运行状态 —— at/call 为本次真实执行的时间戳与计数(防伪)、api_key 为**本次调用现取**的凭据解析结果(present/source,不含密钥值)、registered_capability_count 与 registered_topics 为当前注册规模(九片 topic/label/count 汇总;**不返回全部能力名**,名字从 `list_capabilities` 分片取)、agent_tool_policy 为工具面收敛的现场记录(preset_id / root / outcome / allowed / denied / failed:`outcome=restricted` 是组合期那次减名字的账,`guard-denied` 是一次调用真的被调用级闸门拦下(`ocr` 的 url 形态、`write` / `edit`、角色的 `interrupt_agent`),`not-capital` / `skipped` / `unavailable` / `pending` 是四种没生效的原因;`root=true` 是用户手开出来的会话。工具面本身由该 preset 挂的工具行决定,allowed 恒为空。排查"某个 Agent 为什么看得见、或为什么用不了某颗工具"用)、session_identity 为最近的工具授权判据现场(tool / via=preset|topology / preset_id / allowed;`via:"topology"` 表示 registry 读不到身份、回落到"必须是被委派的子会话"这一旧判据)。数据源注册不依赖 key:api_key.present=false 时同花顺能力仍在目录里,但每次取数会点名 FUYAO_API_KEY 失败。排障时优先调用。', jsonObject(), jsonObject({
198
230
  at: { type: 'integer' },
199
231
  call: { type: 'integer' },
200
232
  api_key: jsonObject({ present: { type: 'boolean' }, source: { oneOf: [{ type: 'string' }, { type: 'null' }] }, error: { oneOf: [{ type: 'string' }, { type: 'null' }] } }, ['present']),
201
- registered_capabilities: { type: 'array', items: { type: 'string' } },
233
+ registered_capability_count: { type: 'integer' },
234
+ registered_topics: { type: 'array', items: jsonObject({
235
+ topic: { type: 'string' },
236
+ label: { type: 'string' },
237
+ count: { type: 'integer' },
238
+ }, ['topic', 'label', 'count']) },
202
239
  agent_tool_policy: { type: 'array', items: jsonObject({
203
240
  agent_id: { oneOf: [{ type: 'string' }, { type: 'null' }] },
204
241
  root: { type: 'boolean' },
@@ -214,7 +251,7 @@ export function registerDataCollectorTools(ctx, hub, diagnostics) {
214
251
  preset_id: { oneOf: [{ type: 'string' }, { type: 'null' }] },
215
252
  allowed: { type: 'boolean' },
216
253
  }, ['tool', 'via', 'preset_id', 'allowed']) },
217
- }, ['at', 'call', 'api_key', 'registered_capabilities']), async (_args, exec) => {
254
+ }, ['at', 'call', 'api_key', 'registered_capability_count', 'registered_topics']), async (_args, exec) => {
218
255
  authorizedSession(ctx, exec, 'dc_status', DATA_COLLECTION_PRESET_IDS);
219
256
  const apiKey = await diagnostics.probeApiKey();
220
257
  const capabilities = hub.capabilityNames();
@@ -233,7 +270,8 @@ export function registerDataCollectorTools(ctx, hub, diagnostics) {
233
270
  at: snapshot.at,
234
271
  call: snapshot.call,
235
272
  api_key: apiKey,
236
- registered_capabilities: capabilities,
273
+ registered_capability_count: capabilities.length,
274
+ registered_topics: hub.catalogTopicEntries().map(({ topic, label, count }) => ({ topic, label, count })),
237
275
  ...(agentToolPolicy === undefined ? {} : { agent_tool_policy: agentToolPolicy }),
238
276
  // Authorization decision trail: preset identity vs fallback to session topology; without
239
277
  // it, "identity unavailable" and "identity confirmed" look identical to the model.
@@ -0,0 +1,11 @@
1
+ export interface PythonEnvOptions {
2
+ pythonDir: string;
3
+ homeDir: string;
4
+ tempDir: string;
5
+ baseEnv?: Record<string, string | undefined>;
6
+ }
7
+ /**
8
+ * Minimal environment for the private interpreter. `-I` already ignores PYTHON* variables; this
9
+ * also removes native-loader variables and keeps the child from reading the user's home/config.
10
+ */
11
+ export declare function pythonChildEnv(options: PythonEnvOptions): Record<string, string>;
@@ -0,0 +1,39 @@
1
+ import { delimiter } from 'node:path';
2
+ import { minimalSystemPath } from './platform.js';
3
+ const REMOVE = [
4
+ 'PYTHONPATH',
5
+ 'PYTHONHOME',
6
+ 'PYTHONSTARTUP',
7
+ 'PYTHONEXECUTABLE',
8
+ 'PYTHONUSERBASE',
9
+ 'NODE_OPTIONS',
10
+ ];
11
+ const REMOVE_PREFIX = ['PIP_', 'LD_', 'DYLD_'];
12
+ /**
13
+ * Minimal environment for the private interpreter. `-I` already ignores PYTHON* variables; this
14
+ * also removes native-loader variables and keeps the child from reading the user's home/config.
15
+ */
16
+ export function pythonChildEnv(options) {
17
+ const base = options.baseEnv ?? process.env;
18
+ const env = {};
19
+ for (const [key, value] of Object.entries(base)) {
20
+ if (value === undefined)
21
+ continue;
22
+ if (REMOVE.includes(key) || REMOVE_PREFIX.some((prefix) => key.startsWith(prefix)))
23
+ continue;
24
+ if (key === 'PATH' || key === 'Path')
25
+ continue;
26
+ env[key] = value;
27
+ }
28
+ env.PATH = [options.pythonDir, minimalSystemPath(base)].join(delimiter);
29
+ env.HOME = options.homeDir;
30
+ env.USERPROFILE = options.homeDir;
31
+ env.TMPDIR = options.tempDir;
32
+ env.TEMP = options.tempDir;
33
+ env.TMP = options.tempDir;
34
+ env.PYTHONUTF8 = '1';
35
+ env.PYTHONIOENCODING = 'utf-8';
36
+ env.PYTHONNOUSERSITE = '1';
37
+ env.PYTHONDONTWRITEBYTECODE = '1';
38
+ return env;
39
+ }
@@ -0,0 +1,8 @@
1
+ export type PythonRuntimeErrorCode = 'unsupported-platform' | 'manifest-invalid' | 'runtime-not-ready' | 'runtime-locked' | 'pnpm-missing' | 'network' | 'not-found' | 'disk-space' | 'permission' | 'probe-failed' | 'timeout' | 'cancelled' | 'pack-invalid' | 'busy' | 'invalid-request' | 'unknown';
2
+ export declare class PythonRuntimeError extends Error {
3
+ readonly code: PythonRuntimeErrorCode;
4
+ readonly diagnostics?: string;
5
+ constructor(code: PythonRuntimeErrorCode, message?: string, diagnostics?: string);
6
+ }
7
+ export declare function isPythonRuntimeError(value: unknown): value is PythonRuntimeError;
8
+ export declare function messageOf(value: unknown): string;
@@ -0,0 +1,34 @@
1
+ const MESSAGES = {
2
+ 'unsupported-platform': '当前平台不在 Python 运行时的支持矩阵内。',
3
+ 'manifest-invalid': 'Python 运行时 manifest 不可读或字段不合法。',
4
+ 'runtime-not-ready': '分析环境尚未准备;请先在设置页准备,或运行 python-runtime CLI。',
5
+ 'runtime-locked': '另一个进程正在安装 Python 运行时,请稍后重试。',
6
+ 'pnpm-missing': '找不到可用的 pnpm;DSH 的包管理器不可用,无法自动安装运行时。',
7
+ 'network': '无法连接 npm registry;请检查网络/代理,或使用离线运行时包。',
8
+ 'not-found': '运行时包版本不存在,或当前镜像尚未同步。',
9
+ 'disk-space': '磁盘空间不足,无法安装 Python 运行时。',
10
+ 'permission': '没有权限写入或执行 Python 运行时缓存目录。',
11
+ 'probe-failed': 'Python 运行时自检失败。',
12
+ timeout: 'Python 运行时操作超时。',
13
+ cancelled: 'Python 运行时操作已取消。',
14
+ 'pack-invalid': '运行时包内容与 manifest 不一致。',
15
+ busy: '已有另一个 Python 运行时任务在进行。',
16
+ 'invalid-request': 'Python 运行时请求不合法。',
17
+ unknown: 'Python 运行时操作失败。',
18
+ };
19
+ export class PythonRuntimeError extends Error {
20
+ code;
21
+ diagnostics;
22
+ constructor(code, message, diagnostics) {
23
+ super(message ?? MESSAGES[code]);
24
+ this.name = 'PythonRuntimeError';
25
+ this.code = code;
26
+ this.diagnostics = diagnostics;
27
+ }
28
+ }
29
+ export function isPythonRuntimeError(value) {
30
+ return value instanceof PythonRuntimeError;
31
+ }
32
+ export function messageOf(value) {
33
+ return value instanceof Error ? value.message : String(value);
34
+ }
@@ -0,0 +1,11 @@
1
+ export interface InstallLockOptions {
2
+ timeoutMs?: number;
3
+ staleMs?: number;
4
+ heartbeatMs?: number;
5
+ }
6
+ /**
7
+ * Cross-process install lock for one pack target. The directory itself is the lock; the
8
+ * heartbeat keeps a long download from looking stale, and a crashed owner expires by mtime.
9
+ */
10
+ export declare function withInstallLock<T>(lockPath: string, fn: () => Promise<T>, options?: InstallLockOptions): Promise<T>;
11
+ export declare function readLockOwner(lockPath: string): Promise<string | undefined>;
@@ -0,0 +1,68 @@
1
+ import { mkdir, readFile, rm, stat, utimes, writeFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { PythonRuntimeError } from './errors.js';
5
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
6
+ /**
7
+ * Cross-process install lock for one pack target. The directory itself is the lock; the
8
+ * heartbeat keeps a long download from looking stale, and a crashed owner expires by mtime.
9
+ */
10
+ export async function withInstallLock(lockPath, fn, options = {}) {
11
+ const timeoutMs = options.timeoutMs ?? 15_000;
12
+ const staleMs = options.staleMs ?? 120_000;
13
+ const heartbeatMs = options.heartbeatMs ?? 20_000;
14
+ const started = Date.now();
15
+ for (;;) {
16
+ try {
17
+ await mkdir(lockPath, { recursive: false });
18
+ break;
19
+ }
20
+ catch (error) {
21
+ const code = error.code;
22
+ if (code !== 'EEXIST')
23
+ throw new PythonRuntimeError('permission', `无法创建运行时安装锁:${lockPath}`, String(error));
24
+ try {
25
+ const info = await stat(lockPath);
26
+ if (Date.now() - info.mtimeMs > staleMs) {
27
+ await rm(lockPath, { recursive: true, force: true });
28
+ continue;
29
+ }
30
+ }
31
+ catch {
32
+ // The owner released it between the mkdir failure and stat; retry immediately.
33
+ continue;
34
+ }
35
+ if (Date.now() - started > timeoutMs) {
36
+ throw new PythonRuntimeError('runtime-locked', `等待运行时安装锁超时:${lockPath}`);
37
+ }
38
+ await sleep(250);
39
+ }
40
+ }
41
+ const ownerPath = join(lockPath, 'owner.json');
42
+ try {
43
+ await writeFile(ownerPath, JSON.stringify({ pid: process.pid, id: randomUUID(), at: new Date().toISOString() }), 'utf8');
44
+ }
45
+ catch {
46
+ // The directory lock is authoritative; owner metadata is diagnostic only.
47
+ }
48
+ const heartbeat = setInterval(() => {
49
+ const now = new Date();
50
+ void utimes(lockPath, now, now).catch(() => undefined);
51
+ }, heartbeatMs);
52
+ heartbeat.unref?.();
53
+ try {
54
+ return await fn();
55
+ }
56
+ finally {
57
+ clearInterval(heartbeat);
58
+ await rm(lockPath, { recursive: true, force: true }).catch(() => undefined);
59
+ }
60
+ }
61
+ export async function readLockOwner(lockPath) {
62
+ try {
63
+ return await readFile(join(lockPath, 'owner.json'), 'utf8');
64
+ }
65
+ catch {
66
+ return undefined;
67
+ }
68
+ }
@@ -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 {};