@dsh-ft/dsh-fft-paper-trading 0.7.0 → 0.7.2
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/lib/client.js +9 -1
- package/package.json +2 -5
- package/src/client/index.js +8 -0
- package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +0 -564
- package/node_modules/@ftshare-lab/dsh-kline/LICENSE +0 -21
- package/node_modules/@ftshare-lab/dsh-kline/PROVENANCE.md +0 -13
- package/node_modules/@ftshare-lab/dsh-kline/README.en.md +0 -265
- package/node_modules/@ftshare-lab/dsh-kline/README.md +0 -281
- package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +0 -686
- package/node_modules/@ftshare-lab/dsh-kline/config/basic-symbols.json +0 -570
- package/node_modules/@ftshare-lab/dsh-kline/config/dsh-kline.patch.yml +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/config/dsh-tool-catalog.json +0 -3783
- package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +0 -33
- package/node_modules/@ftshare-lab/dsh-kline/core/__init__.py +0 -0
- package/node_modules/@ftshare-lab/dsh-kline/core/adjustment.py +0 -16
- package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +0 -683
- package/node_modules/@ftshare-lab/dsh-kline/core/rows.py +0 -228
- package/node_modules/@ftshare-lab/dsh-kline/core/ta_engine.py +0 -99
- package/node_modules/@ftshare-lab/dsh-kline/lib/candle-sequence.js +0 -15
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-adjustment.js +0 -7
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-annotations.js +0 -33
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +0 -171
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +0 -164
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +0 -241
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-service-status.js +0 -82
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-source-status.js +0 -39
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +0 -349
- package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +0 -15445
- package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +0 -252
- package/node_modules/@ftshare-lab/dsh-kline/lib/fibonacci.js +0 -18
- package/node_modules/@ftshare-lab/dsh-kline/lib/ftshare-settings-bridge.js +0 -159
- package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +0 -279
- package/node_modules/@ftshare-lab/dsh-kline/lib/labeled-polyline.js +0 -17
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-bands.js +0 -55
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-series.js +0 -47
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-sticks.js +0 -32
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/candle-sequence.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-adjustment.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-annotations.d.ts +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-applications.d.ts +0 -26
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-context.d.ts +0 -14
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-observation.d.ts +0 -8
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-service-status.d.ts +0 -22
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-source-status.d.ts +0 -47
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-sources.d.ts +0 -25
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/BetterSidebarTab.d.ts +0 -12
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ClassicShell.d.ts +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/KlineContent.d.ts +0 -37
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/PaperKlinePanel.d.ts +0 -15
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/canvas-panel.d.ts +0 -33
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-apply.d.ts +0 -13
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-context.d.ts +0 -23
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-session-resolver.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/client-context.d.ts +0 -14
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +0 -39
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/default-tab.d.ts +0 -3
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/embed.d.ts +0 -37
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/horizontal-lines.d.ts +0 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-services.d.ts +0 -55
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/index.d.ts +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/mode-preferences.d.ts +0 -13
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-contract.d.ts +0 -52
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-register.d.ts +0 -46
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-services.d.ts +0 -45
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar.d.ts +0 -47
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/sidebar-integration.d.ts +0 -12
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ui-onboarding.d.ts +0 -13
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/version.d.ts +0 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/drawing-feedback.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/fibonacci.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/ftshare-settings-bridge.d.ts +0 -50
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/index.d.ts +0 -26
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/labeled-polyline.d.ts +0 -11
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-bands.d.ts +0 -3
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-series.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-sticks.d.ts +0 -3
- package/node_modules/@ftshare-lab/dsh-kline/package.json +0 -136
- package/node_modules/@ftshare-lab/dsh-kline/requirements.txt +0 -6
- package/node_modules/@ftshare-lab/dsh-kline/scripts/bootstrap.sh +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-bootstrap.mjs +0 -179
- package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-mcp-plugin.mjs +0 -27
- package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +0 -655
- package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.sh +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/server.py +0 -1734
- package/node_modules/@ftshare-lab/dsh-kline/tools/__init__.py +0 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/annotations.py +0 -119
- package/node_modules/@ftshare-lab/dsh-kline/tools/baostock_source.py +0 -176
- package/node_modules/@ftshare-lab/dsh-kline/tools/calc.py +0 -39
- package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +0 -260
- package/node_modules/@ftshare-lab/dsh-kline/tools/channel_preview.py +0 -82
- package/node_modules/@ftshare-lab/dsh-kline/tools/channels.py +0 -104
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_applications.py +0 -204
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +0 -186
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +0 -345
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +0 -466
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +0 -63
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_measurements.py +0 -84
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_source_status.py +0 -32
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_sources.py +0 -31
- package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +0 -394
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +0 -45
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_interaction.py +0 -117
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_verification.py +0 -141
- package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +0 -4681
- package/node_modules/@ftshare-lab/dsh-kline/tools/fibonacci.py +0 -83
- package/node_modules/@ftshare-lab/dsh-kline/tools/foreign_daily.py +0 -185
- package/node_modules/@ftshare-lab/dsh-kline/tools/free_sources.py +0 -483
- package/node_modules/@ftshare-lab/dsh-kline/tools/lines.py +0 -91
- package/node_modules/@ftshare-lab/dsh-kline/tools/pivots.py +0 -60
- package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +0 -125
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_bands.py +0 -165
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_series.py +0 -162
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_sticks.py +0 -114
- package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +0 -170
- package/node_modules/@ftshare-lab/dsh-kline/tools/rectangles.py +0 -76
- package/node_modules/@ftshare-lab/dsh-kline/tools/regression_channels.py +0 -87
- package/node_modules/@ftshare-lab/dsh-kline/tools/ta_functions.py +0 -228
- package/node_modules/@ftshare-lab/dsh-kline/tools/trend_lines.py +0 -106
- package/node_modules/@ftshare-lab/dsh-kline/tools/watchlist.py +0 -149
- package/node_modules/@ftshare-lab/dsh-kline/view/ft-logo.jpg +0 -0
- package/node_modules/@ftshare-lab/dsh-kline/view/vendor/klinecharts.min.js +0 -7
|
@@ -1,106 +0,0 @@
|
|
|
1
|
-
"""Explicit two-anchor AI segments, separate from automatic trend annotations."""
|
|
2
|
-
from __future__ import annotations
|
|
3
|
-
|
|
4
|
-
from copy import deepcopy
|
|
5
|
-
from datetime import datetime, timedelta, timezone
|
|
6
|
-
import hashlib
|
|
7
|
-
import re
|
|
8
|
-
import secrets
|
|
9
|
-
from typing import Any
|
|
10
|
-
|
|
11
|
-
from tools.lines import LineError, MAX_LINES, validate_line_fields
|
|
12
|
-
|
|
13
|
-
TREND_COMMAND = "DRAW_AGENT_TREND_LINE"
|
|
14
|
-
CN_TZ = timezone(timedelta(hours=8))
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
def trend_lines(payload: dict[str, Any]) -> list[dict[str, Any]]:
|
|
18
|
-
return deepcopy([c for c in payload.get("chartCommands", []) if c.get("type") == TREND_COMMAND])
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
def resolve_anchor_time(payload: dict[str, Any], value: str) -> int:
|
|
22
|
-
"""Resolve exactly one existing bar; never silently snap to a nearby candle."""
|
|
23
|
-
rows = next((c.get("rows", []) for c in payload.get("chartCommands", []) if c.get("type") == "SET_CANDLES"), [])
|
|
24
|
-
if not isinstance(value, str) or not value.strip():
|
|
25
|
-
raise LineError("invalid_anchor_time", "锚点时间需要 YYYY-MM-DD、带时区的 ISO 时间或 Unix 秒字符串。")
|
|
26
|
-
value = value.strip()
|
|
27
|
-
try:
|
|
28
|
-
if re.fullmatch(r"\d{4}-\d{2}-\d{2}", value):
|
|
29
|
-
date = datetime.strptime(value, "%Y-%m-%d").date()
|
|
30
|
-
if payload.get("interval") not in {"day", "week", "month", "quarter", "year"}:
|
|
31
|
-
raise LineError("ambiguous_anchor_time", "分钟周期请指定带时区的 K 线收盘时间或 Unix 秒,不能只写日期。")
|
|
32
|
-
matches = [int(r["time"]) for r in rows
|
|
33
|
-
if datetime.fromtimestamp(r["time"], CN_TZ).date() == date]
|
|
34
|
-
else:
|
|
35
|
-
if re.fullmatch(r"\d{1,10}", value):
|
|
36
|
-
timestamp = int(value)
|
|
37
|
-
else:
|
|
38
|
-
instant = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
39
|
-
if instant.tzinfo is None or instant.microsecond:
|
|
40
|
-
raise ValueError("explicit timezone and whole seconds required")
|
|
41
|
-
timestamp = int(instant.timestamp())
|
|
42
|
-
matches = [int(r["time"]) for r in rows if r["time"] == timestamp]
|
|
43
|
-
except (ValueError, OverflowError, OSError) as exc:
|
|
44
|
-
if isinstance(exc, LineError):
|
|
45
|
-
raise
|
|
46
|
-
raise LineError("invalid_anchor_time", "时间格式无效;请使用有效日期、带时区的 ISO 时间或 Unix 秒(不是毫秒)。") from exc
|
|
47
|
-
if not matches:
|
|
48
|
-
raise LineError("anchor_not_found", "该锚点时间不在当前快照的 K 线中,未改线;请核对交易日和图表范围,不要擅自换日期。")
|
|
49
|
-
if len(matches) != 1:
|
|
50
|
-
raise LineError("ambiguous_anchor_time", "该日期对应多根 K 线,请指定精确的带时区时间或 Unix 秒。")
|
|
51
|
-
return matches[0]
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
def edit_trend_line(
|
|
55
|
-
payload: dict[str, Any], action: str, *, line_id: str | None = None,
|
|
56
|
-
start_time: str | None = None, start_price: float | None = None,
|
|
57
|
-
end_time: str | None = None, end_price: float | None = None,
|
|
58
|
-
name: str | None = None, color: str | None = None, request_id: str | None = None,
|
|
59
|
-
) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
60
|
-
result = deepcopy(payload)
|
|
61
|
-
commands = result.get("chartCommands", [])
|
|
62
|
-
previous = next((c for c in commands if c.get("type") == TREND_COMMAND and c.get("id") == line_id), None)
|
|
63
|
-
if action in {"update", "delete"} and previous is None:
|
|
64
|
-
raise LineError("line_not_found", "当前快照不存在该 AI 趋势线,请先读回趋势线 ID。")
|
|
65
|
-
if action == "delete":
|
|
66
|
-
commands.remove(previous)
|
|
67
|
-
result["chartCommands"] = commands
|
|
68
|
-
return result, deepcopy(previous)
|
|
69
|
-
if action not in {"create", "update"}:
|
|
70
|
-
raise LineError("invalid_action", "不支持的趋势线操作。")
|
|
71
|
-
if action == "update" and all(v is None for v in (start_time, start_price, end_time, end_price, name, color)):
|
|
72
|
-
raise LineError("empty_update", "请至少修改一个锚点、名称或颜色。")
|
|
73
|
-
if action == "create" and any(v is None for v in (start_time, start_price, end_time, end_price)):
|
|
74
|
-
raise LineError("missing_anchor", "创建趋势线需要两个明确的时间和价格锚点。")
|
|
75
|
-
start_price, name, color = validate_line_fields(
|
|
76
|
-
price=start_price if start_price is not None else previous["from"]["price"],
|
|
77
|
-
name=name, color=color, request_id=request_id)
|
|
78
|
-
end_price, _, _ = validate_line_fields(price=end_price if end_price is not None else previous["to"]["price"])
|
|
79
|
-
start = {"time": resolve_anchor_time(payload, start_time) if start_time is not None else previous["from"]["time"],
|
|
80
|
-
"price": start_price}
|
|
81
|
-
end = {"time": resolve_anchor_time(payload, end_time) if end_time is not None else previous["to"]["time"],
|
|
82
|
-
"price": end_price}
|
|
83
|
-
if start["time"] >= end["time"]:
|
|
84
|
-
raise LineError("invalid_anchor_order", "起点时间必须早于终点时间;未自动交换锚点。")
|
|
85
|
-
line = {"type": TREND_COMMAND, "id": previous["id"] if previous else "trend_" + secrets.token_hex(12),
|
|
86
|
-
"from": start, "to": end,
|
|
87
|
-
"label": name if name is not None else previous["label"] if previous else "",
|
|
88
|
-
"color": color if color is not None else previous["color"] if previous else "info"}
|
|
89
|
-
if previous and previous.get("create_request_id"):
|
|
90
|
-
line["create_request_id"] = previous["create_request_id"]
|
|
91
|
-
if action == "create":
|
|
92
|
-
if request_id:
|
|
93
|
-
line["create_request_id"] = request_id
|
|
94
|
-
line["id"] = "trend_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
|
|
95
|
-
retry = next((c for c in commands if c.get("type") == TREND_COMMAND and c.get("create_request_id") == request_id), None)
|
|
96
|
-
if retry:
|
|
97
|
-
if any(retry.get(k) != line[k] for k in ("from", "to", "label", "color")):
|
|
98
|
-
raise LineError("request_conflict", "同一 request_id 的绘图参数不同,请使用新的 request_id。")
|
|
99
|
-
return result, deepcopy(retry)
|
|
100
|
-
if len(trend_lines(result)) >= MAX_LINES:
|
|
101
|
-
raise LineError("too_many_lines", "当前图表最多保存 60 条 AI 趋势线。")
|
|
102
|
-
commands.append(line)
|
|
103
|
-
else:
|
|
104
|
-
commands[commands.index(previous)] = line
|
|
105
|
-
result["chartCommands"] = commands
|
|
106
|
-
return result, deepcopy(line)
|
|
@@ -1,149 +0,0 @@
|
|
|
1
|
-
"""Persistent, user-local watchlist state shared by dsh_kline clients.
|
|
2
|
-
|
|
3
|
-
Charts, conversations and sidebar tabs deliberately have different local
|
|
4
|
-
state. A watchlist is different: it is a user collection and must survive
|
|
5
|
-
switching conversations or restarting an individual MCP process.
|
|
6
|
-
"""
|
|
7
|
-
|
|
8
|
-
from __future__ import annotations
|
|
9
|
-
|
|
10
|
-
import json
|
|
11
|
-
import os
|
|
12
|
-
import tempfile
|
|
13
|
-
import threading
|
|
14
|
-
import time
|
|
15
|
-
from pathlib import Path
|
|
16
|
-
from typing import Any
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
MAX_ITEMS = 200
|
|
20
|
-
MAX_GROUPS = 12
|
|
21
|
-
_LOCK = threading.RLock()
|
|
22
|
-
_MILLISECONDS_THRESHOLD = 100_000_000_000
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
def _state_path() -> Path:
|
|
26
|
-
configured = str(os.environ.get("DSH_KLINE_STATE_DIR") or "").strip()
|
|
27
|
-
root = Path(configured).expanduser() if configured else Path.home() / ".cache" / "dsh_kline"
|
|
28
|
-
return root / "watchlist-v1.json"
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
def _default_state() -> dict[str, Any]:
|
|
32
|
-
return {
|
|
33
|
-
"version": 1,
|
|
34
|
-
"revision": 0,
|
|
35
|
-
"updated_at": 0,
|
|
36
|
-
"groups": [{"id": "default", "name": "默认分组"}],
|
|
37
|
-
"items": [],
|
|
38
|
-
"activeGroupId": "default",
|
|
39
|
-
"sort": "manual",
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
def _normalize_state(value: Any) -> dict[str, Any]:
|
|
44
|
-
base = _default_state()
|
|
45
|
-
if not isinstance(value, dict):
|
|
46
|
-
return base
|
|
47
|
-
groups: list[dict[str, str]] = []
|
|
48
|
-
seen_groups: set[str] = set()
|
|
49
|
-
for raw in value.get("groups") if isinstance(value.get("groups"), list) else []:
|
|
50
|
-
if not isinstance(raw, dict):
|
|
51
|
-
continue
|
|
52
|
-
group_id = str(raw.get("id") or "").strip()[:48]
|
|
53
|
-
name = str(raw.get("name") or "").strip()[:24]
|
|
54
|
-
if not group_id or not name or group_id in seen_groups:
|
|
55
|
-
continue
|
|
56
|
-
seen_groups.add(group_id)
|
|
57
|
-
groups.append({"id": group_id, "name": name})
|
|
58
|
-
if len(groups) >= MAX_GROUPS:
|
|
59
|
-
break
|
|
60
|
-
if "default" not in seen_groups:
|
|
61
|
-
groups.insert(0, {"id": "default", "name": "默认分组"})
|
|
62
|
-
groups = groups[:MAX_GROUPS]
|
|
63
|
-
allowed = {group["id"] for group in groups}
|
|
64
|
-
items: list[dict[str, str]] = []
|
|
65
|
-
seen_items: set[tuple[str, str]] = set()
|
|
66
|
-
for raw in value.get("items") if isinstance(value.get("items"), list) else []:
|
|
67
|
-
if not isinstance(raw, dict):
|
|
68
|
-
continue
|
|
69
|
-
symbol = str(raw.get("symbol") or "").strip().upper()[:64]
|
|
70
|
-
name = str(raw.get("name") or symbol).strip()[:80]
|
|
71
|
-
group_id = str(raw.get("groupId") or raw.get("group_id") or "default").strip()[:48]
|
|
72
|
-
key = (symbol, group_id)
|
|
73
|
-
if not symbol or group_id not in allowed or key in seen_items:
|
|
74
|
-
continue
|
|
75
|
-
seen_items.add(key)
|
|
76
|
-
items.append({"symbol": symbol, "name": name or symbol, "groupId": group_id})
|
|
77
|
-
if len(items) >= MAX_ITEMS:
|
|
78
|
-
break
|
|
79
|
-
active = str(value.get("activeGroupId") or value.get("active_group_id") or "default")
|
|
80
|
-
if active not in allowed:
|
|
81
|
-
active = "default"
|
|
82
|
-
updated_at = max(0, int(value.get("updated_at") or 0))
|
|
83
|
-
# Early development builds wrote seconds. Persist milliseconds from now
|
|
84
|
-
# on so client edits made in the same second remain orderable.
|
|
85
|
-
if 0 < updated_at < _MILLISECONDS_THRESHOLD:
|
|
86
|
-
updated_at *= 1000
|
|
87
|
-
return {
|
|
88
|
-
"version": 1,
|
|
89
|
-
"revision": max(0, int(value.get("revision") or 0)),
|
|
90
|
-
"updated_at": updated_at,
|
|
91
|
-
"groups": groups,
|
|
92
|
-
"items": items,
|
|
93
|
-
"activeGroupId": active,
|
|
94
|
-
"sort": value.get("sort") if value.get("sort") in {"manual", "change_desc", "change_asc"} else "manual",
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
def get_watchlist_state() -> dict[str, Any]:
|
|
99
|
-
"""Read the user-local watchlist; missing/corrupt files safely become empty."""
|
|
100
|
-
with _LOCK:
|
|
101
|
-
try:
|
|
102
|
-
raw = json.loads(_state_path().read_text(encoding="utf-8"))
|
|
103
|
-
except (OSError, TypeError, ValueError):
|
|
104
|
-
raw = None
|
|
105
|
-
return _normalize_state(raw)
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
def save_watchlist_state(state: Any) -> dict[str, Any]:
|
|
109
|
-
"""Atomically persist a complete validated user watchlist and return it.
|
|
110
|
-
|
|
111
|
-
A browser sends the revision it last read. Rejecting a stale write gives
|
|
112
|
-
it a chance to reconcile instead of silently overwriting edits made in a
|
|
113
|
-
different conversation or DSH instance.
|
|
114
|
-
"""
|
|
115
|
-
with _LOCK:
|
|
116
|
-
previous = get_watchlist_state()
|
|
117
|
-
expected_revision: int | None = None
|
|
118
|
-
if isinstance(state, dict) and "revision" in state:
|
|
119
|
-
try:
|
|
120
|
-
expected_revision = max(0, int(state.get("revision")))
|
|
121
|
-
except (TypeError, ValueError):
|
|
122
|
-
return {"ok": False, "error": "watchlist_invalid_revision", "message": "自选版本号无效"}
|
|
123
|
-
if expected_revision is not None and expected_revision != previous["revision"]:
|
|
124
|
-
return {
|
|
125
|
-
"ok": False,
|
|
126
|
-
"error": "watchlist_conflict",
|
|
127
|
-
"message": "自选已在另一处更新,请同步后重试",
|
|
128
|
-
"watchlist": previous,
|
|
129
|
-
}
|
|
130
|
-
normalized = _normalize_state(state)
|
|
131
|
-
normalized["revision"] = previous["revision"] + 1
|
|
132
|
-
normalized["updated_at"] = time.time_ns() // 1_000_000
|
|
133
|
-
path = _state_path()
|
|
134
|
-
try:
|
|
135
|
-
path.parent.mkdir(parents=True, exist_ok=True)
|
|
136
|
-
descriptor, temporary_name = tempfile.mkstemp(prefix="watchlist-", suffix=".tmp", dir=path.parent)
|
|
137
|
-
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
|
|
138
|
-
json.dump(normalized, handle, ensure_ascii=False, separators=(",", ":"))
|
|
139
|
-
handle.flush()
|
|
140
|
-
os.fsync(handle.fileno())
|
|
141
|
-
os.chmod(temporary_name, 0o600)
|
|
142
|
-
os.replace(temporary_name, path)
|
|
143
|
-
except OSError as exc:
|
|
144
|
-
try:
|
|
145
|
-
os.unlink(temporary_name)
|
|
146
|
-
except (OSError, UnboundLocalError):
|
|
147
|
-
pass
|
|
148
|
-
return {"ok": False, "error": "watchlist_persist_failed", "message": f"无法保存自选:{exc}"}
|
|
149
|
-
return {"ok": True, "watchlist": normalized}
|
|
Binary file
|