feat: 远程群控 (#243)

* feat: restore pipe IPC, LAN pipes, monitor tool, and PR-package features

Core IPC system (UDS_INBOX):
- PipeServer/PipeClient with UDS + TCP dual transport, NDJSON protocol
- PipeRegistry: machineId-based role assignment, file locking
- Master/slave attach, prompt relay, permission forwarding
- Heartbeat lifecycle with parallel isPipeAlive probes
- Commands: /pipes, /attach, /detach, /send, /claim-main, /pipe-status

LAN Pipes (LAN_PIPES):
- UDP multicast beacon (224.0.71.67:7101) for zero-config LAN discovery
- PipeServer TCP listener, PipeClient TCP connect mode
- Heartbeat auto-attaches LAN peers via TCP
- Cross-machine attach allowed regardless of role
- /pipes shows [LAN] peers with role + hostname/IP
- SendMessageTool supports tcp: scheme with user consent

Architecture — extracted hooks from REPL.tsx (~830 lines → ~20 lines):
- usePipeIpc: lifecycle (bootstrap, handlers, heartbeat, cleanup)
- usePipeRelay: slave→master message relay via module singleton
- usePipePermissionForward: permission request/cancel forwarding
- usePipeRouter: selected pipe input routing with role+IP labels
- Shared ndjsonFramer.ts replaces 3 duplicate NDJSON parsers

Key fixes applied during development:
- Multicast binds to correct LAN interface (not WSL/Docker)
- Beacon ref stored as module singleton (not Zustand state mutation)
- Heartbeat preserves LAN peers in discoveredPipes and selectedPipes
- Disconnect handler calls removeSlaveClient (fixes listener leak)
- cleanupStaleEntries probes without lock, writes briefly under lock
- getMachineId uses async execFile (not blocking execSync)
- globalThis.__pipeSendToMaster replaced with setPipeRelay singleton
- M key only toggles route mode when selector panel is expanded
- User prompt displayed in message list on pipe broadcast
- Broadcast notifications show [role] + hostname/IP for LAN peers

Other restored features:
- Monitor tool: /monitor command, MonitorTool, MonitorMcpTask lifecycle
- Daemon supervisor and remoteControlServer command
- Tools: SnipTool, SleepTool, ListPeersTool, SendUserFileTool,
  WebBrowserTool, WorkflowTool, and 10+ stub→implementation rewrites
- Feature flags: UDS_INBOX, LAN_PIPES, MONITOR_TOOL, FORK_SUBAGENT,
  KAIROS, COORDINATOR_MODE, WORKFLOW_SCRIPTS, HISTORY_SNIP

Tests: 2190 pass / 0 fail (15 new: lanBeacon 7, peerAddress 8)

* fix: resolve merge conflicts and fix all tsc/test errors after main merge

- Export ToolResultBlockParam from Tool.ts (14 tool files fixed)
- Migrate ink imports from ../../ink.js to @anthropic/ink (7 files)
- Fix toolUseID → toolUseId typo in monitor.ts and MonitorTool.tsx
- Add fallback values for string|undefined type errors (8 locations)
- Fix AppState type in assistant.ts, add NewInstallWizard stubs
- Fix ParsedRepository.repo → .name in subscribe-pr.ts
- Fix AgentId/string type mismatch in BackgroundTasksDialog.tsx
- Fix PipeRelayFn return type in pipePermissionRelay.ts
- Use PipeMessage type in usePipeRelay.ts
- Fix lanBeacon.test.ts mock type assertions
- Create missing MouseActionEvent class for ink package
- Use ansi: color format instead of bare "green"/"red"
- Resolve theme.permission access via getTheme()

Result: 0 tsc errors, 2496 tests pass, 0 fail

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: 恢复 /poor 的说明

---------

Co-authored-by: unraid <local@unraid.local>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
claude-code-best
2026-04-11 23:22:55 +08:00
committed by GitHub
parent 2fea429dc6
commit 09fc515edb
124 changed files with 10958 additions and 577 deletions

View File

@@ -1,7 +1,142 @@
// Auto-generated stub — replace with real implementation
export {};
import type { Command } from 'src/types/command.js';
export const fetchMcpSkillsForClient: ((...args: unknown[]) => Promise<Command[]>) & { cache: Map<string, unknown> } = Object.assign(
(..._args: unknown[]) => Promise.resolve([] as Command[]),
{ cache: new Map<string, unknown>() }
);
import {
type ListResourcesResult,
ListResourcesResultSchema,
type ReadResourceResult,
ReadResourceResultSchema,
} from '@modelcontextprotocol/sdk/types.js'
import type { Command } from '../commands.js'
import type { MCPServerConnection } from '../services/mcp/types.js'
import { normalizeNameForMCP } from '../services/mcp/normalization.js'
import { memoizeWithLRU } from '../utils/memoize.js'
import { errorMessage } from '../utils/errors.js'
import { logMCPDebug, logMCPError } from '../utils/log.js'
import { recursivelySanitizeUnicode } from '../utils/sanitization.js'
import { parseFrontmatter } from '../utils/frontmatterParser.js'
import { getMCPSkillBuilders } from './mcpSkillBuilders.js'
const SKILL_URI_PREFIX = 'skill://'
const MCP_FETCH_CACHE_SIZE = 20
/**
* Discovers skills exposed as `skill://` resources by an MCP server.
*
* Each matching resource is read, its markdown content is parsed for
* frontmatter, and the result is converted into a Command that the skill
* system can index and invoke just like a local `.md` skill file.
*
* Memoized by server name so repeated calls within a connection lifecycle
* return the cached result. Callers invalidate via `.cache.delete(name)`.
*/
export const fetchMcpSkillsForClient = memoizeWithLRU(
async (client: MCPServerConnection): Promise<Command[]> => {
if (client.type !== 'connected') return []
try {
if (!client.capabilities?.resources) {
return []
}
// List all resources and filter to skill:// URIs
const result = (await client.client.request(
{ method: 'resources/list' },
ListResourcesResultSchema,
)) as ListResourcesResult
if (!result.resources) return []
const skillResources = result.resources.filter(r =>
r.uri.startsWith(SKILL_URI_PREFIX),
)
if (skillResources.length === 0) return []
logMCPDebug(
client.name,
`Found ${skillResources.length} skill resource(s)`,
)
const { createSkillCommand, parseSkillFrontmatterFields } =
getMCPSkillBuilders()
const commands: Command[] = []
for (const resource of skillResources) {
try {
// Read the skill resource content
const readResult = (await client.client.request(
{
method: 'resources/read',
params: { uri: resource.uri },
},
ReadResourceResultSchema,
)) as ReadResourceResult
// Extract text content from the resource
const textContent = readResult.contents
?.map(c => ('text' in c ? c.text : undefined))
.filter(Boolean)
.join('\n')
if (!textContent) {
logMCPDebug(
client.name,
`Skill resource ${resource.uri} returned no text content, skipping`,
)
continue
}
const sanitizedContent = recursivelySanitizeUnicode(textContent)
// Parse the markdown frontmatter
const { frontmatter, content: markdownContent } =
parseFrontmatter(sanitizedContent)
// Derive a skill name from the resource URI. Strip the skill://
// prefix and use the remainder, prefixed with the MCP server name
// so it is unique across servers.
const rawName = resource.uri.slice(SKILL_URI_PREFIX.length)
const skillName =
'mcp__' + normalizeNameForMCP(client.name) + '__' + rawName
const parsed = parseSkillFrontmatterFields(
frontmatter,
markdownContent,
skillName,
)
commands.push(
createSkillCommand({
...parsed,
skillName,
markdownContent,
source: 'mcp',
loadedFrom: 'mcp',
baseDir: undefined,
paths: undefined,
}),
)
} catch (error) {
logMCPError(
client.name,
`Failed to load skill resource ${resource.uri}: ${errorMessage(error)}`,
)
}
}
logMCPDebug(
client.name,
`Loaded ${commands.length} skill(s) from resources`,
)
return commands
} catch (error) {
logMCPError(
client.name,
`Failed to fetch skill resources: ${errorMessage(error)}`,
)
return []
}
},
(client: MCPServerConnection) => client.name,
MCP_FETCH_CACHE_SIZE,
)