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.
Files changed (75) 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 +5 -5
  18. package/docs/technical-design.md +16 -21
  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/extension/acp-member.js +1 -3
  23. package/lib/extension/acp-worker.js +3 -22
  24. package/lib/extension/claude-hooks.d.ts +0 -6
  25. package/lib/extension/claude-hooks.js +5 -31
  26. package/lib/extension/dsh/acp-member.js +1 -2
  27. package/lib/extension/dsh/command.js +2 -7
  28. package/lib/extension/dsh/management.d.ts +1 -1
  29. package/lib/extension/dsh/management.js +3 -3
  30. package/lib/extension/dsh/workspace.d.ts +1 -9
  31. package/lib/extension/dsh/workspace.js +4 -29
  32. package/lib/extension/setup-cli.js +4 -4
  33. package/lib/integrations/dsh/resources.d.ts +1 -5
  34. package/lib/integrations/dsh/resources.js +2 -5
  35. package/lib/integrations/installation/processes.js +0 -15
  36. package/lib/ui/dsh/management.js +1 -9
  37. package/lib/ui/dsh/styles.d.ts +1 -1
  38. package/lib/ui/dsh/styles.js +2 -2
  39. package/lib/ui/presentation.js +1 -1
  40. package/package.json +1 -4
  41. package/resources/claude/skills/pbot/SKILL.md +2 -3
  42. package/resources/prompts/workspace.md +1 -1
  43. package/resources/references/compute.md +6 -8
  44. package/scripts/README.md +2 -6
  45. package/src/extension/acp-member.ts +1 -3
  46. package/src/extension/acp-worker.ts +3 -12
  47. package/src/extension/claude-hooks.ts +5 -25
  48. package/src/extension/command.ts +7 -16
  49. package/src/extension/dsh/acp-member.ts +1 -2
  50. package/src/extension/dsh/command.ts +2 -6
  51. package/src/extension/dsh/management.ts +3 -3
  52. package/src/extension/dsh/workspace.ts +5 -25
  53. package/src/extension/events.ts +2 -11
  54. package/src/extension/lifecycle.ts +8 -23
  55. package/src/extension/setup-cli.ts +4 -4
  56. package/src/extension/subagent-entry.ts +6 -12
  57. package/src/integrations/dsh/resources.ts +2 -5
  58. package/src/integrations/installation/processes.ts +0 -13
  59. package/src/integrations/pi/pi-agents.ts +12 -5
  60. package/src/pbot.ts +1 -2
  61. package/src/ui/dsh/management.ts +2 -8
  62. package/src/ui/dsh/styles.ts +2 -2
  63. package/src/ui/presentation.ts +1 -1
  64. package/lib/integrations/process.d.ts +0 -14
  65. package/lib/integrations/process.js +0 -48
  66. package/lib/integrations/python-activation.d.ts +0 -2
  67. package/lib/integrations/python-activation.js +0 -29
  68. package/lib/services/workspace/python-environment-service.d.ts +0 -21
  69. package/lib/services/workspace/python-environment-service.js +0 -66
  70. package/python/README.md +0 -72
  71. package/python/requirements.lock +0 -38
  72. package/scripts/setup-python.py +0 -170
  73. package/src/integrations/process.ts +0 -40
  74. package/src/integrations/python-activation.ts +0 -23
  75. package/src/services/workspace/python-environment-service.ts +0 -61
@@ -4,7 +4,6 @@ import { initializeWorkspace } from "../services/workspace/workspace-preparation
4
4
  import type { Confirmations } from "../ui/confirmation.js";
5
5
  import { readPage } from "../ui/pi/reader.js";
6
6
  import { choose } from "../ui/pi/menu.js";
7
- import { stateLabel } from "../ui/presentation.js";
8
7
  import { agentOwner } from "../integrations/pi/agent-context.js";
9
8
  import type { Lifecycle } from "./lifecycle.js";
10
9
  import { showAgents } from "./agents-command.js";
@@ -17,7 +16,7 @@ export function registerCommand(pi: ExtensionAPI, lifecycle: Lifecycle, confirma
17
16
  description: "工作区、专家、团队与历史",
18
17
  getArgumentCompletions: prefix => {
19
18
  if (/\s/.test(prefix)) return null;
20
- return ["init", "status", "history", "agents", "teams", "python"]
19
+ return ["init", "status", "history", "agents", "teams"]
21
20
  .filter(command => command.startsWith(prefix)).map(command => ({ value: command, label: command }));
22
21
  },
23
22
  handler: async (args, ctx) => {
@@ -43,38 +42,30 @@ export function registerCommand(pi: ExtensionAPI, lifecycle: Lifecycle, confirma
43
42
  async function execute(command: string | undefined, argument: string) {
44
43
  const instance = lifecycle.get();
45
44
  if (command === "status" && !argument) {
46
- const python = instance.pythonEnvironment.status;
47
- if (ctx.mode !== "tui") { ctx.ui.notify(JSON.stringify({ workspaceRoot: instance.root, release: packageVersion, enabled: true, state: "running", configuration: lifecycle.configuration, python }, null, 2), "info"); return; }
45
+ if (ctx.mode !== "tui") { ctx.ui.notify(JSON.stringify({ workspaceRoot: instance.root, release: packageVersion, enabled: true, state: "running", configuration: lifecycle.configuration }, null, 2), "info"); return; }
48
46
  const agents = instance.agents.list(agentOwner(ctx)), history = instance.history.status;
49
47
  await readPage(ctx, "工作区", [instance.root, "", "状态 已启动", `配置 ${lifecycle.configuration?.path ?? ""}`, `版本 ${packageVersion}`,
50
48
  `模型 ${ctx.model && !(ctx.model.provider === "unknown" && ctx.model.id === "unknown") ? ctx.model.provider + "/" + ctx.model.id : "未选择"}`,
51
49
  `专家 ${agents.length} 位 · ${agents.filter(value => value.alive).length} 位存活`,
52
- `Python ${stateLabel(python.state)}`, ...(python.directory ? [python.directory] : []), ...(python.error ? ["", python.error] : []),
53
50
  "", `历史 ${history.organizing ? "整理中" : history.pending === null ? "查询时更新索引" : history.pending + " 项待整理"}`,
54
51
  ...history.warnings].join("\n")); return;
55
52
  }
56
53
  if (command === "history") { await showHistory(instance, ctx, argument); return; }
57
54
  if (command === "agents") { await showAgents(pi, instance, ctx, confirmations); return; }
58
55
  if (command === "teams") { await showTeams(pi, instance, ctx, confirmations); return; }
59
- if (command === "python" && argument === "setup") {
60
- const cancel = instance.signal(ctx.signal); await ctx.waitForIdle();
61
- ctx.ui.notify("正在准备 Python…", "info");
62
- const result = await instance.preparePython(cancel);
63
- ctx.ui.notify(ctx.mode === "tui" ? "Python 已就绪。" : JSON.stringify(result, null, 2), "info"); return;
64
- }
65
- ctx.ui.notify("/pbot init | status | history [关键词] | agents | teams | python setup", "info");
56
+ ctx.ui.notify("/pbot init | status | history [关键词] | agents | teams", "info");
66
57
  }
67
58
  if (command || ctx.mode !== "tui") { await execute(command, argument); return; }
68
59
  if (confirmations.presenting) { ctx.ui.notify("请先处理待确认操作。", "info"); return; }
69
60
  for (;;) {
70
61
  const instance = lifecycle.get(), agents = instance.agents.list(agentOwner(ctx));
71
- const choices = ["专家 · " + agents.length, "团队", "历史", "工作区状态", "准备资料目录", "准备 Python"];
72
- const choice = await choose(ctx, `Personal Bot · Python ${stateLabel(instance.pythonEnvironment.status.state)}`, choices);
62
+ const choices = ["专家 · " + agents.length, "团队", "历史", "工作区状态", "准备资料目录"];
63
+ const choice = await choose(ctx, "Personal Bot", choices);
73
64
  if (!choice) return;
74
- const command = ["agents", "teams", "history", "status", "init", "python"][choices.indexOf(choice)]!;
65
+ const command = ["agents", "teams", "history", "status", "init"][choices.indexOf(choice)]!;
75
66
  try {
76
67
  if (command === "init") { await ctx.waitForIdle(); instance.check(); await initializeWorkspace(instance.root); ctx.ui.notify("资料目录已准备。", "info"); }
77
- else await execute(command, command === "python" ? "setup" : "");
68
+ else await execute(command, "");
78
69
  }
79
70
  catch (error) { ctx.ui.notify(error instanceof Error ? error.message : String(error), "error"); }
80
71
  }
@@ -25,8 +25,7 @@ export async function apply(ctx: Context) {
25
25
  await agent.ctx.plugin({ name: "pbot-acp-expert", inject, apply: async scope => {
26
26
  registerDshSkills(scope, agent);
27
27
  dshExpertTools(scope, agent, member.d.options);
28
- await dshResources(scope, agent, member.d.workspace, "general-purpose", () => process.env.PBOT_ACP_PYTHON_STATE === "ready" && process.env.VIRTUAL_ENV
29
- ? { state: "ready", directory: process.env.VIRTUAL_ENV } : { state: process.env.PBOT_ACP_PYTHON_STATE ?? "unavailable" }, member.check);
28
+ await dshResources(scope, agent, member.d.workspace, "general-purpose", member.check);
30
29
  registerDshFileEvents(scope, agent, member.d.workspace, true, member.check);
31
30
  let input: AcpInput | undefined, answer = "";
32
31
  scope.on("session/event", (session, event) => {
@@ -19,11 +19,11 @@ const validChat = schema(chatSchema);
19
19
  const approvalSchema = Type.Object({ agentId: Type.String({ minLength: 1 }), requestId: Type.String({ minLength: 1 }),
20
20
  optionId: Type.Union([Type.String({ minLength: 1 }), Type.Null()]) }, { additionalProperties: false });
21
21
  const validApproval = schema(approvalSchema);
22
- const usage = '用法:/pbot status | init | python setup | agent {"action":…} | chat {"agentId":…,"text":…} | team {"action":…} | post {"teamId":…,"text":…} | history {"action":…} | records {"agentId":…}';
22
+ const usage = '用法:/pbot status | init | agent {"action":…} | chat {"agentId":…,"text":…} | team {"action":…} | post {"teamId":…,"text":…} | history {"action":…} | records {"agentId":…}';
23
23
 
24
24
  export function registerDshCommand(ctx: Context, workspaces: DshWorkspaces, management: PbotManagement) {
25
25
  ctx.commands.register({ name: "pbot", description: "Personal Bot 工作区与协作管理", recordInput: false,
26
- input: { hint: "status | init | python setup | agent/chat/team/post/history/records JSON", attachments: true },
26
+ input: { hint: "status | init | agent/chat/team/post/history/records JSON", attachments: true },
27
27
  async handler({ agent, rawInput, signal, attachments, commandId }) {
28
28
  signal.throwIfAborted();
29
29
  const command = rawInput.trim(), split = command.search(/\s/);
@@ -42,10 +42,6 @@ export function registerDshCommand(ctx: Context, workspaces: DshWorkspaces, mana
42
42
  signal.throwIfAborted();
43
43
  const verb = split < 0 ? command : command.slice(0, split);
44
44
  requireThat(verb === "chat" || !attachments.length, "输入框附件仅用于 chat 人工对话。");
45
- if (command === "python setup") {
46
- const result = await workspaces.preparePython(); workspace.check();
47
- return { kind: "success", text: JSON.stringify(result, null, 2) };
48
- }
49
45
  requireThat(split >= 0, usage);
50
46
  const input: unknown = JSON.parse(command.slice(split));
51
47
  requireThat(object(input), "命令参数必须是 JSON 对象。");
@@ -24,11 +24,11 @@ const teamSchema = Type.Object({ teamId: Type.String({ minLength: 1 }), afterSeq
24
24
  limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 16000 })) }, { additionalProperties: false });
25
25
  const validRequest = schema(requestSchema), validExpert = schema(expertSchema), validTeam = schema(teamSchema);
26
26
 
27
- export function dshStatus(workspaces: DshWorkspaces, workspace: DshWorkspace): Json {
27
+ export function dshStatus(workspace: DshWorkspace): Json {
28
28
  workspace.check();
29
29
  const agents = workspace.agents.list(workspace.owner);
30
30
  return json({ host: "dsh", release: packageVersion, enabled: true, state: "running", workspaceRoot: workspace.root, sessionId: workspace.agent.id,
31
- model: workspace.agent.model.current() ?? null, python: workspaces.python.status,
31
+ model: workspace.agent.model.current() ?? null,
32
32
  controlError: workspace.controlError ?? null, history: workspace.history.status,
33
33
  agents, permissions: workspace.agents.pendingPermissions(workspace.owner), teams: workspace.teams.list(workspace.owner, agents) });
34
34
  }
@@ -39,7 +39,7 @@ export async function dshWorkspaceStatus(workspaces: DshWorkspaces, agent: Agent
39
39
  if (!configuration.enabled) return json({ host: "dsh", release: packageVersion, enabled: false,
40
40
  state: configuration.error ? "error" : "disabled", nextStep: configuration.error ? configuration.error : "/pbot init",
41
41
  workspaceRoot: root, sessionId: agent.id, configuration, model: agent.model.current() ?? null, agents: [], teams: [] });
42
- return json({ ...dshStatus(workspaces, await workspaces.get(agent)) as Record<string, Json>, configuration });
42
+ return json({ ...dshStatus(await workspaces.get(agent)) as Record<string, Json>, configuration });
43
43
  }
44
44
 
45
45
  /** Native Remote owns transport and access checks. These workspace reads do not admit or cancel execution. */
@@ -18,8 +18,6 @@ import { registerDshFileEvents } from "./files.js";
18
18
  import { DshHistoryWork, registerDshHistoryEvents } from "./history.js";
19
19
  import type { HistoryService } from "../../services/history/history-service.js";
20
20
  import { registerDshHistoryTool } from "../../tools/history/dsh-tool.js";
21
- import { activatePython } from "../../integrations/python-activation.js";
22
- import { PythonEnvironmentService } from "../../services/workspace/python-environment-service.js";
23
21
  import { requireThat } from "../../common/validation.js";
24
22
  import { registerDshSkills } from "../../integrations/dsh/skills.js";
25
23
  import { readWorkspaceConfig, workspaceDisabledMessage } from "../../services/workspace/workspace-config.js";
@@ -40,7 +38,7 @@ export class DshWorkspace {
40
38
  #events: DshAgentEvents | undefined;
41
39
  #closing: Promise<void> | undefined;
42
40
  constructor(readonly ctx: Context, readonly root: string, readonly agent: Agent,
43
- readonly python: PythonEnvironmentService, readonly component: AbortSignal,
41
+ readonly component: AbortSignal,
44
42
  private readonly historyWork: DshHistoryWork, private readonly releaseHistory: () => Promise<void>, acp?: AcpCommands) {
45
43
  this.history = historyWork.service;
46
44
  this.owner = { sessionId: agent.id, leaf: null, branch: [] };
@@ -53,7 +51,7 @@ export class DshWorkspace {
53
51
  this.#experts.set(d.agentId, runtime);
54
52
  scope.effect(() => () => { if (this.#experts.get(d.agentId) === runtime) this.#experts.delete(d.agentId); });
55
53
  registerDshSkills(scope, child);
56
- await dshResources(scope, child, root, "general-purpose", () => python.status, runtime.check);
54
+ await dshResources(scope, child, root, "general-purpose", runtime.check);
57
55
  const teamTool = dshExpertTools(scope, child, d.options);
58
56
  if (teamTool) registerDshTeamMessageTool(scope, child, this.teams, runtime.actor, runtime.check);
59
57
  registerDshFileEvents(scope, child, root, true, runtime.check);
@@ -77,7 +75,7 @@ export class DshWorkspace {
77
75
  this.check();
78
76
  this.#scope = await this.agent.ctx.plugin({ name: "pbot-coordinator", inject: dshDependencies, apply: async ctx => {
79
77
  registerDshSkills(ctx, this.agent);
80
- await dshResources(ctx, this.agent, this.root, "coordinator", () => this.python.status, this.check);
78
+ await dshResources(ctx, this.agent, this.root, "coordinator", this.check);
81
79
  registerDshFileEvents(ctx, this.agent, this.root, false, this.check);
82
80
  registerDshAgentTool(ctx, this.agent, this.agents, this.owner, this.check);
83
81
  registerDshTeamTool(ctx, this.agent, this.teams, this.agents, this.owner, this.check);
@@ -129,17 +127,13 @@ export class DshWorkspace {
129
127
  }
130
128
  }
131
129
 
132
- /** The execution component owns Python; closing one Session must not undo its activation. */
133
130
  export class DshWorkspaces {
134
- readonly python = new PythonEnvironmentService(process.cwd());
135
131
  readonly #parents = new Map<Agent, Promise<DshWorkspace | undefined>>();
136
132
  readonly #initializing = new Map<string, Promise<void>>();
137
133
  readonly #configurations = new Map<Agent, { root: string; configuration: WorkspaceConfiguration }>();
138
134
  readonly #parentEffects = new Map<Agent, () => Promise<void>>();
139
135
  readonly #histories = new Map<string, { work: DshHistoryWork; users: number }>();
140
136
  readonly #lifetime = new AbortController();
141
- #restorePython: (() => void) | undefined;
142
- #preparing: Promise<{ directory: string; python: string }> | undefined;
143
137
  #closing: Promise<void> | undefined;
144
138
  constructor(readonly ctx: Context) {}
145
139
 
@@ -184,14 +178,13 @@ export class DshWorkspaces {
184
178
  const history = await this.history(root);
185
179
  let workspace: DshWorkspace | undefined;
186
180
  try {
187
- workspace = new DshWorkspace(this.ctx, root, agent, this.python, this.#lifetime.signal, history.work, history.release, configuration.acp);
181
+ workspace = new DshWorkspace(this.ctx, root, agent, this.#lifetime.signal, history.work, history.release, configuration.acp);
188
182
  const owned = workspace;
189
183
  const dispose = agent.ctx.effect(() => async () => {
190
184
  this.#parents.delete(agent); this.#configurations.delete(agent); this.#parentEffects.delete(agent); await owned.close();
191
185
  });
192
186
  this.#parentEffects.set(agent, dispose);
193
187
  await workspace.open(); this.#lifetime.signal.throwIfAborted();
194
- void this.preparePython().catch(error => this.ctx.logger.warn(String(error)));
195
188
  return workspace;
196
189
  } catch (error) {
197
190
  try {
@@ -249,18 +242,6 @@ export class DshWorkspaces {
249
242
  return this.get(agent);
250
243
  }
251
244
 
252
- preparePython() {
253
- this.#lifetime.signal.throwIfAborted();
254
- if (this.#preparing) return this.#preparing;
255
- this.#preparing = (async () => {
256
- const result = await this.python.setup(this.#lifetime.signal);
257
- this.#lifetime.signal.throwIfAborted();
258
- if (!this.#restorePython) this.#restorePython = activatePython(result.directory);
259
- return result;
260
- })().finally(() => { this.#preparing = undefined; });
261
- return this.#preparing;
262
- }
263
-
264
245
  close() {
265
246
  if (this.#closing) return this.#closing;
266
247
  this.#lifetime.abort();
@@ -271,10 +252,9 @@ export class DshWorkspaces {
271
252
  const closed = await Promise.allSettled(opened.flatMap(value => value.status === "fulfilled" && value.value ? [value.value.close()] : []));
272
253
  const effects = await Promise.allSettled([...this.#parentEffects.values()].map(dispose => dispose()));
273
254
  const histories = await Promise.allSettled([...this.#histories.values()].map(value => value.work.close()));
274
- await this.python.close();
275
255
  const errors = [...new Set([...closed, ...effects, ...histories].flatMap(value => value.status === "rejected" ? [value.reason] : []))];
276
256
  if (errors.length) throw new AggregateError(errors, "部分 dsh 工作区未能完成关闭。");
277
- } finally { this.#parents.clear(); this.#configurations.clear(); this.#parentEffects.clear(); this.#histories.clear(); this.#restorePython?.(); this.#restorePython = undefined; }
257
+ } finally { this.#parents.clear(); this.#configurations.clear(); this.#parentEffects.clear(); this.#histories.clear(); }
278
258
  })();
279
259
  return this.#closing;
280
260
  }
@@ -20,14 +20,6 @@ export function registerEvents(pi: ExtensionAPI, lifecycle: Lifecycle, confirmat
20
20
  return;
21
21
  }
22
22
  ctx.ui.setStatus("pbot", "PBot 已启动");
23
- if (ctx.mode === "tui") ctx.ui.setStatus("pbot-python", "Python 准备中");
24
- else ctx.ui.notify("正在准备共享 Python 环境;首次安装可能需要数分钟。", "info");
25
- try { await lifecycle.get().preparePython(); }
26
- catch (error) {
27
- const message = error instanceof Error ? error.message : String(error);
28
- if (ctx.mode === "tui") ctx.ui.notify("Python 未就绪;/pbot status 查看详情。", "warning");
29
- else if (ctx.hasUI) ctx.ui.notify(message, "warning"); else console.error(message);
30
- } finally { if (ctx.mode === "tui") ctx.ui.setStatus("pbot-python", undefined); }
31
23
  } catch (error) {
32
24
  ctx.ui.setStatus("pbot", "PBot 启动失败");
33
25
  if (ctx.hasUI) ctx.ui.notify(error instanceof Error ? error.message : "pbot 启动失败。", "error");
@@ -46,10 +38,9 @@ export function registerEvents(pi: ExtensionAPI, lifecycle: Lifecycle, confirmat
46
38
  const role = await agentText("coordinator", instance.root);
47
39
  const workspace = await readFile(join(resourceRoot, "prompts/workspace.md"), "utf8");
48
40
  instance.check();
49
- const { state, directory } = instance.pythonEnvironment.status;
50
41
  Object.assign(event.systemPromptOptions.sections, {
51
42
  pbot_workspace: workspace,
52
- pbot_environment: JSON.stringify({ workspaceRoot: instance.root, resourceRoot, python: { state, directory } }),
43
+ pbot_environment: JSON.stringify({ workspaceRoot: instance.root, resourceRoot }),
53
44
  pbot: role,
54
45
  });
55
46
  } catch (error) {
@@ -65,7 +56,7 @@ export function registerEvents(pi: ExtensionAPI, lifecycle: Lifecycle, confirmat
65
56
  pi.on("session_shutdown", async (event, ctx) => {
66
57
  const preserve = event.reason === "reload" && lifecycle.root && (await readWorkspaceConfig(lifecycle.root)).enabled;
67
58
  try { await lifecycle.close(Boolean(preserve)); }
68
- finally { ctx.ui.setStatus("pbot", undefined); ctx.ui.setStatus("pbot-python", undefined); }
59
+ finally { ctx.ui.setStatus("pbot", undefined); }
69
60
  });
70
61
  pi.on("tool_call", async (event, ctx) => {
71
62
  const instance = lifecycle.active;
@@ -1,9 +1,7 @@
1
1
  import { realpath } from "node:fs/promises";
2
- import { activatePython } from "../integrations/python-activation.js";
3
2
  import { requireThat } from "../common/validation.js";
4
3
  import { authorizeMutation } from "../services/workspace/workspace-files.js";
5
4
  import type { AgentOwner } from "../model/agent.js";
6
- import type { PythonEnvironmentService } from "../services/workspace/python-environment-service.js";
7
5
  import type { AgentService } from "../services/agents/agent-service.js";
8
6
  import type { TeamService } from "../services/agents/team-service.js";
9
7
  import type { CallAccess } from "../tools/access.js";
@@ -15,18 +13,7 @@ export class WorkspaceInstance implements CallAccess {
15
13
  readonly #controller = new AbortController();
16
14
  #work = new AbortController();
17
15
  #closing: Promise<void> | undefined;
18
- #restorePython: (() => void) | undefined;
19
- constructor(readonly root: string, readonly pythonEnvironment: PythonEnvironmentService, readonly agents: AgentService,
20
- readonly teams: TeamService, readonly history: HistoryService) {}
21
- async preparePython(signal?: AbortSignal) {
22
- this.check();
23
- this.#restorePython?.();
24
- this.#restorePython = undefined;
25
- const result = await this.pythonEnvironment.setup(signal);
26
- this.check();
27
- this.#restorePython ??= activatePython(result.directory);
28
- return result;
29
- }
16
+ constructor(readonly root: string, readonly agents: AgentService, readonly teams: TeamService, readonly history: HistoryService) {}
30
17
  check() {
31
18
  requireThat(!this.#controller.signal.aborted, "pbot 工作区实例已关闭。");
32
19
  }
@@ -49,15 +36,13 @@ export class WorkspaceInstance implements CallAccess {
49
36
  this.#controller.abort();
50
37
  this.#work.abort();
51
38
  this.#closing = (async () => {
52
- try {
53
- const errors: unknown[] = [];
54
- try { if (this.agentOwner) this.teams.pauseAll(this.agentOwner, "主会话关闭或重新载入"); }
55
- catch (error) { errors.push(error); }
56
- this.teams.dispose();
57
- const results = await Promise.allSettled([this.agents.close(this.agentOwner, preserveAgents), this.pythonEnvironment.close(), this.history.close()]);
58
- errors.push(...results.filter(result => result.status === "rejected").map(result => result.reason));
59
- if (errors.length) throw new AggregateError(errors, "工作区关闭失败。");
60
- } finally { this.#restorePython?.(); this.#restorePython = undefined; }
39
+ const errors: unknown[] = [];
40
+ try { if (this.agentOwner) this.teams.pauseAll(this.agentOwner, "主会话关闭或重新载入"); }
41
+ catch (error) { errors.push(error); }
42
+ this.teams.dispose();
43
+ const results = await Promise.allSettled([this.agents.close(this.agentOwner, preserveAgents), this.history.close()]);
44
+ errors.push(...results.filter(result => result.status === "rejected").map(result => result.reason));
45
+ if (errors.length) throw new AggregateError(errors, "工作区关闭失败。");
61
46
  })();
62
47
  return this.#closing;
63
48
  }
@@ -21,7 +21,7 @@ export async function main(args: string[]): Promise<number> {
21
21
  if (options.action === "help") {
22
22
  console.log("Personal Bot " + manifest.version + "\n\n用法:pbot setup [--workspace <目录>]\n" +
23
23
  " npx personal-bot@latest setup\n\nsetup 安装或升级 Pi、pbot 和选中的插件,然后启动 Pi 执行 /pbot init。\n" +
24
- "支持 Linux/macOS,需要 Node.js 22.19+、npm 和 Python 3.11+。\n--help 显示帮助;--version 显示安装器版本。");
24
+ "支持 Linux/macOS,需要 Node.js 22.19+ 和 npm。\n--help 显示帮助;--version 显示安装器版本。");
25
25
  return 0;
26
26
  }
27
27
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
@@ -33,7 +33,7 @@ export async function main(args: string[]): Promise<number> {
33
33
  const ui = new SetupUI(controller), processes = new SetupProcesses(controller.signal);
34
34
  try {
35
35
  const cwd = process.cwd();
36
- ui.text("Personal Bot " + manifest.version + " — 安装与升级\n正在检查 Node/npm、Python 和 tmux…");
36
+ ui.text("Personal Bot " + manifest.version + " — 安装与升级\n正在检查 Node/npm 和 tmux…");
37
37
  const system = await inspectSystem(processes, cwd);
38
38
  const supplied = options.workspace ?? await ui.ask("工作区目录(当前、已有或新建目录)", cwd);
39
39
  const workspace = await resolveWorkspace(supplied, cwd, homedir());
@@ -84,14 +84,14 @@ export async function main(args: string[]): Promise<number> {
84
84
  }
85
85
  const blocking = choices.find(choice => choice.required && choice.error);
86
86
  if (blocking) throw new Error(blocking.error);
87
- ui.text("升级前请停止活动 pbot 子会话和相关 Python 脚本。Pi 为当前用户共用,插件只处理此工作区。");
87
+ ui.text("升级前请停止活动 pbot 子会话。Pi 为当前用户共用,插件只处理此工作区。");
88
88
  if (!await ui.confirm("执行以上计划")) return 130;
89
89
  await mkdir(workspace, { recursive: true });
90
90
  if (await realpath(workspace) !== workspace) throw new Error("工作区路径已发生变化,请重新运行 setup。");
91
91
  const result = await executeSetup(plan, host, item => ui.text("[" + item.state + "] " + item.name + ": " + item.detail), controller.signal);
92
92
  const failed = result.results.some(item => item.state === "failed");
93
93
  if (!result.pi) return 1;
94
- ui.text("\n软件安装阶段结束。初始化、Python 环境和外部服务的状态由 Pi/pbot/插件分别报告。");
94
+ ui.text("\n软件安装阶段结束。工作区初始化和外部服务的状态由 Pi/pbot/插件分别报告。");
95
95
  if (await ui.confirm(failed ? "部分插件失败,是否仍启动 Pi 并初始化启用工作区" : "启动 Pi 并初始化启用工作区", !failed)) {
96
96
  process.stdin.pause();
97
97
  await host.start(result.pi, workspace);
@@ -11,8 +11,6 @@ import { teamContext } from "../integrations/pi/team-context.js";
11
11
  import { teamBrief } from "../integrations/team-context.js";
12
12
  import { readAgentSession } from "../integrations/pi/pi-agents.js";
13
13
  import type { TeamLink } from "../model/team.js";
14
- import { PythonEnvironmentService } from "../services/workspace/python-environment-service.js";
15
- import { activatePython } from "../integrations/python-activation.js";
16
14
  import { authorizeMutation } from "../services/workspace/workspace-files.js";
17
15
  import { agentText } from "../integrations/agent-resources.js";
18
16
  import { agentInput } from "../integrations/pi/agent-input.js";
@@ -38,7 +36,7 @@ export default async function subagent(pi: ExtensionAPI) {
38
36
  let activeTeam: TeamLink | undefined, pendingPause: string | undefined;
39
37
  let ready = false, disposed = false;
40
38
  let ctx: ExtensionContext | undefined, timer: ReturnType<typeof setInterval> | undefined;
41
- let python: PythonEnvironmentService | undefined, restorePython: (() => void) | undefined;
39
+ let initialized = false;
42
40
  let processing = false, closing = false, startLeaf: string | null = null;
43
41
  const execution = new AgentRun(files, id, generation);
44
42
  let lastActivity = 0;
@@ -47,7 +45,7 @@ export default async function subagent(pi: ExtensionAPI) {
47
45
  lifetime.signal.throwIfAborted(); files.check();
48
46
  const run = files.read(id, "launch.json", launch);
49
47
  requireThat(run.generation === generation && !run.stop, "子会话已停止或启动代次变化。");
50
- requireThat(python, "子会话尚未就绪。");
48
+ requireThat(initialized, "子会话尚未就绪。");
51
49
  };
52
50
  const bindSession = () => {
53
51
  const file = ctx?.sessionManager.getSessionFile();
@@ -79,7 +77,7 @@ export default async function subagent(pi: ExtensionAPI) {
79
77
  teams.files.setReady(id, generation, false); ready = false;
80
78
  pauseTeam("成员停止");
81
79
  save({ state: "stopping", activity: "停止" });
82
- } finally { try { await python?.close(); } finally { ctx?.shutdown(); } }
80
+ } finally { ctx?.shutdown(); }
83
81
  };
84
82
  const pump = async () => {
85
83
  if (processing || !ctx || closing) return;
@@ -175,9 +173,7 @@ export default async function subagent(pi: ExtensionAPI) {
175
173
  })) pi.registerTool(tool);
176
174
  // Keep the native CLI loadout, including MCP exposure and explicit --tools choices.
177
175
  pi.setActiveTools(active);
178
- python = new PythonEnvironmentService(d.workspace);
179
- try { const result = await python.setup(lifetime.signal); restorePython = activatePython(result.directory); }
180
- catch (error) { ctx.ui.notify(String(error), "warning"); }
176
+ initialized = true;
181
177
  save({ state: "idle", activity: "空闲" });
182
178
  ready = !pendingPause && pi.getActiveTools().includes("pbot_team_message");
183
179
  teams.files.setReady(id, generation, ready);
@@ -195,7 +191,6 @@ export default async function subagent(pi: ExtensionAPI) {
195
191
  ctx = context;
196
192
  try {
197
193
  ensure(); bindSession();
198
- requireThat(python, "子会话计算环境状态不可用。");
199
194
  const workspace = await readFile(join(resourceRoot, "prompts/workspace.md"), "utf8");
200
195
  const role = await agentText("general-purpose", d.workspace);
201
196
  let brief: string | undefined, message;
@@ -205,9 +200,8 @@ export default async function subagent(pi: ExtensionAPI) {
205
200
  brief = teamBrief(link);
206
201
  message = teamContext(link, context, link.request.throughSeq);
207
202
  }
208
- const { state, directory } = python.status;
209
203
  Object.assign(event.systemPromptOptions.sections, {
210
- pbot_environment: JSON.stringify({ workspaceRoot: d.workspace, resourceRoot, python: { state, directory } }),
204
+ pbot_environment: JSON.stringify({ workspaceRoot: d.workspace, resourceRoot }),
211
205
  pbot_workspace: workspace, pbot_child: role,
212
206
  });
213
207
  if (brief) event.systemPromptOptions.sections.pbot_team = brief;
@@ -270,7 +264,7 @@ export default async function subagent(pi: ExtensionAPI) {
270
264
  if (execution.current) finish(true);
271
265
  if (event.reason !== "reload" && execution.state !== "error") save({ state: "stopped", activity: "已停止" });
272
266
  } finally {
273
- try { await python?.close(); } finally { restorePython?.(); teams.dispose(); ctx = undefined; }
267
+ initialized = false; teams.dispose(); ctx = undefined;
274
268
  }
275
269
  });
276
270
  }
@@ -11,17 +11,14 @@ import { requireThat } from "../../common/validation.js";
11
11
  import type { AgentOptions } from "../../model/agent.js";
12
12
 
13
13
  export async function dshResources(ctx: Context, _agent: Agent, root: string,
14
- role: "coordinator" | "general-purpose", python: () => { state: string; directory?: string; error?: string }, check: () => void) {
14
+ role: "coordinator" | "general-purpose", check: () => void) {
15
15
  const read = () => Promise.all([agentText(role, root), readFile(join(resourceRoot, "prompts/workspace.md"), "utf8")]);
16
16
  const [text, workspace] = await read();
17
17
  check();
18
18
  ctx.systemPrompt.section({ name: "pbot:role", order: 1, text, interpolate: false });
19
19
  ctx.systemPrompt.section({ name: "pbot:workspace", order: 2, text: workspace, interpolate: false });
20
20
  ctx.systemPrompt.context({ name: "pbot:environment", order: 300, required: true, interpolate: false,
21
- text: () => {
22
- const { state, directory } = python();
23
- return JSON.stringify({ workspaceRoot: root, resourceRoot, python: { state, ...(directory ? { directory } : {}) } });
24
- } });
21
+ text: JSON.stringify({ workspaceRoot: root, resourceRoot }) });
25
22
  ctx.on("system-prompt/assemble", async (_assembly, _context, next) => {
26
23
  check();
27
24
  const [roleText, workspaceText] = await read();
@@ -100,19 +100,6 @@ export async function inspectSystem(processes: SetupProcesses, cwd: string): Pro
100
100
  if (major < 22 || major === 22 && minor < 19) throw new Error("需要 Node.js 22.19 或更高版本。");
101
101
  const npm = await findExecutable("npm", processes.env);
102
102
  if (!npm) throw new Error("未找到 npm。请先安装 Node.js/npm。");
103
- const python = await findExecutable("python3", processes.env) ?? await findExecutable("python", processes.env);
104
- if (!python) throw new Error("需要 Python 3.11+ 和 venv/ensurepip。请先安装后重试。");
105
- try {
106
- await processes.run(python, ["-I", "-B", "-c", [
107
- "import sys, tempfile, venv, ensurepip",
108
- "assert sys.version_info >= (3, 11), 'Python 3.11+ required'",
109
- "with tempfile.TemporaryDirectory(prefix='pbot-python-check-') as path:",
110
- " venv.EnvBuilder(with_pip=True).create(path)",
111
- ].join("\n")], cwd);
112
- } catch (error) {
113
- processes.signal.throwIfAborted();
114
- throw new Error("基础 Python 检查失败。需要 Python 3.11+ 和 venv/ensurepip;Debian/Ubuntu 还需 python3-venv。\n" + String(error));
115
- }
116
103
  const tmux = await findExecutable("tmux", processes.env);
117
104
  if (tmux) { await processes.run(tmux, ["-V"], cwd); return { npm }; }
118
105
  const names = process.platform === "darwin" ? ["brew"] : ["apt-get", "dnf", "pacman", "zypper", "apk", "sudo"];
@@ -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);
@@ -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 {};