@dsh-ft/dsh-fft-paper-trading 0.7.1 → 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.
Files changed (130) hide show
  1. package/lib/client.js +1 -1
  2. package/package.json +1 -4
  3. package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +0 -611
  4. package/node_modules/@ftshare-lab/dsh-kline/LICENSE +0 -21
  5. package/node_modules/@ftshare-lab/dsh-kline/PROVENANCE.md +0 -13
  6. package/node_modules/@ftshare-lab/dsh-kline/README.en.md +0 -171
  7. package/node_modules/@ftshare-lab/dsh-kline/README.md +0 -171
  8. package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +0 -687
  9. package/node_modules/@ftshare-lab/dsh-kline/config/basic-symbols.json +0 -570
  10. package/node_modules/@ftshare-lab/dsh-kline/config/dsh-kline.patch.yml +0 -4
  11. package/node_modules/@ftshare-lab/dsh-kline/config/dsh-tool-catalog.json +0 -3875
  12. package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +0 -33
  13. package/node_modules/@ftshare-lab/dsh-kline/core/__init__.py +0 -0
  14. package/node_modules/@ftshare-lab/dsh-kline/core/adjustment.py +0 -16
  15. package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +0 -691
  16. package/node_modules/@ftshare-lab/dsh-kline/core/rows.py +0 -228
  17. package/node_modules/@ftshare-lab/dsh-kline/core/ta_engine.py +0 -99
  18. package/node_modules/@ftshare-lab/dsh-kline/lib/candle-sequence.js +0 -15
  19. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-adjustment.js +0 -7
  20. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-annotations.js +0 -33
  21. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +0 -171
  22. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +0 -164
  23. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +0 -251
  24. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-service-status.js +0 -82
  25. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-source-status.js +0 -39
  26. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +0 -354
  27. package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +0 -17581
  28. package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +0 -284
  29. package/node_modules/@ftshare-lab/dsh-kline/lib/fibonacci.js +0 -18
  30. package/node_modules/@ftshare-lab/dsh-kline/lib/ftshare-settings-bridge.js +0 -159
  31. package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +0 -279
  32. package/node_modules/@ftshare-lab/dsh-kline/lib/labeled-polyline.js +0 -17
  33. package/node_modules/@ftshare-lab/dsh-kline/lib/pattern-groups.js +0 -91
  34. package/node_modules/@ftshare-lab/dsh-kline/lib/price-bands.js +0 -55
  35. package/node_modules/@ftshare-lab/dsh-kline/lib/price-series.js +0 -47
  36. package/node_modules/@ftshare-lab/dsh-kline/lib/price-sticks.js +0 -32
  37. package/node_modules/@ftshare-lab/dsh-kline/lib/types/candle-sequence.d.ts +0 -2
  38. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-adjustment.d.ts +0 -2
  39. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-annotations.d.ts +0 -4
  40. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-applications.d.ts +0 -26
  41. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-context.d.ts +0 -14
  42. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-observation.d.ts +0 -8
  43. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-service-status.d.ts +0 -22
  44. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-source-status.d.ts +0 -47
  45. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-sources.d.ts +0 -25
  46. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/BetterSidebarTab.d.ts +0 -12
  47. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ClassicShell.d.ts +0 -4
  48. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/KlineContent.d.ts +0 -37
  49. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/PanelHost.d.ts +0 -25
  50. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-apply.d.ts +0 -13
  51. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-context.d.ts +0 -23
  52. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-handoff.d.ts +0 -5
  53. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-session-resolver.d.ts +0 -2
  54. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/client-context.d.ts +0 -16
  55. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +0 -43
  56. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/default-tab.d.ts +0 -3
  57. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/embed.d.ts +0 -37
  58. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +0 -2
  59. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/horizontal-lines.d.ts +0 -1
  60. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-options.d.ts +0 -38
  61. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-panels.d.ts +0 -55
  62. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/index.d.ts +0 -4
  63. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/mode-preferences.d.ts +0 -25
  64. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-contract.d.ts +0 -52
  65. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-register.d.ts +0 -46
  66. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-services.d.ts +0 -45
  67. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar.d.ts +0 -47
  68. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/sidebar-integration.d.ts +0 -12
  69. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ui-onboarding.d.ts +0 -7
  70. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/version.d.ts +0 -1
  71. package/node_modules/@ftshare-lab/dsh-kline/lib/types/drawing-feedback.d.ts +0 -5
  72. package/node_modules/@ftshare-lab/dsh-kline/lib/types/fibonacci.d.ts +0 -5
  73. package/node_modules/@ftshare-lab/dsh-kline/lib/types/ftshare-settings-bridge.d.ts +0 -50
  74. package/node_modules/@ftshare-lab/dsh-kline/lib/types/index.d.ts +0 -26
  75. package/node_modules/@ftshare-lab/dsh-kline/lib/types/labeled-polyline.d.ts +0 -11
  76. package/node_modules/@ftshare-lab/dsh-kline/lib/types/pattern-groups.d.ts +0 -2
  77. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-bands.d.ts +0 -3
  78. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-series.d.ts +0 -5
  79. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-sticks.d.ts +0 -3
  80. package/node_modules/@ftshare-lab/dsh-kline/package.json +0 -157
  81. package/node_modules/@ftshare-lab/dsh-kline/requirements.txt +0 -6
  82. package/node_modules/@ftshare-lab/dsh-kline/scripts/bootstrap.sh +0 -5
  83. package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-bootstrap.mjs +0 -179
  84. package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-mcp-plugin.mjs +0 -27
  85. package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +0 -658
  86. package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.sh +0 -5
  87. package/node_modules/@ftshare-lab/dsh-kline/server.py +0 -1755
  88. package/node_modules/@ftshare-lab/dsh-kline/tools/__init__.py +0 -0
  89. package/node_modules/@ftshare-lab/dsh-kline/tools/annotations.py +0 -119
  90. package/node_modules/@ftshare-lab/dsh-kline/tools/automatic_analysis.py +0 -158
  91. package/node_modules/@ftshare-lab/dsh-kline/tools/baostock_source.py +0 -176
  92. package/node_modules/@ftshare-lab/dsh-kline/tools/calc.py +0 -39
  93. package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +0 -260
  94. package/node_modules/@ftshare-lab/dsh-kline/tools/channel_preview.py +0 -82
  95. package/node_modules/@ftshare-lab/dsh-kline/tools/channels.py +0 -104
  96. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_applications.py +0 -204
  97. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +0 -186
  98. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +0 -363
  99. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +0 -451
  100. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +0 -65
  101. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_measurements.py +0 -84
  102. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_source_status.py +0 -32
  103. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_sources.py +0 -31
  104. package/node_modules/@ftshare-lab/dsh-kline/tools/closed_daily.py +0 -68
  105. package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +0 -410
  106. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +0 -45
  107. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_interaction.py +0 -117
  108. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_verification.py +0 -141
  109. package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +0 -4680
  110. package/node_modules/@ftshare-lab/dsh-kline/tools/fibonacci.py +0 -83
  111. package/node_modules/@ftshare-lab/dsh-kline/tools/foreign_daily.py +0 -185
  112. package/node_modules/@ftshare-lab/dsh-kline/tools/free_sources.py +0 -483
  113. package/node_modules/@ftshare-lab/dsh-kline/tools/lines.py +0 -91
  114. package/node_modules/@ftshare-lab/dsh-kline/tools/nine_count.py +0 -66
  115. package/node_modules/@ftshare-lab/dsh-kline/tools/pattern_groups.py +0 -103
  116. package/node_modules/@ftshare-lab/dsh-kline/tools/pivots.py +0 -60
  117. package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +0 -131
  118. package/node_modules/@ftshare-lab/dsh-kline/tools/price_bands.py +0 -165
  119. package/node_modules/@ftshare-lab/dsh-kline/tools/price_patterns.py +0 -311
  120. package/node_modules/@ftshare-lab/dsh-kline/tools/price_series.py +0 -162
  121. package/node_modules/@ftshare-lab/dsh-kline/tools/price_sticks.py +0 -114
  122. package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +0 -170
  123. package/node_modules/@ftshare-lab/dsh-kline/tools/recent_drawing_candidates.py +0 -123
  124. package/node_modules/@ftshare-lab/dsh-kline/tools/rectangles.py +0 -76
  125. package/node_modules/@ftshare-lab/dsh-kline/tools/regression_channels.py +0 -87
  126. package/node_modules/@ftshare-lab/dsh-kline/tools/ta_functions.py +0 -228
  127. package/node_modules/@ftshare-lab/dsh-kline/tools/trend_lines.py +0 -106
  128. package/node_modules/@ftshare-lab/dsh-kline/tools/watchlist.py +0 -149
  129. package/node_modules/@ftshare-lab/dsh-kline/view/ft-logo.jpg +0 -0
  130. package/node_modules/@ftshare-lab/dsh-kline/view/vendor/klinecharts.min.js +0 -7
@@ -1,354 +0,0 @@
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
- }