@dsh-ft/dsh-fft-paper-trading 0.6.2 → 0.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/client.js +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +25 -0
- package/node_modules/@ftshare-lab/dsh-kline/README.en.md +19 -7
- package/node_modules/@ftshare-lab/dsh-kline/README.md +20 -8
- package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +52 -6
- package/node_modules/@ftshare-lab/dsh-kline/config/basic-symbols.json +185 -7
- package/node_modules/@ftshare-lab/dsh-kline/config/dsh-tool-catalog.json +3783 -0
- package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +2 -3
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-service-status.js +82 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +36 -13
- package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +59 -44
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-service-status.d.ts +22 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/package.json +18 -6
- package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-bootstrap.mjs +179 -0
- package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +16 -11
- package/node_modules/@ftshare-lab/dsh-kline/server.py +3 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +143 -84
- package/node_modules/@ftshare-lab/dsh-kline/tools/foreign_daily.py +185 -0
- package/package.json +2 -2
|
@@ -2,6 +2,7 @@ import { readFile } from 'node:fs/promises';
|
|
|
2
2
|
import { homedir } from 'node:os';
|
|
3
3
|
import { join, resolve } from 'node:path';
|
|
4
4
|
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { ChartServiceUnavailable, readServiceLocator, probeChartService, unavailableService } from "./chart-service-status.js";
|
|
5
6
|
import { ChartContextBroker } from "./chart-context.js";
|
|
6
7
|
import { ChartApplications } from "./chart-applications.js";
|
|
7
8
|
import { startFtshareSettingsBridge } from "./ftshare-settings-bridge.js";
|
|
@@ -9,6 +10,7 @@ export const name = 'dsh-kline-sidebar';
|
|
|
9
10
|
export const inject = ['webServer'];
|
|
10
11
|
const RUNTIME_DIR = runtimeDirectory();
|
|
11
12
|
const RUNTIME_FILE = join(RUNTIME_DIR, 'services', `${process.pid}.json`);
|
|
13
|
+
const STATE_DIR = stateDirectory();
|
|
12
14
|
const SESSION_DIR = join(RUNTIME_DIR, 'sessions');
|
|
13
15
|
const VENDOR_FILE = fileURLToPath(new URL('../view/vendor/klinecharts.min.js', import.meta.url));
|
|
14
16
|
const LOGO_FILE = fileURLToPath(new URL('../view/ft-logo.jpg', import.meta.url));
|
|
@@ -62,6 +64,39 @@ async function serveRuntimeSession(request, response, contexts) {
|
|
|
62
64
|
const url = new URL(request.url ?? '/', 'http://localhost');
|
|
63
65
|
const pathname = url.pathname;
|
|
64
66
|
try {
|
|
67
|
+
if (pathname === '/dsh-kline/healthz') {
|
|
68
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
69
|
+
sendJson(response, 405, { ok: false, error: 'method_not_allowed' });
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const version = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
73
|
+
const diagnostics = { version, host_process_id: process.pid, locator_path: RUNTIME_FILE,
|
|
74
|
+
log_path: join(STATE_DIR, 'logs', `backend-${process.pid}.log`) };
|
|
75
|
+
try {
|
|
76
|
+
const locator = await readServiceLocator(RUNTIME_FILE, process.pid);
|
|
77
|
+
await probeChartService(locator);
|
|
78
|
+
sendJson(response, 200, { ok: true, ...diagnostics, process_id: locator.process_id,
|
|
79
|
+
service_url: locator.service_url }, request.method === 'HEAD');
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
let reason = error instanceof ChartServiceUnavailable ? error.reason : 'service_locator_invalid';
|
|
83
|
+
if (reason === 'service_locator_missing') {
|
|
84
|
+
try {
|
|
85
|
+
const status = JSON.parse(await readFile(join(STATE_DIR, 'logs', `backend-${process.pid}.json`), 'utf8'));
|
|
86
|
+
if (status.host_process_id === process.pid && Number.isSafeInteger(status.launcher_process_id)) {
|
|
87
|
+
process.kill(status.launcher_process_id, 0);
|
|
88
|
+
if (status.phase === 'preparing')
|
|
89
|
+
reason = 'runtime_preparing';
|
|
90
|
+
else if (status.phase === 'recovering')
|
|
91
|
+
reason = 'runtime_recovering';
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
catch { /* A missing or stale diagnostic cannot prove readiness. */ }
|
|
95
|
+
}
|
|
96
|
+
sendJson(response, 503, { ...unavailableService(reason), ...diagnostics }, request.method === 'HEAD');
|
|
97
|
+
}
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
65
100
|
if (pathname === '/dsh-kline/recovery' && request.method === 'GET') {
|
|
66
101
|
try {
|
|
67
102
|
const recovery = await new ChartApplications(RUNTIME_DIR).recover(url.searchParams.get('conversation') ?? '');
|
|
@@ -130,11 +165,12 @@ async function serveRuntimeSession(request, response, contexts) {
|
|
|
130
165
|
}
|
|
131
166
|
return;
|
|
132
167
|
}
|
|
133
|
-
|
|
134
|
-
if (!
|
|
135
|
-
sendJson(response,
|
|
168
|
+
// Unknown paths have a stable routing result, independent of backend state.
|
|
169
|
+
if (!pathname.startsWith('/dsh-kline/api/tools/')) {
|
|
170
|
+
sendJson(response, 404, { ok: false, error: 'not_found' }, request.method === 'HEAD');
|
|
136
171
|
return;
|
|
137
172
|
}
|
|
173
|
+
const session = await readLiveSession();
|
|
138
174
|
if (pathname.startsWith('/dsh-kline/api/tools/') && request.method === 'POST') {
|
|
139
175
|
const action = pathname.slice('/dsh-kline/api/tools/'.length).replaceAll('/', '');
|
|
140
176
|
if (!CHART_ACTIONS.has(action)) {
|
|
@@ -163,6 +199,10 @@ async function serveRuntimeSession(request, response, contexts) {
|
|
|
163
199
|
sendJson(response, 404, { ok: false, error: 'not_found' });
|
|
164
200
|
}
|
|
165
201
|
catch (error) {
|
|
202
|
+
if (error instanceof ChartServiceUnavailable) {
|
|
203
|
+
sendJson(response, 200, unavailableService(error.reason), request.method === 'HEAD');
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
166
206
|
const code = error instanceof Error && 'code' in error ? String(error.code) : '';
|
|
167
207
|
sendJson(response, code === 'ENOENT' ? 200 : 500, code === 'ENOENT'
|
|
168
208
|
? (pathname === '/dsh-kline/data' || pathname === '/dsh-kline/session'
|
|
@@ -171,32 +211,40 @@ async function serveRuntimeSession(request, response, contexts) {
|
|
|
171
211
|
: { ok: false, error: 'chart_session_manifest_failed' }, request.method === 'HEAD');
|
|
172
212
|
}
|
|
173
213
|
}
|
|
174
|
-
function unavailableService() {
|
|
175
|
-
return { ok: false, error: 'chart_session_unavailable', message: '当前 DSH 的行情服务尚未就绪,请稍后重试;若持续失败,请重启 dsh web。' };
|
|
176
|
-
}
|
|
177
214
|
export function runtimeDirectory(env = process.env) {
|
|
178
215
|
const explicit = String(env.DSH_KLINE_RUNTIME_DIR || '').trim();
|
|
216
|
+
if (explicit)
|
|
217
|
+
return resolve(explicit);
|
|
218
|
+
return join(stateDirectory(env), 'runtime');
|
|
219
|
+
}
|
|
220
|
+
function stateDirectory(env = process.env) {
|
|
221
|
+
const explicit = String(env.DSH_KLINE_CACHE_DIR || '').trim();
|
|
179
222
|
if (explicit)
|
|
180
223
|
return resolve(explicit);
|
|
181
224
|
if (process.platform === 'win32') {
|
|
182
225
|
const local = String(env.LOCALAPPDATA || env.APPDATA || '').trim();
|
|
183
|
-
return join(local || join(homedir(), 'AppData', 'Local'), 'dsh_kline'
|
|
226
|
+
return join(local || join(homedir(), 'AppData', 'Local'), 'dsh_kline');
|
|
184
227
|
}
|
|
185
228
|
const cache = String(env.XDG_CACHE_HOME || '').trim();
|
|
186
|
-
return join(cache || join(homedir(), '.cache'), 'dsh_kline'
|
|
229
|
+
return join(cache || join(homedir(), '.cache'), 'dsh_kline');
|
|
187
230
|
}
|
|
188
231
|
function chartServiceHeaders(session) {
|
|
189
232
|
return { 'X-DSH-Kline-Token': session.service_token };
|
|
190
233
|
}
|
|
191
234
|
async function readLiveSession() {
|
|
192
|
-
|
|
193
|
-
return isLiveSession(payload) ? payload : undefined;
|
|
235
|
+
return readServiceLocator(RUNTIME_FILE, process.pid);
|
|
194
236
|
}
|
|
195
237
|
function serviceOrigin(session) {
|
|
196
238
|
return new URL(session.service_url).origin;
|
|
197
239
|
}
|
|
198
240
|
async function proxyJson(response, url, init) {
|
|
199
|
-
|
|
241
|
+
let upstream;
|
|
242
|
+
try {
|
|
243
|
+
upstream = await fetch(url, { ...init, signal: AbortSignal.timeout(120000) });
|
|
244
|
+
}
|
|
245
|
+
catch (error) {
|
|
246
|
+
throw new ChartServiceUnavailable(error instanceof Error && error.name === 'TimeoutError' ? 'backend_timeout' : 'backend_unreachable');
|
|
247
|
+
}
|
|
200
248
|
const body = Buffer.from(await upstream.arrayBuffer());
|
|
201
249
|
if (body.length > MAX_PROXY_BYTES) {
|
|
202
250
|
sendJson(response, 502, { ok: false, error: 'chart_response_too_large' });
|
|
@@ -216,39 +264,6 @@ async function readRequestBody(request) {
|
|
|
216
264
|
}
|
|
217
265
|
return Buffer.concat(chunks);
|
|
218
266
|
}
|
|
219
|
-
function isLiveSession(value) {
|
|
220
|
-
if (typeof value !== 'object' || value === null)
|
|
221
|
-
return false;
|
|
222
|
-
const candidate = value;
|
|
223
|
-
if (candidate.ok !== true
|
|
224
|
-
|| candidate.host_process_id !== process.pid
|
|
225
|
-
|| typeof candidate.session !== 'string'
|
|
226
|
-
|| typeof candidate.service_url !== 'string'
|
|
227
|
-
|| typeof candidate.service_token !== 'string'
|
|
228
|
-
|| typeof candidate.process_id !== 'number'
|
|
229
|
-
|| typeof candidate.published_at !== 'number'
|
|
230
|
-
|| !Number.isSafeInteger(candidate.process_id)
|
|
231
|
-
|| candidate.process_id <= 0
|
|
232
|
-
|| candidate.service_token.length < 32
|
|
233
|
-
|| !Number.isSafeInteger(candidate.published_at)
|
|
234
|
-
|| candidate.published_at <= 0)
|
|
235
|
-
return false;
|
|
236
|
-
try {
|
|
237
|
-
const serviceUrl = new URL(candidate.service_url);
|
|
238
|
-
if (serviceUrl.protocol !== 'http:' || !['127.0.0.1', 'localhost'].includes(serviceUrl.hostname))
|
|
239
|
-
return false;
|
|
240
|
-
}
|
|
241
|
-
catch {
|
|
242
|
-
return false;
|
|
243
|
-
}
|
|
244
|
-
try {
|
|
245
|
-
process.kill(candidate.process_id, 0);
|
|
246
|
-
return true;
|
|
247
|
-
}
|
|
248
|
-
catch {
|
|
249
|
-
return false;
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
267
|
function sendJson(response, status, value, head = false) {
|
|
253
268
|
const body = Buffer.from(JSON.stringify(value));
|
|
254
269
|
sendBytes(response, status, body, 'application/json; charset=utf-8', head);
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export declare class ChartServiceUnavailable extends Error {
|
|
2
|
+
readonly reason: string;
|
|
3
|
+
constructor(reason: string);
|
|
4
|
+
}
|
|
5
|
+
export interface ServiceLocator extends Record<string, unknown> {
|
|
6
|
+
ok: true;
|
|
7
|
+
process_id: number;
|
|
8
|
+
host_process_id: number;
|
|
9
|
+
session: string;
|
|
10
|
+
service_url: string;
|
|
11
|
+
service_token: string;
|
|
12
|
+
published_at: number;
|
|
13
|
+
instance_id?: string;
|
|
14
|
+
}
|
|
15
|
+
export declare function readServiceLocator(path: string, hostPid: number): Promise<ServiceLocator>;
|
|
16
|
+
export declare function probeChartService(locator: ServiceLocator, timeoutMs?: number): Promise<void>;
|
|
17
|
+
export declare function unavailableService(reason?: string): {
|
|
18
|
+
ok: boolean;
|
|
19
|
+
error: string;
|
|
20
|
+
reason: string;
|
|
21
|
+
message: string;
|
|
22
|
+
};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const PACKAGE_VERSION = "0.6.
|
|
1
|
+
export declare const PACKAGE_VERSION = "0.6.7";
|
|
2
2
|
export declare function mountKlineView(root: any, payload: any, dependencies?: {}): () => void;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ftshare-lab/dsh-kline",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.7",
|
|
4
4
|
"private": true,
|
|
5
5
|
"description": "DeepSeek Harness K-line plugin for conversational and manual chart drawing, TA-Lib indicators, and FTShare market data.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -44,7 +44,17 @@
|
|
|
44
44
|
"docs/release-acceptance-v0.6.3.md",
|
|
45
45
|
"scripts/dsh-mcp-plugin.mjs",
|
|
46
46
|
"docs/release-notes-v0.6.4.md",
|
|
47
|
-
"docs/release-acceptance-v0.6.4.md"
|
|
47
|
+
"docs/release-acceptance-v0.6.4.md",
|
|
48
|
+
"docs/embedding.md",
|
|
49
|
+
"docs/anonymous-market-support.md",
|
|
50
|
+
"docs/release-notes-v0.6.5.md",
|
|
51
|
+
"docs/release-acceptance-v0.6.5.md",
|
|
52
|
+
"docs/release-notes-v0.6.6.md",
|
|
53
|
+
"docs/release-acceptance-v0.6.6.md",
|
|
54
|
+
"docs/free-foreign-daily.md",
|
|
55
|
+
"docs/release-notes-v0.6.7.md",
|
|
56
|
+
"docs/release-acceptance-v0.6.7.md",
|
|
57
|
+
"scripts/dsh-bootstrap.mjs"
|
|
48
58
|
],
|
|
49
59
|
"main": "lib/index.js",
|
|
50
60
|
"types": "lib/types/index.d.ts",
|
|
@@ -92,9 +102,9 @@
|
|
|
92
102
|
},
|
|
93
103
|
"scripts": {
|
|
94
104
|
"bootstrap": "node ./scripts/run-dsh-kline.mjs --prepare-project",
|
|
95
|
-
"pack:release": "node ./scripts/build-release-package.mjs ./release/dsh-kline-v0.6.
|
|
96
|
-
"pack:codex": "node ./scripts/build-codex-package.mjs ./release/ft-kline-v0.6.
|
|
97
|
-
"smoke:codex-package": "python ./scripts/smoke-codex-package.py ./release/ft-kline-v0.6.
|
|
105
|
+
"pack:release": "node ./scripts/build-release-package.mjs ./release/dsh-kline-v0.6.7.tgz",
|
|
106
|
+
"pack:codex": "node ./scripts/build-codex-package.mjs ./release/ft-kline-v0.6.7.zip && node ./scripts/verify-codex-package.mjs ./release/ft-kline-v0.6.7.zip",
|
|
107
|
+
"smoke:codex-package": "python ./scripts/smoke-codex-package.py ./release/ft-kline-v0.6.7.zip",
|
|
98
108
|
"generate:client-view": "node ./scripts/generate-client-view.mjs",
|
|
99
109
|
"build:sidebar": "pnpm generate:client-view && tsc -p tsconfig.json && tsdown --config tsdown.config.ts && pnpm verify:package",
|
|
100
110
|
"verify:package": "node ./scripts/verify-package.mjs",
|
|
@@ -107,7 +117,9 @@
|
|
|
107
117
|
"generate:codex-catalog": "python scripts/generate-codex-catalog.py",
|
|
108
118
|
"verify:codex-catalog": "python scripts/generate-codex-catalog.py --check",
|
|
109
119
|
"sync:codex-marketplace": "node scripts/sync-codex-marketplace.mjs",
|
|
110
|
-
"verify:codex-marketplace": "node scripts/sync-codex-marketplace.mjs --check"
|
|
120
|
+
"verify:codex-marketplace": "node scripts/sync-codex-marketplace.mjs --check",
|
|
121
|
+
"generate:dsh-catalog": "python scripts/generate-dsh-catalog.py",
|
|
122
|
+
"verify:dsh-catalog": "python scripts/generate-dsh-catalog.py --check"
|
|
111
123
|
},
|
|
112
124
|
"devDependencies": {
|
|
113
125
|
"@deepseek-ai/dsh": "0.1.5-rc.2",
|
|
@@ -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
|
+
}
|
|
@@ -11,6 +11,9 @@ import { fileURLToPath } from 'node:url'
|
|
|
11
11
|
const PROJECT_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)))
|
|
12
12
|
const REQUIREMENTS_FILE = join(PROJECT_ROOT, 'requirements.txt')
|
|
13
13
|
const IMPORT_CHECK = 'import ftshare, mcp, pydantic, pydantic_settings, talib; assert talib.__version__ == "0.8.2" and len(talib.get_functions()) == 201'
|
|
14
|
+
// Native dependency imports can be cold on macOS. Node already owns the MCP
|
|
15
|
+
// handshake, so a short probe timeout must not trigger needless reinstallation.
|
|
16
|
+
const IMPORT_PROBE_TIMEOUT_MS = 90_000
|
|
14
17
|
const VERSION_CHECK = 'import sys; raise SystemExit(sys.version_info < (3, 11))'
|
|
15
18
|
const RUNTIME_VERSION_CHECK = 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")'
|
|
16
19
|
const REQUIREMENTS_STAMP = '.dsh-kline-requirements'
|
|
@@ -209,12 +212,12 @@ export function pythonEnvironment(env = process.env) {
|
|
|
209
212
|
}
|
|
210
213
|
}
|
|
211
214
|
|
|
212
|
-
function commandPasses(command, args, code) {
|
|
215
|
+
function commandPasses(command, args, code, timeoutMs = 10_000) {
|
|
213
216
|
const result = spawnSync(command, [...args, '-c', code], {
|
|
214
217
|
env: pythonEnvironment(),
|
|
215
218
|
encoding: 'utf8',
|
|
216
219
|
stdio: 'ignore',
|
|
217
|
-
timeout:
|
|
220
|
+
timeout: timeoutMs,
|
|
218
221
|
windowsHide: true,
|
|
219
222
|
})
|
|
220
223
|
return result.status === 0
|
|
@@ -548,6 +551,14 @@ async function launchServer(runtimePython, runtimeDirectory) {
|
|
|
548
551
|
export async function main(argv = process.argv.slice(2)) {
|
|
549
552
|
const prepareProject = argv.includes('--prepare-project')
|
|
550
553
|
const bootstrapRuntime = argv.includes('--bootstrap-runtime')
|
|
554
|
+
// The host must never spend its reconnect budget waiting for pip. A stable
|
|
555
|
+
// Node endpoint owns discovery while this same launcher prepares Python.
|
|
556
|
+
if (!prepareProject && !bootstrapRuntime && process.env.DSH_KLINE_DEFER_BOOTSTRAP === '1'
|
|
557
|
+
&& process.env.DSH_KLINE_RUNTIME_MODE !== 'external' && process.env.FT_KLINE_SERVER_ENTRY !== 'codex_server.py') {
|
|
558
|
+
const { serve } = await import('./dsh-bootstrap.mjs')
|
|
559
|
+
serve({ args: [fileURLToPath(import.meta.url)] })
|
|
560
|
+
return 0
|
|
561
|
+
}
|
|
551
562
|
const stateDirectory = defaultStateDirectory()
|
|
552
563
|
const runtimeDirectory = defaultRuntimeDirectory()
|
|
553
564
|
const configuredVenv = String(process.env.DSH_KLINE_VENV || '').trim()
|
|
@@ -566,7 +577,7 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
566
577
|
if (!commandPasses(configuredPython, [], VERSION_CHECK)) {
|
|
567
578
|
throw new Error('External DSH_KLINE_PYTHON must be a working Python 3.11 or newer; automatic installation is disabled')
|
|
568
579
|
}
|
|
569
|
-
if (!commandPasses(configuredPython, [], IMPORT_CHECK)) {
|
|
580
|
+
if (!commandPasses(configuredPython, [], IMPORT_CHECK, IMPORT_PROBE_TIMEOUT_MS)) {
|
|
570
581
|
throw new Error('External DSH_KLINE_PYTHON is missing required dependencies; the host must provision them, automatic installation is disabled')
|
|
571
582
|
}
|
|
572
583
|
return await launchServer(configuredPython, runtimeDirectory)
|
|
@@ -577,14 +588,14 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
577
588
|
const hasProjectRuntime = await pathExists(projectPython)
|
|
578
589
|
const configuredPythonWorks = !prepareProject && !configuredVenv && Boolean(configuredPython)
|
|
579
590
|
&& commandPasses(configuredPython, [], VERSION_CHECK)
|
|
580
|
-
&& commandPasses(configuredPython, [], importCheck)
|
|
591
|
+
&& commandPasses(configuredPython, [], importCheck, IMPORT_PROBE_TIMEOUT_MS)
|
|
581
592
|
const venvDirectory = prepareProject
|
|
582
593
|
? projectVenv
|
|
583
594
|
: configuredVenv || (hasProjectRuntime ? projectVenv : join(stateDirectory, 'venv'))
|
|
584
595
|
const managedRuntime = !configuredPythonWorks && (prepareProject || Boolean(configuredVenv) || !hasProjectRuntime)
|
|
585
596
|
let runtimePython = configuredPythonWorks ? configuredPython : pythonPathForVenv(venvDirectory)
|
|
586
597
|
const fingerprint = await requirementsFingerprint()
|
|
587
|
-
const runtimeImportsWork = await pathExists(runtimePython) && commandPasses(runtimePython, [], importCheck)
|
|
598
|
+
const runtimeImportsWork = configuredPythonWorks || await pathExists(runtimePython) && commandPasses(runtimePython, [], importCheck, IMPORT_PROBE_TIMEOUT_MS)
|
|
588
599
|
const runtimeVenvMatches = configuredPythonWorks || !runtimeImportsWork
|
|
589
600
|
? true
|
|
590
601
|
: await venvInterpreterMatches(venvDirectory, runtimePython)
|
|
@@ -610,12 +621,6 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
610
621
|
}
|
|
611
622
|
await rm(join(venvDirectory, BOOTSTRAP_FAILURE), { force: true }).catch(() => {})
|
|
612
623
|
}
|
|
613
|
-
const deferredBootstrap = String(process.env.DSH_KLINE_DEFER_BOOTSTRAP || '').trim() === '1'
|
|
614
|
-
if (deferredBootstrap && !prepareProject && !bootstrapRuntime) {
|
|
615
|
-
const started = await startBackgroundBootstrap(venvDirectory)
|
|
616
|
-
const state = started ? 'started' : 'is already running'
|
|
617
|
-
throw new Error(`Python runtime preparation ${state}. The MCP connection will retry automatically.`)
|
|
618
|
-
}
|
|
619
624
|
const logPath = join(stateDirectory, 'bootstrap.log')
|
|
620
625
|
process.stderr.write(`[dsh_kline] Preparing Python runtime: ${reason}.\n`)
|
|
621
626
|
process.stderr.write(`[dsh_kline] Installation details: ${logPath}\n`)
|
|
@@ -915,6 +915,8 @@ async def analyze_kline(
|
|
|
915
915
|
)
|
|
916
916
|
chart_payload["adjust"] = effective_adjust
|
|
917
917
|
chart_payload["interval_value"] = interval_value
|
|
918
|
+
provider_metadata = {key: fetched[key] for key in ("source_url", "notice", "volume_unit", "volume_adjustment", "price_adjustment", "timestamp_convention", "history_complete", "history_start", "history_end", "coverage_reason", "source_symbol", "requested_count") if key in fetched}
|
|
919
|
+
chart_payload.update(provider_metadata)
|
|
918
920
|
chart = _chart_spec(rows, active_indicators, periods, normalized_interval or "day", analysis_marks)
|
|
919
921
|
chart_session: str | None = None
|
|
920
922
|
chart_service_status: dict[str, Any]
|
|
@@ -931,6 +933,7 @@ async def analyze_kline(
|
|
|
931
933
|
data = {
|
|
932
934
|
"ok": True,
|
|
933
935
|
"workflow": "fetch_analyze_chart_session",
|
|
936
|
+
**provider_metadata,
|
|
934
937
|
"symbol": fetched.get("symbol") or resolved_symbol or symbol,
|
|
935
938
|
"name": fetched.get("name") or resolved_name or symbol,
|
|
936
939
|
"interval": normalized_interval or "day",
|