@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
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AnalysisSnapshot: freeze the references an analysis is allowed to use, once.
|
|
3
|
+
*
|
|
4
|
+
* The snapshot stores refs, digests and a host-staged copy of each authorized input. It never stores
|
|
5
|
+
* raw rows in the model-visible half: `snapshot.json` is host-only, and the model receives an opaque
|
|
6
|
+
* ref plus a coverage summary.
|
|
7
|
+
*/
|
|
8
|
+
import { createHash } from 'node:crypto';
|
|
9
|
+
import { dirname } from 'node:path';
|
|
10
|
+
import { MAX_PRESENTATION_ROWS } from '../data-collector/store.js';
|
|
11
|
+
import { SNAPSHOT_FILE, analysisDir, inputsDir, newAnalysisId, readJsonFile, snapshotRef, writeFiles } from './storage.js';
|
|
12
|
+
import { ANALYSIS_PROTOCOL, AnalysisError, } from './types.js';
|
|
13
|
+
import { EVIDENCE_ITEM_MAX_BYTES, EVIDENCE_MAX_ITEMS, SNAPSHOT_TTL_MS } from './schemas.js';
|
|
14
|
+
const DATASET_COLUMN_SAMPLE = 200;
|
|
15
|
+
function sha256(text) {
|
|
16
|
+
return createHash('sha256').update(text, 'utf8').digest('hex');
|
|
17
|
+
}
|
|
18
|
+
/** Deterministic JSON: key order must not change a fingerprint. */
|
|
19
|
+
export function stableStringify(value) {
|
|
20
|
+
if (value === null || typeof value !== 'object')
|
|
21
|
+
return JSON.stringify(value) ?? 'null';
|
|
22
|
+
if (Array.isArray(value))
|
|
23
|
+
return `[${value.map((item) => stableStringify(item === undefined ? null : item)).join(',')}]`;
|
|
24
|
+
const entries = Object.entries(value)
|
|
25
|
+
.filter(([, item]) => item !== undefined)
|
|
26
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
27
|
+
return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`).join(',')}}`;
|
|
28
|
+
}
|
|
29
|
+
function inferType(values) {
|
|
30
|
+
let sawNull = false;
|
|
31
|
+
for (const value of values) {
|
|
32
|
+
if (value === null || value === undefined) {
|
|
33
|
+
sawNull = true;
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if (typeof value === 'number')
|
|
37
|
+
return Number.isInteger(value) ? 'integer' : 'number';
|
|
38
|
+
if (typeof value === 'string')
|
|
39
|
+
return 'string';
|
|
40
|
+
if (typeof value === 'boolean')
|
|
41
|
+
return 'boolean';
|
|
42
|
+
if (Array.isArray(value))
|
|
43
|
+
return 'array';
|
|
44
|
+
if (typeof value === 'object')
|
|
45
|
+
return 'object';
|
|
46
|
+
return sawNull ? 'mixed' : typeof value;
|
|
47
|
+
}
|
|
48
|
+
return 'null';
|
|
49
|
+
}
|
|
50
|
+
function columnsOf(rows) {
|
|
51
|
+
const sample = rows.slice(0, DATASET_COLUMN_SAMPLE);
|
|
52
|
+
const names = [];
|
|
53
|
+
const seen = new Set();
|
|
54
|
+
for (const row of sample) {
|
|
55
|
+
if (row === null || typeof row !== 'object' || Array.isArray(row))
|
|
56
|
+
continue;
|
|
57
|
+
for (const key of Object.keys(row)) {
|
|
58
|
+
if (seen.has(key))
|
|
59
|
+
continue;
|
|
60
|
+
seen.add(key);
|
|
61
|
+
names.push(key);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return names.map((name) => {
|
|
65
|
+
const values = sample.map((row) => (row !== null && typeof row === 'object' && !Array.isArray(row)
|
|
66
|
+
? row[name]
|
|
67
|
+
: undefined));
|
|
68
|
+
return {
|
|
69
|
+
name,
|
|
70
|
+
type: inferType(values),
|
|
71
|
+
nullable: values.some((value) => value === null || value === undefined),
|
|
72
|
+
};
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
function timeAxisOf(ref) {
|
|
76
|
+
const coverage = ref.time_coverage;
|
|
77
|
+
if (coverage === undefined || coverage.column === null || coverage.format === 'none')
|
|
78
|
+
return null;
|
|
79
|
+
return { column: coverage.column, unit: coverage.format, tz: 'dataset' };
|
|
80
|
+
}
|
|
81
|
+
function evidenceHash(item) {
|
|
82
|
+
return sha256(stableStringify({ source_id: item.source_id, title: item.title, excerpt: item.excerpt ?? null, url: item.url ?? null }));
|
|
83
|
+
}
|
|
84
|
+
function validateEvidence(evidence) {
|
|
85
|
+
if (evidence.length > EVIDENCE_MAX_ITEMS) {
|
|
86
|
+
throw new AnalysisError('analysis_snapshot_invalid', `evidence 最多 ${EVIDENCE_MAX_ITEMS} 条,收到 ${evidence.length} 条`);
|
|
87
|
+
}
|
|
88
|
+
for (const item of evidence) {
|
|
89
|
+
const bytes = Buffer.byteLength(JSON.stringify(item), 'utf8');
|
|
90
|
+
if (bytes > EVIDENCE_ITEM_MAX_BYTES) {
|
|
91
|
+
throw new AnalysisError('analysis_snapshot_invalid', `证据 ${item.source_id} 有 ${bytes} 字节,超过单条上限 ${EVIDENCE_ITEM_MAX_BYTES};只放摘要,正文留给检索侧`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Create the snapshot and stage its inputs.
|
|
97
|
+
*
|
|
98
|
+
* Any ref that cannot be read fails the whole call and names the object: a snapshot that silently
|
|
99
|
+
* drops an input is worse than no snapshot, because every downstream number looks sourced.
|
|
100
|
+
*/
|
|
101
|
+
export async function createSnapshot(options) {
|
|
102
|
+
const { reader, writer, session, input } = options;
|
|
103
|
+
const now = options.now ?? Date.now();
|
|
104
|
+
const analysisId = newAnalysisId();
|
|
105
|
+
const dir = analysisDir(analysisId);
|
|
106
|
+
validateEvidence(input.evidence);
|
|
107
|
+
const datasets = [];
|
|
108
|
+
const datasetFiles = [];
|
|
109
|
+
const retentionCandidates = [];
|
|
110
|
+
for (const ref of input.dataset_refs) {
|
|
111
|
+
const datasetId = typeof ref?.dataset_id === 'string' ? ref.dataset_id.trim() : '';
|
|
112
|
+
if (datasetId === '')
|
|
113
|
+
throw new AnalysisError('analysis_snapshot_invalid', 'dataset_refs 里有空 dataset_id');
|
|
114
|
+
let staged;
|
|
115
|
+
try {
|
|
116
|
+
staged = await reader.readPresentationRows({
|
|
117
|
+
session,
|
|
118
|
+
dataset_id: datasetId,
|
|
119
|
+
maxRows: MAX_PRESENTATION_ROWS,
|
|
120
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
throw new AnalysisError('analysis_input_invalid', `Dataset ${datasetId} 无法作为分析输入:${error instanceof Error ? error.message : String(error)}`);
|
|
125
|
+
}
|
|
126
|
+
const rows = staged.rows;
|
|
127
|
+
const view = {
|
|
128
|
+
shape: 'rows',
|
|
129
|
+
columns: columnsOf(rows),
|
|
130
|
+
row_count: rows.length,
|
|
131
|
+
rows,
|
|
132
|
+
envelope: staged.envelope ?? null,
|
|
133
|
+
time_axis: timeAxisOf(staged.ref),
|
|
134
|
+
truncated: false,
|
|
135
|
+
source: {
|
|
136
|
+
dataset_id: staged.ref.dataset_id,
|
|
137
|
+
captured_at: staged.ref.captured_at,
|
|
138
|
+
params_digest: staged.ref.params_digest,
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
datasets.push(view);
|
|
142
|
+
retentionCandidates.push(staged.ref.retention_until);
|
|
143
|
+
datasetFiles.push({ name: `${datasetId}.json`, content: JSON.stringify(view) });
|
|
144
|
+
}
|
|
145
|
+
const profiles = [];
|
|
146
|
+
const profileFiles = [];
|
|
147
|
+
for (const ref of input.profile_refs) {
|
|
148
|
+
const profileId = typeof ref?.profile_id === 'string' ? ref.profile_id.trim() : '';
|
|
149
|
+
if (profileId === '')
|
|
150
|
+
throw new AnalysisError('analysis_snapshot_invalid', 'profile_refs 里有空 profile_id');
|
|
151
|
+
let staged;
|
|
152
|
+
try {
|
|
153
|
+
staged = await reader.readProfile({ session, profile_id: profileId, ...(options.signal === undefined ? {} : { signal: options.signal }) });
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
throw new AnalysisError('analysis_input_invalid', `profile ${profileId} 无法作为分析输入:${error instanceof Error ? error.message : String(error)}`);
|
|
157
|
+
}
|
|
158
|
+
profiles.push({ ref: staged.ref });
|
|
159
|
+
retentionCandidates.push(staged.ref.retention_until);
|
|
160
|
+
profileFiles.push({ name: `${profileId}.json`, content: JSON.stringify({ ref: staged.ref, profile: staged.profile }) });
|
|
161
|
+
}
|
|
162
|
+
const evidence = [...input.evidence];
|
|
163
|
+
const inputFingerprint = sha256(stableStringify({
|
|
164
|
+
protocol: ANALYSIS_PROTOCOL,
|
|
165
|
+
task_id: input.task_id,
|
|
166
|
+
question: input.question,
|
|
167
|
+
instrument: input.instrument ?? null,
|
|
168
|
+
purpose: input.purpose,
|
|
169
|
+
horizon: input.horizon ?? null,
|
|
170
|
+
depth: input.depth,
|
|
171
|
+
as_of: input.as_of,
|
|
172
|
+
data_cutoff: input.data_cutoff ?? null,
|
|
173
|
+
datasets: datasets.map((item) => item.source),
|
|
174
|
+
profiles: profiles.map((item) => ({ profile_id: item.ref.profile_id, created_at: item.ref.created_at })),
|
|
175
|
+
evidence: evidence.map((item) => ({ source_id: item.source_id, hash: evidenceHash(item) })),
|
|
176
|
+
prior_analysis_refs: input.prior_analysis_refs,
|
|
177
|
+
constraints: input.constraints,
|
|
178
|
+
}));
|
|
179
|
+
const earliestRetention = retentionCandidates.length === 0 ? Number.POSITIVE_INFINITY : Math.min(...retentionCandidates);
|
|
180
|
+
const expiresAt = Math.min(now + SNAPSHOT_TTL_MS, earliestRetention);
|
|
181
|
+
// Absolute paths come from the store write itself: the worker needs a real directory, the model never sees one.
|
|
182
|
+
const writtenDatasets = datasetFiles.length === 0
|
|
183
|
+
? undefined
|
|
184
|
+
: await writeFiles(writer, session, inputsDir(analysisId, 'datasets'), datasetFiles, {
|
|
185
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
186
|
+
what: '暂存 Dataset 副本失败',
|
|
187
|
+
});
|
|
188
|
+
const writtenProfiles = profileFiles.length === 0
|
|
189
|
+
? undefined
|
|
190
|
+
: await writeFiles(writer, session, inputsDir(analysisId, 'profiles'), profileFiles, {
|
|
191
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
192
|
+
what: '暂存 profile 副本失败',
|
|
193
|
+
});
|
|
194
|
+
if (evidence.length > 0) {
|
|
195
|
+
await writeFiles(writer, session, inputsDir(analysisId, 'evidence'), evidence.map((item) => ({
|
|
196
|
+
name: `${item.source_id}.json`,
|
|
197
|
+
content: JSON.stringify(item),
|
|
198
|
+
})), {
|
|
199
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
200
|
+
what: '暂存证据副本失败',
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
const datasetsAbs = writtenDatasets?.[0]?.absolutePath;
|
|
204
|
+
const profilesAbs = writtenProfiles?.[0]?.absolutePath;
|
|
205
|
+
// dirname, not string slicing: Windows paths use a backslash separator.
|
|
206
|
+
const inputsAbsolute = datasetsAbs !== undefined
|
|
207
|
+
? dirname(datasetsAbs)
|
|
208
|
+
: profilesAbs !== undefined
|
|
209
|
+
? dirname(profilesAbs)
|
|
210
|
+
: undefined;
|
|
211
|
+
const record = {
|
|
212
|
+
analysis_id: analysisId,
|
|
213
|
+
task_id: input.task_id,
|
|
214
|
+
question: input.question,
|
|
215
|
+
...(input.instrument === undefined ? {} : { instrument: input.instrument }),
|
|
216
|
+
purpose: input.purpose,
|
|
217
|
+
...(input.horizon === undefined ? {} : { horizon: input.horizon }),
|
|
218
|
+
depth: input.depth,
|
|
219
|
+
as_of: input.as_of,
|
|
220
|
+
...(input.data_cutoff === undefined ? {} : { data_cutoff: input.data_cutoff }),
|
|
221
|
+
dataset_refs: datasets.map((item) => item.source),
|
|
222
|
+
profile_refs: profiles.map((item) => ({ profile_id: item.ref.profile_id, created_at: item.ref.created_at })),
|
|
223
|
+
evidence,
|
|
224
|
+
prior_analysis_refs: [...input.prior_analysis_refs],
|
|
225
|
+
constraints: input.constraints,
|
|
226
|
+
input_fingerprint: inputFingerprint,
|
|
227
|
+
created_at: now,
|
|
228
|
+
expires_at: expiresAt,
|
|
229
|
+
limitations: [],
|
|
230
|
+
datasets,
|
|
231
|
+
profiles,
|
|
232
|
+
paths: { dir, inputs_dir: inputsAbsolute === undefined ? `${dir}/inputs` : dirname(inputsAbsolute) },
|
|
233
|
+
};
|
|
234
|
+
await writeFiles(writer, session, dir, [{ name: SNAPSHOT_FILE, content: JSON.stringify(record) }], {
|
|
235
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
236
|
+
what: '写入 snapshot.json 失败',
|
|
237
|
+
});
|
|
238
|
+
return { record, ref: snapshotRef(analysisId) };
|
|
239
|
+
}
|
|
240
|
+
/** Load a snapshot by ref and fail loudly when it is missing or expired. */
|
|
241
|
+
export async function loadSnapshot(options) {
|
|
242
|
+
const record = await readJsonFile(options.reader, options.session, `${analysisDir(options.analysisId)}/${SNAPSHOT_FILE}`, options.signal);
|
|
243
|
+
if (record === undefined || record.analysis_id !== options.analysisId) {
|
|
244
|
+
throw new AnalysisError('analysis_snapshot_invalid', `找不到分析快照 ${options.analysisId}(ref 可能已失效,或不属于本会话)`);
|
|
245
|
+
}
|
|
246
|
+
const now = options.now ?? Date.now();
|
|
247
|
+
if (record.expires_at <= now) {
|
|
248
|
+
throw new AnalysisError('analysis_snapshot_expired', `分析快照 ${options.analysisId} 已于 ${new Date(record.expires_at).toISOString()} 过期;重新建快照再跑`);
|
|
249
|
+
}
|
|
250
|
+
return record;
|
|
251
|
+
}
|
|
252
|
+
/** Coverage summary returned to the model: counts and ranges only, never rows. */
|
|
253
|
+
export function snapshotCoverage(record) {
|
|
254
|
+
return {
|
|
255
|
+
datasets: record.datasets.map((item) => ({
|
|
256
|
+
dataset_id: item.source.dataset_id,
|
|
257
|
+
row_count: item.row_count,
|
|
258
|
+
columns: item.columns.length,
|
|
259
|
+
time_axis: item.time_axis?.column ?? null,
|
|
260
|
+
})),
|
|
261
|
+
profiles: record.profiles.map((item) => ({ profile_id: item.ref.profile_id, dataset_id: item.ref.dataset_id })),
|
|
262
|
+
evidence: record.evidence.length,
|
|
263
|
+
as_of: record.as_of,
|
|
264
|
+
data_cutoff: record.data_cutoff ?? null,
|
|
265
|
+
};
|
|
266
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { type SessionLike } from '../data-collector/store.js';
|
|
2
|
+
import { type AnalysisErrorCode } from './types.js';
|
|
3
|
+
export declare const ANALYSIS_ROOT = "capital-analysis/runs";
|
|
4
|
+
export declare const SNAPSHOT_FILE = "snapshot.json";
|
|
5
|
+
export declare const RUN_FILE = "run.json";
|
|
6
|
+
export declare const ARTIFACT_FILE = "artifact.json";
|
|
7
|
+
export declare const REQUEST_FILE = "request.json";
|
|
8
|
+
export declare const RESULT_FILE = "result.json";
|
|
9
|
+
/** Opaque refs: the model never learns a filesystem path, only one of these. */
|
|
10
|
+
export declare const ANALYSIS_ID: RegExp;
|
|
11
|
+
export declare const MODULE_RUN_ID: RegExp;
|
|
12
|
+
export interface AnalysisFileWriter {
|
|
13
|
+
writeWorkspaceFiles(input: {
|
|
14
|
+
session: SessionLike;
|
|
15
|
+
dir: string;
|
|
16
|
+
files: Array<{
|
|
17
|
+
name: string;
|
|
18
|
+
content: string;
|
|
19
|
+
}>;
|
|
20
|
+
signal?: AbortSignal;
|
|
21
|
+
overwrite?: boolean;
|
|
22
|
+
}): Promise<Array<{
|
|
23
|
+
name: string;
|
|
24
|
+
path: string;
|
|
25
|
+
absolutePath: string;
|
|
26
|
+
}>>;
|
|
27
|
+
readWorkspaceJson(input: {
|
|
28
|
+
session: SessionLike;
|
|
29
|
+
path: string;
|
|
30
|
+
signal?: AbortSignal;
|
|
31
|
+
}): Promise<unknown>;
|
|
32
|
+
}
|
|
33
|
+
export declare function newAnalysisId(): string;
|
|
34
|
+
export declare function newModuleRunId(): string;
|
|
35
|
+
export declare const analysisDir: (analysisId: string) => string;
|
|
36
|
+
export declare const inputsDir: (analysisId: string, kind: "datasets" | "profiles" | "evidence") => string;
|
|
37
|
+
export declare const moduleRunDir: (analysisId: string, moduleRunId: string) => string;
|
|
38
|
+
export declare const snapshotRef: (analysisId: string) => string;
|
|
39
|
+
export declare const runRef: (analysisId: string, moduleRunId: string) => string;
|
|
40
|
+
export declare const artifactRef: (analysisId: string) => string;
|
|
41
|
+
/** Parse a model-supplied ref; an unparsable ref must fail as `analysis_snapshot_invalid`. */
|
|
42
|
+
export declare function parseSnapshotRef(ref: unknown): string;
|
|
43
|
+
export declare function parseArtifactRef(ref: unknown): string;
|
|
44
|
+
/**
|
|
45
|
+
* Translate a store failure into an analysis error code. The store already names the object that
|
|
46
|
+
* failed (dataset id, path), so the message stays actionable without a second lookup.
|
|
47
|
+
*/
|
|
48
|
+
export declare function asAnalysisError(error: unknown, fallback: AnalysisErrorCode, what: string): never;
|
|
49
|
+
/** Write one directory's files through the store (createIfAbsent unless `overwrite`). */
|
|
50
|
+
export declare function writeFiles(writer: AnalysisFileWriter, session: SessionLike, dir: string, files: Array<{
|
|
51
|
+
name: string;
|
|
52
|
+
content: string;
|
|
53
|
+
}>, options?: {
|
|
54
|
+
signal?: AbortSignal;
|
|
55
|
+
overwrite?: boolean;
|
|
56
|
+
errorCode?: AnalysisErrorCode;
|
|
57
|
+
what?: string;
|
|
58
|
+
}): Promise<Array<{
|
|
59
|
+
name: string;
|
|
60
|
+
path: string;
|
|
61
|
+
absolutePath: string;
|
|
62
|
+
}>>;
|
|
63
|
+
/** Read one JSON file; a missing file is `undefined` (callers decide whether that is fatal). */
|
|
64
|
+
export declare function readJsonFile<T>(reader: AnalysisFileWriter, session: SessionLike, path: string, signal?: AbortSignal): Promise<T | undefined>;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run-directory layout and the workspace seam for the analysis family.
|
|
3
|
+
*
|
|
4
|
+
* Every path here is workspace-relative and goes through the Dataset store, which owns containment,
|
|
5
|
+
* the sandbox policy and the size gates. Nothing in `src/analysis/` touches `fs` directly.
|
|
6
|
+
*
|
|
7
|
+
* Layout (`capital-analysis/runs/<analysis_id>/`):
|
|
8
|
+
* snapshot.json run.json artifact.json
|
|
9
|
+
* inputs/{datasets,profiles,evidence}/
|
|
10
|
+
* modules/<module_run_id>/{request,result}.json + outputs/ + logs/
|
|
11
|
+
*/
|
|
12
|
+
import { randomUUID } from 'node:crypto';
|
|
13
|
+
import { DatasetStoreError } from '../data-collector/store.js';
|
|
14
|
+
import { AnalysisError } from './types.js';
|
|
15
|
+
export const ANALYSIS_ROOT = 'capital-analysis/runs';
|
|
16
|
+
export const SNAPSHOT_FILE = 'snapshot.json';
|
|
17
|
+
export const RUN_FILE = 'run.json';
|
|
18
|
+
export const ARTIFACT_FILE = 'artifact.json';
|
|
19
|
+
export const REQUEST_FILE = 'request.json';
|
|
20
|
+
export const RESULT_FILE = 'result.json';
|
|
21
|
+
/** Opaque refs: the model never learns a filesystem path, only one of these. */
|
|
22
|
+
export const ANALYSIS_ID = /^analysis_[a-z0-9]{6,40}$/u;
|
|
23
|
+
export const MODULE_RUN_ID = /^module_run_[a-z0-9]{6,40}$/u;
|
|
24
|
+
const idSuffix = () => `${Date.now().toString(36)}${randomUUID().replace(/-/gu, '').slice(0, 10)}`;
|
|
25
|
+
export function newAnalysisId() {
|
|
26
|
+
return `analysis_${idSuffix()}`;
|
|
27
|
+
}
|
|
28
|
+
export function newModuleRunId() {
|
|
29
|
+
return `module_run_${idSuffix()}`;
|
|
30
|
+
}
|
|
31
|
+
export const analysisDir = (analysisId) => `${ANALYSIS_ROOT}/${analysisId}`;
|
|
32
|
+
export const inputsDir = (analysisId, kind) => `${analysisDir(analysisId)}/inputs/${kind}`;
|
|
33
|
+
export const moduleRunDir = (analysisId, moduleRunId) => `${analysisDir(analysisId)}/modules/${moduleRunId}`;
|
|
34
|
+
export const snapshotRef = (analysisId) => `analysis:${analysisId}`;
|
|
35
|
+
export const runRef = (analysisId, moduleRunId) => `analysis_run:${analysisId}/${moduleRunId}`;
|
|
36
|
+
export const artifactRef = (analysisId) => `analysis_artifact:${analysisId}`;
|
|
37
|
+
/** Parse a model-supplied ref; an unparsable ref must fail as `analysis_snapshot_invalid`. */
|
|
38
|
+
export function parseSnapshotRef(ref) {
|
|
39
|
+
const text = typeof ref === 'string' ? ref.trim() : '';
|
|
40
|
+
const id = text.startsWith('analysis:') ? text.slice('analysis:'.length) : '';
|
|
41
|
+
if (!ANALYSIS_ID.test(id)) {
|
|
42
|
+
throw new AnalysisError('analysis_snapshot_invalid', `snapshot 引用无法识别:${JSON.stringify(text).slice(0, 120)}`);
|
|
43
|
+
}
|
|
44
|
+
return id;
|
|
45
|
+
}
|
|
46
|
+
export function parseArtifactRef(ref) {
|
|
47
|
+
const text = typeof ref === 'string' ? ref.trim() : '';
|
|
48
|
+
const id = text.startsWith('analysis_artifact:') ? text.slice('analysis_artifact:'.length) : '';
|
|
49
|
+
if (!ANALYSIS_ID.test(id)) {
|
|
50
|
+
throw new AnalysisError('analysis_snapshot_invalid', `分析产物引用无法识别:${JSON.stringify(text).slice(0, 120)}`);
|
|
51
|
+
}
|
|
52
|
+
return id;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Translate a store failure into an analysis error code. The store already names the object that
|
|
56
|
+
* failed (dataset id, path), so the message stays actionable without a second lookup.
|
|
57
|
+
*/
|
|
58
|
+
export function asAnalysisError(error, fallback, what) {
|
|
59
|
+
if (error instanceof AnalysisError)
|
|
60
|
+
throw error;
|
|
61
|
+
if (error instanceof DatasetStoreError) {
|
|
62
|
+
const code = error.code === 'dataset_expired' || error.code === 'profile_expired'
|
|
63
|
+
? 'analysis_snapshot_expired'
|
|
64
|
+
: error.code === 'dataset_session_mismatch' || error.code === 'dataset_not_found' || error.code === 'profile_not_found'
|
|
65
|
+
? 'analysis_snapshot_invalid'
|
|
66
|
+
: fallback;
|
|
67
|
+
throw new AnalysisError(code, `${what}:${error.message}`);
|
|
68
|
+
}
|
|
69
|
+
throw new AnalysisError(fallback, `${what}:${error instanceof Error ? error.message : String(error)}`);
|
|
70
|
+
}
|
|
71
|
+
/** Write one directory's files through the store (createIfAbsent unless `overwrite`). */
|
|
72
|
+
export async function writeFiles(writer, session, dir, files, options = {}) {
|
|
73
|
+
try {
|
|
74
|
+
return await writer.writeWorkspaceFiles({
|
|
75
|
+
session,
|
|
76
|
+
dir,
|
|
77
|
+
files,
|
|
78
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
79
|
+
...(options.overwrite === true ? { overwrite: true } : {}),
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
asAnalysisError(error, options.errorCode ?? 'analysis_input_invalid', options.what ?? `写入 ${dir} 失败`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/** Read one JSON file; a missing file is `undefined` (callers decide whether that is fatal). */
|
|
87
|
+
export async function readJsonFile(reader, session, path, signal) {
|
|
88
|
+
try {
|
|
89
|
+
return await reader.readWorkspaceJson({ session, path, ...(signal === undefined ? {} : { signal }) });
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
if (error instanceof DatasetStoreError && error.code === 'dataset_not_found')
|
|
93
|
+
return undefined;
|
|
94
|
+
asAnalysisError(error, 'analysis_input_invalid', `读取 ${path} 失败`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `tools/analysis` family: six model-facing tools of the senior analyst.
|
|
3
|
+
*
|
|
4
|
+
* Every tool authorizes the caller through `src/tool-exec.ts` (preset identity, one implementation)
|
|
5
|
+
* and returns refs plus bounded summaries. Raw rows never cross this boundary: they are staged into
|
|
6
|
+
* the snapshot's `inputs/` and read only by the reviewed module inside the private interpreter.
|
|
7
|
+
*/
|
|
8
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
9
|
+
import type { WorkspaceDatasetStore } from '../data-collector/store.js';
|
|
10
|
+
import { ANALYSIS_TOOL_NAMES } from './types.js';
|
|
11
|
+
export interface AnalysisToolDeps {
|
|
12
|
+
readonly ctx: Context;
|
|
13
|
+
readonly store: WorkspaceDatasetStore;
|
|
14
|
+
readonly now?: () => number;
|
|
15
|
+
}
|
|
16
|
+
export declare function registerAnalysisTools(deps: AnalysisToolDeps): void;
|
|
17
|
+
export { ANALYSIS_TOOL_NAMES };
|