personal-bot 0.2.13 → 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.
Files changed (92) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +10 -11
  4. package/README.zh-CN.md +10 -11
  5. package/docs/README.md +2 -2
  6. package/docs/adr/0001-claude-skill-discovery.md +1 -1
  7. package/docs/agent-collaboration.md +3 -3
  8. package/docs/architecture-guidelines.md +1 -1
  9. package/docs/capability-design.md +2 -2
  10. package/docs/claude-code-design.md +10 -11
  11. package/docs/claude-code.md +8 -15
  12. package/docs/dsh.md +7 -8
  13. package/docs/file-storage.md +2 -3
  14. package/docs/installation-design.md +4 -5
  15. package/docs/interaction-design.md +1 -1
  16. package/docs/model-context.md +9 -10
  17. package/docs/release.md +6 -6
  18. package/docs/technical-design.md +18 -23
  19. package/docs/workspace-configuration.md +5 -8
  20. package/hooks/hooks.json +1 -4
  21. package/lib/client.js +3 -15
  22. package/lib/common/schema.d.ts +2 -0
  23. package/lib/common/schema.js +10 -0
  24. package/lib/common/validation.d.ts +0 -2
  25. package/lib/common/validation.js +0 -10
  26. package/lib/extension/acp-member.js +1 -3
  27. package/lib/extension/acp-worker.js +3 -22
  28. package/lib/extension/claude-hooks.d.ts +0 -6
  29. package/lib/extension/claude-hooks.js +5 -31
  30. package/lib/extension/dsh/acp-member.js +1 -2
  31. package/lib/extension/dsh/command.js +4 -8
  32. package/lib/extension/dsh/management.d.ts +1 -1
  33. package/lib/extension/dsh/management.js +5 -4
  34. package/lib/extension/dsh/workspace.d.ts +1 -9
  35. package/lib/extension/dsh/workspace.js +4 -29
  36. package/lib/extension/setup-cli.js +4 -4
  37. package/lib/integrations/dsh/resources.d.ts +1 -5
  38. package/lib/integrations/dsh/resources.js +2 -5
  39. package/lib/integrations/installation/processes.js +0 -15
  40. package/lib/tools/agents/dsh-tool.js +2 -1
  41. package/lib/tools/history/contract.js +2 -1
  42. package/lib/tools/history/dsh-tool.js +2 -1
  43. package/lib/tools/teams/dsh-tool.js +2 -1
  44. package/lib/ui/dsh/management.js +1 -9
  45. package/lib/ui/dsh/styles.d.ts +1 -1
  46. package/lib/ui/dsh/styles.js +2 -2
  47. package/lib/ui/presentation.js +1 -1
  48. package/package.json +1 -5
  49. package/resources/claude/skills/pbot/SKILL.md +2 -3
  50. package/resources/prompts/workspace.md +1 -1
  51. package/resources/references/compute.md +6 -8
  52. package/scripts/README.md +5 -9
  53. package/src/common/schema.ts +11 -0
  54. package/src/common/validation.ts +0 -11
  55. package/src/extension/acp-member.ts +1 -3
  56. package/src/extension/acp-worker.ts +3 -12
  57. package/src/extension/claude-hooks.ts +5 -25
  58. package/src/extension/command.ts +7 -16
  59. package/src/extension/dsh/acp-member.ts +1 -2
  60. package/src/extension/dsh/command.ts +4 -7
  61. package/src/extension/dsh/management.ts +5 -4
  62. package/src/extension/dsh/workspace.ts +5 -25
  63. package/src/extension/events.ts +2 -11
  64. package/src/extension/lifecycle.ts +8 -23
  65. package/src/extension/setup-cli.ts +4 -4
  66. package/src/extension/subagent-entry.ts +6 -12
  67. package/src/integrations/dsh/resources.ts +2 -5
  68. package/src/integrations/installation/processes.ts +0 -13
  69. package/src/integrations/pi/pi-agents.ts +12 -5
  70. package/src/pbot.ts +1 -2
  71. package/src/tools/agents/dsh-tool.ts +2 -1
  72. package/src/tools/agents/tool.ts +2 -1
  73. package/src/tools/history/contract.ts +2 -1
  74. package/src/tools/history/dsh-tool.ts +2 -1
  75. package/src/tools/teams/dsh-tool.ts +2 -1
  76. package/src/tools/teams/tool.ts +2 -1
  77. package/src/ui/dsh/management.ts +2 -8
  78. package/src/ui/dsh/styles.ts +2 -2
  79. package/src/ui/presentation.ts +1 -1
  80. package/lib/integrations/process.d.ts +0 -14
  81. package/lib/integrations/process.js +0 -48
  82. package/lib/integrations/python-activation.d.ts +0 -2
  83. package/lib/integrations/python-activation.js +0 -29
  84. package/lib/services/workspace/python-environment-service.d.ts +0 -21
  85. package/lib/services/workspace/python-environment-service.js +0 -66
  86. package/npm-shrinkwrap.json +0 -13544
  87. package/python/README.md +0 -72
  88. package/python/requirements.lock +0 -38
  89. package/scripts/setup-python.py +0 -170
  90. package/src/integrations/process.ts +0 -40
  91. package/src/integrations/python-activation.ts +0 -23
  92. package/src/services/workspace/python-environment-service.ts +0 -61
@@ -58,11 +58,18 @@ export class PiAgents implements AgentHost {
58
58
  if (o.thinking) args.push("--thinking", o.thinking);
59
59
  }
60
60
  if (o.tools) args.push("--tools", o.tools.join(","));
61
- const result = spawnSync("tmux", ["new-session", "-d", "-s", tmuxName(d.agentId), "-x", "120", "-y", "40", "-c", d.cwd, "--",
62
- "env", `PBOT_SUBAGENT_RUN_ID=${d.agentId}`, `PBOT_SUBAGENT_DIR=${directory}`, `PBOT_SUBAGENT_GENERATION=${generation}`,
63
- `PI_CODING_AGENT_DIR=${getAgentDir()}`, `PI_CODING_AGENT_SESSION_DIR=${process.env.PI_CODING_AGENT_SESSION_DIR ?? ""}`,
64
- ...["PATH", "HOME", "XDG_DATA_HOME", "XDG_CONFIG_HOME"].flatMap(key => process.env[key] === undefined ? [] : [`${key}=${process.env[key]}`]),
65
- process.execPath, join(getPackageDir(), "dist/cli.js"), ...args], { encoding: "utf8" });
61
+ const environment: NodeJS.ProcessEnv = { ...process.env, PWD: d.cwd,
62
+ PBOT_SUBAGENT_RUN_ID: d.agentId, PBOT_SUBAGENT_DIR: directory, PBOT_SUBAGENT_GENERATION: generation,
63
+ PI_CODING_AGENT_DIR: getAgentDir() };
64
+ const terminalKeys = ["TERM", "TMUX", "TMUX_PANE", "TERM_PROGRAM", "TERM_PROGRAM_VERSION"];
65
+ for (const key of terminalKeys) delete environment[key];
66
+ const cached = spawnSync("tmux", ["show-environment", "-g"], { encoding: "utf8" }).stdout ?? "";
67
+ const removed = cached.split("\n").map(line => line.replace(/^-/, "").split("=", 1)[0]!)
68
+ .filter(key => key && environment[key] === undefined && !terminalKeys.includes(key));
69
+ // Session environment values stay out of the pane command; clear values cached only by the server.
70
+ const result = spawnSync("tmux", ["new-session", "-d", "-s", tmuxName(d.agentId), "-x", "120", "-y", "40", "-c", d.cwd,
71
+ ...Object.entries(environment).flatMap(([key, value]) => value === undefined ? [] : ["-e", `${key}=${value}`]), "--",
72
+ "/usr/bin/env", ...removed.flatMap(key => ["-u", key]), process.execPath, join(getPackageDir(), "dist/cli.js"), ...args], { encoding: "utf8" });
66
73
  requireThat(result.status === 0, result.stderr || "子会话启动失败。");
67
74
  }
68
75
  report(d: AgentDescriptor, reference: AgentSessionReference, leaf: string) {
package/src/pbot.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { PiAgents, agentDirectory } from "./integrations/pi/pi-agents.js";
3
3
  import { AgentBackends } from "./integrations/acp/agents.js";
4
- import { PythonEnvironmentService } from "./services/workspace/python-environment-service.js";
5
4
  import { AgentService } from "./services/agents/agent-service.js";
6
5
  import { TeamService } from "./services/agents/team-service.js";
7
6
  import { Confirmations } from "./ui/confirmation.js";
@@ -28,7 +27,7 @@ export default function pbot(pi: ExtensionAPI) {
28
27
  const file = agents.files.optional(agent.agentId, "session-ref.json", sessionRef)?.file;
29
28
  return file ? [file] : [];
30
29
  })), [new HistoryFiles(join(root, ".pbot/history"), "dsh"), new HistoryFiles(join(root, ".pbot/history"), "claude")]);
31
- return new WorkspaceInstance(root, new PythonEnvironmentService(root), agents, new TeamService(root, agents.files, agents.teamFiles), history);
30
+ return new WorkspaceInstance(root, agents, new TeamService(root, agents.files, agents.teamFiles), history);
32
31
  }, instance => registry.register(mainTools(instance.agents, instance.teams, instance.history, instance)), () => registry.hide());
33
32
  registerCommand(pi, lifecycle, confirmations);
34
33
  registerEvents(pi, lifecycle, confirmations);
@@ -4,7 +4,8 @@ import { dshParameters, dshOutputSchema } from "../../integrations/dsh/schema.js
4
4
  import type { AgentService } from "../../services/agents/agent-service.js";
5
5
  import type { AgentOwner } from "../../model/agent.js";
6
6
  import { object, json } from "../../common/json.js";
7
- import { requireThat, schema } from "../../common/validation.js";
7
+ import { requireThat } from "../../common/validation.js";
8
+ import { schema } from "../../common/schema.js";
8
9
  import { markdownFields } from "../../common/markdown.js";
9
10
  import { executeAgent, type AgentInput } from "./actions.js";
10
11
  import { agentDescription, agentResultSchema } from "./contract.js";
@@ -2,7 +2,8 @@ import { defineTool } from "@earendil-works/pi-coding-agent";
2
2
  import type { AgentService } from "../../services/agents/agent-service.js";
3
3
  import { agentOwner } from "../../integrations/pi/agent-context.js";
4
4
  import type { CallAccess } from "../access.js";
5
- import { requireThat, schema } from "../../common/validation.js";
5
+ import { requireThat } from "../../common/validation.js";
6
+ import { schema } from "../../common/schema.js";
6
7
  import { executeAgent } from "./actions.js";
7
8
  import { agentDescription, agentActionSchema, agentParametersSchema, agentResultSchema } from "./contract.js";
8
9
 
@@ -1,5 +1,6 @@
1
1
  import { Type, type Static } from "typebox";
2
- import { requireThat, schema } from "../../common/validation.js";
2
+ import { requireThat } from "../../common/validation.js";
3
+ import { schema } from "../../common/schema.js";
3
4
 
4
5
  const host = Type.Union([Type.Literal("pi"), Type.Literal("dsh"), Type.Literal("claude")]);
5
6
  const nullableOffset = Type.Union([Type.Integer(), Type.Null()]);
@@ -2,7 +2,8 @@ import type { Context } from "@deepseek-ai/cordis";
2
2
  import type { Agent } from "@deepseek-ai/dsh-agent";
3
3
  import type { HistoryService } from "../../services/history/history-service.js";
4
4
  import { dshParameters, dshOutputSchema } from "../../integrations/dsh/schema.js";
5
- import { requireThat, schema } from "../../common/validation.js";
5
+ import { requireThat } from "../../common/validation.js";
6
+ import { schema } from "../../common/schema.js";
6
7
  import { json } from "../../common/json.js";
7
8
  import { markdownFields } from "../../common/markdown.js";
8
9
  import { historyDescription, historyInput, historyParameters, historyResultSchema } from "./contract.js";
@@ -7,7 +7,8 @@ import type { AgentService } from "../../services/agents/agent-service.js";
7
7
  import type { AgentOwner } from "../../model/agent.js";
8
8
  import type { TeamActor } from "../../model/team.js";
9
9
  import { object } from "../../common/json.js";
10
- import { requireThat, schema } from "../../common/validation.js";
10
+ import { requireThat } from "../../common/validation.js";
11
+ import { schema } from "../../common/schema.js";
11
12
  import { markdownFields } from "../../common/markdown.js";
12
13
  import { teamMessagesMarkdown } from "../../integrations/team-context.js";
13
14
  import { executeTeam, executeTeamMessage } from "./actions.js";
@@ -3,7 +3,8 @@ import type { TeamService } from "../../services/agents/team-service.js";
3
3
  import type { AgentService } from "../../services/agents/agent-service.js";
4
4
  import type { TeamActor } from "../../model/team.js";
5
5
  import { agentOwner } from "../../integrations/pi/agent-context.js";
6
- import { requireThat, schema } from "../../common/validation.js";
6
+ import { requireThat } from "../../common/validation.js";
7
+ import { schema } from "../../common/schema.js";
7
8
  import type { CallAccess } from "../access.js";
8
9
  import { executeTeam, executeTeamMessage } from "./actions.js";
9
10
  import { teamDescription, teamMessageDescription, teamParametersSchema, teamActionSchema, teamResultSchema, teamMessageParametersSchema, teamMessageActionSchema, teamMessageResultSchema } from "./contract.js";
@@ -90,8 +90,6 @@ export function showManagement(ctx: Context, parentSessionId: SessionId) {
90
90
  const counts = note(""), workspaceInfo = group(status); status.querySelector("header")!.after(counts); counts.classList.add("pbot-counts");
91
91
  const materials = group(status, "pbot-setting"); materials.append(element("h3", "资料目录"));
92
92
  const initializeButton = button(materials, "准备目录", async () => { await command("init", undefined, "工作区已初始化并启用。"); });
93
- const pythonCard = group(status, "pbot-setting"), pythonInfo = group(pythonCard);
94
- const pythonButton = button(pythonCard, "准备 Python", async () => { await command("python setup", undefined, "Python 准备完成。"); });
95
93
  const diagnostic = details(status, "环境详情"), statusBody = block(""); statusBody.classList.add("pbot-raw"); diagnostic.append(statusBody);
96
94
  const permissions = group(status, "pbot-setting"); permissions.hidden = true;
97
95
  let permissionKey = "";
@@ -383,27 +381,23 @@ export function showManagement(ctx: Context, parentSessionId: SessionId) {
383
381
  counts.textContent = configuration.error ? "Personal Bot 配置错误" : "Personal Bot 未启用";
384
382
  workspaceInfo.replaceChildren(facts([["状态", configuration.error ? "配置错误" : "未启用"], ["工作区", snapshot.workspaceRoot], ["配置文件", configuration.path]]),
385
383
  note(configuration.error ? "修复配置文件后执行 /pbot init。" : "执行 /pbot init,或点击下方按钮初始化并启用。"));
386
- pythonInfo.replaceChildren(note("启用工作区后自动准备共享 Python 环境。"));
387
384
  materials.hidden = false; initializeButton.textContent = "初始化并启用";
388
385
  enabled(initializeButton, !configuration.error);
389
386
  for (const [id, control] of tabs) enabled(control, id === "status");
390
- enabled(pythonButton, false); activate("status");
387
+ activate("status");
391
388
  statusBody.textContent = JSON.stringify(snapshot, null, 2);
392
389
  if (configuration.error) inform(text(configuration.error), "error");
393
390
  return;
394
391
  }
395
392
  for (const control of tabs.values()) enabled(control, true);
396
393
  materials.hidden = false; initializeButton.textContent = "准备目录"; enabled(initializeButton, true);
397
- const agents = rows(snapshot.agents), teams = rows(snapshot.teams), python = record(snapshot.python), history = record(snapshot.history);
394
+ const agents = rows(snapshot.agents), teams = rows(snapshot.teams), history = record(snapshot.history);
398
395
  tabCounts.get("experts")!.textContent = text(agents.length); tabCounts.get("teams")!.textContent = text(teams.length);
399
396
  const active = agents.filter(agent => ["starting", "busy", "stopping"].includes(text(agent.state))).length;
400
397
  counts.textContent = `Personal Bot 已启动 · 专家 ${agents.length} · 执行中 ${active} · 团队 ${teams.length}`;
401
398
  const model = object(snapshot.model) ? snapshot.model : {};
402
399
  workspaceInfo.replaceChildren(facts([["状态", "已启动"], ["工作区", snapshot.workspaceRoot], ["配置文件", record(snapshot.configuration).path], ["模型", model.model || "尚未选择"], ["Provider", model.provider || "—"],
403
400
  ["历史", history.organizing ? "整理中" : history.pending === null ? "查询时更新索引" : `${history.pending} 项待整理`]]));
404
- pythonInfo.replaceChildren(element("h3", "Python"), badge(python.state));
405
- if (python.error) pythonInfo.append(element("p", text(python.error), "pbot-warning"));
406
- enabled(pythonButton, python.state !== "preparing");
407
401
  const { agents: _agents, teams: _teams, ...summary } = snapshot; statusBody.textContent = JSON.stringify(summary, null, 2);
408
402
  const pending = rows(snapshot.permissions), nextPermissionKey = pending.map(request => text(request.agentId) + ":" + text(request.requestId)).join(",");
409
403
  permissions.hidden = !pending.length;
@@ -62,9 +62,9 @@ export const managementStyles = `
62
62
  .pbot-card > :is(h3, .pbot-between) { margin-bottom: 12px; }
63
63
  .pbot-badge { display: inline-flex; align-items: center; gap: 6px; flex-shrink: 0; color: var(--pbot-muted); background: var(--pbot-bg); padding: 3px 8px; border-radius: 6px; font-size: 12px; font-weight: 500; white-space: nowrap; }
64
64
  .pbot-badge::before { content: ""; width: 5px; height: 5px; border-radius: 50%; background: currentColor; }
65
- .pbot-badge:is([data-state=busy],[data-state=running],[data-state=starting],[data-state=preparing]) { color: var(--pbot-accent); background: var(--pbot-tint); }
65
+ .pbot-badge:is([data-state=busy],[data-state=running],[data-state=starting]) { color: var(--pbot-accent); background: var(--pbot-tint); }
66
66
  .pbot-badge:is([data-state=error],[data-state=failed]) { color: var(--pbot-danger); }
67
- .pbot-badge:is([data-state=ready],[data-state=completed]) { color: var(--dsw-alias-state-success-primary, #26834b); }
67
+ .pbot-badge[data-state=completed] { color: var(--dsw-alias-state-success-primary, #26834b); }
68
68
  .pbot-badge:is([data-state=paused],[data-state=stopping]) { color: var(--dsw-alias-state-warn-label, #9a6500); }
69
69
  .pbot-facts { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 7px 18px; margin: 12px 0; font-size: 13px; }
70
70
  .pbot-facts dt { color: var(--pbot-muted); }
@@ -1,7 +1,7 @@
1
1
  const states: Record<string, string> = {
2
2
  starting: "启动中", busy: "执行中", idle: "待命", stopping: "停止中", stopped: "已停止", error: "需要处理",
3
3
  running: "进行中", paused: "已暂停", finished: "已结束", completed: "已完成", failed: "失败",
4
- cancelled: "已取消", interrupted: "已中断", ready: "已就绪", preparing: "准备中", unprepared: "未准备",
4
+ cancelled: "已取消", interrupted: "已中断",
5
5
  open: "待安排", closed: "已关闭",
6
6
  };
7
7
  export const stateLabel = (state: unknown) => states[String(state)] ?? String(state ?? "未知");
@@ -1,14 +0,0 @@
1
- import type { Json } from "../common/json.js";
2
- interface ProcessResult {
3
- success: boolean;
4
- data: Json;
5
- raw: Json;
6
- }
7
- export declare function processEnvironment(env: Record<string, string>): {
8
- PATH: string;
9
- LANG: string;
10
- };
11
- export declare function runCommand(command: string, args: string[], input: string | undefined, cwd: string, env: Record<string, string>, signal?: AbortSignal, options?: {
12
- timeoutMs?: number;
13
- }): Promise<ProcessResult>;
14
- export {};
@@ -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,2 +0,0 @@
1
- /** Like venv activation, scoped to this Pi process; never edits shell configuration. */
2
- export declare function activatePython(directory: string): () => void;
@@ -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
- }