personal-bot 0.2.14 → 0.2.15
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/.claude-plugin/marketplace.json +3 -3
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +10 -11
- package/README.zh-CN.md +10 -11
- package/docs/README.md +2 -2
- package/docs/adr/0001-claude-skill-discovery.md +1 -1
- package/docs/agent-collaboration.md +3 -3
- package/docs/architecture-guidelines.md +1 -1
- package/docs/capability-design.md +2 -2
- package/docs/claude-code-design.md +10 -11
- package/docs/claude-code.md +8 -15
- package/docs/dsh.md +7 -8
- package/docs/file-storage.md +2 -3
- package/docs/installation-design.md +4 -5
- package/docs/interaction-design.md +1 -1
- package/docs/model-context.md +9 -10
- package/docs/release.md +5 -5
- package/docs/technical-design.md +16 -21
- package/docs/workspace-configuration.md +5 -8
- package/hooks/hooks.json +1 -4
- package/lib/client.js +3 -15
- package/lib/extension/acp-member.js +1 -3
- package/lib/extension/acp-worker.js +3 -22
- package/lib/extension/claude-hooks.d.ts +0 -6
- package/lib/extension/claude-hooks.js +5 -31
- package/lib/extension/dsh/acp-member.js +1 -2
- package/lib/extension/dsh/command.js +2 -7
- package/lib/extension/dsh/management.d.ts +1 -1
- package/lib/extension/dsh/management.js +3 -3
- package/lib/extension/dsh/workspace.d.ts +1 -9
- package/lib/extension/dsh/workspace.js +4 -29
- package/lib/extension/setup-cli.js +4 -4
- package/lib/integrations/dsh/resources.d.ts +1 -5
- package/lib/integrations/dsh/resources.js +2 -5
- package/lib/integrations/installation/processes.js +0 -15
- package/lib/ui/dsh/management.js +1 -9
- package/lib/ui/dsh/styles.d.ts +1 -1
- package/lib/ui/dsh/styles.js +2 -2
- package/lib/ui/presentation.js +1 -1
- package/package.json +1 -4
- package/resources/claude/skills/pbot/SKILL.md +2 -3
- package/resources/prompts/workspace.md +1 -1
- package/resources/references/compute.md +6 -8
- package/scripts/README.md +2 -6
- package/src/extension/acp-member.ts +1 -3
- package/src/extension/acp-worker.ts +3 -12
- package/src/extension/claude-hooks.ts +5 -25
- package/src/extension/command.ts +7 -16
- package/src/extension/dsh/acp-member.ts +1 -2
- package/src/extension/dsh/command.ts +2 -6
- package/src/extension/dsh/management.ts +3 -3
- package/src/extension/dsh/workspace.ts +5 -25
- package/src/extension/events.ts +2 -11
- package/src/extension/lifecycle.ts +8 -23
- package/src/extension/setup-cli.ts +4 -4
- package/src/extension/subagent-entry.ts +6 -12
- package/src/integrations/dsh/resources.ts +2 -5
- package/src/integrations/installation/processes.ts +0 -13
- package/src/integrations/pi/pi-agents.ts +12 -5
- package/src/pbot.ts +1 -2
- package/src/ui/dsh/management.ts +2 -8
- package/src/ui/dsh/styles.ts +2 -2
- package/src/ui/presentation.ts +1 -1
- package/lib/integrations/process.d.ts +0 -14
- package/lib/integrations/process.js +0 -48
- package/lib/integrations/python-activation.d.ts +0 -2
- package/lib/integrations/python-activation.js +0 -29
- package/lib/services/workspace/python-environment-service.d.ts +0 -21
- package/lib/services/workspace/python-environment-service.js +0 -66
- package/python/README.md +0 -72
- package/python/requirements.lock +0 -38
- package/scripts/setup-python.py +0 -170
- package/src/integrations/process.ts +0 -40
- package/src/integrations/python-activation.ts +0 -23
- package/src/services/workspace/python-environment-service.ts +0 -61
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
import { spawn } from "node:child_process";
|
|
2
|
-
export function processEnvironment(env) {
|
|
3
|
-
return { PATH: process.env.PATH ?? "/usr/bin:/bin", LANG: "C.UTF-8", ...env };
|
|
4
|
-
}
|
|
5
|
-
export async function runCommand(command, args, input, cwd, env, signal, options = {}) {
|
|
6
|
-
signal?.throwIfAborted();
|
|
7
|
-
return new Promise(resolve => {
|
|
8
|
-
const child = spawn(command, args, { cwd, env: processEnvironment(env), shell: false,
|
|
9
|
-
detached: true, stdio: ["pipe", "pipe", "pipe"] });
|
|
10
|
-
let bytes = 0, failed = false;
|
|
11
|
-
const out = [], err = [];
|
|
12
|
-
const kill = () => { if (child.pid) {
|
|
13
|
-
try {
|
|
14
|
-
process.kill(-child.pid, "SIGKILL");
|
|
15
|
-
}
|
|
16
|
-
catch { /* Already stopped. */ }
|
|
17
|
-
} };
|
|
18
|
-
const stop = () => { failed = true; kill(); };
|
|
19
|
-
const timer = setTimeout(stop, options.timeoutMs ?? 30_000);
|
|
20
|
-
signal?.addEventListener("abort", stop, { once: true });
|
|
21
|
-
const collect = (target) => (chunk) => {
|
|
22
|
-
bytes += chunk.length;
|
|
23
|
-
if (bytes > 2 * 1024 * 1024)
|
|
24
|
-
stop();
|
|
25
|
-
else
|
|
26
|
-
target.push(chunk);
|
|
27
|
-
};
|
|
28
|
-
child.stdout.on("data", collect(out));
|
|
29
|
-
child.stderr.on("data", collect(err));
|
|
30
|
-
child.on("error", stop);
|
|
31
|
-
child.stdin.on("error", stop);
|
|
32
|
-
child.once("close", code => {
|
|
33
|
-
clearTimeout(timer);
|
|
34
|
-
signal?.removeEventListener("abort", stop);
|
|
35
|
-
kill();
|
|
36
|
-
const text = Buffer.concat(out).toString("utf8");
|
|
37
|
-
let data = { stdout: text, stderr: Buffer.concat(err).toString("utf8"), exitCode: code };
|
|
38
|
-
try {
|
|
39
|
-
data = JSON.parse(text);
|
|
40
|
-
}
|
|
41
|
-
catch { /* Preserve text and exit code. */ }
|
|
42
|
-
resolve({ success: !failed && !signal?.aborted && code === 0, data, raw: { stdout: text, stderr: Buffer.concat(err).toString("utf8"), exitCode: code, incomplete: failed || !!signal?.aborted } });
|
|
43
|
-
});
|
|
44
|
-
if (signal?.aborted)
|
|
45
|
-
stop();
|
|
46
|
-
child.stdin.end(input);
|
|
47
|
-
});
|
|
48
|
-
}
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import { delimiter, join } from "node:path";
|
|
2
|
-
/** Like venv activation, scoped to this Pi process; never edits shell configuration. */
|
|
3
|
-
export function activatePython(directory) {
|
|
4
|
-
const values = {
|
|
5
|
-
PATH: join(directory, "bin") + delimiter + (process.env.PATH ?? "/usr/bin:/bin"),
|
|
6
|
-
VIRTUAL_ENV: directory,
|
|
7
|
-
PYTHONHOME: undefined,
|
|
8
|
-
PYTHONPATH: undefined,
|
|
9
|
-
PYTHONNOUSERSITE: "1",
|
|
10
|
-
};
|
|
11
|
-
const previous = new Map(Object.keys(values).map(key => [key, process.env[key]]));
|
|
12
|
-
const assign = (key, value) => {
|
|
13
|
-
if (value === undefined)
|
|
14
|
-
delete process.env[key];
|
|
15
|
-
else
|
|
16
|
-
process.env[key] = value;
|
|
17
|
-
};
|
|
18
|
-
for (const [key, value] of Object.entries(values))
|
|
19
|
-
assign(key, value);
|
|
20
|
-
let restored = false;
|
|
21
|
-
return () => {
|
|
22
|
-
if (restored)
|
|
23
|
-
return;
|
|
24
|
-
restored = true;
|
|
25
|
-
for (const [key, value] of previous)
|
|
26
|
-
if (process.env[key] === values[key])
|
|
27
|
-
assign(key, value);
|
|
28
|
-
};
|
|
29
|
-
}
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
export declare class PythonEnvironmentService {
|
|
2
|
-
#private;
|
|
3
|
-
private readonly root;
|
|
4
|
-
constructor(root: string);
|
|
5
|
-
get status(): {
|
|
6
|
-
state: "unprepared" | "preparing" | "ready" | "error";
|
|
7
|
-
directory?: string;
|
|
8
|
-
error?: string;
|
|
9
|
-
};
|
|
10
|
-
private run;
|
|
11
|
-
inspect(signal?: AbortSignal): Promise<{
|
|
12
|
-
state: "unprepared" | "preparing" | "ready" | "error";
|
|
13
|
-
directory?: string;
|
|
14
|
-
error?: string;
|
|
15
|
-
}>;
|
|
16
|
-
setup(signal?: AbortSignal): Promise<{
|
|
17
|
-
directory: string;
|
|
18
|
-
python: string;
|
|
19
|
-
}>;
|
|
20
|
-
close(): Promise<void>;
|
|
21
|
-
}
|
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
import { join } from "node:path";
|
|
2
|
-
import { object } from "../../common/json.js";
|
|
3
|
-
import { runCommand } from "../../integrations/process.js";
|
|
4
|
-
import { requireThat } from "../../common/validation.js";
|
|
5
|
-
import { resourceRoot } from "../../common/paths.js";
|
|
6
|
-
export class PythonEnvironmentService {
|
|
7
|
-
root;
|
|
8
|
-
#shutdown = new AbortController();
|
|
9
|
-
#pending;
|
|
10
|
-
#status = { state: "unprepared" };
|
|
11
|
-
constructor(root) {
|
|
12
|
-
this.root = root;
|
|
13
|
-
}
|
|
14
|
-
get status() { return { ...this.#status }; }
|
|
15
|
-
async run(checkOnly, signal) {
|
|
16
|
-
const environment = {};
|
|
17
|
-
for (const [key, value] of Object.entries(process.env))
|
|
18
|
-
if (value !== undefined)
|
|
19
|
-
environment[key] = value;
|
|
20
|
-
const result = await runCommand("/bin/sh", ["-c", 'exec "$(command -v python3 || command -v python)" "$@"',
|
|
21
|
-
"pbot-python", "-I", "-B", join(resourceRoot, "../scripts/setup-python.py"), ...(checkOnly ? ["--check"] : [])], undefined, this.root, environment, signal, { timeoutMs: 15 * 60_000 });
|
|
22
|
-
signal.throwIfAborted();
|
|
23
|
-
requireThat(result.success && object(result.data) && typeof result.data.directory === "string" && typeof result.data.python === "string", "共享 Python 环境未就绪;修复后执行 Python 准备入口。\n" + JSON.stringify(result.data).slice(-6000));
|
|
24
|
-
return { directory: result.data.directory, python: result.data.python, action: result.data.action };
|
|
25
|
-
}
|
|
26
|
-
async inspect(signal) {
|
|
27
|
-
const cancel = signal ? AbortSignal.any([this.#shutdown.signal, signal]) : this.#shutdown.signal;
|
|
28
|
-
try {
|
|
29
|
-
const result = await this.run(true, cancel);
|
|
30
|
-
this.#status = result.action === "verify" ? { state: "ready", directory: result.directory } : { state: "unprepared" };
|
|
31
|
-
return this.status;
|
|
32
|
-
}
|
|
33
|
-
catch (error) {
|
|
34
|
-
this.#status = { state: "error", error: error instanceof Error ? error.message : String(error) };
|
|
35
|
-
throw error;
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
setup(signal) {
|
|
39
|
-
const cancel = signal ? AbortSignal.any([this.#shutdown.signal, signal]) : this.#shutdown.signal;
|
|
40
|
-
if (cancel.aborted)
|
|
41
|
-
return Promise.reject(cancel.reason);
|
|
42
|
-
if (this.#pending)
|
|
43
|
-
return this.#pending;
|
|
44
|
-
this.#status = { state: "preparing" };
|
|
45
|
-
this.#pending = (async () => {
|
|
46
|
-
try {
|
|
47
|
-
const result = await this.run(false, cancel);
|
|
48
|
-
const ready = { directory: result.directory, python: result.python };
|
|
49
|
-
this.#status = { state: "ready", directory: ready.directory };
|
|
50
|
-
return ready;
|
|
51
|
-
}
|
|
52
|
-
catch (error) {
|
|
53
|
-
this.#status = { state: "error", error: error instanceof Error ? error.message : String(error) };
|
|
54
|
-
throw error;
|
|
55
|
-
}
|
|
56
|
-
finally {
|
|
57
|
-
this.#pending = undefined;
|
|
58
|
-
}
|
|
59
|
-
})();
|
|
60
|
-
return this.#pending;
|
|
61
|
-
}
|
|
62
|
-
async close() {
|
|
63
|
-
this.#shutdown.abort();
|
|
64
|
-
await this.#pending?.catch(() => undefined);
|
|
65
|
-
}
|
|
66
|
-
}
|
package/python/README.md
DELETED
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
# Python 共享虚拟环境
|
|
2
|
-
|
|
3
|
-
所有 pbot 工作区共用当前系统用户的独立 Python 3.11+ venv。通过原生 Bash 执行普通脚本或模块,直接导入第三方库;没有 Python 计算执行工具或自定义计算包。Pi/dsh 激活进程环境后使用 `python` 或 `python3`;Claude 使用 `python.executable` 的完整路径。
|
|
4
|
-
|
|
5
|
-
## 自动准备与使用
|
|
6
|
-
|
|
7
|
-
工作区的 `.pbot/config.json` 设置 `enabled: true` 后,Pi 加载或原生 `/reload` 时自动执行 setup;dsh 在首个已启用工作区加载时准备环境;Claude 在 SessionStart 和后续用户请求 hook 中检查并准备环境。无需另行确认或指定 Python 路径。同一系统用户的 Pi、dsh、Claude 共用该环境:
|
|
8
|
-
|
|
9
|
-
1. 共享 venv 不存在时创建,不使用系统 site-packages;解释器无法启动时重新创建。
|
|
10
|
-
2. 按 `requirements.lock` 补齐或对齐依赖,允许升级或降级;已匹配时不重新安装。
|
|
11
|
-
3. 检查依赖关系、全部预装库导入和简单 TA-Lib 计算。
|
|
12
|
-
|
|
13
|
-
| 系统 | 共享环境 |
|
|
14
|
-
| --- | --- |
|
|
15
|
-
| Linux | `${XDG_DATA_HOME:-~/.local/share}/pbot/python/.venv`;仅使用绝对 XDG_DATA_HOME |
|
|
16
|
-
| macOS | `~/Library/Application Support/pbot/python/.venv` |
|
|
17
|
-
|
|
18
|
-
首次准备从当前 PATH 选择 python3,无该命令时使用 python;需要 Python 3.11+ 和 venv/ensurepip。系统 Python 只用于创建独立 venv,不在系统环境中安装依赖。已有 venv 按锁文件对齐,保留额外安装的包。基础解释器被移除或升级、导致共享 venv 的解释器无法启动时,setup 用当前 Python 3.11+ 重建该 venv,原有包随之移除;非 venv 数据、符号链接和其他 Python 环境不会被覆盖或删除。
|
|
19
|
-
|
|
20
|
-
首次安装可能需要数分钟和网络。各宿主的 init 入口创建共用启用配置并准备环境;不需要 Personal Bot 的工作区可保留配置缺失或设置 enabled 为 false。Pi/dsh 通过 `/pbot status` 查看状态;Claude 使用原生 `/personal-bot:pbot status` 技能,或直接运行 `node <plugin>/lib/claude.js status`。
|
|
21
|
-
|
|
22
|
-
Pi/dsh 成功后将 venv 的 `bin` 放到所在进程 PATH 前端,设置 `VIRTUAL_ENV`,移除 `PYTHONHOME`、`PYTHONPATH` 并禁用用户 site-packages,原生 Bash 继承该环境。所属激活生命周期关闭时恢复本扩展持有的变量,保留期间其他代码的新修改。dsh 按整个 pbot 组件共享激活,不随浏览器页面或单个工作区关闭而恢复。Pi/dsh 的 ACP worker 独立激活所在进程。
|
|
23
|
-
|
|
24
|
-
Claude 标准插件不修改 Claude PATH 或环境变量。就绪上下文和 CLI status 提供 Python 可执行文件的完整路径,原生 Bash 用该路径执行脚本;禁用或卸载无需恢复环境。外部终端和 shell 配置不变。
|
|
25
|
-
|
|
26
|
-
## 失败与手工重试
|
|
27
|
-
|
|
28
|
-
环境异常时,Pi/dsh 在运行状态中保留错误。Claude 在发生失败的 hook 或当次 `init`、`python setup` 结果中显示错误;后续 `status` 只读检查当前环境,不保存先前进程的安装日志。pbot 的其他能力仍可使用,但不把 Python 标记为就绪,也不替模型自动换用系统 Python 执行研究。原生 Bash 仍然可用。
|
|
29
|
-
|
|
30
|
-
检查错误后,Pi/dsh 可执行 `/pbot python setup`;Claude 可使用原生 `/personal-bot:pbot python setup` 技能,或确定性执行:
|
|
31
|
-
|
|
32
|
-
```sh
|
|
33
|
-
node /absolute/path/to/plugin/lib/claude.js python setup
|
|
34
|
-
```
|
|
35
|
-
|
|
36
|
-
无需路径参数和额外确认,执行同一准备逻辑。安装限时 15 分钟,超时或关闭会取消准备;不会自动回滚或循环重试。失败留下的环境保留,下次 setup 继续按锁文件补齐。共享 venv 解释器无法启动时自动重建;其他损坏不自动删除环境,可自行删除该目录后重试。缺少 pip 时仅尝试该 venv 的 ensurepip。
|
|
37
|
-
|
|
38
|
-
安装只接受 wheel,不编译 C 库、不安装系统软件,不绕过系统 Python 的安装保护。没有匹配 wheel、网络不可用、权限不足或环境损坏时停止。TA-Lib wheel 包含底层库,但并非所有系统和架构都有匹配 wheel。pip 安装配置被忽略,避免包被重定向到其他目标。
|
|
39
|
-
|
|
40
|
-
多个 pbot 进程同时启动时,通过共享排他锁串行准备,后取得锁的进程重新检查。锁文件不删除。该锁不管理普通 Python 进程;更换插件版本或手工重试前,应停止使用该环境的脚本。不同插件版本可能要求不同依赖,不宜同时使用。
|
|
41
|
-
|
|
42
|
-
## 独立准备
|
|
43
|
-
|
|
44
|
-
从包根目录运行也会自动准备同一共享环境:
|
|
45
|
-
|
|
46
|
-
```bash
|
|
47
|
-
python3 scripts/setup-python.py
|
|
48
|
-
python3 scripts/setup-python.py --check # 只检查,不创建或安装
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
脚本不接受解释器或目标路径参数,也不能激活其父终端。不修改工作区设置、脚本、历史运行记录或结果。准备脚本支持 Linux/macOS;插件其他宿主依赖仍须满足。dsh 桌面应用从登录 Shell 读取环境,Python 3.11+ 必须在该环境的 PATH 中可见。
|
|
52
|
-
|
|
53
|
-
## 使用与验证
|
|
54
|
-
|
|
55
|
-
setup 安装 numpy、pandas、TA-Lib、backtesting、scipy、statsmodels、matplotlib、scikit-learn、pyarrow、openpyxl、seaborn 和 Bokeh。按任务导入,环境与项目运行见[计算参考](../resources/references/compute.md),需要技术指标或回测时再读[指标与回测](../resources/references/compute-finance.md)。市场规则、费用、成交时点和数据切分由具体研究确定,原生 Backtest 不自动提供 A 股 T+1、整手或涨跌停约束。
|
|
56
|
-
|
|
57
|
-
Pi/dsh 激活后直接执行 `python scripts/analyze.py` 或 `python -m analysis.main`。Claude 使用状态提供的完整路径,例如 `"/absolute/path/to/shared/.venv/bin/python" scripts/analyze.py`。工作目录、模块导入、参数和结果位置遵循项目约定。项目构建或测试明确要求另一环境时,按项目约定执行。pbot 不复制源码、不生成输入文件或计算记录、不管理研究进程的超时。Python 与 Bash 使用实际账户权限,操作范围见[工具与执行](../docs/capability-design.md)。
|
|
58
|
-
|
|
59
|
-
在已激活环境中验证;Claude 将以下 `python` 换为完整可执行路径:
|
|
60
|
-
|
|
61
|
-
```bash
|
|
62
|
-
python -m pip check
|
|
63
|
-
python -B -m unittest discover -s python/tests -v
|
|
64
|
-
```
|
|
65
|
-
|
|
66
|
-
Node 测试检查环境探测、错误、取消与 Pi/dsh 激活恢复,使用临时 venv 和原生 Bash。上述 Python 测试在已准备的环境中检查原生库配合与文件往返。
|
|
67
|
-
|
|
68
|
-
依赖版本独立于插件版本。更新锁文件须检查最低 Python 3.11 与目标环境的兼容性,不只按开发机选择最新版。
|
|
69
|
-
|
|
70
|
-
## 依赖许可
|
|
71
|
-
|
|
72
|
-
[TA-Lib Python](https://github.com/TA-Lib/ta-lib-python) 使用 BSD-2-Clause,[TA-Lib 底层库](https://github.com/TA-Lib/ta-lib) 使用 BSD-3-Clause。[backtesting.py](https://github.com/kernc/backtesting.py) 0.6.6 使用 AGPL-3.0。具体版本见 requirements.lock。共享环境按锁文件安装依赖,发布包不捆绑第三方 wheel;依赖的使用与再分发须遵循各自许可。
|
package/python/requirements.lock
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
backtesting==0.6.6
|
|
2
|
-
bokeh==3.9.2
|
|
3
|
-
cloudpickle==3.1.2
|
|
4
|
-
contourpy==1.3.3
|
|
5
|
-
cycler==0.12.1
|
|
6
|
-
et_xmlfile==2.0.0
|
|
7
|
-
fonttools==4.67.0
|
|
8
|
-
formulaic==1.2.2
|
|
9
|
-
interface_meta==2.0.1
|
|
10
|
-
Jinja2==3.1.6
|
|
11
|
-
joblib==1.6.0
|
|
12
|
-
kiwisolver==1.5.1
|
|
13
|
-
MarkupSafe==3.0.4
|
|
14
|
-
matplotlib==3.11.2
|
|
15
|
-
narwhals==2.27.1
|
|
16
|
-
numpy==2.3.4
|
|
17
|
-
openpyxl==3.1.5
|
|
18
|
-
packaging==26.3
|
|
19
|
-
pandas==2.3.3
|
|
20
|
-
patsy==1.0.3
|
|
21
|
-
pillow==12.3.0
|
|
22
|
-
pyarrow==26.0.0
|
|
23
|
-
pyparsing==3.3.3
|
|
24
|
-
python-dateutil==2.9.0.post0
|
|
25
|
-
pytz==2026.5
|
|
26
|
-
PyYAML==6.0.3
|
|
27
|
-
scikit-learn==1.9.1
|
|
28
|
-
scipy==1.17.1
|
|
29
|
-
seaborn==0.13.2
|
|
30
|
-
six==1.17.0
|
|
31
|
-
statsmodels==0.15.0
|
|
32
|
-
TA-Lib==0.8.2
|
|
33
|
-
threadpoolctl==3.7.0
|
|
34
|
-
tornado==6.5.10
|
|
35
|
-
typing_extensions==4.16.0
|
|
36
|
-
tzdata==2026.5
|
|
37
|
-
wrapt==2.5.1
|
|
38
|
-
xyzservices==2026.9.1
|
package/scripts/setup-python.py
DELETED
|
@@ -1,170 +0,0 @@
|
|
|
1
|
-
"""Create or verify the current user's shared pbot virtual environment."""
|
|
2
|
-
|
|
3
|
-
import argparse
|
|
4
|
-
import fcntl
|
|
5
|
-
import json
|
|
6
|
-
import os
|
|
7
|
-
from pathlib import Path
|
|
8
|
-
import re
|
|
9
|
-
import shutil
|
|
10
|
-
import stat
|
|
11
|
-
import subprocess
|
|
12
|
-
import sys
|
|
13
|
-
import tempfile
|
|
14
|
-
import venv
|
|
15
|
-
|
|
16
|
-
REQUIREMENTS = Path(__file__).resolve().parent.parent / "python" / "requirements.lock"
|
|
17
|
-
INSPECT = """
|
|
18
|
-
import importlib.metadata as m, json, sys
|
|
19
|
-
print(json.dumps({
|
|
20
|
-
"prefix": sys.prefix, "basePrefix": sys.base_prefix,
|
|
21
|
-
"version": list(sys.version_info[:3]),
|
|
22
|
-
"packages": {d.metadata["Name"]: d.version for d in m.distributions()}
|
|
23
|
-
}))
|
|
24
|
-
"""
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
def directory():
|
|
28
|
-
if sys.platform == "darwin":
|
|
29
|
-
return Path.home() / "Library/Application Support/pbot/python/.venv"
|
|
30
|
-
data = os.environ.get("XDG_DATA_HOME", "")
|
|
31
|
-
root = Path(data) if os.path.isabs(data) else Path.home() / ".local/share"
|
|
32
|
-
return root / "pbot/python/.venv"
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
def normalize(name):
|
|
36
|
-
return re.sub(r"[-_.]+", "-", name).lower()
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
def locked_packages():
|
|
40
|
-
result = {}
|
|
41
|
-
for line in REQUIREMENTS.read_text().splitlines():
|
|
42
|
-
if not line.strip() or line.startswith("#"):
|
|
43
|
-
continue
|
|
44
|
-
match = re.fullmatch(r"([A-Za-z0-9_.-]+)==([A-Za-z0-9_.+!-]+)", line)
|
|
45
|
-
if not match:
|
|
46
|
-
raise ValueError("requirements.lock 必须逐行使用 name==version。")
|
|
47
|
-
name, version = match.groups()
|
|
48
|
-
key = normalize(name)
|
|
49
|
-
if key in result:
|
|
50
|
-
raise ValueError("requirements.lock 存在重复依赖。")
|
|
51
|
-
result[key] = version
|
|
52
|
-
if not result:
|
|
53
|
-
raise ValueError("requirements.lock 不能为空。")
|
|
54
|
-
return result
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
def inspect_environment(target):
|
|
58
|
-
"""Return the shared venv description; None means it must be created or rebuilt."""
|
|
59
|
-
if target.is_symlink():
|
|
60
|
-
raise ValueError("共享环境目录不能是符号链接。")
|
|
61
|
-
if not target.exists():
|
|
62
|
-
return None
|
|
63
|
-
config = target / "pyvenv.cfg"
|
|
64
|
-
if not target.is_dir() or not config.is_file() or config.is_symlink():
|
|
65
|
-
raise ValueError("共享环境位置已被非 venv 数据占用;不会覆盖或删除。")
|
|
66
|
-
if re.search(r"include-system-site-packages\s*=\s*true", config.read_text(), re.I):
|
|
67
|
-
raise ValueError("共享 venv 不能继承系统 site-packages。")
|
|
68
|
-
try:
|
|
69
|
-
probe = subprocess.run([str(target / "bin/python"), "-I", "-B", "-c", INSPECT],
|
|
70
|
-
capture_output=True, text=True)
|
|
71
|
-
except OSError:
|
|
72
|
-
# The base interpreter was removed, so the environment cannot run.
|
|
73
|
-
return None
|
|
74
|
-
if probe.returncode != 0:
|
|
75
|
-
# The base interpreter was upgraded, or the copied executable is damaged.
|
|
76
|
-
return None
|
|
77
|
-
info = json.loads(probe.stdout)
|
|
78
|
-
if Path(info["prefix"]).resolve() != target.resolve() or info["prefix"] == info["basePrefix"]:
|
|
79
|
-
raise ValueError("解释器不属于共享 venv;不会修改其他 Python 环境。")
|
|
80
|
-
if info["version"][:2] < [3, 11]:
|
|
81
|
-
raise ValueError("共享环境需要 Python 3.11+;不会自动替换其基础解释器。")
|
|
82
|
-
info["packages"] = {normalize(name): version for name, version in info["packages"].items()}
|
|
83
|
-
return info
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
def plan(target):
|
|
87
|
-
required = locked_packages()
|
|
88
|
-
current = inspect_environment(target)
|
|
89
|
-
installed = (current or {}).get("packages", {})
|
|
90
|
-
changes = [{"package": name, "from": installed.get(name), "to": version}
|
|
91
|
-
for name, version in required.items() if installed.get(name) != version]
|
|
92
|
-
if current is None:
|
|
93
|
-
action = "rebuild" if target.exists() else "create"
|
|
94
|
-
else:
|
|
95
|
-
action = "update" if changes else "verify"
|
|
96
|
-
return {
|
|
97
|
-
"action": action, "directory": str(target), "python": str(target / "bin/python"),
|
|
98
|
-
"current": current, "required": required, "changes": changes,
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
def setup(target):
|
|
103
|
-
target.parent.mkdir(parents=True, exist_ok=True)
|
|
104
|
-
# Never unlink this file: concurrent installers must lock the same inode.
|
|
105
|
-
fd = os.open(str(target) + ".lock", os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
|
106
|
-
try:
|
|
107
|
-
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
|
108
|
-
raise ValueError("共享环境锁必须是普通文件。")
|
|
109
|
-
# Concurrent startups wait, then inspect again rather than apply stale plans.
|
|
110
|
-
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
111
|
-
actual = plan(target)
|
|
112
|
-
if actual["action"] == "rebuild":
|
|
113
|
-
print("共享 venv 的解释器无法运行,重建共享环境。", file=sys.stderr)
|
|
114
|
-
shutil.rmtree(target)
|
|
115
|
-
if actual["action"] in ("create", "rebuild"):
|
|
116
|
-
venv.EnvBuilder(with_pip=True).create(target)
|
|
117
|
-
python = str(target / "bin/python")
|
|
118
|
-
|
|
119
|
-
def run(args):
|
|
120
|
-
subprocess.run([python, "-I", "-B", *args], check=True, pass_fds=(fd,),
|
|
121
|
-
stdout=sys.stderr, env={**os.environ, "PIP_CONFIG_FILE": os.devnull})
|
|
122
|
-
|
|
123
|
-
current = inspect_environment(target)
|
|
124
|
-
if "pip" not in current["packages"]:
|
|
125
|
-
run(["-m", "ensurepip"])
|
|
126
|
-
pip = ["-m", "pip", "--isolated", "--disable-pip-version-check"]
|
|
127
|
-
if actual["changes"]:
|
|
128
|
-
with tempfile.TemporaryDirectory(prefix="pbot-python-") as temp:
|
|
129
|
-
locked = Path(temp) / "requirements.txt"
|
|
130
|
-
locked.write_text("".join(name + "==" + version + "\n" for name, version in actual["required"].items()))
|
|
131
|
-
run([*pip, "download", "--only-binary=:all:", "--no-deps", "-r", str(locked), "--dest", temp])
|
|
132
|
-
run([*pip, "install", "--no-index", "--find-links", temp, "--no-deps", "-r", str(locked)])
|
|
133
|
-
run([*pip, "check"])
|
|
134
|
-
verified = inspect_environment(target)
|
|
135
|
-
if any(verified["packages"].get(name) != version for name, version in actual["required"].items()):
|
|
136
|
-
raise RuntimeError("安装后版本检查未通过。")
|
|
137
|
-
run(["-c", "import matplotlib; matplotlib.use('Agg'); "
|
|
138
|
-
"import numpy, pandas, talib, backtesting, scipy, statsmodels.api, "
|
|
139
|
-
"matplotlib.pyplot, sklearn, pyarrow, openpyxl, seaborn; "
|
|
140
|
-
"assert talib.SMA(numpy.arange(1., 6.), 3)[-1] == 4."])
|
|
141
|
-
return {"directory": str(target), "python": python, "packages": verified["packages"]}
|
|
142
|
-
finally:
|
|
143
|
-
os.close(fd)
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
def main():
|
|
147
|
-
# venv records the invoking path as its home; resolve first so a symlinked launcher
|
|
148
|
-
# (for example a relocatable CPython managed by another tool) yields a usable base.
|
|
149
|
-
real = os.path.realpath(sys.executable) if sys.executable else ""
|
|
150
|
-
if real and real != sys.executable:
|
|
151
|
-
os.execv(real, [real, "-I", "-B", os.path.abspath(__file__), *sys.argv[1:]])
|
|
152
|
-
parser = argparse.ArgumentParser(description=__doc__)
|
|
153
|
-
parser.add_argument("--check", action="store_true", help="只检查共享环境,不创建或安装")
|
|
154
|
-
args = parser.parse_args()
|
|
155
|
-
if sys.platform not in ("linux", "darwin") or sys.version_info < (3, 11):
|
|
156
|
-
raise RuntimeError("需要 Linux/macOS 和 Python 3.11+。")
|
|
157
|
-
target = directory()
|
|
158
|
-
print(json.dumps(plan(target) if args.check else setup(target), ensure_ascii=False))
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
if __name__ == "__main__":
|
|
162
|
-
try:
|
|
163
|
-
main()
|
|
164
|
-
except (Exception, KeyboardInterrupt) as error:
|
|
165
|
-
if isinstance(error, subprocess.CalledProcessError) and error.output:
|
|
166
|
-
print(error.output if isinstance(error.output, str) else error.output.decode(errors="replace"),
|
|
167
|
-
file=sys.stderr, end="")
|
|
168
|
-
print(str(error), file=sys.stderr)
|
|
169
|
-
print("共享 Python 环境未就绪。请检查 Python 3.11+、venv/ensurepip、网络、安装权限和 wheel;修复后执行 /pbot python setup 或重启。不改用系统环境安装或编译 C 库;共享 venv 解释器无法运行时会重建,其他数据不删除。", file=sys.stderr)
|
|
170
|
-
sys.exit(1)
|
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
import { spawn } from "node:child_process";
|
|
2
|
-
import type { Json } from "../common/json.js";
|
|
3
|
-
|
|
4
|
-
interface ProcessResult {
|
|
5
|
-
success: boolean;
|
|
6
|
-
data: Json;
|
|
7
|
-
raw: Json;
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
export function processEnvironment(env: Record<string, string>) {
|
|
11
|
-
return { PATH: process.env.PATH ?? "/usr/bin:/bin", LANG: "C.UTF-8", ...env };
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export async function runCommand(command: string, args: string[], input: string | undefined, cwd: string,
|
|
15
|
-
env: Record<string, string>, signal?: AbortSignal, options: { timeoutMs?: number } = {}): Promise<ProcessResult> {
|
|
16
|
-
signal?.throwIfAborted();
|
|
17
|
-
return new Promise(resolve => {
|
|
18
|
-
const child = spawn(command, args, { cwd, env: processEnvironment(env), shell: false,
|
|
19
|
-
detached: true, stdio: ["pipe", "pipe", "pipe"] });
|
|
20
|
-
let bytes = 0, failed = false;
|
|
21
|
-
const out: Buffer[] = [], err: Buffer[] = [];
|
|
22
|
-
const kill = () => { if (child.pid) { try { process.kill(-child.pid, "SIGKILL"); } catch { /* Already stopped. */ } } };
|
|
23
|
-
const stop = () => { failed = true; kill(); };
|
|
24
|
-
const timer = setTimeout(stop, options.timeoutMs ?? 30_000);
|
|
25
|
-
signal?.addEventListener("abort", stop, { once: true });
|
|
26
|
-
const collect = (target: Buffer[]) => (chunk: Buffer) => {
|
|
27
|
-
bytes += chunk.length; if (bytes > 2 * 1024 * 1024) stop(); else target.push(chunk);
|
|
28
|
-
};
|
|
29
|
-
child.stdout.on("data", collect(out)); child.stderr.on("data", collect(err));
|
|
30
|
-
child.on("error", stop); child.stdin.on("error", stop);
|
|
31
|
-
child.once("close", code => {
|
|
32
|
-
clearTimeout(timer); signal?.removeEventListener("abort", stop); kill();
|
|
33
|
-
const text = Buffer.concat(out).toString("utf8");
|
|
34
|
-
let data: Json = { stdout: text, stderr: Buffer.concat(err).toString("utf8"), exitCode: code };
|
|
35
|
-
try { data = JSON.parse(text) as Json; } catch { /* Preserve text and exit code. */ }
|
|
36
|
-
resolve({ success: !failed && !signal?.aborted && code === 0, data, raw: { stdout: text, stderr: Buffer.concat(err).toString("utf8"), exitCode: code, incomplete: failed || !!signal?.aborted } });
|
|
37
|
-
});
|
|
38
|
-
if (signal?.aborted) stop(); child.stdin.end(input);
|
|
39
|
-
});
|
|
40
|
-
}
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { delimiter, join } from "node:path";
|
|
2
|
-
|
|
3
|
-
/** Like venv activation, scoped to this Pi process; never edits shell configuration. */
|
|
4
|
-
export function activatePython(directory: string): () => void {
|
|
5
|
-
const values: Record<string, string | undefined> = {
|
|
6
|
-
PATH: join(directory, "bin") + delimiter + (process.env.PATH ?? "/usr/bin:/bin"),
|
|
7
|
-
VIRTUAL_ENV: directory,
|
|
8
|
-
PYTHONHOME: undefined,
|
|
9
|
-
PYTHONPATH: undefined,
|
|
10
|
-
PYTHONNOUSERSITE: "1",
|
|
11
|
-
};
|
|
12
|
-
const previous = new Map(Object.keys(values).map(key => [key, process.env[key]]));
|
|
13
|
-
const assign = (key: string, value: string | undefined) => {
|
|
14
|
-
if (value === undefined) delete process.env[key]; else process.env[key] = value;
|
|
15
|
-
};
|
|
16
|
-
for (const [key, value] of Object.entries(values)) assign(key, value);
|
|
17
|
-
let restored = false;
|
|
18
|
-
return () => {
|
|
19
|
-
if (restored) return;
|
|
20
|
-
restored = true;
|
|
21
|
-
for (const [key, value] of previous) if (process.env[key] === values[key]) assign(key, value);
|
|
22
|
-
};
|
|
23
|
-
}
|
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
import { join } from "node:path";
|
|
2
|
-
import { object } from "../../common/json.js";
|
|
3
|
-
import { runCommand } from "../../integrations/process.js";
|
|
4
|
-
import { requireThat } from "../../common/validation.js";
|
|
5
|
-
import { resourceRoot } from "../../common/paths.js";
|
|
6
|
-
|
|
7
|
-
export class PythonEnvironmentService {
|
|
8
|
-
readonly #shutdown = new AbortController();
|
|
9
|
-
#pending: Promise<{ directory: string; python: string }> | undefined;
|
|
10
|
-
#status: { state: "unprepared" | "preparing" | "ready" | "error"; directory?: string; error?: string } = { state: "unprepared" };
|
|
11
|
-
constructor(private readonly root: string) {}
|
|
12
|
-
get status() { return { ...this.#status }; }
|
|
13
|
-
|
|
14
|
-
private async run(checkOnly: boolean, signal: AbortSignal) {
|
|
15
|
-
const environment: Record<string, string> = {};
|
|
16
|
-
for (const [key, value] of Object.entries(process.env)) if (value !== undefined) environment[key] = value;
|
|
17
|
-
const result = await runCommand("/bin/sh", ["-c", 'exec "$(command -v python3 || command -v python)" "$@"',
|
|
18
|
-
"pbot-python", "-I", "-B", join(resourceRoot, "../scripts/setup-python.py"), ...(checkOnly ? ["--check"] : [])],
|
|
19
|
-
undefined, this.root, environment, signal, { timeoutMs: 15 * 60_000 });
|
|
20
|
-
signal.throwIfAborted();
|
|
21
|
-
requireThat(result.success && object(result.data) && typeof result.data.directory === "string" && typeof result.data.python === "string",
|
|
22
|
-
"共享 Python 环境未就绪;修复后执行 Python 准备入口。\n" + JSON.stringify(result.data).slice(-6000));
|
|
23
|
-
return { directory: result.data.directory, python: result.data.python, action: result.data.action };
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
async inspect(signal?: AbortSignal) {
|
|
27
|
-
const cancel = signal ? AbortSignal.any([this.#shutdown.signal, signal]) : this.#shutdown.signal;
|
|
28
|
-
try {
|
|
29
|
-
const result = await this.run(true, cancel);
|
|
30
|
-
this.#status = result.action === "verify" ? { state: "ready", directory: result.directory } : { state: "unprepared" };
|
|
31
|
-
return this.status;
|
|
32
|
-
} catch (error) {
|
|
33
|
-
this.#status = { state: "error", error: error instanceof Error ? error.message : String(error) };
|
|
34
|
-
throw error;
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
setup(signal?: AbortSignal): Promise<{ directory: string; python: string }> {
|
|
39
|
-
const cancel = signal ? AbortSignal.any([this.#shutdown.signal, signal]) : this.#shutdown.signal;
|
|
40
|
-
if (cancel.aborted) return Promise.reject(cancel.reason);
|
|
41
|
-
if (this.#pending) return this.#pending;
|
|
42
|
-
this.#status = { state: "preparing" };
|
|
43
|
-
this.#pending = (async () => {
|
|
44
|
-
try {
|
|
45
|
-
const result = await this.run(false, cancel);
|
|
46
|
-
const ready = { directory: result.directory, python: result.python };
|
|
47
|
-
this.#status = { state: "ready", directory: ready.directory };
|
|
48
|
-
return ready;
|
|
49
|
-
} catch (error) {
|
|
50
|
-
this.#status = { state: "error", error: error instanceof Error ? error.message : String(error) };
|
|
51
|
-
throw error;
|
|
52
|
-
} finally { this.#pending = undefined; }
|
|
53
|
-
})();
|
|
54
|
-
return this.#pending;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
async close(): Promise<void> {
|
|
58
|
-
this.#shutdown.abort();
|
|
59
|
-
await this.#pending?.catch(() => undefined);
|
|
60
|
-
}
|
|
61
|
-
}
|