@weaxs/dsh-stock-analysis 0.2.11 → 0.2.13

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 (50) hide show
  1. package/README.md +37 -83
  2. package/dist/client.js +14 -1
  3. package/dist/index.js +3897 -2694
  4. package/dist/web/app.js +84 -39
  5. package/dist/web/index.html +6 -2
  6. package/dist/web/style.css +10 -4
  7. package/package.json +1 -1
  8. package/scripts/cli-json.mjs +23 -0
  9. package/scripts/exec-process.mjs +89 -0
  10. package/scripts/setup-python.mjs +37 -4
  11. package/scripts/tool-calls.mjs +493 -0
  12. package/skills/bull-trend/SKILL.md +2 -2
  13. package/skills/bull-trend/references/fat-tails.md +76 -3
  14. package/skills/bull-trend/scripts/tail_analysis.py +92 -3
  15. package/skills/event-driven/SKILL.md +2 -2
  16. package/skills/growth-quality/SKILL.md +1 -1
  17. package/skills/market-review/SKILL.md +1 -0
  18. package/skills/stock-analysis/SKILL.md +12 -7
  19. package/skills/stock-analysis/references/stateless-analysis.md +9 -1
  20. package/skills/stock-screener/SKILL.md +1 -1
  21. package/skills/strategy-backtest/SKILL.md +1 -1
  22. package/tools/_cache.py +13 -0
  23. package/tools/_subproc.py +46 -0
  24. package/tools/alert_rules.py +2 -2
  25. package/tools/backtest.py +3 -3
  26. package/tools/capabilities.py +33 -9
  27. package/tools/cli_budgets.json +1 -0
  28. package/tools/credit_data.py +293 -0
  29. package/tools/diagnostics.py +3 -4
  30. package/tools/gather.py +2 -6
  31. package/tools/import_parser.py +3 -4
  32. package/tools/lixinger.py +119 -27
  33. package/tools/market_regime.py +5 -2
  34. package/tools/market_review.py +5 -6
  35. package/tools/name_resolver.py +45 -33
  36. package/tools/report_renderer.py +3 -3
  37. package/tools/requirements.txt +5 -4
  38. package/tools/risk_screening.py +3 -2
  39. package/tools/screener.py +41 -30
  40. package/tools/search_intel.py +79 -10
  41. package/tools/sec_edgar.py +268 -1
  42. package/tools/sec_holders.py +6 -0
  43. package/tools/signal_tracker.py +5 -5
  44. package/tools/stateless_analysis.py +132 -19
  45. package/tools/stock_data.py +1020 -817
  46. package/tools/tiaa_disclosures.py +4 -0
  47. package/tools/tool_schemas.json +2734 -0
  48. package/tools/trading_calendar.py +65 -30
  49. package/tools/value_data.py +423 -175
  50. package/tools/watchlist.py +43 -5
package/dist/web/app.js CHANGED
@@ -2,7 +2,7 @@
2
2
  (() => {
3
3
  // dsh/web/app.ts
4
4
  var POLL_IDLE = 15e3;
5
- var POLL_BUSY = 1500;
5
+ var POLL_BUSY = 5e3;
6
6
  var REQUEST_TIMEOUT = 15e3;
7
7
  var CACHE_KEY = "stock-dashboard:v2:snapshot";
8
8
  var PREF_KEY = "stock-dashboard:v2:prefs";
@@ -41,10 +41,15 @@
41
41
  prices: /* @__PURE__ */ new Map(),
42
42
  pollTimer: void 0,
43
43
  inflight: false,
44
+ // A poll requested while one is in flight (e.g. right after a watchlist edit) runs once that one ends.
45
+ dirty: false,
44
46
  saving: false,
45
47
  error: null,
46
48
  lastOk: 0,
47
- fromCache: false
49
+ fromCache: false,
50
+ signature: "",
51
+ // Set by the dsh shell when its plugin manager can open this bundle's page (with its Update button).
52
+ pluginPage: false
48
53
  };
49
54
  function $(id) {
50
55
  const node = document.getElementById(id);
@@ -250,9 +255,29 @@
250
255
  node.append(el("span", "live"), document.createTextNode(`${open.map((region) => REGION_NAMES[region]).join("\u3001")}\u4EA4\u6613\u4E2D \xB7 `));
251
256
  }
252
257
  node.append(document.createTextNode(state.fromCache ? "\u663E\u793A\u4E0A\u6B21\u6570\u636E\uFF0C\u6B63\u5728\u66F4\u65B0\u2026" : `${clock(state.lastOk, true)} \u5DF2\u540C\u6B65`));
258
+ if (!state.fromCache && [...snap.ribbon || [], ...snap.market.indices].some(isStale)) {
259
+ node.append(document.createTextNode(" \xB7 "), el("span", "warn", "\u90E8\u5206\u6307\u6570\u66F4\u65B0\u5931\u8D25"));
260
+ }
253
261
  if (!state.fromCache && snap.pending > 0) node.append(document.createTextNode(` \xB7 \u540E\u53F0\u66F4\u65B0 ${snap.pending} \u9879`));
254
262
  $("refresh").classList.toggle("busy", !state.fromCache && snap.pending > 0);
255
263
  }
264
+ function isStale(row) {
265
+ return Boolean(row.error && row.quote);
266
+ }
267
+ function renderVersion() {
268
+ const plugin = state.snap?.plugin;
269
+ $("version").textContent = plugin ? `${plugin.name} v${plugin.version}` : "";
270
+ const update = $("update");
271
+ update.hidden = !plugin?.latest;
272
+ if (!plugin?.latest) return;
273
+ $("update-version").textContent = `\u2191 v${plugin.latest}`;
274
+ const tip = `\u65B0\u7248\u672C v${plugin.latest} \u5DF2\u53D1\u5E03\uFF08\u5F53\u524D v${plugin.version}\uFF09\uFF0C${state.pluginPage ? "\u70B9\u51FB\u524D\u5F80\u63D2\u4EF6\u9875\u66F4\u65B0" : "\u70B9\u51FB\u67E5\u770B\u53D1\u5E03\u8BF4\u660E"}`;
275
+ update.title = tip;
276
+ update.setAttribute("aria-label", tip);
277
+ }
278
+ function staleTitle(row) {
279
+ return `\u66F4\u65B0\u5931\u8D25\uFF0C\u663E\u793A\u4E0A\u6B21\u62A5\u4EF7${row.updatedAt ? `\uFF08${clock(row.updatedAt)}\uFF09` : ""}`;
280
+ }
256
281
  function groupByRegion(list) {
257
282
  const groups = /* @__PURE__ */ new Map();
258
283
  for (const item of list) {
@@ -291,6 +316,10 @@
291
316
  el("span", `tile-price ${dir(row.quote.change_pct)}`, fmtPrice(row.quote.price, 2)),
292
317
  el("span", `tile-pct ${dir(row.quote.change_pct)}`, fmtPct(row.quote.change_pct))
293
318
  );
319
+ if (isStale(row)) {
320
+ tile.classList.add("is-stale");
321
+ tile.title = staleTitle(row);
322
+ }
294
323
  } else if (row.loading) {
295
324
  tile.append(skeleton(64), skeleton(40));
296
325
  } else {
@@ -331,36 +360,27 @@
331
360
  function statsCounts(stats) {
332
361
  return [num(stats.up_count) ?? 0, num(stats.flat_count) ?? 0, num(stats.down_count) ?? 0];
333
362
  }
363
+ var BREADTH_REGIONS = ["cn", "hk", "us"];
334
364
  function renderPulse() {
335
365
  const node = $("pulse");
336
366
  node.replaceChildren();
337
- const slot = state.snap?.stats;
338
- const stats = slot?.value;
339
- node.append(el("span", "label", "A\u80A1"));
340
- if (!slot || !stats) {
341
- node.append(el("span", "", slot?.error && !slot.loading ? "\u5168\u5E02\u573A\u6DA8\u8DCC\u7EDF\u8BA1\u6682\u65F6\u5931\u8D25\uFF0C\u7A0D\u540E\u81EA\u52A8\u91CD\u8BD5" : "\u6B63\u5728\u7EDF\u8BA1\u5168\u5E02\u573A\u6DA8\u8DCC\uFF0C\u9996\u6B21\u7EA6\u9700 15\u201360 \u79D2\u2026"));
342
- return;
367
+ for (const region of BREADTH_REGIONS) {
368
+ const slot = state.snap?.stats?.[region];
369
+ const stats = slot?.value;
370
+ const group = el("span", "breadth");
371
+ group.append(el("span", "label", REGION_NAMES[region]));
372
+ if (!stats) {
373
+ group.append(el("span", "", slot?.error && !slot.loading ? "\u6682\u4E0D\u53EF\u7528" : "\u7EDF\u8BA1\u4E2D\u2026"));
374
+ } else {
375
+ const [up, flat, down] = statsCounts(stats);
376
+ const upText = el("span", "up", "\u6DA8 ");
377
+ upText.append(el("strong", "up", up));
378
+ const downText = el("span", "down", "\u8DCC ");
379
+ downText.append(el("strong", "down", down));
380
+ group.append(upText, breadthBar(up, flat, down), downText);
381
+ }
382
+ node.append(group);
343
383
  }
344
- const [up, flat, down] = statsCounts(stats);
345
- const breadth = el("span", "breadth");
346
- const upText = el("span", "up", "\u6DA8 ");
347
- upText.append(el("strong", "up", up));
348
- const downText = el("span", "down", "\u8DCC ");
349
- downText.append(el("strong", "down", down));
350
- breadth.append(upText, breadthBar(up, flat, down), downText);
351
- const item = (label, value, cls = "") => {
352
- const span = el("span", "", `${label} `);
353
- span.append(el("strong", cls, value));
354
- return span;
355
- };
356
- node.append(
357
- breadth,
358
- item("\u6DA8\u505C", num(stats.limit_up_count) ?? "\u2014", "up"),
359
- item("\u8DCC\u505C", num(stats.limit_down_count) ?? "\u2014", "down"),
360
- item("\u4E2D\u4F4D\u6570", fmtPct(stats.median_change_pct), dir(stats.median_change_pct)),
361
- item("\u6210\u4EA4\u989D", fmtAmount(stats.total_turnover))
362
- );
363
- if (slot.updatedAt) node.append(el("span", "", `\u7EDF\u8BA1\u4E8E ${clock(slot.updatedAt)}`));
364
384
  }
365
385
  function renderFilters() {
366
386
  const node = $("filters");
@@ -558,6 +578,10 @@
558
578
  if (row.quote && num(row.quote.price) !== null) {
559
579
  price.textContent = fmtPrice(row.quote.price, 2);
560
580
  pct.textContent = `${fmtSigned(row.quote.change, 2)} ${fmtPct(row.quote.change_pct)}`;
581
+ if (isStale(row)) {
582
+ tr.classList.add("is-stale");
583
+ tr.title = staleTitle(row);
584
+ }
561
585
  } else if (row.loading) {
562
586
  price.append(skeleton(64));
563
587
  pct.append(skeleton(80));
@@ -576,7 +600,7 @@
576
600
  node.append(table);
577
601
  return node;
578
602
  }
579
- function statsPanel(slot) {
603
+ function statsPanel(region, slot) {
580
604
  const stats = slot?.value;
581
605
  const node = panel("\u6DA8\u8DCC\u5206\u5E03", slot?.updatedAt ? `\u7EDF\u8BA1\u4E8E ${clock(slot.updatedAt)}` : "");
582
606
  if (!stats) {
@@ -589,12 +613,11 @@
589
613
  legend.append(el("span", "up", `\u4E0A\u6DA8 ${up}`), el("span", "flat", `\u5E73\u76D8 ${flat}`), el("span", "down", `\u4E0B\u8DCC ${down}`));
590
614
  wide.append(breadthBar(up, flat, down), legend);
591
615
  const list = el("dl", "stats");
616
+ const aShare = region === "cn";
592
617
  const rows = [
593
- ["\u6DA8\u505C", num(stats.limit_up_count) ?? "\u2014", "up"],
594
- ["\u8DCC\u505C", num(stats.limit_down_count) ?? "\u2014", "down"],
595
- ["\u5E73\u5747\u6DA8\u5E45", fmtPct(stats.avg_change_pct), dir(stats.avg_change_pct)],
618
+ ...aShare ? [["\u6DA8\u505C", num(stats.limit_up_count) ?? "\u2014", "up"], ["\u8DCC\u505C", num(stats.limit_down_count) ?? "\u2014", "down"]] : [],
596
619
  ["\u6DA8\u5E45\u4E2D\u4F4D\u6570", fmtPct(stats.median_change_pct), dir(stats.median_change_pct)],
597
- ["\u603B\u6210\u4EA4\u989D", fmtAmount(stats.total_turnover), ""],
620
+ ...aShare ? [["\u603B\u6210\u4EA4\u989D", fmtAmount(stats.total_turnover), ""]] : [],
598
621
  ["\u7EDF\u8BA1\u80A1\u7968", num(stats.total_stocks) ?? up + flat + down, ""]
599
622
  ];
600
623
  for (const [label, value, cls] of rows) {
@@ -647,7 +670,8 @@
647
670
  if (!value) continue;
648
671
  list.append(el("dt", "", label), el("dd", "", value));
649
672
  }
650
- body.append(list, el("p", "", `\u5168\u5E02\u573A\u6DA8\u8DCC\u5206\u5E03\u4E0E\u884C\u4E1A\u6392\u884C\u76EE\u524D\u53EA\u6709 A \u80A1\u6570\u636E\uFF0C${REGION_NAMES[region]}\u6682\u4E0D\u63D0\u4F9B\uFF0C\u4E0D\u7528\u6307\u6570\u6DA8\u8DCC\u4EE3\u66FF\u3002`));
673
+ const missing = BREADTH_REGIONS.includes(region) ? "\u884C\u4E1A\u6392\u884C" : "\u5168\u5E02\u573A\u6DA8\u8DCC\u5206\u5E03\u4E0E\u884C\u4E1A\u6392\u884C";
674
+ body.append(list, el("p", "", `${missing}\u76EE\u524D\u53EA\u6709 A \u80A1\u6570\u636E\uFF0C${REGION_NAMES[region]}\u6682\u4E0D\u63D0\u4F9B\uFF0C\u4E0D\u7528\u6307\u6570\u6DA8\u8DCC\u4EE3\u66FF\u3002`));
651
675
  node.append(body);
652
676
  return node;
653
677
  }
@@ -666,13 +690,16 @@
666
690
  const phase = snap.phases?.[state.region];
667
691
  body.append(indexPanel(market, phase));
668
692
  const side = el("div", "side");
669
- if (state.region === "cn") side.append(statsPanel(snap.stats), sectorsPanel(snap.sectors));
693
+ if (state.region === "cn") side.append(statsPanel("cn", snap.stats?.cn), sectorsPanel(snap.sectors));
694
+ else if (BREADTH_REGIONS.includes(state.region)) side.append(statsPanel(state.region, snap.stats?.[state.region]), sessionPanel(state.region, phase));
670
695
  else side.append(sessionPanel(state.region, phase));
671
696
  body.append(side);
672
697
  }
673
698
  function render(flash = /* @__PURE__ */ new Map()) {
699
+ $("tip").hidden = true;
674
700
  $("watch-count").textContent = state.snap ? `${state.snap.watchlist.length} / 30` : "";
675
701
  renderStatus();
702
+ renderVersion();
676
703
  renderRibbon();
677
704
  renderPulse();
678
705
  renderFilters();
@@ -700,23 +727,34 @@
700
727
  }
701
728
  async function poll() {
702
729
  clearTimeout(state.pollTimer);
703
- if (state.inflight) return;
730
+ if (state.inflight) {
731
+ state.dirty = true;
732
+ return;
733
+ }
704
734
  state.inflight = true;
735
+ state.dirty = false;
705
736
  const region = state.region;
706
737
  try {
707
738
  const snap = await api(`./api/snapshot?region=${encodeURIComponent(region)}`);
708
739
  state.error = null;
709
740
  state.lastOk = Date.now();
710
741
  if (region === state.region) {
711
- applySnapshot(snap);
712
- writeJson(CACHE_KEY, { savedAt: Date.now(), snap });
742
+ const signature = JSON.stringify({ ...snap, fetchedAt: null, pending: null });
743
+ if (signature === state.signature && !state.fromCache) {
744
+ state.snap = snap;
745
+ renderStatus();
746
+ } else {
747
+ state.signature = signature;
748
+ applySnapshot(snap);
749
+ writeJson(CACHE_KEY, { savedAt: Date.now(), snap });
750
+ }
713
751
  }
714
752
  } catch (error) {
715
753
  state.error = error.message;
716
754
  renderStatus();
717
755
  } finally {
718
756
  state.inflight = false;
719
- if (region !== state.region) void poll();
757
+ if (region !== state.region || state.dirty) void poll();
720
758
  else schedule();
721
759
  }
722
760
  }
@@ -848,12 +886,19 @@
848
886
  const message = event.data;
849
887
  if (!message || message.type !== "stock-analysis:theme" || message.scheme !== "light" && message.scheme !== "dark") return;
850
888
  document.documentElement.dataset.theme = message.scheme;
889
+ state.pluginPage = message.pluginPage === true;
890
+ renderVersion();
851
891
  for (const key of ["bg", "surface", "surfaceSubtle", "text", "muted", "border", "accent", "onAccent"]) {
852
892
  const value = message.palette?.[key];
853
893
  const property = key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
854
894
  if (typeof value === "string" && value.length < 300) document.documentElement.style.setProperty(`--${property}`, value);
855
895
  }
856
896
  });
897
+ $("update").addEventListener("click", (event) => {
898
+ if (!state.pluginPage) return;
899
+ event.preventDefault();
900
+ window.parent.postMessage({ type: "stock-analysis:open-plugin" }, location.origin);
901
+ });
857
902
  document.addEventListener("visibilitychange", () => {
858
903
  if (document.visibilityState === "visible") void poll();
859
904
  else clearTimeout(state.pollTimer);
@@ -18,6 +18,10 @@
18
18
  </div>
19
19
  <p id="status" class="status" role="status" aria-live="polite">正在连接行情服务…</p>
20
20
  <div class="bar-actions">
21
+ <a id="update" class="update-pill" href="https://github.com/Weaxs/stock-analysis-plugin/releases/latest" target="_blank" rel="noreferrer" hidden>
22
+ <span class="update-label">新版本</span>
23
+ <span id="update-version" class="update-version"></span>
24
+ </a>
21
25
  <button id="refresh" class="btn ghost" type="button" title="立即刷新全部行情">
22
26
  <svg class="refresh-icon" viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6v5h-5"/><path d="M18.4 15a7 7 0 1 1-.8-7.8L20 9"/></svg>
23
27
  <span>刷新</span>
@@ -47,7 +51,7 @@
47
51
  <svg viewBox="0 0 20 20" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7.5 4.5L13 10l-5.5 5.5"/></svg>
48
52
  </button>
49
53
  </section>
50
- <div id="pulse" class="pulse" aria-label="A 股市场宽度"></div>
54
+ <div id="pulse" class="pulse" aria-label="A股、港股、美股市场宽度"></div>
51
55
 
52
56
  <section class="watch" aria-labelledby="watch-heading">
53
57
  <h2 id="watch-heading" class="sr-only">自选股行情</h2>
@@ -80,7 +84,7 @@
80
84
  <div id="market-body" class="market-body" role="tabpanel" aria-labelledby="market-heading"></div>
81
85
  </section>
82
86
 
83
- <footer class="foot">报价可能延迟,悬停名称可查看来源与报价时间。交易时段内有页面打开时约每 30 秒更新一次,后台每 5 分钟预热;30 日走势为最近 30 个有效交易日收盘价。</footer>
87
+ <footer class="foot">报价可能延迟,悬停名称可查看来源与报价时间。交易时段内有页面打开时约每 30 秒更新一次,后台每 5 分钟预热;30 日走势为最近 30 个有效交易日收盘价。<span id="version"></span></footer>
84
88
  </div>
85
89
  <div id="tip" class="tip" role="tooltip" hidden></div>
86
90
  </body>
@@ -136,11 +136,11 @@ h1 { font-size: 19px; font-weight: 650; letter-spacing: -.02em; line-height: 1.2
136
136
  .tile-pct { font-size: 12px; font-weight: 600; font-variant-numeric: tabular-nums; }
137
137
  .tile .spark { grid-column: 1 / -1; margin-top: 3px; }
138
138
 
139
- .pulse { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 16px; min-height: 36px; padding: 8px 2px; color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
139
+ .pulse { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 32px; min-height: 36px; padding: 8px 2px; color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
140
140
  .pulse strong { color: var(--text); font-weight: 600; }
141
141
  .pulse .label { color: var(--text); font-weight: 600; }
142
142
  .breadth { display: inline-flex; align-items: center; gap: 8px; }
143
- .breadth-bar { display: flex; width: 180px; height: 6px; border-radius: 3px; overflow: hidden; background: var(--surface-subtle); }
143
+ .breadth-bar { display: flex; width: 140px; height: 6px; border-radius: 3px; overflow: hidden; background: var(--surface-subtle); }
144
144
  .breadth-bar span { display: block; height: 100%; }
145
145
  .breadth-bar .u { background: var(--up); }
146
146
  .breadth-bar .f { background: var(--border); }
@@ -176,6 +176,7 @@ table { width: 100%; border-collapse: collapse; }
176
176
  .code { font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; font-size: 11px; }
177
177
  .tag { padding: 0 4px; border-radius: 3px; background: var(--surface-subtle); font-size: 10.5px; line-height: 16px; }
178
178
  .stale { color: var(--warn); }
179
+ .is-stale .tile-price, .is-stale .tile-pct, .is-stale .iprice, .is-stale .ipct { opacity: .55; }
179
180
  .price { font-size: 15px; font-weight: 650; letter-spacing: -.01em; font-variant-numeric: tabular-nums; border-radius: 5px; }
180
181
  .price.flash-up { animation: flash-up 1.4s cubic-bezier(.16, 1, .3, 1); }
181
182
  .price.flash-down { animation: flash-down 1.4s cubic-bezier(.16, 1, .3, 1); }
@@ -235,8 +236,8 @@ tr:hover .remove, .remove:focus-visible { opacity: 1; }
235
236
  .idx .ipct { text-align: right; font-size: 12.5px; font-weight: 600; font-variant-numeric: tabular-nums; }
236
237
  .idx .ispark { width: 110px; }
237
238
  .side { display: grid; gap: 14px; }
238
- .stats { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1px; margin: 8px 14px 14px; border-radius: 8px; overflow: hidden; background: var(--border); }
239
- .stats div { padding: 8px 10px; background: var(--surface); }
239
+ .stats { display: flex; flex-wrap: wrap; gap: 1px; margin: 8px 14px 14px; border-radius: 8px; overflow: hidden; background: var(--border); }
240
+ .stats div { flex: 1 1 30%; min-width: 0; padding: 8px 10px; background: var(--surface); }
240
241
  .stats dt { color: var(--muted); font-size: 11px; }
241
242
  .stats dd { margin: 2px 0 0; font-size: 15px; font-weight: 650; font-variant-numeric: tabular-nums; }
242
243
  .breadth-wide { padding: 6px 14px 0; }
@@ -256,6 +257,11 @@ tr:hover .remove, .remove:focus-visible { opacity: 1; }
256
257
  .session dd { margin: 0; color: var(--text); font-variant-numeric: tabular-nums; }
257
258
  .panel-note { padding: 14px; color: var(--muted); font-size: 12px; }
258
259
  .foot { margin-top: 16px; color: var(--muted); font-size: 11px; max-width: 110ch; }
260
+ .foot #version:not(:empty)::before { content: " · "; }
261
+ .update-pill { align-self: center; display: inline-flex; align-items: center; gap: 6px; height: 22px; padding: 0 10px; border-radius: 999px; border: 1px solid var(--border); background: var(--surface-subtle); color: inherit; font-size: 12px; text-decoration: none; white-space: nowrap; transition: border-color .16s ease; }
262
+ .update-pill:hover { border-color: var(--warn); }
263
+ .update-label { color: var(--muted); }
264
+ .update-version { color: var(--warn); font-weight: 600; font-variant-numeric: tabular-nums; }
259
265
 
260
266
  .tip { position: fixed; z-index: 10; padding: 6px 9px; border-radius: 7px; background: var(--text); color: var(--bg); font-size: 11.5px; line-height: 1.45; white-space: nowrap; pointer-events: none; box-shadow: var(--shadow); font-variant-numeric: tabular-nums; }
261
267
  .tip b { font-weight: 650; }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@weaxs/dsh-stock-analysis",
3
- "version": "0.2.11",
3
+ "version": "0.2.13",
4
4
  "description": "DeepSeek Harness (dsh) plugin for stock analysis, screening, and strategy backtesting across A/HK/US/JP/KR/TW markets",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -0,0 +1,23 @@
1
+ // Shared host-side CLI result rules; every adapter must surface failures the same way.
2
+ export const failureMessage = (error) =>
3
+ error.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" ? "Python command output exceeded buffer limit"
4
+ : error.killed ? "Python command timed out"
5
+ : typeof error.code === "number" ? `Python command failed (exit ${error.code}); check interpreter/dependencies`
6
+ : "Python command failed; check interpreter/dependencies";
7
+
8
+ // Failed, empty, or non-JSON CLI output becomes a JSON error; a CLI-provided JSON error is kept.
9
+ export function cliJson(stdout, failure) {
10
+ try {
11
+ const data = JSON.parse(stdout);
12
+ if (!failure || (data && typeof data.error === "string")) return stdout;
13
+ } catch {
14
+ failure ??= stdout.trim() ? "Python command returned non-JSON output" : "Python command returned no JSON";
15
+ }
16
+ return JSON.stringify({ error: failure });
17
+ }
18
+
19
+ // Explicit null optional args would otherwise reach argv as "null"; dropping them applies defaults.
20
+ export const withoutNulls = (params) =>
21
+ params && typeof params === "object" && !Array.isArray(params)
22
+ ? Object.fromEntries(Object.entries(params).filter(([, value]) => value !== null))
23
+ : params;
@@ -0,0 +1,89 @@
1
+ import * as cp from "node:child_process";
2
+
3
+ function terminateTree(child) {
4
+ if (!child.pid) return;
5
+ if (process.platform === "win32") {
6
+ cp.execFile("taskkill", ["/F", "/T", "/PID", String(child.pid)], { timeout: 10_000 }, () => {});
7
+ return;
8
+ }
9
+ try {
10
+ process.kill(-child.pid, "SIGKILL");
11
+ } catch {
12
+ try { child.kill("SIGKILL"); } catch { /* already exited */ }
13
+ }
14
+ }
15
+
16
+ function failure(stdout, code, extra = {}) {
17
+ return Object.assign(new Error("Python command failed"), { stdout, code, ...extra });
18
+ }
19
+
20
+ // POSIX children run in their own session, so the host's terminal hangup no longer reaches them.
21
+ const live = new Set();
22
+ process.on("exit", () => { for (const child of live) terminateTree(child); });
23
+
24
+ /** execFile-compatible stdout collection that also terminates nested CLI children.
25
+ * @param {string} bin
26
+ * @param {string[]} argv
27
+ * @param {{timeoutMs?: number, maxBuffer?: number, signal?: AbortSignal}} [options]
28
+ */
29
+ export function execFileTree(bin, argv, { timeoutMs, maxBuffer = 32 * 1024 * 1024, signal } = {}) {
30
+ if (signal?.aborted) {
31
+ return Promise.reject(Object.assign(new Error("The operation was aborted"), { name: "AbortError", stdout: "" }));
32
+ }
33
+ return new Promise((resolve, reject) => {
34
+ const child = cp.spawn(bin, argv, {
35
+ detached: process.platform !== "win32",
36
+ stdio: ["ignore", "pipe", "ignore"],
37
+ windowsHide: true,
38
+ });
39
+ live.add(child);
40
+ const chunks = [];
41
+ const stdout = () => Buffer.concat(chunks).toString("utf8");
42
+ let bytes = 0;
43
+ let settled = false;
44
+ let timedOut = false;
45
+ let aborted = false;
46
+ let overflow = false;
47
+
48
+ const finish = (error) => {
49
+ if (settled) return;
50
+ settled = true;
51
+ if (timer) clearTimeout(timer);
52
+ signal?.removeEventListener("abort", onAbort);
53
+ if (error) reject(error);
54
+ else resolve(stdout());
55
+ };
56
+ const onAbort = () => {
57
+ aborted = true;
58
+ terminateTree(child);
59
+ };
60
+ signal?.addEventListener("abort", onAbort, { once: true });
61
+ const timer = timeoutMs > 0 ? setTimeout(() => {
62
+ timedOut = true;
63
+ terminateTree(child);
64
+ }, timeoutMs) : null;
65
+ timer?.unref();
66
+
67
+ child.stdout.on("data", chunk => {
68
+ if (bytes + chunk.length > maxBuffer) {
69
+ overflow = true;
70
+ terminateTree(child);
71
+ return;
72
+ }
73
+ bytes += chunk.length;
74
+ chunks.push(chunk);
75
+ });
76
+ child.on("error", error => {
77
+ error.stdout = stdout();
78
+ finish(error);
79
+ });
80
+ child.on("close", code => {
81
+ live.delete(child);
82
+ if (overflow) finish(failure(stdout(), "ERR_CHILD_PROCESS_STDIO_MAXBUFFER", { killed: true }));
83
+ else if (timedOut) finish(failure(stdout(), null, { killed: true }));
84
+ else if (aborted) finish(Object.assign(failure(stdout(), null), { name: "AbortError" }));
85
+ else if (code !== 0) finish(failure(stdout(), code));
86
+ else finish();
87
+ });
88
+ });
89
+ }
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { execFileSync } from "node:child_process";
3
- import { existsSync, mkdirSync, renameSync } from "node:fs";
3
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { pythonEnvironmentRoot, venvPythonPath } from "./venv-python.mjs";
@@ -19,6 +19,15 @@ function run(bin, args) {
19
19
  execFileSync(bin, args, { stdio: "inherit", timeout: 1_800_000 });
20
20
  }
21
21
 
22
+ function pipWorks() {
23
+ try {
24
+ execFileSync(venvPython, ["-m", "pip", "--version"], { stdio: "pipe" });
25
+ return true;
26
+ } catch {
27
+ return false;
28
+ }
29
+ }
30
+
22
31
  function findPython() {
23
32
  for (const name of ["python3", "python"]) {
24
33
  try {
@@ -48,11 +57,35 @@ try {
48
57
  mkdirSync(envRoot, { recursive: true });
49
58
  renameSync(join(pkgDir, ".venv"), venvDir);
50
59
  }
51
- if (!existsSync(venvDir)) {
52
- run(python, ["-m", "venv", venvDir]);
60
+ // A half-built venv (e.g. Debian without python3-venv) leaves python but no pip; rebuild it.
61
+ if (!existsSync(venvDir) || !pipWorks()) {
62
+ try {
63
+ run(python, ["-m", "venv", "--clear", venvDir]);
64
+ } catch (err) {
65
+ rmSync(venvDir, { recursive: true, force: true });
66
+ throw err;
67
+ }
53
68
  }
54
69
 
55
- run(venvPython, ["-m", "pip", "install", "-q", "-r", requirements]);
70
+ try {
71
+ run(venvPython, ["-m", "pip", "install", "-q", "-r", requirements]);
72
+ } catch {
73
+ // A failover provider without a wheel for this platform must not block the core tools.
74
+ const lines = readFileSync(requirements, "utf8").split(/\r?\n/).map(line => line.trim());
75
+ const marker = lines.findIndex(line => line.startsWith("# optional providers"));
76
+ const specs = list => list.filter(line => line && !line.startsWith("#"));
77
+ const core = specs(marker < 0 ? lines : lines.slice(0, marker));
78
+ if (core.length) run(venvPython, ["-m", "pip", "install", "-q", ...core]);
79
+ const skipped = specs(marker < 0 ? [] : lines.slice(marker + 1)).filter(spec => {
80
+ try {
81
+ run(venvPython, ["-m", "pip", "install", "-q", spec]);
82
+ return false;
83
+ } catch {
84
+ return true;
85
+ }
86
+ });
87
+ if (skipped.length) console.warn(`[stock-analysis-plugin] optional providers skipped: ${skipped.join(", ")}`);
88
+ }
56
89
  } catch (err) {
57
90
  console.warn(
58
91
  `\n[pi-stock-analysis] Python setup failed: ${err.message}\n` +