From 4be290073e72d6d2bef82cb2e8e00e57243f02c6 Mon Sep 17 00:00:00 2001 From: wusumac <736139669@qq.com> Date: Sun, 8 Nov 2026 20:24:29 +0800 Subject: [PATCH] fix(cli,hub): give Agent Team its own team_spawn tool - Restore spawn_peer as the generic peer-session tool (directory + message) on every hub. The team block had reused the same name, so a teams-enabled hub hijacked normal session creation and rejected non-members. - Register team member spawning as team_spawn, gated by the teams feature. The codex bridge, team system prompt and hub lead brief now reference team_spawn; spawn_peer stays reserved for plain peers. - Keep team_spawn in the manual-approval set and lock the split with a regression test: spawn_peer requires directory/message and has no role; team_spawn requires role. via [HAPI](https://hapi.run) Co-Authored-By: HAPI Co-Authored-By: Claude Code --- cli/src/claude/utils/startHappyServer.test.ts | 22 ++++- cli/src/claude/utils/startHappyServer.ts | 88 +++++++------------ cli/src/codex/happyMcpStdioBridge.ts | 6 +- cli/src/modules/team/teamPrompt.test.ts | 2 +- cli/src/modules/team/teamPrompt.ts | 4 +- hub/src/teams/teamService.ts | 4 +- 6 files changed, 56 insertions(+), 70 deletions(-) diff --git a/cli/src/claude/utils/startHappyServer.test.ts b/cli/src/claude/utils/startHappyServer.test.ts index 7c328306..c36837ca 100644 --- a/cli/src/claude/utils/startHappyServer.test.ts +++ b/cli/src/claude/utils/startHappyServer.test.ts @@ -569,10 +569,10 @@ describe('startHappyServer Agent Team tools', () => { stopServer?.() }) - it('registers spawn_peer once and still serves MCP requests', async () => { - // Regression: the peer block and the team block both registered - // spawn_peer when teams were enabled, so the MCP SDK threw on every - // request and the whole hapi MCP surface answered 500. + it('keeps plain spawn_peer separate from team_spawn and serves MCP requests', async () => { + // Regression: the team block used to reuse the spawn_peer name, so a + // teams-enabled hub hijacked normal peer session creation (and the + // duplicate registration made the whole MCP surface answer 500). const sessionClient = { sessionId: 'team-session-id', getMetadata: () => null, @@ -583,6 +583,7 @@ describe('startHappyServer Agent Team tools', () => { const server = await startHappyServer(sessionClient, { teamToolsEnabled: true }) stopServer = server.stop expect(server.toolNames.filter((name) => name === 'spawn_peer')).toHaveLength(1) + expect(server.toolNames.filter((name) => name === 'team_spawn')).toHaveLength(1) client = new Client( { name: 'hapi-team-tools-test', version: '1.0.0' }, @@ -593,14 +594,27 @@ describe('startHappyServer Agent Team tools', () => { const tools = await client.listTools() const names = tools.tools.map((tool) => tool.name) expect(names.filter((name) => name === 'spawn_peer')).toHaveLength(1) + expect(names.filter((name) => name === 'team_spawn')).toHaveLength(1) expect(names).toEqual(expect.arrayContaining([ 'team_status', 'team_read', 'team_send', 'team_task', 'team_requirement', + 'team_spawn', 'spawn_peer', 'list_peers' ])) + + // Plain spawn_peer must keep requiring directory/message; team fields + // live on team_spawn only. + const spawnPeer = tools.tools.find((tool) => tool.name === 'spawn_peer')! + expect((spawnPeer.inputSchema as { required?: string[] }).required).toEqual( + expect.arrayContaining(['directory', 'message']) + ) + expect(Object.keys((spawnPeer.inputSchema as { properties?: Record }).properties ?? {})) + .not.toContain('role') + const teamSpawn = tools.tools.find((tool) => tool.name === 'team_spawn')! + expect((teamSpawn.inputSchema as { required?: string[] }).required).toEqual(['role']) }) }) diff --git a/cli/src/claude/utils/startHappyServer.ts b/cli/src/claude/utils/startHappyServer.ts index 69d3afef..93b6b42a 100644 --- a/cli/src/claude/utils/startHappyServer.ts +++ b/cli/src/claude/utils/startHappyServer.ts @@ -101,7 +101,8 @@ const CLAUDE_MANUAL_APPROVAL_HAPI_TOOLS = new Set([ 'display_video', 'ping_peer', 'inspect_peer', - 'spawn_peer' + 'spawn_peer', + 'team_spawn' ]); /** @@ -408,17 +409,11 @@ function createHapiMcpServer( effort?: string sessionType?: 'simple' | 'worktree' permissionMode?: string - role?: string - task?: string - modelReasoningEffort?: string - requirementId?: string - worktree?: boolean - worktreeName?: string } /** - * Plain peer spawn. Also the fallback for the unified spawn_peer tool when - * the caller omits `role` (team mode). + * Plain peer spawn: create a regular HAPI session and deliver the first + * message. Never requires a team; Agent Team has its own `team_spawn` tool. */ const runPeerSpawn = async (args: SpawnPeerToolArgs) => { const directory = args.directory @@ -427,7 +422,7 @@ function createHapiMcpServer( return { content: [{ type: 'text' as const, - text: 'Failed to spawn peer: pass role to spawn a team member, or directory + message to spawn a peer session.', + text: 'Failed to spawn peer: directory and message (the remit) are required.', }], isError: true, } @@ -529,17 +524,14 @@ function createHapiMcpServer( } }); - // With Agent Team tools on, spawn_peer is registered once by the team - // block below (team-aware dispatch). Registering it here too makes the - // MCP SDK throw `Tool spawn_peer is already registered` on every - // request, so the whole hapi MCP surface returns 500. - if (!teamToolsEnabled) { - mcp.registerTool('spawn_peer', { - description: SPAWN_PEER_TOOL_DESCRIPTION, - title: 'Spawn Peer Session', - inputSchema: spawnPeerInputSchema, - }, async (args: SpawnPeerToolArgs) => runPeerSpawn(args)); - } + // Plain peer sessions: available on every hub, team or not. Agent Team + // registers a separate `team_spawn` below, so this name is never + // shadowed by team semantics. + mcp.registerTool('spawn_peer', { + description: SPAWN_PEER_TOOL_DESCRIPTION, + title: 'Spawn Peer Session', + inputSchema: spawnPeerInputSchema, + }, async (args: SpawnPeerToolArgs) => runPeerSpawn(args)); mcp.registerTool('inspect_peer', { description: INSPECT_PEER_TOOL_DESCRIPTION, @@ -709,44 +701,24 @@ function createHapiMcpServer( } }); - // Single spawn_peer registration for team-enabled hubs. Passing `role` - // spawns a roster member; omitting it falls back to a plain peer spawn, - // so non-team sessions on a teams-enabled hub keep working. - mcp.registerTool('spawn_peer', { - description: `${SPAWN_PEER_TOOL_DESCRIPTION} Agent Team mode: when this session belongs to a team, pass role (and optional task/requirementId) instead of directory/message to spawn a roster member. Members inherit your tool/model/thinking level/permission by default - override only when the human asks; spawning costs tokens - prefer reusing idle members; requires user approval.`, - title: 'Spawn Peer Session', + // Team-only spawn. Kept separate from the generic spawn_peer so an + // Agent-Team-enabled hub never hijacks normal peer session creation. + mcp.registerTool('team_spawn', { + description: 'Agent Team: spawn a new teammate session (own context window) with a role and an initial task. Members inherit your tool/model/thinking level/permission by default - override only when the human asks; spawning costs tokens - prefer reusing idle members; requires user approval.', + title: 'Spawn Team Member', inputSchema: z.object({ - // Team mode (pass role). - role: z.string().trim().min(1).optional().describe('Team mode: role / display name for the new member, e.g. "Builder A" or "Reviewer". Must be unique in the team.'), - task: z.string().min(1).optional().describe('Team mode: initial task brief delivered to the new member'), - requirementId: z.string().min(1).optional().describe('Team mode: requirement the new member\'s task belongs to (see team_status)'), - worktree: z.boolean().optional().describe('Team mode: run the member in an isolated git worktree (default: follow the caller)'), - worktreeName: z.string().min(1).max(80).optional().describe('Team mode: explicit worktree name'), - modelReasoningEffort: z.string().min(1).max(50).optional().describe('Team mode: thinking-level override (defaults to yours)'), - // Peer mode (omit role). - directory: z.string().trim().min(1).optional() - .describe('Peer mode: working directory for the new session on the target machine (must exist there)'), - message: z.string().min(1).optional().describe('Peer mode: required first user message (the remit). Empty spawn is a failed spawn.'), - name: z.string().trim().min(1).max(SESSION_NAME_MAX_LENGTH).optional().describe('Peer mode: session display name'), - machine: z.string().trim().min(1).optional() - .describe( - 'Peer mode: optional target runner: hub machine UUID or hostname (metadata.host / displayName from GET /api/machines). ' - + 'Omit to spawn on this host.' - ), - effort: z.string().trim().min(1).optional().describe('Peer mode: effort override (flavor-dependent).'), - sessionType: z.enum(['simple', 'worktree']).optional() - .describe('Peer mode: simple or worktree. Default simple (use directory as cwd). worktree creates a new tree from directory.'), - // Shared. + role: z.string().trim().min(1).describe('Role / display name for the new member, e.g. "Builder A" or "Reviewer". Must be unique in the team.'), + task: z.string().min(1).optional().describe('Initial task brief delivered to the new member'), agent: z.enum(CREATABLE_AGENT_FLAVORS as unknown as [string, ...string[]]).optional() - .describe('Agent flavor override. Team members default to the caller flavor; peers resolve hub peerSpawnDefaults then stock claude.'), - model: z.string().trim().min(1).optional().describe('Model override for the resolved agent flavor.'), - permissionMode: PermissionModeSchema.optional() - .describe('Permission mode override. Team members inherit yours by default; peers use hub/stock default (yolo).'), + .describe('Agent flavor (claude, codex, ...). Defaults to the caller flavor.'), + model: z.string().trim().min(1).optional().describe('Optional model override (defaults to yours)'), + modelReasoningEffort: z.string().min(1).max(50).optional().describe('Optional thinking-level override (defaults to yours)'), + permissionMode: PermissionModeSchema.optional().describe('Optional permission-mode override (defaults to yours)'), + requirementId: z.string().min(1).optional().describe('Requirement the new member\'s task belongs to (see team_status)'), + worktree: z.boolean().optional().describe('Run the member in an isolated git worktree (default: follow the caller)'), + worktreeName: z.string().min(1).max(80).optional().describe('Explicit worktree name'), }), - }, async (args: SpawnPeerToolArgs) => { - if (!args.role) { - return await runPeerSpawn(args); - } + }, async (args: { role: string; task?: string; agent?: string; model?: string; modelReasoningEffort?: string; permissionMode?: string; requirementId?: string; worktree?: boolean; worktreeName?: string }) => { try { const status = await requireTeam(); const result = await spawnTeamMember({ @@ -770,7 +742,7 @@ function createHapiMcpServer( isError: false, }; } catch (error) { - return { content: [{ type: 'text' as const, text: `Failed to spawn peer: ${teamErrorText(error)}` }], isError: true }; + return { content: [{ type: 'text' as const, text: `Failed to spawn team member: ${teamErrorText(error)}` }], isError: true }; } }); @@ -1007,7 +979,7 @@ export async function startHappyServer(client: ApiSessionClient, options: StartH ...(peerToolsDisabled ? [] : ['list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer']), ]; if (teamToolsEnabled) { - toolNames.push('team_status', 'team_read', 'team_send', 'team_task', 'team_requirement'); + toolNames.push('team_status', 'team_read', 'team_send', 'team_task', 'team_requirement', 'team_spawn'); } if (options.skillLookup) { toolNames.push('skill_lookup'); diff --git a/cli/src/codex/happyMcpStdioBridge.ts b/cli/src/codex/happyMcpStdioBridge.ts index 9425b4fb..b11cd59c 100644 --- a/cli/src/codex/happyMcpStdioBridge.ts +++ b/cli/src/codex/happyMcpStdioBridge.ts @@ -404,9 +404,9 @@ export async function runHappyMcpStdioBridge(argv: string[]): Promise { }), }, { - name: 'spawn_peer', - title: 'Spawn Team Peer', - description: 'Agent Team: spawn a new teammate session with a role and an initial task. Members inherit your tool/model/thinking level/permission by default. Requires user approval.', + name: 'team_spawn', + title: 'Spawn Team Member', + description: 'Agent Team: spawn a new teammate session with a role and an initial task. Members inherit your tool/model/thinking level/permission by default. Requires the caller to be on a team. Requires user approval.', inputSchema: z.object({ role: z.string().min(1).describe('Role / display name, unique in the team'), task: z.string().min(1).optional().describe('Initial task brief delivered to the new member'), diff --git a/cli/src/modules/team/teamPrompt.test.ts b/cli/src/modules/team/teamPrompt.test.ts index 5a374f00..4f13a1ca 100644 --- a/cli/src/modules/team/teamPrompt.test.ts +++ b/cli/src/modules/team/teamPrompt.test.ts @@ -26,7 +26,7 @@ describe('teamPrompt', () => { expect(block).toContain('functions.hapi__team_status') expect(block).toContain('functions.hapi__team_read') expect(block).toContain('functions.hapi__team_send') - expect(block).toContain('functions.hapi__spawn_peer') + expect(block).toContain('functions.hapi__team_spawn') expect(block).not.toContain('mcp__hapi__') } finally { workspace.cleanup() diff --git a/cli/src/modules/team/teamPrompt.ts b/cli/src/modules/team/teamPrompt.ts index 5d4d5ca5..c4701067 100644 --- a/cli/src/modules/team/teamPrompt.ts +++ b/cli/src/modules/team/teamPrompt.ts @@ -27,9 +27,9 @@ export function getTeamPromptBlock(toolPrefix: string, env: NodeJS.ProcessEnv = - Report progress, completion, and blockers with ${toolPrefix}team_send (kind=status or task-update). Always address the Lead with to="lead" — direct messages to other members are blocked. Pass taskId so the update is filed under the right requirement. Batch updates; do not chat back and forth. - Track your work with ${toolPrefix}team_task (list/update): set a task to doing when you start, blocked when stuck, and done when finished. A done task requires a deliverable (evidence: branch/commit/files/test result), and doing/done requires its dependencies to be done first. - Replies to a message the human just sent you are synced into the team group chat automatically. If your turn was triggered by anything else (a teammate message, a task, a timer) and it ends with something the human must see or decide, you MUST send it explicitly with ${toolPrefix}team_send: use kind="decision" (with to="human") only when the human has to decide something, and a normal broadcast (to="all") for progress or conclusions they merely need to see. Reserve to="human" for decisions - it interrupts them out-of-band. - - Spawned members inherit your tool/model/thinking level/permission by default; only pass overrides to ${toolPrefix}spawn_peer when the human explicitly asks for a different setup. + - Spawned members inherit your tool/model/thinking level/permission by default; only pass overrides to ${toolPrefix}team_spawn when the human explicitly asks for a different setup. - If you need the hub API directly (scripting), use the team-scoped token in $HAPI_TEAM_TOKEN against $HAPI_API_URL. It only reaches this team's messages/tasks/status. NEVER read or use ~/.hapi/settings.json credentials. - - Only use ${toolPrefix}spawn_peer when the human or the lead explicitly asks you to. + - Only use ${toolPrefix}team_spawn when the human or the lead explicitly asks you to. ${memoryLine ?? ''} `) } diff --git a/hub/src/teams/teamService.ts b/hub/src/teams/teamService.ts index af73ff46..af50ab0d 100644 --- a/hub/src/teams/teamService.ts +++ b/hub/src/teams/teamService.ts @@ -1576,9 +1576,9 @@ function buildLeadBrief(team: TeamRecord): string { '', '职责:拆解任务、派生成员、汇总进展,必要时把决策升级给人类。', '成员只向你汇报(成员之间不能直接发消息);需要协作时用任务和依赖串联,不要让他们互相喊话。', - '可用工具:team_status(成员/任务/需求/预算)、team_read(拉取团队消息,广播不会主动推送)、team_send(汇报/分派/通知人类)、team_task(列表/建任务/更新状态/交付物/依赖)、team_requirement(需求列表/状态/结论)、spawn_peer(派生成员,需用户批准)。', + '可用工具:team_status(成员/任务/需求/预算)、team_read(拉取团队消息,广播不会主动推送)、team_send(汇报/分派/通知人类)、team_task(列表/建任务/更新状态/交付物/依赖)、team_requirement(需求列表/状态/结论)、team_spawn(派生成员,需用户批准)。', '复用 idle 成员时用 team_task action=create 给它建任务并指派,不要为了一个小任务新开成员;每个成员同一时间只能有一个 doing 任务。', - '人类每条新消息会自动成为一个"需求":派生任务时带上 requirementId(spawn_peer),完成后用 team_requirement 把需求标 done 并写一句 conclusion(结果)——人类只读结论即可。', + '人类每条新消息会自动成为一个"需求":派生任务时带上 requirementId(team_spawn),完成后用 team_requirement 把需求标 done 并写一句 conclusion(结果)——人类只读结论即可。', '派生成员默认继承你的工具/模型/思考等级/权限,不需要手动指定;只有人类明确要求不同配置时才传覆盖参数。', '需要直接调用 hub API 时用团队级凭证 $HAPI_TEAM_TOKEN(只能访问本团队的消息/任务/状态),不要读取 ~/.hapi/settings.json 的凭证。', '需要人类决策时用 kind="decision"(会通知人类并进"待确认"收件箱);只是汇报进展/结论用普通广播,不要用 to="human"——那会打扰人类;人类也会在群聊里发言、加成员或调整任务。',