@v587d/capital-generation 2.30.0 → 2.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +99 -0
  2. package/README.md +4 -4
  3. package/THIRD_PARTY_NOTICES.md +1 -0
  4. package/automation/package.json +1 -1
  5. package/automation/storage.js +4 -0
  6. package/chart-ui/package.json +1 -1
  7. package/config/client.js +1 -1
  8. package/config/package.json +1 -1
  9. package/lib/agents/messaging-policy.d.ts +1 -1
  10. package/lib/agents/role-tool-policy.d.ts +3 -0
  11. package/lib/agents/role-tool-policy.js +12 -2
  12. package/lib/agents/selected-skills-provider.d.ts +1 -1
  13. package/lib/agents/selected-skills-provider.js +3 -1
  14. package/lib/analysis/registry.d.ts +12 -0
  15. package/lib/analysis/registry.js +76 -0
  16. package/lib/analysis/runtime.d.ts +87 -0
  17. package/lib/analysis/runtime.js +225 -0
  18. package/lib/analysis/schemas.d.ts +52 -0
  19. package/lib/analysis/schemas.js +270 -0
  20. package/lib/analysis/snapshot.d.ts +102 -0
  21. package/lib/analysis/snapshot.js +266 -0
  22. package/lib/analysis/storage.d.ts +64 -0
  23. package/lib/analysis/storage.js +96 -0
  24. package/lib/analysis/tools.d.ts +17 -0
  25. package/lib/analysis/tools.js +352 -0
  26. package/lib/analysis/types.d.ts +201 -0
  27. package/lib/analysis/types.js +44 -0
  28. package/lib/analysis/validation.d.ts +44 -0
  29. package/lib/analysis/validation.js +338 -0
  30. package/lib/analysis-entry.d.ts +10 -0
  31. package/lib/analysis-entry.js +7 -0
  32. package/lib/data-collector/dataset-tools.js +4 -2
  33. package/lib/data-collector/describe.d.ts +2 -0
  34. package/lib/data-collector/describe.js +2 -0
  35. package/lib/data-collector/store.d.ts +25 -1
  36. package/lib/data-collector/store.js +124 -1
  37. package/lib/data-collector/tools.d.ts +1 -1
  38. package/lib/data-collector/tools.js +3 -2
  39. package/lib/data-contract.d.ts +3 -2
  40. package/lib/data-contract.js +18 -2
  41. package/lib/preset-ids.d.ts +5 -0
  42. package/lib/preset-ids.js +7 -1
  43. package/lib/python-runtime/errors.d.ts +7 -1
  44. package/lib/python-runtime/errors.js +9 -1
  45. package/lib/python-runtime/manager.d.ts +30 -0
  46. package/lib/python-runtime/manager.js +88 -0
  47. package/lib/python-runtime/probe.js +5 -1
  48. package/lib/selected-skills-entry.js +1 -1
  49. package/lib/sources/tencent-http.js +1 -1
  50. package/lib/sources/ths-http.js +5 -2
  51. package/lib/time/tools.js +1 -1
  52. package/lib/web-retriever/local-fetch.d.ts +1 -1
  53. package/lib/web-retriever/local-fetch.js +1 -1
  54. package/lib/web-retriever/wind-client.d.ts +1 -1
  55. package/lib/web-retriever/wind-client.js +1 -1
  56. package/package.json +6 -1
  57. package/preset/capital-generation/README.md +5 -6
  58. package/preset/capital-generation/agent.patch.yml +47 -58
  59. package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +99 -0
  60. package/preset/capital-generation/skills/capital-analysis-synthesis/SKILL.md +110 -0
  61. package/preset/capital-generation/skills/capital-analysis-validation/SKILL.md +93 -0
  62. package/preset/capital-generation/skills/capital-data-query/SKILL.md +1 -1
  63. package/preset/capital-generation/skills/capital-equity-research/SKILL.md +1 -1
  64. package/preset/capital-generation/skills/capital-event-impact/SKILL.md +1 -1
  65. package/preset/capital-generation/skills/capital-orchestration/SKILL.md +1 -1
  66. package/preset/capital-generation/skills/capital-portfolio-review/SKILL.md +1 -1
  67. package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +100 -0
  68. package/python/analysis/modules/financial_quality/LICENSE +27 -0
  69. package/python/analysis/modules/financial_quality/module.json +65 -0
  70. package/python/analysis/modules/financial_quality/module.py +535 -0
  71. package/python/analysis/modules/hello/LICENSE +21 -0
  72. package/python/analysis/modules/hello/module.json +46 -0
  73. package/python/analysis/modules/hello/module.py +56 -0
  74. package/python/worker.py +152 -5
  75. package/selected-skills/routing.js +5 -2
  76. package/watchlist/package.json +1 -1
package/python/worker.py CHANGED
@@ -1,8 +1,9 @@
1
1
  """Private Python runtime worker.
2
2
 
3
3
  Subcommands:
4
- probe Print one JSON line describing the interpreter and imported libraries.
5
- run Execute <run-dir>/analysis.py with the private interpreter.
4
+ probe Print one JSON line describing the interpreter and imported libraries.
5
+ run Execute <run-dir>/analysis.py with the private interpreter.
6
+ analysis Import one reviewed analysis module and call analyze(request, context).
6
7
 
7
8
  This file uses the standard library only. Third-party imports are resolved from the
8
9
  explicit --site-packages paths supplied by the host; no pip/venv is involved.
@@ -15,6 +16,7 @@ import json
15
16
  import os
16
17
  from pathlib import Path
17
18
  import platform
19
+ import re
18
20
  import runpy
19
21
  import sys
20
22
  import time
@@ -133,11 +135,147 @@ def run(run_dir: Path) -> int:
133
135
  result_path.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
134
136
 
135
137
 
138
+ def analysis(
139
+ run_dir: Path,
140
+ module_dir: Path,
141
+ entrypoint: str,
142
+ inputs_dir: Path,
143
+ capabilities: list[str],
144
+ limits: dict,
145
+ ) -> int:
146
+ """Run one module from the reviewed registry and write <run-dir>/result.json.
147
+
148
+ The module only ever sees `analyze(request, context)`; the context is the entire execution surface
149
+ (staged inputs, output files, a log). It is not a sandbox — the real control is that modules ship
150
+ with the package and are reviewed, and that the registry is a static whitelist.
151
+ """
152
+ import importlib.util
153
+
154
+ run_dir = run_dir.resolve()
155
+ module_dir = module_dir.resolve()
156
+ inputs_dir = inputs_dir.resolve()
157
+ started = time.time()
158
+ result_path = run_dir / "result.json"
159
+ max_output_bytes = int(limits.get("max_output_bytes", 1048576))
160
+ max_log_bytes = int(limits.get("max_log_bytes", 65536))
161
+ max_input_rows = int(limits.get("max_input_rows", 200000))
162
+ outputs_dir = run_dir / "outputs"
163
+ logs_dir = run_dir / "logs"
164
+ log_path = logs_dir / "module.log"
165
+ log_truncated = False
166
+
167
+ def write_result(payload: dict) -> None:
168
+ result_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8")
169
+
170
+ def log_line(message: object) -> None:
171
+ nonlocal log_truncated
172
+ logs_dir.mkdir(parents=True, exist_ok=True)
173
+ text = log_path.read_text(encoding="utf-8") if log_path.exists() else ""
174
+ line = f"{message}\n"
175
+ if len((text + line).encode("utf-8")) > max_log_bytes:
176
+ log_truncated = True
177
+ return
178
+ log_path.write_text(text + line, encoding="utf-8")
179
+
180
+ class Context:
181
+ def read_dataset(self, dataset_id: str) -> dict:
182
+ if "dataset.read" not in capabilities:
183
+ raise PermissionError(f"module did not declare dataset.read (dataset {dataset_id})")
184
+ path = inputs_dir / "datasets" / f"{dataset_id}.json"
185
+ if not inside(inputs_dir, path) or not path.is_file():
186
+ raise FileNotFoundError(f"dataset {dataset_id} is not staged in this snapshot")
187
+ view = json.loads(path.read_text(encoding="utf-8"))
188
+ rows = view.get("rows") or []
189
+ if len(rows) > max_input_rows:
190
+ view["rows"] = rows[:max_input_rows]
191
+ view["truncated"] = True
192
+ return view
193
+
194
+ def read_profile(self, profile_id: str) -> dict:
195
+ if "profile.read" not in capabilities:
196
+ raise PermissionError(f"module did not declare profile.read (profile {profile_id})")
197
+ path = inputs_dir / "profiles" / f"{profile_id}.json"
198
+ if not inside(inputs_dir, path) or not path.is_file():
199
+ raise FileNotFoundError(f"profile {profile_id} is not staged in this snapshot")
200
+ return json.loads(path.read_text(encoding="utf-8"))
201
+
202
+ def read_evidence(self, evidence_id: str) -> dict:
203
+ if "evidence.read" not in capabilities:
204
+ raise PermissionError(f"module did not declare evidence.read (evidence {evidence_id})")
205
+ path = inputs_dir / "evidence" / f"{evidence_id}.json"
206
+ if not inside(inputs_dir, path) or not path.is_file():
207
+ raise FileNotFoundError(f"evidence {evidence_id} is not in this snapshot")
208
+ return json.loads(path.read_text(encoding="utf-8"))
209
+
210
+ def write_output(self, name: str, value: object) -> str:
211
+ if not isinstance(name, str) or not re.fullmatch(r"[a-z0-9_]{1,64}", name):
212
+ raise ValueError(f"output name is invalid: {name!r}")
213
+ payload = json.dumps(value, ensure_ascii=False, allow_nan=False)
214
+ if len(payload.encode("utf-8")) > max_output_bytes:
215
+ raise ValueError(f"output {name} exceeds max_output_bytes ({max_output_bytes})")
216
+ outputs_dir.mkdir(parents=True, exist_ok=True)
217
+ (outputs_dir / f"{name}.json").write_text(payload + "\n", encoding="utf-8")
218
+ return f"output:{name}"
219
+
220
+ def log(self, message: object) -> None:
221
+ log_line(message)
222
+
223
+ try:
224
+ request = json.loads((run_dir / "request.json").read_text(encoding="utf-8"))
225
+ module_path = (module_dir / entrypoint).resolve()
226
+ if not inside(module_dir, module_path) or not module_path.is_file():
227
+ raise FileNotFoundError(f"module entrypoint not found: {module_path}")
228
+ spec = importlib.util.spec_from_file_location("capital_analysis_module", module_path)
229
+ if spec is None or spec.loader is None:
230
+ raise ImportError(f"cannot import {module_path}")
231
+ module = importlib.util.module_from_spec(spec)
232
+ spec.loader.exec_module(module)
233
+ analyze = getattr(module, "analyze", None)
234
+ if not callable(analyze):
235
+ raise TypeError("module.py must define analyze(request, context)")
236
+ returned = analyze(request, Context())
237
+ if not isinstance(returned, dict):
238
+ raise TypeError(f"analyze() must return a dict, got {type(returned).__name__}")
239
+ write_result({
240
+ "ok": True,
241
+ "python": platform.python_version(),
242
+ "durationMs": int((time.time() - started) * 1000),
243
+ "logTruncated": log_truncated,
244
+ "result": returned,
245
+ })
246
+ return 0
247
+ except BaseException as error: # noqa: BLE001 - the wrapper must report any module failure
248
+ # A reviewed module may declare a stable protocol code on its exception; anything else is a
249
+ # module crash and must not be able to impersonate an analysis error code.
250
+ declared = getattr(error, "analysis_code", None)
251
+ failure = {
252
+ "code": declared if isinstance(declared, str) and declared.startswith("analysis_") else "MODULE_ERROR",
253
+ "type": type(error).__name__,
254
+ "message": str(error),
255
+ "traceback": traceback.format_exc()[-8192:],
256
+ }
257
+ try:
258
+ write_result({
259
+ "ok": False,
260
+ "python": platform.python_version(),
261
+ "durationMs": int((time.time() - started) * 1000),
262
+ "error": failure,
263
+ })
264
+ except BaseException: # noqa: BLE001 - a NaN in the result must still leave a report
265
+ result_path.write_text(json.dumps({"ok": False, "error": failure}, ensure_ascii=False) + "\n", encoding="utf-8")
266
+ return 1
267
+
268
+
136
269
  def main() -> int:
137
270
  parser = argparse.ArgumentParser(description=__doc__)
138
- parser.add_argument("command", choices=("probe", "run"))
271
+ parser.add_argument("command", choices=("probe", "run", "analysis"))
139
272
  parser.add_argument("--site-packages", action="append", default=[])
140
273
  parser.add_argument("--run-dir", type=Path)
274
+ parser.add_argument("--module-dir", type=Path)
275
+ parser.add_argument("--inputs-dir", type=Path)
276
+ parser.add_argument("--entrypoint", default="module.py")
277
+ parser.add_argument("--capabilities", default="")
278
+ parser.add_argument("--limits", default="{}")
141
279
  args = parser.parse_args()
142
280
 
143
281
  if args.command == "probe":
@@ -145,9 +283,18 @@ def main() -> int:
145
283
  return 0
146
284
 
147
285
  if args.run_dir is None:
148
- parser.error("run requires --run-dir")
286
+ parser.error(f"{args.command} requires --run-dir")
149
287
  add_site_packages(args.site_packages)
150
- return run(args.run_dir)
288
+ if args.command == "run":
289
+ return run(args.run_dir)
290
+ if args.module_dir is None or args.inputs_dir is None:
291
+ parser.error("analysis requires --module-dir and --inputs-dir")
292
+ try:
293
+ limits = json.loads(args.limits)
294
+ except json.JSONDecodeError as error:
295
+ parser.error(f"--limits is not valid JSON: {error}")
296
+ capabilities = [item for item in args.capabilities.split(",") if item]
297
+ return analysis(args.run_dir, args.module_dir, args.entrypoint, args.inputs_dir, capabilities, limits)
151
298
 
152
299
 
153
300
  if __name__ == "__main__":
@@ -14,8 +14,11 @@ export const SELECTED_SKILL_ROLES = Object.freeze({
14
14
  web_retriever: Object.freeze({ zh: '检索与取证', en: 'Retrieval & evidence' }),
15
15
  })
16
16
 
17
- /** `data_analyst` is reserved; until it is enabled it executes the data_junior method set. */
18
- export const SELECTED_SKILL_ROLE_ALIASES = Object.freeze({ data_analyst: 'data_junior' })
17
+ /** `senior_analyst` (formerly `data_analyst`) executes the data_junior method set until its own routing lands. */
18
+ export const SELECTED_SKILL_ROLE_ALIASES = Object.freeze({
19
+ data_analyst: 'data_junior',
20
+ senior_analyst: 'data_junior',
21
+ })
19
22
 
20
23
  /**
21
24
  * Settings-card preset names. These are the five cards a user can pick in the
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@v587d/watchlist",
3
- "version": "2.30.0",
3
+ "version": "2.31.0",
4
4
  "description": "自动模式的用户自选股(宿主级清单 + Fuyao 报价快照 + /capital-watchlist 路由 + 输入框菜单弹窗):由 @v587d/capital-generation 随包携带并作为 host 平面行挂载。",
5
5
  "license": "MIT",
6
6
  "type": "module",