personal-bot 0.2.20 → 0.3.1
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 -5
- package/.mcp.json +11 -0
- package/CONTEXT.md +17 -73
- package/README.md +41 -120
- package/README.zh-CN.md +41 -120
- package/docs/README.md +31 -23
- package/docs/architecture/design.md +74 -0
- package/docs/architecture/extensibility.md +78 -0
- package/docs/architecture/model-context.md +31 -0
- package/docs/architecture/model-instruction-guidelines.md +34 -0
- package/docs/architecture/principles.md +33 -0
- package/docs/guides/capabilities.md +36 -0
- package/docs/guides/cross-harness-workers.md +83 -0
- package/docs/guides/history.md +25 -0
- package/docs/guides/workspace-configuration.md +102 -0
- package/docs/hosts/antigravity.md +52 -0
- package/docs/hosts/claude-code.md +47 -0
- package/docs/hosts/dsh.md +67 -0
- package/docs/hosts/pi.md +49 -0
- package/docs/maintainers/release.md +59 -0
- package/hooks/hooks.json +0 -3
- package/lib/antigravity-plugin/hooks.json +23 -0
- package/lib/antigravity-plugin/lib/claude.d.ts +1 -0
- package/lib/antigravity-plugin/lib/claude.js +13 -0
- package/lib/antigravity-plugin/lib/common/json.d.ts +6 -0
- package/lib/antigravity-plugin/lib/common/json.js +16 -0
- package/lib/antigravity-plugin/lib/common/paths.d.ts +1 -0
- package/lib/antigravity-plugin/lib/common/paths.js +2 -0
- package/lib/antigravity-plugin/lib/common/validation.d.ts +3 -0
- package/lib/antigravity-plugin/lib/common/validation.js +8 -0
- package/lib/antigravity-plugin/lib/common/version.d.ts +3 -0
- package/lib/antigravity-plugin/lib/common/version.js +13 -0
- package/lib/antigravity-plugin/lib/extension/acp-worker.js +11597 -0
- package/lib/antigravity-plugin/lib/extension/mcp.js +2715 -0
- package/lib/antigravity-plugin/lib/extension/plugin-runtime.d.ts +10 -0
- package/lib/antigravity-plugin/lib/extension/plugin-runtime.js +67 -0
- package/lib/antigravity-plugin/lib/integrations/agent-resources.d.ts +16 -0
- package/lib/antigravity-plugin/lib/integrations/agent-resources.js +56 -0
- package/lib/antigravity-plugin/lib/integrations/hosts/antigravity.d.ts +4 -0
- package/lib/antigravity-plugin/lib/integrations/hosts/antigravity.js +79 -0
- package/lib/antigravity-plugin/lib/integrations/hosts/claude.d.ts +3 -0
- package/lib/antigravity-plugin/lib/integrations/hosts/claude.js +60 -0
- package/lib/antigravity-plugin/lib/integrations/hosts/registry.d.ts +15 -0
- package/lib/antigravity-plugin/lib/integrations/hosts/registry.js +34 -0
- package/lib/antigravity-plugin/lib/model/acp.d.ts +164 -0
- package/lib/antigravity-plugin/lib/model/acp.js +12 -0
- package/lib/antigravity-plugin/lib/model/plugin-host.d.ts +48 -0
- package/lib/antigravity-plugin/lib/model/workspace-config.d.ts +24 -0
- package/lib/antigravity-plugin/lib/model/workspace-config.js +1 -0
- package/lib/antigravity-plugin/lib/model/workspace-mcp.d.ts +51 -0
- package/lib/antigravity-plugin/lib/model/workspace-mcp.js +4 -0
- package/lib/antigravity-plugin/lib/plugin.d.ts +1 -0
- package/lib/antigravity-plugin/lib/plugin.js +17 -0
- package/lib/antigravity-plugin/lib/services/workspace/workspace-config.d.ts +8 -0
- package/lib/antigravity-plugin/lib/services/workspace/workspace-config.js +95 -0
- package/lib/antigravity-plugin/lib/services/workspace/workspace-preparation.d.ts +3 -0
- package/lib/antigravity-plugin/lib/services/workspace/workspace-preparation.js +26 -0
- package/lib/antigravity-plugin/lib/services/workspace/workspace-skills.d.ts +8 -0
- package/lib/antigravity-plugin/lib/services/workspace/workspace-skills.js +91 -0
- package/lib/antigravity-plugin/lib/storage/atomic-json.d.ts +11 -0
- package/lib/antigravity-plugin/lib/storage/atomic-json.js +101 -0
- package/lib/antigravity-plugin/mcp_config.json +13 -0
- package/lib/antigravity-plugin/package.json +6 -0
- package/lib/antigravity-plugin/plugin.json +7 -0
- package/lib/antigravity-plugin/resources/agents/coordinator.md +11 -0
- package/{resources/claude → lib/antigravity-plugin/resources}/agents/general-purpose.md +0 -5
- package/lib/antigravity-plugin/resources/prompts/plugin-coordinator.md +1 -0
- package/lib/antigravity-plugin/resources/prompts/workspace.md +31 -0
- package/lib/antigravity-plugin/resources/references/compute-finance.md +22 -0
- package/lib/antigravity-plugin/resources/references/compute.md +16 -0
- package/lib/antigravity-plugin/resources/references/task-conductor.md +25 -0
- package/lib/antigravity-plugin/resources/templates/workspace-agents.md +21 -0
- package/lib/antigravity-plugin/skills/pbot/SKILL.md +16 -0
- package/lib/antigravity-plugin/skills/project-maintenance/SKILL.md +35 -0
- package/lib/antigravity-plugin/skills/provider-connections/SKILL.md +42 -0
- package/lib/claude.js +4 -11
- package/lib/client.js +14 -531
- package/lib/common/markdown.js +2 -3
- package/lib/common/validation.d.ts +2 -0
- package/lib/common/validation.js +4 -0
- package/lib/extension/acp-member.d.ts +2 -0
- package/lib/extension/acp-member.js +9 -8
- package/lib/extension/acp-worker.js +11578 -121
- package/lib/extension/dsh/acp-member.js +26 -2
- package/lib/extension/dsh/command.js +19 -57
- package/lib/extension/dsh/history.js +2 -4
- package/lib/extension/dsh/management.d.ts +0 -2
- package/lib/extension/dsh/management.js +27 -126
- package/lib/extension/dsh/workspace.d.ts +5 -47
- package/lib/extension/dsh/workspace.js +76 -108
- package/lib/extension/mcp-bridge.d.ts +41 -0
- package/lib/extension/mcp-bridge.js +412 -0
- package/lib/extension/mcp-workers.d.ts +980 -0
- package/lib/extension/mcp-workers.js +882 -0
- package/lib/extension/mcp.js +2715 -0
- package/lib/extension/plugin-runtime.d.ts +10 -0
- package/lib/extension/plugin-runtime.js +67 -0
- package/lib/extension/setup-cli.js +215 -2
- package/lib/integrations/acp/agents.d.ts +10 -11
- package/lib/integrations/acp/agents.js +65 -33
- package/lib/integrations/acp/claude.d.ts +2 -2
- package/lib/integrations/acp/claude.js +5 -3
- package/lib/integrations/acp/connection.d.ts +17 -4
- package/lib/integrations/acp/connection.js +53 -27
- package/lib/integrations/acp/executable.d.ts +3 -0
- package/lib/integrations/acp/executable.js +42 -0
- package/lib/integrations/acp/harnesses/claude.d.ts +2 -0
- package/lib/integrations/acp/harnesses/claude.js +49 -0
- package/lib/integrations/acp/harnesses/dsh.d.ts +2 -0
- package/lib/integrations/acp/harnesses/dsh.js +35 -0
- package/lib/integrations/acp/harnesses/generic.d.ts +13 -0
- package/lib/integrations/acp/harnesses/generic.js +37 -0
- package/lib/integrations/acp/harnesses/pi.d.ts +2 -0
- package/lib/integrations/acp/harnesses/pi.js +34 -0
- package/lib/integrations/acp/harnesses/presets.d.ts +3 -0
- package/lib/integrations/acp/harnesses/presets.js +20 -0
- package/lib/integrations/acp/launch.d.ts +33 -4
- package/lib/integrations/acp/launch.js +60 -48
- package/lib/integrations/acp/mcp.d.ts +6 -0
- package/lib/integrations/acp/mcp.js +40 -0
- package/lib/integrations/acp/model-selection.d.ts +9 -2
- package/lib/integrations/acp/model-selection.js +73 -27
- package/lib/integrations/acp/registry.d.ts +18 -0
- package/lib/integrations/acp/registry.js +50 -0
- package/lib/integrations/agent-resources.d.ts +16 -1
- package/lib/integrations/agent-resources.js +45 -9
- package/lib/integrations/dsh/mcp.d.ts +4 -0
- package/lib/integrations/dsh/mcp.js +28 -0
- package/lib/integrations/dsh/resources.d.ts +3 -3
- package/lib/integrations/dsh/resources.js +21 -12
- package/lib/integrations/dsh/skills.d.ts +5 -1
- package/lib/integrations/dsh/skills.js +10 -6
- package/lib/integrations/hosts/antigravity.d.ts +4 -0
- package/lib/integrations/hosts/antigravity.js +79 -0
- package/lib/integrations/hosts/claude.d.ts +3 -0
- package/lib/integrations/hosts/claude.js +60 -0
- package/lib/integrations/hosts/registry.d.ts +15 -0
- package/lib/integrations/hosts/registry.js +34 -0
- package/lib/model/acp.d.ts +107 -2
- package/lib/model/acp.js +12 -1
- package/lib/model/agent.d.ts +35 -33
- package/lib/model/plugin-host.d.ts +48 -0
- package/lib/model/plugin-host.js +1 -0
- package/lib/model/workspace-config.d.ts +12 -0
- package/lib/model/workspace-mcp.d.ts +51 -0
- package/lib/model/workspace-mcp.js +4 -0
- package/lib/plugin.d.ts +1 -0
- package/lib/plugin.js +17 -0
- package/lib/services/agents/acp-run.d.ts +13 -1
- package/lib/services/agents/acp-run.js +30 -2
- package/lib/services/agents/agent-service.d.ts +35 -120
- package/lib/services/agents/agent-service.js +156 -160
- package/lib/services/installation/setup-service.js +17 -1
- package/lib/services/workspace/workspace-config.d.ts +2 -1
- package/lib/services/workspace/workspace-config.js +43 -9
- package/lib/services/workspace/workspace-mcp.d.ts +14 -0
- package/lib/services/workspace/workspace-mcp.js +200 -0
- package/lib/services/workspace/workspace-skills.d.ts +8 -0
- package/lib/services/workspace/workspace-skills.js +91 -0
- package/lib/storage/acp-files.d.ts +3 -1
- package/lib/storage/acp-files.js +32 -2
- package/lib/storage/acp-history.d.ts +3 -2
- package/lib/storage/acp-history.js +19 -7
- package/lib/storage/agent-files.d.ts +8 -8
- package/lib/storage/agent-files.js +27 -47
- package/lib/tools/history/contract.d.ts +1 -1
- package/lib/tools/history/contract.js +17 -11
- package/lib/ui/dsh/index.js +8 -3
- package/lib/ui/dsh/management.d.ts +1 -1
- package/lib/ui/dsh/management.js +24 -456
- package/lib/ui/dsh/remote.d.ts +0 -2
- package/lib/ui/dsh/remote.js +1 -1
- package/package.json +12 -7
- package/resources/agents/coordinator.md +2 -2
- package/resources/antigravity/skills/pbot/SKILL.md +16 -0
- package/resources/claude/skills/pbot/SKILL.md +1 -1
- package/resources/prompts/history-coordinator.md +1 -0
- package/resources/prompts/plugin-coordinator.md +1 -0
- package/resources/prompts/workspace.md +9 -8
- package/resources/references/compute.md +9 -11
- package/resources/references/task-conductor.md +12 -26
- package/resources/skills/project-maintenance/SKILL.md +16 -21
- package/resources/skills/provider-connections/SKILL.md +24 -40
- package/resources/templates/workspace-agents.md +4 -0
- package/scripts/README.md +17 -34
- package/src/claude.ts +4 -8
- package/src/common/markdown.ts +2 -3
- package/src/common/validation.ts +6 -0
- package/src/extension/acp-member.ts +9 -8
- package/src/extension/acp-worker.ts +239 -97
- package/src/extension/command.ts +38 -36
- package/src/extension/dsh/acp-member.ts +21 -2
- package/src/extension/dsh/command.ts +21 -51
- package/src/extension/dsh/files.ts +1 -0
- package/src/extension/dsh/history.ts +9 -6
- package/src/extension/dsh/management.ts +27 -58
- package/src/extension/dsh/workspace.ts +88 -99
- package/src/extension/events.ts +13 -10
- package/src/extension/history.ts +2 -50
- package/src/extension/lifecycle.ts +37 -22
- package/src/extension/mcp-bridge.ts +412 -0
- package/src/extension/mcp-workers.ts +941 -0
- package/src/extension/pi-acp-member.ts +29 -5
- package/src/extension/plugin-runtime.ts +63 -0
- package/src/extension/setup-cli.ts +186 -2
- package/src/integrations/acp/agents.ts +70 -24
- package/src/integrations/acp/claude.ts +11 -4
- package/src/integrations/acp/connection.ts +63 -25
- package/src/integrations/acp/executable.ts +41 -0
- package/src/integrations/acp/harnesses/claude.ts +50 -0
- package/src/integrations/acp/harnesses/dsh.ts +40 -0
- package/src/integrations/acp/harnesses/generic.ts +52 -0
- package/src/integrations/acp/harnesses/pi.ts +35 -0
- package/src/integrations/acp/harnesses/presets.ts +22 -0
- package/src/integrations/acp/launch.ts +69 -47
- package/src/integrations/acp/mcp.ts +43 -0
- package/src/integrations/acp/model-selection.ts +68 -25
- package/src/integrations/acp/registry.ts +60 -0
- package/src/integrations/agent-resources.ts +70 -6
- package/src/integrations/dsh/mcp.ts +30 -0
- package/src/integrations/dsh/resources.ts +28 -13
- package/src/integrations/dsh/skills.ts +16 -6
- package/src/integrations/hosts/antigravity.ts +83 -0
- package/src/integrations/hosts/claude.ts +62 -0
- package/src/integrations/hosts/registry.ts +42 -0
- package/src/integrations/pi/mcp.ts +26 -0
- package/src/mcp.ts +14 -0
- package/src/model/acp.ts +113 -3
- package/src/model/agent.ts +18 -14
- package/src/model/plugin-host.ts +39 -0
- package/src/model/workspace-config.ts +14 -0
- package/src/model/workspace-mcp.ts +64 -0
- package/src/pbot.ts +69 -20
- package/src/plugin.ts +19 -0
- package/src/services/agents/acp-run.ts +35 -3
- package/src/services/agents/agent-service.ts +180 -160
- package/src/services/installation/setup-service.ts +17 -2
- package/src/services/workspace/workspace-config.ts +46 -8
- package/src/services/workspace/workspace-mcp.ts +242 -0
- package/src/services/workspace/workspace-skills.ts +78 -0
- package/src/storage/acp-files.ts +32 -3
- package/src/storage/acp-history.ts +18 -7
- package/src/storage/agent-files.ts +27 -41
- package/src/tools/history/contract.ts +17 -11
- package/src/tools/register.ts +4 -8
- package/src/ui/dsh/index.ts +8 -3
- package/src/ui/dsh/management.ts +40 -282
- package/src/ui/dsh/remote.ts +2 -2
- package/docs/adr/0001-claude-skill-discovery.md +0 -3
- package/docs/adr/0002-claude-native-collaboration.md +0 -3
- package/docs/agent-collaboration.md +0 -190
- package/docs/architecture-guidelines.md +0 -37
- package/docs/capability-design.md +0 -55
- package/docs/claude-code-design.md +0 -44
- package/docs/claude-code.md +0 -57
- package/docs/dsh.md +0 -337
- package/docs/file-storage.md +0 -97
- package/docs/history.md +0 -54
- package/docs/installation-design.md +0 -86
- package/docs/interaction-design.md +0 -21
- package/docs/model-context.md +0 -76
- package/docs/model-instruction-guidelines.md +0 -51
- package/docs/release.md +0 -108
- package/docs/technical-design.md +0 -163
- package/docs/workspace-configuration.md +0 -79
- package/lib/extension/claude-hooks.d.ts +0 -9
- package/lib/extension/claude-hooks.js +0 -78
- package/lib/extension/dsh/agent-events.d.ts +0 -24
- package/lib/extension/dsh/agent-events.js +0 -242
- package/lib/extension/dsh/agent-runtime.d.ts +0 -49
- package/lib/extension/dsh/agent-runtime.js +0 -351
- package/lib/integrations/dsh/dsh-agents.d.ts +0 -30
- package/lib/integrations/dsh/dsh-agents.js +0 -104
- package/lib/integrations/dsh/input.d.ts +0 -21
- package/lib/integrations/dsh/input.js +0 -62
- package/lib/integrations/dsh/notifications.d.ts +0 -8
- package/lib/integrations/dsh/notifications.js +0 -55
- package/lib/integrations/dsh/session.d.ts +0 -14
- package/lib/integrations/dsh/session.js +0 -60
- package/lib/integrations/team-context.d.ts +0 -18
- package/lib/integrations/team-context.js +0 -61
- package/lib/model/team.d.ts +0 -85
- package/lib/services/agents/agent-notices.d.ts +0 -13
- package/lib/services/agents/agent-notices.js +0 -25
- package/lib/services/agents/start-options.d.ts +0 -4
- package/lib/services/agents/start-options.js +0 -20
- package/lib/services/agents/team-service.d.ts +0 -168
- package/lib/services/agents/team-service.js +0 -345
- package/lib/storage/team-files.d.ts +0 -16
- package/lib/storage/team-files.js +0 -111
- package/lib/tools/agents/actions.d.ts +0 -62
- package/lib/tools/agents/actions.js +0 -62
- package/lib/tools/agents/contract.d.ts +0 -181
- package/lib/tools/agents/contract.js +0 -84
- package/lib/tools/agents/dsh-tool.d.ts +0 -5
- package/lib/tools/agents/dsh-tool.js +0 -34
- package/lib/tools/result.d.ts +0 -18
- package/lib/tools/result.js +0 -10
- package/lib/tools/teams/actions.d.ts +0 -23
- package/lib/tools/teams/actions.js +0 -40
- package/lib/tools/teams/contract.d.ts +0 -201
- package/lib/tools/teams/contract.js +0 -91
- package/lib/tools/teams/dsh-tool.d.ts +0 -8
- package/lib/tools/teams/dsh-tool.js +0 -39
- package/lib/ui/dsh/attachments.d.ts +0 -5
- package/lib/ui/dsh/attachments.js +0 -39
- package/resources/prompts/claude-coordinator.md +0 -1
- package/resources/prompts/native-coordinator.md +0 -1
- package/resources/prompts/team-member.md +0 -7
- package/src/extension/agent-events.ts +0 -210
- package/src/extension/agents-command.ts +0 -89
- package/src/extension/claude-hooks.ts +0 -74
- package/src/extension/dsh/agent-events.ts +0 -148
- package/src/extension/dsh/agent-runtime.ts +0 -252
- package/src/extension/subagent-entry.ts +0 -270
- package/src/extension/teams-command.ts +0 -67
- package/src/integrations/dsh/dsh-agents.ts +0 -97
- package/src/integrations/dsh/input.ts +0 -66
- package/src/integrations/dsh/notifications.ts +0 -46
- package/src/integrations/pi/agent-context.ts +0 -18
- package/src/integrations/pi/agent-input.ts +0 -19
- package/src/integrations/pi/pi-agents.ts +0 -84
- package/src/integrations/pi/team-context.ts +0 -26
- package/src/integrations/team-context.ts +0 -64
- package/src/model/team.ts +0 -29
- package/src/services/agents/agent-notices.ts +0 -28
- package/src/services/agents/start-options.ts +0 -19
- package/src/services/agents/team-service.ts +0 -275
- package/src/storage/team-files.ts +0 -93
- package/src/tools/agents/actions.ts +0 -57
- package/src/tools/agents/contract.ts +0 -101
- package/src/tools/agents/dsh-tool.ts +0 -37
- package/src/tools/agents/tool.ts +0 -20
- package/src/tools/teams/actions.ts +0 -34
- package/src/tools/teams/contract.ts +0 -109
- package/src/tools/teams/dsh-tool.ts +0 -45
- package/src/tools/teams/tool.ts +0 -29
- package/src/ui/agent-display.ts +0 -14
- package/src/ui/dsh/attachments.ts +0 -42
- package/src/ui/pi/menu.ts +0 -37
- package/src/ui/pi/reader.ts +0 -46
- /package/lib/{model/team.js → antigravity-plugin/lib/model/plugin-host.js} +0 -0
|
@@ -0,0 +1,941 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { realpath, stat } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { isAbsolute, join } from "node:path";
|
|
5
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
6
|
+
import { object } from "../common/json.js";
|
|
7
|
+
import { isAcpBackend, requireThat } from "../common/validation.js";
|
|
8
|
+
import { packageVersion } from "../common/version.js";
|
|
9
|
+
import { AcpWorkerHost } from "../integrations/acp/agents.js";
|
|
10
|
+
import { canonicalAcpBackend, inspectAcpBackends, knownAcpBackends } from "../integrations/acp/launch.js";
|
|
11
|
+
import {
|
|
12
|
+
mcpWorkerToolNames,
|
|
13
|
+
type AcpCommands,
|
|
14
|
+
type AcpElicitationAction,
|
|
15
|
+
type AcpElicitationContent,
|
|
16
|
+
type AcpModelSelection,
|
|
17
|
+
type McpWorkerToolName,
|
|
18
|
+
} from "../model/acp.js";
|
|
19
|
+
import { workspaceMcpToolNames, type WorkspaceMcpToolName } from "../model/workspace-mcp.js";
|
|
20
|
+
import type { AgentCycle, AgentOwner, AgentView } from "../model/agent.js";
|
|
21
|
+
import { AgentService } from "../services/agents/agent-service.js";
|
|
22
|
+
import { readWorkspaceConfig, workspaceDisabledMessage, workspaceFeatures } from "../services/workspace/workspace-config.js";
|
|
23
|
+
import { WorkspaceMcpBridge } from "./mcp-bridge.js";
|
|
24
|
+
|
|
25
|
+
const protocolVersion = "2025-03-26";
|
|
26
|
+
const readyTimeoutMs = 45_000;
|
|
27
|
+
const defaultWaitMs = 50_000;
|
|
28
|
+
const maxWaitMs = 600_000;
|
|
29
|
+
const reportPageSize = 16_000;
|
|
30
|
+
const progressIntervalMs = 5_000;
|
|
31
|
+
|
|
32
|
+
const responseActions = ["accept", "decline", "cancel"] as const;
|
|
33
|
+
const discoverTargets = ["overview", "workers", "backends", "models"] as const;
|
|
34
|
+
type DiscoverTarget = typeof discoverTargets[number];
|
|
35
|
+
|
|
36
|
+
type AllMcpToolName = McpWorkerToolName | WorkspaceMcpToolName;
|
|
37
|
+
const allMcpToolNames: readonly AllMcpToolName[] = [...mcpWorkerToolNames, ...workspaceMcpToolNames];
|
|
38
|
+
|
|
39
|
+
const toolParams: Record<AllMcpToolName, ReadonlySet<string>> = {
|
|
40
|
+
worker_create: new Set(["backend", "model", "thinking", "cwd", "workspace"]),
|
|
41
|
+
worker_close: new Set(["workerId", "workspace"]),
|
|
42
|
+
worker_request: new Set(["workerId", "message", "waitMs", "workspace"]),
|
|
43
|
+
worker_response: new Set(["workerId", "action", "requestId", "optionId", "content", "waitMs", "workspace"]),
|
|
44
|
+
worker_output: new Set(["workerId", "offset", "waitMs", "workspace"]),
|
|
45
|
+
worker_discover: new Set(["target", "workerId", "backend", "model", "workspace"]),
|
|
46
|
+
workspace_mcp_discover: new Set(["server", "workspace"]),
|
|
47
|
+
workspace_mcp_call: new Set(["server", "tool", "arguments", "workspace"]),
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const shortToolMap: Record<string, McpWorkerToolName> = {
|
|
51
|
+
create: "worker_create",
|
|
52
|
+
close: "worker_close",
|
|
53
|
+
request: "worker_request",
|
|
54
|
+
response: "worker_response",
|
|
55
|
+
output: "worker_output",
|
|
56
|
+
discover: "worker_discover",
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
export type ProgressReporter = (message: string) => void;
|
|
60
|
+
|
|
61
|
+
export const mcpInstructions =
|
|
62
|
+
"用于跨代理程序委派任务(worker_*)与调用工作区统一注册的外部 MCP 服务(workspace_mcp_*);未指定其他程序时,优先由当前程序或其原生子代理直接完成。\n" +
|
|
63
|
+
"跨程序委派:worker_create 创建 worker(或用 worker_discover 复用已有 worker)→ worker_request 发送任务或后续消息 → 用完可用 worker_close 关闭;后台等待、超时续等(timedOut)或长报告翻页(nextOffset)用 worker_output;返回 needsResponse 时向用户确认后用 worker_response 回复。\n" +
|
|
64
|
+
"工作区统一 MCP(.pbot/mcp.json):先用 workspace_mcp_discover 查看已注册服务或指定服务的工具清单,再用 workspace_mcp_call 调用目标工具;可与宿主原生 MCP 同时使用。";
|
|
65
|
+
|
|
66
|
+
function formatBackendItem(entry: ReturnType<typeof inspectAcpBackends>[number], defaultBackend?: string): string {
|
|
67
|
+
const tags: string[] = [];
|
|
68
|
+
if (entry.label) tags.push(entry.label);
|
|
69
|
+
if (entry.backend === defaultBackend) tags.push("当前");
|
|
70
|
+
return tags.length ? `${entry.backend}(${tags.join(",")})` : entry.backend;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function summarizeBackends(commands: AcpCommands = {}, defaultBackend?: string) {
|
|
74
|
+
const entries = inspectAcpBackends(commands);
|
|
75
|
+
const available = entries.filter(item => item.available);
|
|
76
|
+
const unavailable = entries.filter(item => !item.available);
|
|
77
|
+
const availableText = available.map(item => formatBackendItem(item, defaultBackend)).join("、");
|
|
78
|
+
const unavailableText = unavailable.map(item => formatBackendItem(item, defaultBackend)).join("、");
|
|
79
|
+
const overview = available.length
|
|
80
|
+
? unavailable.length
|
|
81
|
+
? `可用 backend:${availableText};不可用:${unavailableText}。`
|
|
82
|
+
: `可用 backend:${availableText}。`
|
|
83
|
+
: `当前无可用 backend(不可用:${unavailableText})。`;
|
|
84
|
+
const availableIds = available.map(item => item.backend).join("、");
|
|
85
|
+
return { overview, availableIds };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function workspaceProperty(workspaceBound: boolean) {
|
|
89
|
+
return {
|
|
90
|
+
type: "string",
|
|
91
|
+
description: workspaceBound
|
|
92
|
+
? "工作区根目录绝对路径;已默认绑定当前工作区,通常省略。"
|
|
93
|
+
: "工作区根目录绝对路径(上下文提供 workspaceRoot 时传该路径);当前未默认绑定,请显式传入。",
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function buildPbotWorkerTools(commands: AcpCommands = {}, defaultBackend?: string, workspaceBound = false) {
|
|
98
|
+
const { overview, availableIds } = summarizeBackends(commands, defaultBackend);
|
|
99
|
+
const modelsBackendHint = defaultBackend
|
|
100
|
+
? `省略时默认查 ${defaultBackend}`
|
|
101
|
+
: "必填";
|
|
102
|
+
const workspace = workspaceProperty(workspaceBound);
|
|
103
|
+
|
|
104
|
+
return [
|
|
105
|
+
{
|
|
106
|
+
name: "worker_create",
|
|
107
|
+
description:
|
|
108
|
+
"创建一个新的 worker 并返回其 workerId(仅创建,不发送任务;随后用 worker_request 派发任务)。" +
|
|
109
|
+
"未指定其他程序时优先由当前程序或其原生子代理完成。\n" +
|
|
110
|
+
overview,
|
|
111
|
+
annotations: {
|
|
112
|
+
title: "Create Worker",
|
|
113
|
+
readOnlyHint: false,
|
|
114
|
+
destructiveHint: false,
|
|
115
|
+
idempotentHint: false,
|
|
116
|
+
openWorldHint: true,
|
|
117
|
+
},
|
|
118
|
+
inputSchema: {
|
|
119
|
+
type: "object",
|
|
120
|
+
additionalProperties: false,
|
|
121
|
+
required: ["backend"],
|
|
122
|
+
properties: {
|
|
123
|
+
backend: {
|
|
124
|
+
type: "string",
|
|
125
|
+
description: "目标代理程序名称,不区分大小写,支持常见别名(如 claude-code、agy)。",
|
|
126
|
+
},
|
|
127
|
+
model: {
|
|
128
|
+
type: "string",
|
|
129
|
+
description: "仅用户明确指定模型时传入(支持模型 ID、显示名或 provider/model,不区分大小写);不确定合法值可用 worker_discover(target=\"models\") 查询;省略则使用目标默认。",
|
|
130
|
+
},
|
|
131
|
+
thinking: {
|
|
132
|
+
type: "string",
|
|
133
|
+
description: "仅用户明确指定思考力度时传入(如 low / medium / high / xhigh / max,不区分大小写);省略则使用目标默认。",
|
|
134
|
+
},
|
|
135
|
+
cwd: {
|
|
136
|
+
type: "string",
|
|
137
|
+
description: "worker 工作目录(相对工作区根目录或绝对路径),默认为工作区根目录。",
|
|
138
|
+
},
|
|
139
|
+
workspace,
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
},
|
|
143
|
+
{
|
|
144
|
+
name: "worker_close",
|
|
145
|
+
description:
|
|
146
|
+
"关闭指定 worker。若该 worker 支持恢复(capabilities.resume 为 true),后续仍可直接用 worker_request 继续会话。",
|
|
147
|
+
annotations: {
|
|
148
|
+
title: "Close Worker",
|
|
149
|
+
readOnlyHint: false,
|
|
150
|
+
destructiveHint: true,
|
|
151
|
+
idempotentHint: true,
|
|
152
|
+
openWorldHint: false,
|
|
153
|
+
},
|
|
154
|
+
inputSchema: {
|
|
155
|
+
type: "object",
|
|
156
|
+
additionalProperties: false,
|
|
157
|
+
required: ["workerId"],
|
|
158
|
+
properties: {
|
|
159
|
+
workerId: {
|
|
160
|
+
type: "string",
|
|
161
|
+
description: "要关闭的 worker ID(来自 worker_create 或 worker_discover)。",
|
|
162
|
+
},
|
|
163
|
+
workspace,
|
|
164
|
+
},
|
|
165
|
+
},
|
|
166
|
+
},
|
|
167
|
+
{
|
|
168
|
+
name: "worker_request",
|
|
169
|
+
description:
|
|
170
|
+
"向指定 worker 发送任务或后续消息(若已关闭且支持恢复,会自动续接会话)。" +
|
|
171
|
+
`默认最多等待 ${defaultWaitMs / 1000} 秒返回报告(waitMs 设为 0 立即返回并在后台执行);` +
|
|
172
|
+
"若返回 timedOut 或报告含 nextOffset 用 worker_output 继续,返回 needsResponse 时向用户确认后用 worker_response 回复。",
|
|
173
|
+
annotations: {
|
|
174
|
+
title: "Send Request to Worker",
|
|
175
|
+
readOnlyHint: false,
|
|
176
|
+
destructiveHint: false,
|
|
177
|
+
idempotentHint: false,
|
|
178
|
+
openWorldHint: true,
|
|
179
|
+
},
|
|
180
|
+
inputSchema: {
|
|
181
|
+
type: "object",
|
|
182
|
+
additionalProperties: false,
|
|
183
|
+
required: ["workerId", "message"],
|
|
184
|
+
properties: {
|
|
185
|
+
workerId: {
|
|
186
|
+
type: "string",
|
|
187
|
+
description: "目标 worker ID(来自 worker_create 或 worker_discover)。",
|
|
188
|
+
},
|
|
189
|
+
message: {
|
|
190
|
+
type: "string",
|
|
191
|
+
description: "发给 worker 的任务说明或后续消息。worker 看不到当前对话历史,首次派发时请写清目标、相关文件路径、约束和交付要求。",
|
|
192
|
+
},
|
|
193
|
+
waitMs: {
|
|
194
|
+
type: "integer",
|
|
195
|
+
minimum: 0,
|
|
196
|
+
maximum: maxWaitMs,
|
|
197
|
+
description: `最多等待的毫秒数(默认 ${defaultWaitMs});传 0 立即返回并在后台执行。`,
|
|
198
|
+
},
|
|
199
|
+
workspace,
|
|
200
|
+
},
|
|
201
|
+
},
|
|
202
|
+
},
|
|
203
|
+
{
|
|
204
|
+
name: "worker_response",
|
|
205
|
+
description:
|
|
206
|
+
"回复 worker 返回 needsResponse: true 时的待处理请求(pendingRequests),用于权限审批(kind=\"permission\")、表单提问(kind=\"form\")和 URL 确认(kind=\"url\")。" +
|
|
207
|
+
`回复前先向用户确认;回复后默认最多等待 ${defaultWaitMs / 1000} 秒返回后续结果(waitMs 设为 0 立即返回)。`,
|
|
208
|
+
annotations: {
|
|
209
|
+
title: "Respond to Worker Request",
|
|
210
|
+
readOnlyHint: false,
|
|
211
|
+
destructiveHint: false,
|
|
212
|
+
idempotentHint: false,
|
|
213
|
+
openWorldHint: true,
|
|
214
|
+
},
|
|
215
|
+
inputSchema: {
|
|
216
|
+
type: "object",
|
|
217
|
+
additionalProperties: false,
|
|
218
|
+
required: ["workerId", "action"],
|
|
219
|
+
properties: {
|
|
220
|
+
workerId: {
|
|
221
|
+
type: "string",
|
|
222
|
+
description: "存在待处理请求的 worker ID。",
|
|
223
|
+
},
|
|
224
|
+
action: {
|
|
225
|
+
type: "string",
|
|
226
|
+
enum: [...responseActions],
|
|
227
|
+
description: "accept:同意权限、提交表单或确认 URL;decline:拒绝;cancel:取消。",
|
|
228
|
+
},
|
|
229
|
+
requestId: {
|
|
230
|
+
type: "string",
|
|
231
|
+
description: "待回复的 pendingRequests[].requestId;仅一条请求时可省略,多条时必填。",
|
|
232
|
+
},
|
|
233
|
+
optionId: {
|
|
234
|
+
type: "string",
|
|
235
|
+
description: "仅 kind=\"permission\" 且 action 不为 cancel 时可用:指定 pendingRequests[].options[].optionId(省略时默认单次允许或拒绝)。",
|
|
236
|
+
},
|
|
237
|
+
content: {
|
|
238
|
+
type: "object",
|
|
239
|
+
additionalProperties: true,
|
|
240
|
+
description: "仅 kind=\"form\" 且 action=\"accept\" 时可用:按 pendingRequests[].schema.properties 填写的答案对象(字段值支持字符串、数字、布尔或字符串数组)。",
|
|
241
|
+
},
|
|
242
|
+
waitMs: {
|
|
243
|
+
type: "integer",
|
|
244
|
+
minimum: 0,
|
|
245
|
+
maximum: maxWaitMs,
|
|
246
|
+
description: `回复后最多等待的毫秒数(默认 ${defaultWaitMs});传 0 立即返回。`,
|
|
247
|
+
},
|
|
248
|
+
workspace,
|
|
249
|
+
},
|
|
250
|
+
},
|
|
251
|
+
},
|
|
252
|
+
{
|
|
253
|
+
name: "worker_output",
|
|
254
|
+
description:
|
|
255
|
+
"获取指定 worker 最新一轮的执行报告:仍在运行时等待其完成(也可能返回 timedOut 或 needsResponse),已结束则立即返回;报告含 nextOffset 时传入 offset 翻页续读。",
|
|
256
|
+
annotations: {
|
|
257
|
+
title: "Get Worker Output",
|
|
258
|
+
readOnlyHint: true,
|
|
259
|
+
destructiveHint: false,
|
|
260
|
+
idempotentHint: true,
|
|
261
|
+
openWorldHint: false,
|
|
262
|
+
},
|
|
263
|
+
inputSchema: {
|
|
264
|
+
type: "object",
|
|
265
|
+
additionalProperties: false,
|
|
266
|
+
required: ["workerId"],
|
|
267
|
+
properties: {
|
|
268
|
+
workerId: {
|
|
269
|
+
type: "string",
|
|
270
|
+
description: "要等待或读取报告的 worker ID。",
|
|
271
|
+
},
|
|
272
|
+
offset: {
|
|
273
|
+
type: "integer",
|
|
274
|
+
minimum: 0,
|
|
275
|
+
description: "报告字符偏移量(默认 0);翻页续读时传上次返回的 nextOffset。",
|
|
276
|
+
},
|
|
277
|
+
waitMs: {
|
|
278
|
+
type: "integer",
|
|
279
|
+
minimum: 0,
|
|
280
|
+
maximum: maxWaitMs,
|
|
281
|
+
description: `任务仍在运行时最多等待的毫秒数(默认 ${defaultWaitMs});已结束或翻页时立即返回。`,
|
|
282
|
+
},
|
|
283
|
+
workspace,
|
|
284
|
+
},
|
|
285
|
+
},
|
|
286
|
+
},
|
|
287
|
+
{
|
|
288
|
+
name: "worker_discover",
|
|
289
|
+
description:
|
|
290
|
+
"查询可用 backend、当前会话已有 worker 的状态,或指定 backend 可选的模型与思考力度。" +
|
|
291
|
+
"默认(target=\"overview\")返回可用 backend 与已有 worker;仅需确认模型或思考力度可选值时再查 target=\"models\"(耗时较长)。",
|
|
292
|
+
annotations: {
|
|
293
|
+
title: "Discover Workers, Backends & Models",
|
|
294
|
+
readOnlyHint: true,
|
|
295
|
+
destructiveHint: false,
|
|
296
|
+
idempotentHint: true,
|
|
297
|
+
openWorldHint: false,
|
|
298
|
+
},
|
|
299
|
+
inputSchema: {
|
|
300
|
+
type: "object",
|
|
301
|
+
additionalProperties: false,
|
|
302
|
+
required: [],
|
|
303
|
+
properties: {
|
|
304
|
+
target: {
|
|
305
|
+
type: "string",
|
|
306
|
+
enum: [...discoverTargets],
|
|
307
|
+
description: "查询范围,默认 \"overview\"(同时返回 backends 与 workers);\"workers\" 查全部或单个 worker 状态;\"backends\" 查可用 backend 列表;\"models\" 查指定 backend 的可选模型与思考力度。",
|
|
308
|
+
},
|
|
309
|
+
workerId: {
|
|
310
|
+
type: "string",
|
|
311
|
+
description: "仅 target=\"workers\" 可用:指定单个 worker ID;省略时列出全部。",
|
|
312
|
+
},
|
|
313
|
+
backend: {
|
|
314
|
+
type: "string",
|
|
315
|
+
description: availableIds
|
|
316
|
+
? `仅 target="models" 可用(${modelsBackendHint}):目标代理程序名称,支持常见别名;可用:${availableIds}。`
|
|
317
|
+
: `仅 target="models" 可用(${modelsBackendHint}):目标代理程序名称,支持常见别名。`,
|
|
318
|
+
},
|
|
319
|
+
model: {
|
|
320
|
+
type: "string",
|
|
321
|
+
description: "仅 target=\"models\" 可用:指定模型以查询该模型支持的思考力度选项。",
|
|
322
|
+
},
|
|
323
|
+
workspace,
|
|
324
|
+
},
|
|
325
|
+
},
|
|
326
|
+
},
|
|
327
|
+
];
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
export function buildWorkspaceMcpTools(workspaceBound = false) {
|
|
331
|
+
const workspace = workspaceProperty(workspaceBound);
|
|
332
|
+
return [
|
|
333
|
+
{
|
|
334
|
+
name: "workspace_mcp_discover",
|
|
335
|
+
description:
|
|
336
|
+
"查看工作区 .pbot/mcp.json 中统一注册的 MCP 服务列表;传入 server 时按需连接该服务并返回其全部工具及参数 schema。",
|
|
337
|
+
annotations: {
|
|
338
|
+
title: "Discover Workspace MCP Servers & Tools",
|
|
339
|
+
readOnlyHint: true,
|
|
340
|
+
destructiveHint: false,
|
|
341
|
+
idempotentHint: true,
|
|
342
|
+
openWorldHint: true,
|
|
343
|
+
},
|
|
344
|
+
inputSchema: {
|
|
345
|
+
type: "object",
|
|
346
|
+
additionalProperties: false,
|
|
347
|
+
required: [],
|
|
348
|
+
properties: {
|
|
349
|
+
server: {
|
|
350
|
+
type: "string",
|
|
351
|
+
description: "目标 MCP 服务名(来自 .pbot/mcp.json 的键名);省略时仅列出已注册服务摘要。",
|
|
352
|
+
},
|
|
353
|
+
workspace,
|
|
354
|
+
},
|
|
355
|
+
},
|
|
356
|
+
},
|
|
357
|
+
{
|
|
358
|
+
name: "workspace_mcp_call",
|
|
359
|
+
description:
|
|
360
|
+
"调用工作区 .pbot/mcp.json 中指定 MCP 服务的工具(首次调用按需连接并复用连接,配置变更自动热更新)。" +
|
|
361
|
+
"不确定工具名或参数 schema 时,先用 workspace_mcp_discover(server) 查询。",
|
|
362
|
+
annotations: {
|
|
363
|
+
title: "Call Workspace MCP Tool",
|
|
364
|
+
readOnlyHint: false,
|
|
365
|
+
destructiveHint: false,
|
|
366
|
+
idempotentHint: false,
|
|
367
|
+
openWorldHint: true,
|
|
368
|
+
},
|
|
369
|
+
inputSchema: {
|
|
370
|
+
type: "object",
|
|
371
|
+
additionalProperties: false,
|
|
372
|
+
required: ["server", "tool"],
|
|
373
|
+
properties: {
|
|
374
|
+
server: {
|
|
375
|
+
type: "string",
|
|
376
|
+
description: "目标 MCP 服务名(来自 .pbot/mcp.json)。",
|
|
377
|
+
},
|
|
378
|
+
tool: {
|
|
379
|
+
type: "string",
|
|
380
|
+
description: "要调用的下游 MCP 工具名称。",
|
|
381
|
+
},
|
|
382
|
+
arguments: {
|
|
383
|
+
type: "object",
|
|
384
|
+
additionalProperties: true,
|
|
385
|
+
description: "传递给下游 MCP 工具的参数对象,省略时为空对象。",
|
|
386
|
+
},
|
|
387
|
+
workspace,
|
|
388
|
+
},
|
|
389
|
+
},
|
|
390
|
+
},
|
|
391
|
+
];
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
export const pbotWorkerTools = buildPbotWorkerTools();
|
|
395
|
+
|
|
396
|
+
export function defaultWorkerDirectory(): string {
|
|
397
|
+
if (process.env.PBOT_MCP_AGENT_DIR) return process.env.PBOT_MCP_AGENT_DIR;
|
|
398
|
+
if (process.env.PLUGIN_DATA) return join(process.env.PLUGIN_DATA, "subagents");
|
|
399
|
+
return join(homedir(), ".pbot/subagents");
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function isKnownWorkerTool(name: string): name is McpWorkerToolName {
|
|
403
|
+
return (mcpWorkerToolNames as readonly string[]).includes(name);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
function isKnownTool(name: string): name is AllMcpToolName {
|
|
407
|
+
return (allMcpToolNames as readonly string[]).includes(name);
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** Parse Pi/dsh `/pbot worker ...` CLI arguments into a canonical MCP tool call. */
|
|
411
|
+
export function parseWorkerCommand(raw: string): { tool: McpWorkerToolName; args: Record<string, unknown> } {
|
|
412
|
+
const trimmed = raw.trim();
|
|
413
|
+
if (!trimmed || trimmed === "overview") return { tool: "worker_discover", args: { target: "overview" } };
|
|
414
|
+
if (trimmed === "status" || trimmed === "list" || trimmed === "workers") {
|
|
415
|
+
return { tool: "worker_discover", args: { target: "workers" } };
|
|
416
|
+
}
|
|
417
|
+
if (trimmed.startsWith("status ") || trimmed.startsWith("workers ")) {
|
|
418
|
+
const workerId = trimmed.slice(trimmed.indexOf(" ") + 1).trim();
|
|
419
|
+
requireThat(workerId.length > 0, "请提供 workerId。");
|
|
420
|
+
return { tool: "worker_discover", args: { target: "workers", workerId } };
|
|
421
|
+
}
|
|
422
|
+
if (trimmed === "backends") return { tool: "worker_discover", args: { target: "backends" } };
|
|
423
|
+
if (trimmed === "models") return { tool: "worker_discover", args: { target: "models" } };
|
|
424
|
+
if (trimmed.startsWith("models ")) {
|
|
425
|
+
const backend = trimmed.slice(7).trim();
|
|
426
|
+
requireThat(backend.length > 0, "请提供 backend 名称。");
|
|
427
|
+
return { tool: "worker_discover", args: { target: "models", backend } };
|
|
428
|
+
}
|
|
429
|
+
if (trimmed.startsWith("close ")) {
|
|
430
|
+
const rest = trimmed.slice(6).trim();
|
|
431
|
+
if (!rest.startsWith("{")) {
|
|
432
|
+
requireThat(rest.length > 0, "请提供要关闭的 workerId。");
|
|
433
|
+
return { tool: "worker_close", args: { workerId: rest } };
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
if (trimmed.startsWith("{")) {
|
|
437
|
+
const parsed: unknown = JSON.parse(trimmed);
|
|
438
|
+
requireThat(object(parsed), 'worker 参数必须是 JSON 对象,例如:/pbot worker create {"backend":"codex"}');
|
|
439
|
+
const rawTool = typeof parsed.tool === "string" ? parsed.tool : undefined;
|
|
440
|
+
const resolved = rawTool ? (isKnownWorkerTool(rawTool) ? rawTool : shortToolMap[rawTool]) : undefined;
|
|
441
|
+
requireThat(resolved, `JSON 形式需包含有效 tool 字段(${mcpWorkerToolNames.join(", ")}),或使用 /pbot worker <工具名> <JSON>。`);
|
|
442
|
+
const rest = Object.fromEntries(Object.entries(parsed).filter(([key]) => key !== "tool"));
|
|
443
|
+
return { tool: resolved, args: rest };
|
|
444
|
+
}
|
|
445
|
+
const match = trimmed.match(/^(\S+)(?:\s+([\s\S]*))?$/);
|
|
446
|
+
const verb = match?.[1] ?? "";
|
|
447
|
+
const rest = (match?.[2] ?? "").trim();
|
|
448
|
+
const tool = isKnownWorkerTool(verb) ? verb : shortToolMap[verb];
|
|
449
|
+
requireThat(tool, `未知 worker 命令:${verb}(支持:overview | status | backends | models | create | request | response | output | close | discover)。`);
|
|
450
|
+
if (!rest) return { tool, args: {} };
|
|
451
|
+
const parsed: unknown = JSON.parse(rest);
|
|
452
|
+
requireThat(object(parsed), `${tool} 的参数必须是 JSON 对象。`);
|
|
453
|
+
return { tool, args: parsed };
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function rejectUnknownParams(tool: AllMcpToolName, rawArgs: Record<string, unknown>) {
|
|
457
|
+
const allowed = toolParams[tool];
|
|
458
|
+
const unknown = Object.entries(rawArgs)
|
|
459
|
+
.filter(([key, value]) => value !== undefined && !allowed.has(key))
|
|
460
|
+
.map(([key]) => key);
|
|
461
|
+
requireThat(unknown.length === 0, `未知参数:${unknown.join(", ")}(${tool} 可用参数:${[...allowed].join(", ")})。`);
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
function asString(args: Record<string, unknown>, key: string, required = false): string | undefined {
|
|
465
|
+
const value = args[key];
|
|
466
|
+
if (value === undefined || value === null) {
|
|
467
|
+
requireThat(!required, `缺少必填参数:${key}`);
|
|
468
|
+
return undefined;
|
|
469
|
+
}
|
|
470
|
+
requireThat(typeof value === "string" && value.length > 0, `参数 ${key} 必须是非空字符串。`);
|
|
471
|
+
return value;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function asInt(args: Record<string, unknown>, key: string, min: number, max: number): number | undefined {
|
|
475
|
+
const value = args[key];
|
|
476
|
+
if (value === undefined || value === null) return undefined;
|
|
477
|
+
requireThat(typeof value === "number" && Number.isInteger(value) && value >= min && value <= max,
|
|
478
|
+
`参数 ${key} 必须是 ${min}–${max} 的整数。`);
|
|
479
|
+
return value;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
function asContent(args: Record<string, unknown>, key: string): AcpElicitationContent | undefined {
|
|
483
|
+
const value = args[key];
|
|
484
|
+
if (value === undefined || value === null) return undefined;
|
|
485
|
+
requireThat(object(value), `参数 ${key} 必须是 JSON 对象。`);
|
|
486
|
+
for (const [field, entry] of Object.entries(value)) {
|
|
487
|
+
const valid = typeof entry === "string"
|
|
488
|
+
|| (typeof entry === "number" && Number.isFinite(entry))
|
|
489
|
+
|| typeof entry === "boolean"
|
|
490
|
+
|| (Array.isArray(entry) && entry.every(item => typeof item === "string"));
|
|
491
|
+
requireThat(valid, `参数 ${key}.${field} 必须是字符串、数字、布尔值或字符串数组。`);
|
|
492
|
+
}
|
|
493
|
+
return value as AcpElicitationContent;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
function presentCycle(cycle: AgentCycle) {
|
|
497
|
+
return {
|
|
498
|
+
state: cycle.state,
|
|
499
|
+
...(cycle.error ? { error: cycle.error } : {}),
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
function presentSelection(selection?: AcpModelSelection) {
|
|
504
|
+
if (!selection) return undefined;
|
|
505
|
+
const entries = Object.entries(selection).filter(([, value]) => value !== undefined);
|
|
506
|
+
return entries.length ? Object.fromEntries(entries) : undefined;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
function presentWorker(value: AgentView & {
|
|
510
|
+
report?: string;
|
|
511
|
+
totalLength?: number;
|
|
512
|
+
nextOffset?: number | null;
|
|
513
|
+
}) {
|
|
514
|
+
const selection = presentSelection(value.selection);
|
|
515
|
+
const truncated = value.nextOffset !== undefined && value.nextOffset !== null;
|
|
516
|
+
return {
|
|
517
|
+
workerId: value.agentId,
|
|
518
|
+
backend: value.backend,
|
|
519
|
+
state: value.state,
|
|
520
|
+
activity: value.activity,
|
|
521
|
+
alive: value.alive,
|
|
522
|
+
...(selection ? { selection } : {}),
|
|
523
|
+
...(value.pendingRequests?.length ? { pendingRequests: value.pendingRequests } : {}),
|
|
524
|
+
...(value.cycle ? { cycle: presentCycle(value.cycle) } : {}),
|
|
525
|
+
...(value.report !== undefined ? { report: value.report } : {}),
|
|
526
|
+
...(truncated ? { totalLength: value.totalLength, nextOffset: value.nextOffset } : {}),
|
|
527
|
+
...(value.error ? { error: value.error } : {}),
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
export class McpWorkerRuntime {
|
|
532
|
+
readonly #services = new Map<string, { service: AgentService; host: AcpWorkerHost; owner: AgentOwner }>();
|
|
533
|
+
readonly #bridge = new WorkspaceMcpBridge();
|
|
534
|
+
readonly #sessionId: string;
|
|
535
|
+
readonly #directory: string;
|
|
536
|
+
readonly #defaultBackend: string | undefined;
|
|
537
|
+
#closed = false;
|
|
538
|
+
|
|
539
|
+
constructor(
|
|
540
|
+
directory = defaultWorkerDirectory(),
|
|
541
|
+
sessionId = process.env.PBOT_MCP_SESSION_ID || ("mcp-" + randomUUID()),
|
|
542
|
+
defaultBackend = process.env.PBOT_HOST || undefined,
|
|
543
|
+
) {
|
|
544
|
+
this.#directory = directory;
|
|
545
|
+
this.#sessionId = sessionId;
|
|
546
|
+
this.#defaultBackend = defaultBackend?.trim() || undefined;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
private resolveBackend(rawArgs: Record<string, unknown>, commands: AcpCommands | undefined, allowDefault: boolean): string {
|
|
550
|
+
const raw = asString(rawArgs, "backend") ?? (allowDefault ? this.#defaultBackend : undefined);
|
|
551
|
+
requireThat(raw, `缺少必填参数:backend(请指定目标程序:${knownAcpBackends(commands).join(", ")})。`);
|
|
552
|
+
const backend = canonicalAcpBackend(raw, commands);
|
|
553
|
+
requireThat(isAcpBackend(backend), "无效的 backend 名称:" + raw);
|
|
554
|
+
return backend;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
private async resolveWorkspace(supplied?: string): Promise<string> {
|
|
558
|
+
const target = supplied || process.env.CLAUDE_PROJECT_DIR || process.env.PBOT_WORKSPACE_ROOT || process.cwd();
|
|
559
|
+
requireThat(isAbsolute(target), "工作区需要绝对路径。");
|
|
560
|
+
const root = await realpath(target);
|
|
561
|
+
requireThat((await stat(root)).isDirectory(), "工作区路径不是目录。");
|
|
562
|
+
return root;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
private async workspace(supplied?: string) {
|
|
566
|
+
requireThat(!this.#closed, "Personal Bot MCP 服务已关闭。");
|
|
567
|
+
const root = await this.resolveWorkspace(supplied);
|
|
568
|
+
const configuration = await readWorkspaceConfig(root);
|
|
569
|
+
requireThat(configuration.enabled, workspaceDisabledMessage(configuration));
|
|
570
|
+
let entry = this.#services.get(root);
|
|
571
|
+
if (!entry) {
|
|
572
|
+
const host = new AcpWorkerHost(this.#directory, configuration.acp);
|
|
573
|
+
entry = {
|
|
574
|
+
host,
|
|
575
|
+
service: new AgentService(root, this.#directory, host),
|
|
576
|
+
owner: { sessionId: this.#sessionId, leaf: null, branch: [] },
|
|
577
|
+
};
|
|
578
|
+
this.#services.set(root, entry);
|
|
579
|
+
} else {
|
|
580
|
+
Object.assign(entry.host, { commands: configuration.acp ?? {} });
|
|
581
|
+
}
|
|
582
|
+
return { root, configuration, ...entry };
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
async toolDefinitions() {
|
|
586
|
+
let commands: AcpCommands | undefined;
|
|
587
|
+
let includeWorkspaceMcp = true;
|
|
588
|
+
try {
|
|
589
|
+
const root = await this.resolveWorkspace();
|
|
590
|
+
const configuration = await readWorkspaceConfig(root);
|
|
591
|
+
if (configuration.enabled) {
|
|
592
|
+
commands = configuration.acp;
|
|
593
|
+
includeWorkspaceMcp = workspaceFeatures(configuration).mcp;
|
|
594
|
+
}
|
|
595
|
+
} catch { /* Fall back to registered built-in harnesses when cwd is outside an enabled workspace. */ }
|
|
596
|
+
const defaultBackend = this.#defaultBackend ? canonicalAcpBackend(this.#defaultBackend, commands) : undefined;
|
|
597
|
+
const workspaceBound = Boolean(process.env.CLAUDE_PROJECT_DIR || process.env.PBOT_WORKSPACE_ROOT);
|
|
598
|
+
return [
|
|
599
|
+
...buildPbotWorkerTools(commands, defaultBackend, workspaceBound),
|
|
600
|
+
...(includeWorkspaceMcp ? buildWorkspaceMcpTools(workspaceBound) : []),
|
|
601
|
+
];
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/** Wait until ACP handshake and model/thinking configuration finish so invalid options fail synchronously on create/resume. */
|
|
605
|
+
private async waitReady(
|
|
606
|
+
service: AgentService,
|
|
607
|
+
owner: AgentOwner,
|
|
608
|
+
workerId: string,
|
|
609
|
+
timeoutMs: number,
|
|
610
|
+
progress?: ProgressReporter,
|
|
611
|
+
) {
|
|
612
|
+
const deadline = Date.now() + timeoutMs;
|
|
613
|
+
let lastProgressAt = 0;
|
|
614
|
+
let lastMarker = "";
|
|
615
|
+
for (;;) {
|
|
616
|
+
requireThat(!this.#closed, "Personal Bot MCP 服务已关闭。");
|
|
617
|
+
const current = service.status(workerId, owner);
|
|
618
|
+
if (current.state === "error" || current.state === "stopped") {
|
|
619
|
+
throw new Error(current.error || "worker 启动失败。");
|
|
620
|
+
}
|
|
621
|
+
if (current.state === "idle" || current.state === "busy") return current;
|
|
622
|
+
if (Date.now() >= deadline) return current;
|
|
623
|
+
if (progress) {
|
|
624
|
+
const marker = `${current.state}:${current.activity}`;
|
|
625
|
+
const now = Date.now();
|
|
626
|
+
if (marker !== lastMarker || now - lastProgressAt >= progressIntervalMs) {
|
|
627
|
+
lastMarker = marker;
|
|
628
|
+
lastProgressAt = now;
|
|
629
|
+
progress(`${current.backend}: ${current.activity}`);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
await delay(50);
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
private async waitFor(
|
|
637
|
+
service: AgentService,
|
|
638
|
+
owner: AgentOwner,
|
|
639
|
+
workerId: string,
|
|
640
|
+
requestId: string | undefined,
|
|
641
|
+
timeoutMs: number,
|
|
642
|
+
offset = 0,
|
|
643
|
+
progress?: ProgressReporter,
|
|
644
|
+
) {
|
|
645
|
+
const deadline = Date.now() + timeoutMs;
|
|
646
|
+
let lastProgressAt = 0;
|
|
647
|
+
let lastMarker = "";
|
|
648
|
+
for (;;) {
|
|
649
|
+
requireThat(!this.#closed, "Personal Bot MCP 服务已关闭。");
|
|
650
|
+
const current = service.status(workerId, owner);
|
|
651
|
+
const cycles = service.cycles(workerId, owner);
|
|
652
|
+
const latestRequest = requestId ?? service.files.messages(workerId)
|
|
653
|
+
.filter(item => item.generation === current.generation)
|
|
654
|
+
.at(-1)?.requestId;
|
|
655
|
+
const targetCycle = latestRequest
|
|
656
|
+
? cycles.find(item => item.generation === current.generation && item.requestIds.includes(latestRequest))
|
|
657
|
+
: current.cycle ?? cycles.at(-1);
|
|
658
|
+
const settled = targetCycle && targetCycle.state !== "running";
|
|
659
|
+
const terminalWithoutCycle = !latestRequest && (current.state === "stopped" || current.state === "error" || (current.state === "idle" && !targetCycle));
|
|
660
|
+
const failedBeforeCycle = Boolean(latestRequest && !targetCycle && (current.state === "stopped" || current.state === "error"));
|
|
661
|
+
if (settled) {
|
|
662
|
+
const page = await service.read(workerId, owner, targetCycle.cycleId, offset, reportPageSize);
|
|
663
|
+
return { settled: true, ...presentWorker(page) };
|
|
664
|
+
}
|
|
665
|
+
if (terminalWithoutCycle || failedBeforeCycle) {
|
|
666
|
+
if (offset > 0) await service.read(workerId, owner, undefined, offset, reportPageSize);
|
|
667
|
+
return { settled: true, ...presentWorker(current) };
|
|
668
|
+
}
|
|
669
|
+
if (current.pendingRequests?.length) {
|
|
670
|
+
return {
|
|
671
|
+
settled: false,
|
|
672
|
+
needsResponse: true,
|
|
673
|
+
...presentWorker(current),
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
if (Date.now() >= deadline) {
|
|
677
|
+
return { settled: false, timedOut: true, ...presentWorker(current) };
|
|
678
|
+
}
|
|
679
|
+
if (progress) {
|
|
680
|
+
const marker = `${current.state}:${current.activity}`;
|
|
681
|
+
const now = Date.now();
|
|
682
|
+
if (marker !== lastMarker || now - lastProgressAt >= progressIntervalMs) {
|
|
683
|
+
lastMarker = marker;
|
|
684
|
+
lastProgressAt = now;
|
|
685
|
+
progress(`${current.backend}: ${current.activity}`);
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
await delay(100);
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
async callTool(name: string, rawArgs: unknown, progress?: ProgressReporter): Promise<unknown> {
|
|
693
|
+
requireThat(isKnownTool(name), `未知工具:${name}(可用:${allMcpToolNames.join(", ")})。`);
|
|
694
|
+
requireThat(object(rawArgs), "工具参数必须是对象。");
|
|
695
|
+
rejectUnknownParams(name, rawArgs);
|
|
696
|
+
const { root, configuration, host, service, owner } = await this.workspace(asString(rawArgs, "workspace"));
|
|
697
|
+
|
|
698
|
+
switch (name) {
|
|
699
|
+
case "workspace_mcp_discover": {
|
|
700
|
+
requireThat(workspaceFeatures(configuration).mcp, `工作区统一 MCP 功能已在 ${configuration.path} 中停用(features.mcp: false)。`);
|
|
701
|
+
const server = asString(rawArgs, "server");
|
|
702
|
+
return this.#bridge.discover(root, server);
|
|
703
|
+
}
|
|
704
|
+
case "workspace_mcp_call": {
|
|
705
|
+
requireThat(workspaceFeatures(configuration).mcp, `工作区统一 MCP 功能已在 ${configuration.path} 中停用(features.mcp: false)。`);
|
|
706
|
+
const server = asString(rawArgs, "server", true)!;
|
|
707
|
+
const tool = asString(rawArgs, "tool", true)!;
|
|
708
|
+
const toolArgs = rawArgs.arguments === undefined ? {} : rawArgs.arguments;
|
|
709
|
+
requireThat(object(toolArgs), "参数 arguments 必须是 JSON 对象。");
|
|
710
|
+
return this.#bridge.call(root, server, tool, toolArgs);
|
|
711
|
+
}
|
|
712
|
+
case "worker_create": {
|
|
713
|
+
const backend = this.resolveBackend(rawArgs, configuration.acp, false);
|
|
714
|
+
const model = asString(rawArgs, "model");
|
|
715
|
+
const thinking = asString(rawArgs, "thinking");
|
|
716
|
+
const cwd = asString(rawArgs, "cwd");
|
|
717
|
+
const created = await service.start({
|
|
718
|
+
backend,
|
|
719
|
+
...(model ? { model } : {}),
|
|
720
|
+
...(thinking ? { thinking } : {}),
|
|
721
|
+
...(cwd ? { cwd } : {}),
|
|
722
|
+
}, owner);
|
|
723
|
+
const ready = await this.waitReady(service, owner, created.agentId, readyTimeoutMs, progress);
|
|
724
|
+
return {
|
|
725
|
+
...presentWorker(ready),
|
|
726
|
+
capabilities: { resume: ready.capabilities.resume },
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
case "worker_close":
|
|
730
|
+
return presentWorker(service.stop(asString(rawArgs, "workerId", true)!, owner));
|
|
731
|
+
case "worker_request": {
|
|
732
|
+
const workerId = asString(rawArgs, "workerId", true)!;
|
|
733
|
+
const message = asString(rawArgs, "message", true)!;
|
|
734
|
+
const waitMs = asInt(rawArgs, "waitMs", 0, maxWaitMs) ?? defaultWaitMs;
|
|
735
|
+
const current = service.status(workerId, owner);
|
|
736
|
+
requireThat(current.state !== "stopping", "worker 正在停止,请稍后重试。");
|
|
737
|
+
if (current.alive) {
|
|
738
|
+
const sent = service.send(workerId, message, "followUp", owner);
|
|
739
|
+
if (waitMs > 0) return this.waitFor(service, owner, workerId, sent.requestId, waitMs, 0, progress);
|
|
740
|
+
return presentWorker(sent);
|
|
741
|
+
}
|
|
742
|
+
const startedAt = Date.now();
|
|
743
|
+
const resumed = await service.resume(workerId, message, owner);
|
|
744
|
+
const ready = await this.waitReady(service, owner, workerId, waitMs > 0 ? Math.min(waitMs, readyTimeoutMs) : readyTimeoutMs, progress);
|
|
745
|
+
if (waitMs > 0 && resumed.requestId) {
|
|
746
|
+
const remaining = Math.max(0, waitMs - (Date.now() - startedAt));
|
|
747
|
+
return this.waitFor(service, owner, workerId, resumed.requestId, remaining, 0, progress);
|
|
748
|
+
}
|
|
749
|
+
return {
|
|
750
|
+
...presentWorker(ready),
|
|
751
|
+
...(ready.pendingRequests?.length ? { settled: false, needsResponse: true } : {}),
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
case "worker_response": {
|
|
755
|
+
const workerId = asString(rawArgs, "workerId", true)!;
|
|
756
|
+
const rawAction = asString(rawArgs, "action", true)!;
|
|
757
|
+
requireThat((responseActions as readonly string[]).includes(rawAction),
|
|
758
|
+
`参数 action 无效:${rawAction}(可用:${responseActions.join(", ")})。`);
|
|
759
|
+
const action = rawAction as AcpElicitationAction;
|
|
760
|
+
const requestId = asString(rawArgs, "requestId");
|
|
761
|
+
const optionId = asString(rawArgs, "optionId");
|
|
762
|
+
const content = asContent(rawArgs, "content");
|
|
763
|
+
const waitMs = asInt(rawArgs, "waitMs", 0, maxWaitMs) ?? defaultWaitMs;
|
|
764
|
+
const updated = service.respond(workerId, {
|
|
765
|
+
action,
|
|
766
|
+
...(requestId ? { requestId } : {}),
|
|
767
|
+
...(optionId ? { optionId } : {}),
|
|
768
|
+
...(content !== undefined ? { content } : {}),
|
|
769
|
+
}, owner);
|
|
770
|
+
if (waitMs > 0) return this.waitFor(service, owner, workerId, undefined, waitMs, 0, progress);
|
|
771
|
+
return presentWorker(updated);
|
|
772
|
+
}
|
|
773
|
+
case "worker_output": {
|
|
774
|
+
const workerId = asString(rawArgs, "workerId", true)!;
|
|
775
|
+
const offset = asInt(rawArgs, "offset", 0, 10_000_000) ?? 0;
|
|
776
|
+
const waitMs = asInt(rawArgs, "waitMs", 0, maxWaitMs) ?? defaultWaitMs;
|
|
777
|
+
return this.waitFor(service, owner, workerId, undefined, waitMs, offset, progress);
|
|
778
|
+
}
|
|
779
|
+
case "worker_discover": {
|
|
780
|
+
const rawTarget = asString(rawArgs, "target") ?? "overview";
|
|
781
|
+
requireThat((discoverTargets as readonly string[]).includes(rawTarget),
|
|
782
|
+
`参数 target 无效:${rawTarget}(可用:${discoverTargets.join(", ")})。`);
|
|
783
|
+
const target = rawTarget as DiscoverTarget;
|
|
784
|
+
const workerId = asString(rawArgs, "workerId");
|
|
785
|
+
const backendRaw = asString(rawArgs, "backend");
|
|
786
|
+
const model = asString(rawArgs, "model");
|
|
787
|
+
if (target !== "workers") {
|
|
788
|
+
requireThat(workerId === undefined, '参数 workerId 仅在 target="workers" 时可用。');
|
|
789
|
+
}
|
|
790
|
+
if (target !== "models") {
|
|
791
|
+
requireThat(backendRaw === undefined && model === undefined, '参数 backend / model 仅在 target="models" 时可用。');
|
|
792
|
+
}
|
|
793
|
+
if (target === "overview") {
|
|
794
|
+
return {
|
|
795
|
+
target,
|
|
796
|
+
backends: inspectAcpBackends(configuration.acp),
|
|
797
|
+
workers: service.list(owner).map(presentWorker),
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
if (target === "backends") {
|
|
801
|
+
return { target, backends: inspectAcpBackends(configuration.acp) };
|
|
802
|
+
}
|
|
803
|
+
if (target === "workers") {
|
|
804
|
+
return {
|
|
805
|
+
target,
|
|
806
|
+
workers: workerId
|
|
807
|
+
? [presentWorker(service.status(workerId, owner))]
|
|
808
|
+
: service.list(owner).map(presentWorker),
|
|
809
|
+
};
|
|
810
|
+
}
|
|
811
|
+
const backend = this.resolveBackend(rawArgs, configuration.acp, true);
|
|
812
|
+
return {
|
|
813
|
+
target,
|
|
814
|
+
...(await host.inspectModels(backend, root, { ...(model ? { model } : {}) })),
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
async close(preserve = false): Promise<void> {
|
|
821
|
+
if (this.#closed) return;
|
|
822
|
+
this.#closed = true;
|
|
823
|
+
const entries = [...this.#services.values()];
|
|
824
|
+
this.#services.clear();
|
|
825
|
+
await Promise.allSettled([
|
|
826
|
+
this.#bridge.close(),
|
|
827
|
+
...entries.map(({ service, owner }) => service.close(owner, preserve)),
|
|
828
|
+
]);
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
export async function handleMcpRequest(
|
|
833
|
+
runtime: McpWorkerRuntime,
|
|
834
|
+
message: unknown,
|
|
835
|
+
notify?: (notification: Record<string, unknown>) => void,
|
|
836
|
+
): Promise<Record<string, unknown> | null> {
|
|
837
|
+
if (!object(message) || message.jsonrpc !== "2.0" || typeof message.method !== "string") {
|
|
838
|
+
return { jsonrpc: "2.0", id: null, error: { code: -32600, message: "Invalid JSON-RPC request" } };
|
|
839
|
+
}
|
|
840
|
+
const hasId = Object.hasOwn(message, "id") && message.id !== undefined;
|
|
841
|
+
const id = hasId ? message.id : null;
|
|
842
|
+
if (!hasId) return null; // Notifications expect no response.
|
|
843
|
+
|
|
844
|
+
try {
|
|
845
|
+
if (message.method === "initialize") {
|
|
846
|
+
const requested = object(message.params) && typeof message.params.protocolVersion === "string"
|
|
847
|
+
? message.params.protocolVersion
|
|
848
|
+
: protocolVersion;
|
|
849
|
+
return {
|
|
850
|
+
jsonrpc: "2.0",
|
|
851
|
+
id,
|
|
852
|
+
result: {
|
|
853
|
+
protocolVersion: requested || protocolVersion,
|
|
854
|
+
capabilities: { tools: {} },
|
|
855
|
+
serverInfo: { name: "personal-bot", version: packageVersion },
|
|
856
|
+
instructions: mcpInstructions,
|
|
857
|
+
},
|
|
858
|
+
};
|
|
859
|
+
}
|
|
860
|
+
if (message.method === "ping") return { jsonrpc: "2.0", id, result: {} };
|
|
861
|
+
if (message.method === "tools/list") {
|
|
862
|
+
return { jsonrpc: "2.0", id, result: { tools: await runtime.toolDefinitions() } };
|
|
863
|
+
}
|
|
864
|
+
if (message.method === "tools/call") {
|
|
865
|
+
requireThat(object(message.params) && typeof message.params.name === "string", "tools/call 缺少 name。");
|
|
866
|
+
const meta = object(message.params._meta) ? message.params._meta : undefined;
|
|
867
|
+
const progressToken = meta && (typeof meta.progressToken === "string" || typeof meta.progressToken === "number")
|
|
868
|
+
? meta.progressToken
|
|
869
|
+
: undefined;
|
|
870
|
+
let progressStep = 0;
|
|
871
|
+
const progress: ProgressReporter | undefined = progressToken !== undefined && notify
|
|
872
|
+
? (statusMessage: string) => {
|
|
873
|
+
progressStep++;
|
|
874
|
+
notify({
|
|
875
|
+
jsonrpc: "2.0",
|
|
876
|
+
method: "notifications/progress",
|
|
877
|
+
params: { progressToken, progress: progressStep, message: statusMessage },
|
|
878
|
+
});
|
|
879
|
+
}
|
|
880
|
+
: undefined;
|
|
881
|
+
try {
|
|
882
|
+
const result = await runtime.callTool(message.params.name, message.params.arguments ?? {}, progress);
|
|
883
|
+
return {
|
|
884
|
+
jsonrpc: "2.0",
|
|
885
|
+
id,
|
|
886
|
+
result: {
|
|
887
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
888
|
+
},
|
|
889
|
+
};
|
|
890
|
+
} catch (error) {
|
|
891
|
+
return {
|
|
892
|
+
jsonrpc: "2.0",
|
|
893
|
+
id,
|
|
894
|
+
result: {
|
|
895
|
+
isError: true,
|
|
896
|
+
content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }],
|
|
897
|
+
},
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
return { jsonrpc: "2.0", id, error: { code: -32601, message: "Method not found: " + message.method } };
|
|
902
|
+
} catch (error) {
|
|
903
|
+
return { jsonrpc: "2.0", id, error: { code: -32603, message: error instanceof Error ? error.message : String(error) } };
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
export async function serveMcpStdio(runtime = new McpWorkerRuntime()): Promise<void> {
|
|
908
|
+
const shutdown = () => { void runtime.close().finally(() => process.exit(0)); };
|
|
909
|
+
process.on("SIGTERM", shutdown);
|
|
910
|
+
process.on("SIGINT", shutdown);
|
|
911
|
+
let buffer = "";
|
|
912
|
+
const pending = new Set<Promise<void>>();
|
|
913
|
+
const write = (value: unknown) => { process.stdout.write(JSON.stringify(value) + "\n"); };
|
|
914
|
+
process.stdin.setEncoding("utf8");
|
|
915
|
+
for await (const chunk of process.stdin) {
|
|
916
|
+
buffer += String(chunk);
|
|
917
|
+
for (;;) {
|
|
918
|
+
const nl = buffer.indexOf("\n");
|
|
919
|
+
if (nl < 0) break;
|
|
920
|
+
const line = buffer.slice(0, nl).trim();
|
|
921
|
+
buffer = buffer.slice(nl + 1);
|
|
922
|
+
if (!line) continue;
|
|
923
|
+
let parsed: unknown;
|
|
924
|
+
try { parsed = JSON.parse(line); }
|
|
925
|
+
catch {
|
|
926
|
+
write({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } });
|
|
927
|
+
continue;
|
|
928
|
+
}
|
|
929
|
+
const task = handleMcpRequest(runtime, parsed, write)
|
|
930
|
+
.then(reply => { if (reply) write(reply); })
|
|
931
|
+
.catch(error => {
|
|
932
|
+
const id = object(parsed) && Object.hasOwn(parsed, "id") && parsed.id !== undefined ? parsed.id : null;
|
|
933
|
+
if (id !== null) write({ jsonrpc: "2.0", id, error: { code: -32603, message: error instanceof Error ? error.message : String(error) } });
|
|
934
|
+
})
|
|
935
|
+
.finally(() => { pending.delete(task); });
|
|
936
|
+
pending.add(task);
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
await Promise.allSettled(pending);
|
|
940
|
+
await runtime.close();
|
|
941
|
+
}
|