@v587d/capital-generation 2.30.1 → 2.31.1
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 +127 -0
- package/README.md +4 -4
- package/THIRD_PARTY_NOTICES.md +1 -0
- package/automation/package.json +1 -1
- package/automation/storage.js +4 -0
- package/chart-ui/package.json +1 -1
- package/config/client.js +1 -1
- package/config/package.json +1 -1
- package/lib/agents/messaging-policy.d.ts +23 -6
- package/lib/agents/messaging-policy.js +64 -9
- package/lib/agents/role-tool-policy.d.ts +3 -0
- package/lib/agents/role-tool-policy.js +15 -5
- package/lib/agents/selected-skills-provider.d.ts +1 -1
- package/lib/agents/selected-skills-provider.js +3 -1
- package/lib/analysis/registry.d.ts +12 -0
- package/lib/analysis/registry.js +76 -0
- package/lib/analysis/runtime.d.ts +87 -0
- package/lib/analysis/runtime.js +225 -0
- package/lib/analysis/schemas.d.ts +58 -0
- package/lib/analysis/schemas.js +276 -0
- package/lib/analysis/snapshot.d.ts +102 -0
- package/lib/analysis/snapshot.js +266 -0
- package/lib/analysis/storage.d.ts +64 -0
- package/lib/analysis/storage.js +96 -0
- package/lib/analysis/tools.d.ts +17 -0
- package/lib/analysis/tools.js +357 -0
- package/lib/analysis/types.d.ts +201 -0
- package/lib/analysis/types.js +44 -0
- package/lib/analysis/validation.d.ts +44 -0
- package/lib/analysis/validation.js +381 -0
- package/lib/analysis-entry.d.ts +10 -0
- package/lib/analysis-entry.js +7 -0
- package/lib/data-collector/store.d.ts +14 -1
- package/lib/data-collector/store.js +47 -1
- package/lib/data-contract.d.ts +3 -2
- package/lib/data-contract.js +18 -2
- package/lib/preset-ids.d.ts +5 -0
- package/lib/preset-ids.js +7 -1
- package/lib/python-runtime/errors.d.ts +7 -1
- package/lib/python-runtime/errors.js +9 -1
- package/lib/python-runtime/manager.d.ts +30 -0
- package/lib/python-runtime/manager.js +88 -0
- package/lib/python-runtime/probe.js +5 -1
- package/lib/selected-skills-entry.js +1 -1
- package/lib/web-retriever/local-fetch.d.ts +1 -1
- package/lib/web-retriever/local-fetch.js +1 -1
- package/lib/web-retriever/wind-client.d.ts +1 -1
- package/lib/web-retriever/wind-client.js +1 -1
- package/package.json +6 -1
- package/preset/capital-generation/README.md +5 -6
- package/preset/capital-generation/agent.patch.yml +54 -65
- package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +99 -0
- package/preset/capital-generation/skills/capital-analysis-synthesis/SKILL.md +110 -0
- package/preset/capital-generation/skills/capital-analysis-validation/SKILL.md +96 -0
- package/preset/capital-generation/skills/capital-data-query/SKILL.md +1 -1
- package/preset/capital-generation/skills/capital-equity-research/SKILL.md +1 -1
- package/preset/capital-generation/skills/capital-event-impact/SKILL.md +1 -1
- package/preset/capital-generation/skills/capital-orchestration/SKILL.md +32 -27
- package/preset/capital-generation/skills/capital-portfolio-review/SKILL.md +1 -1
- package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +105 -0
- package/python/analysis/modules/financial_quality/LICENSE +27 -0
- package/python/analysis/modules/financial_quality/module.json +65 -0
- package/python/analysis/modules/financial_quality/module.py +535 -0
- package/python/analysis/modules/hello/LICENSE +21 -0
- package/python/analysis/modules/hello/module.json +46 -0
- package/python/analysis/modules/hello/module.py +56 -0
- package/python/worker.py +152 -5
- package/selected-skills/routing.js +5 -2
- package/watchlist/package.json +1 -1
package/config/package.json
CHANGED
|
@@ -1,21 +1,38 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Call-level `send_message` target guard.
|
|
3
|
-
* each other;
|
|
4
|
-
*
|
|
5
|
-
*
|
|
2
|
+
* Call-level `send_message` target guard. The host lets any two members of one subagent tree message
|
|
3
|
+
* each other; this plugin keeps the adjacency table from design §5.2: root -> direct child only,
|
|
4
|
+
* peer edges only where listed, specialist -> none. Targets match fixed tree names because the guard
|
|
5
|
+
* is synchronous and sees raw strings only (a session id is shaped like a name), so this is routing
|
|
6
|
+
* discipline, not a security boundary. Non-Capital presets fail open.
|
|
7
|
+
*
|
|
8
|
+
* The analyst's outgoing peer sends also carry the §5.6 round-trip budget: the send edge stops the
|
|
9
|
+
* fourth request, and `validateArtifact` re-checks the recorded exchanges per `task_id`.
|
|
6
10
|
*/
|
|
7
11
|
import type { GuardedExecution, PolicyContext } from './root-tool-policy.js';
|
|
8
12
|
export declare const MESSAGE_TOOL_NAME = "send_message";
|
|
13
|
+
/** Fixed tree names from the delegation prompt; peer edges match these strings, never session ids. */
|
|
14
|
+
export declare const ROLE_TREE_NAMES: {
|
|
15
|
+
readonly collector: "data-collector";
|
|
16
|
+
readonly junior: "data-junior";
|
|
17
|
+
readonly retriever: "web-retriever";
|
|
18
|
+
readonly specialist: "visualization-specialist";
|
|
19
|
+
readonly analyst: "senior-analyst";
|
|
20
|
+
readonly lead: "lead";
|
|
21
|
+
};
|
|
9
22
|
export declare const ROOT_MESSAGE_DENIED: string;
|
|
10
23
|
export declare const LEAF_MESSAGE_DENIED = "send_message \u53EA\u80FD\u53D1\u7ED9 `lead`\uFF1A\u53F6\u5B50\u89D2\u8272\u4E0D\u76F4\u63A5\u627E\u5144\u5F1F\u6216\u5B59 Agent\uFF0C\u6750\u6599\u4E0E\u8BF7\u6C42\u90FD\u7ECF\u4E3B Agent \u4E2D\u7EE7\u3002";
|
|
11
24
|
export declare const SPECIALIST_MESSAGE_DENIED = "visualization_specialist \u4E0D\u76F4\u63A5\u53D1\u6D88\u606F\uFF1A\u628A\u56FE\u8868\u7ED3\u679C\u4F5C\u4E3A\u6700\u7EC8\u7B54\u590D\u8FD4\u56DE data_junior\uFF0C\u7531\u5B83\u6C47\u603B\u3002";
|
|
12
|
-
/** Allowed
|
|
25
|
+
/** Allowed send edges per role preset. Empty means no messaging at all. Extending one is a product decision. */
|
|
13
26
|
export declare const ROLE_MESSAGE_TARGETS: Readonly<Record<string, readonly string[]>>;
|
|
27
|
+
/** §5.6-2 budget: one analysis task may ask its peer at most three times. */
|
|
28
|
+
export declare const PEER_ROUND_TRIP_BUDGET = 3;
|
|
29
|
+
export declare const PEER_BUDGET_DENIED: string;
|
|
30
|
+
export declare function peerSendCount(sessionId: string): number;
|
|
14
31
|
/** The host owns the required-field error; the guard only judges a target it can actually read. */
|
|
15
32
|
export declare function sendMessageTargetOf(exec: GuardedExecution | undefined): string | undefined;
|
|
16
33
|
/** Root may address a direct child only: no tree path, and never itself. */
|
|
17
34
|
export declare function isDirectChildName(name: string): boolean;
|
|
18
35
|
/** Read identity per call because a created-time gate misses manually opened modes; fail open otherwise. */
|
|
19
36
|
export declare function sendMessageGuardReasonFor(ctx: PolicyContext): (exec: GuardedExecution | undefined) => string | undefined;
|
|
20
|
-
/**
|
|
37
|
+
/** Install globally once; a created-time gate misses manually opened modes. */
|
|
21
38
|
export declare function registerSendMessageGuard(ctx: PolicyContext): void;
|
|
@@ -1,19 +1,52 @@
|
|
|
1
|
-
import { recordGuardDecision } from './root-tool-policy.js';
|
|
1
|
+
import { agentSessionId, recordGuardDecision } from './root-tool-policy.js';
|
|
2
2
|
import { readPresetClaim } from '../preset-claim.js';
|
|
3
3
|
import { CAPITAL_PRESET_IDS, ROLE_PRESET_IDS, ROOT_PRESET_ID } from '../preset-ids.js';
|
|
4
4
|
export const MESSAGE_TOOL_NAME = 'send_message';
|
|
5
|
+
const LEAD_NAME = 'lead';
|
|
6
|
+
/** Fixed tree names from the delegation prompt; peer edges match these strings, never session ids. */
|
|
7
|
+
export const ROLE_TREE_NAMES = {
|
|
8
|
+
collector: 'data-collector',
|
|
9
|
+
junior: 'data-junior',
|
|
10
|
+
retriever: 'web-retriever',
|
|
11
|
+
specialist: 'visualization-specialist',
|
|
12
|
+
analyst: 'senior-analyst',
|
|
13
|
+
lead: LEAD_NAME,
|
|
14
|
+
};
|
|
5
15
|
export const ROOT_MESSAGE_DENIED = 'send_message 只能发给你的直系子 Agent:目标名不能是 `lead`,也不能含 `/`(孙 Agent 走 data_junior 中继)。'
|
|
6
16
|
+ '重新调用 list_agents() 取直系 name 后再发。';
|
|
7
17
|
export const LEAF_MESSAGE_DENIED = 'send_message 只能发给 `lead`:叶子角色不直接找兄弟或孙 Agent,材料与请求都经主 Agent 中继。';
|
|
8
18
|
export const SPECIALIST_MESSAGE_DENIED = 'visualization_specialist 不直接发消息:把图表结果作为最终答复返回 data_junior,由它汇总。';
|
|
9
|
-
/** Allowed
|
|
19
|
+
/** Allowed send edges per role preset. Empty means no messaging at all. Extending one is a product decision. */
|
|
10
20
|
export const ROLE_MESSAGE_TARGETS = {
|
|
11
|
-
[ROLE_PRESET_IDS.collector]: [
|
|
12
|
-
[ROLE_PRESET_IDS.junior]: [
|
|
13
|
-
[ROLE_PRESET_IDS.retriever]: [
|
|
21
|
+
[ROLE_PRESET_IDS.collector]: [ROLE_TREE_NAMES.junior, ROLE_TREE_NAMES.analyst, LEAD_NAME],
|
|
22
|
+
[ROLE_PRESET_IDS.junior]: [ROLE_TREE_NAMES.analyst, LEAD_NAME],
|
|
23
|
+
[ROLE_PRESET_IDS.retriever]: [ROLE_TREE_NAMES.analyst, LEAD_NAME],
|
|
14
24
|
[ROLE_PRESET_IDS.specialist]: [],
|
|
15
|
-
[ROLE_PRESET_IDS.analyst]: [
|
|
25
|
+
[ROLE_PRESET_IDS.analyst]: [ROLE_TREE_NAMES.junior, LEAD_NAME],
|
|
26
|
+
};
|
|
27
|
+
/** Per-role denial copy; the range gate (new data via lead) belongs in the message, not only in docs. */
|
|
28
|
+
const ROLE_MESSAGE_DENIED = {
|
|
29
|
+
[ROLE_PRESET_IDS.collector]: 'send_message 只能发给 lead、data-junior 或 senior-analyst:DatasetRef 可直达材料消费者,'
|
|
30
|
+
+ '新数据请求仍经 lead。',
|
|
31
|
+
[ROLE_PRESET_IDS.junior]: 'send_message 只能发给 lead 或 senior-analyst:补计算结果可直发 senior,其他兄弟与孙 Agent 经 lead。',
|
|
32
|
+
[ROLE_PRESET_IDS.retriever]: 'send_message 只能发给 lead 或 senior-analyst:带来源的证据可直发 senior,其他目标经 lead。',
|
|
33
|
+
[ROLE_PRESET_IDS.analyst]: 'send_message 只能发给 lead 或 data-junior:新数据/新检索经 lead,'
|
|
34
|
+
+ '只有"用已有 Dataset/profile 补计算"可直连 data-junior。',
|
|
16
35
|
};
|
|
36
|
+
/** §5.6-2 budget: one analysis task may ask its peer at most three times. */
|
|
37
|
+
export const PEER_ROUND_TRIP_BUDGET = 3;
|
|
38
|
+
export const PEER_BUDGET_DENIED = `补计算往返已达 ${PEER_ROUND_TRIP_BUDGET} 次上限:不要再向同行发请求,`
|
|
39
|
+
+ '改用 analysis_blocked + peer_budget_exhausted 把未决缺口回给 lead 裁决。';
|
|
40
|
+
const PEER_SEND_BUDGET = {
|
|
41
|
+
[ROLE_PRESET_IDS.analyst]: PEER_ROUND_TRIP_BUDGET,
|
|
42
|
+
};
|
|
43
|
+
/** Outgoing peer sends per sender session. One senior session carries one analysis task. */
|
|
44
|
+
const peerSends = new Map();
|
|
45
|
+
/** Bounded bookkeeping: leak-free enough without a session lifecycle hook. */
|
|
46
|
+
const PEER_SEND_TRACK_MAX = 256;
|
|
47
|
+
export function peerSendCount(sessionId) {
|
|
48
|
+
return peerSends.get(sessionId) ?? 0;
|
|
49
|
+
}
|
|
17
50
|
function isRecord(value) {
|
|
18
51
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
19
52
|
}
|
|
@@ -27,7 +60,27 @@ export function sendMessageTargetOf(exec) {
|
|
|
27
60
|
}
|
|
28
61
|
/** Root may address a direct child only: no tree path, and never itself. */
|
|
29
62
|
export function isDirectChildName(name) {
|
|
30
|
-
return name !==
|
|
63
|
+
return name !== LEAD_NAME && !name.includes('/');
|
|
64
|
+
}
|
|
65
|
+
/** Counts the send once it passes the edge check; the artifact check is the authoritative record. */
|
|
66
|
+
function peerBudgetReason(role, target, exec) {
|
|
67
|
+
const budget = PEER_SEND_BUDGET[role];
|
|
68
|
+
if (budget === undefined || target === LEAD_NAME)
|
|
69
|
+
return undefined;
|
|
70
|
+
const sessionId = agentSessionId(exec?.agent);
|
|
71
|
+
// No session pull (old host shape / unit call): leave counting to the artifact check.
|
|
72
|
+
if (sessionId === undefined)
|
|
73
|
+
return undefined;
|
|
74
|
+
const used = peerSends.get(sessionId) ?? 0;
|
|
75
|
+
if (used >= budget)
|
|
76
|
+
return PEER_BUDGET_DENIED;
|
|
77
|
+
peerSends.set(sessionId, used + 1);
|
|
78
|
+
if (peerSends.size > PEER_SEND_TRACK_MAX) {
|
|
79
|
+
const oldest = peerSends.keys().next().value;
|
|
80
|
+
if (typeof oldest === 'string')
|
|
81
|
+
peerSends.delete(oldest);
|
|
82
|
+
}
|
|
83
|
+
return undefined;
|
|
31
84
|
}
|
|
32
85
|
/** Read identity per call because a created-time gate misses manually opened modes; fail open otherwise. */
|
|
33
86
|
export function sendMessageGuardReasonFor(ctx) {
|
|
@@ -46,11 +99,13 @@ export function sendMessageGuardReasonFor(ctx) {
|
|
|
46
99
|
const allowed = ROLE_MESSAGE_TARGETS[claim.claim] ?? [];
|
|
47
100
|
if (allowed.length === 0)
|
|
48
101
|
return SPECIALIST_MESSAGE_DENIED;
|
|
49
|
-
|
|
102
|
+
if (!allowed.includes(target))
|
|
103
|
+
return ROLE_MESSAGE_DENIED[claim.claim] ?? LEAF_MESSAGE_DENIED;
|
|
104
|
+
return peerBudgetReason(claim.claim, target, exec);
|
|
50
105
|
};
|
|
51
106
|
}
|
|
52
107
|
const installedGuardRoots = new WeakSet();
|
|
53
|
-
/**
|
|
108
|
+
/** Install globally once; a created-time gate misses manually opened modes. */
|
|
54
109
|
export function registerSendMessageGuard(ctx) {
|
|
55
110
|
const ref = ctx.root ?? ctx;
|
|
56
111
|
if (installedGuardRoots.has(ref))
|
|
@@ -9,6 +9,9 @@ export { ROLE_PRESET_IDS, ROLE_PRESET_ID_LIST, type RolePresetId } from '../pres
|
|
|
9
9
|
/** Registered together with `send_message` by `tool-subagent-control`; no host switch, so leaf roles deny these by name.
|
|
10
10
|
* 0.2.2 moved `list_agents` into the same main entry, so the welded set grew from one to two names. */
|
|
11
11
|
export declare const SIBLING_DENIED_TOOLS: readonly ["interrupt_agent", "list_agents"];
|
|
12
|
+
/** Welded in by the same row, but only the analyst denies it: it is a leaf with nothing to wait on,
|
|
13
|
+
* while data-junior's chart barrier needs `wait_agent` (design §5.5 — do not widen this to the shared set). */
|
|
14
|
+
export declare const ANALYST_DENIED_TOOLS: readonly ["wait_agent"];
|
|
12
15
|
/** Full intended surface; only names that resolve as host-global are enforced by the allow-list.
|
|
13
16
|
* Scoped family-row tools stay visible regardless; they must remain in this list for review. */
|
|
14
17
|
export declare const COLLECTOR_ROLE_TOOLS: readonly ["send_message", "skill", "get_local_datetime", "resolve_data_time_range", "request_data", "list_capabilities", "describe_capability", "dc_status"];
|
|
@@ -10,6 +10,9 @@ export { ROLE_PRESET_IDS, ROLE_PRESET_ID_LIST } from '../preset-ids.js';
|
|
|
10
10
|
/** Registered together with `send_message` by `tool-subagent-control`; no host switch, so leaf roles deny these by name.
|
|
11
11
|
* 0.2.2 moved `list_agents` into the same main entry, so the welded set grew from one to two names. */
|
|
12
12
|
export const SIBLING_DENIED_TOOLS = ['interrupt_agent', 'list_agents'];
|
|
13
|
+
/** Welded in by the same row, but only the analyst denies it: it is a leaf with nothing to wait on,
|
|
14
|
+
* while data-junior's chart barrier needs `wait_agent` (design §5.5 — do not widen this to the shared set). */
|
|
15
|
+
export const ANALYST_DENIED_TOOLS = ['wait_agent'];
|
|
13
16
|
/** Shared leaf capabilities that are host-global in rc.2, not preset-scoped. */
|
|
14
17
|
const ROLE_MESSAGING_TOOLS = ['send_message', 'skill'];
|
|
15
18
|
const ROLE_TIME_TOOLS = ['get_local_datetime', 'resolve_data_time_range'];
|
|
@@ -36,7 +39,7 @@ export const ROLE_TOOL_SURFACES = {
|
|
|
36
39
|
[ROLE_PRESET_IDS.junior]: { denySiblings: SIBLING_DENIED_TOOLS, ...DENY_TEAM },
|
|
37
40
|
[ROLE_PRESET_IDS.retriever]: { allowTools: RETRIEVER_ROLE_TOOLS, denySiblings: SIBLING_DENIED_TOOLS, ...DENY_TEAM },
|
|
38
41
|
[ROLE_PRESET_IDS.specialist]: { allowTools: SPECIALIST_ROLE_TOOLS, ...DENY_TEAM },
|
|
39
|
-
[ROLE_PRESET_IDS.analyst]: { denySiblings: SIBLING_DENIED_TOOLS, ...DENY_TEAM },
|
|
42
|
+
[ROLE_PRESET_IDS.analyst]: { denySiblings: [...SIBLING_DENIED_TOOLS, ...ANALYST_DENIED_TOOLS], ...DENY_TEAM },
|
|
40
43
|
};
|
|
41
44
|
/** Role preset id only, undefined for root and other presets; failure means "do not converge". */
|
|
42
45
|
export function rolePresetIdOf(ctx, agent) {
|
|
@@ -125,18 +128,25 @@ export function restrictRoleAgentTools(agent, surface) {
|
|
|
125
128
|
export function roleSiblingGuardReasonFor(ctx) {
|
|
126
129
|
return (exec) => {
|
|
127
130
|
const name = exec?.name;
|
|
128
|
-
if (typeof name !== 'string'
|
|
131
|
+
if (typeof name !== 'string')
|
|
129
132
|
return undefined;
|
|
130
133
|
const claim = readPresetClaim(ctx, exec?.agent);
|
|
131
134
|
if (claim.registryMissing || claim.failed || claim.claim === undefined)
|
|
132
135
|
return undefined;
|
|
133
136
|
if (!ROLE_PRESET_ID_LIST.includes(claim.claim))
|
|
134
137
|
return undefined;
|
|
138
|
+
const denied = [...SIBLING_DENIED_TOOLS, ...(claim.claim === ROLE_PRESET_IDS.analyst ? ANALYST_DENIED_TOOLS : [])];
|
|
139
|
+
if (!denied.includes(name))
|
|
140
|
+
return undefined;
|
|
141
|
+
if (name === 'wait_agent') {
|
|
142
|
+
return `${name} 不对人设 ${claim.claim} 开放:叶子角色没有子 Agent 可等,结果直接回传主 Agent;`
|
|
143
|
+
+ '等待归主 Agent 的 wait_for_agents 负责。';
|
|
144
|
+
}
|
|
135
145
|
if (name === 'list_agents') {
|
|
136
|
-
return `${name} 不对人设 ${claim.claim}
|
|
137
|
-
+ '
|
|
146
|
+
return `${name} 不对人设 ${claim.claim} 开放:子 Agent 名单与调度归主 Agent;peer 边只认固定树名,`
|
|
147
|
+
+ '按邻接表直接 send_message。需要别的 Agent 配合,不要自己换工具硬做。';
|
|
138
148
|
}
|
|
139
|
-
return `${name} 不对人设 ${claim.claim}
|
|
149
|
+
return `${name} 不对人设 ${claim.claim} 开放:打断别的会话归主 Agent 决定(peer 之间也不许)。`
|
|
140
150
|
+ '需要别的 Agent 停下来,用 send_message 回告主 Agent;不要自己换工具硬做。';
|
|
141
151
|
};
|
|
142
152
|
}
|
|
@@ -16,7 +16,7 @@ export type SelectedSkillCatalogEntry = {
|
|
|
16
16
|
};
|
|
17
17
|
export declare const SELECTED_SKILL_CATALOG: readonly SelectedSkillCatalogEntry[];
|
|
18
18
|
/** Roles a preset row may declare. data_collector / visualization have no method set. */
|
|
19
|
-
export declare const SELECTED_SKILL_ENTRY_ROLES: readonly ["main", "data_junior", "web_retriever", "data_analyst", "data_collector", "visualization_specialist"];
|
|
19
|
+
export declare const SELECTED_SKILL_ENTRY_ROLES: readonly ["main", "data_junior", "web_retriever", "senior_analyst", "data_analyst", "data_collector", "visualization_specialist"];
|
|
20
20
|
export type SelectedSkillRole = typeof SELECTED_SKILL_ENTRY_ROLES[number];
|
|
21
21
|
export type SelectedSkillSelection = Partial<Record<string, boolean>>;
|
|
22
22
|
export type SelectedSkillSelectionSource = SelectedSkillSelection | (() => SelectedSkillSelection);
|
|
@@ -13,7 +13,7 @@ import { SELECTED_SKILL_ROLES, SELECTED_SKILL_ROUTING as ROUTING, selectedSkillN
|
|
|
13
13
|
export const SELECTED_SKILL_CATALOG = CATALOG;
|
|
14
14
|
/** Roles a preset row may declare. data_collector / visualization have no method set. */
|
|
15
15
|
export const SELECTED_SKILL_ENTRY_ROLES = [
|
|
16
|
-
'main', 'data_junior', 'web_retriever', 'data_analyst', 'data_collector', 'visualization_specialist',
|
|
16
|
+
'main', 'data_junior', 'web_retriever', 'senior_analyst', 'data_analyst', 'data_collector', 'visualization_specialist',
|
|
17
17
|
];
|
|
18
18
|
const ROUTING_BY_NAME = ROUTING;
|
|
19
19
|
const PROVIDER_NAME = 'capital-selected-skills';
|
|
@@ -27,6 +27,8 @@ const ROLE_PRESET = {
|
|
|
27
27
|
main: ROOT_PRESET_ID,
|
|
28
28
|
data_junior: ROLE_PRESET_IDS.junior,
|
|
29
29
|
web_retriever: ROLE_PRESET_IDS.retriever,
|
|
30
|
+
senior_analyst: ROLE_PRESET_IDS.analyst,
|
|
31
|
+
/** Legacy key: presets written before 2026-11-24 name the same role. */
|
|
30
32
|
data_analyst: ROLE_PRESET_IDS.analyst,
|
|
31
33
|
data_collector: ROLE_PRESET_IDS.collector,
|
|
32
34
|
visualization_specialist: ROLE_PRESET_IDS.specialist,
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { ModuleManifest } from './types.js';
|
|
2
|
+
export interface AnalysisModuleEntry {
|
|
3
|
+
readonly manifest: ModuleManifest;
|
|
4
|
+
/** Absolute directory handed to the worker; always inside the package. */
|
|
5
|
+
readonly dir: string;
|
|
6
|
+
readonly entrypoint: string;
|
|
7
|
+
}
|
|
8
|
+
/** Registered modules, manifest-normalized. Throws when a registered module cannot be read. */
|
|
9
|
+
export declare function listAnalysisModules(): readonly AnalysisModuleEntry[];
|
|
10
|
+
export declare function analysisModuleById(moduleId: string): AnalysisModuleEntry | undefined;
|
|
11
|
+
/** Test-only: drop the manifest cache so a fixture rewrite is visible. */
|
|
12
|
+
export declare function resetAnalysisModuleCache(): void;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Static analysis-module registry: the whitelist and the version facts, nothing else.
|
|
3
|
+
*
|
|
4
|
+
* Modules are never discovered by scanning a directory — a directory scan would turn "drop a file in
|
|
5
|
+
* the package" into "run arbitrary code under the private interpreter". `module.json` is the single
|
|
6
|
+
* manifest source; the entry only adds the resolved directory the worker gets.
|
|
7
|
+
*/
|
|
8
|
+
import { readFileSync } from 'node:fs';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
import { MODULE_DEFAULT_LIMITS } from './schemas.js';
|
|
12
|
+
const MODULE_ROOT = fileURLToPath(new URL('../../python/analysis/modules/', import.meta.url));
|
|
13
|
+
/** Registered ids, in listing order. Adding a module means adding its id here. */
|
|
14
|
+
const REGISTERED_MODULE_IDS = ['hello', 'financial_quality'];
|
|
15
|
+
const cache = new Map();
|
|
16
|
+
function readManifest(moduleId) {
|
|
17
|
+
const cached = cache.get(moduleId);
|
|
18
|
+
if (cached !== undefined)
|
|
19
|
+
return cached;
|
|
20
|
+
const dir = join(MODULE_ROOT, moduleId);
|
|
21
|
+
let parsed;
|
|
22
|
+
try {
|
|
23
|
+
parsed = JSON.parse(readFileSync(join(dir, 'module.json'), 'utf8'));
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
throw new Error(`分析模块 ${moduleId} 的 module.json 读不到(${error instanceof Error ? error.message : String(error)})`);
|
|
27
|
+
}
|
|
28
|
+
const manifest = normalizeManifest(parsed, moduleId);
|
|
29
|
+
const entry = { manifest, dir, entrypoint: manifest.entrypoint };
|
|
30
|
+
cache.set(moduleId, entry);
|
|
31
|
+
return entry;
|
|
32
|
+
}
|
|
33
|
+
function normalizeManifest(value, moduleId) {
|
|
34
|
+
const raw = value;
|
|
35
|
+
if (typeof raw !== 'object' || raw === null || raw.id !== moduleId) {
|
|
36
|
+
throw new Error(`分析模块 ${moduleId} 的 manifest 缺失或 id 不符`);
|
|
37
|
+
}
|
|
38
|
+
if (typeof raw.version !== 'string' || typeof raw.description !== 'string' || typeof raw.entrypoint !== 'string') {
|
|
39
|
+
throw new Error(`分析模块 ${moduleId} 的 manifest 缺少 version / description / entrypoint`);
|
|
40
|
+
}
|
|
41
|
+
if (!Array.isArray(raw.roles) || raw.roles.length === 0) {
|
|
42
|
+
throw new Error(`分析模块 ${moduleId} 的 manifest 必须声明 roles(语义键,如 senior_analyst)`);
|
|
43
|
+
}
|
|
44
|
+
if (!Array.isArray(raw.capabilities))
|
|
45
|
+
throw new Error(`分析模块 ${moduleId} 的 manifest 缺少 capabilities`);
|
|
46
|
+
const limits = { ...MODULE_DEFAULT_LIMITS, ...(raw.limits ?? {}) };
|
|
47
|
+
return {
|
|
48
|
+
id: moduleId,
|
|
49
|
+
version: raw.version,
|
|
50
|
+
entrypoint: raw.entrypoint,
|
|
51
|
+
runtime: 'python',
|
|
52
|
+
description: raw.description,
|
|
53
|
+
roles: [...raw.roles],
|
|
54
|
+
capabilities: [...raw.capabilities],
|
|
55
|
+
required_fields: [...(raw.required_fields ?? [])],
|
|
56
|
+
input_schema: raw.input_schema ?? {},
|
|
57
|
+
output_schema: raw.output_schema ?? {},
|
|
58
|
+
assumptions: [...(raw.assumptions ?? [])],
|
|
59
|
+
applicability: [...(raw.applicability ?? [])],
|
|
60
|
+
limits,
|
|
61
|
+
provenance: raw.provenance ?? { source_type: 'original', license: 'MIT' },
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/** Registered modules, manifest-normalized. Throws when a registered module cannot be read. */
|
|
65
|
+
export function listAnalysisModules() {
|
|
66
|
+
return REGISTERED_MODULE_IDS.map((moduleId) => readManifest(moduleId));
|
|
67
|
+
}
|
|
68
|
+
export function analysisModuleById(moduleId) {
|
|
69
|
+
if (!REGISTERED_MODULE_IDS.includes(moduleId))
|
|
70
|
+
return undefined;
|
|
71
|
+
return readManifest(moduleId);
|
|
72
|
+
}
|
|
73
|
+
/** Test-only: drop the manifest cache so a fixture rewrite is visible. */
|
|
74
|
+
export function resetAnalysisModuleCache() {
|
|
75
|
+
cache.clear();
|
|
76
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Analysis execution: build the module request, run it under the private interpreter, validate the
|
|
3
|
+
* result and persist it.
|
|
4
|
+
*
|
|
5
|
+
* Two gates are enforced here rather than in the worker, because they are the host's facts:
|
|
6
|
+
* - concurrency: at most two analysis processes globally, and one module run at a time per snapshot
|
|
7
|
+
* (two runs on one snapshot would race the run index);
|
|
8
|
+
* - result contract: the worker's output must satisfy the manifest schema and be lossless JSON.
|
|
9
|
+
*/
|
|
10
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
11
|
+
import type { SessionLike } from '../data-collector/store.js';
|
|
12
|
+
import type { AnalysisModuleEntry } from './registry.js';
|
|
13
|
+
import type { SnapshotRecord } from './snapshot.js';
|
|
14
|
+
import { type AnalysisFileWriter } from './storage.js';
|
|
15
|
+
import { type ModuleResult } from './types.js';
|
|
16
|
+
/** The slice of `pythonRuntime` the analysis family uses. Resolved per call, never memoized. */
|
|
17
|
+
export interface AnalysisRuntimeLike {
|
|
18
|
+
runAnalysisModule(options: {
|
|
19
|
+
moduleDir: string;
|
|
20
|
+
entrypoint: string;
|
|
21
|
+
runDir: string;
|
|
22
|
+
inputsDir: string;
|
|
23
|
+
capabilities: readonly string[];
|
|
24
|
+
limits: {
|
|
25
|
+
max_input_rows: number;
|
|
26
|
+
max_output_bytes: number;
|
|
27
|
+
max_log_bytes: number;
|
|
28
|
+
};
|
|
29
|
+
timeoutMs: number;
|
|
30
|
+
signal?: AbortSignal;
|
|
31
|
+
}): Promise<{
|
|
32
|
+
result: unknown;
|
|
33
|
+
pythonVersion: string;
|
|
34
|
+
durationMs: number;
|
|
35
|
+
}>;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Resolve the runtime service at call time: the row is opt-in and the pack may be missing, so a
|
|
39
|
+
* boot-time lookup would either hide the tools or fail the plugin. Missing runtime is reported with
|
|
40
|
+
* the same install hint as the data capabilities.
|
|
41
|
+
*/
|
|
42
|
+
export declare function analysisRuntimeFrom(ctx: Context): AnalysisRuntimeLike;
|
|
43
|
+
/** Test-only: reset the concurrency counters between cases. */
|
|
44
|
+
export declare function resetAnalysisRuntimeState(): void;
|
|
45
|
+
export interface AnalysisRunRecord {
|
|
46
|
+
readonly module_run_id: string;
|
|
47
|
+
readonly module_id: string;
|
|
48
|
+
readonly module_version: string;
|
|
49
|
+
readonly params_digest: string;
|
|
50
|
+
readonly run_fingerprint: string;
|
|
51
|
+
readonly status: ModuleResult['status'];
|
|
52
|
+
readonly created_at: number;
|
|
53
|
+
readonly reused_from?: string;
|
|
54
|
+
}
|
|
55
|
+
export interface AnalysisRunIndex {
|
|
56
|
+
readonly analysis_id: string;
|
|
57
|
+
readonly input_fingerprint: string;
|
|
58
|
+
readonly runs: readonly AnalysisRunRecord[];
|
|
59
|
+
}
|
|
60
|
+
export interface RunModuleOptions {
|
|
61
|
+
writer: AnalysisFileWriter;
|
|
62
|
+
runtime: AnalysisRuntimeLike;
|
|
63
|
+
session: SessionLike;
|
|
64
|
+
snapshot: SnapshotRecord;
|
|
65
|
+
module: AnalysisModuleEntry;
|
|
66
|
+
params: Readonly<Record<string, unknown>>;
|
|
67
|
+
signal?: AbortSignal;
|
|
68
|
+
now?: number;
|
|
69
|
+
}
|
|
70
|
+
export interface RunModuleOutcome {
|
|
71
|
+
readonly analysis_run_ref: string;
|
|
72
|
+
readonly module_id: string;
|
|
73
|
+
readonly module_version: string;
|
|
74
|
+
readonly status: ModuleResult['status'];
|
|
75
|
+
readonly summary: string;
|
|
76
|
+
readonly metrics: Record<string, unknown>;
|
|
77
|
+
readonly assumptions: readonly string[];
|
|
78
|
+
readonly limitations: readonly string[];
|
|
79
|
+
readonly data_gaps: readonly string[];
|
|
80
|
+
readonly validation: {
|
|
81
|
+
readonly status: 'pass' | 'warning';
|
|
82
|
+
readonly issues: readonly unknown[];
|
|
83
|
+
};
|
|
84
|
+
readonly reused: boolean;
|
|
85
|
+
}
|
|
86
|
+
/** Run one registered module against a loaded snapshot, with reuse keyed by `run_fingerprint`. */
|
|
87
|
+
export declare function runModuleOnSnapshot(options: RunModuleOptions): Promise<RunModuleOutcome>;
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { MODULE_DEFAULT_LIMITS } from './schemas.js';
|
|
2
|
+
import { REQUEST_FILE, RESULT_FILE, RUN_FILE, analysisDir, moduleRunDir, newModuleRunId, readJsonFile, runRef, writeFiles, } from './storage.js';
|
|
3
|
+
import { ANALYSIS_ERROR_CODES, ANALYSIS_PROTOCOL, AnalysisError } from './types.js';
|
|
4
|
+
import { validateAgainstSchema, validateModuleResult } from './validation.js';
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import { dirname } from 'node:path';
|
|
7
|
+
import { stableStringify } from './snapshot.js';
|
|
8
|
+
/**
|
|
9
|
+
* Resolve the runtime service at call time: the row is opt-in and the pack may be missing, so a
|
|
10
|
+
* boot-time lookup would either hide the tools or fail the plugin. Missing runtime is reported with
|
|
11
|
+
* the same install hint as the data capabilities.
|
|
12
|
+
*/
|
|
13
|
+
export function analysisRuntimeFrom(ctx) {
|
|
14
|
+
return {
|
|
15
|
+
async runAnalysisModule(options) {
|
|
16
|
+
const manager = ctx.get('pythonRuntime');
|
|
17
|
+
if (manager === undefined || typeof manager.runAnalysisModule !== 'function') {
|
|
18
|
+
throw new AnalysisError('analysis_runtime_not_ready', '私有 Python 运行时未加载(python-runtime 行未启用或尚未装配);请在插件设置 → 分析环境里安装 base pack');
|
|
19
|
+
}
|
|
20
|
+
return await manager.runAnalysisModule(options);
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** Global cap: the private interpreter is heavy and the machine is shared with the DSH host. */
|
|
25
|
+
const MAX_CONCURRENT_ANALYSES = 2;
|
|
26
|
+
let activeAnalyses = 0;
|
|
27
|
+
const waiting = [];
|
|
28
|
+
async function withAnalysisSlot(run) {
|
|
29
|
+
if (activeAnalyses >= MAX_CONCURRENT_ANALYSES) {
|
|
30
|
+
await new Promise((resolve) => waiting.push(resolve));
|
|
31
|
+
}
|
|
32
|
+
activeAnalyses += 1;
|
|
33
|
+
try {
|
|
34
|
+
return await run();
|
|
35
|
+
}
|
|
36
|
+
finally {
|
|
37
|
+
activeAnalyses -= 1;
|
|
38
|
+
waiting.shift()?.();
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** One run per snapshot at a time; the tail is kept so later runs queue instead of interleaving. */
|
|
42
|
+
const snapshotTails = new Map();
|
|
43
|
+
async function serializeBySnapshot(analysisId, run) {
|
|
44
|
+
const previous = snapshotTails.get(analysisId) ?? Promise.resolve();
|
|
45
|
+
const next = previous.catch(() => undefined).then(run);
|
|
46
|
+
snapshotTails.set(analysisId, next);
|
|
47
|
+
try {
|
|
48
|
+
return await next;
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
if (snapshotTails.get(analysisId) === next)
|
|
52
|
+
snapshotTails.delete(analysisId);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** Test-only: reset the concurrency counters between cases. */
|
|
56
|
+
export function resetAnalysisRuntimeState() {
|
|
57
|
+
activeAnalyses = 0;
|
|
58
|
+
waiting.length = 0;
|
|
59
|
+
snapshotTails.clear();
|
|
60
|
+
}
|
|
61
|
+
function digest(value) {
|
|
62
|
+
return createHash('sha256').update(stableStringify(value), 'utf8').digest('hex');
|
|
63
|
+
}
|
|
64
|
+
function requireString(value, field) {
|
|
65
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
66
|
+
throw new AnalysisError('analysis_snapshot_invalid', `快照缺少 ${field}(快照文件被改动过?)`);
|
|
67
|
+
}
|
|
68
|
+
return value;
|
|
69
|
+
}
|
|
70
|
+
/** Run one registered module against a loaded snapshot, with reuse keyed by `run_fingerprint`. */
|
|
71
|
+
export async function runModuleOnSnapshot(options) {
|
|
72
|
+
const { writer, runtime, session, snapshot, module } = options;
|
|
73
|
+
const now = options.now ?? Date.now();
|
|
74
|
+
const manifest = module.manifest;
|
|
75
|
+
if (!manifest.roles.includes('senior_analyst')) {
|
|
76
|
+
throw new AnalysisError('analysis_module_not_applicable', `模块 ${manifest.id} 未声明 senior_analyst 角色`);
|
|
77
|
+
}
|
|
78
|
+
const params = options.params ?? {};
|
|
79
|
+
const paramIssues = validateAgainstSchema(params, manifest.input_schema, 'params');
|
|
80
|
+
if (paramIssues.length > 0) {
|
|
81
|
+
throw new AnalysisError('analysis_input_invalid', `参数不符合 ${manifest.id} 的输入契约:${paramIssues.slice(0, 4).join(';')}`);
|
|
82
|
+
}
|
|
83
|
+
const analysisId = requireString(snapshot.analysis_id, 'analysis_id');
|
|
84
|
+
const paramsDigest = digest(params);
|
|
85
|
+
const runFingerprint = digest({
|
|
86
|
+
input_fingerprint: snapshot.input_fingerprint,
|
|
87
|
+
module_id: manifest.id,
|
|
88
|
+
module_version: manifest.version,
|
|
89
|
+
params_digest: paramsDigest,
|
|
90
|
+
});
|
|
91
|
+
return await serializeBySnapshot(analysisId, async () => {
|
|
92
|
+
const index = await readRunIndex(writer, session, analysisId, options.signal);
|
|
93
|
+
const reusable = index.runs.find((record) => record.run_fingerprint === runFingerprint && record.status !== 'failed');
|
|
94
|
+
if (reusable !== undefined) {
|
|
95
|
+
const stored = await readJsonFile(writer, session, `${moduleRunDir(analysisId, reusable.module_run_id)}/${RESULT_FILE}`, options.signal);
|
|
96
|
+
if (stored?.result !== undefined)
|
|
97
|
+
return toOutcome(analysisId, reusable.module_run_id, manifest.id, manifest.version, stored.result, true);
|
|
98
|
+
}
|
|
99
|
+
const moduleRunId = newModuleRunId();
|
|
100
|
+
const dir = moduleRunDir(analysisId, moduleRunId);
|
|
101
|
+
const request = {
|
|
102
|
+
protocol: ANALYSIS_PROTOCOL,
|
|
103
|
+
task_id: requireString(snapshot.task_id, 'task_id'),
|
|
104
|
+
analysis_id: analysisId,
|
|
105
|
+
module_run_id: moduleRunId,
|
|
106
|
+
snapshot_id: analysisId,
|
|
107
|
+
as_of: requireString(snapshot.as_of, 'as_of'),
|
|
108
|
+
inputs: {
|
|
109
|
+
datasets: snapshot.dataset_refs.map((item) => ({ dataset_id: item.dataset_id })),
|
|
110
|
+
profiles: snapshot.profile_refs.map((item) => ({ profile_id: item.profile_id })),
|
|
111
|
+
evidence: snapshot.evidence,
|
|
112
|
+
},
|
|
113
|
+
params,
|
|
114
|
+
};
|
|
115
|
+
const [requestFile] = await writeFiles(writer, session, dir, [{ name: REQUEST_FILE, content: JSON.stringify(request) }], {
|
|
116
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
117
|
+
what: '写入模块请求失败',
|
|
118
|
+
});
|
|
119
|
+
const runDirAbsolute = dirname(requestFile.absolutePath);
|
|
120
|
+
const limits = { ...MODULE_DEFAULT_LIMITS, ...manifest.limits };
|
|
121
|
+
let executed;
|
|
122
|
+
try {
|
|
123
|
+
executed = await withAnalysisSlot(() => runtime.runAnalysisModule({
|
|
124
|
+
moduleDir: module.dir,
|
|
125
|
+
entrypoint: module.entrypoint,
|
|
126
|
+
runDir: runDirAbsolute,
|
|
127
|
+
inputsDir: snapshot.paths.inputs_dir,
|
|
128
|
+
capabilities: manifest.capabilities,
|
|
129
|
+
limits: {
|
|
130
|
+
max_input_rows: limits.max_input_rows,
|
|
131
|
+
max_output_bytes: limits.max_output_bytes,
|
|
132
|
+
max_log_bytes: limits.max_log_bytes,
|
|
133
|
+
},
|
|
134
|
+
timeoutMs: limits.timeout_ms,
|
|
135
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
136
|
+
}));
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
throw asRuntimeError(error, manifest.id);
|
|
140
|
+
}
|
|
141
|
+
const validated = validateModuleResult(executed.result, manifest);
|
|
142
|
+
const result = validated.result;
|
|
143
|
+
if (result === undefined || !validated.ok) {
|
|
144
|
+
await writeFiles(writer, session, dir, [{
|
|
145
|
+
name: RESULT_FILE,
|
|
146
|
+
content: JSON.stringify({ ok: false, issues: validated.issues, raw: executed.result ?? null }),
|
|
147
|
+
}], { ...(options.signal === undefined ? {} : { signal: options.signal }), overwrite: true, what: '写入失败结果失败' });
|
|
148
|
+
throw new AnalysisError('analysis_output_invalid', `模块 ${manifest.id} 的结果不满足契约:${validated.issues.slice(0, 4).map((issue) => issue.detail).join(';')}`);
|
|
149
|
+
}
|
|
150
|
+
const moduleResult = result;
|
|
151
|
+
await writeFiles(writer, session, dir, [{
|
|
152
|
+
name: RESULT_FILE,
|
|
153
|
+
content: JSON.stringify({
|
|
154
|
+
ok: true,
|
|
155
|
+
python: executed.pythonVersion,
|
|
156
|
+
duration_ms: executed.durationMs,
|
|
157
|
+
result: moduleResult,
|
|
158
|
+
}),
|
|
159
|
+
}], { ...(options.signal === undefined ? {} : { signal: options.signal }), overwrite: true, what: '写入模块结果失败' });
|
|
160
|
+
const record = {
|
|
161
|
+
module_run_id: moduleRunId,
|
|
162
|
+
module_id: manifest.id,
|
|
163
|
+
module_version: manifest.version,
|
|
164
|
+
params_digest: paramsDigest,
|
|
165
|
+
run_fingerprint: runFingerprint,
|
|
166
|
+
status: moduleResult.status,
|
|
167
|
+
created_at: now,
|
|
168
|
+
};
|
|
169
|
+
const nextIndex = {
|
|
170
|
+
analysis_id: analysisId,
|
|
171
|
+
input_fingerprint: snapshot.input_fingerprint,
|
|
172
|
+
runs: [...index.runs, record],
|
|
173
|
+
};
|
|
174
|
+
await writeFiles(writer, session, analysisDir(analysisId), [{ name: RUN_FILE, content: JSON.stringify(nextIndex) }], {
|
|
175
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
176
|
+
overwrite: true,
|
|
177
|
+
what: '写入 run.json 失败',
|
|
178
|
+
});
|
|
179
|
+
return toOutcome(analysisId, moduleRunId, manifest.id, manifest.version, moduleResult, false);
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
function toOutcome(analysisId, moduleRunId, moduleId, moduleVersion, result, reused) {
|
|
183
|
+
const issues = result.status === 'failed' ? [{ code: 'analysis_module_failed', detail: result.summary }] : [];
|
|
184
|
+
return {
|
|
185
|
+
analysis_run_ref: runRef(analysisId, moduleRunId),
|
|
186
|
+
module_id: moduleId,
|
|
187
|
+
module_version: moduleVersion,
|
|
188
|
+
status: result.status,
|
|
189
|
+
summary: typeof result.summary === 'string' ? result.summary : '',
|
|
190
|
+
metrics: (result.metrics ?? {}),
|
|
191
|
+
assumptions: result.assumptions ?? [],
|
|
192
|
+
limitations: result.limitations ?? [],
|
|
193
|
+
data_gaps: result.data_gaps ?? [],
|
|
194
|
+
validation: { status: issues.length === 0 ? 'pass' : 'warning', issues },
|
|
195
|
+
reused,
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
function asRuntimeError(error, moduleId) {
|
|
199
|
+
if (error instanceof AnalysisError)
|
|
200
|
+
return error;
|
|
201
|
+
const code = error?.code;
|
|
202
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
203
|
+
// A module-declared code (`AnalysisInputError`) becomes the protocol code; only known codes pass,
|
|
204
|
+
// so a module cannot invent one or impersonate a host-side failure.
|
|
205
|
+
const declared = error?.analysisCode;
|
|
206
|
+
if (typeof declared === 'string' && ANALYSIS_ERROR_CODES.includes(declared)) {
|
|
207
|
+
return new AnalysisError(declared, `模块 ${moduleId} 拒绝本次输入:${message}`);
|
|
208
|
+
}
|
|
209
|
+
if (code === 'timeout')
|
|
210
|
+
return new AnalysisError('analysis_timeout', `模块 ${moduleId} 超时:${message}`);
|
|
211
|
+
if (code === 'cancelled')
|
|
212
|
+
return new AnalysisError('analysis_cancelled', `模块 ${moduleId} 被取消`);
|
|
213
|
+
// `resolveDataRuntime` reports a missing base pack as `data-runtime-not-ready`; without this the
|
|
214
|
+
// documented `analysis_runtime_not_ready` degraded into `analysis_output_invalid` (2026-11-24 实测).
|
|
215
|
+
if (code === 'runtime-not-ready' || code === 'data-runtime-not-ready') {
|
|
216
|
+
return new AnalysisError('analysis_runtime_not_ready', message);
|
|
217
|
+
}
|
|
218
|
+
return new AnalysisError('analysis_output_invalid', `模块 ${moduleId} 执行失败:${message}`);
|
|
219
|
+
}
|
|
220
|
+
async function readRunIndex(writer, session, analysisId, signal) {
|
|
221
|
+
const stored = await readJsonFile(writer, session, `${analysisDir(analysisId)}/${RUN_FILE}`, signal);
|
|
222
|
+
if (stored === undefined)
|
|
223
|
+
return { analysis_id: analysisId, input_fingerprint: '', runs: [] };
|
|
224
|
+
return { analysis_id: analysisId, input_fingerprint: stored.input_fingerprint ?? '', runs: Array.isArray(stored.runs) ? stored.runs : [] };
|
|
225
|
+
}
|