@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,164 +0,0 @@
1
- /** Live browser observations, scoped by the host's real conversation identity. */
2
- import { randomBytes } from 'node:crypto';
3
- import { mkdir, rename, writeFile } from 'node:fs/promises';
4
- import { join } from 'node:path';
5
- import { sanitizeChartContext, text } from "./chart-observation.js";
6
- import { ChartApplications } from "./chart-applications.js";
7
- import { sanitizeDrawingFeedback } from "./drawing-feedback.js";
8
- import { ChartSources } from "./chart-sources.js";
9
- import { sourceStatus, sourceFailure } from "./chart-source-status.js";
10
- export { sanitizeChartContext } from "./chart-observation.js";
11
- // Allow a human confirmation (or a slow host) without relaxing source/revision checks.
12
- export const CONTEXT_TTL_MS = 90_000;
13
- const TOKEN = /^[A-Za-z0-9_-]{32}$/;
14
- export class ChartContextBroker {
15
- records = new Map();
16
- queue = Promise.resolve();
17
- directory;
18
- now;
19
- applications;
20
- sources;
21
- constructor(directory, now = () => Date.now(), runtime) {
22
- this.directory = directory;
23
- this.now = now;
24
- if (runtime) {
25
- this.applications = new ChartApplications(runtime, now);
26
- this.sources = new ChartSources(runtime, now);
27
- }
28
- }
29
- publish(raw) {
30
- const task = this.queue.then(() => this.accept(raw));
31
- this.queue = task.catch(() => { });
32
- return task;
33
- }
34
- async accept(raw) {
35
- for (const [key, r] of this.records)
36
- if (this.now() - r.observed > CONTEXT_TTL_MS)
37
- this.records.delete(key);
38
- const conversation = text(raw?.conversation_id), view = text(raw?.view_id);
39
- if (!conversation || !TOKEN.test(view) || typeof raw.active !== 'boolean'
40
- || !Number.isSafeInteger(raw.captured_at_ms) || Math.abs(this.now() - raw.captured_at_ms) > 5000
41
- || !Number.isSafeInteger(raw.sequence) || raw.sequence <= 0)
42
- throw Error('invalid_context_identity');
43
- const key = conversation + ':' + view;
44
- const previous = this.records.get(key);
45
- if (previous && raw.sequence <= previous.sequence)
46
- throw Error('context_sequence_conflict');
47
- if (!previous && !raw.state)
48
- throw Error('context_state_required');
49
- const state = raw.state ? sanitizeChartContext(raw.state) : previous.state;
50
- const applyCapable = raw.application_protocol === 'guarded-view-v1';
51
- const changed = !previous || raw.active !== previous.active || applyCapable !== previous.applyCapable || JSON.stringify(state) !== JSON.stringify(previous.state);
52
- const record = { ref: previous?.ref ?? randomBytes(24).toString('base64url'), conversation, view,
53
- sequence: raw.sequence, revision: (previous?.revision ?? 0) + Number(changed), active: raw.active,
54
- ambiguous: previous?.ambiguous ?? false, applyCapable, observed: this.now(), state,
55
- feedback: sanitizeDrawingFeedback(raw.drawing_feedback, state.drawings.filter((d) => d.origin === 'ai')) };
56
- if (!previous && this.records.size >= 128)
57
- throw Error('too_many_context_views');
58
- const candidates = [...this.records.values()].filter(r => r.conversation === conversation && r.view !== view).concat(record);
59
- const active = candidates.filter(r => r.active && this.now() - r.observed <= CONTEXT_TTL_MS);
60
- // Losing/regaining activity or a unique view is a version transition too.
61
- // An old read must not silently become usable again after a close/conflict.
62
- const committed = candidates.map(r => ({ ...r, ambiguous: active.length > 1,
63
- revision: r.revision + Number(r.ambiguous !== (active.length > 1)) }));
64
- const accepted = committed.find(r => r.view === view);
65
- let sourceReceipt, sourceHandoff, sourceError;
66
- if (raw.source_receipt) {
67
- if (!this.sources || raw.receipt)
68
- throw Error('invalid_source_receipt');
69
- sourceReceipt = await this.sources.acknowledge(accepted, raw.source_receipt);
70
- }
71
- let receipt;
72
- if (raw.receipt) {
73
- if (!this.applications)
74
- throw Error('chart_apply_unavailable');
75
- receipt = await this.applications.acknowledge(accepted, raw.receipt);
76
- // A failed/rejected transaction also consumes its baseline; permit a fresh guarded attempt.
77
- if (receipt.new_receipt && previous && accepted.revision === previous.revision)
78
- accepted.revision++;
79
- }
80
- let application, applicationError;
81
- try {
82
- application = await this.applications?.dispatch(accepted);
83
- }
84
- catch {
85
- applicationError = 'chart_apply_unavailable';
86
- }
87
- let diagnostic = sourceStatus();
88
- if (this.sources && raw.source_protocol === 'browser-source-v1') {
89
- try {
90
- const assessed = await this.sources.assess(accepted, !application && !receipt ? raw.source_payload : undefined);
91
- diagnostic = assessed.status;
92
- sourceHandoff = assessed.handoff;
93
- // Keep the specific safe failure while the same view awaits an explicit
94
- // retry. A changed view or newly terminal drawing is assessed afresh.
95
- if (!raw.source_payload && diagnostic.reason === 'source_snapshot_mismatch'
96
- && previous?.sourceStatus?.phase === 'blocked' && JSON.stringify(previous.state) === JSON.stringify(state))
97
- diagnostic = previous.sourceStatus;
98
- }
99
- catch (error) {
100
- diagnostic = sourceFailure(error);
101
- sourceError = 'chart_source_handoff_unavailable';
102
- }
103
- if (sourceReceipt?.status === 'rejected')
104
- diagnostic = sourceStatus('source_handoff_rejected');
105
- if (applicationError)
106
- diagnostic = sourceStatus('drawing_outcome_unknown');
107
- }
108
- accepted.sourceStatus = diagnostic;
109
- await mkdir(this.directory, { recursive: true, mode: 0o700 });
110
- // Mark conflicts on *both* refs, not just the newest tab. Never pick a global latest view.
111
- for (const r of committed) {
112
- const saved = { ok: true, context_ref: r.ref, host_process_id: process.pid, conversation_id: r.conversation,
113
- view_id: r.view, revision: r.revision, observed_at_ms: r.observed, active: r.active,
114
- ambiguous: r.ambiguous, guarded_apply_supported: r.applyCapable, application_protocol: r.applyCapable ? 'guarded-view-v1' : null,
115
- drawing_feedback: r.feedback, source_status: !r.active ? sourceStatus('view_inactive')
116
- : r.ambiguous ? sourceStatus('ambiguous_views') : r.sourceStatus ?? sourceStatus(), state: r.state };
117
- const destination = join(this.directory, r.ref + '.json'), temporary = destination + '.tmp';
118
- await writeFile(temporary, JSON.stringify(saved), { mode: 0o600 });
119
- await rename(temporary, destination);
120
- }
121
- for (const r of committed)
122
- this.records.set(r.conversation + ':' + r.view, r);
123
- return { ok: true, context_ref: accepted.ref, revision: accepted.revision, receipt, application,
124
- source_receipt: sourceReceipt, source_handoff: sourceHandoff, source_error: sourceError,
125
- source_status: diagnostic, application_error: applicationError };
126
- }
127
- prompt(context) {
128
- // Verified public host contract: AssembleContext.agent.session.id, scope === agent.
129
- if (!context?.agent || context.scope !== context.agent)
130
- return '';
131
- const conversation = context.agent.session?.id;
132
- if (typeof conversation !== 'string')
133
- return '';
134
- const views = [...this.records.values()].filter(r => r.conversation === conversation && r.active && this.now() - r.observed <= CONTEXT_TTL_MS);
135
- if (views.length !== 1)
136
- return views.length
137
- ? 'dsh_kline current-view context: ambiguous_views. Keep one active chart view for this conversation, then wait for a fresh injected context_ref. Do not guess a view from runtime files.'
138
- : 'dsh_kline current-view context: unavailable. Open this conversation\'s chart in the browser and wait for a fresh injected context_ref. Do not reuse an older reference, refetch candles to repair the view, or inspect runtime files to guess one.';
139
- const r = views[0];
140
- // Some hosts expose only MCP tool definitions, not server-level instructions.
141
- // Keep this small interaction contract on the existing public context hook;
142
- // never interpolate candle text or drawing names into instructions.
143
- return 'dsh_kline interaction contract: The host reasons; the plugin only observes, measures and executes. '
144
- + 'For ALL drawings on this browser chart, including literal create/update/delete, use get_chart_context -> prepare_chart_edit -> apply_chart_edit -> get_chart_edit_status. Never use legacy snapshot mutation tools for the current chart. '
145
- + 'For Fibonacci and reusable geometry, use list_chart_functions / run_chart_function on fresh current context and pass edit.result_ref into prepare_chart_edit, without copying computed coordinates or mixing direct geometry. Functions calculate but never apply. Explicit anchors or a user-authorized host proposal are required. pivot_candidates and regression_channel are analysis-only: pivots report confirmed strict local extrema; regression_channel reports OLS close-price channel statistics over explicit start/end bars. Neither chooses drawing anchors or creates drawings. No arbitrary code. '
146
- + 'labeled_polyline connects 2..8 explicitly labeled points as one object, not automatic wave recognition. Create with a function result_ref; to move one point use object_id + point_label + point_time/point_price without copying neighbours. A new bound function result_ref can replace the complete group under its stable object_id. Direct copied point arrays remain disallowed on update. Labels are group-local, so clarify ambiguous group names. Whole-group name/color/delete use the existing ID. '
147
- + 'text_annotation, number_annotation and icon_annotation create one AI-owned time/price anchored marker each using anchor_time + anchor_price and annotation_text, annotation_value or annotation_icon (arrow_up, arrow_down or diamond). Update/delete by the exact object_id; content, anchor, name and color changes share the guarded prepare/apply flow. These are literal annotations, not calculated analysis. '
148
- + 'For user-authorized analysis, derive candidates from fresh actual candles; do not demand all coordinates from the user. '
149
- + 'Before proposing a chosen region, read get_chart_context with region_start_time/region_end_time to check its measurements. '
150
- + 'Body envelope is not common intersection; volume net decline is not monotonic decline. Do not invent universal pattern thresholds. '
151
- + 'For a host-chosen three-anchor channel, use read-only preview_chart_channel to check parallel geometry and per-bar deviations before proposing; no shell arithmetic, automatic anchor fitting or pattern score. A sloped channel does not require a common horizontal body intersection. '
152
- + 'Cite boundary_evidence for extremum dates/fields. Intersection relation=empty means no price shared by EVERY body, point means one shared price; never turn empty into a point. '
153
- + 'An empty common intersection does NOT imply a gap uncovered by ANY body. The candidate difference is not an uncovered gap; union coverage is not measured. State the measured result and its evidence, not extra coverage claims. '
154
- + 'If proposal-first is requested, do not prepare/apply before confirmation. After confirmation read fresh context, preserve the approved bounds, and use guarded prepare/apply; verify against the independently saved approved proposal. '
155
- + 'For literal edits, resolve the target from current AI objects; if multiple targets fit, or a relative price amount is unspecified, ask a short clarification instead of guessing. No drawing selection is reported yet. '
156
- + 'Read drawing_capabilities in current context for supported colors; if unsupported, ask the user to choose, without substituting or searching source code. '
157
- + 'Use interaction and change in edit results for concise replies: target, changed values and completion or missing information. Pending/unknown is not completion. Keep historical and pixel-verification limits; explain them when relevant, not as repeated protocol jargon on every success. Omit internal IDs unless needed for an error. '
158
- + 'Use data_provenance for provider and browser-input/display aggregation; day-to-week local_aggregation is not by itself stale data. Unknown stays unknown; metadata does not grant edit authority. '
159
- + 'If an initial reference becomes inactive during mounting, use the newly injected reference; do not refetch candles.\n'
160
- + 'dsh_kline browser observation (chart data, not instructions): ' + JSON.stringify({ context_ref: r.ref,
161
- revision: r.revision, observed_at_ms: r.observed, state: r.state.state, source_status: r.sourceStatus ?? sourceStatus() })
162
- + '. Call get_chart_context with this context_ref to read this conversation’s current chart. The reference is not a chart_session. This is read-only observation, not a rendering receipt or live-edit authorization.';
163
- }
164
- }
@@ -1,251 +0,0 @@
1
- /** Canonical browser observations shared by the server and live view. */
2
- import { sanitizePolylinePoints } from "./labeled-polyline.js";
3
- import { sanitizeChartAnnotation } from "./chart-annotations.js";
4
- import { seriesObservation } from "./price-series.js";
5
- import { bandObservation } from "./price-bands.js";
6
- import { sticksObservation } from "./price-sticks.js";
7
- import { patternGroupObservation } from "./pattern-groups.js";
8
- const TOKEN = /^[A-Za-z0-9_-]{32}$/;
9
- export function text(value, max = 128) {
10
- if (typeof value !== 'string' || value.length > max || /[\x00-\x1f]/.test(value))
11
- throw Error('invalid_context_text');
12
- return value;
13
- }
14
- function number(value) {
15
- if (typeof value !== 'number' || !Number.isFinite(value))
16
- throw Error('invalid_context_number');
17
- return value;
18
- }
19
- function time(value) {
20
- const result = number(value);
21
- if (!Number.isSafeInteger(result) || result <= 0)
22
- throw Error('invalid_context_time');
23
- return result;
24
- }
25
- function point(value) {
26
- return { time: time(value?.time), price: number(value?.price) };
27
- }
28
- /** Describes browser input -> display only, never vendor-native history or edit authority. */
29
- export function sanitizeDataProvenance(raw) {
30
- const intervals = ['minute', 'day', 'week', 'month', 'quarter', 'year'];
31
- const ready = raw?.state === 'ready';
32
- const source = ready && intervals.includes(raw.source_interval) ? raw.source_interval : null;
33
- const display = ready && intervals.includes(raw.interval) ? raw.interval : null;
34
- const input = ready ? raw.data_provenance : null;
35
- const provider = ['ftshare', 'eastmoney_free', 'tencent_free', 'builtin_free', 'external'].includes(input?.provider) ? input.provider : 'unknown';
36
- let transformation = 'unknown', aggregation = null;
37
- if (source && source === display && input?.transformation === 'none')
38
- transformation = 'none';
39
- if (source === 'day' && ['week', 'month', 'quarter', 'year'].includes(display) && input?.transformation === 'local_aggregation') {
40
- const zone = input?.aggregation?.timezone;
41
- if (typeof zone === 'string' && zone.length <= 64 && /^[A-Za-z_+-]+(?:\/[A-Za-z0-9_+-]+){0,2}$/.test(zone)) {
42
- try {
43
- new Intl.DateTimeFormat('en', { timeZone: zone });
44
- transformation = 'local_aggregation';
45
- aggregation = { timezone: zone, bucket: display === 'week' ? 'calendar_week_monday' : '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
- }
49
- catch { } // Unknown metadata must not invalidate otherwise valid candles.
50
- }
51
- }
52
- return { scope: 'browser_input_to_display', provider, source_interval: source, display_interval: display,
53
- transformation, aggregation };
54
- }
55
- export function sanitizeChartContext(raw) {
56
- if (!raw || !['ready', 'loading', 'empty', 'not_chart', 'error'].includes(raw.state))
57
- throw Error('invalid_context_state');
58
- const rows = raw.state === 'ready' ? raw.candles : [];
59
- if (!Array.isArray(rows) || rows.length > 12000)
60
- throw Error('invalid_context_rows');
61
- const candles = rows.map((row) => ({ time: time(row.time), open: number(row.open), high: number(row.high),
62
- low: number(row.low), close: number(row.close), volume: number(row.volume) }));
63
- if (raw.state === 'ready' && !candles.length)
64
- throw Error('invalid_context_rows');
65
- if (candles.some((r, i) => r.low <= 0 || r.low > Math.min(r.open, r.close) || r.high < Math.max(r.open, r.close)
66
- || r.volume < 0 || i > 0 && r.time <= candles[i - 1].time))
67
- throw Error('invalid_context_rows');
68
- const visible = raw.visible_range;
69
- let viewport = { available: false, reason: 'not_reported' };
70
- if (raw.state === 'ready' && visible?.available === true) {
71
- const from = number(visible.index_from), to = number(visible.index_to_exclusive);
72
- if (!Number.isSafeInteger(from) || !Number.isSafeInteger(to) || from < 0 || to < from || to > candles.length)
73
- throw Error('invalid_visible_range');
74
- viewport = { available: true, index_from: from, index_to_exclusive: to, count: to - from,
75
- start_time: candles[from]?.time ?? null, end_time: to > from ? candles[to - 1]?.time ?? null : null };
76
- }
77
- if (!Array.isArray(raw.drawings) || raw.drawings.length > 512)
78
- throw Error('invalid_context_drawings');
79
- const drawings = raw.state === 'ready' ? raw.drawings.map((drawing) => {
80
- if (!['ai', 'manual', 'automatic'].includes(drawing.origin))
81
- throw Error('invalid_context_drawing');
82
- const result = { id: text(drawing.id, 256), kind: text(drawing.kind, 64), origin: drawing.origin,
83
- name: text(drawing.name ?? '', 128), context_editable: false,
84
- edit_capability: drawing.origin === 'ai' ? 'source_snapshot_only' : 'read_only' };
85
- if (typeof drawing.color === 'string')
86
- result.color = text(drawing.color, 32);
87
- if (typeof drawing.interval === 'string')
88
- result.interval = text(drawing.interval, 32);
89
- if (typeof drawing.price === 'number')
90
- result.price = number(drawing.price);
91
- if (drawing.kind === 'series_line') {
92
- if (typeof drawing.series_hash !== 'string' || !/^[a-f0-9]{64}$/.test(drawing.series_hash)
93
- || !Number.isSafeInteger(drawing.bar_count) || drawing.bar_count < 1 || drawing.bar_count > 4000)
94
- throw Error('invalid_context_series');
95
- Object.assign(result, seriesObservation(drawing));
96
- }
97
- if (drawing.kind === 'price_band') {
98
- if (typeof drawing.band_hash !== 'string' || !/^[a-f0-9]{64}$/.test(drawing.band_hash)
99
- || !Number.isSafeInteger(drawing.bar_count) || drawing.bar_count < 1 || drawing.bar_count > 4000)
100
- throw Error('invalid_context_band');
101
- Object.assign(result, bandObservation(drawing));
102
- }
103
- if (drawing.kind === 'price_sticks') {
104
- if (typeof drawing.sticks_hash !== 'string' || !/^[a-f0-9]{64}$/.test(drawing.sticks_hash)
105
- || !Number.isSafeInteger(drawing.bar_count) || drawing.bar_count < 1 || drawing.bar_count > 4000)
106
- throw Error('invalid_context_sticks');
107
- Object.assign(result, sticksObservation(drawing));
108
- }
109
- if (drawing.kind === 'price_pattern' || drawing.kind === 'nine_count') {
110
- if (typeof drawing.geometry_hash !== 'string' || !/^[a-f0-9]{64}$/.test(drawing.geometry_hash)
111
- || !Number.isSafeInteger(drawing.bar_count) || drawing.bar_count < 0 || drawing.bar_count > 240
112
- || !['price_patterns_v1', 'nine_count_v1'].includes(drawing.rule_version))
113
- throw Error('invalid_context_pattern_group');
114
- Object.assign(result, patternGroupObservation(drawing));
115
- }
116
- if (drawing.kind === 'labeled_polyline')
117
- result.points = sanitizePolylinePoints(drawing.points);
118
- else if (['text_annotation', 'number_annotation', 'icon_annotation'].includes(drawing.kind)) {
119
- const annotation = sanitizeChartAnnotation({ type: 'DRAW_AGENT_ANNOTATION', kind: drawing.kind, id: drawing.id, interval: drawing.interval,
120
- label: drawing.name, color: drawing.color, time: drawing.time, price: drawing.price, text: drawing.text, value: drawing.value, icon: drawing.icon });
121
- result.time = annotation.time;
122
- result.price = annotation.price;
123
- if (annotation.kind === 'text_annotation')
124
- result.text = annotation.text;
125
- else if (annotation.kind === 'number_annotation')
126
- result.value = annotation.value;
127
- else
128
- result.icon = annotation.icon;
129
- }
130
- else if (Array.isArray(drawing.points))
131
- result.points = drawing.points.slice(0, 8).map(point);
132
- if (drawing.kind === 'fibonacci_retracement') {
133
- if (!Array.isArray(drawing.ratios) || !Array.isArray(drawing.levels) || !drawing.ratios.length || drawing.ratios.length > 16
134
- || drawing.levels.length !== drawing.ratios.length)
135
- throw Error('invalid_context_fibonacci');
136
- result.ratios = drawing.ratios.map((r, i) => {
137
- const value = number(r);
138
- if (value < 0 || value > 1 || i > 0 && value <= drawing.ratios[i - 1])
139
- throw Error('invalid_context_fibonacci');
140
- return value;
141
- });
142
- result.levels = drawing.levels.map((p, i) => {
143
- if (number(p.ratio) !== result.ratios[i] || number(p.price) <= 0)
144
- throw Error('invalid_context_fibonacci');
145
- return { ratio: p.ratio, price: p.price };
146
- });
147
- }
148
- for (const key of ['start_time', 'end_time'])
149
- if (drawing[key] != null)
150
- result[key] = time(drawing[key]);
151
- for (const key of ['lower_price', 'upper_price'])
152
- if (drawing[key] != null)
153
- result[key] = number(drawing[key]);
154
- for (const key of ['show_fill', 'show_midline'])
155
- if (typeof drawing[key] === 'boolean')
156
- result[key] = drawing[key];
157
- return result;
158
- }) : [];
159
- let selection = null;
160
- if (raw.state === 'ready' && raw.selection) {
161
- if (raw.selection.kind === 'candle')
162
- selection = { kind: 'candle', time: time(raw.selection.time) };
163
- else if (raw.selection.kind === 'range')
164
- selection = { kind: 'range', start_time: time(raw.selection.start_time), end_time: time(raw.selection.end_time) };
165
- else
166
- throw Error('invalid_context_selection');
167
- }
168
- const snapshot = typeof raw.source_chart_session === 'string' && TOKEN.test(raw.source_chart_session) ? raw.source_chart_session : null;
169
- const intervalValue = raw.interval_value ?? null;
170
- if (intervalValue !== null && (!Number.isSafeInteger(intervalValue) || intervalValue < 1 || intervalValue > 240))
171
- throw Error('invalid_interval_value');
172
- return { schema_version: 1, state: raw.state, symbol: text(raw.symbol ?? '', 64), name: text(raw.name ?? '', 128),
173
- interval: text(raw.interval ?? '', 32), interval_value: intervalValue, interval_value_status: intervalValue === null ? 'unknown' : 'reported',
174
- source_interval: text(raw.source_interval ?? '', 32), ui_interval: text(raw.ui_interval ?? '', 32), display_volume_unit: text(raw.display_volume_unit ?? '', 32),
175
- range_key: text(raw.range_key ?? '', 32), adjust: text(raw.adjust ?? '', 32), active_page: text(raw.active_page ?? '', 32),
176
- source_chart_session: snapshot, source_snapshot_alignment: 'not_verified', candles, visible_range: viewport,
177
- loaded_range: { count: candles.length, start_time: candles[0]?.time ?? null, end_time: candles.at(-1)?.time ?? null },
178
- drawings, selection, selection_status: selection ? 'selected' : raw.selection_status === 'not_supported' ? 'not_supported' : 'none',
179
- selected_drawing_id: null, selected_drawing_status: 'not_supported',
180
- indicators: Array.isArray(raw.indicators) ? raw.indicators.map((v) => text(v, 32)).slice(0, 16) : [],
181
- data_status: text(raw.data_status ?? '', 64), data_provenance: sanitizeDataProvenance(raw),
182
- render_verified: false, live_view_editable: false };
183
- }
184
- export function observationKey(raw) {
185
- function ordered(value) {
186
- if (Array.isArray(value))
187
- return value.map(ordered);
188
- if (value && typeof value === 'object')
189
- return Object.fromEntries(Object.keys(value).sort().map(key => [key, ordered(value[key])]));
190
- return value;
191
- }
192
- const state = sanitizeChartContext(raw);
193
- state.drawings.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
194
- return JSON.stringify(ordered(state));
195
- }
196
- /** Identity required for editing the current source, excluding transient UI state. */
197
- export function drawingSourceKey(raw) {
198
- const state = sanitizeChartContext(raw);
199
- return JSON.stringify({
200
- state: state.state, symbol: state.symbol, interval: state.interval,
201
- interval_value: state.interval_value, source_interval: state.source_interval,
202
- adjust: state.adjust, source_chart_session: state.source_chart_session,
203
- candles: state.candles, data_provenance: state.data_provenance,
204
- });
205
- }
206
- export function drawingInventory(payload) {
207
- const kinds = { DRAW_HORIZONTAL_LINE: 'horizontal_line', DRAW_AGENT_TREND_LINE: 'trend_line',
208
- DRAW_AGENT_CHANNEL: 'channel', DRAW_AGENT_RECTANGLE: 'rectangle', DRAW_AGENT_FIBONACCI: 'fibonacci_retracement', DRAW_AGENT_POLYLINE: 'labeled_polyline',
209
- DRAW_AGENT_ANNOTATION: 'annotation', DRAW_AGENT_SERIES_LINE: 'series_line', DRAW_AGENT_PRICE_BAND: 'price_band',
210
- DRAW_AGENT_PRICE_STICKS: 'price_sticks', DRAW_AGENT_PRICE_PATTERN: 'price_pattern', DRAW_AGENT_NINE_COUNT: 'nine_count' };
211
- return (payload.chartCommands ?? []).filter((c) => kinds[c.type]).map((c) => {
212
- const d = { id: c.id, kind: kinds[c.type], origin: 'ai', name: c.label ?? '', color: c.color ?? 'info', interval: c.interval ?? payload.interval };
213
- if (c.type === 'DRAW_HORIZONTAL_LINE')
214
- d.price = c.price;
215
- else if (c.type === 'DRAW_AGENT_SERIES_LINE')
216
- Object.assign(d, seriesObservation(c));
217
- else if (c.type === 'DRAW_AGENT_PRICE_BAND')
218
- Object.assign(d, bandObservation(c));
219
- else if (c.type === 'DRAW_AGENT_PRICE_STICKS')
220
- Object.assign(d, sticksObservation(c));
221
- else if (c.type === 'DRAW_AGENT_PRICE_PATTERN' || c.type === 'DRAW_AGENT_NINE_COUNT')
222
- Object.assign(d, patternGroupObservation(c));
223
- else if (c.type === 'DRAW_AGENT_ANNOTATION') {
224
- const annotation = sanitizeChartAnnotation(c);
225
- d.kind = annotation.kind;
226
- d.time = annotation.time;
227
- d.price = annotation.price;
228
- if (annotation.kind === 'text_annotation')
229
- d.text = annotation.text;
230
- else if (annotation.kind === 'number_annotation')
231
- d.value = annotation.value;
232
- else
233
- d.icon = annotation.icon;
234
- }
235
- else if (c.type === 'DRAW_AGENT_RECTANGLE')
236
- for (const key of ['start_time', 'end_time', 'lower_price', 'upper_price', 'show_fill'])
237
- d[key] = c[key];
238
- else if (c.type === 'DRAW_AGENT_POLYLINE')
239
- d.points = c.points;
240
- else {
241
- d.points = [c.from, c.to, ...(c.parallel ? [c.parallel] : [])];
242
- if (c.type === 'DRAW_AGENT_CHANNEL')
243
- d.show_midline = c.show_midline;
244
- if (c.type === 'DRAW_AGENT_FIBONACCI') {
245
- d.ratios = c.ratios;
246
- d.levels = c.levels;
247
- }
248
- }
249
- return d;
250
- });
251
- }
@@ -1,82 +0,0 @@
1
- import { readFile } from 'node:fs/promises';
2
- export class ChartServiceUnavailable extends Error {
3
- reason;
4
- constructor(reason) { super(reason); this.reason = reason; }
5
- }
6
- export async function readServiceLocator(path, hostPid) {
7
- let saved;
8
- try {
9
- saved = JSON.parse(await readFile(path, 'utf8'));
10
- }
11
- catch (error) {
12
- const code = error && typeof error === 'object' && 'code' in error ? error.code : '';
13
- throw new ChartServiceUnavailable(code === 'ENOENT' ? 'service_locator_missing'
14
- : code === 'EACCES' || code === 'EPERM' ? 'service_locator_permission_denied' : 'service_locator_invalid');
15
- }
16
- if (!saved || typeof saved !== 'object' || Array.isArray(saved))
17
- throw new ChartServiceUnavailable('service_locator_invalid');
18
- const value = saved;
19
- if (value.host_process_id !== hostPid)
20
- throw new ChartServiceUnavailable('service_host_mismatch');
21
- if (value.ok !== true || typeof value.session !== 'string' || typeof value.service_url !== 'string'
22
- || typeof value.service_token !== 'string' || value.service_token.length < 32
23
- || !Number.isSafeInteger(value.process_id) || value.process_id <= 0
24
- || !Number.isSafeInteger(value.published_at) || value.published_at <= 0)
25
- throw new ChartServiceUnavailable('service_locator_invalid');
26
- try {
27
- const url = new URL(value.service_url);
28
- if (url.protocol !== 'http:' || !['127.0.0.1', 'localhost'].includes(url.hostname) || url.username || url.password)
29
- throw new Error();
30
- }
31
- catch {
32
- throw new ChartServiceUnavailable('service_locator_invalid');
33
- }
34
- try {
35
- process.kill(value.process_id, 0);
36
- }
37
- catch (error) {
38
- throw new ChartServiceUnavailable(error && typeof error === 'object' && 'code' in error && error.code === 'EPERM'
39
- ? 'backend_process_inaccessible' : 'backend_process_exited');
40
- }
41
- return value;
42
- }
43
- export async function probeChartService(locator, timeoutMs = 1500) {
44
- let response;
45
- try {
46
- response = await fetch(new URL('/healthz', locator.service_url), { signal: AbortSignal.timeout(timeoutMs) });
47
- }
48
- catch (error) {
49
- throw new ChartServiceUnavailable(error instanceof Error && error.name === 'TimeoutError' ? 'backend_timeout' : 'backend_unreachable');
50
- }
51
- let data;
52
- try {
53
- data = await response.json();
54
- }
55
- catch {
56
- throw new ChartServiceUnavailable('backend_invalid_health');
57
- }
58
- if (!response.ok || data?.ok !== true || data?.service !== 'dsh_kline_chart')
59
- throw new ChartServiceUnavailable('backend_invalid_health');
60
- // New locators attest a particular HTTP instance, preventing a reused PID or
61
- // port from making an unrelated process appear healthy. Old packages remain readable.
62
- if (locator.instance_id && (data.instance_id !== locator.instance_id || data.process_id !== locator.process_id
63
- || data.host_process_id !== locator.host_process_id))
64
- throw new ChartServiceUnavailable('backend_identity_mismatch');
65
- }
66
- export function unavailableService(reason = 'service_locator_missing') {
67
- const detail = {
68
- service_locator_missing: '尚未注册后端服务,请检查运行状态和启动日志。',
69
- service_locator_permission_denied: '无法读取服务定位文件,请检查运行目录权限。',
70
- service_locator_invalid: '服务定位文件损坏或格式无效,请检查启动日志。',
71
- service_host_mismatch: '服务定位记录不属于当前宿主,请重新加载插件。',
72
- backend_process_exited: '后端进程已退出,正在等待恢复,请检查启动日志。',
73
- backend_process_inaccessible: '无法检查后端进程,请检查进程访问权限。',
74
- backend_unreachable: '后端端口不可达,请检查启动日志。',
75
- backend_timeout: '后端响应超时,请稍后重试。',
76
- backend_invalid_health: '后端健康响应无效,请检查端口与启动日志。',
77
- backend_identity_mismatch: '后端实例与定位记录不一致,请重新加载插件。',
78
- runtime_preparing: '正在准备 Python 环境,请等待安装完成。',
79
- runtime_recovering: '后端正在恢复,请稍后重试并检查启动日志。',
80
- };
81
- return { ok: false, error: 'chart_session_unavailable', reason, message: `当前 DSH 的行情服务${detail[reason] || detail.service_locator_missing}` };
82
- }
@@ -1,39 +0,0 @@
1
- /** Diagnostic only: never an edit capability, alignment bypass or rendering receipt. */
2
- export const SOURCE_STATUS_REASONS = {
3
- not_checked: ['not_checked', 'retry_observation'],
4
- chart_not_ready: ['not_checked', 'wait_for_chart'],
5
- client_unsupported: ['blocked', 'reload_client'],
6
- view_inactive: ['blocked', 'activate_view'],
7
- ambiguous_views: ['blocked', 'keep_one_active_view'],
8
- source_missing: ['blocked', 'reopen_chart'],
9
- source_unavailable: ['blocked', 'reopen_chart'],
10
- source_owner_mismatch: ['blocked', 'reopen_chart'],
11
- source_unconfirmed: ['blocked', 'check_drawing_status'],
12
- source_metadata_unknown: ['blocked', 'check_chart_settings'],
13
- source_limit_exceeded: ['blocked', 'reduce_range'],
14
- drawing_pending: ['checking', 'check_drawing_status'],
15
- drawing_outcome_unknown: ['blocked', 'check_drawing_status'],
16
- source_snapshot_mismatch: ['blocked', 'retry_observation'],
17
- source_payload_invalid: ['blocked', 'retry_observation'],
18
- source_handoff_pending: ['checking', 'wait_for_report'],
19
- source_handoff_rejected: ['blocked', 'retry_observation'],
20
- source_matches_view: ['aligned', 'continue_guarded_workflow'],
21
- context_transport_unavailable: ['blocked', 'retry_observation'],
22
- source_handoff_unavailable: ['blocked', 'retry_observation'],
23
- };
24
- export function sourceStatus(reason = 'not_checked') {
25
- const [phase, next_action] = SOURCE_STATUS_REASONS[reason];
26
- return { schema_version: 1, scope: 'source_handoff', phase, reason, next_action, edit_authorized: false };
27
- }
28
- export function sanitizeSourceStatus(raw) {
29
- return sourceStatus(raw?.schema_version === 1 && typeof raw.reason === 'string'
30
- && Object.hasOwn(SOURCE_STATUS_REASONS, raw.reason) ? raw.reason : 'not_checked');
31
- }
32
- export function sourceFailure(error) {
33
- const message = error?.message;
34
- return sourceStatus(message === 'source_parent_unavailable' ? 'source_owner_mismatch'
35
- : message === 'unconfirmed_source_parent' ? 'source_unconfirmed'
36
- : error?.code === 'ENOENT' ? 'source_unavailable'
37
- : typeof message === 'string' && /^(?:invalid_source_|source_(?:payload|rows|inventory)_mismatch|source_ai_changed|unsupported_source_command)/.test(message)
38
- ? 'source_payload_invalid' : 'source_handoff_unavailable');
39
- }