Files
claude-code/src/utils/path.ts
claude-code-best 09fc515edb 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>
2026-04-11 23:22:55 +08:00

173 lines
6.2 KiB
TypeScript

import { homedir } from 'os'
import { dirname, isAbsolute, join, normalize, posix, relative, resolve } from 'path'
import { getCwd } from './cwd.js'
import { getFsImplementation } from './fsOperations.js'
import { getPlatform } from './platform.js'
import { posixPathToWindowsPath } from './windowsPaths.js'
/**
* Expands a path that may contain tilde notation (~) to an absolute path.
*
* On Windows, POSIX-style paths (e.g., `/c/Users/...`) are automatically converted
* to Windows format (e.g., `C:\Users\...`). The function always returns paths in
* the native format for the current platform.
*
* @param path - The path to expand, may contain:
* - `~` - expands to user's home directory
* - `~/path` - expands to path within user's home directory
* - absolute paths - returned normalized
* - relative paths - resolved relative to baseDir
* - POSIX paths on Windows - converted to Windows format
* @param baseDir - The base directory for resolving relative paths (defaults to current working directory)
* @returns The expanded absolute path in the native format for the current platform
*
* @throws {Error} If path is invalid
*
* @example
* expandPath('~') // '/home/user'
* expandPath('~/Documents') // '/home/user/Documents'
* expandPath('./src', '/project') // '/project/src'
* expandPath('/absolute/path') // '/absolute/path'
*/
export function expandPath(path: string, baseDir?: string): string {
// Set default baseDir to getCwd() if not provided
const actualBaseDir = baseDir ?? getCwd() ?? getFsImplementation().cwd()
// Input validation
if (typeof path !== 'string') {
throw new TypeError(`Path must be a string, received ${typeof path}`)
}
if (typeof actualBaseDir !== 'string') {
throw new TypeError(
`Base directory must be a string, received ${typeof actualBaseDir}`,
)
}
// Security: Check for null bytes
if (path.includes('\0') || actualBaseDir.includes('\0')) {
throw new Error('Path contains null bytes')
}
const isSyntheticPosixPath = (value: string): boolean =>
value.includes('/') && !value.includes('\\') && !/^[A-Za-z]:/.test(value)
// Handle empty or whitespace-only paths
const trimmedPath = path.trim()
if (!trimmedPath) {
if (getPlatform() === 'windows' && isSyntheticPosixPath(actualBaseDir)) {
return posix.normalize(actualBaseDir).normalize('NFC')
}
return normalize(actualBaseDir).normalize('NFC')
}
// Handle home directory notation
if (trimmedPath === '~') {
return homedir().normalize('NFC')
}
if (trimmedPath.startsWith('~/')) {
return join(homedir(), trimmedPath.slice(2)).normalize('NFC')
}
// On Windows, convert POSIX-style paths (e.g., /c/Users/...) to Windows format
let processedPath = trimmedPath
if (getPlatform() === 'windows' && trimmedPath.match(/^\/[a-z]\//i)) {
try {
processedPath = posixPathToWindowsPath(trimmedPath)
} catch {
// If conversion fails, use original path
processedPath = trimmedPath
}
}
// Handle absolute paths
if (isAbsolute(processedPath)) {
if (getPlatform() === 'windows' && isSyntheticPosixPath(processedPath)) {
return posix.normalize(processedPath).normalize('NFC')
}
return normalize(processedPath).normalize('NFC')
}
// Handle relative paths
if (
getPlatform() === 'windows' &&
isSyntheticPosixPath(actualBaseDir) &&
!/^[A-Za-z]:/.test(processedPath) &&
!processedPath.startsWith('\\\\')
) {
return posix.resolve(actualBaseDir, processedPath).normalize('NFC')
}
return resolve(actualBaseDir, processedPath).normalize('NFC')
}
/**
* Converts an absolute path to a relative path from cwd, to save tokens in
* tool output. If the path is outside cwd (relative path would start with ..),
* returns the absolute path unchanged so it stays unambiguous.
*
* @param absolutePath - The absolute path to relativize
* @returns Relative path if under cwd, otherwise the original absolute path
*/
export function toRelativePath(absolutePath: string): string {
const relativePath = relative(getCwd(), absolutePath)
// If the relative path would go outside cwd (starts with ..), keep absolute
return relativePath.startsWith('..') ? absolutePath : relativePath
}
/**
* Gets the directory path for a given file or directory path.
* If the path is a directory, returns the path itself.
* If the path is a file or doesn't exist, returns the parent directory.
*
* @param path - The file or directory path
* @returns The directory path
*/
export function getDirectoryForPath(path: string): string {
const absolutePath = expandPath(path)
// SECURITY: Skip filesystem operations for UNC paths to prevent NTLM credential leaks.
if (absolutePath.startsWith('\\\\') || absolutePath.startsWith('//')) {
return dirname(absolutePath)
}
try {
const stats = getFsImplementation().statSync(absolutePath)
if (stats.isDirectory()) {
return absolutePath
}
} catch {
// Path doesn't exist or can't be accessed
}
// If it's not a directory or doesn't exist, return the parent directory
return dirname(absolutePath)
}
/**
* Checks if a path contains directory traversal patterns that navigate to parent directories.
*
* @param path - The path to check for traversal patterns
* @returns true if the path contains traversal (e.g., '../', '..\', or ends with '..')
*/
export function containsPathTraversal(path: string): boolean {
return /(?:^|[\\/])\.\.(?:[\\/]|$)/.test(path)
}
// Re-export from the shared zero-dep source.
export { sanitizePath } from './sessionStoragePortable.js'
/**
* Normalizes a path for use as a JSON config key.
* On Windows, paths can have inconsistent separators (C:\path vs C:/path)
* depending on whether they come from git, Node.js APIs, or user input.
* This normalizes to forward slashes for consistent JSON serialization.
*
* @param path - The path to normalize
* @returns The normalized path with consistent forward slashes
*/
export function normalizePathForConfigKey(path: string): string {
// First use Node's normalize to resolve . and .. segments
const normalized = normalize(path)
// Then convert all backslashes to forward slashes for consistent JSON keys
// This is safe because forward slashes work in Windows paths for most operations
return normalized.replace(/\\/g, '/')
}