@ftshare-lab/dsh-kline 0.0.0-stage → 0.6.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +611 -0
- package/LICENSE +21 -0
- package/PROVENANCE.md +13 -0
- package/README.en.md +171 -0
- package/README.md +170 -2
- package/chart_service.py +687 -0
- package/config/basic-symbols.json +570 -0
- package/config/dsh-kline.patch.yml +4 -0
- package/config/dsh-tool-catalog.json +3875 -0
- package/cordis.patch.yml +33 -0
- package/core/__init__.py +0 -0
- package/core/adjustment.py +16 -0
- package/core/calc.py +691 -0
- package/core/rows.py +228 -0
- package/core/ta_engine.py +99 -0
- package/docs/anonymous-market-support.md +33 -0
- package/docs/automatic-drawing.md +24 -0
- package/docs/chart-functions.md +136 -0
- package/docs/drawing-examples.en.md +13 -0
- package/docs/drawing-examples.md +13 -0
- package/docs/embedding.md +77 -0
- package/docs/fixtures/price-pattern-real-v1.json +1 -0
- package/docs/free-foreign-daily.md +44 -0
- package/docs/guide.en.md +232 -0
- package/docs/guide.md +248 -0
- package/docs/images/abc-drawing-v0.5.0.jpg +0 -0
- package/docs/images/channel-drawing-v0.5.0.jpg +0 -0
- package/docs/images/drawing-workbench-v0.5.0.jpg +0 -0
- package/docs/images/dsh-kline-tab-workspace.png +0 -0
- package/docs/images/dsh-market.png +0 -0
- package/docs/images/kline-news.png +0 -0
- package/docs/images/kline-range-stats.png +0 -0
- package/docs/images/kline-support.png +0 -0
- package/docs/images/main-chart-comparison-v0.6.9.png +0 -0
- package/docs/images/market-overview-v0.6.9.png +0 -0
- package/docs/images/natural-language-abc-wolong-2026-10-27.png +0 -0
- package/docs/images/natural-language-descending-channel-wolong-2026-10-27.png +0 -0
- package/docs/images/platform-breakout-msft-v0.6.9.png +0 -0
- package/docs/npm-release.md +33 -0
- package/docs/price-pattern-rules-v1.md +40 -0
- package/docs/price-pattern-samples-v1.md +42 -0
- package/docs/provider-adaptation.md +73 -0
- package/docs/release-acceptance-v0.4.0.md +46 -0
- package/docs/release-acceptance-v0.4.1.md +43 -0
- package/docs/release-acceptance-v0.5.0.md +40 -0
- package/docs/release-acceptance-v0.6.0.md +33 -0
- package/docs/release-acceptance-v0.6.1.md +19 -0
- package/docs/release-acceptance-v0.6.10.md +21 -0
- package/docs/release-acceptance-v0.6.11.md +21 -0
- package/docs/release-acceptance-v0.6.2.md +31 -0
- package/docs/release-acceptance-v0.6.3.md +25 -0
- package/docs/release-acceptance-v0.6.4.md +24 -0
- package/docs/release-acceptance-v0.6.5.md +21 -0
- package/docs/release-acceptance-v0.6.6.md +21 -0
- package/docs/release-acceptance-v0.6.7.md +18 -0
- package/docs/release-acceptance-v0.6.8.md +18 -0
- package/docs/release-acceptance-v0.6.9.md +98 -0
- package/docs/release-notes-v0.5.0.md +23 -0
- package/docs/release-notes-v0.6.0.md +11 -0
- package/docs/release-notes-v0.6.1.md +20 -0
- package/docs/release-notes-v0.6.10.md +11 -0
- package/docs/release-notes-v0.6.11.md +16 -0
- package/docs/release-notes-v0.6.2.md +14 -0
- package/docs/release-notes-v0.6.3.md +26 -0
- package/docs/release-notes-v0.6.4.md +12 -0
- package/docs/release-notes-v0.6.5.md +13 -0
- package/docs/release-notes-v0.6.6.md +13 -0
- package/docs/release-notes-v0.6.7.md +17 -0
- package/docs/release-notes-v0.6.8.md +10 -0
- package/docs/release-notes-v0.6.9.md +16 -0
- package/lib/candle-sequence.js +15 -0
- package/lib/chart-adjustment.js +7 -0
- package/lib/chart-annotations.js +33 -0
- package/lib/chart-applications.js +171 -0
- package/lib/chart-context.js +164 -0
- package/lib/chart-observation.js +251 -0
- package/lib/chart-service-status.js +82 -0
- package/lib/chart-source-status.js +39 -0
- package/lib/chart-sources.js +354 -0
- package/lib/client/BetterSidebarTab.js +70 -0
- package/lib/client/ClassicShell.js +254 -0
- package/lib/client/KlineContent.js +155 -0
- package/lib/client/PanelHost.js +46 -0
- package/lib/client/chart-apply.js +73 -0
- package/lib/client/chart-context.js +233 -0
- package/lib/client/chart-handoff.js +34 -0
- package/lib/client/chart-session-resolver.js +74 -0
- package/lib/client/client-context.js +1 -0
- package/lib/client/conversation.js +88 -0
- package/lib/client/default-tab.js +83 -0
- package/lib/client/embed.js +50 -0
- package/lib/client/generated-view.js +12983 -0
- package/lib/client/horizontal-lines.js +19 -0
- package/lib/client/host-options.js +41 -0
- package/lib/client/host-panels.js +111 -0
- package/lib/client/index.js +77 -0
- package/lib/client/mode-preferences.js +48 -0
- package/lib/client/native-sidebar-contract.js +45 -0
- package/lib/client/native-sidebar-register.js +133 -0
- package/lib/client/native-sidebar-services.js +1 -0
- package/lib/client/native-sidebar.js +98 -0
- package/lib/client/sidebar-integration.js +93 -0
- package/lib/client/ui-onboarding.js +48 -0
- package/lib/client/version.js +14 -0
- package/lib/client.js +17581 -0
- package/lib/client.js.map +1 -0
- package/lib/drawing-feedback.js +284 -0
- package/lib/fibonacci.js +18 -0
- package/lib/ftshare-settings-bridge.js +159 -0
- package/lib/index.js +279 -0
- package/lib/labeled-polyline.js +17 -0
- package/lib/pattern-groups.js +91 -0
- package/lib/price-bands.js +55 -0
- package/lib/price-series.js +47 -0
- package/lib/price-sticks.js +32 -0
- package/lib/types/candle-sequence.d.ts +2 -0
- package/lib/types/chart-adjustment.d.ts +2 -0
- package/lib/types/chart-annotations.d.ts +4 -0
- package/lib/types/chart-applications.d.ts +26 -0
- package/lib/types/chart-context.d.ts +14 -0
- package/lib/types/chart-observation.d.ts +8 -0
- package/lib/types/chart-service-status.d.ts +22 -0
- package/lib/types/chart-source-status.d.ts +47 -0
- package/lib/types/chart-sources.d.ts +25 -0
- package/lib/types/client/BetterSidebarTab.d.ts +12 -0
- package/lib/types/client/ClassicShell.d.ts +4 -0
- package/lib/types/client/KlineContent.d.ts +37 -0
- package/lib/types/client/PanelHost.d.ts +25 -0
- package/lib/types/client/chart-apply.d.ts +13 -0
- package/lib/types/client/chart-context.d.ts +23 -0
- package/lib/types/client/chart-handoff.d.ts +5 -0
- package/lib/types/client/chart-session-resolver.d.ts +2 -0
- package/lib/types/client/client-context.d.ts +16 -0
- package/lib/types/client/conversation.d.ts +43 -0
- package/lib/types/client/default-tab.d.ts +3 -0
- package/lib/types/client/embed.d.ts +37 -0
- package/lib/types/client/generated-view.d.ts +2 -0
- package/lib/types/client/horizontal-lines.d.ts +1 -0
- package/lib/types/client/host-options.d.ts +38 -0
- package/lib/types/client/host-panels.d.ts +55 -0
- package/lib/types/client/index.d.ts +4 -0
- package/lib/types/client/mode-preferences.d.ts +25 -0
- package/lib/types/client/native-sidebar-contract.d.ts +52 -0
- package/lib/types/client/native-sidebar-register.d.ts +46 -0
- package/lib/types/client/native-sidebar-services.d.ts +45 -0
- package/lib/types/client/native-sidebar.d.ts +47 -0
- package/lib/types/client/sidebar-integration.d.ts +12 -0
- package/lib/types/client/ui-onboarding.d.ts +7 -0
- package/lib/types/client/version.d.ts +1 -0
- package/lib/types/drawing-feedback.d.ts +5 -0
- package/lib/types/fibonacci.d.ts +5 -0
- package/lib/types/ftshare-settings-bridge.d.ts +50 -0
- package/lib/types/index.d.ts +26 -0
- package/lib/types/labeled-polyline.d.ts +11 -0
- package/lib/types/pattern-groups.d.ts +2 -0
- package/lib/types/price-bands.d.ts +3 -0
- package/lib/types/price-series.d.ts +5 -0
- package/lib/types/price-sticks.d.ts +3 -0
- package/package.json +155 -4
- package/requirements.txt +6 -0
- package/screenshots.json +8 -0
- package/scripts/bootstrap.sh +5 -0
- package/scripts/dsh-bootstrap.mjs +179 -0
- package/scripts/dsh-mcp-plugin.mjs +27 -0
- package/scripts/run-dsh-kline.mjs +658 -0
- package/scripts/run-dsh-kline.sh +5 -0
- package/server.py +1755 -0
- package/tools/__init__.py +0 -0
- package/tools/annotations.py +119 -0
- package/tools/automatic_analysis.py +158 -0
- package/tools/baostock_source.py +176 -0
- package/tools/calc.py +39 -0
- package/tools/channel_candidates.py +260 -0
- package/tools/channel_preview.py +82 -0
- package/tools/channels.py +104 -0
- package/tools/chart_applications.py +204 -0
- package/tools/chart_context.py +186 -0
- package/tools/chart_edits.py +363 -0
- package/tools/chart_functions.py +451 -0
- package/tools/chart_indicators.py +65 -0
- package/tools/chart_measurements.py +84 -0
- package/tools/chart_source_status.py +32 -0
- package/tools/chart_sources.py +31 -0
- package/tools/closed_daily.py +68 -0
- package/tools/draw.py +410 -0
- package/tools/drawing_feedback.py +45 -0
- package/tools/drawing_interaction.py +117 -0
- package/tools/drawing_verification.py +141 -0
- package/tools/fetch.py +4680 -0
- package/tools/fibonacci.py +83 -0
- package/tools/foreign_daily.py +185 -0
- package/tools/free_sources.py +483 -0
- package/tools/lines.py +91 -0
- package/tools/nine_count.py +66 -0
- package/tools/pattern_groups.py +103 -0
- package/tools/pivots.py +60 -0
- package/tools/polylines.py +131 -0
- package/tools/price_bands.py +165 -0
- package/tools/price_patterns.py +311 -0
- package/tools/price_series.py +162 -0
- package/tools/price_sticks.py +114 -0
- package/tools/range_candidates.py +170 -0
- package/tools/recent_drawing_candidates.py +123 -0
- package/tools/rectangles.py +76 -0
- package/tools/regression_channels.py +87 -0
- package/tools/ta_functions.py +228 -0
- package/tools/trend_lines.py +106 -0
- package/tools/watchlist.py +149 -0
- package/view/ft-logo.jpg +0 -0
- package/view/kline.html +12436 -0
- package/view/vendor/klinecharts.min.js +7 -0
|
@@ -0,0 +1,658 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { createHash } from 'node:crypto'
|
|
4
|
+
import { spawn, spawnSync } from 'node:child_process'
|
|
5
|
+
import { createWriteStream } from 'node:fs'
|
|
6
|
+
import { access, appendFile, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
7
|
+
import { homedir } from 'node:os'
|
|
8
|
+
import { delimiter, dirname, join, posix, resolve, win32 } from 'node:path'
|
|
9
|
+
import { fileURLToPath } from 'node:url'
|
|
10
|
+
|
|
11
|
+
const PROJECT_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)))
|
|
12
|
+
const REQUIREMENTS_FILE = join(PROJECT_ROOT, 'requirements.txt')
|
|
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
|
|
17
|
+
const VERSION_CHECK = 'import sys; raise SystemExit(sys.version_info < (3, 11))'
|
|
18
|
+
const RUNTIME_VERSION_CHECK = 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")'
|
|
19
|
+
const REQUIREMENTS_STAMP = '.dsh-kline-requirements'
|
|
20
|
+
const BOOTSTRAP_FAILURE = '.dsh-kline-bootstrap-failed'
|
|
21
|
+
const BOOTSTRAP_RUNNING = '.dsh-kline-bootstrap-running'
|
|
22
|
+
const BACKGROUND_BOOTSTRAP_STALE_MS = 10 * 60 * 1000
|
|
23
|
+
// A failed download or a temporarily unavailable index must not turn into a
|
|
24
|
+
// permanent startup failure. Keep reconnect storms from repeatedly invoking
|
|
25
|
+
// pip, but let a later launch repair the environment by itself.
|
|
26
|
+
const BOOTSTRAP_FAILURE_RETRY_MS = 5 * 60 * 1000
|
|
27
|
+
|
|
28
|
+
function runtimeError(code, message) {
|
|
29
|
+
return Object.assign(new Error(message), { code })
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function pythonProbeOutcome(candidate, result, platform = process.platform, resolvedCommand = candidate.command) {
|
|
33
|
+
const version = String(result.stdout || '').trim()
|
|
34
|
+
if (result.status === 0 && /^\d+\.\d+$/.test(version)) {
|
|
35
|
+
const [major, minor] = version.split('.').map(Number)
|
|
36
|
+
return { code: major > 3 || major === 3 && minor >= 11 ? 'PYTHON_READY' : 'PYTHON_VERSION_TOO_OLD', version }
|
|
37
|
+
}
|
|
38
|
+
// A working Store-installed interpreter is accepted above. Only a failed
|
|
39
|
+
// redirector probe is classified as a Store placeholder.
|
|
40
|
+
if (platform === 'win32' && (/\\Microsoft\\WindowsApps\\/i.test(resolvedCommand)
|
|
41
|
+
|| /Microsoft Store|App execution aliases/i.test(String(result.stderr || '') + String(result.stdout || '')))) {
|
|
42
|
+
return { code: 'PYTHON_STORE_ALIAS' }
|
|
43
|
+
}
|
|
44
|
+
return { code: result.error?.code === 'ENOENT' ? 'PYTHON_NOT_FOUND' : 'PYTHON_EXECUTION_FAILED' }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function resolvedPythonCommand(candidate) {
|
|
48
|
+
if (/[\\/]/.test(candidate.command)) return candidate.command
|
|
49
|
+
for (const directory of (process.env.PATH || '').split(delimiter).filter(Boolean)) {
|
|
50
|
+
const path = join(directory, candidate.command + (process.platform === 'win32' ? '.exe' : ''))
|
|
51
|
+
try { await stat(path); return path } catch {}
|
|
52
|
+
}
|
|
53
|
+
return candidate.command
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function bootstrapStep(code, label, command, args, logPath) {
|
|
57
|
+
try { return await runLogged(command, args, logPath) }
|
|
58
|
+
catch (error) { throw runtimeError(code, `${label}. ${error instanceof Error ? error.message : String(error)}`) }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function dependencyImportCheck() {
|
|
62
|
+
const requirements = await readFile(REQUIREMENTS_FILE, 'utf8')
|
|
63
|
+
const pins = {}
|
|
64
|
+
for (const line of requirements.split(/\r?\n/)) {
|
|
65
|
+
const pinned = line.match(/^([\w.-]+)==([^\s;]+)\s*$/)
|
|
66
|
+
const tagged = line.match(/^([\w.-]+)\s+@\s+https:\/\/github\.com\/[^\s]+\/refs\/tags\/v([\d.]+)\.tar\.gz\s*$/)
|
|
67
|
+
if (pinned || tagged) { const [, name, version] = pinned || tagged; pins[name] = version }
|
|
68
|
+
}
|
|
69
|
+
return `${IMPORT_CHECK}; from importlib.metadata import version as installed_version; assert all(installed_version(name) == expected for name, expected in ${JSON.stringify(pins)}.items()), "Pinned runtime dependency mismatch"`
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function desktopPythonCandidates(executable = process.execPath, platform = process.platform) {
|
|
73
|
+
// Signed macOS app runtimes may forbid loading third-party native wheels.
|
|
74
|
+
// Do not silently select that private runtime over a standard Python.
|
|
75
|
+
if (platform !== 'win32') return []
|
|
76
|
+
const python = win32.join(win32.dirname(executable), 'resources', 'runtime', 'primary-runtime', 'dependencies', 'python')
|
|
77
|
+
return [win32.join(python, 'python.exe'), win32.join(python, 'bin', 'python.exe')]
|
|
78
|
+
.map(command => ({ command, args: [] }))
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function venvBaseCandidates(config, platform = process.platform) {
|
|
82
|
+
const paths = platform === 'win32' ? win32 : posix
|
|
83
|
+
const home = config.match(/^\s*home\s*=\s*(.+?)\s*$/mi)?.[1]
|
|
84
|
+
const executable = config.match(/^\s*executable\s*=\s*(.+?)\s*$/mi)?.[1]
|
|
85
|
+
return [executable, ...(home ? [paths.join(home, platform === 'win32' ? 'python.exe' : 'python3')] : [])]
|
|
86
|
+
.filter(path => path && paths.isAbsolute(path)).map(command => ({ command, args: [] }))
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function bootstrapCandidates(venvDirectory, preferred = '') {
|
|
90
|
+
// An explicit interpreter is authoritative; do not fall back to another one.
|
|
91
|
+
if (String(process.env.DSH_KLINE_PYTHON || '').trim()) return pythonCandidates()
|
|
92
|
+
let config = ''
|
|
93
|
+
try { config = await readFile(join(venvDirectory, 'pyvenv.cfg'), 'utf8') } catch {}
|
|
94
|
+
return [...(preferred ? [{ command: preferred, args: [] }] : []),
|
|
95
|
+
...venvBaseCandidates(config), ...desktopPythonCandidates(), ...pythonCandidates()]
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export async function bootstrapEnvironmentFingerprint(venvDirectory) {
|
|
99
|
+
const candidates = [{ command: pythonPathForVenv(venvDirectory), args: [] },
|
|
100
|
+
...await bootstrapCandidates(venvDirectory)]
|
|
101
|
+
const observations = []
|
|
102
|
+
for (const candidate of candidates) {
|
|
103
|
+
const locations = /[\\/]/.test(candidate.command) ? [candidate.command]
|
|
104
|
+
: (process.env.PATH || '').split(delimiter).filter(Boolean).flatMap(directory => {
|
|
105
|
+
const path = join(directory, candidate.command)
|
|
106
|
+
return process.platform === 'win32' ? [path, path + '.exe'] : [path]
|
|
107
|
+
})
|
|
108
|
+
for (const location of locations) {
|
|
109
|
+
try { const file = await stat(location); observations.push([location, file.size, file.mtimeMs, file.mode]) } catch {}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
let config = ''
|
|
113
|
+
try { config = await readFile(join(venvDirectory, 'pyvenv.cfg'), 'utf8') } catch {}
|
|
114
|
+
return createHash('sha256').update(JSON.stringify({ candidates, observations, config,
|
|
115
|
+
platform: process.platform,
|
|
116
|
+
python: process.env.DSH_KLINE_PYTHON || '', path: process.env.PATH || '',
|
|
117
|
+
pythonHome: process.env.PYTHONHOME || '', pythonPath: process.env.PYTHONPATH || '' })).digest('hex')
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function pythonPathForVenv(venvDirectory, platform = process.platform) {
|
|
121
|
+
const paths = platform === 'win32' ? win32 : posix
|
|
122
|
+
return platform === 'win32'
|
|
123
|
+
? paths.join(venvDirectory, 'Scripts', 'python.exe')
|
|
124
|
+
: paths.join(venvDirectory, 'bin', 'python')
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function defaultStateDirectory(env = process.env, platform = process.platform, userHome = homedir()) {
|
|
128
|
+
const paths = platform === 'win32' ? win32 : posix
|
|
129
|
+
const codexServer = String(env.FT_KLINE_SERVER_ENTRY || '').trim() === 'codex_server.py'
|
|
130
|
+
const codexExplicit = String(env.FT_KLINE_CACHE_DIR || '').trim()
|
|
131
|
+
if (codexServer && codexExplicit) return paths.resolve(codexExplicit)
|
|
132
|
+
const explicit = String(env.DSH_KLINE_CACHE_DIR || '').trim()
|
|
133
|
+
if (explicit) return paths.resolve(explicit)
|
|
134
|
+
if (platform === 'win32') {
|
|
135
|
+
const local = String(env.LOCALAPPDATA || env.APPDATA || '').trim()
|
|
136
|
+
return paths.join(local || paths.join(userHome, 'AppData', 'Local'), codexServer ? 'ft-kline' : 'dsh_kline')
|
|
137
|
+
}
|
|
138
|
+
const cache = String(env.XDG_CACHE_HOME || '').trim()
|
|
139
|
+
return paths.join(cache || paths.join(userHome, '.cache'), codexServer ? 'ft-kline' : 'dsh_kline')
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function defaultRuntimeDirectory(env = process.env, platform = process.platform, userHome = homedir()) {
|
|
143
|
+
const paths = platform === 'win32' ? win32 : posix
|
|
144
|
+
const codexServer = String(env.FT_KLINE_SERVER_ENTRY || '').trim() === 'codex_server.py'
|
|
145
|
+
const codexExplicit = String(env.FT_KLINE_RUNTIME_DIR || '').trim()
|
|
146
|
+
if (codexServer && codexExplicit) return paths.resolve(codexExplicit)
|
|
147
|
+
const explicit = String(env.DSH_KLINE_RUNTIME_DIR || '').trim()
|
|
148
|
+
return explicit ? paths.resolve(explicit) : paths.join(defaultStateDirectory(env, platform, userHome), 'runtime')
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Credential file the DSH host publishes from its FTShare settings service.
|
|
153
|
+
*
|
|
154
|
+
* Mirrors `settingsCredentialFile()` in `src/ftshare-settings-bridge.ts`; the
|
|
155
|
+
* host_process_id keeps a file from an earlier DSH run from being reused.
|
|
156
|
+
*/
|
|
157
|
+
export function settingsCredentialFile(runtimeDirectory, hostPid) {
|
|
158
|
+
return join(runtimeDirectory, 'credentials', `ftshare-${hostPid}.json`)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Point the MCP server at the host's settings credential when this process was
|
|
163
|
+
* launched by a DSH host that could publish one. Without that locator the
|
|
164
|
+
* server keeps its previous credential resolution untouched.
|
|
165
|
+
*/
|
|
166
|
+
export function settingsCredentialEnvironment(runtimeDirectory, env = process.env) {
|
|
167
|
+
const rawPid = String(env.DSH_KLINE_HOST_PID || '').trim()
|
|
168
|
+
if (!/^[1-9]\d*$/.test(rawPid)) return {}
|
|
169
|
+
const hostPid = Number(rawPid)
|
|
170
|
+
if (!Number.isSafeInteger(hostPid) || hostPid <= 0) return {}
|
|
171
|
+
return { DSH_KLINE_SETTINGS_KEY_FILE: settingsCredentialFile(runtimeDirectory, hostPid) }
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function pythonCandidates(env = process.env, platform = process.platform) {
|
|
175
|
+
const explicit = String(env.DSH_KLINE_PYTHON || '').trim()
|
|
176
|
+
if (explicit) return [{ command: explicit, args: [] }]
|
|
177
|
+
if (platform === 'win32') {
|
|
178
|
+
const installed = ['313', '312', '311'].flatMap(version => [
|
|
179
|
+
...(env.LOCALAPPDATA ? [win32.join(env.LOCALAPPDATA, 'Programs', 'Python', `Python${version}`, 'python.exe')] : []),
|
|
180
|
+
...(env.ProgramFiles ? [win32.join(env.ProgramFiles, `Python${version}`, 'python.exe')] : []),
|
|
181
|
+
])
|
|
182
|
+
return [
|
|
183
|
+
...['3.13', '3.12', '3.11'].map(version => ({ command: 'py', args: [`-${version}`] })),
|
|
184
|
+
...installed.map(command => ({ command, args: [] })),
|
|
185
|
+
{ command: 'python', args: [] },
|
|
186
|
+
{ command: 'python3', args: [] },
|
|
187
|
+
]
|
|
188
|
+
}
|
|
189
|
+
return [
|
|
190
|
+
'python3.13', 'python3.12', 'python3.11',
|
|
191
|
+
'/opt/homebrew/bin/python3.13', '/opt/homebrew/bin/python3.12',
|
|
192
|
+
'/opt/homebrew/bin/python3.11',
|
|
193
|
+
'/usr/local/bin/python3.13', '/usr/local/bin/python3.12',
|
|
194
|
+
'/usr/local/bin/python3.11',
|
|
195
|
+
'python3', '/opt/homebrew/bin/python3', '/usr/local/bin/python3',
|
|
196
|
+
join(homedir(), 'miniforge3', 'bin', 'python'),
|
|
197
|
+
join(homedir(), 'Caskroom', 'miniforge', 'base', 'bin', 'python3'),
|
|
198
|
+
'/opt/homebrew/Caskroom/miniforge/base/bin/python3',
|
|
199
|
+
join(homedir(), 'miniconda3', 'bin', 'python'),
|
|
200
|
+
join(homedir(), 'anaconda3', 'bin', 'python'),
|
|
201
|
+
].map(command => ({ command, args: [] }))
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function pythonEnvironment(env = process.env) {
|
|
205
|
+
return {
|
|
206
|
+
...env,
|
|
207
|
+
PYTHONUTF8: '1',
|
|
208
|
+
PYTHONIOENCODING: 'utf-8',
|
|
209
|
+
PIP_PROGRESS_BAR: 'off',
|
|
210
|
+
PIP_DISABLE_PIP_VERSION_CHECK: '1',
|
|
211
|
+
PIP_NO_INPUT: '1',
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function commandPasses(command, args, code, timeoutMs = 10_000) {
|
|
216
|
+
const result = spawnSync(command, [...args, '-c', code], {
|
|
217
|
+
env: pythonEnvironment(),
|
|
218
|
+
encoding: 'utf8',
|
|
219
|
+
stdio: 'ignore',
|
|
220
|
+
timeout: timeoutMs,
|
|
221
|
+
windowsHide: true,
|
|
222
|
+
})
|
|
223
|
+
return result.status === 0
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function commandOutput(command, args, code) {
|
|
227
|
+
const result = spawnSync(command, [...args, '-c', code], {
|
|
228
|
+
env: pythonEnvironment(),
|
|
229
|
+
encoding: 'utf8',
|
|
230
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
231
|
+
timeout: 10_000,
|
|
232
|
+
windowsHide: true,
|
|
233
|
+
})
|
|
234
|
+
return result.status === 0 ? result.stdout.trim() : ''
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
async function pathExists(path) {
|
|
238
|
+
try {
|
|
239
|
+
await access(path)
|
|
240
|
+
return true
|
|
241
|
+
} catch {
|
|
242
|
+
return false
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async function requirementsFingerprint() {
|
|
247
|
+
return createHash('sha256').update(await readFile(REQUIREMENTS_FILE)).digest('hex')
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async function stampMatches(venvDirectory, fingerprint) {
|
|
251
|
+
try {
|
|
252
|
+
return (await readFile(join(venvDirectory, REQUIREMENTS_STAMP), 'utf8')).trim() === fingerprint
|
|
253
|
+
} catch {
|
|
254
|
+
return false
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async function writeStamp(venvDirectory, fingerprint) {
|
|
259
|
+
const destination = join(venvDirectory, REQUIREMENTS_STAMP)
|
|
260
|
+
const temporary = `${destination}.${process.pid}.tmp`
|
|
261
|
+
await writeFile(temporary, `${fingerprint}\n`, { encoding: 'utf8', mode: 0o600 })
|
|
262
|
+
try {
|
|
263
|
+
await replaceWithRetry(temporary, destination)
|
|
264
|
+
} finally {
|
|
265
|
+
await rm(temporary, { force: true })
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async function venvInterpreterMatches(venvDirectory, runtimePython) {
|
|
270
|
+
const runtimeVersion = commandOutput(runtimePython, [], RUNTIME_VERSION_CHECK)
|
|
271
|
+
if (!/^\d+\.\d+$/.test(runtimeVersion)) return false
|
|
272
|
+
try {
|
|
273
|
+
const config = await readFile(join(venvDirectory, 'pyvenv.cfg'), 'utf8')
|
|
274
|
+
const match = config.match(/^\s*version\s*=\s*(\d+\.\d+)(?:\.\d+)?\s*$/mi)
|
|
275
|
+
return match?.[1] === runtimeVersion
|
|
276
|
+
} catch {
|
|
277
|
+
return false
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
async function replaceWithRetry(source, destination) {
|
|
282
|
+
const attempts = process.platform === 'win32' ? 6 : 1
|
|
283
|
+
let lastError
|
|
284
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
285
|
+
try {
|
|
286
|
+
await rename(source, destination)
|
|
287
|
+
return
|
|
288
|
+
} catch (error) {
|
|
289
|
+
lastError = error
|
|
290
|
+
if (process.platform !== 'win32' || !['EACCES', 'EPERM', 'EEXIST'].includes(error?.code) || attempt + 1 === attempts) break
|
|
291
|
+
await rm(destination, { force: true }).catch(() => {})
|
|
292
|
+
await new Promise(resolveDelay => setTimeout(resolveDelay, 40 * (attempt + 1)))
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
throw lastError
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
export function backgroundBootstrapSpawnOptions(platform = process.platform, env = process.env) {
|
|
299
|
+
return {
|
|
300
|
+
cwd: PROJECT_ROOT,
|
|
301
|
+
env,
|
|
302
|
+
// The bootstrap must outlive the short-lived MCP handshake process on
|
|
303
|
+
// every host. On Windows, `unref()` alone does not detach a child from
|
|
304
|
+
// the parent's process group/job, so the child can be reaped as soon as
|
|
305
|
+
// the initial MCP attempt exits.
|
|
306
|
+
detached: true,
|
|
307
|
+
stdio: 'ignore',
|
|
308
|
+
windowsHide: platform === 'win32',
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
async function findBootstrapPython(venvDirectory, logPath, preferred = '') {
|
|
313
|
+
const candidates = await bootstrapCandidates(venvDirectory, preferred)
|
|
314
|
+
const seen = new Set()
|
|
315
|
+
const outcomes = new Set()
|
|
316
|
+
for (const candidate of candidates) {
|
|
317
|
+
const key = `${candidate.command}\u0000${candidate.args.join('\u0000')}`
|
|
318
|
+
if (seen.has(key)) continue
|
|
319
|
+
seen.add(key)
|
|
320
|
+
const result = spawnSync(candidate.command, [...candidate.args, '-c', RUNTIME_VERSION_CHECK], {
|
|
321
|
+
env: pythonEnvironment(), encoding: 'utf8', timeout: 10_000, maxBuffer: 64 * 1024, windowsHide: true,
|
|
322
|
+
})
|
|
323
|
+
const outcome = pythonProbeOutcome(candidate, result, process.platform, await resolvedPythonCommand(candidate))
|
|
324
|
+
if (outcome.code === 'PYTHON_READY' && !commandPasses(candidate.command, candidate.args, 'import venv, ensurepip')) {
|
|
325
|
+
outcome.code = 'PYTHON_VENV_UNAVAILABLE'
|
|
326
|
+
}
|
|
327
|
+
// Record only paths, versions and classifications; never dump the parent
|
|
328
|
+
// environment or arbitrary output from a failed executable.
|
|
329
|
+
const diagnostic = `[dsh_kline] Python candidate: ${JSON.stringify({ command: candidate.command, args: candidate.args, ...outcome })}\n`
|
|
330
|
+
await appendFile(logPath, diagnostic, 'utf8')
|
|
331
|
+
process.stderr.write(diagnostic)
|
|
332
|
+
if (outcome.code === 'PYTHON_READY') return candidate
|
|
333
|
+
outcomes.add(outcome.code)
|
|
334
|
+
}
|
|
335
|
+
const hint = process.platform === 'win32'
|
|
336
|
+
? 'Install Python 3.11 or newer from python.org, enable the Python Launcher, or set DSH_KLINE_PYTHON.'
|
|
337
|
+
: 'Install Python 3.11 or newer, or set DSH_KLINE_PYTHON to its executable.'
|
|
338
|
+
const code = ['PYTHON_VENV_UNAVAILABLE', 'PYTHON_VERSION_TOO_OLD', 'PYTHON_STORE_ALIAS', 'PYTHON_EXECUTION_FAILED']
|
|
339
|
+
.find(code => outcomes.has(code)) || 'PYTHON_NOT_FOUND'
|
|
340
|
+
const message = {
|
|
341
|
+
PYTHON_VENV_UNAVAILABLE: 'Python was found but cannot create a virtual environment (venv/ensurepip missing).',
|
|
342
|
+
PYTHON_VERSION_TOO_OLD: 'Python was found but its version is below Python 3.11.',
|
|
343
|
+
PYTHON_STORE_ALIAS: 'Detected a Windows Store Python placeholder, not a usable interpreter. Install python.org Python or set DSH_KLINE_PYTHON to the full python.exe file path.',
|
|
344
|
+
PYTHON_EXECUTION_FAILED: 'A Python candidate could not execute or report its version.',
|
|
345
|
+
PYTHON_NOT_FOUND: 'No usable Python interpreter was found; dsh_kline requires Python 3.11 or newer.',
|
|
346
|
+
}[code]
|
|
347
|
+
throw runtimeError(code, `${message} ${hint}`)
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
async function runLogged(command, args, logPath) {
|
|
351
|
+
const startedAt = Date.now()
|
|
352
|
+
await mkdir(dirname(logPath), { recursive: true })
|
|
353
|
+
const log = createWriteStream(logPath, { flags: 'a', mode: 0o600 })
|
|
354
|
+
return await new Promise((resolveRun, rejectRun) => {
|
|
355
|
+
let settled = false
|
|
356
|
+
const child = spawn(command, args, {
|
|
357
|
+
cwd: PROJECT_ROOT,
|
|
358
|
+
env: pythonEnvironment(),
|
|
359
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
360
|
+
windowsHide: true,
|
|
361
|
+
})
|
|
362
|
+
const forward = chunk => {
|
|
363
|
+
process.stderr.write(chunk)
|
|
364
|
+
log.write(chunk)
|
|
365
|
+
}
|
|
366
|
+
child.stdout.on('data', forward)
|
|
367
|
+
child.stderr.on('data', forward)
|
|
368
|
+
child.once('error', error => {
|
|
369
|
+
if (settled) return
|
|
370
|
+
settled = true
|
|
371
|
+
log.end()
|
|
372
|
+
rejectRun(error)
|
|
373
|
+
})
|
|
374
|
+
child.once('close', code => {
|
|
375
|
+
if (settled) return
|
|
376
|
+
settled = true
|
|
377
|
+
log.end()
|
|
378
|
+
if (code === 0) resolveRun(Date.now() - startedAt)
|
|
379
|
+
else rejectRun(new Error(`${command} exited with code ${code}`))
|
|
380
|
+
})
|
|
381
|
+
})
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
async function prepareRuntime(venvDirectory, fingerprint, logPath, preferredPython = '', clearExisting = false) {
|
|
385
|
+
await mkdir(dirname(venvDirectory), { recursive: true })
|
|
386
|
+
await mkdir(dirname(logPath), { recursive: true })
|
|
387
|
+
await writeFile(logPath, '', { encoding: 'utf8', mode: 0o600 })
|
|
388
|
+
const runtimePython = pythonPathForVenv(venvDirectory)
|
|
389
|
+
const reusable = !clearExisting && await pathExists(runtimePython)
|
|
390
|
+
&& commandPasses(runtimePython, [], VERSION_CHECK) && await venvInterpreterMatches(venvDirectory, runtimePython)
|
|
391
|
+
&& (commandPasses(runtimePython, [], 'import pip') || commandPasses(runtimePython, [], 'import ensurepip'))
|
|
392
|
+
if (reusable) {
|
|
393
|
+
process.stderr.write('[dsh_kline] Reusing the existing Python environment.\n')
|
|
394
|
+
if (!commandPasses(runtimePython, [], 'import pip')) await bootstrapStep('PYTHON_VENV_UNAVAILABLE',
|
|
395
|
+
'Cannot prepare pip in the existing environment', runtimePython, ['-m', 'ensurepip', '--upgrade'], logPath)
|
|
396
|
+
} else {
|
|
397
|
+
const base = await findBootstrapPython(venvDirectory, logPath, preferredPython)
|
|
398
|
+
process.stderr.write('[dsh_kline] Creating or repairing the Python environment…\n')
|
|
399
|
+
// Python -m venv does not replace an existing interpreter when upgrading
|
|
400
|
+
// across Python versions. Clear any unusable venv before creating it again.
|
|
401
|
+
const replaceExisting = clearExisting || await pathExists(runtimePython)
|
|
402
|
+
const venvArgs = [...base.args, '-m', 'venv', ...(replaceExisting ? ['--clear'] : []), venvDirectory]
|
|
403
|
+
const venvMs = await bootstrapStep('PYTHON_VENV_UNAVAILABLE', 'Cannot create or repair the virtual environment', base.command, venvArgs, logPath)
|
|
404
|
+
process.stderr.write(`[dsh_kline] Python environment ready in ${Math.ceil(venvMs / 1000)}s.\n`)
|
|
405
|
+
}
|
|
406
|
+
process.stderr.write('[dsh_kline] Installing dependencies…\n')
|
|
407
|
+
// Isolate pip from a user's config (notably `user = true`, which makes a
|
|
408
|
+
// venv install fail before it can write the ready stamp).
|
|
409
|
+
const dependenciesMs = await bootstrapStep('PYTHON_DEPENDENCY_INSTALL_FAILED', 'Dependency installation failed',
|
|
410
|
+
runtimePython, ['-m', 'pip', '--isolated', 'install', '-r', REQUIREMENTS_FILE], logPath)
|
|
411
|
+
process.stderr.write(`[dsh_kline] Dependencies ready in ${Math.ceil(dependenciesMs / 1000)}s.\n`)
|
|
412
|
+
process.stderr.write('[dsh_kline] Verifying the runtime…\n')
|
|
413
|
+
await bootstrapStep('PYTHON_IMPORT_CHECK_FAILED', 'Installed dependency verification failed',
|
|
414
|
+
runtimePython, ['-c', await dependencyImportCheck()], logPath)
|
|
415
|
+
await writeStamp(venvDirectory, fingerprint)
|
|
416
|
+
await rm(join(venvDirectory, BOOTSTRAP_FAILURE), { force: true })
|
|
417
|
+
if (!(await stampMatches(venvDirectory, fingerprint))) {
|
|
418
|
+
throw new Error('Dependency fingerprint was not persisted; refusing to report a ready runtime.')
|
|
419
|
+
}
|
|
420
|
+
process.stderr.write('[dsh_kline] Dependency fingerprint saved.\n')
|
|
421
|
+
return runtimePython
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
async function readBootstrapFailure(venvDirectory, fingerprint, environment) {
|
|
425
|
+
try {
|
|
426
|
+
const failure = JSON.parse(await readFile(join(venvDirectory, BOOTSTRAP_FAILURE), 'utf8'))
|
|
427
|
+
return failure?.fingerprint === fingerprint && failure.environment === environment ? failure : null
|
|
428
|
+
} catch {
|
|
429
|
+
return null
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
async function writeBootstrapFailure(venvDirectory, fingerprint, error) {
|
|
434
|
+
await mkdir(venvDirectory, { recursive: true })
|
|
435
|
+
const environment = await bootstrapEnvironmentFingerprint(venvDirectory)
|
|
436
|
+
await writeFile(join(venvDirectory, BOOTSTRAP_FAILURE), JSON.stringify({ fingerprint, environment,
|
|
437
|
+
failureCode: error?.code || 'BOOTSTRAP_FAILED', at: new Date().toISOString(), error: String(error) }), { encoding: 'utf8', mode: 0o600 })
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function bootstrapFailureRetryAt(failure) {
|
|
441
|
+
const failedAt = Date.parse(String(failure?.at || ''))
|
|
442
|
+
return Number.isFinite(failedAt) ? failedAt + BOOTSTRAP_FAILURE_RETRY_MS : 0
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function processIsAlive(pid) {
|
|
446
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false
|
|
447
|
+
try {
|
|
448
|
+
process.kill(pid, 0)
|
|
449
|
+
return true
|
|
450
|
+
} catch (error) {
|
|
451
|
+
return error?.code === 'EPERM'
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
async function readBootstrapMarker(marker) {
|
|
456
|
+
try {
|
|
457
|
+
const details = JSON.parse(await readFile(marker, 'utf8'))
|
|
458
|
+
return details && typeof details === 'object' ? details : null
|
|
459
|
+
} catch {
|
|
460
|
+
return null
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
async function writeBootstrapMarker(marker, details) {
|
|
465
|
+
const temporary = `${marker}.${process.pid}.tmp`
|
|
466
|
+
await writeFile(temporary, JSON.stringify(details), { encoding: 'utf8', mode: 0o600 })
|
|
467
|
+
try {
|
|
468
|
+
await replaceWithRetry(temporary, marker)
|
|
469
|
+
} finally {
|
|
470
|
+
await rm(temporary, { force: true })
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
async function clearBootstrapMarker(venvDirectory, expectedPid = process.pid) {
|
|
475
|
+
const marker = join(venvDirectory, BOOTSTRAP_RUNNING)
|
|
476
|
+
const details = await readBootstrapMarker(marker)
|
|
477
|
+
if (details && Number(details.pid) !== expectedPid) return
|
|
478
|
+
await rm(marker, { force: true }).catch(() => {})
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
async function bootstrapIsRunning(venvDirectory) {
|
|
482
|
+
const marker = join(venvDirectory, BOOTSTRAP_RUNNING)
|
|
483
|
+
const details = await readBootstrapMarker(marker)
|
|
484
|
+
const pid = Number(details?.pid)
|
|
485
|
+
if (processIsAlive(pid)) return true
|
|
486
|
+
const startedAt = Date.parse(details?.started_at || '')
|
|
487
|
+
// Older markers did not carry a PID. Keep their short grace period for
|
|
488
|
+
// upgrade compatibility, but remove markers whose owner is definitely
|
|
489
|
+
// gone instead of blocking reconnect forever after a killed child.
|
|
490
|
+
if (!Number.isSafeInteger(pid) && Number.isFinite(startedAt) && Date.now() - startedAt < BACKGROUND_BOOTSTRAP_STALE_MS) return true
|
|
491
|
+
await rm(marker, { force: true }).catch(() => {})
|
|
492
|
+
return false
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
async function startBackgroundBootstrap(venvDirectory) {
|
|
496
|
+
if (await bootstrapIsRunning(venvDirectory)) return false
|
|
497
|
+
await mkdir(venvDirectory, { recursive: true })
|
|
498
|
+
const marker = join(venvDirectory, BOOTSTRAP_RUNNING)
|
|
499
|
+
const startedAt = new Date().toISOString()
|
|
500
|
+
try {
|
|
501
|
+
// Reserve the marker before spawning so concurrent reconnect attempts do
|
|
502
|
+
// not launch duplicate dependency installers.
|
|
503
|
+
await writeFile(marker, JSON.stringify({ pid: process.pid, started_at: startedAt }), {
|
|
504
|
+
encoding: 'utf8', mode: 0o600, flag: 'wx',
|
|
505
|
+
})
|
|
506
|
+
} catch (error) {
|
|
507
|
+
if (error?.code === 'EEXIST') return false
|
|
508
|
+
throw error
|
|
509
|
+
}
|
|
510
|
+
let child
|
|
511
|
+
try {
|
|
512
|
+
child = spawn(process.execPath, [fileURLToPath(import.meta.url), '--bootstrap-runtime'], backgroundBootstrapSpawnOptions())
|
|
513
|
+
child.once('error', () => { void clearBootstrapMarker(venvDirectory, child?.pid || process.pid) })
|
|
514
|
+
child.once('exit', () => { void clearBootstrapMarker(venvDirectory, child?.pid || process.pid) })
|
|
515
|
+
await writeBootstrapMarker(marker, { pid: child.pid, started_at: startedAt })
|
|
516
|
+
child.unref()
|
|
517
|
+
return true
|
|
518
|
+
} catch (error) {
|
|
519
|
+
if (child && child.exitCode === null) child.kill()
|
|
520
|
+
await clearBootstrapMarker(venvDirectory, child?.pid || process.pid)
|
|
521
|
+
throw error
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
async function launchServer(runtimePython, runtimeDirectory) {
|
|
526
|
+
await mkdir(runtimeDirectory, { recursive: true })
|
|
527
|
+
const serverEntry = String(process.env.FT_KLINE_SERVER_ENTRY || '').trim() || 'server.py'
|
|
528
|
+
if (!['server.py', 'codex_server.py'].includes(serverEntry)) throw new Error('FT_KLINE_SERVER_ENTRY must be server.py or codex_server.py')
|
|
529
|
+
const child = spawn(runtimePython, [join(PROJECT_ROOT, serverEntry)], {
|
|
530
|
+
cwd: PROJECT_ROOT,
|
|
531
|
+
env: pythonEnvironment({
|
|
532
|
+
...process.env,
|
|
533
|
+
DSH_KLINE_RUNTIME_DIR: runtimeDirectory,
|
|
534
|
+
...(serverEntry === 'server.py' ? settingsCredentialEnvironment(runtimeDirectory) : {}),
|
|
535
|
+
}),
|
|
536
|
+
stdio: 'inherit',
|
|
537
|
+
windowsHide: true,
|
|
538
|
+
})
|
|
539
|
+
const forwardSignal = () => {
|
|
540
|
+
if (child.exitCode === null && child.signalCode === null) child.kill()
|
|
541
|
+
}
|
|
542
|
+
process.once('SIGINT', forwardSignal)
|
|
543
|
+
process.once('SIGTERM', forwardSignal)
|
|
544
|
+
const result = await new Promise((resolveExit, rejectExit) => {
|
|
545
|
+
child.once('error', rejectExit)
|
|
546
|
+
child.once('exit', (code, signal) => resolveExit({ code, signal }))
|
|
547
|
+
})
|
|
548
|
+
process.removeListener('SIGINT', forwardSignal)
|
|
549
|
+
process.removeListener('SIGTERM', forwardSignal)
|
|
550
|
+
if (result.signal) return 1
|
|
551
|
+
return result.code ?? 1
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
export async function main(argv = process.argv.slice(2)) {
|
|
555
|
+
const prepareProject = argv.includes('--prepare-project')
|
|
556
|
+
const bootstrapRuntime = argv.includes('--bootstrap-runtime')
|
|
557
|
+
// The host must never spend its reconnect budget waiting for pip. A stable
|
|
558
|
+
// Node endpoint owns discovery while this same launcher prepares Python.
|
|
559
|
+
if (!prepareProject && !bootstrapRuntime && process.env.DSH_KLINE_DEFER_BOOTSTRAP === '1'
|
|
560
|
+
&& process.env.DSH_KLINE_RUNTIME_MODE !== 'external' && process.env.FT_KLINE_SERVER_ENTRY !== 'codex_server.py') {
|
|
561
|
+
const { serve } = await import('./dsh-bootstrap.mjs')
|
|
562
|
+
serve({ args: [fileURLToPath(import.meta.url)] })
|
|
563
|
+
return 0
|
|
564
|
+
}
|
|
565
|
+
const stateDirectory = defaultStateDirectory()
|
|
566
|
+
const runtimeDirectory = defaultRuntimeDirectory()
|
|
567
|
+
const configuredVenv = String(process.env.DSH_KLINE_VENV || '').trim()
|
|
568
|
+
const configuredPython = String(process.env.DSH_KLINE_PYTHON || '').trim()
|
|
569
|
+
const runtimeMode = String(process.env.DSH_KLINE_RUNTIME_MODE || '').trim() || 'auto'
|
|
570
|
+
if (!['auto', 'external'].includes(runtimeMode)) {
|
|
571
|
+
throw new Error('DSH_KLINE_RUNTIME_MODE must be auto or external')
|
|
572
|
+
}
|
|
573
|
+
if (runtimeMode === 'external') {
|
|
574
|
+
if (configuredVenv || prepareProject || bootstrapRuntime) {
|
|
575
|
+
throw new Error('External runtime cannot be combined with DSH_KLINE_VENV, --prepare-project or --bootstrap-runtime')
|
|
576
|
+
}
|
|
577
|
+
if (!configuredPython) {
|
|
578
|
+
throw new Error('External runtime requires DSH_KLINE_PYTHON')
|
|
579
|
+
}
|
|
580
|
+
if (!commandPasses(configuredPython, [], VERSION_CHECK)) {
|
|
581
|
+
throw new Error('External DSH_KLINE_PYTHON must be a working Python 3.11 or newer; automatic installation is disabled')
|
|
582
|
+
}
|
|
583
|
+
if (!commandPasses(configuredPython, [], IMPORT_CHECK, IMPORT_PROBE_TIMEOUT_MS)) {
|
|
584
|
+
throw new Error('External DSH_KLINE_PYTHON is missing required dependencies; the host must provision them, automatic installation is disabled')
|
|
585
|
+
}
|
|
586
|
+
return await launchServer(configuredPython, runtimeDirectory)
|
|
587
|
+
}
|
|
588
|
+
const importCheck = await dependencyImportCheck()
|
|
589
|
+
const projectVenv = join(PROJECT_ROOT, '.venv')
|
|
590
|
+
const projectPython = pythonPathForVenv(projectVenv)
|
|
591
|
+
const hasProjectRuntime = await pathExists(projectPython)
|
|
592
|
+
const configuredPythonWorks = !prepareProject && !configuredVenv && Boolean(configuredPython)
|
|
593
|
+
&& commandPasses(configuredPython, [], VERSION_CHECK)
|
|
594
|
+
&& commandPasses(configuredPython, [], importCheck, IMPORT_PROBE_TIMEOUT_MS)
|
|
595
|
+
const venvDirectory = prepareProject
|
|
596
|
+
? projectVenv
|
|
597
|
+
: configuredVenv || (hasProjectRuntime ? projectVenv : join(stateDirectory, 'venv'))
|
|
598
|
+
const managedRuntime = !configuredPythonWorks && (prepareProject || Boolean(configuredVenv) || !hasProjectRuntime)
|
|
599
|
+
let runtimePython = configuredPythonWorks ? configuredPython : pythonPathForVenv(venvDirectory)
|
|
600
|
+
const fingerprint = await requirementsFingerprint()
|
|
601
|
+
const runtimeImportsWork = configuredPythonWorks || await pathExists(runtimePython) && commandPasses(runtimePython, [], importCheck, IMPORT_PROBE_TIMEOUT_MS)
|
|
602
|
+
const runtimeVenvMatches = configuredPythonWorks || !runtimeImportsWork
|
|
603
|
+
? true
|
|
604
|
+
: await venvInterpreterMatches(venvDirectory, runtimePython)
|
|
605
|
+
const runtimeWorks = runtimeImportsWork && runtimeVenvMatches
|
|
606
|
+
const previousFailure = managedRuntime ? await readBootstrapFailure(venvDirectory, fingerprint,
|
|
607
|
+
await bootstrapEnvironmentFingerprint(venvDirectory)) : null
|
|
608
|
+
let requirementsMatch = !managedRuntime || await stampMatches(venvDirectory, fingerprint)
|
|
609
|
+
let reason = ''
|
|
610
|
+
if (!runtimeWorks) reason = runtimeImportsWork
|
|
611
|
+
? 'Python runtime interpreter metadata is inconsistent'
|
|
612
|
+
: 'Python runtime is missing or incomplete'
|
|
613
|
+
else if (!requirementsMatch) reason = 'dependency requirements changed'
|
|
614
|
+
|
|
615
|
+
if (reason) {
|
|
616
|
+
if (!managedRuntime) {
|
|
617
|
+
throw new Error('The project .venv is incomplete. Run: pnpm bootstrap')
|
|
618
|
+
}
|
|
619
|
+
if (previousFailure && !prepareProject) {
|
|
620
|
+
const logPath = join(stateDirectory, 'bootstrap.log')
|
|
621
|
+
const retryAt = bootstrapFailureRetryAt(previousFailure)
|
|
622
|
+
if (retryAt > Date.now()) {
|
|
623
|
+
throw new Error(`Python runtime preparation recently failed [${previousFailure.failureCode || 'BOOTSTRAP_FAILED'}]; automatic retry will resume after ${new Date(retryAt).toISOString()}. Run: pnpm bootstrap to retry now. See ${logPath}.`)
|
|
624
|
+
}
|
|
625
|
+
await rm(join(venvDirectory, BOOTSTRAP_FAILURE), { force: true }).catch(() => {})
|
|
626
|
+
}
|
|
627
|
+
const logPath = join(stateDirectory, 'bootstrap.log')
|
|
628
|
+
process.stderr.write(`[dsh_kline] Preparing Python runtime: ${reason}.\n`)
|
|
629
|
+
process.stderr.write(`[dsh_kline] Installation details: ${logPath}\n`)
|
|
630
|
+
try {
|
|
631
|
+
runtimePython = await prepareRuntime(
|
|
632
|
+
venvDirectory,
|
|
633
|
+
fingerprint,
|
|
634
|
+
logPath,
|
|
635
|
+
hasProjectRuntime ? projectPython : '',
|
|
636
|
+
runtimeImportsWork && !runtimeVenvMatches,
|
|
637
|
+
)
|
|
638
|
+
} catch (error) {
|
|
639
|
+
await writeBootstrapFailure(venvDirectory, fingerprint, error).catch(() => {})
|
|
640
|
+
throw runtimeError(error?.code || 'BOOTSTRAP_FAILED', `Runtime preparation failed [${error?.code || 'BOOTSTRAP_FAILED'}]. See ${logPath}. ${error instanceof Error ? error.message : String(error)}`)
|
|
641
|
+
} finally {
|
|
642
|
+
if (bootstrapRuntime) await clearBootstrapMarker(venvDirectory)
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
if (prepareProject || bootstrapRuntime) {
|
|
647
|
+
process.stderr.write(`[dsh_kline] Python runtime ready: ${venvDirectory}\n`)
|
|
648
|
+
return 0
|
|
649
|
+
}
|
|
650
|
+
return await launchServer(runtimePython, runtimeDirectory)
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
654
|
+
main().then(code => { process.exitCode = code }).catch(error => {
|
|
655
|
+
process.stderr.write(`[dsh_kline] ${error instanceof Error ? error.message : String(error)}\n`)
|
|
656
|
+
process.exitCode = 1
|
|
657
|
+
})
|
|
658
|
+
}
|