@ftshare-lab/dsh-kline 0.0.0-stage → 0.6.10

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 (203) hide show
  1. package/CHANGELOG.md +601 -0
  2. package/LICENSE +21 -0
  3. package/PROVENANCE.md +13 -0
  4. package/README.en.md +116 -0
  5. package/README.md +115 -2
  6. package/chart_service.py +687 -0
  7. package/config/basic-symbols.json +570 -0
  8. package/config/dsh-kline.patch.yml +4 -0
  9. package/config/dsh-tool-catalog.json +3875 -0
  10. package/cordis.patch.yml +33 -0
  11. package/core/__init__.py +0 -0
  12. package/core/adjustment.py +16 -0
  13. package/core/calc.py +691 -0
  14. package/core/rows.py +228 -0
  15. package/core/ta_engine.py +99 -0
  16. package/docs/anonymous-market-support.md +33 -0
  17. package/docs/automatic-drawing.md +24 -0
  18. package/docs/chart-functions.md +136 -0
  19. package/docs/drawing-examples.en.md +13 -0
  20. package/docs/drawing-examples.md +13 -0
  21. package/docs/embedding.md +43 -0
  22. package/docs/fixtures/price-pattern-real-v1.json +1 -0
  23. package/docs/free-foreign-daily.md +44 -0
  24. package/docs/guide.en.md +232 -0
  25. package/docs/guide.md +248 -0
  26. package/docs/images/abc-drawing-v0.5.0.jpg +0 -0
  27. package/docs/images/channel-drawing-v0.5.0.jpg +0 -0
  28. package/docs/images/drawing-workbench-v0.5.0.jpg +0 -0
  29. package/docs/images/dsh-kline-tab-workspace.png +0 -0
  30. package/docs/images/dsh-market.png +0 -0
  31. package/docs/images/kline-news.png +0 -0
  32. package/docs/images/kline-range-stats.png +0 -0
  33. package/docs/images/kline-support.png +0 -0
  34. package/docs/images/main-chart-comparison-v0.6.9.png +0 -0
  35. package/docs/images/market-overview-v0.6.9.png +0 -0
  36. package/docs/images/natural-language-abc-wolong-2026-10-27.png +0 -0
  37. package/docs/images/natural-language-descending-channel-wolong-2026-10-27.png +0 -0
  38. package/docs/images/platform-breakout-msft-v0.6.9.png +0 -0
  39. package/docs/npm-release.md +33 -0
  40. package/docs/price-pattern-rules-v1.md +40 -0
  41. package/docs/price-pattern-samples-v1.md +42 -0
  42. package/docs/provider-adaptation.md +73 -0
  43. package/docs/release-acceptance-v0.4.0.md +46 -0
  44. package/docs/release-acceptance-v0.4.1.md +43 -0
  45. package/docs/release-acceptance-v0.5.0.md +40 -0
  46. package/docs/release-acceptance-v0.6.0.md +33 -0
  47. package/docs/release-acceptance-v0.6.1.md +19 -0
  48. package/docs/release-acceptance-v0.6.10.md +21 -0
  49. package/docs/release-acceptance-v0.6.2.md +31 -0
  50. package/docs/release-acceptance-v0.6.3.md +25 -0
  51. package/docs/release-acceptance-v0.6.4.md +24 -0
  52. package/docs/release-acceptance-v0.6.5.md +21 -0
  53. package/docs/release-acceptance-v0.6.6.md +21 -0
  54. package/docs/release-acceptance-v0.6.7.md +18 -0
  55. package/docs/release-acceptance-v0.6.8.md +18 -0
  56. package/docs/release-acceptance-v0.6.9.md +98 -0
  57. package/docs/release-notes-v0.5.0.md +23 -0
  58. package/docs/release-notes-v0.6.0.md +11 -0
  59. package/docs/release-notes-v0.6.1.md +20 -0
  60. package/docs/release-notes-v0.6.10.md +11 -0
  61. package/docs/release-notes-v0.6.2.md +14 -0
  62. package/docs/release-notes-v0.6.3.md +26 -0
  63. package/docs/release-notes-v0.6.4.md +12 -0
  64. package/docs/release-notes-v0.6.5.md +13 -0
  65. package/docs/release-notes-v0.6.6.md +13 -0
  66. package/docs/release-notes-v0.6.7.md +17 -0
  67. package/docs/release-notes-v0.6.8.md +10 -0
  68. package/docs/release-notes-v0.6.9.md +16 -0
  69. package/lib/candle-sequence.js +15 -0
  70. package/lib/chart-adjustment.js +7 -0
  71. package/lib/chart-annotations.js +33 -0
  72. package/lib/chart-applications.js +171 -0
  73. package/lib/chart-context.js +164 -0
  74. package/lib/chart-observation.js +251 -0
  75. package/lib/chart-service-status.js +82 -0
  76. package/lib/chart-source-status.js +39 -0
  77. package/lib/chart-sources.js +354 -0
  78. package/lib/client/BetterSidebarTab.js +70 -0
  79. package/lib/client/ClassicShell.js +254 -0
  80. package/lib/client/KlineContent.js +155 -0
  81. package/lib/client/chart-apply.js +73 -0
  82. package/lib/client/chart-context.js +233 -0
  83. package/lib/client/chart-handoff.js +34 -0
  84. package/lib/client/chart-session-resolver.js +74 -0
  85. package/lib/client/client-context.js +1 -0
  86. package/lib/client/conversation.js +88 -0
  87. package/lib/client/default-tab.js +83 -0
  88. package/lib/client/embed.js +50 -0
  89. package/lib/client/generated-view.js +12983 -0
  90. package/lib/client/horizontal-lines.js +19 -0
  91. package/lib/client/index.js +62 -0
  92. package/lib/client/mode-preferences.js +28 -0
  93. package/lib/client/native-sidebar-contract.js +45 -0
  94. package/lib/client/native-sidebar-register.js +133 -0
  95. package/lib/client/native-sidebar-services.js +1 -0
  96. package/lib/client/native-sidebar.js +96 -0
  97. package/lib/client/sidebar-integration.js +93 -0
  98. package/lib/client/ui-onboarding.js +42 -0
  99. package/lib/client/version.js +14 -0
  100. package/lib/client.js +17382 -0
  101. package/lib/client.js.map +1 -0
  102. package/lib/drawing-feedback.js +284 -0
  103. package/lib/fibonacci.js +18 -0
  104. package/lib/ftshare-settings-bridge.js +159 -0
  105. package/lib/index.js +279 -0
  106. package/lib/labeled-polyline.js +17 -0
  107. package/lib/pattern-groups.js +91 -0
  108. package/lib/price-bands.js +55 -0
  109. package/lib/price-series.js +47 -0
  110. package/lib/price-sticks.js +32 -0
  111. package/lib/types/candle-sequence.d.ts +2 -0
  112. package/lib/types/chart-adjustment.d.ts +2 -0
  113. package/lib/types/chart-annotations.d.ts +4 -0
  114. package/lib/types/chart-applications.d.ts +26 -0
  115. package/lib/types/chart-context.d.ts +14 -0
  116. package/lib/types/chart-observation.d.ts +8 -0
  117. package/lib/types/chart-service-status.d.ts +22 -0
  118. package/lib/types/chart-source-status.d.ts +47 -0
  119. package/lib/types/chart-sources.d.ts +25 -0
  120. package/lib/types/client/BetterSidebarTab.d.ts +12 -0
  121. package/lib/types/client/ClassicShell.d.ts +4 -0
  122. package/lib/types/client/KlineContent.d.ts +37 -0
  123. package/lib/types/client/chart-apply.d.ts +13 -0
  124. package/lib/types/client/chart-context.d.ts +23 -0
  125. package/lib/types/client/chart-handoff.d.ts +5 -0
  126. package/lib/types/client/chart-session-resolver.d.ts +2 -0
  127. package/lib/types/client/client-context.d.ts +14 -0
  128. package/lib/types/client/conversation.d.ts +43 -0
  129. package/lib/types/client/default-tab.d.ts +3 -0
  130. package/lib/types/client/embed.d.ts +37 -0
  131. package/lib/types/client/generated-view.d.ts +2 -0
  132. package/lib/types/client/horizontal-lines.d.ts +1 -0
  133. package/lib/types/client/index.d.ts +4 -0
  134. package/lib/types/client/mode-preferences.d.ts +13 -0
  135. package/lib/types/client/native-sidebar-contract.d.ts +52 -0
  136. package/lib/types/client/native-sidebar-register.d.ts +46 -0
  137. package/lib/types/client/native-sidebar-services.d.ts +45 -0
  138. package/lib/types/client/native-sidebar.d.ts +47 -0
  139. package/lib/types/client/sidebar-integration.d.ts +12 -0
  140. package/lib/types/client/ui-onboarding.d.ts +6 -0
  141. package/lib/types/client/version.d.ts +1 -0
  142. package/lib/types/drawing-feedback.d.ts +5 -0
  143. package/lib/types/fibonacci.d.ts +5 -0
  144. package/lib/types/ftshare-settings-bridge.d.ts +50 -0
  145. package/lib/types/index.d.ts +26 -0
  146. package/lib/types/labeled-polyline.d.ts +11 -0
  147. package/lib/types/pattern-groups.d.ts +2 -0
  148. package/lib/types/price-bands.d.ts +3 -0
  149. package/lib/types/price-series.d.ts +5 -0
  150. package/lib/types/price-sticks.d.ts +3 -0
  151. package/package.json +153 -4
  152. package/requirements.txt +6 -0
  153. package/screenshots.json +11 -0
  154. package/scripts/bootstrap.sh +5 -0
  155. package/scripts/dsh-bootstrap.mjs +179 -0
  156. package/scripts/dsh-mcp-plugin.mjs +27 -0
  157. package/scripts/run-dsh-kline.mjs +658 -0
  158. package/scripts/run-dsh-kline.sh +5 -0
  159. package/server.py +1755 -0
  160. package/tools/__init__.py +0 -0
  161. package/tools/annotations.py +119 -0
  162. package/tools/automatic_analysis.py +158 -0
  163. package/tools/baostock_source.py +176 -0
  164. package/tools/calc.py +39 -0
  165. package/tools/channel_candidates.py +260 -0
  166. package/tools/channel_preview.py +82 -0
  167. package/tools/channels.py +104 -0
  168. package/tools/chart_applications.py +204 -0
  169. package/tools/chart_context.py +186 -0
  170. package/tools/chart_edits.py +363 -0
  171. package/tools/chart_functions.py +451 -0
  172. package/tools/chart_indicators.py +65 -0
  173. package/tools/chart_measurements.py +84 -0
  174. package/tools/chart_source_status.py +32 -0
  175. package/tools/chart_sources.py +31 -0
  176. package/tools/closed_daily.py +68 -0
  177. package/tools/draw.py +410 -0
  178. package/tools/drawing_feedback.py +45 -0
  179. package/tools/drawing_interaction.py +117 -0
  180. package/tools/drawing_verification.py +141 -0
  181. package/tools/fetch.py +4680 -0
  182. package/tools/fibonacci.py +83 -0
  183. package/tools/foreign_daily.py +185 -0
  184. package/tools/free_sources.py +483 -0
  185. package/tools/lines.py +91 -0
  186. package/tools/nine_count.py +66 -0
  187. package/tools/pattern_groups.py +103 -0
  188. package/tools/pivots.py +60 -0
  189. package/tools/polylines.py +131 -0
  190. package/tools/price_bands.py +165 -0
  191. package/tools/price_patterns.py +311 -0
  192. package/tools/price_series.py +162 -0
  193. package/tools/price_sticks.py +114 -0
  194. package/tools/range_candidates.py +170 -0
  195. package/tools/recent_drawing_candidates.py +123 -0
  196. package/tools/rectangles.py +76 -0
  197. package/tools/regression_channels.py +87 -0
  198. package/tools/ta_functions.py +228 -0
  199. package/tools/trend_lines.py +106 -0
  200. package/tools/watchlist.py +149 -0
  201. package/view/ft-logo.jpg +0 -0
  202. package/view/kline.html +12436 -0
  203. package/view/vendor/klinecharts.min.js +7 -0
@@ -0,0 +1,204 @@
1
+ """Explicit application requests and historical state receipts; never a pixel receipt."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import re
7
+ import time
8
+
9
+ import chart_service
10
+ from tools.chart_context import read_chart_context
11
+ from tools.lines import LineError
12
+ from tools.drawing_feedback import sanitize_drawing_feedback
13
+
14
+ STATUSES = {"queued", "delivered", "applied", "rejected", "failed", "outcome_unknown"}
15
+
16
+
17
+ def application_path(context_ref: str, candidate: str):
18
+ if any(not isinstance(v, str) or not re.fullmatch(r"[A-Za-z0-9_-]{32}", v) for v in (context_ref, candidate)):
19
+ raise LineError("invalid_chart_application_reference", "请使用准备结果的 context_ref 和候选 chart_session,不猜测引用。")
20
+ return chart_service.RUNTIME_DIR / "edits" / str(chart_service.HOST_PROCESS_ID) / context_ref / "applications" / (candidate + ".json")
21
+
22
+
23
+ def _read(path):
24
+ try:
25
+ if path.stat().st_size > chart_service.MAX_REQUEST_BYTES: raise ValueError("too large")
26
+ data = json.loads(path.read_text(encoding="utf-8"))
27
+ if not isinstance(data, dict): raise ValueError("not an object")
28
+ return data
29
+ except (OSError, ValueError, TypeError):
30
+ raise LineError("chart_application_unavailable", "应用记录不可用,未猜测网页状态或自动重发。") from None
31
+
32
+
33
+ def read_application(context_ref: str, candidate: str) -> dict:
34
+ data = _read(application_path(context_ref, candidate))
35
+ if (data.get("host_process_id") != chart_service.HOST_PROCESS_ID or data.get("context_ref") != context_ref
36
+ or data.get("candidate_chart_session") != candidate or data.get("status") not in STATUSES):
37
+ raise LineError("invalid_chart_application", "应用记录身份或状态不一致。")
38
+ return data
39
+
40
+
41
+ def _present(path) -> bool:
42
+ """Only ENOENT is absence; unreadable/corrupt records must not become 'not requested'."""
43
+ try:
44
+ path.stat()
45
+ return True
46
+ except FileNotFoundError:
47
+ return False
48
+ except OSError:
49
+ raise LineError("chart_application_unavailable", "记录无法核对,未推断尚未请求应用。") from None
50
+
51
+
52
+ def read_edit_status(context_ref: str, candidate: str) -> dict:
53
+ """Read historical preparation or application proof, without acquiring locks or writing.
54
+
55
+ This is not an application reader: confirmed_source must still require a real receipt.
56
+ An absent application alone proves nothing; require the exact successful preparation.
57
+ """
58
+ path = application_path(context_ref, candidate)
59
+ if _present(path):
60
+ return application_status(read_application(context_ref, candidate))
61
+ directory = path.parent.parent
62
+
63
+ def check_inflight():
64
+ if _present(directory / "prepare.lock"):
65
+ raise LineError("chart_edit_busy", "该视图正在处理或存在中断锁,不能断言尚未请求应用;未重发。")
66
+ if _present(directory / "pending.json"):
67
+ pending = _read(directory / "pending.json").get("candidate_chart_session")
68
+ if pending == candidate:
69
+ raise LineError("chart_application_unavailable", "存在应用请求索引但记录缺失,未推断尚未请求应用。")
70
+ if read_application(context_ref, pending)["status"] not in {"applied", "rejected", "failed"}:
71
+ raise LineError("chart_apply_busy", "该视图有等待或结果未确认的应用,未推断新的应用状态。")
72
+
73
+ check_inflight()
74
+ payload = chart_service.read_chart_snapshot(candidate)
75
+ guard = payload.get("drawing_guard") if payload else None
76
+ if (not isinstance(guard, dict) or guard.get("protocol") != "prepared-only-v1"
77
+ or guard.get("context_ref") != context_ref or guard.get("requires_live_apply") is not True
78
+ or payload.get("drawing_parent_session") != guard.get("chart_session")
79
+ or not isinstance(guard.get("expected_revision"), int) or isinstance(guard["expected_revision"], bool)
80
+ or guard["expected_revision"] <= 0 or not isinstance(guard.get("conversation_id"), str) or not guard["conversation_id"]
81
+ or not isinstance(guard.get("view_id"), str) or not re.fullmatch(r"[A-Za-z0-9_-]{32}", guard["view_id"])
82
+ or not isinstance(guard.get("request_id"), str) or not 1 <= len(guard["request_id"]) <= 128
83
+ or not isinstance(guard.get("chart_session"), str) or not re.fullmatch(r"[A-Za-z0-9_-]{32}", guard["chart_session"])
84
+ or not isinstance(guard.get("parameters"), dict) or guard.get("kind") not in ("horizontal_line", "trend_line", "channel", "rectangle", "fibonacci_retracement", "labeled_polyline", "text_annotation", "number_annotation", "icon_annotation", "series_line", "price_band", "price_sticks", "all_drawings")
85
+ or guard.get("action") not in ("create", "update", "delete")):
86
+ raise LineError("invalid_chart_application", "候选不属于该准备请求,未推断应用状态。")
87
+ entries = _read(directory / "journal.json").get("entries")
88
+ from tools.chart_edits import _hash
89
+ identity = {key: guard.get(key) for key in ("context_ref", "expected_revision", "chart_session", "symbol",
90
+ "kind", "action", "object_id", "parameters")}
91
+ matches = [entry for entry in entries if isinstance(entry, dict) and entry.get("request_id") == guard.get("request_id")] if isinstance(entries, list) and len(entries) <= 64 else []
92
+ entry = matches[0] if len(matches) == 1 else {}
93
+ result = entry.get("result")
94
+ if (not isinstance(result, dict) or entry.get("status") != "prepared"
95
+ or entry.get("revision") != guard.get("expected_revision") or entry.get("fingerprint") != _hash(identity)
96
+ or result.get("ok") is not True or result.get("operation_status") != "prepared"
97
+ or result.get("apply_status") != "not_requested" or result.get("chart_session") != candidate
98
+ or result.get("parent_chart_session") != guard.get("chart_session") or result.get("drawing_guard") != guard
99
+ or any(result.get(key) != guard.get(key) for key in
100
+ ("context_ref", "expected_revision", "conversation_id", "view_id", "request_id"))):
101
+ raise LineError("chart_edit_outcome_unknown", "未找到匹配的成功准备记录,未推断尚未请求应用。")
102
+ # A concurrent apply may have completed while we read preparation proof. Prefer
103
+ # its real record; a retained lock/index with no record remains uncertain.
104
+ if _present(path):
105
+ return application_status(read_application(context_ref, candidate))
106
+ check_inflight()
107
+ if _present(path):
108
+ return application_status(read_application(context_ref, candidate))
109
+ return {"ok": True, "operation_status": "prepared", "apply_status": "not_requested",
110
+ **{key: result[key] for key in ("context_ref", "expected_revision", "conversation_id", "view_id", "request_id")},
111
+ "candidate_chart_session": candidate, "parent_chart_session": result["parent_chart_session"],
112
+ "application_record_present": False, "record_is_historical": True,
113
+ "confirmation_scope": "not_confirmed", "render_verified": False,
114
+ "current_view_verified": False, "edit_authorized": False}
115
+
116
+
117
+ def application_status(data: dict) -> dict:
118
+ # Queued/delivered can be historical after a host interruption; never invent an acknowledgment.
119
+ result = {k: data.get(k) for k in ("context_ref", "candidate_chart_session", "conversation_id", "view_id",
120
+ "expected_revision", "created_at_ms", "expires_at_ms", "reason", "acknowledged_at_ms", "confirmed_chart_session")}
121
+ expires = data.get("expires_at_ms")
122
+ candidate = chart_service.read_chart_snapshot(data.get("candidate_chart_session"))
123
+ if candidate:
124
+ from tools.chart_edits import snapshot_inventory
125
+ try:
126
+ allowed = list({d["id"]: d for d in [*data.get("base_state", {}).get("drawings", []), *snapshot_inventory(candidate)]
127
+ if d.get("origin") == "ai"}.values())
128
+ feedback = sanitize_drawing_feedback(data.get("drawing_feedback"), allowed)
129
+ except (KeyError, TypeError, AttributeError): feedback = sanitize_drawing_feedback({"report_status": "invalid"}, [])
130
+ else: feedback = sanitize_drawing_feedback(None, [])
131
+ expired = isinstance(expires, (int, float)) and time.time() * 1000 > expires
132
+ result.update(ok=True, apply_status=data["status"], render_verified=False,
133
+ expired=expired, needs_attention=data["status"] == "outcome_unknown" or expired and data["status"] in {"queued", "delivered"}
134
+ or feedback["report_status"] == "invalid" or any(i["status"] in {"failed", "unknown"} for i in feedback["items"]),
135
+ drawing_feedback=feedback,
136
+ confirmation_scope="view_state_only" if data["status"] == "applied" else "not_confirmed",
137
+ record_is_historical=True)
138
+ return result
139
+
140
+
141
+ def confirmed_source(payload: dict, context: dict, token: str) -> bool:
142
+ guard = payload.get("drawing_guard") or {}
143
+ try: proof = read_application(guard.get("context_ref"), token)
144
+ except LineError: return False
145
+ return (proof["status"] == "applied" and proof.get("confirmed_chart_session") == token
146
+ and proof.get("conversation_id") == context.get("conversation_id") == guard.get("conversation_id")
147
+ and proof.get("view_id") == guard.get("view_id") and proof.get("request_id") == guard.get("request_id"))
148
+
149
+
150
+ def request_chart_apply(context_ref: str, candidate: str) -> dict:
151
+ path = application_path(context_ref, candidate)
152
+ directory = path.parent.parent
153
+ directory.mkdir(mode=0o700, parents=True, exist_ok=True)
154
+ lock = directory / "prepare.lock"
155
+ try: descriptor = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
156
+ except FileExistsError:
157
+ raise LineError("chart_edit_busy", "该视图正在准备或申请应用,未并行修改。") from None
158
+ os.close(descriptor)
159
+ try:
160
+ if path.exists():
161
+ existing = read_application(context_ref, candidate)
162
+ # Same immutable candidate has one delivery, including after a lost reply.
163
+ if existing["status"] != "queued": return application_status(existing)
164
+ else: existing = None
165
+ context = read_chart_context(context_ref, candle_scope="loaded", limit=4000)
166
+ if not context.get("guarded_apply_supported"):
167
+ raise LineError("chart_apply_protocol_unavailable", "该网页尚未声明支持应用协议,请更新/重载插件网页;未发送修改指令。")
168
+ payload = chart_service.read_chart_snapshot(candidate)
169
+ guard = payload.get("drawing_guard") if payload else None
170
+ if (not isinstance(guard, dict) or guard.get("protocol") != "prepared-only-v1"
171
+ or guard.get("context_ref") != context_ref or guard.get("conversation_id") != context["conversation_id"]
172
+ or guard.get("view_id") != context["view_id"]):
173
+ raise LineError("invalid_chart_application", "候选不属于当前视图的准备请求,未申请应用。")
174
+ if context["revision"] != guard.get("expected_revision"):
175
+ raise LineError("chart_context_revision_conflict", "准备后当前图版本已变化,未申请应用。")
176
+ journal = _read(directory / "journal.json")
177
+ entries = journal.get("entries")
178
+ if not isinstance(entries, list) or not any(e.get("status") == "prepared" and e.get("request_id") == guard.get("request_id")
179
+ and isinstance(e.get("result"), dict) and e["result"].get("chart_session") == candidate for e in entries if isinstance(e, dict)):
180
+ raise LineError("chart_edit_outcome_unknown", "未找到成功准备记录,不能申请应用。")
181
+ source = chart_service.read_chart_snapshot(guard.get("chart_session"))
182
+ if source is None: raise LineError("chart_session_not_found", "原始来源快照不可用。")
183
+ from tools.chart_edits import require_alignment
184
+ require_alignment(context, source, guard["chart_session"], guard["symbol"])
185
+ pending = directory / "pending.json"
186
+ if pending.exists():
187
+ old_token = _read(pending).get("candidate_chart_session")
188
+ if old_token != candidate:
189
+ old = read_application(context_ref, old_token)
190
+ if old["status"] not in {"applied", "rejected", "failed"}:
191
+ raise LineError("chart_apply_busy", "该视图有等待或结果未确认的应用,不能覆盖它。")
192
+ if existing is None:
193
+ observation = _read(chart_service.RUNTIME_DIR / "views" / str(chart_service.HOST_PROCESS_ID) / (context_ref + ".json"))
194
+ if observation.get("revision") != guard["expected_revision"] or observation.get("view_id") != guard["view_id"]:
195
+ raise LineError("chart_context_revision_conflict", "读取期间当前图版本已变化,未申请应用。")
196
+ now = int(time.time() * 1000)
197
+ existing = {"host_process_id": chart_service.HOST_PROCESS_ID, "context_ref": context_ref,
198
+ "candidate_chart_session": candidate, "conversation_id": context["conversation_id"], "view_id": context["view_id"],
199
+ "expected_revision": guard["expected_revision"], "request_id": guard["request_id"], "status": "queued",
200
+ "created_at_ms": now, "expires_at_ms": now + 30000, "base_state": observation["state"]}
201
+ chart_service._atomic_runtime_json(path, existing)
202
+ chart_service._atomic_runtime_json(pending, {"candidate_chart_session": candidate})
203
+ return application_status(existing)
204
+ finally: lock.unlink()
@@ -0,0 +1,186 @@
1
+ """Read live browser observations by capability reference; never infer a current view."""
2
+ from __future__ import annotations
3
+
4
+ from copy import deepcopy
5
+ from datetime import datetime
6
+ import json
7
+ import math
8
+ import re
9
+ import time
10
+ from typing import Any
11
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
12
+
13
+ import chart_service
14
+ from core.rows import validate_rows, RowsValidationError
15
+ from tools.lines import LineError
16
+ from tools.drawing_feedback import sanitize_drawing_feedback
17
+ from tools.drawing_interaction import drawing_capabilities
18
+ from tools.trend_lines import CN_TZ
19
+ from tools.chart_measurements import measure_chart_region
20
+ from tools.channel_preview import preview_channel
21
+ from tools.chart_source_status import sanitize_source_status
22
+
23
+
24
+ def sanitize_data_provenance(state: dict[str, Any]) -> dict[str, Any]:
25
+ """Whitelist the additive observation metadata, including old-client unknowns."""
26
+ ready = state.get("state") == "ready"
27
+ intervals = ("minute", "day", "week", "month", "quarter", "year")
28
+ source = state.get("source_interval") if ready and state.get("source_interval") in intervals else None
29
+ display = state.get("interval") if ready and state.get("interval") in intervals else None
30
+ raw = state.get("data_provenance") if ready else None
31
+ raw = raw if isinstance(raw, dict) else {}
32
+ provider = raw.get("provider")
33
+ if provider not in ("ftshare", "eastmoney_free", "tencent_free", "builtin_free", "external"):
34
+ provider = "unknown"
35
+ transformation, aggregation = "unknown", None
36
+ if source and source == display and raw.get("transformation") == "none":
37
+ transformation = "none"
38
+ if source == "day" and display in ("week", "month", "quarter", "year") and raw.get("transformation") == "local_aggregation":
39
+ details = raw.get("aggregation")
40
+ zone = details.get("timezone") if isinstance(details, dict) else None
41
+ if isinstance(zone, str) and len(zone) <= 64 and re.fullmatch(r"[A-Za-z_+-]+(?:/[A-Za-z0-9_+-]+){0,2}", zone):
42
+ try:
43
+ ZoneInfo(zone)
44
+ transformation = "local_aggregation"
45
+ aggregation = {"timezone": zone, "bucket": "calendar_week_monday" if display == "week" else "calendar_" + display,
46
+ "ohlcv": "first_open_max_high_min_low_last_close_sum_volume", "timestamp": "last_source_bar",
47
+ "order": "aggregate_before_range_crop", "completeness": "not_verified"}
48
+ except (ZoneInfoNotFoundError, ValueError):
49
+ pass
50
+ return {"scope": "browser_input_to_display", "provider": provider, "source_interval": source,
51
+ "display_interval": display, "transformation": transformation, "aggregation": aggregation}
52
+
53
+
54
+ def _time_label(value: int | None) -> dict[str, Any] | None:
55
+ if value is None:
56
+ return None
57
+ try:
58
+ instant = datetime.fromtimestamp(value, CN_TZ)
59
+ return {"time": value, "date": instant.date().isoformat(), "iso": instant.isoformat(timespec="seconds")}
60
+ except (ValueError, OverflowError, OSError):
61
+ return {"time": value, "date": None, "iso": None}
62
+
63
+
64
+ def read_chart_context(context_ref: str, *, candle_scope: str = "visible", limit: int = 200,
65
+ region_start_time: str | None = None, region_end_time: str | None = None,
66
+ channel_candidate: dict[str, Any] | None = None) -> dict[str, Any]:
67
+ if not isinstance(context_ref, str) or not re.fullmatch(r"[A-Za-z0-9_-]{32}", context_ref):
68
+ raise LineError("context_ref_required", "请使用当前对话运行时上下文提供的 context_ref,不要使用 chart_session 或猜测其他对话。")
69
+ if candle_scope not in {"visible", "loaded", "none"} or isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= 4000:
70
+ raise LineError("invalid_context_arguments", "candle_scope 请选择 visible、loaded 或 none;limit 为1至4000整数。")
71
+ if (region_start_time is None) != (region_end_time is None):
72
+ raise LineError("invalid_measurement_range", "测量需同时指定起止已有K线时间;不自动猜测另一个端点。")
73
+ path = chart_service.RUNTIME_DIR / "views" / str(chart_service.HOST_PROCESS_ID) / f"{context_ref}.json"
74
+ try:
75
+ if path.stat().st_size > chart_service.MAX_REQUEST_BYTES: raise ValueError("too large")
76
+ saved = json.loads(path.read_text(encoding="utf-8"))
77
+ except (OSError, ValueError, TypeError):
78
+ raise LineError("chart_context_unavailable", "当前图表上下文不可用;请打开该对话的图表。未使用旧快照或其他对话代替。") from None
79
+ if not isinstance(saved, dict) or saved.get("ok") is not True or saved.get("context_ref") != context_ref or saved.get("host_process_id") != chart_service.HOST_PROCESS_ID:
80
+ raise LineError("chart_context_unavailable", "上下文不属于当前 DSH 实例。")
81
+ if (not isinstance(saved.get("revision"), int) or isinstance(saved["revision"], bool) or saved["revision"] <= 0
82
+ or not isinstance(saved.get("conversation_id"), str) or not saved["conversation_id"]
83
+ or not isinstance(saved.get("view_id"), str) or not re.fullmatch(r"[A-Za-z0-9_-]{32}", saved["view_id"])):
84
+ raise LineError("invalid_chart_context", "图表视图身份或观察版本无效。")
85
+ observed = saved.get("observed_at_ms")
86
+ if isinstance(observed, bool) or not isinstance(observed, (int, float)) or not math.isfinite(observed):
87
+ raise LineError("invalid_chart_context", "图表观察时间无效。")
88
+ age = time.time() * 1000 - observed
89
+ if age > 90_000 or age < -5000:
90
+ raise LineError("chart_context_stale", "图表上下文已过期或时钟异常,请等待网页重新上报;未回退到旧行情快照。")
91
+ if saved.get("active") is not True: raise LineError("chart_view_inactive", "该图表视图已关闭或未活动。")
92
+ if saved.get("ambiguous") is not False: raise LineError("ambiguous_chart_views", "该对话存在多个活动视图,不能确定当前图;请保留一个活动图表视图。")
93
+ state = saved.get("state")
94
+ if not isinstance(state, dict) or state.get("schema_version") != 1 or state.get("state") not in {"ready", "empty", "not_chart", "loading", "error"}:
95
+ raise LineError("invalid_chart_context", "图表上下文格式无效。")
96
+ try:
97
+ raw = state.get("candles", [])
98
+ if not isinstance(raw, list) or len(raw) > 12000: raise ValueError("rows")
99
+ if state["state"] == "ready":
100
+ if any(any(isinstance(r.get(k), bool) or not isinstance(r.get(k), (int, float)) or not math.isfinite(r[k])
101
+ for k in ("time", "open", "high", "low", "close", "volume"))
102
+ or not isinstance(r["time"], int) or r["time"] <= 0 for r in raw): raise ValueError("row types")
103
+ rows = validate_rows([{k: r[k] for k in ("time", "open", "high", "low", "close", "volume")} for r in raw], min_len=1)
104
+ else: rows = []
105
+ # The browser's clock/order must already be canonical. Do not repair a stale/malformed report.
106
+ if rows and [r["time"] for r in rows] != [r.get("time") for r in raw]: raise ValueError("clock")
107
+ if len(rows) != len(raw) and state["state"] == "ready": raise ValueError("rows")
108
+ viewport = state.get("visible_range", {})
109
+ visible: list[dict] = []
110
+ if state["state"] == "ready" and viewport.get("available") is True:
111
+ start, end = viewport["index_from"], viewport["index_to_exclusive"]
112
+ if any(isinstance(v, bool) or not isinstance(v, int) for v in (start, end)) or not 0 <= start <= end <= len(rows): raise ValueError("viewport")
113
+ visible = rows[start:end]
114
+ view_range = {"available": True, "index_from": start, "index_to_exclusive": end,
115
+ "count": len(visible), "start_time": visible[0]["time"] if visible else None,
116
+ "end_time": visible[-1]["time"] if visible else None}
117
+ else: view_range = {"available": False, "reason": "not_reported"}
118
+ objects = state.get("drawings", []) if state["state"] == "ready" else []
119
+ if not isinstance(objects, list) or len(objects) > 512: raise ValueError("drawings")
120
+ drawing_keys = {"id", "kind", "origin", "name", "color", "interval", "price", "time", "text", "value", "icon", "start_time", "end_time", "lower_price", "upper_price", "show_fill", "show_midline", "series_hash", "band_hash", "sticks_hash", "geometry_hash", "rule_version", "as_of", "bar_count"}
121
+ drawings = []
122
+ for obj in objects:
123
+ item = {k: deepcopy(obj[k]) for k in drawing_keys if k in obj}
124
+ if obj.get("kind") == "labeled_polyline":
125
+ from tools.polylines import validate_stored_points
126
+ item["points"] = validate_stored_points(obj["points"])
127
+ elif obj.get("kind") in {"text_annotation", "number_annotation", "icon_annotation"}:
128
+ from tools.annotations import validate_annotation
129
+ annotation = validate_annotation({"type": "DRAW_AGENT_ANNOTATION", "kind": obj["kind"], "id": obj.get("id"),
130
+ "interval": obj.get("interval"), "label": obj.get("name", ""), "color": obj.get("color", "info"),
131
+ "time": obj.get("time"), "price": obj.get("price"), "text": obj.get("text"), "value": obj.get("value"),
132
+ "icon": obj.get("icon")})
133
+ item.update(time=annotation["time"], price=annotation["price"])
134
+ if obj["kind"] == "text_annotation": item["text"] = annotation["text"]
135
+ elif obj["kind"] == "number_annotation": item["value"] = annotation["value"]
136
+ else: item["icon"] = annotation["icon"]
137
+ elif "points" in obj: item["points"] = [{k: p[k] for k in ("time", "price")} for p in obj["points"][:8]]
138
+ if obj.get("kind") == "fibonacci_retracement":
139
+ from tools.fibonacci import validate_ratios
140
+ item["ratios"] = validate_ratios(obj["ratios"])
141
+ item["levels"] = [{"ratio": p["ratio"], "price": p["price"]} for p in obj["levels"][:16]]
142
+ item.update(context_editable=False, edit_capability="source_snapshot_only" if obj.get("origin") == "ai" else "read_only")
143
+ drawings.append(item)
144
+ selection = state.get("selection")
145
+ if selection:
146
+ keys = ("kind", "time") if selection.get("kind") == "candle" else ("kind", "start_time", "end_time")
147
+ selection = {k: selection[k] for k in keys}
148
+ except (ValueError, TypeError, KeyError, AttributeError, RowsValidationError):
149
+ raise LineError("invalid_chart_context", "图表数据或可见范围无效,未把已加载范围冒充为屏幕可见范围。") from None
150
+ selected = visible if candle_scope == "visible" else rows if candle_scope == "loaded" else []
151
+ result = {k: deepcopy(state.get(k)) for k in ("symbol", "name", "interval", "interval_value", "interval_value_status", "source_interval",
152
+ "ui_interval", "display_volume_unit", "range_key", "adjust", "active_page", "indicators", "data_status")}
153
+ source = state.get("source_chart_session")
154
+ result["data_provenance"] = sanitize_data_provenance(state)
155
+ result.update(ok=True, context_ref=context_ref, conversation_id=saved.get("conversation_id"), view_id=saved.get("view_id"),
156
+ guarded_apply_supported=saved.get("guarded_apply_supported") is True,
157
+ drawing_workflow="prepare_then_apply" if saved.get("guarded_apply_supported") is True else "observation_only",
158
+ revision=saved.get("revision"), observed_at_ms=observed, age_ms=max(0, int(age)), state=state["state"],
159
+ observation_source="live_browser_report", time_unit="unix_seconds", render_verified=False, live_view_editable=False,
160
+ source_chart_session=source if isinstance(source, str) and re.fullmatch(r"[A-Za-z0-9_-]{32}", source) else None,
161
+ source_snapshot_alignment="not_verified", loaded_range={"count":len(rows), "start_time": rows[0]["time"] if rows else None,
162
+ "end_time":rows[-1]["time"] if rows else None}, visible_range=view_range,
163
+ drawings=drawings, drawings_scope="stored_objects_for_active_instrument", selection=selection,
164
+ drawing_feedback=sanitize_drawing_feedback(saved.get("drawing_feedback"), [d for d in drawings if d.get("origin") == "ai"]),
165
+ selection_status=state.get("selection_status", "none"), selected_drawing_id=None, selected_drawing_status="not_supported",
166
+ drawing_capabilities=drawing_capabilities(),
167
+ candles=selected[-limit:], candle_selection={"scope":candle_scope,"total":len(selected),"returned":min(limit,len(selected)),
168
+ "truncated":len(selected)>limit,"order":"ascending","sample":"last_limit"})
169
+ result["source_status"] = sanitize_source_status(saved.get("source_status"))
170
+ # Keep raw candles untouched for strict source-alignment checks. Supply a
171
+ # separate deterministic display map so the host need not guess dates.
172
+ result["time_display"] = {"timezone": "UTC+08:00", "basis": "same_as_anchor_date_resolution",
173
+ "loaded_start": _time_label(rows[0]["time"] if rows else None),
174
+ "loaded_end": _time_label(rows[-1]["time"] if rows else None),
175
+ "visible_start": _time_label(visible[0]["time"] if visible else None),
176
+ "visible_end": _time_label(visible[-1]["time"] if visible else None),
177
+ "sample_labels": [_time_label(row["time"]) for row in selected[-limit:]]}
178
+ if region_start_time is not None:
179
+ if state["state"] != "ready":
180
+ raise LineError("chart_measurement_not_ready", "当前图未就绪,不能使用旧K线测量区域。")
181
+ result["region_measurements"] = measure_chart_region(rows, result["interval"], region_start_time, region_end_time)
182
+ if channel_candidate is not None:
183
+ if state["state"] != "ready":
184
+ raise LineError("chart_measurement_not_ready", "当前图未就绪,不能使用旧K线预览通道。")
185
+ result["channel_preview"] = preview_channel(rows, result["interval"], **channel_candidate)
186
+ return result