@dsh-ft/dsh-fft-paper-trading 0.6.0 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/README.zh.md +4 -4
- package/lib/agent/format.d.ts.map +1 -1
- package/lib/agent/format.js +4 -0
- package/lib/agent/format.js.map +1 -1
- package/lib/agent/tools.d.ts.map +1 -1
- package/lib/agent/tools.js +5 -3
- package/lib/agent/tools.js.map +1 -1
- package/lib/client.js +76 -13
- package/lib/contract.d.ts.map +1 -1
- package/lib/contract.js +3 -1
- package/lib/contract.js.map +1 -1
- package/lib/core/risk.d.ts.map +1 -1
- package/lib/core/risk.js +10 -2
- package/lib/core/risk.js.map +1 -1
- package/lib/core/views.js +2 -2
- package/lib/core/views.js.map +1 -1
- package/lib/data/ftshare-trading-calendar.d.ts +47 -12
- package/lib/data/ftshare-trading-calendar.d.ts.map +1 -1
- package/lib/data/ftshare-trading-calendar.js +156 -44
- package/lib/data/ftshare-trading-calendar.js.map +1 -1
- package/lib/service/paper-service.d.ts +1 -1
- package/lib/service/paper-service.d.ts.map +1 -1
- package/lib/service/paper-service.js +24 -12
- package/lib/service/paper-service.js.map +1 -1
- package/lib/service/rpc.d.ts.map +1 -1
- package/lib/service/rpc.js +12 -1
- package/lib/service/rpc.js.map +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +98 -0
- package/node_modules/@ftshare-lab/dsh-kline/README.en.md +116 -26
- package/node_modules/@ftshare-lab/dsh-kline/README.md +125 -25
- package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +38 -0
- package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +3 -9
- package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +63 -269
- package/node_modules/@ftshare-lab/dsh-kline/core/rows.py +15 -3
- package/node_modules/@ftshare-lab/dsh-kline/core/ta_engine.py +99 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/candle-sequence.js +15 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-annotations.js +33 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +12 -3
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +91 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +64 -13
- package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +3356 -787
- package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +96 -19
- package/node_modules/@ftshare-lab/dsh-kline/lib/fibonacci.js +18 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +19 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/labeled-polyline.js +17 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-bands.js +55 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-series.js +47 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-sticks.js +32 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/candle-sequence.d.ts +2 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-annotations.d.ts +4 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-context.d.ts +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-observation.d.ts +2 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/BetterSidebarTab.d.ts +3 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ClassicShell.d.ts +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-context.d.ts +1 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/client-context.d.ts +14 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +11 -3
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/embed.d.ts +2 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-services.d.ts +0 -36
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/index.d.ts +2 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-contract.d.ts +35 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-register.d.ts +46 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-services.d.ts +45 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar.d.ts +21 -36
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/fibonacci.d.ts +5 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/labeled-polyline.d.ts +11 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-bands.d.ts +3 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-series.d.ts +5 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-sticks.d.ts +3 -0
- package/node_modules/@ftshare-lab/dsh-kline/package.json +27 -5
- package/node_modules/@ftshare-lab/dsh-kline/requirements.txt +2 -0
- package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-mcp-plugin.mjs +27 -0
- package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +180 -49
- package/node_modules/@ftshare-lab/dsh-kline/server.py +300 -34
- package/node_modules/@ftshare-lab/dsh-kline/tools/annotations.py +119 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/baostock_source.py +176 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +260 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_applications.py +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +22 -3
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +141 -16
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +466 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +63 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +3 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +13 -7
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_interaction.py +117 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_verification.py +58 -3
- package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +164 -40
- package/node_modules/@ftshare-lab/dsh-kline/tools/fibonacci.py +83 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/free_sources.py +78 -21
- package/node_modules/@ftshare-lab/dsh-kline/tools/pivots.py +60 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +125 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_bands.py +165 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_series.py +162 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_sticks.py +114 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +170 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/regression_channels.py +87 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/ta_functions.py +228 -0
- package/package.json +3 -3
- package/src/agent/format.ts +3 -0
- package/src/agent/tools.ts +5 -3
- package/src/client/index.js +75 -12
- package/src/contract.ts +3 -1
- package/src/core/risk.ts +10 -2
- package/src/core/views.ts +2 -2
- package/src/data/ftshare-trading-calendar.ts +184 -45
- package/src/service/paper-service.ts +22 -19
- package/src/service/rpc.ts +12 -1
|
@@ -3,15 +3,15 @@
|
|
|
3
3
|
import { createHash } from 'node:crypto'
|
|
4
4
|
import { spawn, spawnSync } from 'node:child_process'
|
|
5
5
|
import { createWriteStream } from 'node:fs'
|
|
6
|
-
import { access, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
|
|
6
|
+
import { access, appendFile, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
7
7
|
import { homedir } from 'node:os'
|
|
8
|
-
import { dirname, join, posix, resolve, win32 } from 'node:path'
|
|
8
|
+
import { delimiter, dirname, join, posix, resolve, win32 } from 'node:path'
|
|
9
9
|
import { fileURLToPath } from 'node:url'
|
|
10
10
|
|
|
11
11
|
const PROJECT_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)))
|
|
12
12
|
const REQUIREMENTS_FILE = join(PROJECT_ROOT, 'requirements.txt')
|
|
13
|
-
const IMPORT_CHECK = 'import ftshare, mcp, pydantic, pydantic_settings'
|
|
14
|
-
const VERSION_CHECK = 'import sys; raise SystemExit(sys.version_info < (3,
|
|
13
|
+
const IMPORT_CHECK = 'import ftshare, mcp, pydantic, pydantic_settings, talib; assert talib.__version__ == "0.8.2" and len(talib.get_functions()) == 201'
|
|
14
|
+
const VERSION_CHECK = 'import sys; raise SystemExit(sys.version_info < (3, 11))'
|
|
15
15
|
const RUNTIME_VERSION_CHECK = 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")'
|
|
16
16
|
const REQUIREMENTS_STAMP = '.dsh-kline-requirements'
|
|
17
17
|
const BOOTSTRAP_FAILURE = '.dsh-kline-bootstrap-failed'
|
|
@@ -22,6 +22,98 @@ const BACKGROUND_BOOTSTRAP_STALE_MS = 10 * 60 * 1000
|
|
|
22
22
|
// pip, but let a later launch repair the environment by itself.
|
|
23
23
|
const BOOTSTRAP_FAILURE_RETRY_MS = 5 * 60 * 1000
|
|
24
24
|
|
|
25
|
+
function runtimeError(code, message) {
|
|
26
|
+
return Object.assign(new Error(message), { code })
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function pythonProbeOutcome(candidate, result, platform = process.platform, resolvedCommand = candidate.command) {
|
|
30
|
+
const version = String(result.stdout || '').trim()
|
|
31
|
+
if (result.status === 0 && /^\d+\.\d+$/.test(version)) {
|
|
32
|
+
const [major, minor] = version.split('.').map(Number)
|
|
33
|
+
return { code: major > 3 || major === 3 && minor >= 11 ? 'PYTHON_READY' : 'PYTHON_VERSION_TOO_OLD', version }
|
|
34
|
+
}
|
|
35
|
+
// A working Store-installed interpreter is accepted above. Only a failed
|
|
36
|
+
// redirector probe is classified as a Store placeholder.
|
|
37
|
+
if (platform === 'win32' && (/\\Microsoft\\WindowsApps\\/i.test(resolvedCommand)
|
|
38
|
+
|| /Microsoft Store|App execution aliases/i.test(String(result.stderr || '') + String(result.stdout || '')))) {
|
|
39
|
+
return { code: 'PYTHON_STORE_ALIAS' }
|
|
40
|
+
}
|
|
41
|
+
return { code: result.error?.code === 'ENOENT' ? 'PYTHON_NOT_FOUND' : 'PYTHON_EXECUTION_FAILED' }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function resolvedPythonCommand(candidate) {
|
|
45
|
+
if (/[\\/]/.test(candidate.command)) return candidate.command
|
|
46
|
+
for (const directory of (process.env.PATH || '').split(delimiter).filter(Boolean)) {
|
|
47
|
+
const path = join(directory, candidate.command + (process.platform === 'win32' ? '.exe' : ''))
|
|
48
|
+
try { await stat(path); return path } catch {}
|
|
49
|
+
}
|
|
50
|
+
return candidate.command
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function bootstrapStep(code, label, command, args, logPath) {
|
|
54
|
+
try { return await runLogged(command, args, logPath) }
|
|
55
|
+
catch (error) { throw runtimeError(code, `${label}. ${error instanceof Error ? error.message : String(error)}`) }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function dependencyImportCheck() {
|
|
59
|
+
const requirements = await readFile(REQUIREMENTS_FILE, 'utf8')
|
|
60
|
+
const pins = {}
|
|
61
|
+
for (const line of requirements.split(/\r?\n/)) {
|
|
62
|
+
const pinned = line.match(/^([\w.-]+)==([^\s;]+)\s*$/)
|
|
63
|
+
const tagged = line.match(/^([\w.-]+)\s+@\s+https:\/\/github\.com\/[^\s]+\/refs\/tags\/v([\d.]+)\.tar\.gz\s*$/)
|
|
64
|
+
if (pinned || tagged) { const [, name, version] = pinned || tagged; pins[name] = version }
|
|
65
|
+
}
|
|
66
|
+
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"`
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function desktopPythonCandidates(executable = process.execPath, platform = process.platform) {
|
|
70
|
+
// Signed macOS app runtimes may forbid loading third-party native wheels.
|
|
71
|
+
// Do not silently select that private runtime over a standard Python.
|
|
72
|
+
if (platform !== 'win32') return []
|
|
73
|
+
const python = win32.join(win32.dirname(executable), 'resources', 'runtime', 'primary-runtime', 'dependencies', 'python')
|
|
74
|
+
return [win32.join(python, 'python.exe'), win32.join(python, 'bin', 'python.exe')]
|
|
75
|
+
.map(command => ({ command, args: [] }))
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function venvBaseCandidates(config, platform = process.platform) {
|
|
79
|
+
const paths = platform === 'win32' ? win32 : posix
|
|
80
|
+
const home = config.match(/^\s*home\s*=\s*(.+?)\s*$/mi)?.[1]
|
|
81
|
+
const executable = config.match(/^\s*executable\s*=\s*(.+?)\s*$/mi)?.[1]
|
|
82
|
+
return [executable, ...(home ? [paths.join(home, platform === 'win32' ? 'python.exe' : 'python3')] : [])]
|
|
83
|
+
.filter(path => path && paths.isAbsolute(path)).map(command => ({ command, args: [] }))
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function bootstrapCandidates(venvDirectory, preferred = '') {
|
|
87
|
+
// An explicit interpreter is authoritative; do not fall back to another one.
|
|
88
|
+
if (String(process.env.DSH_KLINE_PYTHON || '').trim()) return pythonCandidates()
|
|
89
|
+
let config = ''
|
|
90
|
+
try { config = await readFile(join(venvDirectory, 'pyvenv.cfg'), 'utf8') } catch {}
|
|
91
|
+
return [...(preferred ? [{ command: preferred, args: [] }] : []),
|
|
92
|
+
...venvBaseCandidates(config), ...desktopPythonCandidates(), ...pythonCandidates()]
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function bootstrapEnvironmentFingerprint(venvDirectory) {
|
|
96
|
+
const candidates = [{ command: pythonPathForVenv(venvDirectory), args: [] },
|
|
97
|
+
...await bootstrapCandidates(venvDirectory)]
|
|
98
|
+
const observations = []
|
|
99
|
+
for (const candidate of candidates) {
|
|
100
|
+
const locations = /[\\/]/.test(candidate.command) ? [candidate.command]
|
|
101
|
+
: (process.env.PATH || '').split(delimiter).filter(Boolean).flatMap(directory => {
|
|
102
|
+
const path = join(directory, candidate.command)
|
|
103
|
+
return process.platform === 'win32' ? [path, path + '.exe'] : [path]
|
|
104
|
+
})
|
|
105
|
+
for (const location of locations) {
|
|
106
|
+
try { const file = await stat(location); observations.push([location, file.size, file.mtimeMs, file.mode]) } catch {}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
let config = ''
|
|
110
|
+
try { config = await readFile(join(venvDirectory, 'pyvenv.cfg'), 'utf8') } catch {}
|
|
111
|
+
return createHash('sha256').update(JSON.stringify({ candidates, observations, config,
|
|
112
|
+
platform: process.platform,
|
|
113
|
+
python: process.env.DSH_KLINE_PYTHON || '', path: process.env.PATH || '',
|
|
114
|
+
pythonHome: process.env.PYTHONHOME || '', pythonPath: process.env.PYTHONPATH || '' })).digest('hex')
|
|
115
|
+
}
|
|
116
|
+
|
|
25
117
|
export function pythonPathForVenv(venvDirectory, platform = process.platform) {
|
|
26
118
|
const paths = platform === 'win32' ? win32 : posix
|
|
27
119
|
return platform === 'win32'
|
|
@@ -31,18 +123,24 @@ export function pythonPathForVenv(venvDirectory, platform = process.platform) {
|
|
|
31
123
|
|
|
32
124
|
export function defaultStateDirectory(env = process.env, platform = process.platform, userHome = homedir()) {
|
|
33
125
|
const paths = platform === 'win32' ? win32 : posix
|
|
126
|
+
const codexServer = String(env.FT_KLINE_SERVER_ENTRY || '').trim() === 'codex_server.py'
|
|
127
|
+
const codexExplicit = String(env.FT_KLINE_CACHE_DIR || '').trim()
|
|
128
|
+
if (codexServer && codexExplicit) return paths.resolve(codexExplicit)
|
|
34
129
|
const explicit = String(env.DSH_KLINE_CACHE_DIR || '').trim()
|
|
35
130
|
if (explicit) return paths.resolve(explicit)
|
|
36
131
|
if (platform === 'win32') {
|
|
37
132
|
const local = String(env.LOCALAPPDATA || env.APPDATA || '').trim()
|
|
38
|
-
return paths.join(local || paths.join(userHome, 'AppData', 'Local'), 'dsh_kline')
|
|
133
|
+
return paths.join(local || paths.join(userHome, 'AppData', 'Local'), codexServer ? 'ft-kline' : 'dsh_kline')
|
|
39
134
|
}
|
|
40
135
|
const cache = String(env.XDG_CACHE_HOME || '').trim()
|
|
41
|
-
return paths.join(cache || paths.join(userHome, '.cache'), 'dsh_kline')
|
|
136
|
+
return paths.join(cache || paths.join(userHome, '.cache'), codexServer ? 'ft-kline' : 'dsh_kline')
|
|
42
137
|
}
|
|
43
138
|
|
|
44
139
|
export function defaultRuntimeDirectory(env = process.env, platform = process.platform, userHome = homedir()) {
|
|
45
140
|
const paths = platform === 'win32' ? win32 : posix
|
|
141
|
+
const codexServer = String(env.FT_KLINE_SERVER_ENTRY || '').trim() === 'codex_server.py'
|
|
142
|
+
const codexExplicit = String(env.FT_KLINE_RUNTIME_DIR || '').trim()
|
|
143
|
+
if (codexServer && codexExplicit) return paths.resolve(codexExplicit)
|
|
46
144
|
const explicit = String(env.DSH_KLINE_RUNTIME_DIR || '').trim()
|
|
47
145
|
return explicit ? paths.resolve(explicit) : paths.join(defaultStateDirectory(env, platform, userHome), 'runtime')
|
|
48
146
|
}
|
|
@@ -74,18 +172,24 @@ export function pythonCandidates(env = process.env, platform = process.platform)
|
|
|
74
172
|
const explicit = String(env.DSH_KLINE_PYTHON || '').trim()
|
|
75
173
|
if (explicit) return [{ command: explicit, args: [] }]
|
|
76
174
|
if (platform === 'win32') {
|
|
175
|
+
const installed = ['313', '312', '311'].flatMap(version => [
|
|
176
|
+
...(env.LOCALAPPDATA ? [win32.join(env.LOCALAPPDATA, 'Programs', 'Python', `Python${version}`, 'python.exe')] : []),
|
|
177
|
+
...(env.ProgramFiles ? [win32.join(env.ProgramFiles, `Python${version}`, 'python.exe')] : []),
|
|
178
|
+
])
|
|
77
179
|
return [
|
|
78
|
-
...['3.13', '3.12', '3.11'
|
|
180
|
+
...['3.13', '3.12', '3.11'].map(version => ({ command: 'py', args: [`-${version}`] })),
|
|
181
|
+
...installed.map(command => ({ command, args: [] })),
|
|
79
182
|
{ command: 'python', args: [] },
|
|
80
183
|
{ command: 'python3', args: [] },
|
|
81
184
|
]
|
|
82
185
|
}
|
|
83
186
|
return [
|
|
84
|
-
'python3
|
|
85
|
-
'/opt/homebrew/bin/python3
|
|
86
|
-
'/opt/homebrew/bin/python3.11',
|
|
87
|
-
'/usr/local/bin/python3
|
|
88
|
-
'/usr/local/bin/python3.11',
|
|
187
|
+
'python3.13', 'python3.12', 'python3.11',
|
|
188
|
+
'/opt/homebrew/bin/python3.13', '/opt/homebrew/bin/python3.12',
|
|
189
|
+
'/opt/homebrew/bin/python3.11',
|
|
190
|
+
'/usr/local/bin/python3.13', '/usr/local/bin/python3.12',
|
|
191
|
+
'/usr/local/bin/python3.11',
|
|
192
|
+
'python3', '/opt/homebrew/bin/python3', '/usr/local/bin/python3',
|
|
89
193
|
join(homedir(), 'miniforge3', 'bin', 'python'),
|
|
90
194
|
join(homedir(), 'Caskroom', 'miniforge', 'base', 'bin', 'python3'),
|
|
91
195
|
'/opt/homebrew/Caskroom/miniforge/base/bin/python3',
|
|
@@ -202,21 +306,42 @@ export function backgroundBootstrapSpawnOptions(platform = process.platform, env
|
|
|
202
306
|
}
|
|
203
307
|
}
|
|
204
308
|
|
|
205
|
-
function findBootstrapPython(preferred = '') {
|
|
206
|
-
const candidates = preferred
|
|
207
|
-
? [{ command: preferred, args: [] }, ...pythonCandidates()]
|
|
208
|
-
: pythonCandidates()
|
|
309
|
+
async function findBootstrapPython(venvDirectory, logPath, preferred = '') {
|
|
310
|
+
const candidates = await bootstrapCandidates(venvDirectory, preferred)
|
|
209
311
|
const seen = new Set()
|
|
312
|
+
const outcomes = new Set()
|
|
210
313
|
for (const candidate of candidates) {
|
|
211
314
|
const key = `${candidate.command}\u0000${candidate.args.join('\u0000')}`
|
|
212
315
|
if (seen.has(key)) continue
|
|
213
316
|
seen.add(key)
|
|
214
|
-
|
|
317
|
+
const result = spawnSync(candidate.command, [...candidate.args, '-c', RUNTIME_VERSION_CHECK], {
|
|
318
|
+
env: pythonEnvironment(), encoding: 'utf8', timeout: 10_000, maxBuffer: 64 * 1024, windowsHide: true,
|
|
319
|
+
})
|
|
320
|
+
const outcome = pythonProbeOutcome(candidate, result, process.platform, await resolvedPythonCommand(candidate))
|
|
321
|
+
if (outcome.code === 'PYTHON_READY' && !commandPasses(candidate.command, candidate.args, 'import venv, ensurepip')) {
|
|
322
|
+
outcome.code = 'PYTHON_VENV_UNAVAILABLE'
|
|
323
|
+
}
|
|
324
|
+
// Record only paths, versions and classifications; never dump the parent
|
|
325
|
+
// environment or arbitrary output from a failed executable.
|
|
326
|
+
const diagnostic = `[dsh_kline] Python candidate: ${JSON.stringify({ command: candidate.command, args: candidate.args, ...outcome })}\n`
|
|
327
|
+
await appendFile(logPath, diagnostic, 'utf8')
|
|
328
|
+
process.stderr.write(diagnostic)
|
|
329
|
+
if (outcome.code === 'PYTHON_READY') return candidate
|
|
330
|
+
outcomes.add(outcome.code)
|
|
215
331
|
}
|
|
216
332
|
const hint = process.platform === 'win32'
|
|
217
|
-
? 'Install Python 3.
|
|
218
|
-
: 'Install Python 3.
|
|
219
|
-
|
|
333
|
+
? 'Install Python 3.11 or newer from python.org, enable the Python Launcher, or set DSH_KLINE_PYTHON.'
|
|
334
|
+
: 'Install Python 3.11 or newer, or set DSH_KLINE_PYTHON to its executable.'
|
|
335
|
+
const code = ['PYTHON_VENV_UNAVAILABLE', 'PYTHON_VERSION_TOO_OLD', 'PYTHON_STORE_ALIAS', 'PYTHON_EXECUTION_FAILED']
|
|
336
|
+
.find(code => outcomes.has(code)) || 'PYTHON_NOT_FOUND'
|
|
337
|
+
const message = {
|
|
338
|
+
PYTHON_VENV_UNAVAILABLE: 'Python was found but cannot create a virtual environment (venv/ensurepip missing).',
|
|
339
|
+
PYTHON_VERSION_TOO_OLD: 'Python was found but its version is below Python 3.11.',
|
|
340
|
+
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.',
|
|
341
|
+
PYTHON_EXECUTION_FAILED: 'A Python candidate could not execute or report its version.',
|
|
342
|
+
PYTHON_NOT_FOUND: 'No usable Python interpreter was found; dsh_kline requires Python 3.11 or newer.',
|
|
343
|
+
}[code]
|
|
344
|
+
throw runtimeError(code, `${message} ${hint}`)
|
|
220
345
|
}
|
|
221
346
|
|
|
222
347
|
async function runLogged(command, args, logPath) {
|
|
@@ -254,22 +379,33 @@ async function runLogged(command, args, logPath) {
|
|
|
254
379
|
}
|
|
255
380
|
|
|
256
381
|
async function prepareRuntime(venvDirectory, fingerprint, logPath, preferredPython = '', clearExisting = false) {
|
|
257
|
-
const base = findBootstrapPython(preferredPython)
|
|
258
382
|
await mkdir(dirname(venvDirectory), { recursive: true })
|
|
259
383
|
await mkdir(dirname(logPath), { recursive: true })
|
|
260
384
|
await writeFile(logPath, '', { encoding: 'utf8', mode: 0o600 })
|
|
261
|
-
process.stderr.write('[dsh_kline] Creating or repairing the Python environment…\n')
|
|
262
|
-
const venvArgs = [...base.args, '-m', 'venv', ...(clearExisting ? ['--clear'] : []), venvDirectory]
|
|
263
|
-
const venvMs = await runLogged(base.command, venvArgs, logPath)
|
|
264
|
-
process.stderr.write(`[dsh_kline] Python environment ready in ${Math.ceil(venvMs / 1000)}s.\n`)
|
|
265
385
|
const runtimePython = pythonPathForVenv(venvDirectory)
|
|
386
|
+
const reusable = !clearExisting && await pathExists(runtimePython)
|
|
387
|
+
&& commandPasses(runtimePython, [], VERSION_CHECK) && await venvInterpreterMatches(venvDirectory, runtimePython)
|
|
388
|
+
&& (commandPasses(runtimePython, [], 'import pip') || commandPasses(runtimePython, [], 'import ensurepip'))
|
|
389
|
+
if (reusable) {
|
|
390
|
+
process.stderr.write('[dsh_kline] Reusing the existing Python environment.\n')
|
|
391
|
+
if (!commandPasses(runtimePython, [], 'import pip')) await bootstrapStep('PYTHON_VENV_UNAVAILABLE',
|
|
392
|
+
'Cannot prepare pip in the existing environment', runtimePython, ['-m', 'ensurepip', '--upgrade'], logPath)
|
|
393
|
+
} else {
|
|
394
|
+
const base = await findBootstrapPython(venvDirectory, logPath, preferredPython)
|
|
395
|
+
process.stderr.write('[dsh_kline] Creating or repairing the Python environment…\n')
|
|
396
|
+
const venvArgs = [...base.args, '-m', 'venv', ...(clearExisting ? ['--clear'] : []), venvDirectory]
|
|
397
|
+
const venvMs = await bootstrapStep('PYTHON_VENV_UNAVAILABLE', 'Cannot create or repair the virtual environment', base.command, venvArgs, logPath)
|
|
398
|
+
process.stderr.write(`[dsh_kline] Python environment ready in ${Math.ceil(venvMs / 1000)}s.\n`)
|
|
399
|
+
}
|
|
266
400
|
process.stderr.write('[dsh_kline] Installing dependencies…\n')
|
|
267
401
|
// Isolate pip from a user's config (notably `user = true`, which makes a
|
|
268
402
|
// venv install fail before it can write the ready stamp).
|
|
269
|
-
const dependenciesMs = await
|
|
403
|
+
const dependenciesMs = await bootstrapStep('PYTHON_DEPENDENCY_INSTALL_FAILED', 'Dependency installation failed',
|
|
404
|
+
runtimePython, ['-m', 'pip', '--isolated', 'install', '-r', REQUIREMENTS_FILE], logPath)
|
|
270
405
|
process.stderr.write(`[dsh_kline] Dependencies ready in ${Math.ceil(dependenciesMs / 1000)}s.\n`)
|
|
271
406
|
process.stderr.write('[dsh_kline] Verifying the runtime…\n')
|
|
272
|
-
await
|
|
407
|
+
await bootstrapStep('PYTHON_IMPORT_CHECK_FAILED', 'Installed dependency verification failed',
|
|
408
|
+
runtimePython, ['-c', await dependencyImportCheck()], logPath)
|
|
273
409
|
await writeStamp(venvDirectory, fingerprint)
|
|
274
410
|
await rm(join(venvDirectory, BOOTSTRAP_FAILURE), { force: true })
|
|
275
411
|
if (!(await stampMatches(venvDirectory, fingerprint))) {
|
|
@@ -279,10 +415,10 @@ async function prepareRuntime(venvDirectory, fingerprint, logPath, preferredPyth
|
|
|
279
415
|
return runtimePython
|
|
280
416
|
}
|
|
281
417
|
|
|
282
|
-
async function readBootstrapFailure(venvDirectory, fingerprint) {
|
|
418
|
+
async function readBootstrapFailure(venvDirectory, fingerprint, environment) {
|
|
283
419
|
try {
|
|
284
420
|
const failure = JSON.parse(await readFile(join(venvDirectory, BOOTSTRAP_FAILURE), 'utf8'))
|
|
285
|
-
return failure?.fingerprint === fingerprint ? failure : null
|
|
421
|
+
return failure?.fingerprint === fingerprint && failure.environment === environment ? failure : null
|
|
286
422
|
} catch {
|
|
287
423
|
return null
|
|
288
424
|
}
|
|
@@ -290,7 +426,9 @@ async function readBootstrapFailure(venvDirectory, fingerprint) {
|
|
|
290
426
|
|
|
291
427
|
async function writeBootstrapFailure(venvDirectory, fingerprint, error) {
|
|
292
428
|
await mkdir(venvDirectory, { recursive: true })
|
|
293
|
-
|
|
429
|
+
const environment = await bootstrapEnvironmentFingerprint(venvDirectory)
|
|
430
|
+
await writeFile(join(venvDirectory, BOOTSTRAP_FAILURE), JSON.stringify({ fingerprint, environment,
|
|
431
|
+
failureCode: error?.code || 'BOOTSTRAP_FAILED', at: new Date().toISOString(), error: String(error) }), { encoding: 'utf8', mode: 0o600 })
|
|
294
432
|
}
|
|
295
433
|
|
|
296
434
|
function bootstrapFailureRetryAt(failure) {
|
|
@@ -380,12 +518,14 @@ async function startBackgroundBootstrap(venvDirectory) {
|
|
|
380
518
|
|
|
381
519
|
async function launchServer(runtimePython, runtimeDirectory) {
|
|
382
520
|
await mkdir(runtimeDirectory, { recursive: true })
|
|
383
|
-
const
|
|
521
|
+
const serverEntry = String(process.env.FT_KLINE_SERVER_ENTRY || '').trim() || 'server.py'
|
|
522
|
+
if (!['server.py', 'codex_server.py'].includes(serverEntry)) throw new Error('FT_KLINE_SERVER_ENTRY must be server.py or codex_server.py')
|
|
523
|
+
const child = spawn(runtimePython, [join(PROJECT_ROOT, serverEntry)], {
|
|
384
524
|
cwd: PROJECT_ROOT,
|
|
385
525
|
env: pythonEnvironment({
|
|
386
526
|
...process.env,
|
|
387
527
|
DSH_KLINE_RUNTIME_DIR: runtimeDirectory,
|
|
388
|
-
...settingsCredentialEnvironment(runtimeDirectory),
|
|
528
|
+
...(serverEntry === 'server.py' ? settingsCredentialEnvironment(runtimeDirectory) : {}),
|
|
389
529
|
}),
|
|
390
530
|
stdio: 'inherit',
|
|
391
531
|
windowsHide: true,
|
|
@@ -424,43 +564,34 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
424
564
|
throw new Error('External runtime requires DSH_KLINE_PYTHON')
|
|
425
565
|
}
|
|
426
566
|
if (!commandPasses(configuredPython, [], VERSION_CHECK)) {
|
|
427
|
-
throw new Error('External DSH_KLINE_PYTHON must be a working Python 3.
|
|
567
|
+
throw new Error('External DSH_KLINE_PYTHON must be a working Python 3.11 or newer; automatic installation is disabled')
|
|
428
568
|
}
|
|
429
569
|
if (!commandPasses(configuredPython, [], IMPORT_CHECK)) {
|
|
430
570
|
throw new Error('External DSH_KLINE_PYTHON is missing required dependencies; the host must provision them, automatic installation is disabled')
|
|
431
571
|
}
|
|
432
572
|
return await launchServer(configuredPython, runtimeDirectory)
|
|
433
573
|
}
|
|
574
|
+
const importCheck = await dependencyImportCheck()
|
|
434
575
|
const projectVenv = join(PROJECT_ROOT, '.venv')
|
|
435
576
|
const projectPython = pythonPathForVenv(projectVenv)
|
|
436
577
|
const hasProjectRuntime = await pathExists(projectPython)
|
|
437
578
|
const configuredPythonWorks = !prepareProject && !configuredVenv && Boolean(configuredPython)
|
|
438
579
|
&& commandPasses(configuredPython, [], VERSION_CHECK)
|
|
439
|
-
&& commandPasses(configuredPython, [],
|
|
580
|
+
&& commandPasses(configuredPython, [], importCheck)
|
|
440
581
|
const venvDirectory = prepareProject
|
|
441
582
|
? projectVenv
|
|
442
583
|
: configuredVenv || (hasProjectRuntime ? projectVenv : join(stateDirectory, 'venv'))
|
|
443
584
|
const managedRuntime = !configuredPythonWorks && (prepareProject || Boolean(configuredVenv) || !hasProjectRuntime)
|
|
444
585
|
let runtimePython = configuredPythonWorks ? configuredPython : pythonPathForVenv(venvDirectory)
|
|
445
586
|
const fingerprint = await requirementsFingerprint()
|
|
446
|
-
const runtimeImportsWork = await pathExists(runtimePython) && commandPasses(runtimePython, [],
|
|
587
|
+
const runtimeImportsWork = await pathExists(runtimePython) && commandPasses(runtimePython, [], importCheck)
|
|
447
588
|
const runtimeVenvMatches = configuredPythonWorks || !runtimeImportsWork
|
|
448
589
|
? true
|
|
449
590
|
: await venvInterpreterMatches(venvDirectory, runtimePython)
|
|
450
591
|
const runtimeWorks = runtimeImportsWork && runtimeVenvMatches
|
|
451
|
-
const previousFailure = managedRuntime ? await readBootstrapFailure(venvDirectory, fingerprint
|
|
592
|
+
const previousFailure = managedRuntime ? await readBootstrapFailure(venvDirectory, fingerprint,
|
|
593
|
+
await bootstrapEnvironmentFingerprint(venvDirectory)) : null
|
|
452
594
|
let requirementsMatch = !managedRuntime || await stampMatches(venvDirectory, fingerprint)
|
|
453
|
-
// A previous bootstrap can fail after pip has installed every dependency
|
|
454
|
-
// but before the fingerprint is written. Re-verify imports above, then
|
|
455
|
-
// atomically restore the stamp and clear the stale failure instead of
|
|
456
|
-
// indefinitely rejecting an already-healthy runtime.
|
|
457
|
-
if (runtimeWorks && managedRuntime && !requirementsMatch && previousFailure && !prepareProject) {
|
|
458
|
-
try {
|
|
459
|
-
await writeStamp(venvDirectory, fingerprint)
|
|
460
|
-
requirementsMatch = await stampMatches(venvDirectory, fingerprint)
|
|
461
|
-
if (requirementsMatch) await rm(join(venvDirectory, BOOTSTRAP_FAILURE), { force: true })
|
|
462
|
-
} catch { /* Normal bootstrap below remains the safe fallback. */ }
|
|
463
|
-
}
|
|
464
595
|
let reason = ''
|
|
465
596
|
if (!runtimeWorks) reason = runtimeImportsWork
|
|
466
597
|
? 'Python runtime interpreter metadata is inconsistent'
|
|
@@ -475,7 +606,7 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
475
606
|
const logPath = join(stateDirectory, 'bootstrap.log')
|
|
476
607
|
const retryAt = bootstrapFailureRetryAt(previousFailure)
|
|
477
608
|
if (retryAt > Date.now()) {
|
|
478
|
-
throw new Error(`Python runtime preparation recently failed; automatic retry will resume after ${new Date(retryAt).toISOString()}. Run: pnpm bootstrap to retry now. See ${logPath}.`)
|
|
609
|
+
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}.`)
|
|
479
610
|
}
|
|
480
611
|
await rm(join(venvDirectory, BOOTSTRAP_FAILURE), { force: true }).catch(() => {})
|
|
481
612
|
}
|
|
@@ -498,7 +629,7 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
498
629
|
)
|
|
499
630
|
} catch (error) {
|
|
500
631
|
await writeBootstrapFailure(venvDirectory, fingerprint, error).catch(() => {})
|
|
501
|
-
throw
|
|
632
|
+
throw runtimeError(error?.code || 'BOOTSTRAP_FAILED', `Runtime preparation failed [${error?.code || 'BOOTSTRAP_FAILED'}]. See ${logPath}. ${error instanceof Error ? error.message : String(error)}`)
|
|
502
633
|
} finally {
|
|
503
634
|
if (bootstrapRuntime) await clearBootstrapMarker(venvDirectory)
|
|
504
635
|
}
|