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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (203) hide show
  1. package/CHANGELOG.md +601 -0
  2. package/LICENSE +21 -0
  3. package/PROVENANCE.md +13 -0
  4. package/README.en.md +116 -0
  5. package/README.md +115 -2
  6. package/chart_service.py +687 -0
  7. package/config/basic-symbols.json +570 -0
  8. package/config/dsh-kline.patch.yml +4 -0
  9. package/config/dsh-tool-catalog.json +3875 -0
  10. package/cordis.patch.yml +33 -0
  11. package/core/__init__.py +0 -0
  12. package/core/adjustment.py +16 -0
  13. package/core/calc.py +691 -0
  14. package/core/rows.py +228 -0
  15. package/core/ta_engine.py +99 -0
  16. package/docs/anonymous-market-support.md +33 -0
  17. package/docs/automatic-drawing.md +24 -0
  18. package/docs/chart-functions.md +136 -0
  19. package/docs/drawing-examples.en.md +13 -0
  20. package/docs/drawing-examples.md +13 -0
  21. package/docs/embedding.md +43 -0
  22. package/docs/fixtures/price-pattern-real-v1.json +1 -0
  23. package/docs/free-foreign-daily.md +44 -0
  24. package/docs/guide.en.md +232 -0
  25. package/docs/guide.md +248 -0
  26. package/docs/images/abc-drawing-v0.5.0.jpg +0 -0
  27. package/docs/images/channel-drawing-v0.5.0.jpg +0 -0
  28. package/docs/images/drawing-workbench-v0.5.0.jpg +0 -0
  29. package/docs/images/dsh-kline-tab-workspace.png +0 -0
  30. package/docs/images/dsh-market.png +0 -0
  31. package/docs/images/kline-news.png +0 -0
  32. package/docs/images/kline-range-stats.png +0 -0
  33. package/docs/images/kline-support.png +0 -0
  34. package/docs/images/main-chart-comparison-v0.6.9.png +0 -0
  35. package/docs/images/market-overview-v0.6.9.png +0 -0
  36. package/docs/images/natural-language-abc-wolong-2026-10-27.png +0 -0
  37. package/docs/images/natural-language-descending-channel-wolong-2026-10-27.png +0 -0
  38. package/docs/images/platform-breakout-msft-v0.6.9.png +0 -0
  39. package/docs/npm-release.md +33 -0
  40. package/docs/price-pattern-rules-v1.md +40 -0
  41. package/docs/price-pattern-samples-v1.md +42 -0
  42. package/docs/provider-adaptation.md +73 -0
  43. package/docs/release-acceptance-v0.4.0.md +46 -0
  44. package/docs/release-acceptance-v0.4.1.md +43 -0
  45. package/docs/release-acceptance-v0.5.0.md +40 -0
  46. package/docs/release-acceptance-v0.6.0.md +33 -0
  47. package/docs/release-acceptance-v0.6.1.md +19 -0
  48. package/docs/release-acceptance-v0.6.10.md +21 -0
  49. package/docs/release-acceptance-v0.6.2.md +31 -0
  50. package/docs/release-acceptance-v0.6.3.md +25 -0
  51. package/docs/release-acceptance-v0.6.4.md +24 -0
  52. package/docs/release-acceptance-v0.6.5.md +21 -0
  53. package/docs/release-acceptance-v0.6.6.md +21 -0
  54. package/docs/release-acceptance-v0.6.7.md +18 -0
  55. package/docs/release-acceptance-v0.6.8.md +18 -0
  56. package/docs/release-acceptance-v0.6.9.md +98 -0
  57. package/docs/release-notes-v0.5.0.md +23 -0
  58. package/docs/release-notes-v0.6.0.md +11 -0
  59. package/docs/release-notes-v0.6.1.md +20 -0
  60. package/docs/release-notes-v0.6.10.md +11 -0
  61. package/docs/release-notes-v0.6.2.md +14 -0
  62. package/docs/release-notes-v0.6.3.md +26 -0
  63. package/docs/release-notes-v0.6.4.md +12 -0
  64. package/docs/release-notes-v0.6.5.md +13 -0
  65. package/docs/release-notes-v0.6.6.md +13 -0
  66. package/docs/release-notes-v0.6.7.md +17 -0
  67. package/docs/release-notes-v0.6.8.md +10 -0
  68. package/docs/release-notes-v0.6.9.md +16 -0
  69. package/lib/candle-sequence.js +15 -0
  70. package/lib/chart-adjustment.js +7 -0
  71. package/lib/chart-annotations.js +33 -0
  72. package/lib/chart-applications.js +171 -0
  73. package/lib/chart-context.js +164 -0
  74. package/lib/chart-observation.js +251 -0
  75. package/lib/chart-service-status.js +82 -0
  76. package/lib/chart-source-status.js +39 -0
  77. package/lib/chart-sources.js +354 -0
  78. package/lib/client/BetterSidebarTab.js +70 -0
  79. package/lib/client/ClassicShell.js +254 -0
  80. package/lib/client/KlineContent.js +155 -0
  81. package/lib/client/chart-apply.js +73 -0
  82. package/lib/client/chart-context.js +233 -0
  83. package/lib/client/chart-handoff.js +34 -0
  84. package/lib/client/chart-session-resolver.js +74 -0
  85. package/lib/client/client-context.js +1 -0
  86. package/lib/client/conversation.js +88 -0
  87. package/lib/client/default-tab.js +83 -0
  88. package/lib/client/embed.js +50 -0
  89. package/lib/client/generated-view.js +12983 -0
  90. package/lib/client/horizontal-lines.js +19 -0
  91. package/lib/client/index.js +62 -0
  92. package/lib/client/mode-preferences.js +28 -0
  93. package/lib/client/native-sidebar-contract.js +45 -0
  94. package/lib/client/native-sidebar-register.js +133 -0
  95. package/lib/client/native-sidebar-services.js +1 -0
  96. package/lib/client/native-sidebar.js +96 -0
  97. package/lib/client/sidebar-integration.js +93 -0
  98. package/lib/client/ui-onboarding.js +42 -0
  99. package/lib/client/version.js +14 -0
  100. package/lib/client.js +17382 -0
  101. package/lib/client.js.map +1 -0
  102. package/lib/drawing-feedback.js +284 -0
  103. package/lib/fibonacci.js +18 -0
  104. package/lib/ftshare-settings-bridge.js +159 -0
  105. package/lib/index.js +279 -0
  106. package/lib/labeled-polyline.js +17 -0
  107. package/lib/pattern-groups.js +91 -0
  108. package/lib/price-bands.js +55 -0
  109. package/lib/price-series.js +47 -0
  110. package/lib/price-sticks.js +32 -0
  111. package/lib/types/candle-sequence.d.ts +2 -0
  112. package/lib/types/chart-adjustment.d.ts +2 -0
  113. package/lib/types/chart-annotations.d.ts +4 -0
  114. package/lib/types/chart-applications.d.ts +26 -0
  115. package/lib/types/chart-context.d.ts +14 -0
  116. package/lib/types/chart-observation.d.ts +8 -0
  117. package/lib/types/chart-service-status.d.ts +22 -0
  118. package/lib/types/chart-source-status.d.ts +47 -0
  119. package/lib/types/chart-sources.d.ts +25 -0
  120. package/lib/types/client/BetterSidebarTab.d.ts +12 -0
  121. package/lib/types/client/ClassicShell.d.ts +4 -0
  122. package/lib/types/client/KlineContent.d.ts +37 -0
  123. package/lib/types/client/chart-apply.d.ts +13 -0
  124. package/lib/types/client/chart-context.d.ts +23 -0
  125. package/lib/types/client/chart-handoff.d.ts +5 -0
  126. package/lib/types/client/chart-session-resolver.d.ts +2 -0
  127. package/lib/types/client/client-context.d.ts +14 -0
  128. package/lib/types/client/conversation.d.ts +43 -0
  129. package/lib/types/client/default-tab.d.ts +3 -0
  130. package/lib/types/client/embed.d.ts +37 -0
  131. package/lib/types/client/generated-view.d.ts +2 -0
  132. package/lib/types/client/horizontal-lines.d.ts +1 -0
  133. package/lib/types/client/index.d.ts +4 -0
  134. package/lib/types/client/mode-preferences.d.ts +13 -0
  135. package/lib/types/client/native-sidebar-contract.d.ts +52 -0
  136. package/lib/types/client/native-sidebar-register.d.ts +46 -0
  137. package/lib/types/client/native-sidebar-services.d.ts +45 -0
  138. package/lib/types/client/native-sidebar.d.ts +47 -0
  139. package/lib/types/client/sidebar-integration.d.ts +12 -0
  140. package/lib/types/client/ui-onboarding.d.ts +6 -0
  141. package/lib/types/client/version.d.ts +1 -0
  142. package/lib/types/drawing-feedback.d.ts +5 -0
  143. package/lib/types/fibonacci.d.ts +5 -0
  144. package/lib/types/ftshare-settings-bridge.d.ts +50 -0
  145. package/lib/types/index.d.ts +26 -0
  146. package/lib/types/labeled-polyline.d.ts +11 -0
  147. package/lib/types/pattern-groups.d.ts +2 -0
  148. package/lib/types/price-bands.d.ts +3 -0
  149. package/lib/types/price-series.d.ts +5 -0
  150. package/lib/types/price-sticks.d.ts +3 -0
  151. package/package.json +153 -4
  152. package/requirements.txt +6 -0
  153. package/screenshots.json +11 -0
  154. package/scripts/bootstrap.sh +5 -0
  155. package/scripts/dsh-bootstrap.mjs +179 -0
  156. package/scripts/dsh-mcp-plugin.mjs +27 -0
  157. package/scripts/run-dsh-kline.mjs +658 -0
  158. package/scripts/run-dsh-kline.sh +5 -0
  159. package/server.py +1755 -0
  160. package/tools/__init__.py +0 -0
  161. package/tools/annotations.py +119 -0
  162. package/tools/automatic_analysis.py +158 -0
  163. package/tools/baostock_source.py +176 -0
  164. package/tools/calc.py +39 -0
  165. package/tools/channel_candidates.py +260 -0
  166. package/tools/channel_preview.py +82 -0
  167. package/tools/channels.py +104 -0
  168. package/tools/chart_applications.py +204 -0
  169. package/tools/chart_context.py +186 -0
  170. package/tools/chart_edits.py +363 -0
  171. package/tools/chart_functions.py +451 -0
  172. package/tools/chart_indicators.py +65 -0
  173. package/tools/chart_measurements.py +84 -0
  174. package/tools/chart_source_status.py +32 -0
  175. package/tools/chart_sources.py +31 -0
  176. package/tools/closed_daily.py +68 -0
  177. package/tools/draw.py +410 -0
  178. package/tools/drawing_feedback.py +45 -0
  179. package/tools/drawing_interaction.py +117 -0
  180. package/tools/drawing_verification.py +141 -0
  181. package/tools/fetch.py +4680 -0
  182. package/tools/fibonacci.py +83 -0
  183. package/tools/foreign_daily.py +185 -0
  184. package/tools/free_sources.py +483 -0
  185. package/tools/lines.py +91 -0
  186. package/tools/nine_count.py +66 -0
  187. package/tools/pattern_groups.py +103 -0
  188. package/tools/pivots.py +60 -0
  189. package/tools/polylines.py +131 -0
  190. package/tools/price_bands.py +165 -0
  191. package/tools/price_patterns.py +311 -0
  192. package/tools/price_series.py +162 -0
  193. package/tools/price_sticks.py +114 -0
  194. package/tools/range_candidates.py +170 -0
  195. package/tools/recent_drawing_candidates.py +123 -0
  196. package/tools/rectangles.py +76 -0
  197. package/tools/regression_channels.py +87 -0
  198. package/tools/ta_functions.py +228 -0
  199. package/tools/trend_lines.py +106 -0
  200. package/tools/watchlist.py +149 -0
  201. package/view/ft-logo.jpg +0 -0
  202. package/view/kline.html +12436 -0
  203. package/view/vendor/klinecharts.min.js +7 -0
@@ -0,0 +1,3 @@
1
+ /** One bounded object; null pairs are explicit gaps and crossed bounds are refused. */
2
+ export declare function sanitizePriceBandCommand(raw: any, expectedBars: number, interval: string): any;
3
+ export declare function bandObservation(raw: any): any;
@@ -0,0 +1,5 @@
1
+ declare function source(raw: any): any;
2
+ declare function condition(raw: any): any;
3
+ export { source as sanitizePriceSource, condition as sanitizePriceCondition };
4
+ export declare function sanitizePriceSeriesCommand(raw: any, expectedBars: number, interval: string): any;
5
+ export declare function seriesObservation(raw: any): any;
@@ -0,0 +1,3 @@
1
+ /** A bounded sequence of independent vertical price sticks. */
2
+ export declare function sanitizePriceSticksCommand(raw: any, expectedBars: number, interval: string): any;
3
+ export declare function sticksObservation(raw: any): any;
package/package.json CHANGED
@@ -1,6 +1,155 @@
1
1
  {
2
2
  "name": "@ftshare-lab/dsh-kline",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.6.10",
4
+ "description": "DeepSeek Harness K-line plugin for conversational and manual chart drawing, TA-Lib indicators, and FTShare market data.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "files": [
8
+ "CHANGELOG.md",
9
+ "LICENSE",
10
+ "PROVENANCE.md",
11
+ "README.en.md",
12
+ "README.md",
13
+ "chart_service.py",
14
+ "config",
15
+ "cordis.patch.yml",
16
+ "core",
17
+ "docs/images",
18
+ "docs/release-acceptance-v0.4.0.md",
19
+ "docs/release-acceptance-v0.4.1.md",
20
+ "docs/release-acceptance-v0.5.0.md",
21
+ "docs/release-notes-v0.5.0.md",
22
+ "docs/release-acceptance-v0.6.0.md",
23
+ "docs/release-notes-v0.6.0.md",
24
+ "docs/chart-functions.md",
25
+ "docs/price-pattern-rules-v1.md",
26
+ "docs/price-pattern-samples-v1.md",
27
+ "docs/automatic-drawing.md",
28
+ "docs/fixtures/price-pattern-real-v1.json",
29
+ "!core/**/__pycache__/**",
30
+ "!core/**/*.py[cod]",
31
+ "lib",
32
+ "requirements.txt",
33
+ "screenshots.json",
34
+ "scripts/bootstrap.sh",
35
+ "scripts/run-dsh-kline.mjs",
36
+ "scripts/run-dsh-kline.sh",
37
+ "server.py",
38
+ "tools",
39
+ "!tools/**/__pycache__/**",
40
+ "!tools/**/*.py[cod]",
41
+ "view",
42
+ "docs/release-notes-v0.6.1.md",
43
+ "docs/release-acceptance-v0.6.1.md",
44
+ "docs/release-notes-v0.6.2.md",
45
+ "docs/release-acceptance-v0.6.2.md",
46
+ "docs/release-notes-v0.6.3.md",
47
+ "docs/release-acceptance-v0.6.3.md",
48
+ "scripts/dsh-mcp-plugin.mjs",
49
+ "docs/release-notes-v0.6.4.md",
50
+ "docs/release-acceptance-v0.6.4.md",
51
+ "docs/embedding.md",
52
+ "docs/anonymous-market-support.md",
53
+ "docs/release-notes-v0.6.5.md",
54
+ "docs/release-acceptance-v0.6.5.md",
55
+ "docs/release-notes-v0.6.6.md",
56
+ "docs/release-acceptance-v0.6.6.md",
57
+ "docs/free-foreign-daily.md",
58
+ "docs/release-notes-v0.6.7.md",
59
+ "docs/release-acceptance-v0.6.7.md",
60
+ "docs/release-notes-v0.6.8.md",
61
+ "docs/release-acceptance-v0.6.8.md",
62
+ "scripts/dsh-bootstrap.mjs",
63
+ "docs/release-notes-v0.6.9.md",
64
+ "docs/release-acceptance-v0.6.9.md",
65
+ "docs/npm-release.md",
66
+ "docs/guide.md",
67
+ "docs/guide.en.md",
68
+ "docs/drawing-examples.md",
69
+ "docs/drawing-examples.en.md",
70
+ "docs/provider-adaptation.md",
71
+ "docs/release-notes-v0.6.10.md",
72
+ "docs/release-acceptance-v0.6.10.md"
73
+ ],
74
+ "main": "lib/index.js",
75
+ "types": "lib/types/index.d.ts",
76
+ "exports": {
77
+ ".": {
78
+ "types": "./lib/types/index.d.ts",
79
+ "default": "./lib/index.js"
80
+ },
81
+ "./client": {
82
+ "types": "./lib/types/client/index.d.ts",
83
+ "default": "./lib/client.js"
84
+ },
85
+ "./cordis.patch.yml": "./cordis.patch.yml",
86
+ "./package.json": "./package.json"
87
+ },
88
+ "dsh": {
89
+ "bundle": {
90
+ "patch": "./cordis.patch.yml"
91
+ },
92
+ "client": {
93
+ "platform": "web",
94
+ "inject": [
95
+ "@deepseek-ai/dsh-api-session-controller"
96
+ ]
97
+ }
98
+ },
99
+ "repository": {
100
+ "type": "git",
101
+ "url": "git+https://github.com/FTShare-Lab/dsh_kline.git"
102
+ },
103
+ "bugs": {
104
+ "url": "https://github.com/FTShare-Lab/dsh_kline/issues"
105
+ },
106
+ "homepage": "https://github.com/FTShare-Lab/dsh_kline#readme",
107
+ "keywords": [
108
+ "deepseek",
109
+ "dsh",
110
+ "mcp",
111
+ "kline",
112
+ "ftshare"
113
+ ],
114
+ "packageManager": "pnpm@11.7.0",
115
+ "engines": {
116
+ "node": ">=22.19.0"
117
+ },
118
+ "scripts": {
119
+ "bootstrap": "node ./scripts/run-dsh-kline.mjs --prepare-project",
120
+ "pack:release": "node ./scripts/build-release-package.mjs ./release/dsh-kline-v0.6.10.tgz",
121
+ "pack:codex": "node ./scripts/build-codex-package.mjs ./release/ft-kline-v0.6.10.zip && node ./scripts/verify-codex-package.mjs ./release/ft-kline-v0.6.10.zip",
122
+ "smoke:codex-package": "python ./scripts/smoke-codex-package.py ./release/ft-kline-v0.6.10.zip",
123
+ "generate:client-view": "node ./scripts/generate-client-view.mjs",
124
+ "build:sidebar": "pnpm generate:client-view && tsc -p tsconfig.json && tsdown --config tsdown.config.ts && pnpm verify:package",
125
+ "verify:package": "node ./scripts/verify-package.mjs",
126
+ "verify:packages": "pnpm verify:package && pnpm pack:release && pnpm pack:codex",
127
+ "dsh:web": "bash ./scripts/run-dsh-web.sh",
128
+ "test": "node ./scripts/run-tests.mjs",
129
+ "test:node": "node ./scripts/run-tests.mjs --node",
130
+ "test:python": "node ./scripts/run-tests.mjs --python",
131
+ "test:launcher": "node --test tests/launcher-paths.test.mjs",
132
+ "generate:codex-catalog": "python scripts/generate-codex-catalog.py",
133
+ "verify:codex-catalog": "python scripts/generate-codex-catalog.py --check",
134
+ "sync:codex-marketplace": "node scripts/sync-codex-marketplace.mjs",
135
+ "verify:codex-marketplace": "node scripts/sync-codex-marketplace.mjs --check",
136
+ "generate:dsh-catalog": "python scripts/generate-dsh-catalog.py",
137
+ "verify:dsh-catalog": "python scripts/generate-dsh-catalog.py --check"
138
+ },
139
+ "devDependencies": {
140
+ "@deepseek-ai/dsh": "0.1.5-rc.2",
141
+ "@types/node": "22.20.0",
142
+ "@types/react": "18.3.31",
143
+ "@types/react-dom": "18.3.7",
144
+ "dsh-better-sidebar": "0.19.1",
145
+ "react": "18.3.1",
146
+ "react-dom": "18.3.1",
147
+ "tsdown": "0.22.2",
148
+ "typescript": "6.0.3",
149
+ "unrun": "^0.3.1"
150
+ },
151
+ "publishConfig": {
152
+ "access": "public",
153
+ "registry": "https://registry.npmjs.org/"
154
+ }
155
+ }
@@ -0,0 +1,6 @@
1
+ mcp==1.30.0
2
+ pydantic>=2.0,<3.0
3
+ pydantic-settings==2.14.2
4
+ TA-Lib==0.8.2
5
+ baostock==0.9.4
6
+ ftshare @ https://github.com/FTShare-Lab/FTShare-python-sdk/archive/refs/tags/v1.0.7.tar.gz
@@ -0,0 +1,11 @@
1
+ [
2
+ "docs/images/market-overview-v0.6.9.png",
3
+ "docs/images/main-chart-comparison-v0.6.9.png",
4
+ "docs/images/platform-breakout-msft-v0.6.9.png",
5
+ "docs/images/dsh-kline-tab-workspace.png",
6
+ "docs/images/drawing-workbench-v0.5.0.jpg",
7
+ "docs/images/kline-support.png",
8
+ "docs/images/kline-range-stats.png",
9
+ "docs/images/kline-news.png",
10
+ "docs/images/dsh-market.png"
11
+ ]
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
5
+ exec node "$PROJECT_ROOT/scripts/run-dsh-kline.mjs" --prepare-project
@@ -0,0 +1,179 @@
1
+ // Keep the host's MCP connection alive while Python is prepared or restarted.
2
+ // No deferred/expired call or in-flight operation is replayed after a failure.
3
+ import { spawn } from 'node:child_process'
4
+ import { createInterface } from 'node:readline'
5
+ import { readFileSync, mkdirSync, writeFileSync, renameSync, appendFileSync, statSync, rmSync } from 'node:fs'
6
+ import { join } from 'node:path'
7
+ import { defaultStateDirectory } from './run-dsh-kline.mjs'
8
+
9
+ const catalog = JSON.parse(readFileSync(new URL('../config/dsh-tool-catalog.json', import.meta.url), 'utf8'))
10
+ const runtimeTool = { name: 'dsh_kline_runtime_status', description: 'Check Python preparation or recovery. The complete tool catalog is available from startup; retry the requested tool when ready. Never replay an operation with an unknown outcome.',
11
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false }, annotations: { readOnlyHint: true } }
12
+
13
+ export function serve({ input = process.stdin, output = process.stdout, error = process.stderr,
14
+ command = process.execPath, args, env = process.env, spawnServer = spawn,
15
+ preparationWaitMs = 5000, retryDelayMs = 1000, maxRetryDelayMs = 30000, handshakeTimeoutMs = 20 * 60 * 1000 } = {}) {
16
+ const hostPid = /^[1-9]\d*$/.test(env.DSH_KLINE_HOST_PID || '') ? env.DSH_KLINE_HOST_PID : String(process.ppid)
17
+ const directory = join(defaultStateDirectory(env), 'logs')
18
+ const logPath = join(directory, `backend-${hostPid}.log`)
19
+ const statusPath = join(directory, `backend-${hostPid}.json`)
20
+ let child, lines, init, retryTimer, handshakeTimer, closed = false, ready = false, failures = 0, lastError
21
+ const queued = new Map(), inFlight = new Map()
22
+ const send = value => { if (!closed) output.write(`${JSON.stringify(value)}\n`) }
23
+ const reply = (id, result) => send({ jsonrpc: '2.0', id, result })
24
+ const protocolError = (id, code, message) => send({ jsonrpc: '2.0', id, error: { code, message } })
25
+ const status = () => ({ ok: ready, phase: ready ? 'ready' : lastError ? 'recovering' : 'preparing',
26
+ error: ready ? undefined : lastError || 'runtime_preparing', retryable: !closed,
27
+ host_process_id: Number(hostPid), launcher_process_id: process.pid, log_path: logPath })
28
+ const persist = () => {
29
+ try {
30
+ mkdirSync(directory, { recursive: true, mode: 0o700 })
31
+ const temporary = `${statusPath}.${process.pid}.tmp`
32
+ writeFileSync(temporary, JSON.stringify({ ...status(), updated_at: Date.now() }), { mode: 0o600 })
33
+ renameSync(temporary, statusPath)
34
+ } catch { /* A diagnostic failure must not close the protocol connection. */ }
35
+ }
36
+ const log = chunk => {
37
+ error.write(chunk)
38
+ try {
39
+ mkdirSync(directory, { recursive: true, mode: 0o700 })
40
+ try { if (statSync(logPath).size + Buffer.byteLength(chunk) > 1024 * 1024) { rmSync(`${logPath}.previous`, {force:true}); renameSync(logPath, `${logPath}.previous`) } } catch {}
41
+ appendFileSync(logPath, chunk, { mode: 0o600 })
42
+ } catch { /* stderr remains available when the cache is not writable. */ }
43
+ }
44
+ const unavailable = (id, dispatched = false) => reply(id, {
45
+ content: [{ type: 'text', text: dispatched
46
+ ? '后端连接中断,操作结果未知。请先核对当前状态,不要自动重放操作。'
47
+ : ready ? '后端已恢复,请重新发起操作。' : 'Python 正在准备或恢复。此操作尚未执行,请就绪后重试。' }],
48
+ structuredContent: { ...status(), ok: false, error: dispatched ? 'runtime_connection_lost' : lastError || 'runtime_preparing',
49
+ operation_dispatched: dispatched, outcome_unknown: dispatched }, isError: true,
50
+ })
51
+ const cancelQueued = id => {
52
+ const item = queued.get(id)
53
+ if (item) { clearTimeout(item.timer); queued.delete(id) }
54
+ }
55
+ const forward = message => {
56
+ if (message.id != null && message.method) inFlight.set(message.id, message)
57
+ child.stdin.write(`${JSON.stringify(message)}\n`)
58
+ }
59
+ const terminate = generation => {
60
+ generation.stdin.destroy()
61
+ if (!generation.pid) { generation.kill(); return }
62
+ if (process.platform === 'win32') {
63
+ // Terminate the owned install/backend tree, including pip children. A
64
+ // parent-only kill can leave an installer racing the next activation.
65
+ const killer = spawn('taskkill', ['/pid', String(generation.pid), '/T', '/F'], {stdio:'ignore', windowsHide:true})
66
+ killer.on('error', () => generation.kill())
67
+ } else {
68
+ // spawn(detached) below gives this generation its own process group.
69
+ try { process.kill(-generation.pid, 'SIGTERM') } catch { generation.kill() }
70
+ }
71
+ }
72
+ const down = (generation, reason) => {
73
+ if (closed || child !== generation) return
74
+ ready = false; child = undefined; lastError = reason
75
+ clearTimeout(handshakeTimer)
76
+ lines?.close()
77
+ terminate(generation)
78
+ for (const [id, message] of inFlight) {
79
+ if (message.method === 'tools/call') unavailable(id, true)
80
+ else protocolError(id, -32603, 'Backend connection lost; request was not replayed')
81
+ }
82
+ inFlight.clear()
83
+ for (const id of queued.keys()) { cancelQueued(id); unavailable(id) }
84
+ failures += 1
85
+ const wait = Math.min(maxRetryDelayMs, retryDelayMs * 2 ** Math.min(failures - 1, 10))
86
+ log(`[dsh_kline] ${reason}; retrying backend in ${wait}ms; MCP connection retained.\n`)
87
+ persist()
88
+ // Wait for this generation to exit before starting another Python owner.
89
+ const schedule = () => {
90
+ if (!closed && !retryTimer) retryTimer = setTimeout(() => { retryTimer = undefined; start() }, wait)
91
+ }
92
+ if (generation.exitCode != null || generation.signalCode != null || !generation.pid) schedule()
93
+ else generation.once('exit', schedule)
94
+ }
95
+ const start = () => {
96
+ if (closed || child) return
97
+ let generation
98
+ try { generation = spawnServer(command, args, { env: { ...env, DSH_KLINE_DEFER_BOOTSTRAP: '0' }, stdio: ['pipe', 'pipe', 'pipe'], detached:process.platform !== 'win32', windowsHide: true }) }
99
+ catch {
100
+ lastError = 'backend_spawn_failed'; failures += 1; log('[dsh_kline] backend_spawn_failed; MCP connection retained.\n'); persist()
101
+ retryTimer = setTimeout(() => { retryTimer = undefined; start() }, Math.min(maxRetryDelayMs, retryDelayMs * 2 ** Math.min(failures - 1, 10)))
102
+ return
103
+ }
104
+ child = generation; persist()
105
+ generation.stderr.on('data', log)
106
+ generation.stdin.on('error', () => down(generation, 'backend_pipe_failed'))
107
+ generation.on('error', () => down(generation, 'backend_spawn_failed'))
108
+ generation.on('exit', (code, signal) => {
109
+ if (child === generation && !closed) log(`[dsh_kline] Backend exited code=${code} signal=${signal || 'none'}.\n`)
110
+ down(generation, 'backend_exited')
111
+ })
112
+ lines = createInterface({ input: generation.stdout })
113
+ lines.on('line', line => {
114
+ if (child !== generation || closed) return
115
+ let value
116
+ try { value = JSON.parse(line) } catch { log('[dsh_kline] Ignored non-protocol backend stdout.\n'); return }
117
+ if (!value || typeof value !== 'object' || Array.isArray(value) || value.jsonrpc !== '2.0') {
118
+ log('[dsh_kline] Ignored invalid backend protocol frame.\n'); return
119
+ }
120
+ if (!ready && value.id === 'dsh-kline-bootstrap-initialize') {
121
+ if (value.error || !value.result) { down(generation, 'backend_initialize_failed'); return }
122
+ clearTimeout(handshakeTimer)
123
+ forward({ jsonrpc: '2.0', method: 'notifications/initialized' })
124
+ ready = true; lastError = undefined; failures = 0; persist()
125
+ for (const [id, request] of queued) { cancelQueued(id); forward(request.message) }
126
+ } else if (!['notifications/tools/list_changed', 'notifications/resources/list_changed'].includes(value.method)) {
127
+ if (!value.method) inFlight.delete(value.id)
128
+ send(value)
129
+ }
130
+ })
131
+ handshakeTimer = setTimeout(() => down(generation, 'backend_initialize_timeout'), handshakeTimeoutMs)
132
+ forward({ ...init, id: 'dsh-kline-bootstrap-initialize' })
133
+ inFlight.delete('dsh-kline-bootstrap-initialize')
134
+ }
135
+ const shutdown = () => {
136
+ if (closed) return
137
+ closed = true; ready = false
138
+ clearTimeout(retryTimer); clearTimeout(handshakeTimer)
139
+ for (const id of queued.keys()) cancelQueued(id)
140
+ inFlight.clear()
141
+ if (child) terminate(child)
142
+ lines?.close(); inputLines.close()
143
+ process.removeListener('SIGTERM', shutdown); process.removeListener('SIGINT', shutdown)
144
+ }
145
+ const inputLines = createInterface({ input })
146
+ inputLines.on('line', line => {
147
+ let message
148
+ try { message = JSON.parse(line) } catch { protocolError(null, -32700, 'Invalid JSON'); return }
149
+ if (!message || typeof message !== 'object' || Array.isArray(message) || message.jsonrpc !== '2.0') { protocolError(null, -32600, 'Invalid JSON-RPC message'); return }
150
+ if (message.method === 'initialize' && !init) {
151
+ init = message
152
+ reply(message.id, { protocolVersion: message.params?.protocolVersion || '2024-11-05',
153
+ capabilities: { tools: { listChanged: false } }, serverInfo: { name: 'dsh_kline', version: catalog.version },
154
+ instructions: `${catalog.instructions}\nThe complete tool catalog is available during preparation. Retry calls reporting runtime_preparing only after readiness; never replay operations with unknown outcomes.` })
155
+ start(); return
156
+ }
157
+ if (message.method === 'ping') { reply(message.id, {}); return }
158
+ if (!init) { if (message.id != null) protocolError(message.id, -32002, 'Initialize the server first'); return }
159
+ if (message.method === 'tools/list') reply(message.id, { tools: [...catalog.tools, runtimeTool] })
160
+ else if (message.method === 'resources/list') reply(message.id, { resources: [] })
161
+ else if (message.method === 'resources/templates/list') reply(message.id, { resourceTemplates: [] })
162
+ else if (message.method === 'tools/call' && message.params?.name === runtimeTool.name) {
163
+ reply(message.id, { content: [{ type: 'text', text: JSON.stringify(status()) }], structuredContent: status(), isError: false })
164
+ } else if (message.method === 'notifications/initialized') { /* Child has its own handshake. */ }
165
+ else if (message.method === 'notifications/cancelled') {
166
+ if (queued.has(message.params?.requestId)) cancelQueued(message.params.requestId)
167
+ else if (ready) { inFlight.delete(message.params?.requestId); forward(message) }
168
+ } else if (message.method === 'tools/call' && !catalog.tools.some(tool => tool.name === message.params?.name)) protocolError(message.id, -32602, 'Unknown tool')
169
+ else if (ready) forward(message)
170
+ else if (message.method === 'tools/call') {
171
+ if (queued.has(message.id)) return
172
+ const timer = setTimeout(() => { queued.delete(message.id); unavailable(message.id) }, preparationWaitMs)
173
+ queued.set(message.id, { message, timer })
174
+ } else if (message.id != null) protocolError(message.id, -32002, 'Python backend is preparing or recovering')
175
+ })
176
+ inputLines.on('close', shutdown)
177
+ process.on('SIGTERM', shutdown); process.on('SIGINT', shutdown)
178
+ return { shutdown }
179
+ }
@@ -0,0 +1,27 @@
1
+ // A relative Cordis plugin name is anchored beside its bundle patch by DSH.
2
+ // Resolve the Python launcher from this module, including nested/pnpm installs.
3
+ import { existsSync, readFileSync, realpathSync } from 'node:fs'
4
+ import { isAbsolute, join, resolve } from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
6
+
7
+ export const name = 'dsh-kline-mcp-launcher'
8
+ export const inject = ['loader']
9
+
10
+ export function mcpConfiguration(config = {}, env = process.env, packageRoot = fileURLToPath(new URL('..', import.meta.url))) {
11
+ const override = String(env.DSH_KLINE_PACKAGE_ROOT || '').trim()
12
+ if (override && !isAbsolute(override)) throw new Error('DSH_KLINE_PACKAGE_ROOT must be an absolute package directory')
13
+ let root = resolve(override || packageRoot)
14
+ let manifest
15
+ try { root = realpathSync(root); manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) } catch {}
16
+ if (manifest?.name !== '@ftshare-lab/dsh-kline' || !existsSync(join(root, 'scripts', 'run-dsh-kline.mjs'))) {
17
+ throw new Error('dsh_kline package directory is incomplete; reinstall the plugin or correct DSH_KLINE_PACKAGE_ROOT')
18
+ }
19
+ return { ...config, command: config.command || process.execPath, transport: 'stdio',
20
+ cwd: root, args: [join(root, 'scripts', 'run-dsh-kline.mjs')] }
21
+ }
22
+
23
+ export async function apply(ctx, config) {
24
+ const resolved = mcpConfiguration(config)
25
+ const client = await ctx.loader.import('@deepseek-ai/dsh-mcp-client')
26
+ ctx.plugin(client.default || client, resolved)
27
+ }