@v587d/capital-generation 2.31.4 → 2.31.6

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 CHANGED
@@ -7,6 +7,59 @@
7
7
  - **第三位(patch)**:不破坏既有工具 / 配置 / 会话的新增与修复(如 2.1.1、2.1.2)。
8
8
  - **第二位(minor)**:有需要用户知晓的行为变更,且段内附迁移说明(如 2.1.0 的图表呈现通道重做、2.2.0 的数据源与检索来源扩容、2.4.0 的**必须换宿主版本**、2.9.0 的选择器收敛与质检前置——本插件自己的工具与数据契约没变,所以只抬第二位)。
9
9
 
10
+ ## [2.31.6] - 2026-11-28
11
+
12
+ 数据契约巡检加固:修复巡检假绿、SEC 日索引解析与路径、FINRA 多票结算日发现,并补齐 11 条新增能力的
13
+ 输出护栏与真实 SEC fixture。SEC 五条仍保持巡检 shadow,等待可访问 SEC 的出口完成实时 idx 复核后转正。
14
+
15
+ ### Fixed
16
+
17
+ - 契约巡检同时校验生产 `validateOutput` 与 `output_schema`;required、额外字段、类型、nullable 与非有限数
18
+ 不再漏报,已解析的上游结构错误统一归 `GUARD`,不再埋进 `TRANSPORT`。
19
+ - `sec_daily_filings` 使用 SEC 官方 `QTR{季}` 目录,支持跨两行的定宽表头,并接受 `YYYYMMDD` / `YYYY-MM-DD`
20
+ 申报日;真实 2018 idx 摘录已写入回归 fixture。
21
+ - SEC 五条巡检样本补 `minRows` 与关键 identity;ticker、submissions、全文检索和 frames fixture 使用真实
22
+ 报文摘录,补齐 instant / duration 两个分支。
23
+ - `finra_short_interest` 自动发现结算日时按全部 symbols 判定,不再因首票缺数误退到旧结算日。
24
+ - Treasury 1830 天区间上限在参数层执行;11 条新增能力的 `validateOutput` 完整执行各自 output schema。
25
+ - 契约巡检清单与设计文档解除 Git 忽略,CI checkout 可以读取转正 SOP 与证据。
26
+
27
+ ### Notes
28
+
29
+ - `sec_filings` 明确保持 recent-only;更早历史在 `filings.files`,本能力不自动合并。
30
+ - 回归:`npm test` **1919 pass / 0 fail**;双出口复跑 6 条 active 均至少一个出口 PASS,SEC 直连仍 403。
31
+ - 版本:根包 + 四个随包嵌套包 + `LOCAL_FETCH_CLIENT_VERSION` / `WIND_CLIENT_VERSION` 同步 2.31.6。
32
+
33
+ ## [2.31.5] - 2026-11-27
34
+
35
+ 数据面扩容:新增 11 条 `data_collector` 能力(162 → 173),覆盖港美股财务、美债与 NY Fed 利率、
36
+ SEC 披露与 XBRL 横截面、FINRA 做空。每批都同步了 capability 目录、契约巡检条目、normalize 样例、
37
+ 能力计数与生成文档;`npm test` 1913 通过。
38
+
39
+ ### Added
40
+
41
+ - **`eastmoney_offshore_statements`**:美股/港股三表长表(一行一个科目),`periods` 取最近 N 个报告期,
42
+ `period_type` 区分单季/累计/时点;币种逐行取上游字段(不按上市地推断),跨页按 `REPORT_DATE` 证明完整。
43
+ - **`eastmoney_offshore_indicators`**:美股/港股关键指标,按市场显式映射净利/EPS 同比字段,
44
+ 比率列逐列核验单位(百分数原值 vs 比例),两市场口径不一致的列整列丢弃。
45
+ - **`us_treasury_yield_curve`**:美国财政部每日国债收益率曲线,按年文件 800ms 错开并发拼接,
46
+ 缺列输出 null;收益率是百分数原值,日期是美东业务日。
47
+ - **`nyfed_reference_rates`**:纽约联储 SOFR/TGCR/BGCR/EFFR/OBFR,区间用 `search.json`,
48
+ 周末空区间返回成功空数组;`volumeInBillions` 单位为十亿美元。
49
+ - **`sec_ticker_cik` / `sec_filings` / `sec_daily_filings` / `sec_fulltext_search`**:SEC EDGAR 的
50
+ ticker↔CIK、submissions 申报列表、日索引与全文检索;CIK 统一 10 位补零,`acceptance_datetime` 是 UTC。
51
+ - **`sec_market_frame`**:XBRL frames 全市场横截面(`tag`/`unit`/`period`),instant 与 duration 口径分开,
52
+ 一次返回全部行、不静默截断。
53
+ - **`finra_short_volume` / `finra_short_interest`**:FINRA 做空成交量(文件末尾行数校验、小数成交量)与
54
+ 双周做空余额(settlementDate 分区、204 合法空、最近结算日自动发现)。
55
+ - 新增 `test/sec-source.test.mjs`、`test/us-official-source.test.mjs`,以及东财港美股财务的 fixture 回归。
56
+
57
+ ### Notes
58
+
59
+ - SEC 五条能力的巡检先挂 `shadow`:本机出口被 Akamai 限流(403),真报文形状已用宿主出口核对,
60
+ 待 CI/其它出口可打后转 active(revisit 2026-12-05)。
61
+ - BLS / DOL 与 Form 4 / 13F 暂缓:本机出口 403、取不到真实 XML 样本,待能访问的出口补齐。
62
+
10
63
  ## [2.31.4] - 2026-11-25
11
64
 
12
65
  高级分析师 §9.3 的 P1 分析模块全部落地:新增 8 颗受控模块,静态 registry 从 4 颗扩到 12 颗,
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  <a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-green" alt="License"></a>
4
4
  <a href="https://github.com/v587d/capital-generation"><img src="https://img.shields.io/badge/Financial%20Market-CN%20%7C%20HK%20%7C%20US-orange" alt="Market·CN+HK+US"></a>
5
5
  <a href="https://github.com/deepseek-ai"><img src="https://img.shields.io/badge/DSH%20Baseline-0.2.2--rc.5-blue" alt="DSH@0.2.2-rc.5"></a>
6
- <a href="https://github.com/v587d/capital-generation/releases"><img src="https://img.shields.io/badge/version-2.31.4-9cf" alt="Version"></a>
6
+ <a href="https://github.com/v587d/capital-generation/releases"><img src="https://img.shields.io/badge/version-2.31.6-9cf" alt="Version"></a>
7
7
  <a href="https://www.npmjs.com/package/@v587d/capital-generation"><img src="https://img.shields.io/npm/v/%40v587d%2Fcapital-generation" alt="npm version"></a>
8
8
  </p>
9
9
 
@@ -156,7 +156,7 @@ Capital Generation 是运行在 [DeepSeek Harness(DSH)](https://github.com/d
156
156
 
157
157
  ## 还能做什么
158
158
 
159
- - **查数据和资料:** 覆盖 A 股、港股、美股与期货等品种,由专用角色按需获取行情、财务、指数、基金、宏观行业与期货数据,检索公告、新闻和研报。共计 **162** 个数据收集能力和 **17** 个网页检索能力,部分公开数据源无需额外密钥;具体覆盖范围见 [数据收集能力表](docs/data-collector-capabilities.md) 和 [网页检索能力表](docs/web-retriever-capabilities.md)。
159
+ - **查数据和资料:** 覆盖 A 股、港股、美股与期货等品种,由专用角色按需获取行情、财务、指数、基金、宏观行业与期货数据,检索公告、新闻和研报。共计 **173** 个数据收集能力和 **17** 个网页检索能力,部分公开数据源无需额外密钥;具体覆盖范围见 [数据收集能力表](docs/data-collector-capabilities.md) 和 [网页检索能力表](docs/web-retriever-capabilities.md)。
160
160
  - **数据质检:** 结构化数据不会直接进入模型上下文。每份数据先由分析师检查结构、时间轴、缺失与基础统计,再按受控方式汇总;原始数据行始终留在工具层。
161
161
 
162
162
  <a id="senior-analyst" name="senior-analyst"></a>
@@ -230,7 +230,7 @@ Capital Generation 是运行在 [DeepSeek Harness(DSH)](https://github.com/d
230
230
  - **配置在哪?** 打开「插件」→ 已安装的 **Capital Generation**,插件介绍下方就是「数据源 / 投研自动化 / 精选 Skills / 包含的组件 / 分析环境」五格,五把密钥都在第一格;第二格可指定任务统一使用的默认工作区,也能改自动检查间隔与最长运行时间等上限;第五格准备 Python 分析环境;不在 DSH 的普通「设置」页面,也不用点进任何一行组件。保存密钥后新建会话再试。
231
231
  - **升级到 2.9.0 后,分析师和绘图专员去哪了?** 这一版把它们收进自动模式内部,不再出现在选择器与预设管理里,避免误开一个没有取数入口的空会话。旧会话仍能按原身份恢复;新任务直接用自动模式提出即可。
232
232
  - **宿主更新后插件显示异常、三个模式消失?** 插件只支持**同一 minor** 的宿主(本版是 `>=0.2.2-rc.5 <0.2.3-0`):宿主跨到 0.2.3 及以上时,旧插件会被启动拒载(插件页显示「异常」)。先把宿主升到与插件同一条 minor,再在插件页更新插件;应急可用版本豁免(有崩溃风险,见 CHANGELOG 的 Migration)。日志里出现「宿主 dsh … 未逐项验证」说明你跑在同一 minor 的未验证补丁版上——能跑,但遇异常请先升级插件并把那行日志附在 issue 里。
233
- - **桌面端升级后仍是旧版?** 桌面端安装时会固定所解析的版本,不会自动升级。卸载后重新安装,再到插件详情查看版本号;如需指定版本,可在地址末尾加 `#v2.31.4` 或 `@2.31.4`。
233
+ - **桌面端升级后仍是旧版?** 桌面端安装时会固定所解析的版本,不会自动升级。卸载后重新安装,再到插件详情查看版本号;如需指定版本,可在地址末尾加 `#v2.31.6` 或 `@2.31.6`。
234
234
  - **刚发布的新版本装不到?** 桌面端取包时会跳过**刚发布不久**的版本(宿主侧包管理器的发布冷却策略,实测会静默装成上一个版本),国内镜像的同步也可能滞后一段时间。急着用最新代码,改用仓库地址安装最直接;但仓库地址安装的是 git 依赖,插件页不显示「版本」检查。
235
235
  - **插件页的「版本」段怎么用?** 只有用包名从 npm 安装的版本才有;它只列比当前新的版本。回旧版要先卸载,再安装 `@v587d/capital-generation@版本号`(桌面端地址末尾加 `#v版本号`);旧版必须匹配当前 DSH 基线,对应关系见 [CHANGELOG 的 Migration](CHANGELOG.md)。
236
236
  - **网页抓取失败?** 配置卡片中的「允许启动本地提取网页内容」默认开启:AnySearch 提取失败时可尝试本机直连。关闭后,本机直连的具名来源查询也不可用;请检查该开关和网络连接。
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@v587d/capital-automation",
3
- "version": "2.31.4",
3
+ "version": "2.31.6",
4
4
  "description": "CapGen 投研自动化:独立 host bundle(固定 capital_automation 域、单 scheduler owner、/capital-automation 路由与浏览器页面)。",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@v587d/capital-charts",
3
- "version": "2.31.4",
3
+ "version": "2.31.6",
4
4
  "description": "自动模式的图表前端组件(浏览器半边 + 序列旁路路由):由 @v587d/capital-generation 随包携带并作为 host 平面行挂载。",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@v587d/config",
3
- "version": "2.31.4",
3
+ "version": "2.31.6",
4
4
  "description": "自动模式的取数凭据与偏好配置行:卡片坐在 @v587d/capital-generation 插件主页的「配置」段,点这一行本身没有表单。",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -6,6 +6,7 @@ import { createTencentSources } from './sources/tencent-http.js';
6
6
  import { createEastmoneySources } from './sources/eastmoney-http.js';
7
7
  import { createSinaSources } from './sources/sina-http.js';
8
8
  import { createOfficialSources } from './sources/official-http.js';
9
+ import { createUsOfficialSources } from './sources/us-official-http.js';
9
10
  import { createCsindexSources } from './sources/csindex-http.js';
10
11
  import { createThsSources } from './sources/ths-http.js';
11
12
  import { createPythonSources } from './sources/python-remote.js';
@@ -96,6 +97,13 @@ function registerSources(ctx, hub, config) {
96
97
  return () => { for (const dispose of disposers)
97
98
  dispose(); };
98
99
  }, 'capital-generation.official-sources()');
100
+ ctx.effect(() => {
101
+ const sources = createUsOfficialSources();
102
+ const disposers = sources.map((dataSource) => hub.registerSource(dataSource));
103
+ ctx.logger.info(`capital-generation: 已注册 ${disposers.length} 个美国官方数据源(us_treasury_yield_curve / nyfed_reference_rates)`);
104
+ return () => { for (const dispose of disposers)
105
+ dispose(); };
106
+ }, 'capital-generation.us-official-sources()');
99
107
  ctx.effect(() => {
100
108
  const sources = createThsSources();
101
109
  const disposers = sources.map((dataSource) => hub.registerSource(dataSource));
@@ -97,6 +97,8 @@ export const CATALOG_TAXONOMY = {
97
97
  'baostock_valuation_history': 'financials',
98
98
  'cash_flow': 'financials',
99
99
  'eastmoney_convertible_bond_list': 'financials',
100
+ 'eastmoney_offshore_indicators': 'financials',
101
+ 'eastmoney_offshore_statements': 'financials',
100
102
  'financial_indicators': 'financials',
101
103
  'ftshare_performance_express': 'financials',
102
104
  'ftshare_performance_forecast': 'financials',
@@ -165,6 +167,15 @@ export const CATALOG_TAXONOMY = {
165
167
  'ftshare_shibor': 'macro',
166
168
  'wind_edb_query': 'macro',
167
169
  'wind_edb_search': 'macro',
170
+ 'us_treasury_yield_curve': 'macro',
171
+ 'finra_short_volume': 'flow',
172
+ 'finra_short_interest': 'flow',
173
+ 'sec_ticker_cik': 'meta',
174
+ 'sec_filings': 'events',
175
+ 'sec_daily_filings': 'events',
176
+ 'sec_fulltext_search': 'events',
177
+ 'sec_market_frame': 'financials',
178
+ 'nyfed_reference_rates': 'macro',
168
179
  // futures
169
180
  'ftshare_bullion_price': 'futures',
170
181
  'ftshare_futures_contract_detail': 'futures',
@@ -55,6 +55,8 @@ export interface CapabilityDetail extends CapabilitySummary {
55
55
  input_schema: object;
56
56
  output_fields: string | null;
57
57
  }
58
+ /** Validate the JSON Schema subset used by DataSource output contracts. */
59
+ export declare function outputSchemaIssues(schema: unknown, value: unknown, path?: string): string[];
58
60
  export interface DataSource {
59
61
  schema: SchemaDescriptor;
60
62
  execute(request: DataRequest, signal: AbortSignal): Promise<{
@@ -39,6 +39,64 @@ function codePointLength(value) {
39
39
  function isPlainRecord(value) {
40
40
  return typeof value === 'object' && value !== null && !Array.isArray(value);
41
41
  }
42
+ /** Validate the JSON Schema subset used by DataSource output contracts. */
43
+ export function outputSchemaIssues(schema, value, path = '$') {
44
+ if (!isPlainRecord(schema) || Object.keys(schema).length === 0)
45
+ return [];
46
+ if (Array.isArray(schema.oneOf)) {
47
+ const matches = schema.oneOf.filter((branch) => outputSchemaIssues(branch, value, path).length === 0);
48
+ return matches.length === 1 ? [] : [`${path} must match exactly one oneOf branch (matched ${matches.length})`];
49
+ }
50
+ const type = schema.type;
51
+ if (typeof type === 'string' && !matchesOutputType(value, type))
52
+ return [`${path} must be ${type}`];
53
+ if (Array.isArray(schema.enum) && !schema.enum.includes(value))
54
+ return [`${path} must be one of ${schema.enum.join(', ')}`];
55
+ if (Array.isArray(value)) {
56
+ const issues = [];
57
+ if (isPlainRecord(schema.items)) {
58
+ for (let index = 0; index < value.length; index += 1) {
59
+ if (!(index in value))
60
+ issues.push(`${path}[${index}] is an array hole`);
61
+ else
62
+ issues.push(...outputSchemaIssues(schema.items, value[index], `${path}[${index}]`));
63
+ }
64
+ }
65
+ return issues;
66
+ }
67
+ if (!isPlainRecord(value))
68
+ return [];
69
+ const properties = isPlainRecord(schema.properties) ? schema.properties : {};
70
+ const required = Array.isArray(schema.required) ? schema.required : [];
71
+ const issues = [];
72
+ for (const key of required) {
73
+ if (typeof key !== 'string' || !Object.hasOwn(value, key) || value[key] === undefined)
74
+ issues.push(`${path}.${String(key)} is required`);
75
+ }
76
+ if (schema.additionalProperties === false) {
77
+ for (const key of Object.keys(value)) {
78
+ if (!Object.hasOwn(properties, key))
79
+ issues.push(`${path}.${key} is not declared`);
80
+ }
81
+ }
82
+ for (const [key, child] of Object.entries(properties)) {
83
+ if (Object.hasOwn(value, key) && value[key] !== undefined)
84
+ issues.push(...outputSchemaIssues(child, value[key], `${path}.${key}`));
85
+ }
86
+ return issues;
87
+ }
88
+ function matchesOutputType(value, type) {
89
+ switch (type) {
90
+ case 'object': return isPlainRecord(value);
91
+ case 'array': return Array.isArray(value);
92
+ case 'string': return typeof value === 'string';
93
+ case 'number': return typeof value === 'number' && Number.isFinite(value);
94
+ case 'integer': return Number.isSafeInteger(value);
95
+ case 'boolean': return typeof value === 'boolean';
96
+ case 'null': return value === null;
97
+ default: return true;
98
+ }
99
+ }
42
100
  function inlineFieldText(value) {
43
101
  if (typeof value !== 'string')
44
102
  return undefined;
@@ -1,4 +1,4 @@
1
- import { buildDataKey } from '../data-collector/hub.js';
1
+ import { buildDataKey, outputSchemaIssues } from '../data-collector/hub.js';
2
2
  import { getDataTimeContract } from '../time/tools.js';
3
3
  import { sharedEastmoneyClient, sharedEastmoneyThrottle, EastmoneyTransportError } from '../net/eastmoney-client.js';
4
4
  import { normalizeEastmoneyAshareIdentity, normalizeEastmoneyBoardIdentity, normalizeEastmoneySecurityIdentity } from './security-identity.js';
@@ -1353,7 +1353,8 @@ async function executeBondList(params, signal) {
1353
1353
  function createSource(options) {
1354
1354
  const schema = { capability: options.capability, time_contract: getDataTimeContract(options.capability), name: options.name, source: `http:eastmoney.${options.capability}`, data_key: buildDataKey('eastmoney', 'http', options.capability), source_label: 'eastmoney', paginated: options.paginated === true, cacheMaxAgeMs: options.cacheMaxAgeMs, rowShape: options.rowShape, summary: options.summary, description: options.description, input_schema: options.inputSchema, output_schema: options.outputSchema };
1355
1355
  const normalize = (params) => options.normalize(params);
1356
- const validateOutput = options.validateOutput ?? ((data) => isRecord(data) && Array.isArray(data.item) && isRecord(data.pagination));
1356
+ const semanticGuard = options.validateOutput ?? ((data) => isRecord(data) && Array.isArray(data.item) && isRecord(data.pagination));
1357
+ const validateOutput = (data) => semanticGuard(data) && outputSchemaIssues(options.outputSchema, data).length === 0;
1357
1358
  return { schema, normalizeParams: normalize, validateOutput, execute: async (request, signal) => options.execute(normalize(request.params), signal) };
1358
1359
  }
1359
1360
  const dateRangeInput = {
@@ -2112,6 +2113,260 @@ async function executeNewStock(params, signal) {
2112
2113
  const parsed = await fetchEventPage({ reportName: 'RPTA_APP_IPOAPPLY', context: 'new stock calendar', filter, sortColumns: 'APPLY_DATE,SECURITY_CODE', sortTypes: '-1,-1', page: Number(params.page), size: Number(params.size) }, signal);
2113
2114
  return { data: { item: parsed.rows.map(parseNewStockRow), pagination: pagination(Number(params.page), Number(params.size), parsed.pages, parsed.total) }, schema: datacenterOutput(newStockRow) };
2114
2115
  }
2116
+ const OFFSHORE_STATEMENTS = ['balance', 'income', 'cashflow'];
2117
+ const OFFSHORE_MAX_PERIODS = 40;
2118
+ /** Verified 2026-11-27: these report names honor pageSize=500 (500 rows returned per page). */
2119
+ const OFFSHORE_PAGE_SIZE = 500;
2120
+ /** Quarterly filings: 6h staleness is far below the reporting cadence. */
2121
+ const OFFSHORE_CACHE_MS = 21_600_000;
2122
+ const OFFSHORE_STATEMENT_REPORTS = {
2123
+ balance: { us: 'RPT_USF10_FN_BALANCE', hk: 'RPT_HKF10_FN_BALANCE' },
2124
+ income: { us: 'RPT_USF10_FN_INCOME', hk: 'RPT_HKF10_FN_INCOME' },
2125
+ cashflow: { us: 'RPT_USSK_FN_CASHFLOW', hk: 'RPT_HKSK_FN_CASHFLOW' },
2126
+ };
2127
+ const OFFSHORE_INDICATOR_REPORTS = {
2128
+ us: 'RPT_USF10_FN_GMAININDICATOR',
2129
+ hk: 'RPT_HKF10_FN_GMAININDICATOR',
2130
+ };
2131
+ /** Full code with market suffix; a bare ticker would force the host to guess the exchange. */
2132
+ function offshoreSecucode(value, name = 'secucode') {
2133
+ if (typeof value !== 'string')
2134
+ throw new Error(`${name} must be a string`);
2135
+ const secucode = value.trim().toUpperCase();
2136
+ if (/^\d{5}\.HK$/.test(secucode))
2137
+ return { secucode, market: 'hk' };
2138
+ if (/^[A-Z][A-Z0-9.\-]*\.(?:O|N|A)$/.test(secucode))
2139
+ return { secucode, market: 'us' };
2140
+ throw new Error(`${name} must be a full code with market suffix (00700.HK / AAPL.O / BABA.N); bare codes are rejected`);
2141
+ }
2142
+ function offshoreUpstreamDate(value, label) {
2143
+ const text = typeof value === 'string' ? value.trim().slice(0, 10) : '';
2144
+ const parsed = text.length === 10 ? new Date(`${text}T00:00:00Z`) : undefined;
2145
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(text) || parsed === undefined || Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== text) {
2146
+ throw sourceError(`Eastmoney ${label} is not a valid YYYY-MM-DD date: ${JSON.stringify(String(value ?? ''))}`, 'eastmoney_invalid_response');
2147
+ }
2148
+ return text;
2149
+ }
2150
+ function offshoreOptionalDate(value, label) {
2151
+ return value === undefined || value === null || value === '' ? null : offshoreUpstreamDate(value, label);
2152
+ }
2153
+ function offshoreRequiredText(value, label) {
2154
+ const text = textOrNull(value);
2155
+ if (text === null)
2156
+ throw sourceError(`Eastmoney ${label} is empty`, 'eastmoney_invalid_response');
2157
+ return text;
2158
+ }
2159
+ function normalizeOffshoreStatements(params) {
2160
+ assertKnown(params, ['secucode', 'statement', 'periods']);
2161
+ const { secucode } = offshoreSecucode(params.secucode);
2162
+ const statement = params.statement === undefined ? 'balance' : String(params.statement).toLowerCase();
2163
+ if (!OFFSHORE_STATEMENTS.includes(statement))
2164
+ throw new Error(`statement must be one of ${OFFSHORE_STATEMENTS.join(', ')}`);
2165
+ const periods = params.periods === undefined ? 1 : integer(params.periods, 'periods', 1, OFFSHORE_MAX_PERIODS);
2166
+ return { secucode, statement, periods };
2167
+ }
2168
+ function normalizeOffshoreIndicators(params) {
2169
+ assertKnown(params, ['secucode', 'periods']);
2170
+ const { secucode } = offshoreSecucode(params.secucode);
2171
+ const periods = params.periods === undefined ? 4 : integer(params.periods, 'periods', 1, OFFSHORE_MAX_PERIODS);
2172
+ return { secucode, periods };
2173
+ }
2174
+ /**
2175
+ * Fetch the newest `periods` report dates. Completeness is proven by ordering, not by row counts:
2176
+ * rows are REPORT_DATE-desc, so the first row of the (periods+1)th date means every row of the
2177
+ * wanted dates has already been read. Exhausting the last page is the other terminal condition.
2178
+ */
2179
+ async function fetchOffshorePeriodRows(reportName, secucode, periods, context, signal) {
2180
+ const rows = [];
2181
+ const dates = [];
2182
+ let page = 1;
2183
+ let total = 0;
2184
+ let pages = 1;
2185
+ for (;;) {
2186
+ const url = new URL(DATACENTER_URL);
2187
+ url.searchParams.set('reportName', reportName);
2188
+ url.searchParams.set('columns', 'ALL');
2189
+ url.searchParams.set('filter', `(SECUCODE="${secucode}")`);
2190
+ url.searchParams.set('sortColumns', 'REPORT_DATE');
2191
+ url.searchParams.set('sortTypes', '-1');
2192
+ url.searchParams.set('pageNumber', String(page));
2193
+ url.searchParams.set('pageSize', String(OFFSHORE_PAGE_SIZE));
2194
+ const parsed = requireRows(requireDatacenterResult(await getJson(url.toString(), signal, context), context), context);
2195
+ if (parsed.total === 0)
2196
+ return [];
2197
+ if (page === 1) {
2198
+ total = parsed.total;
2199
+ pages = parsed.pages;
2200
+ }
2201
+ else if (parsed.total !== total || parsed.pages !== pages)
2202
+ throw sourceError(`Eastmoney ${context} changed total/pages between pages (${parsed.total}/${parsed.pages} vs ${total}/${pages})`, 'eastmoney_invalid_response');
2203
+ if (parsed.rows.length === 0)
2204
+ throw sourceError(`Eastmoney ${context} returned an empty page ${page} of ${pages}`, 'eastmoney_invalid_response');
2205
+ for (const row of parsed.rows) {
2206
+ const reportDate = offshoreUpstreamDate(row.REPORT_DATE, `${context} REPORT_DATE`);
2207
+ if (dates.at(-1) !== reportDate) {
2208
+ if (dates.includes(reportDate))
2209
+ throw sourceError(`Eastmoney ${context} rows are not grouped by REPORT_DATE: ${reportDate} reappeared after ${dates.at(-1)}`, 'eastmoney_invalid_response');
2210
+ if (dates.length >= periods)
2211
+ return rows;
2212
+ dates.push(reportDate);
2213
+ }
2214
+ rows.push(row);
2215
+ }
2216
+ if (page >= pages)
2217
+ return rows;
2218
+ page += 1;
2219
+ }
2220
+ }
2221
+ function parseOffshoreStatementRow(raw, expected, market, statement, context) {
2222
+ const secucode = String(raw.SECUCODE ?? '').trim().toUpperCase();
2223
+ if (secucode !== expected)
2224
+ throw sourceError(`Eastmoney ${context} returned SECUCODE ${secucode || '(empty)'} for ${expected}`, 'eastmoney_invalid_response');
2225
+ const reportType = offshoreRequiredText(raw.REPORT_TYPE, `${context} REPORT_TYPE`);
2226
+ return {
2227
+ secucode,
2228
+ security_name: textOrNull(raw.SECURITY_NAME_ABBR),
2229
+ market,
2230
+ statement,
2231
+ report_date: offshoreUpstreamDate(raw.REPORT_DATE, `${context} REPORT_DATE`),
2232
+ start_date: offshoreOptionalDate(raw.START_DATE, `${context} START_DATE`),
2233
+ report_period: offshoreRequiredText(raw.REPORT, `${context} REPORT`),
2234
+ report_type: reportType,
2235
+ period_type: statement === 'balance' ? 'instant' : reportType === '单季报' ? 'single' : 'cumulative',
2236
+ item_code: offshoreRequiredText(raw.STD_ITEM_CODE, `${context} STD_ITEM_CODE`),
2237
+ item_name: offshoreRequiredText(raw.ITEM_NAME, `${context} ITEM_NAME`),
2238
+ amount_raw: numberOrNull(raw.AMOUNT),
2239
+ currency_code: textOrNull(market === 'us' ? raw.CURRENCY_ABBR : raw.CURRENCY_CODE),
2240
+ currency_label: textOrNull(raw.CURRENCY),
2241
+ accounting_standard: textOrNull(raw.ACCOUNT_STANDARD),
2242
+ };
2243
+ }
2244
+ function parseOffshoreIndicatorRow(raw, expected, market, context) {
2245
+ const secucode = String(raw.SECUCODE ?? '').trim().toUpperCase();
2246
+ if (secucode !== expected)
2247
+ throw sourceError(`Eastmoney ${context} returned SECUCODE ${secucode || '(empty)'} for ${expected}`, 'eastmoney_invalid_response');
2248
+ const reportType = offshoreRequiredText(raw.DATE_TYPE, `${context} DATE_TYPE`);
2249
+ return {
2250
+ secucode,
2251
+ security_name: textOrNull(raw.SECURITY_NAME_ABBR),
2252
+ market,
2253
+ report_date: offshoreUpstreamDate(raw.REPORT_DATE, `${context} REPORT_DATE`),
2254
+ start_date: offshoreOptionalDate(raw.START_DATE, `${context} START_DATE`),
2255
+ notice_date: offshoreOptionalDate(raw.NOTICE_DATE, `${context} NOTICE_DATE`),
2256
+ report_period: offshoreRequiredText(raw.REPORT_TYPE, `${context} REPORT_TYPE`),
2257
+ report_type: reportType,
2258
+ period_type: reportType === '单季报' ? 'single' : 'cumulative',
2259
+ currency_code: textOrNull(raw.CURRENCY_ABBR),
2260
+ currency_label: textOrNull(raw.CURRENCY),
2261
+ accounting_standard: textOrNull(raw.ACCOUNTING_STANDARDS),
2262
+ operate_income: numberOrNull(raw.OPERATE_INCOME),
2263
+ operate_income_yoy: numberOrNull(raw.OPERATE_INCOME_YOY),
2264
+ gross_profit: numberOrNull(raw.GROSS_PROFIT),
2265
+ gross_profit_yoy: numberOrNull(raw.GROSS_PROFIT_YOY),
2266
+ net_profit: numberOrNull(market === 'us' ? raw.PARENT_HOLDER_NETPROFIT : raw.HOLDER_PROFIT),
2267
+ net_profit_yoy: numberOrNull(market === 'us' ? raw.PARENT_HOLDER_NETPROFIT_YOY : raw.HOLDER_PROFIT_YOY),
2268
+ basic_eps: numberOrNull(raw.BASIC_EPS),
2269
+ diluted_eps: numberOrNull(raw.DILUTED_EPS),
2270
+ basic_eps_yoy: numberOrNull(market === 'us' ? raw.BASIC_EPS_YOY : raw.EPS_YOY),
2271
+ gross_profit_ratio: numberOrNull(raw.GROSS_PROFIT_RATIO),
2272
+ net_profit_ratio: numberOrNull(raw.NET_PROFIT_RATIO),
2273
+ roe_avg: numberOrNull(raw.ROE_AVG),
2274
+ roa: numberOrNull(raw.ROA),
2275
+ current_ratio: numberOrNull(raw.CURRENT_RATIO),
2276
+ debt_asset_ratio: numberOrNull(raw.DEBT_ASSET_RATIO),
2277
+ };
2278
+ }
2279
+ const offshoreStatementRow = {
2280
+ type: 'object',
2281
+ properties: {
2282
+ secucode: { type: 'string' }, security_name: nullableString, market: { enum: ['us', 'hk'] },
2283
+ statement: { enum: [...OFFSHORE_STATEMENTS] },
2284
+ report_date: { type: 'string' }, start_date: nullableString,
2285
+ report_period: { type: 'string' }, report_type: { type: 'string' },
2286
+ period_type: { enum: ['instant', 'cumulative', 'single'] },
2287
+ item_code: { type: 'string' }, item_name: { type: 'string' },
2288
+ amount_raw: nullableNumber,
2289
+ currency_code: nullableString, currency_label: nullableString, accounting_standard: nullableString,
2290
+ },
2291
+ required: ['secucode', 'market', 'statement', 'report_date', 'report_period', 'report_type', 'period_type', 'item_code', 'item_name'],
2292
+ additionalProperties: false,
2293
+ };
2294
+ const offshoreIndicatorRow = {
2295
+ type: 'object',
2296
+ properties: {
2297
+ secucode: { type: 'string' }, security_name: nullableString, market: { enum: ['us', 'hk'] },
2298
+ report_date: { type: 'string' }, start_date: nullableString, notice_date: nullableString,
2299
+ report_period: { type: 'string' }, report_type: { type: 'string' },
2300
+ period_type: { enum: ['cumulative', 'single'] },
2301
+ currency_code: nullableString, currency_label: nullableString, accounting_standard: nullableString,
2302
+ operate_income: nullableNumber, operate_income_yoy: nullableNumber,
2303
+ gross_profit: nullableNumber, gross_profit_yoy: nullableNumber,
2304
+ net_profit: nullableNumber, net_profit_yoy: nullableNumber,
2305
+ basic_eps: nullableNumber, diluted_eps: nullableNumber, basic_eps_yoy: nullableNumber,
2306
+ gross_profit_ratio: nullableNumber, net_profit_ratio: nullableNumber,
2307
+ roe_avg: nullableNumber, roa: nullableNumber,
2308
+ current_ratio: nullableNumber, debt_asset_ratio: nullableNumber,
2309
+ },
2310
+ required: ['secucode', 'market', 'report_date', 'report_period', 'report_type', 'period_type'],
2311
+ additionalProperties: false,
2312
+ };
2313
+ const offshoreEnvelope = (row) => ({
2314
+ type: 'object',
2315
+ properties: { item: { type: 'array', items: row } },
2316
+ required: ['item'],
2317
+ additionalProperties: false,
2318
+ });
2319
+ function validateOffshoreEnvelope(data) {
2320
+ return isRecord(data) && Array.isArray(data.item) && data.item.every(isRecord);
2321
+ }
2322
+ function offshoreDuplicateKey(row) {
2323
+ return `${String(row.report_date)}|${String(row.report_type)}|${String(row.item_code ?? row.period_type)}`;
2324
+ }
2325
+ function assertNoOffshoreDuplicates(item, context) {
2326
+ const seen = new Set();
2327
+ for (const row of item) {
2328
+ const key = offshoreDuplicateKey(row);
2329
+ if (seen.has(key))
2330
+ throw sourceError(`Eastmoney ${context} returned a duplicate row key ${key}`, 'eastmoney_invalid_response');
2331
+ seen.add(key);
2332
+ }
2333
+ }
2334
+ const offshoreStatementsInput = {
2335
+ type: 'object',
2336
+ properties: {
2337
+ secucode: { type: 'string', description: '带市场后缀的完整代码:美股 AAPL.O / BABA.N,港股 00700.HK(裸码会被拒绝,不猜交易所)' },
2338
+ statement: { type: 'string', enum: [...OFFSHORE_STATEMENTS], description: '报表类型,默认 balance' },
2339
+ periods: { type: 'integer', minimum: 1, maximum: OFFSHORE_MAX_PERIODS, description: '最近 N 个报告期(按 REPORT_DATE 去重,默认 1;同一报告日可能有多个 period_type)' },
2340
+ },
2341
+ required: ['secucode'],
2342
+ additionalProperties: false,
2343
+ };
2344
+ const offshoreIndicatorsInput = {
2345
+ type: 'object',
2346
+ properties: {
2347
+ secucode: { type: 'string', description: '带市场后缀的完整代码:美股 AAPL.O / BABA.N,港股 00700.HK(裸码会被拒绝,不猜交易所)' },
2348
+ periods: { type: 'integer', minimum: 1, maximum: OFFSHORE_MAX_PERIODS, description: '最近 N 个报告期(默认 4;美股同一报告日可能有单季与累计两行)' },
2349
+ },
2350
+ required: ['secucode'],
2351
+ additionalProperties: false,
2352
+ };
2353
+ async function executeOffshoreStatements(params, signal) {
2354
+ const { secucode, market } = offshoreSecucode(params.secucode);
2355
+ const statement = params.statement;
2356
+ const context = `offshore ${statement} ${secucode}`;
2357
+ const rows = await fetchOffshorePeriodRows(OFFSHORE_STATEMENT_REPORTS[statement][market], secucode, Number(params.periods), context, signal);
2358
+ const item = rows.map((raw) => parseOffshoreStatementRow(raw, secucode, market, statement, context));
2359
+ assertNoOffshoreDuplicates(item, context);
2360
+ return { data: { item }, schema: offshoreEnvelope(offshoreStatementRow) };
2361
+ }
2362
+ async function executeOffshoreIndicators(params, signal) {
2363
+ const { secucode, market } = offshoreSecucode(params.secucode);
2364
+ const context = `offshore indicators ${secucode}`;
2365
+ const rows = await fetchOffshorePeriodRows(OFFSHORE_INDICATOR_REPORTS[market], secucode, Number(params.periods), context, signal);
2366
+ const item = rows.map((raw) => parseOffshoreIndicatorRow(raw, secucode, market, context));
2367
+ assertNoOffshoreDuplicates(item, context);
2368
+ return { data: { item }, schema: offshoreEnvelope(offshoreIndicatorRow) };
2369
+ }
2115
2370
  export function createEastmoneySources() {
2116
2371
  return [
2117
2372
  createSource({ capability: 'eastmoney_top_buy_sell_market', name: 'get_eastmoney_top_buy_sell_market', summary: '东财全市场龙虎榜汇总', description: '按交易日区间分页获取东方财富龙虎榜上榜股票汇总。金额字段单位为元,CHANGE_RATE/TURNOVERRATE/DEAL_*_RATIO 为东财百分数原值;同一股票同日可能因多个上榜原因返回多行,不去重。上游 HTTP 200 但 success=false、code 非 0 或 result 缺失均视为失败,不转换为空数组。', inputSchema: dateRangeInput, outputSchema: datacenterOutput(topBuySellRow), paginated: true, rowShape: { rowKey: 'item' }, allowed: ['start_date', 'end_date', 'page', 'size'], normalize: (params) => normalizeDateRange(params, ['start_date', 'end_date', 'page', 'size']), execute: (params, signal) => executeBillboard(params, signal) }),
@@ -3049,5 +3304,25 @@ function createEastmoneyLimitPoolSources() {
3049
3304
  allowed: ['ticker'], normalize: normalizeHotConcepts, execute: executeHotConcepts,
3050
3305
  validateOutput: validateHotConceptOutput,
3051
3306
  }),
3307
+ createSource({
3308
+ capability: 'eastmoney_offshore_statements', cacheMaxAgeMs: OFFSHORE_CACHE_MS,
3309
+ name: 'get_eastmoney_offshore_statements',
3310
+ summary: '港美股三表(一行一个科目)',
3311
+ description: '获取美股/港股三表(东方财富 datacenter F10:美股 RPT_USF10_FN_BALANCE / RPT_USF10_FN_INCOME / RPT_USSK_FN_CASHFLOW,港股 RPT_HKF10_FN_BALANCE / RPT_HKF10_FN_INCOME / RPT_HKSK_FN_CASHFLOW),**长表:一行一个科目**。⛔ `periods` 是「最近 N 个报告期(按 REPORT_DATE 去重)」,不是行数上限:同一报告日可能有多个口径(实测美股利润表/现金流量表同一日期同时有「单季报」与「累计季报/年报」),用 `period_type`(instant/cumulative/single)区分——⛔ 单季与累计**不可相加**,资产负债表是时点值(instant)。真报文实测(2026-11-27):AAPL.O 资产负债表 2907 行 / 103 个报告期、利润表 4646 行、现金流量表 4668 行;00700.HK 资产负债表 4343 行、利润表 2268 行、现金流量表 1818 行。⛔ 币种逐行取上游字段、**不按上市地推断**:美股取 CURRENCY_ABBR、港股取 CURRENCY_CODE;实测 00700/00939=CNY、00005=USD、09988=美国会计准则——港股不等于 HKD,也不等于 CNY。`amount_raw` 是报告币种原值、不换算;`start_date` 只有利润表/现金流量表有(资产负债表无此字段,恒为 null)。⛔ 丢弃未核验或口径不一致的列:`YOY_RATIO`(美股 1.032 是比例、港股 72.64 是百分数原值,两市场口径不一致)、`REMARK`、`FISCAL_YEAR`、`DATE_TYPE_CODE`、`STD_REPORT_DATE` 等未声明键;不要按「上游有这一列」推断本地也该有。⛔ 空结果是合法空:上游 code 9201 表示该证券在该表无数据(实测 00005.HK 利润表 2321 行、资产负债表 2341 行、币种 USD;同一证券的指标表却可能为空,见 `eastmoney_offshore_indicators`),不是取数失败、不要重试。分页:pageSize=500 翻满,按 REPORT_DATE 降序;只有「看到第 N+1 个更早的报告日」或「翻完最后一页」才算前 N 期完整——同一日期在更晚页重现、total/pages 中途变化、空页一律响亮失败。代码必须带市场后缀:港股 5 位数字 `.HK`,美股 `.O/.N/.A`,裸码拒绝(不猜交易所)。报告期是财季截止日、不是自然时间窗,本能力**未注册 time_contract**,`resolve_data_time_range` 不支持它;要更早的报告期就把 `periods` 调大。缓存 6 小时(财报按季更新)。',
3312
+ inputSchema: offshoreStatementsInput, outputSchema: offshoreEnvelope(offshoreStatementRow),
3313
+ paginated: false, rowShape: { rowKey: 'item' },
3314
+ allowed: ['secucode', 'statement', 'periods'], normalize: normalizeOffshoreStatements, execute: executeOffshoreStatements,
3315
+ validateOutput: validateOffshoreEnvelope,
3316
+ }),
3317
+ createSource({
3318
+ capability: 'eastmoney_offshore_indicators', cacheMaxAgeMs: OFFSHORE_CACHE_MS,
3319
+ name: 'get_eastmoney_offshore_indicators',
3320
+ summary: '港美股关键财务指标(按报告期)',
3321
+ description: '获取美股/港股关键财务指标(东方财富 datacenter F10:美股 RPT_USF10_FN_GMAININDICATOR、港股 RPT_HKF10_FN_GMAININDICATOR),**一行一个报告期口径**。`periods` = 最近 N 个报告期(按 REPORT_DATE 去重,默认 4、上限 40)。⛔ 同一报告日可能有两行:美股同时有「单季报」与「累计季报/年报」(实测 AAPL.O 186 行 / 107 个报告期,2026-09-26 两行分别是 2026/Q4 单季与 2026/FY 年报),港股一行一期(00700.HK 97 行 / 97 期);用 `period_type`(cumulative/single)区分,⛔ **不可相加**。字段按市场显式映射并统一命名:净利美股取 `PARENT_HOLDER_NETPROFIT`、港股取 `HOLDER_PROFIT`(均为归母口径);EPS 同比美股取 `BASIC_EPS_YOY`、港股取 `EPS_YOY`;`report_period` 取上游 `REPORT_TYPE`(美股如 2026/FY、港股如 2026/Q9),`report_type` 取 `DATE_TYPE`(年报/中报/一季报/三季报/累计季报/单季报)。⛔ 单位已逐列核验:`operate_income`/`gross_profit`/`net_profit` 为报告币种金额原值(不换算),`basic_eps`/`diluted_eps` 为报告币种/股;`*_yoy`、`gross_profit_ratio`、`net_profit_ratio`、`roe_avg`、`roa`、`debt_asset_ratio` 是**百分数原值**(38.37 读作 38.37%),`current_ratio` 是**比例**(1.303 读作 1.303 倍)——⛔ 不要把比例当百分数,也不要乘 100。⛔ 丢弃两市场口径不一致或未核验的列:`EQUITY_RATIO`(美股 43.7~596 像百分数、港股 0.06~2.03 像比例)、`OCF_LIQDEBT`(美股比例、港股百分数)、`ROE`/`ROIC`/`PER_*`/`BPS`/`DPS_HKD` 等未逐列核验项;`DPS_HKD` 名字带 HKD 但报告币种可能是 CNY,不可直接当港元。空结果合法:code 9201(实测 00005.HK 指标为空、利润表却有数据),不是失败。代码、分页、空页与 total/pages 校验同 `eastmoney_offshore_statements`;报告期不是自然时间窗,未注册 time_contract。缓存 6 小时。',
3322
+ inputSchema: offshoreIndicatorsInput, outputSchema: offshoreEnvelope(offshoreIndicatorRow),
3323
+ paginated: false, rowShape: { rowKey: 'item' },
3324
+ allowed: ['secucode', 'periods'], normalize: normalizeOffshoreIndicators, execute: executeOffshoreIndicators,
3325
+ validateOutput: validateOffshoreEnvelope,
3326
+ }),
3052
3327
  ];
3053
3328
  }
@@ -0,0 +1,5 @@
1
+ /** SEC EDGAR sources: ticker→CIK, submissions, daily index, full-text search and XBRL frames.
2
+ * Contract probes stay shadow until a live SEC egress passes; fixtures mirror official payloads.
3
+ */
4
+ import type { DataSource } from '../data-collector/hub.js';
5
+ export declare function createSecSources(): DataSource[];