@ftshare-lab/dsh-kline 0.0.0-stage → 0.6.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +611 -0
- package/LICENSE +21 -0
- package/PROVENANCE.md +13 -0
- package/README.en.md +171 -0
- package/README.md +170 -2
- package/chart_service.py +687 -0
- package/config/basic-symbols.json +570 -0
- package/config/dsh-kline.patch.yml +4 -0
- package/config/dsh-tool-catalog.json +3875 -0
- package/cordis.patch.yml +33 -0
- package/core/__init__.py +0 -0
- package/core/adjustment.py +16 -0
- package/core/calc.py +691 -0
- package/core/rows.py +228 -0
- package/core/ta_engine.py +99 -0
- package/docs/anonymous-market-support.md +33 -0
- package/docs/automatic-drawing.md +24 -0
- package/docs/chart-functions.md +136 -0
- package/docs/drawing-examples.en.md +13 -0
- package/docs/drawing-examples.md +13 -0
- package/docs/embedding.md +77 -0
- package/docs/fixtures/price-pattern-real-v1.json +1 -0
- package/docs/free-foreign-daily.md +44 -0
- package/docs/guide.en.md +232 -0
- package/docs/guide.md +248 -0
- package/docs/images/abc-drawing-v0.5.0.jpg +0 -0
- package/docs/images/channel-drawing-v0.5.0.jpg +0 -0
- package/docs/images/drawing-workbench-v0.5.0.jpg +0 -0
- package/docs/images/dsh-kline-tab-workspace.png +0 -0
- package/docs/images/dsh-market.png +0 -0
- package/docs/images/kline-news.png +0 -0
- package/docs/images/kline-range-stats.png +0 -0
- package/docs/images/kline-support.png +0 -0
- package/docs/images/main-chart-comparison-v0.6.9.png +0 -0
- package/docs/images/market-overview-v0.6.9.png +0 -0
- package/docs/images/natural-language-abc-wolong-2026-10-27.png +0 -0
- package/docs/images/natural-language-descending-channel-wolong-2026-10-27.png +0 -0
- package/docs/images/platform-breakout-msft-v0.6.9.png +0 -0
- package/docs/npm-release.md +33 -0
- package/docs/price-pattern-rules-v1.md +40 -0
- package/docs/price-pattern-samples-v1.md +42 -0
- package/docs/provider-adaptation.md +73 -0
- package/docs/release-acceptance-v0.4.0.md +46 -0
- package/docs/release-acceptance-v0.4.1.md +43 -0
- package/docs/release-acceptance-v0.5.0.md +40 -0
- package/docs/release-acceptance-v0.6.0.md +33 -0
- package/docs/release-acceptance-v0.6.1.md +19 -0
- package/docs/release-acceptance-v0.6.10.md +21 -0
- package/docs/release-acceptance-v0.6.11.md +21 -0
- package/docs/release-acceptance-v0.6.2.md +31 -0
- package/docs/release-acceptance-v0.6.3.md +25 -0
- package/docs/release-acceptance-v0.6.4.md +24 -0
- package/docs/release-acceptance-v0.6.5.md +21 -0
- package/docs/release-acceptance-v0.6.6.md +21 -0
- package/docs/release-acceptance-v0.6.7.md +18 -0
- package/docs/release-acceptance-v0.6.8.md +18 -0
- package/docs/release-acceptance-v0.6.9.md +98 -0
- package/docs/release-notes-v0.5.0.md +23 -0
- package/docs/release-notes-v0.6.0.md +11 -0
- package/docs/release-notes-v0.6.1.md +20 -0
- package/docs/release-notes-v0.6.10.md +11 -0
- package/docs/release-notes-v0.6.11.md +16 -0
- package/docs/release-notes-v0.6.2.md +14 -0
- package/docs/release-notes-v0.6.3.md +26 -0
- package/docs/release-notes-v0.6.4.md +12 -0
- package/docs/release-notes-v0.6.5.md +13 -0
- package/docs/release-notes-v0.6.6.md +13 -0
- package/docs/release-notes-v0.6.7.md +17 -0
- package/docs/release-notes-v0.6.8.md +10 -0
- package/docs/release-notes-v0.6.9.md +16 -0
- package/lib/candle-sequence.js +15 -0
- package/lib/chart-adjustment.js +7 -0
- package/lib/chart-annotations.js +33 -0
- package/lib/chart-applications.js +171 -0
- package/lib/chart-context.js +164 -0
- package/lib/chart-observation.js +251 -0
- package/lib/chart-service-status.js +82 -0
- package/lib/chart-source-status.js +39 -0
- package/lib/chart-sources.js +354 -0
- package/lib/client/BetterSidebarTab.js +70 -0
- package/lib/client/ClassicShell.js +254 -0
- package/lib/client/KlineContent.js +155 -0
- package/lib/client/PanelHost.js +46 -0
- package/lib/client/chart-apply.js +73 -0
- package/lib/client/chart-context.js +233 -0
- package/lib/client/chart-handoff.js +34 -0
- package/lib/client/chart-session-resolver.js +74 -0
- package/lib/client/client-context.js +1 -0
- package/lib/client/conversation.js +88 -0
- package/lib/client/default-tab.js +83 -0
- package/lib/client/embed.js +50 -0
- package/lib/client/generated-view.js +12983 -0
- package/lib/client/horizontal-lines.js +19 -0
- package/lib/client/host-options.js +41 -0
- package/lib/client/host-panels.js +111 -0
- package/lib/client/index.js +77 -0
- package/lib/client/mode-preferences.js +48 -0
- package/lib/client/native-sidebar-contract.js +45 -0
- package/lib/client/native-sidebar-register.js +133 -0
- package/lib/client/native-sidebar-services.js +1 -0
- package/lib/client/native-sidebar.js +98 -0
- package/lib/client/sidebar-integration.js +93 -0
- package/lib/client/ui-onboarding.js +48 -0
- package/lib/client/version.js +14 -0
- package/lib/client.js +17581 -0
- package/lib/client.js.map +1 -0
- package/lib/drawing-feedback.js +284 -0
- package/lib/fibonacci.js +18 -0
- package/lib/ftshare-settings-bridge.js +159 -0
- package/lib/index.js +279 -0
- package/lib/labeled-polyline.js +17 -0
- package/lib/pattern-groups.js +91 -0
- package/lib/price-bands.js +55 -0
- package/lib/price-series.js +47 -0
- package/lib/price-sticks.js +32 -0
- package/lib/types/candle-sequence.d.ts +2 -0
- package/lib/types/chart-adjustment.d.ts +2 -0
- package/lib/types/chart-annotations.d.ts +4 -0
- package/lib/types/chart-applications.d.ts +26 -0
- package/lib/types/chart-context.d.ts +14 -0
- package/lib/types/chart-observation.d.ts +8 -0
- package/lib/types/chart-service-status.d.ts +22 -0
- package/lib/types/chart-source-status.d.ts +47 -0
- package/lib/types/chart-sources.d.ts +25 -0
- package/lib/types/client/BetterSidebarTab.d.ts +12 -0
- package/lib/types/client/ClassicShell.d.ts +4 -0
- package/lib/types/client/KlineContent.d.ts +37 -0
- package/lib/types/client/PanelHost.d.ts +25 -0
- package/lib/types/client/chart-apply.d.ts +13 -0
- package/lib/types/client/chart-context.d.ts +23 -0
- package/lib/types/client/chart-handoff.d.ts +5 -0
- package/lib/types/client/chart-session-resolver.d.ts +2 -0
- package/lib/types/client/client-context.d.ts +16 -0
- package/lib/types/client/conversation.d.ts +43 -0
- package/lib/types/client/default-tab.d.ts +3 -0
- package/lib/types/client/embed.d.ts +37 -0
- package/lib/types/client/generated-view.d.ts +2 -0
- package/lib/types/client/horizontal-lines.d.ts +1 -0
- package/lib/types/client/host-options.d.ts +38 -0
- package/lib/types/client/host-panels.d.ts +55 -0
- package/lib/types/client/index.d.ts +4 -0
- package/lib/types/client/mode-preferences.d.ts +25 -0
- package/lib/types/client/native-sidebar-contract.d.ts +52 -0
- package/lib/types/client/native-sidebar-register.d.ts +46 -0
- package/lib/types/client/native-sidebar-services.d.ts +45 -0
- package/lib/types/client/native-sidebar.d.ts +47 -0
- package/lib/types/client/sidebar-integration.d.ts +12 -0
- package/lib/types/client/ui-onboarding.d.ts +7 -0
- package/lib/types/client/version.d.ts +1 -0
- package/lib/types/drawing-feedback.d.ts +5 -0
- package/lib/types/fibonacci.d.ts +5 -0
- package/lib/types/ftshare-settings-bridge.d.ts +50 -0
- package/lib/types/index.d.ts +26 -0
- package/lib/types/labeled-polyline.d.ts +11 -0
- package/lib/types/pattern-groups.d.ts +2 -0
- package/lib/types/price-bands.d.ts +3 -0
- package/lib/types/price-series.d.ts +5 -0
- package/lib/types/price-sticks.d.ts +3 -0
- package/package.json +155 -4
- package/requirements.txt +6 -0
- package/screenshots.json +8 -0
- package/scripts/bootstrap.sh +5 -0
- package/scripts/dsh-bootstrap.mjs +179 -0
- package/scripts/dsh-mcp-plugin.mjs +27 -0
- package/scripts/run-dsh-kline.mjs +658 -0
- package/scripts/run-dsh-kline.sh +5 -0
- package/server.py +1755 -0
- package/tools/__init__.py +0 -0
- package/tools/annotations.py +119 -0
- package/tools/automatic_analysis.py +158 -0
- package/tools/baostock_source.py +176 -0
- package/tools/calc.py +39 -0
- package/tools/channel_candidates.py +260 -0
- package/tools/channel_preview.py +82 -0
- package/tools/channels.py +104 -0
- package/tools/chart_applications.py +204 -0
- package/tools/chart_context.py +186 -0
- package/tools/chart_edits.py +363 -0
- package/tools/chart_functions.py +451 -0
- package/tools/chart_indicators.py +65 -0
- package/tools/chart_measurements.py +84 -0
- package/tools/chart_source_status.py +32 -0
- package/tools/chart_sources.py +31 -0
- package/tools/closed_daily.py +68 -0
- package/tools/draw.py +410 -0
- package/tools/drawing_feedback.py +45 -0
- package/tools/drawing_interaction.py +117 -0
- package/tools/drawing_verification.py +141 -0
- package/tools/fetch.py +4680 -0
- package/tools/fibonacci.py +83 -0
- package/tools/foreign_daily.py +185 -0
- package/tools/free_sources.py +483 -0
- package/tools/lines.py +91 -0
- package/tools/nine_count.py +66 -0
- package/tools/pattern_groups.py +103 -0
- package/tools/pivots.py +60 -0
- package/tools/polylines.py +131 -0
- package/tools/price_bands.py +165 -0
- package/tools/price_patterns.py +311 -0
- package/tools/price_series.py +162 -0
- package/tools/price_sticks.py +114 -0
- package/tools/range_candidates.py +170 -0
- package/tools/recent_drawing_candidates.py +123 -0
- package/tools/rectangles.py +76 -0
- package/tools/regression_channels.py +87 -0
- package/tools/ta_functions.py +228 -0
- package/tools/trend_lines.py +106 -0
- package/tools/watchlist.py +149 -0
- package/view/ft-logo.jpg +0 -0
- package/view/kline.html +12436 -0
- package/view/vendor/klinecharts.min.js +7 -0
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
/** Browser-input snapshots. A handoff changes only source identity, never the chart. */
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { drawingInventory, observationKey, sanitizeChartContext, text } from "./chart-observation.js";
|
|
6
|
+
import { sourceStatus } from "./chart-source-status.js";
|
|
7
|
+
import { normalizeAdjustment } from "./chart-adjustment.js";
|
|
8
|
+
import { fibonacciOverlayPoints } from "./fibonacci.js";
|
|
9
|
+
import { sanitizePolylinePoints } from "./labeled-polyline.js";
|
|
10
|
+
import { sanitizeChartAnnotation } from "./chart-annotations.js";
|
|
11
|
+
import { sanitizePriceSeriesCommand } from "./price-series.js";
|
|
12
|
+
import { sanitizePriceBandCommand } from "./price-bands.js";
|
|
13
|
+
import { candleSequenceHash } from "./candle-sequence.js";
|
|
14
|
+
import { sanitizePriceSticksCommand } from "./price-sticks.js";
|
|
15
|
+
import { sanitizePatternGroupCommand } from "./pattern-groups.js";
|
|
16
|
+
const TOKEN = /^[A-Za-z0-9_-]{32}$/;
|
|
17
|
+
const AI = new Set(['DRAW_HORIZONTAL_LINE', 'DRAW_AGENT_TREND_LINE', 'DRAW_AGENT_CHANNEL', 'DRAW_AGENT_RECTANGLE', 'DRAW_AGENT_FIBONACCI', 'DRAW_AGENT_POLYLINE', 'DRAW_AGENT_ANNOTATION', 'DRAW_AGENT_SERIES_LINE', 'DRAW_AGENT_PRICE_BAND', 'DRAW_AGENT_PRICE_STICKS', 'DRAW_AGENT_PRICE_PATTERN', 'DRAW_AGENT_NINE_COUNT']);
|
|
18
|
+
const INTERVALS = ['minute', 'day', 'week', 'month', 'quarter', 'year'];
|
|
19
|
+
function finite(value, positive = false) {
|
|
20
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || positive && value <= 0)
|
|
21
|
+
throw Error('invalid_source_number');
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
function point(raw) {
|
|
25
|
+
if (!Number.isSafeInteger(raw?.time) || raw.time <= 0)
|
|
26
|
+
throw Error('invalid_source_point');
|
|
27
|
+
return { time: raw.time, price: finite(raw.price, true) };
|
|
28
|
+
}
|
|
29
|
+
function color(raw) {
|
|
30
|
+
if (!['info', 'warning', 'success', 'danger'].includes(raw))
|
|
31
|
+
throw Error('invalid_source_color');
|
|
32
|
+
return raw;
|
|
33
|
+
}
|
|
34
|
+
function canonicalAI(state) {
|
|
35
|
+
return observationKey({ ...state, drawings: state.drawings.filter((d) => d.origin === 'ai') });
|
|
36
|
+
}
|
|
37
|
+
function sourceKey(state) {
|
|
38
|
+
// A source can have fewer candles than the new view. Its data key must
|
|
39
|
+
// not validate that new view's viewport indices against the old row count.
|
|
40
|
+
const s = sanitizeChartContext({ ...state, visible_range: { available: false }, selection: null });
|
|
41
|
+
s.adjust = normalizeAdjustment(s.adjust) ?? s.adjust;
|
|
42
|
+
return observationKey({ ...s, name: '', range_key: '', source_interval: '', ui_interval: '', display_volume_unit: '', active_page: '',
|
|
43
|
+
source_chart_session: null, visible_range: { available: false }, selection: null, selection_status: 'none', indicators: [], data_status: '',
|
|
44
|
+
data_provenance: null, drawings: s.drawings.filter((d) => d.origin === 'ai') });
|
|
45
|
+
}
|
|
46
|
+
/** Keep only renderer fields; never copy arbitrary metadata, URLs or provider secrets. */
|
|
47
|
+
export function sanitizeSourcePayload(raw, state) {
|
|
48
|
+
if (raw?.symbol !== state.symbol || raw?.interval !== state.interval || normalizeAdjustment(raw?.adjust) === null
|
|
49
|
+
|| normalizeAdjustment(raw?.adjust) !== normalizeAdjustment(state.adjust)
|
|
50
|
+
|| !Array.isArray(raw.chartCommands) || raw.chartCommands.length > 256)
|
|
51
|
+
throw Error('source_payload_mismatch');
|
|
52
|
+
let candleCount = 0;
|
|
53
|
+
const commands = raw.chartCommands.map((c) => {
|
|
54
|
+
const type = c.type;
|
|
55
|
+
if (type === 'SET_CANDLES') {
|
|
56
|
+
candleCount++;
|
|
57
|
+
const cleaned = sanitizeChartContext({ ...state, candles: c.rows });
|
|
58
|
+
if (JSON.stringify(cleaned.candles) !== JSON.stringify(state.candles))
|
|
59
|
+
throw Error('source_rows_mismatch');
|
|
60
|
+
return { type, rows: cleaned.candles };
|
|
61
|
+
}
|
|
62
|
+
if (type === 'SET_RANGE')
|
|
63
|
+
return { type, start: finite(c.start, true), end: finite(c.end, true) };
|
|
64
|
+
if (type === 'SET_INDICATOR_SERIES') {
|
|
65
|
+
if (!['ma', 'vwap', 'vol', 'macd', 'kdj', 'boll', 'rsi', 'atr'].includes(c.name)
|
|
66
|
+
|| !['candle', 'vol', 'macd', 'kdj', 'rsi', 'atr'].includes(c.pane)
|
|
67
|
+
|| !c.data || typeof c.data !== 'object' || Array.isArray(c.data) || Object.keys(c.data).length > 32)
|
|
68
|
+
throw Error('invalid_source_indicator');
|
|
69
|
+
const params = {};
|
|
70
|
+
for (const key of ['period', 'ma_period', 'fast', 'slow', 'signal', 'n', 'm1', 'm2', 'std_mult'])
|
|
71
|
+
if (c.params?.[key] != null)
|
|
72
|
+
params[key] = finite(c.params[key], true);
|
|
73
|
+
if (c.params?.periods) {
|
|
74
|
+
if (!Array.isArray(c.params.periods) || c.params.periods.length > 8)
|
|
75
|
+
throw Error('invalid_source_indicator');
|
|
76
|
+
params.periods = c.params.periods.map((p) => finite(p, true));
|
|
77
|
+
}
|
|
78
|
+
if (c.params?.anchor === 'loaded_context')
|
|
79
|
+
params.anchor = 'loaded_context';
|
|
80
|
+
const data = {};
|
|
81
|
+
for (const [key, values] of Object.entries(c.data)) {
|
|
82
|
+
if (!/^(?:ma\d{1,3}|vwap|vol_ma|dif|dea|hist|k|d|j|mid|upper|lower|rsi|atr)$/.test(key)
|
|
83
|
+
|| !values || typeof values !== 'object' || Array.isArray(values) || Object.keys(values).length > 12000)
|
|
84
|
+
throw Error('invalid_source_indicator');
|
|
85
|
+
data[key] = Object.fromEntries(Object.entries(values).map(([time, value]) => {
|
|
86
|
+
if (!/^[1-9]\d{0,12}$/.test(time))
|
|
87
|
+
throw Error('invalid_source_indicator_time');
|
|
88
|
+
return [time, finite(value)];
|
|
89
|
+
}));
|
|
90
|
+
}
|
|
91
|
+
return { type, name: c.name, pane: c.pane, params, data };
|
|
92
|
+
}
|
|
93
|
+
if (type === 'SET_COMPARISON_SERIES') {
|
|
94
|
+
if (!Array.isArray(c.series) || c.series.length > 3)
|
|
95
|
+
throw Error('invalid_source_comparison');
|
|
96
|
+
return { type, series: c.series.map((s) => ({ symbol: text(s.symbol, 64), name: text(s.name ?? '', 128),
|
|
97
|
+
rows: sanitizeChartContext({ ...state, candles: s.rows }).candles })) };
|
|
98
|
+
}
|
|
99
|
+
if (type === 'DRAW_AGENT_ANNOTATION') {
|
|
100
|
+
const annotation = sanitizeChartAnnotation(c);
|
|
101
|
+
if (annotation.interval !== state.interval)
|
|
102
|
+
throw Error('invalid_source_interval');
|
|
103
|
+
return annotation;
|
|
104
|
+
}
|
|
105
|
+
if (type === 'DRAW_AGENT_SERIES_LINE') {
|
|
106
|
+
const clean = sanitizePriceSeriesCommand(c, state.candles.length, state.interval);
|
|
107
|
+
if (clean.interval === state.interval && clean.row_hash && clean.row_hash !== candleSequenceHash(state.candles))
|
|
108
|
+
throw Error('source_sequence_rows_mismatch');
|
|
109
|
+
return clean;
|
|
110
|
+
}
|
|
111
|
+
if (type === 'DRAW_AGENT_PRICE_BAND') {
|
|
112
|
+
const clean = sanitizePriceBandCommand(c, state.candles.length, state.interval);
|
|
113
|
+
if (clean.interval === state.interval && clean.row_hash && clean.row_hash !== candleSequenceHash(state.candles))
|
|
114
|
+
throw Error('source_sequence_rows_mismatch');
|
|
115
|
+
return clean;
|
|
116
|
+
}
|
|
117
|
+
if (type === 'DRAW_AGENT_PRICE_STICKS') {
|
|
118
|
+
const clean = sanitizePriceSticksCommand(c, state.candles.length, state.interval);
|
|
119
|
+
if (clean.interval === state.interval && clean.row_hash && clean.row_hash !== candleSequenceHash(state.candles))
|
|
120
|
+
throw Error('source_sequence_rows_mismatch');
|
|
121
|
+
return clean;
|
|
122
|
+
}
|
|
123
|
+
if (type === 'DRAW_AGENT_PRICE_PATTERN' || type === 'DRAW_AGENT_NINE_COUNT') {
|
|
124
|
+
return sanitizePatternGroupCommand(c, state.interval);
|
|
125
|
+
}
|
|
126
|
+
if (type === 'TEXT_MARKER')
|
|
127
|
+
return { type, id: text(c.id ?? '', 256), text: text(c.text ?? '', 256), ...point(c), color: color(c.color ?? 'info') };
|
|
128
|
+
if (type === 'DRAW_TREND_LINE')
|
|
129
|
+
return { type, id: text(c.id ?? '', 256), label: text(c.label ?? '', 128),
|
|
130
|
+
from: point(c.from), to: point(c.to), color: color(c.color ?? 'info') };
|
|
131
|
+
if (!AI.has(type))
|
|
132
|
+
throw Error('unsupported_source_command');
|
|
133
|
+
const result = { type, id: text(c.id, 256), label: text(c.label ?? '', 48), color: color(c.color ?? 'info') };
|
|
134
|
+
if (c.interval != null) {
|
|
135
|
+
if (!INTERVALS.includes(c.interval))
|
|
136
|
+
throw Error('invalid_source_interval');
|
|
137
|
+
result.interval = c.interval;
|
|
138
|
+
}
|
|
139
|
+
if (type === 'DRAW_HORIZONTAL_LINE')
|
|
140
|
+
result.price = finite(c.price, true);
|
|
141
|
+
else if (type === 'DRAW_AGENT_RECTANGLE') {
|
|
142
|
+
result.start_time = point({ time: c.start_time, price: c.lower_price }).time;
|
|
143
|
+
result.end_time = point({ time: c.end_time, price: c.upper_price }).time;
|
|
144
|
+
result.lower_price = finite(c.lower_price, true);
|
|
145
|
+
result.upper_price = finite(c.upper_price, true);
|
|
146
|
+
if (typeof c.show_fill !== 'boolean')
|
|
147
|
+
throw Error('invalid_source_style');
|
|
148
|
+
result.show_fill = c.show_fill;
|
|
149
|
+
}
|
|
150
|
+
else if (type === 'DRAW_AGENT_POLYLINE') {
|
|
151
|
+
if (!result.interval)
|
|
152
|
+
throw Error('invalid_source_interval');
|
|
153
|
+
result.points = sanitizePolylinePoints(c.points);
|
|
154
|
+
}
|
|
155
|
+
else {
|
|
156
|
+
result.from = point(c.from);
|
|
157
|
+
result.to = point(c.to);
|
|
158
|
+
if (type === 'DRAW_AGENT_FIBONACCI') {
|
|
159
|
+
fibonacciOverlayPoints(c);
|
|
160
|
+
if (!result.interval)
|
|
161
|
+
throw Error('invalid_source_interval');
|
|
162
|
+
Object.assign(result, { ratios: [...c.ratios], levels: c.levels.map((p) => ({ ratio: p.ratio, price: p.price })),
|
|
163
|
+
geometry_basis: 'linear_price_retracement' });
|
|
164
|
+
}
|
|
165
|
+
if (type === 'DRAW_AGENT_CHANNEL') {
|
|
166
|
+
result.parallel = point(c.parallel);
|
|
167
|
+
for (const edge of ['upper', 'lower'])
|
|
168
|
+
result[edge] = { from: point(c[edge]?.from), to: point(c[edge]?.to) };
|
|
169
|
+
for (const key of ['width', 'signed_offset', 'slope_per_bar'])
|
|
170
|
+
result[key] = finite(c[key], key === 'width');
|
|
171
|
+
if (typeof c.show_midline !== 'boolean' || !['ascending', 'descending', 'horizontal'].includes(c.direction)
|
|
172
|
+
|| c.geometry_basis !== 'candle_index_linear_price')
|
|
173
|
+
throw Error('invalid_source_channel');
|
|
174
|
+
Object.assign(result, { show_midline: c.show_midline, direction: c.direction, geometry_basis: c.geometry_basis });
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return result;
|
|
178
|
+
});
|
|
179
|
+
if (candleCount !== 1)
|
|
180
|
+
throw Error('invalid_source_candles');
|
|
181
|
+
const meta = { source: state.data_provenance.provider, status: state.data_status };
|
|
182
|
+
const zone = state.data_provenance.aggregation?.timezone ?? raw.data_meta?.exchange_timezone;
|
|
183
|
+
if (typeof zone === 'string' && zone.length <= 64 && /^[A-Za-z_+-]+(?:\/[A-Za-z0-9_+-]+){0,2}$/.test(zone)) {
|
|
184
|
+
try {
|
|
185
|
+
new Intl.DateTimeFormat('en', { timeZone: zone });
|
|
186
|
+
meta.exchange_timezone = zone;
|
|
187
|
+
}
|
|
188
|
+
catch { }
|
|
189
|
+
}
|
|
190
|
+
if (typeof raw.data_meta?.updated_at === 'number' && Number.isFinite(raw.data_meta.updated_at) && raw.data_meta.updated_at > 0)
|
|
191
|
+
meta.updated_at = raw.data_meta.updated_at;
|
|
192
|
+
const payload = { symbol: state.symbol, name: state.name, interval: state.interval, interval_value: state.interval_value,
|
|
193
|
+
adjust: state.adjust, range_key: state.range_key, count: state.candles.length, indicators: state.indicators,
|
|
194
|
+
display_volume_unit: state.display_volume_unit,
|
|
195
|
+
indicators_explicit: true, data_meta: meta, chartCommands: commands };
|
|
196
|
+
if (canonicalAI({ ...state, drawings: drawingInventory(payload) }) !== canonicalAI(state))
|
|
197
|
+
throw Error('source_inventory_mismatch');
|
|
198
|
+
return payload;
|
|
199
|
+
}
|
|
200
|
+
export class ChartSources {
|
|
201
|
+
offers = new Map();
|
|
202
|
+
runtime;
|
|
203
|
+
now;
|
|
204
|
+
constructor(runtime, now = () => Date.now()) { this.runtime = runtime; this.now = now; }
|
|
205
|
+
proofPath(ref, token) {
|
|
206
|
+
if (!TOKEN.test(ref) || !TOKEN.test(token))
|
|
207
|
+
throw Error('invalid_source_identity');
|
|
208
|
+
return join(this.runtime, 'sources', String(process.pid), ref, token + '.json');
|
|
209
|
+
}
|
|
210
|
+
async read(path) {
|
|
211
|
+
const data = await readFile(path, 'utf8');
|
|
212
|
+
if (data.length > 8 * 1024 * 1024)
|
|
213
|
+
throw Error('invalid_source_size');
|
|
214
|
+
return JSON.parse(data);
|
|
215
|
+
}
|
|
216
|
+
async write(path, value) {
|
|
217
|
+
await mkdir(join(path, '..'), { recursive: true, mode: 0o700 });
|
|
218
|
+
const tmp = path + '.' + randomBytes(8).toString('hex') + '.tmp';
|
|
219
|
+
await writeFile(tmp, JSON.stringify(value), { mode: 0o600, flag: 'wx' });
|
|
220
|
+
await rename(tmp, path);
|
|
221
|
+
}
|
|
222
|
+
async acknowledge(view, receipt) {
|
|
223
|
+
const offer = this.offers.get(view.ref);
|
|
224
|
+
if (!TOKEN.test(receipt?.chart_session ?? '') || !['bound', 'rejected'].includes(receipt.status))
|
|
225
|
+
throw Error('invalid_source_receipt');
|
|
226
|
+
// A view can expire/remount while a receipt is in flight. Reject and let
|
|
227
|
+
// that browser restore its prior identity; never leave publication stuck.
|
|
228
|
+
if (!offer || receipt.chart_session !== offer.chart_session)
|
|
229
|
+
return { chart_session: receipt.chart_session, status: 'rejected' };
|
|
230
|
+
if (view.conversation !== offer.conversation_id || view.view !== offer.view_id)
|
|
231
|
+
return { chart_session: offer.chart_session, status: 'rejected' };
|
|
232
|
+
if (offer.status !== 'offered')
|
|
233
|
+
return { chart_session: offer.chart_session, status: offer.status };
|
|
234
|
+
const expected = { ...offer.base_state, source_chart_session: offer.chart_session };
|
|
235
|
+
offer.status = receipt.status === 'bound' && view.active && !view.ambiguous && this.now() <= offer.expires_at_ms
|
|
236
|
+
&& view.conversation === offer.conversation_id && view.view === offer.view_id
|
|
237
|
+
&& observationKey(view.state) === observationKey(expected) ? 'confirmed' : 'rejected';
|
|
238
|
+
await this.write(this.proofPath(view.ref, offer.chart_session), { host_process_id: process.pid, context_ref: view.ref,
|
|
239
|
+
conversation_id: offer.conversation_id, view_id: offer.view_id, chart_session: offer.chart_session, status: offer.status,
|
|
240
|
+
acknowledged_at_ms: this.now() });
|
|
241
|
+
return { chart_session: offer.chart_session, status: offer.status };
|
|
242
|
+
}
|
|
243
|
+
async offer(view, raw) {
|
|
244
|
+
return (await this.assess(view, raw)).handoff;
|
|
245
|
+
}
|
|
246
|
+
async assess(view, raw) {
|
|
247
|
+
const result = (reason, handoff) => ({ status: sourceStatus(reason), handoff });
|
|
248
|
+
for (const [ref, item] of this.offers)
|
|
249
|
+
if (this.now() > item.expires_at_ms + 300000)
|
|
250
|
+
this.offers.delete(ref);
|
|
251
|
+
if (!view.active)
|
|
252
|
+
return result('view_inactive');
|
|
253
|
+
if (view.ambiguous)
|
|
254
|
+
return result('ambiguous_views');
|
|
255
|
+
if (!view.applyCapable)
|
|
256
|
+
return result('client_unsupported');
|
|
257
|
+
if (view.state.state !== 'ready' || !view.state.candles.length || !view.state.symbol)
|
|
258
|
+
return result('chart_not_ready');
|
|
259
|
+
if (view.state.candles.length > 4000)
|
|
260
|
+
return result('source_limit_exceeded');
|
|
261
|
+
if (!INTERVALS.includes(view.state.interval) || normalizeAdjustment(view.state.adjust) === null
|
|
262
|
+
|| view.state.interval === 'minute' && view.state.interval_value === null)
|
|
263
|
+
return result('source_metadata_unknown');
|
|
264
|
+
// A pending drawing must finish or fail explicitly before its source can change.
|
|
265
|
+
let pending;
|
|
266
|
+
try {
|
|
267
|
+
pending = await this.read(join(this.runtime, 'edits', String(process.pid), view.ref, 'pending.json'));
|
|
268
|
+
}
|
|
269
|
+
catch (error) {
|
|
270
|
+
if (error?.code !== 'ENOENT')
|
|
271
|
+
throw error;
|
|
272
|
+
}
|
|
273
|
+
if (pending) {
|
|
274
|
+
if (!TOKEN.test(pending.candidate_chart_session ?? ''))
|
|
275
|
+
return result('drawing_outcome_unknown');
|
|
276
|
+
let app;
|
|
277
|
+
try {
|
|
278
|
+
app = await this.read(join(this.runtime, 'edits', String(process.pid), view.ref, 'applications', pending.candidate_chart_session + '.json'));
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
return result('drawing_outcome_unknown');
|
|
282
|
+
}
|
|
283
|
+
if (!['applied', 'rejected', 'failed'].includes(app.status))
|
|
284
|
+
return result(['queued', 'delivered'].includes(app.status) ? 'drawing_pending' : 'drawing_outcome_unknown');
|
|
285
|
+
}
|
|
286
|
+
const parent = view.state.source_chart_session;
|
|
287
|
+
const hasParent = TOKEN.test(parent ?? '');
|
|
288
|
+
// A chart opened by the browser's symbol search has no Agent-created
|
|
289
|
+
// parent. Bootstrap only from this locally rendered chart; an initial
|
|
290
|
+
// source must not inherit any unverified AI object.
|
|
291
|
+
if (!hasParent && raw?.local_render !== true)
|
|
292
|
+
return result('source_missing');
|
|
293
|
+
let source = null;
|
|
294
|
+
if (hasParent) {
|
|
295
|
+
const saved = await this.read(join(this.runtime, 'sessions', parent + '.json'));
|
|
296
|
+
if (saved.host_process_id !== process.pid || saved.session !== parent || saved.ok !== true)
|
|
297
|
+
throw Error('source_parent_unavailable');
|
|
298
|
+
source = saved.payload;
|
|
299
|
+
}
|
|
300
|
+
if (source?.drawing_guard) {
|
|
301
|
+
const g = source.drawing_guard;
|
|
302
|
+
const app = await this.read(join(this.runtime, 'edits', String(process.pid), g.context_ref, 'applications', parent + '.json'));
|
|
303
|
+
if (app.status !== 'applied' || app.confirmed_chart_session !== parent || app.conversation_id !== view.conversation
|
|
304
|
+
|| app.host_process_id !== process.pid || app.view_id !== g.view_id || app.request_id !== g.request_id
|
|
305
|
+
|| g.conversation_id !== view.conversation)
|
|
306
|
+
throw Error('unconfirmed_source_parent');
|
|
307
|
+
}
|
|
308
|
+
if (source?.view_source_guard) {
|
|
309
|
+
const g = source.view_source_guard, proof = await this.read(this.proofPath(g.context_ref, parent));
|
|
310
|
+
if (proof.status !== 'confirmed' || proof.conversation_id !== view.conversation || proof.host_process_id !== process.pid
|
|
311
|
+
|| proof.chart_session !== parent || g.chart_session !== parent || proof.view_id !== g.view_id
|
|
312
|
+
|| g.conversation_id !== view.conversation)
|
|
313
|
+
throw Error('unconfirmed_source_parent');
|
|
314
|
+
}
|
|
315
|
+
const rows = source?.chartCommands?.find((c) => c.type === 'SET_CANDLES')?.rows;
|
|
316
|
+
if (source?.symbol === view.state.symbol && Array.isArray(rows)) {
|
|
317
|
+
const original = { ...view.state, symbol: source.symbol, interval: source.interval, interval_value: source.interval_value ?? null,
|
|
318
|
+
adjust: source.adjust ?? '', candles: rows, drawings: drawingInventory(source) };
|
|
319
|
+
if (sourceKey(original) === sourceKey(view.state))
|
|
320
|
+
return result('source_matches_view');
|
|
321
|
+
}
|
|
322
|
+
const previous = this.offers.get(view.ref);
|
|
323
|
+
if (previous?.status === 'offered' && observationKey(previous.base_state) === observationKey(view.state)
|
|
324
|
+
&& this.now() <= previous.expires_at_ms)
|
|
325
|
+
return result('source_handoff_pending', previous);
|
|
326
|
+
if (!raw)
|
|
327
|
+
return result(hasParent ? 'source_snapshot_mismatch' : 'source_missing');
|
|
328
|
+
const payload = sanitizeSourcePayload(raw, view.state), token = randomBytes(24).toString('base64url');
|
|
329
|
+
const ai = payload.chartCommands.filter((c) => AI.has(c.type));
|
|
330
|
+
const old = source?.symbol === view.state.symbol ? source.chartCommands.filter((c) => AI.has(c.type)) : [];
|
|
331
|
+
if (ai.length !== old.length || new Set(ai.map((c) => c.id)).size !== ai.length)
|
|
332
|
+
throw Error('source_inventory_mismatch');
|
|
333
|
+
// The handoff may change rows/period, never existing AI definitions or geometry.
|
|
334
|
+
const ordered = (x) => Array.isArray(x) ? x.map(ordered) : x && typeof x === 'object'
|
|
335
|
+
? Object.fromEntries(Object.keys(x).sort().map(k => [k, ordered(x[k])])) : x;
|
|
336
|
+
for (const c of ai) {
|
|
337
|
+
const parent = old.find((p) => p.id === c.id && p.type === c.type);
|
|
338
|
+
if (!parent || !c.id || Object.keys(c).some(k => JSON.stringify(ordered(c[k])) !== JSON.stringify(ordered(parent[k]))))
|
|
339
|
+
throw Error('source_ai_changed');
|
|
340
|
+
}
|
|
341
|
+
payload.view_source_guard = { protocol: 'browser-source-v1', context_ref: view.ref, conversation_id: view.conversation,
|
|
342
|
+
view_id: view.view, expected_revision: view.revision, chart_session: token };
|
|
343
|
+
if (hasParent)
|
|
344
|
+
payload.drawing_parent_session = parent;
|
|
345
|
+
await this.write(join(this.runtime, 'sessions', token + '.json'), { ok: true, session: token, host_process_id: process.pid,
|
|
346
|
+
symbol: payload.symbol, name: payload.name, published_at: Math.floor(this.now() / 1000), payload });
|
|
347
|
+
const offer = { chart_session: token, context_ref: view.ref, conversation_id: view.conversation, view_id: view.view,
|
|
348
|
+
expected_revision: view.revision, base_state: view.state, expires_at_ms: this.now() + 30000, status: 'offered' };
|
|
349
|
+
await this.write(this.proofPath(view.ref, token), { host_process_id: process.pid, context_ref: view.ref,
|
|
350
|
+
conversation_id: view.conversation, view_id: view.view, chart_session: token, status: 'offered' });
|
|
351
|
+
this.offers.set(view.ref, offer);
|
|
352
|
+
return result('source_handoff_pending', offer);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { useCallback, useContext, useEffect, useState, useSyncExternalStore } from 'react';
|
|
3
|
+
import { currentConversationId } from './conversation';
|
|
4
|
+
import { useChartReference } from './chart-session-resolver';
|
|
5
|
+
import { liveChartFor } from './chart-handoff';
|
|
6
|
+
import { NativeKlineApp, StandaloneKlineApp, standaloneWorkspaceScope } from './KlineContent';
|
|
7
|
+
import { InterfaceContext, readAutoOpen } from './mode-preferences';
|
|
8
|
+
import { KLINE_TAB_ID, klineTabTitle, migrateKlineTabTitle } from './sidebar-integration';
|
|
9
|
+
import { installDefaultKlineTabs } from './default-tab';
|
|
10
|
+
/** The chart itself, shared by every host tab: Better Sidebar and the native one. */
|
|
11
|
+
export function KlineTabContent({ sessions, conversationId, visible = true }) {
|
|
12
|
+
// Better Sidebar preserves a tab and its previous scope on the host's
|
|
13
|
+
// New Session screen. Never promote an already-present chart from that
|
|
14
|
+
// scope: accept a live result or its same-conversation tab handoff, never
|
|
15
|
+
// browser-cached history. New conversations still start on the Market page.
|
|
16
|
+
const [liveReference, setLiveReference] = useState(() => liveChartFor(sessions, conversationId));
|
|
17
|
+
const onNewChart = useCallback((reference) => {
|
|
18
|
+
setLiveReference(reference);
|
|
19
|
+
}, []);
|
|
20
|
+
const reference = useChartReference(sessions, conversationId, onNewChart);
|
|
21
|
+
const selectedReference = liveReference ?? (reference?.recovery ? reference : undefined);
|
|
22
|
+
const onIdentity = useCallback(() => { }, []);
|
|
23
|
+
return selectedReference
|
|
24
|
+
? _jsx(NativeKlineApp, { session: { ok: true, ...selectedReference, published_at: selectedReference.order }, conversationId: conversationId ?? '', ownerConversationId: conversationId, visible: visible, onIdentity: onIdentity }, selectedReference.session)
|
|
25
|
+
: _jsx(StandaloneKlineApp, { conversationId: standaloneWorkspaceScope(conversationId), ownerConversationId: conversationId, visible: visible, onIdentity: onIdentity });
|
|
26
|
+
}
|
|
27
|
+
function AutoOpen({ service, sessions, conversationId }) {
|
|
28
|
+
const onNewChart = useCallback((reference) => {
|
|
29
|
+
if (readAutoOpen())
|
|
30
|
+
service.openTab({ type: KLINE_TAB_ID }, { sessionId: conversationId });
|
|
31
|
+
}, [service, conversationId]);
|
|
32
|
+
useChartReference(sessions, conversationId, onNewChart);
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
function KlineTabFrame({ service, sessions, scope, tab, visible }) {
|
|
36
|
+
const interfaceState = useContext(InterfaceContext);
|
|
37
|
+
const sidebar = useSyncExternalStore(listener => service.subscribeState(listener), () => service.getSnapshot());
|
|
38
|
+
// A single-instance Better Sidebar tab retains its last scope during the
|
|
39
|
+
// host's "New Session" screen. The public sidebar snapshot deliberately
|
|
40
|
+
// has no active session there, so it is the authoritative signal: start the
|
|
41
|
+
// Market launcher until a real conversation becomes active.
|
|
42
|
+
const conversationId = sidebar.sessionId === scope.sessionId ? scope.sessionId : undefined;
|
|
43
|
+
useEffect(() => migrateKlineTabTitle(service, tab, scope.sessionId), [service, tab.id, tab.title, scope.sessionId]);
|
|
44
|
+
return (_jsx("div", { "data-dsh-kline-tab": "", style: { width: '100%', height: '100%', minHeight: 0, overflow: 'hidden' }, children: visible && interfaceState.mode === 'better-sidebar'
|
|
45
|
+
? _jsx(KlineTabContent, { conversationId: conversationId, sessions: sessions }, conversationId ?? 'launcher')
|
|
46
|
+
: visible && _jsx("div", { role: "status", style: { padding: 16 }, children: "\u5F53\u524D\u4F7F\u7528\u7ECF\u5178 K \u7EBF\u4FA7\u680F\uFF1B\u5982\u9700\u5728\u6B64\u5904\u6253\u5F00\u56FE\u8868\uFF0C\u8BF7\u5728\u7ECF\u5178\u4FA7\u680F\u53F3\u4E0A\u89D2\u300CUI\u300D\u5207\u6362\u4E3A\u539F\u751F Tab\u3002" }) }));
|
|
47
|
+
}
|
|
48
|
+
export function BetterSidebarBridge({ service, sessions }) {
|
|
49
|
+
const interfaceState = useContext(InterfaceContext);
|
|
50
|
+
const list = useSyncExternalStore(listener => sessions.list.subscribe(listener), () => sessions.list.getSnapshot());
|
|
51
|
+
const activeConversation = currentConversationId(list);
|
|
52
|
+
const isNativeTabMode = interfaceState.mode === 'better-sidebar';
|
|
53
|
+
useEffect(() => {
|
|
54
|
+
const dispose = service.registerTab({
|
|
55
|
+
id: KLINE_TAB_ID,
|
|
56
|
+
title: klineTabTitle(),
|
|
57
|
+
order: 120,
|
|
58
|
+
single: true,
|
|
59
|
+
component: (props) => (_jsx(InterfaceContext.Provider, { value: interfaceState, children: _jsx(KlineTabFrame, { ...props, service: service, sessions: sessions }) })),
|
|
60
|
+
});
|
|
61
|
+
// The tab is always registered so Classic mode retains a discoverable
|
|
62
|
+
// native entry. Only the explicitly chosen native-tab mode may insert or
|
|
63
|
+
// auto-open it for the user.
|
|
64
|
+
const stopDefaults = isNativeTabMode ? installDefaultKlineTabs(service) : () => { };
|
|
65
|
+
return () => { stopDefaults(); dispose(); };
|
|
66
|
+
}, [service, sessions, interfaceState, isNativeTabMode]);
|
|
67
|
+
return isNativeTabMode && activeConversation
|
|
68
|
+
? _jsx(AutoOpen, { service: service, sessions: sessions, conversationId: activeConversation }, activeConversation)
|
|
69
|
+
: null;
|
|
70
|
+
}
|